okami.mom/strata

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

Niko1221Merge f-029-gdn-mx3a76d5eaf

main
23.9 KiB374 linesraw
1// metal/tests/gdn_chunk_bench.cpp - GDN prompt stage microbenchmark and numerical check (30 Oct GDN-M, phase 1).
2// The sequential scans of gdn_prompt.metal (gdn_scanr_2/4/8, production = gdn_scanr_4) against the chunked C = 32 form
3// (gdn_cprep -> gdn_cstate -> gdn_cout) at the real Flash-Next shape (h_k 16, h_v 48, S 128, 10240 conv channels),
4// T = 512 .. 32768, with the same gdn_pre in front and gdn_post behind (the whole GDN stage).  Checks against an FP64
5// sequential oracle on a few heads (output o and final state), the pipeline thread limits, and continuation (a call
6// split in two, chunked or sequential on either side, the second call on buffer offsets).
7//   gdn_chunk_bench [--T 512,2048,..] [--check] [--regime normal|strong] [--heads 0,17,47] [--reps 5] [--noscan]
8#include "mtl_rt.h"
9#include "ref_quant.h"
10
11#include <algorithm>
12#include <cmath>
13#include <cstdio>
14#include <cstdlib>
15#include <cstring>
16#include <string>
17#include <vector>
18
19namespace {
20constexpr int HK = 16, HV = 48, CH = 10240, S = 128, GC = 32, NSC = 14;
21struct GdnPArgs { uint32_t n_tok, h_k, h_v, channels; float eps; uint32_t f32; };
22double median(std::vector<double> v) { std::sort(v.begin(), v.end()); return v[v.size() / 2]; }
23std::vector<int> ints(const char* s) {
24    std::vector<int> r;
25    for (const char* p = s; *p;) { r.push_back(std::atoi(p)); while (*p && *p != ',') ++p; if (*p) ++p; }
26    return r;
27}
28}  // namespace
29
30int main(int argc, char** argv) {
31    std::vector<int> Ts = {512, 1024, 2048, 4096, 8192, 16384, 32768}, heads = {0, 17, 47};
32    bool check = false, noscan = false, strong = false;
33    int reps = 5;
34    for (int i = 1; i < argc; ++i) {
35        std::string a = argv[i];
36        if (a == "--T") Ts = ints(argv[++i]);
37        else if (a == "--heads") heads = ints(argv[++i]);
38        else if (a == "--check") check = true;
39        else if (a == "--noscan") noscan = true;
40        else if (a == "--regime") strong = std::string(argv[++i]) == "strong";
41        else if (a == "--reps") reps = std::atoi(argv[++i]);
42    }
43    const int TMAX = *std::max_element(Ts.begin(), Ts.end());
44    mtl::Context cx;
45    const int lib = cx.compile({"gdn_prompt.metal"}, "#define NO_GGML_COMMON 1\n");
46    std::printf("device %s, regime %s, TMAX %d\n", cx.device_name().c_str(), strong ? "strong-decay" : "normal", TMAX);
47    auto F = [&](size_t n) { return cx.alloc(4 * n); };
48    const size_t NCM = (TMAX + GC - 1) / GC;
49    mtl::Buffer qkv = F((size_t)TMAX * CH), al = F((size_t)TMAX * HV), be = F((size_t)TMAX * HV), z = F((size_t)TMAX * HV * S),
50                cw = F(CH * 4), dt = F(HV), sa = F(HV), gam = F(S), st0 = F((size_t)S * HV * S), stX = F((size_t)S * HV * S),
51                stRef = F((size_t)S * HV * S), h0 = F(CH * 3), hOut = F(CH * 3), yh = cx.alloc(2 * (size_t)TMAX * HV * S),
52                yB = F((size_t)TMAX * HV * S), qn = F((size_t)(TMAX + 32) * HK * S), kn = F((size_t)(TMAX + 32) * HK * S),
53                vc = F((size_t)TMAX * HV * S), gb = F(2 * (size_t)TMAX * HV), kq = F((size_t)TMAX * HK),
54                o = F((size_t)TMAX * HV * S), oRef = F((size_t)TMAX * HV * S), cU = F((size_t)HV * NCM * GC * S),
55                cW = F((size_t)HV * NCM * GC * S), clg = F((size_t)HV * NCM * GC), cD = F((size_t)HV * NCM * GC * S), cM = F((size_t)HV * NCM * GC * GC);
56    ref::Rng r(21);
57    for (size_t i = 0; i < (size_t)TMAX * CH; ++i) qkv.as<float>()[i] = r.sym() * 2.0f;
58    for (size_t i = 0; i < (size_t)TMAX * HV; ++i) { al.as<float>()[i] = r.sym() * 3.0f; be.as<float>()[i] = r.sym() * 2.0f; }
59    for (size_t i = 0; i < (size_t)TMAX * HV * S; ++i) z.as<float>()[i] = r.sym() * 2.0f;
60    for (int i = 0; i < CH * 4; ++i) cw.as<float>()[i] = r.sym() * 0.6f;
61    for (int i = 0; i < HV; ++i) { dt.as<float>()[i] = r.sym(); sa.as<float>()[i] = strong ? -5.0f - r.uni() * 25.0f : -0.2f - r.uni() * 2.0f; }
62    for (int i = 0; i < S; ++i) gam.as<float>()[i] = 0.5f + r.uni();
63    for (int i = 0; i < S * HV * S; ++i) st0.as<float>()[i] = r.sym() * 0.1f;
64    for (int i = 0; i < CH * 3; ++i) h0.as<float>()[i] = r.sym();
65
66    mtl::Pipeline pre = cx.pipeline(lib, "gdn_pre"), post = cx.pipeline(lib, "gdn_post");
67    // the existing sequential scans: {name, threadgroups, threads}; index 1 = gdn_scanr_4 = production
68    struct Sv { const char* nm; int grid, tg; };
69    const Sv svs[NSC] = {{"gdn_scanr_2", HV * 4, 64}, {"gdn_scanr_4", HV * 4, 128}, {"gdn_scanr_8", HV * 4, 256},
70                         {"gdn_scanr_4_8", HV * 4, 128}, {"gdn_scan_v", HV * 4, 256}, {"gdn_scan_1", HV * 4, 32},
71                         {"gdn_scan_2", HV * 2, 64}, {"gdn_scan_4", HV, 128},
72                         {"gdn_scanr_4_4", HV * 4, 128}, {"gdn_scanr_4_2", HV * 4, 128}, {"gdn_scanr_8_8", HV * 4, 256},
73                         {"gdn_scanr_8_4", HV * 4, 256}, {"gdn_scanr_2_8", HV * 4, 64}, {"gdn_scanr_2_4", HV * 4, 64}};
74    std::vector<mtl::Pipeline> scan;
75    for (const Sv& v : svs) scan.push_back(cx.pipeline(lib, v.nm, std::string(v.nm) == "gdn_scan_v" || std::string(v.nm).find("scanr") != std::string::npos ? mtl::Constants().i(6, 0) : mtl::Constants()));
76    mtl::Pipeline pcp = cx.pipeline(lib, "gdn_cprep"), pcs = cx.pipeline(lib, "gdn_cstate"), pco = cx.pipeline(lib, "gdn_cout"), pcp2 = cx.pipeline(lib, "gdn_cprep2"), pcs2 = cx.pipeline(lib, "gdn_cstate2");
77    bool v2 = false;   // chunk_d builds the v2 chunked form (gdn_cprep2 + gdn_cstate2)
78    std::printf("pipeline limits (max threads / simd / static tg mem; threads asked):");
79    for (size_t i = 0; i < scan.size(); ++i) std::printf(" %s %d/%d/%d (%d)", svs[i].nm, scan[i].max_threads, scan[i].simd_width, scan[i].static_tg_mem, svs[i].tg);
80    std::printf("\n  pre %d/%d/%d (256)  cprep %d/%d/%d (256)  cstate %d/%d/%d (256)  cout %d/%d/%d (128)  post %d/%d/%d (128)\n",
81                pre.max_threads, pre.simd_width, pre.static_tg_mem, pcp.max_threads, pcp.simd_width, pcp.static_tg_mem, pcs.max_threads,
82                pcs.simd_width, pcs.static_tg_mem, pco.max_threads, pco.simd_width, pco.static_tg_mem, post.max_threads, post.simd_width,
83                post.static_tg_mem);
84    std::printf("scratch at T: U+W+delta+lg = %.1f KB per token (%.0f MB at T 2048, %.0f MB at T 4096)\n",
85                (3.0 * HV * S * 4 + HV * 4) / 1024.0, (3.0 * HV * S * 4 + HV * 4) * 2048 / 1e6,
86                (3.0 * HV * S * 4 + HV * 4) * 4096 / 1e6);
87
88    // token range [t0, t0 + n) as buffer offsets
89    auto pre_d = [&](int t0, int n, std::vector<mtl::Dispatch>& ds, bool first) {
90        GdnPArgs a{(uint32_t)n, HK, HV, CH, 1e-6f, 1u};
91        mtl::Dispatch d;
92        d.p = &pre;
93        // history: the chunk reads hist (h0 for the first call, hOut afterwards), writes hOut
94        d.args = {mtl::Arg::B(qkv, (size_t)t0 * CH * 4), mtl::Arg::B(first ? h0 : hOut), mtl::Arg::B(cw),
95                  mtl::Arg::B(al, (size_t)t0 * HV * 4), mtl::Arg::B(be, (size_t)t0 * HV * 4), mtl::Arg::B(dt), mtl::Arg::B(sa),
96                  mtl::Arg::B(qn, (size_t)t0 * HK * S * 4), mtl::Arg::B(kn, (size_t)t0 * HK * S * 4),
97                  mtl::Arg::B(vc, (size_t)t0 * HV * S * 4), mtl::Arg::B(gb, (size_t)t0 * HV * 8), mtl::Arg::B(kq, (size_t)t0 * HK * 4),
98                  mtl::Arg::B(hOut), mtl::Arg::V(a)};
99        d.grid[0] = HK + HV / 2; d.grid[1] = n; d.tg[0] = 256;
100        ds.push_back(d);
101    };
102    auto scan_d = [&](int which, int t0, int n, const mtl::Buffer& st, const mtl::Buffer& out, std::vector<mtl::Dispatch>& ds) {
103        GdnPArgs a{(uint32_t)n, HK, HV, CH, 1e-6f, 1u};
104        mtl::Dispatch d;
105        d.p = &scan[which];
106        d.args = {mtl::Arg::B(st), mtl::Arg::B(qn, (size_t)t0 * HK * S * 4), mtl::Arg::B(kn, (size_t)t0 * HK * S * 4),
107                  mtl::Arg::B(vc, (size_t)t0 * HV * S * 4), mtl::Arg::B(gb, (size_t)t0 * HV * 8), mtl::Arg::B(kq, (size_t)t0 * HK * 4),
108                  mtl::Arg::B(out, (size_t)t0 * HV * S * 4), mtl::Arg::V(a)};
109        d.grid[0] = svs[which].grid; d.tg[0] = svs[which].tg;
110        ds.push_back(d);
111    };
112    auto chunk_d = [&](int t0, int n, const mtl::Buffer& st, const mtl::Buffer& out, std::vector<mtl::Dispatch>& ds) {
113        GdnPArgs a{(uint32_t)n, HK, HV, CH, 1e-6f, 1u};
114        const uint32_t nc = (n + GC - 1) / GC;
115        if (v2) {
116            mtl::Dispatch f1; f1.p = &pcp2;
117            f1.args = {mtl::Arg::B(qn, (size_t)t0 * HK * S * 4), mtl::Arg::B(kn, (size_t)t0 * HK * S * 4),
118                       mtl::Arg::B(vc, (size_t)t0 * HV * S * 4), mtl::Arg::B(gb, (size_t)t0 * HV * 8), mtl::Arg::B(cU), mtl::Arg::B(cW),
119                       mtl::Arg::B(clg), mtl::Arg::B(cM), mtl::Arg::V(a)};
120            f1.grid[0] = HV; f1.grid[1] = nc; f1.tg[0] = 256; ds.push_back(f1);
121            mtl::Dispatch f2; f2.p = &pcs2;
122            f2.args = {mtl::Arg::B(st), mtl::Arg::B(qn, (size_t)t0 * HK * S * 4), mtl::Arg::B(kn, (size_t)t0 * HK * S * 4),
123                       mtl::Arg::B(cU), mtl::Arg::B(cW), mtl::Arg::B(clg), mtl::Arg::B(cM), mtl::Arg::B(out, (size_t)t0 * HV * S * 4),
124                       mtl::Arg::V(a)};
125            f2.grid[0] = HV * 4; f2.tg[0] = 128; ds.push_back(f2);
126            return;
127        }
128        mtl::Dispatch e1; e1.p = &pcp;
129        e1.args = {mtl::Arg::B(qn, (size_t)t0 * HK * S * 4), mtl::Arg::B(kn, (size_t)t0 * HK * S * 4),
130                   mtl::Arg::B(vc, (size_t)t0 * HV * S * 4), mtl::Arg::B(gb, (size_t)t0 * HV * 8), mtl::Arg::B(cU), mtl::Arg::B(cW),
131                   mtl::Arg::B(clg), mtl::Arg::V(a)};
132        e1.grid[0] = HV; e1.grid[1] = nc; e1.tg[0] = 256; ds.push_back(e1);
133        mtl::Dispatch e2; e2.p = &pcs;
134        e2.args = {mtl::Arg::B(st), mtl::Arg::B(qn, (size_t)t0 * HK * S * 4), mtl::Arg::B(kn, (size_t)t0 * HK * S * 4),
135                   mtl::Arg::B(cU), mtl::Arg::B(cW), mtl::Arg::B(clg), mtl::Arg::B(cD), mtl::Arg::B(out, (size_t)t0 * HV * S * 4),
136                   mtl::Arg::V(a)};
137        e2.grid[0] = HV * 4; e2.tg[0] = 256; ds.push_back(e2);
138        mtl::Dispatch e3; e3.p = &pco;
139        e3.args = {mtl::Arg::B(qn, (size_t)t0 * HK * S * 4), mtl::Arg::B(kn, (size_t)t0 * HK * S * 4), mtl::Arg::B(cD),
140                   mtl::Arg::B(clg), mtl::Arg::B(out, (size_t)t0 * HV * S * 4), mtl::Arg::V(a)};
141        e3.grid[0] = HV; e3.grid[1] = nc; e3.tg[0] = 128; ds.push_back(e3);
142    };
143    auto post_d = [&](int t0, int n, const mtl::Buffer& out, std::vector<mtl::Dispatch>& ds) {
144        GdnPArgs a{(uint32_t)n, HK, HV, CH, 1e-6f, 1u};
145        mtl::Dispatch d;
146        d.p = &post;
147        d.args = {mtl::Arg::B(out, (size_t)t0 * HV * S * 4), mtl::Arg::B(z, (size_t)t0 * HV * S * 4), mtl::Arg::B(gam),
148                  mtl::Arg::B(yh, (size_t)t0 * HV * S * 2), mtl::Arg::B(yB, (size_t)t0 * HV * S * 4), mtl::Arg::V(a)};
149        d.grid[0] = HV; d.grid[1] = n; d.tg[0] = 128;
150        ds.push_back(d);
151    };
152    mtl::Pipeline pf[3] = {cx.pipeline(lib, "gdn_scanf_4"), cx.pipeline(lib, "gdn_scanf_8"), cx.pipeline(lib, "gdn_scanf_2")};
153    std::printf("fused scan+post pipelines (max threads / static tg mem; 512 asked): TB4 %d/%d  TB8 %d/%d  TB2  %d/%d\n", pf[0].max_threads,
154                pf[0].static_tg_mem, pf[1].max_threads, pf[1].static_tg_mem, pf[2].max_threads, pf[2].static_tg_mem);
155    auto fused_d = [&](int which, int t0, int n, const mtl::Buffer& st, std::vector<mtl::Dispatch>& ds) {
156        GdnPArgs a{(uint32_t)n, HK, HV, CH, 1e-6f, 1u};
157        mtl::Dispatch d;
158        d.p = &pf[which];
159        d.args = {mtl::Arg::B(st), mtl::Arg::B(qn, (size_t)t0 * HK * S * 4), mtl::Arg::B(kn, (size_t)t0 * HK * S * 4),
160                  mtl::Arg::B(vc, (size_t)t0 * HV * S * 4), mtl::Arg::B(gb, (size_t)t0 * HV * 8), mtl::Arg::B(kq, (size_t)t0 * HK * 4),
161                  mtl::Arg::B(z, (size_t)t0 * HV * S * 4), mtl::Arg::B(gam), mtl::Arg::B(yh, (size_t)t0 * HV * S * 2),
162                  mtl::Arg::B(yB, (size_t)t0 * HV * S * 4), mtl::Arg::V(a)};
163        d.grid[0] = HV; d.tg[0] = 512;
164        ds.push_back(d);
165    };
166    auto timeit = [&](const std::vector<mtl::Dispatch>& ds) {
167        cx.warm(ds, 0.3);
168        std::vector<double> t;
169        for (int i = 0; i < reps; ++i) t.push_back(cx.run(ds));
170        return median(t) * 1e3;
171    };
172    auto copy_st0 = [&](mtl::Buffer& dst) { std::memcpy(dst.ptr, st0.ptr, (size_t)S * HV * S * 4); };
173
174    // FP64 oracle for head h over tokens [t0, t0 + n) from the prepared tensors; state in/out [S][S] (i, j)
175    auto oracle = [&](int h, int t0, int n, std::vector<double>& St, std::vector<double>& out) {
176        const int hk = h % HK;
177        out.assign((size_t)n * S, 0.0);
178        std::vector<double> a(S), b(S);
179        for (int t = t0; t < t0 + n; ++t) {
180            const float* k = kn.as<float>() + ((size_t)t * HK + hk) * S;
181            const float* q = qn.as<float>() + ((size_t)t * HK + hk) * S;
182            const float* v = vc.as<float>() + ((size_t)t * HV + h) * S;
183            const double g = gb.as<float>()[((size_t)t * HV + h) * 2], bt = gb.as<float>()[((size_t)t * HV + h) * 2 + 1];
184            double kqv = 0;
185            for (int i = 0; i < S; ++i) kqv += (double)k[i] * q[i];
186            std::fill(a.begin(), a.end(), 0.0); std::fill(b.begin(), b.end(), 0.0);
187            for (int i = 0; i < S; ++i) {
188                const double* row = &St[(size_t)i * S];
189                const double ki = k[i], qi = q[i];
190                for (int j = 0; j < S; ++j) { a[j] += row[j] * ki; b[j] += row[j] * qi; }
191            }
192            std::vector<double> dl(S);
193            for (int j = 0; j < S; ++j) {
194                dl[j] = (v[j] - g * a[j]) * bt;
195                out[(size_t)(t - t0) * S + j] = (g * b[j] + dl[j] * kqv) / std::sqrt((double)S);
196            }
197            for (int i = 0; i < S; ++i) {
198                double* row = &St[(size_t)i * S];
199                for (int j = 0; j < S; ++j) row[j] = g * row[j] + (double)k[i] * dl[j];
200            }
201        }
202    };
203    auto initial = [&](int h, std::vector<double>& St) {
204        St.resize((size_t)S * S);
205        for (int i = 0; i < S; ++i) for (int j = 0; j < S; ++j) St[(size_t)i * S + j] = st0.as<float>()[((size_t)i * HV + h) * S + j];
206    };
207    struct Err { double l2, mx; int nonfinite; };
208    auto cmp_o = [&](const mtl::Buffer& ob, int h, int t0, int n, const std::vector<double>& ro) {
209        double se = 0, sr = 0, mx = 0, rmax = 0; int nf = 0;
210        for (int t = 0; t < n; ++t) for (int j = 0; j < S; ++j) {
211            const float x = ob.as<float>()[((size_t)(t0 + t) * HV + h) * S + j];
212            if (!std::isfinite(x)) { ++nf; continue; }
213            const double e = x - ro[(size_t)t * S + j];
214            se += e * e; sr += ro[(size_t)t * S + j] * ro[(size_t)t * S + j]; mx = std::max(mx, std::fabs(e)); rmax = std::max(rmax, std::fabs(ro[(size_t)t * S + j]));
215        }
216        return Err{std::sqrt(se / std::max(sr, 1e-30)), mx / std::max(rmax, 1e-30), nf};
217    };
218    auto cmp_s = [&](const mtl::Buffer& sb, int h, const std::vector<double>& rs) {
219        double se = 0, sr = 0, mx = 0, rmax = 0; int nf = 0;
220        for (int i = 0; i < S; ++i) for (int j = 0; j < S; ++j) {
221            const float x = sb.as<float>()[((size_t)i * HV + h) * S + j];
222            if (!std::isfinite(x)) { ++nf; continue; }
223            const double e = x - rs[(size_t)i * S + j];
224            se += e * e; sr += rs[(size_t)i * S + j] * rs[(size_t)i * S + j]; mx = std::max(mx, std::fabs(e)); rmax = std::max(rmax, std::fabs(rs[(size_t)i * S + j]));
225        }
226        return Err{std::sqrt(se / std::max(sr, 1e-30)), mx / std::max(rmax, 1e-30), nf};
227    };
228
229    // prepared tensors once for all TMAX tokens (gdn_pre per call carries the history; here one call, the tokens independent
230    // of the scan variant).  For the continuation check the pre runs per split below.
231    {
232        std::vector<mtl::Dispatch> ds;
233        // gdn_pre on a very long T reads hist only for the first 3 tokens; one call over TMAX is the same as pieces
234        pre_d(0, TMAX, ds, true);
235        cx.run(ds);
236    }
237    int fails = 0;
238    if (check) {
239        std::printf("== numerical checks vs FP64 oracle (rel L2 / max-abs over max|ref|, per head)\n");
240        for (int T : Ts) {
241            // the variants, each from st0, over tokens [0, T)
242            struct V { const char* name; int kind; };  // kind: 0..2 scanr IB 2/4/8, 10 chunked
243            for (V v : {V{"scanr_4", 1}, V{"chunked", 10}, V{"chunked2", 11}}) {
244                copy_st0(stX);
245                std::vector<mtl::Dispatch> ds;
246                v2 = v.kind == 11; if (v.kind >= 10) chunk_d(0, T, stX, o, ds); else scan_d(v.kind, 0, T, stX, o, ds); v2 = false;
247                cx.run(ds);
248                for (int h : heads) {
249                    std::vector<double> St, ro; initial(h, St); oracle(h, 0, T, St, ro);
250                    Err eo = cmp_o(o, h, 0, T, ro), es = cmp_s(stX, h, St);
251                    const bool ok = eo.l2 < 3e-3 && es.l2 < 3e-3 && !eo.nonfinite && !es.nonfinite;
252                    fails += !ok;
253                    std::printf("T %5d %-8s head %2d: o rel %.2e (max %.2e)  state rel %.2e (max %.2e)  nonfinite %d  %s\n", T, v.name,
254                                h, eo.l2, eo.mx, es.l2, es.mx, eo.nonfinite + es.nonfinite, ok ? "PASS" : "FAIL");
255                    if (T > 8192) break;   // one head at the largest sizes (oracle cost)
256                }
257            }
258        }
259        // continuation: T = A + B, second call on offsets and the first call's state; every pairing
260        std::printf("== continuation (state carried across two calls, 2nd call on buffer offsets) vs oracle over the whole range\n");
261        const std::pair<int, int> splits[] = {{37, 963}, {1024, 1024}, {2048, 2047}, {31, 33}, {1, 4095}};
262        for (auto [A, B] : splits) {
263            if (A + B > TMAX) continue;
264            const char* nm[8] = {"chunk+chunk", "scan+chunk", "chunk+scan", "scan+scan", "chunk2+chunk2", "scan+chunk2", "chunk2+scan", "-"};
265            for (int m = 0; m < 8; ++m) {
266                v2 = m >= 4;
267                if (v2 && m == 7) continue;   // scan+scan has no chunked part
268                copy_st0(stX);
269                std::vector<mtl::Dispatch> d1, d2;
270                if (m % 4 == 0 || m % 4 == 2) chunk_d(0, A, stX, o, d1); else scan_d(1, 0, A, stX, o, d1);
271                if (m % 4 == 0 || m % 4 == 1) chunk_d(A, B, stX, o, d2); else scan_d(1, A, B, stX, o, d2);
272                cx.run(d1); cx.run(d2); v2 = false;
273                for (int h : {heads[0], heads.back()}) {
274                    std::vector<double> St, ro; initial(h, St); oracle(h, 0, A + B, St, ro);
275                    Err eo = cmp_o(o, h, 0, A + B, ro), es = cmp_s(stX, h, St);
276                    const bool ok = eo.l2 < 3e-3 && es.l2 < 3e-3 && !eo.nonfinite && !es.nonfinite;
277                    fails += !ok;
278                    std::printf("split %5d + %5d %-14s head %2d: o rel %.2e  state rel %.2e  %s\n", A, B, nm[m], h, eo.l2, es.l2, ok ? "PASS" : "FAIL");
279                }
280            }
281        }
282        std::printf("== bitwise: gdn_scanr_4_8 / _4_4 / _4_2 / _8_8 / _2_8 o and state vs gdn_scanr_4\n");
283        for (int T : Ts) {
284            if (T > 16384) continue;
285            copy_st0(stX);
286            std::vector<mtl::Dispatch> d0; scan_d(1, 0, T, stX, o, d0); cx.run(d0);
287            std::vector<float> oref(o.as<float>(), o.as<float>() + (size_t)T * HV * S), sref(stX.as<float>(), stX.as<float>() + (size_t)S * HV * S);
288            for (int w : {3, 8, 9, 10, 12}) {
289                copy_st0(stX);
290                std::memset(o.ptr, 0, (size_t)T * HV * S * 4);
291                std::vector<mtl::Dispatch> d1; scan_d(w, 0, T, stX, o, d1); cx.run(d1);
292                const bool eq = std::memcmp(o.ptr, oref.data(), oref.size() * 4) == 0 && std::memcmp(stX.ptr, sref.data(), sref.size() * 4) == 0;
293                fails += !eq;
294                std::printf("T %5d %-14s %s\n", T, svs[w].nm, eq ? "BITWISE EQUAL" : "DIFFERS");
295            }
296        }
297        std::printf("== fused scan+post vs pre/scanr_4/post: y rel L2, fp16 y mismatches, state rel L2\n");
298        for (int T : Ts) {
299            if (T > 8192) continue;
300            copy_st0(stX);
301            std::vector<mtl::Dispatch> d0; scan_d(1, 0, T, stX, o, d0); post_d(0, T, o, d0); cx.run(d0);
302            std::vector<float> yref(yB.as<float>(), yB.as<float>() + (size_t)T * HV * S), sref(stX.as<float>(), stX.as<float>() + (size_t)S * HV * S);
303            std::vector<uint16_t> href(yh.as<uint16_t>(), yh.as<uint16_t>() + (size_t)T * HV * S);
304            for (int w = 0; w < 3; ++w) {
305                copy_st0(stX);
306                std::memset(yB.ptr, 0, (size_t)T * HV * S * 4);
307                std::vector<mtl::Dispatch> d1; fused_d(w, 0, T, stX, d1); cx.run(d1);
308                double se = 0, sr = 0, ss = 0, ssr = 0; size_t hm = 0;
309                for (size_t i = 0; i < (size_t)T * HV * S; ++i) { const double e = yB.as<float>()[i] - yref[i]; se += e * e; sr += (double)yref[i] * yref[i]; hm += yh.as<uint16_t>()[i] != href[i]; }
310                for (size_t i = 0; i < (size_t)S * HV * S; ++i) { const double e = stX.as<float>()[i] - sref[i]; ss += e * e; ssr += (double)sref[i] * sref[i]; }
311                const bool ok = std::sqrt(se / sr) < 1e-5 && std::sqrt(ss / ssr) < 1e-5;
312                fails += !ok;
313                std::printf("T %5d fused TB%-2d: y rel %.2e, fp16 mismatches %zu, state rel %.2e  %s\n", T, w == 0 ? 4 : w == 1 ? 8 : 2, std::sqrt(se / sr), hm, std::sqrt(ss / ssr), ok ? "PASS" : "FAIL");
314            }
315        }
316        std::printf("%s\n", fails ? "SOME FAILED" : "ALL PASS");
317    }
318    // timing: gdn_pre, the scan variants, chunked parts, gdn_post; the stage = pre + scan + post
319    std::printf("== timing (GPU ms per call, median of %d; stage = pre + scan + post)\n", reps);
320    std::printf("%6s | %7s %7s |", "T", "pre", "post");
321    for (const Sv& v : svs) std::printf(" %s", v.nm + 4);
322    std::printf(" | chunked (cprep cstate cout) | stage scanr_4 / chunked / x\n");
323    for (int T : Ts) {
324        std::vector<mtl::Dispatch> dp, dpo, dc;
325        pre_d(0, T, dp, true);
326        post_d(0, T, o, dpo);
327        const double tp = timeit(dp), tpo = timeit(dpo);
328        std::printf("%6d | %7.3f %7.3f |", T, tp, tpo);
329        double ts1 = 0, tbest = 1e30;
330        int wbest = 1;
331        for (int w = 0; w < NSC; ++w) {
332            std::vector<mtl::Dispatch> d1;
333            double t = 0;
334            if (!noscan) { scan_d(w, 0, T, stX, o, d1); t = timeit(d1); }
335            if (w == 1) ts1 = t;
336            if (t > 0 && t < tbest) { tbest = t; wbest = w; }
337            std::printf(" %8.3f", t);
338        }
339        chunk_d(0, T, stX, o, dc);
340        const double tc = timeit(dc), tc1 = timeit({dc[0]}), tc2 = timeit({dc[1]}), tc3 = timeit({dc[2]});
341        const double base = tp + ts1 + tpo, ch = tp + tc + tpo;
342        std::printf(" | %8.3f (%7.3f %7.3f %7.3f) | %8.3f %8.3f %5.2f | best %s stage %.3f = x%.3f (scan x%.3f)\n", tc, tc1, tc2, tc3, base, ch, base / ch, svs[wbest].nm, tp + tbest + tpo, base / (tp + tbest + tpo), ts1 / tbest);
343        {
344            v2 = true;
345            std::vector<mtl::Dispatch> dc2;
346            chunk_d(0, T, stX, o, dc2);
347            const double t2 = timeit(dc2), t2a = timeit({dc2[0]}), t2b = timeit({dc2[1]});
348            v2 = false;
349            std::printf("       chunked v2 %.3f (cprep2 %.3f cstate2 %.3f); stage pre+v2+post %.3f = x%.3f vs scanr_4 stage (scan x%.3f)\n", t2, t2a, t2b,
350                        tp + t2 + tpo, base / (tp + t2 + tpo), ts1 / t2);
351        }
352        if (std::getenv("GDN_PROBE_RUN")) {
353            v2 = true;
354            std::vector<mtl::Dispatch> dd;
355            chunk_d(0, T, stX, o, dd);
356            for (int pr = 1; pr <= 3; ++pr) {
357                mtl::Pipeline a1 = cx.pipeline(lib, "gdn_cprep2", mtl::Constants().i(6, pr)), a2 = cx.pipeline(lib, "gdn_cstate2", mtl::Constants().i(6, pr));
358                mtl::Dispatch d1 = dd[0], d2 = dd[1];
359                d1.p = &a1; d2.p = &a2;
360                const double x1 = timeit({d1}), x2 = timeit({d2});
361                std::printf("       probe %d: cprep2 %.3f cstate2 %.3f ms\n", pr, x1, x2);
362            }
363            v2 = false;
364        }
365        {
366            double tf[3];
367            for (int w = 0; w < 3; ++w) { std::vector<mtl::Dispatch> d1; fused_d(w, 0, T, stX, d1); tf[w] = timeit(d1); }
368            const double fb = tp + std::min(tf[0], std::min(tf[1], tf[2]));
369            std::printf("       fused scan+post TB4 %.3f TB8 %.3f TB2  %.3f ms; stage pre+fused best %.3f = x%.3f vs scanr_4 stage\n", tf[0], tf[1], tf[2], fb, base / fb);
370        }
371        std::fflush(stdout);
372    }
373    return fails ? 1 : 0;
374}