Modern Apps git

← Modern-Apps.git

library:ml: scaled dot-product attention over [d_model, 1, T]

Commit
562a5fe74bc4e4dd90d139dd3847fc1ec364636a
Author
vayun-mathur <[email protected]>
When
2026-08-27 18:51 UTC (3 months ago)
Parents
2d74f15

Diff

library/ml/src/main/rust/shaders/attn_apply.comp
diff --git a/library/ml/src/main/rust/shaders/attn_apply.comp b/library/ml/src/main/rust/shaders/attn_apply.compnew file mode 100644index 0000000000..f037df8dd2--- /dev/null+++ b/library/ml/src/main/rust/shaders/attn_apply.comp@@ -0,0 +1,48 @@+#version 450+//! `O[h][d][i] = sum_j S[h][i][j] * V[h][d][j]`, the second half of attention.+//!+//! Two uses, one per transformer block in PP-OCRv5 recognition.+//!+//! # Back into the layout it started in+//!+//! `S` is `[heads, T, T]` from `softmax.comp`; `V` and the output are `[d_model, 1, T]`,+//! the same layout every projection in this runtime reads and writes. So the head+//! concatenation that follows attention is not an op: output channel `c` belongs to head+//! `c / head_dim` and is written in place, which *is* the concatenated result. No+//! `Reshape` and no `Permute` on this side either.+//!+//! One invocation per output element, reducing over the `T` keys. Note that `V` needs no+//! head arithmetic at all — channel `c` of `V` is exactly channel `c` of the output — so+//! the head index is used only to pick which of `S`'s planes to read.+//!+//! # 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. Accumulating in `float` like+//! everywhere else here is more than enough; the fp16 store at the end is the only+//! rounding.++#include "common.glsl"++void main() {+    uint index = global_index();+    if (index >= p.count) {+        return;+    }+    // The output is `[d_model, 1, T]`, so this is (channel, 0, query).+    uint channel, unused_row, query;+    unpack(index, channel, unused_row, query);++    uint keys = p.out_w;+    uint head_dim = p.out_c / p.group;+    // `S[head][query][*]`, contiguous in the key index.+    uint row = p.in0 + ((channel / head_dim) * keys + query) * keys;+    // `V[channel][*]`, likewise contiguous, because `V`'s height is 1.+    uint values = p.in1 + channel * keys;++    float total = 0.0;+    for (uint j = 0u; j < keys; j++) {+        total += float(arena[row + j]) * float(arena[values + j]);+    }+    arena[p.out_at + index] = float16_t(total);+}
library/ml/src/main/rust/shaders/attn_scores.comp
diff --git a/library/ml/src/main/rust/shaders/attn_scores.comp b/library/ml/src/main/rust/shaders/attn_scores.compnew file mode 100644index 0000000000..319593f076--- /dev/null+++ b/library/ml/src/main/rust/shaders/attn_scores.comp@@ -0,0 +1,61 @@+#version 450+//! `S[h][i][j] = scale * sum_d Q[h][d][i] * K[h][d][j]`, the first half of attention.+//!+//! Two uses, one per transformer block in PP-OCRv5 recognition.+//!+//! # The contraction is over the middle axis, and that is the whole point+//!+//! Q and K arrive as `[d_model, 1, T]` — the layout the CNN backbone already produces,+//! see `nets::Kind::LayerNorm` for why this runtime keeps it. Read as `[heads, head_dim,+//! T]` those are the same bytes in the same order, so a head is a run of channels and+//! splitting `d_model` into heads costs nothing: no `Permute`, no `Reshape`, no copy.+//! `p.group` carries the head count and this indexes accordingly.+//!+//! What it costs is that the reduction walks `head_dim` channels a stride apart rather+//! than a contiguous vector. At `head_dim` 15 that is 15 strided pairs per score. The+//! alternative — transposing to `[T, d_model]` so each head's vector is contiguous —+//! buys a contiguous read here and pays two permutes of the whole sequence per+//! attention, twice per block.+//!+//! # One invocation per score+//!+//! The output is `[heads, T, T]`, so there are `heads * T * T` invocations and each+//! reduces `head_dim` products. That is the parallel axis: `T` is around 80 for a line+//! of text, so this is tens of thousands of independent invocations against `head_dim`+//! serial steps each — the opposite balance to `gap.comp`, which has only channels to+//! spread across.+//!+//! # Scale+//!+//! `1 / sqrt(head_dim)`, arriving as raw `f32` bits in `p.param0_bits`. It is derived+//! from the head geometry by `nets::Builder::attn_scores` rather than read from the+//! weights file, because it is not a trained value — it is a property of the shape.+//!+//! Applied here, to the accumulator, rather than to Q's projection weights: folding it+//! there would work and would make the scale invisible in the one place a reader looks+//! to check it.++#include "common.glsl"++void main() {+    uint index = global_index();+    if (index >= p.count) {+        return;+    }+    // The output is `[heads, T, T]`, so `unpack` gives head, query and key directly.+    uint head, query, key;+    unpack(index, head, query, key);++    // Q and K are `[d_model, 1, T]`: one channel every `in_h * in_w` elements, which is+    // `T`. A head owns `head_dim` consecutive channels starting at `head * head_dim`.+    uint head_dim = p.in_c / p.group;+    uint stride = p.in_h * p.in_w;+    uint base = head * head_dim * stride;++    float total = 0.0;+    for (uint d = 0u; d < head_dim; d++) {+        uint channel = base + d * stride;+        total += float(arena[p.in0 + channel + query]) * float(arena[p.in1 + channel + key]);+    }+    arena[p.out_at + index] = float16_t(total * uintBitsToFloat(p.param0_bits));+}
library/ml/src/main/rust/shaders/softmax.comp
diff --git a/library/ml/src/main/rust/shaders/softmax.comp b/library/ml/src/main/rust/shaders/softmax.compnew file mode 100644index 0000000000..db0970bbf4--- /dev/null+++ b/library/ml/src/main/rust/shaders/softmax.comp@@ -0,0 +1,62 @@+#version 450+//! Softmax over the **last** axis, one invocation per row.+//!+//! Two uses, both on an attention score map in PP-OCRv5 recognition.+//!+//! # Why the last axis, and why that needs no indexing+//!+//! The scores are `[heads, T, T]` with the key index innermost, so a row — one query's+//! distribution over every key — is a contiguous run of `out_w` elements. The row a+//! given invocation owns is therefore just `row * out_w`, and `p.count` is the number of+//! rows (`out_c * out_h`) rather than the element count. No `unpack` and no stride.+//!+//! That is only true because `nets::Kind::AttnScores` chose to emit the key index last.+//! A softmax over any other axis of this runtime's tensors would be a different shader,+//! and there is no use for one.+//!+//! # The maximum is subtracted, and it is not optional+//!+//! `exp` here is fp32, which overflows to infinity a little past 88. Scores are scaled+//! by `1 / sqrt(head_dim)` before they arrive so they are usually well inside that, but+//! "usually" is doing no work in a shader: one saturated activation upstream turns the+//! whole row into `inf / inf` and every probability into a NaN. Subtracting the row+//! maximum first makes the largest term exactly `exp(0)`, which also means the+//! denominator is at least 1 and the division cannot blow up.+//!+//! The result is unchanged in exact arithmetic — `exp(x - m) / sum(exp(x - m))` is the+//! same function — so this costs one extra pass over a row of `T` and buys the property+//! that the output is always a distribution.+//!+//! # Three passes over the row+//!+//! Maximum, then sum, then store, re-evaluating `exp` in the third rather than keeping+//! the row in registers: `T` is around 80 for a line of text, which is far too large for+//! a fixed-size local array and too small for the bandwidth to matter.++#include "common.glsl"++void main() {+    uint row = global_index();+    if (row >= p.count) {+        return;+    }+    uint at = p.in0 + row * p.out_w;++    // The most negative fp16 rather than -inf, matching `maxpool.comp`: every row here+    // is non-empty, so the seed is never the answer.+    float peak = -65504.0;+    for (uint i = 0u; i < p.out_w; i++) {+        peak = max(peak, float(arena[at + i]));+    }++    float total = 0.0;+    for (uint i = 0u; i < p.out_w; i++) {+        total += exp(float(arena[at + i]) - peak);+    }+    float inverse = 1.0 / total;++    uint out_row = p.out_at + row * p.out_w;+    for (uint i = 0u; i < p.out_w; i++) {+        arena[out_row + i] = float16_t(exp(float(arena[at + i]) - peak) * inverse);+    }+}
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 486dd20935..27baafd1bf 100644--- a/library/ml/src/main/rust/src/nets/mod.rs+++ b/library/ml/src/main/rust/src/nets/mod.rs@@ -171,12 +171,35 @@ pub enum Kind {     /// `d_model` 120 that is 120 loads a stride apart per position, which is nothing     /// against what a contiguous layout would cost in permutes.     LayerNorm,+    /// `S[h][i][j] = scale * sum_d Q[h][d][i] * K[h][d][j]`, attention's score map.+    ///+    /// Contracts over the *middle* axis of `[heads, head_dim, T]`, which is what makes+    /// the head split free — see [`Kind::LayerNorm`]. Takes the head count in+    /// [`Push::group`] and `1 / sqrt(head_dim)` in [`Push::param0_bits`].+    ///+    /// The output is `[heads, T, T]` with the key index innermost, so the row a+    /// [`Kind::Softmax`] normalises is contiguous.+    AttnScores,+    /// Softmax over the last axis, one row at a time.+    ///+    /// Kept separate from [`Kind::AttnScores`] rather than fused into it. Fusing would+    /// save writing a `heads * T * T` intermediate — 100 KiB at the recogniser's sizes,+    /// which is not a cost worth a shader that does two things — and would give up the+    /// per-score parallelism, since a fused pass has to be one invocation per *row* to+    /// see the whole distribution it is normalising.+    Softmax,+    /// `O[h][d][i] = sum_j S[h][i][j] * V[h][d][j]`, attention's weighted sum.+    ///+    /// Writes `[d_model, 1, T]`, so the head concatenation that normally follows+    /// attention is not an op: output channel `c` belongs to head `c / head_dim` and+    /// lands where the concatenated result wants it. Head count in [`Push::group`].+    AttnApply, }  /// The push-constant block every shader declares. /// /// `repr(C)` so field order is declaration order, which is what the SPIR-V offsets-/// assume. Deliberately one block shared by all seven pipelines: it fits inside the+/// assume. Deliberately one block shared by every pipeline: it fits inside the /// 128 bytes the spec guarantees (asserted in [`tests`]), so there is a single /// pipeline layout, no uniform buffers and no descriptor writes after setup. #[repr(C)]@@ -227,7 +250,8 @@ pub struct Push {     /// Element offset of the per-channel slope [`Act::PRelu`] reads, in the weights     /// buffer. Zero and unread for every other activation.     pub act_weight: u32,-    /// [`Kind::Affine`]'s multiplier, as raw bits. Unread by everything else.+    /// [`Kind::Affine`]'s multiplier, or [`Kind::AttnScores`]'s `1 / sqrt(head_dim)`,+    /// as raw bits. Unread by everything else.     ///     /// `f32` bits rather than an `f32` field so [`Push`] stays all-`u32` and     /// `push_bytes` can keep treating it as a plain byte block with no padding.@@ -235,6 +259,9 @@ pub struct Push {     /// [`Kind::Affine`]'s addend, or [`Kind::LayerNorm`]'s epsilon.     pub param1_bits: u32,     /// Output elements, so an over-dispatched workgroup can bail.+    ///+    /// Not always the element count: [`Kind::LayerNorm`] and [`Kind::Softmax`] each run+    /// one invocation over a whole reduction, so for them this is the number of those.     pub count: u32, } @@ -397,6 +424,23 @@ enum Node {         beta: u32,         epsilon: f32,     },+    AttnScores {+        q: Id,+        k: Id,+        out: Id,+        heads: u32,+        scale: f32,+    },+    Softmax {+        input: Id,+        out: Id,+    },+    AttnApply {+        probs: Id,+        v: Id,+        out: Id,+        heads: u32,+    }, }  /// Records a forward pass, then packs and resolves it.@@ -739,6 +783,64 @@ impl<'a> Builder<'a> {         out     } +    /// Attention scores from `q` and `k`, both `[d_model, 1, T]`, into `[heads, T, T]`.+    ///+    /// The `1 / sqrt(head_dim)` scale is derived here rather than taken as an argument:+    /// it is a property of the head geometry, not a trained value, so there is no call+    /// site that could legitimately pass a different one.+    pub fn attn_scores(&mut self, q: Id, k: Id, heads: u32) -> Id {+        let (sq, sk) = (self.shape_of(q), self.shape_of(k));+        if sq != sk {+            self.fail(format!("attention over q {sq:?} and k {sk:?}"));+        }+        if sq.h != 1 {+            self.fail(format!(+                "attention on {sq:?}: a sequence is [d_model, 1, T], so a height above \+                 one would silently reinterpret the layout"+            ));+        }+        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, sq.w, sq.w));+        self.nodes.push(Node::AttnScores { q, k, out, heads, scale });+        out+    }++    /// Softmax over the last axis, which for a score map is one query's distribution.+    pub fn softmax(&mut self, input: Id) -> Id {+        let shape = self.shape_of(input);+        if shape.w == 0 {+            self.fail(format!("a softmax over {shape:?}, whose last axis is empty"));+        }+        let out = self.tensor(shape);+        self.nodes.push(Node::Softmax { input, out });+        out+    }++    /// Apply `probs`, a `[heads, T, T]` score map, to `v`, a `[d_model, 1, T]` sequence.+    pub fn attn_apply(&mut self, probs: Id, v: Id, heads: u32) -> Id {+        let (sp, sv) = (self.shape_of(probs), self.shape_of(v));+        if sp != Shape::new(heads, sv.w, sv.w) {+            self.fail(format!(+                "attention weights {sp:?} do not match {heads} heads over a sequence of \+                 {} from {sv:?}",+                sv.w+            ));+        }+        if sv.h != 1 {+            self.fail(format!("attention values {sv:?} are not [d_model, 1, T]"));+        }+        if heads == 0 || !sv.c.is_multiple_of(heads) {+            self.fail(format!("{} channels do not split into {heads} heads", sv.c));+        }+        let out = self.tensor(sv);+        self.nodes.push(Node::AttnApply { probs, v, out, heads });+        out+    }+     /// Pack the arena and resolve every offset, with `outputs` as the result tensors.     pub fn finish(mut self, outputs: &[Id]) -> Result<Plan, String> {         self.pinned.extend_from_slice(outputs);@@ -1032,6 +1134,71 @@ impl<'a> Builder<'a> {                     invocations: positions,                 });             }+            Node::AttnScores { q, k, out, heads, scale } => {+                let (si, so) = (shape(*q), shape(*out));+                ops.push(Op::Dispatch {+                    kind: Kind::AttnScores,+                    push: Push {+                        in0: at(*q)?,+                        in1: at(*k)?,+                        out: at(*out)?,+                        in_c: si.c,+                        in_h: si.h,+                        in_w: si.w,+                        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::Softmax { input, out } => {+                let so = shape(*out);+                // One invocation per row of the last axis, each normalising `out_w`+                // contiguous elements, so the dispatch is rows rather than elements.+                let rows = so.c * so.h;+                ops.push(Op::Dispatch {+                    kind: Kind::Softmax,+                    push: Push {+                        in0: at(*input)?,+                        out: at(*out)?,+                        in_c: so.c,+                        in_h: so.h,+                        in_w: so.w,+                        out_c: so.c,+                        out_h: so.h,+                        out_w: so.w,+                        count: rows,+                        ..Push::default()+                    },+                    invocations: rows,+                });+            }+            Node::AttnApply { probs, v, out, heads } => {+                let so = shape(*out);+                ops.push(Op::Dispatch {+                    kind: Kind::AttnApply,+                    push: Push {+                        in0: at(*probs)?,+                        in1: at(*v)?,+                        out: at(*out)?,+                        in_c: so.c,+                        in_h: so.h,+                        in_w: so.w,+                        out_c: so.c,+                        out_h: so.h,+                        out_w: so.w,+                        group: *heads,+                        count: so.len(),+                        ..Push::default()+                    },+                    invocations: so.len(),+                });+            }         }         Ok(())     }@@ -1047,6 +1214,9 @@ impl Node {             | Node::Binary { out, .. }             | Node::Affine { out, .. }             | Node::LayerNorm { out, .. }+            | Node::AttnScores { out, .. }+            | Node::Softmax { out, .. }+            | Node::AttnApply { out, .. }             | Node::Concat { out, .. } => *out,         }     }@@ -1058,8 +1228,12 @@ impl Node {             | Node::Resize { input, .. }             | Node::Affine { input, .. }             | Node::LayerNorm { input, .. }+            | Node::Softmax { input, .. }             | Node::GlobalAvgPool { input, .. } => vec![*input],             Node::Binary { a, b, .. } => vec![*a, *b],+            Node::AttnScores { q: a, k: b, .. } | Node::AttnApply { probs: a, v: b, .. } => {+                vec![*a, *b]+            }             Node::Concat { parts, .. } => parts.clone(),         }     }@@ -1208,15 +1382,25 @@ pub(crate) mod tests {                 Op::Copy { src, dst, elems } => ((dst, elems), vec![(src, elems)]),                 Op::Dispatch { kind, push, .. } => {                     let dense = push.in_c * push.in_h * push.in_w;+                    // Not `push.count`: the reducing kinds dispatch one invocation per+                    // reduction rather than per element, so their `count` understates+                    // what they write. Every output here is dense.+                    let written = push.out_c * push.out_h * push.out_w;                     let reads = match kind {-                        Kind::Add => vec![(push.in0, push.count), (push.in1, push.count)],+                        Kind::Add => vec![(push.in0, written), (push.in1, written)],                         // The gate is one value per channel, broadcast over H and W.                         Kind::MulBroadcast => {-                            vec![(push.in0, push.count), (push.in1, push.in_c)]+                            vec![(push.in0, written), (push.in1, push.in_c)]+                        }+                        // Q and K are both whole sequences.+                        Kind::AttnScores => vec![(push.in0, dense), (push.in1, dense)],+                        // The score map is `[heads, T, T]`; V is a sequence.+                        Kind::AttnApply => {+                            vec![(push.in0, push.group * push.out_w * push.out_w), (push.in1, dense)]                         }                         _ => vec![(push.in0, dense)],                     };-                    ((push.out, push.count), reads)+                    ((push.out, written), reads)                 }             };             for read in reads {
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 47e6eb4ea4..f6c1d0daef 100644--- a/library/ml/src/main/rust/src/nets/reference.rs+++ b/library/ml/src/main/rust/src/nets/reference.rs@@ -179,6 +179,9 @@ impl Reference {                     Kind::MulBroadcast => self.mul_broadcast(push),                     Kind::Affine => self.affine(push),                     Kind::LayerNorm => self.layer_norm(push),+                    Kind::AttnScores => self.attn_scores(push),+                    Kind::Softmax => self.softmax(push),+                    Kind::AttnApply => self.attn_apply(push),                 },             };             result.map_err(|e| format!("step {step} ({op:?}): {e}"))?;@@ -476,6 +479,83 @@ impl Reference {         Ok(())     } +    /// `S[h][i][j] = scale * sum_d Q[h][d][i] * K[h][d][j]`.+    ///+    /// Q and K are `[d_model, 1, T]`; the output is `[heads, T, T]`. A head is a run of+    /// `in_c / group` consecutive channels, which is what makes the split free — there is+    /// no transpose anywhere in this, by construction.+    fn attn_scores(&mut self, p: &Push) -> Result<(), String> {+        let head_dim = heads(p, p.in_c)?;+        let stride = p.in_h * p.in_w;+        let scale = f32::from_bits(p.param0_bits);+        for head in 0..p.group {+            let base = head * head_dim * stride;+            for query in 0..p.out_h {+                for key in 0..p.out_w {+                    let mut total = 0.0;+                    for d in 0..head_dim {+                        let channel = base + d * stride;+                        total += self.load(p.in0, channel + query)?+                            * self.load(p.in1, channel + key)?;+                    }+                    self.store(p.out, nchw(p, head, query, key), total * scale)?;+                }+            }+        }+        Ok(())+    }++    /// Softmax over the last axis, `count` contiguous rows of `out_w`.+    ///+    /// The row maximum is subtracted first, as `softmax.comp` does. That is not a+    /// refinement: without it a row containing a large score exponentiates to infinity in+    /// fp32 and every probability in it becomes a NaN.+    fn softmax(&mut self, p: &Push) -> Result<(), String> {+        if p.out_w == 0 {+            return Err("a softmax over an empty axis".into());+        }+        for row in 0..p.count {+            let at = row * p.out_w;+            let mut peak = -65504.0f32;+            for i in 0..p.out_w {+                peak = peak.max(self.load(p.in0, at + i)?);+            }+            let mut total = 0.0;+            for i in 0..p.out_w {+                total += (self.load(p.in0, at + i)? - peak).exp();+            }+            // The peak's own term is `exp(0)`, so this is at least 1.+            let inverse = 1.0 / total;+            for i in 0..p.out_w {+                let value = (self.load(p.in0, at + i)? - peak).exp() * inverse;+                self.store(p.out, at + i, value)?;+            }+        }+        Ok(())+    }++    /// `O[h][d][i] = sum_j S[h][i][j] * V[h][d][j]`.+    ///+    /// `S` is `[heads, T, T]` at `in0`; `V` and the output are `[d_model, 1, T]`. The+    /// head index picks a plane of `S` and nothing else — channel `c` of `V` is channel+    /// `c` of the output — which is why concatenating the heads afterwards is not an op.+    fn attn_apply(&mut self, p: &Push) -> Result<(), String> {+        let head_dim = heads(p, p.out_c)?;+        let keys = p.out_w;+        for channel in 0..p.out_c {+            let row = (channel / head_dim) * keys * keys;+            for query in 0..keys {+                let mut total = 0.0;+                for key in 0..keys {+                    total += self.load(p.in0, row + query * keys + key)?+                        * self.load(p.in1, channel * keys + key)?;+                }+                self.store(p.out, nchw(p, channel, 0, query), total)?;+            }+        }+        Ok(())+    }+     /// `out[c][y][x] = a[c][y][x] * b[c]`, the excite half of a squeeze-excite block.     fn mul_broadcast(&mut self, p: &Push) -> Result<(), String> {         for oc in 0..p.out_c {@@ -492,6 +572,19 @@ impl Reference {     } } +/// `channels / group`, the head dimension, refusing the split the builder should have+/// caught.+fn heads(p: &Push, channels: u32) -> Result<u32, String> {+    if p.group == 0 || !channels.is_multiple_of(p.group) {+        return Err(format!("{channels} channels do not split into {} heads", p.group));+    }+    let head_dim = channels / p.group;+    if head_dim == 0 {+        return Err(format!("{} heads for {channels} channels", p.group));+    }+    Ok(head_dim)+}+ /// `(in_c / group, out_c / group)`, refusing the divisions the builder should have /// caught. fn groups(p: &Push) -> Result<(u32, u32), String> {@@ -731,6 +824,31 @@ mod tests {         run(&plan, given.data(), input).expect("the fixture plan runs")     } +    /// [`one`], for the ops whose two operands are different shapes.+    ///+    /// Attention cannot be checked with one tensor used twice: `Q . K^T` is symmetric+    /// when `Q == K`, so a fixture built that way passes with the two operands swapped+    /// and with the query and key axes transposed.+    fn two(+        shapes: (Shape, Shape),+        inputs: (&[f32], &[f32]),+        record: impl FnOnce(&mut Builder, Id, Id) -> Id,+    ) -> Vec<f32> {+        let given = Given::new(&[]).expect("no tensors");+        let mut builder = Builder::new(&given);+        let first = builder.input(shapes.0);+        let second = builder.input(shapes.1);+        let last = record(&mut builder, first, second);+        let plan = builder.finish(&[last]).expect("the fixture plan builds");+        super::super::tests::assert_no_aliasing(&plan);+        let outputs =+            run_multi(&plan, given.data(), &[inputs.0, inputs.1]).expect("the fixture plan runs");+        match <[Vec<f32>; 1]>::try_from(outputs) {+            Ok([only]) => only,+            Err(other) => panic!("{} outputs", other.len()),+        }+    }+     fn close(got: &[f32], want: &[f32]) {         assert_eq!(got.len(), want.len(), "{got:?} vs {want:?}");         for (i, (&g, &w)) in got.iter().zip(want).enumerate() {@@ -915,6 +1033,9 @@ mod tests {         assert_eq!(Act::Relu.code(), act::RELU);         assert_eq!(Act::HardSwish.code(), act::HARDSWISH);         assert_eq!(Act::Sigmoid.code(), act::SIGMOID);+        assert_eq!(Act::PRelu(0).code(), act::PRELU);+        assert_eq!(Act::Clip01.code(), act::CLIP01);+        assert_eq!(Act::Swish.code(), act::SWISH);     }      #[test]@@ -1163,6 +1284,187 @@ mod tests {         assert!(got.iter().all(|v| v.is_finite()), "{got:?}");     } +    #[test]+    fn attention_scores_contract_over_channels_and_keep_the_key_axis_last() {+        // d_model 2, one head, T 2, so `scale` is 1/sqrt(2). Q and K are `[c, 1, T]`+        // channel-major, so Q's columns are (1,3) and (2,4) and K's are (5,7) and (6,8).+        //+        // Distinct operands on purpose: Q.K^T with Q == K is symmetric, and a symmetric+        // fixture passes with the query and key axes transposed. Here S[0][1] is 30 and+        // S[1][0] is 38.+        let got = two(+            (Shape::new(2, 1, 2), Shape::new(2, 1, 2)),+            (&[1.0, 2.0, 3.0, 4.0], &[5.0, 6.0, 7.0, 8.0]),+            |b, q, k| b.attn_scores(q, k, 1),+        );+        let scale = 1.0 / 2f32.sqrt();+        close(&got, &[26.0 * scale, 30.0 * scale, 38.0 * scale, 44.0 * scale]);+    }++    #[test]+    fn attention_scores_never_mix_two_heads() {+        // d_model 4 in two heads, so head 0 owns channels 0-1 and head 1 channels 2-3.+        // The second head's values are a decade larger, so any leak across the boundary+        // moves head 0's scores by about a hundredfold rather than subtly.+        //+        // Q == K here, which is fine: what is under test is the channel range each head+        // reads, and the axis convention is pinned by the fixture above.+        let sequence = [1.0, 2.0, 3.0, 4.0, 10.0, 20.0, 30.0, 40.0];+        let got = two(+            (Shape::new(4, 1, 2), Shape::new(4, 1, 2)),+            (&sequence, &sequence),+            |b, q, k| b.attn_scores(q, k, 2),+        );+        // head_dim is 2, so the scale is still 1/sqrt(2).+        let scale = 1.0 / 2f32.sqrt();+        close(+            &got,+            &[+                10.0 * scale, 14.0 * scale, 14.0 * scale, 20.0 * scale, //+                1000.0 * scale, 1400.0 * scale, 1400.0 * scale, 2000.0 * scale,+            ],+        );+    }++    #[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+        // this fixture is the raw product and isolates the scale from the contraction.+        // At one head the same tensors would be divided by 2 instead.+        let got = two(+            (Shape::new(4, 1, 1), Shape::new(4, 1, 1)),+            (&[1.0, 2.0, 3.0, 4.0], &[5.0, 6.0, 7.0, 8.0]),+            |b, q, k| b.attn_scores(q, k, 4),+        );+        close(&got, &[5.0, 12.0, 21.0, 32.0]);+    }++    #[test]+    fn softmax_normalises_each_row_of_the_last_axis_on_its_own() {+        // `[2, 2, 2]` is four rows of two, the shape a score map has. Rows are (1,2),+        // (5,5), (0,100) and (-3,-3): a plain pair, two ties at different offsets, and+        // one row whose spread would overflow.+        let got = one(+            Shape::new(2, 2, 2),+            &[1.0, 2.0, 5.0, 5.0, 0.0, 100.0, -3.0, -3.0],+            &[],+            |b, x| b.softmax(x),+        );+        let pair = (-1.0f32).exp() / (1.0 + (-1.0f32).exp());+        close(+            &got,+            &[+                pair, 1.0 - pair, //+                0.5, 0.5, //+                0.0, 1.0, //+                0.5, 0.5,+            ],+        );+        // Every row is a distribution. Two equal values summing to 1 is what a shader+        // that forgot to divide would also produce for rows 2 and 4, so the sum is+        // checked for all of them.+        for (row, pair) in got.chunks_exact(2).enumerate() {+            let total: f32 = pair.iter().sum();+            assert!((total - 1.0).abs() < 2e-3, "row {row} sums to {total}");+        }+    }++    #[test]+    fn softmax_subtracts_the_row_maximum_rather_than_exponentiating_directly() {+        // exp overflows fp32 a little past 88, so a row containing 100 sums to infinity+        // and every probability in it becomes a NaN. Subtracting the maximum first makes+        // the largest term exp(0), which cannot overflow and also floors the denominator+        // at 1.+        let got = one(Shape::new(1, 1, 3), &[100.0, 99.0, -100.0], &[], |b, x| b.softmax(x));+        assert!(got.iter().all(|v| v.is_finite()), "{got:?}");+        let expected = 1.0 / (1.0 + (-1.0f32).exp());+        close(&got, &[expected, 1.0 - expected, 0.0]);+    }++    #[test]+    fn attention_applies_a_row_of_weights_across_the_keys_not_the_queries() {+        // One head, d_model 2, T 2. Weights are `[heads, T, T]` with the key innermost,+        // so query 0 mixes (0.25, 0.75) and query 1 takes key 0 alone.+        //+        // V's columns are (10, 3) and (20, 7). Reading the weight matrix transposed gives+        // 22.5 for the first output instead of 17.5, which is why the rows differ.+        let got = two(+            (Shape::new(1, 2, 2), Shape::new(2, 1, 2)),+            (&[0.25, 0.75, 1.0, 0.0], &[10.0, 20.0, 3.0, 7.0]),+            |b, probs, v| b.attn_apply(probs, v, 1),+        );+        close(&got, &[17.5, 10.0, 6.0, 3.0]);+    }++    #[test]+    fn attention_uses_the_head_only_to_pick_a_plane_of_weights() {+        // Two heads over d_model 4. Head 0's weights are the identity and head 1's swap+        // the two keys, so the expected output is V with its last two channels reversed+        // along T and the first two untouched.+        //+        // This is the claim that makes the head concatenation free: channel `c` of V is+        // channel `c` of the output, and the head index selects nothing but which plane+        // of the score map to read.+        let got = two(+            (Shape::new(2, 2, 2), Shape::new(4, 1, 2)),+            (+                &[1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0],+                &[1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0],+            ),+            |b, probs, v| b.attn_apply(probs, v, 2),+        );+        close(&got, &[1.0, 2.0, 3.0, 4.0, 6.0, 5.0, 8.0, 7.0]);+    }++    #[test]+    fn a_whole_attention_averages_its_values_when_every_score_is_equal() {+        // The three ops composed. Q and K are zero, so every score is zero, so every+        // softmax row is uniform at 1/T, so each output position is the mean of V over+        // the sequence — the same value at all four positions.+        //+        // That pins all three at once in a way none of them can fake: a missing scale+        // still gives zeros, but a softmax that did not normalise scales the mean by T,+        // and a weighted sum that indexed V by query rather than key returns V itself.+        let got = two(+            (Shape::new(2, 1, 4), Shape::new(2, 1, 4)),+            (+                &[0.0; 8],+                &[1.0, 2.0, 3.0, 4.0, 10.0, 20.0, 30.0, 40.0],+            ),+            |b, zeros, v| {+                let scores = b.attn_scores(zeros, zeros, 1);+                let probs = b.softmax(scores);+                b.attn_apply(probs, v, 1)+            },+        );+        close(&got, &[2.5, 2.5, 2.5, 2.5, 25.0, 25.0, 25.0, 25.0]);+    }++    #[test]+    fn a_head_count_that_does_not_divide_the_channels_fails_the_build() {+        // d_model 120 in 8 heads is the recogniser's geometry; anything that does not+        // divide would silently reinterpret the channel runs as overlapping heads.+        let given = Given::new(&[]).expect("no tensors");+        let mut b = Builder::new(&given);+        let q = b.input(Shape::new(6, 1, 2));+        let scores = b.attn_scores(q, q, 4);+        let error = b.finish(&[scores]).expect_err("6 channels in 4 heads");+        assert!(error.contains("do not split into 4 heads"), "{error}");+    }++    #[test]+    fn a_sequence_with_a_height_above_one_is_refused() {+        // `[d_model, 1, T]` is what makes the head split a reinterpretation rather than+        // a copy. A taller tensor would be read as if the extra rows were sequence+        // positions, which is wrong and produces an output of a plausible shape.+        let given = Given::new(&[]).expect("no tensors");+        let mut b = Builder::new(&given);+        let q = b.input(Shape::new(4, 2, 2));+        let scores = b.attn_scores(q, q, 2);+        let error = b.finish(&[scores]).expect_err("a two-row sequence");+        assert!(error.contains("height above"), "{error}");+    }+     #[test]     fn relu_clamps_at_zero_without_touching_positives() {         let got = one(
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 c510f9664d..543d062966 100644--- a/library/ml/src/main/rust/src/vulkan/pipeline.rs+++ b/library/ml/src/main/rust/src/vulkan/pipeline.rs@@ -1,4 +1,4 @@-//! The eight compute pipelines, and the one descriptor set they all share.+//! The compute pipelines, and the one descriptor set they all share. //! //! # One layout, one descriptor set, written once //!@@ -36,6 +36,26 @@ const ADD: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/add.comp.spv")); const MUL_BCAST: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/mul_bcast.comp.spv")); const AFFINE: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/affine.comp.spv")); const LAYERNORM: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/layernorm.comp.spv"));+const ATTN_SCORES: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/attn_scores.comp.spv"));+const SOFTMAX: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/softmax.comp.spv"));+const ATTN_APPLY: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/attn_apply.comp.spv"));++/// Every shader, in the order [`Pipelines::create`] destructures them.+const SPIRV: [&[u8]; 13] = [+    CONV,+    CONV_TRANSPOSE,+    MAXPOOL,+    RESIZE,+    RESIZE_NEAREST,+    GAP,+    ADD,+    MUL_BCAST,+    AFFINE,+    LAYERNORM,+    ATTN_SCORES,+    SOFTMAX,+    ATTN_APPLY,+];  /// `local_size_x` in `shaders/common.glsl`. A dispatch covers `ceil(invocations / this)` /// workgroups, and each shader bails on the over-dispatched tail.@@ -52,7 +72,7 @@ pub const MAX_WORKGROUPS_PER_DIM: u32 = 65_535;  /// Every compute pipeline, plus the layout and descriptor set they share. pub struct Pipelines {-    /// Shared by all eight, so a bind never invalidates push constants.+    /// Shared by all of them, so a bind never invalidates push constants.     pub layout: vk::PipelineLayout,     /// The one set: arena at binding 0, weights at binding 1.     pub descriptor_set: vk::DescriptorSet,@@ -68,10 +88,13 @@ pub struct Pipelines {     mul_bcast: vk::Pipeline,     affine: vk::Pipeline,     layernorm: vk::Pipeline,+    attn_scores: vk::Pipeline,+    softmax: vk::Pipeline,+    attn_apply: vk::Pipeline, }  impl Pipelines {-    /// Build all eight and point the descriptor set at `arena` and `weights`.+    /// Build all of them and point the descriptor set at `arena` and `weights`.     pub fn new(         context: &Context,         arena: vk::Buffer,@@ -176,18 +199,7 @@ impl Pipelines {         cleanup.layout = Some(layout);          let mut built = Vec::new();-        for spirv in [-            CONV,-            CONV_TRANSPOSE,-            MAXPOOL,-            RESIZE,-            RESIZE_NEAREST,-            GAP,-            ADD,-            MUL_BCAST,-            AFFINE,-            LAYERNORM,-        ] {+        for spirv in SPIRV {             match compute_pipeline(device, layout, spirv) {                 Ok(pipeline) => built.push(pipeline),                 Err(e) => {@@ -198,6 +210,8 @@ impl Pipelines {                 }             }         }+        // A fixed-size array rather than a slice pattern of thirteen bindings, so+        // adding a shader is one entry in `SPIRV` and one name here.         let [             conv,             conv_transpose,@@ -209,9 +223,17 @@ impl Pipelines {             mul_bcast,             affine,             layernorm,-        ] = match built.as_slice() {-            [a, b, c, d, e, f, g, h, i, j] => [*a, *b, *c, *d, *e, *f, *g, *h, *i, *j],-            _ => return Err("wrong pipeline count".into()),+            attn_scores,+            softmax,+            attn_apply,+        ] = match <[vk::Pipeline; SPIRV.len()]>::try_from(built) {+            Ok(all) => all,+            Err(built) => {+                for pipeline in built {+                    device.destroy_pipeline(pipeline, None);+                }+                return Err("wrong pipeline count".into());+            }         };          cleanup.disarm();@@ -230,6 +252,9 @@ impl Pipelines {             mul_bcast,             affine,             layernorm,+            attn_scores,+            softmax,+            attn_apply,         })     } @@ -246,6 +271,9 @@ impl Pipelines {             Kind::MulBroadcast => self.mul_bcast,             Kind::Affine => self.affine,             Kind::LayerNorm => self.layernorm,+            Kind::AttnScores => self.attn_scores,+            Kind::Softmax => self.softmax,+            Kind::AttnApply => self.attn_apply,         }     } @@ -264,6 +292,9 @@ impl Pipelines {             self.mul_bcast,             self.affine,             self.layernorm,+            self.attn_scores,+            self.softmax,+            self.attn_apply,         ] {             device.destroy_pipeline(pipeline, None);         }