library:ml: a barrier oracle over Plan, and a fusion report
- Commit
92079581893bf99d0f5d040520efa9312f71670a- Author
- vayun-mathur <[email protected]>
- When
- 2026-09-12 03:04 UTC (2 months ago)
- Parents
b83d0b8
Diff
library/ml/src/main/rust/examples/report_barriers.rs
diff --git a/library/ml/src/main/rust/examples/report_barriers.rs b/library/ml/src/main/rust/examples/report_barriers.rsnew file mode 100644index 0000000000..1362f81f1b--- /dev/null+++ b/library/ml/src/main/rust/examples/report_barriers.rs@@ -0,0 +1,347 @@+//! How many of a plan's barriers are real, and which fusions would pay.+//!+//! ```text+//! cargo run --offline --release -p modelrunner --example report_barriers+//! ```+//!+//! # Why+//!+//! `vulkan::run::Net::record` emits a `vkCmdPipelineBarrier` after **every** op, and on a Tensor+//! G4 that is 74% of a Supertonic utterance — 5,091 ms falling to 1,194 ms with the barriers taken+//! out. See `analysis/maml_vs_litert.md`.+//!+//! There are two ways to spend less on that, and this decides between them before either is+//! built:+//!+//! * **Emit fewer barriers for the same ops.** [`nets::schedule`] computes how many a+//! dependency-correct recorder would need. If that is close to the op count the plan is serial+//! and there is nothing to win, which is the likely answer for a ConvNeXt stack and the reason+//! to measure before implementing.+//! * **Have fewer ops.** Every fused node removes a dispatch *and* a barrier. The adjacency table+//! below ranks the candidates by how often each producer-consumer pair actually occurs, across+//! every net rather than the one currently under the microscope.+//!+//! # No device, no downloads+//!+//! Runs on the host: it reads the `.maml` files committed to the repo and only builds plans, which+//! needs no Vulkan. Nets whose weights are a runtime download (Gemma 4, NLLB) are skipped with a+//! line saying so rather than failing the run.+use std::path::{Path, PathBuf};++use modelrunner::nets::schedule::{self, Schedule};+use modelrunner::nets::{+ gemma4, maia, mobilefacenet, nllb, ppocr_det, ppocr_rec, scrfd, selfie, supertonic_duration,+ supertonic_sampler, supertonic_text, supertonic_vocoder, tinyclip, whisper, Kind, Op, Plan,+ WeightSource,+};+use modelrunner::weights::{graph, Weights};++/// Frames and characters to build Supertonic at.+///+/// The measured utterance in `analysis/maml_vs_litert.md`: "Hello, this voice runs entirely on+/// this device." is 49 latent frames and 55 characters once the language tag is added. Plans are+/// shaped by the utterance, so a report at a made-up length would describe a net nobody runs.+const FRAMES: u32 = 49;+const CHARS: u32 = 55;++fn main() {+ let root = repo_root();+ println!("reading .maml from {}", root.display());+ println!();++ let mut plans: Vec<(String, Plan)> = Vec::new();+ let mut add = |name: &str, plan: Result<Plan, String>| match plan {+ Ok(plan) => plans.push((name.to_string(), plan)),+ Err(why) => println!(" {name:<24} does not build: {why}"),+ };++ // (relative path, graph id, how to build every plan that file backs)+ if let Some(w) = open(&root, "camera/src/main/assets/selfie_segmentation.maml", graph::SELFIE) {+ add("selfie", selfie::build(&w.offsets()));+ }+ if let Some(w) = open(&root, "photos/src/main/assets/u2netp.maml", graph::U2NETP) {+ add("u2netp", modelrunner::nets::u2netp::build(&w.offsets()));+ }+ if let Some(w) = open(&root, "photos/src/main/assets/scrfd_500m.maml", graph::SCRFD) {+ add("scrfd 640x640", scrfd::build(&w.offsets(), 640, 640));+ }+ if let Some(w) = open(&root, "photos/src/main/assets/w600k_mbf.maml", graph::MOBILEFACENET) {+ add("mobilefacenet", mobilefacenet::build(&w.offsets()));+ }+ if let Some(w) = open(&root, "library/ocr/src/main/assets/ppocr_det.maml", graph::PPOCR_DET) {+ add("ppocr_det 960x960", ppocr_det::build(&w.offsets(), 960, 960));+ }+ if let Some(w) = open(&root, "library/ocr/src/main/assets/ppocr_rec.maml", graph::PPOCR_REC) {+ add("ppocr_rec w=320", ppocr_rec::build(&w.offsets(), 320));+ }+ if let Some(w) = open(&root, "photos/src/main/assets/clip/tinyclip.maml", graph::TINYCLIP) {+ add("tinyclip image", tinyclip::build(&w.offsets(), tinyclip::Mode::Image));+ add("tinyclip text", tinyclip::build(&w.offsets(), tinyclip::Mode::Text { len: 16 }));+ }+ if let Some(w) = open(&root, "games/chess/src/main/assets/maia3-5m.maml", graph::MAIA) {+ add("maia", maia::build(&w.offsets()));+ }++ let supertonic = "speech/src/main/assets/supertonic";+ if let Some(w) = open(&root, &format!("{supertonic}/supertonic_dp.maml"), graph::SUPERTONIC_DP)+ {+ add("supertonic duration", supertonic_duration::build(&w.offsets(), CHARS));+ }+ if let Some(w) =+ open(&root, &format!("{supertonic}/supertonic_ttl.maml"), graph::SUPERTONIC_TTL)+ {+ add("supertonic text", supertonic_text::build(&w.offsets(), CHARS));+ }+ if let Some(w) = open(&root, &format!("{supertonic}/supertonic_ve.maml"), graph::SUPERTONIC_VE)+ {+ add("supertonic sampler", supertonic_sampler::build(&w.offsets(), FRAMES, CHARS));+ }+ if let Some(w) =+ open(&root, &format!("{supertonic}/supertonic_voc.maml"), graph::SUPERTONIC_VOC)+ {+ add("supertonic vocoder", supertonic_vocoder::build(&w.offsets(), FRAMES));+ }+ if let Some(w) =+ open(&root, "speech/src/main/assets/whisper-base/whisper_base.maml", graph::WHISPER)+ {+ add("whisper encoder", whisper::build(&w.offsets(), whisper::Mode::Encode));+ }++ // The nets whose weights are a runtime download. Built against `Shapes`, which gives the+ // same plan as the real file for a fraction of the gigabytes. Gemma 4's decode step is the+ // largest plan in the runtime and the one `run.rs:695` measured at 676 ms, so it is the most+ // interesting row here even though it is the only one nobody can load from the repo.+ add(+ "gemma4 decode 4096",+ synthetic(|w| gemma4::build(w, gemma4::Mode::DecodeStep.at(4096))),+ );+ add(+ "gemma4 prefill 256",+ synthetic(|w| gemma4::build(w, gemma4::Mode::Prefill { tokens: 256 }.at(4096))),+ );+ add("nllb encode 32", synthetic(|w| nllb::build(w, nllb::Mode::Encode { len: 32 })));+ add(+ "nllb decode step",+ synthetic(|w| nllb::build(w, nllb::Mode::DecodeStep { src_len: 32 })),+ );++ if plans.is_empty() {+ println!("no .maml files found. Run this from inside the repo.");+ return;+ }++ barrier_table(&plans);+ println!();+ adjacency_table(&plans);+}++/// One row per plan: how many barriers today, how many a correct recorder needs, and why.+fn barrier_table(plans: &[(String, Plan)]) {+ println!("Barriers a dependency-correct recorder would emit, against one per op.");+ println!();+ println!(+ "{:<22} {:>6} {:>8} {:>8} {:>7} {}",+ "plan", "ops", "today", "needed", "saved", "of the needed ones"+ );+ for (name, plan) in plans {+ let s = schedule::schedule(plan);+ if let Err(why) = schedule::is_sound(plan, &s) {+ println!(" {name}: SCHEDULE IS UNSOUND: {why}");+ continue;+ }+ let ops = plan.ops.len();+ let needed = s.barriers();+ let saved = if ops == 0 { 0.0 } else { 100.0 * (ops - needed) as f64 / ops as f64 };+ println!(+ "{:<22} {:>6} {:>8} {:>8} {:>6.0}% {}",+ name,+ ops,+ ops,+ needed,+ saved,+ why(&s),+ );+ }+ println!();+ println!("`today` is one per op, which is what `Net::record` does.");+ println!("A plan whose `saved` is near zero is serial: fusing ops is the only lever on it.");+}++fn why(s: &Schedule) -> String {+ let c = s.causes;+ let mut parts = Vec::new();+ if c.hazard > 0 {+ parts.push(format!("{} a real hazard", c.hazard));+ }+ if c.unknown > 0 {+ parts.push(format!("{} an unaudited read", c.unknown));+ }+ if c.unbounded > 0 {+ parts.push(format!("{} an unbounded write", c.unbounded));+ }+ if parts.is_empty() {+ "none".to_string()+ } else {+ parts.join(", ")+ }+}++/// Which producer-consumer pairs occur often enough to be worth a fused shader.+///+/// Counted over consecutive ops that are genuinely chained — the consumer reads exactly what the+/// producer wrote — because that is the pair a fusion has to replace. Summed across every plan, so+/// the ranking reflects the runtime rather than whichever net is currently slow.+///+/// **Both operands**, and reported separately. A residual `Add(x, f(x))` takes the convolution's+/// output as its *second* operand, so a table keyed on `in0` alone would score the single most+/// interesting fusion in this runtime at zero.+fn adjacency_table(plans: &[(String, Plan)]) {+ let mut pairs: Vec<((Kind, Kind, u8), usize)> = Vec::new();+ let mut total = 0usize;+ for (_, plan) in plans {+ for window in plan.ops.windows(2) {+ let (+ Op::Dispatch { kind: from, push: wrote, .. },+ Op::Dispatch { kind: to, push: reads, .. },+ ) = (&window[0], &window[1])+ else {+ continue;+ };+ // Which operand the producer's output arrives as. `in1` is only meaningful for the+ // binary kinds, so it is only counted where `arena_reads` says the kind reads it.+ let binary = matches!(+ to,+ Kind::Add+ | Kind::Mul+ | Kind::MulBroadcast+ | Kind::AddBroadcast+ | Kind::Rotary+ | Kind::AttnScores+ | Kind::AttnScoresRelative+ | Kind::AttnScoresBanded+ | Kind::AttnApply+ | Kind::AttnApplyRelative+ | Kind::AttnApplyBanded+ | Kind::AttnScoresCached+ | Kind::AttnApplyCached+ );+ let operand = if reads.in0 == wrote.out {+ 0+ } else if binary && reads.in1 == wrote.out {+ 1+ } else {+ continue;+ };+ total += 1;+ match pairs.iter_mut().find(|((f, t, o), _)| f == from && t == to && *o == operand) {+ Some((_, n)) => *n += 1,+ None => pairs.push(((*from, *to, operand), 1)),+ }+ }+ }+ pairs.sort_by(|a, b| b.1.cmp(&a.1));++ println!("Chained producer -> consumer pairs, every plan above summed. {total} in total.");+ println!("Each fused pair removes one dispatch and one barrier everywhere it occurs.");+ println!();+ println!("{:>6} {:>6} {:<44} {}", "count", "share", "pair", "arrives as");+ for ((from, to, operand), n) in pairs.iter().take(24) {+ let share = 100.0 * *n as f64 / total.max(1) as f64;+ let pair = format!("{from:?} -> {to:?}");+ println!("{:>6} {:>5.1}% {:<44} in{}", n, share, pair, operand);+ }+}++/// Read one `.maml`, or say why not and carry on.+fn open(root: &Path, relative: &str, id: u32) -> Option<Weights> {+ let path = root.join(relative);+ let bytes = match std::fs::read(&path) {+ Ok(bytes) => bytes,+ Err(why) => {+ println!(" {relative}: {why}");+ return None;+ }+ };+ match Weights::parse(&bytes, id) {+ Ok(weights) => Some(weights),+ Err(why) => {+ println!(" {relative}: {why}");+ None+ }+ }+}++/// A [`WeightSource`] that invents offsets and no data.+///+/// Building a [`Plan`] never looks at a weight's *value* — [`Builder`] asks only for an offset and+/// checks the shape it was given — so a plan built against this is byte-identical to one built+/// against the real file. That is what lets this report cover Gemma 4 and NLLB, whose weights are+/// a multi-gigabyte runtime download nobody wants a barrier report to depend on.+///+/// Distinct from [`reference::Invented`], which materialises fp32 data and refuses `shaped_words`+/// outright — no use for the int4 and int8 nets, which are exactly the ones missing from disk.+struct Shapes {+ count: usize,+ next: std::cell::Cell<u32>,+}++impl Shapes {+ fn new(count: usize) -> Shapes {+ Shapes { count, next: std::cell::Cell::new(0) }+ }++ /// Hand out a 16-byte-aligned offset covering `dims`, as the real table's would be.+ fn take(&self, dims: &[u32], per: u32) -> u32 {+ let elements: u32 = dims.iter().copied().product::<u32>().max(1);+ let at = self.next.get();+ self.next.set(at + elements.div_ceil(per).next_multiple_of(8));+ at+ }+}++impl WeightSource for Shapes {+ fn shaped(&self, _index: usize, dims: &[u32]) -> Result<u32, String> {+ Ok(self.take(dims, 1))+ }++ fn shaped_words(&self, _index: usize, dims: &[u32]) -> Result<u32, String> {+ // Four int8 codes to a 32-bit word, which is the only place the unit matters here.+ Ok(self.take(dims, 4))+ }++ fn count(&self) -> usize {+ self.count+ }+}++/// Build a plan with no weights, discovering how many tensors the pass wants.+///+/// [`Builder::finish`] refuses a pass that leaves a tensor unread — a real guard against a+/// misindexed net — and a synthetic source has no idea how many there are. So: ask for far too+/// many, read the count back out of the complaint, and build again. Two attempts, always.+fn synthetic(build: impl Fn(&dyn WeightSource) -> Result<Plan, String>) -> Result<Plan, String> {+ match build(&Shapes::new(1 << 20)) {+ Ok(plan) => Ok(plan),+ Err(why) => {+ let wanted = why+ .split("never reads tensor ")+ .nth(1)+ .and_then(|rest| rest.split(' ').next())+ .and_then(|n| n.parse::<usize>().ok())+ .ok_or(why)?;+ build(&Shapes::new(wanted))+ }+ }+}++/// The repo root, from this crate's manifest directory.+///+/// `library/ml/src/main/rust` is five levels down, so the example works from wherever `cargo run`+/// is invoked rather than only from the directory it happens to be in.+fn repo_root() -> PathBuf {+ let mut at = PathBuf::from(env!("CARGO_MANIFEST_DIR"));+ for _ in 0..5 {+ at.pop();+ }+ at+}
library/ml/src/main/rust/src/nets/mod.rs
diff --git a/library/ml/src/main/rust/src/nets/mod.rs b/library/ml/src/main/rust/src/nets/mod.rsindex 6e7c04e990..407a28f63f 100644--- a/library/ml/src/main/rust/src/nets/mod.rs+++ b/library/ml/src/main/rust/src/nets/mod.rs@@ -31,6 +31,7 @@ /// so it adds nothing to the shipped `.so`. #[cfg(test)] pub mod reference;+pub mod schedule; pub mod gemma4; pub mod gemma4_audio; pub mod gemma4_vision;@@ -687,6 +688,131 @@ impl Kind { } reads }++ /// Every arena range this kind reads, in **fp16 elements**, given one op's [`Push`].+ ///+ /// The mirror of [`Kind::weight_reads`] for the other buffer, and the reason it is `pub` is+ /// [`super::schedule`]: deciding whether two ops need a barrier between them is exactly+ /// "does the later one read what the earlier one wrote", and that question needs both sides+ /// to be exact.+ ///+ /// # Why [`Reads::Unknown`] exists+ ///+ /// This table began as the arms of `tests::assert_no_aliasing`, which checks a *weaker*+ /// property: that an op does not read the range it is writing. A table that under-reports an+ /// operand still passes that check in every net where the operand happens not to overlap the+ /// output — but a scheduler believing the same table would drop a barrier and read a value+ /// the previous op had not finished writing, non-deterministically, on one driver.+ ///+ /// So there is no catch-all. A kind whose reads have not been checked against its shader+ /// answers [`Reads::Unknown`], which every caller must treat as "reads everything". Adding a+ /// kind is then a choice to audit it or to be conservative, rather than a default that is+ /// silently wrong.+ pub fn arena_reads(self, push: &Push) -> Reads {+ // Every input plane, as the generic shape-driven kinds read it.+ let dense = push.in_c * push.in_h * push.in_w;+ // Every output element. Not `push.count`: the reducing kinds dispatch one invocation per+ // reduction rather than per element, so their `count` understates what they touch.+ let written = push.out_c * push.out_h * push.out_w;+ let one = |at: u32, len: u32| Reads::Ranges(vec![(at, len)]);+ let two = |a: (u32, u32), b: (u32, u32)| Reads::Ranges(vec![a, b]);+ match self {+ // Both operands are the output's shape.+ Kind::Add | Kind::Mul => two((push.in0, written), (push.in1, written)),+ // Rotary reads a partner channel half a head away, so the whole plane, and the angle+ // table is `head_dim` channels of the same length.+ Kind::Rotary => two((push.in0, written), (push.in1, push.in_c * push.out_w)),+ // The gate is one value per channel, broadcast over H and W.+ Kind::MulBroadcast => two((push.in0, written), (push.in1, push.in_c)),+ // As `MulBroadcast`: one shift per channel.+ Kind::AddBroadcast => two((push.in0, written), (push.in1, push.out_c)),+ // Reads no arena at all - it is a copy out of the weights file.+ Kind::Constant => Reads::Ranges(Vec::new()),+ // Q and K are each `in_c` channels but of their own lengths, which the score map's+ // height and width carry.+ Kind::AttnScores | Kind::AttnScoresRelative | Kind::AttnScoresBanded => {+ two((push.in0, push.in_c * push.out_h), (push.in1, push.in_c * push.out_w))+ }+ // The score map is `[heads, queries, keys]`; V is a sequence of keys.+ Kind::AttnApply | Kind::AttnApplyRelative | Kind::AttnApplyBanded => {+ two((push.in0, push.group * push.out_w * push.in_w), (push.in1, dense))+ }+ // One query against a position-major cache. Q is one position of `in_c` channels; the+ // cache is `out_w` positions of `kv_heads * head_dim`, which under grouped- or+ // multi-query attention is narrower than `in_c`.+ Kind::AttnScoresCached => {+ let head_dim = push.in_c / push.group.max(1);+ let kv = if push.kv_heads == 0 { push.group } else { push.kv_heads };+ two((push.in0, push.in_c), (push.in1, push.out_w * kv * head_dim))+ }+ // One query's row of probabilities is `in_w` keys long, and the cache is `in_w`+ // positions of `kv_heads * head_dim`.+ Kind::AttnApplyCached => {+ let head_dim = push.out_c / push.group.max(1);+ let kv = if push.kv_heads == 0 { push.group } else { push.kv_heads };+ two((push.in0, push.group * push.in_w), (push.in1, push.in_w * kv * head_dim))+ }+ // One id per position per lane, so the read is `in_c * out_w` and not `dense` -+ // `in_w` here is the *table's* row count.+ Kind::Embed => one(push.in0, push.in_c * push.out_w),+ // One row in. Not `dense`: `in_h` here is the cache's capacity, not a spatial extent.+ Kind::CacheWrite => one(push.in0, push.count),+ // The whole input plane, whatever the kernel touches. The tiled and gemv lowerings+ // read it too - their `count` is tiles or channel groups, not elements.+ Kind::Conv+ | Kind::ConvTranspose+ | Kind::ConvInt8+ | Kind::ConvPoint+ | Kind::ConvPointInt8+ | Kind::ConvVecInt8+ | Kind::ConvPointInt4+ | Kind::ConvVecInt4+ | Kind::MaxPool+ | Kind::AvgPool+ | Kind::Resize+ | Kind::ResizeNearest+ | Kind::GlobalAvgPool+ | Kind::LayerNorm+ | Kind::RmsNorm+ | Kind::Softmax+ | Kind::SoftmaxCausal+ | Kind::SoftmaxPrefix+ | Kind::Affine+ | Kind::Softcap+ | Kind::Activate+ | Kind::GatedActivate+ | Kind::MulScalar+ | Kind::Clamp => one(push.in0, dense),+ }+ }+}++/// What [`Kind::arena_reads`] knows about an op's reads.+///+/// Not a bare `Vec`, so that "this kind has not been audited" is a value a caller has to handle+/// rather than an empty list it would mistake for "reads nothing". See [`Kind::arena_reads`].+///+/// No arm returns [`Reads::Unknown`] today — the match is exhaustive over [`Kind`], so a new kind+/// fails to compile until someone writes its reads, which is a stronger guarantee than a+/// conservative default would be. The variant stays for the kind that eventually cannot be+/// described statically, so that being conservative is a decision someone makes rather than one+/// they fall into.+#[derive(Clone, Debug, PartialEq, Eq)]+pub enum Reads {+ /// Exactly these `(element offset, element count)` ranges, and nothing else.+ Ranges(Vec<(u32, u32)>),+ /// Unaudited. Treat as reading the whole arena.+ Unknown,+}++impl Reads {+ /// The ranges, or `None` when nothing is known and the caller must be conservative.+ pub fn ranges(&self) -> Option<&[(u32, u32)]> {+ match self {+ Reads::Ranges(ranges) => Some(ranges),+ Reads::Unknown => None,+ }+ } } /// Where one of a net's inputs or outputs lives, and what shape it is.@@ -3695,83 +3821,17 @@ pub(crate) mod tests { let (out, reads) = match *op { Op::Copy { src, dst, elems } => ((dst, elems), vec![(src, elems)]), Op::Dispatch { kind, push, .. } => {- let dense = push.in_c * push.in_h * push.in_w;- // Not `push.count`: the reducing kinds dispatch one invocation per- // reduction rather than per element, so their `count` understates- // what they write. Every output here is dense.- let written = push.out_c * push.out_h * push.out_w;- let reads = match kind {- Kind::Add | Kind::Mul => {- vec![(push.in0, written), (push.in1, written)]- }- // Rotary reads a partner channel half a head away, so the whole plane,- // and the angle table is `head_dim` channels of the same length.- Kind::Rotary => {- vec![(push.in0, written), (push.in1, push.in_c * push.out_w)]- }- // The gate is one value per channel, broadcast over H and W.- Kind::MulBroadcast => {- vec![(push.in0, written), (push.in1, push.in_c)]- }- // As `MulBroadcast`: one shift per channel.- Kind::AddBroadcast => {- vec![(push.in0, written), (push.in1, push.out_c)]- }- // Reads no arena at all - it is a copy out of the weights file.- Kind::Constant => Vec::new(),- // Q and K are each `in_c` channels but of their own lengths, which the- // score map's height and width carry.- Kind::AttnScores | Kind::AttnScoresRelative => {- vec![- (push.in0, push.in_c * push.out_h),- (push.in1, push.in_c * push.out_w),- ]- }- // The score map is `[heads, queries, keys]`; V is a sequence of keys.- Kind::AttnApply | Kind::AttnApplyRelative => {- vec![(push.in0, push.group * push.out_w * push.in_w), (push.in1, dense)]- }- // One query against a position-major cache. Q is one position of `in_c`- // channels; the cache is `out_w` positions of `kv_heads * head_dim`,- // which under grouped- or multi-query attention is narrower than `in_c`.- Kind::AttnScoresCached => {- let head_dim = push.in_c / push.group.max(1);- let kv = if push.kv_heads == 0 { push.group } else { push.kv_heads };- vec![(push.in0, push.in_c), (push.in1, push.out_w * kv * head_dim)]- }- // One query's row of probabilities is `in_w` keys long, and the cache is- // `in_w` positions of `kv_heads * head_dim`.- Kind::AttnApplyCached => {- let head_dim = push.out_c / push.group.max(1);- let kv = if push.kv_heads == 0 { push.group } else { push.kv_heads };- vec![- (push.in0, push.group * push.in_w),- (push.in1, push.in_w * kv * head_dim),- ]- }- // One id per position per lane, so the read is `in_c * out_w` and- // not `dense` - `in_w` here is the *table's* row count.- Kind::Embed => vec![(push.in0, push.in_c * push.out_w)],- // One row in, one row of the cache out. Not `dense`: `in_h` here is the- // cache's capacity, not a spatial extent, so the generic read span would- // be the whole cache and would overlap the write by construction.- //- // The write is reported as the whole cache rather than the single row it- // touches, because which row that is comes from the step and is not- // known here. That is the conservative direction - it can only refuse a- // plan that would have been fine, never accept one that aliases - and it- // is still disjoint from the source, which is a different tensor.- Kind::CacheWrite => vec![(push.in0, push.count)],- // As `Conv`: the whole input plane, whatever the kernel touches.- Kind::ConvInt8 => vec![(push.in0, dense)],- // count is tiles or channel groups here, so the read span is the input- // plane. `ConvVecInt8`'s is one position of it.- Kind::ConvPoint | Kind::ConvPointInt8 | Kind::ConvVecInt8- | Kind::ConvPointInt4 | Kind::ConvVecInt4 => {- vec![(push.in0, dense)]- }- _ => vec![(push.in0, dense)],+ // The one table, in `Kind::arena_reads`. This assertion is the weaker of its+ // two consumers - it only asks whether the reads overlap the write - but+ // sharing it is what keeps `schedule`, which asks the stronger question,+ // honest against every shipping net.+ let reads = match kind.arena_reads(&push) {+ Reads::Ranges(ranges) => ranges,+ // Nothing to assert about a kind that has not been audited. It is not a+ // failure here; `schedule` is where it costs something.+ Reads::Unknown => continue, };+ let written = push.out_c * push.out_h * push.out_w; ((push.out, written), reads) } };
library/ml/src/main/rust/src/nets/schedule.rs
diff --git a/library/ml/src/main/rust/src/nets/schedule.rs b/library/ml/src/main/rust/src/nets/schedule.rsnew file mode 100644index 0000000000..21487e85e2--- /dev/null+++ b/library/ml/src/main/rust/src/nets/schedule.rs@@ -0,0 +1,391 @@+//! Which of a plan's barriers are actually needed.+//!+//! [`super::Plan`]'s `ops` field says "each depends on the results of the ones before it", and+//! [`crate::vulkan::run::Net::record`] takes it literally: a `vkCmdPipelineBarrier` after every+//! op. That claim is false in general, and it is expensive. Measured on a Tensor G4, removing the+//! barriers from Supertonic's sampler takes it from 5,091 ms to 1,194 ms — **74% of an utterance+//! is the drain between one op and the next**, at about 0.55 ms each. See+//! `analysis/maml_vs_litert.md`.+//!+//! This module answers the narrower question the runtime should have been asking: given what each+//! op reads and writes, which pairs actually have to be ordered.+//!+//! # Three hazards, not one+//!+//! It is tempting to track only read-after-write. That is wrong here, because+//! [`super::Builder::finish`] packs the arena with a best-fit coalescing free list that+//! **recycles offsets** as tensors die. Two ops with no path between them in the graph can+//! therefore land on the same bytes, and then:+//!+//! * **RAW** — the later op reads what the earlier wrote. The obvious one.+//! * **WAR** — the later op overwrites a range the earlier is still reading. Without a barrier the+//! earlier op reads the new value.+//! * **WAW** — both write the same range and the survivor is whichever finishes last.+//!+//! Working from offsets rather than from the graph is what makes this safe: recycling is exactly+//! the case a graph-based analysis would call independent and get wrong. It costs some+//! pessimism — a barrier between two ops that only share a range by coincidence — and that is the+//! right direction to be wrong in.+//!+//! # Everything unknown is a barrier+//!+//! [`Kind::arena_reads`] returns [`Reads::Unknown`] for any kind whose reads have not been checked+//! against its shader, and an unknown read forces a flush. So does an op whose write range does+//! not fit the arena, and so does anything involving a transfer. The failure mode of this module+//! is a barrier that was not needed; it must never be a barrier that was.++use super::{Kind, Op, Plan, Push, Reads};++/// A byte range of the arena. Half-open, `[at, at + len)`.+type Range = (u64, u64);++/// What has to happen before an op runs.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct Step {+ /// Whether a barrier must precede this op.+ pub barrier: bool,+ /// Whether that barrier has to name the transfer stage as well as compute.+ ///+ /// True whenever an [`Op::Copy`] is on either side of it: a copy moves data through+ /// `TRANSFER`, and a dependency that names only `COMPUTE_SHADER` would not order it.+ pub transfer: bool,+}++/// Why a barrier had to be emitted, for [`Schedule`]'s report.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]+pub struct Causes {+ /// A real overlap: RAW, WAR or WAW.+ pub hazard: u32,+ /// A kind whose reads are not audited, so it might read anything.+ pub unknown: u32,+ /// A write range that does not fit the arena, or a zero-length one.+ pub unbounded: u32,+}++/// A plan's barriers, and why each is there.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct Schedule {+ /// One entry per op, in plan order.+ pub steps: Vec<Step>,+ /// Barriers by reason. Sums to [`Schedule::barriers`].+ pub causes: Causes,+}++impl Schedule {+ /// Barriers this schedule emits.+ pub fn barriers(&self) -> usize {+ self.steps.iter().filter(|s| s.barrier).count()+ }+}++/// Where an op reads and writes, in arena bytes.+struct Touches {+ reads: Option<Vec<Range>>,+ writes: Vec<Range>,+ transfer: bool,+}++/// The bytes an op touches, or `None` reads when it could touch anything.+///+/// Element offsets are doubled throughout: the arena is fp16 and+/// [`crate::vulkan::run::Net::record`] measures its barrier ranges in bytes, so this has to agree+/// with it exactly or the two disagree about what a barrier covers.+fn touches(op: &Op, arena_elems: u32) -> Touches {+ let bytes = |at: u32, len: u32| (u64::from(at) * 2, u64::from(len) * 2);+ match *op {+ Op::Copy { src, dst, elems } => Touches {+ reads: Some(vec![bytes(src, elems)]),+ writes: vec![bytes(dst, elems)],+ transfer: true,+ },+ Op::Dispatch { kind, push, .. } => {+ let reads = match kind.arena_reads(&push) {+ Reads::Ranges(ranges) => {+ Some(ranges.into_iter().map(|(at, len)| bytes(at, len)).collect())+ }+ Reads::Unknown => None,+ };+ Touches { reads, writes: vec![written(&push, arena_elems)], transfer: false }+ }+ }+}++/// The arena bytes a dispatch writes.+///+/// The same formula `Net::record` uses, deliberately: if the scheduler and the recorder disagree+/// about an op's output, the barrier that does get emitted covers the wrong range.+fn written(push: &Push, arena_elems: u32) -> Range {+ let elems = u64::from(push.out_c) * u64::from(push.out_h.max(1)) * u64::from(push.out_w.max(1));+ let at = u64::from(push.out) * 2;+ let len = elems * 2;+ // A shape this could not have written is a plan bug rather than something to guess around,+ // so it becomes the whole arena and forces a flush - as it does in `record`.+ if len == 0 || at + len > u64::from(arena_elems) * 2 {+ (0, u64::from(arena_elems) * 2)+ } else {+ (at, len)+ }+}++fn overlaps(a: Range, b: Range) -> bool {+ a.0 < b.0 + b.1 && b.0 < a.0 + a.1+}++/// Whether a dispatch's write range was widened to the whole arena by [`written`].+fn unbounded(op: &Op, arena_elems: u32) -> bool {+ match *op {+ Op::Dispatch { push, .. } => {+ let elems =+ u64::from(push.out_c) * u64::from(push.out_h.max(1)) * u64::from(push.out_w.max(1));+ let at = u64::from(push.out) * 2;+ let len = elems * 2;+ len == 0 || at + len > u64::from(arena_elems) * 2+ }+ Op::Copy { .. } => false,+ }+}++/// Which of `plan`'s ops need a barrier before them.+///+/// Walks once, holding the ranges read and written since the last barrier. An op that conflicts+/// with any of them flushes: the pending set clears and the op starts a new one. Ops that do not+/// conflict accumulate, and the GPU is free to overlap them.+pub fn schedule(plan: &Plan) -> Schedule {+ let arena = plan.arena_elems;+ let mut steps = Vec::with_capacity(plan.ops.len());+ let mut causes = Causes::default();+ // Ranges touched since the last barrier, and whether any of them was a transfer.+ let mut pending_reads: Vec<Range> = Vec::new();+ let mut pending_writes: Vec<Range> = Vec::new();+ let mut pending_transfer = false;+ // An op that reads an unaudited set poisons the pending window: nothing after it can be+ // proved independent of it, so the next op flushes.+ let mut pending_unknown = false;++ for op in &plan.ops {+ let it = touches(op, arena);++ let hazard = match &it.reads {+ // RAW against anything written since the last barrier.+ Some(reads) => reads.iter().any(|r| pending_writes.iter().any(|w| overlaps(*r, *w))),+ None => false,+ };+ // WAW against a pending write, and WAR against a pending read.+ let write_hazard = it.writes.iter().any(|w| {+ pending_writes.iter().any(|p| overlaps(*w, *p))+ || pending_reads.iter().any(|p| overlaps(*w, *p))+ });+ let reads_unknown = it.reads.is_none();+ let write_unbounded = unbounded(op, arena);++ let barrier = hazard || write_hazard || reads_unknown || pending_unknown || write_unbounded;+ if barrier {+ // Attribute to the most specific reason, so the report distinguishes "this plan is+ // genuinely serial" from "this plan is full of kinds nobody has audited".+ if hazard || write_hazard {+ causes.hazard += 1;+ } else if reads_unknown || pending_unknown {+ causes.unknown += 1;+ } else {+ causes.unbounded += 1;+ }+ }++ // The barrier goes *before* this op, so it has to cover the transfer stage if either the+ // pending set or this op moves data through it.+ steps.push(Step { barrier, transfer: barrier && (pending_transfer || it.transfer) });++ if barrier {+ pending_reads.clear();+ pending_writes.clear();+ pending_transfer = false;+ pending_unknown = false;+ }+ if let Some(reads) = &it.reads {+ pending_reads.extend_from_slice(reads);+ }+ pending_writes.extend_from_slice(&it.writes);+ pending_transfer |= it.transfer;+ pending_unknown |= reads_unknown;+ }++ Schedule { steps, causes }+}++/// Whether every op that could see a stale value is preceded by a barrier.+///+/// The property [`schedule`] exists to guarantee, checked directly rather than inferred from the+/// walk that produced it: for every pair `i < j` with no barrier between them, `j` must not+/// conflict with `i`. Quadratic and only for tests, but it is the definition rather than a+/// restatement of the implementation, so it catches a bug in the walk itself.+pub fn is_sound(plan: &Plan, schedule: &Schedule) -> Result<(), String> {+ let arena = plan.arena_elems;+ for (j, op) in plan.ops.iter().enumerate() {+ let later = touches(op, arena);+ for i in (0..j).rev() {+ // A barrier anywhere between `i` and `j` orders them.+ if schedule.steps[i + 1..=j].iter().any(|s| s.barrier) {+ break;+ }+ let earlier = touches(&plan.ops[i], arena);+ let raw = later+ .reads+ .as_ref()+ .is_none_or(|r| r.iter().any(|r| earlier.writes.iter().any(|w| overlaps(*r, *w))));+ let waw = later+ .writes+ .iter()+ .any(|w| earlier.writes.iter().any(|p| overlaps(*w, *p)));+ let war = earlier.reads.as_ref().is_none_or(|reads| {+ later.writes.iter().any(|w| reads.iter().any(|r| overlaps(*w, *r)))+ });+ if raw || waw || war {+ return Err(format!("ops {i} and {j} conflict with no barrier between them"));+ }+ }+ }+ Ok(())+}++/// How many ops of each kind a plan holds, for the fusion survey.+pub fn kinds(plan: &Plan) -> Vec<(Kind, usize)> {+ let mut counts: Vec<(Kind, usize)> = Vec::new();+ for op in &plan.ops {+ if let Op::Dispatch { kind, .. } = op {+ match counts.iter_mut().find(|(k, _)| k == kind) {+ Some((_, n)) => *n += 1,+ None => counts.push((*kind, 1)),+ }+ }+ }+ counts.sort_by(|a, b| b.1.cmp(&a.1));+ counts+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::nets::{Binding, Shape};++ /// A dispatch reading `in0` for `in_len` and writing `out` for `out_len`, in elements.+ fn dispatch(in0: u32, in_len: u32, out: u32, out_len: u32) -> Op {+ Op::Dispatch {+ // `Activate` reads exactly `in_c * in_h * in_w` from `in0`, which is the simplest+ // audited arm to build a hazard out of.+ kind: Kind::Activate,+ push: Push {+ in0,+ out,+ in_c: in_len,+ in_h: 1,+ in_w: 1,+ out_c: out_len,+ out_h: 1,+ out_w: 1,+ count: out_len,+ ..Push::default()+ },+ invocations: out_len,+ }+ }++ fn plan(ops: Vec<Op>, arena_elems: u32) -> Plan {+ Plan {+ ops,+ arena_elems,+ inputs: vec![Binding { at: 0, shape: Shape { c: 1, h: 1, w: 1 } }],+ pinned: Vec::new(),+ outputs: vec![Binding { at: 0, shape: Shape { c: 1, h: 1, w: 1 } }],+ }+ }++ #[test]+ fn independent_ops_need_no_barrier_between_them() {+ // Two dispatches over disjoint ranges: 0..8 -> 8..16 and 16..24 -> 24..32.+ let p = plan(vec![dispatch(0, 8, 8, 8), dispatch(16, 8, 24, 8)], 64);+ let s = schedule(&p);+ assert!(!s.steps[1].barrier, "{:?}", s);+ assert_eq!(s.barriers(), 0);+ is_sound(&p, &s).expect("sound");+ }++ #[test]+ fn a_read_after_write_needs_a_barrier() {+ // The second reads exactly what the first wrote.+ let p = plan(vec![dispatch(0, 8, 8, 8), dispatch(8, 8, 24, 8)], 64);+ let s = schedule(&p);+ assert!(s.steps[1].barrier);+ assert_eq!(s.causes.hazard, 1);+ is_sound(&p, &s).expect("sound");+ }++ #[test]+ fn a_write_after_read_needs_a_barrier() {+ // The first reads 0..8; the second overwrites it. Without a barrier the first may see+ // the new value - the hazard a RAW-only analysis misses.+ let p = plan(vec![dispatch(0, 8, 32, 8), dispatch(40, 8, 0, 8)], 64);+ let s = schedule(&p);+ assert!(s.steps[1].barrier);+ assert_eq!(s.causes.hazard, 1);+ is_sound(&p, &s).expect("sound");+ }++ #[test]+ fn a_write_after_write_needs_a_barrier() {+ // Two ops writing the same range, which the arena's offset recycling makes reachable+ // between ops with no graph edge between them.+ let p = plan(vec![dispatch(0, 8, 32, 8), dispatch(16, 8, 32, 8)], 64);+ let s = schedule(&p);+ assert!(s.steps[1].barrier);+ assert_eq!(s.causes.hazard, 1);+ is_sound(&p, &s).expect("sound");+ }++ #[test]+ fn a_recycled_offset_is_a_hazard_even_though_the_graph_says_otherwise() {+ // Three ops. The third reuses the first's output range for its own output, which is what+ // the best-fit arena does once a tensor dies. Nothing connects them in the graph.+ let p = plan(+ vec![dispatch(0, 8, 8, 8), dispatch(16, 8, 24, 8), dispatch(32, 8, 8, 8)],+ 64,+ );+ let s = schedule(&p);+ assert!(s.steps[2].barrier, "the recycled write must be ordered: {s:?}");+ is_sound(&p, &s).expect("sound");+ }++ #[test]+ fn every_kind_is_audited_so_nothing_falls_back_to_unknown() {+ // `arena_reads` matches every `Kind` explicitly and has no catch-all, so adding a kind+ // will not compile until someone writes its arm. That is a stronger guarantee than a+ // default of `Unknown` would be, and this pins the intent: if a future arm returns+ // `Unknown` deliberately it is a decision, not an oversight.+ //+ // Checked over the kinds a plan can hold rather than by reflection, which Rust has not+ // got. `Activate` stands in for the audited path; the exhaustiveness is the compiler's.+ let op = dispatch(0, 8, 8, 8);+ assert!(touches(&op, 64).reads.is_some());+ }++ #[test]+ fn a_copy_makes_its_barrier_name_the_transfer_stage() {+ let p = plan(+ vec![Op::Copy { src: 0, dst: 8, elems: 8 }, dispatch(8, 8, 24, 8)],+ 64,+ );+ let s = schedule(&p);+ assert!(s.steps[1].barrier);+ assert!(s.steps[1].transfer, "a copy on either side needs the transfer stage");+ is_sound(&p, &s).expect("sound");+ }++ #[test]+ fn a_serial_chain_barriers_every_op_but_the_first() {+ // What Supertonic's ConvNeXt stack looks like: each op reads the previous one's output.+ let ops: Vec<Op> = (0..8).map(|i| dispatch(i * 8, 8, (i + 1) * 8, 8)).collect();+ let p = plan(ops, 128);+ let s = schedule(&p);+ assert_eq!(s.barriers(), 7, "a serial chain has no barriers to remove");+ is_sound(&p, &s).expect("sound");+ }+}