okami.mom/strata

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

Niko1221Trial2 merge f-0291-pr-nv (97b3d614f)1306424be

main
33.7 KiB555 linesraw
1// metal/tests/prompt_chain.cpp - a whole PROMPT through every layer on the REAL weights of a GGUF (mmapped, wrapped
2// no-copy), in chunks of C tokens (one command buffer a chunk): the GPU time of prompt processing with the prompt
3// kernels of metal/.  A timing of the real byte and FLOP stream, not a numerical check: the tokens are random ids
4// (their real embedding rows start every hyper-connection stream), the parity programs check the kernels.
5//
6//   prompt_chain <shard-1.gguf> [--prompt P,P,..] [--chunk C] [--breakdown] [--only CLASS] [--skip CLASS]
7//
8// Per layer and chunk (T tokens; activations fp32 rows, fp16 copies as the matrix units' operands):
9//   HC read     gr_norm_h (fp16 xn) -> GEMM [w_down; w_inject] -> gr_epi_down -> gemm_hc_up (the GEMM with the
10//               mixing epilogue);  PC_HC=plain: gr_norm -> act_f16 -> GEMM -> gr_epi_down -> GEMM -> gr_epi_up
11//   GDN         GEMMs qkv / gate / alpha / beta -> gdn_pre (parallel) -> gdn_scan_r (the state scan) -> gdn_post
12//               (output norm and gate, fp16) -> GEMM out;  PC_GDN=step: the decode step over the T tokens instead
13//   QSA         GEMMs q / k / v / indexer q, k -> qsa_prep (T tokens) -> score + top-k (past the budget) -> attn ->
14//               merge -> GEMM out
15//   MoE         GEMM router -> route_topk -> plan (hist, scan, clear, place) -> gather -> mm_gu2 -> mm_down2 ->
16//               combine; shared expert GEMMs gate, up -> swiglu_h -> GEMM down; GEMM shared gate; moe_out
17// Every dense matrix is dequantized to fp16 (dq_f16) once a chunk, before its GEMM.  After the last chunk: the final
18// HC read and the LM head on the LAST row only (the decode kernels: gr_norm / gr_down / gr_up, GEMV, argmax).
19// Left out: the PLE path and the MTP draft.
20#include "coop_probe.h"
21#include "gguf_lite.h"
22#include "mtl_rt.h"
23#include "ref_quant.h"
24
25#include <algorithm>
26#include <cmath>
27#include <cstdio>
28#include <cstdlib>
29#include <cstring>
30#include <map>
31#include <set>
32#include <string>
33#include <sys/mman.h>
34#include <vector>
35
36namespace {
37
38constexpr int N = 2560, HC = 4, LR = 320, NFF = 640, TOPK = 10, NEXP = 512, NV = 248320, QB = 2051, QCHUNKS = 33;
39struct GrArgs { uint32_t n_embd, hc, hc_lr, n_tok, apply; float eps; };
40struct EpiArgs { uint32_t n_tok, n_embd, hc, hc_lr; };
41struct DqArgs { uint32_t n_in, n_out, row_bytes, perm; };
42struct GemmArgs { int M, N, K, pad; };
43struct GemvArgs { uint32_t n_in, n_out, n_tok, row_bytes, x_stride, y_stride; };
44struct GdnArgs { uint32_t h_k, h_v, channels, commit; float eps; uint32_t plane; };
45struct GdnPArgs { uint32_t n_tok, h_k, h_v, channels; float eps; uint32_t f32; };
46struct QsaArgs { uint32_t pos0, pos_base, max_cells, n_tok; float eps; };
47struct MmPlanArgs { uint32_t n_ent, topk, n_expert, tm, n_blocks; };
48struct MmArgs { uint64_t gate_off, up_off, down_off, gu_stride, d_stride; uint32_t gu_row, d_row, n_embd, n_ff; };
49struct ArgArgs { uint32_t n_vocab, parts; };
50
51double median(std::vector<double> v) { std::sort(v.begin(), v.end()); return v[v.size() / 2]; }
52bool fmt_unit32(int t) { return t == ref::IQ4_XS || t == ref::IQ4_NL; }   // mm_gu2 needs a K chunk >= 32
53int unit_of(int t) { return t == ref::Q2_0 || t == ref::IQ3_S || t == ref::BF16 ? 16 : 32; }
54
55}  // namespace
56
57int main(int argc, char** argv) {
58    if (argc < 2) { std::fprintf(stderr, "usage: prompt_chain <shard-1.gguf> [--prompt P,..] [--chunk C] [--breakdown]\n"); return 2; }
59    std::vector<int> prompts = {1024, 4096, 32768};
60    int C = 2048, reps = 2;
61    bool breakdown = false;
62    std::string only, skip;
63    for (int i = 2; i < argc; ++i) {
64        std::string a = argv[i];
65        if (a == "--prompt") {
66            prompts.clear();
67            for (char* s = argv[++i]; *s;) {
68                prompts.push_back((int)std::strtol(s, &s, 10));
69                if (*s == ',') ++s;
70            }
71        } else if (a == "--chunk") C = std::atoi(argv[++i]);
72        else if (a == "--reps") reps = std::atoi(argv[++i]);
73        else if (a == "--breakdown") breakdown = true;
74        else if (a == "--only") only = argv[++i];
75        else if (a == "--skip") skip = argv[++i];
76    }
77    const int PMAX = *std::max_element(prompts.begin(), prompts.end());
78    gguf::File f;
79    std::string err;
80    if (!f.open(argv[1], err)) { std::fprintf(stderr, "%s\n", err.c_str()); return 2; }
81    mtl::Context cx;
82    std::printf("device %s; %s: %zu tensors, %.1f GB; chunk %d\n", cx.device_name().c_str(), argv[1], f.tensors.size(),
83                f.file_bytes / 1e9, C);
84    {
85        const double t0 = mtl::now_s();
86        madvise(f.map, f.map_bytes, MADV_WILLNEED);
87        volatile uint64_t s = 0;
88        for (size_t o = 0; o < f.file_bytes; o += 16384) s += ((const uint8_t*)f.map)[o];
89        std::printf("file touched in %.1f s\n", mtl::now_s() - t0);
90    }
91    mtl::Buffer W = cx.wrap(f.map, f.map_bytes);
92    auto T_ = [&](const std::string& name) -> const gguf::Tensor& {
93        const gguf::Tensor* t = f.find(name);
94        if (!t) { std::fprintf(stderr, "missing tensor %s\n", name.c_str()); std::exit(2); }
95        return *t;
96    };
97    const double tc0 = mtl::now_s();
98    const int lib = cx.compile({"quant.metal", "units.metal", "mma.metal", "dense_mm.metal", "moe_mm.metal", "gr.metal",
99                                "gemv.metal", "prompt.metal"});
100    const int lgdn = cx.compile({"gdn.metal", "gdn_prompt.metal"}, "#define NO_GGML_COMMON 1\n");
101    const int lqsa = cx.compile({"qsa.metal", "qsa_prompt.metal"}, "#define NO_GGML_COMMON 1\n");
102    const int lsmp = cx.compile({"sample.metal"}, "#define NO_GGML_COMMON 1\n");
103    std::printf("kernels compiled in %.1f s\n", mtl::now_s() - tc0);
104    std::map<std::string, mtl::Pipeline> pcache;
105    const bool k4 = coop_k4(cx);
106    std::printf("matmul2d right-input layout: %s\n", k4 ? "runs of 4 k (per-lane run decoders)" : "other (per-element decode)");
107    auto P = [&](int l, const std::string& fn, const mtl::Constants& c = {}, const std::string& key = "") -> const mtl::Pipeline* {
108        const std::string k = key.empty() ? fn : key;
109        auto it = pcache.find(k);
110        if (it == pcache.end()) it = pcache.emplace(k, cx.pipeline(l, fn, c)).first;
111        return &it->second;
112    };
113
114    // ---- buffers (MT = the chunk's rows)
115    const size_t MT = C;
116    const int MAXC = (PMAX + 64 + 63) / 64 * 64, MB = MAXC / 4 + 2;
117    const int TM = 16;
118    const int maxrows = (int)MT * TOPK + NEXP * TM, nblk_max = ((int)MT * TOPK + 1023) / 1024;
119    auto F32 = [&](size_t n) { return cx.alloc(4 * n); };
120    auto F16 = [&](size_t n) { return cx.alloc(2 * n); };
121    mtl::Buffer R = F32(MT * HC * N), bo = F32(MT * N), inj[2] = {F32(MT * HC), F32(MT * HC)}, xn = F32(MT * HC * N),
122                xnh = F16(MT * HC * N), V = F32(MT * (LR + HC)), loh = F16(MT * LR), G = F32(MT * HC * N), mixed = F32(MT * N),
123                mixh = F16(MT * N);
124    mtl::Buffer qkv = F32(MT * 10240), z = F32(MT * 6144), al = F32(MT * 48), be = F32(MT * 48), yg = F32(MT * 6144),
125                ygh = F16(MT * 6144), gqn = F32(MT * 16 * 128), gkn = F32(MT * 16 * 128), gvc = F32(MT * 6144),
126                ggb = F32(MT * 48 * 2), gkq = F32(MT * 16), go = F32(MT * 6144);
127    const char* hc_env = std::getenv("PC_HC");
128    const std::string hc_mode = hc_env ? hc_env : "fused";   // fused | plain
129    const char* qsa_env = std::getenv("PC_QSA");
130    // flash (one pass on the matrix units, no partials) | mm (split-K on the matrix units + merge) | v1 (qsa_attn,
131    // fp32 + merge).  The M5: flash (= mm + merge or better); the M4: v1 attention (faster there) with the GEMM score.
132    const std::string qsa_mode = qsa_env ? qsa_env : (k4 ? "flash" : "v1");
133    // the expert GEMMs: "v2" (threadgroup-staged weights) or "v3:TM,TN,TK,SG" (register operands, TN rows a simdgroup)
134    const char* gu_env = std::getenv("PC_GU");
135    const char* dn_env = std::getenv("PC_DN");
136    // defaults (M5 Max, moe_mm_parity --v3 --bench): gate/up 16,32,32,4 (every format), down 16,64,32,2
137    // without the M5's right-input layout (the M4) the per-element v3 decode is slower than v2: v2 there
138    const std::string gu_mode = gu_env ? gu_env : (k4 ? "v3:auto" : "v2"), dn_mode = dn_env ? dn_env : (k4 ? "v3:16,64,32,2" : "v2");
139    auto v3_tile = [](const std::string& m, int* t) { std::sscanf(m.c_str() + 3, "%d,%d,%d,%d", &t[0], &t[1], &t[2], &t[3]); };
140    int gu3[4] = {16, 64, 16, 2}, dn3[4] = {16, 64, 16, 2};
141    if (gu_mode.rfind("v3:", 0) == 0 && gu_mode != "v3:auto") v3_tile(gu_mode, gu3);
142    else if (gu_mode == "v3:auto") { gu3[0] = 16; gu3[1] = 32; gu3[2] = 32; gu3[3] = 4; }
143    auto tl3 = [](const int* t) { return std::to_string(t[0]) + "_" + std::to_string(t[1]) + "_" + std::to_string(t[2]) + "_" + std::to_string(t[3]); };
144    auto gu3_for = [&](int type) -> std::string {
145        (void)type;   // one tile for every format since the paired-run decoders (W8)
146        return tl3(gu3);
147    };
148    if (dn_mode.rfind("v3:", 0) == 0) v3_tile(dn_mode, dn3);
149    const bool gu_v3 = gu_mode.rfind("v3:", 0) == 0, dn_v3 = dn_mode.rfind("v3:", 0) == 0;
150    const char* gdn_env = std::getenv("PC_GDN");
151    const std::string gdn_mode = gdn_env ? gdn_env : "scanr_4";
152    mtl::Buffer qfull = F32(MT * 12288), kcur = F32(MT * 512), vcur = F32(MT * 512), iqr = F32(MT * 512), ikr = F32(MT * 128),
153                qcur = F32(MT * 24 * 256), qcurh = F16(MT * 24 * 256), qidx = F32(MT * 4 * 128), scores = F32(MT * MB), qids = cx.alloc(4 * MT * QB),
154                part = F32(MT * QCHUNKS * 24 * 258), XQ = F32(4 * MT * 6144 + MT * 384), xqh = F16(MT * 6144);
155    mtl::Buffer logits = F32(MT * NEXP), ids = cx.alloc(4 * MT * TOPK), wts = F32(MT * TOPK),
156                bcnt = cx.alloc(4 * (size_t)nblk_max * NEXP), boff = cx.alloc(4 * (size_t)nblk_max * NEXP), eoff = cx.alloc(4 * NEXP),
157                tiles = cx.alloc(8 * (size_t)(maxrows / TM + 1)), meta = cx.alloc(64), stok = cx.alloc(4 * (size_t)maxrows),
158                sw = F32(maxrows), pos = cx.alloc(4 * MT * TOPK), XS = F16((size_t)maxrows * N), HS = F16((size_t)maxrows * NFF),
159                YE = F32((size_t)maxrows * N), yr = F32(MT * N), gsh = F32(MT * NFF), ush = F32(MT * NFF), hh = F16(MT * NFF),
160                ys = F32(MT * N), sgv = F32(MT);
161    // fp16 weight scratch, one per role
162    mtl::Buffer WD = F16((size_t)(LR + HC) * HC * N), WU = F16((size_t)HC * N * LR), Wqkv = F16((size_t)10240 * N),
163                Wz = F16((size_t)6144 * N), Wal = F16((size_t)48 * N), Wbe = F16((size_t)48 * N), Wout = F16((size_t)N * 6144),
164                Wq = F16((size_t)12288 * N), Wk = F16((size_t)512 * N), Wv = F16((size_t)512 * N), Wiq = F16((size_t)512 * N),
165                Wik = F16((size_t)128 * N), Wr = F16((size_t)NEXP * N), Wsg = F16((size_t)N), Wshg = F16((size_t)NFF * N),
166                Wshu = F16((size_t)NFF * N), Wshd = F16((size_t)N * NFF);
167    // the last row's final read and head
168    mtl::Buffer xn1 = F32(HC * N), lo1 = F32(LR), inj1 = F32(HC), X1 = F32(4 * N + N / 16), lm = F32(NV), apv = F32(120),
169                api = cx.alloc(4 * 120), tokout = cx.alloc(16);
170    mtl::Buffer cs = cx.alloc(8 * (size_t)(MAXC + 16) * 32);
171    for (int p = 0; p < MAXC + 16; ++p)
172        for (int i = 0; i < 32; ++i) {
173            const double th = (double)p * std::pow(1e7, -2.0 * i / 64.0);
174            cs.as<float>()[(p * 32 + i) * 2] = (float)std::cos(th);
175            cs.as<float>()[(p * 32 + i) * 2 + 1] = (float)std::sin(th);
176        }
177    std::vector<mtl::Buffer> gst, ghist[2], kq, vq, ksc, vsc, tail, dead, pooled;
178    for (int l = 0; l < 48; ++l) {
179        if (l % 4 != 3) {
180            gst.push_back(F32(128 * 48 * 128));
181            ghist[0].push_back(F32(10240 * 3));
182            ghist[1].push_back(F32(10240 * 3));
183        } else {
184            kq.push_back(cx.alloc((size_t)MAXC * 2 * 256));
185            vq.push_back(cx.alloc((size_t)MAXC * 2 * 256));
186            ksc.push_back(cx.alloc(2 * (size_t)MAXC * 2 * 4));
187            vsc.push_back(cx.alloc(2 * (size_t)MAXC * 2 * 4));
188            tail.push_back(F32(4 * 128));
189            dead.push_back(F32(128));
190            pooled.push_back(F32((size_t)MB * 128));
191        }
192    }
193    std::vector<int> gpar(36, 0);
194    // embeddings of random token ids (the real rows)
195    std::vector<float> E(MT * N);
196    {
197        const gguf::Tensor& te = T_("token_embd.weight");
198        const size_t rb = ref::row_bytes(te.type, N);
199        ref::Rng r(17);
200        for (size_t t = 0; t < MT; ++t) {
201            const uint64_t id = r.next() % 200000;
202            ref::dequant(te.type, (const uint8_t*)f.map + te.offset + id * rb, E.data() + t * N, N);
203        }
204    }
205    meta.as<uint32_t>()[2] = gu_v3 ? NFF / (gu3[1] * gu3[3]) : NFF / 64;
206    meta.as<uint32_t>()[5] = dn_v3 ? N / (dn3[1] * dn3[3]) : N / 64;
207
208    // ---- the chunk's dispatches
209    std::vector<mtl::Dispatch> ds;
210    std::vector<std::string> cls;
211    auto push = [&](const mtl::Dispatch& d, const std::string& c) {
212        if (!only.empty() && c != only) return;
213        if (!skip.empty() && c == skip) return;
214        ds.push_back(d);
215        cls.push_back(c);
216    };
217    auto D = [&](const mtl::Pipeline* p, std::vector<mtl::Arg> a, uint32_t gx, uint32_t gy, uint32_t tg, const std::string& c,
218                 uint32_t gz = 1) {
219        mtl::Dispatch d;
220        d.p = p;
221        d.args = std::move(a);
222        d.grid[0] = gx;
223        d.grid[1] = gy;
224        d.grid[2] = gz;
225        d.tg[0] = tg;
226        push(d, c);
227    };
228    const char* gk_env = std::getenv("PC_GEMM");
229    auto gemm = [&](const mtl::Buffer& A, const mtl::Buffer& B, const mtl::Buffer& Y, int M, int Nn, int K, const std::string& c) {
230        int tm = 64, tn = Nn <= 64 ? 32 : 64;
231        if (gk_env && Nn > 64) std::sscanf(gk_env, "%d,%d", &tm, &tn);
232        const std::string fn = "gemm_f16_" + std::to_string(tm) + "_" + std::to_string(tn) + "_4";
233        GemmArgs g{M, Nn, K, 0};
234        D(P(lib, fn), {mtl::Arg::B(A), mtl::Arg::B(B), mtl::Arg::B(Y), mtl::Arg::V(g)}, (Nn + tn - 1) / tn, (M + tm - 1) / tm,
235          128, c);
236    };
237    auto dq = [&](const gguf::Tensor& t, const mtl::Buffer& out, size_t out_off = 0, uint32_t perm = 0) {
238        const int n_in = (int)t.shape[0], n_out = t.shape.size() > 1 ? (int)t.shape[1] : 1;
239        DqArgs a{(uint32_t)n_in, (uint32_t)n_out, (uint32_t)ref::row_bytes(t.type, n_in), perm};
240        D(P(lib, "dq_f16_" + std::to_string(t.type)), {mtl::Arg::B(W, t.offset), mtl::Arg::B(out, out_off), mtl::Arg::V(a)},
241          (n_in / unit_of(t.type) + 63) / 64, n_out, 64, "dq");
242    };
243    auto act16 = [&](const mtl::Buffer& x, const mtl::Buffer& xh, size_t n, const std::string& c) {
244        const uint32_t nn = (uint32_t)n;
245        D(P(lib, "act_f16"), {mtl::Arg::B(x), mtl::Arg::B(xh), mtl::Arg::V(nn)}, (nn + 255) / 256, 1, 256, c);
246    };
247    int cur_inj = 0;
248    // the HC read of T rows: mixed (fp32) and mixh (fp16)
249    auto hc_read = [&](const std::string& pre, bool apply, int T) {
250        const gguf::Tensor &tn = T_(pre + "_norm.weight"), &tdn = T_(pre + "_down.weight"), &tin = T_(pre + "_inject.weight"),
251                           &tup = T_(pre + "_up.weight");
252        dq(tdn, WD);
253        dq(tin, WD, (size_t)2 * LR * HC * N);
254        GrArgs a{N, HC, LR, (uint32_t)T, apply ? 1u : 0u, 1e-6f};
255        EpiArgs ea{(uint32_t)T, N, HC, LR};
256        if (hc_mode == "fused") {
257            // fp16 xn only; the up GEMM's epilogue mixes (w_up rows interleaved by the dequantization)
258            dq(tup, WU, 0, HC);
259            D(P(lib, "gr_norm_h"), {mtl::Arg::B(R), mtl::Arg::B(bo), mtl::Arg::B(inj[cur_inj]), mtl::Arg::B(W, tn.offset),
260                                    mtl::Arg::B(xnh), mtl::Arg::V(a)}, HC, T, 256, "hc");
261            gemm(xnh, WD, V, T, LR + HC, HC * N, "hc gemm");
262            D(P(lib, "gr_epi_down"), {mtl::Arg::B(V), mtl::Arg::B(loh), mtl::Arg::B(inj[1 - cur_inj]), mtl::Arg::V(ea)},
263              (T * (LR + HC) + 255) / 256, 1, 256, "hc");
264            GemmArgs g{T, HC * N, LR, 0};
265            D(P(lib, "gemm_hc_up_64_64_4"), {mtl::Arg::B(loh), mtl::Arg::B(WU), mtl::Arg::B(xnh), mtl::Arg::B(mixed),
266                                             mtl::Arg::B(mixh), mtl::Arg::V(g), mtl::Arg::V(ea)},
267              HC * N / 64, (T + 63) / 64, 128, "hc gemm");
268            cur_inj = 1 - cur_inj;
269            return;
270        }
271        dq(tup, WU);
272        D(P(lib, "gr_norm"), {mtl::Arg::B(R), mtl::Arg::B(bo), mtl::Arg::B(inj[cur_inj]), mtl::Arg::B(W, tn.offset),
273                              mtl::Arg::B(xn), mtl::Arg::V(a)}, HC, T, 256, "hc");
274        act16(xn, xnh, (size_t)T * HC * N, "hc");
275        gemm(xnh, WD, V, T, LR + HC, HC * N, "hc gemm");
276        D(P(lib, "gr_epi_down"), {mtl::Arg::B(V), mtl::Arg::B(loh), mtl::Arg::B(inj[1 - cur_inj]), mtl::Arg::V(ea)},
277          (T * (LR + HC) + 255) / 256, 1, 256, "hc");
278        gemm(loh, WU, G, T, HC * N, LR, "hc gemm");
279        D(P(lib, "gr_epi_up"), {mtl::Arg::B(G), mtl::Arg::B(xn), mtl::Arg::B(mixed), mtl::Arg::B(mixh), mtl::Arg::V(ea)},
280          (T * N + 255) / 256, 1, 256, "hc");
281        cur_inj = 1 - cur_inj;
282    };
283    auto build = [&](int pos0, int T, bool head) {
284        ds.clear();
285        cls.clear();
286        int gi = 0, qi = 0;
287        for (int l = 0; l < 48; ++l) {
288            const std::string b = "blk." + std::to_string(l) + ".";
289            hc_read(b + "hc_attn", l > 0, T);
290            if (l % 4 != 3) {
291                const gguf::Tensor &tq = T_(b + "attn_qkv.weight"), &tz = T_(b + "attn_gate.weight"),
292                                   &ta = T_(b + "ssm_alpha.weight"), &tb = T_(b + "ssm_beta.weight"), &to = T_(b + "ssm_out.weight");
293                dq(tq, Wqkv);
294                dq(tz, Wz);
295                dq(ta, Wal);
296                dq(tb, Wbe);
297                dq(to, Wout);
298                gemm(mixh, Wqkv, qkv, T, 10240, N, "gdn proj");
299                gemm(mixh, Wz, z, T, 6144, N, "gdn proj");
300                gemm(mixh, Wal, al, T, 48, N, "gdn proj");
301                gemm(mixh, Wbe, be, T, 48, N, "gdn proj");
302                GdnArgs a{16, 48, 10240, 1, 1e-6f, 0};
303                const int par = gpar[gi];
304                if (gdn_mode != "step") {
305                    GdnPArgs ga{(uint32_t)T, 16, 48, 10240, 1e-6f, 0};
306                    D(P(lgdn, "gdn_pre"),
307                      {mtl::Arg::B(qkv), mtl::Arg::B(ghist[par][gi]), mtl::Arg::B(W, T_(b + "ssm_conv1d.weight").offset),
308                       mtl::Arg::B(al), mtl::Arg::B(be), mtl::Arg::B(W, T_(b + "ssm_dt.bias").offset),
309                       mtl::Arg::B(W, T_(b + "ssm_a").offset), mtl::Arg::B(gqn), mtl::Arg::B(gkn), mtl::Arg::B(gvc), mtl::Arg::B(ggb),
310                       mtl::Arg::B(gkq), mtl::Arg::B(ghist[1 - par][gi]), mtl::Arg::V(ga)},
311                      16 + 24, T, 256, "gdn scan");
312                    const int ib = gdn_mode == "scan_v" ? 8 : std::atoi(gdn_mode.c_str() + 6);
313                    D(P(lgdn, "gdn_" + gdn_mode, gdn_mode == "scan_v" ? mtl::Constants() : mtl::Constants().i(6, 0)),
314                      {mtl::Arg::B(gst[gi]), mtl::Arg::B(gqn), mtl::Arg::B(gkn), mtl::Arg::B(gvc), mtl::Arg::B(ggb), mtl::Arg::B(gkq),
315                       mtl::Arg::B(go), mtl::Arg::V(ga)},
316                      48 * 4, 1, 32 * ib, "gdn scan");
317                    D(P(lgdn, "gdn_post"), {mtl::Arg::B(go), mtl::Arg::B(z), mtl::Arg::B(W, T_(b + "ssm_norm.weight").offset),
318                                            mtl::Arg::B(ygh), mtl::Arg::B(yg), mtl::Arg::V(ga)},
319                      48, T, 128, "gdn scan");
320                    gemm(ygh, Wout, bo, T, N, 6144, "gdn proj");
321                    ++gi;
322                    goto moe;
323                }
324                D(P(lgdn, "gdn_step", mtl::Constants().i(2, T), "gdn_step#" + std::to_string(T)),
325                  {mtl::Arg::B(gst[gi]), mtl::Arg::B(ghist[par][gi]), mtl::Arg::B(qkv), mtl::Arg::B(al), mtl::Arg::B(be),
326                   mtl::Arg::B(z), mtl::Arg::B(W, T_(b + "ssm_conv1d.weight").offset), mtl::Arg::B(W, T_(b + "ssm_dt.bias").offset),
327                   mtl::Arg::B(W, T_(b + "ssm_a").offset), mtl::Arg::B(W, T_(b + "ssm_norm.weight").offset), mtl::Arg::B(yg),
328                   mtl::Arg::V(a), mtl::Arg::B(ghist[1 - par][gi])},
329                  48, 1, 512, "gdn scan");
330                act16(yg, ygh, (size_t)T * 6144, "gdn proj");
331                gemm(ygh, Wout, bo, T, N, 6144, "gdn proj");
332                ++gi;
333            } else {
334                const gguf::Tensor &tq = T_(b + "attn_q.weight"), &tk = T_(b + "attn_k.weight"), &tv = T_(b + "attn_v.weight"),
335                                   &tiq = T_(b + "indexer.q_proj.weight"), &tik = T_(b + "indexer.k_proj.weight"),
336                                   &to = T_(b + "attn_output.weight");
337                dq(tq, Wq);
338                dq(tk, Wk);
339                dq(tv, Wv);
340                dq(tiq, Wiq);
341                dq(tik, Wik);
342                dq(to, Wout);
343                gemm(mixh, Wq, qfull, T, 12288, N, "qsa proj");
344                gemm(mixh, Wk, kcur, T, 512, N, "qsa proj");
345                gemm(mixh, Wv, vcur, T, 512, N, "qsa proj");
346                gemm(mixh, Wiq, iqr, T, 512, N, "qsa proj");
347                gemm(mixh, Wik, ikr, T, 128, N, "qsa proj");
348                QsaArgs a{(uint32_t)pos0, 0, (uint32_t)MAXC, (uint32_t)T, 1e-6f};
349                D(P(lqsa, "qsa_prep"),
350                  {mtl::Arg::B(qfull), mtl::Arg::B(kcur), mtl::Arg::B(vcur), mtl::Arg::B(iqr), mtl::Arg::B(ikr),
351                   mtl::Arg::B(W, T_(b + "attn_q_norm.weight").offset), mtl::Arg::B(W, T_(b + "attn_k_norm.weight").offset),
352                   mtl::Arg::B(W, T_(b + "indexer.q_norm.weight").offset), mtl::Arg::B(W, T_(b + "indexer.k_norm.weight").offset),
353                   mtl::Arg::B(cs), mtl::Arg::B(qcur), mtl::Arg::B(qidx), mtl::Arg::B(kq[qi]), mtl::Arg::B(vq[qi]),
354                   mtl::Arg::B(ksc[qi]), mtl::Arg::B(vsc[qi]), mtl::Arg::B(tail[qi]), mtl::Arg::B(dead[qi]),
355                   mtl::Arg::B(pooled[qi]), mtl::Arg::V(a)},
356                  33, T, 256, "qsa prep");
357                if (pos0 + T > QB) {   // some token's context is past the budget: select
358                    if (!std::getenv("PC_QSA_SCORE"))   // the GEMM score unless PC_QSA_SCORE (= the scalar qsa_score)
359                        D(P(lqsa, "qsa_score_mm"), {mtl::Arg::B(qidx), mtl::Arg::B(pooled[qi]), mtl::Arg::B(dead[qi]),
360                                                    mtl::Arg::B(scores), mtl::Arg::V(a)},
361                          ((pos0 + T) / 4 + 1 + 63) / 64, (T + 15) / 16, 128, "qsa score");
362                    else
363                    D(P(lqsa, "qsa_score"), {mtl::Arg::B(qidx), mtl::Arg::B(pooled[qi]), mtl::Arg::B(dead[qi]), mtl::Arg::B(scores),
364                                             mtl::Arg::V(a)},
365                      ((pos0 + T) / 4 + 1 + 7) / 8, T, 256, "qsa score");
366                    D(P(lqsa, "qsa_topk"), {mtl::Arg::B(scores), mtl::Arg::B(qids), mtl::Arg::V(a)}, T, 1, 1024, "qsa sel");
367                } else {
368                    // within the budget the selection is the identity: qsa_topk only writes 0..n_kv-1
369                    D(P(lqsa, "qsa_topk"), {mtl::Arg::B(scores), mtl::Arg::B(qids), mtl::Arg::V(a)}, T, 1, 1024, "qsa sel");
370                }
371                if (qsa_mode == "flash") {
372                    const uint32_t nq = (uint32_t)T * 24 * 256;
373                    D(P(lqsa, "qsa_q_f16"), {mtl::Arg::B(qcur), mtl::Arg::B(qcurh), mtl::Arg::V(nq)}, (nq + 255) / 256, 1, 256, "qsa attn");
374                    D(P(lqsa, "qsa_flash", mtl::Constants().b(7, k4)),
375                      {mtl::Arg::B(qcurh), mtl::Arg::B(kq[qi]), mtl::Arg::B(vq[qi]), mtl::Arg::B(ksc[qi]), mtl::Arg::B(vsc[qi]),
376                       mtl::Arg::B(qids), mtl::Arg::B(qfull), mtl::Arg::B(xqh), mtl::Arg::V(a)},
377                      2, T, 128, "qsa attn");
378                    gemm(xqh, Wout, bo, T, N, 6144, "qsa proj");
379                    ++qi;
380                    goto moe;
381                }
382                if (qsa_mode == "mm") {
383                    const uint32_t nq = (uint32_t)T * 24 * 256;
384                    D(P(lqsa, "qsa_q_f16"), {mtl::Arg::B(qcur), mtl::Arg::B(qcurh), mtl::Arg::V(nq)}, (nq + 255) / 256, 1, 256, "qsa attn");
385                    D(P(lqsa, "qsa_attn_mm", mtl::Constants().b(7, k4)), {mtl::Arg::B(qcurh), mtl::Arg::B(kq[qi]), mtl::Arg::B(vq[qi]), mtl::Arg::B(ksc[qi]),
386                                               mtl::Arg::B(vsc[qi]), mtl::Arg::B(qids), mtl::Arg::B(part), mtl::Arg::V(a)},
387                      QCHUNKS, 2, 32, "qsa attn", T);
388                } else
389                D(P(lqsa, "qsa_attn"), {mtl::Arg::B(qcur), mtl::Arg::B(kq[qi]), mtl::Arg::B(vq[qi]), mtl::Arg::B(ksc[qi]),
390                                        mtl::Arg::B(vsc[qi]), mtl::Arg::B(qids), mtl::Arg::B(part), mtl::Arg::V(a)},
391                  QCHUNKS, 2, 256, "qsa attn", T);
392                D(P(lqsa, "qsa_merge"), {mtl::Arg::B(part), mtl::Arg::B(qfull), mtl::Arg::B(XQ), mtl::Arg::V(a)}, 24, T, 256,
393                  "qsa merge");
394                act16(XQ, xqh, (size_t)T * 6144, "qsa proj");
395                gemm(xqh, Wout, bo, T, N, 6144, "qsa proj");
396                ++qi;
397            }
398        moe:
399            // ---- MoE
400            hc_read(b + "hc_ffn", true, T);
401            const gguf::Tensor &tr = T_(b + "ffn_gate_inp.weight"), &tsg = T_(b + "ffn_gate_inp_shexp.weight"),
402                               &tg_ = T_(b + "ffn_gate_shexp.weight"), &tu_ = T_(b + "ffn_up_shexp.weight"),
403                               &td_ = T_(b + "ffn_down_shexp.weight"), &eg = T_(b + "ffn_gate_exps.weight"),
404                               &eu = T_(b + "ffn_up_exps.weight"), &ed = T_(b + "ffn_down_exps.weight");
405            dq(tr, Wr);
406            dq(tsg, Wsg);
407            dq(tg_, Wshg);
408            dq(tu_, Wshu);
409            dq(td_, Wshd);
410            gemm(mixh, Wr, logits, T, NEXP, N, "router");
411            const uint32_t nt = T;
412            D(P(lib, "route_topk"), {mtl::Arg::B(logits), mtl::Arg::B(ids), mtl::Arg::B(wts), mtl::Arg::V(nt), mtl::Arg::V((uint32_t)NEXP)}, (T + 7) / 8, 1,
413              256, "router");
414            const int nent = T * TOPK, nblk = (nent + 1023) / 1024;
415            MmPlanArgs pa{(uint32_t)nent, TOPK, NEXP, (uint32_t)TM, (uint32_t)nblk};
416            const uint32_t nclr = maxrows;
417            D(P(lib, "mm_clear"), {mtl::Arg::B(stok), mtl::Arg::V(nclr)}, (maxrows + 255) / 256, 1, 256, "experts");
418            D(P(lib, "mm_hist"), {mtl::Arg::B(ids), mtl::Arg::B(bcnt), mtl::Arg::V(pa)}, nblk, 1, 1024, "experts");
419            D(P(lib, "mm_scan"), {mtl::Arg::B(bcnt), mtl::Arg::B(boff), mtl::Arg::B(eoff), mtl::Arg::B(tiles), mtl::Arg::B(meta),
420                                  mtl::Arg::V(pa)}, 1, 1, NEXP, "experts");
421            D(P(lib, "mm_place"), {mtl::Arg::B(ids), mtl::Arg::B(wts), mtl::Arg::B(boff), mtl::Arg::B(eoff), mtl::Arg::B(stok),
422                                   mtl::Arg::B(sw), mtl::Arg::B(pos), mtl::Arg::V(pa)}, nblk, 1, 1024, "experts");
423            MmArgs ma{eg.offset, eu.offset, ed.offset, 0, 0, (uint32_t)ref::row_bytes(eg.type, N),
424                      (uint32_t)ref::row_bytes(ed.type, NFF), N, NFF};
425            ma.gu_stride = (uint64_t)ma.gu_row * NFF;
426            ma.d_stride = (uint64_t)ma.d_row * N;
427            const uint32_t ne = N;
428            mtl::Dispatch g;
429            g.p = P(lib, "mm_gather");
430            g.args = {mtl::Arg::B(mixed), mtl::Arg::B(stok), mtl::Arg::B(XS), mtl::Arg::V(ne)};
431            g.tg[0] = 256;
432            g.indirect = &meta;
433            g.ind_off = 8 * 4;
434            push(g, "experts");
435            mtl::Dispatch gu;
436            gu.p = gu_v3 ? P(lib, "mm_gu3_" + std::to_string(eg.type) + "_" + gu3_for(eg.type), mtl::Constants().b(7, k4))
437                         : P(lib, "mm_gu2_" + std::to_string(eg.type) + (fmt_unit32(eg.type) ? "_16_64_32_2" : "_16_64_16_2"),
438                             mtl::Constants().i(5, 0));
439            gu.args = {mtl::Arg::B(W), mtl::Arg::B(XS), mtl::Arg::B(HS), mtl::Arg::B(tiles), mtl::Arg::V(ma)};
440            gu.tg[0] = gu_v3 ? 32 * gu3[3] : 64;
441            gu.indirect = &meta;
442            gu.ind_off = 2 * 4;
443            push(gu, "experts gu");
444            mtl::Dispatch dn;
445            dn.p = dn_v3 ? P(lib, "mm_down3_" + std::to_string(ed.type) + "_" + tl3(dn3), mtl::Constants().b(7, k4))
446                         : P(lib, "mm_down2_" + std::to_string(ed.type) + (ed.type == ref::IQ4_NL ? "_16_64_32_2" : "_16_64_16_2"));
447            dn.args = {mtl::Arg::B(W), mtl::Arg::B(HS), mtl::Arg::B(YE), mtl::Arg::B(tiles), mtl::Arg::V(ma)};
448            dn.tg[0] = dn_v3 ? 32 * dn3[3] : 64;
449            dn.indirect = &meta;
450            dn.ind_off = 5 * 4;
451            push(dn, "experts dn");
452            const uint32_t ca[4] = {(uint32_t)T, N, TOPK, 0};
453            D(P(lib, "mm_combine"), {mtl::Arg::B(YE), mtl::Arg::B(pos), mtl::Arg::B(sw), mtl::Arg::B(yr), mtl::Arg::V(ca)},
454              (T * N + 255) / 256, 1, 256, "experts");
455            gemm(mixh, Wshg, gsh, T, NFF, N, "shared");
456            gemm(mixh, Wshu, ush, T, NFF, N, "shared");
457            const uint32_t nh = T * NFF;
458            D(P(lib, "swiglu_h"), {mtl::Arg::B(gsh), mtl::Arg::B(ush), mtl::Arg::B(hh), mtl::Arg::V(nh)}, (nh + 255) / 256, 1, 256,
459              "shared");
460            gemm(hh, Wshd, ys, T, N, NFF, "shared");
461            gemm(mixh, Wsg, sgv, T, 1, N, "shared");
462            const uint32_t oa[2] = {(uint32_t)T, N};
463            D(P(lib, "moe_out"), {mtl::Arg::B(yr), mtl::Arg::B(ys), mtl::Arg::B(sgv), mtl::Arg::B(bo), mtl::Arg::V(oa)},
464              (T * N + 255) / 256, 1, 256, "shared");
465        }
466        if (head) {
467            // the final read of the last row (decode kernels, 1 token) and the LM head
468            const size_t lr = (size_t)T - 1;
469            const gguf::Tensor &tn = T_("output_hc_norm.weight"), &tdn = T_("output_hc_down.weight"), &tup = T_("output_hc_up.weight");
470            GrArgs a{N, HC, LR, 1, 1, 1e-6f};
471            D(P(lib, "gr_norm"), {mtl::Arg::B(R, lr * HC * N * 4), mtl::Arg::B(bo, lr * N * 4), mtl::Arg::B(inj[cur_inj], lr * HC * 4),
472                                  mtl::Arg::B(W, tn.offset), mtl::Arg::B(xn1), mtl::Arg::V(a)}, HC, 1, 256, "head");
473            D(P(lib, "gr_down_8_8", mtl::Constants().i(1, 1), "gr_down_8_8#1"),
474              {mtl::Arg::B(W, tdn.offset), mtl::Arg::B(W, tdn.offset), mtl::Arg::B(xn1), mtl::Arg::B(lo1), mtl::Arg::B(inj1),
475               mtl::Arg::V(a)}, LR + HC, 1, 256, "head");
476            D(P(lib, "gr_up", mtl::Constants().i(1, 1), "gr_up#1"),
477              {mtl::Arg::B(W, tup.offset), mtl::Arg::B(lo1), mtl::Arg::B(xn1), mtl::Arg::B(X1), mtl::Arg::V(a)}, N / 16, 1, 256, "head");
478            const gguf::Tensor& to = T_("output.weight");
479            GemvArgs ga{N, NV, 1, (uint32_t)ref::row_bytes(to.type, N), N, NV};
480            const std::string fn = "gemv_" + std::to_string(to.type) + "_16_1_4_1";
481            const int xk = to.type == ref::Q4_K || to.type == ref::Q5_K ? 2 : (to.type == ref::Q6_K || to.type == ref::Q3_K) ? 3 : 0;
482            D(P(lib, fn, mtl::Constants().i(0, 1), fn + "#1"),
483              {mtl::Arg::B(W, to.offset), mtl::Arg::B(X1, (size_t)4 * N * xk), mtl::Arg::B(X1, (size_t)4 * N * 4), mtl::Arg::B(lm),
484               mtl::Arg::V(ga)}, (NV + 7) / 8, 1, 128, "head");
485            ArgArgs aa{NV, 120};
486            D(P(lsmp, "argmax_part"), {mtl::Arg::B(lm), mtl::Arg::B(apv), mtl::Arg::B(api), mtl::Arg::V(aa)}, 120, 1, 256, "head");
487            D(P(lsmp, "argmax_final"), {mtl::Arg::B(apv), mtl::Arg::B(api), mtl::Arg::B(tokout), mtl::Arg::V(aa)}, 1, 1, 256, "head");
488        }
489    };
490    // a chunk: the embedding rows into every stream, then the chunk's command buffer; GDN history ping-pong flipped
491    auto run_chunk = [&](int pos0, int T, bool head) {
492        for (int t = 0; t < T; ++t)
493            for (int c = 0; c < HC; ++c) std::memcpy(R.as<float>() + ((size_t)t * HC + c) * N, E.data() + (size_t)t * N, 4 * N);
494        cur_inj = 0;
495        build(pos0, T, head);
496        const double g = cx.run(ds);
497        for (auto& p : gpar) p ^= 1;
498        return g;
499    };
500    auto prompt = [&](int Pn, double* first_chunk) {
501        double tot = 0;
502        for (int p0 = 0; p0 < Pn; p0 += C) {
503            const int T = std::min(C, Pn - p0);
504            const double g = run_chunk(p0, T, p0 + T >= Pn);
505            if (p0 == 0 && first_chunk) *first_chunk = g;
506            tot += g;
507        }
508        return tot;
509    };
510    std::set<std::string> all_cls;
511    // warm: the first chunk until the clocks are up
512    {
513        const double t0 = mtl::now_s();
514        int n = 0;
515        while (mtl::now_s() - t0 < 1.5) { run_chunk(0, std::min(C, prompts[0]), false); ++n; }
516        std::printf("warm-up: %d chunks; %zu dispatches a chunk\n", n, ds.size());
517        all_cls.insert(cls.begin(), cls.end());
518    }
519    if (breakdown) {
520        // each class alone on the first chunk (pos0 0) and on a chunk at pos0 = PMAX - C (QSA past the budget)
521        if (PMAX > C) {   // the classes of a chunk past the budget (score) too
522            run_chunk(std::max(0, PMAX - C), C, false);
523            all_cls.insert(cls.begin(), cls.end());
524        }
525        for (int p0 : {0, std::max(0, PMAX - C)}) {
526            const std::string keep_only = only;
527            std::map<std::string, double> by;
528            double all = 0;
529            std::vector<std::string> names = {""};
530            for (const auto& c : all_cls) names.push_back(c);
531            for (const std::string& c : names) {
532                only = c;
533                std::vector<double> t;
534                for (int i = 0; i < 3; ++i) t.push_back(run_chunk(p0, C, false));
535                if (c.empty()) all = median(t);
536                else by[c] = median(t);
537            }
538            only = keep_only;
539            double sum = 0;
540            for (auto& kv : by) sum += kv.second;
541            std::printf("chunk of %d at pos %d: all %.2f ms (%.0f tok/s); classes alone (sum %.2f ms):\n", C, p0, all * 1e3, C / all,
542                        sum * 1e3);
543            for (auto& kv : by) std::printf("  %-10s %8.2f ms  %6.2f us a token\n", kv.first.c_str(), kv.second * 1e3, kv.second / C * 1e6);
544        }
545    }
546    for (int Pn : prompts) {
547        std::vector<double> t;
548        double fc = 0;
549        for (int r = 0; r < reps; ++r) t.push_back(prompt(Pn, &fc));
550        const double m = median(t);
551        std::printf("prompt %6d tokens (chunks of %d): GPU %8.1f ms -> %7.1f tok/s  (first chunk %.1f ms)\n", Pn, C, m * 1e3,
552                    Pn / m, fc * 1e3);
553    }
554    return 0;
555}