Modern Apps git

← Modern-Apps.git

ml: keep MADLAD cross-attention K/V on device and argmax there

Commit
f69643feee70c33e69716fdc1279ef783e19ef56
Author
vayun-mathur <[email protected]>
When
2026-10-25 20:44 UTC (1 month ago)
Parents
4a016b0

Diff

library/ml/src/main/rust/examples/profile_net.rs
diff --git a/library/ml/src/main/rust/examples/profile_net.rs b/library/ml/src/main/rust/examples/profile_net.rsindex 566e3f09d1..cbe63cccc7 100644--- a/library/ml/src/main/rust/examples/profile_net.rs+++ b/library/ml/src/main/rust/examples/profile_net.rs@@ -10,11 +10,11 @@ use std::collections::BTreeMap; use std::time::Instant; -use modelrunner::nets::{nllb, whisper};+use modelrunner::nets::{madlad, madlad_part1, nllb, whisper}; use modelrunner::vulkan::context; use modelrunner::vulkan::reshape::Reshaped; use modelrunner::vulkan::run::{Net, StepParams};-use modelrunner::weights::{graph, Weights};+use modelrunner::weights::{graph, Streamed, Weights};  /// Source tokens. A longish sentence, so cross-attention costs show. const SRC_LEN: u32 = 32;@@ -28,7 +28,8 @@ fn main() {     let result = match model {         "nllb" => nllb_profile(args.get(1).map(String::as_str)),         "whisper" => whisper_profile(args.get(1).map(String::as_str)),-        other => Err(format!("unknown model {other:?}; known: nllb, whisper")),+        "madlad" => madlad_profile(args.get(1).map(String::as_str)),+        other => Err(format!("unknown model {other:?}; known: nllb, whisper, madlad")),     };     if let Err(why) = result {         println!("failed: {why}");@@ -175,6 +176,93 @@ fn whisper_profile(path: Option<&str>) -> Result<(), String> {     Ok(()) } +/// Whether a MADLAD decode step takes the encoder output as an input. True at HEAD; false once the+/// encode pass leaves the cross-attention K and V on the device.+const MADLAD_STEP_TAKES_ENCODED: bool = false;++/// MADLAD over a fixed 32-token source: three sentences of 24 greedy steps, ids and checksum+/// printed so two builds can be compared. Streamed, because the file is a gigabyte.+fn madlad_profile(path: Option<&str>) -> Result<(), String> {+    const SRC_LEN: u32 = 32;+    const STEPS: u32 = 24;+    let path = path+        .map(str::to_owned)+        .or_else(|| std::env::var("MODELRUNNER_MADLAD").ok())+        .ok_or("pass the madlad400.maml path or set MODELRUNNER_MADLAD")?;+    let file = std::fs::File::open(&path).map_err(|e| format!("cannot open {path}: {e}"))?;+    let len = file.metadata().map_err(|e| format!("cannot size {path}: {e}"))?.len();+    let weights = Streamed::open(file, 0, len, graph::MADLAD)?;+    let context = context::shared()?;++    let started = Instant::now();+    let mut net = Reshaped::streamed(+        context,+        weights.offsets(),+        &weights,+        madlad::Mode::Encode { len: SRC_LEN },+        |offsets, mode| madlad::build(offsets, mode),+    )?;+    println!("load      {:>8.1} ms (upload + first record)", ms(started));++    // A target tag then ordinary pieces then `</s>`, ids well inside the vocabulary.+    let mut source: Vec<u32> = vec![256_000 - 1_000];+    source.extend((0..SRC_LEN - 2).map(|i| 500 + i * 41));+    source.push(1);+    let embedded = madlad_part1::embed_positions(weights.reader(), &source, 0)?;+    let queries: Vec<u32> = (0..SRC_LEN).collect();+    let enc_bias =+        madlad_part1::relative_bias(weights.reader(), madlad::TABLE_ENC, &queries, &queries, true)?;++    let mut encode_ms = Vec::new();+    let mut step_ms = Vec::new();+    let mut ids = Vec::new();+    for round in 0..3 {+        let t = Instant::now();+        let out = net.at(madlad::Mode::Encode { len: SRC_LEN })?.infer_raw_many(&[&embedded, &enc_bias])?;+        encode_ms.push(ms(t));+        let encoded = out.into_iter().next().ok_or("the encoder returned nothing")?;++        let mut token = 0u32;+        for step in 0..STEPS {+            let row = madlad_part1::embed_positions(weights.reader(), &[token], step)?;+            let keys: Vec<u32> = (0..=step).collect();+            let live = madlad_part1::relative_bias(weights.reader(), madlad::TABLE_DEC, &[step], &keys, false)?;+            let width = madlad::MAX_DECODE_POSITIONS as usize;+            let mut bias = vec![0.0f32; madlad::HEADS as usize * width];+            for head in 0..madlad::HEADS as usize {+                bias[head * width..head * width + keys.len()]+                    .copy_from_slice(&live[head * keys.len()..(head + 1) * keys.len()]);+            }+            let at = net.at(madlad::Mode::DecodeStep { src_len: SRC_LEN })?;+            at.set_params(StepParams { prefix: step, window_start: 0 })?;+            let mut inputs: Vec<&[f32]> = vec![&row];+            if MADLAD_STEP_TAKES_ENCODED {+                inputs.push(&encoded);+            }+            inputs.push(&bias);+            let t = Instant::now();+            let out = at.infer_raw_many(&inputs)?;+            if step > 0 {+                step_ms.push(ms(t));+            }+            token = greedy(&out).unwrap_or(1).min(madlad::VOCAB - 1);+            if round == 0 {+                ids.push(token);+            }+        }+    }+    println!("encode    {}", stats(&encode_ms));+    println!("step      {}", stats(&step_ms));+    println!("ids       {ids:?}");++    let decode = net.at(madlad::Mode::DecodeStep { src_len: SRC_LEN })?;+    print_kinds("decode step", decode);+    let encode = net.at(madlad::Mode::Encode { len: SRC_LEN })?;+    encode.infer_raw_many(&[&embedded, &enc_bias])?;+    print_kinds("encode", encode);+    Ok(())+}+ /// The token from a greedy plan's `[lo, hi]` output, or the argmax of a logits plan's splits. fn greedy(out: &[Vec<f32>]) -> Option<u32> {     if let [pair] = out {
library/ml/src/main/rust/src/bridge_part10.rs
diff --git a/library/ml/src/main/rust/src/bridge_part10.rs b/library/ml/src/main/rust/src/bridge_part10.rsindex 5cc04e9bb5..08fa775e2b 100644--- a/library/ml/src/main/rust/src/bridge_part10.rs+++ b/library/ml/src/main/rust/src/bridge_part10.rs@@ -6,11 +6,10 @@ /// # One net, two passes /// /// [`Reshaped`] keyed by [`madlad::Mode`]. The encoder and the decode step (which computes the-/// untied logits head itself) are two passes over **one** ~2.9 GiB file, so two `Net`s would-/// upload it twice. A rebuild is a `device_wait_idle` and a re-record, and a decode step's cache-/// grows by one position each time, so a translation of `n` tokens costs `n + 1` of them. That is-/// the known cost of holding the KV cache on the host, and it is what a future prefix bound in-/// [`crate::nets::Push`] would remove.+/// untied logits head itself) are two passes over **one** ~1 GiB file, so two `Net`s would+/// upload it twice. Both are keyed on the source length, so a translation pays two re-records -+/// into the encoder and back into the decode step - and the decode steps none: the step number+/// reaches the plan through [`StepParams`]. /// /// # The weights file stays open ///@@ -40,10 +39,10 @@ fn madlad_plan(offsets: &Offsets, mode: madlad::Mode) -> Result<Plan, String> {  /// The two GPU passes, as [`madlad_post::Nets`] wants them. ///-/// There is no host-side KV cache any more: the decode plan holds one in the arena and writes to-/// it in place. A sentence cannot leak into the next one because switching back to-/// [`madlad::Mode::Encode`] and out again re-records the plan, and the first step of a translation-/// writes row zero before reading anything.+/// Only the token and its bias row cross to the device per step, and only the next token comes+/// back: the self-attention KV cache and the cross-attention K and V the encoder pass computed all+/// live in the arena. A sentence cannot leak into the next one because the encoder pass rewrites+/// the cross K and V, and the first step writes self-attention row zero before reading anything. struct MadladNets<'a> {     net: &'a mut Reshaped<madlad::Mode>,     weights: &'a Streamed,@@ -58,7 +57,7 @@ impl MadladNets<'_> { }  impl madlad_post::Nets for MadladNets<'_> {-    fn encode(&mut self, source: &[u32]) -> Result<Vec<f32>, String> {+    fn encode(&mut self, source: &[u32]) -> Result<(), String> {         let len = u32::try_from(source.len()).map_err(|_| "a source longer than u32")?;         let reader = self.weights.reader();         // The embedding with no scale and no positions — T5 has neither — all on the host.@@ -68,20 +67,14 @@ impl madlad_post::Nets for MadladNets<'_> {         let queries: Vec<u32> = (0..len).collect();         let bias = madlad_part1::relative_bias(reader, madlad::TABLE_ENC, &queries, &queries, true)?;         let net = self.net.at(madlad::Mode::Encode { len })?;-        let out = one_output(net.infer_raw_many(&[&embedded, &bias])?)?;+        // The output is the encoder state, which the decode steps never need: the pass has+        // already left their cross-attention K and V in the arena.+        net.infer_raw_many(&[&embedded, &bias])?;         self.src_len = len;-        // The plan produces `[d_model, 1, len]`; the trait's contract is `[len, d_model]`. One-        // transpose here rather than a comment that disagrees with the trait.-        Ok(transpose(&out, madlad::D_MODEL as usize, source.len()))+        Ok(())     } -    fn decode_step(-        &mut self,-        token: u32,-        step: usize,-        encoded: &[f32],-    ) -> Result<Vec<f32>, String> {-        let width = madlad::D_MODEL as usize;+    fn decode_step(&mut self, token: u32, step: usize) -> Result<u32, String> {         let cache_len = u32::try_from(step).map_err(|_| "a step past u32")?;         if cache_len >= madlad::MAX_DECODE_POSITIONS {             return Err(format!(@@ -89,17 +82,11 @@ impl madlad_post::Nets for MadladNets<'_> {                 madlad::MAX_DECODE_POSITIONS             ));         }+        if self.src_len == 0 {+            return Err("a decode step before the encoder ran".into());+        }         let reader = self.weights.reader();         let embedded = madlad_part1::embed_positions(reader, &[token], cache_len)?;-        if !encoded.len().is_multiple_of(width) {-            return Err(format!("{} encoder values is not a whole number of {width}", encoded.len()));-        }-        let src_len = (encoded.len() / width) as u32;-        if src_len != self.src_len {-            return Err(format!("a step over {src_len} source positions after {}", self.src_len));-        }-        // Back to `[d_model, 1, src_len]`, which is what the cross-attention projections read.-        let source = transpose(encoded, encoded.len() / width, width);          // The step's bias row: query `step` (absolute) against keys `0..=step`, causal, from         // the decoder block-0 table. Padded with zeros to the plan width; `softmax_prefix`@@ -114,30 +101,19 @@ impl madlad_post::Nets for MadladNets<'_> {             bias[to..to + keys.len()].copy_from_slice(&row[from..from + keys.len()]);         } -        // The key no longer carries the step, so this matches after the first decode step and-        // `at` stops re-recording. The KV cache stays in the arena between submits.-        let net = self.net.at(madlad::Mode::DecodeStep { src_len })?;-        // The one thing that changes per token, and it is a memcpy rather than a re-record.+        // Keyed on the source length only, so this re-records once per translation.+        let net = self.net.at(madlad::Mode::DecodeStep { src_len: self.src_len })?;         net.set_params(StepParams { prefix: cache_len, window_start: 0 })?;-        let out = net.infer_raw_many(&[&embedded, &source, &bias])?;--        // Four logits splits and nothing else: the K and V rows are written straight into the-        // device-side cache by the plan, so there is no cache to bring back.-        if out.len() != madlad::HEAD_SPLITS {-            return Err(format!(-                "a decode step returned {} tensors, not {}",-                out.len(),-                madlad::HEAD_SPLITS-            ));-        }-        let mut logits = Vec::with_capacity(madlad::VOCAB as usize);-        for half in out.iter().take(madlad::HEAD_SPLITS) {-            logits.extend_from_slice(half);-        }-        if logits.len() != madlad::VOCAB as usize {-            return Err(format!("{} logits, not {}", logits.len(), madlad::VOCAB));+        // `Builder::argmax`'s pair: `lo = id % 2048`, `hi = id / 2048`.+        let pair = one_output(net.infer_raw_many(&[&embedded, &bias])?)?;+        let [lo, hi] = pair[..] else {+            return Err(format!("the greedy id holds {} values, not 2", pair.len()));+        };+        let id = hi as u32 * 2048 + lo as u32;+        if id >= madlad::VOCAB {+            return Err(format!("the greedy id {id} is past the {}-entry vocabulary", madlad::VOCAB));         }-        Ok(logits)+        Ok(id)     } } 
library/ml/src/main/rust/src/bridge_part2.rs
diff --git a/library/ml/src/main/rust/src/bridge_part2.rs b/library/ml/src/main/rust/src/bridge_part2.rsindex 100d9106fc..4a84a00fac 100644--- a/library/ml/src/main/rust/src/bridge_part2.rs+++ b/library/ml/src/main/rust/src/bridge_part2.rs@@ -437,9 +437,8 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_destroy<'  /// `[rows, columns]` to `[columns, rows]`. ///-/// MADLAD's encoder output crosses its `Nets` seam as `[positions, d_model]` and this runtime-/// works in `[d_model, positions]`, so it is transposed once on the way out and once per step on-/// the way back in.+/// For a host-side consumer of a channel-major tensor, which this runtime produces and most host+/// code wants position-major. fn transpose(values: &[f32], rows: usize, columns: usize) -> Vec<f32> {     let mut out = vec![0.0f32; values.len()];     for row in 0..rows {
library/ml/src/main/rust/src/nets/madlad.rs
diff --git a/library/ml/src/main/rust/src/nets/madlad.rs b/library/ml/src/main/rust/src/nets/madlad.rsindex 6ad785b405..3c42d3198a 100644--- a/library/ml/src/main/rust/src/nets/madlad.rs+++ b/library/ml/src/main/rust/src/nets/madlad.rs@@ -165,10 +165,10 @@ pub(crate) const DECODER: usize = ENCODER_NORM + 1; pub(crate) const DECODER_NORM: usize = DECODER + DECODER_LAYERS * DECODER_LAYER_TENSORS;  /// The encoder self-attention bias table: fp16 `[BUCKETS, HEADS]`, read on the host.-pub(crate) const TABLE_ENC: usize = DECODER_NORM + 1;+pub const TABLE_ENC: usize = DECODER_NORM + 1;  /// The decoder self-attention bias table. Last.-pub(crate) const TABLE_DEC: usize = TABLE_ENC + 1;+pub const TABLE_DEC: usize = TABLE_ENC + 1;  /// Tensors the `.maml` must hold, and the count `maml_convert.py` writes: 24 head + /// 640 encoder + 1 + 1056 decoder + 1 + 2 tables.@@ -263,21 +263,53 @@ fn self_attention(b: &mut Builder, l: &mut Layers, residual: Id, x: Id, bias: Id /// One pre-norm cross-attention sublayer — no bias — plus its residual. /// /// Cross-attention never carries a relative term (`has_relative_attention_bias` is false for-/// every `EncDecAttention`), so this is NLLB's shape with T5's (absent) scale.-///-/// `pub(crate)` for the decode step in `madlad_extra2`, which inlines the same sequence;-/// kept here so the two attentions read as one vocabulary.-pub(crate) fn cross_attention(b: &mut Builder, l: &mut Layers, residual: Id, queries: Id, keys: Id) -> Id {+/// every `EncDecAttention`), so this is NLLB's shape with T5's (absent) scale. The key and value+/// were projected once by [`Mode::Encode`] into `cross_k` and `cross_v`; the query is this step's.+pub(crate) fn cross_attention(+    b: &mut Builder,+    l: &mut Layers,+    residual: Id,+    queries: Id,+    cross_k: Id,+    cross_v: Id,+) -> Id {     let q = point(b, l, queries, INNER, Act::None);-    let k = point(b, l, keys, INNER, Act::None);-    let v = point(b, l, keys, INNER, Act::None);-    let scores = b.attn_scores_prescaled(q, k, HEADS);+    // Past this layer's cross K and V projections, which the encode pass read.+    l.next += 6;+    let scores = b.attn_scores_prescaled(q, cross_k, HEADS);     let probs = b.softmax(scores);-    let mixed = b.attn_apply(probs, v, HEADS);+    let mixed = b.attn_apply(probs, cross_v, HEADS);     let projected = point(b, l, mixed, D_MODEL, Act::None);     b.add(residual, projected) } +/// Where a decoder layer's cross-attention K and V projections start within the layer: after the+/// self-attention norm and four projections, the cross norm and the cross query.+pub(crate) const CROSS_KV_WITHIN_LAYER: usize = 1 + 4 * 3 + 1 + 3;++/// Decoder layer `layer`'s cross-attention K and V projections: two kernels, scales and biases.+///+/// [`Mode::Encode`] reads them and [`Mode::DecodeStep`] does not.+pub(crate) fn cross_kv(layer: usize) -> std::ops::Range<usize> {+    let start = DECODER + layer * DECODER_LAYER_TENSORS + CROSS_KV_WITHIN_LAYER;+    start..start + 6+}++/// Every decoder layer's cross-attention K and V, `[INNER, 1, src_len]` each, held on the device.+///+/// Must be the first pinned tensors either pass declares: [`Builder::finish`] gives pinned tensors+/// their arena offsets in declaration order, which is what puts these at the same place in both+/// plans. See `nets::nllb` for the same constraint.+pub(crate) fn declare_cross_caches(b: &mut Builder, src_len: u32) -> Vec<(Id, Id)> {+    (0..DECODER_LAYERS)+        .map(|_| {+            let k = b.persistent(Shape::new(INNER, 1, src_len));+            let v = b.persistent(Shape::new(INNER, 1, src_len));+            (k, v)+        })+        .collect()+}+ /// The pre-norm GEGLU feed-forward sublayer, plus its residual. /// /// `wo(GELU(wi_0(x)) * wi_1(x))` over the converter's fused `[wi_0 | wi_1]` projection:@@ -309,11 +341,14 @@ fn encode(weights: &dyn WeightSource, len: u32) -> Result<Plan, String> {     let l = &mut Layers { next: ENCODER };     let mut builder = Builder::new(weights);     let b = &mut builder;-    // The two heads, the whole decoder and the two bias tables belong elsewhere. The-    // trailing encoder norm is part of this range, so it runs to `DECODER` rather than-    // to `ENCODER_NORM`.-    name_host_tensors(b, std::slice::from_ref(&(ENCODER..DECODER)));-+    // The two heads, the decoder and the two bias tables belong elsewhere, except the decoder's+    // cross-attention K and V projections, which run here once per sentence. The trailing encoder+    // norm is part of the first range, so it runs to `DECODER` rather than to `ENCODER_NORM`.+    let mut read = vec![ENCODER..DECODER];+    read.extend((0..DECODER_LAYERS).map(cross_kv));+    name_host_tensors(b, &read);++    let caches = declare_cross_caches(b, len);     let x = b.input(Shape::new(D_MODEL, 1, len));     let bias = b.input(Shape::new(HEADS, len, len));     let mut x = x;@@ -329,6 +364,15 @@ 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));     }+    for (layer, &(cache_k, cache_v)) in caches.iter().enumerate() {+        let kv = &mut Layers { next: cross_kv(layer).start };+        let k = point(b, kv, out, INNER, Act::None);+        let v = point(b, kv, out, INNER, Act::None);+        b.copy_into(k, cache_k);+        b.copy_into(v, cache_v);+    }+    // The encoder state stays the output, although the host no longer needs it: a pass must have+    // one, and a persistent tensor cannot be one without being pinned twice.     builder.finish(&[out]) } 
library/ml/src/main/rust/src/nets/madlad_extra.rs
diff --git a/library/ml/src/main/rust/src/nets/madlad_extra.rs b/library/ml/src/main/rust/src/nets/madlad_extra.rsindex d4f5228274..38c0fa29cd 100644--- a/library/ml/src/main/rust/src/nets/madlad_extra.rs+++ b/library/ml/src/main/rust/src/nets/madlad_extra.rs@@ -212,20 +212,33 @@ mod tests {     }      #[test]-    fn a_decode_step_takes_the_token_the_source_and_the_bias() {+    fn a_decode_step_takes_the_token_and_the_bias_and_returns_the_next_token() {         let (_, plan) = plan(Mode::DecodeStep { src_len: LEN });-        // The token, the encoder output and the step's bias row — and nothing else: the KV-        // cache is on the device.-        assert_eq!(plan.inputs.len(), 3);+        // The token and the step's bias row - and nothing else: both kinds of cache are on the+        // device. The encoder output used to be uploaded here every step.+        assert_eq!(plan.inputs.len(), 2);         assert_eq!(plan.inputs[0].shape, Shape::new(D_MODEL, 1, 1));-        assert_eq!(plan.inputs[1].shape, Shape::new(D_MODEL, 1, LEN));-        assert_eq!(plan.inputs[2].shape, Shape::new(HEADS, 1, MAX_DECODE_POSITIONS));-        // Four logits splits, and no cache rows coming back.-        assert_eq!(plan.outputs.len(), HEAD_SPLITS);-        let classes: u32 = plan.outputs.iter().take(HEAD_SPLITS).map(|b| b.shape.c).sum();-        assert_eq!(classes, VOCAB);-        assert_eq!(plan.outputs[0].shape.c, CLASSES_PER_SPLIT);-        assert_eq!(plan.outputs[HEAD_SPLITS - 1].shape.c, CLASSES_PER_SPLIT);+        assert_eq!(plan.inputs[1].shape, Shape::new(HEADS, 1, MAX_DECODE_POSITIONS));+        // `Builder::argmax`'s two lanes, rather than 256,000 logits.+        assert_eq!(plan.outputs.len(), 1);+        assert_eq!(plan.outputs[0].shape, Shape::new(2, 1, 1));+    }++    #[test]+    fn the_encode_pass_leaves_the_cross_caches_where_the_decode_step_reads_them() {+        // Two plans agreeing on where 64 persistent tensors live. If they disagree the decoder+        // attends over the other plan's activations and still produces fluent text.+        let (_, encode) = plan(Mode::Encode { len: LEN });+        let (_, step) = plan(Mode::DecodeStep { src_len: LEN });+        let caches = DECODER_LAYERS * 2;+        assert_eq!(encode.pinned[..caches], step.pinned[..caches]);+        for binding in &encode.pinned[..caches] {+            assert_eq!(binding.shape, Shape::new(INNER, 1, LEN));+            let filled = encode.ops.iter().any(|op| {+                matches!(*op, Op::Copy { dst, elems, .. } if dst == binding.at && elems == INNER * LEN)+            });+            assert!(filled, "the encode pass never fills the cache at {}", binding.at);+        }     }      #[test]@@ -292,19 +305,21 @@ mod tests {      #[test]     fn the_head_is_four_even_splits_over_disjoint_class_ranges() {-        // Together the four splits are the whole vocabulary, which is what `post::madlad`-        // argmaxes. Even splits: 256,000 = 4 x 64,000.+        // Together the four splits are the whole vocabulary, which the device argmax reduces+        // over in one pass. Even splits: 256,000 = 4 x 64,000.         let source = Shapes::new(TENSORS);         let plan = build(&source, Mode::DecodeStep { src_len: LEN })             .expect("the step builds");-        let heads: Vec<_> = plan-            .outputs+        let argmax: Vec<_> = plan+            .ops             .iter()-            .take(HEAD_SPLITS)-            .map(|b| b.shape.c)+            .filter_map(|op| match op {+                Op::Dispatch { kind: Kind::Argmax, push, .. } => Some(push.count),+                _ => None,+            })             .collect();-        assert_eq!(heads, vec![64_000, 64_000, 64_000, 64_000]);-        assert_eq!(heads.iter().sum::<u32>(), VOCAB);+        assert_eq!(argmax, vec![VOCAB]);+        assert_eq!(split_classes(0) * HEAD_SPLITS as u32, VOCAB);     }      #[test]
library/ml/src/main/rust/src/nets/madlad_extra2.rs
diff --git a/library/ml/src/main/rust/src/nets/madlad_extra2.rs b/library/ml/src/main/rust/src/nets/madlad_extra2.rsindex 0ef8f69a18..e17f633a47 100644--- a/library/ml/src/main/rust/src/nets/madlad_extra2.rs+++ b/library/ml/src/main/rust/src/nets/madlad_extra2.rs@@ -1,9 +1,12 @@ use super::madlad::{     DECODER, DECODER_LAYERS, DECODER_NORM, D_MODEL, ENCODER, EPSILON, HEAD_LM,-    HEAD_SPLITS, HEADS, INNER, MAX_DECODE_POSITIONS, TABLE_DEC, TABLE_ENC, TENSORS,+    HEAD_SPLITS, HEADS, INNER, MAX_DECODE_POSITIONS, TABLE_ENC, }; use super::{Act, Builder, Id, Plan, Shape, WeightSource};-use super::madlad::{Layers, cross_attention, feed_forward, name_host_tensors, point, split_classes};+use super::madlad::{+    cross_attention, cross_kv, declare_cross_caches, feed_forward, name_host_tensors, point,+    split_classes, Layers,+};  /// One decoder step. ///@@ -12,17 +15,15 @@ use super::madlad::{Layers, cross_attention, feed_forward, name_host_tensors, po /// | | shape | | /// | :--- | :--- | :--- | /// | 0 | `[1024, 1, 1]` | the current token, after [`embed_positions`] |-/// | 1 | `[1024, 1, src_len]` | the encoder output, channel-major as the encoder produced it |-/// | 2 | `[16, 1, MAX]` | the step's self-attention bias row, host-computed (see below) |+/// | 1 | `[16, 1, MAX]` | the step's self-attention bias row, host-computed (see below) | ///-/// # Outputs, in declaration order+/// The encoder's contribution is not an input: [`super::madlad::Mode::Encode`] left every layer's+/// cross-attention K and V in persistent tensors at the offsets this plan declares them at. ///-/// | | shape | |-/// | :--- | :--- | :--- |-/// | 0..4 | `[64000, 1, 1]` | the four `lm_head` logits splits, concatenated by the host |+/// # Output ///-/// The K and V rows are no longer outputs: they are written straight into the device-side-/// cache by the plan, and the host never sees them again.+/// One: the greedy next token as the `[2, 1, 1]` pair [`Builder::argmax`] writes, from the four+/// `lm_head` splits concatenated on the device. 256,000 logits used to come back every token. /// /// # The bias input ///@@ -32,15 +33,6 @@ use super::madlad::{Layers, cross_attention, feed_forward, name_host_tensors, po /// followed by zeros: `softmax_prefix` normalises only the leading `prefix + 1` entries, /// and the stale tail never enters the maximum or the sum — the same bound the cached /// score map already reads.-///-/// # Why the cross-attention K and V are recomputed-///-/// As NLLB's: they depend only on the encoder output, so computing them once and caching-/// them would save thirty-two 1024x2048 projections per step. They are not cached here-/// because that would need a third pass and a second kind of persistence for a saving the-/// logits projection dwarfs: the head is ~262 million multiply-accumulates per split-set-/// against the whole decoder's ~1.6 billion. Worth revisiting only after `Kind::ConvVecInt8`-/// makes the head cheap. pub(crate) fn decode_step(weights: &dyn WeightSource, src_len: u32) -> Result<Plan, String> {     if src_len == 0 {         return Err("a decode step with no source to attend over".into());@@ -49,15 +41,22 @@ pub(crate) fn decode_step(weights: &dyn WeightSource, src_len: u32) -> Result<Pl     let l = &mut Layers { next: DECODER };     let mut builder = Builder::new(weights);     let b = &mut builder;-    // The decoder plus the logits head, which this pass computes in the same plan. The input-    // table, the whole encoder and both bias tables belong elsewhere: the tables are read-    // on the host, never by a shader, so the range ends at TABLE_ENC — ending it at-    // TABLE_DEC would leave the encoder bias table in no-man's-land (named by neither-    // pass's complement check).-    name_host_tensors(b, &[HEAD_LM..ENCODER, DECODER..TABLE_ENC]);+    // The decoder plus the logits head, minus the cross-attention K and V the encode pass ran.+    // The input table, the whole encoder and both bias tables belong elsewhere: the tables are+    // read on the host, never by a shader, so the range ends at TABLE_ENC.+    let mut read = vec![HEAD_LM..ENCODER];+    let mut at = DECODER;+    for layer in 0..DECODER_LAYERS {+        let skipped = cross_kv(layer);+        read.push(at..skipped.start);+        at = skipped.end;+    }+    read.push(at..TABLE_ENC);+    name_host_tensors(b, &read); +    // First, so the offsets match the encode pass's.+    let cross = declare_cross_caches(b, src_len);     let mut x = b.input(Shape::new(D_MODEL, 1, 1));-    let encoded = b.input(Shape::new(D_MODEL, 1, src_len));     let step_bias = b.input(Shape::new(HEADS, 1, MAX_DECODE_POSITIONS));     // Every layer's cache pair, held on the device across steps rather than handed in and out.     //@@ -73,7 +72,7 @@ pub(crate) fn decode_step(weights: &dyn WeightSource, src_len: u32) -> Result<Pl         })         .collect(); -    for &(cache_k, cache_v) in &caches {+    for (&(cache_k, cache_v), &(cross_k, cross_v)) in caches.iter().zip(&cross) {         // Self-attention, pre-norm, against the cache this step is about to extend.         let normed = b.rms_norm(x, l.take(), EPSILON);         let q = point(b, l, normed, INNER, Act::None);@@ -96,11 +95,10 @@ pub(crate) fn decode_step(weights: &dyn WeightSource, src_len: u32) -> Result<Pl         let projected = point(b, l, mixed, D_MODEL, Act::None);         x = b.add(x, projected); -        // Cross-attention over the encoder output, which is channel-major and a different length,-        // so it uses the ordinary pair rather than the cached one. No bias: cross-attention+        // Cross-attention over the K and V the encode pass left behind. No bias: cross-attention         // never carries a relative term.         let normed = b.rms_norm(x, l.take(), EPSILON);-        x = cross_attention(b, l, x, normed, encoded);+        x = cross_attention(b, l, x, normed, cross_k, cross_v);          x = feed_forward(b, l, x);     }@@ -112,14 +110,16 @@ pub(crate) fn decode_step(weights: &dyn WeightSource, src_len: u32) -> Result<Pl         return Err(format!("the decoder norm ends at {}, not {TABLE_ENC}", l.next));     } -    // The untied logits head, in the same plan: a separate pass would mean a second `rebuild`-    // and a round trip through the host for a `[1024]` vector. Four even splits of 64,000.+    // The untied logits head, in the same plan. Four even splits of 64,000, concatenated on the+    // device and reduced to the greedy token there.     let head = &mut Layers { next: HEAD_LM };-    let outputs: Vec<Id> = (0..HEAD_SPLITS)+    let splits: Vec<Id> = (0..HEAD_SPLITS)         .map(|split| point(b, head, state, split_classes(split), Act::None))         .collect();     if head.next != ENCODER {         return Err(format!("the head claims {} tensors, not {ENCODER}", head.next));     }-    builder.finish(&outputs)+    let row = b.concat(&splits);+    let id = b.argmax(row);+    builder.finish(&[id]) }
library/ml/src/main/rust/src/post/madlad.rs
diff --git a/library/ml/src/main/rust/src/post/madlad.rs b/library/ml/src/main/rust/src/post/madlad.rsindex c11ac73d19..d2d09cf040 100644--- a/library/ml/src/main/rust/src/post/madlad.rs+++ b/library/ml/src/main/rust/src/post/madlad.rs@@ -81,17 +81,17 @@ pub const MAX_TOKENS: usize = 128;  /// The two GPU stages, as a trait, so the loop below is host-testable. pub trait Nets {-    /// The encoder over the whole source sequence, returning `[source.len(), 1024]`.+    /// The encoder over the whole source sequence.     ///-    /// Run once. Its output conditions every decoder step, and the cross-attention keys and-    /// values derived from it are computed on the first step and then frozen.-    fn encode(&mut self, source: &[u32]) -> Result<Vec<f32>, String>;+    /// Run once. It leaves every decoder layer's cross-attention K and V on the device, so+    /// nothing comes back to the host.+    fn encode(&mut self, source: &[u32]) -> Result<(), String>; -    /// One decoder step: the previous token in, the logits over the vocabulary out.+    /// One decoder step: the previous token in, the greedy next token out.     ///     /// `step` is the position, so the implementation knows where in its KV cache to write and     /// which bias row to upload.-    fn decode_step(&mut self, token: u32, step: usize, encoded: &[f32]) -> Result<Vec<f32>, String>;+    fn decode_step(&mut self, token: u32, step: usize) -> Result<u32, String>; }  /// Translate `text` into the language `tag` names (e.g. `"<2en>"`).@@ -127,7 +127,7 @@ pub fn translate(     source.extend(body);     source.push(EOS); -    let encoded = nets.encode(&source)?;+    nets.encode(&source)?;     profile(&format!("madlad: encoded {} tokens", source.len()));      let mut produced: Vec<u32> = Vec::new();@@ -135,14 +135,11 @@ pub fn translate(     let t0 = std::time::Instant::now();     for step in 0..MAX_TOKENS {         let s0 = std::time::Instant::now();-        let logits = nets.decode_step(token, step, &encoded)?;+        let next = nets.decode_step(token, step)?;         let dt = s0.elapsed();         if step < 5 || step % 20 == 0 {             profile(&format!("madlad: step {step} took {}ms", dt.as_millis()));         }-        let next = argmax(&logits).ok_or_else(|| {-            format!("the decoder returned {} logits at step {step}", logits.len())-        })?;         if next == EOS {             break;         }@@ -157,24 +154,6 @@ pub fn translate(     Ok(table.decode(&produced)) } -/// The index of the largest value, or `None` for an empty slice.-///-/// Ties take the lowest index, which is what `argmax` does everywhere else and what makes a-/// greedy decode reproducible. NaN never wins, so a net that produced one degrades to picking-/// some other token rather than to whichever comparison happened first.-fn argmax(logits: &[f32]) -> Option<u32> {-    let mut best: Option<(usize, f32)> = None;-    for (index, &value) in logits.iter().enumerate() {-        if value.is_nan() {-            continue;-        }-        if best.is_none_or(|(_, top)| value > top) {-            best = Some((index, value));-        }-    }-    best.map(|(index, _)| index as u32)-}- #[cfg(test)] mod tests {     use super::*;@@ -187,39 +166,24 @@ mod tests {         source: Vec<u32>,         /// Every `(token, step)` the decoder saw.         steps: Vec<(u32, usize)>,-        vocabulary: usize,     }      impl Nets for Scripted {-        fn encode(&mut self, source: &[u32]) -> Result<Vec<f32>, String> {+        fn encode(&mut self, source: &[u32]) -> Result<(), String> {             self.source = source.to_vec();-            // One 1024-wide row per source token, as the real encoder returns.-            Ok(vec![0.5; source.len() * 1024])+            Ok(())         } -        fn decode_step(-            &mut self,-            token: u32,-            step: usize,-            encoded: &[f32],-        ) -> Result<Vec<f32>, String> {-            assert_eq!(encoded.len(), self.source.len() * 1024);+        fn decode_step(&mut self, token: u32, step: usize) -> Result<u32, String> {+            assert!(!self.source.is_empty(), "a step before the encoder ran");             self.steps.push((token, step));-            let mut logits = vec![0.0f32; self.vocabulary];-            // The scripted token wins; running off the end asks for `EOS`.-            let wanted = self.script.get(step).copied().unwrap_or(EOS);-            logits[wanted as usize] = 1.0;-            Ok(logits)+            // Running off the end of the script asks for `EOS`.+            Ok(self.script.get(step).copied().unwrap_or(EOS))         }     }      fn scripted(script: &[u32]) -> Scripted {-        Scripted {-            script: script.to_vec(),-            source: Vec::new(),-            steps: Vec::new(),-            vocabulary: 200,-        }+        Scripted { script: script.to_vec(), source: Vec::new(), steps: Vec::new() }     }      /// A table whose ids 10.. are the ASCII letters, so a script maps to readable text —@@ -305,14 +269,4 @@ mod tests {         assert!(nets.source.is_empty(), "the encoder ran on nothing");         assert!(nets.steps.is_empty(), "the decoder ran on nothing");     }--    #[test]-    fn argmax_takes_the_lowest_index_of_a_tie_and_skips_nan() {-        assert_eq!(argmax(&[1.0, 3.0, 3.0, 2.0]), Some(1));-        assert_eq!(argmax(&[f32::NAN, 1.0]), Some(1));-        assert_eq!(argmax(&[f32::NAN]), None);-        assert_eq!(argmax(&[]), None);-        // Negative logits are normal — a softmax was never taken.-        assert_eq!(argmax(&[-5.0, -1.0, -9.0]), Some(1));-    } }