Modern Apps git

← Modern-Apps.git

ml: v2 gemma-ready catalog, int4, cache unification

Commit
ea6b717702ab91632112eb335a02393ce87ab535
Author
vayun-mathur <[email protected]>
When
2026-09-14 10:18 UTC (2 months ago)
Parents
583def3

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.rsindex 52bdfc9dab..4610d66939 100644--- a/library/ml/src/main/rust/examples/emit_net_maml2.rs+++ b/library/ml/src/main/rust/examples/emit_net_maml2.rs@@ -44,9 +44,10 @@ fn usage() -> ! {     eprintln!("usage: emit_net_maml2 <net> [dims...]");     eprintln!("  single-graph: selfie u2netp scrfd mobilefacenet ppocr_det ppocr_rec maia");     eprintln!("    vocoder duration text");-    eprintln!("  multi-graph: tinyclip");+    eprintln!("  multi-graph: tinyclip whisper gemma_text");     eprintln!("  scrfd, ppocr_det take HEIGHT WIDTH; ppocr_rec takes WIDTH;");-    eprintln!("  vocoder takes FRAMES; duration, text take CHARS; tinyclip takes LEN");+    eprintln!("  vocoder takes FRAMES; duration, text take CHARS; tinyclip takes LEN;");+    eprintln!("  gemma_text takes CONTEXT_TIER TOKENS");     std::process::exit(1) } @@ -364,6 +365,58 @@ fn main() {             println!("wrote {}", out_path.display());             return;         }+        "gemma_text" => {+            use modelrunner::nets::gemma4::{Mode, Pass};+            let context: u32 = std::env::args()+                .nth(2)+                .map(|s| s.parse().unwrap_or_else(|_| usage()))+                .unwrap_or(1024);+            let tokens: u32 = std::env::args()+                .nth(3)+                .map(|s| s.parse().unwrap_or_else(|_| usage()))+                .unwrap_or(4);+            let asset = "analysis/models/gemma4_text.maml";+            let (data, tensors, offsets, sha) = load_v1(&root, asset, weights::graph::GEMMA4_TEXT);+            let decode = modelrunner::nets::gemma4::record(+                &offsets,+                Pass { mode: Mode::DecodeStep, context },+            )+            .expect("record decode");+            let prefill = modelrunner::nets::gemma4::record(+                &offsets,+                Pass { mode: Mode::Prefill { tokens }, context },+            )+            .expect("record prefill");+            let roles = ["token_embed", "per_layer", "angles_sliding", "angles_full"];+            let emitted = emit::emit_graphs(+                &tensors,+                &data,+                "gemma4-text int4 nchw (v2)",+                "maml2 emit_net_maml2",+                sha,+                &[+                    emit::GraphSpec {+                        recorded: &decode,+                        graph_name: "decode_step",+                        entry_name: "decode_step",+                        roles: &roles,+                    },+                    emit::GraphSpec {+                        recorded: &prefill,+                        graph_name: "prefill",+                        entry_name: "prefill",+                        roles: &roles,+                    },+                ],+            )+            .expect("emission succeeds");+            let out_path = root.join(asset.replace(".maml", ".maml2"));+            std::fs::write(&out_path, &emitted.bytes).expect("write the v2 file");+            println!("gemma_text v2: {} nodes over 2 graphs", emitted.op_inventory.iter().map(|(_, n)| n).sum::<usize>());+            println!("graph_digest: {}", hex(&emitted.graph_digest));+            println!("wrote {}", out_path.display());+            return;+        }         _ => usage(),     };     let _ = spec.graph;
library/ml/src/main/rust/schema/maml2.fbs
diff --git a/library/ml/src/main/rust/schema/maml2.fbs b/library/ml/src/main/rust/schema/maml2.fbsindex 3044503b20..128a61e48a 100644--- a/library/ml/src/main/rust/schema/maml2.fbs+++ b/library/ml/src/main/rust/schema/maml2.fbs@@ -59,7 +59,11 @@ enum Op : byte {   // kw]`. Appended for the vision nets' learned upsamples; opset stays 1 —   // the catalog grows together with its only loader until the first   // on-device ship (spec section 12.1).-  ConvTranspose = 29+  ConvTranspose = 29,+  // A fused activation applied standalone, for values no convolution+  // produced (the gated feed-forward's epilogue). Carries `activation` like+  // the producer epilogues in section 5.2.+  Activate = 30 }  // Spec section 3.1. Integer dtypes are always quantised weights (section
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 4b92e09a09..243275b32d 100644--- a/library/ml/src/main/rust/src/maml2/emit.rs+++ b/library/ml/src/main/rust/src/maml2/emit.rs@@ -209,11 +209,45 @@ fn emit_weight_tensor(         (WeightPayload::I8(_), WeightQuant::None) => {             return Err(format!("tensor {index} is int8 but read as a plain weight"));         }-        (WeightPayload::I4(bytes), _) => {-            return Err(format!(-                "tensor {index}: int4 repack is not implemented in Phase 1 ({} bytes)",-                bytes.len()-            ));+        (WeightPayload::I4(bytes), WeightQuant::Int4 { .. }) => {+            // Verbatim NCHW nibbles (low-first, v1 packing): the int4 twins+            // unpack through the same word view as int8, so stored bytes are+            // v1-order like everything else. `elems` is the logical count+            // (v1 `len`), not twice the bytes — an odd length pads its last+            // nibble, and verify checks `elem_count == product(dims)`.+            out.push(EmittedTensor {+                name: format!("w{index}.kernel"),+                dims,+                dtype: fb::DType::I4,+                layout: fb::Layout::NCHW,+                bytes: bytes.clone(),+                elems: u64::from(tensor.len),+                quant,+                state: fb::StateKind::NONE,+                dim_params: Vec::new(),+            });+            // The scale follows as its own tensor: `[out, blocks]` fp16.+            let (scale_tensor, scale_payload) = read_weight_payload(table, data, index + 1)?;+            let scale_dims = logical_dims(&scale_tensor);+            let WeightPayload::F16(scale_words) = scale_payload else {+                return Err(format!("tensor {} is not the fp16 scale of tensor {index}", index + 1));+            };+            let scale_bytes: Vec<u8> =+                scale_words.iter().flat_map(|w| w.to_le_bytes()).collect();+            out.push(EmittedTensor {+                name: format!("w{index}.scale"),+                dims: scale_dims,+                dtype: fb::DType::F16,+                layout: fb::Layout::NCHW,+                bytes: scale_bytes,+                elems: scale_words.len() as u64,+                quant: WeightQuant::None,+                state: fb::StateKind::NONE,+                dim_params: Vec::new(),+            });+        }+        (WeightPayload::I4(_), _) => {+            return Err(format!("tensor {index} is int4 but read as a plain or int8 weight"));         }         (WeightPayload::I8(_), WeightQuant::Int4 { .. })         | (WeightPayload::F16(_), WeightQuant::Int4 { .. }) => {@@ -883,6 +917,40 @@ fn emit_nodes(                     ],                 });             }+            Node::AttnScoresBanded { q, k, out, heads, band, table, offsets, scale, cap } => {+                let x = computed(q.0, id_map, emit_tensors);+                let y_in = computed(k.0, id_map, emit_tensors);+                let y = computed(out.0, id_map, emit_tensors);+                let t = weights.fp16("banded table", table)?;+                nodes.push(EmittedNode {+                    op: fb::Op::Attention,+                    inputs: vec![x, y_in, t],+                    outputs: vec![y],+                    attrs: vec![+                        ("heads".into(), AttrValue::Int(heads as i32)),+                        ("band".into(), AttrValue::Int(band as i32)),+                        ("scale".into(), AttrValue::Float(scale)),+                        ("cap".into(), AttrValue::Float(cap)),+                        ("phase".into(), AttrValue::Int(6)),+                        ("rel_offsets".into(), AttrValue::Int(offsets as i32)),+                    ],+                });+            }+            Node::AttnApplyBanded { probs, v, out, heads, band } => {+                let p = computed(probs.0, id_map, emit_tensors);+                let vv = computed(v.0, id_map, emit_tensors);+                let y = computed(out.0, id_map, emit_tensors);+                nodes.push(EmittedNode {+                    op: fb::Op::Attention,+                    inputs: vec![p, vv],+                    outputs: vec![y],+                    attrs: vec![+                        ("heads".into(), AttrValue::Int(heads as i32)),+                        ("band".into(), AttrValue::Int(band as i32)),+                        ("phase".into(), AttrValue::Int(7)),+                    ],+                });+            }             Node::AttnApplyCached { probs, cache, out, heads, kv_heads, dynamic, sliding } => {                 let p = computed(probs.0, id_map, emit_tensors);                 let c = computed(cache.0, id_map, emit_tensors);@@ -913,6 +981,65 @@ fn emit_nodes(                     attrs: vec![],                 });             }+            Node::Activate { input, out, act } => {+                if matches!(act, Act::PRelu(_)) {+                    return Err("a standalone PRelu carries no slope tensor".into());+                }+                let x = computed(input.0, id_map, emit_tensors);+                let y = computed(out.0, id_map, emit_tensors);+                nodes.push(EmittedNode {+                    op: fb::Op::Activate,+                    inputs: vec![x],+                    outputs: vec![y],+                    attrs: vec![+                        ("activation".into(), AttrValue::Int(act_code(act)?)),+                    ],+                });+            }+            Node::GatedActivate { input, out, act } => {+                let x = computed(input.0, id_map, emit_tensors);+                let y = computed(out.0, id_map, emit_tensors);+                nodes.push(EmittedNode {+                    op: fb::Op::GatedSwish,+                    inputs: vec![x],+                    outputs: vec![y],+                    attrs: vec![+                        ("activation".into(), AttrValue::Int(act_code(act)?)),+                    ],+                });+            }+            Node::MulScalar { input, out, scale } => {+                let x = computed(input.0, id_map, emit_tensors);+                let y = computed(out.0, id_map, emit_tensors);+                let s = weights.fp16("mul_scalar", scale)?;+                nodes.push(EmittedNode {+                    op: fb::Op::MulScalar,+                    inputs: vec![x, s],+                    outputs: vec![y],+                    attrs: vec![],+                });+            }+            Node::Clamp { input, out, bounds } => {+                let x = computed(input.0, id_map, emit_tensors);+                let y = computed(out.0, id_map, emit_tensors);+                let b = weights.fp16("clamp bounds", bounds)?;+                nodes.push(EmittedNode {+                    op: fb::Op::Clamp,+                    inputs: vec![x, b],+                    outputs: vec![y],+                    attrs: vec![],+                });+            }+            Node::Softcap { input, out, cap } => {+                let x = computed(input.0, id_map, emit_tensors);+                let y = computed(out.0, id_map, emit_tensors);+                nodes.push(EmittedNode {+                    op: fb::Op::Softcap,+                    inputs: vec![x],+                    outputs: vec![y],+                    attrs: vec![("cap".into(), AttrValue::Float(cap))],+                });+            }             Node::Softmax { input, out, mode, sliding, window } => {                 let x = computed(input.0, id_map, emit_tensors);                 let y = computed(out.0, id_map, emit_tensors);@@ -1282,14 +1409,75 @@ pub fn emit_graphs(     // 3-5. Per graph: inputs (declaration order = binding order), nodes +     // computed tensors in first-use order, exact outputs. Each graph gets a     // fresh tensor-id map (recordings number their ids from zero) over the-    // shared weight map and allocator, so ranges stay disjoint.+    // shared weight map and allocator, so ranges stay disjoint — except+    // shared state rows (below), which name one tensor from every graph.+    //+    // Shared caches: when every graph's persistent sequence is identical+    // (same count, same shapes in pinned order — the v1 caches-first+    // invariant: prefill fills the caches decode reads), the positions name+    // ONE tensor each, so both plans address the same arena storage. Any+    // difference (a graph with no caches, a debug pass with fewer) means no+    // sharing: per-graph rows, which can only waste memory, never alias.+    // The bit-exact gate per net proves the choice: spurious sharing fails+    // numerics against the v1 oracle, which shares through arena offsets.     struct PerGraph {         nodes: Vec<EmittedNode>,         input_ids: Vec<i32>,         outputs: Vec<i32>,         name: String,     }+    // Persistent tensor ids per graph, in pinned order, with shapes.+    let persistent_seqs: Vec<Vec<(usize, Shape)>> = specs+        .iter()+        .map(|spec| {+            let recorded = spec.recorded;+            let is_input_or_output = |id: usize| {+                recorded.inputs.iter().any(|in_id| in_id.index() == id)+                    || recorded.outputs.iter().any(|out_id| out_id.index() == id)+            };+            recorded+                .pinned+                .iter()+                .map(|pinned| pinned.index())+                .filter(|id| !is_input_or_output(*id))+                .map(|id| {+                    let shape =+                        recorded.shapes.get(id).copied().unwrap_or(Shape::new(0, 0, 0));+                    (id, shape)+                })+                .collect()+        })+        .collect();+    let shared_shapes: Option<Vec<Shape>> = {+        let first = persistent_seqs.first().cloned().unwrap_or_default();+        let all_equal = !first.is_empty()+            && persistent_seqs.iter().all(|seq| {+                seq.len() == first.len()+                    && seq.iter().zip(first.iter()).all(|((_, a), (_, b))| a == b)+            });+        all_equal.then(|| first.into_iter().map(|(_, shape)| shape).collect())+    };+    // Shared v2 indices, allocated once up front so every graph maps its+    // position to the same row.+    let mut shared_state: Vec<i32> = Vec::new();     let mut emit_tensors: Vec<EmittedTensor> = Vec::new();+    if let Some(shapes) = &shared_shapes {+        for (pos, shape) in shapes.iter().enumerate() {+            let v2 = id_map.alloc();+            shared_state.push(v2);+            emit_tensors.push(EmittedTensor {+                name: format!("state{pos}"),+                dims: vec![shape.c as i32, shape.h as i32, shape.w as i32],+                dtype: fb::DType::F16,+                layout: fb::Layout::POSITION_MAJOR,+                bytes: Vec::new(),+                elems: shape.len() as u64,+                quant: WeightQuant::None,+                state: fb::StateKind::KV_CACHE,+                dim_params: vec![(0, "K".to_string(), shape.c as i32)],+            });+        }+    }     let mut graphs: Vec<PerGraph> = Vec::with_capacity(specs.len());     for spec in specs {         let recorded = spec.recorded;@@ -1315,17 +1503,21 @@ pub fn emit_graphs(             });         }         // State rows: persistent arena tensors (KV caches) are pinned, not-        // inputs — pre-seed them like inputs so node emission hits the map.-        // `pinned - inputs - outputs` is exactly the persistent set: inputs-        // and outputs pin for binding stability, the rest persist across-        // submits. Caches are POSITION_MAJOR with the live-length axis-        // declared (`K`, capacity from the recorded shape); the loader-        // allocates per session and never recycles them.-        //-        // `seen` is pre-seeded alongside: `CacheWrite` names the cache as-        // its output, and the output mapping resolves through `seen`.+        // inputs. With shared shapes (see above), position maps to the+        // shared row; otherwise each graph allocates its own rows in pinned+        // order. Either way node emission hits the map, and `seen` is seeded+        // alongside so `CacheWrite`'s cache output resolves.         let mut seen: HashMap<usize, i32> = HashMap::new();-        {+        if !shared_state.is_empty() {+            let seq = &persistent_seqs[graphs.len()];+            if seq.len() != shared_state.len() {+                return Err("shared cache count changed mid-emission".into());+            }+            for ((id, _), v2) in seq.iter().zip(shared_state.iter()) {+                id_map.computed.insert(*id, *v2);+                seen.insert(*id, *v2);+            }+        } else {             let is_input_or_output = |id: usize| {                 recorded.inputs.iter().any(|in_id| in_id.index() == id)                     || recorded.outputs.iter().any(|out_id| out_id.index() == id)@@ -1543,7 +1735,7 @@ fn assemble(                 (fb::QuantKind::PER_CHANNEL, (position + 1) as i32, 0, 0)             }             WeightQuant::Int4 { .. } => {-                (fb::QuantKind::PER_CHANNEL, (position + 1) as i32, 0, I4_BLOCK as i32)+                (fb::QuantKind::BLOCKWISE, (position + 1) as i32, 0, I4_BLOCK as i32)             }         };         let quant = fb::Quantization::new(
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 d5f1695425..e4da52874a 100644--- a/library/ml/src/main/rust/src/maml2/infer.rs+++ b/library/ml/src/main/rust/src/maml2/infer.rs@@ -491,6 +491,34 @@ fn infer_node(             let x = shape_of(inputs[0])?.dims.clone();             Ok(vec![Inferred { dims: x, layout: computed_layout }])         }+        fb::Op::Activate | fb::Op::Softcap => {+            if inputs.len() != 1 {+                return Err(err("activation wants [x]"));+            }+            let x = shape_of(inputs[0])?.dims.clone();+            Ok(vec![Inferred { dims: x, layout: computed_layout }])+        }+        fb::Op::GatedSwish => {+            // `activate(gate) * up` over a fused `[gate | up]` projection:+            // channels halve.+            if inputs.len() != 1 {+                return Err(err("GatedSwish wants [fused]"));+            }+            let x = shape_of(inputs[0])?.dims.clone();+            if x.is_empty() || x[0] % 2 != 0 {+                return Err(err(&format!("gated activation over {x:?}, whose channels are not a pair")));+            }+            let mut dims = x;+            dims[0] /= 2;+            Ok(vec![Inferred { dims, layout: computed_layout }])+        }+        fb::Op::MulScalar | fb::Op::Clamp => {+            if inputs.len() != 2 {+                return Err(err("scaled/clamped op wants [x, param]"));+            }+            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.@@ -636,8 +664,53 @@ fn infer_node(                 }                 let head_dim = cache[2] / kv_heads.max(1);                 Ok(vec![Inferred { dims: vec![heads * head_dim, 1, 1], layout: computed_layout }])+            } else if phase == 6 {+                // Banded scores: `[d, 1, T]` queries and keys give+                // `[heads, T, band]`, with the per-head relative table+                // `[heads, offsets, head_dim]`.+                if inputs.len() != 3 {+                    return Err(err("banded Attention scores wants [q, k, table]"));+                }+                let q = shape_of(inputs[0])?.dims.clone();+                let k = shape_of(inputs[1])?.dims.clone();+                let table = shape_of(inputs[2])?.dims.clone();+                let heads = attrs.int("heads")?;+                let band = attrs.int("band")?;+                let offsets = attrs.int("rel_offsets")?;+                if q.len() != 3 || k.len() != 3 {+                    return Err(err("banded Attention shapes are not sequences"));+                }+                if q[2] != k[2] {+                    return Err(err("a band is a window into one sequence, not two lengths"));+                }+                if table.len() != 3 || table[0] != heads || table[1] != offsets {+                    return Err(err(&format!(+                        "banded table {table:?} is not [heads, {offsets}, head_dim]"+                    )));+                }+                Ok(vec![Inferred { dims: vec![heads, q[2], band], layout: computed_layout }])+            } else if phase == 7 {+                // Banded apply: `[heads, T, band]` probabilities against a+                // `[d, 1, T]` sequence give `[d, 1, T]`.+                if inputs.len() != 2 {+                    return Err(err("banded Attention apply wants [probs, v]"));+                }+                let probs = shape_of(inputs[0])?.dims.clone();+                let v = shape_of(inputs[1])?.dims.clone();+                let heads = attrs.int("heads")?;+                let band = attrs.int("band")?;+                if probs.len() != 3 || v.len() != 3 {+                    return Err(err("banded Attention shapes are not [heads, T, band] / [d, 1, T]"));+                }+                if probs[0] != heads || probs[2] != band || probs[1] != v[2] {+                    return Err(err(&format!(+                        "banded probs {probs:?} do not match {heads} heads, band {band}, {T} queries",+                        T = v[2]+                    )));+                }+                Ok(vec![Inferred { dims: vec![v[0], 1, v[2]], layout: computed_layout }])             } else {-                Err(err(&format!("Attention phase {phase} is not 0..=5")))+                Err(err(&format!("Attention phase {phase} is not 0..=7")))             }         }         fb::Op::Embedding => {
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 85a66dd7bb..22396b899c 100644--- a/library/ml/src/main/rust/src/maml2/lower.rs+++ b/library/ml/src/main/rust/src/maml2/lower.rs@@ -447,6 +447,43 @@ fn lower_with_options(         }         builder.mark_read(&read);     }+    // State tensors this graph names, pre-created in file order before any+    // other allocation. Caches must land at identical arena offsets in every+    // plan sharing the file (prefill fills what decode reads), and file+    // order is the one order every lowering agrees on: the v1 caches-first+    // invariant, now a loader rule rather than a net-module convention.+    // Tensors this graph never names are not created — pinning another+    // graph's caches would bloat the arena for nothing.+    {+        let mut state: Vec<i32> = Vec::new();+        for n in 0..nodes.len() {+            let node = nodes.get(n);+            if let Some(inputs) = node.inputs() {+                for i in 0..inputs.len() {+                    let t = inputs.get(i);+                    if t >= 0+                        && tensors.get(t as usize).state() != fb::StateKind::NONE+                        && !state.contains(&t)+                    {+                        state.push(t);+                    }+                }+            }+        }+        state.sort_unstable();+        for t in state {+            let dims = tensors+                .get(t 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(format!("state tensor {t} is not [c, h, w]"));+            }+            let id = builder.persistent(Shape::new(dims[0], dims[1], dims[2]));+            ids.insert(t, id);+        }+    }     // Graph inputs first, in declaration order = binding order.     if let Some(inputs) = graph.inputs() {         for i in 0..inputs.len() {@@ -936,6 +973,41 @@ fn lower_node(             let shift = attrs.float("shift")?;             builder.affine(id_of(inputs[0])?, scale, shift)         }+        fb::Op::Activate => {+            if inputs.len() != 1 {+                return Err(err("Activate wants [x]"));+            }+            let act = act_from_code(attrs.int("activation")?).map_err(|e| err(&e))?;+            builder.activate(id_of(inputs[0])?, act)+        }+        fb::Op::GatedSwish => {+            if inputs.len() != 1 {+                return Err(err("GatedSwish wants [fused]"));+            }+            let act = act_from_code(attrs.int("activation")?).map_err(|e| err(&e))?;+            builder.gated_activate(id_of(inputs[0])?, act)+        }+        fb::Op::MulScalar => {+            if inputs.len() != 2 {+                return Err(err("MulScalar wants [x, scale]"));+            }+            let s = weight_elem(inputs[1])?;+            builder.mul_scalar_raw(id_of(inputs[0])?, s)+        }+        fb::Op::Clamp => {+            if inputs.len() != 2 {+                return Err(err("Clamp wants [x, bounds]"));+            }+            let b = weight_elem(inputs[1])?;+            builder.clamp_raw(id_of(inputs[0])?, b)+        }+        fb::Op::Softcap => {+            if inputs.len() != 1 {+                return Err(err("Softcap wants [x]"));+            }+            let cap = attrs.float("cap")?;+            builder.softcap(id_of(inputs[0])?, cap)+        }         fb::Op::Constant => {             if inputs.len() != 1 {                 return Err(err("Constant wants [weight]"));@@ -1036,8 +1108,33 @@ fn lower_node(                 let probs = id_of(inputs[0])?;                 let cache = persistent_of(builder, tensors, ids, inputs[1], node_index)?;                 builder.attn_apply_cached_raw(probs, cache, heads, kv_heads, dynamic, sliding)+            } else if phase == 6 {+                if inputs.len() != 3 {+                    return Err(err("banded Attention scores wants [q, k, table]"));+                }+                let band = attrs.int("band")? as u32;+                let scale = attrs.float("scale")?;+                let cap = attrs.float("cap")?;+                let offsets = attrs.int("rel_offsets")? as u32;+                let t = weight_elem(inputs[2])?;+                builder.attn_scores_banded_raw(+                    id_of(inputs[0])?,+                    id_of(inputs[1])?,+                    heads,+                    band,+                    t,+                    offsets,+                    scale,+                    cap,+                )+            } else if phase == 7 {+                if inputs.len() != 2 {+                    return Err(err("banded Attention apply wants [probs, v]"));+                }+                let band = attrs.int("band")? as u32;+                builder.attn_apply_banded(id_of(inputs[0])?, id_of(inputs[1])?, heads, band)             } else {-                return Err(err(&format!("Attention phase {phase} is not 0..=5")));+                return Err(err(&format!("Attention phase {phase} is not 0..=7")));             }         }         fb::Op::CacheWrite => {
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 eecc98012f..34d30bef75 100644--- a/library/ml/src/main/rust/src/maml2/parity.rs+++ b/library/ml/src/main/rust/src/maml2/parity.rs@@ -479,3 +479,125 @@ fn v2_whisper_decode_matches_v1_bit_exact() {         spread_inputs(&shapes, 13.0),     ); }++/// Shared cache rows unify, preserve numerics, and stay address-stable.+///+/// Emits the whisper decode recording TWICE into one file (two graphs with+/// identical persistent sequences, the gemma prefill/decode shape without a+/// 1.3 GB file): the emitter must fold the caches into shared rows, both+/// lowerings must address the same arena storage, and both plans must match+/// each other and the v1 oracle bit-exactly. A failure here — divergent+/// outputs, or a digest/verify error — is what a broken prefill→decode+/// handoff looks like, caught on a 74 MB file instead of gemma's 1.3 GB.+/// Skips quietly when the asset is absent.+#[test]+fn v2_shared_cache_rows_unify_and_match_v1() {+    use crate::maml2::emit::{emit_graphs, GraphSpec};+    use crate::nets::whisper;+    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/whisper-base/whisper_base.maml");+    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::WHISPER).expect("parse the v1 asset");+    let table = v1parsed.offsets();+    let tensors: Vec<WeightTensor> =+        (0..table.len()).map(|i| table.tensor(i).expect("tensor")).collect();+    let decode_a = whisper::record(&table, whisper::Mode::DecodeStep).expect("record");+    let decode_b = whisper::record(&table, whisper::Mode::DecodeStep).expect("record");+    // Thirteen roles per graph: the token plus per-layer cross K/V pairs.+    let mut role_names: Vec<String> = vec!["token".to_string()];+    for layer in 0..whisper::DECODER_LAYERS {+        role_names.push(format!("cross_k{layer}"));+        role_names.push(format!("cross_v{layer}"));+    }+    let roles: Vec<&str> = role_names.iter().map(|s| s.as_str()).collect();+    let emitted = emit_graphs(+        &tensors,+        v1parsed.data(),+        "whisper decode twice (cache-sharing probe)",+        "maml2 parity probe",+        v1parsed.source_sha256,+        &[+            GraphSpec {+                recorded: &decode_a,+                graph_name: "decode_a",+                entry_name: "decode_a",+                roles: &roles,+            },+            GraphSpec {+                recorded: &decode_b,+                graph_name: "decode_b",+                entry_name: "decode_b",+                roles: &roles,+            },+        ],+    )+    .expect("emission succeeds");+    // The two graphs share every cache row: same count, same shapes, one+    // row each. Count the KV_CACHE rows directly from the file.+    let model = crate::maml2::fb::root_as_model(&emitted.bytes).expect("the probe file parses");+    let tensors_out = model.tensors().expect("tensors");+    let mut shared = 0;+    for i in 0..tensors_out.len() {+        if tensors_out.get(i).state() == crate::maml2::fb::StateKind::KV_CACHE {+            shared += 1;+        }+    }+    assert_eq!(+        shared, 12,+        "twelve shared cache rows (six layers x K/V), found {shared}"+    );+    eprintln!("probe: {shared} shared cache rows over 2 graphs; lowering both entries");+    // Both entries lower, run, and agree with each other and the v1 oracle.+    let verified = verify::verify(&emitted.bytes).expect("verify");+    let inferred = infer::infer(&verified).expect("infer");+    assert_eq!(inferred.len(), 2);+    let bridge = lower::V2Weights::new(&verified).expect("bridge");+    let plan_a = lower::lower(&verified, &inferred[0], &bridge, 0).expect("lower a");+    let plan_b = lower::lower(&verified, &inferred[1], &bridge, 1).expect("lower b");+    // Shared rows land at identical arena offsets in both plans: the+    // prefill-fills-decode-reads contract, checked structurally.+    assert_eq!(+        plan_a.arena_elems, plan_b.arena_elems,+        "identical arenas for identical graphs"+    );+    let mut shapes = vec![(512usize, 1usize, 1usize)];+    for _ in 0..whisper::DECODER_LAYERS {+        shapes.push((512usize, 1usize, 1500usize));+        shapes.push((512usize, 1usize, 1500usize));+    }+    let inputs = spread_inputs(&shapes, 14.0);+    let refs: Vec<&[f32]> = inputs.iter().map(|v| v.as_slice()).collect();+    let v1plan = whisper::build(&table, whisper::Mode::DecodeStep).expect("build v1");+    let v1out =+        crate::nets::reference::run_multi(&v1plan, v1parsed.data(), &refs).expect("run v1");+    let blob = bridge.blob();+    let out_a = crate::nets::reference::run_multi(&plan_a, &blob, &refs).expect("run a");+    let out_b = crate::nets::reference::run_multi(&plan_b, &blob, &refs).expect("run b");+    assert_eq!(out_a.len(), v1out.len());+    assert_eq!(out_b.len(), v1out.len());+    for (index, ((a, b), v)) in out_a.iter().zip(out_b.iter()).zip(v1out.iter()).enumerate() {+        assert_eq!(a.len(), v.len(), "output {index} length");+        assert_eq!(b.len(), v.len(), "output {index} length");+        for (at, ((x, y), z)) in a.iter().zip(b.iter()).zip(v.iter()).enumerate() {+            assert!(+                x == y && y == z,+                "output {index} element {at}: graph_a {x} vs graph_b {y} vs v1 {z}"+            );+        }+    }+    // The two plans' cache bindings coincide: same rows, same offsets.+    // (Arena equality above already implies it; the bindings say it plainly.)+    assert_eq!(plan_a.pinned.len(), plan_b.pinned.len());+    for (a, b) in plan_a.pinned.iter().zip(plan_b.pinned.iter()) {+        assert_eq!((a.at, a.shape), (b.at, b.shape), "pinned bindings coincide");+    }+}
library/ml/src/main/rust/src/nets/gemma4_audio_part1.rs
diff --git a/library/ml/src/main/rust/src/nets/gemma4_audio_part1.rs b/library/ml/src/main/rust/src/nets/gemma4_audio_part1.rsindex 361693cb0c..bef6fc8daa 100644--- a/library/ml/src/main/rust/src/nets/gemma4_audio_part1.rs+++ b/library/ml/src/main/rust/src/nets/gemma4_audio_part1.rs@@ -210,6 +210,17 @@ pub const MIN_TOKENS: u32 = ATTEND_SPAN;  /// Build the pass `mode` describes. pub fn build(weights: &dyn WeightSource, mode: Mode) -> Result<Plan, String> {+    Ok(record(weights, mode)?.plan)+}++/// Record the pass `mode` describes: 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`].+/// Only `Clip` goes in shipped files (trace/sscp modes are parity tooling+/// with different output counts, which would poison multi-graph emission).+pub fn record(weights: &dyn WeightSource, mode: Mode) -> Result<crate::nets::Recorded, String> {     let frames = mode.frames();     let seq = tokens(frames);     if frames == 0 {@@ -256,7 +267,7 @@ pub fn build(weights: &dyn WeightSource, mode: Mode) -> Result<Plan, String> {             name_layer(b, index);         }         name_tail(b);-        return builder.finish(&[sscp_out, projected]);+        return builder.record(&[sscp_out, projected], &crate::weights::Offsets::empty());     }      let mut x = projected;@@ -276,14 +287,14 @@ pub fn build(weights: &dyn WeightSource, mode: Mode) -> Result<Plan, String> {         b.host_tensor(EMBED_NORM, &[OUT_DIM]);         b.host_tensor(EMBED_PROJECTION, &[OUT_DIM, OUT_DIM, 1, 1]);         b.host_tensor(EMBED_PROJECTION + 1, &[OUT_DIM]);-        return builder.finish(&[x, tail]);+        return builder.record(&[x, tail], &crate::weights::Offsets::empty());     }      // The embedder, which the exporter traced through: the result is already in text-embedding     // space and scatters straight into the decoder's prompt.     let normed = b.rms_norm(tail, EMBED_NORM, EPSILON);     let out = dense_point(b, EMBED_PROJECTION, normed, OUT_DIM);-    builder.finish(&[out])+    builder.record(&[out], &crate::weights::Offsets::empty()) }  /// One subsampling stage: `conv -> layer norm -> ReLU`, halving both axes.
library/ml/src/main/rust/src/nets/gemma4_part1.rs
diff --git a/library/ml/src/main/rust/src/nets/gemma4_part1.rs b/library/ml/src/main/rust/src/nets/gemma4_part1.rsindex d048a95aab..9344c546b7 100644--- a/library/ml/src/main/rust/src/nets/gemma4_part1.rs+++ b/library/ml/src/main/rust/src/nets/gemma4_part1.rs@@ -98,6 +98,19 @@ pub const INPUTS: usize = 4; /// `dynamic` too but must see the whole prefix. That is the one piece of this that does not yet /// have a home, and it is why [`Mode`] has a single variant rather than two. pub fn build(weights: &dyn WeightSource, pass: Pass) -> Result<Plan, String> {+    Ok(record(weights, pass)?.plan)+}++/// Record one gemma 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`].+/// Decode and prefill recordings share their cache sequence (caches-first,+/// layer order), which is what the v2 emitter unifies into shared state+/// rows; trace recordings go in no shipped file (fewer caches would poison+/// the unification).+pub fn record(weights: &dyn WeightSource, pass: Pass) -> Result<crate::nets::Recorded, String> {     let Pass { mode, context } = pass;     if !CONTEXT_TIERS.contains(&context) {         return Err(format!("a cache of {context} positions, which is not one of the tiers"));@@ -214,7 +227,7 @@ pub fn build(weights: &dyn WeightSource, pass: Pass) -> Result<Plan, String> {             name_layer(b, index);         }         name_head(b);-        return builder.finish(&[x, per_layer_inputs]);+        return builder.record(&[x, per_layer_inputs], &crate::weights::Offsets::empty());     }      if let Mode::Prefill { .. } = mode {@@ -226,7 +239,7 @@ pub fn build(weights: &dyn WeightSource, pass: Pass) -> Result<Plan, String> {         // product is the thirty caches, which are `persistent` and so are not outputs at all;         // returning `x` costs nothing, since it is already in the arena, and gives the host         // something to sanity-check a pass against.-        return builder.finish(&[x]);+        return builder.record(&[x], &crate::weights::Offsets::empty());     }      let state = b.rms_norm(x, FINAL_NORM, EPSILON);@@ -237,7 +250,7 @@ pub fn build(weights: &dyn WeightSource, pass: Pass) -> Result<Plan, String> {         let logits = point(b, at, state, CLASSES_PER_SPLIT);         outputs.push(b.softcap(logits, LOGIT_CAP));     }-    builder.finish(&outputs)+    builder.record(&outputs, &crate::weights::Offsets::empty()) }  /// Name the logits head and the final norm as host-read, for the modes that stop before them.
library/ml/src/main/rust/src/nets/gemma4_vision_part1.rs
diff --git a/library/ml/src/main/rust/src/nets/gemma4_vision_part1.rs b/library/ml/src/main/rust/src/nets/gemma4_vision_part1.rsindex 4cfd0337bc..2a37a6a08f 100644--- a/library/ml/src/main/rust/src/nets/gemma4_vision_part1.rs+++ b/library/ml/src/main/rust/src/nets/gemma4_vision_part1.rs@@ -15,6 +15,17 @@ pub const INPUTS: usize = 3;  /// Build the image pass. pub fn build(weights: &dyn WeightSource, mode: Mode) -> Result<Plan, String> {+    Ok(record(weights, mode)?.plan)+}++/// Record the image 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`].+/// Only `Image` goes in shipped files (trace mode has different outputs,+/// which would poison multi-graph emission).+pub fn record(weights: &dyn WeightSource, mode: Mode) -> Result<crate::nets::Recorded, String> {     let grid = mode.grid();     let stop_after = match mode {         Mode::Image(_) => LAYERS,@@ -58,13 +69,13 @@ pub fn build(weights: &dyn WeightSource, mode: Mode) -> Result<Plan, String> {         // Both sides of the pooling, so a tower that agrees and an output that does not can be         // told apart from a tower that never agreed.         let pooled = pool(b, x, grid);-        return builder.finish(&[x, pooled]);+        return builder.record(&[x, pooled], &crate::weights::Offsets::empty());     }      let pooled = pool(b, x, grid);     let normed = b.rms_norm(pooled, FINAL_NORM, EPSILON);     let out = dense_point(b, OUT_PROJECTION, normed, OUT_DIM);-    builder.finish(&[out])+    builder.record(&[out], &crate::weights::Offsets::empty()) }  /// Average each `POOL x POOL` block of patches into one soft token.
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 a1a5742d85..1368ec0b47 100644--- a/library/ml/src/main/rust/src/nets/mod_part6.rs+++ b/library/ml/src/main/rust/src/nets/mod_part6.rs@@ -190,6 +190,18 @@ impl<'a> Builder<'a> {         out     } +    /// [`Builder::clamp`] with a resolved bounds offset rather than a table+    /// index.+    ///+    /// As [`Builder::conv_raw`]: the loader validated shapes at inference, so+    /// lowering only translates addressing.+    pub fn clamp_raw(&mut self, input: Id, bounds: u32) -> Id {+        let shape = self.shape_of(input);+        let out = self.tensor(shape);+        self.nodes.push(Node::Clamp { input, out, bounds });+        out+    }+     /// Multiply by a **scalar held in the weights**, a `[1]` tensor at `weight_index`.     ///     /// Distinct from [`Builder::affine`], whose scale is a compile-time constant. See@@ -202,6 +214,18 @@ impl<'a> Builder<'a> {         out     } +    /// [`Builder::mul_scalar`] with a resolved scale offset rather than a+    /// table index.+    ///+    /// As [`Builder::conv_raw`]: the loader validated shapes at inference, so+    /// lowering only translates addressing.+    pub fn mul_scalar_raw(&mut self, input: Id, scale: u32) -> Id {+        let shape = self.shape_of(input);+        let out = self.tensor(shape);+        self.nodes.push(Node::MulScalar { input, out, scale });+        out+    }+     /// An [`Act`] applied on its own, for a value no convolution produced.     ///     /// Every other activation in this runtime is folded into the projection before it. A gated
library/ml/src/main/rust/src/nets/mod_part7.rs
diff --git a/library/ml/src/main/rust/src/nets/mod_part7.rs b/library/ml/src/main/rust/src/nets/mod_part7.rsindex c7e19c8b71..9f95509311 100644--- a/library/ml/src/main/rust/src/nets/mod_part7.rs+++ b/library/ml/src/main/rust/src/nets/mod_part7.rs@@ -113,6 +113,30 @@ impl<'a> Builder<'a> {         out     } +    /// [`Builder::attn_scores_banded`] with a resolved table offset rather+    /// than a table index.+    ///+    /// As [`Builder::conv_raw`]: the loader validated shapes at inference, so+    /// lowering only translates addressing.+    #[allow(clippy::too_many_arguments)]+    pub fn attn_scores_banded_raw(+        &mut self,+        q: Id,+        k: Id,+        heads: u32,+        band: u32,+        table: u32,+        offsets: u32,+        scale: f32,+        cap: f32,+    ) -> Id {+        let sq = self.shape_of(q);+        let out = self.tensor(Shape::new(heads, sq.w, band));+        self.nodes+            .push(Node::AttnScoresBanded { q, k, out, heads, band, table, offsets, scale, cap });+        out+    }+     /// Apply a `[heads, T, band]` band of probabilities to `v`, a `[d_model, 1, T]` sequence.     ///     /// The value half of [`Builder::attn_scores_banded`], with the same window: column `j` of