okami.mom/strata

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

Niko1221Int3 merge f-0291-bw-draft (75d742778): DFlash2 drafter levers (bit-exact), Q4_0 pack pathdc96ad703

main
28.8 KiB527 linesraw
1// src/kernels/mmvq_il_parity.cpp - native_mmvq_il (2-4 columns from the interleaved q8_1 copy, fork F4) against
2// native_mmvq's multi-column kernels, bitwise, for every rows-a-warp choice; --bench times both per call.
3//
4//     build/mmvq_il_parity [--bench [--emit-table] [--hot] [--gap MB] [--persist] [--ab] [--pf a,b,..] [--rounds N]]
5//
6// --pf a,b,..: the P1 / P2 kernel variants (native_mmvq_il_pf: 0 = today's kernel, 6 hoisted group loads, 3 + P2's exact
7// integer forms, 4 = 3 at 5 blocks a SM, 2 / 5 = 3 / 4 with a ring) are each bit-checked against native_mmvq, and with
8// --bench timed interleaved per (case, T, rows): N rounds
9// (default 5) of 100 calls each, variant after variant, the median of the rounds printed per variant (PFBENCH lines; the
10// table cells take the first listed variant).  Without --pf every call takes STRATA_MMVQ_IL_PF (unset: today's kernel).
11//
12// --hot times one copy of the weights (they sit in L2 after the first call: the ceiling of an L2
13// prefetch); --gap MB reads MB megabytes of OTHER weights (native_mmvq over other copies) before every timed call, as
14// the window's GEMVs do between a prefetch and its consumer (a memset gap was tried first: its write-backs drain
15// during the timed call and make every arm slower than cold); --persist puts the timed weights in a persisting L2
16// set-aside (cudaLimitPersistingL2CacheSize + an access-policy window on the stream) so the gap's reads stream past
17// them.  --ab runs the arms cold / hot / hot+gap / hot+gap+persist / cold per case in ONE process (the clocks ramp
18// over the first ~100 ms of a run, so arms in separate runs are not comparable).  MMVQ_IL_TMIN / MMVQ_IL_TMAX bound T.
19//
20// --emit-table (with --bench) prints the rows-a-warp table this card measured, in the source form of kIlRows in
21// native_mmvq.cu: per cell the rows count (1/2/4) that takes at least 3% off native_mmvq's time, else 0.
22//
23// The same Q8_1 bytes feed both paths (quantize_q8_1_rows, then native_q8_1_interleave). Weights are random bytes with
24// the block scales rewritten as normal fp16 values, so every output is finite (a NaN would compare equal whatever
25// produced it). The bench cycles through enough copies of the weights to miss the L2 cache, as a layer's call does.
26#include "strata/kernels/iq_kernels.hpp"
27#include "strata/core/defaults_026.hpp"
28#include "strata/core/sm120_series.hpp"
29#include "strata/kernels/native_mmvq.hpp"
30
31#include <cuda_runtime.h>
32
33#include <algorithm>
34#include <array>
35#include <cmath>
36#include <cstdint>
37#include <cstdio>
38#include <cstdlib>
39#include <cstring>
40#include <random>
41#include <string>
42#include <vector>
43
44namespace {
45using namespace strata::kernels;
46
47struct Cell { int type, T, n_out, pf; double ref; double il[5]; };   // pf: the variant the il[] times ran (-1: the environment's)
48std::vector<Cell> g_cells;
49bool g_hot = false, g_persist = false, g_ab = false;
50std::vector<int> g_pf;   // --pf: the variants to check and time; empty: the environment's
51int g_rounds = 5;
52std::size_t g_gap_bytes = 0;
53std::size_t g_gap_now = 0;   // the gap in force for the current arm (--ab) or g_gap_bytes
54// time `reps` calls of `fn` on `s`; with --gap each call is preceded by `gap` (other weights' reads) and timed on its own
55template <class F, class G>
56double time_us(F fn, int reps, cudaStream_t s, G gap) {
57    cudaEvent_t e0, e1;
58    (void) cudaEventCreate(&e0);
59    (void) cudaEventCreate(&e1);
60    float total = 0;
61    for (int rep = 0; rep < 2; ++rep) {   // rep 0 warms, rep 1 times
62        total = 0;
63        if (g_gap_now == 0) {
64            (void) cudaEventRecord(e0, s);
65            for (int i = 0; i < reps; ++i) fn(i);
66            (void) cudaEventRecord(e1, s);
67            (void) cudaEventSynchronize(e1);
68            (void) cudaEventElapsedTime(&total, e0, e1);
69        } else {
70            for (int i = 0; i < reps; ++i) {
71                gap();
72                (void) cudaEventRecord(e0, s);
73                fn(i);
74                (void) cudaEventRecord(e1, s);
75                (void) cudaEventSynchronize(e1);
76                float ms = 0;
77                (void) cudaEventElapsedTime(&ms, e0, e1);
78                total += ms;
79            }
80        }
81    }
82    (void) cudaEventDestroy(e0);
83    (void) cudaEventDestroy(e1);
84    return 1000.0 * total / reps;
85}
86// --persist: the matrix `w` (wbytes) persisting in L2 for every kernel on `s`; off: the window cleared
87void persist_window(cudaStream_t s, void* w, std::size_t wbytes, bool on) {
88#if !defined(STRATA_HIP_GFX906)
89    cudaStreamAttrValue v{};
90    v.accessPolicyWindow.base_ptr = on ? w : nullptr;
91    v.accessPolicyWindow.num_bytes = on ? wbytes : 0;
92    v.accessPolicyWindow.hitRatio = 1.0f;
93    v.accessPolicyWindow.hitProp = cudaAccessPropertyPersisting;
94    v.accessPolicyWindow.missProp = cudaAccessPropertyStreaming;
95    if (cudaStreamSetAttribute(s, cudaStreamAttributeAccessPolicyWindow, &v) != cudaSuccess) {
96        std::printf("--persist: the access policy window was refused: %s\n", cudaGetErrorString(cudaGetLastError()));
97    }
98#else
99    (void) s; (void) w; (void) wbytes;   // (no L2 access policy window in the gfx906 compat layer)
100    std::printf("--persist: not available in this build (%s)\n", on ? "on" : "off");
101#endif
102}
103struct Case {
104    const char* name;
105    int type, n_in, n_out, block_elems, block_bytes, scale_at[2];
106};
107// the engine's dense shapes: qkv 10240 / gate 6144 / out 2560 (GDN), q 12288 / k,v 512 / o 2560 (QSA), the head
108const Case CASES[] = {
109    {"IQ4_XS 2560x10240", 23, 2560, 10240, 256, 136, {0, -1}},
110    {"IQ4_XS 2560x6144", 23, 2560, 6144, 256, 136, {0, -1}},
111    {"IQ4_XS 6144x2560", 23, 6144, 2560, 256, 136, {0, -1}},
112    {"IQ4_XS 2560x512", 23, 2560, 512, 256, 136, {0, -1}},
113    {"Q4_K 2560x10240", 12, 2560, 10240, 256, 144, {0, 2}},
114    {"Q4_K 6144x2560", 12, 6144, 2560, 256, 144, {0, 2}},
115    {"Q4_K odd rows 2560x2051", 12, 2560, 2051, 256, 144, {0, 2}},
116    {"Q5_K 2560x12288", 13, 2560, 12288, 256, 176, {0, 2}},
117    {"Q5_K 2560x6144", 13, 2560, 6144, 256, 176, {0, 2}},
118    {"Q5_K 6144x2560", 13, 6144, 2560, 256, 176, {0, 2}},
119    {"Q5_K head 2560x248320", 13, 2560, 248320, 256, 176, {0, 2}},
120    {"Q5_K draft head 2560x106299", 13, 2560, 106299, 256, 176, {0, 2}},
121    {"Q6_K 2560x12288", 14, 2560, 12288, 256, 210, {208, -1}},
122    {"Q6_K 2560x10240", 14, 2560, 10240, 256, 210, {208, -1}},
123    {"Q6_K 6144x2560", 14, 6144, 2560, 256, 210, {208, -1}},
124    {"Q6_K odd rows 2560x2051", 14, 2560, 2051, 256, 210, {208, -1}},
125    {"Q6_K 2560x512", 14, 2560, 512, 256, 210, {208, -1}},
126    {"IQ4_XS 2560x12288", 23, 2560, 12288, 256, 136, {0, -1}},
127    {"IQ4_XS 2560x640", 23, 2560, 640, 256, 136, {0, -1}},
128    {"Q4_K 2560x6144", 12, 2560, 6144, 256, 144, {0, 2}},
129    {"Q4_K 2560x640", 12, 2560, 640, 256, 144, {0, 2}},
130    {"Q4_K 2560x512", 12, 2560, 512, 256, 144, {0, 2}},
131    {"Q5_K 2560x10240", 13, 2560, 10240, 256, 176, {0, 2}},
132    {"Q5_K 2560x640", 13, 2560, 640, 256, 176, {0, 2}},
133    {"Q5_K 2560x512", 13, 2560, 512, 256, 176, {0, 2}},
134    {"Q6_K 2560x6144", 14, 2560, 6144, 256, 210, {208, -1}},
135    {"Q6_K 2560x640", 14, 2560, 640, 256, 210, {208, -1}},
136    {"Q3_K 2560x10240", 11, 2560, 10240, 256, 110, {108, -1}},
137    {"Q3_K 2560x12288", 11, 2560, 12288, 256, 110, {108, -1}},
138    {"Q3_K 2560x6144", 11, 2560, 6144, 256, 110, {108, -1}},
139    {"Q3_K 6144x2560", 11, 6144, 2560, 256, 110, {108, -1}},
140    {"Q3_K 2560x640", 11, 2560, 640, 256, 110, {108, -1}},
141    {"Q3_K 2560x512", 11, 2560, 512, 256, 110, {108, -1}},
142    {"Q3_K 2560x2051 odd", 11, 2560, 2051, 256, 110, {108, -1}},
143};
144
145uint16_t sane_half(std::mt19937& rng) {
146    const uint32_t r = rng();
147    return (uint16_t) (((r >> 31) << 15) | ((5u + (r >> 10) % 5u) << 10) | (r & 0x3ffu));
148}
149bool ck(cudaError_t e, const char* what) {
150    if (e == cudaSuccess) return true;
151    std::printf("CUDA: %s: %s\n", what, cudaGetErrorString(e));
152    return false;
153}
154
155int run_case(const Case& c, bool bench, cudaStream_t s) {
156    if (std::strstr(c.name, "odd") != nullptr) bench = false;   // parity-only shape: not a timing cell of the table
157    if (c.type == 13 && c.n_out > 100000 && !bench) { /* the head: parity too, just big */ }
158    const std::size_t wbytes = native_mmvq_weight_bytes(c.type, c.n_in, c.n_out);
159    std::mt19937 rng(77u + (unsigned) c.type * 31u + (unsigned) c.n_out);
160    std::vector<uint8_t> w(wbytes);
161    for (auto& b : w) b = (uint8_t) (rng() & 0xff);
162    const std::size_t n_blocks = (std::size_t) c.n_out * (std::size_t) (c.n_in / c.block_elems);
163    if (n_blocks * (std::size_t) c.block_bytes != wbytes) {
164        std::printf("%s: weight bytes mismatch\n", c.name);
165        return 1;
166    }
167    for (std::size_t k = 0; k < n_blocks; ++k)
168        for (int at : c.scale_at)
169            if (at >= 0) {
170                const uint16_t h = sane_half(rng);
171                std::memcpy(&w[k * (std::size_t) c.block_bytes + (std::size_t) at], &h, 2);
172            }
173    // --hot: one copy (timed hot); with --gap, 1 + the copies the gap reads (dw[1..]) - the timed call always reads dw[0]
174    const int gap_copies = g_gap_bytes > 0 ? (int) std::min<std::size_t>(23, (g_gap_bytes + wbytes - 1) / wbytes) : 0;
175    const int copies = bench && (!g_hot || g_ab) ? (int) std::max<std::size_t>(1, std::min<std::size_t>(24, (192u << 20) / wbytes)) : 1 + gap_copies;
176    std::vector<void*> dw(copies, nullptr);
177    for (int i = 0; i < copies; ++i) {
178        if (!ck(cudaMalloc(&dw[i], wbytes), "malloc w") || !ck(cudaMemcpy(dw[i], w.data(), wbytes, cudaMemcpyHostToDevice), "copy w"))
179            return 1;
180    }
181    int bad = 0;
182    if (bench && g_persist && !g_ab) persist_window(s, dw[0], wbytes, true);
183    g_gap_now = g_gap_bytes;
184    const int t_max = std::getenv("MMVQ_IL_TMAX") ? std::atoi(std::getenv("MMVQ_IL_TMAX")) : 8;   // 147-verify: 5-8 columns
185    const int t_min = std::getenv("MMVQ_IL_TMIN") ? std::atoi(std::getenv("MMVQ_IL_TMIN")) : 1;
186    for (int T = t_min; T <= t_max; ++T) {
187        std::vector<float> x((std::size_t) T * c.n_in);
188        std::normal_distribution<float> nd(0.f, 1.f);
189        for (auto& v : x) v = nd(rng);
190        float* dx = nullptr;
191        void *xq = nullptr, *xil = nullptr;
192        float *yref = nullptr, *yil = nullptr;
193        const std::size_t ybytes = (std::size_t) T * c.n_out * 4;
194        if (!ck(cudaMalloc(&dx, x.size() * 4), "malloc x") ||
195            !ck(cudaMalloc(&xq, native_q8_1_bytes(c.n_in, T)), "malloc xq") ||
196            !ck(cudaMalloc(&xil, native_q8_1_il_bytes(c.n_in, T)), "malloc xil") ||
197            !ck(cudaMalloc((void**) &yref, ybytes), "malloc yref") || !ck(cudaMalloc((void**) &yil, ybytes), "malloc yil"))
198            return 1;
199        ck(cudaMemcpy(dx, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "copy x");
200        quantize_q8_1_rows(dx, T, c.n_in, xq, s);
201        if (T >= 2) native_q8_1_interleave(xq, xil, c.n_in, T, s);
202        native_mmvq(c.type, dw[0], xq, yref, c.n_in, c.n_out, T, s);
203        ck(cudaStreamSynchronize(s), "ref");
204        auto gap = [&]() {   // --gap: other weights' reads between the timed calls (the window's traffic)
205            for (int j = 1; j <= gap_copies; ++j) native_mmvq(c.type, dw[j], xq, yref, c.n_in, c.n_out, T, s);
206        };
207        std::vector<uint32_t> a((std::size_t) T * c.n_out), b(a.size());
208        ck(cudaMemcpy(a.data(), yref, ybytes, cudaMemcpyDeviceToHost), "read ref");
209        double best_ref = 0, best_il[5] = {0, 0, 0, 0, 0};
210        std::vector<std::array<double, 5>> pf_il(g_pf.size(), std::array<double, 5>{0, 0, 0, 0, 0});   // per --pf variant
211        int table_r = 0;
212        struct Arm { const char* name; bool hot; std::size_t gap; bool persist; };
213        const Arm arms_ab[] = {{"cold", false, 0, false}, {"hot", true, 0, false}, {"hot+gap", true, g_gap_bytes, false},
214                               {"hot+gap+persist", true, g_gap_bytes, true}, {"cold2", false, 0, false}};
215        const Arm arms_one[] = {{g_hot ? "hot" : "cold", g_hot, g_gap_bytes, g_persist}};
216        const Arm* arms = g_ab ? arms_ab : arms_one;
217        const int n_arms = g_ab ? 5 : 1;
218        for (int ai = 0; ai < (bench ? n_arms : 1); ++ai) {
219        if (bench) {
220            g_hot = arms[ai].hot;
221            g_gap_now = arms[ai].gap;
222            if (arms[ai].persist != g_persist) { g_persist = arms[ai].persist; persist_window(s, dw[0], wbytes, g_persist); }
223        }
224        const std::vector<int> pfs = g_pf.empty() ? std::vector<int>{-1} : g_pf;
225        for (int r : {0, 1, 2, 4}) {
226            native_mmvq_il_tune(r);
227            for (int pf : pfs) {
228                native_mmvq_il_pf(pf);
229                cudaMemset(yil, 0xff, ybytes);
230                native_mmvq_il(c.type, dw[0], xq, xil, yil, c.n_in, c.n_out, T, s);
231                ck(cudaStreamSynchronize(s), "il");
232                ck(cudaMemcpy(b.data(), yil, ybytes, cudaMemcpyDeviceToHost), "read il");
233                long long diff = 0, nonfinite = 0;
234                for (std::size_t i = 0; i < a.size(); ++i) {
235                    float fa;
236                    std::memcpy(&fa, &a[i], 4);
237                    if (!std::isfinite(fa)) ++nonfinite;
238                    if (a[i] != b[i]) ++diff;
239                }
240                if (diff != 0 || nonfinite != 0) {
241                    ++bad;
242                    std::printf("FAIL %-26s T=%d rows=%d pf=%d: %lld bits differ, %lld non-finite of %zu\n", c.name, T, r, pf, diff,
243                                nonfinite, a.size());
244                }
245            }
246            native_mmvq_il_pf(-1);
247            if (bench && r != 0) {
248                auto il_call = [&](int i) { native_mmvq_il(c.type, dw[g_hot ? 0 : i % copies], xq, xil, yil, c.n_in, c.n_out, T, s); };
249                if (g_pf.empty()) {
250                    best_il[r] = time_us(il_call, 200, s, gap);
251                } else {   // the variants interleaved, round after round; the median of each one's rounds
252                    std::vector<std::vector<double>> t(g_pf.size());
253                    for (int round = 0; round < g_rounds; ++round)
254                        for (std::size_t k = 0; k < g_pf.size(); ++k) {
255                            native_mmvq_il_pf(g_pf[k]);
256                            t[k].push_back(time_us(il_call, 100, s, gap));
257                        }
258                    native_mmvq_il_pf(-1);
259                    std::printf("PFBENCH %-26s T=%d rows=%d:", c.name, T, r);
260                    for (std::size_t k = 0; k < g_pf.size(); ++k) {
261                        std::sort(t[k].begin(), t[k].end());
262                        const double med = t[k][t[k].size() / 2];
263                        if (k == 0) best_il[r] = med;
264                        pf_il[k][r] = med;
265                        std::printf("  pf%d %.1f us (min %.1f max %.1f)", g_pf[k], med, t[k].front(), t[k].back());
266                    }
267                    std::printf("\n");
268                }
269            }
270        }
271        native_mmvq_il_tune(0);
272        if (bench) {
273            best_ref = time_us([&](int i) { native_mmvq(c.type, dw[g_hot ? 0 : i % copies], xq, yref, c.n_in, c.n_out, T, s); }, 200, s, gap);
274            (void) table_r;
275            if (g_pf.empty()) g_cells.push_back({c.type, T, c.n_out, -1, best_ref, {0, best_il[1], best_il[2], 0, best_il[4]}});
276            for (std::size_t k = 0; k < g_pf.size(); ++k)
277                g_cells.push_back({c.type, T, c.n_out, g_pf[k], best_ref, {0, pf_il[k][1], pf_il[k][2], 0, pf_il[k][4]}});
278            std::printf("BENCH %-26s T=%d %-16s multi %.1f us | il rows1 %.1f rows2 %.1f rows4 %.1f us\n", c.name, T,
279                        arms[ai].name, best_ref, best_il[1], best_il[2], best_il[4]);
280        }
281        }   // arms
282        cudaFree(dx); cudaFree(xq); cudaFree(xil); cudaFree(yref); cudaFree(yil);
283    }
284    if (bench && g_persist) persist_window(s, dw[0], wbytes, false);
285    for (void* p : dw) cudaFree(p);
286    return bad;
287}
288
289// the table as kIlRows prints it: per (type, ncols, n_out class) the fastest rows count if >= 3% under native_mmvq, else 0.
290// A cell with several measured shapes takes the worst (smallest) gain of the best choice, as the shipped table does for
291// two cards; a class with no measured shape prints the value of its neighbour below it (or 0).
292void emit_table() {
293    const int types[] = {23, 12, 13, 14, 11};
294    const char* names[] = {"IQ4_XS", "Q4_K", "Q5_K", "Q6_K", "Q3_K"};
295    std::printf("// measured on this card by mmvq_il_parity --bench --emit-table\n");
296    // per cell: the rows count whose WORST ratio to native_mmvq over the cell's measured shapes is the best, taken only
297    // when that worst ratio is under 0.97 (else 0); a class with no measured shape takes its lower neighbour's value
298    // pf_sel: the cells of that variant (the environment's when --pf was not given, else 0 = today's kernel); -2: every
299    // listed variant, the answer then pf << 4 | rows (the kIlPf form), 0 when nothing beats native_mmvq by 3%
300    auto pick_cell = [&](int type, int nc, int cls, int prev, int pf_sel) {
301        double best_worst = 1e9;
302        int best = -1;
303        bool any = false;
304        for (int pf : (pf_sel == -2 ? (g_pf.empty() ? std::vector<int>{-1} : g_pf) : std::vector<int>{pf_sel}))
305            for (int r : {1, 2, 4}) {
306                double worst = 0;
307                bool have = false;
308                for (const Cell& c : g_cells) {
309                    if (c.type != type || c.T != nc || c.pf != pf) continue;
310                    const int cc = c.n_out < 2048 ? 0 : c.n_out < 4096 ? 1 : c.n_out < 8192 ? 2 : c.n_out < 12288 ? 3 : 4;
311                    if (cc != cls || c.il[r] <= 0) continue;
312                    have = true;
313                    worst = std::max(worst, c.il[r] / c.ref);
314                }
315                any = any || have;
316                if (have && worst < best_worst) { best_worst = worst; best = pf_sel == -2 ? (std::max(pf, 0) << 4 | r) : r; }
317            }
318        if (!any) return prev;
319        return best_worst < 0.97 ? best : 0;
320    };
321    const int pf_today = g_pf.empty() ? -1 : 0;
322    for (int ti = 0; ti < 5; ++ti) {
323        std::printf("    {%d, {", types[ti]);
324        for (int nc = 2; nc <= 4; ++nc) {
325            int prev = 0;
326            std::printf("{");
327            for (int cls = 0; cls < 5; ++cls) {
328                prev = pick_cell(types[ti], nc, cls, prev, pf_today);
329                std::printf("%d%s", prev, cls < 4 ? ", " : "");
330            }
331            std::printf("}%s", nc < 4 ? ", " : "");
332        }
333        std::printf("}},   // %s\n", names[ti]);
334    }
335    std::printf("// 5-8 columns (kIlRows58_<cc>; rows 4 runs as 2 there):\n");
336    for (int ti = 0; ti < 5; ++ti) {
337        std::printf("    {%d, {", types[ti]);
338        for (int nc = 5; nc <= 8; ++nc) {
339            int prev = 0;
340            std::printf("{");
341            for (int cls = 0; cls < 5; ++cls) {
342                prev = pick_cell(types[ti], nc, cls, prev, pf_today);
343                std::printf("%d%s", prev, cls < 4 ? ", " : "");
344            }
345            std::printf("}%s", nc < 8 ? ", " : "");
346        }
347        std::printf("}},   // %s\n", names[ti]);
348    }
349    if (!g_pf.empty()) {   // the joint (variant, rows) table over the listed variants: kIlPf_80 / kIlPf58_80
350        std::printf("// variant << 4 | rows over --pf (kIlPf_<cc>), 2-4 columns:\n");
351        for (int ti = 0; ti < 5; ++ti) {
352            std::printf("    {%d, {", types[ti]);
353            for (int nc = 2; nc <= 4; ++nc) {
354                int prev = 0;
355                std::printf("{");
356                for (int cls = 0; cls < 5; ++cls) {
357                    prev = pick_cell(types[ti], nc, cls, prev, -2);
358                    std::printf("0x%02x%s", prev, cls < 4 ? ", " : "");
359                }
360                std::printf("}%s", nc < 4 ? ", " : "");
361            }
362            std::printf("}},   // %s\n", names[ti]);
363        }
364        std::printf("// 5-8 columns (kIlPf58_<cc>):\n");
365        for (int ti = 0; ti < 5; ++ti) {
366            std::printf("    {%d, {", types[ti]);
367            for (int nc = 5; nc <= 8; ++nc) {
368                int prev = 0;
369                std::printf("{");
370                for (int cls = 0; cls < 5; ++cls) {
371                    prev = pick_cell(types[ti], nc, cls, prev, -2);
372                    std::printf("0x%02x%s", prev, cls < 4 ? ", " : "");
373                }
374                std::printf("}%s", nc < 8 ? ", " : "");
375            }
376            std::printf("}},   // %s\n", names[ti]);
377        }
378    }
379    std::printf("// one column (kIl1RowsShared):\n");
380    for (int ti = 0; ti < 5; ++ti) {
381        std::printf("    {%d, {", types[ti]);
382        int prev = 0;
383        for (int cls = 0; cls < 5; ++cls) {
384            prev = pick_cell(types[ti], 1, cls, prev, pf_today);
385            std::printf("%d%s", prev, cls < 4 ? ", " : "");
386        }
387        std::printf("}},   // %s\n", names[ti]);
388    }
389}
390
391// the per-architecture lookup, no GPU needed for its answers
392// The two Ada runs sm_89's table was merged from (mmvq_il_parity --bench --emit-table, issue 3453): by type IQ4_XS, Q4_K,
393// Q5_K, Q6_K, Q3_K, then 2/3/4 columns, then the five n_out classes.
394const int kAda4070[5][3][5] = {
395    {{0, 0, 0, 1, 0}, {1, 1, 1, 1, 1}, {2, 2, 1, 1, 1}}, {{0, 0, 1, 1, 1}, {0, 0, 1, 1, 1}, {0, 1, 1, 1, 1}},
396    {{0, 0, 1, 1, 1}, {0, 0, 1, 1, 1}, {1, 2, 1, 2, 2}}, {{0, 0, 0, 0, 0}, {0, 0, 1, 2, 2}, {0, 1, 4, 1, 1}},
397    {{1, 1, 1, 2, 1}, {1, 1, 1, 1, 1}, {2, 1, 1, 1, 1}}};
398const int kAda4080[5][3][5] = {
399    {{0, 0, 0, 0, 0}, {0, 0, 1, 1, 1}, {0, 1, 1, 1, 1}}, {{0, 0, 1, 1, 1}, {0, 0, 1, 1, 1}, {0, 0, 1, 1, 1}},
400    {{0, 0, 1, 1, 0}, {0, 0, 1, 1, 0}, {0, 0, 1, 1, 1}}, {{0, 0, 0, 1, 0}, {0, 0, 1, 1, 1}, {0, 0, 1, 1, 1}},
401    {{0, 0, 1, 1, 1}, {0, 1, 1, 1, 1}, {0, 1, 1, 1, 1}}};
402int check_tables() {
403    int bad = 0;
404    const char* e89 = std::getenv("STRATA_MMVQ_IL_89");
405    // sm_89's own tables are ON by default (#3453, 0.2.7) unless STRATA_MMVQ_IL_89=0 or STRATA_DEFAULTS=026
406    const bool opt89 = strata::mmvq_il_89_resolve(e89, false, 89, strata::qwen_defaults_026());
407    for (int type : {23, 12, 13, 14, 11})
408        for (int nc = 2; nc <= 4; ++nc)
409            for (int n_out : {512, 2560, 6144, 10240, 12288, 248320}) {
410                const int a = native_mmvq_il_rows_for(86, type, nc, n_out);
411                if (a != 0 && a != 1 && a != 2 && a != 4) { ++bad; std::printf("FAIL table: rows %d\n", a); }
412                // sm_89 (#3453): the cells where an RTX 4070 and an RTX 4080 gave the same rows count, else 0
413                const int cls = n_out < 2048 ? 0 : n_out < 4096 ? 1 : n_out < 8192 ? 2 : n_out < 12288 ? 3 : 4;
414                const int ti = type == 23 ? 0 : type == 12 ? 1 : type == 13 ? 2 : type == 14 ? 3 : 4;
415                const int b = native_mmvq_il_rows_for(89, type, nc, n_out);
416                // tables on (the default): the agreement; off (=0 or STRATA_DEFAULTS=026): what sm_89 answered before #3453 (the shared table, which is
417                // sm_86's except Q3_K, a type the shared table has no row for)
418                const int want = opt89 ? (kAda4070[ti][nc - 2][cls] == kAda4080[ti][nc - 2][cls] ? kAda4070[ti][nc - 2][cls] : 0)
419                                       : (type == 11 ? 0 : a);
420                if (b != want) {
421                    ++bad;
422                    std::printf("FAIL table: sm_89 is %d, %s says %d at type %d ncols %d n_out %d\n", b,
423                                opt89 ? "the 4070/4080 agreement" : "the shared table", want, type, nc, n_out);
424                }
425            }
426    // Volta has its own table (PR 1401): Q6_K at 2 columns, 2560 rows -> 1 row a warp; the Ampere table says 0 there
427    if (native_mmvq_il_rows_for(70, 14, 2, 2560) != 1 || native_mmvq_il_rows_for(86, 14, 2, 2560) != 0) {
428        ++bad;
429        std::printf("FAIL table: the sm_70 table is not the V100's\n");
430    }
431    // Pascal has its own table too (the P100's): Q6_K, 3 columns, 12288 rows -> 4 rows a warp; sm_75 still has none (the shared one)
432    if (native_mmvq_il_rows_for(60, 14, 3, 12288) != 4 || native_mmvq_il_rows_for(60, 23, 2, 512) != 0) {
433        ++bad;
434        std::printf("FAIL table: the sm_60 table is not the P100's\n");
435    }
436    // sm_89 one column: only Q3_K with the tables on (the 4070 and the 4080 agree), else none; wider than 4: the plain kernels
437    if (native_mmvq_il_rows_for(89, 11, 1, 2560) != 0 || native_mmvq_il_rows_for(89, 11, 1, 6144) != (opt89 ? 1 : 0) ||
438        native_mmvq_il_rows_for(89, 12, 1, 6144) != 0) {
439        ++bad;
440        std::printf("FAIL table: the sm_89 one-column row is not Q3_K only\n");
441    }
442    // sm_80 has its own tables (kIlRows_80 / kIlRows58_80 / kIl1Rows_80: a CMP 170HX's); the key 81 is what STRATA_MMVQ_IL_SM80=0
443    // gives an sm_80 card: no table of its own, so the shared one (and no one-column table).  Every answer is 0, 1, 2 or 4.
444    {
445        bool differs = false;
446        for (int type : {23, 12, 13, 14, 11})
447            for (int nc = 1; nc <= 8; ++nc)
448                for (int n_out : {512, 2560, 6144, 10240, 12288, 248320}) {
449                    const int a = native_mmvq_il_rows_for(80, type, nc, n_out), b = native_mmvq_il_rows_for(81, type, nc, n_out);
450                    if (a != 0 && a != 1 && a != 2 && a != 4) { ++bad; std::printf("FAIL table: sm_80 rows %d\n", a); }
451                    differs = differs || a != b;
452                }
453        if (!differs) { ++bad; std::printf("FAIL table: sm_80 answers like the shared table\n"); }
454        // spot checks read off the source tables: Q6_K at 3 columns and 2560 rows (class 1) is {0, 2, 2, 2, 2}[1] = 2; one-column
455        // IQ4_XS at 6144 rows (class 2) is {0, 0, 1, 4, 1}[2] = 1 on sm_80 and 0 (no one-column table) on the key 81
456        if (native_mmvq_il_rows_for(80, 14, 3, 2560) != 2 || native_mmvq_il_rows_for(80, 23, 1, 6144) != 1 ||
457            native_mmvq_il_rows_for(81, 23, 1, 6144) != 0) {
458            ++bad;
459            std::printf("FAIL table: the sm_80 table is not the CMP 170HX's\n");
460        }
461    }
462    if (native_mmvq_il_rows_for(89, 99, 2, 2560) != 0 || native_mmvq_il_rows_for(89, 12, 5, 2560) != 0 ||
463        native_mmvq_il_rows_for(86, 12, 5, 2560) != 0 || native_mmvq_il_rows_for(120, 12, 9, 2560) != 0) {
464        ++bad;
465        std::printf("FAIL table: an unknown type or ncols must be 0\n");
466    }
467    return bad;
468}
469}  // namespace
470
471int main(int argc, char** argv) {
472    const bool bench = argc > 1 && std::string(argv[1]) == "--bench";
473    const bool emit = bench && argc > 2 && std::string(argv[2]) == "--emit-table";
474    for (int i = 1; i < argc; ++i) {
475        const std::string a = argv[i];
476        if (a == "--hot") g_hot = true;
477        else if (a == "--ab") g_ab = true;
478        else if (a == "--persist") g_persist = true;
479        else if (a == "--gap" && i + 1 < argc) g_gap_bytes = (std::size_t) std::atoi(argv[++i]) << 20;
480        else if (a == "--rounds" && i + 1 < argc) g_rounds = std::atoi(argv[++i]);
481        else if (a == "--pf" && i + 1 < argc) {
482            const std::string list = argv[++i];
483            for (std::size_t p = 0; p < list.size();) {
484                std::size_t q = list.find(',', p);
485                if (q == std::string::npos) q = list.size();
486                g_pf.push_back(std::atoi(list.substr(p, q - p).c_str()));
487                p = q + 1;
488            }
489        }
490    }
491    cudaStream_t s;
492    cudaStreamCreate(&s);
493#if !defined(STRATA_HIP_GFX906)
494    if (g_persist || g_ab) {
495        int dev = 0, l2 = 0, maxp = 0, maxw = 0;
496        cudaGetDevice(&dev);
497        cudaDeviceGetAttribute(&l2, cudaDevAttrL2CacheSize, dev);
498        cudaDeviceGetAttribute(&maxp, cudaDevAttrMaxPersistingL2CacheSize, dev);
499        cudaDeviceGetAttribute(&maxw, cudaDevAttrMaxAccessPolicyWindowSize, dev);
500        std::size_t want = std::min<std::size_t>(20u << 20, (std::size_t) maxp), got = 0;
501        const cudaError_t e = cudaDeviceSetLimit(cudaLimitPersistingL2CacheSize, want);
502        cudaDeviceGetLimit(&got, cudaLimitPersistingL2CacheSize);
503        std::printf("--persist: L2 %d MiB, max persisting %d MiB, max window %d MiB; set-aside asked %zu MiB -> %s, granted %zu MiB\n",
504                    l2 >> 20, maxp >> 20, maxw >> 20, want >> 20, cudaGetErrorString(e), got >> 20);
505    }
506#endif
507    if (bench) std::printf("bench arms: %s%s%s\n", g_hot ? "hot (one copy) " : "cold (192 MB rotation) ",
508                           g_gap_bytes ? ("gap " + std::to_string(g_gap_bytes >> 20) + " MB ").c_str() : "", g_persist ? "persist" : "");
509    int bad = 0;
510    bad += check_tables();
511    if (bench) {   // ~150 ms of launches so the clocks are up before the first timed case
512        void* wu = nullptr; float* yu = nullptr; void* xu = nullptr;
513        if (cudaMalloc(&wu, 6144u * 2560u) == cudaSuccess && cudaMalloc((void**) &yu, 2560 * 4) == cudaSuccess &&
514            cudaMalloc(&xu, native_q8_1_bytes(6144, 1)) == cudaSuccess) {
515            (void) cudaMemset(wu, 0, 6144u * 2560u); (void) cudaMemset(xu, 0, native_q8_1_bytes(6144, 1));
516            for (int i = 0; i < 6000; ++i) native_mmvq(12, wu, xu, yu, 6144, 2560, 1, s);
517            (void) cudaStreamSynchronize(s);
518            (void) cudaFree(wu); (void) cudaFree(yu); (void) cudaFree(xu);
519        }
520    }
521    const char* only = std::getenv("MMVQ_IL_ONLY");   // 143-dense: only the cases whose name contains this
522    for (const Case& c : CASES)
523        if (only == nullptr || std::strstr(c.name, only) != nullptr) bad += run_case(c, bench, s);
524    if (emit) emit_table();
525    std::printf("%s\n", bad ? "mmvq_il_parity: FAIL" : "mmvq_il_parity: OK (every case, T 1-8, rows 1/2/4 and the table, bitwise)");
526    return bad ? 1 : 0;
527}