okami.mom/strata

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

Niko1221Merge f-0214-int 437668151 (round 0214: the new Unsloth Qwen quants, the Q5_0 dot fix, the Mac app branch) into f-0211-rc3e0210663

main
20.2 KiB419 linesraw
1// src/kernels/native_grouped_parity.cpp - native_expert_grouped's group stride (grid_groups) and its fused SwiGLU +
2// q8_1 pass, against the launches before them (native_grouped_set_v1: a block row per possible group, SwiGLU and the
3// q8_1 quantization as two kernels over all cap_entries).  Synthetic blobs, no model.
4//
5//     build/native_grouped_parity           the checks (a ctest; needs the GPU)
6//     build/native_grouped_parity --bench   the checks, then v1/new timings of 48 calls in a graph (a window's layers)
7//
8// Every gate/up format with every down format; calls of 0..cap groups of 1..T entries each (an empty call is what the
9// verify window's PCIe call usually is), entries from 0 and from past 0 (the PCIe call's follow the VRAM call's),
10// scattered destinations, stale scratch, grid_groups 0 (= cap), 1, 2, 3, 4 and above cap: the output must be BITWISE
11// equal to v1's, the rows the call must not write included (both start from the same NaN pattern).
12//
13// Random bytes are valid codes for every format here (every grid index is in range); only the fp16 block scales are
14// set, small enough that the SwiGLU outputs keep a finite fp16 q8_1 scale.
15#include "strata/kernels/iq_kernels.hpp"
16
17#include <cuda_runtime.h>
18
19#include <algorithm>
20#include <cmath>
21#include <cstdio>
22#include <cstdlib>
23#include <cstring>
24#include <numeric>
25#include <random>
26#include <string>
27#include <vector>
28
29namespace k = strata::kernels;
30
31namespace {
32
33int g_fail = 0;
34
35void ck(cudaError_t e, const char* what) {
36    if (e != cudaSuccess) {
37        std::fprintf(stderr, "CUDA error in %s: %s\n", what, cudaGetErrorString(e));
38        std::exit(2);
39    }
40}
41
42template<typename T>
43T* dalloc(size_t n) {
44    T* p = nullptr;
45    ck(cudaMalloc(&p, n * sizeof(T) + 256), "malloc");
46    ck(cudaMemset(p, 0, n * sizeof(T) + 256), "memset");
47    return p;
48}
49
50const char* name_of(int t) {
51    switch (t) {
52        case 16: return "IQ2_XXS";
53        case 17: return "IQ2_XS";
54        case 18: return "IQ3_XXS";
55        case 20: return "IQ4_NL";
56        case 21: return "IQ3_S";
57        case 22: return "IQ2_S";
58        case 23: return "IQ4_XS";
59        case 29: return "IQ1_M";
60        case 42: return "Q2_0";
61        case 12: return "Q4_K";
62        case 13: return "Q5_K";
63        case 14: return "Q6_K";
64        case 7: return "Q5_1";
65        case 8: return "Q8_0";
66        case 6: return "Q5_0";
67        default: return "?";
68    }
69}
70int block_values(int t) { return t == 20 || t == 7 || t == 8 || t == 6 || t == 2 || t == 3 ? 32 : t == 42 ? 64 : 256; }   // (6 = Q5_0: 32-value blocks, each needs its own finite scale)
71
72// `rows` rows of `n` values of format t: random bytes, then a finite fp16 scale in every block
73std::vector<uint8_t> random_rows(int t, int64_t rows, int64_t n, std::mt19937& rng) {
74    const size_t rb = k::iq_row_bytes(t, n), bs = k::iq_row_bytes(t, block_values(t));
75    std::vector<uint8_t> w((size_t) rows * rb);
76    std::uniform_int_distribution<int> byte(0, 255), ex(2, 8), man(0, 1023), sgn(0, 1);
77    for (auto& b : w) b = (uint8_t) byte(rng);
78    for (size_t o = 0; o < w.size(); o += bs) {
79        if (t == 29) {
80            // IQ1_M: the fp16 scale is the top nibbles of its four scale words (bytes 48..55), the sign and the
81            // exponent's top bits in the last: 0x1 / 0x2 there (0x9 / 0xA negative) keeps it in 2^-11 .. 2^-3
82            const uint8_t nib = (uint8_t) ((sgn(rng) ? 0x8 : 0x0) | (1 + (byte(rng) & 1)));
83            w[o + 55] = (uint8_t) ((w[o + 55] & 0x0F) | (nib << 4));
84        } else {   // the other formats start their block with the fp16 scale: 2^-13 .. 2^-6
85            // (Q4_K / Q5_K: 2^-14 .. 2^-11, their 6-bit sub-scales multiply it by up to 63)
86            const int e = (t == 12 || t == 13) ? 1 + ex(rng) % 4 : ex(rng);
87            const uint16_t h = (uint16_t) ((sgn(rng) ? 0x8000 : 0) | (e << 10) | man(rng));
88            std::memcpy(&w[o], &h, 2);
89            if (t == 12 || t == 13 || t == 7) {   // Q4_K / Q5_K: dmin, Q5_1: m - the second fp16, as small
90                const int em = (t == 7) ? ex(rng) : 1 + ex(rng) % 4;
91                const uint16_t m = (uint16_t) ((sgn(rng) ? 0x8000 : 0) | (em << 10) | man(rng));
92                std::memcpy(&w[o + 2], &m, 2);
93            }
94        }
95    }
96    return w;
97}
98
99// one window's worth of expert calls on one format pair: blobs, T tokens' q8_1 activations, cap = T * K entries
100struct Setup {
101    k::NativeExpertLayout L;
102    int T = 0, K = 0, cap = 0, n_blobs = 0;
103    int active_lo = 0, active_hi = 0;
104    size_t slot = 0;
105    uint8_t* blobs = nullptr;
106    uint8_t* xq = nullptr;
107    uint8_t* scr = nullptr;
108    size_t scr_bytes = 0;
109    float* out = nullptr;
110    size_t out_floats = 0;
111    unsigned long long* ptr = nullptr;
112    int32_t *start = nullptr, *n = nullptr, *dst = nullptr, *tok = nullptr;
113
114    Setup(int gu, int dt, int64_t H, int64_t FF, int tokens, int k_per_token, int blobs_n, std::mt19937& rng,
115          cudaStream_t s) {
116        L = k::native_expert_layout(gu, dt, H, FF);
117        T = tokens; K = k_per_token; cap = T * K; n_blobs = blobs_n;
118        slot = (L.bytes + 255) & ~(size_t) 255;
119        blobs = dalloc<uint8_t>(slot * (size_t) n_blobs);
120        for (int b = 0; b < n_blobs; ++b) {
121            // gate rows | up rows (format gu, H values each) | down rows (format dt, FF values each)
122            auto blob = random_rows(gu, 2 * FF, H, rng);
123            const auto down = random_rows(dt, H, FF, rng);
124            blob.insert(blob.end(), down.begin(), down.end());
125            if (blob.size() != L.bytes) { std::fprintf(stderr, "blob %zu != %zu bytes\n", blob.size(), L.bytes); std::exit(2); }
126            ck(cudaMemcpy(blobs + slot * (size_t) b, blob.data(), blob.size(), cudaMemcpyHostToDevice), "blob");
127        }
128        std::normal_distribution<float> nd(0.f, 1.f);
129        std::vector<float> x((size_t) T * H);
130        for (auto& v : x) v = nd(rng);
131        float* dx = dalloc<float>(x.size());
132        ck(cudaMemcpy(dx, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "x");
133        xq = dalloc<uint8_t>((size_t) T * (H / 32) * 36);
134        k::quantize_q8_1_rows(dx, T, H, xq, s);
135        ck(cudaStreamSynchronize(s), "quantize");
136        cudaFree(dx);
137        scr_bytes = k::native_expert_scratch_bytes(cap, FF);
138        scr = dalloc<uint8_t>(scr_bytes);
139        out_floats = (size_t) cap * H;
140        out = dalloc<float>(out_floats);
141        ptr = dalloc<unsigned long long>(cap);
142        start = dalloc<int32_t>(cap + 1);
143        n = dalloc<int32_t>(1);
144        dst = dalloc<int32_t>(cap);
145        tok = dalloc<int32_t>(cap);
146    }
147    ~Setup() {
148        cudaFree(blobs); cudaFree(xq); cudaFree(scr); cudaFree(out);
149        cudaFree(ptr); cudaFree(start); cudaFree(n); cudaFree(dst); cudaFree(tok);
150    }
151    // a plan: `groups` groups of 1..T entries from entry `base` on (as many as fit in cap)
152    int plan(int groups, int base, std::mt19937& rng) {
153        std::uniform_int_distribution<int> size(1, T);
154        std::vector<int> sizes;
155        int used = base;
156        for (int g = 0; g < groups; ++g) {
157            const int m = std::min(size(rng), cap - used);
158            if (m <= 0) break;
159            sizes.push_back(m);
160            used += m;
161        }
162        return plan_sizes(sizes, base, rng);
163    }
164    // groups of these sizes from entry `base` on, each its own blob (as long as there are enough: a window's groups
165    // are different experts); scattered destinations, random tokens
166    int plan_sizes(const std::vector<int>& sizes, int base, std::mt19937& rng) {
167        std::uniform_int_distribution<int> tk(0, T - 1);
168        std::vector<int> order(n_blobs);
169        std::iota(order.begin(), order.end(), 0);
170        std::shuffle(order.begin(), order.end(), rng);
171        std::vector<unsigned long long> p;
172        std::vector<int32_t> st(1, base), tk_v, ds(cap);
173        for (const int m : sizes) {
174            p.push_back((unsigned long long) (blobs + slot * (size_t) order[p.size() % order.size()]));
175            st.push_back(st.back() + m);
176        }
177        if (st.back() > cap) { std::fprintf(stderr, "plan: %d entries > cap %d\n", st.back(), cap); std::exit(2); }
178        const int ng = (int) p.size();
179        active_lo = base;
180        active_hi = st.back();
181        std::iota(ds.begin(), ds.end(), 0);
182        std::shuffle(ds.begin(), ds.end(), rng);                  // scattered rows of `out`
183        for (int e = 0; e < cap; ++e) tk_v.push_back(tk(rng));
184        if (ng) ck(cudaMemcpy(ptr, p.data(), p.size() * 8, cudaMemcpyHostToDevice), "ptr");
185        ck(cudaMemcpy(start, st.data(), st.size() * 4, cudaMemcpyHostToDevice), "start");
186        ck(cudaMemcpy(n, &ng, 4, cudaMemcpyHostToDevice), "n");
187        ck(cudaMemcpy(dst, ds.data(), ds.size() * 4, cudaMemcpyHostToDevice), "dst");
188        ck(cudaMemcpy(tok, tk_v.data(), tk_v.size() * 4, cudaMemcpyHostToDevice), "tok");
189        return ng;
190    }
191    void call(int64_t grid_groups, cudaStream_t s) {
192        k::native_expert_grouped(L, ptr, start, n, dst, tok, cap, cap, xq, scr, out, s, grid_groups);
193    }
194    // `out` after one call from the NaN pattern, the scratch holding `junk` (what earlier calls left there)
195    std::vector<uint32_t> result(bool v1, int64_t grid_groups, int junk, cudaStream_t s) {
196        ck(cudaMemset(out, 0xFF, out_floats * 4), "memset");
197        ck(cudaMemset(scr, junk, scr_bytes), "memset");
198        k::native_grouped_set_v1(v1);
199        call(grid_groups, s);
200        k::native_grouped_set_v1(false);
201        ck(cudaStreamSynchronize(s), "sync");
202        std::vector<uint32_t> o(out_floats);
203        ck(cudaMemcpy(o.data(), out, o.size() * 4, cudaMemcpyDeviceToHost), "out");
204        // Fused SwiGLU does not write h or inactive Q8 rows. Compare only the
205        // active Q8_1 bytes, appended after the full output (including padding).
206        const size_t fa = ((size_t) cap * L.n_ff * sizeof(float) + 255) & ~(size_t) 255;
207        const size_t qrow = (size_t) (L.n_ff / 32) * 36;
208        const size_t qb = (size_t) (active_hi - active_lo) * qrow;
209        const size_t old = o.size();
210        o.resize(old + qb / sizeof(uint32_t));
211        if (qb)
212            ck(cudaMemcpy(o.data() + old, scr + 3 * fa + active_lo * qrow, qb, cudaMemcpyDeviceToHost), "active hq");
213        return o;
214    }
215};
216
217// The words that differ between v1 and the new launches: where, their values, and whether it is a NaN / Inf pair or a finite difference.
218void diff_list(const std::vector<uint32_t>& v1, const std::vector<uint32_t>& nw, int64_t H, size_t out_floats, const char* what) {
219    size_t shown = 0, total = 0, nan_pairs = 0, fin = 0;
220    double maxrel = 0;
221    for (size_t i = 0; i < v1.size(); ++i) {
222        if (v1[i] == nw[i]) continue;
223        ++total;
224        float a, b;
225        std::memcpy(&a, &v1[i], 4);
226        std::memcpy(&b, &nw[i], 4);
227        const bool fa = std::isfinite(a), fb = std::isfinite(b);
228        if (!fa && !fb) ++nan_pairs;
229        if (fa && fb && i < out_floats) { ++fin; maxrel = std::max(maxrel, (double) std::fabs(a - b) / (std::fabs(a) + 1e-30)); }
230        if (shown++ < 6) {
231            if (i < out_floats)
232                std::printf("      %s word %zu (row %zu col %lld): v1 %.9g (0x%08x)  new %.9g (0x%08x)\n", what, i, i / (size_t) H,
233                            (long long) (i % (size_t) H), a, v1[i], b, nw[i]);
234            else
235                std::printf("      %s q8 word %zu (past the output): v1 0x%08x  new 0x%08x\n", what, i - out_floats, v1[i], nw[i]);
236        }
237    }
238    std::printf("      %s: %zu words differ: %zu both non-finite, %zu finite output floats (max relative difference %.3e)\n", what, total,
239                nan_pairs, fin, maxrel);
240}
241
242void check(int gu, int dt, int64_t H, int64_t FF, cudaStream_t s, std::mt19937& rng) {
243    Setup S(gu, dt, H, FF, 6, 4, 9, rng, s);   // 6 tokens x 4 experts: cap 24 entries
244    int calls = 0, bad = 0;
245    size_t written = 0;
246    for (const int base : {0, 7}) {
247        for (const int groups : {0, 1, 2, 3, 5, 8, 24}) {
248            const int ng = S.plan(groups, base, rng);
249            const auto ref = S.result(true, 0, 0x00, s);
250            size_t w = 0;
251            for (size_t i = 0; i < S.out_floats; ++i) w += ref[i] != 0xFFFFFFFFu;
252            written += w;
253            for (const int64_t gy : {(int64_t) 0, (int64_t) 1, (int64_t) 2, (int64_t) 3, (int64_t) 4, (int64_t) S.cap + 3}) {
254                const auto got = S.result(false, gy, (calls & 1) ? 0x7F : 0x00, s);
255                ++calls;
256                size_t diff = 0;
257                for (size_t i = 0; i < ref.size(); ++i) diff += ref[i] != got[i];
258                if (diff) {
259                    std::printf("  %-8s/%-7s base %d, %d groups, grid_groups %lld: %zu of %zu output/Q8 words differ  FAIL\n",
260                                name_of(gu), name_of(dt), base, ng, (long long) gy, diff, ref.size());
261                    if (!bad) {
262                        diff_list(ref, got, H, S.out_floats, "first failure");
263                    }
264                    ++bad;
265                }
266            }
267        }
268    }
269    std::printf("%-8s/%-7s %5lld x %4lld  %d calls: %s (%zu output floats written in all)\n", name_of(gu), name_of(dt),
270                (long long) H, (long long) FF, calls, bad ? "FAIL" : "bitwise equal to v1", written);
271    if (written == 0) { std::printf("  nothing was written: the check checked nothing  FAIL\n"); ++bad; }
272    g_fail += bad;
273}
274
275// ------------------------------------------------------------------------------------------------ --bench
276// A window's 48 calls, one per layer, each with ITS OWN experts as the layers have: copies of the Setup's blobs in one
277// arena, so the weights stream from DRAM as in the engine.  (48 calls re-reading the same 28 experts - 73 MB, about an
278// Ada L2 - would read part of them from L2; the engine's layers share none.)
279struct Layers {
280    uint8_t* arena = nullptr;
281    std::vector<unsigned long long*> ptr;           // per layer: its groups' blobs (device)
282    Layers(Setup& S, int ng) {
283        const int per = std::max(ng, 1);
284        arena = dalloc<uint8_t>(S.slot * (size_t) (48 * per));
285        for (int l = 0; l < 48; ++l) {
286            std::vector<unsigned long long> p;
287            for (int j = 0; j < per; ++j) {
288                uint8_t* d = arena + S.slot * (size_t) (l * per + j);
289                ck(cudaMemcpy(d, S.blobs + S.slot * (size_t) ((l * per + j) % S.n_blobs), S.L.bytes,
290                              cudaMemcpyDeviceToDevice), "blob copy");
291                p.push_back((unsigned long long) d);
292            }
293            unsigned long long* dp = dalloc<unsigned long long>(p.size());
294            ck(cudaMemcpy(dp, p.data(), p.size() * 8, cudaMemcpyHostToDevice), "ptr");
295            ptr.push_back(dp);
296        }
297    }
298    Layers(const Layers&) = delete;
299    Layers& operator=(const Layers&) = delete;
300    ~Layers() {
301        for (auto* p : ptr) cudaFree(p);
302        cudaFree(arena);
303    }
304};
305
306// the 48 calls of one variant captured in one graph
307cudaGraphExec_t make_graph(cudaStream_t s, Setup& S, const Layers& Ls, bool v1, int64_t gy) {
308    k::native_grouped_set_v1(v1);
309    cudaGraph_t g;
310    cudaGraphExec_t ge;
311    ck(cudaStreamBeginCapture(s, cudaStreamCaptureModeThreadLocal), "capture");
312    for (int l = 0; l < 48; ++l)
313        k::native_expert_grouped(S.L, Ls.ptr[l], S.start, S.n, S.dst, S.tok, S.cap, S.cap, S.xq, S.scr, S.out, s, gy);
314    ck(cudaStreamEndCapture(s, &g), "capture");
315    ck(cudaGraphInstantiate(&ge, g, 0), "instantiate");
316    ck(cudaGraphDestroy(g), "graph");
317    k::native_grouped_set_v1(false);
318    return ge;
319}
320
321// one launch of the graph: microseconds per call
322float launch_us(cudaStream_t s, cudaGraphExec_t ge, cudaEvent_t e0, cudaEvent_t e1) {
323    ck(cudaEventRecord(e0, s), "record");
324    ck(cudaGraphLaunch(ge, s), "launch");
325    ck(cudaEventRecord(e1, s), "record");
326    ck(cudaEventSynchronize(e1), "bench");
327    float ms = 0;
328    ck(cudaEventElapsedTime(&ms, e0, e1), "elapsed");
329    return 1e3f * ms / 48.0f;
330}
331
332float median(std::vector<float> v) {
333    std::sort(v.begin(), v.end());
334    return v[v.size() / 2];
335}
336
337// The two variants' launches ALTERNATE (v1-new, new-v1, ...) after a warm-up, and each reports its median: a card
338// under sustained load steps its clock down after a fraction of a second (an RTX 4080 SUPER went from 80 to 89 us
339// per gate/up call within one run), and whichever variant ran before the step would look faster.
340constexpr int kWarmPairs = 20, kPairs = 40;
341
342void bench(cudaStream_t s, std::mt19937& rng) {
343    std::printf("\n--bench: microseconds per call, a window's 48 calls in a graph, each layer with its own experts (the\n"
344                "weights stream from DRAM as in the engine); v1 / new (grid_groups): medians of %d launches each,\n"
345                "alternating, after %d warm-up pairs - idle GPU assumed\n", kPairs, kWarmPairs);
346    // a verify window's shape: 4 tokens x 10 experts, 2560 x 768 IQ3_S / IQ4_XS experts
347    Setup S(21, 23, 2560, 768, 4, 10, 32, rng, s);
348    std::vector<int> vram(16, 1);
349    vram.insert(vram.end(), 12, 2);                                   // 28 groups, 40 entries
350    const struct { const char* what; std::vector<int> sizes; int64_t gy; } rows[] = {
351        {"no group (the PCIe call at pcie_frac 0)", {}, 4},
352        {"1 group of 2 entries (a PCIe call)", {2}, 4},
353        {"28 groups, 40 entries (a VRAM call)", vram, 0},
354    };
355    cudaEvent_t e0, e1;
356    ck(cudaEventCreate(&e0), "event");
357    ck(cudaEventCreate(&e1), "event");
358    for (const auto& r : rows) {
359        const int ng = S.plan_sizes(r.sizes, 0, rng);
360        const Layers Ls(S, ng);                                       // 48 x 28 experts: 3.7 GB for the VRAM call
361        cudaGraphExec_t ga = make_graph(s, S, Ls, true, 0), gb = make_graph(s, S, Ls, false, r.gy);
362        std::vector<float> ta, tb;
363        for (int i = 0; i < kWarmPairs + kPairs; ++i) {
364            const bool a_first = i % 2 == 0;
365            const float x = launch_us(s, a_first ? ga : gb, e0, e1), y = launch_us(s, a_first ? gb : ga, e0, e1);
366            if (i < kWarmPairs) continue;
367            ta.push_back(a_first ? x : y);
368            tb.push_back(a_first ? y : x);
369        }
370        ck(cudaGraphExecDestroy(ga), "graph");
371        ck(cudaGraphExecDestroy(gb), "graph");
372        std::printf("  %-42s %8.2f / %8.2f us (grid_groups %lld)\n", r.what, median(ta), median(tb), (long long) r.gy);
373    }
374    cudaEventDestroy(e0);
375    cudaEventDestroy(e1);
376}
377
378}  // namespace
379
380int main(int argc, char** argv) {
381    setvbuf(stdout, nullptr, _IONBF, 0);   // keep the trail on a crash
382#if defined(__HIP_PLATFORM_AMD__)
383    {   // gfx1151 defaults to expert mode 8 (the fused gate/up + SwiGLU + q8_1 LDS kernel) for an unstrided call and to the CUDA layout
384        // for a strided one; the two sum in a different order, so "bitwise equal to v1" does not hold between them there (summation
385        // order only: round 0214 diagnosis, RESULTS-ENGAMD.md).  Pin the CUDA layout for both runs unless the caller chose a mode.
386        cudaDeviceProp prop;
387        if (std::getenv("STRATA_EXP_MODE") == nullptr && cudaGetDeviceProperties(&prop, 0) == cudaSuccess &&
388            std::strstr(prop.gcnArchName, "gfx1151") != nullptr) {
389#ifdef _WIN32
390            _putenv_s("STRATA_EXP_MODE", "0");
391#else
392            setenv("STRATA_EXP_MODE", "0", 1);
393#endif
394            std::printf("gfx1151: STRATA_EXP_MODE=0 pinned for both runs (mode 8 and the CUDA layout differ in summation order)\n");
395        }
396    }
397#endif
398    const bool do_bench = argc > 1 && std::string(argv[1]) == "--bench";
399    cudaStream_t s;
400    ck(cudaStreamCreate(&s), "stream");
401    std::mt19937 rng(316);
402    for (int gu : {16, 17, 18, 21, 22, 23, 29, 42, 12, 13,
403#ifdef STRATA_Q6K_EXPERTS
404                   14,
405#endif
406                   8})        // STRATA_GU_FMTS
407        for (int dt : {20, 23, 42, 7, 8, 6}) check(gu, dt, 512, 256, s, rng);   // STRATA_D_FMTS (6 = Q5_0: UD-IQ4_XS / Q3_K_XL); IQ4_XS: n_ff % 256
408    check(42, 42, 2560, 640, s, rng);
409    check(21, 20, 2560, 640, s, rng);                                   // a model's shapes
410    // round 0214: every expert type pair of the new Unsloth Qwen3.8-Flash-Next sets at the model's 2560 x 640
411    // (IQ1_M/IQ2_XXS/IQ2_XS/IQ2_S/Q2_0/IQ3_XXS/IQ4_XS gate/up; Q2_0/IQ4_NL/Q5_0/Q8_0 down; IQ4_XS is 256-wide so n_ff 640 needs a 32-block down)
412    for (int gu : {29, 16, 17, 22, 42, 18, 23})
413        for (int dt : {42, 20, 6, 8}) check(gu, dt, 2560, 640, s, rng);
414    check(21, 23, 2560, 768, s, rng);
415    if (do_bench) bench(s, rng);
416    std::printf("native_grouped_parity: %d failures\n", g_fail);
417    cudaStreamDestroy(s);
418    return g_fail ? 1 : 0;
419}