okami.mom/strata

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

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

main
31.4 KiB598 linesraw
1// metal/kernels/moe.metal - routed experts of one layer for a verify window of 1..8 tokens, grouped by expert:
2//
3//   moe_plan    one threadgroup: the window's top-k ids -> groups (distinct experts, by id) with their entries
4//               (token, weight), each (token, k)'s entry index, and the indirect grid sizes of the next two kernels.
5//               Deterministic (no atomics).
6//   moe_gu      per group, a block of FFN rows: gate and up rows read once, applied to every entry of the group
7//               (the shared input x is read from cache), h = silu(gate) * up per entry.
8//   moe_down    per group, a block of output rows: ye[entry] = weight * (down . h[entry]).
9//   moe_combine y[token] = sum over k of ye[entry(token, k)], in k order.
10//
11// The plan is one int buffer (see P_* below).  Expert addressing: MoeArgs (a pack blob or the GGUF tensors):
12// [gate rows | up rows | down rows] in GGUF blocks (tools/iq_pack.py's experts.bin layout).
13
14#define P_NG 0
15#define P_IGU 4
16#define P_IDN 8
17#define P_MAXE 128
18#define P_GEXP 16
19#define P_GSTART (P_GEXP + P_MAXE)
20#define P_ETOK (P_GSTART + P_MAXE + 4)
21#define P_EW (P_ETOK + P_MAXE)
22#define P_TOKENT (P_EW + P_MAXE)
23#define P_INTS (P_TOKENT + P_MAXE)
24
25// experts per token (Flash-Next 10); the host prelude (engine/geo.h) defines GEO_TOPK for another shape
26#ifndef ROUTE_K
27#ifdef GEO_TOPK
28#define ROUTE_K GEO_TOPK
29#else
30#define ROUTE_K 10
31#endif
32#endif
33
34// Expert e's matrices: gate at W + gate_off + e * gu_stride, up at W + up_off + e * gu_stride, down at
35// W + down_off + e * d_stride (a pack's blobs: gate_off 0, strides = the blob; a GGUF: the three tensors).
36struct MoeArgs {
37    ulong gate_off;
38    ulong up_off;
39    ulong down_off;
40    ulong gu_stride;
41    ulong d_stride;
42    uint gu_row;     // bytes per gate/up row
43    uint d_row;      // bytes per down row
44    uint n_embd;
45    uint n_ff;
46    uint n_tok;
47    uint topk;
48    uint n_expert;
49    uint gx_gu;      // threadgroups along the rows for moe_gu (n_ff / rows per threadgroup)
50    uint gx_dn;      // ... for moe_down (n_embd / rows per threadgroup)
51    uint pad;
52};
53
54// The SSD-streaming arena (metal/src/engine/stream.cpp): with function constant 20 set, expert e of the layer lies in
55// an arena slot, smap[e] = (chunk << 28) | its 16 KiB page in that chunk; the chunks are W (buffer 0) and buffers 7..9
56// (gate_off / up_off / down_off are then offsets inside the slot).  The same block is in moe_mm.metal.
57#ifndef STRATA_ARENA_METAL
58#define STRATA_ARENA_METAL
59constant bool kArenaFc [[function_constant(20)]];
60constant bool kArena = is_function_constant_defined(kArenaFc) && kArenaFc;
61static inline device const uchar* arena_slot(uint v, device const uchar* W, device const uchar* W1, device const uchar* W2,
62                                             device const uchar* W3) {
63    const uint c = v >> 28;
64    device const uchar* b = c == 0 ? W : (c == 1 ? W1 : (c == 2 ? W2 : W3));
65    return b + (ulong)(v & 0x0FFFFFFFu) * 16384ul;
66}
67#endif
68
69static inline void plan_body(device const int* ids, device const float* w, device int* plan, constant MoeArgs& a,
70                             ushort tid, ushort nth, ushort sg, ushort lane, threadgroup int* s_grp,
71                             threadgroup int* s_ent) {
72    const int ne = int(a.n_tok * a.topk);
73    // one thread per expert id (nth == n_expert, at most 1024)
74    const int e = tid;
75    int cnt = 0;
76    if (e < int(a.n_expert))
77        for (int i = 0; i < ne; ++i) cnt += ids[i] == e;
78    const int has = cnt > 0;
79    const int pg = simd_prefix_exclusive_sum(has), pe = simd_prefix_exclusive_sum(cnt);
80    if (lane == 31) { s_grp[sg] = pg + has; s_ent[sg] = pe + cnt; }
81    threadgroup_barrier(mem_flags::mem_threadgroup);
82    if (tid == 0) {
83        int og = 0, oe = 0;
84        const int nsg = (nth + 31) / 32;
85        for (int i = 0; i < nsg; ++i) {
86            const int g = s_grp[i], n = s_ent[i];
87            s_grp[i] = og;
88            s_ent[i] = oe;
89            og += g;
90            oe += n;
91        }
92        plan[P_NG] = og;
93        plan[P_IGU] = int(a.gx_gu); plan[P_IGU + 1] = og; plan[P_IGU + 2] = 1;
94        plan[P_IDN] = int(a.gx_dn); plan[P_IDN + 1] = og; plan[P_IDN + 2] = 1;
95        plan[P_GSTART + og] = oe;
96    }
97    threadgroup_barrier(mem_flags::mem_threadgroup);
98    if (has) {
99        const int gi = s_grp[sg] + pg, off = s_ent[sg] + pe;
100        plan[P_GEXP + gi] = e;
101        plan[P_GSTART + gi] = off;
102        int j = 0;
103        for (int i = 0; i < ne; ++i)
104            if (ids[i] == e) {
105                plan[P_ETOK + off + j] = i / int(a.topk);
106                plan[P_EW + off + j] = as_type<int>(w[i]);
107                plan[P_TOKENT + i] = off + j;
108                ++j;
109            }
110    }
111}
112
113kernel void moe_plan(device const int* ids [[buffer(0)]], device const float* w [[buffer(1)]],
114                     device int* plan [[buffer(2)]], constant MoeArgs& a [[buffer(3)]],
115                     ushort tid [[thread_position_in_threadgroup]], ushort nth [[threads_per_threadgroup]],
116                     ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
117    threadgroup int s_grp[32], s_ent[32];
118    plan_body(ids, w, plan, a, tid, nth, sg, lane, s_grp, s_ent);
119}
120
121// The router's tail for the window, then the plan, in one threadgroup of n_expert (512) threads: simdgroup t routes
122// token t exactly as native_router.cu (pinned llama.cpp topk-moe): softmax over the 512 logits, top 10 by
123// probability (equal values: the lower expert index), weights = p / max(sum of the selected, 2^-14), the sum taken
124// by winning lane in selection order and reduced with the same xor tree.
125// One token's routing by one simdgroup: softmax over NL * 32 logits (512: NL 16; the 256-expert Coder: NL 8), top 10, weights.
126// `l` the token's logits, `ids` / `w` its 10 outputs.  NL = 16 is the original code token for token.
127template <int NL>
128static inline void route_tok(device const float* l, device int* ids, device float* w, ushort lane) {
129    float v[NL];
130    for (int i = 0; i < NL; ++i) v[i] = l[lane + 32 * i];
131    float mx = -INFINITY;
132    for (int i = 0; i < NL; ++i) mx = max(mx, v[i]);
133    for (ushort m = 16; m > 0; m >>= 1) mx = max(mx, simd_shuffle_xor(mx, m));
134    float sum = 0.0f;
135    for (int i = 0; i < NL; ++i) {
136        v[i] = exp(v[i] - mx);
137        sum += v[i];
138    }
139    for (ushort m = 16; m > 0; m >>= 1) sum += simd_shuffle_xor(sum, m);
140    const float rcp = 1.0f / sum;
141    for (int i = 0; i < NL; ++i) {
142        v[i] *= rcp;
143        if (isnan(v[i])) v[i] = -FLT_MAX;
144    }
145    float selected = 0.0f, ssum = 0.0f;
146    for (int rank = 0; rank < ROUTE_K; ++rank) {
147        float best = v[0];
148        int ex = lane;
149        for (int i = 1; i < NL; ++i)
150            if (v[i] > best) { best = v[i]; ex = lane + 32 * i; }
151        for (ushort m = 16; m > 0; m >>= 1) {
152            const float ob = simd_shuffle_xor(best, m);
153            const int oe = simd_shuffle_xor(ex, m);
154            if (ob > best || (ob == best && oe < ex)) { best = ob; ex = oe; }
155        }
156        if ((ex & 31) == lane) {
157            v[ex / 32] = -INFINITY;
158            ids[rank] = ex;
159            ssum += best;
160        }
161        if (rank == lane) selected = best;
162    }
163    for (ushort m = 16; m > 0; m >>= 1) ssum += simd_shuffle_xor(ssum, m);
164    ssum = max(ssum, 6.103515625e-5f);
165    const float inv = 1.0f / ssum;
166    if (lane < ROUTE_K) w[lane] = selected * inv;
167}
168
169kernel void moe_route(device const float* logits [[buffer(0)]], device int* ids [[buffer(1)]],
170                      device float* w [[buffer(2)]], device int* plan [[buffer(3)]], constant MoeArgs& a [[buffer(4)]],
171                      ushort tid [[thread_position_in_threadgroup]], ushort nth [[threads_per_threadgroup]],
172                      ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
173    threadgroup int s_grp[32], s_ent[32];
174    if (sg < a.n_tok) {
175        if (a.n_expert == 256) route_tok<8>(logits + sg * 512, ids + sg * ROUTE_K, w + sg * ROUTE_K, lane);
176        else route_tok<16>(logits + sg * 512, ids + sg * ROUTE_K, w + sg * ROUTE_K, lane);
177    }
178    threadgroup_barrier(mem_flags::mem_device);
179    plan_body(ids, w, plan, a, tid, nth, sg, lane, s_grp, s_ent);
180}
181
182// ---- gate + up + SwiGLU -------------------------------------------------------------------------------------------
183// One pass over a group's rows for all its NE entries (1..8: an expert appears once per token); NE is uniform per
184// threadgroup, so the kernel switches once into a body specialised for it.
185template <int F, int LPR, int NR, int NE>
186static inline void gu_body(device const uchar* g0, device const uchar* u0, device const float* x,
187                           device const float* xs16, device float* h, device const int* etok, int c, int row0, int li,
188                           constant MoeArgs& a, threadgroup const uint* tab) {
189    constexpr int UNIT = fmt<F>::UNIT;
190    float ag[NR][NE], au[NR][NE];
191    for (int r = 0; r < NR; ++r)
192        for (int t = 0; t < NE; ++t) ag[r][t] = au[r][t] = 0.0f;
193    const int U = int(a.n_embd) / UNIT;
194    for (int u = li; u < U; u += LPR) {
195        float qg[NR][UNIT], qu[NR][UNIT];
196        float4 cg[NR], cu[NR];
197        for (int r = 0; r < NR; ++r) {
198            Dec<F>::run(g0 + r * a.gu_row, u, qg[r], cg[r], tab);
199            Dec<F>::run(u0 + r * a.gu_row, u, qu[r], cu[r], tab);
200        }
201        for (int t = 0; t < NE; ++t) {
202            const int tok = etok[t];
203            float xs[UNIT], xsum[2];
204            X<F>::load(x + tok * int(a.n_embd), xs16 + tok * int(a.n_embd / 16), u, xs, xsum);
205            for (int r = 0; r < NR; ++r) {
206                ag[r][t] += unit_combine<UNIT>(qg[r], cg[r], xs, xsum);
207                au[r][t] += unit_combine<UNIT>(qu[r], cu[r], xs, xsum);
208            }
209        }
210    }
211    for (int r = 0; r < NR; ++r)
212        for (int t = 0; t < NE; ++t) {
213            const float gv = lane_sum<LPR>(ag[r][t]), uv = lane_sum<LPR>(au[r][t]);
214            if (li == 0) h[(c + t) * int(a.n_ff) + row0 + r] = gv / (1.0f + exp(-gv)) * uv;
215        }
216}
217
218// bench probe (function constant 22): 1 = no table load (wrong values for the i-quants)
219constant int MOE_PROBE [[function_constant(22)]];
220constant int moe_probe = is_function_constant_defined(MOE_PROBE) ? MOE_PROBE : 0;
221
222template <int F, int LPR, int NR, int SG>
223kernel void moe_gu(device const uchar* W [[buffer(0)]], device const float* x [[buffer(1)]],
224                   device float* h [[buffer(2)]], device const int* plan [[buffer(3)]],
225                   constant MoeArgs& a [[buffer(4)]], device const float* xs16 [[buffer(5)]],
226                   device const uint* smap [[buffer(6)]], device const uchar* W1 [[buffer(7)]],
227                   device const uchar* W2 [[buffer(8)]], device const uchar* W3 [[buffer(9)]],
228                   uint3 tg [[threadgroup_position_in_grid]], ushort sg [[simdgroup_index_in_threadgroup]],
229                   ushort lane [[thread_index_in_simdgroup]], ushort tid [[thread_index_in_threadgroup]]) {
230    constexpr int RG = 32 / LPR;
231    threadgroup uint tab[fmt<F>::TAB];
232    if (moe_probe != 1) {
233        load_tab<F>(tab, tid, SG * 32);
234        threadgroup_barrier(mem_flags::mem_threadgroup);
235    }
236    const int g = int(tg.y);
237    if (g >= plan[P_NG]) return;
238    const int li = lane % LPR;
239    const int row0 = ((int(tg.x) * SG + sg) * RG + lane / LPR) * NR;
240    const ulong ex = (ulong)plan[P_GEXP + g];
241    const int c = plan[P_GSTART + g], ne = plan[P_GSTART + g + 1] - c;
242    device const int* etok = plan + P_ETOK + c;
243    device const uchar* E = kArena ? arena_slot(smap[ex], W, W1, W2, W3) : W + ex * a.gu_stride;
244    device const uchar* g0 = E + a.gate_off + (ulong)row0 * a.gu_row;
245    device const uchar* u0 = E + a.up_off + (ulong)row0 * a.gu_row;
246    switch (ne) {
247        case 1: gu_body<F, LPR, NR, 1>(g0, u0, x, xs16, h, etok, c, row0, li, a, tab); break;
248        case 2: gu_body<F, LPR, NR, 2>(g0, u0, x, xs16, h, etok, c, row0, li, a, tab); break;
249        case 3: gu_body<F, LPR, NR, 3>(g0, u0, x, xs16, h, etok, c, row0, li, a, tab); break;
250        case 4: gu_body<F, LPR, NR, 4>(g0, u0, x, xs16, h, etok, c, row0, li, a, tab); break;
251        default:
252            for (int k = 0; k < ne; k += 4) {
253                const int m = min(4, ne - k);
254                if (m == 4) gu_body<F, LPR, NR, 4>(g0, u0, x, xs16, h, etok + k, c + k, row0, li, a, tab);
255                else if (m == 3) gu_body<F, LPR, NR, 3>(g0, u0, x, xs16, h, etok + k, c + k, row0, li, a, tab);
256                else if (m == 2) gu_body<F, LPR, NR, 2>(g0, u0, x, xs16, h, etok + k, c + k, row0, li, a, tab);
257                else gu_body<F, LPR, NR, 1>(g0, u0, x, xs16, h, etok + k, c + k, row0, li, a, tab);
258            }
259    }
260}
261
262// ---- down ---------------------------------------------------------------------------------------------------------
263template <int F, int LPR, int NR, int NE>
264static inline void dn_body(device const uchar* d0, device const float* h, device const float* hs16, device float* ye,
265                           device const int* plan, int c, int row0, int li, constant MoeArgs& a,
266                           threadgroup const uint* tab) {
267    constexpr int UNIT = fmt<F>::UNIT;
268    float ac[NR][NE];
269    for (int r = 0; r < NR; ++r)
270        for (int t = 0; t < NE; ++t) ac[r][t] = 0.0f;
271    const int U = int(a.n_ff) / UNIT;
272    for (int u = li; u < U; u += LPR) {
273        float q[NR][UNIT];
274        float4 sc[NR];
275        for (int r = 0; r < NR; ++r) Dec<F>::run(d0 + r * a.d_row, u, q[r], sc[r], tab);
276        for (int t = 0; t < NE; ++t) {
277            float xs[UNIT], xsum[2];
278            X<F>::load(h + (c + t) * int(a.n_ff), hs16 + (c + t) * int(a.n_ff / 16), u, xs, xsum);
279            for (int r = 0; r < NR; ++r) ac[r][t] += unit_combine<UNIT>(q[r], sc[r], xs, xsum);
280        }
281    }
282    for (int r = 0; r < NR; ++r)
283        for (int t = 0; t < NE; ++t) {
284            const float v = lane_sum<LPR>(ac[r][t]);
285            if (li == 0) ye[(c + t) * int(a.n_embd) + row0 + r] = as_type<float>(plan[P_EW + c + t]) * v;
286        }
287}
288
289template <int F, int LPR, int NR, int SG>
290kernel void moe_down(device const uchar* W [[buffer(0)]], device const float* h [[buffer(1)]],
291                     device float* ye [[buffer(2)]], device const int* plan [[buffer(3)]],
292                     constant MoeArgs& a [[buffer(4)]], device const float* hs16 [[buffer(5)]],
293                     device const uint* smap [[buffer(6)]], device const uchar* W1 [[buffer(7)]],
294                     device const uchar* W2 [[buffer(8)]], device const uchar* W3 [[buffer(9)]],
295                     uint3 tg [[threadgroup_position_in_grid]], ushort sg [[simdgroup_index_in_threadgroup]],
296                     ushort lane [[thread_index_in_simdgroup]], ushort tid [[thread_index_in_threadgroup]]) {
297    constexpr int RG = 32 / LPR;
298    threadgroup uint tab[fmt<F>::TAB];
299    load_tab<F>(tab, tid, SG * 32);
300    threadgroup_barrier(mem_flags::mem_threadgroup);
301    const int g = int(tg.y);
302    if (g >= plan[P_NG]) return;
303    const int li = lane % LPR;
304    const int row0 = ((int(tg.x) * SG + sg) * RG + lane / LPR) * NR;
305    const ulong ex = (ulong)plan[P_GEXP + g];
306    const int c = plan[P_GSTART + g], ne = plan[P_GSTART + g + 1] - c;
307    device const uchar* d0 = (kArena ? arena_slot(smap[ex], W, W1, W2, W3) : W + ex * a.d_stride) + a.down_off + (ulong)row0 * a.d_row;
308    switch (ne) {
309        case 1: dn_body<F, LPR, NR, 1>(d0, h, hs16, ye, plan, c, row0, li, a, tab); break;
310        case 2: dn_body<F, LPR, NR, 2>(d0, h, hs16, ye, plan, c, row0, li, a, tab); break;
311        case 3: dn_body<F, LPR, NR, 3>(d0, h, hs16, ye, plan, c, row0, li, a, tab); break;
312        case 4: dn_body<F, LPR, NR, 4>(d0, h, hs16, ye, plan, c, row0, li, a, tab); break;
313        default:
314            for (int k = 0; k < ne; k += 4) {
315                const int m = min(4, ne - k);
316                if (m == 4) dn_body<F, LPR, NR, 4>(d0, h, hs16, ye, plan, c + k, row0, li, a, tab);
317                else if (m == 3) dn_body<F, LPR, NR, 3>(d0, h, hs16, ye, plan, c + k, row0, li, a, tab);
318                else if (m == 2) dn_body<F, LPR, NR, 2>(d0, h, hs16, ye, plan, c + k, row0, li, a, tab);
319                else dn_body<F, LPR, NR, 1>(d0, h, hs16, ye, plan, c + k, row0, li, a, tab);
320            }
321    }
322}
323
324// ---- down experts in the K-quants (Q3_K / Q4_K / Q5_K / Q6_K) - the 256-wide block types a UD file carries at expert
325// widths that divide by 256 (512, 1024: Qwen3.6's UD-Q4_K_XL has Q5_K / Q6_K downs).  Their decoders read the codes in place
326// (the mask trick of units.metal), so the activations must be pre-scaled and need per-16 sums: for the gate/up that is the
327// host's xprep planes; the down's h is the raw f32 rows moe_gu wrote, so XD<F> forms the same slices from the raw row here
328// (the scaling of xprep: x * 2^-(8 (i % 4)) for Q4_K / Q5_K, x * 2^-(8 (i % 2)) for Q6_K / Q3_K, both exact; the sums of 16
329// raw values).  New kernels moe_down_<type>_<L>_<R>_<S> under the names the host already builds; nothing existing changes.
330static inline void xd16(device const float* p, thread float* xs, thread float& sum, int kind) {
331    float s = 0.0f;
332    for (int j = 0; j < 16; ++j) {
333        const float v = p[j];
334        s += v;
335        xs[j] = kind == 4 ? v * (j & 3 ? (j & 3) == 1 ? 0.00390625f : (j & 3) == 2 ? 1.52587890625e-05f : 5.9604644775390625e-08f : 1.0f)
336                          : ((j & 1) ? v * 0.00390625f : v);
337    }
338    sum = s;
339}
340template <int F> struct XD;
341template <> struct XD<T_Q4_K> {
342    static inline void load(device const float* h, int u, thread float* xs, thread float* xsum) {
343        const int p0 = 256 * (u >> 3) + 64 * ((u >> 1) & 3) + 16 * (u & 1);
344        xd16(h + p0, xs, xsum[0], 4);
345        xd16(h + p0 + 32, xs + 16, xsum[1], 4);
346    }
347};
348template <> struct XD<T_Q5_K> {
349    static inline void load(device const float* h, int u, thread float* xs, thread float* xsum) { XD<T_Q4_K>::load(h, u, xs, xsum); }
350};
351template <> struct XD<T_Q6_K> {
352    static inline void load(device const float* h, int u, thread float* xs, thread float* xsum) {
353        const int p0 = 256 * (u >> 3) + 128 * ((u >> 2) & 1) + 32 * (u & 1) + 16 * ((u >> 1) & 1);
354        xd16(h + p0, xs, xsum[0], 2);
355        xd16(h + p0 + 64, xs + 16, xsum[1], 2);
356    }
357};
358template <> struct XD<T_Q3_K> {
359    static inline void load(device const float* h, int u, thread float* xs, thread float* xsum) {
360        xd16(h + 32 * u, xs, xsum[0], 2);
361        xd16(h + 32 * u + 16, xs + 16, xsum[1], 2);
362    }
363};
364
365template <int F, int LPR, int NR, int NE>
366static inline void dn_body_k(device const uchar* d0, device const float* h, device float* ye, device const int* plan, int c,
367                             int row0, int li, constant MoeArgs& a, threadgroup const uint* tab) {
368    constexpr int UNIT = fmt<F>::UNIT;
369    float ac[NR][NE];
370    for (int r = 0; r < NR; ++r)
371        for (int t = 0; t < NE; ++t) ac[r][t] = 0.0f;
372    const int U = int(a.n_ff) / UNIT;
373    for (int u = li; u < U; u += LPR) {
374        float q[NR][UNIT];
375        float4 sc[NR];
376        for (int r = 0; r < NR; ++r) Dec<F>::run(d0 + r * a.d_row, u, q[r], sc[r], tab);
377        for (int t = 0; t < NE; ++t) {
378            float xs[UNIT], xsum[2];
379            XD<F>::load(h + (c + t) * int(a.n_ff), u, xs, xsum);
380            for (int r = 0; r < NR; ++r) ac[r][t] += unit_combine<UNIT>(q[r], sc[r], xs, xsum);
381        }
382    }
383    for (int r = 0; r < NR; ++r)
384        for (int t = 0; t < NE; ++t) {
385            const float v = lane_sum<LPR>(ac[r][t]);
386            if (li == 0) ye[(c + t) * int(a.n_embd) + row0 + r] = as_type<float>(plan[P_EW + c + t]) * v;
387        }
388}
389
390// same arguments and plan walk as moe_down (buffer 5, the prepared sums, is unused: the sums are formed from h)
391template <int F, int LPR, int NR, int SG>
392kernel void moe_down_k(device const uchar* W [[buffer(0)]], device const float* h [[buffer(1)]],
393                       device float* ye [[buffer(2)]], device const int* plan [[buffer(3)]],
394                       constant MoeArgs& a [[buffer(4)]], device const float* hs16 [[buffer(5)]],
395                       device const uint* smap [[buffer(6)]], device const uchar* W1 [[buffer(7)]],
396                       device const uchar* W2 [[buffer(8)]], device const uchar* W3 [[buffer(9)]],
397                       uint3 tg [[threadgroup_position_in_grid]], ushort sg [[simdgroup_index_in_threadgroup]],
398                       ushort lane [[thread_index_in_simdgroup]], ushort tid [[thread_index_in_threadgroup]]) {
399    constexpr int RG = 32 / LPR;
400    threadgroup uint tab[fmt<F>::TAB];
401    load_tab<F>(tab, tid, SG * 32);
402    threadgroup_barrier(mem_flags::mem_threadgroup);
403    const int g = int(tg.y);
404    if (g >= plan[P_NG]) return;
405    const int li = lane % LPR;
406    const int row0 = ((int(tg.x) * SG + sg) * RG + lane / LPR) * NR;
407    const ulong ex = (ulong)plan[P_GEXP + g];
408    const int c = plan[P_GSTART + g], ne = plan[P_GSTART + g + 1] - c;
409    device const uchar* d0 = (kArena ? arena_slot(smap[ex], W, W1, W2, W3) : W + ex * a.d_stride) + a.down_off + (ulong)row0 * a.d_row;
410    switch (ne) {
411        case 1: dn_body_k<F, LPR, NR, 1>(d0, h, ye, plan, c, row0, li, a, tab); break;
412        case 2: dn_body_k<F, LPR, NR, 2>(d0, h, ye, plan, c, row0, li, a, tab); break;
413        case 3: dn_body_k<F, LPR, NR, 3>(d0, h, ye, plan, c, row0, li, a, tab); break;
414        case 4: dn_body_k<F, LPR, NR, 4>(d0, h, ye, plan, c, row0, li, a, tab); break;
415        default:
416            for (int k = 0; k < ne; k += 4) {
417                const int m = min(4, ne - k);
418                if (m == 4) dn_body_k<F, LPR, NR, 4>(d0, h, ye, plan, c + k, row0, li, a, tab);
419                else if (m == 3) dn_body_k<F, LPR, NR, 3>(d0, h, ye, plan, c + k, row0, li, a, tab);
420                else if (m == 2) dn_body_k<F, LPR, NR, 2>(d0, h, ye, plan, c + k, row0, li, a, tab);
421                else dn_body_k<F, LPR, NR, 1>(d0, h, ye, plan, c + k, row0, li, a, tab);
422            }
423    }
424}
425
426kernel void moe_combine(device const float* ye [[buffer(0)]], device float* y [[buffer(1)]],
427                        device const int* plan [[buffer(2)]], constant MoeArgs& a [[buffer(3)]],
428                        uint gid [[thread_position_in_grid]]) {
429    const uint t = gid / a.n_embd, k = gid % a.n_embd;
430    if (t >= a.n_tok) return;
431    float s = 0.0f;
432    for (uint j = 0; j < a.topk; ++j) s += ye[plan[P_TOKENT + t * a.topk + j] * int(a.n_embd) + k];
433    y[gid] = s;
434}
435
436// ---- instantiations: moe_gu_<type>_<LPR>_<NR>_<SG>, moe_down_<type>_<LPR>_<NR>_<SG> -------------------------------
437#define GU(F, L, R, S) template [[host_name("moe_gu_" #F "_" #L "_" #R "_" #S)]] kernel decltype(moe_gu<F, L, R, S>) moe_gu<F, L, R, S>;
438#define DN(F, L, R, S) template [[host_name("moe_down_" #F "_" #L "_" #R "_" #S)]] kernel decltype(moe_down<F, L, R, S>) moe_down<F, L, R, S>;
439#define GU_SET(F) GU(F, 32, 1, 4) GU(F, 32, 2, 4) GU(F, 32, 4, 4) GU(F, 32, 2, 2) GU(F, 32, 2, 8) GU(F, 32, 1, 8) \
440                  GU(F, 16, 1, 4) GU(F, 16, 2, 4) GU(F, 8, 1, 4) GU(F, 8, 2, 4) GU(F, 8, 1, 2)
441#define DN_SET(F) DN(F, 8, 1, 4) DN(F, 8, 2, 4) DN(F, 8, 4, 4) DN(F, 8, 1, 8) DN(F, 8, 2, 8) DN(F, 4, 1, 4) DN(F, 4, 2, 4) \
442                  DN(F, 4, 4, 4) DN(F, 16, 1, 4) DN(F, 16, 2, 4) DN(F, 32, 1, 4) DN(F, 2, 2, 4)
443GU_SET(T_Q2_0)
444GU_SET(T_IQ3_XXS)
445GU_SET(T_IQ2_XXS)
446GU_SET(T_IQ2_XS)
447GU_SET(T_IQ2_S)
448GU_SET(T_IQ3_S)
449GU_SET(T_IQ4_XS)   // the IQ3_S pack's gate/up in one layer
450GU_SET(T_Q4_K) GU_SET(T_Q5_K) GU_SET(T_Q6_K) GU_SET(T_Q8_0)   // the UD-Q4/5/6_K_XL packs
451DN_SET(T_Q5_1) DN_SET(T_Q8_0)
452DN_SET(T_Q5_0)   // the UD-IQ2_XS / Q2_K_XL / Q3_K_XL / IQ4_XS packs' down experts (generic Dec: d * (code - 16))
453DN_SET(T_Q2_0)
454DN_SET(T_Q2_0R)
455DN_SET(T_IQ4_NL)
456// UD files at expert widths divisible by 256: IQ4_XS / IQ3_S downs read raw h like the gate/up's raw-kind formats (the generic
457// X / Dec); the K-quants take moe_down_k (XD above).  Same host names, moe_down_<type>_<L>_<R>_<S>.
458#ifdef STRATA_KQ_DOWN   // the host defines it when a layer's down is one of these types (window.cpp kq_down_prelude): today's sets compile exactly what they did
459DN_SET(T_IQ4_XS) DN_SET(T_IQ3_S)
460#define DNK(F, L, R, S) template [[host_name("moe_down_" #F "_" #L "_" #R "_" #S)]] kernel decltype(moe_down_k<F, L, R, S>) moe_down_k<F, L, R, S>;
461#define DNK_SET(F) DNK(F, 8, 1, 4) DNK(F, 8, 2, 4) DNK(F, 8, 4, 4) DNK(F, 8, 1, 8) DNK(F, 8, 2, 8) DNK(F, 4, 1, 4) DNK(F, 4, 2, 4)                    DNK(F, 4, 4, 4) DNK(F, 16, 1, 4) DNK(F, 16, 2, 4) DNK(F, 32, 1, 4) DNK(F, 2, 2, 4)
462DNK_SET(T_Q4_K) DNK_SET(T_Q5_K) DNK_SET(T_Q6_K) DNK_SET(T_Q3_K)
463#endif   // STRATA_KQ_DOWN
464// Gyro (agentionai's trellis experts): TQK6 / TQ2_T gate/up, TQK7 / TQ2_T down (the CUDA engine's STRATA_GU_FMTS / D_FMTS)
465GU_SET(T_TQK6) GU_SET(T_TQ2T)
466DN_SET(T_TQK7) DN_SET(T_TQ2T)
467
468#ifdef STRATA_METAL_F16   // window.cpp compiles it in only under STRATA_METAL_F16=1
469// ---- the fp16 path (STRATA_METAL_F16): x from the window's half plane, h also as half for the down
470template <int F, int LPR, int NR, int NE>
471static inline void gu_body16(device const uchar* g0, device const uchar* u0, device const half* x,
472                             device const float* xs16, device float* h, device half* h16, device const int* etok, int c,
473                             int row0, int li, constant MoeArgs& a, threadgroup const uint* tab) {
474    constexpr int UNIT = fmt<F>::UNIT;
475    float ag[NR][NE], au[NR][NE];
476    for (int r = 0; r < NR; ++r)
477        for (int t = 0; t < NE; ++t) ag[r][t] = au[r][t] = 0.0f;
478    const int U = int(a.n_embd) / UNIT;
479    for (int u = li; u < U; u += LPR) {
480        half qg[NR][UNIT], qu[NR][UNIT];
481        float4 cg[NR], cu[NR];
482        for (int r = 0; r < NR; ++r) {
483            Dec16<F>::run(g0 + r * a.gu_row, u, qg[r], cg[r], tab);
484            Dec16<F>::run(u0 + r * a.gu_row, u, qu[r], cu[r], tab);
485        }
486        for (int t = 0; t < NE; ++t) {
487            const int tok = etok[t];
488            half xs[UNIT];
489            float xsum[2];
490            X16<F>::load(x + tok * int(a.n_embd), xs16 + tok * int(a.n_embd / 16), u, xs, xsum);
491            for (int r = 0; r < NR; ++r) {
492                ag[r][t] += unit_combine16<UNIT>(qg[r], cg[r], xs, xsum);
493                au[r][t] += unit_combine16<UNIT>(qu[r], cu[r], xs, xsum);
494            }
495        }
496    }
497    for (int r = 0; r < NR; ++r)
498        for (int t = 0; t < NE; ++t) {
499            const float gv = lane_sum<LPR>(ag[r][t]), uv = lane_sum<LPR>(au[r][t]);
500            const float hv = gv / (1.0f + exp(-gv)) * uv;
501            if (li == 0) {
502                h[(c + t) * int(a.n_ff) + row0 + r] = hv;
503                h16[(c + t) * int(a.n_ff) + row0 + r] = half(hv);
504            }
505        }
506}
507
508template <int F, int LPR, int NR, int SG>
509kernel void moe_gu16(device const uchar* W [[buffer(0)]], device const half* x [[buffer(1)]],
510                     device float* h [[buffer(2)]], device const int* plan [[buffer(3)]],
511                     constant MoeArgs& a [[buffer(4)]], device const float* xs16 [[buffer(5)]],
512                     device half* h16 [[buffer(6)]],
513                     uint3 tg [[threadgroup_position_in_grid]], ushort sg [[simdgroup_index_in_threadgroup]],
514                     ushort lane [[thread_index_in_simdgroup]], ushort tid [[thread_index_in_threadgroup]]) {
515    constexpr int RG = 32 / LPR;
516    threadgroup uint tab[fmt<F>::TAB];
517    load_tab<F>(tab, tid, SG * 32);
518    threadgroup_barrier(mem_flags::mem_threadgroup);
519    const int g = int(tg.y);
520    if (g >= plan[P_NG]) return;
521    const int li = lane % LPR;
522    const int row0 = ((int(tg.x) * SG + sg) * RG + lane / LPR) * NR;
523    const ulong ex = (ulong)plan[P_GEXP + g];
524    const int c = plan[P_GSTART + g], ne = plan[P_GSTART + g + 1] - c;
525    device const int* etok = plan + P_ETOK + c;
526    device const uchar* E = W + ex * a.gu_stride;
527    device const uchar* g0 = E + a.gate_off + (ulong)row0 * a.gu_row;
528    device const uchar* u0 = E + a.up_off + (ulong)row0 * a.gu_row;
529    for (int k = 0; k < ne; k += 4) {
530        const int m = min(4, ne - k);
531        if (m == 4) gu_body16<F, LPR, NR, 4>(g0, u0, x, xs16, h, h16, etok + k, c + k, row0, li, a, tab);
532        else if (m == 3) gu_body16<F, LPR, NR, 3>(g0, u0, x, xs16, h, h16, etok + k, c + k, row0, li, a, tab);
533        else if (m == 2) gu_body16<F, LPR, NR, 2>(g0, u0, x, xs16, h, h16, etok + k, c + k, row0, li, a, tab);
534        else gu_body16<F, LPR, NR, 1>(g0, u0, x, xs16, h, h16, etok + k, c + k, row0, li, a, tab);
535    }
536}
537
538template <int F, int LPR, int NR, int NE>
539static inline void dn_body16(device const uchar* d0, device const half* h16, device float* ye, device const int* plan,
540                             int c, int row0, int li, constant MoeArgs& a, threadgroup const uint* tab) {
541    constexpr int UNIT = fmt<F>::UNIT;
542    float ac[NR][NE];
543    for (int r = 0; r < NR; ++r)
544        for (int t = 0; t < NE; ++t) ac[r][t] = 0.0f;
545    const int U = int(a.n_ff) / UNIT;
546    for (int u = li; u < U; u += LPR) {
547        half q[NR][UNIT];
548        float4 sc[NR];
549        for (int r = 0; r < NR; ++r) Dec16<F>::run(d0 + r * a.d_row, u, q[r], sc[r], tab);
550        for (int t = 0; t < NE; ++t) {
551            half xs[UNIT];
552            float xsum[2];
553            X16<F>::load(h16 + (c + t) * int(a.n_ff), nullptr, u, xs, xsum);
554            for (int r = 0; r < NR; ++r) ac[r][t] += unit_combine16<UNIT>(q[r], sc[r], xs, xsum);
555        }
556    }
557    for (int r = 0; r < NR; ++r)
558        for (int t = 0; t < NE; ++t) {
559            const float v = lane_sum<LPR>(ac[r][t]);
560            if (li == 0) ye[(c + t) * int(a.n_embd) + row0 + r] = as_type<float>(plan[P_EW + c + t]) * v;
561        }
562}
563
564template <int F, int LPR, int NR, int SG>
565kernel void moe_down16(device const uchar* W [[buffer(0)]], device const half* h16 [[buffer(1)]],
566                       device float* ye [[buffer(2)]], device const int* plan [[buffer(3)]],
567                       constant MoeArgs& a [[buffer(4)]],
568                       uint3 tg [[threadgroup_position_in_grid]], ushort sg [[simdgroup_index_in_threadgroup]],
569                       ushort lane [[thread_index_in_simdgroup]], ushort tid [[thread_index_in_threadgroup]]) {
570    constexpr int RG = 32 / LPR;
571    threadgroup uint tab[fmt<F>::TAB];
572    load_tab<F>(tab, tid, SG * 32);
573    threadgroup_barrier(mem_flags::mem_threadgroup);
574    const int g = int(tg.y);
575    if (g >= plan[P_NG]) return;
576    const int li = lane % LPR;
577    const int row0 = ((int(tg.x) * SG + sg) * RG + lane / LPR) * NR;
578    const ulong ex = (ulong)plan[P_GEXP + g];
579    const int c = plan[P_GSTART + g], ne = plan[P_GSTART + g + 1] - c;
580    device const uchar* d0 = W + a.down_off + ex * a.d_stride + (ulong)row0 * a.d_row;
581    for (int k = 0; k < ne; k += 4) {
582        const int m = min(4, ne - k);
583        if (m == 4) dn_body16<F, LPR, NR, 4>(d0, h16, ye, plan, c + k, row0, li, a, tab);
584        else if (m == 3) dn_body16<F, LPR, NR, 3>(d0, h16, ye, plan, c + k, row0, li, a, tab);
585        else if (m == 2) dn_body16<F, LPR, NR, 2>(d0, h16, ye, plan, c + k, row0, li, a, tab);
586        else dn_body16<F, LPR, NR, 1>(d0, h16, ye, plan, c + k, row0, li, a, tab);
587    }
588}
589#define GU16_(F, L, R, S) template [[host_name("moe_gu16_" #F "_" #L "_" #R "_" #S)]] kernel decltype(moe_gu16<F, L, R, S>) moe_gu16<F, L, R, S>;
590#define DN16_(F, L, R, S) template [[host_name("moe_down16_" #F "_" #L "_" #R "_" #S)]] kernel decltype(moe_down16<F, L, R, S>) moe_down16<F, L, R, S>;
591#define GU16(F, L, R, S) GU16_(F, L, R, S)   // F expanded to its number before the name is made
592#define DN16(F, L, R, S) DN16_(F, L, R, S)
593GU16(T_Q2_0, 32, 1, 4) GU16(T_Q2_0, 32, 2, 4) GU16(T_Q2_0, 32, 4, 4) GU16(T_Q2_0, 32, 2, 2) GU16(T_Q2_0, 32, 2, 8)
594GU16(T_Q2_0, 32, 1, 8) GU16(T_Q2_0, 16, 1, 4) GU16(T_Q2_0, 16, 2, 4) GU16(T_Q2_0, 8, 1, 4) GU16(T_Q2_0, 8, 2, 4) GU16(T_Q2_0, 8, 1, 2)
595DN16(T_Q2_0R, 8, 1, 4) DN16(T_Q2_0R, 8, 2, 4) DN16(T_Q2_0R, 8, 4, 4) DN16(T_Q2_0R, 4, 1, 4) DN16(T_Q2_0R, 4, 2, 4)
596DN16(T_Q2_0R, 4, 4, 4) DN16(T_Q2_0R, 8, 1, 8) DN16(T_Q2_0R, 8, 2, 8) DN16(T_Q2_0R, 16, 1, 4) DN16(T_Q2_0R, 16, 2, 4)
597DN16(T_Q2_0R, 32, 1, 4) DN16(T_Q2_0R, 2, 2, 4)
598#endif   // STRATA_METAL_F16