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
35.0 KiB694 linesraw
1// metal/tests/expert_parity.cpp - the grouped routed-expert kernels (moe.metal) against a double-precision CPU
2// reference, and their speed.
3//
4//   expert_parity [--gu Q2_0] [--dn Q2_0] [--ntok 1..8] [--gucfg L,R,S] [--dncfg L,R,S]     parity (synthetic)
5//   expert_parity --bench [--gu ..] [--dn ..] [--ntok N] [--layers 8] [--reps 96] [--sweep]  speed
6//   EXPERT_F16=1 expert_parity [--ntok N] [--gucfg ..] [--dncfg ..]     the fp16 experts (STRATA_METAL_F16, Q2_0 only)
7//
8// Gyro (agentionai's trellis experts, TQ2_T / TQK6 / TQK7):
9//   expert_parity --gu TQK6 --dn TQK7 [--had-pack <pack dir>]       synthetic blocks; with a pack, the Hadamard rotation of
10//                                                                   x (CPU) and of h (the Metal had128 kernel) is part of it
11//   expert_parity --gguf <Gyro file> --layer L [--had-pack <pack dir>] [--ntok N] [--seed S]   REAL experts of layer L (64 of
12//                                                                   the 512, random) instead of random blocks
13//   expert_parity --had-test [--had-pack <pack dir>]                the Metal had128 kernels (f32, f16, f16 rows) against the CPU rotation, bitwise
14//
15// Parity: random valid blocks for 64 experts, random activations x ~ U(-1,1), random distinct top-10 per token,
16// weights summing to 1.  Checked: the plan (groups by expert id, entries in (token, k) order), h = silu(gate) * up
17// per entry and y = sum_k w * down . h, each against double; reported as max |err| / max |ref| and relative L2.
18// Bench: `layers` distinct copies of a 512-expert arena (no reuse across reps beyond chance; the SLC is ~32 MB),
19// a different random routing per rep; GB/s = bytes of the distinct experts the kernel must read / GPU time.
20#include "mtl_rt.h"
21#include "ref_quant.h"
22#include "engine/geo.h"
23#include "gguf_lite.h"
24// Gyro: the engine's CPU Hadamard rotation (the reference of the Metal one) and hadamard.txt's parser
25#include "../../src/kernels/cpu/hadamard.cpp"
26
27#include <algorithm>
28#include <cmath>
29#include <cstdio>
30#include <cstdlib>
31#include <cstring>
32#include <map>
33#include <set>
34#include <string>
35#include <vector>
36
37#include "ggml-common-tq.h"
38const uint16_t* tq_lut_for_test() { return tq_lut_f16; }
39
40namespace {
41
42int N_EMBD = strata_metal::geo::N, N_FF = strata_metal::geo::NFF;   // the shape this build is compiled for (engine/geo.h); --embd / --ff change them (Q4-KQ: expert widths 512 and 1024)
43constexpr int TOPK = strata_metal::geo::TOPK;
44// plan layout (moe.metal)
45constexpr int P_NG = 0, P_IGU = 4, P_IDN = 8, P_MAXE = 128, P_GEXP = 16, P_GSTART = P_GEXP + P_MAXE,
46              P_ETOK = P_GSTART + P_MAXE + 4, P_EW = P_ETOK + P_MAXE, P_TOKENT = P_EW + P_MAXE,
47              P_INTS = P_TOKENT + P_MAXE;
48
49struct MoeArgs {
50    uint64_t gate_off, up_off, down_off, gu_stride, d_stride;
51    uint32_t gu_row, d_row, n_embd, n_ff, n_tok, topk, n_expert, gx_gu, gx_dn, pad;
52};
53
54int type_of(const std::string& s) {
55    for (int t : {ref::TQ2_T, ref::TQK6, ref::TQK7, ref::Q2_0, ref::IQ3_XXS, ref::IQ2_XXS, ref::IQ2_XS, ref::IQ2_S, ref::IQ3_S, ref::IQ4_NL, ref::IQ4_XS, ref::Q3_K, ref::Q4_K, ref::Q5_K, ref::Q6_K, ref::Q8_0, ref::Q5_1, ref::Q5_0})
56        if (s == ref::type_name(t)) return t;
57    std::fprintf(stderr, "unknown type %s\n", s.c_str());
58    std::exit(2);
59}
60
61struct Cfg { int L, R, S; };
62Cfg parse_cfg(const char* s) {
63    Cfg c{};
64    if (std::sscanf(s, "%d,%d,%d", &c.L, &c.R, &c.S) != 3) { std::fprintf(stderr, "bad cfg %s\n", s); std::exit(2); }
65    return c;
66}
67std::string kname(const char* k, int t, Cfg c) {
68    return std::string(k) + "_" + std::to_string(t) + "_" + std::to_string(c.L) + "_" + std::to_string(c.R) + "_" +
69           std::to_string(c.S);
70}
71int rows_per_tg(Cfg c) { return c.S * (32 / c.L) * c.R; }
72
73struct Layout {
74    int gu, dn;
75    size_t gu_row, d_row, up_off, down_off, blob;
76};
77Layout layout(int gu, int dn) {
78    Layout L{gu, dn};
79    L.gu_row = ref::row_bytes(gu, N_EMBD);
80    L.d_row = ref::row_bytes(dn, N_FF);
81    L.up_off = (size_t)N_FF * L.gu_row;
82    L.down_off = 2 * L.up_off;
83    L.blob = L.down_off + (size_t)N_EMBD * L.d_row;
84    return L;
85}
86
87void random_routing(ref::Rng& r, int ntok, int n_expert, std::vector<int>& ids, std::vector<float>& w,
88                    double share = 0.0, const std::vector<int>* prev = nullptr) {
89    ids.assign(ntok * TOPK, 0);
90    w.assign(ntok * TOPK, 0.0f);
91    for (int t = 0; t < ntok; ++t) {
92        std::set<int> used;
93        float sum = 0;
94        for (int k = 0; k < TOPK; ++k) {
95            int e;
96            do {
97                // with probability `share`, reuse an expert of the previous token (verify windows share experts)
98                if (t > 0 && share > 0 && r.uni() < share) e = ids[(t - 1) * TOPK + (r.next() % TOPK)];
99                else e = (int)(r.next() % n_expert);
100            } while (used.count(e));
101            used.insert(e);
102            ids[t * TOPK + k] = e;
103            w[t * TOPK + k] = 0.2f + r.uni();
104            sum += w[t * TOPK + k];
105        }
106        for (int k = 0; k < TOPK; ++k) w[t * TOPK + k] /= sum;
107    }
108    (void)prev;
109}
110
111struct Kernels {
112    mtl::Pipeline plan, gu, dn, comb, prep;
113    Cfg cgu, cdn;
114};
115int xkind(int t) {
116    switch (t) {
117        case ref::Q2_0: return 1;
118        case ref::Q4_K: case ref::Q5_K: return 2;
119        case ref::Q6_K: case ref::Q3_K: return 3;
120        default: return 0;
121    }
122}
123constexpr int CAPE = 8 * TOPK;                     // entries capacity of h
124// prepared buffers: x [8][N_EMBD] -> XPX, h [CAPE][N_FF] -> XPH (4 planes + S16)
125#define PLANE_X ((size_t)8 * N_EMBD)
126#define PLANE_H ((size_t)CAPE * N_FF)
127
128mtl::Dispatch prep_dispatch(const mtl::Pipeline& p, const mtl::Buffer& x, const mtl::Buffer& xp, uint32_t n, uint32_t nt) {
129    mtl::Dispatch d;
130    d.p = &p;
131    d.args = {mtl::Arg::B(x), mtl::Arg::B(xp), mtl::Arg::V(n), mtl::Arg::V(nt)};
132    d.tg[0] = 256;
133    d.grid[0] = (n / 16 * nt + 255) / 256;
134    return d;
135}
136
137int g_gu_type = 0, g_dn_type = 0;
138// Gyro: the rotation of h between the gate/up and the down dispatch (the Metal had128_f32 kernel, signs of width n_ff)
139struct HadArgs { uint32_t width, x_stride, y_stride; float scale; uint32_t has_signs, pad; };
140const mtl::Pipeline* g_had32 = nullptr;
141const mtl::Buffer* g_hsh = nullptr;
142bool g_had_h = false;
143bool g_dn_prep = false;   // Q2_0 down: prepared h (an xprep dispatch) instead of the raw-x decoder
144const mtl::Buffer* g_xpx = nullptr;
145const mtl::Buffer* g_xph = nullptr;
146// EXPERT_F16=1: moe_gu16 / moe_down16 (STRATA_METAL_F16) - x from the half plane x * 4^-(i % 4), h handed down as half
147const bool g_f16 = std::getenv("EXPERT_F16") != nullptr;
148const mtl::Buffer* g_h16 = nullptr;
149
150void encode_layer(std::vector<mtl::Dispatch>& ds, const Kernels& K, const mtl::Buffer& W, size_t w_off,
151                  const mtl::Buffer& x, const mtl::Buffer& h, const mtl::Buffer& ye, const mtl::Buffer& y,
152                  const mtl::Buffer& ids, const mtl::Buffer& wts, const mtl::Buffer& plan, size_t plan_off,
153                  const MoeArgs& a, bool with_plan, bool with_gu, bool with_dn, bool with_comb) {
154    const mtl::Buffer& XPX = *g_xpx;
155    const mtl::Buffer& XPH = *g_xph;
156    if (with_plan) {
157        mtl::Dispatch d;
158        d.p = &K.plan;
159        d.args = {mtl::Arg::B(ids), mtl::Arg::B(wts), mtl::Arg::B(plan, plan_off), mtl::Arg::V(a)};
160        d.tg[0] = 512;
161        ds.push_back(d);
162    }
163    if (with_gu) {
164        mtl::Dispatch d;
165        d.p = &K.gu;
166        d.args = {mtl::Arg::B(W, w_off), mtl::Arg::B(XPX, 4 * PLANE_X * xkind(g_gu_type)), mtl::Arg::B(h),
167                  mtl::Arg::B(plan, plan_off), mtl::Arg::V(a), mtl::Arg::B(XPX, 4 * PLANE_X * 4)};
168        if (g_f16) {
169            d.args[1] = mtl::Arg::B(XPX, 4 * (4 * PLANE_X + PLANE_X / 16) + 2 * PLANE_X);
170            d.args.push_back(mtl::Arg::B(*g_h16));
171        }
172        d.tg[0] = K.cgu.S * 32;
173        d.indirect = &plan;
174        d.ind_off = plan_off + P_IGU * 4;
175        ds.push_back(d);
176        if (g_had_h) {   // H h in place, one row per entry (the entries are the window's token x k)
177            static HadArgs ha;
178            ha = HadArgs{(uint32_t)N_FF, (uint32_t)N_FF, (uint32_t)N_FF, 1.0f / std::sqrt(128.0f), g_hsh ? 1u : 0u, 0u};
179            mtl::Dispatch hd;
180            hd.p = g_had32;
181            hd.args = {mtl::Arg::B(h), mtl::Arg::B(h), mtl::Arg::B(g_hsh ? *g_hsh : h), mtl::Arg::V(ha)};
182            hd.grid[0] = N_FF / 128;
183            hd.grid[1] = a.n_tok * TOPK;
184            hd.tg[0] = 128;
185            ds.push_back(hd);
186        }
187    }
188    if (with_dn) {
189        const int dk = g_dn_prep ? xkind(g_dn_type) : 0;
190        if (dk) ds.push_back(prep_dispatch(K.prep, h, XPH, N_FF, CAPE));
191        mtl::Dispatch d;
192        d.p = &K.dn;
193        d.args = {mtl::Arg::B(W, w_off),
194                  dk ? mtl::Arg::B(XPH, 4 * PLANE_H * dk) : mtl::Arg::B(h), mtl::Arg::B(ye),
195                  mtl::Arg::B(plan, plan_off), mtl::Arg::V(a), mtl::Arg::B(XPH, 4 * PLANE_H * 4)};
196        if (g_f16) d.args = {mtl::Arg::B(W, w_off), mtl::Arg::B(*g_h16), mtl::Arg::B(ye), mtl::Arg::B(plan, plan_off), mtl::Arg::V(a)};
197        d.tg[0] = K.cdn.S * 32;
198        d.indirect = &plan;
199        d.ind_off = plan_off + P_IDN * 4;
200        ds.push_back(d);
201    }
202    if (with_comb) {
203        mtl::Dispatch d;
204        d.p = &K.comb;
205        d.args = {mtl::Arg::B(ye), mtl::Arg::B(y), mtl::Arg::B(plan, plan_off), mtl::Arg::V(a)};
206        d.tg[0] = 256;
207        d.grid[0] = (a.n_tok * N_EMBD + 255) / 256;
208        ds.push_back(d);
209    }
210}
211
212struct Err {
213    double max_abs = 0, max_ref = 0, se = 0, sr = 0;
214    void add(double got, double ref) {
215        max_abs = std::max(max_abs, std::fabs(got - ref));
216        max_ref = std::max(max_ref, std::fabs(ref));
217        se += (got - ref) * (got - ref);
218        sr += ref * ref;
219    }
220    double rel_max() const { return max_ref > 0 ? max_abs / max_ref : max_abs; }
221    double rel_l2() const { return sr > 0 ? std::sqrt(se / sr) : std::sqrt(se); }
222};
223
224double median(std::vector<double> v) {
225    std::sort(v.begin(), v.end());
226    return v[v.size() / 2];
227}
228
229}  // namespace
230
231int main(int argc, char** argv) {
232    int gu = ref::Q2_0, dn = ref::Q2_0, ntok = 1, layers = 8, reps = 96;
233    Cfg cgu{32, 2, 4}, cdn{8, 2, 4};
234    bool bench = false, sweep = false, had_test = false, decode_check = false;
235    double share = 0.0;
236    std::string gguf_path, had_pack;
237    int real_layer = 0, experts_first = 0;
238    uint64_t seed = 1;
239    bool cfg_gu_set = false, cfg_dn_set = false;
240    for (int i = 1; i < argc; ++i) {
241        std::string a = argv[i];
242        auto nx = [&] { return i + 1 < argc ? argv[++i] : (std::fprintf(stderr, "%s needs a value\n", a.c_str()), std::exit(2), (char*)nullptr); };
243        if (a == "--gu") gu = type_of(nx());
244        else if (a == "--dn") dn = type_of(nx());
245        else if (a == "--ntok") ntok = std::atoi(nx());
246        else if (a == "--gucfg") { cgu = parse_cfg(nx()); cfg_gu_set = true; }
247        else if (a == "--dncfg") { cdn = parse_cfg(nx()); cfg_dn_set = true; }
248        else if (a == "--bench") bench = true;
249        else if (a == "--sweep") sweep = true;
250        else if (a == "--layers") layers = std::atoi(nx());
251        else if (a == "--reps") reps = std::atoi(nx());
252        else if (a == "--share") share = std::atof(nx());
253        else if (a == "--dn-prep") g_dn_prep = true;
254        else if (a == "--gguf") gguf_path = nx();
255        else if (a == "--layer") real_layer = std::atoi(nx());
256        else if (a == "--experts-first") experts_first = std::atoi(nx());   // only experts 0..N-1 of the layer are in the file (a sparse copy)
257        else if (a == "--had-pack") had_pack = nx();
258        else if (a == "--had-test") had_test = true;
259        else if (a == "--decode-check") decode_check = true;
260        else if (a == "--ff") N_FF = std::atoi(nx());
261        else if (a == "--embd") N_EMBD = std::atoi(nx());
262        else if (a == "--seed") seed = std::strtoull(nx(), nullptr, 10);
263        else { std::fprintf(stderr, "unknown argument %s\n", a.c_str()); return 2; }
264    }
265    (void)cfg_gu_set;
266    (void)cfg_dn_set;
267    if (dn == ref::IQ4_NL && cdn.L == 8 && !cfg_dn_set) cdn = {4, 2, 4};
268    gguf::File gf;
269    const gguf::Tensor *tg_ = nullptr, *tu_ = nullptr, *td_ = nullptr;
270    if (!gguf_path.empty()) {   // real experts: the types come from the file
271        std::string err;
272        if (!gf.open(gguf_path, err)) { std::fprintf(stderr, "%s\n", err.c_str()); return 2; }
273        const std::string b = "blk." + std::to_string(real_layer) + ".";
274        tg_ = gf.find(b + "ffn_gate_exps.weight");
275        tu_ = gf.find(b + "ffn_up_exps.weight");
276        td_ = gf.find(b + "ffn_down_exps.weight");
277        if (!tg_ || !tu_ || !td_) { std::fprintf(stderr, "no routed experts in layer %d of %s\n", real_layer, gguf_path.c_str()); return 2; }
278        gu = tg_->type;
279        dn = td_->type;
280    }
281    mtl::Context cx;
282    if (g_f16 && (gu != ref::Q2_0 || dn != ref::Q2_0 || g_dn_prep || !had_pack.empty())) {
283        std::fprintf(stderr, "EXPERT_F16: Q2_0 gate/up and down only, without --dn-prep and Hadamard\n");
284        return 2;
285    }
286    // the host defines STRATA_KQ_DOWN only for a model whose downs are K-quant / IQ4_XS / IQ3_S (window.cpp kq_down_prelude)
287    const bool kq_dn = dn == ref::Q3_K || dn == ref::Q4_K || dn == ref::Q5_K || dn == ref::Q6_K || dn == ref::IQ3_S || dn == ref::IQ4_XS;
288    const int lib = cx.compile({"quant.metal", "units.metal", "moe.metal"},
289                               std::string(g_f16 ? "#define STRATA_METAL_F16 1\n" : "") + (kq_dn ? "#define STRATA_KQ_DOWN 1\n" : ""));
290    const Layout L = layout(gu, dn);
291    // Gyro: the pack's hadamard.txt (the signs of the widths 2560 and 640) -> the engine's CPU spec (the reference)
292    mtl::Buffer hsx, hsh;
293    mtl::Pipeline had32 = cx.pipeline(lib, "had128_f32"), had16 = cx.pipeline(lib, "had128_f16"), had16r = cx.pipeline(lib, "had128_f16_rows");
294    const float* sgx = nullptr;
295    const float* sgh = nullptr;
296    if (!had_pack.empty()) {
297        strata::kernels::cpu::HadamardSpec spec;
298        std::string err;
299        if (!strata::kernels::cpu::hadamard_parse(had_pack + "/hadamard.txt", 48, spec, err)) {
300            std::fprintf(stderr, "%s\n", err.c_str());
301            return 2;
302        }
303        strata::kernels::cpu::hadamard_set(std::move(spec));
304        sgx = strata::kernels::cpu::hadamard_signs(N_EMBD);
305        sgh = strata::kernels::cpu::hadamard_signs(N_FF);
306        if (sgx) { hsx = cx.alloc(4 * N_EMBD); std::memcpy(hsx.ptr, sgx, 4 * N_EMBD); }
307        if (sgh) { hsh = cx.alloc(4 * N_FF); std::memcpy(hsh.ptr, sgh, 4 * N_FF); }
308        g_had32 = &had32;
309        g_hsh = sgh ? &hsh : nullptr;
310        g_had_h = !had_test;
311        std::printf("Hadamard: block %d, signs for %s%s\n", strata::kernels::cpu::hadamard_spec().block, sgx ? "2560 " : "", sgh ? "640" : "(none)");
312    }
313    if (decode_check) {
314        // the decoder the Metal kernels and ref_quant share the meaning of, written a third time straight from the format's
315        // definition (ggml-common-tq.h): step t's state = 16 stream bits from bit (31 - t) * K, LSB first, circular modulo 32 K
316        // bits, masked to 15 bits (TQ2_T: qs[(t + 31) % 32] << 8 | qs[t]); x = state * 0x9e3779b1; points lut[x >> 21] and
317        // lut[(x >> 10) & 2047]; weights = fp16 values * d.  Compared bit for bit with ref::dequant on the real tensors.
318        extern const uint16_t* tq_lut_for_test();
319        long blocks = 0, bad = 0;
320        const gguf::Tensor* ts[3] = {tg_, tu_, td_};
321        if (!tg_) { std::fprintf(stderr, "--decode-check needs --gguf\n"); return 2; }
322        for (const gguf::Tensor* t : ts) {
323            const int ty = t->type, K = ty == ref::TQ2_T ? 8 : ty == ref::TQK6 ? 6 : 7, bb = ref::block_bytes(ty);
324            const uint8_t* base = (const uint8_t*)gf.map + t->offset;
325            const size_t nb = t->bytes / bb;
326            const size_t step = std::max<size_t>(1, nb / 200000);   // up to 200k blocks a tensor, spread over it
327            for (size_t i = 0; i < nb; i += step) {
328                const uint8_t* b = base + i * bb;
329                float want[128], got[128];
330                const float d = ref::f16_to_f32((uint16_t)(b[0] | (b[1] << 8)));
331                const uint8_t* qs = b + 2;
332                for (int st = 0; st < 32; ++st) {
333                    uint32_t state;
334                    if (K == 8) state = (((uint32_t)qs[(st + 31) % 32] << 8) | qs[st]) & 0x7fff;
335                    else {
336                        const int off = ((31 - st) * K) % (32 * K);
337                        uint32_t v = 0;
338                        for (int bit = 0; bit < 16; ++bit) {
339                            const int pos = (off + bit) % (32 * K);
340                            v |= (uint32_t)((qs[pos / 8] >> (pos % 8)) & 1) << bit;
341                        }
342                        state = v & 0x7fff;
343                    }
344                    const uint32_t x = state * 0x9e3779b1u;
345                    const uint16_t* lut = tq_lut_for_test();
346                    const uint32_t pa = x >> 21, pb = (x >> 10) & 2047u;
347                    want[4 * st] = ref::f16_to_f32(lut[2 * pa]) * d;
348                    want[4 * st + 1] = ref::f16_to_f32(lut[2 * pa + 1]) * d;
349                    want[4 * st + 2] = ref::f16_to_f32(lut[2 * pb]) * d;
350                    want[4 * st + 3] = ref::f16_to_f32(lut[2 * pb + 1]) * d;
351                }
352                ref::dequant(ty, b, got, 128);
353                bad += std::memcmp(want, got, sizeof want) != 0;
354                ++blocks;
355            }
356        }
357        std::printf("decode-check layer %d: %ld blocks of the real tensors, %ld differ from the format's definition  %s\n", real_layer,
358                    blocks, bad, bad == 0 ? "PASS" : "FAIL");
359        return bad == 0 ? 0 : 1;
360    }
361    if (had_test) {
362        // the Metal rotation kernels against the CPU's (hadamard_rotate), bit for bit
363        int bad = 0;
364        ref::Rng r2(77 + seed);
365        for (int width : {N_FF, N_EMBD}) {
366            const int rows = 37;
367            const float* sg = width == N_EMBD ? sgx : sgh;
368            const mtl::Buffer& sb = width == N_EMBD ? hsx : hsh;
369            const float scale = 1.0f / std::sqrt(128.0f);
370            std::vector<float> in((size_t)rows * width);
371            for (auto& v : in) v = r2.sym() * 3.0f;
372            mtl::Buffer bx = cx.alloc(4 * in.size()), by = cx.alloc(4 * in.size());
373            std::memcpy(bx.ptr, in.data(), 4 * in.size());
374            HadArgs ha{(uint32_t)width, (uint32_t)width, (uint32_t)width, scale, sg ? 1u : 0u, 0u};
375            auto run32 = [&](const mtl::Buffer& src, const mtl::Buffer& dst) {
376                mtl::Dispatch d;
377                d.p = &had32;
378                d.args = {mtl::Arg::B(src), mtl::Arg::B(dst), mtl::Arg::B(sg ? sb : src), mtl::Arg::V(ha)};
379                d.grid[0] = width / 128; d.grid[1] = rows; d.tg[0] = 128;
380                cx.run({d});
381            };
382            run32(bx, by);   // out of place
383            std::vector<float> want = in;
384            for (int r = 0; r < rows; ++r) strata::kernels::cpu::hadamard_rotate(want.data() + (size_t)r * width, width, 128, sg);
385            int b32 = 0;
386            for (size_t i = 0; i < in.size(); ++i) b32 += std::memcmp(&want[i], by.as<float>() + i, 4) != 0;
387            run32(bx, bx);   // in place
388            int b32i = 0;
389            for (size_t i = 0; i < in.size(); ++i) b32i += std::memcmp(&want[i], bx.as<float>() + i, 4) != 0;
390            // f16 (no signs): out of place, and the rows kernel in place; the CPU's float result rounded to half
391            std::vector<_Float16> hin(in.size());
392            for (size_t i = 0; i < in.size(); ++i) hin[i] = (_Float16)in[i];
393            std::vector<float> hw(in.size());
394            for (size_t i = 0; i < in.size(); ++i) hw[i] = (float)hin[i];
395            for (int r = 0; r < rows; ++r) strata::kernels::cpu::hadamard_rotate(hw.data() + (size_t)r * width, width, 128, nullptr);
396            mtl::Buffer hx = cx.alloc(2 * in.size()), hy = cx.alloc(2 * in.size());
397            std::memcpy(hx.ptr, hin.data(), 2 * in.size());
398            HadArgs hb{(uint32_t)width, (uint32_t)width, (uint32_t)width, scale, 0u, 0u};
399            {
400                mtl::Dispatch d;
401                d.p = &had16;
402                d.args = {mtl::Arg::B(hx), mtl::Arg::B(hy), mtl::Arg::B(hx), mtl::Arg::V(hb)};
403                d.grid[0] = width / 128; d.grid[1] = rows; d.tg[0] = 128;
404                cx.run({d});
405            }
406            int b16 = 0;
407            for (size_t i = 0; i < in.size(); ++i) {
408                const _Float16 w = (_Float16)hw[i];
409                b16 += std::memcmp(&w, hy.as<_Float16>() + i, 2) != 0;
410            }
411            {
412                mtl::Dispatch d;
413                d.p = &had16r;
414                d.args = {mtl::Arg::B(hx), mtl::Arg::B(hx), mtl::Arg::B(hx), mtl::Arg::V(hb)};
415                d.grid[0] = rows; d.tg[0] = 128;
416                cx.run({d});
417            }
418            int b16r = 0;
419            for (size_t i = 0; i < in.size(); ++i) {
420                const _Float16 w = (_Float16)hw[i];
421                b16r += std::memcmp(&w, hx.as<_Float16>() + i, 2) != 0;
422            }
423            std::printf("had-test width %d, %d rows%s: f32 %d / f32 in place %d / f16 %d / f16 rows %d of %zu values differ from the CPU\n",
424                        width, rows, sg ? " (with signs)" : " (no signs)", b32, b32i, b16, b16r, in.size());
425            bad += b32 + b32i + b16 + b16r;
426        }
427        std::printf("had-test %s\n", bad == 0 ? "PASS (bitwise)" : "FAIL");
428        return bad == 0 ? 0 : 1;
429    }
430    std::printf("device %s; gate/up %s, down %s, blob %zu bytes; %d token(s)\n", cx.device_name().c_str(),
431                ref::type_name(gu), ref::type_name(dn), L.blob, ntok);
432
433    auto make = [&](Cfg a, Cfg b) {
434        Kernels K;
435        K.plan = cx.pipeline(lib, "moe_plan");
436        K.prep = cx.pipeline(lib, "xprep");
437        K.comb = cx.pipeline(lib, "moe_combine");
438        K.gu = cx.pipeline(lib, kname(g_f16 ? "moe_gu16" : "moe_gu", gu, a), mtl::Constants().i(22, std::getenv("MOE_PROBE") ? std::atoi(std::getenv("MOE_PROBE")) : 0).b(23, std::getenv("QUANT_CTAB") != nullptr));
439        K.dn = cx.pipeline(lib, kname(g_f16 ? "moe_down16" : "moe_down", dn == ref::Q2_0 && !g_dn_prep ? 142 : dn, b));
440        K.cgu = a;
441        K.cdn = b;
442        if (std::getenv("PIPE_INFO"))
443            std::printf("pipelines: gu %s max threads %d tg mem %d | dn %s max threads %d tg mem %d\n", K.gu.name.c_str(), K.gu.max_threads,
444                        K.gu.static_tg_mem, K.dn.name.c_str(), K.dn.max_threads, K.dn.static_tg_mem);
445        return K;
446    };
447    auto args_for = [&](const Kernels& K, int nt, int n_expert) {
448        MoeArgs a{};
449        a.gate_off = 0;
450        a.up_off = L.up_off;
451        a.down_off = L.down_off;
452        a.gu_stride = L.blob;
453        a.d_stride = L.blob;
454        a.gu_row = (uint32_t)L.gu_row;
455        a.d_row = (uint32_t)L.d_row;
456        a.n_embd = N_EMBD;
457        a.n_ff = N_FF;
458        a.n_tok = nt;
459        a.topk = TOPK;
460        a.n_expert = n_expert;
461        a.gx_gu = N_FF / rows_per_tg(K.cgu);
462        a.gx_dn = N_EMBD / rows_per_tg(K.cdn);
463        return a;
464    };
465
466    mtl::Buffer x = cx.alloc(4 * 8 * N_EMBD), h = cx.alloc(4 * 8 * TOPK * N_FF), ye = cx.alloc(4 * 8 * TOPK * N_EMBD),
467                y = cx.alloc(4 * 8 * N_EMBD);
468    mtl::Buffer XPX = cx.alloc(4 * (4 * PLANE_X + PLANE_X / 16) + (g_f16 ? 2 * 3 * PLANE_X : 0)),
469                XPH = cx.alloc(4 * (4 * PLANE_H + PLANE_H / 16)), h16 = g_f16 ? cx.alloc(2 * 8 * TOPK * N_FF) : mtl::Buffer{};
470    g_xpx = &XPX;
471    g_h16 = &h16;
472    g_xph = &XPH;
473    g_gu_type = gu;
474    g_dn_type = dn;
475    ref::Rng rng(12345 + (seed - 1));
476    for (int i = 0; i < 8 * N_EMBD; ++i) x.as<float>()[i] = rng.sym();
477    if (g_had_h) {   // H (s * x) per token on the GPU, checked against the CPU's; x then holds the rotated rows
478        std::vector<float> want(x.as<float>(), x.as<float>() + 8 * N_EMBD);
479        for (int t = 0; t < 8; ++t) strata::kernels::cpu::hadamard_rotate(want.data() + t * N_EMBD, N_EMBD, 128, sgx);
480        HadArgs ha{(uint32_t)N_EMBD, (uint32_t)N_EMBD, (uint32_t)N_EMBD, 1.0f / std::sqrt(128.0f), sgx ? 1u : 0u, 0u};
481        mtl::Dispatch d;
482        d.p = &had32;
483        d.args = {mtl::Arg::B(x), mtl::Arg::B(x), mtl::Arg::B(sgx ? hsx : x), mtl::Arg::V(ha)};
484        d.grid[0] = N_EMBD / 128; d.grid[1] = 8; d.tg[0] = 128;
485        cx.run({d});
486        int bad = 0;
487        for (int i = 0; i < 8 * N_EMBD; ++i) bad += std::memcmp(&want[i], x.as<float>() + i, 4) != 0;
488        std::printf("x rotation on the GPU vs the CPU: %d of %d values differ\n", bad, 8 * N_EMBD);
489    }
490    {
491        mtl::Pipeline pp = cx.pipeline(lib, "xprep", g_f16 ? mtl::Constants().b(25, true) : mtl::Constants());
492        cx.run({prep_dispatch(pp, x, XPX, N_EMBD, 8)});
493    }
494
495    if (!bench) {
496        // ---------------- parity ----------------
497        const int NE = tg_ && experts_first ? std::max(experts_first, 2 * TOPK) : 64;
498        mtl::Buffer W = cx.alloc(L.blob * NE);
499        std::vector<int> pick;
500        for (int e = 0; e < NE; ++e) {
501            uint8_t* b = W.as<uint8_t>() + e * L.blob;
502            if (tg_) {   // real experts of the file: expert `ex` of the layer's three tensors
503                int ex;
504                if (experts_first) ex = e % experts_first;   // (a sparse copy holds only the first experts: reused when NE is larger)
505                else do ex = (int)(rng.next() % 512); while (std::find(pick.begin(), pick.end(), ex) != pick.end());
506                pick.push_back(ex);
507                std::memcpy(b, (const uint8_t*)gf.map + tg_->offset + (size_t)ex * L.gu_row * N_FF, L.gu_row * N_FF);
508                std::memcpy(b + L.up_off, (const uint8_t*)gf.map + tu_->offset + (size_t)ex * L.gu_row * N_FF, L.gu_row * N_FF);
509                std::memcpy(b + L.down_off, (const uint8_t*)gf.map + td_->offset + (size_t)ex * L.d_row * N_EMBD, L.d_row * N_EMBD);
510            } else {
511                ref::random_blocks(gu, b, 2 * N_FF, N_EMBD, 1000 + e + 100 * (seed - 1));
512                ref::random_blocks(dn, b + L.down_off, N_EMBD, N_FF, 5000 + e + 100 * (seed - 1));
513            }
514        }
515        std::vector<int> ids;
516        std::vector<float> w;
517        random_routing(rng, ntok, NE, ids, w, 0.3);
518        mtl::Buffer bid = cx.alloc(4 * ids.size()), bw = cx.alloc(4 * w.size()), plan = cx.alloc(4 * P_INTS);
519        std::memcpy(bid.ptr, ids.data(), 4 * ids.size());
520        std::memcpy(bw.ptr, w.data(), 4 * w.size());
521        Kernels K = make(cgu, cdn);
522        MoeArgs a = args_for(K, ntok, 512);
523        std::vector<mtl::Dispatch> ds;
524        encode_layer(ds, K, W, 0, x, h, ye, y, bid, bw, plan, 0, a, true, true, true, true);
525        cx.run(ds);
526        // the plan
527        const int* P = plan.as<int>();
528        std::set<int> distinct(ids.begin(), ids.end());
529        bool plan_ok = P[P_NG] == (int)distinct.size() && P[P_IGU + 1] == P[P_NG] && P[P_IDN + 1] == P[P_NG];
530        {
531            int gi = 0;
532            for (int e : distinct) {
533                if (P[P_GEXP + gi] != e) plan_ok = false;
534                int j = P[P_GSTART + gi];
535                for (int i = 0; i < ntok * TOPK; ++i)
536                    if (ids[i] == e) {
537                        if (P[P_ETOK + j] != i / TOPK || P[P_TOKENT + i] != j) plan_ok = false;
538                        float fw;
539                        std::memcpy(&fw, &P[P_EW + j], 4);
540                        if (fw != w[i]) plan_ok = false;
541                        ++j;
542                    }
543                if (j != P[P_GSTART + gi + 1]) plan_ok = false;
544                ++gi;
545            }
546        }
547        // the reference
548        Err eh, ey;
549        std::vector<float> wg(N_FF * N_EMBD), wu(N_FF * N_EMBD), wd(N_EMBD * N_FF);
550        std::vector<double> yref(ntok * N_EMBD, 0.0);
551        for (int i = 0; i < ntok * TOPK; ++i) {
552            const int e = ids[i], t = i / TOPK;
553            const uint8_t* b = W.as<uint8_t>() + e * L.blob;
554            ref::dequant(gu, b, wg.data(), wg.size());
555            ref::dequant(gu, b + L.up_off, wu.data(), wu.size());
556            ref::dequant(dn, b + L.down_off, wd.data(), wd.size());
557            const float* xt = x.as<float>() + t * N_EMBD;
558            std::vector<double> hr(N_FF);
559            const int ent = P[P_TOKENT + i];
560            for (int r = 0; r < N_FF; ++r) {
561                double g = 0, u = 0;
562                for (int k = 0; k < N_EMBD; ++k) {
563                    g += (double)wg[r * N_EMBD + k] * xt[k];
564                    u += (double)wu[r * N_EMBD + k] * xt[k];
565                }
566                hr[r] = g / (1.0 + std::exp(-g)) * u;
567            }
568            if (g_had_h) {   // the reference of the down input: H h, in float as the engine's CPU path does
569                std::vector<float> hf(N_FF);
570                for (int r = 0; r < N_FF; ++r) hf[r] = (float)hr[r];
571                strata::kernels::cpu::hadamard_rotate(hf.data(), N_FF, 128, sgh);
572                for (int r = 0; r < N_FF; ++r) hr[r] = hf[r];
573            }
574            for (int r = 0; r < N_FF; ++r) eh.add(h.as<float>()[ent * N_FF + r], hr[r]);
575            for (int r = 0; r < N_EMBD; ++r) {
576                double s = 0;
577                // the reference down uses the GPU's h (float) so that the y check isolates the down kernel ...
578                for (int k = 0; k < N_FF; ++k) s += (double)wd[r * N_FF + k] * h.as<float>()[ent * N_FF + k];
579                yref[t * N_EMBD + r] += w[i] * s;
580            }
581        }
582        for (int i = 0; i < ntok * N_EMBD; ++i) ey.add(y.as<float>()[i], yref[i]);
583        // fp16: half products and h rounded to half on the way down - rel L2 ~1e-3 against double
584        const double tl2 = g_f16 ? 4e-3 : 1e-5, tmax = g_f16 ? 1e-2 : 1e-4;
585        const bool ok = plan_ok && eh.rel_l2() < tl2 && ey.rel_l2() < tl2 && eh.rel_max() < tmax && ey.rel_max() < tmax;
586        std::printf("parity %s/%s ntok %d gu %d,%d,%d dn %d,%d,%d: plan %s (%d groups), h rel L2 %.2e max %.2e, "
587                    "y rel L2 %.2e max %.2e  %s\n",
588                    ref::type_name(gu), ref::type_name(dn), ntok, cgu.L, cgu.R, cgu.S, cdn.L, cdn.R, cdn.S,
589                    plan_ok ? "ok" : "WRONG", P[P_NG], eh.rel_l2(), eh.rel_max(), ey.rel_l2(), ey.rel_max(),
590                    ok ? "PASS" : "FAIL");
591        return ok ? 0 : 1;
592    }
593
594    // ---------------- bench ----------------
595    const int NE = 512;
596    const size_t layer_bytes = L.blob * NE;
597    std::printf("arena: %d layers x %d experts = %.2f GB (max buffer %.1f GB)\n", layers, NE, layers * layer_bytes / 1e9,
598                cx.max_buffer_length() / 1e9);
599    mtl::Buffer W = cx.alloc(layer_bytes * layers);
600    {
601        // 64 distinct random experts, copied over the arena
602        std::vector<uint8_t> tmp(L.blob * 64);
603        for (int e = 0; e < 64; ++e) {
604            ref::random_blocks(gu, tmp.data() + e * L.blob, 2 * N_FF, N_EMBD, 1000 + e);
605            ref::random_blocks(dn, tmp.data() + e * L.blob + L.down_off, N_EMBD, N_FF, 5000 + e);
606        }
607        for (size_t e = 0; e < (size_t)NE * layers; ++e)
608            std::memcpy(W.as<uint8_t>() + e * L.blob, tmp.data() + (e % 64) * L.blob, L.blob);
609    }
610    std::vector<std::vector<int>> rids(reps);
611    std::vector<std::vector<float>> rw(reps);
612    mtl::Buffer bid = cx.alloc(4 * 8 * TOPK * reps), bw = cx.alloc(4 * 8 * TOPK * reps), plan = cx.alloc(4 * P_INTS * reps);
613    auto set_routing = [&](int nt) {
614        double groups = 0;
615        for (int r = 0; r < reps; ++r) {
616            random_routing(rng, nt, NE, rids[r], rw[r], share);
617            std::memcpy(bid.as<int>() + r * 8 * TOPK, rids[r].data(), 4 * rids[r].size());
618            std::memcpy(bw.as<float>() + r * 8 * TOPK, rw[r].data(), 4 * rw[r].size());
619            groups += std::set<int>(rids[r].begin(), rids[r].end()).size();
620        }
621        return groups / reps;
622    };
623    auto run_cfg = [&](const Kernels& K, int nt, double groups, bool print) {
624        const MoeArgs a = args_for(K, nt, NE);
625        std::vector<mtl::Dispatch> dp, dg, dd, dall;
626        for (int r = 0; r < reps; ++r) {
627            const size_t woff = (size_t)(r % layers) * layer_bytes;
628            std::vector<mtl::Dispatch> one;
629            encode_layer(one, K, W, woff, x, h, ye, y, bid, bw, plan, (size_t)r * P_INTS * 4, a, true, false, false, false);
630            one[0].args[0] = mtl::Arg::B(bid, (size_t)r * 8 * TOPK * 4);
631            one[0].args[1] = mtl::Arg::B(bw, (size_t)r * 8 * TOPK * 4);
632            dp.push_back(one[0]);
633            std::vector<mtl::Dispatch> g, d;
634            encode_layer(g, K, W, woff, x, h, ye, y, bid, bw, plan, (size_t)r * P_INTS * 4, a, false, true, false, false);
635            encode_layer(d, K, W, woff, x, h, ye, y, bid, bw, plan, (size_t)r * P_INTS * 4, a, false, false, true, false);
636            dg.push_back(g[0]);
637            for (auto& z : d) dd.push_back(z);
638            dall.push_back(one[0]);
639            dall.push_back(g[0]);
640            for (auto& z : d) dall.push_back(z);
641        }
642        cx.run(dp);   // plans in place
643        cx.warm(dall, 0.1);
644        std::vector<double> tp, tg, td, ta;
645        for (int it = 0; it < 7; ++it) {
646            tp.push_back(cx.run(dp) / reps);
647            tg.push_back(cx.run(dg) / reps);
648            td.push_back(cx.run(dd) / reps);
649            ta.push_back(cx.run(dall) / reps);
650        }
651        const double mp = median(tp), mg = median(tg), md = median(td), ma = median(ta);
652        const double bg = groups * 2.0 * N_FF * L.gu_row, bd = groups * N_EMBD * L.d_row;
653        if (print)
654            std::printf("ntok %d groups %5.1f | gu %2d,%d,%d %7.1f us %6.1f GB/s | dn %2d,%d,%d %7.1f us %6.1f GB/s | "
655                        "plan %5.1f us | layer %7.1f us = %6.1f GB/s (%4.1f%% of 585)\n",
656                        nt, groups, K.cgu.L, K.cgu.R, K.cgu.S, mg * 1e6, bg / mg / 1e9, K.cdn.L, K.cdn.R, K.cdn.S,
657                        md * 1e6, bd / md / 1e9, mp * 1e6, ma * 1e6, (bg + bd) / ma / 1e9,
658                        (bg + bd) / ma / 1e9 / 585 * 100);
659        return std::make_pair(mg, md);
660    };
661    const std::vector<Cfg> gus = {{32, 1, 4}, {32, 2, 4}, {32, 4, 4}, {32, 2, 2}, {32, 2, 8}, {32, 1, 8},
662                                  {16, 1, 4}, {16, 2, 4}, {8, 1, 4},  {8, 2, 4},  {8, 1, 2}};
663    const std::vector<Cfg> dns = {{8, 1, 4}, {8, 2, 4}, {8, 4, 4}, {8, 1, 8},  {8, 2, 8}, {4, 1, 4},
664                                  {4, 2, 4}, {4, 4, 4}, {16, 1, 4}, {16, 2, 4}, {32, 1, 4}, {2, 2, 4}};
665    std::vector<int> ntoks = {ntok};
666    if (sweep) ntoks = {1, 2, 3, 4, 8};
667    for (int nt : ntoks) {
668        const double groups = set_routing(nt);
669        if (sweep) {
670            // gate/up sweep with the default down, then down sweep with the best gate/up
671            Cfg bgu = cgu, bdn = cdn;
672            double best = 1e9;
673            for (Cfg c : gus) {
674                if (N_FF % rows_per_tg(c)) continue;
675                auto t = run_cfg(make(c, cdn), nt, groups, false);
676                std::printf("  gu %2d,%d,%d: %7.1f us  %6.1f GB/s\n", c.L, c.R, c.S, t.first * 1e6,
677                            groups * 2.0 * N_FF * L.gu_row / t.first / 1e9);
678                if (t.first < best) { best = t.first; bgu = c; }
679            }
680            best = 1e9;
681            for (Cfg c : dns) {
682                if (N_EMBD % rows_per_tg(c)) continue;
683                auto t = run_cfg(make(bgu, c), nt, groups, false);
684                std::printf("  dn %2d,%d,%d: %7.1f us  %6.1f GB/s\n", c.L, c.R, c.S, t.second * 1e6,
685                            groups * N_EMBD * L.d_row / t.second / 1e9);
686                if (t.second < best) { best = t.second; bdn = c; }
687            }
688            run_cfg(make(bgu, bdn), nt, groups, true);
689        } else {
690            run_cfg(make(cgu, cdn), nt, groups, true);
691        }
692    }
693    return 0;
694}