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
31.7 KiB681 linesraw
1// src/kernels/s2_expert_grouped_parity.cpp - the rewritten expert kernels against the previous ones,
2// BITWISE (GPU, synthetic, no model).
3//
4//     build/s2_expert_grouped_parity            the checks below; exit 1 on any difference
5//     build/s2_expert_grouped_parity --bench    previous vs new kernel timings on engine-like shapes
6//
7// Random Q2_0 expert blobs (random codes, fp16 scales in a realistic range) and random Q8_0 activations.  Every entry
8// point of `s2_expert_grouped.hpp` that gained a new kernel runs twice from identical inputs and sentinel-filled
9// outputs - `moe_grouped_select_old(1)`, then `(0)` - and the two runs are compared byte for byte:
10//   1. `moe_hit_grouped_s2`          per hit, host count; with fp32 activation scales and with the blocks' fp16 `d`
11//   2. `moe_hit_grouped_s2_dev`      device count below the capacity (the rows past it must stay untouched)
12//   3. `moe_hit_grouped_s2_multi`    verify window: each hit reads its own token's activation row
13//   4. `moe_grouped_s2`              host-built groups of 1..8 entries, one of them a mapped HOST blob (the PCIe
14//                                    share), and more group capacity than groups
15//   5. `moe_group_resident` + `moe_grouped_s2`   the MTP layer's shape, with and without fp32 scales
16//   6. an activation row that is only 2-byte aligned: the new path must fall back to the previous kernels
17//   7. a slot stride that is not a multiple of 8 (BLOB + 4), and 8. an arena 4 bytes past an aligned address: the
18//      per-hit path must fall back as well (its codes are read as uint2)
19// Every run asks `moe_grouped_last_path` which kernels it launched, so a new path that silently declined cannot pass
20// as "the previous kernels against themselves": forced new must report the new kernels, and 6-8 the previous ones.
21// (A misaligned scratch is not exercised: the previous kernels store floats there, so it is not a legal input.)
22// The output AND the scratch (gate/up, the quantized intermediate and its scales) are compared, so a failure names
23// the projection.  Bitwise equality with the previous kernels is the contract; on top of it a double-precision
24// host reference of every up row and every down row checks that the fixture computes an expert at all - two
25// kernels agreeing on garbage would otherwise pass.
26#include "strata/kernels/f16_bits.hpp"
27#include "strata/kernels/s2_expert_grouped.hpp"
28
29#include <cuda_runtime.h>
30
31#include <algorithm>
32#include <cmath>
33#include <cstdint>
34#include <cstdio>
35#include <cstdlib>
36#include <cstring>
37#include <functional>
38#include <numeric>
39#include <random>
40#include <string>
41#include <vector>
42
43namespace k = strata::kernels;
44
45namespace {
46// The blob geometry, `cpu/expert.hpp`'s (restated as in the kernel).
47constexpr int H = 2560, FF = 640, NCH_GU = H / 32, NCH_D = FF / 32;
48constexpr size_t ROW_GU = H / 4, ROW_D = FF / 4, SC_GU = H / 64, SC_D = FF / 64;
49constexpr size_t O_D_CODES = 2ull * FF * ROW_GU;
50constexpr size_t O_GU_SCALES = O_D_CODES + (size_t) H * ROW_D;
51constexpr size_t O_D_SCALES = O_GU_SCALES + 2ull * FF * SC_GU * 2;
52constexpr size_t BLOB = O_D_SCALES + (size_t) H * SC_D * 2;
53static_assert(BLOB == 1382400, "the Q2_0 expert blob is 1,382,400 bytes");
54constexpr size_t XROW = (size_t) NCH_GU * 34;   // one token's activation row of block_q8_0
55
56int g_fail = 0;
57
58void ck(cudaError_t e, const char* w) {
59    if (e != cudaSuccess) { std::fprintf(stderr, "%s: %s\n", w, cudaGetErrorString(e)); std::exit(2); }
60}
61template <typename T> T* dalloc(size_t n) {
62    T* p = nullptr;
63    ck(cudaMalloc(&p, n * sizeof(T) + 256), "malloc");
64    ck(cudaMemset(p, 0, n * sizeof(T) + 256), "memset");
65    return p;
66}
67template <typename T> void up(T* d, const std::vector<T>& h) {
68    ck(cudaMemcpy(d, h.data(), h.size() * sizeof(T), cudaMemcpyHostToDevice), "h2d");
69}
70template <typename T> std::vector<T> down(const T* d, size_t n) {
71    std::vector<T> h(n);
72    ck(cudaMemcpy(h.data(), d, n * sizeof(T), cudaMemcpyDeviceToHost), "d2h");
73    return h;
74}
75
76float f16f(const uint8_t* p) { return k::f32_from_f16((uint16_t) (p[0] | (p[1] << 8))); }
77void put16(uint8_t* p, float f) {
78    const uint16_t h = k::f16_from_f32(f);
79    p[0] = (uint8_t) h;
80    p[1] = (uint8_t) (h >> 8);
81}
82
83// Random codes; fp16 scales of either sign in [1e-3, 3e-2] (a real pack's range, so no overflow downstream).
84void fill_blob(uint8_t* b, std::mt19937& rng) {
85    for (size_t i = 0; i < O_GU_SCALES; ++i) b[i] = (uint8_t) rng();
86    std::uniform_real_distribution<float> mag(1e-3f, 3e-2f);
87    for (size_t i = O_GU_SCALES; i < BLOB; i += 2) put16(b + i, (rng() & 1 ? -1.0f : 1.0f) * mag(rng));
88}
89
90// `n_tok` activation rows: per 32-chunk an fp16 `d` then 32 int8 in [-127, 127] (what `quantize_q8_0` writes),
91// plus the fp32 scales `quantize_q8_0_scaled` would pass alongside.  Some chunks are saturated on purpose.
92void fill_x(std::vector<uint8_t>& x, std::vector<float>& xs, int n_tok, std::mt19937& rng) {
93    x.assign((size_t) n_tok * XROW, 0);
94    xs.assign((size_t) n_tok * NCH_GU, 0.0f);
95    std::uniform_real_distribution<float> sc(2e-3f, 5e-2f);
96    for (size_t c = 0; c < (size_t) n_tok * NCH_GU; ++c) {
97        uint8_t* b = x.data() + c * 34;
98        xs[c] = sc(rng);
99        put16(b, xs[c]);
100        const int mode = (int) (rng() % 16);
101        for (int j = 0; j < 32; ++j) {
102            const int v = mode == 0 ? 127 : mode == 1 ? -127 : (int) (rng() % 255) - 127;
103            b[2 + j] = (uint8_t) (int8_t) v;
104        }
105    }
106}
107
108// Double-precision reference of one row against one activation row: sum_c dw * dx * sum_e (code_e - 1) * x_e.
109// `mag` receives sum |term|, the scale the tolerance is relative to.
110double row_ref(const uint8_t* codes, const uint8_t* scales, const uint8_t* xrow, const float* xs, int n_chunks,
111               double* mag) {
112    double acc = 0.0, a = 0.0;
113    for (int c = 0; c < n_chunks; ++c) {
114        const uint8_t* xb = xrow + (size_t) c * 34;
115        const double dx = xs ? (double) xs[c] : (double) f16f(xb);
116        const double dw = (double) f16f(scales + (size_t) (c >> 1) * 2);
117        int s = 0;
118        for (int e = 0; e < 32; ++e) {
119            const int code = (codes[(size_t) c * 8 + e / 4] >> (2 * (e % 4))) & 3;
120            s += (code - 1) * (int) (int8_t) xb[2 + e];
121        }
122        const double t = dw * dx * (double) s;
123        acc += t;
124        a += std::fabs(t);
125    }
126    *mag = a;
127    return acc;
128}
129
130bool close_to(float got, double ref, double mag) {
131    return std::isfinite(got) && std::fabs((double) got - ref) <= 4e-5 * mag + 1e-30;
132}
133
134struct Scratch {
135    void* p = nullptr;
136    uint64_t bytes = 0;
137    int64_t cap = 0;
138    uint64_t gu_bytes() const { return ((uint64_t) cap * 2 * FF * 4 + 15) & ~15ull; }
139    uint64_t q8_bytes() const { return ((uint64_t) cap * NCH_D * 34 + 15) & ~15ull; }
140};
141
142// One entry point, run with the previous kernels then with the new ones from identical sentinel-filled buffers;
143// every differing float of the output and byte of the scratch is counted.  `keep` receives the new run.
144struct Run {
145    std::vector<float> out;
146    std::vector<uint8_t> scratch;
147};
148
149bool twice(const char* name, float* d_out, size_t out_floats, const Scratch& s,
150           const std::function<void()>& call, Run* keep, bool expect_new = true) {
151    Run r[2];
152    for (int old = 1; old >= 0; --old) {
153        ck(cudaMemset(d_out, 0xA5, out_floats * 4), "sentinel out");
154        ck(cudaMemset(s.p, 0x5A, s.bytes), "sentinel scratch");
155        k::moe_grouped_select_old(old);
156        (void) k::moe_grouped_last_path();   // clear
157        call();
158        const int path = k::moe_grouped_last_path();
159        const int want = old ? 0 : (expect_new ? 1 : 0);
160        if (path != want) {
161            std::printf("  %-44s forced %s: launched %s kernels, expected %s\n", name, old ? "previous" : "new",
162                        path == 1 ? "the new" : path == 0 ? "the previous" : "no", want ? "the new" : "the previous");
163            ++g_fail;
164        }
165        ck(cudaGetLastError(), name);
166        ck(cudaDeviceSynchronize(), name);
167        Run& x = r[old ? 0 : 1];
168        x.out = down(d_out, out_floats);
169        x.scratch = down((const uint8_t*) s.p, (size_t) s.bytes);
170    }
171    k::moe_grouped_select_old(-1);
172    const uint64_t gu = s.gu_bytes(), q8 = s.q8_bytes();
173    size_t diff_out = 0, diff_gu = 0, diff_q8 = 0, diff_hs = 0;
174    for (size_t i = 0; i < out_floats; ++i)
175        diff_out += std::memcmp(&r[0].out[i], &r[1].out[i], 4) != 0;
176    for (size_t i = 0; i < (size_t) s.bytes; ++i) {
177        if (r[0].scratch[i] == r[1].scratch[i]) continue;
178        if (i < gu) ++diff_gu;
179        else if (i < gu + q8) ++diff_q8;
180        else ++diff_hs;
181    }
182    const bool ok = diff_out + diff_gu + diff_q8 + diff_hs == 0;
183    std::printf("  %-44s %s", name, ok ? "bitwise identical" : "DIFFERS");
184    if (!ok)
185        std::printf(" (out %zu floats, gate/up %zu B, intermediate %zu B, its scales %zu B)", diff_out, diff_gu,
186                    diff_q8, diff_hs);
187    std::printf("\n");
188    if (!ok) ++g_fail;
189    if (keep) *keep = std::move(r[1]);
190    return ok;
191}
192
193// The host reference on a finished run: every up row (the second half of gate/up, which the swiglu leaves alone)
194// against the activation row it read, and every written down row against the intermediate the run produced.
195struct Entry {
196    const uint8_t* blob;   // host copy of the entry's blob
197    int tok;               // activation row it reads
198    int dst;               // output row it writes
199};
200void reference(const char* name, const Run& r, const Scratch& s, const std::vector<Entry>& ent,
201               const std::vector<uint8_t>& x, const std::vector<float>* xs) {
202    const float* gu = (const float*) r.scratch.data();
203    const uint8_t* hq = r.scratch.data() + s.gu_bytes();
204    const float* hs = (const float*) (r.scratch.data() + s.gu_bytes() + s.q8_bytes());
205    long checked = 0, bad = 0;
206    double worst = 0.0;
207    for (size_t e = 0; e < ent.size(); ++e) {
208        const uint8_t* b = ent[e].blob;
209        const uint8_t* xrow = x.data() + (size_t) ent[e].tok * XROW;
210        const float* xsr = xs ? xs->data() + (size_t) ent[e].tok * NCH_GU : nullptr;
211        for (int rr = 0; rr < FF; rr += 7) {   // up row rr = row-slot 2rr + 1
212            double mag;
213            const double ref = row_ref(b + (size_t) (2 * rr + 1) * ROW_GU, b + O_GU_SCALES + (size_t) (2 * rr + 1) * SC_GU * 2,
214                                       xrow, xsr, NCH_GU, &mag);
215            const float got = gu[(size_t) s.cap * FF + e * FF + (size_t) rr];
216            ++checked;
217            if (!close_to(got, ref, mag)) ++bad;
218            if (mag > 0) worst = std::max(worst, std::fabs((double) got - ref) / mag);
219        }
220        const uint8_t* hrow = hq + e * (size_t) NCH_D * 34;
221        const float* hsr = xs ? hs + e * (size_t) NCH_D : nullptr;
222        for (int rr = 0; rr < H; rr += 13) {
223            double mag;
224            const double ref = row_ref(b + O_D_CODES + (size_t) rr * ROW_D, b + O_D_SCALES + (size_t) rr * SC_D * 2,
225                                       hrow, hsr, NCH_D, &mag);
226            const float got = r.out[(size_t) ent[e].dst * H + (size_t) rr];
227            ++checked;
228            if (!close_to(got, ref, mag)) ++bad;
229            if (mag > 0) worst = std::max(worst, std::fabs((double) got - ref) / mag);
230        }
231    }
232    std::printf("  %-44s host reference: %ld rows, %ld outside tolerance, worst %.2e of sum|term|\n", name, checked,
233                bad, worst);
234    if (bad || checked == 0) ++g_fail;
235}
236
237struct Fixture {
238    int nb = 0;
239    std::vector<uint8_t> h;   // nb blobs
240    uint8_t* d = nullptr;
241    const uint8_t* hb(int i) const { return h.data() + (size_t) i * BLOB; }
242};
243
244Fixture make_blobs(int nb, std::mt19937& rng) {
245    Fixture f;
246    f.nb = nb;
247    f.h.resize((size_t) nb * BLOB);
248    for (int i = 0; i < nb; ++i) fill_blob(f.h.data() + (size_t) i * BLOB, rng);
249    f.d = dalloc<uint8_t>((size_t) nb * BLOB);
250    up(f.d, f.h);
251    return f;
252}
253
254Scratch make_scratch(int64_t cap) {
255    Scratch s;
256    s.cap = cap;
257    s.bytes = k::moe_hit_grouped_scratch_bytes(cap, H, FF);
258    s.p = dalloc<uint8_t>(s.bytes);
259    return s;
260}
261
262// ---------------------------------------------------------------- the checks
263void check_all() {
264    std::mt19937 rng(20260928);
265    const Fixture fx = make_blobs(12, rng);
266    constexpr int K = 10;
267
268    // Activations for up to 8 tokens, device copies with and without the fp32 scales.
269    std::vector<uint8_t> x;
270    std::vector<float> xs;
271    fill_x(x, xs, 8, rng);
272    uint8_t* d_x = dalloc<uint8_t>(x.size());
273    float* d_xs = dalloc<float>(xs.size());
274    up(d_x, x);
275    up(d_xs, xs);
276
277    // ---- 1. moe_hit_grouped_s2: 9 hits of 10 routed rows, slots and destinations shuffled
278    {
279        const int n_hits = 9;
280        std::vector<int32_t> slot(n_hits), dst(K);
281        for (int i = 0; i < n_hits; ++i) slot[i] = (int32_t) ((i * 5 + 3) % fx.nb);
282        std::iota(dst.begin(), dst.end(), 0);
283        std::shuffle(dst.begin(), dst.end(), rng);
284        dst.resize(n_hits);
285        int32_t* d_slot = dalloc<int32_t>(n_hits);
286        int32_t* d_dst = dalloc<int32_t>(n_hits);
287        up(d_slot, slot);
288        up(d_dst, dst);
289        const Scratch s = make_scratch(n_hits);
290        float* d_out = dalloc<float>((size_t) K * H);
291        std::vector<Entry> ent;
292        for (int i = 0; i < n_hits; ++i) ent.push_back({fx.hb(slot[i]), 0, dst[i]});
293        for (int scaled = 1; scaled >= 0; --scaled) {
294            Run r;
295            const std::string name = std::string("moe_hit_grouped_s2") + (scaled ? " (fp32 scales)" : " (fp16 d)");
296            twice(name.c_str(), d_out, (size_t) K * H, s, [&] {
297                k::moe_hit_grouped_s2(fx.d, d_slot, d_dst, n_hits, (int64_t) BLOB, d_x, s.p, d_out, nullptr,
298                                      scaled ? d_xs : nullptr);
299            }, &r);
300            reference(name.c_str(), r, s, ent, x, scaled ? &xs : nullptr);
301        }
302    }
303
304    // ---- 2. moe_hit_grouped_s2_dev: capacity 10, device count 7
305    {
306        const int cap = 10, count = 7;
307        std::vector<int32_t> slot(cap), dst(cap);
308        for (int i = 0; i < cap; ++i) slot[i] = (int32_t) ((i * 7 + 1) % fx.nb);
309        std::iota(dst.begin(), dst.end(), 0);
310        std::shuffle(dst.begin(), dst.end(), rng);
311        int32_t* d_slot = dalloc<int32_t>(cap);
312        int32_t* d_dst = dalloc<int32_t>(cap);
313        int32_t* d_count = dalloc<int32_t>(1);
314        up(d_slot, slot);
315        up(d_dst, dst);
316        up(d_count, std::vector<int32_t>{count});
317        const Scratch s = make_scratch(cap);
318        float* d_out = dalloc<float>((size_t) K * H);
319        std::vector<Entry> ent;
320        for (int i = 0; i < count; ++i) ent.push_back({fx.hb(slot[i]), 0, dst[i]});
321        Run r;
322        twice("moe_hit_grouped_s2_dev (count 7 of 10)", d_out, (size_t) K * H, s, [&] {
323            k::moe_hit_grouped_s2_dev(fx.d, d_slot, d_dst, d_count, cap, (int64_t) BLOB, d_x, s.p, d_out, nullptr,
324                                      d_xs);
325        }, &r);
326        reference("moe_hit_grouped_s2_dev (count 7 of 10)", r, s, ent, x, &xs);
327        // the rows of the hits past the count keep the sentinel
328        long touched = 0;
329        for (int i = count; i < cap; ++i)
330            for (int c = 0; c < H; ++c) {
331                uint32_t v;
332                std::memcpy(&v, &r.out[(size_t) dst[i] * H + c], 4);
333                touched += v != 0xA5A5A5A5u;
334            }
335        std::printf("  %-44s rows past the count written: %ld\n", "moe_hit_grouped_s2_dev (count 7 of 10)", touched);
336        if (touched) ++g_fail;
337    }
338
339    // ---- 3. moe_hit_grouped_s2_multi: 4 tokens x 10 routed entries, 29 hits
340    {
341        const int T = 4, n = T * K, count = 29;
342        std::vector<int32_t> ent_ids(n);
343        std::iota(ent_ids.begin(), ent_ids.end(), 0);
344        std::shuffle(ent_ids.begin(), ent_ids.end(), rng);
345        std::vector<int32_t> slot(n), dst(n);
346        for (int i = 0; i < n; ++i) {
347            dst[i] = ent_ids[i];
348            slot[i] = (int32_t) (rng() % fx.nb);
349        }
350        std::sort(dst.begin(), dst.begin() + count);   // hit order is routing order, as `moe_hit_select_multi` makes it
351        int32_t* d_slot = dalloc<int32_t>(n);
352        int32_t* d_dst = dalloc<int32_t>(n);
353        int32_t* d_count = dalloc<int32_t>(1);
354        up(d_slot, slot);
355        up(d_dst, dst);
356        up(d_count, std::vector<int32_t>{count});
357        const Scratch s = make_scratch(n);
358        float* d_out = dalloc<float>((size_t) n * H);
359        std::vector<Entry> ent;
360        for (int i = 0; i < count; ++i) ent.push_back({fx.hb(slot[i]), dst[i] / K, dst[i]});
361        Run r;
362        twice("moe_hit_grouped_s2_multi (4 tokens, 29 hits)", d_out, (size_t) n * H, s, [&] {
363            k::moe_hit_grouped_s2_multi(fx.d, d_slot, d_dst, d_count, n, (int64_t) BLOB, d_x, d_xs, K, s.p, d_out,
364                                        nullptr);
365        }, &r);
366        reference("moe_hit_grouped_s2_multi (4 tokens, 29 hits)", r, s, ent, x, &xs);
367    }
368
369    // ---- 4. moe_grouped_s2: 8 tokens x 10 entries in groups of 1..8, one group on a mapped host blob
370    {
371        const int T = 8, n = T * K;
372        uint8_t* h_host = nullptr;
373        uint8_t* d_host = nullptr;
374        ck(cudaHostAlloc((void**) &h_host, BLOB, cudaHostAllocMapped), "host blob");
375        std::memcpy(h_host, fx.hb(fx.nb - 1), BLOB);
376        ck(cudaHostGetDevicePointer((void**) &d_host, h_host, 0), "host blob ptr");
377        // group sizes: 8, 1, 5, 2, 7, 3, 1, 6, 4, ... up to n entries
378        const int sizes[] = {8, 1, 5, 2, 7, 3, 1, 6, 4, 8, 1, 2, 3, 4, 5, 6, 7, 1, 1, 5};
379        std::vector<int32_t> order(n);   // the output rows, in group order
380        std::iota(order.begin(), order.end(), 0);
381        std::shuffle(order.begin(), order.end(), rng);
382        std::vector<unsigned long long> gptr;
383        std::vector<int32_t> gstart{0}, edst, etok;
384        std::vector<Entry> ent;
385        int at = 0, gi = 0;
386        while (at < n) {
387            const int sz = std::min(sizes[gi % 20], n - at);
388            const bool host = gi == 3;
389            const int b = gi % (fx.nb - 1);
390            gptr.push_back((unsigned long long) (host ? d_host : fx.d + (size_t) b * BLOB));
391            for (int j = 0; j < sz; ++j, ++at) {
392                edst.push_back(order[at]);
393                etok.push_back(order[at] / K);
394                ent.push_back({host ? h_host : fx.hb(b), order[at] / K, order[at]});
395            }
396            gstart.push_back(at);
397            ++gi;
398        }
399        const int n_groups = gi, cap_groups = n_groups + 3;
400        gstart.resize((size_t) cap_groups + 1, at);
401        gptr.resize((size_t) cap_groups, gptr[0]);
402        unsigned long long* d_gptr = dalloc<unsigned long long>(gptr.size());
403        int32_t* d_gstart = dalloc<int32_t>(gstart.size());
404        int32_t* d_ng = dalloc<int32_t>(1);
405        int32_t* d_edst = dalloc<int32_t>(n);
406        int32_t* d_etok = dalloc<int32_t>(n);
407        up(d_gptr, gptr);
408        up(d_gstart, gstart);
409        up(d_ng, std::vector<int32_t>{n_groups});
410        up(d_edst, edst);
411        up(d_etok, etok);
412        const Scratch s = make_scratch(n);
413        float* d_out = dalloc<float>((size_t) n * H);
414        for (int scaled = 1; scaled >= 0; --scaled) {
415            Run r;
416            const std::string name = std::string("moe_grouped_s2 (") + std::to_string(n_groups) + " groups" +
417                                     (scaled ? ", fp32 scales)" : ", fp16 d)");
418            twice(name.c_str(), d_out, (size_t) n * H, s, [&] {
419                k::moe_grouped_s2(d_gptr, d_gstart, d_ng, d_edst, d_etok, cap_groups, n, d_x, scaled ? d_xs : nullptr,
420                                  s.p, d_out, nullptr);
421            }, &r);
422            reference(name.c_str(), r, s, ent, x, scaled ? &xs : nullptr);
423        }
424        ck(cudaFreeHost(h_host), "free host blob");
425    }
426
427    // ---- 5. moe_group_resident + moe_grouped_s2: the MTP layer (experts resident at base + id * BLOB), T=1 and T=5
428    for (const int T : {1, 5}) {
429        const int n = T * K;
430        std::vector<int32_t> ids(n);
431        for (int t = 0; t < T; ++t) {   // distinct within a token, shared across tokens
432            std::vector<int32_t> pick(fx.nb);
433            std::iota(pick.begin(), pick.end(), 0);
434            std::shuffle(pick.begin(), pick.end(), rng);
435            for (int j = 0; j < K; ++j) ids[(size_t) t * K + j] = pick[j];
436        }
437        int32_t* d_ids = dalloc<int32_t>(n);
438        up(d_ids, ids);
439        unsigned long long* d_gptr = dalloc<unsigned long long>(n);
440        int32_t* d_gstart = dalloc<int32_t>(n + 1);
441        int32_t* d_counts = dalloc<int32_t>(2);
442        int32_t* d_edst = dalloc<int32_t>(n);
443        int32_t* d_etok = dalloc<int32_t>(n);
444        k::moe_group_resident(d_ids, n, K, fx.d, (int64_t) BLOB, d_gptr, d_gstart, d_counts, d_edst, d_etok, nullptr);
445        ck(cudaDeviceSynchronize(), "group_resident");
446        const std::vector<int32_t> edst = down(d_edst, n), etok = down(d_etok, n);
447        std::vector<Entry> ent(n);   // entry e: dst = routing index, blob = its expert
448        for (int e = 0; e < n; ++e) ent[e] = {fx.hb(ids[(size_t) edst[e]]), etok[e], edst[e]};
449        const Scratch s = make_scratch(n);
450        float* d_out = dalloc<float>((size_t) n * H);
451        for (int scaled = 1; scaled >= 0; --scaled) {
452            Run r;
453            const std::string name = std::string("moe_group_resident + moe_grouped_s2 T=") + std::to_string(T) +
454                                     (scaled ? " (fp32)" : " (fp16)");
455            twice(name.c_str(), d_out, (size_t) n * H, s, [&] {
456                k::moe_grouped_s2(d_gptr, d_gstart, d_counts, d_edst, d_etok, n, n, d_x, scaled ? d_xs : nullptr, s.p,
457                                  d_out, nullptr);
458            }, &r);
459            reference(name.c_str(), r, s, ent, x, scaled ? &xs : nullptr);
460        }
461    }
462
463    // ---- 6. a 2-byte aligned activation row: the new path must decline and the previous kernels run
464    {
465        uint8_t* d_x2 = dalloc<uint8_t>(x.size() + 2);
466        ck(cudaMemcpy(d_x2 + 2, x.data(), XROW, cudaMemcpyHostToDevice), "x2");
467        const int n_hits = 3;
468        std::vector<int32_t> slot{2, 5, 7}, dst{4, 0, 9};
469        int32_t* d_slot = dalloc<int32_t>(n_hits);
470        int32_t* d_dst = dalloc<int32_t>(n_hits);
471        up(d_slot, slot);
472        up(d_dst, dst);
473        const Scratch s = make_scratch(n_hits);
474        float* d_out = dalloc<float>((size_t) K * H);
475        std::vector<Entry> ent;
476        for (int i = 0; i < n_hits; ++i) ent.push_back({fx.hb(slot[i]), 0, dst[i]});
477        Run r;
478        twice("moe_hit_grouped_s2 (2-byte aligned x)", d_out, (size_t) K * H, s, [&] {
479            k::moe_hit_grouped_s2(fx.d, d_slot, d_dst, n_hits, (int64_t) BLOB, d_x2 + 2, s.p, d_out, nullptr, d_xs);
480        }, &r, /*expect_new=*/false);
481        reference("moe_hit_grouped_s2 (2-byte aligned x)", r, s, ent, x, &xs);
482    }
483
484    // ---- 7. slots BLOB + 4 bytes apart, and 8. an arena at an address that is 4 mod 8: per-hit fallback
485    {
486        constexpr size_t STRIDE = BLOB + 4;
487        static_assert(STRIDE % 8 != 0, "the stride must defeat the uint2 code loads");
488        const int nb = 8;
489        uint8_t* d_arena = dalloc<uint8_t>((size_t) nb * STRIDE + 8);
490        const int n_hits = 4;
491        std::vector<int32_t> slot{6, 1, 3, 0}, dst{2, 7, 5, 8};
492        int32_t* d_slot = dalloc<int32_t>(n_hits);
493        int32_t* d_dst = dalloc<int32_t>(n_hits);
494        up(d_slot, slot);
495        up(d_dst, dst);
496        const Scratch s = make_scratch(n_hits);
497        float* d_out = dalloc<float>((size_t) K * H);
498        std::vector<Entry> ent;
499        for (int i = 0; i < n_hits; ++i) ent.push_back({fx.hb(slot[i]), 0, dst[i]});
500        // One allocation for both layouts: the BLOB + 4 strided copies first, then the same blobs BLOB apart from
501        // `d_arena + 4` over them.
502        for (int i = 0; i < nb; ++i)
503            ck(cudaMemcpy(d_arena + (size_t) i * STRIDE, fx.hb(i), BLOB, cudaMemcpyHostToDevice), "arena");
504        {
505            Run r;
506            twice("moe_hit_grouped_s2 (slot stride BLOB + 4)", d_out, (size_t) K * H, s, [&] {
507                k::moe_hit_grouped_s2(d_arena, d_slot, d_dst, n_hits, (int64_t) STRIDE, d_x, s.p, d_out, nullptr,
508                                      d_xs);
509            }, &r, /*expect_new=*/false);
510            reference("moe_hit_grouped_s2 (slot stride BLOB + 4)", r, s, ent, x, &xs);
511        }
512        for (int i = 0; i < nb; ++i)
513            ck(cudaMemcpy(d_arena + 4 + (size_t) i * BLOB, fx.hb(i), BLOB, cudaMemcpyHostToDevice), "arena");
514        {
515            Run r;
516            twice("moe_hit_grouped_s2 (arena 4 mod 8)", d_out, (size_t) K * H, s, [&] {
517                k::moe_hit_grouped_s2(d_arena + 4, d_slot, d_dst, n_hits, (int64_t) BLOB, d_x, s.p, d_out, nullptr,
518                                      d_xs);
519            }, &r, /*expect_new=*/false);
520            reference("moe_hit_grouped_s2 (arena 4 mod 8)", r, s, ent, x, &xs);
521        }
522    }
523}
524
525// ---------------------------------------------------------------- --bench
526// Engine-like shapes with the blobs cycled through a set larger than the L2, so each call reads its codes from
527// DRAM as the engine's do.  Reports microseconds per call and the codes' effective bandwidth.
528void bench() {
529    int dev = 0;
530    cudaDeviceProp prop{};
531    ck(cudaGetDevice(&dev), "dev");
532    ck(cudaGetDeviceProperties(&prop, dev), "props");
533    const int nb = std::max(48, (int) (3ull * (size_t) prop.l2CacheSize / BLOB) + 8);
534    std::printf("bench: %s, L2 %d MB, %d blobs (%.0f MB) cycled\n", prop.name, prop.l2CacheSize >> 20, nb,
535                nb * (double) BLOB / 1e6);
536    std::mt19937 rng(7);
537    Fixture fx;
538    fx.nb = nb;
539    fx.d = dalloc<uint8_t>((size_t) nb * BLOB);
540    {
541        std::vector<uint8_t> b(BLOB);
542        for (int i = 0; i < nb; ++i) {
543            fill_blob(b.data(), rng);
544            ck(cudaMemcpy(fx.d + (size_t) i * BLOB, b.data(), BLOB, cudaMemcpyHostToDevice), "blob");
545        }
546    }
547    std::vector<uint8_t> x;
548    std::vector<float> xs;
549    fill_x(x, xs, 8, rng);
550    uint8_t* d_x = dalloc<uint8_t>(x.size());
551    float* d_xs = dalloc<float>(xs.size());
552    up(d_x, x);
553    up(d_xs, xs);
554    constexpr int K = 10, ITERS = 200, SETS = 16;
555    cudaEvent_t e0, e1;
556    ck(cudaEventCreate(&e0), "ev");
557    ck(cudaEventCreate(&e1), "ev");
558    auto time = [&](const std::function<void(int)>& call) {
559        call(0);
560        ck(cudaDeviceSynchronize(), "warm");
561        ck(cudaEventRecord(e0), "rec");
562        for (int i = 0; i < ITERS; ++i) call(i % SETS);
563        ck(cudaEventRecord(e1), "rec");
564        ck(cudaEventSynchronize(e1), "sync");
565        float ms = 0;
566        ck(cudaEventElapsedTime(&ms, e0, e1), "elapsed");
567        return 1000.0 * ms / ITERS;
568    };
569    auto ab = [&](const char* name, double blobs_per_call, const std::function<void(int)>& call) {
570        double us[2];
571        for (int old = 1; old >= 0; --old) {
572            k::moe_grouped_select_old(old);
573            us[old ? 0 : 1] = time(call);
574        }
575        k::moe_grouped_select_old(-1);
576        const double gb = blobs_per_call * (double) BLOB / 1e3;   // bytes / us = MB/s ... / 1e3 -> GB/s
577        std::printf("  %-40s previous %8.1f us (%6.0f GB/s)   new %8.1f us (%6.0f GB/s)   x%.2f\n", name, us[0],
578                    gb / us[0], us[1], gb / us[1], us[0] / us[1]);
579    };
580
581    // per-hit path, decode: 9 hits of 10 (5090-like residency), 5 of 10, and the low-residency 1-3 hits, where the
582    // new kernels' grid (80 gate/up blocks per hit) is below one block per SM - see `STRATA_GROUPED_PAIR_MIN_HITS`
583    for (const int n_hits : {9, 5, 3, 2, 1}) {
584        std::vector<int32_t> slots((size_t) SETS * n_hits), dst(K);
585        for (auto& v : slots) v = (int32_t) (rng() % nb);
586        std::iota(dst.begin(), dst.end(), 0);
587        int32_t* d_slots = dalloc<int32_t>(slots.size());
588        int32_t* d_dst = dalloc<int32_t>(K);
589        up(d_slots, slots);
590        up(d_dst, dst);
591        const Scratch s = make_scratch(n_hits);
592        float* d_out = dalloc<float>((size_t) K * H);
593        const std::string name = "moe_hit_grouped_s2, " + std::to_string(n_hits) + " hits";
594        ab(name.c_str(), n_hits, [&](int set) {
595            k::moe_hit_grouped_s2(fx.d, d_slots + (size_t) set * n_hits, d_dst, n_hits, (int64_t) BLOB, d_x, s.p,
596                                  d_out, nullptr, d_xs);
597        });
598    }
599    // grouped path, verify window: T tokens x 10, routed with `share` = the chance an entry reuses an expert already
600    // routed by an earlier token of the window
601    struct Shape { int T; double share; const char* what; };
602    for (const Shape sh : {Shape{1, 0.0, "1 token, MTP shape"},
603                           Shape{4, 0.0, "4 tokens, no sharing"}, Shape{4, 0.3, "4 tokens, 30% shared"},
604                           Shape{8, 0.3, "8 tokens, 30% shared"}, Shape{8, 1.0, "8 tokens, all shared (ne 8)"}}) {
605        const int n = sh.T * K;
606        std::vector<unsigned long long> gptr((size_t) SETS * n);
607        std::vector<int32_t> gstart((size_t) SETS * (n + 1)), ng(SETS), edst((size_t) SETS * n), etok((size_t) SETS * n);
608        double groups = 0;
609        std::uniform_real_distribution<double> u(0, 1);
610        for (int set = 0; set < SETS; ++set) {
611            std::vector<std::vector<int>> g;       // per group: routing indices
612            std::vector<int> gexp;                 // per group: blob
613            for (int t = 0; t < sh.T; ++t) {
614                std::vector<char> used(g.size(), 0);
615                for (int j = 0; j < K; ++j) {
616                    int pick = -1;
617                    if (t > 0 && u(rng) < sh.share)
618                        for (size_t q = 0; q < g.size(); ++q)
619                            if (!used[q] && (int) g[q].size() < 8) { pick = (int) q; break; }
620                    if (pick < 0) {
621                        pick = (int) g.size();
622                        g.emplace_back();
623                        gexp.push_back((int) (rng() % nb));
624                        used.push_back(0);
625                    }
626                    used[(size_t) pick] = 1;
627                    g[(size_t) pick].push_back(t * K + j);
628                }
629            }
630            int at = 0;
631            for (size_t q = 0; q < g.size(); ++q) {
632                gptr[(size_t) set * n + q] = (unsigned long long) (fx.d + (size_t) gexp[q] * BLOB);
633                gstart[(size_t) set * (n + 1) + q] = at;
634                for (int e : g[q]) {
635                    edst[(size_t) set * n + at] = e;
636                    etok[(size_t) set * n + at] = e / K;
637                    ++at;
638                }
639            }
640            for (size_t q = g.size(); q <= (size_t) n; ++q) gstart[(size_t) set * (n + 1) + q] = at;
641            ng[set] = (int32_t) g.size();
642            groups += (double) g.size() / SETS;
643        }
644        unsigned long long* d_gptr = dalloc<unsigned long long>(gptr.size());
645        int32_t* d_gstart = dalloc<int32_t>(gstart.size());
646        int32_t* d_ng = dalloc<int32_t>(SETS);
647        int32_t* d_edst = dalloc<int32_t>(edst.size());
648        int32_t* d_etok = dalloc<int32_t>(etok.size());
649        up(d_gptr, gptr);
650        up(d_gstart, gstart);
651        up(d_ng, ng);
652        up(d_edst, edst);
653        up(d_etok, etok);
654        const Scratch s = make_scratch(n);
655        float* d_out = dalloc<float>((size_t) n * H);
656        char name[96];
657        std::snprintf(name, sizeof name, "moe_grouped_s2, %s (%.0f groups)", sh.what, groups);
658        ab(name, groups, [&](int set) {
659            k::moe_grouped_s2(d_gptr + (size_t) set * n, d_gstart + (size_t) set * (n + 1), d_ng + set,
660                              d_edst + (size_t) set * n, d_etok + (size_t) set * n, n, n, d_x, d_xs, s.p, d_out,
661                              nullptr);
662        });
663    }
664}
665}  // namespace
666
667int main(int argc, char** argv) {
668    bool do_bench = false;
669    for (int i = 1; i < argc; ++i) {
670        if (std::strcmp(argv[i], "--bench") == 0) do_bench = true;
671        else if (std::strcmp(argv[i], "--selftest") != 0) {
672            std::fprintf(stderr, "usage: s2_expert_grouped_parity [--selftest] [--bench]\n");
673            return 2;
674        }
675    }
676    std::printf("s2_expert_grouped_parity: new expert kernels vs the previous ones, bitwise\n");
677    check_all();
678    if (do_bench) bench();
679    std::printf("s2_expert_grouped_parity: %d failures\n%s\n", g_fail, g_fail ? "FAIL" : "PASS");
680    return g_fail ? 1 : 0;
681}