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
12.9 KiB224 linesraw
1// metal/tests/prompt_parity.cpp - the prompt-chunk glue (prompt.metal) against CPU references:
2//   route_topk           softmax + top 10 + renormalised weights (moe_route's rule) for 300 tokens, a third of them
3//                        with exact ties
4//   the HC read as GEMMs gr_norm -> act_f16 -> [w_down; w_inject] GEMM -> gr_epi_down -> w_up GEMM -> gr_epi_up, on
5//                        random BF16 weights, vs the exact formula (fp64) - the fp16 operands set the tolerance
6//   swiglu_h, moe_out    elementwise
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 <vector>
15
16namespace {
17constexpr int N = strata_metal::geo::N, HC = strata_metal::geo::HC, LR = strata_metal::geo::LR, TK = strata_metal::geo::TOPK;
18struct GrArgs { uint32_t n_embd, hc, hc_lr, n_tok, apply; float eps; };
19struct EpiArgs { uint32_t n_tok, n_embd, hc, hc_lr; };
20struct DqArgs { uint32_t n_in, n_out, row_bytes, perm; };
21struct GemmArgs { int M, N, K, pad; };
22double sig(double v) { return 1.0 / (1.0 + std::exp(-v)); }
23}  // namespace
24
25int main() {
26    mtl::Context cx;
27    const int lib = cx.compile({"quant.metal", "units.metal", "mma.metal", "dense_mm.metal", "gr.metal", "prompt.metal"}, strata_metal::geo::prelude());
28    std::printf("device %s\n", cx.device_name().c_str());
29    int fails = 0;
30    // ---- route_topk (512 experts, and the 256-expert Coder's rows)
31    for (const int NEX : {512, 256}) {
32        const int T = 300;
33        mtl::Pipeline p = cx.pipeline(lib, "route_topk");
34        mtl::Buffer lg = cx.alloc(4 * T * NEX), ids = cx.alloc(4 * T * TK), w = cx.alloc(4 * T * TK);
35        ref::Rng r(9);
36        for (int t = 0; t < T; ++t)
37            for (int e = 0; e < NEX; ++e) {
38                float v = r.sym() * 4.0f;
39                if (t % 3 == 0) v = std::round(v * 4.0f) / 4.0f;
40                lg.as<float>()[t * NEX + e] = v;
41            }
42        const uint32_t nt = T;
43        mtl::Dispatch d;
44        d.p = &p;
45        const uint32_t nex = NEX;
46        d.args = {mtl::Arg::B(lg), mtl::Arg::B(ids), mtl::Arg::B(w), mtl::Arg::V(nt), mtl::Arg::V(nex)};
47        d.grid[0] = (T + 7) / 8;
48        d.tg[0] = 256;
49        cx.run({d});
50        int bad = 0;
51        double worst = 0;
52        for (int t = 0; t < T; ++t) {
53            const float* l = lg.as<float>() + t * NEX;
54            float mx = -INFINITY;
55            for (int e = 0; e < NEX; ++e) mx = std::max(mx, l[e]);
56            std::vector<double> pr(NEX);
57            double s = 0;
58            for (int e = 0; e < NEX; ++e) s += (pr[e] = std::exp((double)l[e] - mx));
59            std::vector<int> order(NEX);
60            for (int e = 0; e < NEX; ++e) order[e] = e;
61            std::stable_sort(order.begin(), order.end(), [&](int x, int y) { return l[x] > l[y]; });
62            double ss = 0;
63            for (int k = 0; k < TK; ++k) ss += pr[order[k]] / s;
64            for (int k = 0; k < TK; ++k) {
65                if (ids.as<int>()[t * TK + k] != order[k]) { ++bad; break; }
66                const double ref = pr[order[k]] / s / std::max(ss, 6.103515625e-5);
67                worst = std::max(worst, std::fabs(w.as<float>()[t * TK + k] - ref) / ref);
68            }
69        }
70        const bool ok = bad == 0 && worst < 2e-6;
71        fails += !ok;
72        std::printf("route_topk, %d tokens: id mismatches %d, worst weight rel err %.2e  %s\n", T, bad, worst, ok ? "PASS" : "FAIL");
73    }
74    // ---- the HC read as GEMMs
75    for (int apply = 0; apply < 2; ++apply) {
76        const int T = 70, NIN = HC * N, NR = LR + HC;
77        mtl::Buffer R = cx.alloc(4 * (size_t)T * NIN), bo = cx.alloc(4 * (size_t)T * N), inj = cx.alloc(4 * T * HC),
78                    wn = cx.alloc(4 * NIN), wdn = cx.alloc(2 * (size_t)LR * NIN), win = cx.alloc(2 * (size_t)HC * NIN),
79                    wup = cx.alloc(2 * (size_t)NIN * LR), xn = cx.alloc(4 * (size_t)T * NIN), xnh = cx.alloc(2 * (size_t)T * NIN),
80                    WD = cx.alloc(2 * (size_t)NR * NIN), WU = cx.alloc(2 * (size_t)NIN * LR), V = cx.alloc(4 * (size_t)T * NR),
81                    loh = cx.alloc(2 * (size_t)T * LR), injo = cx.alloc(4 * T * HC), G = cx.alloc(4 * (size_t)T * NIN),
82                    mixed = cx.alloc(4 * (size_t)T * N), mixh = cx.alloc(2 * (size_t)T * N);
83        ref::Rng r(11 + apply);
84        std::vector<float> R0((size_t)T * NIN);
85        for (auto& v : R0) v = r.sym();
86        std::copy(R0.begin(), R0.end(), R.as<float>());
87        for (size_t i = 0; i < (size_t)T * N; ++i) bo.as<float>()[i] = r.sym();
88        for (int i = 0; i < T * HC; ++i) inj.as<float>()[i] = r.sym() * 3.0f;
89        for (int i = 0; i < NIN; ++i) wn.as<float>()[i] = 0.5f + r.uni();
90        for (size_t i = 0; i < (size_t)LR * NIN; ++i) wdn.as<uint16_t>()[i] = ref::f32_to_bf16(r.sym() * 0.05f);
91        for (size_t i = 0; i < (size_t)HC * NIN; ++i) win.as<uint16_t>()[i] = ref::f32_to_bf16(r.sym() * 0.05f);
92        for (size_t i = 0; i < (size_t)NIN * LR; ++i) wup.as<uint16_t>()[i] = ref::f32_to_bf16(r.sym() * 0.2f);
93        mtl::Pipeline pn = cx.pipeline(lib, "gr_norm"), pa = cx.pipeline(lib, "act_f16"), pdq = cx.pipeline(lib, "dq_f16_30"),
94                      pg = cx.pipeline(lib, "gemm_f16_64_64_4"), ped = cx.pipeline(lib, "gr_epi_down"), peu = cx.pipeline(lib, "gr_epi_up");
95        std::vector<mtl::Dispatch> ds;
96        GrArgs ga{N, HC, LR, (uint32_t)T, (uint32_t)apply, 1e-6f};
97        EpiArgs ea{(uint32_t)T, N, HC, LR};
98        auto D = [&](const mtl::Pipeline& p, std::vector<mtl::Arg> a, uint32_t gx, uint32_t gy, uint32_t tg) {
99            mtl::Dispatch d; d.p = &p; d.args = std::move(a); d.grid[0] = gx; d.grid[1] = gy; d.tg[0] = tg; ds.push_back(d);
100        };
101        auto dq = [&](const mtl::Buffer& w, const mtl::Buffer& out, size_t ooff, int n_in, int n_out) {
102            DqArgs a{(uint32_t)n_in, (uint32_t)n_out, (uint32_t)(2 * n_in)};
103            D(pdq, {mtl::Arg::B(w), mtl::Arg::B(out, ooff), mtl::Arg::V(a)}, (n_in / 16 + 63) / 64, n_out, 64);
104        };
105        auto gemm = [&](const mtl::Buffer& A, const mtl::Buffer& B, const mtl::Buffer& Y, int M, int Nn, int K) {
106            GemmArgs g{M, Nn, K, 0};
107            D(pg, {mtl::Arg::B(A), mtl::Arg::B(B), mtl::Arg::B(Y), mtl::Arg::V(g)}, (Nn + 63) / 64, (M + 63) / 64, 128);
108        };
109        const uint32_t nx = T * NIN;
110        dq(wdn, WD, 0, NIN, LR);
111        dq(win, WD, (size_t)2 * LR * NIN, NIN, HC);
112        dq(wup, WU, 0, LR, NIN);
113        D(pn, {mtl::Arg::B(R), mtl::Arg::B(bo), mtl::Arg::B(inj), mtl::Arg::B(wn), mtl::Arg::B(xn), mtl::Arg::V(ga)}, HC, T, 256);
114        D(pa, {mtl::Arg::B(xn), mtl::Arg::B(xnh), mtl::Arg::V(nx)}, (nx + 255) / 256, 1, 256);
115        gemm(xnh, WD, V, T, NR, NIN);
116        D(ped, {mtl::Arg::B(V), mtl::Arg::B(loh), mtl::Arg::B(injo), mtl::Arg::V(ea)}, (T * NR + 255) / 256, 1, 256);
117        gemm(loh, WU, G, T, NIN, LR);
118        D(peu, {mtl::Arg::B(G), mtl::Arg::B(xn), mtl::Arg::B(mixed), mtl::Arg::B(mixh), mtl::Arg::V(ea)}, (T * N + 255) / 256, 1, 256);
119        cx.run(ds);
120        // the fused read: gr_norm_h (fp16 xn), the down GEMM, gr_epi_down, the up GEMM with the epilogue (w_up rows
121        // interleaved by dq_f16's perm)
122        mtl::Buffer mixed2 = cx.alloc(4 * (size_t)T * N), mixh2 = cx.alloc(2 * (size_t)T * N), WU2 = cx.alloc(2 * (size_t)NIN * LR),
123                    xnh2 = cx.alloc(2 * (size_t)T * NIN), V2 = cx.alloc(4 * (size_t)T * NR), loh2 = cx.alloc(2 * (size_t)T * LR),
124                    injo2 = cx.alloc(4 * T * HC);
125        std::copy(R0.begin(), R0.end(), R.as<float>());
126        {
127            mtl::Pipeline pnh = cx.pipeline(lib, "gr_norm_h"), pup = cx.pipeline(lib, "gemm_hc_up_64_64_4");
128            ds.clear();
129            DqArgs da{(uint32_t)LR, (uint32_t)NIN, (uint32_t)(2 * LR), (uint32_t)HC};
130            D(pdq, {mtl::Arg::B(wup), mtl::Arg::B(WU2), mtl::Arg::V(da)}, (LR / 16 + 63) / 64, NIN, 64);
131            D(pnh, {mtl::Arg::B(R), mtl::Arg::B(bo), mtl::Arg::B(inj), mtl::Arg::B(wn), mtl::Arg::B(xnh2), mtl::Arg::V(ga)}, HC, T, 256);
132            gemm(xnh2, WD, V2, T, NR, NIN);
133            D(ped, {mtl::Arg::B(V2), mtl::Arg::B(loh2), mtl::Arg::B(injo2), mtl::Arg::V(ea)}, (T * NR + 255) / 256, 1, 256);
134            GemmArgs g{T, NIN, LR, 0};
135            D(pup, {mtl::Arg::B(loh2), mtl::Arg::B(WU2), mtl::Arg::B(xnh2), mtl::Arg::B(mixed2), mtl::Arg::B(mixh2), mtl::Arg::V(g),
136                    mtl::Arg::V(ea)}, NIN / 64, (T + 63) / 64, 128);
137            cx.run(ds);
138        }
139        // reference
140        double se = 0, sr = 0, sei = 0, sri = 0, ser = 0, srr = 0, se2 = 0, sh2 = 0;
141        std::vector<double> x(NIN), lo(LR);
142        for (int t = 0; t < T; ++t) {
143            for (int c = 0; c < HC; ++c) {
144                const double g = apply ? 2.0 * sig(inj.as<float>()[t * HC + c] / (double)HC) : 0.0;
145                double ss = 0;
146                for (int d = 0; d < N; ++d) {
147                    const size_t i = (size_t)t * NIN + c * N + d;
148                    const double v = R0[i] + (apply ? bo.as<float>()[(size_t)t * N + d] * g : 0.0);
149                    x[c * N + d] = v;
150                    ss += v * v;
151                    ser += (R.as<float>()[i] - v) * (R.as<float>()[i] - v);
152                    srr += v * v;
153                }
154                const double rs = 1.0 / std::sqrt(ss / N + 1e-6);
155                for (int d = 0; d < N; ++d) x[c * N + d] *= wn.as<float>()[c * N + d] * rs;
156            }
157            for (int k = 0; k < NR; ++k) {
158                const uint16_t* w = k < LR ? wdn.as<uint16_t>() + (size_t)k * NIN : win.as<uint16_t>() + (size_t)(k - LR) * NIN;
159                double s = 0;
160                for (int i = 0; i < NIN; ++i) s += ref::bf16_to_f32(w[i]) * x[i];
161                if (k < LR) lo[k] = s / HC * sig(s / HC);
162                else {
163                    const double gv = injo.as<float>()[t * HC + k - LR];
164                    sei += (gv - s) * (gv - s);
165                    sri += s * s;
166                }
167            }
168            for (int d = 0; d < N; ++d) {
169                double m = 0;
170                for (int c = 0; c < HC; ++c) {
171                    const uint16_t* w = wup.as<uint16_t>() + (size_t)(c * N + d) * LR;
172                    double s = 0;
173                    for (int k = 0; k < LR; ++k) s += ref::bf16_to_f32(w[k]) * lo[k];
174                    m += x[c * N + d] * sig(s);
175                }
176                m /= HC;
177                const double gv = mixed.as<float>()[(size_t)t * N + d], g2 = mixed2.as<float>()[(size_t)t * N + d],
178                             h2 = ref::f16_to_f32(mixh2.as<uint16_t>()[(size_t)t * N + d]);
179                se += (gv - m) * (gv - m);
180                se2 += (g2 - m) * (g2 - m);
181                sh2 += (h2 - m) * (h2 - m);
182                sr += m * m;
183            }
184        }
185        const double rm = std::sqrt(se / sr), ri = std::sqrt(sei / sri), rr = std::sqrt(ser / srr);
186        const double r2 = std::sqrt(se2 / sr), rh2 = std::sqrt(sh2 / sr);
187        const bool ok = rm < 2e-3 && ri < 2e-3 && rr < 1e-6 && r2 < 2e-3 && rh2 < 2e-3;
188        fails += !ok;
189        std::printf("HC read as GEMMs, %d tokens, apply %d: mixed rel err %.2e, inject %.2e, residual %.2e; fused read "
190                    "(fp16 xn, up GEMM epilogue): mixed %.2e, fp16 %.2e  %s\n", T, apply, rm, ri, rr, r2, rh2, ok ? "PASS" : "FAIL");
191    }
192    // ---- swiglu_h, moe_out
193    {
194        const int n = 5000, T = 7, NE = 640;
195        mtl::Pipeline ps = cx.pipeline(lib, "swiglu_h"), pm = cx.pipeline(lib, "moe_out");
196        mtl::Buffer g = cx.alloc(4 * n), u = cx.alloc(4 * n), h = cx.alloc(2 * n), yr = cx.alloc(4 * T * NE),
197                    ys = cx.alloc(4 * T * NE), sg = cx.alloc(4 * T), bo = cx.alloc(4 * T * NE);
198        ref::Rng r(5);
199        for (int i = 0; i < n; ++i) { g.as<float>()[i] = r.sym() * 6; u.as<float>()[i] = r.sym(); }
200        for (int i = 0; i < T * NE; ++i) { yr.as<float>()[i] = r.sym(); ys.as<float>()[i] = r.sym(); }
201        for (int i = 0; i < T; ++i) sg.as<float>()[i] = r.sym() * 4;
202        const uint32_t nn = n;
203        const uint32_t a2[2] = {(uint32_t)T, (uint32_t)NE};
204        mtl::Dispatch d1; d1.p = &ps; d1.args = {mtl::Arg::B(g), mtl::Arg::B(u), mtl::Arg::B(h), mtl::Arg::V(nn)};
205        d1.grid[0] = (n + 255) / 256; d1.tg[0] = 256;
206        mtl::Dispatch d2; d2.p = &pm; d2.args = {mtl::Arg::B(yr), mtl::Arg::B(ys), mtl::Arg::B(sg), mtl::Arg::B(bo), mtl::Arg::V(a2)};
207        d2.grid[0] = (T * NE + 255) / 256; d2.tg[0] = 256;
208        cx.run({d1, d2});
209        double w1 = 0, w2 = 0;
210        for (int i = 0; i < n; ++i) {
211            const double gv = g.as<float>()[i], ref = gv * sig(gv) * u.as<float>()[i];
212            w1 = std::max(w1, std::fabs(ref::f16_to_f32(h.as<uint16_t>()[i]) - ref) / (std::fabs(ref) + 1e-3));
213        }
214        for (int i = 0; i < T * NE; ++i) {
215            const double ref = yr.as<float>()[i] + sig(sg.as<float>()[i / NE]) * ys.as<float>()[i];
216            w2 = std::max(w2, std::fabs(bo.as<float>()[i] - ref));
217        }
218        const bool ok = w1 < 1e-3 && w2 < 1e-5;
219        fails += !ok;
220        std::printf("swiglu_h worst rel err %.2e, moe_out worst abs err %.2e  %s\n", w1, w2, ok ? "PASS" : "FAIL");
221    }
222    std::printf("%s\n", fails ? "SOME FAILED" : "ALL PASS");
223    return fails ? 1 : 0;
224}