okami.mom/strata

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

Niko1221Merge f-q4-sycl (41717f29c): the Intel Arc (SYCL) engine follows the compiled geometry, so q4_lite/q4_mid/q4_big build; default build unchanged (CUDA SASS 3573/3573, HIP gfx1201 3920/3920, gfx1151 string offsets only, Metal 85/85 objects, SYCL 22/22 checksums); A750 gate 2 q4_lite 0.00021 vs floor 0.00017; one conflict with f-clean-6-0 in sycl/src/prefill/prefill.cpp resolved as tested by Q4-SYMERGE (Qwen4 prep)db137d917

main
36.9 KiB791 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#define DPCT_PROFILING_ENABLED
27#include <sycl/sycl.hpp>
28#include <dpct/dpct.hpp>
29#include "strata/kernels/f16_bits.hpp"
30#include "strata/kernels/s2_expert_grouped.hpp"
31#include "strata/core/geometry.hpp"
32
33#include <algorithm>
34#include <cmath>
35#include <cstdint>
36#include <cstdio>
37#include <cstdlib>
38#include <cstring>
39#include <functional>
40#include <numeric>
41#include <random>
42#include <string>
43#include <vector>
44
45namespace k = strata::kernels;
46
47namespace {
48// The blob geometry, `cpu/expert.hpp`'s (restated as in the kernel).
49constexpr int H = strata::core::kCompiledGeometry.n_embd, FF = strata::core::kCompiledGeometry.n_ff, NCH_GU = H / 32, NCH_D = FF / 32;   // the compiled shape (Q4-SYCL; Flash-Next 2560 x 640)
50constexpr size_t ROW_GU = H / 4, ROW_D = FF / 4, SC_GU = H / 64, SC_D = FF / 64;
51constexpr size_t O_D_CODES = 2ull * FF * ROW_GU;
52constexpr size_t O_GU_SCALES = O_D_CODES + (size_t) H * ROW_D;
53constexpr size_t O_D_SCALES = O_GU_SCALES + 2ull * FF * SC_GU * 2;
54constexpr size_t BLOB = O_D_SCALES + (size_t) H * SC_D * 2;
55static_assert(H != 2560 || FF != 640 || BLOB == 1382400, "the Q2_0 expert blob of Flash-Next's 2560 x 640 is 1,382,400 bytes");
56constexpr size_t XROW = (size_t) NCH_GU * 34;   // one token's activation row of block_q8_0
57
58int g_fail = 0;
59
60void ck(dpct::err0 e, const char *w) {
61    /*
62    DPCT1009: SYCL reports errors using exceptions and does not use error
63    codes. Please replace the "get_error_string_dummy(...)" with a real
64    error-handling function.
65    */
66}
67template <typename T> T* dalloc(size_t n) {
68    T* p = nullptr;
69    ck(DPCT_CHECK_ERROR(p = (T *)sycl::malloc_device(
70                            n * sizeof(T) + 256, dpct::get_in_order_queue())),
71       "malloc");
72    ck(DPCT_CHECK_ERROR(
73           (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memset(p, 0, n * sizeof(T) + 256).wait()),
74       "memset");
75    return p;
76}
77template <typename T> void up(T* d, const std::vector<T>& h) {
78    /*
79    DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming in
80    the original code the source host memory is pageable memory. If the memory
81    is not pageable, call wait() on event return by memcpy API to ensure
82    synchronization behavior.
83    */
84    ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
85           d, h.data(), h.size() * sizeof(T)).wait()),
86       "h2d");
87}
88template <typename T> std::vector<T> down(const T* d, size_t n) {
89    std::vector<T> h(n);
90    ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
91                            .memcpy(h.data(), d, n * sizeof(T))
92                            .wait()),
93       "d2h");
94    return h;
95}
96
97float f16f(const uint8_t* p) { return k::f32_from_f16((uint16_t) (p[0] | (p[1] << 8))); }
98void put16(uint8_t* p, float f) {
99    const uint16_t h = k::f16_from_f32(f);
100    p[0] = (uint8_t) h;
101    p[1] = (uint8_t) (h >> 8);
102}
103
104// Random codes; fp16 scales of either sign in [1e-3, 3e-2] (a real pack's range, so no overflow downstream).
105void fill_blob(uint8_t* b, std::mt19937& rng) {
106    for (size_t i = 0; i < O_GU_SCALES; ++i) b[i] = (uint8_t) rng();
107    std::uniform_real_distribution<float> mag(1e-3f, 3e-2f);
108    for (size_t i = O_GU_SCALES; i < BLOB; i += 2) put16(b + i, (rng() & 1 ? -1.0f : 1.0f) * mag(rng));
109}
110
111// `n_tok` activation rows: per 32-chunk an fp16 `d` then 32 int8 in [-127, 127] (what `quantize_q8_0` writes),
112// plus the fp32 scales `quantize_q8_0_scaled` would pass alongside.  Some chunks are saturated on purpose.
113void fill_x(std::vector<uint8_t>& x, std::vector<float>& xs, int n_tok, std::mt19937& rng) {
114    x.assign((size_t) n_tok * XROW, 0);
115    xs.assign((size_t) n_tok * NCH_GU, 0.0f);
116    std::uniform_real_distribution<float> sc(2e-3f, 5e-2f);
117    for (size_t c = 0; c < (size_t) n_tok * NCH_GU; ++c) {
118        uint8_t* b = x.data() + c * 34;
119        xs[c] = sc(rng);
120        put16(b, xs[c]);
121        const int mode = (int) (rng() % 16);
122        for (int j = 0; j < 32; ++j) {
123            const int v = mode == 0 ? 127 : mode == 1 ? -127 : (int) (rng() % 255) - 127;
124            b[2 + j] = (uint8_t) (int8_t) v;
125        }
126    }
127}
128
129// Double-precision reference of one row against one activation row: sum_c dw * dx * sum_e (code_e - 1) * x_e.
130// `mag` receives sum |term|, the scale the tolerance is relative to.
131double row_ref(const uint8_t* codes, const uint8_t* scales, const uint8_t* xrow, const float* xs, int n_chunks,
132               double* mag) {
133    double acc = 0.0, a = 0.0;
134    for (int c = 0; c < n_chunks; ++c) {
135        const uint8_t* xb = xrow + (size_t) c * 34;
136        const double dx = xs ? (double) xs[c] : (double) f16f(xb);
137        const double dw = (double) f16f(scales + (size_t) (c >> 1) * 2);
138        int s = 0;
139        for (int e = 0; e < 32; ++e) {
140            const int code = (codes[(size_t) c * 8 + e / 4] >> (2 * (e % 4))) & 3;
141            s += (code - 1) * (int) (int8_t) xb[2 + e];
142        }
143        const double t = dw * dx * (double) s;
144        acc += t;
145        a += std::fabs(t);
146    }
147    *mag = a;
148    return acc;
149}
150
151bool close_to(float got, double ref, double mag) {
152    return std::isfinite(got) && std::fabs((double) got - ref) <= 4e-5 * mag + 1e-30;
153}
154
155struct Scratch {
156    void* p = nullptr;
157    uint64_t bytes = 0;
158    int64_t cap = 0;
159    uint64_t gu_bytes() const { return ((uint64_t) cap * 2 * FF * 4 + 15) & ~15ull; }
160    uint64_t q8_bytes() const { return ((uint64_t) cap * NCH_D * 34 + 15) & ~15ull; }
161};
162
163// One entry point, run with the previous kernels then with the new ones from identical sentinel-filled buffers;
164// every differing float of the output and byte of the scratch is counted.  `keep` receives the new run.
165struct Run {
166    std::vector<float> out;
167    std::vector<uint8_t> scratch;
168};
169
170bool twice(const char* name, float* d_out, size_t out_floats, const Scratch& s,
171           const std::function<void()>& call, Run* keep, bool expect_new = true) {
172    Run r[2];
173    for (int old = 1; old >= 0; --old) {
174        ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
175                                .memset(d_out, 0xA5, out_floats * 4)
176                                .wait()),
177           "sentinel out");
178        ck(DPCT_CHECK_ERROR(
179               (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memset(s.p, 0x5A, s.bytes).wait()),
180           "sentinel scratch");
181        k::moe_grouped_select_old(old);
182        (void) k::moe_grouped_last_path();   // clear
183        call();
184        const int path = k::moe_grouped_last_path();
185        const int want = old ? 0 : (expect_new ? 1 : 0);
186        if (path != want) {
187            std::printf("  %-44s forced %s: launched %s kernels, expected %s\n", name, old ? "previous" : "new",
188                        path == 1 ? "the new" : path == 0 ? "the previous" : "no", want ? "the new" : "the previous");
189            ++g_fail;
190        }
191        /*
192        DPCT1010: SYCL uses exceptions to report errors and does not use the
193        error codes. The cudaGetLastError function call was replaced with 0. You
194        need to rewrite this code.
195        */
196        ck(0, name);
197        ck(DPCT_CHECK_ERROR(dpct::get_current_device().queues_wait_and_throw()),
198           name);
199        Run& x = r[old ? 0 : 1];
200        x.out = down(d_out, out_floats);
201        x.scratch = down((const uint8_t*) s.p, (size_t) s.bytes);
202    }
203    k::moe_grouped_select_old(-1);
204    const uint64_t gu = s.gu_bytes(), q8 = s.q8_bytes();
205    size_t diff_out = 0, diff_gu = 0, diff_q8 = 0, diff_hs = 0;
206    for (size_t i = 0; i < out_floats; ++i)
207        diff_out += std::memcmp(&r[0].out[i], &r[1].out[i], 4) != 0;
208    for (size_t i = 0; i < (size_t) s.bytes; ++i) {
209        if (r[0].scratch[i] == r[1].scratch[i]) continue;
210        if (i < gu) ++diff_gu;
211        else if (i < gu + q8) ++diff_q8;
212        else ++diff_hs;
213    }
214    const bool ok = diff_out + diff_gu + diff_q8 + diff_hs == 0;
215    std::printf("  %-44s %s", name, ok ? "bitwise identical" : "DIFFERS");
216    if (!ok)
217        std::printf(" (out %zu floats, gate/up %zu B, intermediate %zu B, its scales %zu B)", diff_out, diff_gu,
218                    diff_q8, diff_hs);
219    std::printf("\n");
220    if (!ok) ++g_fail;
221    if (keep) *keep = std::move(r[1]);
222    return ok;
223}
224
225// The host reference on a finished run: every up row (the second half of gate/up, which the swiglu leaves alone)
226// against the activation row it read, and every written down row against the intermediate the run produced.
227struct Entry {
228    const uint8_t* blob;   // host copy of the entry's blob
229    int tok;               // activation row it reads
230    int dst;               // output row it writes
231};
232void reference(const char* name, const Run& r, const Scratch& s, const std::vector<Entry>& ent,
233               const std::vector<uint8_t>& x, const std::vector<float>* xs) {
234    const float* gu = (const float*) r.scratch.data();
235    const uint8_t* hq = r.scratch.data() + s.gu_bytes();
236    const float* hs = (const float*) (r.scratch.data() + s.gu_bytes() + s.q8_bytes());
237    long checked = 0, bad = 0;
238    double worst = 0.0;
239    for (size_t e = 0; e < ent.size(); ++e) {
240        const uint8_t* b = ent[e].blob;
241        const uint8_t* xrow = x.data() + (size_t) ent[e].tok * XROW;
242        const float* xsr = xs ? xs->data() + (size_t) ent[e].tok * NCH_GU : nullptr;
243        for (int rr = 0; rr < FF; rr += 7) {   // up row rr = row-slot 2rr + 1
244            double mag;
245            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,
246                                       xrow, xsr, NCH_GU, &mag);
247            const float got = gu[(size_t) s.cap * FF + e * FF + (size_t) rr];
248            ++checked;
249            if (!close_to(got, ref, mag)) ++bad;
250            if (mag > 0) worst = std::max(worst, std::fabs((double) got - ref) / mag);
251        }
252        const uint8_t* hrow = hq + e * (size_t) NCH_D * 34;
253        const float* hsr = xs ? hs + e * (size_t) NCH_D : nullptr;
254        for (int rr = 0; rr < H; rr += 13) {
255            double mag;
256            const double ref = row_ref(b + O_D_CODES + (size_t) rr * ROW_D, b + O_D_SCALES + (size_t) rr * SC_D * 2,
257                                       hrow, hsr, NCH_D, &mag);
258            const float got = r.out[(size_t) ent[e].dst * H + (size_t) rr];
259            ++checked;
260            if (!close_to(got, ref, mag)) ++bad;
261            if (mag > 0) worst = std::max(worst, std::fabs((double) got - ref) / mag);
262        }
263    }
264    std::printf("  %-44s host reference: %ld rows, %ld outside tolerance, worst %.2e of sum|term|\n", name, checked,
265                bad, worst);
266    if (bad || checked == 0) ++g_fail;
267}
268
269struct Fixture {
270    int nb = 0;
271    std::vector<uint8_t> h;   // nb blobs
272    uint8_t* d = nullptr;
273    const uint8_t* hb(int i) const { return h.data() + (size_t) i * BLOB; }
274};
275
276Fixture make_blobs(int nb, std::mt19937& rng) {
277    Fixture f;
278    f.nb = nb;
279    f.h.resize((size_t) nb * BLOB);
280    for (int i = 0; i < nb; ++i) fill_blob(f.h.data() + (size_t) i * BLOB, rng);
281    f.d = dalloc<uint8_t>((size_t) nb * BLOB);
282    up(f.d, f.h);
283    return f;
284}
285
286Scratch make_scratch(int64_t cap) {
287    Scratch s;
288    s.cap = cap;
289    s.bytes = k::moe_hit_grouped_scratch_bytes(cap, H, FF);
290    s.p = dalloc<uint8_t>(s.bytes);
291    return s;
292}
293
294// ---------------------------------------------------------------- the checks
295void check_all() {
296    std::mt19937 rng(20260928);
297    const Fixture fx = make_blobs(12, rng);
298    constexpr int K = 10;
299
300    // Activations for up to 8 tokens, device copies with and without the fp32 scales.
301    std::vector<uint8_t> x;
302    std::vector<float> xs;
303    fill_x(x, xs, 8, rng);
304    uint8_t* d_x = dalloc<uint8_t>(x.size());
305    float* d_xs = dalloc<float>(xs.size());
306    up(d_x, x);
307    up(d_xs, xs);
308
309    // ---- 1. moe_hit_grouped_s2: 9 hits of 10 routed rows, slots and destinations shuffled
310    {
311        const int n_hits = 9;
312        std::vector<int32_t> slot(n_hits), dst(K);
313        for (int i = 0; i < n_hits; ++i) slot[i] = (int32_t) ((i * 5 + 3) % fx.nb);
314        std::iota(dst.begin(), dst.end(), 0);
315        std::shuffle(dst.begin(), dst.end(), rng);
316        dst.resize(n_hits);
317        int32_t* d_slot = dalloc<int32_t>(n_hits);
318        int32_t* d_dst = dalloc<int32_t>(n_hits);
319        up(d_slot, slot);
320        up(d_dst, dst);
321        const Scratch s = make_scratch(n_hits);
322        float* d_out = dalloc<float>((size_t) K * H);
323        std::vector<Entry> ent;
324        for (int i = 0; i < n_hits; ++i) ent.push_back({fx.hb(slot[i]), 0, dst[i]});
325        for (int scaled = 1; scaled >= 0; --scaled) {
326            Run r;
327            const std::string name = std::string("moe_hit_grouped_s2") + (scaled ? " (fp32 scales)" : " (fp16 d)");
328            twice(name.c_str(), d_out, (size_t) K * H, s, [&] {
329                k::moe_hit_grouped_s2(fx.d, d_slot, d_dst, n_hits, (int64_t) BLOB, d_x, s.p, d_out, nullptr,
330                                      scaled ? d_xs : nullptr);
331            }, &r);
332            reference(name.c_str(), r, s, ent, x, scaled ? &xs : nullptr);
333        }
334    }
335
336    // ---- 2. moe_hit_grouped_s2_dev: capacity 10, device count 7
337    {
338        const int cap = 10, count = 7;
339        std::vector<int32_t> slot(cap), dst(cap);
340        for (int i = 0; i < cap; ++i) slot[i] = (int32_t) ((i * 7 + 1) % fx.nb);
341        std::iota(dst.begin(), dst.end(), 0);
342        std::shuffle(dst.begin(), dst.end(), rng);
343        int32_t* d_slot = dalloc<int32_t>(cap);
344        int32_t* d_dst = dalloc<int32_t>(cap);
345        int32_t* d_count = dalloc<int32_t>(1);
346        up(d_slot, slot);
347        up(d_dst, dst);
348        up(d_count, std::vector<int32_t>{count});
349        const Scratch s = make_scratch(cap);
350        float* d_out = dalloc<float>((size_t) K * H);
351        std::vector<Entry> ent;
352        for (int i = 0; i < count; ++i) ent.push_back({fx.hb(slot[i]), 0, dst[i]});
353        Run r;
354        twice("moe_hit_grouped_s2_dev (count 7 of 10)", d_out, (size_t) K * H, s, [&] {
355            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,
356                                      d_xs);
357        }, &r);
358        reference("moe_hit_grouped_s2_dev (count 7 of 10)", r, s, ent, x, &xs);
359        // the rows of the hits past the count keep the sentinel
360        long touched = 0;
361        for (int i = count; i < cap; ++i)
362            for (int c = 0; c < H; ++c) {
363                uint32_t v;
364                std::memcpy(&v, &r.out[(size_t) dst[i] * H + c], 4);
365                touched += v != 0xA5A5A5A5u;
366            }
367        std::printf("  %-44s rows past the count written: %ld\n", "moe_hit_grouped_s2_dev (count 7 of 10)", touched);
368        if (touched) ++g_fail;
369    }
370
371    // ---- 3. moe_hit_grouped_s2_multi: 4 tokens x 10 routed entries, 29 hits
372    {
373        const int T = 4, n = T * K, count = 29;
374        std::vector<int32_t> ent_ids(n);
375        std::iota(ent_ids.begin(), ent_ids.end(), 0);
376        std::shuffle(ent_ids.begin(), ent_ids.end(), rng);
377        std::vector<int32_t> slot(n), dst(n);
378        for (int i = 0; i < n; ++i) {
379            dst[i] = ent_ids[i];
380            slot[i] = (int32_t) (rng() % fx.nb);
381        }
382        std::sort(dst.begin(), dst.begin() + count);   // hit order is routing order, as `moe_hit_select_multi` makes it
383        int32_t* d_slot = dalloc<int32_t>(n);
384        int32_t* d_dst = dalloc<int32_t>(n);
385        int32_t* d_count = dalloc<int32_t>(1);
386        up(d_slot, slot);
387        up(d_dst, dst);
388        up(d_count, std::vector<int32_t>{count});
389        const Scratch s = make_scratch(n);
390        float* d_out = dalloc<float>((size_t) n * H);
391        std::vector<Entry> ent;
392        for (int i = 0; i < count; ++i) ent.push_back({fx.hb(slot[i]), dst[i] / K, dst[i]});
393        Run r;
394        twice("moe_hit_grouped_s2_multi (4 tokens, 29 hits)", d_out, (size_t) n * H, s, [&] {
395            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,
396                                        nullptr);
397        }, &r);
398        reference("moe_hit_grouped_s2_multi (4 tokens, 29 hits)", r, s, ent, x, &xs);
399    }
400
401    // ---- 4. moe_grouped_s2: 8 tokens x 10 entries in groups of 1..8, one group on a mapped host blob
402    {
403        const int T = 8, n = T * K;
404        uint8_t* h_host = nullptr;
405        uint8_t* d_host = nullptr;
406        /*
407        DPCT1048: The original value cudaHostAllocMapped is not meaningful in
408        the migrated code and was removed or replaced with 0. You may need to
409        check the migrated code.
410        */
411        ck(DPCT_CHECK_ERROR(h_host = (uint8_t *)sycl::malloc_host(
412                                BLOB, dpct::get_in_order_queue())),
413           "host blob");
414        std::memcpy(h_host, fx.hb(fx.nb - 1), BLOB);
415        ck(DPCT_CHECK_ERROR(*(void **)&d_host = (uint8_t *)h_host),
416           "host blob ptr");
417        // group sizes: 8, 1, 5, 2, 7, 3, 1, 6, 4, ... up to n entries
418        const int sizes[] = {8, 1, 5, 2, 7, 3, 1, 6, 4, 8, 1, 2, 3, 4, 5, 6, 7, 1, 1, 5};
419        std::vector<int32_t> order(n);   // the output rows, in group order
420        std::iota(order.begin(), order.end(), 0);
421        std::shuffle(order.begin(), order.end(), rng);
422        std::vector<unsigned long long> gptr;
423        std::vector<int32_t> gstart{0}, edst, etok;
424        std::vector<Entry> ent;
425        int at = 0, gi = 0;
426        while (at < n) {
427            const int sz = std::min(sizes[gi % 20], n - at);
428            const bool host = gi == 3;
429            const int b = gi % (fx.nb - 1);
430            gptr.push_back((unsigned long long) (host ? d_host : fx.d + (size_t) b * BLOB));
431            for (int j = 0; j < sz; ++j, ++at) {
432                edst.push_back(order[at]);
433                etok.push_back(order[at] / K);
434                ent.push_back({host ? h_host : fx.hb(b), order[at] / K, order[at]});
435            }
436            gstart.push_back(at);
437            ++gi;
438        }
439        const int n_groups = gi, cap_groups = n_groups + 3;
440        gstart.resize((size_t) cap_groups + 1, at);
441        gptr.resize((size_t) cap_groups, gptr[0]);
442        unsigned long long* d_gptr = dalloc<unsigned long long>(gptr.size());
443        int32_t* d_gstart = dalloc<int32_t>(gstart.size());
444        int32_t* d_ng = dalloc<int32_t>(1);
445        int32_t* d_edst = dalloc<int32_t>(n);
446        int32_t* d_etok = dalloc<int32_t>(n);
447        up(d_gptr, gptr);
448        up(d_gstart, gstart);
449        up(d_ng, std::vector<int32_t>{n_groups});
450        up(d_edst, edst);
451        up(d_etok, etok);
452        const Scratch s = make_scratch(n);
453        float* d_out = dalloc<float>((size_t) n * H);
454        for (int scaled = 1; scaled >= 0; --scaled) {
455            Run r;
456            const std::string name = std::string("moe_grouped_s2 (") + std::to_string(n_groups) + " groups" +
457                                     (scaled ? ", fp32 scales)" : ", fp16 d)");
458            twice(name.c_str(), d_out, (size_t) n * H, s, [&] {
459                k::moe_grouped_s2(d_gptr, d_gstart, d_ng, d_edst, d_etok, cap_groups, n, d_x, scaled ? d_xs : nullptr,
460                                  s.p, d_out, nullptr);
461            }, &r);
462            reference(name.c_str(), r, s, ent, x, scaled ? &xs : nullptr);
463        }
464        ck(DPCT_CHECK_ERROR(sycl::free(h_host, dpct::get_in_order_queue())),
465           "free host blob");
466    }
467
468    // ---- 5. moe_group_resident + moe_grouped_s2: the MTP layer (experts resident at base + id * BLOB)
469    {
470        const int T = 5, n = T * K;
471        std::vector<int32_t> ids(n);
472        for (int t = 0; t < T; ++t) {   // distinct within a token, shared across tokens
473            std::vector<int32_t> pick(fx.nb);
474            std::iota(pick.begin(), pick.end(), 0);
475            std::shuffle(pick.begin(), pick.end(), rng);
476            for (int j = 0; j < K; ++j) ids[(size_t) t * K + j] = pick[j];
477        }
478        int32_t* d_ids = dalloc<int32_t>(n);
479        up(d_ids, ids);
480        unsigned long long* d_gptr = dalloc<unsigned long long>(n);
481        int32_t* d_gstart = dalloc<int32_t>(n + 1);
482        int32_t* d_counts = dalloc<int32_t>(2);
483        int32_t* d_edst = dalloc<int32_t>(n);
484        int32_t* d_etok = dalloc<int32_t>(n);
485        k::moe_group_resident(d_ids, n, K, fx.d, (int64_t) BLOB, d_gptr, d_gstart, d_counts, d_edst, d_etok, nullptr);
486        ck(DPCT_CHECK_ERROR(dpct::get_current_device().queues_wait_and_throw()),
487           "group_resident");
488        const std::vector<int32_t> edst = down(d_edst, n), etok = down(d_etok, n);
489        std::vector<Entry> ent(n);   // entry e: dst = routing index, blob = its expert
490        for (int e = 0; e < n; ++e) ent[e] = {fx.hb(ids[(size_t) edst[e]]), etok[e], edst[e]};
491        const Scratch s = make_scratch(n);
492        float* d_out = dalloc<float>((size_t) n * H);
493        for (int scaled = 1; scaled >= 0; --scaled) {
494            Run r;
495            const std::string name = std::string("moe_group_resident + moe_grouped_s2") + (scaled ? " (fp32)" : " (fp16)");
496            twice(name.c_str(), d_out, (size_t) n * H, s, [&] {
497                k::moe_grouped_s2(d_gptr, d_gstart, d_counts, d_edst, d_etok, n, n, d_x, scaled ? d_xs : nullptr, s.p,
498                                  d_out, nullptr);
499            }, &r);
500            reference(name.c_str(), r, s, ent, x, scaled ? &xs : nullptr);
501        }
502    }
503
504    // ---- 6. a 2-byte aligned activation row: the new path must decline and the previous kernels run
505    {
506        uint8_t* d_x2 = dalloc<uint8_t>(x.size() + 2);
507        /*
508        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
509        assuming in the original code the source host memory is pageable memory.
510        If the memory is not pageable, call wait() on event return by memcpy API
511        to ensure synchronization behavior.
512        */
513        ck(DPCT_CHECK_ERROR(
514               (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(d_x2 + 2, x.data(), XROW).wait()),
515           "x2");
516        const int n_hits = 3;
517        std::vector<int32_t> slot{2, 5, 7}, dst{4, 0, 9};
518        int32_t* d_slot = dalloc<int32_t>(n_hits);
519        int32_t* d_dst = dalloc<int32_t>(n_hits);
520        up(d_slot, slot);
521        up(d_dst, dst);
522        const Scratch s = make_scratch(n_hits);
523        float* d_out = dalloc<float>((size_t) K * H);
524        std::vector<Entry> ent;
525        for (int i = 0; i < n_hits; ++i) ent.push_back({fx.hb(slot[i]), 0, dst[i]});
526        Run r;
527        twice("moe_hit_grouped_s2 (2-byte aligned x)", d_out, (size_t) K * H, s, [&] {
528            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);
529        }, &r, /*expect_new=*/false);
530        reference("moe_hit_grouped_s2 (2-byte aligned x)", r, s, ent, x, &xs);
531    }
532
533    // ---- 7. slots BLOB + 4 bytes apart, and 8. an arena at an address that is 4 mod 8: per-hit fallback
534    {
535        constexpr size_t STRIDE = BLOB + 4;
536        static_assert(STRIDE % 8 != 0, "the stride must defeat the uint2 code loads");
537        const int nb = 8;
538        uint8_t* d_arena = dalloc<uint8_t>((size_t) nb * STRIDE + 8);
539        const int n_hits = 4;
540        std::vector<int32_t> slot{6, 1, 3, 0}, dst{2, 7, 5, 8};
541        int32_t* d_slot = dalloc<int32_t>(n_hits);
542        int32_t* d_dst = dalloc<int32_t>(n_hits);
543        up(d_slot, slot);
544        up(d_dst, dst);
545        const Scratch s = make_scratch(n_hits);
546        float* d_out = dalloc<float>((size_t) K * H);
547        std::vector<Entry> ent;
548        for (int i = 0; i < n_hits; ++i) ent.push_back({fx.hb(slot[i]), 0, dst[i]});
549        // One allocation for both layouts: the BLOB + 4 strided copies first, then the same blobs BLOB apart from
550        // `d_arena + 4` over them.
551        for (int i = 0; i < nb; ++i)
552            /*
553            DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
554            assuming in the original code the source host memory is pageable
555            memory. If the memory is not pageable, call wait() on event return
556            by memcpy API to ensure synchronization behavior.
557            */
558            ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
559                   d_arena + (size_t)i * STRIDE, fx.hb(i), BLOB).wait()),
560               "arena");
561        {
562            Run r;
563            twice("moe_hit_grouped_s2 (slot stride BLOB + 4)", d_out, (size_t) K * H, s, [&] {
564                k::moe_hit_grouped_s2(d_arena, d_slot, d_dst, n_hits, (int64_t) STRIDE, d_x, s.p, d_out, nullptr,
565                                      d_xs);
566            }, &r, /*expect_new=*/false);
567            reference("moe_hit_grouped_s2 (slot stride BLOB + 4)", r, s, ent, x, &xs);
568        }
569        for (int i = 0; i < nb; ++i)
570            /*
571            DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
572            assuming in the original code the source host memory is pageable
573            memory. If the memory is not pageable, call wait() on event return
574            by memcpy API to ensure synchronization behavior.
575            */
576            ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
577                   d_arena + 4 + (size_t)i * BLOB, fx.hb(i), BLOB).wait()),
578               "arena");
579        {
580            Run r;
581            twice("moe_hit_grouped_s2 (arena 4 mod 8)", d_out, (size_t) K * H, s, [&] {
582                k::moe_hit_grouped_s2(d_arena + 4, d_slot, d_dst, n_hits, (int64_t) BLOB, d_x, s.p, d_out, nullptr,
583                                      d_xs);
584            }, &r, /*expect_new=*/false);
585            reference("moe_hit_grouped_s2 (arena 4 mod 8)", r, s, ent, x, &xs);
586        }
587    }
588}
589
590// ---------------------------------------------------------------- --bench
591// Engine-like shapes with the blobs cycled through a set larger than the L2, so each call reads its codes from
592// DRAM as the engine's do.  Reports microseconds per call and the codes' effective bandwidth.
593void bench() {
594    int dev = 0;
595    dpct::device_info prop{};
596    ck(DPCT_CHECK_ERROR(dev = dpct::get_current_device_id()), "dev");
597    ck(DPCT_CHECK_ERROR(dpct::get_device(dev).get_device_info(prop)), "props");
598    /*
599    DPCT1051: SYCL does not support a device property functionally
600    compatible with l2CacheSize. It was migrated to global_mem_cache_size. You
601    may need to adjust the value of global_mem_cache_size for the specific
602    device.
603    */
604    const int nb = std::max(
605        48, (int)(3ull * (size_t)prop.get_global_mem_cache_size() / BLOB) + 8);
606    /*
607    DPCT1051: SYCL does not support a device property functionally
608    compatible with l2CacheSize. It was migrated to global_mem_cache_size. You
609    may need to adjust the value of global_mem_cache_size for the specific
610    device.
611    */
612    std::printf("bench: %s, L2 %d MB, %d blobs (%.0f MB) cycled\n",
613                prop.get_name(), prop.get_global_mem_cache_size() >> 20, nb,
614                nb * (double)BLOB / 1e6);
615    std::mt19937 rng(7);
616    Fixture fx;
617    fx.nb = nb;
618    fx.d = dalloc<uint8_t>((size_t) nb * BLOB);
619    {
620        std::vector<uint8_t> b(BLOB);
621        for (int i = 0; i < nb; ++i) {
622            fill_blob(b.data(), rng);
623            /*
624            DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
625            assuming in the original code the source host memory is pageable
626            memory. If the memory is not pageable, call wait() on event return
627            by memcpy API to ensure synchronization behavior.
628            */
629            ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
630                   fx.d + (size_t)i * BLOB, b.data(), BLOB).wait()),
631               "blob");
632        }
633    }
634    std::vector<uint8_t> x;
635    std::vector<float> xs;
636    fill_x(x, xs, 8, rng);
637    uint8_t* d_x = dalloc<uint8_t>(x.size());
638    float* d_xs = dalloc<float>(xs.size());
639    up(d_x, x);
640    up(d_xs, xs);
641    constexpr int K = 10, ITERS = 200, SETS = 16;
642    dpct::event_ptr e0, e1;
643    ck(DPCT_CHECK_ERROR(e0 = new sycl::event()), "ev");
644    ck(DPCT_CHECK_ERROR(e1 = new sycl::event()), "ev");
645    auto time = [&](const std::function<void(int)> &call) {
646        try {
647    call(0);
648        ck(DPCT_CHECK_ERROR(dpct::get_current_device().queues_wait_and_throw()),
649           "warm");
650        /*
651        DPCT1024: The original code returned the error code that was further
652        consumed by the program logic. This original code was replaced with 0.
653        You may need to rewrite the program logic consuming the error code.
654        */
655        ck(DPCT_CHECK_ERROR(dpct::sync_barrier(e0)), "rec");
656        for (int i = 0; i < ITERS; ++i) call(i % SETS);
657        /*
658        DPCT1024: The original code returned the error code that was further
659        consumed by the program logic. This original code was replaced with 0.
660        You may need to rewrite the program logic consuming the error code.
661        */
662        ck(DPCT_CHECK_ERROR(dpct::sync_barrier(e1)), "rec");
663        ck(DPCT_CHECK_ERROR(e1->wait_and_throw()), "sync");
664        float ms = 0;
665        ck(DPCT_CHECK_ERROR(
666               ms = (e1->get_profiling_info<
667                         sycl::info::event_profiling::command_end>() -
668                     e0->get_profiling_info<
669                         sycl::info::event_profiling::command_start>()) /
670                    1000000.0f),
671           "elapsed");
672        return 1000.0 * ms / ITERS;
673    }
674    catch (sycl::exception const &exc) {
675      std::cerr << exc.what() << "Exception caught at file:" << __FILE__
676                << ", line:" << __LINE__ << std::endl;
677      std::exit(1);
678    }
679    };
680    auto ab = [&](const char* name, double blobs_per_call, const std::function<void(int)>& call) {
681        double us[2];
682        for (int old = 1; old >= 0; --old) {
683            k::moe_grouped_select_old(old);
684            us[old ? 0 : 1] = time(call);
685        }
686        k::moe_grouped_select_old(-1);
687        const double gb = blobs_per_call * (double) BLOB / 1e3;   // bytes / us = MB/s ... / 1e3 -> GB/s
688        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],
689                    gb / us[0], us[1], gb / us[1], us[0] / us[1]);
690    };
691
692    // per-hit path, decode: 9 hits of 10 (5090-like residency), 5 of 10, and the low-residency 1-3 hits, where the
693    // new kernels' grid (80 gate/up blocks per hit) is below one block per SM - see `STRATA_GROUPED_PAIR_MIN_HITS`
694    for (const int n_hits : {9, 5, 3, 2, 1}) {
695        std::vector<int32_t> slots((size_t) SETS * n_hits), dst(K);
696        for (auto& v : slots) v = (int32_t) (rng() % nb);
697        std::iota(dst.begin(), dst.end(), 0);
698        int32_t* d_slots = dalloc<int32_t>(slots.size());
699        int32_t* d_dst = dalloc<int32_t>(K);
700        up(d_slots, slots);
701        up(d_dst, dst);
702        const Scratch s = make_scratch(n_hits);
703        float* d_out = dalloc<float>((size_t) K * H);
704        const std::string name = "moe_hit_grouped_s2, " + std::to_string(n_hits) + " hits";
705        ab(name.c_str(), n_hits, [&](int set) {
706            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,
707                                  d_out, nullptr, d_xs);
708        });
709    }
710    // grouped path, verify window: T tokens x 10, routed with `share` = the chance an entry reuses an expert already
711    // routed by an earlier token of the window
712    struct Shape { int T; double share; const char* what; };
713    for (const Shape sh : {Shape{4, 0.0, "4 tokens, no sharing"}, Shape{4, 0.3, "4 tokens, 30% shared"},
714                           Shape{8, 0.3, "8 tokens, 30% shared"}, Shape{8, 1.0, "8 tokens, all shared (ne 8)"}}) {
715        const int n = sh.T * K;
716        std::vector<unsigned long long> gptr((size_t) SETS * n);
717        std::vector<int32_t> gstart((size_t) SETS * (n + 1)), ng(SETS), edst((size_t) SETS * n), etok((size_t) SETS * n);
718        double groups = 0;
719        std::uniform_real_distribution<double> u(0, 1);
720        for (int set = 0; set < SETS; ++set) {
721            std::vector<std::vector<int>> g;       // per group: routing indices
722            std::vector<int> gexp;                 // per group: blob
723            for (int t = 0; t < sh.T; ++t) {
724                std::vector<char> used(g.size(), 0);
725                for (int j = 0; j < K; ++j) {
726                    int pick = -1;
727                    if (t > 0 && u(rng) < sh.share)
728                        for (size_t q = 0; q < g.size(); ++q)
729                            if (!used[q] && (int) g[q].size() < 8) { pick = (int) q; break; }
730                    if (pick < 0) {
731                        pick = (int) g.size();
732                        g.emplace_back();
733                        gexp.push_back((int) (rng() % nb));
734                        used.push_back(0);
735                    }
736                    used[(size_t) pick] = 1;
737                    g[(size_t) pick].push_back(t * K + j);
738                }
739            }
740            int at = 0;
741            for (size_t q = 0; q < g.size(); ++q) {
742                gptr[(size_t) set * n + q] = (unsigned long long) (fx.d + (size_t) gexp[q] * BLOB);
743                gstart[(size_t) set * (n + 1) + q] = at;
744                for (int e : g[q]) {
745                    edst[(size_t) set * n + at] = e;
746                    etok[(size_t) set * n + at] = e / K;
747                    ++at;
748                }
749            }
750            for (size_t q = g.size(); q <= (size_t) n; ++q) gstart[(size_t) set * (n + 1) + q] = at;
751            ng[set] = (int32_t) g.size();
752            groups += (double) g.size() / SETS;
753        }
754        unsigned long long* d_gptr = dalloc<unsigned long long>(gptr.size());
755        int32_t* d_gstart = dalloc<int32_t>(gstart.size());
756        int32_t* d_ng = dalloc<int32_t>(SETS);
757        int32_t* d_edst = dalloc<int32_t>(edst.size());
758        int32_t* d_etok = dalloc<int32_t>(etok.size());
759        up(d_gptr, gptr);
760        up(d_gstart, gstart);
761        up(d_ng, ng);
762        up(d_edst, edst);
763        up(d_etok, etok);
764        const Scratch s = make_scratch(n);
765        float* d_out = dalloc<float>((size_t) n * H);
766        char name[96];
767        std::snprintf(name, sizeof name, "moe_grouped_s2, %s (%.0f groups)", sh.what, groups);
768        ab(name, groups, [&](int set) {
769            k::moe_grouped_s2(d_gptr + (size_t) set * n, d_gstart + (size_t) set * (n + 1), d_ng + set,
770                              d_edst + (size_t) set * n, d_etok + (size_t) set * n, n, n, d_x, d_xs, s.p, d_out,
771                              nullptr);
772        });
773    }
774}
775}  // namespace
776
777int main(int argc, char** argv) {
778    bool do_bench = false;
779    for (int i = 1; i < argc; ++i) {
780        if (std::strcmp(argv[i], "--bench") == 0) do_bench = true;
781        else if (std::strcmp(argv[i], "--selftest") != 0) {
782            std::fprintf(stderr, "usage: s2_expert_grouped_parity [--selftest] [--bench]\n");
783            return 2;
784        }
785    }
786    std::printf("s2_expert_grouped_parity: new expert kernels vs the previous ones, bitwise\n");
787    check_all();
788    if (do_bench) bench();
789    std::printf("s2_expert_grouped_parity: %d failures\n%s\n", g_fail, g_fail ? "FAIL" : "PASS");
790    return g_fail ? 1 : 0;
791}