Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / library / ml / src / main / rust / shaders / attn_scores.comp
attn_scores.comp163 lines · 7.4 KiBRaw
| 1 | #version 450 |
| 2 | //! `S[h][i][j] = scale * sum_d Q[h][d][i] * K[h][d][j]`, the first half of attention. |
| 3 | //! |
| 4 | //! Two uses per transformer block in PP-OCRv5 recognition, and Supertonic's text encoder |
| 5 | //! attends its text over 50 style tokens with it. |
| 6 | //! |
| 7 | //! # Q and K may be different lengths |
| 8 | //! |
| 9 | //! The output is `[heads, queries, keys]`, square only for self-attention. `p.out_h` is Q's |
| 10 | //! length and `p.out_w` is K's, so the two sequences are strided independently; when they are |
| 11 | //! equal this is the arithmetic it always was. |
| 12 | //! |
| 13 | //! # The contraction is over the middle axis, and that is the whole point |
| 14 | //! |
| 15 | //! Q and K arrive as `[d_model, 1, T]` — the layout the CNN backbone already produces, |
| 16 | //! see `nets::Kind::LayerNorm` for why this runtime keeps it. Read as `[heads, head_dim, |
| 17 | //! T]` those are the same bytes in the same order, so a head is a run of channels and |
| 18 | //! splitting `d_model` into heads costs nothing: no `Permute`, no `Reshape`, no copy. |
| 19 | //! `p.group` carries the head count and this indexes accordingly. |
| 20 | //! |
| 21 | //! What it costs is that the reduction walks `head_dim` channels a stride apart rather |
| 22 | //! than a contiguous vector. At `head_dim` 15 that is 15 strided pairs per score. The |
| 23 | //! alternative — transposing to `[T, d_model]` so each head's vector is contiguous — |
| 24 | //! buys a contiguous read here and pays two permutes of the whole sequence per |
| 25 | //! attention, twice per block. |
| 26 | //! |
| 27 | //! # One invocation per score |
| 28 | //! |
| 29 | //! The output is `[heads, queries, keys]`, so there are `heads * queries * keys` invocations |
| 30 | //! and each reduces `head_dim` products. That is the parallel axis: `T` is around 80 for a line |
| 31 | //! of text, so this is tens of thousands of independent invocations against `head_dim` |
| 32 | //! serial steps each - the opposite balance to `gap.comp`, which has only channels to |
| 33 | //! spread across. |
| 34 | //! |
| 35 | //! # Scale |
| 36 | //! |
| 37 | //! `1 / sqrt(head_dim)`, arriving as raw `f32` bits in `p.param0_bits`. It is derived |
| 38 | //! from the head geometry by `nets::Builder::attn_scores` rather than read from the |
| 39 | //! weights file, because it is not a trained value — it is a property of the shape. |
| 40 | //! |
| 41 | //! Applied here, to the accumulator, rather than to Q's projection weights: folding it |
| 42 | //! there would work and would make the scale invisible in the one place a reader looks |
| 43 | //! to check it. |
| 44 | //! |
| 45 | //! # Tiled mode |
| 46 | //! |
| 47 | //! With `p.kw == 1` each invocation owns four queries by four keys of one head and a workgroup a |
| 48 | //! 32 x 32 block; each step of the `head_dim` reduction reads four queries and four keys as one |
| 49 | //! `f16vec4` each and accumulates their outer product. `nets` picks it when both lengths and both |
| 50 | //! bases are divisible by four, and then `p.count` is the workgroup count. On a Pixel 8 one |
| 51 | //! invocation per score made whisper's six 1,500 x 1,500 maps 570 ms. |
| 52 | |
| 53 | #include "common.glsl" |
| 54 | |
| 55 | layout(std430, binding = 0) readonly buffer ArenaQuad { |
| 56 | f16vec4 arena_quad[]; |
| 57 | }; |
| 58 | |
| 59 | #define TILE 32u |
| 60 | |
| 61 | /// The tiled mode for lengths or bases that are not multiples of four (`p.kw == 2`): the same |
| 62 | /// 4 x 4 block per invocation through scalar loads, edge queries and keys clamped on load and |
| 63 | /// dropped on store. The per-element shader re-read a whole `head_dim` column pair per score; |
| 64 | /// with the apply's, a Gemma vision tower (594 patches) spent 1.05 s of an image there on a Pixel 8. |
| 65 | void ragged(uint queries, uint keys, uint head_dim, uint head, uint query_base, uint key_base) { |
| 66 | uint q_at = p.in0 + head * head_dim * queries; |
| 67 | uint k_at = p.in1 + kv_head_of(head) * head_dim * keys; |
| 68 | uvec4 qi = min(uvec4(query_base) + uvec4(0u, 1u, 2u, 3u), uvec4(queries - 1u)); |
| 69 | uvec4 kj = min(uvec4(key_base) + uvec4(0u, 1u, 2u, 3u), uvec4(keys - 1u)); |
| 70 | mat4 acc = mat4(0.0); |
| 71 | for (uint d = 0u; d < head_dim; d++) { |
| 72 | uint qd = q_at + d * queries; |
| 73 | uint kd = k_at + d * keys; |
| 74 | vec4 q = vec4(float(arena[qd + qi.x]), float(arena[qd + qi.y]), float(arena[qd + qi.z]), float(arena[qd + qi.w])); |
| 75 | vec4 k = vec4(float(arena[kd + kj.x]), float(arena[kd + kj.y]), float(arena[kd + kj.z]), float(arena[kd + kj.w])); |
| 76 | acc += outerProduct(q, k); |
| 77 | } |
| 78 | float scale = uintBitsToFloat(p.param0_bits); |
| 79 | for (uint j = 0u; j < 4u && key_base + j < keys; j++) { |
| 80 | for (uint i = 0u; i < 4u && query_base + i < queries; i++) { |
| 81 | uint at = (head * queries + query_base + i) * keys + key_base + j; |
| 82 | arena[p.out_at + at] = float16_t(acc[j][i] * scale); |
| 83 | } |
| 84 | } |
| 85 | } |
| 86 | |
| 87 | void tiled() { |
| 88 | uint tile = gl_WorkGroupID.y * gl_NumWorkGroups.x + gl_WorkGroupID.x; |
| 89 | if (tile >= p.count) { |
| 90 | return; |
| 91 | } |
| 92 | uint queries = p.out_h; |
| 93 | uint keys = p.out_w; |
| 94 | uint head_dim = p.in_c / p.group; |
| 95 | uint across = (keys + TILE - 1u) / TILE; |
| 96 | uint down = (queries + TILE - 1u) / TILE; |
| 97 | uint head = tile / (across * down); |
| 98 | uint within = tile % (across * down); |
| 99 | uint lid = gl_LocalInvocationID.x; |
| 100 | uint query_base = (within / across) * TILE + (lid >> 3u) * 4u; |
| 101 | uint key_base = (within % across) * TILE + (lid & 7u) * 4u; |
| 102 | if (query_base >= queries || key_base >= keys) { |
| 103 | return; |
| 104 | } |
| 105 | // Causal (`p.kh` 1): the only readers stop at the diagonal, so a block wholly above it is |
| 106 | // never read and is left unwritten. |
| 107 | if (p.kh == 1u && key_base > query_base + 3u) { |
| 108 | return; |
| 109 | } |
| 110 | if (p.kw == 2u) { |
| 111 | ragged(queries, keys, head_dim, head, query_base, key_base); |
| 112 | return; |
| 113 | } |
| 114 | // Both lengths are multiples of four, so a quad is wholly inside its sequence. |
| 115 | uint q_quad = (p.in0 + head * head_dim * queries + query_base) >> 2u; |
| 116 | uint k_quad = (p.in1 + kv_head_of(head) * head_dim * keys + key_base) >> 2u; |
| 117 | uint q_stride = queries >> 2u; |
| 118 | uint k_stride = keys >> 2u; |
| 119 | mat4 acc = mat4(0.0); |
| 120 | for (uint d = 0u; d < head_dim; d++) { |
| 121 | vec4 q = vec4(arena_quad[q_quad + d * q_stride]); |
| 122 | vec4 k = vec4(arena_quad[k_quad + d * k_stride]); |
| 123 | // Column `j` of `acc` is key `j`: `acc[j][i] += q[i] * k[j]`. |
| 124 | acc += outerProduct(q, k); |
| 125 | } |
| 126 | float scale = uintBitsToFloat(p.param0_bits); |
| 127 | for (uint j = 0u; j < 4u; j++) { |
| 128 | for (uint i = 0u; i < 4u; i++) { |
| 129 | uint at = (head * queries + query_base + i) * keys + key_base + j; |
| 130 | arena[p.out_at + at] = float16_t(acc[j][i] * scale); |
| 131 | } |
| 132 | } |
| 133 | } |
| 134 | |
| 135 | void main() { |
| 136 | if (p.kw != 0u) { |
| 137 | tiled(); |
| 138 | return; |
| 139 | } |
| 140 | uint index = global_index(); |
| 141 | if (index >= p.count) { |
| 142 | return; |
| 143 | } |
| 144 | // The output is `[heads, queries, keys]`, so `unpack` gives head, query and key directly. |
| 145 | uint head, query, key; |
| 146 | unpack(index, head, query, key); |
| 147 | // Q and K are `[d_model, 1, T]`: one channel every `T` elements. A head owns `head_dim` |
| 148 | // consecutive channels starting at `head * head_dim`. The two lengths are the score map's |
| 149 | // own height and width. |
| 150 | uint head_dim = p.in_c / p.group; |
| 151 | uint query_stride = p.out_h; |
| 152 | uint key_stride = p.out_w; |
| 153 | uint query_base = head * head_dim * query_stride; |
| 154 | // Under grouped- or multi-query attention several query heads read one key head, so K is |
| 155 | // narrower than Q and the two bases differ. `kv_head_of` is the identity when they match. |
| 156 | uint key_base = kv_head_of(head) * head_dim * key_stride; |
| 157 | float total = 0.0; |
| 158 | for (uint d = 0u; d < head_dim; d++) { |
| 159 | total += float(arena[p.in0 + query_base + d * query_stride + query]) |
| 160 | * float(arena[p.in1 + key_base + d * key_stride + key]); |
| 161 | } |
| 162 | arena[p.out_at + index] = float16_t(total * uintBitsToFloat(p.param0_bits)); |
| 163 | } |