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

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

profile_net.rs389 lines · 15.8 KiBRaw
1//! Per-kind GPU time and per-pass wall time for one model, on whatever device runs it.
2//!
3//! ```text
4//! cargo run --release -p modelrunner --example profile_net -- nllb [path/to/nllb600.maml]
5//! adb shell MODELRUNNER_TIMESTAMPS=1 /data/local/tmp/maml/profile_net nllb /data/local/tmp/maml/nllb/nllb600.maml
6//! ```
7//!
8//! Timestamps need `MODELRUNNER_TIMESTAMPS=1`; without it only wall times print. The wall times
9//! are with timestamps off unless it is set, so measure the two in separate runs.
10use std::collections::BTreeMap;
11use std::time::Instant;
12
13use modelrunner::nets::{madlad, madlad_part1, nllb, whisper, Op, Plan};
14use modelrunner::vulkan::context;
15use modelrunner::vulkan::reshape::Reshaped;
16use modelrunner::vulkan::run::{Net, StepParams};
17use modelrunner::weights::{graph, Streamed, Weights};
18
19/// Source tokens. A longish sentence, so cross-attention costs show.
20const SRC_LEN: u32 = 32;
21
22/// Decode steps timed after one warm-up.
23const STEPS: u32 = 24;
24
25fn main() {
26 let args: Vec<String> = std::env::args().skip(1).collect();
27 let model = args.first().map(String::as_str).unwrap_or("nllb");
28 let result = match model {
29 "nllb" => nllb_profile(args.get(1).map(String::as_str)),
30 "whisper" => whisper_profile(args.get(1).map(String::as_str)),
31 "madlad" => madlad_profile(args.get(1).map(String::as_str)),
32 other => Err(format!("unknown model {other:?}; known: nllb, whisper, madlad")),
33 };
34 if let Err(why) = result {
35 println!("failed: {why}");
36 }
37}
38
39fn nllb_profile(path: Option<&str>) -> Result<(), String> {
40 let path = path
41 .map(str::to_owned)
42 .or_else(|| std::env::var("MODELRUNNER_NLLB").ok())
43 .ok_or("pass the nllb600.maml path or set MODELRUNNER_NLLB")?;
44 let bytes = std::fs::read(&path).map_err(|e| format!("cannot read {path}: {e}"))?;
45 let weights = Weights::parse(&bytes, graph::NLLB)?;
46 let context = context::shared()?;
47
48 let started = Instant::now();
49 // Decode-first construction when MODELRUNNER_DECODE_FIRST=1: the cold record (one-time
50 // driver cost, ~130-166 ms for the 280-op decode plan) and the max-size arena allocation
51 // happen in load, and later switches only re-record (~10-15 ms) with no arena growth.
52 // Any other number is the src_len to record the decode plan at, to check the cold cost is per
53 // kernel rather than per shape.
54 let first = match std::env::var("MODELRUNNER_DECODE_FIRST").ok().and_then(|v| v.parse().ok()) {
55 Some(1) => nllb::Mode::DecodeStep { src_len: SRC_LEN },
56 Some(src_len) => nllb::Mode::DecodeStep { src_len },
57 None => nllb::Mode::Encode { len: SRC_LEN },
58 };
59 let mut net = Reshaped::new(
60 context,
61 &weights,
62 first,
63 |offsets, mode| nllb::build(offsets, mode),
64 )?;
65 println!("load {:>8.1} ms (upload + first record)", ms(started));
66
67 // A plausible source
68
69 // A plausible source: the source-language token, then ordinary pieces, then `</s>`.
70 let mut source: Vec<u32> = vec![256_047];
71 source.extend((0..SRC_LEN - 2).map(|i| 1_000 + i * 37));
72 source.push(2);
73 let embedded = nllb::embed_positions(weights.reader(), &source, 0)?;
74
75 let mut encode_ms = Vec::new();
76 let mut switch_ms = Vec::new();
77 let mut step_ms = Vec::new();
78 // Three sentences, so the per-call re-records show up as well as steady-state steps.
79 for _ in 0..3 {
80 let t = Instant::now();
81 net.at(nllb::Mode::Encode { len: SRC_LEN })?.infer_raw(&embedded)?;
82 encode_ms.push(ms(t));
83
84 let mut token = 2u32;
85 for step in 0..=STEPS {
86 let row = nllb::embed_positions(weights.reader(), &[token], step)?;
87 let t = Instant::now();
88 let at = net.at(nllb::Mode::DecodeStep { src_len: SRC_LEN })?;
89 if step == 0 {
90 switch_ms.push(ms(t));
91 }
92 let t = Instant::now();
93 at.set_params(StepParams { prefix: step, window_start: 0 })?;
94 let out = at.infer_raw(&row)?;
95 if step > 0 {
96 step_ms.push(ms(t));
97 }
98 token = greedy(&out).unwrap_or(2).min(nllb::VOCAB - 1);
99 }
100 }
101 println!("encode {} (includes the re-record into Encode after the first)", stats(&encode_ms));
102 println!("switch {} (re-record into DecodeStep)", stats(&switch_ms));
103 println!("step {}", stats(&step_ms));
104
105 let decode = net.at(nllb::Mode::DecodeStep { src_len: SRC_LEN })?;
106 print_kinds("decode step", decode);
107 let encode = net.at(nllb::Mode::Encode { len: SRC_LEN })?;
108 encode.infer_raw(&embedded)?;
109 print_kinds("encode", encode);
110 Ok(())
111}
112
113/// Whisper over a synthetic window: the real prompt, then a fixed number of greedy steps.
114///
115/// Prints the ids and a logits checksum so two builds can be compared for identical output, which
116/// is the regression check here - there is no recorded reference transcript to match.
117fn whisper_profile(path: Option<&str>) -> Result<(), String> {
118 const STEPS: u32 = 32;
119 // `<|startoftranscript|> <|en|> <|transcribe|> <|notimestamps|>`.
120 const PROMPT: [u32; 4] = [50_258, 50_259, 50_359, 50_363];
121 let path = path
122 .map(str::to_owned)
123 .or_else(|| std::env::var("MODELRUNNER_WHISPER").ok())
124 .ok_or("pass the whisper_base.maml path or set MODELRUNNER_WHISPER")?;
125 let bytes = std::fs::read(&path).map_err(|e| format!("cannot read {path}: {e}"))?;
126 let weights = Weights::parse(&bytes, graph::WHISPER)?;
127 let context = context::shared()?;
128
129 let started = Instant::now();
130 // MODELRUNNER_DECODE_FIRST=1 mirrors the app's create: decode step recorded, then the encoder.
131 let decode_first = std::env::var("MODELRUNNER_DECODE_FIRST").is_ok();
132 let first = if decode_first { whisper::Mode::DecodeStep } else { whisper::Mode::Encode };
133 let mut net =
134 Reshaped::new(context, &weights, first, |offsets, mode| whisper::build(offsets, mode))?;
135 net.at(whisper::Mode::Encode)?;
136 println!("load {:>8.1} ms (upload + first record)", ms(started));
137
138 // A deterministic log-mel-like window: smooth in time, varied across bins.
139 let mel: Vec<f32> = (0..whisper::MELS * whisper::MEL_FRAMES)
140 .map(|i| {
141 let (bin, frame) = (i / whisper::MEL_FRAMES, i % whisper::MEL_FRAMES);
142 ((frame as f32 * 0.013 + bin as f32 * 0.37).sin() * 0.6 - 0.2).clamp(-1.0, 1.0)
143 })
144 .collect();
145
146 let mut encode_ms = Vec::new();
147 let mut step_ms = Vec::new();
148 let mut switch_ms = Vec::new();
149 let mut ids = Vec::new();
150 let mut checksum = 0.0f64;
151 for round in 0..2 {
152 let t = Instant::now();
153 let encoder = net.at(whisper::Mode::Encode)?;
154 let encoded = encoder.infer_raw_many(&[&mel])?;
155 encode_ms.push(ms(t));
156 // HEAD's encoder hands its twelve cross caches back; the decode step there takes them in.
157 let cross: Vec<Vec<f32>> = encoded.into_iter().skip(1).collect();
158
159 let mut token = PROMPT[0];
160 for step in 0..PROMPT.len() as u32 + STEPS {
161 let row = whisper::embed_positions(weights.reader(), &[token], step)?;
162 let t = Instant::now();
163 let at = net.at(whisper::Mode::DecodeStep)?;
164 if step == 0 {
165 switch_ms.push(ms(t));
166 }
167 at.set_params(StepParams { prefix: step, window_start: 0 })?;
168 let mut inputs: Vec<&[f32]> = vec![&row];
169 inputs.extend(cross.iter().map(Vec::as_slice));
170 let t = Instant::now();
171 let out = at.infer_raw_many(&inputs)?;
172 step_ms.push(ms(t));
173 let logits = out.first().ok_or("no logits")?;
174 token = if let Some(&next) = PROMPT.get(step as usize + 1) {
175 next
176 } else {
177 let next = greedy(&out).unwrap_or(50_257);
178 if round == 0 {
179 ids.push(next);
180 checksum += logits.iter().map(|&v| f64::from(v)).sum::<f64>();
181 }
182 next
183 };
184 }
185 }
186 println!("encode {}", stats(&encode_ms));
187 println!("switch {} (into DecodeStep)", stats(&switch_ms));
188 println!("step {}", stats(&step_ms));
189 println!("ids {ids:?}");
190 println!("checksum {checksum:.3}");
191
192 let decode = net.at(whisper::Mode::DecodeStep)?;
193 print_kinds("decode step", decode);
194 let encode = net.at(whisper::Mode::Encode)?;
195 encode.infer_raw_many(&[&mel])?;
196 print_kinds("encode", encode);
197 Ok(())
198}
199
200/// Whether a MADLAD decode step takes the encoder output as an input. True at HEAD; false once the
201/// encode pass leaves the cross-attention K and V on the device.
202const MADLAD_STEP_TAKES_ENCODED: bool = false;
203
204/// MADLAD over a fixed 32-token source: three sentences of 24 greedy steps, ids and checksum
205/// printed so two builds can be compared. Streamed, because the file is a gigabyte.
206fn madlad_profile(path: Option<&str>) -> Result<(), String> {
207 const SRC_LEN: u32 = 32;
208 const STEPS: u32 = 24;
209 let path = path
210 .map(str::to_owned)
211 .or_else(|| std::env::var("MODELRUNNER_MADLAD").ok())
212 .ok_or("pass the madlad400.maml path or set MODELRUNNER_MADLAD")?;
213 let file = std::fs::File::open(&path).map_err(|e| format!("cannot open {path}: {e}"))?;
214 let len = file.metadata().map_err(|e| format!("cannot size {path}: {e}"))?.len();
215 let weights = Streamed::open(file, 0, len, graph::MADLAD)?;
216 let context = context::shared()?;
217
218 let started = Instant::now();
219 let mut net = Reshaped::streamed(
220 context,
221 weights.offsets(),
222 &weights,
223 madlad::Mode::Encode { len: SRC_LEN },
224 |offsets, mode| madlad::build(offsets, mode),
225 )?;
226 println!("load {:>8.1} ms (upload + first record)", ms(started));
227
228 // A target tag then ordinary pieces then `</s>`, ids well inside the vocabulary.
229 let mut source: Vec<u32> = vec![256_000 - 1_000];
230 source.extend((0..SRC_LEN - 2).map(|i| 500 + i * 41));
231 source.push(1);
232 let embedded = madlad_part1::embed_positions(weights.reader(), &source, 0)?;
233 let queries: Vec<u32> = (0..SRC_LEN).collect();
234 let enc_bias =
235 madlad_part1::relative_bias(weights.reader(), madlad::TABLE_ENC, &queries, &queries, true)?;
236
237 let mut encode_ms = Vec::new();
238 let mut step_ms = Vec::new();
239 let mut ids = Vec::new();
240 for round in 0..3 {
241 let t = Instant::now();
242 let out = net.at(madlad::Mode::Encode { len: SRC_LEN })?.infer_raw_many(&[&embedded, &enc_bias])?;
243 encode_ms.push(ms(t));
244 let encoded = out.into_iter().next().ok_or("the encoder returned nothing")?;
245 if round == 0 {
246 let sum: f64 = encoded.iter().map(|&v| f64::from(v)).sum();
247 println!("encoded checksum {sum:.6}");
248 }
249
250 let mut token = 0u32;
251 for step in 0..STEPS {
252 let row = madlad_part1::embed_positions(weights.reader(), &[token], step)?;
253 let keys: Vec<u32> = (0..=step).collect();
254 let live = madlad_part1::relative_bias(weights.reader(), madlad::TABLE_DEC, &[step], &keys, false)?;
255 let width = madlad::MAX_DECODE_POSITIONS as usize;
256 let mut bias = vec![0.0f32; madlad::HEADS as usize * width];
257 for head in 0..madlad::HEADS as usize {
258 bias[head * width..head * width + keys.len()]
259 .copy_from_slice(&live[head * keys.len()..(head + 1) * keys.len()]);
260 }
261 let at = net.at(madlad::Mode::DecodeStep { src_len: SRC_LEN })?;
262 at.set_params(StepParams { prefix: step, window_start: 0 })?;
263 let mut inputs: Vec<&[f32]> = vec![&row];
264 if MADLAD_STEP_TAKES_ENCODED {
265 inputs.push(&encoded);
266 }
267 inputs.push(&bias);
268 let t = Instant::now();
269 let out = at.infer_raw_many(&inputs)?;
270 if step > 0 {
271 step_ms.push(ms(t));
272 }
273 token = greedy(&out).unwrap_or(1).min(madlad::VOCAB - 1);
274 if round == 0 {
275 ids.push(token);
276 }
277 }
278 }
279 println!("encode {}", stats(&encode_ms));
280 println!("step {}", stats(&step_ms));
281 println!("ids {ids:?}");
282
283 let (planner, offsets) = net.planner();
284 let decode = net.at(madlad::Mode::DecodeStep { src_len: SRC_LEN })?;
285 print_kinds("decode step", decode);
286 print_shapes("decode step", decode, &planner(&offsets, madlad::Mode::DecodeStep { src_len: SRC_LEN })?);
287 let encode = net.at(madlad::Mode::Encode { len: SRC_LEN })?;
288 encode.infer_raw_many(&[&embedded, &enc_bias])?;
289 print_kinds("encode", encode);
290 print_shapes("encode", encode, &planner(&offsets, madlad::Mode::Encode { len: SRC_LEN })?);
291 Ok(())
292}
293
294/// The token from a greedy plan's `[lo, hi]` output, or the argmax of a logits plan's splits.
295fn greedy(out: &[Vec<f32>]) -> Option<u32> {
296 if let [pair] = out {
297 if let [lo, hi] = pair[..] {
298 return Some(hi as u32 * 2048 + lo as u32);
299 }
300 }
301 let mut best: Option<(u32, f32)> = None;
302 let mut index = 0u32;
303 for split in out {
304 for &value in split {
305 if best.is_none_or(|(_, top)| value > top) {
306 best = Some((index, value));
307 }
308 index += 1;
309 }
310 }
311 best.map(|(id, _)| id)
312}
313
314fn print_kinds(label: &str, net: &Net) {
315 let times = match net.op_times() {
316 Ok(times) => times,
317 Err(why) => {
318 println!("{label}: {why}");
319 return;
320 }
321 };
322 let mut kinds: BTreeMap<String, (usize, f64)> = BTreeMap::new();
323 let (mut total, mut gaps) = (0.0, 0.0);
324 for (name, us, gap) in &times {
325 let kind = name.split(": ").nth(1).unwrap_or(name).to_string();
326 let entry = kinds.entry(kind).or_default();
327 entry.0 += 1;
328 entry.1 += us;
329 total += us;
330 gaps += gap;
331 }
332 let mut rows: Vec<_> = kinds.into_iter().collect();
333 rows.sort_by(|a, b| b.1 .1.total_cmp(&a.1 .1));
334 println!();
335 println!("{label}: {} dispatches, {:.2} ms in shaders, {:.2} ms in gaps", times.len(), total / 1e3, gaps / 1e3);
336 println!(" {:<22} {:>6} {:>10} {:>10}", "kind", "count", "total ms", "mean us");
337 for (kind, (count, us)) in rows {
338 println!(" {kind:<22} {count:>6} {:>10.3} {:>10.1}", us / 1e3, us / count as f64);
339 }
340}
341
342/// GPU time per (kind, in_c, out_c, positions) when `MODELRUNNER_SHAPES` is set.
343fn print_shapes(label: &str, net: &Net, plan: &Plan) {
344 if std::env::var("MODELRUNNER_SHAPES").is_err() {
345 return;
346 }
347 let Ok(times) = net.op_times() else { return };
348 let pushes: Vec<_> = plan
349 .ops
350 .iter()
351 .filter_map(|op| match op {
352 Op::Dispatch { kind, push, .. } => Some((*kind, *push)),
353 _ => None,
354 })
355 .collect();
356 let mut shapes: BTreeMap<String, (usize, f64)> = BTreeMap::new();
357 for ((_, us, _), (kind, push)) in times.iter().zip(&pushes) {
358 let key = format!("{kind:?} {}->{} x{} in1={}", push.in_c, push.out_c, push.out_h * push.out_w, push.in1);
359 let entry = shapes.entry(key).or_default();
360 entry.0 += 1;
361 entry.1 += us;
362 }
363 let mut rows: Vec<_> = shapes.into_iter().collect();
364 rows.sort_by(|a, b| b.1 .1.total_cmp(&a.1 .1));
365 println!("{label} by shape:");
366 for (key, (count, us)) in rows.into_iter().take(16) {
367 println!(" {key:<44} {count:>5} {:>10.3} ms {:>9.1} us", us / 1e3, us / count as f64);
368 }
369}
370
371fn ms(since: Instant) -> f64 {
372 since.elapsed().as_secs_f64() * 1e3
373}
374
375fn stats(values: &[f64]) -> String {
376 if values.is_empty() {
377 return "n/a".into();
378 }
379 let mut sorted = values.to_vec();
380 sorted.sort_by(f64::total_cmp);
381 let mean = sorted.iter().sum::<f64>() / sorted.len() as f64;
382 format!(
383 "mean {mean:>8.2} ms median {:>8.2} min {:>8.2} max {:>8.2} (n={})",
384 sorted[sorted.len() / 2],
385 sorted[0],
386 sorted[sorted.len() - 1],
387 sorted.len()
388 )
389}