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
17.3 KiB262 linesraw
1// metal/tests/moe_mm_parity.cpp - the prompt-chunk routed experts (moe_mm.metal): plan, gate/up GEMM, down GEMM,
2// combine, against a CPU reference that rounds the activations and weights to fp16 as the kernels do (the matrix
3// units' operands) - and against the exact float reference for the size of that rounding; then the speed.
4//
5//   moe_mm_parity [--gu Q2_0] [--dn Q2_0] [--T 256] [--tile 32,64,64,4]          parity (64 experts)
6//   moe_mm_parity --bench [--gu ..] [--dn ..] [--T 2048] [--tile ..]            per-layer time, 512 experts
7#include "coop_probe.h"
8#include "mtl_rt.h"
9#include "ref_quant.h"
10#include "engine/geo.h"
11
12#include <algorithm>
13#include <cmath>
14#include <cstdio>
15#include <cstdlib>
16#include <cstring>
17#include <set>
18#include <string>
19#include <vector>
20
21namespace {
22int N_EMBD = strata_metal::geo::N, N_FF = strata_metal::geo::NFF;   // the shape this build is compiled for (engine/geo.h); --embd / --ff change them (Q4-KQ: expert widths 512 and 1024)
23constexpr int TOPK = strata_metal::geo::TOPK;
24struct MmPlanArgs { uint32_t n_ent, topk, n_expert, tm, n_blocks; };
25struct MmArgs { uint64_t gate_off, up_off, down_off, gu_stride, d_stride; uint32_t gu_row, d_row, n_embd, n_ff; };
26double median(std::vector<double> v) { std::sort(v.begin(), v.end()); return v[v.size() / 2]; }
27int type_of(const std::string& s) {
28    for (int t : {ref::TQ2_T, ref::TQK6, ref::TQK7, ref::Q2_0, ref::IQ3_XXS, ref::IQ2_XXS, ref::IQ2_XS, ref::IQ2_S, ref::IQ3_S, ref::IQ4_NL, ref::IQ4_XS, ref::Q3_K, ref::Q4_K, ref::Q5_K, ref::Q6_K, ref::Q8_0, ref::Q5_1, ref::Q5_0})
29        if (s == ref::type_name(t)) return t;
30    std::exit(2);
31}
32float h16(float v) { return ref::f16_to_f32(ref::f32_to_f16(v)); }
33}  // namespace
34
35int main(int argc, char** argv) {
36    int gu = ref::Q2_0, dn = ref::Q2_0, T = 256, TM = 16, TN = 64, TK = 64, SG = 2, DTN = -1, DTK = -1, DSG = -1;
37    bool bench = false, v2 = false, v3 = false, v4 = false, v5 = false, v6 = false;
38    int MS = 1;
39    for (int i = 1; i < argc; ++i) {
40        std::string a = argv[i];
41        if (a == "--gu") gu = type_of(argv[++i]);
42        else if (a == "--dn") dn = type_of(argv[++i]);
43        else if (a == "--T") T = std::atoi(argv[++i]);
44        else if (a == "--ff") N_FF = std::atoi(argv[++i]);
45        else if (a == "--embd") N_EMBD = std::atoi(argv[++i]);
46        else if (a == "--tile") std::sscanf(argv[++i], "%d,%d,%d,%d", &TM, &TN, &TK, &SG);
47        else if (a == "--dtile") std::sscanf(argv[++i], "%d,%d,%d", &DTN, &DTK, &DSG);   // the down kernel's TN,TK,SG
48        else if (a == "--bench") bench = true;
49        else if (a == "--v2") v2 = true;
50        else if (a == "--v3") v2 = v3 = true;   // v2's gather + the register-operand GEMMs (TN per simdgroup)
51        else if (a == "--v4") { v2 = v3 = v4 = true; MS = std::atoi(argv[++i]); }   // mm_gu4 with MS 16-row subtiles
52        else if (a == "--v6") { v2 = v3 = true; v6 = true; MS = std::atoi(argv[++i]); }   // mm_gu6 / mm_down6 / mm_scan6: groups of MS 16-row subtiles
53        else if (a == "--v5") { v2 = v3 = true; v5 = true; }   // mm_gu5 (weight blocks staged in threadgroup memory)
54    }
55    if (bench && T == 256) T = 2048;
56    // v1 (mm_gu / mm_down) is the first-generation test kernel: the engine only ever dispatches mm_gu2 / mm_gu3 (window.cpp, prompt_chain.inc).
57    // It has no IQ4_XS gate/up, so that type runs the v2 path here instead of failing at the pipeline lookup.
58    if (!v2 && gu == ref::IQ4_XS) { v2 = true; std::printf("note: IQ4_XS gate/up has no v1 kernel (the engine does not use v1): running v2\n"); }
59    if (v4) TM = 16 * MS;   // the plan's tile height; mm_gu4's name carries MS instead
60    if (v6) TM = 16;   // ragged tiles: the padding is 16 rows, the group size is MS
61    mtl::Context cx;
62    // the host defines STRATA_KQ_DOWN only for a model whose downs are K-quant / IQ4_XS / IQ3_S (window.cpp kq_down_prelude)
63    const bool kq_dn = dn == ref::Q3_K || dn == ref::Q4_K || dn == ref::Q5_K || dn == ref::Q6_K || dn == ref::IQ3_S || dn == ref::IQ4_XS;
64    const int lib = cx.compile({"quant.metal", "units.metal", "mma.metal", "moe_mm.metal"}, kq_dn ? "#define STRATA_KQ_DOWN 1\n" : "");
65    const int NE = bench ? 512 : 64, LAYERS = bench ? 4 : 1;
66    const size_t gu_row = ref::row_bytes(gu, N_EMBD), d_row = ref::row_bytes(dn, N_FF);
67    const size_t up_off = (size_t)N_FF * gu_row, down_off = 2 * up_off, blob = down_off + (size_t)N_EMBD * d_row;
68    std::printf("device %s; %s/%s, T %d, %d experts, tile TM %d TN %d TK %d SG %d\n", cx.device_name().c_str(),
69                ref::type_name(gu), ref::type_name(dn), T, NE, TM, TN, TK, SG);
70    mtl::Buffer W = cx.alloc(blob * NE * LAYERS);
71    {
72        std::vector<uint8_t> tmp(blob * 16);
73        for (int e = 0; e < 16; ++e) {
74            ref::random_blocks(gu, tmp.data() + e * blob, 2 * N_FF, N_EMBD, 100 + e, 0.02f);
75            ref::random_blocks(dn, tmp.data() + e * blob + down_off, N_EMBD, N_FF, 200 + e, 0.02f);
76        }
77        for (size_t e = 0; e < (size_t)NE * LAYERS; ++e) std::memcpy(W.as<uint8_t>() + e * blob, tmp.data() + (e % 16) * blob, blob);
78    }
79    const int nent = T * TOPK, nblk = (nent + 1023) / 1024;
80    const int maxrows = nent + NE * TM;
81    mtl::Buffer x = cx.alloc(4 * (size_t)T * N_EMBD), ids = cx.alloc(4 * nent), w = cx.alloc(4 * nent),
82                bcnt = cx.alloc(4 * (size_t)nblk * NE), boff = cx.alloc(4 * (size_t)nblk * NE), eoff = cx.alloc(4 * NE),
83                tiles = cx.alloc(8 * (size_t)(maxrows / TM + 1)), meta = cx.alloc(64), stok = cx.alloc(4 * (size_t)maxrows),
84                sw = cx.alloc(4 * (size_t)maxrows), pos = cx.alloc(4 * nent), H = cx.alloc(4 * (size_t)maxrows * N_FF),
85                YE = cx.alloc(4 * (size_t)maxrows * N_EMBD), y = cx.alloc(4 * (size_t)T * N_EMBD),
86                XS = cx.alloc(2 * (size_t)maxrows * N_EMBD), HS = cx.alloc(2 * (size_t)maxrows * N_FF);
87    ref::Rng r(7);
88    for (size_t i = 0; i < (size_t)T * N_EMBD; ++i) x.as<float>()[i] = r.sym();
89    for (int t = 0; t < T; ++t) {
90        std::set<int> used;
91        float s = 0;
92        for (int k = 0; k < TOPK; ++k) {
93            int e;
94            do e = (int)(r.next() % NE); while (used.count(e));
95            used.insert(e);
96            ids.as<int>()[t * TOPK + k] = e;
97            s += (w.as<float>()[t * TOPK + k] = 0.2f + r.uni());
98        }
99        for (int k = 0; k < TOPK; ++k) w.as<float>()[t * TOPK + k] /= s;
100    }
101    mtl::Pipeline phist = cx.pipeline(lib, "mm_hist"), pscan = cx.pipeline(lib, v6 ? "mm_scan6" : "mm_scan"), pplace = cx.pipeline(lib, "mm_place"),
102                  pclear = cx.pipeline(lib, "mm_clear"), pcomb = cx.pipeline(lib, "mm_combine");
103    if (DTN < 0) { DTN = TN; DTK = TK; DSG = SG; }
104    if ((dn == ref::IQ4_NL || dn == ref::Q5_0) && DTK < 32) DTK = 32;   // 32-value units (the v2 / v3 down tiles of IQ4_NL / Q5_0 need TK >= 32)
105    const std::string tl = std::to_string(TM) + "_" + std::to_string(TN) + "_" + std::to_string(TK) + "_" + std::to_string(SG);
106    const std::string dtl = std::to_string(TM) + "_" + std::to_string(DTN) + "_" + std::to_string(DTK) + "_" + std::to_string(DSG);
107    std::string v6_gu, v6_dn;
108    mtl::Constants probe;
109    probe.i(5, std::getenv("MM_PROBE") ? std::atoi(std::getenv("MM_PROBE")) : 0);
110    const bool k4 = coop_k4(cx);
111    if (v3) std::printf("right-input layout: %s\n", k4 ? "runs of 4 k" : "other (per-element decode)");
112    if (v6) {   // the ragged-tile kernels: names carry MS, TN, TK, SG (TM is the plan's 16-row padding)
113        const std::string tl6 = std::to_string(MS) + "_" + std::to_string(TN) + "_" + std::to_string(TK) + "_" + std::to_string(SG);
114        const std::string dtl6 = std::to_string(MS) + "_" + std::to_string(DTN) + "_" + std::to_string(DTK) + "_" + std::to_string(DSG);
115        v6_gu = "mm_gu6_" + std::to_string(gu) + "_" + tl6;
116        v6_dn = "mm_down6_" + std::to_string(dn) + "_" + dtl6;
117    }
118    mtl::Pipeline pgu = v6 ? cx.pipeline(lib, v6_gu, mtl::Constants().b(7, k4)) : v5 ? cx.pipeline(lib, "mm_gu5_" + std::to_string(gu) + "_" + std::to_string(TN) + "_" + std::to_string(SG),
119                                         mtl::Constants().b(7, k4))
120                      : v4 ? cx.pipeline(lib, "mm_gu4_" + std::to_string(gu) + "_" + std::to_string(MS) + tl.substr(tl.find('_')),
121                                         mtl::Constants().b(7, k4).i(5, std::getenv("MM_PROBE") ? std::atoi(std::getenv("MM_PROBE")) : 0))
122                      : v3 ? cx.pipeline(lib, "mm_gu3_" + std::to_string(gu) + "_" + tl, mtl::Constants().b(7, k4).i(5, std::getenv("MM_PROBE") ? std::atoi(std::getenv("MM_PROBE")) : 0).b(23, std::getenv("QUANT_CTAB") != nullptr))
123                           : cx.pipeline(lib, (v2 ? "mm_gu2_" : "mm_gu_") + std::to_string(gu) + "_" + tl, probe),
124                  pdn = v6 ? cx.pipeline(lib, v6_dn, mtl::Constants().b(7, k4)) : v3 ? cx.pipeline(lib, "mm_down3_" + std::to_string(dn) + "_" + dtl, mtl::Constants().b(7, k4))
125                           : cx.pipeline(lib, (v2 ? "mm_down2_" : "mm_down_") + std::to_string(dn) + "_" + (v2 ? dtl : tl)),
126                  pgat = cx.pipeline(lib, "mm_gather");
127    MmPlanArgs pa{(uint32_t)nent, TOPK, (uint32_t)NE, (uint32_t)(v6 ? MS : TM), (uint32_t)nblk};
128    auto encode = [&](int layer, std::vector<mtl::Dispatch>& ds, bool plan, bool gemm) {
129        if (plan) {
130            const uint32_t nclr = maxrows;
131            mtl::Dispatch c; c.p = &pclear; c.args = {mtl::Arg::B(stok), mtl::Arg::V(nclr)}; c.grid[0] = (maxrows + 255) / 256; c.tg[0] = 256; ds.push_back(c);
132            mtl::Dispatch h; h.p = &phist; h.args = {mtl::Arg::B(ids), mtl::Arg::B(bcnt), mtl::Arg::V(pa)}; h.grid[0] = nblk; h.tg[0] = 1024; ds.push_back(h);
133            meta.as<uint32_t>()[2] = N_FF / TN;
134            mtl::Dispatch sc; sc.p = &pscan; sc.args = {mtl::Arg::B(bcnt), mtl::Arg::B(boff), mtl::Arg::B(eoff), mtl::Arg::B(tiles), mtl::Arg::B(meta), mtl::Arg::V(pa)}; sc.tg[0] = NE; ds.push_back(sc);
135            mtl::Dispatch pl; pl.p = &pplace; pl.args = {mtl::Arg::B(ids), mtl::Arg::B(w), mtl::Arg::B(boff), mtl::Arg::B(eoff), mtl::Arg::B(stok), mtl::Arg::B(sw), mtl::Arg::B(pos), mtl::Arg::V(pa)}; pl.grid[0] = nblk; pl.tg[0] = 1024; ds.push_back(pl);
136        }
137        if (gemm) {
138            MmArgs ma{(uint64_t)layer * NE * blob, (uint64_t)layer * NE * blob + up_off, (uint64_t)layer * NE * blob + down_off,
139                      blob, blob, (uint32_t)gu_row, (uint32_t)d_row, (uint32_t)N_EMBD, (uint32_t)N_FF};
140            if (v2 || v3) {   // v3 is v2's gather plus the register-operand GEMMs
141                const uint32_t ne = N_EMBD;
142                mtl::Dispatch ga; ga.p = &pgat; ga.args = {mtl::Arg::B(x), mtl::Arg::B(stok), mtl::Arg::B(XS), mtl::Arg::V(ne)};
143                ga.grid[0] = meta.as<uint32_t>()[1]; ga.tg[0] = 256; ds.push_back(ga);
144            }
145            mtl::Dispatch g; g.p = &pgu;
146            if (v2 || v3) g.args = {mtl::Arg::B(W), mtl::Arg::B(XS), mtl::Arg::B(HS), mtl::Arg::B(tiles), mtl::Arg::V(ma)};
147            else g.args = {mtl::Arg::B(W), mtl::Arg::B(x), mtl::Arg::B(H), mtl::Arg::B(stok), mtl::Arg::B(tiles), mtl::Arg::V(ma)};
148            g.grid[0] = N_FF / (v3 ? TN * SG : TN); g.grid[1] = meta.as<uint32_t>()[0]; g.tg[0] = 32 * SG; ds.push_back(g);
149            mtl::Dispatch d; d.p = &pdn; d.args = {mtl::Arg::B(W), mtl::Arg::B(v2 || v3 ? HS : H), mtl::Arg::B(YE), mtl::Arg::B(tiles), mtl::Arg::V(ma)};
150            d.grid[0] = N_EMBD / (v3 ? DTN * DSG : v2 ? DTN : TN); d.grid[1] = meta.as<uint32_t>()[0]; d.tg[0] = 32 * ((v2 || v3) ? DSG : SG); ds.push_back(d);
151            const uint32_t ca[4] = {(uint32_t)T, (uint32_t)N_EMBD, TOPK, 0};
152            mtl::Dispatch cb; cb.p = &pcomb; cb.args = {mtl::Arg::B(YE), mtl::Arg::B(pos), mtl::Arg::B(sw), mtl::Arg::B(y), mtl::Arg::V(ca)};
153            cb.grid[0] = (T * N_EMBD + 255) / 256; cb.tg[0] = 256; ds.push_back(cb);
154        }
155    };
156    {
157        std::vector<mtl::Dispatch> ds;
158        encode(0, ds, true, false);
159        cx.run(ds);   // the plan first: the GEMMs' grid is the tile count
160    }
161    const uint32_t ntiles = meta.as<uint32_t>()[0];
162    std::printf("plan: %u tiles of %d, %u padded rows for %d entries\n", ntiles, TM, meta.as<uint32_t>()[1], nent);
163    if (!bench) {
164        // the plan: every entry placed once, rows of an expert contiguous and in entry order
165        bool ok_plan = true;
166        std::vector<int> seen(maxrows, 0);
167        for (int i = 0; i < nent; ++i) {
168            const int row = pos.as<int>()[i];
169            if (row < 0 || row >= (int)meta.as<uint32_t>()[1] || stok.as<int>()[row] != i / TOPK) ok_plan = false;
170            else seen[row]++;
171        }
172        for (int i = 0; i < maxrows; ++i) if (seen[i] > 1) ok_plan = false;
173        std::vector<mtl::Dispatch> ds;
174        encode(0, ds, false, true);
175        cx.run(ds);
176        // reference: fp16 operands (x, weights, h), fp32+ accumulation; and the exact one
177        double se16 = 0, se = 0, sr = 0;
178        std::vector<float> wg((size_t)N_FF * N_EMBD), wu(wg.size()), wd((size_t)N_EMBD * N_FF);
179        std::vector<double> yr16((size_t)T * N_EMBD, 0.0), yr((size_t)T * N_EMBD, 0.0);
180        for (int e = 0; e < NE; ++e) {
181            const uint8_t* b = W.as<uint8_t>() + e * blob;
182            bool any = false;
183            for (int i = 0; i < nent && !any; ++i) any = ids.as<int>()[i] == e;
184            if (!any) continue;
185            ref::dequant(gu, b, wg.data(), wg.size());
186            ref::dequant(gu, b + up_off, wu.data(), wu.size());
187            ref::dequant(dn, b + down_off, wd.data(), wd.size());
188            for (int i = 0; i < nent; ++i) {
189                if (ids.as<int>()[i] != e) continue;
190                const int t = i / TOPK;
191                const float* xt = x.as<float>() + (size_t)t * N_EMBD;
192                std::vector<double> h16v(N_FF), hv(N_FF);
193                for (int f = 0; f < N_FF; ++f) {
194                    double g = 0, u = 0, g16 = 0, u16 = 0;
195                    for (int k = 0; k < N_EMBD; ++k) {
196                        const float xk = xt[k], xh = h16(xk);
197                        g += (double)wg[(size_t)f * N_EMBD + k] * xk;
198                        u += (double)wu[(size_t)f * N_EMBD + k] * xk;
199                        g16 += (double)h16(wg[(size_t)f * N_EMBD + k]) * xh;
200                        u16 += (double)h16(wu[(size_t)f * N_EMBD + k]) * xh;
201                    }
202                    hv[f] = g / (1 + std::exp(-g)) * u;
203                    h16v[f] = h16((float)(g16 / (1 + std::exp(-g16)) * u16));
204                }
205                const double wt = w.as<float>()[i];
206                for (int d = 0; d < N_EMBD; ++d) {
207                    double s = 0, s16 = 0;
208                    for (int f = 0; f < N_FF; ++f) {
209                        s += (double)wd[(size_t)d * N_FF + f] * hv[f];
210                        s16 += (double)h16(wd[(size_t)d * N_FF + f]) * h16v[f];
211                    }
212                    yr[(size_t)t * N_EMBD + d] += wt * s;
213                    yr16[(size_t)t * N_EMBD + d] += wt * s16;
214                }
215            }
216        }
217        for (size_t i = 0; i < yr.size(); ++i) {
218            const double g = y.as<float>()[i];
219            se16 += (g - yr16[i]) * (g - yr16[i]);
220            se += (g - yr[i]) * (g - yr[i]);
221            sr += yr[i] * yr[i];
222        }
223        uint64_t yh = 14695981039346656037ull;   // FNV-1a over y's bits: two runs (v3 TM 16, v6 groups) must print the same hash
224        for (size_t i = 0; i < yr.size(); ++i) { uint32_t u; std::memcpy(&u, y.as<float>() + i, 4); yh = (yh ^ u) * 1099511628211ull; }
225        std::printf("yhash %016llx\n", (unsigned long long) yh);
226        const double rel16 = std::sqrt(se16 / sr), rel = std::sqrt(se / sr);
227        const bool ok = ok_plan && rel16 < 2e-4;
228        std::printf("parity: plan %s; y vs fp16-operand reference rel L2 %.2e, vs exact float reference %.2e  %s\n",
229                    ok_plan ? "ok" : "WRONG", rel16, rel, ok ? "PASS" : "FAIL");
230        return ok ? 0 : 1;
231    }
232    // bench: the plan, the two GEMMs and the combine, LAYERS distinct weight sets rotated
233    double flops = 0;
234    {
235        const double rows = meta.as<uint32_t>()[1];
236        flops = 2.0 * nent * (2.0 * N_FF * N_EMBD + (double)N_EMBD * N_FF);
237        std::printf("useful GFLOP per layer %.1f (padded rows %.0f = %.2fx entries)\n", flops / 1e9, rows, rows / nent);
238    }
239    auto timeit = [&](bool plan, bool gemm, int part) {
240        std::vector<mtl::Dispatch> ds;
241        for (int l = 0; l < 8; ++l) {
242            std::vector<mtl::Dispatch> one;
243            encode(l % LAYERS, one, plan, gemm);
244            if (part >= 0 && gemm) { ds.push_back(one[part]); continue; }
245            for (auto& d : one) ds.push_back(d);
246        }
247        cx.warm(ds, 0.3);
248        std::vector<double> t;
249        for (int i = 0; i < 5; ++i) t.push_back(cx.run(ds) / 8);
250        return median(t);
251    };
252    const int o = v2 ? 1 : 0;
253    const double tp = timeit(true, false, -1), tg = timeit(false, true, o), td = timeit(false, true, o + 1),
254                 tc = timeit(false, true, o + 2), ta = timeit(false, true, -1);
255    if (v2) std::printf("gather %.1f us\n", timeit(false, true, 0) * 1e6);
256    const double fgu = 2.0 * nent * 2.0 * N_FF * N_EMBD, fdn = 2.0 * nent * N_EMBD * N_FF;
257    std::printf("per layer: plan %.1f us, gate/up %.1f us (%.1f TFLOP/s useful), down %.1f us (%.1f TFLOP/s), combine %.1f us;"
258                " GEMMs + combine %.1f us = %.1f TFLOP/s; %.1f us per token per layer -> 48 layers: %.0f tok/s (experts only)\n",
259                tp * 1e6, tg * 1e6, fgu / tg / 1e12, td * 1e6, fdn / td / 1e12, tc * 1e6, ta * 1e6, flops / ta / 1e12,
260                (ta + tp) / T * 1e6, T / (48 * (ta + tp)));
261    return 0;
262}