okami.mom/strata

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

Niko1221Merge f-bw-nvfp4-m17 b933674ed into the batch 19 candidate (NVFP4 prompt experts on the int8 kernels, the bench's NVFP4 row, the staged group entry for NVFP4 layers, the start-up line's NVFP4 count)52d2d3ee2

main
83.0 KiB1400 linesraw
1// prefill_expert_paths_bench - one prompt layer of routed experts, timed on every path the engine can take for it, side by side:
2//   MMQ      llama.cpp's int8 MMQ kernels in prefill.cpp's sequence (gather_native into 16-expert groups, q8_1 of the rows, gate/up, SwiGLU, q8_1 of H, down)
3//            (only in a build that has MMQ; prefill_fused_iq_test.cpp's run_mmq, the same calls)
4//   FP16     the engine's dequantize + FP16 GEMM path, per expert: iq_dequant_gu_f16 + iq_dequant_f16, Gemm::f16 (gate/up), swiglu_interleaved,
5//            Gemm::f16 (down), after one gather_rows16 of the layer's rows.  These are the calls of prefill.cpp's `compute` lambda, FP16 branch
6//            (src/prefill/prefill.cpp, "const int q = (int) (j % DQ); if (lay.native) { ... iq_dequant_gu_f16 ... m.gemm.f16 ... swiglu_interleaved ...
7//            m.gemm.f16 }"), with the engine's two-slot dequantize ring (DQ = 2) and its Gemm set up as Prefill::init sets it (init_external with the
8//            32 MiB workspace, set_f16_io(prompt_f16()), set_act_f16).  Nothing of that sequence is re-implemented here: every call is the library's.
9//   FP16+FR  the same with the few-row experts (fewrows.hpp, STRATA_PF_FEWROWS; the engine's default on a Tesla P100) on the quantized grouped kernels:
10//            an expert with 1..kFewRows rows runs fewrows_record + native_expert_grouped on the GGUF blob instead of the dequantize and the two GEMMs
11//            (prefill.cpp, "if (fr_env) { ... fewrows_takes(...) ... fewrows_record ... native_expert_grouped(...) }")
12//   GRP      the whole layer in one native_expert_grouped call (the grouped decode-family kernels on q8_1 activations): what the Qwen3.6 engine
13//            (q36_engine.cu) runs for a layer with neither fused kernels nor MMQ, and what the verify window uses.  Off unless --grouped or --shape=q36.
14//   FUSED    Strata's own fused int8 kernels (moe_fused_iq.hpp experts_native; at the Qwen3.6 shape the copy moe_fused_iq_q36.cu's experts_native_ext)
15//            where the card has them for the pair.  The opt-in switches that select them (STRATA_PF_FUSED=1, _KQ, _Q50, _Q8D, _Q8GU, _Q6K) are set
16//            when not already set, so the column shows what the kernels do, not what the engine picks by default on this card.
17// No model file is read.  Every path's output is hashed (FNV-1a over the bits, in pair order) and a sample of pairs (default 96) is compared with a
18// CPU FP32 reference (ggml's own to_float of the weights, FP32 activations, double sums): rel RMS and worst row.
19//
20// Synthetic weights are random GGUF blocks with a sane scale (as prefill_fused_iq_test.cpp); 512 / 256 blobs at the engine's stride; routing is K distinct
21// experts per token, uniform (--skew=0, as the timing part of prefill_fused_iq_test.cpp) or Zipf-skewed (--skew=S: expert e has weight (e+1)^-S).
22//
23//   prefill_expert_paths_bench [--shape=flash|q36|N,FF,E,K] [--tokens=2048,4096,8192,20000] [--only=NAME]... [--all] [--list]
24//       [--repeats=7] [--warm-ms=1000] [--skew=S] [--experts=E] [--sample=96] [--seed=N] [--grouped] [--no-mmq] [--no-fused] [--no-fp16] [--no-ref] [--quick]
25//   Exit 0 when it ran, 1 on an error, 77 without a device (ctest skip).  One machine-readable line per cell starts with "RESULT ".
26//
27// What it does not capture of a real run: expert streaming (every expert is resident here), the engine's chunking of a long prompt (one chunk of T tokens),
28// attention / GDN / dense layers, the drafter, the KV cache, and the host-side planning between layers.
29// (a HIP build compiles this file as plain C++ against the compat headers: STRATA_USE_HIP comes with strata_hip_runtime, __HIPCC__ only in .cu / HIP-language files)
30#if defined(__HIPCC__) || defined(STRATA_USE_HIP)
31#define FB_HIP 1
32#endif
33#include "strata/kernels/iq_kernels.hpp"
34#include "strata/prefill/fewrows.hpp"
35#include "strata/prefill/gemm.hpp"
36#include "strata/prefill/kernels.hpp"
37#include "strata/prefill/mmq_ids_margin.hpp"
38#include "strata/prefill/moe_fused_iq.hpp"
39#include "strata/prefill/moe_mmq.hpp"
40#if !defined(FB_HIP)
41#include "strata/prefill/moe_fused_q36.hpp"
42#endif
43
44#include "ggml.h"
45#include "strata/quant/types.hpp"
46#include "../prefill/bench_blob_layout.hpp"
47
48#include <cuda_runtime.h>
49
50#include <algorithm>
51#include <array>
52#include <cmath>
53#include <cstdint>
54#include <cstdio>
55#include <cstdlib>
56#include <cctype>
57#include <cstring>
58#include <fstream>
59#include <functional>
60#include <memory>
61#include <random>
62#include <stdexcept>
63#include <string>
64#include <thread>
65#include <vector>
66
67namespace {
68namespace mmq = strata::prefill::mmq;
69namespace fused = strata::prefill::fused;
70namespace kern = strata::kernels;
71namespace pf = strata::prefill;
72
73constexpr int GROUP = 16;   // MMQ's expert group (prefill.cpp MMQ_GROUP)
74constexpr int DQ = 2;       // the engine's dequantized-expert ring (prefill.cpp DQ)
75constexpr int64_t GEMM_SCRATCH = 32ll << 20;   // prefill.cpp GEMM_SCRATCH / GEMM_WS: the engine's Gemm::init_external sizes
76constexpr size_t GEMM_WS = 32u << 20;
77
78void ck(cudaError_t e, const char* what) {
79    if (e != cudaSuccess) throw std::runtime_error(std::string(what) + ": " + cudaGetErrorString(e));
80}
81
82struct Dev {
83    void* p = nullptr;
84    size_t n = 0;
85    explicit Dev(size_t bytes = 0) : n(bytes) { if (bytes) ck(cudaMalloc(&p, bytes), "cudaMalloc"); }
86    ~Dev() { if (p) cudaFree(p); }
87    Dev(const Dev&) = delete;
88    Dev& operator=(const Dev&) = delete;
89    Dev(Dev&& o) noexcept : p(o.p), n(o.n) { o.p = nullptr; o.n = 0; }
90    Dev& operator=(Dev&& o) noexcept {
91        if (this != &o) { if (p) cudaFree(p); p = o.p; n = o.n; o.p = nullptr; o.n = 0; }
92        return *this;
93    }
94    template <typename T> T* as() const { return (T*) p; }
95};
96
97struct Shape {
98    int N, FF, E, K;
99    std::string name;
100    int FF2() const { return 2 * FF; }
101};
102
103struct Pair {
104    ggml_type gu, d;
105    const char* name;
106};
107
108size_t type_size(ggml_type t) { return ggml_type_size(t); }
109int64_t blck_size(ggml_type t) { return ggml_blck_size(t); }
110size_t row_size(ggml_type t, int64_t n) { return (size_t) (n / blck_size(t)) * type_size(t); }
111bool fits_blocks(ggml_type t, int64_t n) { return n % blck_size(t) == 0; }
112
113// NVFP4 (ModelOpt packs: gate/up and down NVFP4): the blob ends with a 16-byte tail {s_gate, s_up, s_down, 0}, the per-expert weight_scale_2 values
114// (cpu::NativeFmt::tail_off = down_off + d_row n_embd).  Every path applies them as the engine does: MMQ around its products (swiglu_scaled, scale_down_rows),
115// the FP16 path on the dequantized weights (iq_dequant_gu_f16 / iq_dequant_f16's scale), the fused kernels on their FP32 products.
116bool nvfp4_pair(const Pair& p) { return p.gu == GGML_TYPE_NVFP4 && p.d == GGML_TYPE_NVFP4; }
117
118struct Geo {
119    size_t gu_row, d_row, up_off, down_off, bytes;
120    size_t tail_off = 0;   // 0: no tail
121    Geo(const Pair& p, const Shape& s) {
122        gu_row = row_size(p.gu, s.N);
123        d_row = row_size(p.d, s.FF);
124        up_off = gu_row * (size_t) s.FF;
125        down_off = 2 * up_off;
126        bytes = down_off + d_row * (size_t) s.N;
127        if (nvfp4_pair(p)) {
128            tail_off = bytes;
129            bytes += 16;
130        }
131    }
132};
133
134// random blocks with a sane fp16 scale `d` at each block's start (as prefill_fused_iq_test.cpp's fill_matrix), scales chosen so that the weights'
135// typical size is that of a 2-3 bit expert (a few hundredths).  IQ1_M has no leading d: its fp16 scale is spread over the top nibbles of its four
136// 16-bit sub-scales (block_iq1_m: qs[32] qh[16] scales[8]).
137void fill_matrix(uint8_t* m, ggml_type t, int64_t rows, int64_t cols, std::mt19937& rng) {
138    const size_t bs = type_size(t), nb = (size_t) rows * (size_t) (cols / blck_size(t));
139    std::uniform_int_distribution<int> byte(0, 255);
140    const float lo = t == GGML_TYPE_Q4_K || t == GGML_TYPE_Q5_K ? 0.00004f : t == GGML_TYPE_Q5_1 ? 0.0006f
141                   : t == GGML_TYPE_Q8_0 ? 0.0001f : t == GGML_TYPE_IQ3_S ? 0.0004f : t == GGML_TYPE_IQ4_XS ? 0.00005f
142                   : t == GGML_TYPE_IQ4_NL ? 0.0002f : t == GGML_TYPE_Q2_0 ? 0.004f : t == GGML_TYPE_Q6_K ? 0.000005f
143                   : t == GGML_TYPE_IQ1_M ? 0.002f : 0.0008f;
144    std::uniform_real_distribution<float> sc(lo, 6.0f * lo);
145    for (size_t i = 0; i < nb * bs; ++i) m[i] = (uint8_t) byte(rng);
146    if (t == GGML_TYPE_NVFP4) {   // four UE4M3 scale bytes then 32 bytes of codes: scales 0x28..0x58 (finite, bit 7 clear), the codes as drawn
147        std::uniform_int_distribution<int> ub(0x28, 0x58);
148        for (size_t b = 0; b < nb; ++b)
149            for (int k = 0; k < 4; ++k) m[b * bs + (size_t) k] = (uint8_t) ub(rng);
150        return;
151    }
152    for (size_t b = 0; b < nb; ++b) {
153        const ggml_fp16_t h = ggml_fp32_to_fp16(sc(rng));
154        uint8_t* blk = m + b * bs;
155        if (t == GGML_TYPE_IQ1_M) {
156            uint16_t s16[4];
157            std::memcpy(s16, blk + 48, 8);
158            for (int k = 0; k < 4; ++k) s16[k] = (uint16_t) ((s16[k] & 0x0fff) | (((unsigned) h >> (4 * k)) & 0xf) << 12);
159            std::memcpy(blk + 48, s16, 8);
160            continue;
161        }
162        std::memcpy(blk + (t == GGML_TYPE_Q6_K ? 208 : 0), &h, 2);   // (Q6_K keeps d at its end; its 16 int8 scales stay random bytes)
163        if (t == GGML_TYPE_Q4_K || t == GGML_TYPE_Q5_K || t == GGML_TYPE_Q5_1) {   // the minimum's scale, either sign
164            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));
165            std::memcpy(blk + 2, &h2, 2);
166        }
167    }
168}
169std::vector<uint8_t> make_blob(const Pair& p, const Geo& g, const Shape& s, std::mt19937& rng) {
170    std::vector<uint8_t> b(g.bytes);
171    fill_matrix(b.data(), p.gu, 2 * s.FF, s.N, rng);
172    fill_matrix(b.data() + g.down_off, p.d, s.N, s.FF, rng);
173    if (g.tail_off) {   // the per-expert scales, about 1e-4 .. 1e-3
174        std::uniform_real_distribution<float> ss(2e-4f, 2e-3f);
175        const float t[4] = {ss(rng), ss(rng), ss(rng), 0.0f};
176        std::memcpy(b.data() + g.tail_off, t, 16);
177    }
178    return b;
179}
180
181// ggml's dequantized weights of one expert: gate [FF][N], up [FF][N] (rows 0..FF-1 and FF..2FF-1 of gu), down [N][FF]
182void dequant(const Pair& p, const Geo& g, const Shape& s, const std::vector<uint8_t>& b, std::vector<float>& gu, std::vector<float>& dn) {
183    gu.resize((size_t) 2 * s.FF * s.N);
184    dn.resize((size_t) s.N * s.FF);
185    const auto* tg = ggml_get_type_traits(p.gu);
186    const auto* td = ggml_get_type_traits(p.d);
187    for (int r = 0; r < 2 * s.FF; ++r) tg->to_float(b.data() + (size_t) r * g.gu_row, gu.data() + (size_t) r * s.N, s.N);
188    for (int r = 0; r < s.N; ++r) td->to_float(b.data() + g.down_off + (size_t) r * g.d_row, dn.data() + (size_t) r * s.FF, s.FF);
189    if (g.tail_off) {   // NVFP4: each projection times its own per-expert scale
190        float t[4];
191        std::memcpy(t, b.data() + g.tail_off, 16);
192        for (int r = 0; r < s.FF; ++r) for (int k = 0; k < s.N; ++k) gu[(size_t) r * s.N + k] *= t[0];
193        for (int r = s.FF; r < 2 * s.FF; ++r) for (int k = 0; k < s.N; ++k) gu[(size_t) r * s.N + k] *= t[1];
194        for (size_t i = 0; i < dn.size(); ++i) dn[i] *= t[2];
195    }
196}
197
198// activations: N(0, 1) with a few large values (the hidden state has outliers)
199std::vector<float> make_x(int T, int N, std::mt19937& rng) {
200    std::vector<float> x((size_t) T * N);
201    std::normal_distribution<float> nd(0.0f, 1.0f);
202    std::uniform_int_distribution<int> pick(0, 199);
203    for (float& v : x) v = nd(rng) * (pick(rng) == 0 ? 12.0f : 1.0f);
204    return x;
205}
206
207// K distinct experts per token; skew > 0: expert e is drawn with weight (e + 1)^-skew (the lowest ids are the hot ones)
208std::vector<int32_t> make_ids(int T, int E, int K, double skew, std::mt19937& rng) {
209    std::vector<int32_t> ids((size_t) T * K);
210    std::uniform_int_distribution<int> any(0, E - 1);
211    std::vector<double> w((size_t) E);
212    for (int e = 0; e < E; ++e) w[(size_t) e] = std::pow((double) (e + 1), -skew);
213    std::discrete_distribution<int> zipf(w.begin(), w.end());
214    for (int t = 0; t < T; ++t)
215        for (int k = 0; k < K; ++k) {
216            int e;
217            bool dup;
218            do {
219                e = skew > 0 ? zipf(rng) : any(rng);
220                dup = false;
221                for (int j = 0; j < k; ++j) dup |= ids[(size_t) t * K + j] == e;
222            } while (dup);
223            ids[(size_t) t * K + k] = e;
224        }
225    return ids;
226}
227
228struct Routing {
229    std::vector<int32_t> cnt, off, src;   // per expert; sorted row -> token (rows in pair order within an expert)
230    std::vector<int32_t> row_of;          // pair -> sorted row
231    std::vector<int32_t> order;           // experts with rows, ascending (the engine's `order`)
232};
233Routing sort_rows(const std::vector<int32_t>& ids, int E, int K) {
234    Routing r;
235    r.cnt.assign((size_t) E, 0);
236    for (int32_t e : ids) ++r.cnt[(size_t) e];
237    r.off.assign((size_t) E + 1, 0);
238    for (int e = 0; e < E; ++e) r.off[(size_t) e + 1] = r.off[(size_t) e] + r.cnt[(size_t) e];
239    std::vector<int32_t> fill(r.off.begin(), r.off.end() - 1);
240    r.src.resize(ids.size());
241    r.row_of.resize(ids.size());
242    for (size_t i = 0; i < ids.size(); ++i) {
243        const int32_t p = fill[(size_t) ids[i]]++;
244        r.row_of[i] = p;
245        r.src[(size_t) p] = (int32_t) (i / (size_t) K);
246    }
247    for (int e = 0; e < E; ++e) if (r.cnt[(size_t) e] > 0) r.order.push_back(e);
248    return r;
249}
250
251// ---------------------------------------------------------------------------------------------------------------------------------------------
252// MMQ: prefill_fused_iq_test.cpp's run_mmq (the non-direct form), with the shape at run time.  llama.cpp's mul_mat_q and its stream-k fixup read the
253// row-id table up to a J-column tile past the last row: the table takes mmq_ids_table_rows(rows, max_rows) entries (mmq_ids_margin.hpp).
254struct MmqPath {
255    const Pair& p;
256    const Shape& s;
257    const Geo& geo;
258    mmq::Context ctx;
259    Dev xq, hq, ident, bounds, grp_gu, grp_d, tails;   // tails: NVFP4's {s_gate, s_up, s_down, 0} of each expert of the open group
260    const Dev &gu, &h, &dm;   // shared with the other paths (FP32 [rows][2FF], [rows][FF], [rows][N])
261    const Routing& r;
262    const std::vector<const uint8_t*>& blob;
263    int64_t rows;
264    size_t gub, db;
265    MmqPath(const Pair& p_, const Shape& s_, const Geo& g_, int64_t rows_, const Routing& r_, const std::vector<const uint8_t*>& blob_,
266            const Dev& gu_, const Dev& h_, const Dev& dm_)
267        : p(p_), s(s_), geo(g_), xq(mmq::q8_bytes(rows_, s_.N)), hq(mmq::q8_bytes(rows_, s_.FF)),
268          ident((size_t) mmq::mmq_ids_table_rows((uint64_t) rows_, (uint64_t) (rows_ / s_.K)) * 4),
269          bounds((size_t) (2 * (s_.E + s_.E / GROUP + 2)) * 4),
270          grp_gu(GROUP * mmq::matrix_bytes(p_.gu, s_.FF2(), s_.N) + 4096), grp_d(GROUP * mmq::matrix_bytes(p_.d, s_.N, s_.FF) + 4096),
271          tails((size_t) GROUP * 16), gu(gu_), h(h_), dm(dm_), r(r_), blob(blob_), rows(rows_) {
272        gub = mmq::matrix_bytes(p.gu, s.FF2(), s.N);
273        db = mmq::matrix_bytes(p.d, s.N, s.FF);
274    }
275    void run(const float* x_dev, const int32_t* src_dev, cudaStream_t st) {
276        const std::vector<int32_t>& order = r.order;
277        const size_t n = order.size(), ng = (n + GROUP - 1) / GROUP;
278        std::vector<int32_t> bh(n + 1 + ng * (GROUP + 1));
279        for (size_t j = 0; j < n; ++j) bh[j] = r.off[(size_t) order[j]];
280        bh[n] = (int32_t) rows;
281        for (size_t g = 0; g < ng; ++g)
282            for (size_t i = 0; i <= GROUP; ++i) bh[n + 1 + g * (GROUP + 1) + i] = bh[std::min(n, g * GROUP + i)] - bh[g * GROUP];
283        ck(cudaMemcpyAsync(bounds.p, bh.data(), bh.size() * 4, cudaMemcpyHostToDevice, st), "bounds");
284        mmq::iota(ident.as<int32_t>(), (int64_t) (ident.n / 4), st);
285        mmq::quantize(x_dev, src_dev, xq.p, (int) p.gu, s.N, s.N, rows, st);
286        const int FF = s.FF, FF2 = s.FF2(), N = s.N;
287        for (size_t j = 0; j < n; ++j) {
288            const size_t q = j % GROUP;
289            const uint8_t* bl = blob[(size_t) order[j]];
290            // NVFP4: the expert's tail goes next to its group slot in the same launch, as prefill.cpp's gather
291            mmq::gather_native(bl, bl + geo.up_off, gub / 2, bl + geo.down_off, db, grp_gu.as<uint8_t>() + q * gub, grp_d.as<uint8_t>() + q * db, st,
292                               geo.tail_off ? bl + geo.tail_off : nullptr, geo.tail_off ? tails.as<uint8_t>() + q * 16 : nullptr);
293            if (q + 1 < GROUP && j + 1 < n) continue;
294            const size_t j0 = j - q, g = j0 / GROUP;
295            const int ngx = (int) (q + 1);
296            const int64_t r0 = bh[j0], nr = bh[j + 1] - r0;
297            int64_t maxr = 0;
298            for (size_t i = j0; i <= j; ++i) maxr = std::max<int64_t>(maxr, r.cnt[(size_t) order[i]]);
299            ck(cudaMemsetAsync(grp_gu.as<uint8_t>() + (size_t) ngx * gub, 0, 4096, st), "tail");
300            ck(cudaMemsetAsync(grp_d.as<uint8_t>() + (size_t) ngx * db, 0, 4096, st), "tail");
301            mmq::Product pg;
302            pg.w = grp_gu.p; pg.type = (int) p.gu; pg.w_rows = FF2; pg.w_cols = N; pg.expert_bytes = gub;
303            pg.n = ngx; pg.xq = xq.p; pg.bounds = bounds.as<int32_t>() + j0; pg.ids = ident.as<int32_t>();
304            pg.total_rows = rows; pg.max_rows = maxr; pg.dst = gu.as<float>(); pg.ld_dst = FF2;
305            ctx.run(pg, st);
306            if (geo.tail_off)   // gate/up scales applied as read (prefill.cpp)
307                mmq::swiglu_scaled(gu.as<float>() + r0 * FF2, h.as<float>() + r0 * FF, nr, FF, bounds.as<int32_t>() + j0, ngx, tails.as<float>(), r0, st);
308            else
309                mmq::swiglu(gu.as<float>() + r0 * FF2, h.as<float>() + r0 * FF, nr, FF, false, st);
310            mmq::quantize(h.as<float>() + r0 * FF, nullptr, hq.p, (int) p.d, FF, FF, nr, st);
311            mmq::Product pd;
312            pd.w = grp_d.p; pd.type = (int) p.d; pd.w_rows = N; pd.w_cols = FF; pd.expert_bytes = db;
313            pd.n = ngx; pd.xq = hq.p; pd.bounds = bounds.as<int32_t>() + n + 1 + g * (GROUP + 1);
314            pd.ids = ident.as<int32_t>(); pd.total_rows = nr; pd.max_rows = maxr; pd.dst = dm.as<float>() + r0 * N;
315            pd.ld_dst = N;
316            ctx.run(pd, st);
317            // NVFP4's s_down on the FP32 rows (the engine applies it in the combine; the same product per row)
318            if (geo.tail_off) mmq::scale_down_rows(dm.as<float>() + r0 * N, N, pd.bounds, ngx, tails.as<float>(), nr, st);
319        }
320    }
321};
322
323// ---------------------------------------------------------------------------------------------------------------------------------------------
324// FP16 (and FP16+FR): prefill.cpp's compute lambda, FP16 branch, with the library's own functions.
325struct Fp16Path {
326    const Pair& p;
327    const Shape& s;
328    const Geo& geo;
329    pf::Gemm& gemm;
330    Dev xs, hh, dqgu0, dqgu1, dqd0, dqd1, fr_rec, fr_xq, fr_scr;
331    const Dev &gu, &dm;
332    const Routing& r;
333    const std::vector<const uint8_t*>& blob;
334    int64_t rows;
335    int T;
336    bool fr_ok;
337    kern::NativeExpertLayout FL;
338    Fp16Path(const Pair& p_, const Shape& s_, const Geo& g_, pf::Gemm& gm, int T_, int64_t rows_, const Routing& r_,
339             const std::vector<const uint8_t*>& blob_, const Dev& gu_, const Dev& dm_, bool want_fr)
340        : p(p_), s(s_), geo(g_), gemm(gm), xs((size_t) rows_ * s_.N * 2), hh((size_t) rows_ * s_.FF * 2),
341          dqgu0((size_t) s_.FF2() * s_.N * 2), dqgu1((size_t) s_.FF2() * s_.N * 2), dqd0((size_t) s_.N * s_.FF * 2), dqd1((size_t) s_.N * s_.FF * 2),
342          gu(gu_), dm(dm_), r(r_), blob(blob_), rows(rows_), T(T_), fr_ok(false) {
343        fr_ok = want_fr && kern::native_expert_supported((int) p.gu, (int) p.d, s.N, s.FF);
344        if (fr_ok) {
345            FL = kern::native_expert_layout((int) p.gu, (int) p.d, s.N, s.FF);
346            fr_rec = Dev((size_t) s.E * pf::kFewRowsRecBytes);
347            fr_xq = Dev((size_t) T * (size_t) (s.N / 32) * 36);
348            fr_scr = Dev(kern::native_expert_scratch_bytes(pf::kFewRows, s.FF));
349        }
350    }
351    int few_rows_experts() const {
352        int c = 0;
353        for (int e : r.order) c += pf::fewrows_takes(true, true, true, false, r.cnt[(size_t) e]);
354        return c;
355    }
356    void run(bool fr, const float* x_dev, const uint16_t* x16_dev, const int32_t* src_dev, cudaStream_t st) {
357        const int N = s.N, FF = s.FF, FF2 = s.FF2();
358        pf::gather_rows16(x16_dev, src_dev, xs.as<uint16_t>(), rows, N, st);
359        if (fr && fr_ok) kern::quantize_q8_1_rows(x_dev, T, N, fr_xq.p, st);   // the layer's T rows as q8_1, once
360        size_t j = 0;
361        for (int32_t e : r.order) {
362            const int64_t o0 = r.off[(size_t) e], ne = r.cnt[(size_t) e];
363            const uint8_t* bl = blob[(size_t) e];
364            if (fr && fr_ok && pf::fewrows_takes(true, true, true, false, ne)) {
365                uint8_t* rec = fr_rec.as<uint8_t>() + j * pf::kFewRowsRecBytes;
366                pf::fewrows_record(rec, bl, (int) ne, (int) o0, st);
367                kern::native_expert_grouped(FL, (const unsigned long long*) rec, (const int32_t*) (rec + 8), (const int32_t*) (rec + 16),
368                                            (const int32_t*) (rec + 24), src_dev + o0, 1, ne, fr_xq.p, fr_scr.p, dm.as<float>(), st, 1);
369            } else {
370                const size_t q = j % DQ;
371                uint16_t* dgu = q ? dqgu1.as<uint16_t>() : dqgu0.as<uint16_t>();
372                uint16_t* dd = q ? dqd1.as<uint16_t>() : dqd0.as<uint16_t>();
373                // (NVFP4: the blob's tail {s_gate, s_up, s_down, 0}: the gate / up rows and the down matrix scaled as prefill.cpp's compute lambda does)
374                kern::iq_dequant_gu_f16((int) p.gu, bl, bl + geo.up_off, FF, N, dgu, st, geo.tail_off ? (const float*) (bl + geo.tail_off) : nullptr);
375                kern::iq_dequant_f16((int) p.d, bl + geo.down_off, (int64_t) N * FF, dd, st, geo.tail_off ? (const float*) (bl + geo.tail_off) + 2 : nullptr);
376                gemm.f16(xs.as<uint16_t>() + o0 * N, dgu, gu.as<float>() + o0 * FF2, ne, FF2, N);
377                pf::swiglu_interleaved(gu.as<float>() + o0 * FF2, hh.as<uint16_t>() + o0 * FF, ne, st);
378                gemm.f16(hh.as<uint16_t>() + o0 * FF, dd, dm.as<float>() + o0 * N, ne, N, FF);
379            }
380            ++j;
381        }
382    }
383};
384
385// ---------------------------------------------------------------------------------------------------------------------------------------------
386// GRP: the whole layer in one native_expert_grouped call (q36_engine.cu's fallback for a layer without fused kernels and without MMQ)
387struct GrpPath {
388    Dev xq, scr, ptr, start, ngroups, dst, tok;
389    kern::NativeExpertLayout L;
390    int64_t rows, n;
391    int T;
392    const Shape& s;
393    const Dev& dm;
394    GrpPath(const Pair& p, const Shape& s_, int T_, int64_t rows_, const Routing& r, const std::vector<const uint8_t*>& blob, const Dev& dm_)
395        : xq((size_t) T_ * (size_t) (s_.N / 32) * 36), scr(kern::native_expert_scratch_bytes(rows_, s_.FF)),
396          ptr(r.order.size() * 8), start((r.order.size() + 1) * 4), ngroups(4), dst((size_t) rows_ * 4), tok((size_t) rows_ * 4),
397          rows(rows_), n((int64_t) r.order.size()), T(T_), s(s_), dm(dm_) {
398        L = kern::native_expert_layout((int) p.gu, (int) p.d, s.N, s.FF);
399        std::vector<unsigned long long> hp((size_t) n);
400        std::vector<int32_t> hs((size_t) n + 1), hd((size_t) rows);
401        for (int64_t j = 0; j < n; ++j) {
402            hp[(size_t) j] = (unsigned long long) (uintptr_t) blob[(size_t) r.order[(size_t) j]];
403            hs[(size_t) j] = r.off[(size_t) r.order[(size_t) j]];
404        }
405        hs[(size_t) n] = (int32_t) rows;
406        for (int64_t i = 0; i < rows; ++i) hd[(size_t) i] = (int32_t) i;
407        const int32_t ng = (int32_t) n;
408        ck(cudaMemcpy(ptr.p, hp.data(), hp.size() * 8, cudaMemcpyHostToDevice), "grp ptr");
409        ck(cudaMemcpy(start.p, hs.data(), hs.size() * 4, cudaMemcpyHostToDevice), "grp start");
410        ck(cudaMemcpy(ngroups.p, &ng, 4, cudaMemcpyHostToDevice), "grp n");
411        ck(cudaMemcpy(dst.p, hd.data(), hd.size() * 4, cudaMemcpyHostToDevice), "grp dst");
412        ck(cudaMemcpy(tok.p, r.src.data(), r.src.size() * 4, cudaMemcpyHostToDevice), "grp tok");
413    }
414    void run(const float* x_dev, cudaStream_t st) {
415        kern::quantize_q8_1_rows(x_dev, T, s.N, xq.p, st);
416        kern::native_expert_grouped(L, ptr.as<unsigned long long>(), start.as<int32_t>(), ngroups.as<int32_t>(), dst.as<int32_t>(), tok.as<int32_t>(), n, rows,
417                                    xq.p, scr.p, dm.as<float>(), st);
418    }
419};
420
421static void set_i8_tm(int tm) {   // research: STRATA_I8_TM for the next native_expert_i8 calls (0 = unset: the call's own choice)
422#if defined(_WIN32)
423    _putenv_s("STRATA_I8_TM", tm > 0 ? std::to_string(tm).c_str() : "");
424#else
425    if (tm > 0) setenv("STRATA_I8_TM", std::to_string(tm).c_str(), 1); else unsetenv("STRATA_I8_TM");
426#endif
427}
428
429// I8: the same layer through native_expert_i8 (our own int8 dot-product tile kernels, src/kernels/cuda/i8_expert.cuh); the same tables and activations as GRP
430struct I8Path : GrpPath {
431    using GrpPath::GrpPath;
432    void run_i8(const float* x_dev, cudaStream_t st) {
433        kern::native_expert_i8_quantize(x_dev, T, s.N, xq.p, st);
434        kern::native_expert_i8(L, ptr.as<unsigned long long>(), start.as<int32_t>(), ngroups.as<int32_t>(), dst.as<int32_t>(), tok.as<int32_t>(), n, rows, xq.p, scr.p,
435                               dm.as<float>(), st);
436        // what the call really asked its launches for (the tile code, the dynamic shared memory passed to each launch, each launch's status), once per distinct request
437        const auto la = kern::native_expert_i8_last_launch();
438        static std::vector<std::array<long long, 7>> seen;
439        const std::array<long long, 7> key = {(long long) L.gu_type, (long long) L.d_type, (long long) T, (long long) la.tile, (long long) la.gu_bytes, (long long) la.down_bytes,
440                                              (long long) la.gu_err * 1000 + la.down_err};
441        if (std::find(seen.begin(), seen.end(), key) == seen.end()) {
442            seen.push_back(key);
443            std::printf("I8-LAUNCH gu_type=%d d_type=%d tokens=%d tile=%d gu_dyn_smem_bytes=%zu down_dyn_smem_bytes=%zu gu_launch=%s down_launch=%s\n", (int) L.gu_type, (int) L.d_type,
444                        (int) T, la.tile, la.gu_bytes, la.down_bytes, la.gu_err == 0 ? "accepted" : "ERROR", la.down_err == 0 ? "accepted" : "ERROR");
445            std::fflush(stdout);
446        }
447    }
448};
449
450// ---------------------------------------------------------------------------------------------------------------------------------------------
451// FUSED: moe_fused_iq.hpp's native entry points (the compiled geometry's copy), or the Qwen3.6 copy's.
452struct FusedFlash {
453    using Batch = fused::Batch;
454    using Geom = fused::NativeGeom;
455    static constexpr int kMaxB = fused::kMaxBatch;
456    static bool supported(int g, int d) { return fused::native_supported(g, d); }
457    static void quant(const float* x, int64_t rows, int64_t cols, void* xa, void* st) { fused::quantize_act_native(x, rows, cols, xa, st); }
458    static void experts(const Batch& b, const Geom& g, int ne, int64_t n, const void* scr, const void* xa, const int32_t* src, void* ha, float* dm, void* st) {
459        fused::experts_native(b, g, ne, n, scr, xa, src, ha, dm, st);
460    }
461};
462#if !defined(FB_HIP)
463namespace fq = strata::prefill::fused_q36;
464struct FusedQ36 {
465    using Batch = fq::Batch;
466    using Geom = fq::NativeGeom;
467    static constexpr int kMaxB = fq::kQ36MaxBatch;
468    static bool supported(int g, int d) { return fq::native_supported_ext(g, d); }
469    static void quant(const float* x, int64_t rows, int64_t cols, void* xa, void* st) { fq::quantize_act_native(x, rows, cols, xa, st); }
470    static void experts(const Batch& b, const Geom& g, int ne, int64_t n, const void* scr, const void* xa, const int32_t* src, void* ha, float* dm, void* st) {
471        fq::experts_native_ext(b, g, ne, n, scr, xa, src, ha, dm, st);
472    }
473};
474#endif
475
476struct FusedBase {
477    virtual ~FusedBase() = default;
478    virtual void run(const float* x_dev, cudaStream_t st) = 0;
479    virtual const Dev& slot() const = 0;
480};
481template <class F>
482struct FusedPath : FusedBase {
483    Dev xa, ha, scratch, slot_, src_, ids;
484    typename F::Geom ng;
485    const Shape& s;
486    const std::vector<const uint8_t*>& blob;
487    const Dev& dm;
488    int T;
489    int64_t rows;
490    FusedPath(const Pair& p, const Geo& geo, const Shape& s_, int T_, int64_t rows_, const std::vector<int32_t>& ids_h,
491              const std::vector<const uint8_t*>& blob_, const Dev& dm_)
492        : xa(fused::act_bytes(T_, s_.N)), ha(fused::act_bytes(rows_, s_.FF)), scratch(fused::group_bytes(rows_, s_.E)), slot_((size_t) rows_ * 4),
493          src_((size_t) rows_ * 4), ids((size_t) rows_ * 4), s(s_), blob(blob_), dm(dm_), T(T_), rows(rows_) {
494        ng = {};
495        ng.gu_type = (int) p.gu; ng.d_type = (int) p.d; ng.gu_row = geo.gu_row; ng.d_row = geo.d_row; ng.up_off = geo.up_off; ng.down_off = geo.down_off;
496        ck(cudaMemcpy(ids.p, ids_h.data(), ids_h.size() * 4, cudaMemcpyHostToDevice), "ids");
497    }
498    void run(const float* x_dev, cudaStream_t st) override {
499        F::quant(x_dev, T, s.N, xa.p, st);
500        fused::group(ids.as<int32_t>(), rows, s.K, s.E, scratch.p, slot_.as<int32_t>(), src_.as<int32_t>(), st);
501        for (int e0 = 0; e0 < s.E; e0 += F::kMaxB) {
502            typename F::Batch bt;
503            bt.e0 = e0;
504            bt.e1 = std::min(s.E, e0 + F::kMaxB);
505            for (int e = bt.e0; e < bt.e1; ++e) bt.blob[e - bt.e0] = blob[(size_t) e];
506            F::experts(bt, ng, s.E, rows, scratch.p, xa.p, src_.as<int32_t>(), ha.p, dm.as<float>(), st);
507        }
508    }
509    const Dev& slot() const override { return slot_; }
510};
511
512// ---------------------------------------------------------------------------------------------------------------------------------------------
513struct Err {
514    double rms = -1, worst = -1;   // RMS error / RMS of the reference; the worst row's max |error| / its max |ref|   (-1: not measured)
515};
516Err compare(const std::vector<float>& a, const std::vector<float>& ref, size_t pairs, int N) {
517    double e2 = 0, r2 = 0;
518    Err out;
519    out.worst = 0;
520    for (size_t i = 0; i < pairs; ++i) {
521        double me = 0, mr = 0;
522        for (int o = 0; o < N; ++o) {
523            const double ya = a[i * (size_t) N + (size_t) o], yb = ref[i * (size_t) N + (size_t) o];
524            const double d = std::isfinite(ya) ? ya - yb : 1e30;
525            e2 += d * d;
526            r2 += yb * yb;
527            me = std::max(me, std::fabs(d));
528            mr = std::max(mr, std::fabs(yb));
529        }
530        out.worst = std::max(out.worst, mr > 0 ? me / mr : (me > 0 ? 1e30 : 0.0));
531    }
532    out.rms = r2 > 0 ? std::sqrt(e2 / r2) : 0;
533    return out;
534}
535
536struct Out {   // one path's output, read back: per pair order
537    uint64_t hash = 0;
538    int64_t nonfinite_rows = 0;
539    std::vector<float> sample;   // the sampled pairs' rows
540};
541// reads the [rows][N] FP32 outputs in chunks (host RAM stays small): a hash per row, folded in pair order; the sampled pairs' rows kept
542Out read_back(const Dev& dm, int64_t rows, int N, const std::vector<int32_t>& row_of_pair, const std::vector<size_t>& pick) {
543    Out o;
544    o.sample.assign(pick.size() * (size_t) N, 0.0f);
545    std::vector<uint64_t> rh((size_t) rows);
546    std::vector<int32_t> want((size_t) rows, -1);   // row -> sample index
547    for (size_t j = 0; j < pick.size(); ++j) want[(size_t) row_of_pair[pick[j]]] = (int32_t) j;
548    const int64_t chunk = std::max<int64_t>(1, (64ll << 20) / ((int64_t) N * 4));
549    std::vector<float> buf((size_t) chunk * (size_t) N);
550    for (int64_t r0 = 0; r0 < rows; r0 += chunk) {
551        const int64_t n = std::min(chunk, rows - r0);
552        ck(cudaMemcpy(buf.data(), dm.as<uint8_t>() + (size_t) r0 * (size_t) N * 4, (size_t) n * (size_t) N * 4, cudaMemcpyDeviceToHost), "download");
553        for (int64_t i = 0; i < n; ++i) {
554            const uint32_t* u = (const uint32_t*) (buf.data() + (size_t) i * (size_t) N);
555            uint64_t h = 1469598103934665603ull;
556            bool bad = false;
557            for (int c = 0; c < N; ++c) {
558                h = (h ^ u[c]) * 1099511628211ull;
559                bad |= !std::isfinite(buf[(size_t) i * (size_t) N + (size_t) c]);
560            }
561            rh[(size_t) (r0 + i)] = h;
562            o.nonfinite_rows += bad;
563            if (const int32_t j = want[(size_t) (r0 + i)]; j >= 0)
564                std::memcpy(o.sample.data() + (size_t) j * (size_t) N, buf.data() + (size_t) i * (size_t) N, (size_t) N * 4);
565        }
566    }
567    uint64_t hsh = 1469598103934665603ull;
568    for (size_t i = 0; i < row_of_pair.size(); ++i) hsh = (hsh ^ rh[(size_t) row_of_pair[i]]) * 1099511628211ull;
569    o.hash = hsh;
570    return o;
571}
572
573float median(std::vector<float> v) {
574    std::sort(v.begin(), v.end());
575    return v[v.size() / 2];
576}
577
578struct PathRow {
579    const char* name;
580    std::function<void()> run;
581    std::function<std::vector<int32_t>()> rows_of_pair;   // pair -> output row of this path
582    std::vector<float> t;
583    Out out;
584    Err err;
585    float first_ms = 0;
586};
587
588struct Opts {
589    Shape shape{2560, 640, 512, 10, "flash"};
590    std::vector<int> tokens = {2048, 4096, 8192, 20000};
591    std::vector<std::string> only;
592    std::vector<int> i8_tms;   // --i8-tm=2,3,4: one extra I8 column per tile-row count (STRATA_I8_TM set around each run)
593    bool dense = false, tokens_set = false, all = false, list = false, grouped = false, i8 = false, no_grp = false, no_mmq = false, no_fused = false, no_fp16 = false, no_ref = false, quick = false;
594    int repeats = 7, sample = 96, experts = 0;
595    float warm_ms = 1000.0f;
596    double skew = 0;
597    unsigned seed = 1360;
598    std::string dense_type = "Q8_0";
599    // --real=DIR --real-pack=native_experts.txt --real-gguf=SHARD.gguf [--real-layers=0,1,...]: real rows (the engine's STRATA_DUMP_MOE_INPUT=DIR/moe STRATA_DUMP_MOE_LAYER=all files DIR/moe.L<l>:
600    // a layer's MoE input and routing) through that layer's real experts (read from the GGUF at the offsets of the pack's native_experts.txt), one cell per layer, the pair taken from the pack's types
601    std::string real_dir, real_pack, real_gguf;
602    std::vector<int> real_layers;
603};
604
605// one real layer: the engine's own MoE input rows of the first chunk, its routing, and the layer's expert blobs (gate | up | down per expert, the engine's blob layout)
606struct RealLayer {
607    int layer = 0, T = 0;
608    std::vector<float> x;
609    std::vector<int32_t> ids;
610    std::vector<std::vector<uint8_t>> blob;   // per expert
611};
612
613void defenv(const char* name, const char* val) {
614    if (std::getenv(name) != nullptr) return;
615#ifdef _WIN32
616    _putenv_s(name, val);
617#else
618    setenv(name, val, 0);
619#endif
620}
621
622std::string arg_after(const char* a, const char* key) {
623    const size_t n = std::strlen(key);
624    return std::strncmp(a, key, n) == 0 ? std::string(a + n) : std::string();
625}
626std::string nospace(const char* s) {
627    std::string r;
628    for (; *s; ++s) if (*s != ' ') r += (char) std::tolower((unsigned char) *s);   // (case and spaces ignored)
629    return r;
630}
631std::vector<int> parse_ints(const std::string& s) {
632    std::vector<int> v;
633    for (const char* c = s.c_str(); *c;) {
634        v.push_back(std::atoi(c));
635        while (*c && *c != ',') ++c;
636        if (*c == ',') ++c;
637    }
638    return v;
639}
640
641const std::vector<Pair>& all_pairs() {
642    static const std::vector<Pair> pairs = {
643        // 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_S / IQ4_NL), IQ3_XXS's: the default set
644        {GGML_TYPE_IQ2_S, GGML_TYPE_Q2_0, "IQ2_S / Q2_0"},       {GGML_TYPE_IQ2_XXS, GGML_TYPE_Q2_0, "IQ2_XXS / Q2_0"},
645        {GGML_TYPE_IQ3_S, GGML_TYPE_IQ4_NL, "IQ3_S / IQ4_NL"},   {GGML_TYPE_IQ3_XXS, GGML_TYPE_IQ4_NL, "IQ3_XXS / IQ4_NL"},
646        {GGML_TYPE_IQ2_XS, GGML_TYPE_IQ4_NL, "IQ2_XS / IQ4_NL"}, {GGML_TYPE_IQ4_XS, GGML_TYPE_Q2_0, "IQ4_XS / Q2_0"},
647        {GGML_TYPE_IQ2_S, GGML_TYPE_IQ4_NL, "IQ2_S / IQ4_NL"},   {GGML_TYPE_IQ3_XXS, GGML_TYPE_Q2_0, "IQ3_XXS / Q2_0"},
648        {GGML_TYPE_IQ3_S, GGML_TYPE_Q2_0, "IQ3_S / Q2_0"},       {GGML_TYPE_IQ4_XS, GGML_TYPE_IQ4_NL, "IQ4_XS / IQ4_NL"},
649        {GGML_TYPE_IQ2_XXS, GGML_TYPE_IQ4_NL, "IQ2_XXS / IQ4_NL"},
650        // the Coder IQ1_M pack: IQ1_M gate/up (the down pairing is not verified against a pack here)
651        {GGML_TYPE_IQ1_M, GGML_TYPE_IQ4_NL, "IQ1_M / IQ4_NL"},   {GGML_TYPE_IQ1_M, GGML_TYPE_Q2_0, "IQ1_M / Q2_0"},
652        {GGML_TYPE_IQ3_XXS, GGML_TYPE_Q5_0, "IQ3_XXS / Q5_0"},   {GGML_TYPE_IQ4_XS, GGML_TYPE_Q5_0, "IQ4_XS / Q5_0"},
653        {GGML_TYPE_Q2_0, GGML_TYPE_Q2_0, "Q2_0 / Q2_0"},
654        // the K-quant sets: UD-Q4_K_XL (47 layers Q4_K / Q5_1, 4 Q4_K / Q8_0, one Q5_K layer), UD-IQ4_XS's Q8_0 downs, the Q8_0 set, UD-Q6_K_XL
655        {GGML_TYPE_Q4_K, GGML_TYPE_Q5_1, "Q4_K / Q5_1"},         {GGML_TYPE_Q4_K, GGML_TYPE_Q8_0, "Q4_K / Q8_0"},
656        {GGML_TYPE_Q5_K, GGML_TYPE_Q5_1, "Q5_K / Q5_1"},         {GGML_TYPE_Q5_K, GGML_TYPE_Q8_0, "Q5_K / Q8_0"},
657        {GGML_TYPE_IQ3_S, GGML_TYPE_Q8_0, "IQ3_S / Q8_0"},       {GGML_TYPE_IQ4_XS, GGML_TYPE_Q8_0, "IQ4_XS / Q8_0"},
658        {GGML_TYPE_Q8_0, GGML_TYPE_Q8_0, "Q8_0 / Q8_0"},         {GGML_TYPE_Q6_K, GGML_TYPE_Q8_0, "Q6_K + Q8_0"},
659        // Qwen3.6's K-quant downs (n_ff 512 is a whole number of 256-value blocks)
660        {GGML_TYPE_Q4_K, GGML_TYPE_Q5_K, "Q4_K / Q5_K"},         {GGML_TYPE_Q4_K, GGML_TYPE_Q6_K, "Q4_K / Q6_K"},
661        {GGML_TYPE_Q5_K, GGML_TYPE_Q6_K, "Q5_K / Q6_K"},
662        // NVFP4 (ModelOpt packs: Strata's GPTQ pack, NVIDIA's): NVFP4 gate/up and down, the blob's tail = the per-expert scales
663        {GGML_TYPE_NVFP4, GGML_TYPE_NVFP4, "NVFP4 / NVFP4"}};
664    return pairs;
665}
666constexpr int kDefaultPairs = 4;   // pairs[0..3]
667
668// ---------------------------------------------------------------------------------------------------------------------------------------------
669struct Card {
670    std::string name, arch;
671    int major = 0, minor = 0;
672    size_t total = 0;
673    bool hip = false;
674};
675
676void run_cell(const Pair& p, const Shape& s, int T, const Opts& o, const Card& card, pf::Gemm& gemm, cudaStream_t st, bool fp16_shape_ok, bool fewrows_dflt, const RealLayer* real = nullptr) {
677    const Geo geo(p, s);
678    const int N = s.N, FF = s.FF, FF2 = s.FF2(), K = s.K, E = s.E;
679    const int64_t rows = (int64_t) T * K;
680    size_t free0 = 0, tot = 0;
681    cudaMemGetInfo(&free0, &tot);
682
683    // blobs at the engine's stride (a whole number of blocks of both formats), identical but for one quant byte of the gate matrix's first row:
684    // strata::bench_blob::perturb_offset skips every byte that carries scale bits in the gate/up type's block (fixed offsets 4..19 reached block 1's
685    // fp16 scale on Q2_0's 18-byte blocks and gave some experts scales of +-12,992 or NaN)
686    strata::bench_blob::BlockLayout gu_lay;
687    if (!real && !strata::bench_blob::layout_of((int) p.gu, gu_lay)) {
688        std::printf("   %s: no block layout for gate/up type %d in bench_blob_layout.hpp: pair skipped\n", p.name, (int) p.gu);
689        return;
690    }
691    // checked against the engine's own type table (strata::quant::type_info), not ggml's: a build without MMQ links no ggml for this
692    const strata::quant::TypeInfo* gu_ti = real ? nullptr : strata::quant::type_info((int) p.gu);
693    if (!real && (gu_ti == nullptr || gu_lay.bytes != (int) gu_ti->bytes || gu_lay.values != gu_ti->blck || strata::bench_blob::perturb_offset(gu_lay, 15) >= geo.gu_row)) {
694        std::fprintf(stderr, "bench_blob_layout.hpp: type %d has %d bytes / %d values per block there, strata::quant::type_info says %zu / %d\n", (int) p.gu,
695                     gu_lay.bytes, gu_lay.values, gu_ti ? gu_ti->bytes : (size_t) 0, gu_ti ? gu_ti->blck : 0);
696        std::exit(1);
697    }
698    std::mt19937 rng(o.seed + (unsigned) p.gu * 7 + (unsigned) p.d);
699    size_t unit = type_size(p.gu);
700    while (unit % type_size(p.d) != 0 || unit % 16 != 0) unit += type_size(p.gu);
701    const size_t stride = (geo.bytes + unit - 1) / unit * unit;
702    Dev blobs((size_t) E * stride + 4096);
703    ck(cudaMemset(blobs.p, 0, blobs.n), "zero");
704    const std::vector<uint8_t> base = real ? std::vector<uint8_t>() : make_blob(p, geo, s, rng);
705    auto blob_bytes = [&](int e) -> std::vector<uint8_t> {
706        if (real) { std::vector<uint8_t> rb = real->blob[(size_t) e]; rb.resize(geo.bytes, 0); return rb; }   // (an expert no row routes to is not loaded: zeros)
707        std::vector<uint8_t> b = base;
708        b[strata::bench_blob::perturb_offset(gu_lay, e)] ^= (uint8_t) e;
709        return b;
710    };
711    for (int e = 0; e < E; ++e) {
712        const std::vector<uint8_t> b = blob_bytes(e);
713        ck(cudaMemcpy(blobs.as<uint8_t>() + (size_t) e * stride, b.data(), geo.bytes, cudaMemcpyHostToDevice), "blob");
714    }
715    std::vector<const uint8_t*> blob((size_t) E);
716    for (int e = 0; e < E; ++e) blob[(size_t) e] = blobs.as<uint8_t>() + (size_t) e * stride;
717
718    std::vector<float> x = real ? real->x : make_x(T, N, rng);
719    const std::vector<int32_t> ids = real ? real->ids : make_ids(T, E, K, o.skew, rng);
720    const Routing r = sort_rows(ids, E, K);
721    int max_rows = 0, few = 0;
722    for (int e = 0; e < E; ++e) {
723        max_rows = std::max<int>(max_rows, r.cnt[(size_t) e]);
724        few += r.cnt[(size_t) e] >= 1 && r.cnt[(size_t) e] <= pf::kFewRows;
725    }
726
727    Dev x_dev((size_t) T * N * 4), x16_dev((size_t) T * N * 2), src_dev((size_t) rows * 4);
728    {
729        ck(cudaMemcpy(x_dev.p, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "x");
730        std::vector<uint16_t> x16(x.size());
731        for (size_t i = 0; i < x.size(); ++i) x16[i] = ggml_fp32_to_fp16(x[i]);
732        ck(cudaMemcpy(x16_dev.p, x16.data(), x16.size() * 2, cudaMemcpyHostToDevice), "x16");
733        ck(cudaMemcpy(src_dev.p, r.src.data(), r.src.size() * 4, cudaMemcpyHostToDevice), "src");
734    }
735    Dev gu((size_t) rows * FF2 * 4), hmq((size_t) rows * FF * 4), dm((size_t) rows * N * 4);   // shared by the paths (one runs at a time)
736
737    const bool mmq_ok = !o.no_mmq && mmq::built() && mmq::supported((int) p.gu) && mmq::supported((int) p.d) && mmq::fits((int) p.gu, FF2) && mmq::fits((int) p.d, N);
738    const bool fp16_ok = !o.no_fp16 && fp16_shape_ok && kern::iq_supported((int) p.gu) && kern::iq_supported((int) p.d);
739    const bool fused_flash = !o.no_fused && N == (int) fused::kMoeEmbd && FF == (int) fused::kMoeFF && FusedFlash::supported((int) p.gu, (int) p.d);
740#if !defined(FB_HIP)
741    const bool fused_q36 = !o.no_fused && !fused_flash && N == fq::kQ36Embd && FF == fq::kQ36FF && FusedQ36::supported((int) p.gu, (int) p.d);
742#else
743    const bool fused_q36 = false;
744#endif
745    const bool grp_ok = !o.no_grp && (o.grouped || s.name == "q36") && kern::native_expert_supported((int) p.gu, (int) p.d, N, FF);
746    const bool fr_ok = fp16_ok && kern::native_expert_supported((int) p.gu, (int) p.d, N, FF);
747    const bool i8_ok = o.i8 && kern::native_expert_supported((int) p.gu, (int) p.d, N, FF) && kern::native_expert_i8_supported(kern::native_expert_layout((int) p.gu, (int) p.d, N, FF));
748
749    std::unique_ptr<MmqPath> mp;
750    std::unique_ptr<Fp16Path> fp;
751    std::unique_ptr<GrpPath> gp;
752    std::unique_ptr<I8Path> ip;
753    std::unique_ptr<FusedBase> fu;
754    if (mmq_ok) mp = std::make_unique<MmqPath>(p, s, geo, rows, r, blob, gu, hmq, dm);
755    if (fp16_ok) fp = std::make_unique<Fp16Path>(p, s, geo, gemm, T, rows, r, blob, gu, dm, fr_ok);
756    if (grp_ok) gp = std::make_unique<GrpPath>(p, s, T, rows, r, blob, dm);
757    if (i8_ok) ip = std::make_unique<I8Path>(p, s, T, rows, r, blob, dm);
758    if (fused_flash) fu = std::make_unique<FusedPath<FusedFlash>>(p, geo, s, T, rows, ids, blob, dm);
759#if !defined(FB_HIP)
760    if (fused_q36) fu = std::make_unique<FusedPath<FusedQ36>>(p, geo, s, T, rows, ids, blob, dm);
761#endif
762    ck(cudaDeviceSynchronize(), "uploads");   // (the uploads above are on the legacy stream, the work below on a non-blocking one)
763
764    auto pair_rows = [&] { return r.row_of; };
765    std::vector<PathRow> paths;
766    if (mp) paths.push_back({"MMQ", [&] { mp->run(x_dev.as<float>(), src_dev.as<int32_t>(), st); }, pair_rows, {}, {}, {}, 0});
767    if (fp) {
768        paths.push_back({"FP16", [&] { fp->run(false, x_dev.as<float>(), x16_dev.as<uint16_t>(), src_dev.as<int32_t>(), st); }, pair_rows, {}, {}, {}, 0});
769        if (fr_ok) paths.push_back({"FP16+FR", [&] { fp->run(true, x_dev.as<float>(), x16_dev.as<uint16_t>(), src_dev.as<int32_t>(), st); }, pair_rows, {}, {}, {}, 0});
770    }
771    if (gp) paths.push_back({"GRP", [&] { gp->run(x_dev.as<float>(), st); }, pair_rows, {}, {}, {}, 0});
772    if (ip) paths.push_back({"I8", [&] { set_i8_tm(0); ip->run_i8(x_dev.as<float>(), st); }, pair_rows, {}, {}, {}, 0});
773    if (ip) {
774        static const char* const tm_names[] = {"I8t1", "I8t2", "I8t3", "I8t4", "I8t5", "I8t6", "I8t7", "I8t8"};
775        for (size_t k = 0; k < o.i8_tms.size() && k < 8; ++k) {
776            const int tm = o.i8_tms[k];
777            paths.push_back({tm_names[std::min(std::max(tm, 1), 8) - 1], [&, tm] { set_i8_tm(tm); ip->run_i8(x_dev.as<float>(), st); }, pair_rows, {}, {}, {}, 0});
778        }
779    }
780    if (fu) paths.push_back({"FUSED", [&] { fu->run(x_dev.as<float>(), st); },
781                             [&] {
782                                 std::vector<int32_t> slot((size_t) rows);
783                                 ck(cudaMemcpy(slot.data(), fu->slot().p, slot.size() * 4, cudaMemcpyDeviceToHost), "slot");
784                                 return slot;
785                             }, {}, {}, {}, 0});
786
787    size_t free1 = 0;
788    cudaMemGetInfo(&free1, &tot);
789    const double vram_mib = (double) (free0 - std::min(free0, free1)) / (1024.0 * 1024.0);
790
791    if (real) std::printf("== REAL layer %d (the engine's own rows and routing, the layer's own experts)\n", real->layer);
792    std::printf("== %s  shape %s (%dx%d, %d experts, top %d)  T=%d  rows %lld (per expert avg %.1f max %d; experts with <= %d rows: %d)  weights %.1f MiB/expert\n",
793                p.name, s.name.c_str(), N, FF, E, K, T, (long long) rows, (double) rows / E, max_rows, pf::kFewRows, few, (double) geo.bytes / (1024.0 * 1024.0));
794    if (paths.empty()) {
795        std::printf("   no path covers this pair here\n");
796        return;
797    }
798
799    // the CPU FP32 reference on a sample of pairs
800    std::vector<size_t> pick;
801    std::vector<float> ref;
802    if (!o.no_ref) {
803        for (size_t i = 0; pick.size() < (size_t) o.sample && i < (size_t) o.sample * 4; ++i) {
804            const size_t c = (i * 2654435761u + 12345u) % (size_t) rows;
805            if (std::find(pick.begin(), pick.end(), c) == pick.end()) pick.push_back(c);
806        }
807        ref.assign(pick.size() * (size_t) N, 0.0f);
808        std::vector<std::thread> th;
809        const int nth = std::max(1, std::min(16, (int) std::thread::hardware_concurrency()));
810        for (int w = 0; w < nth; ++w)
811            th.emplace_back([&, w] {
812                std::vector<float> g, dn, h((size_t) FF);
813                for (size_t j = (size_t) w; j < pick.size(); j += (size_t) nth) {
814                    const size_t i = pick[j];
815                    dequant(p, geo, s, blob_bytes(ids[i]), g, dn);
816                    const float* xr = x.data() + (i / (size_t) K) * (size_t) N;
817                    for (int f = 0; f < FF; ++f) {
818                        double gt = 0, up = 0;
819                        const float *wg = g.data() + (size_t) f * N, *wu = g.data() + (size_t) (FF + f) * N;
820                        for (int k = 0; k < N; ++k) { gt += (double) wg[k] * xr[k]; up += (double) wu[k] * xr[k]; }
821                        h[(size_t) f] = (float) (gt / (1.0 + std::exp(-gt)) * up);
822                    }
823                    for (int oo = 0; oo < N; ++oo) {
824                        double a = 0;
825                        const float* wd = dn.data() + (size_t) oo * FF;
826                        for (int f = 0; f < FF; ++f) a += (double) wd[f] * h[(size_t) f];
827                        ref[j * (size_t) N + (size_t) oo] = (float) a;
828                    }
829                }
830            });
831        for (auto& t : th) t.join();
832    }
833
834    cudaEvent_t ea, eb;
835    ck(cudaEventCreate(&ea), "event");
836    ck(cudaEventCreate(&eb), "event");
837    auto once = [&](PathRow& pr) {
838        ck(cudaEventRecord(ea, st), "record");
839        pr.run();
840        ck(cudaEventRecord(eb, st), "record");
841        ck(cudaEventSynchronize(eb), "sync");
842        float t = 0;
843        ck(cudaEventElapsedTime(&t, ea, eb), "elapsed");
844        return t;
845    };
846
847    // 1. each path once: its output (hashed, a sample against the reference), first-run time (includes one-time setup: not reported)
848    float slowest = 0;
849    for (PathRow& pr : paths) {
850        ck(cudaMemset(dm.p, 0xff, dm.n), "sentinel");   // an unwritten row is NaN
851        ck(cudaDeviceSynchronize(), "sentinel");
852        pr.first_ms = once(pr);
853        slowest = std::max(slowest, pr.first_ms);
854        const std::vector<int32_t> rop = pr.rows_of_pair();
855        pr.out = read_back(dm, rows, N, rop, pick);
856        if (!o.no_ref) pr.err = compare(pr.out.sample, ref, pick.size(), N);
857    }
858    // 2. warm-up (~warm-ms of all paths, the clocks ramp up), then alternating rounds, the first path rotating; a very slow cell keeps fewer rounds
859    const bool slow = slowest > 1500.0f;
860    int repeats = slow ? std::min(o.repeats, 3) : o.repeats;
861    for (float spent = 0; spent < (slow ? 0.0f : o.warm_ms);) {
862        float round = 0;
863        for (PathRow& pr : paths) round += once(pr);
864        spent += round;
865        if (round <= 0) break;
866    }
867    for (int rep = 0; rep < repeats; ++rep)
868        for (size_t i = 0; i < paths.size(); ++i) {
869            PathRow& pr = paths[(i + (size_t) rep) % paths.size()];
870            pr.t.push_back(once(pr));
871        }
872    cudaEventDestroy(ea);
873    cudaEventDestroy(eb);
874    ck(cudaGetLastError(), "after timing");
875
876    const auto find = [&](const char* n) -> PathRow* { for (PathRow& pr : paths) if (std::strcmp(pr.name, n) == 0) return &pr; return nullptr; };
877    PathRow* pm = find("MMQ");
878    // the sampled pairs of every path against MMQ's (not against the FP32 reference): two paths with the same int8 activations and exact integer sums differ by float rounding only
879    if (pm != nullptr && !pm->out.sample.empty()) {
880        std::printf("   rms difference to MMQ's output on the sampled pairs (relative to MMQ's own RMS; worst row max|diff| / max|MMQ|):");
881        for (PathRow& pr : paths) {
882            if (&pr == pm || pr.out.sample.size() != pm->out.sample.size()) continue;
883            const Err d = compare(pr.out.sample, pm->out.sample, pick.size(), N);
884            std::printf("  %s %.2e / %.2e", pr.name, d.rms, d.worst);
885        }
886        std::printf("\n");
887        // how the difference spreads over the sampled pairs: a few pairs far above the float-rounding level (one int8 code of an activation or of H landing on the other side of a
888        // rounding boundary) against every pair slightly different
889        for (PathRow& pr : paths) {
890            if (&pr == pm || pr.out.sample.size() != pm->out.sample.size()) continue;
891            std::vector<double> rel;
892            for (size_t i = 0; i < pick.size(); ++i) {
893                double me = 0, mr = 0;
894                for (int o = 0; o < N; ++o) {
895                    const double ya = pr.out.sample[i * (size_t) N + (size_t) o], yb = pm->out.sample[i * (size_t) N + (size_t) o];
896                    me = std::max(me, std::isfinite(ya) ? std::fabs(ya - yb) : 1e30);
897                    mr = std::max(mr, std::fabs(yb));
898                }
899                rel.push_back(mr > 0 ? me / mr : (me > 0 ? 1e30 : 0.0));
900            }
901            std::sort(rel.begin(), rel.end());
902            size_t over = 0;
903            for (double r : rel) over += r > 1e-5;
904            const size_t n = rel.size();
905            std::printf("   %s per sampled pair, max|diff| / max|MMQ|: %zu of %zu pairs above 1e-5; largest %.2e, second %.2e, median %.2e\n", pr.name, over, n,
906                        n ? rel[n - 1] : 0.0, n > 1 ? rel[n - 2] : 0.0, n ? rel[n / 2] : 0.0);
907        }
908    }
909    std::printf("   %-8s %10s %10s %10s %9s  %9s %9s  %-16s %s\n", "path", "ms median", "min", "max", pm ? "x MMQ" : "", "err rms", "worst row", "output hash", "non-finite rows");
910    for (PathRow& pr : paths) {
911        const float md = median(pr.t), mn = *std::min_element(pr.t.begin(), pr.t.end()), mx = *std::max_element(pr.t.begin(), pr.t.end());
912        char rel[32] = "";
913        if (pm) std::snprintf(rel, sizeof rel, "%.3f", median(pm->t) / md);
914        std::printf("   %-8s %10.3f %10.3f %10.3f %9s  ", pr.name, md, mn, mx, rel);
915        if (pr.err.rms >= 0) std::printf("%9.2e %9.2e  ", pr.err.rms, pr.err.worst); else std::printf("%9s %9s  ", "-", "-");
916        std::printf("%016llx %lld\n", (unsigned long long) pr.out.hash, (long long) pr.out.nonfinite_rows);
917    }
918    if (real) {   // REALROW: one line per layer for the tables (error against FP32 of MMQ / I8 / FP16, and the sampled I8-to-MMQ difference)
919        PathRow *rm = find("MMQ"), *ri = find("I8"), *rf = find("FP16");
920        double dif = -1, dwr = -1;
921        if (rm && ri && !rm->out.sample.empty() && ri->out.sample.size() == rm->out.sample.size()) { const Err d = compare(ri->out.sample, rm->out.sample, pick.size(), N); dif = d.rms; dwr = d.worst; }
922        std::printf("REALROW layer=%d pair=\"%s\" T=%d mmq_err=%.3e mmq_worst=%.3e i8_err=%.3e i8_worst=%.3e fp16_err=%.3e i8_vs_mmq=%.3e i8_vs_mmq_worst=%.3e\n", real->layer, p.name, T,
923                    rm ? rm->err.rms : -1.0, rm ? rm->err.worst : -1.0, ri ? ri->err.rms : -1.0, ri ? ri->err.worst : -1.0, rf ? rf->err.rms : -1.0, dif, dwr);
924    }
925    // the machine-readable line: key=value, n/a where a path is absent; ratios are speed ratios (the first path's ms over this path's ms, > 1: faster)
926    auto ms = [&](const char* n, char* buf, size_t cap) { PathRow* q = find(n); if (q) std::snprintf(buf, cap, "%.3f", median(q->t)); else std::snprintf(buf, cap, "n/a"); };
927    auto ratio = [&](const char* a, const char* b, char* buf, size_t cap) {
928        PathRow *x1 = find(a), *x2 = find(b);
929        if (x1 && x2) std::snprintf(buf, cap, "%.3f", median(x1->t) / median(x2->t)); else std::snprintf(buf, cap, "n/a");
930    };
931    auto errs = [&](const char* n, char* buf, size_t cap) { PathRow* q = find(n); if (q && q->err.rms >= 0) std::snprintf(buf, cap, "%.3e/%.3e", q->err.rms, q->err.worst); else std::snprintf(buf, cap, "n/a"); };
932    auto hs = [&](const char* n, char* buf, size_t cap) { PathRow* q = find(n); if (q) std::snprintf(buf, cap, "%016llx", (unsigned long long) q->out.hash); else std::snprintf(buf, cap, "n/a"); };
933    auto spread = [&](const char* n, char* buf, size_t cap) {
934        PathRow* q = find(n);
935        if (q) std::snprintf(buf, cap, "%.3f", (*std::max_element(q->t.begin(), q->t.end()) - *std::min_element(q->t.begin(), q->t.end())) / median(q->t));
936        else std::snprintf(buf, cap, "n/a");
937    };
938    char m_mmq[24], m_fp[24], m_fr[24], m_grp[24], m_fu[24], r_fp[24], r_fr[24], r_grp[24], r_fu[24], r_fu_fp[24], e_mmq[40], e_fp[40], e_fr[40], e_grp[40], e_fu[40];
939    char m_i8[24], r_i8[24], e_i8[40], h_i8[24], sp_i8[24];
940    char h_mmq[24], h_fp[24], h_fr[24], h_grp[24], h_fu[24], sp_mmq[24], sp_fp[24], sp_fu[24];
941    ms("MMQ", m_mmq, sizeof m_mmq); ms("FP16", m_fp, sizeof m_fp); ms("FP16+FR", m_fr, sizeof m_fr); ms("GRP", m_grp, sizeof m_grp); ms("FUSED", m_fu, sizeof m_fu); ms("I8", m_i8, sizeof m_i8); ratio("MMQ", "I8", r_i8, sizeof r_i8); errs("I8", e_i8, sizeof e_i8); hs("I8", h_i8, sizeof h_i8); spread("I8", sp_i8, sizeof sp_i8);
942    ratio("MMQ", "FP16", r_fp, sizeof r_fp); ratio("MMQ", "FP16+FR", r_fr, sizeof r_fr); ratio("MMQ", "GRP", r_grp, sizeof r_grp); ratio("MMQ", "FUSED", r_fu, sizeof r_fu);
943    ratio("FP16", "FUSED", r_fu_fp, sizeof r_fu_fp);
944    errs("MMQ", e_mmq, sizeof e_mmq); errs("FP16", e_fp, sizeof e_fp); errs("FP16+FR", e_fr, sizeof e_fr); errs("GRP", e_grp, sizeof e_grp); errs("FUSED", e_fu, sizeof e_fu);
945    hs("MMQ", h_mmq, sizeof h_mmq); hs("FP16", h_fp, sizeof h_fp); hs("FP16+FR", h_fr, sizeof h_fr); hs("GRP", h_grp, sizeof h_grp); hs("FUSED", h_fu, sizeof h_fu);
946    spread("MMQ", sp_mmq, sizeof sp_mmq); spread("FP16", sp_fp, sizeof sp_fp); spread("FUSED", sp_fu, sizeof sp_fu);
947    long long bad = 0;
948    for (const PathRow& pr : paths) bad += pr.out.nonfinite_rows;
949    std::string pn = p.name;
950    for (char& c : pn) if (c == ' ') c = '_';
951    std::printf("RESULT shape=%s pair=%s tokens=%d experts=%d top=%d few_row_experts=%d fewrows_default_here=%d mmq_ms=%s fp16_ms=%s fp16fr_ms=%s grp_ms=%s fused_ms=%s "
952                "mmq_over_fp16=%s mmq_over_fp16fr=%s mmq_over_grp=%s mmq_over_fused=%s fp16_over_fused=%s spread_mmq=%s spread_fp16=%s spread_fused=%s repeats=%d "
953                "err_mmq=%s err_fp16=%s err_fp16fr=%s err_grp=%s err_fused=%s hash_mmq=%s hash_fp16=%s hash_fp16fr=%s hash_grp=%s hash_fused=%s nonfinite_rows=%lld "
954                "i8_ms=%s mmq_over_i8=%s err_i8=%s hash_i8=%s spread_i8=%s vram_mib=%.0f card=%s arch=%s skew=%.2f\n",
955                s.name.c_str(), pn.c_str(), T, E, K, few, fewrows_dflt ? 1 : 0, m_mmq, m_fp, m_fr, m_grp, m_fu, r_fp, r_fr, r_grp, r_fu, r_fu_fp, sp_mmq, sp_fp, sp_fu,
956                repeats, e_mmq, e_fp, e_fr, e_grp, e_fu, h_mmq, h_fp, h_fr, h_grp, h_fu, bad, m_i8, r_i8, e_i8, h_i8, sp_i8, vram_mib, [&] {
957                    static std::string cn; cn = card.name; for (char& c : cn) if (c == ' ') c = '_'; return cn.c_str(); }(), card.arch.c_str(), o.skew);
958    std::fflush(stdout);
959}
960#if defined(FB_HIP)
961constexpr bool FB_HIP_ON = true;
962#else
963constexpr bool FB_HIP_ON = false;
964#endif
965// ---------------------------------------------------------------------------------------------------------------------------------------------
966// --dense: the engine's dense prompt GEMMs (projections) through strata::prefill::Gemm with FP16 io off and on.  "On" is Gemm::set_f16_io(true), what
967// STRATA_HIP_PROMPT_F16=1 (prompt_f16(), src/prefill/gemm.cu) sets on a HIP card: bf16() then takes the FP16 image of the activations and native() / bf16()
968// run the GEMM with FP16 out (widened in place).  On CUDA set_f16_io has no effect (the engine never turns it on there): both columns are the same code, which
969// makes the ratio the run-to-run noise floor.  The shapes are Flash-Next's (the compiled geometry's), (T, N, K) as the engine's call sites pass them:
970//   prefill.cpp (a269d4c82)   gdn_qkv native :4393   gdn_gate native :4401   gdn_out native :4424   alpha/beta bf16 :4402-4403   qsa_k/v native :4445-4446
971//                             qsa_q native :4448   indexer k/q bf16 :4450-4451   qsa_out native :4785   router bf16 :4797   shared expert native :4861-4864
972//                             hyper-connection down bf16 :4336, up :4345/4366, inj :4368 (bf16_proj / native_proj at :3219-3251)
973// `uses` is how often a prompt chunk runs the shape (per layer kind); the totals line weights by it.
974struct DenseShape {
975    const char* name;
976    bool bf16;    // the weights are BF16 tensors (bf16_proj); else GGUF blocks (native_proj)
977    int64_t N, K;
978    int uses;
979    const char* site;
980};
981std::vector<DenseShape> dense_shapes() {
982    const auto& g = strata::core::kCompiledGeometry;
983    const int64_t Nn = g.n_embd, D = g.hc * g.n_embd, LR = g.hc_lr, C = g.ssm_conv_channels, ZV = g.ssm_value_dim, QW = g.n_head * g.head_dim,
984                  KV = g.n_head_kv * g.head_dim, IQW = g.idx_q_heads * g.idx_key_dim;
985    const int nl = (int) g.n_layers, nq = (int) g.n_qsa_layers(), ng = (int) g.n_gdn_layers();
986    return {{"gdn_qkv", false, C, Nn, ng, "4393"},           {"gdn_gate", false, ZV, Nn, ng, "4401"},       {"gdn_out", false, Nn, ZV, ng, "4424"},
987            {"ssm_alpha_beta", true, g.ssm_v_heads, Nn, 2 * ng, "4402-4403"},
988            {"qsa_q", false, 2 * QW, Nn, nq, "4448"},        {"qsa_k_v", false, KV, Nn, 2 * nq, "4445-4446"}, {"qsa_out", false, Nn, QW, nq, "4785"},
989            {"idx_k", true, g.idx_key_dim, Nn, nq, "4450"},  {"idx_q", true, IQW, Nn, nq, "4451"},
990            {"hc_down", true, LR, D, 2 * nl, "4336"},        {"hc_up", true, D, LR, 2 * nl, "4345/4366"},   {"hc_inj", true, g.hc, D, 2 * nl, "4368"},
991            {"router", true, g.n_expert, Nn, nl, "4797"},
992            {"shexp_gate_up", false, g.n_ff_shexp, Nn, 2 * nl, "4861-4862"}, {"shexp_down", false, Nn, g.n_ff_shexp, nl, "4864"}};
993}
994uint16_t f2bf(float f) {
995    uint32_t b;
996    std::memcpy(&b, &f, 4);
997    b += 0x7fffu + ((b >> 16) & 1u);
998    return (uint16_t) (b >> 16);
999}
1000float bf2f(uint16_t h) {
1001    const uint32_t b = (uint32_t) h << 16;
1002    float f;
1003    std::memcpy(&f, &b, 4);
1004    return f;
1005}
1006
1007void run_dense_cell(const DenseShape& d, int T, ggml_type ntype, const Opts& o, const Card& card, pf::Gemm& gemm, cudaStream_t st, bool dflt_on,
1008                    double* sum_off, double* sum_on) {
1009    const int64_t N = d.N, K = d.K;
1010    if (!d.bf16 && !fits_blocks(ntype, K)) { std::printf("   %-15s skipped: K=%lld is not a whole number of %s blocks\n", d.name, (long long) K, ggml_type_name(ntype)); return; }
1011    std::mt19937 rng(o.seed + (unsigned) (N * 31 + K));
1012    // weights (BF16 tensor or GGUF blocks), kept on the host as FP32 for the reference
1013    std::vector<float> wf((size_t) (N * K));
1014    Dev w;
1015    if (d.bf16) {
1016        std::vector<uint16_t> wb((size_t) (N * K));
1017        std::uniform_real_distribution<float> u(-0.05f, 0.05f);
1018        for (size_t i = 0; i < wb.size(); ++i) { wb[i] = f2bf(u(rng)); wf[i] = bf2f(wb[i]); }
1019        w = Dev(wb.size() * 2);
1020        ck(cudaMemcpy(w.p, wb.data(), wb.size() * 2, cudaMemcpyHostToDevice), "w");
1021    } else {
1022        const size_t rb = row_size(ntype, K);
1023        std::vector<uint8_t> blk((size_t) N * rb);
1024        fill_matrix(blk.data(), ntype, N, K, rng);
1025        const auto* tr = ggml_get_type_traits(ntype);
1026        for (int64_t r = 0; r < N; ++r) tr->to_float(blk.data() + (size_t) r * rb, wf.data() + (size_t) (r * K), K);
1027        w = Dev(blk.size());
1028        ck(cudaMemcpy(w.p, blk.data(), blk.size(), cudaMemcpyHostToDevice), "w");
1029    }
1030    // activations: N(0,1)-like values with a few large ones, written as BF16 and FP16 images in chunks (no T x K host array); the sample rows are kept in FP32
1031    Dev xbf((size_t) T * K * 2), xh((size_t) T * K * 2);
1032    const int nsamp = std::min(8, T);
1033    std::vector<int> srow;
1034    for (int i = 0; i < nsamp; ++i) srow.push_back((int) ((int64_t) i * (T - 1) / std::max(1, nsamp - 1)));
1035    std::vector<float> xs((size_t) nsamp * (size_t) K);
1036    {
1037        const int64_t chunk = 256;
1038        std::vector<uint16_t> cb((size_t) (chunk * K)), ch((size_t) (chunk * K));
1039        std::uniform_real_distribution<float> u(-1.7320508f, 1.7320508f);
1040        std::uniform_int_distribution<int> pick(0, 199);
1041        for (int64_t r0 = 0; r0 < T; r0 += chunk) {
1042            const int64_t n = std::min<int64_t>(chunk, T - r0);
1043            for (int64_t i = 0; i < n; ++i)
1044                for (int64_t k = 0; k < K; ++k) {
1045                    float v = u(rng) * (pick(rng) == 0 ? 12.0f : 1.0f);
1046                    cb[(size_t) (i * K + k)] = f2bf(v);
1047                    ch[(size_t) (i * K + k)] = ggml_fp32_to_fp16(v);
1048                    for (int s = 0; s < nsamp; ++s) if (srow[(size_t) s] == r0 + i) xs[(size_t) s * (size_t) K + (size_t) k] = v;
1049                }
1050            ck(cudaMemcpy(xbf.as<uint8_t>() + (size_t) r0 * K * 2, cb.data(), (size_t) (n * K) * 2, cudaMemcpyHostToDevice), "x");
1051            ck(cudaMemcpy(xh.as<uint8_t>() + (size_t) r0 * K * 2, ch.data(), (size_t) (n * K) * 2, cudaMemcpyHostToDevice), "x");
1052        }
1053    }
1054    Dev y((size_t) T * N * 4);
1055    ck(cudaDeviceSynchronize(), "uploads");
1056
1057    // the CPU FP32 reference on the sample rows
1058    std::vector<float> ref((size_t) nsamp * (size_t) N);
1059    {
1060        std::vector<std::thread> th;
1061        const int nth = std::max(1, std::min(16, (int) std::thread::hardware_concurrency()));
1062        for (int t = 0; t < nth; ++t)
1063            th.emplace_back([&, t] {
1064                for (int64_t n = t; n < N; n += nth)
1065                    for (int s = 0; s < nsamp; ++s) {
1066                        double a = 0;
1067                        const float* wr = wf.data() + (size_t) (n * K);
1068                        const float* xr = xs.data() + (size_t) s * (size_t) K;
1069                        for (int64_t k = 0; k < K; ++k) a += (double) wr[k] * xr[k];
1070                        ref[(size_t) s * (size_t) N + (size_t) n] = (float) a;
1071                    }
1072            });
1073        for (auto& t : th) t.join();
1074    }
1075    auto run = [&](bool on) {
1076        gemm.set_f16_io(on);
1077        if (d.bf16) gemm.bf16((on && FB_HIP_ON) ? xh.as<uint16_t>() : xbf.as<uint16_t>(), w.as<uint16_t>(), y.as<float>(), T, N, K);
1078        else gemm.native(xh.as<uint16_t>(), (int) ntype, w.p, y.as<float>(), T, N, K);
1079    };
1080    cudaEvent_t ea, eb;
1081    ck(cudaEventCreate(&ea), "event");
1082    ck(cudaEventCreate(&eb), "event");
1083    auto once = [&](bool on) {
1084        ck(cudaEventRecord(ea, st), "record");
1085        run(on);
1086        ck(cudaEventRecord(eb, st), "record");
1087        ck(cudaEventSynchronize(eb), "sync");
1088        float t = 0;
1089        ck(cudaEventElapsedTime(&t, ea, eb), "elapsed");
1090        return t;
1091    };
1092    Err err[2];
1093    uint64_t hsh[2] = {0, 0};
1094    long long nonfin[2] = {0, 0};
1095    for (int on = 0; on < 2; ++on) {
1096        ck(cudaMemset(y.p, 0xff, y.n), "sentinel");
1097        ck(cudaDeviceSynchronize(), "sentinel");
1098        once(on != 0);
1099        std::vector<float> got((size_t) nsamp * (size_t) N);
1100        uint64_t h = 1469598103934665603ull;
1101        for (int s = 0; s < nsamp; ++s) {
1102            ck(cudaMemcpy(got.data() + (size_t) s * (size_t) N, y.as<uint8_t>() + (size_t) srow[(size_t) s] * (size_t) N * 4, (size_t) N * 4, cudaMemcpyDeviceToHost), "download");
1103            const uint32_t* u = (const uint32_t*) (got.data() + (size_t) s * (size_t) N);
1104            for (int64_t c = 0; c < N; ++c) { h = (h ^ u[c]) * 1099511628211ull; nonfin[on] += !std::isfinite(got[(size_t) s * (size_t) N + (size_t) c]); }
1105        }
1106        hsh[on] = h;
1107        err[on] = compare(got, ref, (size_t) nsamp, (int) N);
1108    }
1109    std::vector<float> t_off, t_on;
1110    for (int rep = 0; rep < o.repeats + 2; ++rep) {   // two warm-up rounds, then the timed ones, off and on alternating (the first rotating)
1111        const bool first_on = rep & 1;
1112        const float a = once(first_on), b = once(!first_on);
1113        if (rep < 2) continue;
1114        (first_on ? t_on : t_off).push_back(a);
1115        (first_on ? t_off : t_on).push_back(b);
1116    }
1117    cudaEventDestroy(ea);
1118    cudaEventDestroy(eb);
1119    ck(cudaGetLastError(), "after timing");
1120    const float m_off = median(t_off), m_on = median(t_on);
1121    auto spread = [](const std::vector<float>& v) { return (*std::max_element(v.begin(), v.end()) - *std::min_element(v.begin(), v.end())) / median(v); };
1122    std::printf("   %-15s %-6s T=%-6d N=%-6lld K=%-6lld uses %-3d  off %9.3f ms  on %9.3f ms  off/on %6.3f   err off %.2e/%.2e  on %.2e/%.2e\n", d.name, d.bf16 ? "bf16" : ggml_type_name(ntype), T,
1123                (long long) N, (long long) K, d.uses, m_off, m_on, m_off / m_on, err[0].rms, err[0].worst, err[1].rms, err[1].worst);
1124    std::string cn = card.name;
1125    for (char& c : cn) if (c == ' ') c = '_';
1126    std::printf("RESULT dense=1 gemm=%s kind=%s site=prefill.cpp:%s tokens=%d N=%lld K=%lld uses=%d ms_off=%.3f ms_on=%.3f off_over_on=%.3f spread_off=%.3f spread_on=%.3f repeats=%d "
1127                "err_off=%.3e/%.3e err_on=%.3e/%.3e hash_off=%016llx hash_on=%016llx nonfinite=%lld f16io_effective=%d f16io_default_here=%d card=%s arch=%s\n",
1128                d.name, d.bf16 ? "bf16" : ggml_type_name(ntype), d.site, T, (long long) N, (long long) K, d.uses, m_off, m_on, m_off / m_on, spread(t_off), spread(t_on), o.repeats,
1129                err[0].rms, err[0].worst, err[1].rms, err[1].worst, (unsigned long long) hsh[0], (unsigned long long) hsh[1], nonfin[0] + nonfin[1], FB_HIP_ON ? 1 : 0,
1130                dflt_on ? 1 : 0, cn.c_str(), card.arch.c_str());
1131    std::fflush(stdout);
1132    *sum_off += (double) m_off * d.uses;
1133    *sum_on += (double) m_on * d.uses;
1134}
1135}  // namespace
1136
1137// --real: one line of the pack's native_experts.txt ("layer gu_type d_type offset blob_bytes gate_off up_off down_off": absolute offsets of the three stacked expert tensors in the GGUF shard)
1138struct PackRow {
1139    int layer = 0, gu = 0, d = 0;
1140    unsigned long long blob = 0, gate_off = 0, up_off = 0, down_off = 0;
1141};
1142std::vector<PackRow> read_pack(const std::string& path) {
1143    std::vector<PackRow> v;
1144    std::ifstream in(path);
1145    if (!in) throw std::runtime_error("--real-pack: cannot open " + path);
1146    std::string line;
1147    while (std::getline(in, line)) {
1148        if (line.empty() || line[0] == '#') continue;
1149        PackRow r;
1150        unsigned long long off = 0;
1151        if (std::sscanf(line.c_str(), "%d %d %d %llu %llu %llu %llu %llu", &r.layer, &r.gu, &r.d, &off, &r.blob, &r.gate_off, &r.up_off, &r.down_off) == 8) v.push_back(r);
1152    }
1153    return v;
1154}
1155
1156// the dump of STRATA_DUMP_MOE_INPUT (one file per layer: {T, N, K} int64, T x N floats, T x K expert ids) and the layer's experts (the ones some row routes to) from the GGUF
1157RealLayer load_real(const Opts& o, const PackRow& pr, const Pair& p, const Shape& s) {
1158    RealLayer rl;
1159    rl.layer = pr.layer;
1160    const std::string dump = o.real_dir + "/moe.L" + std::to_string(pr.layer);
1161    std::ifstream f(dump, std::ios::binary);
1162    if (!f) throw std::runtime_error("no dump " + dump);
1163    int64_t hdr[3] = {};
1164    f.read((char*) hdr, sizeof hdr);
1165    if (!f || hdr[1] != s.N || hdr[2] != s.K || hdr[0] <= 0) throw std::runtime_error("dump " + dump + ": header T " + std::to_string(hdr[0]) + " N " + std::to_string(hdr[1]) + " K " + std::to_string(hdr[2]));
1166    rl.T = (int) hdr[0];
1167    rl.x.resize((size_t) rl.T * s.N);
1168    rl.ids.resize((size_t) rl.T * s.K);
1169    f.read((char*) rl.x.data(), (std::streamsize) (rl.x.size() * 4));
1170    f.read((char*) rl.ids.data(), (std::streamsize) (rl.ids.size() * 4));
1171    if (!f) throw std::runtime_error("dump " + dump + ": short");
1172    const Geo geo(p, s);
1173    const size_t gate_per_e = geo.up_off, down_per_e = geo.bytes - geo.down_off;
1174    std::vector<char> need((size_t) s.E, 0);
1175    for (int32_t e : rl.ids) {
1176        if (e < 0 || e >= s.E) throw std::runtime_error("dump " + dump + ": expert id " + std::to_string(e));
1177        need[(size_t) e] = 1;
1178    }
1179    std::ifstream g(o.real_gguf, std::ios::binary);
1180    if (!g) throw std::runtime_error("--real-gguf: cannot open " + o.real_gguf);
1181    rl.blob.assign((size_t) s.E, std::vector<uint8_t>());
1182    for (int e = 0; e < s.E; ++e) {
1183        if (!need[(size_t) e]) continue;
1184        std::vector<uint8_t>& b = rl.blob[(size_t) e];
1185        b.resize(geo.bytes);
1186        const unsigned long long at[3] = {pr.gate_off + (unsigned long long) e * gate_per_e, pr.up_off + (unsigned long long) e * gate_per_e, pr.down_off + (unsigned long long) e * down_per_e};
1187        const size_t dst[3] = {0, geo.up_off, geo.down_off}, len[3] = {gate_per_e, gate_per_e, down_per_e};
1188        for (int k = 0; k < 3; ++k) {
1189            g.seekg((std::streamoff) at[k]);
1190            g.read((char*) b.data() + dst[k], (std::streamsize) len[k]);
1191            if (!g) throw std::runtime_error("--real-gguf: short read of layer " + std::to_string(pr.layer) + " expert " + std::to_string(e));
1192        }
1193    }
1194    return rl;
1195}
1196
1197int main(int argc, char** argv) {
1198    try {
1199        Opts o;
1200        for (int i = 1; i < argc; ++i) {
1201            const char* a = argv[i];
1202            if (std::string v = arg_after(a, "--shape="); !v.empty()) {
1203                if (v == "flash") o.shape = {2560, 640, 512, 10, "flash"};
1204                else if (v == "q36") o.shape = {2048, 512, 256, 8, "q36"};
1205                else {
1206                    const std::vector<int> d = parse_ints(v);
1207                    if (d.size() != 4 || d[0] <= 0 || d[1] <= 0 || d[2] <= 0 || d[3] <= 0 || d[3] > d[2]) throw std::runtime_error("--shape=flash|q36|N,FF,E,K");
1208                    o.shape = {d[0], d[1], d[2], d[3], "custom"};
1209                }
1210            }
1211            else if (std::string v2 = arg_after(a, "--tokens="); !v2.empty()) { o.tokens = parse_ints(v2); o.tokens_set = true; }
1212            else if (std::string va = arg_after(a, "--dense-type="); !va.empty()) o.dense_type = va;
1213            else if (std::string v3 = arg_after(a, "--only="); !v3.empty()) o.only.push_back(v3);
1214            else if (std::string v4 = arg_after(a, "--repeats="); !v4.empty()) o.repeats = std::max(1, std::atoi(v4.c_str()));
1215            else if (std::string v5 = arg_after(a, "--warm-ms="); !v5.empty()) o.warm_ms = (float) std::atof(v5.c_str());
1216            else if (std::string v6 = arg_after(a, "--skew="); !v6.empty()) o.skew = std::atof(v6.c_str());
1217            else if (std::string v7 = arg_after(a, "--experts="); !v7.empty()) o.experts = std::atoi(v7.c_str());
1218            else if (std::string v8 = arg_after(a, "--sample="); !v8.empty()) o.sample = std::max(1, std::atoi(v8.c_str()));
1219            else if (std::string v9 = arg_after(a, "--seed="); !v9.empty()) o.seed = (unsigned) std::atoll(v9.c_str());
1220            else if (!std::strcmp(a, "--all")) o.all = true;
1221            else if (!std::strcmp(a, "--list")) o.list = true;
1222            else if (!std::strcmp(a, "--grouped")) o.grouped = true;
1223            else if (std::string v10 = arg_after(a, "--i8-tm="); !v10.empty()) {
1224                o.i8 = true;
1225                for (size_t q = 0; q < v10.size();) { o.i8_tms.push_back(std::atoi(v10.c_str() + q)); q = v10.find(',', q) == std::string::npos ? v10.size() : v10.find(',', q) + 1; }
1226            }
1227            else if (!std::strcmp(a, "--i8")) o.i8 = true;
1228            else if (!std::strcmp(a, "--no-grp")) o.no_grp = true;
1229            else if (!std::strcmp(a, "--no-mmq")) o.no_mmq = true;
1230            else if (!std::strcmp(a, "--no-fused")) o.no_fused = true;
1231            else if (!std::strcmp(a, "--no-fp16")) o.no_fp16 = true;
1232            else if (!std::strcmp(a, "--no-ref")) o.no_ref = true;
1233            else if (!std::strcmp(a, "--quick")) o.quick = true;
1234            else if (!std::strcmp(a, "--dense")) o.dense = true;
1235            else if (std::string vr = arg_after(a, "--real="); !vr.empty()) o.real_dir = vr;
1236            else if (std::string vp = arg_after(a, "--real-pack="); !vp.empty()) o.real_pack = vp;
1237            else if (std::string vg = arg_after(a, "--real-gguf="); !vg.empty()) o.real_gguf = vg;
1238            else if (std::string vl = arg_after(a, "--real-layers="); !vl.empty()) o.real_layers = parse_ints(vl);
1239            else { std::fprintf(stderr, "unknown argument %s (see the head of tests/cuda/prefill_expert_paths_bench.cpp)\n", a); return 1; }
1240        }
1241        if (o.experts > 0) o.shape.E = std::max(o.experts, o.shape.K);
1242        if (o.quick) { o.tokens = {512}; o.repeats = 3; o.warm_ms = 100.0f; o.sample = 8; if (o.only.empty()) o.only.push_back("IQ3_XXS / IQ4_NL"); }
1243        const std::vector<Pair>& pairs = all_pairs();
1244        if (o.list) {
1245            for (const Pair& p : pairs) std::printf("%s\n", p.name);
1246            return 0;
1247        }
1248        // the opt-in switches that select the fused kernels and MMQ's K-quant library (the engine reads them; unset ones are set here, set ones are kept)
1249        defenv("STRATA_PF_FUSED", "1");
1250        defenv("STRATA_PF_FUSED_KQ", "1");
1251        defenv("STRATA_PF_FUSED_Q50", "1");
1252        defenv("STRATA_PF_FUSED_Q8D", "1");
1253        defenv("STRATA_PF_FUSED_Q8GU", "1");
1254        defenv("STRATA_PF_FUSED_Q6K", "1");
1255        defenv("STRATA_MMQ_KQ", "1");
1256
1257        int n = 0;
1258        if (cudaGetDeviceCount(&n) != cudaSuccess || n == 0) { std::printf("no GPU device: skipped\n"); return 77; }
1259        cudaDeviceProp prop{};
1260        ck(cudaGetDeviceProperties(&prop, 0), "device properties");
1261        Card card;
1262        card.name = prop.name;
1263        card.major = prop.major;
1264        card.minor = prop.minor;
1265        card.total = prop.totalGlobalMem;
1266#if defined(FB_HIP)
1267        card.hip = true;
1268        card.arch = prop.gcnArchName;
1269#else
1270        card.arch = "sm_" + std::to_string(prop.major) + std::to_string(prop.minor);
1271#endif
1272        size_t fr_free = 0, fr_tot = 0;
1273        cudaMemGetInfo(&fr_free, &fr_tot);
1274        const Shape s0 = o.shape;
1275        // the FP16 path's swiglu_interleaved and the few-row record are written for the compiled geometry (prefill.cpp is, too): any other shape has no FP16 column
1276        const bool fp16_shape_ok = s0.N == (int) fused::kMoeEmbd && s0.FF == (int) fused::kMoeFF;
1277        // fewrows.hpp's default: off unless STRATA_PF_FEWROWS, except on the Tesla P100 (cc 6.0) where gp100_prompt_default.hpp turns it on with the FP16 path
1278        const char* few_env = std::getenv("STRATA_PF_FEWROWS");
1279        const bool fewrows_dflt = pf::fewrows_switch(few_env, card.major == 6 && card.minor == 0);
1280        std::printf("prefill_expert_paths_bench: %s (%s), %.1f GiB (%.1f free), device 0 of %d\n", card.name.c_str(), card.arch.c_str(), (double) card.total / 1073741824.0,
1281                    (double) fr_free / 1073741824.0, n);
1282        std::printf("  shape %s: n_embd %d, n_ff %d, %d experts, top %d; compiled geometry %d x %d (FP16 column %s); MMQ in this build: %s; fused kernels for an IQ3_XXS / IQ4_NL layer here: %s\n",
1283                    s0.name.c_str(), s0.N, s0.FF, s0.E, s0.K, (int) fused::kMoeEmbd, (int) fused::kMoeFF, fp16_shape_ok ? "on" : "off: this shape is not the compiled one",
1284                    mmq::built() ? "yes" : "no", (fused::native_supported(GGML_TYPE_IQ3_XXS, GGML_TYPE_IQ4_NL) ? "yes" : "no"));
1285        std::printf("  few-row experts (<= %d rows) on the quantized kernels by default here: %s (STRATA_PF_FEWROWS=%s); routing %s; repeats %d after %.0f ms warm-up\n", pf::kFewRows,
1286                    fewrows_dflt ? "yes" : "no", few_env ? few_env : "unset", o.skew > 0 ? "Zipf" : "uniform", o.repeats, (double) o.warm_ms);
1287
1288        cudaStream_t st = nullptr;
1289        ck(cudaStreamCreateWithFlags(&st, cudaStreamNonBlocking), "stream");
1290        // the engine's Gemm, set up as Prefill::init sets it (prefill.cpp: init_external with the 32 MiB scratch and workspace, f16 I/O where the card wants it)
1291        pf::Gemm gemm;
1292        Dev gscratch((size_t) GEMM_SCRATCH * 2), gws(GEMM_WS);
1293        {
1294            std::string err;
1295            if (!gemm.init_external(st, gscratch.as<uint16_t>(), GEMM_SCRATCH, gws.p, GEMM_WS, err)) throw std::runtime_error("Gemm::init_external: " + err);
1296            const bool f16io = pf::prompt_f16();
1297            gemm.set_f16_io(f16io);
1298            pf::set_act_f16(f16io);
1299            std::printf("  Gemm: prompt_f16() %s\n", f16io ? "on (FP16 in / FP16 out)" : "off");
1300        }
1301
1302        if (o.dense) {   // the dense prompt GEMMs, FP16 io off and on (no experts, no pairs)
1303            ggml_type nt = GGML_TYPE_COUNT;
1304            for (int t = 0; t < (int) GGML_TYPE_COUNT; ++t) {
1305                const char* nm = ggml_type_name((ggml_type) t);
1306                if (nm != nullptr && nospace(nm) == nospace(o.dense_type.c_str())) nt = (ggml_type) t;
1307            }
1308            if (nt == GGML_TYPE_COUNT || ggml_get_type_traits(nt)->to_float == nullptr) throw std::runtime_error("--dense-type=NAME: a ggml type with a to_float, e.g. Q8_0");
1309            if (!o.tokens_set) o.tokens = {2048, 8192, 20000};
1310            if (o.quick) { o.tokens = {512}; if (o.only.size() == 1 && o.only[0] == "IQ3_XXS / IQ4_NL") o.only.clear(); }   // (--quick put its expert pair in --only)
1311            const bool dflt_on = pf::prompt_f16();
1312            std::printf("  dense mode: Flash-Next (compiled geometry) projection GEMMs, native weights %s; FP16 io off = Gemm as the engine runs it by default, on = Gemm::set_f16_io(true) (STRATA_HIP_PROMPT_F16=1);\n"
1313                        "  prompt_f16() here: %s (the engine turns it on only when STRATA_HIP_PROMPT_F16=1 on a HIP card); effect of set_f16_io on this build: %s\n",
1314                        ggml_type_name(nt), dflt_on ? "on" : "off", FB_HIP_ON ? "yes (HIP)" : "none (CUDA: both columns are the same code, the ratio is the noise floor)");
1315            const std::vector<DenseShape> ds = dense_shapes();
1316            for (int T : o.tokens) {
1317                double so = 0, sn = 0;
1318                int ran = 0;
1319                std::printf("== dense GEMMs at T=%d tokens\n", T);
1320                for (const DenseShape& d : ds) {
1321                    if (!o.only.empty()) {
1322                        bool take = false;
1323                        for (const std::string& k : o.only) take |= nospace(d.name).find(nospace(k.c_str())) != std::string::npos;
1324                        if (!take) continue;
1325                    }
1326                    try {
1327                        run_dense_cell(d, T, nt, o, card, gemm, st, dflt_on, &so, &sn);
1328                        ++ran;
1329                    } catch (const std::exception& e) {
1330                        cudaGetLastError();
1331                        std::printf("   %-15s T=%d: SKIPPED (%s)\n", d.name, T, e.what());
1332                        if (std::strstr(e.what(), "cudaMalloc") == nullptr) throw;
1333                    }
1334                }
1335                if (ran > 0) std::printf("RESULT dense_total=1 tokens=%d gemms=%d ms_off_per_chunk=%.2f ms_on_per_chunk=%.2f off_over_on=%.3f (sum over the shapes x uses per chunk) arch=%s\n", T, ran, so, sn, sn > 0 ? so / sn : 0.0, card.arch.c_str());
1336            }
1337            ck(cudaStreamDestroy(st), "destroy");
1338            return 0;
1339        }
1340        if (!o.real_dir.empty()) {   // --real: one cell per layer of the dump, the layer's own pair, rows, routing and experts
1341            if (o.real_pack.empty() || o.real_gguf.empty()) throw std::runtime_error("--real needs --real-pack=native_experts.txt and --real-gguf=SHARD.gguf");
1342            const std::vector<PackRow> pack = read_pack(o.real_pack);
1343            int cells = 0, skipped = 0;
1344            for (const PackRow& pr : pack) {
1345                if (!o.real_layers.empty() && std::find(o.real_layers.begin(), o.real_layers.end(), pr.layer) == o.real_layers.end()) continue;
1346                const Pair* pp = nullptr;
1347                for (const Pair& q : pairs) if ((int) q.gu == pr.gu && (int) q.d == pr.d) pp = &q;
1348                if (pp == nullptr) { std::printf("== REAL layer %d: gate/up type %d, down type %d is not a pair of this bench: skipped\n", pr.layer, pr.gu, pr.d); ++skipped; continue; }
1349                try {
1350                    const RealLayer rl = load_real(o, pr, *pp, s0);
1351                    run_cell(*pp, s0, rl.T, o, card, gemm, st, fp16_shape_ok, fewrows_dflt, &rl);
1352                    ++cells;
1353                } catch (const std::exception& e) {
1354                    cudaGetLastError();
1355                    std::printf("== REAL layer %d: SKIPPED (%s)\n", pr.layer, e.what());
1356                    ++skipped;
1357                    if (std::strstr(e.what(), "cudaMalloc") == nullptr && std::strstr(e.what(), "dump") == nullptr) throw;
1358                }
1359                std::fflush(stdout);
1360            }
1361            ck(cudaStreamDestroy(st), "destroy");
1362            std::printf("prefill_expert_paths_bench --real: %d layers run, %d skipped\n", cells, skipped);
1363            return 0;
1364        }
1365        std::vector<Pair> sel;
1366        for (size_t i = 0; i < pairs.size(); ++i) {
1367            bool take = false;
1368            if (!o.only.empty()) for (const std::string& k : o.only) take |= nospace(pairs[i].name).find(nospace(k.c_str())) != std::string::npos;   // (spaces ignored: --only=IQ3_XXS/IQ4_NL)
1369            else take = o.all || i < (size_t) kDefaultPairs;
1370            if (take) sel.push_back(pairs[i]);
1371        }
1372        if (sel.empty()) throw std::runtime_error("no pair matches --only (see --list)");
1373        int cells = 0, skipped = 0;
1374        for (const Pair& p : sel) {
1375            if (!fits_blocks(p.gu, s0.N) || !fits_blocks(p.d, s0.FF) || !fits_blocks(p.gu, s0.N)) {
1376                std::printf("== %s: skipped, the rows (%d / %d values) are not whole blocks of the format\n", p.name, s0.N, s0.FF);
1377                ++skipped;
1378                continue;
1379            }
1380            for (int T : o.tokens) {
1381                try {
1382                    run_cell(p, s0, T, o, card, gemm, st, fp16_shape_ok, fewrows_dflt);
1383                    ++cells;
1384                } catch (const std::exception& e) {
1385                    cudaGetLastError();
1386                    std::printf("== %s T=%d: SKIPPED (%s)\n", p.name, T, e.what());
1387                    std::fflush(stdout);
1388                    ++skipped;
1389                    if (std::strstr(e.what(), "cudaMalloc") == nullptr) throw;   // only a failed allocation is a skip; anything else ends the run
1390                }
1391            }
1392        }
1393        ck(cudaStreamDestroy(st), "destroy");
1394        std::printf("prefill_expert_paths_bench: %d cells run, %d skipped\n", cells, skipped);
1395        return 0;
1396    } catch (const std::exception& e) {
1397        std::fprintf(stderr, "prefill_expert_paths_bench failed: %s\n", e.what());
1398        return 1;
1399    }
1400}