Skip to content

Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.

C++

metal: hyper-connection read, router tail + plan, expert kernels specialised per group size

Niko1221dffa167fcd2b
diff --git a/metal/kernels/gr.metal b/metal/kernels/gr.metal
new file mode 100644
index 000000000..52156b022
--- /dev/null
+++ b/metal/kernels/gr.metal
@@ -0,0 +1,168 @@
+// metal/kernels/gr.metal - the hyper-connection (gated residual) read for a window of tokens, with the previous
+// sublayer's write folded in. The math is fused_gr.hpp's (native contract: FP32 activations, BF16 weights):
+//
+// gr_norm R'[c] = R[c] + bo * 2 sigmoid(inj_prev[c] / hc) (when apply; written back in place)
+// xn[c] = R'[c] * w_norm[c] * rsqrt(mean(R'[c]^2) + eps)
+// gr_down lo[k] = silu((w_down[k] . xn) / hc) k < hc_lr; inject[c] = w_inject[c] . xn
+// gr_up mixed[d] = mean_c xn[c][d] * sigmoid(w_up[c n + d] . lo), written as prepared activations (xprep's
+// planes and per-16 sums) for the GEMVs that read it
+//
+// Shapes: n_embd 2560, hc 4, hc_lr 320. Per token t: R[t] (hc * n), bo[t] (n), inj_prev[t] (hc), xn[t] (hc * n),
+// lo[t] (hc_lr), inject[t] (hc), XP planes of n_tok rows.
+
+constant int GR_NTOK [[function_constant(1)]];
+
+struct GrArgs {
+ uint n_embd;
+ uint hc;
+ uint hc_lr;
+ uint n_tok;
+ uint apply;
+ float eps;
+};
+
+// one threadgroup per (stream c, token t), 256 threads
+kernel void gr_norm(device float* R [[buffer(0)]], device const float* bo [[buffer(1)]],
+ device const float* inj [[buffer(2)]], device const float* w_norm [[buffer(3)]],
+ device float* xn [[buffer(4)]], constant GrArgs& a [[buffer(5)]],
+ uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]],
+ ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
+ threadgroup float part[8];
+ const uint c = tg.x, t = tg.y, n = a.n_embd;
+ device float* r = R + (t * a.hc + c) * n;
+ const float g = a.apply ? 2.0f / (1.0f + exp(-inj[t * a.hc + c] / float(a.hc))) : 0.0f;
+ float ss = 0.0f;
+ for (uint d = tid; d < n; d += 256) {
+ float v = r[d];
+ if (a.apply) {
+ v = fma(bo[t * n + d], g, v);
+ r[d] = v;
+ }
+ ss = fma(v, v, ss);
+ }
+ ss = simd_sum(ss);
+ if (lane == 0) part[sg] = ss;
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ float tot = 0.0f;
+ for (int i = 0; i < 8; ++i) tot += part[i];
+ const float rs = rsqrt(tot / float(n) + a.eps);
+ device float* o = xn + (t * a.hc + c) * n;
+ device const float* w = w_norm + c * n;
+ for (uint d = tid; d < n; d += 256) o[d] = r[d] * w[d] * rs;
+}
+
+// rows: 0 .. hc_lr - 1 = w_down, hc_lr .. hc_lr + hc - 1 = w_inject (both bf16 rows of hc * n_embd).
+// SG simdgroups split the row's units KS ways; LPR = 32 (a simdgroup per row); RS = SG / KS rows per threadgroup.
+template <int SG, int KS>
+kernel void gr_down(device const uchar* w_down [[buffer(0)]], device const uchar* w_inject [[buffer(1)]],
+ device const float* xn [[buffer(2)]], device float* lo [[buffer(3)]],
+ device float* inject [[buffer(4)]], constant GrArgs& a [[buffer(5)]],
+ uint3 tg [[threadgroup_position_in_grid]], ushort sg [[simdgroup_index_in_threadgroup]],
+ ushort lane [[thread_index_in_simdgroup]]) {
+ constexpr int RS = SG / KS;
+ threadgroup float red[KS * RS * 8];
+ threadgroup uint notab[1];
+ const int ks = sg / RS, rs = sg % RS;
+ const int row = int(tg.x) * RS + rs;
+ const int nrows = int(a.hc_lr + a.hc);
+ const int rr = min(row, nrows - 1);
+ const int nin = int(a.hc * a.n_embd);
+ const uint rb = uint(nin) * 2;
+ device const uchar* w = rr < int(a.hc_lr) ? w_down + ulong(rr) * rb : w_inject + ulong(rr - int(a.hc_lr)) * rb;
+ const int U = nin / 16, u0 = ks * U / KS, u1 = (ks + 1) * U / KS;
+ float acc[8];
+ for (int t = 0; t < 8; ++t) acc[t] = 0.0f;
+ for (int u = u0 + lane; u < u1; u += 32) {
+ float q[16];
+ float4 sc;
+ Dec<T_BF16>::run(w, u, q, sc, notab);
+ for (int t = 0; t < GR_NTOK; ++t) {
+ float xs[16], xsum[2] = {0.0f, 0.0f};
+ load16(xn + t * nin + 16 * u, xs);
+ acc[t] += unit_combine<16>(q, sc, xs, xsum);
+ }
+ }
+ for (int t = 0; t < GR_NTOK; ++t) {
+ const float v = simd_sum(acc[t]);
+ if (lane == 0) red[(ks * RS + rs) * 8 + t] = v;
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ if (ks == 0 && lane < GR_NTOK && row < nrows) {
+ const int t = lane;
+ float v = 0.0f;
+ for (int k = 0; k < KS; ++k) v += red[(k * RS + rs) * 8 + t];
+ if (row < int(a.hc_lr)) {
+ const float z = v / float(a.hc);
+ lo[t * int(a.hc_lr) + row] = z / (1.0f + exp(-z));
+ } else {
+ inject[t * int(a.hc) + row - int(a.hc_lr)] = v;
+ }
+ }
+}
+
+// A threadgroup owns 16 consecutive d for all hc = 4 streams: 8 simdgroups, simdgroup s -> stream s / 2 and
+// d0 + 8 (s % 2) .. + 8; LPR = 4 lanes per row (320 = 20 units of 16, 5 per lane).
+// XP: [4 kinds][n_tok][n] then S16 [n_tok][n / 16] (units.metal's xprep layout).
+kernel void gr_up(device const uchar* w_up [[buffer(0)]], device const float* lo [[buffer(1)]],
+ device const float* xn [[buffer(2)]], device float* xp [[buffer(3)]],
+ constant GrArgs& a [[buffer(4)]],
+ uint3 tg [[threadgroup_position_in_grid]], ushort sg [[simdgroup_index_in_threadgroup]],
+ ushort lane [[thread_index_in_simdgroup]], ushort tid [[thread_index_in_threadgroup]]) {
+ threadgroup float gate[8][4][16];
+ threadgroup float msum[8][16];
+ threadgroup uint notab[1];
+ const int n = int(a.n_embd), c = sg >> 1, dl = 8 * (sg & 1) + lane / 4, li = lane & 3;
+ const int d = int(tg.x) * 16 + dl;
+ device const uchar* w = w_up + ulong(c * n + d) * (a.hc_lr * 2);
+ const int U = int(a.hc_lr) / 16;
+ float acc[8];
+ for (int t = 0; t < 8; ++t) acc[t] = 0.0f;
+ for (int u = li; u < U; u += 4) {
+ float q[16];
+ float4 sc;
+ Dec<T_BF16>::run(w, u, q, sc, notab);
+ for (int t = 0; t < GR_NTOK; ++t) {
+ float xs[16], xsum[2] = {0.0f, 0.0f};
+ load16(lo + t * int(a.hc_lr) + 16 * u, xs);
+ acc[t] += unit_combine<16>(q, sc, xs, xsum);
+ }
+ }
+ for (int t = 0; t < GR_NTOK; ++t) {
+ const float v = lane_sum<4>(acc[t]);
+ if (li == 0) gate[t][c][dl] = 1.0f / (1.0f + exp(-v));
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ // 16 threads per token: thread j -> d0 + j
+ const int t = tid / 16, j = tid & 15;
+ if (t < GR_NTOK) {
+ const int dd = int(tg.x) * 16 + j;
+ const int hc = int(a.hc);
+ float m = 0.0f;
+ for (int cc = 0; cc < hc; ++cc) m = fma(xn[(t * hc + cc) * n + dd], gate[t][cc][j], m);
+ m = m / float(hc);
+ const uint plane = a.n_tok * uint(n);
+ device float* raw = xp + t * n + dd;
+ const float q2s[8] = {1.0f, 0.25f, 0.0625f, 0.015625f, 0.00390625f, 0.0009765625f, 0.000244140625f,
+ 0.00006103515625f};
+ const float p4s[4] = {1.0f, 0.00390625f, 1.52587890625e-05f, 5.9604644775390625e-08f};
+ raw[0] = m;
+ raw[plane] = m * q2s[j & 7];
+ raw[2 * plane] = m * p4s[j & 3];
+ raw[3 * plane] = (j & 1) ? m * 0.00390625f : m;
+ msum[t][j] = m;
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ if (t < GR_NTOK && j == 0) {
+ // the per-16 sum in xprep's order (even and odd partial sums, then added)
+ float s0 = 0.0f, s1 = 0.0f;
+ for (int k = 0; k < 16; k += 2) { s0 += msum[t][k]; s1 += msum[t][k + 1]; }
+ xp[4 * a.n_tok * uint(n) + t * (n / 16) + tg.x] = s0 + s1;
+ }
+}
+
+template [[host_name("gr_down_8_8")]] kernel decltype(gr_down<8, 8>) gr_down<8, 8>;
+template [[host_name("gr_down_8_4")]] kernel decltype(gr_down<8, 4>) gr_down<8, 4>;
+template [[host_name("gr_down_4_4")]] kernel decltype(gr_down<4, 4>) gr_down<4, 4>;
+template [[host_name("gr_down_4_2")]] kernel decltype(gr_down<4, 2>) gr_down<4, 2>;
+template [[host_name("gr_down_16_16")]] kernel decltype(gr_down<16, 16>) gr_down<16, 16>;
+template [[host_name("gr_down_16_8")]] kernel decltype(gr_down<16, 8>) gr_down<16, 8>;
diff --git a/metal/kernels/moe.metal b/metal/kernels/moe.metal
index c5bbd4ff4..617b120f9 100644
--- a/metal/kernels/moe.metal
+++ b/metal/kernels/moe.metal
@@ -38,11 +38,9 @@ struct MoeArgs {
uint pad;
};
-kernel void moe_plan(device const int* ids [[buffer(0)]], device const float* w [[buffer(1)]],
- device int* plan [[buffer(2)]], constant MoeArgs& a [[buffer(3)]],
- ushort tid [[thread_position_in_threadgroup]], ushort nth [[threads_per_threadgroup]],
- ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
- threadgroup int s_grp[32], s_ent[32];
+static inline void plan_body(device const int* ids, device const float* w, device int* plan, constant MoeArgs& a,
+ ushort tid, ushort nth, ushort sg, ushort lane, threadgroup int* s_grp,
+ threadgroup int* s_ent) {
const int ne = int(a.n_tok * a.topk);
// one thread per expert id (nth == n_expert, at most 1024)
const int e = tid;
@@ -84,15 +82,111 @@ kernel void moe_plan(device const int* ids [[buffer(0)]], device const float* w
}
}
+kernel void moe_plan(device const int* ids [[buffer(0)]], device const float* w [[buffer(1)]],
+ device int* plan [[buffer(2)]], constant MoeArgs& a [[buffer(3)]],
+ ushort tid [[thread_position_in_threadgroup]], ushort nth [[threads_per_threadgroup]],
+ ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
+ threadgroup int s_grp[32], s_ent[32];
+ plan_body(ids, w, plan, a, tid, nth, sg, lane, s_grp, s_ent);
+}
+
+// The router's tail for the window, then the plan, in one threadgroup of n_expert (512) threads: simdgroup t routes
+// token t exactly as native_router.cu (pinned llama.cpp topk-moe): softmax over the 512 logits, top 10 by
+// probability (equal values: the lower expert index), weights = p / max(sum of the selected, 2^-14), the sum taken
+// by winning lane in selection order and reduced with the same xor tree.
+kernel void moe_route(device const float* logits [[buffer(0)]], device int* ids [[buffer(1)]],
+ device float* w [[buffer(2)]], device int* plan [[buffer(3)]], constant MoeArgs& a [[buffer(4)]],
+ ushort tid [[thread_position_in_threadgroup]], ushort nth [[threads_per_threadgroup]],
+ ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
+ threadgroup int s_grp[32], s_ent[32];
+ if (sg < a.n_tok) {
+ device const float* l = logits + sg * 512;
+ float v[16];
+ for (int i = 0; i < 16; ++i) v[i] = l[lane + 32 * i];
+ float mx = -INFINITY;
+ for (int i = 0; i < 16; ++i) mx = max(mx, v[i]);
+ for (ushort m = 16; m > 0; m >>= 1) mx = max(mx, simd_shuffle_xor(mx, m));
+ float sum = 0.0f;
+ for (int i = 0; i < 16; ++i) {
+ v[i] = exp(v[i] - mx);
+ sum += v[i];
+ }
+ for (ushort m = 16; m > 0; m >>= 1) sum += simd_shuffle_xor(sum, m);
+ const float rcp = 1.0f / sum;
+ for (int i = 0; i < 16; ++i) {
+ v[i] *= rcp;
+ if (isnan(v[i])) v[i] = -FLT_MAX;
+ }
+ float selected = 0.0f, ssum = 0.0f;
+ for (int rank = 0; rank < 10; ++rank) {
+ float best = v[0];
+ int ex = lane;
+ for (int i = 1; i < 16; ++i)
+ if (v[i] > best) { best = v[i]; ex = lane + 32 * i; }
+ for (ushort m = 16; m > 0; m >>= 1) {
+ const float ob = simd_shuffle_xor(best, m);
+ const int oe = simd_shuffle_xor(ex, m);
+ if (ob > best || (ob == best && oe < ex)) { best = ob; ex = oe; }
+ }
+ if ((ex & 31) == lane) {
+ v[ex / 32] = -INFINITY;
+ ids[sg * 10 + rank] = ex;
+ ssum += best;
+ }
+ if (rank == lane) selected = best;
+ }
+ for (ushort m = 16; m > 0; m >>= 1) ssum += simd_shuffle_xor(ssum, m);
+ ssum = max(ssum, 6.103515625e-5f);
+ const float inv = 1.0f / ssum;
+ if (lane < 10) w[sg * 10 + lane] = selected * inv;
+ }
+ threadgroup_barrier(mem_flags::mem_device);
+ plan_body(ids, w, plan, a, tid, nth, sg, lane, s_grp, s_ent);
+}
+
// ---- gate + up + SwiGLU -------------------------------------------------------------------------------------------
-// One pass over a group's rows for all its entries (at most 8: an expert appears once per token).
+// One pass over a group's rows for all its NE entries (1..8: an expert appears once per token); NE is uniform per
+// threadgroup, so the kernel switches once into a body specialised for it.
+template <int F, int LPR, int NR, int NE>
+static inline void gu_body(device const uchar* g0, device const uchar* u0, device const float* x,
+ device const float* xs16, device float* h, device const int* etok, int c, int row0, int li,
+ constant MoeArgs& a, threadgroup const uint* tab) {
+ constexpr int UNIT = fmt<F>::UNIT;
+ float ag[NR][NE], au[NR][NE];
+ for (int r = 0; r < NR; ++r)
+ for (int t = 0; t < NE; ++t) ag[r][t] = au[r][t] = 0.0f;
+ const int U = int(a.n_embd) / UNIT;
+ for (int u = li; u < U; u += LPR) {
+ float qg[NR][UNIT], qu[NR][UNIT];
+ float4 cg[NR], cu[NR];
+ for (int r = 0; r < NR; ++r) {
+ Dec<F>::run(g0 + r * a.gu_row, u, qg[r], cg[r], tab);
+ Dec<F>::run(u0 + r * a.gu_row, u, qu[r], cu[r], tab);
+ }
+ for (int t = 0; t < NE; ++t) {
+ const int tok = etok[t];
+ float xs[UNIT], xsum[2];
+ X<F>::load(x + tok * int(a.n_embd), xs16 + tok * int(a.n_embd / 16), u, xs, xsum);
+ for (int r = 0; r < NR; ++r) {
+ ag[r][t] += unit_combine<UNIT>(qg[r], cg[r], xs, xsum);
+ au[r][t] += unit_combine<UNIT>(qu[r], cu[r], xs, xsum);
+ }
+ }
+ }
+ for (int r = 0; r < NR; ++r)
+ for (int t = 0; t < NE; ++t) {
+ const float gv = lane_sum<LPR>(ag[r][t]), uv = lane_sum<LPR>(au[r][t]);
+ if (li == 0) h[(c + t) * int(a.n_ff) + row0 + r] = gv / (1.0f + exp(-gv)) * uv;
+ }
+}
+
template <int F, int LPR, int NR, int SG>
kernel void moe_gu(device const uchar* W [[buffer(0)]], device const float* x [[buffer(1)]],
device float* h [[buffer(2)]], device const int* plan [[buffer(3)]],
constant MoeArgs& a [[buffer(4)]], device const float* xs16 [[buffer(5)]],
uint3 tg [[threadgroup_position_in_grid]], ushort sg [[simdgroup_index_in_threadgroup]],
ushort lane [[thread_index_in_simdgroup]], ushort tid [[thread_index_in_threadgroup]]) {
- constexpr int UNIT = fmt<F>::UNIT, RG = 32 / LPR;
+ constexpr int RG = 32 / LPR;
threadgroup uint tab[fmt<F>::TAB];
load_tab<F>(tab, tid, SG * 32);
threadgroup_barrier(mem_flags::mem_threadgroup);
@@ -102,54 +196,59 @@ kernel void moe_gu(device const uchar* W [[buffer(0)]], device const float* x [[
const int row0 = ((int(tg.x) * SG + sg) * RG + lane / LPR) * NR;
device const uchar* blob = W + (ulong)plan[P_GEXP + g] * a.blob_bytes;
const int c = plan[P_GSTART + g], ne = plan[P_GSTART + g + 1] - c;
- device const float* xt[8];
- device const float* st[8];
- for (int t = 0; t < 8; ++t) {
- const int tok = plan[P_ETOK + c + min(t, ne - 1)];
- xt[t] = x + tok * int(a.n_embd);
- st[t] = xs16 + tok * int(a.n_embd / 16);
- }
- float ag[NR][8], au[NR][8];
- for (int r = 0; r < NR; ++r)
- for (int t = 0; t < 8; ++t) ag[r][t] = au[r][t] = 0.0f;
+ device const int* etok = plan + P_ETOK + c;
device const uchar* g0 = blob + (ulong)row0 * a.gu_row;
device const uchar* u0 = blob + a.up_off + (ulong)row0 * a.gu_row;
- const int U = int(a.n_embd) / UNIT;
- for (int u = li; u < U; u += LPR) {
- float qg[NR][UNIT], qu[NR][UNIT];
- float4 cg[NR], cu[NR];
- for (int r = 0; r < NR; ++r) {
- Dec<F>::run(g0 + r * a.gu_row, u, qg[r], cg[r], tab);
- Dec<F>::run(u0 + r * a.gu_row, u, qu[r], cu[r], tab);
- }
- for (int t = 0; t < 8; ++t) {
- if (t < ne) {
- float xs[UNIT], xsum[2];
- X<F>::load(xt[t], st[t], u, xs, xsum);
- for (int r = 0; r < NR; ++r) {
- ag[r][t] += unit_combine<UNIT>(qg[r], cg[r], xs, xsum);
- au[r][t] += unit_combine<UNIT>(qu[r], cu[r], xs, xsum);
- }
+ switch (ne) {
+ case 1: gu_body<F, LPR, NR, 1>(g0, u0, x, xs16, h, etok, c, row0, li, a, tab); break;
+ case 2: gu_body<F, LPR, NR, 2>(g0, u0, x, xs16, h, etok, c, row0, li, a, tab); break;
+ case 3: gu_body<F, LPR, NR, 3>(g0, u0, x, xs16, h, etok, c, row0, li, a, tab); break;
+ case 4: gu_body<F, LPR, NR, 4>(g0, u0, x, xs16, h, etok, c, row0, li, a, tab); break;
+ default:
+ for (int k = 0; k < ne; k += 4) {
+ const int m = min(4, ne - k);
+ if (m == 4) gu_body<F, LPR, NR, 4>(g0, u0, x, xs16, h, etok + k, c + k, row0, li, a, tab);
+ else if (m == 3) gu_body<F, LPR, NR, 3>(g0, u0, x, xs16, h, etok + k, c + k, row0, li, a, tab);
+ else if (m == 2) gu_body<F, LPR, NR, 2>(g0, u0, x, xs16, h, etok + k, c + k, row0, li, a, tab);
+ else gu_body<F, LPR, NR, 1>(g0, u0, x, xs16, h, etok + k, c + k, row0, li, a, tab);
}
+ }
+}
+
+// ---- down ---------------------------------------------------------------------------------------------------------
+template <int F, int LPR, int NR, int NE>
+static inline void dn_body(device const uchar* d0, device const float* h, device const float* hs16, device float* ye,
+ device const int* plan, int c, int row0, int li, constant MoeArgs& a,
+ threadgroup const uint* tab) {
+ constexpr int UNIT = fmt<F>::UNIT;
+ float ac[NR][NE];
+ for (int r = 0; r < NR; ++r)
+ for (int t = 0; t < NE; ++t) ac[r][t] = 0.0f;
+ const int U = int(a.n_ff) / UNIT;
+ for (int u = li; u < U; u += LPR) {
+ float q[NR][UNIT];
+ float4 sc[NR];
+ for (int r = 0; r < NR; ++r) Dec<F>::run(d0 + r * a.d_row, u, q[r], sc[r], tab);
+ for (int t = 0; t < NE; ++t) {
+ float xs[UNIT], xsum[2];
+ X<F>::load(h + (c + t) * int(a.n_ff), hs16 + (c + t) * int(a.n_ff / 16), u, xs, xsum);
+ for (int r = 0; r < NR; ++r) ac[r][t] += unit_combine<UNIT>(q[r], sc[r], xs, xsum);
}
}
for (int r = 0; r < NR; ++r)
- for (int t = 0; t < 8; ++t) {
- if (t < ne) {
- const float gv = lane_sum<LPR>(ag[r][t]), uv = lane_sum<LPR>(au[r][t]);
- if (li == 0) h[(c + t) * int(a.n_ff) + row0 + r] = gv / (1.0f + exp(-gv)) * uv;
- }
+ for (int t = 0; t < NE; ++t) {
+ const float v = lane_sum<LPR>(ac[r][t]);
+ if (li == 0) ye[(c + t) * int(a.n_embd) + row0 + r] = as_type<float>(plan[P_EW + c + t]) * v;
}
}
-// ---- down ---------------------------------------------------------------------------------------------------------
template <int F, int LPR, int NR, int SG>
kernel void moe_down(device const uchar* W [[buffer(0)]], device const float* h [[buffer(1)]],
device float* ye [[buffer(2)]], device const int* plan [[buffer(3)]],
constant MoeArgs& a [[buffer(4)]], device const float* hs16 [[buffer(5)]],
uint3 tg [[threadgroup_position_in_grid]], ushort sg [[simdgroup_index_in_threadgroup]],
ushort lane [[thread_index_in_simdgroup]], ushort tid [[thread_index_in_threadgroup]]) {
- constexpr int UNIT = fmt<F>::UNIT, RG = 32 / LPR;
+ constexpr int RG = 32 / LPR;
threadgroup uint tab[fmt<F>::TAB];
load_tab<F>(tab, tid, SG * 32);
threadgroup_barrier(mem_flags::mem_threadgroup);
@@ -159,30 +258,21 @@ kernel void moe_down(device const uchar* W [[buffer(0)]], device const float* h
const int row0 = ((int(tg.x) * SG + sg) * RG + lane / LPR) * NR;
device const uchar* blob = W + (ulong)plan[P_GEXP + g] * a.blob_bytes;
const int c = plan[P_GSTART + g], ne = plan[P_GSTART + g + 1] - c;
- float ac[NR][8];
- for (int r = 0; r < NR; ++r)
- for (int t = 0; t < 8; ++t) ac[r][t] = 0.0f;
device const uchar* d0 = blob + a.down_off + (ulong)row0 * a.d_row;
- const int U = int(a.n_ff) / UNIT;
- for (int u = li; u < U; u += LPR) {
- float q[NR][UNIT];
- float4 sc[NR];
- for (int r = 0; r < NR; ++r) Dec<F>::run(d0 + r * a.d_row, u, q[r], sc[r], tab);
- for (int t = 0; t < 8; ++t) {
- if (t < ne) {
- float xs[UNIT], xsum[2];
- X<F>::load(h + (c + t) * int(a.n_ff), hs16 + (c + t) * int(a.n_ff / 16), u, xs, xsum);
- for (int r = 0; r < NR; ++r) ac[r][t] += unit_combine<UNIT>(q[r], sc[r], xs, xsum);
+ switch (ne) {
+ case 1: dn_body<F, LPR, NR, 1>(d0, h, hs16, ye, plan, c, row0, li, a, tab); break;
+ case 2: dn_body<F, LPR, NR, 2>(d0, h, hs16, ye, plan, c, row0, li, a, tab); break;
+ case 3: dn_body<F, LPR, NR, 3>(d0, h, hs16, ye, plan, c, row0, li, a, tab); break;
+ case 4: dn_body<F, LPR, NR, 4>(d0, h, hs16, ye, plan, c, row0, li, a, tab); break;
+ default:
+ for (int k = 0; k < ne; k += 4) {
+ const int m = min(4, ne - k);
+ if (m == 4) dn_body<F, LPR, NR, 4>(d0, h, hs16, ye, plan, c + k, row0, li, a, tab);
+ else if (m == 3) dn_body<F, LPR, NR, 3>(d0, h, hs16, ye, plan, c + k, row0, li, a, tab);
+ else if (m == 2) dn_body<F, LPR, NR, 2>(d0, h, hs16, ye, plan, c + k, row0, li, a, tab);
+ else dn_body<F, LPR, NR, 1>(d0, h, hs16, ye, plan, c + k, row0, li, a, tab);
}
- }
}
- for (int r = 0; r < NR; ++r)
- for (int t = 0; t < 8; ++t) {
- if (t < ne) {
- const float v = lane_sum<LPR>(ac[r][t]);
- if (li == 0) ye[(c + t) * int(a.n_embd) + row0 + r] = as_type<float>(plan[P_EW + c + t]) * v;
- }
- }
}
kernel void moe_combine(device const float* ye [[buffer(0)]], device float* y [[buffer(1)]],
@@ -209,4 +299,5 @@ GU_SET(T_IQ2_XS)
GU_SET(T_IQ2_S)
GU_SET(T_IQ3_S)
DN_SET(T_Q2_0)
+DN_SET(T_Q2_0R)
DN_SET(T_IQ4_NL)
diff --git a/metal/kernels/quant.metal b/metal/kernels/quant.metal
index 3c7bc8cb9..32376e350 100644
--- a/metal/kernels/quant.metal
+++ b/metal/kernels/quant.metal
@@ -26,10 +26,12 @@
#define T_IQ2_S 22
#define T_IQ4_XS 23
#define T_Q2_0 42
+#define T_Q2_0R 142 // Q2_0 read with raw activations (codes - 1 in the decoder; no prepared x needed)
template <int F> struct fmt;
// QK block elements, BB block bytes, UNIT weights per unit, TAB words of threadgroup table
template <> struct fmt<T_Q2_0> { enum { QK = 64, BB = 18, UNIT = 16, TAB = 1 }; };
+template <> struct fmt<T_Q2_0R> { enum { QK = 64, BB = 18, UNIT = 16, TAB = 1 }; };
template <> struct fmt<T_IQ3_XXS> { enum { QK = 256, BB = 98, UNIT = 16, TAB = 256 + 32 }; };
template <> struct fmt<T_IQ2_XXS> { enum { QK = 256, BB = 66, UNIT = 16, TAB = 512 + 32 }; };
template <> struct fmt<T_IQ2_XS> { enum { QK = 256, BB = 74, UNIT = 16, TAB = 1024 + 32 }; };
@@ -57,6 +59,7 @@ static inline float rdh(device const uchar* p) { return float(*(device const hal
template <int F> static inline void load_tab(threadgroup uint* tab, ushort tid, ushort nth);
template <> inline void load_tab<T_Q2_0>(threadgroup uint*, ushort, ushort) {}
+template <> inline void load_tab<T_Q2_0R>(threadgroup uint*, ushort, ushort) {}
template <> inline void load_tab<T_Q8_0>(threadgroup uint*, ushort, ushort) {}
template <> inline void load_tab<T_Q4_0>(threadgroup uint*, ushort, ushort) {}
template <> inline void load_tab<T_Q5_0>(threadgroup uint*, ushort, ushort) {}
diff --git a/metal/kernels/units.metal b/metal/kernels/units.metal
index c78b01684..c074ffba4 100644
--- a/metal/kernels/units.metal
+++ b/metal/kernels/units.metal
@@ -133,6 +133,21 @@ template <> struct Dec<T_Q2_0> {
}
};
+// Q2_0 with raw x: q = c - 1 (shift, and, convert, subtract), one scale
+template <> struct Dec<T_Q2_0R> {
+ static inline void run(device const uchar* row, int u, thread float* q, thread float4& sc, threadgroup const uint*) {
+ device const uchar* b = row + (u >> 2) * 18;
+ device const ushort* p = (device const ushort*)(b + 2 + 4 * (u & 3));
+ const ushort a = p[0], c = p[1];
+ for (int j = 0; j < 8; ++j) {
+ q[j] = float((a >> (2 * j)) & 3) - 1.0f;
+ q[8 + j] = float((c >> (2 * j)) & 3) - 1.0f;
+ }
+ const float d = rdh(b);
+ sc = float4(d, d, 0.0f, 0.0f);
+ }
+};
+
static inline void scale_min_k4(int j, device const uchar* q, thread float& d, thread float& m) {
if (j < 4) {
d = float(q[j] & 63);
diff --git a/metal/src/mtl_rt.h b/metal/src/mtl_rt.h
index b933f06e1..d91b282a8 100644
--- a/metal/src/mtl_rt.h
+++ b/metal/src/mtl_rt.h
@@ -87,6 +87,8 @@ public:
// Indirect command buffer: the dispatches recorded once, executed `reps` times in one command buffer.
// Buffers are bound per command (setKernelBuffer); inline bytes are not allowed (use buffers).
double run_icb(const std::vector<Dispatch>& ds, int reps, bool barrier_between);
+ // Runs `ds` repeatedly for about `seconds` of wall time: lifts the GPU out of its idle clocks before a timing.
+ void warm(const std::vector<Dispatch>& ds, double seconds = 0.3);
std::string ggml_common_path; // where ggml-common.h is read from
std::string kernel_dir; // where relative kernel paths resolve
diff --git a/metal/src/mtl_rt.mm b/metal/src/mtl_rt.mm
index f876dd2ae..59168cdce 100644
--- a/metal/src/mtl_rt.mm
+++ b/metal/src/mtl_rt.mm
@@ -229,6 +229,11 @@ double Context::run_wall(const std::vector<Dispatch>& ds, int reps, double* gpu_
return now_s() - t0;
}
+void Context::warm(const std::vector<Dispatch>& ds, double seconds) {
+ const double t0 = now_s();
+ while (now_s() - t0 < seconds) run(ds);
+}
+
double Context::run_icb(const std::vector<Dispatch>& ds, int reps, bool barrier_between) {
@autoreleasepool {
size_t maxb = 1;
diff --git a/metal/tests/expert_parity.cpp b/metal/tests/expert_parity.cpp
index fa50bdc3f..2c3a6df0f 100644
--- a/metal/tests/expert_parity.cpp
+++ b/metal/tests/expert_parity.cpp
@@ -118,6 +118,7 @@ mtl::Dispatch prep_dispatch(const mtl::Pipeline& p, const mtl::Buffer& x, const
}
int g_gu_type = 0, g_dn_type = 0;
+bool g_dn_prep = false; // Q2_0 down: prepared h (an xprep dispatch) instead of the raw-x decoder
const mtl::Buffer* g_xpx = nullptr;
const mtl::Buffer* g_xph = nullptr;
@@ -145,11 +146,12 @@ void encode_layer(std::vector<mtl::Dispatch>& ds, const Kernels& K, const mtl::B
ds.push_back(d);
}
if (with_dn) {
- if (xkind(g_dn_type)) ds.push_back(prep_dispatch(K.prep, h, XPH, N_FF, CAPE));
+ const int dk = g_dn_prep ? xkind(g_dn_type) : 0;
+ if (dk) ds.push_back(prep_dispatch(K.prep, h, XPH, N_FF, CAPE));
mtl::Dispatch d;
d.p = &K.dn;
d.args = {mtl::Arg::B(W, w_off),
- xkind(g_dn_type) ? mtl::Arg::B(XPH, 4 * PLANE_H * xkind(g_dn_type)) : mtl::Arg::B(h), mtl::Arg::B(ye),
+ dk ? mtl::Arg::B(XPH, 4 * PLANE_H * dk) : mtl::Arg::B(h), mtl::Arg::B(ye),
mtl::Arg::B(plan, plan_off), mtl::Arg::V(a), mtl::Arg::B(XPH, 4 * PLANE_H * 4)};
d.tg[0] = K.cdn.S * 32;
d.indirect = &plan;
@@ -204,6 +206,7 @@ int main(int argc, char** argv) {
else if (a == "--layers") layers = std::atoi(nx());
else if (a == "--reps") reps = std::atoi(nx());
else if (a == "--share") share = std::atof(nx());
+ else if (a == "--dn-prep") g_dn_prep = true;
else { std::fprintf(stderr, "unknown argument %s\n", a.c_str()); return 2; }
}
(void)cfg_gu_set;
@@ -221,7 +224,7 @@ int main(int argc, char** argv) {
K.prep = cx.pipeline(lib, "xprep");
K.comb = cx.pipeline(lib, "moe_combine");
K.gu = cx.pipeline(lib, kname("moe_gu", gu, a));
- K.dn = cx.pipeline(lib, kname("moe_down", dn, b));
+ K.dn = cx.pipeline(lib, kname("moe_down", dn == ref::Q2_0 && !g_dn_prep ? 142 : dn, b));
K.cgu = a;
K.cdn = b;
return K;
@@ -386,6 +389,7 @@ int main(int argc, char** argv) {
for (auto& z : d) dall.push_back(z);
}
cx.run(dp); // plans in place
+ cx.warm(dall, 0.1);
std::vector<double> tp, tg, td, ta;
for (int it = 0; it < 7; ++it) {
tp.push_back(cx.run(dp) / reps);
diff --git a/metal/tests/gemv_parity.cpp b/metal/tests/gemv_parity.cpp
index e2d3583c2..a7c16f5a1 100644
--- a/metal/tests/gemv_parity.cpp
+++ b/metal/tests/gemv_parity.cpp
@@ -239,7 +239,7 @@ int main(int argc, char** argv) {
d.tg[0] = c.S * 32;
ds.push_back(d);
}
- cx.run(ds);
+ cx.warm(ds, 0.05);
std::vector<double> t;
for (int i = 0; i < 5; ++i) t.push_back(cx.run(ds) / R);
const double m = median(t);
diff --git a/metal/tests/gr_parity.cpp b/metal/tests/gr_parity.cpp
new file mode 100644
index 000000000..642a2e258
--- /dev/null
+++ b/metal/tests/gr_parity.cpp
@@ -0,0 +1,187 @@
+// metal/tests/gr_parity.cpp - the hyper-connection read (gr.metal) against a double-precision CPU reference
+// (fused_gr.hpp's formulas), and its speed.
+//
+// gr_parity [--ntok N] parity for N = 1, 3, 8 (or N), with and without the folded write
+// gr_parity --bench [--ntok N] per-kernel GPU time, 8 weight sets rotated (no cache reuse across calls)
+#include "mtl_rt.h"
+#include "ref_quant.h"
+
+#include <algorithm>
+#include <cmath>
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
+#include <string>
+#include <vector>
+
+namespace {
+constexpr int N = 2560, HC = 4, LR = 320, NIN = HC * N;
+struct GrArgs { uint32_t n_embd, hc, hc_lr, n_tok, apply; float eps; };
+double median(std::vector<double> v) { std::sort(v.begin(), v.end()); return v[v.size() / 2]; }
+struct Err {
+ double se = 0, sr = 0, mx = 0, mr = 0;
+ void add(double g, double r) { se += (g - r) * (g - r); sr += r * r; mx = std::max(mx, std::fabs(g - r)); mr = std::max(mr, std::fabs(r)); }
+ double l2() const { return sr > 0 ? std::sqrt(se / sr) : std::sqrt(se); }
+};
+} // namespace
+
+int main(int argc, char** argv) {
+ bool bench = false;
+ std::vector<int> ntoks = {1, 3, 8};
+ for (int i = 1; i < argc; ++i) {
+ std::string a = argv[i];
+ if (a == "--bench") bench = true;
+ else if (a == "--ntok") ntoks = {std::atoi(argv[++i])};
+ }
+ mtl::Context cx;
+ const int lib = cx.compile({"quant.metal", "units.metal", "gr.metal"});
+ std::printf("device %s\n", cx.device_name().c_str());
+ const int SETS = bench ? 48 : 1;
+ const size_t wd_bytes = (size_t)LR * NIN * 2, wi_bytes = (size_t)HC * NIN * 2, wu_bytes = (size_t)NIN * LR * 2;
+ const size_t set_bytes = wd_bytes + wi_bytes + wu_bytes + NIN * 4;
+ mtl::Buffer W = cx.alloc(set_bytes * SETS);
+ ref::Rng rng(3);
+ for (int s = 0; s < SETS; ++s) {
+ uint8_t* b = W.as<uint8_t>() + s * set_bytes;
+ ref::random_blocks(ref::BF16, b, LR, NIN, 11 + s, 0.02f);
+ ref::random_blocks(ref::BF16, b + wd_bytes, HC, NIN, 22 + s, 0.02f);
+ ref::random_blocks(ref::BF16, b + wd_bytes + wi_bytes, NIN, LR, 33 + s, 0.1f);
+ float* wn = (float*)(b + wd_bytes + wi_bytes + wu_bytes);
+ for (int i = 0; i < NIN; ++i) wn[i] = 1.0f + 0.1f * rng.sym();
+ }
+ const int MAXT = 8;
+ mtl::Buffer R = cx.alloc(4 * MAXT * NIN), R0 = cx.alloc(4 * MAXT * NIN), bo = cx.alloc(4 * MAXT * N),
+ inj = cx.alloc(4 * MAXT * HC), xn = cx.alloc(4 * MAXT * NIN), lo = cx.alloc(4 * MAXT * LR),
+ injo = cx.alloc(4 * MAXT * HC), xp = cx.alloc(4 * (4 * MAXT * N + MAXT * N / 16)),
+ xr = cx.alloc(4 * (4 * MAXT * N + MAXT * N / 16));
+ for (int i = 0; i < MAXT * NIN; ++i) R0.as<float>()[i] = rng.sym() * 2.0f;
+ for (int i = 0; i < MAXT * N; ++i) bo.as<float>()[i] = rng.sym();
+ for (int i = 0; i < MAXT * HC; ++i) inj.as<float>()[i] = rng.sym() * 3.0f;
+ mtl::Pipeline pprep = cx.pipeline(lib, "xprep");
+ int fails = 0;
+ for (int nt : ntoks) {
+ mtl::Pipeline pn = cx.pipeline(lib, "gr_norm"), pd = cx.pipeline(lib, "gr_down_8_8", mtl::Constants().i(1, nt)),
+ pu = cx.pipeline(lib, "gr_up", mtl::Constants().i(1, nt));
+ for (int apply = 0; apply < 2; ++apply) {
+ GrArgs a{N, HC, LR, (uint32_t)nt, (uint32_t)apply, 1e-6f};
+ std::memcpy(R.ptr, R0.ptr, R.bytes);
+ auto enc = [&](int set, std::vector<mtl::Dispatch>& ds, int which) {
+ const size_t o = (size_t)set * set_bytes;
+ mtl::Dispatch d;
+ if (which & 1) {
+ d.p = &pn;
+ d.args = {mtl::Arg::B(R), mtl::Arg::B(bo), mtl::Arg::B(inj), mtl::Arg::B(W, o + wd_bytes + wi_bytes + wu_bytes),
+ mtl::Arg::B(xn), mtl::Arg::V(a)};
+ d.grid[0] = HC;
+ d.grid[1] = nt;
+ d.tg[0] = 256;
+ ds.push_back(d);
+ }
+ if (which & 2) {
+ mtl::Dispatch e;
+ e.p = &pd;
+ e.args = {mtl::Arg::B(W, o), mtl::Arg::B(W, o + wd_bytes), mtl::Arg::B(xn), mtl::Arg::B(lo),
+ mtl::Arg::B(injo), mtl::Arg::V(a)};
+ e.grid[0] = LR + HC; // RS = 1 row per threadgroup (8 simdgroups split it)
+ e.tg[0] = 256;
+ ds.push_back(e);
+ }
+ if (which & 4) {
+ mtl::Dispatch f;
+ f.p = &pu;
+ f.args = {mtl::Arg::B(W, o + wd_bytes + wi_bytes), mtl::Arg::B(lo), mtl::Arg::B(xn), mtl::Arg::B(xp),
+ mtl::Arg::V(a)};
+ f.grid[0] = N / 16;
+ f.tg[0] = 256;
+ ds.push_back(f);
+ }
+ };
+ if (!bench) {
+ std::vector<mtl::Dispatch> ds;
+ enc(0, ds, 7);
+ cx.run(ds);
+ // reference
+ const uint8_t* b = W.as<uint8_t>();
+ std::vector<float> wd((size_t)LR * NIN), wi((size_t)HC * NIN), wu((size_t)NIN * LR);
+ ref::dequant(ref::BF16, b, wd.data(), wd.size());
+ ref::dequant(ref::BF16, b + wd_bytes, wi.data(), wi.size());
+ ref::dequant(ref::BF16, b + wd_bytes + wi_bytes, wu.data(), wu.size());
+ const float* wn = (const float*)(b + wd_bytes + wi_bytes + wu_bytes);
+ Err eR, elo, einj, emix;
+ for (int t = 0; t < nt; ++t) {
+ std::vector<double> r(NIN), x(NIN), l(LR);
+ for (int c = 0; c < HC; ++c) {
+ const double g = apply ? 2.0 / (1.0 + std::exp(-(double)inj.as<float>()[t * HC + c] / HC)) : 0.0;
+ double ss = 0;
+ for (int d = 0; d < N; ++d) {
+ double v = R0.as<float>()[t * NIN + c * N + d];
+ if (apply) v += bo.as<float>()[t * N + d] * g;
+ r[c * N + d] = v;
+ ss += v * v;
+ }
+ const double rs = 1.0 / std::sqrt(ss / N + 1e-6);
+ for (int d = 0; d < N; ++d) x[c * N + d] = r[c * N + d] * wn[c * N + d] * rs;
+ }
+ for (int i = 0; i < NIN; ++i) eR.add(R.as<float>()[t * NIN + i], r[i]);
+ for (int k = 0; k < LR; ++k) {
+ double s = 0;
+ for (int i = 0; i < NIN; ++i) s += (double)wd[(size_t)k * NIN + i] * x[i];
+ const double z = s / HC;
+ l[k] = z / (1.0 + std::exp(-z));
+ elo.add(lo.as<float>()[t * LR + k], l[k]);
+ }
+ for (int c = 0; c < HC; ++c) {
+ double s = 0;
+ for (int i = 0; i < NIN; ++i) s += (double)wi[(size_t)c * NIN + i] * x[i];
+ einj.add(injo.as<float>()[t * HC + c], s);
+ }
+ for (int d = 0; d < N; ++d) {
+ double m = 0;
+ for (int c = 0; c < HC; ++c) {
+ double s = 0;
+ // the up projection reads the GPU's lo, so the check isolates gr_up
+ for (int k = 0; k < LR; ++k) s += (double)wu[(size_t)(c * N + d) * LR + k] * lo.as<float>()[t * LR + k];
+ m += x[c * N + d] / (1.0 + std::exp(-s));
+ }
+ emix.add(xp.as<float>()[t * N + d], m / HC);
+ }
+ }
+ // the prepared planes must be bitwise xprep's of the raw plane
+ {
+ mtl::Dispatch d;
+ d.p = &pprep;
+ const uint32_t n = N, ntt = nt;
+ d.args = {mtl::Arg::B(xp), mtl::Arg::B(xr), mtl::Arg::V(n), mtl::Arg::V(ntt)};
+ d.tg[0] = 256;
+ d.grid[0] = (N / 16 * nt + 255) / 256;
+ cx.run({d});
+ }
+ const size_t elems = (size_t)4 * nt * N + (size_t)nt * N / 16;
+ const bool planes = std::memcmp(xp.ptr, xr.ptr, 4 * elems) == 0;
+ const bool ok = eR.l2() < 1e-6 && elo.l2() < 1e-5 && einj.l2() < 1e-5 && emix.l2() < 1e-5 && planes;
+ fails += !ok;
+ std::printf("parity ntok %d apply %d: R rel L2 %.2e, lo %.2e, inject %.2e, mixed %.2e, prepared planes "
+ "== xprep: %s %s\n", nt, apply, eR.l2(), elo.l2(), einj.l2(), emix.l2(),
+ planes ? "bitwise" : "NO", ok ? "PASS" : "FAIL");
+ } else {
+ for (int which : {1, 2, 4, 7}) {
+ std::vector<mtl::Dispatch> ds;
+ for (int r = 0; r < 96; ++r) enc(r % SETS, ds, which);
+ cx.warm(ds, 0.1);
+ std::vector<double> ts;
+ for (int i = 0; i < 7; ++i) ts.push_back(cx.run(ds) / 96);
+ const double m = median(ts);
+ const double bytes = which == 1 ? 2.0 * nt * NIN * 4 + NIN * 4 + nt * NIN * 4
+ : which == 2 ? wd_bytes + wi_bytes
+ : which == 4 ? wu_bytes
+ : wd_bytes + wi_bytes + wu_bytes;
+ std::printf("bench ntok %d apply %d %-8s %7.2f us %6.1f GB/s (%.2f MB)\n", nt, apply,
+ which == 1 ? "norm" : which == 2 ? "down" : which == 4 ? "up" : "all 3", m * 1e6,
+ bytes / m / 1e9, bytes / 1e6);
+ }
+ }
+ }
+ }
+ if (!bench) std::printf("%s\n", fails ? "SOME FAILED" : "ALL PASS");
+ return fails ? 1 : 0;
+}
diff --git a/metal/tests/route_parity.cpp b/metal/tests/route_parity.cpp
new file mode 100644
index 000000000..849f5934b
--- /dev/null
+++ b/metal/tests/route_parity.cpp
@@ -0,0 +1,90 @@
+// metal/tests/route_parity.cpp - moe_route (softmax + top-10 + the expert plan) against a CPU replica of
+// native_router.cu's rule, for 1..8 tokens; logits with deliberate ties.
+#include "mtl_rt.h"
+#include "ref_quant.h"
+
+#include <algorithm>
+#include <cfloat>
+#include <cmath>
+#include <cstdio>
+#include <cstring>
+#include <set>
+#include <vector>
+
+namespace {
+constexpr int P_NG = 0, P_MAXE = 128, P_GEXP = 16, P_GSTART = P_GEXP + P_MAXE, P_ETOK = P_GSTART + P_MAXE + 4,
+ P_EW = P_ETOK + P_MAXE, P_TOKENT = P_EW + P_MAXE, P_INTS = P_TOKENT + P_MAXE;
+struct MoeArgs {
+ uint64_t blob_bytes, up_off, down_off;
+ uint32_t gu_row, d_row, n_embd, n_ff, n_tok, topk, n_expert, gx_gu, gx_dn, pad;
+};
+} // namespace
+
+int main() {
+ mtl::Context cx;
+ const int lib = cx.compile({"quant.metal", "units.metal", "moe.metal"});
+ mtl::Pipeline p = cx.pipeline(lib, "moe_route");
+ mtl::Buffer lg = cx.alloc(4 * 8 * 512), ids = cx.alloc(4 * 80), w = cx.alloc(4 * 80), plan = cx.alloc(4 * P_INTS);
+ ref::Rng r(9);
+ int fails = 0;
+ double worst_w = 0;
+ for (int trial = 0; trial < 200; ++trial) {
+ const int nt = 1 + trial % 8;
+ for (int i = 0; i < nt * 512; ++i) {
+ float v = r.sym() * 4.0f;
+ if (trial % 3 == 0) v = std::round(v * 4.0f) / 4.0f; // many exact ties
+ lg.as<float>()[i] = v;
+ }
+ MoeArgs a{};
+ a.n_tok = nt;
+ a.topk = 10;
+ a.n_expert = 512;
+ a.gx_gu = 1;
+ a.gx_dn = 1;
+ mtl::Dispatch d;
+ d.p = &p;
+ d.args = {mtl::Arg::B(lg), mtl::Arg::B(ids), mtl::Arg::B(w), mtl::Arg::B(plan), mtl::Arg::V(a)};
+ d.tg[0] = 512;
+ cx.run({d});
+ for (int t = 0; t < nt; ++t) {
+ const float* l = lg.as<float>() + t * 512;
+ float mx = -INFINITY;
+ for (int e = 0; e < 512; ++e) mx = std::max(mx, l[e]);
+ std::vector<double> pr(512);
+ double s = 0;
+ for (int e = 0; e < 512; ++e) s += (pr[e] = std::exp((double)l[e] - mx));
+ for (int e = 0; e < 512; ++e) pr[e] /= s;
+ // top 10: largest probability, ties -> lower index (probabilities of equal logits are equal)
+ std::vector<int> order(512);
+ for (int e = 0; e < 512; ++e) order[e] = e;
+ std::stable_sort(order.begin(), order.end(), [&](int x, int y) { return l[x] > l[y]; });
+ double ssum = 0;
+ for (int k = 0; k < 10; ++k) ssum += pr[order[k]];
+ for (int k = 0; k < 10; ++k) {
+ if (ids.as<int>()[t * 10 + k] != order[k]) { ++fails; break; }
+ const double ref = pr[order[k]] / std::max(ssum, 6.103515625e-5);
+ worst_w = std::max(worst_w, std::fabs(w.as<float>()[t * 10 + k] - ref) / ref);
+ }
+ }
+ // the plan
+ const int* P = plan.as<int>();
+ std::set<int> distinct(ids.as<int>(), ids.as<int>() + nt * 10);
+ bool ok = P[P_NG] == (int)distinct.size();
+ int gi = 0;
+ for (int e : distinct) {
+ if (P[P_GEXP + gi] != e) ok = false;
+ int j = P[P_GSTART + gi];
+ for (int i = 0; i < nt * 10; ++i)
+ if (ids.as<int>()[i] == e) {
+ if (P[P_ETOK + j] != i / 10 || P[P_TOKENT + i] != j) ok = false;
+ ++j;
+ }
+ if (j != P[P_GSTART + gi + 1]) ok = false;
+ ++gi;
+ }
+ fails += !ok;
+ }
+ std::printf("route parity, 200 windows of 1..8 tokens (a third with exact ties): ids/plan mismatches %d, worst weight "
+ "rel err %.2e %s\n", fails, worst_w, fails == 0 && worst_w < 2e-6 ? "PASS" : "FAIL");
+ return fails ? 1 : 0;
+}