okami.mom/strata

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

Niko1221Merge f-q4-kquant (d19ab7302): Metal and SYCL take Q5_K/Q6_K (Metal also Q3_K/Q4_K/IQ4_XS/IQ3_S) down experts for UD files at expert widths 512/1024; additive, today's sets unchanged (Qwen4 prep)99807e8da

main
82.4 KiB1436 linesraw
1// metal/kernels/moe_mm.metal - routed experts for a PROMPT chunk (after quant/units/mma.metal): a grouped GEMM on
2// the matrix units through Metal 4's MetalPerformancePrimitives matmul2d (on the M5 its neural accelerators).
3//
4// Plan (deterministic, three passes):  the chunk's T x topk (token, expert) entries are sorted by expert, then by
5// entry index; each expert's run is padded to a multiple of TM rows; tile i = (expert, first padded row).
6//   mm_hist   per block of 1024 entries: a histogram of experts      -> bcnt[block][expert]
7//   mm_scan   one threadgroup (thread = expert): block offsets, the padded expert offsets, the tile list
8//   mm_place  per block: an entry's padded row = expert offset + earlier blocks' count + rank in its block;
9//             srt_tok[row] = token (-1 on padding), srt_w[row] = weight, pos[entry] = row
10// GEMMs: a threadgroup takes a tile (TM rows of one expert) and TN output rows; per K chunk of TK it converts the
11// tile's activations to fp16 and dequantizes TN x TK weights (ref_quant's arithmetic, then rounded to fp16) into
12// threadgroup memory, and matmul2d multiplies them, fp32 accumulation.
13//   mm_gu     H[row][f] = silu(x . gate_f) * (x . up_f), fp32, for the n_ff rows
14//   mm_down   YE[row][d] = h . down_d, fp32
15//   mm_combine y[t][d] = sum_k w(t, k) * YE[pos(t, k)][d], k in order
16//
17// The idea of feeding matmul2d tiles of dequantized weights from threadgroup memory follows yibie/strata-mlx's
18// tile_matmul (MIT); the code is our own.
19#include <MetalPerformancePrimitives/MetalPerformancePrimitives.h>
20using namespace mpp::tensor_ops;
21
22struct MmPlanArgs {
23    uint n_ent;      // T * topk
24    uint topk;
25    uint n_expert;
26    uint tm;         // the tile height (rows of one expert)
27    uint n_blocks;   // ceil(n_ent / 1024)
28};
29
30// counts per block: bcnt[block * n_expert + e]
31kernel void mm_hist(device const int* ids [[buffer(0)]], device uint* bcnt [[buffer(1)]],
32                    constant MmPlanArgs& a [[buffer(2)]],
33                    uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]]) {
34    threadgroup atomic_uint h[1024];
35    for (uint e = tid; e < a.n_expert; e += 1024) atomic_store_explicit(&h[e], 0u, memory_order_relaxed);
36    threadgroup_barrier(mem_flags::mem_threadgroup);
37    const uint i = tg.x * 1024 + tid;
38    if (i < a.n_ent) atomic_fetch_add_explicit(&h[ids[i]], 1u, memory_order_relaxed);
39    threadgroup_barrier(mem_flags::mem_threadgroup);
40    for (uint e = tid; e < a.n_expert; e += 1024)
41        bcnt[tg.x * a.n_expert + e] = atomic_load_explicit(&h[e], memory_order_relaxed);
42}
43
44// one threadgroup of n_expert (<= 1024) threads.  boff[block][e] = expert e's rows before this block (within e);
45// eoff[e] = expert e's first padded row; tiles[i] = (expert, row0); meta[0] = n_tiles, meta[1] = padded rows;
46// indirect grids: meta[2..4] = (gx_gu, n_tiles, 1) for the gate/up GEMM, meta[5..7] = (gx_down, n_tiles, 1) for the
47// down GEMM (gx_gu in meta[2], gx_down in meta[5] written by the host once), meta[8..10] = (rows, 1, 1) for mm_gather.
48kernel void mm_scan(device const uint* bcnt [[buffer(0)]], device uint* boff [[buffer(1)]],
49                    device uint* eoff [[buffer(2)]], device int2* tiles [[buffer(3)]], device uint* meta [[buffer(4)]],
50                    constant MmPlanArgs& a [[buffer(5)]],
51                    ushort tid [[thread_index_in_threadgroup]], ushort sg [[simdgroup_index_in_threadgroup]],
52                    ushort lane [[thread_index_in_simdgroup]]) {
53    threadgroup uint s_rows[32], s_tiles[32];
54    // simdgroups past the launched ones must count 0 (512 threads fill only 16 of the 32 slots)
55    if (tid < 32) { s_rows[tid] = 0; s_tiles[tid] = 0; }
56    threadgroup_barrier(mem_flags::mem_threadgroup);
57    const uint e = tid;
58    uint tot = 0;
59    if (e < a.n_expert)
60        for (uint b = 0; b < a.n_blocks; ++b) {
61            boff[b * a.n_expert + e] = tot;
62            tot += bcnt[b * a.n_expert + e];
63        }
64    const uint nt = (tot + a.tm - 1) / a.tm, rows = nt * a.tm;
65    const uint pr = simd_prefix_exclusive_sum(rows), pt = simd_prefix_exclusive_sum(nt);
66    if (lane == 31) { s_rows[sg] = pr + rows; s_tiles[sg] = pt + nt; }
67    threadgroup_barrier(mem_flags::mem_threadgroup);
68    uint orow = 0, otile = 0, all_rows = 0, all_tiles = 0;
69    for (int i = 0; i < 32; ++i) {
70        if (i < int(sg)) { orow += s_rows[i]; otile += s_tiles[i]; }
71        all_rows += s_rows[i];
72        all_tiles += s_tiles[i];
73    }
74    if (e < a.n_expert) {
75        const uint r0 = orow + pr, t0 = otile + pt;
76        eoff[e] = r0;
77        for (uint k = 0; k < nt; ++k) tiles[t0 + k] = int2(int(e), int(r0 + k * a.tm));
78    }
79    if (tid == 0) {
80        meta[0] = all_tiles;
81        meta[1] = all_rows;
82        meta[3] = all_tiles;   // indirect grid of the gate/up GEMM: (meta[2] given, tiles, 1)
83        meta[4] = 1;
84        meta[6] = all_tiles;   // of the down GEMM: (meta[5] given, tiles, 1)
85        meta[7] = 1;
86        meta[8] = all_rows;    // of the gather: (rows, 1, 1)
87        meta[9] = 1;
88        meta[10] = 1;
89    }
90}
91
92// grid (n_blocks), 1024 threads.  srt_* must be cleared to the padding value (-1 / 0) beforehand by mm_clear.
93kernel void mm_place(device const int* ids [[buffer(0)]], device const float* w [[buffer(1)]],
94                     device const uint* boff [[buffer(2)]], device const uint* eoff [[buffer(3)]],
95                     device int* srt_tok [[buffer(4)]], device float* srt_w [[buffer(5)]], device int* pos [[buffer(6)]],
96                     constant MmPlanArgs& a [[buffer(7)]],
97                     uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]]) {
98    threadgroup int s_id[1024];
99    const uint i = tg.x * 1024 + tid;
100    const int e = i < a.n_ent ? ids[i] : -1;
101    s_id[tid] = e;
102    threadgroup_barrier(mem_flags::mem_threadgroup);
103    if (i >= a.n_ent) return;
104    uint rank = 0;
105    for (uint j = 0; j < tid; ++j) rank += s_id[j] == e;
106    const uint row = eoff[e] + boff[tg.x * a.n_expert + e] + rank;
107    srt_tok[row] = int(i / a.topk);
108    srt_w[row] = w[i];
109    pos[i] = int(row);
110}
111
112kernel void mm_clear(device int* srt_tok [[buffer(0)]], constant uint& n [[buffer(1)]], uint gid [[thread_position_in_grid]]) {
113    if (gid < n) srt_tok[gid] = -1;
114}
115
116// ---- the GEMMs -----------------------------------------------------------------------------------------------------
117// weights of one expert: gate at W + gate_off + e * gu_stride (+ up_off for up), down at W + down_off + e * d_stride
118struct MmArgs {
119    ulong gate_off;
120    ulong up_off;
121    ulong down_off;
122    ulong gu_stride;
123    ulong d_stride;
124    uint gu_row;     // bytes per gate/up row (n_embd values)
125    uint d_row;      // bytes per down row (n_ff values)
126    uint n_embd;
127    uint n_ff;
128};
129
130// TN x TK weights of `nrow`-strided rows into threadgroup half: thread-strided units of the format
131template <int F, int TN, int TK>
132static inline void stage_w(device const uchar* w0, uint row_bytes, int k0, threadgroup half* dst,
133                           threadgroup const uint* tab, ushort tid, ushort nth) {
134    constexpr int UNIT = fmt<F>::UNIT, UPC = TK / UNIT, H = UNIT / 2;
135    static_assert(TK % UNIT == 0, "the K chunk must hold whole units of the format");
136    for (int it = tid; it < TN * UPC; it += nth) {
137        const int r = it / UPC, uu = it - r * UPC;
138        float wv[UNIT];
139        int p0, p1;
140        DW<F>::run(w0 + ulong(r) * row_bytes, k0 / UNIT + uu, k0, wv, p0, p1, tab);
141        for (int j = 0; j < H; ++j) {
142            dst[r * TK + p0 + j] = half(wv[j]);
143            dst[r * TK + p1 + j] = half(wv[H + j]);
144        }
145    }
146}
147
148template <int F, int TM, int TN, int TK, int SG>
149kernel void mm_gu(device const uchar* W [[buffer(0)]], device const float* x [[buffer(1)]],
150                  device float* H [[buffer(2)]], device const int* srt_tok [[buffer(3)]],
151                  device const int2* tiles [[buffer(4)]], constant MmArgs& a [[buffer(5)]],
152                  uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]]) {
153    constexpr int NTH = SG * 32;
154    threadgroup half xa[TM * TK];
155    threadgroup half wg[TN * TK];
156    threadgroup half wu[TN * TK];
157    threadgroup uint tab[fmt<F>::TAB];
158    threadgroup int tok[TM];
159    load_tab<F>(tab, tid, NTH);
160    const int2 tl = tiles[tg.y];
161    const int e = tl.x, row0 = tl.y, f0 = int(tg.x) * TN;
162    for (int m = tid; m < TM; m += NTH) tok[m] = srt_tok[row0 + m];
163    device const uchar* g0 = W + a.gate_off + ulong(e) * a.gu_stride + ulong(f0) * a.gu_row;
164    device const uchar* u0 = W + a.up_off + ulong(e) * a.gu_stride + ulong(f0) * a.gu_row;
165    constexpr auto desc = matmul2d_descriptor(TM, TN, TK, false, true, false);
166    matmul2d<desc, execution_simdgroups<SG>> op;
167    tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline> tA(xa, dextents<int32_t, 2>(TK, TM));
168    tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline> tG(wg, dextents<int32_t, 2>(TK, TN));
169    tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline> tU(wu, dextents<int32_t, 2>(TK, TN));
170    auto accg = op.template get_destination_cooperative_tensor<decltype(tA), decltype(tG), float>();
171    auto accu = op.template get_destination_cooperative_tensor<decltype(tA), decltype(tG), float>();
172    for (uint16_t i = 0; i < accg.get_capacity(); ++i)
173        if (accg.is_valid_element(i)) { accg[i] = 0.0f; accu[i] = 0.0f; }
174    threadgroup_barrier(mem_flags::mem_threadgroup);
175    for (int k0 = 0; k0 < int(a.n_embd); k0 += TK) {
176        for (int it = tid; it < TM * TK; it += NTH) {
177            const int m = it / TK, k = it - m * TK;
178            xa[it] = tok[m] >= 0 ? half(x[ulong(tok[m]) * a.n_embd + k0 + k]) : half(0.0f);
179        }
180        stage_w<F, TN, TK>(g0, a.gu_row, k0, wg, tab, tid, NTH);
181        stage_w<F, TN, TK>(u0, a.gu_row, k0, wu, tab, tid, NTH);
182        threadgroup_barrier(mem_flags::mem_threadgroup);
183        auto pg = op.template get_destination_cooperative_tensor<decltype(tA), decltype(tG), float>();
184        auto pu = op.template get_destination_cooperative_tensor<decltype(tA), decltype(tG), float>();
185        op.run(tA, tG, pg);
186        op.run(tA, tU, pu);
187        for (uint16_t i = 0; i < pg.get_capacity(); ++i)
188            if (pg.is_valid_element(i)) { accg[i] += pg[i]; accu[i] += pu[i]; }
189        threadgroup_barrier(mem_flags::mem_threadgroup);
190    }
191    for (uint16_t i = 0; i < accg.get_capacity(); ++i)
192        if (accg.is_valid_element(i)) {
193            const float g = accg[i];
194            accg[i] = g / (1.0f + exp(-g)) * accu[i];
195        }
196    tensor<device float, dextents<int32_t, 2>, tensor_inline> tH(H, dextents<int32_t, 2>(a.n_ff, 1 << 30));
197    accg.store(tH.slice(f0, row0));
198}
199
200template <int F, int TM, int TN, int TK, int SG>
201kernel void mm_down(device const uchar* W [[buffer(0)]], device const float* H [[buffer(1)]],
202                    device float* YE [[buffer(2)]], device const int2* tiles [[buffer(3)]],
203                    constant MmArgs& a [[buffer(4)]],
204                    uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]]) {
205    constexpr int NTH = SG * 32;
206    threadgroup half ha[TM * TK];
207    threadgroup half wd[TN * TK];
208    threadgroup uint tab[fmt<F>::TAB];
209    load_tab<F>(tab, tid, NTH);
210    const int2 tl = tiles[tg.y];
211    const int e = tl.x, row0 = tl.y, d0 = int(tg.x) * TN;
212    device const uchar* w0 = W + a.down_off + ulong(e) * a.d_stride + ulong(d0) * a.d_row;
213    constexpr auto desc = matmul2d_descriptor(TM, TN, TK, false, true, false);
214    matmul2d<desc, execution_simdgroups<SG>> op;
215    tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline> tA(ha, dextents<int32_t, 2>(TK, TM));
216    tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline> tW(wd, dextents<int32_t, 2>(TK, TN));
217    auto acc = op.template get_destination_cooperative_tensor<decltype(tA), decltype(tW), float>();
218    for (uint16_t i = 0; i < acc.get_capacity(); ++i)
219        if (acc.is_valid_element(i)) acc[i] = 0.0f;
220    threadgroup_barrier(mem_flags::mem_threadgroup);
221    for (int k0 = 0; k0 < int(a.n_ff); k0 += TK) {
222        for (int it = tid; it < TM * TK; it += NTH) {
223            const int m = it / TK, k = it - m * TK;
224            ha[it] = half(H[ulong(row0 + m) * a.n_ff + k0 + k]);
225        }
226        stage_w<F, TN, TK>(w0, a.d_row, k0, wd, tab, tid, NTH);
227        threadgroup_barrier(mem_flags::mem_threadgroup);
228        auto p = op.template get_destination_cooperative_tensor<decltype(tA), decltype(tW), float>();
229        op.run(tA, tW, p);
230        for (uint16_t i = 0; i < p.get_capacity(); ++i)
231            if (p.is_valid_element(i)) acc[i] += p[i];
232        threadgroup_barrier(mem_flags::mem_threadgroup);
233    }
234    tensor<device float, dextents<int32_t, 2>, tensor_inline> tY(YE, dextents<int32_t, 2>(a.n_embd, 1 << 30));
235    acc.store(tY.slice(d0, row0));
236}
237
238// grid (T * n_embd / 256), 256 threads
239kernel void mm_combine(device const float* YE [[buffer(0)]], device const int* pos [[buffer(1)]],
240                       device const float* srt_w [[buffer(2)]], device float* y [[buffer(3)]],
241                       constant uint4& a [[buffer(4)]],   // (T, n_embd, topk, -)
242                       uint gid [[thread_position_in_grid]]) {
243    const uint t = gid / a.y, d = gid % a.y;
244    if (t >= a.x) return;
245    float s = 0.0f;
246    for (uint k = 0; k < a.z; ++k) {
247        const int r = pos[t * a.z + k];
248        s = fma(srt_w[r], YE[ulong(r) * a.y + d], s);
249    }
250    y[gid] = s;
251}
252
253#define MMGU_(F, M, N, K, S) template [[host_name("mm_gu_" #F "_" #M "_" #N "_" #K "_" #S)]] kernel decltype(mm_gu<F, M, N, K, S>) mm_gu<F, M, N, K, S>;
254#define MMDN_(F, M, N, K, S) template [[host_name("mm_down_" #F "_" #M "_" #N "_" #K "_" #S)]] kernel decltype(mm_down<F, M, N, K, S>) mm_down<F, M, N, K, S>;
255#define MMGU(F, M, N, K, S) MMGU_(F, M, N, K, S)
256#define MMDN(F, M, N, K, S) MMDN_(F, M, N, K, S)
257#define MM_GU_SET(F) MMGU(F, 32, 64, 64, 4) MMGU(F, 64, 64, 64, 4) MMGU(F, 16, 64, 64, 2) MMGU(F, 32, 32, 64, 2)
258#define MM_DN_SET(F) MMDN(F, 32, 64, 64, 4) MMDN(F, 64, 64, 64, 4) MMDN(F, 16, 64, 64, 2) MMDN(F, 32, 32, 64, 2)
259MM_GU_SET(T_Q2_0) MM_GU_SET(T_IQ3_XXS) MM_GU_SET(T_IQ2_XXS) MM_GU_SET(T_IQ2_XS) MM_GU_SET(T_IQ2_S) MM_GU_SET(T_IQ3_S)
260MM_DN_SET(T_Q2_0) MM_DN_SET(T_IQ4_NL) MM_DN_SET(T_Q5_0)
261
262// ---- v2: activations gathered once per layer as fp16 rows, read by matmul2d from device memory ---------------------
263// mm_gather: XS[row][k] = half(x[srt_tok[row]][k]) (0 on padding rows).  grid (rows), 256 threads.
264kernel void mm_gather(device const float* x [[buffer(0)]], device const int* srt_tok [[buffer(1)]],
265                      device half* XS [[buffer(2)]], constant uint& n [[buffer(3)]],
266                      uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]]) {
267    const int t = srt_tok[tg.x];
268    device half* o = XS + ulong(tg.x) * n;
269    for (uint k = tid; k < n; k += 256) o[k] = t >= 0 ? half(x[ulong(t) * n + k]) : half(0.0f);
270}
271
272// The SSD-streaming arena (as in moe.metal): with function constant 20, expert e's slot is smap[e] in the chunks W,
273// W1..W3 (buffers 5..8 of mm_gu2 / mm_down2 / mm_gu3 / mm_down3); gate_off / up_off / down_off are offsets in the slot.
274#ifndef STRATA_ARENA_METAL
275#define STRATA_ARENA_METAL
276constant bool kArenaFc [[function_constant(20)]];
277constant bool kArena = is_function_constant_defined(kArenaFc) && kArenaFc;
278static inline device const uchar* arena_slot(uint v, device const uchar* W, device const uchar* W1, device const uchar* W2,
279                                             device const uchar* W3) {
280    const uint c = v >> 28;
281    device const uchar* b = c == 0 ? W : (c == 1 ? W1 : (c == 2 ? W2 : W3));
282    return b + (ulong)(v & 0x0FFFFFFFu) * 16384ul;
283}
284#endif
285
286// a probe for the bench (function constant 5): 1 = the weights not decoded (a cheap fill), 2 = no matrix multiply
287constant int MM_PROBE [[function_constant(5)]];
288constant int mm_probe = is_function_constant_defined(MM_PROBE) ? MM_PROBE : 0;
289
290template <int F, int TM, int TN, int TK, int SG>
291kernel void mm_gu2(device const uchar* W [[buffer(0)]], device const half* XS [[buffer(1)]],
292                   device half* HS [[buffer(2)]], device const int2* tiles [[buffer(3)]], constant MmArgs& a [[buffer(4)]], device const uint* smap [[buffer(5)]],
293                     device const uchar* W1 [[buffer(6)]], device const uchar* W2 [[buffer(7)]], device const uchar* W3 [[buffer(8)]],
294                   uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]]) {
295    constexpr int NTH = SG * 32;
296    threadgroup half wg[TN * TK];
297    threadgroup half wu[TN * TK];
298    threadgroup float ot[TM * TN];
299    threadgroup uint tab[fmt<F>::TAB];
300    load_tab<F>(tab, tid, NTH);
301    const int2 tl = tiles[tg.y];
302    const int e = tl.x, row0 = tl.y, f0 = int(tg.x) * TN;
303    device const uchar* E = kArena ? arena_slot(smap[e], W, W1, W2, W3) : W + ulong(e) * a.gu_stride;
304    device const uchar* g0 = E + a.gate_off + ulong(f0) * a.gu_row;
305    device const uchar* u0 = E + a.up_off + ulong(f0) * a.gu_row;
306    constexpr auto desc = matmul2d_descriptor(TM, TN, TK, false, true, false, matmul2d_descriptor::mode::multiply_accumulate);
307    matmul2d<desc, execution_simdgroups<SG>> op;
308    tensor<device half, dextents<int32_t, 2>, tensor_inline> tX((device half*)XS, dextents<int32_t, 2>(a.n_embd, 1 << 30));
309    tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline> tG(wg, dextents<int32_t, 2>(TK, TN));
310    tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline> tU(wu, dextents<int32_t, 2>(TK, TN));
311    auto tA = tX.template slice<TK, TM>(0, row0);
312    auto accg = op.template get_destination_cooperative_tensor<decltype(tA), decltype(tG), float>();
313    auto accu = op.template get_destination_cooperative_tensor<decltype(tA), decltype(tG), float>();
314    for (uint16_t i = 0; i < accg.get_capacity(); ++i)
315        if (accg.is_valid_element(i)) { accg[i] = 0.0f; accu[i] = 0.0f; }
316    threadgroup_barrier(mem_flags::mem_threadgroup);
317    for (int k0 = 0; k0 < int(a.n_embd); k0 += TK) {
318        if (mm_probe == 1) {
319            for (int it = tid; it < TN * TK; it += NTH) { wg[it] = half(k0 & 7); wu[it] = half(it & 7); }
320        } else {
321            stage_w<F, TN, TK>(g0, a.gu_row, k0, wg, tab, tid, NTH);
322            stage_w<F, TN, TK>(u0, a.gu_row, k0, wu, tab, tid, NTH);
323        }
324        threadgroup_barrier(mem_flags::mem_threadgroup);
325        tA = tX.template slice<TK, TM>(k0, row0);
326        if (mm_probe != 2) {
327            op.run(tA, tG, accg);
328            op.run(tA, tU, accu);
329        }
330        threadgroup_barrier(mem_flags::mem_threadgroup);
331    }
332    for (uint16_t i = 0; i < accg.get_capacity(); ++i)
333        if (accg.is_valid_element(i)) {
334            const float g = accg[i];
335            accg[i] = g / (1.0f + exp(-g)) * accu[i];
336        }
337    tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline> tO(ot, dextents<int32_t, 2>(TN, TM));
338    accg.store(tO);
339    threadgroup_barrier(mem_flags::mem_threadgroup);
340    for (int it = tid; it < TM * TN; it += NTH) {
341        const int m = it / TN, f = it - m * TN;
342        HS[ulong(row0 + m) * a.n_ff + f0 + f] = half(ot[it]);
343    }
344}
345
346template <int F, int TM, int TN, int TK, int SG>
347kernel void mm_down2(device const uchar* W [[buffer(0)]], device const half* HS [[buffer(1)]],
348                     device float* YE [[buffer(2)]], device const int2* tiles [[buffer(3)]],
349                     constant MmArgs& a [[buffer(4)]], device const uint* smap [[buffer(5)]],
350                     device const uchar* W1 [[buffer(6)]], device const uchar* W2 [[buffer(7)]], device const uchar* W3 [[buffer(8)]],
351                     uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]]) {
352    constexpr int NTH = SG * 32;
353    threadgroup half wd[TN * TK];
354    threadgroup uint tab[fmt<F>::TAB];
355    load_tab<F>(tab, tid, NTH);
356    const int2 tl = tiles[tg.y];
357    const int e = tl.x, row0 = tl.y, d0 = int(tg.x) * TN;
358    device const uchar* w0 = (kArena ? arena_slot(smap[e], W, W1, W2, W3) : W + ulong(e) * a.d_stride) + a.down_off + ulong(d0) * a.d_row;
359    constexpr auto desc = matmul2d_descriptor(TM, TN, TK, false, true, false, matmul2d_descriptor::mode::multiply_accumulate);
360    matmul2d<desc, execution_simdgroups<SG>> op;
361    tensor<device half, dextents<int32_t, 2>, tensor_inline> tH((device half*)HS, dextents<int32_t, 2>(a.n_ff, 1 << 30));
362    tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline> tW(wd, dextents<int32_t, 2>(TK, TN));
363    auto tA = tH.template slice<TK, TM>(0, row0);
364    auto acc = op.template get_destination_cooperative_tensor<decltype(tA), decltype(tW), float>();
365    for (uint16_t i = 0; i < acc.get_capacity(); ++i)
366        if (acc.is_valid_element(i)) acc[i] = 0.0f;
367    threadgroup_barrier(mem_flags::mem_threadgroup);
368    for (int k0 = 0; k0 < int(a.n_ff); k0 += TK) {
369        stage_w<F, TN, TK>(w0, a.d_row, k0, wd, tab, tid, NTH);
370        threadgroup_barrier(mem_flags::mem_threadgroup);
371        tA = tH.template slice<TK, TM>(k0, row0);
372        op.run(tA, tW, acc);
373        threadgroup_barrier(mem_flags::mem_threadgroup);
374    }
375    tensor<device float, dextents<int32_t, 2>, tensor_inline> tY(YE, dextents<int32_t, 2>(a.n_embd, 1 << 30));
376    acc.store(tY.slice(d0, row0));
377}
378
379#define MMGU2_(F, M, N, K, S) template [[host_name("mm_gu2_" #F "_" #M "_" #N "_" #K "_" #S)]] kernel decltype(mm_gu2<F, M, N, K, S>) mm_gu2<F, M, N, K, S>;
380#define MMDN2_(F, M, N, K, S) template [[host_name("mm_down2_" #F "_" #M "_" #N "_" #K "_" #S)]] kernel decltype(mm_down2<F, M, N, K, S>) mm_down2<F, M, N, K, S>;
381#define MMGU2(F, M, N, K, S) MMGU2_(F, M, N, K, S)
382#define MMDN2(F, M, N, K, S) MMDN2_(F, M, N, K, S)
383#define MM_GU2_SET(F) MMGU2(F, 32, 64, 32, 2) MMGU2(F, 32, 32, 32, 2) MMGU2(F, 32, 64, 16, 2) MMGU2(F, 64, 32, 16, 2) MMGU2(F, 16, 32, 32, 2) MMGU2(F, 16, 64, 16, 2) MMGU2(F, 16, 128, 32, 4) MMGU2(F, 32, 64, 16, 4) MMGU2(F, 16, 32, 32, 1) MMGU2(F, 16, 64, 32, 4) MMGU2(F, 16, 64, 64, 2) MMGU2(F, 32, 64, 64, 4) MMGU2(F, 64, 64, 64, 4) MMGU2(F, 16, 32, 64, 2) MMGU2(F, 32, 64, 32, 4) MMGU2(F, 64, 64, 32, 4) MMGU2(F, 16, 64, 32, 2)
384#define MM_DN2_SET(F) MMDN2(F, 32, 64, 32, 2) MMDN2(F, 32, 32, 32, 2) MMDN2(F, 32, 64, 16, 2) MMDN2(F, 64, 32, 16, 2) MMDN2(F, 16, 32, 32, 2) MMDN2(F, 16, 64, 16, 2) MMDN2(F, 16, 128, 32, 4) MMDN2(F, 32, 64, 16, 4) MMDN2(F, 16, 32, 32, 1) MMDN2(F, 16, 64, 32, 4) MMDN2(F, 16, 64, 64, 2) MMDN2(F, 32, 64, 64, 4) MMDN2(F, 64, 64, 64, 4) MMDN2(F, 16, 32, 64, 2) MMDN2(F, 32, 64, 32, 4) MMDN2(F, 64, 64, 32, 4) MMDN2(F, 16, 64, 32, 2)
385#define MM_GU2_U32(F) MMGU2(F, 16, 64, 32, 2) MMGU2(F, 16, 64, 64, 2) MMGU2(F, 32, 64, 32, 2) MMGU2(F, 16, 32, 32, 2) \
386    MMGU2(F, 64, 64, 32, 4)
387#define MM_DN2_U32(F) MMDN2(F, 16, 64, 32, 2) MMDN2(F, 16, 64, 64, 2) MMDN2(F, 16, 32, 32, 2) MMDN2(F, 32, 32, 32, 2) \
388    MMDN2(F, 16, 128, 32, 4) MMDN2(F, 32, 64, 32, 2) MMDN2(F, 64, 64, 32, 4)
389// K-quants: the staged K chunk must hold whole units as DW places them (128 wide): TK 128
390#define MM_GU2_KQ(F) MMGU2(F, 16, 32, 128, 2) MMGU2(F, 16, 16, 128, 2) MMGU2(F, 32, 32, 128, 2) MMGU2(F, 16, 32, 128, 4)
391MM_GU2_KQ(T_Q4_K) MM_GU2_KQ(T_Q5_K) MM_GU2_KQ(T_Q6_K) MM_GU2_U32(T_Q8_0) MM_DN2_U32(T_Q5_1) MM_DN2_U32(T_Q5_0) MM_DN2_U32(T_Q8_0)
392// K-quant / IQ4_XS / IQ3_S down experts (a UD file's downs at expert widths divisible by 256: Q4-KQ): the staged K chunk
393// follows the same rule as the gate/up's (Q4_K / Q5_K / Q6_K 128, Q3_K and IQ4_XS 32, IQ3_S 16)
394#ifdef STRATA_KQ_DOWN   // (see moe.metal)
395#define MM_DN2_KQ(F) MMDN2(F, 16, 16, 128, 2) MMDN2(F, 16, 32, 128, 2) MMDN2(F, 32, 32, 128, 2) MMDN2(F, 16, 32, 128, 4)
396MM_DN2_KQ(T_Q4_K) MM_DN2_KQ(T_Q5_K) MM_DN2_KQ(T_Q6_K)
397MMDN2(T_IQ4_XS, 16, 64, 32, 2) MMDN2(T_IQ4_XS, 16, 64, 64, 2) MMDN2(T_IQ4_XS, 16, 32, 32, 2)
398MMDN2(T_Q3_K, 16, 64, 32, 2) MMDN2(T_Q3_K, 16, 32, 32, 2)
399MMDN2(T_IQ3_S, 16, 64, 16, 2) MMDN2(T_IQ3_S, 16, 64, 32, 2) MMDN2(T_IQ3_S, 16, 32, 32, 2)
400#endif
401// IQ4_XS (UNIT 32): the K chunk must be >= 32
402MMGU2(T_IQ4_XS, 16, 64, 32, 2) MMGU2(T_IQ4_XS, 16, 64, 64, 2) MMGU2(T_IQ4_XS, 32, 64, 32, 2) MMGU2(T_IQ4_XS, 16, 32, 32, 2)
403MMGU2(T_IQ4_XS, 64, 64, 32, 4)
404MM_GU2_SET(T_Q2_0) MM_GU2_SET(T_IQ3_XXS) MM_GU2_SET(T_IQ2_XXS) MM_GU2_SET(T_IQ2_XS) MM_GU2_SET(T_IQ2_S) MM_GU2_SET(T_IQ3_S)
405MM_GU2_SET(T_TQK6) MM_GU2_SET(T_TQ2T)   // Gyro: the trellis gate/up (units of 16 weights: TK 16 or a multiple)
406MM_DN2_SET(T_Q2_0)
407MM_DN2_SET(T_TQK7) MM_DN2_SET(T_TQ2T)
408MMDN2(T_IQ4_NL, 16, 64, 32, 2) MMDN2(T_IQ4_NL, 16, 64, 64, 2) MMDN2(T_IQ4_NL, 16, 32, 32, 2) MMDN2(T_IQ4_NL, 32, 32, 32, 2) MMDN2(T_IQ4_NL, 16, 128, 32, 4)
409
410// ---- v3: the weights decoded straight into matmul2d's right-input cooperative tensor (single-simdgroup scope),
411// no threadgroup staging and no barriers in the K loop.  Each simdgroup owns TN output rows; a threadgroup SG * TN.
412// The right input's element layout (tests/coop_layout): runs of 4 consecutive k at one n, so a lane decodes 4 values
413// at a time (W4<F>).  Activations: the gathered fp16 rows from device memory.
414#ifndef STRATA_COOP_K4
415#define STRATA_COOP_K4
416// function constant 7: the right-input cooperative tensor holds runs of 4 consecutive k at one n per lane (the M5's
417// layout; tests/coop_layout).  false (the M4: runs of 2 n at one k): every element decoded on its own.
418constant bool COOP_K4 [[function_constant(7)]];
419constant bool coop_k4 = is_function_constant_defined(COOP_K4) ? COOP_K4 : true;
420#endif
421template <int F> struct W4;
422// the four weights k .. k + 3 (k % 4 == 0) of a row, in quant.metal's deq arithmetic (code * scale in fp32), as fp16
423// the threadgroup forms of quant.metal's field readers (blocks staged in threadgroup memory)
424static inline uint rd32(threadgroup const uchar* p) {
425    threadgroup const ushort* s = (threadgroup const ushort*)p;
426    return uint(s[0]) | (uint(s[1]) << 16);
427}
428static inline float rdh(threadgroup const uchar* p) { return float(*(threadgroup const half*)p); }
429
430static inline half4 w4_signed(uint g, uint s, float sc) {
431    const uchar4 v = as_type<uchar4>(g);
432    const float4 q = float4((s & 1) ? -float(v[0]) : float(v[0]), (s & 2) ? -float(v[1]) : float(v[1]),
433                            (s & 4) ? -float(v[2]) : float(v[2]), (s & 8) ? -float(v[3]) : float(v[3]));
434    return half4(q * sc);
435}
436template <> struct W4<T_Q2_0> {   // 64 values a block: fp16 d, 16 bytes of 2-bit codes (value v at byte v / 4)
437    // fp32 math then fp16 (an fp16-math decode was measured slower: 4.2 vs 3.5 ms a layer)
438    static inline half4 run(device const uchar* row, int k, threadgroup const uint*) {
439        device const uchar* b = row + (k >> 6) * 18;
440        const float d = float(*(device const half*)b);
441        const uint q = b[2 + ((k & 63) >> 2)];
442        return half4(float4(float(int(q & 3) - 1), float(int((q >> 2) & 3) - 1), float(int((q >> 4) & 3) - 1),
443                            float(int(q >> 6) - 1)) * d);
444    }
445};
446template <> struct W4<T_IQ3_XXS> {
447    static inline half4 run(device const uchar* row, int k, threadgroup const uint* tab) {
448        device const uchar* b = row + (k >> 8) * 98;
449        const int ib = (k & 255) >> 5, l = (k & 31) >> 3, hh = (k & 7) >> 2;
450        const uint aux = rd32(b + 2 + 64 + 4 * ib);
451        threadgroup const uchar* ks = (threadgroup const uchar*)(tab + 256);
452        const uint s = ks[(aux >> (7 * l)) & 127];
453        const float sc = rdh(b) * (0.5f + float(aux >> 28)) * 0.5f;
454        return w4_signed(tab[b[2 + 8 * ib + 2 * l + hh]], hh ? s >> 4 : s, sc);
455    }
456};
457template <> struct W4<T_IQ2_XXS> {
458    static inline half4 run(device const uchar* row, int k, threadgroup const uint* tab) {
459        device const uchar* b = row + (k >> 8) * 66;
460        const int ib = (k & 255) >> 5, l = (k & 31) >> 3, hh = (k & 7) >> 2;
461        const uint a0 = rd32(b + 2 + 8 * ib), a1 = rd32(b + 2 + 8 * ib + 4);
462        threadgroup const uchar* ks = (threadgroup const uchar*)(tab + 512);
463        const uint idx = (a0 >> (8 * l)) & 255, s = ks[(a1 >> (7 * l)) & 127];
464        const float sc = rdh(b) * (0.5f + float(a1 >> 28)) * 0.25f;
465        return w4_signed(tab[2 * idx + hh], hh ? s >> 4 : s, sc);
466    }
467};
468template <> struct W4<T_IQ2_XS> {
469    static inline half4 run(device const uchar* row, int k, threadgroup const uint* tab) {
470        device const uchar* b = row + (k >> 8) * 74;
471        const int ib = (k & 255) >> 5, l = (k & 31) >> 3, hh = (k & 7) >> 2;
472        const uint v = ((device const ushort*)(b + 2))[4 * ib + l];
473        threadgroup const uchar* ks = (threadgroup const uchar*)(tab + 1024);
474        const uint idx = v & 511, s = ks[v >> 9];
475        const uint scb = b[66 + ib];
476        const float sc = rdh(b) * (0.5f + float((scb >> (4 * (l >> 1))) & 15)) * 0.25f;
477        return w4_signed(tab[2 * idx + hh], hh ? s >> 4 : s, sc);
478    }
479};
480template <> struct W4<T_IQ2_S> {
481    static inline half4 run(device const uchar* row, int k, threadgroup const uint* tab) {
482        device const uchar* b = row + (k >> 8) * 82;
483        const int ib = (k & 255) >> 5, l = (k & 31) >> 3, hh = (k & 7) >> 2;
484        const uint qh = b[66 + ib];
485        const uint idx = uint(b[2 + 4 * ib + l]) | ((qh << (8 - 2 * l)) & 0x300);
486        const uint s = b[2 + 32 + 4 * ib + l];
487        const uint scb = b[74 + ib];
488        const float sc = rdh(b) * (0.5f + float((scb >> (4 * (l >> 1))) & 15)) * 0.25f;
489        return w4_signed(tab[2 * idx + hh], hh ? s >> 4 : s, sc);
490    }
491};
492template <> struct W4<T_IQ3_S> {
493    static inline half4 run(device const uchar* row, int k, threadgroup const uint* tab) {
494        device const uchar* b = row + (k >> 8) * 110;
495        const int ib = (k & 255) >> 5, l = (k & 31) >> 3, hh = (k & 7) >> 2;
496        const uint qh = b[66 + ib];
497        const uint i = hh ? (uint(b[2 + 8 * ib + 2 * l + 1]) | ((qh << (7 - 2 * l)) & 256))
498                          : (uint(b[2 + 8 * ib + 2 * l]) | ((qh << (8 - 2 * l)) & 256));
499        const uint s = b[74 + 4 * ib + l];
500        const uint scb = b[106 + (ib >> 1)];
501        const float sc = rdh(b) * float(1 + 2 * ((scb >> (4 * (ib & 1))) & 15));
502        return w4_signed(tab[i], hh ? s >> 4 : s, sc);
503    }
504};
505template <> struct W4<T_IQ4_XS> {   // 256 a block: d, scales_h, scales_l[4], qs[128]; 32-groups as IQ4_NL's
506    static inline half4 run(device const uchar* row, int k, threadgroup const uint* tab) {
507        device const uchar* b = row + (k >> 8) * 136;
508        const int j = k & 255, ib = j >> 5, o = j & 15, hi = (j >> 4) & 1;
509        const uint sh = *(device const ushort*)(b + 2);
510        const int ls = int((b[4 + (ib >> 1)] >> (4 * (ib & 1))) & 15) | int(((sh >> (2 * ib)) & 3) << 4);
511        const float s = rdh(b) * float(ls - 32);
512        device const uchar* qs = b + 8 + 16 * ib;
513        float4 q;
514        for (int c = 0; c < 4; ++c) {
515            const half2 w = as_type<half2>(tab[qs[o + c]]);
516            q[c] = float(hi ? w.y : w.x);
517        }
518        return half4(q * s);
519    }
520};
521template <> struct W4<T_IQ4_NL> {   // 32 a block: d, 16 bytes; low nibbles are elements 0..15, high 16..31
522    static inline half4 run(device const uchar* row, int k, threadgroup const uint* tab) {
523        device const uchar* b = row + (k >> 5) * 18;
524        const int j = k & 31, hi = j >> 4, o = j & 15;
525        const float d = rdh(b);
526        float4 q;
527        for (int c = 0; c < 4; ++c) {
528            const half2 w = as_type<half2>(tab[b[2 + o + c]]);
529            q[c] = float(hi ? w.y : w.x);
530        }
531        return half4(q * d);
532    }
533};
534
535// W8<F>: the runs k .. k + 3 and k + 16 .. k + 19 of a row (k % 32 < 16): one 32-group, so the per-group fields (scale,
536// sign word) are read once.  The generic one is two W4.
537// ---- the K-quant / legacy-quant W4 decoders (the UD-Q4/5/6_K_XL packs' experts): values k .. k + 3 (k % 4 == 0)
538// of a row in ref_quant's arithmetic (float), then fp16
539template <> struct W4<T_Q8_0> {   // 32 a block: d, int8 qs[32]
540    static inline half4 run(device const uchar* row, int k, threadgroup const uint*) {
541        device const uchar* b = row + (k >> 5) * 34;
542        const float d = rdh(b);
543        device const char* q = (device const char*)(b + 2 + (k & 31));
544        return half4(float4(float(q[0]), float(q[1]), float(q[2]), float(q[3])) * d);
545    }
546};
547template <> struct W4<T_Q5_1> {   // 32 a block: d, m, qh (32 bits), qs[16] (low nibbles 0..15, high 16..31)
548    static inline half4 run(device const uchar* row, int k, threadgroup const uint*) {
549        device const uchar* b = row + (k >> 5) * 24;
550        const float d = rdh(b), m = rdh(b + 2);
551        const uint hb = rd32(b + 4);
552        const int j = k & 31, o = j & 15, hi = j >> 4;
553        float4 w;
554        for (int c = 0; c < 4; ++c) {
555            const uint qv = b[8 + o + c];
556            const int x = int(hi ? (qv >> 4) : (qv & 15)) | int(((hb >> (j + c)) & 1) << 4);
557            w[c] = float(x) * d + m;
558        }
559        return half4(w);
560    }
561};
562template <> struct W4<T_Q5_0> {   // 32 a block: d, qh (32 bits), qs[16] (low nibbles 0..15, high 16..31); w = (code - 16) d
563    static inline half4 run(device const uchar* row, int k, threadgroup const uint*) {
564        device const uchar* b = row + (k >> 5) * 22;
565        const float d = rdh(b);
566        const uint hb = rd32(b + 2);
567        const int j = k & 31, o = j & 15, hi = j >> 4;
568        float4 w;
569        for (int c = 0; c < 4; ++c) {
570            const uint qv = b[6 + o + c];
571            const int x = int(hi ? (qv >> 4) : (qv & 15)) | int(((hb >> (j + c)) & 1) << 4);
572            w[c] = float(x - 16) * d;
573        }
574        return half4(w);
575    }
576};
577template <> struct W4<T_Q4_K> {   // 256 a block: d, dmin, scales[12], qs[128] (64-chunks: low nibbles then high)
578    static inline half4 run(device const uchar* row, int k, threadgroup const uint*) {
579        device const uchar* b = row + (k >> 8) * 144;
580        const int j = k & 255, c = j >> 6, hi = (j >> 5) & 1, l = j & 31;
581        float s, mm;
582        scale_min_k4(2 * c + hi, b + 4, s, mm);
583        const float d1 = rdh(b) * s, m1 = rdh(b + 2) * mm;
584        device const uchar* q = b + 16 + 32 * c + l;
585        float4 w;
586        for (int i = 0; i < 4; ++i) w[i] = d1 * float(hi ? (q[i] >> 4) : (q[i] & 15)) - m1;
587        return half4(w);
588    }
589};
590template <> struct W4<T_Q5_K> {   // 256 a block: d, dmin, scales[12], qh[32], qs[128]
591    static inline half4 run(device const uchar* row, int k, threadgroup const uint*) {
592        device const uchar* b = row + (k >> 8) * 176;
593        const int j = k & 255, c = j >> 6, hi = (j >> 5) & 1, l = j & 31;
594        float s, mm;
595        scale_min_k4(2 * c + hi, b + 4, s, mm);
596        const float d1 = rdh(b) * s, m1 = rdh(b + 2) * mm;
597        device const uchar* qh = b + 16 + l;
598        device const uchar* ql = b + 48 + 32 * c + l;
599        const uint bit = 1u << (2 * c + hi);
600        float4 w;
601        for (int i = 0; i < 4; ++i)
602            w[i] = d1 * float(int(hi ? (ql[i] >> 4) : (ql[i] & 15)) + ((qh[i] & bit) ? 16 : 0)) - m1;
603        return half4(w);
604    }
605};
606template <> struct W4<T_Q6_K> {   // 256 a block: ql[128], qh[64], int8 scales[16], d; halves of 128
607    static inline half4 run(device const uchar* row, int k, threadgroup const uint*) {
608        device const uchar* b = row + (k >> 8) * 210;
609        const int j = k & 255, n = j >> 7, jj = j & 127, qd = jj >> 5, l = jj & 31;
610        device const uchar* ql = b + 64 * n + l + ((qd & 1) ? 32 : 0);
611        device const uchar* qh = b + 128 + 32 * n + l;
612        const float d = rdh(b + 208);
613        const float ds = d * float(((device const char*)(b + 192 + 8 * n))[l / 16 + 2 * qd]);
614        float4 w;
615        for (int i = 0; i < 4; ++i) {
616            const int q = int(((qd >> 1) ? (ql[i] >> 4) : (ql[i] & 15)) | (((qh[i] >> (2 * qd)) & 3) << 4)) - 32;
617            w[i] = ds * float(q);
618        }
619        return half4(w);
620    }
621};
622
623template <> struct W4<T_Q3_K> {   // 256 a block: hmask[32], qs[64], scales[12], d (fp16 at 108); value = d (scale - 32) ((q & 3) - (hmask bit ? 0 : 4))
624    static inline half4 run(device const uchar* row, int k, threadgroup const uint*) {
625        device const uchar* b = row + (k >> 8) * 110;
626        const int j = k & 255, n = j >> 7, jj = j & 127, jg = jj >> 5, l = jj & 31;
627        device const uchar* s = b + 96;
628        const int i = 8 * n + 2 * jg + (l >> 4);
629        const int sc = (i < 8 ? s[i] & 0xF : s[i - 8] >> 4) | (((s[8 + (i & 3)] >> (2 * (i >> 2))) & 3) << 4);
630        const float dl = rdh(b + 108) * float(sc - 32);
631        device const uchar* qs = b + 32 + 32 * n + l;
632        device const uchar* hm = b + l;
633        const uint bit = 1u << (4 * n + jg);
634        float4 w;
635        for (int c = 0; c < 4; ++c) w[c] = dl * float(int((qs[c] >> (2 * jg)) & 3) - ((hm[c] & bit) ? 0 : 4));
636        return half4(w);
637    }
638};
639
640template <int F> struct W8 {
641    static inline void run(device const uchar* row, int k, threadgroup const uint* tab, thread half4& a, thread half4& b) {
642        a = W4<F>::run(row, k, tab);
643        b = W4<F>::run(row, k + 16, tab);
644    }
645};
646// (a W8<T_Q2_0> sharing the block scale was measured slower than the two W4 of the generic one: 5.5 vs 3.5-4.2 ms)
647template <> struct W8<T_IQ3_XXS> {
648    template <typename P>
649    static inline void run(P row, int k, threadgroup const uint* tab, thread half4& a, thread half4& b) {
650        const P bl = row + (k >> 8) * 98;
651        const int ib = (k & 255) >> 5, l = (k & 31) >> 3, hh = (k & 7) >> 2;
652        const uint aux = rd32(bl + 2 + 64 + 4 * ib);
653        threadgroup const uchar* ks = (threadgroup const uchar*)(tab + 256);
654        const float sc = rdh(bl) * (0.5f + float(aux >> 28)) * 0.5f;
655        const P qs = bl + 2 + 8 * ib + hh;
656        if (mm_probe == 3) {   // bench probe: no threadgroup-table lookups (wrong values)
657            a = w4_signed(qs[2 * l] * 0x01010101u, aux, sc);
658            b = w4_signed(qs[2 * l + 4] * 0x01010101u, aux >> 7, sc);
659            return;
660        }
661        uint s0, s1;
662        if (mm_probe == 4) {   // the signs computed (ksigns_iq2xs[i] = i | parity(i) << 7) instead of looked up
663            const uint i0 = (aux >> (7 * l)) & 127, i1 = (aux >> (7 * (l + 2))) & 127;
664            s0 = i0 | ((popcount(i0) & 1u) << 7);
665            s1 = i1 | ((popcount(i1) & 1u) << 7);
666        } else {
667            s0 = ksg(tab, 256, (aux >> (7 * l)) & 127);
668            s1 = ksg(tab, 256, (aux >> (7 * (l + 2))) & 127);
669        }
670        a = w4_signed(g_iq3xxs(tab, qs[2 * l]), hh ? s0 >> 4 : s0, sc);
671        b = w4_signed(g_iq3xxs(tab, qs[2 * l + 4]), hh ? s1 >> 4 : s1, sc);
672    }
673};
674template <> struct W8<T_IQ2_XXS> {
675    static inline void run(device const uchar* row, int k, threadgroup const uint* tab, thread half4& a, thread half4& b) {
676        device const uchar* bl = row + (k >> 8) * 66;
677        const int ib = (k & 255) >> 5, l = (k & 31) >> 3, hh = (k & 7) >> 2;
678        const uint a0 = rd32(bl + 2 + 8 * ib), a1 = rd32(bl + 2 + 8 * ib + 4);
679        const float sc = rdh(bl) * (0.5f + float(a1 >> 28)) * 0.25f;
680        const uint i0 = (a0 >> (8 * l)) & 255, i1 = (a0 >> (8 * (l + 2))) & 255;
681        // through the accessors, so QUANT_CTAB (the constant grids, no threadgroup copy) gives the same values: the
682        // direct tab[] reads below skipped the ctab branch and read an unfilled table
683        const uint s0 = ksg(tab, 512, (a1 >> (7 * l)) & 127), s1 = ksg(tab, 512, (a1 >> (7 * (l + 2))) & 127);
684        a = w4_signed(g_iq2xxs(tab, i0, hh), hh ? s0 >> 4 : s0, sc);
685        b = w4_signed(g_iq2xxs(tab, i1, hh), hh ? s1 >> 4 : s1, sc);
686    }
687};
688template <> struct W8<T_IQ2_XS> {
689    static inline void run(device const uchar* row, int k, threadgroup const uint* tab, thread half4& a, thread half4& b) {
690        device const uchar* bl = row + (k >> 8) * 74;
691        const int ib = (k & 255) >> 5, l = (k & 31) >> 3, hh = (k & 7) >> 2;
692        device const ushort* q = (device const ushort*)(bl + 2) + 4 * ib;
693        const uint v0 = q[l], v1 = q[l + 2];
694        const uint scb = bl[66 + ib];
695        const float d = rdh(bl);
696        const float sc0 = d * (0.5f + float((scb >> (4 * (l >> 1))) & 15)) * 0.25f;
697        const float sc1 = d * (0.5f + float((scb >> (4 * ((l + 2) >> 1))) & 15)) * 0.25f;
698        // through the accessors: the direct tab[]/ks[] reads ignored QUANT_CTAB, whose tables are then never filled
699        const uint s0 = ksg(tab, 1024, v0 >> 9), s1 = ksg(tab, 1024, v1 >> 9);
700        a = w4_signed(g_iq2xs(tab, v0 & 511, hh), hh ? s0 >> 4 : s0, sc0);
701        b = w4_signed(g_iq2xs(tab, v1 & 511, hh), hh ? s1 >> 4 : s1, sc1);
702    }
703};
704template <> struct W8<T_IQ2_S> {
705    template <typename P>
706    static inline void run(P row, int k, threadgroup const uint* tab, thread half4& a, thread half4& b) {
707        const P bl = row + (k >> 8) * 82;
708        const int ib = (k & 255) >> 5, l = (k & 31) >> 3, hh = (k & 7) >> 2;
709        const uint qh = bl[66 + ib], scb = bl[74 + ib];
710        const float d = rdh(bl);
711        const uint i0 = uint(bl[2 + 4 * ib + l]) | ((qh << (8 - 2 * l)) & 0x300);
712        const uint i1 = uint(bl[2 + 4 * ib + l + 2]) | ((qh << (8 - 2 * (l + 2))) & 0x300);
713        const uint s0 = bl[2 + 32 + 4 * ib + l], s1 = bl[2 + 32 + 4 * ib + l + 2];
714        const float sc0 = d * (0.5f + float((scb >> (4 * (l >> 1))) & 15)) * 0.25f;
715        const float sc1 = d * (0.5f + float((scb >> (4 * ((l + 2) >> 1))) & 15)) * 0.25f;
716        a = w4_signed(g_iq2s(tab, i0, hh), hh ? s0 >> 4 : s0, sc0);
717        b = w4_signed(g_iq2s(tab, i1, hh), hh ? s1 >> 4 : s1, sc1);
718    }
719};
720
721// IQ1_M (the 2.00 bpw pack's 1.75-bit type), ggml's dequantize_row_iq1_m: the block's F16 scale sits in the top
722// nibbles of its four u16 scales; a 32-value sub-block has two 3-bit scales (groups 0-1 and 2-3, eight values each),
723// and each eight-value group carries a +-0.125 delta picked by a bit of its qh byte.  The tile's two halves are the
724// four values at k and the four at k + 16, each decoded on its own (k + 16 crosses into the next sub-block at l >= 2).
725template <typename P>
726static inline half4 iq1m_w4(P row, int k) {
727    const P bl = row + (k >> 8) * 56;
728    const int ib = (k & 255) >> 5, g = (k & 31) >> 3, hh = (k & 7) >> 2;
729    const uint s0 = uint(bl[48]) | (uint(bl[49]) << 8), s1 = uint(bl[50]) | (uint(bl[51]) << 8);
730    const uint s2 = uint(bl[52]) | (uint(bl[53]) << 8), s3 = uint(bl[54]) | (uint(bl[55]) << 8);
731    const float d = float(as_type<half>(ushort((s0 >> 12) | ((s1 >> 8) & 0x00f0u) | ((s2 >> 4) & 0x0f00u) | (s3 & 0xf000u))));
732    const uint sc = uint(((const device ushort*) (bl + 48))[ib >> 1]);
733    const float dl = d * float(2u * ((sc >> (6u * uint(ib & 1) + (g < 2 ? 0u : 3u))) & 7u) + 1u);
734    const uint qh = (g < 2) ? uint(bl[32 + 2 * ib]) : uint(bl[33 + 2 * ib]);
735    const uint idx = uint(bl[4 * ib + g]) | (((g & 1) != 0) ? ((qh << 4u) & 0x700u) : ((qh << 8u) & 0x700u));
736    const bool neg = ((g & 1) != 0) ? ((qh & 0x80u) != 0u) : ((qh & 0x08u) != 0u);
737    const ulong gr = iq1s_grid[idx];
738    const float delta = neg ? -0.125f : 0.125f;
739    float v[4];
740    for (int j = 0; j < 4; ++j) {
741        const uint by = uint((gr >> (8u * uint(4 * hh + j))) & 0xffu);
742        const int c = (by & 0x80u) != 0u ? int(by) - 256 : int(by);
743        v[j] = dl * (float(c) + delta);
744    }
745    return half4(v[0], v[1], v[2], v[3]);
746}
747template <> struct W8<T_IQ1_M> {
748    template <typename P>
749    static inline void run(P row, int k, threadgroup const uint* tab, thread half4& a, thread half4& b) {
750        (void) tab;
751        a = iq1m_w4(row, k);
752        b = iq1m_w4(row, k + 16);
753    }
754};
755
756// IQ1_S (Unsloth's UD-IQ1_S / UD-IQ1_M experts), ggml's dequantize_row_iq1_s: f16 d, qs[32], qh[8] u16; a 32-value sub-block has
757// one scale dl = d (2 s + 1) (qh bits 12-14), a +-0.125 delta (qh bit 15) and four 8-value groups whose grid index is
758// qs[4 ib + g] | 3 bits of qh << 8.  Same float arithmetic as ggml (dl (grid + delta)), so the half4 is what the CPU reference rounds to.
759template <typename P>
760static inline half4 iq1s_w4(P row, int k) {
761    const P bl = row + (k >> 8) * 50;
762    const int ib = (k & 255) >> 5, g = (k & 31) >> 3, hh = (k & 7) >> 2;
763    const uint qh = uint(bl[34 + 2 * ib]) | (uint(bl[35 + 2 * ib]) << 8);
764    const float dl = float(as_type<half>(ushort(uint(bl[0]) | (uint(bl[1]) << 8)))) * float(2u * ((qh >> 12) & 7u) + 1u);
765    const float delta = (qh & 0x8000u) != 0u ? -0.125f : 0.125f;
766    const uint idx = uint(bl[2 + 4 * ib + g]) | (((qh >> (3u * uint(g))) & 7u) << 8);
767    const ulong gr = iq1s_grid[idx];
768    float v[4];
769    for (int j = 0; j < 4; ++j) {
770        const uint by = uint((gr >> (8u * uint(4 * hh + j))) & 0xffu);
771        const int c = (by & 0x80u) != 0u ? int(by) - 256 : int(by);
772        v[j] = dl * (float(c) + delta);
773    }
774    return half4(v[0], v[1], v[2], v[3]);
775}
776template <> struct W8<T_IQ1_S> {
777    template <typename P>
778    static inline void run(P row, int k, threadgroup const uint* tab, thread half4& a, thread half4& b) {
779        (void) tab;
780        a = iq1s_w4(row, k);
781        b = iq1s_w4(row, k + 16);
782    }
783};
784
785template <> struct W8<T_IQ3_S> {
786    template <typename P>
787    static inline void run(P row, int k, threadgroup const uint* tab, thread half4& a, thread half4& b) {
788        const P bl = row + (k >> 8) * 110;
789        const int ib = (k & 255) >> 5, l = (k & 31) >> 3, hh = (k & 7) >> 2;
790        const uint qh = bl[66 + ib], scb = bl[106 + (ib >> 1)];
791        const float sc = rdh(bl) * float(1 + 2 * ((scb >> (4 * (ib & 1))) & 15));
792        const int l1 = l + 2;
793        const uint i0 = hh ? (uint(bl[2 + 8 * ib + 2 * l + 1]) | ((qh << (7 - 2 * l)) & 256))
794                           : (uint(bl[2 + 8 * ib + 2 * l]) | ((qh << (8 - 2 * l)) & 256));
795        const uint i1 = hh ? (uint(bl[2 + 8 * ib + 2 * l1 + 1]) | ((qh << (7 - 2 * l1)) & 256))
796                           : (uint(bl[2 + 8 * ib + 2 * l1]) | ((qh << (8 - 2 * l1)) & 256));
797        const uint s0 = bl[74 + 4 * ib + l], s1 = bl[74 + 4 * ib + l1];
798        if (mm_probe == 7) {
799            // bench probe: a repacked layout's cost - one aligned 16-byte load a lane a row a 32-group holding every
800            // field the lane needs (wrong values: the bytes come from an arbitrary aligned spot of the row)
801            const uint4 r = *(device const uint4*)((ulong(row) + ulong(k >> 5) * 16) & ~ulong(15));
802            const uint qhv = r.z & 0xFF, scv = (r.z >> 8) & 0xFF;
803            const float scr = float(as_type<half>(ushort(r.w & 0xFFFF))) * float(1 + 2 * ((scv >> (4 * (ib & 1))) & 15));
804            const uint j0 = ((r.x >> (8 * (l & 1))) & 0xFF) | ((qhv << (8 - 2 * l)) & 256);
805            const uint j1 = ((r.x >> (16 + 8 * (l & 1))) & 0xFF) | ((qhv << (7 - 2 * l)) & 256);
806            a = w4_signed(tab[j0], (r.y >> (8 * hh)) & 0xFF, scr);
807            b = w4_signed(tab[j1], (r.y >> (16 + 8 * hh)) & 0xFF, scr);
808            return;
809        }
810        if (mm_probe == 5) {   // bench probe: the loads and the scale, no grid lookup / sign math (wrong values)
811            a = half4(half(float(i0 ^ s0) * sc));
812            b = half4(half(float(i1 ^ s1) * sc));
813            return;
814        }
815        a = w4_signed(g_iq3s(tab, i0), hh ? s0 >> 4 : s0, sc);
816        b = w4_signed(g_iq3s(tab, i1), hh ? s1 >> 4 : s1, sc);
817    }
818};
819
820// W8 for the K-quants and Q5_1: the lane's runs k and k + 16 (k % 32 < 16) share the block's scales / mins / high
821// bits; the 4-byte code runs read as one uint where the block layout keeps them 4-aligned (Q4_K 144-, Q5_K 176-,
822// Q5_1 24-byte blocks: rows of whole blocks start 4-aligned).  The same per-value arithmetic as W4.
823static inline float4 nib4(uint v, int hi) { const uint s = hi ? (v >> 4) : v; return float4(as_type<uchar4>(s & 0x0F0F0F0Fu)); }
824template <> struct W8<T_Q4_K> {
825    static inline void run(device const uchar* row, int k, threadgroup const uint*, thread half4& a, thread half4& b) {
826        device const uchar* bl = row + (k >> 8) * 144;
827        const int j = k & 255, c = j >> 6, hi = (j >> 5) & 1, l = j & 31;
828        float s, mm;
829        scale_min_k4(2 * c + hi, bl + 4, s, mm);
830        const float d1 = rdh(bl) * s, m1 = rdh(bl + 2) * mm;
831        device const uint* q = (device const uint*)(bl + 16 + 32 * c + l);
832        const float4 qa = nib4(q[0], hi), qb = nib4(q[4], hi);
833        a = half4(d1 * qa - m1);
834        b = half4(d1 * qb - m1);
835    }
836};
837template <> struct W8<T_Q5_K> {
838    static inline void run(device const uchar* row, int k, threadgroup const uint*, thread half4& a, thread half4& b) {
839        device const uchar* bl = row + (k >> 8) * 176;
840        const int j = k & 255, c = j >> 6, hi = (j >> 5) & 1, l = j & 31;
841        float s, mm;
842        scale_min_k4(2 * c + hi, bl + 4, s, mm);
843        const float d1 = rdh(bl) * s, m1 = rdh(bl + 2) * mm;
844        device const uint* qh = (device const uint*)(bl + 16 + l);
845        device const uint* ql = (device const uint*)(bl + 48 + 32 * c + l);
846        const uint sh = uint(2 * c + hi);
847        const float4 ha = float4(as_type<uchar4>((qh[0] >> sh) & 0x01010101u)) * 16.0f;
848        const float4 hb = float4(as_type<uchar4>((qh[4] >> sh) & 0x01010101u)) * 16.0f;
849        a = half4(d1 * (nib4(ql[0], hi) + ha) - m1);
850        b = half4(d1 * (nib4(ql[4], hi) + hb) - m1);
851    }
852};
853template <> struct W8<T_Q5_1> {
854    static inline void run(device const uchar* row, int k, threadgroup const uint*, thread half4& a, thread half4& b) {
855        device const uchar* bl = row + (k >> 5) * 24;
856        const float d = rdh(bl), m = rdh(bl + 2);
857        const uint hb = rd32(bl + 4);
858        const int j = k & 15;   // runs at j and j + 16: the low nibbles of qs[j..j+3], then the high ones
859        const uint v = *(device const uint*)(bl + 8 + j);
860        float4 wa, wb;
861        for (int c = 0; c < 4; ++c) {
862            const uint qv = (v >> (8 * c)) & 0xFFu;
863            wa[c] = float(int(qv & 15) | int(((hb >> (j + c)) & 1) << 4)) * d + m;
864            wb[c] = float(int(qv >> 4) | int(((hb >> (j + 16 + c)) & 1) << 4)) * d + m;
865        }
866        a = half4(wa);
867        b = half4(wb);
868    }
869};
870template <> struct W8<T_Q5_0> {   // 22-byte blocks (2-aligned): the code bytes as ushorts; one d and one qh a pair
871    static inline void run(device const uchar* row, int k, threadgroup const uint*, thread half4& a, thread half4& b) {
872        device const uchar* bl = row + (k >> 5) * 22;
873        const float d = rdh(bl);
874        const uint hb = rd32(bl + 2);
875        const int j = k & 15;   // runs at j and j + 16: the low nibbles of qs[j..j+3], then the high ones
876        device const ushort* p = (device const ushort*)(bl + 6 + j);
877        const uint v = uint(p[0]) | (uint(p[1]) << 16);
878        float4 wa, wb;
879        for (int c = 0; c < 4; ++c) {
880            const uint qv = (v >> (8 * c)) & 0xFFu;
881            wa[c] = float((int(qv & 15) | int(((hb >> (j + c)) & 1) << 4)) - 16) * d;
882            wb[c] = float((int(qv >> 4) | int(((hb >> (j + 16 + c)) & 1) << 4)) - 16) * d;
883        }
884        a = half4(wa);
885        b = half4(wb);
886    }
887};
888template <> struct W8<T_Q6_K> {
889    static inline void run(device const uchar* row, int k, threadgroup const uint* tab, thread half4& a, thread half4& b) {
890        device const uchar* bl = row + (k >> 8) * 210;
891        const int j = k & 255, n = j >> 7, jj = j & 127, qd = jj >> 5, l = jj & 31;   // l < 16; the pair at l + 16
892        device const uchar* ql = bl + 64 * n + l + ((qd & 1) ? 32 : 0);
893        device const uchar* qh = bl + 128 + 32 * n + l;
894        const float d = rdh(bl + 208);
895        device const char* sc = (device const char*)(bl + 192 + 8 * n);
896        const float dsa = d * float(sc[2 * qd]), dsb = d * float(sc[1 + 2 * qd]);
897        // the 4-byte runs as two ushorts each (210-byte blocks: 2-aligned)
898        device const ushort* l2 = (device const ushort*)ql;
899        device const ushort* h2 = (device const ushort*)qh;
900        const uint la = uint(l2[0]) | (uint(l2[1]) << 16), lb = uint(l2[8]) | (uint(l2[9]) << 16);
901        const uint ha = uint(h2[0]) | (uint(h2[1]) << 16), hb = uint(h2[8]) | (uint(h2[9]) << 16);
902        const uint sl = (qd >> 1) ? 4u : 0u, shh = uint(2 * qd);
903        const uint4 qa = (uint4(as_type<uchar4>((la >> sl) & 0x0F0F0F0Fu)) | (uint4(as_type<uchar4>((ha >> shh) & 0x03030303u)) << 4));
904        const uint4 qb = (uint4(as_type<uchar4>((lb >> sl) & 0x0F0F0F0Fu)) | (uint4(as_type<uchar4>((hb >> shh) & 0x03030303u)) << 4));
905        a = half4(dsa * (float4(qa) - 32.0f));
906        b = half4(dsb * (float4(qb) - 32.0f));
907    }
908};
909
910template <int F, int TM, int TN, int TK, int SG>
911kernel void mm_gu3(device const uchar* W [[buffer(0)]], device const half* XS [[buffer(1)]],
912                   device half* HS [[buffer(2)]], device const int2* tiles [[buffer(3)]], constant MmArgs& a [[buffer(4)]], device const uint* smap [[buffer(5)]],
913                     device const uchar* W1 [[buffer(6)]], device const uchar* W2 [[buffer(7)]], device const uchar* W3 [[buffer(8)]],
914                   uint3 tg [[threadgroup_position_in_grid]], ushort sg [[simdgroup_index_in_threadgroup]],
915                   ushort lane [[thread_index_in_simdgroup]], ushort tid [[thread_index_in_threadgroup]]) {
916    threadgroup float ot[SG][TM * TN];
917    threadgroup uint tab[fmt<F>::TAB];
918    load_tab<F>(tab, tid, SG * 32);
919    threadgroup_barrier(mem_flags::mem_threadgroup);
920    const int2 tl = tiles[tg.y];
921    const int e = tl.x, row0 = tl.y, n0 = (int(tg.x) * SG + sg) * TN;
922    device const uchar* E = kArena ? arena_slot(smap[e], W, W1, W2, W3) : W + ulong(e) * a.gu_stride;
923    device const uchar* g0 = E + a.gate_off + ulong(n0) * a.gu_row;
924    device const uchar* u0 = E + a.up_off + ulong(n0) * a.gu_row;
925    constexpr auto desc = matmul2d_descriptor(TM, TN, TK, false, true, false, matmul2d_descriptor::mode::multiply_accumulate);
926    matmul2d<desc, execution_simdgroup> op;
927    tensor<device half, dextents<int32_t, 2>, tensor_inline> tX((device half*)XS, dextents<int32_t, 2>(a.n_embd, 1 << 30));
928    auto rg = op.template get_right_input_cooperative_tensor<half, half, float>();
929    auto ru = op.template get_right_input_cooperative_tensor<half, half, float>();
930    auto tA = tX.template slice<TK, TM>(0, row0);
931    auto accg = op.template get_destination_cooperative_tensor<__tensor_ops_detail::__remove_addrspace_t<decltype(tA)>, __tensor_ops_detail::__remove_addrspace_t<decltype(rg)>, float>();
932    auto accu = op.template get_destination_cooperative_tensor<__tensor_ops_detail::__remove_addrspace_t<decltype(tA)>, __tensor_ops_detail::__remove_addrspace_t<decltype(rg)>, float>();
933    for (uint16_t i = 0; i < accg.get_capacity(); ++i)
934        if (accg.is_valid_element(i)) { accg[i] = 0.0f; accu[i] = 0.0f; }
935    for (int k0 = 0; k0 < int(a.n_embd); k0 += TK) {
936        const uint16_t cap = rg.get_capacity(), half_cap = cap / 2;
937        if (!coop_k4) {
938            for (uint16_t i = 0; i < cap; ++i) {
939                const auto ix = rg.get_multidimensional_index(i);
940                const int k = k0 + ix[0], n = ix[1];
941                rg[i] = W4<F>::run(g0 + ulong(n) * a.gu_row, k & ~3, tab)[k & 3];
942                ru[i] = W4<F>::run(u0 + ulong(n) * a.gu_row, k & ~3, tab)[k & 3];
943            }
944        } else
945#pragma clang loop unroll(full)
946        for (uint16_t i = 0; i < half_cap; i += 4) {
947            const auto ix = rg.get_multidimensional_index(i);
948            const auto iy = rg.get_multidimensional_index(i + half_cap);
949            const int k = k0 + ix[0], n = ix[1];
950            device const uchar* rgw = g0 + ulong(n) * a.gu_row;
951            device const uchar* ruw = u0 + ulong(n) * a.gu_row;
952            half4 wg, wu, wg2, wu2;
953            if (mm_probe == 1) {   // the bench probe: no decode (constant weights)
954                wg = half4(half(n & 7)); wu = wg; wg2 = half4(half(k & 7)); wu2 = wg2;
955            } else if (TK == 32) {
956                // the lane's two runs of this row sit in one 32-group: element i + cap / 2 is (k + 16, n) - part of
957                // the COOP_K4 layout (coop_probe checks it); a runtime check of it here cost 30%
958                W8<F>::run(rgw, k, tab, wg, wg2);
959                W8<F>::run(ruw, k, tab, wu, wu2);
960            } else {
961                const int k2 = k0 + iy[0];
962                device const uchar* rgw2 = g0 + ulong(iy[1]) * a.gu_row;
963                device const uchar* ruw2 = u0 + ulong(iy[1]) * a.gu_row;
964                wg = W4<F>::run(rgw, k, tab); wu = W4<F>::run(ruw, k, tab);
965                wg2 = W4<F>::run(rgw2, k2, tab); wu2 = W4<F>::run(ruw2, k2, tab);
966            }
967            rg[i] = wg.x; rg[i + 1] = wg.y; rg[i + 2] = wg.z; rg[i + 3] = wg.w;
968            ru[i] = wu.x; ru[i + 1] = wu.y; ru[i + 2] = wu.z; ru[i + 3] = wu.w;
969            const uint16_t j = i + half_cap;
970            rg[j] = wg2.x; rg[j + 1] = wg2.y; rg[j + 2] = wg2.z; rg[j + 3] = wg2.w;
971            ru[j] = wu2.x; ru[j + 1] = wu2.y; ru[j + 2] = wu2.z; ru[j + 3] = wu2.w;
972        }
973        tA = tX.template slice<TK, TM>(k0, row0);
974        op.run(tA, rg, accg);
975        op.run(tA, ru, accu);
976    }
977    for (uint16_t i = 0; i < accg.get_capacity(); ++i)
978        if (accg.is_valid_element(i)) {
979            const float g = accg[i];
980            accg[i] = g / (1.0f + exp(-g)) * accu[i];
981        }
982    tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline> tO(ot[sg], dextents<int32_t, 2>(TN, TM));
983    accg.store(tO);
984    simdgroup_barrier(mem_flags::mem_threadgroup);
985    for (int it = lane; it < TM * TN; it += 32) {
986        const int m = it / TN, f = it - m * TN;
987        HS[ulong(row0 + m) * a.n_ff + n0 + f] = half(ot[sg][it]);
988    }
989}
990
991template <int F, int TM, int TN, int TK, int SG>
992kernel void mm_down3(device const uchar* W [[buffer(0)]], device const half* HS [[buffer(1)]],
993                     device float* YE [[buffer(2)]], device const int2* tiles [[buffer(3)]], constant MmArgs& a [[buffer(4)]], device const uint* smap [[buffer(5)]],
994                     device const uchar* W1 [[buffer(6)]], device const uchar* W2 [[buffer(7)]], device const uchar* W3 [[buffer(8)]],
995                     uint3 tg [[threadgroup_position_in_grid]], ushort sg [[simdgroup_index_in_threadgroup]],
996                     ushort tid [[thread_index_in_threadgroup]]) {
997    threadgroup uint tab[fmt<F>::TAB];
998    load_tab<F>(tab, tid, SG * 32);
999    threadgroup_barrier(mem_flags::mem_threadgroup);
1000    const int2 tl = tiles[tg.y];
1001    const int e = tl.x, row0 = tl.y, n0 = (int(tg.x) * SG + sg) * TN;
1002    device const uchar* w0 = (kArena ? arena_slot(smap[e], W, W1, W2, W3) : W + ulong(e) * a.d_stride) + a.down_off + ulong(n0) * a.d_row;
1003    constexpr auto desc = matmul2d_descriptor(TM, TN, TK, false, true, false, matmul2d_descriptor::mode::multiply_accumulate);
1004    matmul2d<desc, execution_simdgroup> op;
1005    tensor<device half, dextents<int32_t, 2>, tensor_inline> tH((device half*)HS, dextents<int32_t, 2>(a.n_ff, 1 << 30));
1006    auto rw = op.template get_right_input_cooperative_tensor<half, half, float>();
1007    auto tA = tH.template slice<TK, TM>(0, row0);
1008    auto acc = op.template get_destination_cooperative_tensor<__tensor_ops_detail::__remove_addrspace_t<decltype(tA)>, __tensor_ops_detail::__remove_addrspace_t<decltype(rw)>, float>();
1009    for (uint16_t i = 0; i < acc.get_capacity(); ++i)
1010        if (acc.is_valid_element(i)) acc[i] = 0.0f;
1011    for (int k0 = 0; k0 < int(a.n_ff); k0 += TK) {
1012        if (!coop_k4) {
1013            for (uint16_t i = 0; i < rw.get_capacity(); ++i) {
1014                const auto ix = rw.get_multidimensional_index(i);
1015                const int k = k0 + ix[0];
1016                rw[i] = W4<F>::run(w0 + ulong(ix[1]) * a.d_row, k & ~3, tab)[k & 3];
1017            }
1018        } else if (TK == 32) {
1019            // the paired runs (element i + cap / 2 is (k + 16, n), the COOP_K4 layout): one W8 a pair
1020            const uint16_t half_cap = rw.get_capacity() / 2;
1021#pragma clang loop unroll(full)
1022            for (uint16_t i = 0; i < half_cap; i += 4) {
1023                const auto ix = rw.get_multidimensional_index(i);
1024                half4 w, w2;
1025                W8<F>::run(w0 + ulong(ix[1]) * a.d_row, k0 + ix[0], tab, w, w2);
1026                rw[i] = w.x; rw[i + 1] = w.y; rw[i + 2] = w.z; rw[i + 3] = w.w;
1027                const uint16_t j = i + half_cap;
1028                rw[j] = w2.x; rw[j + 1] = w2.y; rw[j + 2] = w2.z; rw[j + 3] = w2.w;
1029            }
1030        } else
1031#pragma clang loop unroll(full)
1032        for (uint16_t i = 0; i < rw.get_capacity(); i += 4) {
1033            const auto ix = rw.get_multidimensional_index(i);
1034            const half4 w = W4<F>::run(w0 + ulong(ix[1]) * a.d_row, k0 + ix[0], tab);
1035            rw[i] = w.x; rw[i + 1] = w.y; rw[i + 2] = w.z; rw[i + 3] = w.w;
1036        }
1037        tA = tH.template slice<TK, TM>(k0, row0);
1038        op.run(tA, rw, acc);
1039    }
1040    tensor<device float, dextents<int32_t, 2>, tensor_inline> tY(YE, dextents<int32_t, 2>(a.n_embd, 1 << 30));
1041    acc.store(tY.slice(n0, row0));
1042}
1043
1044#define MMGU3_(F, M, N, K, S) template [[host_name("mm_gu3_" #F "_" #M "_" #N "_" #K "_" #S)]] kernel decltype(mm_gu3<F, M, N, K, S>) mm_gu3<F, M, N, K, S>;
1045#define MMDN3_(F, M, N, K, S) template [[host_name("mm_down3_" #F "_" #M "_" #N "_" #K "_" #S)]] kernel decltype(mm_down3<F, M, N, K, S>) mm_down3<F, M, N, K, S>;
1046#define MMGU3(F, M, N, K, S) MMGU3_(F, M, N, K, S)
1047#define MMDN3(F, M, N, K, S) MMDN3_(F, M, N, K, S)
1048#define MM3_ONE(F, M, N, K, S) MMGU3(F, M, N, K, S) MMDN3(F, M, N, K, S)
1049#define MM3_GU(F) MMGU3(F, 16, 64, 32, 2) MMGU3(F, 16, 32, 32, 4) MMGU3(F, 32, 64, 32, 2) MMGU3(F, 16, 64, 64, 2) \
1050    MMGU3(F, 16, 32, 16, 2) MMGU3(F, 32, 32, 32, 2) MMGU3(F, 16, 64, 32, 1) MMGU3(F, 16, 64, 32, 4)     MMGU3(F, 16, 32, 16, 4) MMGU3(F, 16, 32, 32, 5) MMGU3(F, 16, 32, 16, 5) MMGU3(F, 16, 16, 32, 4) MMGU3(F, 16, 16, 32, 8)     MMGU3(F, 16, 16, 16, 8)
1051#define MM3_DN(F) MMDN3(F, 16, 64, 32, 2) MMDN3(F, 16, 32, 32, 4) MMDN3(F, 32, 64, 32, 2) MMDN3(F, 16, 64, 64, 2) \
1052    MMDN3(F, 16, 32, 16, 2) MMDN3(F, 32, 32, 32, 2) MMDN3(F, 16, 64, 32, 1) MMDN3(F, 16, 64, 32, 4)     MMDN3(F, 16, 64, 16, 2) MMDN3(F, 16, 32, 16, 4) MMDN3(F, 16, 64, 32, 5) MMDN3(F, 16, 64, 16, 4)
1053MM3_GU(T_Q4_K) MM3_GU(T_Q5_K) MM3_GU(T_Q6_K) MM3_GU(T_Q8_0) MM3_GU(T_IQ4_XS) MM3_GU(T_Q2_0) MM3_GU(T_IQ3_XXS) MM3_GU(T_IQ2_XXS) MM3_GU(T_IQ2_XS) MM3_GU(T_IQ2_S) MM3_GU(T_IQ3_S)
1054MM3_DN(T_Q2_0) MM3_DN(T_IQ4_NL) MM3_DN(T_Q5_1) MM3_DN(T_Q5_0) MM3_DN(T_Q8_0)
1055#ifdef STRATA_KQ_DOWN
1056MM3_DN(T_Q4_K) MM3_DN(T_Q5_K) MM3_DN(T_Q6_K) MM3_DN(T_Q3_K) MM3_DN(T_IQ4_XS) MM3_DN(T_IQ3_S)
1057#endif
1058
1059// mm_gu4: mm_gu3 with each decoded right operand (TN x TK weights of gate and of up) applied to MS 16-row token
1060// tiles (a tile of 16 * MS rows from the plan, tm = 16 * MS): the decode, which bounds mm_gu3, is shared by MS times
1061// as many token rows (more padding rows per expert, but the matrix ops are cheap next to the decode).  The same
1062// per-row arithmetic as mm_gu3 (each 16-row op is mm_gu3's): bitwise for the rows both compute.  COOP_K4 layout only.
1063template <int F, int MS, int TN, int TK, int SG>
1064kernel void mm_gu4(device const uchar* W [[buffer(0)]], device const half* XS [[buffer(1)]],
1065                   device half* HS [[buffer(2)]], device const int2* tiles [[buffer(3)]], constant MmArgs& a [[buffer(4)]],
1066                   uint3 tg [[threadgroup_position_in_grid]], ushort sg [[simdgroup_index_in_threadgroup]],
1067                   ushort lane [[thread_index_in_simdgroup]], ushort tid [[thread_index_in_threadgroup]]) {
1068    constexpr int TM = 16;
1069    threadgroup float ot[SG][TM * TN];
1070    threadgroup uint tab[fmt<F>::TAB];
1071    load_tab<F>(tab, tid, SG * 32);
1072    threadgroup_barrier(mem_flags::mem_threadgroup);
1073    const int2 tl = tiles[tg.y];
1074    const int e = tl.x, row0 = tl.y, n0 = (int(tg.x) * SG + sg) * TN;
1075    device const uchar* g0 = W + a.gate_off + ulong(e) * a.gu_stride + ulong(n0) * a.gu_row;
1076    device const uchar* u0 = W + a.up_off + ulong(e) * a.gu_stride + ulong(n0) * a.gu_row;
1077    constexpr auto desc = matmul2d_descriptor(TM, TN, TK, false, true, false, matmul2d_descriptor::mode::multiply_accumulate);
1078    matmul2d<desc, execution_simdgroup> op;
1079    tensor<device half, dextents<int32_t, 2>, tensor_inline> tX((device half*)XS, dextents<int32_t, 2>(a.n_embd, 1 << 30));
1080    auto rg = op.template get_right_input_cooperative_tensor<half, half, float>();
1081    auto ru = op.template get_right_input_cooperative_tensor<half, half, float>();
1082    auto tA0 = tX.template slice<TK, TM>(0, row0);
1083    auto tA1 = tX.template slice<TK, TM>(0, row0 + TM);
1084#define MM4_DST op.template get_destination_cooperative_tensor<__tensor_ops_detail::__remove_addrspace_t<decltype(tA0)>,                                                                __tensor_ops_detail::__remove_addrspace_t<decltype(rg)>, float>()
1085    auto accg0 = MM4_DST;
1086    auto accu0 = MM4_DST;
1087    auto accg1 = MM4_DST;
1088    auto accu1 = MM4_DST;
1089#undef MM4_DST
1090    using DT = decltype(accg0);
1091    for (uint16_t i = 0; i < accg0.get_capacity(); ++i)
1092        if (accg0.is_valid_element(i)) { accg0[i] = 0.0f; accu0[i] = 0.0f; accg1[i] = 0.0f; accu1[i] = 0.0f; }
1093    for (int k0 = 0; k0 < int(a.n_embd); k0 += TK) {
1094        const uint16_t cap = rg.get_capacity(), half_cap = cap / 2;
1095#pragma clang loop unroll(full)
1096        for (uint16_t i = 0; i < half_cap; i += 4) {
1097            const auto ix = rg.get_multidimensional_index(i);
1098            const int k = k0 + ix[0], n = ix[1];
1099            device const uchar* rgw = g0 + ulong(n) * a.gu_row;
1100            device const uchar* ruw = u0 + ulong(n) * a.gu_row;
1101            half4 wg, wu, wg2, wu2;
1102            W8<F>::run(rgw, k, tab, wg, wg2);
1103            W8<F>::run(ruw, k, tab, wu, wu2);
1104            rg[i] = wg.x; rg[i + 1] = wg.y; rg[i + 2] = wg.z; rg[i + 3] = wg.w;
1105            ru[i] = wu.x; ru[i + 1] = wu.y; ru[i + 2] = wu.z; ru[i + 3] = wu.w;
1106            const uint16_t j = i + half_cap;
1107            rg[j] = wg2.x; rg[j + 1] = wg2.y; rg[j + 2] = wg2.z; rg[j + 3] = wg2.w;
1108            ru[j] = wu2.x; ru[j + 1] = wu2.y; ru[j + 2] = wu2.z; ru[j + 3] = wu2.w;
1109        }
1110        tA0 = tX.template slice<TK, TM>(k0, row0);
1111        op.run(tA0, rg, accg0);
1112        op.run(tA0, ru, accu0);
1113        if (MS > 1) {
1114            tA1 = tX.template slice<TK, TM>(k0, row0 + TM);
1115            op.run(tA1, rg, accg1);
1116            op.run(tA1, ru, accu1);
1117        }
1118    }
1119    for (int s = 0; s < MS; ++s) {
1120        thread DT& ag = s == 0 ? accg0 : accg1;
1121        thread DT& au = s == 0 ? accu0 : accu1;
1122        for (uint16_t i = 0; i < ag.get_capacity(); ++i)
1123            if (ag.is_valid_element(i)) {
1124                const float g = ag[i];
1125                ag[i] = g / (1.0f + exp(-g)) * au[i];
1126            }
1127        tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline> tO(ot[sg], dextents<int32_t, 2>(TN, TM));
1128        simdgroup_barrier(mem_flags::mem_threadgroup);
1129        ag.store(tO);
1130        simdgroup_barrier(mem_flags::mem_threadgroup);
1131        for (int it = lane; it < TM * TN; it += 32) {
1132            const int m = it / TN, f = it - m * TN;
1133            HS[ulong(row0 + s * TM + m) * a.n_ff + n0 + f] = half(ot[sg][it]);
1134        }
1135    }
1136}
1137#define MMGU4_(F, M, N, K, S) template [[host_name("mm_gu4_" #F "_" #M "_" #N "_" #K "_" #S)]] kernel decltype(mm_gu4<F, M, N, K, S>) mm_gu4<F, M, N, K, S>;
1138#define MMGU4(F, M, N, K, S) MMGU4_(F, M, N, K, S)
1139#define MM4_GU(F) MMGU4(F, 2, 32, 32, 4) MMGU4(F, 2, 32, 32, 2) MMGU4(F, 2, 16, 32, 4) MMGU4(F, 1, 32, 32, 4)
1140MM4_GU(T_Q2_0) MM4_GU(T_IQ3_XXS) MM4_GU(T_IQ2_XXS) MM4_GU(T_IQ2_XS) MM4_GU(T_IQ2_S) MM4_GU(T_IQ3_S) MM4_GU(T_IQ4_XS)
1141
1142// mm_gu5: mm_gu3 (COOP_K4 layout, TK 32) with the threadgroup's weight rows staged block by block (QK = 256 values a
1143// row, gate and up) into threadgroup memory by coalesced ushort loads, the lanes decoding from there: the decode's
1144// many small scattered device loads (2-6 a run) become threadgroup reads.  Same decoded values and the same matrix
1145// ops as mm_gu3: bitwise.  Formats with 256-value blocks and a templated W8 (IQ3_S, IQ3_XXS, IQ2_S).
1146template <int F, int TN, int SG>
1147kernel void mm_gu5(device const uchar* W [[buffer(0)]], device const half* XS [[buffer(1)]],
1148                   device half* HS [[buffer(2)]], device const int2* tiles [[buffer(3)]], constant MmArgs& a [[buffer(4)]],
1149                   uint3 tg [[threadgroup_position_in_grid]], ushort sg [[simdgroup_index_in_threadgroup]],
1150                   ushort lane [[thread_index_in_simdgroup]], ushort tid [[thread_index_in_threadgroup]]) {
1151    constexpr int TM = 16, TK = 32, BB = fmt<F>::BB, ROWS = SG * TN, RU = BB / 2;
1152    threadgroup float ot[SG][TM * TN];
1153    threadgroup uint tab[fmt<F>::TAB];
1154    threadgroup ushort stg[2][ROWS * RU];
1155    load_tab<F>(tab, tid, SG * 32);
1156    const int2 tl = tiles[tg.y];
1157    const int e = tl.x, row0 = tl.y, nt0 = int(tg.x) * ROWS, n0 = nt0 + sg * TN;
1158    device const uchar* gt = W + a.gate_off + ulong(e) * a.gu_stride + ulong(nt0) * a.gu_row;
1159    device const uchar* ut = W + a.up_off + ulong(e) * a.gu_stride + ulong(nt0) * a.gu_row;
1160    constexpr auto desc = matmul2d_descriptor(TM, TN, TK, false, true, false, matmul2d_descriptor::mode::multiply_accumulate);
1161    matmul2d<desc, execution_simdgroup> op;
1162    tensor<device half, dextents<int32_t, 2>, tensor_inline> tX((device half*)XS, dextents<int32_t, 2>(a.n_embd, 1 << 30));
1163    auto rg = op.template get_right_input_cooperative_tensor<half, half, float>();
1164    auto ru = op.template get_right_input_cooperative_tensor<half, half, float>();
1165    auto tA = tX.template slice<TK, TM>(0, row0);
1166    auto accg = op.template get_destination_cooperative_tensor<__tensor_ops_detail::__remove_addrspace_t<decltype(tA)>, __tensor_ops_detail::__remove_addrspace_t<decltype(rg)>, float>();
1167    auto accu = op.template get_destination_cooperative_tensor<__tensor_ops_detail::__remove_addrspace_t<decltype(tA)>, __tensor_ops_detail::__remove_addrspace_t<decltype(rg)>, float>();
1168    for (uint16_t i = 0; i < accg.get_capacity(); ++i)
1169        if (accg.is_valid_element(i)) { accg[i] = 0.0f; accu[i] = 0.0f; }
1170    const int NB = int(a.n_embd) / 256;
1171    for (int kb = 0; kb < NB; ++kb) {
1172        threadgroup_barrier(mem_flags::mem_threadgroup);
1173        for (int idx = tid; idx < ROWS * RU; idx += SG * 32) {
1174            const int r = idx / RU, w = idx - r * RU;
1175            stg[0][idx] = ((device const ushort*)(gt + ulong(r) * a.gu_row + kb * BB))[w];
1176            stg[1][idx] = ((device const ushort*)(ut + ulong(r) * a.gu_row + kb * BB))[w];
1177        }
1178        threadgroup_barrier(mem_flags::mem_threadgroup);
1179        for (int ks = 0; ks < 8; ++ks) {
1180            const int k0 = kb * 256 + ks * TK;
1181            const uint16_t half_cap = rg.get_capacity() / 2;
1182#pragma clang loop unroll(full)
1183            for (uint16_t i = 0; i < half_cap; i += 4) {
1184                const auto ix = rg.get_multidimensional_index(i);
1185                const int kl = ks * TK + ix[0], n = sg * TN + ix[1];
1186                // the block's row in the stage; W8 indexes block (k >> 8) = 0 of it with k = kl
1187                threadgroup const uchar* rgw = (threadgroup const uchar*)(stg[0] + n * RU);
1188                threadgroup const uchar* ruw = (threadgroup const uchar*)(stg[1] + n * RU);
1189                half4 wg, wu, wg2, wu2;
1190                W8<F>::run(rgw, kl, tab, wg, wg2);
1191                W8<F>::run(ruw, kl, tab, wu, wu2);
1192                rg[i] = wg.x; rg[i + 1] = wg.y; rg[i + 2] = wg.z; rg[i + 3] = wg.w;
1193                ru[i] = wu.x; ru[i + 1] = wu.y; ru[i + 2] = wu.z; ru[i + 3] = wu.w;
1194                const uint16_t j = i + half_cap;
1195                rg[j] = wg2.x; rg[j + 1] = wg2.y; rg[j + 2] = wg2.z; rg[j + 3] = wg2.w;
1196                ru[j] = wu2.x; ru[j + 1] = wu2.y; ru[j + 2] = wu2.z; ru[j + 3] = wu2.w;
1197            }
1198            tA = tX.template slice<TK, TM>(k0, row0);
1199            op.run(tA, rg, accg);
1200            op.run(tA, ru, accu);
1201        }
1202    }
1203    for (uint16_t i = 0; i < accg.get_capacity(); ++i)
1204        if (accg.is_valid_element(i)) {
1205            const float g = accg[i];
1206            accg[i] = g / (1.0f + exp(-g)) * accu[i];
1207        }
1208    tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline> tO(ot[sg], dextents<int32_t, 2>(TN, TM));
1209    accg.store(tO);
1210    simdgroup_barrier(mem_flags::mem_threadgroup);
1211    for (int it = lane; it < TM * TN; it += 32) {
1212        const int m = it / TN, f = it - m * TN;
1213        HS[ulong(row0 + m) * a.n_ff + n0 + f] = half(ot[sg][it]);
1214    }
1215}
1216#define MMGU5_(F, N, S) template [[host_name("mm_gu5_" #F "_" #N "_" #S)]] kernel decltype(mm_gu5<F, N, S>) mm_gu5<F, N, S>;
1217#define MMGU5(F, N, S) MMGU5_(F, N, S)
1218MMGU5(T_IQ3_S, 32, 2) MMGU5(T_IQ3_S, 32, 1) MMGU5(T_IQ3_S, 16, 4) MMGU5(T_IQ3_XXS, 32, 2) MMGU5(T_IQ3_XXS, 32, 1)
1219MMGU5(T_IQ3_XXS, 16, 4) MMGU5(T_IQ2_S, 32, 2) MMGU5(T_IQ2_S, 32, 1) MMGU5(T_IQ2_S, 16, 4)
1220
1221// ---- v6: ragged tiles.  A tile of the plan is a GROUP of up to MS consecutive 16-row subtiles of ONE expert (the expert's
1222// run is still padded only to 16 rows): the weights of a TN x TK block are decoded ONCE per k step and multiplied with every
1223// subtile of the group, so the decode (which bounds mm_gu3 / mm_down3: 59% of the Q4_K gate/up time with the decode
1224// removed, MM_PROBE 1) is shared by up to 16 * MS token rows without the padding of a taller plan tile.  Each subtile is an
1225// independent 16-row matmul2d accumulation over the same k sequence, so every output is bitwise mm_gu3's / mm_down3's.
1226//   mm_scan6   mm_scan's plan with groups: tiles[i] = (expert | nsub << 16, first padded row); eoff / rows count whole
1227//              16-row subtiles; meta as mm_scan's (meta[3] / meta[6] = the number of groups)
1228kernel void mm_scan6(device const uint* bcnt [[buffer(0)]], device uint* boff [[buffer(1)]],
1229                     device uint* eoff [[buffer(2)]], device int2* tiles [[buffer(3)]], device uint* meta [[buffer(4)]],
1230                     constant MmPlanArgs& a [[buffer(5)]],
1231                     ushort tid [[thread_index_in_threadgroup]], ushort sg [[simdgroup_index_in_threadgroup]],
1232                     ushort lane [[thread_index_in_simdgroup]]) {
1233    threadgroup uint s_rows[32], s_tiles[32];
1234    const uint ms = a.tm;   // here tm = the group size in 16-row subtiles
1235    if (tid < 32) { s_rows[tid] = 0; s_tiles[tid] = 0; }
1236    threadgroup_barrier(mem_flags::mem_threadgroup);
1237    const uint e = tid;
1238    uint tot = 0;
1239    if (e < a.n_expert)
1240        for (uint b = 0; b < a.n_blocks; ++b) {
1241            boff[b * a.n_expert + e] = tot;
1242            tot += bcnt[b * a.n_expert + e];
1243        }
1244    const uint nsub = (tot + 15) / 16, rows = nsub * 16, nt = (nsub + ms - 1) / ms;
1245    const uint pr = simd_prefix_exclusive_sum(rows), pt = simd_prefix_exclusive_sum(nt);
1246    if (lane == 31) { s_rows[sg] = pr + rows; s_tiles[sg] = pt + nt; }
1247    threadgroup_barrier(mem_flags::mem_threadgroup);
1248    uint orow = 0, otile = 0, all_rows = 0, all_tiles = 0;
1249    for (int i = 0; i < 32; ++i) {
1250        if (i < int(sg)) { orow += s_rows[i]; otile += s_tiles[i]; }
1251        all_rows += s_rows[i];
1252        all_tiles += s_tiles[i];
1253    }
1254    if (e < a.n_expert) {
1255        const uint r0 = orow + pr, t0 = otile + pt;
1256        eoff[e] = r0;
1257        for (uint k = 0; k < nt; ++k) {
1258            const uint n = min(ms, nsub - k * ms);
1259            tiles[t0 + k] = int2(int(e | (n << 16)), int(r0 + k * ms * 16));
1260        }
1261    }
1262    if (tid == 0) {
1263        meta[0] = all_tiles;
1264        meta[1] = all_rows;
1265        meta[3] = all_tiles;
1266        meta[4] = 1;
1267        meta[6] = all_tiles;
1268        meta[7] = 1;
1269        meta[8] = all_rows;
1270        meta[9] = 1;
1271        meta[10] = 1;
1272    }
1273}
1274
1275template <int F, int MS, int TN, int TK, int SG>
1276kernel void mm_gu6(device const uchar* W [[buffer(0)]], device const half* XS [[buffer(1)]],
1277                   device half* HS [[buffer(2)]], device const int2* tiles [[buffer(3)]], constant MmArgs& a [[buffer(4)]],
1278                   uint3 tg [[threadgroup_position_in_grid]], ushort sg [[simdgroup_index_in_threadgroup]],
1279                   ushort lane [[thread_index_in_simdgroup]], ushort tid [[thread_index_in_threadgroup]]) {
1280    constexpr int TM = 16;
1281    threadgroup float ot[SG][TM * TN];
1282    threadgroup uint tab[fmt<F>::TAB];
1283    load_tab<F>(tab, tid, SG * 32);
1284    threadgroup_barrier(mem_flags::mem_threadgroup);
1285    const int2 tl = tiles[tg.y];
1286    const int e = tl.x & 0xFFFF, nsub = tl.x >> 16, row0 = tl.y, n0 = (int(tg.x) * SG + sg) * TN;
1287    device const uchar* E = W + ulong(e) * a.gu_stride;
1288    device const uchar* g0 = E + a.gate_off + ulong(n0) * a.gu_row;
1289    device const uchar* u0 = E + a.up_off + ulong(n0) * a.gu_row;
1290    constexpr auto desc = matmul2d_descriptor(TM, TN, TK, false, true, false, matmul2d_descriptor::mode::multiply_accumulate);
1291    matmul2d<desc, execution_simdgroup> op;
1292    tensor<device half, dextents<int32_t, 2>, tensor_inline> tX((device half*)XS, dextents<int32_t, 2>(a.n_embd, 1 << 30));
1293    auto rg = op.template get_right_input_cooperative_tensor<half, half, float>();
1294    auto ru = op.template get_right_input_cooperative_tensor<half, half, float>();
1295    auto tA = tX.template slice<TK, TM>(0, row0);
1296#define MM6_DST op.template get_destination_cooperative_tensor<__tensor_ops_detail::__remove_addrspace_t<decltype(tA)>, __tensor_ops_detail::__remove_addrspace_t<decltype(rg)>, float>()
1297    auto accg0 = MM6_DST;
1298    auto accu0 = MM6_DST;
1299    auto accg1 = MM6_DST;
1300    auto accu1 = MM6_DST;
1301    auto accg2 = MM6_DST;
1302    auto accu2 = MM6_DST;
1303    auto accg3 = MM6_DST;
1304    auto accu3 = MM6_DST;
1305#undef MM6_DST
1306    for (uint16_t i = 0; i < accg0.get_capacity(); ++i)
1307        if (accg0.is_valid_element(i)) {
1308            accg0[i] = 0.0f; accu0[i] = 0.0f;
1309            if (MS > 1) { accg1[i] = 0.0f; accu1[i] = 0.0f; }
1310            if (MS > 2) { accg2[i] = 0.0f; accu2[i] = 0.0f; }
1311            if (MS > 3) { accg3[i] = 0.0f; accu3[i] = 0.0f; }
1312        }
1313    for (int k0 = 0; k0 < int(a.n_embd); k0 += TK) {
1314        const uint16_t cap = rg.get_capacity(), half_cap = cap / 2;
1315#pragma clang loop unroll(full)
1316        for (uint16_t i = 0; i < half_cap; i += 4) {
1317            const auto ix = rg.get_multidimensional_index(i);
1318            const int k = k0 + ix[0], n = ix[1];
1319            half4 wg, wu, wg2, wu2;
1320            W8<F>::run(g0 + ulong(n) * a.gu_row, k, tab, wg, wg2);
1321            W8<F>::run(u0 + ulong(n) * a.gu_row, k, tab, wu, wu2);
1322            rg[i] = wg.x; rg[i + 1] = wg.y; rg[i + 2] = wg.z; rg[i + 3] = wg.w;
1323            ru[i] = wu.x; ru[i + 1] = wu.y; ru[i + 2] = wu.z; ru[i + 3] = wu.w;
1324            const uint16_t j = i + half_cap;
1325            rg[j] = wg2.x; rg[j + 1] = wg2.y; rg[j + 2] = wg2.z; rg[j + 3] = wg2.w;
1326            ru[j] = wu2.x; ru[j + 1] = wu2.y; ru[j + 2] = wu2.z; ru[j + 3] = wu2.w;
1327        }
1328        tA = tX.template slice<TK, TM>(k0, row0);
1329        op.run(tA, rg, accg0);
1330        op.run(tA, ru, accu0);
1331        if (MS > 1 && nsub > 1) {
1332            tA = tX.template slice<TK, TM>(k0, row0 + 16);
1333            op.run(tA, rg, accg1);
1334            op.run(tA, ru, accu1);
1335        }
1336        if (MS > 2 && nsub > 2) {
1337            tA = tX.template slice<TK, TM>(k0, row0 + 32);
1338            op.run(tA, rg, accg2);
1339            op.run(tA, ru, accu2);
1340        }
1341        if (MS > 3 && nsub > 3) {
1342            tA = tX.template slice<TK, TM>(k0, row0 + 48);
1343            op.run(tA, rg, accg3);
1344            op.run(tA, ru, accu3);
1345        }
1346    }
1347    tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline> tO(ot[sg], dextents<int32_t, 2>(TN, TM));
1348#define MM6_OUT(S, AG, AU) \
1349    if (MS > S && nsub > S) { \
1350        for (uint16_t i = 0; i < AG.get_capacity(); ++i) \
1351            if (AG.is_valid_element(i)) { const float g = AG[i]; AG[i] = g / (1.0f + exp(-g)) * AU[i]; } \
1352        simdgroup_barrier(mem_flags::mem_threadgroup); \
1353        AG.store(tO); \
1354        simdgroup_barrier(mem_flags::mem_threadgroup); \
1355        for (int it = lane; it < TM * TN; it += 32) { \
1356            const int m = it / TN, f = it - m * TN; \
1357            HS[ulong(row0 + S * 16 + m) * a.n_ff + n0 + f] = half(ot[sg][it]); \
1358        } \
1359    }
1360    MM6_OUT(0, accg0, accu0)
1361    MM6_OUT(1, accg1, accu1)
1362    MM6_OUT(2, accg2, accu2)
1363    MM6_OUT(3, accg3, accu3)
1364#undef MM6_OUT
1365}
1366
1367template <int F, int MS, int TN, int TK, int SG>
1368kernel void mm_down6(device const uchar* W [[buffer(0)]], device const half* HS [[buffer(1)]],
1369                     device float* YE [[buffer(2)]], device const int2* tiles [[buffer(3)]], constant MmArgs& a [[buffer(4)]],
1370                     uint3 tg [[threadgroup_position_in_grid]], ushort sg [[simdgroup_index_in_threadgroup]],
1371                     ushort tid [[thread_index_in_threadgroup]]) {
1372    constexpr int TM = 16;
1373    threadgroup uint tab[fmt<F>::TAB];
1374    load_tab<F>(tab, tid, SG * 32);
1375    threadgroup_barrier(mem_flags::mem_threadgroup);
1376    const int2 tl = tiles[tg.y];
1377    const int e = tl.x & 0xFFFF, nsub = tl.x >> 16, row0 = tl.y, n0 = (int(tg.x) * SG + sg) * TN;
1378    device const uchar* w0 = W + ulong(e) * a.d_stride + a.down_off + ulong(n0) * a.d_row;
1379    constexpr auto desc = matmul2d_descriptor(TM, TN, TK, false, true, false, matmul2d_descriptor::mode::multiply_accumulate);
1380    matmul2d<desc, execution_simdgroup> op;
1381    tensor<device half, dextents<int32_t, 2>, tensor_inline> tH((device half*)HS, dextents<int32_t, 2>(a.n_ff, 1 << 30));
1382    auto rw = op.template get_right_input_cooperative_tensor<half, half, float>();
1383    auto tA = tH.template slice<TK, TM>(0, row0);
1384#define MM6_DST op.template get_destination_cooperative_tensor<__tensor_ops_detail::__remove_addrspace_t<decltype(tA)>, __tensor_ops_detail::__remove_addrspace_t<decltype(rw)>, float>()
1385    auto acc0 = MM6_DST;
1386    auto acc1 = MM6_DST;
1387    auto acc2 = MM6_DST;
1388    auto acc3 = MM6_DST;
1389#undef MM6_DST
1390    for (uint16_t i = 0; i < acc0.get_capacity(); ++i)
1391        if (acc0.is_valid_element(i)) {
1392            acc0[i] = 0.0f;
1393            if (MS > 1) acc1[i] = 0.0f;
1394            if (MS > 2) acc2[i] = 0.0f;
1395            if (MS > 3) acc3[i] = 0.0f;
1396        }
1397    for (int k0 = 0; k0 < int(a.n_ff); k0 += TK) {
1398        const uint16_t half_cap = rw.get_capacity() / 2;
1399#pragma clang loop unroll(full)
1400        for (uint16_t i = 0; i < half_cap; i += 4) {
1401            const auto ix = rw.get_multidimensional_index(i);
1402            half4 w, w2;
1403            W8<F>::run(w0 + ulong(ix[1]) * a.d_row, k0 + ix[0], tab, w, w2);
1404            rw[i] = w.x; rw[i + 1] = w.y; rw[i + 2] = w.z; rw[i + 3] = w.w;
1405            const uint16_t j = i + half_cap;
1406            rw[j] = w2.x; rw[j + 1] = w2.y; rw[j + 2] = w2.z; rw[j + 3] = w2.w;
1407        }
1408        tA = tH.template slice<TK, TM>(k0, row0);
1409        op.run(tA, rw, acc0);
1410        if (MS > 1 && nsub > 1) { tA = tH.template slice<TK, TM>(k0, row0 + 16); op.run(tA, rw, acc1); }
1411        if (MS > 2 && nsub > 2) { tA = tH.template slice<TK, TM>(k0, row0 + 32); op.run(tA, rw, acc2); }
1412        if (MS > 3 && nsub > 3) { tA = tH.template slice<TK, TM>(k0, row0 + 48); op.run(tA, rw, acc3); }
1413    }
1414    tensor<device float, dextents<int32_t, 2>, tensor_inline> tY(YE, dextents<int32_t, 2>(a.n_embd, 1 << 30));
1415    acc0.store(tY.slice(n0, row0));
1416    if (MS > 1 && nsub > 1) acc1.store(tY.slice(n0, row0 + 16));
1417    if (MS > 2 && nsub > 2) acc2.store(tY.slice(n0, row0 + 32));
1418    if (MS > 3 && nsub > 3) acc3.store(tY.slice(n0, row0 + 48));
1419}
1420
1421#define MMGU6_(F, M, N, K, S) template [[host_name("mm_gu6_" #F "_" #M "_" #N "_" #K "_" #S)]] kernel decltype(mm_gu6<F, M, N, K, S>) mm_gu6<F, M, N, K, S>;
1422#define MMDN6_(F, M, N, K, S) template [[host_name("mm_down6_" #F "_" #M "_" #N "_" #K "_" #S)]] kernel decltype(mm_down6<F, M, N, K, S>) mm_down6<F, M, N, K, S>;
1423#define MMGU6(F, M, N, K, S) MMGU6_(F, M, N, K, S)
1424#define MMDN6(F, M, N, K, S) MMDN6_(F, M, N, K, S)
1425#define MM6_GU(F) MMGU6(F, 2, 32, 32, 4) MMGU6(F, 3, 32, 32, 4) MMGU6(F, 4, 32, 32, 4) MMGU6(F, 4, 32, 32, 2) MMGU6(F, 4, 16, 32, 4)
1426#define MM6_DN(F) MMDN6(F, 2, 64, 32, 2) MMDN6(F, 3, 64, 32, 2) MMDN6(F, 4, 64, 32, 2) MMDN6(F, 4, 32, 32, 4) MMDN6(F, 4, 32, 32, 2)
1427MM6_GU(T_Q4_K) MM6_GU(T_Q5_K)
1428MM6_DN(T_Q5_1) MM6_DN(T_Q8_0)
1429// the other sets' types (UD-IQ4_XS-v31, IQ3_S): the one tile shape the engine uses (MS 4; gate/up TN 16, down TN 32, SG 4)
1430#define MM6_GU1(F) MMGU6(F, 4, 16, 32, 4)
1431#define MM6_DN1(F) MMDN6(F, 4, 32, 32, 4)
1432MM6_GU1(T_Q6_K) MM6_GU1(T_Q8_0) MM6_GU1(T_IQ3_XXS) MM6_GU1(T_IQ2_S) MM6_GU1(T_IQ4_XS) MM6_GU1(T_IQ3_S) MM6_GU1(T_IQ2_XS) MM6_GU1(T_IQ2_XXS)
1433MM6_DN1(T_Q5_0) MM6_DN1(T_IQ4_NL) MM6_DN1(T_Q2_0)
1434#ifdef STRATA_KQ_DOWN
1435MM6_DN1(T_Q4_K) MM6_DN1(T_Q5_K) MM6_DN1(T_Q6_K) MM6_DN1(T_Q3_K) MM6_DN1(T_IQ4_XS) MM6_DN1(T_IQ3_S)
1436#endif