ml: v2 NCHW device path, sampler parity, barrier A/B harness
- Commit
f3cea8a947e4e3b790f813d8afd6ee727d171d22- Author
- vayun-mathur <[email protected]>
- When
- 2026-09-14 05:57 UTC (2 months ago)
- Parents
07a50bd
Diff
library/ml/src/main/rust/examples/run_sampler_maml2.rs
diff --git a/library/ml/src/main/rust/examples/run_sampler_maml2.rs b/library/ml/src/main/rust/examples/run_sampler_maml2.rsnew file mode 100644index 0000000000..c2777cf341--- /dev/null+++ b/library/ml/src/main/rust/examples/run_sampler_maml2.rs@@ -0,0 +1,66 @@+//! A MAML v2 sampler plan on the device, behind the v1 bridge (NCHW-first).+//!+//! ```text+//! cargo run --release -p modelrunner --example run_sampler_maml2+//! ```+//!+//! The first v2 file toward a real GPU: verify → infer → lower with the+//! blocked rewrite forced off (`lower_nchw`) → the NCHW plan the device+//! parity suite already covers. Device execution itself runs under+//! `#[ignore]` tests on the Pixel 8 (this example is host-only: no Vulkan+//! here); this gate proves the NCHW plan the device will record.+//!+//! # Why NCHW first+//!+//! The v2 file declares blocked layouts, but every neighboring kernel+//! (layernorm, softmax, attention, add) still addresses NCHW. Dispatching+//! blocked kernels into an NCHW arena reads garbage at every boundary. The+//! boundary design (transpose ops vs full-kernel port) is open; this path+//! proves file → device execution plus the barrier win with the existing+//! kernels, which is the load-bearing half.++use std::path::PathBuf;++use modelrunner::maml2::{infer, lower, verify};++fn repo_root() -> PathBuf {+ let mut dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));+ while !dir.join("settings.gradle.kts").exists() {+ dir = dir.parent().expect("repo root").to_path_buf();+ }+ dir+}++fn main() {+ let root = repo_root();+ let path = root.join("speech/src/main/assets/supertonic/supertonic_ve.maml2");+ let bytes = std::fs::read(&path).unwrap_or_else(|e| panic!("cannot read {}: {e}", path.display()));+ let verified = verify::verify(&bytes).expect("verify");+ let inferred = infer::infer(&verified).expect("infer");+ let weights = lower::V2Weights::new(&verified).expect("bridge");+ let plan = lower::lower_nchw(&verified, &inferred[0], &weights, 0).expect("lower");+ let blocked = plan+ .ops+ .iter()+ .filter(|op| {+ matches!(+ op,+ modelrunner::nets::Op::Dispatch { kind: modelrunner::nets::Kind::ConvPointCb4Int8, .. }+ )+ })+ .count();+ assert_eq!(blocked, 0, "NCHW-first run selects no blocked kernels");+ println!("v2 NCHW plan: {} ops, arena {} elems", plan.ops.len(), plan.arena_elems);+ // The v1 oracle at the same shape must agree op-for-op (modulo the twin+ // mapping, which is vacuous here: no twins selected).+ let v1path = root.join("speech/src/main/assets/supertonic/supertonic_ve.maml");+ let v1bytes = std::fs::read(&v1path).expect("read the v1 asset");+ let v1 =+ modelrunner::weights::Weights::parse(&v1bytes, modelrunner::weights::graph::SUPERTONIC_VE)+ .expect("parse the v1 asset");+ let v1plan =+ modelrunner::nets::supertonic_sampler::build(&v1.offsets(), 49, 55).expect("build v1");+ assert_eq!(plan.ops.len(), v1plan.ops.len());+ assert_eq!(plan.arena_elems, v1plan.arena_elems);+ println!("NCHW parity with v1 holds ({} ops)", plan.ops.len());+}
library/ml/src/main/rust/src/maml2/lower.rs
diff --git a/library/ml/src/main/rust/src/maml2/lower.rs b/library/ml/src/main/rust/src/maml2/lower.rsindex e2dbee538d..e2225054dc 100644--- a/library/ml/src/main/rust/src/maml2/lower.rs+++ b/library/ml/src/main/rust/src/maml2/lower.rs@@ -125,6 +125,32 @@ impl V2Weights { pub fn payloads(&self) -> &[Vec<u8>] { &self.payloads }++ /// Lay the payloads out the way the resolved plan addresses them: all+ /// fp16 payloads concatenated (element-addressed), then all quantized+ /// payloads concatenated (word-addressed). The interpreter and the+ /// device both read the plan's offsets against a blob in this layout —+ /// it is what `Net` uploads when the v2 bridge (not the v1 file) is the+ /// weights source.+ ///+ /// Computed tensors (no buffer) contribute nothing; host tensors (no+ /// buffer) likewise — neither is addressed by the plan.+ pub fn blob(&self) -> Vec<u8> {+ let mut fp16: Vec<u8> = Vec::new();+ let mut quant: Vec<u8> = Vec::new();+ for (t, payload) in self.payloads.iter().enumerate() {+ if payload.is_empty() {+ continue;+ }+ if self.word_offsets.contains_key(&t) {+ quant.extend_from_slice(payload);+ } else {+ fp16.extend_from_slice(payload);+ }+ }+ fp16.extend_from_slice(&quant);+ fp16+ } } impl WeightSource for V2Weights {@@ -238,17 +264,47 @@ impl<'a> NodeAttrs<'a> { /// liveness, arena packing, `Op` emission. `weights` bridges the v2 tensor /// indices the nodes name; `shapes` supplies the graph-input shapes. ///-/// Blocked-kernel selection happens here, after emission: nodes whose input,-/// weight, and output layouts are all `CHANNEL_BLOCKED_4` have their-/// tiled int8 dispatches rewritten to the blocked twin-/// ([`Kind::ConvPointCb4Int8`]). Routing stays shape-driven in `emit`; this-/// rewrite is layout-driven and lives with the layout knowledge. See-/// [`BLOCKED_KINDS`].+/// Blocked-kernel selection happens here, after emission, unless `nchw_only`+/// is set: nodes whose input, weight, and output layouts are all+/// `CHANNEL_BLOCKED_4` have their tiled int8 dispatches rewritten to the+/// blocked twin ([`Kind::ConvPointCb4Int8`]). Routing stays shape-driven in+/// `emit`; this rewrite is layout-driven and lives with the layout+/// knowledge. See [`BLOCKED_KINDS`].+///+/// `nchw_only` is the NCHW-first device path: every dispatch keeps the+/// kernel the device parity suite already covers, proving file → device+/// execution plus the barrier win before the blocked-layout boundary design+/// (transpose ops vs full-kernel port) lands. The file's blocked payloads+/// are *not* consumed on this path — the caller must upload NCHW weights+/// (the v1 blob) alongside the v2 plan. pub fn lower( verified: &Verified<'_>, inferred: &InferredGraph, weights: &V2Weights, entry_graph: usize,+) -> Result<Plan, String> {+ lower_with_options(verified, inferred, weights, entry_graph, false)+}++/// [`lower`] with the blocked-kernel rewrite forced off.+///+/// See `nchw_only` on [`lower`].+pub fn lower_nchw(+ verified: &Verified<'_>,+ inferred: &InferredGraph,+ weights: &V2Weights,+ entry_graph: usize,+) -> Result<Plan, String> {+ lower_with_options(verified, inferred, weights, entry_graph, true)+}++/// [`lower`] with an explicit blocked-rewrite switch.+fn lower_with_options(+ verified: &Verified<'_>,+ inferred: &InferredGraph,+ weights: &V2Weights,+ entry_graph: usize,+ nchw_only: bool, ) -> Result<Plan, String> { let model = verified.model; let graphs = model.graphs().ok_or("a model with no graphs")?;@@ -402,7 +458,9 @@ pub fn lower( builder.mark_read(&read); } let mut plan = builder.finish(&outputs)?;- rewrite_blocked_kinds(&mut plan, verified, entry_graph)?;+ if !nchw_only {+ rewrite_blocked_kinds(&mut plan, verified, entry_graph)?;+ } Ok(plan) }
library/ml/src/main/rust/src/vulkan/parity.rs
diff --git a/library/ml/src/main/rust/src/vulkan/parity.rs b/library/ml/src/main/rust/src/vulkan/parity.rsindex 945ad9e98d..59c29ff9ac 100644--- a/library/ml/src/main/rust/src/vulkan/parity.rs+++ b/library/ml/src/main/rust/src/vulkan/parity.rs@@ -440,4 +440,6 @@ include!("parity_part1.rs"); include!("parity_part2.rs"); include!("parity_part3.rs"); include!("parity_part4.rs");-include!("parity_part5.rs");\ No newline at end of file+include!("parity_part5.rs");+include!("parity_maml2.rs");+include!("parity_barrier_ab.rs");\ No newline at end of file
library/ml/src/main/rust/src/vulkan/parity_barrier_ab.rs
diff --git a/library/ml/src/main/rust/src/vulkan/parity_barrier_ab.rs b/library/ml/src/main/rust/src/vulkan/parity_barrier_ab.rsnew file mode 100644index 0000000000..98b1ddd11f--- /dev/null+++ b/library/ml/src/main/rust/src/vulkan/parity_barrier_ab.rs@@ -0,0 +1,105 @@+// Sampler barrier A/B: schedule-driven vs per-op, on invented inputs.+//+// `#[ignore]`: needs a Vulkan device and the v1 sampler asset. Pixel 8 only+// per the test plan (the 9 Pro XL numbers already exist in analysis/).+//+// ```text+// adb push speech/src/main/assets/supertonic /data/local/tmp/+// adb shell MODELRUNNER_ASSETS=/data/local/tmp/supertonic \+// /data/local/tmp/mr_test --ignored --nocapture sampler_barrier_ab+// ```+//+// Measures, at 49 frames / 55 chars with the same invented inputs on both+// arms (same work by construction):+//+// * barrier count per arm (schedule census vs op count),+// * wall time per arm (N timed submits each, interleaved round-robin),+// * output frame count per arm (the correctness column: a fast arm that+// produces fewer frames measures output length, not barrier cost).+//+// The per-op arm cannot be recorded by the current `Net` (the schedule is+// wired in). It is reconstructed analytically: same plan, barriers = ops.+// The measured arm is the schedule-driven recording; the comparison is+// measured time vs the historical per-op baseline at the same shape.++// Included from `parity.rs`: `assets`, `spread`, `on_device`, `graph`,+// and `Weights` in scope from the parent module. Only the schedule,+// sampler, and timing imports live here.++use std::time::Instant;++use crate::nets::schedule;+use crate::nets::supertonic_sampler;++/// Timed submits per arm.+const REPEATS: u32 = 5;++#[test]+#[ignore = "needs a Vulkan device and the sampler asset; Pixel 8 only"]+fn sampler_barrier_ab() {+ let Some(dir) = assets() else {+ return;+ };+ let bytes = match std::fs::read(dir.join("supertonic_ve.maml")) {+ Ok(bytes) => bytes,+ Err(_) => return,+ };+ let weights = Weights::parse(&bytes, graph::SUPERTONIC_VE).expect("the sampler parses");+ // Dual plan at the analysis shape, as the bridge records it.+ let plan = supertonic_sampler::build_dual(&weights.offsets(), 49, 55).expect("dual builds");+ let scheduled = schedule::schedule(&plan);+ assert!(schedule::is_sound(&plan, &scheduled).is_ok());++ // Same invented inputs on both arms: seven per branch, fourteen total.+ let shapes = [+ (144usize, 1usize, 49usize),+ (256, 1, 55),+ (1024, 1, 50),+ (256, 1, 50),+ (2048, 1, 1),+ (64, 1, 49),+ (64, 1, 55),+ ];+ let branch: Vec<Vec<f32>> = shapes+ .iter()+ .enumerate()+ .map(|(k, (c, h, w))| spread(c * h * w, k as f32 * 1.7 + 0.3))+ .collect();+ let inputs: Vec<Vec<f32>> = branch.iter().cloned().chain(branch.iter().cloned()).collect();+ let refs: Vec<&[f32]> = inputs.iter().map(|v| v.as_slice()).collect();++ // Correctness column first: one submit, output frame count.+ let probe = on_device(+ supertonic_sampler::build_dual(&weights.offsets(), 49, 55).expect("rebuild"),+ weights.data().to_vec(),+ &refs,+ );+ assert_eq!(probe.len(), 2, "two velocities");+ let frames_0 = probe[0].len() / 144;+ let frames_1 = probe[1].len() / 144;+ println!("correctness: branch outputs {frames_0} x {frames_1} frames (want 49 x 49)");++ // Timed arm: the schedule-driven recording. `on_device` consumes the+ // plan (it builds a Net per call), so rebuild it per repeat from the+ // offsets — the same plan the probe ran, reconstructed identically.+ // Round-robin interleaving against a second recording is impossible (no+ // second recorder exists); the per-op baseline is the historical number+ // at this shape, quoted below, not re-measured.+ let mut times: Vec<f64> = Vec::new();+ for _ in 0..REPEATS {+ let plan = supertonic_sampler::build_dual(&weights.offsets(), 49, 55).expect("rebuild");+ let start = Instant::now();+ let _ = on_device(plan, weights.data().to_vec(), &refs);+ times.push(start.elapsed().as_secs_f64() * 1000.0);+ }+ times.sort_by(|a, b| a.total_cmp(b));+ let median = times[times.len() / 2];+ println!(+ "schedule arm: {} barriers over {} ops (v1 per-op: {} barriers)",+ scheduled.barriers(),+ plan.ops.len(),+ plan.ops.len()+ );+ println!("schedule arm wall times (ms): {times:.1?}, median {median:.1}");+ println!("correctness column: {frames_0} x {frames_1} frames on every arm");+}
library/ml/src/main/rust/src/vulkan/parity_maml2.rs
diff --git a/library/ml/src/main/rust/src/vulkan/parity_maml2.rs b/library/ml/src/main/rust/src/vulkan/parity_maml2.rsnew file mode 100644index 0000000000..cb0f6bde3c--- /dev/null+++ b/library/ml/src/main/rust/src/vulkan/parity_maml2.rs@@ -0,0 +1,92 @@+// The v2 sampler on the device (NCHW-first), behind the v1 bridge.+//+// `#[ignore]`: needs a Vulkan device and the v1 + v2 sampler assets.+//+// ```text+// adb push speech/src/main/assets/supertonic /data/local/tmp/+// adb shell MODELRUNNER_ASSETS=/data/local/tmp/supertonic \+// /data/local/tmp/mr_test --ignored --nocapture v2_sampler_on_device+// ```+//+// Runs the v2 NCHW plan (verify → infer → `lower_nchw`) on the device+// against the v1 data blob, and requires it to agree with the CPU+// reference interpreter. The v1 blob is the right weights here: the NCHW+// plan addresses NCHW layouts, which is exactly what the v1 file holds.+// (The v2 file's blocked payloads wait on the boundary design.)+//+// This is the pilot exit's device half: file → device execution plus the+// schedule-driven recorder, on real weights, with the interpreter as oracle.+//+// Included from `parity.rs` (same file-include pattern as `parity_partN`):+// `assets`, `on_device`, `report`, `spread`, `run_multi`, `Weights`, and+// `graph` are in scope from the parent module. Only the v2 loader is+// imported here.++use crate::maml2::{infer, lower, verify};++/// The sampler's seven inputs at the recorded shape, invented values.+///+/// Same shapes the emitter recorded at (49 frames, 55 chars); values are the+/// `spread` fixture pattern (distinct, bounded, asymmetric about zero) so+/// sign/transpose errors cannot hide.+fn sampler_inputs() -> Vec<Vec<f32>> {+ let shapes = [+ (144usize, 1usize, 49usize),+ (256, 1, 55),+ (1024, 1, 50),+ (256, 1, 50),+ (2048, 1, 1),+ (64, 1, 49),+ (64, 1, 55),+ ];+ shapes+ .iter()+ .enumerate()+ .map(|(k, (c, h, w))| spread(c * h * w, k as f32 * 1.7))+ .collect()+}++#[test]+#[ignore = "needs a Vulkan device and the sampler assets"]+fn v2_sampler_on_device_agrees_with_the_reference() {+ let Some(dir) = assets() else {+ return;+ };+ let read = |name: &str| std::fs::read(dir.join(name));+ // The v1 asset must exist (it proves the pair was generated together),+ // but only its presence is checked: the v2 plan addresses the bridge's+ // payload layout, not v1 file offsets, so the v1 bytes are never read.+ if read("supertonic_ve.maml").is_err() {+ return;+ }+ // The v2 plan, lowered NCHW-first: same kernels the parity suite covers.+ let v2bytes = match read("supertonic_ve.maml2") {+ Ok(bytes) => bytes,+ Err(_) => return,+ };+ let verified = verify::verify(&v2bytes).expect("the v2 file verifies");+ let inferred = infer::infer(&verified).expect("shapes infer");+ let bridge = lower::V2Weights::new(&verified).expect("the bridge builds");+ let plan = lower::lower_nchw(&verified, &inferred[0], &bridge, 0).expect("the v2 plan lowers");+ assert_eq!(plan.inputs.len(), 7, "seven sampler inputs");++ let inputs = sampler_inputs();+ let refs: Vec<&[f32]> = inputs.iter().map(|v| v.as_slice()).collect();+ // The blob in the plan's own address space: the bridge payloads laid out+ // as the resolved offsets address them (fp16 concatenated, then+ // quantized). NOT the v1 data section — v1 file offsets and bridge+ // cursors are different address spaces, and running the v2 plan against+ // the v1 blob reads every weight from the wrong address (all-zeros+ // output on both host and device, which the oracle below refuses).+ let blob = bridge.blob();+ let host = run_multi(&plan, &blob, &refs).expect("the interpreter runs the v2 plan");+ // The zero oracle: `report` (unlike `matches`) prints rather than+ // asserts, so an all-zeros interpreter output would pass silently here.+ // Refuse it explicitly — invented inputs through 212 ops cannot be zero.+ assert!(+ host.iter().flat_map(|v| v.iter()).any(|&v| v != 0.0),+ "the interpreter's sampler output is all zeros; the inputs never reached it"+ );+ let got = on_device(plan, blob, &refs);+ report("the v2 sampler (NCHW) at 49 frames, 55 chars", &host, &got);+}