library:ml: causal softmax and a position-axis concat
- Commit
1b40af5a1a0c379de78fd71ce967ffbd59f3923b- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-29 04:51 UTC (3 months ago)
- Parents
f9ee241
Diff
library/ml/src/main/rust/shaders/softmax_causal.comp
diff --git a/library/ml/src/main/rust/shaders/softmax_causal.comp b/library/ml/src/main/rust/shaders/softmax_causal.compnew file mode 100644index 0000000000..c90af6e10f--- /dev/null+++ b/library/ml/src/main/rust/shaders/softmax_causal.comp@@ -0,0 +1,65 @@+#version 450+//! `softmax.comp` with the row truncated at the diagonal: a **causal** attention softmax.+//!+//! One use, TinyCLIP's text tower. Its three layers attend over the whole 77-token+//! sequence at once and each query may only see itself and the keys before it, which the+//! export spells as adding a `-inf` upper triangle to the score map before normalising.+//!+//! # Why a second shader rather than a flag on `softmax.comp`+//!+//! A `Push` field would be free to add and expensive to be wrong about: `softmax.comp` is+//! shared by PP-OCRv5 recognition, both Supertonic encoders and SMaLL-100, so a field the+//! bound is read from breaks four shipping nets at once if it is ever left unset. This+//! file duplicates twenty lines instead.+//!+//! The other alternative was no shader at all — run the text tower one token at a time+//! through `attn_scores_cached`, where one query needs no mask because the cache *is* the+//! prefix. That is 77 plan rebuilds per query, each a `device_wait_idle`, for a tower that+//! is three layers deep.+//!+//! # The bound is `query + 1`, and off by one in either direction is wrong+//!+//! The scores are `[heads, T, T]`, key innermost, so a row is contiguous and the row index+//! is `head * out_h + query`. Query `q` may read keys `0 ..= q`, so the row is `q + 1`+//! long. At `q = 0` that is one key and the distribution is exactly `[1, 0, ...]`; a bound+//! of `q` would leave an empty row and divide by zero, and a bound of `q + 2` would let+//! every position read one token of the future — a fluent, subtly wrong embedding.+//!+//! The masked tail is written as zero rather than left alone. `attn_apply.comp` multiplies+//! the whole row by V, so a stale value there from a previous layer's score map would+//! contribute; and the arena is reused, so "previous" is not even predictable.++#include "common.glsl"++void main() {+ uint row = global_index();+ if (row >= p.count) {+ return;+ }+ // Rows are laid out head-major, `out_h` queries per head, so this is the query index+ // whatever the head count is.+ uint query = row % p.out_h;+ uint keys = min(query + 1u, p.out_w);+ uint at = p.in0 + row * p.out_w;++ // The most negative fp16 rather than -inf, as `softmax.comp` does. `keys` is at least+ // one, so the seed is never the answer.+ float peak = -65504.0;+ for (uint i = 0u; i < keys; i++) {+ peak = max(peak, float(arena[at + i]));+ }++ float total = 0.0;+ for (uint i = 0u; i < keys; 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 < keys; i++) {+ arena[out_row + i] = float16_t(exp(float(arena[at + i]) - peak) * inverse);+ }+ for (uint i = keys; i < p.out_w; i++) {+ arena[out_row + i] = float16_t(0.0);+ }+}
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 ac66ca9b9d..7d8202fea1 100644--- a/library/ml/src/main/rust/src/nets/mod.rs+++ b/library/ml/src/main/rust/src/nets/mod.rs@@ -237,6 +237,17 @@ pub enum Kind { /// per-score parallelism, since a fused pass has to be one invocation per *row* to /// see the whole distribution it is normalising. Softmax,+ /// [`Kind::Softmax`] with each row truncated at the diagonal: a **causal** mask.+ ///+ /// One use, TinyCLIP's text tower, whose three layers attend over all 77 tokens at once and+ /// may not read the future. Query `q`'s row is normalised over keys `0 ..= q` and the rest of+ /// it is written as zero, so [`Kind::AttnApply`] can multiply the whole row unchanged.+ ///+ /// A separate pipeline rather than a flag on [`Kind::Softmax`], because that one is shared by+ /// PP-OCRv5 recognition, both Supertonic encoders and SMaLL-100 — a push field the bound came+ /// from would break four shipping nets at once if it were ever left unset. See+ /// `shaders/softmax_causal.comp`.+ SoftmaxCausal, /// `O[h][d][i] = sum_j S[h][i][j] * V[h][d][j]`, attention's weighted sum. /// /// `O[h][d][i] = sum_j S[h][i][j] * V[h][d][j]`, attention's weighted sum.@@ -505,6 +516,7 @@ impl Kind { | Kind::AttnScores | Kind::AttnScoresCached | Kind::Softmax+ | Kind::SoftmaxCausal | Kind::AttnApply | Kind::AttnApplyCached | Kind::Rotary => {}@@ -715,6 +727,14 @@ enum Node { Softmax { input: Id, out: Id,+ /// Truncate each row at the diagonal. See [`Kind::SoftmaxCausal`].+ causal: bool,+ },+ /// Concatenation along the **width** axis, one strided run per channel row. See+ /// [`Builder::concat_positions`].+ ConcatPositions {+ parts: Vec<Id>,+ out: Id, }, Constant { out: Id,@@ -1295,6 +1315,38 @@ impl<'a> Builder<'a> { out } + /// Concatenate along the **width** axis. Channels and height must match.+ ///+ /// One use, TinyCLIP's class token: prepending a single position to the `[256, 1, 196]` patch+ /// grid to make the `[256, 1, 197]` sequence the vision transformer reads.+ ///+ /// Unlike [`Builder::concat`] this is not one copy. The position axis is innermost, so a+ /// *part* is a column range of every channel rather than a contiguous run — the same fact that+ /// forced the position-major KV cache in [`Kind::AttnScoresCached`]. It is still only+ /// [`Op::Copy`] and needs no shader: `c * h` runs per part, recorded **once** when the plan is+ /// built rather than per inference. For CLIP that is 512 copies in the command buffer, for a+ /// tensor the class token is one 512-byte column of.+ pub fn concat_positions(&mut self, parts: &[Id]) -> Id {+ let shapes: Vec<Shape> = parts.iter().map(|&p| self.shape_of(p)).collect();+ let first = match shapes.first() {+ Some(&s) => s,+ None => {+ self.fail("a position concat of nothing".into());+ Shape::new(0, 0, 0)+ }+ };+ let mut width = 0;+ for s in &shapes {+ if s.c != first.c || s.h != first.h {+ self.fail(format!("a position concat of {first:?} with {s:?}"));+ }+ width += s.w;+ }+ let out = self.tensor(Shape::new(first.c, first.h, width));+ self.nodes.push(Node::ConcatPositions { parts: parts.to_vec(), out });+ out+ }+ /// `x * scale + shift`, elementwise with scalar parameters. See [`Kind::Affine`]. pub fn affine(&mut self, input: Id, scale: f32, shift: f32) -> Id { let shape = self.shape_of(input);@@ -1432,7 +1484,29 @@ impl<'a> Builder<'a> { self.fail(format!("a softmax over {shape:?}, whose last axis is empty")); } let out = self.tensor(shape);- self.nodes.push(Node::Softmax { input, out });+ self.nodes.push(Node::Softmax { input, out, causal: false });+ out+ }++ /// [`Builder::softmax`] with each query's row truncated at the diagonal.+ ///+ /// The input must be a square score map `[heads, T, T]`: a causal mask is a statement about+ /// which *keys* a *query* may read, so queries and keys have to be the same sequence. A+ /// cross-attention map is not square and masking one would be meaningless rather than merely+ /// wrong, which is why this is refused instead of clamped.+ pub fn softmax_causal(&mut self, input: Id) -> Id {+ let shape = self.shape_of(input);+ if shape.w == 0 {+ self.fail(format!("a causal softmax over {shape:?}, whose last axis is empty"));+ }+ if shape.h != shape.w {+ self.fail(format!(+ "a causal softmax over {shape:?}: the mask is over one sequence attending to \+ itself, so the map is [heads, T, T]"+ ));+ }+ let out = self.tensor(shape);+ self.nodes.push(Node::Softmax { input, out, causal: true }); out } @@ -2252,13 +2326,13 @@ impl<'a> Builder<'a> { invocations: so.len(), }); }- Node::Softmax { input, out } => {+ Node::Softmax { input, out, causal } => { 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,+ kind: if *causal { Kind::SoftmaxCausal } else { Kind::Softmax }, push: Push { in0: at(*input)?, out: at(*out)?,@@ -2274,6 +2348,25 @@ impl<'a> Builder<'a> { invocations: rows, }); }+ Node::ConcatPositions { parts, out } => {+ let so = shape(*out);+ let base = at(*out)?;+ let mut column = 0;+ for &part in parts {+ let sp = shape(part);+ let src = at(part)?;+ // A part is a column range, so one run per channel row rather than the single+ // copy `Node::Concat` gets away with.+ for row in 0..sp.c * sp.h {+ ops.push(Op::Copy {+ src: src + row * sp.w,+ dst: base + row * so.w + column,+ elems: sp.w,+ });+ }+ column += sp.w;+ }+ } Node::AttnApply { probs, v, out, heads } => { let (sv, so) = (shape(*v), shape(*out)); ops.push(Op::Dispatch {@@ -2362,6 +2455,7 @@ impl Node { | Node::AttnApply { out, .. } | Node::Constant { out, .. } | Node::Rotary { out, .. }+ | Node::ConcatPositions { out, .. } | Node::Concat { out, .. } => *out, } }@@ -2390,6 +2484,7 @@ impl Node { vec![*a, *b] } Node::Concat { parts, .. } => parts.clone(),+ Node::ConcatPositions { parts, .. } => parts.clone(), // The only op with no arena input at all: it reads the weights file. Node::Constant { .. } => Vec::new(), }
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 335671d107..fcb71ddf55 100644--- a/library/ml/src/main/rust/src/nets/reference.rs+++ b/library/ml/src/main/rust/src/nets/reference.rs@@ -197,7 +197,8 @@ impl Reference { Kind::Affine => self.affine(push), Kind::LayerNorm => self.layer_norm(push), Kind::AttnScores => self.attn_scores(push),- Kind::Softmax => self.softmax(push),+ Kind::Softmax => self.softmax(push, false),+ Kind::SoftmaxCausal => self.softmax(push, true), Kind::AttnApply => self.attn_apply(push), Kind::AttnScoresRelative => self.attn_scores_relative(push), Kind::AttnApplyRelative => self.attn_apply_relative(push),@@ -745,26 +746,45 @@ impl Reference { /// 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> {+ ///+ /// `causal` truncates each row at the diagonal, as `softmax_causal.comp` does: rows are+ /// head-major with `out_h` queries per head, so query `row % out_h` reads `query + 1` keys and+ /// the rest of its row is stored as zero.+ fn softmax(&mut self, p: &Push, causal: bool) -> Result<(), String> { if p.out_w == 0 { return Err("a softmax over an empty axis".into()); }+ if causal && p.out_h == 0 {+ return Err("a causal softmax over no queries".into());+ } for row in 0..p.count { let at = row * p.out_w;+ let keys = if causal {+ // At query 0 this is 1, so the distribution is exactly `[1, 0, ...]` and the+ // denominator can never be empty.+ ((row % p.out_h.max(1)) + 1).min(p.out_w)+ } else {+ p.out_w+ }; let mut peak = -65504.0f32;- for i in 0..p.out_w {+ for i in 0..keys { peak = peak.max(self.load(p.in0, at + i)?); } let mut total = 0.0;- for i in 0..p.out_w {+ for i in 0..keys { 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 {+ for i in 0..keys { let value = (self.load(p.in0, at + i)? - peak).exp() * inverse; self.store(p.out, at + i, value)?; }+ // Written rather than left alone: `attn_apply` multiplies the whole row, and the+ // arena is reused, so a stale masked value would contribute something unpredictable.+ for i in keys..p.out_w {+ self.store(p.out, at + i, 0.0)?;+ } } Ok(()) }@@ -2018,6 +2038,88 @@ mod tests { close(&got, &[expected, 1.0 - expected, 0.0]); } + #[test]+ fn a_causal_softmax_gives_position_zero_a_point_distribution() {+ // The fixture that fails if the row bound is off by one in either direction. One head,+ // T 3, so three rows of three: query 0 sees key 0 alone, query 1 keys 0-1, query 2 all+ // three.+ //+ // Row 0's scores are (0, 100, 100). Its distribution must be exactly (1, 0, 0) — a bound+ // of `query + 2` would let the 100 in and give (0, 1, 0), and a bound of `query` would+ // leave an empty row and divide by zero.+ let got = one(+ Shape::new(1, 3, 3),+ &[+ 0.0, 100.0, 100.0, //+ 1.0, 2.0, 100.0, //+ 5.0, 5.0, 5.0,+ ],+ &[],+ |b, x| b.softmax_causal(x),+ );+ let pair = (-1.0f32).exp() / (1.0 + (-1.0f32).exp());+ close(+ &got,+ &[+ 1.0, 0.0, 0.0, //+ pair, 1.0 - pair, 0.0, //+ 1.0 / 3.0, 1.0 / 3.0, 1.0 / 3.0,+ ],+ );+ // Every row is still a distribution, masked tail and all — which is what says the divisor+ // was the truncated sum rather than the whole row's.+ for (row, values) in got.chunks_exact(3).enumerate() {+ let total: f32 = values.iter().sum();+ assert!((total - 1.0).abs() < 2e-3, "row {row} sums to {total}");+ }+ }++ #[test]+ fn a_causal_softmax_masks_within_each_head_rather_than_across_the_map() {+ // Two heads, T 2, so rows are (head 0 query 0), (head 0 query 1), (head 1 query 0),+ // (head 1 query 1). The query index is `row % out_h`, so head 1's first row must be+ // masked exactly as head 0's was; taking the flat row index instead would leave head 1+ // unmasked entirely.+ let got = one(+ Shape::new(2, 2, 2),+ &[+ 0.0, 100.0, //+ 5.0, 5.0, //+ 0.0, 100.0, //+ 5.0, 5.0,+ ],+ &[],+ |b, x| b.softmax_causal(x),+ );+ close(&got, &[1.0, 0.0, 0.5, 0.5, 1.0, 0.0, 0.5, 0.5]);+ }++ #[test]+ fn a_position_concat_prepends_a_column_to_every_channel() {+ // TinyCLIP's class token, in miniature: a `[2, 1, 1]` token in front of a `[2, 1, 3]`+ // grid. The position axis is innermost, so this is one run per channel and not one copy —+ // a contiguous concat would give (9, 1, 2, 3, 8, 4, 5, 6) shifted by a channel.+ let given = Given::new(&[]).expect("no tensors");+ let mut builder = Builder::new(&given);+ let token = builder.input(Shape::new(2, 1, 1));+ let grid = builder.input(Shape::new(2, 1, 3));+ let joined = builder.concat_positions(&[token, grid]);+ let plan = builder.finish(&[joined]).expect("the fixture plan builds");+ // No dispatch at all: the whole op is `vkCmdCopyBuffer`, which is the reason it needs no+ // shader and no reference arm of its own.+ assert!(+ plan.ops.iter().all(|op| matches!(op, crate::nets::Op::Copy { .. })),+ "{:?}",+ plan.ops+ );+ let outputs = run_multi(&plan, given.data(), &[&[9.0, 8.0], &[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]])+ .expect("the fixture plan runs");+ match outputs.as_slice() {+ [only] => close(only, &[9.0, 1.0, 2.0, 3.0, 8.0, 4.0, 5.0, 6.0]),+ other => panic!("{} outputs", other.len()),+ }+ }+ #[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,
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 21a2da48c3..669d0165d2 100644--- a/library/ml/src/main/rust/src/vulkan/parity.rs+++ b/library/ml/src/main/rust/src/vulkan/parity.rs@@ -237,6 +237,64 @@ fn a_cached_score_map_alone_agrees_with_the_reference() { ); } +#[test]+#[ignore = "needs a Vulkan device"]+fn a_causal_softmax_agrees_with_the_reference() {+ // `softmax_causal.comp`, the only new shader TinyCLIP needs. The CPU interpreter is the only+ // oracle for the SPIR-V, so this is what says the two compute the same mask on real hardware.+ //+ // Two heads over T 5, which makes both indexing mistakes visible: the query index is+ // `row % out_h`, so a shader taking the flat row would leave head 1 unmasked, and the bound is+ // `query + 1`, so an off-by-one shows up as row 0 being a pair rather than a point.+ let scores = spread(2 * 5 * 5, 0.4);+ agrees(+ "a causal softmax",+ &[Shape::new(2, 5, 5)],+ &[&scores],+ &[],+ |b, ids| b.softmax_causal(ids[0]),+ );+}++#[test]+#[ignore = "needs a Vulkan device"]+fn a_causal_text_attention_agrees_with_the_reference() {+ // The whole of TinyCLIP's text-tower attention: scores, the causal softmax and the weighted+ // sum, in the shapes the real tower uses in miniature. `attn_apply.comp` multiplies the masked+ // tail as well as the head, so a shader that left the tail stale rather than zeroing it is+ // invisible in the softmax's own output and shows up here.+ let q = spread(8 * 4, 0.1);+ let k = spread(8 * 4, 0.9);+ let v = spread(8 * 4, 1.6);+ let given = Given::new(&[]).expect("no tensors");+ let mut builder = Builder::new(&given);+ let qi = builder.input(Shape::new(8, 1, 4));+ let ki = builder.input(Shape::new(8, 1, 4));+ let vi = builder.input(Shape::new(8, 1, 4));+ let scores = builder.attn_scores(qi, ki, 2);+ let probs = builder.softmax_causal(scores);+ let out = builder.attn_apply(probs, vi, 2);+ let plan = builder.finish(&[out]).expect("the fixture plan builds");+ compare("a causal text attention", plan, given.data().to_vec(), &[&q, &k, &v]);+}++#[test]+#[ignore = "needs a Vulkan device"]+fn a_position_concat_moves_the_same_columns_on_the_device() {+ // TinyCLIP's class token: `c * h` strided `vkCmdCopyBuffer`s rather than the one a channel+ // concat gets away with. What is under test is the destination stride, which is the output's+ // width and not the part's.+ let token = spread(6, 0.5);+ let grid = spread(6 * 4, 1.3);+ let given = Given::new(&[]).expect("no tensors");+ let mut builder = Builder::new(&given);+ let t = builder.input(Shape::new(6, 1, 1));+ let g = builder.input(Shape::new(6, 1, 4));+ let joined = builder.concat_positions(&[t, g]);+ let plan = builder.finish(&[joined]).expect("the fixture plan builds");+ compare("a position concat", plan, given.data().to_vec(), &[&token, &grid]);+}+ #[test] #[ignore = "needs a Vulkan device"] fn a_reshape_moves_the_same_elements_on_the_device() {
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 5a97fda860..c3263f4b0b 100644--- a/library/ml/src/main/rust/src/vulkan/pipeline.rs+++ b/library/ml/src/main/rust/src/vulkan/pipeline.rs@@ -40,6 +40,8 @@ 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 SOFTMAX_CAUSAL: &[u8] =+ include_bytes!(concat!(env!("OUT_DIR"), "/softmax_causal.comp.spv")); const ATTN_APPLY: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/attn_apply.comp.spv")); const ATTN_SCORES_RELATIVE: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/attn_scores_relative.comp.spv"));@@ -62,7 +64,7 @@ const CONV_VEC_INT8: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/conv_vec_int8.comp.spv")); /// Every shader, in the order [`Pipelines::create`] destructures them.-const SPIRV: [&[u8]; 27] = [+const SPIRV: [&[u8]; 28] = [ CONV, CONV_TRANSPOSE, MAXPOOL,@@ -90,6 +92,7 @@ const SPIRV: [&[u8]; 27] = [ ATTN_SCORES_CACHED, ATTN_APPLY_CACHED, CONV_VEC_INT8,+ SOFTMAX_CAUSAL, ]; /// `local_size_x` in `shaders/common.glsl`. A dispatch covers `ceil(invocations / this)`@@ -145,6 +148,7 @@ pub struct Pipelines { attn_scores_cached: vk::Pipeline, attn_apply_cached: vk::Pipeline, conv_vec_int8: vk::Pipeline,+ softmax_causal: vk::Pipeline, } impl Pipelines {@@ -361,6 +365,7 @@ impl Pipelines { attn_scores_cached, attn_apply_cached, conv_vec_int8,+ softmax_causal, ] = match <[vk::Pipeline; SPIRV.len()]>::try_from(built) { Ok(all) => all, Err(built) => {@@ -404,6 +409,7 @@ impl Pipelines { attn_scores_cached, attn_apply_cached, conv_vec_int8,+ softmax_causal, }) } @@ -423,6 +429,7 @@ impl Pipelines { Kind::LayerNorm => self.layernorm, Kind::AttnScores => self.attn_scores, Kind::Softmax => self.softmax,+ Kind::SoftmaxCausal => self.softmax_causal, Kind::AttnApply => self.attn_apply, Kind::AttnScoresRelative => self.attn_scores_relative, Kind::AttnApplyRelative => self.attn_apply_relative,@@ -472,6 +479,7 @@ impl Pipelines { self.attn_scores_cached, self.attn_apply_cached, self.conv_vec_int8,+ self.softmax_causal, ] { device.destroy_pipeline(pipeline, None); }