diff --git a/zig/kernels/metal/deepseek_v41/csa2_attn.metal b/zig/kernels/metal/deepseek_v41/csa2_attn.metal index dc6bb83fb98..5cc7165f3c5 100644 --- a/zig/kernels/metal/deepseek_v41/csa2_attn.metal +++ b/zig/kernels/metal/deepseek_v41/csa2_attn.metal @@ -22,7 +22,7 @@ using namespace metal; #define TF_ATTN_KU 2u #define TF_ATTN_RR 2u #define TF_ATTN_HG 4u -#define TF_ATTN_TILE 16u +#define TF_ATTN_PH 2u #define TF_ATTN_NEG (-1e30f) struct TfAttnArgs { @@ -47,16 +47,19 @@ struct TfQ { float v[TF_ATTN_HS][16]; }; -// A chunk's softmax state: running max, sum, weighted sum, and how many keys it has met. -struct TfAcc { - float m[TF_ATTN_HS]; - float l[TF_ATTN_HS]; - float acc[TF_ATTN_HS][16]; +// A chunk's softmax state of HS heads: running max, sum, weighted sum, and how many keys it has met. +template +struct TfAccN { + float m[HS]; + float l[HS]; + float acc[HS][16]; uint n; }; +typedef TfAccN TfAcc; -inline float tf_attn_lo(uint w) { return as_type(w << 16); } -inline float tf_attn_hi(uint w) { return as_type(w & 0xFFFF0000u); } +// The two bf16 halves of a word widened through the bfloat type (exact: a bf16 value is an fp32 value). +inline float tf_attn_lo(uint w) { return float(as_type(w).x); } +inline float tf_attn_hi(uint w) { return float(as_type(w).y); } inline void tf_attn_x16(TfKey k, thread float* x) { for (uint j = 0; j < 4; ++j) { @@ -67,8 +70,9 @@ inline void tf_attn_x16(TfKey k, thread float* x) { } } -inline void tf_attn_zero(thread TfAcc& s) { - for (uint hh = 0; hh < TF_ATTN_HS; ++hh) { +template +inline void tf_attn_zero(thread TfAccN& s) { + for (uint hh = 0; hh < HS; ++hh) { s.m[hh] = TF_ATTN_NEG; s.l[hh] = 0.0f; for (uint i = 0; i < 16; ++i) s.acc[hh][i] = 0.0f; @@ -184,7 +188,7 @@ inline uint tf_attn_load_selected(thread TfKey* k, const device uint4* C, IP I, // Selected run `run` (0..3) into a zeroed state; PF loads the next step's keys before this step's math. -// `I` is the row's index list, in device memory (prompt) or staged in threadgroup memory (decode). +// `I` is the row's index list, staged in threadgroup memory. template inline void tf_attn_selected(thread TfAcc& s, thread const TfQ& q, const device uint4* C, IP I, thread const TfAttnMeta& m, uint run, float scale, uint lane) { @@ -236,7 +240,8 @@ inline void tf_attn_window(thread TfAcc& s, thread const TfQ& q, const device ui } // A chunk's (max, sum, weighted sum) joined to the running result of head hh: both rescaled to the larger max. -inline void tf_attn_join(thread TfAcc& t, uint hh, float mc, float lc, thread const float* ac) { +template +inline void tf_attn_join(thread TfAccN& t, uint hh, float mc, float lc, thread const float* ac) { const float nm = mc > t.m[hh] ? mc : t.m[hh]; const float a = precise::exp(t.m[hh] - nm); const float b = precise::exp(mc - nm); @@ -252,8 +257,8 @@ inline void tf_attn_join(thread TfAcc& t, uint hh, float mc, float lc, thread co } // Sink, normalisation, the inverse RoPE of the last 64 dims and the store of a head's row. -template -inline void tf_attn_store(thread TfAcc& s, uint hh, float sink, const device float* cs, device T* out, uint lane) { +template +inline void tf_attn_store(thread TfAccN& s, uint hh, float sink, const device float* cs, device T* out, uint lane) { const float m = s.m[hh]; const float top = sink > m ? sink : m; const float af = precise::exp(m - top); @@ -326,61 +331,86 @@ template if (TF_CTL == 4 && r == 0 && h0 == 0 && lane == 0) O[ulong(a.rows) * a.heads * TF_ATTN_D] = T(1.0f); } -// Prompt: a threadgroup is RR consecutive rows of one linear window buffer by HG head groups. +// Prompt: a threadgroup is RR consecutive rows by HG pairs of heads; a simdgroup is one row and PH heads. -// The window is staged in tiles of 16 keys at absolute positions, one barrier pair a tile. +// A simdgroup's heads share each key's loads; keys come from device memory, a run's indices four at a time. + +// One key for PH heads, lane l holding head l % PH's score: a head whose max rose is rescaled, then each head adds it. + +// The steps and their order are tf_attn_update's, so each head's sums carry the decode kernel's bits. +inline void tf_attn_pkey(thread TfAccN& s, thread const float (*q)[16], TfKey k, float scale, uint lane) { + float x[16], v[TF_ATTN_PH]; + tf_attn_x16(k, x); + for (uint hh = 0; hh < TF_ATTN_PH; ++hh) { + v[hh] = 0.0f; + for (uint i = 0; i < 16; ++i) v[hh] = tf_attn_step(v[hh], q[hh][i], x[i]); + } + const float w = tf_attn_reduce2(v[0], v[1], lane) * scale; + if (TF_CTL == 1 && simd_any(w != w)) return; + const uint mine = lane % TF_ATTN_PH; + float mm = s.m[0]; + for (uint hh = 1; hh < TF_ATTN_PH; ++hh) mm = mine == hh ? s.m[hh] : mm; + const bool rise = w > mm; + if (simd_any(rise)) { + const float a = precise::exp(mm - w); + for (uint hh = 0; hh < TF_ATTN_PH; ++hh) + if (simd_broadcast(rise ? 1u : 0u, hh) != 0) { + const float ah = simd_broadcast(a, hh); + s.l[hh] = s.l[hh] * ah; + for (uint i = 0; i < 16; ++i) s.acc[hh][i] = s.acc[hh][i] * ah; + s.m[hh] = simd_broadcast(w, hh); + } + mm = rise ? w : mm; + } + const float p = precise::exp(w - mm); + for (uint hh = 0; hh < TF_ATTN_PH; ++hh) { + const float ph = simd_broadcast(p, hh); + s.l[hh] = s.l[hh] + ph; + for (uint i = 0; i < 16; ++i) s.acc[hh][i] = fma(ph, x[i], s.acc[hh][i]); + } + s.n += 1; +} -// Each row reads its own span of a tile, so its keys and their order do not depend on its chunk or the rows beside it. template [[kernel, max_total_threads_per_threadgroup(32 * TF_ATTN_RR * TF_ATTN_HG)]] void tf_dsv41_attn_pre( TF_ATTN_ARGS, uint2 tg [[threadgroup_position_in_grid]], uint sg [[simdgroup_index_in_threadgroup]], - uint lane [[thread_index_in_simdgroup]], uint tid [[thread_index_in_threadgroup]]) { - threadgroup uint4 tile[TF_ATTN_TILE * (TF_ATTN_D / 8)]; - const uint ra = sg / TF_ATTN_HG, r0 = tg.x * TF_ATTN_RR, r = r0 + ra; - const uint h0 = (tg.y * TF_ATTN_HG + sg % TF_ATTN_HG) * TF_ATTN_HS; - const bool on = r < a.rows && h0 < a.heads; - const TfAttnMeta m0 = M[r0]; - const int last = M[min(r0 + TF_ATTN_RR, a.rows) - 1].pos; - const int lo = max(m0.pos - int(TF_ATTN_WIN) + 1, 0); - const TfAttnMeta m = on ? M[r] : m0; + uint lane [[thread_index_in_simdgroup]]) { + const uint ra = sg / TF_ATTN_HG, r = tg.x * TF_ATTN_RR + ra; + const uint h0 = (tg.y * TF_ATTN_HG + sg % TF_ATTN_HG) * TF_ATTN_PH; + if (r >= a.rows || h0 >= a.heads) return; + const uint nh = min(TF_ATTN_PH, a.heads - h0); + const TfAttnMeta m = M[r]; const float scale = (TF_CTL == 5 && ra == 1) ? a.scale * 1.0000001f : a.scale; - TfQ q; - TfAcc s; - tf_attn_zero(s); - if (on) tf_attn_loadq(q, Q, r, h0, a.heads, lane); - for (int ti = lo / int(TF_ATTN_TILE); ti <= last / int(TF_ATTN_TILE); ++ti) { - const int base = ti * int(TF_ATTN_TILE); - threadgroup_barrier(mem_flags::mem_threadgroup); - for (uint u = 0; u < TF_ATTN_TILE * (TF_ATTN_D / 8) / (32 * TF_ATTN_RR * TF_ATTN_HG); ++u) { - const uint g = tid + 32 * TF_ATTN_RR * TF_ATTN_HG * u; - const int t = base + int(g / (TF_ATTN_D / 8)); - if (t >= lo && t <= last) tile[g] = W[ulong(m0.wofs + t - m0.wbase) * (TF_ATTN_D / 8) + g % (TF_ATTN_D / 8)]; - } - threadgroup_barrier(mem_flags::mem_threadgroup); - if (!on) continue; - const int ja = max(base, max(m.pos - int(TF_ATTN_WIN) + 1, 0)), jb = min(base + int(TF_ATTN_TILE) - 1, m.pos); - for (int j = ja; j <= jb; j += int(TF_ATTN_KU)) { - TfKey k[TF_ATTN_KU]; - uint valid = 0; - for (uint u = 0; u < TF_ATTN_KU; ++u) { - const bool ok = j + int(u) <= jb; - const uint at = uint((ok ? j + int(u) : ja) - base) * (TF_ATTN_D / 8) + 2 * lane; - k[u] = TfKey{tile[at], tile[at + 1]}; - valid |= (ok ? 1u : 0u) << u; - } - tf_attn_batch(s, q, k, valid, scale, lane); - } + float q[TF_ATTN_PH][16]; + for (uint hh = 0; hh < TF_ATTN_PH; ++hh) { + const ulong at = (ulong(r) * a.heads + h0 + min(hh, nh - 1)) * (TF_ATTN_D / 8) + 2 * lane; + tf_attn_x16(TfKey{Q[at], Q[at + 1]}, q[hh]); } - if (!on) return; + TfAccN s; + tf_attn_zero(s); + const int lo = max(m.pos - int(TF_ATTN_WIN) + 1, 0); + const device uint4* wk = W + ulong(m.wofs + lo - m.wbase) * (TF_ATTN_D / 8) + 2 * lane; + for (int t = lo; t <= m.pos; ++t, wk += TF_ATTN_D / 8) tf_attn_pkey(s, q, TfKey{wk[0], wk[1]}, scale, lane); + const device int4* ix = (const device int4*)(I + ulong(r) * TF_ATTN_SEL); + const device uint4* ck = C + ulong(m.cofs) * (TF_ATTN_D / 8) + 2 * lane; for (uint run = 0; run < TF_ATTN_NCH - 1; ++run) { if (int(run * TF_ATTN_RUN) >= m.ncomp) break; - TfAcc c; + const int end = min(m.ncomp, int((run + 1) * TF_ATTN_RUN)); + TfAccN c; tf_attn_zero(c); - tf_attn_selected(c, q, C, I + ulong(r) * TF_ATTN_SEL, m, run, scale, lane); + for (int j = int(run * TF_ATTN_RUN); j < end; j += 4) { + const int4 iv = ix[j / 4]; + for (uint u = 0; u < 4; ++u) { + const int jj = j + int(u); + if (jj >= end || iv[u] < 0 || (TF_CTL == 2 && jj == m.ncomp - 1)) continue; + const device uint4* kp = ck + uint(iv[u]) * (TF_ATTN_D / 8); + tf_attn_pkey(c, q, TfKey{kp[0], kp[1]}, scale, lane); + } + } if (c.n == 0) continue; - for (uint hh = 0; hh < TF_ATTN_HS; ++hh) tf_attn_join(s, hh, c.m[hh], c.l[hh], c.acc[hh]); + for (uint hh = 0; hh < TF_ATTN_PH; ++hh) tf_attn_join(s, hh, c.m[hh], c.l[hh], c.acc[hh]); } - for (uint hh = 0; hh < TF_ATTN_HS; ++hh) + for (uint hh = 0; hh < nh; ++hh) tf_attn_store(s, hh, SK[h0 + hh], CS + ulong(m.pos) * 64, O + (ulong(r) * a.heads + h0 + hh) * TF_ATTN_D, lane); } diff --git a/zig/src/core/contract/dsv41_attn_records.zig b/zig/src/core/contract/dsv41_attn_records.zig index 9170380c25b..5a4e038cf67 100644 --- a/zig/src/core/contract/dsv41_attn_records.zig +++ b/zig/src/core/contract/dsv41_attn_records.zig @@ -6,8 +6,8 @@ pub const records = [_]M{ .{ .name = "dsv41 attn decode bf16 tf_dsv41_attn_dec_bf16", .threads = 160, .tg_memory = 12352, .reserved = 160 }, .{ .name = "dsv41 attn decode prefetch f32 tf_dsv41_attn_dec_pf_f32", .threads = 160, .tg_memory = 12352, .reserved = 160 }, .{ .name = "dsv41 attn decode prefetch bf16 tf_dsv41_attn_dec_pf_bf16", .threads = 160, .tg_memory = 12352, .reserved = 160 }, - .{ .name = "dsv41 attn prompt f32 tf_dsv41_attn_pre_f32", .threads = 256, .tg_memory = 16384, .reserved = 256 }, - .{ .name = "dsv41 attn prompt bf16 tf_dsv41_attn_pre_bf16", .threads = 256, .tg_memory = 16384, .reserved = 256 }, + .{ .name = "dsv41 attn prompt f32 tf_dsv41_attn_pre_f32", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "dsv41 attn prompt bf16 tf_dsv41_attn_pre_bf16", .threads = 256, .tg_memory = 0, .reserved = 256 }, }; test "the DeepSeek V4.1 attention launches fit every Apple family" { diff --git a/zig/src/families/deepseek_v41/metal/csa2_attn.zig b/zig/src/families/deepseek_v41/metal/csa2_attn.zig index 9351a7c3d96..ded6634386e 100644 --- a/zig/src/families/deepseek_v41/metal/csa2_attn.zig +++ b/zig/src/families/deepseek_v41/metal/csa2_attn.zig @@ -7,12 +7,12 @@ pub const head_dim = 512; pub const window = 128; pub const max_selected = 512; pub const rope_dims = 64; -/// Heads a simdgroup carries, and the groups of the two launch shapes. +/// Heads a simdgroup carries (decode, prompt), and the groups of the two launch shapes. pub const heads_per_sg = 1; +pub const prompt_heads_per_sg = 2; pub const chunks = 5; pub const prompt_rows = 2; pub const prompt_head_groups = 4; -pub const prompt_tile = 16; pub const Ref = struct { buf: mtl.Buffer, off: usize = 0 }; pub const Out = enum { f32, bf16 }; @@ -25,7 +25,7 @@ const Args = extern struct { rows: u32, heads: u32, scale: f32, pad: u32 = 0 }; const dec_names = [_][:0]const u8{ "tf_dsv41_attn_dec_f32", "tf_dsv41_attn_dec_bf16" }; const pf_names = [_][:0]const u8{ "tf_dsv41_attn_dec_pf_f32", "tf_dsv41_attn_dec_pf_bf16" }; /// Decode launches of at most this many rows load each step's keys a step ahead (the same math, so the same bits). -pub const prefetch_rows = 2; +pub const prefetch_rows = 64; const pre_names = [_][:0]const u8{ "tf_dsv41_attn_pre_f32", "tf_dsv41_attn_pre_bf16" }; pub const Pipelines = struct { @@ -91,6 +91,6 @@ pub fn encodePrompt(p: *const Pipelines, e: mtl.ComputeEncoder, b: Bind, c: Call try check(c); e.setPipeline(p.pre[@backingInt(c.out)]); bind(e, b, c); - const per = heads_per_sg * prompt_head_groups; + const per = prompt_heads_per_sg * prompt_head_groups; e.dispatchGroups(mtl.Size.of((c.rows + prompt_rows - 1) / prompt_rows, (c.heads + per - 1) / per, 1), mtl.Size.of(32 * prompt_rows * prompt_head_groups, 1, 1)); } diff --git a/zig/tests/contract/metal_dsv41_attn.zig b/zig/tests/contract/metal_dsv41_attn.zig index f6d62fdcae7..01e5966fc03 100644 --- a/zig/tests/contract/metal_dsv41_attn.zig +++ b/zig/tests/contract/metal_dsv41_attn.zig @@ -20,7 +20,7 @@ fn sh(rows: usize, heads: usize, k: usize) c.Shape { return .{ .rows = rows, .n = heads * D, .k = k }; } -const decode_served = [_]c.Shape{ sh(8, 8, 16), sh(4, 8, 512), sh(1, 8, 512), sh(2, 8, 0), sh(4, 64, 512), sh(16, 8, 37), sh(32, 8, 512), sh(3, 2, 5) }; +const decode_served = [_]c.Shape{ sh(8, 8, 16), sh(4, 8, 512), sh(1, 8, 512), sh(2, 8, 0), sh(4, 64, 512), sh(16, 8, 37), sh(32, 8, 512), sh(3, 2, 5), sh(72, 2, 512) }; const prompt_served = [_]c.Shape{ sh(8, 4, 16), sh(4, 8, 512), sh(16, 4, 64), sh(17, 2, 0), sh(3, 8, 512), sh(32, 4, 128), sh(2, 2, 512), sh(8192, 2, 32), sh(1, 2, 5) }; pub fn spec(v: Variant, name: []const u8) c.Spec {