okami.mom/strata

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

Niko1221Trial2 merge f-0291-pr-amd (82eaeb422): verify.cpp head keeps both: pr-nv2's chunked head (h0/HT, up to 8 columns a launch) and pr-amd's fused q8_1 image (q8_head, image at the chunk's own xq_ offset)62db0bf10

main
24.7 KiB502 linesraw
1// src/kernels/expdec_bench.cpp - the VRAM experts of a decode verify window: the default grouped kernels against
2// EXPDEC (STRATA_EXPDEC=1, docs/EXPERTDEC.md), bit for bit and in microseconds, per card, per T, per format pair.
3//
4//     build/expdec_bench [reps = 300] [device = -1 (all)] [groups = 20] [pairs = all] [choices = def,dec,dec:r2,dec:b4,dec:r2:b4] [shape = real]
5//
6// The model's routed expert formats at its geometry (n_embd 2560, n_ff 640): gate/up IQ2_XXS (16), IQ2_XS (17), IQ3_XXS
7// (18), IQ3_S (21), IQ2_S (22); down IQ4_NL (20), Q2_0 (42).  `pairs` is a comma list of gu/down type ids ("21/20,16/42")
8// or "all" (the 10 pairs).  `choices` is a comma list of kernel choices:
9//   def                     the default kernels (STRATA_EXPDEC off); the reference for the bitwise check
10//   dec[:r<n>][:d<n>][:b<n>][:w<n>][:x<n>][:g<n>][:h<n>][:m<n>]
11//                           EXPDEC with r = gate/up rows per lane (1, 2), d = down rows per lane (1, 2, 4), b = the
12//                           gate/up kernel's min blocks per SM (2 | 4), w = 1 EXPDEC for the down too (the engine's
13//                           default is the gate/up only), x = 1 also for the IQ4_NL down, g / h = gate/up / down rows
14//                           per block (0 = auto), m = the auto rule's minimum blocks; a missing field takes the
15//                           engine's value (the environment's STRATA_EXPDEC_* or its default)
16// `shape`: real = every token picks 10 experts out of `groups` distinct ones (as fp_expert_bench: T=1 10 groups x 1
17// entry, T=2 20 x 1, T=4 20 groups with 40 entries); single = 10 T groups of one entry each (the same entries as `real`
18// spread over distinct experts); both = the two, plus the decomposition at the end: per-expert cost a = (single T=4 -
19// real T=2) / 20 and per-entry cost b = (real T=4 - real T=2) / 20, in us, for every choice (groups = 20 only).
20//
21// Per (device, pair, T, shape, choice): the output buffer against `def`'s, bit for bit (memcmp), and the median of
22// 5 rounds of `reps` back-to-back `native_expert_grouped` calls with CUDA events: the whole call (gate/up + SwiGLU +
23// q8_1 + down), then the gate/up phase and the down phase alone (native_expert_set_mode's phase, 3 rounds each).
24// The experts rotate over a pool of >= 96 MB of distinct synthetic blobs (random bytes, sane fp16 block scales), so
25// every call reads its weights cold from DRAM as the decode does each layer.
26//
27// One line per cell:  dev T shape gu/d choice all_us gu_us down_us GB/s pct identical|DIFFERENT   (GB/s = groups x blob
28// bytes / all_us; pct = of the peak DRAM bandwidth 2 x memory clock x bus width / 8).  Lines starting with '#' are
29// context.  Exit code 1 if any choice differs or a CUDA error occurred.  GPU time only.
30#include "strata/kernels/iq_kernels.hpp"
31
32#include <cuda_runtime.h>
33
34#include <algorithm>
35#include <array>
36#include <cmath>
37#include <cstdint>
38#include <cstdio>
39#include <cstdlib>
40#include <cstring>
41#include <map>
42#include <random>
43#include <string>
44#include <tuple>
45#include <vector>
46
47namespace K = strata::kernels;
48
49namespace {
50
51constexpr int kEmbd = 2560, kFf = 640, kTop = 10, kMaxT = 4;
52constexpr int kMaxEntries = kMaxT * kTop;
53
54struct Pair { int gu, d; };
55const Pair kModelPairs[] = { {16, 20}, {17, 20}, {18, 20}, {21, 20}, {22, 20}, {16, 42}, {17, 42}, {18, 42}, {21, 42}, {22, 42} };
56
57const char* type_name(int t) {
58    switch (t) {
59        case 16: return "IQ2_XXS"; case 17: return "IQ2_XS"; case 18: return "IQ3_XXS"; case 21: return "IQ3_S";
60        case 22: return "IQ2_S"; case 20: return "IQ4_NL"; case 42: return "Q2_0"; default: return "?";
61    }
62}
63int qk_of(int t) { return t == 20 ? 32 : t == 42 ? 64 : 256; }
64
65struct Choice {
66    std::string name;
67    bool dec = false;
68    K::NativeExpertExpdecParams p;   // only explicitly specified fields set; unspecified fields keep their sentinels
69};
70
71K::NativeExpertExpdecParams resolve_choice_params(const K::NativeExpertExpdecParams& base, const Choice& c) {
72    K::NativeExpertExpdecParams p = base;
73    if (c.p.gu_rows_per_lane > 0) p.gu_rows_per_lane = c.p.gu_rows_per_lane;
74    if (c.p.down_rows_per_lane > 0) p.down_rows_per_lane = c.p.down_rows_per_lane;
75    if (c.p.gu_min_blocks_per_sm > 0) p.gu_min_blocks_per_sm = c.p.gu_min_blocks_per_sm;
76    if (c.p.down_iq4_nl >= 0) p.down_iq4_nl = c.p.down_iq4_nl;
77    if (c.p.down >= 0) p.down = c.p.down;
78    if (c.p.gu_rows_per_block >= 0) p.gu_rows_per_block = c.p.gu_rows_per_block;
79    if (c.p.down_rows_per_block >= 0) p.down_rows_per_block = c.p.down_rows_per_block;
80    if (c.p.min_blocks > 0) p.min_blocks = c.p.min_blocks;
81    return p;
82}
83
84// "def" | "dec[:r<n>][:d<n>][:b<n>][:x<n>][:g<n>][:h<n>][:m<n>]"; false on anything else
85bool parse_choice(const std::string& s, Choice& c) {
86    c = Choice{};
87    c.name = s;
88    if (s == "def") return true;
89    if (s.rfind("dec", 0) != 0) return false;
90    c.dec = true;
91    size_t i = 3;
92    while (i < s.size()) {
93        if (s[i] != ':') return false;
94        size_t j = s.find(':', i + 1);
95        if (j == std::string::npos) j = s.size();
96        if (j < i + 3) return false;
97        const char key = s[i + 1];
98        const int v = std::atoi(s.substr(i + 2, j - i - 2).c_str());
99        switch (key) {
100            case 'r': if (v != 1 && v != 2) return false; c.p.gu_rows_per_lane = v; break;
101            case 'd': if (v != 1 && v != 2 && v != 4) return false; c.p.down_rows_per_lane = v; break;
102            case 'b': if (v != 2 && v != 4) return false; c.p.gu_min_blocks_per_sm = v; break;
103            case 'x': if (v != 0 && v != 1) return false; c.p.down_iq4_nl = v; break;
104            case 'w': if (v != 0 && v != 1) return false; c.p.down = v; break;   // EXPDEC for the down (device default when omitted)
105            case 'g': if (v < 0) return false; c.p.gu_rows_per_block = v; break;
106            case 'h': if (v < 0) return false; c.p.down_rows_per_block = v; break;
107            case 'm': if (v <= 0) return false; c.p.min_blocks = v; break;
108            default: return false;
109        }
110        i = j;
111    }
112    return true;
113}
114
115void apply_choice(const K::NativeExpertExpdecParams& base, const Choice& c) {
116    K::native_expert_set_expdec(c.dec ? 1 : 0);
117    K::native_expert_set_expdec_params(resolve_choice_params(base, c));
118}
119
120bool g_cuda_error = false;
121
122bool ck(cudaError_t e, const char* what) {
123    if (e == cudaSuccess) return true;
124    std::printf("CUDA: %s: %s\n", what, cudaGetErrorString(e));
125    g_cuda_error = true;
126    return false;
127}
128
129uint16_t sane_half(std::mt19937& rng) {   // a finite fp16 of magnitude ~2^-10 .. 2^-6
130    const uint32_t r = rng();
131    return (uint16_t) (((r >> 31) << 15) | ((5u + (r >> 10) % 5u) << 10) | (r & 0x3ffu));
132}
133
134// One expert blob [gate rows | up rows | down rows]: random bytes (any qs / qh / signs / scales nibble / grid index /
135// IQ4_NL nibble / Q2_0 pair is a valid code) with a sane fp16 `d` in every block (offset 0 of every format's block).
136void fill_blob(uint8_t* b, const K::NativeExpertLayout& L, std::mt19937& rng) {
137    for (size_t i = 0; i + 4 <= L.bytes; i += 4) {
138        const uint32_t r = rng();
139        std::memcpy(b + i, &r, 4);
140    }
141    const size_t gu_block = K::iq_row_bytes(L.gu_type, qk_of(L.gu_type)), d_block = K::iq_row_bytes(L.d_type, qk_of(L.d_type));
142    const size_t gu_blocks = (size_t) 2 * (size_t) L.n_ff * (size_t) (L.n_embd / qk_of(L.gu_type));
143    for (size_t k = 0; k < gu_blocks; ++k) {
144        const uint16_t h = sane_half(rng);
145        std::memcpy(b + k * gu_block, &h, 2);
146    }
147    const size_t d_blocks = (size_t) L.n_embd * (size_t) (L.n_ff / qk_of(L.d_type));
148    for (size_t k = 0; k < d_blocks; ++k) {
149        const uint16_t h = sane_half(rng);
150        std::memcpy(b + L.down_off + k * d_block, &h, 2);
151    }
152}
153
154struct Window {
155    int groups = 0, entries = 0;
156    std::vector<int32_t> start, tok, dst;   // group g: entries [start[g], start[g + 1]); tok = token, dst = out row
157};
158
159// real: T tokens, kTop experts each, `groups_req` distinct experts in all (capped at kTop * T, floored at kTop).
160// Expert j is forced onto token j % T so that every group has at least one entry; the rest of each token's picks are
161// random.
162Window build_real(int T, int groups_req, std::mt19937& rng) {
163    Window w;
164    const int G = std::min(std::max(groups_req, kTop), kTop * T);
165    std::vector<std::vector<int>> picks((size_t) G);
166    for (int k = 0; k < T; ++k) {
167        std::vector<char> in((size_t) G, 0);
168        int cnt = 0;
169        for (int j = k; j < G; j += T) { in[(size_t) j] = 1; ++cnt; }
170        std::vector<int> rest;
171        for (int j = 0; j < G; ++j)
172            if (!in[(size_t) j]) rest.push_back(j);
173        std::shuffle(rest.begin(), rest.end(), rng);
174        for (size_t i = 0; cnt < kTop; ++i, ++cnt) in[(size_t) rest[i]] = 1;
175        for (int j = 0; j < G; ++j)
176            if (in[(size_t) j]) picks[(size_t) j].push_back(k);
177    }
178    w.groups = G;
179    w.start.push_back(0);
180    for (int g = 0; g < G; ++g) {
181        for (int k : picks[(size_t) g]) {
182            w.tok.push_back(k);
183            w.dst.push_back((int32_t) w.dst.size());
184        }
185        w.start.push_back((int32_t) w.dst.size());
186    }
187    w.entries = (int) w.dst.size();
188    return w;
189}
190// single: kTop T groups of one entry each (token g % T)
191Window build_single(int T) {
192    Window w;
193    w.groups = kTop * T;
194    w.start.push_back(0);
195    for (int g = 0; g < w.groups; ++g) {
196        w.tok.push_back(g % T);
197        w.dst.push_back(g);
198        w.start.push_back(g + 1);
199    }
200    w.entries = w.groups;
201    return w;
202}
203
204struct DevMem {
205    std::vector<void*> ptrs;
206    ~DevMem() { for (void* p : ptrs) cudaFree(p); }
207    void* alloc(size_t n) {
208        void* p = nullptr;
209        if (!ck(cudaMalloc(&p, n), "malloc")) return nullptr;
210        ptrs.push_back(p);
211        return p;
212    }
213};
214
215struct StreamEvents {
216    cudaStream_t s = nullptr;
217    cudaEvent_t a = nullptr, b = nullptr;
218    ~StreamEvents() {
219        if (a) cudaEventDestroy(a);
220        if (b) cudaEventDestroy(b);
221        if (s) cudaStreamDestroy(s);
222    }
223};
224
225// (device, pair gu, pair d, T, shape, choice) -> {all, gu, down} us
226using Key = std::tuple<int, int, int, int, std::string, std::string>;
227std::map<Key, std::array<double, 3>> g_times;
228
229bool run_device(int dev, const K::NativeExpertExpdecParams& dev_params, int reps, int groups_req,
230                const std::vector<uint8_t>& pool, size_t P, size_t stride, const std::vector<float>& xh,
231                const K::NativeExpertLayout& L, const Pair& pair, const std::vector<Choice>& choices,
232                const std::vector<std::string>& shapes, long long& bad) {
233    if (!ck(cudaSetDevice(dev), "set device")) return false;
234    cudaDeviceProp pr{};
235    cudaGetDeviceProperties(&pr, dev);
236    std::printf("# device %d: %s (sm_%d%d, %d SMs, L2 %d KB), %d reps x 5 rounds, <= %d groups, pool %d blobs x %.2f MB\n", dev,
237                pr.name, pr.major, pr.minor, pr.multiProcessorCount, pr.l2CacheSize / 1024, reps, groups_req, (int) P,
238                (double) L.bytes / 1e6);
239    int mclk_khz = 0, bus_bits = 0;
240    cudaDeviceGetAttribute(&mclk_khz, cudaDevAttrMemoryClockRate, dev);
241    cudaDeviceGetAttribute(&bus_bits, cudaDevAttrGlobalMemoryBusWidth, dev);
242    const double peak = 2.0 * (double) mclk_khz * 1e3 * (double) bus_bits / 8.0;   // bytes / s
243    std::printf("# device %d peak DRAM bandwidth %.1f GB/s (memory clock %d kHz, bus %d bit)\n", dev, peak / 1e9, mclk_khz, bus_bits);
244    const int gmax = kMaxEntries;
245    DevMem mem;
246    auto* dpool = (uint8_t*) mem.alloc(pool.size());
247    auto* dx = (float*) mem.alloc(xh.size() * sizeof(float));
248    void* dxq = mem.alloc((size_t) kMaxT * kEmbd / 32 * 36);
249    void* dscr = mem.alloc(K::native_expert_scratch_bytes(kMaxEntries, kFf));
250    auto* dout = (float*) mem.alloc((size_t) kMaxEntries * kEmbd * sizeof(float));
251    auto* dptr = (unsigned long long*) mem.alloc(P * (size_t) gmax * sizeof(unsigned long long));
252    auto* dstart = (int32_t*) mem.alloc((size_t) (gmax + 1) * sizeof(int32_t));
253    auto* dn = (int32_t*) mem.alloc(sizeof(int32_t));
254    auto* ddst = (int32_t*) mem.alloc((size_t) kMaxEntries * sizeof(int32_t));
255    auto* dtok = (int32_t*) mem.alloc((size_t) kMaxEntries * sizeof(int32_t));
256    if (!dpool || !dx || !dxq || !dscr || !dout || !dptr || !dstart || !dn || !ddst || !dtok) return false;
257    StreamEvents se;
258    if (!ck(cudaStreamCreate(&se.s), "stream") || !ck(cudaEventCreate(&se.a), "event") ||
259        !ck(cudaEventCreate(&se.b), "event"))
260        return false;
261    void* stream = (void*) se.s;
262    if (!ck(cudaMemcpy(dpool, pool.data(), pool.size(), cudaMemcpyHostToDevice), "copy pool") ||
263        !ck(cudaMemcpy(dx, xh.data(), xh.size() * sizeof(float), cudaMemcpyHostToDevice), "copy x"))
264        return false;
265    K::quantize_q8_1_rows(dx, kMaxT, kEmbd, dxq, stream);
266    if (!ck(cudaStreamSynchronize(se.s), "quantize")) return false;
267
268    std::mt19937 rng(20261012u);
269    bool ok = true;
270    for (int T = 1; T <= kMaxT && ok; ++T) {
271        for (const std::string& shape : shapes) {
272            if (!ok) break;
273            const Window w = shape == "single" ? build_single(T) : build_real(T, groups_req, rng);
274            const int G = w.groups, NE = w.entries;
275            // call i reads G experts starting at blob (i * G) % P: a fresh set until the pool wraps (>= 96 MB later)
276            std::vector<unsigned long long> hp(P * (size_t) G);
277            for (size_t i = 0; i < P; ++i)
278                for (int g = 0; g < G; ++g)
279                    hp[i * (size_t) G + (size_t) g] = (unsigned long long) (dpool + ((i * (size_t) G + (size_t) g) % P) * stride);
280            ok = ck(cudaMemcpy(dptr, hp.data(), hp.size() * sizeof(unsigned long long), cudaMemcpyHostToDevice), "copy ptrs") &&
281                 ck(cudaMemcpy(dstart, w.start.data(), w.start.size() * sizeof(int32_t), cudaMemcpyHostToDevice), "copy start") &&
282                 ck(cudaMemcpy(dn, &G, sizeof(int32_t), cudaMemcpyHostToDevice), "copy n") &&
283                 ck(cudaMemcpy(ddst, w.dst.data(), w.dst.size() * sizeof(int32_t), cudaMemcpyHostToDevice), "copy dst") &&
284                 ck(cudaMemcpy(dtok, w.tok.data(), w.tok.size() * sizeof(int32_t), cudaMemcpyHostToDevice), "copy tok");
285            if (!ok) break;
286            std::printf("# T=%d %s: %d groups, %d entries, %.1f MB of weights per call\n", T, shape.c_str(), G, NE,
287                        (double) G * (double) L.bytes / 1e6);
288            auto call = [&](size_t i) {
289                K::native_expert_grouped(L, dptr + (i % P) * (size_t) G, dstart, dn, ddst, dtok, G, NE, dxq, dscr, dout, stream, 0);
290            };
291            auto timed = [&](int phase, int rounds, double& out_us) {
292                K::native_expert_set_mode(-1, phase);
293                for (size_t i = 0; i < (phase == 0 ? 100u : 20u); ++i) call(i);
294                std::vector<double> rs((size_t) rounds);
295                for (double& r : rs) {
296                    cudaEventRecord(se.a, se.s);
297                    for (int i = 0; i < reps; ++i) call((size_t) i);
298                    cudaEventRecord(se.b, se.s);
299                    cudaEventSynchronize(se.b);
300                    float ms = 0.0f;
301                    ok = ok && ck(cudaEventElapsedTime(&ms, se.a, se.b), "elapsed") && ck(cudaGetLastError(), "kernel");
302                    r = 1000.0 * (double) ms / reps;
303                }
304                std::sort(rs.begin(), rs.end());
305                out_us = rs[(size_t) rounds / 2];
306                K::native_expert_set_mode(-1, 0);
307            };
308            std::vector<float> ref, res((size_t) NE * kEmbd);
309            for (size_t vi = 0; vi < choices.size() && ok; ++vi) {
310                const Choice& c = choices[vi];
311                apply_choice(dev_params, c);
312                K::native_expert_set_mode(-1, 0);
313                ok = ck(cudaMemset(dout, 0, (size_t) NE * kEmbd * sizeof(float)), "memset out");
314                call(0);
315                ok = ok && ck(cudaStreamSynchronize(se.s), "run") && ck(cudaGetLastError(), "kernel") &&
316                     ck(cudaMemcpy(res.data(), dout, res.size() * sizeof(float), cudaMemcpyDeviceToHost), "copy out");
317                if (!ok) break;
318                bool same = true;
319                if (vi == 0) {
320                    ref = res;
321                    long long nonfinite = 0;
322                    for (float f : ref) nonfinite += std::isfinite(f) ? 0 : 1;
323                    if (nonfinite) std::printf("# T=%d: %s output has %lld non-finite values\n", T, c.name.c_str(), nonfinite);
324                } else {
325                    same = std::memcmp(ref.data(), res.data(), ref.size() * sizeof(float)) == 0;
326                }
327                double us[3] = {0.0, 0.0, 0.0};
328                timed(0, 5, us[0]);
329                timed(1, 3, us[1]);
330                timed(2, 3, us[2]);
331                const double gbps = (double) G * (double) L.bytes / (us[0] * 1e-6) / 1e9;
332                std::printf("%d %d %s %d/%d %s %.1f %.1f %.1f %.1f %.1f%% %s\n", dev, T, shape.c_str(), L.gu_type, L.d_type,
333                            c.name.c_str(), us[0], us[1], us[2], gbps, peak > 0.0 ? 100.0 * gbps * 1e9 / peak : 0.0,
334                            same ? "identical" : "DIFFERENT");
335                g_times[Key(dev, L.gu_type, L.d_type, T, shape, c.name)] = {us[0], us[1], us[2]};
336                if (!same) ++bad;
337            }
338        }
339    }
340    Choice off;
341    apply_choice(dev_params, off);
342    K::native_expert_set_mode(-1, 0);
343    return ok;
344}
345
346// "gu/d,gu/d,..." -> pairs; false on a malformed item
347bool parse_pairs(const std::string& spec, std::vector<Pair>& out) {
348    size_t i = 0;
349    while (i < spec.size()) {
350        size_t j = spec.find(',', i);
351        if (j == std::string::npos) j = spec.size();
352        const std::string item = spec.substr(i, j - i);
353        i = j + 1;
354        if (item.empty()) continue;
355        const size_t s = item.find('/');
356        if (s == std::string::npos || s == 0 || s + 1 >= item.size()) return false;
357        Pair p;
358        p.gu = std::atoi(item.substr(0, s).c_str());
359        p.d = std::atoi(item.substr(s + 1).c_str());
360        if (p.gu <= 0 || p.d <= 0) return false;
361        out.push_back(p);
362    }
363    return !out.empty();
364}
365
366std::vector<std::string> split_commas(const std::string& s) {
367    std::vector<std::string> out;
368    size_t i = 0;
369    while (i <= s.size()) {
370        size_t j = s.find(',', i);
371        if (j == std::string::npos) j = s.size();
372        if (j > i) out.push_back(s.substr(i, j - i));
373        i = j + 1;
374    }
375    return out;
376}
377
378}  // namespace
379
380int main(int argc, char** argv) {
381    setvbuf(stdout, nullptr, _IONBF, 0);
382    const int reps = argc > 1 ? std::max(20, std::atoi(argv[1])) : 300;
383    const int only = argc > 2 ? std::atoi(argv[2]) : -1;
384    const int groups_req = argc > 3 ? std::min(kMaxEntries, std::max(kTop, std::atoi(argv[3]))) : 20;
385    std::vector<Pair> pairs;
386    if (argc > 4 && std::string(argv[4]) != "all") {
387        if (!parse_pairs(argv[4], pairs)) {
388            std::printf("expdec_bench: pairs '%s' is not a comma list of gu/down ggml type ids\n", argv[4]);
389            return 1;
390        }
391    } else {
392        pairs.assign(std::begin(kModelPairs), std::end(kModelPairs));
393    }
394    std::vector<Choice> choices;
395    for (const std::string& s : split_commas(argc > 5 ? argv[5] : "def,dec,dec:r2,dec:b4,dec:r2:b4")) {
396        Choice c;
397        if (!parse_choice(s, c)) {
398            std::printf("expdec_bench: choice '%s' is not def or dec[:r<1|2>][:d<1|2|4>][:b<2|4>][:x<0|1>][:g<n>][:h<n>][:m<n>]\n", s.c_str());
399            return 1;
400        }
401        choices.push_back(c);
402    }
403    if (choices.empty() || choices[0].dec) {
404        Choice d;
405        parse_choice("def", d);
406        choices.insert(choices.begin(), d);   // the reference first
407    }
408    std::vector<std::string> shapes;
409    {
410        const std::string sh = argc > 6 ? argv[6] : "real";
411        if (sh == "both") shapes = {"real", "single"};
412        else if (sh == "real" || sh == "single") shapes = {sh};
413        else { std::printf("expdec_bench: shape '%s' is not real, single or both\n", sh.c_str()); return 1; }
414    }
415    int n_dev = 0;
416    if (!ck(cudaGetDeviceCount(&n_dev), "device count") || n_dev == 0) {
417        std::printf("expdec_bench: no CUDA device\n");
418        return 1;
419    }
420    if (only >= n_dev) {
421        std::printf("expdec_bench: device %d, only %d present\n", only, n_dev);
422        return 1;
423    }
424    // Snapshot each device's startup defaults before any choice overrides the process-wide EXPDEC parameters.
425    std::vector<K::NativeExpertExpdecParams> dev_params((size_t) n_dev);
426    for (int d = 0; d < n_dev; ++d) {
427        if (only >= 0 && d != only) continue;
428        if (!ck(cudaSetDevice(d), "set device")) return 1;
429        dev_params[(size_t) d] = K::native_expert_expdec_params();
430    }
431    const K::NativeExpertExpdecParams banner_params = dev_params[(size_t) (only >= 0 ? only : 0)];
432    for (const Pair& p : pairs) {
433        if (!K::native_expert_supported(p.gu, p.d, kEmbd, kFf)) {
434            std::printf("expdec_bench: native_expert_supported(%d, %d, %d, %d) is false\n", p.gu, p.d, kEmbd, kFf);
435            return 1;
436        }
437        const K::NativeExpertLayout L = K::native_expert_layout(p.gu, p.d, kEmbd, kFf);
438        bool gu = false, down = false;
439        K::native_expert_expdec_takes(L, gu, down);
440        if (!gu || !down) std::printf("# warning: EXPDEC has no %s kernel for pair %d/%d: that phase runs the default\n",
441                                      !gu ? "gate/up" : "down", p.gu, p.d);
442    }
443    for (const char* name : {"STRATA_NO_SUB16_GU", "STRATA_EXPERT_V2", "STRATA_OLD_IQ_MMVQ", "STRATA_EXP_MODE"}) {
444        const char* v = std::getenv(name);
445        if (v != nullptr && v[0] != '\0' && v[0] != '0') std::printf("# warning: %s is set, the kernel choice is bypassed\n", name);
446    }
447    K::iq_set_old_kernels(false);
448    std::printf("# n_embd %d, n_ff %d, %d pair(s), choices:", kEmbd, kFf, (int) pairs.size());
449    for (const Choice& c : choices) {
450        if (c.dec) {
451            const K::NativeExpertExpdecParams cp = resolve_choice_params(banner_params, c);
452            std::printf(" %s(gu R %d minb %d, down %d R %d iq4_nl %d, rb %d drb %d, min blocks %d)", c.name.c_str(),
453                        cp.gu_rows_per_lane, cp.gu_min_blocks_per_sm, cp.down, cp.down_rows_per_lane, cp.down_iq4_nl,
454                        cp.gu_rows_per_block, cp.down_rows_per_block, cp.min_blocks);
455        } else {
456            std::printf(" %s", c.name.c_str());
457        }
458    }
459    std::printf("\n# dev T shape gu/d choice all_us gu_us down_us GB/s pct identical|DIFFERENT\n");
460    long long bad = 0;
461    bool ok = true;
462    for (const Pair& p : pairs) {
463        if (!ok) break;
464        const K::NativeExpertLayout L = K::native_expert_layout(p.gu, p.d, kEmbd, kFf);
465        const size_t stride = (L.bytes + 255) / 256 * 256;
466        const size_t P = std::max<size_t>((size_t) (96u << 20) / stride + 1, (size_t) 2 * (size_t) kMaxEntries);
467        std::printf("# pair %d/%d: gate/up %s, down %s: blob %.2f MB (gu_row %d, d_row %d), pool %.0f MB\n", p.gu, p.d,
468                    type_name(p.gu), type_name(p.d), (double) L.bytes / 1e6, (int) L.gu_row, (int) L.d_row,
469                    (double) (P * stride) / 1e6);
470        std::mt19937 rng(77u + (unsigned) (p.gu * 131 + p.d));
471        std::vector<uint8_t> pool(P * stride, 0);
472        for (size_t i = 0; i < P; ++i) fill_blob(pool.data() + i * stride, L, rng);
473        std::vector<float> xh((size_t) kMaxT * kEmbd);
474        std::normal_distribution<float> nd(0.0f, 1.0f);
475        for (float& v : xh) v = nd(rng);
476        for (int dev = 0; dev < n_dev; ++dev) {
477            if (only >= 0 && dev != only) continue;
478            ok = run_device(dev, dev_params[(size_t) dev], reps, groups_req, pool, P, stride, xh, L, p, choices, shapes, bad) && ok;
479        }
480    }
481    if (shapes.size() == 2 && groups_req == 20) {
482        std::printf("\n# decomposition (us per layer call): a = per expert = (single T=4 - real T=2) / 20, b = per entry = (real T=4 - real T=2) / 20\n");
483        std::printf("# dev gu/d choice a_all a_gu a_down b_all b_gu b_down\n");
484        for (int dev = 0; dev < n_dev; ++dev) {
485            if (only >= 0 && dev != only) continue;
486            for (const Pair& p : pairs)
487                for (const Choice& c : choices) {
488                    auto f2 = g_times.find(Key(dev, p.gu, p.d, 2, "real", c.name));
489                    auto f4 = g_times.find(Key(dev, p.gu, p.d, 4, "real", c.name));
490                    auto s4 = g_times.find(Key(dev, p.gu, p.d, 4, "single", c.name));
491                    if (f2 == g_times.end() || f4 == g_times.end() || s4 == g_times.end()) continue;
492                    std::printf("%d %d/%d %s", dev, p.gu, p.d, c.name.c_str());
493                    for (int k = 0; k < 3; ++k) std::printf(" %.2f", (s4->second[k] - f2->second[k]) / 20.0);
494                    for (int k = 0; k < 3; ++k) std::printf(" %.2f", (f4->second[k] - f2->second[k]) / 20.0);
495                    std::printf("\n");
496                }
497        }
498    }
499    std::printf("\nexpdec_bench: %s (%lld choice comparisons differ%s)\n", (bad || !ok || g_cuda_error) ? "FAILED" : "ok", bad,
500                (!ok || g_cuda_error) ? ", CUDA error" : "");
501    return (bad || !ok || g_cuda_error) ? 1 : 0;
502}