okami.mom/strata

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

Niko1221Merge f-145-havok (#2364 multi-user series, opt-in)df44bcb71

main
31.5 KiB625 linesraw
1// prefill_mmq_tab_test - STRATA_MMQ_DIRECT: the pointer-table MMQ (src/prefill/moe_mmq_tab.cuh, Product::tab) bit for
2// bit against the gathered MMQ the prompt path runs today (experts copied `expert_bytes` apart, a zeroed 4096-byte
3// tail after the last one).
4//
5// Part 1, per product type (IQ3_S gate/up [1280, 2560], IQ4_NL and Q8_0 down [2560, 640], and every other type with a
6// pointer-table instance, at its pack shape): random valid expert matrices at scattered 256-aligned addresses, each
7// followed by a guard filled with an fp16 NaN pattern (0xFF 0x7C); prep_group zeroes the over-read bytes, then the
8// table launch; memcmp of the whole output (pre-filled with a NaN pattern in both runs) against the gathered launch.
9// Sweep: 1..16 experts with mixed row counts {0,1,7,8,9,31,64,100,512,1000}; max_rows from 1 to 1000 so that every
10// tile width J from 8 to 128 is taken (and max_rows above the largest count); few-tile launches (stream-k grid of
11// nsm blocks with the fixup kernel) and many-tile ones (one block per tile).
12// Part 2, negative control: the same table launch with the guards NOT zeroed must give non-finite values in a down
13// product (proves the guard handling is load-bearing; skipped for types that read nothing past a matrix).
14// Part 3, mixed groups as prefill.cpp's walk builds them: native expert blobs (gate|up|down) for IQ3_S + IQ4_NL and
15// IQ3_S + Q8_0, some read in place (direct), the others gathered at compact positions c != q - one at a time
16// (gather_native) or by gather_native_group with a mid-group flush (first > 0) - including groups whose last entry is
17// direct and groups with no gathered entry; both products bitwise equal to all-gathered.
18// Part 4, STRATA_MMQ_GROUP_SORT: a layer's experts in groups of 16 as prefill.cpp runs them (activations quantized
19// in group order through the src map, absolute bounds, max_rows = the group's largest count), once in ID order and
20// once with the full groups in row-count order (mmq_resident_sort_rows, the partial group kept): every token's
21// product row bitwise equal, when mmq::whole_tiles says so for this card (else only reported). Sorting the partial
22// group too (STRATA_MMQ_RESIDENT_SORT_NE) is reported, not required.
23// Exit 77 without a CUDA device of sm_80 or newer or without the pointer-table build.
24#include "strata/prefill/moe_mmq.hpp"
25
26#include "ggml.h"
27
28#include "../../src/prefill/mmq_resident_sort.hpp"
29
30#include <cuda_runtime.h>
31
32#include <algorithm>
33#include <cmath>
34#include <cstdint>
35#include <cstdio>
36#include <cstdlib>
37#include <cstring>
38#include <random>
39#include <stdexcept>
40#include <string>
41#include <vector>
42
43namespace {
44namespace mmq = strata::prefill::mmq;
45
46constexpr int G = mmq::kGatherGroupMax;
47constexpr size_t TAIL = 4096;
48constexpr int64_t kIdsPad = 2048 + 128;   // > the largest max_rows of the sweep plus one tile
49
50void ck(cudaError_t e, const char* what) {
51    if (e != cudaSuccess) throw std::runtime_error(std::string(what) + ": " + cudaGetErrorString(e));
52}
53
54struct Dev {
55    void* p = nullptr;
56    size_t n = 0;
57    explicit Dev(size_t bytes) : n(bytes) { ck(cudaMalloc(&p, bytes), "cudaMalloc"); }
58    ~Dev() { cudaFree(p); }
59    Dev(const Dev&) = delete;
60    Dev& operator=(const Dev&) = delete;
61    uint8_t* b() const { return (uint8_t*) p; }
62};
63
64// random blocks with a sane fp16 scale at each block's start (every format here begins with it)
65void fill_matrix(uint8_t* m, ggml_type t, int64_t rows, int64_t cols, std::mt19937& rng) {
66    const size_t bs = ggml_type_size(t), nb = (size_t) rows * (size_t) (cols / ggml_blck_size(t));
67    std::uniform_int_distribution<int> byte(0, 255);
68    const float lo = t == GGML_TYPE_Q8_0 ? 0.0001f : t == GGML_TYPE_IQ3_S ? 0.0004f : t == GGML_TYPE_IQ4_XS ? 0.00005f
69                   : t == GGML_TYPE_IQ4_NL ? 0.0002f : t == GGML_TYPE_Q2_0 ? 0.004f : 0.0008f;
70    std::uniform_real_distribution<float> sc(lo, 6.0f * lo);
71    for (size_t i = 0; i < nb * bs; ++i) m[i] = (uint8_t) byte(rng);
72    for (size_t b = 0; b < nb; ++b) {
73        const ggml_fp16_t h = ggml_fp32_to_fp16(sc(rng));
74        std::memcpy(m + b * bs, &h, 2);
75    }
76}
77
78// host -> device, finished before any work on the (non-blocking) test stream starts: a pageable cudaMemcpy returns
79// before its DMA lands, and the legacy stream does not order it against a cudaStreamNonBlocking stream
80void upload(void* dst, const void* src, size_t n, const char* what) {
81    ck(cudaMemcpy(dst, src, n, cudaMemcpyHostToDevice), what);
82    ck(cudaDeviceSynchronize(), what);
83}
84
85// the fp16 NaN pattern a guard holds before prep_group (0x7CFF little-endian at every even offset)
86void fill_nan(uint8_t* dev, size_t n) {
87    std::vector<uint8_t> h(n);
88    for (size_t i = 0; i < n; ++i) h[i] = (i & 1) ? 0x7C : 0xFF;
89    upload(dev, h.data(), n, "fill_nan");
90}
91
92struct Shape {
93    ggml_type t;
94    int64_t rows, cols;   // the weight matrix [rows, cols]
95    const char* role;
96};
97
98// activations for `total` rows of `cols`, quantized for type t (q8_1), plus an identity map and the bounds
99struct Acts {
100    Dev x, xq, ids, bounds;
101    int64_t total;
102    Acts(ggml_type t, int64_t cols, const std::vector<int>& cnt, std::mt19937& rng, cudaStream_t s)
103        : x((size_t) std::max<int64_t>(1, sum(cnt)) * cols * 4), xq(mmq::q8_bytes(std::max<int64_t>(1, sum(cnt)), cols)),
104          ids((size_t) (sum(cnt) + kIdsPad) * 4), bounds((cnt.size() + 1) * 4), total(sum(cnt)) {
105        std::vector<float> hx((size_t) std::max<int64_t>(1, total) * cols);
106        std::normal_distribution<float> nd(0.0f, 1.0f);
107        for (auto& v : hx) v = nd(rng);
108        upload(x.p, hx.data(), hx.size() * 4, "x");
109        std::vector<int32_t> hb(cnt.size() + 1, 0);
110        for (size_t i = 0; i < cnt.size(); ++i) hb[i + 1] = hb[i] + cnt[i];
111        upload(bounds.p, hb.data(), hb.size() * 4, "bounds");
112        // MMQ loads a whole tile's J ids from an expert's first row, and its stream-k fixup does so for every column
113        // tile of max_rows, also past the last row (upstream behaviour, harmless values): padded for memcheck
114        mmq::iota((int32_t*) ids.p, total + kIdsPad, s);
115        if (total > 0) mmq::quantize((const float*) x.p, nullptr, xq.p, (int) t, cols, cols, total, s);
116        ck(cudaStreamSynchronize(s), "acts");
117    }
118    static int64_t sum(const std::vector<int>& c) {
119        int64_t n = 0;
120        for (int v : c) n += v;
121        return n;
122    }
123};
124
125mmq::Product product(const Shape& sh, const Acts& a, int n, int64_t max_rows, float* dst) {
126    mmq::Product p;
127    p.type = (int) sh.t; p.w_rows = sh.rows; p.w_cols = sh.cols;
128    p.n = n; p.xq = a.xq.p; p.bounds = (const int32_t*) a.bounds.p; p.ids = (const int32_t*) a.ids.p;
129    p.total_rows = a.total; p.max_rows = max_rows; p.dst = dst; p.ld_dst = sh.rows;
130    return p;
131}
132
133int g_cases = 0, g_fail = 0;
134
135bool same_bits(const Dev& a, const Dev& b, size_t n, const char* what) {
136    std::vector<uint8_t> ha(n), hb(n);
137    ck(cudaMemcpy(ha.data(), a.p, n, cudaMemcpyDeviceToHost), "dtoh a");
138    ck(cudaMemcpy(hb.data(), b.p, n, cudaMemcpyDeviceToHost), "dtoh b");
139    ++g_cases;
140    if (std::memcmp(ha.data(), hb.data(), n) == 0) return true;
141    size_t i = 0;
142    while (i < n && ha[i] == hb[i]) ++i;
143    std::printf("  FAIL %s: first differing byte %zu of %zu\n", what, i, n);
144    if (std::getenv("TAB_TEST_DEBUG")) {
145        const float* fa = (const float*) ha.data();
146        const float* fb = (const float*) hb.data();
147        size_t nd = 0;
148        for (size_t k = 0; k < n / 4; ++k)
149            if (std::memcmp(fa + k, fb + k, 4) != 0) {
150                if (nd < 6) std::printf("    float %zu: %.9g vs %.9g\n", k, fa[k], fb[k]);
151                ++nd;
152            }
153        std::printf("    %zu floats differ\n", nd);
154    }
155    ++g_fail;
156    return false;
157}
158
159bool any_nonfinite(const Dev& d, size_t floats) {
160    std::vector<float> h(floats);
161    ck(cudaMemcpy(h.data(), d.p, floats * 4, cudaMemcpyDeviceToHost), "dtoh");
162    for (float v : h)
163        if (!std::isfinite(v)) return true;
164    return false;
165}
166
167// Part 1 + 2: one product, `cnt` rows per expert
168void product_case(mmq::Context& ctx, const Shape& sh, const std::vector<int>& cnt, int64_t max_rows, std::mt19937& rng,
169                  cudaStream_t s, bool negative, const char* label) {
170    const int n = (int) cnt.size();
171    const size_t eb = mmq::matrix_bytes((int) sh.t, sh.rows, sh.cols);
172    const size_t over = mmq::overread_bytes((int) sh.t, sh.cols);
173    Acts a(sh.t, sh.cols, cnt, rng, s);
174    // the experts' matrices on the host
175    std::vector<std::vector<uint8_t>> w((size_t) n, std::vector<uint8_t>(eb));
176    for (auto& m : w) fill_matrix(m.data(), sh.t, sh.rows, sh.cols, rng);
177    // gathered: back to back, a zeroed tail, the space after it NaN-patterned
178    Dev grp((size_t) n * eb + TAIL + 4096);
179    fill_nan(grp.b(), grp.n);
180    for (int z = 0; z < n; ++z) upload(grp.b() + (size_t) z * eb, w[(size_t) z].data(), eb, "grp");
181    ck(cudaMemset(grp.b() + (size_t) n * eb, 0, TAIL), "tail");
182    ck(cudaDeviceSynchronize(), "tail");
183    // in place: scattered 256-aligned slots in one arena (shuffled order, random gaps), each with a NaN guard
184    const size_t stride = (eb + mmq::kSlotGuard + 255) / 256 * 256;
185    std::vector<size_t> pos((size_t) n);
186    for (int z = 0; z < n; ++z) pos[(size_t) z] = (size_t) z;
187    std::shuffle(pos.begin(), pos.end(), rng);
188    std::uniform_int_distribution<int> gap(0, 8);
189    Dev arena((size_t) n * (stride + 8 * 256) + 4096);
190    fill_nan(arena.b(), arena.n);
191    mmq::WeightTab tab;
192    mmq::GuardTab guards;
193    size_t at = 0;
194    std::vector<size_t> where((size_t) n);
195    for (int k = 0; k < n; ++k) {
196        at += (size_t) gap(rng) * 256;
197        where[pos[(size_t) k]] = at;
198        at += stride;
199    }
200    for (int z = 0; z < n; ++z) {
201        uint8_t* p = arena.b() + where[(size_t) z];
202        upload(p, w[(size_t) z].data(), eb, "arena");
203        tab.p[z] = p;
204        guards.p[guards.n++] = p + eb;
205    }
206    const size_t out = (size_t) std::max<int64_t>(1, a.total) * (size_t) sh.rows * 4;
207    Dev ref(out), got(out);
208    fill_nan(ref.b(), out);
209    fill_nan(got.b(), out);
210    mmq::Product pr = product(sh, a, n, max_rows, (float*) ref.p);
211    pr.w = grp.p; pr.expert_bytes = eb;
212    ctx.run(pr, s);
213    if (!negative) mmq::prep_group(guards, over, nullptr, nullptr, 0, s);
214    mmq::Product pt = product(sh, a, n, max_rows, (float*) got.p);
215    pt.w = nullptr; pt.expert_bytes = 0; pt.tab = &tab;
216    ctx.run(pt, s);
217    ck(cudaStreamSynchronize(s), "run");
218    char what[256];
219    std::snprintf(what, sizeof what, "%s %s n=%d rows=%lld max_rows=%lld (%s)", ggml_type_name(sh.t), sh.role, n,
220                  (long long) a.total, (long long) max_rows, label);
221    if (!negative) {
222        same_bits(ref, got, out, what);
223        return;
224    }
225    ++g_cases;
226    if (!any_nonfinite(got, out / 4)) {
227        std::printf("  FAIL negative control %s: no non-finite value with the guards left as NaN\n", what);
228        ++g_fail;
229    } else if (any_nonfinite(ref, (size_t) a.total * (size_t) sh.rows)) {
230        std::printf("  FAIL negative control %s: the gathered reference is not finite\n", what);
231        ++g_fail;
232    }
233}
234
235std::vector<int> random_counts(int n, std::mt19937& rng) {
236    static const int kRows[] = {0, 1, 7, 8, 9, 31, 64, 100, 512, 1000};
237    std::uniform_int_distribution<int> pick(0, 9);
238    std::vector<int> c((size_t) n);
239    for (auto& v : c) v = kRows[pick(rng)];
240    return c;
241}
242int64_t max_of(const std::vector<int>& c) {
243    int64_t m = 0;
244    for (int v : c) m = std::max<int64_t>(m, v);
245    return m;
246}
247
248void sweep(mmq::Context& ctx, const Shape& sh, bool full, std::mt19937& rng, cudaStream_t s) {
249    const int f0 = g_fail, c0 = g_cases;
250    // 1..16 experts, mixed counts (max_rows = the largest count, as prefill.cpp passes it)
251    for (int n = 1; n <= G; ++n) {
252        if (!full && n != 1 && n != 3 && n != 8 && n != G) continue;
253        for (int rep = 0; rep < (full ? 3 : 1); ++rep) {
254            std::vector<int> c = random_counts(n, rng);
255            if (max_of(c) == 0) c[0] = 1;
256            product_case(ctx, sh, c, max_of(c), rng, s, false, "mixed");
257        }
258    }
259    // every J: one expert with m rows, the others fewer; and max_rows above the largest count
260    static const int kMax[] = {1, 7, 8, 9, 16, 17, 24, 25, 32, 33, 40, 41, 48, 56, 64, 65, 72, 80, 88, 96, 100, 104,
261                               112, 120, 127, 128, 129, 300, 1000};
262    for (int m : kMax) {
263        if (!full && m % 8 != 0 && m != 1 && m != 129) continue;
264        for (int n : {1, 5, 16}) {
265            if (!full && n == 5) continue;
266            std::uniform_int_distribution<int> fewer(0, m);
267            std::vector<int> c((size_t) n);
268            for (auto& v : c) v = fewer(rng);
269            c[(size_t) (rng() % (unsigned) n)] = m;
270            product_case(ctx, sh, c, m, rng, s, false, "J sweep");
271        }
272    }
273    for (int n : {1, 4, 16}) {
274        std::vector<int> c = random_counts(n, rng);
275        if (max_of(c) == 0) c[0] = 9;
276        product_case(ctx, sh, c, max_of(c) + 37, rng, s, false, "max_rows above the largest count");
277    }
278    // experts with 0 rows at the ends and in the middle
279    product_case(ctx, sh, {0, 0, 5, 0, 1000, 0, 0}, 1000, rng, s, false, "empty experts");
280    product_case(ctx, sh, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, 1, rng, s, false, "only the last expert");
281    std::printf("%-8s %-7s %4d cases, %s\n", ggml_type_name(sh.t), sh.role, g_cases - c0,
282                g_fail == f0 ? "all bitwise identical" : "FAILURES");
283    // negative control: a down product that reads past its matrix, guards not zeroed
284    if (mmq::overread_bytes((int) sh.t, sh.cols) > 0) {
285        const int f1 = g_fail;
286        product_case(ctx, sh, {3, 64, 0, 17}, 64, rng, s, true, "negative");
287        product_case(ctx, sh, {200}, 200, rng, s, true, "negative");
288        std::printf("%-8s %-7s negative control (guards not zeroed): %s\n", ggml_type_name(sh.t), sh.role,
289                    g_fail == f1 ? "non-finite output, as required" : "FAILED");
290    }
291}
292
293// Part 3: groups as prefill.cpp's walk builds them, both products
294struct Pair {
295    ggml_type gu, d;
296};
297void group_case(mmq::Context& ctx, const Pair& pr, const std::vector<int>& cnt, const std::vector<char>& direct,
298                bool group_gather, int flush_at, std::mt19937& rng, cudaStream_t s, const char* label) {
299    const int n = (int) cnt.size();
300    const Shape gs{pr.gu, 1280, 2560, "gate/up"}, ds{pr.d, 2560, 640, "down"};
301    const size_t gub = mmq::matrix_bytes((int) pr.gu, 1280, 2560), db = mmq::matrix_bytes((int) pr.d, 2560, 640);
302    const size_t up_off = gub / 2, down_off = gub, bytes = gub + db;
303    const size_t over = mmq::overread_bytes((int) pr.d, 640);
304    // native blobs, each in its own place: direct ones in "cache slots" with a guard, gathered ones elsewhere
305    std::vector<std::vector<uint8_t>> blob((size_t) n, std::vector<uint8_t>(bytes));
306    for (auto& b : blob) {
307        fill_matrix(b.data(), pr.gu, 1280, 2560, rng);
308        fill_matrix(b.data() + down_off, pr.d, 2560, 640, rng);
309    }
310    const size_t stride = (bytes + mmq::kSlotGuard + 255) / 256 * 256;
311    Dev arena((size_t) n * (stride + 4 * 256) + 4096);
312    fill_nan(arena.b(), arena.n);
313    std::vector<uint8_t*> at((size_t) n);
314    size_t o = 0;
315    for (int z = 0; z < n; ++z) {
316        o += (size_t) (rng() % 4) * 256;
317        at[(size_t) z] = arena.b() + o;
318        o += stride;
319        upload(at[(size_t) z], blob[(size_t) z].data(), bytes, "blob");
320    }
321    Acts ag(pr.gu, 2560, cnt, rng, s), ad(pr.d, 640, cnt, rng, s);
322    const int64_t mr = std::max<int64_t>(1, max_of(cnt));
323    const size_t out_g = (size_t) std::max<int64_t>(1, ag.total) * 1280 * 4, out_d = (size_t) std::max<int64_t>(1, ad.total) * 2560 * 4;
324    // reference: today's walk (gather at q, two tail memsets)
325    Dev rgu((size_t) G * gub + TAIL), rd((size_t) G * db + TAIL), ref_g(out_g), ref_d(out_d);
326    fill_nan(rgu.b(), rgu.n);
327    fill_nan(rd.b(), rd.n);
328    fill_nan(ref_g.b(), out_g);
329    fill_nan(ref_d.b(), out_d);
330    for (int q = 0; q < n; ++q) {
331        const uint8_t* b = at[(size_t) q];
332        mmq::gather_native(b, b + up_off, gub / 2, b + down_off, db, rgu.b() + (size_t) q * gub, rd.b() + (size_t) q * db, s);
333    }
334    ck(cudaMemsetAsync(rgu.b() + (size_t) n * gub, 0, TAIL, s), "memset");
335    ck(cudaMemsetAsync(rd.b() + (size_t) n * db, 0, TAIL, s), "memset");
336    mmq::Product p = product(gs, ag, n, mr, (float*) ref_g.p);
337    p.w = rgu.p; p.expert_bytes = gub;
338    ctx.run(p, s);
339    p = product(ds, ad, n, mr, (float*) ref_d.p);
340    p.w = rd.p; p.expert_bytes = db;
341    ctx.run(p, s);
342    // direct: prefill.cpp's compute() in direct mode
343    Dev tgu_buf((size_t) G * gub + TAIL), td_buf((size_t) G * db + TAIL), got_g(out_g), got_d(out_d);
344    fill_nan(tgu_buf.b(), tgu_buf.n);
345    fill_nan(td_buf.b(), td_buf.n);
346    fill_nan(got_g.b(), out_g);
347    fill_nan(got_d.b(), out_d);
348    mmq::WeightTab tgu, td;
349    mmq::GuardTab gd;
350    mmq::GatherGroup gg;
351    int ns = 0;
352    auto flush = [&]() {
353        if (gg.n <= gg.first) return;
354        if (!mmq::gather_native_group(gg, up_off, gub / 2, down_off, db, tgu_buf.p, gub, td_buf.p, db, s))
355            throw std::runtime_error("gather_native_group refused an aligned group");
356        gg.first = gg.n;
357    };
358    for (int q = 0; q < n; ++q) {
359        uint8_t* b = at[(size_t) q];
360        if (direct[(size_t) q]) {
361            tgu.p[q] = b;
362            td.p[q] = b + down_off;
363            gd.p[gd.n++] = b + bytes;
364        } else {
365            const int c = ns++;
366            tgu.p[q] = tgu_buf.b() + (size_t) c * gub;
367            td.p[q] = td_buf.b() + (size_t) c * db;
368            if (group_gather) {
369                gg.blob[c] = b;
370                gg.n = c + 1;
371            } else {
372                mmq::gather_native(b, b + up_off, gub / 2, b + down_off, db, tgu_buf.b() + (size_t) c * gub,
373                                   td_buf.b() + (size_t) c * db, s);
374            }
375        }
376        if (group_gather && q == flush_at) flush();   // release_to's mid-group flush
377    }
378    if (group_gather) flush();
379    mmq::prep_group(gd, over, ns ? tgu_buf.b() + (size_t) ns * gub : nullptr, ns ? td_buf.b() + (size_t) ns * db : nullptr,
380                    TAIL, s);
381    p = product(gs, ag, n, mr, (float*) got_g.p);
382    p.tab = &tgu;
383    ctx.run(p, s);
384    p = product(ds, ad, n, mr, (float*) got_d.p);
385    p.tab = &td;
386    ctx.run(p, s);
387    ck(cudaStreamSynchronize(s), "group");
388    char what[256];
389    std::snprintf(what, sizeof what, "%s+%s group n=%d direct=%d %s (%s)", ggml_type_name(pr.gu), ggml_type_name(pr.d), n,
390                  gd.n, group_gather ? "gather_native_group" : "gather_native", label);
391    std::string w1 = std::string(what) + " gate/up", w2 = std::string(what) + " down";
392    same_bits(ref_g, got_g, out_g, w1.c_str());
393    same_bits(ref_d, got_d, out_d, w2.c_str());
394}
395
396
397// Part 4: one layer's experts in groups of G; `span` as mmq_resident_sort_span gives it (0: ID order)
398struct Layer {
399    std::vector<int32_t> ids, count, off, order, slot, src;
400};
401Layer route(const std::vector<int>& cnt, std::mt19937& rng) {
402    Layer L;
403    for (size_t e = 0; e < cnt.size(); ++e)
404        for (int r = 0; r < cnt[e]; ++r) L.ids.push_back((int32_t) e);
405    std::shuffle(L.ids.begin(), L.ids.end(), rng);   // one route per token (K = 1), experts interleaved
406    L.count.assign(cnt.begin(), cnt.end());
407    L.off.assign(cnt.size() + 1, 0);
408    for (size_t e = 0; e < cnt.size(); ++e) L.off[e + 1] = L.off[e] + cnt[e];
409    for (size_t e = 0; e < cnt.size(); ++e)
410        if (cnt[e] > 0) L.order.push_back((int32_t) e);
411    L.slot.assign(L.ids.size(), 0);
412    L.src.assign(L.ids.size(), 0);
413    std::vector<int32_t> fill(L.off.begin(), L.off.end() - 1);
414    for (size_t i = 0; i < L.ids.size(); ++i) {
415        const int32_t p = fill[(size_t) L.ids[i]]++;
416        L.slot[i] = p;
417        L.src[(size_t) p] = (int32_t) i;
418    }
419    return L;
420}
421
422// the layer's product rows in the layer's row order (row p = token src[p])
423std::vector<float> run_layer(mmq::Context& ctx, const Shape& sh, const Layer& L, const std::vector<std::vector<uint8_t>>& w,
424                             const Dev& x, cudaStream_t s) {
425    const int64_t T = (int64_t) L.ids.size();
426    const size_t eb = mmq::matrix_bytes((int) sh.t, sh.rows, sh.cols), n = L.order.size();
427    Dev src((size_t) T * 4), xq(mmq::q8_bytes(T, sh.cols)), ids((size_t) (T + kIdsPad) * 4), bounds((n + 1) * 4);
428    Dev grp((size_t) G * eb + TAIL), out((size_t) T * sh.rows * 4);
429    upload(src.p, L.src.data(), (size_t) T * 4, "src");
430    std::vector<int32_t> hb(n + 1);
431    for (size_t j = 0; j < n; ++j) hb[j] = L.off[(size_t) L.order[j]];
432    hb[n] = (int32_t) T;
433    upload(bounds.p, hb.data(), hb.size() * 4, "bounds");
434    fill_nan(out.b(), out.n);
435    mmq::iota((int32_t*) ids.p, T + kIdsPad, s);
436    mmq::quantize((const float*) x.p, (const int32_t*) src.p, xq.p, (int) sh.t, sh.cols, sh.cols, T, s);
437    for (size_t j0 = 0; j0 < n; j0 += G) {
438        const int ng = (int) std::min<size_t>(G, n - j0);
439        int64_t maxr = 0;
440        ck(cudaStreamSynchronize(s), "group");   // grp is rewritten below
441        for (int q = 0; q < ng; ++q) {
442            const int32_t e = L.order[j0 + (size_t) q];
443            maxr = std::max<int64_t>(maxr, L.count[(size_t) e]);
444            upload(grp.b() + (size_t) q * eb, w[(size_t) e].data(), eb, "grp");
445        }
446        ck(cudaMemset(grp.b() + (size_t) ng * eb, 0, TAIL), "tail");
447        ck(cudaDeviceSynchronize(), "tail");
448        mmq::Product p;
449        p.w = grp.p; p.type = (int) sh.t; p.w_rows = sh.rows; p.w_cols = sh.cols; p.expert_bytes = eb;
450        p.n = ng; p.xq = xq.p; p.bounds = (const int32_t*) bounds.p + j0; p.ids = (const int32_t*) ids.p;
451        p.total_rows = T; p.max_rows = maxr; p.dst = (float*) out.p; p.ld_dst = sh.rows;
452        ctx.run(p, s);
453    }
454    ck(cudaStreamSynchronize(s), "layer");
455    std::vector<float> h((size_t) T * sh.rows);
456    ck(cudaMemcpy(h.data(), out.p, h.size() * 4, cudaMemcpyDeviceToHost), "dtoh layer");
457    return h;
458}
459
460// tokens whose product row differs between two orders of the same layer
461int64_t rows_differing(const Layer& a, const std::vector<float>& ra, const Layer& b, const std::vector<float>& rb, int64_t cols) {
462    int64_t nd = 0;
463    for (size_t t = 0; t < a.ids.size(); ++t)
464        if (std::memcmp(ra.data() + (size_t) a.slot[t] * cols, rb.data() + (size_t) b.slot[t] * cols, (size_t) cols * 4) != 0) ++nd;
465    return nd;
466}
467
468void order_case(mmq::Context& ctx, const Shape& sh, const std::vector<int>& cnt, bool whole, std::mt19937& rng, cudaStream_t s,
469                const char* label) {
470    const size_t eb = mmq::matrix_bytes((int) sh.t, sh.rows, sh.cols);
471    std::vector<std::vector<uint8_t>> w(cnt.size(), std::vector<uint8_t>(eb));
472    for (auto& m : w) fill_matrix(m.data(), sh.t, sh.rows, sh.cols, rng);
473    Layer id = route(cnt, rng);
474    const int64_t T = (int64_t) id.ids.size();
475    Dev x((size_t) T * sh.cols * 4);
476    {
477        std::vector<float> hx((size_t) T * sh.cols);
478        std::normal_distribution<float> nd(0.0f, 1.0f);
479        for (auto& v : hx) v = nd(rng);
480        upload(x.p, hx.data(), hx.size() * 4, "x");
481    }
482    Layer full = id, all = id;
483    namespace d = strata::prefill::detail;
484    d::mmq_resident_sort_rows(full.ids.data(), T, 1, full.count, full.off, full.order, full.slot.data(), full.src.data(),
485                              d::mmq_resident_sort_span(full.order.size(), G, true));
486    d::mmq_resident_sort_rows(all.ids.data(), T, 1, all.count, all.off, all.order, all.slot.data(), all.src.data(),
487                              d::mmq_resident_sort_span(all.order.size(), G, false));
488    const size_t n = id.order.size(), tail = n % G;
489    // the partial group's entries and row range stay where they were
490    bool kept = std::equal(id.order.end() - (ptrdiff_t) tail, id.order.end(), full.order.end() - (ptrdiff_t) tail);
491    for (size_t j = n - tail; j < n && kept; ++j) kept = full.off[(size_t) full.order[j]] == id.off[(size_t) id.order[j]];
492    const std::vector<float> r_id = run_layer(ctx, sh, id, w, x, s);
493    const std::vector<float> r_full = run_layer(ctx, sh, full, w, x, s);
494    const std::vector<float> r_all = run_layer(ctx, sh, all, w, x, s);
495    const int64_t d_full = rows_differing(id, r_id, full, r_full, sh.rows), d_all = rows_differing(id, r_id, all, r_all, sh.rows);
496    ++g_cases;
497    const bool ok = kept && (!whole || d_full == 0);
498    if (!ok) ++g_fail;
499    std::printf("  %s %-7s %s: %zu experts (%zu in the partial group), %lld rows: full groups sorted %lld rows differ%s, "
500                "all sorted %lld rows differ%s\n", ggml_type_name(sh.t), sh.role, label, n, tail, (long long) T,
501                (long long) d_full, ok ? "" : (kept ? " FAIL" : " FAIL (partial group moved)"), (long long) d_all,
502                whole ? "" : " (whole_tiles false on this card: reported only)");
503}
504
505std::vector<int> skewed_counts(int n, int lo, int hi, std::mt19937& rng) {
506    // prompt-like: most experts few rows, some many (log-uniform)
507    std::uniform_real_distribution<double> u(std::log((double) lo), std::log((double) hi + 1));
508    std::vector<int> c((size_t) n);
509    for (auto& v : c) v = std::max(lo, (int) std::exp(u(rng)));
510    return c;
511}
512
513}  // namespace
514
515int main() {
516    try {
517        int dev = 0;
518        cudaDeviceProp prop{};
519        if (cudaGetDevice(&dev) != cudaSuccess || cudaGetDeviceProperties(&prop, dev) != cudaSuccess || prop.major < 8) {
520            std::printf("needs a CUDA device of sm_80 or newer: skipped\n");
521            return 77;
522        }
523        if (!mmq::built() || !mmq::tab_built()) {
524            std::printf("no pointer-table MMQ in this build: skipped\n");
525            return 77;
526        }
527        std::printf("%s (sm_%d%d, %d SMs)\n", prop.name, prop.major, prop.minor, prop.multiProcessorCount);
528        cudaStream_t s;
529        ck(cudaStreamCreateWithFlags(&s, cudaStreamNonBlocking), "stream");
530        mmq::Context ctx;
531        std::mt19937 rng(20261011);
532        // the pack's three formats, fully; every other type with an instance, a shorter sweep
533        const Shape main_shapes[] = {{GGML_TYPE_IQ3_S, 1280, 2560, "gate/up"},
534                                     {GGML_TYPE_IQ4_NL, 2560, 640, "down"},
535                                     {GGML_TYPE_Q8_0, 2560, 640, "down"}};
536        // the types without a pointer table (the optional Q5_0 / K-quant instances) must keep the gather
537        for (const ggml_type t : {GGML_TYPE_Q5_0, GGML_TYPE_Q4_K, GGML_TYPE_Q5_K, GGML_TYPE_Q5_1, GGML_TYPE_Q6_K}) {
538            if (mmq::tab_fits((int) t, 1280) || mmq::tab_fits((int) t, 2560)) {
539                std::printf("FAIL: %s reports a pointer table (only the nine tested types have one)\n", ggml_type_name(t));
540                return 1;
541            }
542        }
543        // the over-read each guard must cover: within kSlotGuard, and on sm_86 the values the guards were sized for
544        // (256-value K tiles: 640 columns are 20 blocks of 32, so the last tile reads 4 blocks more - 4 x 18 B of
545        // IQ4_NL, 4 x 34 B of Q8_0; 2560 columns end on a tile)
546        const size_t want_over[] = {0, 72, 136};
547        for (size_t i = 0; i < 3; ++i) {
548            const Shape& sh = main_shapes[i];
549            const size_t ov = mmq::overread_bytes((int) sh.t, sh.cols);
550            if (ov > mmq::kSlotGuard || (prop.major == 8 && prop.minor == 6 && ov != want_over[i])) {
551                std::printf("FAIL: %s over-read %zu B (want %zu, at most %zu)\n", ggml_type_name(sh.t), ov, want_over[i],
552                            mmq::kSlotGuard);
553                return 1;
554            }
555        }
556        for (const Shape& sh : main_shapes) {
557            if (!mmq::tab_fits((int) sh.t, sh.rows)) {
558                std::printf("FAIL: no pointer-table MMQ for %s\n", ggml_type_name(sh.t));
559                return 1;
560            }
561            std::printf("%-8s %-7s over-read past the matrix: %zu B\n", ggml_type_name(sh.t), sh.role,
562                        mmq::overread_bytes((int) sh.t, sh.cols));
563            sweep(ctx, sh, true, rng, s);
564        }
565        const Shape other[] = {{GGML_TYPE_IQ2_XXS, 1280, 2560, "gate/up"}, {GGML_TYPE_IQ2_XS, 1280, 2560, "gate/up"},
566                               {GGML_TYPE_IQ2_S, 1280, 2560, "gate/up"},   {GGML_TYPE_IQ3_XXS, 1280, 2560, "gate/up"},
567                               {GGML_TYPE_IQ4_XS, 1280, 2560, "gate/up"},  {GGML_TYPE_Q8_0, 1280, 2560, "gate/up"},
568                               {GGML_TYPE_IQ4_NL, 1280, 2560, "gate/up"},  {GGML_TYPE_Q2_0, 2560, 640, "down"}};
569        for (const Shape& sh : other) {
570            if (!mmq::tab_fits((int) sh.t, sh.rows)) {   // all nine types have an instance (CMake's tab types)
571                std::printf("FAIL: no pointer-table MMQ for %s %s\n", ggml_type_name(sh.t), sh.role);
572                return 1;
573            }
574            sweep(ctx, sh, false, rng, s);
575        }
576        // Part 3
577        const int f0 = g_fail, c0 = g_cases;
578        for (const Pair pr : {Pair{GGML_TYPE_IQ3_S, GGML_TYPE_IQ4_NL}, Pair{GGML_TYPE_IQ3_S, GGML_TYPE_Q8_0}}) {
579            for (int gg = 0; gg < 2; ++gg) {
580                const bool group_gather = gg == 1;
581                // alternating direct / gathered, last entry direct
582                group_case(ctx, pr, {5, 0, 31, 64, 1, 100, 8, 9}, {0, 1, 0, 1, 1, 0, 0, 1}, group_gather, 3, rng, s,
583                           "interleaved, last direct");
584                // a full group, the first entries gathered, then mostly direct; flush after entry 5
585                group_case(ctx, pr, {7, 8, 9, 31, 64, 100, 1, 0, 512, 3, 17, 33, 2, 64, 90, 128},
586                           {0, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 0}, group_gather, 5, rng, s,
587                           "full group, last gathered");
588                // every entry direct (ns == 0: no tails), and every entry gathered
589                group_case(ctx, pr, {12, 40, 0, 7}, {1, 1, 1, 1}, group_gather, -1, rng, s, "all direct");
590                group_case(ctx, pr, {12, 40, 0, 7}, {0, 0, 0, 0}, group_gather, 1, rng, s, "all gathered");
591                // one entry
592                group_case(ctx, pr, {1000}, {1}, group_gather, -1, rng, s, "one direct entry");
593                // random mixes
594                for (int r = 0; r < 4; ++r) {
595                    const int n = 1 + (int) (rng() % G);
596                    std::vector<int> c = random_counts(n, rng);
597                    if (max_of(c) == 0) c[0] = 1;
598                    std::vector<char> d((size_t) n);
599                    for (auto& v : d) v = (char) (rng() & 1);
600                    group_case(ctx, pr, c, d, group_gather, (int) (rng() % (unsigned) n), rng, s, "random mix");
601                }
602            }
603        }
604        std::printf("mixed groups: %d comparisons, %s\n", g_cases - c0, g_fail == f0 ? "all bitwise identical" : "FAILURES");
605        // Part 4
606        const int f4 = g_fail, c4 = g_cases;
607        const Shape order_shapes[] = {{GGML_TYPE_IQ3_S, 1280, 2560, "gate/up"}, {GGML_TYPE_IQ4_XS, 1280, 2560, "gate/up"},
608                                      {GGML_TYPE_IQ4_NL, 2560, 640, "down"},   {GGML_TYPE_Q8_0, 2560, 640, "down"}};
609        for (const Shape& sh : order_shapes) {
610            const bool whole = mmq::whole_tiles((int) sh.t, sh.rows, G);
611            std::printf("%-8s %-7s whole_tiles(%d experts): %s\n", ggml_type_name(sh.t), sh.role, G, whole ? "yes" : "no");
612            order_case(ctx, sh, skewed_counts(147, 1, 40, rng), whole, rng, s, "150-token prompt");
613            order_case(ctx, sh, skewed_counts(219, 1, 160, rng), whole, rng, s, "512-token chunk");
614            order_case(ctx, sh, skewed_counts(48, 1, 300, rng), whole, rng, s, "no partial group");
615            order_case(ctx, sh, skewed_counts(11, 1, 300, rng), whole, rng, s, "partial group only");
616        }
617        std::printf("group order: %d comparisons, %s\n", g_cases - c4, g_fail == f4 ? "all bitwise identical" : "FAILURES");
618        cudaStreamDestroy(s);
619        std::printf("%d comparisons, %d failed\n", g_cases, g_fail);
620        return g_fail == 0 ? 0 : 1;
621    } catch (const std::exception& e) {
622        std::printf("error: %s\n", e.what());
623        return 1;
624    }
625}