#version 450 //! `S[h][i][j] = scale * sum_d Q[h][d][i] * K[h][d][j]`, the first half of attention. //! //! Two uses per transformer block in PP-OCRv5 recognition, and Supertonic's text encoder //! attends its text over 50 style tokens with it. //! //! # Q and K may be different lengths //! //! The output is `[heads, queries, keys]`, square only for self-attention. `p.out_h` is Q's //! length and `p.out_w` is K's, so the two sequences are strided independently; when they are //! equal this is the arithmetic it always was. //! //! # 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, queries, keys]`, so there are `heads * queries * keys` 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. //! //! # 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 /// The tiled mode for lengths or bases that are not multiples of four (`p.kw == 2`): the same /// 4 x 4 block per invocation through scalar loads, edge queries and keys clamped on load and /// dropped on store. The per-element shader re-read a whole `head_dim` column pair per score; /// with the apply's, a Gemma vision tower (594 patches) spent 1.05 s of an image there on a Pixel 8. void ragged(uint queries, uint keys, uint head_dim, uint head, uint query_base, uint key_base) { uint q_at = p.in0 + head * head_dim * queries; uint k_at = p.in1 + kv_head_of(head) * head_dim * keys; uvec4 qi = min(uvec4(query_base) + uvec4(0u, 1u, 2u, 3u), uvec4(queries - 1u)); uvec4 kj = min(uvec4(key_base) + uvec4(0u, 1u, 2u, 3u), uvec4(keys - 1u)); mat4 acc = mat4(0.0); for (uint d = 0u; d < head_dim; d++) { uint qd = q_at + d * queries; uint kd = k_at + d * keys; vec4 q = vec4(float(arena[qd + qi.x]), float(arena[qd + qi.y]), float(arena[qd + qi.z]), float(arena[qd + qi.w])); vec4 k = vec4(float(arena[kd + kj.x]), float(arena[kd + kj.y]), float(arena[kd + kj.z]), float(arena[kd + kj.w])); acc += outerProduct(q, k); } float scale = uintBitsToFloat(p.param0_bits); for (uint j = 0u; j < 4u && key_base + j < keys; j++) { for (uint i = 0u; i < 4u && query_base + i < queries; i++) { uint at = (head * queries + query_base + i) * keys + key_base + j; arena[p.out_at + at] = float16_t(acc[j][i] * scale); } } } 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; } // Causal (`p.kh` 1): the only readers stop at the diagonal, so a block wholly above it is // never read and is left unwritten. if (p.kh == 1u && key_base > query_base + 3u) { return; } if (p.kw == 2u) { ragged(queries, keys, head_dim, head, query_base, key_base); 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 != 0u) { tiled(); return; } uint index = global_index(); if (index >= p.count) { return; } // The output is `[heads, queries, keys]`, 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 `T` elements. A head owns `head_dim` // consecutive channels starting at `head * head_dim`. The two lengths are the score map's // own height and width. uint head_dim = p.in_c / p.group; uint query_stride = p.out_h; uint key_stride = p.out_w; uint query_base = head * head_dim * query_stride; // Under grouped- or multi-query attention several query heads read one key head, so K is // narrower than Q and the two bases differ. `kv_head_of` is the identity when they match. uint key_base = kv_head_of(head) * head_dim * key_stride; float total = 0.0; for (uint d = 0u; d < head_dim; d++) { total += float(arena[p.in0 + query_base + d * query_stride + query]) * float(arena[p.in1 + key_base + d * key_stride + key]); } arena[p.out_at + index] = float16_t(total * uintBitsToFloat(p.param0_bits)); }