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

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

profile_vision.rs422 lines · 17.5 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(
153 label: &str,
154 net: &mut Net,
155 inputs: &[&[f32]],
156 passes: u32,
157) -> Result<(), String> {
158 let mut ms = Vec::new();
159 net.infer_raw_many(inputs)?;
160 for _ in 0..passes {
161 let t = Instant::now();
162 let out = net.infer_raw_many(inputs)?;
163 ms.push(since(t));
164 if ms.len() == passes as usize {
165 print_checksums(&out);
166 }
167 }
168 println!("infer {}", stats(&ms));
169 net.infer_raw_many(inputs)?;
170 print_kinds(label, net);
171 Ok(())
172}
173
174fn print_checksums(out: &[Vec<f32>]) {
175 for (i, binding) in out.iter().enumerate() {
176 let sum: f64 = binding.iter().map(|&v| f64::from(v)).sum();
177 let max: f32 = binding.iter().fold(0.0f32, |a, &v| a.max(v.abs()));
178 println!("output[{i}] len {:>8} checksum {sum:.6} maxabs {max:.6}", binding.len());
179 }
180}
181
182fn profile_selfie(path: &str, passes: u32) -> Result<(), String> {
183 let weights = load(path, graph::SELFIE)?;
184 let context = context::shared()?;
185 let started = Instant::now();
186 let plan = selfie::build(&weights)?;
187 let mut net = Net::new(context, plan, &weights, RESCALE_ONLY)?;
188 println!("load {:>8.1} ms (upload + first record)", since(started));
189 let input = pattern(3 * selfie::SIZE as usize * selfie::SIZE as usize);
190 let input_b = blob(3, selfie::SIZE as usize, selfie::SIZE as usize);
191 report("selfie", &mut net, &input, &input_b, passes)
192}
193
194fn profile_modnet(path: &str, passes: u32) -> Result<(), String> {
195 let weights = load(path, graph::MODNET)?;
196 let context = context::shared()?;
197 let started = Instant::now();
198 let plan = modnet::build(&weights)?;
199 let mut net = Net::new(context, plan, &weights, RESCALE_ONLY)?;
200 println!("load {:>8.1} ms (upload + first record)", since(started));
201 let input = pattern(3 * modnet::SIZE as usize * modnet::SIZE as usize);
202 let input_b = blob(3, modnet::SIZE as usize, modnet::SIZE as usize);
203 report("modnet", &mut net, &input, &input_b, passes)
204}
205
206fn profile_u2netp(path: &str, passes: u32) -> Result<(), String> {
207 let weights = load(path, graph::U2NETP)?;
208 let context = context::shared()?;
209 let started = Instant::now();
210 let plan = u2netp::build(&weights)?;
211 let mut net = Net::new(context, plan, &weights, RESCALE_ONLY)?;
212 println!("load {:>8.1} ms (upload + first record)", since(started));
213 let input = pattern(3 * u2netp::SIZE as usize * u2netp::SIZE as usize);
214 let input_b = blob(3, u2netp::SIZE as usize, u2netp::SIZE as usize);
215 report("u2netp", &mut net, &input, &input_b, passes)
216}
217
218fn profile_scrfd(path: &str, passes: u32) -> Result<(), String> {
219 let weights = load(path, graph::SCRFD)?;
220 let context = context::shared()?;
221 let started = Instant::now();
222 // The bridge builds at the fixed LONG_SIDE square; profile that.
223 let plan = scrfd::build(&weights, scrfd::LONG_SIDE, scrfd::LONG_SIDE)?;
224 let mut net = Net::new(context, plan, &weights, RESCALE_ONLY)?;
225 println!("load {:>8.1} ms (upload + first record)", since(started));
226 let side = scrfd::LONG_SIDE as usize;
227 let input = pattern(3 * side * side);
228 let input_b = blob(3, side, side);
229 report("scrfd", &mut net, &input, &input_b, passes)
230}
231
232fn profile_mbf(path: &str, passes: u32) -> Result<(), String> {
233 let weights = load(path, graph::MOBILEFACENET)?;
234 let context = context::shared()?;
235 let started = Instant::now();
236 let plan = mobilefacenet::build(&weights)?;
237 let mut net = Net::new(context, plan, &weights, RESCALE_ONLY)?;
238 println!("load {:>8.1} ms (upload + first record)", since(started));
239 let input = pattern(3 * mobilefacenet::SIZE as usize * mobilefacenet::SIZE as usize);
240 let input_b = blob(3, mobilefacenet::SIZE as usize, mobilefacenet::SIZE as usize);
241 report("mbf", &mut net, &input, &input_b, passes)
242}
243
244fn profile_det(path: &str, passes: u32) -> Result<(), String> {
245 let weights = load(path, graph::PPOCR_DET)?;
246 let context = context::shared()?;
247 let started = Instant::now();
248 // The bridge builds at the fixed LONG_SIDE square; profile that.
249 let plan = ppocr_det::build(&weights, ppocr_det::LONG_SIDE, ppocr_det::LONG_SIDE)?;
250 let mut net = Net::new(context, plan, &weights, RESCALE_ONLY)?;
251 println!("load {:>8.1} ms (upload + first record)", since(started));
252 let side = ppocr_det::LONG_SIDE as usize;
253 let input = pattern(3 * side * side);
254 let input_b = blob(3, side, side);
255 report("det", &mut net, &input, &input_b, passes)
256}
257
258fn profile_rec(path: &str, passes: u32) -> Result<(), String> {
259 let weights = load(path, graph::PPOCR_REC)?;
260 let context = context::shared()?;
261 let started = Instant::now();
262 // The bridge builds at the fixed REC_WIDTH; profile that.
263 let plan = ppocr_rec::build(&weights, REC_WIDTH)?;
264 let mut net = Net::new(context, plan, &weights, PPOCR_REC)?;
265 println!("load {:>8.1} ms (upload + first record)", since(started));
266 let input = pattern(3 * ppocr_rec::HEIGHT as usize * REC_WIDTH as usize);
267 let input_b = blob(3, ppocr_rec::HEIGHT as usize, REC_WIDTH as usize);
268 report("rec", &mut net, &input, &input_b, passes)
269}
270
271/// Eight lines one submit each against one batched submit; the logits must match bit for bit.
272fn profile_rec_batch(path: &str, passes: u32) -> Result<(), String> {
273 const LINES: u32 = 8;
274 let weights = load(path, graph::PPOCR_REC)?;
275 let context = context::shared()?;
276 let t = Instant::now();
277 let mut single = Net::new(context.clone(), ppocr_rec::build(&weights, REC_WIDTH)?, &weights, PPOCR_REC)?;
278 println!("load single {:.1} ms", since(t));
279 for lines in [2u32, 4] {
280 let t = Instant::now();
281 let _net = Net::new(context.clone(), ppocr_rec::build_batch(&weights, REC_WIDTH, lines)?, &weights, PPOCR_REC)?;
282 println!("load batch of {lines} {:.1} ms", since(t));
283 }
284 let t = Instant::now();
285 let mut batch =
286 Net::new(context, ppocr_rec::build_batch(&weights, REC_WIDTH, LINES)?, &weights, PPOCR_REC)?;
287 println!("load batch of {LINES} {:.1} ms", since(t));
288 let len = ppocr_rec::HEIGHT as usize * REC_WIDTH as usize;
289 let strips: Vec<Vec<i32>> = (0..LINES as usize)
290 .map(|i| (0..len).map(|p| (0xff00_0000u32 | ((p * 37 + i * 101) as u32 * 2_654_435_761 >> 8)) as i32).collect())
291 .collect();
292 let shape = modelrunner::nets::Shape::new(3, ppocr_rec::HEIGHT, REC_WIDTH);
293 let mut half = vec![0u16; shape.len() as usize];
294 let mut inputs = Vec::new();
295 for strip in &strips {
296 to_planar_f16(strip, REC_WIDTH, ppocr_rec::HEIGHT, shape, &PPOCR_REC, &mut half)?;
297 inputs.push(half.iter().map(|&h| f16_to_f32(h)).collect::<Vec<f32>>());
298 }
299 let refs: Vec<&[f32]> = inputs.iter().map(Vec::as_slice).collect();
300 let (mut one, mut many) = (Vec::new(), Vec::new());
301 let mut expected = Vec::new();
302 for _ in 0..=passes {
303 let t = Instant::now();
304 expected = strips
305 .iter()
306 .map(|s| single.infer(s, REC_WIDTH, ppocr_rec::HEIGHT))
307 .collect::<Result<Vec<_>, _>>()?;
308 one.push(since(t));
309 let t = Instant::now();
310 let got = batch.infer_raw_many(&refs)?;
311 many.push(since(t));
312 if expected != got {
313 return Err("a batched line's logits differ from its single run".into());
314 }
315 }
316 println!("single {} for {LINES} lines", stats(&one[1..]));
317 println!("batched {} for {LINES} lines (identical logits)", stats(&many[1..]));
318 print_checksums(&expected);
319 Ok(())
320}
321
322fn tinyclip_plan(offsets: &Offsets, mode: tinyclip::Mode) -> Result<Plan, String> {
323 tinyclip::build(offsets, mode)
324}
325
326fn profile_clip_image(path: &str, passes: u32) -> Result<(), String> {
327 let weights = load(path, graph::TINYCLIP)?;
328 let context = context::shared()?;
329 let started = Instant::now();
330 let mut nets = Reshaped::new(context, &weights, tinyclip::Mode::Image, tinyclip_plan)?;
331 println!("load {:>8.1} ms (upload + first record)", since(started));
332 let side = tinyclip::IMAGE_SIZE as usize;
333 let input = pattern(3 * side * side);
334 let input_b = blob(3, side, side);
335 let net = nets.at(tinyclip::Mode::Image)?;
336 report("clip_image", net, &input, &input_b, passes)
337}
338
339fn profile_clip_text(path: &str, passes: u32) -> Result<(), String> {
340 let weights = load(path, graph::TINYCLIP)?;
341 let context = context::shared()?;
342 let started = Instant::now();
343 // `<|startoftext|>`, three pieces, `<|endoftext|>`: a typical short query.
344 let ids: Vec<u32> = vec![49406, 1234, 5678, 9012, 49407];
345 let embedded = tinyclip::embed_positions(weights.reader(), &ids)?;
346 let len = ids.len() as u32;
347 let mut nets = Reshaped::new(context, &weights, tinyclip::Mode::Text { len }, tinyclip_plan)?;
348 println!("load {:>8.1} ms (upload + first record)", since(started));
349 let net = nets.at(tinyclip::Mode::Text { len })?;
350 report_many("clip_text", net, &[&embedded], passes)
351}
352
353fn profile_maia(path: &str, passes: u32) -> Result<(), String> {
354 let weights = load(path, graph::MAIA)?;
355 let context = context::shared()?;
356 let started = Instant::now();
357 let plan = maia::build(&weights)?;
358 let mut net = Net::new(context, plan, &weights, RESCALE_ONLY)?;
359 println!("load {:>8.1} ms (upload + first record)", since(started));
360 // A sparse opening-like board: a few pieces on their squares, both sides at 1500.
361 let mut planes = vec![0.0f32; maia::PLANES as usize * maia::SQUARES as usize];
362 for (plane, square) in [(5, 12), (5, 52), (4, 1), (4, 57), (11, 4), (11, 60)] {
363 planes[plane * maia::SQUARES as usize + square] = 1.0;
364 }
365 let elo = maia::elo_embedding(weights.reader(), 1500.0)?;
366 let tokens = maia::tokens(&planes, &elo, &elo)?;
367 report_many("maia", &mut net, &[&tokens], passes)
368}
369
370fn print_kinds(label: &str, net: &Net) {
371 let times = match net.op_times() {
372 Ok(times) => times,
373 Err(why) => {
374 println!("{label}: {why}");
375 return;
376 }
377 };
378 let mut kinds: BTreeMap<String, (usize, f64)> = BTreeMap::new();
379 let (mut total, mut gaps) = (0.0, 0.0);
380 for (name, us, gap) in &times {
381 let kind = name.split(": ").nth(1).unwrap_or(name).to_string();
382 let entry = kinds.entry(kind).or_default();
383 entry.0 += 1;
384 entry.1 += us;
385 total += us;
386 gaps += gap;
387 }
388 let mut rows: Vec<_> = kinds.into_iter().collect();
389 rows.sort_by(|a, b| b.1 .1.total_cmp(&a.1 .1));
390 println!();
391 println!("{label}: {} dispatches, {:.2} ms in shaders, {:.2} ms in gaps", times.len(), total / 1e3, gaps / 1e3);
392 println!(" {:<22} {:>6} {:>10} {:>10}", "kind", "count", "total ms", "mean us");
393 for (kind, (count, us)) in rows {
394 println!(" {kind:<22} {count:>6} {:>10.3} {:>10.1}", us / 1e3, us / count as f64);
395 }
396 let top: usize = std::env::var("MODELRUNNER_TOP").ok().and_then(|v| v.parse().ok()).unwrap_or(0);
397 let mut slowest: Vec<_> = times.iter().collect();
398 slowest.sort_by(|a, b| b.1.total_cmp(&a.1));
399 for (name, us, _) in slowest.into_iter().take(top) {
400 println!(" top {name:<30} {:>10.3} ms", us / 1e3);
401 }
402}
403
404fn since(since: Instant) -> f64 {
405 since.elapsed().as_secs_f64() * 1e3
406}
407
408fn stats(values: &[f64]) -> String {
409 if values.is_empty() {
410 return "n/a".into();
411 }
412 let mut sorted = values.to_vec();
413 sorted.sort_by(f64::total_cmp);
414 let mean = sorted.iter().sum::<f64>() / sorted.len() as f64;
415 format!(
416 "mean {mean:>8.2} ms median {:>8.2} min {:>8.2} max {:>8.2} (n={})",
417 sorted[sorted.len() / 2],
418 sorted[0],
419 sorted[sorted.len() - 1],
420 sorted.len()
421 )
422}