okami.mom/strata

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

Niko1221Merge f-q36-mmqoff 30d9fc1a3 into the batch 16 candidate (Qwen3.6 without MMQ)1cdc6033b

main
38.5 KiB679 linesraw
1// prefill_fused_q36_test - the fused int8 expert kernels at Qwen3.6-35B-A3B's expert shape (n_embd 2048, n_ff 512, 256 experts, top 8):
2// the second copy of moe_fused_iq.cu that src/prefill/moe_fused_iq_q36.cu compiles (strata::prefill::fused_q36, moe_fused_q36.hpp), on
3// random native expert blobs ([gate rows | up rows | down rows], GGUF blocks) and random routing, per format pair, against
4//   - a double-precision reference: the weights dequantized by ggml's own to_float, times the FP32 activations (gate/up, SwiGLU, down),
5//   - the same with the kernels' int8 rounding of the activations and H per 32 values ("the int8 model"), and
6//   - the MMQ path in prefill.cpp's sequence (gather_native into 16-expert groups, q8_1 of the slots' activations, gate/up, SwiGLU, q8_1 of H,
7//     down), where MMQ has the pair's formats.
8// It is the counterpart of prefill_fused_iq_test.cpp, which is built for the compiled geometry (Flash-Next's 2560 / 640) and cannot reach the
9// copy.  The pairs are the Qwen3.6 sets' layers: UD-Q6_K_XL Q6_K / Q8_0 (40 layers) and Q8_0 / Q8_0 (1), the Q8_0 file's Q8_0 / Q8_0.
10// Part 1 (reference), per pair: 256 tokens over 64 experts, skewed routing (experts with 0 rows, with one, with several 64-row tiles), an
11// all-zero token, per-expert blobs at unrelated (2-byte aligned) addresses, three launches of different expert ranges; then the tails and
12// tile edges (33, 1, 130, 517 tokens).  Part 2 (timing): one layer at the engine's chunks (2048, 8192 tokens; 256 experts, top 8) on both
13// paths, the grouping checked and a sample of rows against the reference.  --no-ref, --no-timing, --only=NAME, --chunks=A,B,
14// --host-blobs=N [--expect-fallback | --expect-no-fallback] (the first N experts' blobs in host memory: the weight-staging check fails for the launches that hold one and they take the
15// unstaged kernel, same output bits; timing part, use with --no-ref).
16// Exit 77 without a CUDA device of sm_80 or newer.
17#include "strata/prefill/moe_fused.hpp"
18#include "strata/prefill/moe_fused_q36.hpp"
19#include "strata/prefill/mmq_ids_margin.hpp"
20#include "strata/prefill/moe_mmq.hpp"
21
22#include "ggml.h"
23
24#include <cuda_runtime.h>
25
26#include <algorithm>
27#include <cmath>
28#include <cstdint>
29#include <cstdio>
30#include <cstdlib>
31#include <cstring>
32#include <memory>
33#include <random>
34#include <stdexcept>
35#include <string>
36#include <thread>
37#include <vector>
38
39namespace {
40namespace mmq = strata::prefill::mmq;
41namespace fused = strata::prefill::fused;       // the grouping (the shape does not matter for it)
42namespace fq = strata::prefill::fused_q36;      // the kernels of the copy
43
44constexpr int N = fq::kQ36Embd, FF = fq::kQ36FF, FF2 = 2 * FF, K = 8, NEXP = 256, GROUP = 16;
45
46void ck(cudaError_t e, const char* what) {
47    if (e != cudaSuccess) throw std::runtime_error(std::string(what) + ": " + cudaGetErrorString(e));
48}
49
50struct Dev {
51    void* p = nullptr;
52    explicit Dev(size_t n) { ck(cudaMalloc(&p, n), "cudaMalloc"); }
53    ~Dev() { cudaFree(p); }
54    Dev(const Dev&) = delete;
55    Dev& operator=(const Dev&) = delete;
56    template <typename T> T* as() const { return (T*) p; }
57};
58
59struct Pair {
60    ggml_type gu, d;
61    const char* name;
62    bool optional = false;   // a pair this build may not cover yet: skipped with a printed line instead of failing (UD-Q4_K_XL's K-quant downs)
63};
64bool mmq_ok(const Pair& p) { return mmq::supported((int) p.gu) && mmq::supported((int) p.d); }
65int 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
66int g_expect_fallback = 0;  // --expect-fallback (+1) / --expect-no-fallback (-1): with --host-blobs, require that some / no launch took the unstaged kernel
67size_t row_size(ggml_type t, int64_t n) { return (size_t) (n / ggml_blck_size(t)) * ggml_type_size(t); }
68
69struct Geo {
70    size_t gu_row, d_row, up_off, down_off, bytes;
71    explicit Geo(const Pair& p) {
72        gu_row = row_size(p.gu, N);
73        d_row = row_size(p.d, FF);
74        up_off = gu_row * FF;
75        down_off = 2 * up_off;
76        bytes = down_off + d_row * N;
77    }
78    fq::NativeGeom native(const Pair& p) const {
79        fq::NativeGeom g;
80        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;
81        g.down_off = down_off;
82        return g;
83    }
84};
85
86// random blocks with a sane fp16 scale `d` in each block (a few hundredths of a typical weight's size)
87void fill_matrix(uint8_t* m, ggml_type t, int64_t rows, int64_t cols, std::mt19937& rng) {
88    const size_t bs = ggml_type_size(t), nb = (size_t) rows * (size_t) (cols / ggml_blck_size(t));
89    std::uniform_int_distribution<int> byte(0, 255);
90    const float lo = t == GGML_TYPE_Q4_K || t == GGML_TYPE_Q5_K ? 0.00004f : t == GGML_TYPE_Q5_1 ? 0.0006f
91                   : t == GGML_TYPE_Q8_0 ? 0.0001f : t == GGML_TYPE_Q6_K ? 0.000005f : 0.0008f;
92    std::uniform_real_distribution<float> sc(lo, 6.0f * lo);
93    for (size_t i = 0; i < nb * bs; ++i) m[i] = (uint8_t) byte(rng);
94    for (size_t b = 0; b < nb; ++b) {
95        const ggml_fp16_t h = ggml_fp32_to_fp16(sc(rng));
96        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)
97        if (t == GGML_TYPE_Q4_K || t == GGML_TYPE_Q5_K || t == GGML_TYPE_Q5_1) {   // the minimum's scale, either sign
98            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));
99            std::memcpy(m + b * bs + 2, &h2, 2);
100        }
101    }
102}
103std::vector<uint8_t> make_blob(const Pair& p, const Geo& g, std::mt19937& rng) {
104    std::vector<uint8_t> b(g.bytes);
105    fill_matrix(b.data(), p.gu, FF2, N, rng);
106    fill_matrix(b.data() + g.down_off, p.d, N, FF, rng);
107    return b;
108}
109
110// ggml's dequantized weights: gate [FF][N], up [FF][N], down [N][FF]
111void dequant(const Pair& p, const Geo& g, const std::vector<uint8_t>& b, std::vector<float>& gu, std::vector<float>& dn) {
112    gu.resize((size_t) FF2 * N);
113    dn.resize((size_t) N * FF);
114    const auto* tg = ggml_get_type_traits(p.gu);
115    const auto* td = ggml_get_type_traits(p.d);
116    for (int r = 0; r < FF2; ++r) tg->to_float(b.data() + (size_t) r * g.gu_row, gu.data() + (size_t) r * N, N);
117    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);
118}
119
120// activations: N(0, 1) with a few large values (the hidden state has outliers); token `zero` all zero
121std::vector<float> make_x(int T, std::mt19937& rng, int zero) {
122    std::vector<float> x((size_t) T * N);
123    std::normal_distribution<float> nd(0.0f, 1.0f);
124    std::uniform_int_distribution<int> pick(0, 199);
125    for (float& v : x) v = nd(rng) * (pick(rng) == 0 ? 12.0f : 1.0f);
126    if (zero >= 0) std::fill(x.begin() + (size_t) zero * N, x.begin() + (size_t) (zero + 1) * N, 0.0f);
127    return x;
128}
129
130// K distinct experts per token; `hot` > 0 skews the first choices towards the lowest ids; the last `unused` experts get none
131std::vector<int32_t> make_ids(int T, int E, std::mt19937& rng, int hot, int unused) {
132    std::vector<int32_t> ids((size_t) T * K);
133    std::uniform_int_distribution<int> any(0, E - 1 - unused);
134    for (int t = 0; t < T; ++t)
135        for (int k = 0; k < K; ++k) {
136            int e;
137            bool dup;
138            do {
139                e = (hot > 0 && k < 3 && (int) (rng() % 4) != 0) ? (int) (rng() % (unsigned) hot) : any(rng);
140                dup = false;
141                for (int j = 0; j < k; ++j) dup |= ids[(size_t) t * K + j] == e;
142            } while (dup);
143            ids[(size_t) t * K + k] = e;
144        }
145    return ids;
146}
147
148struct Routing {
149    std::vector<int32_t> cnt, off, src;   // per expert; sorted row -> token (rows in pair order within an expert)
150    std::vector<int32_t> row_of;          // pair -> sorted row
151};
152Routing sort_rows(const std::vector<int32_t>& ids, int E) {
153    Routing r;
154    r.cnt.assign((size_t) E, 0);
155    for (int32_t e : ids) ++r.cnt[(size_t) e];
156    r.off.assign((size_t) E + 1, 0);
157    for (int e = 0; e < E; ++e) r.off[(size_t) e + 1] = r.off[(size_t) e] + r.cnt[(size_t) e];
158    std::vector<int32_t> fill(r.off.begin(), r.off.end() - 1);
159    r.src.resize(ids.size());
160    r.row_of.resize(ids.size());
161    for (size_t i = 0; i < ids.size(); ++i) {
162        const int32_t p = fill[(size_t) ids[i]]++;
163        r.row_of[i] = p;
164        r.src[(size_t) p] = (int32_t) (i / K);
165    }
166    return r;
167}
168
169// MMQ's row table (the identity ids) is read past its end by llama.cpp's mul_mat_q and its stream-k fixup (a whole J-column tile from an expert's first row, J up
170// to 128): the table takes mmq_ids_table_rows(rows, max_rows) entries, max_rows <= the tokens of the layer (an expert takes at most one row per token).  An exact
171// table of rows * 4 = 64 KB ended a cudaMalloc chunk and faulted in compute-sanitizer's and the plain run (z440-20261111-2224-d478: 311 invalid reads of size 4 in
172// mul_mat_q<Q8_0, 96>, 29 to 57+ bytes after the 65,536-byte allocation).
173size_t ids_table_rows(int64_t rows) { return (size_t) mmq::mmq_ids_table_rows((uint64_t) rows, (uint64_t) (rows / K)); }
174
175// MMQ, as prefill.cpp runs a native layer: per group of 16 routed experts a gather, gate/up, SwiGLU (gate rows, then up rows), q8_1 of H,
176// down.  Returns Dm [rows][N] in sorted-row order.
177struct MmqBufs {
178    Dev xq, gu, h, hq, dm, ident, bounds, grp_gu, grp_d;
179    MmqBufs(const Pair& p, int64_t rows, int E)
180        : xq(mmq::q8_bytes(rows, N)), gu((size_t) rows * FF2 * 4), h((size_t) rows * FF * 4),
181          hq(mmq::q8_bytes(rows, FF)), dm((size_t) rows * N * 4), ident(ids_table_rows(rows) * 4),   // (the margin llama.cpp's kernels read past the table: see ids_table_rows)
182          bounds((size_t) (2 * (E + E / GROUP + 2)) * 4), grp_gu(GROUP * mmq::matrix_bytes(p.gu, FF2, N) + 4096),
183          grp_d(GROUP * mmq::matrix_bytes(p.d, N, FF) + 4096) {}
184};
185void run_mmq(const Pair& p, const Geo& geo, mmq::Context& ctx, MmqBufs& b, const Routing& r, const float* x_dev,
186             const int32_t* src_dev, const std::vector<const uint8_t*>& blob, int64_t rows, cudaStream_t s) {
187    const size_t gub = mmq::matrix_bytes(p.gu, FF2, N), db = mmq::matrix_bytes(p.d, N, FF);
188    const int E = (int) r.cnt.size();
189    std::vector<int32_t> order;
190    for (int e = 0; e < E; ++e) if (r.cnt[(size_t) e] > 0) order.push_back(e);
191    const size_t n = order.size(), ng = (n + GROUP - 1) / GROUP;
192    std::vector<int32_t> bh(n + 1 + ng * (GROUP + 1));
193    for (size_t j = 0; j < n; ++j) bh[j] = r.off[(size_t) order[j]];
194    bh[n] = (int32_t) rows;
195    for (size_t g = 0; g < ng; ++g)
196        for (size_t i = 0; i <= GROUP; ++i)
197            bh[n + 1 + g * (GROUP + 1) + i] = bh[std::min(n, g * GROUP + i)] - bh[g * GROUP];
198    ck(cudaMemcpyAsync(b.bounds.p, bh.data(), bh.size() * 4, cudaMemcpyHostToDevice, s), "bounds");
199    mmq::iota(b.ident.as<int32_t>(), (int64_t) ids_table_rows(rows), s);
200    mmq::quantize(x_dev, src_dev, b.xq.p, (int) p.gu, N, N, rows, s);
201    for (size_t j = 0; j < n; ++j) {
202        const size_t q = j % GROUP;
203        const uint8_t* bl = blob[(size_t) order[j]];
204        mmq::gather_native(bl, bl + geo.up_off, gub / 2, bl + geo.down_off, db, b.grp_gu.as<uint8_t>() + q * gub,
205                           b.grp_d.as<uint8_t>() + q * db, s);
206        if (q + 1 < GROUP && j + 1 < n) continue;
207        const size_t j0 = j - q, g = j0 / GROUP;
208        const int ngx = (int) (q + 1);
209        const int64_t r0 = bh[j0], nr = bh[j + 1] - r0;
210        int64_t maxr = 0;
211        for (size_t i = j0; i <= j; ++i) maxr = std::max<int64_t>(maxr, r.cnt[(size_t) order[i]]);
212        ck(cudaMemsetAsync(b.grp_gu.as<uint8_t>() + (size_t) ngx * gub, 0, 4096, s), "tail");
213        ck(cudaMemsetAsync(b.grp_d.as<uint8_t>() + (size_t) ngx * db, 0, 4096, s), "tail");
214        mmq::Product gu;
215        gu.w = b.grp_gu.p; gu.type = (int) p.gu; gu.w_rows = FF2; gu.w_cols = N;
216        gu.expert_bytes = gub;
217        gu.n = ngx; gu.xq = b.xq.p; gu.bounds = b.bounds.as<int32_t>() + j0; gu.ids = b.ident.as<int32_t>();
218        gu.total_rows = rows; gu.max_rows = maxr; gu.dst = b.gu.as<float>(); gu.ld_dst = FF2;
219        ctx.run(gu, s);
220        mmq::swiglu(b.gu.as<float>() + r0 * FF2, b.h.as<float>() + r0 * FF, nr, FF, false, s);
221        mmq::quantize(b.h.as<float>() + r0 * FF, nullptr, b.hq.p, (int) p.d, FF, FF, nr, s);
222        mmq::Product dn;
223        dn.w = b.grp_d.p; dn.type = (int) p.d; dn.w_rows = N; dn.w_cols = FF;
224        dn.expert_bytes = db;
225        dn.n = ngx; dn.xq = b.hq.p; dn.bounds = b.bounds.as<int32_t>() + n + 1 + g * (GROUP + 1);
226        dn.ids = b.ident.as<int32_t>(); dn.total_rows = nr; dn.max_rows = maxr; dn.dst = b.dm.as<float>() + r0 * N;
227        dn.ld_dst = N;
228        ctx.run(dn, s);
229    }
230}
231
232// the fused path: quantize, group on the device, then launches over expert ranges `cuts` (e.g. {0, 20, 64})
233struct FusedBufs {
234    Dev xa, ha, dm, scratch, slot, src, ids;
235    FusedBufs(int T, int64_t rows, int E)
236        : xa(fused::act_bytes(T, N)), ha(fused::act_bytes(rows, FF)), dm((size_t) rows * N * 4),
237          scratch(fused::group_bytes(rows, E)), slot((size_t) rows * 4), src((size_t) rows * 4),
238          ids((size_t) rows * 4) {}
239};
240void run_fused(const Pair& p, const Geo& geo, FusedBufs& b, const float* x_dev, int T, int E,
241               const std::vector<int>& cuts, const std::vector<const uint8_t*>& blob, cudaStream_t s) {
242    const int64_t rows = (int64_t) T * K;
243    const fq::NativeGeom ng = geo.native(p);
244    fq::quantize_act_native(x_dev, T, N, b.xa.p, s);
245    fused::group(b.ids.as<int32_t>(), rows, K, E, b.scratch.p, b.slot.as<int32_t>(), b.src.as<int32_t>(), s);
246    for (size_t c = 0; c + 1 < cuts.size(); ++c) {
247        for (int e0 = cuts[c]; e0 < cuts[c + 1]; e0 += fq::kQ36MaxBatch) {
248            fq::Batch bt;
249            bt.e0 = e0;
250            bt.e1 = std::min(cuts[c + 1], e0 + fq::kQ36MaxBatch);
251            for (int e = bt.e0; e < bt.e1; ++e) bt.blob[e - bt.e0] = blob[(size_t) e];
252            fq::experts_native_ext(bt, ng, E, rows, b.scratch.p, b.xa.p, b.src.as<int32_t>(), b.ha.p, b.dm.as<float>(), s);
253        }
254    }
255}
256
257struct Err {
258    double rms = 0, worst = 0;   // RMS error / RMS of the reference; the worst row's max |error| / its max |ref|
259};
260// y_a[row_a(i)] against y_b[row_b(i)] for every pair i (rows of N values)
261template <typename RA, typename RB>
262Err compare(const std::vector<float>& a, RA row_a, const std::vector<float>& b, RB row_b, size_t pairs) {
263    double e2 = 0, r2 = 0;
264    Err out;
265    for (size_t i = 0; i < pairs; ++i) {
266        const float* ya = a.data() + (size_t) row_a(i) * N;
267        const float* yb = b.data() + (size_t) row_b(i) * N;
268        double me = 0, mr = 0;
269        for (int o = 0; o < N; ++o) {
270            if (!std::isfinite(ya[o])) throw std::runtime_error("a non-finite output");
271            const double d = (double) ya[o] - yb[o];
272            e2 += d * d;
273            r2 += (double) yb[o] * yb[o];
274            me = std::max(me, std::fabs(d));
275            mr = std::max(mr, (double) std::fabs(yb[o]));
276        }
277        if (mr > 0) out.worst = std::max(out.worst, me / mr);
278        else if (me > 0) out.worst = 1e30;   // a zero row must stay exactly zero
279    }
280    out.rms = r2 > 0 ? std::sqrt(e2 / r2) : 0;
281    return out;
282}
283
284// the kernels' int8 rounding per 32 values (quant_act_nat_kernel / the H epilogue), as floats: codes * (amax / 127)
285void quant32(const float* in, float* out, int n) {
286    for (int b = 0; b < n; b += 32) {
287        float am = 0.0f;
288        for (int j = 0; j < 32; ++j) am = std::max(am, std::fabs(in[b + j]));
289        const float inv = am > 0.0f ? 127.0f / am : 0.0f, d = am / 127.0f;
290        for (int j = 0; j < 32; ++j) out[b + j] = (float) std::nearbyint(in[b + j] * inv) * d;
291    }
292}
293
294std::vector<float> download(const Dev& d, size_t n) {
295    std::vector<float> h(n);
296    ck(cudaMemcpy(h.data(), d.p, n * 4, cudaMemcpyDeviceToHost), "download");
297    return h;
298}
299std::vector<int32_t> download_i(const Dev& d, size_t n) {
300    std::vector<int32_t> h(n);
301    ck(cudaMemcpy(h.data(), d.p, n * 4, cudaMemcpyDeviceToHost), "download");
302    return h;
303}
304
305// The rules (as prefill_fused_iq_test.cpp's, which this test follows):
306//   (a) the fused path against the int8 model (same activation / H rounding, double sums): rel RMS 2e-3, worst row 3e-2, for every pair;
307//   with MMQ for the pair's formats: the fused path's distance to FP32 at most 1.5 x MMQ's (RMS) and 2 x (worst row); a K-quant gate/up
308//   pair (a minimum per 32 values: MMQ takes its minimum term from its own activation sums, 3-5e-3 away from the model) at most 1.15 x and
309//   1.5 x (kKqRms / kKqWorst), and fused against MMQ is information;
310//   without MMQ for the pair (the rule of lane P4-SPLIT's e22f397d0): (b) the model's own distance to FP32 under the ceiling of its class,
311//   (c) the fused path's distance to FP32 at most kOwnRel (RMS) / kOwnRelWorst (worst row) times the model's, plus kOwnAbs.
312// The int8 model's distance to FP32 (rel RMS / worst row) at this shape and with this test's inputs, RTX A4000 sm_86, CUDA 12.9, libstdc++ (11-11, P4-Q36;
313// MMQ sits at the same numbers to 3 digits):
314//   Q6_K + Q8_0, reference part 256 / 33 / 1 / 130 / 517 tokens: 1.604e-2 / 2.790e-2, 1.580e-2 / 2.491e-2, 1.263e-2 / 2.015e-2, 1.619e-2 / 2.835e-2, 1.611e-2 / 3.013e-2;
315//     96-pair samples at 2048 / 8192 tokens: 1.634e-2 / 2.319e-2, 1.612e-2 / 2.320e-2
316//   Q8_0 / Q8_0, same shapes: 1.589e-2 / 2.617e-2, 1.597e-2 / 2.528e-2, 1.532e-2 / 1.891e-2, 1.582e-2 / 2.633e-2, 1.592e-2 / 3.007e-2; samples 1.590e-2 / 2.418e-2, 1.623e-2 / 2.489e-2
317// The ceilings below are the dense ceilings of prefill_fused_iq_test.cpp (P4-SPLIT e22f397d0: 2.5e-2 / 5.0e-2): 1.53x and 1.66x of the largest measured here.  The K-quant
318// ceiling is that test's too and is checked when the K-quant-down pairs join (item C).
319constexpr double kKqRms = 1.15, kKqWorst = 1.5;
320bool kq_gu(const Pair& p) { return p.gu == GGML_TYPE_Q4_K || p.gu == GGML_TYPE_Q5_K; }
321constexpr double kOwnRel = 1.15, kOwnRelWorst = 1.5, kOwnAbs = 1e-3;
322struct Ceiling {
323    double rms, worst;
324};
325constexpr Ceiling kCeilDense{2.5e-2, 5.0e-2}, kCeilKq{6.0e-2, 3.5e-1};
326Ceiling model_ceiling(const Pair& p, bool) { return kq_gu(p) ? kCeilKq : kCeilDense; }
327void judge(const Pair& p, const Err& e2, const Err& ev, const Err& ef, const Err& em, bool mq, bool sample) {
328    const std::string where = sample ? " (timing)" : "";
329    if (e2.rms > 2e-3 || e2.worst > 3e-2)
330        throw std::runtime_error(std::string(p.name) + ": the fused path differs from its own arithmetic's model" + where);
331    if (!mq) {
332        const Ceiling c = model_ceiling(p, sample);
333        if (ev.rms > c.rms || ev.worst > c.worst)
334            throw std::runtime_error(std::string(p.name) + ": the int8-rounded model is further from FP32 than the ceiling of its class" + where);
335        if (ef.rms > kOwnRel * ev.rms + kOwnAbs || ef.worst > kOwnRelWorst * ev.worst + kOwnAbs)
336            throw std::runtime_error(std::string(p.name) + ": the fused path is further from FP32 than the int8-rounded model" + where);
337        return;
338    }
339    if (kq_gu(p)) {
340        if (ef.rms > kKqRms * em.rms || ef.worst > kKqWorst * em.worst)
341            throw std::runtime_error(std::string(p.name) + ": the fused path is further from the reference than MMQ (K-quant rule)" + where);
342        return;
343    }
344    if (ef.rms > 1.5 * em.rms || ef.worst > 2.0 * em.worst)
345        throw std::runtime_error(std::string(p.name) + ": the fused path's error is not comparable to MMQ's" + where);
346}
347
348// one expert's reference for one pair of (token row xr): FP32 (ref) and the int8 model (ref2), `out` N values each
349struct RefWork {
350    std::vector<float> gu, dn, h, h2, hq, xq;
351    RefWork() : h(FF), h2(FF), hq(FF), xq(N) {}
352    void run(const std::vector<float>& gu_w, const std::vector<float>& dn_w, const float* xr, float* ref, float* ref2) {
353        for (int f = 0; f < FF; ++f) {
354            double gt = 0, up = 0;
355            const float *wg = gu_w.data() + (size_t) f * N, *wu = gu_w.data() + (size_t) (FF + f) * N;
356            for (int k = 0; k < N; ++k) { gt += (double) wg[k] * xr[k]; up += (double) wu[k] * xr[k]; }
357            h[(size_t) f] = (float) (gt / (1.0 + std::exp(-gt)) * up);
358        }
359        for (int o = 0; o < N; ++o) {
360            double a = 0;
361            const float* wd = dn_w.data() + (size_t) o * FF;
362            for (int f = 0; f < FF; ++f) a += (double) wd[f] * h[(size_t) f];
363            ref[o] = (float) a;
364        }
365        quant32(xr, xq.data(), N);
366        for (int f = 0; f < FF; ++f) {
367            double gt = 0, up = 0;
368            const float *wg = gu_w.data() + (size_t) f * N, *wu = gu_w.data() + (size_t) (FF + f) * N;
369            for (int k = 0; k < N; ++k) { gt += (double) wg[k] * xq[(size_t) k]; up += (double) wu[k] * xq[(size_t) k]; }
370            h2[(size_t) f] = (float) (gt / (1.0 + std::exp(-gt)) * up);
371        }
372        quant32(h2.data(), hq.data(), FF);
373        for (int o = 0; o < N; ++o) {
374            double a = 0;
375            const float* wd = dn_w.data() + (size_t) o * FF;
376            for (int f = 0; f < FF; ++f) a += (double) wd[f] * hq[(size_t) f];
377            ref2[o] = (float) a;
378        }
379    }
380};
381
382// part 1: against the double-precision reference
383void reference_part(const Pair& p, cudaStream_t s, int T = 256, int E = 64, int ZERO = 77) {
384    const Geo geo(p);
385    std::mt19937 rng(136 + (unsigned) p.gu * 7 + (unsigned) p.d + (unsigned) T);
386    std::vector<std::vector<uint8_t>> host((size_t) E);
387    std::vector<std::unique_ptr<Dev>> dev;
388    std::vector<const uint8_t*> blob((size_t) E);
389    for (int e = 0; e < E; ++e) {
390        host[(size_t) e] = make_blob(p, geo, rng);
391        dev.push_back(std::make_unique<Dev>(geo.bytes + 4096 * (size_t) (e % 3) + 64));   // unrelated addresses
392        uint8_t* q = dev.back()->as<uint8_t>() + 256 * (size_t) (e % 3) + 2 * (size_t) (e % 2);   // 2-byte aligned
393        ck(cudaMemcpy(q, host[(size_t) e].data(), geo.bytes, cudaMemcpyHostToDevice), "blob");
394        blob[(size_t) e] = q;
395    }
396    std::vector<float> x = make_x(T, rng, ZERO);
397    const std::vector<int32_t> ids = make_ids(T, E, rng, 2, 4);   // experts 0, 1 hot (several tiles), the last 4 unused
398    const int64_t rows = (int64_t) T * K;
399    const Routing r = sort_rows(ids, E);
400    std::printf("%s - reference part: %d tokens, %d experts, rows per expert: max %d, experts without rows %d\n", p.name,
401                T, E, *std::max_element(r.cnt.begin(), r.cnt.end()), (int) std::count(r.cnt.begin(), r.cnt.end(), 0));
402
403    Dev x_dev(x.size() * 4), src_dev((size_t) rows * 4);
404    ck(cudaMemcpy(x_dev.p, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "x");
405    ck(cudaMemcpy(src_dev.p, r.src.data(), r.src.size() * 4, cudaMemcpyHostToDevice), "src");
406    ck(cudaDeviceSynchronize(), "uploads");
407    const bool mq = mmq_ok(p);
408    mmq::Context ctx;
409    MmqBufs* mbp = mq ? new MmqBufs(p, rows, E) : nullptr;
410    if (mq) run_mmq(p, geo, ctx, *mbp, r, x_dev.as<float>(), src_dev.as<int32_t>(), blob, rows, s);
411    FusedBufs fb(T, rows, E);
412    ck(cudaMemcpy(fb.ids.p, ids.data(), ids.size() * 4, cudaMemcpyHostToDevice), "ids");
413    ck(cudaMemset(fb.dm.p, 0xff, (size_t) rows * N * 4), "sentinel");   // an unwritten row is NaN
414    ck(cudaDeviceSynchronize(), "uploads");
415    run_fused(p, geo, fb, x_dev.as<float>(), T, E, {0, 1, std::min(20, E - 1), E}, blob, s);
416    ck(cudaStreamSynchronize(s), "sync");
417    const std::vector<float> y_mmq = mq ? download(mbp->dm, (size_t) rows * N) : std::vector<float>((size_t) rows * N, 0.0f),
418                             y_f = download(fb.dm, (size_t) rows * N);
419    delete mbp;
420    const std::vector<int32_t> slot = download_i(fb.slot, (size_t) rows), fsrc = download_i(fb.src, (size_t) rows);
421    for (int64_t i = 0; i < rows; ++i)
422        if (fsrc[(size_t) slot[(size_t) i]] != (int32_t) (i / K)) throw std::runtime_error("group: slot/src disagree");
423
424    // the reference, an expert at a time on all cores
425    std::vector<float> ref((size_t) rows * N), ref2((size_t) rows * N);
426    std::vector<std::thread> th;
427    const int nth = std::max(1, std::min(16, (int) std::thread::hardware_concurrency()));
428    for (int w = 0; w < nth; ++w)
429        th.emplace_back([&, w] {
430            std::vector<float> gu, dn;
431            RefWork rw;
432            for (int e = w; e < E; e += nth) {
433                if (r.cnt[(size_t) e] == 0) continue;
434                dequant(p, geo, host[(size_t) e], gu, dn);
435                for (int64_t i = 0; i < rows; ++i)
436                    if (ids[(size_t) i] == e) rw.run(gu, dn, x.data() + (size_t) (i / K) * N, ref.data() + (size_t) i * N, ref2.data() + (size_t) i * N);
437            }
438        });
439    for (auto& t : th) t.join();
440
441    auto pair = [](size_t i) { return (int64_t) i; };
442    auto mrow = [&](size_t i) { return (int64_t) r.row_of[i]; };
443    auto frow = [&](size_t i) { return (int64_t) slot[i]; };
444    const Err em = mq ? compare(y_mmq, mrow, ref, pair, (size_t) rows) : Err{};
445    const Err ef = compare(y_f, frow, ref, pair, (size_t) rows);
446    const Err efm = mq ? compare(y_f, frow, y_mmq, mrow, (size_t) rows) : Err{};
447    const Err e2 = compare(y_f, frow, ref2, pair, (size_t) rows);
448    const Err ev = compare(ref2, pair, ref, pair, (size_t) rows);
449    std::printf("  fused vs the int8-rounded model: rel RMS %.3e  worst %.3e;  the model vs FP32: rel RMS %.3e  worst %.3e\n", e2.rms, e2.worst, ev.rms, ev.worst);
450    if (mq) std::printf("  MMQ   vs FP32 reference: rel RMS %.3e  worst row max rel %.3e\n", em.rms, em.worst);
451    std::printf("  fused vs FP32 reference: rel RMS %.3e  worst row max rel %.3e\n", ef.rms, ef.worst);
452    if (mq) std::printf("  fused vs MMQ           : rel RMS %.3e  worst row max rel %.3e\n", efm.rms, efm.worst);
453    double zmax = 0;
454    for (int k = 0; k < K && ZERO >= 0; ++k)
455        for (int o = 0; o < N; ++o)
456            zmax = std::max(zmax, (double) std::fabs(y_f[(size_t) slot[(size_t) (ZERO * K + k)] * N + o]));
457    if (zmax != 0) throw std::runtime_error(std::string(p.name) + ": the all-zero token's outputs are not zero");
458    judge(p, e2, ev, ef, em, mq, false);
459}
460
461// part 2: one layer at a real chunk, timed
462void timing_part(const Pair& p, int T, cudaStream_t s) {
463    const int E = NEXP;
464    const Geo geo(p);
465    std::mt19937 rng(1360);
466    const int64_t rows = (int64_t) T * K;
467    // 256 distinct blobs at a stride of whole blocks of both formats (MMQ's expert stride counts blocks)
468    size_t unit = ggml_type_size(p.gu);
469    while (unit % ggml_type_size(p.d) != 0 || unit % 16 != 0) unit += ggml_type_size(p.gu);
470    const size_t stride = (geo.bytes + unit - 1) / unit * unit;
471    Dev blobs((size_t) E * stride + 4096);
472    ck(cudaMemset(blobs.p, 0, (size_t) E * stride + 4096), "zero");
473    {
474        std::vector<uint8_t> b = make_blob(p, geo, rng);
475        for (int e = 0; e < E; ++e) {
476            b[4 + (size_t) (e % 16)] ^= (uint8_t) e;   // not all equal (inside the first block, not its scale)
477            ck(cudaMemcpy(blobs.as<uint8_t>() + (size_t) e * stride, b.data(), geo.bytes, cudaMemcpyHostToDevice), "blob");
478        }
479    }
480    std::vector<const uint8_t*> blob((size_t) E);
481    for (int e = 0; e < E; ++e) blob[(size_t) e] = blobs.as<uint8_t>() + (size_t) e * stride;
482    // --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
483    // check of the launch fails for the launches that hold one, which then take the unstaged 64-row kernel (no process exit); the output bits must equal the all-device run's
484    struct HostBlobs {
485        void* p = nullptr;
486        ~HostBlobs() { if (p) cudaFreeHost(p); }
487    } host_blobs;
488    if (g_host_blobs > 0) {
489        const int nh = std::min(g_host_blobs, E);
490        ck(cudaHostAlloc(&host_blobs.p, (size_t) nh * stride + 4096, cudaHostAllocMapped), "cudaHostAlloc");
491        std::memset(host_blobs.p, 0, (size_t) nh * stride + 4096);
492        for (int e = 0; e < nh; ++e) {
493            uint8_t* dst = (uint8_t*) host_blobs.p + (size_t) e * stride;
494            ck(cudaMemcpy(dst, blob[(size_t) e], geo.bytes, cudaMemcpyDeviceToHost), "blob to host");
495            blob[(size_t) e] = dst;
496        }
497    }
498    std::vector<float> x = make_x(T, rng, -1);
499    const std::vector<int32_t> ids = make_ids(T, E, rng, 0, 0);
500    const Routing r = sort_rows(ids, E);
501    Dev x_dev(x.size() * 4), src_dev((size_t) rows * 4);
502    ck(cudaMemcpy(x_dev.p, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "x");
503    ck(cudaMemcpy(src_dev.p, r.src.data(), r.src.size() * 4, cudaMemcpyHostToDevice), "src");
504    const bool mq = mmq_ok(p) && g_host_blobs == 0;   // (MMQ does not read host blobs)
505    mmq::Context ctx;
506    MmqBufs* mbp = mq ? new MmqBufs(p, rows, E) : nullptr;
507    FusedBufs fb(T, rows, E);
508    ck(cudaMemcpy(fb.ids.p, ids.data(), ids.size() * 4, cudaMemcpyHostToDevice), "ids");
509    ck(cudaDeviceSynchronize(), "uploads");
510    cudaEvent_t a, b;
511    ck(cudaEventCreate(&a), "event");
512    ck(cudaEventCreate(&b), "event");
513    auto once = [&](auto&& f) {
514        ck(cudaEventRecord(a, s), "record");
515        f();
516        ck(cudaEventRecord(b, s), "record");
517        ck(cudaEventSynchronize(b), "sync");
518        float t = 0;
519        ck(cudaEventElapsedTime(&t, a, b), "elapsed");
520        return t;
521    };
522    auto mmq_run = [&] { run_mmq(p, geo, ctx, *mbp, r, x_dev.as<float>(), src_dev.as<int32_t>(), blob, rows, s); };
523    auto fused_run = [&] { run_fused(p, geo, fb, x_dev.as<float>(), T, E, {0, E}, blob, s); };
524    // ~1 s of both first (the clocks ramp up), then alternating rounds; the medians
525    for (float spent = 0; spent < 1000.0f;) spent += (mq ? once(mmq_run) : 0.0f) + once(fused_run);
526    std::vector<float> tm, tf;
527    for (int rep = 0; rep < 8; ++rep) {
528        tm.push_back(mq ? once(mmq_run) : 1.0f);
529        tf.push_back(once(fused_run));
530    }
531    std::sort(tm.begin(), tm.end());
532    std::sort(tf.begin(), tf.end());
533    const float t_mmq = tm[tm.size() / 2], t_f = tf[tf.size() / 2];
534    const std::vector<float> y_mmq = mq ? download(mbp->dm, (size_t) rows * N) : std::vector<float>((size_t) rows * N, 0.0f),
535                             y_f = download(fb.dm, (size_t) rows * N);
536    const std::vector<int32_t> slot = download_i(fb.slot, (size_t) rows);
537    const Err efm = mq ? compare(y_f, [&](size_t i) { return (int64_t) slot[i]; }, y_mmq, [&](size_t i) { return (int64_t) r.row_of[i]; }, (size_t) rows) : Err{};
538    {   // a hash of the fused output's bits (pair order: the rows of an expert are placed in any order), to compare two builds or two tile choices bit for bit
539        uint64_t hsh = 1469598103934665603ull;
540        for (size_t i = 0; i < (size_t) rows; ++i)
541            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; }
542        std::printf("  fused output bits hash %016llx\n", (unsigned long long) hsh);
543    }
544    if (mq)
545        std::printf("%s - timing part: %d tokens x top %d over %d experts, one layer: MMQ path %.3f ms (min %.3f), fused %.3f ms (min %.3f) (%.2fx); fused vs MMQ rel RMS %.3e worst row %.3e\n",
546                    p.name, T, K, E, t_mmq, tm[0], t_f, tf[0], t_mmq / t_f, efm.rms, efm.worst);
547    else
548        std::printf("%s - timing part: %d tokens x top %d over %d experts, one layer: fused %.3f ms (min %.3f); no MMQ for this pair\n", p.name, T, K, E, t_f, tf[0]);
549    {   // the grouping: every pair in its expert's rows (the near-identical blobs here would hide a wrong expert)
550        const std::vector<int32_t> fsrc = download_i(fb.src, (size_t) rows);
551        int64_t bad = 0, bad_src = 0;
552        for (size_t i = 0; i < (size_t) rows; ++i) {
553            const int e = ids[i];
554            bad += slot[i] < r.off[(size_t) e] || slot[i] >= r.off[(size_t) e + 1];
555            bad_src += fsrc[(size_t) slot[i]] != (int32_t) (i / K);
556        }
557        if (bad || bad_src) throw std::runtime_error(std::string(p.name) + ": the grouping is wrong");
558    }
559    // the fused path against the double-precision reference on a sample of 96 pairs
560    {
561        std::vector<size_t> pick;
562        for (size_t i = 0; i < 96; ++i) pick.push_back((i * 2654435761u) % (size_t) rows);
563        std::vector<float> ref(pick.size() * N), ref2(pick.size() * N), ym(pick.size() * N), yf(pick.size() * N);
564        std::vector<uint8_t> hb(geo.bytes);
565        std::vector<float> gu, dn;
566        RefWork rw;
567        for (size_t j = 0; j < pick.size(); ++j) {
568            const size_t i = pick[j];
569            ck(cudaMemcpy(hb.data(), blob[(size_t) ids[i]], geo.bytes, cudaMemcpyDefault), "blob back");   // (default kind: a --host-blobs blob is host memory)
570            dequant(p, geo, hb, gu, dn);
571            rw.run(gu, dn, x.data() + (i / K) * N, ref.data() + j * N, ref2.data() + j * N);
572            if (mq) std::copy_n(y_mmq.begin() + (ptrdiff_t) ((size_t) r.row_of[i] * N), N, ym.begin() + (ptrdiff_t) (j * N));
573            std::copy_n(y_f.begin() + (ptrdiff_t) ((size_t) slot[i] * N), N, yf.begin() + (ptrdiff_t) (j * N));
574        }
575        auto id = [](size_t j) { return (int64_t) j; };
576        const Err em = mq ? compare(ym, id, ref, id, pick.size()) : Err{}, ef = compare(yf, id, ref, id, pick.size());
577        const Err e2 = compare(yf, id, ref2, id, pick.size()), ev = compare(ref2, id, ref, id, pick.size());
578        std::printf("  sample of %zu pairs vs FP32 reference: MMQ rel RMS %.3e worst %.3e, fused rel RMS %.3e worst %.3e; fused vs the int8 model %.3e / %.3e; the model vs FP32 %.3e / %.3e\n",
579                    pick.size(), em.rms, em.worst, ef.rms, ef.worst, e2.rms, e2.worst, ev.rms, ev.worst);
580        judge(p, e2, ev, ef, em, mq, true);
581    }
582    cudaEventDestroy(a);
583    cudaEventDestroy(b);
584    delete mbp;
585    if (g_host_blobs > 0) {
586        const int fbk = fq::staged_blob_fallbacks();
587        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);
588        if (g_expect_fallback > 0 && fbk == 0) throw std::runtime_error(std::string(p.name) + ": --expect-fallback: no launch took the unstaged kernel");
589        if (g_expect_fallback < 0 && fbk != 0) throw std::runtime_error(std::string(p.name) + ": --expect-no-fallback: a launch took the unstaged kernel");
590    }
591    // the two int8 paths at the real shape, every tile of the layer (K-quant gate/up pairs: fused against MMQ is information only, see kq_gu)
592    if (mq && !kq_gu(p) && (efm.rms > 1e-3 || efm.worst > 2e-2))
593        throw std::runtime_error(std::string(p.name) + ": the paths disagree at the real shape");
594}
595}  // namespace
596
597int main(int argc, char** argv) {
598    try {
599        // the formats the Qwen3.6 engine sets up for itself (src/qwen35/q36_engine.cu, main): the K-quant, Q6_K and Q8_0 gate/up kernels
600#ifdef _WIN32
601        _putenv_s("STRATA_PF_FUSED", "1");
602#else
603        setenv("STRATA_PF_FUSED", "1", 1);
604        setenv("STRATA_PF_FUSED_KQ", "1", 1);
605        setenv("STRATA_PF_FUSED_Q6K", "1", 1);
606        setenv("STRATA_PF_FUSED_Q8GU", "1", 1);
607        setenv("STRATA_MMQ_KQ", "1", 1);
608#endif
609        int n = 0;
610        if (cudaGetDeviceCount(&n) != cudaSuccess || n == 0) { std::printf("no CUDA device: skipped\n"); return 77; }
611#if defined(__HIPCC__) || defined(__HIP_PLATFORM_AMD__)
612        {   // HIP: the Qwen3.6 copy's kernels are gfx12's (native_w11_kernel); another AMD card skips
613            cudaDeviceProp prop{};
614            if (cudaGetDeviceProperties(&prop, 0) != cudaSuccess || std::strncmp(prop.gcnArchName, "gfx12", 5) != 0) {
615                std::printf("the Qwen3.6 fused kernels on HIP are gfx12's (%s: skipped)\n", prop.gcnArchName);
616                return 77;
617            }
618        }
619#else
620        int major = 0;
621        cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, 0);
622        if (major < 8) { std::printf("the fused kernels need sm_80 or newer: skipped\n"); return 77; }
623#endif
624        if (!mmq::built()) std::printf("no MMQ in this build: the pairs are judged by the no-MMQ rule (the int8 model and its ceiling)\n");
625        const std::vector<Pair> pairs = {
626            // UD-Q6_K_XL: 40 layers Q6_K / Q8_0 and one Q8_0 / Q8_0; the Q8_0 file: Q8_0 / Q8_0 on all 41
627            {GGML_TYPE_Q6_K, GGML_TYPE_Q8_0, "Q6_K + Q8_0"},
628            {GGML_TYPE_Q8_0, GGML_TYPE_Q8_0, "Q8_0 / Q8_0"},
629            // UD-Q4_K_XL: Q4_K gate/up with a Q5_K down on 38 layers, Q4_K / Q6_K on 2, Q5_K / Q6_K on 1 (K-quant downs: K = 512 is two 256-value super-blocks)
630            {GGML_TYPE_Q4_K, GGML_TYPE_Q5_K, "Q4_K / Q5_K", true},
631            {GGML_TYPE_Q4_K, GGML_TYPE_Q6_K, "Q4_K / Q6_K", true},
632            {GGML_TYPE_Q5_K, GGML_TYPE_Q6_K, "Q5_K / Q6_K", true},
633            {GGML_TYPE_Q5_K, GGML_TYPE_Q5_K, "Q5_K / Q5_K", true}};
634        const char* only = nullptr;   // --only=NAME: the pairs whose name contains NAME
635        bool timing = true, ref = true;
636        std::vector<int> chunks = {2048, 8192};   // --chunks=A,B: the timing part's chunk sizes
637        for (int i = 1; i < argc; ++i) {
638            if (std::strncmp(argv[i], "--only=", 7) == 0) only = argv[i] + 7;
639            if (std::strcmp(argv[i], "--no-timing") == 0) timing = false;
640            if (std::strcmp(argv[i], "--no-ref") == 0) ref = false;
641            if (std::strncmp(argv[i], "--host-blobs=", 13) == 0) g_host_blobs = std::atoi(argv[i] + 13);
642            if (std::strcmp(argv[i], "--expect-fallback") == 0) g_expect_fallback = 1;
643            if (std::strcmp(argv[i], "--expect-no-fallback") == 0) g_expect_fallback = -1;
644            if (std::strncmp(argv[i], "--chunks=", 9) == 0) {
645                chunks.clear();
646                for (const char* c = argv[i] + 9; *c;) {
647                    chunks.push_back(std::atoi(c));
648                    while (*c && *c != ',') ++c;
649                    if (*c == ',') ++c;
650                }
651            }
652        }
653        cudaStream_t s = nullptr;
654        ck(cudaStreamCreateWithFlags(&s, cudaStreamNonBlocking), "stream");
655        for (const Pair& p : pairs) {
656            if (only && std::string(p.name).find(only) == std::string::npos) continue;
657            if (!fq::native_supported_ext((int) p.gu, (int) p.d)) {
658                if (p.optional) { std::printf("%s: not covered by this build of the Qwen3.6 kernels (skipped)\n", p.name); continue; }
659                throw std::runtime_error(std::string(p.name) + ": not covered by the Qwen3.6 copy of the kernels");
660            }
661            if (ref) {
662                reference_part(p, s);
663                // the tails and tile edges: a handful of tokens, one token, 130 and 517 tokens (the counts follow the routing)
664                reference_part(p, s, 33, 16, 5);
665                reference_part(p, s, 1, 16, -1);
666                reference_part(p, s, 130, 32, 77);
667                reference_part(p, s, 517, 32, 300);
668            }
669            if (timing)
670                for (int T : chunks) timing_part(p, T, s);
671        }
672        ck(cudaStreamDestroy(s), "destroy");
673        std::printf("prefill fused MoE (Qwen3.6 shape) parity passed\n");
674        return 0;
675    } catch (const std::exception& e) {
676        std::fprintf(stderr, "prefill fused MoE (Qwen3.6 shape) parity failed: %s\n", e.what());
677        return 1;
678    }
679}