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

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

profile_vision.rs439 lines · 17.7 KiBRaw
1//! Per-model wall time, per-kind GPU time and output checksums for the vision nets.
2//!
3//! ```text
4//! cargo run --release -p modelrunner --example profile_vision -- all path/to/assets
5//! adb shell MODELRUNNER_TIMESTAMPS=1 /data/local/tmp/maml/vision/profile_vision all /data/local/tmp/maml/vision
6//! ```
7//!
8//! `which` is one of `all`, `selfie`, `modnet`, `u2netp`, `scrfd`, `mbf`, `det`, `rec`,
9//! `clip_image`, `clip_text`, `maia`. `dir` holds the `.maml` files under their asset
10//! names (`selfie_segmentation.maml`, `modnet.maml`, `u2netp.maml`, `scrfd_500m.maml`,
11//! `w600k_mbf.maml`, `ppocr_det.maml`, `ppocr_rec.maml`, `clip/tinyclip.maml`,
12//! `maia3-5m.maml`); it defaults to `MODELRUNNER_VISION` or the current directory.
13//!
14//! Timestamps need `MODELRUNNER_TIMESTAMPS=1`; without it only wall times and checksums
15//! print. Measure the two in separate runs. The checksum is the whole-output f64 sum,
16//! printed so two builds can be compared for identical output.
17use std::collections::BTreeMap;
18use std::time::Instant;
19
20use modelrunner::nets::{
21 maia, mobilefacenet, modnet, ppocr_det, ppocr_rec, scrfd, selfie, tinyclip, u2netp, Plan,
22};
23use modelrunner::post::ocr::REC_WIDTH;
24use modelrunner::preprocess::{f16_to_f32, to_planar_f16, PPOCR_REC, RESCALE_ONLY};
25use modelrunner::vulkan::context;
26use modelrunner::vulkan::reshape::Reshaped;
27use modelrunner::vulkan::run::Net;
28use modelrunner::weights::{graph, Offsets, Weights};
29
30fn main() {
31 let args: Vec<String> = std::env::args().skip(1).collect();
32 let which = args.first().map(String::as_str).unwrap_or("all");
33 let dir = args
34 .get(1)
35 .map(String::as_str)
36 .map(str::to_owned)
37 .or_else(|| std::env::var("MODELRUNNER_VISION").ok())
38 .unwrap_or_else(|| ".".into());
39 let models: &[(&str, &str, u32)] = &[
40 ("selfie", "selfie_segmentation.maml", 5),
41 ("modnet", "modnet.maml", 3),
42 ("u2netp", "u2netp.maml", 2),
43 ("scrfd", "scrfd_500m.maml", 3),
44 ("mbf", "w600k_mbf.maml", 5),
45 ("det", "ppocr_det.maml", 2),
46 ("rec", "ppocr_rec.maml", 5),
47 ("rec_batch", "ppocr_rec.maml", 5),
48 ("clip_image", "clip/tinyclip.maml", 3),
49 ("clip_text", "clip/tinyclip.maml", 5),
50 ("maia", "maia3-5m.maml", 3),
51 ];
52 let mut failed = false;
53 for (name, file, passes) in models {
54 if which != "all" && which != *name {
55 continue;
56 }
57 let path = format!("{dir}/{file}");
58 println!("=== {name} ({path}) ===");
59 let result = match *name {
60 "selfie" => profile_selfie(&path, *passes),
61 "modnet" => profile_modnet(&path, *passes),
62 "u2netp" => profile_u2netp(&path, *passes),
63 "scrfd" => profile_scrfd(&path, *passes),
64 "mbf" => profile_mbf(&path, *passes),
65 "det" => profile_det(&path, *passes),
66 "rec" => profile_rec(&path, *passes),
67 "rec_batch" => profile_rec_batch(&path, *passes),
68 "clip_image" => profile_clip_image(&path, *passes),
69 "clip_text" => profile_clip_text(&path, *passes),
70 "maia" => profile_maia(&path, *passes),
71 other => Err(format!("unknown model {other:?}")),
72 };
73 if let Err(why) = result {
74 println!("failed: {why}");
75 failed = true;
76 }
77 println!();
78 }
79 if failed {
80 std::process::exit(1);
81 }
82}
83
84/// Deterministic photo-range input: the same ramp `scripts/ml/onnx_parity.py` feeds.
85///
86/// A full-range sawtooth in [-0.5, 0.5), exercising every activation's range rather
87/// than saturating the segmenters' sigmoids to one end. Free of transcendentals so
88/// both sides of a parity comparison read the same bytes.
89fn pattern(len: usize) -> Vec<f32> {
90 (0..len).map(|i| (i as u64 * 37 % 255) as f32 / 255.0 - 0.5).collect()
91}
92
93/// A bright centred blob on a dark field — structurally nothing like [`pattern`].
94///
95/// Matches `nets::reference`'s `blob` so the response check compares the same pair.
96/// Layout is channel-major `[c, h, w]`, the order every plan input uses.
97fn blob(channels: usize, height: usize, width: usize) -> Vec<f32> {
98 let mut values = Vec::with_capacity(channels * height * width);
99 let (cy, cx) = (height as f32 / 2.0, width as f32 / 2.0);
100 let radius = height.min(width) as f32 / 3.0;
101 for c in 0..channels {
102 for y in 0..height {
103 for x in 0..width {
104 let (dy, dx) = (y as f32 - cy, x as f32 - cx);
105 let inside = (dy * dy + dx * dx).sqrt() < radius;
106 values.push(if inside { 0.9 - c as f32 * 0.2 } else { 0.05 });
107 }
108 }
109 }
110 values
111}
112
113fn load(path: &str, graph_id: u32) -> Result<Weights, String> {
114 let bytes = std::fs::read(path).map_err(|e| format!("cannot read {path}: {e}"))?;
115 Weights::parse(&bytes, graph_id)
116}
117
118/// Time `passes` inferences after one warm-up, then print the kinds table and checksums.
119///
120/// Runs `input_b` once after the timed passes and reports the peak per-element
121/// response between the two inputs. Segmentation masks are near-zero on synthetic
122/// input even when correct — see `nets::reference::assert_usable_mask` — so the
123/// response, not the checksum, is what distinguishes a net that answers from one
124/// that cannot.
125fn report(
126 label: &str,
127 net: &mut Net,
128 input: &[f32],
129 input_b: &[f32],
130 passes: u32,
131) -> Result<(), String> {
132 let mut ms = Vec::new();
133 let mut last: Vec<Vec<f32>> = Vec::new();
134 net.infer_raw(input)?;
135 for _ in 0..passes {
136 let t = Instant::now();
137 last = net.infer_raw(input)?;
138 ms.push(since(t));
139 }
140 println!("infer {}", stats(&ms));
141 print_checksums(&last);
142 let other = net.infer_raw(input_b)?;
143 for (a, b) in last.iter().zip(other.iter()) {
144 let response = a.iter().zip(b.iter()).map(|(x, y)| (x - y).abs()).fold(0.0f32, f32::max);
145 println!("response peak {response:.6}");
146 }
147 net.infer_raw(input)?;
148 print_kinds(label, net);
149 Ok(())
150}
151
152fn report_many(label: &str, net: &mut Net, inputs: &[&[f32]], passes: u32) -> Result<(), String> {
153 let mut ms = Vec::new();
154 net.infer_raw_many(inputs)?;
155 for _ in 0..passes {
156 let t = Instant::now();
157 let out = net.infer_raw_many(inputs)?;
158 ms.push(since(t));
159 if ms.len() == passes as usize {
160 print_checksums(&out);
161 }
162 }
163 println!("infer {}", stats(&ms));
164 net.infer_raw_many(inputs)?;
165 print_kinds(label, net);
166 Ok(())
167}
168
169fn print_checksums(out: &[Vec<f32>]) {
170 for (i, binding) in out.iter().enumerate() {
171 let sum: f64 = binding.iter().map(|&v| f64::from(v)).sum();
172 let max: f32 = binding.iter().fold(0.0f32, |a, &v| a.max(v.abs()));
173 println!("output[{i}] len {:>8} checksum {sum:.6} maxabs {max:.6}", binding.len());
174 }
175}
176
177fn profile_selfie(path: &str, passes: u32) -> Result<(), String> {
178 let weights = load(path, graph::SELFIE)?;
179 let context = context::shared()?;
180 let started = Instant::now();
181 let plan = selfie::build(&weights)?;
182 let mut net = Net::new(context, plan, &weights, RESCALE_ONLY)?;
183 println!("load {:>8.1} ms (upload + first record)", since(started));
184 let input = pattern(3 * selfie::SIZE as usize * selfie::SIZE as usize);
185 let input_b = blob(3, selfie::SIZE as usize, selfie::SIZE as usize);
186 report("selfie", &mut net, &input, &input_b, passes)
187}
188
189fn profile_modnet(path: &str, passes: u32) -> Result<(), String> {
190 let weights = load(path, graph::MODNET)?;
191 let context = context::shared()?;
192 let started = Instant::now();
193 let plan = modnet::build(&weights)?;
194 let mut net = Net::new(context, plan, &weights, RESCALE_ONLY)?;
195 println!("load {:>8.1} ms (upload + first record)", since(started));
196 let input = pattern(3 * modnet::SIZE as usize * modnet::SIZE as usize);
197 let input_b = blob(3, modnet::SIZE as usize, modnet::SIZE as usize);
198 report("modnet", &mut net, &input, &input_b, passes)
199}
200
201fn profile_u2netp(path: &str, passes: u32) -> Result<(), String> {
202 let weights = load(path, graph::U2NETP)?;
203 let context = context::shared()?;
204 let started = Instant::now();
205 let plan = u2netp::build(&weights)?;
206 let mut net = Net::new(context, plan, &weights, RESCALE_ONLY)?;
207 println!("load {:>8.1} ms (upload + first record)", since(started));
208 let input = pattern(3 * u2netp::SIZE as usize * u2netp::SIZE as usize);
209 let input_b = blob(3, u2netp::SIZE as usize, u2netp::SIZE as usize);
210 report("u2netp", &mut net, &input, &input_b, passes)
211}
212
213fn profile_scrfd(path: &str, passes: u32) -> Result<(), String> {
214 let weights = load(path, graph::SCRFD)?;
215 let context = context::shared()?;
216 let started = Instant::now();
217 // The bridge builds at the fixed LONG_SIDE square; profile that.
218 let plan = scrfd::build(&weights, scrfd::LONG_SIDE, scrfd::LONG_SIDE)?;
219 let mut net = Net::new(context, plan, &weights, RESCALE_ONLY)?;
220 println!("load {:>8.1} ms (upload + first record)", since(started));
221 let side = scrfd::LONG_SIDE as usize;
222 let input = pattern(3 * side * side);
223 let input_b = blob(3, side, side);
224 report("scrfd", &mut net, &input, &input_b, passes)
225}
226
227fn profile_mbf(path: &str, passes: u32) -> Result<(), String> {
228 let weights = load(path, graph::MOBILEFACENET)?;
229 let context = context::shared()?;
230 let started = Instant::now();
231 let plan = mobilefacenet::build(&weights)?;
232 let mut net = Net::new(context, plan, &weights, RESCALE_ONLY)?;
233 println!("load {:>8.1} ms (upload + first record)", since(started));
234 let input = pattern(3 * mobilefacenet::SIZE as usize * mobilefacenet::SIZE as usize);
235 let input_b = blob(3, mobilefacenet::SIZE as usize, mobilefacenet::SIZE as usize);
236 report("mbf", &mut net, &input, &input_b, passes)
237}
238
239fn profile_det(path: &str, passes: u32) -> Result<(), String> {
240 let weights = load(path, graph::PPOCR_DET)?;
241 let context = context::shared()?;
242 let started = Instant::now();
243 // The bridge builds at the fixed LONG_SIDE square; profile that.
244 let plan = ppocr_det::build(&weights, ppocr_det::LONG_SIDE, ppocr_det::LONG_SIDE)?;
245 let mut net = Net::new(context, plan, &weights, RESCALE_ONLY)?;
246 println!("load {:>8.1} ms (upload + first record)", since(started));
247 let side = ppocr_det::LONG_SIDE as usize;
248 let input = pattern(3 * side * side);
249 let input_b = blob(3, side, side);
250 report("det", &mut net, &input, &input_b, passes)
251}
252
253fn profile_rec(path: &str, passes: u32) -> Result<(), String> {
254 let weights = load(path, graph::PPOCR_REC)?;
255 let context = context::shared()?;
256 let started = Instant::now();
257 // The bridge builds at the fixed REC_WIDTH; profile that.
258 let plan = ppocr_rec::build(&weights, REC_WIDTH)?;
259 let mut net = Net::new(context, plan, &weights, PPOCR_REC)?;
260 println!("load {:>8.1} ms (upload + first record)", since(started));
261 let input = pattern(3 * ppocr_rec::HEIGHT as usize * REC_WIDTH as usize);
262 let input_b = blob(3, ppocr_rec::HEIGHT as usize, REC_WIDTH as usize);
263 report("rec", &mut net, &input, &input_b, passes)
264}
265
266/// Eight lines one submit each against one batched submit; the logits must match bit for bit.
267fn profile_rec_batch(path: &str, passes: u32) -> Result<(), String> {
268 const LINES: u32 = 8;
269 let weights = load(path, graph::PPOCR_REC)?;
270 let context = context::shared()?;
271 let t = Instant::now();
272 let mut single =
273 Net::new(context.clone(), ppocr_rec::build(&weights, REC_WIDTH)?, &weights, PPOCR_REC)?;
274 println!("load single {:.1} ms", since(t));
275 for lines in [2u32, 4] {
276 let t = Instant::now();
277 let _net = Net::new(
278 context.clone(),
279 ppocr_rec::build_batch(&weights, REC_WIDTH, lines)?,
280 &weights,
281 PPOCR_REC,
282 )?;
283 println!("load batch of {lines} {:.1} ms", since(t));
284 }
285 let t = Instant::now();
286 let mut batch = Net::new(
287 context,
288 ppocr_rec::build_batch(&weights, REC_WIDTH, LINES)?,
289 &weights,
290 PPOCR_REC,
291 )?;
292 println!("load batch of {LINES} {:.1} ms", since(t));
293 let len = ppocr_rec::HEIGHT as usize * REC_WIDTH as usize;
294 let strips: Vec<Vec<i32>> = (0..LINES as usize)
295 .map(|i| {
296 (0..len)
297 .map(|p| {
298 (0xff00_0000u32 | (((p * 37 + i * 101) as u32 * 2_654_435_761) >> 8)) as i32
299 })
300 .collect()
301 })
302 .collect();
303 let shape = modelrunner::nets::Shape::new(3, ppocr_rec::HEIGHT, REC_WIDTH);
304 let mut half = vec![0u16; shape.len() as usize];
305 let mut inputs = Vec::new();
306 for strip in &strips {
307 to_planar_f16(strip, REC_WIDTH, ppocr_rec::HEIGHT, shape, &PPOCR_REC, &mut half)?;
308 inputs.push(half.iter().map(|&h| f16_to_f32(h)).collect::<Vec<f32>>());
309 }
310 let refs: Vec<&[f32]> = inputs.iter().map(Vec::as_slice).collect();
311 let (mut one, mut many) = (Vec::new(), Vec::new());
312 let mut expected = Vec::new();
313 for _ in 0..=passes {
314 let t = Instant::now();
315 expected = strips
316 .iter()
317 .map(|s| single.infer(s, REC_WIDTH, ppocr_rec::HEIGHT))
318 .collect::<Result<Vec<_>, _>>()?;
319 one.push(since(t));
320 let t = Instant::now();
321 let got = batch.infer_raw_many(&refs)?;
322 many.push(since(t));
323 if expected != got {
324 return Err("a batched line's logits differ from its single run".into());
325 }
326 }
327 println!("single {} for {LINES} lines", stats(&one[1..]));
328 println!("batched {} for {LINES} lines (identical logits)", stats(&many[1..]));
329 print_checksums(&expected);
330 Ok(())
331}
332
333fn tinyclip_plan(offsets: &Offsets, mode: tinyclip::Mode) -> Result<Plan, String> {
334 tinyclip::build(offsets, mode)
335}
336
337fn profile_clip_image(path: &str, passes: u32) -> Result<(), String> {
338 let weights = load(path, graph::TINYCLIP)?;
339 let context = context::shared()?;
340 let started = Instant::now();
341 let mut nets = Reshaped::new(context, &weights, tinyclip::Mode::Image, tinyclip_plan)?;
342 println!("load {:>8.1} ms (upload + first record)", since(started));
343 let side = tinyclip::IMAGE_SIZE as usize;
344 let input = pattern(3 * side * side);
345 let input_b = blob(3, side, side);
346 let net = nets.at(tinyclip::Mode::Image)?;
347 report("clip_image", net, &input, &input_b, passes)
348}
349
350fn profile_clip_text(path: &str, passes: u32) -> Result<(), String> {
351 let weights = load(path, graph::TINYCLIP)?;
352 let context = context::shared()?;
353 let started = Instant::now();
354 // `<|startoftext|>`, three pieces, `<|endoftext|>`: a typical short query.
355 let ids: Vec<u32> = vec![49406, 1234, 5678, 9012, 49407];
356 let embedded = tinyclip::embed_positions(weights.reader(), &ids)?;
357 let len = ids.len() as u32;
358 let mut nets = Reshaped::new(context, &weights, tinyclip::Mode::Text { len }, tinyclip_plan)?;
359 println!("load {:>8.1} ms (upload + first record)", since(started));
360 let net = nets.at(tinyclip::Mode::Text { len })?;
361 report_many("clip_text", net, &[&embedded], passes)
362}
363
364fn profile_maia(path: &str, passes: u32) -> Result<(), String> {
365 let weights = load(path, graph::MAIA)?;
366 let context = context::shared()?;
367 let started = Instant::now();
368 let plan = maia::build(&weights)?;
369 let mut net = Net::new(context, plan, &weights, RESCALE_ONLY)?;
370 println!("load {:>8.1} ms (upload + first record)", since(started));
371 // A sparse opening-like board: a few pieces on their squares, both sides at 1500.
372 let mut planes = vec![0.0f32; maia::PLANES as usize * maia::SQUARES as usize];
373 for (plane, square) in [(5, 12), (5, 52), (4, 1), (4, 57), (11, 4), (11, 60)] {
374 planes[plane * maia::SQUARES as usize + square] = 1.0;
375 }
376 let elo = maia::elo_embedding(weights.reader(), 1500.0)?;
377 let tokens = maia::tokens(&planes, &elo, &elo)?;
378 report_many("maia", &mut net, &[&tokens], passes)
379}
380
381fn print_kinds(label: &str, net: &Net) {
382 let times = match net.op_times() {
383 Ok(times) => times,
384 Err(why) => {
385 println!("{label}: {why}");
386 return;
387 }
388 };
389 let mut kinds: BTreeMap<String, (usize, f64)> = BTreeMap::new();
390 let (mut total, mut gaps) = (0.0, 0.0);
391 for (name, us, gap) in &times {
392 let kind = name.split(": ").nth(1).unwrap_or(name).to_string();
393 let entry = kinds.entry(kind).or_default();
394 entry.0 += 1;
395 entry.1 += us;
396 total += us;
397 gaps += gap;
398 }
399 let mut rows: Vec<_> = kinds.into_iter().collect();
400 rows.sort_by(|a, b| b.1 .1.total_cmp(&a.1 .1));
401 println!();
402 println!(
403 "{label}: {} dispatches, {:.2} ms in shaders, {:.2} ms in gaps",
404 times.len(),
405 total / 1e3,
406 gaps / 1e3
407 );
408 println!(" {:<22} {:>6} {:>10} {:>10}", "kind", "count", "total ms", "mean us");
409 for (kind, (count, us)) in rows {
410 println!(" {kind:<22} {count:>6} {:>10.3} {:>10.1}", us / 1e3, us / count as f64);
411 }
412 let top: usize =
413 std::env::var("MODELRUNNER_TOP").ok().and_then(|v| v.parse().ok()).unwrap_or(0);
414 let mut slowest: Vec<_> = times.iter().collect();
415 slowest.sort_by(|a, b| b.1.total_cmp(&a.1));
416 for (name, us, _) in slowest.into_iter().take(top) {
417 println!(" top {name:<30} {:>10.3} ms", us / 1e3);
418 }
419}
420
421fn since(since: Instant) -> f64 {
422 since.elapsed().as_secs_f64() * 1e3
423}
424
425fn stats(values: &[f64]) -> String {
426 if values.is_empty() {
427 return "n/a".into();
428 }
429 let mut sorted = values.to_vec();
430 sorted.sort_by(f64::total_cmp);
431 let mean = sorted.iter().sum::<f64>() / sorted.len() as f64;
432 format!(
433 "mean {mean:>8.2} ms median {:>8.2} min {:>8.2} max {:>8.2} (n={})",
434 sorted[sorted.len() / 2],
435 sorted[0],
436 sorted[sorted.len() - 1],
437 sorted.len()
438 )
439}