Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.
C++
Merge f-mac-ssd f0609f40 (expert streaming from the SSD for Macs whose memory cannot hold the pack)
Niko122193e582d08715
diff --cc metal/src/engine/prompt_chain.incindex 6372b75ab,000000000..1b8513b52mode 100644,000000..100644--- a/metal/src/engine/prompt_chain.inc+++ b/metal/src/engine/prompt_chain.inc@@@ -1,418 -1,0 +1,418 @@@+// metal/src/engine/prompt_chain.inc (included by window.cpp) - the prompt through mac-kern's prompt kernels+// (metal/tests/prompt_chain.cpp's chain, 6f6c555b), into the decode window's own state: chunks of C rows, every+// dense matrix dequantized to fp16 and multiplied on the matrix units, the routed experts as grouped GEMMs, the GDN+// state by the parallel prompt scan, QSA K/V and indexer keys into the window's caches. Added for the engine:+// the PLE block after layer 0 (GEMMs + msl/ple.metal), every row's final residual (the drafter's prompt rows), the+// window's history parity, RoPE table and pending fold. No head: the last prompt token runs as a decode window.+//+// The 8-row-window prompt path stays as the fallback: STRATA_METAL_PROMPT=window, and prompts shorter than+// STRATA_METAL_PROMPT_MIN rows (default 32). STRATA_METAL_PROMPT_CHUNK = C (default 2048). The kernel variants+// follow prompt_chain's defaults: matrix-unit register operands where the GPU has the M5's right-input layout+// (COOP_K4, function constant 7), else the older expert and attention kernels (the M4).++namespace {+constexpr int PC_QB = 2051, PC_QCHUNKS = 33, PC_TM = 16;+struct PcDqArgs { uint32_t n_in, n_out, row_bytes, perm; };+struct PcGemmArgs { int M, N, K, pad; };+struct PcEpiArgs { uint32_t n_tok, n_embd, hc, hc_lr; };+struct PcGdnPArgs { uint32_t n_tok, h_k, h_v, channels; float eps; uint32_t f32; };+struct PcMmPlanArgs { uint32_t n_ent, topk, n_expert, tm, n_blocks; };+struct PcMmArgs { uint64_t gate_off, up_off, down_off, gu_stride, d_stride; uint32_t gu_row, d_row, n_embd, n_ff; };+int pc_unit_of(int t) {+ return t == ref::Q2_0 || t == ref::IQ3_S || t == ref::BF16 || t == 18 || t == 16 || t == 17 || t == 22 ? 16 : 32;+}+} // namespace++bool Window::coop_k4() {+ if (const char* e = std::getenv("COOP_K4")) return std::atoi(e) != 0;+ const int lib = cx_->compile({"mm_bench.metal"}, "#define NO_GGML_COMMON 1\n");+ mtl::Pipeline p = cx_->pipeline(lib, "coop_layout_16_64_32");+ mtl::Buffer out = cx_->alloc(4 * 3 * 32 * 128 * 4);+ mtl::Dispatch d;+ d.p = &p;+ d.args = {mtl::Arg::B(out)};+ d.tg[0] = 32;+ cx_->run({d});+ const int* o = out.as<int>();+ bool k4 = true;+ for (int l = 0; l < 32 && k4; ++l) {+ const int* q = o + l * 128 * 4;+ const int cap = q[2];+ for (int i = 0; i + 3 < cap && k4; i += 4)+ for (int j = 1; j < 4; ++j)+ if (q[(i + j) * 4] != q[i * 4] + j || q[(i + j) * 4 + 1] != q[i * 4 + 1]) { k4 = false; break; }+ }+ cx_->free(out);+ return k4;+}++bool Window::pc_setup(int C) {+ PromptBufs& b = pb_;+ if (b.C >= C) return true;+ const double t0 = now_ms();+ if (b.C == 0) {+ b.lib = cx_->compile({"quant.metal", "units.metal", "mma.metal", "dense_mm.metal", "moe_mm.metal", "gr.metal",+ "gemv.metal", "prompt.metal"});+ b.lgdn = cx_->compile({"gdn.metal", "gdn_prompt.metal"}, "#define NO_GGML_COMMON 1\n");+ b.lqsa = cx_->compile({"qsa.metal", "qsa_prompt.metal"}, "#define NO_GGML_COMMON 1\n");+ b.k4 = coop_k4();+ }+ b = PromptBufs{b.lib, b.lgdn, b.lqsa, b.k4}; // (re)allocated below for the larger chunk+ b.C = C;+ const size_t MT = (size_t) C;+ const int MB = (int) max_cells_ / 4 + 2;+ b.maxrows = (int) MT * TOPK + NEXP * PC_TM;+ const int nblk_max = ((int) MT * TOPK + 1023) / 1024;+ auto F32 = [&](size_t n) { return cx_->alloc(4 * n); };+ auto F16 = [&](size_t n) { return cx_->alloc(2 * n); };+ b.R = F32(MT * HC * N); b.bo = F32(MT * N); b.inj[0] = F32(MT * HC); b.inj[1] = F32(MT * HC); b.xn = F32(MT * HC * N);+ b.xnh = F16(MT * HC * N); b.V = F32(MT * (LR + HC)); b.loh = F16(MT * LR); b.mixed = F32(MT * N); b.mixh = F16(MT * N);+ b.qkv = F32(MT * 10240); b.z = F32(MT * 6144); b.al = F32(MT * 48); b.be = F32(MT * 48); b.yg = F32(MT * 6144);+ b.ygh = F16(MT * 6144); b.gqn = F32(MT * 16 * 128); b.gkn = F32(MT * 16 * 128); b.gvc = F32(MT * 6144);+ b.ggb = F32(MT * 48 * 2); b.gkq = F32(MT * 16); b.go = F32(MT * 6144);+ b.qfull = F32(MT * 12288); b.kcur = F32(MT * 512); b.vcur = F32(MT * 512); b.iqr = F32(MT * 512); b.ikr = F32(MT * 128);+ b.qcur = F32(MT * 24 * 256); b.qcurh = F16(MT * 24 * 256); b.qidx = F32(MT * 4 * 128); b.scores = F32(MT * MB);+ b.qids = cx_->alloc(4 * MT * PC_QB); b.part = F32(MT * PC_QCHUNKS * 24 * 258); b.XQ = F32(4 * MT * 6144 + MT * 384);+ b.xqh = F16(MT * 6144);+ b.logits = F32(MT * NEXP); b.ids = cx_->alloc(4 * MT * TOPK); b.wts = F32(MT * TOPK);+ b.bcnt = cx_->alloc(4 * (size_t) nblk_max * NEXP); b.boff = cx_->alloc(4 * (size_t) nblk_max * NEXP);+ b.eoff = cx_->alloc(4 * NEXP); b.tiles = cx_->alloc(8 * (size_t) (b.maxrows / PC_TM + 1)); b.meta = cx_->alloc(64);+ b.stok = cx_->alloc(4 * (size_t) b.maxrows); b.sw = F32(b.maxrows); b.pos = cx_->alloc(4 * MT * TOPK);+ b.XS = F16((size_t) b.maxrows * N); b.HS = F16((size_t) b.maxrows * NFF); b.YE = F32((size_t) b.maxrows * N);+ b.yr = F32(MT * N); b.gsh = F32(MT * NFF); b.ush = F32(MT * NFF); b.hh = F16(MT * NFF); b.ys = F32(MT * N); b.sgv = F32(MT);+ b.WD = F16((size_t) (LR + HC) * HC * N); b.WU = F16((size_t) HC * N * LR); b.Wqkv = F16((size_t) 10240 * N);+ b.Wz = F16((size_t) 6144 * N); b.Wal = F16((size_t) 48 * N); b.Wbe = F16((size_t) 48 * N); b.Wout = F16((size_t) N * 6144);+ b.Wq = F16((size_t) 12288 * N); b.Wk = F16((size_t) 512 * N); b.Wv = F16((size_t) 512 * N); b.Wiq = F16((size_t) 512 * N);+ b.Wik = F16((size_t) 128 * N); b.Wr = F16((size_t) NEXP * N); b.Wsg = F16((size_t) N); b.Wshg = F16((size_t) NFF * N);+ b.Wshu = F16((size_t) NFF * N); b.Wshd = F16((size_t) N * NFF);+ // the PLE block's rows and projections+ b.pemb = F32(MT * N); b.pembh = F16(MT * N); b.pkey = F32(MT * 10240); b.pval = F32(MT * N); b.keyn = F32(MT * 10240);+ b.qn = F32(MT * 10240); b.gated = F32(MT * 10240); b.normW = F32(MT * 10240);+ b.Wpk = F16((size_t) 10240 * N); b.Wpv = F16((size_t) N * N);+ // the expert GEMM tiles (prompt_chain's defaults): v3 gate/up 16,32,32,4 and down 16,64,32,2 with the M5 layout,+ // else v2+ b.gu3[0] = 16; b.gu3[1] = 32; b.gu3[2] = 32; b.gu3[3] = 4;+ b.dn3[0] = 16; b.dn3[1] = 64; b.dn3[2] = 32; b.dn3[3] = 2;+ b.meta.as<uint32_t>()[2] = b.k4 ? NFF / (b.gu3[1] * b.gu3[3]) : NFF / 64;+ b.meta.as<uint32_t>()[5] = b.k4 ? N / (b.dn3[1] * b.dn3[3]) : N / 64;+ std::fprintf(stderr, "strata metal: prompt kernels (mac-kern's prompt chain) for chunks of %d rows, %s, ready in %.0f ms\n",+ C, b.k4 ? "matrix-unit register operands (COOP_K4)" : "the older expert / attention kernels (no M5 layout)",+ now_ms() - t0);+ return true;+}++// one chunk of nT rows at cells pos0.. (the window state is exactly at pos0 before, at pos0 + nT after)+bool Window::pc_chunk(const int64_t* tokens, int nT, int64_t pos0, std::string& err) {+ PromptBufs& b = pb_;+ strata::core::SessionState& ss = *ss_;+ const double th0 = now_ms();+ // ---- the rows: the embedding into every stream; the PLE table rows+ const gguf::Tensor& te = T("token_embd.weight");+ const size_t rb = ref::row_bytes(te.type, N);+ for (int t = 0; t < nT; ++t) {+ float* r = b.R.as<float>() + (size_t) t * HC * N;- ref::dequant(te.type, (const uint8_t*) f_.map + te.offset + (size_t) tokens[t] * rb, r, N);++ ref::dequant(te.type, (const uint8_t*) W_.ptr + te.offset + (size_t) tokens[t] * rb, r, N);+ for (int c = 1; c < HC; ++c) std::memcpy(r + (size_t) c * N, r, (size_t) N * 4);+ }+ if (ple_on_) {+ std::vector<uint32_t> rows((size_t) nT * strata::kernels::PLE_N_HEADS);+ int32_t prev[2] = {ss.ple_prev[0], ss.ple_prev[1]};+ for (int t = 0; t < nT; ++t) {+ const int32_t tk = (int32_t) tokens[t];+ strata::kernels::ngram_rows(&tk, prev, 1, ss.ple.consts, rows.data() + (size_t) t * strata::kernels::PLE_N_HEADS);+ prev[0] = prev[1];+ prev[1] = tk;+ }+ if (!ss.ple.table->gather_batch(rows.data(), (size_t) nT, b.pemb.as<float>(), err)) return false;+ }+ b.host_ms += now_ms() - th0;+ std::vector<mtl::Dispatch> ds;+ ds.reserve(2400);+ nb_ = false;+ if (pend_fold_ > 0) { // the last window's commit, first+ fold(ds, pend_fold_, 1 - hp_);+ pend_fold_ = 0;+ }+ auto P_ = [&](int l, const std::string& fn, const mtl::Constants& c = {}, const std::string& key = "") {+ return P(l, fn, c, "pc:" + (key.empty() ? fn : key));+ };+ auto D = [&](const mtl::Pipeline* p, std::vector<mtl::Arg> a, uint32_t gx, uint32_t gy, uint32_t tg, uint32_t gz = 1) {+ mtl::Dispatch d;+ d.p = p;+ d.args = std::move(a);+ d.grid[0] = gx; d.grid[1] = gy; d.grid[2] = gz;+ d.tg[0] = tg;+ ds.push_back(std::move(d));+ };+ auto gemm = [&](const mtl::Buffer& A, const mtl::Buffer& B, const mtl::Buffer& Y, int M, int Nn, int K) {+ const int tm = 64, tn = Nn <= 64 ? 32 : 64;+ const std::string fn = "gemm_f16_" + std::to_string(tm) + "_" + std::to_string(tn) + "_4";+ PcGemmArgs g{M, Nn, K, 0};+ D(P_(b.lib, fn), {mtl::Arg::B(A), mtl::Arg::B(B), mtl::Arg::B(Y), mtl::Arg::V(g)}, (Nn + tn - 1) / tn, (M + tm - 1) / tm, 128);+ };+ auto dq = [&](const gguf::Tensor& t, const mtl::Buffer& out, size_t out_off = 0, uint32_t perm = 0) {+ const int n_in = (int) t.shape[0], n_out = t.shape.size() > 1 ? (int) t.shape[1] : 1;+ PcDqArgs a{(uint32_t) n_in, (uint32_t) n_out, (uint32_t) ref::row_bytes(t.type, n_in), perm};+ D(P_(b.lib, "dq_f16_" + std::to_string(t.type)), {mtl::Arg::B(W_, t.offset), mtl::Arg::B(out, out_off), mtl::Arg::V(a)},+ (n_in / pc_unit_of(t.type) + 63) / 64, n_out, 64);+ };+ auto act16 = [&](const mtl::Buffer& x, const mtl::Buffer& xh, size_t n) {+ const uint32_t nn = (uint32_t) n;+ D(P_(b.lib, "act_f16"), {mtl::Arg::B(x), mtl::Arg::B(xh), mtl::Arg::V(nn)}, (nn + 255) / 256, 1, 256);+ };+ int cur_inj = 0;+ auto hc_read = [&](const std::string& pre, bool apply) {+ const gguf::Tensor &tn = T(pre + "_norm.weight"), &tdn = T(pre + "_down.weight"), &tin = T(pre + "_inject.weight"),+ &tup = T(pre + "_up.weight");+ dq(tdn, b.WD);+ dq(tin, b.WD, (size_t) 2 * LR * HC * N);+ GrArgs a{N, HC, LR, (uint32_t) nT, apply ? 1u : 0u, eps_};+ PcEpiArgs ea{(uint32_t) nT, N, HC, LR};+ dq(tup, b.WU, 0, HC);+ D(P_(b.lib, "gr_norm_h"), {mtl::Arg::B(b.R), mtl::Arg::B(b.bo), mtl::Arg::B(b.inj[cur_inj]), mtl::Arg::B(W_, tn.offset),+ mtl::Arg::B(b.xnh), mtl::Arg::V(a)}, HC, nT, 256);+ gemm(b.xnh, b.WD, b.V, nT, LR + HC, HC * N);+ D(P_(b.lib, "gr_epi_down"), {mtl::Arg::B(b.V), mtl::Arg::B(b.loh), mtl::Arg::B(b.inj[1 - cur_inj]), mtl::Arg::V(ea)},+ (nT * (LR + HC) + 255) / 256, 1, 256);+ PcGemmArgs g{nT, HC * N, LR, 0};+ D(P_(b.lib, "gemm_hc_up_64_64_4"), {mtl::Arg::B(b.loh), mtl::Arg::B(b.WU), mtl::Arg::B(b.xnh), mtl::Arg::B(b.mixed),+ mtl::Arg::B(b.mixh), mtl::Arg::V(g), mtl::Arg::V(ea)},+ HC * N / 64, (nT + 63) / 64, 128);+ cur_inj = 1 - cur_inj;+ };+ const int hp = hp_;+ int gi = 0, qi = 0;+ for (int l = 0; l < 48; ++l) {+ const std::string bl = "blk." + std::to_string(l) + ".";+ hc_read(bl + "hc_attn", l > 0 && !(l == 1 && ple_on_));+ if (l % 4 != 3) {+ dq(T(bl + "attn_qkv.weight"), b.Wqkv);+ dq(T(bl + "attn_gate.weight"), b.Wz);+ dq(T(bl + "ssm_alpha.weight"), b.Wal);+ dq(T(bl + "ssm_beta.weight"), b.Wbe);+ dq(T(bl + "ssm_out.weight"), b.Wout);+ gemm(b.mixh, b.Wqkv, b.qkv, nT, 10240, N);+ gemm(b.mixh, b.Wz, b.z, nT, 6144, N);+ gemm(b.mixh, b.Wal, b.al, nT, 48, N);+ gemm(b.mixh, b.Wbe, b.be, nT, 48, N);+ PcGdnPArgs ga{(uint32_t) nT, 16, 48, 10240, eps_, 0};+ D(P_(b.lgdn, "gdn_pre"),+ {mtl::Arg::B(b.qkv), mtl::Arg::B(ghist_[hp][(size_t) gi]), mtl::Arg::B(W_, T(bl + "ssm_conv1d.weight").offset),+ mtl::Arg::B(b.al), mtl::Arg::B(b.be), mtl::Arg::B(W_, T(bl + "ssm_dt.bias").offset),+ mtl::Arg::B(W_, T(bl + "ssm_a").offset), mtl::Arg::B(b.gqn), mtl::Arg::B(b.gkn), mtl::Arg::B(b.gvc),+ mtl::Arg::B(b.ggb), mtl::Arg::B(b.gkq), mtl::Arg::B(ghist_[1 - hp][(size_t) gi]), mtl::Arg::V(ga)},+ 16 + 24, nT, 256);+ D(P_(b.lgdn, "gdn_scanr_4", mtl::Constants().i(6, 0)),+ {mtl::Arg::B(gst_[(size_t) gi]), mtl::Arg::B(b.gqn), mtl::Arg::B(b.gkn), mtl::Arg::B(b.gvc), mtl::Arg::B(b.ggb),+ mtl::Arg::B(b.gkq), mtl::Arg::B(b.go), mtl::Arg::V(ga)},+ 48 * 4, 1, 32 * 4);+ D(P_(b.lgdn, "gdn_post"), {mtl::Arg::B(b.go), mtl::Arg::B(b.z), mtl::Arg::B(W_, T(bl + "ssm_norm.weight").offset),+ mtl::Arg::B(b.ygh), mtl::Arg::B(b.yg), mtl::Arg::V(ga)},+ 48, nT, 128);+ gemm(b.ygh, b.Wout, b.bo, nT, N, 6144);+ ++gi;+ } else {+ dq(T(bl + "attn_q.weight"), b.Wq);+ dq(T(bl + "attn_k.weight"), b.Wk);+ dq(T(bl + "attn_v.weight"), b.Wv);+ dq(T(bl + "indexer.q_proj.weight"), b.Wiq);+ dq(T(bl + "indexer.k_proj.weight"), b.Wik);+ dq(T(bl + "attn_output.weight"), b.Wout);+ gemm(b.mixh, b.Wq, b.qfull, nT, 12288, N);+ gemm(b.mixh, b.Wk, b.kcur, nT, 512, N);+ gemm(b.mixh, b.Wv, b.vcur, nT, 512, N);+ gemm(b.mixh, b.Wiq, b.iqr, nT, 512, N);+ gemm(b.mixh, b.Wik, b.ikr, nT, 128, N);+ QsaArgs a{(uint32_t) pos0, 0, (uint32_t) max_cells_, (uint32_t) nT, eps_};+ D(P_(b.lqsa, "qsa_prep"),+ {mtl::Arg::B(b.qfull), mtl::Arg::B(b.kcur), mtl::Arg::B(b.vcur), mtl::Arg::B(b.iqr), mtl::Arg::B(b.ikr),+ mtl::Arg::B(W_, T(bl + "attn_q_norm.weight").offset), mtl::Arg::B(W_, T(bl + "attn_k_norm.weight").offset),+ mtl::Arg::B(W_, T(bl + "indexer.q_norm.weight").offset), mtl::Arg::B(W_, T(bl + "indexer.k_norm.weight").offset),+ mtl::Arg::B(cs_), mtl::Arg::B(b.qcur), mtl::Arg::B(b.qidx), mtl::Arg::B(kq_[(size_t) qi]), mtl::Arg::B(vq_[(size_t) qi]),+ mtl::Arg::B(ksc_[(size_t) qi]), mtl::Arg::B(vsc_[(size_t) qi]), mtl::Arg::B(tail_[(size_t) qi]),+ mtl::Arg::B(dead_[(size_t) qi]), mtl::Arg::B(pooled_[(size_t) qi]), mtl::Arg::V(a)},+ 33, nT, 256);+ if (pos0 + nT > PC_QB) { // some row's context is past the budget: the indexer selects+ if (b.k4)+ D(P_(b.lqsa, "qsa_score_mm"), {mtl::Arg::B(b.qidx), mtl::Arg::B(pooled_[(size_t) qi]), mtl::Arg::B(dead_[(size_t) qi]),+ mtl::Arg::B(b.scores), mtl::Arg::V(a)},+ (uint32_t) (((pos0 + nT) / 4 + 1 + 63) / 64), (nT + 15) / 16, 128);+ else+ D(P_(b.lqsa, "qsa_score"), {mtl::Arg::B(b.qidx), mtl::Arg::B(pooled_[(size_t) qi]), mtl::Arg::B(dead_[(size_t) qi]),+ mtl::Arg::B(b.scores), mtl::Arg::V(a)},+ (uint32_t) (((pos0 + nT) / 4 + 1 + 7) / 8), nT, 256);+ }+ D(P_(b.lqsa, "qsa_topk"), {mtl::Arg::B(b.scores), mtl::Arg::B(b.qids), mtl::Arg::V(a)}, nT, 1, 1024);+ if (b.k4) {+ const uint32_t nq = (uint32_t) nT * 24 * 256;+ D(P_(b.lqsa, "qsa_q_f16"), {mtl::Arg::B(b.qcur), mtl::Arg::B(b.qcurh), mtl::Arg::V(nq)}, (nq + 255) / 256, 1, 256);+ D(P_(b.lqsa, "qsa_attn_mm", mtl::Constants().b(7, true), "qsa_attn_mm#k4"),+ {mtl::Arg::B(b.qcurh), mtl::Arg::B(kq_[(size_t) qi]), mtl::Arg::B(vq_[(size_t) qi]), mtl::Arg::B(ksc_[(size_t) qi]),+ mtl::Arg::B(vsc_[(size_t) qi]), mtl::Arg::B(b.qids), mtl::Arg::B(b.part), mtl::Arg::V(a)},+ PC_QCHUNKS, 2, 32, nT);+ } else {+ D(P_(b.lqsa, "qsa_attn"), {mtl::Arg::B(b.qcur), mtl::Arg::B(kq_[(size_t) qi]), mtl::Arg::B(vq_[(size_t) qi]),+ mtl::Arg::B(ksc_[(size_t) qi]), mtl::Arg::B(vsc_[(size_t) qi]), mtl::Arg::B(b.qids),+ mtl::Arg::B(b.part), mtl::Arg::V(a)},+ PC_QCHUNKS, 2, 256, nT);+ }+ D(P_(b.lqsa, "qsa_merge"), {mtl::Arg::B(b.part), mtl::Arg::B(b.qfull), mtl::Arg::B(b.XQ), mtl::Arg::V(a)}, 24, nT, 256);+ act16(b.XQ, b.xqh, (size_t) nT * 6144);+ gemm(b.xqh, b.Wout, b.bo, nT, N, 6144);+ ++qi;+ }+ // ---- MoE+ hc_read(bl + "hc_ffn", true);+ const gguf::Tensor &eg = T(bl + "ffn_gate_exps.weight"), &eu = T(bl + "ffn_up_exps.weight"), &ed = T(bl + "ffn_down_exps.weight");+ dq(T(bl + "ffn_gate_inp.weight"), b.Wr);+ dq(T(bl + "ffn_gate_inp_shexp.weight"), b.Wsg);+ dq(T(bl + "ffn_gate_shexp.weight"), b.Wshg);+ dq(T(bl + "ffn_up_shexp.weight"), b.Wshu);+ dq(T(bl + "ffn_down_shexp.weight"), b.Wshd);+ gemm(b.mixh, b.Wr, b.logits, nT, NEXP, N);+ const uint32_t nt = (uint32_t) nT;+ D(P_(b.lib, "route_topk"), {mtl::Arg::B(b.logits), mtl::Arg::B(b.ids), mtl::Arg::B(b.wts), mtl::Arg::V(nt)}, (nT + 7) / 8, 1, 256);+ const int nent = nT * TOPK, nblk = (nent + 1023) / 1024;+ PcMmPlanArgs pa{(uint32_t) nent, TOPK, NEXP, (uint32_t) PC_TM, (uint32_t) nblk};+ const uint32_t nclr = (uint32_t) b.maxrows;+ D(P_(b.lib, "mm_clear"), {mtl::Arg::B(b.stok), mtl::Arg::V(nclr)}, (b.maxrows + 255) / 256, 1, 256);+ D(P_(b.lib, "mm_hist"), {mtl::Arg::B(b.ids), mtl::Arg::B(b.bcnt), mtl::Arg::V(pa)}, nblk, 1, 1024);+ D(P_(b.lib, "mm_scan"), {mtl::Arg::B(b.bcnt), mtl::Arg::B(b.boff), mtl::Arg::B(b.eoff), mtl::Arg::B(b.tiles), mtl::Arg::B(b.meta),+ mtl::Arg::V(pa)}, 1, 1, NEXP);+ D(P_(b.lib, "mm_place"), {mtl::Arg::B(b.ids), mtl::Arg::B(b.wts), mtl::Arg::B(b.boff), mtl::Arg::B(b.eoff), mtl::Arg::B(b.stok),+ mtl::Arg::B(b.sw), mtl::Arg::B(b.pos), mtl::Arg::V(pa)}, nblk, 1, 1024);+ PcMmArgs ma{eg.offset, eu.offset, ed.offset, 0, 0, (uint32_t) ref::row_bytes(eg.type, N), (uint32_t) ref::row_bytes(ed.type, NFF),+ N, NFF};+ ma.gu_stride = (uint64_t) ma.gu_row * NFF;+ ma.d_stride = (uint64_t) ma.d_row * N;+ const uint32_t ne = N;+ mtl::Dispatch g;+ g.p = P_(b.lib, "mm_gather");+ g.args = {mtl::Arg::B(b.mixed), mtl::Arg::B(b.stok), mtl::Arg::B(b.XS), mtl::Arg::V(ne)};+ g.tg[0] = 256;+ g.indirect = &b.meta;+ g.ind_off = 8 * 4;+ ds.push_back(g);+ auto tl3 = [](const int* t) { return std::to_string(t[0]) + "_" + std::to_string(t[1]) + "_" + std::to_string(t[2]) + "_" + std::to_string(t[3]); };+ mtl::Dispatch gu;+ if (b.k4) {+ const std::string fn = "mm_gu3_" + std::to_string(eg.type) + "_" + tl3(b.gu3);+ gu.p = P_(b.lib, fn, mtl::Constants().b(7, true), fn + "#k4");+ } else {+ const std::string fn = "mm_gu2_" + std::to_string(eg.type) + "_16_64_16_2";+ gu.p = P_(b.lib, fn, mtl::Constants().i(5, 0), fn + "#p0");+ }+ gu.args = {mtl::Arg::B(W_), mtl::Arg::B(b.XS), mtl::Arg::B(b.HS), mtl::Arg::B(b.tiles), mtl::Arg::V(ma)};+ gu.tg[0] = b.k4 ? 32 * b.gu3[3] : 64;+ gu.indirect = &b.meta;+ gu.ind_off = 2 * 4;+ ds.push_back(gu);+ mtl::Dispatch dn;+ if (b.k4) {+ const std::string fn = "mm_down3_" + std::to_string(ed.type) + "_" + tl3(b.dn3);+ dn.p = P_(b.lib, fn, mtl::Constants().b(7, true), fn + "#k4");+ } else {+ dn.p = P_(b.lib, "mm_down2_" + std::to_string(ed.type) + (ed.type == ref::IQ4_NL ? "_16_64_32_2" : "_16_64_16_2"));+ }+ dn.args = {mtl::Arg::B(W_), mtl::Arg::B(b.HS), mtl::Arg::B(b.YE), mtl::Arg::B(b.tiles), mtl::Arg::V(ma)};+ dn.tg[0] = b.k4 ? 32 * b.dn3[3] : 64;+ dn.indirect = &b.meta;+ dn.ind_off = 5 * 4;+ ds.push_back(dn);+ const uint32_t ca[4] = {(uint32_t) nT, N, TOPK, 0};+ D(P_(b.lib, "mm_combine"), {mtl::Arg::B(b.YE), mtl::Arg::B(b.pos), mtl::Arg::B(b.sw), mtl::Arg::B(b.yr), mtl::Arg::V(ca)},+ (nT * N + 255) / 256, 1, 256);+ gemm(b.mixh, b.Wshg, b.gsh, nT, NFF, N);+ gemm(b.mixh, b.Wshu, b.ush, nT, NFF, N);+ const uint32_t nh = (uint32_t) nT * NFF;+ D(P_(b.lib, "swiglu_h"), {mtl::Arg::B(b.gsh), mtl::Arg::B(b.ush), mtl::Arg::B(b.hh), mtl::Arg::V(nh)}, (nh + 255) / 256, 1, 256);+ gemm(b.hh, b.Wshd, b.ys, nT, N, NFF);+ gemm(b.mixh, b.Wsg, b.sgv, nT, 1, N);+ const uint32_t oa[2] = {(uint32_t) nT, N};+ D(P_(b.lib, "moe_out"), {mtl::Arg::B(b.yr), mtl::Arg::B(b.ys), mtl::Arg::B(b.sgv), mtl::Arg::B(b.bo), mtl::Arg::V(oa)},+ (nT * N + 255) / 256, 1, 256);+ if (l == 0 && ple_on_) {+ // layer 0's FFN write applied to R, then the PLE block (as the window: msl/ple.metal over nT rows)+ GrArgs a{N, HC, LR, (uint32_t) nT, 1u, eps_};+ D(P_(b.lib, "gr_norm"), {mtl::Arg::B(b.R), mtl::Arg::B(b.bo), mtl::Arg::B(b.inj[cur_inj]),+ mtl::Arg::B(W_, T("blk.1.hc_attn_norm.weight").offset), mtl::Arg::B(b.xn), mtl::Arg::V(a)},+ HC, nT, 256);+ act16(b.pemb, b.pembh, (size_t) nT * N);+ dq(T("blk.1.ple_key.weight"), b.Wpk);+ dq(T("blk.1.ple_value.weight"), b.Wpv);+ gemm(b.pembh, b.Wpk, b.pkey, nT, 10240, N);+ gemm(b.pembh, b.Wpv, b.pval, nT, N, N);+ struct PleArgs { uint32_t n_embd, hc; float eps; } pa2{N, HC, strata::kernels::NG_RMS_EPS};+ auto off = [&](const char* n) { return T(n).offset; };+ D(P(lple_, "ple_gnorm", {}, "ple_gnorm"), {mtl::Arg::B(b.pkey), mtl::Arg::B(W_, off("blk.1.ple_norm_key.weight")),+ mtl::Arg::B(b.keyn), mtl::Arg::V(pa2)}, HC, nT, 256);+ D(P(lple_, "ple_gnorm", {}, "ple_gnorm"), {mtl::Arg::B(b.R), mtl::Arg::B(W_, off("blk.1.ple_norm_query.weight")),+ mtl::Arg::B(b.qn), mtl::Arg::V(pa2)}, HC, nT, 256);+ D(P(lple_, "ple_gate_norm", {}, "ple_gate_norm"),+ {mtl::Arg::B(b.keyn), mtl::Arg::B(b.qn), mtl::Arg::B(b.pval), mtl::Arg::B(W_, off("blk.1.ple_norm_conv.weight")),+ mtl::Arg::B(b.gated), mtl::Arg::B(b.normW), mtl::Arg::V(pa2)}, HC, nT, 256);+ D(P(lple_, "ple_conv_add", {}, "ple_conv_add"),+ {mtl::Arg::B(pleHist_), mtl::Arg::B(b.normW), mtl::Arg::B(W_, off("blk.1.ple_conv1d.weight")), mtl::Arg::B(b.gated),+ mtl::Arg::B(b.R), mtl::Arg::V(pa2)}, HC * N / 256, nT, 256);+ }+ }+ // every row's final residual (the last write applied): the drafter's prompt rows+ {+ GrArgs a{N, HC, LR, (uint32_t) nT, 1u, eps_};+ D(P_(b.lib, "gr_norm"), {mtl::Arg::B(b.R), mtl::Arg::B(b.bo), mtl::Arg::B(b.inj[cur_inj]),+ mtl::Arg::B(W_, T("output_hc_norm.weight").offset), mtl::Arg::B(b.xn), mtl::Arg::V(a)}, HC, nT, 256);+ }+ const double g = cx_->run(ds);+ b.gpu_ms += 1000.0 * g;+ hp_ = 1 - hp_;+ // the host side of the commit: the PLE history (the last 9 normalized rows) and the n-gram context+ if (ple_on_) {+ using namespace strata::kernels;+ const float* nw = b.normW.as<float>();+ float* hist = pleHist_.as<float>();+ for (int c = 0; c < NG_HC_DIM; ++c) {+ float* col = hist + (size_t) c * NG_HIST;+ float tmp[NG_HIST * 2];+ int k = 0;+ const int keep_old = std::max(0, NG_HIST - nT);+ for (int r = NG_HIST - keep_old; r < NG_HIST; ++r) tmp[k++] = col[r];+ for (int t = std::max(0, nT - NG_HIST); t < nT; ++t) tmp[k++] = nw[(size_t) t * NG_HC_DIM + c];+ for (int r = 0; r < NG_HIST; ++r) col[r] = tmp[r];+ }+ }+ for (int t = 0; t < nT; ++t) {+ ss.ple_prev[0] = ss.ple_prev[1];+ ss.ple_prev[1] = (int32_t) tokens[t];+ }+ last_T_ = 0; // nothing to commit+ return true;+}++bool Window::prompt(const int64_t* tokens, int64_t n, int64_t pos0,+ const std::function<bool(const float*, int64_t, int64_t, std::string&)>& on_chunk, std::string& err) {+ static const int C = [] {+ const char* e = std::getenv("STRATA_METAL_PROMPT_CHUNK");+ return std::max(64, std::min(8192, e ? std::atoi(e) : 2048));+ }();+ if (!pc_setup((int) std::min<int64_t>(C, std::max<int64_t>(n, 64)))) { err = "metal prompt: setup failed"; return false; }+ const double t0 = now_ms();+ pb_.gpu_ms = pb_.host_ms = pb_.mtp_ms = 0;+ for (int64_t c = 0; c < n; c += C) {+ const int nT = (int) std::min<int64_t>(C, n - c);+ if (pos0 + c + nT + 1 >= max_cells_) { err = "metal prompt: the prompt runs past the context"; return false; }+ if (!pc_chunk(tokens + c, nT, pos0 + c, err)) return false;+ if (on_chunk) {+ const double tm0 = now_ms();+ mpsrc_ = &pb_.R; // the drafter's prompt rows are this chunk's final residuals+ const bool ok = on_chunk(nullptr, nT, pos0 + c, err);+ mpsrc_ = nullptr;+ pb_.mtp_ms += now_ms() - tm0;+ if (!ok) return false;+ }+ }+ if (std::getenv("STRATA_METAL_TRACE") || std::getenv("STRATA_METAL_PROFILE"))+ std::fprintf(stderr, "strata metal: prompt %lld tokens in %.1f ms (GPU %.1f ms, host rows %.1f ms, drafter rows %.1f ms) "+ "-> %.1f tok/s\n", (long long) n, now_ms() - t0, pb_.gpu_ms, pb_.host_ms, pb_.mtp_ms,+ 1000.0 * (double) n / (now_ms() - t0));+ return true;+}diff --cc metal/src/engine/window.cppindex 3652dd1d8,f5a81c071..44a404ea3--- a/metal/src/engine/window.cpp+++ b/metal/src/engine/window.cpp@@@ -94,6 -87,6 +100,7 @@@ publicbool copy_logits(int t, float* host) const;int64_t vocab() const { return n_vocab_; }bool ready() const { return cx_ != nullptr; }++ bool streaming() const { return stream_; }void set_max_t(int t) { max_t_ = std::min(t, MAXT); }// ---- the MTP draft layer (mtp.hpp's math on mac-kern's kernels; the MTP GGUF from tools/mtp_pack.py)bool mtp_load(const std::string& gguf, int max_t, std::string& err);@@@ -283,13 -299,18 +346,20 @@@ bool Window::init(const strata::core::Mconst double t0 = now_ms();if (!f_.open(shard1, err)) return false;cx_ = std::make_unique<mtl::Context>();- madvise(f_.map, f_.map_bytes, MADV_WILLNEED);- W_ = cx_->wrap(f_.map, f_.map_bytes);- if (W_.handle == nullptr) { err = "metal window: cannot wrap " + shard1 + " as a Metal buffer"; return false; }+ stream_ = ExpertStream::wanted(f_, *cx_);+ if (stream_) {+ // the model does not fit: the dense weights are read into memory below, the experts stream from the SSD+ st_ = std::make_unique<ExpertStream>();+ if (!st_->open(f_, err)) return false;+ } else {+ madvise(f_.map, f_.map_bytes, MADV_WILLNEED);+ W_ = cx_->wrap(f_.map, f_.map_bytes);+ if (W_.handle == nullptr) { err = "metal window: cannot wrap " + shard1 + " as a Metal buffer"; return false; }+ }n_vocab_ = (int64_t) T("output.weight").shape[1];- lib_ = cx_->compile({"quant.metal", "units.metal", "moe.metal", "gemv.metal", "gr.metal", "gr2.metal", "glue.metal"});+ lib_ = cx_->compile({"quant.metal", "units.metal", "moe.metal", "gemv.metal", "router.metal", "gr.metal", "gr2.metal",+ "glue.metal"});+ rcounter_ = cx_->alloc(16);lgdn_ = cx_->compile({"gdn.metal"}, "#define NO_GGML_COMMON 1\n");lqsa_ = cx_->compile({"qsa.metal", "qsa2.metal"}, "#define NO_GGML_COMMON 1\n");lsmp_ = cx_->compile({"sample.metal"}, "#define NO_GGML_COMMON 1\n");@@@ -565,12 -607,18 +662,23 @@@ void Window::layer(std::vector<mtl::Dis}// ---- the MoEgr_read(ds, b + "hc_ffn", true, XF_, false, ntok);- gemv(ds, T(b + "ffn_gate_inp.weight"), XF_, logits_, 512, ntok);- if (stream_ && st_pred_ && l + 1 < 48) { // the next layer's routing guessed from this layer's FFN input+ const gguf::Tensor& trt = T(b + "ffn_gate_inp.weight");+ const bool rf = routef_ && trt.type == ref::BF16;+ if (!rf) {+ gemv(ds, trt, XF_, logits_, 512, ntok);nb_ = true;+ }++ if (stream_ && st_pred_ && l + 1 < 48) { // the next layer's routing guessed from this layer's FFN input++ nb_ = !rf; // beside the router GEMV; with router_route it is the first reader of XF_ here: a barrier+ gemv(ds, T("blk." + std::to_string(l + 1) + ".ffn_gate_inp.weight"), XF_, predL_, 512, ntok,+ (size_t) l * MAXT * 512 * 4);+ if (predL2_.ptr && l + 2 < 48) {+ nb_ = true;+ gemv(ds, T("blk." + std::to_string(l + 2) + ".ffn_gate_inp.weight"), XF_, predL2_, 512, ntok,+ (size_t) l * MAXT * 512 * 4);+ }++ nb_ = true;+ }- nb_ = true;gemv(ds, T(b + "ffn_gate_shexp.weight"), XF_, gsh_, NFF, ntok);nb_ = true;gemv(ds, T(b + "ffn_up_shexp.weight"), XF_, ush_, NFF, ntok);@@@ -765,13 -809,9 +889,14 @@@ bool Window::run(int Tn, const int32_tstd::memcpy(d.args.back().bytes.data(), &a, sizeof a);if (kind == 2) d.grid[0] = (uint32_t) (((pos0 + Tn) / 4 + 1 + 7) / 8);}+ seg_T_ = Tn;const double r0 = now_ms();- last_gpu_ms_ = 1000.0 * cx_->run_graph(c.ds);+ last_gpu_ms_ = 1000.0 * run_ds(c);+ {+ static const int kt = std::getenv("STRATA_METAL_KPROF") ? std::atoi(std::getenv("STRATA_METAL_KPROF")) : 0;+ static int seen = 0;- if (kt == Tn && head && ++seen == 20) kprof(c.ds, Tn);++ if (kt == Tn && head && ++seen == 20 && !stream_) kprof(c.ds, Tn);+ }tp_rg_ = now_ms() - r0;last_n_disp_ = (int) c.ds.size();return finish(Tn, tokens, pos0, head, out, t0);@@@ -1225,8 -1267,8 +1415,8 @@@ void Window::mtp_encode(std::vector<mtlconst size_t rb = ref::row_bytes(te.type, N);if (tokens)for (int i = 0; i < n; ++i)- ref::dequant(te.type, (const uint8_t*) f_.map + te.offset + (size_t) tokens[i] * rb,+ ref::dequant(te.type, (const uint8_t*) W_.ptr + te.offset + (size_t) tokens[i] * rb,- memb_.as<float>() + (size_t) (erow + i) * N, N);+ (membp_ ? *membp_ : memb_).as<float>() + (size_t) (erow + i) * N, N);const std::string L = "mtp.layers.0.";auto rms = [&](const mtl::Buffer& x, size_t xo, const std::string& w, mtl::Buffer& y, int width, int rows) {mtl::Dispatch d;@@@ -1415,21 -1457,13 +1605,22 @@@// the prompt's K/V: cell cell0 + i pairs the main window's final residual row i with the token at cell0 + i + 1bool Window::mtp_prefill(const int32_t* next_tokens, int64_t n, int64_t cell0, std::string& err) {if (!mtp_on_) { err = "metal mtp: not loaded"; return false; }+ // every group of MAXT rows in one command buffer: the embedding rows of all of them in mpemb_ (row c + i)+ if ((int64_t) mpemb_rows_ < n) {+ if (mpemb_rows_ > 0) cx_->free(mpemb_);+ mpemb_rows_ = (size_t) std::max<int64_t>(n, 64);+ mpemb_ = cx_->alloc(4 * mpemb_rows_ * N);+ }+ membp_ = &mpemb_;+ std::vector<mtl::Dispatch> ds;+ nb_ = false;for (int64_t c = 0; c < n; c += MAXT) {const int k = (int) std::min<int64_t>(MAXT, n - c);- mtp_encode(ds, mpsrc_ ? *mpsrc_ : R_, (size_t) c * HC * N * 4, k, next_tokens + c, cell0 + c, false, (int) c, 0);- std::vector<mtl::Dispatch> ds;- nb_ = false;- mtp_encode(ds, mtp_src_ ? *mtp_src_ : R_, (size_t) c * HC * N * 4, k, next_tokens + c, cell0 + c, false);- cx_->run_graph(ds);++ mtp_encode(ds, mpsrc_ ? *mpsrc_ : mtp_src_ ? *mtp_src_ : R_, (size_t) c * HC * N * 4, k, next_tokens + c,++ cell0 + c, false, (int) c, 0);}+ membp_ = nullptr;+ cx_->run_graph(ds);return true;}@@@ -1520,6 -1554,467 +1711,467 @@@ bool Window::copy_logits(int t, float*return true;}++ // ================================================================================== prompts through the matrix units+ // A prompt chunk of T rows (mac-kern's tests/prompt_chain.cpp, on the engine's state): every dense matrix dequantized+ // to fp16 once a chunk and multiplied on the matrix units (MPP), the GDN scan, QSA over the chunk, the routed experts+ // 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+ // PLE history are the decode window's own, so decoding goes on from them. With SSD streaming the experts of a layer+ // are put in place at the layer's handshake (the arena's misses) and the next layer's are streamed in behind it.+ // STRATA_METAL_PROMPT_GEMM=0: prompts through the decode window (8 rows at a time). Its numerics differ from the+ // window's (fp16 operands): STRATA_METAL_PROMPT_GEMM_MIN (default 64) keeps shorter prompts on the window path.+ namespace {+ struct PgDq { uint32_t n_in, n_out, row_bytes, perm; };+ struct PgGemm { int M, N, K, pad; };+ struct PgEpi { uint32_t n_tok, n_embd, hc, hc_lr; };+ struct PgGdnP { uint32_t n_tok, h_k, h_v, channels; float eps; uint32_t f32; };+ struct PgPlan { uint32_t n_ent, topk, n_expert, tm, n_blocks; };+ struct PgMm { uint64_t gate_off, up_off, down_off, gu_stride, d_stride; uint32_t gu_row, d_row, n_embd, n_ff; };+ int pg_unit(int t) { return t == ref::Q2_0 || t == ref::IQ3_S || t == ref::BF16 ? 16 : 32; }+ } // namespace++ struct Window::PromptGemm {+ int MT = 0, QS = 256, TM = 16, maxrows = 0, nblk_max = 0;+ int lib = -1, lgdn = -1, lqsa = -1;+ bool k4 = false, gu_v3 = false, dn_v3 = false, flash = false;+ 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,+ iqr, ikr, qcur, qcurh, qidx, scores, qids, part, XQ, xqh, logits, ids, wts, bcnt, boff, eoff, tiles, meta, stok, sw, pos,+ XS, HS, YE, yr, gsh, ush, hh, ys, sgv, emb, embh, pkey, pval, keyn, qn, gated, normW;+ mtl::Buffer WD, WU, Wqkv, Wz, Wal, Wbe, Wout, Wq, Wk, Wv, Wiq, Wik, Wr, Wsg, Wshg, Wshu, Wshd, Wpk, Wpv;+ };++ int Window::prompt_chunk_rows() const { return pg_ ? pg_->MT : 0; }++ bool Window::prompt_gemm_on(int64_t n) const {+ static const bool on = [] {+ const char* e = std::getenv("STRATA_METAL_PROMPT_GEMM");+ return e ? std::string(e) != "0" : true;+ }();+ static const int64_t mn = [] {+ const char* e = std::getenv("STRATA_METAL_PROMPT_GEMM_MIN");+ return e ? (int64_t) std::atoll(e) : (int64_t) 64;+ }();+ return on && n >= mn && pg_ != nullptr;+ }++ bool Window::prompt_gemm_init(std::string& err) {+ if (pg_) return true;+ if (stream_ && !st_->ready()) return stream_arena(err); // it makes the prompt buffers after the arena+ const char* ec = std::getenv("STRATA_METAL_PROMPT_CHUNK");+ const int C = std::max(64, ec ? std::atoi(ec) : (stream_ ? 1024 : 2048)) / 64 * 64;+ auto pg = std::make_unique<PromptGemm>();+ PromptGemm& p = *pg;+ p.MT = C;+ p.QS = std::min(C, 256);+ p.lib = cx_->compile({"quant.metal", "units.metal", "mma.metal", "dense_mm.metal", "moe_mm.metal", "gr.metal", "gemv.metal",+ "prompt.metal"});+ p.lgdn = cx_->compile({"gdn.metal", "gdn_prompt.metal"}, "#define NO_GGML_COMMON 1\n");+ p.lqsa = cx_->compile({"qsa.metal", "qsa_prompt.metal"}, "#define NO_GGML_COMMON 1\n");- p.k4 = coop_k4(*cx_);++ p.k4 = ::coop_k4(*cx_);+ const char* eg = std::getenv("STRATA_METAL_PROMPT_EXPERTS"); // v2 | v3 (default: v3 with the M5's layout)+ p.gu_v3 = p.dn_v3 = eg ? std::string(eg) == "v3" : p.k4;+ const char* eq = std::getenv("STRATA_METAL_PROMPT_QSA"); // v1 | flash (default: flash with the M5's layout)+ p.flash = eq ? std::string(eq) == "flash" : p.k4;+ const size_t MT = (size_t) C;+ p.maxrows = C * TOPK + NEXP * p.TM;+ p.nblk_max = (C * TOPK + 1023) / 1024;+ const int MB = (int) max_cells_ / 4 + 2;+ // the buffers: measured first, then placed - on a streaming Mac inside the expert arena (a region of its slots+ // reserved only while a prompt runs: the prompt's scratch costs no decode memory), else allocated+ uint64_t need = 0;+ uint8_t* region = nullptr;+ bool measure = true;+ auto AB = [&](size_t bytes) -> mtl::Buffer {+ const size_t b = (bytes + 16383) / 16384 * 16384;+ if (measure) { need += b; return mtl::Buffer{}; }+ if (region == nullptr) return cx_->alloc(bytes);+ mtl::Buffer r = cx_->wrap(region, b);+ region += b;+ return r;+ };+ auto F32 = [&](size_t n) { return AB(4 * n); };+ auto F16 = [&](size_t n) { return AB(2 * n); };+ auto make = [&] {+ const size_t mr = (size_t) p.maxrows;+ 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);+ p.V = F32(MT * (LR + HC)); p.loh = F16(MT * LR); p.mixed = F32(MT * N); p.mixh = F16(MT * N);+ p.qkv = F32(MT * 10240); p.z = F32(MT * 6144); p.al = F32(MT * 48); p.be = F32(MT * 48); p.yg = F32(MT * 6144);+ p.ygh = F16(MT * 6144); p.gqn = F32(MT * 16 * 128); p.gkn = F32(MT * 16 * 128); p.gvc = F32(MT * 6144);+ p.ggb = F32(MT * 96); p.gkq = F32(MT * 16); p.go = F32(MT * 6144);+ p.qfull = F32(MT * 12288); p.kcur = F32(MT * 512); p.vcur = F32(MT * 512); p.iqr = F32(MT * 512); p.ikr = F32(MT * 128);+ p.qcur = F32(MT * 24 * 256); p.qcurh = F16(MT * 24 * 256); p.qidx = F32(MT * 4 * 128); p.scores = F32(MT * (size_t) MB);+ p.qids = AB(4 * MT * 2051);+ p.part = p.flash ? F32(16) : F32((size_t) p.QS * 33 * 24 * 258);+ p.XQ = F32(4 * MT * 6144 + 3 * (size_t) p.QS * 6144 + MT * 384); p.xqh = F16(MT * 6144);+ p.logits = F32(MT * NEXP); p.ids = AB(4 * MT * TOPK); p.wts = F32(MT * TOPK);+ p.bcnt = AB(4 * (size_t) p.nblk_max * NEXP); p.boff = AB(4 * (size_t) p.nblk_max * NEXP);+ p.eoff = AB(4 * NEXP); p.tiles = AB(8 * (mr / p.TM + 1)); p.meta = AB(64);+ 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);+ 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);+ p.ys = F32(MT * N); p.sgv = F32(MT);+ p.WD = F16((size_t) (LR + HC) * HC * N); p.WU = F16((size_t) HC * N * LR); p.Wqkv = F16((size_t) 10240 * N);+ p.Wz = F16((size_t) 6144 * N); p.Wal = F16((size_t) 48 * N); p.Wbe = F16((size_t) 48 * N); p.Wout = F16((size_t) N * 6144);+ p.Wq = F16((size_t) 12288 * N); p.Wk = F16((size_t) 512 * N); p.Wv = F16((size_t) 512 * N); p.Wiq = F16((size_t) 512 * N);+ p.Wik = F16((size_t) 128 * N); p.Wr = F16((size_t) NEXP * N); p.Wsg = F16((size_t) N); p.Wshg = F16((size_t) NFF * N);+ p.Wshu = F16((size_t) NFF * N); p.Wshd = F16((size_t) N * NFF);+ if (ple_on_) {+ p.emb = F32(MT * N); p.embh = F16(MT * N); p.pkey = F32(MT * 10240); p.pval = F32(MT * N); p.keyn = F32(MT * 10240);+ p.qn = F32(MT * 10240); p.gated = F32(MT * 10240); p.normW = F32(MT * 10240);+ p.Wpk = F16((size_t) 10240 * N); p.Wpv = F16((size_t) N * N);+ }+ };+ make();+ measure = false;+ if (stream_) {+ region = st_->region(need);+ if (region == nullptr) { err = "metal prompt: no arena region for the prompt buffers"; return false; }+ }+ make();+ pg_ = pg.release();+ std::fprintf(stderr, "strata metal: prompts on the matrix units in chunks of %d (experts %s, QSA %s, matmul2d layout %s; "+ "%.2f GB of buffers%s)\n", C, p.gu_v3 ? "v3" : "v2", p.flash ? "flash" : "v1", p.k4 ? "K4" : "other",+ need / 1e9, stream_ ? ", in the expert arena while a prompt runs" : "");+ (void) err;+ return true;+ }++ bool Window::prompt_chunk(const int32_t* tokens, int Tn, int64_t pos0, std::string& err) {+ PromptGemm& p = *pg_;+ p.meta.as<uint32_t>()[2] = p.gu_v3 ? NFF / (32 * 4) : NFF / 64;+ p.meta.as<uint32_t>()[5] = p.dn_v3 ? N / (64 * 2) : N / 64;+ auto TN = [this](const std::string& n) -> const gguf::Tensor& { return this->T(n); };+ if (Tn < 1 || Tn > p.MT) { err = "metal prompt: chunk size out of range"; return false; }+ if (pos0 + Tn + 1 >= max_cells_) { err = "metal prompt: the chunk runs past the context"; return false; }+ if (stream_ && !st_->ready() && !stream_arena(err)) return false;+ if (pend_fold_ > 0) { // the last decode window's commit, still pending+ std::vector<mtl::Dispatch> fd;+ nb_ = false;+ fold(fd, pend_fold_, 1 - hp_);+ cx_->run_graph(fd);+ pend_fold_ = 0;+ }+ const int T = Tn;+ // ---- the embeddings into every stream, the PLE rows+ {+ const gguf::Tensor& te = TN("token_embd.weight");+ const size_t rb = ref::row_bytes(te.type, N);+ for (int t = 0; t < T; ++t) {+ float* r = p.R.as<float>() + (size_t) t * HC * N;+ ref::dequant(te.type, (const uint8_t*) W_.ptr + te.offset + (size_t) tokens[t] * rb, r, N);+ for (int c = 1; c < HC; ++c) std::memcpy(r + (size_t) c * N, r, (size_t) N * 4);+ }+ }+ strata::core::SessionState& ss = *ss_;+ if (ple_on_) {+ std::vector<uint32_t> rows((size_t) T * strata::kernels::PLE_N_HEADS);+ int32_t prev[2] = {ss.ple_prev[0], ss.ple_prev[1]};+ for (int t = 0; t < T; ++t) {+ strata::kernels::ngram_rows(&tokens[t], prev, 1, ss.ple.consts, rows.data() + (size_t) t * strata::kernels::PLE_N_HEADS);+ prev[0] = prev[1];+ prev[1] = tokens[t];+ }+ if (!ss.ple.table->gather_batch(rows.data(), (size_t) T, p.emb.as<float>(), err)) return false;+ }+ std::vector<mtl::Dispatch> ds;+ std::vector<int> cuts;+ nb_ = false;+ auto D = [&](const mtl::Pipeline* pp, std::vector<mtl::Arg> a, uint32_t gx, uint32_t gy, uint32_t tg, uint32_t gz = 1) {+ mtl::Dispatch d;+ d.p = pp;+ d.args = std::move(a);+ d.grid[0] = gx; d.grid[1] = gy; d.grid[2] = gz;+ d.tg[0] = tg;+ push(ds, d);+ };+ auto PP = [&](int lib, const std::string& fn, const mtl::Constants& c = {}, const std::string& key = "") {+ return P(lib, fn, c, "pg:" + (key.empty() ? fn : key));+ };+ auto gemm = [&](const mtl::Buffer& A, const mtl::Buffer& B, const mtl::Buffer& Y, int M, int Nn, int K) {+ const int tm = 64, tn = Nn <= 64 ? 32 : 64;+ const std::string fn = "gemm_f16_" + std::to_string(tm) + "_" + std::to_string(tn) + "_4";+ PgGemm g{M, Nn, K, 0};+ 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);+ };+ 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,+ uint32_t perm = 0) {+ PgDq a{(uint32_t) n_in, (uint32_t) n_out, (uint32_t) ref::row_bytes(type, n_in), perm};+ 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)},+ (n_in / pg_unit(type) + 63) / 64, n_out, 64);+ };+ auto dq = [&](const gguf::Tensor& t, const mtl::Buffer& out, size_t out_off = 0, uint32_t perm = 0) {+ const int n_in = (int) t.shape[0], n_out = t.shape.size() > 1 ? (int) t.shape[1] : 1;+ if (hc_q8_ && q8off_.count(t.name)) dqb(Q8_, q8off_.at(t.name), ref::Q8_0, n_in, n_out, out, out_off, perm);+ else dqb(W_, t.offset, t.type, n_in, n_out, out, out_off, perm);+ };+ auto act16 = [&](const mtl::Buffer& x, const mtl::Buffer& xh, size_t n) {+ const uint32_t nn = (uint32_t) n;+ D(PP(p.lib, "act_f16"), {mtl::Arg::B(x), mtl::Arg::B(xh), mtl::Arg::V(nn)}, (nn + 255) / 256, 1, 256);+ };+ int ci = 0;+ auto hc_read = [&](const std::string& pre, bool apply) {+ const gguf::Tensor &tn = TN(pre + "_norm.weight"), &tdn = TN(pre + "_down.weight"), &tin = TN(pre + "_inject.weight"),+ &tup = TN(pre + "_up.weight");+ dq(tdn, p.WD);+ dq(tin, p.WD, (size_t) 2 * LR * HC * N);+ dq(tup, p.WU, 0, HC);+ GrArgs a{N, HC, LR, (uint32_t) T, apply ? 1u : 0u, eps_};+ PgEpi ea{(uint32_t) T, N, HC, LR};+ 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),+ mtl::Arg::B(p.xnh), mtl::Arg::V(a)}, HC, T, 256);+ gemm(p.xnh, p.WD, p.V, T, LR + HC, HC * N);+ 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)},+ (T * (LR + HC) + 255) / 256, 1, 256);+ PgGemm g{T, HC * N, LR, 0};+ 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),+ mtl::Arg::B(p.mixh), mtl::Arg::V(g), mtl::Arg::V(ea)}, HC * N / 64, (T + 63) / 64, 128);+ ci = 1 - ci;+ };+ // the PLE projections (the window's gemv pair as GEMMs)+ if (ple_on_) {+ act16(p.emb, p.embh, (size_t) T * N);+ dq(TN("blk.1.ple_key.weight"), p.Wpk);+ dq(TN("blk.1.ple_value.weight"), p.Wpv);+ gemm(p.embh, p.Wpk, p.pkey, T, 10240, N);+ gemm(p.embh, p.Wpv, p.pval, T, N, N);+ }+ const int MB = (int) max_cells_ / 4 + 2;+ (void) MB;+ for (int l = 0; l < 48; ++l) {+ const std::string b = "blk." + std::to_string(l) + ".";+ hc_read(b + "hc_attn", l > 0 && !(l == 1 && ple_on_));+ if (l % 4 != 3) {+ const int gi = l - l / 4;+ dq(TN(b + "attn_qkv.weight"), p.Wqkv);+ dq(TN(b + "attn_gate.weight"), p.Wz);+ dq(TN(b + "ssm_alpha.weight"), p.Wal);+ dq(TN(b + "ssm_beta.weight"), p.Wbe);+ dq(TN(b + "ssm_out.weight"), p.Wout);+ gemm(p.mixh, p.Wqkv, p.qkv, T, 10240, N);+ gemm(p.mixh, p.Wz, p.z, T, 6144, N);+ gemm(p.mixh, p.Wal, p.al, T, 48, N);+ gemm(p.mixh, p.Wbe, p.be, T, 48, N);+ PgGdnP ga{(uint32_t) T, 16, 48, 10240, eps_, 0};+ D(PP(p.lgdn, "gdn_pre"),+ {mtl::Arg::B(p.qkv), mtl::Arg::B(ghist_[hp_][(size_t) gi]), mtl::Arg::B(W_, TN(b + "ssm_conv1d.weight").offset),+ 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),+ 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),+ mtl::Arg::B(ghist_[1 - hp_][(size_t) gi]), mtl::Arg::V(ga)}, 16 + 24, T, 256);+ D(PP(p.lgdn, "gdn_scanr_4", mtl::Constants().i(6, 0), "gdn_scanr_4"),+ {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),+ mtl::Arg::B(p.gkq), mtl::Arg::B(p.go), mtl::Arg::V(ga)}, 48 * 4, 1, 32 * 4);+ 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),+ mtl::Arg::B(p.ygh), mtl::Arg::B(p.yg), mtl::Arg::V(ga)}, 48, T, 128);+ gemm(p.ygh, p.Wout, p.bo, T, N, 6144);+ } else {+ const int qi = l / 4;+ dq(TN(b + "attn_q.weight"), p.Wq);+ dq(TN(b + "attn_k.weight"), p.Wk);+ dq(TN(b + "attn_v.weight"), p.Wv);+ dq(TN(b + "indexer.q_proj.weight"), p.Wiq);+ dq(TN(b + "indexer.k_proj.weight"), p.Wik);+ dq(TN(b + "attn_output.weight"), p.Wout);+ gemm(p.mixh, p.Wq, p.qfull, T, 12288, N);+ gemm(p.mixh, p.Wk, p.kcur, T, 512, N);+ gemm(p.mixh, p.Wv, p.vcur, T, 512, N);+ gemm(p.mixh, p.Wiq, p.iqr, T, 512, N);+ gemm(p.mixh, p.Wik, p.ikr, T, 128, N);+ QsaArgs a{(uint32_t) pos0, 0, (uint32_t) max_cells_, (uint32_t) T, eps_};+ D(PP(p.lqsa, "qsa_prep"),+ {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),+ mtl::Arg::B(W_, TN(b + "attn_q_norm.weight").offset), mtl::Arg::B(W_, TN(b + "attn_k_norm.weight").offset),+ mtl::Arg::B(W_, TN(b + "indexer.q_norm.weight").offset), mtl::Arg::B(W_, TN(b + "indexer.k_norm.weight").offset),+ 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]),+ mtl::Arg::B(ksc_[(size_t) qi]), mtl::Arg::B(vsc_[(size_t) qi]), mtl::Arg::B(tail_[(size_t) qi]),+ mtl::Arg::B(dead_[(size_t) qi]), mtl::Arg::B(pooled_[(size_t) qi]), mtl::Arg::V(a)}, 33, T, 256);+ if (pos0 + T > 2051)+ 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]),+ mtl::Arg::B(p.scores), mtl::Arg::V(a)},+ (uint32_t) (((pos0 + T) / 4 + 1 + 63) / 64), (T + 15) / 16, 128);+ D(PP(p.lqsa, "qsa_topk"), {mtl::Arg::B(p.scores), mtl::Arg::B(p.qids), mtl::Arg::V(a)}, T, 1, 1024);+ if (p.flash) {+ const uint32_t nq = (uint32_t) T * 24 * 256;+ 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);+ D(PP(p.lqsa, "qsa_flash", mtl::Constants().b(7, p.k4), "qsa_flash"),+ {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]),+ 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)},+ 2, T, 128);+ } else {+ // v1 attention + merge in slices of QS rows (the partials of a slice only)+ for (int t0 = 0; t0 < T; t0 += p.QS) {+ const int ns = std::min(p.QS, T - t0);+ QsaArgs as{(uint32_t) (pos0 + t0), 0, (uint32_t) max_cells_, (uint32_t) ns, eps_};+ D(PP(p.lqsa, "qsa_attn"), {mtl::Arg::B(p.qcur, (size_t) t0 * 24 * 256 * 4), mtl::Arg::B(kq_[(size_t) qi]),+ mtl::Arg::B(vq_[(size_t) qi]), mtl::Arg::B(ksc_[(size_t) qi]), mtl::Arg::B(vsc_[(size_t) qi]),+ mtl::Arg::B(p.qids, (size_t) t0 * 2051 * 4), mtl::Arg::B(p.part), mtl::Arg::V(as)},+ 33, 2, 256, (uint32_t) ns);+ D(PP(p.lqsa, "qsa_merge"), {mtl::Arg::B(p.part), mtl::Arg::B(p.qfull, (size_t) t0 * 12288 * 4),+ mtl::Arg::B(p.XQ, (size_t) t0 * 6144 * 4), mtl::Arg::V(as)}, 24, ns, 256);+ }+ act16(p.XQ, p.xqh, (size_t) T * 6144);+ }+ gemm(p.xqh, p.Wout, p.bo, T, N, 6144);+ }+ if (l == 0 && ple_on_) {+ // layer 0's attention write applied to R happens in the FFN read below; the PLE block comes after the FFN+ }+ // ---- the MoE+ hc_read(b + "hc_ffn", true);+ const gguf::Tensor &tr = TN(b + "ffn_gate_inp.weight"), &tsg = TN(b + "ffn_gate_inp_shexp.weight"),+ &tg_ = TN(b + "ffn_gate_shexp.weight"), &tu_ = TN(b + "ffn_up_shexp.weight"),+ &td_ = TN(b + "ffn_down_shexp.weight"), &eg = TN(b + "ffn_gate_exps.weight"),+ &ed = TN(b + "ffn_down_exps.weight");+ dq(tr, p.Wr);+ dq(tsg, p.Wsg);+ dq(tg_, p.Wshg);+ dq(tu_, p.Wshu);+ dq(td_, p.Wshd);+ gemm(p.mixh, p.Wr, p.logits, T, NEXP, N);+ const uint32_t nt = (uint32_t) T;+ 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)}, (T + 7) / 8, 1, 256);+ const int nent = T * TOPK, nblk = (nent + 1023) / 1024;+ PgPlan pa{(uint32_t) nent, TOPK, NEXP, (uint32_t) p.TM, (uint32_t) nblk};+ const uint32_t nclr = (uint32_t) p.maxrows;+ D(PP(p.lib, "mm_clear"), {mtl::Arg::B(p.stok), mtl::Arg::V(nclr)}, (p.maxrows + 255) / 256, 1, 256);+ D(PP(p.lib, "mm_hist"), {mtl::Arg::B(p.ids), mtl::Arg::B(p.bcnt), mtl::Arg::V(pa)}, nblk, 1, 1024);+ 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),+ mtl::Arg::B(p.meta), mtl::Arg::V(pa)}, 1, 1, NEXP);+ 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),+ mtl::Arg::B(p.stok), mtl::Arg::B(p.sw), mtl::Arg::B(p.pos), mtl::Arg::V(pa)}, nblk, 1, 1024);+ PgMm ma{eg.offset, TN(b + "ffn_up_exps.weight").offset, ed.offset, 0, 0, (uint32_t) ref::row_bytes(eg.type, N),+ (uint32_t) ref::row_bytes(ed.type, NFF), N, NFF};+ ma.gu_stride = (uint64_t) ma.gu_row * NFF;+ ma.d_stride = (uint64_t) ma.d_row * N;+ if (stream_) { ma.gate_off = 0; ma.up_off = st_->up_in_slot(l); ma.down_off = st_->down_in_slot(l); }+ const uint32_t ne_ = N;+ {+ mtl::Dispatch g;+ g.p = PP(p.lib, "mm_gather");+ g.args = {mtl::Arg::B(p.mixed), mtl::Arg::B(p.stok), mtl::Arg::B(p.XS), mtl::Arg::V(ne_)};+ g.tg[0] = 256;+ g.indirect = &p.meta;+ g.ind_off = 8 * 4;+ push(ds, g);+ }+ const mtl::Buffer& EW = stream_ ? st_->chunk(0) : W_;+ auto arena_args = [&](mtl::Dispatch& d) {+ if (!stream_) return;+ d.args.push_back(mtl::Arg::B(st_->smap(), (size_t) l * 512 * 4));+ for (int c = 1; c < 4; ++c) d.args.push_back(mtl::Arg::B(st_->chunk(c)));+ };+ const std::string ak = stream_ ? "#arena" : "";+ mtl::Dispatch gu;+ if (p.gu_v3) {+ const std::string fn = "mm_gu3_" + std::to_string(eg.type) + "_16_32_32_4";+ mtl::Constants c = mtl::Constants().b(7, p.k4);+ if (stream_) c.b(20, true);+ gu.p = PP(p.lib, fn, c, fn + ak);+ gu.tg[0] = 32 * 4;+ } else {+ const std::string fn = "mm_gu2_" + std::to_string(eg.type) + "_16_64_16_2";+ mtl::Constants c = mtl::Constants().i(5, 0);+ if (stream_) c.b(20, true);+ gu.p = PP(p.lib, fn, c, fn + ak);+ gu.tg[0] = 64;+ }+ gu.args = {mtl::Arg::B(EW), mtl::Arg::B(p.XS), mtl::Arg::B(p.HS), mtl::Arg::B(p.tiles), mtl::Arg::V(ma)};+ arena_args(gu);+ gu.indirect = &p.meta;+ gu.ind_off = 2 * 4;+ if (stream_) cuts.push_back((int) ds.size()); // the host's turn: this layer's experts put in place+ push(ds, gu);+ mtl::Dispatch dn;+ if (p.dn_v3) {+ const std::string fn = "mm_down3_" + std::to_string(ed.type) + "_16_64_32_2";+ mtl::Constants c = mtl::Constants().b(7, p.k4);+ if (stream_) c.b(20, true);+ dn.p = PP(p.lib, fn, c, fn + ak);+ dn.tg[0] = 32 * 2;+ } else {+ const std::string fn = "mm_down2_" + std::to_string(ed.type) + (ed.type == ref::IQ4_NL ? "_16_64_32_2" : "_16_64_16_2");+ mtl::Constants c;+ if (stream_) c.b(20, true);+ dn.p = PP(p.lib, fn, c, fn + ak);+ dn.tg[0] = 64;+ }+ dn.args = {mtl::Arg::B(EW), mtl::Arg::B(p.HS), mtl::Arg::B(p.YE), mtl::Arg::B(p.tiles), mtl::Arg::V(ma)};+ arena_args(dn);+ dn.indirect = &p.meta;+ dn.ind_off = 5 * 4;+ push(ds, dn);+ const uint32_t ca[4] = {(uint32_t) T, N, TOPK, 0};+ 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)},+ (T * N + 255) / 256, 1, 256);+ gemm(p.mixh, p.Wshg, p.gsh, T, NFF, N);+ gemm(p.mixh, p.Wshu, p.ush, T, NFF, N);+ const uint32_t nh = (uint32_t) T * NFF;+ 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);+ gemm(p.hh, p.Wshd, p.ys, T, N, NFF);+ gemm(p.mixh, p.Wsg, p.sgv, T, 1, N);+ const uint32_t oa[2] = {(uint32_t) T, N};+ 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)},+ (T * N + 255) / 256, 1, 256);+ if (l == 0 && ple_on_) {+ // layer 0's FFN write applied to R, then the PLE block (as the window, for T rows)+ const gguf::Tensor& tn = TN("blk.1.hc_attn_norm.weight");+ GrArgs a{N, HC, LR, (uint32_t) T, 1u, eps_};+ 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),+ mtl::Arg::B(p.YE), mtl::Arg::V(a)}, HC, T, 256);+ struct PleArgs { uint32_t n_embd, hc; float eps; } pl{N, HC, strata::kernels::NG_RMS_EPS};+ auto off = [&](const char* n) { return TN(n).offset; };+ D(P(lple_, "ple_gnorm", {}, "ple_gnorm"), {mtl::Arg::B(p.pkey), mtl::Arg::B(W_, off("blk.1.ple_norm_key.weight")),+ mtl::Arg::B(p.keyn), mtl::Arg::V(pl)}, HC, T, 256);+ nb_ = true;+ D(P(lple_, "ple_gnorm", {}, "ple_gnorm"), {mtl::Arg::B(p.R), mtl::Arg::B(W_, off("blk.1.ple_norm_query.weight")),+ mtl::Arg::B(p.qn), mtl::Arg::V(pl)}, HC, T, 256);+ D(P(lple_, "ple_gate_norm", {}, "ple_gate_norm"),+ {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")),+ mtl::Arg::B(p.gated), mtl::Arg::B(p.normW), mtl::Arg::V(pl)}, HC, T, 256);+ D(P(lple_, "ple_conv_add", {}, "ple_conv_add"),+ {mtl::Arg::B(pleHist_), mtl::Arg::B(p.normW), mtl::Arg::B(W_, off("blk.1.ple_conv1d.weight")), mtl::Arg::B(p.gated),+ mtl::Arg::B(p.R), mtl::Arg::V(pl)}, HC * N / 256, T, 256);+ }+ }+ // the last layer's write applied to R (the draft layer's K/V read the final residual rows)+ {+ const gguf::Tensor& tn = TN("output_hc_norm.weight");+ GrArgs a{N, HC, LR, (uint32_t) T, 1u, eps_};+ 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),+ mtl::Arg::B(p.YE), mtl::Arg::V(a)}, HC, T, 256);+ }+ const double t0 = now_ms();+ if (stream_) {+ seg_T_ = T;+ cut_ids_ = p.ids.as<int32_t>();+ cx_->run_graph_seg(ds, cuts, [](void* u, int s) { ((Window*) u)->at_cut(s); }, this);+ cut_ids_ = nullptr;+ } else {+ cx_->run_graph(ds);+ }+ pg_ms_ += now_ms() - t0;+ pg_tok_ += T;+ static const bool trace = std::getenv("STRATA_METAL_TRACE") != nullptr;+ if (trace) std::fprintf(stderr, "strata metal: prompt chunk pos %lld, %d rows: %.0f ms\n", (long long) pos0, T, now_ms() - t0);+ // the window's state after the chunk: the conv history turned, the PLE history and token window advanced+ hp_ = 1 - hp_;+ if (ple_on_) {+ using namespace strata::kernels;+ float* hist = pleHist_.as<float>();+ const float* nw = p.normW.as<float>();+ for (int c = 0; c < NG_HC_DIM; ++c) {+ float col[NG_HIST];+ for (int r = 0; r < NG_HIST; ++r) {+ const int src = T - NG_HIST + r; // row r of the new history: chunk row src, or the old history+ col[r] = src >= 0 ? nw[(size_t) src * NG_HC_DIM + c] : hist[(size_t) c * NG_HIST + (size_t) (r + T)];+ }+ std::memcpy(hist + (size_t) c * NG_HIST, col, sizeof col);+ }+ }+ if (T >= 2) { ss.ple_prev[0] = tokens[T - 2]; ss.ple_prev[1] = tokens[T - 1]; }+ else { ss.ple_prev[0] = ss.ple_prev[1]; ss.ple_prev[1] = tokens[0]; }+ mtp_src_ = &p.R; // the draft layer's prompt K/V read this chunk's final rows+ return true;+ }+// ---------------------------------------------------------------------------------------------- the hook's entry pointsnamespace {std::string g_shard1;@@@ -1603,9 -2102,25 +2259,28 @@@ bool mtp_load_pending(Window* w, std::sbool prompt_run(const int64_t* tokens, int64_t n, int64_t pos0,const std::function<bool(const float*, int64_t, int64_t, std::string&)>& on_chunk, std::string& err) {if (g_window == nullptr) { err = "metal prompt: the decode window is not up yet"; return false; }- {+ static const bool windows = std::getenv("STRATA_METAL_PROMPT") && std::string(std::getenv("STRATA_METAL_PROMPT")) == "window";+ static const int64_t min_rows = std::getenv("STRATA_METAL_PROMPT_MIN") ? std::atoll(std::getenv("STRATA_METAL_PROMPT_MIN")) : 32;- if (!windows && n >= min_rows) return g_window->prompt(tokens, n, pos0, on_chunk, err);++ if (!windows && !g_window->streaming() && n >= min_rows) return g_window->prompt(tokens, n, pos0, on_chunk, err);++ if (!windows && g_window->streaming()) {+ const char* e = std::getenv("STRATA_METAL_PROMPT_GEMM");+ const char* em = std::getenv("STRATA_METAL_PROMPT_GEMM_MIN");+ const int64_t mn = em ? std::atoll(em) : 64;+ if (!(e && std::string(e) == "0") && n >= mn) {+ if (!g_window->prompt_gemm_init(err)) return false;+ const int C = g_window->prompt_chunk_rows();+ std::vector<int32_t> tk32((size_t) C);+ g_window->prompt_region(true);+ bool ok = true;+ for (int64_t c = 0; c < n && ok; c += C) {+ const int k = (int) std::min<int64_t>(C, n - c);+ for (int i = 0; i < k; ++i) tk32[(size_t) i] = (int32_t) tokens[c + i];+ ok = g_window->prompt_chunk(tk32.data(), k, pos0 + c, err) && (!on_chunk || on_chunk(nullptr, k, pos0 + c, err));+ }+ g_window->prompt_region(false);+ return ok;+ }+ }int32_t tk[MAXT], out[MAXT];for (int64_t c = 0; c < n; c += MAXT) {const int k = (int) std::min<int64_t>(MAXT, n - c);