Modern Apps git

← Modern-Apps.git

ml: register-blocked tiled attention scores and apply

Commit
e5de9d3d391fcf260760346da749fc808c8993c6
Author
vayun-mathur <[email protected]>
When
2026-10-25 20:15 UTC (1 month ago)
Parents
a986916

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 93a9b9bec1..cdb2c13af0 100644--- a/library/ml/src/main/rust/shaders/attn_apply.comp+++ b/library/ml/src/main/rust/shaders/attn_apply.comp@@ -28,10 +28,90 @@ //! 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.+//!+//! # Tiled mode+//!+//! With `p.kw == 1` each invocation owns four channels by four queries and a workgroup a 32 x 32+//! block, reading both operands four keys at a time through a read-only `f16vec4` view: each pair+//! of quads is a `dot` per output. `nets` picks it when the key count and both bases are divisible+//! by four, and then `p.count` is the workgroup count. One invocation per output re-read every+//! row of `S` and `V` from memory per element; on a Pixel 8 that made whisper's six 1,500-key+//! applications 1.5 s of a 3.4 s encoder.  #include "common.glsl" +layout(std430, binding = 0) readonly buffer ArenaQuad {+    f16vec4 arena_quad[];+};++#define TILE 32u+#define BLOCK 4u++void tiled() {+    uint tile = gl_WorkGroupID.y * gl_NumWorkGroups.x + gl_WorkGroupID.x;+    if (tile >= p.count) {+        return;+    }+    uint queries = p.out_w;+    uint keys = p.in_w;+    uint head_dim = p.out_c / p.group;+    uint tiles_across = (queries + TILE - 1u) / TILE;+    uint lid = gl_LocalInvocationID.x;+    uint channel_base = (tile / tiles_across) * TILE + (lid >> 3u) * BLOCK;+    uint query_base = (tile % tiles_across) * TILE + (lid & 7u) * BLOCK;+    if (channel_base >= p.out_c || query_base >= queries) {+        return;+    }+    // `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;+    uint value_row[BLOCK];+    uint prob_row[BLOCK];+    for (uint i = 0u; i < BLOCK; i++) {+        uint channel = min(channel_base + i, p.out_c - 1u);+        value_row[i] = ((p.in1 + (kv_head_of(head) * head_dim + channel % head_dim) * keys) >> 2u);+        uint query = min(query_base + i, queries - 1u);+        prob_row[i] = ((p.in0 + (head * queries + query) * keys) >> 2u);+    }+    float acc[BLOCK][BLOCK];+    for (uint i = 0u; i < BLOCK; i++) {+        for (uint j = 0u; j < BLOCK; j++) {+            acc[i][j] = 0.0;+        }+    }+    for (uint q = 0u; q < quads; q++) {+        vec4 v[BLOCK];+        vec4 s[BLOCK];+        for (uint i = 0u; i < BLOCK; i++) {+            v[i] = vec4(arena_quad[value_row[i] + q]);+            s[i] = vec4(arena_quad[prob_row[i] + q]);+        }+        for (uint i = 0u; i < BLOCK; i++) {+            for (uint j = 0u; j < BLOCK; j++) {+                acc[i][j] += dot(v[i], s[j]);+            }+        }+    }+    for (uint i = 0u; i < BLOCK; i++) {+        uint channel = channel_base + i;+        if (channel >= p.out_c) {+            break;+        }+        for (uint j = 0u; j < BLOCK; j++) {+            uint query = query_base + j;+            if (query >= queries) {+                break;+            }+            arena[p.out_at + channel * queries + query] = float16_t(acc[i][j]);+        }+    }+}+ void main() {+    if (p.kw == 1u) {+        tiled();+        return;+    }     uint index = global_index();     if (index >= p.count) {         return;
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.compindex ac3e6bf4af..470d847afe 100644--- a/library/ml/src/main/rust/shaders/attn_scores.comp+++ b/library/ml/src/main/rust/shaders/attn_scores.comp@@ -41,10 +41,67 @@ //! 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.+//!+//! # Tiled mode+//!+//! With `p.kw == 1` each invocation owns four queries by four keys of one head and a workgroup a+//! 32 x 32 block; each step of the `head_dim` reduction reads four queries and four keys as one+//! `f16vec4` each and accumulates their outer product. `nets` picks it when both lengths and both+//! bases are divisible by four, and then `p.count` is the workgroup count. On a Pixel 8 one+//! invocation per score made whisper's six 1,500 x 1,500 maps 570 ms.  #include "common.glsl" +layout(std430, binding = 0) readonly buffer ArenaQuad {+    f16vec4 arena_quad[];+};++#define TILE 32u++void tiled() {+    uint tile = gl_WorkGroupID.y * gl_NumWorkGroups.x + gl_WorkGroupID.x;+    if (tile >= p.count) {+        return;+    }+    uint queries = p.out_h;+    uint keys = p.out_w;+    uint head_dim = p.in_c / p.group;+    uint across = (keys + TILE - 1u) / TILE;+    uint down = (queries + TILE - 1u) / TILE;+    uint head = tile / (across * down);+    uint within = tile % (across * down);+    uint lid = gl_LocalInvocationID.x;+    uint query_base = (within / across) * TILE + (lid >> 3u) * 4u;+    uint key_base = (within % across) * TILE + (lid & 7u) * 4u;+    if (query_base >= queries || key_base >= keys) {+        return;+    }+    // Both lengths are multiples of four, so a quad is wholly inside its sequence.+    uint q_quad = (p.in0 + head * head_dim * queries + query_base) >> 2u;+    uint k_quad = (p.in1 + kv_head_of(head) * head_dim * keys + key_base) >> 2u;+    uint q_stride = queries >> 2u;+    uint k_stride = keys >> 2u;+    mat4 acc = mat4(0.0);+    for (uint d = 0u; d < head_dim; d++) {+        vec4 q = vec4(arena_quad[q_quad + d * q_stride]);+        vec4 k = vec4(arena_quad[k_quad + d * k_stride]);+        // Column `j` of `acc` is key `j`: `acc[j][i] += q[i] * k[j]`.+        acc += outerProduct(q, k);+    }+    float scale = uintBitsToFloat(p.param0_bits);+    for (uint j = 0u; j < 4u; j++) {+        for (uint i = 0u; i < 4u; i++) {+            uint at = (head * queries + query_base + i) * keys + key_base + j;+            arena[p.out_at + at] = float16_t(acc[j][i] * scale);+        }+    }+}+ void main() {+    if (p.kw == 1u) {+        tiled();+        return;+    }     uint index = global_index();     if (index >= p.count) {         return;
library/ml/src/main/rust/src/nets/mod_part11.rs
diff --git a/library/ml/src/main/rust/src/nets/mod_part11.rs b/library/ml/src/main/rust/src/nets/mod_part11.rsindex e5870ce1f7..57d14a6a54 100644--- a/library/ml/src/main/rust/src/nets/mod_part11.rs+++ b/library/ml/src/main/rust/src/nets/mod_part11.rs@@ -57,16 +57,24 @@ pub(crate) mod tests {     /// mismatch leaves part of every projection unwritten - plausible wrong numbers, not an error.     #[test]     fn the_int8_tile_matches_its_shader() {-        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))-            .join("shaders")-            .join("conv_point_int8.comp");+        assert_eq!(tile_of("conv_point_int8.comp"), CONV_POINT_INT8_TILE);+    }++    /// `ATTN_TILE` must equal `TILE` in both attention shaders' tiled modes, for the same reason.+    #[test]+    fn the_attention_tiles_match_their_shaders() {+        assert_eq!(tile_of("attn_scores.comp"), ATTN_TILE);+        assert_eq!(tile_of("attn_apply.comp"), ATTN_TILE);+    }++    fn tile_of(shader: &str) -> u32 {+        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("shaders").join(shader);         let source = std::fs::read_to_string(&path).expect("the shader reads");-        let tile: u32 = source+        source             .lines()             .find_map(|line| line.trim_start().strip_prefix("#define TILE"))             .and_then(|rest| rest.trim().trim_end_matches('u').parse().ok())-            .expect("conv_point_int8.comp declares TILE");-        assert_eq!(tile, CONV_POINT_INT8_TILE);+            .unwrap_or_else(|| panic!("{shader} declares no TILE"))     }     use super::*; 
library/ml/src/main/rust/src/nets/mod_part3.rs
diff --git a/library/ml/src/main/rust/src/nets/mod_part3.rs b/library/ml/src/main/rust/src/nets/mod_part3.rsindex 225d0de3d8..933c3f6aeb 100644--- a/library/ml/src/main/rust/src/nets/mod_part3.rs+++ b/library/ml/src/main/rust/src/nets/mod_part3.rs@@ -11,6 +11,11 @@ const CONV_POINT_TILE: u32 = 16; /// register blocking and covers a larger tile - see its header. **Must equal `TILE` there.** const CONV_POINT_INT8_TILE: u32 = 32; +/// `TILE` in the tiled modes of `shaders/attn_scores.comp` and `shaders/attn_apply.comp`.+///+/// **Must equal `TILE` in both.** Held by `the_attention_tiles_match_their_shaders`.+const ATTN_TILE: u32 = 32;+ /// `ROWS` in `shaders/conv_vec_int8.comp`: output channels per workgroup. /// /// That shader is dispatched one workgroup per group of this many channels, so [`Builder::emit`]
library/ml/src/main/rust/src/nets/mod_part9.rs
diff --git a/library/ml/src/main/rust/src/nets/mod_part9.rs b/library/ml/src/main/rust/src/nets/mod_part9.rsindex b69aa93757..a8acaa4c56 100644--- a/library/ml/src/main/rust/src/nets/mod_part9.rs+++ b/library/ml/src/main/rust/src/nets/mod_part9.rs@@ -449,11 +449,22 @@ impl<'a> Builder<'a> {             }             Node::AttnScores { q, k, out, heads, kv_heads, scale } => {                 let (si, so) = (shape(*q), shape(*out));+                let (in0, in1) = (at(*q)?, at(*k)?);+                // The tiled shader reads four queries and four keys per load, so both lengths and+                // both bases must divide by four. See `shaders/attn_scores.comp`.+                let tiled = so.h >= 4+                    && so.h % 4 == 0+                    && so.w % 4 == 0+                    && in0 % 4 == 0+                    && in1 % 4 == 0;+                let tiles = so.c * so.h.div_ceil(ATTN_TILE) * so.w.div_ceil(ATTN_TILE);+                let (kw, count, invocations) =+                    if tiled { (1, tiles, tiles * 64) } else { (0, so.len(), so.len()) };                 ops.push(Op::Dispatch {                     kind: Kind::AttnScores,                     push: Push {-                        in0: at(*q)?,-                        in1: at(*k)?,+                        in0,+                        in1,                         out: at(*out)?,                         in_c: si.c,                         in_h: si.h,@@ -464,10 +475,11 @@ impl<'a> Builder<'a> {                         group: *heads,                         kv_heads: *kv_heads,                         param0_bits: scale.to_bits(),-                        count: so.len(),+                        count,+                        kw,                         ..Push::default()                     },-                    invocations: so.len(),+                    invocations,                 });             }             Node::AttnScoresCached { q, cache, out, heads, kv_heads, scale, dynamic, sliding } => {
library/ml/src/main/rust/src/nets/mod_part9b.rs
diff --git a/library/ml/src/main/rust/src/nets/mod_part9b.rs b/library/ml/src/main/rust/src/nets/mod_part9b.rsindex 5daa1b4010..1b7942cf98 100644--- a/library/ml/src/main/rust/src/nets/mod_part9b.rs+++ b/library/ml/src/main/rust/src/nets/mod_part9b.rs@@ -392,11 +392,24 @@ impl<'a> Builder<'a> {             }             Node::AttnApply { probs, v, out, heads, kv_heads } => {                 let (sv, so) = (shape(*v), shape(*out));+                let (in0, in1) = (at(*probs)?, at(*v)?);+                // The tiled shader reads both operands four keys per load and owns four channels of+                // one head per invocation. A single query would waste three of every four lanes'+                // work, so a decode step stays on the per-element shader.+                let head_dim = so.c / (*heads).max(1);+                let tiled = so.w >= 8+                    && sv.w % 4 == 0+                    && head_dim % 4 == 0+                    && in0 % 4 == 0+                    && in1 % 4 == 0;+                let tiles = so.c.div_ceil(ATTN_TILE) * so.w.div_ceil(ATTN_TILE);+                let (kw, count, invocations) =+                    if tiled { (1, tiles, tiles * 64) } else { (0, so.len(), so.len()) };                 ops.push(Op::Dispatch {                     kind: Kind::AttnApply,                     push: Push {-                        in0: at(*probs)?,-                        in1: at(*v)?,+                        in0,+                        in1,                         out: at(*out)?,                         in_c: so.c,                         in_h: so.h,@@ -408,10 +421,11 @@ impl<'a> Builder<'a> {                         out_w: so.w,                         group: *heads,                         kv_heads: *kv_heads,-                        count: so.len(),+                        count,+                        kw,                         ..Push::default()                     },-                    invocations: so.len(),+                    invocations,                 });             }             Node::Rotary { input, angles, out, heads, axes } => {
library/ml/src/main/rust/src/vulkan/parity_part4.rs
diff --git a/library/ml/src/main/rust/src/vulkan/parity_part4.rs b/library/ml/src/main/rust/src/vulkan/parity_part4.rsindex 388291d435..6a1e68a019 100644--- a/library/ml/src/main/rust/src/vulkan/parity_part4.rs+++ b/library/ml/src/main/rust/src/vulkan/parity_part4.rs@@ -182,6 +182,63 @@ fn row_mode_plan(     plan } +#[test]+#[ignore = "needs a Vulkan device"]+fn a_tiled_score_map_agrees_with_the_reference() {+    // Lengths divisible by four but not by the 32-wide tile, in both axes, so partial tiles run;+    // a cross-attention shape (queries != keys) so the two strides cannot be confused; and a+    // grouped case where two query heads share each key head.+    for (heads, kv_heads, head_dim, queries, keys) in+        [(2u32, 2u32, 8u32, 36u32, 44u32), (4, 2, 12, 40, 68)]+    {+        let q = spread((heads * head_dim * queries) as usize, 0.31);+        let k = spread((kv_heads * head_dim * keys) as usize, -0.23);+        let source = Invented::new(0);+        let plan = row_mode_plan(+            &source,+            &[Shape::new(heads * head_dim, 1, queries), Shape::new(kv_heads * head_dim, 1, keys)],+            crate::nets::Kind::AttnScores,+            |b, ids| {+                if heads == kv_heads {+                    b.attn_scores(ids[0], ids[1], heads)+                } else {+                    b.attn_scores_grouped_prescaled(ids[0], ids[1], heads, kv_heads)+                }+            },+        );+        let what = format!("a tiled score map, {heads}/{kv_heads} heads, {queries}x{keys}");+        compare(&what, plan, source.into_data(), &[&q, &k]);+    }+}++#[test]+#[ignore = "needs a Vulkan device"]+fn a_tiled_attention_apply_agrees_with_the_reference() {+    // As above: partial tiles in both axes, queries != keys, and a grouped case.+    for (heads, kv_heads, head_dim, queries, keys) in+        [(2u32, 2u32, 8u32, 40u32, 52u32), (4, 2, 12, 44, 36)]+    {+        // Probabilities need not sum to one for the arithmetic under test.+        let probs = spread((heads * queries * keys) as usize, 0.17);+        let v = spread((kv_heads * head_dim * keys) as usize, 0.53);+        let source = Invented::new(0);+        let plan = row_mode_plan(+            &source,+            &[Shape::new(heads, queries, keys), Shape::new(kv_heads * head_dim, 1, keys)],+            crate::nets::Kind::AttnApply,+            |b, ids| {+                if heads == kv_heads {+                    b.attn_apply(ids[0], ids[1], heads)+                } else {+                    b.attn_apply_grouped(ids[0], ids[1], heads, kv_heads)+                }+            },+        );+        let what = format!("a tiled attention apply, {heads}/{kv_heads} heads, {queries}x{keys}");+        compare(&what, plan, source.into_data(), &[&probs, &v]);+    }+}+ #[test] #[ignore = "needs a Vulkan device"] fn a_row_mode_layer_norm_agrees_with_the_reference() {