ml: gemma4 batched prefill attends the KV cache at any position
- Commit
78e20b5262a30dfa0f31336c76bbf4366f14c0fd- Author
- vayun-mathur <[email protected]>
- When
- 2026-10-26 00:12 UTC (1 month ago)
- Parents
a0d6ae5
Diff
library/ml/src/main/rust/shaders/attn_apply_cached.comp
diff --git a/library/ml/src/main/rust/shaders/attn_apply_cached.comp b/library/ml/src/main/rust/shaders/attn_apply_cached.compindex 4b8e839458..38e89986c4 100644--- a/library/ml/src/main/rust/shaders/attn_apply_cached.comp+++ b/library/ml/src/main/rust/shaders/attn_apply_cached.comp@@ -46,22 +46,24 @@ void main() { if (index >= p.count) { return; }- // The output is `[d_model, 1, 1]`, so the index *is* the channel.- uint channel = index;+ // The output is `[d_model, 1, queries]`: channel-major, query innermost.+ uint queries = max(p.dil_h, 1u);+ uint channel = index / queries;+ uint q = index % queries; uint stride = p.in_w; uint head_dim = p.out_c / p.group; uint head = channel / head_dim;- // `S[head][*]`, contiguous in the key index because there is one query.- uint row = p.in0 + head * stride;+ // `S[head][q][*]`, contiguous in the key index.+ uint row = p.in0 + (head * queries + q) * stride; // V's channel for this query head, which under multi-query attention is shared. uint value = p.in1 + kv_head_of(head) * head_dim + (channel % head_dim); uint vstride = kv_stride(head_dim); float total = 0.0;- for (uint j = attn_first(); j <= attn_last(stride); j++) {+ for (uint j = attn_first_q(q); j <= attn_last_q(stride, q); j++) { total += float(arena[row + j]) * float(arena[value + j * vstride]); } // A folded int8 round-trip: the attention mixture's `Quantize` (live's // `Mm` round-trip at `MM_SCALE`) stores here instead of its own dispatch.- arena[p.out_at + channel] = float16_t(quant_store(total));+ arena[p.out_at + index] = float16_t(quant_store(total)); }
library/ml/src/main/rust/shaders/attn_scores_cached.comp
diff --git a/library/ml/src/main/rust/shaders/attn_scores_cached.comp b/library/ml/src/main/rust/shaders/attn_scores_cached.compindex 6cc9f0e80f..f152cdc066 100644--- a/library/ml/src/main/rust/shaders/attn_scores_cached.comp+++ b/library/ml/src/main/rust/shaders/attn_scores_cached.comp@@ -50,24 +50,25 @@ void main() { if (index >= p.count) { return; }- // The output is `[heads, 1, key_stride]`, so `unpack` gives head and key directly.- uint head, unused_row, key;- unpack(index, head, unused_row, key);- // Outside the range this step attends over. Only possible when the plan is built at a+ // The output is `[heads, queries, key_stride]`, so `unpack` gives head, query and key.+ uint head, row, key;+ unpack(index, head, row, key);+ // Outside the range this query attends over. Only possible when the plan is built at a // maximum, in which case the dispatch covers the whole stride.- if (key < attn_first() || key > attn_last(p.out_w)) {+ if (key < attn_first_q(row) || key > attn_last_q(p.out_w, row)) { return; } uint head_dim = p.in_c / p.group;- // Q is one position, so its channels are consecutive from `p.in0`.- uint query = p.in0 + head * head_dim;+ // Q is `[d_model, 1, queries]`: channel `c` of query `row` at `c * queries + row`.+ uint queries = max(p.dil_h, 1u);+ uint query = p.in0 + head * head_dim * queries + row; // Position `key` of the cache, then this head's *key/value* head slice within it. Under // multi-query attention several query heads land on the same slice. uint keys = p.in1 + key * kv_stride(head_dim) + kv_head_of(head) * head_dim; float total = 0.0; for (uint d = 0u; d < head_dim; d++) {- total += float(arena[query + d]) * float(arena[keys + d]);+ total += float(arena[query + d * queries]) * float(arena[keys + d]); } arena[p.out_at + index] = float16_t(total * uintBitsToFloat(p.param0_bits)); }
library/ml/src/main/rust/shaders/common.glsl
diff --git a/library/ml/src/main/rust/shaders/common.glsl b/library/ml/src/main/rust/shaders/common.glslindex fe6ac929a4..2901859c58 100644--- a/library/ml/src/main/rust/shaders/common.glsl+++ b/library/ml/src/main/rust/shaders/common.glsl@@ -177,6 +177,24 @@ uint attn_last(uint stride) { return p.dyn_keys != 0u ? min(step_params.prefix, stride - 1u) : stride - 1u; } +// The same range for query `q` of a multi-query op (`p.dil_h` queries at positions `prefix + q`,+// `p.dil_w` the sliding window or 0). Single-query ops (`p.dil_h == 0`) take exactly the+// decode path above.+uint attn_first_q(uint q) {+ if (p.dil_h == 0u) {+ return attn_first();+ }+ uint pos = step_params.prefix + q;+ return (p.sliding != 0u && p.dil_w != 0u && pos + 1u > p.dil_w) ? pos + 1u - p.dil_w : 0u;+}++uint attn_last_q(uint stride, uint q) {+ if (p.dil_h == 0u) {+ return attn_last(stride);+ }+ return min(step_params.prefix + q, stride - 1u);+}+ // The KV head a query head reads from. // // `p.group` query heads share `p.kv_heads` key/value heads, so head `h` reads KV head
library/ml/src/main/rust/shaders/softmax_prefix.comp
diff --git a/library/ml/src/main/rust/shaders/softmax_prefix.comp b/library/ml/src/main/rust/shaders/softmax_prefix.compindex 3a8cf432fd..87bf106c28 100644--- a/library/ml/src/main/rust/shaders/softmax_prefix.comp+++ b/library/ml/src/main/rust/shaders/softmax_prefix.comp@@ -39,8 +39,10 @@ void row_mode() { uint lane = gl_LocalInvocationID.x; uint lanes = gl_WorkGroupSize.x; uint stride = p.out_w;- uint first = attn_first();- uint last = attn_last(stride);+ // Rows are `[heads, queries]`, so a row's query is its index modulo the query count.+ uint q = row % max(p.dil_h, 1u);+ uint first = attn_first_q(q);+ uint last = attn_last_q(stride, q); uint at = p.in0 + row * stride; float peak = -65504.0; for (uint i = first + lane; i <= last; i += lanes) {@@ -68,9 +70,11 @@ void main() { return; } uint stride = p.out_w;- uint first = attn_first();- uint last = attn_last(stride);+ uint q = row % max(p.dil_h, 1u);+ uint first = attn_first_q(q);+ uint last = attn_last_q(stride, q); uint at = p.in0 + row * stride;+ // The most negative // The most negative fp16 rather than -inf, matching `softmax.comp`: a decode step always // attends over at least its own position, so the range is never empty and the seed is never
library/ml/src/main/rust/src/bridge_part11.rs
diff --git a/library/ml/src/main/rust/src/bridge_part11.rs b/library/ml/src/main/rust/src/bridge_part11.rsindex 7d9f5a90db..e9a688fafc 100644--- a/library/ml/src/main/rust/src/bridge_part11.rs+++ b/library/ml/src/main/rust/src/bridge_part11.rs@@ -52,22 +52,9 @@ fn gemma4_head_file_plan(head: &Streamed) -> Option<Reshaped<bool>> { ) .ok() }-/// Positions one prefill submit covers. Large enough that a prompt is **one** submit.-///-/// # Splitting a prefill is wrong, not merely slower-///-/// `prefill_layer` attends T queries against the chunk's own T keys. Positions in a second chunk-/// therefore never see the first chunk's keys at all, and the answer depends on where the split-/// fell - the same 31-token prompt gives "Paris", "Berlin" or "Rome" at chunk 8, 16 and 64.-/// Only the last is right, and it is right because it is a single chunk.-///-/// Verified against the sequential path, which is the decode path and unambiguously correct: a-/// single chunk agrees with it exactly at 100, 400, 900 and 1,907 positions.-///-/// The real repair is to attend over the cache rather than the chunk, as decode does, which-/// makes any chunking correct. Until then only the first chunk at position 0 is batched and-/// everything after it (later turns included) runs one position at a time.-const CHUNK: u32 = 4096;+/// Positions one prefill submit covers. Every chunk attends the whole cache, so the split only+/// trades GEMM width against the `8 x CHUNK x context` score maps (4 MB each at 256 x 1024).+const CHUNK: u32 = 256; /// Write one position's `values` into column `column` of a `[C, 1, width]` block. ///
library/ml/src/main/rust/src/bridge_part6.rs
diff --git a/library/ml/src/main/rust/src/bridge_part6.rs b/library/ml/src/main/rust/src/bridge_part6.rsindex 95d9cb9b3f..b36a93f776 100644--- a/library/ml/src/main/rust/src/bridge_part6.rs+++ b/library/ml/src/main/rust/src/bridge_part6.rs@@ -339,9 +339,7 @@ impl Gemma4Handle { /// same 1.30 GB once and every projection becomes a GEMM over T columns, so the weights are /// amortised T ways. ///- /// Chunked rather than one submit for the whole prompt, because attention is quadratic in T- /// and the score maps are a real allocation - eight heads of T x T at [`CHUNK`] is 16 MB,- /// and the arena has to hold it alongside everything else.+ /// Chunked because each chunk's score maps are eight heads of `T x context`. fn prefill(&mut self, tokens: &[u32]) -> Result<(), String> { if tokens.is_empty() { return Ok(());@@ -353,16 +351,9 @@ impl Gemma4Handle { self.context )); }- // `prefill_layer` attends only within its own chunk, so a batch is correct only when- // nothing precedes it. Past position 0 (later turns, text after an image, a second- // chunk) each token goes through the single-position pass, which attends the cache.- let (batched, sequential) = if self.position == 0 {- tokens.split_at(tokens.len().min(CHUNK as usize))- } else {- (&[][..], tokens)- };- if !batched.is_empty() {- let chunk = batched;+ // Every chunk attends the whole cache (`attn_cached_multi`), so any split and any+ // starting position is correct.+ for chunk in tokens.chunks(CHUNK as usize) { let width = chunk.len() as u32; let gathering = std::time::Instant::now(); // Gathered per position and laid out `[C, 1, T]` - channel-major, which is what@@ -408,19 +399,6 @@ impl Gemma4Handle { )); self.position += width; }- if !sequential.is_empty() {- let started = std::time::Instant::now();- for &token in sequential {- let (hidden, per_layer) = self.gather(token)?;- self.step_hidden(&hidden, &per_layer, false)?;- }- log(&format!(- "gemma4 prefill {} positions sequentially, ending at {}: {:.0} ms",- sequential.len(),- self.position,- started.elapsed().as_secs_f64() * 1000.0,- ));- } Ok(()) } } // close impl Gemma4Handle: everything below is a free function.
library/ml/src/main/rust/src/nets/gemma4.rs
diff --git a/library/ml/src/main/rust/src/nets/gemma4.rs b/library/ml/src/main/rust/src/nets/gemma4.rsindex 1e2e90411d..66baa30094 100644--- a/library/ml/src/main/rust/src/nets/gemma4.rs+++ b/library/ml/src/main/rust/src/nets/gemma4.rs@@ -433,4 +433,5 @@ include!("gemma4_part2.rs"); include!("gemma4_part3.rs"); include!("gemma4_part4.rs"); include!("gemma4_part5.rs");-include!("gemma4_part6.rs");\ No newline at end of file+include!("gemma4_part6.rs");+include!("gemma4_part7.rs");\ No newline at end of file
library/ml/src/main/rust/src/nets/gemma4_part1.rs
diff --git a/library/ml/src/main/rust/src/nets/gemma4_part1.rs b/library/ml/src/main/rust/src/nets/gemma4_part1.rsindex 41b7c2a16b..2394786d45 100644--- a/library/ml/src/main/rust/src/nets/gemma4_part1.rs+++ b/library/ml/src/main/rust/src/nets/gemma4_part1.rs@@ -180,14 +180,7 @@ pub fn build(weights: &dyn WeightSource, pass: Pass) -> Result<Plan, String> { b.host_tensor(ONE_SLIDING, &[HEAD_DIM]); b.host_tensor(ONE_FULL, &[GLOBAL_HEAD_DIM]); - // A batched prefill cannot read its own keys out of the cache: the cache is position-major- // and the pass needs them `[width, 1, T]`, and the twenty shared layers would be reading- // rows their owning layer wrote earlier in the same submit with no barrier between. So the- // owning layers' K and V are carried forward as tensors instead, which is also how the- // decode path's `cache_source` mapping is honoured without a second transpose.- let mut sliding_kv: Option<(Id, Id)> = None;- let mut full_kv: Option<(Id, Id)> = None;- // TraceTail runs layer 0 through `layer_tail`, which returns the four branch+ // TraceTail runs layer 0 through `layer_tail` // intermediates alongside the output. Every other mode runs `layer`. let mut tail: Option<[Id; 4]> = None; for index in 0..stop_after {@@ -204,17 +197,7 @@ pub fn build(weights: &dyn WeightSource, pass: Pass) -> Result<Plan, String> { x = layer(b, index, x, per_layer_inputs, angles, cache_k, cache_v)?; continue; }- let shared = if is_full_attention(index) { full_kv } else { sliding_kv };- let (next, kv) =- prefill_layer(b, index, x, per_layer_inputs, angles, cache_k, cache_v, shared, width)?;- x = next;- if let Some(kv) = kv {- if is_full_attention(index) {- full_kv = Some(kv);- } else {- sliding_kv = Some(kv);- }- }+ x = prefill_layer(b, index, x, per_layer_inputs, angles, cache_k, cache_v, width)?; } if let Mode::TraceTail = mode {@@ -350,9 +333,8 @@ fn prefill_layer( angles: Id, cache_k: Id, cache_v: Id,- shared: Option<(Id, Id)>, width: u32,-) -> Result<(Id, Option<(Id, Id)>), String> {+) -> Result<Id, String> { let dim = head_dim(index); let inner = ffn(index); let at = layer_at(index);@@ -400,38 +382,28 @@ fn prefill_layer( let q = b.rms_norm_grouped(q, q_norm_at, EPSILON, HEADS); let q = b.rotary(q, angles, HEADS); - let mine = match (k_norm_at, k_proj, v_proj) {- (Some(k_norm_at), Some(k_proj), Some(v_proj)) => {- let k = point(b, k_proj, normed_q, KV_HEADS * dim);- let k = b.quantize(k, KO_SCALE[index]);- let k = b.rms_norm_grouped(k, k_norm_at, EPSILON, KV_HEADS);- let k = b.rotary(k, angles, KV_HEADS);- let v = point(b, v_proj, normed_q, KV_HEADS * dim);- let v = b.quantize(v, VO_SCALE[index]);- // S10's `value_norm`, as in [`super::layer`]: a parameter-free- // RMS norm (all-ones gamma, [`ONE_SLIDING`]/[`ONE_FULL`]) before- // the cache write. The decode path must read what this wrote.- let ones = if is_full_attention(index) { ONE_FULL } else { ONE_SLIDING };- let v = b.rms_norm(v, ones, EPSILON);- // Written for the decode steps that follow this prompt. `cache_write` transposes- // channel-major into the cache's position-major layout.- b.cache_write(k, cache_k);- b.cache_write(v, cache_v);- Some((k, v))- }- _ => None,- };- // A shared layer has no K or V of its own and reads the last owning layer's of the same- // attention type - the same mapping `cache_source` states, resolved to tensors here.- let (k, v) = mine- .or(shared)- .ok_or_else(|| format!("layer {index} has no keys and none were carried forward"))?;+ if let (Some(k_norm_at), Some(k_proj), Some(v_proj)) = (k_norm_at, k_proj, v_proj) {+ let k = point(b, k_proj, normed_q, KV_HEADS * dim);+ let k = b.quantize(k, KO_SCALE[index]);+ let k = b.rms_norm_grouped(k, k_norm_at, EPSILON, KV_HEADS);+ let k = b.rotary(k, angles, KV_HEADS);+ let v = point(b, v_proj, normed_q, KV_HEADS * dim);+ let v = b.quantize(v, VO_SCALE[index]);+ // S10's `value_norm`, as in [`super::layer`]: a parameter-free+ // RMS norm (all-ones gamma, [`ONE_SLIDING`]/[`ONE_FULL`]) before+ // the cache write. The decode path must read what this wrote.+ let ones = if is_full_attention(index) { ONE_FULL } else { ONE_SLIDING };+ let v = b.rms_norm(v, ones, EPSILON);+ // Positions `prefix .. prefix + T`, transposed into the position-major cache.+ b.cache_write(k, cache_k);+ b.cache_write(v, cache_v);+ } - // The scale is already inside `q_norm`'s gamma, so this must not derive it again.- let scores = b.attn_scores_grouped_prescaled(q, k, HEADS, KV_HEADS);+ // Every query attends the cache - the positions before this chunk and the chunk itself,+ // which the owning layer just wrote - so a prefill is correct at any position. The scale is+ // already inside `q_norm`'s gamma. let slides = !is_full_attention(index);- let probs = b.softmax_causal_windowed(scores, if slides { WINDOW } else { 0 });- let mixed = b.attn_apply_grouped(probs, v, HEADS, KV_HEADS);+ let mixed = b.attn_cached_multi(q, cache_k, cache_v, HEADS, KV_HEADS, if slides { WINDOW } else { 0 }); // The live int8 round-trip, as in [`super::layer`]: prefill fills the same // caches a decode reads, so its mixtures quantize identically. let mixed = b.quantize(mixed, MM_SCALE[index]);@@ -460,7 +432,7 @@ fn prefill_layer( let x = b.mul_scalar(x, skip_at); let _ = width; // The whole residual is scaled by `skip` after add2, as in [`super::layer`].- Ok((x, mine))+ Ok(x) } /// A `1 x 1` int4 convolution, which every large projection in this net is.
library/ml/src/main/rust/src/nets/gemma4_part3.rs
diff --git a/library/ml/src/main/rust/src/nets/gemma4_part3.rs b/library/ml/src/main/rust/src/nets/gemma4_part3.rsindex 743fbe714f..bbb134db99 100644--- a/library/ml/src/main/rust/src/nets/gemma4_part3.rs+++ b/library/ml/src/main/rust/src/nets/gemma4_part3.rs@@ -232,14 +232,11 @@ mod tests { } #[test]- fn a_batched_prefill_widens_every_stage_and_masks_causally() {- // The whole prompt in one submit. What makes it worth having is that the projections- // become GEMMs: at one position the model is bandwidth-bound reading 1.3 GB of weights- // per token, and at T it reads the same weights once for all of them.- //- // What makes it dangerous is that a plan recorded for T positions which attends as- // though it were one produces fluent, wrong text and no shape error. So this checks the- // masking, not merely that it builds.+ fn a_batched_prefill_widens_every_stage_and_attends_the_cache() {+ // The whole chunk in one submit, so the projections become GEMMs. Every layer's+ // attention reads the KV cache with one row per query (`attn_cached_multi`): queries+ // after position 0 must see what earlier submits wrote, and a plan that attended only its+ // own chunk produced fluent, wrong text with no shape error. for tokens in [2u32, 8, 64] { let plan = build(&Shapes::new(TENSORS), Mode::Prefill { tokens }.at(TEST_CONTEXT)) .unwrap_or_else(|e| panic!("{tokens} positions: {e}"));@@ -247,30 +244,33 @@ mod tests { for input in &plan.inputs { assert_eq!(input.shape.w, tokens, "every input is widened"); }- let mut causal = 0;- let mut windowed = 0;+ let (mut scores, mut softmaxes, mut windowed) = (0, 0, 0); for op in &plan.ops { let Op::Dispatch { kind, push, .. } = op else { continue }; match kind {- Kind::SoftmaxCausal => {- causal += 1;- if push.kh != 0 {+ Kind::AttnScoresCached => {+ scores += 1;+ assert_eq!((push.group, push.kv_heads), (HEADS, KV_HEADS));+ assert_eq!((push.dil_h, push.out_h, push.out_w), (tokens, tokens, TEST_CONTEXT));+ if push.sliding != 0 { windowed += 1;- assert_eq!(push.kh, WINDOW);+ assert_eq!(push.dil_w, WINDOW); }- assert_eq!((push.out_h, push.out_w), (tokens, tokens), "T x T scores"); }- // Every score map is multi-query, as the decode path's is.- Kind::AttnScores | Kind::AttnApply => {- assert_eq!(push.group, HEADS);- assert_eq!(push.kv_heads, KV_HEADS);+ Kind::SoftmaxPrefix => {+ softmaxes += 1;+ assert_eq!(push.dil_h, tokens, "one row per query");+ }+ Kind::AttnApplyCached => assert_eq!(push.dil_h, tokens),+ Kind::SoftmaxCausal | Kind::AttnScores | Kind::AttnApply => {+ panic!("{kind:?}: a prefill must attend the cache, not its own chunk") } // Fifteen owning layers write a key and a value, transposing as they go. Kind::CacheWrite => assert_eq!(push.group, tokens, "one write per position"), _ => {} } }- assert_eq!(causal, LAYERS, "one causal softmax per layer");+ assert_eq!((scores, softmaxes), (LAYERS, LAYERS), "one cached attention per layer"); assert_eq!(windowed, 28, "and the sliding ones carry a window"); } assert!(build(&Shapes::new(TENSORS), Mode::Prefill { tokens: 0 }.at(TEST_CONTEXT)).is_err());
library/ml/src/main/rust/src/nets/gemma4_part7.rs
diff --git a/library/ml/src/main/rust/src/nets/gemma4_part7.rs b/library/ml/src/main/rust/src/nets/gemma4_part7.rsnew file mode 100644index 0000000000..f457ddb277--- /dev/null+++ b/library/ml/src/main/rust/src/nets/gemma4_part7.rs@@ -0,0 +1,70 @@+// Multi-query cached attention: T queries against the position-major KV caches, so a batched+// prefill at any position attends everything already in the cache. Query `t` sits at+// `step_params.prefix + t` and sees keys `window_first(prefix + t) ..= prefix + t`. Lowered onto+// the decode kinds (`AttnScoresCached`, `SoftmaxPrefix`, `AttnApplyCached`) with the query count+// in `Push::dil_h` and the window in `Push::dil_w`; at one query those fields are zero and the+// decode path is unchanged.++impl Builder<'_> {+ /// `q` is `[heads * head_dim, 1, T]` (already scaled, as Gemma's `q_norm` carries the+ /// scale), `cache_k`/`cache_v` are `[context, 1, kv_heads * head_dim]` and must already hold+ /// positions `prefix .. prefix + T`. `window` is the sliding window, or 0 for full attention.+ /// Returns `[heads * head_dim, 1, T]`.+ pub fn attn_cached_multi(+ &mut self,+ q: Id,+ cache_k: Id,+ cache_v: Id,+ heads: u32,+ kv_heads: u32,+ window: u32,+ ) -> Id {+ let (sq, sk, sv) = (self.shape_of(q), self.shape_of(cache_k), self.shape_of(cache_v));+ let head_dim = sq.c.checked_div(heads).unwrap_or(0);+ if sq.h != 1 || heads == 0 || head_dim * heads != sq.c {+ self.fail(format!("multi-query attention over q {sq:?} with {heads} heads"));+ }+ if kv_heads == 0 || heads % kv_heads != 0 {+ self.fail(format!("{heads} query heads do not group into {kv_heads} key/value heads"));+ }+ if sk != sv || sk.h != 1 || sk.w != kv_heads * head_dim {+ self.fail(format!("caches {sk:?} / {sv:?} for {kv_heads} heads of {head_dim}"));+ }+ let queries = sq.w;+ let context = sk.c;+ let sliding = window != 0;+ let scores = self.tensor(Shape::new(heads, queries, context));+ self.nodes.push(super::Node::AttnScoresCached {+ q,+ cache: cache_k,+ out: scores,+ heads,+ kv_heads,+ scale: 1.0,+ dynamic: true,+ sliding,+ window,+ });+ let probs = self.tensor(Shape::new(heads, queries, context));+ self.nodes.push(super::Node::Softmax {+ input: scores,+ out: probs,+ mode: super::SoftmaxMode::Prefix,+ sliding,+ window,+ });+ let out = self.tensor(Shape::new(heads * head_dim, 1, queries));+ self.nodes.push(super::Node::AttnApplyCached {+ probs,+ cache: cache_v,+ out,+ heads,+ kv_heads,+ dynamic: true,+ sliding,+ window,+ quant_scale: None,+ });+ out+ }+}
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 e9cadab752..c48ed9b833 100644--- a/library/ml/src/main/rust/src/nets/mod_part5.rs+++ b/library/ml/src/main/rust/src/nets/mod_part5.rs@@ -436,7 +436,7 @@ impl<'a> Builder<'a> { } let scale = if derive_scale { 1.0 / (head_dim.max(1) as f32).sqrt() } else { 1.0 }; let out = self.tensor(Shape::new(heads, 1, sc.c));- self.nodes.push(Node::AttnScoresCached { q, cache, out, heads, kv_heads, scale, dynamic, sliding });+ self.nodes.push(Node::AttnScoresCached { q, cache, out, heads, kv_heads, scale, dynamic, sliding, window: 0 }); out }
library/ml/src/main/rust/src/nets/mod_part9.rs
diff --git a/library/ml/src/main/rust/src/nets/mod_part9.rs b/library/ml/src/main/rust/src/nets/mod_part9.rsindex 8ad1a81277..db253e3708 100644--- a/library/ml/src/main/rust/src/nets/mod_part9.rs+++ b/library/ml/src/main/rust/src/nets/mod_part9.rs@@ -552,7 +552,7 @@ impl<'a> Builder<'a> { invocations, }); }- Node::AttnScoresCached { q, cache, out, heads, kv_heads, scale, dynamic, sliding } => {+ Node::AttnScoresCached { q, cache, out, heads, kv_heads, scale, dynamic, sliding, window } => { let (sq, so) = (shape(*q), shape(*out)); ops.push(Op::Dispatch { kind: Kind::AttnScoresCached,@@ -574,6 +574,10 @@ impl<'a> Builder<'a> { dyn_keys: u32::from(*dynamic), kv_heads: *kv_heads, sliding: u32::from(*sliding),+ // Several queries (`so.h`): the per-query range path. Zero otherwise,+ // so a decode step's push is unchanged.+ dil_h: if so.h > 1 || *window != 0 { so.h } else { 0 },+ dil_w: *window, ..Push::default() }, invocations: so.len(),
library/ml/src/main/rust/src/nets/mod_part9b.rs
diff --git a/library/ml/src/main/rust/src/nets/mod_part9b.rs b/library/ml/src/main/rust/src/nets/mod_part9b.rsindex ca489e6272..ad50ac9ef4 100644--- a/library/ml/src/main/rust/src/nets/mod_part9b.rs+++ b/library/ml/src/main/rust/src/nets/mod_part9b.rs@@ -35,7 +35,7 @@ impl<'a> Builder<'a> { // in the shader reads it. param0_bits: quant_scale.map_or(0, f32::to_bits), // `[d_model, 1, queries]`: several queries take the per-query path.- dil_h: if so.w > 1 { so.w } else { 0 },+ dil_h: if so.w > 1 || *window != 0 { so.w } else { 0 }, dil_w: *window, ..Push::default() },@@ -400,7 +400,7 @@ impl<'a> Builder<'a> { kh: *window, kw, // A prefix softmax over several queries' rows (`[heads, queries, keys]`).- dil_h: if *mode == SoftmaxMode::Prefix && so.h > 1 { so.h } else { 0 },+ dil_h: if *mode == SoftmaxMode::Prefix && (so.h > 1 || *window != 0) { so.h } else { 0 }, dil_w: if *mode == SoftmaxMode::Prefix { *window } else { 0 }, ..Push::default() },
library/ml/src/main/rust/src/nets/reference_part3.rs
diff --git a/library/ml/src/main/rust/src/nets/reference_part3.rs b/library/ml/src/main/rust/src/nets/reference_part3.rsindex b672ebd4b9..ad660afb41 100644--- a/library/ml/src/main/rust/src/nets/reference_part3.rs+++ b/library/ml/src/main/rust/src/nets/reference_part3.rs@@ -16,6 +16,17 @@ impl Reference { } } + /// [`Self::attended`] for query `q` of a multi-query op. Mirrors `attn_first_q` /+ /// `attn_last_q`: query `q` sits at `prefix + q` and slides over `p.dil_w` keys.+ fn attended_q(&self, p: &Push, stride: u32, q: u32) -> (u32, u32) {+ if p.dil_h == 0 {+ return self.attended(p, stride);+ }+ let pos = self.prefix + q;+ let first = if p.sliding != 0 && p.dil_w != 0 { (pos + 1).saturating_sub(p.dil_w) } else { 0 };+ (first, pos.min(stride.saturating_sub(1)))+ }+ /// The KV head a query head reads from. Mirrors `kv_head_of` in `shaders/common.glsl`. fn kv_head_of(p: &Push, head: u32) -> u32 { let kv = if p.kv_heads == 0 { p.group } else { p.kv_heads };@@ -168,20 +179,23 @@ impl Reference { fn attn_scores_cached(&mut self, p: &Push) -> Result<(), String> { let head_dim = heads(p, p.in_c)?; let scale = f32::from_bits(p.param0_bits);- let (first, last) = self.attended(p, p.out_w); let stride = Self::kv_stride(p, head_dim);+ let queries = p.dil_h.max(1); for head in 0..p.group {- // Q is one position, so its channels are consecutive.- let query_base = head * head_dim;+ // Q is `[d_model, 1, queries]`: channel `c` of query `q` at `c * queries + q`. let kv_base = Self::kv_head_of(p, head) * head_dim;- for key in first..=last {- let key_base = key * stride + kv_base;- let mut total = 0.0;- for d in 0..head_dim {- total +=- self.load(p.in0, query_base + d)? * self.load(p.in1, key_base + d)?;+ for q in 0..queries {+ let query_base = head * head_dim * queries + q;+ let (first, last) = self.attended_q(p, p.out_w, q);+ for key in first..=last {+ let key_base = key * stride + kv_base;+ let mut total = 0.0;+ for d in 0..head_dim {+ total += self.load(p.in0, query_base + d * queries)?+ * self.load(p.in1, key_base + d)?;+ }+ self.store(p.out, nchw(p, head, q, key), total * scale)?; }- self.store(p.out, nchw(p, head, 0, key), total * scale)?; } } Ok(())@@ -195,20 +209,23 @@ impl Reference { fn attn_apply_cached(&mut self, p: &Push) -> Result<(), String> { let head_dim = heads(p, p.out_c)?; let stride = p.in_w;- let (first, last) = self.attended(p, stride); let vstride = Self::kv_stride(p, head_dim);+ let queries = p.dil_h.max(1); for channel in 0..p.out_c { let head = channel / head_dim;- // One query, so a head's row of probabilities starts a full stride apart even when- // this step attends over fewer keys than the row can hold.- let row = head * stride; let value = Self::kv_head_of(p, head) * head_dim + (channel % head_dim);- let mut total = 0.0;- for key in first..=last {- total += self.load(p.in0, row + key)?- * self.load(p.in1, value + key * vstride)?;+ for q in 0..queries {+ // A row of probabilities starts a full stride apart even when this step attends+ // over fewer keys than the row can hold.+ let row = (head * queries + q) * stride;+ let (first, last) = self.attended_q(p, stride, q);+ let mut total = 0.0;+ for key in first..=last {+ total += self.load(p.in0, row + key)?+ * self.load(p.in1, value + key * vstride)?;+ }+ self.store(p.out, channel * queries + q, self.fused_quant(p, total)?)?; }- self.store(p.out, nchw(p, channel, 0, 0), self.fused_quant(p, total)?)?; } Ok(()) }
library/ml/src/main/rust/src/vulkan/parity_part7.rs
diff --git a/library/ml/src/main/rust/src/vulkan/parity_part7.rs b/library/ml/src/main/rust/src/vulkan/parity_part7.rsindex 2419a32cd6..5e6b95dd18 100644--- a/library/ml/src/main/rust/src/vulkan/parity_part7.rs+++ b/library/ml/src/main/rust/src/vulkan/parity_part7.rs@@ -315,4 +315,83 @@ fn a_ragged_wide_int4_gemv_agrees_with_the_reference() { "a single-position int4 convolution must lower to the gemv shader", ); compare("a ragged wide int4 gemv", plan, weights.data().to_vec(), &[&input]);-}\ No newline at end of file+}+/// T queries at prefix `prefix` through `attn_cached_multi` against T single decode steps at+/// `prefix + t`, over caches holding junk past the last position (so an over-read shows).+fn multi_query_fixture(queries: u32, prefix: u32, head_dim: u32, window: u32) {+ use crate::nets::reference::run_multi_at;+ const HEADS: u32 = 8;+ const KV_HEADS: u32 = 1;+ let what = format!("multi-query attention T={queries} prefix={prefix} dim={head_dim} window={window}");+ let width = HEADS * head_dim;+ let kv = KV_HEADS * head_dim;+ let filled = prefix + queries;+ let context = filled + 3;+ let cache = |seed: f32| -> Vec<f32> {+ let mut values = spread((context * kv) as usize, seed);+ for v in values.iter_mut().skip((filled * kv) as usize) {+ *v = 50.0;+ }+ values+ };+ let (keys, values) = (cache(1.3), cache(2.9));+ let q: Vec<f32> = spread((width * queries) as usize, 0.4).iter().map(|v| v * 0.08).collect();+ let sliding = window != 0;++ let source = Invented::new(0);+ let mut builder = Builder::new(&source);+ let q1 = builder.input(Shape::new(width, 1, 1));+ let k1 = builder.input(Shape::new(context, 1, kv));+ let v1 = builder.input(Shape::new(context, 1, kv));+ let scores = builder.attn_scores_cached_prescaled(q1, k1, HEADS, KV_HEADS, sliding);+ let probs = builder.softmax_prefix(scores, sliding);+ let out = builder.attn_apply_cached_grouped(probs, v1, HEADS, KV_HEADS, sliding);+ let plan = builder.finish(&[out]).expect("the single-query plan builds");+ let weights = Weights::from_data(source.into_data());+ let mut net = Net::new(device(), plan, &weights, RESCALE_ONLY).expect("the single-query plan records");+ let mut stepped = vec![0f32; (width * queries) as usize];+ for t in 0..queries {+ let position = prefix + t;+ let window_start = if sliding { (position + 1).saturating_sub(window) } else { 0 };+ net.set_params(StepParams { prefix: position, window_start }).expect("step params");+ let column: Vec<f32> =+ (0..width).map(|c| q[(c * queries + t) as usize]).collect();+ let got = net.infer_raw_many(&[&column, &keys, &values]).expect("a single step submits");+ for c in 0..width {+ stepped[(c * queries + t) as usize] = got[0][c as usize];+ }+ }++ let source = Invented::new(0);+ let mut builder = Builder::new(&source);+ let qm = builder.input(Shape::new(width, 1, queries));+ let km = builder.input(Shape::new(context, 1, kv));+ let vm = builder.input(Shape::new(context, 1, kv));+ let out = builder.attn_cached_multi(qm, km, vm, HEADS, KV_HEADS, window);+ let plan = builder.finish(&[out]).expect("the multi-query plan builds");+ crate::nets::tests::assert_no_aliasing(&plan);+ let data = source.into_data();+ let oracle = run_multi_at(&plan, &data, &[&q, &keys, &values], prefix, 0).expect("the oracle runs");+ let weights = Weights::from_data(data);+ let mut net = Net::new(device(), plan, &weights, RESCALE_ONLY).expect("the multi-query plan records");+ net.set_params(StepParams { prefix, window_start: 0 }).expect("step params");+ let multi = net.infer_raw_many(&[&q, &keys, &values]).expect("the multi-query plan submits");++ matches(&format!("{what} vs the oracle"), &oracle, &multi);+ matches(&format!("{what} vs single steps"), &[stepped], &multi);+}++#[test]+#[ignore = "needs a Vulkan device"]+fn multi_query_cached_attention_equals_single_steps() {+ // Gemma 4: sliding layers are head_dim 256 over a 512-key window, full layers 512 over+ // everything. Prefix 600 puts the window's start inside the cache.+ for queries in [1, 7, 64] {+ for prefix in [0, 5, 600] {+ multi_query_fixture(queries, prefix, 256, 512);+ multi_query_fixture(queries, prefix, 512, 0);+ }+ }+ // A short window, so every query's lower bound differs and most of them clip.+ multi_query_fixture(7, 5, 256, 4);+}