okami.mom/strata

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

Niko1221tests: cast ignored CUDA / HIP return values to (void)8aec2625d

main
77.1 KiB1202 linesraw
1// prefill_fused_iq_test - #136: the fused int8 expert kernels for the native packs (moe_fused_iq.hpp, STRATA_PF_FUSED=1)
2// on random native expert blobs ([gate rows | up rows | down rows], GGUF blocks) and random routing, per format pair,
3// against
4//   - a double-precision reference: the weights dequantized by ggml's own to_float, times the FP32 activations
5//     (gate/up, SwiGLU, down), and
6//   - the MMQ path in prefill.cpp's sequence (gather_native into 16-expert groups, q8_1 of the slots' activations,
7//     gate/up, SwiGLU, q8_1 of H, down).
8// Both round the activations and H to int8 per 32 values, differently, so this is not a bitwise test: the fused
9// path's error against the reference has to be comparable to MMQ's own (at most 1.5x its RMS and 2x its worst row).
10// The pairs cover every format the kernels take: gate/up IQ2_XXS IQ2_XS IQ2_S IQ3_XXS IQ3_S IQ4_XS, down Q2_0 IQ4_NL.
11// Part 1 (reference), per pair: 256 tokens over 64 experts, skewed routing - experts with 0 rows, with one, with
12// several 64-row tiles - an all-zero token, per-expert blobs at unrelated (2-byte aligned) addresses, three launches of
13// different expert ranges.  Part 2 (timing): one layer at the engine's chunks (2048, 3584, 8192 tokens; 512 experts,
14// top 10) on both paths and on MMQ's products alone (no gathers), for the IQ2_XS, IQ3_XXS and IQ3_S packs' most
15// common layers, with the grouping checked and a sample of rows against the reference.  --no-ref, --no-timing,
16// --only=NAME, --edge, --chunks=A,B, --blob-shift=N, --host-blobs=N [--expect-fallback | --expect-no-fallback] (the first N experts' blobs in host memory: the weight-staging
17// check fails for the launches that hold one and they take the unstaged kernel, same output bits), --unset-pf-fused (STRATA_PF_FUSED left unset instead of set to 1: the engine's default, for the
18// STRATA_PF_FUSED_Q2N=1 ctest entry).  Exit 77 without a CUDA device of sm_80 or newer.
19#include "strata/core/emulate.hpp"
20#include "strata/prefill/moe_fused_iq.hpp"
21#include "strata/prefill/mmq_ids_margin.hpp"
22#include "strata/prefill/moe_mmq.hpp"
23
24#include "ggml.h"
25
26#include <cuda_runtime.h>
27
28#include <algorithm>
29#include <cmath>
30#include <cstdint>
31#include <cstdio>
32#include <cstdlib>
33#include <cstring>
34#include <memory>
35#include <random>
36#include <stdexcept>
37#include <string>
38#include <thread>
39#include <vector>
40
41// the trellis types' codebooks (CUDA STRATA_PF_FUSED_TQ=1 pairs): the fp16 one (the format definition, ggml-common-tq.h, host data in a C++ file)
42// for the reference, and the int8 one the kernels read (tq_lut_i8.cuh, a __device__ table there: read here as host data) for the int8 model
43#pragma push_macro("__device__")
44#undef __device__
45#define __device__
46#include "../../third_party/ggml/ggml-common-tq.h"   // (a HIP build compiles this file as HIP: the empty __device__ keeps both tables host data)
47#include "../../src/kernels/cuda/tq_lut_i8.cuh"
48#pragma pop_macro("__device__")
49
50namespace {
51namespace mmq = strata::prefill::mmq;
52namespace fused = strata::prefill::fused;
53
54// The compiled geometry's widths (Flash-Next: 2560 x 640, 512 experts, top 10): build with -DSTRATA_GEOMETRY=<name> to test another shape.
55constexpr int N = fused::kMoeEmbd, FF = fused::kMoeFF, FF2 = fused::kMoeGuRows, K = (int) strata::core::kCompiledGeometry.n_expert_used, GROUP = 16;
56
57void ck(cudaError_t e, const char* what) {
58    if (e != cudaSuccess) throw std::runtime_error(std::string(what) + ": " + cudaGetErrorString(e));
59}
60
61struct Dev {
62    void* p = nullptr;
63    explicit Dev(size_t n) { ck(cudaMalloc(&p, n), "cudaMalloc"); }
64    ~Dev() { (void)cudaFree(p); }
65    Dev(const Dev&) = delete;
66    Dev& operator=(const Dev&) = delete;
67    template <typename T> T* as() const { return (T*) p; }
68};
69
70struct Pair {
71    ggml_type gu, d;
72    const char* name;
73};
74// MMQ covers this pair (the HIP build has no Q4_K / Q5_K / Q5_1 MMQ: those pairs are checked against the reference only)
75// (the NVFP4 pair is judged against the reference alone: MMQ's NVFP4 products have no per-expert scales - the engine applies the blob's tail around them - and run_mmq below does not)
76bool nvfp4_pair(const Pair& p) { return p.gu == GGML_TYPE_NVFP4 && p.d == GGML_TYPE_NVFP4; }
77bool mmq_ok(const Pair& p) { return !nvfp4_pair(p) && mmq::supported((int) p.gu) && mmq::supported((int) p.d); }
78
79// The trellis types (Gyro: TQ2_T 144, TQK6 145, TQK7 146; agentionai's ids) are outside the pinned ggml's type table: their sizes and their
80// dequantization here, from the format definition (third_party/ggml/ggml-common-tq.h's header comment), not from the kernels' code.
81bool tq_type(ggml_type t) { return (int) t >= 144 && (int) t <= 146; }
82size_t type_size(ggml_type t) { return (int) t == 144 ? 34 : (int) t == 145 ? 26 : (int) t == 146 ? 30 : ggml_type_size(t); }
83int64_t blck_size(ggml_type t) { return tq_type(t) ? 128 : ggml_blck_size(t); }
84size_t row_size(ggml_type t, int64_t n) { return (size_t) (n / blck_size(t)) * type_size(t); }
85float fp16_bits(uint16_t h) {   // IEEE half -> float
86    const uint32_t s = (uint32_t) (h >> 15) << 31, e = (h >> 10) & 31, m = h & 1023;
87    uint32_t f;
88    if (e == 0) return (h >> 15 ? -1.0f : 1.0f) * std::ldexp((float) m, -24);   // zero and subnormals
89    if (e == 31) f = s | 0x7f800000u | (m << 13);
90    else f = s | ((e + 112) << 23) | (m << 13);
91    float v;
92    std::memcpy(&v, &f, 4);
93    return v;
94}
95// one 128-weight trellis block: step t (32 steps, 4 weights each) has a 15-bit state; TQ2_T: qs[(t + 31) % 32] << 8 | qs[t]; TQK (K = 6 / 7):
96// the 16 stream bits from bit (31 - t) K of the circular stream of 32 K bits, LSB first.  x = state * 0x9e3779b1, points x >> 21 and
97// (x >> 10) & 2047, two weights each.  int8cb: the int8 codebook times TQ_LUT_I8_SCALE (what the kernels and MMQ read) instead of the fp16 one.
98void tq_block(int t, const uint8_t* b, float* out, bool int8cb) {
99    uint16_t dh;
100    std::memcpy(&dh, b, 2);
101    const float d = fp16_bits(dh);
102    const uint8_t* qs = b + 2;
103    const int K = t == 145 ? 6 : t == 146 ? 7 : 8, nbits = 32 * K;
104    auto bit = [&](int i) { i %= nbits; return (qs[i >> 3] >> (i & 7)) & 1; };
105    for (int st = 0; st < 32; ++st) {
106        uint32_t s = 0;
107        if (t == 144) s = ((uint32_t) qs[(st + 31) % 32] << 8) | qs[st];
108        else for (int k = 0; k < 16; ++k) s |= (uint32_t) bit((31 - st) * K + k) << k;
109        const uint32_t x = (s & 0x7fffu) * 0x9e3779b1u;
110        const uint32_t pt[2] = {x >> 21, (x >> 10) & 2047u};
111        for (int h = 0; h < 2; ++h)
112            for (int c = 0; c < 2; ++c)
113                out[4 * st + 2 * h + c] = int8cb ? d * TQ_LUT_I8_SCALE * (float) (int8_t) (tq_lut_i8[pt[h]] >> (8 * c))
114                                                 : d * fp16_bits(tq_lut_f16[2 * pt[h] + c]);
115    }
116}
117
118// --folded (trellis pairs): the Gyro packs' Hadamard-folded experts (include/strata/kernels/cpu/hadamard.hpp): the weights are taken as stored
119// (W' = W diag(s) H^T), so every activation entering them is rotated first, y = H_128 (s * x) / sqrt(128) per 128 values, with random signs.
120// The reference rotates on the host (this function, from the definition); the fused path's H rotation is set_down_rotation, MMQ's is
121// hadamard128_rows (the same device code: the reference is the independent side); the gate/up input is rotated on the host for every path.
122int g_blob_shift = 0;   // --blob-shift=N (even, 0-14; the timing part): every expert blob starts N bytes past its 16-byte aligned place, as in the engine's cache slots (stage-ring and slot offsets are only 2-byte aligned); use it with S20_NOMMQ=1 (MMQ wants aligned blobs)
123bool g_folded = false;
124int g_host_blobs = 0;       // --host-blobs=N (the timing part): the first N experts' blobs in pinned host memory, see timing_part; use with --no-ref (the reference part is not affected)
125int g_expect_fallback = 0;  // --expect-fallback (+1) / --expect-no-fallback (-1): with --host-blobs, require that some / no launch took the unstaged kernel
126void rot128(float* x, int n, const float* signs) {
127    for (int b = 0; b < n; b += 128) {
128        double v[128];
129        for (int i = 0; i < 128; ++i) v[i] = (double) x[b + i] * (signs ? signs[b + i] : 1.0f);
130        for (int st = 1; st < 128; st <<= 1)
131            for (int i = 0; i < 128; ++i)
132                if (!(i & st)) { const double a = v[i], c = v[i + st]; v[i] = a + c; v[i + st] = a - c; }
133        for (int i = 0; i < 128; ++i) x[b + i] = (float) (v[i] / std::sqrt(128.0));
134    }
135}
136const float* g_rot_signs_dev = nullptr;   // the down input's signs on the device while a folded pair runs
137bool g_rot_on = false;
138struct Folded {   // a folded trellis pair's signs (host and device); inactive for every other pair
139    bool on = false;
140    std::vector<float> sx, sh;
141    std::unique_ptr<struct Dev> dsh;
142    Folded(bool tq, int64_t rows) {
143        (void) rows;
144        if (!g_folded || !tq) return;
145        on = true;
146        std::mt19937 rs(20261111);   // (its own generator: every other draw of the test is unchanged)
147        sx.resize((size_t) N);
148        sh.resize((size_t) FF);
149        for (float& v : sx) v = (rs() & 1) ? 1.0f : -1.0f;
150        for (float& v : sh) v = (rs() & 1) ? 1.0f : -1.0f;
151        dsh = std::make_unique<Dev>(sh.size() * 4);
152        ck(cudaMemcpy(dsh->p, sh.data(), sh.size() * 4, cudaMemcpyHostToDevice), "signs");
153        g_rot_signs_dev = dsh->as<float>();
154        g_rot_on = true;
155    }
156    ~Folded() { g_rot_signs_dev = nullptr; g_rot_on = false; }
157    void rotate_x(std::vector<float>& x) const {   // the gate/up input, every token, on the host (all paths read the rotated rows)
158        if (on) for (size_t t = 0; t < x.size() / N; ++t) rot128(x.data() + t * N, N, sx.data());
159    }
160};
161
162struct Geo {
163    size_t gu_row, d_row, up_off, down_off, bytes;
164    explicit Geo(const Pair& p) {
165        gu_row = row_size(p.gu, N);
166        d_row = row_size(p.d, FF);
167        up_off = gu_row * FF;
168        down_off = 2 * up_off;
169        bytes = down_off + d_row * N;
170        if (nvfp4_pair(p)) bytes += 16;   // the blob's tail {s_gate, s_up, s_down, 0} (cpu::NativeFmt::tail_off = down_off + d_row n_embd)
171    }
172    fused::NativeGeom native(const Pair& p) const {
173        fused::NativeGeom g;
174        g.gu_type = (int) p.gu; g.d_type = (int) p.d; g.gu_row = gu_row; g.d_row = d_row; g.up_off = up_off;
175        g.down_off = down_off;
176        return g;
177    }
178};
179
180// random blocks with a sane fp16 scale `d` at each block's start (every format here begins with it): scales chosen so
181// STRATA_PF_F16=1: the covered formats run on F16 weights (moe_f16_kq.cu, native_f16_kernel), not the int8 kernels
182bool f16_on() {
183    const char* v = std::getenv("STRATA_PF_F16");
184    // STRATA_PF_FUSED_F16=1 / STRATA_PF_FUSED_WS=1 (the int8 kernels' f16 mma form, #3779): F16 products too, so the same limits
185    const char* f = std::getenv("STRATA_PF_FUSED_F16");
186    const char* w = std::getenv("STRATA_PF_FUSED_WS");
187    return (v != nullptr && v[0] == '1') || (f != nullptr && f[0] == '1') || (w != nullptr && w[0] == '1');
188}
189
190// that the weights' typical size is that of a 2-3 bit expert (a few hundredths)
191void fill_matrix(uint8_t* m, ggml_type t, int64_t rows, int64_t cols, std::mt19937& rng) {
192    const size_t bs = type_size(t), nb = (size_t) rows * (size_t) (cols / blck_size(t));
193    std::uniform_int_distribution<int> byte(0, 255);
194    const float lo = t == GGML_TYPE_Q4_K || t == GGML_TYPE_Q5_K ? 0.00004f : t == GGML_TYPE_Q5_1 ? 0.0006f
195                   : t == GGML_TYPE_Q8_0 ? 0.0001f : t == GGML_TYPE_IQ3_S ? 0.0004f : t == GGML_TYPE_IQ4_XS ? 0.00005f
196                   : t == GGML_TYPE_IQ4_NL ? 0.0002f : t == GGML_TYPE_Q2_0 ? 0.004f : t == GGML_TYPE_Q6_K ? 0.000005f
197                   : tq_type(t) ? 0.003f : 0.0008f;
198    std::uniform_real_distribution<float> sc(lo, 6.0f * lo);
199    for (size_t i = 0; i < nb * bs; ++i) m[i] = (uint8_t) byte(rng);
200    if (t == GGML_TYPE_NVFP4) {   // four UE4M3 scale bytes then 32 bytes of codes: scales 0x28..0x58 (2^-2 .. 2^4 raw, finite, bit 7 clear), the codes as drawn
201        std::uniform_int_distribution<int> ub(0x28, 0x58);
202        for (size_t b = 0; b < nb; ++b)
203            for (int k = 0; k < 4; ++k) m[b * bs + (size_t) k] = (uint8_t) ub(rng);
204        return;
205    }
206    for (size_t b = 0; b < nb; ++b) {
207        const ggml_fp16_t h = ggml_fp32_to_fp16(sc(rng));
208        std::memcpy(m + b * bs + (t == GGML_TYPE_Q6_K ? 208 : 0), &h, 2);   // (Q6_K keeps d at its end; its 16 int8 scales stay random bytes)
209        if (t == GGML_TYPE_Q4_K || t == GGML_TYPE_Q5_K || t == GGML_TYPE_Q5_1) {   // the minimum's scale, either sign
210            const ggml_fp16_t h2 = ggml_fp32_to_fp16(sc(rng) * ((rng() & 1) ? 1.0f : -1.0f) * (t == GGML_TYPE_Q5_1 ? 4.0f : 1.0f));
211            std::memcpy(m + b * bs + 2, &h2, 2);
212        }
213    }
214}
215std::vector<uint8_t> make_blob(const Pair& p, const Geo& g, std::mt19937& rng) {
216    std::vector<uint8_t> b(g.bytes);
217    fill_matrix(b.data(), p.gu, 2 * FF, N, rng);
218    fill_matrix(b.data() + g.down_off, p.d, N, FF, rng);
219    if (nvfp4_pair(p)) {   // the per-expert scales, about 1e-4 (a ModelOpt weight_scale_2): three of them, then a zero word
220        std::uniform_real_distribution<float> ss(2e-4f, 2e-3f);
221        const float t[4] = {ss(rng), ss(rng), ss(rng), 0.0f};
222        std::memcpy(b.data() + g.bytes - 16, t, 16);
223    }
224    return b;
225}
226
227// ggml's dequantized weights: gate [FF][N], up [FF][N], down [N][FF]
228// (the trellis types: tq_block above; int8cb = the int8 codebook the kernels read, for the int8 model)
229void dequant(const Pair& p, const Geo& g, const std::vector<uint8_t>& b, std::vector<float>& gu, std::vector<float>& dn, bool int8cb = false) {
230    gu.resize((size_t) 2 * FF * N);
231    dn.resize((size_t) N * FF);
232    if (tq_type(p.gu) || tq_type(p.d)) {
233        if (!tq_type(p.gu) || !tq_type(p.d)) throw std::runtime_error("a trellis pair needs both formats trellis");
234        for (int r = 0; r < 2 * FF; ++r)
235            for (int k = 0; k < N; k += 128) tq_block((int) p.gu, b.data() + (size_t) r * g.gu_row + (size_t) (k / 128) * type_size(p.gu), gu.data() + (size_t) r * N + k, int8cb);
236        for (int r = 0; r < N; ++r)
237            for (int k = 0; k < FF; k += 128) tq_block((int) p.d, b.data() + g.down_off + (size_t) r * g.d_row + (size_t) (k / 128) * type_size(p.d), dn.data() + (size_t) r * FF + k, int8cb);
238        return;
239    }
240    const auto* tg = ggml_get_type_traits(p.gu);
241    const auto* td = ggml_get_type_traits(p.d);
242    for (int r = 0; r < 2 * FF; ++r) tg->to_float(b.data() + (size_t) r * g.gu_row, gu.data() + (size_t) r * N, N);
243    for (int r = 0; r < N; ++r) td->to_float(b.data() + g.down_off + (size_t) r * g.d_row, dn.data() + (size_t) r * FF, FF);
244    if (nvfp4_pair(p)) {   // NVFP4: each projection times its own per-expert scale (the blob's tail), as llama.cpp applies .scale
245        float t[4];
246        std::memcpy(t, b.data() + g.bytes - 16, 16);
247        for (int r = 0; r < FF; ++r) for (int k = 0; k < N; ++k) gu[(size_t) r * N + k] *= t[0];
248        for (int r = FF; r < 2 * FF; ++r) for (int k = 0; k < N; ++k) gu[(size_t) r * N + k] *= t[1];
249        for (size_t i = 0; i < dn.size(); ++i) dn[i] *= t[2];
250    }
251}
252
253// activations: N(0, 1) with a few large values (the hidden state has outliers); token `zero` all zero
254std::vector<float> make_x(int T, std::mt19937& rng, int zero) {
255    std::vector<float> x((size_t) T * N);
256    std::normal_distribution<float> nd(0.0f, 1.0f);
257    std::uniform_int_distribution<int> pick(0, 199);
258    for (float& v : x) v = nd(rng) * (pick(rng) == 0 ? 12.0f : 1.0f);
259    if (zero >= 0) std::fill(x.begin() + (size_t) zero * N, x.begin() + (size_t) (zero + 1) * N, 0.0f);
260    return x;
261}
262
263// K distinct experts per token; `hot` > 0 skews the first choices towards the lowest ids
264std::vector<int32_t> make_ids(int T, int E, std::mt19937& rng, int hot, int unused) {
265    std::vector<int32_t> ids((size_t) T * K);
266    std::uniform_int_distribution<int> any(0, E - 1 - unused);
267    for (int t = 0; t < T; ++t)
268        for (int k = 0; k < K; ++k) {
269            int e;
270            bool dup;
271            do {
272                e = (hot > 0 && k < 3 && (int) (rng() % 4) != 0) ? (int) (rng() % (unsigned) hot) : any(rng);
273                dup = false;
274                for (int j = 0; j < k; ++j) dup |= ids[(size_t) t * K + j] == e;
275            } while (dup);
276            ids[(size_t) t * K + k] = e;
277        }
278    return ids;
279}
280
281struct Routing {
282    std::vector<int32_t> cnt, off, src;   // per expert; sorted row -> token (rows in pair order within an expert)
283    std::vector<int32_t> row_of;          // pair -> sorted row
284};
285Routing sort_rows(const std::vector<int32_t>& ids, int E) {
286    Routing r;
287    r.cnt.assign((size_t) E, 0);
288    for (int32_t e : ids) ++r.cnt[(size_t) e];
289    r.off.assign((size_t) E + 1, 0);
290    for (int e = 0; e < E; ++e) r.off[(size_t) e + 1] = r.off[(size_t) e] + r.cnt[(size_t) e];
291    std::vector<int32_t> fill(r.off.begin(), r.off.end() - 1);
292    r.src.resize(ids.size());
293    r.row_of.resize(ids.size());
294    for (size_t i = 0; i < ids.size(); ++i) {
295        const int32_t p = fill[(size_t) ids[i]]++;
296        r.row_of[i] = p;
297        r.src[(size_t) p] = (int32_t) (i / K);
298    }
299    return r;
300}
301
302// MMQ, as prefill.cpp runs a native layer: per group of 16 routed experts a gather, gate/up, SwiGLU (gate rows, then
303// up rows), q8_1 of H, down.  Returns Dm [rows][N] in sorted-row order.
304// llama.cpp's mul_mat_q and its stream-k fixup read the row-id table up to a J-column tile (J <= 128) past the last row, up to roundup(max_rows, J) from an
305// expert's first row: the table takes mmq_ids_table_rows(rows, max_rows) entries (mmq_ids_margin.hpp), the identity written over all of them.
306size_t ids_table_rows(int64_t rows) { return (size_t) mmq::mmq_ids_table_rows((uint64_t) rows, (uint64_t) (rows / K)); }
307struct MmqBufs {
308    Dev xq, gu, h, hq, dm, ident, bounds, grp_gu, grp_d;
309    MmqBufs(const Pair& p, int64_t rows, int E)
310        : xq(mmq::q8_bytes(rows, N)), gu((size_t) rows * FF2 * 4), h((size_t) rows * FF * 4),
311          hq(mmq::q8_bytes(rows, FF)), dm((size_t) rows * N * 4), ident(ids_table_rows(rows) * 4),
312          bounds((size_t) (2 * (E + E / GROUP + 2)) * 4), grp_gu(GROUP * mmq::matrix_bytes(p.gu, FF2, N) + 4096),
313          grp_d(GROUP * mmq::matrix_bytes(p.d, N, FF) + 4096) {}
314};
315// `direct`: no gathers - the products read the blobs where they are (they must lie at a fixed stride, every expert
316// with rows: the timing part's layout), the cost of MMQ's own kernels alone
317void run_mmq(const Pair& p, const Geo& geo, mmq::Context& ctx, MmqBufs& b, const Routing& r, const float* x_dev,
318             const int32_t* src_dev, const std::vector<const uint8_t*>& blob, int64_t rows, cudaStream_t s,
319             bool direct = false, size_t stride = 0) {
320    const size_t gub = mmq::matrix_bytes(p.gu, FF2, N), db = mmq::matrix_bytes(p.d, N, FF);
321    const int E = (int) r.cnt.size();
322    std::vector<int32_t> order;
323    for (int e = 0; e < E; ++e) if (r.cnt[(size_t) e] > 0) order.push_back(e);
324    const size_t n = order.size(), ng = (n + GROUP - 1) / GROUP;
325    std::vector<int32_t> bh(n + 1 + ng * (GROUP + 1));
326    for (size_t j = 0; j < n; ++j) bh[j] = r.off[(size_t) order[j]];
327    bh[n] = (int32_t) rows;
328    for (size_t g = 0; g < ng; ++g)
329        for (size_t i = 0; i <= GROUP; ++i)
330            bh[n + 1 + g * (GROUP + 1) + i] = bh[std::min(n, g * GROUP + i)] - bh[g * GROUP];
331    ck(cudaMemcpyAsync(b.bounds.p, bh.data(), bh.size() * 4, cudaMemcpyHostToDevice, s), "bounds");
332    mmq::iota(b.ident.as<int32_t>(), (int64_t) ids_table_rows(rows), s);
333    mmq::quantize(x_dev, src_dev, b.xq.p, (int) p.gu, N, N, rows, s);
334    for (size_t j = 0; j < n; ++j) {
335        const size_t q = j % GROUP;
336        const uint8_t* bl = blob[(size_t) order[j]];
337        if (!direct)
338            mmq::gather_native(bl, bl + geo.up_off, gub / 2, bl + geo.down_off, db, b.grp_gu.as<uint8_t>() + q * gub,
339                               b.grp_d.as<uint8_t>() + q * db, s);
340        if (q + 1 < GROUP && j + 1 < n) continue;
341        const size_t j0 = j - q, g = j0 / GROUP;
342        const int ngx = (int) (q + 1);
343        const int64_t r0 = bh[j0], nr = bh[j + 1] - r0;
344        int64_t maxr = 0;
345        for (size_t i = j0; i <= j; ++i) maxr = std::max<int64_t>(maxr, r.cnt[(size_t) order[i]]);
346        if (!direct) {
347            ck(cudaMemsetAsync(b.grp_gu.as<uint8_t>() + (size_t) ngx * gub, 0, 4096, s), "tail");
348            ck(cudaMemsetAsync(b.grp_d.as<uint8_t>() + (size_t) ngx * db, 0, 4096, s), "tail");
349        }
350        const uint8_t* b0 = blob[(size_t) order[j0]];
351        mmq::Product gu;
352        gu.w = direct ? (const void*) b0 : b.grp_gu.p; gu.type = (int) p.gu; gu.w_rows = FF2; gu.w_cols = N;
353        gu.expert_bytes = direct ? stride : gub;
354        gu.n = ngx; gu.xq = b.xq.p; gu.bounds = b.bounds.as<int32_t>() + j0; gu.ids = b.ident.as<int32_t>();
355        gu.total_rows = rows; gu.max_rows = maxr; gu.dst = b.gu.as<float>(); gu.ld_dst = FF2;
356        ctx.run(gu, s);
357        mmq::swiglu(b.gu.as<float>() + r0 * FF2, b.h.as<float>() + r0 * FF, nr, FF, false, s);
358        if (g_rot_on) fused::hadamard128_rows(b.h.as<float>() + r0 * FF, nr, FF, g_rot_signs_dev, s);   // (--folded: the down input rotated)
359        mmq::quantize(b.h.as<float>() + r0 * FF, nullptr, b.hq.p, (int) p.d, FF, FF, nr, s);
360        mmq::Product dn;
361        dn.w = direct ? (const void*) (b0 + geo.down_off) : b.grp_d.p; dn.type = (int) p.d; dn.w_rows = N; dn.w_cols = FF;
362        dn.expert_bytes = direct ? stride : db;
363        dn.n = ngx; dn.xq = b.hq.p; dn.bounds = b.bounds.as<int32_t>() + n + 1 + g * (GROUP + 1);
364        dn.ids = b.ident.as<int32_t>(); dn.total_rows = nr; dn.max_rows = maxr; dn.dst = b.dm.as<float>() + r0 * N;
365        dn.ld_dst = N;
366        ctx.run(dn, s);
367    }
368}
369
370// the fused path: quantize, group on the device, then launches over expert ranges `cuts` (e.g. {0, 20, 64})
371struct FusedBufs {
372    Dev xa, ha, dm, scratch, slot, src, ids;
373    FusedBufs(int T, int64_t rows, int E)
374        : xa(fused::act_bytes(T, N)), ha(fused::act_bytes(rows, FF)), dm((size_t) rows * N * 4),
375          scratch(fused::group_bytes(rows, E)), slot((size_t) rows * 4), src((size_t) rows * 4),
376          ids((size_t) rows * 4) {}
377};
378void run_fused(const Pair& p, const Geo& geo, FusedBufs& b, const float* x_dev, int T, int E,
379               const std::vector<int>& cuts, const std::vector<const uint8_t*>& blob, cudaStream_t s) {
380    const int64_t rows = (int64_t) T * K;
381    const fused::NativeGeom ng = geo.native(p);
382    fused::quantize_act_native(x_dev, T, N, b.xa.p, s);
383    fused::group(b.ids.as<int32_t>(), rows, K, E, b.scratch.p, b.slot.as<int32_t>(), b.src.as<int32_t>(), s);
384    fused::set_down_rotation(g_rot_on, g_rot_signs_dev);   // (--folded trellis pairs; off for every other pair)
385    struct Off { ~Off() { fused::set_down_rotation(false, nullptr); } } off_at_end;
386    for (size_t c = 0; c + 1 < cuts.size(); ++c) {
387        for (int e0 = cuts[c]; e0 < cuts[c + 1]; e0 += fused::kMaxBatch) {
388            fused::Batch bt;
389            bt.e0 = e0;
390            bt.e1 = std::min(cuts[c + 1], e0 + fused::kMaxBatch);
391            for (int e = bt.e0; e < bt.e1; ++e) bt.blob[e - bt.e0] = blob[(size_t) e];
392            fused::experts_native(bt, ng, E, rows, b.scratch.p, b.xa.p, b.src.as<int32_t>(), b.ha.p, b.dm.as<float>(), s);
393        }
394    }
395}
396
397struct Err {
398    double rms = 0, worst = 0;   // RMS error / RMS of the reference; the worst row's max |error| / its max |ref|
399};
400// y_a[row_a(i)] against y_b[row_b(i)] for every pair i (rows of N values)
401template <typename RA, typename RB>
402Err compare(const std::vector<float>& a, RA row_a, const std::vector<float>& b, RB row_b, size_t pairs) {
403    double e2 = 0, r2 = 0;
404    Err out;
405    for (size_t i = 0; i < pairs; ++i) {
406        const float* ya = a.data() + (size_t) row_a(i) * N;
407        const float* yb = b.data() + (size_t) row_b(i) * N;
408        double me = 0, mr = 0;
409        for (int o = 0; o < N; ++o) {
410            if (!std::isfinite(ya[o])) throw std::runtime_error("a non-finite output");
411            const double d = (double) ya[o] - yb[o];
412            e2 += d * d;
413            r2 += (double) yb[o] * yb[o];
414            me = std::max(me, std::fabs(d));
415            mr = std::max(mr, (double) std::fabs(yb[o]));
416        }
417        if (mr > 0) out.worst = std::max(out.worst, me / mr);
418        else if (me > 0) out.worst = 1e30;   // a zero row must stay exactly zero
419    }
420    out.rms = r2 > 0 ? std::sqrt(e2 / r2) : 0;
421    return out;
422}
423
424// the kernels' int8 rounding per 32 values (quant_act_nat_kernel / the H epilogue), as floats: codes * (amax / 127)
425void quant32(const float* in, float* out, int n) {
426    for (int b = 0; b < n; b += 32) {
427        float am = 0.0f;
428        for (int j = 0; j < 32; ++j) am = std::max(am, std::fabs(in[b + j]));
429        const float inv = am > 0.0f ? 127.0f / am : 0.0f, d = am / 127.0f;
430        for (int j = 0; j < 32; ++j) out[b + j] = (float) std::nearbyint(in[b + j] * inv) * d;
431    }
432}
433
434std::vector<float> download(const Dev& d, size_t n) {
435    std::vector<float> h(n);
436    ck(cudaMemcpy(h.data(), d.p, n * 4, cudaMemcpyDeviceToHost), "download");
437    return h;
438}
439std::vector<int32_t> download_i(const Dev& d, size_t n) {
440    std::vector<int32_t> h(n);
441    ck(cudaMemcpy(h.data(), d.p, n * 4, cudaMemcpyDeviceToHost), "download");
442    return h;
443}
444
445// K-quant gate/up pairs (Q4_K / Q5_K: a minimum per 32 values) are not judged against MMQ.  MMQ takes the minimum term from its own
446// activation sums (q8_1 / DS4 per 32 values, stored as half2) and so departs from the int8 model by 3-5e-3 rel RMS behind a Q8_0 down
447// (CUDA, RTX A6000 / PRO 5000 / PRO 6000: Q4_K / Q8_0 3.9-4.8e-3, Q5_K / Q8_0 2.8-3.5e-3; gfx1201 (lane OWN-4A): Q4_K / Q8_0 3.9-4.8e-3),
448// while MMQ and the int8 model are the same distance from FP32 in every shape (within 1%; 1.07-1.10x at the 1-token shape's 10 rows).
449// Rule: the int8 model as for every pair (rel RMS 2e-3, worst row 3e-2) AND FP32 no further than MMQ's own distance times
450// kKqRms (RMS) / kKqWorst (worst row); fused against MMQ is printed as information.  The i-quant pairs keep their rule.
451constexpr double kKqRms = 1.15, kKqWorst = 1.5;
452bool kq_gu(const Pair& p) { return p.gu == GGML_TYPE_Q4_K || p.gu == GGML_TYPE_Q5_K; }
453
454// A build WITHOUT MMQ (mmq::built() false) has no MMQ distance to measure against.  Its rule, for every pair:
455//   (a) the fused path against the int8-rounded model: as above (2e-3 rel RMS, 3e-2 worst row; 5e-3 RMS with STRATA_PF_F16=1);
456//   (b) the int8-rounded model's own distance to FP32 stays under the ceiling of the pair's class (a broken model cannot pass relative to itself);
457//   (c) the fused path's distance to FP32 is at most kOwnRel (RMS) / kOwnRelWorst (worst row) times the model's, plus kOwnAbs.
458// (MMQ and the model are the same distance from FP32 within 1% on every shape; the fused path equals the model to 1.001 x.)  Builds with MMQ keep
459// the rules above and below, unchanged.  The inputs come from the standard library's distributions, so the numbers differ between platforms
460// (libstdc++ on Linux, MSVC on Windows); the ceilings are the larger of the two plus a margin of about 1.5 to 1.75.
461// The model's distance to FP32, rel RMS / worst row, the largest over the shapes of the ctest entries (11-11, P4-SPLIT; RTX PRO 5000 sm_120 and
462// RTX A4000 sm_86 give the same numbers on Linux, RTX 5070 sm_120 on Windows):
463//   i-quant gate/up (base, nt256, f16, q50, q8d entries), Q6_K, Q8_0 / Q8_0:  Linux 1.60e-2 / 2.97e-2, Windows 1.60e-2 / 2.96e-2   -> kCeilDense
464//   Q2_0 / Q2_0, reference part: Linux 1.09e-2 / 4.69e-2, Windows 1.14e-2 / 4.50e-2                                        -> kCeilQ2
465//   Q2_0 / Q2_0, the 96-pair timing sample: Linux 2.71e-2 / 1.09e-1, Windows 2.42e-2 / 2.41e-1                            -> kCeilQ2Sample
466//   Q4_K / Q5_K gate/up (kq entry): Linux 1.49e-2 / 1.70e-1, Windows 3.68e-2 / 2.13e-1 (MMQ itself 3.70e-2 / 2.19e-1)    -> kCeilKq
467//   trellis (tq, tqh entries): Linux 2.20e-2 / 4.02e-2, Windows 2.19e-2 / 4.61e-2                                         -> kCeilTq
468// Against MMQ (kq entry, MMQ build): fused / MMQ at most 1.097 (RMS) and 1.23 (worst row) on Linux, 1.037 and 1.17 on Windows.
469constexpr double kOwnRel = 1.15, kOwnRelWorst = 1.5, kOwnAbs = 1e-3;
470struct Ceiling {
471    double rms, worst;
472};
473constexpr Ceiling kCeilDense{2.5e-2, 5.0e-2}, kCeilQ2{2.0e-2, 8.0e-2}, kCeilQ2Sample{4.5e-2, 3.6e-1}, kCeilKq{6.0e-2, 3.5e-1}, kCeilTq{3.5e-2, 7.5e-2};
474Ceiling model_ceiling(const Pair& p, bool sample) {
475    if (tq_type(p.gu)) return kCeilTq;
476    if (kq_gu(p)) return kCeilKq;
477    if (p.gu == GGML_TYPE_Q2_0 && p.d == GGML_TYPE_Q2_0) return sample ? kCeilQ2Sample : kCeilQ2;
478    return kCeilDense;
479}
480// ev: the int8-rounded model against FP32, ef: the fused path against FP32 (the same rows)
481void own_only_check(const Pair& p, const Err& ev, const Err& ef, bool sample) {
482    const std::string where = sample ? " (timing)" : "";
483    const Ceiling c = model_ceiling(p, sample);
484    if (ev.rms > c.rms || ev.worst > c.worst)
485        throw std::runtime_error(std::string(p.name) + ": the int8-rounded model is further from FP32 than the ceiling of its class (no-MMQ rule)" + where);
486    if (ef.rms > kOwnRel * ev.rms + kOwnAbs || ef.worst > kOwnRelWorst * ev.worst + kOwnAbs)
487        throw std::runtime_error(std::string(p.name) + ": the fused path is further from FP32 than the int8-rounded model (no-MMQ rule)" + where);
488}
489
490// part 1: against the double-precision reference
491void reference_part(const Pair& p, cudaStream_t s, int T = 256, int E = 64, int ZERO = 77) {
492    const Geo geo(p);
493    std::mt19937 rng(136 + (unsigned) p.gu * 7 + (unsigned) p.d);
494    std::vector<std::vector<uint8_t>> host((size_t) E);
495    std::vector<std::unique_ptr<Dev>> dev;
496    std::vector<const uint8_t*> blob((size_t) E);
497    for (int e = 0; e < E; ++e) {
498        host[(size_t) e] = make_blob(p, geo, rng);
499        dev.push_back(std::make_unique<Dev>(geo.bytes + 4096 * (size_t) (e % 3) + 64));   // unrelated addresses
500        uint8_t* q = dev.back()->as<uint8_t>() + 256 * (size_t) (e % 3) + 2 * (size_t) (e % 2);   // 2-byte aligned
501        ck(cudaMemcpy(q, host[(size_t) e].data(), geo.bytes, cudaMemcpyHostToDevice), "blob");
502        blob[(size_t) e] = q;
503    }
504    std::vector<float> x = make_x(T, rng, ZERO);
505    const std::vector<int32_t> ids = make_ids(T, E, rng, 2, E >= 64 ? 4 : 4);   // experts 0, 1 hot (several tiles), the last 4 unused
506    const int64_t rows = (int64_t) T * K;
507    const Routing r = sort_rows(ids, E);
508    const Folded fo(tq_type(p.gu), rows);   // (--folded trellis pairs: the signs, the H scratch; x rotated for every path and the reference)
509    fo.rotate_x(x);
510    if (fo.on) std::printf("%s - folded: the gate/up input and H rotated per 128 values with random signs\n", p.name);
511    std::printf("%s - reference part: %d tokens, %d experts, rows per expert: max %d, experts without rows %d\n", p.name,
512                T, E, *std::max_element(r.cnt.begin(), r.cnt.end()), (int) std::count(r.cnt.begin(), r.cnt.end(), 0));
513
514    Dev x_dev(x.size() * 4), src_dev((size_t) rows * 4);
515    ck(cudaMemcpy(x_dev.p, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "x");
516    ck(cudaMemcpy(src_dev.p, r.src.data(), r.src.size() * 4, cudaMemcpyHostToDevice), "src");
517    // (the uploads above are on the legacy stream and the work below on a non-blocking one: a cudaMemcpy from pageable
518    // memory may return before its DMA lands - on Windows it can wait in the queue until the next synchronous call)
519    ck(cudaDeviceSynchronize(), "uploads");
520    const bool mq = mmq_ok(p);
521    mmq::Context ctx;
522    MmqBufs* mbp = mq ? new MmqBufs(p, rows, E) : nullptr;
523    if (mq) run_mmq(p, geo, ctx, *mbp, r, x_dev.as<float>(), src_dev.as<int32_t>(), blob, rows, s);
524    FusedBufs fb(T, rows, E);
525    ck(cudaMemcpy(fb.ids.p, ids.data(), ids.size() * 4, cudaMemcpyHostToDevice), "ids");
526    ck(cudaMemset(fb.dm.p, 0xff, (size_t) rows * N * 4), "sentinel");   // an unwritten row is NaN
527    ck(cudaDeviceSynchronize(), "uploads");
528    run_fused(p, geo, fb, x_dev.as<float>(), T, E, {0, 1, std::min(20, E - 1), E}, blob, s);
529    ck(cudaStreamSynchronize(s), "sync");
530    const std::vector<float> y_mmq = mq ? download(mbp->dm, (size_t) rows * N) : std::vector<float>((size_t) rows * N, 0.0f),
531                             y_f = download(fb.dm, (size_t) rows * N);
532    delete mbp;
533    const std::vector<int32_t> slot = download_i(fb.slot, (size_t) rows), fsrc = download_i(fb.src, (size_t) rows);
534    for (int64_t i = 0; i < rows; ++i)
535        if (fsrc[(size_t) slot[(size_t) i]] != (int32_t) (i / K)) throw std::runtime_error("group: slot/src disagree");
536
537    // the reference, an expert at a time on all cores
538    std::vector<float> ref((size_t) rows * N), ref2((size_t) rows * N);   // ref2: the same with the kernels' int8 rounding
539    std::vector<std::thread> th;
540    const int nth = std::max(1, std::min(16, (int) std::thread::hardware_concurrency()));
541    for (int w = 0; w < nth; ++w)
542        th.emplace_back([&, w] {
543            std::vector<float> gu, dn, gu8, dn8, h(FF), h2(FF), hq(FF), xq(N);
544            const bool tq = tq_type(p.gu);
545            for (int e = w; e < E; e += nth) {
546                if (r.cnt[(size_t) e] == 0) continue;
547                dequant(p, geo, host[(size_t) e], gu, dn);
548                if (tq) dequant(p, geo, host[(size_t) e], gu8, dn8, true);   // (trellis: the int8 model reads the int8 codebook, as the kernels do)
549                const std::vector<float>& gm = tq ? gu8 : gu;
550                const std::vector<float>& dmw = tq ? dn8 : dn;
551                for (int64_t i = 0; i < rows; ++i) {
552                    if (ids[(size_t) i] != e) continue;
553                    const float* xr = x.data() + (size_t) (i / K) * N;
554                    for (int f = 0; f < FF; ++f) {
555                        double gt = 0, up = 0;
556                        const float *wg = gu.data() + (size_t) f * N, *wu = gu.data() + (size_t) (FF + f) * N;
557                        for (int k = 0; k < N; ++k) { gt += (double) wg[k] * xr[k]; up += (double) wu[k] * xr[k]; }
558                        h[(size_t) f] = (float) (gt / (1.0 + std::exp(-gt)) * up);
559                    }
560                    if (fo.on) rot128(h.data(), FF, fo.sh.data());   // (--folded: the down input rotated)
561                    for (int o = 0; o < N; ++o) {
562                        double a = 0;
563                        const float* wd = dn.data() + (size_t) o * FF;
564                        for (int f = 0; f < FF; ++f) a += (double) wd[f] * h[(size_t) f];
565                        ref[(size_t) i * N + o] = (float) a;
566                    }
567                    quant32(xr, xq.data(), N);
568                    for (int f = 0; f < FF; ++f) {
569                        double gt = 0, up = 0;
570                        const float *wg = gm.data() + (size_t) f * N, *wu = gm.data() + (size_t) (FF + f) * N;
571                        for (int k = 0; k < N; ++k) { gt += (double) wg[k] * xq[(size_t) k]; up += (double) wu[k] * xq[(size_t) k]; }
572                        h2[(size_t) f] = (float) (gt / (1.0 + std::exp(-gt)) * up);
573                    }
574                    if (fo.on) rot128(h2.data(), FF, fo.sh.data());
575                    quant32(h2.data(), hq.data(), FF);
576                    for (int o = 0; o < N; ++o) {
577                        double a = 0;
578                        const float* wd = dmw.data() + (size_t) o * FF;
579                        for (int f = 0; f < FF; ++f) a += (double) wd[f] * hq[(size_t) f];
580                        ref2[(size_t) i * N + o] = (float) a;
581                    }
582                }
583            }
584        });
585    for (auto& t : th) t.join();
586
587    auto pair = [](size_t i) { return (int64_t) i; };
588    auto mrow = [&](size_t i) { return (int64_t) r.row_of[i]; };
589    auto frow = [&](size_t i) { return (int64_t) slot[i]; };
590    const Err em = mq ? compare(y_mmq, mrow, ref, pair, (size_t) rows) : Err{};
591    const Err ef = compare(y_f, frow, ref, pair, (size_t) rows);
592    const Err efm = mq ? compare(y_f, frow, y_mmq, mrow, (size_t) rows) : Err{};
593    const Err e2 = compare(y_f, frow, ref2, pair, (size_t) rows);
594    std::printf("  fused vs the int8-rounded model (same activation / H rounding, double sums): rel RMS %.3e  worst %.3e\n",
595                e2.rms, e2.worst);
596    // STRATA_PF_F16=1: H's int8 rounding meets values a few F16 ulps from the int8 model's (f16_on); the FP32 reference
597    // checks below stay as they are
598    if (e2.rms > (f16_on() ? 5e-3 : 2e-3) || e2.worst > 3e-2)
599        throw std::runtime_error(std::string(p.name) + ": the fused path differs from its own arithmetic's model");
600    if (mq) std::printf("  MMQ   vs FP32 reference: rel RMS %.3e  worst row max rel %.3e\n", em.rms, em.worst);
601    std::printf("  fused vs FP32 reference: rel RMS %.3e  worst row max rel %.3e\n", ef.rms, ef.worst);
602    if (mq) std::printf("  fused vs MMQ           : rel RMS %.3e  worst row max rel %.3e\n", efm.rms, efm.worst);
603    double zmax = 0;
604    for (int k = 0; k < K && ZERO >= 0; ++k)
605        for (int o = 0; o < N; ++o)
606            zmax = std::max(zmax, (double) std::fabs(y_f[(size_t) slot[(size_t) (ZERO * K + k)] * N + o]));
607    if (zmax != 0) throw std::runtime_error(std::string(p.name) + ": the all-zero token's outputs are not zero");
608    if (!mq) {   // no MMQ here: the int8 activations' own error (the IQ pairs' fused path sits at ~1e-2 rel RMS)
609        if (!mmq::built()) {   // a build without MMQ at all: the rule of kOwnRel (the int8 model's own distance, with a ceiling per class)
610            const Err ev = compare(ref2, pair, ref, pair, (size_t) rows);
611            std::printf("  int8-rounded model vs FP32 reference: rel RMS %.3e  worst row max rel %.3e\n", ev.rms, ev.worst);
612            own_only_check(p, ev, ef, false);
613            return;
614        }
615        if (ef.rms > 0.03 || ef.worst > 0.25)
616            throw std::runtime_error(std::string(p.name) + ": the fused path's error against the reference is too large");
617        return;
618    }
619    if (kq_gu(p)) {   // the K-quant rule (kq_gu): the int8 model above, and FP32 no further than MMQ's own distance + the margin
620        if (ef.rms > kKqRms * em.rms || ef.worst > kKqWorst * em.worst)
621            throw std::runtime_error(std::string(p.name) + ": the fused path is further from the reference than MMQ (K-quant rule)");
622        return;
623    }
624    if (ef.rms > 1.5 * em.rms || ef.worst > 2.0 * em.worst)
625        throw std::runtime_error(std::string(p.name) + ": the fused path's error is not comparable to MMQ's");
626}
627
628// part 2: one layer at a real chunk, timed
629void timing_part(const Pair& p, int T, cudaStream_t s) {
630    static const int E = [] { const char* v = std::getenv("S20_E"); return v != nullptr && std::atoi(v) > 0 ? std::atoi(v) : (int) strata::core::kCompiledGeometry.n_expert; }();   // S20_E=256: the Coder pack
631    const Geo geo(p);
632    std::mt19937 rng(1360);
633    const int64_t rows = (int64_t) T * K;
634    // 512 distinct blobs - the products read each once per tile, as the engine does
635    // at a stride of whole blocks of both formats (MMQ's expert stride counts blocks), + MMQ's read past the end
636    size_t unit = type_size(p.gu);
637    while (unit % type_size(p.d) != 0 || unit % 16 != 0) unit += type_size(p.gu);
638    const size_t stride = (geo.bytes + unit - 1) / unit * unit;
639    Dev blobs((size_t) E * stride + 4096);
640    ck(cudaMemset(blobs.p, 0, (size_t) E * stride + 4096), "zero");
641    {
642        std::vector<uint8_t> b = make_blob(p, geo, rng);
643        for (int e = 0; e < E; ++e) {
644            b[4 + (size_t) (e % 16)] ^= (uint8_t) e;   // not all equal (inside the first block, not its scale)
645            ck(cudaMemcpy(blobs.as<uint8_t>() + (size_t) e * stride + g_blob_shift, b.data(), geo.bytes, cudaMemcpyHostToDevice),
646               "blob");
647        }
648    }
649    std::vector<const uint8_t*> blob((size_t) E);
650    for (int e = 0; e < E; ++e) blob[(size_t) e] = blobs.as<uint8_t>() + (size_t) e * stride + g_blob_shift;
651    // --host-blobs=N: the first N experts' blobs live in pinned, mapped HOST memory (the kernels can still read them through the host pointer), not device memory: the weight-staging
652    // check of experts_native fails for the launches that hold one, which then take the unstaged kernel (no process exit); the output bits must equal the all-device run's
653    struct HostBlobs {
654        void* p = nullptr;
655        ~HostBlobs() { if (p) (void)cudaFreeHost(p); }
656    } host_blobs;
657    if (g_host_blobs > 0) {
658        const int nh = std::min(g_host_blobs, E);
659        ck(cudaHostAlloc(&host_blobs.p, (size_t) nh * stride + 4096, cudaHostAllocMapped), "cudaHostAlloc");
660        std::memset(host_blobs.p, 0, (size_t) nh * stride + 4096);
661        for (int e = 0; e < nh; ++e) {
662            uint8_t* dst = (uint8_t*) host_blobs.p + (size_t) e * stride + g_blob_shift;
663            ck(cudaMemcpy(dst, blob[(size_t) e], geo.bytes, cudaMemcpyDeviceToHost), "blob to host");
664            blob[(size_t) e] = dst;
665        }
666    }
667    std::vector<float> x = make_x(T, rng, -1);
668    const Folded fo(tq_type(p.gu), rows);   // (--folded trellis pairs: rotated input, the H rotation on both paths, inside their times)
669    fo.rotate_x(x);
670    const std::vector<int32_t> ids = make_ids(T, E, rng, 0, 0);
671    const Routing r = sort_rows(ids, E);
672    Dev x_dev(x.size() * 4), src_dev((size_t) rows * 4);
673    ck(cudaMemcpy(x_dev.p, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "x");
674    ck(cudaMemcpy(src_dev.p, r.src.data(), r.src.size() * 4, cudaMemcpyHostToDevice), "src");
675    const bool mq = mmq_ok(p);
676    mmq::Context ctx;
677    MmqBufs* mbp = mq ? new MmqBufs(p, rows, E) : nullptr;
678    MmqBufs& mb = *mbp;   // (only used when mq)
679    FusedBufs fb(T, rows, E);
680    ck(cudaMemcpy(fb.ids.p, ids.data(), ids.size() * 4, cudaMemcpyHostToDevice), "ids");
681    ck(cudaDeviceSynchronize(), "uploads");   // (see reference_part)
682    cudaEvent_t a, b;
683    ck(cudaEventCreate(&a), "event");
684    ck(cudaEventCreate(&b), "event");
685    auto once = [&](auto&& f) {
686        ck(cudaEventRecord(a, s), "record");
687        f();
688        ck(cudaEventRecord(b, s), "record");
689        ck(cudaEventSynchronize(b), "sync");
690        float t = 0;
691        ck(cudaEventElapsedTime(&t, a, b), "elapsed");
692        return t;
693    };
694    auto mmq_run = [&] { run_mmq(p, geo, ctx, mb, r, x_dev.as<float>(), src_dev.as<int32_t>(), blob, rows, s); };
695    auto fused_run = [&] { run_fused(p, geo, fb, x_dev.as<float>(), T, E, {0, E}, blob, s); };
696    const bool all_routed = mq && std::count(r.cnt.begin(), r.cnt.end(), 0) == 0;
697    auto direct_run = [&] {
698        run_mmq(p, geo, ctx, mb, r, x_dev.as<float>(), src_dev.as<int32_t>(), blob, rows, s, true, stride);
699    };
700    if (std::getenv("S20_IDSDIAG")) {   // which step overwrites the routing ids on the device
701        auto check = [&](const char* after) {
702            ck(cudaStreamSynchronize(s), "sync");
703            const std::vector<int32_t> d = download_i(fb.ids, (size_t) rows);
704            int64_t bad = 0;
705            for (size_t i = 0; i < (size_t) rows; ++i) bad += d[i] != ids[i];
706            std::printf("    ids on the device after %s: %lld of %lld differ (fb.ids %p, mb.dm %p..%p, fb.dm %p..%p)\n",
707                        after, (long long) bad, (long long) rows, fb.ids.p, mb.dm.p,
708                        (void*) (mb.dm.as<uint8_t>() + (size_t) rows * N * 4), fb.dm.p,
709                        (void*) (fb.dm.as<uint8_t>() + (size_t) rows * N * 4));
710        };
711        check("the upload");
712        mmq_run();
713        check("an MMQ run");
714        fused_run();
715        check("a fused run");
716        if (all_routed) {
717            direct_run();
718            check("an MMQ run without gathers");
719        }
720    }
721    // ~1 s of both first (the clocks ramp up), then alternating rounds; the medians
722    const bool no_mmq = !mq || std::getenv("S20_NOMMQ") != nullptr || g_host_blobs > 0;   // (debug: the fused runs alone; MMQ does not read host blobs)
723    for (float spent = 0; spent < 1000.0f;) spent += (no_mmq ? 0.0f : once(mmq_run)) + once(fused_run);
724    std::vector<float> tm, tf, td;
725    for (int rep = 0; rep < 8; ++rep) {
726        tm.push_back(no_mmq ? 1.0f : once(mmq_run));
727        tf.push_back(once(fused_run));
728        if (all_routed && !no_mmq) td.push_back(once(direct_run));
729    }
730    if (td.empty()) td.push_back(0.0f);
731    std::sort(tm.begin(), tm.end());
732    std::sort(tf.begin(), tf.end());
733    std::sort(td.begin(), td.end());
734    const float t_mmq = tm[tm.size() / 2], t_f = tf[tf.size() / 2];
735    if (all_routed)
736        std::printf("  (MMQ's products alone, no gathers: %.3f ms - fused %.2fx)\n", td[td.size() / 2],
737                    td[td.size() / 2] / t_f);
738    std::vector<float> tf2;   // back to back
739    for (int rep = 0; rep < 8; ++rep) tf2.push_back(once(fused_run));
740    std::sort(tf2.begin(), tf2.end());
741    std::printf("  (fused back to back: median %.3f ms, min %.3f; alternating min %.3f; MMQ min %.3f)\n", tf2[4],
742                tf2[0], tf[0], tm[0]);
743    const std::vector<float> y_mmq = mq ? download(mb.dm, (size_t) rows * N) : std::vector<float>((size_t) rows * N, 0.0f),
744                             y_f = download(fb.dm, (size_t) rows * N);
745    const std::vector<int32_t> slot = download_i(fb.slot, (size_t) rows);
746    {   // (Aurora S23) a hash of the fused output's bits, to compare two builds bit for bit
747        uint64_t hsh = 1469598103934665603ull;
748        for (size_t i = 0; i < (size_t) rows; ++i)   // in pair order: the rows of an expert are placed in any order
749            for (size_t c = 0; c < (size_t) N; ++c) { uint32_t u; std::memcpy(&u, &y_f[(size_t) slot[i] * N + c], 4); hsh = (hsh ^ u) * 1099511628211ull; }
750        std::printf("  fused output bits hash %016llx\n", (unsigned long long) hsh);
751    }
752    const Err efm = mq ? compare(y_f, [&](size_t i) { return (int64_t) slot[i]; }, y_mmq,
753                                 [&](size_t i) { return (int64_t) r.row_of[i]; }, (size_t) rows) : Err{};
754    std::printf("%s - timing part: %d tokens x top %d over %d experts, one layer: MMQ path %.3f ms, fused %.3f ms "
755                "(%.2fx); fused vs MMQ rel RMS %.3e worst row %.3e\n",
756                p.name, T, K, E, t_mmq, t_f, t_mmq / t_f, efm.rms, efm.worst);
757    // fused against MMQ pair by pair (information): the share of pairs that differ by more than 1e-5 of the pair's largest MMQ value, and the largest two.  Two int8 paths that round the
758    // activations differently disagree on a few pairs by up to a few 1e-3, and the largest of those over all pairs grows with their number (Q2_0 / Q2_0 on an RTX A4000, measured 11-13,
759    // 3,000 sampled pairs at 8,192 / 16,384 / 20,000 tokens: 15 .. 23 pairs above 1e-5, largest 4.5e-3 .. 5.8e-3, median 2.2e-7; the same two kernels sit at the same distance from FP32 as MMQ)
760    if (mq && !no_mmq) {
761        std::vector<double> rel((size_t) rows);
762        for (size_t i = 0; i < (size_t) rows; ++i) {
763            const float* a = y_f.data() + (size_t) slot[i] * N;
764            const float* m = y_mmq.data() + (size_t) r.row_of[i] * N;
765            double me = 0, mr = 0;
766            for (int o = 0; o < N; ++o) { me = std::max(me, (double) std::fabs(a[o] - m[o])); mr = std::max(mr, (double) std::fabs(m[o])); }
767            rel[i] = mr > 0 ? me / mr : (me > 0 ? 1e30 : 0.0);
768        }
769        size_t above = 0;
770        for (double v : rel) above += v > 1e-5;
771        std::vector<double> top(rel);
772        std::nth_element(top.begin(), top.begin() + (ptrdiff_t) (top.size() / 2), top.end());
773        const double med = top[top.size() / 2];
774        std::sort(rel.rbegin(), rel.rend());
775        std::printf("%s - fused vs MMQ per pair (information): %zu of %lld pairs above 1e-5, largest %.3e, second %.3e, median %.3e\n", p.name, above, (long long) rows,
776                    rel.size() > 0 ? rel[0] : 0.0, rel.size() > 1 ? rel[1] : 0.0, med);
777    }
778    {   // the grouping: every pair in its expert's rows (the near-identical blobs here would hide a wrong expert)
779        const std::vector<int32_t> fsrc = download_i(fb.src, (size_t) rows);
780        int64_t bad = 0, bad_src = 0;
781        for (size_t i = 0; i < (size_t) rows; ++i) {
782            const int e = ids[i];
783            bad += slot[i] < r.off[(size_t) e] || slot[i] >= r.off[(size_t) e + 1];
784            bad_src += fsrc[(size_t) slot[i]] != (int32_t) (i / K);
785        }
786        if (bad || bad_src) {
787            std::vector<int32_t> tbl((size_t) 4 * E + 2);
788            ck(cudaMemcpy(tbl.data(), fb.scratch.p, tbl.size() * 4, cudaMemcpyDeviceToHost), "tables");
789            int64_t bad_cnt = 0, bad_off = 0, bad_ids = 0;
790            const std::vector<int32_t> d_ids = download_i(fb.ids, (size_t) rows);
791            for (size_t i = 0; i < (size_t) rows; ++i) bad_ids += d_ids[i] != ids[i];
792            std::printf("  the routing ids on the device: %lld of %lld differ (first %d %d %d)\n", (long long) bad_ids,
793                        (long long) rows, d_ids[0], d_ids[1], d_ids[2]);
794            const int32_t smin = *std::min_element(slot.begin(), slot.end()), smax = *std::max_element(slot.begin(), slot.end());
795            std::printf("  slots %d..%d; off[0..3] %d %d %d %d off[E] %d; fill[0..3] %d %d %d %d; ts[0..3] %d %d %d %d "
796                        "ts[E] %d\n", smin, smax, tbl[E], tbl[E + 1], tbl[E + 2], tbl[E + 3], tbl[2 * E], tbl[2 * E + 1],
797                        tbl[2 * E + 2], tbl[2 * E + 3], tbl[2 * E + 4], tbl[3 * E + 1], tbl[3 * E + 2], tbl[3 * E + 3],
798                        tbl[3 * E + 4], tbl[4 * E + 1]);
799            // the group again on these ids, synchronously
800            fused::group(fb.ids.as<int32_t>(), rows, K, E, fb.scratch.p, fb.slot.as<int32_t>(), fb.src.as<int32_t>(), s);
801            ck(cudaStreamSynchronize(s), "sync");
802            std::vector<int32_t> t2((size_t) 4 * E + 2);
803            ck(cudaMemcpy(t2.data(), fb.scratch.p, t2.size() * 4, cudaMemcpyDeviceToHost), "tables");
804            std::printf("  group() again, synchronized: cnt[0..3] %d %d %d %d off[E] %d\n", t2[0], t2[1], t2[2], t2[3],
805                        t2[(size_t) 2 * E]);
806            for (int e = 0; e < E; ++e) {
807                bad_cnt += tbl[(size_t) e] != r.cnt[(size_t) e];
808                bad_off += tbl[(size_t) E + e] != r.off[(size_t) e];
809            }
810            std::printf("  GROUPING WRONG: %lld pairs outside their expert's rows, %lld src mismatches; tables: %lld counts "
811                        "and %lld offsets differ from the host's (cnt[0..3] %d %d %d %d vs %d %d %d %d)\n",
812                        (long long) bad, (long long) bad_src, (long long) bad_cnt, (long long) bad_off, tbl[0], tbl[1],
813                        tbl[2], tbl[3], r.cnt[0], r.cnt[1], r.cnt[2], r.cnt[3]);
814            throw std::runtime_error(std::string(p.name) + ": the grouping is wrong");
815        }
816    }
817    if (std::getenv("S20_ROWDIAG")) {   // the pairs whose rows differ most: expert, its rows, the row's place
818        const std::vector<int32_t> fsrc = download_i(fb.src, (size_t) rows);
819        std::vector<std::pair<double, size_t>> worst;
820        for (size_t i = 0; i < (size_t) rows; ++i) {
821            const float* a = y_f.data() + (size_t) slot[i] * N;
822            const float* m = y_mmq.data() + (size_t) r.row_of[i] * N;
823            double me = 0, mr = 0;
824            for (int o = 0; o < N; ++o) { me = std::max(me, (double) std::fabs(a[o] - m[o])); mr = std::max(mr, (double) std::fabs(m[o])); }
825            worst.push_back({mr > 0 ? me / mr : me, i});
826        }
827        std::sort(worst.rbegin(), worst.rend());
828        for (int k = 0; k < 12; ++k) {
829            const size_t i = worst[(size_t) k].second;
830            const int e = ids[i];
831            // the expert's rows start at its first fused row: the smallest slot of its pairs
832            int32_t first = INT32_MAX;
833            for (size_t j = 0; j < (size_t) rows; ++j) if (ids[j] == e) first = std::min(first, slot[j]);
834            std::printf("    pair %zu token %zu expert %d (%d rows) fused row %d (+%d in the expert) max rel %.3e\n", i,
835                        i / K, e, r.cnt[(size_t) e], slot[i], slot[i] - first, worst[(size_t) k].first);
836        }
837        (void) fsrc;
838    }
839    // both against the double-precision reference on a sample of 96 pairs
840    {
841        std::vector<size_t> pick;
842        for (size_t i = 0; i < 96; ++i) pick.push_back((i * 2654435761u) % (size_t) rows);
843        std::vector<float> ref(pick.size() * N), ref2(pick.size() * N), ym(pick.size() * N), yf(pick.size() * N);
844        std::vector<uint8_t> hb(geo.bytes);
845        std::vector<float> gu, dn, h(FF), xq(N), h2(FF), hq(FF);
846        const bool own_model = !mmq::built() && !tq_type(p.gu);   // (the sample's int8 model reads the plain weights: not the trellis codebook)
847        for (size_t j = 0; j < pick.size(); ++j) {
848            const size_t i = pick[j];
849            const int e = ids[i];
850            ck(cudaMemcpy(hb.data(), blob[(size_t) e], geo.bytes, cudaMemcpyDefault), "blob back");   // (default kind: a --host-blobs blob is host memory)
851            dequant(p, geo, hb, gu, dn);
852            const float* xr = x.data() + (i / K) * N;
853            for (int f = 0; f < FF; ++f) {
854                double gt = 0, up = 0;
855                const float *wg = gu.data() + (size_t) f * N, *wu = gu.data() + (size_t) (FF + f) * N;
856                for (int k = 0; k < N; ++k) { gt += (double) wg[k] * xr[k]; up += (double) wu[k] * xr[k]; }
857                h[(size_t) f] = (float) (gt / (1.0 + std::exp(-gt)) * up);
858            }
859            if (fo.on) rot128(h.data(), FF, fo.sh.data());   // (--folded)
860            for (int o = 0; o < N; ++o) {
861                double a = 0;
862                const float* wd = dn.data() + (size_t) o * FF;
863                for (int f = 0; f < FF; ++f) a += (double) wd[f] * h[(size_t) f];
864                ref[j * N + o] = (float) a;
865            }
866            if (kq_gu(p) || own_model) {   // the int8-rounded model on the sample (the K-quant rule, see kq_gu; a build without MMQ: every pair but the trellis ones)
867                quant32(xr, xq.data(), N);
868                for (int f = 0; f < FF; ++f) {
869                    double gt = 0, up = 0;
870                    const float *wg = gu.data() + (size_t) f * N, *wu = gu.data() + (size_t) (FF + f) * N;
871                    for (int k = 0; k < N; ++k) { gt += (double) wg[k] * xq[(size_t) k]; up += (double) wu[k] * xq[(size_t) k]; }
872                    h2[(size_t) f] = (float) (gt / (1.0 + std::exp(-gt)) * up);
873                }
874                quant32(h2.data(), hq.data(), FF);
875                for (int o = 0; o < N; ++o) {
876                    double a = 0;
877                    const float* wd = dn.data() + (size_t) o * FF;
878                    for (int f = 0; f < FF; ++f) a += (double) wd[f] * hq[(size_t) f];
879                    ref2[j * N + o] = (float) a;
880                }
881            }
882            if (mq) std::copy_n(y_mmq.begin() + (ptrdiff_t) ((size_t) r.row_of[i] * N), N, ym.begin() + (ptrdiff_t) (j * N));
883            std::copy_n(y_f.begin() + (ptrdiff_t) ((size_t) slot[i] * N), N, yf.begin() + (ptrdiff_t) (j * N));
884        }
885        auto id = [](size_t j) { return (int64_t) j; };
886        const Err em = mq ? compare(ym, id, ref, id, pick.size()) : Err{}, ef = compare(yf, id, ref, id, pick.size());
887        std::printf("  sample of %zu pairs vs FP32 reference: MMQ rel RMS %.3e worst %.3e, fused rel RMS %.3e worst "
888                    "%.3e\n", pick.size(), em.rms, em.worst, ef.rms, ef.worst);
889        if (own_model) {   // a build without MMQ: the rule of kOwnRel on the sample
890            const Err e2 = compare(yf, id, ref2, id, pick.size()), ev = compare(ref2, id, ref, id, pick.size());
891            std::printf("  sample of %zu pairs, fused vs the int8-rounded model: rel RMS %.3e worst %.3e; the model vs FP32: rel RMS %.3e worst %.3e\n",
892                        pick.size(), e2.rms, e2.worst, ev.rms, ev.worst);
893            if (e2.rms > (f16_on() ? 5e-3 : 2e-3) || e2.worst > 3e-2)
894                throw std::runtime_error(std::string(p.name) + ": the fused path differs from its own arithmetic's model (timing)");
895            own_only_check(p, ev, ef, true);
896        } else
897        if (kq_gu(p)) {
898            const Err e2 = compare(yf, id, ref2, id, pick.size());
899            std::printf("  sample of %zu pairs, fused vs the int8-rounded model: rel RMS %.3e worst %.3e\n", pick.size(), e2.rms, e2.worst);
900            if (e2.rms > (f16_on() ? 5e-3 : 2e-3) || e2.worst > 3e-2)
901                throw std::runtime_error(std::string(p.name) + ": the fused path differs from its own arithmetic's model (timing)");
902            if (mq && (ef.rms > kKqRms * em.rms || ef.worst > kKqWorst * em.worst))
903                throw std::runtime_error(std::string(p.name) + ": the fused path is further from the reference than MMQ (K-quant rule, timing)");
904        } else
905        if (!mq ? (ef.rms > 0.03 || ef.worst > 0.25) : (ef.rms > 1.5 * em.rms || ef.worst > 2.0 * em.worst))
906            throw std::runtime_error(std::string(p.name) + ": the fused path's error is not comparable to MMQ's (timing)");
907    }
908    (void)cudaEventDestroy(a);
909    (void)cudaEventDestroy(b);
910    delete mbp;
911    if (g_host_blobs > 0) {
912        const int fbk = fused::staged_blob_fallbacks();
913        std::printf("  host blobs (first %d experts): %d launches took the unstaged kernel (the staging check failed; no process exit)\n", g_host_blobs, fbk);
914        if (g_expect_fallback > 0 && fbk == 0) throw std::runtime_error(std::string(p.name) + ": --expect-fallback: no launch took the unstaged kernel");
915        if (g_expect_fallback < 0 && fbk != 0) throw std::runtime_error(std::string(p.name) + ": --expect-no-fallback: a launch took the unstaged kernel");
916    }
917    // the two int8 paths at the real shape, every tile of the layer: R9700 rel RMS 1.3-1.9e-4, worst row 2.9e-3-8.3e-3
918    // (STRATA_PF_F16=1: F16 products against MMQ's int8, gfx1151 rel RMS 2.5-2.7e-3, worst row 6.4e-3-8.8e-3)
919    // (K-quant gate/up pairs: fused against MMQ is information only, see kq_gu)
920    // Fused against MMQ is a comparison of two noisy paths with each other, not against the truth: its worst row is the largest of many tail values and grows with the row count (Q2_0 / Q2_0,
921    // RTX A4000: 1.0e-2 at 8,192 tokens, 2.6e-2 at 20,000 and 32,768 with rel RMS 2e-5, while both paths stand at the same distance from the FP32 reference).  So the worst row here is only a
922    // backstop against a wrong row (a few 1e-1 and up), and the pair statistics above are information; the check that a fused path is not further from FP32 than MMQ is the sample's
923    // (ef against em, 1.5x RMS and 2x worst row, or the K-quant and own-model rules), which does not grow with the row count.
924    if (mq && !no_mmq && !kq_gu(p) && (efm.rms > (f16_on() ? 5e-3 : 1e-3) || efm.worst > 1e-1))
925        throw std::runtime_error(std::string(p.name) + ": the paths disagree at the real shape");
926}
927// --bits-staged: byte identity of the weight-staging kernels against the unstaged kernel of the same formats.  The same experts, input and routing run twice per size:
928// first with every blob in device memory (the staged 128-row instances where the pair has them, at blobs 2-byte aligned at eight different offsets modulo 16), then with every
929// blob in pinned, mapped HOST memory, where the staging check of experts_native fails and the launch takes the unstaged 64-row instances (sticky for the process, so all the
930// staged runs come first).  Every output float of every routed row must be the same bits.  Needs --only=NAME.
931struct BitsRun {
932    std::vector<float> y;
933    std::vector<int32_t> slot;
934    uint64_t hash = 0;
935};
936BitsRun bits_run(const Pair& p, int T, int E, bool host, cudaStream_t s) {
937    const Geo geo(p);
938    std::mt19937 rng(5100 + (unsigned) p.gu * 7 + (unsigned) p.d + (unsigned) T);
939    const int64_t rows = (int64_t) T * K;
940    const size_t stride = (geo.bytes + 64 + 15) / 16 * 16;
941    constexpr int kDistinct = 8;   // eight different blobs, repeated over the experts with a byte changed in each
942    std::vector<std::vector<uint8_t>> base;
943    for (int i = 0; i < kDistinct; ++i) base.push_back(make_blob(p, geo, rng));
944    Dev blobs((size_t) E * stride + 4096);
945    ck(cudaMemset(blobs.p, 0, (size_t) E * stride + 4096), "zero");
946    struct HostMem {
947        void* p = nullptr;
948        ~HostMem() { if (p) (void)cudaFreeHost(p); }
949    } hm;
950    if (host) {
951        ck(cudaHostAlloc(&hm.p, (size_t) E * stride + 4096, cudaHostAllocMapped), "cudaHostAlloc");
952        std::memset(hm.p, 0, (size_t) E * stride + 4096);
953    }
954    std::vector<const uint8_t*> blob((size_t) E);
955    for (int e = 0; e < E; ++e) {
956        std::vector<uint8_t> b = base[(size_t) (e % kDistinct)];
957        b[4 + (size_t) (e % 16)] ^= (uint8_t) e;
958        const size_t off = (size_t) e * stride + 2 * (size_t) (e % 8);   // 2-byte aligned, eight positions inside a 16-byte window
959        if (host) {
960            std::memcpy((uint8_t*) hm.p + off, b.data(), geo.bytes);
961            blob[(size_t) e] = (const uint8_t*) hm.p + off;
962        } else {
963            ck(cudaMemcpy(blobs.as<uint8_t>() + off, b.data(), geo.bytes, cudaMemcpyHostToDevice), "blob");
964            blob[(size_t) e] = blobs.as<uint8_t>() + off;
965        }
966    }
967    const std::vector<float> x = make_x(T, rng, T > 3 ? 1 : -1);
968    const std::vector<int32_t> ids = make_ids(T, E, rng, 2, 4);   // experts 0 and 1 hot (several tiles), the last 4 unused
969    Dev x_dev(x.size() * 4);
970    ck(cudaMemcpy(x_dev.p, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "x");
971    FusedBufs fb(T, rows, E);
972    ck(cudaMemcpy(fb.ids.p, ids.data(), ids.size() * 4, cudaMemcpyHostToDevice), "ids");
973    ck(cudaMemset(fb.dm.p, 0xff, (size_t) rows * N * 4), "sentinel");   // an unwritten row is NaN
974    ck(cudaDeviceSynchronize(), "uploads");
975    run_fused(p, geo, fb, x_dev.as<float>(), T, E, {0, 1, std::min(20, E - 1), E}, blob, s);
976    ck(cudaStreamSynchronize(s), "sync");
977    BitsRun r;
978    r.y = download(fb.dm, (size_t) rows * N);
979    r.slot = download_i(fb.slot, (size_t) rows);
980    r.hash = 1469598103934665603ull;
981    for (size_t i = 0; i < (size_t) rows; ++i)
982        for (size_t c = 0; c < (size_t) N; ++c) { uint32_t u; std::memcpy(&u, &r.y[(size_t) r.slot[i] * N + c], 4); r.hash = (r.hash ^ u) * 1099511628211ull; }
983    return r;
984}
985// every pair's staged runs first (the fallback is sticky for the process), then every pair's unstaged runs
986void bits_staged(const std::vector<Pair>& ps, const std::vector<int>& sizes, int E, cudaStream_t s) {
987    std::vector<BitsRun> staged;
988    for (const Pair& p : ps)
989        for (int T : sizes) staged.push_back(bits_run(p, T, E, false, s));
990    if (fused::staged_blob_fallbacks() != 0) throw std::runtime_error("--bits-staged: a device-blob launch took the unstaged kernel");
991    size_t idx = 0;
992    for (const Pair& p : ps)
993        for (int T : sizes) {
994        const BitsRun u = bits_run(p, T, E, true, s);
995        if (fused::staged_blob_fallbacks() == 0) throw std::runtime_error(std::string(p.name) + ": --bits-staged: the host-blob run did not take the unstaged kernel");
996        const BitsRun& a = staged[idx++];
997        int64_t diff = 0, bad = 0, nz = 0;
998        for (size_t q = 0; q < (size_t) T * K; ++q) {
999            const float* ya = a.y.data() + (size_t) a.slot[q] * N;
1000            const float* yb = u.y.data() + (size_t) u.slot[q] * N;
1001            if (std::memcmp(ya, yb, (size_t) N * 4) != 0) ++diff;
1002            for (int c = 0; c < N; ++c) { bad += !std::isfinite(ya[c]); nz += ya[c] != 0.0f; }
1003        }
1004        std::printf("%s - bits-staged: %d tokens x top %d over %d experts: staged vs unstaged %lld of %d rows differ, hash %016llx / %016llx, %lld non-finite, %lld nonzero values\n",
1005                    p.name, T, K, E, (long long) diff, T * K, (unsigned long long) a.hash, (unsigned long long) u.hash, (long long) bad, (long long) nz);
1006        if (diff != 0 || a.hash != u.hash) throw std::runtime_error(std::string(p.name) + ": --bits-staged: the staged and unstaged outputs differ");
1007        if (bad != 0 || nz == 0) throw std::runtime_error(std::string(p.name) + ": --bits-staged: a non-finite or an all-zero output");
1008    }
1009}
1010}  // namespace
1011
1012int main(int argc, char** argv) {
1013    try {
1014        // --unset-pf-fused: STRATA_PF_FUSED unset, as the engine's default (the ctest entry for the opt-in STRATA_PF_FUSED_Q2N=1,
1015        // whose Q2_0 / Q2_0 pair the engine takes with the old variable unset or at 1)
1016        // --no-kq: STRATA_PF_FUSED_KQ left as it is (HIP: the ctest entry for STRATA_PF_FUSED_Q8D=1 on gfx12, which must cover the i-quant / Q8_0
1017        // pairs without the K-quant switch that also covers them there)
1018        // --turing: the Turing set only (STRATA_PF_FUSED_SM75=1; the ctest entry prefill_fused_iq_test_sm75): skipped (77) unless the card is a compute capability 7.5 one or emulates it (STRATA_EMULATE_CC=75)
1019        bool unset_pf = false, no_kq = false, turing_only = false;
1020        for (int i = 1; i < argc; ++i) {
1021            if (std::strcmp(argv[i], "--unset-pf-fused") == 0) unset_pf = true;
1022            if (std::strcmp(argv[i], "--no-kq") == 0) no_kq = true;
1023            if (std::strcmp(argv[i], "--turing") == 0) turing_only = true;
1024        }
1025        if (turing_only) {
1026            int cmaj = 0, cmin = 0;
1027            if (cudaGetDeviceCount(&cmaj) != cudaSuccess || cmaj == 0) { std::printf("no CUDA device: skipped\n"); return 77; }
1028            (void)cudaDeviceGetAttribute(&cmaj, cudaDevAttrComputeCapabilityMajor, 0);
1029            (void)cudaDeviceGetAttribute(&cmin, cudaDevAttrComputeCapabilityMinor, 0);
1030            if (strata::cc_major_of(cmaj) != 7 || strata::cc_minor_of(cmin) != 5) { std::printf("--turing: not a compute capability 7.5 card (and no STRATA_EMULATE_CC=75): skipped\n"); return 77; }
1031        }
1032#ifdef _WIN32
1033        if (unset_pf) _putenv_s("STRATA_PF_FUSED", ""); else _putenv_s("STRATA_PF_FUSED", "1");   // (an empty value removes it)
1034        (void) no_kq;   // (Windows: the K-quant switch is not set here)
1035#else
1036        if (unset_pf) unsetenv("STRATA_PF_FUSED"); else setenv("STRATA_PF_FUSED", "1", 1);
1037        if (!no_kq) setenv("STRATA_PF_FUSED_KQ", "1", 1);   // (the HIP build's Q4_K / Q5_K / Q5_1 / Q8_0 pairs)
1038        setenv("STRATA_PF_FUSED_Q50", "1", 1);  // (gfx12's Q5_0 down pairs)
1039#endif
1040        int n = 0;
1041        if (cudaGetDeviceCount(&n) != cudaSuccess || n == 0) { std::printf("no CUDA device: skipped\n"); return 77; }
1042        // gfx12: only the native kernels exist (fused::available() is the Q2_0 pack's), so they decide there
1043        if (!fused::available() && !fused::native_supported(GGML_TYPE_IQ3_XXS, GGML_TYPE_IQ4_NL)) {
1044            std::printf("the fused kernels need sm_80 or newer (or gfx11 / gfx12 matrix cores): skipped\n");
1045            return 77;
1046        }
1047        // --no-kq (the STRATA_PF_FUSED_Q8D entry): a device or build where the i-quant / Q8_0 pairs are not covered without the K-quant switch
1048        // (gfx11, or the switch unset) skips instead of failing
1049        // (with STRATA_PF_FUSED_Q8GU=1 the probe is the Q8_0 / Q8_0 pair: the Q8GU entry asks the same of its own switch)
1050        const char* q8gu_env = std::getenv("STRATA_PF_FUSED_Q8GU");
1051        const bool probe_q8gu = q8gu_env != nullptr && q8gu_env[0] == '1';
1052        if (no_kq && !fused::native_supported(probe_q8gu ? GGML_TYPE_Q8_0 : GGML_TYPE_IQ3_S, GGML_TYPE_Q8_0)) {
1053            std::printf("--no-kq: the %s pairs are not covered here without STRATA_PF_FUSED_KQ (skipped)\n", probe_q8gu ? "Q8_0 / Q8_0" : "i-quant / Q8_0");
1054            return 77;
1055        }
1056#if defined(__HIPCC__)
1057        // the trellis pairs on HIP are gfx12's (STRATA_PF_FUSED_TQ=1): another AMD card skips the _tq / _tqh entries instead of failing; on gfx12
1058        // the pairs must be covered (a host rule that does not take them fails below)
1059        const char* only_tq = nullptr;
1060        for (int i = 1; i < argc; ++i)
1061            if (std::strncmp(argv[i], "--only=", 7) == 0) only_tq = argv[i] + 7;
1062        if (only_tq != nullptr && std::strstr("TQK6 + TQK7 TQ2_T + TQ2_T Q6_K + Q8_0", only_tq) != nullptr) {   // (and the Q6_K pair: STRATA_PF_FUSED_Q6K=1 is gfx12's too)
1063            cudaDeviceProp prop{};
1064            if (cudaGetDeviceProperties(&prop, 0) == cudaSuccess && std::strncmp(prop.gcnArchName, "gfx12", 5) != 0) {
1065                std::printf("the trellis / Q6_K pairs: gfx12 only on HIP (%s: skipped)\n", prop.gcnArchName);
1066                return 77;
1067            }
1068        }
1069#endif
1070        // with STRATA_PF_FUSED unset nothing is set up below sm_80 (Turing's pair is STRATA_PF_FUSED=1 STRATA_PF_FUSED_SM75=1's)
1071        if (unset_pf) {
1072            int major = 0;
1073            (void)cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, 0);
1074            if (strata::cc_major_of(major) < 8) { std::printf("STRATA_PF_FUSED unset: nothing is set up below sm_80 (skipped)\n"); return 77; }
1075        }
1076        // the opt-in kernel sets (STRATA_PF_FUSED_NT=256, _F16=1, _WS=1): a card that cannot set them up (shared memory,
1077        // occupancy) falls back to the 512-thread kernels, and a run of those would pass for the wrong kernels - skip it
1078        {
1079            const char* nt = std::getenv("STRATA_PF_FUSED_NT");
1080            const char* f16 = std::getenv("STRATA_PF_FUSED_F16");
1081            const char* ws = std::getenv("STRATA_PF_FUSED_WS");
1082            const bool asked = (nt && std::atoi(nt) == 256) || (f16 && f16[0] == '1') || (ws && ws[0] == '1');
1083            if (asked && !fused::native_wide()) {
1084                std::printf("STRATA_PF_FUSED_NT / _F16 / _WS: those kernels are not set up on this device (skipped)\n");
1085                return 77;
1086            }
1087        }
1088        if (!mmq::built()) std::printf("no MMQ in this build: the fused path against the references alone\n");
1089        const std::vector<Pair> pairs = {
1090            {GGML_TYPE_IQ2_S, GGML_TYPE_Q2_0, "IQ2_S / Q2_0"},       {GGML_TYPE_IQ2_XXS, GGML_TYPE_Q2_0, "IQ2_XXS / Q2_0"},
1091            {GGML_TYPE_IQ2_XS, GGML_TYPE_IQ4_NL, "IQ2_XS / IQ4_NL"}, {GGML_TYPE_IQ3_XXS, GGML_TYPE_IQ4_NL, "IQ3_XXS / IQ4_NL"},
1092            {GGML_TYPE_IQ3_S, GGML_TYPE_IQ4_NL, "IQ3_S / IQ4_NL"},   {GGML_TYPE_IQ4_XS, GGML_TYPE_Q2_0, "IQ4_XS / Q2_0"},
1093            // (HIP only) UD-Q4_K_XL's: 47 layers Q4_K / Q5_1, 4 Q4_K / Q8_0, and the one Q5_K layer
1094            {GGML_TYPE_Q4_K, GGML_TYPE_Q5_1, "Q4_K / Q5_1"},         {GGML_TYPE_Q4_K, GGML_TYPE_Q8_0, "Q4_K / Q8_0"},
1095            {GGML_TYPE_Q5_K, GGML_TYPE_Q5_1, "Q5_K / Q5_1"},         {GGML_TYPE_Q5_K, GGML_TYPE_Q8_0, "Q5_K / Q8_0"},
1096            // the Coder IQ1_M pack's other pairs (appended: the default timing set takes pairs 0, 1, 4, 3 by index)
1097            {GGML_TYPE_IQ2_S, GGML_TYPE_IQ4_NL, "IQ2_S / IQ4_NL"},   {GGML_TYPE_IQ3_XXS, GGML_TYPE_Q2_0, "IQ3_XXS / Q2_0"},
1098            {GGML_TYPE_IQ3_S, GGML_TYPE_Q2_0, "IQ3_S / Q2_0"},       {GGML_TYPE_IQ4_XS, GGML_TYPE_IQ4_NL, "IQ4_XS / IQ4_NL"},
1099            // UD-IQ4_XS-v31's Q5_0 down layers (STRATA_PF_FUSED_Q50=1: HIP gfx12, and CUDA sm_80+ since phase 4 step 1; checked against the reference, the build has no Q5_0 MMQ)
1100            {GGML_TYPE_IQ3_XXS, GGML_TYPE_Q5_0, "IQ3_XXS / Q5_0"},   {GGML_TYPE_IQ4_XS, GGML_TYPE_Q5_0, "IQ4_XS / Q5_0"},
1101            // the canonical Q2_0 pack (gate/up and down Q2_0; CUDA)
1102            {GGML_TYPE_Q2_0, GGML_TYPE_Q2_0, "Q2_0 / Q2_0"},
1103            // the pinned UD-IQ4_XS's Q8_0 down layers (IQ3_S / Q8_0 4, IQ4_XS / Q8_0 1): STRATA_PF_FUSED_Q8D=1 on CUDA sm_80+ (opt-in)
1104            {GGML_TYPE_IQ3_S, GGML_TYPE_Q8_0, "IQ3_S / Q8_0"},       {GGML_TYPE_IQ4_XS, GGML_TYPE_Q8_0, "IQ4_XS / Q8_0"},
1105            // the Q8_0 set's layers (and UD-Q6_K_XL's one Q8_0 layer): STRATA_PF_FUSED_Q8GU=1 on CUDA sm_80+ (opt-in)
1106            {GGML_TYPE_Q8_0, GGML_TYPE_Q8_0, "Q8_0 / Q8_0"},
1107            // UD-Q6_K_XL's layers (and UD-Q5_K_XL's one Q6_K layer): STRATA_PF_FUSED_Q6K=1 on CUDA sm_80+ (opt-in); MMQ = the K-quant library.
1108            // Named with "+" so the _kq entry's --only="K / Q" does not take it
1109            {GGML_TYPE_Q6_K, GGML_TYPE_Q8_0, "Q6_K + Q8_0"},
1110            // Gyro-S (TQK6 gate/up, TQK7 down) and Gyro-M (TQ2_T both): STRATA_PF_FUSED_TQ=1 on CUDA sm_80+ (opt-in); MMQ = the overlay's trellis
1111            // instances; the ids are agentionai's (the pinned ggml.h has no enumerators for them)
1112            {(ggml_type) 145, (ggml_type) 146, "TQK6 + TQK7"},       {(ggml_type) 144, (ggml_type) 144, "TQ2_T + TQ2_T"},
1113            // NVFP4 (ModelOpt packs: gate/up and down NVFP4, the blob's tail = the per-expert scales); STRATA_PF_FUSED=1 as the test sets it; CUDA sm_80+; against the reference alone
1114            {GGML_TYPE_NVFP4, GGML_TYPE_NVFP4, "NVFP4 / NVFP4"}};
1115        const char* only = nullptr;   // --only=NAME: the pairs whose name contains NAME
1116        for (int i = 1; i < argc; ++i)
1117            if (std::strncmp(argv[i], "--only=", 7) == 0) only = argv[i] + 7;
1118        bool timing = true, ref = true;   // --no-timing, --no-ref: skip a part
1119        bool edge = false;                // --edge: the tails and tile boundaries (a handful of tokens, one token, 130 / 517 / 640) of the Q5_0 pairs, for every pair
1120        std::vector<int> chunks = {2048, 3584, 8192};   // --chunks=A,B: the timing part's chunk sizes
1121        for (int i = 1; i < argc; ++i) {
1122            if (std::strcmp(argv[i], "--no-timing") == 0) timing = false;
1123            if (std::strcmp(argv[i], "--no-ref") == 0) ref = false;
1124            if (std::strcmp(argv[i], "--edge") == 0) edge = true;
1125            if (std::strncmp(argv[i], "--blob-shift=", 13) == 0) g_blob_shift = std::atoi(argv[i] + 13);
1126            if (std::strncmp(argv[i], "--host-blobs=", 13) == 0) g_host_blobs = std::atoi(argv[i] + 13);
1127            if (std::strcmp(argv[i], "--expect-fallback") == 0) g_expect_fallback = 1;
1128            if (std::strcmp(argv[i], "--expect-no-fallback") == 0) g_expect_fallback = -1;
1129            if (std::strcmp(argv[i], "--folded") == 0) g_folded = true;   // (the trellis pairs as Hadamard-folded experts: see g_folded)
1130            if (std::strncmp(argv[i], "--chunks=", 9) == 0) {
1131                chunks.clear();
1132                for (const char* c = argv[i] + 9; *c;) {
1133                    chunks.push_back(std::atoi(c));
1134                    while (*c && *c != ',') ++c;
1135                    if (*c == ',') ++c;
1136                }
1137            }
1138        }
1139        int pairs_run = 0;   // (the pairs whose kernels this device has; --turing insists on at least one)
1140        cudaStream_t s = nullptr;
1141        ck(cudaStreamCreateWithFlags(&s, cudaStreamNonBlocking), "stream");
1142        bool bits = false;
1143        for (int i = 1; i < argc; ++i)
1144            if (std::strcmp(argv[i], "--bits-staged") == 0) bits = true;
1145        if (bits) {   // see bits_staged: tails (1, 33, 130, 517 tokens), a tile boundary and a real chunk
1146            if (!only) throw std::runtime_error("--bits-staged needs --only=NAME");
1147            std::vector<Pair> sel;
1148            for (const Pair& p : pairs) {
1149                if (std::string(p.name).find(only) == std::string::npos) continue;
1150                if (!fused::native_supported((int) p.gu, (int) p.d)) throw std::runtime_error(std::string(p.name) + ": not covered by the native kernels");
1151                sel.push_back(p);
1152            }
1153            if (sel.empty()) throw std::runtime_error("--bits-staged: no pair matches --only");
1154            bits_staged(sel, {1, 33, 130, 517, 640, 2048}, 64, s);
1155            ck(cudaStreamDestroy(s), "destroy");
1156            std::printf("prefill fused MoE (native formats) staged-vs-unstaged bit identity passed\n");
1157            return 0;
1158        }
1159        for (const Pair& p : pairs) {
1160            if (only ? std::string(p.name).find(only) == std::string::npos : p.gu == GGML_TYPE_Q4_K || p.gu == GGML_TYPE_Q5_K) continue;
1161            // the i-quant / Q8_0 and Q8_0 / Q8_0 pairs run only when --only names them (ctest prefill_fused_iq_test_q8d / _q8gu), so every
1162            // other entry runs what it ran
1163            if (!only && ((p.d == GGML_TYPE_Q8_0 && !kq_gu(p)) || tq_type(p.gu) || nvfp4_pair(p))) continue;   // (and the trellis pairs: _tq; the NVFP4 pair: _nvfp4)
1164            if (!fused::native_supported((int) p.gu, (int) p.d)) {
1165                // the Q2_0 / Q2_0 pair is the Turing opt-in's (STRATA_PF_FUSED_SM75=1; the only pair set up there) or, on sm_80+,
1166                // STRATA_PF_FUSED_Q2N=1's: skip what this device does not take (--only=NAME still insists)
1167                const bool turing_pair = p.gu == GGML_TYPE_Q2_0 && p.d == GGML_TYPE_Q2_0;
1168                const bool q50_pair = p.d == GGML_TYPE_Q5_0;   // (STRATA_PF_FUSED_Q50=1 only: off by default on CUDA and gfx12)
1169                int major = 0;
1170                (void)cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, 0);
1171                major = strata::cc_major_of(major);   // (STRATA_EMULATE_CC=75 on a bigger card: the pairs Turing has no kernels for are skipped as on the real card)
1172                if ((major < 8 || turing_pair || q50_pair) && (!only || turing_only)) { std::printf("%s: not set up on this device (skipped)\n", p.name); continue; }
1173                throw std::runtime_error(std::string(p.name) + ": not covered by the native kernels");
1174            }
1175            ++pairs_run;
1176            if (ref) reference_part(p, s);
1177            // Q5_0 down (round 0217): tails and boundaries - a handful of tokens, one token, a tile's edge (63, 65 rows an expert is not controlled, the counts follow the routing)
1178            if (ref && (p.d == GGML_TYPE_Q5_0 || edge)) {
1179                reference_part(p, s, 33, 16, 5);
1180                reference_part(p, s, 1, 16, -1);
1181                reference_part(p, s, 130, 32, 77);
1182                reference_part(p, s, 517, 32, 300);
1183                if (edge) reference_part(p, s, 640, 16, 300);   // five 64-row tiles an expert: the paired-tile (128-row) kernels
1184            }
1185        }
1186        if (turing_only && pairs_run == 0) throw std::runtime_error("--turing: no pair has kernels on this device (the Turing set was not set up)");
1187        if (timing) {
1188            // the IQ2_XS pack's layers (34 of 48 IQ2_S / Q2_0, 11 IQ2_XXS / Q2_0), the IQ3_S pack's most common, IQ3_XXS's
1189            for (const Pair& p : only ? pairs : std::vector<Pair>{pairs[0], pairs[1], pairs[4], pairs[3]}) {
1190                if (only && std::string(p.name).find(only) == std::string::npos) continue;
1191                if (!fused::native_supported((int) p.gu, (int) p.d)) continue;   // (Turing: the Q2_0 pair and the i-quant pairs the Turing set takes)
1192                for (int T : chunks) timing_part(p, T, s);
1193            }
1194        }
1195        ck(cudaStreamDestroy(s), "destroy");
1196        std::printf("prefill fused MoE (native formats) parity passed\n");
1197        return 0;
1198    } catch (const std::exception& e) {
1199        std::fprintf(stderr, "prefill fused MoE (native formats) parity failed: %s\n", e.what());
1200        return 1;
1201    }
1202}