Modern Apps git

← Modern-Apps.git

ml: v2 cached attention, state tensors, whisper encode plus decode

Commit
583def35aae4cbdddada2066b425c89b731a9335
Author
vayun-mathur <[email protected]>
When
2026-09-14 09:58 UTC (2 months ago)
Parents
683c7ab

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 a1c98e0168..52bdfc9dab 100644--- a/library/ml/src/main/rust/examples/emit_net_maml2.rs+++ b/library/ml/src/main/rust/examples/emit_net_maml2.rs@@ -314,6 +314,56 @@ fn main() {             println!("wrote {}", out_path.display());             return;         }+        "whisper" => {+            let asset = "speech/src/main/assets/whisper-base/whisper_base.maml";+            let (data, tensors, offsets, sha) = load_v1(&root, asset, weights::graph::WHISPER);+            let encode = modelrunner::nets::whisper::record(+                &offsets,+                modelrunner::nets::whisper::Mode::Encode,+            )+            .expect("record encode");+            let decode = modelrunner::nets::whisper::record(+                &offsets,+                modelrunner::nets::whisper::Mode::DecodeStep,+            )+            .expect("record decode");+            // 13 decode inputs: the token plus per-layer cross K/V pairs.+            let mut decode_roles: Vec<String> = vec!["token".to_string()];+            for layer in 0..modelrunner::nets::whisper::DECODER_LAYERS {+                decode_roles.push(format!("cross_k{layer}"));+                decode_roles.push(format!("cross_v{layer}"));+            }+            let decode_role_refs: Vec<&str> =+                decode_roles.iter().map(|s| s.as_str()).collect();+            let emitted = emit::emit_graphs(+                &tensors,+                &data,+                "whisper-base int8 nchw (v2)",+                "maml2 emit_net_maml2",+                sha,+                &[+                    emit::GraphSpec {+                        recorded: &encode,+                        graph_name: "encode",+                        entry_name: "encode",+                        roles: &["mel"],+                    },+                    emit::GraphSpec {+                        recorded: &decode,+                        graph_name: "decode_step",+                        entry_name: "decode_step",+                        roles: &decode_role_refs,+                    },+                ],+            )+            .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!("whisper 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/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 dd45be0562..4b92e09a09 100644--- a/library/ml/src/main/rust/src/maml2/emit.rs+++ b/library/ml/src/main/rust/src/maml2/emit.rs@@ -72,6 +72,10 @@ struct EmittedTensor {     /// Quantization descriptor. Scales reference the emitted scale tensor by     /// its position in the emission order, filled in on a second pass.     quant: WeightQuant,+    /// State kind: KV_CACHE for persistent arena tensors, NONE otherwise.+    state: fb::StateKind,+    /// Dimension parameters `(axis, symbol, max)`, for state capacity axes.+    dim_params: Vec<(u32, String, i32)>, }  /// Weight payload of one v1 tensor, read from the data section.@@ -161,6 +165,8 @@ fn emit_weight_tensor(                 bytes,                 elems,                 quant: WeightQuant::None,+                state: fb::StateKind::NONE,+                dim_params: Vec::new(),             });         }         (WeightPayload::F16(_), WeightQuant::Int8 { .. }) => {@@ -177,6 +183,8 @@ fn emit_weight_tensor(                 bytes: bytes.clone(),                 elems: bytes.len() as u64,                 quant,+                state: fb::StateKind::NONE,+                dim_params: Vec::new(),             });             // The scale follows as its own tensor: `[out]` fp16, contiguous.             let (scale_tensor, scale_payload) = read_weight_payload(table, data, index + 1)?;@@ -194,6 +202,8 @@ fn emit_weight_tensor(                 bytes: scale_bytes,                 elems: scale_words.len() as u64,                 quant: WeightQuant::None,+                state: fb::StateKind::NONE,+                dim_params: Vec::new(),             });         }         (WeightPayload::I8(_), WeightQuant::None) => {@@ -434,6 +444,8 @@ fn emit_nodes(             bytes: Vec::new(),             elems: shape.len() as u64,             quant: WeightQuant::None,+                state: fb::StateKind::NONE,+                dim_params: Vec::new(),         });         index     };@@ -853,6 +865,54 @@ fn emit_nodes(                     attrs: vec![("rows".into(), AttrValue::Int(rows as i32))],                 });             }+            Node::AttnScoresCached { q, cache, out, heads, kv_heads, scale, dynamic, sliding } => {+                let x = computed(q.0, id_map, emit_tensors);+                let c = computed(cache.0, id_map, emit_tensors);+                let y = computed(out.0, id_map, emit_tensors);+                nodes.push(EmittedNode {+                    op: fb::Op::Attention,+                    inputs: vec![x, c],+                    outputs: vec![y],+                    attrs: vec![+                        ("heads".into(), AttrValue::Int(heads as i32)),+                        ("kv_heads".into(), AttrValue::Int(kv_heads as i32)),+                        ("scale".into(), AttrValue::Float(scale)),+                        ("phase".into(), AttrValue::Int(4)),+                        ("dynamic".into(), AttrValue::Bool(dynamic)),+                        ("sliding".into(), AttrValue::Bool(sliding)),+                    ],+                });+            }+            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);+                let y = computed(out.0, id_map, emit_tensors);+                nodes.push(EmittedNode {+                    op: fb::Op::Attention,+                    inputs: vec![p, c],+                    outputs: vec![y],+                    attrs: vec![+                        ("heads".into(), AttrValue::Int(heads as i32)),+                        ("kv_heads".into(), AttrValue::Int(kv_heads as i32)),+                        ("phase".into(), AttrValue::Int(5)),+                        ("dynamic".into(), AttrValue::Bool(dynamic)),+                        ("sliding".into(), AttrValue::Bool(sliding)),+                    ],+                });+            }+            Node::CacheWrite { row, cache } => {+                let r = computed(row.0, id_map, emit_tensors);+                let c = computed(cache.0, id_map, emit_tensors);+                // The cache is both operand and output: one writer per graph+                // (one CacheWrite per cache per submit), so SSA holds within+                // the graph and the state persists across submits.+                nodes.push(EmittedNode {+                    op: fb::Op::CacheWrite,+                    inputs: vec![r, c],+                    outputs: vec![c],+                    attrs: vec![],+                });+            }             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);@@ -1195,6 +1255,8 @@ pub fn emit_graphs(                 bytes: Vec::new(),                 elems: u64::from(tensor.len),                 quant: WeightQuant::None,+                state: fb::StateKind::NONE,+                dim_params: Vec::new(),             });             continue;         }@@ -1248,11 +1310,52 @@ pub fn emit_graphs(                 bytes: Vec::new(),                 elems: shape.len() as u64,                 quant: WeightQuant::None,+                state: fb::StateKind::NONE,+                dim_params: Vec::new(),             });         }-        // `emit_nodes` allocates computed tensors in first-use order and-        // records tensor-id → v2-index in `seen`.+        // 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`.         let mut seen: HashMap<usize, i32> = HashMap::new();+        {+            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)+            };+            for pinned in &recorded.pinned {+                let id = pinned.index();+                if is_input_or_output(id) || id_map.computed.contains_key(&id) {+                    continue;+                }+                let shape =+                    recorded.shapes.get(id).copied().unwrap_or(Shape::new(0, 0, 0));+                let v2 = id_map.alloc();+                id_map.computed.insert(id, v2);+                seen.insert(id, v2);+                emit_tensors.push(EmittedTensor {+                    name: format!("state{id}"),+                    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)],+                });+            }+        }+        // `emit_nodes` allocates computed tensors in first-use order and+        // records tensor-id → v2-index in `seen` (which already holds the+        // pre-seeded state rows).         let nodes = emit_nodes(recorded, &mut id_map, &weights, &mut emit_tensors, &mut seen)?;          // Outputs: the v2 index of each recorded output tensor id. Exact —@@ -1468,24 +1571,38 @@ fn assemble(         };         let placement =             if tensor.bytes.is_empty() { fb::Placement::HOST } else { fb::Placement::DEVICE };+        // State rows (KV caches) carry dim_params for their capacity axis;+        // everything else carries none.+        let mut param_offsets = Vec::with_capacity(tensor.dim_params.len());+        for (axis, symbol, max) in &tensor.dim_params {+            let symbol = builder.create_string(symbol);+            param_offsets.push(fb::DimParam::create(+                builder,+                &fb::DimParamArgs { axis: *axis, symbol: Some(symbol), max: *max },+            ));+        }+        let dim_params =+            (!param_offsets.is_empty()).then(|| builder.create_vector(&param_offsets));         tensors.push(fb::Tensor::create(             builder,             &fb::TensorArgs {                 name: Some(name),                 dtype: tensor.dtype,                 dims: Some(dims),-                dim_params: None,+                dim_params,                 layout: tensor.layout,                 quantization: Some(&quant),                 buffer,                 buffer_offset,                 elem_count: tensor.elems,                 placement,-                state: fb::StateKind::NONE,+                state: tensor.state,             },         ));     }-    // Computed + input tensors: dtype F16, CB4, no buffer, no quant.+    // Computed + input tensors: dtype F16, no buffer, no quant. State rows+    // (KV caches) carry their state kind, layout, and dim_params from the+    // emission; the rest are plain NCHW device tensors.     // Their v2 indices continue after the weights; node refs already assume     // that order (inputs allocated after weights, computed in first-use     // order matching `emit_tensors` push order).@@ -1493,20 +1610,30 @@ fn assemble(         let name = builder.create_string(&tensor.name);         let dims = builder.create_vector(&tensor.dims);         let quant = fb::Quantization::new(fb::QuantKind::NONE, -1, -1, 0, 0);+        let mut param_offsets = Vec::with_capacity(tensor.dim_params.len());+        for (axis, symbol, max) in &tensor.dim_params {+            let symbol = builder.create_string(symbol);+            param_offsets.push(fb::DimParam::create(+                builder,+                &fb::DimParamArgs { axis: *axis, symbol: Some(symbol), max: *max },+            ));+        }+        let dim_params =+            (!param_offsets.is_empty()).then(|| builder.create_vector(&param_offsets));         tensors.push(fb::Tensor::create(             builder,             &fb::TensorArgs {                 name: Some(name),                 dtype: tensor.dtype,                 dims: Some(dims),-                dim_params: None,+                dim_params,                 layout: tensor.layout,                 quantization: Some(&quant),                 buffer: -1,                 buffer_offset: 0,                 elem_count: tensor.elems,                 placement: fb::Placement::DEVICE,-                state: fb::StateKind::NONE,+                state: tensor.state,             },         ));     }
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 146a8c5fcb..d5f1695425 100644--- a/library/ml/src/main/rust/src/maml2/infer.rs+++ b/library/ml/src/main/rust/src/maml2/infer.rs@@ -158,12 +158,18 @@ fn infer_graph(     }     // Weight tensors (buffer >= 0) and host tensors (no buffer, PLACEMENT host)     // are file facts: seed from stored rows so node inference can read them.+    // State tensors (KV caches, PINNED) seed the same way: capacity, not+    // data — the loader allocates per session and the plan addresses the+    // recorded maxima.     for t in 0..tensors.len() as i32 {         if shapes.contains_key(&t) {             continue;         }         let tensor = tensors.get(t as usize);-        if tensor.buffer() != -1 || tensor.placement() == fb::Placement::HOST {+        if tensor.buffer() != -1+            || tensor.placement() == fb::Placement::HOST+            || tensor.state() != fb::StateKind::NONE+        {             shapes.insert(t, Inferred { dims: stored_dims(tensors, t)?, layout: tensor.layout() });         }     }@@ -190,6 +196,40 @@ fn infer_graph(                 ));             }         }+        // CacheWrite appends to a state tensor rather than defining one: its+        // output must be an already-defined state tensor (one writer per+        // graph, persisting across submits). Digest and continue — no shape+        // is derived, and the single-writer rule below does not apply.+        if node.op() == fb::Op::CacheWrite {+            if inputs.len() != 2 || outputs.len() != 1 {+                return Err(format!(+                    "graph {graph_index} ({name}): node {n} (CacheWrite) wants [row, cache] -> [cache]"+                ));+            }+            if outputs[0] != inputs[1] {+                return Err(format!(+                    "graph {graph_index} ({name}): node {n} (CacheWrite) writes tensor {} but reads cache {}",+                    outputs[0], inputs[1]+                ));+            }+            let attrs = node.attrs().map(|v| Attrs { attrs: v });+            if shapes.get(&outputs[0]).is_none() {+                return Err(format!(+                    "graph {graph_index} ({name}): node {n} (CacheWrite) targets undefined tensor {}",+                    outputs[0]+                ));+            }+            // The target must be a state tensor: appending to a computed+            // tensor would fork SSA with no writer to blame.+            if tensors.get(outputs[0] as usize).state() == fb::StateKind::NONE {+                return Err(format!(+                    "graph {graph_index} ({name}): node {n} (CacheWrite) targets non-state tensor {}",+                    outputs[0]+                ));+            }+            digest_node(&mut hasher, &node, attrs.as_ref())?;+            continue;+        }         // Single-writer SSA: no output may already be defined.         for output in &outputs {             if defined.contains(output) {@@ -561,8 +601,43 @@ fn infer_node(                     )));                 }                 Ok(vec![Inferred { dims: vec![v[0], 1, probs[1]], layout: computed_layout }])+            } else if phase == 4 {+                // One query against a position-major K cache: `[d, 1, 1]`+                // and `[K, 1, kv_heads * head_dim]` give `[heads, 1, K]`.+                // Live lengths arrive per submit as step uniforms; the plan+                // is built at the recorded maxima.+                if inputs.len() != 2 {+                    return Err(err("cached Attention scores wants [q, cache]"));+                }+                let q = shape_of(inputs[0])?.dims.clone();+                let cache = shape_of(inputs[1])?.dims.clone();+                let heads = attrs.int("heads")?;+                let kv_heads = attrs.opt_int("kv_heads")?.unwrap_or(heads);+                if q.len() != 3 || cache.len() != 3 {+                    return Err(err("cached Attention shapes are not [d, 1, 1] / [K, 1, w]"));+                }+                if q[1] != 1 || q[2] != 1 || cache[1] != 1 {+                    return Err(err("a decode step is one query against [K, 1, w] positions"));+                }+                Ok(vec![Inferred { dims: vec![heads, 1, cache[0]], layout: computed_layout }])+            } else if phase == 5 {+                // A `[heads, 1, K]` probability row against a position-major+                // V cache gives one `[d_model, 1, 1]` query result, where+                // d_model is the query side's width (GQA: kv_heads <= heads).+                if inputs.len() != 2 {+                    return Err(err("cached Attention apply wants [probs, cache]"));+                }+                let probs = shape_of(inputs[0])?.dims.clone();+                let cache = shape_of(inputs[1])?.dims.clone();+                let heads = attrs.int("heads")?;+                let kv_heads = attrs.opt_int("kv_heads")?.unwrap_or(heads);+                if probs.len() != 3 || cache.len() != 3 {+                    return Err(err("cached Attention shapes are not [heads, 1, K] / [K, 1, w]"));+                }+                let head_dim = cache[2] / kv_heads.max(1);+                Ok(vec![Inferred { dims: vec![heads * head_dim, 1, 1], layout: computed_layout }])             } else {-                Err(err(&format!("Attention phase {phase} is not 0, 1, 2, or 3")))+                Err(err(&format!("Attention phase {phase} is not 0..=5")))             }         }         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 a9743fefb8..85a66dd7bb 100644--- a/library/ml/src/main/rust/src/maml2/lower.rs+++ b/library/ml/src/main/rust/src/maml2/lower.rs@@ -611,6 +611,40 @@ fn rewrite_blocked_kinds(     Ok(()) } +/// Resolve a cache tensor to its persistent builder Id, creating it first.+///+/// State tensors are arena storage, not values: the first node that names+/// one (a `CacheWrite`, a cached attention) allocates it via+/// [`Builder::persistent`] at the file's recorded shape, and later nodes+/// reuse the Id. Anything else — a cache named with a non-state row, or a+/// state row with a rank the arena cannot hold — is a corrupt file.+fn persistent_of(+    builder: &mut Builder<'_>,+    tensors: &flatbuffers::Vector<'_, flatbuffers::ForwardsUOffset<fb::Tensor<'_>>>,+    ids: &mut HashMap<i32, Id>,+    t: i32,+    node_index: usize,+) -> Result<Id, String> {+    let err = |what: &str| format!("node {node_index}: {what}");+    if let Some(id) = ids.get(&t).copied() {+        return Ok(id);+    }+    if tensors.get(t as usize).state() == fb::StateKind::NONE {+        return Err(err(&format!("tensor {t} is not a state tensor")));+    }+    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(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);+    Ok(id)+}+ /// Lower one v2 node through the matching `*_raw` builder. fn lower_node(     builder: &mut Builder<'_>,@@ -978,9 +1012,50 @@ fn lower_node(                     t,                     offsets,                 )+            } else if phase == 4 {+                if inputs.len() != 2 {+                    return Err(err("cached Attention scores wants [q, cache]"));+                }+                let scale = attrs.float("scale")?;+                let kv_heads = attrs.opt_int("kv_heads").unwrap_or(heads as i32) as u32;+                let dynamic = attrs.opt_bool("dynamic");+                let sliding = attrs.opt_bool("sliding");+                // `id_of` before `persistent_of`: the closure borrows `ids`+                // immutably, and the borrow must be dead before the mutable+                // cache allocation on this path.+                let q = id_of(inputs[0])?;+                let cache = persistent_of(builder, tensors, ids, inputs[1], node_index)?;+                builder.attn_scores_cached_raw(q, cache, heads, kv_heads, scale, dynamic, sliding)+            } else if phase == 5 {+                if inputs.len() != 2 {+                    return Err(err("cached Attention apply wants [probs, cache]"));+                }+                let kv_heads = attrs.opt_int("kv_heads").unwrap_or(heads as i32) as u32;+                let dynamic = attrs.opt_bool("dynamic");+                let sliding = attrs.opt_bool("sliding");+                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 {-                return Err(err(&format!("Attention phase {phase} is not 0, 1, 2, or 3")));+                return Err(err(&format!("Attention phase {phase} is not 0..=5")));+            }+        }+        fb::Op::CacheWrite => {+            if inputs.len() != 2 || outputs.len() != 1 {+                return Err(err("CacheWrite wants [row, cache] -> [cache]"));+            }+            if outputs[0] != inputs[1] {+                return Err(err("CacheWrite output is not its cache input"));             }+            let row = id_of(inputs[0])?;+            let cache =+                persistent_of(builder, tensors, ids, inputs[1], node_index)?;+            builder.cache_write(row, cache);+            // The cache Id is the output: record it so downstream nodes and+            // the graph-output mapping resolve. (The builder holds no new+            // tensor — the cache persists.)+            ids.insert(outputs[0], cache);+            return Ok(());         }         fb::Op::Embedding => {             if inputs.len() != 2 {
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 b55275c8e6..eecc98012f 100644--- a/library/ml/src/main/rust/src/maml2/parity.rs+++ b/library/ml/src/main/rust/src/maml2/parity.rs@@ -442,3 +442,40 @@ fn v2_tinyclip_text_matches_v1_bit_exact() {         spread_inputs(&[(256usize, 1usize, 16usize)], 11.0),     ); }++/// True numeric parity for whisper's encoder: entry 0 of the+/// encode/decode file.+#[test]+fn v2_whisper_encode_matches_v1_bit_exact() {+    use crate::nets::whisper;+    assert_bit_exact(+        "whisper encode",+        "speech/src/main/assets/whisper-base/whisper_base.maml",+        weights::graph::WHISPER,+        "speech/src/main/assets/whisper-base/whisper_base.maml2",+        0,+        |offsets| whisper::build(offsets, whisper::Mode::Encode),+        spread_inputs(&[(80usize, 1usize, 3000usize)], 12.0),+    );+}++/// True numeric parity for one whisper decode step: entry 1. Caches start+/// zeroed on both sides (the first step); the cross K/V arrive as inputs.+#[test]+fn v2_whisper_decode_matches_v1_bit_exact() {+    use crate::nets::whisper;+    let mut shapes = vec![(512usize, 1usize, 1usize)];+    for _ in 0..whisper::DECODER_LAYERS {+        shapes.push((512usize, 1usize, 1500usize));+        shapes.push((512usize, 1usize, 1500usize));+    }+    assert_bit_exact(+        "whisper decode step",+        "speech/src/main/assets/whisper-base/whisper_base.maml",+        weights::graph::WHISPER,+        "speech/src/main/assets/whisper-base/whisper_base.maml2",+        1,+        |offsets| whisper::build(offsets, whisper::Mode::DecodeStep),+        spread_inputs(&shapes, 13.0),+    );+}
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 b89dd212b8..46a47e923c 100644--- a/library/ml/src/main/rust/src/nets/mod_part5.rs+++ b/library/ml/src/main/rust/src/nets/mod_part5.rs@@ -450,6 +450,28 @@ impl<'a> Builder<'a> {         out     } +    /// [`Builder::attn_scores_cached`] with a resolved scale and no derivation.+    ///+    /// The v2 form: the file carries the explicit `scale` (derived or folded+    /// upstream at convert time), plus the dynamic/sliding flags, so the+    /// loader passes everything through rather than re-deciding it. Shapes+    /// were validated at inference; lowering only translates addressing.+    pub fn attn_scores_cached_raw(+        &mut self,+        q: Id,+        cache: Id,+        heads: u32,+        kv_heads: u32,+        scale: f32,+        dynamic: bool,+        sliding: bool,+    ) -> Id {+        let sc = self.shape_of(cache);+        let out = self.tensor(Shape::new(heads, 1, sc.c));+        self.nodes.push(Node::AttnScoresCached { q, cache, out, heads, kv_heads, scale, dynamic, sliding });+        out+    }+     /// One query's attention output against a **position-major** V cache.     ///     /// `probs` is `[heads, 1, keys]` and `cache` is `[keys, 1, d_model]`, giving
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 8bd457dd5d..a1a5742d85 100644--- a/library/ml/src/main/rust/src/nets/mod_part6.rs+++ b/library/ml/src/main/rust/src/nets/mod_part6.rs@@ -57,6 +57,28 @@ impl<'a> Builder<'a> {         out     } +    /// [`Builder::attn_apply_cached`] with the key count and grouping carried+    /// through rather than derived.+    ///+    /// The v2 form, beside [`Builder::attn_scores_cached_raw`]: dynamic,+    /// sliding, and kv_heads ride the file, so the loader passes them+    /// through rather than re-deciding them.+    pub fn attn_apply_cached_raw(+        &mut self,+        probs: Id,+        cache: Id,+        heads: u32,+        kv_heads: u32,+        dynamic: bool,+        sliding: bool,+    ) -> Id {+        let sc = self.shape_of(cache);+        let head_dim = sc.w.checked_div(kv_heads.max(1)).unwrap_or(0);+        let out = self.tensor(Shape::new(heads * head_dim, 1, 1));+        self.nodes.push(Node::AttnApplyCached { probs, cache, out, heads, kv_heads, dynamic, sliding });+        out+    }+     /// The same elements under a different shape, as one contiguous copy.     ///     /// A projection writes `[d_model, 1, 1]` and a position-major cache is `[T, 1, d_model]`, so
library/ml/src/main/rust/src/nets/nllb.rs
diff --git a/library/ml/src/main/rust/src/nets/nllb.rs b/library/ml/src/main/rust/src/nets/nllb.rsindex 3945f3e687..629fcb4ad7 100644--- a/library/ml/src/main/rust/src/nets/nllb.rs+++ b/library/ml/src/main/rust/src/nets/nllb.rs@@ -92,7 +92,6 @@  use super::{Act, Builder, Id, Plan, Shape, WeightSource}; use crate::weights::Reader;-use super::nllb_extra2::decode_step;  /// Channels throughout: `d_model`. pub const D_MODEL: u32 = 1024;@@ -268,14 +267,30 @@ pub(crate) fn feed_forward(b: &mut Builder, l: &mut Layers, x: Id) -> Id {  /// Build one of NLLB's two passes. See [`Mode`]. pub fn build(weights: &dyn WeightSource, mode: Mode) -> Result<Plan, String> {+    Ok(record(weights, mode)?.plan)+}++/// Record one of NLLB's two passes: 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 bodies verbatim. See [`Builder::record`].+/// Each pass names the other's tensors host (the multi-pass file idiom);+/// the union check lives in the v2 emitter, which holds both recordings.+pub fn record(weights: &dyn WeightSource, mode: Mode) -> Result<crate::nets::Recorded, String> {     match mode {-        Mode::Encode { len } => encode(weights, len),-        Mode::DecodeStep { src_len } => decode_step(weights, src_len),+        Mode::Encode { len } => encode_record(weights, len),+        Mode::DecodeStep { src_len } => super::nllb_extra2::decode_step_record(weights, src_len),     } }  /// The encoder over `len` already-embedded positions. fn encode(weights: &dyn WeightSource, len: u32) -> Result<Plan, String> {+    Ok(encode_record(weights, len)?.plan)+}++/// The recording behind [`encode`].+fn encode_record(weights: &dyn WeightSource, len: u32) -> Result<crate::nets::Recorded, String> {     if len == 0 {         return Err("an encoder pass over no tokens".into());     }@@ -304,7 +319,7 @@ fn encode(weights: &dyn WeightSource, len: u32) -> Result<Plan, String> {     if l.next != DECODER {         return Err(format!("the encoder norm ends at {}, not {DECODER}", l.next));     }-    builder.finish(&[out])+    builder.record(&[out], &crate::weights::Offsets::empty()) }  /// Name every tensor **outside** `read` as one this pass does not touch.
library/ml/src/main/rust/src/nets/nllb_extra2.rs
diff --git a/library/ml/src/main/rust/src/nets/nllb_extra2.rs b/library/ml/src/main/rust/src/nets/nllb_extra2.rsindex 8374690522..c47b3d4bb4 100644--- a/library/ml/src/main/rust/src/nets/nllb_extra2.rs+++ b/library/ml/src/main/rust/src/nets/nllb_extra2.rs@@ -36,6 +36,14 @@ use super::nllb::{Layers, feed_forward, name_host_tensors, point, split_classes} /// ~262 million multiply-accumulates against the whole decoder's ~200 million. Worth revisiting /// only after `Kind::ConvVecInt8` makes the head cheap. pub(crate) fn decode_step(weights: &dyn WeightSource, src_len: u32) -> Result<Plan, String> {+    Ok(decode_step_record(weights, src_len)?.plan)+}++/// The recording behind [`decode_step`].+pub(crate) fn decode_step_record(+    weights: &dyn WeightSource,+    src_len: u32,+) -> Result<crate::nets::Recorded, String> {     if src_len == 0 {         return Err("a decode step with no source to attend over".into());     }@@ -116,5 +124,5 @@ pub(crate) fn decode_step(weights: &dyn WeightSource, src_len: u32) -> Result<Pl     }     // The K and V rows are no longer outputs: they are in the cache, on the device, and the host     // never sees them again.-    builder.finish(&outputs)+    builder.record(&outputs, &crate::weights::Offsets::empty()) }
library/ml/src/main/rust/src/nets/whisper.rs
diff --git a/library/ml/src/main/rust/src/nets/whisper.rs b/library/ml/src/main/rust/src/nets/whisper.rsindex 656d14d6ed..705e96ded6 100644--- a/library/ml/src/main/rust/src/nets/whisper.rs+++ b/library/ml/src/main/rust/src/nets/whisper.rs@@ -262,14 +262,30 @@ fn cross_kv(layer: usize) -> usize {  /// Build one of whisper's two passes. See [`Mode`]. pub fn build(weights: &dyn WeightSource, mode: Mode) -> Result<Plan, String> {+    Ok(record(weights, mode)?.plan)+}++/// Record one of whisper's two passes: 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 bodies verbatim. See [`Builder::record`].+/// Each pass names the other's tensors host (the multi-pass file idiom);+/// the union check lives in the v2 emitter, which holds both recordings.+pub fn record(weights: &dyn WeightSource, mode: Mode) -> Result<crate::nets::Recorded, String> {     match mode {-        Mode::Encode => encode(weights),-        Mode::DecodeStep => decode_step(weights),+        Mode::Encode => encode_record(weights),+        Mode::DecodeStep => decode_step_record(weights),     } }  /// The audio encoder over one 30-second window, plus the twelve cross-attention caches. fn encode(weights: &dyn WeightSource) -> Result<Plan, String> {+    Ok(encode_record(weights)?.plan)+}++/// The recording behind [`encode`].+fn encode_record(weights: &dyn WeightSource) -> Result<crate::nets::Recorded, String> {     let mut builder = Builder::new(weights);     let b = &mut builder;     name_host_tensors(b, &device_tensors(Mode::Encode));@@ -332,7 +348,7 @@ fn encode(weights: &dyn WeightSource) -> Result<Plan, String> {             return Err(format!("layer {layer}'s cross cache ends at {}", cross.next));         }     }-    builder.finish(&outputs)+    builder.record(&outputs, &crate::weights::Offsets::empty()) }  /// One decoder step.@@ -353,6 +369,11 @@ fn encode(weights: &dyn WeightSource) -> Result<Plan, String> { /// | :--- | :--- | :--- | /// | 0 | `[51865, 1, 1]` | the logits, which the host argmaxes | fn decode_step(weights: &dyn WeightSource) -> Result<Plan, String> {+    Ok(decode_step_record(weights)?.plan)+}++/// The recording behind [`decode_step`].+fn decode_step_record(weights: &dyn WeightSource) -> Result<crate::nets::Recorded, String> {     let mut builder = Builder::new(weights);     let b = &mut builder;     name_host_tensors(b, &device_tensors(Mode::DecodeStep));@@ -423,7 +444,7 @@ fn decode_step(weights: &dyn WeightSource) -> Result<Plan, String> {         return Err(format!("the head claims {} tensors, not {DEC_POSITIONS}", head.next));     }     // The K and V rows are no longer outputs: they are in the cache, on the device.-    builder.finish(&[logits])+    builder.record(&[logits], &crate::weights::Offsets::empty()) }  include!("whisper_part1.rs");