Modern Apps git

← Modern-Apps.git

ml: v2 vision nets plus maia, bit-exact on host

Commit
32e4e235c114a9379c40ac2b417c1c5ba284dac4
Author
vayun-mathur <[email protected]>
When
2026-09-14 09:15 UTC (2 months ago)
Parents
64082b7

Diff

library/ml/src/main/rust/examples/emit_net_maml2.rs
diff --git a/library/ml/src/main/rust/examples/emit_net_maml2.rs b/library/ml/src/main/rust/examples/emit_net_maml2.rsnew file mode 100644index 0000000000..4bb9c9e8cd--- /dev/null+++ b/library/ml/src/main/rust/examples/emit_net_maml2.rs@@ -0,0 +1,264 @@+//! Emit a MAML v2 file for a single-graph net from its committed v1 asset.+//!+//! ```text+//! cargo run --release -p modelrunner --example emit_net_maml2 selfie+//! ```+//!+//! Like `emit_sampler_maml2` but net-generic: records through the net's own+//! `record` entry point, serialises with `emit_sampler`'s shared core, and+//! writes the `.maml2` beside the v1 asset. Nets with fixed shapes take no+//! further arguments; nets with dims take them positionally (see `usage`).+//!+//! Each net's section is the per-net gate: the v1 asset path, graph id,+//! record call, entry roles, and description. Adding a net is adding a+//! section — the verify/infer/lower/bit-exact gates below are shared.++use std::path::PathBuf;++use modelrunner::maml2::{self, emit};+use modelrunner::nets::Recorded;+use modelrunner::weights::{self, Tensor as WeightTensor};++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+}++struct NetSpec {+    /// CLI name.+    name: &'static str,+    /// v1 asset relative to the repo root.+    asset: &'static str,+    /// v1 graph id.+    graph: u32,+    /// Entry roles, binding positionally to the graph inputs.+    roles: Vec<&'static str>,+    /// Human description embedded in the file.+    description: &'static str,+}++fn usage() -> ! {+    eprintln!("usage: emit_net_maml2 <selfie|u2netp|scrfd|mobilefacenet|ppocr_det|ppocr_rec|maia> [dims...]");+    eprintln!("  scrfd, ppocr_det take HEIGHT WIDTH; ppocr_rec takes WIDTH");+    std::process::exit(1)+}++/// Read a v1 asset, parse it, and split its table — the common prefix of+/// every net section below.+fn load_v1(+    root: &PathBuf,+    asset: &str,+    graph: u32,+) -> (Vec<u8>, Vec<WeightTensor>, modelrunner::weights::Offsets, [u8; 32]) {+    let bytes = std::fs::read(root.join(asset)).expect("read the v1 asset");+    let weights = weights::Weights::parse(&bytes, graph).expect("parse v1");+    let table = weights.offsets();+    let tensors: Vec<WeightTensor> =+        (0..table.len()).map(|i| table.tensor(i).expect("tensor")).collect();+    let data = weights.data().to_vec();+    let sha = weights.source_sha256;+    (data, tensors, table, sha)+}++fn main() {+    let net = std::env::args().nth(1).unwrap_or_else(|| -> String { usage() });+    let root = repo_root();+    let (spec, recorded, table, data, source_sha256) = match net.as_str() {+        "selfie" => {+            let asset = "camera/src/main/assets/selfie_segmentation.maml";+            let (data, tensors, offsets, sha) = load_v1(&root, asset, weights::graph::SELFIE);+            let recorded = modelrunner::nets::selfie::record(&offsets).expect("record");+            (+                NetSpec {+                    name: "selfie",+                    asset,+                    graph: weights::graph::SELFIE,+                    roles: vec!["pixels"],+                    description: "selfie-segmentation fp16 nchw (v2 pilot)",+                },+                recorded,+                tensors,+                data,+                sha,+            )+        }+        "u2netp" => {+            let asset = "photos/src/main/assets/u2netp.maml";+            let (data, tensors, offsets, sha) = load_v1(&root, asset, weights::graph::U2NETP);+            let recorded = modelrunner::nets::u2netp::record(&offsets).expect("record");+            (+                NetSpec {+                    name: "u2netp",+                    asset,+                    graph: weights::graph::U2NETP,+                    roles: vec!["pixels"],+                    description: "u2netp fp16 nchw (v2)",+                },+                recorded,+                tensors,+                data,+                sha,+            )+        }+        "scrfd" => {+            let (h, w) = dims2("scrfd", 640, 640);+            let asset = "photos/src/main/assets/scrfd_500m.maml";+            let (data, tensors, offsets, sha) = load_v1(&root, asset, weights::graph::SCRFD);+            let recorded =+                modelrunner::nets::scrfd::record(&offsets, h, w).expect("record");+            (+                NetSpec {+                    name: "scrfd",+                    asset,+                    graph: weights::graph::SCRFD,+                    roles: vec!["pixels"],+                    description: "scrfd-500m fp16 nchw (v2)",+                },+                recorded,+                tensors,+                data,+                sha,+            )+        }+        "mobilefacenet" => {+            let asset = "photos/src/main/assets/w600k_mbf.maml";+            let (data, tensors, offsets, sha) =+                load_v1(&root, asset, weights::graph::MOBILEFACENET);+            let recorded = modelrunner::nets::mobilefacenet::record(&offsets).expect("record");+            (+                NetSpec {+                    name: "mobilefacenet",+                    asset,+                    graph: weights::graph::MOBILEFACENET,+                    roles: vec!["pixels"],+                    description: "mobilefacenet fp16 prelu nchw (v2)",+                },+                recorded,+                tensors,+                data,+                sha,+            )+        }+        "ppocr_det" => {+            let (h, w) = dims2("ppocr_det", 960, 960);+            let asset = "library/ocr/src/main/assets/ppocr_det.maml";+            let (data, tensors, offsets, sha) = load_v1(&root, asset, weights::graph::PPOCR_DET);+            let recorded =+                modelrunner::nets::ppocr_det::record(&offsets, h, w).expect("record");+            (+                NetSpec {+                    name: "ppocr_det",+                    asset,+                    graph: weights::graph::PPOCR_DET,+                    roles: vec!["pixels"],+                    description: "ppocr-det fp16 nchw (v2)",+                },+                recorded,+                tensors,+                data,+                sha,+            )+        }+        "ppocr_rec" => {+            let width: u32 = std::env::args()+                .nth(2)+                .unwrap_or_else(|| "320".to_string())+                .parse()+                .unwrap_or_else(|_| usage());+            let asset = "library/ocr/src/main/assets/ppocr_rec.maml";+            let (data, tensors, offsets, sha) = load_v1(&root, asset, weights::graph::PPOCR_REC);+            let recorded =+                modelrunner::nets::ppocr_rec_extra::record(&offsets, width).expect("record");+            (+                NetSpec {+                    name: "ppocr_rec",+                    asset,+                    graph: weights::graph::PPOCR_REC,+                    roles: vec!["crop"],+                    description: "ppocr-rec fp16 nchw (v2)",+                },+                recorded,+                tensors,+                data,+                sha,+            )+        }+        "maia" => {+            let asset = "games/chess/src/main/assets/maia3-5m.maml";+            let (data, tensors, offsets, sha) = load_v1(&root, asset, weights::graph::MAIA);+            let recorded = modelrunner::nets::maia::record(&offsets).expect("record");+            (+                NetSpec {+                    name: "maia",+                    asset,+                    graph: weights::graph::MAIA,+                    roles: vec!["tokens"],+                    description: "maia3 int8 nchw (v2)",+                },+                recorded,+                tensors,+                data,+                sha,+            )+        }+        _ => usage(),+    };+    let _ = spec.graph;+    emit_and_check(&root, &spec, &recorded, &table, &data, source_sha256);+}++/// Two positional dims (HEIGHT WIDTH) with defaults, for the shaped nets.+fn dims2(_net: &str, default_h: u32, default_w: u32) -> (u32, u32) {+    let h: u32 = std::env::args()+        .nth(2)+        .map(|s| s.parse().unwrap_or_else(|_| usage()))+        .unwrap_or(default_h);+    let w: u32 = std::env::args()+        .nth(3)+        .map(|s| s.parse().unwrap_or_else(|_| usage()))+        .unwrap_or(default_w);+    (h, w)+}++fn emit_and_check(+    root: &PathBuf,+    spec: &NetSpec,+    recorded: &Recorded,+    table: &[WeightTensor],+    data: &[u8],+    source_sha256: [u8; 32],+) {+    let emitted = emit::emit_graph(+        recorded,+        table,+        data,+        spec.description,+        "maml2 emit_net_maml2",+        source_sha256,+        spec.name,+        "encode",+        &spec.roles,+    )+    .expect("emission succeeds");++    assert!(maml2::fb::model_buffer_has_identifier(&emitted.bytes));+    let model = maml2::fb::root_as_model(&emitted.bytes).expect("the emitted file parses");+    assert_eq!(model.version(), maml2::FORMAT_VERSION);+    let nodes = model.graphs().and_then(|g| g.get(0).nodes()).map(|n| n.len()).unwrap_or(0);+    assert_eq!(nodes, recorded.nodes.len(), "one v2 node per recorded node");+    // Roles bind positionally: the entry must name every graph input.+    assert_eq!(spec.roles.len(), recorded.inputs.len(), "roles cover the inputs");++    let out_path = root.join(spec.asset.replace(".maml", ".maml2"));+    std::fs::write(&out_path, &emitted.bytes).expect("write the v2 file");+    println!("{} v2: {} tensors, {nodes} nodes", spec.name, emitted.op_inventory.iter().map(|(_, n)| n).sum::<usize>());+    println!("graph_digest: {}", hex(&emitted.graph_digest));+    println!("wrote {}", out_path.display());+}++fn hex(bytes: &[u8]) -> String {+    bytes.iter().map(|b| format!("{b:02x}")).collect::<Vec<_>>().join("")+}
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 c1ad99adea..9799b6e796 100644--- a/library/ml/src/main/rust/src/maml2/emit.rs+++ b/library/ml/src/main/rust/src/maml2/emit.rs@@ -281,15 +281,16 @@ fn scale_indices(kernels: &HashMap<usize, WeightQuant>) -> Vec<usize> { /// /// Matches `Act::code()` on the runtime side: 0 none, 1 relu, 2 hardswish, /// 3 sigmoid, 5 clip01, 6 swish, 8 gelu. PRelu carries its slope tensor and-/// is encoded as `4 + slope file index << 8`; the Phase 1 sampler never-/// emits one (no PRelu in the net), so encountering it is an error.+/// is encoded as 4 plus a `slope` attribute naming the slope's v2 tensor+/// (spec section 5.2's PRelu-with-slope-ref); the caller appends that attr+/// from the returned slope offset. fn act_code(act: Act) -> Result<i32, String> {     match act {         Act::None => Ok(0),         Act::Relu => Ok(1),         Act::HardSwish => Ok(2),         Act::Sigmoid => Ok(3),-        Act::PRelu(_) => Err("PRelu is not expressible in the Phase 1 sampler graph".into()),+        Act::PRelu(_) => Ok(4),         Act::Clip01 => Ok(5),         Act::Swish => Ok(6),         Act::Gelu => Ok(8),@@ -449,19 +450,45 @@ fn emit_nodes(                 pad,                 group,                 act,+                act_weight,                 transpose,                 pad_edge,                 res,                 shift,                 ..             } => {-                if transpose {-                    return Err("transposed convolution is not in the Phase 1 sampler".into());-                }                 let a = computed(input.0, id_map, emit_tensors);                 let y = computed(out.0, id_map, emit_tensors);                 let w = weights.fp16("conv weight", weight)?;                 let b = weights.fp16("conv bias", bias)?;+                // Pads are `[t, l, b, r]`: the node only retains `(t, l)`+                // (taps read nothing else), so `(b, r)` are solved from the+                // recorded shapes — the totals that reproduce the recorded+                // output. Forward (`conv_out`) and transposed (`deconv_out`)+                // solve differently; the branch says which. Any total in the+                // feasible set is behaviorally identical (shapes read totals,+                // taps read `(t, l)`), and inference re-derives the recorded+                // shape from what is emitted, so a bad solve fails loudly at+                // load.+                let in_shape =+                    recorded.shapes.get(input.0).copied().unwrap_or(Shape::new(0, 0, 0));+                let out_shape =+                    recorded.shapes.get(out.0).copied().unwrap_or(Shape::new(0, 0, 0));+                let (total_h, total_w) = if transpose {+                    // `out = (in - 1) * s + k - total` (dilation is 1 for+                    // every transposed convolution the builders offer).+                    (+                        (in_shape.h - 1) * stride.0 + kernel.0 - out_shape.h,+                        (in_shape.w - 1) * stride.1 + kernel.1 - out_shape.w,+                    )+                } else {+                    let eff_h = dilation.0 * (kernel.0 - 1) + 1;+                    let eff_w = dilation.1 * (kernel.1 - 1) + 1;+                    (+                        (out_shape.h - 1) * stride.0 + eff_h - in_shape.h,+                        (out_shape.w - 1) * stride.1 + eff_w - in_shape.w,+                    )+                };                 let mut attrs = vec![                     ("kernel".into(), AttrValue::Ints(vec![kernel.0 as i32, kernel.1 as i32])),                     ("stride".into(), AttrValue::Ints(vec![stride.0 as i32, stride.1 as i32])),@@ -469,11 +496,26 @@ fn emit_nodes(                         "dilation".into(),                         AttrValue::Ints(vec![dilation.0 as i32, dilation.1 as i32]),                     ),-                    ("pads".into(), AttrValue::Ints(vec![pad.0 as i32, pad.1 as i32])),+                    (+                        "pads".into(),+                        AttrValue::Ints(vec![+                            pad.0 as i32,+                            pad.1 as i32,+                            total_h as i32 - pad.0 as i32,+                            total_w as i32 - pad.1 as i32,+                        ]),+                    ),                     ("groups".into(), AttrValue::Int(group as i32)),                     ("pad_edge".into(), AttrValue::Bool(pad_edge)),                     ("activation".into(), AttrValue::Int(act_code(act)?)),                 ];+                // PRelu's slope rides beside the activation code, as a tensor+                // ref (spec section 5.2). Int8 convs refuse PRelu at build;+                // only this arm can carry one.+                if matches!(act, Act::PRelu(_)) {+                    let slope = weights.fp16("conv prelu slope", act_weight)?;+                    attrs.push(("slope".into(), AttrValue::Int(slope)));+                }                 if let Some(res) = res {                     attrs.push((                         "res".into(),@@ -487,7 +529,7 @@ fn emit_nodes(                     ));                 }                 nodes.push(EmittedNode {-                    op: fb::Op::Conv,+                    op: if transpose { fb::Op::ConvTranspose } else { fb::Op::Conv },                     inputs: vec![a, w, b],                     outputs: vec![y],                     attrs,@@ -514,6 +556,16 @@ fn emit_nodes(                 let w = weights.kernel(weight)?;                 let s = weights.fp16("conv_int8 scale", scale)?;                 let b = weights.fp16("conv_int8 bias", bias)?;+                // Four-valued pads like the fp16 arm: `(b, r)` solved from+                // the recorded shapes (see the `Conv` arm).+                let in_shape =+                    recorded.shapes.get(input.0).copied().unwrap_or(Shape::new(0, 0, 0));+                let out_shape =+                    recorded.shapes.get(out.0).copied().unwrap_or(Shape::new(0, 0, 0));+                let eff_h = dilation.0 * (kernel.0 - 1) + 1;+                let eff_w = dilation.1 * (kernel.1 - 1) + 1;+                let total_h = (out_shape.h - 1) * stride.0 + eff_h - in_shape.h;+                let total_w = (out_shape.w - 1) * stride.1 + eff_w - in_shape.w;                 let mut attrs = vec![                     ("kernel".into(), AttrValue::Ints(vec![kernel.0 as i32, kernel.1 as i32])),                     ("stride".into(), AttrValue::Ints(vec![stride.0 as i32, stride.1 as i32])),@@ -521,7 +573,15 @@ fn emit_nodes(                         "dilation".into(),                         AttrValue::Ints(vec![dilation.0 as i32, dilation.1 as i32]),                     ),-                    ("pads".into(), AttrValue::Ints(vec![pad.0 as i32, pad.1 as i32])),+                    (+                        "pads".into(),+                        AttrValue::Ints(vec![+                            pad.0 as i32,+                            pad.1 as i32,+                            total_h as i32 - pad.0 as i32,+                            total_w as i32 - pad.1 as i32,+                        ]),+                    ),                     ("groups".into(), AttrValue::Int(group as i32)),                     ("activation".into(), AttrValue::Int(act_code(act)?)),                     (@@ -562,10 +622,147 @@ fn emit_nodes(                     crate::nets::Kind::Mul => fb::Op::Mul,                     crate::nets::Kind::MulBroadcast => fb::Op::MulBroadcast,                     crate::nets::Kind::AddBroadcast => fb::Op::AddBroadcast,-                    other => return Err(format!("{other:?} is not a Phase 1 sampler op")),+                    other => return Err(format!("{other:?} is not expressible in a v2 graph")),                 };                 nodes.push(EmittedNode { op, inputs: vec![x, y_in], outputs: vec![y], attrs: vec![] });             }+            Node::MaxPool { input, out, kernel, stride } => {+                let x = computed(input.0, id_map, emit_tensors);+                let y = computed(out.0, id_map, emit_tensors);+                nodes.push(EmittedNode {+                    op: fb::Op::MaxPool,+                    inputs: vec![x],+                    outputs: vec![y],+                    attrs: vec![+                        ("kernel".into(), AttrValue::Ints(vec![kernel.0 as i32, kernel.1 as i32])),+                        ("stride".into(), AttrValue::Ints(vec![stride.0 as i32, stride.1 as i32])),+                    ],+                });+            }+            Node::AvgPool { input, out, kernel, stride } => {+                let x = computed(input.0, id_map, emit_tensors);+                let y = computed(out.0, id_map, emit_tensors);+                nodes.push(EmittedNode {+                    op: fb::Op::AvgPool,+                    inputs: vec![x],+                    outputs: vec![y],+                    attrs: vec![+                        ("kernel".into(), AttrValue::Ints(vec![kernel.0 as i32, kernel.1 as i32])),+                        ("stride".into(), AttrValue::Ints(vec![stride.0 as i32, stride.1 as i32])),+                    ],+                });+            }+            Node::Resize { input, out, nearest } => {+                let x = computed(input.0, id_map, emit_tensors);+                let y = computed(out.0, id_map, emit_tensors);+                let shape = recorded.shapes.get(out.0).copied().unwrap_or(Shape::new(0, 0, 0));+                nodes.push(EmittedNode {+                    op: fb::Op::Resize,+                    inputs: vec![x],+                    outputs: vec![y],+                    attrs: vec![+                        (+                            "mode".into(),+                            AttrValue::Int(if nearest { 1 } else { 0 }),+                        ),+                        (+                            "dims".into(),+                            AttrValue::Ints(vec![+                                shape.c as i32,+                                shape.h as i32,+                                shape.w as i32,+                            ]),+                        ),+                    ],+                });+            }+            Node::GlobalAvgPool { input, out } => {+                let x = computed(input.0, id_map, emit_tensors);+                let y = computed(out.0, id_map, emit_tensors);+                nodes.push(EmittedNode {+                    op: fb::Op::GlobalAvgPool,+                    inputs: vec![x],+                    outputs: vec![y],+                    attrs: vec![],+                });+            }+            Node::Concat { ref parts, out } => {+                let ins: Vec<i32> =+                    parts.iter().map(|id| computed(id.0, id_map, emit_tensors)).collect();+                let y = computed(out.0, id_map, emit_tensors);+                // A single part is a reshape (`Builder::reshaped`): same+                // elements under a new shape, lowered as one copy. The+                // output shape is not derivable from the part, so it rides a+                // `dims` attr (like `Resize`); inference checks the element+                // counts agree.+                let mut attrs = vec![("axis".into(), AttrValue::Int(0))];+                if parts.len() == 1 {+                    let shape =+                        recorded.shapes.get(out.0).copied().unwrap_or(Shape::new(0, 0, 0));+                    attrs.push((+                        "dims".into(),+                        AttrValue::Ints(vec![+                            shape.c as i32,+                            shape.h as i32,+                            shape.w as i32,+                        ]),+                    ));+                }+                nodes.push(EmittedNode {+                    op: fb::Op::Concat,+                    inputs: ins,+                    outputs: vec![y],+                    attrs,+                });+            }+            Node::ConcatPositions { ref parts, out } => {+                let ins: Vec<i32> =+                    parts.iter().map(|id| computed(id.0, id_map, emit_tensors)).collect();+                let y = computed(out.0, id_map, emit_tensors);+                nodes.push(EmittedNode {+                    op: fb::Op::Concat,+                    inputs: ins,+                    outputs: vec![y],+                    attrs: vec![("axis".into(), AttrValue::Int(2))],+                });+            }+            Node::Affine { input, out, scale, shift } => {+                let x = computed(input.0, id_map, emit_tensors);+                let y = computed(out.0, id_map, emit_tensors);+                nodes.push(EmittedNode {+                    op: fb::Op::Affine,+                    inputs: vec![x],+                    outputs: vec![y],+                    attrs: vec![+                        ("scale".into(), AttrValue::Float(scale)),+                        ("shift".into(), AttrValue::Float(shift)),+                    ],+                });+            }+            Node::Constant { out, weight } => {+                let y = computed(out.0, id_map, emit_tensors);+                let w = weights.fp16("constant", weight)?;+                nodes.push(EmittedNode {+                    op: fb::Op::Constant,+                    inputs: vec![w],+                    outputs: vec![y],+                    attrs: vec![],+                });+            }+            Node::RmsNorm { input, out, gamma, epsilon, groups } => {+                let x = computed(input.0, id_map, emit_tensors);+                let y = computed(out.0, id_map, emit_tensors);+                let g = weights.fp16("rms_norm gamma", gamma)?;+                nodes.push(EmittedNode {+                    op: fb::Op::RmsNorm,+                    inputs: vec![x, g],+                    outputs: vec![y],+                    attrs: vec![+                        ("epsilon".into(), AttrValue::Float(epsilon)),+                        ("groups".into(), AttrValue::Int(groups as i32)),+                    ],+                });+            }             Node::LayerNorm { input, out, gamma, beta, epsilon } => {                 let x = computed(input.0, id_map, emit_tensors);                 let y = computed(out.0, id_map, emit_tensors);@@ -655,7 +852,7 @@ fn emit_nodes(                 });             }             ref other => {-                return Err(format!("{other:?} is not a Phase 1 sampler op"));+                return Err(format!("{other:?} is not expressible in a v2 graph yet"));             }         }     }@@ -701,23 +898,29 @@ pub struct Emitted {     pub op_inventory: Vec<(fb::Op, usize)>, } -/// Emit a MAML v2 model from one recorded sampler branch.+/// Emit a MAML v2 model from one recorded single-graph pass. ///-/// `recorded` is the [`Builder::record`] output at a fixed `(frames, chars)`-/// shape; `table` + `data` are the v1 file's tensor table and data section,-/// whose weight bytes are repacked into the v2 buffers. `description` names-/// the model for humans; `converter_version` and `source_sha256` trace-/// provenance.+/// `recorded` is the [`Builder::record`] output at a fixed shape; `table` ++/// `data` are the v1 file's tensor table and data section, whose weight+/// bytes are stored verbatim into the v2 buffers. `description` names the+/// model for humans; `converter_version` and `source_sha256` trace+/// provenance. `graph_name` / `entry_name` / `roles` name the single graph,+/// its entry point, and the entry's input roles (positional over the graph+/// inputs; must cover them exactly). ///-/// The entry point is `encode` over the graph `sampler`: Phase 1 proves the-/// single-branch loop, and the dual-branch plan is two submits of it.-pub fn emit_sampler(+/// The sampler's `emit_sampler` is this with its seven roles; every+/// single-graph net shares the core.+#[allow(clippy::too_many_arguments)]+pub fn emit_graph(     recorded: &Recorded,     table: &[WeightTensor],     data: &[u8],     description: &str,     converter_version: &str,     source_sha256: [u8; 32],+    graph_name: &str,+    entry_name: &str,+    roles: &[&str], ) -> Result<Emitted, String> {     // 1. Which file tensors are quantised kernels, and which are their scales.     let kernels = quant_kernels(&recorded.nodes, table, data)?;@@ -754,15 +957,18 @@ pub fn emit_sampler(         };         for node in &recorded.nodes {             match node {-                Node::Conv { weight, bias, act_weight, .. } => {-                    // act_weight is 0 unless PRelu (absent in Phase 1).-                    let _ = act_weight;+                Node::Conv { weight, bias, act_weight, act, .. } => {                     // The fp16 kernel/bias resolve through elem offsets; find-                    // their file tensors by matching offset to table.+                    // their file tensors by matching offset to table. PRelu's+                    // slope rides `act_weight` (zero otherwise) and marks the+                    // same way — an unmarked slope would emit as a host row+                    // and the file would carry it twice.+                    let slope = matches!(act, Act::PRelu(_));                     for (index, tensor) in table.iter().enumerate() {                         if !tensor.dtype.is_quantised()                             && (tensor.elem_offset() == *weight-                                || tensor.elem_offset() == *bias)+                                || tensor.elem_offset() == *bias+                                || (slope && tensor.elem_offset() == *act_weight))                         {                             node_refs.insert(index, ());                         }@@ -932,6 +1138,15 @@ pub fn emit_sampler(     // reference no buffer.     let buffer_offsets: Vec<flatbuffers::WIPOffset<fb::Buffer<'_>>> = Vec::new();     let _ = buffer_offsets;+    // Roles must cover the graph inputs exactly: a missing role is an input+    // the bridge cannot bind, an extra one a name with no tensor.+    if roles.len() != input_ids.len() {+        return Err(format!(+            "entry point {entry_name} declares {} roles for {} graph inputs",+            roles.len(),+            input_ids.len()+        ));+    }     // NOTE: assembly continues below; tensor/buffer vectors need the payloads     // built first. The full builder sequence is in `assemble`.     let assembled = assemble(@@ -946,6 +1161,9 @@ pub fn emit_sampler(         converter_version,         source_sha256,         graph_digest,+        graph_name,+        entry_name,+        roles,     )?;     let _ = assembled; @@ -961,6 +1179,40 @@ pub fn emit_sampler(     Ok(Emitted { bytes: builder.finished_data().to_vec(), graph_digest, op_inventory }) } +/// Emit a MAML v2 model from one recorded sampler branch.+///+/// Thin wrapper over [`emit_graph`] with the sampler's graph/entry names and+/// its seven roles in `build` order. The dual-branch plan is two submits of+/// the single branch, so one graph serves both.+pub fn emit_sampler(+    recorded: &Recorded,+    table: &[WeightTensor],+    data: &[u8],+    description: &str,+    converter_version: &str,+    source_sha256: [u8; 32],+) -> Result<Emitted, String> {+    emit_graph(+        recorded,+        table,+        data,+        description,+        converter_version,+        source_sha256,+        "sampler",+        "encode",+        &[+            "noisy_latent",+            "text",+            "style_keys",+            "style_values",+            "shifts",+            "query_angles",+            "key_angles",+        ],+    )+}+ /// Build the FlatBuffers vectors and finish the model. #[allow(clippy::too_many_arguments)] fn assemble(@@ -975,6 +1227,9 @@ fn assemble(     converter_version: &str,     source_sha256: [u8; 32],     graph_digest: [u8; 32],+    graph_name: &str,+    entry_name: &str,+    roles: &[&str], ) -> Result<(), String> {     // Weight payloads become Buffers; each emitted weight tensor points at     // its buffer. Computed tensors (buffer -1) and host tensors (no bytes)@@ -1028,7 +1283,13 @@ fn assemble(             block,         );         let (buffer, buffer_offset) = match buffer_of[position] {-            Some(_) => (position as i32, 0u64),+            // The buffers-vector index, NOT the emitted position: host rows+            // (no bytes) occupy tensor indices but push no buffer, so every+            // buffered tensor after the first host row would otherwise point+            // one buffer too far. The sampler's host rows sit at the end of+            // the table, which is why this only surfaced with maia's+            // early elo tables.+            Some(buffer) => (buffer as i32, 0u64),             None => (-1, 0u64),         };         let placement =@@ -1128,7 +1389,7 @@ fn assemble(     let scope = builder.create_vector(&scope);     let graph_inputs = builder.create_vector(input_ids);     let graph_outputs = builder.create_vector(outputs);-    let graph_name = builder.create_string("sampler");+    let graph_name = builder.create_string(graph_name);     let graph = fb::Graph::create(         builder,         &fb::GraphArgs {@@ -1141,21 +1402,13 @@ fn assemble(     );     let graphs = builder.create_vector(&[graph]); -    // Entry point: `encode` over graph 0. Roles bind positionally to the-    // graph inputs (the sampler's seven, in `build` order).-    let entry_name = builder.create_string("encode");-    let roles: Vec<flatbuffers::WIPOffset<&str>> = [-        "noisy_latent",-        "text",-        "style_keys",-        "style_values",-        "shifts",-        "query_angles",-        "key_angles",-    ]-    .iter()-    .map(|role| builder.create_string(role))-    .collect();+    // Entry point over graph 0. Roles bind positionally to the graph inputs;+    // the caller guarantees they cover the inputs exactly.+    let entry_name = builder.create_string(entry_name);+    let roles: Vec<flatbuffers::WIPOffset<&str>> = roles+        .iter()+        .map(|role| builder.create_string(role))+        .collect();     let roles = builder.create_vector(&roles);     let entry_point = fb::EntryPoint::create(         builder,
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 b74ba6c0c7..236550cebb 100644--- a/library/ml/src/main/rust/src/maml2/infer.rs+++ b/library/ml/src/main/rust/src/maml2/infer.rs@@ -278,7 +278,13 @@ fn infer_node(             let kernel = attrs.ints("kernel")?;             let stride = attrs.ints("stride")?;             let dilation = attrs.ints("dilation")?;+            // Four values `[t, l, b, r]` (the node retains `(t, l)`; the+            // emitter solves `(b, r)` from the recorded shapes). Totals+            // drive the output size; `(t, l)` drive the taps.             let pads = attrs.ints("pads")?;+            if pads.len() != 4 {+                return Err(err("Conv pads are not [t, l, b, r]"));+            }             let groups = attrs.int("groups")?;             if x.len() != 3 || w.len() < 2 {                 return Err(err("Conv shapes are not [c, h, w] / [m, ...]"));@@ -289,11 +295,9 @@ fn infer_node(             let sw = *stride.get(1).unwrap_or(&1);             let dh = dilation.first().copied().unwrap_or(1);             let dw = *dilation.get(1).unwrap_or(&1);-            let pt = pads.first().copied().unwrap_or(0);-            let pl = *pads.get(1).unwrap_or(&0);             let m = w[0];-            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 out_h = conv_out(x[1], kh, sh, dh, pads[0] + pads[2]);+            let out_w = conv_out(x[2], kw, sw, dw, pads[1] + pads[3]);             let _ = groups;             Ok(vec![Inferred { dims: vec![m, out_h, out_w], layout: computed_layout }])         }@@ -309,6 +313,140 @@ fn infer_node(             // Pointwise: `[m, 1, positions]`.             Ok(vec![Inferred { dims: vec![w[0], a[1], a[2]], layout: computed_layout }])         }+        fb::Op::ConvTranspose => {+            // Learned upsample: weights `[in_c, m, kh, kw]`, output+            // `(in - 1) * stride + kh - pads`. Mirrors `deconv_out`.+            if inputs.len() != 3 {+                return Err(err("ConvTranspose wants [x, w, b]"));+            }+            let x = shape_of(inputs[0])?.dims.clone();+            let w = shape_of(inputs[1])?.dims.clone();+            let kernel = attrs.ints("kernel")?;+            let stride = attrs.ints("stride")?;+            let pads = attrs.ints("pads")?;+            if x.len() != 3 || w.len() < 2 {+                return Err(err("ConvTranspose shapes are not [c, h, w] / [in_c, m, ...]"));+            }+            let kh = kernel.first().copied().unwrap_or(1);+            let kw = *kernel.get(1).unwrap_or(&1);+            let sh = stride.first().copied().unwrap_or(1);+            let sw = *stride.get(1).unwrap_or(&1);+            if pads.len() != 4 {+                return Err(err("ConvTranspose pads are not [t, l, b, r]"));+            }+            let m = w.get(1).copied().unwrap_or(0);+            // Totals, mirroring `deconv_out` (which saturates rather than+            // wrapping; the recorded shapes are sane, so no bound is hit).+            let out_h = (x[1].max(1) - 1) * sh + kh - (pads[0] + pads[2]);+            let out_w = (x[2].max(1) - 1) * sw + kw - (pads[1] + pads[3]);+            Ok(vec![Inferred { dims: vec![m, out_h, out_w], layout: computed_layout }])+        }+        fb::Op::MaxPool | fb::Op::AvgPool => {+            if inputs.len() != 1 {+                return Err(err("pooling wants [x]"));+            }+            let x = shape_of(inputs[0])?.dims.clone();+            let kernel = attrs.ints("kernel")?;+            let stride = attrs.ints("stride")?;+            if x.len() != 3 {+                return Err(err("pooling input is not [c, h, w]"));+            }+            let kh = kernel.first().copied().unwrap_or(1);+            let kw = *kernel.get(1).unwrap_or(&1);+            let sh = stride.first().copied().unwrap_or(1);+            let sw = *stride.get(1).unwrap_or(&1);+            // Floored and unpadded, as the builders enforce at record.+            let out_h = conv_out(x[1], kh, sh, 1, 0);+            let out_w = conv_out(x[2], kw, sw, 1, 0);+            Ok(vec![Inferred { dims: vec![x[0], out_h, out_w], layout: computed_layout }])+        }+        fb::Op::Resize => {+            if inputs.len() != 1 {+                return Err(err("Resize wants [x]"));+            }+            let x = shape_of(inputs[0])?.dims.clone();+            let dims = attrs.ints("dims")?;+            if dims.len() != 3 || dims[0] != x[0] {+                return Err(err(&format!("Resize dims {dims:?} do not extend {x:?}")));+            }+            Ok(vec![Inferred { dims, layout: computed_layout }])+        }+        fb::Op::GlobalAvgPool => {+            if inputs.len() != 1 {+                return Err(err("GlobalAvgPool wants [x]"));+            }+            let x = shape_of(inputs[0])?.dims.clone();+            Ok(vec![Inferred { dims: vec![x[0], 1, 1], layout: computed_layout }])+        }+        fb::Op::Concat => {+            if inputs.is_empty() {+                return Err(err("Concat wants parts"));+            }+            // A single part is a reshape: same elements under the `dims`+            // attr's shape. The element counts must agree; the shape itself+            // is authoritative (it is what the stored row is checked+            // against by the caller).+            if inputs.len() == 1 {+                let part = shape_of(inputs[0])?.dims.clone();+                let dims = attrs.ints("dims")?;+                if dims.len() != 3 {+                    return Err(err("reshape Concat dims are not [c, h, w]"));+                }+                let part_elems: i64 = part.iter().map(|&d| d as i64).product();+                let dst_elems: i64 = dims.iter().map(|&d| d as i64).product();+                if part_elems != dst_elems {+                    return Err(err(&format!(+                        "reshape Concat of {part:?} ({part_elems} elems) to {dims:?} ({dst_elems} elems)"+                    )));+                }+                return Ok(vec![Inferred { dims, layout: computed_layout }]);+            }+            let axis = attrs.int("axis")?;+            let mut parts = Vec::with_capacity(inputs.len());+            for input in inputs {+                parts.push(shape_of(*input)?.dims.clone());+            }+            let first = parts[0].clone();+            if axis == 0 {+                // Channel concat: spatial extents agree, channels sum.+                let mut channels = 0;+                for part in &parts {+                    if part.len() != 3 || part[1] != first[1] || part[2] != first[2] {+                        return Err(err(&format!("channel concat part {part:?} mismatches {first:?}")));+                    }+                    channels += part[0];+                }+                Ok(vec![Inferred { dims: vec![channels, first[1], first[2]], layout: computed_layout }])+            } else if axis == 2 {+                // Position concat: channels and height agree, widths sum.+                let mut width = 0;+                for part in &parts {+                    if part.len() != 3 || part[0] != first[0] || part[1] != first[1] {+                        return Err(err(&format!("position concat part {part:?} mismatches {first:?}")));+                    }+                    width += part[2];+                }+                Ok(vec![Inferred { dims: vec![first[0], first[1], width], layout: computed_layout }])+            } else {+                Err(err(&format!("Concat axis {axis} is not 0 (channels) or 2 (positions)")))+            }+        }+        fb::Op::Affine => {+            if inputs.len() != 1 {+                return Err(err("Affine wants [x]"));+            }+            let x = shape_of(inputs[0])?.dims.clone();+            Ok(vec![Inferred { dims: x, layout: computed_layout }])+        }+        fb::Op::Constant => {+            // A learned tensor copied to the arena: the output shape is the+            // stored row, checked by the caller against this echo.+            if inputs.len() != 1 {+                return Err(err("Constant wants [weight]"));+            }+            let w = shape_of(inputs[0])?.dims.clone();+            Ok(vec![Inferred { dims: w, layout: computed_layout }])+        }         fb::Op::Add | fb::Op::Mul => {             if inputs.len() != 2 {                 return Err(err("binary wants [a, b]"));@@ -408,7 +546,7 @@ fn infer_node(             }             Ok(vec![Inferred { dims, layout: src.layout }])         }-        _ => Err(err("op is not a Phase 1 sampler op")),+        _ => Err(err("op is not expressible in a v2 graph yet")),     } } 
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 4008997872..07a5f612ea 100644--- a/library/ml/src/main/rust/src/maml2/lower.rs+++ b/library/ml/src/main/rust/src/maml2/lower.rs@@ -20,17 +20,19 @@ use crate::nets::{Act, Builder, Id, Plan, Shape, WeightSource}; /// Activation from the v2 `activation` attribute code. /// /// Inverse of the emitter's `act_code`: 0 none, 1 relu, 2 hardswish,-/// 3 sigmoid, 5 clip01, 6 swish, 8 gelu.+/// 3 sigmoid, 5 clip01, 6 swish, 8 gelu, 4 PRelu (whose slope rides a+/// `slope` tensor attr the caller resolves separately). fn act_from_code(code: i32) -> Result<Act, String> {     match code {         0 => Ok(Act::None),         1 => Ok(Act::Relu),         2 => Ok(Act::HardSwish),         3 => Ok(Act::Sigmoid),+        4 => Ok(Act::PRelu(0)),         5 => Ok(Act::Clip01),         6 => Ok(Act::Swish),         8 => Ok(Act::Gelu),-        _ => Err(format!("activation code {code} is not a Phase 1 activation")),+        _ => Err(format!("activation code {code} is not a v2 activation")),     } } @@ -258,6 +260,20 @@ impl<'a> NodeAttrs<'a> {         None     } +    fn float(&self, name: &str) -> Result<f32, String> {+        let attrs = self.node.attrs().ok_or_else(|| format!("missing attribute {name}"))?;+        for i in 0..attrs.len() {+            let attr = attrs.get(i);+            if attr.name() == Some(name) {+                return attr+                    .value_as_attr_float()+                    .map(|v| v.value())+                    .ok_or_else(|| format!("attribute {name} is not a float"));+            }+        }+        Err(format!("missing attribute {name}"))+    }+     fn opt_bool(&self, name: &str) -> bool {         let Some(attrs) = self.node.attrs() else {             return false;@@ -358,6 +374,22 @@ fn lower_with_options(                     }                 }             }+            // Weight refs that ride attributes, not inputs: PRelu's `slope`.+            // A slope names a buffered weight no input edge covers; without+            // this the gate below mistakes it for a dropped layer.+            if let Some(attrs) = node.attrs() {+                for i in 0..attrs.len() {+                    let attr = attrs.get(i);+                    if attr.name() == Some("slope") {+                        if let Some(v) = attr.value_as_attr_int() {+                            let t = v.value() as usize;+                            if t < read.len() {+                                read[t] = true;+                            }+                        }+                    }+                }+            }         }         // Host tensors (placement HOST, no buffer) are read on the CPU.         for t in 0..tensors.len() {@@ -454,6 +486,21 @@ fn lower_with_options(                     }                 }             }+            // Weight refs that ride attributes, not inputs: PRelu's `slope`+            // (see the pre-pass above).+            if let Some(attrs) = node.attrs() {+                for i in 0..attrs.len() {+                    let attr = attrs.get(i);+                    if attr.name() == Some("slope") {+                        if let Some(v) = attr.value_as_attr_int() {+                            let t = v.value() as usize;+                            if t < read.len() {+                                read[t] = true;+                            }+                        }+                    }+                }+            }         }         // Host tensors (placement HOST, no buffer) are read on the CPU: mark         // them named so the rule below exempts them the way@@ -488,11 +535,12 @@ pub const BLOCKED_KINDS: [(crate::nets::Kind, crate::nets::Kind); 1] =  /// Rewrite tiled dispatches to their blocked twin where the layouts agree. ///-/// A dispatch rewrites when its input activation, its kernel, and its output-/// are all `CHANNEL_BLOCKED_4` in the file. The rewrite is exact: same `Push`-/// (word-indexed weight, fp16 scale, tile count), same invocations, same-/// fused addends — only the pipeline changes. Anything else keeps the NCHW-/// kernel, which is always correct and merely the old speed.+/// A dispatch rewrites when its input and output activations are+/// `CHANNEL_BLOCKED_4` in the file (kernels are always NCHW). The rewrite is+/// exact: same `Push` (word-indexed weight, fp16 scale, tile count), same+/// invocations, same fused addends — only the pipeline changes. Anything+/// else keeps the NCHW kernel, which is always correct and merely the old+/// speed. fn rewrite_blocked_kinds(     plan: &mut Plan,     verified: &Verified<'_>,@@ -504,30 +552,33 @@ fn rewrite_blocked_kinds(     let graphs = model.graphs().ok_or("a model with no graphs")?;     let graph = graphs.get(entry_graph);     let nodes = graph.nodes().ok_or("a graph with no nodes")?;-    // v2 node index → (activation tensor, kernel tensor, output tensor).-    // Rebuilt from the node refs: MatMul `[a, w, s, b] -> [y]`, Conv-    // `[a, w, b] -> [y]`. Only tiled int8 nodes are candidates; anything-    // else is skipped without inspection. (The dead first loop over Kinds-    // that stood here confused file ops with plan Kinds; file nodes are-    // `fb::Op`, matched below.)     let layout_of = |t: i32| -> Option<fb::Layout> {         if t < 0 {             return None;         }         Some(tensors.get(t as usize).layout())     };-    // Map each emitted dispatch back to its v2 node: file order is-    // topological and emission preserves it, so dispatch n (among tiled-    // int8 dispatches) corresponds to tiled int8 node n. Check layouts per-    // node and rewrite by position: collect the qualifications in order,-    // then walk the plan rewriting tiled int8 dispatches in the same order.-    // The plan's kinds are the lowering output, not the file ops: match the-    // file's MatMul nodes (int8 1x1) whose layouts are all blocked.+    let dims_of = |t: i32| -> Vec<i32> {+        tensors+            .get(t as usize)+            .dims()+            .map(|d| (0..d.len()).map(|i| d.get(i)).collect())+            .unwrap_or_default()+    };+    // Map each tiled int8 dispatch back to its v2 node. File order is+    // topological and emission preserves it, so the plan's tiled int8+    // dispatches correspond in order to the file's tiled MatMul nodes — but+    // ONLY the tiled ones: a MatMul node with groups, stride, padding, or a+    // single position lowers to the untiled or GEMV kernel, which has no+    // blocked twin. The routing is recomputed here from the node attrs and+    // tensor shapes, mirroring `Builder::emit`'s tiled test exactly+    // (ungrouped 1x1, stride 1, unpadded, same spatial extent, >1 position).+    // A drift between the two routings fails the count check below rather+    // than rewriting the wrong dispatch.     let mut qualify: Vec<bool> = Vec::new();     for n in 0..nodes.len() {         let node = nodes.get(n);-        let is_matmul = node.op() == fb::Op::MatMul;-        if !is_matmul {+        if node.op() != fb::Op::MatMul {             continue;         }         let inputs: Vec<i32> = node.inputs().map(|v| (0..v.len()).map(|i| v.get(i)).collect()).unwrap_or_default();@@ -536,7 +587,27 @@ fn rewrite_blocked_kinds(         if inputs.len() != 4 || outputs.len() != 1 {             continue;         }-        let blocked = [inputs[0], inputs[1], outputs[0]]+        let attrs = NodeAttrs { node };+        let ints = |name: &str| attrs.ints(name).unwrap_or_default();+        let kernel = ints("kernel");+        let stride = ints("stride");+        let pads = ints("pads");+        let groups = attrs.int("groups").unwrap_or(1);+        let a = dims_of(inputs[0]);+        let y = dims_of(outputs[0]);+        let tiled = groups == 1+            && kernel == [1, 1]+            && stride == [1, 1]+            && pads == [0, 0, 0, 0]+            && a.len() == 3+            && y.len() == 3+            && a[1] == y[1]+            && a[2] == y[2]+            && y[1] * y[2] > 1;+        if !tiled {+            continue;+        }+        let blocked = [inputs[0], outputs[0]]             .iter()             .all(|t| layout_of(*t) == Some(fb::Layout::CHANNEL_BLOCKED_4));         qualify.push(blocked);@@ -553,7 +624,7 @@ fn rewrite_blocked_kinds(                     Some(false) => {}                     None => {                         return Err(format!(-                            "more tiled int8 dispatches than MatMul nodes ({qi} seen)"+                            "more tiled int8 dispatches than tiled MatMul nodes ({qi} seen)"                         ));                     }                 }@@ -563,7 +634,7 @@ fn rewrite_blocked_kinds(     }     if qi != qualify.len() {         return Err(format!(-            "MatMul node count {} != tiled int8 dispatch count {qi}",+            "tiled MatMul node count {} != tiled int8 dispatch count {qi}",             qualify.len()         ));     }@@ -585,7 +656,7 @@ fn lower_node(     let outputs: Vec<i32> =         node.outputs().map(|v| (0..v.len()).map(|i| v.get(i)).collect::<Vec<i32>>()).unwrap_or_default();     if outputs.len() != 1 {-        return Err(err("Phase 1 nodes write exactly one tensor"));+        return Err(err("v2 nodes write exactly one tensor"));     }     let id_of = |t: i32| -> Result<Id, String> {         ids.get(&t).copied().ok_or_else(|| err(&format!("tensor {t} has no Id yet")))@@ -614,9 +685,22 @@ fn lower_node(             let stride = attrs.ints("stride")?;             let dilation = attrs.ints("dilation")?;             let pads = attrs.ints("pads")?;+            if pads.len() != 4 {+                return Err(err("Conv pads are not [t, l, b, r]"));+            }             let groups = attrs.int("groups")? as u32;             let pad_edge = attrs.opt_bool("pad_edge");-            let act = act_from_code(attrs.int("activation")?).map_err(|e| err(&e))?;+            let act_code = attrs.int("activation")?;+            let act = act_from_code(act_code).map_err(|e| err(&e))?;+            // PRelu's slope is a tensor ref beside the code; every other+            // activation leaves the slope slot zero and unread.+            let act_weight = match act {+                Act::PRelu(_) => {+                    let slope = attrs.opt_int("slope").ok_or_else(|| err("PRelu with no slope"))?;+                    weight_elem(slope)?+                }+                _ => 0,+            };             let m = tensors                 .get(inputs[1] as usize)                 .dims()@@ -630,13 +714,13 @@ fn lower_node(                 id_of(inputs[0])?,                 w,                 b,-                0,+                act_weight,                 m,                 act,                 (kernel[0] as u32, kernel[1] as u32),                 (stride[0] as u32, stride[1] as u32),                 (dilation[0] as u32, dilation[1] as u32),-                (pads[0] as u32, pads[1] as u32, pads[0] as u32, pads[1] as u32),+                (pads[0] as u32, pads[1] as u32, pads[2] as u32, pads[3] as u32),                 groups,                 pad_edge,                 res,@@ -644,13 +728,56 @@ fn lower_node(             );             id         }+        fb::Op::ConvTranspose => {+            if inputs.len() != 3 {+                return Err(err("ConvTranspose wants [x, w, b]"));+            }+            let kernel = attrs.ints("kernel")?;+            let stride = attrs.ints("stride")?;+            let pads = attrs.ints("pads")?;+            if pads.len() != 4 {+                return Err(err("ConvTranspose pads are not [t, l, b, r]"));+            }+            let act_code = attrs.int("activation")?;+            let act = act_from_code(act_code).map_err(|e| err(&e))?;+            let act_weight = match act {+                Act::PRelu(_) => {+                    let slope = attrs.opt_int("slope").ok_or_else(|| err("PRelu with no slope"))?;+                    weight_elem(slope)?+                }+                _ => 0,+            };+            let m = tensors+                .get(inputs[1] as usize)+                .dims()+                .map(|d| if d.len() > 1 { d.get(1) as u32 } else { 0 })+                .unwrap_or(0);+            let w = weight_elem(inputs[1])?;+            let b = weight_elem(inputs[2])?;+            builder.conv_transpose_raw(+                id_of(inputs[0])?,+                w,+                b,+                act_weight,+                m,+                act,+                (kernel[0] as u32, kernel[1] as u32),+                (stride[0] as u32, stride[1] as u32),+                (pads[0] as u32, pads[1] as u32, pads[2] as u32, pads[3] as u32),+            )+        }         fb::Op::MatMul => {-            // Int8 1x1: `[a, w, s, b]`. The loader routes by shape through-            // `conv_int8_raw`, which lowers to the tiled/GEMV kernels.+            // Quantised 1x1: `[a, w, s, b]`. The loader routes by shape+            // through `conv_int8_raw_fused`, which lowers to the+            // tiled/GEMV/untiled kernels — including grouped 1x1s (maia's+            // replicated smolgen expansion, group 8), which take the untiled+            // path exactly as the hand-written pass does. Groups ride the+            // node attrs; the kernel dims carry per-group taps.             if inputs.len() != 4 {                 return Err(err("MatMul wants [a, w, s, b]"));             }             let act = act_from_code(attrs.int("activation")?).map_err(|e| err(&e))?;+            let groups = attrs.int("groups").unwrap_or(1) as u32;             let m = tensors                 .get(inputs[1] as usize)                 .dims()@@ -677,7 +804,7 @@ fn lower_node(                 (1, 1),                 (1, 1),                 (0, 0, 0, 0),-                1,+                groups,                 crate::nets::Quant::I8,                 res,                 shift,@@ -701,11 +828,126 @@ fn lower_node(             }             builder.add_channel(id_of(inputs[0])?, id_of(inputs[1])?)         }+        fb::Op::MulBroadcast => {+            if inputs.len() != 2 {+                return Err(err("MulBroadcast wants [a, b]"));+            }+            builder.mul_channel(id_of(inputs[0])?, id_of(inputs[1])?)+        }+        fb::Op::MaxPool => {+            if inputs.len() != 1 {+                return Err(err("MaxPool wants [x]"));+            }+            // The only max pooling the nets record is 2x2 stride 2 (the+            // builder refuses odd extents); replay through it so the same+            // refusal guards the file.+            builder.max_pool_2x2(id_of(inputs[0])?)+        }+        fb::Op::AvgPool => {+            if inputs.len() != 1 {+                return Err(err("AvgPool wants [x]"));+            }+            let kernel = attrs.ints("kernel")?;+            let stride = attrs.ints("stride")?;+            builder.avg_pool(+                id_of(inputs[0])?,+                (kernel[0] as u32, kernel[1] as u32),+                (stride[0] as u32, stride[1] as u32),+            )+        }+        fb::Op::Resize => {+            if inputs.len() != 1 {+                return Err(err("Resize wants [x]"));+            }+            let mode = attrs.int("mode")?;+            let dims = attrs.ints("dims")?;+            if dims.len() != 3 {+                return Err(err("Resize dims are not [c, h, w]"));+            }+            // Bilinear is the `half_pixel` shader; nearest is asymmetric.+            // Mode 0/1 mirrors the emitter; anything else is a corrupt file.+            match mode {+                0 => builder.resize_to(id_of(inputs[0])?, dims[1] as u32, dims[2] as u32),+                1 => builder.resize_nearest_to(id_of(inputs[0])?, dims[1] as u32, dims[2] as u32),+                _ => return Err(err(&format!("Resize mode {mode} is not 0 or 1"))),+            }+        }+        fb::Op::GlobalAvgPool => {+            if inputs.len() != 1 {+                return Err(err("GlobalAvgPool wants [x]"));+            }+            builder.global_avg_pool(id_of(inputs[0])?)+        }+        fb::Op::Concat => {+            if inputs.is_empty() {+                return Err(err("Concat wants parts"));+            }+            // A single part is a reshape (`Builder::reshaped`): replay the+            // relabel against the stored output shape rather than deriving a+            // channel sum from the part.+            if inputs.len() == 1 {+                let dims = tensors+                    .get(outputs[0] as usize)+                    .dims()+                    .map(|d| (0..d.len()).map(|i| d.get(i) as u32).collect::<Vec<u32>>())+                    .unwrap_or_default();+                if dims.len() != 3 {+                    return Err(err("reshape Concat output is not [c, h, w]"));+                }+                builder.reshaped(+                    id_of(inputs[0])?,+                    Shape::new(dims[0], dims[1], dims[2]),+                )+            } else {+                let axis = attrs.int("axis")?;+                let parts: Vec<Id> = inputs+                    .iter()+                    .map(|t| id_of(*t))+                    .collect::<Result<Vec<Id>, String>>()?;+                match axis {+                    0 => builder.concat(&parts),+                    2 => builder.concat_positions(&parts),+                    _ => return Err(err(&format!("Concat axis {axis} is not 0 or 2"))),+                }+            }+        }+        fb::Op::Affine => {+            if inputs.len() != 1 {+                return Err(err("Affine wants [x]"));+            }+            let scale = attrs.float("scale")?;+            let shift = attrs.float("shift")?;+            builder.affine(id_of(inputs[0])?, scale, shift)+        }+        fb::Op::Constant => {+            if inputs.len() != 1 {+                return Err(err("Constant wants [weight]"));+            }+            let w = weight_elem(inputs[0])?;+            let dims = tensors+                .get(outputs[0] as usize)+                .dims()+                .map(|d| (0..d.len()).map(|i| d.get(i) as u32).collect::<Vec<u32>>())+                .unwrap_or_default();+            if dims.len() != 3 {+                return Err(err("Constant output is not [c, h, w]"));+            }+            builder.constant_raw(w, Shape::new(dims[0], dims[1], dims[2]))+        }+        fb::Op::RmsNorm => {+            if inputs.len() != 2 {+                return Err(err("RmsNorm wants [x, gamma]"));+            }+            let epsilon = attrs.float("epsilon")?;+            let groups = attrs.int("groups")? as u32;+            let g = weight_elem(inputs[1])?;+            builder.rms_norm_raw(id_of(inputs[0])?, g, epsilon, groups)+        }         fb::Op::LayerNorm => {             if inputs.len() != 3 {                 return Err(err("LayerNorm wants [x, gamma, beta]"));             }-            let epsilon = 1e-5;+            let epsilon = attrs.float("epsilon")?;             let g = weight_elem(inputs[1])?;             let be = weight_elem(inputs[2])?;             builder.layer_norm_raw(id_of(inputs[0])?, g, be, epsilon)@@ -754,7 +996,7 @@ fn lower_node(             // channel extent; the offset names its start.             builder.slice_channels(id_of(inputs[0])?, offset, dims[0] as u32)         }-        _ => return Err(err("op is not a Phase 1 sampler op")),+        _ => return Err(err("op is not expressible in a v2 graph yet")),     };     ids.insert(outputs[0], out);     Ok(())
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 e8b01a504c..5ba5e3f9c0 100644--- a/library/ml/src/main/rust/src/maml2/parity.rs+++ b/library/ml/src/main/rust/src/maml2/parity.rs@@ -141,38 +141,36 @@ fn lowered_plan_schedules_like_v1() {     ); } -/// True numeric parity: the v2-lowered plan against the v1 plan, same-/// interpreter, same invented inputs, real weights both sides.+/// True numeric parity between a v1 plan and its v2 lowering. ///-/// 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() {-    // The v1 plan must be built against the real `Offsets` table: the-    // `Shapes` stub hands back tensor indices as addresses, which read-    // wrong weights on a real blob (NaN within an op or two). Real-    // addresses, real weights, same interpreter, same inputs.+/// Builds the v1 plan against the real `Offsets` (never the `Shapes` stub,+/// whose index-as-address reads wrong weights on a real blob), lowers the+/// v2 file, and requires bit-exact outputs through the same interpreter on+/// the same invented inputs. Skips quietly when either asset is absent.+fn assert_bit_exact(+    what: &str,+    v1asset: &str,+    graph_id: u32,+    v2asset: &str,+    build_v1: impl FnOnce(&crate::weights::Offsets) -> Result<crate::nets::Plan, String>,+    inputs: Vec<Vec<f32>>,+) {     let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))         .ancestors()         .nth(5)         .expect("workspace root")         .to_path_buf();-    let v1path = root.join("speech/src/main/assets/supertonic/supertonic_ve.maml");+    let v1path = root.join(v1asset);     let v1bytes = match std::fs::read(&v1path) {         Ok(bytes) => bytes,         Err(e) if e.kind() == std::io::ErrorKind::NotFound => return,         Err(e) => panic!("cannot read {}: {e}", v1path.display()),     };-    let v1parsed = weights::Weights::parse(&v1bytes, weights::graph::SUPERTONIC_VE)-        .expect("parse the v1 asset");+    let v1parsed =+        weights::Weights::parse(&v1bytes, graph_id).expect("parse the v1 asset");     let v1data = v1parsed.data().to_vec();-    let v1plan = supertonic_sampler::build(&v1parsed.offsets(), 49, 55).expect("build v1");-    let path = root.join("speech/src/main/assets/supertonic/supertonic_ve.maml2");+    let v1plan = build_v1(&v1parsed.offsets()).expect("build v1");+    let path = root.join(v2asset);     let bytes = match std::fs::read(&path) {         Ok(bytes) => bytes,         Err(e) if e.kind() == std::io::ErrorKind::NotFound => return,@@ -182,40 +180,177 @@ fn v2_plan_matches_v1_bit_exact() {     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();+    assert_eq!(+        refs.len(),+        v1plan.inputs.len(),+        "{what}: invented inputs cover the v1 plan inputs"+    );+    assert_eq!(+        refs.len(),+        plan.inputs.len(),+        "{what}: invented inputs cover the v2 plan inputs"+    );     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+    // The zero oracle: invented inputs through 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"+        "{what}: the v1 interpreter output is all zeros"     );-    assert_eq!(v2out.len(), v1out.len(), "same output count");+    assert_eq!(v2out.len(), v1out.len(), "{what}: same output count");     for (index, (a, b)) in v1out.iter().zip(v2out.iter()).enumerate() {-        assert_eq!(a.len(), b.len(), "output {index} length");+        assert_eq!(a.len(), b.len(), "{what}: 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}");+            assert!(x == y, "{what}: output {index} element {at}: v1 {x} vs v2 {y}");         }     } }++/// Invented inputs: distinct, bounded, asymmetric about zero, so+/// sign/transpose errors cannot hide. One vector per plan input shape.+fn spread_inputs(shapes: &[(usize, usize, usize)], seed: f32) -> Vec<Vec<f32>> {+    shapes+        .iter()+        .enumerate()+        .map(|(k, (c, h, w))| {+            (0..c * h * w)+                .map(|i| (i as f32 * 0.7 + (seed + k as f32) * 1.7).sin() * 0.8 + 0.1)+                .collect()+        })+        .collect()+}++/// True numeric parity for the sampler: the v2-lowered plan against the v1+/// plan. See [`assert_bit_exact`] for the contract.+#[test]+fn v2_plan_matches_v1_bit_exact() {+    assert_bit_exact(+        "the sampler at 49 frames, 55 chars",+        "speech/src/main/assets/supertonic/supertonic_ve.maml",+        weights::graph::SUPERTONIC_VE,+        "speech/src/main/assets/supertonic/supertonic_ve.maml2",+        |offsets| supertonic_sampler::build(offsets, 49, 55),+        spread_inputs(+            &[+                (144usize, 1usize, 49usize),+                (256, 1, 55),+                (1024, 1, 50),+                (256, 1, 50),+                (2048, 1, 1),+                (64, 1, 49),+                (64, 1, 55),+            ],+            0.0,+        ),+    );+}++/// True numeric parity for selfie segmentation: the v2-lowered plan against+/// the v1 plan at 256x256.+#[test]+fn v2_selfie_matches_v1_bit_exact() {+    use crate::nets::selfie;+    assert_bit_exact(+        "selfie at 256x256",+        "camera/src/main/assets/selfie_segmentation.maml",+        weights::graph::SELFIE,+        "camera/src/main/assets/selfie_segmentation.maml2",+        |offsets| selfie::build(offsets),+        spread_inputs(&[(3usize, 256usize, 256usize)], 0.0),+    );+}++/// True numeric parity for U^2-Net portable at 320x320.+#[test]+fn v2_u2netp_matches_v1_bit_exact() {+    use crate::nets::u2netp;+    assert_bit_exact(+        "u2netp at 320x320",+        "photos/src/main/assets/u2netp.maml",+        weights::graph::U2NETP,+        "photos/src/main/assets/u2netp.maml2",+        |offsets| u2netp::build(offsets),+        spread_inputs(&[(3usize, 320usize, 320usize)], 1.0),+    );+}++/// True numeric parity for SCRFD at 640x640.+#[test]+fn v2_scrfd_matches_v1_bit_exact() {+    use crate::nets::scrfd;+    assert_bit_exact(+        "scrfd at 640x640",+        "photos/src/main/assets/scrfd_500m.maml",+        weights::graph::SCRFD,+        "photos/src/main/assets/scrfd_500m.maml2",+        |offsets| scrfd::build(offsets, 640, 640),+        spread_inputs(&[(3usize, 640usize, 640usize)], 2.0),+    );+}++/// True numeric parity for MobileFaceNet at 112x112 (exercises fused PRelu+/// slopes through the file).+#[test]+fn v2_mobilefacenet_matches_v1_bit_exact() {+    use crate::nets::mobilefacenet;+    assert_bit_exact(+        "mobilefacenet at 112x112",+        "photos/src/main/assets/w600k_mbf.maml",+        weights::graph::MOBILEFACENET,+        "photos/src/main/assets/w600k_mbf.maml2",+        |offsets| mobilefacenet::build(offsets),+        spread_inputs(&[(3usize, 112usize, 112usize)], 3.0),+    );+}++/// True numeric parity for PP-OCR detection at 960x960.+#[test]+fn v2_ppocr_det_matches_v1_bit_exact() {+    use crate::nets::ppocr_det;+    assert_bit_exact(+        "ppocr_det at 960x960",+        "library/ocr/src/main/assets/ppocr_det.maml",+        weights::graph::PPOCR_DET,+        "library/ocr/src/main/assets/ppocr_det.maml2",+        |offsets| ppocr_det::build(offsets, 960, 960),+        spread_inputs(&[(3usize, 960usize, 960usize)], 4.0),+    );+}++/// True numeric parity for PP-OCR recognition on a 48x320 crop.+#[test]+fn v2_ppocr_rec_matches_v1_bit_exact() {+    use crate::nets::ppocr_rec_extra;+    assert_bit_exact(+        "ppocr_rec on 48x320",+        "library/ocr/src/main/assets/ppocr_rec.maml",+        weights::graph::PPOCR_REC,+        "library/ocr/src/main/assets/ppocr_rec.maml2",+        |offsets| ppocr_rec_extra::build(offsets, 320),+        spread_inputs(&[(3usize, 48usize, 320usize)], 5.0),+    );+}++/// True numeric parity for Maia (two outputs, host-side elo tables, int8+/// points, single-head attention).+#[test]+fn v2_maia_matches_v1_bit_exact() {+    use crate::nets::maia;+    assert_bit_exact(+        "maia",+        "games/chess/src/main/assets/maia3-5m.maml",+        weights::graph::MAIA,+        "games/chess/src/main/assets/maia3-5m.maml2",+        |offsets| maia::build(offsets),+        spread_inputs(+            &[(+                maia::INPUT as usize,+                1usize,+                maia::SQUARES as usize,+            )],+            6.0,+        ),+    );+}
library/ml/src/main/rust/src/nets/maia.rs
diff --git a/library/ml/src/main/rust/src/nets/maia.rs b/library/ml/src/main/rust/src/nets/maia.rsindex 96dcf9877b..9993c1feec 100644--- a/library/ml/src/main/rust/src/nets/maia.rs+++ b/library/ml/src/main/rust/src/nets/maia.rs@@ -309,6 +309,15 @@ fn encoder_block(b: &mut Builder, l: &mut Layers, x: Id) -> Id { /// `post::maia` turns them into the 4352-logit move vector; see [`crate::post::maia`] for /// why the promotion head runs over all 64 positions rather than the eight it needs. pub fn build(weights: &dyn WeightSource) -> Result<Plan, String> {+    Ok(record(weights)?.plan)+}++/// Record the forward pass: the resolved plan plus the graph.+///+/// [`build`] is this plus `Op` emission; the MAML v2 emitter needs the graph+/// without the plan, after the same fusion fold and the same every-tensor+/// rule. Split out so both share the body verbatim. See [`Builder::record`].+pub fn record(weights: &dyn WeightSource) -> Result<crate::nets::Recorded, String> {     let mut builder = Builder::new(weights);     let b = &mut builder;     // The elo tables are read on the host by `elo_embedding`, so nothing in the plan touches@@ -342,7 +351,7 @@ pub fn build(weights: &dyn WeightSource) -> Result<Plan, String> {     if policy.next != TENSORS {         return Err(format!("the policy head ends at {}, not {TENSORS}", policy.next));     }-    builder.finish(&[scores, promo])+    builder.record(&[scores, promo], &crate::weights::Offsets::empty()) }  /// The blended elo vector for `elo`, `ELO_DIM` long.
library/ml/src/main/rust/src/nets/mobilefacenet.rs
diff --git a/library/ml/src/main/rust/src/nets/mobilefacenet.rs b/library/ml/src/main/rust/src/nets/mobilefacenet.rsindex d5815841dd..11a6e79b48 100644--- a/library/ml/src/main/rust/src/nets/mobilefacenet.rs+++ b/library/ml/src/main/rust/src/nets/mobilefacenet.rs@@ -115,6 +115,15 @@ fn transition(b: &mut Builder, l: &mut Layers, x: Id, wide: u32, out: u32) -> Id  /// Compile the whole forward pass. pub fn build(weights: &dyn WeightSource) -> Result<Plan, String> {+    Ok(record(weights)?.plan)+}++/// Record the whole forward pass: the resolved plan plus the graph.+///+/// [`build`] is this plus `Op` emission; the MAML v2 emitter needs the graph+/// without the plan, after the same fusion fold and the same every-tensor+/// rule. Split out so both share the body verbatim. See [`Builder::record`].+pub fn record(weights: &dyn WeightSource) -> Result<crate::nets::Recorded, String> {     let mut b = Builder::new(weights);     let mut layers = Layers { next: 0 };     let l = &mut layers;@@ -190,7 +199,7 @@ pub fn build(weights: &dyn WeightSource) -> Result<Plan, String> {         1,         Act::None,     );-    b.finish(&[embedding])+    b.record(&[embedding], &crate::weights::Offsets::empty()) }  #[cfg(test)]
library/ml/src/main/rust/src/nets/mod_part4.rs
diff --git a/library/ml/src/main/rust/src/nets/mod_part4.rs b/library/ml/src/main/rust/src/nets/mod_part4.rsindex b9a1c529e1..ebe9d16f32 100644--- a/library/ml/src/main/rust/src/nets/mod_part4.rs+++ b/library/ml/src/main/rust/src/nets/mod_part4.rs@@ -595,4 +595,51 @@ impl<'a> Builder<'a> {         });         out     }++    /// [`Builder::conv_transpose`] with resolved weight offsets rather than+    /// table indices.+    ///+    /// As [`Builder::conv_raw`]: the section parser validated shapes, so+    /// lowering only translates addressing. `m` is the section's computed+    /// output channels. No fused form: `fuse_elementwise` never folds into a+    /// transpose (its producer predicate names `Conv`/`ConvInt8` nodes), so+    /// there is no `res`/`shift` to replay.+    #[allow(clippy::too_many_arguments)]+    pub fn conv_transpose_raw(+        &mut self,+        input: Id,+        weight: u32,+        bias: u32,+        act_weight: u32,+        m: u32,+        act: Act,+        kernel: (u32, u32),+        stride: (u32, u32),+        pads: (u32, u32, u32, u32),+    ) -> Id {+        let in_shape = self.shape_of(input);+        let (kh, kw) = kernel;+        let (pad_t, pad_l, pad_b, pad_r) = pads;+        let out_h = deconv_out(in_shape.h, kh, stride.0, pad_t + pad_b);+        let out_w = deconv_out(in_shape.w, kw, stride.1, pad_l + pad_r);+        let out = self.tensor(Shape::new(m, out_h, out_w));+        self.nodes.push(Node::Conv {+            input,+            out,+            weight,+            bias,+            kernel,+            stride,+            dilation: (1, 1),+            pad: (pad_t, pad_l),+            group: 1,+            act,+            act_weight,+            transpose: true,+            pad_edge: false,+            res: None,+            shift: None,+        });+        out+    } }\ No newline at end of file
library/ml/src/main/rust/src/nets/mod_part5.rs
diff --git a/library/ml/src/main/rust/src/nets/mod_part5.rs b/library/ml/src/main/rust/src/nets/mod_part5.rsindex 46cf87b7b9..b89dd212b8 100644--- a/library/ml/src/main/rust/src/nets/mod_part5.rs+++ b/library/ml/src/main/rust/src/nets/mod_part5.rs@@ -91,6 +91,16 @@ impl<'a> Builder<'a> {         out     } +    /// [`Builder::resize_nearest_like`] to an explicit size, for lowering a+    /// version-2 graph section: the file carries the recorded target dims,+    /// not a `like` tensor. Same node as the `like` form.+    pub fn resize_nearest_to(&mut self, input: Id, h: u32, w: u32) -> Id {+        let in_shape = self.shape_of(input);+        let out = self.tensor(Shape::new(in_shape.c, h, w));+        self.nodes.push(Node::Resize { input, out, nearest: true });+        out+    }+     /// Mean over H and W, to `C x 1 x 1`.     pub fn global_avg_pool(&mut self, input: Id) -> Id {         let in_shape = self.shape_of(input);@@ -279,6 +289,19 @@ impl<'a> Builder<'a> {         out     } +    /// [`Builder::rms_norm_grouped`] with a resolved gamma offset rather than+    /// a table index.+    ///+    /// As [`Builder::conv_raw`]: the loader validated shapes at inference, so+    /// lowering only translates addressing. `groups` rides the node as the+    /// indexed path sets it.+    pub fn rms_norm_raw(&mut self, input: Id, gamma: u32, epsilon: f32, groups: u32) -> Id {+        let shape = self.shape_of(input);+        let out = self.tensor(shape);+        self.nodes.push(Node::RmsNorm { input, out, gamma, epsilon, groups });+        out+    }+     /// Attention scores from `q` and `k`, both `[d_model, 1, T]`, into `[heads, T, T]`.     ///     /// The `1 / sqrt(head_dim)` scale is derived here rather than taken as an argument:
library/ml/src/main/rust/src/nets/mod_part6.rs
diff --git a/library/ml/src/main/rust/src/nets/mod_part6.rs b/library/ml/src/main/rust/src/nets/mod_part6.rsindex f53902c1f8..234473211f 100644--- a/library/ml/src/main/rust/src/nets/mod_part6.rs+++ b/library/ml/src/main/rust/src/nets/mod_part6.rs@@ -393,6 +393,17 @@ impl<'a> Builder<'a> {         out     } +    /// [`Builder::constant`] with a resolved weight offset rather than a+    /// table index.+    ///+    /// As [`Builder::conv_raw`]: the loader validated shapes at inference, so+    /// lowering only translates addressing.+    pub fn constant_raw(&mut self, weight: u32, shape: Shape) -> Id {+        let out = self.tensor(shape);+        self.nodes.push(Node::Constant { out, weight });+        out+    }+     /// An embedding lookup: `out[c][t] = table[id(t)][c]`, over a `[1, 1, T]` id tensor, or a     /// `[2, 1, T]` one when the table has more than [`EMBED_LANE`] rows.     ///
library/ml/src/main/rust/src/nets/nnfp.rs
diff --git a/library/ml/src/main/rust/src/nets/nnfp.rs b/library/ml/src/main/rust/src/nets/nnfp.rsindex 1cbc3e7e74..274566ecff 100644--- a/library/ml/src/main/rust/src/nets/nnfp.rs+++ b/library/ml/src/main/rust/src/nets/nnfp.rs@@ -207,6 +207,15 @@ fn temporal(b: &mut Builder, l: &mut Layers, x: Id, out_c: u32, stride: u32) -> /// divisor is undone by the affine — `avg_pool` divides by the window unconditionally, and there /// is no sum-pool. Two dispatches and no new shader. pub fn build(weights: &dyn WeightSource) -> Result<Plan, String> {+    Ok(record(weights)?.plan)+}++/// Record the whole forward pass: the resolved plan plus the graph.+///+/// [`build`] is this plus `Op` emission; the MAML v2 emitter needs the graph+/// without the plan, after the same fusion fold and the same every-tensor+/// rule. Split out so both share the body verbatim. See [`Builder::record`].+pub fn record(weights: &dyn WeightSource) -> Result<crate::nets::Recorded, String> {     let mut b = Builder::new(weights);     let mut layers = Layers { next: 0 };     let l = &mut layers;@@ -252,7 +261,7 @@ pub fn build(weights: &dyn WeightSource) -> Result<Plan, String> {     let bias = b.constant(l.constant(), Shape::new(EMBEDDING, 1, 1));     let embedding = b.add(column, bias); -    b.finish(&[embedding])+    b.record(&[embedding], &crate::weights::Offsets::empty()) }  #[cfg(test)]
library/ml/src/main/rust/src/nets/ppocr_det.rs
diff --git a/library/ml/src/main/rust/src/nets/ppocr_det.rs b/library/ml/src/main/rust/src/nets/ppocr_det.rsindex 484b463a43..6401a09958 100644--- a/library/ml/src/main/rust/src/nets/ppocr_det.rs+++ b/library/ml/src/main/rust/src/nets/ppocr_det.rs@@ -132,6 +132,19 @@ fn residual_excite(b: &mut Builder, l: &mut Layers, x: Id, reduce: u32) -> Id {  /// Compile the forward pass for an input of `height` x `width`. pub fn build(weights: &dyn WeightSource, height: u32, width: u32) -> Result<Plan, String> {+    Ok(record(weights, height, width)?.plan)+}++/// Record the forward pass for an input of `height` x `width`.+///+/// [`build`] is this plus `Op` emission; the MAML v2 emitter needs the graph+/// without the plan, after the same fusion fold and the same every-tensor+/// rule. Split out so both share the body verbatim. See [`Builder::record`].+pub fn record(+    weights: &dyn WeightSource,+    height: u32,+    width: u32,+) -> Result<crate::nets::Recorded, String> {     compile(weights, height, width, false) } @@ -140,7 +153,7 @@ fn compile(     height: u32,     width: u32,     backbone: bool,-) -> Result<Plan, String> {+) -> Result<crate::nets::Recorded, String> {     if height == 0 || width == 0 {         return Err(format!("a {width}x{height} input"));     }@@ -249,9 +262,9 @@ fn compile(     let probability =         b.conv_transpose(x, l.take(), 1, (2, 2), (2, 2), (0, 0, 0, 0), Act::Sigmoid);     if backbone {-        return b.finish(&[probability, c5]);+        return b.record(&[probability, c5], &crate::weights::Offsets::empty());     }-    b.finish(&[probability])+    b.record(&[probability], &crate::weights::Offsets::empty()) }  /// [`build`], plus the backbone's output as a second binding.@@ -265,7 +278,7 @@ pub fn build_with_backbone(     height: u32,     width: u32, ) -> Result<Plan, String> {-    compile(weights, height, width, true)+    Ok(compile(weights, height, width, true)?.plan) }  /// A 3x3 convolution at `stride`, for the stem.
library/ml/src/main/rust/src/nets/ppocr_rec_extra.rs
diff --git a/library/ml/src/main/rust/src/nets/ppocr_rec_extra.rs b/library/ml/src/main/rust/src/nets/ppocr_rec_extra.rsindex 0fd1dc620c..5f65ea45a6 100644--- a/library/ml/src/main/rust/src/nets/ppocr_rec_extra.rs+++ b/library/ml/src/main/rust/src/nets/ppocr_rec_extra.rs@@ -9,6 +9,15 @@ use super::ppocr_rec::{along_sequence, block, depthwise, point, squeeze_excite}; /// `width` must be a positive multiple of [`WIDTH_MULTIPLE`]; the output is /// `[LOGITS, 1, width / 8]`. pub fn build(weights: &dyn WeightSource, width: u32) -> Result<Plan, String> {+    Ok(record(weights, width)?.plan)+}++/// Record the recognition pass for a `48 x width` crop.+///+/// [`build`] is this plus `Op` emission; the MAML v2 emitter needs the graph+/// without the plan, after the same fusion fold and the same every-tensor+/// rule. Split out so both share the body verbatim. See [`Builder::record`].+pub fn record(weights: &dyn WeightSource, width: u32) -> Result<crate::nets::Recorded, String> {     use super::ppocr_rec::Layers;     if width == 0 || !width.is_multiple_of(WIDTH_MULTIPLE) {         return Err(format!(@@ -108,5 +117,5 @@ pub fn build(weights: &dyn WeightSource, width: u32) -> Result<Plan, String> {     if l.next != TENSORS {         return Err(format!("the forward pass claims {} tensors, not {TENSORS}", l.next));     }-    builder.finish(&[logits])+    builder.record(&[logits], &crate::weights::Offsets::empty()) }
library/ml/src/main/rust/src/nets/scrfd.rs
diff --git a/library/ml/src/main/rust/src/nets/scrfd.rs b/library/ml/src/main/rust/src/nets/scrfd.rsindex 9d74cdddd0..6939bed90b 100644--- a/library/ml/src/main/rust/src/nets/scrfd.rs+++ b/library/ml/src/main/rust/src/nets/scrfd.rs@@ -160,6 +160,19 @@ fn head(b: &mut Builder, l: &mut Layers, x: Id) -> (Id, Id, Id) { /// Both must be multiples of [`EXTENT_MULTIPLE`]; see the module docs for why that is a /// requirement and not a convention. pub fn build(weights: &dyn WeightSource, height: u32, width: u32) -> Result<Plan, String> {+    Ok(record(weights, height, width)?.plan)+}++/// Record the whole forward pass: the resolved plan plus the graph.+///+/// [`build`] is this plus `Op` emission; the MAML v2 emitter needs the graph+/// without the plan, after the same fusion fold and the same every-tensor+/// rule. Split out so both share the body verbatim. See [`Builder::record`].+pub fn record(+    weights: &dyn WeightSource,+    height: u32,+    width: u32,+) -> Result<crate::nets::Recorded, String> {     if height == 0 || width == 0 {         return Err(format!("a {width}x{height} input"));     }@@ -233,7 +246,7 @@ pub fn build(weights: &dyn WeightSource, height: u32, width: u32) -> Result<Plan     // over `STRIDES`. The ONNX declares its nine outputs grouped the other way, by kind     // then stride; the order here is the one that makes the post-processing loop     // obviously right, and it is the only place the two conventions meet.-    b.finish(&outputs)+    b.record(&outputs, &crate::weights::Offsets::empty()) }  #[cfg(test)]
library/ml/src/main/rust/src/nets/selfie.rs
diff --git a/library/ml/src/main/rust/src/nets/selfie.rs b/library/ml/src/main/rust/src/nets/selfie.rsindex f69f567be3..63e8fd47c1 100644--- a/library/ml/src/main/rust/src/nets/selfie.rs+++ b/library/ml/src/main/rust/src/nets/selfie.rs@@ -128,6 +128,15 @@ fn final_block(b: &mut Builder, layers: &mut Layers, deep: Id, skip: Id, channel  /// Compile the whole forward pass. pub fn build(weights: &dyn WeightSource) -> Result<Plan, String> {+    Ok(record(weights)?.plan)+}++/// Record the whole forward pass: the resolved plan plus the graph.+///+/// [`build`] is this plus `Op` emission; the MAML v2 emitter needs the graph+/// without the plan, after the same fusion fold and the same every-tensor+/// rule. Split out so both share the body verbatim. See [`Builder::record`].+pub fn record(weights: &dyn WeightSource) -> Result<crate::nets::Recorded, String> {     let mut b = Builder::new(weights);     let mut layers = Layers { next: 0 };     let l = &mut layers;@@ -181,7 +190,7 @@ pub fn build(weights: &dyn WeightSource) -> Result<Plan, String> {      // 128 -> 256, and the sigmoid that makes it an alpha.     let alphas = b.conv_transpose(x, l.take(), 1, (2, 2), (2, 2), (0, 0, 0, 0), Act::Sigmoid);-    b.finish(&[alphas])+    b.record(&[alphas], &crate::weights::Offsets::empty()) }  #[cfg(test)]
library/ml/src/main/rust/src/nets/u2netp.rs
diff --git a/library/ml/src/main/rust/src/nets/u2netp.rs b/library/ml/src/main/rust/src/nets/u2netp.rsindex db90234d3d..37ebaf1f7f 100644--- a/library/ml/src/main/rust/src/nets/u2netp.rs+++ b/library/ml/src/main/rust/src/nets/u2netp.rs@@ -226,6 +226,15 @@ fn rsu4f(b: &mut Builder, layers: &mut Layers, x: Id) -> Id { /// Of the seven outputs the ONNX declares — the fused `d0` and the six per-scale side /// maps — only `d0` is produced. `MlSegmentation.kt` never read the others. pub fn build(weights: &dyn WeightSource) -> Result<Plan, String> {+    Ok(record(weights)?.plan)+}++/// Record the whole forward pass: the resolved plan plus the graph.+///+/// [`build`] is this plus `Op` emission; the MAML v2 emitter needs the graph+/// without the plan, after the same fusion fold and the same every-tensor+/// rule. Split out so both share the body verbatim. See [`Builder::record`].+pub fn record(weights: &dyn WeightSource) -> Result<crate::nets::Recorded, String> {     let mut b = Builder::new(weights);     let mut layers = Layers { next: 0 };     let l = &mut layers;@@ -275,7 +284,7 @@ pub fn build(weights: &dyn WeightSource) -> Result<Plan, String> {     let fused = b.concat(&sides);     let d0 = b.conv_same(fused, l.take(), 1, 1, 1, Act::Sigmoid); -    b.finish(&[d0])+    b.record(&[d0], &crate::weights::Offsets::empty()) }  #[cfg(test)]