okami.mom/strata

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

Niko1221Merge branch 'f-split-int' into f-split-vision7c5e84612

main
21.8 KiB418 linesraw
1// Recovered from the Claude Daily merge parity harness (lab/wip-0809), extended to the Daily's chunk kernel.
2// src/kernels/qsa_merge_daily_parity.cpp - the Daily's decode attention (STRATA_ATTN_DAILY=1: attn_chunk_kernel_pre75
3// and attn_merge_v2_kernel) against upstream's (attn_chunk_kernel, attn_merge_kernel), bitwise (GPU, synthetic, no
4// model).
5//
6// The reference is upstream's pair: one chunk pass with attn_chunk_kernel (qsa_decode_attn_chunks_only, daily_chunk 0)
7// and attn_merge_kernel (qsa_decode_attn_merge_only, v2 0).  Against it, memcmp of: attn_merge_v2_kernel on the same
8// partials; the production entry points (qsa_decode_attn_batch, and _step at n_q 1) as the environment sets them; the
9// Daily's chunk kernel (daily_chunk 1, NaN-filled scratch again) merged by both mergers.  Kernels are chosen by the
10// arguments, never by the environment, except for the production entries.  Covers:
11//   - the four KV formats the chunk kernel reads: fp16, int8, q4_0 (rotated or not, the merge cannot tell), k8v4;
12//   - page tables with unresident (-1) pages: scattered single pages, and one run of 64 pages (256 consecutive cells)
13//     that the window-shaped selections land on, so whole chunks inside the width are masked (m = -FLT_MAX, l = 0,
14//     acc = 0) and some queries are masked entirely (output 0);
15//   - widths {-1, 0, 1, 63, 64, 65, 1023, 1024, 1025, 2051, 4096, 16383, 16385, 32768, INT_MAX} per query (1023-1025 and 16383 /
16//     16385 sit on the v2 merge's 16-chunk block edges), all queries alike and mixed within one batch; a width above
17//     aligned cap (2112/32768) is bounded by the chunk grid; an unaligned cap2051 keeps width<=cap;
18//   - n_q 1..6, caps2051/2112 (main selection and its rounded capacity) and32768 (the drafter's
19//     default --mtp-window);
20//   - selections shaped like the drafter's window (consecutive cells, window_ids), like the indexer's (ascending, with
21//     gaps) and unordered with repeats.
22// The scratch is filled with NaN before every chunk pass, so a merge that read a partial the chunk pass did not write
23// (a chunk past the width, say) would differ from the other one or produce a NaN.  ~260 MB of VRAM.
24//
25//   qsa_merge_daily_parity [--device N]           the sweep; exit 0 when every case is bit-identical (77: no GPU)
26//   qsa_merge_daily_parity [--device N] --bench   plus each merge's time per call at target/drafter caps2051/32768
27#include "strata/kernels/kv_q4.hpp"
28#include "strata/kernels/kv_q8.hpp"
29#include "strata/kernels/qsa.hpp"
30#include "strata/kernels/qsa_decode_attn.hpp"
31
32#include <cuda_runtime.h>
33
34#include <algorithm>
35#include <cmath>
36#include <cstdint>
37#include <cstdio>
38#include <cstdlib>
39#include <cstring>
40#include <limits>
41#include <random>
42#include <vector>
43
44namespace k = strata::kernels;
45
46namespace {
47void ck(cudaError_t e, const char* what) {
48    if (e != cudaSuccess) {
49        std::fprintf(stderr, "qsa_merge_daily_parity: %s: %s\n", what, cudaGetErrorString(e));
50        std::exit(2);
51    }
52}
53template <typename T> T* dalloc(size_t n) {
54    T* p = nullptr;
55    ck(cudaMalloc((void**) &p, n * sizeof(T) + 256), "cudaMalloc");
56    ck(cudaMemset(p, 0, n * sizeof(T) + 256), "cudaMemset");
57    return p;
58}
59template <typename T> T* upload(const std::vector<T>& h) {
60    T* d = dalloc<T>(h.size());
61    ck(cudaMemcpy(d, h.data(), h.size() * sizeof(T), cudaMemcpyHostToDevice), "upload");
62    return d;
63}
64
65// fp16 bits drawn directly: a random sign, exponent 11..15 (|x| in [2^-4, 2)), a random mantissa; finite by
66// construction. Scales are positive: INT8 [1/64, 1/32) (codes up to 127 give |x| < 4), Q4_0 [1/4, 1/2).
67uint16_t f16_value(uint32_t r) { return (uint16_t) ((r & 0x8000u) | ((11u + (r >> 16) % 5u) << 10) | (r & 0x3FFu)); }
68uint16_t f16_scale_q8(uint32_t r) { return (uint16_t) ((9u << 10) | (r & 0x3FFu)); }
69uint16_t f16_scale_q4(uint32_t r) { return (uint16_t) ((13u << 10) | (r & 0x3FFu)); }
70
71constexpr int kFmtF16 = 0, kFmtInt8 = 1, kFmtQ4 = 2, kFmtK8V4 = 3;
72const char* fmt_name(int f) { return f == kFmtF16 ? "fp16" : f == kFmtInt8 ? "int8" : f == kFmtQ4 ? "q4_0" : "k8v4"; }
73
74struct DevicePools {   // every format's pools over the same physical rows; `view` picks what a KV mode reads
75    uint16_t *k16 = nullptr, *v16 = nullptr, *k8s = nullptr, *v8s = nullptr;
76    int8_t *k8 = nullptr, *v8 = nullptr;
77    uint8_t *k4 = nullptr, *v4 = nullptr;
78    k::QsaAttnPools view(int fmt, const int32_t* table) const {
79        k::QsaAttnPools p;
80        p.page_table = table;
81        if (fmt == kFmtF16) { p.k_pool = k16; p.v_pool = v16; }
82        else if (fmt == kFmtInt8) { p.k_q = k8; p.v_q = v8; p.k_scale = k8s; p.v_scale = v8s; }
83        else if (fmt == kFmtQ4) { p.k_q4 = k4; p.v_q4 = v4; }
84        else { p.k_q = k8; p.k_scale = k8s; p.v_q4 = v4; }   // K8V4: INT8 K, Q4_0 V (qsa_decode_attn.cu kv_mode 3)
85        return p;
86    }
87};
88
89DevicePools make_pools(int64_t rows, int64_t D, std::mt19937& rng) {
90    DevicePools p;
91    {
92        std::vector<uint16_t> h((size_t) (rows * D));
93        for (auto& x : h) x = f16_value(rng());
94        p.k16 = upload(h);
95        for (auto& x : h) x = f16_value(rng());
96        p.v16 = upload(h);
97    }
98    {
99        std::vector<int8_t> c((size_t) (rows * D));
100        for (auto& x : c) x = (int8_t) ((int) (rng() % 255u) - 127);
101        p.k8 = upload(c);
102        for (auto& x : c) x = (int8_t) ((int) (rng() % 255u) - 127);
103        p.v8 = upload(c);
104        std::vector<uint16_t> sc((size_t) (rows * (D / k::KV_Q8_GROUP)));
105        for (auto& x : sc) x = f16_scale_q8(rng());
106        p.k8s = upload(sc);
107        for (auto& x : sc) x = f16_scale_q8(rng());
108        p.v8s = upload(sc);
109    }
110    {
111        const size_t blocks = (size_t) (rows * (D / k::QK4_0));
112        std::vector<uint8_t> b(blocks * sizeof(k::block_q4_0));
113        for (int side = 0; side < 2; ++side) {
114            for (size_t i = 0; i < blocks; ++i) {
115                k::block_q4_0 blk;
116                blk.d = f16_scale_q4(rng());
117                for (auto& q : blk.qs) q = (uint8_t) (rng() & 0xFFu);
118                std::memcpy(b.data() + i * sizeof(k::block_q4_0), &blk, sizeof(blk));
119            }
120            (side == 0 ? p.k4 : p.v4) = upload(b);
121        }
122    }
123    return p;
124}
125
126struct Case {
127    int fmt = 0;
128    int64_t cap = 0;
129    int n_q = 0;
130    std::vector<int32_t> widths;
131};
132
133// the cells this harness can address, and where the 64 unresident pages in a row sit (cells [kHole, kHole + 256))
134constexpr int64_t kCells = 40960;
135constexpr int64_t kHole = 8192;
136
137// query `i`'s `cap` selection ids. Every entry is a valid cell: a width above the cap makes the chunk kernel read
138// all `cap` of them.
139void selection(int32_t* ids, int64_t cap, int width, int shape, std::mt19937& rng) {
140    const int64_t w = std::max<int64_t>(0, std::min<int64_t>(width, cap));
141    if (shape == 0) {   // the drafter's window: consecutive cells (window_ids), often across the unresident run
142        int64_t start;
143        if (rng() % 2 == 0) start = std::max<int64_t>(0, kHole - 64 * (int64_t) (rng() % 8));   // chunk-aligned on it
144        else start = (int64_t) (rng() % (uint32_t) (kCells - std::max<int64_t>(w, 1)));
145        if (start + w > kCells) start = kCells - w;
146        for (int64_t j = 0; j < cap; ++j) ids[j] = (int32_t) ((start + j) % kCells);
147    } else if (shape == 1) {   // the indexer's: ascending with gaps
148        std::vector<int32_t> v((size_t) cap);
149        for (auto& x : v) x = (int32_t) (rng() % (uint32_t) kCells);
150        std::sort(v.begin(), v.begin() + w);
151        std::copy(v.begin(), v.end(), ids);
152    } else {   // unordered, with repeats
153        for (int64_t j = 0; j < cap; ++j) ids[j] = (int32_t) (rng() % (uint32_t) kCells);
154    }
155}
156
157struct Harness {
158    k::QsaShapes s = k::qsa_real_shapes();
159    DevicePools pools;
160    int32_t* table = nullptr;
161    float *q = nullptr, *scratch = nullptr, *attn_old = nullptr, *attn_new = nullptr;
162    int32_t *ids = nullptr, *steps = nullptr;
163    int64_t max_q = 0, max_cap = 0;
164
165    void init(std::mt19937& rng, int64_t max_q_, int64_t max_cap_) {
166        max_q = max_q_;
167        max_cap = max_cap_;
168        const int64_t PS = s.page_size, pages = kCells / PS, H = s.n_head_kv, D = s.head_dim;
169        // logical page -> physical page: a permutation, ~3% scattered unresident pages, and the 64-page hole
170        std::vector<int32_t> tab((size_t) pages);
171        for (int64_t i = 0; i < pages; ++i) tab[(size_t) i] = (int32_t) i;
172        std::shuffle(tab.begin(), tab.end(), rng);
173        for (int64_t i = 0; i < pages; ++i)
174            if (rng() % 32u == 0) tab[(size_t) i] = -1;
175        for (int64_t i = kHole / PS; i < (kHole + 256) / PS; ++i) tab[(size_t) i] = -1;
176        table = upload(tab);
177        pools = make_pools(pages * H * PS, D, rng);
178        q = dalloc<float>((size_t) (max_q * s.n_head * D));
179        ids = dalloc<int32_t>((size_t) (max_q * max_cap));
180        steps = dalloc<int32_t>((size_t) (max_q * k::kStepCount));
181        scratch = dalloc<float>((size_t) (k::qsa_decode_attn_scratch_floats(max_cap, s) * (uint64_t) max_q));
182        attn_old = dalloc<float>((size_t) (max_q * s.n_head * D));
183        attn_new = dalloc<float>((size_t) (max_q * s.n_head * D));
184    }
185
186    ~Harness() {
187        for (void* p : {static_cast<void*>(table), static_cast<void*>(q), static_cast<void*>(ids),
188                       static_cast<void*>(steps), static_cast<void*>(scratch), static_cast<void*>(attn_old),
189                       static_cast<void*>(attn_new), static_cast<void*>(pools.k16), static_cast<void*>(pools.v16),
190                       static_cast<void*>(pools.k8), static_cast<void*>(pools.v8), static_cast<void*>(pools.k8s),
191                       static_cast<void*>(pools.v8s), static_cast<void*>(pools.k4), static_cast<void*>(pools.v4)})
192            if (p) ck(cudaFree(p), "free harness");
193    }
194
195    // uploads the case's queries, selections and widths, and runs ONE chunk pass into NaN-filled scratch
196    void prepare(const Case& c, std::mt19937& rng) {
197        const int64_t D = s.head_dim, NH = s.n_head;
198        std::normal_distribution<float> nd(0.0f, 1.0f);
199        std::vector<float> hq((size_t) (c.n_q * NH * D));
200        for (auto& x : hq) x = nd(rng);
201        ck(cudaMemcpy(q, hq.data(), hq.size() * 4, cudaMemcpyHostToDevice), "q");
202        std::vector<int32_t> hid((size_t) (c.n_q * c.cap));
203        std::vector<int32_t> hst((size_t) (c.n_q * k::kStepCount), 0);
204        for (int i = 0; i < c.n_q; ++i) {
205            selection(hid.data() + (size_t) i * c.cap, c.cap, c.widths[(size_t) i], (int) (rng() % 3u), rng);
206            hst[(size_t) i * k::kStepCount + k::kStepWidth] = c.widths[(size_t) i];
207        }
208        ck(cudaMemcpy(ids, hid.data(), hid.size() * 4, cudaMemcpyHostToDevice), "ids");
209        ck(cudaMemcpy(steps, hst.data(), hst.size() * 4, cudaMemcpyHostToDevice), "steps");
210        const size_t scratch_bytes = (size_t) k::qsa_decode_attn_scratch_floats(c.cap, s) * (size_t) c.n_q * 4;
211        ck(cudaMemset(scratch, 0xFF, scratch_bytes), "scratch NaN fill");
212        ck(cudaMemset(attn_old, 0xFF, (size_t) (c.n_q * NH * D) * 4), "attn_old fill");
213        ck(cudaMemset(attn_new, 0x7F, (size_t) (c.n_q * NH * D) * 4), "attn_new fill");
214        k::qsa_decode_attn_chunks_only(q, pools.view(c.fmt, table), ids, steps, c.cap, s, scratch, c.n_q, 0, nullptr);
215    }
216
217    // true when the two merges' outputs are bit-identical (and the original's has no NaN)
218    bool check(const Case& c, long long& nonzero) {
219        const int64_t D = s.head_dim, NH = s.n_head;
220        k::qsa_decode_attn_merge_only(steps, c.cap, s, scratch, attn_old, c.n_q, 0, nullptr);
221        k::qsa_decode_attn_merge_only(steps, c.cap, s, scratch, attn_new, c.n_q, 1, nullptr);
222        ck(cudaDeviceSynchronize(), "merge sync");
223        const size_t n = (size_t) (c.n_q * NH * D);
224        std::vector<float> a(n), b(n);
225        ck(cudaMemcpy(a.data(), attn_old, n * 4, cudaMemcpyDeviceToHost), "attn_old");
226        ck(cudaMemcpy(b.data(), attn_new, n * 4, cudaMemcpyDeviceToHost), "attn_new");
227        nonzero = 0;
228        long long nan = 0;
229        for (size_t i = 0; i < n; ++i) {
230            if (a[i] != 0.0f) ++nonzero;
231            if (!std::isfinite(a[i])) ++nan;
232        }
233        const bool same = std::memcmp(a.data(), b.data(), n * 4) == 0;
234        if (!same || nan) {
235            size_t first = 0;
236            while (first < n && std::memcmp(&a[first], &b[first], 4) == 0) ++first;
237            std::printf("FAIL %s cap %lld n_q %d widths", fmt_name(c.fmt), (long long) c.cap, c.n_q);
238            for (int32_t w : c.widths) std::printf(" %d", w);
239            if (first < n) {
240                uint32_t ua, ub;
241                std::memcpy(&ua, &a[first], 4);
242                std::memcpy(&ub, &b[first], 4);
243                std::printf(": first difference at query %lld head %lld dim %lld: %.9g (0x%08x) vs %.9g (0x%08x)",
244                            (long long) (first / (NH * D)), (long long) (first / D % NH), (long long) (first % D),
245                            a[first], ua, b[first], ub);
246            }
247            if (nan) std::printf(" (%lld nonfinite values in the original's output)", nan);
248            std::printf("\n");
249        }
250        // Exercise production entry points too: either selected merger must equal the reference partials.
251        bool entry_same = true;
252        k::qsa_decode_attn_batch(q, pools.view(c.fmt, table), ids, steps, c.cap, s, scratch, attn_new, c.n_q, nullptr);
253        ck(cudaDeviceSynchronize(), "batch entry sync");
254        ck(cudaMemcpy(b.data(), attn_new, n * 4, cudaMemcpyDeviceToHost), "batch entry output");
255        if (std::memcmp(a.data(), b.data(), n * 4) != 0) {
256            std::puts("FAIL production batch differs from merge reference");
257            entry_same = false;
258        }
259        if (c.n_q == 1) {
260            k::qsa_decode_attn_step(q, pools.view(c.fmt, table), ids, steps, c.cap, s, scratch, attn_new, nullptr);
261            ck(cudaDeviceSynchronize(), "step entry sync");
262            ck(cudaMemcpy(b.data(), attn_new, n * 4, cudaMemcpyDeviceToHost), "step entry output");
263            if (std::memcmp(a.data(), b.data(), n * 4) != 0) {
264                std::puts("FAIL production step differs from merge reference");
265                entry_same = false;
266            }
267        }
268        // The Daily's chunk kernel on the same inputs, into NaN-filled scratch, merged by both mergers.
269        bool daily_same = true;
270        const size_t scratch_bytes = (size_t) k::qsa_decode_attn_scratch_floats(c.cap, s) * (size_t) c.n_q * 4;
271        ck(cudaMemset(scratch, 0xFF, scratch_bytes), "scratch NaN refill");
272        k::qsa_decode_attn_chunks_only(q, pools.view(c.fmt, table), ids, steps, c.cap, s, scratch, c.n_q, 1, nullptr);
273        for (int v2 = 0; v2 < 2; ++v2) {
274            ck(cudaMemset(attn_new, 0x7F, n * 4), "attn_new refill");
275            k::qsa_decode_attn_merge_only(steps, c.cap, s, scratch, attn_new, c.n_q, v2, nullptr);
276            ck(cudaDeviceSynchronize(), "daily chunk sync");
277            ck(cudaMemcpy(b.data(), attn_new, n * 4, cudaMemcpyDeviceToHost), "daily chunk output");
278            if (std::memcmp(a.data(), b.data(), n * 4) != 0) {
279                std::printf("FAIL Daily chunk kernel + %s differs from upstream reference\n",
280                            v2 ? "attn_merge_v2_kernel" : "attn_merge_kernel");
281                daily_same = false;
282            }
283        }
284        return same && nan == 0 && entry_same && daily_same;
285    }
286};
287
288void bench(Harness& hx, std::mt19937& rng) {
289    std::printf("\n--bench: CUDA events over 200 calls per arm, each arm warmed outside timing, same buffers.\n"
290                "chunks BAB: B1(Daily chunk) -> A(upstream chunk) -> B2(Daily chunk); merges on hot partials:\n"
291                "BAB: B1(v2) -> A(upstream merger) -> B2(v2).\n");
292    std::printf("%-6s %6s %4s %6s | %9s %9s %9s %9s | %9s %9s %9s %9s\n", "fmt", "cap", "n_q", "width",
293                "chB1 us", "chA us", "chB2 us", "meanB/A", "B1 us", "A us", "B2 us", "meanB/A");
294    cudaEvent_t e0, e1;
295    ck(cudaEventCreate(&e0), "event");
296    ck(cudaEventCreate(&e1), "event");
297    const int iters = 200;
298    for (int64_t cap : {(int64_t) 2051, (int64_t) 32768})
299    for (int fmt : {kFmtQ4, kFmtInt8, kFmtF16}) {
300        for (int n_q : {1, 2, 3, 4}) {
301            for (int width : {64, 2051, 16384, 31000, 32768}) {
302                Case c;
303                c.fmt = fmt;
304                if (width > cap) continue;
305                c.cap = cap;
306                c.n_q = n_q;
307                c.widths.assign((size_t) n_q, width);
308                hx.prepare(c, rng);
309                ck(cudaDeviceSynchronize(), "bench prepare");
310                double us_ch[3] = {};
311                for (int arm = 0; arm < 3; ++arm) {   // B1 -> A -> B2: Daily, upstream, Daily chunk kernel
312                    const int daily = arm == 1 ? 0 : 1;
313                    auto chunks = [&] {
314                        k::qsa_decode_attn_chunks_only(hx.q, hx.pools.view(fmt, hx.table), hx.ids, hx.steps, c.cap,
315                                                       hx.s, hx.scratch, n_q, daily, nullptr);
316                    };
317                    for (int i = 0; i < iters; ++i) chunks();
318                    ck(cudaDeviceSynchronize(), "chunk warm");
319                    ck(cudaEventRecord(e0, nullptr), "record");
320                    for (int i = 0; i < iters; ++i) chunks();
321                    ck(cudaEventRecord(e1, nullptr), "record");
322                    ck(cudaEventSynchronize(e1), "sync");
323                    float ms_chunks = 0.0f;
324                    ck(cudaEventElapsedTime(&ms_chunks, e0, e1), "elapsed");
325                    us_ch[arm] = 1000.0 * ms_chunks / iters;
326                }
327                const double ratio_ch = us_ch[1] > 0.0 ? (us_ch[0] + us_ch[2]) / (2.0 * us_ch[1]) : std::nan("");
328                double us[3] = {};
329                for (int arm = 0; arm < 3; ++arm) {   // B1 -> A -> B2 at this identical shape
330                    const int v2 = arm == 1 ? 0 : 1;
331                    auto merge = [&] {
332                        k::qsa_decode_attn_merge_only(hx.steps, c.cap, hx.s, hx.scratch, hx.attn_new, n_q, v2, nullptr);
333                    };
334                    for (int i = 0; i < iters; ++i) merge();
335                    ck(cudaDeviceSynchronize(), "merge arm warm");
336                    ck(cudaEventRecord(e0, nullptr), "record");
337                    for (int i = 0; i < iters; ++i) merge();
338                    ck(cudaEventRecord(e1, nullptr), "record");
339                    ck(cudaEventSynchronize(e1), "sync");
340                    float ms = 0.0f;
341                    ck(cudaEventElapsedTime(&ms, e0, e1), "elapsed");
342                    us[arm] = 1000.0 * ms / iters;
343                }
344                const double ratio = us[1] > 0.0 ? (us[0] + us[2]) / (2.0 * us[1]) : std::nan("");
345                std::printf("%-6s %6lld %4d %6d | %9.2f %9.2f %9.2f %9.4f | %9.2f %9.2f %9.2f %9.4f\n",
346                            fmt_name(fmt), (long long) cap, n_q, width, us_ch[0], us_ch[1], us_ch[2], ratio_ch, us[0],
347                            us[1], us[2], ratio);
348            }
349        }
350    }
351    ck(cudaEventDestroy(e0), "destroy event");
352    ck(cudaEventDestroy(e1), "destroy event");
353}
354}  // namespace
355
356int main(int argc, char** argv) {
357    int device = 0;
358    bool do_bench = false;
359    for (int i = 1; i < argc; ++i) {
360        if (std::strcmp(argv[i], "--bench") == 0) do_bench = true;
361        else if (std::strcmp(argv[i], "--device") == 0 && i + 1 < argc) device = std::atoi(argv[++i]);
362        else {
363            std::fprintf(stderr, "usage: qsa_merge_daily_parity [--device N] [--bench]\n");
364            return 2;
365        }
366    }
367    int devices = 0;
368    if (cudaGetDeviceCount(&devices) != cudaSuccess || devices == 0) {
369        std::puts("SKIP: no GPU");
370        return 77;
371    }
372    ck(cudaSetDevice(device), "cudaSetDevice");
373    cudaDeviceProp prop{};
374    ck(cudaGetDeviceProperties(&prop, device), "cudaGetDeviceProperties");
375    std::printf("qsa_merge_daily_parity on device %d (%s, %d.%d)\n", device, prop.name, prop.major, prop.minor);
376
377    std::mt19937 rng(20261004u);
378    Harness hx;
379    hx.init(rng, 7, 32768);
380
381    // 1023 / 1024 / 1025 and 16383 / 16385: the v2 merge's U = 16 chunks x 64 cells block edges
382    const int32_t widths[] = {-1, 0, 1, 63, 64, 65, 1023, 1024, 1025, 2051, 4096, 16383, 16384, 16385, 32768, std::numeric_limits<int32_t>::max()};
383    const int n_widths = (int) (sizeof(widths) / sizeof(widths[0]));
384    long long cases = 0, failed = 0, nonzero_total = 0;
385    for (int fmt = 0; fmt < 4; ++fmt) {
386        long long fmt_cases = 0, fmt_failed = 0;
387        for (int64_t cap : {(int64_t) 2051, (int64_t) 2112, (int64_t) 32768}) {
388            for (int n_q = 1; n_q <= 6; ++n_q) {
389                // every width for all queries alike, then three batches of mixed widths
390                for (int wc = 0; wc < n_widths + 3; ++wc) {
391                    Case c;
392                    c.fmt = fmt;
393                    c.cap = cap;
394                    c.n_q = n_q;
395                    for (int i = 0; i < n_q; ++i)
396                        c.widths.push_back(wc < n_widths ? widths[wc] : widths[rng() % (uint32_t) n_widths]);
397                    // The unchanged chunk contract requires width<=cap for an unaligned last chunk.
398                    // Overflow widths remain tested at aligned caps, where the grid bounds the reads.
399                    if (cap % 64 != 0 && std::any_of(c.widths.begin(), c.widths.end(),
400                            [cap](int32_t w) { return (int64_t) w > cap; })) continue;
401                    hx.prepare(c, rng);
402                    long long nz = 0;
403                    const bool ok = hx.check(c, nz);
404                    nonzero_total += nz;
405                    ++cases;
406                    ++fmt_cases;
407                    if (!ok) { ++failed; ++fmt_failed; }
408                }
409            }
410        }
411        std::printf("[%s] %lld cases, %s (%lld differ)\n", fmt_name(fmt), fmt_cases, fmt_failed ? "FAIL" : "bit-identical",
412                    fmt_failed);
413    }
414    std::printf("qsa_merge_daily_parity: %lld cases, %lld differ, %lld nonzero output values in all -> %s\n", cases, failed,
415                nonzero_total, failed == 0 && nonzero_total > 0 ? "PASS" : "FAIL");
416    if (do_bench) bench(hx, rng);
417    return failed == 0 && nonzero_total > 0 ? 0 : 1;
418}