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

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

report_barriers.rs341 lines · 14.2 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("gemma4 decode 4096", synthetic(|w| gemma4::build(w, gemma4::Mode::DecodeStep.at(4096))));
123 add(
124 "gemma4 prefill 256",
125 synthetic(|w| gemma4::build(w, gemma4::Mode::Prefill { tokens: 256 }.at(4096))),
126 );
127 add("nllb encode 32", synthetic(|w| nllb::build(w, nllb::Mode::Encode { len: 32 })));
128 add("nllb decode step", synthetic(|w| nllb::build(w, nllb::Mode::DecodeStep { src_len: 32 })));
129
130 if plans.is_empty() {
131 println!("no .maml files found. Run this from inside the repo.");
132 return;
133 }
134
135 barrier_table(&plans);
136 println!();
137 adjacency_table(&plans);
138}
139
140/// One row per plan: how many barriers today, how many a correct recorder needs, and why.
141fn barrier_table(plans: &[(String, Plan)]) {
142 println!("Barriers a dependency-correct recorder would emit, against one per op.");
143 println!();
144 println!(
145 "{:<22} {:>6} {:>8} {:>8} {:>7} of the needed ones",
146 "plan", "ops", "today", "needed", "saved"
147 );
148 for (name, plan) in plans {
149 let s = schedule::schedule(plan);
150 if let Err(why) = schedule::is_sound(plan, &s) {
151 println!(" {name}: SCHEDULE IS UNSOUND: {why}");
152 continue;
153 }
154 let ops = plan.ops.len();
155 let needed = s.barriers();
156 let saved = if ops == 0 { 0.0 } else { 100.0 * (ops - needed) as f64 / ops as f64 };
157 println!("{:<22} {:>6} {:>8} {:>8} {:>6.0}% {}", name, ops, ops, needed, saved, why(&s),);
158 }
159 println!();
160 println!("`today` is one per op, which is what `Net::record` does.");
161 println!("A plan whose `saved` is near zero is serial: fusing ops is the only lever on it.");
162}
163
164fn why(s: &Schedule) -> String {
165 let c = s.causes;
166 let mut parts = Vec::new();
167 if c.hazard > 0 {
168 parts.push(format!("{} a real hazard", c.hazard));
169 }
170 if c.unknown > 0 {
171 parts.push(format!("{} an unaudited read", c.unknown));
172 }
173 if c.unbounded > 0 {
174 parts.push(format!("{} an unbounded write", c.unbounded));
175 }
176 if parts.is_empty() {
177 "none".to_string()
178 } else {
179 parts.join(", ")
180 }
181}
182
183/// Which producer-consumer pairs occur often enough to be worth a fused shader.
184///
185/// Counted over consecutive ops that are genuinely chained — the consumer reads exactly what the
186/// producer wrote — because that is the pair a fusion has to replace. Summed across every plan, so
187/// the ranking reflects the runtime rather than whichever net is currently slow.
188///
189/// **Both operands**, and reported separately. A residual `Add(x, f(x))` takes the convolution's
190/// output as its *second* operand, so a table keyed on `in0` alone would score the single most
191/// interesting fusion in this runtime at zero.
192fn adjacency_table(plans: &[(String, Plan)]) {
193 let mut pairs: Vec<((Kind, Kind, u8), usize)> = Vec::new();
194 let mut total = 0usize;
195 for (_, plan) in plans {
196 for window in plan.ops.windows(2) {
197 let (
198 Op::Dispatch { kind: from, push: wrote, .. },
199 Op::Dispatch { kind: to, push: reads, .. },
200 ) = (&window[0], &window[1])
201 else {
202 continue;
203 };
204 // Which operand the producer's output arrives as. `in1` is only meaningful for the
205 // binary kinds, so it is only counted where `arena_reads` says the kind reads it.
206 let binary = matches!(
207 to,
208 Kind::Add
209 | Kind::Mul
210 | Kind::MulBroadcast
211 | Kind::AddBroadcast
212 | Kind::Rotary
213 | Kind::AttnScores
214 | Kind::AttnScoresRelative
215 | Kind::AttnScoresBanded
216 | Kind::AttnApply
217 | Kind::AttnApplyRelative
218 | Kind::AttnApplyBanded
219 | Kind::AttnScoresCached
220 | Kind::AttnApplyCached
221 );
222 let operand = if reads.in0 == wrote.out {
223 0
224 } else if binary && reads.in1 == wrote.out {
225 1
226 } else {
227 continue;
228 };
229 total += 1;
230 match pairs.iter_mut().find(|((f, t, o), _)| f == from && t == to && *o == operand) {
231 Some((_, n)) => *n += 1,
232 None => pairs.push(((*from, *to, operand), 1)),
233 }
234 }
235 }
236 pairs.sort_by_key(|b| std::cmp::Reverse(b.1));
237
238 println!("Chained producer -> consumer pairs, every plan above summed. {total} in total.");
239 println!("Each fused pair removes one dispatch and one barrier everywhere it occurs.");
240 println!();
241 println!("{:>6} {:>6} {:<44} arrives as", "count", "share", "pair");
242 for ((from, to, operand), n) in pairs.iter().take(24) {
243 let share = 100.0 * *n as f64 / total.max(1) as f64;
244 let pair = format!("{from:?} -> {to:?}");
245 println!("{:>6} {:>5.1}% {:<44} in{}", n, share, pair, operand);
246 }
247}
248
249/// Read one `.maml`, or say why not and carry on.
250fn open(root: &Path, relative: &str, id: u32) -> Option<Weights> {
251 let path = root.join(relative);
252 let bytes = match std::fs::read(&path) {
253 Ok(bytes) => bytes,
254 Err(why) => {
255 println!(" {relative}: {why}");
256 return None;
257 }
258 };
259 match Weights::parse(&bytes, id) {
260 Ok(weights) => Some(weights),
261 Err(why) => {
262 println!(" {relative}: {why}");
263 None
264 }
265 }
266}
267
268/// A [`WeightSource`] that invents offsets and no data.
269///
270/// Building a [`Plan`] never looks at a weight's *value* — [`Builder`] asks only for an offset and
271/// checks the shape it was given — so a plan built against this is byte-identical to one built
272/// against the real file. That is what lets this report cover Gemma 4 and NLLB, whose weights are
273/// a multi-gigabyte runtime download nobody wants a barrier report to depend on.
274///
275/// Distinct from [`reference::Invented`], which materialises fp32 data and refuses `shaped_words`
276/// outright — no use for the int4 and int8 nets, which are exactly the ones missing from disk.
277struct Shapes {
278 count: usize,
279 next: std::cell::Cell<u32>,
280}
281
282impl Shapes {
283 fn new(count: usize) -> Shapes {
284 Shapes { count, next: std::cell::Cell::new(0) }
285 }
286
287 /// Hand out a 16-byte-aligned offset covering `dims`, as the real table's would be.
288 fn take(&self, dims: &[u32], per: u32) -> u32 {
289 let elements: u32 = dims.iter().copied().product::<u32>().max(1);
290 let at = self.next.get();
291 self.next.set(at + elements.div_ceil(per).next_multiple_of(8));
292 at
293 }
294}
295
296impl WeightSource for Shapes {
297 fn shaped(&self, _index: usize, dims: &[u32]) -> Result<u32, String> {
298 Ok(self.take(dims, 1))
299 }
300
301 fn shaped_words(&self, _index: usize, dims: &[u32]) -> Result<u32, String> {
302 // Four int8 codes to a 32-bit word, which is the only place the unit matters here.
303 Ok(self.take(dims, 4))
304 }
305
306 fn count(&self) -> usize {
307 self.count
308 }
309}
310
311/// Build a plan with no weights, discovering how many tensors the pass wants.
312///
313/// [`Builder::finish`] refuses a pass that leaves a tensor unread — a real guard against a
314/// misindexed net — and a synthetic source has no idea how many there are. So: ask for far too
315/// many, read the count back out of the complaint, and build again. Two attempts, always.
316fn synthetic(build: impl Fn(&dyn WeightSource) -> Result<Plan, String>) -> Result<Plan, String> {
317 match build(&Shapes::new(1 << 20)) {
318 Ok(plan) => Ok(plan),
319 Err(why) => {
320 let wanted = why
321 .split("never reads tensor ")
322 .nth(1)
323 .and_then(|rest| rest.split(' ').next())
324 .and_then(|n| n.parse::<usize>().ok())
325 .ok_or(why)?;
326 build(&Shapes::new(wanted))
327 }
328 }
329}
330
331/// The repo root, from this crate's manifest directory.
332///
333/// `library/ml/src/main/rust` is five levels down, so the example works from wherever `cargo run`
334/// is invoked rather than only from the directory it happens to be in.
335fn repo_root() -> PathBuf {
336 let mut at = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
337 for _ in 0..5 {
338 at.pop();
339 }
340 at
341}