Modern Apps git

← Modern-Apps.git

ml: causal attention apply stops at the diagonal, gemma4 AttnApply 46 -> 26 ms

Commit
d5876fa44f37bbe31ecfe2c3bb4631fc83975c02
Author
vayun-mathur <[email protected]>
When
2026-10-26 20:16 UTC (1 month ago)
Parents
4f303d3

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.compindex 126cd7be5c..bcb9146aaf 100644--- a/library/ml/src/main/rust/shaders/attn_apply.comp+++ b/library/ml/src/main/rust/shaders/attn_apply.comp@@ -61,7 +61,9 @@ void ragged(uint channel_base, uint query_base, uint queries, uint keys, uint he         s_row[i] = p.in0 + (head * queries + query) * keys;     }     mat4 acc = mat4(0.0);-    for (uint j = 0u; j < keys; j++) {+    // Causal (`p.kh` 1): keys past this block's last query hold exact zeros.+    uint bound = p.kh == 1u ? min(keys, min(query_base + BLOCK, queries)) : keys;+    for (uint j = 0u; j < bound; j++) {         vec4 v = vec4(float(arena[v_row.x + j]), float(arena[v_row.y + j]), float(arena[v_row.z + j]), float(arena[v_row.w + j]));         vec4 s = vec4(float(arena[s_row.x + j]), float(arena[s_row.y + j]), float(arena[s_row.z + j]), float(arena[s_row.w + j]));         // Column `q` of `acc` is query `q`: `acc[q][c] += v[c] * s[q]`.@@ -96,6 +98,10 @@ void tiled() {     // `head_dim` is a multiple of four, so a block of four channels never spans two heads.     uint head = channel_base / head_dim;     uint quads = keys >> 2u;+    if (p.kh == 1u) {+        // Causal: keys past this block's last query hold exact zeros, so only `+ 0` is skipped.+        quads = min(quads, (min(query_base + BLOCK, queries) + 3u) >> 2u);+    }     uint value_row[BLOCK];     uint prob_row[BLOCK];     for (uint i = 0u; i < BLOCK; i++) {
library/ml/src/main/rust/src/nets/mod_part9d.rs
diff --git a/library/ml/src/main/rust/src/nets/mod_part9d.rs b/library/ml/src/main/rust/src/nets/mod_part9d.rsindex 752a04b77b..5efd88f8eb 100644--- a/library/ml/src/main/rust/src/nets/mod_part9d.rs+++ b/library/ml/src/main/rust/src/nets/mod_part9d.rs@@ -30,6 +30,13 @@ impl<'a> Builder<'a> {                 } else {                     (0, so.len(), so.len())                 };+                // Causal self-attention: the softmax wrote exact zeros past the diagonal, so the+                // tiled shader stops each block at its last query's key (`kh` 1), dropping only+                // `+ 0` terms.+                let causal = so.w == sv.w+                    && self.nodes.iter().any(|n| {+                        matches!(n, Node::Softmax { out, mode: SoftmaxMode::Causal, .. } if out == probs)+                    });                 ops.push(Op::Dispatch {                     kind: Kind::AttnApply,                     push: Push {@@ -48,6 +55,7 @@ impl<'a> Builder<'a> {                         kv_heads: *kv_heads,                         count,                         kw,+                        kh: u32::from(causal),                         ..Push::default()                     },                     invocations,
library/ml/src/main/rust/src/vulkan/parity_part12.rs
diff --git a/library/ml/src/main/rust/src/vulkan/parity_part12.rs b/library/ml/src/main/rust/src/vulkan/parity_part12.rsindex 3ee039b5c0..6024a0a1f2 100644--- a/library/ml/src/main/rust/src/vulkan/parity_part12.rs+++ b/library/ml/src/main/rust/src/vulkan/parity_part12.rs@@ -73,3 +73,30 @@ fn a_tile_mode_rms_norm_agrees_with_the_reference() {         compare(&format!("a tile-mode rms norm, {channels}/{groups} x {positions}"), plan, given.data().to_vec(), &[&input]);     } }+#[test]+#[ignore = "needs a Vulkan device"]+fn causal_attention_skips_only_zero_probabilities() {+    // Gemma 4's fresh prefill: grouped queries over their own keys through a causal softmax, at a+    // width with a partial 32-query tile (200), and a ragged width on the scalar-load path (258).+    for (heads, kv_heads, head_dim, positions) in [(2u32, 1u32, 64u32, 200u32), (2, 1, 16, 258)] {+        let q = spread((heads * head_dim * positions) as usize, 0.31);+        let k = spread((kv_heads * head_dim * positions) as usize, -0.23);+        let v = spread((kv_heads * head_dim * positions) as usize, 0.53);+        let source = Invented::new(0);+        let shapes = [+            Shape::new(heads * head_dim, 1, positions),+            Shape::new(kv_heads * head_dim, 1, positions),+            Shape::new(kv_heads * head_dim, 1, positions),+        ];+        let plan = build(&source, &shapes, |b, ids| {+            let scores = b.attn_scores_grouped_prescaled(ids[0], ids[1], heads, kv_heads);+            let probs = b.softmax_causal(scores);+            b.attn_apply_grouped(probs, ids[2], heads, kv_heads)+        });+        let bounded = plan.ops.iter().any(|op| {+            matches!(op, crate::nets::Op::Dispatch { kind: crate::nets::Kind::AttnApply, push, .. } if push.kh == 1 && push.kw != 0)+        });+        assert!(bounded, "the causal apply at {positions} did not take the bounded tiled path");+        compare(&format!("causal attention {heads}/{kv_heads} heads x {positions}"), plan, source.into_data(), &[&q, &k, &v]);+    }+}