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
207.3 KiB3662 linesraw
1// metal/src/engine/window.cpp - the decode window on Metal: Verifier::init/run/commit's Metal side (the one backend
2// hook, src/core/verify.cpp under STRATA_GPU_METAL).  Everything above it - the decode loop, MTP control, the serve
3// protocol, the PLE table reads, the file tier - is the shared host code.
4//
5// The window is mac-kern's chain (metal/kernels, tests/token_chain.cpp) on the model GGUF itself: shard 1 is mmapped
6// and wrapped no-copy as one MTLBuffer, every weight is read where it lies (unified memory: no upload, no expert
7// cache), and one window is encoded as a dependency graph in one command buffer.  Its own state lives here (the GDN
8// recurrence and conv history, the int8 K/V and the indexer per QSA layer, the PLE history): the engine's
9// SessionState buffers are not used by it, except the PLE token window (ss.ple_prev) and table.
10//
11// First version (MAC-PLAN Phase 3 start): windows of one token (no MTP drafts yet: --mtp-max-t 1), greedy.  The PLE
12// block's projections run on the GPU; its norms, gate and conv (10240 values) on the CPU between two command buffers
13// (layer 0 | layers 1..47 + head).
14#include "gguf_lite.h"
15#include "mtl_rt.h"
16#include "resource_path.h"
17#include "ref_quant.h"
18#include "arena_budget.h"
19#include "stream.h"
20#include "geo.h"
21#include "msl_libs.h"
22#include "../../tests/coop_probe.h"
23
24#include "strata/artifact/gguf_reader.hpp"
25#include "strata/core/weights.hpp"
26#include "strata/core/dflash2.hpp"
27#include "strata/core/layer.hpp"
28#include "strata/core/conversation_cache.hpp"
29#include "strata/core/session.hpp"
30#include "strata/kernels/ngram.hpp"
31#include "strata/kernels/sampler.hpp"
32namespace strata::gpu { void* host_view(const void* device_pointer); }
33#include "strata/kernels/cpu/hadamard.hpp"
34#include "strata/kernels/cpu/expert_layout.hpp"
35
36#include <algorithm>
37#include <chrono>
38#include <cmath>
39#include <cstdio>
40#include <cstdlib>
41#include <cstring>
42#include <cctype>
43#include <cerrno>
44#include <filesystem>
45#include <functional>
46#include <future>
47#include <signal.h>
48#include <unistd.h>
49#include <map>
50#include <memory>
51#include <numeric>
52#include <set>
53#include <string>
54#include <sys/mman.h>
55#include <sys/sysctl.h>
56#include <mach/mach.h>
57#include <thread>
58#include <vector>
59
60namespace strata::gpu { uint64_t purge_device_allocations(size_t min_bytes); }   // metal/src/gpu/runtime.cpp
61
62namespace {
63std::string engine_msl_dir() { return strata_metal::resource("STRATA_METAL_ENGINE_KERNELS", "engine-msl", STRATA_METAL_ENGINE_KERNELS_DEFAULT); }
64}  // namespace
65
66namespace strata::metal_engine {
67
68// The prompt GDN scan kernel, chosen by chip and prompt length (gdn_prompt.metal, gdn_scan_r<IB, TB>; every choice is
69// bit-identical to gdn_scanr_4: the token order and the arithmetic are the same, only the staged block size TB changes, which
70// changes the threadgroup memory a core can hold at once).  Measured by metal/tests/gdn_chunk_bench:
71//   Apple M4 (the base chip): gdn_scanr_4_8, 1.16x on the scan, 1.11x on the GDN prompt stage, T 512..32K
72//   Apple M5 Max: gdn_scanr_4_4 from T >= 4096 (1.04x at 4K, 1.10x at 16K); below that the default is as fast
73//   anything else (other chips, unknown names): gdn_scanr_4 as before
74// STRATA_METAL_GDN_SCAN=<gdn_scanr_4 | gdn_scanr_4_8 | gdn_scanr_4_4 | gdn_scanr_4_2> forces a kernel (A/B and diagnosis).
75static const char* gdn_scan_name(const std::string& device, int T) {
76    static const std::string forced = [] {
77        const char* e = std::getenv("STRATA_METAL_GDN_SCAN");
78        const std::string s = e ? e : "";
79        return (s == "gdn_scanr_4" || s == "gdn_scanr_4_8" || s == "gdn_scanr_4_4" || s == "gdn_scanr_4_2") ? s : std::string();
80    }();
81    if (!forced.empty()) return forced.c_str();
82    if (device == "Apple M4") return "gdn_scanr_4_8";
83    if (device == "Apple M5 Max" && T >= 4096) return "gdn_scanr_4_4";
84    return "gdn_scanr_4";
85}
86
87// The M5 family's dense GEMM tiles for the prompt (bit-identical to the 64 x 64 tile: the tile only splits the output; measured on
88// an M5 Max, T = 2048 / 4096): the GDN out projection (N 2560, K 6144) 64 x 128 (1.17 -> 0.99 ms), the wide input projections
89// (N >= 6144) 128 x 64.  Other chips keep 64 x 64 (M4: no gain).  STRATA_METAL_GEMM_TILES=0 keeps the old tiles everywhere.
90static void gemm_tile(const std::string& device, int Nn, int K, int& tm, int& tn) {
91    static const bool off = [] { const char* e = std::getenv("STRATA_METAL_GEMM_TILES"); return e && std::string(e) == "0"; }();
92    if (off || device.rfind("Apple M5", 0) != 0) return;
93    if (Nn == strata_metal::geo::N && K == strata_metal::geo::ZV) { tm = 64; tn = 128; }
94    else if (Nn >= 6144) { tm = 128; tn = 64; }
95}
96// The four GDN input projections (qkv, z, alpha, beta) as ONE GEMM with a 16480 float output row (M5 family: 3.09 -> 2.87 ms a layer at
97// T = 2048; gdn_pre / gdn_post read the pieces at that stride, function constant 7).  Bit-identical to the separate GEMMs.
98// STRATA_METAL_GDN_FUSE=0 keeps the separate ones.
99static bool gdn_fused_inputs(const std::string& device) {
100    static const bool off = [] { const char* e = std::getenv("STRATA_METAL_GDN_FUSE"); return e && std::string(e) == "0"; }();
101    return !off && device.rfind("Apple M5", 0) == 0;
102}
103
104namespace {
105
106int g_slot_cap = 0;   // --batch N: the window keeps N + 1 sequences' running states side by side (set_batch_slots)
107
108// Q4-KQ: the kernel sources define STRATA_KQ_DOWN to instantiate the K-quant / IQ4_XS / IQ3_S down experts (moe.metal, moe_mm.metal).
109// The host asks for them only when a layer's down tensor has one of those types, so a Flash-Next set (Q5_1 / Q5_0 / Q8_0 / IQ4_NL / Q2_0
110// downs) compiles the same kernel text as before and pays nothing for them.
111std::string kq_down_prelude(const gguf::File& f) {
112    for (int l = 0; l < 128; ++l) {
113        const gguf::Tensor* t = f.find("blk." + std::to_string(l) + ".ffn_down_exps.weight");
114        if (!t) continue;
115        if (t->type == ref::Q3_K || t->type == ref::Q4_K || t->type == ref::Q5_K || t->type == ref::Q6_K || t->type == ref::IQ3_S ||
116            t->type == ref::IQ4_XS)
117            return "#define STRATA_KQ_DOWN 1\n";
118    }
119    return "";
120}
121
122namespace geo = strata_metal::geo;   // engine/geo.h: the shape this build is compiled for (kCompiledGeometry); Flash-Next's numbers by default
123constexpr int N = geo::N, HC = geo::HC, LR = geo::LR, NFF = geo::NFF, TOPK = geo::TOPK, NEXP = geo::NEXP, MAXT = 8, NVOCAB_MAX = 248320;
124constexpr int G_NL = geo::NL, G_QI = geo::QI, G_NGDN = geo::NGDN, G_SS = geo::SS, G_HK = geo::HK, G_HV = geo::HV, G_CONV = geo::CONV,
125              G_ZV = geo::ZV, G_GDNF = geo::GDN_FUSED, G_QH = geo::QH, G_QKV = geo::QKV, G_QD = geo::QD, G_IH = geo::IH, G_ID = geo::ID,
126              G_BUD = geo::BUD, G_QCHUNKS = geo::QCHUNKS, G_QCHUNKS2 = geo::QCHUNKS2, G_QPREP = geo::QPREP, G_HCD = geo::HCD, G_QFULL = geo::QFULL, G_QOUT = geo::QOUT,
127              G_KV = geo::KV, G_IQR = geo::IQR;
128// bytes of the running state of one sequence, per layer
129constexpr size_t GST_B = (size_t) 4 * G_SS * G_HV * G_SS;                       // GDN recurrence
130constexpr size_t HIST_B = (size_t) 4 * G_CONV * 3;                              // GDN conv history
131constexpr size_t PLEH_B = (size_t) 4 * strata::kernels::NG_HIST * G_HCD;        // PLE history
132constexpr size_t TAIL_B = (size_t) 4 * 4 * G_ID;                                // indexer raw tail (4 cells)
133constexpr size_t DEAD_B = (size_t) 4 * G_ID;                                    // indexer tail-block key
134constexpr int P_MAXE = 128, P_GEXP = 16, P_GSTART = P_GEXP + P_MAXE, P_ETOK = P_GSTART + P_MAXE + 4,
135              P_EW = P_ETOK + P_MAXE, P_TOKENT = P_EW + P_MAXE, P_INTS = P_TOKENT + P_MAXE, P_IGU = 4, P_IDN = 8;
136struct GemvArgs { uint32_t n_in, n_out, n_tok, row_bytes, x_stride, y_stride; };
137struct GrArgs { uint32_t n_embd, hc, hc_lr, n_tok, apply; float eps; };
138struct MoeArgs {
139    uint64_t gate_off, up_off, down_off, gu_stride, d_stride;
140    uint32_t gu_row, d_row, n_embd, n_ff, n_tok, topk, n_expert, gx_gu, gx_dn, pad;
141};
142struct GdnArgs { uint32_t h_k, h_v, channels, commit; float eps; uint32_t plane; };
143struct QsaArgs { uint32_t pos0, pos_base, max_cells, n_tok; float eps; };
144struct GlueArgs { uint32_t n, n_tok, n_embd, topk; };
145struct ArgArgs { uint32_t n_vocab, parts; };
146// the routed gate/up's i-quant grids from constant memory (QUANT_CTAB, function constant 23 of quant.metal): bitwise
147// the threadgroup copy's values, 3-7% faster on the M5 Max; STRATA_METAL_CTAB=0 turns it off
148bool metal_ctab() {
149    static const bool on = [] {
150        const char* e = std::getenv("STRATA_METAL_CTAB");
151        return !(e && std::string(e) == "0");
152    }();
153    return on;
154}
155// STRATA_METAL_F16=1 (opt-in): the decode windows' (resident model, with the head) dense GEMVs of Q2_0, the K-quants and IQ4_XS on the fp16 path -
156// the weights decoded into half, the window's x as half planes the writers of x add (function constant 25), the
157// products of a half unit summed in half, the scales and the units' sum in float (gemv.metal gemv16)
158// Unset (owner yes 2026-11-07; was strata_control/mac_fit.py engine_env): on for a resident IQ3_S or Q2_0 pack, found from the file name the launcher's
159// models carry ("...-IQ3_S-0000N-of-0000M.gguf", "...-Q2_0-..."), decided once the model is open (f16_auto_for).  M5 Max: decode +9 to +15%
160// (Q2_0) and +9 to +12% (IQ3_S), top-1 agreement 97.1% / 96.2%, mean KL 0.009 / 0.016, 61-task suite the same.  STRATA_METAL_F16=0 turns it off,
161// =1 turns it on for any pack.
162bool g_f16_auto = false;
163bool metal_f16() {
164    static const int mode = [] { const char* e = std::getenv("STRATA_METAL_F16"); return e == nullptr || *e == '\0' ? -1 : (std::string(e) == "1" ? 1 : 0); }();
165    return mode == 1 || (mode < 0 && g_f16_auto);
166}
167bool f16_auto_for(const std::string& path, bool streaming) {
168    if (streaming) return false;
169    const size_t k = path.find_last_of("/\\");
170    std::string n = k == std::string::npos ? path : path.substr(k + 1);
171    for (char& c : n) c = (char) std::toupper((unsigned char) c);
172    return n.find("-IQ3_S-") != std::string::npos || n.find("-Q2_0-") != std::string::npos;
173}
174// the half plane a format reads: 0 raw, 1 x * 4^-(i % 4), 2 x * 2^-8 at odd i; -1 no fp16 decode
175int x16_kind(int ty) {
176    switch (ty) {
177        case ref::IQ4_XS: return 0;
178        case ref::Q2_0: return 1;
179        case ref::Q3_K: case ref::Q4_K: case ref::Q5_K: case ref::Q6_K: return 2;
180        default: return -1;
181    }
182}
183// the tiles gemv.metal instantiates gemv16 on (GV16_SET)
184bool gemv16_tile(int L, int R, int S, int K) {
185    static const std::array<int, 4> t16[] = {{32, 1, 4, 1}, {32, 2, 4, 1}, {16, 1, 4, 1}, {16, 2, 4, 1}, {8, 1, 4, 1}, {8, 2, 4, 1}, {4, 2, 4, 1},
186                                             {4, 1, 4, 1}, {32, 1, 8, 2}, {16, 1, 8, 4}, {2, 1, 4, 1}, {2, 2, 4, 1}, {1, 1, 4, 1}};
187    return std::find(std::begin(t16), std::end(t16), std::array<int, 4>{L, R, S, K}) != std::end(t16);
188}
189// the writers of the window's x: their pipelines with the half planes (function constant 25) under STRATA_METAL_F16
190mtl::Constants x16c(mtl::Constants c = {}) { return metal_f16() ? c.b(25, true) : c; }
191std::string x16k(const std::string& k) { return metal_f16() ? k + "#h" : k; }
192
193int xkind(int t) {
194    switch (t) {
195        case ref::Q2_0: return 1;
196        case ref::Q4_K: case ref::Q5_K: return 2;
197        case ref::Q6_K: case ref::Q3_K: return 3;
198        default: return 0;
199    }
200}
201
202// a prepared activation: 4 planes of MAXT rows of n, then the per-16 sums
203struct Act {
204    mtl::Buffer b;
205    int n = 0;
206    size_t plane_bytes() const { return (size_t) 4 * MAXT * n; }
207    size_t x16_bytes() const { return plane_bytes() * 4 + plane_bytes() / 16; }   // the half planes' start (STRATA_METAL_F16)
208};
209
210double now_ms() { return std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now().time_since_epoch()).count(); }
211
212}  // namespace
213
214// the prompt chain's state (prompt_chain.inc): kernel libraries, the variant, buffers for chunks of C rows
215struct PromptBufs {
216    int lib = -1, lgdn = -1, lqsa = -1;
217    bool k4 = false;
218    bool v3e = false;
219    bool v6 = false;             // ragged expert tiles (mm_gu6 / mm_down6): groups of ms 16-row subtiles share one weight decode
220    int ms = 1;
221    bool fused = false;          // the GDN input projections as one GEMM (gdn_fused_inputs)            // the M5's expert kernels (v3): not for the trellis types, which have only v2
222    int C = 0, maxrows = 0, tm = 16;   // tm: the expert plan's tile height
223    double gpu_ms = 0, host_ms = 0, mtp_ms = 0, hidden_ms = 0, emb_ms = 0, ple_ms = 0;   // hidden_ms: the host rows computed beside the GPU (pc_host_rows)
224    int gu3[4] = {}, dn3[4] = {};
225    mtl::Buffer R, R2, bo, inj[2], xn, xnh, V, loh, mixed, mixh, qkv, z, al, be, yg, ygh, gqn, gkn, gvc, ggb, gkq, go, qfull,
226        kcur, vcur, iqr, ikr, qcur, qcurh, qidx, scores, qids, part, XQ, xqh, logits, ids, wts, bcnt, boff, eoff, tiles, meta,
227        stok, sw, pos, XS, HS, YE, yr, gsh, ush, hh, ys, sgv, WD, WU, Wqkv, Wz, Wal, Wbe, Wout, Wq, Wk, Wv, Wiq, Wik, Wr,
228        Wsg, Wshg, Wshu, Wshd, yf, Wcat, pemb, pembh, pkey, pval, keyn, qn, gated, normW, Wpk, Wpv, mixr;
229};
230
231// The vision path (--vision, GENI requests), from the shared host code: the image rows of the prompt being read
232// (host rows by absolute position, null = embed the token; set by prompt_run for its duration) and the M-RoPE table
233// (int32 [cells][3] (t, h, w); mrope_table_set: the host view of the device table the server fills per request).
234const float* const* g_embd_rows = nullptr;
235const int32_t* g_mrope_host = nullptr;
236const int32_t* g_mrope_dev = nullptr;
237
238class Window {
239public:
240    bool init(const strata::core::ModelGeometry& g, strata::core::SessionState& ss, const std::string& shard1, int max_t,
241              int64_t max_cells, std::string& err);
242    bool run(int T, const int32_t* tokens, int64_t pos0, bool head, int32_t* out, std::string& err);
243    bool commit(int n_keep, std::string& err);
244    bool finish(int Tn, const int32_t* tokens, int64_t pos0, bool head, int32_t* out, double t0);
245    // The request's sampling for the head rows of the windows that follow (sample.metal): null = greedy, the in-graph argmax.  `hist` is the penalty
246    // history, Tn rows of hist_len tokens (the last penalty_last_n of a row count, -1 = unused), read when the window's rows are sampled.
247    void set_sampling(const strata::kernels::SamplerParams* sp, const int32_t* hist, int hist_len);
248    bool sample_rows(int Tn, int32_t* out, std::string& err);
249    bool sample_slot_row(int row, const strata::kernels::SamplerParams& sp, const int32_t* hist, int hist_len, int32_t* tok, std::string& err);   // one slot's row of a batch window, its own params
250    bool sample_run(int row0, int n, const strata::kernels::SamplerParams& sp, const int32_t* hist, int hl, std::string& err);   // after run(): replaces out[0..Tn) (and tokout_) by the sampled tokens
251    bool copy_logits(int t, float* host) const;
252    int64_t vocab() const { return n_vocab_; }
253    bool ready() const { return cx_ != nullptr; }
254    bool streaming() const { return stream_; }
255    // --serve's conversation checkpoints: the window's running state (the GDN recurrences and conv histories, the
256    // PLE history, each QSA layer's indexer tail and tail-block key); the KV and pooled keys are positional
257    bool checkpoint_save(strata::core::ConversationCheckpoint& c, std::string& err);
258    bool checkpoint_restore(const strata::core::ConversationCheckpoint& c, std::string& err);
259    // Conversation parking reads the K/V from the session's QsaStates.  On Metal the K/V lives only in this window's buffers
260    // (the session's own pools are never written), so each owned QsaState is pointed at the window's buffers: the same
261    // cell-major layout the generic snapshot copies as byte prefixes (kq/vq cells*512 B, scales cells*16 B, pooled rows*512 B).
262    void bind_session(strata::core::SessionState& ss);
263    void bind_draft(strata::core::QsaState& st);
264    bool mtp_ready() const { return mtp_on_; }
265    void reset();   // a new sequence (session_zero): the running state zeroed
266    // ---- batch slots (--batch N): each slot is another sequence's running state (GDN recurrence and conv history, the PLE
267    // history, each QSA layer's K/V, indexer tail and pooled keys).  The live members always hold ONE sequence's state (the
268    // main one between calls); a slot's lives in a stash and is swapped in for its window (activate): the buffer objects stay
269    // where they are (the cached dispatches point at them), only their contents are exchanged.
270    bool slots_init(const std::vector<strata::core::SessionState*>& slots, std::string& err);
271    int n_slots() const { return sets_.empty() ? 0 : (int) sets_.size() - 1; }
272    int set_of(const strata::core::SessionState* s) const {
273        auto it = set_of_ss_.find(s);
274        return it == set_of_ss_.end() ? 0 : it->second;
275    }
276    // one window of S one-token rows, row t = slot rows[t] at position pos[t]: each runs and commits in its own state
277    bool run_slots(const int* rows, int S, const int32_t* tokens, const int64_t* pos, int32_t* out, std::string& err);
278    // slot b's state <-> the main one (the GPU is idle between windows): the running state and the first `upto` cells of K/V
279    bool slot_copy(bool into_slot, int b, int64_t upto, bool kv_only, std::string& err);
280    void activate(int set);
281    void set_max_t(int t) { max_t_ = std::min(t, MAXT); }
282    // ---- the MTP draft layer (mtp.hpp's math on mac-kern's kernels; the MTP GGUF from tools/mtp_pack.py)
283    bool mtp_load(const std::string& gguf, int max_t, std::string& err);
284    bool mtp_prefill(const int32_t* next_tokens, int64_t n, int64_t cell0, std::string& err);
285    bool mtp_draft(int T, const int32_t* tokens, int64_t p, int a, int max_steps, int32_t* drafts, float* probs,
286                   float min_p, int* n_drafts, std::string& err);
287    bool mtp_loaded() const { return mtp_on_; }
288    // ---- DFlash2 (dflash2.inc): the taps of the tapped layers and the drafter
289    bool taps_enable(const std::vector<int>& layers, std::string& err);
290    void taps_set_cb(int64_t first_pos, const std::function<bool(const float*, int64_t, int64_t, std::string&)>& cb) { tap_first_ = first_pos; tap_cb_ = cb; }
291    const float* tap_dec_ptr() const { return tap_dec_.as<float>(); }
292    bool tap_deliver(const mtl::Buffer& buf, int rows, int64_t pos0, std::string& err);
293    bool tap_deliver_dec(int rows, int64_t pos0, std::string& err) { return tap_deliver(tap_dec_, rows, pos0, err); }
294    bool df2_ensure(const std::string& path, std::string& err);
295    bool df2_bind(const std::string& vocab_file, std::string& err);
296    bool df2_context_ptr(const float* taps, int64_t n, int64_t pos0, std::string& err);
297    bool df2_prepare(std::string& err);
298    void df2_set_cap(int n);
299    void df2_set_floor(int64_t pos);
300    int64_t df2_restore_lineage(const std::vector<int32_t>& cur_hist, int64_t cur_hi, const int32_t* ids, int64_t resume, std::string& err);
301    void df2_kv_list(std::vector<mtl::Dispatch>& ds, int n, const mtl::Buffer& pos, size_t pos_off, const mtl::Buffer& rt, size_t rt_off);
302    int64_t df2_floor() const;
303    bool df2_draft(int n_new, int64_t pos0, int32_t anchor, int32_t* drafts, float* probs, std::string& err);
304    uint64_t df2_bytes() const;
305    double df2_gpu_ms() const;
306    double df2_last_build_ms() const;
307    // the prompt through mac-kern's prompt kernels (prompt_chain.inc)
308    bool prompt(const int64_t* tokens, int64_t n, int64_t pos0,
309                const std::function<bool(const float*, int64_t, int64_t, std::string&)>& on_chunk, std::string& err);
310
311private:
312    const gguf::Tensor& T(const std::string& name) const {
313        const gguf::Tensor* t = f_.find(name);
314        if (!t) { std::fprintf(stderr, "strata metal: the model has no tensor %s\n", name.c_str()); std::exit(2); }
315        return *t;
316    }
317    const mtl::Pipeline* P(int lib, const std::string& fn, const mtl::Constants& c, const std::string& key) {
318        auto it = pcache_.find(key);
319        if (it == pcache_.end()) {
320            it = pcache_.emplace(key, cx_->pipeline(lib, fn, c)).first;
321            pkey_of_[&it->second] = key;
322        }
323        return &it->second;
324    }
325    void push(std::vector<mtl::Dispatch>& ds, mtl::Dispatch d) {
326        d.barrier = !nb_;
327        nb_ = false;
328        // timing only (WRONG answers): STRATA_METAL_SKIP=a,b,... runs the dispatches whose pipeline name contains one
329        // of the words as empty grids (the marginal cost of a kernel class by leaving it out)
330        static const std::vector<std::string> skip = [] {
331            std::vector<std::string> v;
332            if (const char* e = std::getenv("STRATA_METAL_SKIP")) {
333                std::string s = e, w;
334                for (char c : s + ",") { if (c == ',') { if (!w.empty()) v.push_back(w); w.clear(); } else w += c; }
335            }
336            return v;
337        }();
338        if (!skip.empty()) {
339            const std::string& k = pkey_of_[d.p];
340            for (const auto& w : skip)
341                if (k.find(w) != std::string::npos) { d.indirect = nullptr; d.grid[0] = 0; break; }
342        }
343        mtl::require_fit(d, "engine dispatch (graph build)");   // a kernel Metal would skip silently: stop at the build, not at the first wrong answer
344        ds.push_back(std::move(d));
345    }
346    std::map<const mtl::Pipeline*, std::string> pkey_of_;
347    void gemv(std::vector<mtl::Dispatch>& ds, const gguf::Tensor& t, const Act& x, const mtl::Buffer& y, size_t y_stride,
348              int ntok, size_t y_off = 0, const mtl::Buffer* wb = nullptr);
349    void xprep(std::vector<mtl::Dispatch>& ds, const mtl::Buffer& x, const Act& out, int n);
350    void gr_read(std::vector<mtl::Dispatch>& ds, const std::string& pre, bool apply, const Act& out, bool final_, int ntok);
351    void layer(std::vector<mtl::Dispatch>& ds, int l, int ntok, int64_t pos0);
352    void ple_cpu(int T);
353    // the MTP layer: the input branches + attention HC read + K/V append for `n` rows (srcR rows, host tokens) at
354    // cells cell0..; with `full` (n == 1) the rest of the layer too and the draft head into mlm_/tokout_.  The
355    // embedding rows go to memb_ rows erow..; tokens == nullptr: memb_ row erow already holds the embedding (put
356    // there by mtp_embed on the GPU).  `slot`: the dense attention's cell list (one per draft step of a round).
357    void mtp_encode(std::vector<mtl::Dispatch>& ds, const mtl::Buffer& srcR, size_t src_off, int n, const int32_t* tokens,
358                    int64_t cell0, bool full, int erow = 0, int slot = 0);
359    // a draft round's step j on the GPU: the pick and its probability (dout_/dprob_ [j]), and with `embed` the picked
360    // token's embedding into memb_ row 0 (the next step's input)
361    void mtp_pick(std::vector<mtl::Dispatch>& ds, int j, bool embed);
362    void gr_read_m(std::vector<mtl::Dispatch>& ds, const std::string& pre, mtl::Buffer& Rb, const mtl::Buffer& bo,
363                   const mtl::Buffer& inj_in, const mtl::Buffer& inj_out, bool apply, const Act& out, bool final_, int ntok);
364    const gguf::Tensor& TM(const std::string& name) const {
365        const gguf::Tensor* x = fm_.find(name);
366        if (!x) { std::fprintf(stderr, "strata metal: the MTP model has no tensor %s\n", name.c_str()); std::exit(2); }
367        return *x;
368    }
369    size_t NM(const std::string& name) const {   // the folded (1 + w) copy of an F32 norm of the MTP model
370        auto it = mnorm_off_.find(name);
371        if (it == mnorm_off_.end()) { std::fprintf(stderr, "strata metal: no MTP norm %s\n", name.c_str()); std::exit(2); }
372        return it->second;
373    }
374
375    strata::core::SessionState* ss_ = nullptr;        // the session whose sequence the live state is (the main one, or a batch slot's)
376    strata::core::SessionState* main_ss_ = nullptr;   // the main session: it owns the PLE table (read by every slot)
377    gguf::File f_;
378    std::unique_ptr<mtl::Context> cx_;
379    mtl::Buffer W_;
380    // a model wrapped in chunks (mtl::Context::wrap): the routed experts are bound at the layer's first expert tensor,
381    // their offsets made relative to it; returns that binding offset (0 when W_ is one buffer or the experts stream)
382    size_t moe_rebase(uint64_t& g, uint64_t& u, uint64_t& d) const {
383        if (stream_ || !W_.chunks) return 0;
384        const uint64_t b = std::min({g, u, d});
385        g -= b; u -= b; d -= b;
386        return (size_t) b;
387    }
388    int lib_ = -1, lgdn_ = -1, lqsa_ = -1, lsmp_ = -1, lple_ = -1;
389    bool samp_on_ = false;
390    strata::kernels::SamplerParams samp_;
391    const int32_t* samp_hist_ = nullptr;
392    int samp_hist_len_ = 0;
393    mtl::Buffer sbias_, shist_, scv_, sci_;
394    size_t shist_cap_ = 0, sbias_cap_ = 0;
395    uint64_t samp_windows_ = 0;
396    std::map<std::string, mtl::Pipeline> pcache_;
397    bool nb_ = false;
398    // ---- DFlash2 (dflash2.inc)
399    struct Df2;
400    Df2* df2_ = nullptr;
401    bool df2_open(const std::string& path, std::string& err);
402    bool df2_load_pack(std::string& err);
403    bool df2_context(const mtl::Buffer& taps, size_t taps_off, int64_t n, int64_t pos0, std::string& err);
404    void df2_ctx_list(std::vector<mtl::Dispatch>& ds, const mtl::Buffer& taps, size_t taps_off, int n, const mtl::Buffer& pos, size_t pos_off, const mtl::Buffer& rt, size_t rt_off);
405    void df2_block_list(std::vector<mtl::Dispatch>& ds);
406    void df2_mm(std::vector<mtl::Dispatch>& ds, const mtl::Buffer& qs, size_t qs_off, const mtl::Buffer& sc, size_t sc_off, uint32_t K, uint32_t rows, const mtl::Buffer& x, size_t x_off, uint32_t x_stride, const mtl::Buffer& y, size_t y_off, uint32_t y_stride, int ncol);
407    void df2_mmn(std::vector<mtl::Dispatch>& ds, const std::string& name, const mtl::Buffer& x, size_t x_off, uint32_t x_stride, const mtl::Buffer& y, uint32_t y_stride, int ncol, bool reuse = false);
408    void df2_mm4(std::vector<mtl::Dispatch>& ds, const mtl::Buffer& qs, size_t qs_off, const mtl::Buffer& sc, size_t sc_off, uint32_t K, uint32_t rows, const mtl::Buffer& x, size_t x_off, const mtl::Buffer& y, uint32_t y_stride, int ncol, bool reuse);
409    void df2_rms(std::vector<mtl::Dispatch>& ds, const mtl::Buffer& x, const mtl::Buffer& y, const char* wname, int rows);
410    void df2_free();
411    void df2_dump_rows(const mtl::Buffer& taps, size_t taps_off, int64_t n, int64_t pos0);
412    void df2_dump_write(int64_t s, int32_t anchor);
413    void df2_prof(const std::vector<mtl::Dispatch>& ds);
414    bool taps_on_ = false;
415    std::vector<int> tap_layers_;
416    int tap_slot_[64] = {};
417    int ldf2_ = -1;
418    mtl::Buffer tap_dec_, tap_pro_, df2_stage_;
419    int tap_pro_rows_ = 0;
420    int64_t df2_stage_rows_ = 0;
421    int64_t tap_first_ = 0;
422    std::function<bool(const float*, int64_t, int64_t, std::string&)> tap_cb_;
423    void tap_dispatch(std::vector<mtl::Dispatch>& ds, int l, const mtl::Buffer& R, const mtl::Buffer& bo, const mtl::Buffer& inj, const mtl::Buffer& out, int rows);
424    mtl::Buffer& tap_pro_buf(int rows);
425    int max_t_ = 1;
426    int nexp_ = NEXP;   // the trunk's routed experts per layer (512, or 256 for the Coder); the MTP layer is always NEXP
427    int64_t max_cells_ = 0;
428    int64_t n_vocab_ = 0;
429    float eps_ = 1e-6f;
430    // buffers
431    mtl::Buffer R_, bo_, inj_[2], xn_, lo_, qkv_, z_, al_, be_, yg_, logits_, ids_, wts_, plan_, h_, ye_, gsh_, ush_,
432        ysh_, sg_, qfull_, kcur_, vcur_, iqr_, ikr_, qcur_, qidx_, scores_, qids_, part_, cs_, lm_, apv_, api_, tokout_,
433        emb_, pkey_, pval_, qkvL_, alL_, beL_, zL_, ydump_, keyn_, qn_, gated_, normW_, pleHist_;
434    Act XA_, XF_, XY_, XQ_, XH_, XE_;
435    mtl::Buffer h16_;   // STRATA_METAL_F16: the routed gate/up's h as half, for the down
436    int cur_inj_ = 0;
437    // state
438    std::vector<mtl::Buffer> gst_, ghist_[2], kq_, vq_, ksc_, vsc_, tail_, dead_, pooled_;
439    // --batch N: every one of those is a view of set 0 in a bigger buffer holding all N + 1 sets (the slots' running states side
440    // by side), so ONE dispatch can address any slot (rinfo_: the strides and each row's slot / cell / history parity)
441    bool bigs_ok_ = false;
442    std::vector<mtl::Buffer> gstBig_, hbBig_, kqBig_, vqBig_, kscBig_, vscBig_, tailBig_, deadBig_, pooledBig_;
443    mtl::Buffer pleBig_, rinfo_;
444    size_t st_gst_ = 0, st_hist_ = 0, st_kq_ = 0, st_sc_ = 0, st_tail_ = 0, st_dead_ = 0, st_pooled_ = 0, st_ple_ = 0;   // bytes between sets
445    bool rows_ = false;       // the window being built / run holds one token of each of rows_n_ DIFFERENT sequences (batch slots)
446    int rows_n_ = 0;
447    strata::core::SessionState* rows_ss_[MAXT] = {};
448    int rows_set_[MAXT] = {};
449    static mtl::Buffer view_of(const mtl::Buffer& big, size_t off, size_t bytes) {
450        mtl::Buffer v = big;
451        v.ptr = (char*) big.ptr + off;
452        v.bias = big.bias + off;
453        v.bytes = bytes;
454        return v;
455    }
456    bool run_rows(const int* rows, int S, const int32_t* tokens, const int64_t* pos, int32_t* out, std::string& err);
457    bool finish_rows(int S, const int32_t* tokens, int32_t* out, double t0);
458    struct SeqSet {
459        std::vector<mtl::Buffer> gst, gh0, gh1, kq, vq, ksc, vsc, tail, dead, pooled;
460        mtl::Buffer pleHist;
461        std::vector<float> ple_hist;
462        std::vector<float> last_norm;
463        int hp = 0, pend_fold = 0, last_T = 0;
464        bool last_head = true;
465        int32_t last_tokens[MAXT] = {};
466        strata::core::SessionState* ss = nullptr;
467    };
468    std::vector<std::unique_ptr<SeqSet>> sets_;     // [0] the spare the main state is exchanged with, [b + 1] slot b
469    std::map<const strata::core::SessionState*, int> set_of_ss_;
470    int active_ = 0;
471    void swap_state(SeqSet& o);
472    void alloc_set(SeqSet& o, bool real, int idx = 0);
473    int hp_ = 0;                     // which of the two history buffers holds the committed conv history (all layers)
474    // commit(n) of a window of several tokens: the GDN fold of the kept prefix waits for the next window and runs at
475    // the start of its command buffer (one submit and wait less a round).  Nothing else reads the GDN state between
476    // the two (the drafter reads the window's rows and its own caches).  STRATA_METAL_LAZY_FOLD=0: at commit.
477    int pend_fold_ = 0;
478    bool win_head_ = true;      // the window being encoded has the head
479    bool last_head_ = true;     // the last window had it
480    // token_chain's --fuse (mac-kern): the GDN step writes the prepared y planes itself (no xprep), and a window whose
481    // context is within the selection budget skips the QSA score and top-k (the cell list is the identity: qids_
482    // holds it from init, restored after a window that selected).  STRATA_METAL_FUSE=0: off.
483    // gr_norm2 / moe_combine_sh2 (gr.metal, glue.metal): the same arithmetic with the loads batched ahead of the stores / sums (the
484    // originals wait one memory latency per loop iteration).  Bitwise the same outputs.  STRATA_METAL_LDB=0: the original kernels.
485    bool ldb_ = !(std::getenv("STRATA_METAL_LDB") && std::string(std::getenv("STRATA_METAL_LDB")) == "0");
486    const char* k_norm() const { return ldb_ ? "gr_norm2" : "gr_norm"; }
487    const char* k_comb() const { return ldb_ ? "moe_combine_sh2" : "moe_combine_sh"; }
488    bool fuse_ = !(std::getenv("STRATA_METAL_FUSE") && std::string(std::getenv("STRATA_METAL_FUSE")) == "0");
489    bool qdirty_ = false;
490    // STRATA_METAL_KPROF=T (test tooling): once, after the 20th cached window of T tokens with the head, the GPU time
491    // of each kernel class alone (the window's own dispatches of that pipeline + weight role, run by themselves)
492    void kprof(const std::vector<mtl::Dispatch>& ds, int Tn);
493    // STRATA_METAL_STEPPROF=T (measurement, round 0215): once, after the 20th cached head window of T tokens, where one decode step's GPU time
494    // goes IN SITU, by part: the window's dispatch list is run as prefixes ending at every barrier group (STRATA_METAL_STEPPROF_REPS runs each,
495    // default 5, median); a group's time is the difference of two prefixes, so the gaps between dispatches and the overlap of the groups that
496    // share a barrier are inside the numbers.  Also the weight bytes read per part (dense from the tensor table, experts from the routed ids of
497    // every layer: the distinct experts) and the GB/s each part reaches.  STRATA_METAL_STEPPROF_OUT=path: one line per group.
498    void stepprof(const std::vector<mtl::Dispatch>& ds, int Tn);
499    void fold(std::vector<mtl::Dispatch>& ds, int n_keep, int hp);
500    // the encoded window per (T, head, hp_): built once, then only the positions are patched (the host's encode cost)
501    struct Cached {
502        std::vector<mtl::Dispatch> ds;
503        std::vector<int> cuts;                  // SSD streaming: the segment ends (one per layer, before its experts)
504        std::vector<std::pair<int, int>> qsa;   // (dispatch, kind): 0 QsaArgs n_tok = T, 1 the merge (MAXT), 2 the scores
505    };
506    std::map<int, Cached> wcache_;
507    bool f16_enc_ = false;   // STRATA_METAL_F16: a decode window is being encoded (the MTP layer stays fp32)
508    std::vector<std::pair<int, int>>* rec_ = nullptr;
509    // ---- SSD streaming (stream.h): the dense weights in W_, the routed experts in the arena
510    std::unique_ptr<ExpertStream> st_;
511    bool stream_ = false, st_pred_ = false;
512    std::vector<int>* cuts_ = nullptr;
513    mtl::Buffer predL_, predL2_;     // 48 x MAXT x 512: layer l + 1's (l + 2's) router logits from layer l's FFN input
514    int seg_T_ = 0;
515    bool stream_arena(std::string& err);
516    double run_ds(Cached& c);
517    // prompts on the matrix units (prompt_chunk below)
518    struct PromptGemm;
519    PromptGemm* pg_ = nullptr;
520    const int32_t* cut_ids_ = nullptr;    // the routed ids the handshake reads (a prompt chunk's; else ids_)
521    const mtl::Buffer* mtp_src_ = nullptr;   // the rows the draft layer's prompt K/V read (a prompt chunk's; else R_)
522    double pg_ms_ = 0;
523    int64_t pg_tok_ = 0;
524public:
525    bool prompt_gemm_on(int64_t n) const;
526    bool prompt_gemm_init(std::string& err);
527    bool prompt_chunk(const int32_t* tokens, int Tn, int64_t pos0, std::string& err);
528    int prompt_chunk_rows() const;
529    void prompt_region(bool hold) { if (stream_ && st_ && st_->ready()) st_->hold_region(hold); }
530    void stream_report(FILE* f) const {
531        if (!st_) return;
532        st_->report(f);
533        for (int t = 1; t <= MAXT; ++t)
534            if (win_n_[t])
535                std::fprintf(f, "stream windows T=%d     %d (%s): %.2f ms each (GPU incl. the host's turns %.2f ms)\n", t, win_n_[t],
536                             t == 8 ? "prompt rows" : "decode", win_ms_[t] / win_n_[t], win_gpu_[t] / win_n_[t]);
537    }
538    int win_n_[MAXT + 1] = {};
539    double win_ms_[MAXT + 1] = {}, win_gpu_[MAXT + 1] = {};
540    void at_cut(int s) {
541        st_->at_layer(s, seg_T_, TOPK, cut_ids_ ? cut_ids_ : ids_.as<int32_t>(), st_pred_ && !cut_ids_ ? predL_.as<float>() + (size_t) s * MAXT * 512 : nullptr,
542                      predL2_.ptr && !cut_ids_ ? predL2_.as<float>() + (size_t) s * MAXT * 512 : nullptr);
543    }
544private:
545    std::vector<float> ple_hist_;    // NG_HIST x hc_dim normalized rows, row-fastest
546    bool ple_on_ = false;
547    int last_T_ = 0;
548    double last_gpu_ms_ = 0;
549    int last_n_disp_ = 0;
550    int32_t last_tokens_[MAXT] = {};
551    std::vector<float> last_norm_;   // the window's normalized PLE rows (T x hc_dim), for commit
552    // STRATA_METAL_LOGPOS=<path> (test tooling, one-token windows): per decode position the log-probability of the
553    // token that came next (the next window's input: with --spec-follow, the forced text) and the top 64, in the
554    // KL harness's row format (phaseA-tests cuda_p0/cuda_kl.py load_lp): pos, target, lp, argmax, 4 x 0, id:lp ...
555    std::FILE* logpos_ = nullptr;
556    bool lp_pend_ = false;
557    int64_t lp_pos_ = 0, lp_first_ = -1;
558    int32_t lp_arg_ = 0;
559    double lp_lse_ = 0.0;
560    std::vector<float> lp_row_;
561    std::vector<std::pair<float, int32_t>> lp_top_;
562    void logpos(int Tn, const int32_t* tokens, int64_t pos0, bool head);
563    // STRATA_METAL_PROFILE=1: where a window's time goes, per window size (printed when the window goes away)
564    struct Prof { int64_t n = 0; double pre = 0, rg = 0, gpu = 0, fin = 0, all = 0; };
565    std::map<int, Prof> prof_;
566    Prof cprof_, dprof_;   // commit (folds), the draft rounds
567    double tp_pre_ = 0, tp_rg_ = 0;
568    bool prof_printed_ = false;
569public:
570    void print_prof(bool periodic = false);
571    ~Window();
572    void prof_add(bool draft, double ms) { Prof& x = draft ? dprof_ : cprof_; ++x.n; x.all += ms; }
573private:
574    // the Q8_0 copies of the hyper-connection matrices (the default; STRATA_HC_Q8=0: the BF16 originals)
575    // Gyro (agentionai's Hadamard-folded trellis experts, native_experts.txt v5 + hadamard.txt): the gate/up input is
576    // H (s * x) and the down input H h, per block of 128; XR_ holds the rotated rows, hsx_/hsh_ the +/-1 signs
577    bool had_on_ = false;
578    int had_block_ = 128;
579    bool gyro_dense_ = false;   // a trellis-expert file: its dense K-quants get their own GEMV tiles (gemv() below)
580    bool had_gu(int l) const { return had_on_ && strata::kernels::cpu::hadamard_spec().gu(l); }
581    bool had_dn(int l) const { return had_on_ && strata::kernels::cpu::hadamard_spec().down(l); }
582    mtl::Buffer XR_, hsx_, hsh_;
583    // one rotation dispatch: rows of `width` values (a multiple of 128) in place or from x to y; f16 = half rows
584    void had_rows(std::vector<mtl::Dispatch>& ds, int lib, const std::string& pfx, const mtl::Buffer& x, size_t x_off,
585                  const mtl::Buffer& y, size_t y_off, int rows, int width, const mtl::Buffer* signs, bool f16);
586    // the prompt's h rows (half, padded rows of the expert tiles, their count in meta[8]): rotated in place, one
587    // threadgroup a row through the indirect grid
588    void had_rows_ind(std::vector<mtl::Dispatch>& ds, int lib, const std::string& pfx, const mtl::Buffer& h, const mtl::Buffer& meta);
589    bool hc_q8_ = false;
590    mtl::Buffer Q8_;
591    std::map<std::string, size_t> q8off_;
592    // MTP
593    bool mtp_on_ = false;
594    int lmtp_ = -1;
595    gguf::File fm_;
596    mtl::Buffer Wm_, mnorm_, mR_, memb_, men_, me2_, mhn_, mh2_, midx_, mbo_, minj_[2], mqids_, mlm_;
597    std::map<std::string, size_t> mnorm_off_;
598    std::vector<mtl::Buffer> mkq_, mvq_, mksc_, mvsc_, mtail_, mdead_, mpooled_;
599    // the draft head over a token subset (data/draft_vocab.bin, as the CUDA drafter): its rows gathered from the head
600    mtl::Buffer mhead_;
601    gguf::Tensor mhead_t_;
602    std::vector<int32_t> dvocab_;
603    // the draft layer's BF16 matrices in Q8_0 (half the bytes a draft step reads; drafts only: the verify window
604    // decides every token).  STRATA_METAL_MTP_Q8=0 keeps BF16.
605    mtl::Buffer mq8_;
606    std::map<std::string, gguf::Tensor> mq8t_;
607    const mtl::Buffer& MB(const std::string& name) const { return mq8t_.count(name) ? mq8_ : Wm_; }
608    const gguf::Tensor& TQ(const std::string& name) const {
609        auto it = mq8t_.find(name);
610        return it != mq8t_.end() ? it->second : TM(name);
611    }
612    Act XEn_, XHn_;
613    PromptBufs pb_;
614    // The drafter's K/V rows of a prompt chunk run on a second queue while the next chunk's main work runs on the first (the two touch
615    // different buffers: the chunk's final residual rows are double-buffered, pb_.R / pb_.R2).  The drafter's rows of chunk c+1 wait for
616    // chunk c's (they share the drafter's cache and scratch).  STRATA_METAL_MTP_OVERLAP=0: each chunk's rows run before the next chunk.
617    bool mtp_ovl_ = !(std::getenv("STRATA_METAL_MTP_OVERLAP") && std::string(std::getenv("STRATA_METAL_MTP_OVERLAP")) == "0");
618    void* mtp_async_ = nullptr;
619    void mtp_wait() { if (mtp_async_) { cx_->wait_async(mtp_async_); mtp_async_ = nullptr; } }
620    mtl::Buffer mpemb_;                    // the drafter's prompt embedding rows (mtp_prefill, one command buffer)
621    size_t mpemb_rows_ = 0;
622    const mtl::Buffer* membp_ = nullptr;   // mtp_encode's embedding rows (nullptr: memb_)
623    const mtl::Buffer* mpsrc_ = nullptr;   // the drafter's prompt rows (nullptr: R_)
624    bool coop_k4();
625    // the vision path: the embedding row of an absolute position (an image row, or null), the M-RoPE table rows a
626    // window reads copied into mrope_ (qsa_prep's buffer 20, function constant 24)
627    const float* img_row(int64_t pos) const { return g_embd_rows ? g_embd_rows[pos] : nullptr; }
628    mtl::Buffer mrope_;
629    // the PLE conv kernel as F16 (ple_conv_add reads half): the file's own F16 tensor, or an F32 one (Unsloth's)
630    // narrowed with round-to-nearest-even as the host loader does
631    mtl::Buffer plekw_;
632    bool plekw_own_ = false;
633    mtl::Arg kw_arg() { return plekw_own_ ? mtl::Arg::B(plekw_) : mtl::Arg::B(W_, T("blk.1.ple_conv1d.weight").offset); }
634    const uint16_t* kw_host() {
635        return plekw_own_ ? plekw_.as<uint16_t>()
636                          : (const uint16_t*) ((const uint8_t*) W_.ptr + T("blk.1.ple_conv1d.weight").offset);
637    }
638    bool mrope_on() const { return g_mrope_host != nullptr; }
639    void mrope_sync(int64_t c0, int64_t n) {
640        if (!mrope_on()) return;
641        const int64_t a = std::max<int64_t>(0, c0 & ~(int64_t) 3), b = std::min<int64_t>(max_cells_, c0 + n);
642        if (b > a) std::memcpy(mrope_.as<int32_t>() + a * 3, g_mrope_host + a * 3, (size_t) (b - a) * 12);
643    }
644    mtl::Constants qsa_c() const { return mrope_on() ? mtl::Constants().b(24, true) : mtl::Constants(); }
645    std::string qsa_k() const { return mrope_on() ? "qsa_prep#mrope" : "qsa_prep"; }
646    int m5_layout_ = -1;   // the M5's matmul2d layout (coop_k4), asked once: the M4's tiles differ
647    bool m5_layout() { if (m5_layout_ < 0) m5_layout_ = coop_k4() ? 1 : 0; return m5_layout_ == 1; }
648    bool pc_setup(int C);
649    void pc_kprof(const std::vector<mtl::Dispatch>& ds, int nT, int64_t pos0);
650    // the chunk's host rows (the embedding rows and the PLE table rows): computed on a thread while the GPU runs the previous
651    // chunk (STRATA_METAL_PROMPT_HOSTPIPE=0 computes them inline before each chunk)
652    struct PcHost {
653        int nT = 0;
654        int64_t pos0 = -1;
655        std::vector<float> emb, ple;
656        double ms = 0, ms_emb = 0;
657        bool ok = true;
658        std::string err;
659    };
660    bool pc_host_rows(const int64_t* tokens, int nT, int64_t pos0, const int32_t prev_in[2], PcHost& out);
661    std::future<PcHost> pc_next_;
662    void pc_drain() { if (pc_next_.valid()) pc_next_.wait(); }
663    bool pc_chunk(const int64_t* tokens, int nT, int64_t pos0, std::string& err, const int64_t* next_tokens = nullptr, int next_nT = 0);
664    // the draft round in one command buffer (msl/mtp_chain.metal): STRATA_METAL_MTP_CHAIN=0 runs a command buffer
665    // per step with the host's pick and embedding (as before)
666    int lchain_ = -1;
667    bool chain_ = false;
668    mtl::Buffer dout_, dprob_, posv_, dmap_;
669};
670
671namespace {
672// A repack (metal_repack.py: <file>.repack.lock) or setup's model preparation (.preparing.lock) beside the GPU's file holds a lock
673// with its pid.  The repack and the pack move 100+ GB through the disk and one holds up to 20 GB of memory: an engine of 70-90 GB
674// beside them is what froze the 128 GB M5 Max twice (watchdog panics, 2026-10-13).  Returns the pid of a live one, else 0.
675// STRATA_METAL_IGNORE_REPACK=1 starts anyway (your choice).
676long repack_pid_running(const std::string& model_file) {
677    namespace fs = std::filesystem;
678    std::error_code ec;
679    const fs::path dir = fs::path(model_file).parent_path().empty() ? fs::path(".") : fs::path(model_file).parent_path();
680    for (const auto& e : fs::directory_iterator(dir, ec)) {
681        const std::string n = e.path().filename().string();
682        const bool lock = n == ".preparing.lock" || (n.size() > 12 && n.compare(n.size() - 12, 12, ".repack.lock") == 0);
683        if (!lock) continue;
684        std::FILE* f = std::fopen(e.path().string().c_str(), "r");
685        long pid = 0;
686        if (f) { if (std::fscanf(f, "%ld", &pid) != 1) pid = 0; std::fclose(f); }
687        if (pid > 0 && pid != (long) getpid() && (kill((pid_t) pid, 0) == 0 || errno == EPERM)) return pid;
688    }
689    return 0;
690}
691}  // namespace
692
693bool Window::init(const strata::core::ModelGeometry& g, strata::core::SessionState& ss, const std::string& shard1,
694                  int max_t, int64_t max_cells, std::string& err) {
695    ss_ = &ss;
696    main_ss_ = &ss;
697    max_t_ = std::min(max_t, MAXT);
698    max_cells_ = max_cells;
699    // The 19 fields the CUDA guard compares with the compiled shape (strata::geometry_unsupported, + rms_eps); the two it leaves free are
700    // checked here: the routed experts per layer (the router kernels take NL = 16, i.e. 512, and 8, i.e. 256 for the expert-pruned
701    // Coder) and the experts per token (the kernels are built for TOPK).
702    const bool experts_ok = g.n_expert == NEXP || (NEXP == 512 && g.n_expert == 256);
703    if (!strata::geometry_unsupported(g).empty() || !experts_ok || g.n_expert_used != TOPK) {
704        err = "metal window: the geometry differs from Qwen3.8-Flash-Next's";
705        return false;
706    }
707    nexp_ = (int) g.n_expert;   // 512, or 256 (the expert-pruned Coder); the routers' logits rows keep a 512-float stride either way
708    eps_ = 1e-6f;
709    const double t0 = now_ms();
710    if (const long rp = repack_pid_running(shard1); rp > 0 && !(std::getenv("STRATA_METAL_IGNORE_REPACK") && std::string(std::getenv("STRATA_METAL_IGNORE_REPACK")) == "1")) {
711        err = "metal window: a model repack or setup's preparation is running here (pid " + std::to_string(rp) + "): the engine is not started "
712              "beside it (it froze a 128 GB Mac twice); wait for it to finish, or set STRATA_METAL_IGNORE_REPACK=1";
713        return false;
714    }
715    if (!f_.open(shard1, err)) return false;
716    cx_ = std::make_unique<mtl::Context>();
717    stream_ = ExpertStream::wanted(f_, *cx_);
718    g_f16_auto = f16_auto_for(f_.path, stream_);   // STRATA_METAL_F16 unset: a resident IQ3_S / Q2_0 pack takes the fp16 decode windows
719    if (stream_) {
720        // the model does not fit: the dense weights are read into memory below, the experts stream from the SSD
721        st_ = std::make_unique<ExpertStream>();
722        if (!st_->open(f_, err)) return false;
723    } else {
724        {   // read ahead the weights, not the n-gram table: in a Gyro file it is 28.8 GB in the middle of the one file, read by the host from
725            // the SSD a few rows at a time (src/ngram/ple_reader.cpp), and must not fill the page cache
726            const gguf::Tensor* ple = f_.find("per_layer_token_embd.weight");
727            if (ple == nullptr) {
728                madvise(f_.map, f_.map_bytes, MADV_WILLNEED);
729            } else {
730                const size_t page = 16384;
731                const size_t lo = (size_t) ple->offset / page * page, hi = ((size_t) (ple->offset + ple->bytes) + page - 1) / page * page;
732                if (lo > 0) madvise(f_.map, lo, MADV_WILLNEED);
733                if (hi < f_.map_bytes) madvise((uint8_t*) f_.map + hi, f_.map_bytes - hi, MADV_WILLNEED);
734            }
735        }
736        // the chunks of a model bigger than one Metal buffer overlap by the largest range bound at one offset: a tensor,
737        // or a layer's routed experts (gate, up and down, bound together at the first of them: moe_rebase)
738        size_t span = 0;
739        // (not the n-gram table: the host reads it from the SSD, the GPU never binds it - in a Gyro file it is 28.8 GB of the one file)
740        for (const auto& kv : f_.tensors)
741            if (kv.first != "per_layer_token_embd.weight") span = std::max<size_t>(span, kv.second.bytes);
742        for (int l = 0; l < G_NL; ++l) {
743            const std::string b = "blk." + std::to_string(l) + ".";
744            const gguf::Tensor *g = f_.find(b + "ffn_gate_exps.weight"), *u = f_.find(b + "ffn_up_exps.weight"),
745                               *d = f_.find(b + "ffn_down_exps.weight");
746            if (!g || !u || !d) continue;
747            const uint64_t lo = std::min({g->offset, u->offset, d->offset});
748            const uint64_t hi = std::max({g->offset + g->bytes, u->offset + u->bytes, d->offset + d->bytes});
749            span = std::max<size_t>(span, hi - lo);
750        }
751        W_ = cx_->wrap(f_.map, f_.map_bytes, span);
752        if (W_.handle == nullptr) { err = "metal window: cannot wrap " + shard1 + " as a Metal buffer"; return false; }
753    }
754    n_vocab_ = (int64_t) T("output.weight").shape[1];
755    if (const gguf::Tensor* e0 = f_.find("blk.0.ffn_gate_exps.weight")) gyro_dense_ = e0->type >= 144;
756    {
757        using namespace strata_metal;
758        auto cc = [&](const MslLib& L) { return cx_->compile(L.files, L.prelude); };
759        lib_ = cc(lib_core(metal_f16(), kq_down_prelude(f_)));
760        lgdn_ = cc(lib_gdn());
761        lqsa_ = cc(lib_qsa());
762        lsmp_ = cc(lib_sample());
763        lple_ = cc(lib_ple(engine_msl_dir()));
764    }
765
766    const int MAXC = (int) std::max<int64_t>(4096, (max_cells + 64) / 4 * 4 + 64), MB = MAXC / 4 + 2;
767    max_cells_ = MAXC;
768    auto A = [&](size_t bytes) { return cx_->alloc(bytes); };
769    R_ = A(4 * MAXT * HC * N); bo_ = A(4 * MAXT * N); inj_[0] = A(4 * MAXT * HC); inj_[1] = A(4 * MAXT * HC);
770    xn_ = A(4 * MAXT * HC * N); lo_ = A(4 * MAXT * LR); qkv_ = A(4 * MAXT * G_CONV); z_ = A(4 * MAXT * G_ZV);
771    al_ = A(4 * MAXT * G_HV); be_ = A(4 * MAXT * G_HV); yg_ = A(4 * MAXT * G_ZV); logits_ = A(4 * MAXT * 512);
772    ids_ = A(4 * MAXT * TOPK); wts_ = A(4 * MAXT * TOPK); plan_ = A(4 * P_INTS); h_ = A(4 * MAXT * TOPK * NFF);
773    ye_ = A(4 * MAXT * TOPK * N); gsh_ = A(4 * MAXT * NFF); ush_ = A(4 * MAXT * NFF); ysh_ = A(4 * MAXT * N);
774    sg_ = A(4 * MAXT * 4); qfull_ = A(4 * MAXT * G_QFULL); kcur_ = A(4 * MAXT * G_KV); vcur_ = A(4 * MAXT * G_KV);
775    iqr_ = A(4 * MAXT * G_IQR); ikr_ = A(4 * MAXT * G_ID); qcur_ = A(4 * MAXT * G_QOUT); qidx_ = A(4 * MAXT * G_IH * G_ID);
776    scores_ = A(4 * (size_t) MAXT * MB); qids_ = A(4 * MAXT * G_BUD); part_ = A(4 * (size_t) MAXT * G_QCHUNKS2 * G_QH * (G_QD + 2));
777    cs_ = A(8 * (size_t) (MAXC + 16) * 32); lm_ = A(4 * (size_t) MAXT * n_vocab_); apv_ = A(4 * MAXT * 120);
778    api_ = A(4 * MAXT * 120); tokout_ = A(4 * MAXT); emb_ = A(4 * MAXT * N); pkey_ = A(4 * MAXT * G_HCD);
779    pval_ = A(4 * MAXT * N);
780    // the GDN layers' window inputs, kept per layer so commit() can fold the accepted prefix into the state
781    qkvL_ = A(4 * (size_t) G_NGDN * MAXT * G_CONV); alL_ = A(4 * (size_t) G_NGDN * MAXT * G_HV); beL_ = A(4 * (size_t) G_NGDN * MAXT * G_HV);
782    zL_ = A(4 * (size_t) G_NGDN * MAXT * G_ZV); ydump_ = A(4 * MAXT * G_ZV);
783    keyn_ = A(4 * MAXT * G_HCD); qn_ = A(4 * MAXT * G_HCD); gated_ = A(4 * MAXT * G_HCD); normW_ = A(4 * MAXT * G_HCD);
784    mrope_ = A(12 * (size_t) (MAXC + 16));
785    bigs_ok_ = g_slot_cap > 0;
786    const size_t NSET = 1 + (size_t) std::max(0, g_slot_cap);
787    auto R256 = [](size_t b) { return (b + 255) / 256 * 256; };
788    st_gst_ = R256(GST_B); st_hist_ = R256(HIST_B); st_kq_ = R256((size_t) MAXC * G_QKV * G_QD);
789    st_sc_ = R256(2 * (size_t) MAXC * G_QKV * 4); st_tail_ = R256(TAIL_B); st_dead_ = R256(DEAD_B);
790    st_pooled_ = R256(4 * (size_t) MB * G_ID); st_ple_ = R256(PLEH_B);
791    // the set-0 view of a new buffer of `bytes` per set (or a plain buffer when there are no batch slots)
792    auto SV = [&](std::vector<mtl::Buffer>& bigs, size_t bytes, size_t stride, size_t per = 1, size_t which = 0) {
793        if (!bigs_ok_) { bigs.push_back(mtl::Buffer()); return A(bytes); }
794        if (which == 0) bigs.push_back(A(stride * per * NSET));
795        return view_of(bigs.back(), which * stride, bytes);
796    };
797    if (bigs_ok_) { pleBig_ = A(st_ple_ * NSET); pleHist_ = view_of(pleBig_, 0, PLEH_B); } else pleHist_ = A(PLEH_B);
798    rinfo_ = A(4 * (8 + 4 * MAXT));
799    auto act = [&](int n) {
800        Act a;
801        a.n = n;
802        a.b = A(4 * ((size_t) 4 * MAXT * n + (size_t) MAXT * n / 16) + (metal_f16() ? (size_t) 2 * 3 * MAXT * n : 0));
803        return a;
804    };
805    XA_ = act(N); XF_ = act(N); XY_ = act(G_ZV); XQ_ = act(G_QOUT); XH_ = act(NFF); XE_ = act(N);
806    if (metal_f16()) h16_ = A(2 * (size_t) MAXT * TOPK * NFF);
807    {   // Gyro (native_experts.txt v5 + hadamard.txt): the rotation's signs and the rotated gate/up input
808        const auto& hs = strata::kernels::cpu::hadamard_spec();
809        had_on_ = hs.any();
810        if (had_on_) {
811            had_block_ = hs.block;
812            if (had_block_ != 128) {
813                err = "metal window: the pack's Hadamard block is " + std::to_string(had_block_) + "; the Metal rotation takes 128";
814                return false;
815            }
816            XR_ = A(4 * MAXT * N);
817            auto upload = [&](int w, mtl::Buffer& b) {
818                if (const float* sg = strata::kernels::cpu::hadamard_signs(w)) {
819                    b = A(4 * (size_t) w);
820                    std::memcpy(b.ptr, sg, 4 * (size_t) w);
821                }
822            };
823            upload(N, hsx_);
824            upload(NFF, hsh_);
825            std::fprintf(stderr, "strata metal: Hadamard-folded experts (block %d): the gate/up and down inputs are rotated on the GPU\n",
826                         had_block_);
827        }
828    }
829    // RoPE: cos/sin [pos][32] for the first 64 dims, NEOX pairs (i, i + 32), in double as build_rope_table
830    const double base = f_.meta_num.count("qwen4exp.rope.freq_base") ? f_.meta_num["qwen4exp.rope.freq_base"] : 1e7;
831    for (int p = 0; p < MAXC + 16; ++p)
832        for (int i = 0; i < 32; ++i) {
833            const double th = (double) p * std::pow(base, -2.0 * i / 64.0);
834            cs_.as<float>()[(p * 32 + i) * 2] = (float) std::cos(th);
835            cs_.as<float>()[(p * 32 + i) * 2 + 1] = (float) std::sin(th);
836        }
837    for (int t = 0; t < MAXT; ++t)
838        for (int c = 0; c < G_BUD; ++c) qids_.as<int>()[t * G_BUD + c] = c;
839    for (int l = 0; l < G_NL; ++l) {
840        if (l % G_QI != G_QI - 1) {
841            gst_.push_back(SV(gstBig_, GST_B, st_gst_));
842            ghist_[0].push_back(SV(hbBig_, HIST_B, st_hist_, 2, 0));   // [set][parity]: the two parities side by side
843            ghist_[1].push_back(SV(hbBig_, HIST_B, st_hist_, 2, 1));
844        } else {
845            kq_.push_back(SV(kqBig_, (size_t) MAXC * G_QKV * G_QD, st_kq_));
846            vq_.push_back(SV(vqBig_, (size_t) MAXC * G_QKV * G_QD, st_kq_));
847            ksc_.push_back(SV(kscBig_, 2 * (size_t) MAXC * G_QKV * 4, st_sc_));
848            vsc_.push_back(SV(vscBig_, 2 * (size_t) MAXC * G_QKV * 4, st_sc_));
849            tail_.push_back(SV(tailBig_, TAIL_B, st_tail_));
850            dead_.push_back(SV(deadBig_, DEAD_B, st_dead_));
851            pooled_.push_back(SV(pooledBig_, 4 * (size_t) MB * G_ID, st_pooled_));
852        }
853    }
854    bind_session(ss);
855    // ---- the HC read in Q8_0 (the owner's default on Metal, as STRATA_HC_Q8 on gfx12): the BF16 down / up / inject
856    // matrices quantized once at load (ggml's q8_0 rule, ref_quant), read by gr_down_q8 / gr_up_q8
857    {
858        const char* e = std::getenv("STRATA_HC_Q8");
859        hc_q8_ = !(e && std::string(e) == "0");
860    }
861    {
862        const double tq = now_ms();
863        size_t tot = 0;
864        std::vector<std::string> names;
865        for (const auto& kv : f_.tensors) {
866            const gguf::Tensor& x = kv.second;
867            // BF16 (when the Q8_0 read is on) and, whatever the setting, the Gyro file's Q6_K / IQ4_NL ones: the decode window's
868            // hyper-connection kernels read BF16 or Q8_0 only
869            const bool conv = (x.type == ref::BF16 && hc_q8_) || x.type == ref::Q6_K || x.type == ref::IQ4_NL;
870            if (!conv || x.name.find("hc_") == std::string::npos || x.name.find("_norm") != std::string::npos) continue;
871            uint64_t ne = 1;
872            for (uint64_t d : x.shape) ne *= d;
873            q8off_[x.name] = tot;
874            names.push_back(x.name);
875            tot += ne / 32 * 34;
876        }
877        Q8_ = cx_->alloc((tot + 4095) / 4096 * 4096 + 4096);   // + a page: a file with Q8_0 HC already has no copies
878        std::vector<std::thread> th;
879        const unsigned nth = std::max(1u, std::min(16u, std::thread::hardware_concurrency()));
880        for (unsigned k = 0; k < nth; ++k)
881            th.emplace_back([&, k] {
882                std::vector<float> tmp;
883                std::vector<uint8_t> raw;
884                for (size_t i = k; i < names.size(); i += nth) {
885                    const gguf::Tensor& x = *f_.find(names[i]);
886                    uint64_t ne = 1;
887                    for (uint64_t d : x.shape) ne *= d;
888                    tmp.resize(ne);
889                    const uint8_t* src = (const uint8_t*) f_.map + x.offset;
890                    if (stream_) {   // F_NOCACHE reads: the page cache is kept for the arena
891                        raw.resize(x.bytes);
892                        if (!st_->read(raw.data(), x.bytes, x.offset)) { std::fprintf(stderr, "strata metal: read failed\n"); std::exit(6); }
893                        src = raw.data();
894                    }
895                    ref::dequant(x.type, src, tmp.data(), ne);
896                    // a Q6_K / IQ4_NL matrix (Gyro) goes through BF16 first: the form the pack gives the CUDA engine
897                    // (tools/iq_pack.py --compat-bf16), so the Q8_0 copy below is made from the same numbers
898                    if (x.type != ref::BF16)
899                        for (uint64_t i = 0; i < ne; ++i) tmp[i] = ref::bf16_to_f32(ref::f32_to_bf16(tmp[i]));
900                    ref::quantize_q8_0(tmp.data(), ne, Q8_.as<uint8_t>() + q8off_[names[i]]);
901                }
902            });
903        for (auto& x : th) x.join();
904        std::fprintf(stderr, "strata metal: HC read in Q8_0 (STRATA_HC_Q8=0: BF16): %zu matrices, %.0f MB, made in %.0f ms\n",
905                     names.size(), tot / 1e6, now_ms() - tq);
906    }
907    if (stream_) {
908        std::vector<std::string> skip;   // the BF16 originals of the Q8_0 HC copies are not read again
909        if (hc_q8_)
910            for (const auto& kv : q8off_) skip.push_back(kv.first);
911        if (!st_->load_dense(f_, *cx_, skip, W_, err)) return false;
912        const char* e = std::getenv("STRATA_METAL_PREFETCH");
913        st_pred_ = !(e && std::atoi(e) <= 0);
914        if (st_pred_) predL_ = A(4 * (size_t) G_NL * MAXT * 512);
915        if (st_pred_ && st_->ahead2() > 0) predL2_ = A(4 * (size_t) G_NL * MAXT * 512);
916        if (nexp_ < NEXP) {   // the predictor reads 512 logits a token: the columns past the trunk's experts must never win
917            for (mtl::Buffer* pb : {&predL_, &predL2_})
918                if (pb->ptr)
919                    for (size_t r = 0; r < (size_t) G_NL * MAXT; ++r)
920                        for (int c = nexp_; c < NEXP; ++c) pb->as<float>()[r * 512 + c] = -INFINITY;
921        }
922    }
923    ple_on_ = ss.ple.ready() && f_.find("blk.1.ple_key.weight") != nullptr;
924    if (ple_on_ && T("blk.1.ple_conv1d.weight").type == ref::F32) {
925        const gguf::Tensor& k = T("blk.1.ple_conv1d.weight");
926        const size_t ne = k.bytes / 4;
927        plekw_ = cx_->alloc((ne * 2 + 4095) / 4096 * 4096);
928        const float* src = (const float*) ((const uint8_t*) W_.ptr + k.offset);
929        uint16_t* dst = plekw_.as<uint16_t>();
930        for (size_t i = 0; i < ne; ++i) dst[i] = ref::f32_to_f16(src[i]);
931        plekw_own_ = true;
932    }
933    ple_hist_.assign((size_t) strata::kernels::NG_HIST * strata::kernels::NG_HC_DIM, 0.0f);
934    last_norm_.assign((size_t) MAXT * strata::kernels::NG_HC_DIM, 0.0f);
935    std::fprintf(stderr, "strata metal: decode window on %s: %s %s (%.1f GB), %d cells, PLE %s, ready in %.0f ms\n",
936                 cx_->device_name().c_str(), shard1.c_str(), stream_ ? "streamed from the SSD (experts)" : "wrapped",
937                 f_.file_bytes / 1e9, MAXC, ple_on_ ? "on" : "OFF", now_ms() - t0);
938    return true;
939}
940
941void Window::gemv(std::vector<mtl::Dispatch>& ds, const gguf::Tensor& t, const Act& x, const mtl::Buffer& y,
942                  size_t y_stride, int ntok, size_t y_off, const mtl::Buffer* wb) {
943    const int n_in = (int) t.shape[0], n_out = t.shape.size() > 1 ? (int) t.shape[1] : 1;
944    const int ty = t.type;
945    int L = 16, Rr = 1, S = 4, K = 1;
946    if (n_in >= 6144) { L = 32; Rr = 1; S = 8; K = 2; }
947    else if (n_in == 640) { L = 8; Rr = 1; S = 4; K = 1; }
948    else if (n_out <= 640 || ty == ref::Q2_0 || ty == ref::BF16) { L = 32; Rr = 1; S = 4; K = 1; }
949    static const bool gyro_tiles = !(std::getenv("STRATA_METAL_GYRO_TILES") && std::string(std::getenv("STRATA_METAL_GYRO_TILES")) == "0");   // off: the A/B arm
950    if (gyro_dense_ && gyro_tiles && ntok >= 2) {
951        // Gyro's dense weights are Q5_K / Q6_K / Q8_0 (3.6 GB a token).  gemv_parity --one on the M4, 2 tokens: Q5_K 2560->10240
952        // 261 us with 16,1,4,1 against 210 with 2,1,4,1 (-20%), 2560->6144 158 -> 129, 6144->2560 162 -> 139, 2560->12288
953        // 313 -> 247, and the shared down Q8_0 640->2560 36 -> 19 us with 4,2,4,1.  (The tile changes the order of the lane sums.)
954        if (ty == ref::Q5_K && n_in == 2560 && n_out >= 6144) { L = 2; Rr = 1; S = 4; K = 1; }
955        else if (ty == ref::Q5_K && n_in == 6144) { L = 2; Rr = 1; S = 4; K = 1; }
956        else if (ty == ref::Q8_0 && n_in == 640) { L = 4; Rr = 2; S = 4; K = 1; }
957    }
958    {
959        // windows of several tokens: NR rows a lane share each x load (the window's cost is its x traffic).  The sums
960        // run in the same order for any NR, so the answers do not change.  STRATA_METAL_GEMV_NR (1, 2): the tile.
961        static const int nr_env = [] { const char* e = std::getenv("STRATA_METAL_GEMV_NR"); return e ? std::atoi(e) : 1; }();
962        if (ntok > 1 && nr_env == 2 && n_out >= 2048) {
963            if (S == 8 && K == 2) { S = 4; K = 2; }
964            if (S == 8 && K == 1) S = 4;
965            if (K == 1 || (L == 32 && K == 2)) Rr = 2;
966        }
967    }
968    const int k16 = f16_enc_ && x.n == n_in ? x16_kind(ty) : -1;
969    const bool f16 = k16 >= 0 && gemv16_tile(L, Rr, S, K);
970    const std::string fn = std::string(f16 ? "gemv16_" : "gemv_") + std::to_string(ty) + "_" + std::to_string(L) + "_" +
971                           std::to_string(Rr) + "_" + std::to_string(S) + "_" + std::to_string(K);
972    const mtl::Pipeline* p = P(lib_, fn, mtl::Constants().i(0, ntok), fn + "#" + std::to_string(ntok));
973    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,
974               (uint32_t) y_stride};
975    mtl::Dispatch d;
976    d.p = p;
977    d.args = {mtl::Arg::B(wb ? *wb : W_, t.offset),
978              f16 ? mtl::Arg::B(x.b, x.x16_bytes() + (size_t) k16 * 2 * MAXT * n_in) : mtl::Arg::B(x.b, x.plane_bytes() * xkind(ty)),
979              mtl::Arg::B(x.b, x.plane_bytes() * 4), mtl::Arg::B(y, y_off), mtl::Arg::V(a)};
980    const int rpt = (S / K) * (32 / L) * Rr;
981    d.grid[0] = (n_out + rpt - 1) / rpt;
982    d.tg[0] = S * 32;
983    push(ds, d);
984}
985
986void Window::xprep(std::vector<mtl::Dispatch>& ds, const mtl::Buffer& x, const Act& out, int n) {
987    mtl::Dispatch d;
988    d.p = P(lib_, "xprep", x16c(), x16k("xprep"));
989    const uint32_t nn = n, nt = MAXT;
990    d.args = {mtl::Arg::B(x), mtl::Arg::B(out.b), mtl::Arg::V(nn), mtl::Arg::V(nt)};
991    d.tg[0] = 256;
992    d.grid[0] = (n / 16 * MAXT + 255) / 256;
993    push(ds, d);
994}
995
996// the hyper-connection read (gr.metal, 3 dispatches): the previous sublayer's write folded in when `apply`
997void Window::gr_read(std::vector<mtl::Dispatch>& ds, const std::string& pre, bool apply, const Act& out, bool final_,
998                     int ntok) {
999    const gguf::Tensor& tn = T(pre + "_norm.weight");
1000    const gguf::Tensor& tdn = T(pre + "_down.weight");
1001    const gguf::Tensor& tup = T(pre + "_up.weight");
1002    const gguf::Tensor& tin = final_ ? tdn : T(pre + "_inject.weight");
1003    GrArgs a{N, HC, LR, (uint32_t) ntok, apply ? 1u : 0u, eps_};
1004    mtl::Dispatch d1;
1005    d1.p = P(lib_, k_norm(), {}, k_norm());
1006    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_),
1007               mtl::Arg::V(a)};
1008    d1.grid[0] = HC;
1009    d1.grid[1] = ntok;
1010    d1.tg[0] = 256;
1011    push(ds, d1);
1012    // each matrix: its load-time Q8_0 copy (q8off_), else the file's own tensor (Unsloth's are Q8_0 already, their
1013    // inject rows F32)
1014    auto src = [&](const gguf::Tensor& t) -> std::pair<const mtl::Buffer*, size_t> {
1015        auto it = q8off_.find(t.name);
1016        return it != q8off_.end() ? std::make_pair(&Q8_, it->second) : std::make_pair(&W_, (size_t) t.offset);
1017    };
1018    auto is_q8 = [&](const gguf::Tensor& t) { return q8off_.count(t.name) || t.type == ref::Q8_0; };
1019    const auto [bd, od] = src(tdn);
1020    const auto [bi, oi] = src(tin);
1021    const auto [bu, ou] = src(tup);
1022    const bool q8 = is_q8(tdn) && is_q8(tup);
1023    const bool injf = q8 && !final_ && !q8off_.count(tin.name) && tin.type == ref::F32;
1024    mtl::Dispatch d2;
1025    static const bool hcld = std::getenv("STRATA_METAL_HCLD") && std::string(std::getenv("STRATA_METAL_HCLD")) == "1";   // OFF (measured -10.9%, 4 of 4 rounds, M5 Max UD-Q4_K_XL): the HC kernels' units loaded two or three at a time, bitwise the same; registers and occupancy, as the earlier gemvu / moeu unrolls
1026    const char* dn = injf ? (hcld ? "gr_downp_q8f_8_8" : "gr_down_q8f_8_8") : q8 ? (hcld ? "gr_downp_q8_8_8" : "gr_down_q8_8_8") : "gr_down_8_8";
1027    d2.p = P(lib_, dn, mtl::Constants().i(1, ntok), std::string(dn) + "#" + std::to_string(ntok));
1028    d2.args = {mtl::Arg::B(*bd, od), mtl::Arg::B(*bi, oi), mtl::Arg::B(xn_), mtl::Arg::B(lo_),
1029               mtl::Arg::B(inj_[1 - cur_inj_]), mtl::Arg::V(a)};
1030    d2.grid[0] = LR + HC;
1031    d2.tg[0] = 256;
1032    push(ds, d2);
1033    mtl::Dispatch d3;
1034    const char* up = q8 ? (hcld ? "gr_upp_q8" : "gr_up_q8") : "gr_up";
1035    d3.p = P(lib_, up, x16c(mtl::Constants().i(1, ntok)), x16k(std::string(up) + "#" + std::to_string(ntok)));
1036    GrArgs au = a;
1037    au.n_tok = MAXT;   // the plane stride of the prepared activation
1038    d3.args = {mtl::Arg::B(*bu, ou), mtl::Arg::B(lo_), mtl::Arg::B(xn_), mtl::Arg::B(out.b), mtl::Arg::V(au)};
1039    d3.grid[0] = N / 16;
1040    d3.tg[0] = 256;
1041    push(ds, d3);
1042    cur_inj_ = 1 - cur_inj_;
1043}
1044
1045namespace {
1046struct HadArgs { uint32_t width, x_stride, y_stride; float scale; uint32_t has_signs, pad; };   // quant.metal
1047}
1048// y = H (s * x) per block of 128 values of `rows` rows of `width` (x_off / y_off: byte offsets; f16: half rows, no signs)
1049void Window::had_rows(std::vector<mtl::Dispatch>& ds, int lib, const std::string& pfx, const mtl::Buffer& x, size_t x_off,
1050                      const mtl::Buffer& y, size_t y_off, int rows, int width, const mtl::Buffer* signs, bool f16) {
1051    HadArgs a{(uint32_t) width, (uint32_t) width, (uint32_t) width, 1.0f / std::sqrt((float) had_block_), signs ? 1u : 0u, 0u};
1052    const char* fn = f16 ? "had128_f16" : "had128_f32";
1053    mtl::Dispatch d;
1054    d.p = P(lib, fn, {}, pfx + fn);
1055    d.args = {mtl::Arg::B(x, x_off), mtl::Arg::B(y, y_off), mtl::Arg::B(signs ? *signs : x), mtl::Arg::V(a)};
1056    d.grid[0] = width / 128;
1057    d.grid[1] = rows;
1058    d.tg[0] = 128;
1059    push(ds, d);
1060}
1061
1062void Window::had_rows_ind(std::vector<mtl::Dispatch>& ds, int lib, const std::string& pfx, const mtl::Buffer& h,
1063                          const mtl::Buffer& meta) {
1064    HadArgs a{(uint32_t) NFF, (uint32_t) NFF, (uint32_t) NFF, 1.0f / std::sqrt((float) had_block_), hsh_.handle ? 1u : 0u, 0u};
1065    mtl::Dispatch d;
1066    d.p = P(lib, "had128_f16_rows", {}, pfx + "had128_f16_rows");
1067    d.args = {mtl::Arg::B(h), mtl::Arg::B(h), mtl::Arg::B(hsh_.handle ? hsh_ : h), mtl::Arg::V(a)};
1068    d.tg[0] = 128;
1069    d.indirect = &meta;
1070    d.ind_off = 8 * 4;   // (rows, 1, 1): the padded rows of the tiles
1071    push(ds, d);
1072}
1073
1074void Window::layer(std::vector<mtl::Dispatch>& ds, int l, int ntok, int64_t pos0) {
1075    const std::string b = "blk." + std::to_string(l) + ".";
1076    // ---- the mixer: layer 1's read after the PLE is not applied again (its pending write was applied before it)
1077    gr_read(ds, b + "hc_attn", l > 0 && !(l == 1 && ple_on_), XA_, false, ntok);
1078    if (l % G_QI != G_QI - 1) {
1079        const int gi = l - l / G_QI;
1080        // a one-token window commits in the step; a longer one leaves the state and commit() folds the kept prefix
1081        // from the inputs kept per layer (qkvL_ ...)
1082        const bool self_commit = ntok == 1;
1083        const uint32_t cm = self_commit ? 1u : 0u;
1084        const size_t o_qkv = (size_t) gi * MAXT * G_CONV * 4, o_ab = (size_t) gi * MAXT * G_HV * 4, o_z = (size_t) gi * MAXT * G_ZV * 4;
1085        gemv(ds, T(b + "attn_qkv.weight"), XA_, qkvL_, G_CONV, ntok, o_qkv);
1086        nb_ = true;
1087        gemv(ds, T(b + "attn_gate.weight"), XA_, zL_, G_ZV, ntok, o_z);
1088        nb_ = true;
1089        gemv(ds, T(b + "ssm_alpha.weight"), XA_, alL_, G_HV, ntok, o_ab);
1090        nb_ = true;
1091        gemv(ds, T(b + "ssm_beta.weight"), XA_, beL_, G_HV, ntok, o_ab);
1092        GdnArgs a{G_HK, G_HV, G_CONV, cm, eps_, fuse_ ? (uint32_t) (MAXT * G_ZV) : 0u};
1093        mtl::Dispatch d;
1094        d.p = P(lgdn_, "gdn_step", x16c(mtl::Constants().i(2, ntok)), x16k("gdn_step#" + std::to_string(ntok)));
1095        const int hp = hp_;
1096        if (rows_) {   // each row is a different sequence: its own state, parity and conv history (rinfo_), one grid row each
1097            d.p = P(lgdn_, "gdn_step", mtl::Constants().i(2, 1).b(31, true), "gdn_step#rows");
1098            GdnArgs ar{G_HK, G_HV, G_CONV, 1u, eps_, fuse_ ? (uint32_t) (MAXT * G_ZV) : 0u};
1099            d.args = {mtl::Arg::B(gstBig_[(size_t) gi]), mtl::Arg::B(hbBig_[(size_t) gi]), mtl::Arg::B(qkvL_, o_qkv),
1100                      mtl::Arg::B(alL_, o_ab), mtl::Arg::B(beL_, o_ab), mtl::Arg::B(zL_, o_z),
1101                      mtl::Arg::B(W_, T(b + "ssm_conv1d.weight").offset),
1102                      mtl::Arg::B(W_, T(b + "ssm_dt.bias").offset), mtl::Arg::B(W_, T(b + "ssm_a").offset),
1103                      mtl::Arg::B(W_, T(b + "ssm_norm.weight").offset), mtl::Arg::B(fuse_ ? XY_.b : yg_), mtl::Arg::V(ar),
1104                      mtl::Arg::B(hbBig_[(size_t) gi]), mtl::Arg::B(rinfo_)};
1105            d.grid[0] = G_HV;
1106            d.grid[1] = (uint32_t) rows_n_;
1107            d.tg[0] = 512;
1108            push(ds, d);
1109            if (!fuse_) xprep(ds, yg_, XY_, G_ZV);
1110            gemv(ds, T(b + "ssm_out.weight"), XY_, bo_, N, ntok);
1111        } else {
1112        d.args = {mtl::Arg::B(gst_[(size_t) gi]), mtl::Arg::B(ghist_[hp][(size_t) gi]), mtl::Arg::B(qkvL_, o_qkv),
1113                  mtl::Arg::B(alL_, o_ab), mtl::Arg::B(beL_, o_ab), mtl::Arg::B(zL_, o_z),
1114                  mtl::Arg::B(W_, T(b + "ssm_conv1d.weight").offset),
1115                  mtl::Arg::B(W_, T(b + "ssm_dt.bias").offset), mtl::Arg::B(W_, T(b + "ssm_a").offset),
1116                  mtl::Arg::B(W_, T(b + "ssm_norm.weight").offset), mtl::Arg::B(fuse_ ? XY_.b : yg_), mtl::Arg::V(a),
1117                  mtl::Arg::B(ghist_[1 - hp][(size_t) gi])};
1118        d.grid[0] = G_HV;
1119        d.tg[0] = 512;
1120        push(ds, d);
1121        (void) self_commit;   // the history ping-pong turns after the window (run) or at commit
1122        if (!fuse_) xprep(ds, yg_, XY_, G_ZV);
1123        gemv(ds, T(b + "ssm_out.weight"), XY_, bo_, N, ntok);
1124        }
1125    } else {
1126        const int qi = l / G_QI;
1127        gemv(ds, T(b + "attn_q.weight"), XA_, qfull_, G_QFULL, ntok);
1128        nb_ = true;
1129        gemv(ds, T(b + "attn_k.weight"), XA_, kcur_, G_KV, ntok);
1130        nb_ = true;
1131        gemv(ds, T(b + "attn_v.weight"), XA_, vcur_, G_KV, ntok);
1132        nb_ = true;
1133        gemv(ds, T(b + "indexer.q_proj.weight"), XA_, iqr_, G_IQR, ntok);
1134        nb_ = true;
1135        gemv(ds, T(b + "indexer.k_proj.weight"), XA_, ikr_, G_ID, ntok);
1136        QsaArgs a{(uint32_t) pos0, 0, (uint32_t) max_cells_, (uint32_t) ntok, eps_};
1137        mtl::Dispatch d;
1138        const bool rw = rows_;   // (batch slots: pos0 is the highest row's cell, the rows have their own in rinfo_)
1139        const mtl::Constants rc = mtl::Constants().b(30, true);
1140        const mtl::Buffer& KQ = rw ? kqBig_[(size_t) qi] : kq_[(size_t) qi];
1141        const mtl::Buffer& VQ = rw ? vqBig_[(size_t) qi] : vq_[(size_t) qi];
1142        const mtl::Buffer& KS = rw ? kscBig_[(size_t) qi] : ksc_[(size_t) qi];
1143        const mtl::Buffer& VS = rw ? vscBig_[(size_t) qi] : vsc_[(size_t) qi];
1144        const mtl::Buffer& TL = rw ? tailBig_[(size_t) qi] : tail_[(size_t) qi];
1145        const mtl::Buffer& DD = rw ? deadBig_[(size_t) qi] : dead_[(size_t) qi];
1146        const mtl::Buffer& PL = rw ? pooledBig_[(size_t) qi] : pooled_[(size_t) qi];
1147        d.p = rw ? P(lqsa_, "qsa_prep", rc, "qsa_prep#rows") : P(lqsa_, "qsa_prep", qsa_c(), qsa_k());
1148        d.args = {mtl::Arg::B(qfull_), mtl::Arg::B(kcur_), mtl::Arg::B(vcur_), mtl::Arg::B(iqr_), mtl::Arg::B(ikr_),
1149                  mtl::Arg::B(W_, T(b + "attn_q_norm.weight").offset), mtl::Arg::B(W_, T(b + "attn_k_norm.weight").offset),
1150                  mtl::Arg::B(W_, T(b + "indexer.q_norm.weight").offset), mtl::Arg::B(W_, T(b + "indexer.k_norm.weight").offset),
1151                  mtl::Arg::B(cs_), mtl::Arg::B(qcur_), mtl::Arg::B(qidx_), mtl::Arg::B(KQ),
1152                  mtl::Arg::B(VQ), mtl::Arg::B(KS), mtl::Arg::B(VS),
1153                  mtl::Arg::B(TL), mtl::Arg::B(DD), mtl::Arg::B(PL),
1154                  mtl::Arg::V(a), mtl::Arg::B(mrope_)};
1155        if (rw) d.args.push_back(mtl::Arg::B(rinfo_));
1156        d.grid[0] = G_QPREP;
1157        d.grid[1] = ntok;
1158        d.tg[0] = 256;
1159        push(ds, d);
1160        if (rec_) rec_->push_back({(int) ds.size() - 1, 0});
1161        mtl::Dispatch s;
1162        s.p = rw ? P(lqsa_, "qsa_score", rc, "qsa_score#rows") : P(lqsa_, "qsa_score", {}, "qsa_score");
1163        s.args = {mtl::Arg::B(qidx_), mtl::Arg::B(PL), mtl::Arg::B(DD), mtl::Arg::B(scores_),
1164                  mtl::Arg::V(a)};
1165        if (rw) s.args.push_back(mtl::Arg::B(rinfo_));
1166        s.grid[0] = (uint32_t) (((pos0 + ntok) / 4 + 1 + 7) / 8);
1167        s.grid[1] = ntok;
1168        s.tg[0] = 256;
1169        const bool sel = !(fuse_ && pos0 + ntok <= G_BUD);
1170        if (sel) {
1171            push(ds, s);
1172            if (rec_) rec_->push_back({(int) ds.size() - 1, 2});
1173        }
1174        mtl::Dispatch k;
1175        k.p = rw ? P(lqsa_, "qsa_topk2", rc, "qsa_topk#rows") : P(lqsa_, "qsa_topk2", {}, "qsa_topk");
1176        k.args = {mtl::Arg::B(scores_), mtl::Arg::B(qids_), mtl::Arg::V(a)};
1177        if (rw) k.args.push_back(mtl::Arg::B(rinfo_));
1178        k.grid[0] = ntok;
1179        k.tg[0] = 1024;
1180        if (sel) {
1181            push(ds, k);
1182            if (rec_) rec_->push_back({(int) ds.size() - 1, 0});
1183        }
1184        mtl::Dispatch at;
1185        at.p = rw ? P(lqsa_, "qsa_attn", rc, "qsa_attn#rows") : P(lqsa_, "qsa_attn", {}, "qsa_attn");
1186        at.args = {mtl::Arg::B(qcur_), mtl::Arg::B(KQ), mtl::Arg::B(VQ), mtl::Arg::B(KS),
1187                   mtl::Arg::B(VS), mtl::Arg::B(qids_), mtl::Arg::B(part_), mtl::Arg::V(a)};
1188        if (rw) at.args.push_back(mtl::Arg::B(rinfo_));
1189        at.grid[0] = G_QCHUNKS;
1190        at.grid[1] = G_QKV;
1191        at.grid[2] = ntok;
1192        at.tg[0] = 256;
1193        push(ds, at);
1194        if (rec_) rec_->push_back({(int) ds.size() - 1, 0});
1195        mtl::Dispatch m;
1196        m.p = rw ? P(lqsa_, "qsa_merge", rc, "qsa_merge#rows") : P(lqsa_, "qsa_merge", x16c(), x16k("qsa_merge"));
1197        QsaArgs am = a;
1198        am.n_tok = MAXT;   // the plane stride
1199        m.args = {mtl::Arg::B(part_), mtl::Arg::B(qfull_), mtl::Arg::B(XQ_.b), mtl::Arg::V(am)};
1200        if (rw) m.args.push_back(mtl::Arg::B(rinfo_));
1201        m.grid[0] = G_QH;
1202        m.grid[1] = ntok;
1203        m.tg[0] = 256;
1204        push(ds, m);
1205        if (rec_) rec_->push_back({(int) ds.size() - 1, 1});
1206        gemv(ds, T(b + "attn_output.weight"), XQ_, bo_, N, ntok);
1207    }
1208    // ---- the MoE
1209    gr_read(ds, b + "hc_ffn", true, XF_, false, ntok);
1210    const gguf::Tensor& trt = T(b + "ffn_gate_inp.weight");
1211    gemv(ds, trt, XF_, logits_, 512, ntok);
1212    nb_ = true;
1213    if (stream_ && st_pred_ && l + 1 < G_NL) {   // the next layer's routing guessed from this layer's FFN input
1214        nb_ = true;   // beside the router GEMV
1215        gemv(ds, T("blk." + std::to_string(l + 1) + ".ffn_gate_inp.weight"), XF_, predL_, 512, ntok,
1216             (size_t) l * MAXT * 512 * 4);
1217        if (predL2_.ptr && l + 2 < G_NL) {
1218            nb_ = true;
1219            gemv(ds, T("blk." + std::to_string(l + 2) + ".ffn_gate_inp.weight"), XF_, predL2_, 512, ntok,
1220                 (size_t) l * MAXT * 512 * 4);
1221        }
1222        nb_ = true;
1223    }
1224    gemv(ds, T(b + "ffn_gate_shexp.weight"), XF_, gsh_, NFF, ntok);
1225    nb_ = true;
1226    gemv(ds, T(b + "ffn_up_shexp.weight"), XF_, ush_, NFF, ntok);
1227    nb_ = true;
1228    gemv(ds, T(b + "ffn_gate_inp_shexp.weight"), XF_, sg_, 1, ntok);
1229    {
1230        MoeArgs a{};
1231        const gguf::Tensor &tg_ = T(b + "ffn_gate_exps.weight"), &tu = T(b + "ffn_up_exps.weight"),
1232                           &td = T(b + "ffn_down_exps.weight");
1233        a.gate_off = tg_.offset;
1234        a.up_off = tu.offset;
1235        a.down_off = td.offset;
1236        if (stream_) {   // offsets inside the expert's arena slot
1237            a.gate_off = 0;
1238            a.up_off = st_->up_in_slot(l);
1239            a.down_off = st_->down_in_slot(l);
1240        }
1241        const size_t ebase = moe_rebase(a.gate_off, a.up_off, a.down_off);
1242        a.gu_row = (uint32_t) ref::row_bytes(tg_.type, N);
1243        a.d_row = (uint32_t) ref::row_bytes(td.type, NFF);
1244        a.gu_stride = (uint64_t) a.gu_row * NFF;
1245        a.d_stride = (uint64_t) a.d_row * N;
1246        a.n_embd = N;
1247        a.n_ff = NFF;
1248        a.n_tok = ntok;
1249        a.topk = TOPK;
1250        a.n_expert = nexp_;
1251        const bool dq2 = td.type == ref::Q2_0;
1252        // the trellis gate/up: 16 lanes a row, 2 rows a lane (expert_parity --bench --sweep, M4, TQK6, 10 experts: 166.6 us a layer
1253        // against 174.5 for 32,2,4 and 196.8 for 32,1,4; also the fastest at 2 and 3 tokens)
1254        const bool tq_ = tg_.type >= 144;
1255        int gl = tq_ ? 16 : 32, gr = tq_ ? 2 : 1, gs = 4, ds_ = 4;
1256        // the down tile: Q2_0 8,1; else 4,2 - but on the M4 (no M5 layout) Q5_1 4,1 and Q8_0 8,1 (4,2 spills there:
1257        // 24-36 GB/s, mac-kern 513fc615)
1258        const bool m4 = !m5_layout();
1259        int dl = dq2 || (m4 && td.type == ref::Q8_0) ? 8 : 4,
1260            dr = dq2 || (m4 && (td.type == ref::Q8_0 || td.type == ref::Q5_1 || td.type == ref::Q5_0)) ? 1 : 2;
1261        {   // STRATA_METAL_MOE_GU=L,R,S / STRATA_METAL_MOE_DN=L,R,S (tile screens: lanes per row, rows per lane, simdgroups; an instantiated moe_gu_ / moe_down_ combination)
1262            static const auto parse = [](const char* name, int* o) {
1263                const char* e = std::getenv(name);
1264                return e && std::sscanf(e, "%d,%d,%d", &o[0], &o[1], &o[2]) == 3;
1265            };
1266            static int gu_o[3], dn_o[3];
1267            static const bool gu_e = parse("STRATA_METAL_MOE_GU", gu_o), dn_e = parse("STRATA_METAL_MOE_DN", dn_o);
1268            if (gu_e && !tq_) { gl = gu_o[0]; gr = gu_o[1]; gs = gu_o[2]; }
1269            if (dn_e && !dq2) { dl = dn_o[0]; dr = dn_o[1]; ds_ = dn_o[2]; }
1270        }
1271        const bool m16 = f16_enc_ && !stream_ && tg_.type == ref::Q2_0 && dq2 && !had_gu(l) && !had_dn(l);
1272        a.gx_gu = NFF / (gs * (32 / gl) * gr);
1273        a.gx_dn = N / (ds_ * (32 / dl) * dr);
1274        mtl::Dispatch r;
1275        r.p = P(lib_, "moe_route", {}, "moe_route");
1276        r.args = {mtl::Arg::B(logits_), mtl::Arg::B(ids_), mtl::Arg::B(wts_), mtl::Arg::B(plan_), mtl::Arg::V(a)};
1277        r.tg[0] = 512;
1278        push(ds, r);
1279        {
1280            GlueArgs ga{NFF, MAXT, N, TOPK};
1281            mtl::Dispatch d;
1282            d.p = P(lib_, "swiglu_prep", x16c(), x16k("swiglu_prep"));
1283            d.args = {mtl::Arg::B(gsh_), mtl::Arg::B(ush_), mtl::Arg::B(XH_.b), mtl::Arg::V(ga)};
1284            d.grid[0] = NFF / 16;
1285            d.grid[1] = ntok;
1286            d.tg[0] = 16;
1287            nb_ = true;
1288            push(ds, d);
1289        }
1290        const std::string gun = std::string(m16 ? "moe_gu16_" : "moe_gu_") + std::to_string(tg_.type) + "_" + std::to_string(gl) +
1291                                "_" + std::to_string(gr) + "_" + std::to_string(gs);
1292        const std::string dnn = std::string(m16 ? "moe_down16_" : "moe_down_") + std::to_string(dq2 ? 142 : td.type) + "_" +
1293                                std::to_string(dl) + "_" + std::to_string(dr) + "_" + std::to_string(ds_);
1294        mtl::Dispatch g;
1295        const mtl::Buffer& EW = stream_ ? st_->chunk(0) : W_;
1296        // function constant 23 (QUANT_CTAB): the i-quant grids from constant memory, no threadgroup copy (same values)
1297        const bool ct = metal_ctab();
1298        mtl::Constants ac = stream_ ? mtl::Constants().b(20, true) : mtl::Constants();
1299        ac.b(23, ct);
1300        const std::string ak = std::string(stream_ ? "#arena" : "") + (ct ? "#ct" : "");
1301        g.p = m16 ? P(lib_, gun, {}, gun) : P(lib_, gun, ac, gun + ak);
1302        const bool hg = had_gu(l), hd = had_dn(l);
1303        if (hg) had_rows(ds, lib_, "d:", XF_.b, 0, XR_, 0, ntok, N, hsx_.handle ? &hsx_ : nullptr, false);   // before the host's turn
1304        g.args = {mtl::Arg::B(EW, ebase), hg ? mtl::Arg::B(XR_) : mtl::Arg::B(XF_.b, XF_.plane_bytes() * xkind(tg_.type)), mtl::Arg::B(h_),
1305                  mtl::Arg::B(plan_), mtl::Arg::V(a), mtl::Arg::B(XF_.b, XF_.plane_bytes() * 4)};
1306        if (m16) {   // x from the half plane x * 4^-(i % 4), h also as half
1307            g.args[1] = mtl::Arg::B(XF_.b, XF_.x16_bytes() + (size_t) 2 * MAXT * N);
1308            g.args.push_back(mtl::Arg::B(h16_));
1309        }
1310        if (stream_)
1311            for (int c = -1; c < 3; ++c)
1312                g.args.push_back(c < 0 ? mtl::Arg::B(st_->smap(), (size_t) l * 512 * 4) : mtl::Arg::B(st_->chunk(c + 1)));
1313        g.tg[0] = 32 * gs;
1314        g.indirect = &plan_;
1315        g.ind_off = P_IGU * 4;
1316        if (cuts_) cuts_->push_back((int) ds.size());   // the host's turn: this layer's experts put in place
1317        push(ds, g);
1318        nb_ = true;
1319        gemv(ds, T(b + "ffn_down_shexp.weight"), XH_, ysh_, N, ntok);
1320        if (hd) had_rows(ds, lib_, "d:", h_, 0, h_, 0, ntok * TOPK, NFF, hsh_.handle ? &hsh_ : nullptr, false);   // H h, in place
1321        mtl::Dispatch dd;
1322        dd.p = m16 ? P(lib_, dnn, {}, dnn) : P(lib_, dnn, ac, dnn + ak);
1323        dd.args = {mtl::Arg::B(EW, ebase), mtl::Arg::B(h_), mtl::Arg::B(ye_), mtl::Arg::B(plan_), mtl::Arg::V(a), mtl::Arg::B(h_)};
1324        if (m16) dd.args = {mtl::Arg::B(EW, ebase), mtl::Arg::B(h16_), mtl::Arg::B(ye_), mtl::Arg::B(plan_), mtl::Arg::V(a)};
1325        if (stream_)
1326            for (int c = -1; c < 3; ++c)
1327                dd.args.push_back(c < 0 ? mtl::Arg::B(st_->smap(), (size_t) l * 512 * 4) : mtl::Arg::B(st_->chunk(c + 1)));
1328        dd.tg[0] = 32 * ds_;
1329        dd.indirect = &plan_;
1330        dd.ind_off = P_IDN * 4;
1331        push(ds, dd);
1332    }
1333    {
1334        GlueArgs a{N, (uint32_t) ntok, N, TOPK};
1335        mtl::Dispatch d;
1336        d.p = P(lib_, k_comb(), {}, k_comb());
1337        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)};
1338        d.grid[0] = (ntok * N + 255) / 256;
1339        d.tg[0] = 256;
1340        push(ds, d);
1341    }
1342    if (taps_on_ && tap_slot_[l] >= 0) tap_dispatch(ds, l, R_, bo_, inj_[cur_inj_], tap_dec_, ntok);   // DFlash2: the layers completed output (dflash2.inc)
1343}
1344
1345namespace {
1346float bf16f(uint16_t h) { uint32_t i = (uint32_t) h << 16; float f; std::memcpy(&f, &i, 4); return f; }
1347// ple.cu's gnorm_kernel: per stream, the squares rounded in f32, summed in double
1348void gnorm(const float* x, const float* w, float* y, int n_embd, int hc, float eps) {
1349    for (int c = 0; c < hc; ++c) {
1350        const float* xc = x + (size_t) c * n_embd;
1351        double acc = 0.0;
1352        for (int d = 0; d < n_embd; ++d) { const float sq = xc[d] * xc[d]; acc += (double) sq; }
1353        const float mean = (float) (acc / (double) n_embd);
1354        const float scale = 1.0f / std::sqrt(mean + eps);
1355        for (int d = 0; d < n_embd; ++d) y[(size_t) c * n_embd + d] = xc[d] * scale * w[(size_t) c * n_embd + d];
1356    }
1357}
1358}  // namespace
1359
1360// The PLE block (ple.hpp) for the window's T rows on the CPU, after layer 0 (its pending write applied to R): R +=
1361// gated + silu(conv); the normalized rows go to last_norm_ (the history advances at commit).
1362void Window::ple_cpu(int Tn) {
1363    using namespace strata::kernels;
1364    const int hc_dim = NG_HC_DIM;
1365    const float* nkey = (const float*) ((const uint8_t*) W_.ptr + T("blk.1.ple_norm_key.weight").offset);
1366    const float* nqry = (const float*) ((const uint8_t*) W_.ptr + T("blk.1.ple_norm_query.weight").offset);
1367    const float* nconv = (const float*) ((const uint8_t*) W_.ptr + T("blk.1.ple_norm_conv.weight").offset);
1368    const uint16_t* kw = kw_host();
1369    std::vector<float> key(hc_dim), query(hc_dim), gated(hc_dim), norm(hc_dim), hist = ple_hist_;
1370    for (int t = 0; t < Tn; ++t) {
1371        float* hidden = R_.as<float>() + (size_t) t * HC * N;
1372        gnorm(pkey_.as<float>() + (size_t) t * hc_dim, nkey, key.data(), N, HC, NG_RMS_EPS);
1373        gnorm(hidden, nqry, query.data(), N, HC, NG_RMS_EPS);
1374        const float* value = pval_.as<float>() + (size_t) t * N;
1375        float gate[HC];
1376        const float inv_sqrt_n = 1.0f / std::sqrt((float) N);
1377        for (int c = 0; c < HC; ++c) {
1378            double acc = 0.0;
1379            for (int d = 0; d < N; ++d) acc += (double) (key[(size_t) c * N + d] * query[(size_t) c * N + d]);
1380            const float s = (float) acc * inv_sqrt_n;
1381            const float mag = std::sqrt(std::max(std::fabs(s), 1e-6f));
1382            const float sgn = s > 0.0f ? 1.0f : (s < 0.0f ? -1.0f : 0.0f);
1383            gate[c] = 1.0f / (1.0f + std::exp(-(sgn * mag)));
1384        }
1385        for (int i = 0; i < hc_dim; ++i) gated[(size_t) i] = value[i % N] * gate[i / N];
1386        gnorm(gated.data(), nconv, norm.data(), N, HC, NG_RMS_EPS);
1387        for (int c = 0; c < hc_dim; ++c) {
1388            float acc = 0.0f;
1389            for (int k = 0; k < PLE_CONV_KERNEL; ++k) {
1390                const int row = NG_HIST - (PLE_CONV_KERNEL - 1 - k) * NGRAM_SIZE;
1391                const float v = row == NG_HIST ? norm[(size_t) c] : hist[(size_t) row + (size_t) NG_HIST * c];
1392                acc += ref::f16_to_f32(kw[k + PLE_CONV_KERNEL * c]) * v;
1393            }
1394            const float conv = acc / (1.0f + std::exp(-acc));
1395            hidden[c] = hidden[c] + gated[(size_t) c] + conv;
1396        }
1397        std::memcpy(last_norm_.data() + (size_t) t * hc_dim, norm.data(), (size_t) hc_dim * 4);
1398        // the next row of this window sees this one in its history
1399        for (int c = 0; c < hc_dim; ++c) {
1400            float* col = hist.data() + (size_t) c * NG_HIST;
1401            for (int r = 0; r + 1 < NG_HIST; ++r) col[r] = col[r + 1];
1402            col[NG_HIST - 1] = norm[(size_t) c];
1403        }
1404    }
1405}
1406
1407bool Window::run(int Tn, const int32_t* tokens, int64_t pos0, bool head, int32_t* out, std::string& err) {
1408    mtp_src_ = nullptr;
1409    if (Tn < 1 || Tn > MAXT || (head && Tn > max_t_)) { err = "metal window: window size out of range"; return false; }
1410    if (pos0 + Tn + 1 >= max_cells_) { err = "metal window: the window runs past the context"; return false; }
1411    const double t0 = now_ms();
1412    // ---- the embeddings (CPU dequant of the token rows straight into the shared buffer), broadcast to the streams
1413    const gguf::Tensor& te = T("token_embd.weight");
1414    const size_t rb = ref::row_bytes(te.type, N);
1415    for (int t = 0; t < Tn; ++t) {
1416        float* r = R_.as<float>() + (size_t) t * HC * N;
1417        if (const float* img = img_row(pos0 + t)) std::memcpy(r, img, (size_t) N * 4);
1418        else ref::dequant(te.type, (const uint8_t*) W_.ptr + te.offset + (size_t) tokens[t] * rb, r, N);
1419        for (int c = 1; c < HC; ++c) std::memcpy(r + (size_t) c * N, r, (size_t) N * 4);
1420    }
1421    // ---- the PLE rows (the table read is the shared host code's), projected on the GPU
1422    if (ple_on_) {
1423        strata::core::SessionState& ss = *ss_;
1424        uint32_t rows[MAXT * strata::kernels::PLE_N_HEADS];
1425        int32_t prev[2] = {ss.ple_prev[0], ss.ple_prev[1]};
1426        for (int t = 0; t < Tn; ++t) {
1427            if (rows_) { prev[0] = rows_ss_[t]->ple_prev[0]; prev[1] = rows_ss_[t]->ple_prev[1]; }   // (batch slots: each row its own sequence)
1428            strata::kernels::ngram_rows(&tokens[t], prev, 1, main_ss_->ple.consts, rows + t * strata::kernels::PLE_N_HEADS);
1429            if (!rows_) { prev[0] = prev[1]; prev[1] = tokens[t]; }
1430        }
1431        if (!main_ss_->ple.table->gather_batch(rows, (size_t) Tn, emb_.as<float>(), err)) return false;
1432    }
1433    tp_pre_ = now_ms();
1434    const bool sel = !(fuse_ && pos0 + Tn <= G_BUD);
1435    if (sel) qdirty_ = true;
1436    else if (qdirty_) {
1437        for (int t = 0; t < MAXT; ++t)
1438            for (int c = 0; c < G_BUD; ++c) qids_.as<int>()[t * G_BUD + c] = c;
1439        qdirty_ = false;
1440    }
1441    const int key = rows_ ? 1000000 + Tn * 2 + (sel ? 1 : 0) + (int) (pend_fold_ * 100)
1442                          : (((((Tn * 2 + (head ? 1 : 0)) * 2 + hp_) * (MAXT + 1)) + pend_fold_) * 2 + (sel ? 1 : 0)) * 2 +
1443                                (mrope_on() ? 1 : 0);
1444    mrope_sync(pos0, Tn);
1445    const int fold_n = pend_fold_;
1446    pend_fold_ = 0;
1447    win_head_ = head;
1448    auto hit = wcache_.find(key);
1449    if (hit != wcache_.end()) {
1450        // the same window shape: only the positions change (QSA's cells, the score grid)
1451        Cached& c = hit->second;
1452        for (const auto& [i, kind] : c.qsa) {
1453            mtl::Dispatch& d = c.ds[(size_t) i];
1454            QsaArgs a{(uint32_t) pos0, 0, (uint32_t) max_cells_, (uint32_t) (kind == 1 ? MAXT : Tn), eps_};
1455            // the QsaArgs: the dispatch's last inline argument (qsa_prep has the M-RoPE table bound after it)
1456            mtl::Arg* qa = nullptr;
1457            for (auto& g : d.args)
1458                if (!g.bytes.empty()) qa = &g;
1459            std::memcpy(qa->bytes.data(), &a, sizeof a);
1460            if (kind == 2) d.grid[0] = (uint32_t) (((pos0 + Tn) / 4 + 1 + 7) / 8);
1461        }
1462        seg_T_ = Tn;
1463        const double r0 = now_ms();
1464        last_gpu_ms_ = 1000.0 * run_ds(c);
1465        {
1466            static const int kt = std::getenv("STRATA_METAL_KPROF") ? std::atoi(std::getenv("STRATA_METAL_KPROF")) : 0;
1467            static int seen = 0;
1468            if (kt == Tn && head && ++seen == 20 && !stream_) kprof(c.ds, Tn);
1469            static const int st = std::getenv("STRATA_METAL_STEPPROF") ? std::atoi(std::getenv("STRATA_METAL_STEPPROF")) : 0;
1470            static int seen2 = 0;
1471            static const int st_at = std::getenv("STRATA_METAL_STEPPROF_AT") ? std::atoi(std::getenv("STRATA_METAL_STEPPROF_AT")) : 20;
1472            if (st == Tn && head && ++seen2 == st_at && !stream_) stepprof(c.ds, Tn);
1473        }
1474        tp_rg_ = now_ms() - r0;
1475        last_n_disp_ = (int) c.ds.size();
1476        return rows_ ? finish_rows(Tn, tokens, out, t0) : finish(Tn, tokens, pos0, head, out, t0);
1477    }
1478    if (stream_ && !st_->ready() && !stream_arena(err)) return false;
1479    Cached& cw = wcache_[key];
1480    rec_ = &cw.qsa;
1481    f16_enc_ = metal_f16() && head && !stream_ && !rows_;   // decode windows of one resident sequence: not the prompt's,
1482                                                            // not streaming, not batch slots
1483    cuts_ = stream_ ? &cw.cuts : nullptr;
1484    std::vector<mtl::Dispatch>& ds = cw.ds;
1485    nb_ = false;
1486    if (fold_n > 0) fold(ds, fold_n, 1 - hp_);   // the last window's commit (hp_ already turned)
1487    if (ple_on_) {
1488        xprep(ds, emb_, XE_, N);
1489        gemv(ds, T("blk.1.ple_key.weight"), XE_, pkey_, G_HCD, Tn);
1490        nb_ = true;
1491        gemv(ds, T("blk.1.ple_value.weight"), XE_, pval_, N, Tn);
1492    }
1493    cur_inj_ = 0;
1494    layer(ds, 0, Tn, pos0);
1495    if (ple_on_) {
1496        // layer 0's FFN write applied to R (gr_norm with apply writes R back; its xn is not used)
1497        const gguf::Tensor& tn = T("blk.1.hc_attn_norm.weight");
1498        GrArgs a{N, HC, LR, (uint32_t) Tn, 1u, eps_};
1499        mtl::Dispatch d1;
1500        d1.p = P(lib_, k_norm(), {}, k_norm());
1501        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_),
1502                   mtl::Arg::V(a)};
1503        d1.grid[0] = HC;
1504        d1.grid[1] = Tn;
1505        d1.tg[0] = 256;
1506        push(ds, d1);
1507        // the PLE block on the GPU (msl/ple.metal): norms, gate, conv, the residual update
1508        struct PleArgs { uint32_t n_embd, hc; float eps; } pa{N, HC, strata::kernels::NG_RMS_EPS};
1509        auto off = [&](const char* n) { return T(n).offset; };
1510        mtl::Dispatch g1, g2, g3, g4;
1511        g1.p = P(lple_, "ple_gnorm", {}, "ple_gnorm");
1512        g1.args = {mtl::Arg::B(pkey_), mtl::Arg::B(W_, off("blk.1.ple_norm_key.weight")), mtl::Arg::B(keyn_), mtl::Arg::V(pa)};
1513        g1.grid[0] = HC; g1.grid[1] = Tn; g1.tg[0] = 256;
1514        push(ds, g1);
1515        g2.p = g1.p;
1516        g2.args = {mtl::Arg::B(R_), mtl::Arg::B(W_, off("blk.1.ple_norm_query.weight")), mtl::Arg::B(qn_), mtl::Arg::V(pa)};
1517        g2.grid[0] = HC; g2.grid[1] = Tn; g2.tg[0] = 256;
1518        nb_ = true;   // beside the key norm
1519        push(ds, g2);
1520        g3.p = P(lple_, "ple_gate_norm", {}, "ple_gate_norm");
1521        g3.args = {mtl::Arg::B(keyn_), mtl::Arg::B(qn_), mtl::Arg::B(pval_), mtl::Arg::B(W_, off("blk.1.ple_norm_conv.weight")),
1522                   mtl::Arg::B(gated_), mtl::Arg::B(normW_), mtl::Arg::V(pa)};
1523        g3.grid[0] = HC; g3.grid[1] = Tn; g3.tg[0] = 256;
1524        push(ds, g3);
1525        g4.p = rows_ ? P(lple_, "ple_conv_add", mtl::Constants().b(32, true), "ple_conv_add#rows") : P(lple_, "ple_conv_add", {}, "ple_conv_add");
1526        g4.args = {mtl::Arg::B(rows_ ? pleBig_ : pleHist_), mtl::Arg::B(normW_), kw_arg(),
1527                   mtl::Arg::B(gated_), mtl::Arg::B(R_), mtl::Arg::V(pa)};
1528        if (rows_) g4.args.push_back(mtl::Arg::B(rinfo_));
1529        g4.grid[0] = HC * N / 256; g4.grid[1] = Tn; g4.tg[0] = 256;
1530        push(ds, g4);
1531    }
1532    for (int l = 1; l < G_NL; ++l) layer(ds, l, Tn, pos0);
1533    // ---- the final mixer and the head
1534    gr_read(ds, "output_hc", true, XA_, true, Tn);
1535    if (head) gemv(ds, T("output.weight"), XA_, lm_, (size_t) n_vocab_, Tn);
1536    if (head) {
1537        ArgArgs a{(uint32_t) n_vocab_, 120};
1538        mtl::Dispatch d1, d2;
1539        d1.p = P(lsmp_, "argmax_part", {}, "argmax_part");
1540        d1.args = {mtl::Arg::B(lm_), mtl::Arg::B(apv_), mtl::Arg::B(api_), mtl::Arg::V(a)};
1541        d1.grid[0] = 120;
1542        d1.grid[1] = Tn;
1543        d1.tg[0] = 256;
1544        push(ds, d1);
1545        d2.p = P(lsmp_, "argmax_final", {}, "argmax_final");
1546        d2.args = {mtl::Arg::B(apv_), mtl::Arg::B(api_), mtl::Arg::B(tokout_), mtl::Arg::V(a)};
1547        d2.grid[0] = Tn;
1548        d2.tg[0] = 256;
1549        push(ds, d2);
1550    }
1551    rec_ = nullptr;
1552    f16_enc_ = false;
1553    cuts_ = nullptr;
1554    seg_T_ = Tn;
1555    const double r0 = now_ms();
1556    last_gpu_ms_ = 1000.0 * run_ds(cw);
1557    tp_rg_ = now_ms() - r0;
1558    last_n_disp_ = (int) ds.size();
1559    return rows_ ? finish_rows(Tn, tokens, out, t0) : finish(Tn, tokens, pos0, head, out, t0);
1560}
1561
1562bool Window::run_rows(const int* rows, int S, const int32_t* tokens, const int64_t* pos, int32_t* out, std::string& err) {
1563    if (S < 1 || S > MAXT || S > max_t_) { err = "metal window: batch window size out of range"; return false; }
1564    if (active_ != 0) activate(0);
1565    uint32_t* ri = rinfo_.as<uint32_t>() + 8;
1566    int64_t maxpos = 0;
1567    for (int t = 0; t < S; ++t) {
1568        if (rows[t] < 0 || rows[t] >= n_slots()) { err = "metal window: a batch row names a slot that does not exist"; return false; }
1569        for (int u = 0; u < t; ++u)
1570            if (rows[u] == rows[t]) { err = "metal window: two rows of one batch window are the same slot"; return false; }
1571        const int set = rows[t] + 1;
1572        rows_ss_[t] = sets_[(size_t) set]->ss;
1573        rows_set_[t] = set;
1574        ri[4 * t] = (uint32_t) set;
1575        ri[4 * t + 1] = (uint32_t) pos[t];
1576        ri[4 * t + 2] = (uint32_t) sets_[(size_t) set]->hp;
1577        ri[4 * t + 3] = 0;
1578        maxpos = std::max<int64_t>(maxpos, pos[t]);
1579    }
1580    rows_ = true;
1581    rows_n_ = S;
1582    const bool ok = run(S, tokens, maxpos, true, out, err);
1583    rows_ = false;
1584    return ok;
1585}
1586
1587// the end of a window of batch slots: the picks, and each slot's commit (a one-token step committed its row: the other history
1588// parity is the committed one; the PLE history takes the row's normalized values; the session's token pair advances)
1589bool Window::finish_rows(int Tn, const int32_t* tokens, int32_t* out, double t0) {
1590    ++win_n_[Tn];
1591    win_ms_[Tn] += now_ms() - t0;
1592    win_gpu_[Tn] += last_gpu_ms_;
1593    for (int t = 0; t < Tn; ++t) out[t] = tokout_.as<int32_t>()[t];
1594    for (int t = 0; t < Tn; ++t) {
1595        SeqSet& s = *sets_[(size_t) rows_set_[t]];
1596        s.hp = 1 - s.hp;
1597        if (ple_on_) {
1598            const float* norm = normW_.as<float>() + (size_t) t * strata::kernels::NG_HC_DIM;
1599            for (int c = 0; c < strata::kernels::NG_HC_DIM; ++c) {
1600                float* col = s.pleHist.as<float>() + (size_t) c * strata::kernels::NG_HIST;
1601                for (int r = 0; r + 1 < strata::kernels::NG_HIST; ++r) col[r] = col[r + 1];
1602                col[strata::kernels::NG_HIST - 1] = norm[c];
1603            }
1604        }
1605        s.ss->ple_prev[0] = s.ss->ple_prev[1];
1606        s.ss->ple_prev[1] = tokens[t];
1607    }
1608    return true;
1609}
1610
1611double Window::run_ds(Cached& c) {
1612    if (!stream_) return cx_->run_graph(c.ds);
1613    return cx_->run_graph_seg(c.ds, c.cuts, [](void* u, int s) { ((Window*) u)->at_cut(s); }, this);
1614}
1615
1616namespace {
1617Window* g_stream_window = nullptr;
1618// What the process holds now, all of it (task_info TASK_VM_INFO): phys_footprint is its anonymous + wired + compressed memory
1619// (not the clean file pages it only maps), resident_size is the RSS (those pages too).  Bytes; 0 when the call fails.
1620struct ProcMem {
1621    double footprint = 0, rss = 0;
1622};
1623ProcMem proc_mem() {
1624    task_vm_info_data_t ti;
1625    mach_msg_type_number_t cnt = TASK_VM_INFO_COUNT;
1626    ProcMem r;
1627    if (task_info(mach_task_self(), TASK_VM_INFO, (task_info_t) &ti, &cnt) == KERN_SUCCESS) {
1628        r.footprint = (double) ti.phys_footprint;
1629        r.rss = (double) ti.resident_size;
1630    }
1631    return r;
1632}
1633void stream_atexit() {
1634    if (g_stream_window) g_stream_window->stream_report(stderr);
1635}
1636}  // namespace
1637
1638// The arena, once the rest is allocated (the MTP layer loads after init): what the GPU working set and the RAM leave
1639// with STRATA_METAL_KEEP_FREE_GB kept for macOS (default: 7 GB, or 15% of the RAM when that is more - the M5 Max
1640// froze with an 89 GB arena and 7 GB left beside a 50 GB n-gram table read through the file cache; arena_budget.h);
1641// STRATA_METAL_ARENA_GB sets it.
1642bool Window::stream_arena(std::string& err) {
1643    uint64_t phys = 0;
1644    size_t len = sizeof phys;
1645    sysctlbyname("hw.memsize", &phys, &len, nullptr, 0);
1646    const double gb = 1e9;
1647    if (!(std::getenv("STRATA_METAL_KEEP_HOST_WEIGHTS") && std::string(std::getenv("STRATA_METAL_KEEP_HOST_WEIGHTS")) == "1")) {
1648        const uint64_t g = strata::gpu::purge_device_allocations(32u << 20);
1649        std::fprintf(stderr, "strata metal stream: %.2f GB of the host code's device weight copies given back (unused by the "
1650                             "Metal window)\n", g / 1e9);
1651    }
1652    const double used = (double) cx_->allocated();
1653    // what macOS gives now without paging anything out (arena_avail: free, purgeable, the clean file cache; not other
1654    // programs' inactive memory, freed only by compressing or swapping it)
1655    auto avail_now = [&]() -> double {
1656        vm_statistics64_data_t vs;
1657        mach_msg_type_number_t cnt = HOST_VM_INFO64_COUNT;
1658        if (host_statistics64(mach_host_self(), HOST_VM_INFO64, (host_info64_t) &vs, &cnt) == KERN_SUCCESS) {
1659            const double pg = (double) vm_page_size;
1660            return arena_avail(vs.free_count * pg, vs.purgeable_count * pg, vs.inactive_count * pg, vs.speculative_count * pg,
1661                               vs.external_page_count * pg);
1662        }
1663        return (double) phys - (double) cx_->allocated();
1664    };
1665    ArenaMem am;   // arena_budget.h: the rule, testable
1666    am.phys = (double) phys;
1667    am.working_set = (double) cx_->recommended_working_set();
1668    am.allocated = used;
1669    const ProcMem pm0 = proc_mem();   // everything the process holds, not only the Metal buffers (the old 67% rule missed it)
1670    am.proc_footprint = pm0.footprint;
1671    {   // the file cache macOS keeps before it compresses anonymous memory (a 4-byte count of pages, read into a zeroed 8)
1672        unsigned long long pages = 0;
1673        size_t pl = sizeof pages;
1674        if (sysctlbyname("vm.vm_page_filecache_min", &pages, &pl, nullptr, 0) == 0) am.filecache_min = (double) pages * (double) vm_page_size;
1675    }
1676    am.available = avail_now();
1677    if (main_ss_ && main_ss_->ple.table && main_ss_->ple.table->mode() == strata::kernels::PleIo::Mmap)
1678        am.ple_mapped = (double) ss_->ple.table->rows() * 192.0;   // a row is at most 192 bytes (Q8_0 + its scale)
1679    if (const char* e = std::getenv("STRATA_METAL_KEEP_FREE_GB")) am.keep_gb = std::atof(e);
1680    if (const char* e = std::getenv("STRATA_METAL_ARENA_GB")) am.arena_gb = std::atof(e);
1681    if (const char* e = std::getenv("STRATA_METAL_LEAVE_SHARE")) am.leave_share = std::atof(e);   // for measuring; the default is kLeaveShare
1682    const double keep = arena_keep(am);
1683    const double avail = am.available;
1684    double budget = arena_budget(am);
1685    if (budget < 2 * gb) {
1686        std::fprintf(stderr, "strata metal stream: only %.1f GB left for the expert arena (the GPU working set %.1f GB, RAM %.1f GB, "
1687                             "%.1f GB allocated): expect a low hit rate\n", budget / gb, cx_->recommended_working_set() / gb,
1688                     phys / gb, used / gb);
1689        budget = std::max(budget, 1.0 * gb);
1690    }
1691    std::string prof;
1692    if (const char* e = std::getenv("STRATA_METAL_EXPERT_PROFILE")) prof = e;
1693    else prof = strata_metal::resource(nullptr, "data", STRATA_METAL_DATA_DEFAULT) + "/expert-profile.bin";
1694    std::fprintf(stderr, "strata metal stream: %.2f GB allocated before the arena (the process holds %.2f GB, %.2f GB resident); "
1695                         "RAM %.1f GB (%.1f GB available, %.1f GB kept for macOS), GPU working set %.1f GB\n", used / gb,
1696                 pm0.footprint / gb, pm0.rss / gb, phys / gb, avail / gb, keep / gb, cx_->recommended_working_set() / gb);
1697    {   // the planned total: arena + the Metal buffers (or the process's own count when it is more) + the n-gram table's
1698        // reserve, against the cap (arena_budget.h: footprint_cap)
1699        const FootprintPlan fp = footprint_plan(am, budget);
1700        std::fprintf(stderr, "strata metal stream: planned resident footprint %.1f GB = arena %.1f + %.1f held before it + %.1f "
1701                             "reserved for the n-gram table; cap %.1f GB = the lesser of the GPU working set %.1f GB and the RAM "
1702                             "%.1f GB less %.1f GB left to macOS and its file cache%s\n",
1703                     fp.total / gb, fp.arena / gb, fp.base / gb, fp.ple / gb, fp.cap / gb, cx_->recommended_working_set() / gb,
1704                     phys / gb, (am.phys - fp.cap) / gb,
1705                     am.arena_gb >= 0 && fp.over() ? " - STRATA_METAL_ARENA_GB is above the cap: kept as set (your choice), but "
1706                                                     "a Mac that runs short of memory can freeze (watchdog panics seen at 90+ GB "
1707                                                     "resident of 128)" : "");
1708    }
1709    const char* epg = std::getenv("STRATA_METAL_PROMPT_GEMM");
1710    const bool pg_on = !(epg && std::string(epg) == "0");
1711    bool minimal = false;   // the arena's least layout (the min slots) is not shrunk further: it goes ahead, filled in steps
1712    for (int tries = 0;; ++tries) {
1713        const double planned = budget;
1714        std::function<uint64_t()> recheck = [&]() -> uint64_t { return (uint64_t) arena_shrink(am, planned, avail_now()); };
1715        if (st_->make_arena(*cx_, (uint64_t) budget, prof, pg_on ? 576 : 64, err, minimal ? std::function<uint64_t()>() : recheck,
1716                            [&](uint64_t step) { return arena_grow(am, avail_now(), (double) step); }))
1717            break;
1718        if (st_->shrink_to() == 0 || tries == 4) return false;
1719        if ((double) st_->shrink_to() + 64.0 * (1 << 20) >= budget) minimal = true;   // no smaller layout than this one
1720        std::fprintf(stderr, "strata metal stream: less memory is free than when the arena was planned: %.1f -> %.1f GB\n",
1721                     budget / gb, st_->shrink_to() / gb);
1722        budget = (double) st_->shrink_to();
1723    }
1724    if (pg_on && !prompt_gemm_init(err)) return false;
1725    {   // what the process really holds now, against the plan and the cap (a number that disagrees is a bug in the count)
1726        const ProcMem pm1 = proc_mem();
1727        const double cap = footprint_cap(am);
1728        std::fprintf(stderr, "strata metal stream: resident footprint after the fill: the process holds %.1f GB (%.1f GB resident), "
1729                             "planned %.1f GB, cap %.1f GB%s\n", pm1.footprint / gb, pm1.rss / gb,
1730                     footprint_plan(am, (double) st_->arena_used_bytes()).total / gb, cap / gb,
1731                     pm1.footprint > cap ? " - OVER THE CAP" : "");
1732    }
1733    g_stream_window = this;
1734    std::atexit(stream_atexit);
1735    return true;
1736}
1737
1738void Window::logpos(int Tn, const int32_t* tokens, int64_t pos0, bool head) {
1739    static const char* path = std::getenv("STRATA_METAL_LOGPOS");
1740    if (path == nullptr || !head) return;
1741    if (logpos_ == nullptr) logpos_ = std::fopen(path, "ab");
1742    if (logpos_ == nullptr) return;
1743    if (lp_pend_ && Tn >= 1 && pos0 == lp_pos_ + 1) {
1744        const int32_t tgt = tokens[0];
1745        std::fprintf(logpos_, "%lld\t%d\t%.6f\t%d\t0\t0\t0\t0", (long long) (lp_pos_ - lp_first_), tgt,
1746                     (double) lp_row_[(size_t) tgt] - lp_lse_, lp_arg_);
1747        for (const auto& [v, id] : lp_top_) std::fprintf(logpos_, "\t%d:%.6f", id, (double) v - lp_lse_);
1748        std::fputc('\n', logpos_);
1749        std::fflush(logpos_);
1750    }
1751    lp_pend_ = false;
1752    if (Tn != 1) return;
1753    if (lp_first_ < 0) lp_first_ = pos0;
1754    const float* lg = lm_.as<float>();
1755    lp_row_.assign(lg, lg + n_vocab_);
1756    float mx = lg[0];
1757    int32_t am = 0;
1758    for (int64_t i = 1; i < n_vocab_; ++i) if (lg[i] > mx) { mx = lg[i]; am = (int32_t) i; }
1759    double s = 0.0;
1760    for (int64_t i = 0; i < n_vocab_; ++i) s += std::exp((double) (lg[i] - mx));
1761    lp_lse_ = (double) mx + std::log(s);
1762    lp_arg_ = am;
1763    lp_top_.clear();
1764    for (int64_t i = 0; i < n_vocab_; ++i) lp_top_.push_back({lg[i], (int32_t) i});
1765    std::partial_sort(lp_top_.begin(), lp_top_.begin() + 64, lp_top_.end(),
1766                      [](const auto& a, const auto& b) { return a.first > b.first || (a.first == b.first && a.second < b.second); });
1767    lp_top_.resize(64);
1768    lp_pos_ = pos0;
1769    lp_pend_ = true;
1770}
1771
1772void Window::kprof(const std::vector<mtl::Dispatch>& ds, int Tn) {
1773    std::map<const mtl::Pipeline*, std::string> pname;
1774    for (const auto& [k, v] : pcache_) pname[&v] = k.substr(0, k.find('#'));
1775    std::map<uint64_t, std::string> tname;
1776    for (const auto& [k, v] : f_.tensors) {
1777        std::string n = k;
1778        if (n.rfind("blk.", 0) == 0) n = n.substr(n.find('.', 4) + 1);
1779        tname[v.offset] = n;
1780    }
1781    std::map<size_t, std::string> q8name;
1782    for (const auto& [k, v] : q8off_) {
1783        std::string n = k;
1784        if (n.rfind("blk.", 0) == 0) n = n.substr(n.find('.', 4) + 1);
1785        q8name[v] = n;
1786    }
1787    std::map<std::string, std::vector<mtl::Dispatch>> by;
1788    for (const auto& d : ds) {
1789        std::string c = pname.count(d.p) ? pname[d.p] : "?";
1790        if (!d.args.empty() && d.args[0].buf == &W_ && tname.count(d.args[0].off) && c.rfind("moe_", 0) != 0)
1791            c += " " + tname[d.args[0].off];
1792        else if (!d.args.empty() && d.args[0].buf == &Q8_) c += " " + (q8name.count(d.args[0].off) ? q8name[d.args[0].off] : std::string("Q8"));
1793        mtl::Dispatch x = d;
1794        x.barrier = true;
1795        by[c].push_back(x);
1796    }
1797    auto med = [&](const std::vector<mtl::Dispatch>& v) {
1798        std::vector<double> t;
1799        for (int i = 0; i < 7; ++i) t.push_back(1000.0 * cx_->run_graph(v));
1800        std::sort(t.begin(), t.end());
1801        return t[3];
1802    };
1803    const double all = med(ds);
1804    std::vector<std::pair<double, std::string>> rows;
1805    double sum = 0;
1806    for (const auto& [c, v] : by) {
1807        const double m = med(v);
1808        sum += m;
1809        rows.push_back({m, c + " x" + std::to_string(v.size())});
1810    }
1811    std::sort(rows.rbegin(), rows.rend());
1812    std::fprintf(stderr, "strata metal kprof: window T%d, %zu dispatches, GPU %.3f ms; classes alone (serialized) sum %.3f ms:\n",
1813                 Tn, ds.size(), all, sum);
1814    for (const auto& [m, c] : rows) std::fprintf(stderr, "strata metal kprof: %8.3f ms %5.1f%%  %s\n", m, 100.0 * m / sum, c.c_str());
1815}
1816
1817void Window::stepprof(const std::vector<mtl::Dispatch>& ds, int Tn) {
1818    std::map<const mtl::Pipeline*, std::string> pname;
1819    for (const auto& [k, v] : pcache_) pname[&v] = k.substr(0, k.find('#'));
1820    std::map<uint64_t, const gguf::Tensor*> wt;       // W_ offset -> tensor
1821    for (const auto& [k, v] : f_.tensors) wt[v.offset] = &v;
1822    std::map<size_t, const gguf::Tensor*> qt;         // Q8_ offset -> tensor (the load-time Q8_0 copies)
1823    for (const auto& [k, v] : q8off_) { auto it = f_.tensors.find(k); if (it != f_.tensors.end()) qt[v] = &it->second; }
1824    auto role = [](const std::string& n) { return n.rfind("blk.", 0) == 0 ? n.substr(n.find('.', 4) + 1) : n; };
1825    const size_t n = ds.size();
1826    struct Info { std::string part; double wbytes = 0; };
1827    std::vector<Info> info(n);
1828    for (size_t i = 0; i < n; ++i) {
1829        const auto& d = ds[i];
1830        const std::string c = pname.count(d.p) ? pname[d.p] : "?";
1831        std::string part = "other", tn;
1832        double wb = 0;
1833        auto wbuf = [&](size_t a) -> const gguf::Tensor* {
1834            if (a >= d.args.size() || !d.args[a].buf) return nullptr;
1835            if (d.args[a].buf == &W_) { auto it = wt.find(d.args[a].off); return it == wt.end() ? nullptr : it->second; }
1836            if (d.args[a].buf == &Q8_) { auto it = qt.find(d.args[a].off); return it == qt.end() ? nullptr : it->second; }
1837            return nullptr;
1838        };
1839        const gguf::Tensor* t0 = wbuf(0);
1840        if (t0) tn = role(t0->name);
1841        auto tsize = [&](size_t a) -> double {
1842            const gguf::Tensor* t = wbuf(a);
1843            if (!t) return 0;
1844            if (d.args[a].buf == &Q8_) return (double) (t->shape[0] / 32 * 34) * (t->shape.size() > 1 ? (double) t->shape[1] : 1.0);
1845            return (double) t->bytes;
1846        };
1847        if (c.rfind("moe_gu", 0) == 0) part = "experts gate+up";
1848        else if (c.rfind("moe_down", 0) == 0) part = "experts down";
1849        else if (c.rfind("moe_route", 0) == 0) part = "router";
1850        else if (c.rfind("moe_combine", 0) == 0) part = "combine";
1851        else if (c.rfind("gr_", 0) == 0) { part = "hc"; wb = c.rfind("gr_down", 0) == 0 ? tsize(0) + tsize(1) : c.rfind("gr_up", 0) == 0 ? tsize(0) : 0; }
1852        else if (c.rfind("gdn_", 0) == 0) part = "gdn other";
1853        else if (c.rfind("qsa_", 0) == 0) part = "qsa other";
1854        else if (c.rfind("ple_", 0) == 0) part = "ple";
1855        else if (c.rfind("argmax", 0) == 0) part = "lm head (argmax)";
1856        else if (c.rfind("swiglu_prep", 0) == 0) part = "shared";
1857        else if (c.rfind("xprep", 0) == 0) part = "xprep";
1858        else if (c.rfind("gemv", 0) == 0 && t0) {
1859            wb = tsize(0);
1860            if (tn == "attn_qkv.weight" || tn == "attn_gate.weight" || tn == "ssm_alpha.weight" || tn == "ssm_beta.weight" || tn == "ssm_out.weight") part = "gdn dense";
1861            else if (tn == "attn_q.weight" || tn == "attn_k.weight" || tn == "attn_v.weight" || tn == "attn_output.weight" || tn.rfind("indexer.", 0) == 0) part = "qsa dense";
1862            else if (tn == "ffn_gate_inp.weight") part = "router";
1863            else if (tn.find("shexp") != std::string::npos) part = "shared";
1864            else if (tn == "output.weight" || t0->name == "output.weight") part = "lm head";
1865            else if (tn.find("ple_") != std::string::npos) part = "ple";
1866            else part = "gemv other " + tn;
1867        }
1868        info[i] = {part, wb};
1869    }
1870    // barrier groups
1871    std::vector<size_t> gs;
1872    for (size_t i = 0; i < n; ++i) if (i == 0 || ds[i].barrier) gs.push_back(i);
1873    gs.push_back(n);
1874    const size_t m = gs.size() - 1;
1875    // the route dispatches (one per layer): the prefix that ends right after one holds that layer's routed ids
1876    std::vector<size_t> routes;
1877    for (size_t i = 0; i < n; ++i)
1878        if (pname.count(ds[i].p) && pname[ds[i].p].rfind("moe_route", 0) == 0) routes.push_back(i);
1879    const int reps = std::getenv("STRATA_METAL_STEPPROF_REPS") ? std::max(1, std::atoi(std::getenv("STRATA_METAL_STEPPROF_REPS"))) : 5;
1880    std::fprintf(stderr, "strata metal stepprof: T%d, %zu dispatches in %zu barrier groups, %zu layers routed, %d reps per prefix\n", Tn, n, m, routes.size(), reps);
1881    for (int i = 0; i < 40; ++i) cx_->run_graph(ds);   // clocks up
1882    const double full = [&] { std::vector<double> t; for (int i = 0; i < 15; ++i) t.push_back(1000.0 * cx_->run_graph(ds)); std::sort(t.begin(), t.end()); return t[7]; }();
1883    std::vector<std::vector<double>> tp(m + 1);
1884    // the GPU heats up during the hundreds of runs: every pass is scaled by (the cool whole-window time / the whole window run at the start of that pass)
1885    for (int r = 0; r < reps; ++r) {
1886        double fr = 0;
1887        { std::vector<double> q; for (int i = 0; i < 5; ++i) q.push_back(1000.0 * cx_->run_graph(ds)); std::sort(q.begin(), q.end()); fr = q[2]; }
1888        const double sc = full / fr;
1889        tp[0].push_back(sc * 1000.0 * cx_->run_graph(ds, 0));
1890        for (size_t j = 1; j <= m; ++j) tp[j].push_back(sc * 1000.0 * cx_->run_graph(ds, gs[j]));
1891        std::fprintf(stderr, "strata metal stepprof: pass %d: whole window %.3f ms (cool %.3f, scale %.3f)\n", r, fr, full, sc);
1892    }
1893    std::vector<double> t(m + 1);
1894    for (size_t j = 0; j <= m; ++j) { std::sort(tp[j].begin(), tp[j].end()); t[j] = tp[j][tp[j].size() / 2]; }
1895    // distinct experts per layer
1896    std::vector<int> distinct;
1897    double expert_total = 0;
1898    for (size_t li = 0; li < routes.size(); ++li) {
1899        cx_->run_graph(ds, routes[li] + 1);
1900        std::set<int> u;
1901        for (int k = 0; k < Tn * TOPK; ++k) { const int v = ids_.as<int32_t>()[k]; if (v >= 0) u.insert(v); }
1902        distinct.push_back((int) u.size());
1903    }
1904    auto expert_bytes = [&](size_t layer, bool gu, bool dn) {
1905        const std::string L = "blk." + std::to_string(layer) + ".";
1906        auto eb = [&](const char* nm) { const gguf::Tensor* tt = f_.find(L + nm); return tt ? (double) tt->bytes / std::max(1, nexp_) : 0.0; };
1907        double b = 0;
1908        if (gu) b += eb("ffn_gate_exps.weight") + eb("ffn_up_exps.weight");
1909        if (dn) b += eb("ffn_down_exps.weight");
1910        return b * (layer < distinct.size() ? distinct[layer] : 0);
1911    };
1912    for (size_t li = 0; li < distinct.size(); ++li) expert_total += expert_bytes(li, true, true);
1913    // per group: time, part (the experts if the group has any, else the dispatch with the most weight bytes, else the first), bytes
1914    struct Row { double ms = 0, bytes = 0; int groups = 0, disp = 0; };
1915    std::map<std::string, Row> by;
1916    FILE* of = std::getenv("STRATA_METAL_STEPPROF_OUT") ? std::fopen(std::getenv("STRATA_METAL_STEPPROF_OUT"), "w") : nullptr;
1917    size_t layer_gu = 0, layer_dn = 0;
1918    for (size_t j = 0; j < m; ++j) {
1919        const double ms = t[j + 1] - t[j];
1920        size_t best = gs[j];
1921        double bw = -1;
1922        for (size_t i = gs[j]; i < gs[j + 1]; ++i) if (info[i].wbytes > bw) { bw = info[i].wbytes; best = i; }
1923        std::string part = bw > 0 ? info[best].part : info[gs[j]].part;
1924        double bytes = 0;
1925        bool has_gu = false, has_dn = false;
1926        for (size_t i = gs[j]; i < gs[j + 1]; ++i) {
1927            bytes += info[i].wbytes;
1928            if (info[i].part == "experts gate+up") has_gu = true;
1929            if (info[i].part == "experts down") has_dn = true;
1930        }
1931        if (has_gu) { part = "experts gate+up"; bytes += expert_bytes(layer_gu++, true, false); }
1932        if (has_dn) { part = has_gu ? part : "experts down"; bytes += expert_bytes(layer_dn++, false, true); }
1933        Row& r = by[part];
1934        r.ms += ms; r.bytes += bytes; r.groups += 1; r.disp += (int) (gs[j + 1] - gs[j]);
1935        if (of) std::fprintf(of, "%zu\t%zu\t%s\t%.4f\t%.0f\t%s\n", j, gs[j + 1] - gs[j], part.c_str(), ms, bytes, pname.count(ds[gs[j]].p) ? pname[ds[gs[j]].p].c_str() : "?");
1936    }
1937    if (of) std::fclose(of);
1938    double sum = 0, sumb = 0;
1939    for (auto& [k, r] : by) { sum += r.ms; sumb += r.bytes; }
1940    std::fprintf(stderr, "strata metal stepprof: window T%d: whole-window GPU %.3f ms (median of 15), prefix chain %.3f ms (empty-list base %.3f ms), weight bytes %.1f MiB (experts %.1f MiB, distinct per layer avg %.2f)\n",
1941                 Tn, full, t[m] - t[0], t[0], sumb / 1048576.0, expert_total / 1048576.0,
1942                 distinct.empty() ? 0.0 : std::accumulate(distinct.begin(), distinct.end(), 0.0) / (double) distinct.size());
1943    std::vector<std::pair<double, std::string>> rows;
1944    for (auto& [k, r] : by) rows.push_back({r.ms, k});
1945    std::sort(rows.rbegin(), rows.rend());
1946    for (const auto& [ms, k] : rows) {
1947        const Row& r = by[k];
1948        std::fprintf(stderr, "strata metal stepprof: %-22s %8.3f ms %5.1f%%  %5d disp %5d groups  %9.1f MiB  %7.1f GB/s\n", k.c_str(), ms, 100.0 * ms / sum, r.disp, r.groups,
1949                     r.bytes / 1048576.0, r.bytes > 0 && ms > 0 ? r.bytes / 1e9 / (ms / 1000.0) : 0.0);
1950    }
1951    std::string ds_str;
1952    for (size_t i = 0; i < distinct.size(); ++i) ds_str += std::to_string(distinct[i]) + (i + 1 < distinct.size() ? "," : "");
1953    std::fprintf(stderr, "strata metal stepprof: distinct experts per layer: %s\n", ds_str.c_str());
1954    std::fflush(stderr);
1955}
1956
1957Window::~Window() {
1958    df2_free();
1959    if (logpos_) std::fclose(logpos_);
1960    print_prof();
1961}
1962
1963// STRATA_METAL_PROFILE=1: the per-window time split.  Printed once: at the window's destruction, or at process exit
1964// (the serve loop leaves through exit() without destroying the window)
1965void Window::print_prof(bool periodic) {
1966    if ((prof_printed_ && !periodic) || std::getenv("STRATA_METAL_PROFILE") == nullptr) return;
1967    prof_printed_ = !periodic;
1968    auto line = [](const char* what, const Prof& x) {
1969        if (x.n == 0) return;
1970        std::fprintf(stderr, "strata metal profile: %-10s %6lld x  %.3f ms: host before %.3f, run_graph %.3f (GPU %.3f, so "
1971                             "encode/submit/wait %.3f), patch+finish %.3f\n", what, (long long) x.n, x.all / x.n, x.pre / x.n,
1972                     x.rg / x.n, x.gpu / x.n, (x.rg - x.gpu) / x.n, x.fin / x.n);
1973    };
1974    for (const auto& [k, x] : prof_) {
1975        const std::string w = "window T" + std::to_string(k / 2) + (k % 2 ? "" : " nohead");
1976        line(w.c_str(), x);
1977    }
1978    line("commit", cprof_);
1979    line("draft", dprof_);
1980}
1981
1982bool Window::finish(int Tn, const int32_t* tokens, int64_t pos0, bool head, int32_t* out, double t0) {
1983    ++win_n_[Tn];
1984    win_ms_[Tn] += now_ms() - t0;
1985    win_gpu_[Tn] += last_gpu_ms_;
1986    static const bool prof = std::getenv("STRATA_METAL_PROFILE") != nullptr;
1987    if (prof) {
1988        Prof& x = prof_[Tn * 2 + (head ? 1 : 0)];
1989        const double t1 = now_ms();
1990        ++x.n; x.pre += tp_pre_ - t0; x.rg += tp_rg_; x.gpu += last_gpu_ms_; x.fin += t1 - tp_pre_ - tp_rg_;
1991        x.all += t1 - t0;
1992        static int nprof = 0;
1993        if (++nprof % 100 == 0) print_prof(true);   // cumulative; the serve loop may leave without a destructor
1994    }
1995    {   // STRATA_METAL_NFCHECK=1 (test tooling): every head window's logits scanned for non-finite values and the largest |logit| kept;
1996        // a line for the first five bad windows, and a count every 500 head windows and at the 5000th (the numeric health of STRATA_METAL_F16 and the like)
1997        static const bool nfc = std::getenv("STRATA_METAL_NFCHECK") != nullptr;
1998        if (nfc && head) {
1999            static long long nwin = 0, nbad_win = 0, nbad_val = 0;
2000            static float maxabs = 0.0f;
2001            long long bad = 0;
2002            for (int t = 0; t < Tn; ++t) {
2003                const float* row = lm_.as<float>() + (size_t) t * n_vocab_;
2004                for (int64_t i = 0; i < n_vocab_; ++i) {
2005                    if (!std::isfinite(row[i])) ++bad;
2006                    else maxabs = std::max(maxabs, std::fabs(row[i]));
2007                }
2008            }
2009            ++nwin;
2010            if (bad) {
2011                ++nbad_win; nbad_val += bad;
2012                if (nbad_win <= 5)
2013                    std::fprintf(stderr, "strata metal: NFCHECK non-finite logits: %lld values in a %d-token window at position %lld\n", bad, Tn, (long long) pos0);
2014            }
2015            if (nwin % 500 == 0 || nwin == 5000)
2016                std::fprintf(stderr, "strata metal: NFCHECK %lld head windows, %lld with non-finite logits (%lld values), largest |logit| %.2f\n",
2017                             nwin, nbad_win, nbad_val, (double) maxabs);
2018        }
2019    }
2020    logpos(Tn, tokens, pos0, head);
2021    if (Tn == 1) hp_ = 1 - hp_;   // the window committed its first row in the step
2022    last_head_ = head;
2023    for (int t = 0; t < Tn; ++t) out[t] = head ? tokout_.as<int32_t>()[t] : -1;
2024    last_T_ = Tn;
2025    for (int t = 0; t < Tn; ++t) last_tokens_[t] = tokens[t];
2026    static const bool trace = std::getenv("STRATA_METAL_TRACE") != nullptr;
2027    if (trace && head) {
2028        // the pick and its margin over the runner-up (a near tie says a backend difference may flip it)
2029        const float* lg = lm_.as<float>();
2030        int i1 = -1, i2 = -1;
2031        for (int i = 0; i < n_vocab_; ++i) {
2032            if (i1 < 0 || lg[i] > lg[i1]) { i2 = i1; i1 = i; }
2033            else if (i2 < 0 || lg[i] > lg[i2]) i2 = i;
2034        }
2035        std::fprintf(stderr, "strata metal: window pos %lld token %d -> %d (top %d %.4f, 2nd %d %.4f, margin %.4f) %.2f ms (GPU %.2f ms, %d dispatches)\n",
2036                     (long long) pos0, tokens[0], out[0], i1, lg[i1], i2, lg[i2], lg[i1] - lg[i2], now_ms() - t0, last_gpu_ms_, last_n_disp_);
2037    }
2038    return true;
2039}
2040
2041void Window::fold(std::vector<mtl::Dispatch>& ds, int n_keep, int hp) {
2042    const size_t off = 0;
2043    for (int l = 0; l < G_NL; ++l) {
2044        if (l % G_QI == G_QI - 1) continue;
2045        const int gi = l - l / G_QI;
2046        const std::string b = "blk." + std::to_string(l) + ".";
2047        const size_t o_qkv = ((size_t) gi * MAXT + off) * G_CONV * 4, o_ab = ((size_t) gi * MAXT + off) * G_HV * 4,
2048                     o_z = ((size_t) gi * MAXT + off) * G_ZV * 4;
2049        GdnArgs a{G_HK, G_HV, G_CONV, 1u, eps_, 0};
2050        mtl::Dispatch d;
2051        d.p = P(lgdn_, "gdn_step", mtl::Constants().i(2, n_keep), "gdn_step#" + std::to_string(n_keep));
2052        d.args = {mtl::Arg::B(gst_[(size_t) gi]), mtl::Arg::B(ghist_[hp][(size_t) gi]), mtl::Arg::B(qkvL_, o_qkv),
2053                  mtl::Arg::B(alL_, o_ab), mtl::Arg::B(beL_, o_ab), mtl::Arg::B(zL_, o_z),
2054                  mtl::Arg::B(W_, T(b + "ssm_conv1d.weight").offset), mtl::Arg::B(W_, T(b + "ssm_dt.bias").offset),
2055                  mtl::Arg::B(W_, T(b + "ssm_a").offset), mtl::Arg::B(W_, T(b + "ssm_norm.weight").offset),
2056                  mtl::Arg::B(ydump_), mtl::Arg::V(a), mtl::Arg::B(ghist_[1 - hp][(size_t) gi])};
2057        d.grid[0] = G_HV;
2058        d.tg[0] = 512;
2059        nb_ = true;   // the layers' folds are independent of each other
2060        push(ds, d);
2061    }
2062    nb_ = false;   // what follows reads the folded state: a barrier
2063}
2064
2065void Window::swap_state(SeqSet& o) {
2066    auto sw = [](std::vector<mtl::Buffer>& a, std::vector<mtl::Buffer>& b) {
2067        for (size_t i = 0; i < a.size() && i < b.size(); ++i) std::swap(a[i], b[i]);
2068    };
2069    sw(gst_, o.gst); sw(ghist_[0], o.gh0); sw(ghist_[1], o.gh1); sw(kq_, o.kq); sw(vq_, o.vq); sw(ksc_, o.ksc); sw(vsc_, o.vsc);
2070    sw(tail_, o.tail); sw(dead_, o.dead); sw(pooled_, o.pooled);
2071    std::swap(pleHist_, o.pleHist);
2072    ple_hist_.swap(o.ple_hist);
2073    last_norm_.swap(o.last_norm);
2074    std::swap(hp_, o.hp); std::swap(pend_fold_, o.pend_fold); std::swap(last_T_, o.last_T); std::swap(last_head_, o.last_head);
2075    for (int t = 0; t < MAXT; ++t) std::swap(last_tokens_[t], o.last_tokens[t]);
2076    std::swap(ss_, o.ss);
2077}
2078
2079// the buffers of one sequence's running state, shaped like the live ones (real: allocated and zero; else empty placeholders)
2080void Window::alloc_set(SeqSet& o, bool real, int idx) {
2081    const size_t MAXC = (size_t) max_cells_, MB = MAXC / 4 + 2;
2082    if (real && bigs_ok_) {   // set idx's part of the big buffers
2083        for (size_t i = 0; i < gst_.size(); ++i) {
2084            o.gst.push_back(view_of(gstBig_[i], (size_t) idx * st_gst_, GST_B));
2085            o.gh0.push_back(view_of(hbBig_[i], ((size_t) idx * 2 + 0) * st_hist_, HIST_B));
2086            o.gh1.push_back(view_of(hbBig_[i], ((size_t) idx * 2 + 1) * st_hist_, HIST_B));
2087        }
2088        for (size_t j = 0; j < kq_.size(); ++j) {
2089            o.kq.push_back(view_of(kqBig_[j], (size_t) idx * st_kq_, MAXC * G_QKV * G_QD));
2090            o.vq.push_back(view_of(vqBig_[j], (size_t) idx * st_kq_, MAXC * G_QKV * G_QD));
2091            o.ksc.push_back(view_of(kscBig_[j], (size_t) idx * st_sc_, 2 * MAXC * G_QKV * 4));
2092            o.vsc.push_back(view_of(vscBig_[j], (size_t) idx * st_sc_, 2 * MAXC * G_QKV * 4));
2093            o.tail.push_back(view_of(tailBig_[j], (size_t) idx * st_tail_, TAIL_B));
2094            o.dead.push_back(view_of(deadBig_[j], (size_t) idx * st_dead_, DEAD_B));
2095            o.pooled.push_back(view_of(pooledBig_[j], (size_t) idx * st_pooled_, 4 * MB * G_ID));
2096        }
2097        o.pleHist = view_of(pleBig_, (size_t) idx * st_ple_, PLEH_B);
2098        o.ple_hist.assign(ple_hist_.size(), 0.0f);
2099        return;
2100    }
2101    auto A = [&](size_t bytes) { return real ? cx_->alloc(bytes) : mtl::Buffer(); };
2102    for (size_t i = 0; i < gst_.size(); ++i) {
2103        o.gst.push_back(A(GST_B));
2104        o.gh0.push_back(A(HIST_B));
2105        o.gh1.push_back(A(HIST_B));
2106    }
2107    for (size_t j = 0; j < kq_.size(); ++j) {
2108        o.kq.push_back(A(MAXC * G_QKV * G_QD));
2109        o.vq.push_back(A(MAXC * G_QKV * G_QD));
2110        o.ksc.push_back(A(2 * MAXC * 2 * 4));
2111        o.vsc.push_back(A(2 * MAXC * 2 * 4));
2112        o.tail.push_back(A(TAIL_B));
2113        o.dead.push_back(A(DEAD_B));
2114        o.pooled.push_back(A(4 * MB * G_ID));
2115    }
2116    o.pleHist = A(PLEH_B);
2117    if (real) o.ple_hist.assign(ple_hist_.size(), 0.0f);
2118}
2119
2120bool Window::slots_init(const std::vector<strata::core::SessionState*>& slots, std::string& err) {
2121    if (!sets_.empty()) return true;   // (asked once)
2122    if (cx_ == nullptr) { err = "metal window: slots before the window is up"; return false; }
2123    std::vector<std::unique_ptr<SeqSet>> v;
2124    v.push_back(std::make_unique<SeqSet>());
2125    alloc_set(*v[0], false);
2126    v[0]->ss = ss_;
2127    set_of_ss_[ss_] = 0;
2128    uint64_t bytes = 0;
2129    for (size_t b = 0; b < slots.size(); ++b) {
2130        if ((int) b >= g_slot_cap) bigs_ok_ = false;   // more slots than the window was sized for: serial windows only
2131        auto x = std::make_unique<SeqSet>();
2132        alloc_set(*x, true, (int) b + 1);
2133        x->ss = slots[b];
2134        for (auto* vec : {&x->gst, &x->gh0, &x->gh1, &x->kq, &x->vq, &x->ksc, &x->vsc, &x->tail, &x->dead, &x->pooled})
2135            for (const auto& bf : *vec) bytes += bf.bytes;
2136        set_of_ss_[slots[b]] = (int) b + 1;
2137        v.push_back(std::move(x));
2138    }
2139    sets_ = std::move(v);
2140    active_ = 0;
2141    if (bigs_ok_) {   // the strides the row kernels need (elements of each array's type)
2142        uint32_t* h = rinfo_.as<uint32_t>();
2143        h[0] = (uint32_t) st_kq_; h[1] = (uint32_t) (st_sc_ / 2); h[2] = (uint32_t) (st_tail_ / 4); h[3] = (uint32_t) (st_dead_ / 4);
2144        h[4] = (uint32_t) (st_pooled_ / 4); h[5] = (uint32_t) (st_gst_ / 4); h[6] = (uint32_t) (st_hist_ / 4); h[7] = (uint32_t) (st_ple_ / 4);
2145    }
2146    std::fprintf(stderr, "strata metal: %zu batch slots, each with its own running state and K/V (%.2f GB each, %.2f GB in all)\n",
2147                 slots.size(), slots.empty() ? 0.0 : (double) bytes / (double) slots.size() / 1e9, (double) bytes / 1e9);
2148    return true;
2149}
2150
2151// Makes `set` the live state.  The live members and the stashes exchange contents (two swaps through the active set's own stash).
2152void Window::activate(int set) {
2153    if (set == active_ || set < 0 || set >= (int) sets_.size()) return;
2154    swap_state(*sets_[(size_t) active_]);   // the stash of the active one now holds its state, the live members the spare
2155    swap_state(*sets_[(size_t) set]);       // ... and now the wanted one
2156    active_ = set;
2157}
2158
2159bool Window::run_slots(const int* rows, int S, const int32_t* tokens, const int64_t* pos, int32_t* out, std::string& err) {
2160    if (sets_.empty()) { err = "metal window: no batch slots"; return false; }
2161    static const bool one_window = !(std::getenv("STRATA_METAL_BATCH_ROWS") && std::string(std::getenv("STRATA_METAL_BATCH_ROWS")) == "0");
2162    if (one_window && bigs_ok_) {
2163        activate(0);
2164        return run_rows(rows, S, tokens, pos, out, err);
2165    }
2166    bool ok = true;
2167    for (int t = 0; t < S && ok; ++t) {
2168        if (rows[t] < 0 || rows[t] >= n_slots()) { err = "metal window: a batch row names a slot that does not exist"; ok = false; break; }
2169        activate(rows[t] + 1);
2170        // a one-token window commits its row in its own step; commit(1) adds the PLE history and the session's token pair,
2171        // which read buffers the next window rewrites
2172        ok = run(1, tokens + t, pos[t], true, out + t, err) && commit(1, err);
2173    }
2174    activate(0);
2175    return ok;
2176}
2177
2178bool Window::slot_copy(bool into_slot, int b, int64_t upto, bool kv_only, std::string& err) {
2179    if (b < 0 || b >= n_slots()) { err = "metal window: no such batch slot"; return false; }
2180    activate(0);
2181    SeqSet& o = *sets_[(size_t) b + 1];
2182    if (pend_fold_ > 0 || o.pend_fold > 0) { err = "metal window: a slot copy with a fold pending"; return false; }
2183    const size_t cells = (size_t) std::max<int64_t>(0, std::min<int64_t>(upto, max_cells_));
2184    auto cp = [&](const mtl::Buffer& live, const mtl::Buffer& stash, size_t n) {
2185        n = std::min({n, live.bytes, stash.bytes});
2186        if (into_slot) std::memcpy(stash.ptr, live.ptr, n); else std::memcpy(live.ptr, stash.ptr, n);
2187    };
2188    const int hs = into_slot ? hp_ : o.hp;   // the committed history parity of the source
2189    if (!kv_only) {
2190    if (into_slot) o.hp = hp_; else hp_ = o.hp;
2191    for (size_t i = 0; i < gst_.size(); ++i) {
2192        cp(gst_[i], o.gst[i], gst_[i].bytes);
2193        cp(ghist_[hs][i], hs ? o.gh1[i] : o.gh0[i], ghist_[hs][i].bytes);
2194    }
2195    }
2196    for (size_t j = 0; j < kq_.size(); ++j) {
2197        cp(kq_[j], o.kq[j], cells * G_QKV * G_QD);
2198        cp(vq_[j], o.vq[j], cells * G_QKV * G_QD);
2199        cp(ksc_[j], o.ksc[j], cells * G_QKV * 8);
2200        cp(vsc_[j], o.vsc[j], cells * G_QKV * 8);
2201        cp(pooled_[j], o.pooled[j], ((cells + 3) / 4 + 2) * G_ID * 4);
2202        if (kv_only) continue;
2203        cp(tail_[j], o.tail[j], tail_[j].bytes);
2204        cp(dead_[j], o.dead[j], dead_[j].bytes);
2205    }
2206    if (kv_only) return true;
2207    cp(pleHist_, o.pleHist, pleHist_.bytes);
2208    if (into_slot) { o.ple_hist = ple_hist_; o.ss->ple_prev[0] = ss_->ple_prev[0]; o.ss->ple_prev[1] = ss_->ple_prev[1]; }
2209    else { ple_hist_ = o.ple_hist; ss_->ple_prev[0] = o.ss->ple_prev[0]; ss_->ple_prev[1] = o.ss->ple_prev[1]; }
2210    return true;
2211}
2212
2213namespace { strata::core::QsaState* g_draft_state = nullptr; }   // the drafter's QsaState (MtpDrafter::kv_state), bound once the window has the draft layer
2214
2215static void bind_qsa(strata::core::QsaState& st, const mtl::Buffer& kq, const mtl::Buffer& vq, const mtl::Buffer& ksc,
2216                     const mtl::Buffer& vsc, const mtl::Buffer* pooled, const mtl::Buffer* tail, const mtl::Buffer* dead,
2217                     int64_t cells) {
2218    const int64_t page = strata::kernels::qsa_real_shapes().page_size;
2219    st.kv_int8 = true; st.kv_q4 = false; st.kv_hybrid = false; st.kv_rot = false;
2220    st.k_q = (int8_t*) kq.ptr; st.v_q = (int8_t*) vq.ptr;
2221    st.k_scale = (uint16_t*) ksc.ptr; st.v_scale = (uint16_t*) vsc.ptr;
2222    st.k_pool = nullptr; st.v_pool = nullptr;
2223    st.kv_mode = 0;
2224    st.n_pages = cells / page; st.n_slots = st.n_pages;
2225    st.max_cells = std::min<int64_t>(st.max_cells > 0 ? st.max_cells : cells, st.n_pages * page);
2226    if (pooled) { st.idx_pooled = (float*) pooled->ptr; st.idx_pooled_rows = (int64_t) (pooled->bytes / (G_ID * 4)); }
2227    if (tail) st.idx_tail = (float*) tail->ptr;
2228    if (dead) st.idx_dead = (float*) dead->ptr;
2229}
2230
2231void Window::bind_session(strata::core::SessionState& ss) {
2232    if (!ss.qsa_states) return;
2233    const int64_t n = ss.qsa_alloc, o = ss.qsa_ord0;
2234    if (n != (int64_t) kq_.size() || o != 0) return;   // a carved session: not this window's whole model
2235    for (int64_t j = 0; j < n; ++j)
2236        bind_qsa(ss.qsa_states[(size_t) (o + j)], kq_[(size_t) j], vq_[(size_t) j], ksc_[(size_t) j], vsc_[(size_t) j],
2237                 &pooled_[(size_t) j], &tail_[(size_t) j], &dead_[(size_t) j], max_cells_);
2238}
2239
2240void Window::bind_draft(strata::core::QsaState& st) {
2241    if (mkq_.empty()) return;
2242    // the draft layer has no indexer (the snapshot saves no pooled rows for it); its tail/dead ring is not part of the image
2243    bind_qsa(st, mkq_[0], mvq_[0], mksc_[0], mvsc_[0], nullptr, nullptr, nullptr, max_cells_);
2244}
2245
2246bool Window::checkpoint_save(strata::core::ConversationCheckpoint& c, std::string& err) {
2247    (void) err;
2248    if (pend_fold_ > 0) {   // the last commit's fold first: the checkpoint is the state after it
2249        std::vector<mtl::Dispatch> ds;
2250        nb_ = false;
2251        fold(ds, pend_fold_, 1 - hp_);
2252        cx_->run_graph(ds);
2253        pend_fold_ = 0;
2254    }
2255    // The checkpoint is the shared contract (core/conversation_state.cpp's conversation_state_sizes), the one the CUDA indexer
2256    // keeps: the raw tail is idx_block - 1 = 3 rows a layer and block_pos is a scratch int32 a layer.  This window's ring has
2257    // 4 rows (slot = cell % 4), but row 3 is written by the cell that completes the block before it is read, so it never
2258    // has to survive a checkpoint: rows 0..2 are the whole state (the means are identical, qsa.metal qsa_prep).
2259    const size_t gs = GST_B, hs = HIST_B, ts = 3 * 4 * G_ID, dsz = DEAD_B;
2260    c.gdn.resize(gst_.size() * (gs + hs));
2261    for (size_t i = 0; i < gst_.size(); ++i) {
2262        std::memcpy(c.gdn.data() + i * (gs + hs), gst_[i].ptr, gs);
2263        std::memcpy(c.gdn.data() + i * (gs + hs) + gs, ghist_[hp_][i].ptr, hs);
2264    }
2265    c.ple.assign((const uint8_t*) pleHist_.ptr, (const uint8_t*) pleHist_.ptr + PLEH_B);
2266    c.tails.resize(tail_.size() * ts);
2267    c.dead.resize(dead_.size() * dsz);
2268    for (size_t j = 0; j < tail_.size(); ++j) {
2269        std::memcpy(c.tails.data() + j * ts, tail_[j].ptr, ts);   // rows 0..2 of the 4-row ring
2270        std::memcpy(c.dead.data() + j * dsz, dead_[j].ptr, dsz);
2271    }
2272    c.block_pos.assign(tail_.size() * sizeof(int32_t), 0);   // scratch on every backend: written before it is read
2273    return true;
2274}
2275
2276void Window::reset() {
2277    pend_fold_ = 0;
2278    last_T_ = 0;
2279    auto zero = [](const mtl::Buffer& b, size_t n) { std::memset(b.ptr, 0, n); };
2280    for (size_t i = 0; i < gst_.size(); ++i) {
2281        zero(gst_[i], GST_B);
2282        zero(ghist_[0][i], HIST_B);
2283        zero(ghist_[1][i], HIST_B);
2284    }
2285    zero(pleHist_, PLEH_B);
2286    for (size_t j = 0; j < tail_.size(); ++j) {
2287        zero(tail_[j], TAIL_B);
2288        zero(dead_[j], DEAD_B);
2289    }
2290    for (size_t j = 0; j < mtail_.size(); ++j) {
2291        zero(mtail_[j], TAIL_B);
2292        zero(mdead_[j], DEAD_B);
2293    }
2294}
2295
2296bool Window::checkpoint_restore(const strata::core::ConversationCheckpoint& c, std::string& err) {
2297    const size_t gs = GST_B, hs = HIST_B, ts = 3 * 4 * G_ID, tsw = TAIL_B, dsz = DEAD_B;
2298    if (c.gdn.size() != gst_.size() * (gs + hs) || c.ple.size() != (size_t) PLEH_B ||
2299        (c.tails.size() != tail_.size() * ts && c.tails.size() != tail_.size() * tsw) || c.dead.size() != dead_.size() * dsz) {
2300        err = "metal window: the checkpoint is not this engine's (sizes differ)";
2301        return false;
2302    }
2303    pend_fold_ = 0;   // the restored state replaces whatever was pending
2304    last_T_ = 0;
2305    for (size_t i = 0; i < gst_.size(); ++i) {
2306        std::memcpy(gst_[i].ptr, c.gdn.data() + i * (gs + hs), gs);
2307        std::memcpy(ghist_[hp_][i].ptr, c.gdn.data() + i * (gs + hs) + gs, hs);
2308    }
2309    std::memcpy(pleHist_.ptr, c.ple.data(), c.ple.size());
2310    const size_t cts = c.tails.size() / std::max<size_t>(tail_.size(), 1);   // 3 rows (the shared contract) or 4 (an older image)
2311    for (size_t j = 0; j < tail_.size(); ++j) {
2312        std::memset(tail_[j].ptr, 0, tsw);
2313        std::memcpy(tail_[j].ptr, c.tails.data() + j * cts, cts);
2314        std::memcpy(dead_[j].ptr, c.dead.data() + j * dsz, dsz);
2315    }
2316    return true;
2317}
2318
2319bool Window::commit(int n_keep, std::string& err) {
2320    if (n_keep < 1 || n_keep > last_T_) { err = "metal window: commit count out of range"; return false; }
2321    using namespace strata::kernels;
2322    if (last_T_ > 1) {
2323        // the GDN layers: the kept prefix folded into the state (gdn_step over n_keep tokens from the window's own
2324        // inputs, with commit; bitwise the window's trajectory).  K/V and indexer cells past the prefix are rewritten
2325        // when those positions run again, before anything reads them.
2326        static const bool lazy = !(std::getenv("STRATA_METAL_LAZY_FOLD") && std::string(std::getenv("STRATA_METAL_LAZY_FOLD")) == "0");
2327        int nf = n_keep;
2328        if (nf > 0) {
2329            if (lazy) {
2330                pend_fold_ = nf;   // folded at the start of the next window (from the history parity before the turn)
2331            } else {
2332                std::vector<mtl::Dispatch> ds;
2333                nb_ = false;
2334                fold(ds, nf, hp_);
2335                cx_->run_graph(ds);
2336            }
2337            hp_ = 1 - hp_;
2338        }
2339    }
2340    strata::core::SessionState& ss = *ss_;
2341    for (int t = 0; t < n_keep; ++t) {
2342        if (ple_on_) {
2343            const float* norm = normW_.as<float>() + (size_t) t * NG_HC_DIM;
2344            for (int c = 0; c < NG_HC_DIM; ++c) {
2345                float* col = pleHist_.as<float>() + (size_t) c * NG_HIST;
2346                for (int r = 0; r + 1 < NG_HIST; ++r) col[r] = col[r + 1];
2347                col[NG_HIST - 1] = norm[c];
2348            }
2349        }
2350        ss.ple_prev[0] = ss.ple_prev[1];
2351        ss.ple_prev[1] = last_tokens_[t];
2352    }
2353    return true;
2354}
2355
2356
2357// ================================================================================================ the MTP draft layer
2358bool Window::mtp_load(const std::string& gguf_path, int max_t, std::string& err) {
2359    (void) max_t;
2360    if (!fm_.open(gguf_path, err)) return false;
2361    madvise(fm_.map, fm_.map_bytes, MADV_WILLNEED);
2362    Wm_ = cx_->wrap(fm_.map, fm_.map_bytes);
2363    if (Wm_.handle == nullptr) { err = "metal mtp: cannot wrap " + gguf_path; return false; }
2364    // vLLM's GemmaRMSNorm scales by (1 + w): the F32 norms folded once (tools/mtp_rt.py does the same for CUDA)
2365    size_t tot = 0;
2366    for (const auto& kv : fm_.tensors)
2367        if (kv.second.type == 0) { mnorm_off_[kv.first] = tot; tot += (kv.second.bytes + 255) / 256 * 256; }
2368    mnorm_ = cx_->alloc(tot + 256);
2369    for (const auto& kv : mnorm_off_) {
2370        const gguf::Tensor& x = fm_.tensors.at(kv.first);
2371        const float* src = (const float*) ((const uint8_t*) fm_.map + x.offset);
2372        float* dst = (float*) (mnorm_.as<uint8_t>() + kv.second);
2373        for (uint64_t i = 0; i < x.bytes / 4; ++i) dst[i] = src[i] + 1.0f;
2374    }
2375    {
2376        const strata_metal::MslLib L = strata_metal::lib_mtp(engine_msl_dir());
2377        lmtp_ = cx_->compile(L.files, L.prelude);
2378    }
2379    {
2380        const char* e = std::getenv("STRATA_METAL_MTP_Q8");
2381        if (!(e && std::string(e) == "0")) {
2382            size_t tot = 0;
2383            std::vector<std::string> names;
2384            for (const auto& kv : fm_.tensors) {
2385                const gguf::Tensor& x = kv.second;
2386                uint64_t ne = 1;
2387                for (uint64_t d : x.shape) ne *= d;
2388                if (x.type != ref::BF16 || x.shape.size() < 2 || x.shape[0] % 32 != 0) continue;
2389                gguf::Tensor q = x;
2390                q.type = ref::Q8_0;
2391                q.offset = tot;
2392                q.bytes = ne / 32 * 34;
2393                mq8t_[x.name] = q;
2394                names.push_back(x.name);
2395                tot += (q.bytes + 255) / 256 * 256;
2396            }
2397            mq8_ = cx_->alloc(tot + 4096);
2398            std::vector<std::thread> th;
2399            const unsigned nth = std::max(1u, std::min(16u, std::thread::hardware_concurrency()));
2400            for (unsigned k = 0; k < nth; ++k)
2401                th.emplace_back([&, k] {
2402                    std::vector<float> tmp;
2403                    for (size_t i = k; i < names.size(); i += nth) {
2404                        const gguf::Tensor& x = fm_.tensors.at(names[i]);
2405                        const uint64_t ne = x.bytes / 2;
2406                        tmp.resize(ne);
2407                        ref::dequant(ref::BF16, (const uint8_t*) fm_.map + x.offset, tmp.data(), ne);
2408                        ref::quantize_q8_0(tmp.data(), ne, mq8_.as<uint8_t>() + mq8t_[names[i]].offset);
2409                    }
2410                });
2411            for (auto& x : th) x.join();
2412        }
2413    }
2414    auto A = [&](size_t bytes) { return cx_->alloc(bytes); };
2415    const int MAXC = (int) max_cells_, MB = MAXC / 4 + 2;
2416    mR_ = A(4 * MAXT * HC * N); memb_ = A(4 * MAXT * N); men_ = A(4 * MAXT * N); me2_ = A(4 * MAXT * N);
2417    mhn_ = A(4 * MAXT * HC * N); mh2_ = A(4 * HC * MAXT * N); midx_ = A(4 * MAXT * (G_IQR + G_ID)); mbo_ = A(4 * MAXT * N);
2418    minj_[0] = A(4 * MAXT * HC); minj_[1] = A(4 * MAXT * HC); mqids_ = A(4 * MAXT * G_BUD); mlm_ = A(4 * (size_t) n_vocab_);
2419    auto act = [&](int n) {
2420        Act x;
2421        x.n = n;
2422        x.b = A(4 * ((size_t) 4 * MAXT * n + (size_t) MAXT * n / 16) + (metal_f16() ? (size_t) 2 * 3 * MAXT * n : 0));
2423        return x;
2424    };
2425    XEn_ = act(N); XHn_ = act(N);
2426    mkq_.push_back(A((size_t) MAXC * G_QKV * G_QD)); mvq_.push_back(A((size_t) MAXC * G_QKV * G_QD));
2427    mksc_.push_back(A(2 * (size_t) MAXC * G_QKV * 4)); mvsc_.push_back(A(2 * (size_t) MAXC * G_QKV * 4));
2428    mtail_.push_back(A(TAIL_B)); mdead_.push_back(A(DEAD_B)); mpooled_.push_back(A(4 * (size_t) MB * G_ID));
2429    {
2430        std::string vp;
2431        // the subset setup put beside the draft layer (--draft-vocab: <mtp>/rt/draft_vocab.bin, as CUDA reads it),
2432        // else the repository's default
2433        const std::string beside = gguf_path.substr(0, gguf_path.find_last_of('/') + 1) + "rt/draft_vocab.bin";
2434        if (const char* e = std::getenv("STRATA_METAL_DRAFT_VOCAB")) vp = e;
2435        else if (FILE* t = std::fopen(beside.c_str(), "rb")) { std::fclose(t); vp = beside; }
2436        else vp = strata_metal::resource(nullptr, "data", STRATA_METAL_DATA_DEFAULT) + "/draft_vocab.bin";
2437        FILE* f = vp == "full" ? nullptr : std::fopen(vp.c_str(), "rb");
2438        if (f) {
2439            int32_t id;
2440            while (std::fread(&id, 4, 1, f) == 1) if (id >= 0 && id < n_vocab_) dvocab_.push_back(id);
2441            std::fclose(f);
2442        }
2443        if (!dvocab_.empty()) {
2444            const gguf::Tensor& h = T("output.weight");
2445            const size_t rb = ref::row_bytes(h.type, N);
2446            mhead_ = A(dvocab_.size() * rb + 4096);
2447            for (size_t i = 0; i < dvocab_.size(); ++i)
2448                std::memcpy(mhead_.as<uint8_t>() + i * rb, (const uint8_t*) W_.ptr + h.offset + (size_t) dvocab_[i] * rb, rb);
2449            mhead_t_ = h;
2450            mhead_t_.offset = 0;
2451            mhead_t_.shape = {(uint64_t) N, (uint64_t) dvocab_.size()};
2452            mhead_t_.bytes = dvocab_.size() * rb;
2453        }
2454    }
2455    mtp_on_ = true;
2456    if (g_draft_state) bind_draft(*g_draft_state);
2457    {
2458        const int ty = T("token_embd.weight").type;
2459        const int ok_types[] = {30, 8, 2, 6, 20, 23, 42, 21, 11, 12, 13, 14, 18};
2460        const char* e = std::getenv("STRATA_METAL_MTP_CHAIN");
2461        chain_ = !(e && std::string(e) == "0") && std::find(std::begin(ok_types), std::end(ok_types), ty) != std::end(ok_types);
2462        if (chain_) {
2463            {
2464                const strata_metal::MslLib L = strata_metal::lib_mtp_chain(engine_msl_dir());
2465                lchain_ = cx_->compile(L.files, L.prelude);
2466            }
2467            dout_ = A(4 * MAXT); dprob_ = A(4 * MAXT); posv_ = A(4 * N);
2468            for (int i = 0; i < N; ++i) posv_.as<float>()[i] = (float) i;
2469            dmap_ = A(4 * std::max<size_t>(1, dvocab_.size()));
2470            if (!dvocab_.empty()) std::memcpy(dmap_.as<int32_t>(), dvocab_.data(), 4 * dvocab_.size());
2471            // parity: a few tokens' embeddings, GPU vs the host's dequant (the per-step path's)
2472            const gguf::Tensor& te = T("token_embd.weight");
2473            const size_t rb = ref::row_bytes(te.type, N);
2474            const int32_t probe[MAXT] = {0, 1, 271, 760, 6511, 11751, 100000, (int32_t) n_vocab_ - 1};
2475            double worst = 0.0;
2476            std::vector<float> ref_row(N);
2477            for (int k = 0; k < MAXT; ++k) {
2478                dout_.as<int32_t>()[0] = probe[k];
2479                std::vector<mtl::Dispatch> ds;
2480                nb_ = false;
2481                mtl::Dispatch d;
2482                d.p = P(lchain_, "mtp_embed_" + std::to_string(ty), {}, "mtp_embed_" + std::to_string(ty));
2483                struct EmbArgs { uint32_t n, row_bytes, j; } ea{(uint32_t) N, (uint32_t) rb, 0};
2484                d.args = {mtl::Arg::B(W_, te.offset), mtl::Arg::B(dout_), mtl::Arg::B(posv_), mtl::Arg::B(memb_), mtl::Arg::V(ea)};
2485                d.tg[0] = 256;
2486                push(ds, d);
2487                cx_->run_graph(ds);
2488                ref::dequant(te.type, (const uint8_t*) W_.ptr + te.offset + (size_t) probe[k] * rb, ref_row.data(), N);
2489                for (int i = 0; i < N; ++i) worst = std::max(worst, (double) std::fabs(ref_row[i] - memb_.as<float>()[i]));
2490            }
2491            std::fprintf(stderr, "strata metal: MTP draft round in one command buffer (embedding type %d on the GPU: max "
2492                                 "|GPU - host| %.3g over %d rows)\n", ty, worst, MAXT);
2493            if (worst > 1e-6) {
2494                std::fprintf(stderr, "strata metal: the GPU embedding differs from the host's: a command buffer per step\n");
2495                chain_ = false;
2496            }
2497        }
2498    }
2499    std::fprintf(stderr, "strata metal: MTP draft layer from %s (%.2f GB, %zu norms folded), draft head over %s tokens\n",
2500                 gguf_path.c_str(), fm_.file_bytes / 1e9, mnorm_off_.size(),
2501                 dvocab_.empty() ? "all" : std::to_string(dvocab_.size()).c_str());
2502    return true;
2503}
2504
2505void Window::gr_read_m(std::vector<mtl::Dispatch>& ds, const std::string& pre, mtl::Buffer& Rb, const mtl::Buffer& bo,
2506                       const mtl::Buffer& inj_in, const mtl::Buffer& inj_out, bool apply, const Act& out, bool final_,
2507                       int ntok) {
2508    const gguf::Tensor& tdn = TQ(pre + ".input_mix_weight_down.weight");
2509    const gguf::Tensor& tup = TQ(pre + ".input_mix_weight_up.weight");
2510    const gguf::Tensor& tin = final_ ? tdn : TQ(pre + ".block_inject_weight.weight");
2511    const bool q8 = tdn.type == ref::Q8_0 && tup.type == ref::Q8_0 && tin.type == ref::Q8_0;
2512    const mtl::Buffer& WB = q8 ? mq8_ : Wm_;
2513    GrArgs a{N, HC, LR, (uint32_t) ntok, apply ? 1u : 0u, eps_};
2514    mtl::Dispatch d1;
2515    d1.p = P(lib_, k_norm(), {}, k_norm());
2516    d1.args = {mtl::Arg::B(Rb), mtl::Arg::B(bo), mtl::Arg::B(inj_in), mtl::Arg::B(mnorm_, NM(pre + ".hc_norm.weight")),
2517               mtl::Arg::B(xn_), mtl::Arg::V(a)};
2518    d1.grid[0] = HC; d1.grid[1] = ntok; d1.tg[0] = 256;
2519    push(ds, d1);
2520    mtl::Dispatch d2;
2521    const char* dn = q8 ? "gr_down_q8_8_8" : "gr_down_8_8";
2522    d2.p = P(lib_, dn, mtl::Constants().i(1, ntok), std::string(dn) + "#" + std::to_string(ntok));
2523    d2.args = {mtl::Arg::B(WB, tdn.offset), mtl::Arg::B(WB, tin.offset), mtl::Arg::B(xn_), mtl::Arg::B(lo_),
2524               mtl::Arg::B(inj_out), mtl::Arg::V(a)};
2525    d2.grid[0] = LR + HC; d2.tg[0] = 256;
2526    push(ds, d2);
2527    mtl::Dispatch d3;
2528    const char* up = q8 ? "gr_up_q8" : "gr_up";
2529    d3.p = P(lib_, up, mtl::Constants().i(1, ntok), std::string(up) + "#" + std::to_string(ntok));
2530    GrArgs au = a;
2531    au.n_tok = MAXT;
2532    d3.args = {mtl::Arg::B(WB, tup.offset), mtl::Arg::B(lo_), mtl::Arg::B(xn_), mtl::Arg::B(out.b), mtl::Arg::V(au)};
2533    d3.grid[0] = N / 16; d3.tg[0] = 256;
2534    push(ds, d3);
2535}
2536
2537void Window::mtp_encode(std::vector<mtl::Dispatch>& ds, const mtl::Buffer& srcR, size_t src_off, int n, const int32_t* tokens,
2538                        int64_t cell0, bool full, int erow, int slot) {
2539    struct RmsArgs { uint32_t n; float eps; };
2540    struct XpArgs { uint32_t n, n_tok, plane_tok, stride; };
2541    struct CombArgs { uint32_t n, hc, n_tok, h_stride; };
2542    // ---- the embedding rows (host tokens: dequantized on the CPU into the shared buffer)
2543    const gguf::Tensor& te = T("token_embd.weight");
2544    const size_t rb = ref::row_bytes(te.type, N);
2545    if (tokens)
2546        for (int i = 0; i < n; ++i)
2547            ref::dequant(te.type, (const uint8_t*) W_.ptr + te.offset + (size_t) tokens[i] * rb,
2548                         (membp_ ? *membp_ : memb_).as<float>() + (size_t) (erow + i) * N, N);
2549    const std::string L = "mtp.layers.0.";
2550    auto rms = [&](const mtl::Buffer& x, size_t xo, const std::string& w, mtl::Buffer& y, int width, int rows) {
2551        mtl::Dispatch d;
2552        const char* rk = ldb_ && width == geo::N && geo::N == 2560 ? "mtp_rms_b10" : ldb_ && width == geo::HCD && geo::HCD == 10240 ? "mtp_rms_b40" : "mtp_rms";   // (loads batched: same values)
2553        d.p = P(lmtp_, rk, {}, rk);
2554        RmsArgs a{(uint32_t) width, eps_};
2555        d.args = {mtl::Arg::B(x, xo), mtl::Arg::B(mnorm_, NM(w)), mtl::Arg::B(y), mtl::Arg::V(a)};
2556        d.grid[0] = rows; d.tg[0] = 256;
2557        push(ds, d);
2558    };
2559    auto xp = [&](const mtl::Buffer& x, size_t xo, const Act& out, int width, int rows, int stride) {
2560        mtl::Dispatch d;
2561        d.p = P(lmtp_, "mtp_xprep", {}, "mtp_xprep");
2562        XpArgs a{(uint32_t) width, (uint32_t) rows, MAXT, (uint32_t) stride};
2563        d.args = {mtl::Arg::B(x, xo), mtl::Arg::B(out.b), mtl::Arg::V(a)};
2564        d.grid[0] = (width / 16 * rows + 255) / 256; d.tg[0] = 256;
2565        push(ds, d);
2566    };
2567    auto gm = [&](const std::string& name, const Act& x, const mtl::Buffer& y, size_t y_stride, int rows, size_t y_off = 0) {
2568        // a GEMV on the MTP model's tensor (the window's gemv() reads the main model's buffer)
2569        const gguf::Tensor& tt = TQ(name);
2570        const int n_in = (int) tt.shape[0], n_out = tt.shape.size() > 1 ? (int) tt.shape[1] : 1, ty = tt.type;
2571        int Lq = 16, Rr = 1, S = 4, K = 1;
2572        if (n_in >= 6144) { Lq = 32; Rr = 1; S = 8; K = 2; }
2573        else if (n_in == 640) { Lq = 8; Rr = 1; S = 4; K = 1; }
2574        else if (n_out <= 640 || ty == ref::Q2_0 || ty == ref::BF16) { Lq = 32; Rr = 1; S = 4; K = 1; }
2575        const std::string fn = "gemv_" + std::to_string(ty) + "_" + std::to_string(Lq) + "_" + std::to_string(Rr) + "_" +
2576                               std::to_string(S) + "_" + std::to_string(K);
2577        GemvArgs a{(uint32_t) n_in, (uint32_t) n_out, (uint32_t) rows, (uint32_t) ref::row_bytes(ty, n_in), (uint32_t) n_in,
2578                   (uint32_t) y_stride};
2579        mtl::Dispatch d;
2580        d.p = P(lib_, fn, mtl::Constants().i(0, rows), fn + "#" + std::to_string(rows));
2581        d.args = {mtl::Arg::B(MB(name), tt.offset), mtl::Arg::B(x.b, x.plane_bytes() * xkind(ty)),
2582                  mtl::Arg::B(x.b, x.plane_bytes() * 4), mtl::Arg::B(y, y_off), mtl::Arg::V(a)};
2583        const int rpt = (S / K) * (32 / Lq) * Rr;
2584        d.grid[0] = (n_out + rpt - 1) / rpt; d.tg[0] = S * 32;
2585        push(ds, d);
2586    };
2587    // ---- e = fc_embedding(rms(embed(tok)) * (1 + w)),  h = fc_hidden per stream (rms_10240(R) * (1 + w)),  R = h + e
2588    rms(membp_ ? *membp_ : memb_, (size_t) erow * N * 4, "mtp.pre_fc_norm_embedding.weight", men_, N, n);
2589    xp(men_, 0, XEn_, N, n, N);
2590    gm("mtp.fc_embedding.weight", XEn_, me2_, N, n);
2591    rms(srcR, src_off, "mtp.pre_fc_norm_hidden.weight", mhn_, HC * N, n);
2592    for (int c = 0; c < HC; ++c) {
2593        xp(mhn_, (size_t) c * N * 4, XHn_, N, n, HC * N);
2594        gm("mtp.fc_hidden.weight", XHn_, mh2_, N, n, (size_t) c * MAXT * N * 4);
2595    }
2596    {
2597        mtl::Dispatch d;
2598        d.p = P(lmtp_, "mtp_combine", {}, "mtp_combine");
2599        CombArgs a{N, HC, (uint32_t) n, (uint32_t) (MAXT * N)};
2600        d.args = {mtl::Arg::B(mh2_), mtl::Arg::B(me2_), mtl::Arg::B(mR_), mtl::Arg::V(a)};
2601        d.grid[0] = (n * HC * N + 255) / 256; d.tg[0] = 256;
2602        push(ds, d);
2603    }
2604    // ---- the attention hyper-connection, K/V (and the indexer keys) into the layer's own cache
2605    gr_read_m(ds, L + "attn_hyper_connection", mR_, mbo_, minj_[1], minj_[0], false, XA_, false, n);
2606    gm(L + "self_attn.k_proj.weight", XA_, kcur_, G_KV, n);
2607    nb_ = true;
2608    gm(L + "self_attn.v_proj.weight", XA_, vcur_, G_KV, n);
2609    nb_ = true;
2610    gm(L + "self_attn.indexer.index_qk_proj.weight", XA_, midx_, G_IQR + G_ID, n);
2611    if (full) {
2612        nb_ = true;
2613        gm(L + "self_attn.q_proj.weight", XA_, qfull_, G_QFULL, n);
2614    }
2615    QsaArgs qa{(uint32_t) cell0, 0, (uint32_t) max_cells_, (uint32_t) n, eps_};
2616    {
2617        mtl::Dispatch d;
2618        d.p = P(lqsa_, "qsa_prep", qsa_c(), qsa_k());
2619        d.args = {mtl::Arg::B(qfull_), mtl::Arg::B(kcur_), mtl::Arg::B(vcur_), mtl::Arg::B(midx_), mtl::Arg::B(midx_, G_IQR * 4),
2620                  mtl::Arg::B(mnorm_, NM(L + "self_attn.q_norm.weight")), mtl::Arg::B(mnorm_, NM(L + "self_attn.k_norm.weight")),
2621                  mtl::Arg::B(mnorm_, NM(L + "self_attn.indexer.q_layernorm.weight")),
2622                  mtl::Arg::B(mnorm_, NM(L + "self_attn.indexer.k_layernorm.weight")),
2623                  mtl::Arg::B(cs_), mtl::Arg::B(qcur_), mtl::Arg::B(qidx_), mtl::Arg::B(mkq_[0]), mtl::Arg::B(mvq_[0]),
2624                  mtl::Arg::B(mksc_[0]), mtl::Arg::B(mvsc_[0]), mtl::Arg::B(mtail_[0]), mtl::Arg::B(mdead_[0]),
2625                  mtl::Arg::B(mpooled_[0]), mtl::Arg::V(qa), mtl::Arg::B(mrope_)};
2626        d.grid[0] = G_QPREP; d.grid[1] = n; d.tg[0] = 256;
2627        push(ds, d);
2628    }
2629    if (!full) return;
2630    // ---- dense attention over the window of cells up to this one (the draft layer's rule), the output gate, o_proj
2631    {
2632        int* ids = mqids_.as<int>() + (size_t) slot * G_BUD;
2633        const int64_t first = std::max<int64_t>(0, cell0 - 2050);
2634        for (int64_t c = first; c <= cell0; ++c) ids[c - first] = (int) c;
2635        mtl::Dispatch at;
2636        at.p = P(lqsa_, "qsa_attn", {}, "qsa_attn");
2637        at.args = {mtl::Arg::B(qcur_), mtl::Arg::B(mkq_[0]), mtl::Arg::B(mvq_[0]), mtl::Arg::B(mksc_[0]), mtl::Arg::B(mvsc_[0]),
2638                   mtl::Arg::B(mqids_, (size_t) slot * G_BUD * 4), mtl::Arg::B(part_), mtl::Arg::V(qa)};
2639        at.grid[0] = G_QCHUNKS; at.grid[1] = G_QKV; at.grid[2] = 1; at.tg[0] = 256;
2640        push(ds, at);
2641        mtl::Dispatch m;
2642        m.p = P(lqsa_, "qsa_merge", {}, "qsa_merge");
2643        QsaArgs am = qa;
2644        am.n_tok = MAXT;
2645        m.args = {mtl::Arg::B(part_), mtl::Arg::B(qfull_), mtl::Arg::B(XQ_.b), mtl::Arg::V(am)};
2646        m.grid[0] = G_QH; m.grid[1] = 1; m.tg[0] = 256;
2647        push(ds, m);
2648        gm(L + "self_attn.o_proj.weight", XQ_, mbo_, N, 1);
2649    }
2650    // ---- the MLP hyper-connection (the attention write folded in), the MoE, the write + final mixer, the head
2651    gr_read_m(ds, L + "mlp_hyper_connection", mR_, mbo_, minj_[0], minj_[1], true, XF_, false, 1);
2652    gm(L + "mlp.gate.weight", XF_, logits_, 512, 1);
2653    nb_ = true;
2654    gm(L + "mlp.shared_expert.gate_proj.weight", XF_, gsh_, NFF, 1);
2655    nb_ = true;
2656    gm(L + "mlp.shared_expert.up_proj.weight", XF_, ush_, NFF, 1);
2657    nb_ = true;
2658    gm(L + "mlp.shared_expert_gate.weight", XF_, sg_, 1, 1);
2659    {
2660        MoeArgs a{};
2661        const gguf::Tensor &tgu = TM(L + "mlp.experts.gate_up_proj"), &td = TM(L + "mlp.experts.down_proj");
2662        a.gu_row = (uint32_t) ref::row_bytes(tgu.type, N);
2663        a.d_row = (uint32_t) ref::row_bytes(td.type, NFF);
2664        a.gate_off = tgu.offset;
2665        a.up_off = tgu.offset + (uint64_t) NFF * a.gu_row;   // [gate rows | up rows] per expert
2666        a.down_off = td.offset;
2667        a.gu_stride = (uint64_t) a.gu_row * 2 * NFF;
2668        a.d_stride = (uint64_t) a.d_row * N;
2669        a.n_embd = N; a.n_ff = NFF; a.n_tok = 1; a.topk = TOPK; a.n_expert = NEXP;   // (the draft layer: its own 512 experts)
2670        const bool dq2 = td.type == ref::Q2_0;
2671        const int gl = 32, gr = 1, gs = 4, ds_ = 4;
2672        // the down tile: Q2_0 8,1; else 4,2 - but on the M4 (no M5 layout) Q5_1 4,1 and Q8_0 8,1 (4,2 spills there:
2673        // 24-36 GB/s, mac-kern 513fc615)
2674        const bool m4 = !m5_layout();
2675        const int dl = dq2 || (m4 && td.type == ref::Q8_0) ? 8 : 4,
2676                  dr = dq2 || (m4 && (td.type == ref::Q8_0 || td.type == ref::Q5_1 || td.type == ref::Q5_0)) ? 1 : 2;
2677        a.gx_gu = NFF / (gs * (32 / gl) * gr);
2678        a.gx_dn = N / (ds_ * (32 / dl) * dr);
2679        mtl::Dispatch r;
2680        r.p = P(lib_, "moe_route", {}, "moe_route");
2681        r.args = {mtl::Arg::B(logits_), mtl::Arg::B(ids_), mtl::Arg::B(wts_), mtl::Arg::B(plan_), mtl::Arg::V(a)};
2682        r.tg[0] = 512;
2683        push(ds, r);
2684        {
2685            GlueArgs ga{NFF, MAXT, N, TOPK};
2686            mtl::Dispatch d;
2687            d.p = P(lib_, "swiglu_prep", {}, "swiglu_prep");
2688            d.args = {mtl::Arg::B(gsh_), mtl::Arg::B(ush_), mtl::Arg::B(XH_.b), mtl::Arg::V(ga)};
2689            d.grid[0] = NFF / 16; d.grid[1] = 1; d.tg[0] = 16;
2690            nb_ = true;
2691            push(ds, d);
2692        }
2693        const std::string gun = "moe_gu_" + std::to_string(tgu.type) + "_" + std::to_string(gl) + "_" + std::to_string(gr) +
2694                                "_" + std::to_string(gs);
2695        const std::string dnn = "moe_down_" + std::to_string(dq2 ? 142 : td.type) + "_" + std::to_string(dl) + "_" +
2696                                std::to_string(dr) + "_" + std::to_string(ds_);
2697        mtl::Dispatch g;
2698        g.p = P(lib_, gun, mtl::Constants().b(23, metal_ctab()), gun + (metal_ctab() ? "#ct" : ""));
2699        g.args = {mtl::Arg::B(Wm_), mtl::Arg::B(XF_.b, XF_.plane_bytes() * xkind(tgu.type)), mtl::Arg::B(h_), mtl::Arg::B(plan_),
2700                  mtl::Arg::V(a), mtl::Arg::B(XF_.b, XF_.plane_bytes() * 4)};
2701        g.tg[0] = 32 * gs;
2702        g.indirect = &plan_;
2703        g.ind_off = P_IGU * 4;
2704        push(ds, g);
2705        nb_ = true;
2706        gm(L + "mlp.shared_expert.down_proj.weight", XH_, ysh_, N, 1);
2707        mtl::Dispatch dd;
2708        dd.p = P(lib_, dnn, {}, dnn);
2709        dd.args = {mtl::Arg::B(Wm_), mtl::Arg::B(h_), mtl::Arg::B(ye_), mtl::Arg::B(plan_), mtl::Arg::V(a), mtl::Arg::B(h_)};
2710        dd.tg[0] = 32 * ds_;
2711        dd.indirect = &plan_;
2712        dd.ind_off = P_IDN * 4;
2713        push(ds, dd);
2714        GlueArgs ca{N, 1, N, TOPK};
2715        mtl::Dispatch cb;
2716        cb.p = P(lib_, k_comb(), {}, k_comb());
2717        cb.args = {mtl::Arg::B(ye_), mtl::Arg::B(plan_), mtl::Arg::B(ysh_), mtl::Arg::B(sg_), mtl::Arg::B(mbo_), mtl::Arg::V(ca)};
2718        cb.grid[0] = (N + 255) / 256; cb.tg[0] = 256;
2719        push(ds, cb);
2720    }
2721    // the layer's write (R updated in place: the next draft step's input residual) and the final mixer
2722    gr_read_m(ds, "mtp.hyper_connection_mixer", mR_, mbo_, minj_[1], minj_[0], true, XA_, true, 1);
2723    const int64_t nv = dvocab_.empty() ? n_vocab_ : (int64_t) dvocab_.size();
2724    if (dvocab_.empty()) gemv(ds, T("output.weight"), XA_, mlm_, (size_t) n_vocab_, 1);
2725    else gemv(ds, mhead_t_, XA_, mlm_, (size_t) nv, 1, 0, &mhead_);
2726    {
2727        ArgArgs a{(uint32_t) nv, 120};
2728        mtl::Dispatch d1, d2;
2729        d1.p = P(lsmp_, "argmax_part", {}, "argmax_part");
2730        d1.args = {mtl::Arg::B(mlm_), mtl::Arg::B(apv_), mtl::Arg::B(api_), mtl::Arg::V(a)};
2731        d1.grid[0] = 120; d1.grid[1] = 1; d1.tg[0] = 256;
2732        push(ds, d1);
2733        d2.p = P(lsmp_, "argmax_final", {}, "argmax_final");
2734        d2.args = {mtl::Arg::B(apv_), mtl::Arg::B(api_), mtl::Arg::B(tokout_), mtl::Arg::V(a)};
2735        d2.grid[0] = 1; d2.tg[0] = 256;
2736        push(ds, d2);
2737    }
2738}
2739
2740// the prompt's K/V: cell cell0 + i pairs the main window's final residual row i with the token at cell0 + i + 1
2741bool Window::mtp_prefill(const int32_t* next_tokens, int64_t n, int64_t cell0, std::string& err) {
2742    if (!mtp_on_) { err = "metal mtp: not loaded"; return false; }
2743    mtp_wait();   // (the previous chunk's rows share the cache, the scratch and the embedding rows)
2744    mrope_sync(cell0, n);
2745    // every group of MAXT rows in one command buffer: the embedding rows of all of them in mpemb_ (row c + i)
2746    if ((int64_t) mpemb_rows_ < n) {
2747        if (mpemb_rows_ > 0) cx_->free(mpemb_);
2748        mpemb_rows_ = (size_t) std::max<int64_t>(n, 64);
2749        mpemb_ = cx_->alloc(4 * mpemb_rows_ * N);
2750    }
2751    membp_ = &mpemb_;
2752    std::vector<mtl::Dispatch> ds;
2753    nb_ = false;
2754    for (int64_t c = 0; c < n; c += MAXT) {
2755        const int k = (int) std::min<int64_t>(MAXT, n - c);
2756        mtp_encode(ds, mpsrc_ ? *mpsrc_ : mtp_src_ ? *mtp_src_ : R_, (size_t) c * HC * N * 4, k, next_tokens + c,
2757                   cell0 + c, false, (int) c, 0);
2758    }
2759    membp_ = nullptr;
2760    if (mtp_ovl_ && mpsrc_ == &pb_.R && pb_.R2.handle != nullptr && !mrope_on()) mtp_async_ = cx_->run_graph_async(ds);
2761    else cx_->run_graph(ds);
2762    return true;
2763}
2764
2765void Window::mtp_pick(std::vector<mtl::Dispatch>& ds, int j, bool embed) {
2766    struct PickArgs { uint32_t nv, j, use_map; };
2767    const int64_t nv = dvocab_.empty() ? n_vocab_ : (int64_t) dvocab_.size();
2768    mtl::Dispatch d;
2769    d.p = P(lchain_, "mtp_pick", {}, "mtp_pick");
2770    PickArgs pa{(uint32_t) nv, (uint32_t) j, dvocab_.empty() ? 0u : 1u};
2771    d.args = {mtl::Arg::B(mlm_), mtl::Arg::B(tokout_), mtl::Arg::B(dmap_), mtl::Arg::B(dout_), mtl::Arg::B(dprob_),
2772              mtl::Arg::V(pa)};
2773    d.tg[0] = 1024;
2774    push(ds, d);
2775    if (!embed) return;
2776    const gguf::Tensor& te = T("token_embd.weight");
2777    struct EmbArgs { uint32_t n, row_bytes, j; } ea{(uint32_t) N, (uint32_t) ref::row_bytes(te.type, N), (uint32_t) j};
2778    mtl::Dispatch e;
2779    const std::string fn = "mtp_embed_" + std::to_string(te.type);
2780    e.p = P(lchain_, fn, {}, fn);
2781    e.args = {mtl::Arg::B(W_, te.offset), mtl::Arg::B(dout_), mtl::Arg::B(posv_), mtl::Arg::B(memb_), mtl::Arg::V(ea)};
2782    e.tg[0] = 256;
2783    push(ds, e);
2784}
2785
2786// One round (mtp.hpp's draft()): the window's rows 0..a-1 caught up (K/V), then the full layer on row a (draft 0) and
2787// on its own output for the next drafts.  By default the whole round is one command buffer (the pick, its
2788// probability and the next step's embedding on the GPU); STRATA_METAL_MTP_CHAIN=0: a command buffer per step, the
2789// host picking and dequantizing.  The embedding rows: the catch-up's at memb_ rows 0..a-1, draft 0's at row a.
2790bool Window::mtp_draft(int Tn, const int32_t* tokens, int64_t p, int a, int max_steps, int32_t* drafts, float* probs,
2791                       float min_p, int* n_drafts, std::string& err) {
2792    if (!mtp_on_) { err = "metal mtp: not loaded"; return false; }
2793    (void) Tn;
2794    mrope_sync(p, a + max_steps + 1);
2795    int n = 0;
2796    int32_t tok = tokens[a];
2797    if (chain_ && max_steps > 0) {
2798        std::vector<mtl::Dispatch> ds;
2799        nb_ = false;
2800        if (a > 0) mtp_encode(ds, R_, 0, a, tokens, p, false);
2801        mtp_encode(ds, R_, (size_t) a * HC * N * 4, 1, &tok, p + a, true, a, 0);
2802        mtp_pick(ds, 0, max_steps > 1);
2803        for (int j = 1; j < max_steps; ++j) {
2804            mtp_encode(ds, mR_, 0, 1, nullptr, p + a + j, true, 0, j);
2805            mtp_pick(ds, j, j + 1 < max_steps);
2806        }
2807        cx_->run_graph(ds);
2808        for (int j = 0; j < max_steps; ++j) {
2809            const float pj = dprob_.as<float>()[j];
2810            drafts[j] = dout_.as<int32_t>()[j];
2811            if (probs) probs[j] = pj;
2812            ++n;
2813            if (min_p > 0.0f && pj < min_p) break;
2814        }
2815        if (n_drafts) *n_drafts = n;
2816        return true;
2817    }
2818    for (int j = 0; j < max_steps; ++j) {
2819        std::vector<mtl::Dispatch> ds;
2820        nb_ = false;
2821        if (j == 0) {
2822            if (a > 0) mtp_encode(ds, R_, 0, a, tokens, p, false);
2823            mtp_encode(ds, R_, (size_t) a * HC * N * 4, 1, &tok, p + a, true, a, 0);
2824        } else {
2825            mtp_encode(ds, mR_, 0, 1, &tok, p + a + j, true);
2826        }
2827        cx_->run_graph(ds);
2828        const int32_t di = tokout_.as<int32_t>()[0];
2829        const int32_t d = dvocab_.empty() ? di : dvocab_[(size_t) di];
2830        // the draft's probability: softmax of the draft head's logits at the pick
2831        const float* lg = mlm_.as<float>();
2832        const float mx = lg[di];
2833        const int64_t nv = dvocab_.empty() ? n_vocab_ : (int64_t) dvocab_.size();
2834        double s = 0.0;
2835        for (int64_t i = 0; i < nv; ++i) s += std::exp((double) (lg[i] - mx));
2836        const float pj = (float) (1.0 / s);
2837        drafts[j] = d;
2838        if (probs) probs[j] = pj;
2839        tok = d;
2840        ++n;
2841        if (min_p > 0.0f && pj < min_p) break;
2842    }
2843    if (n_drafts) *n_drafts = n;
2844    return true;
2845}
2846
2847bool Window::copy_logits(int t, float* host) const {
2848    if (t < 0 || t >= last_T_) return false;
2849    std::memcpy(host, lm_.as<float>() + (size_t) t * n_vocab_, (size_t) n_vocab_ * 4);
2850    return true;
2851}
2852
2853
2854// ================================================================================== prompts through the matrix units
2855// A prompt chunk of T rows (mac-kern's tests/prompt_chain.cpp, on the engine's state): every dense matrix dequantized
2856// to fp16 once a chunk and multiplied on the matrix units (MPP), the GDN scan, QSA over the chunk, the routed experts
2857// as grouped GEMMs (v2 on the M4, v3 on the M5).  The GDN state, the conv history, the K/V and indexer cells and the
2858// PLE history are the decode window's own, so decoding goes on from them.  With SSD streaming the experts of a layer
2859// are put in place at the layer's handshake (the arena's misses) and the next layer's are streamed in behind it.
2860// STRATA_METAL_PROMPT_GEMM=0: prompts through the decode window (8 rows at a time).  Its numerics differ from the
2861// window's (fp16 operands): STRATA_METAL_PROMPT_GEMM_MIN (default 64) keeps shorter prompts on the window path.
2862namespace {
2863struct PgDq { uint32_t n_in, n_out, row_bytes, perm; };
2864struct PgGemm { int M, N, K, pad; };
2865struct PgEpi { uint32_t n_tok, n_embd, hc, hc_lr; };
2866struct PgGdnP { uint32_t n_tok, h_k, h_v, channels; float eps; uint32_t f32; };
2867struct PgPlan { uint32_t n_ent, topk, n_expert, tm, n_blocks; };
2868struct PgMm { uint64_t gate_off, up_off, down_off, gu_stride, d_stride; uint32_t gu_row, d_row, n_embd, n_ff; };
2869int pg_unit(int t) { return t == ref::Q2_0 || t == ref::IQ3_S || t == ref::BF16 || t == ref::F32 ? 16 : 32; }
2870// the v2 (M4) expert tiles: the K-quants need TK 128, Q8_0 / IQ4_XS TK 32 (their 32-value units), the rest TK 16
2871std::string gu2_tile(int t) {
2872    if (t == ref::Q4_K || t == ref::Q5_K || t == ref::Q6_K) return "_16_16_128_2";   // the M4's best (513fc615)
2873    if (t == ref::Q8_0 || t == ref::IQ4_XS) return "_16_64_32_2";
2874    return "_16_64_16_2";
2875}
2876std::string dn2_tile(int t) {
2877    if (t == ref::Q4_K || t == ref::Q5_K || t == ref::Q6_K) return "_16_16_128_2";   // Q4-KQ: the K-quants' down experts need TK 128 as their gate/up do
2878    if (t == ref::Q3_K || t == ref::IQ4_XS) return "_16_64_32_2";
2879    return t == ref::IQ4_NL || t == ref::Q5_1 || t == ref::Q5_0 || t == ref::Q8_0 ? "_16_64_32_2" : "_16_64_16_2";
2880}
2881}  // namespace
2882
2883struct Window::PromptGemm {
2884    int MT = 0, QS = 256, TM = 16, maxrows = 0, nblk_max = 0;
2885    int lib = -1, lgdn = -1, lqsa = -1;
2886    bool k4 = false, gu_v3 = false, dn_v3 = false, flash = false;
2887    mtl::Buffer R, bo, inj[2], xnh, V, loh, mixed, mixh, qkv, z, al, be, ygh, gqn, gkn, gvc, ggb, gkq, go, yg, qfull, kcur, vcur,
2888        iqr, ikr, qcur, qcurh, qidx, scores, qids, part, XQ, xqh, logits, ids, wts, bcnt, boff, eoff, tiles, meta, stok, sw, pos,
2889        XS, HS, YE, yr, gsh, ush, hh, ys, sgv, emb, embh, pkey, pval, keyn, qn, gated, normW;
2890    mtl::Buffer WD, WU, Wqkv, Wz, Wal, Wbe, Wout, Wq, Wk, Wv, Wiq, Wik, Wr, Wsg, Wshg, Wshu, Wshd, Wpk, Wpv;
2891    mtl::Buffer mixr;   // Gyro: the rotated gate/up input rows [MT][N]
2892};
2893
2894int Window::prompt_chunk_rows() const { return pg_ ? pg_->MT : 0; }
2895
2896bool Window::prompt_gemm_on(int64_t n) const {
2897    static const bool on = [] {
2898        const char* e = std::getenv("STRATA_METAL_PROMPT_GEMM");
2899        return e ? std::string(e) != "0" : true;
2900    }();
2901    static const int64_t mn = [] {
2902        const char* e = std::getenv("STRATA_METAL_PROMPT_GEMM_MIN");
2903        return e ? (int64_t) std::atoll(e) : (int64_t) 64;
2904    }();
2905    return on && n >= mn && pg_ != nullptr;
2906}
2907
2908bool Window::prompt_gemm_init(std::string& err) {
2909    if (pg_) return true;
2910    if (stream_ && !st_->ready()) return stream_arena(err);   // it makes the prompt buffers after the arena
2911    const char* ec = std::getenv("STRATA_METAL_PROMPT_CHUNK");
2912    // Streaming: every chunk makes one pass over the layer's experts that are not in the arena, so a longer chunk
2913    // streams each expert fewer times. M5 Max, UD-Q5, warm: 1024 -> 700 tok/s at 4K, 2048 -> 920, 4096 -> 1,100 (32K the
2914    // same). The longer chunk's buffers (4.3 GB) come out of the arena only while a prompt runs, so it is the default on a
2915    // big Mac; a small one keeps 1024 (the buffers would cost it cache).
2916    uint64_t phys = 0;
2917    size_t plen = sizeof phys;
2918    sysctlbyname("hw.memsize", &phys, &plen, nullptr, 0);
2919    const int stream_chunk = phys >= (96ull << 30) ? 4096 : 1024;
2920    const int C = std::max(64, ec ? std::atoi(ec) : (stream_ ? stream_chunk : 2048)) / 64 * 64;
2921    auto pg = std::make_unique<PromptGemm>();
2922    PromptGemm& p = *pg;
2923    p.MT = C;
2924    p.QS = std::min(C, 256);
2925    {
2926        using namespace strata_metal;
2927        auto cc = [&](const MslLib& L) { return cx_->compile(L.files, L.prelude); };
2928        p.lib = cc(lib_prompt(kq_down_prelude(f_)));
2929        p.lgdn = cc(lib_prompt_gdn());
2930        p.lqsa = cc(lib_prompt_qsa());
2931    }
2932    p.k4 = ::coop_k4(*cx_);
2933    const char* eg = std::getenv("STRATA_METAL_PROMPT_EXPERTS");   // v2 | v3 (default: v3 with the M5's layout)
2934    p.gu_v3 = p.dn_v3 = eg ? std::string(eg) == "v3" : p.k4;
2935    if (T("blk.0.ffn_gate_exps.weight").type >= 144) p.gu_v3 = p.dn_v3 = false;   // the trellis experts have the v2 kernels only
2936    const char* eq = std::getenv("STRATA_METAL_PROMPT_QSA");       // v1 | flash (default: flash with the M5's layout)
2937    p.flash = eq ? std::string(eq) == "flash" : p.k4;
2938    const size_t MT = (size_t) C;
2939    p.maxrows = C * TOPK + nexp_ * p.TM;
2940    p.nblk_max = (C * TOPK + 1023) / 1024;
2941    const int MB = (int) max_cells_ / 4 + 2;
2942    // the buffers: measured first, then placed - on a streaming Mac inside the expert arena (a region of its slots
2943    // reserved only while a prompt runs: the prompt's scratch costs no decode memory), else allocated
2944    uint64_t need = 0;
2945    uint8_t* region = nullptr;
2946    bool measure = true;
2947    auto AB = [&](size_t bytes) -> mtl::Buffer {
2948        const size_t b = (bytes + 16383) / 16384 * 16384;
2949        if (measure) { need += b; return mtl::Buffer{}; }
2950        if (region == nullptr) return cx_->alloc(bytes);
2951        mtl::Buffer r = cx_->wrap(region, b);
2952        region += b;
2953        return r;
2954    };
2955    auto F32 = [&](size_t n) { return AB(4 * n); };
2956    auto F16 = [&](size_t n) { return AB(2 * n); };
2957    auto make = [&] {
2958        const size_t mr = (size_t) p.maxrows;
2959        p.R = F32(MT * HC * N); p.bo = F32(MT * N); p.inj[0] = F32(MT * HC); p.inj[1] = F32(MT * HC); p.xnh = F16(MT * HC * N);
2960        p.V = F32(MT * (LR + HC)); p.loh = F16(MT * LR); p.mixed = F32(MT * N); p.mixh = F16(MT * N);
2961        p.qkv = F32(MT * G_CONV); p.z = F32(MT * G_ZV); p.al = F32(MT * G_HV); p.be = F32(MT * G_HV); p.yg = F32(MT * G_ZV);
2962        p.ygh = F16(MT * G_ZV); p.gqn = F32(MT * G_HK * G_SS); p.gkn = F32(MT * G_HK * G_SS); p.gvc = F32(MT * G_ZV);
2963        p.ggb = F32(MT * G_HV * 2); p.gkq = F32(MT * G_HK); p.go = F32(MT * G_ZV);
2964        p.qfull = F32(MT * G_QFULL); p.kcur = F32(MT * G_KV); p.vcur = F32(MT * G_KV); p.iqr = F32(MT * G_IQR); p.ikr = F32(MT * G_ID);
2965        p.qcur = F32(MT * G_QOUT); p.qcurh = F16(MT * G_QOUT); p.qidx = F32(MT * G_IH * G_ID); p.scores = F32(MT * (size_t) MB);
2966        p.qids = AB(4 * MT * G_BUD);
2967        p.part = p.flash ? F32(16) : F32((size_t) p.QS * G_QCHUNKS * G_QH * (G_QD + 2));
2968        p.XQ = F32(4 * MT * G_QOUT + 3 * (size_t) p.QS * G_QOUT + MT * G_QOUT / 16); p.xqh = F16(MT * G_QOUT);
2969        p.logits = F32(MT * nexp_); p.ids = AB(4 * MT * TOPK); p.wts = F32(MT * TOPK);
2970        p.bcnt = AB(4 * (size_t) p.nblk_max * nexp_); p.boff = AB(4 * (size_t) p.nblk_max * nexp_);
2971        p.eoff = AB(4 * nexp_); p.tiles = AB(8 * (mr / p.TM + 1)); p.meta = AB(64);
2972        p.stok = AB(4 * mr); p.sw = F32(mr); p.pos = AB(4 * MT * TOPK); p.XS = F16(mr * N); p.HS = F16(mr * NFF);
2973        p.YE = F32(mr * N); p.yr = F32(MT * N); p.gsh = F32(MT * NFF); p.ush = F32(MT * NFF); p.hh = F16(MT * NFF);
2974        p.ys = F32(MT * N); p.sgv = F32(MT);
2975        if (had_on_) p.mixr = F32(MT * N);
2976        p.WD = F16((size_t) (LR + HC) * HC * N); p.WU = F16((size_t) HC * N * LR); p.Wqkv = F16((size_t) G_CONV * N);
2977        p.Wz = F16((size_t) G_ZV * N); p.Wal = F16((size_t) G_HV * N); p.Wbe = F16((size_t) G_HV * N); p.Wout = F16((size_t) N * G_QOUT);
2978        p.Wq = F16((size_t) G_QFULL * N); p.Wk = F16((size_t) G_KV * N); p.Wv = F16((size_t) G_KV * N); p.Wiq = F16((size_t) G_IQR * N);
2979        p.Wik = F16((size_t) G_ID * N); p.Wr = F16((size_t) nexp_ * N); p.Wsg = F16((size_t) N); p.Wshg = F16((size_t) NFF * N);
2980        p.Wshu = F16((size_t) NFF * N); p.Wshd = F16((size_t) N * NFF);
2981        if (ple_on_) {
2982            p.emb = F32(MT * N); p.embh = F16(MT * N); p.pkey = F32(MT * G_HCD); p.pval = F32(MT * N); p.keyn = F32(MT * G_HCD);
2983            p.qn = F32(MT * G_HCD); p.gated = F32(MT * G_HCD); p.normW = F32(MT * G_HCD);
2984            p.Wpk = F16((size_t) G_HCD * N); p.Wpv = F16((size_t) N * N);
2985        }
2986    };
2987    make();
2988    measure = false;
2989    if (stream_) {
2990        region = st_->region(need);
2991        if (region == nullptr) { err = "metal prompt: no arena region for the prompt buffers"; return false; }
2992    }
2993    make();
2994    pg_ = pg.release();
2995    std::fprintf(stderr, "strata metal: prompts on the matrix units in chunks of %d (experts %s, QSA %s, matmul2d layout %s; "
2996                         "%.2f GB of buffers%s)\n", C, p.gu_v3 ? "v3" : "v2", p.flash ? "flash" : "v1", p.k4 ? "K4" : "other",
2997                 need / 1e9, stream_ ? ", in the expert arena while a prompt runs" : "");
2998    (void) err;
2999    return true;
3000}
3001
3002bool Window::prompt_chunk(const int32_t* tokens, int Tn, int64_t pos0, std::string& err) {
3003    PromptGemm& p = *pg_;
3004    p.meta.as<uint32_t>()[2] = p.gu_v3 ? NFF / (32 * 4) : NFF / 64;
3005    p.meta.as<uint32_t>()[5] = p.dn_v3 ? N / (64 * 2) : N / 64;
3006    auto TN = [this](const std::string& n) -> const gguf::Tensor& { return this->T(n); };
3007    if (Tn < 1 || Tn > p.MT) { err = "metal prompt: chunk size out of range"; return false; }
3008    if (pos0 + Tn + 1 >= max_cells_) { err = "metal prompt: the chunk runs past the context"; return false; }
3009    if (stream_ && !st_->ready() && !stream_arena(err)) return false;
3010    if (pend_fold_ > 0) {   // the last decode window's commit, still pending
3011        std::vector<mtl::Dispatch> fd;
3012        nb_ = false;
3013        fold(fd, pend_fold_, 1 - hp_);
3014        cx_->run_graph(fd);
3015        pend_fold_ = 0;
3016    }
3017    const int T = Tn;
3018    // ---- the embeddings into every stream, the PLE rows
3019    {
3020        const gguf::Tensor& te = TN("token_embd.weight");
3021        const size_t rb = ref::row_bytes(te.type, N);
3022        mrope_sync(pos0, T);
3023        for (int t = 0; t < T; ++t) {
3024            float* r = p.R.as<float>() + (size_t) t * HC * N;
3025            if (const float* img = img_row(pos0 + t)) std::memcpy(r, img, (size_t) N * 4);
3026            else ref::dequant(te.type, (const uint8_t*) W_.ptr + te.offset + (size_t) tokens[t] * rb, r, N);
3027            for (int c = 1; c < HC; ++c) std::memcpy(r + (size_t) c * N, r, (size_t) N * 4);
3028        }
3029    }
3030    strata::core::SessionState& ss = *ss_;
3031    if (ple_on_) {
3032        std::vector<uint32_t> rows((size_t) T * strata::kernels::PLE_N_HEADS);
3033        int32_t prev[2] = {ss.ple_prev[0], ss.ple_prev[1]};
3034        for (int t = 0; t < T; ++t) {
3035            strata::kernels::ngram_rows(&tokens[t], prev, 1, ss.ple.consts, rows.data() + (size_t) t * strata::kernels::PLE_N_HEADS);
3036            prev[0] = prev[1];
3037            prev[1] = tokens[t];
3038        }
3039        if (!ss.ple.table->gather_batch(rows.data(), (size_t) T, p.emb.as<float>(), err)) return false;
3040    }
3041    std::vector<mtl::Dispatch> ds;
3042    std::vector<int> cuts;
3043    nb_ = false;
3044    auto D = [&](const mtl::Pipeline* pp, std::vector<mtl::Arg> a, uint32_t gx, uint32_t gy, uint32_t tg, uint32_t gz = 1) {
3045        mtl::Dispatch d;
3046        d.p = pp;
3047        d.args = std::move(a);
3048        d.grid[0] = gx; d.grid[1] = gy; d.grid[2] = gz;
3049        d.tg[0] = tg;
3050        push(ds, d);
3051    };
3052    auto PP = [&](int lib, const std::string& fn, const mtl::Constants& c = {}, const std::string& key = "") {
3053        return P(lib, fn, c, "pg:" + (key.empty() ? fn : key));
3054    };
3055    auto gemm = [&](const mtl::Buffer& A, const mtl::Buffer& B, const mtl::Buffer& Y, int M, int Nn, int K) {
3056        const int tm = 64, tn = Nn <= 64 ? 32 : 64;
3057        const std::string fn = "gemm_f16_" + std::to_string(tm) + "_" + std::to_string(tn) + "_4";
3058        PgGemm g{M, Nn, K, 0};
3059        D(PP(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, 128);
3060    };
3061    auto dqb = [&](const mtl::Buffer& src, size_t off, int type, int n_in, int n_out, const mtl::Buffer& out, size_t out_off = 0,
3062                   uint32_t perm = 0) {
3063        PgDq a{(uint32_t) n_in, (uint32_t) n_out, (uint32_t) ref::row_bytes(type, n_in), perm};
3064        D(PP(p.lib, "dq_f16_" + std::to_string(type)), {mtl::Arg::B(src, off), mtl::Arg::B(out, out_off), mtl::Arg::V(a)},
3065          (n_in / pg_unit(type) + 63) / 64, n_out, 64);
3066    };
3067    auto dq = [&](const gguf::Tensor& t, const mtl::Buffer& out, size_t out_off = 0, uint32_t perm = 0) {
3068        const int n_in = (int) t.shape[0], n_out = t.shape.size() > 1 ? (int) t.shape[1] : 1;
3069        if (hc_q8_ && q8off_.count(t.name)) dqb(Q8_, q8off_.at(t.name), ref::Q8_0, n_in, n_out, out, out_off, perm);
3070        else dqb(W_, t.offset, t.type, n_in, n_out, out, out_off, perm);
3071    };
3072    auto act16 = [&](const mtl::Buffer& x, const mtl::Buffer& xh, size_t n) {
3073        const uint32_t nn = (uint32_t) n;
3074        D(PP(p.lib, "act_f16"), {mtl::Arg::B(x), mtl::Arg::B(xh), mtl::Arg::V(nn)}, (nn + 255) / 256, 1, 256);
3075    };
3076    int ci = 0;
3077    auto hc_read = [&](const std::string& pre, bool apply) {
3078        const gguf::Tensor &tn = TN(pre + "_norm.weight"), &tdn = TN(pre + "_down.weight"), &tin = TN(pre + "_inject.weight"),
3079                           &tup = TN(pre + "_up.weight");
3080        dq(tdn, p.WD);
3081        dq(tin, p.WD, (size_t) 2 * LR * HC * N);
3082        dq(tup, p.WU, 0, HC);
3083        GrArgs a{N, HC, LR, (uint32_t) T, apply ? 1u : 0u, eps_};
3084        PgEpi ea{(uint32_t) T, N, HC, LR};
3085        D(PP(p.lib, "gr_norm_h"), {mtl::Arg::B(p.R), mtl::Arg::B(p.bo), mtl::Arg::B(p.inj[ci]), mtl::Arg::B(W_, tn.offset),
3086                                   mtl::Arg::B(p.xnh), mtl::Arg::V(a)}, HC, T, 256);
3087        gemm(p.xnh, p.WD, p.V, T, LR + HC, HC * N);
3088        D(PP(p.lib, "gr_epi_down"), {mtl::Arg::B(p.V), mtl::Arg::B(p.loh), mtl::Arg::B(p.inj[1 - ci]), mtl::Arg::V(ea)},
3089          (T * (LR + HC) + 255) / 256, 1, 256);
3090        PgGemm g{T, HC * N, LR, 0};
3091        D(PP(p.lib, "gemm_hc_up_64_64_4"), {mtl::Arg::B(p.loh), mtl::Arg::B(p.WU), mtl::Arg::B(p.xnh), mtl::Arg::B(p.mixed),
3092                                            mtl::Arg::B(p.mixh), mtl::Arg::V(g), mtl::Arg::V(ea)}, HC * N / 64, (T + 63) / 64, 128);
3093        ci = 1 - ci;
3094    };
3095    // the PLE projections (the window's gemv pair as GEMMs)
3096    if (ple_on_) {
3097        act16(p.emb, p.embh, (size_t) T * N);
3098        dq(TN("blk.1.ple_key.weight"), p.Wpk);
3099        dq(TN("blk.1.ple_value.weight"), p.Wpv);
3100        gemm(p.embh, p.Wpk, p.pkey, T, G_HCD, N);
3101        gemm(p.embh, p.Wpv, p.pval, T, N, N);
3102    }
3103    const int MB = (int) max_cells_ / 4 + 2;
3104    (void) MB;
3105    for (int l = 0; l < G_NL; ++l) {
3106        const std::string b = "blk." + std::to_string(l) + ".";
3107        hc_read(b + "hc_attn", l > 0 && !(l == 1 && ple_on_));
3108        if (l % 4 != 3) {
3109            const int gi = l - l / 4;
3110            dq(TN(b + "attn_qkv.weight"), p.Wqkv);
3111            dq(TN(b + "attn_gate.weight"), p.Wz);
3112            dq(TN(b + "ssm_alpha.weight"), p.Wal);
3113            dq(TN(b + "ssm_beta.weight"), p.Wbe);
3114            dq(TN(b + "ssm_out.weight"), p.Wout);
3115            gemm(p.mixh, p.Wqkv, p.qkv, T, G_CONV, N);
3116            gemm(p.mixh, p.Wz, p.z, T, G_ZV, N);
3117            gemm(p.mixh, p.Wal, p.al, T, G_HV, N);
3118            gemm(p.mixh, p.Wbe, p.be, T, G_HV, N);
3119            PgGdnP ga{(uint32_t) T, G_HK, G_HV, G_CONV, eps_, 0};
3120            D(PP(p.lgdn, "gdn_pre"),
3121              {mtl::Arg::B(p.qkv), mtl::Arg::B(ghist_[hp_][(size_t) gi]), mtl::Arg::B(W_, TN(b + "ssm_conv1d.weight").offset),
3122               mtl::Arg::B(p.al), mtl::Arg::B(p.be), mtl::Arg::B(W_, TN(b + "ssm_dt.bias").offset), mtl::Arg::B(W_, TN(b + "ssm_a").offset),
3123               mtl::Arg::B(p.gqn), mtl::Arg::B(p.gkn), mtl::Arg::B(p.gvc), mtl::Arg::B(p.ggb), mtl::Arg::B(p.gkq),
3124               mtl::Arg::B(ghist_[1 - hp_][(size_t) gi]), mtl::Arg::V(ga)}, G_HK + G_HV / 2, T, 256);
3125            D(PP(p.lgdn, gdn_scan_name(cx_->device_name(), T), mtl::Constants().i(6, 0), gdn_scan_name(cx_->device_name(), T)),
3126              {mtl::Arg::B(gst_[(size_t) gi]), mtl::Arg::B(p.gqn), mtl::Arg::B(p.gkn), mtl::Arg::B(p.gvc), mtl::Arg::B(p.ggb),
3127               mtl::Arg::B(p.gkq), mtl::Arg::B(p.go), mtl::Arg::V(ga)}, G_HV * 4, 1, 32 * 4);
3128            D(PP(p.lgdn, "gdn_post"), {mtl::Arg::B(p.go), mtl::Arg::B(p.z), mtl::Arg::B(W_, TN(b + "ssm_norm.weight").offset),
3129                                       mtl::Arg::B(p.ygh), mtl::Arg::B(p.yg), mtl::Arg::V(ga)}, G_HV, T, 128);
3130            gemm(p.ygh, p.Wout, p.bo, T, N, G_ZV);
3131        } else {
3132            const int qi = l / 4;
3133            dq(TN(b + "attn_q.weight"), p.Wq);
3134            dq(TN(b + "attn_k.weight"), p.Wk);
3135            dq(TN(b + "attn_v.weight"), p.Wv);
3136            dq(TN(b + "indexer.q_proj.weight"), p.Wiq);
3137            dq(TN(b + "indexer.k_proj.weight"), p.Wik);
3138            dq(TN(b + "attn_output.weight"), p.Wout);
3139            gemm(p.mixh, p.Wq, p.qfull, T, G_QFULL, N);
3140            gemm(p.mixh, p.Wk, p.kcur, T, 512, N);
3141            gemm(p.mixh, p.Wv, p.vcur, T, 512, N);
3142            gemm(p.mixh, p.Wiq, p.iqr, T, 512, N);
3143            gemm(p.mixh, p.Wik, p.ikr, T, 128, N);
3144            QsaArgs a{(uint32_t) pos0, 0, (uint32_t) max_cells_, (uint32_t) T, eps_};
3145            D(PP(p.lqsa, "qsa_prep", qsa_c(), qsa_k()),
3146              {mtl::Arg::B(p.qfull), mtl::Arg::B(p.kcur), mtl::Arg::B(p.vcur), mtl::Arg::B(p.iqr), mtl::Arg::B(p.ikr),
3147               mtl::Arg::B(W_, TN(b + "attn_q_norm.weight").offset), mtl::Arg::B(W_, TN(b + "attn_k_norm.weight").offset),
3148               mtl::Arg::B(W_, TN(b + "indexer.q_norm.weight").offset), mtl::Arg::B(W_, TN(b + "indexer.k_norm.weight").offset),
3149               mtl::Arg::B(cs_), mtl::Arg::B(p.qcur), mtl::Arg::B(p.qidx), mtl::Arg::B(kq_[(size_t) qi]), mtl::Arg::B(vq_[(size_t) qi]),
3150               mtl::Arg::B(ksc_[(size_t) qi]), mtl::Arg::B(vsc_[(size_t) qi]), mtl::Arg::B(tail_[(size_t) qi]),
3151               mtl::Arg::B(dead_[(size_t) qi]), mtl::Arg::B(pooled_[(size_t) qi]), mtl::Arg::V(a), mtl::Arg::B(mrope_)}, G_QPREP, T, 256);
3152            if (pos0 + T > G_BUD)
3153                D(PP(p.lqsa, "qsa_score_mm"), {mtl::Arg::B(p.qidx), mtl::Arg::B(pooled_[(size_t) qi]), mtl::Arg::B(dead_[(size_t) qi]),
3154                                               mtl::Arg::B(p.scores), mtl::Arg::V(a)},
3155                  (uint32_t) (((pos0 + T) / 4 + 1 + 63) / 64), (T + 15) / 16, 128);
3156            D(PP(p.lqsa, "qsa_topk"), {mtl::Arg::B(p.scores), mtl::Arg::B(p.qids), mtl::Arg::V(a)}, T, 1, 1024);
3157            if (p.flash) {
3158                const uint32_t nq = (uint32_t) T * G_QOUT;
3159                D(PP(p.lqsa, "qsa_q_f16"), {mtl::Arg::B(p.qcur), mtl::Arg::B(p.qcurh), mtl::Arg::V(nq)}, (nq + 255) / 256, 1, 256);
3160                D(PP(p.lqsa, "qsa_flash", mtl::Constants().b(7, p.k4), "qsa_flash"),
3161                  {mtl::Arg::B(p.qcurh), mtl::Arg::B(kq_[(size_t) qi]), mtl::Arg::B(vq_[(size_t) qi]), mtl::Arg::B(ksc_[(size_t) qi]),
3162                   mtl::Arg::B(vsc_[(size_t) qi]), mtl::Arg::B(p.qids), mtl::Arg::B(p.qfull), mtl::Arg::B(p.xqh), mtl::Arg::V(a)},
3163                  2, T, 128);
3164            } else {
3165                // v1 attention + merge in slices of QS rows (the partials of a slice only)
3166                for (int t0 = 0; t0 < T; t0 += p.QS) {
3167                    const int ns = std::min(p.QS, T - t0);
3168                    QsaArgs as{(uint32_t) (pos0 + t0), 0, (uint32_t) max_cells_, (uint32_t) ns, eps_};
3169                    D(PP(p.lqsa, "qsa_attn"), {mtl::Arg::B(p.qcur, (size_t) t0 * G_QOUT * 4), mtl::Arg::B(kq_[(size_t) qi]),
3170                                               mtl::Arg::B(vq_[(size_t) qi]), mtl::Arg::B(ksc_[(size_t) qi]), mtl::Arg::B(vsc_[(size_t) qi]),
3171                                               mtl::Arg::B(p.qids, (size_t) t0 * G_BUD * 4), mtl::Arg::B(p.part), mtl::Arg::V(as)},
3172                      G_QCHUNKS, G_QKV, 256, (uint32_t) ns);
3173                    D(PP(p.lqsa, "qsa_merge"), {mtl::Arg::B(p.part), mtl::Arg::B(p.qfull, (size_t) t0 * G_QFULL * 4),
3174                                                mtl::Arg::B(p.XQ, (size_t) t0 * G_QOUT * 4), mtl::Arg::V(as)}, G_QH, ns, 256);
3175                }
3176                act16(p.XQ, p.xqh, (size_t) T * G_QOUT);
3177            }
3178            gemm(p.xqh, p.Wout, p.bo, T, N, G_QOUT);
3179        }
3180        if (l == 0 && ple_on_) {
3181            // layer 0's attention write applied to R happens in the FFN read below; the PLE block comes after the FFN
3182        }
3183        // ---- the MoE
3184        hc_read(b + "hc_ffn", true);
3185        const gguf::Tensor &tr = TN(b + "ffn_gate_inp.weight"), &tsg = TN(b + "ffn_gate_inp_shexp.weight"),
3186                           &tg_ = TN(b + "ffn_gate_shexp.weight"), &tu_ = TN(b + "ffn_up_shexp.weight"),
3187                           &td_ = TN(b + "ffn_down_shexp.weight"), &eg = TN(b + "ffn_gate_exps.weight"),
3188                           &ed = TN(b + "ffn_down_exps.weight");
3189        dq(tr, p.Wr);
3190        dq(tsg, p.Wsg);
3191        dq(tg_, p.Wshg);
3192        dq(tu_, p.Wshu);
3193        dq(td_, p.Wshd);
3194        gemm(p.mixh, p.Wr, p.logits, T, nexp_, N);
3195        const uint32_t nt = (uint32_t) T;
3196        D(PP(p.lib, "route_topk"), {mtl::Arg::B(p.logits), mtl::Arg::B(p.ids), mtl::Arg::B(p.wts), mtl::Arg::V(nt), mtl::Arg::V((uint32_t) nexp_)}, (T + 7) / 8, 1, 256);
3197        const int nent = T * TOPK, nblk = (nent + 1023) / 1024;
3198        PgPlan pa{(uint32_t) nent, TOPK, (uint32_t) nexp_, (uint32_t) p.TM, (uint32_t) nblk};
3199        const uint32_t nclr = (uint32_t) p.maxrows;
3200        D(PP(p.lib, "mm_clear"), {mtl::Arg::B(p.stok), mtl::Arg::V(nclr)}, (p.maxrows + 255) / 256, 1, 256);
3201        D(PP(p.lib, "mm_hist"), {mtl::Arg::B(p.ids), mtl::Arg::B(p.bcnt), mtl::Arg::V(pa)}, nblk, 1, 1024);
3202        D(PP(p.lib, "mm_scan"), {mtl::Arg::B(p.bcnt), mtl::Arg::B(p.boff), mtl::Arg::B(p.eoff), mtl::Arg::B(p.tiles),
3203                                 mtl::Arg::B(p.meta), mtl::Arg::V(pa)}, 1, 1, nexp_);
3204        D(PP(p.lib, "mm_place"), {mtl::Arg::B(p.ids), mtl::Arg::B(p.wts), mtl::Arg::B(p.boff), mtl::Arg::B(p.eoff),
3205                                  mtl::Arg::B(p.stok), mtl::Arg::B(p.sw), mtl::Arg::B(p.pos), mtl::Arg::V(pa)}, nblk, 1, 1024);
3206        PgMm ma{eg.offset, TN(b + "ffn_up_exps.weight").offset, ed.offset, 0, 0, (uint32_t) ref::row_bytes(eg.type, N),
3207                (uint32_t) ref::row_bytes(ed.type, NFF), N, NFF};
3208        ma.gu_stride = (uint64_t) ma.gu_row * NFF;
3209        ma.d_stride = (uint64_t) ma.d_row * N;
3210        if (stream_) { ma.gate_off = 0; ma.up_off = st_->up_in_slot(l); ma.down_off = st_->down_in_slot(l); }
3211        const size_t ebase = moe_rebase(ma.gate_off, ma.up_off, ma.down_off);
3212        const uint32_t ne_ = N;
3213        const bool hg = had_gu(l), hd = had_dn(l);
3214        if (hg) had_rows(ds, p.lib, "pg:", p.mixed, 0, p.mixr, 0, T, N, hsx_.handle ? &hsx_ : nullptr, false);
3215        {
3216            mtl::Dispatch g;
3217            g.p = PP(p.lib, "mm_gather");
3218            g.args = {mtl::Arg::B(hg ? p.mixr : p.mixed), mtl::Arg::B(p.stok), mtl::Arg::B(p.XS), mtl::Arg::V(ne_)};
3219            g.tg[0] = 256;
3220            g.indirect = &p.meta;
3221            g.ind_off = 8 * 4;
3222            push(ds, g);
3223        }
3224        const mtl::Buffer& EW = stream_ ? st_->chunk(0) : W_;
3225        auto arena_args = [&](mtl::Dispatch& d) {
3226            if (!stream_) return;
3227            d.args.push_back(mtl::Arg::B(st_->smap(), (size_t) l * 512 * 4));
3228            for (int c = 1; c < 4; ++c) d.args.push_back(mtl::Arg::B(st_->chunk(c)));
3229        };
3230        const std::string ak = stream_ ? "#arena" : "";
3231        mtl::Dispatch gu;
3232        if (p.gu_v3) {
3233            const std::string fn = "mm_gu3_" + std::to_string(eg.type) + "_16_32_32_4";
3234            mtl::Constants c = mtl::Constants().b(7, p.k4);
3235            if (stream_) c.b(20, true);
3236            gu.p = PP(p.lib, fn, c, fn + ak);
3237            gu.tg[0] = 32 * 4;
3238        } else {
3239            const std::string fn = "mm_gu2_" + std::to_string(eg.type) + gu2_tile(eg.type);
3240            mtl::Constants c = mtl::Constants().i(5, 0);
3241            if (stream_) c.b(20, true);
3242            gu.p = PP(p.lib, fn, c, fn + ak);
3243            gu.tg[0] = 64;
3244        }
3245        gu.args = {mtl::Arg::B(EW, ebase), mtl::Arg::B(p.XS), mtl::Arg::B(p.HS), mtl::Arg::B(p.tiles), mtl::Arg::V(ma)};
3246        arena_args(gu);
3247        gu.indirect = &p.meta;
3248        gu.ind_off = 2 * 4;
3249        if (stream_) cuts.push_back((int) ds.size());   // the host's turn: this layer's experts put in place
3250        push(ds, gu);
3251        if (hd) had_rows_ind(ds, p.lib, "pg:", p.HS, p.meta);
3252        mtl::Dispatch dn;
3253        if (p.dn_v3) {
3254            const std::string fn = "mm_down3_" + std::to_string(ed.type) + "_16_64_32_2";
3255            mtl::Constants c = mtl::Constants().b(7, p.k4);
3256            if (stream_) c.b(20, true);
3257            dn.p = PP(p.lib, fn, c, fn + ak);
3258            dn.tg[0] = 32 * 2;
3259        } else {
3260            const std::string fn = "mm_down2_" + std::to_string(ed.type) + dn2_tile(ed.type);
3261            mtl::Constants c;
3262            if (stream_) c.b(20, true);
3263            dn.p = PP(p.lib, fn, c, fn + ak);
3264            dn.tg[0] = 64;
3265        }
3266        dn.args = {mtl::Arg::B(EW, ebase), mtl::Arg::B(p.HS), mtl::Arg::B(p.YE), mtl::Arg::B(p.tiles), mtl::Arg::V(ma)};
3267        arena_args(dn);
3268        dn.indirect = &p.meta;
3269        dn.ind_off = 5 * 4;
3270        push(ds, dn);
3271        const uint32_t ca[4] = {(uint32_t) T, N, TOPK, 0};
3272        D(PP(p.lib, "mm_combine"), {mtl::Arg::B(p.YE), mtl::Arg::B(p.pos), mtl::Arg::B(p.sw), mtl::Arg::B(p.yr), mtl::Arg::V(ca)},
3273          (T * N + 255) / 256, 1, 256);
3274        gemm(p.mixh, p.Wshg, p.gsh, T, NFF, N);
3275        gemm(p.mixh, p.Wshu, p.ush, T, NFF, N);
3276        const uint32_t nh = (uint32_t) T * NFF;
3277        D(PP(p.lib, "swiglu_h"), {mtl::Arg::B(p.gsh), mtl::Arg::B(p.ush), mtl::Arg::B(p.hh), mtl::Arg::V(nh)}, (nh + 255) / 256, 1, 256);
3278        gemm(p.hh, p.Wshd, p.ys, T, N, NFF);
3279        gemm(p.mixh, p.Wsg, p.sgv, T, 1, N);
3280        const uint32_t oa[2] = {(uint32_t) T, N};
3281        D(PP(p.lib, "moe_out"), {mtl::Arg::B(p.yr), mtl::Arg::B(p.ys), mtl::Arg::B(p.sgv), mtl::Arg::B(p.bo), mtl::Arg::V(oa)},
3282          (T * N + 255) / 256, 1, 256);
3283        if (taps_on_ && tap_slot_[l] >= 0) tap_dispatch(ds, l, p.R, p.bo, p.inj[ci], tap_pro_buf(std::max(p.MT, T) + MAXT), T);   // DFlash2
3284        if (l == 0 && ple_on_) {
3285            // layer 0's FFN write applied to R, then the PLE block (as the window, for T rows)
3286            const gguf::Tensor& tn = TN("blk.1.hc_attn_norm.weight");
3287            GrArgs a{N, HC, LR, (uint32_t) T, 1u, eps_};
3288            D(P(lib_, "gr_norm", {}, "gr_norm"), {mtl::Arg::B(p.R), mtl::Arg::B(p.bo), mtl::Arg::B(p.inj[ci]), mtl::Arg::B(W_, tn.offset),
3289                                                  mtl::Arg::B(p.YE), mtl::Arg::V(a)}, HC, T, 256);
3290            struct PleArgs { uint32_t n_embd, hc; float eps; } pl{N, HC, strata::kernels::NG_RMS_EPS};
3291            auto off = [&](const char* n) { return TN(n).offset; };
3292            D(P(lple_, "ple_gnorm", {}, "ple_gnorm"), {mtl::Arg::B(p.pkey), mtl::Arg::B(W_, off("blk.1.ple_norm_key.weight")),
3293                                                      mtl::Arg::B(p.keyn), mtl::Arg::V(pl)}, HC, T, 256);
3294            nb_ = true;
3295            D(P(lple_, "ple_gnorm", {}, "ple_gnorm"), {mtl::Arg::B(p.R), mtl::Arg::B(W_, off("blk.1.ple_norm_query.weight")),
3296                                                      mtl::Arg::B(p.qn), mtl::Arg::V(pl)}, HC, T, 256);
3297            D(P(lple_, "ple_gate_norm", {}, "ple_gate_norm"),
3298              {mtl::Arg::B(p.keyn), mtl::Arg::B(p.qn), mtl::Arg::B(p.pval), mtl::Arg::B(W_, off("blk.1.ple_norm_conv.weight")),
3299               mtl::Arg::B(p.gated), mtl::Arg::B(p.normW), mtl::Arg::V(pl)}, HC, T, 256);
3300            D(P(lple_, "ple_conv_add", {}, "ple_conv_add"),
3301              {mtl::Arg::B(pleHist_), mtl::Arg::B(p.normW), kw_arg(), mtl::Arg::B(p.gated),
3302               mtl::Arg::B(p.R), mtl::Arg::V(pl)}, HC * N / 256, T, 256);
3303        }
3304    }
3305    // the last layer's write applied to R (the draft layer's K/V read the final residual rows)
3306    {
3307        const gguf::Tensor& tn = TN("output_hc_norm.weight");
3308        GrArgs a{N, HC, LR, (uint32_t) T, 1u, eps_};
3309        D(P(lib_, "gr_norm", {}, "gr_norm"), {mtl::Arg::B(p.R), mtl::Arg::B(p.bo), mtl::Arg::B(p.inj[ci]), mtl::Arg::B(W_, tn.offset),
3310                                              mtl::Arg::B(p.YE), mtl::Arg::V(a)}, HC, T, 256);
3311    }
3312    const double t0 = now_ms();
3313    if (stream_) {
3314        seg_T_ = T;
3315        cut_ids_ = p.ids.as<int32_t>();
3316        cx_->run_graph_seg(ds, cuts, [](void* u, int s) { ((Window*) u)->at_cut(s); }, this);
3317        cut_ids_ = nullptr;
3318    } else {
3319        cx_->run_graph(ds);
3320    }
3321    pg_ms_ += now_ms() - t0;
3322    pg_tok_ += T;
3323    static const bool trace = std::getenv("STRATA_METAL_TRACE") != nullptr;
3324    if (trace) std::fprintf(stderr, "strata metal: prompt chunk pos %lld, %d rows: %.0f ms\n", (long long) pos0, T, now_ms() - t0);
3325    // the window's state after the chunk: the conv history turned, the PLE history and token window advanced
3326    hp_ = 1 - hp_;
3327    if (ple_on_) {
3328        using namespace strata::kernels;
3329        float* hist = pleHist_.as<float>();
3330        const float* nw = p.normW.as<float>();
3331        for (int c = 0; c < NG_HC_DIM; ++c) {
3332            float col[NG_HIST];
3333            for (int r = 0; r < NG_HIST; ++r) {
3334                const int src = T - NG_HIST + r;   // row r of the new history: chunk row src, or the old history
3335                col[r] = src >= 0 ? nw[(size_t) src * NG_HC_DIM + c] : hist[(size_t) c * NG_HIST + (size_t) (r + T)];
3336            }
3337            std::memcpy(hist + (size_t) c * NG_HIST, col, sizeof col);
3338        }
3339    }
3340    if (T >= 2) { ss.ple_prev[0] = tokens[T - 2]; ss.ple_prev[1] = tokens[T - 1]; }
3341    else { ss.ple_prev[0] = ss.ple_prev[1]; ss.ple_prev[1] = tokens[0]; }
3342    mtp_src_ = &p.R;   // the draft layer's prompt K/V read this chunk's final rows
3343    if (taps_on_ && !tap_deliver(tap_pro_, T, pos0, err)) return false;   // DFlash2: the prompt rows the drafter looks at
3344    return true;
3345}
3346
3347// ---- the request's sampling (sample.metal): the chain over the window's head rows, after run() has left the logits in lm_
3348void Window::set_sampling(const strata::kernels::SamplerParams* sp, const int32_t* hist, int hist_len) {
3349    samp_on_ = sp != nullptr;
3350    if (sp) samp_ = *sp;
3351    samp_hist_ = hist;
3352    samp_hist_len_ = hist_len;
3353}
3354
3355bool Window::sample_rows(int Tn, int32_t* out, std::string& err) {
3356    if (!samp_on_ || Tn < 1 || Tn > MAXT) return true;
3357    if (!sample_run(0, Tn, samp_, samp_hist_, samp_hist_len_, err)) return false;
3358    for (int t = 0; t < Tn; ++t) out[t] = tokout_.as<int32_t>()[t];
3359    return true;
3360}
3361
3362bool Window::sample_slot_row(int row, const strata::kernels::SamplerParams& sp, const int32_t* hist, int hist_len, int32_t* tok, std::string& err) {
3363    if (row < 0 || row >= MAXT) return true;
3364    if (!sample_run(row, 1, sp, hist, hist_len, err)) return false;
3365    *tok = tokout_.as<int32_t>()[row];
3366    return true;
3367}
3368
3369// the chain over logits rows [row0, row0 + n) of lm_, written to tokout_[row0 ..]; row r's draw is Philox(seed, counter + r - row0)
3370bool Window::sample_run(int row0, int n, const strata::kernels::SamplerParams& sp, const int32_t* hist_in, int hl, std::string& err) {
3371    const int Tn = n;
3372    const int64_t V = n_vocab_;
3373    constexpr uint32_t PARTS = 64;
3374    if (V > (int64_t) PARTS * 4096) { err = "metal sampler: the vocabulary is wider than 64 parts of 4096"; return false; }
3375    if (!scv_.handle) {
3376        scv_ = cx_->alloc(4 * (size_t) MAXT * PARTS * 64);
3377        sci_ = cx_->alloc(4 * (size_t) MAXT * PARTS * 64);
3378    }
3379    const bool greedy = sp.greedy || sp.temperature <= 0.0f;
3380    uint32_t flags = greedy ? 2u : 0u;
3381    // the logit bias: a device array of n_vocab floats (unified memory: read as it is, copied into the sampler's own buffer)
3382    if (sp.logit_bias != nullptr) {
3383        if (sbias_cap_ < 4 * (size_t) V) {   // (an earlier request without a bias left the 16-byte stand-in)
3384            if (sbias_.handle) cx_->free(sbias_);
3385            sbias_ = cx_->alloc(4 * (size_t) V);
3386            sbias_cap_ = 4 * (size_t) V;
3387        }
3388        std::memcpy(sbias_.ptr, strata::gpu::host_view(sp.logit_bias), 4 * (size_t) V);   // (a cudaMalloc'd array: the runtime's CPU view)
3389        flags |= 1u;
3390    } else if (!sbias_.handle) {
3391        sbias_ = cx_->alloc(16);
3392        sbias_cap_ = 16;
3393    }
3394    uint32_t pen_n = 0;
3395    if (hist_in != nullptr && hl > 0 && sp.penalty_last_n > 0) {
3396        pen_n = (uint32_t) std::min(sp.penalty_last_n, hl);
3397        const size_t need = 4 * (size_t) MAXT * (size_t) hl;
3398        if (shist_cap_ < need) { if (shist_.handle) cx_->free(shist_); shist_ = cx_->alloc(need); shist_cap_ = need; }
3399        std::memcpy(shist_.ptr, strata::gpu::host_view(hist_in), 4 * (size_t) Tn * (size_t) hl);
3400        flags |= 4u;
3401    } else if (!shist_.handle) {
3402        shist_ = cx_->alloc(16); shist_cap_ = 16;
3403    }
3404    struct SampArgs {
3405        uint32_t n_vocab, parts, k, hist_len, pen_n, min_keep, flags;
3406        float top_p, min_p, inv_t, rep, freq, pres;
3407        uint32_t seed_lo, seed_hi, ctr_lo, ctr_hi;
3408    } a{};
3409    a.n_vocab = (uint32_t) V;
3410    a.parts = PARTS;
3411    a.k = greedy ? 1u : (uint32_t) ((sp.top_k > 0 && sp.top_k < 64) ? sp.top_k : 64);
3412    a.hist_len = (flags & 4u) ? (uint32_t) hl : 0u;
3413    a.pen_n = pen_n;
3414    a.min_keep = (uint32_t) std::max(1, sp.min_keep);
3415    a.flags = flags;
3416    a.top_p = sp.top_p;
3417    a.min_p = sp.min_p;
3418    a.inv_t = greedy ? 1.0f : 1.0f / sp.temperature;
3419    a.rep = sp.penalty_repeat;
3420    a.freq = sp.penalty_freq;
3421    a.pres = sp.penalty_present;
3422    a.seed_lo = (uint32_t) sp.seed; a.seed_hi = (uint32_t) (sp.seed >> 32);
3423    a.ctr_lo = (uint32_t) sp.counter; a.ctr_hi = (uint32_t) (sp.counter >> 32);
3424    mtl::Dispatch d1, d2;
3425    d1.p = P(lsmp_, "samp_part", {}, "samp_part");
3426    const size_t cand_off = 4 * (size_t) row0 * PARTS * 64;
3427    d1.args = {mtl::Arg::B(lm_, 4 * (size_t) row0 * (size_t) V), mtl::Arg::B(sbias_), mtl::Arg::B(shist_), mtl::Arg::B(scv_, cand_off), mtl::Arg::B(sci_, cand_off), mtl::Arg::V(a)};
3428    d1.grid[0] = PARTS; d1.grid[1] = (uint32_t) Tn; d1.tg[0] = 256;
3429    d2.p = P(lsmp_, "samp_pick", {}, "samp_pick");
3430    d2.args = {mtl::Arg::B(scv_, cand_off), mtl::Arg::B(sci_, cand_off), mtl::Arg::B(tokout_, 4 * (size_t) row0), mtl::Arg::V(a)};
3431    d2.grid[0] = (uint32_t) Tn; d2.tg[0] = 256;
3432    const double t0 = now_ms();
3433    cx_->run_graph({d1, d2});
3434    ++samp_windows_;
3435    static const bool st = std::getenv("STRATA_METAL_SAMPLE_STATS") != nullptr;
3436    if (st && samp_windows_ % 200 == 0)
3437        std::fprintf(stderr, "strata metal: sampler %llu windows, last %d rows in %.2f ms\n", (unsigned long long) samp_windows_, Tn, now_ms() - t0);
3438    return true;
3439}
3440
3441// ---------------------------------------------------------------------------------------------- the hook's entry points
3442namespace {
3443std::string g_shard1;
3444}
3445void window_register(void* w);
3446bool mtp_load_pending(Window* w, std::string& err);
3447void set_model_shard(const char* shard1) { g_shard1 = shard1 ? shard1 : ""; }
3448void set_batch_slots(int n) { g_slot_cap = n > 0 ? std::min(n, 8) : 0; }
3449
3450// The draft vocabulary the build ships (data/draft_vocab.bin beside the build, else the compiled-in data folder): what a DFlash2-alone start without <mtp>/draft_vocab.bin
3451// uses (generate.cpp), and what Window::df2_bind falls back to.  STRATA_METAL_DRAFT_VOCAB names another file, or "full" for the whole head.
3452std::string draft_vocab_default() {
3453    const char* e = std::getenv("STRATA_METAL_DRAFT_VOCAB");
3454    if (e != nullptr && e[0] != 0 && std::string(e) != "full") return e;
3455    return strata_metal::resource(nullptr, "data", STRATA_METAL_DATA_DEFAULT) + "/draft_vocab.bin";
3456}
3457bool draft_vocab_whole_head() {
3458    const char* e = std::getenv("STRATA_METAL_DRAFT_VOCAB");
3459    return e != nullptr && std::string(e) == "full";
3460}
3461
3462// One decode window per process: the prompt path (Prefill::init) may bring it up before the Verifier does.
3463namespace {
3464Window* g_the_window = nullptr;
3465}
3466void* window_create() {
3467    if (g_the_window == nullptr) {
3468        g_the_window = new Window();
3469        if (std::getenv("STRATA_METAL_PROFILE")) std::atexit([] { if (g_the_window) g_the_window->print_prof(); });
3470    }
3471    return g_the_window;
3472}
3473void window_destroy(void* w) {
3474    if (w != nullptr && w == g_the_window) {
3475        if (g_stream_window == g_the_window) {
3476            g_the_window->stream_report(stderr);
3477            g_stream_window = nullptr;
3478        }
3479        delete g_the_window;
3480        g_the_window = nullptr;
3481        window_register(nullptr);
3482    }
3483}
3484bool window_init(void* w, const strata::core::ModelGeometry& g, strata::core::SessionState& ss, int max_t, int64_t max_cells,
3485                 int64_t* n_vocab, std::string& err) {
3486    Window* x = (Window*) w;
3487    if (!x->ready()) {
3488        if (g_shard1.empty()) { err = "metal window: the model shard is not set (--native SHARD1)"; return false; }
3489        if (!x->init(g, ss, g_shard1, MAXT, max_cells, err)) return false;
3490        window_register(w);
3491        if (!mtp_load_pending(x, err)) return false;
3492    }
3493    x->set_max_t(max_t);
3494    *n_vocab = x->vocab();
3495    return true;
3496}
3497bool window_ensure(const strata::core::ModelGeometry& g, strata::core::SessionState& ss, int64_t max_cells, std::string& err) {
3498    int64_t nv = 0;
3499    return window_init(window_create(), g, ss, MAXT, max_cells, &nv, err);
3500}
3501bool window_sample_slot_row(void* w, int row, const strata::kernels::SamplerParams& sp, const int32_t* hist, int hist_len, int32_t* tok, std::string& err) {
3502    return ((Window*) w)->sample_slot_row(row, sp, hist, hist_len, tok, err);
3503}
3504void window_set_sampling(void* w, const strata::kernels::SamplerParams* sp, const int32_t* hist, int hist_len) {
3505    ((Window*) w)->set_sampling(sp, hist, hist_len);
3506}
3507bool window_run(void* w, int T, const int32_t* tokens, int64_t pos0, bool head, int32_t* out, std::string& err) {
3508    // STRATA_LOGPOS (the quant yardstick, the KL harness): every window's head logits are read, also the prompt's
3509    // windows that sample nothing (head_sampling off)
3510    static const bool logpos = std::getenv("STRATA_LOGPOS") != nullptr;
3511    Window* win = (Window*) w;
3512    if (!win->run(T, tokens, pos0, head || logpos, out, err)) return false;
3513    return !head || win->sample_rows(T, out, err);   // a sampled / penalised / biased request: the head rows' tokens by the sampler chain (nothing to do for greedy)
3514}
3515void window_reset(const strata::core::SessionState* ss) {
3516    if (g_the_window == nullptr || !g_the_window->ready()) return;
3517    g_the_window->activate(g_the_window->set_of(ss));
3518    g_the_window->reset();
3519    g_the_window->activate(0);
3520}
3521bool window_checkpoint_save(strata::core::ConversationCheckpoint& c, const strata::core::SessionState* ss, std::string& err) {
3522    if (g_the_window == nullptr || !g_the_window->ready()) { err = "metal window: not up"; return false; }
3523    g_the_window->activate(g_the_window->set_of(ss));   // a batch slot's session: that slot's running state
3524    const bool ok = g_the_window->checkpoint_save(c, err);
3525    g_the_window->activate(0);
3526    return ok;
3527}
3528bool window_checkpoint_restore(const strata::core::ConversationCheckpoint& c, const strata::core::SessionState* ss, std::string& err) {
3529    if (g_the_window == nullptr || !g_the_window->ready()) { err = "metal window: not up"; return false; }
3530    g_the_window->activate(g_the_window->set_of(ss));
3531    const bool ok = g_the_window->checkpoint_restore(c, err);
3532    g_the_window->activate(0);
3533    return ok;
3534}
3535bool window_init_slots(void* w, const std::vector<strata::core::SessionState*>& slots, std::string& err) {
3536    return ((Window*) w)->slots_init(slots, err);
3537}
3538bool window_run_slots(void* w, const int* rows, int S, const int32_t* tokens, const int64_t* pos, int32_t* out, std::string& err) {
3539    const double t0 = now_ms();
3540    const bool ok = ((Window*) w)->run_slots(rows, S, tokens, pos, out, err);
3541    ((Window*) w)->prof_add(true, now_ms() - t0);
3542    return ok;
3543}
3544bool window_slot_copy_main(bool into_slot, int slot, int64_t upto, bool kv_only, std::string& err) {
3545    if (g_the_window == nullptr || !g_the_window->ready()) { err = "metal window: not up"; return false; }
3546    return g_the_window->slot_copy(into_slot, slot, upto, kv_only, err);
3547}
3548bool window_commit(void* w, int n_keep, std::string& err) {
3549    const double t0 = now_ms();
3550    const bool ok = ((Window*) w)->commit(n_keep, err);
3551    ((Window*) w)->prof_add(false, now_ms() - t0);
3552    return ok;
3553}
3554bool window_copy_logits(void* w, int t, float* host) { return ((Window*) w)->copy_logits(t, host); }
3555
3556// the MTP hook (src/core/mtp.cpp under STRATA_GPU_METAL): the drafter lives beside the decode window it reads
3557namespace {
3558Window* g_window = nullptr;
3559}
3560void window_register(void* w) { g_window = (Window*) w; }
3561// the engine loads the drafter before the decode window exists: the path is kept and the window loads it at its init
3562std::string g_mtp_path;
3563int g_mtp_max_t = 0;
3564bool mtp_load(const std::string& rt_dir, int max_t, std::string& err) {
3565    (void) err;
3566    // the MTP model in GGUF form (tools/mtp_pack.py) beside the rt directory: STRATA_METAL_MTP_GGUF, else
3567    // <rt>/../mtp-q2_0.gguf
3568    std::string path;
3569    if (const char* e = std::getenv("STRATA_METAL_MTP_GGUF")) path = e;
3570    else {
3571        std::string d = rt_dir;
3572        while (!d.empty() && d.back() == '/') d.pop_back();
3573        const size_t s = d.rfind('/');
3574        path = (s == std::string::npos ? std::string(".") : d.substr(0, s)) + "/mtp-q2_0.gguf";
3575    }
3576    g_mtp_path = path;
3577    g_mtp_max_t = max_t;
3578    return true;
3579}
3580void mtp_bind_state(strata::core::QsaState& st) {
3581    g_draft_state = &st;
3582    if (g_the_window && g_the_window->mtp_ready()) g_the_window->bind_draft(st);
3583}
3584bool mtp_load_pending(Window* w, std::string& err) {
3585    return g_mtp_path.empty() || w->mtp_load(g_mtp_path, g_mtp_max_t, err);
3586}
3587// Prefill::run's Metal side: the prompt read through the window, MAXT rows at a time (no head), each window
3588// committed; on_chunk (the MTP's K/V) after each, with the window's final residual rows in place.
3589bool prompt_run_rows(const int64_t* tokens, int64_t n, int64_t pos0,
3590                     const std::function<bool(const float*, int64_t, int64_t, std::string&)>& on_chunk, std::string& err);
3591bool prompt_run(const int64_t* tokens, int64_t n, int64_t pos0, const float* const* embd_rows,
3592                const std::function<bool(const float*, int64_t, int64_t, std::string&)>& on_chunk, std::string& err) {
3593    struct Rows {
3594        explicit Rows(const float* const* r) { g_embd_rows = r; }
3595        ~Rows() { g_embd_rows = nullptr; }
3596    } rows(embd_rows);
3597    return prompt_run_rows(tokens, n, pos0, on_chunk, err);
3598}
3599bool prompt_run_rows(const int64_t* tokens, int64_t n, int64_t pos0,
3600                     const std::function<bool(const float*, int64_t, int64_t, std::string&)>& on_chunk, std::string& err) {
3601    if (g_window == nullptr) { err = "metal prompt: the decode window is not up yet"; return false; }
3602    static const bool windows = std::getenv("STRATA_METAL_PROMPT") && std::string(std::getenv("STRATA_METAL_PROMPT")) == "window";
3603    static const int64_t min_rows = std::getenv("STRATA_METAL_PROMPT_MIN") ? std::atoll(std::getenv("STRATA_METAL_PROMPT_MIN")) : 32;
3604    if (!windows && !g_window->streaming() && n >= min_rows) return g_window->prompt(tokens, n, pos0, on_chunk, err);
3605    if (!windows && g_window->streaming()) {
3606        const char* e = std::getenv("STRATA_METAL_PROMPT_GEMM");
3607        const char* em = std::getenv("STRATA_METAL_PROMPT_GEMM_MIN");
3608        const int64_t mn = em ? std::atoll(em) : 64;
3609        if (!(e && std::string(e) == "0") && n >= mn) {
3610            if (!g_window->prompt_gemm_init(err)) return false;
3611            const int C = g_window->prompt_chunk_rows();
3612            std::vector<int32_t> tk32((size_t) C);
3613            g_window->prompt_region(true);
3614            bool ok = true;
3615            for (int64_t c = 0; c < n && ok; c += C) {
3616                const int k = (int) std::min<int64_t>(C, n - c);
3617                for (int i = 0; i < k; ++i) tk32[(size_t) i] = (int32_t) tokens[c + i];
3618                ok = g_window->prompt_chunk(tk32.data(), k, pos0 + c, err) && (!on_chunk || on_chunk(nullptr, k, pos0 + c, err));
3619            }
3620            g_window->prompt_region(false);
3621            return ok;
3622        }
3623    }
3624    int32_t tk[MAXT], out[MAXT];
3625    for (int64_t c = 0; c < n; c += MAXT) {
3626        const int k = (int) std::min<int64_t>(MAXT, n - c);
3627        for (int i = 0; i < k; ++i) tk[i] = (int32_t) tokens[c + i];
3628        if (!g_window->run(k, tk, pos0 + c, false, out, err) || !g_window->commit(k, err)) return false;
3629        if (!g_window->tap_deliver_dec(k, pos0 + c, err)) return false;   // DFlash2
3630        if (on_chunk && !on_chunk(nullptr, k, pos0 + c, err)) return false;
3631    }
3632    return true;
3633}
3634bool mtp_prefill(const int32_t* next_tokens, int64_t n, int64_t cell0, std::string& err) {
3635    if (g_window == nullptr) { err = "metal mtp: no decode window"; return false; }
3636    return g_window->mtp_prefill(next_tokens, n, cell0, err);
3637}
3638bool mtp_draft(int T, const int32_t* tokens, int64_t p, int a, int max_steps, int32_t* drafts, float* probs, float min_p,
3639               int* n_drafts, std::string& err) {
3640    if (g_window == nullptr) { err = "metal mtp: no decode window"; return false; }
3641    const double t0 = now_ms();
3642    const bool ok = g_window->mtp_draft(T, tokens, p, a, max_steps, drafts, probs, min_p, n_drafts, err);
3643    g_window->prof_add(true, now_ms() - t0);
3644    return ok;
3645}
3646
3647#include "prompt_chain.inc"
3648#include "dflash2.inc"
3649
3650}  // namespace strata::metal_engine
3651namespace strata::gpu { void* host_view(const void* device_pointer); }
3652namespace strata::kernels {
3653void mrope_table_set(const int32_t* device_table) {
3654    strata::metal_engine::g_mrope_dev = device_table;
3655    strata::metal_engine::g_mrope_host =
3656        device_table ? (const int32_t*) strata::gpu::host_view(device_table) : nullptr;
3657}
3658const int32_t* mrope_table() { return strata::metal_engine::g_mrope_dev; }
3659}  // namespace strata::kernels
3660namespace strata::metal_engine {
3661
3662}  // namespace strata::metal_engine