okami.mom/strata

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

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

main
41.1 KiB733 linesraw
1// metal/tests/token_chain.cpp - one decode step of the whole model, every kernel of metal/ on the REAL weights of a
2// GGUF (mmapped, wrapped no-copy as one MTLBuffer), each layer with its own tensor formats, all dispatches in one
3// command buffer: the GPU time of a decode token (or a verify window) with these kernels, dispatch boundaries
4// included.  Not a numerical check (the activations are synthetic): a timing of the real byte stream.
5//
6//   token_chain <shard-1.gguf> [--ntok N] [--ctx P] [--reps R] [--skip-qsa] [--only CLASS]
7//
8// Left out: the PLE path (one table row and two small projections at one layer) and the MTP draft.
9#include "gguf_lite.h"
10#include "mtl_rt.h"
11#include "ref_quant.h"
12
13#include <algorithm>
14#include <cmath>
15#include <cstdio>
16#include <cstdlib>
17#include <cstring>
18#include <map>
19#include <string>
20#include <sys/mman.h>
21#include <vector>
22
23namespace {
24
25constexpr int N = 2560, HC = 4, LR = 320, NFF = 640, TOPK = 10, NEXP = 512, MAXT = 8;
26constexpr int P_MAXE = 128, P_GEXP = 16, P_GSTART = P_GEXP + P_MAXE, P_ETOK = P_GSTART + P_MAXE + 4,
27              P_EW = P_ETOK + P_MAXE, P_TOKENT = P_EW + P_MAXE, P_INTS = P_TOKENT + P_MAXE, P_IGU = 4, P_IDN = 8;
28struct GemvArgs { uint32_t n_in, n_out, n_tok, row_bytes, x_stride, y_stride; };
29struct GrArgs { uint32_t n_embd, hc, hc_lr, n_tok, apply; float eps; };
30struct GrArgs3 { uint32_t n_embd, hc, hc_lr, n_tok, apply; float eps; uint32_t rb_down, rb_up, comb, topk; };
31struct MoeArgs {
32    uint64_t gate_off, up_off, down_off, gu_stride, d_stride;
33    uint32_t gu_row, d_row, n_embd, n_ff, n_tok, topk, n_expert, gx_gu, gx_dn, pad;
34};
35struct GdnArgs { uint32_t h_k, h_v, channels, commit; float eps; uint32_t plane; };
36struct QsaArgs { uint32_t pos0, pos_base, max_cells, n_tok; float eps; };
37struct GlueArgs { uint32_t n, n_tok, n_embd, topk; };
38struct HcfArgs { uint32_t n_embd, hc; float eps; uint32_t pad; };
39struct ArgArgs { uint32_t n_vocab, parts; };
40
41int xkind(int t) {
42    switch (t) {
43        case ref::Q2_0: return 1;
44        case ref::Q4_K: case ref::Q5_K: return 2;
45        case ref::Q6_K: case ref::Q3_K: return 3;
46        default: return 0;
47    }
48}
49double median(std::vector<double> v) { std::sort(v.begin(), v.end()); return v[v.size() / 2]; }
50
51// a prepared activation: 4 planes of n_tok rows of n, then the per-16 sums
52struct Act {
53    mtl::Buffer b;
54    int n = 0;
55    size_t plane_bytes() const { return (size_t)4 * MAXT * n; }
56};
57
58// CHAIN_DEFS=A,B: a "#define A 1" line for each name ahead of the kernels (probe switches)
59std::string defs_prelude() {
60    std::string out, w;
61    const char* e = std::getenv("CHAIN_DEFS");
62    if (!e) return out;
63    for (const char* p = e;; ++p) {
64        if (*p == ',' || *p == 0) { if (!w.empty()) out += "#define " + w + " 1" + char(10); w.clear(); if (!*p) break; }
65        else w += *p;
66    }
67    return out;
68}
69
70}  // namespace
71
72int main(int argc, char** argv) {
73    if (argc < 2) { std::fprintf(stderr, "usage: token_chain <shard-1.gguf> [--ntok N] [--ctx P] [--reps R]\n"); return 2; }
74    int ntok = 1, ctx = 1000, reps = 10;
75    bool skip_qsa = false, graph = false;
76    // the HC read: Q8_0 copies through the 3-dispatch read by default (the owner's decision, as STRATA_HC_Q8 on gfx12);
77    // STRATA_HC_Q8=0 selects the exact BF16 path.  --hc 3: BF16, 3 dispatches; 2: BF16, 2 dispatches; q8: Q8_0 copies,
78    // 2 dispatches; q8_3: Q8_0 copies, 3 dispatches
79    const char* hcq8 = std::getenv("STRATA_HC_Q8");
80    std::string hc_mode = hcq8 && std::string(hcq8) == "0" ? "3" : "q8_3";
81    bool fuse = false;           // the GDN y prep in the step; no QSA score/top-k within the selection budget
82    bool fold_comb = false;      // the MoE combine folded into the next 2-dispatch HC read (measured slower)
83    std::string only, skip;
84    for (int i = 2; i < argc; ++i) {
85        std::string a = argv[i];
86        if (a == "--ntok") ntok = std::atoi(argv[++i]);
87        else if (a == "--ctx") ctx = std::atoi(argv[++i]);
88        else if (a == "--reps") reps = std::atoi(argv[++i]);
89        else if (a == "--skip-qsa") skip_qsa = true;
90        else if (a == "--graph") graph = true;
91        else if (a == "--hc") hc_mode = argv[++i];
92        else if (a == "--fuse") fuse = true;
93        else if (a == "--fold-comb") fold_comb = true;
94        else if (a == "--only") only = argv[++i];
95        else if (a == "--skip") skip = argv[++i];
96    }
97    gguf::File f;
98    std::string err;
99    if (!f.open(argv[1], err)) { std::fprintf(stderr, "%s\n", err.c_str()); return 2; }
100    mtl::Context cx;
101    std::printf("device %s; %s: %zu tensors, %.1f GB; %d token(s), context %d\n", cx.device_name().c_str(),
102                argv[1], f.tensors.size(), f.file_bytes / 1e9, ntok, ctx);
103    // fault the file in (page cache), then wrap it
104    {
105        const double t0 = mtl::now_s();
106        madvise(f.map, f.map_bytes, MADV_WILLNEED);
107        volatile uint64_t s = 0;
108        for (size_t o = 0; o < f.file_bytes; o += 16384) s += ((const uint8_t*)f.map)[o];
109        std::printf("file touched in %.1f s\n", mtl::now_s() - t0);
110    }
111    mtl::Buffer W = cx.wrap(f.map, f.map_bytes);
112    auto T = [&](const std::string& name) -> const gguf::Tensor& {
113        const gguf::Tensor* t = f.find(name);
114        if (!t) { std::fprintf(stderr, "missing tensor %s\n", name.c_str()); std::exit(2); }
115        return *t;
116    };
117
118    const int lib = cx.compile({"quant.metal", "units.metal", "moe.metal", "gemv.metal", "gr.metal", "gr2.metal", "glue.metal",
119                                "router.metal", "hcf.metal", "gemvu.metal", "moeu.metal"},
120                               defs_prelude());
121    const int lgdn = cx.compile({"gdn.metal"}, "#define NO_GGML_COMMON 1\n");
122    const int lqsa = cx.compile({"qsa.metal", "qsa2.metal", "qsab.metal"},"#define NO_GGML_COMMON 1\n");
123    const int lsmp = cx.compile({"sample.metal"}, "#define NO_GGML_COMMON 1\n");
124    std::map<std::string, mtl::Pipeline> pcache;
125
126    // ---- buffers
127    const int MAXC = std::max(4096, (ctx + 64) / 4 * 4 + 64), MB = MAXC / 4 + 2;
128    mtl::Buffer R = cx.alloc(4 * MAXT * HC * N), bo = cx.alloc(4 * MAXT * N), inj[2] = {cx.alloc(4 * MAXT * HC), cx.alloc(4 * MAXT * HC)},
129                xn = cx.alloc(4 * MAXT * HC * N), lo = cx.alloc(4 * MAXT * LR), qkv = cx.alloc(4 * MAXT * 10240),
130                z = cx.alloc(4 * MAXT * 6144), al = cx.alloc(4 * MAXT * 48), be = cx.alloc(4 * MAXT * 48),
131                yg = cx.alloc(4 * MAXT * 6144), logits = cx.alloc(4 * MAXT * 512), ids = cx.alloc(4 * MAXT * TOPK),
132                wts = cx.alloc(4 * MAXT * TOPK), plan = cx.alloc(4 * P_INTS), h = cx.alloc(4 * MAXT * TOPK * NFF),
133                ye = cx.alloc(4 * MAXT * TOPK * N), gsh = cx.alloc(4 * MAXT * NFF), ush = cx.alloc(4 * MAXT * NFF),
134                ysh = cx.alloc(4 * MAXT * N), sg = cx.alloc(4 * MAXT * 4), qfull = cx.alloc(4 * MAXT * 12288),
135                kcur = cx.alloc(4 * MAXT * 512), vcur = cx.alloc(4 * MAXT * 512), iqr = cx.alloc(4 * MAXT * 512),
136                ikr = cx.alloc(4 * MAXT * 128), qcur = cx.alloc(4 * MAXT * 24 * 256), qidx = cx.alloc(4 * MAXT * 4 * 128),
137                scores = cx.alloc(4 * (size_t)MAXT * MB), qids = cx.alloc(4 * MAXT * 2051),
138                part = cx.alloc(4 * (size_t)MAXT * 65 * 24 * 258), cs = cx.alloc(8 * (size_t)(MAXC + 16) * 32),
139                lm = cx.alloc(4 * (size_t)MAXT * 248320), apv = cx.alloc(4 * MAXT * 120), api = cx.alloc(4 * MAXT * 120),
140                tokout = cx.alloc(4 * MAXT);
141    auto act = [&](int n) { Act a; a.n = n; a.b = cx.alloc(4 * ((size_t)4 * MAXT * n + (size_t)MAXT * n / 16)); return a; };
142    Act XA = act(N), XF = act(N), XY = act(6144), XQ = act(6144), XH = act(NFF);
143    for (size_t i = 0; i < R.bytes / 4; ++i) R.as<float>()[i] = 0.01f * (float)((i * 2654435761u) % 200) - 1.0f;
144    for (int p = 0; p < MAXC + 16; ++p)
145        for (int i = 0; i < 32; ++i) {
146            const double th = (double)p * std::pow(1e7, -2.0 * i / 64.0);
147            cs.as<float>()[(p * 32 + i) * 2] = (float)std::cos(th);
148            cs.as<float>()[(p * 32 + i) * 2 + 1] = (float)std::sin(th);
149        }
150    // per-layer recurrent state and QSA caches
151    std::vector<mtl::Buffer> gst, ghist, ghist2, kq, vq, ksc, vsc, tail, dead, pooled;
152    for (int l = 0; l < 48; ++l) {
153        if (l % 4 != 3) {
154            gst.push_back(cx.alloc(4 * 128 * 48 * 128));
155            ghist.push_back(cx.alloc(4 * 10240 * 3));
156            ghist2.push_back(cx.alloc(4 * 10240 * 3));
157        } else {
158            kq.push_back(cx.alloc((size_t)MAXC * 2 * 256));
159            vq.push_back(cx.alloc((size_t)MAXC * 2 * 256));
160            ksc.push_back(cx.alloc(2 * (size_t)MAXC * 2 * 4));
161            vsc.push_back(cx.alloc(2 * (size_t)MAXC * 2 * 4));
162            tail.push_back(cx.alloc(4 * 4 * 128));
163            dead.push_back(cx.alloc(4 * 128));
164            pooled.push_back(cx.alloc(4 * (size_t)MB * 128));
165        }
166    }
167    for (int t = 0; t < MAXT; ++t)
168        for (int c = 0; c < 2051; ++c) qids.as<int>()[t * 2051 + c] = c;
169    for (auto& b : vsc) for (size_t i = 0; i < b.bytes / 2; ++i) b.as<uint16_t>()[i] = 0x2000;   // small fp16 scales
170    for (auto& b : ksc) for (size_t i = 0; i < b.bytes / 2; ++i) b.as<uint16_t>()[i] = 0x2000;
171
172    std::vector<mtl::Dispatch> ds;
173    std::vector<std::string> cls;   // class of each dispatch (for --only)
174    std::map<std::string, double> bytes_by;
175    bool nb = false;   // the next push is independent of the previous dispatch (no barrier before it)
176    std::map<const mtl::Pipeline*, std::string> pname;
177    auto push = [&](const mtl::Dispatch& d0, const std::string& c, double bytes = 0) {
178        mtl::Dispatch d = d0;
179        d.barrier = !nb;
180        nb = false;
181        if (!only.empty() && c != only) return;
182        if (const char* sk = std::getenv("CHAIN_SKIPK")) {   // marginal cost of a kernel: drop every dispatch whose pipeline key contains sk
183            auto it = pname.find(d.p);
184            if (it != pname.end() && it->second.find(sk) != std::string::npos) return;
185        }
186        if (!skip.empty() && c == skip) return;
187        ds.push_back(d);
188        cls.push_back(c);
189        bytes_by[c] += bytes;
190    };
191    // pipelines whose names do not match the function (cached by key): create by function name first
192    auto Pn = [&](int l, const std::string& fn, const std::string& key, const mtl::Constants& c) -> const mtl::Pipeline* {
193        auto it = pcache.find(key);
194        if (it == pcache.end()) it = pcache.emplace(key, cx.pipeline(l, fn, c)).first;
195        pname[&it->second] = key;
196        return &it->second;
197    };
198    // ---- SLC prefetch (--prefetch): the next HC read's weights touched concurrently with the first projection GEMV
199    // after the current read, so the latency-bound read finds them in the SLC
200    const bool prefetch = std::getenv("CHAIN_PREFETCH") != nullptr;
201    const bool albe = std::getenv("CHAIN_ALBE") != nullptr;   // ssm_alpha + ssm_beta as one gemv_cat
202    // the router GEMV + moe_route as one router_route (default; CHAIN_ROUTE=0: separate)
203    const bool routef = !(std::getenv("CHAIN_ROUTE") && std::string(std::getenv("CHAIN_ROUTE")) == "0");
204    const bool combf = std::getenv("CHAIN_COMB") != nullptr;   // the MoE combine folded into the next gr_norm
205    bool comb_pending = false;
206    // routed gate/up: the i-quant grids from constant memory (QUANT_CTAB, function constant 23; bitwise; default,
207    // CHAIN_CTAB=0: the threadgroup copy)
208    const bool ctabf = !(std::getenv("CHAIN_CTAB") && std::string(std::getenv("CHAIN_CTAB")) == "0");
209    mtl::Buffer rcounter = cx.alloc(16);
210    struct Range { const mtl::Buffer* b; size_t off, bytes; };
211    std::vector<Range> pending;
212    mtl::Buffer sink = cx.alloc(16);
213    const mtl::Pipeline* ptouch = nullptr;
214    auto push_prefetch = [&]() {
215        for (const Range& r : pending) {
216            const uint32_t n16 = (uint32_t)(r.bytes / 16);
217            mtl::Dispatch d;
218            d.p = ptouch;
219            d.args = {mtl::Arg::B(*r.b, r.off), mtl::Arg::B(sink), mtl::Arg::V(n16)};
220            d.grid[0] = (n16 + 1023) / 1024;
221            d.tg[0] = 256;
222            nb = true;
223            push(d, "prefetch", (double)r.bytes);
224        }
225        pending.clear();
226    };
227    // ---- GEMV by tensor, with a tile from the measured table
228    auto gemv2 = [&](const gguf::Tensor& t, const Act& x, const mtl::Buffer& y, size_t y_stride, const std::string& c,
229                     int ty_override = -1) {
230        const int n_in = (int)t.shape[0], n_out = t.shape.size() > 1 ? (int)t.shape[1] : 1;
231        const int ty = ty_override >= 0 ? ty_override : t.type;
232        int L = 16, Rr = 1, S = 4, K = 1;
233        if (n_in >= 6144) { L = 32; Rr = 1; S = 8; K = 2; }
234        else if (n_in == 640) { L = 8; Rr = 1; S = 4; K = 1; }
235        else if (n_out <= 640 || ty == ref::Q2_0 || ty == ref::BF16) { L = 32; Rr = 1; S = 4; K = 1; }
236        const char* gu = std::getenv("CHAIN_GEMVU");
237        const std::string fn = std::string(gu ? "gemvu_" : "gemv_") + std::to_string(ty) + "_" + std::to_string(L) + "_" + std::to_string(Rr) + "_" +
238                               std::to_string(S) + "_" + std::to_string(K) + (gu ? std::string("_") + gu : std::string());
239        const mtl::Pipeline* p = Pn(lib, fn, fn + "#" + std::to_string(ntok), mtl::Constants().i(0, ntok));
240        GemvArgs a{(uint32_t)n_in, (uint32_t)n_out, (uint32_t)ntok, (uint32_t)ref::row_bytes(t.type, n_in), (uint32_t)n_in,
241                   (uint32_t)y_stride};
242        mtl::Dispatch d;
243        d.p = p;
244        d.args = {mtl::Arg::B(W, t.offset), mtl::Arg::B(x.b, x.plane_bytes() * xkind(ty)), mtl::Arg::B(x.b, x.plane_bytes() * 4),
245                  mtl::Arg::B(y), mtl::Arg::V(a)};
246        const int rpt = (S / K) * (32 / L) * Rr;
247        d.grid[0] = (n_out + rpt - 1) / rpt;
248        d.tg[0] = S * 32;
249        push(d, c, (double)t.bytes);
250        if (!pending.empty()) push_prefetch();
251    };
252    const mtl::Pipeline* pnorm = Pn(lib, std::getenv("CHAIN_NORM2") ? "gr_norm2" : "gr_norm", std::getenv("CHAIN_NORM2") ? "gr_norm2" : "gr_norm", {});
253    const mtl::Pipeline* pnormc = Pn(lib, "gr_norm_comb", "gr_norm_comb", {});
254    ptouch = Pn(lib, "slc_touch", "slc_touch", {});
255    const mtl::Pipeline* pdown = Pn(lib, "gr_down_8_8", "gr_down_8_8", mtl::Constants().i(1, ntok));
256    const mtl::Pipeline* pup = Pn(lib, "gr_up", "gr_up", mtl::Constants().i(1, ntok));
257    const mtl::Pipeline* pdownq = Pn(lib, "gr_down_q8_8_8", "gr_down_q8_8_8", mtl::Constants().i(1, ntok));
258    const mtl::Pipeline* pupq = Pn(lib, "gr_up_q8", "gr_up_q8", mtl::Constants().i(1, ntok));
259    const mtl::Pipeline* pprep = Pn(lib, "xprep", "xprep", {});
260    const mtl::Pipeline* proute = Pn(lib, "moe_route", "moe_route", {});
261    const mtl::Pipeline* pswi = Pn(lib, "swiglu_prep", "swiglu_prep", {});
262    const mtl::Pipeline* pcomb = Pn(lib, std::getenv("CHAIN_COMB2") ? "moe_combine_sh2" : "moe_combine_sh", std::getenv("CHAIN_COMB2") ? "moe_combine_sh2" : "moe_combine_sh", {});
263    const mtl::Pipeline* pgdn = Pn(lgdn, "gdn_step", "gdn_step", mtl::Constants().i(2, ntok));
264    const mtl::Pipeline* qprep = Pn(lqsa, "qsa_prep", "qsa_prep", {});
265    const mtl::Pipeline* qscore = Pn(lqsa, "qsa_score", "qsa_score", {});
266    const int qav = std::getenv("QSA_ATTN") ? std::atoi(std::getenv("QSA_ATTN")) : 1;
267    const bool qv2 = qav == 2;
268    const mtl::Pipeline* qtopk = Pn(lqsa, std::getenv("QSA_TOPK") ? "qsa_topk" : "qsa_topk2", "qsa_topk", {});
269    const mtl::Pipeline* qattn = Pn(lqsa, qav == 1 ? (std::getenv("CHAIN_QB") ? "qsa_attn_b" : "qsa_attn") : qv2 ? "qsa_attn2" : "qsa_attn3", "qsa_attn", {});
270    const mtl::Pipeline* qmerge = Pn(lqsa, qv2 ? "qsa_merge2" : "qsa_merge", "qsa_merge", {});
271    const mtl::Pipeline* pam1 = Pn(lsmp, "argmax_part", "argmax_part", {});
272    const mtl::Pipeline* pam2 = Pn(lsmp, "argmax_final", "argmax_final", {});
273
274    // the 2-dispatch read: residual and partial-dot ping-pong buffers, rs; the Q8_0 copies of the HC matrices
275    mtl::Buffer Rb[2] = {R, cx.alloc(4 * MAXT * HC * N)}, Db[2] = {cx.alloc(4 * MAXT * (LR + HC) * HC), cx.alloc(4 * MAXT * (LR + HC) * HC)},
276                rsb = cx.alloc(4 * MAXT * HC);
277    int cur_r = 0, cur_d = 0;
278    std::map<std::string, size_t> q8off;
279    mtl::Buffer Q8;
280    if (hc_mode == "q8" || hc_mode == "q8_3") {
281        size_t tot = 0;
282        for (const auto& kv : f.tensors) {
283            const gguf::Tensor& t = kv.second;
284            if (t.type != ref::BF16 || t.name.find("hc_") == std::string::npos || t.name.find("_norm") != std::string::npos) continue;
285            uint64_t ne = 1;
286            for (uint64_t d : t.shape) ne *= d;
287            q8off[t.name] = tot;
288            tot += ne / 32 * 34;
289        }
290        Q8 = cx.alloc((tot + 4095) / 4096 * 4096);
291        const double t0 = mtl::now_s();
292        std::vector<float> tmp;
293        for (const auto& kv : q8off) {
294            const gguf::Tensor& t = *f.find(kv.first);
295            uint64_t ne = 1;
296            for (uint64_t d : t.shape) ne *= d;
297            tmp.resize(ne);
298            ref::dequant(ref::BF16, (const uint8_t*)f.map + t.offset, tmp.data(), ne);
299            ref::quantize_q8_0(tmp.data(), ne, Q8.as<uint8_t>() + kv.second);
300        }
301        std::printf("HC Q8_0 copies: %zu tensors, %.1f MB, quantized in %.1f s\n", q8off.size(), tot / 1e6, mtl::now_s() - t0);
302    }
303    int cur_inj = 0;
304    // CHAIN_HCF: gr_norm folded into the producer of bo (hcf.metal): the mixer's output GEMV and the MoE combine apply bo to R
305    // and the last threadgroup forms xn; the next read has no gr_norm dispatch
306    const bool hcf = std::getenv("CHAIN_HCF") != nullptr && (hc_mode == "q8_3" || hc_mode == "3");
307    const bool hcf_keep = std::getenv("CHAIN_KEEPNORM") != nullptr;   // timing probe: swap the producers, keep gr_norm
308    const std::string hcf_only = std::getenv("CHAIN_HCF_ONLY") ? std::getenv("CHAIN_HCF_ONLY") : "";   // gemv | comb
309    bool hcf_pend = false;
310    mtl::Buffer hcnt = cx.alloc(16), sink2 = cx.alloc(256);
311    auto hcf_args = [&](const std::string& nextpre) {
312        HcfArgs h{N, HC, 1e-6f, 0};
313        return std::vector<mtl::Arg>{mtl::Arg::B(R), mtl::Arg::B(inj[cur_inj]), mtl::Arg::B(W, T(nextpre + "_norm.weight").offset),
314                                     mtl::Arg::B(xn), mtl::Arg::B(hcnt), mtl::Arg::V(h)};
315    };
316    // a producer GEMV of bo (n_in >= 6144: the 32,1,8,2 tile): gemv2, or with CHAIN_HCF gemvh (R updated, xn formed by the last threadgroup)
317    auto gemv_p = [&](const gguf::Tensor& t, const Act& x, const mtl::Buffer& y, size_t y_stride, const std::string& c,
318                      const std::string& nextpre) {
319        const int n_in = (int)t.shape[0], n_out = (int)t.shape[1];
320        if (!hcf || n_in < 6144 || hcf_only == "comb") { gemv2(t, x, y, y_stride, c); return; }
321        const std::string fn = "gemvh_" + std::to_string(t.type);
322        const mtl::Pipeline* p = Pn(lib, fn, fn + "#" + std::to_string(ntok), mtl::Constants().i(0, ntok));
323        GemvArgs a{(uint32_t)n_in, (uint32_t)n_out, (uint32_t)ntok, (uint32_t)ref::row_bytes(t.type, n_in), (uint32_t)n_in,
324                   (uint32_t)y_stride};
325        mtl::Dispatch d;
326        d.p = p;
327        d.args = {mtl::Arg::B(W, t.offset), mtl::Arg::B(x.b, x.plane_bytes() * xkind(t.type)), mtl::Arg::B(x.b, x.plane_bytes() * 4),
328                  mtl::Arg::B(y), mtl::Arg::V(a)};
329        for (auto& g : hcf_args(nextpre)) d.args.push_back(g);
330        d.grid[0] = (n_out + 3) / 4;   // rpt = (S / K) * (32 / L) * Rr = 4
331        d.tg[0] = 256;
332        push(d, c, (double)t.bytes);
333        hcf_pend = !hcf_keep;
334    };
335    auto gr_read = [&](const std::string& pre, bool apply, const Act& out, bool final_) {
336        if (hc_mode != "3" && hc_mode != "q8_3") {
337            const bool q8 = hc_mode == "q8";
338            const gguf::Tensor& tn = T(pre + "_norm.weight");
339            const gguf::Tensor& tdn = T(pre + "_down.weight");
340            const gguf::Tensor& tup = T(pre + "_up.weight");
341            const gguf::Tensor& tin = final_ ? tdn : T(pre + "_inject.weight");
342            const int tt = std::min(ntok, 3);
343            const std::string dn = std::string("gr_down3_") + (q8 ? "8_" : "30_") + std::to_string(tt) + "_2";
344            const std::string up = std::string("gr_up3_") + (q8 ? "8" : "30");
345            // after an MoE (the next layer's mixer read, the final read) the combine is folded in here
346            const bool comb = fold_comb && apply && pre.find("hc_ffn") == std::string::npos;
347            GrArgs3 a{N, HC, LR, MAXT, apply ? 1u : 0u, 1e-6f, (uint32_t)(q8 ? HC * N / 32 * 34 : HC * N * 2),
348                      (uint32_t)(q8 ? LR / 32 * 34 : LR * 2), comb ? 1u : 0u, (uint32_t)TOPK};
349            const mtl::Buffer& WB = q8 ? Q8 : W;
350            const size_t od = q8 ? q8off.at(tdn.name) : tdn.offset, oi = q8 ? q8off.at(tin.name) : tin.offset,
351                         ou = q8 ? q8off.at(tup.name) : tup.offset;
352            mtl::Dispatch d;
353            d.p = Pn(lib, dn, dn + "#" + std::to_string(ntok), mtl::Constants().i(1, ntok));
354            d.args = {mtl::Arg::B(WB, od), mtl::Arg::B(WB, oi), mtl::Arg::B(Rb[cur_r]), mtl::Arg::B(Rb[1 - cur_r]),
355                      mtl::Arg::B(bo), mtl::Arg::B(Db[cur_d]), mtl::Arg::B(W, tn.offset), mtl::Arg::B(Db[1 - cur_d]),
356                      mtl::Arg::B(rsb), mtl::Arg::V(a), mtl::Arg::B(plan), mtl::Arg::B(ye), mtl::Arg::B(ysh), mtl::Arg::B(sg)};
357            d.grid[0] = (LR + HC + 15) / 16;
358            d.grid[1] = HC;
359            d.tg[0] = 256;
360            const double wb = q8 ? (tdn.bytes + (final_ ? 0 : tin.bytes)) * 34.0 / 64.0 : (double)tdn.bytes + (final_ ? 0 : tin.bytes);
361            push(d, "hc", wb);
362            cur_r = 1 - cur_r;
363            cur_d = 1 - cur_d;
364            mtl::Dispatch u;
365            u.p = Pn(lib, up, up + "#" + std::to_string(ntok), mtl::Constants().i(1, ntok));
366            u.args = {mtl::Arg::B(WB, ou), mtl::Arg::B(Db[cur_d]), mtl::Arg::B(Rb[cur_r]), mtl::Arg::B(out.b), mtl::Arg::V(a),
367                      mtl::Arg::B(W, tn.offset), mtl::Arg::B(rsb)};
368            u.grid[0] = N / 16;
369            u.tg[0] = 256;
370            push(u, "hc", q8 ? tup.bytes * 34.0 / 64.0 : (double)tup.bytes);
371            return;
372        }
373        const gguf::Tensor& tn = T(pre + "_norm.weight");
374        const gguf::Tensor& tdn = T(pre + "_down.weight");
375        const gguf::Tensor& tup = T(pre + "_up.weight");
376        const gguf::Tensor& tin = final_ ? tdn : T(pre + "_inject.weight");
377        GrArgs a{N, HC, LR, (uint32_t)ntok, apply ? 1u : 0u, 1e-6f};
378        const bool q83 = hc_mode == "q8_3";
379        const mtl::Buffer& WB = q83 ? Q8 : W;
380        const size_t od = q83 ? q8off.at(tdn.name) : tdn.offset, oi = q83 ? q8off.at(tin.name) : tin.offset,
381                     ou = q83 ? q8off.at(tup.name) : tup.offset;
382        mtl::Dispatch d1;
383        d1.p = pnorm;
384        d1.args = {mtl::Arg::B(R), mtl::Arg::B(bo), mtl::Arg::B(inj[cur_inj]), mtl::Arg::B(W, tn.offset), mtl::Arg::B(xn),
385                   mtl::Arg::V(a)};
386        if (comb_pending) {
387            // the MoE combine folded into this norm (gr_norm_comb; bitwise moe_combine_sh + gr_norm)
388            const uint32_t tk = TOPK;
389            d1.p = pnormc;
390            d1.args = {mtl::Arg::B(R), mtl::Arg::B(ye), mtl::Arg::B(inj[cur_inj]), mtl::Arg::B(W, tn.offset), mtl::Arg::B(xn),
391                       mtl::Arg::V(a), mtl::Arg::B(plan), mtl::Arg::B(ysh), mtl::Arg::B(sg), mtl::Arg::V(tk)};
392            comb_pending = false;
393        }
394        d1.grid[0] = HC;
395        d1.grid[1] = ntok;
396        d1.tg[0] = 256;
397        if (!std::getenv("CHAIN_NONORM") && !(hcf_pend && apply)) push(d1, "hc", 0);
398        if (const char* e = std::getenv("CHAIN_NOOPS")) {
399            for (int k = 0; k < std::atoi(e); ++k) {
400                mtl::Dispatch z;
401                z.p = Pn(lib, "noop_k", "noop_k", {});
402                z.args = {mtl::Arg::B(sink2)};
403                z.grid[0] = 1;
404                z.tg[0] = 32;
405                push(z, "hc", 0);
406            }
407        }
408        hcf_pend = false;   // CHAIN_NONORM: marginal cost of the norm dispatch (timing only)
409        mtl::Dispatch d2;
410        d2.p = q83 ? pdownq : pdown;
411        d2.args = {mtl::Arg::B(WB, od), mtl::Arg::B(WB, oi), mtl::Arg::B(xn), mtl::Arg::B(lo),
412                   mtl::Arg::B(inj[1 - cur_inj]), mtl::Arg::V(a)};
413        d2.grid[0] = LR + HC;
414        d2.tg[0] = 256;
415        push(d2, "hc", (double)tdn.bytes + (final_ ? 0 : tin.bytes));
416        mtl::Dispatch d3;
417        d3.p = q83 ? pupq : pup;
418        d3.args = {mtl::Arg::B(WB, ou), mtl::Arg::B(lo), mtl::Arg::B(xn), mtl::Arg::B(out.b), mtl::Arg::V(a)};
419        d3.grid[0] = N / 16;
420        d3.tg[0] = 256;
421        push(d3, "hc", (double)tup.bytes);
422        cur_inj = 1 - cur_inj;
423        if (prefetch && !final_) {
424            // the next read: blk.l.hc_attn -> blk.l.hc_ffn -> blk.(l+1).hc_attn ... -> output_hc
425            std::string nx;
426            const size_t at = pre.find(".hc_attn");
427            if (at != std::string::npos) nx = pre.substr(0, at) + ".hc_ffn";
428            else {
429                const int l = std::atoi(pre.c_str() + 4);
430                nx = l == 47 ? std::string("output_hc") : "blk." + std::to_string(l + 1) + ".hc_attn";
431            }
432            const bool fin = nx == "output_hc";
433            for (const std::string& part : fin ? std::vector<std::string>{"_down", "_up"}
434                                               : std::vector<std::string>{"_down", "_inject", "_up"}) {
435                const gguf::Tensor& tt = T(nx + part + ".weight");
436                if (q83) {
437                    uint64_t ne = 1;
438                    for (uint64_t dd : tt.shape) ne *= dd;
439                    pending.push_back({&Q8, q8off.at(tt.name), (size_t)(ne / 32 * 34) / 16 * 16});
440                } else {
441                    pending.push_back({&W, tt.offset, (size_t)tt.bytes / 16 * 16});
442                }
443            }
444        }
445    };
446    auto xprep = [&](const mtl::Buffer& x, const Act& out, int n, const std::string& c) {
447        mtl::Dispatch d;
448        d.p = pprep;
449        const uint32_t nn = n, nt = MAXT;
450        d.args = {mtl::Arg::B(x), mtl::Arg::B(out.b), mtl::Arg::V(nn), mtl::Arg::V(nt)};
451        d.tg[0] = 256;
452        d.grid[0] = (n / 16 * MAXT + 255) / 256;
453        push(d, c, 0);
454    };
455    // Every prepared activation has planes of MAXT rows (Act::plane_bytes); the producers that take a token count
456    // for the plane stride (gr_up, qsa_merge, swiglu_prep, xprep) are given MAXT there.
457
458    int gi = 0, qi = 0;
459    for (int l = 0; l < 48; ++l) {
460        const std::string b = "blk." + std::to_string(l) + ".";
461        // ---- mixer
462        gr_read(b + "hc_attn", l > 0, XA, false);
463        if (l % 4 != 3) {
464            gemv2(T(b + "attn_qkv.weight"), XA, qkv, 10240, "gdn proj");
465            nb = true;
466            gemv2(T(b + "attn_gate.weight"), XA, z, 6144, "gdn proj");
467            nb = true;
468            if (albe) {
469                // ssm_alpha + ssm_beta in one dispatch (gemv_cat; bitwise the two GEMVs)
470                const gguf::Tensor &ta = T(b + "ssm_alpha.weight"), &tb = T(b + "ssm_beta.weight");
471                const std::string fn = "gemvc_" + std::to_string(ta.type) + "_32_1_4";
472                mtl::Dispatch d;
473                d.p = Pn(lib, fn, fn + "#" + std::to_string(ntok), mtl::Constants().i(0, ntok));
474                GemvArgs ga{(uint32_t)N, 96, (uint32_t)ntok, (uint32_t)ref::row_bytes(ta.type, N), (uint32_t)N, 48};
475                const uint32_t sp = 48;
476                d.args = {mtl::Arg::B(W, ta.offset), mtl::Arg::B(XA.b, XA.plane_bytes() * xkind(ta.type)),
477                          mtl::Arg::B(XA.b, XA.plane_bytes() * 4), mtl::Arg::B(al), mtl::Arg::V(ga), mtl::Arg::B(W, tb.offset),
478                          mtl::Arg::B(be), mtl::Arg::V(sp)};
479                d.grid[0] = 96 / 4;
480                d.tg[0] = 128;
481                push(d, "gdn proj", (double)ta.bytes + tb.bytes);
482            } else {
483                gemv2(T(b + "ssm_alpha.weight"), XA, al, 48, "gdn proj");
484                nb = true;
485                gemv2(T(b + "ssm_beta.weight"), XA, be, 48, "gdn proj");
486            }
487            GdnArgs a{16, 48, 10240, 1, 1e-6f, fuse ? (uint32_t)(MAXT * 6144) : 0u};
488            mtl::Dispatch d;
489            d.p = pgdn;
490            d.args = {mtl::Arg::B(gst[gi]), mtl::Arg::B(ghist[gi]), mtl::Arg::B(qkv), mtl::Arg::B(al), mtl::Arg::B(be),
491                      mtl::Arg::B(z), mtl::Arg::B(W, T(b + "ssm_conv1d.weight").offset), mtl::Arg::B(W, T(b + "ssm_dt.bias").offset),
492                      mtl::Arg::B(W, T(b + "ssm_a").offset), mtl::Arg::B(W, T(b + "ssm_norm.weight").offset), mtl::Arg::B(fuse ? XY.b : yg),
493                      mtl::Arg::V(a), mtl::Arg::B(ghist2[gi])};
494            d.grid[0] = std::getenv("CHAIN_GDNGRID") ? std::atoi(std::getenv("CHAIN_GDNGRID")) : 48;   // timing probe (wrong values)
495            d.tg[0] = 512;
496            push(d, "gdn step", 2.0 * 4 * 128 * 48 * 128);
497            if (!fuse) xprep(yg, XY, 6144, "gdn proj");
498            gemv_p(T(b + "ssm_out.weight"), XY, bo, N, "gdn proj", b + "hc_ffn");
499            ++gi;
500        } else if (!skip_qsa) {
501            gemv2(T(b + "attn_q.weight"), XA, qfull, 12288, "qsa proj");
502            nb = true;
503            gemv2(T(b + "attn_k.weight"), XA, kcur, 512, "qsa proj");
504            nb = true;
505            gemv2(T(b + "attn_v.weight"), XA, vcur, 512, "qsa proj");
506            nb = true;
507            gemv2(T(b + "indexer.q_proj.weight"), XA, iqr, 512, "qsa proj");
508            nb = true;
509            gemv2(T(b + "indexer.k_proj.weight"), XA, ikr, 128, "qsa proj");
510            QsaArgs a{(uint32_t)ctx, 0, (uint32_t)MAXC, (uint32_t)ntok, 1e-6f};
511            mtl::Dispatch d;
512            d.p = qprep;
513            d.args = {mtl::Arg::B(qfull), mtl::Arg::B(kcur), mtl::Arg::B(vcur), mtl::Arg::B(iqr), mtl::Arg::B(ikr),
514                      mtl::Arg::B(W, T(b + "attn_q_norm.weight").offset), mtl::Arg::B(W, T(b + "attn_k_norm.weight").offset),
515                      mtl::Arg::B(W, T(b + "indexer.q_norm.weight").offset), mtl::Arg::B(W, T(b + "indexer.k_norm.weight").offset),
516                      mtl::Arg::B(cs), mtl::Arg::B(qcur), mtl::Arg::B(qidx), mtl::Arg::B(kq[qi]), mtl::Arg::B(vq[qi]),
517                      mtl::Arg::B(ksc[qi]), mtl::Arg::B(vsc[qi]), mtl::Arg::B(tail[qi]), mtl::Arg::B(dead[qi]),
518                      mtl::Arg::B(pooled[qi]), mtl::Arg::V(a)};
519            d.grid[0] = 33;
520            d.grid[1] = ntok;
521            d.tg[0] = 256;
522            push(d, "qsa attn", 0);
523            const bool sel = !(fuse && ctx + ntok <= 2051);   // within the budget the selection is the identity
524            mtl::Dispatch s;
525            s.p = qscore;
526            s.args = {mtl::Arg::B(qidx), mtl::Arg::B(pooled[qi]), mtl::Arg::B(dead[qi]), mtl::Arg::B(scores), mtl::Arg::V(a)};
527            s.grid[0] = ((ctx + ntok) / 4 + 1 + 7) / 8;
528            s.grid[1] = ntok;
529            s.tg[0] = 256;
530            if (sel) push(s, "qsa attn", 0);
531            mtl::Dispatch k;
532            k.p = qtopk;
533            k.args = {mtl::Arg::B(scores), mtl::Arg::B(qids), mtl::Arg::V(a)};
534            k.grid[0] = ntok;
535            k.tg[0] = 1024;
536            if (sel) push(k, "qsa attn", 0);
537            mtl::Dispatch at;
538            at.p = qattn;
539            at.args = {mtl::Arg::B(qcur), mtl::Arg::B(kq[qi]), mtl::Arg::B(vq[qi]), mtl::Arg::B(ksc[qi]), mtl::Arg::B(vsc[qi]),
540                       mtl::Arg::B(qids), mtl::Arg::B(part), mtl::Arg::V(a)};
541            at.grid[0] = qv2 ? 65 : 33;
542            at.grid[1] = qv2 ? 4 : 2;
543            at.grid[2] = ntok;
544            at.tg[0] = 256;
545            push(at, "qsa attn", 2.0 * 2 * 512 * std::min(ctx, 2051));
546            mtl::Dispatch m;
547            m.p = qmerge;
548            QsaArgs am = a;
549            am.n_tok = MAXT;   // the plane stride (see above)
550            m.args = {mtl::Arg::B(part), mtl::Arg::B(qfull), mtl::Arg::B(XQ.b), mtl::Arg::V(am)};
551            m.grid[0] = 24;
552            m.grid[1] = ntok;
553            m.tg[0] = 256;
554            push(m, "qsa attn", 0);
555            gemv_p(T(b + "attn_output.weight"), XQ, bo, N, "qsa proj", b + "hc_ffn");
556            ++qi;
557        }
558        // ---- MoE
559        gr_read(b + "hc_ffn", true, XF, false);
560        if (!routef) {
561            gemv2(T(b + "ffn_gate_inp.weight"), XF, logits, 512, "router");
562            nb = true;
563        }
564        const bool pair = fuse && std::getenv("CHAIN_PAIR");   // measured slower (+0.11 ms): opt-in
565        if (pair) {
566            // the shared expert's gate + up + SwiGLU in one dispatch, h raw into XH's raw plane
567            const gguf::Tensor &tgs = T(b + "ffn_gate_shexp.weight"), &tus = T(b + "ffn_up_shexp.weight");
568            const std::string fn = "gemv_pair_" + std::to_string(tgs.type) + "_" + std::to_string(tus.type);
569            mtl::Dispatch d;
570            d.p = Pn(lib, fn, fn + "#" + std::to_string(ntok), mtl::Constants().i(0, ntok));
571            GemvArgs ga{(uint32_t)N, (uint32_t)NFF, (uint32_t)ntok, (uint32_t)ref::row_bytes(tgs.type, N), (uint32_t)N,
572                        (uint32_t)NFF};
573            const uint32_t rbu = (uint32_t)ref::row_bytes(tus.type, N);
574            d.args = {mtl::Arg::B(W, tgs.offset), mtl::Arg::B(XF.b, XF.plane_bytes() * xkind(tgs.type)),
575                      mtl::Arg::B(W, tus.offset), mtl::Arg::B(XF.b, XF.plane_bytes() * xkind(tus.type)),
576                      mtl::Arg::B(XF.b, XF.plane_bytes() * 4), mtl::Arg::B(XH.b), mtl::Arg::V(ga), mtl::Arg::V(rbu)};
577            d.grid[0] = NFF / 4;
578            d.tg[0] = 128;
579            push(d, "shared", (double)tgs.bytes + tus.bytes);
580        } else {
581            gemv2(T(b + "ffn_gate_shexp.weight"), XF, gsh, NFF, "shared");
582            nb = true;
583            gemv2(T(b + "ffn_up_shexp.weight"), XF, ush, NFF, "shared");
584        }
585        nb = true;
586        gemv2(T(b + "ffn_gate_inp_shexp.weight"), XF, sg, 1, "shared");
587        {
588            MoeArgs a{};
589            const gguf::Tensor &tg_ = T(b + "ffn_gate_exps.weight"), &tu = T(b + "ffn_up_exps.weight"),
590                               &td = T(b + "ffn_down_exps.weight");
591            a.gate_off = tg_.offset;
592            a.up_off = tu.offset;
593            a.down_off = td.offset;
594            a.gu_row = (uint32_t)ref::row_bytes(tg_.type, N);
595            a.d_row = (uint32_t)ref::row_bytes(td.type, NFF);
596            a.gu_stride = (uint64_t)a.gu_row * NFF;
597            a.d_stride = (uint64_t)a.d_row * N;
598            a.n_embd = N;
599            a.n_ff = NFF;
600            a.n_tok = ntok;
601            a.topk = TOPK;
602            a.n_expert = NEXP;
603            // tiles (lanes per row, rows per lane, simdgroups): CHAIN_GU / CHAIN_DN / CHAIN_DN4 override
604            const bool dq2 = td.type == ref::Q2_0;
605            int gl = 32, gr = 1, gs = 4, dl = dq2 ? 8 : 4, dr = dq2 ? 1 : 2, ds_ = 4;
606            if (const char* e = std::getenv("CHAIN_GU")) std::sscanf(e, "%d,%d,%d", &gl, &gr, &gs);
607            if (const char* e = std::getenv(dq2 ? "CHAIN_DN" : "CHAIN_DN4")) std::sscanf(e, "%d,%d,%d", &dl, &dr, &ds_);
608            a.gx_gu = NFF / (gs * (32 / gl) * gr);
609            a.gx_dn = N / (ds_ * (32 / dl) * dr);
610            if (routef) {
611                // the router GEMV + moe_route in one dispatch (router_route; bitwise), concurrent with the shared GEMVs
612                const gguf::Tensor& tr = T(b + "ffn_gate_inp.weight");
613                mtl::Dispatch r;
614                r.p = Pn(lib, "router_route_30", "router_route#" + std::to_string(ntok), mtl::Constants().i(0, ntok));
615                GemvArgs ga{(uint32_t)N, 512, (uint32_t)ntok, (uint32_t)ref::row_bytes(tr.type, N), (uint32_t)N, 512};
616                r.args = {mtl::Arg::B(W, tr.offset), mtl::Arg::B(XF.b, 0), mtl::Arg::B(XF.b, XF.plane_bytes() * 4),
617                          mtl::Arg::B(logits), mtl::Arg::V(ga), mtl::Arg::B(ids), mtl::Arg::B(wts), mtl::Arg::B(plan),
618                          mtl::Arg::V(a), mtl::Arg::B(rcounter)};
619                r.grid[0] = 512 / 16;
620                r.tg[0] = 512;
621                nb = true;
622                push(r, "router", (double)tr.bytes);
623            } else {
624                mtl::Dispatch r;
625                r.p = proute;
626                r.args = {mtl::Arg::B(logits), mtl::Arg::B(ids), mtl::Arg::B(wts), mtl::Arg::B(plan), mtl::Arg::V(a)};
627                r.tg[0] = 512;
628                push(r, "router", 0);
629            }
630            {
631                GlueArgs ga{NFF, MAXT, N, TOPK};
632                mtl::Dispatch d;
633                d.p = pswi;
634                d.args = {mtl::Arg::B(gsh), mtl::Arg::B(ush), mtl::Arg::B(XH.b), mtl::Arg::V(ga)};
635                d.grid[0] = NFF / 16;
636                d.grid[1] = ntok;
637                d.tg[0] = 16;
638                nb = true;
639                if (!pair) push(d, "shared", 0);
640                nb = false;
641            }
642            const char* mu = std::getenv("CHAIN_MOEU");
643            const std::string gun = std::string(mu ? "moe_guu_" : "moe_gu_") + std::to_string(tg_.type) + "_" + std::to_string(gl) + "_" +
644                                    std::to_string(gr) + "_" + std::to_string(gs) + (mu ? std::string("_") + mu : std::string());
645            const std::string dnn = std::string(mu ? "moe_dnu_" : "moe_down_") + std::to_string(dq2 ? 142 : td.type) + "_" + std::to_string(dl) + "_" +
646                                    std::to_string(dr) + "_" + std::to_string(ds_) + (mu ? std::string("_") + mu : std::string());
647            mtl::Dispatch g;
648            g.p = Pn(lib, gun, gun + (ctabf ? "#ct" : ""), mtl::Constants().b(23, ctabf));
649            g.args = {mtl::Arg::B(W), mtl::Arg::B(XF.b, XF.plane_bytes() * xkind(tg_.type)), mtl::Arg::B(h), mtl::Arg::B(plan),
650                      mtl::Arg::V(a), mtl::Arg::B(XF.b, XF.plane_bytes() * 4)};
651            g.tg[0] = 32 * gs;
652            g.indirect = &plan;
653            g.ind_off = P_IGU * 4;
654            push(g, "experts", 10.0 * ntok * 2 * a.gu_stride);
655            nb = true;
656            {
657                const gguf::Tensor& tds = T(b + "ffn_down_shexp.weight");
658                // with --fuse h is raw: a Q2_0 down reads it through the raw-activation decoder (type 142)
659                gemv2(tds, XH, ysh, N, "shared", pair && tds.type == ref::Q2_0 ? 142 : -1);
660            }
661            mtl::Dispatch dd;
662            dd.p = Pn(lib, dnn, dnn, {});
663            dd.args = {mtl::Arg::B(W), mtl::Arg::B(h), mtl::Arg::B(ye), mtl::Arg::B(plan), mtl::Arg::V(a), mtl::Arg::B(h)};
664            dd.tg[0] = 32 * ds_;
665            dd.indirect = &plan;
666            dd.ind_off = P_IDN * 4;
667            push(dd, "experts", 10.0 * ntok * a.d_stride);
668        }
669        {
670            GlueArgs a{N, (uint32_t)ntok, N, TOPK};
671            mtl::Dispatch d;
672            d.p = pcomb;
673            d.args = {mtl::Arg::B(ye), mtl::Arg::B(plan), mtl::Arg::B(ysh), mtl::Arg::B(sg), mtl::Arg::B(bo), mtl::Arg::V(a)};
674            d.grid[0] = (ntok * N + 255) / 256;
675            d.tg[0] = 256;
676            if (hcf && hcf_only != "gemv") {
677                // the combine applies bo to R and the last threadgroup forms xn for the next read
678                d.p = Pn(lib, "moe_combine_hcf", "moe_combine_hcf", {});
679                d.args = {mtl::Arg::B(ye), mtl::Arg::B(plan), mtl::Arg::B(ysh), mtl::Arg::B(sg), mtl::Arg::B(bo), mtl::Arg::V(a)};
680                for (auto& g : hcf_args(l == 47 ? std::string("output_hc") : "blk." + std::to_string(l + 1) + ".hc_attn")) d.args.push_back(g);
681                push(d, "shared", 0);
682                hcf_pend = !hcf_keep;
683            }
684            else if (combf && (hc_mode == "3" || hc_mode == "q8_3")) comb_pending = true;   // folded into the next gr_norm
685            else if (!(fold_comb && hc_mode != "3")) push(d, "shared", 0);   // else folded into the next HC read
686        }
687    }
688    // ---- the final mixer and the head
689    gr_read("output_hc", true, XA, true);
690    gemv2(T("output.weight"), XA, lm, 248320, "lm head");
691    {
692        ArgArgs a{248320, 120};
693        mtl::Dispatch d1, d2;
694        d1.p = pam1;
695        d1.args = {mtl::Arg::B(lm), mtl::Arg::B(apv), mtl::Arg::B(api), mtl::Arg::V(a)};
696        d1.grid[0] = 120;
697        d1.grid[1] = ntok;
698        d1.tg[0] = 256;
699        push(d1, "lm head", 0);
700        d2.p = pam2;
701        d2.args = {mtl::Arg::B(apv), mtl::Arg::B(api), mtl::Arg::B(tokout), mtl::Arg::V(a)};
702        d2.grid[0] = ntok;
703        d2.tg[0] = 256;
704        push(d2, "lm head", 0);
705    }
706    // the producers' plane stride must be MAXT rows: gr_up's and swiglu's args carry n_tok for the stride, so the
707    // gr_up launches above use a.n_tok = ntok - patch them to MAXT (the kernels loop over GR_NTOK tokens anyway)
708    for (auto& d : ds)
709        if (d.p == pup || d.p == pupq || d.p == pnorm || d.p == pdown || d.p == pdownq) {
710            GrArgs a;
711            std::memcpy(&a, d.args.back().bytes.data(), sizeof a);
712            if (d.p == pup || d.p == pupq) a.n_tok = MAXT;
713            std::memcpy(d.args.back().bytes.data(), &a, sizeof a);
714        }
715
716    double total_bytes = 0;
717    for (auto& kv : bytes_by) total_bytes += kv.second;
718    std::printf("%zu dispatches; weight + state bytes %.1f MB\n", ds.size(), total_bytes / 1e6);
719    auto run = [&] { return graph ? cx.run_graph(ds) : cx.run(ds); };
720    run();
721    const double tw = mtl::now_s();
722    while (mtl::now_s() - tw < 1.0) run();
723    std::vector<double> t;
724    for (int i = 0; i < reps; ++i) t.push_back(run());
725    std::printf("HC read: %s\n", hc_mode == "3" ? "BF16, 3 dispatches" : hc_mode == "2" ? "BF16, 2 dispatches" : hc_mode == "q8_3" ? "Q8_0, 3 dispatches" : "Q8_0, 2 dispatches");
726    std::printf("encoding: %s\n", graph ? "concurrent encoder, barriers at dependencies" : "serial encoder");
727    const double m = median(t);
728    std::printf("decode step (%d token(s)): GPU %.3f ms  (min %.3f, max %.3f)  -> %.1f GB/s effective; %.1f tok/s if "
729                "every token were a window of %d\n", ntok, m * 1e3, *std::min_element(t.begin(), t.end()) * 1e3,
730                *std::max_element(t.begin(), t.end()) * 1e3, total_bytes / m / 1e9, ntok / m, ntok);
731    for (auto& kv : bytes_by) std::printf("  %-10s %8.1f MB\n", kv.first.c_str(), kv.second / 1e6);
732    return 0;
733}