okami.mom/strata

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

Niko1221Merge f-q4-metal (ed1f58d27): the Mac (Metal) engine follows the compiled geometry (q4_lite/q4_mid/q4_big kernel parity 40/40, gate 2 like CUDA), plus the PLE row-buffer fix in src/program/generate.cpp (sized by the compiled hidden size, not 2560; it overran 24 KB at hidden 4096 and crashed Metal serve); default build unchanged (CUDA SASS 3573/3573 and 160/160 host objects, HIP gfx1201/gfx1151 string offsets only, SYCL 129/129 objects and 22/22 checksums, Metal per-token functions identical, UD-Q4_K_XL 10/10 tokens, CUDA IQ3_S 26/26 tokens) (Qwen4 prep)7f46672a4

main
10.5 KiB176 linesraw
1// metal/tests/gdn_prompt_parity.cpp - the prompt GDN passes (gdn_prompt.metal: gdn_pre -> gdn_scan -> gdn_post)
2// against the decode step run over the same T tokens in order (gdn.metal's gdn_step, GDN_NTOK = T, itself checked
3// against the CPU reference by gdn_parity): y, the final state and the conv history.  The scan reassociates
4// o = S_new^T q as g S^T q + delta (k . q), so the match is to rounding, not bitwise.  Then the speed for T = 2048.
5//   gdn_prompt_parity [--bench]
6#include "mtl_rt.h"
7#include "ref_quant.h"
8#include "engine/geo.h"
9
10#include <algorithm>
11#include <cmath>
12#include <cstdio>
13#include <cstdlib>
14#include <string>
15#include <vector>
16
17namespace {
18constexpr int HK = strata_metal::geo::HK, HV = strata_metal::geo::HV, CH = strata_metal::geo::CONV, S = strata_metal::geo::SS;
19struct GdnArgs { uint32_t h_k, h_v, channels, commit; float eps; uint32_t plane; };
20struct GdnPArgs { uint32_t n_tok, h_k, h_v, channels; float eps; uint32_t f32; };
21double median(std::vector<double> v) { std::sort(v.begin(), v.end()); return v[v.size() / 2]; }
22}  // namespace
23
24int main(int argc, char** argv) {
25    const bool bench = argc > 1 && std::string(argv[1]) == "--bench";
26    mtl::Context cx;
27    const int lib = cx.compile({"gdn.metal", "gdn_prompt.metal"}, "#define NO_GGML_COMMON 1\n");
28    std::printf("device %s\n", cx.device_name().c_str());
29    const int TMAX = 2048;
30    auto F = [&](size_t n) { return cx.alloc(4 * n); };
31    mtl::Buffer qkv = F((size_t)TMAX * CH), al = F(TMAX * HV), be = F(TMAX * HV), z = F((size_t)TMAX * HV * S), cw = F(CH * 4),
32                dt = F(HV), sa = F(HV), gam = F(S), st0 = F(S * HV * S), stA = F(S * HV * S), stB = F(S * HV * S),
33                h0 = F(CH * 3), hA = F(CH * 3), hA2 = F(CH * 3), hB = F(CH * 3), yA = F((size_t)TMAX * HV * S),
34                yB = F((size_t)TMAX * HV * S), yh = cx.alloc(2 * (size_t)TMAX * HV * S), qn = F((size_t)TMAX * HK * S),
35                kn = F((size_t)TMAX * HK * S), vc = F((size_t)TMAX * HV * S), gb = F(2 * TMAX * HV), kq = F(TMAX * HK),
36                o = F((size_t)TMAX * HV * S);
37    const size_t NCM = (TMAX + 31) / 32;
38    mtl::Buffer cU = F((size_t)HV * NCM * 32 * S), cW = F((size_t)HV * NCM * 32 * S), clg = F((size_t)HV * NCM * 32),
39                cD = F((size_t)HV * NCM * 32 * S);
40    ref::Rng r(21);
41    for (size_t i = 0; i < (size_t)TMAX * CH; ++i) qkv.as<float>()[i] = r.sym() * 2.0f;
42    for (int i = 0; i < TMAX * HV; ++i) { al.as<float>()[i] = r.sym() * 3.0f; be.as<float>()[i] = r.sym() * 2.0f; }
43    for (size_t i = 0; i < (size_t)TMAX * HV * S; ++i) z.as<float>()[i] = r.sym() * 2.0f;
44    for (int i = 0; i < CH * 4; ++i) cw.as<float>()[i] = r.sym() * 0.6f;
45    for (int i = 0; i < HV; ++i) { dt.as<float>()[i] = r.sym(); sa.as<float>()[i] = -0.2f - r.uni() * 2.0f; }
46    for (int i = 0; i < S; ++i) gam.as<float>()[i] = 0.5f + r.uni();
47    for (int i = 0; i < S * HV * S; ++i) st0.as<float>()[i] = r.sym() * 0.1f;
48    for (int i = 0; i < CH * 3; ++i) h0.as<float>()[i] = r.sym();
49    auto prompt_ds = [&](int T, const mtl::Pipeline& pre, const mtl::Pipeline& scan, const mtl::Pipeline& post, int cb,
50                         std::vector<mtl::Dispatch>& ds) {
51        GdnPArgs a{(uint32_t)T, HK, HV, CH, 1e-6f, 1u};
52        mtl::Dispatch d1;
53        d1.p = &pre;
54        d1.args = {mtl::Arg::B(qkv), mtl::Arg::B(hB), mtl::Arg::B(cw), mtl::Arg::B(al), mtl::Arg::B(be), mtl::Arg::B(dt),
55                   mtl::Arg::B(sa), mtl::Arg::B(qn), mtl::Arg::B(kn), mtl::Arg::B(vc), mtl::Arg::B(gb), mtl::Arg::B(kq),
56                   mtl::Arg::B(hA2), mtl::Arg::V(a)};
57        d1.grid[0] = HK + HV / 2;
58        d1.grid[1] = T;
59        d1.tg[0] = 256;
60        ds.push_back(d1);
61        if (cb == -100) {   // the chunked form: gdn_cprep, gdn_cstate, gdn_cout
62            const uint32_t nc = (T + 31) / 32;
63            static mtl::Pipeline pcp = cx.pipeline(lib, "gdn_cprep"), pcs = cx.pipeline(lib, "gdn_cstate"),
64                                 pco = cx.pipeline(lib, "gdn_cout");
65            mtl::Dispatch e1; e1.p = &pcp;
66            e1.args = {mtl::Arg::B(qn), mtl::Arg::B(kn), mtl::Arg::B(vc), mtl::Arg::B(gb), mtl::Arg::B(cU), mtl::Arg::B(cW),
67                       mtl::Arg::B(clg), mtl::Arg::V(a)};
68            e1.grid[0] = HV; e1.grid[1] = nc; e1.tg[0] = 256; ds.push_back(e1);
69            mtl::Dispatch e2; e2.p = &pcs;
70            e2.args = {mtl::Arg::B(stB), mtl::Arg::B(qn), mtl::Arg::B(kn), mtl::Arg::B(cU), mtl::Arg::B(cW), mtl::Arg::B(clg),
71                       mtl::Arg::B(cD), mtl::Arg::B(o), mtl::Arg::V(a)};
72            e2.grid[0] = HV * 4; e2.tg[0] = 256; ds.push_back(e2);
73            mtl::Dispatch e3; e3.p = &pco;
74            e3.args = {mtl::Arg::B(qn), mtl::Arg::B(kn), mtl::Arg::B(cD), mtl::Arg::B(clg), mtl::Arg::B(o), mtl::Arg::V(a)};
75            e3.grid[0] = HV; e3.grid[1] = nc; e3.tg[0] = 128; ds.push_back(e3);
76        } else {
77        mtl::Dispatch d2;
78        d2.p = &scan;
79        d2.args = {mtl::Arg::B(stB), mtl::Arg::B(qn), mtl::Arg::B(kn), mtl::Arg::B(vc), mtl::Arg::B(gb), mtl::Arg::B(kq),
80                   mtl::Arg::B(o), mtl::Arg::V(a)};
81        // cb > 0: gdn_scan_<cb> (cb column blocks of 32 a threadgroup); cb < 0: gdn_scanr_<-cb> (-cb row blocks)
82        d2.grid[0] = cb > 0 ? HV * 4 / cb : HV * 4;
83        d2.tg[0] = 32 * (cb > 0 ? cb : -cb);
84        ds.push_back(d2);
85        }
86        mtl::Dispatch d3;
87        d3.p = &post;
88        d3.args = {mtl::Arg::B(o), mtl::Arg::B(z), mtl::Arg::B(gam), mtl::Arg::B(yh), mtl::Arg::B(yB), mtl::Arg::V(a)};
89        d3.grid[0] = HV;
90        d3.grid[1] = T;
91        d3.tg[0] = 128;
92        ds.push_back(d3);
93    };
94    mtl::Pipeline pre = cx.pipeline(lib, "gdn_pre"), post = cx.pipeline(lib, "gdn_post");
95    int fails = 0;
96    if (!bench)
97        for (int T : {1, 3, 37, 300})
98            for (int cb : {1, 4, -2, -4, -8, -9, -100}) {
99                mtl::Constants pc;
100                if (cb < 0 && cb != -9) pc.i(6, 0);
101                mtl::Pipeline scan = cx.pipeline(lib, cb == -100 ? std::string("gdn_scanr_4") : cb == -9 ? std::string("gdn_scan_v") : cb > 0 ? "gdn_scan_" + std::to_string(cb) : "gdn_scanr_" + std::to_string(-cb), cb == -100 ? mtl::Constants().i(6, 0) : pc);
102                if (cb == -9) cb = -8;
103                mtl::Pipeline step = cx.pipeline(lib, "gdn_step", mtl::Constants().i(2, T));
104                std::copy(st0.as<float>(), st0.as<float>() + S * HV * S, stA.as<float>());
105                std::copy(st0.as<float>(), st0.as<float>() + S * HV * S, stB.as<float>());
106                std::copy(h0.as<float>(), h0.as<float>() + CH * 3, hA.as<float>());
107                std::copy(h0.as<float>(), h0.as<float>() + CH * 3, hB.as<float>());
108                GdnArgs da{HK, HV, CH, 1, 1e-6f, 0};
109                mtl::Dispatch d;
110                d.p = &step;
111                d.args = {mtl::Arg::B(stA), mtl::Arg::B(hA), mtl::Arg::B(qkv), mtl::Arg::B(al), mtl::Arg::B(be), mtl::Arg::B(z),
112                          mtl::Arg::B(cw), mtl::Arg::B(dt), mtl::Arg::B(sa), mtl::Arg::B(gam), mtl::Arg::B(yA), mtl::Arg::V(da),
113                          mtl::Arg::B(hA2)};
114                d.grid[0] = HV;
115                d.tg[0] = 512;
116                cx.run({d});
117                std::vector<float> hdec(hA2.as<float>(), hA2.as<float>() + CH * 3);
118                std::vector<mtl::Dispatch> ds;
119                prompt_ds(T, pre, scan, post, cb, ds);
120                cx.run(ds);
121                auto rel = [](const float* a, const float* b, size_t n) {
122                    double se = 0, sr = 0;
123                    for (size_t i = 0; i < n; ++i) { se += (double)(a[i] - b[i]) * (a[i] - b[i]); sr += (double)b[i] * b[i]; }
124                    return std::sqrt(se / std::max(sr, 1e-30));
125                };
126                const double ry = rel(yB.as<float>(), yA.as<float>(), (size_t)T * HV * S),
127                             rs = rel(stB.as<float>(), stA.as<float>(), S * HV * S), rh = rel(hA2.as<float>(), hdec.data(), CH * 3);
128                double ryh = 0, syh = 0;
129                for (size_t i = 0; i < (size_t)T * HV * S; ++i) {
130                    const double e = ref::f16_to_f32(yh.as<uint16_t>()[i]) - yA.as<float>()[i];
131                    ryh += e * e;
132                    syh += (double)yA.as<float>()[i] * yA.as<float>()[i];
133                }
134                const bool ok = ry < 1e-5 && rs < 1e-5 && rh == 0 && std::sqrt(ryh / syh) < 1e-3;
135                fails += !ok;
136                std::printf("T %3d, scan CB %d: y rel %.2e (fp16 %.2e), state rel %.2e, history %s  %s\n", T, cb, ry,
137                            std::sqrt(ryh / syh), rs, rh == 0 ? "exact" : "DIFFERS", ok ? "PASS" : "FAIL");
138            }
139    if (fails || !bench) {
140        std::printf("%s\n", fails ? "SOME FAILED" : "ALL PASS");
141        return fails ? 1 : 0;
142    }
143    // speed, T = 2048: the decode step over the chunk vs the three passes (each scan width)
144    const int T = 2048;
145    mtl::Pipeline step = cx.pipeline(lib, "gdn_step", mtl::Constants().i(2, T));
146    GdnArgs da{HK, HV, CH, 1, 1e-6f, 0};
147    mtl::Dispatch d;
148    d.p = &step;
149    d.args = {mtl::Arg::B(stA), mtl::Arg::B(hA), mtl::Arg::B(qkv), mtl::Arg::B(al), mtl::Arg::B(be), mtl::Arg::B(z),
150              mtl::Arg::B(cw), mtl::Arg::B(dt), mtl::Arg::B(sa), mtl::Arg::B(gam), mtl::Arg::B(yA), mtl::Arg::V(da), mtl::Arg::B(hA2)};
151    d.grid[0] = HV;
152    d.tg[0] = 512;
153    auto timeit = [&](const std::vector<mtl::Dispatch>& ds) {
154        cx.warm(ds, 0.3);
155        std::vector<double> t;
156        for (int i = 0; i < 5; ++i) t.push_back(cx.run(ds));
157        return median(t);
158    };
159    std::printf("T %d: decode step over the chunk %.2f ms\n", T, timeit({d}) * 1e3);
160    for (const char* nm : {"gdn_scanr_4", "chunked", "gdn_scanr_4", "chunked"}) {
161        const bool ch = std::string(nm) == "chunked";
162        const int cb = ch ? -100 : nm[9] == 'v' ? -8 : nm[8] == 'r' ? -(nm[10] - '0') : nm[9] - '0';
163        mtl::Constants pc;
164        if (cb < 0 && nm[9] != 'v') pc.i(6, std::getenv("GDN_PROBE") ? std::atoi(std::getenv("GDN_PROBE")) : 0);
165        mtl::Pipeline scan = cx.pipeline(lib, ch ? "gdn_scanr_4" : nm, pc);
166        std::vector<mtl::Dispatch> ds;
167        prompt_ds(T, pre, scan, post, cb, ds);
168        const double all = timeit(ds), tp = timeit({ds[0]}),
169                     ts = timeit(std::vector<mtl::Dispatch>(ds.begin() + 1, ds.end() - 1)), to = timeit({ds.back()});
170        if (ch) std::printf("  chunked parts: cprep %.3f, cstate %.3f, cout %.3f ms\n", timeit({ds[1]}) * 1e3, timeit({ds[2]}) * 1e3,
171                            timeit({ds[3]}) * 1e3);
172        std::printf("T %d, %-13s: pre %.3f + scan %.3f + post %.3f ms = %.3f ms together\n", T, nm, tp * 1e3, ts * 1e3,
173                    to * 1e3, all * 1e3);
174    }
175    return 0;
176}