okami.mom/strata

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

Niko1221rc1 merge metal-selq4 (371a28ed1)6527e33c7

main
44.7 KiB852 linesraw
1// metal/src/engine/msl/dflash2.metal - the small kernels of the DFlash2 drafter on Metal (the ones between the Q8_0 GEMVs, which are the
2// engine's own gemv_8_* over the DF2P pack): the same math as src/kernels/cuda/dflash2.cu, see include/strata/kernels/dflash2.hpp.
3//
4//   df2_rms         y[r] = x[r] * rsqrt(mean(x[r]^2) + eps) * w            rows of width n (w: the plain weight)
5//   df2_conv        the grouped dynamic 2-tap convolution over the block's rows (+ residual)
6//   df2_norm_rope   per (row, head): rope(rmsnorm(x) * gamma), written to slot(r) (the K/V ring or the block's own rows)
7//   df2_copy_rows   the V half of the ring write
8//   df2_swiglu      silu(gate) * up
9//   df2_attn_part / df2_attn_merge   the 8 query rows over the ring + the block's keys, windowed, not causal inside the block
10//   df2_topk_part / df2_topk_merge   the head's top-16 per row (value-descending, ties to the lower index)
11//   df2_select      the candidate selector's left-to-right walk
12//   df2_tap         the verify window's / prompt chunk's tap: the mean over the hc streams of a layer's completed output
13//
14// Compiled standalone (no quant.metal): the GEMVs and xprep come from the engine's main library.
15
16#include <metal_stdlib>
17using namespace metal;
18
19constant int HD = 128;
20
21struct RmsArgs { uint n; float eps; };
22
23// grid (rows), 256 threads
24kernel void df2_rms(device const float* x [[buffer(0)]], device const float* w [[buffer(1)]], device float* y [[buffer(2)]],
25                    constant RmsArgs& a [[buffer(3)]], uint3 tg [[threadgroup_position_in_grid]],
26                    ushort tid [[thread_index_in_threadgroup]], ushort sg [[simdgroup_index_in_threadgroup]],
27                    ushort lane [[thread_index_in_simdgroup]]) {
28    threadgroup float part[8];
29    device const float* xr = x + tg.x * a.n;
30    float ss = 0.0f;
31    for (uint d = tid; d < a.n; d += 256) ss = fma(xr[d], xr[d], ss);
32    ss = simd_sum(ss);
33    if (lane == 0) part[sg] = ss;
34    threadgroup_barrier(mem_flags::mem_threadgroup);
35    float tot = 0.0f;
36    for (int i = 0; i < 8; ++i) tot += part[i];
37    const float rs = rsqrt(tot / float(a.n) + a.eps);
38    device float* yr = y + tg.x * a.n;
39    for (uint d = tid; d < a.n; d += 256) yr[d] = xr[d] * rs * w[d];
40}
41
42struct ConvArgs { uint rows; uint H; uint group; uint dyn_stride; uint has_resid; };
43
44kernel void df2_conv(device const float* x [[buffer(0)]], device const float* dyn [[buffer(1)]], device const float* base [[buffer(2)]],
45                     device const float* resid [[buffer(3)]], device float* out [[buffer(4)]], constant ConvArgs& a [[buffer(5)]],
46                     uint i [[thread_position_in_grid]]) {
47    if (i >= a.rows * a.H) return;
48    const uint b = i / a.H, c = i % a.H;
49    const uint groups = a.H / a.group;
50    float acc = 0.0f;
51    for (uint o = 0; o < 2; ++o) {
52        if (b < o) continue;
53        const float k = base[o * a.H + c] + dyn[b * a.dyn_stride + o * groups + c / a.group];
54        acc = fma(k, x[(b - o) * a.H + c], acc);
55    }
56    out[i] = a.has_resid ? resid[i] + acc : acc;
57}
58
59struct NrArgs { uint in_stride; uint slot_mod; uint heads; float eps; uint has_rope; };
60
61// grid (rows, heads), 128 threads
62kernel void df2_norm_rope(device const float* in [[buffer(0)]], device const float* gamma [[buffer(1)]], device const int* pos [[buffer(2)]],
63                          device const float* table [[buffer(3)]], device float* out [[buffer(4)]], constant NrArgs& a [[buffer(5)]],
64                          uint3 tg [[threadgroup_position_in_grid]], ushort d [[thread_index_in_threadgroup]],
65                          ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
66    threadgroup float red[4];
67    threadgroup float y[HD];
68    const uint r = tg.x, h = tg.y;
69    const float x = in[r * a.in_stride + h * HD + d];
70    float ss = simd_sum(x * x);
71    if (lane == 0) red[sg] = ss;
72    threadgroup_barrier(mem_flags::mem_threadgroup);
73    const float tot = red[0] + red[1] + red[2] + red[3];
74    const float v = x * rsqrt(tot / float(HD) + a.eps) * gamma[d];
75    float res = v;
76    if (a.has_rope) {
77        y[d] = v;
78        threadgroup_barrier(mem_flags::mem_threadgroup);
79        const int i = d & 63;
80        const float c = table[(r * 2 + 0) * 64 + i], s = table[(r * 2 + 1) * 64 + i];
81        res = d < 64 ? v * c - y[d + 64] * s : v * c + y[d - 64] * s;
82    }
83    const uint slot = a.slot_mod > 0 ? uint(pos[r]) % a.slot_mod : r;
84    out[(slot * a.heads + h) * HD + d] = res;
85}
86
87struct CopyArgs { uint slot_mod; uint rows; uint cols; };
88
89kernel void df2_copy_rows(device const float* in [[buffer(0)]], device float* out [[buffer(1)]], device const int* pos [[buffer(2)]],
90                          constant CopyArgs& a [[buffer(3)]], uint i [[thread_position_in_grid]]) {
91    if (i >= a.rows * a.cols) return;
92    const uint r = i / a.cols, c = i % a.cols;
93    const uint slot = a.slot_mod > 0 ? uint(pos[r]) % a.slot_mod : r;
94    out[slot * a.cols + c] = in[i];
95}
96
97struct SwArgs { uint n; };
98
99kernel void df2_swiglu(device const float* g [[buffer(0)]], device const float* u [[buffer(1)]], device float* y [[buffer(2)]],
100                       constant SwArgs& a [[buffer(3)]], uint i [[thread_position_in_grid]]) {
101    if (i >= a.n) return;
102    const float gv = g[i];
103    y[i] = gv / (1.0f + exp(-gv)) * u[i];
104}
105
106// ---- attention.  Grid (8 K/V heads, chunks of 64 keys), 64 threads: thread t scores key t of the chunk against the 32 queries
107// (4 heads x 8 rows) of its K/V head, the 32 threads below 32 then take each one query's softmax statistics over the chunk, and
108// thread t sums V for the dims t and t + 64.  part[chunk][kvh][qi] = (m, l, O[128]).
109struct AttnArgs { uint ring; uint window; };
110constant int AK = 64;     // keys per chunk
111constant int AROWS = 8;   // the block's rows (and block keys)
112
113kernel void df2_attn_part(device const float* q [[buffer(0)]], device const float* kring [[buffer(1)]], device const float* vring [[buffer(2)]],
114                          device const float* kblk [[buffer(3)]], device const float* vblk [[buffer(4)]],
115                          device const int* anchor_pos [[buffer(5)]], device float* part [[buffer(6)]], constant AttnArgs& a [[buffer(7)]],
116                          uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]]) {
117    threadgroup float Qs[32 * HD];
118    threadgroup float Ss[32 * AK];
119    threadgroup float Mx[32];
120    threadgroup float Ls[32];
121    const uint kvh = tg.x, chunk = tg.y;
122    const int s = *anchor_pos;
123    const int lo = max(max(0, s - (int(a.window) - 1)), anchor_pos[1]);   // anchor_pos[1]: first position whose ring slot belongs to this request's lineage
124    const int nctx = s - lo;
125    const int nkeys = nctx + AROWS;
126    const int k_begin = int(chunk) * AK;
127    device float* pbase = part + ((chunk * 8 + kvh) * 32) * 130;
128    if (k_begin >= nkeys) {
129        for (int qi = 0; qi < 32; ++qi) {
130            if (tid == 0) { pbase[qi * 130] = -INFINITY; pbase[qi * 130 + 1] = 0.0f; }
131            pbase[qi * 130 + 2 + tid] = 0.0f;
132            pbase[qi * 130 + 2 + tid + 64] = 0.0f;
133        }
134        return;
135    }
136    const float scale = rsqrt(float(HD));
137    for (int i = tid; i < 32 * HD; i += AK) {
138        const int qa = i / HD, d = i % HD;
139        const int row = qa >> 2, g = qa & 3;
140        Qs[qa * HD + d] = q[(row * 32 + kvh * 4 + g) * HD + d] * scale;
141    }
142    threadgroup_barrier(mem_flags::mem_threadgroup);
143    // phase 1: scores
144    const int k = k_begin + int(tid);
145    const bool valid = k < nkeys;
146    float sc[32];
147    for (int qi = 0; qi < 32; ++qi) sc[qi] = 0.0f;
148    if (valid) {
149        device const float4* kp = (device const float4*)(k < nctx ? kring + ((uint(lo + k) % a.ring) * 8 + kvh) * HD
150                                                                   : kblk + (uint(k - nctx) * 8 + kvh) * HD);
151        for (int d4 = 0; d4 < HD / 4; ++d4) {
152            const float4 kv = kp[d4];
153            for (int qi = 0; qi < 32; ++qi) sc[qi] += dot(kv, *(threadgroup const float4*)(Qs + qi * HD + d4 * 4));
154        }
155    }
156    for (int qi = 0; qi < 32; ++qi) {
157        const int row = qi >> 2;
158        bool ok = valid;
159        if (ok && k < nctx) ok = (lo + k) > (s + row - int(a.window));   // s + row - j < window
160        Ss[qi * AK + tid] = ok ? sc[qi] : -INFINITY;
161    }
162    threadgroup_barrier(mem_flags::mem_threadgroup);
163    // phase 2: softmax statistics per query
164    if (tid < 32) {
165        float m = -INFINITY;
166        for (int j = 0; j < AK; ++j) m = max(m, Ss[tid * AK + j]);
167        float l = 0.0f;
168        for (int j = 0; j < AK; ++j) {
169            const float sv = Ss[tid * AK + j];
170            const float p = sv == -INFINITY ? 0.0f : exp(sv - m);
171            Ss[tid * AK + j] = p;
172            l += p;
173        }
174        Mx[tid] = m;
175        Ls[tid] = l;
176    }
177    threadgroup_barrier(mem_flags::mem_threadgroup);
178    // phase 3: P V
179    float acc0[32], acc1[32];
180    for (int qi = 0; qi < 32; ++qi) { acc0[qi] = 0.0f; acc1[qi] = 0.0f; }
181    const int kend = min(AK, nkeys - k_begin);
182    for (int j = 0; j < kend; ++j) {
183        const int kk = k_begin + j;
184        device const float* vp = kk < nctx ? vring + ((uint(lo + kk) % a.ring) * 8 + kvh) * HD : vblk + (uint(kk - nctx) * 8 + kvh) * HD;
185        const float v0 = vp[tid], v1 = vp[tid + 64];
186        for (int qi = 0; qi < 32; ++qi) {
187            const float p = Ss[qi * AK + j];
188            acc0[qi] = fma(p, v0, acc0[qi]);
189            acc1[qi] = fma(p, v1, acc1[qi]);
190        }
191    }
192    for (int qi = 0; qi < 32; ++qi) {
193        if (tid == 0) { pbase[qi * 130] = Mx[qi]; pbase[qi * 130 + 1] = Ls[qi]; }
194        pbase[qi * 130 + 2 + tid] = acc0[qi];
195        pbase[qi * 130 + 2 + tid + 64] = acc1[qi];
196    }
197}
198
199// grid (8 * 32), 128 threads: out[row][32 heads][128]
200kernel void df2_attn_merge(device const float* part [[buffer(0)]], device const int* anchor_pos [[buffer(1)]], device float* out [[buffer(2)]],
201                           constant AttnArgs& a [[buffer(3)]], uint3 tg [[threadgroup_position_in_grid]], ushort d [[thread_index_in_threadgroup]]) {
202    const uint kvh = tg.x >> 5, qi = tg.x & 31;
203    const int s = *anchor_pos;
204    const int lo = max(max(0, s - (int(a.window) - 1)), anchor_pos[1]);   // anchor_pos[1]: first position whose ring slot belongs to this request's lineage
205    const int nchunks = ((s - lo) + AROWS + AK - 1) / AK;
206    float M = -INFINITY;
207    for (int c = 0; c < nchunks; ++c) M = max(M, part[(((uint(c) * 8 + kvh) * 32) + qi) * 130]);
208    float L = 0.0f, o = 0.0f;
209    for (int c = 0; c < nchunks; ++c) {
210        device const float* p = part + (((uint(c) * 8 + kvh) * 32) + qi) * 130;
211        const float mc = p[0];
212        const float w = mc == -INFINITY ? 0.0f : exp(mc - M);
213        L += p[1] * w;
214        o = fma(p[2 + d], w, o);
215    }
216    const uint row = qi >> 2, g = qi & 3;
217    out[(row * 32 + kvh * 4 + g) * HD + d] = L > 0.0f ? o / L : 0.0f;
218}
219
220// ---- top-16
221struct TkArgs { int n; };
222struct TkMArgs { int use_map; };
223constant int TOPB = 64;
224constant int TOPK = 16;
225
226static inline bool better(float va, int ia, float vb, int ib) { return va > vb || (va == vb && ia < ib); }
227
228// grid (rows, TOPB), 256 threads
229kernel void df2_topk_part(device const float* logits [[buffer(0)]], device float* cval [[buffer(1)]], device int* cidx [[buffer(2)]],
230                          constant TkArgs& a [[buffer(3)]], uint3 tg [[threadgroup_position_in_grid]],
231                          ushort tid [[thread_index_in_threadgroup]], ushort sg [[simdgroup_index_in_threadgroup]],
232                          ushort lane [[thread_index_in_simdgroup]]) {
233    threadgroup float vals[4096];
234    threadgroup float wv[8];
235    threadgroup int wi[8];
236    const int row = int(tg.x), blk = int(tg.y), n = a.n;
237    const int cs = (n + TOPB - 1) / TOPB;
238    const int c0 = blk * cs, c1 = min(c0 + cs, n);
239    for (int i = tid; i < cs; i += 256) vals[i] = (c0 + i < c1) ? logits[row * n + c0 + i] : -INFINITY;
240    threadgroup_barrier(mem_flags::mem_threadgroup);
241    for (int k = 0; k < TOPK; ++k) {
242        float bv = -INFINITY;
243        int bi = 0x7fffffff;
244        for (int i = tid; i < cs; i += 256)
245            if (better(vals[i], i, bv, bi)) { bv = vals[i]; bi = i; }
246        for (ushort o = 16; o > 0; o >>= 1) {
247            const float ov = simd_shuffle_xor(bv, o);
248            const int oi = simd_shuffle_xor(bi, o);
249            if (better(ov, oi, bv, bi)) { bv = ov; bi = oi; }
250        }
251        if (lane == 0) { wv[sg] = bv; wi[sg] = bi; }
252        threadgroup_barrier(mem_flags::mem_threadgroup);
253        if (tid == 0) {
254            float v = wv[0];
255            int ix = wi[0];
256            for (int w = 1; w < 8; ++w)
257                if (better(wv[w], wi[w], v, ix)) { v = wv[w]; ix = wi[w]; }
258            const int o = (row * TOPB + blk) * TOPK + k;
259            cval[o] = v;
260            cidx[o] = v == -INFINITY ? -1 : c0 + ix;
261            if (v != -INFINITY) vals[ix] = -INFINITY;
262        }
263        threadgroup_barrier(mem_flags::mem_threadgroup);
264    }
265}
266
267// grid (rows), 256 threads
268kernel void df2_topk_merge(device const float* cval [[buffer(0)]], device const int* cidx [[buffer(1)]], device const int* idx_map [[buffer(2)]],
269                           device float* val [[buffer(3)]], device int* tok [[buffer(4)]], constant TkMArgs& a [[buffer(5)]],
270                           uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]],
271                           ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
272    constexpr int NC = TOPB * TOPK;
273    threadgroup float sv[NC];
274    threadgroup int si[NC];
275    threadgroup float wv[8];
276    threadgroup int wi[8], wp[8];
277    const int row = int(tg.x);
278    for (int i = tid; i < NC; i += 256) { sv[i] = cval[row * NC + i]; si[i] = cidx[row * NC + i]; }
279    threadgroup_barrier(mem_flags::mem_threadgroup);
280    for (int k = 0; k < TOPK; ++k) {
281        float bv = -INFINITY;
282        int bi = 0x7fffffff, bp = -1;
283        for (int i = tid; i < NC; i += 256)
284            if (si[i] >= 0 && better(sv[i], si[i], bv, bi)) { bv = sv[i]; bi = si[i]; bp = i; }
285        for (ushort o = 16; o > 0; o >>= 1) {
286            const float ov = simd_shuffle_xor(bv, o);
287            const int oi = simd_shuffle_xor(bi, o);
288            const int op = simd_shuffle_xor(bp, o);
289            if (better(ov, oi, bv, bi)) { bv = ov; bi = oi; bp = op; }
290        }
291        if (lane == 0) { wv[sg] = bv; wi[sg] = bi; wp[sg] = bp; }
292        threadgroup_barrier(mem_flags::mem_threadgroup);
293        if (tid == 0) {
294            float v = wv[0];
295            int ix = wi[0], p = wp[0];
296            for (int w = 1; w < 8; ++w)
297                if (better(wv[w], wi[w], v, ix)) { v = wv[w]; ix = wi[w]; p = wp[w]; }
298            if (p >= 0) si[p] = -1;
299            val[row * TOPK + k] = v;
300            tok[row * TOPK + k] = p >= 0 ? (a.use_map != 0 ? idx_map[ix] : ix) : 0;
301        }
302        threadgroup_barrier(mem_flags::mem_threadgroup);
303    }
304}
305
306// ---- the selector's walk: one threadgroup of 256.  Scores: unary[i][j] + dot(succ[tok[i][j]], pred[prev] * hp[i]) over rank 256.
307struct SelArgs { uint rank; uint rows; };
308
309static inline float bf16f(ushort h) { return as_type<float>(uint(h) << 16); }
310
311kernel void df2_select(device const float* hp [[buffer(0)]], device const float* unary [[buffer(1)]], device const int* tok [[buffer(2)]],
312                       device const ushort* pred_cb [[buffer(3)]], device const ushort* succ_cb [[buffer(4)]],
313                       device const int* anchor_tok [[buffer(5)]], device int* out_tok [[buffer(6)]], device float* out_prob [[buffer(7)]],
314                       constant SelArgs& a [[buffer(8)]], ushort tid [[thread_index_in_threadgroup]],
315                       ushort w [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
316    threadgroup float vp[256];
317    threadgroup float sc[TOPK];
318    threadgroup int prev;
319    if (tid == 0) prev = *anchor_tok;
320    threadgroup_barrier(mem_flags::mem_threadgroup);
321    for (uint i = 0; i < a.rows; ++i) {
322        vp[tid] = bf16f(pred_cb[uint(prev) * a.rank + tid]) * hp[i * a.rank + tid];
323        threadgroup_barrier(mem_flags::mem_threadgroup);
324        for (int j = w * 2; j < w * 2 + 2; ++j) {
325            const int t = tok[i * TOPK + j];
326            const uint4 raw = *(device const uint4*)(succ_cb + uint(t) * a.rank + lane * 8);
327            const uint u[4] = {raw.x, raw.y, raw.z, raw.w};
328            float acc = 0.0f;
329            for (int e = 0; e < 4; ++e) {
330                acc = fma(as_type<float>(u[e] << 16), vp[lane * 8 + e * 2], acc);
331                acc = fma(as_type<float>(u[e] & 0xffff0000u), vp[lane * 8 + e * 2 + 1], acc);
332            }
333            acc = simd_sum(acc);
334            if (lane == 0) sc[j] = unary[i * TOPK + j] + acc;
335        }
336        threadgroup_barrier(mem_flags::mem_threadgroup);
337        if (tid == 0) {
338            int bj = 0;
339            float bv = sc[0];
340            for (int j = 1; j < TOPK; ++j)
341                if (sc[j] > bv) { bv = sc[j]; bj = j; }
342            float z = 0.0f;
343            for (int j = 0; j < TOPK; ++j) z += exp(sc[j] - bv);
344            out_tok[i] = tok[i * TOPK + bj];
345            out_prob[i] = 1.0f / z;
346            prev = out_tok[i];
347        }
348        threadgroup_barrier(mem_flags::mem_threadgroup);
349    }
350}
351
352// The same walk over Q4_0 selector tables (the community GGUF's): a row is 8 ggml Q4_0 blocks of 18 bytes (half d, 16 bytes: byte j = element j low nibble,
353// element j + 16 high nibble); a value is (q - 8) * d, in fp32 as ggml dequantizes it.
354static inline float q4_0_val(device const uchar* row, uint e) {
355    device const uchar* b = row + (e >> 5) * 18;
356    const float d = float(*(device const half*)b);
357    const uint j = e & 31;
358    const uint q = j < 16 ? (b[2 + j] & 15u) : (b[2 + j - 16] >> 4);
359    return d * (float(q) - 8.0f);
360}
361
362kernel void df2_select_q4(device const float* hp [[buffer(0)]], device const float* unary [[buffer(1)]], device const int* tok [[buffer(2)]],
363                          device const uchar* pred_cb [[buffer(3)]], device const uchar* succ_cb [[buffer(4)]],
364                          device const int* anchor_tok [[buffer(5)]], device int* out_tok [[buffer(6)]], device float* out_prob [[buffer(7)]],
365                          constant SelArgs& a [[buffer(8)]], ushort tid [[thread_index_in_threadgroup]],
366                          ushort w [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
367    threadgroup float vp[256];
368    threadgroup float sc[TOPK];
369    threadgroup int prev;
370    const uint rowb = (a.rank / 32) * 18;   // 144 bytes a row
371    if (tid == 0) prev = *anchor_tok;
372    threadgroup_barrier(mem_flags::mem_threadgroup);
373    for (uint i = 0; i < a.rows; ++i) {
374        vp[tid] = q4_0_val(pred_cb + uint(prev) * rowb, tid) * hp[i * a.rank + tid];
375        threadgroup_barrier(mem_flags::mem_threadgroup);
376        for (int j = w * 2; j < w * 2 + 2; ++j) {
377            const int t = tok[i * TOPK + j];
378            device const uchar* row = succ_cb + uint(t) * rowb;
379            float acc = 0.0f;
380            for (int e = 0; e < 8; ++e) acc = fma(q4_0_val(row, lane * 8 + e), vp[lane * 8 + e], acc);
381            acc = simd_sum(acc);
382            if (lane == 0) sc[j] = unary[i * TOPK + j] + acc;
383        }
384        threadgroup_barrier(mem_flags::mem_threadgroup);
385        if (tid == 0) {
386            int bj = 0;
387            float bv = sc[0];
388            for (int j = 1; j < TOPK; ++j)
389                if (sc[j] > bv) { bv = sc[j]; bj = j; }
390            float z = 0.0f;
391            for (int j = 0; j < TOPK; ++j) z += exp(sc[j] - bv);
392            out_tok[i] = tok[i * TOPK + bj];
393            out_prob[i] = 1.0f / z;
394            prev = out_tok[i];
395        }
396        threadgroup_barrier(mem_flags::mem_threadgroup);
397    }
398}
399
400// ---- the tap: out[r][out_off + i] = (sum_c R[r][c][i] + bo[r][i] * sum_c 2 sigmoid(inj[r][c] / hc)) / hc.  Grid (n / 256, rows), 256 threads.
401struct TapArgs { uint n; uint hc; uint R_stride; uint bo_stride; uint inj_stride; uint out_stride; uint out_off; };
402
403kernel void df2_tap(device const float* R [[buffer(0)]], device const float* bo [[buffer(1)]], device const float* inj [[buffer(2)]],
404                    device float* out [[buffer(3)]], constant TapArgs& a [[buffer(4)]], uint2 gid [[thread_position_in_grid]]) {
405    const uint i = gid.x, r = gid.y;
406    if (i >= a.n) return;
407    float wsum = 0.0f, rs = 0.0f;
408    for (uint c = 0; c < a.hc; ++c) {
409        const float x = inj[r * a.inj_stride + c] / float(a.hc);
410        wsum += 2.0f / (1.0f + exp(-x));
411        rs += R[r * a.R_stride + c * a.n + i];
412    }
413    out[r * a.out_stride + a.out_off + i] = (rs + bo[r * a.bo_stride + i] * wsum) / float(a.hc);
414}
415
416// ---- Q8_0 matrix x up to 8 float columns, for the repacked pack (dflash2.inc): qs = int8 [rows][K], sc = half [rows][K / 32].
417// A threadgroup = 4 simdgroups x R rows each.  The columns' K chunk of 512 values sits in threadgroup memory; lane l reads 16 int8 of
418// every row of its simdgroup (one 16-byte load per row, a simdgroup covers 512 contiguous bytes of a row per step), converts them to
419// float four at a time, scales them with the block's d and takes the dot products with the NCOL columns.  Every weight byte is read
420// once; K must be a multiple of 512.
421constant int NCOL [[function_constant(0)]];
422
423struct MmArgs { uint K; uint rows; uint y_stride; uint x_stride; };
424
425template <int R, int SG>
426kernel void df2_mm(device const char* qs [[buffer(0)]], device const half* sc [[buffer(1)]], device const float* x [[buffer(2)]],
427                   device float* y [[buffer(3)]], constant MmArgs& a [[buffer(4)]], uint3 tg [[threadgroup_position_in_grid]],
428                   ushort tid [[thread_index_in_threadgroup]], ushort sgi [[simdgroup_index_in_threadgroup]],
429                   ushort lane [[thread_index_in_simdgroup]]) {
430    threadgroup float4 xs[8 * 128];   // [col][s * 32 + lane]: float4 number lane * 4 + s of the chunk (a conflict-free read for the lanes)
431    const uint row0 = (tg.x * SG + sgi) * R;
432    const uint nb = a.K / 32;
433    device const char* wr[R];
434    device const half* sr[R];
435    for (int r = 0; r < R; ++r) {
436        const uint row = min(row0 + uint(r), a.rows - 1);
437        wr[r] = qs + ulong(row) * a.K;
438        sr[r] = sc + ulong(row) * nb;
439    }
440    float acc[R][8];
441    for (int r = 0; r < R; ++r)
442        for (int c = 0; c < 8; ++c) acc[r][c] = 0.0f;
443    const uint kk = uint(lane) * 16;
444    uint4 raw[R];
445    float d[R];
446    for (int r = 0; r < R; ++r) {
447        raw[r] = *(device const uint4*)(wr[r] + kk);
448        d[r] = float(sr[r][kk / 32]);
449    }
450    for (uint k0 = 0; k0 < a.K; k0 += 512) {
451        // the next chunk's weights are in flight while this one is staged and used
452        uint4 rawn[R];
453        float dn[R];
454        const bool more = k0 + 512 < a.K;
455        if (more)
456            for (int r = 0; r < R; ++r) {
457                rawn[r] = *(device const uint4*)(wr[r] + k0 + 512 + kk);
458                dn[r] = float(sr[r][(k0 + 512 + kk) / 32]);
459            }
460        threadgroup_barrier(mem_flags::mem_threadgroup);
461        for (uint i = tid; i < uint(NCOL) * 128; i += SG * 32) {
462            const uint c = i / 128, j = i % 128;
463            xs[c * 128 + (j & 3) * 32 + (j >> 2)] = ((device const float4*)(x + ulong(c) * a.x_stride + k0))[j];
464        }
465        threadgroup_barrier(mem_flags::mem_threadgroup);
466        for (int sub = 0; sub < 4; ++sub) {
467            float4 xv[8];
468            for (int c = 0; c < NCOL; ++c) xv[c] = xs[c * 128 + sub * 32 + lane];
469            for (int r = 0; r < R; ++r) {
470                const uint word = sub == 0 ? raw[r].x : sub == 1 ? raw[r].y : sub == 2 ? raw[r].z : raw[r].w;
471                const float4 w = float4(as_type<char4>(word)) * d[r];
472                for (int c = 0; c < NCOL; ++c) acc[r][c] += dot(w, xv[c]);
473            }
474        }
475        if (more)
476            for (int r = 0; r < R; ++r) { raw[r] = rawn[r]; d[r] = dn[r]; }
477    }
478    for (int r = 0; r < R; ++r)
479        for (int c = 0; c < NCOL; ++c) {
480            const float v = simd_sum(acc[r][c]);
481            if (lane == 0 && row0 + uint(r) < a.rows) y[ulong(c) * a.y_stride + row0 + r] = v;
482        }
483}
484
485#define DF2MM(R, S) template [[host_name("df2_mm_" #R "_" #S)]] kernel decltype(df2_mm<R, S>) df2_mm<R, S>;
486DF2MM(1, 4) DF2MM(1, 8) DF2MM(1, 16) DF2MM(2, 4) DF2MM(2, 8) DF2MM(2, 16) DF2MM(4, 4) DF2MM(4, 8) DF2MM(4, 16) DF2MM(8, 4) DF2MM(8, 8)
487
488// ---- Q4_0 matrix x up to 8 float columns, for the pack repacked at load (DF2-METAL micro-bench): qs = uchar [rows][K / 32][16] (the 16 bytes of a
489// Q4_0 block, byte j = element j in the low nibble, element j + 16 in the high one), sc = half [rows][K / 32].  Same shape as df2_mm: a
490// threadgroup = SG simdgroups x R rows each; the columns' K chunk of 512 values sits in threadgroup memory; lane l reads 8 bytes (half a block:
491// block l / 2 of the chunk, bytes 8 * (l & 1) ..) of every row of its simdgroup, so the 32 lanes cover 16 blocks = 512 values per step.
492// K must be a multiple of 512.  The block's scale multiplies the dot product of its nibbles (minus 8) with the columns.
493struct Mm4Args { uint K; uint rows; uint y_stride; uint x_stride; };
494
495template <int R, int SG>
496kernel void df2_mm4(device const uchar* qs [[buffer(0)]], device const half* sc [[buffer(1)]], device const float* x [[buffer(2)]],
497                    device float* y [[buffer(3)]], constant Mm4Args& a [[buffer(4)]], uint3 tg [[threadgroup_position_in_grid]],
498                    ushort tid [[thread_index_in_threadgroup]], ushort sgi [[simdgroup_index_in_threadgroup]],
499                    ushort lane [[thread_index_in_simdgroup]]) {
500    threadgroup float4 xs[8 * 128];   // [col][128 float4 of the chunk]
501    const uint row0 = (tg.x * SG + sgi) * R;
502    const uint nb = a.K / 32;
503    const uint blk = uint(lane) >> 1, hh = uint(lane) & 1;
504    device const uchar* wr[R];
505    device const half* sr[R];
506    for (int r = 0; r < R; ++r) {
507        const uint row = min(row0 + uint(r), a.rows - 1);
508        wr[r] = qs + (ulong(row) * nb + blk) * 16 + hh * 8;
509        sr[r] = sc + ulong(row) * nb + blk;
510    }
511    float acc[R][8];
512    for (int r = 0; r < R; ++r)
513        for (int c = 0; c < 8; ++c) acc[r][c] = 0.0f;
514    uint2 raw[R];
515    float d[R];
516    for (int r = 0; r < R; ++r) { raw[r] = *(device const uint2*)(wr[r]); d[r] = float(sr[r][0]); }
517    for (uint k0 = 0; k0 < a.K; k0 += 512) {
518        uint2 rawn[R];
519        float dn[R];
520        const bool more = k0 + 512 < a.K;
521        if (more)
522            for (int r = 0; r < R; ++r) { rawn[r] = *(device const uint2*)(wr[r] + (k0 + 512) / 2); dn[r] = float(sr[r][(k0 + 512) / 32]); }
523        threadgroup_barrier(mem_flags::mem_threadgroup);
524        for (uint i = tid; i < uint(NCOL) * 128; i += SG * 32) {
525            const uint c = i / 128, j = i % 128;
526            xs[c * 128 + j] = ((device const float4*)(x + ulong(c) * a.x_stride + k0))[j];
527        }
528        threadgroup_barrier(mem_flags::mem_threadgroup);
529        // this lane's 16 elements: low nibbles = chunk positions blk * 32 + hh * 8 + 0..7, high nibbles = +16
530        float4 xl0[8], xl1[8], xh0[8], xh1[8];
531        const uint pl = (blk * 32 + hh * 8) / 4;
532        for (int c = 0; c < NCOL; ++c) {
533            xl0[c] = xs[c * 128 + pl]; xl1[c] = xs[c * 128 + pl + 1];
534            xh0[c] = xs[c * 128 + pl + 4]; xh1[c] = xs[c * 128 + pl + 5];
535        }
536        for (int r = 0; r < R; ++r) {
537            const uint w0 = raw[r].x, w1 = raw[r].y;
538            const float4 lo0 = float4(int4((w0 >> 0) & 15, (w0 >> 8) & 15, (w0 >> 16) & 15, (w0 >> 24) & 15)) - 8.0f;
539            const float4 lo1 = float4(int4((w1 >> 0) & 15, (w1 >> 8) & 15, (w1 >> 16) & 15, (w1 >> 24) & 15)) - 8.0f;
540            const float4 hi0 = float4(int4((w0 >> 4) & 15, (w0 >> 12) & 15, (w0 >> 20) & 15, (w0 >> 28) & 15)) - 8.0f;
541            const float4 hi1 = float4(int4((w1 >> 4) & 15, (w1 >> 12) & 15, (w1 >> 20) & 15, (w1 >> 28) & 15)) - 8.0f;
542            for (int c = 0; c < NCOL; ++c)
543                acc[r][c] = fma(d[r], dot(lo0, xl0[c]) + dot(lo1, xl1[c]) + dot(hi0, xh0[c]) + dot(hi1, xh1[c]), acc[r][c]);
544        }
545        if (more)
546            for (int r = 0; r < R; ++r) { raw[r] = rawn[r]; d[r] = dn[r]; }
547    }
548    for (int r = 0; r < R; ++r)
549        for (int c = 0; c < NCOL; ++c) {
550            const float v = simd_sum(acc[r][c]);
551            if (lane == 0 && row0 + uint(r) < a.rows) y[ulong(c) * a.y_stride + row0 + r] = v;
552        }
553}
554
555#define DF2MM4(R, S) template [[host_name("df2_mm4_" #R "_" #S)]] kernel decltype(df2_mm4<R, S>) df2_mm4<R, S>;
556DF2MM4(1, 4) DF2MM4(1, 8) DF2MM4(2, 4) DF2MM4(2, 8) DF2MM4(2, 16) DF2MM4(4, 4) DF2MM4(4, 8) DF2MM4(4, 16) DF2MM4(8, 4) DF2MM4(8, 8)
557
558// ---- Q4_0 matrix x 8 float columns on the simdgroup matrix units (df2_mma4).  The pack is repacked at load into FRAGMENT ORDER: for a tile of 8 rows
559// and one Q4_0 block (32 values) the 32 lanes read 32 consecutive uint32; lane l holds the eight 4-bit codes of the weights W[row fm(l)][8 s + fn(l) + e]
560// for s = 0..3 (the four k steps of the block) and e = 0..1 (the two columns of its fragment), code number 2 s + e at bits 4 (2 s + e).  fm / fn are the
561// fragment coordinates of simdgroup_matrix 8x8 (row fm, columns fn and fn + 1 of lane l).  The scales: half [row tile][block][8 rows].
562// y[t][row] = sum over blocks of d(row, block) * sum_k (code - 8) * x[t][k], the integer part on the matrix units in half operands with float
563// accumulation (codes - 8 are exact in half; the activations are rounded to half).
564struct MmaQArgs { uint K; uint rows; uint y_stride; uint x_stride; };
565
566template <int RT, int SG>
567kernel void df2_mma4(device const uint* qw [[buffer(0)]], device const half* sc [[buffer(1)]], device const half* xh [[buffer(2)]],
568                     device float* y [[buffer(3)]], constant MmaQArgs& a [[buffer(4)]], uint3 tg [[threadgroup_position_in_grid]],
569                     ushort sgi [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
570    const uint nb = a.K / 32;
571    const uint nrt_total = (a.rows + 7) / 8;
572    const uint rt0 = (tg.x * SG + sgi) * RT;
573    if (rt0 >= nrt_total) return;
574    const uint qid = uint(lane) >> 2;
575    const uint fm = (qid & 4) + ((uint(lane) >> 1) & 3);
576    const uint fn = (qid & 2) * 2 + (uint(lane) & 1) * 2;
577    float acc0[RT], acc1[RT];
578    for (int r = 0; r < RT; ++r) { acc0[r] = 0.0f; acc1[r] = 0.0f; }
579    device const uint* wp[RT];
580    device const half* sp[RT];
581    for (int r = 0; r < RT; ++r) {
582        const uint rt = min(rt0 + uint(r), nrt_total - 1);
583        wp[r] = qw + (ulong(rt) * nb) * 32 + lane;
584        sp[r] = sc + (ulong(rt) * nb) * 8 + fm;
585    }
586    uint wcur[RT]; half dcur[RT];
587    for (int r = 0; r < RT; ++r) { wcur[r] = wp[r][0]; dcur[r] = sp[r][0]; }
588    for (uint b = 0; b < nb; ++b) {
589        uint wn[RT]; half dn[RT];
590        const bool more = b + 1 < nb;
591        if (more)
592            for (int r = 0; r < RT; ++r) { wn[r] = wp[r][(b + 1) * 32]; dn[r] = sp[r][(b + 1) * 8]; }
593        simdgroup_half8x8 B0, B1, B2, B3;
594        simdgroup_load(B0, xh + b * 32 + 0, a.x_stride, ulong2(0, 0), true);
595        simdgroup_load(B1, xh + b * 32 + 8, a.x_stride, ulong2(0, 0), true);
596        simdgroup_load(B2, xh + b * 32 + 16, a.x_stride, ulong2(0, 0), true);
597        simdgroup_load(B3, xh + b * 32 + 24, a.x_stride, ulong2(0, 0), true);
598        for (int r = 0; r < RT; ++r) {
599            const uint w = wcur[r];
600            simdgroup_half8x8 A0, A1, A2, A3;
601            A0.thread_elements()[0] = half(int((w >> 0) & 15) - 8);  A0.thread_elements()[1] = half(int((w >> 4) & 15) - 8);
602            A1.thread_elements()[0] = half(int((w >> 8) & 15) - 8);  A1.thread_elements()[1] = half(int((w >> 12) & 15) - 8);
603            A2.thread_elements()[0] = half(int((w >> 16) & 15) - 8); A2.thread_elements()[1] = half(int((w >> 20) & 15) - 8);
604            A3.thread_elements()[0] = half(int((w >> 24) & 15) - 8); A3.thread_elements()[1] = half(int((w >> 28) & 15) - 8);
605            simdgroup_float8x8 C = make_filled_simdgroup_matrix<float, 8, 8>(0.0f);
606            simdgroup_multiply_accumulate(C, A0, B0, C);
607            simdgroup_multiply_accumulate(C, A1, B1, C);
608            simdgroup_multiply_accumulate(C, A2, B2, C);
609            simdgroup_multiply_accumulate(C, A3, B3, C);
610            const float d = float(dcur[r]);
611            acc0[r] = fma(d, C.thread_elements()[0], acc0[r]);
612            acc1[r] = fma(d, C.thread_elements()[1], acc1[r]);
613        }
614        if (more)
615            for (int r = 0; r < RT; ++r) { wcur[r] = wn[r]; dcur[r] = dn[r]; }
616    }
617    for (int r = 0; r < RT; ++r) {
618        const uint row = (rt0 + uint(r)) * 8 + fm;
619        if (rt0 + uint(r) < nrt_total && row < a.rows) {
620            y[ulong(fn) * a.y_stride + row] = acc0[r];
621            y[ulong(fn + 1) * a.y_stride + row] = acc1[r];
622        }
623    }
624}
625
626#define DF2MMA4(R, S) template [[host_name("df2_mma4_" #R "_" #S)]] kernel decltype(df2_mma4<R, S>) df2_mma4<R, S>;
627DF2MMA4(1, 2) DF2MMA4(1, 4) DF2MMA4(1, 8) DF2MMA4(2, 2) DF2MMA4(2, 4) DF2MMA4(4, 2) DF2MMA4(4, 4)
628
629kernel void df2_f16(device const float* x [[buffer(0)]], device half* y [[buffer(1)]], constant uint& n [[buffer(2)]], uint i [[thread_position_in_grid]]) {
630    if (i < n) y[i] = half(x[i]);
631}
632
633// split-K variant of df2_mma4: the SG simdgroups of a threadgroup work on the SAME RT row tiles, each on its own range of blocks (the weights stream in
634// parallel from SG places, so a small matrix still fills the GPU), then add their partial sums through threadgroup memory.  Block loop unrolled by 2.
635template <int RT, int SG>
636kernel void df2_mma4s(device const uint* qw [[buffer(0)]], device const half* sc [[buffer(1)]], device const half* xh [[buffer(2)]],
637                      device float* y [[buffer(3)]], constant MmaQArgs& a [[buffer(4)]], uint3 tg [[threadgroup_position_in_grid]],
638                      ushort sgi [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
639    threadgroup float part[SG][RT][2][32];
640    const uint nb = a.K / 32;
641    const uint nrt_total = (a.rows + 7) / 8;
642    const uint rt0 = tg.x * RT;
643    const uint qid = uint(lane) >> 2;
644    const uint fm = (qid & 4) + ((uint(lane) >> 1) & 3);
645    const uint fn = (qid & 2) * 2 + (uint(lane) & 1) * 2;
646    const uint b0 = nb * uint(sgi) / SG, b1 = nb * (uint(sgi) + 1) / SG;
647    float acc0[RT], acc1[RT];
648    for (int r = 0; r < RT; ++r) { acc0[r] = 0.0f; acc1[r] = 0.0f; }
649    device const uint* wp[RT];
650    device const half* sp[RT];
651    for (int r = 0; r < RT; ++r) {
652        const uint rt = min(rt0 + uint(r), nrt_total - 1);
653        wp[r] = qw + (ulong(rt) * nb) * 32 + lane;
654        sp[r] = sc + (ulong(rt) * nb) * 8 + fm;
655    }
656    for (uint b = b0; b < b1; b += 2) {
657        const bool two = b + 1 < b1;
658        uint w0[RT], w1[RT]; half d0[RT], d1[RT];
659        for (int r = 0; r < RT; ++r) {
660            w0[r] = wp[r][b * 32]; d0[r] = sp[r][b * 8];
661            w1[r] = two ? wp[r][(b + 1) * 32] : 0u; d1[r] = two ? sp[r][(b + 1) * 8] : half(0);
662        }
663        for (int h = 0; h < (two ? 2 : 1); ++h) {
664            const uint bb = b + uint(h);
665            simdgroup_half8x8 B0, B1, B2, B3;
666            simdgroup_load(B0, xh + bb * 32 + 0, a.x_stride, ulong2(0, 0), true);
667            simdgroup_load(B1, xh + bb * 32 + 8, a.x_stride, ulong2(0, 0), true);
668            simdgroup_load(B2, xh + bb * 32 + 16, a.x_stride, ulong2(0, 0), true);
669            simdgroup_load(B3, xh + bb * 32 + 24, a.x_stride, ulong2(0, 0), true);
670            for (int r = 0; r < RT; ++r) {
671                const uint w = h == 0 ? w0[r] : w1[r];
672                simdgroup_half8x8 A0, A1, A2, A3;
673                A0.thread_elements()[0] = half(int((w >> 0) & 15) - 8);  A0.thread_elements()[1] = half(int((w >> 4) & 15) - 8);
674                A1.thread_elements()[0] = half(int((w >> 8) & 15) - 8);  A1.thread_elements()[1] = half(int((w >> 12) & 15) - 8);
675                A2.thread_elements()[0] = half(int((w >> 16) & 15) - 8); A2.thread_elements()[1] = half(int((w >> 20) & 15) - 8);
676                A3.thread_elements()[0] = half(int((w >> 24) & 15) - 8); A3.thread_elements()[1] = half(int((w >> 28) & 15) - 8);
677                simdgroup_float8x8 C = make_filled_simdgroup_matrix<float, 8, 8>(0.0f);
678                simdgroup_multiply_accumulate(C, A0, B0, C);
679                simdgroup_multiply_accumulate(C, A1, B1, C);
680                simdgroup_multiply_accumulate(C, A2, B2, C);
681                simdgroup_multiply_accumulate(C, A3, B3, C);
682                const float d = float(h == 0 ? d0[r] : d1[r]);
683                acc0[r] = fma(d, C.thread_elements()[0], acc0[r]);
684                acc1[r] = fma(d, C.thread_elements()[1], acc1[r]);
685            }
686        }
687    }
688    for (int r = 0; r < RT; ++r) { part[sgi][r][0][lane] = acc0[r]; part[sgi][r][1][lane] = acc1[r]; }
689    threadgroup_barrier(mem_flags::mem_threadgroup);
690    if (sgi == 0) {
691        for (int r = 0; r < RT; ++r) {
692            float t0 = 0.0f, t1 = 0.0f;
693            for (int g = 0; g < SG; ++g) { t0 += part[g][r][0][lane]; t1 += part[g][r][1][lane]; }
694            const uint row = (rt0 + uint(r)) * 8 + fm;
695            if (rt0 + uint(r) < nrt_total && row < a.rows) {
696                y[ulong(fn) * a.y_stride + row] = t0;
697                y[ulong(fn + 1) * a.y_stride + row] = t1;
698            }
699        }
700    }
701}
702#define DF2MMA4S(R, S) template [[host_name("df2_mma4s_" #R "_" #S)]] kernel decltype(df2_mma4s<R, S>) df2_mma4s<R, S>;
703DF2MMA4S(1, 2) DF2MMA4S(1, 4) DF2MMA4S(1, 8) DF2MMA4S(2, 4) DF2MMA4S(2, 8)
704
705// ---- Q8_0 rows on the matrix units for the draft head: the same fragment order, eight int8 per lane per block as two uint32 (word 0: k steps 0 and 1, word 1: 2 and 3).
706template <int RT, int SG>
707kernel void df2_mma8(device const uint2* qw [[buffer(0)]], device const half* sc [[buffer(1)]], device const half* xh [[buffer(2)]],
708                     device float* y [[buffer(3)]], constant MmaQArgs& a [[buffer(4)]], uint3 tg [[threadgroup_position_in_grid]],
709                     ushort sgi [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
710    const uint nb = a.K / 32;
711    const uint nrt_total = (a.rows + 7) / 8;
712    const uint rt0 = (tg.x * SG + sgi) * RT;
713    if (rt0 >= nrt_total) return;
714    const uint qid = uint(lane) >> 2;
715    const uint fm = (qid & 4) + ((uint(lane) >> 1) & 3);
716    const uint fn = (qid & 2) * 2 + (uint(lane) & 1) * 2;
717    float acc0[RT], acc1[RT];
718    for (int r = 0; r < RT; ++r) { acc0[r] = 0.0f; acc1[r] = 0.0f; }
719    device const uint2* wp[RT];
720    device const half* sp[RT];
721    for (int r = 0; r < RT; ++r) {
722        const uint rt = min(rt0 + uint(r), nrt_total - 1);
723        wp[r] = qw + (ulong(rt) * nb) * 32 + lane;
724        sp[r] = sc + (ulong(rt) * nb) * 8 + fm;
725    }
726    uint2 wcur[RT]; half dcur[RT];
727    for (int r = 0; r < RT; ++r) { wcur[r] = wp[r][0]; dcur[r] = sp[r][0]; }
728    for (uint b = 0; b < nb; ++b) {
729        uint2 wn[RT]; half dn[RT];
730        const bool more = b + 1 < nb;
731        if (more)
732            for (int r = 0; r < RT; ++r) { wn[r] = wp[r][(b + 1) * 32]; dn[r] = sp[r][(b + 1) * 8]; }
733        simdgroup_half8x8 B0, B1, B2, B3;
734        simdgroup_load(B0, xh + b * 32 + 0, a.x_stride, ulong2(0, 0), true);
735        simdgroup_load(B1, xh + b * 32 + 8, a.x_stride, ulong2(0, 0), true);
736        simdgroup_load(B2, xh + b * 32 + 16, a.x_stride, ulong2(0, 0), true);
737        simdgroup_load(B3, xh + b * 32 + 24, a.x_stride, ulong2(0, 0), true);
738        for (int r = 0; r < RT; ++r) {
739            const char4 c0 = as_type<char4>(wcur[r].x), c1 = as_type<char4>(wcur[r].y);
740            simdgroup_half8x8 A0, A1, A2, A3;
741            A0.thread_elements()[0] = half(c0.x); A0.thread_elements()[1] = half(c0.y);
742            A1.thread_elements()[0] = half(c0.z); A1.thread_elements()[1] = half(c0.w);
743            A2.thread_elements()[0] = half(c1.x); A2.thread_elements()[1] = half(c1.y);
744            A3.thread_elements()[0] = half(c1.z); A3.thread_elements()[1] = half(c1.w);
745            simdgroup_float8x8 C = make_filled_simdgroup_matrix<float, 8, 8>(0.0f);
746            simdgroup_multiply_accumulate(C, A0, B0, C);
747            simdgroup_multiply_accumulate(C, A1, B1, C);
748            simdgroup_multiply_accumulate(C, A2, B2, C);
749            simdgroup_multiply_accumulate(C, A3, B3, C);
750            const float d = float(dcur[r]);
751            acc0[r] = fma(d, C.thread_elements()[0], acc0[r]);
752            acc1[r] = fma(d, C.thread_elements()[1], acc1[r]);
753        }
754        if (more)
755            for (int r = 0; r < RT; ++r) { wcur[r] = wn[r]; dcur[r] = dn[r]; }
756    }
757    for (int r = 0; r < RT; ++r) {
758        const uint row = (rt0 + uint(r)) * 8 + fm;
759        if (rt0 + uint(r) < nrt_total && row < a.rows) {
760            y[ulong(fn) * a.y_stride + row] = acc0[r];
761            y[ulong(fn + 1) * a.y_stride + row] = acc1[r];
762        }
763    }
764}
765#define DF2MMA8(R, S) template [[host_name("df2_mma8_" #R "_" #S)]] kernel decltype(df2_mma8<R, S>) df2_mma8<R, S>;
766DF2MMA8(1, 4) DF2MMA8(1, 8) DF2MMA8(2, 4) DF2MMA8(2, 8) DF2MMA8(4, 4)
767
768// ---- the same kernels with a second output: the result also rounded to half, the matrix-unit GEMMs' activation operand (replaces the df2_f16 dispatch
769// before each GEMM; the half value is exactly what df2_f16 made from the stored float)
770kernel void df2_rms_h(device const float* x [[buffer(0)]], device const float* w [[buffer(1)]], device float* y [[buffer(2)]],
771                      constant RmsArgs& a [[buffer(3)]], device half* yh [[buffer(4)]], uint3 tg [[threadgroup_position_in_grid]],
772                      ushort tid [[thread_index_in_threadgroup]], ushort sg [[simdgroup_index_in_threadgroup]],
773                      ushort lane [[thread_index_in_simdgroup]]) {
774    threadgroup float part[8];
775    device const float* xr = x + tg.x * a.n;
776    float ss = 0.0f;
777    for (uint d = tid; d < a.n; d += 256) ss = fma(xr[d], xr[d], ss);
778    ss = simd_sum(ss);
779    if (lane == 0) part[sg] = ss;
780    threadgroup_barrier(mem_flags::mem_threadgroup);
781    float tot = 0.0f;
782    for (int i = 0; i < 8; ++i) tot += part[i];
783    const float rs = rsqrt(tot / float(a.n) + a.eps);
784    device float* yr = y + tg.x * a.n;
785    device half* yhr = yh + tg.x * a.n;
786    for (uint d = tid; d < a.n; d += 256) { const float v = xr[d] * rs * w[d]; yr[d] = v; yhr[d] = half(v); }
787}
788
789kernel void df2_conv_h(device const float* x [[buffer(0)]], device const float* dyn [[buffer(1)]], device const float* base [[buffer(2)]],
790                       device const float* resid [[buffer(3)]], device float* out [[buffer(4)]], constant ConvArgs& a [[buffer(5)]],
791                       device half* outh [[buffer(6)]], uint i [[thread_position_in_grid]]) {
792    if (i >= a.rows * a.H) return;
793    const uint b = i / a.H, c = i % a.H;
794    const uint groups = a.H / a.group;
795    float acc = 0.0f;
796    for (uint o = 0; o < 2; ++o) {
797        if (b < o) continue;
798        const float k = base[o * a.H + c] + dyn[b * a.dyn_stride + o * groups + c / a.group];
799        acc = fma(k, x[(b - o) * a.H + c], acc);
800    }
801    const float v = a.has_resid ? resid[i] + acc : acc;
802    out[i] = v;
803    outh[i] = half(v);
804}
805
806kernel void df2_swiglu_h(device const float* g [[buffer(0)]], device const float* u [[buffer(1)]], device float* y [[buffer(2)]],
807                         constant SwArgs& a [[buffer(3)]], device half* yh [[buffer(4)]], uint i [[thread_position_in_grid]]) {
808    if (i >= a.n) return;
809    const float gv = g[i];
810    const float v = gv / (1.0f + exp(-gv)) * u[i];
811    y[i] = v;
812    yh[i] = half(v);
813}
814
815kernel void df2_attn_merge_h(device const float* part [[buffer(0)]], device const int* anchor_pos [[buffer(1)]], device float* out [[buffer(2)]],
816                             constant AttnArgs& a [[buffer(3)]], device half* outh [[buffer(4)]], uint3 tg [[threadgroup_position_in_grid]],
817                             ushort d [[thread_index_in_threadgroup]]) {
818    const uint kvh = tg.x >> 5, qi = tg.x & 31;
819    const int s = *anchor_pos;
820    const int lo = max(max(0, s - (int(a.window) - 1)), anchor_pos[1]);
821    const int nchunks = ((s - lo) + AROWS + AK - 1) / AK;
822    float M = -INFINITY;
823    for (int c = 0; c < nchunks; ++c) M = max(M, part[(((uint(c) * 8 + kvh) * 32) + qi) * 130]);
824    float L = 0.0f, o = 0.0f;
825    for (int c = 0; c < nchunks; ++c) {
826        device const float* p = part + (((uint(c) * 8 + kvh) * 32) + qi) * 130;
827        const float mc = p[0];
828        const float w = mc == -INFINITY ? 0.0f : exp(mc - M);
829        L += p[1] * w;
830        o = fma(p[2 + d], w, o);
831    }
832    const uint row = qi >> 2, g = qi & 3;
833    const float v = L > 0.0f ? o / L : 0.0f;
834    out[(row * 32 + kvh * 4 + g) * HD + d] = v;
835    outh[(row * 32 + kvh * 4 + g) * HD + d] = half(v);
836}
837
838// ---- the row log (lineage rebuild): the half-rounded hidden_norm rows of the context update, kept per position, are the exact operand of every layer's
839// k/v projection; a restored conversation's ring is rebuilt from them (same kernels, same bytes).
840kernel void df2_log_rows(device const half* in [[buffer(0)]], device half* log [[buffer(1)]], device const int* pos [[buffer(2)]],
841                         constant CopyArgs& a [[buffer(3)]], uint i [[thread_position_in_grid]]) {
842    if (i >= a.rows * a.cols) return;
843    const uint r = i / a.cols, c = i % a.cols;
844    log[(uint(pos[r]) % a.slot_mod) * a.cols + c] = in[i];
845}
846
847kernel void df2_gather_rows(device const half* log [[buffer(0)]], device half* out [[buffer(1)]], device const int* pos [[buffer(2)]],
848                            constant CopyArgs& a [[buffer(3)]], uint i [[thread_position_in_grid]]) {
849    if (i >= a.rows * a.cols) return;
850    const uint r = i / a.cols, c = i % a.cols;
851    out[i] = log[(uint(pos[r]) % a.slot_mod) * a.cols + c];
852}