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
15.7 KiB310 linesraw
1// metal/tests/qsa_parity.cpp - QSA decode (qsa.metal) stage by stage against a CPU reference, and its speed.
2//
3//   qsa_parity [P]          a context of P cells built by qsa_prep (default 3000: the selection is active above
4//                           2051), then a window of 3 tokens: prep, score, top-k, attention, merge.  Each stage is
5//                           checked against the CPU fed with the GPU's inputs to that stage; the ids exactly.
6//   qsa_parity --bench [P]  GPU time of the window's kernels at context P, 1 and 3 tokens
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 QH = strata_metal::geo::QH, QKV = strata_metal::geo::QKV, QD = strata_metal::geo::QD, IH = strata_metal::geo::IH, ID = strata_metal::geo::ID,
21              BUDGET = strata_metal::geo::BUD, CH = 64, NCH = (BUDGET + CH - 1) / CH;
22struct QsaArgs { uint32_t pos0, pos_base, max_cells, n_tok; float eps; };
23double median(std::vector<double> v) { std::sort(v.begin(), v.end()); return v[v.size() / 2]; }
24struct Err {
25    double se = 0, sr = 0;
26    void add(double g, double r) { se += (g - r) * (g - r); sr += r * r; }
27    double l2() const { return sr > 0 ? std::sqrt(se / sr) : std::sqrt(se); }
28};
29float h2f(uint16_t h) { return ref::f16_to_f32(h); }
30}  // namespace
31
32int main(int argc, char** argv) {
33    bool bench = false;
34    int P = 3000;
35    for (int i = 1; i < argc; ++i) {
36        std::string a = argv[i];
37        if (a == "--bench") bench = true;
38        else P = std::atoi(argv[i]);
39    }
40    const int MAXT = 8, MAXC = std::max(4096, (P + 64) / 4 * 4 + 64);
41    mtl::Context cx;
42    const int lib = cx.compile({"qsa.metal", "qsa2.metal"}, strata_metal::geo::prelude() + "#define NO_GGML_COMMON 1\n");
43    // QSA_TOPK=1: the v1 top-k; QSA_ATTN=1|2|3 (default 3): which attention (2 has its own chunking and merge)
44    const int av = std::getenv("QSA_ATTN") ? std::atoi(std::getenv("QSA_ATTN")) : 1;
45    const bool v2 = av == 2;
46    mtl::Pipeline pprep = cx.pipeline(lib, "qsa_prep", mtl::Constants().b(24, std::getenv("QSA_MROPE") != nullptr)), pscore = cx.pipeline(lib, "qsa_score"),
47                  ptopk = cx.pipeline(lib, std::getenv("QSA_TOPK") ? "qsa_topk" : "qsa_topk2"),
48                  pattn = cx.pipeline(lib, av == 1 ? "qsa_attn" : av == 2 ? "qsa_attn2" : "qsa_attn3"),
49                  pmerge = cx.pipeline(lib, v2 ? "qsa_merge2" : "qsa_merge");
50    const int MB = MAXC / 4 + 2;
51    // per-cell inputs for every cell (context + window)
52    const int NC = P + MAXT;
53    mtl::Buffer qfull = cx.alloc(4 * (size_t)NC * QH * 2 * QD), kc = cx.alloc(4 * (size_t)NC * QKV * QD),
54                vc = cx.alloc(4 * (size_t)NC * QKV * QD), iq = cx.alloc(4 * (size_t)NC * IH * ID),
55                ik = cx.alloc(4 * (size_t)NC * ID), qn = cx.alloc(4 * QD), kn = cx.alloc(4 * QD), iqn = cx.alloc(4 * ID),
56                ikn = cx.alloc(4 * ID), cs = cx.alloc(8 * (size_t)(MAXC + 16) * 32), qcur = cx.alloc(4 * MAXT * QH * QD),
57                qidx = cx.alloc(4 * MAXT * IH * ID), kq = cx.alloc((size_t)MAXC * QKV * QD), vq = cx.alloc((size_t)MAXC * QKV * QD),
58                ksc = cx.alloc(2 * (size_t)MAXC * QKV * 4), vsc = cx.alloc(2 * (size_t)MAXC * QKV * 4), tail = cx.alloc(4 * 4 * ID),
59                dead = cx.alloc(4 * ID), pooled = cx.alloc(4 * (size_t)MB * ID), scores = cx.alloc(4 * (size_t)MAXT * MB),
60                ids = cx.alloc(4 * MAXT * BUDGET), part = cx.alloc(4 * (size_t)MAXT * 2 * NCH * QH * (QD + 2)),
61                xp = cx.alloc(4 * (4 * MAXT * QH * QD + MAXT * QH * QD / 16));
62    ref::Rng r(23);
63    for (size_t i = 0; i < qfull.bytes / 4; ++i) qfull.as<float>()[i] = r.sym() * 2.0f;
64    for (size_t i = 0; i < kc.bytes / 4; ++i) kc.as<float>()[i] = r.sym() * 2.0f;
65    for (size_t i = 0; i < vc.bytes / 4; ++i) vc.as<float>()[i] = r.sym();
66    for (size_t i = 0; i < iq.bytes / 4; ++i) iq.as<float>()[i] = r.sym();
67    for (size_t i = 0; i < ik.bytes / 4; ++i) ik.as<float>()[i] = r.sym();
68    for (int i = 0; i < QD; ++i) { qn.as<float>()[i] = 1.0f + 0.2f * r.sym(); kn.as<float>()[i] = 1.0f + 0.2f * r.sym(); }
69    for (int i = 0; i < ID; ++i) { iqn.as<float>()[i] = 1.0f + 0.2f * r.sym(); ikn.as<float>()[i] = 1.0f + 0.2f * r.sym(); }
70    const uint32_t pos_base = 0;
71    // QSA_MROPE=1: qsa_prep with the M-RoPE table (function constant 24): random (t, h, w) positions per cell, the CPU
72    // reference rotating pair i by row tab[cell * 3 + i % 3]; QSA_MROPE=id: the identity table, checked bitwise
73    // against the plain kernel
74    const char* mre = std::getenv("QSA_MROPE");
75    const bool mrope = mre != nullptr, mid = mrope && std::string(mre) == "id";
76    mtl::Buffer mtab = cx.alloc(4 * 3 * (size_t)(MAXC + 16));
77    {
78        ref::Rng rm(77);
79        for (int c = 0; c < MAXC + 16; ++c)
80            for (int k = 0; k < 3; ++k) mtab.as<int>()[c * 3 + k] = mid ? c : (int)(rm.next() % (uint64_t)(MAXC + 16));
81    }
82    for (int p = 0; p < MAXC + 16; ++p)
83        for (int i = 0; i < 32; ++i) {
84            const double inv = std::pow(1e7, -2.0 * i / 64.0), th = (double)p * inv;
85            cs.as<float>()[(p * 32 + i) * 2] = (float)std::cos(th);
86            cs.as<float>()[(p * 32 + i) * 2 + 1] = (float)std::sin(th);
87        }
88    auto prep = [&](uint32_t pos0, int nt) {
89        QsaArgs a{pos0, pos_base, (uint32_t)MAXC, (uint32_t)nt, 1e-6f};
90        mtl::Dispatch d;
91        d.p = &pprep;
92        d.args = {mtl::Arg::B(qfull, 4 * (size_t)pos0 * QH * 2 * QD), mtl::Arg::B(kc, 4 * (size_t)pos0 * QKV * QD),
93                  mtl::Arg::B(vc, 4 * (size_t)pos0 * QKV * QD), mtl::Arg::B(iq, 4 * (size_t)pos0 * IH * ID),
94                  mtl::Arg::B(ik, 4 * (size_t)pos0 * ID), mtl::Arg::B(qn), mtl::Arg::B(kn), mtl::Arg::B(iqn),
95                  mtl::Arg::B(ikn), mtl::Arg::B(cs), mtl::Arg::B(qcur), mtl::Arg::B(qidx), mtl::Arg::B(kq),
96                  mtl::Arg::B(vq), mtl::Arg::B(ksc), mtl::Arg::B(vsc), mtl::Arg::B(tail), mtl::Arg::B(dead),
97                  mtl::Arg::B(pooled), mtl::Arg::V(a), mtl::Arg::B(mtab)};
98        d.grid[0] = strata_metal::geo::QPREP;
99        d.grid[1] = nt;
100        d.tg[0] = 256;
101        return d;
102    };
103    auto window = [&](uint32_t pos0, int nt, std::vector<mtl::Dispatch>& ds) {
104        QsaArgs a{pos0, pos_base, (uint32_t)MAXC, (uint32_t)nt, 1e-6f};
105        ds.push_back(prep(pos0, nt));
106        mtl::Dispatch s;
107        s.p = &pscore;
108        s.args = {mtl::Arg::B(qidx), mtl::Arg::B(pooled), mtl::Arg::B(dead), mtl::Arg::B(scores), mtl::Arg::V(a)};
109        s.grid[0] = ((pos0 + nt) / 4 + 1 + 7) / 8;
110        s.grid[1] = nt;
111        s.tg[0] = 256;
112        ds.push_back(s);
113        mtl::Dispatch k;
114        k.p = &ptopk;
115        k.args = {mtl::Arg::B(scores), mtl::Arg::B(ids), mtl::Arg::V(a)};
116        k.grid[0] = nt;
117        k.tg[0] = 1024;
118        ds.push_back(k);
119        mtl::Dispatch at;
120        at.p = &pattn;
121        at.args = {mtl::Arg::B(qcur), mtl::Arg::B(kq), mtl::Arg::B(vq), mtl::Arg::B(ksc), mtl::Arg::B(vsc),
122                   mtl::Arg::B(ids), mtl::Arg::B(part), mtl::Arg::V(a)};
123        at.grid[0] = v2 ? (BUDGET + 31) / 32 : NCH;
124        at.grid[1] = v2 ? QKV * 2 : QKV;
125        at.grid[2] = nt;
126        at.tg[0] = 256;
127        ds.push_back(at);
128        mtl::Dispatch m;
129        m.p = &pmerge;
130        m.args = {mtl::Arg::B(part), mtl::Arg::B(qfull, 4 * (size_t)pos0 * QH * 2 * QD), mtl::Arg::B(xp), mtl::Arg::V(a)};
131        m.grid[0] = QH;
132        m.grid[1] = nt;
133        m.tg[0] = 256;
134        ds.push_back(m);
135    };
136    // the context, one cell at a time
137    {
138        std::vector<mtl::Dispatch> ds;
139        for (int p = 0; p < P; ++p) ds.push_back(prep(p, 1));
140        cx.run(ds);
141    }
142    if (bench) {
143        std::printf("device %s, context %d cells\n", cx.device_name().c_str(), P);
144        for (int nt : {1, 3}) {
145            std::vector<mtl::Dispatch> ds;
146            window(P, nt, ds);
147            const char* names[] = {"prep", "score", "topk", "attn", "merge"};
148            double total = 0;
149            for (int i = 0; i < 5; ++i) {
150                std::vector<mtl::Dispatch> one(32, ds[i]);
151                cx.warm(one, 0.05);
152                std::vector<double> t;
153                for (int k = 0; k < 7; ++k) t.push_back(cx.run(one) / 32);
154                std::printf("  ntok %d %-6s %7.2f us\n", nt, names[i], median(t) * 1e6);
155                total += median(t);
156            }
157            std::vector<double> t;
158            for (int k = 0; k < 7; ++k) t.push_back(cx.run(ds));
159            std::printf("  ntok %d window (5 dependent dispatches): %.2f us (sum of parts %.2f)\n", nt, median(t) * 1e6,
160                        total * 1e6);
161        }
162        return 0;
163    }
164    const int NT = 3;
165    std::vector<mtl::Dispatch> ds;
166    window(P, NT, ds);
167    // stage by stage, re-reading GPU state in between
168    cx.run({ds[0]});
169    int fails = 0;
170    // ---- prep: qcur, qidx, the window cells' KV codes and the pooled keys vs CPU
171    {
172        Err eq, ei, ekv, ep;
173        auto normrope = [&](const float* x, const float* g, int w, int absp, bool rope, std::vector<double>& out) {
174            double ss = 0;
175            for (int i = 0; i < w; ++i) ss += (double)x[i] * x[i];
176            const double rs = 1.0 / std::sqrt(ss / w + 1e-6);
177            out.assign(w, 0.0);
178            for (int i = 0; i < w; ++i) out[i] = rs * x[i] * g[i];
179            if (rope)
180                for (int i = 0; i < 32; ++i) {
181                    const int pp = mrope ? mtab.as<int>()[absp * 3 + i % 3] : absp;
182                    const double c = cs.as<float>()[(pp * 32 + i) * 2], s = cs.as<float>()[(pp * 32 + i) * 2 + 1];
183                    const double a = out[i], b = out[i + 32];
184                    out[i] = a * c - b * s;
185                    out[i + 32] = a * s + b * c;
186                }
187        };
188        std::vector<double> o;
189        for (int t = 0; t < NT; ++t) {
190            const int cell = P + t;
191            for (int h = 0; h < QH; ++h) {
192                normrope(qfull.as<float>() + ((size_t)cell * QH + h) * 2 * QD, qn.as<float>(), QD, cell, true, o);
193                for (int i = 0; i < QD; ++i) eq.add(qcur.as<float>()[(t * QH + h) * QD + i], o[i]);
194            }
195            for (int h = 0; h < IH; ++h) {
196                normrope(iq.as<float>() + ((size_t)cell * IH + h) * ID, iqn.as<float>(), ID, cell, true, o);
197                for (int i = 0; i < ID; ++i) ei.add(qidx.as<float>()[(t * IH + h) * ID + i], o[i]);
198            }
199            for (int h = 0; h < QKV; ++h) {
200                normrope(kc.as<float>() + ((size_t)cell * QKV + h) * QD, kn.as<float>(), QD, cell, true, o);
201                for (int i = 0; i < QD; ++i) {
202                    const size_t row = (size_t)cell * QKV + h;
203                    const double deq = (double)(int8_t)kq.as<int8_t>()[row * QD + i] * h2f(ksc.as<uint16_t>()[row * 4 + i / 64]);
204                    ekv.add(deq, o[i]);
205                }
206            }
207        }
208        // pooled keys of the last few completed blocks
209        const int nb = (P + NT) / 4;
210        for (int b = std::max(0, nb - 8); b < nb; ++b) {
211            std::vector<float> m(ID);
212            for (int i = 0; i < ID; ++i)
213                m[i] = (((ik.as<float>()[(4 * b) * ID + i] + ik.as<float>()[(4 * b + 1) * ID + i]) +
214                         ik.as<float>()[(4 * b + 2) * ID + i]) + ik.as<float>()[(4 * b + 3) * ID + i]) * 0.25f;
215            normrope(m.data(), ikn.as<float>(), ID, 4 * b, true, o);
216            for (int i = 0; i < ID; ++i) ep.add(pooled.as<float>()[b * ID + i], o[i]);
217        }
218        // int8 quantization error is ~1/254 of max|x| per group: the KV check is a quantization tolerance
219        const bool ok = eq.l2() < 1e-5 && ei.l2() < 1e-5 && ep.l2() < 1e-5 && ekv.l2() < 6e-3;
220        fails += !ok;
221        std::printf("prep: q rel L2 %.2e, indexer q %.2e, pooled keys %.2e, K int8 (vs float) %.2e  %s\n", eq.l2(),
222                    ei.l2(), ep.l2(), ekv.l2(), ok ? "PASS" : "FAIL");
223    }
224    // ---- score
225    cx.run({ds[1]});
226    {
227        Err es;
228        for (int t = 0; t < NT; ++t) {
229            const int n_kv = P + t + 1, n_bid = n_kv / 4;
230            for (int b = 0; b <= n_bid; ++b) {
231                const float* key = b == n_bid ? dead.as<float>() : pooled.as<float>() + b * ID;
232                double s = 0;
233                for (int h = 0; h < IH; ++h) {
234                    double d = 0;
235                    for (int i = 0; i < ID; ++i) d += (double)qidx.as<float>()[(t * IH + h) * ID + i] * key[i];
236                    s += std::max(d, 0.0);
237                }
238                if (b == n_bid && (n_kv & 3)) {
239                    // float(s + 1e9) keeps no bits of s: only check that the bias is there
240                    if (!(scores.as<float>()[t * MB + b] >= 1e9f)) es.add(1.0, 0.0);
241                } else {
242                    es.add(scores.as<float>()[t * MB + b], s);
243                }
244            }
245        }
246        const bool ok = es.l2() < 1e-5;
247        fails += !ok;
248        std::printf("score: rel L2 %.2e (tail +1e9 checked separately)  %s\n", es.l2(), ok ? "PASS" : "FAIL");
249    }
250    // ---- top-k (exact, from the GPU's scores)
251    cx.run({ds[2]});
252    {
253        int bad = 0;
254        for (int t = 0; t < NT; ++t) {
255            const int n_kv = P + t + 1, n_bid = n_kv / 4, width = std::min(n_kv, BUDGET);
256            std::vector<int> cells(n_kv);
257            for (int c = 0; c < n_kv; ++c) cells[c] = c;
258            if (n_kv > BUDGET) {
259                const float* sc = scores.as<float>() + t * MB;
260                std::stable_sort(cells.begin(), cells.end(), [&](int x, int y) { return sc[x / 4] > sc[y / 4]; });
261                cells.resize(width);
262                std::sort(cells.begin(), cells.end());
263            }
264            (void)n_bid;
265            for (int i = 0; i < width; ++i) bad += ids.as<int>()[t * BUDGET + i] != cells[i];
266        }
267        fails += bad != 0;
268        std::printf("top-k: %d of %d ids differ (context %d: selection %s)  %s\n", bad, NT * std::min(P + 1, BUDGET), P,
269                    P + 1 > BUDGET ? "active" : "identity", bad ? "FAIL" : "PASS");
270    }
271    // ---- attention + merge (from the GPU's qcur, ids and KV codes)
272    cx.run({ds[3], ds[4]});
273    {
274        Err eo;
275        for (int t = 0; t < NT; ++t) {
276            const int n_kv = P + t + 1, width = std::min(n_kv, BUDGET);
277            for (int h = 0; h < QH; ++h) {
278                const int g = h / (QH / QKV);
279                std::vector<double> s(width);
280                double mx = -1e300;
281                for (int c = 0; c < width; ++c) {
282                    const size_t row = (size_t)ids.as<int>()[t * BUDGET + c] * QKV + g;
283                    double d = 0;
284                    for (int i = 0; i < QD; ++i)
285                        d += (double)qcur.as<float>()[(t * QH + h) * QD + i] * (int8_t)kq.as<int8_t>()[row * QD + i] *
286                             h2f(ksc.as<uint16_t>()[row * 4 + i / 64]);
287                    s[c] = d / 16.0;
288                    mx = std::max(mx, s[c]);
289                }
290                double l = 0;
291                for (int c = 0; c < width; ++c) l += (s[c] = std::exp(s[c] - mx));
292                for (int i = 0; i < QD; ++i) {
293                    double o = 0;
294                    for (int c = 0; c < width; ++c) {
295                        const size_t row = (size_t)ids.as<int>()[t * BUDGET + c] * QKV + g;
296                        o += s[c] * (int8_t)vq.as<int8_t>()[row * QD + i] * h2f(vsc.as<uint16_t>()[row * 4 + i / 64]);
297                    }
298                    o /= l;
299                    const double gate = qfull.as<float>()[((size_t)(P + t) * QH + h) * 2 * QD + QD + i];
300                    eo.add(xp.as<float>()[t * QH * QD + h * QD + i], o / (1.0 + std::exp(-gate)));
301                }
302            }
303        }
304        const bool ok = eo.l2() < 1e-5;
305        fails += !ok;
306        std::printf("attention + gate: rel L2 %.2e  %s\n", eo.l2(), ok ? "PASS" : "FAIL");
307    }
308    std::printf("%s\n", fails ? "SOME FAILED" : "ALL PASS");
309    return fails ? 1 : 0;
310}