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

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

report_barriers.rs355 lines · 14.3 KiBRaw
1//! How many of a plan's barriers are real, and which fusions would pay.
2//!
3//! ```text
4//! cargo run --offline --release -p modelrunner --example report_barriers
5//! ```
6//!
7//! # Why
8//!
9//! `vulkan::run::Net::record` emits a `vkCmdPipelineBarrier` after **every** op, which is
10//! expensive — but how expensive is **unmeasured**. The figure this header used to quote (74% of a
11//! Supertonic utterance, 5,091 ms falling to 1,194 ms) came from a no-barrier control that
12//! delivered 43,008 frames against a correct run's 150,528, so it compared a full utterance
13//! against a truncated one and measured output length as much as barrier cost.
14//!
15//! The one valid same-work comparison available is `narrow` at 2,179 ms against `none` at
16//! 1,160 ms, both at 43,008 frames: a 47% delta, at a truncated workload and with a cheaper
17//! barrier than the default. Treat that as a lower bound and not as the headline. A real ceiling
18//! needs the frame count pinned so both paths do identical work — that is task 11. See
19//! `analysis/maml_vs_litert.md` section 6.
20//!
21//! There are two ways to spend less on that, and this decides between them before either is
22//! built:
23//!
24//! * **Emit fewer barriers for the same ops.** [`nets::schedule`] computes how many a
25//! dependency-correct recorder would need. If that is close to the op count the plan is serial
26//! and there is nothing to win, which is the likely answer for a ConvNeXt stack and the reason
27//! to measure before implementing.
28//! * **Have fewer ops.** Every fused node removes a dispatch *and* a barrier. The adjacency table
29//! below ranks the candidates by how often each producer-consumer pair actually occurs, across
30//! every net rather than the one currently under the microscope.
31//!
32//! # No device, no downloads
33//!
34//! Runs on the host: it reads the `.maml` files committed to the repo and only builds plans, which
35//! needs no Vulkan. Nets whose weights are a runtime download (Gemma 4, NLLB) are skipped with a
36//! line saying so rather than failing the run.
37use std::path::{Path, PathBuf};
38
39use modelrunner::nets::schedule::{self, Schedule};
40use modelrunner::nets::{
41 gemma4, maia, mobilefacenet, nllb, ppocr_det, ppocr_rec, scrfd, selfie, supertonic_duration,
42 supertonic_sampler, supertonic_text, supertonic_vocoder, tinyclip, whisper, Kind, Op, Plan,
43 WeightSource,
44};
45use modelrunner::weights::{graph, Weights};
46
47/// Frames and characters to build Supertonic at.
48///
49/// The measured utterance in `analysis/maml_vs_litert.md`: "Hello, this voice runs entirely on
50/// this device." is 49 latent frames and 55 characters once the language tag is added. Plans are
51/// shaped by the utterance, so a report at a made-up length would describe a net nobody runs.
52const FRAMES: u32 = 49;
53const CHARS: u32 = 55;
54
55fn main() {
56 let root = repo_root();
57 println!("reading .maml from {}", root.display());
58 println!();
59
60 let mut plans: Vec<(String, Plan)> = Vec::new();
61 let mut add = |name: &str, plan: Result<Plan, String>| match plan {
62 Ok(plan) => plans.push((name.to_string(), plan)),
63 Err(why) => println!(" {name:<24} does not build: {why}"),
64 };
65
66 // (relative path, graph id, how to build every plan that file backs)
67 if let Some(w) = open(&root, "camera/src/main/assets/selfie_segmentation.maml", graph::SELFIE) {
68 add("selfie", selfie::build(&w.offsets()));
69 }
70 if let Some(w) = open(&root, "photos/src/main/assets/u2netp.maml", graph::U2NETP) {
71 add("u2netp", modelrunner::nets::u2netp::build(&w.offsets()));
72 }
73 if let Some(w) = open(&root, "photos/src/main/assets/scrfd_500m.maml", graph::SCRFD) {
74 add("scrfd 640x640", scrfd::build(&w.offsets(), 640, 640));
75 }
76 if let Some(w) = open(&root, "photos/src/main/assets/w600k_mbf.maml", graph::MOBILEFACENET) {
77 add("mobilefacenet", mobilefacenet::build(&w.offsets()));
78 }
79 if let Some(w) = open(&root, "library/ocr/src/main/assets/ppocr_det.maml", graph::PPOCR_DET) {
80 add("ppocr_det 960x960", ppocr_det::build(&w.offsets(), 960, 960));
81 }
82 if let Some(w) = open(&root, "library/ocr/src/main/assets/ppocr_rec.maml", graph::PPOCR_REC) {
83 add("ppocr_rec w=320", ppocr_rec::build(&w.offsets(), 320));
84 }
85 if let Some(w) = open(&root, "photos/src/main/assets/clip/tinyclip.maml", graph::TINYCLIP) {
86 add("tinyclip image", tinyclip::build(&w.offsets(), tinyclip::Mode::Image));
87 add("tinyclip text", tinyclip::build(&w.offsets(), tinyclip::Mode::Text { len: 16 }));
88 }
89 if let Some(w) = open(&root, "games/chess/src/main/assets/maia3-5m.maml", graph::MAIA) {
90 add("maia", maia::build(&w.offsets()));
91 }
92
93 let supertonic = "speech/src/main/assets/supertonic";
94 if let Some(w) = open(&root, &format!("{supertonic}/supertonic_dp.maml"), graph::SUPERTONIC_DP)
95 {
96 add("supertonic duration", supertonic_duration::build(&w.offsets(), CHARS));
97 }
98 if let Some(w) =
99 open(&root, &format!("{supertonic}/supertonic_ttl.maml"), graph::SUPERTONIC_TTL)
100 {
101 add("supertonic text", supertonic_text::build(&w.offsets(), CHARS));
102 }
103 if let Some(w) = open(&root, &format!("{supertonic}/supertonic_ve.maml"), graph::SUPERTONIC_VE)
104 {
105 add("supertonic sampler", supertonic_sampler::build(&w.offsets(), FRAMES, CHARS));
106 }
107 if let Some(w) =
108 open(&root, &format!("{supertonic}/supertonic_voc.maml"), graph::SUPERTONIC_VOC)
109 {
110 add("supertonic vocoder", supertonic_vocoder::build(&w.offsets(), FRAMES));
111 }
112 if let Some(w) =
113 open(&root, "speech/src/main/assets/whisper-base/whisper_base.maml", graph::WHISPER)
114 {
115 add("whisper encoder", whisper::build(&w.offsets(), whisper::Mode::Encode));
116 }
117
118 // The nets whose weights are a runtime download. Built against `Shapes`, which gives the
119 // same plan as the real file for a fraction of the gigabytes. Gemma 4's decode step is the
120 // largest plan in the runtime and the one `run.rs:695` measured at 676 ms, so it is the most
121 // interesting row here even though it is the only one nobody can load from the repo.
122 add(
123 "gemma4 decode 4096",
124 synthetic(|w| gemma4::build(w, gemma4::Mode::DecodeStep.at(4096))),
125 );
126 add(
127 "gemma4 prefill 256",
128 synthetic(|w| gemma4::build(w, gemma4::Mode::Prefill { tokens: 256 }.at(4096))),
129 );
130 add("nllb encode 32", synthetic(|w| nllb::build(w, nllb::Mode::Encode { len: 32 })));
131 add(
132 "nllb decode step",
133 synthetic(|w| nllb::build(w, nllb::Mode::DecodeStep { src_len: 32 })),
134 );
135
136 if plans.is_empty() {
137 println!("no .maml files found. Run this from inside the repo.");
138 return;
139 }
140
141 barrier_table(&plans);
142 println!();
143 adjacency_table(&plans);
144}
145
146/// One row per plan: how many barriers today, how many a correct recorder needs, and why.
147fn barrier_table(plans: &[(String, Plan)]) {
148 println!("Barriers a dependency-correct recorder would emit, against one per op.");
149 println!();
150 println!(
151 "{:<22} {:>6} {:>8} {:>8} {:>7} {}",
152 "plan", "ops", "today", "needed", "saved", "of the needed ones"
153 );
154 for (name, plan) in plans {
155 let s = schedule::schedule(plan);
156 if let Err(why) = schedule::is_sound(plan, &s) {
157 println!(" {name}: SCHEDULE IS UNSOUND: {why}");
158 continue;
159 }
160 let ops = plan.ops.len();
161 let needed = s.barriers();
162 let saved = if ops == 0 { 0.0 } else { 100.0 * (ops - needed) as f64 / ops as f64 };
163 println!(
164 "{:<22} {:>6} {:>8} {:>8} {:>6.0}% {}",
165 name,
166 ops,
167 ops,
168 needed,
169 saved,
170 why(&s),
171 );
172 }
173 println!();
174 println!("`today` is one per op, which is what `Net::record` does.");
175 println!("A plan whose `saved` is near zero is serial: fusing ops is the only lever on it.");
176}
177
178fn why(s: &Schedule) -> String {
179 let c = s.causes;
180 let mut parts = Vec::new();
181 if c.hazard > 0 {
182 parts.push(format!("{} a real hazard", c.hazard));
183 }
184 if c.unknown > 0 {
185 parts.push(format!("{} an unaudited read", c.unknown));
186 }
187 if c.unbounded > 0 {
188 parts.push(format!("{} an unbounded write", c.unbounded));
189 }
190 if parts.is_empty() {
191 "none".to_string()
192 } else {
193 parts.join(", ")
194 }
195}
196
197/// Which producer-consumer pairs occur often enough to be worth a fused shader.
198///
199/// Counted over consecutive ops that are genuinely chained — the consumer reads exactly what the
200/// producer wrote — because that is the pair a fusion has to replace. Summed across every plan, so
201/// the ranking reflects the runtime rather than whichever net is currently slow.
202///
203/// **Both operands**, and reported separately. A residual `Add(x, f(x))` takes the convolution's
204/// output as its *second* operand, so a table keyed on `in0` alone would score the single most
205/// interesting fusion in this runtime at zero.
206fn adjacency_table(plans: &[(String, Plan)]) {
207 let mut pairs: Vec<((Kind, Kind, u8), usize)> = Vec::new();
208 let mut total = 0usize;
209 for (_, plan) in plans {
210 for window in plan.ops.windows(2) {
211 let (
212 Op::Dispatch { kind: from, push: wrote, .. },
213 Op::Dispatch { kind: to, push: reads, .. },
214 ) = (&window[0], &window[1])
215 else {
216 continue;
217 };
218 // Which operand the producer's output arrives as. `in1` is only meaningful for the
219 // binary kinds, so it is only counted where `arena_reads` says the kind reads it.
220 let binary = matches!(
221 to,
222 Kind::Add
223 | Kind::Mul
224 | Kind::MulBroadcast
225 | Kind::AddBroadcast
226 | Kind::Rotary
227 | Kind::AttnScores
228 | Kind::AttnScoresRelative
229 | Kind::AttnScoresBanded
230 | Kind::AttnApply
231 | Kind::AttnApplyRelative
232 | Kind::AttnApplyBanded
233 | Kind::AttnScoresCached
234 | Kind::AttnApplyCached
235 );
236 let operand = if reads.in0 == wrote.out {
237 0
238 } else if binary && reads.in1 == wrote.out {
239 1
240 } else {
241 continue;
242 };
243 total += 1;
244 match pairs.iter_mut().find(|((f, t, o), _)| f == from && t == to && *o == operand) {
245 Some((_, n)) => *n += 1,
246 None => pairs.push(((*from, *to, operand), 1)),
247 }
248 }
249 }
250 pairs.sort_by(|a, b| b.1.cmp(&a.1));
251
252 println!("Chained producer -> consumer pairs, every plan above summed. {total} in total.");
253 println!("Each fused pair removes one dispatch and one barrier everywhere it occurs.");
254 println!();
255 println!("{:>6} {:>6} {:<44} {}", "count", "share", "pair", "arrives as");
256 for ((from, to, operand), n) in pairs.iter().take(24) {
257 let share = 100.0 * *n as f64 / total.max(1) as f64;
258 let pair = format!("{from:?} -> {to:?}");
259 println!("{:>6} {:>5.1}% {:<44} in{}", n, share, pair, operand);
260 }
261}
262
263/// Read one `.maml`, or say why not and carry on.
264fn open(root: &Path, relative: &str, id: u32) -> Option<Weights> {
265 let path = root.join(relative);
266 let bytes = match std::fs::read(&path) {
267 Ok(bytes) => bytes,
268 Err(why) => {
269 println!(" {relative}: {why}");
270 return None;
271 }
272 };
273 match Weights::parse(&bytes, id) {
274 Ok(weights) => Some(weights),
275 Err(why) => {
276 println!(" {relative}: {why}");
277 None
278 }
279 }
280}
281
282/// A [`WeightSource`] that invents offsets and no data.
283///
284/// Building a [`Plan`] never looks at a weight's *value* — [`Builder`] asks only for an offset and
285/// checks the shape it was given — so a plan built against this is byte-identical to one built
286/// against the real file. That is what lets this report cover Gemma 4 and NLLB, whose weights are
287/// a multi-gigabyte runtime download nobody wants a barrier report to depend on.
288///
289/// Distinct from [`reference::Invented`], which materialises fp32 data and refuses `shaped_words`
290/// outright — no use for the int4 and int8 nets, which are exactly the ones missing from disk.
291struct Shapes {
292 count: usize,
293 next: std::cell::Cell<u32>,
294}
295
296impl Shapes {
297 fn new(count: usize) -> Shapes {
298 Shapes { count, next: std::cell::Cell::new(0) }
299 }
300
301 /// Hand out a 16-byte-aligned offset covering `dims`, as the real table's would be.
302 fn take(&self, dims: &[u32], per: u32) -> u32 {
303 let elements: u32 = dims.iter().copied().product::<u32>().max(1);
304 let at = self.next.get();
305 self.next.set(at + elements.div_ceil(per).next_multiple_of(8));
306 at
307 }
308}
309
310impl WeightSource for Shapes {
311 fn shaped(&self, _index: usize, dims: &[u32]) -> Result<u32, String> {
312 Ok(self.take(dims, 1))
313 }
314
315 fn shaped_words(&self, _index: usize, dims: &[u32]) -> Result<u32, String> {
316 // Four int8 codes to a 32-bit word, which is the only place the unit matters here.
317 Ok(self.take(dims, 4))
318 }
319
320 fn count(&self) -> usize {
321 self.count
322 }
323}
324
325/// Build a plan with no weights, discovering how many tensors the pass wants.
326///
327/// [`Builder::finish`] refuses a pass that leaves a tensor unread — a real guard against a
328/// misindexed net — and a synthetic source has no idea how many there are. So: ask for far too
329/// many, read the count back out of the complaint, and build again. Two attempts, always.
330fn synthetic(build: impl Fn(&dyn WeightSource) -> Result<Plan, String>) -> Result<Plan, String> {
331 match build(&Shapes::new(1 << 20)) {
332 Ok(plan) => Ok(plan),
333 Err(why) => {
334 let wanted = why
335 .split("never reads tensor ")
336 .nth(1)
337 .and_then(|rest| rest.split(' ').next())
338 .and_then(|n| n.parse::<usize>().ok())
339 .ok_or(why)?;
340 build(&Shapes::new(wanted))
341 }
342 }
343}
344
345/// The repo root, from this crate's manifest directory.
346///
347/// `library/ml/src/main/rust` is five levels down, so the example works from wherever `cargo run`
348/// is invoked rather than only from the directory it happens to be in.
349fn repo_root() -> PathBuf {
350 let mut at = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
351 for _ in 0..5 {
352 at.pop();
353 }
354 at
355}