ml: v2 kernels NCHW-verbatim, bit-exact v1 parity on host
- Commit
9d652fb3a9d4793aadbf463c49910733c981ce3d- Author
- vayun-mathur <[email protected]>
- When
- 2026-09-14 07:18 UTC (2 months ago)
- Parents
cb22ad8
Diff
library/ml/MAML2_SPEC.md
diff --git a/library/ml/MAML2_SPEC.md b/library/ml/MAML2_SPEC.mdindex 178303ffa3..facee7f7bf 100644--- a/library/ml/MAML2_SPEC.md+++ b/library/ml/MAML2_SPEC.md@@ -146,17 +146,27 @@ Quantization { Layout : byte { NCHW = 0; CHANNEL_BLOCKED_4 = 1; POSITION_MAJOR = 2; } ``` -* Each tensor declares its layout. The converter **repacks weights into- whatever the kernels consume** (kernel-chosen layout at convert time, per- the v1 lesson that init-time repack forfeits zero-copy upload).-* Computed tensors default to `CHANNEL_BLOCKED_4` (the PHWC4 equivalent):- channel groups of 4 contiguous, so a channel reduction is a `vec4` load.- The v1 NCHW strided-reduction defect (§0.3) becomes inexpressible.+* Each tensor declares its layout. Kernels are **always NCHW** in the file:+ every kernel — NCHW or blocked twin — reads kernel bytes NCHW, so one+ stored layout serves every execution layout and the host interpreter+ (NCHW-only) stays a valid oracle for all of them. Only activations block.+ (The pilot stored blocked kernels; that forked the interpreter from the+ device with both sides self-consistent, and was reverted.)+* Computed tensors are `CHANNEL_BLOCKED_4` where the dispatched kernels+ consume blocked activations (the PHWC4 equivalent): channel groups of 4+ contiguous, so a channel reduction is a `vec4` load. The v1 NCHW+ strided-reduction defect (§0.3) becomes inexpressible wherever twins run.+* Mixed plans carry explicit transpose ops at NCHW↔blocked boundaries; a+ producer/consumer pair with different layouts and no transpose between+ them is a loader bug, caught by shape+layout inference at load.+* During the migration most files are all-NCHW (few dispatched kernels have+ blocked twins yet): they declare NCHW throughout, honestly. A file is+ re-emitted blocked when its net's transpose boundaries + twins land —+ files are generated artifacts, and the layout declaration always matches+ the execution the file was emitted for. * KV-caches are `POSITION_MAJOR`: `[K, 1, d]` positions appended per step (v1's decode-cache layout, kept and now declared instead of implicit).-* Layout is part of the pipeline cache key (§8.2). No runtime transpose- passes: a layout mismatch between producer and consumer is a converter- bug, caught by shape+layout inference at load.+* Layout is part of the pipeline cache key (§8.2). ## 4. Tensors and buffers
library/ml/src/main/rust/examples/emit_sampler_maml2.rs
diff --git a/library/ml/src/main/rust/examples/emit_sampler_maml2.rs b/library/ml/src/main/rust/examples/emit_sampler_maml2.rsindex ecb3f07128..961c36a9e3 100644--- a/library/ml/src/main/rust/examples/emit_sampler_maml2.rs+++ b/library/ml/src/main/rust/examples/emit_sampler_maml2.rs@@ -55,7 +55,7 @@ fn main() { &recorded, &tensors, weights.data(),- "supertonic-sampler ve fp16/int8 cb4 (Phase 1 pilot)",+ "supertonic-sampler ve fp16/int8 nchw (v2 pilot)", "maml2 emit_sampler_maml2", weights.source_sha256, )
library/ml/src/main/rust/src/maml2/emit.rs
diff --git a/library/ml/src/main/rust/src/maml2/emit.rs b/library/ml/src/main/rust/src/maml2/emit.rsindex f10789e41e..6bccdd17b9 100644--- a/library/ml/src/main/rust/src/maml2/emit.rs+++ b/library/ml/src/main/rust/src/maml2/emit.rs@@ -39,51 +39,17 @@ enum WeightQuant { }, } -/// Channel-blocked-4 repack of an fp16 NCHW plane.+/// Kernels are stored verbatim (NCHW), never repacked. ///-/// Groups channels in fours: `[c, h, w]` becomes `[(c + 3) / 4, h, w, 4]`-/// with zero padding in the final group. Element count grows to the padded-/// size; the loader's shape inference knows the logical shape from `dims`.-fn repack_channel_blocked_4(values: &[u16], c: u32, h: u32, w: u32) -> Vec<u16> {- let (c, h, w) = (c as usize, h as usize, w as usize);- let groups = c.div_ceil(4);- let mut out = vec![0u16; groups * h * w * 4];- for channel in 0..c {- let group = channel / 4;- let lane = channel % 4;- for row in 0..h {- for col in 0..w {- let src = (channel * h + row) * w + col;- let dst = ((group * h + row) * w + col) * 4 + lane;- out[dst] = values[src];- }- }- }- out-}--/// Channel-blocked-4 repack of an int8 kernel.-///-/// Same permutation as [`repack_channel_blocked_4`], over bytes. The-/// contraction axis the kernel reduces over is laid out so a channel group-/// of four is contiguous at every position.-fn repack_channel_blocked_4_u8(values: &[u8], c: u32, h: u32, w: u32) -> Vec<u8> {- let (c, h, w) = (c as usize, h as usize, w as usize);- let groups = c.div_ceil(4);- let mut out = vec![0u8; groups * h * w * 4];- for channel in 0..c {- let group = channel / 4;- let lane = channel % 4;- for row in 0..h {- for col in 0..w {- let src = (channel * h + row) * w + col;- let dst = ((group * h + row) * w + col) * 4 + lane;- out[dst] = values[src];- }- }- }- out-}+/// The channel-blocked twins (`Kind::ConvPointCb4Int8` and its successors)+/// read their kernel NCHW — only the activations are blocked — so the file+/// holds v1-order bytes and one stored layout serves every execution+/// layout. Repacking kernels would silently fork the host interpreter+/// (NCHW) from the device (blocked) with both sides self-consistent;+/// storing one layout keeps that class of bug inexpressible. (The pilot+/// stored blocked kernels, which made NCHW-kernel runs read permuted+/// weights on both sides and agree anyway; the repack pair was deleted+/// with that lesson.) /// The v2 tensor rows for one v1 weight tensor, in emission order. ///@@ -175,32 +141,23 @@ fn emit_weight_tensor( ) -> Result<(), String> { let (tensor, payload) = read_weight_payload(table, data, index)?; let mut dims = rank_hint.unwrap_or_else(|| logical_dims(&tensor));- // A `[c, 1, 1]` shorthand (per-channel vectors stored rank-3) repacks as- // `[c, 1, 1]`; a `[n]` vector repacks as `[n, 1, 1]`.+ // A `[c, 1, 1]` shorthand (per-channel vectors stored rank-3) stays+ // `[c, 1, 1]`; a `[n]` vector stays `[n, 1, 1]`. Padding is descriptive+ // only: stored bytes are verbatim either way. while dims.len() < 3 { dims.push(1); }- let (c, h, w) = (dims[0] as u32, dims[1] as u32, dims[2] as u32); match (payload, quant) { (WeightPayload::F16(words), WeightQuant::None) => {- let bytes: Vec<u8> = if dims.len() == 3- || (dims.len() == 4 && dims[2] == 1 && dims[3] == 1)- {- repack_channel_blocked_4(&words, c, h, w)- .iter()- .flat_map(|w| w.to_le_bytes())- .collect()- } else {- // Rank-4 spatial kernels stay in kernel order; the blocked- // lowering applies at dispatch, not to the stored bytes.- words.iter().flat_map(|w| w.to_le_bytes()).collect()- };+ // Verbatim NCHW: every kernel reads fp16 weights NCHW, so the+ // file holds v1-order bytes (see the module note on kernels).+ let bytes: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect(); let elems = words.len() as u64; out.push(EmittedTensor {- name: format!("w{index}.cb4"),+ name: format!("w{index}"), dims, dtype: fb::DType::F16,- layout: fb::Layout::CHANNEL_BLOCKED_4,+ layout: fb::Layout::NCHW, bytes, elems, quant: WeightQuant::None,@@ -210,17 +167,14 @@ fn emit_weight_tensor( return Err(format!("tensor {index} is fp16 but read as a quantised kernel")); } (WeightPayload::I8(bytes), WeightQuant::Int8 { .. }) => {- // Kernels arrive `[out, in]` (possibly `[out, in, 1, 1]`); block- // over the output rows: `[out/4, in, 4]`.- let rows = dims[0] as usize;- let cols: usize = dims[1..].iter().map(|&d| d as usize).product();- let blocked = repack_channel_blocked_4_u8(&bytes, rows as u32, 1, cols as u32);+ // Verbatim NCHW: the int8 twins read `channel * in_c + tap`+ // exactly as the NCHW kernel does — only activations block. out.push(EmittedTensor {- name: format!("w{index}.kernel.cb4"),+ name: format!("w{index}.kernel"), dims, dtype: fb::DType::I8,- layout: fb::Layout::CHANNEL_BLOCKED_4,- bytes: blocked,+ layout: fb::Layout::NCHW,+ bytes: bytes.clone(), elems: bytes.len() as u64, quant, });@@ -236,7 +190,7 @@ fn emit_weight_tensor( name: format!("w{index}.scale"), dims: scale_dims, dtype: fb::DType::F16,- layout: fb::Layout::CHANNEL_BLOCKED_4,+ layout: fb::Layout::NCHW, bytes: scale_bytes, elems: scale_words.len() as u64, quant: WeightQuant::None,@@ -464,7 +418,10 @@ fn emit_nodes( name: format!("t{id}"), dims: vec![shape.c as i32, shape.h as i32, shape.w as i32], dtype: fb::DType::F16,- layout: fb::Layout::CHANNEL_BLOCKED_4,+ // NCHW during the migration: the recording ran NCHW kernels, so+ // the arena the loader rebuilds is NCHW too, and the file+ // declares it. Re-emitted blocked when twins land.+ layout: fb::Layout::NCHW, bytes: Vec::new(), elems: shape.len() as u64, quant: WeightQuant::None,@@ -894,7 +851,7 @@ pub fn emit_sampler( name: format!("in{}", input.0), dims: vec![shape.c as i32, shape.h as i32, shape.w as i32], dtype: fb::DType::F16,- layout: fb::Layout::CHANNEL_BLOCKED_4,+ layout: fb::Layout::NCHW, bytes: Vec::new(), elems: shape.len() as u64, quant: WeightQuant::None,
library/ml/src/main/rust/src/maml2/infer.rs
diff --git a/library/ml/src/main/rust/src/maml2/infer.rs b/library/ml/src/main/rust/src/maml2/infer.rsindex c95497f39f..11e743de6d 100644--- a/library/ml/src/main/rust/src/maml2/infer.rs+++ b/library/ml/src/main/rust/src/maml2/infer.rs@@ -238,9 +238,13 @@ fn infer_node( shapes.get(&t).ok_or_else(|| err(&format!("tensor {t} has no shape"))) }; let attrs = attrs.ok_or_else(|| err("no attributes"))?;- // Computed tensors default to CHANNEL_BLOCKED_4 (spec 3.4); View keeps- // its source layout (zero-copy reinterpret).- let blocked = fb::Layout::CHANNEL_BLOCKED_4;+ // Computed tensors default to NCHW during the migration: every kernel+ // the loader can dispatch today addresses NCHW, so the arena is NCHW+ // and the file declares it. (Spec 3.4's CHANNEL_BLOCKED_4 default+ // describes the end state, when blocked twins + transpose boundaries+ // land and files are re-emitted.) View keeps its source layout+ // (zero-copy reinterpret).+ let computed_layout = fb::Layout::NCHW; match op { fb::Op::Conv => { if inputs.len() != 3 {@@ -268,7 +272,7 @@ fn infer_node( let out_h = conv_out(x[1], kh, sh, dh, pt * 2); let out_w = conv_out(x[2], kw, sw, dw, pl * 2); let _ = groups;- Ok(vec![Inferred { dims: vec![m, out_h, out_w], layout: blocked }])+ Ok(vec![Inferred { dims: vec![m, out_h, out_w], layout: computed_layout }]) } fb::Op::MatMul => { if inputs.len() != 4 && inputs.len() != 3 {@@ -280,7 +284,7 @@ fn infer_node( return Err(err("MatMul shapes are not [c, h, w] / [m, ...]")); } // Pointwise: `[m, 1, positions]`.- Ok(vec![Inferred { dims: vec![w[0], a[1], a[2]], layout: blocked }])+ Ok(vec![Inferred { dims: vec![w[0], a[1], a[2]], layout: computed_layout }]) } fb::Op::Add | fb::Op::Mul => { if inputs.len() != 2 {@@ -291,7 +295,7 @@ fn infer_node( if a != b { return Err(err(&format!("binary shape mismatch {a:?} vs {b:?}"))); }- Ok(vec![Inferred { dims: a, layout: blocked }])+ Ok(vec![Inferred { dims: a, layout: computed_layout }]) } fb::Op::AddBroadcast | fb::Op::MulBroadcast => { if inputs.len() != 2 {@@ -302,14 +306,14 @@ fn infer_node( if b.len() != 3 || b[1] != 1 || b[2] != 1 || b[0] != a[0] { return Err(err(&format!("broadcast {b:?} is not [c, 1, 1] over {a:?}"))); }- Ok(vec![Inferred { dims: a, layout: blocked }])+ Ok(vec![Inferred { dims: a, layout: computed_layout }]) } fb::Op::LayerNorm | fb::Op::RmsNorm => { if inputs.is_empty() { return Err(err("norm wants [x, ...]")); } let x = shape_of(inputs[0])?.dims.clone();- Ok(vec![Inferred { dims: x, layout: blocked }])+ Ok(vec![Inferred { dims: x, layout: computed_layout }]) } fb::Op::Attention => { // Two phases share one op: phase 0 scores (q, k -> map), phase 1@@ -325,7 +329,7 @@ fn infer_node( if q.len() != 3 || k.len() != 3 { return Err(err("Attention shapes are not sequences")); }- Ok(vec![Inferred { dims: vec![heads, q[2], k[2]], layout: blocked }])+ Ok(vec![Inferred { dims: vec![heads, q[2], k[2]], layout: computed_layout }]) } else { if inputs.len() != 2 { return Err(err("Attention apply wants [probs, v]"));@@ -340,7 +344,7 @@ fn infer_node( // value width scaled to query heads (GQA: kv_heads <= heads). let kv_heads = attrs.opt_int("kv_heads")?.unwrap_or(heads); let head_dim = v[0] / kv_heads.max(1);- Ok(vec![Inferred { dims: vec![heads * head_dim, 1, probs[1]], layout: blocked }])+ Ok(vec![Inferred { dims: vec![heads * head_dim, 1, probs[1]], layout: computed_layout }]) } } fb::Op::Softmax => {@@ -348,14 +352,14 @@ fn infer_node( return Err(err("Softmax wants [x]")); } let x = shape_of(inputs[0])?.dims.clone();- Ok(vec![Inferred { dims: x, layout: blocked }])+ Ok(vec![Inferred { dims: x, layout: computed_layout }]) } fb::Op::RotaryEmbedding => { if inputs.len() != 2 { return Err(err("RotaryEmbedding wants [x, angles]")); } let x = shape_of(inputs[0])?.dims.clone();- Ok(vec![Inferred { dims: x, layout: blocked }])+ Ok(vec![Inferred { dims: x, layout: computed_layout }]) } fb::Op::View => { if inputs.len() != 1 {
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 e2225054dc..e14de7dbe8 100644--- a/library/ml/src/main/rust/src/maml2/lower.rs+++ b/library/ml/src/main/rust/src/maml2/lower.rs@@ -265,18 +265,18 @@ impl<'a> NodeAttrs<'a> { /// indices the nodes name; `shapes` supplies the graph-input shapes. /// /// Blocked-kernel selection happens here, after emission, unless `nchw_only`-/// is set: nodes whose input, weight, and output layouts are all+/// is set: nodes whose activation input and output are both /// `CHANNEL_BLOCKED_4` have their tiled int8 dispatches rewritten to the-/// blocked twin ([`Kind::ConvPointCb4Int8`]). Routing stays shape-driven in+/// blocked twin ([`Kind::ConvPointCb4Int8`]). Kernels are always NCHW in the+/// file — the twin reads its kernel NCHW and only its activations blocked —+/// so the kernel layout needs no check here. 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.+/// `nchw_only` forces the rewrite off. While every emitted file is all-NCHW+/// the two paths lower identically (the rewrite qualifies nothing); once+/// transpose boundaries + blocked twins land per net, `lower` runs the mixed+/// plan and `lower_nchw` stays the all-NCHW proof path. pub fn lower( verified: &Verified<'_>, inferred: &InferredGraph,
library/ml/src/main/rust/src/maml2/parity.rs
diff --git a/library/ml/src/main/rust/src/maml2/parity.rs b/library/ml/src/main/rust/src/maml2/parity.rsindex f1938fb0a8..206c84a641 100644--- a/library/ml/src/main/rust/src/maml2/parity.rs+++ b/library/ml/src/main/rust/src/maml2/parity.rs@@ -140,3 +140,73 @@ fn lowered_plan_schedules_like_v1() { v1plan.ops.len() ); }++/// True numeric parity: the v2-lowered plan against the v1 plan, same+/// interpreter, same invented inputs, real weights both sides.+///+/// Both plans run through `run_multi` on their own blob (v1 data section vs+/// bridge blob) — different address spaces, same values, since kernels are+/// NCHW in both files. The arithmetic is identical kind-for-kind (the+/// blocked rewrite qualifies nothing on an all-NCHW file), so the outputs+/// must be bit-exact, not within tolerance: any divergence is a loader bug+/// (wrong offset, dropped res/shift, permuted kernel), never rounding.+/// Skips quietly when either asset is absent.+#[test]+fn v2_plan_matches_v1_bit_exact() {+ let Some((v1data, tensors)) = v1_table() else {+ return;+ };+ let source = crate::nets::tests::Shapes::new(tensors.len());+ let v1plan = supertonic_sampler::build(&source, 49, 55).expect("build v1");+ let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))+ .ancestors()+ .nth(4)+ .expect("workspace root")+ .to_path_buf();+ let path = root.join("speech/src/main/assets/supertonic/supertonic_ve.maml2");+ let bytes = match std::fs::read(&path) {+ Ok(bytes) => bytes,+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => return,+ Err(e) => panic!("cannot read {}: {e}", path.display()),+ };+ let verified = verify::verify(&bytes).expect("verify");+ let inferred = infer::infer(&verified).expect("infer");+ let bridge = lower::V2Weights::new(&verified).expect("bridge");+ let plan = lower::lower(&verified, &inferred[0], &bridge, 0).expect("lower");+ // Same invented inputs both sides: the seven sampler inputs at the+ // recorded shape, distinct and asymmetric about zero.+ let shapes = [+ (144usize, 1usize, 49usize),+ (256, 1, 55),+ (1024, 1, 50),+ (256, 1, 50),+ (2048, 1, 1),+ (64, 1, 49),+ (64, 1, 55),+ ];+ let inputs: Vec<Vec<f32>> = shapes+ .iter()+ .enumerate()+ .map(|(k, (c, h, w))| {+ (0..c * h * w)+ .map(|i| (i as f32 * 0.7 + k as f32 * 1.7).sin() * 0.8 + 0.1)+ .collect()+ })+ .collect();+ let refs: Vec<&[f32]> = inputs.iter().map(|v| v.as_slice()).collect();+ let v1out = crate::nets::reference::run_multi(&v1plan, &v1data, &refs).expect("run v1");+ let v2out = crate::nets::reference::run_multi(&plan, &bridge.blob(), &refs).expect("run v2");+ // The zero oracle: invented inputs through 212 real-weight ops cannot be+ // zero; an all-zeros output means the inputs never reached the graph.+ assert!(+ v1out.iter().flat_map(|v| v.iter()).any(|&v| v != 0.0),+ "the v1 interpreter output is all zeros"+ );+ assert_eq!(v2out.len(), v1out.len(), "same output count");+ for (index, (a, b)) in v1out.iter().zip(v2out.iter()).enumerate() {+ assert_eq!(a.len(), b.len(), "output {index} length");+ for (at, (x, y)) in a.iter().zip(b.iter()).enumerate() {+ assert!(x == y, "output {index} element {at}: v1 {x} vs v2 {y}");+ }+ }+}
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.rsindex cb0f6bde3c..17a6f1bf1b 100644--- a/library/ml/src/main/rust/src/vulkan/parity_maml2.rs+++ b/library/ml/src/main/rust/src/vulkan/parity_maml2.rs@@ -1,4 +1,4 @@-// The v2 sampler on the device (NCHW-first), behind the v1 bridge.+// The v2 sampler on the device, through the v2 bridge. // // `#[ignore]`: needs a Vulkan device and the v1 + v2 sampler assets. //@@ -8,11 +8,11 @@ // /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.)+// Runs the v2 plan (verify → infer → `lower_nchw`) on the device against+// the bridge blob, and requires it to agree with the CPU reference+// interpreter. Kernels are NCHW in the file, so the NCHW kernels both sides+// run read true values and the agreement is numeric truth, not two sides+// misreading one repack identically. // // This is the pilot exit's device half: file → device execution plus the // schedule-driven recorder, on real weights, with the interpreter as oracle.