translate: SMaLL-100 decode step with a position-major KV cache
- Commit
f68b01c24cbccca9b65e3433bfcc9d98d775e297- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-29 03:45 UTC (3 months ago)
- Parents
9c74710
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.compnew file mode 100644index 0000000000..224009f19e--- /dev/null+++ b/library/ml/src/main/rust/shaders/attn_apply_cached.comp@@ -0,0 +1,56 @@+#version 450+//! `O[d] = sum_j S[h][j] * Vcache[j][d]`, attention output for **one** query.+//!+//! The counterpart of `attn_scores_cached.comp`, and it exists for the same reason: V is a+//! position-major `[T, 1, d_model]` cache rather than the `[d_model, 1, T]` every projection+//! writes, so appending a position is one contiguous copy instead of `d_model` scattered ones. See+//! that shader for why the three shared attention shaders are left untouched.+//!+//! # Back into the layout the next projection reads+//!+//! The output is `[d_model, 1, 1]` — channel-major, one position — which is exactly what+//! `conv_point_int8.comp` wants next. So the cache layout is confined to the two operands that are+//! caches, and nothing else in the decoder changes shape. As in `attn_apply.comp`, the head+//! concatenation is not an op: output channel `c` belongs to head `c / head_dim` and is written in+//! place, which *is* the concatenated result.+//!+//! V needs no head arithmetic — channel `c` of V is channel `c` of the output — so the head index+//! only picks which of `S`'s rows to read.+//!+//! # This is the strided side of the layout+//!+//! `Vcache[j][d]` for fixed `d` walks `p.in_c` apart, where `attn_apply.comp`'s read is contiguous.+//! That is the price of the cheap append, and it is paid once per output channel per key rather+//! than per weight tap; the projections either side of it dominate.+//!+//! # Precision+//!+//! `S` is a distribution, so every product is bounded by the corresponding `V` and the sum of a+//! convex combination cannot exceed `V`'s range. `float` accumulation is ample and the fp16 store+//! is the only rounding, as in `attn_apply.comp`.+//!+//! # Push fields+//!+//! `p.in0` is `S` at `[heads, 1, keys]`, `p.in1` the cache, `p.in_c` and `p.out_c` are `d_model`,+//! `p.in_w` the key count and `p.group` the head count. No new field.++#include "common.glsl"++void main() {+ uint index = global_index();+ if (index >= p.count) {+ return;+ }+ // The output is `[d_model, 1, 1]`, so the index *is* the channel.+ uint channel = index;+ uint keys = p.in_w;+ uint head_dim = p.out_c / p.group;+ // `S[head][*]`, contiguous in the key index because there is one query.+ uint row = p.in0 + (channel / head_dim) * keys;++ float total = 0.0;+ for (uint j = 0u; j < keys; j++) {+ total += float(arena[row + j]) * float(arena[p.in1 + j * p.in_c + channel]);+ }+ arena[p.out_at + channel] = float16_t(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.compnew file mode 100644index 0000000000..a0a29002f9--- /dev/null+++ b/library/ml/src/main/rust/shaders/attn_scores_cached.comp@@ -0,0 +1,62 @@+#version 450+//! `S[h][j] = scale * sum_d Q[h][d] * Kcache[j][h][d]`, attention scores for **one** query.+//!+//! # Why a second scores shader+//!+//! `attn_scores.comp` reads K as `[d_model, 1, T]`, the layout every projection in this runtime+//! writes. That layout is right everywhere it is used — and wrong for a decoder's KV cache, for one+//! reason: appending a position to `[d_model, 1, T]` means writing one element into each of+//! `d_model` runs that are `T` apart. At `d_model` 1024 that is 1024 non-contiguous two-byte+//! copies per tensor per layer per step, which for SMaLL-100's three layers and 128 tokens is over+//! three quarters of a million `vkCmdCopyBuffer` calls.+//!+//! So a cache is **position-major**, `[T, 1, d_model]`, where appending a position is one+//! contiguous copy of `d_model` elements. That is the only difference between this and+//! `attn_scores.comp`, and it is why the existing shader is left alone: `attn_scores.comp`,+//! `softmax.comp` and `attn_apply.comp` are shared by PP-OCRv5 recognition and both Supertonic+//! encoders, so a change to any of their `Push` fields would break three shipping nets at once.+//! This adds a shader instead and touches none of them.+//!+//! # One query, which is what makes a causal mask unnecessary+//!+//! A decode step has exactly one query — the token just produced — attending over the `j < T`+//! positions before it plus itself. The prefix bound *is* the tensor length, so there is nothing to+//! mask: this runtime has no additive mask and needs none. The output is `[heads, 1, keys]`, so+//! `softmax.comp` normalises it unchanged.+//!+//! # The reduction is contiguous here+//!+//! `Kcache[j]` is a run of `d_model` elements and a head owns `head_dim` consecutive channels+//! inside it, so the dot product walks a contiguous vector rather than `head_dim` channels a+//! stride apart. That is strictly better than `attn_scores.comp`'s access pattern; the cost of the+//! layout is paid in `attn_apply_cached.comp`, where V's read becomes the strided one.+//!+//! # Push fields+//!+//! `p.in0` is Q at `[d_model, 1, 1]`, so channel `c` is simply element `c`. `p.in1` is the cache.+//! `p.in_c` is `d_model` and doubles as the cache's per-position stride, `p.group` is the head+//! count, `p.out_w` is the key count and `p.param0_bits` is `1 / sqrt(head_dim)` as raw f32 bits —+//! all fields that already exist, so the 26-slot push block does not grow.++#include "common.glsl"++void main() {+ uint index = global_index();+ if (index >= p.count) {+ return;+ }+ // The output is `[heads, 1, keys]`, so `unpack` gives head and key directly.+ uint head, unused_row, key;+ unpack(index, head, unused_row, key);+ 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;+ // Position `key` of the cache, then this head's slice within it.+ uint keys = p.in1 + key * p.in_c + head * head_dim;++ float total = 0.0;+ for (uint d = 0u; d < head_dim; d++) {+ total += float(arena[query + d]) * float(arena[keys + d]);+ }+ arena[p.out_at + index] = float16_t(total * uintBitsToFloat(p.param0_bits));+}
library/ml/src/main/rust/src/nets/mod.rs
diff --git a/library/ml/src/main/rust/src/nets/mod.rs b/library/ml/src/main/rust/src/nets/mod.rsindex f12457ca3d..6663a5bd40 100644--- a/library/ml/src/main/rust/src/nets/mod.rs+++ b/library/ml/src/main/rust/src/nets/mod.rs@@ -255,6 +255,15 @@ pub enum Kind { /// [`Kind::AttnApply`] plus the value-side relative term. See /// [`Kind::AttnScoresRelative`]. AttnApplyRelative,+ /// [`AttnScores`](Kind::AttnScores) for one query against a **position-major** K cache.+ ///+ /// A decoder step is one query, and its keys live in a cache that a position is appended to+ /// every step. `[d_model, 1, T]` makes that append `d_model` scattered two-byte copies, so a+ /// cache is `[T, 1, d_model]` instead and reads through this. See+ /// `shaders/attn_scores_cached.comp` for why the shared shaders are not extended.+ AttnScoresCached,+ /// [`AttnApply`](Kind::AttnApply) for one query against a **position-major** V cache.+ AttnApplyCached, /// A `1 x 1` convolution as a tiled matrix multiply, staging weights through shared memory. /// /// [`Kind::Conv`] reads each output element''s weights from global memory with no reuse, which@@ -471,7 +480,8 @@ impl Kind { reads.push(WeightRead { at: elems(push.weight), field: "weight" }); } // Purely elementwise or arena-only. `attn_scores`, `softmax`, `attn_apply` and- // `rotary` all take their second operand from the arena.+ // `rotary` all take their second operand from the arena, and the cached attention+ // pair take theirs from a cache in the arena too. Kind::MaxPool | Kind::AvgPool | Kind::Resize@@ -483,8 +493,10 @@ impl Kind { | Kind::Mul | Kind::Affine | Kind::AttnScores+ | Kind::AttnScoresCached | Kind::Softmax | Kind::AttnApply+ | Kind::AttnApplyCached | Kind::Rotary => {} } if !reads.is_empty() && push.act == Act::PRelu(0).code() {@@ -675,6 +687,21 @@ enum Node { heads: u32, scale: f32, },+ /// One query against a position-major K cache. See [`Kind::AttnScoresCached`].+ AttnScoresCached {+ q: Id,+ cache: Id,+ out: Id,+ heads: u32,+ scale: f32,+ },+ /// One query against a position-major V cache. See [`Kind::AttnApplyCached`].+ AttnApplyCached {+ probs: Id,+ cache: Id,+ out: Id,+ heads: u32,+ }, Softmax { input: Id, out: Id,@@ -1284,6 +1311,80 @@ impl<'a> Builder<'a> { out } + /// Attention scores for one query against a **position-major** K cache.+ ///+ /// `q` is `[d_model, 1, 1]` and `cache` is `[keys, 1, d_model]`, giving `[heads, 1, keys]`.+ /// The cache's axes are the other way round from every other sequence here, deliberately: see+ /// [`Kind::AttnScoresCached`].+ ///+ /// One query is what makes a causal mask unnecessary — a decode step attends over exactly the+ /// positions in the cache, so the prefix bound is the tensor's own length.+ pub fn attn_scores_cached(&mut self, q: Id, cache: Id, heads: u32) -> Id {+ let (sq, sc) = (self.shape_of(q), self.shape_of(cache));+ if sq.h != 1 || sq.w != 1 {+ self.fail(format!(+ "a cached score map over q {sq:?}: a decode step is one query, so q is \+ [d_model, 1, 1]"+ ));+ }+ if sc.h != 1 || sc.w != sq.c {+ self.fail(format!(+ "a cached score map over q {sq:?} and a cache {sc:?}: a cache is \+ [keys, 1, d_model], so its width is d_model and its channels are the keys"+ ));+ }+ if heads == 0 || !sq.c.is_multiple_of(heads) {+ self.fail(format!("{} channels do not split into {heads} heads", sq.c));+ }+ let head_dim = sq.c.checked_div(heads).unwrap_or(0);+ let scale = 1.0 / (head_dim.max(1) as f32).sqrt();+ let out = self.tensor(Shape::new(heads, 1, sc.c));+ self.nodes.push(Node::AttnScoresCached { q, cache, out, heads, scale });+ out+ }++ /// One query's attention output against a **position-major** V cache.+ ///+ /// `probs` is `[heads, 1, keys]` and `cache` is `[keys, 1, d_model]`, giving+ /// `[d_model, 1, 1]` — back in the channel-major layout the next projection reads, so the+ /// cache layout is confined to the two operands that are caches.+ pub fn attn_apply_cached(&mut self, probs: Id, cache: Id, heads: u32) -> Id {+ let (sp, sc) = (self.shape_of(probs), self.shape_of(cache));+ if sp.c != heads || sp.h != 1 {+ self.fail(format!("cached attention over probs {sp:?} with {heads} heads"));+ }+ if sc.h != 1 || sp.w != sc.c {+ self.fail(format!(+ "cached attention over probs {sp:?} and a cache {sc:?}: the key counts differ"+ ));+ }+ if heads == 0 || !sc.w.is_multiple_of(heads) {+ self.fail(format!("{} channels do not split into {heads} heads", sc.w));+ }+ let out = self.tensor(Shape::new(sc.w, 1, 1));+ self.nodes.push(Node::AttnApplyCached { probs, cache, out, heads });+ out+ }++ /// The same elements under a different shape, as one contiguous copy.+ ///+ /// A projection writes `[d_model, 1, 1]` and a position-major cache is `[T, 1, d_model]`, so+ /// appending the step's key means reading `d_model` elements as one *position* rather than as+ /// `d_model` channels. Those are the same bytes in the same order, and this is the relabelling.+ ///+ /// A copy rather than a view for the reason [`Builder::slice_channels`] gives: a view would+ /// have to survive the arena's last-use bookkeeping. It is `d_model` elements, and it reuses+ /// the concatenation path exactly — one [`Op::Copy`], no shader and no new op kind.+ pub fn reshaped(&mut self, input: Id, shape: Shape) -> Id {+ let from = self.shape_of(input);+ if from.len() != shape.len() {+ self.fail(format!("reshaping {from:?} to {shape:?} changes the element count"));+ }+ let out = self.tensor(shape);+ self.nodes.push(Node::Concat { parts: vec![input], out });+ out+ }+ /// The validation, output tensor and scale every score map shares, relative or not. /// /// `q` and `k` may be different lengths: the map is `[heads, queries, keys]`, which for@@ -1986,6 +2087,54 @@ impl<'a> Builder<'a> { invocations: so.len(), }); }+ Node::AttnScoresCached { q, cache, out, heads, scale } => {+ let (sq, so) = (shape(*q), shape(*out));+ ops.push(Op::Dispatch {+ kind: Kind::AttnScoresCached,+ push: Push {+ in0: at(*q)?,+ in1: at(*cache)?,+ out: at(*out)?,+ // `d_model`, which doubles as the cache's per-position stride: a cache is+ // `[keys, 1, d_model]`, so one position is `in_c` elements.+ in_c: sq.c,+ in_h: 1,+ in_w: 1,+ out_c: so.c,+ out_h: so.h,+ out_w: so.w,+ group: *heads,+ param0_bits: scale.to_bits(),+ count: so.len(),+ ..Push::default()+ },+ invocations: so.len(),+ });+ }+ Node::AttnApplyCached { probs, cache, out, heads } => {+ let (sc, so) = (shape(*cache), shape(*out));+ ops.push(Op::Dispatch {+ kind: Kind::AttnApplyCached,+ push: Push {+ in0: at(*probs)?,+ in1: at(*cache)?,+ out: at(*out)?,+ // As above: the cache's stride is `d_model`, which is also the output's+ // channel count because attention preserves the width.+ in_c: so.c,+ in_h: 1,+ // The key count, which is the cache's *channel* count in this layout.+ in_w: sc.c,+ out_c: so.c,+ out_h: so.h,+ out_w: so.w,+ group: *heads,+ count: so.len(),+ ..Push::default()+ },+ invocations: so.len(),+ });+ } Node::AttnScoresRelative { q, k, out, heads, scale, table, offsets } => { let (si, so) = (shape(*q), shape(*out)); ops.push(Op::Dispatch {@@ -2166,6 +2315,8 @@ impl Node { | Node::Affine { out, .. } | Node::LayerNorm { out, .. } | Node::AttnScores { out, .. }+ | Node::AttnScoresCached { out, .. }+ | Node::AttnApplyCached { out, .. } | Node::AttnScoresRelative { out, .. } | Node::AttnApplyRelative { out, .. } | Node::Softmax { out, .. }@@ -2195,6 +2346,8 @@ impl Node { Node::Binary { a, b, .. } => vec![*a, *b], Node::Rotary { input, angles, .. } => vec![*input, *angles], Node::AttnScores { q: a, k: b, .. }+ | Node::AttnScoresCached { q: a, cache: b, .. }+ | Node::AttnApplyCached { probs: a, cache: b, .. } | Node::AttnApply { probs: a, v: b, .. } | Node::AttnScoresRelative { q: a, k: b, .. } | Node::AttnApplyRelative { probs: a, v: b, .. } => {@@ -2403,6 +2556,17 @@ pub(crate) mod tests { Kind::AttnApply | Kind::AttnApplyRelative => { vec![(push.in0, push.group * push.out_w * push.in_w), (push.in1, dense)] }+ // One query against a position-major cache. Q is one position of `in_c`+ // channels; the cache is `out_w` positions of `in_c`. Not `dense`, whose+ // `in_h` and `in_w` are 1 here.+ Kind::AttnScoresCached => {+ vec![(push.in0, push.in_c), (push.in1, push.out_w * push.in_c)]+ }+ // One query's row of probabilities is `in_w` keys long, and the cache is+ // `in_w` positions of `in_c`.+ Kind::AttnApplyCached => {+ vec![(push.in0, push.group * push.in_w), (push.in1, push.in_w * push.in_c)]+ } // One id per position per lane, so the read is `in_c * out_w` and // not `dense` - `in_w` here is the *table's* row count. Kind::Embed => vec![(push.in0, push.in_c * push.out_w)],
library/ml/src/main/rust/src/nets/reference.rs
diff --git a/library/ml/src/main/rust/src/nets/reference.rs b/library/ml/src/main/rust/src/nets/reference.rsindex adf52244ea..c508d5fb62 100644--- a/library/ml/src/main/rust/src/nets/reference.rs+++ b/library/ml/src/main/rust/src/nets/reference.rs@@ -201,6 +201,8 @@ impl Reference { Kind::AttnApply => self.attn_apply(push), Kind::AttnScoresRelative => self.attn_scores_relative(push), Kind::AttnApplyRelative => self.attn_apply_relative(push),+ Kind::AttnScoresCached => self.attn_scores_cached(push),+ Kind::AttnApplyCached => self.attn_apply_cached(push), Kind::Embed => self.embed(push), Kind::Constant => self.constant(push), Kind::AddBroadcast => self.add_broadcast(push),@@ -788,6 +790,52 @@ impl Reference { Ok(()) } + /// [`Self::attn_scores`] for one query against a **position-major** K cache.+ ///+ /// The only difference from [`Self::attn_scores`] is the cache's indexing: a key is a run of+ /// `in_c` elements rather than a channel every `key_stride` apart, which is what makes+ /// appending a position one contiguous copy. `out_w` is the key count, and there is exactly one+ /// query, so the score map is `[heads, 1, keys]` and `softmax` normalises it unchanged.+ 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);+ for head in 0..p.group {+ // Q is one position, so its channels are consecutive.+ let query_base = head * head_dim;+ for key in 0..p.out_w {+ let key_base = key * p.in_c + head * head_dim;+ 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)?;+ }+ self.store(p.out, nchw(p, head, 0, key), total * scale)?;+ }+ }+ Ok(())+ }++ /// [`Self::attn_apply`] for one query against a **position-major** V cache.+ ///+ /// The output is `[d_model, 1, 1]`, back in the channel-major layout the next projection+ /// reads, so the cache layout is confined to the operand that is a cache. `in_w` is the key+ /// count, which in this layout is the cache's channel count.+ fn attn_apply_cached(&mut self, p: &Push) -> Result<(), String> {+ let head_dim = heads(p, p.out_c)?;+ let keys = p.in_w;+ for channel in 0..p.out_c {+ // One query, so a head's row of probabilities is `keys` long and starts here.+ let row = (channel / head_dim) * keys;+ let mut total = 0.0;+ for key in 0..keys {+ total += self.load(p.in0, row + key)?+ * self.load(p.in1, key * p.in_c + channel)?;+ }+ self.store(p.out, nchw(p, channel, 0, 0), total)?;+ }+ Ok(())+ }+ /// [`Self::attn_scores`] plus a relative-position term: nine taps of a learned /// table indexed by `key - query`, in place of the export's product-and-skew. ///@@ -1809,6 +1857,110 @@ mod tests { ); } + #[test]+ fn a_cached_score_map_reads_a_position_as_a_contiguous_run() {+ // The same numbers as `attention_scores_contract_over_channels_and_keep_the_key_axis_last`,+ // laid out the other way round, so the two fixtures pin the layout difference and nothing+ // else. d_model 2, one head, two keys.+ //+ // There, K was `[2, 1, 2]` channel-major with columns (5,7) and (6,8). Here the cache is+ // `[2, 1, 2]` position-major, so key 0 is the run (5,6) and key 1 is (7,8) — the same+ // vectors, contiguous. Q is one position, (1,2).+ //+ // S[0] = 1*5 + 2*6 = 17, S[1] = 1*7 + 2*8 = 23. A shader that read the cache+ // channel-major would get 1*5 + 2*7 = 19 and 1*6 + 2*8 = 22 instead, which is why the+ // fixture is deliberately not symmetric in the two axes.+ let got = two(+ (Shape::new(2, 1, 1), Shape::new(2, 1, 2)),+ (&[1.0, 2.0], &[5.0, 6.0, 7.0, 8.0]),+ |b, q, cache| b.attn_scores_cached(q, cache, 1),+ );+ let scale = 1.0 / 2f32.sqrt();+ close(&got, &[17.0 * scale, 23.0 * scale]);+ }++ #[test]+ fn a_cached_score_map_never_mixes_two_heads() {+ // d_model 4 in two heads, so head 0 owns channels 0-1 of each position and head 1 owns+ // 2-3. The second head's values are a decade larger, so a leak across the boundary moves+ // head 0's scores about a hundredfold rather than subtly.+ //+ // Q is (1,2,10,20). The cache holds two positions of four: (1,2,10,20) and (3,4,30,40).+ // head 0, key 0: 1*1 + 2*2 = 5 head 0, key 1: 1*3 + 2*4 = 11+ // head 1, key 0: 10*10 + 20*20 = 500 head 1, key 1: 10*30 + 20*40 = 1100+ let got = two(+ (Shape::new(4, 1, 1), Shape::new(2, 1, 4)),+ (&[1.0, 2.0, 10.0, 20.0], &[1.0, 2.0, 10.0, 20.0, 3.0, 4.0, 30.0, 40.0]),+ |b, q, cache| b.attn_scores_cached(q, cache, 2),+ );+ // head_dim is 2, so the scale is 1/sqrt(2).+ let scale = 1.0 / 2f32.sqrt();+ close(&got, &[5.0 * scale, 11.0 * scale, 500.0 * scale, 1100.0 * scale]);+ }++ #[test]+ fn a_cached_attention_output_is_channel_major_again() {+ // probs `[1, 1, 2]` over two keys, cache `[2, 1, 3]` position-major: key 0 is (1,2,3) and+ // key 1 is (4,5,6). At weights 0.25 and 0.75 the output is+ // (0.25*1 + 0.75*4, 0.25*2 + 0.75*5, 0.25*3 + 0.75*6) = (3.25, 4.25, 5.25).+ //+ // The output is `[3, 1, 1]`, so the cache layout does not escape this op — which is the+ // property that lets the next projection be an ordinary `conv_point_int8`.+ let got = two(+ (Shape::new(1, 1, 2), Shape::new(2, 1, 3)),+ (&[0.25, 0.75], &[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]),+ |b, probs, cache| b.attn_apply_cached(probs, cache, 1),+ );+ close(&got, &[3.25, 4.25, 5.25]);+ }++ #[test]+ fn a_cached_attention_uses_the_head_only_to_pick_a_row_of_weights() {+ // Two heads over d_model 4, two keys. Head 0's distribution is (1, 0) and head 1's is+ // (0, 1), so head 0's channels come entirely from key 0 and head 1's from key 1.+ //+ // Cache key 0 is (1,2,3,4) and key 1 is (5,6,7,8), so the output is (1,2,7,8). A shader+ // that indexed the probability rows the other way round would give (5,6,3,4).+ let got = two(+ (Shape::new(2, 1, 2), Shape::new(2, 1, 4)),+ (&[1.0, 0.0, 0.0, 1.0], &[1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0]),+ |b, probs, cache| b.attn_apply_cached(probs, cache, 2),+ );+ close(&got, &[1.0, 2.0, 7.0, 8.0]);+ }++ #[test]+ fn a_cached_attention_averages_its_cache_when_every_score_is_equal() {+ // The end-to-end shape of a decode step's self-attention: one query, a two-position cache,+ // scores that are all equal because Q is zero, so softmax is uniform and the output is the+ // mean of the cached values. Anything wrong in the chaining shows up as something other+ // than the midpoint.+ let cache = [1.0f32, 2.0, 5.0, 10.0];+ let got = two(+ (Shape::new(2, 1, 1), Shape::new(2, 1, 2)),+ (&[0.0, 0.0], &cache),+ |b, q, cache| {+ let scores = b.attn_scores_cached(q, cache, 1);+ let probs = b.softmax(scores);+ b.attn_apply_cached(probs, cache, 1)+ },+ );+ close(&got, &[3.0, 6.0]);+ }++ #[test]+ fn a_reshape_is_one_copy_and_the_same_elements() {+ // A projection writes `[d_model, 1, 1]` and a cache position is `[1, 1, d_model]`. Those+ // are the same bytes, and this is the relabelling that lets the two meet.+ let got = one(+ Shape::new(4, 1, 1),+ &[1.0, 2.0, 3.0, 4.0],+ &[],+ |b, x| b.reshaped(x, Shape::new(1, 1, 4)),+ );+ close(&got, &[1.0, 2.0, 3.0, 4.0]);+ }+ #[test] fn attention_scale_is_the_inverse_root_of_the_head_dimension() { // Four channels in four heads is head_dim 1, where the scale is exactly 1, so
library/ml/src/main/rust/src/nets/small100.rs
diff --git a/library/ml/src/main/rust/src/nets/small100.rs b/library/ml/src/main/rust/src/nets/small100.rsindex af907a8dff..561e4a7872 100644--- a/library/ml/src/main/rust/src/nets/small100.rs+++ b/library/ml/src/main/rust/src/nets/small100.rs@@ -163,6 +163,21 @@ pub enum Mode { }, /// The tied logits projection: one `[1024]` state in, two half-vocabularies out. Logits,+ /// One decoder step: the token just produced in, its logits and its new K/V out.+ ///+ /// A step is **one query** against `cache_len + 1` keys — the `cache_len` positions already+ /// decoded plus this one — which is causal by construction and needs no mask. The K and V for+ /// the prefix arrive as ordinary inputs in [`Mode::DecodeStep`]'s declaration order, the step's+ /// own K and V leave as outputs, and the host appends them for the next step.+ ///+ /// Position-major, so appending is one contiguous copy of `d_model` elements rather than+ /// `d_model` scattered ones. See [`crate::nets::Kind::AttnScoresCached`].+ DecodeStep {+ /// Positions already in the cache, which is also the step number.+ cache_len: u32,+ /// Source positions the cross-attention attends over.+ src_len: u32,+ }, } /// Hands out `.maml` tensor indices in the order the layers appear.@@ -220,9 +235,132 @@ pub fn build(weights: &dyn WeightSource, mode: Mode) -> Result<Plan, String> { match mode { Mode::Encode { len } => encode(weights, len), Mode::Logits => logits(weights),+ Mode::DecodeStep { cache_len, src_len } => decode_step(weights, cache_len, src_len), } } +/// 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 |+/// | 6, 7 | | layer 2's |+///+/// The cache pair is **omitted at step 0**, where there is nothing before the current token.+///+/// # Outputs, in declaration order+///+/// | | shape | |+/// | :--- | :--- | :--- |+/// | 0, 1 | `[64056, 1, 1]` | the two logits halves, which the host argmaxes across |+/// | 2, 3 | `[1, 1, 1024]` | layer 0's new self-attention K and V, ready to append |+/// | 4, 5 | | layer 1's |+/// | 6, 7 | | layer 2's |+///+/// # 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+/// six 1024x1024 projections per step. They are not cached here because that would need a fourth+/// pass and a second kind of persistence for a saving the logits projection dwarfs: the head is+/// 131 million multiply-accumulates against the whole decoder's 50 million. Worth revisiting only+/// after `Kind::ConvVecInt8` makes the head cheap.+fn decode_step(weights: &dyn WeightSource, cache_len: u32, src_len: u32) -> Result<Plan, String> {+ if src_len == 0 {+ return Err("a decode step with no source to attend over".into());+ }+ if cache_len >= MAX_POSITIONS {+ return Err(format!("a cache of {cache_len}, at the {MAX_POSITIONS}-position limit"));+ }++ 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]);++ 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, declared up front so the host uploads them in one block rather+ // than interleaved with anything else.+ //+ // None at step 0: the only key is the token itself, and a `[0, 1, 1024]` binding would be a+ // zero-length upload, which Vulkan refuses.+ let caches: Vec<Option<(Id, Id)>> = (0..DECODER_LAYERS)+ .map(|_| {+ (cache_len > 0).then(|| {+ let k = b.input(Shape::new(cache_len, 1, D_MODEL));+ let v = b.input(Shape::new(cache_len, 1, D_MODEL));+ (k, v)+ })+ })+ .collect();++ let mut produced: Vec<Id> = Vec::new();+ for past in &caches {+ // Self-attention, pre-norm, with the cache.+ let normed = b.layer_norm(x, l.take(), EPSILON);+ let q = point(b, l, normed, D_MODEL, Act::None);+ let k_new = point(b, l, normed, D_MODEL, Act::None);+ let v_new = point(b, l, normed, D_MODEL, Act::None);+ // A projection writes `[d_model, 1, 1]`; a cache position is `[1, 1, d_model]`. The same+ // bytes, so this is a relabelling and the append 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));+ let (k, v) = match *past {+ Some((past_k, past_v)) => {+ (b.concat(&[past_k, k_row]), b.concat(&[past_v, v_row]))+ }+ None => (k_row, v_row),+ };+ let scores = b.attn_scores_cached(q, k, HEADS);+ let probs = b.softmax(scores);+ let mixed = b.attn_apply_cached(probs, v, HEADS);+ let projected = point(b, l, mixed, D_MODEL, Act::None);+ x = b.add(x, projected);+ produced.push(k_row);+ produced.push(v_row);++ // 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.+ 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);+ let probs = b.softmax(scores);+ let mixed = b.attn_apply(probs, v, HEADS);+ let projected = point(b, l, mixed, D_MODEL, Act::None);+ x = b.add(x, projected);++ x = feed_forward(b, l, x);+ }+ if l.next != DECODER_NORM {+ return Err(format!("the decoder claims {} tensors, not {DECODER_NORM}", l.next));+ }+ let state = b.layer_norm(x, l.take(), EPSILON);+ if l.next != TENSORS {+ return Err(format!("the decoder norm ends at {}, not {TENSORS}", l.next));+ }++ // The tied head, in the same plan: a separate `Mode::Logits` pass would mean a second+ // `rebuild` and a round trip through the host for a `[1024]` vector.+ let head = &mut Layers { next: HEAD };+ let mut outputs: Vec<Id> = (0..HEAD_SPLITS)+ .map(|_| point(b, head, state, CLASSES_PER_SPLIT, Act::None))+ .collect();+ if head.next != ENCODER {+ return Err(format!("the head claims {} tensors, not {ENCODER}", head.next));+ }+ outputs.append(&mut produced);+ builder.finish(&outputs)+}+ /// The encoder over `len` already-embedded positions. fn encode(weights: &dyn WeightSource, len: u32) -> Result<Plan, String> { if len == 0 {@@ -237,7 +375,7 @@ fn encode(weights: &dyn WeightSource, len: u32) -> Result<Plan, String> { let b = &mut builder; // The tied weight and the whole decoder belong to the other two passes. The trailing encoder // norm is part of this range, so it runs to `DECODER` rather than to `ENCODER_NORM`.- name_host_tensors(b, ENCODER..DECODER);+ name_host_tensors(b, &[ENCODER..DECODER]); let x = b.input(Shape::new(D_MODEL, 1, len)); let mut x = x;@@ -266,7 +404,7 @@ fn logits(weights: &dyn WeightSource) -> Result<Plan, String> { let l = &mut Layers { next: HEAD }; let mut builder = Builder::new(weights); let b = &mut builder;- name_host_tensors(b, HEAD..ENCODER);+ name_host_tensors(b, &[HEAD..ENCODER]); let state = b.input(Shape::new(D_MODEL, 1, 1)); let halves: Vec<Id> = (0..HEAD_SPLITS)@@ -282,10 +420,10 @@ fn logits(weights: &dyn WeightSource) -> Result<Plan, String> { /// /// [`Builder::finish`] refuses an unread tensor, and no one of the three passes reads the whole /// file. Declaring the complement rather than listing it keeps the two in step: adding a layer-/// changes the range and nothing else.-fn name_host_tensors(b: &mut Builder, read: std::ops::Range<usize>) {+/// changes the ranges and nothing else.+fn name_host_tensors(b: &mut Builder, read: &[std::ops::Range<usize>]) { for index in 0..TENSORS {- if !read.contains(&index) {+ if !read.iter().any(|range| range.contains(&index)) { b.host_tensor(index, &dims_of(index)); } }@@ -471,34 +609,39 @@ mod tests { assert!((318 << 20..319 << 20).contains(&file), "{file} bytes"); } - /// The tensor range each pass reads on the device. Everything else it names.+ /// The tensor ranges each pass reads on the device. Everything else it names. /// /// Stated here rather than returned by [`build`] because it is the thing under test: a pass /// that read the wrong range would name the right one and still be wrong.- fn read_by(mode: Mode) -> std::ops::Range<usize> {+ fn read_by(mode: Mode) -> Vec<std::ops::Range<usize>> { match mode {- Mode::Encode { .. } => ENCODER..DECODER,- Mode::Logits => HEAD..ENCODER,+ Mode::Encode { .. } => vec![ENCODER..DECODER],+ Mode::Logits => vec![HEAD..ENCODER],+ Mode::DecodeStep { .. } => vec![HEAD..ENCODER, DECODER..TENSORS], } } #[test]- fn the_passes_partition_the_file_and_every_one_of_them_builds() {+ fn the_passes_cover_the_file_and_every_one_of_them_builds() { // `Builder::finish` only checks that a tensor is read *or* named, so this is what stops- // naming being used to hide a layer the device never touches. The ranges must tile- // `0..TENSORS` with no gap and no overlap.+ // naming being used to hide a layer the device never touches. Together the passes must read+ // every index. //- // The encoder's range runs to `DECODER`, so it covers the trailing encoder norm; the- // decoder's remaining range is `DECODER..TENSORS`, which the decode step claims.- let mut covered: Vec<usize> = Vec::new();- for mode in [Mode::Encode { len: LEN }, Mode::Logits] {+ // Not a partition: the decode step computes the tied head itself, so it and `Mode::Logits`+ // both read `HEAD..ENCODER`. `Mode::Logits` stays because it is the isolated case for the+ // split head, where a device parity run has nothing else in the plan to blame.+ let mut covered = std::collections::BTreeSet::new();+ for mode in [+ Mode::Encode { len: LEN },+ Mode::Logits,+ Mode::DecodeStep { cache_len: 0, src_len: LEN },+ Mode::DecodeStep { cache_len: 3, src_len: LEN },+ ] { let source = Shapes::new(TENSORS); build(&source, mode).unwrap_or_else(|e| panic!("{mode:?}: {e}"));- covered.extend(read_by(mode));+ covered.extend(read_by(mode).into_iter().flatten()); }- covered.extend(DECODER..TENSORS);- covered.sort_unstable();- assert_eq!(covered, (0..TENSORS).collect::<Vec<usize>>());+ assert_eq!(covered.into_iter().collect::<Vec<_>>(), (0..TENSORS).collect::<Vec<_>>()); } #[test]@@ -542,6 +685,109 @@ mod tests { } } + #[test]+ fn a_decode_step_is_three_layers_of_two_attentions() {+ let (_, plan) = plan(Mode::DecodeStep { cache_len: 3, src_len: LEN });+ let mut counts = std::collections::BTreeMap::new();+ for op in &plan.ops {+ if let Op::Dispatch { kind, .. } = op {+ *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 two+ // halves of the tied head.+ assert_eq!(+ counts.get("ConvInt8"),+ Some(&(DECODER_LAYERS * 10 + HEAD_SPLITS)),+ "{counts:?}"+ );+ // Three norms per layer, pre-norm, plus the trailing one.+ assert_eq!(counts.get("LayerNorm"), Some(&(DECODER_LAYERS * 3 + 1)), "{counts:?}");+ // Self-attention is cached and single-query; the cross-attention is not.+ assert_eq!(counts.get("AttnScoresCached"), Some(&DECODER_LAYERS), "{counts:?}");+ assert_eq!(counts.get("AttnApplyCached"), Some(&DECODER_LAYERS), "{counts:?}");+ assert_eq!(counts.get("AttnScores"), Some(&DECODER_LAYERS), "{counts:?}");+ assert_eq!(counts.get("AttnApply"), Some(&DECODER_LAYERS), "{counts:?}");+ assert_eq!(counts.get("Softmax"), Some(&(DECODER_LAYERS * 2)), "{counts:?}");+ // Three residuals per layer.+ assert_eq!(counts.get("Add"), Some(&(DECODER_LAYERS * 3)), "{counts:?}");+ assert_no_aliasing(&plan);+ }++ #[test]+ fn a_decode_step_declares_its_cache_in_and_out() {+ let cache_len = 5;+ let (_, plan) = plan(Mode::DecodeStep { cache_len, src_len: LEN });+ // The token, the encoder output, then a K/V pair per layer.+ assert_eq!(plan.inputs.len(), 2 + DECODER_LAYERS * 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));+ for binding in &plan.inputs[2..] {+ // Position-major: the cache's channels are the positions.+ assert_eq!(binding.shape, Shape::new(cache_len, 1, D_MODEL));+ }+ // Two logits halves, then the step's own K and V per layer.+ assert_eq!(plan.outputs.len(), HEAD_SPLITS + DECODER_LAYERS * 2);+ for binding in &plan.outputs[..HEAD_SPLITS] {+ assert_eq!(binding.shape, Shape::new(CLASSES_PER_SPLIT, 1, 1));+ }+ for binding in &plan.outputs[HEAD_SPLITS..] {+ assert_eq!(binding.shape, Shape::new(1, 1, D_MODEL));+ }+ }++ #[test]+ fn the_first_step_has_no_cache_to_read() {+ // At step 0 the only key is the token itself, so there is nothing to concatenate and no+ // cache input. A `[0, 1, 1024]` binding would be a zero-length upload, which Vulkan+ // refuses and which would make the first step the one special case on the device.+ let (_, plan) = plan(Mode::DecodeStep { cache_len: 0, src_len: LEN });+ assert_eq!(plan.inputs.len(), 2);+ assert_eq!(plan.outputs.len(), HEAD_SPLITS + DECODER_LAYERS * 2);+ // And the scores are over exactly one key.+ for op in &plan.ops {+ if let Op::Dispatch { kind: Kind::AttnScoresCached, push, .. } = op {+ assert_eq!((push.group, push.out_w), (HEADS, 1), "{push:?}");+ }+ }+ assert_no_aliasing(&plan);+ }++ #[test]+ fn a_decode_step_attends_over_the_prefix_and_the_current_token() {+ let cache_len = 7;+ let (_, plan) = plan(Mode::DecodeStep { cache_len, src_len: LEN });+ for op in &plan.ops {+ match op {+ // Self-attention: one query, `cache_len + 1` keys. An off-by-one here would drop+ // the current token from its own attention, which is fluent and wrong.+ Op::Dispatch { kind: Kind::AttnScoresCached, push, .. } => {+ assert_eq!((push.out_h, push.out_w), (1, cache_len + 1), "{push:?}");+ }+ Op::Dispatch { kind: Kind::AttnApplyCached, push, .. } => {+ assert_eq!((push.in_w, push.out_c), (cache_len + 1, D_MODEL), "{push:?}");+ }+ // Cross-attention: one query over the source, which is a different length.+ Op::Dispatch { kind: Kind::AttnScores, push, .. } => {+ assert_eq!((push.out_h, push.out_w), (1, LEN), "{push:?}");+ }+ _ => {}+ }+ }+ }++ #[test]+ fn a_decode_step_over_nothing_or_past_the_cache_is_refused() {+ let source = Shapes::new(TENSORS);+ let error = build(&source, Mode::DecodeStep { cache_len: 0, src_len: 0 })+ .expect_err("no source");+ assert!(error.contains("no source"), "{error}");+ let source = Shapes::new(TENSORS);+ let error = build(&source, Mode::DecodeStep { cache_len: MAX_POSITIONS, src_len: LEN })+ .expect_err("cache full");+ assert!(error.contains("position limit") || error.contains("limit"), "{error}");+ }+ #[test] fn the_head_is_two_ops_over_disjoint_class_ranges() { let (_, plan) = plan(Mode::Logits);
library/ml/src/main/rust/src/vulkan/parity.rs
diff --git a/library/ml/src/main/rust/src/vulkan/parity.rs b/library/ml/src/main/rust/src/vulkan/parity.rsindex 7a310604ca..8b045df8ed 100644--- a/library/ml/src/main/rust/src/vulkan/parity.rs+++ b/library/ml/src/main/rust/src/vulkan/parity.rs@@ -195,6 +195,64 @@ fn the_cnn_spine_agrees_with_the_reference() { ); } +#[test]+#[ignore = "needs a Vulkan device"]+fn cached_attention_agrees_with_the_reference() {+ // A whole decode-step self-attention: one query against a position-major cache, through+ // softmax and back out channel-major. `nets::reference` is the only oracle for the two new+ // shaders, so this is what says the SPIR-V matches it on real hardware.+ //+ // d_model 8 in two heads, five cached positions. The cache is `[5, 1, 8]` — positions as+ // channels — which is the layout that makes appending one position a single contiguous copy.+ // A shader that read it channel-major would produce the right shape from the wrong vectors.+ let query = spread(8, 0.0);+ let cache = spread(5 * 8, 0.7);+ agrees(+ "cached attention",+ &[Shape::new(8, 1, 1), Shape::new(5, 1, 8)],+ &[&query, &cache],+ &[],+ |b, ids| {+ let scores = b.attn_scores_cached(ids[0], ids[1], 2);+ let probs = b.softmax(scores);+ b.attn_apply_cached(probs, ids[1], 2)+ },+ );+}++#[test]+#[ignore = "needs a Vulkan device"]+fn a_cached_score_map_alone_agrees_with_the_reference() {+ // The scores on their own, undivided by a softmax, so a wrong `1 / sqrt(head_dim)` or a+ // transposed head range shows up as a value rather than as a redistribution. Four heads of+ // two over three positions.+ let query = spread(8, 0.2);+ let cache = spread(3 * 8, 1.1);+ agrees(+ "cached scores",+ &[Shape::new(8, 1, 1), Shape::new(3, 1, 8)],+ &[&query, &cache],+ &[],+ |b, ids| b.attn_scores_cached(ids[0], ids[1], 4),+ );+}++#[test]+#[ignore = "needs a Vulkan device"]+fn a_reshape_moves_the_same_elements_on_the_device() {+ // The relabelling that lets a `[d_model, 1, 1]` projection become a `[1, 1, d_model]` cache+ // position. One `vkCmdCopyBuffer`, so what is under test is that the shapes either side agree+ // about the element count.+ let x = spread(16, 0.3);+ agrees(+ "reshape",+ &[Shape::new(16, 1, 1)],+ &[&x],+ &[],+ |b, ids| b.reshaped(ids[0], Shape::new(1, 1, 16)),+ );+}+ #[test] #[ignore = "needs a Vulkan device"] fn rotary_agrees_with_the_reference() {
library/ml/src/main/rust/src/vulkan/pipeline.rs
diff --git a/library/ml/src/main/rust/src/vulkan/pipeline.rs b/library/ml/src/main/rust/src/vulkan/pipeline.rsindex 0abcfc9f42..d8ee7dd22f 100644--- a/library/ml/src/main/rust/src/vulkan/pipeline.rs+++ b/library/ml/src/main/rust/src/vulkan/pipeline.rs@@ -54,9 +54,13 @@ const CONV_POINT_INT8: &[u8] = const CONSTANT: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/constant.comp.spv")); const ADD_BCAST: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/add_bcast.comp.spv")); const ROTARY: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/rotary.comp.spv"));+const ATTN_SCORES_CACHED: &[u8] =+ include_bytes!(concat!(env!("OUT_DIR"), "/attn_scores_cached.comp.spv"));+const ATTN_APPLY_CACHED: &[u8] =+ include_bytes!(concat!(env!("OUT_DIR"), "/attn_apply_cached.comp.spv")); /// Every shader, in the order [`Pipelines::create`] destructures them.-const SPIRV: [&[u8]; 24] = [+const SPIRV: [&[u8]; 26] = [ CONV, CONV_TRANSPOSE, MAXPOOL,@@ -81,6 +85,8 @@ const SPIRV: [&[u8]; 24] = [ CONSTANT, ADD_BCAST, ROTARY,+ ATTN_SCORES_CACHED,+ ATTN_APPLY_CACHED, ]; /// `local_size_x` in `shaders/common.glsl`. A dispatch covers `ceil(invocations / this)`@@ -133,6 +139,8 @@ pub struct Pipelines { constant: vk::Pipeline, add_bcast: vk::Pipeline, rotary: vk::Pipeline,+ attn_scores_cached: vk::Pipeline,+ attn_apply_cached: vk::Pipeline, } impl Pipelines {@@ -346,6 +354,8 @@ impl Pipelines { constant, add_bcast, rotary,+ attn_scores_cached,+ attn_apply_cached, ] = match <[vk::Pipeline; SPIRV.len()]>::try_from(built) { Ok(all) => all, Err(built) => {@@ -386,6 +396,8 @@ impl Pipelines { constant, add_bcast, rotary,+ attn_scores_cached,+ attn_apply_cached, }) } @@ -408,6 +420,8 @@ impl Pipelines { Kind::AttnApply => self.attn_apply, Kind::AttnScoresRelative => self.attn_scores_relative, Kind::AttnApplyRelative => self.attn_apply_relative,+ Kind::AttnScoresCached => self.attn_scores_cached,+ Kind::AttnApplyCached => self.attn_apply_cached, Kind::Embed => self.embed, Kind::ConvInt8 => self.conv_int8, Kind::ConvPoint => self.conv_point,@@ -448,6 +462,8 @@ impl Pipelines { self.constant, self.add_bcast, self.rotary,+ self.attn_scores_cached,+ self.attn_apply_cached, ] { device.destroy_pipeline(pipeline, None); }