okami.mom/strata

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

Niko1221Merge f-0216-dfship into f-0216-all78c5a834e

main
22.3 KiB374 linesraw
1// metal/kernels/qsa_prompt.metal - QSA attention for a PROMPT chunk on the matrix units (after qsa.metal: QH, QKV, QD,
2// QBUDGET, QCH, QsaArgs).  The same split-K partials as qsa_attn (part [t][chunk][QH][QD + 2]: acc, then m, l), so
3// qsa_merge is unchanged; per (chunk of QCH = 64 selected cells, kv head g, token t) one simdgroup:
4//   S[12 x 64] = Qh[12 x 256] . K^T / 16      single-simdgroup matmul2d, K (int8 * fp16 scale per 64) decoded into
5//                                             the right-input cooperative tensor, 32 dims a step
6//   per head: m = max, p = exp(s - m), l = sum p (fp32, through threadgroup memory), P -> fp16
7//   acc[12 x 256] = P[12 x 64] . V[64 x 256]  four 64-dim matmuls, V decoded into the right input
8// The operands are fp16 (q rounded from fp32; k, v = int8 * scale rounded): to rounding of qsa_attn's fp32.
9#include <MetalPerformancePrimitives/MetalPerformancePrimitives.h>
10using namespace mpp::tensor_ops;
11#ifndef STRATA_COOP_K4
12#define STRATA_COOP_K4
13// function constant 7: the right-input cooperative tensor holds runs of 4 consecutive k at one n per lane (the M5's
14// layout; tests/coop_layout).  false (the M4: runs of 2 n at one k): every element decoded on its own.
15constant bool COOP_K4 [[function_constant(7)]];
16constant bool coop_k4 = is_function_constant_defined(COOP_K4) ? COOP_K4 : true;
17#endif
18
19// a bisection probe (function constant 8): stop at stage n and write m = n (1: after the ids, 2: after S, 3: after
20// the softmax); 0 = normal
21constant int QSA_STOP [[function_constant(8)]];
22constant int qsa_stop = is_function_constant_defined(QSA_STOP) ? QSA_STOP : 0;
23
24// grid (chunks, QKV, n_tok), 32 threads.  qh: the q heads as fp16 [t][QH][QD] (qcur rounded).
25kernel void qsa_attn_mm(device const half* qh [[buffer(0)]], device const char* kq [[buffer(1)]],
26                        device const char* vq [[buffer(2)]], device const half* ksc [[buffer(3)]],
27                        device const half* vsc [[buffer(4)]], device const int* ids [[buffer(5)]],
28                        device float* part [[buffer(6)]], constant QsaArgs& a [[buffer(7)]],
29                        uint3 tg [[threadgroup_position_in_grid]], ushort lane [[thread_index_in_simdgroup]]) {
30    constexpr int HPG = QH / QKV, NCH = (QBUDGET + QCH - 1) / QCH;
31    threadgroup float s[16 * QCH];
32    threadgroup half p[16 * QCH];
33    threadgroup int cid[QCH];
34    threadgroup half vs[QCH][4];
35    const int chunk = int(tg.x), g = int(tg.y), t = int(tg.z);
36    const uint n_kv = a.pos0 + uint(t) + 1, width = min(n_kv, uint(QBUDGET));
37    const int c0 = chunk * QCH;
38    device float* pp = part + ((uint(t) * NCH + chunk) * QH + g * HPG) * (QD + 2);
39    if (uint(c0) >= width) {
40        if (lane < HPG) { pp[lane * (QD + 2) + QD] = -INFINITY; pp[lane * (QD + 2) + QD + 1] = 0.0f; }
41        return;
42    }
43    const int nc = min(QCH, int(width) - c0);
44    for (int c = lane; c < QCH; c += 32) {
45        const int id = c < nc ? ids[t * QBUDGET + c0 + c] : -1;
46        cid[c] = id;
47        for (int j = 0; j < 4; ++j) vs[c][j] = id >= 0 ? vsc[(uint(id) * QKV + g) * 4 + j] : half(0.0f);
48    }
49    simdgroup_barrier(mem_flags::mem_threadgroup);
50    if (qsa_stop == 1) { if (lane < HPG) { pp[lane * (QD + 2) + QD] = 1.0f; pp[lane * (QD + 2) + QD + 1] = 1.0f; } return; }
51    // ---- S = Q K^T
52    {
53        constexpr auto desc = matmul2d_descriptor(16, QCH, 32, false, true, false, matmul2d_descriptor::mode::multiply_accumulate);
54        matmul2d<desc, execution_simdgroup> op;
55        tensor<device half, dextents<int32_t, 2>, tensor_inline> tQ((device half*)qh + (uint(t) * QH + g * HPG) * QD,
56                                                                   dextents<int32_t, 2>(QD, HPG));
57        auto rk = op.template get_right_input_cooperative_tensor<half, half, float>();
58        auto tA = tQ.template slice<32, 16>(0, 0);
59        auto acc = op.template get_destination_cooperative_tensor<__tensor_ops_detail::__remove_addrspace_t<decltype(tA)>, __tensor_ops_detail::__remove_addrspace_t<decltype(rk)>, float>();
60        for (uint16_t i = 0; i < acc.get_capacity(); ++i)
61            if (acc.is_valid_element(i)) acc[i] = 0.0f;
62        for (int k0 = 0; k0 < QD; k0 += 32) {
63            if (!coop_k4) {
64                for (uint16_t i = 0; i < rk.get_capacity(); ++i) {
65                    const auto ix = rk.get_multidimensional_index(i);
66                    const int k = k0 + ix[0], id = cid[ix[1]];
67                    // the row is clamped and the select is on the value: a select with the device load in the arm
68                    // loses the threadgroup on the M1 (macOS 26, measured); the discarded value cannot matter
69                    const uint row = uint(max(id, 0)) * QKV + g;
70                    const float v = float(kq[row * QD + k]) * float(ksc[row * 4 + (k >> 6)]);
71                    rk[i] = id >= 0 ? half(v) : half(0.0f);
72                }
73            } else
74#pragma clang loop unroll(full)
75            for (uint16_t i = 0; i < rk.get_capacity(); i += 4) {
76                const auto ix = rk.get_multidimensional_index(i);
77                const int k = k0 + ix[0], c = ix[1], id = cid[c];
78                half4 w = half4(0.0h);
79                if (id >= 0) {
80                    const uint row = uint(id) * QKV + g;
81                    const char4 q4 = *(device const char4*)(kq + row * QD + k);
82                    w = half4(float4(q4) * float(ksc[row * 4 + (k >> 6)]));
83                }
84                rk[i] = w.x; rk[i + 1] = w.y; rk[i + 2] = w.z; rk[i + 3] = w.w;
85            }
86            tA = tQ.template slice<32, 16>(k0, 0);
87            op.run(tA, rk, acc);
88        }
89        tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline> tS(s, dextents<int32_t, 2>(QCH, 16));
90        acc.store(tS);
91    }
92    simdgroup_barrier(mem_flags::mem_threadgroup);
93    if (qsa_stop == 2) { if (lane < HPG) { pp[lane * (QD + 2) + QD] = 2.0f; pp[lane * (QD + 2) + QD + 1] = 1.0f; } return; }
94    // ---- softmax pieces per head (lane = head for the reductions; 12 heads)
95    float mh = -INFINITY, lh = 0.0f;
96    if (lane < HPG) {
97        for (int c = 0; c < nc; ++c) mh = max(mh, s[lane * QCH + c] * 0.0625f);
98        for (int c = 0; c < QCH; ++c) {
99            const float e = c < nc ? exp(s[lane * QCH + c] * 0.0625f - mh) : 0.0f;
100            lh += e;
101            p[lane * QCH + c] = half(e);
102        }
103    } else if (lane < 16) {
104        for (int c = 0; c < QCH; ++c) p[lane * QCH + c] = half(0.0f);
105    }
106    simdgroup_barrier(mem_flags::mem_threadgroup);
107    if (qsa_stop == 3) { if (lane < HPG) { pp[lane * (QD + 2) + QD] = 3.0f; pp[lane * (QD + 2) + QD + 1] = 1.0f; } return; }
108    // ---- acc = P V, 64 dims at a time
109    {
110        // K = 32 cells a run (two runs a 64-cell chunk): K = 64 runs compute garbage on the M4
111        constexpr auto desc = matmul2d_descriptor(16, 64, 32, false, true, false, matmul2d_descriptor::mode::multiply_accumulate);
112        matmul2d<desc, execution_simdgroup> op;
113        tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline> tP(p, dextents<int32_t, 2>(QCH, 16));
114        tensor<device float, dextents<int32_t, 2>, tensor_inline> tO(pp, dextents<int32_t, 2>(QD + 2, HPG));
115        for (int d0 = 0; d0 < QD; d0 += 64) {
116            auto rv = op.template get_right_input_cooperative_tensor<half, half, float>();
117            auto tPh = tP.template slice<32, 16>(0, 0);
118            auto acc = op.template get_destination_cooperative_tensor<__tensor_ops_detail::__remove_addrspace_t<decltype(tPh)>, __tensor_ops_detail::__remove_addrspace_t<decltype(rv)>, float>();
119            for (uint16_t i = 0; i < acc.get_capacity(); ++i)
120                if (acc.is_valid_element(i)) acc[i] = 0.0f;
121            for (int c0 = 0; c0 < QCH; c0 += 32) {
122#pragma clang loop unroll(full)
123                for (uint16_t i = 0; i < rv.get_capacity(); ++i) {
124                    const auto ix = rv.get_multidimensional_index(i);   // (cell, dim)
125                    const int c = c0 + ix[0], d = d0 + ix[1], id = cid[c];
126                    const uint row = uint(max(id, 0)) * QKV + g;   // clamped, as in the S fill above
127                    const float v = float(vq[row * QD + d]) * float(vs[c][d >> 6]);
128                    rv[i] = id >= 0 ? half(v) : half(0.0f);
129                }
130                tPh = tP.template slice<32, 16>(c0, 0);
131                op.run(tPh, rv, acc);
132            }
133            if (qsa_stop == 4) {   // the bisection: the old direct store into the 258-float rows
134                auto mO = tO.slice(d0, 0);
135                acc.store(mO);
136                continue;
137            }
138            // through threadgroup memory (s is free now): a matmul2d store into rows of QD + 2 floats loses the
139            // whole threadgroup on the M4
140            tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline> tT(s, dextents<int32_t, 2>(64, 16));
141            simdgroup_barrier(mem_flags::mem_threadgroup);
142            acc.store(tT);
143            simdgroup_barrier(mem_flags::mem_threadgroup);
144            for (int it = lane; it < HPG * 64; it += 32) pp[(it >> 6) * (QD + 2) + d0 + (it & 63)] = s[it];
145        }
146    }
147    if (lane < HPG) { pp[lane * (QD + 2) + QD] = mh; pp[lane * (QD + 2) + QD + 1] = lh; }
148}
149
150// qcur (fp32) -> fp16 for qsa_attn_mm
151kernel void qsa_q_f16(device const float* q [[buffer(0)]], device half* qh [[buffer(1)]], constant uint& n [[buffer(2)]],
152                      uint gid [[thread_position_in_grid]]) {
153    if (gid < n) qh[gid] = half(q[gid]);
154}
155
156// qsa_merge for a prompt chunk with the fp16 output the attn_output GEMM reads: qsa_merge's y, as half, at [t][h][d]
157// (qsa_merge writes y into the first plane of the prepared activations and act_f16 rounds that plane to half; here one
158// pass, bitwise the same halves, and no other plane or sum).  grid (QH, n_tok), 256 threads.
159kernel void qsa_merge_h(device const float* part [[buffer(0)]], device const float* qfull [[buffer(1)]],
160                        device half* xh [[buffer(2)]], constant QsaArgs& a [[buffer(3)]],
161                        uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]]) {
162    const int h = int(tg.x), t = int(tg.y);
163    const int nchunks = (QBUDGET + QCH - 1) / QCH;
164    const uint n_kv = a.pos0 + uint(t) + 1, width = min(n_kv, uint(QBUDGET));
165    const int nc = int((width + QCH - 1) / QCH);
166    device const float* pp = part + (uint(t) * nchunks * QH + uint(h)) * (QD + 2);
167    float M = -INFINITY;
168    for (int k = 0; k < nc; ++k) M = max(M, pp[k * QH * (QD + 2) + QD]);
169    float L = 0.0f, o = 0.0f;
170    for (int k = 0; k < nc; ++k) {
171        device const float* q = pp + k * QH * (QD + 2);
172        const float e = exp(q[QD] - M);
173        L = fma(q[QD + 1], e, L);
174        o = fma(q[tid], e, o);
175    }
176    o = o / L;
177    const float gate = qfull[(t * QH + h) * 2 * QD + QD + tid];
178    const float y = o * (1.0f / (1.0f + exp(-gate)));
179    xh[(uint(t) * QH + uint(h)) * QD + tid] = half(y);
180}
181
182// qsa_score as a GEMM (fp32 operands, so the selection sees qsa_score's values to fp32 rounding): S[(t, h)][b] =
183// qidx[t][h] . pooled[b] for 16 tokens x IH heads (64 rows) by 64 blocks a threadgroup; the epilogue sums relu over
184// the heads.  The tail block n_bid (the `dead` key, + 1e9 when it has cells) and blocks past it are left to the
185// scalar path: the tail is scored here by one simdgroup a token; blocks > n_bid are not written (qsa_topk reads
186// b <= n_bid).  grid (ceil(max blocks / 64), ceil(T / 16)), 128 threads.
187kernel void qsa_score_mm(device const float* qidx [[buffer(0)]], device const float* pooled [[buffer(1)]],
188                         device const float* dead [[buffer(2)]], device float* scores [[buffer(3)]],
189                         constant QsaArgs& a [[buffer(4)]],
190                         uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]],
191                         ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
192    threadgroup float ot[64 * 64];
193    const int b0 = int(tg.x) * 64, t0 = int(tg.y) * 16;
194    const uint nb_all = (a.pos0 + a.n_tok) / 4 + 1;   // blocks any token of the chunk can score
195    tensor<device float, dextents<int32_t, 2>, tensor_inline> tQ((device float*)qidx, dextents<int32_t, 2>(ID, int(a.n_tok) * IH));
196    tensor<device float, dextents<int32_t, 2>, tensor_inline> tK((device float*)pooled, dextents<int32_t, 2>(ID, int(nb_all)));
197    tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline> tO(ot, dextents<int32_t, 2>(64, 64));
198    constexpr auto desc = matmul2d_descriptor(64, 64, dynamic_length_v<int>, false, true, false);
199    matmul2d<desc, execution_simdgroups<4>> op;
200    auto mA = tQ.slice(0, t0 * IH);
201    auto mB = tK.slice(0, b0);
202    op.run(mA, mB, tO);
203    threadgroup_barrier(mem_flags::mem_threadgroup);
204    const uint stride = a.max_cells / 4 + 2;
205    for (int idx = tid; idx < 16 * 64; idx += 128) {
206        const int tt = idx >> 6, j = idx & 63, t = t0 + tt, b = b0 + j;
207        if (t >= int(a.n_tok)) continue;
208        const uint n_kv = a.pos0 + uint(t) + 1, n_bid = n_kv >> 2;
209        if (uint(b) >= n_bid) continue;
210        float s = 0.0f;
211        for (int h = 0; h < IH; ++h) s += max(ot[(tt * IH + h) * 64 + j], 0.0f);
212        scores[uint(t) * stride + b] = s;
213    }
214    // the tail block of each token in this threadgroup's block range (the first column threadgroup does it)
215    if (tg.x == 0)
216        for (int tt = sg; tt < 16; tt += 4) {
217            const int t = t0 + tt;
218            if (t >= int(a.n_tok)) break;
219            const uint n_kv = a.pos0 + uint(t) + 1, n_bid = n_kv >> 2;
220            float k[4];
221            for (int i = 0; i < 4; ++i) k[i] = dead[lane + 32 * i];
222            float s = 0.0f;
223            for (int h = 0; h < IH; ++h) {
224                float d = 0.0f;
225                for (int i = 0; i < 4; ++i) d = fma(qidx[(t * IH + h) * ID + lane + 32 * i], k[i], d);
226                d = simd_sum(d);
227                s += max(d, 0.0f);
228            }
229            if ((n_kv & 3) != 0) s += 1e9f;
230            if (lane == 0) scores[uint(t) * stride + n_bid] = s;
231        }
232}
233
234// qsa_flash: the whole attention of a (kv head g, token t) in one threadgroup (no split-K partials, no merge): the
235// width selected cells in chunks of 64 with an online softmax; 4 simdgroups, simdgroup s owns dims 64 s .. 64 s + 63
236// (its slice of S's K sum and its 64 output dims).  Out: xq = (acc / l) * sigmoid(gate) as fp16 (attn_output's GEMM
237// operand).  grid (QKV, n_tok), 128 threads.
238kernel void qsa_flash(device const half* qh [[buffer(0)]], device const char* kq [[buffer(1)]],
239                      device const char* vq [[buffer(2)]], device const half* ksc [[buffer(3)]],
240                      device const half* vsc [[buffer(4)]], device const int* ids [[buffer(5)]],
241                      device const float* qfull [[buffer(6)]], device half* xqh [[buffer(7)]], constant QsaArgs& a [[buffer(8)]],
242                      uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]],
243                      ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
244    constexpr int HPG = QH / QKV;
245    threadgroup float sp[4][16 * QCH];
246    threadgroup half p[16 * QCH];
247    threadgroup int cid[QCH];
248    threadgroup float vs[QCH];
249    threadgroup float fac[16], lsum[16], mrun[16];
250    const int g = int(tg.x), t = int(tg.y);
251    const uint n_kv = a.pos0 + uint(t) + 1, width = min(n_kv, uint(QBUDGET));
252    const int nch = int((width + QCH - 1) / QCH);
253    if (tid < 16) { mrun[tid] = -INFINITY; lsum[tid] = 0.0f; }
254    constexpr auto dS = matmul2d_descriptor(16, QCH, 32, false, true, false, matmul2d_descriptor::mode::multiply_accumulate);
255    constexpr auto dO = matmul2d_descriptor(16, 64, 32, false, true, false, matmul2d_descriptor::mode::multiply_accumulate);
256    matmul2d<dS, execution_simdgroup> opS;
257    matmul2d<dO, execution_simdgroup> opO;
258    tensor<device half, dextents<int32_t, 2>, tensor_inline> tQ((device half*)qh + (uint(t) * QH + g * HPG) * QD,
259                                                               dextents<int32_t, 2>(QD, HPG));
260    tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline> tP(p, dextents<int32_t, 2>(QCH, 16));
261    auto rv = opO.template get_right_input_cooperative_tensor<half, half, float>();
262    auto tPh = tP.template slice<32, 16>(0, 0);
263    auto acc = opO.template get_destination_cooperative_tensor<__tensor_ops_detail::__remove_addrspace_t<decltype(tPh)>,
264                                                               __tensor_ops_detail::__remove_addrspace_t<decltype(rv)>, float>();
265    // (a second destination tensor, not a copy of acc: the MetalPerformancePrimitives headers of macOS 26.3 cannot copy a
266    // cooperative tensor - "cannot initialize a parameter of type 'void *' with an rvalue of type 'const void *'", #2323;
267    // tot is zeroed right below, so the copy was only there for its type)
268    auto tot = opO.template get_destination_cooperative_tensor<__tensor_ops_detail::__remove_addrspace_t<decltype(tPh)>,
269                                                               __tensor_ops_detail::__remove_addrspace_t<decltype(rv)>, float>();   // the running output; acc takes one chunk (fresh each chunk: on the M4 a run does not accumulate
270                      // into elements rescaled in place)
271    for (uint16_t i = 0; i < acc.get_capacity(); ++i)
272        if (acc.is_valid_element(i)) tot[i] = 0.0f;
273    const int d0 = sg * 64;
274    for (int ch = 0; ch < nch; ++ch) {
275        const int c0 = ch * QCH, nc = min(QCH, int(width) - c0);
276        threadgroup_barrier(mem_flags::mem_threadgroup);
277        if (tid < QCH) {
278            const int id = tid < nc ? ids[t * QBUDGET + c0 + tid] : -1;
279            cid[tid] = id;
280            vs[tid] = id >= 0 ? float(vsc[(uint(id) * QKV + g) * 4 + sg * 0]) : 0.0f;   // (per-simdgroup scale below)
281        }
282        threadgroup_barrier(mem_flags::mem_threadgroup);
283        // S partial over this simdgroup's 64 dims
284        {
285            auto rk = opS.template get_right_input_cooperative_tensor<half, half, float>();
286            auto tA = tQ.template slice<32, 16>(d0, 0);
287            auto s = opS.template get_destination_cooperative_tensor<__tensor_ops_detail::__remove_addrspace_t<decltype(tA)>,
288                                                                     __tensor_ops_detail::__remove_addrspace_t<decltype(rk)>, float>();
289            for (uint16_t i = 0; i < s.get_capacity(); ++i)
290                if (s.is_valid_element(i)) s[i] = 0.0f;
291            for (int k0 = d0; k0 < d0 + 64; k0 += 32) {
292                if (!coop_k4) {
293                    for (uint16_t i = 0; i < rk.get_capacity(); ++i) {
294                        const auto ix = rk.get_multidimensional_index(i);
295                        const int k = k0 + ix[0], id = cid[ix[1]];
296                        const uint row = uint(max(id, 0)) * QKV + g;   // clamped, as in qsa_attn_mm
297                        const float v = float(kq[row * QD + k]) * float(ksc[row * 4 + (k >> 6)]);
298                        rk[i] = id >= 0 ? half(v) : half(0.0f);
299                    }
300                } else
301#pragma clang loop unroll(full)
302                for (uint16_t i = 0; i < rk.get_capacity(); i += 4) {
303                    const auto ix = rk.get_multidimensional_index(i);
304                    const int k = k0 + ix[0], c = ix[1], id = cid[c];
305                    half4 w = half4(0.0h);
306                    if (id >= 0) {
307                        const uint row = uint(id) * QKV + g;
308                        const char4 q4 = *(device const char4*)(kq + row * QD + k);
309                        w = half4(float4(q4) * float(ksc[row * 4 + (k >> 6)]));
310                    }
311                    rk[i] = w.x; rk[i + 1] = w.y; rk[i + 2] = w.z; rk[i + 3] = w.w;
312                }
313                tA = tQ.template slice<32, 16>(k0, 0);
314                opS.run(tA, rk, s);
315            }
316            tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline> tS(sp[sg], dextents<int32_t, 2>(QCH, 16));
317            s.store(tS);
318        }
319        threadgroup_barrier(mem_flags::mem_threadgroup);
320        // online softmax per head row: simdgroup 0, lane = row
321        if (sg == 0 && lane < 16) {
322            if (lane < HPG) {
323                float m = mrun[lane];
324                for (int c = 0; c < nc; ++c) {
325                    const int q = lane * QCH + c;
326                    m = max(m, (((sp[0][q] + sp[1][q]) + (sp[2][q] + sp[3][q])) * 0.0625f));
327                }
328                const float f = exp(mrun[lane] - m);
329                float l = lsum[lane] * f;
330                for (int c = 0; c < QCH; ++c) {
331                    const int q = lane * QCH + c;
332                    const float e = c < nc ? exp(((sp[0][q] + sp[1][q]) + (sp[2][q] + sp[3][q])) * 0.0625f - m) : 0.0f;
333                    l += e;
334                    p[q] = half(e);
335                }
336                mrun[lane] = m;
337                lsum[lane] = l;
338                fac[lane] = f;
339            } else {
340                for (int c = 0; c < QCH; ++c) p[lane * QCH + c] = half(0.0f);
341                fac[lane] = 0.0f;
342            }
343        }
344        threadgroup_barrier(mem_flags::mem_threadgroup);
345        // rescale this simdgroup's accumulator rows, then acc += P V over its 64 dims
346        for (uint16_t i = 0; i < acc.get_capacity(); ++i)
347            if (acc.is_valid_element(i)) acc[i] = 0.0f;
348        for (int c0 = 0; c0 < QCH; c0 += 32) {   // K = 32 cells a run (K = 64 is wrong on the M4)
349#pragma clang loop unroll(full)
350            for (uint16_t i = 0; i < rv.get_capacity(); ++i) {
351                const auto ix = rv.get_multidimensional_index(i);   // (cell, dim)
352                const int c = c0 + ix[0], d = d0 + ix[1], id = cid[c];
353                const uint row = uint(max(id, 0)) * QKV + g;   // clamped, as in qsa_attn_mm
354                const float v = float(vq[row * QD + d]) * float(vsc[row * 4 + sg]);
355                rv[i] = id >= 0 ? half(v) : half(0.0f);
356            }
357            tPh = tP.template slice<32, 16>(c0, 0);
358            opO.run(tPh, rv, acc);
359        }
360        for (uint16_t i = 0; i < acc.get_capacity(); ++i)
361            if (acc.is_valid_element(i)) tot[i] = fma(tot[i], fac[acc.get_multidimensional_index(i)[1]], acc[i]);
362    }
363    threadgroup_barrier(mem_flags::mem_threadgroup);
364    for (uint16_t i = 0; i < acc.get_capacity(); ++i)
365        if (acc.is_valid_element(i)) {
366            const auto ix = acc.get_multidimensional_index(i);   // (dim, row)
367            const int h = ix[1], d = d0 + ix[0];
368            if (h < HPG) {
369                const int hh = g * HPG + h;
370                const float gate = qfull[(uint(t) * QH + hh) * 2 * QD + QD + d];
371                xqh[(uint(t) * QH + hh) * QD + d] = half(tot[i] / lsum[h] * (1.0f / (1.0f + exp(-gate))));
372            }
373        }
374}