ml: cache NLLB cross-attention K/V and argmax on device
- Commit
483d95eb22e7e2cb9447f9549985a057ec0ae1d9- Author
- vayun-mathur <[email protected]>
- When
- 2026-10-25 19:47 UTC (1 month ago)
- Parents
e7aadf7
Diff
library/ml/src/main/java/com/vayunmathur/library/ml/NllbHandle.kt
diff --git a/library/ml/src/main/java/com/vayunmathur/library/ml/NllbHandle.kt b/library/ml/src/main/java/com/vayunmathur/library/ml/NllbHandle.ktindex f8e16263b7..797e5c279e 100644--- a/library/ml/src/main/java/com/vayunmathur/library/ml/NllbHandle.kt+++ b/library/ml/src/main/java/com/vayunmathur/library/ml/NllbHandle.kt@@ -47,9 +47,10 @@ import java.text.Normalizer * * # Threading *- * Not thread-safe, and more sharply than the other handles here: a translation re-records- * the network once per decoded token, so two concurrent calls would interleave recordings- * of the same command buffer. A caller must hold a lock across [translate] and [close].+ * Not thread-safe: the self-attention KV cache and the cross-attention K and V live on the+ * device between calls, and a translation re-records the network on the way in, so two+ * concurrent calls would clobber each other's state. A caller must hold a lock across+ * [translate] and [close]. */ class NllbHandle private constructor(private val directory: File) : AutoCloseable { private var handle: Long = 0L
library/ml/src/main/rust/examples/check_nllb_parity.rs
diff --git a/library/ml/src/main/rust/examples/check_nllb_parity.rs b/library/ml/src/main/rust/examples/check_nllb_parity.rsindex b7bb6053f7..3c23756441 100644--- a/library/ml/src/main/rust/examples/check_nllb_parity.rs+++ b/library/ml/src/main/rust/examples/check_nllb_parity.rs@@ -144,15 +144,10 @@ fn decode( |offsets, mode| nllb::build(offsets, mode), )?; - // The encoder, once. Its output conditions every step.+ // The encoder, once. It leaves every layer's cross-attention K and V in the arena. let embedded = nllb::embed_positions(weights.reader(), &pair.source, 0)?;- let encoded = {- let at = net.at(nllb::Mode::Encode { len: src_len })?;- let out = at.infer_raw(&embedded)?;- out.into_iter().next().ok_or("the encoder returned nothing")?- };+ net.at(nllb::Mode::Encode { len: src_len })?.infer_raw(&embedded)?; - let width = nllb::D_MODEL as usize; let mut produced = Vec::new(); let mut token = EOS; for step in 0..MAX_TOKENS {@@ -165,18 +160,14 @@ fn decode( // never again. The KV cache stays in the arena between submits. let at = net.at(nllb::Mode::DecodeStep { src_len })?; at.set_params(StepParams { prefix: cache_len, window_start: 0 })?;- let out = at.infer_raw_many(&[&embedded, &encoded])?;-- let mut logits: Vec<f32> = Vec::with_capacity(nllb::VOCAB as usize);- for split in out.iter().take(nllb::HEAD_SPLITS) {- logits.extend_from_slice(split);- }- if logits.len() != nllb::VOCAB as usize {- return Err(format!("{} logits, not {} (width {width})", logits.len(), nllb::VOCAB));- }+ let out = at.infer_raw(&embedded)?;+ let pair_out = out.into_iter().next().ok_or("the step returned nothing")?;+ let [lo, hi] = pair_out[..] else {+ return Err(format!("the greedy id holds {} values, not 2", pair_out.len()));+ }; // Step 0's argmax is discarded: HuggingFace forces the target language token there.- let next = if step == 0 { pair.target } else { argmax(&logits)? };+ let next = if step == 0 { pair.target } else { hi as u32 * 2048 + lo as u32 }; if next == EOS { break; }@@ -188,20 +179,6 @@ fn decode( Ok(produced) } -/// Largest index, ties to the lowest, NaN skipped. Matches `post::translate::argmax`.-fn argmax(logits: &[f32]) -> Result<u32, String> {- 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).ok_or_else(|| "no finite logit".to_string())-}- /// Pull the pairs out of the fixture. /// /// A hand-rolled reader rather than a JSON crate: this crate's only dependencies are `ash` and
library/ml/src/main/rust/examples/report_decode_cost.rs
diff --git a/library/ml/src/main/rust/examples/report_decode_cost.rs b/library/ml/src/main/rust/examples/report_decode_cost.rsindex c105cc30c5..30e27cdfa2 100644--- a/library/ml/src/main/rust/examples/report_decode_cost.rs+++ b/library/ml/src/main/rust/examples/report_decode_cost.rs@@ -107,7 +107,8 @@ fn main() { println!(" {arena_mb:.1} MB of arena, including the KV cache it now holds"); println!(); - // A token and an encoder output. The values do not matter to the timing, only the shapes.+ // A token. The value does not matter to the timing, only the shape. The cross-attention K and+ // V the encoder pass would leave in the arena are whatever it holds, which is also fine here. let embedded = match nllb::embed_positions(weights.reader(), &[2], 0) { Ok(values) => values, Err(why) => {@@ -115,13 +116,12 @@ fn main() { return; } };- let source = vec![0.01f32; (nllb::D_MODEL * SRC_LEN) as usize]; // One discarded step: the first submit pays for pipeline warm-up and for faulting the weights // into device memory, neither of which a steady-state token pays. if let Err(why) = net .set_params(StepParams { prefix: 0, window_start: 0 })- .and_then(|()| net.infer_raw_many(&[&embedded, &source]).map(|_| ()))+ .and_then(|()| net.infer_raw(&embedded).map(|_| ())) { println!("the warm-up step failed: {why}"); return;@@ -136,7 +136,7 @@ fn main() { println!("step {step} could not set params: {why}"); return; }- if let Err(why) = net.infer_raw_many(&[&embedded, &source]) {+ if let Err(why) = net.infer_raw(&embedded) { println!("step {step} did not submit: {why}"); return; }
library/ml/src/main/rust/shaders/argmax.comp
diff --git a/library/ml/src/main/rust/shaders/argmax.comp b/library/ml/src/main/rust/shaders/argmax.compindex 37d6a3814d..d7d39cfc0f 100644--- a/library/ml/src/main/rust/shaders/argmax.comp+++ b/library/ml/src/main/rust/shaders/argmax.comp@@ -43,13 +43,14 @@ void main() { best_val[lane] = mine_val; best_idx[lane] = mine_idx; barrier();- // Lane 0 folds the 64 lane-maxima. Strict `>` keeps the FIRST index on- // ties, matching the host `argmax` loop.+ // Lane 0 folds the 64 lane-maxima. Each lane holds its own first index, but lanes interleave,+ // so an equal value from a later lane can still be the earlier index - the tie compares+ // indices, which is what keeps the FIRST index globally, matching the host `argmax` loop. if (lane == 0u) { float top_val = best_val[0]; uint top_idx = best_idx[0]; for (uint l = 1u; l < 64u; l++) {- if (best_val[l] > top_val) {+ if (best_val[l] > top_val || (best_val[l] == top_val && best_idx[l] < top_idx)) { top_val = best_val[l]; top_idx = best_idx[l]; }
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 996a838660..100d9106fc 100644--- a/library/ml/src/main/rust/src/bridge_part2.rs+++ b/library/ml/src/main/rust/src/bridge_part2.rs@@ -437,10 +437,9 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_destroy<' /// `[rows, columns]` to `[columns, rows]`. ///-/// The encoder output crosses the `translate::Nets` seam as `[positions, d_model]` and this runtime+/// 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. Eight kilobytes for a sentence, against a trait whose documented shape would-/// otherwise be wrong.+/// the way back in. 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/bridge_part3.rs
diff --git a/library/ml/src/main/rust/src/bridge_part3.rs b/library/ml/src/main/rust/src/bridge_part3.rsindex 91608968a6..0adb4e88fa 100644--- a/library/ml/src/main/rust/src/bridge_part3.rs+++ b/library/ml/src/main/rust/src/bridge_part3.rs@@ -7,10 +7,9 @@ /// /// [`Reshaped`] keyed by [`nllb::Mode`]. The encoder and the decode step (which computes the tied /// head itself) are two passes over **one** ~600 MiB 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.+/// Both plans 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 themselves pay none: the step+/// number reaches the plan through [`StepParams`], not through the key. /// /// # The weights file stays open ///@@ -32,10 +31,11 @@ fn nllb_plan(offsets: &Offsets, mode: nllb::Mode) -> Result<Plan, String> { /// The two GPU passes, as [`translate::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-/// [`nllb::Mode::Encode`] and out again re-records the plan, and the first step of a translation-/// writes row zero before reading anything.+/// Nothing but the token crosses to the device per step and nothing but 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 of a translation writes self-attention row zero before+/// reading anything. struct NllbNets<'a> { net: &'a mut Reshaped<nllb::Mode>, weights: &'a Streamed,@@ -50,27 +50,21 @@ impl NllbNets<'_> { } impl translate::Nets for NllbNets<'_> {- 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, `sqrt(d_model)` and the sinusoidal positions, all on the host. See // `nets::nllb` for why none of that is a shader. let embedded = nllb::embed_positions(reader, source, 0)?; let net = self.net.at(nllb::Mode::Encode { len })?;- let out = one_output(net.infer_raw(&embedded)?)?;+ // 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(&embedded)?; 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, nllb::D_MODEL as usize, source.len()))+ Ok(()) } - fn decode_step(- &mut self,- token: u32,- step: usize,- encoded: &[f32],- ) -> Result<Vec<f32>, String> {- let width = nllb::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 >= nllb::MAX_DECODE_POSITIONS { return Err(format!(@@ -78,43 +72,27 @@ impl translate::Nets for NllbNets<'_> { nllb::MAX_DECODE_POSITIONS )); }+ if self.src_len == 0 {+ return Err("a decode step before the encoder ran".into());+ } let reader = self.weights.reader(); // `past = step`, which is what puts this token at position `step + 2`. let embedded = nllb::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 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(nllb::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, on the+ // switch out of `Encode`.+ let net = self.net.at(nllb::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])?;-- // 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() != nllb::HEAD_SPLITS {- return Err(format!(- "a decode step returned {} tensors, not {}",- out.len(),- nllb::HEAD_SPLITS- ));- }- let mut logits = Vec::with_capacity(nllb::VOCAB as usize);- for half in out.iter().take(nllb::HEAD_SPLITS) {- logits.extend_from_slice(half);- }- if logits.len() != nllb::VOCAB as usize {- return Err(format!("{} logits, not {}", logits.len(), nllb::VOCAB));+ // `Builder::argmax`'s pair: `lo = id % 2048`, `hi = id / 2048`.+ let pair = one_output(net.infer_raw(&embedded)?)?;+ 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 >= nllb::VOCAB {+ return Err(format!("the greedy id {id} is past the {}-entry vocabulary", nllb::VOCAB)); }- Ok(logits)+ Ok(id) } } @@ -221,7 +199,7 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_translate return Ok(std::ptr::null_mut()); } // SAFETY: the caller guarantees the handle came from `createNllb` and is still live. It is- // `&mut` because a decode step re-records the net, and Kotlin serialises calls on one handle.+ // `&mut` because a translation re-records the net, and Kotlin serialises calls on one handle. let handle = unsafe { &mut *(handle as *mut NllbHandle) }; let translated = match text.try_to_string(env) { Ok(text) => run_nllb(handle, &text, source_token, target_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 3f4a01bf56..454dcbc3d2 100644--- a/library/ml/src/main/rust/src/nets/mod_part6.rs+++ b/library/ml/src/main/rust/src/nets/mod_part6.rs@@ -156,6 +156,22 @@ impl<'a> Builder<'a> { self.nodes.push(Node::CacheWrite { row, cache }); } + /// Copy `src` into `dst`, a [`Builder::persistent`] tensor of the same shape, as one+ /// [`Op::Copy`].+ ///+ /// For a pass that fills a tensor a *later, differently shaped* plan reads. Unlike+ /// [`Builder::cache_write`] it ignores the step's prefix, which belongs to the other plan.+ pub fn copy_into(&mut self, src: Id, dst: Id) {+ let (ss, sd) = (self.shape_of(src), self.shape_of(dst));+ if ss != sd {+ self.fail(format!("copying {ss:?} into {sd:?}"));+ }+ if !self.pinned.contains(&dst) {+ self.fail("copying into a tensor that is not persistent".into());+ }+ self.nodes.push(Node::Concat { parts: vec![src], out: dst });+ }+ /// Clamp to the `[min, max]` pair at `weight_index`, a `[2]` fp16 tensor. /// /// The bounds are weights rather than arguments because Gemma 4's vision tower has 177 of
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..46b8597f26 100644--- a/library/ml/src/main/rust/src/nets/nllb.rs+++ b/library/ml/src/main/rust/src/nets/nllb.rs@@ -51,8 +51,9 @@ //! //! 256,206 classes at 1024 channels is ~250 MiB of int8, and `maxStorageBufferRange`'s guaranteed //! minimum is 128 MiB — so `scripts/ml/maml_convert.py` emits the tied weight as **four**-//! tensors over disjoint class ranges, [`Mode::DecodeStep`] emits four `ConvVecInt8` ops, and-//! `post::translate` argmaxes over all four — which it already did, because it argmaxes anyway.+//! tensors over disjoint class ranges, and [`Mode::DecodeStep`] emits four `ConvVecInt8` ops, then+//! concatenates them on the device and reduces them with [`Builder::argmax`], so a step reads back+//! one token id rather than 512 KB of logits. //! //! 256,206 is not divisible by 4, so the splits are uneven: the first two hold 64,052 classes //! each and the last two 64,051 (see [`split_classes`]). No range is padded — padding would add@@ -77,6 +78,17 @@ //! exactly the model's `self.scaling`. So nothing folds a query scale, and `sqrt(d_model)` stays //! in the host gather rather than folded into the embedding. //!+//! # Cross-attention K and V are computed once per sentence+//!+//! They depend only on the encoder output, so [`Mode::Encode`] projects them with the decoder's+//! weights and copies them into persistent tensors that [`Mode::DecodeStep`] reads. Recomputing+//! them per token cost `24 * src_len` million multiply-accumulates a step, more than the rest of+//! the step put together at any realistic sentence length.+//!+//! Both passes declare those tensors first, through [`declare_cross_caches`], because+//! [`Builder::finish`] gives pinned tensors offsets in declaration order: that is what puts them at+//! the same arena offsets in both plans. See `nets::gemma4`'s caches for the same constraint.+//! //! # Pre-norm //! //! The encoder and decoder layers normalise **before** each sublayer and skip around both, and@@ -161,6 +173,10 @@ pub(crate) const ENCODER_LAYER_TENSORS: usize = 2 + 4 * 3 + 2 + 3 + 3; /// Tensors per decoder layer: an encoder layer plus a cross-attention norm and four projections. pub(crate) const DECODER_LAYER_TENSORS: usize = ENCODER_LAYER_TENSORS + 2 + 4 * 3; +/// 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 = 2 + 4 * 3 + 2 + 3;+ /// The first of the four head splits. They come first, because the embedding is read before /// anything else and the file is written in forward order. pub(crate) const HEAD: usize = 0;@@ -198,7 +214,7 @@ pub enum Mode { /// Source tokens, after [`embed_positions`]. len: u32, },- /// One decoder step: the token just produced in, its logits out.+ /// One decoder step: the token just produced in, the greedy next token out. /// /// A step is **one query** against `prefix + 1` keys — the positions already decoded plus this /// one — which is causal by construction and needs no mask.@@ -236,6 +252,27 @@ impl Layers { } } +/// 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 caches, `[d_model, 1, src_len]` each.+///+/// Must be the first pinned tensors either pass declares. See the module docs.+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(D_MODEL, 1, src_len));+ let v = b.persistent(Shape::new(D_MODEL, 1, src_len));+ (k, v)+ })+ .collect()+}+ /// A `1 x 1` convolution with an int8 kernel, which every projection here is. pub(crate) fn point(b: &mut Builder, l: &mut Layers, x: Id, out: u32, act: Act) -> Id { b.conv_int8(x, l.take3(), out, (1, 1), (1, 1), (1, 1), (0, 0, 0, 0), 1, act)@@ -286,10 +323,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 tied weight and the whole decoder belong to the other pass. 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 tied weight and the decoder belong to the other pass, except the cross-attention K and V+ // projections, which run here once. 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 mut x = x; for _ in 0..ENCODER_LAYERS {@@ -304,6 +345,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, D_MODEL, Act::None);+ let v = point(b, kv, out, D_MODEL, Act::None);+ b.copy_into(k, cache_k);+ b.copy_into(v, cache_v);+ }+ // The encoder state is still 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/nllb_extra.rs
diff --git a/library/ml/src/main/rust/src/nets/nllb_extra.rs b/library/ml/src/main/rust/src/nets/nllb_extra.rsindex d0e5c1a9e7..d1ca2fc72f 100644--- a/library/ml/src/main/rust/src/nets/nllb_extra.rs+++ b/library/ml/src/main/rust/src/nets/nllb_extra.rs@@ -71,12 +71,21 @@ mod tests { /// that read the wrong range would name the right one and still be wrong. fn read_by(mode: Mode) -> Vec<std::ops::Range<usize>> { let mut ranges = Vec::new();+ let cross: Vec<_> = (0..DECODER_LAYERS).map(cross_kv).collect(); match mode {- Mode::Encode { .. } => ranges.push(ENCODER..DECODER),+ Mode::Encode { .. } => {+ ranges.push(ENCODER..DECODER);+ ranges.extend(cross);+ } Mode::DecodeStep { .. } => {- // The decode step computes the tied head itself, so it reads both ends of the file.+ // The decode step computes the tied head itself, so it reads both ends of the file,+ // minus the cross-attention K and V the encode pass ran. ranges.push(HEAD..ENCODER);- ranges.push(DECODER..TENSORS);+ ranges.extend(+ (DECODER..TENSORS)+ .filter(|index| !cross.iter().any(|range| range.contains(index)))+ .map(|index| index..index + 1),+ ); } } ranges@@ -108,8 +117,13 @@ mod tests { *counts.entry(super::super::tests::name_of(*kind)).or_insert(0usize) += 1; } }- // Six int8 convolutions per layer: q, k, v, the output projection, fc1 and fc2.- assert_eq!(counts.get("ConvInt8"), Some(&(ENCODER_LAYERS * 6)), "{counts:?}");+ // Six int8 convolutions per layer: q, k, v, the output projection, fc1 and fc2 - and the+ // decoder's cross-attention K and V, computed here once per sentence.+ assert_eq!(+ counts.get("ConvInt8"),+ Some(&(ENCODER_LAYERS * 6 + DECODER_LAYERS * 2)),+ "{counts:?}"+ ); // Three norms per layer would be post-norm. Pre-norm is two, plus one at the end. assert_eq!(counts.get("LayerNorm"), Some(&(ENCODER_LAYERS * 2 + 1)), "{counts:?}"); assert_eq!(counts.get("AttnScores"), Some(&ENCODER_LAYERS), "{counts:?}");@@ -153,6 +167,56 @@ mod tests { } } + #[test]+ fn the_encode_pass_leaves_the_cross_caches_where_the_decode_step_reads_them() {+ // The whole of the cross-attention cache rests on this: two differently shaped plans+ // agreeing on where 24 persistent tensors are. If they disagree the decoder attends over+ // the other plan's activations - no crash, no shape error, fluent wrong output.+ 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(D_MODEL, 1, LEN));+ }++ // The encode pass writes every one of them, whole.+ let written: Vec<_> = encode+ .ops+ .iter()+ .filter_map(|op| match *op {+ Op::Copy { dst, elems, .. } => Some((dst, elems)),+ _ => None,+ })+ .collect();+ for binding in &encode.pinned[..caches] {+ assert!(+ written.contains(&(binding.at, D_MODEL * LEN)),+ "the encode pass never fills the cache at {}",+ binding.at+ );+ }++ // And the decode step's cross-attention reads them rather than anything it computed.+ let starts: Vec<u32> = encode.pinned[..caches].iter().map(|b| b.at).collect();+ let mut reads = 0;+ for op in &step.ops {+ match op {+ Op::Dispatch { kind: Kind::AttnScores, push, .. } => {+ assert!(starts.contains(&push.in1), "cross K from {}: {push:?}", push.in1);+ reads += 1;+ }+ Op::Dispatch { kind: Kind::AttnApply, push, .. } => {+ assert!(starts.contains(&push.in1), "cross V from {}: {push:?}", push.in1);+ reads += 1;+ }+ _ => {}+ }+ }+ assert_eq!(reads, caches);+ assert_no_aliasing(&encode);+ }+ #[test] fn a_decode_step_is_twelve_layers_of_two_attentions() { let (_, plan) = plan(Mode::DecodeStep { src_len: LEN });@@ -162,11 +226,12 @@ mod tests { *counts.entry(super::super::tests::name_of(*kind)).or_insert(0usize) += 1; } }- // Ten int8 convolutions per layer — two attentions of four plus fc1 and fc2 — and the four- // splits of the tied head.+ // Eight int8 convolutions per layer - the self-attention's four, the cross-attention's+ // query and output, fc1 and fc2 - and the four splits of the tied head. The cross K and V+ // are the encode pass's. assert_eq!( counts.get("ConvInt8"),- Some(&(DECODER_LAYERS * 10 + HEAD_SPLITS)),+ Some(&(DECODER_LAYERS * 8 + HEAD_SPLITS)), "{counts:?}" ); // Three norms per layer, pre-norm, plus the trailing one.@@ -184,24 +249,21 @@ mod tests { // Three residuals per layer — half of which fold into their producing // convolution's store. See `Builder::add`. assert_eq!(counts.get("Add"), Some(&18), "{counts:?}");+ // And the greedy pick, on the device.+ assert_eq!(counts.get("Argmax"), Some(&1), "{counts:?}"); assert_no_aliasing(&plan); } #[test]- fn a_decode_step_takes_only_the_token_and_the_source() {+ fn a_decode_step_takes_only_the_token_and_returns_only_the_next_one() { let (_, plan) = plan(Mode::DecodeStep { src_len: LEN });- // The token and the encoder output, and nothing else: the KV cache is on the device.- // This is the shape of the change - twenty-four cache bindings used to be uploaded on- // every token, growing by a position each time.- assert_eq!(plan.inputs.len(), 2);+ // The token, and nothing else: the self-attention cache and the cross-attention K and V are+ // on the device. The encoder output used to be uploaded here on every token.+ assert_eq!(plan.inputs.len(), 1); assert_eq!(plan.inputs[0].shape, Shape::new(D_MODEL, 1, 1));- assert_eq!(plan.inputs[1].shape, Shape::new(D_MODEL, 1, LEN));- // 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_TAIL_SPLIT);+ // `Builder::argmax`'s two lanes, rather than 256,206 logits.+ assert_eq!(plan.outputs.len(), 1);+ assert_eq!(plan.outputs[0].shape, Shape::new(2, 1, 1)); } #[test]@@ -279,27 +341,20 @@ mod tests { _ => None, }) .collect();- assert_eq!(int8.len(), DECODER_LAYERS * 10 + HEAD_SPLITS);+ assert_eq!(int8.len(), DECODER_LAYERS * 8 + HEAD_SPLITS); - // The split is not "everything": the cross-attention's key and value projections read the- // **encoder output**, which is `src_len` positions, so they stay tiled and are the only- // multi-position work a decode step does. Everything else — the four self-attention- // projections, the cross-attention's query and output, both feed-forwards and all four- // head splits — is one position.- let (vector, tiled): (Vec<_>, Vec<_>) =- int8.iter().partition(|(kind, _, _)| *kind == Kind::ConvVecInt8);- assert_eq!(vector.len(), DECODER_LAYERS * 8 + HEAD_SPLITS, "single-position");- assert_eq!(tiled.len(), DECODER_LAYERS * 2, "the cross-attention K and V");- for (kind, push, _) in &tiled {- assert_eq!(*kind, Kind::ConvPointInt8, "{push:?}");- assert_eq!(push.out_w, LEN, "{push:?}");+ // Every one of them: with the cross-attention K and V moved to the encode pass, a decode+ // step does no multi-position work at all.+ for (kind, push, _) in &int8 {+ assert_eq!(*kind, Kind::ConvVecInt8, "{push:?}"); }+ let vector = &int8; // One workgroup per group of `CONV_VEC_ROWS` output channels, 64 invocations each. // // Derived rather than written out: the group size is an occupancy tuning knob and was // eight when this was written. Hard-coding it here meant tuning it failed a test about // NLLB's decode shape, which is not what this is checking.- for (_, push, invocations) in &vector {+ for (_, push, invocations) in vector { assert_eq!(push.out_h * push.out_w, 1, "{push:?}"); assert_eq!(push.count, push.out_c.div_ceil(super::super::CONV_VEC_ROWS), "{push:?}"); assert_eq!(*invocations, push.count * 64, "{push:?}");@@ -308,19 +363,33 @@ mod tests { #[test] fn the_head_is_four_ops_over_disjoint_class_ranges() {- // Together the four splits are the whole vocabulary, which is what `post::translate`- // argmaxes. The last two splits are one class short each.+ // Together the four splits are the whole vocabulary, which is what the device argmax+ // reduces over. The last two splits are one class short each. let source = Shapes::new(TENSORS); let plan = build(&source, Mode::DecodeStep { src_len: LEN }) .expect("the step builds"); let heads: Vec<_> = plan- .outputs+ .ops .iter()- .take(HEAD_SPLITS)- .map(|b| b.shape.c)+ .filter_map(|op| match op {+ Op::Dispatch { kind: Kind::ConvVecInt8, push, .. } if push.out_c > FFN => {+ Some(push.out_c)+ }+ _ => None,+ }) .collect(); assert_eq!(heads, vec![64_052, 64_052, 64_051, 64_051]); assert_eq!(heads.iter().sum::<u32>(), VOCAB);+ // The argmax runs over all of them at once, in id order.+ let argmax: Vec<_> = plan+ .ops+ .iter()+ .filter_map(|op| match op {+ Op::Dispatch { kind: Kind::Argmax, push, .. } => Some(push.count),+ _ => None,+ })+ .collect();+ assert_eq!(argmax, vec![VOCAB]); } #[test]
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..18fad62572 100644--- a/library/ml/src/main/rust/src/nets/nllb_extra2.rs+++ b/library/ml/src/main/rust/src/nets/nllb_extra2.rs@@ -1,40 +1,25 @@ use super::nllb::{- DECODER, DECODER_LAYERS, DECODER_NORM, ENCODER, EPSILON, HEAD, HEAD_SPLITS, HEADS,- MAX_DECODE_POSITIONS, TENSORS, D_MODEL,+ DECODER, DECODER_LAYERS, DECODER_NORM, ENCODER, EPSILON, HEAD,+ HEAD_SPLITS, HEADS, MAX_DECODE_POSITIONS, TENSORS, D_MODEL, }; use super::{Act, Builder, Id, Plan, Shape, WeightSource};-use super::nllb::{Layers, feed_forward, name_host_tensors, point, split_classes};+use super::nllb::{+ cross_kv, declare_cross_caches, feed_forward, name_host_tensors, point, split_classes, Layers,+}; /// One decoder step. ///-/// # Inputs, in declaration order-///-/// | | shape | |-/// | :--- | :--- | :--- |-/// | 0 | `[1024, 1, 1]` | the current token, after [`embed_positions`] at `past = cache_len` |-/// | 1 | `[1024, 1, src_len]` | the encoder output, channel-major as the encoder produced it |-/// | 2, 3 | `[cache_len, 1, 1024]` | layer 0's self-attention K and V, position-major |-/// | 4, 5 | | layer 1's |-/// | … | | … |+/// # Inputs ///-/// The cache pair is **omitted at step 0**, where there is nothing before the current token.+/// One: the current token, `[1024, 1, 1]`, after [`embed_positions`] at `past = cache_len`. ///-/// # Outputs, in declaration order+/// The encoder's contribution is not an input. [`super::nllb::Mode::Encode`] left every layer's+/// cross-attention K and V in persistent tensors at the same arena offsets this plan declares+/// them at, and the self-attention caches are persistent too. ///-/// | | shape | |-/// | :--- | :--- | :--- |-/// | 0..4 | `[~64052, 1, 1]` | the four logits splits (the last two one class short), concatenated by the host |-/// | 4, 5 | `[1, 1, 1024]` | layer 0's new self-attention K and V, ready to append |-/// | 6, 7 | | layer 1's |-/// | … | | … |+/// # Output ///-/// # Why the cross-attention K and V are recomputed-///-/// They depend only on the encoder output, so computing them once and caching them would save-/// twelve 1024x1024 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 against the whole decoder's ~200 million. Worth revisiting-/// only after `Kind::ConvVecInt8` makes the head cheap.+/// One: the greedy next token as the `[2, 1, 1]` pair [`Builder::argmax`] writes. 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());@@ -43,18 +28,23 @@ 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 tied head, which this pass computes in the same plan. The whole encoder- // belongs to `Mode::Encode`.- name_host_tensors(b, &[HEAD..ENCODER, DECODER..TENSORS]);+ // The decoder plus the tied head, which this pass computes in the same plan, minus the+ // cross-attention K and V projections the encode pass ran. The encoder belongs to that pass.+ let mut read = vec![HEAD..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..TENSORS);+ name_host_tensors(b, &read); + // First, so the offsets match the encode pass's. See `nllb::declare_cross_caches`.+ 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));- // Every layer's cache pair, held on the device across steps rather than handed in and out.- //- // Sized for the longest decode the loop will run, not for this step, which is what lets one- // recording serve every token: the plan no longer mentions the step number, so- // `Reshaped::at` stops matching a new key and re-recording on each one. How much of each- // cache is live comes from `StepParams::prefix` at submit time.+ // Every layer's self-attention cache pair, sized for the longest decode the loop will run so+ // one recording serves every token. How much is live comes from `StepParams::prefix`. let caches: Vec<(Id, Id)> = (0..DECODER_LAYERS) .map(|_| { let k = b.persistent(Shape::new(MAX_DECODE_POSITIONS, 1, D_MODEL));@@ -63,7 +53,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.layer_norm(x, l.take(), EPSILON); let q = point(b, l, normed, D_MODEL, Act::None);@@ -73,8 +63,6 @@ pub(crate) fn decode_step(weights: &dyn WeightSource, src_len: u32) -> Result<Pl // bytes, so this is a relabelling and the write below is one contiguous copy. let k_row = b.reshaped(k_new, Shape::new(1, 1, D_MODEL)); let v_row = b.reshaped(v_new, Shape::new(1, 1, D_MODEL));- // Written into the cache at the row the step names, replacing the concatenation that- // used to copy the entire prefix on every layer of every token. b.cache_write(k_row, cache_k); b.cache_write(v_row, cache_v); let scores = b.attn_scores_cached_dynamic(q, cache_k, HEADS);@@ -83,15 +71,14 @@ 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.+ // Cross-attention over the K and V the encode pass left behind. let normed = b.layer_norm(x, l.take(), EPSILON); let q = point(b, l, normed, D_MODEL, Act::None);- let k = point(b, l, encoded, D_MODEL, Act::None);- let v = point(b, l, encoded, D_MODEL, Act::None);- let scores = b.attn_scores(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(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); x = b.add(x, projected); @@ -105,16 +92,17 @@ pub(crate) fn decode_step(weights: &dyn WeightSource, src_len: u32) -> Result<Pl return Err(format!("the decoder norm ends at {}, not {TENSORS}", l.next)); } - // The tied head, in the same plan: a separate pass would mean a second `rebuild` and a round- // trip through the host for a `[1024]` vector. The last two splits are one class short.+ // The tied head, in the same plan. The last two splits are one class short. let head = &mut Layers { next: HEAD };- 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)); }- // 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)+ // Greedy on the device: the splits are disjoint, in id order, so their concatenation is the+ // whole vocabulary and the argmax index is the token id.+ let row = b.concat(&splits);+ let id = b.argmax(row);+ builder.finish(&[id]) }
library/ml/src/main/rust/src/post/translate.rs
diff --git a/library/ml/src/main/rust/src/post/translate.rs b/library/ml/src/main/rust/src/post/translate.rsindex 5627892396..f8f63d4405 100644--- a/library/ml/src/main/rust/src/post/translate.rs+++ b/library/ml/src/main/rust/src/post/translate.rs@@ -50,17 +50,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 what every decoder step attends over 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 how /// far the causal mask reaches.- 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 `normalised` from the language `source_token` names into the language `target_token`@@ -118,22 +118,16 @@ pub fn translate( source.extend(body); source.push(EOS); - let encoded = nets.encode(&source)?;+ nets.encode(&source)?; let mut produced: Vec<u32> = Vec::new(); // The decoder starts from `</s>`, and step 0 is forced to the target language — the // `forced_bos_token_id` override. The forced token is fed back as step 1's input but never- // emitted: it is framing, not translated text.+ // emitted: it is framing, not translated text. Step 0 still runs, to fill cache row 0. let mut token = DECODER_START; for step in 0..MAX_TOKENS {- let logits = nets.decode_step(token, step, &encoded)?;- let next = if step == 0 {- target_token- } else {- argmax(&logits).ok_or_else(|| {- format!("the decoder returned {} logits at step {step}", logits.len())- })?- };+ let greedy = nets.decode_step(token, step)?;+ let next = if step == 0 { target_token } else { greedy }; if next == EOS { break; }@@ -145,24 +139,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::*;@@ -175,39 +151,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.@@ -331,16 +292,6 @@ mod tests { } } - #[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));- }- #[test] fn the_loop_replays_the_parity_fixture_framing() { // `scripts/ml/nllb_parity_fixture.json`, pair 1 (eng_Latn -> fra_Latn): the reference@@ -351,17 +302,11 @@ mod tests { let table = Table::parse(&bytes).expect("parses"); let target = 256_057u32; // fra_Latn let content = [17994u32, 141190, 248079, 25358, 123732, 248105, 30213, 385];- // script[0] is discarded by the forcing; script[1..] answer steps 1... The fixture ids- // need a full-size vocabulary, which the 200-entry helper cannot hold.+ // script[0] is discarded by the forcing; script[1..] answer steps 1... let mut script = vec![0u32]; script.extend(content); script.push(EOS);- let mut nets = Scripted {- script,- source: Vec::new(),- steps: Vec::new(),- vocabulary: 300_000,- };+ let mut nets = Scripted { script, source: Vec::new(), steps: Vec::new() }; translate(&mut nets, &table, 256_047, target, "a").expect("translates"); let mut want = vec![(DECODER_START, 0), (target, 1)]; want.extend(content.iter().enumerate().map(|(i, &id)| (id, i + 2)));
translate/src/main/java/com/vayunmathur/translate/platform/NllbTranslator.kt
diff --git a/translate/src/main/java/com/vayunmathur/translate/platform/NllbTranslator.kt b/translate/src/main/java/com/vayunmathur/translate/platform/NllbTranslator.ktindex cee94f84f3..090983cf13 100644--- a/translate/src/main/java/com/vayunmathur/translate/platform/NllbTranslator.kt+++ b/translate/src/main/java/com/vayunmathur/translate/platform/NllbTranslator.kt@@ -27,8 +27,8 @@ import kotlinx.coroutines.withContext * * # The lock is not only for the handle *- * A translation re-records the network once per decoded token, so two concurrent calls- * would interleave recordings of the same command buffer. The mutex therefore covers the+ * A translation keeps its KV caches on the device and re-records the network on the way in,+ * so two concurrent calls would clobber each other's state. The mutex therefore covers the * whole of [translate] rather than just the load, and [close] too. */ class NllbTranslator(private val context: Context) : TranslationEngine {