Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
cov/c3 ▾

Modern-Apps.git / library / ml / src / main / rust / examples / report_decode_cost.rs

report_decode_cost.rs178 lines · 6.6 KiBRaw
1//! What one NLLB decode token costs before it reaches the GPU.
2//!
3//! ```text
4//! cargo run --offline --release -p modelrunner --example report_decode_cost
5//! ```
6//!
7//! # What this measures
8//!
9//! The real per-token cost of the decode loop: `set_params` plus a submit, with the plan recorded
10//! once. Before the record-once change this was a full `nllb::build` and a `Net::rebuild` - a
11//! `device_wait_idle` under the process-wide queue lock and a re-emit of every dispatch - on top
12//! of the submit, plus an upload of the whole KV cache from the host that grew by a position
13//! every token.
14//!
15//! Build with `--release`. A debug build measures `rustc -O0`, not the runtime.
16use std::path::PathBuf;
17use std::time::Instant;
18
19use modelrunner::nets::nllb;
20use modelrunner::preprocess::RESCALE_ONLY;
21use modelrunner::vulkan::context;
22use modelrunner::vulkan::run::{Net, StepParams};
23use modelrunner::weights::{graph, Weights};
24
25/// Source tokens the cross-attention attends over. A short sentence.
26const SRC_LEN: u32 = 32;
27
28/// Decode steps to time. Enough to show whether cost grows with the cache.
29const STEPS: u32 = 24;
30
31fn main() {
32 let Some(path) = weights_path() else {
33 println!("no nllb600.maml found.");
34 println!("Set MODELRUNNER_NLLB, or run scripts/ml/fetch_nllb600.py to populate");
35 println!("build/nllb600/nllb600.maml.");
36 return;
37 };
38 println!("weights {}", path.display());
39
40 let bytes = match std::fs::read(&path) {
41 Ok(bytes) => bytes,
42 Err(why) => {
43 println!("cannot read it: {why}");
44 return;
45 }
46 };
47 let weights = match Weights::parse(&bytes, graph::NLLB) {
48 Ok(weights) => weights,
49 Err(why) => {
50 println!("cannot parse it: {why}");
51 return;
52 }
53 };
54 println!(" {:.1} MB of data section", weights.data().len() as f64 / 1e6);
55
56 let context = match context::shared() {
57 Ok(context) => context,
58 Err(why) => {
59 println!("no usable Vulkan device: {why}");
60 return;
61 }
62 };
63 println!();
64
65 // The encoder runs once per sentence, so its build cost is amortised. Reported for scale.
66 let start = Instant::now();
67 let encode = match nllb::build(&weights, nllb::Mode::Encode { len: SRC_LEN }) {
68 Ok(plan) => plan,
69 Err(why) => {
70 println!("the encoder does not build: {why}");
71 return;
72 }
73 };
74 let encode_build = start.elapsed();
75 println!(
76 "encoder {:>7.2} ms to build a {}-op plan, once per sentence",
77 encode_build.as_secs_f64() * 1e3,
78 encode.ops.len(),
79 );
80
81 // The first decode plan, which the Net is created from. Creation is not per-token cost, so it
82 // is timed separately.
83 let start = Instant::now();
84 let first = match nllb::build(&weights, nllb::Mode::DecodeStep { src_len: SRC_LEN }) {
85 Ok(plan) => plan,
86 Err(why) => {
87 println!("a decode step does not build: {why}");
88 return;
89 }
90 };
91 let plan_build = start.elapsed();
92 let ops = first.ops.len();
93 let arena_mb = f64::from(first.arena_elems) * 2.0 / 1e6;
94 let start = Instant::now();
95 let mut net = match Net::new(context, first, &weights, RESCALE_ONLY) {
96 Ok(net) => net,
97 Err(why) => {
98 println!("the decode plan does not record: {why}");
99 return;
100 }
101 };
102 println!(
103 "decoder {:>7.2} ms to build a {ops}-op plan, {:>7.2} ms to record it, both once",
104 plan_build.as_secs_f64() * 1e3,
105 start.elapsed().as_secs_f64() * 1e3,
106 );
107 println!(" {arena_mb:.1} MB of arena, including the KV cache it now holds");
108 println!();
109
110 // A token. The value does not matter to the timing, only the shape. The cross-attention K and
111 // V the encoder pass would leave in the arena are whatever it holds, which is also fine here.
112 let embedded = match nllb::embed_positions(weights.reader(), &[2], 0) {
113 Ok(values) => values,
114 Err(why) => {
115 println!("cannot embed: {why}");
116 return;
117 }
118 };
119
120 // One discarded step: the first submit pays for pipeline warm-up and for faulting the weights
121 // into device memory, neither of which a steady-state token pays.
122 if let Err(why) = net
123 .set_params(StepParams { prefix: 0, window_start: 0 })
124 .and_then(|()| net.infer_raw(&embedded).map(|_| ()))
125 {
126 println!("the warm-up step failed: {why}");
127 return;
128 }
129
130 println!("per token, with the plan recorded once");
131 println!(" step total ms");
132 let mut total = 0.0f64;
133 for step in 1..=STEPS {
134 let start = Instant::now();
135 if let Err(why) = net.set_params(StepParams { prefix: step, window_start: 0 }) {
136 println!("step {step} could not set params: {why}");
137 return;
138 }
139 if let Err(why) = net.infer_raw(&embedded) {
140 println!("step {step} did not submit: {why}");
141 return;
142 }
143 let each = start.elapsed().as_secs_f64() * 1e3;
144 total += each;
145 // Sparse output: the first few, then every eighth, so growth is visible without noise.
146 if step <= 3 || step % 8 == 0 {
147 println!(" {step:>4} {each:>8.2}");
148 }
149 }
150
151 let each = total / f64::from(STEPS);
152 println!();
153 println!("mean {each:>8.2} ms per token, {:.1} tokens/s", 1e3 / each);
154 println!();
155 println!("This is the whole step: params, submit, compute and readback. The rebuild it");
156 println!("replaced measured 1.64 ms per token on this device, so on NLLB the saving is a");
157 println!("modest fraction of a step that is dominated by its own arithmetic.");
158 println!();
159 println!("The shape of the number matters more than its size. It is flat: the old loop also");
160 println!("re-uploaded the entire KV cache every token, which grew by a position each time, so");
161 println!("its cost rose with sentence length where this does not. And the rebuild it removes");
162 println!("scales with op count - 317 here, thousands for an LLM - which is the case the");
163 println!("record-once design was actually for.");
164}
165
166/// `MODELRUNNER_NLLB` if set, else `build/nllb600/nllb600.maml` from the repo root.
167fn weights_path() -> Option<PathBuf> {
168 if let Ok(path) = std::env::var("MODELRUNNER_NLLB") {
169 let path = PathBuf::from(path);
170 return path.is_file().then_some(path);
171 }
172 let mut dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
173 while !dir.join("settings.gradle.kts").is_file() {
174 dir = dir.parent()?.to_path_buf();
175 }
176 let path = dir.join("build/nllb600/nllb600.maml");
177 path.is_file().then_some(path)
178}