okami.mom/strata

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

Niko1221Merge f-i8-share 1ce91c84c into the batch 17 candidate (CPU-share fix: the share keeps the staged fused entry and the int8 kernels for the GPU's own experts in a build without MMQ)88bcc24b9

main
24.9 KiB449 linesraw
1// src/kernels/native_i8_parity.cpp - native_expert_i8 (our own int8 dot-product tile kernels, src/kernels/cuda/i8_expert.cuh) against
2// native_expert_grouped on the same synthetic blobs and the same q8_1 activations.  GPU, no model.
3//
4//     build/native_i8_parity              the checks (a ctest)
5//
6// Both paths compute the same quantized dot (int8 weights x q8_1 activations, the formats' own scales): they differ only where the grouped
7// kernels truncate an integer division inside the dot (IQ2_XS / IQ2_S / IQ2_XXS / IQ3_XXS: `/ 8`, `/ 4`, `/ 2`) and in the order of the float
8// sums, so the two outputs agree to a small relative RMS (checked below 5e-3 per call; the error of either against FP32 is about 1.5e-2,
9// bench: tests/cuda/prefill_expert_paths_bench.cpp).  Per call: every output row of an active entry is finite and written, rows no entry
10// maps to are untouched (the NaN pattern is still there), and three runs of the same call give the same bits (the tile order never changes a sum).
11// Every gate/up format of the kernel with both down formats; groups of 0, 1, 31..33, 47..49, 63..65 and 130 entries (zero-entry groups too),
12// the three tile sizes (STRATA_I8_TM = 2, 3, 4), scattered destinations, random tokens, stale scratch.
13#include "strata/kernels/iq_kernels.hpp"
14
15#include <cuda_runtime.h>
16
17#include <algorithm>
18#include <chrono>
19#include <cmath>
20#include <cstdio>
21#include <cstdlib>
22#include <cstring>
23#include <numeric>
24#include <random>
25#include <vector>
26
27namespace k = strata::kernels;
28
29namespace {
30
31int g_fail = 0, g_run = 0, g_skipped = 0;
32
33void ck(cudaError_t e, const char* what) {
34    if (e != cudaSuccess) {
35        std::fprintf(stderr, "CUDA error in %s: %s\n", what, cudaGetErrorString(e));
36        std::exit(2);
37    }
38}
39
40template <typename T>
41T* dalloc(size_t n) {
42    T* p = nullptr;
43    ck(cudaMalloc(&p, n * sizeof(T) + 256), "malloc");
44    ck(cudaMemset(p, 0, n * sizeof(T) + 256), "memset");
45    ck(cudaDeviceSynchronize(), "memset sync");   // (a legacy-stream memset may still be queued when the first kernel of the non-blocking stream runs: it zeroed the activations)
46    return p;
47}
48
49const char* name_of(int t) {
50    switch (t) {
51        case 16: return "IQ2_XXS";
52        case 17: return "IQ2_XS";
53        case 18: return "IQ3_XXS";
54        case 20: return "IQ4_NL";
55        case 21: return "IQ3_S";
56        case 22: return "IQ2_S";
57        case 42: return "Q2_0";
58        case 23: return "IQ4_XS";
59        case 29: return "IQ1_M";
60        case 6: return "Q5_0";
61        case 8: return "Q8_0";
62        case 12: return "Q4_K";
63        case 13: return "Q5_K";
64        case 14: return "Q6_K";
65        case 7: return "Q5_1";
66        default: return "?";
67    }
68}
69int block_values(int t) { return t == 20 || t == 6 || t == 8 || t == 7 ? 32 : t == 42 ? 64 : 256; }
70
71// `rows` rows of `n` values of format t: random bytes (every code is valid for these formats), then a finite fp16 scale in every block
72std::vector<uint8_t> random_rows(int t, int64_t rows, int64_t n, std::mt19937& rng) {
73    const size_t rb = k::iq_row_bytes(t, n), bs = k::iq_row_bytes(t, block_values(t));
74    std::vector<uint8_t> w((size_t) rows * rb);
75    std::uniform_int_distribution<int> byte(0, 255), ex(2, 8), man(0, 1023), sgn(0, 1);
76    for (auto& b : w) b = (uint8_t) byte(rng);
77    for (size_t o = 0; o < w.size(); o += bs) {   // the fp16 scale starts the block: 2^-13 .. 2^-6
78        const uint16_t h = (uint16_t) ((sgn(rng) ? 0x8000 : 0) | (ex(rng) << 10) | man(rng));
79        if (t == 29) {   // IQ1_M: the fp16 scale is spread over the top nibbles of the block's four 16-bit scale words (bytes 48..55)
80            for (int i = 0; i < 4; ++i) w[o + 48 + 2 * i + 1] = (uint8_t) ((w[o + 48 + 2 * i + 1] & 0x0F) | (((h >> (4 * i)) & 15) << 4));
81            continue;
82        }
83        if (t == 14) {   // Q6_K: d is the block's last two bytes (offset 208); the ql / qh / int8 scale bytes stay random
84            std::memcpy(&w[o + 208], &h, 2);
85            continue;
86        }
87        std::memcpy(&w[o], &h, 2);
88        if (t == 12 || t == 13 || t == 7) {   // Q4_K / Q5_K: dmin, Q5_1: m, the second fp16 of the block, either sign
89            const uint16_t h2 = (uint16_t) ((sgn(rng) ? 0x8000 : 0) | (ex(rng) << 10) | man(rng));
90            std::memcpy(&w[o + 2], &h2, 2);
91        }
92    }
93    return w;
94}
95
96struct Setup {
97    k::NativeExpertLayout L;
98    int T, cap, n_blobs;
99    size_t slot;
100    uint8_t *blobs, *xq, *xq8, *scr;   // xq: the q8_1 image of native_expert_grouped; xq8: native_expert_i8's own image (FP32 scales)
101    size_t scr_bytes, out_floats;
102    float* out;
103    unsigned long long* ptr;
104    int32_t *start, *n, *dst, *tok;
105    int active_lo = 0, active_hi = 0;
106    std::vector<int32_t> dst_h;
107
108    Setup(int gu, int dt, int64_t H, int64_t FF, int tokens, int k_per_token, int blobs_n, std::mt19937& rng, cudaStream_t s) {
109        L = k::native_expert_layout(gu, dt, H, FF);
110        T = tokens;
111        cap = T * k_per_token;
112        n_blobs = blobs_n;
113        slot = (L.bytes + 255) & ~(size_t) 255;
114        blobs = dalloc<uint8_t>(slot * (size_t) n_blobs);
115        for (int b = 0; b < n_blobs; ++b) {
116            auto blob = random_rows(gu, 2 * FF, H, rng);
117            const auto down = random_rows(dt, H, FF, rng);
118            blob.insert(blob.end(), down.begin(), down.end());
119            if (blob.size() != L.bytes) { std::fprintf(stderr, "blob %zu != %zu bytes\n", blob.size(), L.bytes); std::exit(2); }
120            ck(cudaMemcpy(blobs + slot * (size_t) b, blob.data(), blob.size(), cudaMemcpyHostToDevice), "blob");
121        }
122        std::normal_distribution<float> nd(0.f, 1.f);
123        std::vector<float> x((size_t) T * H);
124        for (auto& v : x) v = nd(rng);
125        float* dx = dalloc<float>(x.size());
126        ck(cudaMemcpy(dx, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "x");
127        xq = dalloc<uint8_t>((size_t) T * (H / 32) * 36);
128        k::quantize_q8_1_rows(dx, T, H, xq, s);
129        xq8 = dalloc<uint8_t>((size_t) T * (H / 32) * 36);
130        k::native_expert_i8_quantize(dx, T, H, xq8, s);
131        ck(cudaStreamSynchronize(s), "quantize");
132        cudaFree(dx);
133        scr_bytes = k::native_expert_scratch_bytes(cap, FF);
134        scr = dalloc<uint8_t>(scr_bytes);
135        out_floats = (size_t) cap * H;
136        out = dalloc<float>(out_floats);
137        ptr = dalloc<unsigned long long>(cap);
138        start = dalloc<int32_t>(cap + 1);
139        n = dalloc<int32_t>(1);
140        dst = dalloc<int32_t>(cap);
141        tok = dalloc<int32_t>(cap);
142    }
143    ~Setup() {
144        cudaFree(blobs); cudaFree(xq); cudaFree(xq8); cudaFree(scr); cudaFree(out);
145        cudaFree(ptr); cudaFree(start); cudaFree(n); cudaFree(dst); cudaFree(tok);
146    }
147    // groups of these sizes from entry `base` on, each its own blob; every other entry row of `out` is a destination nobody uses
148    int plan_sizes(const std::vector<int>& sizes, int base, std::mt19937& rng) {
149        std::uniform_int_distribution<int> tk(0, T - 1);
150        std::vector<unsigned long long> p;
151        std::vector<int32_t> st(1, base), tk_v, ds(cap);
152        for (const int m : sizes) {
153            p.push_back((unsigned long long) (blobs + slot * (size_t) (p.size() % (size_t) n_blobs)));
154            st.push_back(st.back() + m);
155        }
156        if (st.back() > cap) { std::fprintf(stderr, "plan: %d entries > cap %d\n", st.back(), cap); std::exit(2); }
157        const int ng = (int) p.size();
158        active_lo = base;
159        active_hi = st.back();
160        std::iota(ds.begin(), ds.end(), 0);
161        std::shuffle(ds.begin(), ds.end(), rng);   // scattered rows of `out`
162        dst_h = ds;
163        for (int e = 0; e < cap; ++e) tk_v.push_back(tk(rng));
164        if (ng) ck(cudaMemcpy(ptr, p.data(), p.size() * 8, cudaMemcpyHostToDevice), "ptr");
165        ck(cudaMemcpy(start, st.data(), st.size() * 4, cudaMemcpyHostToDevice), "start");
166        ck(cudaMemcpy(n, &ng, 4, cudaMemcpyHostToDevice), "n");
167        ck(cudaMemcpy(dst, ds.data(), ds.size() * 4, cudaMemcpyHostToDevice), "dst");
168        ck(cudaMemcpy(tok, tk_v.data(), tk_v.size() * 4, cudaMemcpyHostToDevice), "tok");
169        return ng;
170    }
171    std::vector<float> result(bool i8, int junk, cudaStream_t s) {
172        ck(cudaMemsetAsync(out, 0xFF, out_floats * 4, s), "memset");   // (on the same stream: a legacy-stream cudaMemset is not ordered against a non-blocking stream)
173        ck(cudaMemsetAsync(scr, junk, scr_bytes, s), "memset");
174        if (i8) k::native_expert_i8(L, ptr, start, n, dst, tok, cap, cap, xq8, scr, out, s);
175        else k::native_expert_grouped(L, ptr, start, n, dst, tok, cap, cap, xq, scr, out, s, 0);
176        ck(cudaStreamSynchronize(s), "sync");
177        std::vector<float> o(out_floats);
178        ck(cudaMemcpy(o.data(), out, o.size() * 4, cudaMemcpyDeviceToHost), "out");
179        return o;
180    }
181};
182
183void set_env(const char* name, const char* value) {
184#ifdef _WIN32
185    _putenv_s(name, value);
186#else
187    setenv(name, value, 1);
188#endif
189}
190
191uint64_t hash_bits(const std::vector<float>& v) {
192    uint64_t h = 1469598103934665603ull;
193    for (float f : v) {
194        uint32_t u;
195        std::memcpy(&u, &f, 4);
196        h = (h ^ u) * 1099511628211ull;
197    }
198    return h;
199}
200
201// The prompt path's call for a layer the CPU share took experts of (include/strata/prefill/share_own_rule.hpp): the GPU's experts sit in the first `rows_local` rows of the layer's
202// rows in groups of 16, the CPU's experts' rows are the LAST block [rows_local, cap) of the layer's output and nobody on the GPU writes them.  Each group is one launch exactly as
203// i8grp::run makes it: bounds relative to the group's first row r0, the entry-to-place table the identity from there, the rows' tokens src + r0, the scratch at r0 * (2 * FF) floats,
204// the output at out + r0 * H.  Checked against native_expert_grouped on the same layout: the GPU rows are finite and agree (relative RMS under 5e-3), the CPU block is untouched
205// (the 0xFF pattern) in both, and a second run gives the same bits.
206void check_carved(const Setup& S, int64_t H, int64_t FF, cudaStream_t s, std::mt19937& rng, int tm, int& bad, double& worst, int& calls) {
207    const int E = 20;   // experts of the GPU's part (some with no rows)
208    std::uniform_int_distribution<int> cnt_d(0, 14), tk(0, S.T - 1);
209    std::vector<int> order, cnt(E), off(E);
210    int rows_local = 0;
211    for (int e = 0; e < E; ++e) {
212        cnt[(size_t) e] = cnt_d(rng);
213        off[(size_t) e] = rows_local;
214        rows_local += cnt[(size_t) e];
215        if (cnt[(size_t) e] > 0) order.push_back(e);
216    }
217    const int rows_cpu = std::min(S.cap - rows_local, 57);   // the CPU's block after them
218    if (rows_cpu <= 0 || order.empty()) return;
219    const size_t gu_row = (size_t) 2 * FF;
220    uint8_t* scr_i8 = dalloc<uint8_t>((size_t) S.cap * gu_row * 4);
221    uint8_t* scr_ref = dalloc<uint8_t>(k::native_expert_scratch_bytes(S.cap, FF));
222    float* out_i8 = dalloc<float>((size_t) S.cap * (size_t) H);
223    float* out_ref = dalloc<float>((size_t) S.cap * (size_t) H);
224    std::vector<int32_t> ident((size_t) S.cap), tok_h((size_t) S.cap);
225    std::iota(ident.begin(), ident.end(), 0);
226    for (auto& t : tok_h) t = tk(rng);
227    int32_t* d_ident = dalloc<int32_t>((size_t) S.cap);
228    int32_t* d_tok = dalloc<int32_t>((size_t) S.cap);
229    ck(cudaMemcpy(d_ident, ident.data(), ident.size() * 4, cudaMemcpyHostToDevice), "ident");
230    ck(cudaMemcpy(d_tok, tok_h.data(), tok_h.size() * 4, cudaMemcpyHostToDevice), "tok");
231    std::vector<std::vector<float>> got(2);   // two runs of the i8 side
232    std::vector<float> ref_h;
233    for (int pass = 0; pass < 3; ++pass) {   // 0, 1: the int8 kernel (twice), 2: the grouped reference
234        const bool i8 = pass < 2;
235        float* out = i8 ? out_i8 : out_ref;
236        ck(cudaMemsetAsync(out, 0xFF, (size_t) S.cap * (size_t) H * 4, s), "memset out");
237        ck(cudaMemsetAsync(i8 ? scr_i8 : scr_ref, pass == 1 ? 0x7F : 0, i8 ? (size_t) S.cap * gu_row * 4 : k::native_expert_scratch_bytes(S.cap, FF), s), "memset scr");
238        ck(cudaStreamSynchronize(s), "memset sync");
239        for (size_t a = 0; a < order.size(); a += 16) {
240            const size_t b = std::min(order.size(), a + 16);
241            const int ne = (int) (b - a);
242            const int r0 = off[(size_t) order[a]];
243            const int nr = off[(size_t) order[b - 1]] + cnt[(size_t) order[b - 1]] - r0;
244            std::vector<unsigned long long> p((size_t) ne);
245            std::vector<int32_t> st((size_t) ne + 1);
246            for (int i = 0; i < ne; ++i) {
247                p[(size_t) i] = (unsigned long long) (S.blobs + S.slot * (size_t) (order[a + (size_t) i] % S.n_blobs));
248                st[(size_t) i] = off[(size_t) order[a + (size_t) i]] - r0;
249            }
250            st[(size_t) ne] = nr;
251            ck(cudaMemcpy(S.ptr, p.data(), p.size() * 8, cudaMemcpyHostToDevice), "ptr");
252            ck(cudaMemcpy(S.start, st.data(), st.size() * 4, cudaMemcpyHostToDevice), "start");
253            ck(cudaMemcpy(S.n, &ne, 4, cudaMemcpyHostToDevice), "n");
254            if (i8) k::native_expert_i8(S.L, S.ptr, S.start, S.n, d_ident, d_tok + r0, ne, nr, S.xq8, scr_i8 + (size_t) r0 * gu_row * 4, out + (size_t) r0 * (size_t) H, s);
255            else k::native_expert_grouped(S.L, S.ptr, S.start, S.n, d_ident, d_tok + r0, ne, nr, S.xq, scr_ref, out + (size_t) r0 * (size_t) H, s, 0);
256            ck(cudaStreamSynchronize(s), "carved sync");
257        }
258        std::vector<float> o((size_t) S.cap * (size_t) H);
259        ck(cudaMemcpy(o.data(), out, o.size() * 4, cudaMemcpyDeviceToHost), "carved out");
260        if (i8) got[(size_t) pass] = std::move(o); else ref_h = std::move(o);
261    }
262    ++calls;
263    bool fail = false;
264    if (hash_bits(got[0]) != hash_bits(got[1])) { std::printf("  carved tm %d: the bits changed between runs  FAIL\n", tm); fail = true; }
265    double e2 = 0, r2 = 0;
266    for (int r = 0; r < S.cap && !fail; ++r)
267        for (int64_t col = 0; col < H; ++col) {
268            const size_t i = (size_t) r * (size_t) H + (size_t) col;
269            uint32_t ua, ur;
270            std::memcpy(&ua, &got[0][i], 4);
271            std::memcpy(&ur, &ref_h[i], 4);
272            if (r >= rows_local) {   // the CPU's block: nobody wrote it
273                if (ua != 0xFFFFFFFFu || ur != 0xFFFFFFFFu) { std::printf("  carved tm %d: row %d of the CPU's block was written  FAIL\n", tm, r); fail = true; break; }
274                continue;
275            }
276            if (!std::isfinite(got[0][i])) { std::printf("  carved tm %d: row %d col %lld is not finite  FAIL\n", tm, r, (long long) col); fail = true; break; }
277            const double d = (double) got[0][i] - (double) ref_h[i];
278            e2 += d * d;
279            r2 += (double) ref_h[i] * (double) ref_h[i];
280        }
281    const double rel = r2 > 0 ? std::sqrt(e2 / r2) : 0;
282    worst = std::max(worst, rel);
283    if (!fail && r2 == 0) { std::printf("  carved tm %d: nothing was written  FAIL\n", tm); fail = true; }
284    if (!fail && rel > 5e-3) { std::printf("  carved tm %d: relative RMS against grouped %.3e > 5e-3  FAIL\n", tm, rel); fail = true; }
285    bad += fail;
286    cudaFree(scr_i8); cudaFree(scr_ref); cudaFree(out_i8); cudaFree(out_ref); cudaFree(d_ident); cudaFree(d_tok);
287}
288
289void check(int gu, int dt, int64_t H, int64_t FF, cudaStream_t s, std::mt19937& rng) {
290    const int tokens = 40, kpt = 8;   // cap 320 entries
291    // A pair the device does not cover (its smallest tile does not fit the shared memory per block, or the layout is out of range) is skipped, not an error;
292    // the earlier pass of another pair may have left a pretended limit in the environment, so ask with the device's own.
293#ifdef _WIN32
294    _putenv_s("STRATA_I8_SMEM_LIMIT", "0");
295#else
296    setenv("STRATA_I8_SMEM_LIMIT", "0", 1);
297#endif
298    if (!k::native_expert_i8_supported(k::native_expert_layout(gu, dt, H, FF))) {
299        std::printf("%-8s/%-7s %5lld x %4lld  skipped: not covered on this device\n", name_of(gu), name_of(dt), (long long) H, (long long) FF);
300        ++g_skipped;
301        return;
302    }
303    ++g_run;
304    Setup S(gu, dt, H, FF, tokens, kpt, 12, rng, s);
305    const std::vector<std::vector<int>> plans = {
306        {},                                                // no groups at all
307        {1, 0, 31, 32, 33},                                // zero-entry group in the middle
308        {47, 48, 49, 0, 63, 64, 65},
309        {130, 5},
310        {64, 64, 64, 64, 64},
311        {200, 5, 63, 0, 33},                               // a group of two 128-entry tiles (the second one partly empty)
312        {128, 129, 17},
313    };
314    int calls = 0, bad = 0;
315    double worst = 0;
316    // (tile code, shared-memory limit to pretend: 0 = the device's own).  Tile code 8 is variant B (128 entries); with a 48 KB limit (a Pascal card) the
317    // call must fall to a tile that fits, or the format is unsupported there (then the pass is skipped).
318    for (const auto& tl : std::vector<std::pair<int, int>>{{2, 0}, {3, 0}, {4, 0}, {8, 0}, {8, 49152}, {4, 49152}}) {
319        const int tm = tl.first;
320#ifdef _WIN32
321        _putenv_s("STRATA_I8_TM", std::to_string(tm).c_str());
322        _putenv_s("STRATA_I8_SMEM_LIMIT", std::to_string(tl.second).c_str());
323#else
324        setenv("STRATA_I8_TM", std::to_string(tm).c_str(), 1);
325        setenv("STRATA_I8_SMEM_LIMIT", std::to_string(tl.second).c_str(), 1);
326#endif
327        if (tl.second && !k::native_expert_i8_supported(S.L)) continue;
328        for (const int base : {0, 9}) {
329            for (const auto& sizes : plans) {
330                int total = 0;
331                for (int m : sizes) total += m;
332                if (base + total > S.cap) continue;
333                S.plan_sizes(sizes, base, rng);
334                set_env("STRATA_I8_N8", "0");   // the 16-entry slices: the reference of the bit check below, whatever the class default is
335                const auto ref = S.result(false, 0x00, s);
336                const auto a = S.result(true, 0x00, s);
337                const auto b = S.result(true, 0x7F, s);
338                const auto c = S.result(true, 0x00, s);
339                ++calls;
340                bool fail = false;
341                if (hash_bits(a) != hash_bits(b) || hash_bits(a) != hash_bits(c)) { std::printf("  tm %d base %d: the bits changed between runs  FAIL\n", tm, base); fail = true; }
342                if (tm <= 4) {   // tile codes 2-4 also run as 8-entry slices (STRATA_I8_N8=1): the same terms in the same order, so the same bits
343                    set_env("STRATA_I8_N8", "1");
344                    const auto d8 = S.result(true, 0x7F, s);
345                    set_env("STRATA_I8_N8", "0");
346                    if (hash_bits(a) != hash_bits(d8)) { std::printf("  tm %d base %d: 8-entry slices (N8) changed the bits  FAIL\n", tm, base); fail = true; }
347                }
348                std::vector<char> active((size_t) S.cap, 0);
349                for (int e = S.active_lo; e < S.active_hi; ++e) active[(size_t) S.dst_h[(size_t) e]] = 1;
350                double e2 = 0, r2 = 0;
351                for (int r = 0; r < S.cap && !fail; ++r) {
352                    for (int64_t col = 0; col < H; ++col) {
353                        const size_t i = (size_t) r * (size_t) H + (size_t) col;
354                        uint32_t ua;
355                        std::memcpy(&ua, &a[i], 4);
356                        if (!active[(size_t) r]) {
357                            if (ua != 0xFFFFFFFFu) { std::printf("  tm %d: row %d (no entry) was written  FAIL\n", tm, r); fail = true; break; }
358                            continue;
359                        }
360                        if (!std::isfinite(a[i])) { std::printf("  tm %d: row %d col %lld is not finite  FAIL\n", tm, r, (long long) col); fail = true; break; }
361                        const double d = (double) a[i] - (double) ref[i];
362                        e2 += d * d;
363                        r2 += (double) ref[i] * (double) ref[i];
364                    }
365                }
366                const double rel = r2 > 0 ? std::sqrt(e2 / r2) : 0;
367                worst = std::max(worst, rel);
368                if (!fail && (r2 == 0 && total > 0)) {
369                    double mr = 0, ma = 0;
370                    size_t nzr = 0;
371                    for (size_t i = 0; i < ref.size(); ++i) {
372                        if (std::isfinite(ref[i])) mr = std::max(mr, (double) std::fabs(ref[i]));
373                        if (std::isfinite(a[i])) ma = std::max(ma, (double) std::fabs(a[i]));
374                        nzr += ref[i] != 0.0f && std::isfinite(ref[i]);
375                    }
376                    std::printf("  tm %d base %d: nothing was written  FAIL (entries %d, active rows %d; max |grouped| %.3e, max |i8| %.3e, non-zero finite grouped %zu)\n", tm, base,
377                                total, (int) std::count(active.begin(), active.end(), (char) 1), mr, ma, nzr);
378                    fail = true;
379                }
380                if (!fail && rel > 5e-3) { std::printf("  tm %d base %d: relative RMS against grouped %.3e > 5e-3  FAIL\n", tm, base, rel); fail = true; }
381                bad += fail;
382            }
383        }
384    }
385    set_env("STRATA_I8_SMEM_LIMIT", "0");
386    for (const int tm : {2, 3, 4, 8}) {   // the carved layer of a CPU share (check_carved), the device's own limit
387        set_env("STRATA_I8_TM", std::to_string(tm).c_str());
388        check_carved(S, H, FF, s, rng, tm, bad, worst, calls);
389    }
390    std::printf("%-8s/%-7s %5lld x %4lld  %d calls: %s (worst relative RMS against grouped %.3e)\n", name_of(gu), name_of(dt), (long long) H,
391                (long long) FF, calls, bad ? "FAIL" : "ok", worst);
392    g_fail += bad;
393}
394
395}  // namespace
396
397int main() {
398    int n = 0;
399    if (cudaGetDeviceCount(&n) != cudaSuccess || n == 0) { std::printf("no GPU device: skipped\n"); return 77; }
400    {   // for the log: what the device reports (the call's own limit is one of its own to find: i8_smem_limit)
401        int dev = 0, a = 0, b = 0, mj = 0, mn = 0;
402        cudaGetDevice(&dev);
403#if defined(__HIPCC__) || defined(__HIP_PLATFORM_AMD__)
404        cudaDeviceGetAttribute(&a, hipDeviceAttributeMaxSharedMemoryPerBlock, dev);
405#else
406        cudaDeviceGetAttribute(&a, cudaDevAttrMaxSharedMemoryPerBlock, dev);
407#endif
408        cudaDeviceGetAttribute(&b, cudaDevAttrMaxSharedMemoryPerBlockOptin, dev);
409        cudaDeviceGetAttribute(&mj, cudaDevAttrComputeCapabilityMajor, dev);
410        cudaDeviceGetAttribute(&mn, cudaDevAttrComputeCapabilityMinor, dev);
411        cudaFree(nullptr);
412        std::printf("device: sm_%d%d, shared memory per block %d bytes, opt-in %d bytes\n", mj, mn, a, b);
413        // to stderr (the result lines on stdout stay the same on every card): the limit the call uses, and which sizes an empty kernel really launches with (1 yes, 0 refused,
414        // -1 not available): 49152 = 48 KB, then the sizes the iteration-3 and later tiles of IQ2_S ask for (TM 2 / 3 / 4: 41,088 / 46,272 / 51,456 bytes; later sources 51,328 / 56,512 / 61,696)
415        std::fprintf(stderr, "i8 shared-memory limit used by the call: %zu bytes\n", k::native_expert_i8_smem_limit());
416        std::fprintf(stderr, "empty-kernel launch with dynamic shared memory:");
417        for (const size_t sz : {(size_t) 41088, (size_t) 46272, (size_t) 49152, (size_t) 49408, (size_t) 51328, (size_t) 51456, (size_t) 56512, (size_t) 61696, (size_t) 65536})
418            std::fprintf(stderr, " %zu %s", sz, k::native_expert_i8_probe_launch(sz) == 1 ? "ok" : k::native_expert_i8_probe_launch(sz) == 0 ? "REFUSED" : "n/a");
419        std::fprintf(stderr, "\n");
420    }
421    cudaStream_t s;
422    ck(cudaStreamCreateWithFlags(&s, cudaStreamNonBlocking), "stream");
423    std::mt19937 rng(20261112);
424    for (const int gu : {16, 17, 18, 21, 22})
425        for (const int dt : {20, 42}) {
426            check(gu, dt, 512, 256, s, rng);
427            if (gu == 22 || dt == 42 || gu == 18) check(gu, dt, 2560, 640, s, rng);
428        }
429    // second wave: gate/up IQ4_XS, IQ1_M and Q2_0, down Q5_0 and Q8_0 (after the first-wave rows, so those lines keep their place)
430    for (const auto& pr : std::vector<std::pair<int, int>>{{23, 20}, {23, 42}, {23, 6}, {29, 20}, {29, 42}, {29, 8}, {16, 6}, {21, 8}, {22, 6}, {22, 8}, {42, 42}, {42, 20}, {42, 6}}) {
431        check(pr.first, pr.second, 512, 256, s, rng);
432        check(pr.first, pr.second, 2560, 640, s, rng);
433    }
434    // third wave: the K-quants Q4_K, Q5_K, Q6_K as gate/up and Q5_1 as down (the UD-Q4_K_XL / Q6_K_XL pairs and mixes of them with the earlier formats)
435    for (const auto& pr : std::vector<std::pair<int, int>>{{12, 7}, {12, 8}, {13, 7}, {13, 8}, {14, 8}, {14, 7}, {12, 20}, {12, 42}, {13, 20}, {14, 20}, {14, 42}, {16, 7}, {23, 7}, {42, 7}}) {
436        check(pr.first, pr.second, 512, 256, s, rng);
437        check(pr.first, pr.second, 2560, 640, s, rng);
438    }
439    // fourth wave: the Qwen3.6 sets (n_embd 2048, n_ff 512): UD-Q4_K_XL's Q4_K / Q5_K, Q4_K / Q6_K, Q5_K / Q6_K (Q5_K and Q6_K as down), UD-Q6_K_XL's Q6_K / Q8_0 and its one
440    // Q8_0 / Q8_0 layer, and the smaller shapes of the same pairs
441    for (const auto& pr : std::vector<std::pair<int, int>>{{12, 13}, {12, 14}, {13, 14}, {14, 13}, {14, 14}, {8, 8}, {8, 13}, {16, 13}, {23, 14}, {14, 8}}) {
442        check(pr.first, pr.second, 512, 256, s, rng);
443        check(pr.first, pr.second, 2048, 512, s, rng);
444    }
445    if (g_run == 0) { std::printf("native_i8_parity: nothing ran (%d skipped: not covered on this device)\n", g_skipped); return 77; }
446    if (g_skipped) std::printf("native_i8_parity: %d format rows skipped: not covered on this device\n", g_skipped);
447    std::printf("native_i8_parity: %s\n", g_fail ? "FAILED" : "all ok");
448    return g_fail ? 1 : 0;
449}