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
37.4 KiB596 linesraw
1// metal/src/engine/prompt_chain.inc (included by window.cpp) - the prompt through mac-kern's prompt kernels
2// (metal/tests/prompt_chain.cpp's chain, 6f6c555b), into the decode window's own state: chunks of C rows, every
3// dense matrix dequantized to fp16 and multiplied on the matrix units, the routed experts as grouped GEMMs, the GDN
4// state by the parallel prompt scan, QSA K/V and indexer keys into the window's caches.  Added for the engine:
5// the PLE block after layer 0 (GEMMs + msl/ple.metal), every row's final residual (the drafter's prompt rows), the
6// window's history parity, RoPE table and pending fold.  No head: the last prompt token runs as a decode window.
7//
8// The 8-row-window prompt path stays as the fallback: STRATA_METAL_PROMPT=window, and prompts shorter than
9// STRATA_METAL_PROMPT_MIN rows (default 32).  STRATA_METAL_PROMPT_CHUNK = C (default 2048).  The kernel variants
10// follow prompt_chain's defaults: matrix-unit register operands where the GPU has the M5's right-input layout
11// (COOP_K4, function constant 7), else the older expert and attention kernels (the M4).
12
13namespace {
14constexpr int PC_QB = G_BUD, PC_QCHUNKS = G_QCHUNKS, PC_TM = 16;
15struct PcDqArgs { uint32_t n_in, n_out, row_bytes, perm; };
16struct PcGemmArgs { int M, N, K, pad; };
17struct PcEpiArgs { uint32_t n_tok, n_embd, hc, hc_lr; };
18struct PcGdnPArgs { uint32_t n_tok, h_k, h_v, channels; float eps; uint32_t f32; };
19struct PcMmPlanArgs { uint32_t n_ent, topk, n_expert, tm, n_blocks; };
20struct PcMmArgs { uint64_t gate_off, up_off, down_off, gu_stride, d_stride; uint32_t gu_row, d_row, n_embd, n_ff; };
21int pc_unit_of(int t) {
22    return t == ref::Q2_0 || t == ref::IQ3_S || t == ref::BF16 || t == ref::F32 || t == 18 || t == 16 || t == 17 || t == 22 ? 16 : 32;
23}
24}  // namespace
25
26bool Window::coop_k4() {
27    if (const char* e = std::getenv("COOP_K4")) return std::atoi(e) != 0;
28    const int lib = cx_->compile({"mm_bench.metal"}, "#define NO_GGML_COMMON 1\n");
29    mtl::Pipeline p = cx_->pipeline(lib, "coop_layout_16_64_32");
30    mtl::Buffer out = cx_->alloc(4 * 3 * 32 * 128 * 4);
31    mtl::Dispatch d;
32    d.p = &p;
33    d.args = {mtl::Arg::B(out)};
34    d.tg[0] = 32;
35    cx_->run({d});
36    const int* o = out.as<int>();
37    bool k4 = true;
38    for (int l = 0; l < 32 && k4; ++l) {
39        const int* q = o + l * 128 * 4;
40        const int cap = q[2];
41        for (int i = 0; i + 3 < cap && k4; i += 4)
42            for (int j = 1; j < 4; ++j)
43                if (q[(i + j) * 4] != q[i * 4] + j || q[(i + j) * 4 + 1] != q[i * 4 + 1]) { k4 = false; break; }
44    }
45    cx_->free(out);
46    return k4;
47}
48
49bool Window::pc_setup(int C) {
50    PromptBufs& b = pb_;
51    if (b.C >= C) return true;
52    const double t0 = now_ms();
53    if (b.C == 0) {
54        using namespace strata_metal;
55        auto cc = [&](const MslLib& L) { return cx_->compile(L.files, L.prelude); };
56        b.lib = cc(lib_prompt(kq_down_prelude(f_)));
57        b.lgdn = cc(lib_prompt_gdn());
58        b.lqsa = cc(lib_prompt_qsa());
59        b.k4 = coop_k4();
60    }
61    b = PromptBufs{b.lib, b.lgdn, b.lqsa, b.k4};   // (re)allocated below for the larger chunk
62    b.v3e = b.k4 && T("blk.0.ffn_gate_exps.weight").type < 144;   // the trellis experts have the v2 kernels only
63    b.C = C;
64    const size_t MT = (size_t) C;
65    const int MB = (int) max_cells_ / 4 + 2;
66    // the expert GEMM tiles (prompt_chain's defaults): v3 gate/up 16,32,32,4 and down 16,64,32,2 with the M5 layout, else v2.
67    // STRATA_PROMPT_GU / STRATA_PROMPT_DN = TM,TN,TK,SG override them (test tooling; TM = the plan's tile height, the same for both)
68    b.gu3[0] = 16; b.gu3[1] = 32; b.gu3[2] = 32; b.gu3[3] = 4;
69    b.dn3[0] = 16; b.dn3[1] = 64; b.dn3[2] = 32; b.dn3[3] = 2;
70    if (const char* e = std::getenv("STRATA_PROMPT_GU")) std::sscanf(e, "%d,%d,%d,%d", &b.gu3[0], &b.gu3[1], &b.gu3[2], &b.gu3[3]);
71    if (const char* e = std::getenv("STRATA_PROMPT_DN")) std::sscanf(e, "%d,%d,%d,%d", &b.dn3[0], &b.dn3[1], &b.dn3[2], &b.dn3[3]);
72    if (!b.v3e) { b.gu3[0] = b.dn3[0] = PC_TM; }
73    b.tm = b.gu3[0];
74    if (b.v3e) {   // STRATA_PROMPT_V6=MS (default 4, 0 = off): ragged tiles, groups of MS (2..4) 16-row subtiles of one expert share the weight decode
75        // the ragged-tile kernels exist for these expert types only (every layer's must be one of them)
76        auto gu_ok = [](int t) { return t == ref::Q4_K || t == ref::Q5_K || t == ref::Q6_K || t == ref::Q8_0 || t == ref::IQ3_XXS ||
77                                        t == ref::IQ2_S || t == ref::IQ4_XS || t == ref::IQ3_S || t == ref::IQ2_XS || t == ref::IQ2_XXS; };
78        auto dn_ok = [](int t) { return t == ref::Q5_1 || t == ref::Q8_0 || t == ref::Q5_0 || t == ref::IQ4_NL || t == ref::Q2_0 ||
79                                        t == ref::Q4_K || t == ref::Q5_K || t == ref::Q6_K || t == ref::Q3_K || t == ref::IQ4_XS || t == ref::IQ3_S; };   // (the last six: Q4-KQ, UD downs at widths divisible by 256)
80        bool types_ok = true;
81        for (int l = 0; l < G_NL && types_ok; ++l) {
82            const std::string bl = "blk." + std::to_string(l) + ".";
83            types_ok = gu_ok(T(bl + "ffn_gate_exps.weight").type) && gu_ok(T(bl + "ffn_up_exps.weight").type) && dn_ok(T(bl + "ffn_down_exps.weight").type);
84        }
85        const char* e6 = std::getenv("STRATA_PROMPT_V6");
86        const int ms = types_ok ? (e6 ? std::atoi(e6) : 4) : 0;   // on by default (STRATA_PROMPT_V6=0 off, 2..4 = the group size)
87        if (ms >= 2) {
88            b.v6 = true; b.ms = std::min(ms, 4); b.tm = 16; b.gu3[0] = b.dn3[0] = 16;
89            if (!std::getenv("STRATA_PROMPT_GU")) { b.gu3[1] = 16; b.gu3[2] = 32; b.gu3[3] = 4; }   // measured (moe_mm_parity, T 2048): the accumulators of MS subtiles x gate/up need the narrow tile
90            if (!std::getenv("STRATA_PROMPT_DN")) { b.dn3[1] = 32; b.dn3[2] = 32; b.dn3[3] = 4; }
91        }
92    }
93    if (b.dn3[0] != b.tm) { std::fprintf(stderr, "strata metal: STRATA_PROMPT_GU/DN tile heights differ: using %d for both\n", b.tm); b.dn3[0] = b.tm; }
94    b.maxrows = (int) MT * TOPK + nexp_ * b.tm;
95    const int nblk_max = ((int) MT * TOPK + 1023) / 1024;
96    auto F32 = [&](size_t n) { return cx_->alloc(4 * n); };
97    auto F16 = [&](size_t n) { return cx_->alloc(2 * n); };
98    b.R = F32(MT * HC * N); if (mtp_ovl_ && mtp_on_) b.R2 = F32(MT * HC * N); b.bo = F32(MT * N); b.inj[0] = F32(MT * HC); b.inj[1] = F32(MT * HC); b.xn = F32(MT * HC * N);
99    b.xnh = F16(MT * HC * N); b.V = F32(MT * (LR + HC)); b.loh = F16(MT * LR); b.mixed = F32(MT * N); b.mixh = F16(MT * N);
100    b.fused = gdn_fused_inputs(cx_->device_name());
101    if (b.fused) {   // the four GDN input projections as one GEMM: [qkv | z | alpha | beta] rows of 16480 floats
102        b.yf = F32(MT * G_GDNF);
103        b.qkv = F32(1); b.z = F32(1); b.al = F32(1); b.be = F32(1);
104    } else {
105        b.qkv = F32(MT * G_CONV); b.z = F32(MT * G_ZV); b.al = F32(MT * G_HV); b.be = F32(MT * G_HV);
106    }
107    b.yg = F32(MT * G_ZV);
108    b.ygh = F16(MT * G_ZV); b.gqn = F32(MT * G_HK * G_SS); b.gkn = F32(MT * G_HK * G_SS); b.gvc = F32(MT * G_ZV);
109    b.ggb = F32(MT * G_HV * 2); b.gkq = F32(MT * G_HK); b.go = F32(MT * G_ZV);
110    b.qfull = F32(MT * G_QFULL); b.kcur = F32(MT * G_KV); b.vcur = F32(MT * G_KV); b.iqr = F32(MT * G_IQR); b.ikr = F32(MT * G_ID);
111    b.qcur = F32(MT * G_QOUT); b.qcurh = F16(MT * G_QOUT); b.qidx = F32(MT * G_IH * G_ID); b.scores = F32(MT * MB);
112    b.qids = cx_->alloc(4 * MT * PC_QB); b.part = F32(MT * PC_QCHUNKS * G_QH * (G_QD + 2)); b.XQ = F32(4 * MT * G_QOUT + MT * G_QOUT / 16);
113    b.xqh = F16(MT * G_QOUT);
114    b.logits = F32(MT * nexp_); b.ids = cx_->alloc(4 * MT * TOPK); b.wts = F32(MT * TOPK);
115    b.bcnt = cx_->alloc(4 * (size_t) nblk_max * nexp_); b.boff = cx_->alloc(4 * (size_t) nblk_max * nexp_);
116    b.eoff = cx_->alloc(4 * nexp_); b.tiles = cx_->alloc(8 * (size_t) (b.maxrows / b.tm + 1)); b.meta = cx_->alloc(64);
117    b.stok = cx_->alloc(4 * (size_t) b.maxrows); b.sw = F32(b.maxrows); b.pos = cx_->alloc(4 * MT * TOPK);
118    b.XS = F16((size_t) b.maxrows * N); b.HS = F16((size_t) b.maxrows * NFF); b.YE = F32((size_t) b.maxrows * N);
119    b.yr = F32(MT * N); b.gsh = F32(MT * NFF); b.ush = F32(MT * NFF); b.hh = F16(MT * NFF); b.ys = F32(MT * N); b.sgv = F32(MT);
120    b.WD = F16((size_t) (LR + HC) * HC * N); b.WU = F16((size_t) HC * N * LR);
121    if (b.fused) {
122        b.Wcat = F16((size_t) G_GDNF * N);
123        b.Wqkv = F16(1); b.Wz = F16(1); b.Wal = F16(1); b.Wbe = F16(1);
124    } else {
125        b.Wqkv = F16((size_t) G_CONV * N); b.Wz = F16((size_t) G_ZV * N); b.Wal = F16((size_t) G_HV * N); b.Wbe = F16((size_t) G_HV * N);
126    }
127    b.Wout = F16((size_t) N * G_QOUT);
128    b.Wq = F16((size_t) G_QFULL * N); b.Wk = F16((size_t) G_KV * N); b.Wv = F16((size_t) G_KV * N); b.Wiq = F16((size_t) G_IQR * N);
129    b.Wik = F16((size_t) G_ID * N); b.Wr = F16((size_t) nexp_ * N); b.Wsg = F16((size_t) N); b.Wshg = F16((size_t) NFF * N);
130    b.Wshu = F16((size_t) NFF * N); b.Wshd = F16((size_t) N * NFF);
131    // the PLE block's rows and projections
132    b.pemb = F32(MT * N); b.pembh = F16(MT * N); b.pkey = F32(MT * G_HCD); b.pval = F32(MT * N); b.keyn = F32(MT * G_HCD);
133    b.qn = F32(MT * G_HCD); b.gated = F32(MT * G_HCD); b.normW = F32(MT * G_HCD);
134    if (had_on_) b.mixr = F32(MT * N);
135    b.Wpk = F16((size_t) G_HCD * N); b.Wpv = F16((size_t) N * N);
136    b.meta.as<uint32_t>()[2] = b.v3e ? NFF / (b.gu3[1] * b.gu3[3]) : NFF / 64;
137    b.meta.as<uint32_t>()[5] = b.v3e ? N / (b.dn3[1] * b.dn3[3]) : N / 64;
138    std::fprintf(stderr, "strata metal: prompt kernels (mac-kern's prompt chain) for chunks of %d rows, %s, ready in %.0f ms\n",
139                 C, b.k4 ? "matrix-unit register operands (COOP_K4)" : "the older expert / attention kernels (no M5 layout)",
140                 now_ms() - t0);
141    return true;
142}
143
144// STRATA_PROMPT_KPROF: the per-dispatch GPU times of one chunk (see pc_chunk).  The table (all profiled chunks summed) is
145// rewritten after every chunk to the file named by the variable's value (stderr if it is not a path): the engine may leave
146// without running atexit handlers.
147void Window::pc_kprof(const std::vector<mtl::Dispatch>& ds, int nT, int64_t pos0) {
148    static std::map<std::string, std::pair<double, int>> acc;
149    double sum = 0;
150    for (const auto& d : ds) {
151        std::string k = d.p->name;
152        if (k.rfind("gemm_f16", 0) == 0 || k.rfind("gemm_hc_up", 0) == 0) {
153            for (const auto& a : d.args)
154                if (a.bytes.size() == sizeof(PcGemmArgs)) {
155                    PcGemmArgs g;
156                    std::memcpy(&g, a.bytes.data(), sizeof g);
157                    k += " M" + std::to_string(g.M) + " N" + std::to_string(g.N) + " K" + std::to_string(g.K);
158                    break;
159                }
160        } else if (k.rfind("dq_f16", 0) == 0) {
161            for (const auto& a : d.args)
162                if (a.bytes.size() == sizeof(PcDqArgs)) {
163                    PcDqArgs g;
164                    std::memcpy(&g, a.bytes.data(), sizeof g);
165                    k += " in" + std::to_string(g.n_in) + " out" + std::to_string(g.n_out);
166                    break;
167                }
168        }
169        const double s = cx_->run({d}, 1, false, false);
170        sum += s;
171        auto& e = acc[k];
172        e.first += s;
173        e.second += 1;
174    }
175    const double g0 = now_ms();
176    const double gg = cx_->run(ds);
177    const char* path = std::getenv("STRATA_PROMPT_KPROF");
178    FILE* f = path != nullptr && path[0] == '/' ? std::fopen(path, "w") : stderr;
179    if (f == nullptr) f = stderr;
180    double tot = 0;
181    std::vector<std::pair<double, std::string>> v;
182    for (auto& [k, x] : acc) { tot += x.first; v.emplace_back(x.first, k); }
183    std::sort(v.begin(), v.end(), [](auto& a, auto& b) { return a.first > b.first; });
184    std::fprintf(f, "KPROF-TABLE total %.1f ms over all profiled chunks\n", tot * 1e3);
185    for (auto& [t, k] : v) std::fprintf(f, "KPROF %9.2f ms %5.1f%% n=%-5d %s\n", t * 1e3, 100 * t / tot, acc[k].second, k.c_str());
186    std::fprintf(f, "KPROF chunk pos %lld rows %d: %zu dispatches, sum of single-dispatch GPU times %.1f ms; the same chunk as one command buffer %.1f ms (GPU %.1f)\n",
187                 (long long) pos0, nT, ds.size(), sum * 1e3, now_ms() - g0, gg * 1e3);
188    if (f != stderr) std::fclose(f);
189}
190
191// The host rows of a chunk: the token embedding rows (dequantized from the model file; rows of an image are the caller's) and the
192// PLE table rows of its tokens.  Pure CPU work on the model file: it can run beside the GPU's previous chunk.
193bool Window::pc_host_rows(const int64_t* tokens, int nT, int64_t pos0, const int32_t prev_in[2], PcHost& out) {
194    const double t0 = now_ms();
195    out.nT = nT;
196    out.pos0 = pos0;
197    out.ok = true;
198    const gguf::Tensor& te = T("token_embd.weight");
199    const size_t rb = ref::row_bytes(te.type, N);
200    out.emb.resize((size_t) nT * N);
201    for (int t = 0; t < nT; ++t)
202        if (img_row(pos0 + t) == nullptr)
203            ref::dequant(te.type, (const uint8_t*) W_.ptr + te.offset + (size_t) tokens[t] * rb, out.emb.data() + (size_t) t * N, N);
204    out.ms_emb = now_ms() - t0;
205    if (ple_on_) {
206        strata::core::SessionState& ss = *ss_;
207        std::vector<uint32_t> rows((size_t) nT * strata::kernels::PLE_N_HEADS);
208        int32_t prev[2] = {prev_in[0], prev_in[1]};
209        for (int t = 0; t < nT; ++t) {
210            const int32_t tk = (int32_t) tokens[t];
211            strata::kernels::ngram_rows(&tk, prev, 1, ss.ple.consts, rows.data() + (size_t) t * strata::kernels::PLE_N_HEADS);
212            prev[0] = prev[1];
213            prev[1] = tk;
214        }
215        out.ple.resize((size_t) nT * N);
216        if (!ss.ple.table->gather_batch(rows.data(), (size_t) nT, out.ple.data(), out.err)) out.ok = false;
217    }
218    out.ms = now_ms() - t0;
219    return out.ok;
220}
221
222// one chunk of nT rows at cells pos0.. (the window state is exactly at pos0 before, at pos0 + nT after).  next_tokens: the
223// following chunk of the same prompt, whose host rows are computed on a thread while this chunk runs on the GPU.
224bool Window::pc_chunk(const int64_t* tokens, int nT, int64_t pos0, std::string& err, const int64_t* next_tokens, int next_nT) {
225    PromptBufs& b = pb_;
226    strata::core::SessionState& ss = *ss_;
227    const double th0 = now_ms();
228    // ---- the rows: the embedding into every stream; the PLE table rows
229    PcHost cur;
230    bool have = false;
231    if (pc_next_.valid()) {
232        cur = pc_next_.get();
233        have = cur.ok && cur.pos0 == pos0 && cur.nT == nT;
234        if (have) b.hidden_ms += cur.ms;
235    }
236    if (have) { b.emb_ms += cur.ms_emb; b.ple_ms += cur.ms - cur.ms_emb; }
237    if (!have) {
238        const int32_t prev0[2] = {ss.ple_prev[0], ss.ple_prev[1]};
239        if (!pc_host_rows(tokens, nT, pos0, prev0, cur)) { err = cur.err; return false; }
240        b.emb_ms += cur.ms_emb; b.ple_ms += cur.ms - cur.ms_emb;
241    }
242    mrope_sync(pos0, nT);
243    for (int t = 0; t < nT; ++t) {
244        float* r = b.R.as<float>() + (size_t) t * HC * N;
245        if (const float* img = img_row(pos0 + t)) std::memcpy(r, img, (size_t) N * 4);
246        else std::memcpy(r, cur.emb.data() + (size_t) t * N, (size_t) N * 4);
247        for (int c = 1; c < HC; ++c) std::memcpy(r + (size_t) c * N, r, (size_t) N * 4);
248    }
249    if (ple_on_) std::memcpy(b.pemb.as<float>(), cur.ple.data(), (size_t) nT * N * 4);
250    b.host_ms += now_ms() - th0;
251    std::vector<mtl::Dispatch> ds;
252    ds.reserve(2400);
253    nb_ = false;
254    if (pend_fold_ > 0) {   // the last window's commit, first
255        fold(ds, pend_fold_, 1 - hp_);
256        pend_fold_ = 0;
257    }
258    auto P_ = [&](int l, const std::string& fn, const mtl::Constants& c = {}, const std::string& key = "") {
259        return P(l, fn, c, "pc:" + (key.empty() ? fn : key));
260    };
261    auto D = [&](const mtl::Pipeline* p, std::vector<mtl::Arg> a, uint32_t gx, uint32_t gy, uint32_t tg, uint32_t gz = 1) {
262        mtl::Dispatch d;
263        d.p = p;
264        d.args = std::move(a);
265        d.grid[0] = gx; d.grid[1] = gy; d.grid[2] = gz;
266        d.tg[0] = tg;
267        mtl::require_fit(d, "prompt-chain dispatch");
268        ds.push_back(std::move(d));
269    };
270    auto gemm = [&](const mtl::Buffer& A, const mtl::Buffer& B, const mtl::Buffer& Y, int M, int Nn, int K) {
271        int tm = 64, tn = Nn <= 64 ? 32 : 64;
272        gemm_tile(cx_->device_name(), Nn, K, tm, tn);
273        const std::string fn = "gemm_f16_" + std::to_string(tm) + "_" + std::to_string(tn) + "_4";
274        PcGemmArgs g{M, Nn, K, 0};
275        D(P_(b.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, 128);
276    };
277    auto dq = [&](const gguf::Tensor& t, const mtl::Buffer& out, size_t out_off = 0, uint32_t perm = 0) {
278        const int n_in = (int) t.shape[0], n_out = t.shape.size() > 1 ? (int) t.shape[1] : 1;
279        PcDqArgs a{(uint32_t) n_in, (uint32_t) n_out, (uint32_t) ref::row_bytes(t.type, n_in), perm};
280        D(P_(b.lib, "dq_f16_" + std::to_string(t.type)), {mtl::Arg::B(W_, t.offset), mtl::Arg::B(out, out_off), mtl::Arg::V(a)},
281          (n_in / pc_unit_of(t.type) + 63) / 64, n_out, 64);
282    };
283    auto act16 = [&](const mtl::Buffer& x, const mtl::Buffer& xh, size_t n) {
284        const uint32_t nn = (uint32_t) n;
285        D(P_(b.lib, "act_f16"), {mtl::Arg::B(x), mtl::Arg::B(xh), mtl::Arg::V(nn)}, (nn + 255) / 256, 1, 256);
286    };
287    int cur_inj = 0;
288    auto hc_read = [&](const std::string& pre, bool apply) {
289        const gguf::Tensor &tn = T(pre + "_norm.weight"), &tdn = T(pre + "_down.weight"), &tin = T(pre + "_inject.weight"),
290                           &tup = T(pre + "_up.weight");
291        dq(tdn, b.WD);
292        dq(tin, b.WD, (size_t) 2 * LR * HC * N);
293        GrArgs a{N, HC, LR, (uint32_t) nT, apply ? 1u : 0u, eps_};
294        PcEpiArgs ea{(uint32_t) nT, N, HC, LR};
295        dq(tup, b.WU, 0, HC);
296        D(P_(b.lib, "gr_norm_h"), {mtl::Arg::B(b.R), mtl::Arg::B(b.bo), mtl::Arg::B(b.inj[cur_inj]), mtl::Arg::B(W_, tn.offset),
297                                  mtl::Arg::B(b.xnh), mtl::Arg::V(a)}, HC, nT, 256);
298        gemm(b.xnh, b.WD, b.V, nT, LR + HC, HC * N);
299        D(P_(b.lib, "gr_epi_down"), {mtl::Arg::B(b.V), mtl::Arg::B(b.loh), mtl::Arg::B(b.inj[1 - cur_inj]), mtl::Arg::V(ea)},
300          (nT * (LR + HC) + 255) / 256, 1, 256);
301        PcGemmArgs g{nT, HC * N, LR, 0};
302        D(P_(b.lib, "gemm_hc_up_64_64_4"), {mtl::Arg::B(b.loh), mtl::Arg::B(b.WU), mtl::Arg::B(b.xnh), mtl::Arg::B(b.mixed),
303                                           mtl::Arg::B(b.mixh), mtl::Arg::V(g), mtl::Arg::V(ea)},
304          HC * N / 64, (nT + 63) / 64, 128);
305        cur_inj = 1 - cur_inj;
306    };
307    const int hp = hp_;
308    int gi = 0, qi = 0;
309    for (int l = 0; l < G_NL; ++l) {
310        const std::string bl = "blk." + std::to_string(l) + ".";
311        hc_read(bl + "hc_attn", l > 0 && !(l == 1 && ple_on_));
312        if (l % G_QI != G_QI - 1) {
313            dq(T(bl + "ssm_out.weight"), b.Wout);
314            PcGdnPArgs ga{(uint32_t) nT, G_HK, G_HV, G_CONV, eps_, 0};
315            if (b.fused) {
316                dq(T(bl + "attn_qkv.weight"), b.Wcat, 0);
317                dq(T(bl + "attn_gate.weight"), b.Wcat, (size_t) 2 * G_CONV * N);
318                dq(T(bl + "ssm_alpha.weight"), b.Wcat, (size_t) 2 * (G_CONV + G_ZV) * N);
319                dq(T(bl + "ssm_beta.weight"), b.Wcat, (size_t) 2 * (G_CONV + G_ZV + G_HV) * N);
320                gemm(b.mixh, b.Wcat, b.yf, nT, G_GDNF, N);
321                D(P_(b.lgdn, "gdn_pre", mtl::Constants().i(7, G_GDNF), "gdn_pre_f"),
322                  {mtl::Arg::B(b.yf), mtl::Arg::B(ghist_[hp][(size_t) gi]), mtl::Arg::B(W_, T(bl + "ssm_conv1d.weight").offset),
323                   mtl::Arg::B(b.yf, (size_t) 4 * (G_CONV + G_ZV)), mtl::Arg::B(b.yf, (size_t) 4 * (G_CONV + G_ZV + G_HV)),
324                   mtl::Arg::B(W_, T(bl + "ssm_dt.bias").offset), mtl::Arg::B(W_, T(bl + "ssm_a").offset), mtl::Arg::B(b.gqn),
325                   mtl::Arg::B(b.gkn), mtl::Arg::B(b.gvc), mtl::Arg::B(b.ggb), mtl::Arg::B(b.gkq),
326                   mtl::Arg::B(ghist_[1 - hp][(size_t) gi]), mtl::Arg::V(ga)},
327                  G_HK + G_HV / 2, nT, 256);
328            } else {
329                dq(T(bl + "attn_qkv.weight"), b.Wqkv);
330                dq(T(bl + "attn_gate.weight"), b.Wz);
331                dq(T(bl + "ssm_alpha.weight"), b.Wal);
332                dq(T(bl + "ssm_beta.weight"), b.Wbe);
333                gemm(b.mixh, b.Wqkv, b.qkv, nT, G_CONV, N);
334                gemm(b.mixh, b.Wz, b.z, nT, G_ZV, N);
335                gemm(b.mixh, b.Wal, b.al, nT, G_HV, N);
336                gemm(b.mixh, b.Wbe, b.be, nT, G_HV, N);
337                D(P_(b.lgdn, "gdn_pre"),
338                  {mtl::Arg::B(b.qkv), mtl::Arg::B(ghist_[hp][(size_t) gi]), mtl::Arg::B(W_, T(bl + "ssm_conv1d.weight").offset),
339                   mtl::Arg::B(b.al), mtl::Arg::B(b.be), mtl::Arg::B(W_, T(bl + "ssm_dt.bias").offset),
340                   mtl::Arg::B(W_, T(bl + "ssm_a").offset), mtl::Arg::B(b.gqn), mtl::Arg::B(b.gkn), mtl::Arg::B(b.gvc),
341                   mtl::Arg::B(b.ggb), mtl::Arg::B(b.gkq), mtl::Arg::B(ghist_[1 - hp][(size_t) gi]), mtl::Arg::V(ga)},
342                  G_HK + G_HV / 2, nT, 256);
343            }
344            D(P_(b.lgdn, gdn_scan_name(cx_->device_name(), nT), mtl::Constants().i(6, 0)),
345              {mtl::Arg::B(gst_[(size_t) gi]), mtl::Arg::B(b.gqn), mtl::Arg::B(b.gkn), mtl::Arg::B(b.gvc), mtl::Arg::B(b.ggb),
346               mtl::Arg::B(b.gkq), mtl::Arg::B(b.go), mtl::Arg::V(ga)},
347              G_HV * 4, 1, 32 * 4);
348            if (b.fused)
349                D(P_(b.lgdn, "gdn_post", mtl::Constants().i(7, G_GDNF), "gdn_post_f"),
350                  {mtl::Arg::B(b.go), mtl::Arg::B(b.yf, (size_t) 4 * G_CONV), mtl::Arg::B(W_, T(bl + "ssm_norm.weight").offset),
351                   mtl::Arg::B(b.ygh), mtl::Arg::B(b.yg), mtl::Arg::V(ga)},
352                  G_HV, nT, 128);
353            else
354                D(P_(b.lgdn, "gdn_post"), {mtl::Arg::B(b.go), mtl::Arg::B(b.z), mtl::Arg::B(W_, T(bl + "ssm_norm.weight").offset),
355                                          mtl::Arg::B(b.ygh), mtl::Arg::B(b.yg), mtl::Arg::V(ga)},
356                  G_HV, nT, 128);
357            gemm(b.ygh, b.Wout, b.bo, nT, N, G_ZV);
358            ++gi;
359        } else {
360            dq(T(bl + "attn_q.weight"), b.Wq);
361            dq(T(bl + "attn_k.weight"), b.Wk);
362            dq(T(bl + "attn_v.weight"), b.Wv);
363            dq(T(bl + "indexer.q_proj.weight"), b.Wiq);
364            dq(T(bl + "indexer.k_proj.weight"), b.Wik);
365            dq(T(bl + "attn_output.weight"), b.Wout);
366            gemm(b.mixh, b.Wq, b.qfull, nT, G_QFULL, N);
367            gemm(b.mixh, b.Wk, b.kcur, nT, G_KV, N);
368            gemm(b.mixh, b.Wv, b.vcur, nT, G_KV, N);
369            gemm(b.mixh, b.Wiq, b.iqr, nT, G_IQR, N);
370            gemm(b.mixh, b.Wik, b.ikr, nT, G_ID, N);
371            QsaArgs a{(uint32_t) pos0, 0, (uint32_t) max_cells_, (uint32_t) nT, eps_};
372            D(P_(b.lqsa, "qsa_prep", qsa_c(), qsa_k()),
373              {mtl::Arg::B(b.qfull), mtl::Arg::B(b.kcur), mtl::Arg::B(b.vcur), mtl::Arg::B(b.iqr), mtl::Arg::B(b.ikr),
374               mtl::Arg::B(W_, T(bl + "attn_q_norm.weight").offset), mtl::Arg::B(W_, T(bl + "attn_k_norm.weight").offset),
375               mtl::Arg::B(W_, T(bl + "indexer.q_norm.weight").offset), mtl::Arg::B(W_, T(bl + "indexer.k_norm.weight").offset),
376               mtl::Arg::B(cs_), mtl::Arg::B(b.qcur), mtl::Arg::B(b.qidx), mtl::Arg::B(kq_[(size_t) qi]), mtl::Arg::B(vq_[(size_t) qi]),
377               mtl::Arg::B(ksc_[(size_t) qi]), mtl::Arg::B(vsc_[(size_t) qi]), mtl::Arg::B(tail_[(size_t) qi]),
378               mtl::Arg::B(dead_[(size_t) qi]), mtl::Arg::B(pooled_[(size_t) qi]), mtl::Arg::V(a), mtl::Arg::B(mrope_)},
379              G_QPREP, nT, 256);
380            if (pos0 + nT > PC_QB) {   // some row's context is past the budget: the indexer selects
381                if (b.k4)
382                    D(P_(b.lqsa, "qsa_score_mm"), {mtl::Arg::B(b.qidx), mtl::Arg::B(pooled_[(size_t) qi]), mtl::Arg::B(dead_[(size_t) qi]),
383                                                 mtl::Arg::B(b.scores), mtl::Arg::V(a)},
384                      (uint32_t) (((pos0 + nT) / 4 + 1 + 63) / 64), (nT + 15) / 16, 128);
385                else
386                    D(P_(b.lqsa, "qsa_score"), {mtl::Arg::B(b.qidx), mtl::Arg::B(pooled_[(size_t) qi]), mtl::Arg::B(dead_[(size_t) qi]),
387                                              mtl::Arg::B(b.scores), mtl::Arg::V(a)},
388                      (uint32_t) (((pos0 + nT) / 4 + 1 + 7) / 8), nT, 256);
389            }
390            D(P_(b.lqsa, "qsa_topk"), {mtl::Arg::B(b.scores), mtl::Arg::B(b.qids), mtl::Arg::V(a)}, nT, 1, 1024);
391            if (b.k4) {
392                const uint32_t nq = (uint32_t) nT * G_QOUT;
393                D(P_(b.lqsa, "qsa_q_f16"), {mtl::Arg::B(b.qcur), mtl::Arg::B(b.qcurh), mtl::Arg::V(nq)}, (nq + 255) / 256, 1, 256);
394                D(P_(b.lqsa, "qsa_attn_mm", mtl::Constants().b(7, true), "qsa_attn_mm#k4"),
395                  {mtl::Arg::B(b.qcurh), mtl::Arg::B(kq_[(size_t) qi]), mtl::Arg::B(vq_[(size_t) qi]), mtl::Arg::B(ksc_[(size_t) qi]),
396                   mtl::Arg::B(vsc_[(size_t) qi]), mtl::Arg::B(b.qids), mtl::Arg::B(b.part), mtl::Arg::V(a)},
397                  PC_QCHUNKS, G_QKV, 32, nT);
398            } else {
399                D(P_(b.lqsa, "qsa_attn"), {mtl::Arg::B(b.qcur), mtl::Arg::B(kq_[(size_t) qi]), mtl::Arg::B(vq_[(size_t) qi]),
400                                          mtl::Arg::B(ksc_[(size_t) qi]), mtl::Arg::B(vsc_[(size_t) qi]), mtl::Arg::B(b.qids),
401                                          mtl::Arg::B(b.part), mtl::Arg::V(a)},
402                  PC_QCHUNKS, G_QKV, 256, nT);
403            }
404            static const bool mergeh = [] { const char* e = std::getenv("STRATA_PROMPT_MERGEH"); return !(e && std::string(e) == "0"); }();
405            if (mergeh) {   // the merge writes the fp16 operand directly (bitwise the same halves)
406                D(P_(b.lqsa, "qsa_merge_h"), {mtl::Arg::B(b.part), mtl::Arg::B(b.qfull), mtl::Arg::B(b.xqh), mtl::Arg::V(a)}, G_QH, nT, 256);
407            } else {
408                D(P_(b.lqsa, "qsa_merge"), {mtl::Arg::B(b.part), mtl::Arg::B(b.qfull), mtl::Arg::B(b.XQ), mtl::Arg::V(a)}, G_QH, nT, 256);
409                act16(b.XQ, b.xqh, (size_t) nT * G_QOUT);
410            }
411            gemm(b.xqh, b.Wout, b.bo, nT, N, G_QOUT);
412            ++qi;
413        }
414        // ---- MoE
415        hc_read(bl + "hc_ffn", true);
416        const gguf::Tensor &eg = T(bl + "ffn_gate_exps.weight"), &eu = T(bl + "ffn_up_exps.weight"), &ed = T(bl + "ffn_down_exps.weight");
417        dq(T(bl + "ffn_gate_inp.weight"), b.Wr);
418        dq(T(bl + "ffn_gate_inp_shexp.weight"), b.Wsg);
419        dq(T(bl + "ffn_gate_shexp.weight"), b.Wshg);
420        dq(T(bl + "ffn_up_shexp.weight"), b.Wshu);
421        dq(T(bl + "ffn_down_shexp.weight"), b.Wshd);
422        gemm(b.mixh, b.Wr, b.logits, nT, nexp_, N);
423        const uint32_t nt = (uint32_t) nT;
424        D(P_(b.lib, "route_topk"), {mtl::Arg::B(b.logits), mtl::Arg::B(b.ids), mtl::Arg::B(b.wts), mtl::Arg::V(nt), mtl::Arg::V((uint32_t) nexp_)}, (nT + 7) / 8, 1, 256);
425        const int nent = nT * TOPK, nblk = (nent + 1023) / 1024;
426        PcMmPlanArgs pa{(uint32_t) nent, TOPK, (uint32_t) nexp_, (uint32_t) (b.v6 ? b.ms : b.tm), (uint32_t) nblk};
427        const uint32_t nclr = (uint32_t) b.maxrows;
428        D(P_(b.lib, "mm_clear"), {mtl::Arg::B(b.stok), mtl::Arg::V(nclr)}, (b.maxrows + 255) / 256, 1, 256);
429        D(P_(b.lib, "mm_hist"), {mtl::Arg::B(b.ids), mtl::Arg::B(b.bcnt), mtl::Arg::V(pa)}, nblk, 1, 1024);
430        D(P_(b.lib, b.v6 ? "mm_scan6" : "mm_scan"), {mtl::Arg::B(b.bcnt), mtl::Arg::B(b.boff), mtl::Arg::B(b.eoff), mtl::Arg::B(b.tiles), mtl::Arg::B(b.meta),
431                                mtl::Arg::V(pa)}, 1, 1, nexp_);
432        D(P_(b.lib, "mm_place"), {mtl::Arg::B(b.ids), mtl::Arg::B(b.wts), mtl::Arg::B(b.boff), mtl::Arg::B(b.eoff), mtl::Arg::B(b.stok),
433                                 mtl::Arg::B(b.sw), mtl::Arg::B(b.pos), mtl::Arg::V(pa)}, nblk, 1, 1024);
434        PcMmArgs ma{eg.offset, eu.offset, ed.offset, 0, 0, (uint32_t) ref::row_bytes(eg.type, N), (uint32_t) ref::row_bytes(ed.type, NFF),
435                    N, NFF};
436        ma.gu_stride = (uint64_t) ma.gu_row * NFF;
437        ma.d_stride = (uint64_t) ma.d_row * N;
438        const size_t ebase = moe_rebase(ma.gate_off, ma.up_off, ma.down_off);
439        const uint32_t ne = N;
440        const bool hg = had_gu(l), hd = had_dn(l);
441        if (hg) had_rows(ds, b.lib, "pc:", b.mixed, 0, b.mixr, 0, nT, N, hsx_.handle ? &hsx_ : nullptr, false);
442        mtl::Dispatch g;
443        g.p = P_(b.lib, "mm_gather");
444        g.args = {mtl::Arg::B(hg ? b.mixr : b.mixed), mtl::Arg::B(b.stok), mtl::Arg::B(b.XS), mtl::Arg::V(ne)};
445        g.tg[0] = 256;
446        g.indirect = &b.meta;
447        g.ind_off = 8 * 4;
448        ds.push_back(g);
449        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]); };
450        mtl::Dispatch gu;
451        if (b.v3e) {
452            const std::string fn = b.v6 ? "mm_gu6_" + std::to_string(eg.type) + "_" + std::to_string(b.ms) + "_" + std::to_string(b.gu3[1]) + "_" +
453                                              std::to_string(b.gu3[2]) + "_" + std::to_string(b.gu3[3])
454                                        : "mm_gu3_" + std::to_string(eg.type) + "_" + tl3(b.gu3);
455            gu.p = P_(b.lib, fn, mtl::Constants().b(7, true), fn + "#k4");
456        } else {
457            const std::string fn = "mm_gu2_" + std::to_string(eg.type) + gu2_tile(eg.type);
458            gu.p = P_(b.lib, fn, mtl::Constants().i(5, 0), fn + "#p0");
459        }
460        gu.args = {mtl::Arg::B(W_, ebase), mtl::Arg::B(b.XS), mtl::Arg::B(b.HS), mtl::Arg::B(b.tiles), mtl::Arg::V(ma)};
461        gu.tg[0] = b.v3e ? 32 * b.gu3[3] : 64;
462        gu.indirect = &b.meta;
463        gu.ind_off = 2 * 4;
464        ds.push_back(gu);
465        if (hd) had_rows_ind(ds, b.lib, "pc:", b.HS, b.meta);
466        mtl::Dispatch dn;
467        if (b.v3e) {
468            const std::string fn = b.v6 ? "mm_down6_" + std::to_string(ed.type) + "_" + std::to_string(b.ms) + "_" + std::to_string(b.dn3[1]) + "_" +
469                                              std::to_string(b.dn3[2]) + "_" + std::to_string(b.dn3[3])
470                                        : "mm_down3_" + std::to_string(ed.type) + "_" + tl3(b.dn3);
471            dn.p = P_(b.lib, fn, mtl::Constants().b(7, true), fn + "#k4");
472        } else {
473            dn.p = P_(b.lib, "mm_down2_" + std::to_string(ed.type) + dn2_tile(ed.type));
474        }
475        dn.args = {mtl::Arg::B(W_, ebase), mtl::Arg::B(b.HS), mtl::Arg::B(b.YE), mtl::Arg::B(b.tiles), mtl::Arg::V(ma)};
476        dn.tg[0] = b.v3e ? 32 * b.dn3[3] : 64;
477        dn.indirect = &b.meta;
478        dn.ind_off = 5 * 4;
479        ds.push_back(dn);
480        const uint32_t ca[4] = {(uint32_t) nT, N, TOPK, 0};
481        D(P_(b.lib, "mm_combine"), {mtl::Arg::B(b.YE), mtl::Arg::B(b.pos), mtl::Arg::B(b.sw), mtl::Arg::B(b.yr), mtl::Arg::V(ca)},
482          (nT * N + 255) / 256, 1, 256);
483        gemm(b.mixh, b.Wshg, b.gsh, nT, NFF, N);
484        gemm(b.mixh, b.Wshu, b.ush, nT, NFF, N);
485        const uint32_t nh = (uint32_t) nT * NFF;
486        D(P_(b.lib, "swiglu_h"), {mtl::Arg::B(b.gsh), mtl::Arg::B(b.ush), mtl::Arg::B(b.hh), mtl::Arg::V(nh)}, (nh + 255) / 256, 1, 256);
487        gemm(b.hh, b.Wshd, b.ys, nT, N, NFF);
488        gemm(b.mixh, b.Wsg, b.sgv, nT, 1, N);
489        const uint32_t oa[2] = {(uint32_t) nT, N};
490        D(P_(b.lib, "moe_out"), {mtl::Arg::B(b.yr), mtl::Arg::B(b.ys), mtl::Arg::B(b.sgv), mtl::Arg::B(b.bo), mtl::Arg::V(oa)},
491          (nT * N + 255) / 256, 1, 256);
492        if (taps_on_ && tap_slot_[l] >= 0) tap_dispatch(ds, l, b.R, b.bo, b.inj[cur_inj], tap_pro_buf(b.C + MAXT), nT);   // DFlash2
493        if (l == 0 && ple_on_) {
494            // layer 0's FFN write applied to R, then the PLE block (as the window: msl/ple.metal over nT rows)
495            GrArgs a{N, HC, LR, (uint32_t) nT, 1u, eps_};
496            D(P_(b.lib, "gr_norm"), {mtl::Arg::B(b.R), mtl::Arg::B(b.bo), mtl::Arg::B(b.inj[cur_inj]),
497                                    mtl::Arg::B(W_, T("blk.1.hc_attn_norm.weight").offset), mtl::Arg::B(b.xn), mtl::Arg::V(a)},
498              HC, nT, 256);
499            act16(b.pemb, b.pembh, (size_t) nT * N);
500            dq(T("blk.1.ple_key.weight"), b.Wpk);
501            dq(T("blk.1.ple_value.weight"), b.Wpv);
502            gemm(b.pembh, b.Wpk, b.pkey, nT, G_HCD, N);
503            gemm(b.pembh, b.Wpv, b.pval, nT, N, N);
504            struct PleArgs { uint32_t n_embd, hc; float eps; } pa2{N, HC, strata::kernels::NG_RMS_EPS};
505            auto off = [&](const char* n) { return T(n).offset; };
506            D(P(lple_, "ple_gnorm", {}, "ple_gnorm"), {mtl::Arg::B(b.pkey), mtl::Arg::B(W_, off("blk.1.ple_norm_key.weight")),
507                                                       mtl::Arg::B(b.keyn), mtl::Arg::V(pa2)}, HC, nT, 256);
508            D(P(lple_, "ple_gnorm", {}, "ple_gnorm"), {mtl::Arg::B(b.R), mtl::Arg::B(W_, off("blk.1.ple_norm_query.weight")),
509                                                       mtl::Arg::B(b.qn), mtl::Arg::V(pa2)}, HC, nT, 256);
510            D(P(lple_, "ple_gate_norm", {}, "ple_gate_norm"),
511              {mtl::Arg::B(b.keyn), mtl::Arg::B(b.qn), mtl::Arg::B(b.pval), mtl::Arg::B(W_, off("blk.1.ple_norm_conv.weight")),
512               mtl::Arg::B(b.gated), mtl::Arg::B(b.normW), mtl::Arg::V(pa2)}, HC, nT, 256);
513            D(P(lple_, "ple_conv_add", {}, "ple_conv_add"),
514              {mtl::Arg::B(pleHist_), mtl::Arg::B(b.normW), kw_arg(), mtl::Arg::B(b.gated),
515               mtl::Arg::B(b.R), mtl::Arg::V(pa2)}, HC * N / 256, nT, 256);
516        }
517    }
518    // every row's final residual (the last write applied): the drafter's prompt rows
519    {
520        GrArgs a{N, HC, LR, (uint32_t) nT, 1u, eps_};
521        D(P_(b.lib, "gr_norm"), {mtl::Arg::B(b.R), mtl::Arg::B(b.bo), mtl::Arg::B(b.inj[cur_inj]),
522                                mtl::Arg::B(W_, T("output_hc_norm.weight").offset), mtl::Arg::B(b.xn), mtl::Arg::V(a)}, HC, nT, 256);
523    }
524    // STRATA_PROMPT_KPROF=1 (test tooling): every dispatch alone in its own command buffer, its GPU time kept per kernel and
525    // shape, a table at exit.  The chunk then runs once more as a whole, so the GDN state is advanced twice: profiling only.
526    static const bool kprof = std::getenv("STRATA_PROMPT_KPROF") != nullptr;
527    if (kprof && nT >= 1024) pc_kprof(ds, nT, pos0);
528    static const bool hostpipe = [] { const char* e = std::getenv("STRATA_METAL_PROMPT_HOSTPIPE"); return !(e && std::string(e) == "0"); }();
529    if (hostpipe && next_tokens != nullptr && next_nT > 0 && g_embd_rows == nullptr) {
530        const int32_t pv[2] = {nT >= 2 ? (int32_t) tokens[nT - 2] : ss.ple_prev[1], (int32_t) tokens[nT - 1]};
531        const int64_t npos = pos0 + nT;
532        pc_next_ = std::async(std::launch::async, [this, next_tokens, next_nT, npos, pv0 = pv[0], pv1 = pv[1]] {
533            PcHost h;
534            const int32_t pp[2] = {pv0, pv1};
535            pc_host_rows(next_tokens, next_nT, npos, pp, h);
536            return h;
537        });
538    }
539    const double g = cx_->run(ds);
540    b.gpu_ms += 1000.0 * g;
541    hp_ = 1 - hp_;
542    // the host side of the commit: the PLE history (the last 9 normalized rows) and the n-gram context
543    if (ple_on_) {
544        using namespace strata::kernels;
545        const float* nw = b.normW.as<float>();
546        float* hist = pleHist_.as<float>();
547        for (int c = 0; c < NG_HC_DIM; ++c) {
548            float* col = hist + (size_t) c * NG_HIST;
549            float tmp[NG_HIST * 2];
550            int k = 0;
551            const int keep_old = std::max(0, NG_HIST - nT);
552            for (int r = NG_HIST - keep_old; r < NG_HIST; ++r) tmp[k++] = col[r];
553            for (int t = std::max(0, nT - NG_HIST); t < nT; ++t) tmp[k++] = nw[(size_t) t * NG_HC_DIM + c];
554            for (int r = 0; r < NG_HIST; ++r) col[r] = tmp[r];
555        }
556    }
557    for (int t = 0; t < nT; ++t) {
558        ss.ple_prev[0] = ss.ple_prev[1];
559        ss.ple_prev[1] = (int32_t) tokens[t];
560    }
561    if (taps_on_ && !tap_deliver(tap_pro_, nT, pos0, err)) return false;   // DFlash2: the prompt rows the drafter looks at
562    last_T_ = 0;   // nothing to commit
563    return true;
564}
565
566bool Window::prompt(const int64_t* tokens, int64_t n, int64_t pos0,
567                    const std::function<bool(const float*, int64_t, int64_t, std::string&)>& on_chunk, std::string& err) {
568    static const int C = [] {
569        const char* e = std::getenv("STRATA_METAL_PROMPT_CHUNK");
570        return std::max(64, std::min(8192, e ? std::atoi(e) : 2048));
571    }();
572    if (!pc_setup((int) std::min<int64_t>(C, std::max<int64_t>(n, 64)))) { err = "metal prompt: setup failed"; return false; }
573    const double t0 = now_ms();
574    pb_.gpu_ms = pb_.host_ms = pb_.mtp_ms = pb_.hidden_ms = pb_.emb_ms = pb_.ple_ms = 0;
575    struct MtpJoin { Window* w; ~MtpJoin() { w->mtp_wait(); w->pc_drain(); } } mtp_join{this};   // (every way out waits for the drafter's last rows)
576    for (int64_t c = 0; c < n; c += C) {
577        const int nT = (int) std::min<int64_t>(C, n - c);
578        if (pos0 + c + nT + 1 >= max_cells_) { err = "metal prompt: the prompt runs past the context"; return false; }
579        const int next_nT = (int) std::min<int64_t>(C, n - c - nT);
580        if (!pc_chunk(tokens + c, nT, pos0 + c, err, next_nT > 0 ? tokens + c + nT : nullptr, next_nT)) return false;
581        if (on_chunk) {
582            const double tm0 = now_ms();
583            mpsrc_ = &pb_.R;   // the drafter's prompt rows are this chunk's final residuals
584            const bool ok = on_chunk(nullptr, nT, pos0 + c, err);
585            mpsrc_ = nullptr;
586            if (mtp_async_) std::swap(pb_.R, pb_.R2);   // the drafter's rows are still reading this chunk's residuals: the next chunk writes the other
587            pb_.mtp_ms += now_ms() - tm0;
588            if (!ok) return false;
589        }
590    }
591    if (std::getenv("STRATA_METAL_TRACE") || std::getenv("STRATA_METAL_PROFILE"))
592        std::fprintf(stderr, "strata metal: prompt %lld tokens in %.1f ms (GPU %.1f ms, host rows %.1f ms [+%.1f ms beside the GPU; embeddings %.1f, PLE %.1f], drafter rows %.1f ms) "
593                             "-> %.1f tok/s\n", (long long) n, now_ms() - t0, pb_.gpu_ms, pb_.host_ms, pb_.hidden_ms, pb_.emb_ms, pb_.ple_ms, pb_.mtp_ms,
594                     1000.0 * (double) n / (now_ms() - t0));
595    return true;
596}