okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-q4-metal (ed1f58d27): the Mac (Metal) engine follows the compiled geometry (q4_lite/q4_mid/q4_big kernel parity 40/40, gate 2 like CUDA), plus the PLE row-buffer fix in src/program/generate.cpp (sized by the compiled hidden size, not 2560; it overran 24 KB at hidden 4096 and crashed Metal serve); default build unchanged (CUDA SASS 3573/3573 and 160/160 host objects, HIP gfx1201/gfx1151 string offsets only, SYCL 129/129 objects and 22/22 checksums, Metal per-token functions identical, UD-Q4_K_XL 10/10 tokens, CUDA IQ3_S 26/26 tokens) (Qwen4 prep)7f46672a4

main
22.8 KiB445 linesraw
1// metal/kernels/qsa.metal - QSA (sparse full attention) decode for a window of tokens, between the projections.
2// Contract of include/strata/kernels/qsa.hpp / qsa_select.hpp / qsa_decode_attn.hpp / kv_q8.hpp (the engine's
3// native path), in a Metal layout (no paging: unified memory):
4//
5//   qsa_prep    per token t (cell pos0 + t): q heads rms_norm * q_norm, NEOX RoPE on 64 dims -> qcur;
6//               k rms_norm * k_norm, RoPE -> int8 KV append (fp16 scale per 64 = fp16(amax/127), rint, clamp);
7//               v -> int8 append; indexer q rms_norm * iq_norm, RoPE -> qidx.  The indexer KEYS (last
8//               threadgroup, all window tokens in order): raw tail [cell % 4]; on a block completion
9//               pooled[b] = rope(rms_norm(mean of the block's 4 raw keys) * ik_norm, pos of the block's first cell);
10//               cell 0 also sets dead = rms_norm(raw) * ik_norm (the tail block's key).
11//   qsa_score   per token, block b <= n_bid: sum over the 4 indexer heads of relu(qidx . key_b); key_b = pooled[b],
12//               the tail block n_bid scores `dead` and gets +1e9 when it has cells.
13//   qsa_topk    per token: width = min(n_kv, 2051) cells; n_kv <= 2051: all; else the width cells of largest
14//               score (a cell inherits its block's), ties to the lowest cell, emitted ascending (radix select).
15//   qsa_attn    split-K: (chunk of CH cells, kv head, token): 12 query heads; s = q.k / 16, chunk max m, sum l,
16//               acc = p . v  -> partials
17//   qsa_merge   per (head, token): log-sum-exp merge, * sigmoid(gate), written as prepared activations (xprep
18//               planes) for attn_output.
19//
20// RoPE: cos/sin from a host table [pos][32] (double precision, as build_rope_table).
21
22// QH, QKV: query heads and kv heads of the model (Flash-Next 24 / 2); the host prelude (geo.h) defines GEO_QH / GEO_QKV for another shape
23#ifdef GEO_QH
24#define QH GEO_QH
25#else
26#define QH 24
27#endif
28#ifdef GEO_QKV
29#define QKV GEO_QKV
30#else
31#define QKV 2
32#endif
33#define QD 256
34#define QROT 64
35#define IH 4
36#define ID 128
37// the threadgroup of qsa_prep that does the indexer keys: after the q, k, v and indexer-q groups (Flash-Next 24 + 4 + 4)
38#if defined(GEO_QH) || defined(GEO_QKV)
39#define QSA_KEYS_ROW (QH + 2 * QKV + IH)
40#else
41#define QSA_KEYS_ROW 32
42#endif
43// QBUDGET: the selection budget in cells, indexer top_k + 3 (Flash-Next 2048 + 3); GEO_BUD from the host prelude for another top_k
44#ifdef GEO_BUD
45#define QBUDGET GEO_BUD
46#else
47#define QBUDGET 2051
48#endif
49#define QCH 64
50
51#ifndef STRATA_XH16_DECL
52#define STRATA_XH16_DECL
53// STRATA_METAL_F16 (function constant 25): the window's x also as half planes, after the float planes and S16:
54// [3][plane] halves - raw (IQ4_XS), x * 4^-(i % 4) (Q2_0), x * 2^-8 at odd i (the K-quants); idx = t * n + d, jj = d % 16
55constant bool XH16 [[function_constant(25)]];
56constant bool xh16 = is_function_constant_defined(XH16) && XH16;
57static inline void put_x16(device float* xp, uint plane, uint idx, uint jj, float v) {
58    device half* xh = (device half*)(xp + 4 * plane + plane / 16);
59    const float q2b[4] = {1.0f, 0.25f, 0.0625f, 0.015625f};
60    xh[idx] = half(v);
61    xh[plane + idx] = half(v * q2b[jj & 3]);
62    xh[2 * plane + idx] = half((jj & 1) ? v * 0.00390625f : v);
63}
64#endif
65
66constant int QSA_NTOK [[function_constant(3)]];
67// QSA_MROPE (function constant 24): interleaved M-RoPE (the vision path; strata/kernels/mrope.hpp, ggml IMROPE,
68// sections 11/11/10): buffer 20 of qsa_prep is a table int32 [cells][3] (t, h, w), and rotary pair i (0..31) of the row
69// at (pos_base + cell) rotates by the cos/sin table's row tab[(pos_base + cell) * 3 + i % 3] instead of its own -
70// the pooled indexer keys too (position pos_base + 4 b of a block).  Off: exactly the plain RoPE.
71constant bool QSA_MROPE [[function_constant(24)]];
72constant bool qsa_mrope = is_function_constant_defined(QSA_MROPE) && QSA_MROPE;
73constant bool QSA_ROWS_C [[function_constant(30)]];
74constant bool qsa_rows = is_function_constant_defined(QSA_ROWS_C) && QSA_ROWS_C;
75// QSA_ROWS (function constant 30): the rows of the window are DIFFERENT sequences (batch slots), one token each, each at its own
76// cell and in its own slot of the caches.  A buffer rinfo (uint) carries the strides between the slots' caches, in elements:
77// [0] kq / vq (chars), [1] ksc / vsc (halves), [2] tail, [3] dead, [4] pooled (floats), [5] GDN state (floats), [6] conv history
78// (floats, per slot and parity), [7] PLE history (floats); then row t at [8 + 4 t] = {slot, cell, history parity, 0}.  Off: exactly the
79// plain kernels.
80
81struct QsaArgs {
82    uint pos0;        // the window's first cell (relative to the sequence)
83    uint pos_base;    // absolute position of cell 0 (RoPE)
84    uint max_cells;
85    uint n_tok;
86    float eps;
87};
88
89// cache layout per layer
90//   kq/vq [cell][kv head][256] int8, ks/vs [cell][kv head][4] half
91//   tail [4][128] f32 (slot = cell % 4), dead [128], pooled [max_cells / 4 + 1][128]
92
93static inline float tg_sum256(float v, threadgroup float* part, ushort sg, ushort lane, ushort nsg) {
94    v = simd_sum(v);
95    if (lane == 0) part[sg] = v;
96    threadgroup_barrier(mem_flags::mem_threadgroup);
97    float t = 0.0f;
98    for (int i = 0; i < nsg; ++i) t += part[i];
99    threadgroup_barrier(mem_flags::mem_threadgroup);
100    return t;
101}
102
103// one row (width w <= 256 = threads) : out = rope((rs * x) * g)  (RoPE on the first 64 dims, NEOX pairs i, i+32)
104static inline float norm_rope(float x, float xhi_unused, device const float* g, threadgroup float* row,
105                              threadgroup float* part, ushort tid, ushort sg, ushort lane, int w, float eps,
106                              device const float2* cs, uint absp, bool rope, device const int* mtab) {
107    const float ss = tg_sum256(tid < w ? x * x : 0.0f, part, sg, lane, 8);
108    const float rs = rsqrt(ss / float(w) + eps);
109    const float y = tid < w ? (rs * x) * g[tid] : 0.0f;
110    row[tid] = y;
111    threadgroup_barrier(mem_flags::mem_threadgroup);
112    float o = y;
113    if (rope && tid < QROT) {
114        const int p = tid & 31;
115        const uint pp = qsa_mrope ? uint(mtab[absp * 3 + uint(p % 3)]) : absp;
116        const float2 c = cs[pp * 32 + p];
117        const float a = row[p], b = row[p + 32];
118        o = tid < 32 ? a * c.x - b * c.y : a * c.y + b * c.x;
119    }
120    threadgroup_barrier(mem_flags::mem_threadgroup);
121    (void)xhi_unused;
122    return o;
123}
124
125// grid (QH + 2 QKV + IH + 1, n_tok): rows 0..QH-1 q heads, then the k heads, the v heads, the indexer q heads (Flash-Next: 24 / 2 / 2 / 4);
126// threadgroup QH + 2 QKV + IH (32; y = 0) is the indexer-key threadgroup.  256 threads.
127kernel void qsa_prep(device const float* qfull [[buffer(0)]], device const float* kcur [[buffer(1)]],
128                     device const float* vcur [[buffer(2)]], device const float* iqraw [[buffer(3)]],
129                     device const float* ikraw [[buffer(4)]], device const float* qn [[buffer(5)]],
130                     device const float* kn [[buffer(6)]], device const float* iqn [[buffer(7)]],
131                     device const float* ikn [[buffer(8)]], device const float2* cs [[buffer(9)]],
132                     device float* qcur [[buffer(10)]], device float* qidx [[buffer(11)]],
133                     device char* kq [[buffer(12)]], device char* vq [[buffer(13)]], device half* ksc [[buffer(14)]],
134                     device half* vsc [[buffer(15)]], device float* tail [[buffer(16)]], device float* dead [[buffer(17)]],
135                     device float* pooled [[buffer(18)]], constant QsaArgs& a [[buffer(19)]],
136                     device const int* mtab [[buffer(20)]],
137                     device const uint* rinfo [[buffer(21), function_constant(qsa_rows)]],
138                     uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]],
139                     ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
140    threadgroup float part[8];
141    threadgroup float row[256];
142    threadgroup float amax[8];
143    const int r = int(tg.x);
144    if (r == QSA_KEYS_ROW) {
145        // the indexer keys, every window token in order (only threadgroup (32, 0) works)
146        if (tg.y != 0) return;
147        for (int t = 0; t < int(a.n_tok); ++t) {
148            uint cell = a.pos0 + uint(t);
149            device float* tail_t = tail; device float* dead_t = dead; device float* pooled_t = pooled;
150            if (qsa_rows) {
151                const ulong sl = rinfo[8 + 4 * t];
152                cell = rinfo[8 + 4 * t + 1];
153                tail_t = tail + sl * rinfo[2]; dead_t = dead + sl * rinfo[3]; pooled_t = pooled + sl * rinfo[4];
154            }
155            const float x = tid < ID ? ikraw[t * ID + tid] : 0.0f;
156            if (tid < ID) tail_t[(cell & 3) * ID + tid] = x;
157            threadgroup_barrier(mem_flags::mem_device);
158            if (cell == 0) {
159                const float o = norm_rope(x, 0.0f, ikn, row, part, tid, sg, lane, ID, a.eps, cs, 0, false, mtab);
160                if (tid < ID) dead_t[tid] = o;
161            }
162            if ((cell & 3) == 3) {
163                float m = 0.0f;
164                if (tid < ID) m = (((tail_t[tid] + tail_t[ID + tid]) + tail_t[2 * ID + tid]) + tail_t[3 * ID + tid]) * 0.25f;
165                const uint b = cell >> 2;
166                const float o = norm_rope(m, 0.0f, ikn, row, part, tid, sg, lane, ID, a.eps, cs, a.pos_base + 4 * b, true, mtab);
167                if (tid < ID) pooled_t[b * ID + tid] = o;
168            }
169            threadgroup_barrier(mem_flags::mem_device);
170        }
171        return;
172    }
173    const int t = int(tg.y);
174    const uint cell = qsa_rows ? rinfo[8 + 4 * t + 1] : a.pos0 + uint(t), absp = a.pos_base + cell;
175    device char* kqr = kq; device char* vqr = vq; device half* kscr = ksc; device half* vscr = vsc;
176    if (qsa_rows) {
177        const ulong sl = rinfo[8 + 4 * t];
178        kqr = kq + sl * rinfo[0]; vqr = vq + sl * rinfo[0]; kscr = ksc + sl * rinfo[1]; vscr = vsc + sl * rinfo[1];
179    }
180    if (r < QH) {
181        const float x = qfull[(t * QH + r) * 2 * QD + tid];
182        const float o = norm_rope(x, 0.0f, qn, row, part, tid, sg, lane, QD, a.eps, cs, absp, true, mtab);
183        qcur[(t * QH + r) * QD + tid] = o;
184    } else if (r < QH + 2 * QKV) {
185        const bool isv = r >= QH + QKV;
186        const int h = r - QH - (isv ? QKV : 0);
187        float x = (isv ? vcur : kcur)[(t * QKV + h) * QD + tid];
188        if (!isv) x = norm_rope(x, 0.0f, kn, row, part, tid, sg, lane, QD, a.eps, cs, absp, true, mtab);
189        // int8 with an fp16 scale per 64 values: groups = simdgroup pairs (64 threads)
190        float m = simd_max(fabs(x));
191        if (lane == 0) amax[sg] = m;
192        threadgroup_barrier(mem_flags::mem_threadgroup);
193        const int g = tid >> 6;
194        m = max(amax[2 * g], amax[2 * g + 1]);
195        const half sh = half(m / 127.0f);
196        const float sf = float(sh);
197        int q = 0;
198        if (sf > 0.0f) q = clamp(int(rint(x / sf)), -127, 127);
199        const uint rowi = cell * QKV + uint(h);
200        (isv ? vqr : kqr)[rowi * QD + tid] = char(q);
201        if ((tid & 63) == 0) (isv ? vscr : kscr)[rowi * 4 + g] = sh;
202    } else {
203        const int h = r - QH - 2 * QKV;
204        const float x = tid < ID ? iqraw[(t * IH + h) * ID + tid] : 0.0f;
205        const float o = norm_rope(x, 0.0f, iqn, row, part, tid, sg, lane, ID, a.eps, cs, absp, true, mtab);
206        if (tid < ID) qidx[(t * IH + h) * ID + tid] = o;
207    }
208}
209
210// scores [n_tok][max_blocks]; grid (ceil(max_blocks / 8), n_tok), 256 threads: a simdgroup per block.
211kernel void qsa_score(device const float* qidx [[buffer(0)]], device const float* pooled [[buffer(1)]],
212                      device const float* dead [[buffer(2)]], device float* scores [[buffer(3)]],
213                      constant QsaArgs& a [[buffer(4)]],
214                      device const uint* rinfo [[buffer(5), function_constant(qsa_rows)]],
215                      uint3 tg [[threadgroup_position_in_grid]], ushort sg [[simdgroup_index_in_threadgroup]],
216                      ushort lane [[thread_index_in_simdgroup]]) {
217    const int t = int(tg.y);
218    const uint n_kv = (qsa_rows ? rinfo[8 + 4 * t + 1] : a.pos0 + uint(t)) + 1, n_bid = n_kv >> 2;
219    const uint b = tg.x * 8 + sg;
220    if (b > n_bid) return;
221    device const float* pooled_s = pooled; device const float* dead_s = dead;
222    if (qsa_rows) { const ulong sl = rinfo[8 + 4 * t]; pooled_s = pooled + sl * rinfo[4]; dead_s = dead + sl * rinfo[3]; }
223    device const float* key = b == n_bid ? dead_s : pooled_s + b * ID;
224    float k[4];
225    for (int i = 0; i < 4; ++i) k[i] = key[lane + 32 * i];
226    float s = 0.0f;
227    for (int h = 0; h < IH; ++h) {
228        float d = 0.0f;
229        for (int i = 0; i < 4; ++i) d = fma(qidx[(t * IH + h) * ID + lane + 32 * i], k[i], d);
230        d = simd_sum(d);
231        s += max(d, 0.0f);
232    }
233    if (b == n_bid && (n_kv & 3) != 0) s += 1e9f;
234    if (lane == 0) scores[uint(t) * (a.max_cells / 4 + 2) + b] = s;
235}
236
237// ids [n_tok][QBUDGET], ascending.  One threadgroup of 1024 threads per token.  Order key of a float: larger score =
238// larger key; a radix select (4 passes of 8 bits) over the blocks with weights = their cell counts finds the
239// threshold key T and how many cells with key == T to take (the lowest cells first).
240static inline uint okey(float f) {
241    const uint u = as_type<uint>(f);
242    return (u & 0x80000000u) ? ~u : (u | 0x80000000u);
243}
244kernel void qsa_topk(device const float* scores [[buffer(0)]], device int* ids [[buffer(1)]],
245                     constant QsaArgs& a [[buffer(2)]],
246                     uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]],
247                     ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
248    threadgroup atomic_uint hist[256];
249    threadgroup uint sel[4];
250    threadgroup uint pref[32];
251    const int t = int(tg.x);
252    const uint n_kv = a.pos0 + uint(t) + 1, n_bid = n_kv >> 2, nb = n_bid + 1;
253    device int* out = ids + t * QBUDGET;
254    device const float* sc = scores + uint(t) * (a.max_cells / 4 + 2);
255    if (n_kv <= QBUDGET) {
256        for (uint c = tid; c < n_kv; c += 1024) out[c] = int(c);
257        return;
258    }
259    // radix select of the `need`-th largest cell key
260    uint prefix = 0, pmask = 0, need = QBUDGET;
261    for (int pass = 0; pass < 4; ++pass) {
262        const int shift = 24 - 8 * pass;
263        if (tid < 256) atomic_store_explicit(&hist[tid], 0u, memory_order_relaxed);
264        threadgroup_barrier(mem_flags::mem_threadgroup);
265        for (uint b = tid; b < nb; b += 1024) {
266            const uint k = okey(sc[b]);
267            if ((k & pmask) == prefix) {
268                const uint w = b < n_bid ? 4u : (n_kv & 3u);
269                if (w) atomic_fetch_add_explicit(&hist[(k >> shift) & 255u], w, memory_order_relaxed);
270            }
271        }
272        threadgroup_barrier(mem_flags::mem_threadgroup);
273        if (tid == 0) {
274            uint acc = 0, d = 0;
275            for (int v = 255; v >= 0; --v) {
276                const uint h = atomic_load_explicit(&hist[v], memory_order_relaxed);
277                if (acc + h >= need) { d = uint(v); break; }
278                acc += h;
279            }
280            sel[0] = d;
281            sel[1] = need - acc;
282        }
283        threadgroup_barrier(mem_flags::mem_threadgroup);
284        prefix |= sel[0] << shift;
285        pmask |= 255u << shift;
286        need = sel[1];
287        threadgroup_barrier(mem_flags::mem_threadgroup);
288    }
289    // T = prefix; take every cell with key > T and the first `need` cells (lowest index) with key == T, ascending.
290    // Pass over blocks in order of index with a prefix scan of each block's selected cell count.
291    const uint T = prefix;
292    uint base = 0, eq_taken = 0;
293    for (uint b0 = 0; b0 < nb; b0 += 1024) {
294        const uint b = b0 + tid;
295        uint w = 0, weq = 0;
296        if (b < nb) {
297            const uint k = okey(sc[b]);
298            const uint cells = b < n_bid ? 4u : (n_kv & 3u);
299            if (k > T) w = cells;
300            else if (k == T) weq = cells;
301        }
302        // equal-key cells: the lowest first, `need` of them in total
303        const uint eq_before = simd_prefix_exclusive_sum(weq);
304        if (lane == 31) pref[sg] = eq_before + weq;
305        threadgroup_barrier(mem_flags::mem_threadgroup);
306        uint eq_sg = 0;
307        for (int i = 0; i < int(sg); ++i) eq_sg += pref[i];
308        uint eq_tot = 0;
309        for (int i = 0; i < 32; ++i) eq_tot += pref[i];
310        threadgroup_barrier(mem_flags::mem_threadgroup);
311        const uint eq0 = eq_taken + eq_sg + eq_before;
312        uint take_eq = 0;
313        if (weq && eq0 < need) take_eq = min(weq, need - eq0);
314        const uint mine = w + take_eq;
315        const uint before = simd_prefix_exclusive_sum(mine);
316        if (lane == 31) pref[sg] = before + mine;
317        threadgroup_barrier(mem_flags::mem_threadgroup);
318        uint off = base;
319        for (int i = 0; i < int(sg); ++i) off += pref[i];
320        uint tot = 0;
321        for (int i = 0; i < 32; ++i) tot += pref[i];
322        threadgroup_barrier(mem_flags::mem_threadgroup);
323        off += before;
324        for (uint c = 0; c < mine; ++c) out[off + c] = int(4 * b + c);
325        base += tot;
326        eq_taken += eq_tot;
327    }
328}
329
330// partials: [n_tok][chunks][QH][QD + 2] (acc, then m, l).  grid (chunks, QKV, n_tok), 256 threads.
331kernel void qsa_attn(device const float* qcur [[buffer(0)]], device const char* kq [[buffer(1)]],
332                     device const char* vq [[buffer(2)]], device const half* ksc [[buffer(3)]],
333                     device const half* vsc [[buffer(4)]], device const int* ids [[buffer(5)]],
334                     device float* part [[buffer(6)]], constant QsaArgs& a [[buffer(7)]],
335                     device const uint* rinfo [[buffer(8), function_constant(qsa_rows)]],
336                     uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]],
337                     ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
338    constexpr int HPG = QH / QKV;   // 12 query heads per kv head
339    threadgroup float qs[HPG][QD];
340    threadgroup float s[HPG][QCH];
341    threadgroup int cid[QCH];
342    const int chunk = int(tg.x), g = int(tg.y), t = int(tg.z);
343    const uint n_kv = (qsa_rows ? rinfo[8 + 4 * t + 1] : a.pos0 + uint(t)) + 1, width = min(n_kv, uint(QBUDGET));
344    if (qsa_rows) { const ulong sl = rinfo[8 + 4 * t]; kq += sl * rinfo[0]; vq += sl * rinfo[0]; ksc += sl * rinfo[1]; vsc += sl * rinfo[1]; }
345    const int c0 = chunk * QCH;
346    const int nchunks = (QBUDGET + QCH - 1) / QCH;
347    device float* pp = part + ((uint(t) * nchunks + chunk) * QH) * (QD + 2);
348    if (uint(c0) >= width) {
349        // an empty chunk: m = -inf, l = 0 (the merge skips it)
350        for (int h = 0; h < HPG; ++h)
351            if (tid == 0) { pp[(g * HPG + h) * (QD + 2) + QD] = -INFINITY; pp[(g * HPG + h) * (QD + 2) + QD + 1] = 0.0f; }
352        return;
353    }
354    const int nc = min(QCH, int(width) - c0);
355    for (int h = 0; h < HPG; ++h) qs[h][tid] = qcur[(t * QH + g * HPG + h) * QD + tid];
356    if (tid < QCH) cid[tid] = tid < nc ? ids[t * QBUDGET + c0 + tid] : 0;
357    threadgroup_barrier(mem_flags::mem_threadgroup);
358    // scores: 12 x 64 dots of 256; simdgroup sg takes cells sg, sg + 8, ...; lanes split the 256 dims (8 each)
359    for (int c = sg; c < nc; c += 8) {
360        const uint rowi = uint(cid[c]) * QKV + uint(g);
361        device const char* kr = kq + rowi * QD;
362        float kv[8];
363        const float scl = float(ksc[rowi * 4 + (lane >> 3)]);
364        for (int i = 0; i < 8; ++i) kv[i] = float(kr[lane * 8 + i]) * scl;
365        for (int h = 0; h < HPG; ++h) {
366            float d = 0.0f;
367            for (int i = 0; i < 8; ++i) d = fma(qs[h][lane * 8 + i], kv[i], d);
368            d = simd_sum(d);
369            if (lane == 0) s[h][c] = d * 0.0625f;
370        }
371    }
372    threadgroup_barrier(mem_flags::mem_threadgroup);
373    // per head: max, exp, sum (simdgroup h % 8 handles heads h, h + 8)
374    threadgroup float mh[HPG], lh[HPG];
375    for (int h = sg; h < HPG; h += 8) {
376        float m = -INFINITY;
377        for (int c = lane; c < nc; c += 32) m = max(m, s[h][c]);
378        m = simd_max(m);
379        float l = 0.0f;
380        for (int c = lane; c < nc; c += 32) {
381            const float p = exp(s[h][c] - m);
382            s[h][c] = p;
383            l += p;
384        }
385        l = simd_sum(l);
386        if (lane == 0) { mh[h] = m; lh[h] = l; }
387    }
388    threadgroup_barrier(mem_flags::mem_threadgroup);
389    // acc[h][j] = sum_c p[h][c] v[c][j]: thread = dim j
390    float acc[HPG];
391    for (int h = 0; h < HPG; ++h) acc[h] = 0.0f;
392    for (int c = 0; c < nc; ++c) {
393        const uint rowi = uint(cid[c]) * QKV + uint(g);
394        const float v = float(vq[rowi * QD + tid]) * float(vsc[rowi * 4 + (tid >> 6)]);
395        for (int h = 0; h < HPG; ++h) acc[h] = fma(s[h][c], v, acc[h]);
396    }
397    for (int h = 0; h < HPG; ++h) {
398        device float* o = pp + (g * HPG + h) * (QD + 2);
399        o[tid] = acc[h];
400        if (tid == 0) { o[QD] = mh[h]; o[QD + 1] = lh[h]; }
401    }
402}
403
404// grid (QH, n_tok), 256 threads: out = merge * sigmoid(gate), as prepared activations of n = QH * QD per token
405kernel void qsa_merge(device const float* part [[buffer(0)]], device const float* qfull [[buffer(1)]],
406                      device float* xp [[buffer(2)]], constant QsaArgs& a [[buffer(3)]],
407                      device const uint* rinfo [[buffer(4), function_constant(qsa_rows)]],
408                      uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]]) {
409    threadgroup float msum[256];
410    const int h = int(tg.x), t = int(tg.y);
411    const int nchunks = (QBUDGET + QCH - 1) / QCH;
412    const uint n_kv = (qsa_rows ? rinfo[8 + 4 * t + 1] : a.pos0 + uint(t)) + 1, width = min(n_kv, uint(QBUDGET));
413    const int nc = int((width + QCH - 1) / QCH);
414    device const float* pp = part + (uint(t) * nchunks * QH + uint(h)) * (QD + 2);
415    float M = -INFINITY;
416    for (int k = 0; k < nc; ++k) M = max(M, pp[k * QH * (QD + 2) + QD]);
417    float L = 0.0f, o = 0.0f;
418    for (int k = 0; k < nc; ++k) {
419        device const float* q = pp + k * QH * (QD + 2);
420        const float e = exp(q[QD] - M);
421        L = fma(q[QD + 1], e, L);
422        o = fma(q[tid], e, o);
423    }
424    o = o / L;
425    const float gate = qfull[(t * QH + h) * 2 * QD + QD + tid];
426    const float y = o * (1.0f / (1.0f + exp(-gate)));
427    // prepared planes (xprep layout) of the n = QH * QD vector
428    const uint n = QH * QD, plane = a.n_tok * n, d = uint(h) * QD + tid;
429    const int j = tid & 15;
430    const float q2s[8] = {1.0f, 0.25f, 0.0625f, 0.015625f, 0.00390625f, 0.0009765625f, 0.000244140625f, 0.00006103515625f};
431    const float p4s[4] = {1.0f, 0.00390625f, 1.52587890625e-05f, 5.9604644775390625e-08f};
432    device float* raw = xp + uint(t) * n + d;
433    raw[0] = y;
434    raw[plane] = y * q2s[j & 7];
435    raw[2 * plane] = y * p4s[j & 3];
436    raw[3 * plane] = (j & 1) ? y * 0.00390625f : y;
437    if (xh16) put_x16(xp, plane, uint(t) * n + d, j, y);
438    msum[tid] = y;
439    threadgroup_barrier(mem_flags::mem_threadgroup);
440    if (j == 0) {
441        float s0 = 0.0f, s1 = 0.0f;
442        for (int k = 0; k < 16; k += 2) { s0 += msum[tid + k]; s1 += msum[tid + k + 1]; }
443        xp[4 * plane + uint(t) * (n / 16) + d / 16] = s0 + s1;
444    }
445}