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

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

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