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
11.9 KiB214 linesraw
1// metal/tests/gdn_parity.cpp - the fused GDN layer step (gdn.metal) against a double-precision CPU reference of the
2// native contract, the window properties, and its speed.
3//
4//   gdn_parity            parity for windows of 1..4 tokens: y, the committed state and conv history; a verify
5//                         window leaves the state untouched; its first m outputs are bitwise a fold of m
6//   gdn_parity --bench    GPU time per layer: 36 distinct layer states rotated (113 MB, beyond the SLC)
7#include "mtl_rt.h"
8#include "ref_quant.h"
9#include "engine/geo.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 S = strata_metal::geo::SS, HK = strata_metal::geo::HK, HV = strata_metal::geo::HV, C = (2 * HK + HV) * S, MAXT = 8;
21struct GdnArgs { uint32_t h_k, h_v, channels, commit; float eps; uint32_t plane; };
22double median(std::vector<double> v) { std::sort(v.begin(), v.end()); return v[v.size() / 2]; }
23struct Err {
24    double se = 0, sr = 0;
25    void add(double g, double r) { se += (g - r) * (g - r); sr += r * r; }
26    double l2() const { return sr > 0 ? std::sqrt(se / sr) : std::sqrt(se); }
27};
28}  // namespace
29
30int main(int argc, char** argv) {
31    const bool bench = argc > 1 && std::string(argv[1]) == "--bench";
32    mtl::Context cx;
33    const int lib = cx.compile({"gdn.metal"}, "#define NO_GGML_COMMON 1\n");
34    std::printf("device %s\n", cx.device_name().c_str());
35    const int LAYERS = bench ? 36 : 1;
36    const size_t st_elems = (size_t)S * HV * S;
37    mtl::Buffer state = cx.alloc(4 * st_elems * LAYERS), st0 = cx.alloc(4 * st_elems), hist = cx.alloc(4 * C * 3 * LAYERS),
38                h0 = cx.alloc(4 * C * 3), qkv = cx.alloc(4 * C * MAXT), al = cx.alloc(4 * HV * MAXT),
39                be = cx.alloc(4 * HV * MAXT), z = cx.alloc(4 * HV * S * MAXT), cw = cx.alloc(4 * C * 4),
40                dt = cx.alloc(4 * HV), sa = cx.alloc(4 * HV), gm = cx.alloc(4 * S), y = cx.alloc(4 * HV * S * MAXT),
41                y2 = cx.alloc(4 * HV * S * MAXT), hist2 = cx.alloc(4 * C * 3 * LAYERS);
42    ref::Rng r(17);
43    for (size_t i = 0; i < st_elems; ++i) st0.as<float>()[i] = r.sym() * 0.1f;
44    for (int i = 0; i < C * 3; ++i) h0.as<float>()[i] = r.sym();
45    for (int i = 0; i < C * MAXT; ++i) qkv.as<float>()[i] = r.sym() * 2.0f;
46    for (int i = 0; i < HV * MAXT; ++i) { al.as<float>()[i] = r.sym() * 2.0f; be.as<float>()[i] = r.sym() * 2.0f; }
47    for (int i = 0; i < HV * S * MAXT; ++i) z.as<float>()[i] = r.sym() * 2.0f;
48    for (int i = 0; i < C * 4; ++i) cw.as<float>()[i] = r.sym() * 0.5f;
49    for (int i = 0; i < HV; ++i) { dt.as<float>()[i] = r.sym(); sa.as<float>()[i] = -std::exp(r.sym()); }
50    for (int i = 0; i < S; ++i) gm.as<float>()[i] = 1.0f + 0.2f * r.sym();
51    for (int l = 0; l < LAYERS; ++l) {
52        std::memcpy(state.as<float>() + l * st_elems, st0.ptr, 4 * st_elems);
53        std::memcpy(hist.as<float>() + l * C * 3, h0.ptr, 4 * C * 3);
54    }
55    auto disp = [&](const mtl::Pipeline& p, int layer, int commit, const mtl::Buffer& out) {
56        GdnArgs a{HK, HV, C, (uint32_t)commit, 1e-6f, 0};
57        mtl::Dispatch d;
58        d.p = &p;
59        d.args = {mtl::Arg::B(state, 4 * st_elems * layer), mtl::Arg::B(hist, 4 * (size_t)C * 3 * layer), mtl::Arg::B(qkv),
60                  mtl::Arg::B(al), mtl::Arg::B(be), mtl::Arg::B(z), mtl::Arg::B(cw), mtl::Arg::B(dt), mtl::Arg::B(sa),
61                  mtl::Arg::B(gm), mtl::Arg::B(out), mtl::Arg::V(a), mtl::Arg::B(hist2, 4 * (size_t)C * 3 * layer)};
62        d.grid[0] = HV;
63        d.tg[0] = std::getenv("GDN_IB8") ? 1024 : 512;
64        return d;
65    };
66    {
67        // every specialization the engine launches (GDN_NTOK 1..8): an M2 Max gave 448 for ntok >= 2 (#2323)
68        const char* kn = std::getenv("GDN_IB8") ? "gdn_step8" : "gdn_step";
69        const int need = std::getenv("GDN_IB8") ? 1024 : 512;
70        int low = 0;
71        for (int nt = 1; nt <= 8; ++nt) {
72            mtl::Pipeline pn = cx.pipeline(lib, kn, mtl::Constants().i(2, nt));
73            std::printf("%s pipeline GDN_NTOK %d: max %d threads per threadgroup (the kernel needs %d)%s\n", kn, nt, pn.max_threads,
74                        need, pn.max_threads < need ? "  TOO FEW" : "");
75            low += pn.max_threads < need;
76        }
77        if (low) {
78            std::printf("gdn parity: %d specialization(s) cannot run with %d threads on this GPU: FAIL\n", low, need);
79            return 1;
80        }
81    }
82    if (bench) {
83        for (int nt : {1, 2, 3, 4}) {
84            const char* kn = std::getenv("GDN_IB8") ? "gdn_step8" : "gdn_step";
85            mtl::Pipeline p = cx.pipeline(lib, kn, mtl::Constants().i(2, nt));
86            for (int commit : {1, 0}) {
87                std::vector<mtl::Dispatch> ds;
88                for (int k = 0; k < 72; ++k) ds.push_back(disp(p, k % LAYERS, commit, y));
89                cx.warm(ds, 0.1);
90                std::vector<double> t;
91                for (int i = 0; i < 7; ++i) t.push_back(cx.run(ds) / 72);
92                const double m = median(t), bytes = 4.0 * st_elems * (commit ? 2 : 1);
93                std::printf("gdn_step ntok %d %-7s %7.2f us per layer  state %.1f MB at %6.1f GB/s  (x36 layers: %.3f ms)\n",
94                            nt, commit ? "commit" : "verify", m * 1e6, bytes / 1e6, bytes / m / 1e9, 36 * m * 1e3);
95            }
96        }
97        return 0;
98    }
99    int fails = 0;
100    for (int nt = 1; nt <= 4; ++nt) {
101        mtl::Pipeline p = cx.pipeline(lib, std::getenv("GDN_IB8") ? "gdn_step8" : "gdn_step", mtl::Constants().i(2, nt));
102        // determinism: the same verify call three times
103        {
104            std::memcpy(state.ptr, st0.ptr, 4 * st_elems);
105            std::memcpy(hist.ptr, h0.ptr, 4 * C * 3);
106            cx.run({disp(p, 0, 0, y2)});
107            std::vector<float> first((float*)y2.ptr, (float*)y2.ptr + HV * S * nt);
108            int diff = 0;
109            for (int k = 0; k < 2; ++k) {
110                cx.run({disp(p, 0, 0, y2)});
111                diff += std::memcmp(first.data(), y2.ptr, 4 * HV * S * nt) != 0;
112            }
113            if (diff) std::printf("  ntok %d: NOT deterministic (%d of 2 repeats differ)\n", nt, diff);
114        }
115        // verify: state untouched
116        std::memcpy(state.ptr, st0.ptr, 4 * st_elems);
117        std::memcpy(hist.ptr, h0.ptr, 4 * C * 3);
118        cx.run({disp(p, 0, 0, y2)});
119        const bool untouched = std::memcmp(state.ptr, st0.ptr, 4 * st_elems) == 0 && std::memcmp(hist.ptr, h0.ptr, 4 * C * 3) == 0;
120        cx.run({disp(p, 0, 1, y)});
121        const bool same_y = std::memcmp(y.ptr, y2.ptr, 4 * HV * S * nt) == 0;
122        // the reference
123        std::vector<double> Sd(st_elems), Hd(C * 3);
124        for (size_t i = 0; i < st_elems; ++i) Sd[i] = st0.as<float>()[i];
125        for (int i = 0; i < C * 3; ++i) Hd[i] = h0.as<float>()[i];
126        Err ey, es, eh;
127        for (int t = 0; t < nt; ++t) {
128            std::vector<double> cv(C);
129            for (int c = 0; c < C; ++c) {
130                const double in = qkv.as<float>()[t * C + c];
131                double s = Hd[c * 3] * cw.as<float>()[c * 4] + Hd[c * 3 + 1] * cw.as<float>()[c * 4 + 1] +
132                           Hd[c * 3 + 2] * cw.as<float>()[c * 4 + 2] + in * cw.as<float>()[c * 4 + 3];
133                cv[c] = s / (1.0 + std::exp(-s));
134                Hd[c * 3] = Hd[c * 3 + 1];
135                Hd[c * 3 + 1] = Hd[c * 3 + 2];
136                Hd[c * 3 + 2] = in;
137            }
138            for (int hh = 0; hh < 2 * HK; ++hh) {
139                double ss = 0;
140                for (int i = 0; i < S; ++i) ss += cv[hh * S + i] * cv[hh * S + i];
141                const double rs = 1.0 / std::sqrt(ss / S + 1e-6 / S);
142                for (int i = 0; i < S; ++i) cv[hh * S + i] = cv[hh * S + i] * rs / std::sqrt((double)S);
143            }
144            for (int h = 0; h < HV; ++h) {
145                const int hk = h % HK;
146                const double* q = &cv[hk * S];
147                const double* k = &cv[HK * S + hk * S];
148                const double* v = &cv[2 * HK * S + h * S];
149                const double av = (double)al.as<float>()[t * HV + h] + dt.as<float>()[h];
150                const double sp = av > 20 ? av : std::log1p(std::exp(av));
151                const double g = std::exp(sp * sa.as<float>()[h]);
152                const double b = 1.0 / (1.0 + std::exp(-(double)be.as<float>()[t * HV + h]));
153                std::vector<double> o(S);
154                for (int jj = 0; jj < S; ++jj) {
155                    double kv = 0;
156                    for (int i = 0; i < S; ++i) kv += Sd[((size_t)i * HV + h) * S + jj] * k[i];
157                    const double delta = (v[jj] - g * kv) * b;
158                    double acc = 0;
159                    for (int i = 0; i < S; ++i) {
160                        double& sv = Sd[((size_t)i * HV + h) * S + jj];
161                        sv = g * sv + k[i] * delta;
162                        acc += sv * q[i];
163                    }
164                    o[jj] = acc / std::sqrt((double)S);
165                }
166                double ss = 0;
167                for (int jj = 0; jj < S; ++jj) ss += o[jj] * o[jj];
168                const double rs = 1.0 / std::sqrt(ss / S + 1e-6);
169                for (int jj = 0; jj < S; ++jj) {
170                    const double zz = z.as<float>()[t * HV * S + h * S + jj];
171                    ey.add(y.as<float>()[t * HV * S + h * S + jj], o[jj] * rs * gm.as<float>()[jj] / (1.0 + std::exp(-zz)));
172                }
173            }
174        }
175        for (size_t i = 0; i < st_elems; ++i) es.add(state.as<float>()[i], Sd[i]);
176        for (int i = 0; i < C * 3; ++i) eh.add(hist2.as<float>()[i], Hd[i]);
177        // fold property: a window of nt + 1 tokens (no commit) gives bitwise the same first nt outputs
178        bool prefix = true;
179        if (nt < 4) {
180            mtl::Pipeline p2 = cx.pipeline(lib, std::getenv("GDN_IB8") ? "gdn_step8" : "gdn_step", mtl::Constants().i(2, nt + 1));
181            std::memcpy(state.ptr, st0.ptr, 4 * st_elems);
182            std::memcpy(hist.ptr, h0.ptr, 4 * C * 3);
183            cx.run({disp(p2, 0, 0, y2)});
184            prefix = std::memcmp(y.ptr, y2.ptr, 4 * HV * S * nt) == 0;
185        }
186        // partial commit (commit = 0x100 | k): the state and history after the first k tokens, bitwise those of a
187        // k-token commit; y bitwise the verify window's
188        bool partial = true;
189        for (int k = 1; k < nt; ++k) {
190            mtl::Pipeline pk = cx.pipeline(lib, std::getenv("GDN_IB8") ? "gdn_step8" : "gdn_step", mtl::Constants().i(2, k));
191            mtl::Pipeline pn = cx.pipeline(lib, std::getenv("GDN_IB8") ? "gdn_step8" : "gdn_step", mtl::Constants().i(2, nt));
192            std::memcpy(state.ptr, st0.ptr, 4 * st_elems);
193            std::memcpy(hist.ptr, h0.ptr, 4 * C * 3);
194            cx.run({disp(pk, 0, 1, y2)});
195            std::vector<float> sk(state.as<float>(), state.as<float>() + st_elems), hk(hist2.as<float>(), hist2.as<float>() + C * 3);
196            std::memcpy(state.ptr, st0.ptr, 4 * st_elems);
197            cx.run({disp(pn, 0, 0, y)});
198            std::vector<float> yv(y.as<float>(), y.as<float>() + HV * S * nt);
199            std::memcpy(state.ptr, st0.ptr, 4 * st_elems);
200            std::memset(hist2.ptr, 0xFF, 4 * C * 3);
201            cx.run({disp(pn, 0, 0x100 | k, y2)});
202            partial = partial && std::memcmp(state.ptr, sk.data(), 4 * st_elems) == 0 &&
203                      std::memcmp(hist2.ptr, hk.data(), 4 * C * 3) == 0 && std::memcmp(y2.ptr, yv.data(), 4 * HV * S * nt) == 0;
204        }
205        const bool ok = untouched && same_y && prefix && partial && ey.l2() < 1e-5 && es.l2() < 1e-5 && eh.l2() == 0;
206        fails += !ok;
207        std::printf("gdn parity ntok %d: y rel L2 %.2e, state %.2e, history %.1e; verify leaves state: %s, verify y == "
208                    "commit y: %s, first %d of a longer window bitwise: %s, partial commits bitwise: %s  %s\n", nt, ey.l2(), es.l2(),
209                    eh.l2(), untouched ? "yes" : "NO", same_y ? "yes" : "NO", nt, prefix ? "yes" : "NO", partial ? "yes" : "NO",
210                    ok ? "PASS" : "FAIL");
211    }
212    std::printf("%s\n", fails ? "SOME FAILED" : "ALL PASS");
213    return fails ? 1 : 0;
214}