okami.mom/strata

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

Niko1221Trial2 merge f-0291-pr-amd (82eaeb422): verify.cpp head keeps both: pr-nv2's chunked head (h0/HT, up to 8 columns a launch) and pr-amd's fused q8_1 image (q8_head, image at the chunk's own xq_ offset)62db0bf10

main
61.1 KiB1029 linesraw
1// src/kernels/gr_parity.cpp - P2.S2's test for the gated residual / hyper-connection.
2//
3// `ref/gr.py` opens by listing the details "a prose reading gets wrong", and every one of them is a reading
4// that has the RIGHT SHAPES and produces a PLAUSIBLE number.  So each is computed here the wrong way round and
5// required to differ materially BEFORE the kernel is judged against the right one.  A test that only does the
6// second half passes against either reading:
7//
8//   1. PER-STREAM RMSNorm.  The source comment reads ambiguously; the code reduces over ne[0] = n_embd, i.e.
9//      one RMS per stream.  The rival reading is one RMS over the whole hc*n_embd stack.
10//   2. `/ hc` INSIDE the silu: `lo = silu(proj / hc)`.  Moving it outside is a one-line change that keeps
11//      every shape.
12//   3. SiLU on `lo` and SIGMOID on the gate, a few lines apart in the same function.  Swapping them is the
13//      obvious slip, and both are monotone saturating functions so the magnitudes stay comparable.
14//   4. `mean` over the stream axis, not `sum`.  A factor of hc = 4, which is exactly the kind of error that
15//      looks like a scale problem rather than a structural one.
16//   5. ACTIVATION PRECISION. The historical BF16-rounded CPU contract and the pinned CUDA single-token
17//      FP32-activation contract must be distinguishable. Both are tested against explicit references;
18//      neither is selected merely because the weight is BF16. The scalar fixture isolates xn and lo
19//      rounding from reduction order, and graph replay must preserve the precision chosen at capture.
20//   6. `gr_write`'s `2*sigmoid`, which centres the gate on 1 so a ZERO injection is a plain residual add.
21//      Asserted as a property, not as a value, because that is what the source comment claims.
22#include "strata/kernels/gr.hpp"
23#include "strata/kernels/fused_gr.hpp"
24#include "strata/kernels/native_mmvq.hpp"
25
26#include <cuda_runtime.h>
27
28#include <cmath>
29#include <cstdio>
30#include <algorithm>
31#include <cstdlib>
32#include <cstring>
33#include <random>
34#include <string>
35#include <vector>
36
37namespace {
38
39void check(cudaError_t e, const char* what) {
40    if (e != cudaSuccess) {
41        std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e));
42        std::exit(1);
43    }
44}
45
46/// The same rule the kernel uses, on the host - `ref/quant.py::bf16`.
47float to_bf16(float f) {
48    uint32_t i;
49    std::memcpy(&i, &f, 4);
50    i = (i + ((i >> 16) & 1u) + 0x7FFFu) & 0xFFFF0000u;
51    float o;
52    std::memcpy(&o, &i, 4);
53    return o;
54}
55
56uint16_t bf16_bits(float f) {
57    uint32_t i;
58    std::memcpy(&i, &f, 4);
59    return (uint16_t) (i >> 16);
60}
61
62struct Opts {
63    bool per_stream_norm = true;   ///< false: one RMS over the whole stack (WRONG)
64    bool scale_inside_silu = true; ///< false: silu(proj)/hc instead of silu(proj/hc) (WRONG)
65    bool sigmoid_on_gate = true;   ///< false: silu on the gate and sigmoid on lo (WRONG)
66    bool mean_over_streams = true; ///< false: sum over streams instead of mean (WRONG)
67    bool round_activation = true;  ///< false: pinned CUDA single-token BF16 MMVF contract
68};
69
70/// `ref/gr.py::gr_read`, transcribed with switches for the rival readings.
71void reference(const std::vector<float>& R, const std::vector<float>& w_norm,
72               const std::vector<float>& w_down, const std::vector<float>& w_up,
73               const std::vector<float>& w_inject, float eps, long long n_embd, long long hc, long long hc_lr,
74               const Opts& o, std::vector<float>& mixed, std::vector<float>& inject) {
75    const long long hc_dim = hc * n_embd;
76    std::vector<float> xn((size_t) hc_dim);
77    if (o.per_stream_norm) {
78        for (long long c = 0; c < hc; ++c) {
79            double ms = 0;
80            for (long long d = 0; d < n_embd; ++d) ms += (double) R[(size_t) (c * n_embd + d)] * R[(size_t) (c * n_embd + d)];
81            ms /= (double) n_embd;
82            const float rs = (float) (1.0 / std::sqrt(ms + (double) eps));
83            for (long long d = 0; d < n_embd; ++d) {
84                const size_t i = (size_t) (c * n_embd + d);
85                xn[i] = R[i] * rs * w_norm[i];
86            }
87        }
88    } else {
89        double ms = 0;
90        for (long long i = 0; i < hc_dim; ++i) ms += (double) R[(size_t) i] * R[(size_t) i];
91        ms /= (double) hc_dim;
92        const float rs = (float) (1.0 / std::sqrt(ms + (double) eps));
93        for (long long i = 0; i < hc_dim; ++i) xn[(size_t) i] = R[(size_t) i] * rs * w_norm[(size_t) i];
94    }
95
96    std::vector<float> act((size_t) hc_dim);
97    for (long long i = 0; i < hc_dim; ++i) act[(size_t) i] = o.round_activation ? to_bf16(xn[(size_t) i]) : xn[(size_t) i];
98
99    // lo
100    std::vector<float> lo((size_t) hc_lr);
101    for (long long k = 0; k < hc_lr; ++k) {
102        double a = 0;
103        for (long long i = 0; i < hc_dim; ++i) a += (double) act[(size_t) i] * (double) w_down[(size_t) (k * hc_dim + i)];
104        const float p = (float) a;
105        if (o.sigmoid_on_gate) lo[(size_t) k] = o.scale_inside_silu ? (p / (float) hc) / (1.0f + std::exp(-(p / (float) hc)))
106                                                                  : (p / (1.0f + std::exp(-p))) / (float) hc;
107        else                   lo[(size_t) k] = o.scale_inside_silu ? 1.0f / (1.0f + std::exp(-(p / (float) hc)))
108                                                                    : (1.0f / (1.0f + std::exp(-p))) / (float) hc;
109    }
110    std::vector<float> lq((size_t) hc_lr);
111    for (long long k = 0; k < hc_lr; ++k)
112        lq[(size_t) k] = o.round_activation ? to_bf16(lo[(size_t) k]) : lo[(size_t) k];
113
114    // gate and the gated mean
115    mixed.assign((size_t) n_embd, 0.0f);
116    for (long long d = 0; d < n_embd; ++d) {
117        float m = 0.0f;
118        for (long long c = 0; c < hc; ++c) {
119            const long long i = c * n_embd + d;
120            double a = 0;
121            for (long long k = 0; k < hc_lr; ++k) a += (double) lq[(size_t) k] * (double) w_up[(size_t) (i * hc_lr + k)];
122            const float g = (float) a;
123            const float s = o.sigmoid_on_gate ? 1.0f / (1.0f + std::exp(-g)) : g / (1.0f + std::exp(-g));
124            m += xn[(size_t) i] * s;
125        }
126        mixed[(size_t) d] = o.mean_over_streams ? m / (float) hc : m;
127    }
128
129    inject.assign((size_t) hc, 0.0f);
130    for (long long c = 0; c < hc; ++c) {
131        double a = 0;
132        for (long long i = 0; i < hc_dim; ++i) a += (double) act[(size_t) i] * (double) w_inject[(size_t) (c * hc_dim + i)];
133        inject[(size_t) c] = (float) a;
134    }
135}
136
137/// Normalised L1 difference.  `mag_out` returns the mean |a|, for reporting.
138double rel_diff(const std::vector<float>& a, const std::vector<float>& b, double* mag_out = nullptr) {
139    double d = 0, mag = 0;
140    for (size_t i = 0; i < a.size(); ++i) {
141        d += std::fabs((double) a[i] - (double) b[i]);
142        mag += std::fabs((double) a[i]);
143    }
144    if (mag_out) *mag_out = mag / (double) (a.empty() ? 1 : a.size());
145    return d / (mag > 1e-30 ? mag : 1e-30);
146}
147
148/// Relative error against the magnitude of the TERMS, not of the result.
149///
150/// `R + block_out * w` cancels wherever block_out*w is close to -R, and a plain |want-got|/|want| then
151/// reports the CONDITION NUMBER instead of the arithmetic.  This is the same metric mistake the project has
152/// now made four times: rounds 169 (Q4_K), 189 (RoPE), 194 (shared_expert) and this one.  For a sum, the
153/// denominator is the sum of the term magnitudes.
154double rel_terms(double want, double got, double term_a, double term_b) {
155    const double den = std::fabs(term_a) + std::fabs(term_b);
156    return std::fabs(want - got) / (den > 1e-30 ? den : 1e-30);
157}
158
159const char* activation_mode_name(int mode) {
160    return mode == 2 ? "native pinned GR" : (mode == 1 ? "FP32" : "BF16");
161}
162void select_activation_mode(int mode) {
163    strata::kernels::gr_set_native_mmvf(mode == 2);
164    // In mode 2 the precision-only switch is deliberately false: native MMVF must imply FP32 by itself.
165    strata::kernels::gr_set_fp32_activations(mode == 1);
166}
167
168// A diagonal GR fixture makes activation precision observable without summation-order ambiguity.
169// Two-wide matrices satisfy native MMVF's pair ABI, while each nonzero dot has only one nonzero product.
170// At R=1 and eps=0, xn=gamma exactly; any rounding in xn or lo comes from the selected activation contract.
171int scalar_activation_contract() {
172    using namespace strata::kernels;
173    const GrShapes sh{2, 1, 2};
174    float *d_R = nullptr, *d_norm = nullptr, *d_mixed = nullptr, *d_inject = nullptr;
175    uint16_t* d_weights = nullptr;
176    void* d_scratch = nullptr;
177    check(cudaMalloc(&d_R, 2 * sizeof(float)), "scalar R");
178    check(cudaMalloc(&d_norm, 2 * sizeof(float)), "scalar norm");
179    check(cudaMalloc(&d_mixed, 2 * sizeof(float)), "scalar mixed");
180    check(cudaMalloc(&d_inject, sizeof(float)), "scalar inject");
181    check(cudaMalloc(&d_weights, 10 * sizeof(uint16_t)), "scalar weights");
182    check(cudaMalloc(&d_scratch, gr_workspace_bytes(sh)), "scalar scratch");
183    GrWorkspace ws;
184    gr_workspace_init(sh, d_scratch, ws);
185    const float ones[] = {1.0f, 1.0f};
186    const uint16_t weights[] = {
187        bf16_bits(0.5f), 0, 0, 0,             // down: lo[0]=silu(xn[0]/2), lo[1]=0
188        bf16_bits(1.5f), 0, bf16_bits(1.5f), 0, // both gate rows consume lo[0]
189        bf16_bits(2.0f), 0                     // injection: 2*xn[0]
190    };
191    check(cudaMemcpy(d_R, ones, sizeof(ones), cudaMemcpyHostToDevice), "scalar upload R");
192    check(cudaMemcpy(d_weights, weights, sizeof(weights), cudaMemcpyHostToDevice), "scalar upload weights");
193    // the uploads run on the legacy stream from pageable memory, which the non-blocking `stream` does not wait for
194    check(cudaDeviceSynchronize(), "scalar setup");
195    cudaStream_t stream;
196    check(cudaStreamCreateWithFlags(&stream, cudaStreamNonBlocking), "scalar stream");
197    int bad = 0;
198    for (float gamma : {1.0f, 1.00390625f}) {
199        const float gammas[] = {gamma, gamma};
200        check(cudaMemcpy(d_norm, gammas, sizeof(gammas), cudaMemcpyHostToDevice), "scalar upload norm");
201        check(cudaDeviceSynchronize(), "scalar norm sync");
202        float mixed_by_mode[3][2] = {}, inject_by_mode[3] = {};
203        for (int mode = 0; mode < 3; ++mode) {
204            select_activation_mode(mode);
205            gr_read(d_R, d_norm, d_weights, d_weights + 4, d_weights + 8, 0.0f,
206                    sh, ws, d_mixed, d_inject, stream);
207            check(cudaStreamSynchronize(stream), "scalar warmup");
208            cudaGraph_t graph;
209            cudaGraphExec_t executable;
210            check(cudaStreamBeginCapture(stream, cudaStreamCaptureModeThreadLocal), "scalar capture begin");
211            gr_read(d_R, d_norm, d_weights, d_weights + 4, d_weights + 8, 0.0f,
212                    sh, ws, d_mixed, d_inject, stream);
213            check(cudaStreamEndCapture(stream, &graph), "scalar capture end");
214            check(cudaGraphInstantiate(&executable, graph, nullptr, nullptr, 0), "scalar instantiate");
215            // Changing both host options after capture cannot change the graph's selected kernels.
216            select_activation_mode((mode + 1) % 3);
217            // Warmup results must not make a missing/no-op captured launch pass.
218            // Poison the outputs and intermediate workspace before replay.
219            check(cudaMemsetAsync(d_mixed, 0xa5, 2 * sizeof(float), stream), "scalar poison mixed");
220            check(cudaMemsetAsync(d_inject, 0xa5, sizeof(float), stream), "scalar poison inject");
221            check(cudaMemsetAsync(d_scratch, 0xa5, ws.bytes, stream), "scalar poison workspace");
222            check(cudaGraphLaunch(executable, stream), "scalar replay");
223            check(cudaStreamSynchronize(stream), "scalar replay sync");
224            check(cudaMemcpy(mixed_by_mode[mode], d_mixed, 2 * sizeof(float), cudaMemcpyDeviceToHost), "scalar mixed copy");
225            check(cudaMemcpy(&inject_by_mode[mode], d_inject, sizeof(float), cudaMemcpyDeviceToHost), "scalar inject copy");
226            const float activation = mode ? gamma : to_bf16(gamma);
227            const float projection = activation * 0.5f;
228            const float lo = projection / (1.0f + std::exp(-projection));
229            const float gate = (mode ? lo : to_bf16(lo)) * 1.5f;
230            const float expected_mixed = gamma / (1.0f + std::exp(-gate));
231            const float expected_inject = activation * 2.0f;
232            // Each mode has its own activation contract and bounded scalar-formula
233            // check. Native fast exp/div need not match ordinary FP32 postops bit
234            // for bit: native_gr_postops_parity establishes that arithmetic with
235            // actual pinned CUDA graphs. The nonzero projection/injection here
236            // has only one exactly representable product and remains exact.
237            const bool ok = std::fabs(mixed_by_mode[mode][0] - expected_mixed) <= 2e-7f &&
238                            mixed_by_mode[mode][0] == mixed_by_mode[mode][1] &&
239                            inject_by_mode[mode] == expected_inject;
240            std::printf("  scalar gamma %.8f %s activation/capture %s (mixed %.9f, ref %.9f)\n",
241                        gamma, activation_mode_name(mode), ok ? "pass" : "FAIL",
242                        mixed_by_mode[mode][0], expected_mixed);
243            if (!ok) ++bad;
244            check(cudaGraphExecDestroy(executable), "scalar graph exec destroy");
245            check(cudaGraphDestroy(graph), "scalar graph destroy");
246
247            const float sentinel = -73.25f;
248            check(cudaMemcpy(d_inject, &sentinel, sizeof(float), cudaMemcpyHostToDevice), "scalar sentinel");
249            check(cudaDeviceSynchronize(), "scalar sentinel sync");   // a late sentinel would hide a write to d_inject
250            select_activation_mode(mode);
251            gr_read(d_R, d_norm, d_weights, d_weights + 4, nullptr, 0.0f,
252                    sh, ws, d_mixed, d_inject, stream);
253            check(cudaStreamSynchronize(stream), "scalar final mixer sync");
254            float final_mixed[2] = {}, untouched = 0.0f;
255            check(cudaMemcpy(final_mixed, d_mixed, sizeof(final_mixed), cudaMemcpyDeviceToHost), "scalar final mixed");
256            check(cudaMemcpy(&untouched, d_inject, sizeof(float), cudaMemcpyDeviceToHost), "scalar sentinel copy");
257            const bool final_ok = std::memcmp(final_mixed, mixed_by_mode[mode], sizeof(final_mixed)) == 0 && untouched == sentinel;
258            std::printf("  scalar final mixer %s %s\n", activation_mode_name(mode), final_ok ? "pass" : "FAIL");
259            if (!final_ok) ++bad;
260        }
261        if (std::fabs(mixed_by_mode[1][0] - mixed_by_mode[0][0]) <= 1e-5f ||
262            (gamma != 1.0f && inject_by_mode[0] == inject_by_mode[1])) {
263            std::printf("  scalar precision fixture is not observable\n");
264            ++bad;
265        }
266        if (inject_by_mode[1] != inject_by_mode[2]) {
267            std::printf("  native MMVF changed the exact scalar FP32 injection projection\n");
268            ++bad;
269        }
270    }
271    select_activation_mode(0);
272    check(cudaStreamDestroy(stream), "scalar stream destroy");
273    cudaFree(d_R); cudaFree(d_norm); cudaFree(d_mixed); cudaFree(d_inject);
274    cudaFree(d_weights); cudaFree(d_scratch);
275    return bad;
276}
277
278int fused_multi_lds_parity(const float* d_norm, const uint16_t* d_down, const uint16_t* d_up,
279                           const uint16_t* d_inject, float eps) {
280    using namespace strata::kernels;
281    constexpr int N = 2560, HC = 4, LR = 320, D = N * HC, T = kFusedGrMaxT;
282    std::mt19937 rng(0x6f8a);
283    std::normal_distribution<float> normal(0.0f, 0.3f);
284    std::vector<float> r((size_t) T * D), bo((size_t) T * N), inj((size_t) T * HC);
285    for (auto& x : r) x = normal(rng);
286    for (auto& x : bo) x = normal(rng);
287    for (auto& x : inj) x = normal(rng);
288
289    float *d_r = nullptr, *d_r_out = nullptr, *d_bo = nullptr, *d_inj = nullptr;
290    float *d_lo = nullptr, *d_rs = nullptr, *d_inj_out = nullptr, *d_mixed = nullptr, *d_xn = nullptr;
291    check(cudaMalloc(&d_r, r.size() * sizeof(float)), "multi R");
292    check(cudaMalloc(&d_r_out, r.size() * sizeof(float)), "multi R_out");
293    check(cudaMalloc(&d_bo, bo.size() * sizeof(float)), "multi bo");
294    check(cudaMalloc(&d_inj, inj.size() * sizeof(float)), "multi inj");
295    check(cudaMalloc(&d_lo, (size_t) T * LR * sizeof(float)), "multi lo");
296    check(cudaMalloc(&d_rs, (size_t) T * HC * sizeof(float)), "multi rs");
297    check(cudaMalloc(&d_inj_out, (size_t) T * HC * sizeof(float)), "multi injection");
298    check(cudaMalloc(&d_mixed, (size_t) T * N * sizeof(float)), "multi mixed");
299    check(cudaMalloc(&d_xn, (size_t) T * D * sizeof(float)), "multi xn");
300    check(cudaMemcpy(d_r, r.data(), r.size() * sizeof(float), cudaMemcpyHostToDevice), "multi copy R");
301    check(cudaMemcpy(d_bo, bo.data(), bo.size() * sizeof(float), cudaMemcpyHostToDevice), "multi copy bo");
302    check(cudaMemcpy(d_inj, inj.data(), inj.size() * sizeof(float), cudaMemcpyHostToDevice), "multi copy inj");
303
304    std::vector<FusedGrArgs> args(T);
305    for (int t = 0; t < T; ++t) {
306        auto& a = args[t];
307        a.R = d_r + (size_t) t * D;
308        a.R_out = d_r_out + (size_t) t * D;
309        a.apply = true;
310        a.bo_prev = d_bo + (size_t) t * N;
311        a.inj_prev = d_inj + (size_t) t * HC;
312        a.w_norm = d_norm;
313        a.w_down = d_down;
314        a.w_up = d_up;
315        a.w_inject = d_inject;
316        a.eps = eps;
317        a.lo = d_lo + (size_t) t * LR;
318        a.rs = d_rs + (size_t) t * HC;
319        a.inject_out = d_inj_out + (size_t) t * HC;
320        a.mixed = d_mixed + (size_t) t * N;
321    }
322
323    struct Snapshot {
324        std::vector<float> r_out, lo, rs, inject, mixed;
325    };
326    auto snapshot = [&]() {
327        Snapshot s;
328        s.r_out.resize((size_t) T * D);
329        s.lo.resize((size_t) T * LR);
330        s.rs.resize((size_t) T * HC);
331        s.inject.resize((size_t) T * HC);
332        s.mixed.resize((size_t) T * N);
333        check(cudaMemcpy(s.r_out.data(), d_r_out, s.r_out.size() * sizeof(float), cudaMemcpyDeviceToHost), "multi read R_out");
334        check(cudaMemcpy(s.lo.data(), d_lo, s.lo.size() * sizeof(float), cudaMemcpyDeviceToHost), "multi read lo");
335        check(cudaMemcpy(s.rs.data(), d_rs, s.rs.size() * sizeof(float), cudaMemcpyDeviceToHost), "multi read rs");
336        check(cudaMemcpy(s.inject.data(), d_inj_out, s.inject.size() * sizeof(float), cudaMemcpyDeviceToHost), "multi read inject");
337        check(cudaMemcpy(s.mixed.data(), d_mixed, s.mixed.size() * sizeof(float), cudaMemcpyDeviceToHost), "multi read mixed");
338        return s;
339    };
340    // the split read (STRATA_GR_V3=1) sums in another order than the single-token kernel: equal within float
341    // rounding, not to the bit, so it is compared with a relative tolerance; the default kernels bit for bit
342    static const bool v3 = [] { const char* v = std::getenv("STRATA_GR_V3"); return v != nullptr && std::atoi(v) != 0; }();
343    auto close = [](const std::vector<float>& x, const std::vector<float>& y) {
344        double worst = 0.0, mag = 1e-30;
345        for (size_t i = 0; i < x.size(); ++i) {
346            worst = std::max(worst, (double) std::fabs(x[i] - y[i]));
347            mag = std::max(mag, (double) std::fabs(y[i]));
348        }
349        if (worst > 2e-6 * mag)
350            std::printf("    tolerance: worst %.3e of max |ref| %.3e (rel %.3e), n %zu\n", worst, mag, worst / mag, x.size());
351        return worst <= 2e-6 * mag;
352    };
353    auto same = [&](const Snapshot& a, const Snapshot& b) {
354        if (v3)   // `lo` is the default kernels' workspace between down and up; the split read keeps it in shared memory
355            return close(a.r_out, b.r_out) && close(a.rs, b.rs) && close(a.inject, b.inject) && close(a.mixed, b.mixed);
356        return std::memcmp(a.r_out.data(), b.r_out.data(), a.r_out.size() * sizeof(float)) == 0 &&
357               std::memcmp(a.lo.data(), b.lo.data(), a.lo.size() * sizeof(float)) == 0 &&
358               std::memcmp(a.rs.data(), b.rs.data(), a.rs.size() * sizeof(float)) == 0 &&
359               std::memcmp(a.inject.data(), b.inject.data(), a.inject.size() * sizeof(float)) == 0 &&
360               std::memcmp(a.mixed.data(), b.mixed.data(), a.mixed.size() * sizeof(float)) == 0;
361    };
362
363    cudaStream_t stream = nullptr;
364    check(cudaStreamCreateWithFlags(&stream, cudaStreamNonBlocking), "multi stream");
365    // the uploads above (and the caller's weights) run on the legacy stream, which the non-blocking `stream` does not wait for
366    check(cudaDeviceSynchronize(), "multi setup");
367    // Max T forces the HIP kernel's full dynamic-LDS request: 8 * 1280 * sizeof(float) = 40 KiB.
368    fused_gr_read_multi(args.data(), T, d_xn, stream);
369    check(cudaStreamSynchronize(stream), "multi max-T sync");
370    const Snapshot multi = snapshot();
371    for (int t = 0; t < T; ++t) fused_gr_read(args[t], stream);
372    check(cudaStreamSynchronize(stream), "single reference sync");
373    const Snapshot single = snapshot();
374    int bad = 0;
375    if (!same(multi, single)) {
376        std::printf("  fused GR multi max-T differs from single-token calls\n");
377        ++bad;
378    }
379
380    cudaGraph_t graph = nullptr;
381    cudaGraphExec_t graph_exec = nullptr;
382    check(cudaStreamBeginCapture(stream, cudaStreamCaptureModeThreadLocal), "multi graph begin");
383    fused_gr_read_multi(args.data(), T, d_xn, stream);
384    check(cudaStreamEndCapture(stream, &graph), "multi graph end");
385    check(cudaGraphInstantiate(&graph_exec, graph, nullptr, nullptr, 0), "multi graph instantiate");
386    check(cudaGraphLaunch(graph_exec, stream), "multi graph initial replay");
387    check(cudaStreamSynchronize(stream), "multi graph initial sync");
388    const Snapshot captured = snapshot();
389    if (!same(multi, captured)) {
390        std::printf("  fused GR multi captured graph differs from direct max-T call\n");
391        ++bad;
392    }
393
394    // Reuse the same captured pointers with new payloads; then independently run the single-token path again.
395    for (size_t i = 0; i < r.size(); ++i) r[i] = -0.7f * r[i] + 0.001f * (float) (i % 17);
396    for (size_t i = 0; i < bo.size(); ++i) bo[i] = -0.4f * bo[i] + 0.02f;
397    for (size_t i = 0; i < inj.size(); ++i) inj[i] += 0.3f;
398    check(cudaMemcpyAsync(d_r, r.data(), r.size() * sizeof(float), cudaMemcpyHostToDevice, stream), "multi replay R");
399    check(cudaMemcpyAsync(d_bo, bo.data(), bo.size() * sizeof(float), cudaMemcpyHostToDevice, stream), "multi replay bo");
400    check(cudaMemcpyAsync(d_inj, inj.data(), inj.size() * sizeof(float), cudaMemcpyHostToDevice, stream), "multi replay inj");
401    check(cudaGraphLaunch(graph_exec, stream), "multi graph changed replay");
402    check(cudaStreamSynchronize(stream), "multi graph changed sync");
403    const Snapshot replay = snapshot();
404    if (std::memcmp(multi.mixed.data(), replay.mixed.data(), multi.mixed.size() * sizeof(float)) == 0) {
405        std::printf("  fused GR graph replay ignored changed inputs\n");
406        ++bad;
407    }
408    for (int t = 0; t < T; ++t) fused_gr_read(args[t], stream);
409    check(cudaStreamSynchronize(stream), "changed single reference sync");
410    if (!same(replay, snapshot())) {
411        std::printf("  fused GR changed graph replay differs from single-token calls\n");
412        ++bad;
413    }
414
415
416    // S26 STRATA_QFUSE: the read's own q8_1 image of `mixed` must be the bytes native_quantize_q8_1 writes from it -
417    // for every T (1..8), directly and through a captured graph replayed twice (the group counters must reset)
418    {
419        uint8_t *d_q = nullptr, *d_ref = nullptr;
420        unsigned* d_cnt = nullptr;
421        const size_t qbytes = (size_t) T * (N / 32) * 36;
422        check(cudaMalloc(&d_q, qbytes), "qfuse q8");
423        check(cudaMalloc(&d_ref, qbytes), "qfuse ref");
424        check(cudaMalloc(&d_cnt, (N / 32) * sizeof(unsigned)), "qfuse counters");
425        check(cudaMemset(d_cnt, 0, (N / 32) * sizeof(unsigned)), "qfuse counters zero");
426        int qbad = 0;
427        std::vector<uint8_t> hq(qbytes), hr(qbytes);
428        for (int tt = 1; tt <= T && !qbad; ++tt) {
429            std::vector<FusedGrArgs> qa(args.begin(), args.begin() + tt);
430            for (int t = 0; t < tt; ++t) { qa[t].q8_mixed = d_q + (size_t) t * (N / 32) * 36; qa[t].q8_cnt = d_cnt; }
431            for (int rep = 0; rep < 3 && !qbad; ++rep) {
432                check(cudaMemsetAsync(d_q, 0x5a, qbytes, stream), "qfuse poison");
433                bool wrote = false;
434                cudaGraph_t qg = nullptr;
435                cudaGraphExec_t qx = nullptr;
436                if (rep == 0) {
437                    wrote = fused_gr_read_multi(qa.data(), tt, d_xn, stream);
438                } else {   // a captured read, replayed (twice: rep 1 and 2 use fresh captures, each replayed twice)
439                    check(cudaStreamBeginCapture(stream, cudaStreamCaptureModeThreadLocal), "qfuse begin");
440                    wrote = fused_gr_read_multi(qa.data(), tt, d_xn, stream);
441                    check(cudaStreamEndCapture(stream, &qg), "qfuse end");
442                    check(cudaGraphInstantiate(&qx, qg, nullptr, nullptr, 0), "qfuse instantiate");
443                    check(cudaGraphLaunch(qx, stream), "qfuse replay 1");
444                    check(cudaMemsetAsync(d_q, 0x5a, qbytes, stream), "qfuse poison 2");
445                    check(cudaGraphLaunch(qx, stream), "qfuse replay 2");
446                }
447                strata::kernels::native_quantize_q8_1(d_mixed, d_ref, N, tt, stream);
448                check(cudaStreamSynchronize(stream), "qfuse sync");
449                if (qx) { cudaGraphExecDestroy(qx); cudaGraphDestroy(qg); }
450                if (v3) { std::printf("  QFUSE: the v3 read writes no q8_1 (%s)\n", wrote ? "WRONG: it says it did" : "ok"); qbad += wrote; break; }
451                check(cudaMemcpy(hq.data(), d_q, (size_t) tt * (N / 32) * 36, cudaMemcpyDeviceToHost), "qfuse read");
452                check(cudaMemcpy(hr.data(), d_ref, (size_t) tt * (N / 32) * 36, cudaMemcpyDeviceToHost), "qfuse ref read");
453                if (!wrote || std::memcmp(hq.data(), hr.data(), (size_t) tt * (N / 32) * 36) != 0) {
454                    std::printf("  QFUSE: T=%d rep %d: %s\n", tt, rep, wrote ? "q8_1 bytes differ" : "not written");
455                    ++qbad;
456                }
457            }
458        }
459        std::printf("  fused GR read + q8_1 (STRATA_QFUSE), T 1..8, direct and graph replays: %s\n", qbad ? "FAIL" : "pass");
460        bad += qbad;
461#if (defined(STRATA_USE_HIP) || defined(__HIP_PLATFORM_AMD__)) && !defined(STRATA_HIP_GFX906)
462        // Counter-free q8_mixed path (q8_cnt == nullptr, used by MTP when STRATA_QFUSE_HC_LOCAL=1 on wave32 HIP where
463        // STRATA_GR_FAST_BUILD == 0): must return true and write identical q8_1 bytes across T=1..8 and graph replays,
464        // and must return false without writing when STRATA_QFUSE_HC_LOCAL=0 and q8_cnt == nullptr.
465        if (!v3) {
466            int cf_bad = 0;
467            const char* prev_loc = std::getenv("STRATA_QFUSE_HC_LOCAL");
468            const std::string saved_loc = prev_loc ? prev_loc : "";
469#if defined(_WIN32)
470            _putenv_s("STRATA_QFUSE_HC_LOCAL", "1");
471#else
472            setenv("STRATA_QFUSE_HC_LOCAL", "1", 1);
473#endif
474            for (int tt = 1; tt <= T && !cf_bad; ++tt) {
475                std::vector<FusedGrArgs> qa(args.begin(), args.begin() + tt);
476                for (int t = 0; t < tt; ++t) { qa[t].q8_mixed = d_q + (size_t) t * (N / 32) * 36; qa[t].q8_cnt = nullptr; }
477                for (int rep = 0; rep < 2 && !cf_bad; ++rep) {
478                    check(cudaMemcpyAsync(d_r, r.data(), r.size() * sizeof(float), cudaMemcpyHostToDevice, stream), "cf R");
479                    check(cudaMemsetAsync(d_q, 0xff, qbytes, stream), "cf poison");
480                    bool wrote = false;
481                    cudaGraph_t qg = nullptr;
482                    cudaGraphExec_t qx = nullptr;
483                    if (rep == 0) {
484                        wrote = fused_gr_read_multi(qa.data(), tt, d_xn, stream);
485                    } else {
486                        check(cudaStreamBeginCapture(stream, cudaStreamCaptureModeThreadLocal), "cf begin");
487                        wrote = fused_gr_read_multi(qa.data(), tt, d_xn, stream);
488                        check(cudaStreamEndCapture(stream, &qg), "cf end");
489                        check(cudaGraphInstantiate(&qx, qg, nullptr, nullptr, 0), "cf inst");
490                        check(cudaGraphLaunch(qx, stream), "cf replay 1");
491                        check(cudaMemsetAsync(d_q, 0x5a, qbytes, stream), "cf poison 2");
492                        check(cudaMemcpyAsync(d_r, r.data(), r.size() * sizeof(float), cudaMemcpyHostToDevice, stream), "cf R2");
493                        check(cudaGraphLaunch(qx, stream), "cf replay 2");
494                    }
495                    strata::kernels::native_quantize_q8_1(d_mixed, d_ref, N, tt, stream);
496                    check(cudaStreamSynchronize(stream), "cf sync");
497                    if (qx) { cudaGraphExecDestroy(qx); cudaGraphDestroy(qg); }
498                    check(cudaMemcpy(hq.data(), d_q, (size_t) tt * (N / 32) * 36, cudaMemcpyDeviceToHost), "cf read");
499                    check(cudaMemcpy(hr.data(), d_ref, (size_t) tt * (N / 32) * 36, cudaMemcpyDeviceToHost), "cf ref");
500                    if (!wrote || std::memcmp(hq.data(), hr.data(), (size_t) tt * (N / 32) * 36) != 0) ++cf_bad;
501                }
502            }
503#if defined(_WIN32)
504            _putenv_s("STRATA_QFUSE_HC_LOCAL", "0");
505#else
506            setenv("STRATA_QFUSE_HC_LOCAL", "0", 1);
507#endif
508            {
509                std::vector<FusedGrArgs> qa(args.begin(), args.begin() + 2);
510                for (int t = 0; t < 2; ++t) { qa[t].q8_mixed = d_q + (size_t) t * (N / 32) * 36; qa[t].q8_cnt = nullptr; }
511                check(cudaMemsetAsync(d_q, 0xa5, qbytes, stream), "cf off poison");
512                const bool wrote = fused_gr_read_multi(qa.data(), 2, d_xn, stream);
513                check(cudaStreamSynchronize(stream), "cf off sync");
514                check(cudaMemcpy(hq.data(), d_q, (size_t) 2 * (N / 32) * 36, cudaMemcpyDeviceToHost), "cf off read");
515                bool untouched = true;
516                for (size_t i = 0; i < (size_t) 2 * (N / 32) * 36; ++i) untouched = untouched && (hq[i] == 0xa5);
517                if (wrote || !untouched) ++cf_bad;
518            }
519#if defined(_WIN32)
520            _putenv_s("STRATA_QFUSE_HC_LOCAL", prev_loc ? saved_loc.c_str() : "");
521#else
522            if (prev_loc) setenv("STRATA_QFUSE_HC_LOCAL", saved_loc.c_str(), 1);
523            else unsetenv("STRATA_QFUSE_HC_LOCAL");
524#endif
525            std::printf("  fused GR counter-free q8_1 (q8_cnt == nullptr), T 1..8, direct/graph + LOCAL=0 guard: %s\n",
526                        cf_bad ? "FAIL" : "pass");
527            bad += cf_bad;
528        }
529#endif
530        cudaFree(d_q); cudaFree(d_ref); cudaFree(d_cnt);
531    }
532
533    // #3948: STRATA_QFUSE in a verify window of TWO GROUPS (verify.cpp gr_read_group with G = 2): the window's tokens are
534    // read in two calls one after the other, the same group counters, each call with its own tokens' destinations - the
535    // attention half's xq_ is indexed from the group's first token, the expert half's nat_xq_ by the window's token.
536    // Fresh random inputs every repetition, 200 repetitions for each T = 2..8 (a race that fires one launch in a hundred
537    // shows), direct and as a graph replay. After every repetition: both groups' q8_1 bytes equal what
538    // native_quantize_q8_1 makes of `mixed`, nothing outside the written ranges changed, and the counters are back at zero.
539    if (!v3) {
540        // (STRATA_GRP_REPS=N more repetitions, STRATA_GRP_KEEP_GOING=1 counts every failure instead of stopping at the first: to measure a rare one)
541        const int REPS = std::getenv("STRATA_GRP_REPS") ? std::max(1, std::atoi(std::getenv("STRATA_GRP_REPS"))) : 200;
542        const bool keep_going = std::getenv("STRATA_GRP_KEEP_GOING") != nullptr;
543        const size_t B = (size_t) (N / 32) * 36;   // one token's q8_1 image
544        uint8_t *d_qa = nullptr, *d_qb = nullptr, *d_qabs = nullptr, *d_ref2 = nullptr;
545        unsigned* d_cnt2 = nullptr;
546        check(cudaMalloc(&d_qa, (size_t) T * B), "qfuse2 qa");
547        check(cudaMalloc(&d_qb, (size_t) T * B), "qfuse2 qb");
548        check(cudaMalloc(&d_qabs, (size_t) T * B), "qfuse2 qabs");
549        check(cudaMalloc(&d_ref2, (size_t) T * B), "qfuse2 ref");
550        check(cudaMalloc(&d_cnt2, (N / 32) * sizeof(unsigned)), "qfuse2 counters");
551        check(cudaMemset(d_cnt2, 0, (N / 32) * sizeof(unsigned)), "qfuse2 counters zero");
552        std::mt19937 prng(0x3948u);
553        std::normal_distribution<float> pn(0.0f, 0.3f);
554        std::vector<uint8_t> g_all((size_t) T * B), g_ref((size_t) T * B), g_a((size_t) T * B), g_b((size_t) T * B);
555        std::vector<unsigned> h_cnt(N / 32);
556        int g2bad = 0;
557        long runs = 0;
558        for (int tt = 2; tt <= T && (!g2bad || keep_going); ++tt) {
559            const int h = (tt + 1) / 2;   // verify.cpp: tb_/te_ = {0, (T + 1) / 2}, {(T + 1) / 2, T}
560            std::vector<FusedGrArgs> rel1(args.begin(), args.begin() + h), rel2(args.begin() + h, args.begin() + tt);
561            std::vector<FusedGrArgs> abs1 = rel1, abs2 = rel2;
562            for (int t = 0; t < h; ++t) {
563                rel1[t].q8_mixed = d_qa + (size_t) t * B;     rel1[t].q8_cnt = d_cnt2;
564                abs1[t].q8_mixed = d_qabs + (size_t) t * B;   abs1[t].q8_cnt = d_cnt2;
565            }
566            for (int t = h; t < tt; ++t) {
567                rel2[t - h].q8_mixed = d_qb + (size_t) (t - h) * B;   rel2[t - h].q8_cnt = d_cnt2;
568                abs2[t - h].q8_mixed = d_qabs + (size_t) t * B;       abs2[t - h].q8_cnt = d_cnt2;
569            }
570            cudaGraph_t gg = nullptr;
571            cudaGraphExec_t gx = nullptr;
572            check(cudaStreamBeginCapture(stream, cudaStreamCaptureModeThreadLocal), "qfuse2 begin");
573            const bool w1 = fused_gr_read_multi(rel1.data(), h, d_xn, stream);
574            const bool w2 = fused_gr_read_multi(rel2.data(), tt - h, d_xn + (size_t) h * D, stream);
575            check(cudaStreamEndCapture(stream, &gg), "qfuse2 end");
576            check(cudaGraphInstantiate(&gx, gg, nullptr, nullptr, 0), "qfuse2 instantiate");
577            if (!w1 || !w2) { std::printf("  QFUSE two groups: T=%d: a group did not write its q8_1\n", tt); ++g2bad; }
578            for (int rep = 0; rep < REPS && (!g2bad || keep_going); ++rep) {
579                for (auto& x : r) x = pn(prng);
580                for (auto& x : bo) x = pn(prng);
581                for (auto& x : inj) x = pn(prng);
582                check(cudaMemcpy(d_r, r.data(), r.size() * sizeof(float), cudaMemcpyHostToDevice), "qfuse2 R");
583                check(cudaMemcpy(d_bo, bo.data(), bo.size() * sizeof(float), cudaMemcpyHostToDevice), "qfuse2 bo");
584                check(cudaMemcpy(d_inj, inj.data(), inj.size() * sizeof(float), cudaMemcpyHostToDevice), "qfuse2 inj");
585                check(cudaMemsetAsync(d_qa, 0x5a, (size_t) T * B, stream), "qfuse2 poison a");
586                check(cudaMemsetAsync(d_qb, 0x5a, (size_t) T * B, stream), "qfuse2 poison b");
587                check(cudaMemsetAsync(d_qabs, 0x5a, (size_t) T * B, stream), "qfuse2 poison abs");
588                const int mode = rep % 3;   // 0: group-relative, direct; 1: window-indexed, direct; 2: group-relative, graph replay
589                if (mode == 0) {
590                    fused_gr_read_multi(rel1.data(), h, d_xn, stream);
591                    fused_gr_read_multi(rel2.data(), tt - h, d_xn + (size_t) h * D, stream);
592                } else if (mode == 1) {
593                    fused_gr_read_multi(abs1.data(), h, d_xn, stream);
594                    fused_gr_read_multi(abs2.data(), tt - h, d_xn + (size_t) h * D, stream);
595                } else {
596                    check(cudaGraphLaunch(gx, stream), "qfuse2 replay");
597                }
598                strata::kernels::native_quantize_q8_1(d_mixed, d_ref2, N, tt, stream);
599                check(cudaStreamSynchronize(stream), "qfuse2 sync");
600                ++runs;
601                check(cudaMemcpy(g_ref.data(), d_ref2, (size_t) tt * B, cudaMemcpyDeviceToHost), "qfuse2 read ref");
602                check(cudaMemcpy(h_cnt.data(), d_cnt2, h_cnt.size() * sizeof(unsigned), cudaMemcpyDeviceToHost), "qfuse2 read counters");
603                for (size_t i = 0; i < h_cnt.size(); ++i)
604                    if (h_cnt[i] != 0) {
605                        std::printf("  QFUSE two groups: T=%d rep %d: counter %zu left at %u\n", tt, rep, i, h_cnt[i]);
606                        ++g2bad;
607                        break;
608                    }
609                if (mode == 1) {
610                    check(cudaMemcpy(g_all.data(), d_qabs, (size_t) T * B, cudaMemcpyDeviceToHost), "qfuse2 read abs");
611                    if (std::memcmp(g_all.data(), g_ref.data(), (size_t) tt * B) != 0) {
612                        for (int t = 0; t < tt; ++t)
613                            if (std::memcmp(g_all.data() + (size_t) t * B, g_ref.data() + (size_t) t * B, B) != 0) {
614                                std::printf("  QFUSE two groups (window-indexed): T=%d rep %d: token %d (group %d) differs\n", tt, rep, t, t < h ? 0 : 1);
615                                int nd = 0;   // where: block = 32 columns, bytes 0-3 the (scale, sum) pair, 4-35 the codes
616                                for (size_t o = 0; o < B && nd < 6; ++o)
617                                    if (g_all[(size_t) t * B + o] != g_ref[(size_t) t * B + o]) {
618                                        std::printf("    block %zu byte %zu (%s): got 0x%02x, separate quantise 0x%02x\n", o / 36, o % 36,
619                                                    o % 36 < 4 ? "scale/sum" : "code", g_all[(size_t) t * B + o], g_ref[(size_t) t * B + o]);
620                                        ++nd;
621                                    }
622                                break;
623                            }
624                        ++g2bad;
625                    }
626                    for (size_t i = (size_t) tt * B; i < (size_t) T * B; ++i)
627                        if (g_all[i] != 0x5a) { std::printf("  QFUSE two groups: T=%d rep %d: wrote past the window at byte %zu\n", tt, rep, i); ++g2bad; break; }
628                } else {
629                    check(cudaMemcpy(g_a.data(), d_qa, (size_t) T * B, cudaMemcpyDeviceToHost), "qfuse2 read a");
630                    check(cudaMemcpy(g_b.data(), d_qb, (size_t) T * B, cudaMemcpyDeviceToHost), "qfuse2 read b");
631                    if (std::memcmp(g_a.data(), g_ref.data(), (size_t) h * B) != 0) {
632                        std::printf("  QFUSE two groups (group-relative, %s): T=%d rep %d: group 0 differs\n", mode == 2 ? "graph" : "direct", tt, rep);
633                        for (size_t o = 0, nd = 0; o < (size_t) h * B && nd < 6; ++o)
634                            if (g_a[o] != g_ref[o]) {
635                                std::printf("    token %zu block %zu byte %zu (%s): got 0x%02x, separate quantise 0x%02x\n", o / B, (o % B) / 36,
636                                            o % 36, o % 36 < 4 ? "scale/sum" : "code", g_a[o], g_ref[o]);
637                                ++nd;
638                            }
639                        ++g2bad;
640                    }
641                    if (std::memcmp(g_b.data(), g_ref.data() + (size_t) h * B, (size_t) (tt - h) * B) != 0) {
642                        std::printf("  QFUSE two groups (group-relative, %s): T=%d rep %d: group 1 differs\n", mode == 2 ? "graph" : "direct", tt, rep);
643                        ++g2bad;
644                    }
645                    for (size_t i = (size_t) h * B; i < (size_t) T * B; ++i)
646                        if (g_a[i] != 0x5a) { std::printf("  QFUSE two groups: T=%d rep %d: group 0 wrote past its tokens at byte %zu\n", tt, rep, i); ++g2bad; break; }
647                    for (size_t i = (size_t) (tt - h) * B; i < (size_t) T * B; ++i)
648                        if (g_b[i] != 0x5a) { std::printf("  QFUSE two groups: T=%d rep %d: group 1 wrote past its tokens at byte %zu\n", tt, rep, i); ++g2bad; break; }
649                }
650            }
651            cudaGraphExecDestroy(gx);
652            cudaGraphDestroy(gg);
653        }
654        // the inputs the rest of the test (and its caller) expect again
655        check(cudaDeviceSynchronize(), "qfuse2 done");
656        std::printf("  fused GR read + q8_1 (STRATA_QFUSE), a window of two groups, T 2..8, %ld runs (%d random inputs each T), "
657                    "group-relative and window-indexed, direct and graph: %s\n", runs, REPS, g2bad ? "FAIL" : "pass");
658        bad += g2bad;
659        cudaFree(d_qa); cudaFree(d_qb); cudaFree(d_qabs); cudaFree(d_ref2); cudaFree(d_cnt2);
660    }
661    std::printf("  fused GR multi max-T=8 LDS launch and changing graph replay %s\n",
662                bad == 0 ? "pass" : "FAIL");
663    check(cudaGraphExecDestroy(graph_exec), "multi graph exec destroy");
664    check(cudaGraphDestroy(graph), "multi graph destroy");
665    check(cudaStreamDestroy(stream), "multi stream destroy");
666    check(cudaFree(d_xn), "free multi xn");
667    check(cudaFree(d_mixed), "free multi mixed");
668    check(cudaFree(d_inj_out), "free multi injection");
669    check(cudaFree(d_rs), "free multi rs");
670    check(cudaFree(d_lo), "free multi lo");
671    check(cudaFree(d_inj), "free multi inj");
672    check(cudaFree(d_bo), "free multi bo");
673    check(cudaFree(d_r_out), "free multi R_out");
674    check(cudaFree(d_r), "free multi R");
675    return bad;
676}
677
678}  // namespace
679
680int main(int argc, char** argv) {
681    // this test compares the default kernels bit for bit; the split read (a default on a 12.0 card since 0.2.7) is STRATA_GR_V3=1 below
682#if defined(_WIN32)
683    if (std::getenv("STRATA_GR_V3") == nullptr) _putenv_s("STRATA_GR_V3", "0");
684#else
685    if (std::getenv("STRATA_GR_V3") == nullptr) setenv("STRATA_GR_V3", "0", 1);
686#endif
687    bool selftest = false;
688    for (int i = 1; i < argc; ++i) {
689        if (std::string(argv[i]) == "--selftest") selftest = true;
690        else { std::fprintf(stderr, "usage: gr_parity [--selftest]\n"); return 2; }
691    }
692
693    const long long n_embd = 256, hc = 4, hc_lr = 32;
694    const long long hc_dim = hc * n_embd;
695    const float eps = 1e-6f;
696    std::mt19937 rng(1234);
697    std::normal_distribution<float> gauss(0.0f, 1.0f);
698
699    // Weights are BF16-VALUED f32, which is what the pack holds for a BF16 source type.  Generating plain f32
700    // weights would make the kernel (which stores 16 bits) differ from the reference by the rounding itself,
701    // and the test would then be measuring the fixture.
702    auto bf16_weight = [&](size_t n, float sigma) {
703        std::vector<float> v(n);
704        for (auto& x : v) x = to_bf16(gauss(rng) * sigma);
705        return v;
706    };
707    std::vector<float> R((size_t) hc_dim);
708    for (auto& x : R) x = gauss(rng);
709    // STREAM SCALES 1, 4, 16, 64.  Without them trap 1 is only ~5% observable, because four streams of i.i.d.
710    // normal noise have nearly the same RMS by accident - so a whole-stack RMS and a per-stream RMS agree to
711    // within the noise, and the fixture would be asserting a distinction it cannot see.  Giving the streams
712    // different magnitudes is what makes "per-stream" a claim with content.
713    for (long long c = 0; c < hc; ++c)
714        for (long long d = 0; d < n_embd; ++d) R[(size_t) (c * n_embd + d)] *= std::pow(4.0f, (float) c);
715    // gamma stored as (1 + w), so values near 1 - a reader expecting a plain scale is the one this catches
716    std::vector<float> w_norm((size_t) hc_dim);
717    for (auto& x : w_norm) x = 1.0f + 0.1f * gauss(rng);
718    std::vector<float> w_down = bf16_weight((size_t) (hc_lr * hc_dim), 0.2f);
719    std::vector<float> w_up = bf16_weight((size_t) (hc_dim * hc_lr), 0.2f);
720    std::vector<float> w_inject = bf16_weight((size_t) (hc * hc_dim), 0.05f);
721
722    // NO PERMUTATION: the kernel takes both matrices exactly as the manifest (and `ref/gr.py`) store them.
723    // `w_down` is (hc_lr, hc_dim) row-major and `w_up` is (hc_dim, hc_lr) row-major, so the bit-copy below is
724    // the whole conversion.  An earlier version of this kernel wanted both TRANSPOSED - the test built them
725    // that way and asserted the orientation observable - and that is gone because the warp-per-row mapping
726    // makes it unnecessary.  What replaces it is the general orientation trap further down: a weight array
727    // read with the wrong index expression must still produce a visibly different answer.
728    std::vector<uint16_t> q_down(w_down.size()), q_up(w_up.size()), q_inject(w_inject.size());
729    for (size_t i = 0; i < w_down.size(); ++i) q_down[i] = bf16_bits(w_down[i]);
730    for (size_t i = 0; i < w_up.size(); ++i) q_up[i] = bf16_bits(w_up[i]);
731    for (size_t i = 0; i < w_inject.size(); ++i) q_inject[i] = bf16_bits(w_inject[i]);
732
733    // ---- device side
734    float *d_R = nullptr, *d_norm = nullptr, *d_mixed = nullptr, *d_inject = nullptr;
735    uint16_t *d_down = nullptr, *d_up = nullptr, *d_inj = nullptr;
736    check(cudaMalloc(&d_R, R.size() * sizeof(float)), "m R");
737    check(cudaMalloc(&d_norm, w_norm.size() * sizeof(float)), "m norm");
738    check(cudaMalloc(&d_down, q_down.size() * sizeof(uint16_t)), "m down");
739    check(cudaMalloc(&d_up, q_up.size() * sizeof(uint16_t)), "m up");
740    check(cudaMalloc(&d_inj, q_inject.size() * sizeof(uint16_t)), "m inj");
741    check(cudaMalloc(&d_mixed, (size_t) n_embd * sizeof(float)), "m mixed");
742    check(cudaMalloc(&d_inject, (size_t) hc * sizeof(float)), "m inject");
743    check(cudaMemcpy(d_R, R.data(), R.size() * sizeof(float), cudaMemcpyHostToDevice), "c R");
744    check(cudaMemcpy(d_norm, w_norm.data(), w_norm.size() * sizeof(float), cudaMemcpyHostToDevice), "c norm");
745    check(cudaMemcpy(d_down, q_down.data(), q_down.size() * sizeof(uint16_t), cudaMemcpyHostToDevice), "c down");
746    check(cudaMemcpy(d_up, q_up.data(), q_up.size() * sizeof(uint16_t), cudaMemcpyHostToDevice), "c up");
747    check(cudaMemcpy(d_inj, q_inject.data(), q_inject.size() * sizeof(uint16_t), cudaMemcpyHostToDevice), "c inj");
748
749    const strata::kernels::GrShapes sh{n_embd, hc, hc_lr};
750    // DEVICE memory: the workspace is written by the kernel.
751    void* d_ws_raw = nullptr;
752    check(cudaMalloc(&d_ws_raw, strata::kernels::gr_workspace_bytes(sh)), "m ws");
753    strata::kernels::GrWorkspace ws;
754    strata::kernels::gr_workspace_init(sh, d_ws_raw, ws);
755    strata::kernels::gr_read(d_R, d_norm, d_down, d_up, d_inj, eps, sh, ws, d_mixed, d_inject, nullptr);
756    std::vector<float> got_mixed((size_t) n_embd), got_inject((size_t) hc);
757    check(cudaMemcpy(got_mixed.data(), d_mixed, got_mixed.size() * sizeof(float), cudaMemcpyDeviceToHost), "c mixed");
758    check(cudaMemcpy(got_inject.data(), d_inject, got_inject.size() * sizeof(float), cudaMemcpyDeviceToHost), "c inject");
759
760    int bad = 0;
761
762    // ---- the traps, asserted OBSERVABLE before the kernel is judged against the right reading
763    Opts right;
764    std::vector<float> want_mixed, want_inject;
765    reference(R, w_norm, w_down, w_up, w_inject, eps, n_embd, hc, hc_lr, right, want_mixed, want_inject);
766
767    struct Trap { const char* name; Opts o; double floor; };
768    const Trap traps[] = {
769        {"per-stream RMSNorm vs whole-stack", {false, true, true, true, true}, 0.05},
770        {"/hc inside the silu vs outside", {true, false, true, true, true}, 0.05},
771        {"SiLU on lo / sigmoid on gate, swapped", {true, true, false, true, true}, 0.05},
772        {"mean over streams vs sum", {true, true, true, false, true}, 0.50},
773        {"BF16 vs FP32 activation contracts", {true, true, true, true, false}, 1e-4},
774    };
775    for (const Trap& t : traps) {
776        std::vector<float> m, i;
777        reference(R, w_norm, w_down, w_up, w_inject, eps, n_embd, hc, hc_lr, t.o, m, i);
778        const double rel = rel_diff(want_mixed, m);
779        const bool observable = rel > t.floor;
780        std::printf("  %-40s %-4s (%.4f%% apart, floor %.3f%%)\n", t.name, observable ? "yes" : "*** NO ***",
781                    rel * 100, t.floor * 100);
782        if (!observable) {
783            std::printf("      *** the fixture cannot see this trap, so passing proves nothing about it ***\n");
784            ++bad;
785        }
786    }
787
788    // ---- the kernel against the correct reference
789    double mag = 0;
790    const double rel_mixed = rel_diff(want_mixed, got_mixed, &mag);
791    std::printf("\n  %-40s worst %.3e (mean |ref| %.4f)\n", "mixed vs reference", rel_mixed, mag);
792
793    // The tolerance is set by SUMMATION ORDER, not by the structure: both sides round the activation to bf16
794    // and both weights are bf16-valued, so every product is exact in f32 and only the order differs.  A
795    // structural error is several orders of magnitude larger - the trap floors above say so.
796    if (!(rel_mixed <= 1e-4)) {
797        std::printf("    *** over 1e-4, which summation order does not explain - look for a structural bug ***\n");
798        ++bad;
799    }
800
801    const double rel_inject = rel_diff(want_inject, got_inject);
802    std::printf("  %-40s rel %.3e\n", "inject vs reference", rel_inject);
803    if (!(rel_inject <= 1e-4)) {
804        // Say WHICH elements and by how much: a whole-array L1 hides whether this is one stream wrong (an
805        // indexing bug) or all of them slightly wrong (a precision bug), and those need different responses.
806        std::printf("    want:");
807        for (long long c = 0; c < hc; ++c) std::printf(" %12.6f", (double) want_inject[(size_t) c]);
808        std::printf("\n    got :");
809        for (long long c = 0; c < hc; ++c) std::printf(" %12.6f", (double) got_inject[(size_t) c]);
810        std::printf("\n");
811        ++bad;
812    }
813
814    // Same geometry and weights with the CUDA single-token activation contract.  The scalar fixture
815    // below is the independent precision check; this case exercises multi-stream reductions and indexing.
816    {
817        Opts fp32;
818        fp32.round_activation = false;
819        std::vector<float> wm, wi, gm((size_t) n_embd), gi((size_t) hc);
820        reference(R, w_norm, w_down, w_up, w_inject, eps, n_embd, hc, hc_lr, fp32, wm, wi);
821        strata::kernels::gr_set_fp32_activations(true);
822        strata::kernels::gr_read(d_R, d_norm, d_down, d_up, d_inj, eps, sh, ws, d_mixed, d_inject, nullptr);
823        check(cudaMemcpy(gm.data(), d_mixed, gm.size() * sizeof(float), cudaMemcpyDeviceToHost), "FP32 mixed");
824        check(cudaMemcpy(gi.data(), d_inject, gi.size() * sizeof(float), cudaMemcpyDeviceToHost), "FP32 inject");
825        strata::kernels::gr_set_fp32_activations(false);
826        const double rm = rel_diff(wm, gm), ri = rel_diff(wi, gi);
827        const bool ok = rm <= 1e-4 && ri <= 1e-4;
828        std::printf("  FP32 activations vs reference: %s (mixed %.3e, inject %.3e)\n",
829                    ok ? "pass" : "FAIL", rm, ri);
830        if (!ok) ++bad;
831        strata::kernels::gr_read(d_R, d_norm, d_down, d_up, d_inj, eps, sh, ws, d_mixed, d_inject, nullptr);
832        check(cudaMemcpy(gm.data(), d_mixed, gm.size() * sizeof(float), cudaMemcpyDeviceToHost), "restored mixed");
833        check(cudaMemcpy(gi.data(), d_inject, gi.size() * sizeof(float), cudaMemcpyDeviceToHost), "restored inject");
834        const bool restored = std::memcmp(gm.data(), got_mixed.data(), gm.size() * sizeof(float)) == 0 &&
835                              std::memcmp(gi.data(), got_inject.data(), gi.size() * sizeof(float)) == 0;
836        std::printf("  restoring default activation contract: %s\n", restored ? "byte-identical" : "FAIL");
837        if (!restored) ++bad;
838    }
839
840    // ---- THE WEIGHT ORIENTATION MUST BE OBSERVABLE.  The kernel now takes both matrices exactly as the
841    // manifest stores them, so there is no permutation for a loader to forget - but the INDEX EXPRESSIONS
842    // inside the kernel are still a place to be wrong, and a wrong one gives right-shaped, wrong-valued
843    // output.  Feed transposed copies through the same code path and require the answer to differ.
844    {
845        uint16_t *d_down_bad = nullptr, *d_up_bad = nullptr;
846        check(cudaMalloc(&d_down_bad, q_down.size() * sizeof(uint16_t)), "m down_bad");
847        check(cudaMalloc(&d_up_bad, q_up.size() * sizeof(uint16_t)), "m up_bad");
848        std::vector<uint16_t> tr_down(q_down.size()), tr_up(q_up.size());
849        for (long long k = 0; k < hc_lr; ++k)
850            for (long long i = 0; i < hc_dim; ++i)
851                tr_down[(size_t) (i * hc_lr + k)] = q_down[(size_t) (k * hc_dim + i)];
852        for (long long i = 0; i < hc_dim; ++i)
853            for (long long k = 0; k < hc_lr; ++k)
854                tr_up[(size_t) (k * hc_dim + i)] = q_up[(size_t) (i * hc_lr + k)];
855        check(cudaMemcpy(d_down_bad, tr_down.data(), tr_down.size() * 2, cudaMemcpyHostToDevice), "cb d");
856        check(cudaMemcpy(d_up_bad, tr_up.data(), tr_up.size() * 2, cudaMemcpyHostToDevice), "cb u");
857        std::vector<float> bad_mixed((size_t) n_embd);
858        float* d_bad = nullptr;
859        check(cudaMalloc(&d_bad, bad_mixed.size() * sizeof(float)), "m bad");
860        strata::kernels::gr_read(d_R, d_norm, d_down_bad, d_up_bad, d_inj, eps, sh, ws, d_bad, d_inject,
861                                 nullptr);
862        check(cudaMemcpy(bad_mixed.data(), d_bad, bad_mixed.size() * sizeof(float), cudaMemcpyDeviceToHost), "cb b");
863        const double rel = rel_diff(want_mixed, bad_mixed);
864        const bool visible = rel > 0.05;
865        std::printf("  %-40s %s (%.1f%% apart)\n", "weight orientation is observable",
866                    visible ? "yes" : "*** NO ***", rel * 100);
867        if (!visible) ++bad;
868        cudaFree(d_down_bad); cudaFree(d_up_bad); cudaFree(d_bad);
869    }
870
871    // ---- the FINAL mixer passes w_inject = nullptr, and then nothing may be written
872    float sentinel = -12345.0f;
873    check(cudaMemcpy(d_inject, &sentinel, sizeof(float), cudaMemcpyHostToDevice), "c sentinel");
874    strata::kernels::gr_read(d_R, d_norm, d_down, d_up, nullptr, eps, sh, ws, d_mixed, d_inject, nullptr);
875    float after = 0.0f;
876    check(cudaMemcpy(&after, d_inject, sizeof(float), cudaMemcpyDeviceToHost), "c after");
877    const bool untouched = (after == sentinel);
878    std::printf("  %-40s %s\n", "null w_inject writes nothing", untouched ? "yes" : "*** NO ***");
879    if (!untouched) ++bad;
880
881    // ---- gr_write: the `2*sigmoid` centring, asserted as the PROPERTY the source comment claims
882    std::vector<float> block_out((size_t) n_embd);
883    for (auto& x : block_out) x = gauss(rng);
884    std::vector<float> zero_inj((size_t) hc, 0.0f);
885    float *d_Rw = nullptr, *d_bo = nullptr, *d_zi = nullptr, *d_outw = nullptr;
886    check(cudaMalloc(&d_Rw, R.size() * sizeof(float)), "m Rw");
887    check(cudaMalloc(&d_bo, block_out.size() * sizeof(float)), "m bo");
888    check(cudaMalloc(&d_zi, zero_inj.size() * sizeof(float)), "m zi");
889    check(cudaMalloc(&d_outw, R.size() * sizeof(float)), "m outw");
890    check(cudaMemcpy(d_Rw, R.data(), R.size() * sizeof(float), cudaMemcpyHostToDevice), "c Rw");
891    check(cudaMemcpy(d_bo, block_out.data(), block_out.size() * sizeof(float), cudaMemcpyHostToDevice), "c bo");
892    check(cudaMemcpy(d_zi, zero_inj.data(), zero_inj.size() * sizeof(float), cudaMemcpyHostToDevice), "c zi");
893
894    strata::kernels::gr_write(d_Rw, d_bo, d_zi, sh, d_outw, nullptr);
895    std::vector<float> got_write((size_t) hc_dim);
896    check(cudaMemcpy(got_write.data(), d_outw, got_write.size() * sizeof(float), cudaMemcpyDeviceToHost), "c outw");
897
898    double worst_plain = 0;
899    for (long long c = 0; c < hc; ++c)
900        for (long long d = 0; d < n_embd; ++d) {
901            const size_t i = (size_t) (c * n_embd + d);
902            const double want = (double) R[i] + (double) block_out[(size_t) d];
903            worst_plain = std::fmax(worst_plain, rel_terms(want, (double) got_write[i], (double) R[i],
904                                                           (double) block_out[(size_t) d]));
905        }
906    const bool plain = worst_plain < 1e-6;
907    std::printf("  %-40s %s (worst rel %.3e)\n", "zero injection -> plain residual add",
908                plain ? "yes" : "*** NO ***", worst_plain);
909    if (!plain) ++bad;
910
911    // the rival reading: sigmoid without the 2 halves the update, and must be visible.
912    //
913    // The comparison is on the DELTA `out - R`, not on `out`.  The claim is about the gate WEIGHT, and `R`
914    // now reaches 64 in the last stream, so measuring `R + block_out*w` against the wrong reading dilutes a
915    // 100% error in `w` down to 2.27% - which is how this check first passed as "not observable" while being
916    // perfectly observable.  Measure the quantity the claim is about.
917    {
918        std::vector<float> got_delta((size_t) hc_dim), want_delta((size_t) hc_dim), wrong_delta((size_t) hc_dim);
919        for (long long c = 0; c < hc; ++c)
920            for (long long d = 0; d < n_embd; ++d) {
921                const size_t i = (size_t) (c * n_embd + d);
922                got_delta[i] = (float) ((double) got_write[i] - (double) R[i]);
923                want_delta[i] = block_out[(size_t) d];        // 2*sigmoid(0) = 1.0
924                wrong_delta[i] = block_out[(size_t) d] * 0.5f; // 1*sigmoid(0) = 0.5
925            }
926        const double rel = rel_diff(want_delta, wrong_delta);
927        const double rel_got = rel_diff(want_delta, got_delta);
928        const bool visible = rel > 0.05 && rel_got < 0.05;
929        std::printf("  %-40s %s (readings %.0f%% apart, kernel within %.2e)\n",
930                    "1*sigmoid vs 2*sigmoid is observable", visible ? "yes" : "*** NO ***", rel * 100, rel_got);
931        if (!visible) ++bad;
932    }
933
934    // a non-zero injection: every stream receives the SAME block output, differing only by weight
935    std::vector<float> inj((size_t) hc);
936    for (auto& x : inj) x = gauss(rng) * 3.0f;
937    check(cudaMemcpy(d_zi, inj.data(), inj.size() * sizeof(float), cudaMemcpyHostToDevice), "c inj2");
938    strata::kernels::gr_write(d_Rw, d_bo, d_zi, sh, d_outw, nullptr);
939    check(cudaMemcpy(got_write.data(), d_outw, got_write.size() * sizeof(float), cudaMemcpyDeviceToHost), "c outw2");
940    double worst_stream = 0;
941    for (long long c = 0; c < hc; ++c) {
942        const double w = 2.0 / (1.0 + std::exp(-(double) inj[(size_t) c] / (double) hc));
943        for (long long d = 0; d < n_embd; ++d) {
944            const size_t i = (size_t) (c * n_embd + d);
945            const double want = (double) R[i] + (double) block_out[(size_t) d] * w;
946            worst_stream = std::fmax(worst_stream, rel_terms(want, (double) got_write[i], (double) R[i],
947                                                             (double) block_out[(size_t) d] * w));
948        }
949    }
950    const bool streams_ok = worst_stream < 1e-6;
951    std::printf("  %-40s %s (worst rel %.3e)\n", "every stream adds the same block output",
952                streams_ok ? "yes" : "*** NO ***", worst_stream);
953    if (!streams_ok) ++bad;
954
955    // ---- THE REAL DIMENSIONS. Exercise all activation/projection variants at n_embd=2560, hc=4, hc_lr=320.
956    // Workspace sizing and every full weight row must agree with the model geometry.
957    {
958        const long long rn = 2560, rhc = 4, rlr = 320, rdim = rhc * rn;
959        std::mt19937 rrng(99);
960        std::normal_distribution<float> rg(0.0f, 1.0f);
961        auto rbf16 = [&](size_t n, float sigma) {
962            std::vector<float> v(n);
963            for (auto& x : v) x = to_bf16(rg(rrng) * sigma);
964            return v;
965        };
966        std::vector<float> rR((size_t) rdim);
967        for (auto& x : rR) x = rg(rrng);
968        for (long long c = 0; c < rhc; ++c)
969            for (long long d = 0; d < rn; ++d) rR[(size_t) (c * rn + d)] *= std::pow(4.0f, (float) c);
970        std::vector<float> rnorm((size_t) rdim);
971        for (auto& x : rnorm) x = 1.0f + 0.1f * rg(rrng);
972        std::vector<float> rdown = rbf16((size_t) (rlr * rdim), 0.2f);
973        std::vector<float> rup = rbf16((size_t) (rdim * rlr), 0.2f);
974        std::vector<float> rinj = rbf16((size_t) (rhc * rdim), 0.05f);
975
976        std::vector<uint16_t> qd(rdown.size()), qu(rup.size()), qi(rinj.size());
977        for (size_t i = 0; i < rdown.size(); ++i) qd[i] = bf16_bits(rdown[i]);
978        for (size_t i = 0; i < rup.size(); ++i) qu[i] = bf16_bits(rup[i]);
979        for (size_t i = 0; i < rinj.size(); ++i) qi[i] = bf16_bits(rinj[i]);
980
981        float *dR = nullptr, *dN = nullptr, *dM = nullptr, *dI = nullptr;
982        uint16_t *dD = nullptr, *dU = nullptr, *dJ = nullptr;
983        check(cudaMalloc(&dR, rR.size() * 4), "rR");
984        check(cudaMalloc(&dN, rnorm.size() * 4), "rN");
985        check(cudaMalloc(&dD, qd.size() * 2), "rD");
986        check(cudaMalloc(&dU, qu.size() * 2), "rU");
987        check(cudaMalloc(&dJ, qi.size() * 2), "rJ");
988        check(cudaMalloc(&dM, (size_t) rn * 4), "rM");
989        check(cudaMalloc(&dI, (size_t) rhc * 4), "rI");
990        check(cudaMemcpy(dR, rR.data(), rR.size() * 4, cudaMemcpyHostToDevice), "crR");
991        check(cudaMemcpy(dN, rnorm.data(), rnorm.size() * 4, cudaMemcpyHostToDevice), "crN");
992        check(cudaMemcpy(dD, qd.data(), qd.size() * 2, cudaMemcpyHostToDevice), "crD");
993        check(cudaMemcpy(dU, qu.data(), qu.size() * 2, cudaMemcpyHostToDevice), "crU");
994        check(cudaMemcpy(dJ, qi.data(), qi.size() * 2, cudaMemcpyHostToDevice), "crJ");
995
996        const strata::kernels::GrShapes rsh{rn, rhc, rlr};
997        void* rws_raw = nullptr;
998        check(cudaMalloc(&rws_raw, strata::kernels::gr_workspace_bytes(rsh)), "m rws");
999        strata::kernels::GrWorkspace rws;
1000        strata::kernels::gr_workspace_init(rsh, rws_raw, rws);
1001        for (int mode = 0; mode < 3; ++mode) {
1002            select_activation_mode(mode);
1003            strata::kernels::gr_read(dR, dN, dD, dU, dJ, eps, rsh, rws, dM, dI, nullptr);
1004            std::vector<float> gm((size_t) rn), gi((size_t) rhc);
1005            check(cudaMemcpy(gm.data(), dM, gm.size() * 4, cudaMemcpyDeviceToHost), "cgm");
1006            check(cudaMemcpy(gi.data(), dI, gi.size() * 4, cudaMemcpyDeviceToHost), "cgi");
1007
1008            Opts precision;
1009            precision.round_activation = mode == 0;
1010            std::vector<float> wm, wi;
1011            reference(rR, rnorm, rdown, rup, rinj, eps, rn, rhc, rlr, precision, wm, wi);
1012            const double rm = rel_diff(wm, gm), ri = rel_diff(wi, gi);
1013            const bool ok = rm <= 1e-4 && ri <= 1e-4;
1014            std::printf("\n  real dims 2560/4/320 %s %s (mixed %.3e, inject %.3e)\n",
1015                        activation_mode_name(mode), ok ? "pass" : "*** FAIL ***", rm, ri);
1016            if (!ok) ++bad;
1017        }
1018        bad += fused_multi_lds_parity(dN, dD, dU, dJ, eps);
1019        select_activation_mode(0);
1020        cudaFree(rws_raw);
1021        cudaFree(dR); cudaFree(dN); cudaFree(dD); cudaFree(dU); cudaFree(dJ); cudaFree(dM); cudaFree(dI);
1022    }
1023
1024    bad += scalar_activation_contract();
1025    std::printf("\ngr_read/gr_write: %d failures\n", bad);
1026    if (bad) return 1;
1027    if (selftest) std::printf("gr_parity OK\n");
1028    return 0;
1029}