From ee2a907e3040d98effaad0e13cce662b1703a6cf Mon Sep 17 00:00:00 2001 From: havok2-htwo Date: Sat, 10 Oct 2026 17:16:06 +0200 Subject: [PATCH 01/33] batch: more than 8 slots with a layer split (8 rows per pipeline group), hand-off sized per slot Measured on 4x RTX 3090 (UD-IQ4_XS): 16 and 32 slots decode bit-identical to solo (tools/batch_test16.py / batch_test32.py); 16 slots 603 tok/s batch decode vs 345 with 8. Rebased on 0.1.42: the stages' batch row check (batch_rows_error, upstream 48f2c47d) bounds hbase + S by the hand-off rows; set_handoff_rows passes the per-slot size there (only above 8 slots). --- include/strata/core/verify.hpp | 4 + src/core/verify.cpp | 4 +- src/program/generate.cpp | 35 +++++-- tools/batch_test16.py | 181 ++++++++++++++++++++++++++++++++ tools/batch_test32.py | 183 +++++++++++++++++++++++++++++++++ 5 files changed, 397 insertions(+), 10 deletions(-) create mode 100644 tools/batch_test16.py create mode 100644 tools/batch_test32.py diff --git a/include/strata/core/verify.hpp b/include/strata/core/verify.hpp index a9dc19db..e190a3b7 100644 --- a/include/strata/core/verify.hpp +++ b/include/strata/core/verify.hpp @@ -170,6 +170,9 @@ public: void set_stage(int64_t layer_begin, int64_t layer_end, const float* handoff_in, float* handoff_out) { lb_ = layer_begin; le_ = layer_end; hand_in_ = handoff_in; hand_out_ = handoff_out; } + /// The rows the hand-off buffers of `set_stage` hold (0: kVerifyMaxT, the default). More than --batch's 8 slots on a + /// layer split: the pipelined slot groups write their rows at hbase = group * rows-per-group, one row per slot. + void set_handoff_rows(int rows) { handoff_rows_ = rows; } /// The next stage: `run` and `commit` continue into it (its pool calls get `next_user`); sampling settings /// and `final_R` are the last stage's. void set_next(Verifier* next, void* next_user) { next_ = next; next_user_ = next_user; } @@ -412,6 +415,7 @@ private: unsigned* qcnt_ = nullptr; ///< S26 STRATA_QFUSE: the HC read's q8_1 group counters (n_embd / 32) unsigned long long* slot_off_d_ = nullptr; ///< E-6: the slot offsets on the device int64_t lb_ = 0, le_ = -1; ///< set_stage: the layers this verifier runs (-1: to the last) + int handoff_rows_ = 0; ///< set_handoff_rows (0: kVerifyMaxT) const float* hand_in_ = nullptr; float* hand_out_ = nullptr; Verifier* next_ = nullptr; diff --git a/src/core/verify.cpp b/src/core/verify.cpp index a8791cc6..f45bf826 100644 --- a/src/core/verify.cpp +++ b/src/core/verify.cpp @@ -2936,9 +2936,9 @@ bool Verifier::stage_batch(const int* rows, int S, int hbase, const int32_t* tok std::string& err) { using namespace strata::kernels; // the row layout: a slot may own a contiguous group of rows (--batch-mtp), also across the stages of a layer split, - // whose hand-off buffers hold kVerifyMaxT rows (a stage that hands rows on or takes them) + // whose hand-off buffers hold kVerifyMaxT rows, or set_handoff_rows' (a stage that hands rows on or takes them) if (const char* why = batch_rows_error(rows, S, pos, (int) slots_.size(), max_t_, hbase, - next_ != nullptr || lb_ > 0, kVerifyMaxT)) { + next_ != nullptr || lb_ > 0, handoff_rows_ > 0 ? handoff_rows_ : kVerifyMaxT)) { err = why; return false; } diff --git a/src/program/generate.cpp b/src/program/generate.cpp index ba00f94d..1a82c5a9 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -4521,9 +4521,17 @@ int main(int argc, char** argv) { std::fprintf(stderr, "strata generate: WARNING: --batch %d is off: %s\n", o.batch, off); o.batch = 0; } else if (o.batch > cap && !batch_mtp) { - std::fprintf(stderr, "strata generate: WARNING: --batch %d: a batch window holds at most %d rows, so %d " - "slots\n", o.batch, cap, cap); - o.batch = cap; + // g3: with a layer split the slots flow through the stages in groups, and a group's window holds + // batch / groups rows - so up to cap rows per group, one group per stage, i.e. cap * stages slots + const int pipe_cap = !stages.empty() && !(o.batch_groups_set && !o.batch_groups_auto && o.batch_groups == 1) ? cap * (int) (stages.size() + 1) : cap; + if (o.batch > pipe_cap) { + std::fprintf(stderr, "strata generate: WARNING: --batch %d: a batch window holds at most %d rows, so %d " + "slots\n", o.batch, cap, pipe_cap); + o.batch = pipe_cap; + } + if (o.batch > cap) + std::fprintf(stderr, "strata generate: --batch %d over %d stages (g3 patch: up to %d rows per group " + "window)\n", o.batch, (int) stages.size() + 1, cap); } } // --batch-groups auto: the pipeline needs one group per GPU stage to keep every card busy (4 x R9700, 8 clients: @@ -4546,6 +4554,13 @@ int main(int argc, char** argv) { r.groups == 1 ? "" : "s", o.batch / r.groups, o.batch / r.groups == 1 ? "" : "s"); }; if (o.batch > 0) resolve_groups_auto(); + if (o.batch > strata::kernels::kVerifyMaxT && !batch_mtp && + (o.batch_groups < 2 || o.batch / std::max(o.batch_groups, 1) > strata::kernels::kVerifyMaxT)) { + const int g_ = std::max(o.batch_groups, 1), keep = strata::kernels::kVerifyMaxT * g_; + std::fprintf(stderr, "strata generate: WARNING: --batch %d in %d group%s exceeds %d rows per window: %d slots\n", + o.batch, g_, g_ == 1 ? "" : "s", (int) strata::kernels::kVerifyMaxT, keep); + o.batch = keep; + } if (o.batch > 0 && o.batch_groups > 1 && (stages.empty() || o.batch % o.batch_groups != 0)) { std::fprintf(stderr, "strata generate: WARNING: --batch-groups %d needs a layer split and to divide --batch %d; " "one group\n", o.batch_groups, o.batch); @@ -7821,8 +7836,10 @@ int main(int argc, char** argv) { } } if (n_stages > 1) { - const size_t hb = (size_t) strata::kernels::kVerifyMaxT * - (size_t) strata::core::Verifier::handoff_floats(g) * sizeof(float); + // g3: pipelined slot groups write their rows at hbase = group * rows-per-group, so with more than + // kVerifyMaxT slots the hand-off must hold one row per slot + const int hrows = std::max(strata::kernels::kVerifyMaxT, o.batch); + const size_t hb = (size_t) hrows * (size_t) strata::core::Verifier::handoff_floats(g) * sizeof(float); std::vector hand((size_t) n_stages - 1, nullptr); for (float*& h : hand) { float* hh = nullptr; @@ -7838,6 +7855,7 @@ int main(int argc, char** argv) { for (int st = 0; st < n_stages; ++st) { stage_ver(st).set_stage(st == 0 ? 0 : split_at[(size_t) st - 1], st + 1 < n_stages ? split_at[(size_t) st] : -1, st == 0 ? nullptr : hand[(size_t) st - 1], st + 1 < n_stages ? hand[(size_t) st] : nullptr); + if (hrows > strata::kernels::kVerifyMaxT) stage_ver(st).set_handoff_rows(hrows); split_drive.end[st] = st + 1 < n_stages ? split_at[(size_t) st] : g.n_layers; split_drive.cache_base[st] = drive.d.cache_base; split_drive.cache_slot_off[st] = drive.d.cache_slot_off; @@ -7846,7 +7864,7 @@ int main(int argc, char** argv) { for (int st = 1; st < n_stages; ++st) { bool ok_s = false; if (split_same) { - ok_s = ver_same.init(wt, g, ss, vh, native_head.loaded() ? &native_head : nullptr, std::max(o.spec, o.batch), err); + ok_s = ver_same.init(wt, g, ss, vh, native_head.loaded() ? &native_head : nullptr, std::max(o.spec, std::min(o.batch, (int) strata::kernels::kVerifyMaxT)), err); } else { GpuStage& gs = *stages[(size_t) st - 1]; const strata::core::OnDevice on(gs.dev); @@ -7862,7 +7880,8 @@ int main(int argc, char** argv) { // rows, the hand-off's size) and bounds its captured batch layouts like the first (below) if (batch_mtp) gs.ver.set_batch_graph_limit(64); ok_s = gs.ver.init(gs.wt, g, gs.ss, vs, gs.head.loaded() ? &gs.head : nullptr, - batch_mtp ? strata::kernels::kVerifyMaxT : std::max(o.spec, o.batch), err); + batch_mtp ? strata::kernels::kVerifyMaxT + : std::max(o.spec, std::min(o.batch, (int) strata::kernels::kVerifyMaxT)), err); split_drive.cache_base[st] = gs.cache.device_slot(0); split_drive.cache_slot_off[st] = gs.cache.slot_offsets(); split_drive.pcie_num[st] = pcie_num_of(gs.pcie_frac); @@ -7940,7 +7959,7 @@ int main(int argc, char** argv) { ver.set_remote_expert_opt(remote_opt.get()); if (batch_mtp) ver.set_batch_graph_limit(64); // --batch-mtp only: slot rotation makes many layouts (LRU); 0.1.39 keeps all if (!ver.init(wt, g, ss, vh, native_head.loaded() || prefill_head_alias_bound ? &native_head : nullptr, - batch_mtp ? strata::kernels::kVerifyMaxT : std::max(o.spec, o.batch), err) || + batch_mtp ? strata::kernels::kVerifyMaxT : std::max(o.spec, std::min(o.batch, (int) strata::kernels::kVerifyMaxT)), err) || (use_mtp && !prefill_head_alias_bound && !mtp.bind(last_st && !mtp_first ? last_st->wt : wt, last_st ? &last_st->head : &native_head, pipe ? pl_mtp_R : ver.final_R_all(), err))) { std::fprintf(stderr, "strata serve: %s\n", err.c_str()); diff --git a/tools/batch_test16.py b/tools/batch_test16.py new file mode 100644 index 00000000..77686d5c --- /dev/null +++ b/tools/batch_test16.py @@ -0,0 +1,181 @@ +#!/usr/bin/env python3 +"""Batching test: the same prompts decoded alone (GEN, the usual path with drafts) and together in the batch +windows (BGEN), greedy. Every slot's tokens must equal its solo tokens; prints the aggregate decode rate. + + python3 tools/batch_test.py --exe engine/strata --config strata-.json --batch 4 --n 4 \ + --extra "--layer-split 12,24,36 --trim-stage-weights --pcie-frac 0 --adapt-every 1000000" +""" +import argparse, json, os, subprocess, sys, tempfile, threading, time +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import strata_tokenizer as ST # noqa: E402 + +QUESTIONS = [ + "Explique en detail le fonctionnement d'un B-tree.", + "Write a Python function that merges overlapping intervals, then explain it.", + "Compare TCP and QUIC: handshake, congestion control, multiplexing.", + "Raconte l'histoire du calcul de pi, d'Archimede a nos jours.", + "What are the main causes of the French Revolution?", + "Explain how a transformer's attention works, step by step.", + "Donne une recette de tarte aux pommes, etape par etape.", + "Describe the life cycle of a star like the Sun.", + "Erklaere ausfuehrlich, wie ein Dieselmotor funktioniert.", + "Write a Rust function that parses a CSV line with quoted fields, then explain it.", + "What were the main consequences of the invention of the printing press?", + "Explique le theoreme de Pythagore avec trois demonstrations differentes.", + "Describe how the immune system responds to a viral infection.", + "Explain the difference between processes and threads in an operating system.", + "Beschreibe die Geschichte des Roemischen Reiches in Grundzuegen.", + "How does public-key cryptography work? Give an example with RSA.", +] + + +def tokenizer(path): + t = Path(path) + vocab = json.loads((t / "vocab.json").read_text(encoding="utf-8")) + tokens = [None] * len(vocab) + for s, i in vocab.items(): + tokens[i] = s + merges = (t / "merges.txt").read_text(encoding="utf-8").split("\n") + types = json.loads((t / "token_type.json").read_text()) + return ST.Tokenizer(tokens, merges, types) + + +class Engine: + def __init__(self, exe, cfg, batch, extra_env, extra_args): + args = list(cfg["args"]) + if len(cfg.get("gpu") or []) > 1: + args += ["--layer-split", str(cfg.get("layer_split") or "auto")] + if batch: + args += ["--batch", str(batch)] + args += extra_args + env = dict(os.environ, **extra_env) + env["LD_LIBRARY_PATH"] = ":".join(cfg.get("lib_dirs", []) + [env.get("LD_LIBRARY_PATH", "")]) + if os.name == "nt": + env["PATH"] = os.pathsep.join(cfg.get("lib_dirs", []) + [env.get("PATH", "")]) + self.log_path = os.environ.get("BATCH_TEST_LOG") or os.path.join(tempfile.gettempdir(), "batch_test_engine.log") + self.log = open(self.log_path, "w") + self.p = subprocess.Popen([exe, "--serve", *args], cwd=cfg.get("cwd"), stdin=subprocess.PIPE, + stdout=subprocess.PIPE, stderr=self.log, text=True, bufsize=1, env=env) + for line in self.p.stdout: + if line.startswith("READY"): + return + raise SystemExit(f"the engine ended before READY - see {self.log_path}") + + def send(self, line): + self.p.stdin.write(line + "\n") + self.p.stdin.flush() + + def lines(self): + for line in self.p.stdout: + yield line.rstrip("\n") + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--exe", required=True) + ap.add_argument("--config", required=True) + ap.add_argument("--batch", type=int, default=4) + ap.add_argument("--n", type=int, default=4, help="prompts (<= --batch)") + ap.add_argument("--max-new", type=int, default=64) + ap.add_argument("--skip-solo", action="store_true") + ap.add_argument("--keys", default="", help='sampling keys for every request, e.g. "temperature=0.7 top_k=20"') + ap.add_argument("--extra", default="", help='more engine arguments in one string, e.g. "--adapt-every 1000000"') + ap.add_argument("--dump", default="", help="write every slot's tokens (solo and batch) as JSON: an A/B of two engine builds") + ap.add_argument("--long-tokens", type=int, default=0, + help="the LAST prompt is read from about this many tokens of filler text first: its chunks run " + "beside the earlier slots' windows (the prompt path lends experts then)") + ap.add_argument("--mt-min", default="1", help="STRATA_IQ_MT_MIN for the engine (1: exact; empty: the default)") + a = ap.parse_args() + cfg = json.loads(Path(a.config).read_text()) + tok = tokenizer(cfg["tokenizer"]) + prompts = [] + for q in QUESTIONS[: a.n]: + text = f"<|im_start|>user\n{q}<|im_end|>\n<|im_start|>assistant\n\n\n\n\n" + if a.long_tokens and q is QUESTIONS[a.n - 1]: + para = ("The committee reviewed item %d of the long agenda, noting the budget, the schedule and the open " + "risks, and asked the staff to report back next quarter. ") + per = max(1, len(tok.encode(para % 100))) + filler = "".join(para % i for i in range(a.long_tokens // per + 1)) + text = f"<|im_start|>user\n{filler}\n\n{q}<|im_end|>\n<|im_start|>assistant\n\n\n\n\n" + prompts.append(tok.encode(text, parse_special=True)) + env = {"STRATA_DECODE_TIMING": "1", **({"STRATA_VERIFY_PROFILE": "1"} if os.environ.get("PROF") else {})} + if a.mt_min: + env["STRATA_IQ_MT_MIN"] = a.mt_min + eng = Engine(a.exe, cfg, a.batch, env, a.extra.split()) + out = eng.lines() + + solo = [] + if not a.skip_solo: + for i, ids in enumerate(prompts): + eng.send(" ".join(x for x in ("GEN", str(a.max_new), a.keys, ",".join(map(str, ids))) if x)) + got, t0 = [], time.time() + for line in out: + if line.startswith("T "): + got.append(int(line.split()[1])) + elif line.startswith("DONE") or line.startswith("ERR"): + print(f"solo {i}: {len(got)} tokens in {time.time() - t0:.1f}s {line[:60]}", flush=True) + break + solo.append(got) + + # batch: admit every prompt, then the slots decode together + got = {i: [] for i in range(len(prompts))} + done = {} + t_admit = time.time() + first_bt = None + for i, ids in enumerate(prompts): + eng.send(" ".join(x for x in ("BGEN", str(i), str(a.max_new), a.keys, ",".join(map(str, ids))) if x)) + for line in out: + if line.startswith("T "): + got[i].append(int(line.split()[1])) + elif line.startswith("BT "): + _, s, y = line.split() + got[int(s)].append(int(y)) + first_bt = first_bt or time.time() + elif line.startswith("BDONE "): + done[int(line.split()[1])] = line + elif line.startswith("ERR"): + print("batch:", line) + return 1 + elif line.startswith("BADM "): + if line.split()[2] == "0": + done[i] = line + break + t_admitted = time.time() + for line in out: + if line.startswith("BT "): + _, s, y = line.split() + got[int(s)].append(int(y)) + first_bt = first_bt or time.time() + elif line.startswith("BDONE "): + done[int(line.split()[1])] = line + if len(done) == len(prompts): + break + elif line.startswith("ERR"): + print("batch:", line) + return 1 + t_end = time.time() + total = sum(len(v) for v in got.values()) + print(f"batch: {len(prompts)} slots, {total} tokens; admissions {t_admitted - t_admit:.1f}s; " + f"then {t_end - t_admitted:.1f}s -> aggregate {total / max(t_end - t_admit, 1e-9):.1f} tok/s overall, " + f"{sum(len(v) for v in got.values()) / max(t_end - (first_bt or t_admit), 1e-9):.1f} tok/s from the first batch token", + flush=True) + ok = True + for i in range(len(prompts)): + b = got[i] + if solo: + same = b == solo[i] + ok &= same + first_diff = next((k for k in range(min(len(b), len(solo[i]))) if b[k] != solo[i][k]), None) + print(f"slot {i}: {len(b)} tokens, solo {len(solo[i])}: {'IDENTICAL' if same else f'DIFFERS at {first_diff}'}") + print(" ", ascii(tok.decode(b)[:160])) + if a.dump: + Path(a.dump).write_text(json.dumps({"solo": solo, "batch": [got[i] for i in range(len(prompts))]}), encoding="utf-8") + eng.send("QUIT") + eng.p.wait(timeout=180) # the next run needs the GPUs back + return 0 if ok else 2 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/batch_test32.py b/tools/batch_test32.py new file mode 100644 index 00000000..fd60e26b --- /dev/null +++ b/tools/batch_test32.py @@ -0,0 +1,183 @@ +#!/usr/bin/env python3 +"""Batching test: the same prompts decoded alone (GEN, the usual path with drafts) and together in the batch +windows (BGEN), greedy. Every slot's tokens must equal its solo tokens; prints the aggregate decode rate. + + python3 tools/batch_test.py --exe engine/strata --config strata-.json --batch 4 --n 4 \ + --extra "--layer-split 12,24,36 --trim-stage-weights --pcie-frac 0 --adapt-every 1000000" +""" +import argparse, json, os, subprocess, sys, tempfile, threading, time +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import strata_tokenizer as ST # noqa: E402 + +QUESTIONS = [ + "Explique en detail le fonctionnement d'un B-tree.", + "Write a Python function that merges overlapping intervals, then explain it.", + "Compare TCP and QUIC: handshake, congestion control, multiplexing.", + "Raconte l'histoire du calcul de pi, d'Archimede a nos jours.", + "What are the main causes of the French Revolution?", + "Explain how a transformer's attention works, step by step.", + "Donne une recette de tarte aux pommes, etape par etape.", + "Describe the life cycle of a star like the Sun.", + "Erklaere ausfuehrlich, wie ein Dieselmotor funktioniert.", + "Write a Rust function that parses a CSV line with quoted fields, then explain it.", + "What were the main consequences of the invention of the printing press?", + "Explique le theoreme de Pythagore avec trois demonstrations differentes.", + "Describe how the immune system responds to a viral infection.", + "Explain the difference between processes and threads in an operating system.", + "Beschreibe die Geschichte des Roemischen Reiches in Grundzuegen.", + "How does public-key cryptography work? Give an example with RSA.", +] + +QUESTIONS = QUESTIONS + [q + " Answer in German." for q in QUESTIONS] + + +def tokenizer(path): + t = Path(path) + vocab = json.loads((t / "vocab.json").read_text(encoding="utf-8")) + tokens = [None] * len(vocab) + for s, i in vocab.items(): + tokens[i] = s + merges = (t / "merges.txt").read_text(encoding="utf-8").split("\n") + types = json.loads((t / "token_type.json").read_text()) + return ST.Tokenizer(tokens, merges, types) + + +class Engine: + def __init__(self, exe, cfg, batch, extra_env, extra_args): + args = list(cfg["args"]) + if len(cfg.get("gpu") or []) > 1: + args += ["--layer-split", str(cfg.get("layer_split") or "auto")] + if batch: + args += ["--batch", str(batch)] + args += extra_args + env = dict(os.environ, **extra_env) + env["LD_LIBRARY_PATH"] = ":".join(cfg.get("lib_dirs", []) + [env.get("LD_LIBRARY_PATH", "")]) + if os.name == "nt": + env["PATH"] = os.pathsep.join(cfg.get("lib_dirs", []) + [env.get("PATH", "")]) + self.log_path = os.environ.get("BATCH_TEST_LOG") or os.path.join(tempfile.gettempdir(), "batch_test_engine.log") + self.log = open(self.log_path, "w") + self.p = subprocess.Popen([exe, "--serve", *args], cwd=cfg.get("cwd"), stdin=subprocess.PIPE, + stdout=subprocess.PIPE, stderr=self.log, text=True, bufsize=1, env=env) + for line in self.p.stdout: + if line.startswith("READY"): + return + raise SystemExit(f"the engine ended before READY - see {self.log_path}") + + def send(self, line): + self.p.stdin.write(line + "\n") + self.p.stdin.flush() + + def lines(self): + for line in self.p.stdout: + yield line.rstrip("\n") + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--exe", required=True) + ap.add_argument("--config", required=True) + ap.add_argument("--batch", type=int, default=4) + ap.add_argument("--n", type=int, default=4, help="prompts (<= --batch)") + ap.add_argument("--max-new", type=int, default=64) + ap.add_argument("--skip-solo", action="store_true") + ap.add_argument("--keys", default="", help='sampling keys for every request, e.g. "temperature=0.7 top_k=20"') + ap.add_argument("--extra", default="", help='more engine arguments in one string, e.g. "--adapt-every 1000000"') + ap.add_argument("--dump", default="", help="write every slot's tokens (solo and batch) as JSON: an A/B of two engine builds") + ap.add_argument("--long-tokens", type=int, default=0, + help="the LAST prompt is read from about this many tokens of filler text first: its chunks run " + "beside the earlier slots' windows (the prompt path lends experts then)") + ap.add_argument("--mt-min", default="1", help="STRATA_IQ_MT_MIN for the engine (1: exact; empty: the default)") + a = ap.parse_args() + cfg = json.loads(Path(a.config).read_text()) + tok = tokenizer(cfg["tokenizer"]) + prompts = [] + for q in QUESTIONS[: a.n]: + text = f"<|im_start|>user\n{q}<|im_end|>\n<|im_start|>assistant\n\n\n\n\n" + if a.long_tokens and q is QUESTIONS[a.n - 1]: + para = ("The committee reviewed item %d of the long agenda, noting the budget, the schedule and the open " + "risks, and asked the staff to report back next quarter. ") + per = max(1, len(tok.encode(para % 100))) + filler = "".join(para % i for i in range(a.long_tokens // per + 1)) + text = f"<|im_start|>user\n{filler}\n\n{q}<|im_end|>\n<|im_start|>assistant\n\n\n\n\n" + prompts.append(tok.encode(text, parse_special=True)) + env = {"STRATA_DECODE_TIMING": "1", **({"STRATA_VERIFY_PROFILE": "1"} if os.environ.get("PROF") else {})} + if a.mt_min: + env["STRATA_IQ_MT_MIN"] = a.mt_min + eng = Engine(a.exe, cfg, a.batch, env, a.extra.split()) + out = eng.lines() + + solo = [] + if not a.skip_solo: + for i, ids in enumerate(prompts): + eng.send(" ".join(x for x in ("GEN", str(a.max_new), a.keys, ",".join(map(str, ids))) if x)) + got, t0 = [], time.time() + for line in out: + if line.startswith("T "): + got.append(int(line.split()[1])) + elif line.startswith("DONE") or line.startswith("ERR"): + print(f"solo {i}: {len(got)} tokens in {time.time() - t0:.1f}s {line[:60]}", flush=True) + break + solo.append(got) + + # batch: admit every prompt, then the slots decode together + got = {i: [] for i in range(len(prompts))} + done = {} + t_admit = time.time() + first_bt = None + for i, ids in enumerate(prompts): + eng.send(" ".join(x for x in ("BGEN", str(i), str(a.max_new), a.keys, ",".join(map(str, ids))) if x)) + for line in out: + if line.startswith("T "): + got[i].append(int(line.split()[1])) + elif line.startswith("BT "): + _, s, y = line.split() + got[int(s)].append(int(y)) + first_bt = first_bt or time.time() + elif line.startswith("BDONE "): + done[int(line.split()[1])] = line + elif line.startswith("ERR"): + print("batch:", line) + return 1 + elif line.startswith("BADM "): + if line.split()[2] == "0": + done[i] = line + break + t_admitted = time.time() + for line in out: + if line.startswith("BT "): + _, s, y = line.split() + got[int(s)].append(int(y)) + first_bt = first_bt or time.time() + elif line.startswith("BDONE "): + done[int(line.split()[1])] = line + if len(done) == len(prompts): + break + elif line.startswith("ERR"): + print("batch:", line) + return 1 + t_end = time.time() + total = sum(len(v) for v in got.values()) + print(f"batch: {len(prompts)} slots, {total} tokens; admissions {t_admitted - t_admit:.1f}s; " + f"then {t_end - t_admitted:.1f}s -> aggregate {total / max(t_end - t_admit, 1e-9):.1f} tok/s overall, " + f"{sum(len(v) for v in got.values()) / max(t_end - (first_bt or t_admit), 1e-9):.1f} tok/s from the first batch token", + flush=True) + ok = True + for i in range(len(prompts)): + b = got[i] + if solo: + same = b == solo[i] + ok &= same + first_diff = next((k for k in range(min(len(b), len(solo[i]))) if b[k] != solo[i][k]), None) + print(f"slot {i}: {len(b)} tokens, solo {len(solo[i])}: {'IDENTICAL' if same else f'DIFFERS at {first_diff}'}") + print(" ", ascii(tok.decode(b)[:160])) + if a.dump: + Path(a.dump).write_text(json.dumps({"solo": solo, "batch": [got[i] for i in range(len(prompts))]}), encoding="utf-8") + eng.send("QUIT") + eng.p.wait(timeout=180) # the next run needs the GPUs back + return 0 if ok else 2 + + +if __name__ == "__main__": + sys.exit(main()) From dd5443646c18913860f0541c6fe1bd5b36c3b29d Mon Sep 17 00:00:00 2001 From: havok2-htwo Date: Sun, 11 Oct 2026 09:30:57 +0200 Subject: [PATCH 02/33] batch: device-to-device slot copy for admissions and slot resumes The main sessions and the batch slot sessions of a stage live on the same device and are carved alike, so copy_to_slot / copy_from_slot (without a checkpoint) now copy the running state and the QSA K/V directly (conversation_checkpoint_copy, conversation_kv_copy: the snapshot code's private non-blocking copy stream, one device sync before and after) instead of the checkpoint/K-V image round trip through host memory with a sync per layer. Same bytes into the same places in the same order; the residency refresh for streamed K/V is shared with conversation_kv_restore. Opt-in: STRATA_SLOT_COPY_DIRECT=1 (default: the host path, as upstream). 4x RTX 3090, UD-IQ4_XS, --batch 16, split 12,24,36 + --trim-stage-weights: admission copy 65.6 -> 34.0 ms average (pure copy ~8 ms); tools/batch_test16.py 16/16 and batch_interleave_test.py (incl. next turn from its slot) identical to solo. --- include/strata/core/conversation_snapshot.hpp | 8 +++ src/core/conversation_snapshot.cpp | 54 +++++++++++++++---- src/core/conversation_state.cpp | 30 +++++++++++ src/program/generate.cpp | 43 +++++++++++++++ 4 files changed, 124 insertions(+), 11 deletions(-) diff --git a/include/strata/core/conversation_snapshot.hpp b/include/strata/core/conversation_snapshot.hpp index 80b1de8b..5a97bff3 100644 --- a/include/strata/core/conversation_snapshot.hpp +++ b/include/strata/core/conversation_snapshot.hpp @@ -25,6 +25,10 @@ bool conversation_kv_validate(const ConversationKv& image, const QsaState& state int64_t upto, bool include_index, std::string& error); bool conversation_kv_restore(const ConversationKv& image, const QsaState& state, const ModelGeometry& g, int64_t upto, bool include_index, std::string& error); +// conversation_kv_save(from) + conversation_kv_restore(to) without a host image, for two states of the same layout. +// The copies are complete on return; the residency refresh is queued on the legacy stream like the restore's. +bool conversation_kv_copy(const QsaState& from, const QsaState& to, const ModelGeometry& g, + int64_t upto, bool include_index, std::string& error); // Diagnostic read-back after a synchronized restore. Uses 64 KiB of stack // workspace, compares authoritative bytes and resident draft-ring pages, and // fingerprints the authoritative payload only. Never changes model state. @@ -60,6 +64,10 @@ bool conversation_checkpoint_save(ConversationCheckpoint& checkpoint, const Sess const ModelGeometry& g, std::string& error); bool conversation_checkpoint_restore(const ConversationCheckpoint& checkpoint, SessionState& session, const ModelGeometry& g, std::string& error); +// conversation_checkpoint_save(from) + conversation_checkpoint_restore(to) of `ids` without a host image, for two +// sessions carved alike on the same device; the caller synchronizes the device before (as for the restore). +bool conversation_checkpoint_copy(const SessionState& from, SessionState& to, const std::vector& ids, + const ModelGeometry& g, std::string& error); struct ConversationView { const std::vector& ids; diff --git a/src/core/conversation_snapshot.cpp b/src/core/conversation_snapshot.cpp index 1468dc65..852e42df 100644 --- a/src/core/conversation_snapshot.cpp +++ b/src/core/conversation_snapshot.cpp @@ -201,17 +201,10 @@ bool conversation_kv_validate(const ConversationKv& image, const QsaState& st, c return true; } -bool conversation_kv_restore(const ConversationKv& image, const QsaState& st, const ModelGeometry& g, - int64_t upto, bool index, std::string& error) { - if (!conversation_kv_validate(image, st, g, upto, index, error)) return false; - const std::array src = {&image.k, &image.v, &image.k_scale, &image.v_scale, &image.pooled}; - const auto dst = pools(st); - for (size_t i = 0; i < src.size(); ++i) - if (!src[i]->visit(0, src[i]->size(), [&](const uint8_t* p, size_t n, size_t at) { - return transfer(static_cast(dst[i]) + at, p, n, error); - })) return false; - // VRAM slots still contain the outgoing conversation. Resolve must refill - // them from the restored authoritative pools before any attention reads. +namespace { +// After the authoritative pools were rewritten: the VRAM slots of a streamed state still hold the outgoing +// conversation, so resolve must refill them before any attention reads (shared by restore and direct copy). +bool refresh_residency(const QsaState& st, const ModelGeometry& g, int64_t upto, std::string& error) { if (st.kv_mode == 1) strata::kernels::kv_stream_reset(st.map, nullptr); if (st.kv_mode == 2 && upto > 0) { auto shapes = strata::kernels::qsa_real_shapes(); @@ -225,6 +218,45 @@ bool conversation_kv_restore(const ConversationKv& image, const QsaState& st, co error = std::string("conversation snapshot residency restore: ") + cudaGetErrorString(status); return false; } +} // namespace + +bool conversation_kv_copy(const QsaState& from, const QsaState& to, const ModelGeometry& g, + int64_t upto, bool index, std::string& error) { + Layout lf{}, lt{}; + if (!layout(from, g, upto, index, lf, error) || !valid(from, lf, upto, error) || + !layout(to, g, upto, index, lt, error) || !valid(to, lt, upto, error)) return false; + if (lf.format != lt.format || lf.cells != lt.cells || lf.page_size != lt.page_size || + lf.pooled_rows != lt.pooled_rows || lf.data != lt.data || lf.value_data != lt.value_data || + lf.scales != lt.scales || lf.value_scales != lt.value_scales || lf.pooled != lt.pooled) { + error = "conversation snapshot: direct K/V copy between different layouts"; + return false; + } + // The same bytes conversation_kv_save + conversation_kv_restore move, without the host image: each part + // straight from the source's authoritative pool into the target's (device or mapped host memory), through the + // private non-blocking stream the other snapshot copies use (complete on return, before the residency refresh). + const auto src = pools(from); + const auto dst = pools(to); + const std::array sizes = {lf.data, lf.value_data, lf.scales, lf.value_scales, lf.pooled}; + for (size_t i = 0; i < sizes.size(); ++i) { + if (!sizes[i]) continue; + if (!src[i] || !dst[i]) { error = "conversation snapshot: missing state buffer"; return false; } + const cudaError_t e = conversation_detail::copy_nonblocking(dst[i], src[i], sizes[i]); + if (e != cudaSuccess) { error = std::string("conversation snapshot direct copy: ") + cudaGetErrorString(e); return false; } + } + return refresh_residency(to, g, upto, error); +} + +bool conversation_kv_restore(const ConversationKv& image, const QsaState& st, const ModelGeometry& g, + int64_t upto, bool index, std::string& error) { + if (!conversation_kv_validate(image, st, g, upto, index, error)) return false; + const std::array src = {&image.k, &image.v, &image.k_scale, &image.v_scale, &image.pooled}; + const auto dst = pools(st); + for (size_t i = 0; i < src.size(); ++i) + if (!src[i]->visit(0, src[i]->size(), [&](const uint8_t* p, size_t n, size_t at) { + return transfer(static_cast(dst[i]) + at, p, n, error); + })) return false; + return refresh_residency(st, g, upto, error); +} bool conversation_kv_part_sizes(const QsaState& st, const ModelGeometry& g, int64_t upto, bool index, std::array& sizes, std::string& error) { diff --git a/src/core/conversation_state.cpp b/src/core/conversation_state.cpp index a93715dd..74f0e474 100644 --- a/src/core/conversation_state.cpp +++ b/src/core/conversation_state.cpp @@ -215,6 +215,36 @@ bool conversation_checkpoint_restore(const ConversationCheckpoint& c, SessionSta return sync(error); } +bool conversation_checkpoint_copy(const SessionState& from, SessionState& to, const std::vector& ids, + const ModelGeometry& g, std::string& error) { + // conversation_checkpoint_save(from) + conversation_checkpoint_restore(to) without the host image, for two + // sessions carved alike on the same device (a stage's own session and its batch slots): the same bytes into + // the same places, through copy() like the restore (the private non-blocking stream, complete on return). + ConversationStateSizes zf, zt; + if (!checkpoint_targets(from, g, ids.size(), zf, error) || !checkpoint_targets(to, g, ids.size(), zt, error)) + return false; + if (zf.gdn != zt.gdn || zf.tail != zt.tail || zf.dead != zt.dead || zf.block_pos != zt.block_pos || + owned_qsa(from) != owned_qsa(to) || (from.ple_hist != nullptr) != (to.ple_hist != nullptr)) + return fail(error, "direct copy between differently carved sessions"); + auto acopy = [&](void* dst, const void* src, size_t bytes) { return copy(dst, src, bytes, error); }; + if (!acopy(to.gdn_state, from.gdn_state, zf.gdn) || + !acopy(to.ple_hist, from.ple_hist, from.ple_hist ? zf.ple : 0)) return false; + for (size_t j = 0; j < owned_qsa(from); ++j) { + const auto& a = owned(from, j); + const auto& b = owned(to, j); + if (!acopy(b.idx_tail, a.idx_tail, zf.tail) || !acopy(b.idx_dead, a.idx_dead, zf.dead) || + !acopy(b.idx_block_pos, a.idx_block_pos, zf.block_pos)) return false; + if (!ids.empty()) { // restore writes the saved `dead` row into the pooled row the next token fills + const size_t row = ids.size() / strata::kernels::qsa_real_shapes().idx_block; + if (!acopy(b.idx_pooled + row * g.idx_key_dim, a.idx_dead, zf.dead)) return false; + } + } + const size_t tokens = ids.size(); + to.ple_prev[0] = tokens >= 2 ? ids[tokens - 2] : -1; + to.ple_prev[1] = tokens >= 1 ? ids[tokens - 1] : -1; + return true; +} + bool conversation_snapshot_bytes(const ConversationView& view, const SessionState& ss, const ModelGeometry& g, const QsaState* draft, size_t& bytes, std::string& error) { bytes = 0; diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 1a82c5a9..1536d16a 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -9881,8 +9881,48 @@ int main(int argc, char** argv) { return true; }; // the session a request just left behind (its prompt) -> slot b's sessions, on every stage + // g3: the main sessions and the slot sessions of a stage live on the same device and are carved alike, so + // a slot copy can go device to device (the same bytes into the same places as the checkpoint/K-V image + // round trip through host memory, which costs ~40-90 ms per admission on a 4-card split); each device is + // synchronized once before and once after. Opt-in: STRATA_SLOT_COPY_DIRECT=1 (default: the host path). + static const bool slot_copy_direct = [] { + const char* v = std::getenv("STRATA_SLOT_COPY_DIRECT"); + return v != nullptr && v[0] != '\0' && v[0] != '0'; + }(); + auto direct_slot_copy = [&](bool into_slot, int b, const std::vector& ids, std::string& e) -> bool { + const int64_t upto = (int64_t) ids.size(); + auto sync_all = [&]() { + bool ok = true; + for (size_t k = 0; k < bslot_ss.size(); ++k) { + const strata::core::OnDevice on_k(k == 0 ? 0 : stages[k - 1]->dev); + ok = cudaDeviceSynchronize() == cudaSuccess && ok; + } + return ok; + }; + // a copy that fails part-way leaves earlier residency refreshes queued on the legacy stream: drain them + // before the caller reuses the sessions (its zeroing runs on non-blocking streams, not ordered against these) + auto failed = [&]() { (void) sync_all(); return false; }; + if (!sync_all()) { e = "batch slot copy: device sync failed"; return false; } + for (size_t k = 0; k < bslot_ss.size(); ++k) { + strata::core::SessionState& main_ss = k == 0 ? ss : stages[k - 1]->ss; + strata::core::SessionState& slot_ss = *bslot_ss[k][(size_t) b]; + strata::core::SessionState& from = into_slot ? main_ss : slot_ss; + strata::core::SessionState& to = into_slot ? slot_ss : main_ss; + const strata::core::OnDevice on_k(k == 0 ? 0 : stages[k - 1]->dev); + if (!strata::core::conversation_checkpoint_copy(from, to, ids, g, e)) return failed(); + for (int64_t j = 0; j < from.qsa_alloc; ++j) + if (!strata::core::conversation_kv_copy(from.qsa_states[from.qsa_ord0 + j], + to.qsa_states[to.qsa_ord0 + j], g, upto, true, e)) + return failed(); + } + if (!sync_all()) { e = "batch slot copy: device sync failed"; return false; } + return true; + }; auto copy_to_slot = [&](int b, const std::vector& ids, std::string& e) -> bool { const int64_t upto = (int64_t) ids.size(); + if (slot_copy_direct) { + if (!direct_slot_copy(true, b, ids, e)) return false; + } else for (size_t k = 0; k < bslot_ss.size(); ++k) { strata::core::SessionState& from = k == 0 ? ss : stages[k - 1]->ss; strata::core::SessionState& to = *bslot_ss[k][(size_t) b]; @@ -9925,6 +9965,9 @@ int main(int argc, char** argv) { auto copy_from_slot = [&](int b, const ConvCheckpoint* at, std::string& e) -> bool { const int64_t upto = at != nullptr ? (int64_t) at->ids.size() : (int64_t) bs[(size_t) b].ids.size(); if (at != nullptr && at->stage_parts.size() != stages.size()) { e = "a checkpoint without its stage parts"; return false; } + if (slot_copy_direct && at == nullptr) { + if (!direct_slot_copy(false, b, bs[(size_t) b].ids, e)) return false; + } else for (size_t k = 0; k < bslot_ss.size(); ++k) { strata::core::SessionState& from = *bslot_ss[k][(size_t) b]; strata::core::SessionState& to = k == 0 ? ss : stages[k - 1]->ss; From 86f677b4a976893e61fb55ac84aa400bfe36e109 Mon Sep 17 00:00:00 2001 From: havok2-htwo Date: Sun, 11 Oct 2026 12:03:24 +0200 Subject: [PATCH 03/33] prefill mmq: pointer-table MMQ (STRATA_MMQ_TAB), prep_group, the bitwise test A Strata-side copy of llama.cpp's MMQ outer scheduler (mul_mat_q, launch_mul_mat_q, mul_mat_q_switch_J; fallback=false only) in src/prefill/moe_mmq_tab.cuh: each expert's base address comes from a 16-entry table passed by value instead of x + z * stride_channel_x. The launch geometry (J, tiles, stream-k grid and k split, fixup) is computed from the same mmq_args, and process_tile / load_tiles / vec_dot / write_back / the fixup kernel are upstream's own templates, so the results are the same bits. Instantiated per type from mmq_tab_instance.cu.in in strata_mmq (same flags); moe_mmq.cu sees declarations only. CMake turns it off unless the SHA-256 of mmq.cuh's mirrored region (mul_mat_q_process_tile through mul_mat_q_case) is a verified one: 3cf03257 (the fetched pin; the vendored tree's mmq.cuh is byte-identical). HIP and SYCL get nothing; Product::tab is a default-null field. Also: overread_bytes, tab_fits, direct_mode (STRATA_MMQ_DIRECT, read once, 0 unless the tab is built), direct_slot_guard, and prep_group (one launch: zero the direct experts' guards and the two group tails). Nothing calls them yet; the default path is unchanged. tests/cuda/prefill_mmq_tab_test.cu (STRATA_BUILD_TESTS): 874 comparisons on an RTX 3090, all bitwise identical - IQ3_S gate/up, IQ4_NL and Q8_0 down (1..16 experts, rows {0,1,7,8,9,31,64,100,512,1000}, every J 8..128, stream-k fixup on and off, max_rows above the largest count), every other instanced type, mixed direct/gathered groups (compact c != q, mid-group flush, last entry direct); negative control: guards left as fp16 NaN give non-finite down outputs. --- CMakeLists.txt | 49 +++ include/strata/prefill/moe_mmq.hpp | 37 ++- src/prefill/mmq_tab_instance.cu.in | 8 + src/prefill/moe_mmq.cu | 146 ++++++++- src/prefill/moe_mmq_tab.cuh | 510 +++++++++++++++++++++++++++++ src/prefill/moe_mmq_tab.hpp | 41 +++ src/prefill/prefill.cpp | 6 + tests/cuda/prefill_mmq_tab_test.cu | 469 ++++++++++++++++++++++++++ 8 files changed, 1264 insertions(+), 2 deletions(-) create mode 100644 src/prefill/mmq_tab_instance.cu.in create mode 100644 src/prefill/moe_mmq_tab.cuh create mode 100644 src/prefill/moe_mmq_tab.hpp create mode 100644 tests/cuda/prefill_mmq_tab_test.cu diff --git a/CMakeLists.txt b/CMakeLists.txt index e28abd9b..c4b684a1 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -85,6 +85,10 @@ if(STRATA_Q6K_EXPERTS) add_compile_definitions(STRATA_Q6K_EXPERTS=1) endif() option(STRATA_ORCA_Q4KS_MMQ "Build the GGML Q5_0 MMQ instance for OrcaRouter Q4_K_S" OFF) +# STRATA_MMQ_DIRECT (opt-in at run time): the prompt path's MMQ reads resident experts in their cache slots through a +# Strata-side copy of llama.cpp's MMQ scheduler with a per-expert pointer table (src/prefill/moe_mmq_tab.cuh). CUDA +# only; switched off at configure time when the llama.cpp tree's mmq.cuh is not one the copy was verified against. +option(STRATA_MMQ_TAB "prompt MMQ reads resident experts in place (STRATA_MMQ_DIRECT=1; CUDA)" ON) if(STRATA_PREFILL_MMQ AND NOT STRATA_ENABLE_HIP) message(FATAL_ERROR "STRATA_PREFILL_MMQ requires STRATA_ENABLE_HIP=ON") endif() @@ -1455,6 +1459,44 @@ if(STRATA_NATIVE_EXPERTS) endif() target_link_libraries(strata_mmq_w4a4 PUBLIC ggml-base ${_strata_gpu_runtime_target}) target_link_libraries(strata_mmq PRIVATE strata_mmq_w4a4) + # STRATA_MMQ_TAB: the pointer-table copy of MMQ's scheduler mirrors mmq.cuh from mul_mat_q_process_tile through + # mul_mat_q_case (struct mmq_args included). A fingerprint of that text instead of a compile probe: nothing is + # compiled at configure time, and a llama.cpp tree with another scheduler turns the feature off instead of + # failing the build. _strata_mmq_tab_known: the hashes moe_mmq_tab.cuh was verified against (3cf03257, the + # fetched pin; the vendored third_party/llama.cpp tree has the same mmq.cuh). + set(_strata_mmq_tab_on OFF) + if(STRATA_MMQ_TAB) + set(_strata_mmq_tab_known 36e4dc716c504470ec09cc0852d29a6ac5eace257f6e5e72db3805ca4f043eb0) + set(_strata_mmq_tab_hash "") + if(EXISTS ${_strata_mmq}/mmq.cuh) + file(READ ${_strata_mmq}/mmq.cuh _strata_mmq_src) + string(REPLACE "\r\n" "\n" _strata_mmq_src "${_strata_mmq_src}") + string(FIND "${_strata_mmq_src}" "static __device__ __forceinline__ void mul_mat_q_process_tile" _strata_tab_a) + string(FIND "${_strata_mmq_src}" "#define DECL_MMQ_CASE" _strata_tab_b) + if(_strata_tab_a GREATER -1 AND _strata_tab_b GREATER _strata_tab_a) + math(EXPR _strata_tab_len "${_strata_tab_b} - ${_strata_tab_a}") + string(SUBSTRING "${_strata_mmq_src}" ${_strata_tab_a} ${_strata_tab_len} _strata_tab_region) + string(SHA256 _strata_mmq_tab_hash "${_strata_tab_region}") + endif() + unset(_strata_mmq_src) + unset(_strata_tab_region) + endif() + if(_strata_mmq_tab_hash AND _strata_mmq_tab_hash IN_LIST _strata_mmq_tab_known) + set(_strata_mmq_tab_on ON) + else() + message(STATUS "STRATA_MMQ_TAB off: mmq.cuh differs from the mirrored scheduler (${_strata_mmq_tab_hash})") + endif() + endif() + if(_strata_mmq_tab_on) + set(_strata_tab_cuh ${CMAKE_CURRENT_SOURCE_DIR}/src/prefill/moe_mmq_tab.cuh) + foreach(_t IN LISTS _strata_mmq_cuda_types) + string(TOUPPER ${_t} _strata_tab_T) + configure_file(src/prefill/mmq_tab_instance.cu.in ${CMAKE_BINARY_DIR}/mmq_tab/mmq-tab-${_t}.cu @ONLY) + target_sources(strata_mmq PRIVATE ${CMAKE_BINARY_DIR}/mmq_tab/mmq-tab-${_t}.cu) + endforeach() + target_compile_definitions(strata_mmq PRIVATE STRATA_MMQ_TAB=1) + message(STATUS "STRATA_MMQ_TAB on: pointer-table MMQ for ${_strata_mmq_cuda_types}") + endif() target_include_directories(strata_mmq PRIVATE ${_strata_gg}/include ${_strata_gg}/src ${_strata_mmq} PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include) target_compile_options(strata_mmq PRIVATE $<$:--extended-lambda -use_fast_math>) @@ -1515,6 +1557,13 @@ if(STRATA_NATIVE_EXPERTS) add_test(NAME prefill_fused_iq_test COMMAND prefill_fused_iq_test) set_tests_properties(prefill_fused_iq_test PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 600) endif() + if(STRATA_BUILD_TESTS AND _strata_mmq_tab_on) + # STRATA_MMQ_DIRECT: the pointer-table MMQ bit for bit against the gathered MMQ (exit 77 below sm_80) + add_executable(prefill_mmq_tab_test tests/cuda/prefill_mmq_tab_test.cu) + target_link_libraries(prefill_mmq_tab_test PRIVATE strata_mmq ggml-base ${_strata_gpu_runtime_target}) + add_test(NAME prefill_mmq_tab_test COMMAND prefill_mmq_tab_test) + set_tests_properties(prefill_mmq_tab_test PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 600) + endif() if(STRATA_BUILD_TESTS AND STRATA_MMQ_KQUANTS) # the UD-Q4_K_XL expert formats through MMQ against ggml's dequantized weights (synthetic, a few seconds) add_executable(prefill_mmq_kquant_test tests/cuda/prefill_mmq_kquant_test.cpp) diff --git a/include/strata/prefill/moe_mmq.hpp b/include/strata/prefill/moe_mmq.hpp index 7c37fb41..3492023c 100644 --- a/include/strata/prefill/moe_mmq.hpp +++ b/include/strata/prefill/moe_mmq.hpp @@ -47,6 +47,14 @@ void scale_gu_rows(float* gu, int64_t ld, int64_t n_ff, const int32_t* bounds, i /// output, not folded into up, where the hidden would sit near 1e-5 (FP16-subnormal block scales in q8 formats). void scale_down_rows(float* d, int64_t ld, const int32_t* bounds, int n, const float* tails, int64_t nrows, void* stream); +constexpr int kGatherGroupMax = 16; +/// STRATA_MMQ_DIRECT: each expert's own weight address (gate|up or down), in place of `w + z * expert_bytes` - +/// expert z < n <= kGatherGroupMax starts at p[z]. The launch (tiles, stream-k split, fixup) is the same as +/// with `w`: only the base address of each expert's matrix changes. +struct WeightTab { + const void* p[kGatherGroupMax] = {}; +}; + /// One launch over n experts whose weights lie `expert_bytes` apart from `w`: for expert e, the activation rows /// [bounds[e], bounds[e+1]) of `xq` (bounds on the device, n+1 entries) times its [w_rows, w_cols] matrix into /// dst rows of the same indices (`ld_dst` floats apart, via `ids`: dst row = ids[row], an identity table works). @@ -64,6 +72,9 @@ struct Product { float* dst = nullptr; int64_t ld_dst = 0; const float* y_scale = nullptr; ///< NVFP4 w4a4: the per-row activation scales (fp4_activations) + /// set: expert z's matrix starts at tab->p[z] (w and expert_bytes are not used for addressing). CUDA only, + /// and only where `tab_fits` said so. + const WeightTab* tab = nullptr; }; /// The launch context (llama.cpp's MMQ keeps a small scratch pool for its stream-k fixup). One per prompt path. @@ -91,7 +102,6 @@ void gather_native(const void* gate, const void* up, size_t gu_half_bytes, const /// each. Every pointer, offset and size 16-byte aligned (false otherwise: nothing launched, gather one at a time). /// NVFP4: `tail_off` (0 = none) is each blob's 16-byte tail, copied to tail_dst + 16 q; `zero_bytes` are zeroed after /// the last expert's gu and d slots (the MMQ tail). -constexpr int kGatherGroupMax = 16; struct GatherGroup { const uint8_t* blob[kGatherGroupMax] = {}; int first = 0, n = 0; @@ -120,4 +130,29 @@ void f16_to_f32(const uint16_t* x, float* y, int64_t n, void* stream); /// dst = {0, rows} (the bounds of one matrix; dst on the device). void set_bounds(int32_t* dst, int32_t rows, void* stream); +// ---- STRATA_MMQ_DIRECT: the prompt MMQ reads resident experts in place (docs: README, "STRATA_MMQ_DIRECT") ---- +/// This build has the pointer-table MMQ (CUDA, STRATA_MMQ_TAB on: the llama.cpp tree matched the mirrored +/// scheduler's fingerprint). false under HIP, SYCL and builds without MMQ. +bool tab_built(); +/// `tab_built`, `fits`, rows a multiple of 128 (no fallback tiles) and a pointer-table instance for the type. +bool tab_fits(int ggml_type, int64_t w_rows); +/// The bytes past a [rows, cols] matrix that its last row's final K tile reads (the largest K tile of any config +/// on any visible GPU): 72 for IQ4_NL and 136 for Q8_0 at 640 columns, 0 for IQ3_S at 2560. 0 without MMQ. +size_t overread_bytes(int ggml_type, int64_t cols); +/// The room kept after each sized expert slot's blob for that over-read (the guard). +constexpr size_t kSlotGuard = 256; +/// STRATA_MMQ_DIRECT, read once: 0 (default) today's gather; 1 the guard layout and resident experts read in +/// place; 2 the guard layout with today's gather (the bitwise A/B reference). 0 whenever !tab_built(). +int direct_mode(); +/// kSlotGuard when direct_mode() != 0, else 0 (no CUDA call). +size_t direct_slot_guard(); +/// The guards a group's direct experts' down over-reads land in (each `guard_bytes` long). +struct GuardTab { + uint8_t* p[kGatherGroupMax] = {}; + int n = 0; +}; +/// One launch: zeroes `guard_bytes` at each g.p[i] and `tail_bytes` at tail_gu and tail_d (null: skipped). It +/// replaces the two tail memsets of a group in direct mode. Nothing is launched when there is nothing to zero. +void prep_group(const GuardTab& g, size_t guard_bytes, void* tail_gu, void* tail_d, size_t tail_bytes, void* stream); + } // namespace strata::prefill::mmq diff --git a/src/prefill/mmq_tab_instance.cu.in b/src/prefill/mmq_tab_instance.cu.in new file mode 100644 index 00000000..10da98b6 --- /dev/null +++ b/src/prefill/mmq_tab_instance.cu.in @@ -0,0 +1,8 @@ +// Generated by CMake from src/prefill/mmq_tab_instance.cu.in (STRATA_MMQ_TAB): the pointer-table MMQ for one type, +// in its own TU so nvcc builds the types in parallel and each object stays small. +#include "@_strata_tab_cuh@" + +namespace strata::prefill::mmq { +template bool mul_mat_q_tab_case(ggml_backend_cuda_context&, const mmq_args&, const mmq_x_tab&, + cudaStream_t); +} // namespace strata::prefill::mmq diff --git a/src/prefill/moe_mmq.cu b/src/prefill/moe_mmq.cu index 9861b607..6b2b019c 100644 --- a/src/prefill/moe_mmq.cu +++ b/src/prefill/moe_mmq.cu @@ -6,9 +6,13 @@ #include "common.cuh" #include "mmq.cuh" #include "quantize.cuh" +#if defined(STRATA_MMQ_TAB) && !defined(__HIPCC__) +#include "moe_mmq_tab.hpp" // declarations only: the tab kernels live in the per-type mmq-tab-*.cu TUs +#endif #include "strata/prefill/mmq_kq_abi.hpp" +#include #include #include #include @@ -173,6 +177,68 @@ __global__ void set_bounds_kernel(int32_t* d, int32_t rows) { unsigned blocks(int64_t n) { return (unsigned) ((n + 255) / 256); } +// STRATA_MMQ_DIRECT: a group's guards (y < g.n, byte stores) and its two zero tails (y == g.n: gate/up, y == g.n + 1: +// down; uint4 stores when `tail16`, which the host checked: both pointers and the size 16-byte aligned) +__global__ void prep_group_kernel(GuardTab g, int64_t guard, uint8_t* tail_gu, uint8_t* tail_d, int64_t tail, bool tail16) { + const int y = (int) blockIdx.y; + const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; + if (y < g.n) { + if (i < guard) g.p[y][i] = 0; + return; + } + uint8_t* t = y == g.n ? tail_gu : tail_d; + if (t == nullptr) return; + if (tail16) { + if (i < tail / 16) ((uint4*) t)[i] = make_uint4(0, 0, 0, 0); + } else if (i < tail) { + t[i] = 0; + } +} + +#if defined(STRATA_MMQ_TAB) && !defined(__HIPCC__) +// the pointer-table MMQ per type: the same types and #ifdefs as Context::run's switch. false: no instance +bool run_tab(ggml_backend_cuda_context* ctx, const mmq_args* a, const mmq_x_tab* tab, cudaStream_t s) { + const ggml_type t = a ? a->type_x : GGML_TYPE_COUNT; +#define STRATA_TAB_CASE(T) case T: return ctx == nullptr || mul_mat_q_tab_case(*ctx, *a, *tab, s) + switch (t) { +#ifdef STRATA_ORCA_Q4KS_MMQ + STRATA_TAB_CASE(GGML_TYPE_Q5_0); +#endif + STRATA_TAB_CASE(GGML_TYPE_Q2_0); + STRATA_TAB_CASE(GGML_TYPE_IQ2_XXS); + STRATA_TAB_CASE(GGML_TYPE_IQ2_XS); + STRATA_TAB_CASE(GGML_TYPE_IQ2_S); + STRATA_TAB_CASE(GGML_TYPE_IQ3_XXS); + STRATA_TAB_CASE(GGML_TYPE_IQ3_S); + STRATA_TAB_CASE(GGML_TYPE_IQ4_NL); + STRATA_TAB_CASE(GGML_TYPE_IQ4_XS); + STRATA_TAB_CASE(GGML_TYPE_Q8_0); +#ifdef STRATA_MMQ_KQUANTS + STRATA_TAB_CASE(GGML_TYPE_Q4_K); + STRATA_TAB_CASE(GGML_TYPE_Q5_K); +#if defined(STRATA_Q6K_EXPERTS) + STRATA_TAB_CASE(GGML_TYPE_Q6_K); +#endif + STRATA_TAB_CASE(GGML_TYPE_Q5_1); +#endif + default: return false; + } +#undef STRATA_TAB_CASE +} +// whether run_tab has an instance for type t (no launch) +bool tab_has_type(int t) { + mmq_args a{}; + a.type_x = (ggml_type) t; + return run_tab(nullptr, &a, nullptr, nullptr); +} +#else +bool run_tab(ggml_backend_cuda_context*, const mmq_args*, const void*, cudaStream_t) { + std::fprintf(stderr, "prefill mmq: this build has no pointer-table MMQ (STRATA_MMQ_TAB)\n"); + std::exit(1); +} +bool tab_has_type(int) { return false; } +#endif + } // namespace // mmq_nvfp4_w4a8.cu: mmq.cuh's int8 NVFP4 path, compiled for this GPU with Blackwell's FP4 MMA hidden @@ -337,11 +403,30 @@ void Context::run(const Product& p, void* stream) { const int64_t qk = ggml_blck_size(t), bpr = p.w_cols / qk; const mmq_args a = {(const char*) p.w, t, (const int*) p.xq, p.ids, p.bounds, p.dst, p.y_scale, p.w_cols, p.w_rows, p.total_rows, bpr, p.total_rows, p.ld_dst, - p.n, p.n, (int64_t) (p.expert_bytes / ggml_type_size(t)), 0, 0, + p.n, p.n, p.tab ? 0 : (int64_t) (p.expert_bytes / ggml_type_size(t)), 0, 0, 1, 1, 0, 0, 0, p.max_rows, p.max_rows}; auto& ctx = *(ggml_backend_cuda_context*) ctx_; const cudaStream_t s = (cudaStream_t) stream; + if (p.tab) { + if (p.n > kGatherGroupMax) { + std::fprintf(stderr, "prefill mmq: a pointer table holds at most %d experts (got %d)\n", kGatherGroupMax, p.n); + std::exit(1); + } +#if defined(STRATA_MMQ_TAB) && !defined(__HIPCC__) + mmq_x_tab tab{}; + for (int z = 0; z < p.n; ++z) tab.p[z] = (const char*) p.tab->p[z]; + if (!run_tab(&ctx, &a, &tab, s)) { + std::fprintf(stderr, "prefill mmq: no pointer-table MMQ for %s with %lld rows\n", ggml_type_name(t), + (long long) p.w_rows); + std::exit(1); + } +#else + run_tab(&ctx, &a, nullptr, s); +#endif + ck(cudaGetLastError(), "mul_mat_q (pointer table)"); + return; + } switch (t) { #ifdef STRATA_ORCA_Q4KS_MMQ case GGML_TYPE_Q5_0: mul_mat_q_case(ctx, a, s); break; @@ -383,6 +468,65 @@ void Context::run(const Product& p, void* stream) { ck(cudaGetLastError(), "mul_mat_q"); } +// ---- STRATA_MMQ_DIRECT ---- +bool tab_built() { +#if defined(STRATA_MMQ_TAB) && !defined(__HIPCC__) + return true; +#else + return false; +#endif +} + +bool tab_fits(int t, int64_t w_rows) { + return tab_built() && w_rows % 128 == 0 && tab_has_type(t) && fits(t, w_rows); +} + +size_t overread_bytes(int t, int64_t cols) { + if (!supported(t)) return 0; + // the longest K tile any (fallback=false) config reads on any visible GPU; MMQ_ITER_K when none is known + int64_t k_vram = MMQ_ITER_K; + const ggml_cuda_device_info& info = ggml_cuda_info(); + for (int id = 0; id < info.device_count; ++id) + for (int J = 8; J <= 128; J += 8) { + const ggml_cuda_mmq_config c = ggml_cuda_mmq_get_config((ggml_type) t, J, false, info.devices[id].cc); + if (c.type != GGML_TYPE_COUNT) k_vram = std::max(k_vram, c.K_vram); + } + const int64_t qk = ggml_blck_size((ggml_type) t), bpi = k_vram / qk, bpn = cols / qk; + if (bpi <= 0) return 0; + return (size_t) ((bpi - bpn % bpi) % bpi) * ggml_type_size((ggml_type) t); +} + +int direct_mode() { + static const int mode = [] { + const char* v = std::getenv("STRATA_MMQ_DIRECT"); + const int m = v ? std::atoi(v) : 0; + if (m != 1 && m != 2) return 0; + if (!tab_built()) { + std::fprintf(stderr, "strata: STRATA_MMQ_DIRECT=%d is ignored: this build has no pointer-table MMQ " + "(CUDA with STRATA_MMQ_TAB only)\n", m); + return 0; + } + return m; + }(); + return mode; +} + +size_t direct_slot_guard() { return direct_mode() != 0 ? kSlotGuard : 0; } + +void prep_group(const GuardTab& g, size_t guard_bytes, void* tail_gu, void* tail_d, size_t tail_bytes, void* stream) { + const int n = g.n > 0 ? std::min(g.n, kGatherGroupMax) : 0; + const size_t guard = n > 0 ? guard_bytes : 0; + const size_t tail = tail_gu || tail_d ? tail_bytes : 0; + if (guard == 0 && tail == 0) return; + GuardTab gt = g; + gt.n = guard > 0 ? n : 0; + const bool tail16 = ((uintptr_t) tail_gu | (uintptr_t) tail_d | tail_bytes) % 16 == 0; + const size_t span = std::max(guard, tail); + prep_group_kernel<<>>( + gt, (int64_t) guard, (uint8_t*) tail_gu, (uint8_t*) tail_d, (int64_t) tail, tail16); + ck(cudaGetLastError(), "prep_group"); +} + void gather_native(const void* gate, const void* up, size_t gu_half_bytes, const void* down, size_t d_bytes, void* gu_dst, void* d_dst, void* stream, const void* tail, void* tail_dst, size_t zero_bytes) { const cudaStream_t s = (cudaStream_t) stream; diff --git a/src/prefill/moe_mmq_tab.cuh b/src/prefill/moe_mmq_tab.cuh new file mode 100644 index 00000000..89099761 --- /dev/null +++ b/src/prefill/moe_mmq_tab.cuh @@ -0,0 +1,510 @@ +// src/prefill/moe_mmq_tab.cuh - STRATA_MMQ_DIRECT: llama.cpp's MMQ outer scheduler (ggml-cuda mmq.cuh, MIT) with a +// per-expert pointer table, so the prompt path's MMQ reads resident experts in their expert-cache slots instead of +// a gathered copy. Included only by the per-type instance TUs (CMake: mmq_tab_instance.cu.in); moe_mmq.cu sees +// the declarations in moe_mmq_tab.hpp. +// +// Mirrored from llama.cpp 3cf03257f219afbe7334045ff7c6a06ac68c627d (the fetched pin; the vendored third_party tree's +// mmq.cuh is byte-identical to it), ggml/src/ggml-cuda/mmq.cuh: +// mul_mat_q lines 953-1238 -> mul_mat_q_tab +// launch_mul_mat_q lines 1395-1475 -> launch_mul_mat_q_tab +// mul_mat_q_switch_J lines 1477-1558 -> mul_mat_q_tab_switch_J +// fallback = false only (mul_mat_q_tab_case refuses rows % 128 != 0). Everything else is the upstream text, and +// mul_mat_q_process_tile, the tile loaders, vec_dot, write_back and mul_mat_q_stream_k_fixup are upstream's own +// templates from the same mmq.cuh, compiled in the same target with the same flags. Deliberate deviations: +// 1. at the three offset_x sites the expert's base is `tab.p[fastdiv(zt, channel_ratio)]` and the +// fastdiv(zt, channel_ratio)*stride_channel_x term leaves offset_x (stride_channel_x is still passed, unused); +// 2. the launcher raises the shared-memory limit of mul_mat_q_tab only - upstream's line for +// mul_mat_q is dropped, so no fallback=true kernel is instantiated. +// The launch geometry (J, tiles, the stream-k grid and k split, the fixup) is computed from the same mmq_args as +// upstream's, so every output tile is summed in the same order: the results are bitwise the same as gathering the +// experts `stride_channel_x` apart (tests/cuda/prefill_mmq_tab_test.cu checks it per type and J). +// CMake turns STRATA_MMQ_TAB off unless the SHA-256 of mmq.cuh's mirrored region (mul_mat_q_process_tile through +// mul_mat_q_case, which includes struct mmq_args) is one this copy was verified against; when the llama.cpp pin +// moves, re-sync this file, re-run the test and record the new hash in CMakeLists.txt (_strata_mmq_tab_known). +#pragma once + +#include "mmq.cuh" +#include "moe_mmq_tab.hpp" + +#include + +namespace strata::prefill::mmq { + +// A second net behind the configure fingerprint: the upstream templates this copy calls keep their signatures. +static_assert(std::is_same), + void (*)(const char*, int, const int*, const int*, float*, float*, const float*, int, int, int, + int, int, int, int)>::value, + "mmq.cuh: mul_mat_q_process_tile changed - re-sync src/prefill/moe_mmq_tab.cuh"); +static_assert(std::is_same), + void (*)(const int32_t*, const int32_t*, float*, float*, uint3, int, int, int, uint3, int, + uint3, int, uint3)>::value, + "mmq.cuh: mul_mat_q_stream_k_fixup changed - re-sync src/prefill/moe_mmq_tab.cuh"); + +// ---- mirrored: mul_mat_q (fallback = false, per-expert base from `tab`) ---- +template +__launch_bounds__(ggml_cuda_mmq_get_nthreads(type, J, false), ggml_cuda_mmq_get_occupancy(type, J, false)) +static __global__ void mul_mat_q_tab( + const mmq_x_tab tab, const int * __restrict__ y, const int32_t * __restrict__ ids_dst, + const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup, + const float * __restrict__ y_scale, + const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst, + const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst, + const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst, + const uint3 ntx) { + constexpr bool fallback = false; // STRATA: the tab copy has no fallback (rows % 128 == 0) instantiation + + // Skip unused template specializations for faster compilation: + if (ggml_cuda_mmq_get_config(type, J, fallback).type == GGML_TYPE_COUNT) { + NO_DEVICE_CODE; + return; + } + + constexpr int warp_size = ggml_cuda_get_physical_warp_size(); + constexpr int nwarps = ggml_cuda_mmq_get_nthreads(type, J, fallback) / warp_size; + constexpr int qk = ggml_cuda_type_traits::qk; + constexpr int I = ggml_cuda_mmq_get_I(type, J, fallback); + + const uint32_t nty = (nrows_x + I - 1) / I; // Number of tiles y + + // Initialize the ids for writing back data with just the index. + // For regular matrix multiplications this is never changed. + // For MoE the correct indices are loaded from ids_dst. + extern __shared__ int ids_dst_shared[]; // Stored at beginning of shared memory. +#pragma unroll + for (int j0 = 0; j0 < J; j0 += nwarps*warp_size) { + const int j = j0 + threadIdx.y*warp_size + threadIdx.x; + + if (j0 + nwarps*warp_size > J && j >= J) { + break; + } + + ids_dst_shared[j] = j; + } + __syncthreads(); + + if constexpr (!ggml_cuda_mmq_get_stream_k(type, J, fallback)) { + const uint2 tmp2 = fast_div_modulo(blockIdx.z, nchannels_y); + const int wt = tmp2.x; + const int zt = tmp2.y; + const int jt = blockIdx.y; + const int it = blockIdx.x; + + // Defaults for regular matrix multiplication: + int col_low = 0; + int col_high = ncols_dst; + int col_diff = ncols_dst; + int offset_y = wt*stride_sample_y + zt*stride_channel_y; + int offset_dst = wt*stride_sample_dst + zt*stride_channel_dst + jt*J*stride_col_dst; + int offset_y_scale; + if constexpr (type == GGML_TYPE_NVFP4) { + offset_y_scale = wt*nchannels_y.z*ncols_y + zt*ncols_y; + } else { + GGML_UNUSED(offset_y_scale); + } + + if (ids_dst) { + col_low = expert_bounds[zt + 0]; + col_high = expert_bounds[zt + 1]; + col_diff = col_high - col_low; + + offset_y = 0; + offset_dst = 0; + if constexpr (type == GGML_TYPE_NVFP4) { + offset_y_scale = 0; + } + + if (jt*J >= col_diff) { + return; + } + + // __syncthreads(); // There is no previous tile that could cause a race condition. +#pragma unroll + for (int j0 = 0; j0 < J; j0 += nwarps*warp_size) { + const int j = j0 + threadIdx.y*warp_size + threadIdx.x; + + if (j0 + nwarps*warp_size > J && j >= J) { + break; + } + + ids_dst_shared[j] = ids_dst[col_low + jt*J + j]; + } + __syncthreads(); + } + + offset_y += (col_low + jt*J)*(sizeof(block_q8_1_mmq)/sizeof(int)); + offset_dst += it*I; + const float * y_scale_tile = nullptr; + if constexpr (type == GGML_TYPE_NVFP4) { + offset_y_scale += col_low + jt*J; + y_scale_tile = y_scale ? y_scale + offset_y_scale : nullptr; + } + + const int tile_x_max_i = nrows_x - it*I - 1; + const int tile_y_max_j = col_diff - jt*J - 1; + + const char * xz = tab.p[fastdiv(zt, channel_ratio)]; // STRATA: per-expert base + const int offset_x = fastdiv(wt, sample_ratio)*stride_sample_x + it*I*stride_row_x; + + constexpr bool fixup = false; + mul_mat_q_process_tile + (xz, offset_x, y + offset_y, ids_dst_shared, dst + offset_dst, tmp_fixup, y_scale_tile, + stride_row_x, ncols_y, stride_col_dst, + tile_x_max_i, tile_y_max_j, 0, blocks_per_ne00.z); + return; + } + + constexpr int ITER_K = ggml_cuda_mmq_get_K_vram(type, J, fallback); + constexpr int blocks_per_iter = ITER_K / qk; + + // kbc == k block continuous, current index in continuous ijk space. + int kbc = int64_t(blockIdx.x) *(nsamples_y.z*nchannels_y.z*ntx.z*nty*blocks_per_ne00.z) / gridDim.x; + int kbc_stop = int64_t(blockIdx.x + 1)*(nsamples_y.z*nchannels_y.z*ntx.z*nty*blocks_per_ne00.z) / gridDim.x; + + kbc -= fastmodulo(kbc, blocks_per_ne00) % blocks_per_iter; + kbc_stop -= fastmodulo(kbc_stop, blocks_per_ne00) % blocks_per_iter; + + // kb0 == k index when doing the matrix multiplication for an output tile. + int kb0_start = fastmodulo(kbc, blocks_per_ne00); + int kb0_stop = min(blocks_per_ne00.z, uint32_t(kb0_start + kbc_stop - kbc)); + while (kbc < kbc_stop && kb0_stop == int(blocks_per_ne00.z)) { + int tmp = fastdiv(kbc, blocks_per_ne00); + uint2 tmp2 = fast_div_modulo(tmp, ntx); + const int jt = tmp2.y; + tmp = tmp2.x; + tmp2 = fast_div_modulo(tmp, nchannels_y); + const int zt = tmp2.y; + tmp = tmp2.x; + tmp2 = fast_div_modulo(tmp, nsamples_y); + const int wt = tmp2.y; + const int it = tmp2.x; + + // Defaults for regular matrix multiplication: + int col_low = 0; + int col_high = ncols_dst; + int col_diff = ncols_dst; + int offset_y = wt*stride_sample_y + zt*stride_channel_y; + int offset_dst = wt*stride_sample_dst + zt*stride_channel_dst + jt*J*stride_col_dst; + int offset_y_scale; + if constexpr (type == GGML_TYPE_NVFP4) { + offset_y_scale = wt*nchannels_y.z*ncols_y + zt*ncols_y; + } else { + GGML_UNUSED(offset_y_scale); + } + + if (ids_dst) { + col_low = expert_bounds[zt + 0]; + col_high = expert_bounds[zt + 1]; + col_diff = col_high - col_low; + + offset_y = 0; + offset_dst = 0; + if constexpr (type == GGML_TYPE_NVFP4) { + offset_y_scale = 0; + } + + if (jt*J >= col_diff) { + kbc += blocks_per_ne00.z; + kbc -= fastmodulo(kbc, blocks_per_ne00); + + kb0_start = 0; + kb0_stop = min(blocks_per_ne00.z, uint32_t(kbc_stop - kbc)); + + continue; + } + + __syncthreads(); +#pragma unroll + for (int j0 = 0; j0 < J; j0 += nwarps*warp_size) { + const int j = j0 + threadIdx.y*warp_size + threadIdx.x; + + if (j0 + nwarps*warp_size > J && j >= J) { + break; + } + + ids_dst_shared[j] = ids_dst[col_low + jt*J + j]; + } + __syncthreads(); + } + + offset_y += (col_low + jt * J) * (sizeof(block_q8_1_mmq) / sizeof(int)); + offset_dst += it*I; + const float * y_scale_tile = nullptr; + if constexpr (type == GGML_TYPE_NVFP4) { + offset_y_scale += col_low + jt * J; + y_scale_tile = y_scale ? y_scale + offset_y_scale : nullptr; + } + + const int tile_x_max_i = nrows_x - it*I - 1; + const int tile_y_max_j = col_diff - jt*J - 1; + + const char * xz = tab.p[fastdiv(zt, channel_ratio)]; // STRATA: per-expert base + const int offset_x = fastdiv(wt, sample_ratio)*stride_sample_x + it*I*stride_row_x; + + constexpr bool fixup = false; // All but (potentially) the last iterations write their data to dst rather than the fixup buffer. + mul_mat_q_process_tile + (xz, offset_x, y + offset_y, ids_dst_shared, dst + offset_dst, tmp_fixup, y_scale_tile, + stride_row_x, ncols_y, stride_col_dst, + tile_x_max_i, tile_y_max_j, kb0_start, kb0_stop); + + kbc += blocks_per_ne00.z; + kbc -= fastmodulo(kbc, blocks_per_ne00); + + kb0_start = 0; + kb0_stop = min(blocks_per_ne00.z, uint32_t(kbc_stop - kbc)); + } + + if (kbc >= kbc_stop) { + return; + } + + int tmp = fastdiv(kbc, blocks_per_ne00); + uint2 tmp2 = fast_div_modulo(tmp, ntx); + const int jt = tmp2.y; + tmp = tmp2.x; + tmp2 = fast_div_modulo(tmp, nchannels_y); + const int zt = tmp2.y; + tmp = tmp2.x; + tmp2 = fast_div_modulo(tmp, nsamples_y); + const int wt = tmp2.y; + const int it = tmp2.x; + + // Defaults for regular matrix multiplication: + int col_low = 0; + int col_high = ncols_dst; + int col_diff = ncols_dst; + int offset_y = wt*stride_sample_y + zt*stride_channel_y; + int offset_dst = wt*stride_sample_dst + zt*stride_channel_dst + jt*J*stride_col_dst; + int offset_y_scale; + if constexpr (type == GGML_TYPE_NVFP4) { + offset_y_scale = wt*nchannels_y.z*ncols_y + zt*ncols_y; + } else { + GGML_UNUSED(offset_y_scale); + } + + if (ids_dst) { + col_low = expert_bounds[zt + 0]; + col_high = expert_bounds[zt + 1]; + col_diff = col_high - col_low; + + offset_y = 0; + offset_dst = 0; + if constexpr (type == GGML_TYPE_NVFP4) { + offset_y_scale = 0; + } + + if (jt*J >= col_diff) { + return; + } + + // The memory layout for the fixup buffer is always contiguous, therefore reset ids: + __syncthreads(); +#pragma unroll + for (int j0 = 0; j0 < J; j0 += nwarps*warp_size) { + const int j = j0 + threadIdx.y*warp_size + threadIdx.x; + + if (j0 + nwarps*warp_size > J && j >= J) { + break; + } + + ids_dst_shared[j] = j; + } + __syncthreads(); + } + + offset_y += (col_low + jt * J) * (sizeof(block_q8_1_mmq) / sizeof(int)); + offset_dst += it*I; + const float * y_scale_tile = nullptr; + if constexpr (type == GGML_TYPE_NVFP4) { + offset_y_scale += col_low + jt * J; + y_scale_tile = y_scale ? y_scale + offset_y_scale : nullptr; + } + + const int tile_x_max_i = nrows_x - it*I - 1; + const int tile_y_max_j = col_diff - jt*J - 1; + + const char * xz = tab.p[fastdiv(zt, channel_ratio)]; // STRATA: per-expert base + const int offset_x = fastdiv(wt, sample_ratio)*stride_sample_x + it*I*stride_row_x; + + constexpr bool fixup = true; // Last index writes its data to fixup buffer to avoid data races with other blocks. + mul_mat_q_process_tile + (xz, offset_x, y + offset_y, ids_dst_shared, dst + offset_dst, tmp_fixup, y_scale_tile, + stride_row_x, ncols_y, stride_col_dst, + tile_x_max_i, tile_y_max_j, kb0_start, kb0_stop); +} + +// ---- mirrored: launch_mul_mat_q (fallback = false) ---- +template +static void launch_mul_mat_q_tab(ggml_backend_cuda_context & ctx, const mmq_args & args, const mmq_x_tab & tab, cudaStream_t stream) { + constexpr bool fallback = false; + const int id = ggml_cuda_get_device(); + const int cc = ggml_cuda_info().devices[id].cc; + const int nsm = ggml_cuda_info().devices[id].nsm; + const int warp_size = ggml_cuda_info().devices[id].warp_size; + + const ggml_cuda_mmq_config config = ggml_cuda_mmq_get_config(type, J, fallback, cc); + GGML_ASSERT(config.nthreads % warp_size == 0); + const int nwarps = config.nthreads / warp_size; + const int nbytes_shared = mmq_get_nbytes_shared(config, cc); + + const dim3 block_dims(warp_size, nwarps, 1); + + CUDA_SET_SHARED_MEMORY_LIMIT((mul_mat_q_tab), nbytes_shared); // STRATA: no fallback=true line + + const int nty = (args.nrows_x + config.I - 1) / config.I; + const int ntx = (args.ncols_max + config.J - 1) / config.J; + const int ntzw = args.nchannels_y * args.nsamples_y; + const dim3 block_nums_xy_tiling(nty, ntx, ntzw); + + GGML_ASSERT(args.nchannels_y % args.nchannels_x == 0); + GGML_ASSERT(args.nsamples_y % args.nsamples_x == 0); + const int channel_ratio = args.nchannels_y / args.nchannels_x; + const int sample_ratio = args.nsamples_y / args.nsamples_x; + + const uint3 blocks_per_ne00_fd = init_fastdiv_values(args.ncols_x / ggml_cuda_type_traits::qk); + const uint3 ntx_fd = init_fastdiv_values(ntx); + const uint3 nchannels_y_fd = init_fastdiv_values(args.nchannels_y); + const uint3 nsamples_y_fd = init_fastdiv_values(args.nsamples_y); + const uint3 channel_ratio_fd = init_fastdiv_values(channel_ratio); + const uint3 sample_ratio_fd = init_fastdiv_values(sample_ratio); + + if (!ggml_cuda_mmq_get_stream_k(type, J, fallback, cc)) { + mul_mat_q_tab<<>> + (tab, args.y, args.ids_dst, args.expert_bounds, args.dst, nullptr, args.y_scale, + blocks_per_ne00_fd, args.nrows_x, args.ncols_dst, args.stride_row_x, args.ncols_y, args.nrows_dst, + channel_ratio_fd, nchannels_y_fd, args.stride_channel_x, args.stride_channel_y, args.stride_channel_dst, + sample_ratio_fd, nsamples_y_fd, args.stride_sample_x, args.stride_sample_y, args.stride_sample_dst, + ntx_fd); + return; + } + + // For the stream-k kernel it is possible to run it with tiling by setting the number of CUDA blocks equal to the number of tiles. + // This is worthwhile if the efficiency of tiling is high and skipping the fixup kernel is more important. + const int ntiles_dst = ntx * nty * ntzw; + const int tiles_nwaves = (ntiles_dst + nsm - 1) / nsm; + const int tiles_efficiency_percent = 100 * ntiles_dst / (nsm*tiles_nwaves); + const dim3 block_nums_stream_k(GGML_CUDA_CC_IS_NVIDIA(cc) && tiles_efficiency_percent >= 90 ? ntiles_dst : nsm, 1, 1); + + GGML_ASSERT(ntiles_dst * blocks_per_ne00_fd.z < (1 << 30)); // Assert that variable kbc will not overflow. + + const bool fixup_needed = ntiles_dst % block_nums_stream_k.x != 0; + + ggml_cuda_pool & pool = ctx.pool(id); + ggml_cuda_pool_alloc tmp_fixup(pool); + if (fixup_needed) { + tmp_fixup.alloc(block_nums_stream_k.x * config.J*config.I); + } + + const dim3 block_nums_fixup(block_nums_stream_k.x, config.I/warp_size, 1); + const dim3 block_dims_fixup(block_dims.x, block_dims.y/2, block_dims.z); + + mul_mat_q_tab<<>> + (tab, args.y, args.ids_dst, args.expert_bounds, args.dst, tmp_fixup.ptr, args.y_scale, + blocks_per_ne00_fd, args.nrows_x, args.ncols_dst, args.stride_row_x, args.ncols_y, args.nrows_dst, + channel_ratio_fd, nchannels_y_fd, args.stride_channel_x, args.stride_channel_y, args.stride_channel_dst, + sample_ratio_fd, nsamples_y_fd, args.stride_sample_x, args.stride_sample_y, args.stride_sample_dst, + ntx_fd); + + if (!fixup_needed) { + return; + } + + CUDA_CHECK(cudaGetLastError()); + mul_mat_q_stream_k_fixup<<>> + (args.ids_dst, args.expert_bounds, args.dst, tmp_fixup.ptr, blocks_per_ne00_fd, args.nrows_x, args.ncols_dst, + args.nrows_dst, nchannels_y_fd, args.stride_channel_dst, nsamples_y_fd, args.stride_sample_dst, + ntx_fd); +} + +// ---- mirrored: mul_mat_q_switch_J (fallback = false) ---- +template +static void mul_mat_q_tab_switch_J(ggml_backend_cuda_context & ctx, const mmq_args & args, const mmq_x_tab & tab, cudaStream_t stream) { + constexpr bool fallback = false; + const int id = ggml_cuda_get_device(); + const int cc = ggml_cuda_info().devices[id].cc; + const size_t smpbo = ggml_cuda_info().devices[id].smpbo; + + int J_best = 0; + int ntiles_J_best = INT_MAX; + + for (int J = 8; J <= 128 && ntiles_J_best > 1; J += 8) { + const ggml_cuda_mmq_config config = ggml_cuda_mmq_get_config(type, J, fallback, cc); + if (config.type == GGML_TYPE_COUNT) { + continue; + } + + if (mmq_get_nbytes_shared(config, cc) > smpbo) { + continue; + } + + const int ntiles_x = (args.ncols_opt + config.J - 1) / config.J; + + if (ntiles_x < ntiles_J_best) { + J_best = J; + ntiles_J_best = ntiles_x; + } + } + + switch (J_best) { + case 8: + launch_mul_mat_q_tab(ctx, args, tab, stream); + break; + case 16: + launch_mul_mat_q_tab(ctx, args, tab, stream); + break; + case 24: + launch_mul_mat_q_tab(ctx, args, tab, stream); + break; + case 32: + launch_mul_mat_q_tab(ctx, args, tab, stream); + break; + case 40: + launch_mul_mat_q_tab(ctx, args, tab, stream); + break; + case 48: + launch_mul_mat_q_tab(ctx, args, tab, stream); + break; + case 56: + launch_mul_mat_q_tab(ctx, args, tab, stream); + break; + case 64: + launch_mul_mat_q_tab(ctx, args, tab, stream); + break; + case 72: + launch_mul_mat_q_tab(ctx, args, tab, stream); + break; + case 80: + launch_mul_mat_q_tab(ctx, args, tab, stream); + break; + case 88: + launch_mul_mat_q_tab(ctx, args, tab, stream); + break; + case 96: + launch_mul_mat_q_tab(ctx, args, tab, stream); + break; + case 104: + launch_mul_mat_q_tab(ctx, args, tab, stream); + break; + case 112: + launch_mul_mat_q_tab(ctx, args, tab, stream); + break; + case 120: + launch_mul_mat_q_tab(ctx, args, tab, stream); + break; + case 128: + launch_mul_mat_q_tab(ctx, args, tab, stream); + break; + default: + fprintf(stderr, "J_best=%d\n", J_best); + GGML_ABORT("fatal error"); + break; + } +} + +template +bool mul_mat_q_tab_case(ggml_backend_cuda_context& ctx, const mmq_args& a, const mmq_x_tab& tab, cudaStream_t s) { + if (a.nrows_x % 128 != 0) return false; // upstream would take the fallback configs: not mirrored + mul_mat_q_tab_switch_J(ctx, a, tab, s); + return true; +} + +} // namespace strata::prefill::mmq diff --git a/src/prefill/moe_mmq_tab.hpp b/src/prefill/moe_mmq_tab.hpp new file mode 100644 index 00000000..c0c2a8b5 --- /dev/null +++ b/src/prefill/moe_mmq_tab.hpp @@ -0,0 +1,41 @@ +// src/prefill/moe_mmq_tab.hpp - STRATA_MMQ_DIRECT: declarations of the pointer-table MMQ (moe_mmq_tab.cuh). +// moe_mmq.cu includes only this header, so the tab kernels are instantiated once, in the per-type TUs that CMake +// generates from mmq_tab_instance.cu.in (STRATA_MMQ_TAB on), never implicitly in moe_mmq.cu. +#pragma once + +#include "mmq.cuh" + +namespace strata::prefill::mmq { + +/// Expert z's weight matrix starts at p[z] (z < the launch's nchannels <= 16). +struct mmq_x_tab { + const char* p[16]; +}; + +/// llama.cpp's mul_mat_q_case for fallback=false, with the per-expert base address from `tab` instead of +/// x + z * stride_channel_x. false (nothing launched) when the rows are not a multiple of 128. +template +bool mul_mat_q_tab_case(ggml_backend_cuda_context& ctx, const mmq_args& a, const mmq_x_tab& tab, cudaStream_t s); + +#ifdef STRATA_ORCA_Q4KS_MMQ +extern template bool mul_mat_q_tab_case(ggml_backend_cuda_context&, const mmq_args&, const mmq_x_tab&, cudaStream_t); +#endif +extern template bool mul_mat_q_tab_case(ggml_backend_cuda_context&, const mmq_args&, const mmq_x_tab&, cudaStream_t); +extern template bool mul_mat_q_tab_case(ggml_backend_cuda_context&, const mmq_args&, const mmq_x_tab&, cudaStream_t); +extern template bool mul_mat_q_tab_case(ggml_backend_cuda_context&, const mmq_args&, const mmq_x_tab&, cudaStream_t); +extern template bool mul_mat_q_tab_case(ggml_backend_cuda_context&, const mmq_args&, const mmq_x_tab&, cudaStream_t); +extern template bool mul_mat_q_tab_case(ggml_backend_cuda_context&, const mmq_args&, const mmq_x_tab&, cudaStream_t); +extern template bool mul_mat_q_tab_case(ggml_backend_cuda_context&, const mmq_args&, const mmq_x_tab&, cudaStream_t); +extern template bool mul_mat_q_tab_case(ggml_backend_cuda_context&, const mmq_args&, const mmq_x_tab&, cudaStream_t); +extern template bool mul_mat_q_tab_case(ggml_backend_cuda_context&, const mmq_args&, const mmq_x_tab&, cudaStream_t); +extern template bool mul_mat_q_tab_case(ggml_backend_cuda_context&, const mmq_args&, const mmq_x_tab&, cudaStream_t); +#ifdef STRATA_MMQ_KQUANTS +extern template bool mul_mat_q_tab_case(ggml_backend_cuda_context&, const mmq_args&, const mmq_x_tab&, cudaStream_t); +extern template bool mul_mat_q_tab_case(ggml_backend_cuda_context&, const mmq_args&, const mmq_x_tab&, cudaStream_t); +#if defined(STRATA_Q6K_EXPERTS) +extern template bool mul_mat_q_tab_case(ggml_backend_cuda_context&, const mmq_args&, const mmq_x_tab&, cudaStream_t); +#endif +extern template bool mul_mat_q_tab_case(ggml_backend_cuda_context&, const mmq_args&, const mmq_x_tab&, cudaStream_t); +#endif + +} // namespace strata::prefill::mmq diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index 2fa71c7c..e68855b7 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -79,6 +79,12 @@ void swiglu(const float*, float*, int64_t, int64_t, bool, void*) {} void swiglu_scaled(const float*, float*, int64_t, int64_t, const int32_t*, int, const float*, int64_t, void*) {} void down_row_scales(float*, const int32_t*, int, const float*, int64_t, void*) {} void iota(int32_t*, int64_t, void*) {} +bool tab_built() { return false; } +bool tab_fits(int, int64_t) { return false; } +size_t overread_bytes(int, int64_t) { return 0; } +int direct_mode() { return 0; } +size_t direct_slot_guard() { return 0; } +void prep_group(const GuardTab&, size_t, void*, void*, size_t, void*) {} } // namespace strata::prefill::mmq #endif #ifndef STRATA_PREFILL_FUSED diff --git a/tests/cuda/prefill_mmq_tab_test.cu b/tests/cuda/prefill_mmq_tab_test.cu new file mode 100644 index 00000000..d005de04 --- /dev/null +++ b/tests/cuda/prefill_mmq_tab_test.cu @@ -0,0 +1,469 @@ +// prefill_mmq_tab_test - STRATA_MMQ_DIRECT: the pointer-table MMQ (src/prefill/moe_mmq_tab.cuh, Product::tab) bit for +// bit against the gathered MMQ the prompt path runs today (experts copied `expert_bytes` apart, a zeroed 4096-byte +// tail after the last one). +// +// Part 1, per product type (IQ3_S gate/up [1280, 2560], IQ4_NL and Q8_0 down [2560, 640], and every other type with a +// pointer-table instance, at its pack shape): random valid expert matrices at scattered 256-aligned addresses, each +// followed by a guard filled with an fp16 NaN pattern (0xFF 0x7C); prep_group zeroes the over-read bytes, then the +// table launch; memcmp of the whole output (pre-filled with a NaN pattern in both runs) against the gathered launch. +// Sweep: 1..16 experts with mixed row counts {0,1,7,8,9,31,64,100,512,1000}; max_rows from 1 to 1000 so that every +// tile width J from 8 to 128 is taken (and max_rows above the largest count); few-tile launches (stream-k grid of +// nsm blocks with the fixup kernel) and many-tile ones (one block per tile). +// Part 2, negative control: the same table launch with the guards NOT zeroed must give non-finite values in a down +// product (proves the guard handling is load-bearing; skipped for types that read nothing past a matrix). +// Part 3, mixed groups as prefill.cpp's walk builds them: native expert blobs (gate|up|down) for IQ3_S + IQ4_NL and +// IQ3_S + Q8_0, some read in place (direct), the others gathered at compact positions c != q - one at a time +// (gather_native) or by gather_native_group with a mid-group flush (first > 0) - including groups whose last entry is +// direct and groups with no gathered entry; both products bitwise equal to all-gathered. +// Exit 77 without a CUDA device of sm_80 or newer or without the pointer-table build. +#include "strata/prefill/moe_mmq.hpp" + +#include "ggml.h" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +namespace mmq = strata::prefill::mmq; + +constexpr int G = mmq::kGatherGroupMax; +constexpr size_t TAIL = 4096; + +void ck(cudaError_t e, const char* what) { + if (e != cudaSuccess) throw std::runtime_error(std::string(what) + ": " + cudaGetErrorString(e)); +} + +struct Dev { + void* p = nullptr; + size_t n = 0; + explicit Dev(size_t bytes) : n(bytes) { ck(cudaMalloc(&p, bytes), "cudaMalloc"); } + ~Dev() { cudaFree(p); } + Dev(const Dev&) = delete; + Dev& operator=(const Dev&) = delete; + uint8_t* b() const { return (uint8_t*) p; } +}; + +// random blocks with a sane fp16 scale at each block's start (every format here begins with it) +void fill_matrix(uint8_t* m, ggml_type t, int64_t rows, int64_t cols, std::mt19937& rng) { + const size_t bs = ggml_type_size(t), nb = (size_t) rows * (size_t) (cols / ggml_blck_size(t)); + std::uniform_int_distribution byte(0, 255); + const float lo = t == GGML_TYPE_Q8_0 ? 0.0001f : t == GGML_TYPE_IQ3_S ? 0.0004f : t == GGML_TYPE_IQ4_XS ? 0.00005f + : t == GGML_TYPE_IQ4_NL ? 0.0002f : t == GGML_TYPE_Q2_0 ? 0.004f : 0.0008f; + std::uniform_real_distribution sc(lo, 6.0f * lo); + for (size_t i = 0; i < nb * bs; ++i) m[i] = (uint8_t) byte(rng); + for (size_t b = 0; b < nb; ++b) { + const ggml_fp16_t h = ggml_fp32_to_fp16(sc(rng)); + std::memcpy(m + b * bs, &h, 2); + if (t == GGML_TYPE_Q4_K || t == GGML_TYPE_Q5_K || t == GGML_TYPE_Q5_1) { + const ggml_fp16_t h2 = ggml_fp32_to_fp16(sc(rng) * ((rng() & 1) ? 1.0f : -1.0f)); + std::memcpy(m + b * bs + 2, &h2, 2); + } + } +} + +// host -> device, finished before any work on the (non-blocking) test stream starts: a pageable cudaMemcpy returns +// before its DMA lands, and the legacy stream does not order it against a cudaStreamNonBlocking stream +void upload(void* dst, const void* src, size_t n, const char* what) { + ck(cudaMemcpy(dst, src, n, cudaMemcpyHostToDevice), what); + ck(cudaDeviceSynchronize(), what); +} + +// the fp16 NaN pattern a guard holds before prep_group (0x7CFF little-endian at every even offset) +void fill_nan(uint8_t* dev, size_t n) { + std::vector h(n); + for (size_t i = 0; i < n; ++i) h[i] = (i & 1) ? 0x7C : 0xFF; + upload(dev, h.data(), n, "fill_nan"); +} + +struct Shape { + ggml_type t; + int64_t rows, cols; // the weight matrix [rows, cols] + const char* role; +}; + +// activations for `total` rows of `cols`, quantized for type t (q8_1), plus an identity map and the bounds +struct Acts { + Dev x, xq, ids, bounds; + int64_t total; + Acts(ggml_type t, int64_t cols, const std::vector& cnt, std::mt19937& rng, cudaStream_t s) + : x((size_t) std::max(1, sum(cnt)) * cols * 4), xq(mmq::q8_bytes(std::max(1, sum(cnt)), cols)), + ids((size_t) std::max(1, sum(cnt)) * 4), bounds((cnt.size() + 1) * 4), total(sum(cnt)) { + std::vector hx((size_t) std::max(1, total) * cols); + std::normal_distribution nd(0.0f, 1.0f); + for (auto& v : hx) v = nd(rng); + upload(x.p, hx.data(), hx.size() * 4, "x"); + std::vector hb(cnt.size() + 1, 0); + for (size_t i = 0; i < cnt.size(); ++i) hb[i + 1] = hb[i] + cnt[i]; + upload(bounds.p, hb.data(), hb.size() * 4, "bounds"); + mmq::iota((int32_t*) ids.p, std::max(1, total), s); + if (total > 0) mmq::quantize((const float*) x.p, nullptr, xq.p, (int) t, cols, cols, total, s); + ck(cudaStreamSynchronize(s), "acts"); + } + static int64_t sum(const std::vector& c) { + int64_t n = 0; + for (int v : c) n += v; + return n; + } +}; + +mmq::Product product(const Shape& sh, const Acts& a, int n, int64_t max_rows, float* dst) { + mmq::Product p; + p.type = (int) sh.t; p.w_rows = sh.rows; p.w_cols = sh.cols; + p.n = n; p.xq = a.xq.p; p.bounds = (const int32_t*) a.bounds.p; p.ids = (const int32_t*) a.ids.p; + p.total_rows = a.total; p.max_rows = max_rows; p.dst = dst; p.ld_dst = sh.rows; + return p; +} + +int g_cases = 0, g_fail = 0; + +bool same_bits(const Dev& a, const Dev& b, size_t n, const char* what) { + std::vector ha(n), hb(n); + ck(cudaMemcpy(ha.data(), a.p, n, cudaMemcpyDeviceToHost), "dtoh a"); + ck(cudaMemcpy(hb.data(), b.p, n, cudaMemcpyDeviceToHost), "dtoh b"); + ++g_cases; + if (std::memcmp(ha.data(), hb.data(), n) == 0) return true; + size_t i = 0; + while (i < n && ha[i] == hb[i]) ++i; + std::printf(" FAIL %s: first differing byte %zu of %zu\n", what, i, n); + if (std::getenv("TAB_TEST_DEBUG")) { + const float* fa = (const float*) ha.data(); + const float* fb = (const float*) hb.data(); + size_t nd = 0; + for (size_t k = 0; k < n / 4; ++k) + if (std::memcmp(fa + k, fb + k, 4) != 0) { + if (nd < 6) std::printf(" float %zu: %.9g vs %.9g\n", k, fa[k], fb[k]); + ++nd; + } + std::printf(" %zu floats differ\n", nd); + } + ++g_fail; + return false; +} + +bool any_nonfinite(const Dev& d, size_t floats) { + std::vector h(floats); + ck(cudaMemcpy(h.data(), d.p, floats * 4, cudaMemcpyDeviceToHost), "dtoh"); + for (float v : h) + if (!std::isfinite(v)) return true; + return false; +} + +// Part 1 + 2: one product, `cnt` rows per expert +void product_case(mmq::Context& ctx, const Shape& sh, const std::vector& cnt, int64_t max_rows, std::mt19937& rng, + cudaStream_t s, bool negative, const char* label) { + const int n = (int) cnt.size(); + const size_t eb = mmq::matrix_bytes((int) sh.t, sh.rows, sh.cols); + const size_t over = mmq::overread_bytes((int) sh.t, sh.cols); + Acts a(sh.t, sh.cols, cnt, rng, s); + // the experts' matrices on the host + std::vector> w((size_t) n, std::vector(eb)); + for (auto& m : w) fill_matrix(m.data(), sh.t, sh.rows, sh.cols, rng); + // gathered: back to back, a zeroed tail, the space after it NaN-patterned + Dev grp((size_t) n * eb + TAIL + 4096); + fill_nan(grp.b(), grp.n); + for (int z = 0; z < n; ++z) upload(grp.b() + (size_t) z * eb, w[(size_t) z].data(), eb, "grp"); + ck(cudaMemset(grp.b() + (size_t) n * eb, 0, TAIL), "tail"); + ck(cudaDeviceSynchronize(), "tail"); + // in place: scattered 256-aligned slots in one arena (shuffled order, random gaps), each with a NaN guard + const size_t stride = (eb + mmq::kSlotGuard + 255) / 256 * 256; + std::vector pos((size_t) n); + for (int z = 0; z < n; ++z) pos[(size_t) z] = (size_t) z; + std::shuffle(pos.begin(), pos.end(), rng); + std::uniform_int_distribution gap(0, 8); + Dev arena((size_t) n * (stride + 8 * 256) + 4096); + fill_nan(arena.b(), arena.n); + mmq::WeightTab tab; + mmq::GuardTab guards; + size_t at = 0; + std::vector where((size_t) n); + for (int k = 0; k < n; ++k) { + at += (size_t) gap(rng) * 256; + where[pos[(size_t) k]] = at; + at += stride; + } + for (int z = 0; z < n; ++z) { + uint8_t* p = arena.b() + where[(size_t) z]; + upload(p, w[(size_t) z].data(), eb, "arena"); + tab.p[z] = p; + guards.p[guards.n++] = p + eb; + } + const size_t out = (size_t) std::max(1, a.total) * (size_t) sh.rows * 4; + Dev ref(out), got(out); + fill_nan(ref.b(), out); + fill_nan(got.b(), out); + mmq::Product pr = product(sh, a, n, max_rows, (float*) ref.p); + pr.w = grp.p; pr.expert_bytes = eb; + ctx.run(pr, s); + if (!negative) mmq::prep_group(guards, over, nullptr, nullptr, 0, s); + mmq::Product pt = product(sh, a, n, max_rows, (float*) got.p); + pt.w = nullptr; pt.expert_bytes = 0; pt.tab = &tab; + ctx.run(pt, s); + ck(cudaStreamSynchronize(s), "run"); + char what[256]; + std::snprintf(what, sizeof what, "%s %s n=%d rows=%lld max_rows=%lld (%s)", ggml_type_name(sh.t), sh.role, n, + (long long) a.total, (long long) max_rows, label); + if (!negative) { + same_bits(ref, got, out, what); + return; + } + ++g_cases; + if (!any_nonfinite(got, out / 4)) { + std::printf(" FAIL negative control %s: no non-finite value with the guards left as NaN\n", what); + ++g_fail; + } else if (any_nonfinite(ref, (size_t) a.total * (size_t) sh.rows)) { + std::printf(" FAIL negative control %s: the gathered reference is not finite\n", what); + ++g_fail; + } +} + +std::vector random_counts(int n, std::mt19937& rng) { + static const int kRows[] = {0, 1, 7, 8, 9, 31, 64, 100, 512, 1000}; + std::uniform_int_distribution pick(0, 9); + std::vector c((size_t) n); + for (auto& v : c) v = kRows[pick(rng)]; + return c; +} +int64_t max_of(const std::vector& c) { + int64_t m = 0; + for (int v : c) m = std::max(m, v); + return m; +} + +void sweep(mmq::Context& ctx, const Shape& sh, bool full, std::mt19937& rng, cudaStream_t s) { + const int f0 = g_fail, c0 = g_cases; + // 1..16 experts, mixed counts (max_rows = the largest count, as prefill.cpp passes it) + for (int n = 1; n <= G; ++n) { + if (!full && n != 1 && n != 3 && n != 8 && n != G) continue; + for (int rep = 0; rep < (full ? 3 : 1); ++rep) { + std::vector c = random_counts(n, rng); + if (max_of(c) == 0) c[0] = 1; + product_case(ctx, sh, c, max_of(c), rng, s, false, "mixed"); + } + } + // every J: one expert with m rows, the others fewer; and max_rows above the largest count + static const int kMax[] = {1, 7, 8, 9, 16, 17, 24, 25, 32, 33, 40, 41, 48, 56, 64, 65, 72, 80, 88, 96, 100, 104, + 112, 120, 127, 128, 129, 300, 1000}; + for (int m : kMax) { + if (!full && m % 8 != 0 && m != 1 && m != 129) continue; + for (int n : {1, 5, 16}) { + if (!full && n == 5) continue; + std::uniform_int_distribution fewer(0, m); + std::vector c((size_t) n); + for (auto& v : c) v = fewer(rng); + c[(size_t) (rng() % (unsigned) n)] = m; + product_case(ctx, sh, c, m, rng, s, false, "J sweep"); + } + } + for (int n : {1, 4, 16}) { + std::vector c = random_counts(n, rng); + if (max_of(c) == 0) c[0] = 9; + product_case(ctx, sh, c, max_of(c) + 37, rng, s, false, "max_rows above the largest count"); + } + // experts with 0 rows at the ends and in the middle + product_case(ctx, sh, {0, 0, 5, 0, 1000, 0, 0}, 1000, rng, s, false, "empty experts"); + product_case(ctx, sh, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, 1, rng, s, false, "only the last expert"); + std::printf("%-8s %-7s %4d cases, %s\n", ggml_type_name(sh.t), sh.role, g_cases - c0, + g_fail == f0 ? "all bitwise identical" : "FAILURES"); + // negative control: a down product that reads past its matrix, guards not zeroed + if (mmq::overread_bytes((int) sh.t, sh.cols) > 0) { + const int f1 = g_fail; + product_case(ctx, sh, {3, 64, 0, 17}, 64, rng, s, true, "negative"); + product_case(ctx, sh, {200}, 200, rng, s, true, "negative"); + std::printf("%-8s %-7s negative control (guards not zeroed): %s\n", ggml_type_name(sh.t), sh.role, + g_fail == f1 ? "non-finite output, as required" : "FAILED"); + } +} + +// Part 3: groups as prefill.cpp's walk builds them, both products +struct Pair { + ggml_type gu, d; +}; +void group_case(mmq::Context& ctx, const Pair& pr, const std::vector& cnt, const std::vector& direct, + bool group_gather, int flush_at, std::mt19937& rng, cudaStream_t s, const char* label) { + const int n = (int) cnt.size(); + const Shape gs{pr.gu, 1280, 2560, "gate/up"}, ds{pr.d, 2560, 640, "down"}; + const size_t gub = mmq::matrix_bytes((int) pr.gu, 1280, 2560), db = mmq::matrix_bytes((int) pr.d, 2560, 640); + const size_t up_off = gub / 2, down_off = gub, bytes = gub + db; + const size_t over = mmq::overread_bytes((int) pr.d, 640); + // native blobs, each in its own place: direct ones in "cache slots" with a guard, gathered ones elsewhere + std::vector> blob((size_t) n, std::vector(bytes)); + for (auto& b : blob) { + fill_matrix(b.data(), pr.gu, 1280, 2560, rng); + fill_matrix(b.data() + down_off, pr.d, 2560, 640, rng); + } + const size_t stride = (bytes + mmq::kSlotGuard + 255) / 256 * 256; + Dev arena((size_t) n * (stride + 4 * 256) + 4096); + fill_nan(arena.b(), arena.n); + std::vector at((size_t) n); + size_t o = 0; + for (int z = 0; z < n; ++z) { + o += (size_t) (rng() % 4) * 256; + at[(size_t) z] = arena.b() + o; + o += stride; + upload(at[(size_t) z], blob[(size_t) z].data(), bytes, "blob"); + } + Acts ag(pr.gu, 2560, cnt, rng, s), ad(pr.d, 640, cnt, rng, s); + const int64_t mr = std::max(1, max_of(cnt)); + const size_t out_g = (size_t) std::max(1, ag.total) * 1280 * 4, out_d = (size_t) std::max(1, ad.total) * 2560 * 4; + // reference: today's walk (gather at q, two tail memsets) + Dev rgu((size_t) G * gub + TAIL), rd((size_t) G * db + TAIL), ref_g(out_g), ref_d(out_d); + fill_nan(rgu.b(), rgu.n); + fill_nan(rd.b(), rd.n); + fill_nan(ref_g.b(), out_g); + fill_nan(ref_d.b(), out_d); + for (int q = 0; q < n; ++q) { + const uint8_t* b = at[(size_t) q]; + mmq::gather_native(b, b + up_off, gub / 2, b + down_off, db, rgu.b() + (size_t) q * gub, rd.b() + (size_t) q * db, s); + } + ck(cudaMemsetAsync(rgu.b() + (size_t) n * gub, 0, TAIL, s), "memset"); + ck(cudaMemsetAsync(rd.b() + (size_t) n * db, 0, TAIL, s), "memset"); + mmq::Product p = product(gs, ag, n, mr, (float*) ref_g.p); + p.w = rgu.p; p.expert_bytes = gub; + ctx.run(p, s); + p = product(ds, ad, n, mr, (float*) ref_d.p); + p.w = rd.p; p.expert_bytes = db; + ctx.run(p, s); + // direct: prefill.cpp's compute() in direct mode + Dev tgu_buf((size_t) G * gub + TAIL), td_buf((size_t) G * db + TAIL), got_g(out_g), got_d(out_d); + fill_nan(tgu_buf.b(), tgu_buf.n); + fill_nan(td_buf.b(), td_buf.n); + fill_nan(got_g.b(), out_g); + fill_nan(got_d.b(), out_d); + mmq::WeightTab tgu, td; + mmq::GuardTab gd; + mmq::GatherGroup gg; + int ns = 0; + auto flush = [&]() { + if (gg.n <= gg.first) return; + if (!mmq::gather_native_group(gg, up_off, gub / 2, down_off, db, tgu_buf.p, gub, td_buf.p, db, s)) + throw std::runtime_error("gather_native_group refused an aligned group"); + gg.first = gg.n; + }; + for (int q = 0; q < n; ++q) { + uint8_t* b = at[(size_t) q]; + if (direct[(size_t) q]) { + tgu.p[q] = b; + td.p[q] = b + down_off; + gd.p[gd.n++] = b + bytes; + } else { + const int c = ns++; + tgu.p[q] = tgu_buf.b() + (size_t) c * gub; + td.p[q] = td_buf.b() + (size_t) c * db; + if (group_gather) { + gg.blob[c] = b; + gg.n = c + 1; + } else { + mmq::gather_native(b, b + up_off, gub / 2, b + down_off, db, tgu_buf.b() + (size_t) c * gub, + td_buf.b() + (size_t) c * db, s); + } + } + if (group_gather && q == flush_at) flush(); // release_to's mid-group flush + } + if (group_gather) flush(); + mmq::prep_group(gd, over, ns ? tgu_buf.b() + (size_t) ns * gub : nullptr, ns ? td_buf.b() + (size_t) ns * db : nullptr, + TAIL, s); + p = product(gs, ag, n, mr, (float*) got_g.p); + p.tab = &tgu; + ctx.run(p, s); + p = product(ds, ad, n, mr, (float*) got_d.p); + p.tab = &td; + ctx.run(p, s); + ck(cudaStreamSynchronize(s), "group"); + char what[256]; + std::snprintf(what, sizeof what, "%s+%s group n=%d direct=%d %s (%s)", ggml_type_name(pr.gu), ggml_type_name(pr.d), n, + gd.n, group_gather ? "gather_native_group" : "gather_native", label); + std::string w1 = std::string(what) + " gate/up", w2 = std::string(what) + " down"; + same_bits(ref_g, got_g, out_g, w1.c_str()); + same_bits(ref_d, got_d, out_d, w2.c_str()); +} + +} // namespace + +int main() { + try { + int dev = 0; + cudaDeviceProp prop{}; + if (cudaGetDevice(&dev) != cudaSuccess || cudaGetDeviceProperties(&prop, dev) != cudaSuccess || prop.major < 8) { + std::printf("needs a CUDA device of sm_80 or newer: skipped\n"); + return 77; + } + if (!mmq::built() || !mmq::tab_built()) { + std::printf("no pointer-table MMQ in this build: skipped\n"); + return 77; + } + std::printf("%s (sm_%d%d, %d SMs)\n", prop.name, prop.major, prop.minor, prop.multiProcessorCount); + cudaStream_t s; + ck(cudaStreamCreateWithFlags(&s, cudaStreamNonBlocking), "stream"); + mmq::Context ctx; + std::mt19937 rng(20261011); + // the pack's three formats, fully; every other type with an instance, a shorter sweep + const Shape main_shapes[] = {{GGML_TYPE_IQ3_S, 1280, 2560, "gate/up"}, + {GGML_TYPE_IQ4_NL, 2560, 640, "down"}, + {GGML_TYPE_Q8_0, 2560, 640, "down"}}; + for (const Shape& sh : main_shapes) { + if (!mmq::tab_fits((int) sh.t, sh.rows)) { + std::printf("FAIL: no pointer-table MMQ for %s\n", ggml_type_name(sh.t)); + return 1; + } + std::printf("%-8s %-7s over-read past the matrix: %zu B\n", ggml_type_name(sh.t), sh.role, + mmq::overread_bytes((int) sh.t, sh.cols)); + sweep(ctx, sh, true, rng, s); + } + const Shape other[] = {{GGML_TYPE_IQ2_XXS, 1280, 2560, "gate/up"}, {GGML_TYPE_IQ2_XS, 1280, 2560, "gate/up"}, + {GGML_TYPE_IQ2_S, 1280, 2560, "gate/up"}, {GGML_TYPE_IQ3_XXS, 1280, 2560, "gate/up"}, + {GGML_TYPE_IQ4_XS, 1280, 2560, "gate/up"}, {GGML_TYPE_Q8_0, 1280, 2560, "gate/up"}, + {GGML_TYPE_IQ4_NL, 1280, 2560, "gate/up"}, {GGML_TYPE_Q2_0, 2560, 640, "down"}}; + for (const Shape& sh : other) { + if (!mmq::tab_fits((int) sh.t, sh.rows)) { + std::printf("%-8s %-7s no pointer-table instance here: skipped\n", ggml_type_name(sh.t), sh.role); + continue; + } + sweep(ctx, sh, false, rng, s); + } + // Part 3 + const int f0 = g_fail, c0 = g_cases; + for (const Pair pr : {Pair{GGML_TYPE_IQ3_S, GGML_TYPE_IQ4_NL}, Pair{GGML_TYPE_IQ3_S, GGML_TYPE_Q8_0}}) { + for (int gg = 0; gg < 2; ++gg) { + const bool group_gather = gg == 1; + // alternating direct / gathered, last entry direct + group_case(ctx, pr, {5, 0, 31, 64, 1, 100, 8, 9}, {0, 1, 0, 1, 1, 0, 0, 1}, group_gather, 3, rng, s, + "interleaved, last direct"); + // a full group, the first entries gathered, then mostly direct; flush after entry 5 + group_case(ctx, pr, {7, 8, 9, 31, 64, 100, 1, 0, 512, 3, 17, 33, 2, 64, 90, 128}, + {0, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 0}, group_gather, 5, rng, s, + "full group, last gathered"); + // every entry direct (ns == 0: no tails), and every entry gathered + group_case(ctx, pr, {12, 40, 0, 7}, {1, 1, 1, 1}, group_gather, -1, rng, s, "all direct"); + group_case(ctx, pr, {12, 40, 0, 7}, {0, 0, 0, 0}, group_gather, 1, rng, s, "all gathered"); + // one entry + group_case(ctx, pr, {1000}, {1}, group_gather, -1, rng, s, "one direct entry"); + // random mixes + for (int r = 0; r < 4; ++r) { + const int n = 1 + (int) (rng() % G); + std::vector c = random_counts(n, rng); + if (max_of(c) == 0) c[0] = 1; + std::vector d((size_t) n); + for (auto& v : d) v = (char) (rng() & 1); + group_case(ctx, pr, c, d, group_gather, (int) (rng() % (unsigned) n), rng, s, "random mix"); + } + } + } + std::printf("mixed groups: %d comparisons, %s\n", g_cases - c0, g_fail == f0 ? "all bitwise identical" : "FAILURES"); + cudaStreamDestroy(s); + std::printf("%d comparisons, %d failed\n", g_cases, g_fail); + return g_fail == 0 ? 0 : 1; + } catch (const std::exception& e) { + std::printf("error: %s\n", e.what()); + return 1; + } +} From b82cdb10906dc0953e7ce342a6c8dd5643d95ece Mon Sep 17 00:00:00 2001 From: havok2-htwo Date: Sun, 11 Oct 2026 12:06:30 +0200 Subject: [PATCH 04/33] expert cache: a slot guard for STRATA_MMQ_DIRECT (set_slot_guard), the sizing sites use slot_stride ExpertCache gets inline set_slot_guard / slot_guard / slot_stride / slot_room / slot_tail; the 4-argument open_sized declaration is unchanged (the SYCL engine defines it out of line against the same header and ignores the guard). open_sized lays slots out at slot_stride(blob, guard); blob_ stays the largest blob, so fills, verify_slot and the HIP staging read no further. slot_tail works on uniform caches too (through slot_offset). generate.cpp: slot_guard = Prefill::slot_guard_bytes() (mmq::direct_slot_guard(): 256 when STRATA_MMQ_DIRECT is 1 or 2 on a pointer-table build, else 0) for native packs; the seven round-256 slot costs (split-skip-if-fits, split placement, per-layer sum, profile sizing, shrink_to, cache_bytes, stage sizing) use ExpertCache::slot_stride(b, slot_guard), and the primary and stage caches get set_slot_guard before they open. Guard 0: the same arithmetic as before, so the default layout is unchanged byte for byte. --- include/strata/core/expert_cache.hpp | 18 ++++++++++++++++++ include/strata/prefill/prefill.hpp | 5 +++++ src/core/expert_cache.cpp | 5 +++-- src/prefill/prefill.cpp | 1 + src/program/generate.cpp | 28 ++++++++++++++++++++-------- 5 files changed, 47 insertions(+), 10 deletions(-) diff --git a/include/strata/core/expert_cache.hpp b/include/strata/core/expert_cache.hpp index 17e277de..4ec789b7 100644 --- a/include/strata/core/expert_cache.hpp +++ b/include/strata/core/expert_cache.hpp @@ -119,6 +119,15 @@ public: /// always. CUDA only: a HIP build refuses it at open. The slots past `slots()` after a shrink must hold no /// resident expert and no loan: the CALLER evicts them first (they become CPU misses). void set_segment_bytes(int64_t seg_bytes) { seg_req_ = seg_bytes > 0 ? seg_bytes : 0; } + /// STRATA_MMQ_DIRECT: `open_sized` leaves at least `g` bytes of room after each slot's blob (the prompt MMQ + /// reads a little past a down matrix when it reads an expert in its slot). Set before opening, like + /// `set_segment_bytes`; `close` keeps it. 0 (the default): no guard. The uniform `open` ignores it, and so does + /// the SYCL engine's open_sized (its slots then have no guard, and `slot_tail` finds no room). + void set_slot_guard(int64_t g) { guard_req_ = g > 0 ? g : 0; } + /// The guard the open slots have (0 for uniform slots). + int64_t slot_guard() const { return off_.empty() ? 0 : guard_req_; } + /// A sized slot's arena bytes: the blob plus the guard, 256-byte aligned. + static int64_t slot_stride(int64_t blob, int64_t guard = 0) { return (blob + guard + 255) / 256 * 256; } bool segmented() const { return !segs_.empty(); } int64_t segment_bytes() const { return seg_; } /// Bytes of the arena backed by VRAM now (a whole number of segments; the arena when not segmented). @@ -208,6 +217,14 @@ public: VmmRange* vmm_range() { return vmm_.get(); } /// Byte offset of slot `s` in the arena (s == slots(): the end). uint64_t slot_offset(int64_t s) const { return off_.empty() ? (uint64_t) s * (uint64_t) blob_ : off_[(size_t) s]; } + /// The arena bytes of slot `s` (its blob, any slack and the guard). + uint64_t slot_room(int32_t s) const { return slot_offset(s + 1) - slot_offset(s); } + /// STRATA_MMQ_DIRECT: the address `blob` bytes into slot `s` when the slot has room for `need` more bytes there + /// (null otherwise, or for a bad slot). Uniform slots too: their stride is the largest blob. + uint8_t* slot_tail(int32_t s, uint64_t blob, uint64_t need) const { + if (s < 0 || s >= slots_ || base_ == nullptr) return nullptr; + return slot_room(s) >= blob + need ? base_ + slot_offset(s) + blob : nullptr; + } private: #if defined(STRATA_USE_HIP) @@ -221,6 +238,7 @@ private: uint8_t* base_ = nullptr; int64_t live_slots_ = 0; ///< #533: slots() - all of them unless shrunk int64_t seg_req_ = 0; ///< #533: the segment size asked for (0: one cudaMalloc) + int64_t guard_req_ = 0; ///< STRATA_MMQ_DIRECT: bytes kept after each sized slot's blob (set_slot_guard) int64_t seg_ = 0; ///< #533: the segment size used (a multiple of the driver's granularity) uint64_t reserved_ = 0; ///< #533: the reserved address range's size std::vector segs_; ///< #533: each segment's physical handle (0: unmapped) diff --git a/include/strata/prefill/prefill.hpp b/include/strata/prefill/prefill.hpp index b4f100df..92c26148 100644 --- a/include/strata/prefill/prefill.hpp +++ b/include/strata/prefill/prefill.hpp @@ -124,6 +124,11 @@ public: /// keeps the ring full. STRATA_RING_BYTES=0: 0.1.39's ring, loan and chunk list. static bool ring_bytes_enabled(); + /// STRATA_MMQ_DIRECT: the guard each sized expert-cache slot keeps after its blob (ExpertCache::set_slot_guard), + /// so the prompt MMQ can read a resident expert in its slot. 0 unless STRATA_MMQ_DIRECT is 1 or 2 on a CUDA + /// build with the pointer-table MMQ (STRATA_MMQ_TAB). + static size_t slot_guard_bytes(); + /// Positions [pos0, pos0 + n) holding `tokens`; `ss.ple_prev` must be the two tokens before pos0 (oldest /// first, -1 for none) and is advanced to the last two of these. bool run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& err); diff --git a/src/core/expert_cache.cpp b/src/core/expert_cache.cpp index 1920fdb7..1500f2b2 100644 --- a/src/core/expert_cache.cpp +++ b/src/core/expert_cache.cpp @@ -564,8 +564,9 @@ bool ExpertCache::open_sized(const std::vector& slot_bytes, int64_t n_l int64_t mx = 0; std::vector off(slot_bytes.size() + 1, 0); for (size_t i = 0; i < slot_bytes.size(); ++i) { - // 256-byte aligned slots, so every blob starts where the kernels' vector loads expect it - off[i + 1] = off[i] + ((uint64_t) slot_bytes[i] + 255) / 256 * 256; + // 256-byte aligned slots, so every blob starts where the kernels' vector loads expect it (and the + // STRATA_MMQ_DIRECT guard after each blob, 0 by default) + off[i + 1] = off[i] + (uint64_t) slot_stride(slot_bytes[i], guard_req_); mx = slot_bytes[i] > mx ? slot_bytes[i] : mx; } // one allocation of the summed size, through the uniform path's checks: n "slots" of 1 byte diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index e68855b7..b7651c73 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -1978,6 +1978,7 @@ void Prefill::arm_cpu_share(bool applies, bool by_default) { } bool Prefill::ring_bytes_enabled() { return ring_bytes_on(); } +size_t Prefill::slot_guard_bytes() { return mmq::direct_slot_guard(); } namespace { diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 1536d16a..c1873e70 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -2831,6 +2831,9 @@ int main(int argc, char** argv) { } } const bool native_pack = strata::kernels::cpu::expert_layout().native; + // STRATA_MMQ_DIRECT: the room each sized expert slot keeps after its blob (0 unless it is on: the slot costs and + // the arena are then today's, byte for byte) + const int64_t slot_guard = native_pack ? (int64_t) strata::prefill::Prefill::slot_guard_bytes() : 0; // STRATA_EARLY_REMOTE_CONTEXTS=1: create EVERY secondary context here, like CUDA1's. Under WSL2 the driver's // pinned/mapped host budget (dxg gpadl, ~1 GiB) is spent by CUDA0's weights and MTP before the later loop runs, // and a new context then fails with cudaErrorMemoryAllocation (CUDA2: "cudaSetDevice(2) failed: out of memory"). @@ -3459,7 +3462,8 @@ int main(int argc, char** argv) { const auto& lay = strata::kernels::cpu::expert_layout(); int64_t pairs_bytes = 0; for (const auto& pr : prof) - pairs_bytes += native_pack ? ((int64_t) lay.blob_bytes(pr.first) + 255) / 256 * 256 : (int64_t) lay.max_blob; + pairs_bytes += native_pack ? strata::core::ExpertCache::slot_stride((int64_t) lay.blob_bytes(pr.first), slot_guard) + : (int64_t) lay.max_blob; size_t fb = 0, tb = 0; cudaMemGetInfo(&fb, &tb); const int64_t session = (int64_t) strata::core::session_bytes(g, o.max_context, K, 0, g.n_layers); @@ -3896,7 +3900,8 @@ int main(int argc, char** argv) { total_mass += (mass[r] = hi - lo); } auto cost = [&](int64_t l) -> int64_t { - return native_pack ? ((int64_t) lay.blob_bytes(l) + 255) / 256 * 256 : (int64_t) lay.max_blob; + return native_pack ? strata::core::ExpertCache::slot_stride((int64_t) lay.blob_bytes(l), slot_guard) + : (int64_t) lay.max_blob; }; // the predicted window time (ms) of a placement, and the routed mass its caches hold std::vector held_cnt((size_t) ns, 0); // per-stage fill count, for the startability gate @@ -5275,7 +5280,7 @@ int main(int argc, char** argv) { const uint64_t cap = std::min(budget, (uint64_t) free_room); uint64_t sum = 0; for (int64_t l = 0; l < g.n_layers; ++l) - sum += (lay.blob_bytes(l) + 255) / 256 * 256; + sum += (uint64_t) strata::core::ExpertCache::slot_stride((int64_t) lay.blob_bytes(l), slot_guard); int64_t q = sum > 0 ? (int64_t) (cap / sum) : 0; if (q > g.n_expert) q = g.n_expert; if (q > 0) { @@ -5304,7 +5309,7 @@ int main(int argc, char** argv) { size_t free_room = free_b > keep_free ? free_b - keep_free : 0; const uint64_t cap = std::min(budget, (uint64_t) free_room); for (const auto& pr : profile) { - const uint64_t b = (lay.blob_bytes(pr.first) + 255) / 256 * 256; + const uint64_t b = (uint64_t) strata::core::ExpertCache::slot_stride((int64_t) lay.blob_bytes(pr.first), slot_guard); if (used + b > cap) break; used += b; sized_slots.push_back((int64_t) lay.blob_bytes(pr.first)); @@ -5336,6 +5341,10 @@ int main(int argc, char** argv) { xcache.set_segment_bytes(o.vram_segment_mib << 20); } } + // STRATA_MMQ_DIRECT: the guard after each sized slot (kept across the retry loop's close/open) + xcache.set_slot_guard(slot_guard); + if (slot_guard > 0) + std::fprintf(stderr, "strata generate: +%lld B guard per sized slot (STRATA_MMQ_DIRECT)\n", (long long) slot_guard); if (o.expert_cache > 0) { // keep the first `keep_bytes` of the cache (the profile's hottest experts first); false when nothing is left auto shrink_to = [&](int64_t keep_bytes) -> bool { @@ -5357,8 +5366,9 @@ int main(int argc, char** argv) { if (!sized_slots.empty()) { int64_t used = 0; size_t keep = 0; - while (keep < sized_slots.size() && used + (sized_slots[keep] + 255) / 256 * 256 <= keep_bytes) - used += (sized_slots[keep++] + 255) / 256 * 256; + while (keep < sized_slots.size() && + used + strata::core::ExpertCache::slot_stride(sized_slots[keep], slot_guard) <= keep_bytes) + used += strata::core::ExpertCache::slot_stride(sized_slots[keep++], slot_guard); sized_slots.resize(keep); o.expert_cache = (int) keep; } else { @@ -5370,7 +5380,7 @@ int main(int argc, char** argv) { auto cache_bytes = [&]() -> int64_t { if (sized_slots.empty()) return (int64_t) o.expert_cache * (int64_t) strata::kernels::cpu::expert_layout().max_blob; int64_t b = 0; - for (const int64_t s : sized_slots) b += (s + 255) / 256 * 256; + for (const int64_t s : sized_slots) b += strata::core::ExpertCache::slot_stride(s, slot_guard); return b; }; // With `--expert-cache auto` the reserve must still be free once the slots are WRITTEN: under WDDM an @@ -5580,7 +5590,8 @@ int main(int argc, char** argv) { std::vector sized; int64_t used = 0; for (const auto& pr : st.profile) { - const int64_t b = native_pack ? ((int64_t) lay.blob_bytes(pr.first) + 255) / 256 * 256 : (int64_t) lay.max_blob; + const int64_t b = native_pack ? strata::core::ExpertCache::slot_stride((int64_t) lay.blob_bytes(pr.first), slot_guard) + : (int64_t) lay.max_blob; if (used + b > room) break; used += b; sized.push_back((int64_t) lay.blob_bytes(pr.first)); @@ -5589,6 +5600,7 @@ int main(int argc, char** argv) { // Windows commit, or the free figure ran high): it is tried again with 90% of the slots, up to 3 times, each // try said. Nothing changes when the first open works. bool stage_open = false; + st.cache.set_slot_guard(slot_guard); // STRATA_MMQ_DIRECT: the stages' prompt MMQ reads their own slots for (int attempt = 0; !sized.empty(); ++attempt) { stage_open = native_pack ? st.cache.open_sized(sized, g.n_layers, g.n_expert, err) : st.cache.open((int64_t) sized.size(), g.n_layers, g.n_expert, (int64_t) lay.max_blob, err); From 7d9b50dc1a5ca89db88416552d3b6cb8df3cc08b Mon Sep 17 00:00:00 2001 From: havok2-htwo Date: Sun, 11 Oct 2026 12:06:40 +0200 Subject: [PATCH 05/33] prefill: STRATA_MMQ_DIRECT=1 reads resident experts in their cache slots (pointer-table MMQ) mmq_plan marks a native layer direct when the pointer-table MMQ covers both products, gate/up reads nothing past its matrix, the down over-read (72 B IQ4_NL, 136 B Q8_0) fits the 256 B guard, and the blob is exactly [gate | up | down] in MMQ's matrix sizes; it says once how many layers qualify. In the MoE walk (both the staged and the streamed walk) compute() takes the expert's cache slot: a resident expert whose slot has room for the over-read (slot_tail) and a 16-byte aligned blob is not gathered - the group's pointer tables point at its gate|up and down in the slot, and the guard goes into the group's GuardTab. Streamed, peer and unguarded experts are gathered as before, at compact positions c = 0..ns-1 (gather_native, or gather_native_group with its mid-group flushes unchanged); the end-of-group flush runs even when the last entry was direct. At the group end one prep_group launch zeroes the direct experts' guards and the tails after position ns, replacing the two memsets; both products run with the same n, bounds, ids, max_rows and buffers plus .tab. STRATA_MMQ_DIRECT=0 (default) and 2 run the existing body. PrefillStats::experts_direct, said on the generate summary when non-zero. --- include/strata/prefill/prefill.hpp | 1 + src/prefill/prefill.cpp | 97 +++++++++++++++++++++++++++--- src/program/generate.cpp | 3 + 3 files changed, 94 insertions(+), 7 deletions(-) diff --git a/include/strata/prefill/prefill.hpp b/include/strata/prefill/prefill.hpp index 92c26148..dc392990 100644 --- a/include/strata/prefill/prefill.hpp +++ b/include/strata/prefill/prefill.hpp @@ -35,6 +35,7 @@ struct PrefillStats { int64_t experts_streamed = 0; ///< expert blobs copied host -> device int64_t experts_dma = 0; ///< ...of which straight from the pinned arena (no CPU copy) int64_t experts_resident = 0; ///< expert-layer groups served from the VRAM tier + int64_t experts_direct = 0; ///< ...of which MMQ read in their cache slots, not gathered (STRATA_MMQ_DIRECT=1) int64_t experts_cpu = 0; ///< ...computed on the CPU pool instead of streamed (STRATA_PREFILL_CPU_SHARE) double cpu_share = 0; ///< ...the share of the streamed ones it took last (measured by default) double ms_ple = 0; diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index b7651c73..f6dd0bf8 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -1014,6 +1014,10 @@ struct MmqPlan { std::vector fo; // per layer: no MMQ here but the native fused kernels cover its formats // (gfx11: UD-Q4_K_XL's Q4_K / Q5_K and Q5_1 / Q8_0 experts, STRATA_PF_FUSED=1) size_t gu_max = 0, d_max = 0; + // STRATA_MMQ_DIRECT=1: per layer, whether resident experts are read in their cache slots (pointer-table MMQ), + // and the bytes the down product reads past its matrix there (zeroed in the slot's guard before each group) + std::vector direct; + std::vector d_over; }; const MmqPlan& mmq_plan() { static const MmqPlan plan = [] { @@ -1039,6 +1043,28 @@ const MmqPlan& mmq_plan() { p.gu_max = std::max(p.gu_max, mmq::matrix_bytes(gt, 1280, N)); p.d_max = std::max(p.d_max, mmq::matrix_bytes(dt, N, 640)); } + // STRATA_MMQ_DIRECT=1: a native layer's resident experts are read in place when the pointer-table MMQ covers + // both products, gate/up reads nothing past its matrix, the down over-read fits the slot guard, and the blob + // is exactly [gate | up | down] in MMQ's matrix sizes (the bytes a gather would copy) + p.direct.assign(p.layer.size(), 0); + p.d_over.assign(p.layer.size(), 0); + if (on && lay.native && mmq::direct_mode() == 1) { + int64_t nd = 0; + for (int64_t l = 0; l < layers; ++l) { + if (!p.layer[(size_t) l]) continue; + const auto& f = lay.fmt[(size_t) l]; + const int gt = f.gu_type, dt = f.d_type; + if (!mmq::tab_fits(gt, 1280) || !mmq::tab_fits(dt, N)) continue; + if (mmq::overread_bytes(gt, N) != 0 || mmq::overread_bytes(dt, 640) > mmq::kSlotGuard) continue; + if (f.up_off != mmq::matrix_bytes(gt, 1280, N) / 2 || f.down_off != 2 * f.up_off) continue; + if (mmq::matrix_bytes(dt, N, 640) != f.bytes - f.down_off) continue; + p.direct[(size_t) l] = 1; + p.d_over[(size_t) l] = (uint32_t) mmq::overread_bytes(dt, 640); + ++nd; + } + std::fprintf(stderr, "strata: prompt MMQ reads resident experts in place (STRATA_MMQ_DIRECT=1): %lld of %lld " + "layers\n", (long long) nd, (long long) layers); + } return p; }(); return plan; @@ -3843,7 +3869,15 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri mmq::GatherGroup gg; int gg_slots[MMQ_GROUP]; int gg_nslots = 0; // ring slots gathered by the next flush - // `zero`: the MMQ tail zeroed after the gathered experts (the group's last flush) + // STRATA_MMQ_DIRECT=1: a resident expert with guard room in its slot is not gathered - the + // group's pointer tables give MMQ each expert's own address (group position q), the others are + // gathered at compact positions c = 0..ns-1 of the group buffers, as before (same bytes) + const bool direct = use_mmq && lay.native && m.cache && mmq_plan().direct[(size_t) l]; + mmq::WeightTab tgu, td; + mmq::GuardTab gd; + int ns = 0; + // `zero`: the MMQ tail zeroed after the gathered experts (the group's last flush); a direct + // group's tail is zeroed by prep_group auto flush = [&](size_t zero) { if (gg.n <= gg.first) return; const auto& f = lay.fmt[(size_t) l]; @@ -3873,8 +3907,9 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri gg.first = gg.n; }; // one expert's products from its blob on the device; `slot` (a ring slot, or -1 for a resident - // expert) is released once the blob is read - auto compute = [&](size_t j, const uint8_t* blob_dev, int slot) -> bool { + // expert) is released once the blob is read; `cslot`: the expert-cache slot the blob is in (-1: + // a ring slot or the peer's), which STRATA_MMQ_DIRECT reads in place + auto compute = [&](size_t j, const uint8_t* blob_dev, int slot, int32_t cslot) -> bool { const int32_t e = order[j]; pt.mark(kPfDequant, cs); if (use_mmq) { @@ -3882,6 +3917,37 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri const size_t q = j % MMQ_GROUP; // the group's last expert also zeroes the MMQ tail after its slot (see MMQ_TAIL) const bool last_of_group = q + 1 == MMQ_GROUP || j + 1 == order.size(); + if (direct) { + const auto& f = lay.fmt[(size_t) l]; + uint8_t* gp = cslot >= 0 && ((uintptr_t) blob_dev | (uintptr_t) f.down_off) % 16 == 0 + ? m.cache->slot_tail(cslot, f.bytes, mmq_plan().d_over[(size_t) l]) + : nullptr; + if (gp) { // read in its slot: the guard after the blob is zeroed at the group end + tgu.p[q] = blob_dev; + td.p[q] = blob_dev + f.down_off; + gd.p[gd.n++] = gp; + ++stats_.experts_direct; + } else { + const int c = ns++; + tgu.p[q] = m.grp_gu + (size_t) c * mmq_gub; + td.p[q] = m.grp_d + (size_t) c * mmq_db; + if (group_gather) { + gg.blob[c] = blob_dev; + gg.n = c + 1; + if (slot >= 0) gg_slots[gg_nslots++] = slot; + } else { + mmq::gather_native(blob_dev, blob_dev + f.up_off, mmq_gub / 2, blob_dev + f.down_off, + mmq_db, m.grp_gu + (size_t) c * mmq_gub, + m.grp_d + (size_t) c * mmq_db, m.cs); + } + } + if (slot >= 0 && !group_gather) { cudaEventRecord(m.used[slot], m.cs); m.used_of[slot] = slot; } + if (q + 1 < MMQ_GROUP && j + 1 < order.size()) return true; + if (group_gather) { // also when the last entry was direct (a no-op without gathers) + flush(0); + gg = mmq::GatherGroup{}; + } + } else { if (group_gather) { gg.blob[q] = blob_dev; gg.n = (int) q + 1; @@ -3905,6 +3971,7 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri } if (slot >= 0 && !group_gather) { cudaEventRecord(m.used[slot], m.cs); m.used_of[slot] = slot; } if (q + 1 < MMQ_GROUP && j + 1 < order.size()) return true; + } // the group's products: gate/up, swiglu, the group's H to q8_1, down const size_t j0 = j - q, g = j0 / MMQ_GROUP, n = order.size(); const int ngx = (int) (q + 1); @@ -3912,11 +3979,19 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri int64_t maxr = 0; for (size_t i = j0; i <= j; ++i) maxr = std::max(maxr, m.cnt[(size_t) order[i]]); pt.mark(kPfGemmGU, cs); + if (direct) { + // one launch: the direct experts' guards (their down over-read) and the zeroed tail + // after the last gathered expert (see MMQ_TAIL) + mmq::prep_group(gd, mmq_plan().d_over[(size_t) l], + ns ? m.grp_gu + (size_t) ns * mmq_gub : nullptr, + ns ? m.grp_d + (size_t) ns * mmq_db : nullptr, MMQ_TAIL, m.cs); + } mmq::Product gu; gu.w = m.grp_gu; gu.type = mmq_gt; gu.w_rows = 1280; gu.w_cols = N; gu.expert_bytes = mmq_gub; gu.n = ngx; gu.xq = m.Xq; gu.bounds = m.bounds_dev + j0; gu.ids = m.ids_identity; gu.total_rows = T * K; gu.max_rows = maxr; gu.dst = m.GU; gu.ld_dst = 1280; gu.y_scale = mmq::fp4_activations(mmq_gt) ? m.Xscale : nullptr; + if (direct) gu.tab = &tgu; m.mmq_ctx->run(gu, m.cs); if (lay.native && lay.fmt[(size_t) l].tail_off) // gate/up scales applied as read mmq::swiglu_scaled(m.GU + r0 * 1280, m.H + r0 * 640, nr, 640, m.bounds_dev + j0, ngx, @@ -3931,9 +4006,16 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri dn.ids = m.ids_identity; dn.total_rows = nr; dn.max_rows = maxr; dn.dst = m.Dm + r0 * N; dn.ld_dst = N; dn.y_scale = mmq::fp4_activations(mmq_dt) ? m.Hscale : nullptr; + if (direct) dn.tab = &td; m.mmq_ctx->run(dn, m.cs); if (lay.native && lay.fmt[(size_t) l].tail_off) // s_down: applied by the combine mmq::down_row_scales(m.row_sd + r0, dn.bounds, ngx, m.grp_tail, nr, m.cs); + if (direct) { + tgu = mmq::WeightTab{}; + td = mmq::WeightTab{}; + gd = mmq::GuardTab{}; + ns = 0; + } return true; } const int q = (int) (j % DQ); @@ -3973,11 +4055,12 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri const int32_t e = order[j]; if (stage_of[j] < 0) { ++stats_.experts_resident; - if (!compute(j, m.cache->device_slot(m.host_res[(size_t) l * m.g->n_expert + e]), -1)) return false; + if (!compute(j, m.cache->device_slot(m.host_res[(size_t) l * m.g->n_expert + e]), -1, + m.host_res[(size_t) l * m.g->n_expert + e])) return false; } else { pt.mark(kPfWaitCopy, cs); cudaStreamWaitEvent(m.cs, m.copied[stage_of[j]], 0); - if (!compute(j, m.stage_dev[stage_of[j]], stage_of[j])) return false; + if (!compute(j, m.stage_dev[stage_of[j]], stage_of[j], -1)) return false; --pending; // compute recorded the slot's release event before any reuse } } @@ -4006,7 +4089,7 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri pt.mark(kPfWaitCopy, cs); cudaStreamWaitEvent(m.cs, m.copied[sl], 0); } - if (!compute(j, m.stage_dev[sl], sl)) return false; + if (!compute(j, m.stage_dev[sl], sl, -1)) return false; consumed = ++k; if (!group_gather || gg_nslots == 0) give_back(consumed); // its group was gathered } else { @@ -4015,7 +4098,7 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri : (m.pp && m.pp->peer ? m.pp->peer->slot_ptr(l, e) : nullptr); // over the cap: P2P if (bp == nullptr) { err = "prefill: an expert is neither resident, streamed nor on the peer"; return false; } ++stats_.experts_resident; - if (!compute(j, bp, -1)) return false; + if (!compute(j, bp, -1, r0 ? m.host_res[(size_t) l * m.g->n_expert + e] : -1)) return false; if (group_gather && gg_nslots == 0) give_back(consumed); } } diff --git a/src/program/generate.cpp b/src/program/generate.cpp index c1873e70..eab6af89 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -13348,6 +13348,9 @@ int main(int argc, char** argv) { ps.ms_total > 0 ? 1000.0 * (double) ps.tokens / ps.ms_total : 0.0, (long long) ps.experts_streamed, (long long) ps.experts_dma, ps.ms_experts_host, (long long) ps.experts_resident, (long long) ps.experts_cpu, ps.cpu_share, ps.ms_ple); + if (ps.experts_direct > 0) + std::fprintf(stderr, "strata generate: prompt MMQ read %lld of the %lld resident experts in their slots " + "(STRATA_MMQ_DIRECT)\n", (long long) ps.experts_direct, (long long) ps.experts_resident); } if (!kvg_started) { // the elastic K/V of a prompt that was not read in batches From 20f75a747420b3a4047fb2783aa91ee1793cef5d Mon Sep 17 00:00:00 2001 From: havok2-htwo Date: Sun, 11 Oct 2026 12:23:37 +0200 Subject: [PATCH 06/33] prefill mmq tab: the table as 16 restrict kernel parameters, so the weights keep LDG.CONSTANT loads A pointer taken from a dynamically indexed array parameter (mmq_x_tab by value) made nvcc copy the table to local memory and read the weights through generic LD.E loads instead of upstream's LDG.E.*.CONSTANT: the products ran 1.2-2.5x slower than upstream's in the unit test (Q8_0 down 2.2-2.6x, IQ4_NL 1.7-2.1x, IQ3_S 1.2-1.35x), which ate most of the gather saving. The kernel now takes x0..x15 as `const char * __restrict__` parameters (like upstream's x) and picks an expert's with a select chain: same SASS load mix as upstream (no local memory), kernel time within 1% of upstream over every type and J in prefill_mmq_tab_test (69.7 vs 69.3 ms in total), and still 874/874 comparisons bitwise identical. --- src/prefill/moe_mmq_tab.cuh | 37 +++++++++++++++++++++++++++++-------- 1 file changed, 29 insertions(+), 8 deletions(-) diff --git a/src/prefill/moe_mmq_tab.cuh b/src/prefill/moe_mmq_tab.cuh index 89099761..d348920a 100644 --- a/src/prefill/moe_mmq_tab.cuh +++ b/src/prefill/moe_mmq_tab.cuh @@ -11,8 +11,10 @@ // fallback = false only (mul_mat_q_tab_case refuses rows % 128 != 0). Everything else is the upstream text, and // mul_mat_q_process_tile, the tile loaders, vec_dot, write_back and mul_mat_q_stream_k_fixup are upstream's own // templates from the same mmq.cuh, compiled in the same target with the same flags. Deliberate deviations: -// 1. at the three offset_x sites the expert's base is `tab.p[fastdiv(zt, channel_ratio)]` and the -// fastdiv(zt, channel_ratio)*stride_channel_x term leaves offset_x (stride_channel_x is still passed, unused); +// 1. upstream's `const char * __restrict__ x` parameter becomes 16 such parameters x0..x15 (the table, see +// STRATA_MMQ_TAB_PARAMS); at the three offset_x sites the expert's base is the one picked by +// fastdiv(zt, channel_ratio), and the fastdiv(zt, channel_ratio)*stride_channel_x term leaves offset_x +// (stride_channel_x is still passed, unused); // 2. the launcher raises the shared-memory limit of mul_mat_q_tab only - upstream's line for // mul_mat_q is dropped, so no fallback=true kernel is instantiated. // The launch geometry (J, tiles, the stream-k grid and k split, the fixup) is computed from the same mmq_args as @@ -40,11 +42,30 @@ static_assert(std::is_same::value, "mmq.cuh: mul_mat_q_stream_k_fixup changed - re-sync src/prefill/moe_mmq_tab.cuh"); +// The table reaches the kernel as 16 separate `const char * __restrict__` parameters, like upstream's `x`, and an +// expert's entry is picked with a select chain: a pointer picked from read-only kernel parameters keeps upstream's +// non-coherent global loads (LDG.CONSTANT) of the weights; a dynamically indexed array parameter would be copied to +// local memory and its pointers read through generic loads (measured ~1.2-2.5x slower products). +#define STRATA_MMQ_TAB_PARAMS \ + const char * __restrict__ x0, const char * __restrict__ x1, const char * __restrict__ x2, \ + const char * __restrict__ x3, const char * __restrict__ x4, const char * __restrict__ x5, \ + const char * __restrict__ x6, const char * __restrict__ x7, const char * __restrict__ x8, \ + const char * __restrict__ x9, const char * __restrict__ x10, const char * __restrict__ x11, \ + const char * __restrict__ x12, const char * __restrict__ x13, const char * __restrict__ x14, \ + const char * __restrict__ x15 +#define STRATA_MMQ_TAB_PICK(z) \ + ((z) == 0 ? x0 : (z) == 1 ? x1 : (z) == 2 ? x2 : (z) == 3 ? x3 : (z) == 4 ? x4 : (z) == 5 ? x5 : \ + (z) == 6 ? x6 : (z) == 7 ? x7 : (z) == 8 ? x8 : (z) == 9 ? x9 : (z) == 10 ? x10 : (z) == 11 ? x11 : \ + (z) == 12 ? x12 : (z) == 13 ? x13 : (z) == 14 ? x14 : x15) +#define STRATA_MMQ_TAB_ARGS(t) \ + (t).p[0], (t).p[1], (t).p[2], (t).p[3], (t).p[4], (t).p[5], (t).p[6], (t).p[7], (t).p[8], (t).p[9], \ + (t).p[10], (t).p[11], (t).p[12], (t).p[13], (t).p[14], (t).p[15] + // ---- mirrored: mul_mat_q (fallback = false, per-expert base from `tab`) ---- template __launch_bounds__(ggml_cuda_mmq_get_nthreads(type, J, false), ggml_cuda_mmq_get_occupancy(type, J, false)) static __global__ void mul_mat_q_tab( - const mmq_x_tab tab, const int * __restrict__ y, const int32_t * __restrict__ ids_dst, + STRATA_MMQ_TAB_PARAMS, const int * __restrict__ y, const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup, const float * __restrict__ y_scale, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst, @@ -142,7 +163,7 @@ static __global__ void mul_mat_q_tab( const int tile_x_max_i = nrows_x - it*I - 1; const int tile_y_max_j = col_diff - jt*J - 1; - const char * xz = tab.p[fastdiv(zt, channel_ratio)]; // STRATA: per-expert base + const char * xz = STRATA_MMQ_TAB_PICK(fastdiv(zt, channel_ratio)); // STRATA: per-expert base const int offset_x = fastdiv(wt, sample_ratio)*stride_sample_x + it*I*stride_row_x; constexpr bool fixup = false; @@ -237,7 +258,7 @@ static __global__ void mul_mat_q_tab( const int tile_x_max_i = nrows_x - it*I - 1; const int tile_y_max_j = col_diff - jt*J - 1; - const char * xz = tab.p[fastdiv(zt, channel_ratio)]; // STRATA: per-expert base + const char * xz = STRATA_MMQ_TAB_PICK(fastdiv(zt, channel_ratio)); // STRATA: per-expert base const int offset_x = fastdiv(wt, sample_ratio)*stride_sample_x + it*I*stride_row_x; constexpr bool fixup = false; // All but (potentially) the last iterations write their data to dst rather than the fixup buffer. @@ -322,7 +343,7 @@ static __global__ void mul_mat_q_tab( const int tile_x_max_i = nrows_x - it*I - 1; const int tile_y_max_j = col_diff - jt*J - 1; - const char * xz = tab.p[fastdiv(zt, channel_ratio)]; // STRATA: per-expert base + const char * xz = STRATA_MMQ_TAB_PICK(fastdiv(zt, channel_ratio)); // STRATA: per-expert base const int offset_x = fastdiv(wt, sample_ratio)*stride_sample_x + it*I*stride_row_x; constexpr bool fixup = true; // Last index writes its data to fixup buffer to avoid data races with other blocks. @@ -369,7 +390,7 @@ static void launch_mul_mat_q_tab(ggml_backend_cuda_context & ctx, const mmq_args if (!ggml_cuda_mmq_get_stream_k(type, J, fallback, cc)) { mul_mat_q_tab<<>> - (tab, args.y, args.ids_dst, args.expert_bounds, args.dst, nullptr, args.y_scale, + (STRATA_MMQ_TAB_ARGS(tab), args.y, args.ids_dst, args.expert_bounds, args.dst, nullptr, args.y_scale, blocks_per_ne00_fd, args.nrows_x, args.ncols_dst, args.stride_row_x, args.ncols_y, args.nrows_dst, channel_ratio_fd, nchannels_y_fd, args.stride_channel_x, args.stride_channel_y, args.stride_channel_dst, sample_ratio_fd, nsamples_y_fd, args.stride_sample_x, args.stride_sample_y, args.stride_sample_dst, @@ -398,7 +419,7 @@ static void launch_mul_mat_q_tab(ggml_backend_cuda_context & ctx, const mmq_args const dim3 block_dims_fixup(block_dims.x, block_dims.y/2, block_dims.z); mul_mat_q_tab<<>> - (tab, args.y, args.ids_dst, args.expert_bounds, args.dst, tmp_fixup.ptr, args.y_scale, + (STRATA_MMQ_TAB_ARGS(tab), args.y, args.ids_dst, args.expert_bounds, args.dst, tmp_fixup.ptr, args.y_scale, blocks_per_ne00_fd, args.nrows_x, args.ncols_dst, args.stride_row_x, args.ncols_y, args.nrows_dst, channel_ratio_fd, nchannels_y_fd, args.stride_channel_x, args.stride_channel_y, args.stride_channel_dst, sample_ratio_fd, nsamples_y_fd, args.stride_sample_x, args.stride_sample_y, args.stride_sample_dst, From 0f10feb4d20cde6e218e070aee7db2e55d73c0ad Mon Sep 17 00:00:00 2001 From: havok2-htwo Date: Sun, 11 Oct 2026 12:58:29 +0200 Subject: [PATCH 07/33] prefill_mmq_tab_test: pad the identity row map for memcheck MMQ loads a whole tile's ids, and its stream-k fixup one per column tile of max_rows, past an expert's last row (upstream behaviour on both paths; the values are not used). With the map padded, compute-sanitizer memcheck runs the whole test clean: 0 errors, 874/874 bitwise equal. --- tests/cuda/prefill_mmq_tab_test.cu | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/tests/cuda/prefill_mmq_tab_test.cu b/tests/cuda/prefill_mmq_tab_test.cu index d005de04..574fd135 100644 --- a/tests/cuda/prefill_mmq_tab_test.cu +++ b/tests/cuda/prefill_mmq_tab_test.cu @@ -38,6 +38,7 @@ namespace mmq = strata::prefill::mmq; constexpr int G = mmq::kGatherGroupMax; constexpr size_t TAIL = 4096; +constexpr int64_t kIdsPad = 2048 + 128; // > the largest max_rows of the sweep plus one tile void ck(cudaError_t e, const char* what) { if (e != cudaSuccess) throw std::runtime_error(std::string(what) + ": " + cudaGetErrorString(e)); @@ -97,7 +98,7 @@ struct Acts { int64_t total; Acts(ggml_type t, int64_t cols, const std::vector& cnt, std::mt19937& rng, cudaStream_t s) : x((size_t) std::max(1, sum(cnt)) * cols * 4), xq(mmq::q8_bytes(std::max(1, sum(cnt)), cols)), - ids((size_t) std::max(1, sum(cnt)) * 4), bounds((cnt.size() + 1) * 4), total(sum(cnt)) { + ids((size_t) (sum(cnt) + kIdsPad) * 4), bounds((cnt.size() + 1) * 4), total(sum(cnt)) { std::vector hx((size_t) std::max(1, total) * cols); std::normal_distribution nd(0.0f, 1.0f); for (auto& v : hx) v = nd(rng); @@ -105,7 +106,9 @@ struct Acts { std::vector hb(cnt.size() + 1, 0); for (size_t i = 0; i < cnt.size(); ++i) hb[i + 1] = hb[i] + cnt[i]; upload(bounds.p, hb.data(), hb.size() * 4, "bounds"); - mmq::iota((int32_t*) ids.p, std::max(1, total), s); + // MMQ loads a whole tile's J ids from an expert's first row, and its stream-k fixup does so for every column + // tile of max_rows, also past the last row (upstream behaviour, harmless values): padded for memcheck + mmq::iota((int32_t*) ids.p, total + kIdsPad, s); if (total > 0) mmq::quantize((const float*) x.p, nullptr, xq.p, (int) t, cols, cols, total, s); ck(cudaStreamSynchronize(s), "acts"); } From a5ad4077efe4d4502077cf10ae404a5cfee88bd2 Mon Sep 17 00:00:00 2001 From: havok2-htwo Date: Sun, 11 Oct 2026 13:56:57 +0200 Subject: [PATCH 08/33] prefill mmq tab: STRATA_MMQ_TAB off by default, the nine tested types only, not on gfx906 Review fixes for the pointer-table MMQ build: - STRATA_MMQ_TAB defaults to OFF, like STRATA_MMQ_KQUANTS: the engine loads every kernel at start (CUDA_MODULE_LOADING=EAGER), and the nine tab instances took 36-38 MiB of VRAM per GPU (sm_86, measured with a cudaMemGetInfo probe linked with and without the tab objects; equal under LAZY), with STRATA_MMQ_DIRECT unset too. prep_group_kernel is compiled only with STRATA_MMQ_TAB, so a build without it has the same device code as 3adce85 (the 58 cubins and PTX of build/strata are byte-identical to engine/strata-g3b's). - The fingerprint block and the tab TUs are skipped on STRATA_HIP_GFX906: that build compiles no .cu from here, so the define, the uncompiled TUs and an unlinkable prefill_mmq_tab_test no longer appear. - Tab instances only for Q2_0 IQ2_XXS IQ2_XS IQ2_S IQ3_XXS IQ3_S IQ4_NL IQ4_XS Q8_0, the types prefill_mmq_tab_test checks bit for bit; Q5_0 and the K-quants (STRATA_ORCA_Q4KS_MMQ, STRATA_MMQ_KQUANTS) keep the gather. - overread_bytes takes the largest over-read of any config, not the over-read of the largest K tile (the over-read is not monotonic in the tile length). - The test fails (instead of skipping) when a tested type has no tab, checks that Q5_0/K-quants report none, and pins the sm_86 over-reads (0, 72, 136 B); the dead K-quant scale branch is gone. - SYCL's moe_mmq.dp.cpp gets the STRATA_MMQ_DIRECT stubs (false/0), for a future migrated prefill.cpp. - moe_mmq.hpp points at docs/DETAILS.md. --- CMakeLists.txt | 22 ++++++++++----- include/strata/prefill/moe_mmq.hpp | 13 ++++----- src/prefill/moe_mmq.cu | 43 ++++++++++++++++-------------- src/prefill/moe_mmq_tab.hpp | 11 -------- sycl/src/prefill/moe_mmq.dp.cpp | 9 +++++++ tests/cuda/prefill_mmq_tab_test.cu | 30 ++++++++++++++++----- 6 files changed, 77 insertions(+), 51 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index c4b684a1..0b7ef11b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -85,10 +85,15 @@ if(STRATA_Q6K_EXPERTS) add_compile_definitions(STRATA_Q6K_EXPERTS=1) endif() option(STRATA_ORCA_Q4KS_MMQ "Build the GGML Q5_0 MMQ instance for OrcaRouter Q4_K_S" OFF) -# STRATA_MMQ_DIRECT (opt-in at run time): the prompt path's MMQ reads resident experts in their cache slots through a -# Strata-side copy of llama.cpp's MMQ scheduler with a per-expert pointer table (src/prefill/moe_mmq_tab.cuh). CUDA -# only; switched off at configure time when the llama.cpp tree's mmq.cuh is not one the copy was verified against. -option(STRATA_MMQ_TAB "prompt MMQ reads resident experts in place (STRATA_MMQ_DIRECT=1; CUDA)" ON) +# CUDA: the pointer-table MMQ behind STRATA_MMQ_DIRECT=1 (the prompt path's MMQ reads resident experts in their cache +# slots through a Strata-side copy of llama.cpp's MMQ scheduler, src/prefill/moe_mmq_tab.cuh). Off by default, like +# the K-quant options above: the engine loads every kernel when it starts (CUDA_MODULE_LOADING=EAGER), and these nine +# instances (+15 MB of binary) take 36-38 MiB of VRAM per GPU on sm_86 - expert slots every model would lose, with +# STRATA_MMQ_DIRECT unset too. They also add ~70% of the upstream MMQ instances' compile time per CUDA arch (175 s +# of CPU for the nine at sm_86 alone). Off, the build's device code is byte for byte the one without this feature. CUDA +# only (not HIP, not gfx906); switched off at configure time when the llama.cpp tree's mmq.cuh is not one the copy +# was verified against. +option(STRATA_MMQ_TAB "Build the pointer-table prompt MMQ for STRATA_MMQ_DIRECT=1 (CUDA; ~37 MiB VRAM per GPU)" OFF) if(STRATA_PREFILL_MMQ AND NOT STRATA_ENABLE_HIP) message(FATAL_ERROR "STRATA_PREFILL_MMQ requires STRATA_ENABLE_HIP=ON") endif() @@ -1465,7 +1470,7 @@ if(STRATA_NATIVE_EXPERTS) # failing the build. _strata_mmq_tab_known: the hashes moe_mmq_tab.cuh was verified against (3cf03257, the # fetched pin; the vendored third_party/llama.cpp tree has the same mmq.cuh). set(_strata_mmq_tab_on OFF) - if(STRATA_MMQ_TAB) + if(STRATA_MMQ_TAB AND NOT STRATA_HIP_GFX906) # gfx906 compiles no .cu from here (its HIP glob): no tab at all set(_strata_mmq_tab_known 36e4dc716c504470ec09cc0852d29a6ac5eace257f6e5e72db3805ca4f043eb0) set(_strata_mmq_tab_hash "") if(EXISTS ${_strata_mmq}/mmq.cuh) @@ -1489,13 +1494,16 @@ if(STRATA_NATIVE_EXPERTS) endif() if(_strata_mmq_tab_on) set(_strata_tab_cuh ${CMAKE_CURRENT_SOURCE_DIR}/src/prefill/moe_mmq_tab.cuh) - foreach(_t IN LISTS _strata_mmq_cuda_types) + # the native packs' nine types, the ones prefill_mmq_tab_test checks bit for bit; the optional Q5_0 / K-quant + # instances (STRATA_ORCA_Q4KS_MMQ, STRATA_MMQ_KQUANTS) get no pointer table and keep the gather + set(_strata_mmq_tab_types q2_0 iq2_xxs iq2_xs iq2_s iq3_xxs iq3_s iq4_nl iq4_xs q8_0) + foreach(_t IN LISTS _strata_mmq_tab_types) string(TOUPPER ${_t} _strata_tab_T) configure_file(src/prefill/mmq_tab_instance.cu.in ${CMAKE_BINARY_DIR}/mmq_tab/mmq-tab-${_t}.cu @ONLY) target_sources(strata_mmq PRIVATE ${CMAKE_BINARY_DIR}/mmq_tab/mmq-tab-${_t}.cu) endforeach() target_compile_definitions(strata_mmq PRIVATE STRATA_MMQ_TAB=1) - message(STATUS "STRATA_MMQ_TAB on: pointer-table MMQ for ${_strata_mmq_cuda_types}") + message(STATUS "STRATA_MMQ_TAB on: pointer-table MMQ for ${_strata_mmq_tab_types}") endif() target_include_directories(strata_mmq PRIVATE ${_strata_gg}/include ${_strata_gg}/src ${_strata_mmq} PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include) diff --git a/include/strata/prefill/moe_mmq.hpp b/include/strata/prefill/moe_mmq.hpp index 3492023c..62b84b74 100644 --- a/include/strata/prefill/moe_mmq.hpp +++ b/include/strata/prefill/moe_mmq.hpp @@ -130,14 +130,15 @@ void f16_to_f32(const uint16_t* x, float* y, int64_t n, void* stream); /// dst = {0, rows} (the bounds of one matrix; dst on the device). void set_bounds(int32_t* dst, int32_t rows, void* stream); -// ---- STRATA_MMQ_DIRECT: the prompt MMQ reads resident experts in place (docs: README, "STRATA_MMQ_DIRECT") ---- -/// This build has the pointer-table MMQ (CUDA, STRATA_MMQ_TAB on: the llama.cpp tree matched the mirrored -/// scheduler's fingerprint). false under HIP, SYCL and builds without MMQ. +// ---- STRATA_MMQ_DIRECT: the prompt MMQ reads resident experts in place (docs/DETAILS.md, "STRATA_MMQ_DIRECT") ---- +/// This build has the pointer-table MMQ (CUDA, the build option STRATA_MMQ_TAB on - off by default - and the +/// llama.cpp tree matched the mirrored scheduler's fingerprint). false under HIP, gfx906, SYCL and builds without MMQ. bool tab_built(); -/// `tab_built`, `fits`, rows a multiple of 128 (no fallback tiles) and a pointer-table instance for the type. +/// `tab_built`, `fits`, rows a multiple of 128 (no fallback tiles) and a pointer-table instance for the type (the +/// native packs' nine: Q2_0 IQ2_XXS IQ2_XS IQ2_S IQ3_XXS IQ3_S IQ4_NL IQ4_XS Q8_0; not Q5_0 or the K-quants). bool tab_fits(int ggml_type, int64_t w_rows); -/// The bytes past a [rows, cols] matrix that its last row's final K tile reads (the largest K tile of any config -/// on any visible GPU): 72 for IQ4_NL and 136 for Q8_0 at 640 columns, 0 for IQ3_S at 2560. 0 without MMQ. +/// The bytes past a [rows, cols] matrix that its last row's final K tile reads (the largest over-read of any +/// config on any visible GPU): 72 for IQ4_NL and 136 for Q8_0 at 640 columns, 0 for IQ3_S at 2560 (sm_86). 0 without MMQ. size_t overread_bytes(int ggml_type, int64_t cols); /// The room kept after each sized expert slot's blob for that over-read (the guard). constexpr size_t kSlotGuard = 256; diff --git a/src/prefill/moe_mmq.cu b/src/prefill/moe_mmq.cu index 6b2b019c..4e210c9f 100644 --- a/src/prefill/moe_mmq.cu +++ b/src/prefill/moe_mmq.cu @@ -177,8 +177,10 @@ __global__ void set_bounds_kernel(int32_t* d, int32_t rows) { unsigned blocks(int64_t n) { return (unsigned) ((n + 255) / 256); } +#if defined(STRATA_MMQ_TAB) && !defined(__HIPCC__) // STRATA_MMQ_DIRECT: a group's guards (y < g.n, byte stores) and its two zero tails (y == g.n: gate/up, y == g.n + 1: -// down; uint4 stores when `tail16`, which the host checked: both pointers and the size 16-byte aligned) +// down; uint4 stores when `tail16`, which the host checked: both pointers and the size 16-byte aligned). Only in a +// STRATA_MMQ_TAB build: the engine loads every kernel at start (EAGER), so a build without it keeps today's image. __global__ void prep_group_kernel(GuardTab g, int64_t guard, uint8_t* tail_gu, uint8_t* tail_d, int64_t tail, bool tail16) { const int y = (int) blockIdx.y; const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; @@ -195,15 +197,12 @@ __global__ void prep_group_kernel(GuardTab g, int64_t guard, uint8_t* tail_gu, u } } -#if defined(STRATA_MMQ_TAB) && !defined(__HIPCC__) -// the pointer-table MMQ per type: the same types and #ifdefs as Context::run's switch. false: no instance +// the pointer-table MMQ per type: the native packs' nine types (CMake's _strata_mmq_tab_types, all of them checked +// bit for bit by prefill_mmq_tab_test). false: no instance - the optional Q5_0 and K-quant experts keep the gather bool run_tab(ggml_backend_cuda_context* ctx, const mmq_args* a, const mmq_x_tab* tab, cudaStream_t s) { const ggml_type t = a ? a->type_x : GGML_TYPE_COUNT; #define STRATA_TAB_CASE(T) case T: return ctx == nullptr || mul_mat_q_tab_case(*ctx, *a, *tab, s) switch (t) { -#ifdef STRATA_ORCA_Q4KS_MMQ - STRATA_TAB_CASE(GGML_TYPE_Q5_0); -#endif STRATA_TAB_CASE(GGML_TYPE_Q2_0); STRATA_TAB_CASE(GGML_TYPE_IQ2_XXS); STRATA_TAB_CASE(GGML_TYPE_IQ2_XS); @@ -213,14 +212,6 @@ bool run_tab(ggml_backend_cuda_context* ctx, const mmq_args* a, const mmq_x_tab* STRATA_TAB_CASE(GGML_TYPE_IQ4_NL); STRATA_TAB_CASE(GGML_TYPE_IQ4_XS); STRATA_TAB_CASE(GGML_TYPE_Q8_0); -#ifdef STRATA_MMQ_KQUANTS - STRATA_TAB_CASE(GGML_TYPE_Q4_K); - STRATA_TAB_CASE(GGML_TYPE_Q5_K); -#if defined(STRATA_Q6K_EXPERTS) - STRATA_TAB_CASE(GGML_TYPE_Q6_K); -#endif - STRATA_TAB_CASE(GGML_TYPE_Q5_1); -#endif default: return false; } #undef STRATA_TAB_CASE @@ -483,17 +474,22 @@ bool tab_fits(int t, int64_t w_rows) { size_t overread_bytes(int t, int64_t cols) { if (!supported(t)) return 0; - // the longest K tile any (fallback=false) config reads on any visible GPU; MMQ_ITER_K when none is known - int64_t k_vram = MMQ_ITER_K; + // the K tile's over-read for each (fallback=false) config on any visible GPU, the largest of them: the over-read + // is not monotonic in the tile length (20 blocks: 12 more with a 16-block tile, 4 with a 24-block one), so each + // config's own; MMQ_ITER_K's is the floor (it is the tile when no config is known) + const int64_t qk = ggml_blck_size((ggml_type) t), bpn = cols / qk; + auto over = [&](int64_t k_vram) -> int64_t { + const int64_t bpi = k_vram / qk; + return bpi > 0 ? (bpi - bpn % bpi) % bpi : 0; + }; + int64_t blocks = over(MMQ_ITER_K); const ggml_cuda_device_info& info = ggml_cuda_info(); for (int id = 0; id < info.device_count; ++id) for (int J = 8; J <= 128; J += 8) { const ggml_cuda_mmq_config c = ggml_cuda_mmq_get_config((ggml_type) t, J, false, info.devices[id].cc); - if (c.type != GGML_TYPE_COUNT) k_vram = std::max(k_vram, c.K_vram); + if (c.type != GGML_TYPE_COUNT) blocks = std::max(blocks, over(c.K_vram)); } - const int64_t qk = ggml_blck_size((ggml_type) t), bpi = k_vram / qk, bpn = cols / qk; - if (bpi <= 0) return 0; - return (size_t) ((bpi - bpn % bpi) % bpi) * ggml_type_size((ggml_type) t); + return (size_t) blocks * ggml_type_size((ggml_type) t); } int direct_mode() { @@ -514,6 +510,12 @@ int direct_mode() { size_t direct_slot_guard() { return direct_mode() != 0 ? kSlotGuard : 0; } void prep_group(const GuardTab& g, size_t guard_bytes, void* tail_gu, void* tail_d, size_t tail_bytes, void* stream) { +#if !defined(STRATA_MMQ_TAB) || defined(__HIPCC__) + // never reached: only a direct group calls it, and direct_mode() is 0 without the pointer-table MMQ + (void) g; (void) guard_bytes; (void) tail_gu; (void) tail_d; (void) tail_bytes; (void) stream; + std::fprintf(stderr, "prefill mmq: this build has no pointer-table MMQ (STRATA_MMQ_TAB)\n"); + std::exit(1); +#else const int n = g.n > 0 ? std::min(g.n, kGatherGroupMax) : 0; const size_t guard = n > 0 ? guard_bytes : 0; const size_t tail = tail_gu || tail_d ? tail_bytes : 0; @@ -525,6 +527,7 @@ void prep_group(const GuardTab& g, size_t guard_bytes, void* tail_gu, void* tail prep_group_kernel<<>>( gt, (int64_t) guard, (uint8_t*) tail_gu, (uint8_t*) tail_d, (int64_t) tail, tail16); ck(cudaGetLastError(), "prep_group"); +#endif } void gather_native(const void* gate, const void* up, size_t gu_half_bytes, const void* down, size_t d_bytes, diff --git a/src/prefill/moe_mmq_tab.hpp b/src/prefill/moe_mmq_tab.hpp index c0c2a8b5..99074198 100644 --- a/src/prefill/moe_mmq_tab.hpp +++ b/src/prefill/moe_mmq_tab.hpp @@ -17,9 +17,6 @@ struct mmq_x_tab { template bool mul_mat_q_tab_case(ggml_backend_cuda_context& ctx, const mmq_args& a, const mmq_x_tab& tab, cudaStream_t s); -#ifdef STRATA_ORCA_Q4KS_MMQ -extern template bool mul_mat_q_tab_case(ggml_backend_cuda_context&, const mmq_args&, const mmq_x_tab&, cudaStream_t); -#endif extern template bool mul_mat_q_tab_case(ggml_backend_cuda_context&, const mmq_args&, const mmq_x_tab&, cudaStream_t); extern template bool mul_mat_q_tab_case(ggml_backend_cuda_context&, const mmq_args&, const mmq_x_tab&, cudaStream_t); extern template bool mul_mat_q_tab_case(ggml_backend_cuda_context&, const mmq_args&, const mmq_x_tab&, cudaStream_t); @@ -29,13 +26,5 @@ extern template bool mul_mat_q_tab_case(ggml_backend_cuda_conte extern template bool mul_mat_q_tab_case(ggml_backend_cuda_context&, const mmq_args&, const mmq_x_tab&, cudaStream_t); extern template bool mul_mat_q_tab_case(ggml_backend_cuda_context&, const mmq_args&, const mmq_x_tab&, cudaStream_t); extern template bool mul_mat_q_tab_case(ggml_backend_cuda_context&, const mmq_args&, const mmq_x_tab&, cudaStream_t); -#ifdef STRATA_MMQ_KQUANTS -extern template bool mul_mat_q_tab_case(ggml_backend_cuda_context&, const mmq_args&, const mmq_x_tab&, cudaStream_t); -extern template bool mul_mat_q_tab_case(ggml_backend_cuda_context&, const mmq_args&, const mmq_x_tab&, cudaStream_t); -#if defined(STRATA_Q6K_EXPERTS) -extern template bool mul_mat_q_tab_case(ggml_backend_cuda_context&, const mmq_args&, const mmq_x_tab&, cudaStream_t); -#endif -extern template bool mul_mat_q_tab_case(ggml_backend_cuda_context&, const mmq_args&, const mmq_x_tab&, cudaStream_t); -#endif } // namespace strata::prefill::mmq diff --git a/sycl/src/prefill/moe_mmq.dp.cpp b/sycl/src/prefill/moe_mmq.dp.cpp index bf74e77b..565bd7cb 100644 --- a/sycl/src/prefill/moe_mmq.dp.cpp +++ b/sycl/src/prefill/moe_mmq.dp.cpp @@ -308,4 +308,13 @@ void iota(int32_t* dst, int64_t n, void* stream) { ck(0, "iota"); } +// STRATA_MMQ_DIRECT (include/strata/prefill/moe_mmq.hpp): the pointer-table MMQ is CUDA only, so SYCL keeps the +// gather - these say so, for a prefill.cpp migrated from a tree that calls them +bool tab_built() { return false; } +bool tab_fits(int, int64_t) { return false; } +size_t overread_bytes(int, int64_t) { return 0; } +int direct_mode() { return 0; } +size_t direct_slot_guard() { return 0; } +void prep_group(const GuardTab&, size_t, void*, void*, size_t, void*) {} + } // namespace strata::prefill::mmq diff --git a/tests/cuda/prefill_mmq_tab_test.cu b/tests/cuda/prefill_mmq_tab_test.cu index 574fd135..76be697a 100644 --- a/tests/cuda/prefill_mmq_tab_test.cu +++ b/tests/cuda/prefill_mmq_tab_test.cu @@ -65,10 +65,6 @@ void fill_matrix(uint8_t* m, ggml_type t, int64_t rows, int64_t cols, std::mt199 for (size_t b = 0; b < nb; ++b) { const ggml_fp16_t h = ggml_fp32_to_fp16(sc(rng)); std::memcpy(m + b * bs, &h, 2); - if (t == GGML_TYPE_Q4_K || t == GGML_TYPE_Q5_K || t == GGML_TYPE_Q5_1) { - const ggml_fp16_t h2 = ggml_fp32_to_fp16(sc(rng) * ((rng() & 1) ? 1.0f : -1.0f)); - std::memcpy(m + b * bs + 2, &h2, 2); - } } } @@ -413,6 +409,26 @@ int main() { const Shape main_shapes[] = {{GGML_TYPE_IQ3_S, 1280, 2560, "gate/up"}, {GGML_TYPE_IQ4_NL, 2560, 640, "down"}, {GGML_TYPE_Q8_0, 2560, 640, "down"}}; + // the types without a pointer table (the optional Q5_0 / K-quant instances) must keep the gather + for (const ggml_type t : {GGML_TYPE_Q5_0, GGML_TYPE_Q4_K, GGML_TYPE_Q5_K, GGML_TYPE_Q5_1, GGML_TYPE_Q6_K}) { + if (mmq::tab_fits((int) t, 1280) || mmq::tab_fits((int) t, 2560)) { + std::printf("FAIL: %s reports a pointer table (only the nine tested types have one)\n", ggml_type_name(t)); + return 1; + } + } + // the over-read each guard must cover: within kSlotGuard, and on sm_86 the values the guards were sized for + // (256-value K tiles: 640 columns are 20 blocks of 32, so the last tile reads 4 blocks more - 4 x 18 B of + // IQ4_NL, 4 x 34 B of Q8_0; 2560 columns end on a tile) + const size_t want_over[] = {0, 72, 136}; + for (size_t i = 0; i < 3; ++i) { + const Shape& sh = main_shapes[i]; + const size_t ov = mmq::overread_bytes((int) sh.t, sh.cols); + if (ov > mmq::kSlotGuard || (prop.major == 8 && prop.minor == 6 && ov != want_over[i])) { + std::printf("FAIL: %s over-read %zu B (want %zu, at most %zu)\n", ggml_type_name(sh.t), ov, want_over[i], + mmq::kSlotGuard); + return 1; + } + } for (const Shape& sh : main_shapes) { if (!mmq::tab_fits((int) sh.t, sh.rows)) { std::printf("FAIL: no pointer-table MMQ for %s\n", ggml_type_name(sh.t)); @@ -427,9 +443,9 @@ int main() { {GGML_TYPE_IQ4_XS, 1280, 2560, "gate/up"}, {GGML_TYPE_Q8_0, 1280, 2560, "gate/up"}, {GGML_TYPE_IQ4_NL, 1280, 2560, "gate/up"}, {GGML_TYPE_Q2_0, 2560, 640, "down"}}; for (const Shape& sh : other) { - if (!mmq::tab_fits((int) sh.t, sh.rows)) { - std::printf("%-8s %-7s no pointer-table instance here: skipped\n", ggml_type_name(sh.t), sh.role); - continue; + if (!mmq::tab_fits((int) sh.t, sh.rows)) { // all nine types have an instance (CMake's tab types) + std::printf("FAIL: no pointer-table MMQ for %s %s\n", ggml_type_name(sh.t), sh.role); + return 1; } sweep(ctx, sh, false, rng, s); } From c2b44ca5b8774eec80f07e3e065aa0a301741011 Mon Sep 17 00:00:00 2001 From: havok2-htwo Date: Sun, 11 Oct 2026 13:56:57 +0200 Subject: [PATCH 09/33] expert cache: slot_guard() reports the guard applied; a test for slot_tail on uniform and sized caches - ExpertCache::slot_guard() returns the guard open_sized applied (guard_, reset by close), not the request: 0 for uniform slots, when closed, and on SYCL, whose open_sized applies none. - tests/core/expert_cache_slot_guard_test: slot_stride, slot_room and slot_tail on a uniform cache (empty off_, including the last slot) and on sized caches with and without the 256 B guard; no guard gives today's offsets; close and reopen. - generate: the "+256 B guard per sized slot" line only for a sized cache; a uniform one says it has no guard. - prefill: STRATA_MMQ_DIRECT_LOG=1 (with STRATA_MMQ_DIRECT=1) prints each stage's totals of experts read in place, resident and streamed after every prompt, so an engine run can show which walk read what. --- CMakeLists.txt | 6 + include/strata/core/expert_cache.hpp | 6 +- src/core/expert_cache.cpp | 2 + src/prefill/prefill.cpp | 10 ++ src/program/generate.cpp | 9 +- tests/core/expert_cache_slot_guard_test.cpp | 117 ++++++++++++++++++++ 6 files changed, 146 insertions(+), 4 deletions(-) create mode 100644 tests/core/expert_cache_slot_guard_test.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 0b7ef11b..c044c14b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -586,6 +586,12 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) target_link_libraries(expert_cache_segmented_test PRIVATE strata_engine) add_test(NAME expert_cache_segmented_test COMMAND expert_cache_segmented_test) set_tests_properties(expert_cache_segmented_test PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) + # STRATA_MMQ_DIRECT: slot_guard / slot_room / slot_tail on the uniform and the sized cache, and the default + # (no guard) sized layout unchanged + add_executable(expert_cache_slot_guard_test tests/core/expert_cache_slot_guard_test.cpp) + target_link_libraries(expert_cache_slot_guard_test PRIVATE strata_engine) + add_test(NAME expert_cache_slot_guard_test COMMAND expert_cache_slot_guard_test) + set_tests_properties(expert_cache_slot_guard_test PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) endif() if(STRATA_BUILD_CONVERSATION_TESTS) add_executable(conversation_snapshot_test src/core/conversation_snapshot_test.cpp) diff --git a/include/strata/core/expert_cache.hpp b/include/strata/core/expert_cache.hpp index 4ec789b7..5262ce5f 100644 --- a/include/strata/core/expert_cache.hpp +++ b/include/strata/core/expert_cache.hpp @@ -124,8 +124,9 @@ public: /// `set_segment_bytes`; `close` keeps it. 0 (the default): no guard. The uniform `open` ignores it, and so does /// the SYCL engine's open_sized (its slots then have no guard, and `slot_tail` finds no room). void set_slot_guard(int64_t g) { guard_req_ = g > 0 ? g : 0; } - /// The guard the open slots have (0 for uniform slots). - int64_t slot_guard() const { return off_.empty() ? 0 : guard_req_; } + /// The guard the open slots were laid out with: what `open_sized` applied (0 for uniform slots, when closed, and + /// on SYCL, whose open_sized applies none). + int64_t slot_guard() const { return guard_; } /// A sized slot's arena bytes: the blob plus the guard, 256-byte aligned. static int64_t slot_stride(int64_t blob, int64_t guard = 0) { return (blob + guard + 255) / 256 * 256; } bool segmented() const { return !segs_.empty(); } @@ -239,6 +240,7 @@ private: int64_t live_slots_ = 0; ///< #533: slots() - all of them unless shrunk int64_t seg_req_ = 0; ///< #533: the segment size asked for (0: one cudaMalloc) int64_t guard_req_ = 0; ///< STRATA_MMQ_DIRECT: bytes kept after each sized slot's blob (set_slot_guard) + int64_t guard_ = 0; ///< ...the guard open_sized applied to the open slots (0: none) int64_t seg_ = 0; ///< #533: the segment size used (a multiple of the driver's granularity) uint64_t reserved_ = 0; ///< #533: the reserved address range's size std::vector segs_; ///< #533: each segment's physical handle (0: unmapped) diff --git a/src/core/expert_cache.cpp b/src/core/expert_cache.cpp index 1500f2b2..e113a7e6 100644 --- a/src/core/expert_cache.cpp +++ b/src/core/expert_cache.cpp @@ -575,6 +575,7 @@ bool ExpertCache::open_sized(const std::vector& slot_bytes, int64_t n_l live_slots_ = slots_; blob_ = mx; off_ = std::move(off); + guard_ = guard_req_; #if defined(STRATA_USE_HIP) if (!ensure_blocking_staging((std::size_t) blob_, err)) { close(); @@ -599,6 +600,7 @@ void ExpertCache::close() { blocking_staging_bytes_ = 0; #endif off_.clear(); + guard_ = 0; if (!segs_.empty()) { release_segmented(); } else if (vmm_) { diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index f6dd0bf8..9ff33eba 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -4446,6 +4446,16 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e err = drain_err; return false; } + // STRATA_MMQ_DIRECT=1 with STRATA_MMQ_DIRECT_LOG=1 (a check, not a default): each stage's totals so far - how many + // resident experts its prompt MMQ read in their slots, of all its resident and streamed ones + if (mmq::direct_mode() == 1) { + static const bool log = [] { const char* v = std::getenv("STRATA_MMQ_DIRECT_LOG"); return v && std::atoi(v) != 0; }(); + for (const Prefill* p = this; log && p != nullptr; p = p->next_) + std::fprintf(stderr, "strata prefill: layers %lld..%lld: %lld of %lld resident experts read in place, %lld " + "streamed (STRATA_MMQ_DIRECT, totals)\n", (long long) p->stage_lb_, + (long long) p->stage_le_, (long long) p->stats_.experts_direct, + (long long) p->stats_.experts_resident, (long long) p->stats_.experts_streamed); + } return true; } diff --git a/src/program/generate.cpp b/src/program/generate.cpp index eab6af89..3326d086 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -5343,8 +5343,13 @@ int main(int argc, char** argv) { } // STRATA_MMQ_DIRECT: the guard after each sized slot (kept across the retry loop's close/open) xcache.set_slot_guard(slot_guard); - if (slot_guard > 0) - std::fprintf(stderr, "strata generate: +%lld B guard per sized slot (STRATA_MMQ_DIRECT)\n", (long long) slot_guard); + if (slot_guard > 0 && o.expert_cache > 0) { + if (!sized_slots.empty()) + std::fprintf(stderr, "strata generate: +%lld B guard per sized slot (STRATA_MMQ_DIRECT)\n", (long long) slot_guard); + else // xcache.open below: every slot is the largest blob's size, and no guard is added + std::fprintf(stderr, "strata generate: uniform expert slots, no guard (STRATA_MMQ_DIRECT): an expert is read " + "in its slot where the slot's slack covers the over-read\n"); + } if (o.expert_cache > 0) { // keep the first `keep_bytes` of the cache (the profile's hottest experts first); false when nothing is left auto shrink_to = [&](int64_t keep_bytes) -> bool { diff --git a/tests/core/expert_cache_slot_guard_test.cpp b/tests/core/expert_cache_slot_guard_test.cpp new file mode 100644 index 00000000..d7b5ac40 --- /dev/null +++ b/tests/core/expert_cache_slot_guard_test.cpp @@ -0,0 +1,117 @@ +// STRATA_MMQ_DIRECT: the expert cache's slot guard (set_slot_guard), slot_room and slot_tail on the uniform cache +// (open: off_ empty, the stride is the largest blob) and on the sized one (open_sized: off_ holds each slot's start). +// No guard asked (the default) must give today's sized layout byte for byte. Needs a CUDA device (exits 77 without). +#include "strata/core/expert_cache.hpp" + +#include + +#include +#include +#include + +namespace { + +int g_fail = 0; + +void check(bool ok, const char* what) { + if (!ok) { + std::fprintf(stderr, "FAIL: %s\n", what); + ++g_fail; + } +} + +} // namespace + +int main() { + int n = 0; + if (cudaGetDeviceCount(&n) != cudaSuccess || n == 0) { + std::puts("no CUDA device: skipped"); + return 77; + } + using strata::core::ExpertCache; + std::string err; + + // slot_stride: the blob plus the guard, 256-byte aligned; guard 0 is the old (b + 255) / 256 * 256 + for (int64_t b : {1, 255, 256, 257, 1000, 2457600, 2949120, 3047424}) { + check(ExpertCache::slot_stride(b) == (b + 255) / 256 * 256, "slot_stride without a guard is today's stride"); + check(ExpertCache::slot_stride(b, 256) == (b + 256 + 255) / 256 * 256, "slot_stride with a 256 B guard"); + check(ExpertCache::slot_stride(b, 256) - b >= 256, "a guarded slot has at least the guard after its blob"); + } + + // 1. uniform: off_ is empty; the guard is asked for but not applied (every slot is the largest blob) + { + ExpertCache c; + c.set_slot_guard(256); + if (!c.open(6, 3, 4, 1024, err)) { std::fprintf(stderr, "open: %s\n", err.c_str()); return 1; } + check(c.slot_guard() == 0, "uniform: no guard applied"); + for (int32_t s = 0; s < 6; ++s) { + check(c.slot_room(s) == 1024, "uniform: slot_room is the blob size"); + check(c.slot_offset(s) == (uint64_t) s * 1024, "uniform: slot_offset"); + } + // the last slot reads slot_offset(slots) - the end - without indexing an empty off_ + check(c.slot_tail(5, 1000, 24) == c.device_slot(5) + 1000, "uniform: the last slot's slack covers 24 B"); + check(c.slot_tail(5, 1000, 25) == nullptr, "uniform: the last slot has no room for 25 B past 1000"); + check(c.slot_tail(0, 1024, 0) == c.device_slot(0) + 1024, "uniform: need 0 at the slot's end"); + check(c.slot_tail(0, 1024, 1) == nullptr, "uniform: a full slot has no room"); + check(c.slot_tail(3, 512, 136) == c.device_slot(3) + 512, "uniform: a smaller blob's slack"); + check(c.slot_tail(-1, 10, 10) == nullptr && c.slot_tail(6, 10, 10) == nullptr, "uniform: a bad slot is null"); + c.close(); + check(c.slot_guard() == 0 && c.slot_tail(0, 10, 10) == nullptr, "uniform: closed"); + } + + // 2. sized without a guard (the default): today's layout, and slot_tail sees only the 256-byte rounding + const std::vector blobs = {1000, 2457600, 700, 3047424, 256, 2949120}; + std::vector plain(blobs.size() + 1, 0); + for (size_t i = 0; i < blobs.size(); ++i) plain[i + 1] = plain[i] + ((uint64_t) blobs[i] + 255) / 256 * 256; + { + ExpertCache c; + if (!c.open_sized(blobs, 3, 4, err)) { std::fprintf(stderr, "open_sized: %s\n", err.c_str()); return 1; } + check(c.slot_guard() == 0, "sized, no guard: slot_guard 0"); + for (size_t s = 0; s <= blobs.size(); ++s) check(c.slot_offset((int64_t) s) == plain[s], "sized, no guard: today's offsets"); + check(c.slot_tail(0, 1000, 24) == c.device_slot(0) + 1000, "sized, no guard: the rounding's 24 B"); + check(c.slot_tail(0, 1000, 25) == nullptr, "sized, no guard: no more than the rounding"); + check(c.slot_tail(4, 256, 1) == nullptr, "sized, no guard: a blob of 256 has no room"); + check(c.slot_tail(5, 2949120, 1) == nullptr, "sized, no guard: the last slot (offset of the end)"); + } + + // 3. sized with the 256 B guard: every slot has >= 256 B after its blob; close() drops the applied guard and a + // reopen applies the kept request again + { + ExpertCache c; + c.set_slot_guard(256); + for (int round = 0; round < 2; ++round) { + if (!c.open_sized(blobs, 3, 4, err)) { std::fprintf(stderr, "open_sized: %s\n", err.c_str()); return 1; } + check(c.slot_guard() == 256, "sized, guard: slot_guard 256"); + uint64_t off = 0; + for (size_t s = 0; s < blobs.size(); ++s) { + const int32_t si = (int32_t) s; + check(c.slot_offset(si) == off, "sized, guard: offsets"); + off += (uint64_t) ExpertCache::slot_stride(blobs[s], 256); + check(c.slot_room(si) == (uint64_t) ExpertCache::slot_stride(blobs[s], 256), "sized, guard: slot_room"); + check(c.device_slot(si) == c.device_slot(0) + c.slot_offset(si), "sized, guard: device_slot"); + uint8_t* t = c.slot_tail(si, (uint64_t) blobs[s], 256); + check(t == c.device_slot(si) + blobs[s], "sized, guard: slot_tail at the blob's end"); + check(c.slot_tail(si, (uint64_t) blobs[s], c.slot_room(si) - (uint64_t) blobs[s] + 1) == nullptr, + "sized, guard: no room past the slot"); + } + check(c.slot_offset((int64_t) blobs.size()) == off, "sized, guard: the end"); + // the guard is writable device memory inside the arena (the prompt path zeroes it) + uint8_t* t = c.slot_tail((int32_t) blobs.size() - 1, (uint64_t) blobs.back(), 256); + check(t != nullptr && cudaMemset(t, 0, 256) == cudaSuccess && cudaDeviceSynchronize() == cudaSuccess, + "sized, guard: the last slot's guard can be zeroed"); + c.close(); + check(c.slot_guard() == 0 && c.slot_tail(0, 10, 10) == nullptr, "sized, guard: closed"); + } + // asked for 0 again: today's layout + c.set_slot_guard(0); + if (!c.open_sized(blobs, 3, 4, err)) { std::fprintf(stderr, "open_sized: %s\n", err.c_str()); return 1; } + check(c.slot_guard() == 0 && c.slot_offset((int64_t) blobs.size()) == plain.back(), "sized: guard reset to 0"); + } + + if (g_fail != 0) { + std::fprintf(stderr, "expert cache slot guard: %d checks failed\n", g_fail); + return 1; + } + std::puts("expert cache slot guard: uniform and sized caches, with and without the guard, passed"); + return 0; +} From a2d979b9990faf4df8edd3107ad6717c519ff380 Mon Sep 17 00:00:00 2001 From: havok2-htwo Date: Sun, 11 Oct 2026 21:35:39 +0200 Subject: [PATCH 10/33] prefill mmq tab: moe_mmq_tab.cuh carries ggml's MIT notice The file mirrors parts of llama.cpp's ggml-cuda mmq.cuh; like the other ggml-derived kernels (native_moe.cu etc.) it now includes the copyright and permission notice the MIT license asks for. Comment only. --- src/prefill/moe_mmq_tab.cuh | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/src/prefill/moe_mmq_tab.cuh b/src/prefill/moe_mmq_tab.cuh index d348920a..3bd0742a 100644 --- a/src/prefill/moe_mmq_tab.cuh +++ b/src/prefill/moe_mmq_tab.cuh @@ -23,6 +23,27 @@ // CMake turns STRATA_MMQ_TAB off unless the SHA-256 of mmq.cuh's mirrored region (mul_mat_q_process_tile through // mul_mat_q_case, which includes struct mmq_args) is one this copy was verified against; when the llama.cpp pin // moves, re-sync this file, re-run the test and record the new hash in CMakeLists.txt (_strata_mmq_tab_known). +// +// MIT License +// Copyright (c) 2023-2026 The ggml authors +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. #pragma once #include "mmq.cuh" From 02d0c23a599127b8b5ad26880699404b9021097d Mon Sep 17 00:00:00 2001 From: havok2-htwo Date: Sun, 11 Oct 2026 12:53:05 +0200 Subject: [PATCH 11/33] docs: STRATA_MMQ_DIRECT (opt-in) and the STRATA_MMQ_TAB build option, with the measurements --- docs/DETAILS.md | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 5bd5fbbb..53ec9dde 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -1786,6 +1786,28 @@ the pairs in which the switched arm won). They are here so you can try them on y instead of 512: prefill 292.5 -> 667.1 tok/s on a 29,854-token prompt (medians of 12 and 6 fresh-engine trials). Reads of up to 512 fresh tokens cost about 0.6-0.75 s more per request, and the card had 0 MiB free while decoding. Details, limits and the measurement: [PREFILL_HEAD_ALIAS.md](PREFILL_HEAD_ALIAS.md). + `STRATA_ADAPT_NOWAIT` or `STRATA_DMA_BATCH`; otherwise the log says why it is off. RTX A4000, 6 interleaved pairs each, + decode median tok/s: Q2_0 16 GB 62.5 -> 66.2 (+5.9%), Q2_0 as a 12 GB card 51.3 -> 54.2 (+5.7%), IQ3_XXS 16 GB 48.6 -> 52.6 (+8.3%), + IQ3_XXS as 12 GB 39.3 -> 41.5 (+5.5%), 6/6 pairs faster every time. +- **`STRATA_MMQ_DIRECT=1`: the prompt's MMQ reads resident experts in their cache slots** (CUDA, native packs). The prompt + path multiplies its experts in groups of 16 with llama.cpp's MMQ, which wants a group's weights in one buffer at a fixed + stride, so every expert a chunk routes to is copied there first (2.3-3.1 MB each, per chunk and layer), resident ones + too. With this on, a Strata-side copy of MMQ's outer scheduler (`src/prefill/moe_mmq_tab.cuh`) takes one pointer per + expert instead, and a resident expert is read where it is; streamed, peer-GPU and other experts are still copied. The + launch (tile size, stream-k split, fixup) is the one MMQ makes for the copied group and the tile code is llama.cpp's + own, so the answers are the same bits (`prefill_mmq_tab_test`: 874 products bitwise equal to the copied path, every type + and tile size). Each sized cache slot keeps 256 bytes after its expert, because MMQ reads up to 136 bytes past a + 640-wide down matrix; they are zeroed before each group. That is about 2.3 MiB over 9,300 slots (one slot fewer out of + 6,998 on one RTX 3090). `STRATA_MMQ_DIRECT=2` keeps that layout but copies as before (an A/B reference); 0 or unset is + the default path, byte for byte. Under HIP, or when CMake turned the build option `STRATA_MMQ_TAB` off (it does so, with + a message, when the llama.cpp tree's `mmq.cuh` differs from the one the copy mirrors), the variable is ignored. + Measured on 4x RTX 3090, UD-IQ4_XS, split `12,24,36` with `--trim-stage-weights` and `--batch 16` (every expert + resident), the engine driven directly, its "read in" time, medians of 8: a 170-token prompt 331 -> 251 ms (-24%) and + 369 -> 290 ms (-21%) in two series, a 1,217-token prompt 773 -> 634 ms (-18%) and 838 -> 675 ms (-19%). Skipping + those copies altogether (wrong answers; the bound) gave 225 and 577 ms. On one RTX 3090 with 40 GiB of experts + streamed from RAM the copies of streamed experts stay, and the prompt time moved by 0-1.5%. Greedy answers with it on + were identical to off: `tools/batch_test16.py` (16 prompts, solo and batch), 20 prompts of 170 and 1,217 tokens, and + on one GPU (resident and streamed experts in the same groups), with `STRATA_PREFILL_CPU_SHARE=0` and no adaptive swaps. ## Thread placement: `--aux-cpus` (Linux, off by default) From 574dcbf9c335e741548a29585da2412617cdb2b4 Mon Sep 17 00:00:00 2001 From: havok2-htwo Date: Sun, 11 Oct 2026 13:56:58 +0200 Subject: [PATCH 12/33] docs: STRATA_MMQ_DIRECT needs -DSTRATA_MMQ_TAB=ON; its VRAM and build cost; the hack is no bound; engine exactness - The build option is off by default and why (36-38 MiB of VRAM per GPU under EAGER, ~70% of the upstream MMQ instances' compile time per arch); the nine types with a pointer table. - The skip-gather hack's 225/577 ms are no bound: it changes the routing and does less work. - Engine exactness as measured: first-window logits (STRATA_DUMP_FIRST_LOGITS) and greedy tokens byte-identical, 2 vs 1 vs 0, on the 4-GPU split with --prefill 2048 (the streamed walk), with 9 GB less expert cache per GPU (mixed in-place, copied and mid-group-flushed groups), and on one GPU with --expert-cache-per-layer. --- docs/DETAILS.md | 50 ++++++++++++++++++++++++++++++++----------------- 1 file changed, 33 insertions(+), 17 deletions(-) diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 53ec9dde..69b7cdf8 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -1789,25 +1789,41 @@ the pairs in which the switched arm won). They are here so you can try them on y `STRATA_ADAPT_NOWAIT` or `STRATA_DMA_BATCH`; otherwise the log says why it is off. RTX A4000, 6 interleaved pairs each, decode median tok/s: Q2_0 16 GB 62.5 -> 66.2 (+5.9%), Q2_0 as a 12 GB card 51.3 -> 54.2 (+5.7%), IQ3_XXS 16 GB 48.6 -> 52.6 (+8.3%), IQ3_XXS as 12 GB 39.3 -> 41.5 (+5.5%), 6/6 pairs faster every time. -- **`STRATA_MMQ_DIRECT=1`: the prompt's MMQ reads resident experts in their cache slots** (CUDA, native packs). The prompt - path multiplies its experts in groups of 16 with llama.cpp's MMQ, which wants a group's weights in one buffer at a fixed - stride, so every expert a chunk routes to is copied there first (2.3-3.1 MB each, per chunk and layer), resident ones - too. With this on, a Strata-side copy of MMQ's outer scheduler (`src/prefill/moe_mmq_tab.cuh`) takes one pointer per - expert instead, and a resident expert is read where it is; streamed, peer-GPU and other experts are still copied. The - launch (tile size, stream-k split, fixup) is the one MMQ makes for the copied group and the tile code is llama.cpp's - own, so the answers are the same bits (`prefill_mmq_tab_test`: 874 products bitwise equal to the copied path, every type - and tile size). Each sized cache slot keeps 256 bytes after its expert, because MMQ reads up to 136 bytes past a - 640-wide down matrix; they are zeroed before each group. That is about 2.3 MiB over 9,300 slots (one slot fewer out of - 6,998 on one RTX 3090). `STRATA_MMQ_DIRECT=2` keeps that layout but copies as before (an A/B reference); 0 or unset is - the default path, byte for byte. Under HIP, or when CMake turned the build option `STRATA_MMQ_TAB` off (it does so, with - a message, when the llama.cpp tree's `mmq.cuh` differs from the one the copy mirrors), the variable is ignored. +- **`STRATA_MMQ_DIRECT=1`: the prompt's MMQ reads resident experts in their cache slots** (CUDA, native packs; needs an + engine built with `-DSTRATA_MMQ_TAB=ON`, which is off by default). The prompt path multiplies its experts in groups of + 16 with llama.cpp's MMQ, which wants a group's weights in one buffer at a fixed stride, so every expert a chunk routes + to is copied there first (2.3-3.1 MB each, per chunk and layer), resident ones too. With this on, a Strata-side copy of + MMQ's outer scheduler (`src/prefill/moe_mmq_tab.cuh`) takes one pointer per expert instead, and a resident expert is + read where it is; streamed, peer-GPU and other experts are still copied. The launch (tile size, stream-k split, + fixup) is the one MMQ makes for the copied group and the tile code is llama.cpp's own, so the answers are the same + bits (`prefill_mmq_tab_test`: 874 products bitwise equal to the copied path, all nine types - Q2_0, IQ2_XXS, IQ2_XS, + IQ2_S, IQ3_XXS, IQ3_S, IQ4_NL, IQ4_XS, Q8_0 - and every tile size; the optional Q5_0 and K-quant experts get no + pointer table and keep the copy). Each sized cache slot keeps 256 bytes after its expert, because MMQ reads up to + 136 bytes past a 640-wide down matrix; they are zeroed before each group. That is about 2.3 MiB over 9,300 slots (one + slot fewer out of 6,998 on one RTX 3090). `STRATA_MMQ_DIRECT=2` keeps that layout but copies as before (an A/B + reference); 0 or unset is the default path, byte for byte. `STRATA_MMQ_DIRECT_LOG=1` adds each stage's count of experts + read in place to the log after every prompt. Under HIP, on a build without `STRATA_MMQ_TAB`, or when CMake turned + that option off (it does so, with a message, when the llama.cpp tree's `mmq.cuh` differs from the one the copy + mirrors), the variable is ignored. + **Why the build option is off:** the engine loads every kernel at start (`CUDA_MODULE_LOADING=EAGER`), and the nine + pointer-table instances (+15 MB of binary) take 36-38 MiB of VRAM on every GPU (sm_86), with the variable unset too - + expert slots every model would lose, as with `STRATA_MMQ_KQUANTS`. They also cost ~70% of the upstream MMQ instances' + compile time per CUDA arch (175 s of CPU at sm_86). Without the option the device code is byte for byte that of a + build without the feature. Measured on 4x RTX 3090, UD-IQ4_XS, split `12,24,36` with `--trim-stage-weights` and `--batch 16` (every expert resident), the engine driven directly, its "read in" time, medians of 8: a 170-token prompt 331 -> 251 ms (-24%) and - 369 -> 290 ms (-21%) in two series, a 1,217-token prompt 773 -> 634 ms (-18%) and 838 -> 675 ms (-19%). Skipping - those copies altogether (wrong answers; the bound) gave 225 and 577 ms. On one RTX 3090 with 40 GiB of experts - streamed from RAM the copies of streamed experts stay, and the prompt time moved by 0-1.5%. Greedy answers with it on - were identical to off: `tools/batch_test16.py` (16 prompts, solo and batch), 20 prompts of 170 and 1,217 tokens, and - on one GPU (resident and streamed experts in the same groups), with `STRATA_PREFILL_CPU_SHARE=0` and no adaptive swaps. + 369 -> 290 ms (-21%) in two series, a 1,217-token prompt 773 -> 634 ms (-18%) and 838 -> 675 ms (-19%). A hack that + skipped the copies altogether ran 225 and 577 ms, but it is no bound for an exact implementation: it changes the + routing (12,003 expert-layer entries fell to 777 on one prompt) and so does less work. On one RTX 3090 with most + experts streamed from RAM the copies of streamed experts stay, and the prompt time did not move (within 1.5%). + Exactness, with `STRATA_PREFILL_CPU_SHARE=0` and no adaptive swaps: the first decode window's logits after the prompt + (`STRATA_DUMP_FIRST_LOGITS`, fp32) and 32 greedy tokens were byte-identical between 2 and 1 (and 0) for prompts of + 180-2,619 tokens - on the 4-GPU split with `--prefill 2048` (chunks of 1,024 tokens and more: the streamed walk), + the same with 9 GB less expert cache per GPU (20-31% of the expert reads streamed, so groups mix in-place, copied and + mid-group flushed experts), and on one GPU with `--expert-cache-per-layer`; the 150 greedy tokens of each of + `tools/batch_test16.py`'s 16 prompts (solo and batch) were identical too, and to those of a build without the + option. The uniform cache (no profile) holds no resident expert when a native pack's prompt is read (serve needs the + profile, and a one-shot run fills the cache only while it decodes), so `expert_cache_slot_guard_test` covers it. ## Thread placement: `--aux-cpus` (Linux, off by default) From 6ab4c312431abb0b314c6292cc194470679f851f Mon Sep 17 00:00:00 2001 From: havok2-htwo Date: Sun, 11 Oct 2026 19:56:16 +0200 Subject: [PATCH 13/33] generate: more than 8 batch slots are held to 8 rows per group window once the slot sessions that fit are known The >8-slot cap ran only before the slot sessions were carved. When fewer sessions fit than asked for, the groups were resolved again with no row bound: auto could pick a group of more than kVerifyMaxT slots (PGroup's rows overrun, every window refused) and a --batch-groups N that no longer divides the slots fell back to one serial group whose windows reach only the first 8 slots. slots_in_windows() picks the most slots whose groups, resolved as batch_groups::resolve does (a number given, auto, the default's one group for --adapt-async 1), divide them with at most kVerifyMaxT rows each and at most one group's worth per stage. It runs before the groups are resolved and again on the slots that fit (the extra sessions are dropped like the per-stage trim); the pump refuses a group over kVerifyMaxT rows as a safety net. The hand-off buffers hold one row per slot only for pipelined groups, so --batch-mtp keeps upstream's kVerifyMaxT rows. Log and comment wording without the g3 tags. --- src/program/generate.cpp | 60 ++++++++++++++++++++++++++-------------- 1 file changed, 40 insertions(+), 20 deletions(-) diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 3326d086..fb780a2e 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -4517,6 +4517,23 @@ int main(int argc, char** argv) { batch_mtp = false; } } + // The most slots, up to n, whose windows hold at most kVerifyMaxT rows each: n itself up to that, more only as + // pipelined groups on a layer split - the groups as resolved below (a number given, auto, or the default's one + // group for --adapt-async 1), dividing the slots, each at most kVerifyMaxT, all at most one group's worth per + // stage. (--batch-mtp: n, as before.) + auto slots_in_windows = [&](int n) { + const int cap = strata::kernels::kVerifyMaxT; + if (batch_mtp || n <= cap) return n; + const int asked = o.batch; + for (; n > cap; --n) { + o.batch = n; + const int gr = batch_groups_for(batch_mtp).groups; + if (!stages.empty() && gr > 1 && n % gr == 0 && n / gr <= cap && n <= cap * ((int) stages.size() + 1)) + break; + } + o.batch = asked; + return n; + }; std::vector>> bslot_ss; if (o.batch != 0) { const int cap = strata::kernels::kVerifyMaxT; @@ -4526,17 +4543,12 @@ int main(int argc, char** argv) { std::fprintf(stderr, "strata generate: WARNING: --batch %d is off: %s\n", o.batch, off); o.batch = 0; } else if (o.batch > cap && !batch_mtp) { - // g3: with a layer split the slots flow through the stages in groups, and a group's window holds - // batch / groups rows - so up to cap rows per group, one group per stage, i.e. cap * stages slots - const int pipe_cap = !stages.empty() && !(o.batch_groups_set && !o.batch_groups_auto && o.batch_groups == 1) ? cap * (int) (stages.size() + 1) : cap; - if (o.batch > pipe_cap) { + const int n = slots_in_windows(o.batch); + if (n < o.batch) { std::fprintf(stderr, "strata generate: WARNING: --batch %d: a batch window holds at most %d rows, so %d " - "slots\n", o.batch, cap, pipe_cap); - o.batch = pipe_cap; + "slots\n", o.batch, cap, n); + o.batch = n; } - if (o.batch > cap) - std::fprintf(stderr, "strata generate: --batch %d over %d stages (g3 patch: up to %d rows per group " - "window)\n", o.batch, (int) stages.size() + 1, cap); } } // --batch-groups auto: the pipeline needs one group per GPU stage to keep every card busy (4 x R9700, 8 clients: @@ -4559,13 +4571,6 @@ int main(int argc, char** argv) { r.groups == 1 ? "" : "s", o.batch / r.groups, o.batch / r.groups == 1 ? "" : "s"); }; if (o.batch > 0) resolve_groups_auto(); - if (o.batch > strata::kernels::kVerifyMaxT && !batch_mtp && - (o.batch_groups < 2 || o.batch / std::max(o.batch_groups, 1) > strata::kernels::kVerifyMaxT)) { - const int g_ = std::max(o.batch_groups, 1), keep = strata::kernels::kVerifyMaxT * g_; - std::fprintf(stderr, "strata generate: WARNING: --batch %d in %d group%s exceeds %d rows per window: %d slots\n", - o.batch, g_, g_ == 1 ? "" : "s", (int) strata::kernels::kVerifyMaxT, keep); - o.batch = keep; - } if (o.batch > 0 && o.batch_groups > 1 && (stages.empty() || o.batch % o.batch_groups != 0)) { std::fprintf(stderr, "strata generate: WARNING: --batch-groups %d needs a layer split and to divide --batch %d; " "one group\n", o.batch_groups, o.batch); @@ -4612,6 +4617,13 @@ int main(int argc, char** argv) { bslot_ss.clear(); o.batch = 0; } else { + const int n = slots_in_windows(fit); // (the slots that fit are held to kVerifyMaxT rows per group too) + if (n < fit) { + std::fprintf(stderr, "strata generate: WARNING: --batch: %d slot sessions fit, and a batch window holds " + "at most %d rows, so %d slots\n", fit, (int) strata::kernels::kVerifyMaxT, n); + for (auto& v : bslot_ss) v.resize((size_t) n); + fit = n; + } o.batch = fit; resolve_groups_auto(); // (the slots that fit may not be the ones asked for) if (o.batch_groups > 1 && o.batch % o.batch_groups != 0) o.batch_groups = 1; @@ -7853,9 +7865,10 @@ int main(int argc, char** argv) { } } if (n_stages > 1) { - // g3: pipelined slot groups write their rows at hbase = group * rows-per-group, so with more than - // kVerifyMaxT slots the hand-off must hold one row per slot - const int hrows = std::max(strata::kernels::kVerifyMaxT, o.batch); + // pipelined slot groups write their rows at hbase = group * rows-per-group, so with more than + // kVerifyMaxT slots in groups the hand-off holds one row per slot (otherwise kVerifyMaxT, as before) + const int hrows = !batch_mtp && o.batch_groups > 1 ? std::max(strata::kernels::kVerifyMaxT, o.batch) + : strata::kernels::kVerifyMaxT; const size_t hb = (size_t) hrows * (size_t) strata::core::Verifier::handoff_floats(g) * sizeof(float); std::vector hand((size_t) n_stages - 1, nullptr); for (float*& h : hand) { @@ -9898,7 +9911,7 @@ int main(int argc, char** argv) { return true; }; // the session a request just left behind (its prompt) -> slot b's sessions, on every stage - // g3: the main sessions and the slot sessions of a stage live on the same device and are carved alike, so + // the main sessions and the slot sessions of a stage live on the same device and are carved alike, so // a slot copy can go device to device (the same bytes into the same places as the checkpoint/K-V image // round trip through host memory, which costs ~40-90 ms per admission on a 4-card split); each device is // synchronized once before and once after. Opt-in: STRATA_SLOT_COPY_DIRECT=1 (default: the host path). @@ -10255,6 +10268,13 @@ int main(int argc, char** argv) { "--batch-mtp's per-slot MTP drafts do not run there (their drafters still hold VRAM, about 0.9 GB per " "slot). Drop --batch-mtp, or use --batch-groups 1.\n", o.batch_groups); const int GS = piped ? o.batch / o.batch_groups : o.batch; + if (GS > strata::kernels::kVerifyMaxT && !batch_mtp) { // (slots_in_windows keeps it so: a group's window is + // PGroup's rows, and the serial windows reach only the first kVerifyMaxT slots) + std::fprintf(stderr, "strata generate: --batch %d in %d group%s: more than %d rows per window\n", + o.batch, std::max(o.batch_groups, 1), o.batch_groups > 1 ? "s" : "", + (int) strata::kernels::kVerifyMaxT); + return 1; + } struct PGroup { bool inflight = false; int stage = 0; ///< the stage it runs on or waits for From bc761d06b1eeb4526d7e41e3b0862e36fce6409b Mon Sep 17 00:00:00 2001 From: havok2-htwo Date: Sun, 11 Oct 2026 22:16:12 +0200 Subject: [PATCH 14/33] generate: STRATA_TRACE times a batch admission's phases One stderr line per batch admission ("strata trace: admission of slot N: ...") splits it into the drain before BGEN, the prompt (batched read, header windows, the checkpoints' device syncs, copies into RAM and eviction, the rest), the first window, the slot copy, freeing the slot's old state and the copy of the turn checkpoint into the slot. Each checkpoint gets its own line, and with pipelined groups "first rows N ms after the admission" times the refill after BADM. A drain for another line says how many groups were in flight and what it cost. Only with STRATA_TRACE set; without it the log and the tokens are unchanged. Measured (4x RTX 3090, split 12,24,36, 16 slots in 4 groups, 24 admissions): drain 25-26, header windows 23.5, checkpoint 17.3 (sync 0.1, save 17.2), first window 11.5, slot copy 1.3, slot freed 0.0, checkpoint copy 7.8 (60 on a slot's first fill), refill after BADM 23.7 ms. --- src/program/generate.cpp | 107 ++++++++++++++++++++++++++++++++++++--- 1 file changed, 100 insertions(+), 7 deletions(-) diff --git a/src/program/generate.cpp b/src/program/generate.cpp index fb780a2e..d7625efc 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -8477,6 +8477,14 @@ int main(int argc, char** argv) { // #613: why the last checkpoint_at failed - a failed device sync is the GPU itself (a hang Windows then resets), // not the checkpoint, and the error says so std::string ckpt_why; + // STRATA_TRACE: what each checkpoint cost - the device syncs, the copies into RAM (the vectors' first fill + // included), the eviction that frees one - one line per checkpoint; with the prompt's read parts summed per + // request for a batch admission's line (below, at BADM) + const bool ckpt_trace = std::getenv("STRATA_TRACE") != nullptr; + struct ReqTimes { + int ckpts = 0; + double sync_ms = 0.0, save_ms = 0.0, evict_ms = 0.0, read_ms = 0.0, windows_ms = 0.0; + } req_times; auto gpu_sync_ok = [&]() -> bool { const cudaError_t e = cudaDeviceSynchronize(); if (e == cudaSuccess) return true; @@ -8505,13 +8513,34 @@ int main(int argc, char** argv) { c.block_pos = std::move((*parts)[0].block_pos); for (size_t i = 1; i < parts->size(); ++i) c.stage_parts.push_back(std::move((*parts)[i])); } else { - if (!gpu_sync_ok() || !checkpoint_save(c, ss, g)) return false; + Clock::time_point t0 = Clock::now(); + auto lap = [&](double& acc) { // (STRATA_TRACE only) + if (!ckpt_trace) return; + const Clock::time_point t1 = Clock::now(); + acc += std::chrono::duration(t1 - t0).count(); + t0 = t1; + }; + double sync_ms = 0.0, save_ms = 0.0; + if (!gpu_sync_ok()) return false; + lap(sync_ms); + if (!checkpoint_save(c, ss, g)) return false; + lap(save_ms); for (auto& st : stages) { // a layer split's later stages: their sessions' part const strata::core::OnDevice on(st->dev); ConvCheckpoint part; part.ids = c.ids; - if (!gpu_sync_ok() || !checkpoint_save(part, st->ss, g)) return false; + if (!gpu_sync_ok()) return false; + lap(sync_ms); + if (!checkpoint_save(part, st->ss, g)) return false; c.stage_parts.push_back(std::move(part)); + lap(save_ms); + } + if (ckpt_trace) { + ++req_times.ckpts; + req_times.sync_ms += sync_ms; + req_times.save_ms += save_ms; + std::fprintf(stderr, "strata trace: checkpoint at %lld: sync %.1f ms, save %.1f ms (%zu stage(s))\n", + (long long) L, sync_ms, save_ms, stages.size() + 1); } } c.used = ++check_clock; @@ -8525,6 +8554,8 @@ int main(int argc, char** argv) { tail_ckpt_len = -1; // the flagged tail was dropped and a normal checkpoint takes its length } checks.push_back(std::move(c)); + const Clock::time_point te0 = Clock::now(); + const size_t before_evict = checks.size(); while ((int) checks.size() > o.prompt_cache) { std::vector stamps; std::vector is_tail; @@ -8548,6 +8579,12 @@ int main(int argc, char** argv) { stamps.data(), stamps.size(), o.prompt_cache, tail_flags.get(), pin_flags.get()); checks.erase(checks.begin() + (std::ptrdiff_t) victim); } + if (ckpt_trace && checks.size() < before_evict) { + const double ms = std::chrono::duration(Clock::now() - te0).count(); + req_times.evict_ms += ms; + std::fprintf(stderr, "strata trace: checkpoint at %lld: %zu evicted in %.1f ms\n", (long long) L, + before_evict - checks.size(), ms); + } return true; }; // STRATA_SPLIT_MTP_BATCH=1 (default off): the layer split's drafter is on the last stage, so E-9 (Prefill::draft_kv) @@ -10291,6 +10328,11 @@ int main(int argc, char** argv) { for (int t = 0; t < GS; ++t) if (bs[(size_t) (gi * GS + t)].active) return true; return false; }; + // STRATA_TRACE: the drain before the line in hand (an admission's first phase), and when the first rows came + // after a batch admission (the pipeline's refill after BADM) or after a drain for another line (drain + refill) + double line_drain_ms = 0.0, adm_drain_ms = 0.0; + const char* rows_wait = nullptr; // what the next rows are timed from (rows_wait_t) + Clock::time_point rows_wait_t{}; // one turn: serve every running stage, hand finished groups on, start what can start auto pump = [&](bool may_start) -> bool { ++pipe_tick; @@ -10348,6 +10390,11 @@ int main(int argc, char** argv) { } } std::fflush(stdout); + if (rows_wait != nullptr) { + std::fprintf(stderr, "strata trace: first rows %.1f ms after %s\n", + std::chrono::duration(Clock::now() - rows_wait_t).count(), rows_wait); + rows_wait = nullptr; + } ++bt_windows; G.inflight = false; } @@ -10412,13 +10459,28 @@ int main(int argc, char** argv) { return true; }; for (;;) { + line_drain_ms = 0.0; if (batch_on() || (piped && pipe_inflight())) { if (!try_next_line(line)) { if (!(piped ? pump(true) : batch_step())) return 1; continue; } // a request reads its prompt through every stage: the groups in flight finish first - if (piped && line.rfind("BSTOP ", 0) != 0 && !pipe_drain()) return 1; + if (piped && line.rfind("BSTOP ", 0) != 0) { + const int in_flight = trace ? (int) std::count_if(pg.begin(), pg.end(), [](const PGroup& G) { + return G.inflight; }) : 0; + const auto td = Clock::now(); + if (!pipe_drain()) return 1; + if (trace) { // STRATA_TRACE: what the drain before this line cost (BGEN: an admission's first phase) + line_drain_ms = std::chrono::duration(Clock::now() - td).count(); + std::fprintf(stderr, "strata trace: drain for %.*s: %d groups in flight, %.1f ms\n", + (int) std::min(line.find(' '), line.size()), line.c_str(), in_flight, line_drain_ms); + const bool timed = in_flight > 0 && line.rfind("BYIELD", 0) == 0; + rows_wait = timed ? "the drain for BYIELD started" : nullptr; + rows_wait_t = td; + std::fflush(stderr); + } + } } else if (!next_line(line)) { break; } @@ -10429,7 +10491,12 @@ int main(int argc, char** argv) { if (b >= 0 && b < (int) bs.size()) bs[(size_t) b].stop = true; continue; } - if (line.rfind("BYIELD", 0) == 0) continue; // for a prompt read that has ended meanwhile + if (line.rfind("BYIELD", 0) == 0) { // for a prompt read that has ended meanwhile + if (trace && piped) + std::fprintf(stderr, "strata trace: BYIELD dropped, %d groups in flight\n", + (int) std::count_if(pg.begin(), pg.end(), [](const PGroup& G) { return G.inflight; })); + continue; + } if (line.rfind("VRAM", 0) == 0) { // #533 (above): between requests, not a request std::string verr; if (batch_on()) verr = "VRAM: not while batch slots are decoding"; @@ -10458,6 +10525,7 @@ int main(int argc, char** argv) { } admit_slot = (int) b; admit_max_new = mn; + adm_drain_ms = line_drain_ms; line = std::string(bimg ? "GENI 1" : "GEN 1") + e2; } // #477: every --expert-profile-save-every minutes, before the next request (at QUIT: after the loop) @@ -11295,6 +11363,7 @@ int main(int argc, char** argv) { // host copies and slots are always current (every writer writes both), so they need nothing if (use_mtp && resume > 0 && reread_to <= 0) mtp.kv_restore(resume); tr("request", n, geni ? 1 : 0); + req_times = ReqTimes{}; if (use_mtp) mtp.set_prompt_len(n); const int64_t read_from = reread_to > 0 ? 0 : resume; conversations.limit_reuse(read_from); @@ -11882,9 +11951,10 @@ int main(int argc, char** argv) { const bool sp_ok = win ? read_windows(at, to, err) : read_part(at, to, err); if (sp_ok) pp_exact = true; if (trace) { + const double ms = std::chrono::duration(Clock::now() - tsp).count(); + (win ? req_times.windows_ms : req_times.read_ms) += ms; std::fprintf(stderr, "strata trace: read %lld tokens (%s) in %.1f ms\n", (long long) (to - at), - win ? "windows" : "batched", - std::chrono::duration(Clock::now() - tsp).count()); + win ? "windows" : "batched", ms); std::fflush(stderr); } if (!sp_ok && nf_hit) { // #879: DONE nonfinite (the lent slots are refilled below) @@ -13049,10 +13119,12 @@ int main(int argc, char** argv) { bs[(size_t) admit_slot].cached = false; // its sessions may be half written cont = false; } + const auto tc1 = Clock::now(); if (cont) { ver.set_slot_sampling(admit_slot, req_sp); // the request's own sampling, row by row BSlot& sl = bs[(size_t) admit_slot]; sl = BSlot{}; + const auto tc2 = Clock::now(); // (the slot's old checkpoints freed) sl.active = true; sl.x = x; sl.p = p; @@ -13076,11 +13148,32 @@ int main(int argc, char** argv) { if (c.ids.size() < live.size() && (best == nullptr || c.ids.size() > best->ids.size()) && std::equal(c.ids.begin(), c.ids.end(), live.begin())) best = &c; + const auto tc3 = Clock::now(); if (best != nullptr && !sl.img) sl.checks.push_back(*best); + const auto tc4 = Clock::now(); std::fprintf(stderr, "strata batch: slot %d takes %lld tokens (copied in %.1f ms)\n", admit_slot, - (long long) live.size(), std::chrono::duration(Clock::now() - tc0).count()); + (long long) live.size(), std::chrono::duration(tc4 - tc0).count()); + if (trace) { // STRATA_TRACE: the admission's phases (ms), from the drain before BGEN to this copy + auto span = [](Clock::time_point a, Clock::time_point b) { + return std::chrono::duration(b - a).count(); + }; + const double ck = req_times.sync_ms + req_times.save_ms + req_times.evict_ms; + std::fprintf(stderr, "strata trace: admission of slot %d: drain %.1f, prompt %.1f (read %.1f, " + "windows %.1f, %d checkpoint(s) %.1f = sync %.1f + save %.1f + evict %.1f, " + "rest %.1f), first window %.1f, slot copy %.1f, slot freed %.1f, " + "checkpoint copy %.1f\n", admit_slot, adm_drain_ms, prompt_ms, + req_times.read_ms, req_times.windows_ms, req_times.ckpts, ck, req_times.sync_ms, + req_times.save_ms, req_times.evict_ms, + prompt_ms - req_times.read_ms - req_times.windows_ms - ck, decode_ms, span(tc0, tc1), + span(tc1, tc2), span(tc3, tc4)); + } } std::printf("BADM %d %d\n", admit_slot, cont ? 1 : 0); + if (trace && piped && cont) { + rows_wait = "the admission"; + rows_wait_t = Clock::now(); + } + adm_drain_ms = 0.0; std::fflush(stdout); admit_slot = -1; } From a62bd38eba139c159c04d5e828df2afdd343c621 Mon Sep 17 00:00:00 2001 From: havok2-htwo Date: Sun, 11 Oct 2026 22:16:12 +0200 Subject: [PATCH 15/33] generate: STRATA_PIPE_BYIELD_NODRAIN=1 drops a BYIELD without draining the pipelined groups A pipelined read never gives way (batch_read_piece returns 0 when piped), so a BYIELD that reaches the main loop is for a read that has ended and is dropped. The main loop still drained the groups for it first, as for a request, unless STRATA_PIPE_OVERLAP was set. With the switch the BYIELD is dropped as it comes. A BYIELD the server sends during the read is queued and taken right after BADM, before any group is restarted, so that drain costs nothing today (0 groups in flight, 0.0 ms). Only a BYIELD that arrives once the groups run again (the server reads the control lines late) paid for it: measured with one sent 60 ms after BADM, drain 26 ms with 4 groups in flight and the first rows 50 ms after it, a 23.5 ms gap in the slots' rows and about 14 rows lost (at 576 rows/s). With the switch the longest gap is 7.1 ms, as in plain decode. Off by default: the same path as before. Tokens: batch_overlap_test (a BYIELD during B's read) on vs off token- and RESUME-identical, batch_interleave_test output byte-identical, batch_test16 16/16, and 41 sampled requests of the admission driver (8 with a BYIELD while 4 groups were in flight) equal. --- src/program/generate.cpp | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/src/program/generate.cpp b/src/program/generate.cpp index d7625efc..cb704d36 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -164,6 +164,17 @@ std::string vram_free_note() { return buf; } +// STRATA_PIPE_BYIELD_NODRAIN=1 (read once; off by default): with the pipelined groups, a BYIELD that reaches the main +// loop is dropped without draining the groups first. A pipelined read never gives way (batch_read_piece), so the +// BYIELD is for a read that has ended, and the drain (and the refill after it) did nothing for it +bool pipe_byield_nodrain_env() { + static const bool on = [] { + const char* v = std::getenv("STRATA_PIPE_BYIELD_NODRAIN"); + return v && v[0] != '0'; + }(); + return on; +} + // perf-review D-4: the lent slots are refilled with queued copies and one wait; STRATA_REFILL_BLOCKING=1 waits on each // A file-backed arena on AMD (STRATA_ARENA_MMAP; the engine raises ROCclr's pin-in-place threshold, see main): an // adaptive swap copies one expert straight from the mapped file. Through ROCclr's staging that copy blocks the host @@ -10466,7 +10477,9 @@ int main(int argc, char** argv) { continue; } // a request reads its prompt through every stage: the groups in flight finish first - if (piped && line.rfind("BSTOP ", 0) != 0) { + // (STRATA_PIPE_BYIELD_NODRAIN: not for a BYIELD, which is dropped below) + if (piped && line.rfind("BSTOP ", 0) != 0 && + !(pipe_byield_nodrain_env() && line.rfind("BYIELD", 0) == 0)) { const int in_flight = trace ? (int) std::count_if(pg.begin(), pg.end(), [](const PGroup& G) { return G.inflight; }) : 0; const auto td = Clock::now(); From 0cf1a9b7c8d6192828f5160a10ef7fb3da3516be Mon Sep 17 00:00:00 2001 From: havok2-htwo Date: Sun, 11 Oct 2026 22:37:05 +0200 Subject: [PATCH 16/33] generate: STRATA_ADMIT_MERGE_FIRST=1 reads a batch admission's last prompt tokens and its first token in one window A batch admission read its header through the verify windows (T=4 + T=2 for the usual 6 tokens) and then its first token in a window of the last prompt token alone. With the switch the last windowed part leaves its last tokens (up to the verifier's max_t, 8, the last prompt token included) to the first window: the part's earlier tokens are read as before, the first window commits every row, the drafter gets the rows of the prompt tokens in it as the prompt windows give them, and only row T-1's output is emitted. Row T-1 sits at the first window's position with the same history and Philox draw, and a row computes what it computes in any window while every expert is in VRAM, so the token and the state are the same. Only for a BGEN admission with every expert of every stage in VRAM (no loan, no swap pending, the zero-doorbell graphs), and not with --batch-mtp, the pipelined windows, pictures, the elastic K/V, a peer device, remote caches, foresight swaps, STRATA_LOGPOS or a checkpoint at the last token. The merged window takes no drafter q (STRATA_SPEC_PROB), adds nothing to the draft counts, and the "PP " line is printed before it. Verifier::max_t() is new. Off by default: the same path as before. Tokens (4x RTX 3090, split 12,24,36, 16 slots, STRATA_IQ_MT_MIN=1): 24 admissions of prompts of 3 to 65 tokens and chat headers with and without an assistant prefill (merged T 3 to 8), greedy, seeded and with penalties, on vs off identical; batch_test16 16/16 and equal to the earlier dump; batch_overlap_test token- and RESUME-identical; batch_interleave_test equal; 47 sampled driver requests equal. Measured (24 admissions, ~131 and ~1195 tokens): header windows 23.5 plus first window 11.5 ms become one 7-token window of 27.6 ms, 7.4 ms less per admission (send to first batch token 246.8 -> 239.4 ms short, 656.1 -> 648.5 long). A window row costs ~2.4 ms up to T=6 and ~4 ms at T=7 and 8 (T=1 11.4, T=7 28.6, T=8 32.1 ms). --- include/strata/core/verify.hpp | 2 + src/program/generate.cpp | 91 ++++++++++++++++++++++++++++------ 2 files changed, 78 insertions(+), 15 deletions(-) diff --git a/include/strata/core/verify.hpp b/include/strata/core/verify.hpp index e190a3b7..c988da3e 100644 --- a/include/strata/core/verify.hpp +++ b/include/strata/core/verify.hpp @@ -120,6 +120,8 @@ public: return t >= 0 && t < 32 && ((nf_mask_ >> t) & 1u) != 0; } static bool nan_guard_on(); + /// The most tokens one window holds (`init`'s `max_t`; 0 before it). + int max_t() const { return max_t_; } /// The sampling the verify window's head applies (temperature / top_p / top_k / seed). Set per /// request; greedy by default. The sampling itself runs OUTSIDE the captured graph - its /// parameters would otherwise be baked forever - so this can change between requests freely. diff --git a/src/program/generate.cpp b/src/program/generate.cpp index cb704d36..06cb05be 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -174,6 +174,18 @@ bool pipe_byield_nodrain_env() { }(); return on; } +// STRATA_ADMIT_MERGE_FIRST=1 (read once; off by default): a batch admission reads the last prompt tokens of its last +// windowed part (up to a window's max_t, the last prompt token included) and its first token in ONE window instead of +// the part's last windows and a window of the last token alone. A row computes what it computes in any window while +// every expert is in VRAM, and row T-1 is the first window's position with its history and its Philox draw, so the +// token and the state are the same; the rows before it commit as the prompt windows commit them +bool admit_merge_first_env() { + static const bool on = [] { + const char* v = std::getenv("STRATA_ADMIT_MERGE_FIRST"); + return v && v[0] != '0'; + }(); + return on; +} // perf-review D-4: the lent slots are refilled with queued copies and one wait; STRATA_REFILL_BLOCKING=1 waits on each // A file-backed arena on AMD (STRATA_ARENA_MMAP; the engine raises ROCclr's pin-in-place threshold, see main): an @@ -11947,6 +11959,28 @@ int main(int argc, char** argv) { std::sort(cuts.begin(), cuts.end()); // the skipped -1s first, n - 1 still last } int64_t at = read_from; + // STRATA_ADMIT_MERGE_FIRST: the last part, when it goes through the windows, leaves its last tokens (up to + // max_t with the last prompt token) to the first window, which starts at merge_at (-1: the first window + // holds the last prompt token alone). Only where every window row is the same in any window: a batch + // admission's first token, every expert of every stage in VRAM (the zero-doorbell graphs, no loan, no swap) + // and the serial loop with nothing else reading its windows + int64_t merge_at = -1; + auto merge_from = [&](int64_t a0, int64_t to) -> int64_t { + if (!admit_merge_first_env() || admit_slot < 0 || max_new != 1 || batch_mtp || pipe) return -1; + if (to != n - 1 || to == turn_at || to == root_at || to == message_at || to == pin_at) return -1; + if (!req_imgs.empty() || kvg.on || peer.valid() || remote_caches || remote_opt || fs_swap) return -1; + if (std::getenv("STRATA_LOGPOS") != nullptr) return -1; + if (host_res.empty() || !pending.empty() || + std::any_of(host_res.begin(), host_res.end(), [](int32_t r) { return r < 0; })) + return -1; + int mt = strata::kernels::kVerifyMaxT; + for (int k = 0; k < n_pipe; ++k) { + if (!stage_verifier(k).ar_live()) return -1; + mt = std::min(mt, stage_verifier(k).max_t()); + } + if (mt < 2) return -1; + return std::max(a0, n - mt); + }; for (const int64_t to : cuts) { if (to <= at) continue; err.clear(); @@ -11959,21 +11993,32 @@ int main(int argc, char** argv) { std::printf("ERR lending the prompt path its slots failed: %s\n", err.c_str()); return 1; } + if (win) merge_at = merge_from(at, to); // (after the refill: the loans are back) + const int64_t read_to = merge_at >= 0 ? merge_at : to; // (merge_at > at: the part's windows before it) const auto tsp = Clock::now(); pp_exact = false; // a batched or pipelined part is in flight: a cancel may leave the state past pp_reached - const bool sp_ok = win ? read_windows(at, to, err) : read_part(at, to, err); + const bool sp_ok = read_to <= at || (win ? read_windows(at, read_to, err) : read_part(at, to, err)); if (sp_ok) pp_exact = true; if (trace) { const double ms = std::chrono::duration(Clock::now() - tsp).count(); (win ? req_times.windows_ms : req_times.read_ms) += ms; - std::fprintf(stderr, "strata trace: read %lld tokens (%s) in %.1f ms\n", (long long) (to - at), + std::fprintf(stderr, "strata trace: read %lld tokens (%s) in %.1f ms\n", (long long) (read_to - at), win ? "windows" : "batched", ms); + if (merge_at >= 0) + std::fprintf(stderr, "strata trace: the first window takes the last %lld prompt tokens\n", + (long long) (n - merge_at)); std::fflush(stderr); } if (!sp_ok && nf_hit) { // #879: DONE nonfinite (the lent slots are refilled below) cancelled = true; break; } + if (sp_ok && merge_at >= 0) { // the server's progress reaches the prompt's end, as after its last window + const double ms = std::chrono::duration(Clock::now() - pp_t0).count(); + std::printf("PP %lld %lld %.0f %.1f\n", (long long) to, (long long) pp_total, ms, + ms > 0.0 ? 1000.0 * (double) (to - pp_from) / ms : 0.0); + std::fflush(stdout); + } if (!sp_ok) { if (yielded_at < 0 && (batch_fatal || !stop_req.load())) { std::fprintf(stderr, "strata serve: %s\n", err.c_str()); @@ -12030,12 +12075,15 @@ int main(int argc, char** argv) { const double prompt_ms = std::chrono::duration(Clock::now() - r0).count(); std::printf("REUSED %lld\n", (long long) resume); // the prompt is read; the first window comes next std::fflush(stdout); - // the verify windows: the first holds the last prompt token alone - int64_t p = n - 1; - int32_t x = (int32_t) ids[(size_t) (n - 1)]; + // the verify windows: the first holds the last prompt token alone (STRATA_ADMIT_MERGE_FIRST: the prompt + // tokens from merge_at on, the last one's output its first token) + const int merge_T = merge_at >= 0 && !cancelled ? (int) (n - merge_at) : 0; + int64_t p = merge_T > 0 ? merge_at : n - 1; + int32_t x = (int32_t) ids[(size_t) p]; // (the drafter writes max_t - 1 drafts: 8 rows with --pipeline-windows 2) const size_t DS = (size_t) std::max(S, use_mtp ? mtp.max_t() : 0); - std::vector drafts(DS, 0), window((size_t) S), outv((size_t) S); + const size_t WS = (size_t) std::max(S, merge_T); + std::vector drafts(DS, 0), window(WS), outv(WS); std::vector dprob(DS, 0.0f); std::vector sbuf((size_t) S, 0); const bool sfx_on = o.suffix_draft > 0 || o.lookup_chain > 0; @@ -12059,7 +12107,7 @@ int main(int argc, char** argv) { // what the session holds once this request is done: the prompt read so far, then every committed token std::vector consumed; consumed.reserve((size_t) (n + max_new + S)); - for (int64_t i = 0; i < n - 1; ++i) consumed.push_back((int32_t) ids[(size_t) i]); + for (int64_t i = 0; i < p; ++i) consumed.push_back((int32_t) ids[(size_t) i]); const char* finish = "length"; const Clock::time_point d0 = Clock::now(); // STRATA_DECODE_TIMING=1: where a request's decode time goes (one line per request) @@ -12749,7 +12797,8 @@ int main(int argc, char** argv) { T = 1; while (T < S_mtp && dprob[(size_t) T - 1] >= (float) req_spec_min_p) ++T; } - if (first_window) T = 1; + if (first_window) T = merge_T > 0 ? merge_T : 1; + const bool merged = first_window && merge_T > 0; // the prompt's last tokens and the first token // a repeat of earlier context (prompt lookup) where the MTP's own first guess agrees: the policy takes it // when its expected tokens per ms, from the measured acceptance and window costs, beat the MTP window's bool from_sfx = false; @@ -12783,7 +12832,10 @@ int main(int argc, char** argv) { const Clock::time_point round0 = Clock::now(); if (p + T > o.max_context) break; window[0] = x; - for (int i = 1; i < T_mtp; ++i) window[(size_t) i] = from_sfx ? sbuf[(size_t) i - 1] : drafts[(size_t) i - 1]; + for (int i = 1; i < T_mtp; ++i) + window[(size_t) i] = merged ? (int32_t) ids[(size_t) (p + i)] + : from_sfx ? sbuf[(size_t) i - 1] + : drafts[(size_t) i - 1]; for (int i = 0; i < chain_n; ++i) window[(size_t) (T_mtp + i)] = cbuf[(size_t) i]; drive.d.layers = 0; drive.d.experts = 0; @@ -12835,7 +12887,8 @@ int main(int argc, char** argv) { const Clock::time_point tw0 = Clock::now(); // STRATA_SPEC_PROB: the MTP drafts' distributions q, judged by rejection sampling (core/spec_prob.hpp); // a suffix window and the lookup chain's tail are point masses and keep the exact-match rule - if (use_mtp && mtp.prob() && !from_sfx && T_mtp > 1) ver.set_spec_q(mtp.spec_q(), T_mtp - 1); + // (never on a first window: a merged one holds prompt tokens, not drafts) + if (use_mtp && mtp.prob() && !from_sfx && !first_window && T_mtp > 1) ver.set_spec_q(mtp.spec_q(), T_mtp - 1); if (!ver.run(T, window.data(), p, win_pool_fn, win_pool_user, outv.data(), err) || drive.d.failed) { std::printf("ERR %s\n", drive.d.failed && drive.d.fail ? drive.d.fail : err.c_str()); return 1; @@ -12849,13 +12902,13 @@ int main(int argc, char** argv) { if (fl != nullptr) { std::vector row((size_t) ver.vocab()); const std::string path = std::string(fl) + "." + std::to_string(fl_n++); - std::FILE* f = ver.copy_logits(0, row.data()) ? std::fopen(path.c_str(), "wb") : nullptr; + std::FILE* f = ver.copy_logits(merged ? T - 1 : 0, row.data()) ? std::fopen(path.c_str(), "wb") : nullptr; if (f == nullptr || std::fwrite(row.data(), sizeof(float), row.size(), f) != row.size()) std::fprintf(stderr, "strata serve: STRATA_DUMP_FIRST_LOGITS: cannot write %s\n", path.c_str()); if (f) std::fclose(f); } } - int a = 0; + int a = merged ? T - 1 : 0; // a merged window commits every row, as the prompt windows do while (a < T - 1 && window[(size_t) a + 1] == outv[(size_t) a]) ++a; if (from_sfx) { ++sfx_windows; sfx_drafts += T - 1; sfx_ok += a; } if (chain_n > 0) { ++chain_windows; chain_drafts += chain_n; chain_ok += std::max(0, a - (T_mtp - 1)); } @@ -12885,13 +12938,21 @@ int main(int argc, char** argv) { finish = "nonfinite"; break; } + // a merged window: the drafter's rows of the prompt tokens in it, as the prompt windows give them + if (merged && use_mtp && !mtp.prefill(ver.final_R_all(), window.data() + 1, T - 1, p, err)) { + if (adapt_thr.joinable()) adapt_thr.join(); + std::printf("ERR %s\n", err.c_str()); + return 1; + } // the window's first a + 1 tokens are in the session now (the last output is not: it is next x) for (int i = 0; i <= a; ++i) consumed.push_back(window[(size_t) i]); - draft_offered += T - 1; - draft_accepted += a; + if (!merged) { // (a merged window's rows are prompt tokens, not drafts) + draft_offered += T - 1; + draft_accepted += a; + } first_window = false; bool eos = false; - for (int i = 0; i <= a && produced_n < max_new && !eos; ++i) { + for (int i = merged ? a : 0; i <= a && produced_n < max_new && !eos; ++i) { // (merged: row T-1 only) std::printf("T %d\n", (int) outv[(size_t) i]); strata::core::progress_beat(); ++produced_n; From bebeb791a460dd1cd777599c9dbfe4cd9b789471 Mon Sep 17 00:00:00 2001 From: havok2-htwo Date: Sun, 11 Oct 2026 23:04:09 +0200 Subject: [PATCH 17/33] generate: STRATA_CKPT_POOL=1 saves checkpoints into dropped ones' vectors, STRATA_CKPT_THREADS=1 saves a split's parts at once STRATA_CKPT_POOL=1 (off by default): the serve loop keeps the running-state vectors of the checkpoints it drops (LRU eviction, the tail one, the prune at a new request, a batch slot's old one), at most two, and the next checkpoint or slot copy goes into them. A save then resizes nothing: no zero-fill of ~118 MB of fresh vectors. Every byte is overwritten by the copy. STRATA_CKPT_THREADS=1 (off by default): a layer split's checkpoint saves the first stage's part on the calling thread and every later stage's on a persistent thread of its own (the copies' private streams are per thread, so short-lived threads would leak them). The threads leave the host thread's one CPU first (to the aux CPUs with --aux-cpus, else to every CPU the process may use): on it the copies only took turns. Measured on a 4-stage split (T16, 24 batch admissions per arm): a turn checkpoint takes 17.2 ms today, 10.4 ms with the pool and 5.6 ms with both; the batch tests, the overlap and interleave tests and a driver run give the same tokens with the switches on as off. --- src/program/generate.cpp | 235 +++++++++++++++++++++++++++++++++++++-- 1 file changed, 227 insertions(+), 8 deletions(-) diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 06cb05be..a60f9da6 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -133,6 +133,8 @@ namespace strata::metal_engine { void set_model_shard(const char* shard1); } / #include #include #include +#include +#include #include #include #include @@ -186,6 +188,27 @@ bool admit_merge_first_env() { }(); return on; } +// STRATA_CKPT_POOL=1 (read once; off by default): the serve loop keeps the running-state vectors of the conversation +// checkpoints it drops (evicted, pruned, a batch slot's old one) and saves the next checkpoint into them, so a save +// resizes nothing (no zero-fill of ~118 MB of fresh vectors) and a slot's copy reuses their pages. Every byte is +// overwritten by the copy, so the checkpoints are the same +bool ckpt_pool_env() { + static const bool on = [] { + const char* v = std::getenv("STRATA_CKPT_POOL"); + return v && v[0] != '0'; + }(); + return on; +} +// STRATA_CKPT_THREADS=1 (read once; off by default): a layer split's checkpoint saves every stage's part at once, the +// first on the calling thread and each later stage's on a thread of its own device (kept for the process: the copies' +// private streams are per thread), instead of one stage after the other. Each part is the same copy of the same state +bool ckpt_threads_env() { + static const bool on = [] { + const char* v = std::getenv("STRATA_CKPT_THREADS"); + return v && v[0] != '0'; + }(); + return on; +} // perf-review D-4: the lent slots are refilled with queued copies and one wait; STRATA_REFILL_BLOCKING=1 waits on each // A file-backed arena on AMD (STRATA_ARENA_MMAP; the engine raises ROCclr's pin-in-place threshold, see main): an @@ -1555,6 +1578,122 @@ bool checkpoint_restore(const ConvCheckpoint& c, strata::core::SessionState& ss, return false; } +/// STRATA_CKPT_POOL: the storage of dropped checkpoints, for the next save or slot copy to reuse. `give` keeps a +/// checkpoint's vectors (its tokens, pictures and marks cleared), `take` hands one back (an empty checkpoint when none +/// is kept). At most `cap` are kept (a batch admission drops and takes about two), the rest are freed as before. +class CheckpointPool { +public: + explicit CheckpointPool(bool on, size_t cap = 2) : on_(on), cap_(cap) {} + bool on() const { return on_; } + void give(ConvCheckpoint&& c) { + if (!on_ || c.gdn.empty()) return; + clear_marks(c); + std::lock_guard lk(mu_); + if (free_.size() < cap_) free_.push_back(std::move(c)); + } + ConvCheckpoint take() { + std::lock_guard lk(mu_); + if (!on_ || free_.empty()) return ConvCheckpoint{}; + ConvCheckpoint c = std::move(free_.back()); + free_.pop_back(); + return c; + } + /// v.erase(remove_if(v, drop)) with the dropped ones given to the pool (the kept ones keep their order) + template void erase_if(std::vector& v, Drop drop) { + size_t w = 0; + for (size_t i = 0; i < v.size(); ++i) { + if (drop(static_cast(v[i]))) { give(std::move(v[i])); continue; } + if (w != i) v[w] = std::move(v[i]); + ++w; + } + v.erase(v.begin() + (std::ptrdiff_t) w, v.end()); + } +private: + static void clear_marks(ConvCheckpoint& c) { + c.ids.clear(); c.imgs.clear(); c.used = 0; c.pinned = false; + for (ConvCheckpoint& part : c.stage_parts) clear_marks(part); + } + bool on_; + size_t cap_; + std::mutex mu_; + std::vector free_; +}; + +/// STRATA_CKPT_THREADS: runs job(0) on the calling thread and job(k), k = 1..n-1, on persistent thread k at the same +/// time, and returns when all have. The threads live as long as this object: a short-lived thread would leave its +/// private copy stream behind on every device it used (conversation_detail::copy_nonblocking). A thread inherits the +/// host thread's one CPU (aux_cpus.hpp), where the copies would only take turns, so each first goes to the aux CPUs +/// (--aux-cpus) or else to every CPU the process may use. One caller at a time; a job does not throw. +class StageThreads { +public: + StageThreads() = default; + StageThreads(const StageThreads&) = delete; + StageThreads& operator=(const StageThreads&) = delete; + ~StageThreads() { + { + std::lock_guard lk(mu_); + stop_ = true; + } + go_.notify_all(); + for (std::thread& t : threads_) t.join(); + } + void run(size_t n, const std::function& job) { + if (n == 0) return; + { + std::lock_guard lk(mu_); + while (threads_.size() + 1 < n) { + const size_t k = threads_.size() + 1; + threads_.emplace_back([this, k] { loop(k); }); + } + job_ = &job; + n_ = n; + pending_ = n - 1; + ++round_; + } + go_.notify_all(); + job(0); + std::unique_lock lk(mu_); + done_.wait(lk, [&] { return pending_ == 0; }); + job_ = nullptr; + } +private: + static void spread_current_thread() { +#if defined(__linux__) + if (strata::aux_cpus::enabled()) { + strata::aux_cpus::pin_current_thread(); + return; + } + cpu_set_t all; + CPU_ZERO(&all); + for (int c = 0; c < CPU_SETSIZE; ++c) CPU_SET(c, &all); + (void) sched_setaffinity(0, sizeof all, &all); // the kernel keeps the CPUs the process may use +#endif + } + void loop(size_t k) { + spread_current_thread(); + uint64_t seen = 0; + std::unique_lock lk(mu_); + for (;;) { + go_.wait(lk, [&] { return stop_ || round_ != seen; }); + if (stop_) return; + seen = round_; + if (k >= n_) continue; // a round with fewer jobs than threads + const std::function* job = job_; + lk.unlock(); + (*job)(k); + lk.lock(); + if (--pending_ == 0) done_.notify_all(); + } + } + std::mutex mu_; + std::condition_variable go_, done_; + std::vector threads_; + const std::function* job_ = nullptr; + size_t n_ = 0, pending_ = 0; + uint64_t round_ = 0; + bool stop_ = false; +}; + // --control-vector-scaled: llama.cpp's `common_control_vector_load` (every file's `direction.` times its scale, // summed; layer 0 has none) and `llama_adapter_cvec::apply` with the projection-mode patch (project: the unit // direction and its norm as the scale), into the tables `cvec_upload` takes. `summary` is what INFO reports; @@ -8202,6 +8341,7 @@ int main(int argc, char** argv) { // #879: a window met non-finite logits: the next request drops every cached state first and reads from token 0 bool nan_flush = false; std::vector checks; + CheckpointPool ckpt_pool(ckpt_pool_env()); // STRATA_CKPT_POOL: the dropped checkpoints' storage, reused uint64_t check_clock = 0; // the checkpoints' LRU clock; creation and every use advance it int64_t tail_ckpt_len = -1; // --prompt-cache-tail: the length of the one tail checkpoint alive (-1 = none) bool cvec_cached = true; // the control vector's state the live session and the checkpoints were read with @@ -8515,6 +8655,7 @@ int main(int argc, char** argv) { ") - a GPU hang; on Windows the driver is then reset"; return false; }; + StageThreads ckpt_threads; // STRATA_CKPT_THREADS: the later stages' parts of a checkpoint (started on first use) auto checkpoint_at = [&](int64_t L, std::vector* parts = nullptr, bool as_tail = false) -> bool { ckpt_why.clear(); if (o.prompt_cache <= 0 || L < 1) return true; @@ -8524,7 +8665,7 @@ int main(int argc, char** argv) { if (!as_tail && L == tail_ckpt_len) tail_ckpt_len = -1; // a periodic one lands here: a normal item now return true; } - ConvCheckpoint c; + ConvCheckpoint c = parts == nullptr ? ckpt_pool.take() : ConvCheckpoint{}; // (STRATA_CKPT_POOL) c.ids.assign(cur.begin(), cur.begin() + L); c.imgs = imgs_below(req_imgs, L); if (parts != nullptr) { @@ -8535,6 +8676,67 @@ int main(int argc, char** argv) { c.dead = std::move((*parts)[0].dead); c.block_pos = std::move((*parts)[0].block_pos); for (size_t i = 1; i < parts->size(); ++i) c.stage_parts.push_back(std::move((*parts)[i])); + } else if (ckpt_pool.on() || ckpt_threads_env()) { + // STRATA_CKPT_POOL / STRATA_CKPT_THREADS: the parts go into the vectors a pooled checkpoint already has + // (none resized), with the threads all at once; part k is stage k's session, synchronized first + const size_t n = stages.size() + 1; + const bool reused = !c.gdn.empty(); // (a pooled one) + c.stage_parts.resize(stages.size()); + for (ConvCheckpoint& part : c.stage_parts) part.ids = c.ids; + std::vector synced(n, 0), saved(n, 0); + std::vector why(n); + std::vector sync_part(n, 0.0), part_ms(n, 0.0); + std::vector thrown(n); // (a failed allocation: thrown here, as without the threads) + const std::function save_part = [&](size_t k) { + try { + const Clock::time_point p0 = Clock::now(); + const strata::core::OnDevice on(k == 0 ? -1 : stages[k - 1]->dev); + const cudaError_t e = cudaDeviceSynchronize(); + if (e != cudaSuccess) { + why[k] = std::string(": the GPU stopped responding before it (") + cudaGetErrorString(e) + + ") - a GPU hang; on Windows the driver is then reset"; + return; + } + synced[k] = 1; + const Clock::time_point p1 = Clock::now(); + saved[k] = checkpoint_save(k == 0 ? c : c.stage_parts[k - 1], k == 0 ? ss : stages[k - 1]->ss, g); + sync_part[k] = std::chrono::duration(p1 - p0).count(); + part_ms[k] = std::chrono::duration(Clock::now() - p0).count(); + } catch (...) { + thrown[k] = std::current_exception(); + } + }; + const Clock::time_point t0 = Clock::now(); + if (ckpt_threads_env()) { + ckpt_threads.run(n, save_part); + } else { + for (size_t k = 0; k < n; ++k) { + save_part(k); + if (!synced[k] || !saved[k]) break; + } + } + for (size_t k = 0; k < n; ++k) + if (thrown[k]) std::rethrow_exception(thrown[k]); + for (size_t k = 0; k < n; ++k) { + if (!synced[k]) { ckpt_why = why[k]; return false; } + if (!saved[k]) return false; + } + if (ckpt_trace) { // sync: the first stage's (the others' are in their parts' times) + const double wall = std::chrono::duration(Clock::now() - t0).count(); + std::string each; + for (size_t k = 0; k < n; ++k) { + char b[32]; + std::snprintf(b, sizeof b, " %.1f", part_ms[k]); + each += b; + } + ++req_times.ckpts; + req_times.sync_ms += sync_part[0]; + req_times.save_ms += wall - sync_part[0]; + std::fprintf(stderr, "strata trace: checkpoint at %lld: sync %.1f ms, save %.1f ms (%zu stage(s)%s, " + "each%s ms, %s)\n", (long long) L, sync_part[0], wall - sync_part[0], n, + ckpt_threads_env() ? " at once" : "", each.c_str(), + reused ? "into a dropped checkpoint's vectors" : "new vectors"); + } } else { Clock::time_point t0 = Clock::now(); auto lap = [&](double& acc) { // (STRATA_TRACE only) @@ -8569,9 +8771,11 @@ int main(int argc, char** argv) { c.used = ++check_clock; if (as_tail) { // only one tail checkpoint stays alive: the previous request's goes const int64_t old_tail = tail_ckpt_len; - checks.erase(std::remove_if(checks.begin(), checks.end(), [&](const ConvCheckpoint& k) { - return old_tail >= 0 && (int64_t) k.ids.size() == old_tail; - }), checks.end()); + auto old = [&](const ConvCheckpoint& k) { return old_tail >= 0 && (int64_t) k.ids.size() == old_tail; }; + if (ckpt_pool.on()) + ckpt_pool.erase_if(checks, old); + else + checks.erase(std::remove_if(checks.begin(), checks.end(), old), checks.end()); tail_ckpt_len = L; } else if (L == tail_ckpt_len) { tail_ckpt_len = -1; // the flagged tail was dropped and a normal checkpoint takes its length @@ -8600,6 +8804,7 @@ int main(int argc, char** argv) { } const size_t victim = strata::program::conv_cache::eviction_victim( stamps.data(), stamps.size(), o.prompt_cache, tail_flags.get(), pin_flags.get()); + ckpt_pool.give(std::move(checks[victim])); // (STRATA_CKPT_POOL; else nothing) checks.erase(checks.begin() + (std::ptrdiff_t) victim); } if (ckpt_trace && checks.size() < before_evict) { @@ -11325,9 +11530,13 @@ int main(int argc, char** argv) { if (strata::kernels::cvec().loaded()) strata::kernels::cvec_set_enabled(want_cvec); // this request rewrites every cell from `resume` on, so a checkpoint past it (or not on this prompt's // path) no longer has its cells; the ones kept are prefixes of both the old tokens and the new - checks.erase(std::remove_if(checks.begin(), checks.end(), [&](const ConvCheckpoint& c) { - return (int64_t) c.ids.size() > resume || !starts_with(c.ids, c.imgs); - }), checks.end()); + auto off_path = [&](const ConvCheckpoint& c) { + return (int64_t) c.ids.size() > resume || !starts_with(c.ids, c.imgs); + }; + if (ckpt_pool.on()) // STRATA_CKPT_POOL: their storage is the next checkpoint's + ckpt_pool.erase_if(checks, off_path); + else + checks.erase(std::remove_if(checks.begin(), checks.end(), off_path), checks.end()); live_ok = false; // until this request has finished, the session is in between // the elastic K/V: the outgoing session is parked and this request rewrites every cell from `resume` on, // so cells past this prompt's are no longer anyone's - far more than it needs go back to the cache @@ -13197,6 +13406,8 @@ int main(int argc, char** argv) { if (cont) { ver.set_slot_sampling(admit_slot, req_sp); // the request's own sampling, row by row BSlot& sl = bs[(size_t) admit_slot]; + if (ckpt_pool.on()) + for (ConvCheckpoint& c : sl.checks) ckpt_pool.give(std::move(c)); sl = BSlot{}; const auto tc2 = Clock::now(); // (the slot's old checkpoints freed) sl.active = true; @@ -13223,7 +13434,15 @@ int main(int argc, char** argv) { std::equal(c.ids.begin(), c.ids.end(), live.begin())) best = &c; const auto tc3 = Clock::now(); - if (best != nullptr && !sl.img) sl.checks.push_back(*best); + if (best != nullptr && !sl.img) { + if (ckpt_pool.on()) { // a copy into a dropped checkpoint's vectors (their pages are in) + ConvCheckpoint c = ckpt_pool.take(); + c = *best; + sl.checks.push_back(std::move(c)); + } else { + sl.checks.push_back(*best); + } + } const auto tc4 = Clock::now(); std::fprintf(stderr, "strata batch: slot %d takes %lld tokens (copied in %.1f ms)\n", admit_slot, (long long) live.size(), std::chrono::duration(tc4 - tc0).count()); From 139d702ebdcae407a258d041aa6568a92c2a890d Mon Sep 17 00:00:00 2001 From: havok2-htwo Date: Sun, 11 Oct 2026 23:30:14 +0200 Subject: [PATCH 18/33] generate: STRATA_SLOT_CKPT_MOVE=1 moves a batch admission's turn checkpoint into the slot A batch admission copied the main chain's longest checkpoint into the slot (~112 MB of host vectors, 7.6 ms, ~60 ms on fresh pages). With the switch, the request's own turn checkpoint (or one it took out of the slot it is admitted to) moves instead; a root, a pinned prefix and any other checkpoint the chain shares are still copied. The chain then no longer holds it, so the request path also looks in the slots: - while the main session holds its tokens (live, its cells below it), a slot's checkpoint is restored on the main session as a chain one would be, with no K/V copy; when that slot is the one the request is admitted to, it moves back into the chain first (the admission drops the slot's checkpoints), else the slot keeps it and the admission copies it as it copied the chain's; - an active slot's checkpoints are a slot source like an idle slot's (its windows write its cells from p on): a second request with the same history after the main session moved on restores instead of reading it all; - a slot source that is the admit slot moves its checkpoint into the chain instead of copying it. The switch also keeps the dropped checkpoints' storage as STRATA_CKPT_POOL=1 does: a moved checkpoint frees nothing at the next prune, so without it every save faulted in fresh pages (17 -> 38-60 ms, more than the copy saved). Off by default: nothing changes. A session SAVE or a parked conversation right after an admission lacks the moved turn checkpoint (the slot holds it). --- src/program/generate.cpp | 111 +++++++++++++++++++++++++++++++++++---- 1 file changed, 101 insertions(+), 10 deletions(-) diff --git a/src/program/generate.cpp b/src/program/generate.cpp index a60f9da6..bfbb128e 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -209,6 +209,19 @@ bool ckpt_threads_env() { }(); return on; } +// STRATA_SLOT_CKPT_MOVE=1 (read once; off by default): a batch admission MOVES its own turn checkpoint into the slot +// instead of copying it (~112 MB of host vectors). The main session's chain no longer holds it, so the request path +// looks for it in the slots' checkpoints too: while the main session's cells still hold its tokens it is restored there +// as before (no K/V copy), else an active slot holding it gives it back like an idle one (a second request with the +// same history). The same bytes are restored from another container, so the tokens are the same. It keeps the +// dropped checkpoints' storage as STRATA_CKPT_POOL does (the slot's old checkpoint is the next save's) +bool slot_ckpt_move_env() { + static const bool on = [] { + const char* v = std::getenv("STRATA_SLOT_CKPT_MOVE"); + return v && v[0] != '0'; + }(); + return on; +} // perf-review D-4: the lent slots are refilled with queued copies and one wait; STRATA_REFILL_BLOCKING=1 waits on each // A file-backed arena on AMD (STRATA_ARENA_MMAP; the engine raises ROCclr's pin-in-place threshold, see main): an @@ -8341,7 +8354,9 @@ int main(int argc, char** argv) { // #879: a window met non-finite logits: the next request drops every cached state first and reads from token 0 bool nan_flush = false; std::vector checks; - CheckpointPool ckpt_pool(ckpt_pool_env()); // STRATA_CKPT_POOL: the dropped checkpoints' storage, reused + // STRATA_CKPT_POOL: the dropped checkpoints' storage, reused. STRATA_SLOT_CKPT_MOVE turns it on too: a moved + // checkpoint frees nothing at the next prune, so every save would fault in fresh pages (17 -> 40-60 ms) + CheckpointPool ckpt_pool(ckpt_pool_env() || slot_ckpt_move_env()); uint64_t check_clock = 0; // the checkpoints' LRU clock; creation and every use advance it int64_t tail_ckpt_len = -1; // --prompt-cache-tail: the length of the one tail checkpoint alive (-1 = none) bool cvec_cached = true; // the control vector's state the live session and the checkpoints were read with @@ -11323,8 +11338,29 @@ int main(int argc, char** argv) { from_live = false; } } + // STRATA_SLOT_CKPT_MOVE: a turn checkpoint a batch admission moved into its slot is still one of the main + // session's while the main session holds its tokens (the cells below it are the ones it was taken over): + // it is restored there as one of `checks` would be (lent_slot: the slot that keeps it). moved_in: the length + // of a slot's checkpoint this request moved into `checks` (from the slot it is admitted to), -1: none + int lent_slot = -1; + int64_t moved_in = -1; + if (slot_ckpt_move_env() && o.prompt_cache > 0 && want_cvec == cvec_cached && live_ok) + for (int b = 0; b < (int) bs.size(); ++b) { + if (bs[(size_t) b].cvec != cvec_cached) continue; + for (const ConvCheckpoint& c : bs[(size_t) b].checks) { + const int64_t L = (int64_t) c.ids.size(); + if (L > resume && L <= (int64_t) live.size() && starts_with(c.ids, c.imgs) && + std::equal(c.ids.begin(), c.ids.end(), live.begin()) && imgs_below(live_imgs, L) == c.imgs) { + resume = L; + from_live = false; + lent_slot = b; + } + } + } // --batch: an idle slot that holds the start of this prompt (the conversation it served last) is a - // source too - its sessions are copied back below, so only the new part is read + // source too - its sessions are copied back below, so only the new part is read. STRATA_SLOT_CKPT_MOVE: an + // active slot's checkpoints too (its windows write its cells from p on, so the ones below a checkpoint still + // hold its prompt; the groups have finished before a request is read) int slot_source = -1; int64_t slot_tokens = 0; bool resumed_from0 = false; // a prompt read parked in a slot (BYIELD) that had started at token 0 @@ -11332,8 +11368,9 @@ int main(int argc, char** argv) { if (o.prompt_cache > 0 && req_imgs.empty()) for (int b = 0; b < (int) bs.size(); ++b) { const BSlot& sl = bs[(size_t) b]; - if (sl.active || !sl.cached || sl.cvec != want_cvec) continue; - if ((int64_t) sl.ids.size() > std::max(resume, slot_tokens) && starts_with(sl.ids, {})) { + const bool idle_source = !sl.active && sl.cached; + if (sl.cvec != want_cvec || !(idle_source || (sl.active && slot_ckpt_move_env()))) continue; + if (idle_source && (int64_t) sl.ids.size() > std::max(resume, slot_tokens) && starts_with(sl.ids, {})) { slot_source = b; slot_tokens = (int64_t) sl.ids.size(); slot_ck = nullptr; @@ -11422,6 +11459,7 @@ int main(int argc, char** argv) { return 1; } if (slot_source >= 0) { + lent_slot = -1; // (a longer start than the main session's) const auto t0 = Clock::now(); if (!copy_from_slot(slot_source, slot_ck, err)) { // the main session may be half written: read this prompt from the start @@ -11444,7 +11482,18 @@ int main(int argc, char** argv) { } if (slot_ck != nullptr) { live = slot_ck->ids; - checks.push_back(*slot_ck); // the main session's chain has it now + if (slot_ckpt_move_env() && admit_slot == slot_source) { + // STRATA_SLOT_CKPT_MOVE: the slot this request continues in drops its checkpoints at the + // admission, so this one moves (and moves on into the slot then: moved_in) + std::vector& sc = bs[(size_t) slot_source].checks; + const auto it = sc.begin() + (slot_ck - sc.data()); + checks.push_back(std::move(*it)); + sc.erase(it); + slot_ck = &checks.back(); + moved_in = (int64_t) slot_ck->ids.size(); + } else { + checks.push_back(*slot_ck); // the main session's chain has it now + } checks.back().used = ++check_clock; } else { live = bs[(size_t) slot_source].ids; @@ -11517,6 +11566,7 @@ int main(int argc, char** argv) { conversations.retain(std::move(incoming->kv), int64_t(live.size()), std::move(stage_kv)); } incoming.reset(); // Running-state/checkpoint copies are no longer needed. + lent_slot = -1; // (the main session holds the parked conversation now) std::fprintf(stderr, "strata serve: conversation cache: restored %lld tokens (%s) in %.1f ms; parked=%zu bytes=%zu\n", (long long) resume, from_live ? "live" : "checkpoint", std::chrono::duration(Clock::now() - t0).count(), @@ -11563,6 +11613,11 @@ int main(int argc, char** argv) { } else if (!from_live) { ConvCheckpoint* c = nullptr; for (ConvCheckpoint& k : checks) if ((int64_t) k.ids.size() == resume) c = &k; + bool lent = false; // STRATA_SLOT_CKPT_MOVE: the one a slot keeps (found above) + if (c == nullptr && lent_slot >= 0) + for (ConvCheckpoint& k : bs[(size_t) lent_slot].checks) + if ((int64_t) k.ids.size() == resume && starts_with(k.ids, k.imgs)) { c = &k; lent = true; } + if (!lent) lent_slot = -1; if (c != nullptr) c->used = ++check_clock; // mounting through it is the use LRU counts static const bool reread = std::getenv("STRATA_CKPT_REREAD") != nullptr; if (reread && c != nullptr) { @@ -11592,6 +11647,20 @@ int main(int argc, char** argv) { std::printf("ERR restoring a conversation checkpoint failed\n"); return 1; } + if (lent && lent_slot == admit_slot) { + // the slot this request continues in drops its checkpoints at the admission: this one moves back + // into the chain (and on into the slot then: moved_in) + std::vector& sc = bs[(size_t) lent_slot].checks; + const auto it = sc.begin() + (c - sc.data()); + checks.push_back(std::move(*it)); + sc.erase(it); + moved_in = resume; + lent_slot = -1; + } + if (lent && trace) + std::fprintf(stderr, "strata trace: the checkpoint at %lld restored from slot %d's%s\n", + (long long) resume, lent_slot >= 0 ? lent_slot : admit_slot, + lent_slot >= 0 ? "" : " (moved back into the chain)"); } // KV streaming: the drafter's ring may hold cells past `resume` from a longer turn; the main layers' // host copies and slots are always current (every writer writes both), so they need nothing @@ -13429,12 +13498,34 @@ int main(int argc, char** argv) { sl.cvec = cvec_cached; sl.img = !live_imgs.empty(); // pictures: not matched again by tokens alone, so not cached const ConvCheckpoint* best = nullptr; - for (const ConvCheckpoint& c : checks) + size_t best_at = 0; // its place in `checks` (STRATA_SLOT_CKPT_MOVE) + for (size_t i = 0; i < checks.size(); ++i) { + const ConvCheckpoint& c = checks[i]; if (c.ids.size() < live.size() && (best == nullptr || c.ids.size() > best->ids.size()) && - std::equal(c.ids.begin(), c.ids.end(), live.begin())) + std::equal(c.ids.begin(), c.ids.end(), live.begin())) { best = &c; + best_at = i; + } + } + bool best_lent = false; + // STRATA_SLOT_CKPT_MOVE: the checkpoint this request mounted from another slot (that slot keeps it) + if (lent_slot >= 0 && lent_slot != admit_slot && (best == nullptr || (int64_t) best->ids.size() < resume)) + for (const ConvCheckpoint& c : bs[(size_t) lent_slot].checks) + if ((int64_t) c.ids.size() == resume && c.ids.size() < live.size() && + std::equal(c.ids.begin(), c.ids.end(), live.begin())) { + best = &c; + best_lent = true; + } + // STRATA_SLOT_CKPT_MOVE: this request's own turn checkpoint (or the one it moved out of this slot) + // moves into the slot; a pinned prefix, a root and any other the chain shares are copied as before + const bool move_best = slot_ckpt_move_env() && best != nullptr && !best_lent && !sl.img && + !best->pinned && ((turn_at > 0 && (int64_t) best->ids.size() == turn_at) || + (int64_t) best->ids.size() == moved_in); const auto tc3 = Clock::now(); - if (best != nullptr && !sl.img) { + if (move_best) { + sl.checks.push_back(std::move(checks[best_at])); + checks.erase(checks.begin() + (std::ptrdiff_t) best_at); + } else if (best != nullptr && !sl.img) { if (ckpt_pool.on()) { // a copy into a dropped checkpoint's vectors (their pages are in) ConvCheckpoint c = ckpt_pool.take(); c = *best; @@ -13454,11 +13545,11 @@ int main(int argc, char** argv) { std::fprintf(stderr, "strata trace: admission of slot %d: drain %.1f, prompt %.1f (read %.1f, " "windows %.1f, %d checkpoint(s) %.1f = sync %.1f + save %.1f + evict %.1f, " "rest %.1f), first window %.1f, slot copy %.1f, slot freed %.1f, " - "checkpoint copy %.1f\n", admit_slot, adm_drain_ms, prompt_ms, + "checkpoint copy %.1f%s\n", admit_slot, adm_drain_ms, prompt_ms, req_times.read_ms, req_times.windows_ms, req_times.ckpts, ck, req_times.sync_ms, req_times.save_ms, req_times.evict_ms, prompt_ms - req_times.read_ms - req_times.windows_ms - ck, decode_ms, span(tc0, tc1), - span(tc1, tc2), span(tc3, tc4)); + span(tc1, tc2), span(tc3, tc4), move_best ? " (moved)" : ""); } } std::printf("BADM %d %d\n", admit_slot, cont ? 1 : 0); From ca239cdabc8e9e7121b61f26e361fa34994f8c6f Mon Sep 17 00:00:00 2001 From: havok2-htwo Date: Sun, 11 Oct 2026 23:54:10 +0200 Subject: [PATCH 19/33] generate: STRATA_SLOT_COPY_BATCHSYNC=1 queues the direct slot copy and synchronizes each device once The direct slot copy (STRATA_SLOT_COPY_DIRECT) waited for each of its ~116 copies on the private copy stream. With the switch, conversation_checkpoint_copy and conversation_kv_copy only queue them (new `queued` argument, default off), and the slot copy's closing sync_all is the one wait per device. A streamed K/V state (kv_mode != 0) has its residency refresh on the legacy stream, which is not ordered after a non-blocking stream: conversation_detail::order_after_queued records an event on the private stream and makes the legacy stream wait for it first. The copies stay on the private non-blocking stream. Same copies in the same order on one stream: tokens are identical. Measured on 4x RTX 3090 (T16-142, 24 admissions): the slot copy takes 0.5 ms instead of 1.3 ms; batch_test16 16/16, batch_overlap_test and batch_interleave_test token-identical to the references; a --kv-resident 20480 run with a 21K prompt is identical with the switch off and on. --- include/strata/core/conversation_snapshot.hpp | 7 +++- src/core/conversation_copy.hpp | 37 +++++++++++++++++-- src/core/conversation_snapshot.cpp | 9 ++++- src/core/conversation_state.cpp | 11 +++--- src/program/generate.cpp | 17 ++++++++- 5 files changed, 67 insertions(+), 14 deletions(-) diff --git a/include/strata/core/conversation_snapshot.hpp b/include/strata/core/conversation_snapshot.hpp index 5a97bff3..449fc831 100644 --- a/include/strata/core/conversation_snapshot.hpp +++ b/include/strata/core/conversation_snapshot.hpp @@ -27,8 +27,10 @@ bool conversation_kv_restore(const ConversationKv& image, const QsaState& state, int64_t upto, bool include_index, std::string& error); // conversation_kv_save(from) + conversation_kv_restore(to) without a host image, for two states of the same layout. // The copies are complete on return; the residency refresh is queued on the legacy stream like the restore's. +// `queued`: the copies are only queued on the private copy stream, the refresh is ordered after them on the device, +// and the caller synchronizes the device before it reads or writes either state. bool conversation_kv_copy(const QsaState& from, const QsaState& to, const ModelGeometry& g, - int64_t upto, bool include_index, std::string& error); + int64_t upto, bool include_index, std::string& error, bool queued = false); // Diagnostic read-back after a synchronized restore. Uses 64 KiB of stack // workspace, compares authoritative bytes and resident draft-ring pages, and // fingerprints the authoritative payload only. Never changes model state. @@ -66,8 +68,9 @@ bool conversation_checkpoint_restore(const ConversationCheckpoint& checkpoint, S const ModelGeometry& g, std::string& error); // conversation_checkpoint_save(from) + conversation_checkpoint_restore(to) of `ids` without a host image, for two // sessions carved alike on the same device; the caller synchronizes the device before (as for the restore). +// `queued`: the copies are only queued (the private copy stream), and the caller synchronizes the device after too. bool conversation_checkpoint_copy(const SessionState& from, SessionState& to, const std::vector& ids, - const ModelGeometry& g, std::string& error); + const ModelGeometry& g, std::string& error, bool queued = false); struct ConversationView { const std::vector& ids; diff --git a/src/core/conversation_copy.hpp b/src/core/conversation_copy.hpp index 0dea46a3..7e8341b3 100644 --- a/src/core/conversation_copy.hpp +++ b/src/core/conversation_copy.hpp @@ -19,7 +19,8 @@ namespace strata::core::conversation_detail { /// device, and while another thread captures a graph on one (a drafter or a stage worker), HIP refuses it with /// "operation would make the legacy stream depend on a capturing blocking stream". The caller's contract is /// unchanged: the device was synchronized before the copy (the copy itself is complete on return). -inline cudaError_t copy_nonblocking(void* dst, const void* src, size_t bytes) { +/// private_stream: this thread's stream on the current device, created on first use. +inline cudaError_t private_stream(cudaStream_t& s) { int dev = 0; cudaError_t e = cudaGetDevice(&dev); if (e != cudaSuccess) return e; @@ -30,9 +31,18 @@ inline cudaError_t copy_nonblocking(void* dst, const void* src, size_t bytes) { e = cudaStreamCreateWithFlags(&streams[(size_t) dev], cudaStreamNonBlocking); if (e != cudaSuccess) { streams[(size_t) dev] = nullptr; return e; } } - cudaStream_t s = streams[(size_t) dev]; - e = cudaMemcpyAsync(dst, src, bytes, cudaMemcpyDefault, s); + s = streams[(size_t) dev]; + return cudaSuccess; +} + +/// `queued`: the copy is only queued on the private stream, and the caller synchronizes the device (or orders a +/// later launch after it with order_after_queued) before anything reads the target or writes the source. +inline cudaError_t copy_nonblocking(void* dst, const void* src, size_t bytes, bool queued = false) { + cudaStream_t s = nullptr; + cudaError_t e = private_stream(s); if (e != cudaSuccess) return e; + e = cudaMemcpyAsync(dst, src, bytes, cudaMemcpyDefault, s); + if (e != cudaSuccess || queued) return e; e = cudaStreamSynchronize(s); core::progress_beat(); // #2049: a parked conversation is many of these; each one that lands is progress return e; @@ -87,4 +97,25 @@ inline std::vector copy_checkpoints_beating(const std::v return out; } +/// Work queued on the legacy stream after this call starts after every copy this thread queued on the current +/// device's private stream (an event the legacy stream waits for; no host wait). +inline cudaError_t order_after_queued() { + cudaStream_t s = nullptr; + cudaError_t e = private_stream(s); + if (e != cudaSuccess) return e; + int dev = 0; + e = cudaGetDevice(&dev); + if (e != cudaSuccess) return e; + thread_local std::vector events; + if (dev < 0) dev = 0; + if ((size_t) dev >= events.size()) events.resize((size_t) dev + 1, nullptr); // never destroyed: process lifetime + if (!events[(size_t) dev]) { + e = cudaEventCreateWithFlags(&events[(size_t) dev], cudaEventDisableTiming); + if (e != cudaSuccess) { events[(size_t) dev] = nullptr; return e; } + } + e = cudaEventRecord(events[(size_t) dev], s); + if (e != cudaSuccess) return e; + return cudaStreamWaitEvent(nullptr, events[(size_t) dev], 0); +} + } // namespace strata::core::conversation_detail diff --git a/src/core/conversation_snapshot.cpp b/src/core/conversation_snapshot.cpp index 852e42df..d0dd80a1 100644 --- a/src/core/conversation_snapshot.cpp +++ b/src/core/conversation_snapshot.cpp @@ -221,7 +221,7 @@ bool refresh_residency(const QsaState& st, const ModelGeometry& g, int64_t upto, } // namespace bool conversation_kv_copy(const QsaState& from, const QsaState& to, const ModelGeometry& g, - int64_t upto, bool index, std::string& error) { + int64_t upto, bool index, std::string& error, bool queued) { Layout lf{}, lt{}; if (!layout(from, g, upto, index, lf, error) || !valid(from, lf, upto, error) || !layout(to, g, upto, index, lt, error) || !valid(to, lt, upto, error)) return false; @@ -234,13 +234,18 @@ bool conversation_kv_copy(const QsaState& from, const QsaState& to, const ModelG // The same bytes conversation_kv_save + conversation_kv_restore move, without the host image: each part // straight from the source's authoritative pool into the target's (device or mapped host memory), through the // private non-blocking stream the other snapshot copies use (complete on return, before the residency refresh). + // `queued`: the copies are only queued, and a streamed state's refresh waits for them on the device (an event). const auto src = pools(from); const auto dst = pools(to); const std::array sizes = {lf.data, lf.value_data, lf.scales, lf.value_scales, lf.pooled}; for (size_t i = 0; i < sizes.size(); ++i) { if (!sizes[i]) continue; if (!src[i] || !dst[i]) { error = "conversation snapshot: missing state buffer"; return false; } - const cudaError_t e = conversation_detail::copy_nonblocking(dst[i], src[i], sizes[i]); + const cudaError_t e = conversation_detail::copy_nonblocking(dst[i], src[i], sizes[i], queued); + if (e != cudaSuccess) { error = std::string("conversation snapshot direct copy: ") + cudaGetErrorString(e); return false; } + } + if (queued && to.kv_mode != 0) { + const cudaError_t e = conversation_detail::order_after_queued(); if (e != cudaSuccess) { error = std::string("conversation snapshot direct copy: ") + cudaGetErrorString(e); return false; } } return refresh_residency(to, g, upto, error); diff --git a/src/core/conversation_state.cpp b/src/core/conversation_state.cpp index 74f0e474..56ec7c53 100644 --- a/src/core/conversation_state.cpp +++ b/src/core/conversation_state.cpp @@ -30,10 +30,10 @@ bool sync(std::string& error) { return false; } -bool copy(void* dst, const void* src, size_t bytes, std::string& error) { +bool copy(void* dst, const void* src, size_t bytes, std::string& error, bool queued = false) { if (!bytes) return true; if (!dst || !src) return fail(error, "missing running-state buffer"); - const auto status = conversation_detail::copy_nonblocking(dst, src, bytes); + const auto status = conversation_detail::copy_nonblocking(dst, src, bytes, queued); if (status == cudaSuccess) return true; error = std::string("conversation snapshot running-state copy: ") + cudaGetErrorString(status); return false; @@ -216,17 +216,18 @@ bool conversation_checkpoint_restore(const ConversationCheckpoint& c, SessionSta } bool conversation_checkpoint_copy(const SessionState& from, SessionState& to, const std::vector& ids, - const ModelGeometry& g, std::string& error) { + const ModelGeometry& g, std::string& error, bool queued) { // conversation_checkpoint_save(from) + conversation_checkpoint_restore(to) without the host image, for two // sessions carved alike on the same device (a stage's own session and its batch slots): the same bytes into - // the same places, through copy() like the restore (the private non-blocking stream, complete on return). + // the same places, through copy() like the restore (the private non-blocking stream, complete on return unless + // `queued`: then the caller synchronizes the device). ConversationStateSizes zf, zt; if (!checkpoint_targets(from, g, ids.size(), zf, error) || !checkpoint_targets(to, g, ids.size(), zt, error)) return false; if (zf.gdn != zt.gdn || zf.tail != zt.tail || zf.dead != zt.dead || zf.block_pos != zt.block_pos || owned_qsa(from) != owned_qsa(to) || (from.ple_hist != nullptr) != (to.ple_hist != nullptr)) return fail(error, "direct copy between differently carved sessions"); - auto acopy = [&](void* dst, const void* src, size_t bytes) { return copy(dst, src, bytes, error); }; + auto acopy = [&](void* dst, const void* src, size_t bytes) { return copy(dst, src, bytes, error, queued); }; if (!acopy(to.gdn_state, from.gdn_state, zf.gdn) || !acopy(to.ple_hist, from.ple_hist, from.ple_hist ? zf.ple : 0)) return false; for (size_t j = 0; j < owned_qsa(from); ++j) { diff --git a/src/program/generate.cpp b/src/program/generate.cpp index bfbb128e..45698d90 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -222,6 +222,17 @@ bool slot_ckpt_move_env() { }(); return on; } +// STRATA_SLOT_COPY_BATCHSYNC=1 (read once; off by default): the direct slot copy (STRATA_SLOT_COPY_DIRECT) only queues +// its copies on each device's private copy stream and synchronizes every device once at the end, instead of waiting +// for each of its ~116 copies. A streamed K/V state's residency refresh waits for its copies through an event. The +// same copies in the same order on one stream, so the slot holds the same bytes +bool slot_copy_batchsync_env() { + static const bool on = [] { + const char* v = std::getenv("STRATA_SLOT_COPY_BATCHSYNC"); + return v && v[0] != '0'; + }(); + return on; +} // perf-review D-4: the lent slots are refilled with queued copies and one wait; STRATA_REFILL_BLOCKING=1 waits on each // A file-backed arena on AMD (STRATA_ARENA_MMAP; the engine raises ROCclr's pin-in-place threshold, see main): an @@ -10213,16 +10224,18 @@ int main(int argc, char** argv) { // before the caller reuses the sessions (its zeroing runs on non-blocking streams, not ordered against these) auto failed = [&]() { (void) sync_all(); return false; }; if (!sync_all()) { e = "batch slot copy: device sync failed"; return false; } + // STRATA_SLOT_COPY_BATCHSYNC: every copy is only queued, and the sync_all below is the one wait per device + const bool queued = slot_copy_batchsync_env(); for (size_t k = 0; k < bslot_ss.size(); ++k) { strata::core::SessionState& main_ss = k == 0 ? ss : stages[k - 1]->ss; strata::core::SessionState& slot_ss = *bslot_ss[k][(size_t) b]; strata::core::SessionState& from = into_slot ? main_ss : slot_ss; strata::core::SessionState& to = into_slot ? slot_ss : main_ss; const strata::core::OnDevice on_k(k == 0 ? 0 : stages[k - 1]->dev); - if (!strata::core::conversation_checkpoint_copy(from, to, ids, g, e)) return failed(); + if (!strata::core::conversation_checkpoint_copy(from, to, ids, g, e, queued)) return failed(); for (int64_t j = 0; j < from.qsa_alloc; ++j) if (!strata::core::conversation_kv_copy(from.qsa_states[from.qsa_ord0 + j], - to.qsa_states[to.qsa_ord0 + j], g, upto, true, e)) + to.qsa_states[to.qsa_ord0 + j], g, upto, true, e, queued)) return failed(); } if (!sync_all()) { e = "batch slot copy: device sync failed"; return false; } From a923889bd2b1055bf2a8139bad4caef425983633 Mon Sep 17 00:00:00 2001 From: havok2-htwo Date: Mon, 12 Oct 2026 00:13:58 +0200 Subject: [PATCH 20/33] generate: review fixes for the admission switches STRATA_SLOT_CKPT_MOVE: an active slot is a slot source only when the main drafter's rows come along or are not drafted from (no --mtp, --batch-mtp, or a batch admission). The slot copy takes the main layers' cells only, so a solo GEN beside active slots would draft from another conversation's drafter rows below its start; it reads its prompt as with the switch off. STRATA_CKPT_THREADS: a checkpoint thread widens its CPU mask before it goes to the aux CPUs, so the mask the aux placement restores (a request with aux_cpus=0) is the wide one, not the host thread's single CPU. STRATA_ADMIT_MERGE_FIRST: a merged first window counts as one row in the STRATA_DECODE_TIMING window statistics (its prompt rows are not decode rows). --- src/program/generate.cpp | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 45698d90..839fc861 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -1683,14 +1683,13 @@ public: private: static void spread_current_thread() { #if defined(__linux__) - if (strata::aux_cpus::enabled()) { - strata::aux_cpus::pin_current_thread(); - return; - } + // wide first: the mask the aux placement keeps as this thread's own is the one restore() puts back (a request + // with aux_cpus=0), and the host's one CPU must not be it cpu_set_t all; CPU_ZERO(&all); for (int c = 0; c < CPU_SETSIZE; ++c) CPU_SET(c, &all); (void) sched_setaffinity(0, sizeof all, &all); // the kernel keeps the CPUs the process may use + strata::aux_cpus::pin_current_thread(); // (a no-op while the feature is off) #endif } void loop(size_t k) { @@ -11382,7 +11381,10 @@ int main(int argc, char** argv) { for (int b = 0; b < (int) bs.size(); ++b) { const BSlot& sl = bs[(size_t) b]; const bool idle_source = !sl.active && sl.cached; - if (sl.cvec != want_cvec || !(idle_source || (sl.active && slot_ckpt_move_env()))) continue; + // (an active slot only where the drafter's rows come along or are not drafted from: the copy + // takes the main layers' cells, so the main drafter would keep another conversation's below it) + const bool active_source = sl.active && slot_ckpt_move_env() && (!use_mtp || batch_mtp || admit_slot >= 0); + if (sl.cvec != want_cvec || !(idle_source || active_source)) continue; if (idle_source && (int64_t) sl.ids.size() > std::max(resume, slot_tokens) && starts_with(sl.ids, {})) { slot_source = b; slot_tokens = (int64_t) sl.ids.size(); @@ -13265,7 +13267,7 @@ int main(int argc, char** argv) { const Clock::time_point tw3 = Clock::now(); auto msd = [](Clock::time_point a0, Clock::time_point b0) { return std::chrono::duration(b0 - a0).count(); }; dt_run += msd(tw0, tw1); dt_commit += msd(tw1, tw2); dt_draft += msd(tw2, tw3); - ++dec_windows; dec_T += T; + ++dec_windows; dec_T += merged ? 1 : T; // a merged window's prompt rows are not decode rows } pcie_auto_step(req_pcie_frac); // the default share, refined from the CPU pool's speed (PcieAuto); a request's own share is left alone if (adapt_thr.joinable()) { From 62fc7c8a3c984a3a3303af13c9999bb55f4aaa12 Mon Sep 17 00:00:00 2001 From: havok2-htwo Date: Mon, 12 Oct 2026 02:58:41 +0200 Subject: [PATCH 21/33] prefill: STRATA_MMQ_GROUP_SORT=1 sorts the full MMQ groups by row count, keeping the partial group STRATA_MMQ_RESIDENT_SORT_NE=1 puts a fully resident layer's experts in row-count order, so each 16-expert group's max_rows (its tile padding) is close to its experts' own. It also moves the hottest experts into the last, partial group, whose few tiles take MMQ's stream-k split: the K boundaries move with the group's tile count and the prompt's bits change. The new switch sorts only order[0, n - n % 16] (mmq_resident_sort_span) and leaves the partial group's experts, and so its rows, where they were. A full group's launch has 160 (gate/up) or 320 (down) tiles per column tile; mmq::whole_tiles checks on every visible GPU that every such launch runs one block per tile (tile efficiency >= 90 %, NVIDIA) and that all tile widths share the I/K tiles and SRAM layout. Then each expert's rows get the same bits in any full group whatever its group-mates and max_rows. Where it does not hold (e.g. 108 or 128 SMs, AMD's stream-k grid) the switch does nothing. RESIDENT_SORT_NE takes precedence when both are set; with neither the code path is unchanged. prefill_mmq_tab_test part 4 runs a layer's groups as prefill.cpp does (src-gathered q8_1 rows, absolute bounds, the group's max_rows) in ID order and in both sorted orders, for IQ3_S / IQ4_XS gate/up and IQ4_NL / Q8_0 down: with the partial group kept every token's rows are bitwise equal (16 cases); sorting the partial group too changes 133-1881 rows per case. 890 comparisons, 0 failed (RTX 3090). Measured on 4x RTX 3090, UD-IQ4_XS, T16-142fcb (split 12,24,37, every expert resident), read time, medians of 6, back to back: 150-token prompt 145.8 -> 136.2 ms, 1,200-token prompt 428.6 -> 363.4 ms (RESIDENT_SORT_NE: 134.9 / 358.6 ms). The final residuals of five prompts (300-1,200 tokens, STRATA_PREFILL_DUMP_R_ALL every position and STRATA_PREFILL_DUMP_R fp32) are byte-identical to the reference build; with RESIDENT_SORT_NE every row differs. batch_test16 (16 slots, a 1,200-token prompt) is token-identical to the reference dump. --- include/strata/prefill/moe_mmq.hpp | 5 ++ src/prefill/mmq_resident_sort.hpp | 23 ++++- src/prefill/moe_mmq.cu | 33 +++++++ src/prefill/prefill.cpp | 13 ++- tests/cuda/prefill_mmq_tab_test.cu | 137 +++++++++++++++++++++++++++++ 5 files changed, 207 insertions(+), 4 deletions(-) diff --git a/include/strata/prefill/moe_mmq.hpp b/include/strata/prefill/moe_mmq.hpp index 62b84b74..3d7b4ccd 100644 --- a/include/strata/prefill/moe_mmq.hpp +++ b/include/strata/prefill/moe_mmq.hpp @@ -142,6 +142,11 @@ bool tab_fits(int ggml_type, int64_t w_rows); size_t overread_bytes(int ggml_type, int64_t cols); /// The room kept after each sized expert slot's blob for that over-read (the guard). constexpr size_t kSlotGuard = 256; +/// Every launch of `n_experts` experts of [w_rows, *] `ggml_type` weights computes each output tile in one block +/// with no stream-k K split, and every tile width has the same I/K tiles and SRAM layout, on every visible GPU - so an +/// expert's rows get the same bits in any such launch, whatever its group-mates and max_rows (STRATA_MMQ_GROUP_SORT). +/// 160 or 320 tiles per column tile on 82 SMs: yes; 108 or 128 SMs: no (stream-k splits the few-tile launches). +bool whole_tiles(int ggml_type, int64_t w_rows, int n_experts); /// STRATA_MMQ_DIRECT, read once: 0 (default) today's gather; 1 the guard layout and resident experts read in /// place; 2 the guard layout with today's gather (the bitwise A/B reference). 0 whenever !tab_built(). int direct_mode(); diff --git a/src/prefill/mmq_resident_sort.hpp b/src/prefill/mmq_resident_sort.hpp index c81b4562..ae3f8e10 100644 --- a/src/prefill/mmq_resident_sort.hpp +++ b/src/prefill/mmq_resident_sort.hpp @@ -2,6 +2,7 @@ #pragma once #include +#include #include #include #include @@ -18,6 +19,22 @@ inline bool mmq_resident_sort_requested() { return on; } +// STRATA_MMQ_GROUP_SORT=1: the same row-count order for the full 16-expert groups only; the last, partial group keeps +// its experts in ID order. A full group's launch has 160 * ntx (gate/up) or 320 * ntx (down) tiles, at or above the +// 90 % tile efficiency on the cards' SM counts, so it runs one block per tile with no stream-k K split whatever its tile +// width: each expert's rows get the same bits in any full group. The partial group can take the stream-k split, whose +// K boundaries depend on the group's tile count - leaving it unchanged keeps the prompt's bits. +inline bool mmq_group_sort_requested() { + static const bool on = mmq_resident_sort_flag(std::getenv("STRATA_MMQ_GROUP_SORT")); + return on; +} + +// How many of `n` ordered experts the sort may move: all of them (STRATA_MMQ_RESIDENT_SORT_NE), or the full groups +// of `group` experts (STRATA_MMQ_GROUP_SORT). +inline size_t mmq_resident_sort_span(size_t n, size_t group, bool keep_tail) { + return keep_tail && group > 0 ? n - n % group : n; +} + inline bool mmq_resident_sort_eligible(bool requested, bool use_mmq, bool native_layout, bool has_cache, const int32_t* layer_resident, int64_t n_expert, bool stream_all, bool layer_stream_empty) { @@ -35,10 +52,12 @@ inline bool mmq_resident_sort_eligible(bool requested, bool use_mmq, bool native // order contains each positive-count expert once in ID order; off has count.size()+1 entries; // routes fits its original int32 offsets, and slot/src each have routes writable entries. // After sorting, off[e] is an expert-indexed START, not an ID-prefix end at off[e+1]. +// Only order[0, span) is sorted (span >= order.size(): all of it); the entries after it keep their positions. inline void mmq_resident_sort_rows(const int32_t* ids, int64_t routes, int32_t k, const std::vector& count, std::vector& off, - std::vector& order, int32_t* slot, int32_t* src) { - std::stable_sort(order.begin(), order.end(), [&](int32_t a, int32_t b) { + std::vector& order, int32_t* slot, int32_t* src, + size_t span = SIZE_MAX) { + std::stable_sort(order.begin(), order.begin() + (ptrdiff_t) std::min(span, order.size()), [&](int32_t a, int32_t b) { return count[(size_t) a] != count[(size_t) b] ? count[(size_t) a] < count[(size_t) b] : a < b; }); diff --git a/src/prefill/moe_mmq.cu b/src/prefill/moe_mmq.cu index 4e210c9f..9b78fcc9 100644 --- a/src/prefill/moe_mmq.cu +++ b/src/prefill/moe_mmq.cu @@ -492,6 +492,39 @@ size_t overread_bytes(int t, int64_t cols) { return (size_t) blocks * ggml_type_size((ggml_type) t); } +bool whole_tiles(int t, int64_t w_rows, int n_experts) { + if (!supported(t) || w_rows % 128 != 0 || n_experts <= 0) return false; + // launch_mul_mat_q's grid: without stream-k one block per tile; with it one block per tile when the tiles fill + // their waves to >= 90 % (NVIDIA), else nsm blocks that split tiles along K at boundaries set by the tile count. + // The tile count is nty * n_experts * ntx, ntx = any positive count of J-wide column tiles (max_rows decides), + // and ntiles >= 9 * nsm always fills its waves to >= 90 %: the ntx below that are checked one by one. + const ggml_cuda_device_info& info = ggml_cuda_info(); + for (int id = 0; id < info.device_count; ++id) { + const int cc = info.devices[id].cc, nsm = info.devices[id].nsm; + const size_t smpbo = info.devices[id].smpbo; + bool any = false, stream_k = false; + ggml_cuda_mmq_config c0 = ggml_cuda_mmq_get_config((ggml_type) t, 8, false, cc); + for (int J = 8; J <= 128; J += 8) { + const ggml_cuda_mmq_config c = ggml_cuda_mmq_get_config((ggml_type) t, J, false, cc); + if (c.type == GGML_TYPE_COUNT || mmq_get_nbytes_shared(c, cc) > smpbo) continue; + if (!any) c0 = c; + any = true; + // every tile width accumulates each output over the same K tiles in the same order + if (c.I != c0.I || c.K_vram != c0.K_vram || c.sram_layout != c0.sram_layout) return false; + stream_k = stream_k || c.stream_k; + } + if (!any) return false; + if (!stream_k) continue; + if (!GGML_CUDA_CC_IS_NVIDIA(cc) || nsm <= 0) return false; + const int64_t per_ntx = (w_rows / c0.I) * n_experts; + for (int64_t ntx = 1; per_ntx * ntx < 9 * (int64_t) nsm + per_ntx; ++ntx) { + const int64_t tiles = per_ntx * ntx, waves = (tiles + nsm - 1) / nsm; + if (100 * tiles / (nsm * waves) < 90) return false; + } + } + return true; +} + int direct_mode() { static const int mode = [] { const char* v = std::getenv("STRATA_MMQ_DIRECT"); diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index 9ff33eba..4c39f4b9 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -82,6 +82,7 @@ void iota(int32_t*, int64_t, void*) {} bool tab_built() { return false; } bool tab_fits(int, int64_t) { return false; } size_t overread_bytes(int, int64_t) { return 0; } +bool whole_tiles(int, int64_t, int) { return false; } int direct_mode() { return 0; } size_t direct_slot_guard() { return 0; } void prep_group(const GuardTab&, size_t, void*, void*, size_t, void*) {} @@ -3377,10 +3378,18 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri // run through MMQ groups takes them in row-count order, so each 16-expert group's max_rows // (its padded tile rows) is close to its experts' own; slot/src/off are rebuilt coherently // before the upload, the routed ids, weights and the within-expert row order stay as they are. - if (detail::mmq_resident_sort_eligible(detail::mmq_resident_sort_requested() && on_peer.empty(), use_mmq, lay.native, + // STRATA_MMQ_GROUP_SORT=1 (opt-in, exact): the same order for the full groups only, where each + // tile is one block's whole K (mmq::whole_tiles); the partial group keeps its ID order and bits. + // STRATA_MMQ_RESIDENT_SORT_NE=1 takes precedence (it sorts the partial group too). + const bool sort_all = detail::mmq_resident_sort_requested(); + const bool sort_full = !sort_all && detail::mmq_group_sort_requested() && use_mmq && + order.size() >= (size_t) MMQ_GROUP && mmq::whole_tiles(mmq_gt, 1280, MMQ_GROUP) && + mmq::whole_tiles(mmq_dt, N, MMQ_GROUP); + if (detail::mmq_resident_sort_eligible((sort_all || sort_full) && on_peer.empty(), use_mmq, lay.native, m.cache != nullptr, m.host_res ? m.host_res + (size_t) l * m.g->n_expert : nullptr, m.g->n_expert, stream_all, !stream_all || seq_start[(size_t) l] == seq_start[(size_t) l + 1])) - detail::mmq_resident_sort_rows(ids_h, T * K, (int32_t) K, m.cnt, m.off, order, slot_h, src_h); + detail::mmq_resident_sort_rows(ids_h, T * K, (int32_t) K, m.cnt, m.off, order, slot_h, src_h, + detail::mmq_resident_sort_span(order.size(), MMQ_GROUP, sort_full)); if (grp_mapped) { copy_i32(m.slot_dev, m.grp_dev + m.grp_tk, T * K, m.cs); copy_i32(m.src_dev, m.grp_dev + 2 * m.grp_tk, T * K, m.cs); diff --git a/tests/cuda/prefill_mmq_tab_test.cu b/tests/cuda/prefill_mmq_tab_test.cu index 76be697a..69518299 100644 --- a/tests/cuda/prefill_mmq_tab_test.cu +++ b/tests/cuda/prefill_mmq_tab_test.cu @@ -15,11 +15,18 @@ // IQ3_S + Q8_0, some read in place (direct), the others gathered at compact positions c != q - one at a time // (gather_native) or by gather_native_group with a mid-group flush (first > 0) - including groups whose last entry is // direct and groups with no gathered entry; both products bitwise equal to all-gathered. +// Part 4, STRATA_MMQ_GROUP_SORT: a layer's experts in groups of 16 as prefill.cpp runs them (activations quantized +// in group order through the src map, absolute bounds, max_rows = the group's largest count), once in ID order and +// once with the full groups in row-count order (mmq_resident_sort_rows, the partial group kept): every token's +// product row bitwise equal, when mmq::whole_tiles says so for this card (else only reported). Sorting the partial +// group too (STRATA_MMQ_RESIDENT_SORT_NE) is reported, not required. // Exit 77 without a CUDA device of sm_80 or newer or without the pointer-table build. #include "strata/prefill/moe_mmq.hpp" #include "ggml.h" +#include "../../src/prefill/mmq_resident_sort.hpp" + #include #include @@ -386,6 +393,123 @@ void group_case(mmq::Context& ctx, const Pair& pr, const std::vector& cnt, same_bits(ref_d, got_d, out_d, w2.c_str()); } + +// Part 4: one layer's experts in groups of G; `span` as mmq_resident_sort_span gives it (0: ID order) +struct Layer { + std::vector ids, count, off, order, slot, src; +}; +Layer route(const std::vector& cnt, std::mt19937& rng) { + Layer L; + for (size_t e = 0; e < cnt.size(); ++e) + for (int r = 0; r < cnt[e]; ++r) L.ids.push_back((int32_t) e); + std::shuffle(L.ids.begin(), L.ids.end(), rng); // one route per token (K = 1), experts interleaved + L.count.assign(cnt.begin(), cnt.end()); + L.off.assign(cnt.size() + 1, 0); + for (size_t e = 0; e < cnt.size(); ++e) L.off[e + 1] = L.off[e] + cnt[e]; + for (size_t e = 0; e < cnt.size(); ++e) + if (cnt[e] > 0) L.order.push_back((int32_t) e); + L.slot.assign(L.ids.size(), 0); + L.src.assign(L.ids.size(), 0); + std::vector fill(L.off.begin(), L.off.end() - 1); + for (size_t i = 0; i < L.ids.size(); ++i) { + const int32_t p = fill[(size_t) L.ids[i]]++; + L.slot[i] = p; + L.src[(size_t) p] = (int32_t) i; + } + return L; +} + +// the layer's product rows in the layer's row order (row p = token src[p]) +std::vector run_layer(mmq::Context& ctx, const Shape& sh, const Layer& L, const std::vector>& w, + const Dev& x, cudaStream_t s) { + const int64_t T = (int64_t) L.ids.size(); + const size_t eb = mmq::matrix_bytes((int) sh.t, sh.rows, sh.cols), n = L.order.size(); + Dev src((size_t) T * 4), xq(mmq::q8_bytes(T, sh.cols)), ids((size_t) (T + kIdsPad) * 4), bounds((n + 1) * 4); + Dev grp((size_t) G * eb + TAIL), out((size_t) T * sh.rows * 4); + upload(src.p, L.src.data(), (size_t) T * 4, "src"); + std::vector hb(n + 1); + for (size_t j = 0; j < n; ++j) hb[j] = L.off[(size_t) L.order[j]]; + hb[n] = (int32_t) T; + upload(bounds.p, hb.data(), hb.size() * 4, "bounds"); + fill_nan(out.b(), out.n); + mmq::iota((int32_t*) ids.p, T + kIdsPad, s); + mmq::quantize((const float*) x.p, (const int32_t*) src.p, xq.p, (int) sh.t, sh.cols, sh.cols, T, s); + for (size_t j0 = 0; j0 < n; j0 += G) { + const int ng = (int) std::min(G, n - j0); + int64_t maxr = 0; + ck(cudaStreamSynchronize(s), "group"); // grp is rewritten below + for (int q = 0; q < ng; ++q) { + const int32_t e = L.order[j0 + (size_t) q]; + maxr = std::max(maxr, L.count[(size_t) e]); + upload(grp.b() + (size_t) q * eb, w[(size_t) e].data(), eb, "grp"); + } + ck(cudaMemset(grp.b() + (size_t) ng * eb, 0, TAIL), "tail"); + ck(cudaDeviceSynchronize(), "tail"); + mmq::Product p; + p.w = grp.p; p.type = (int) sh.t; p.w_rows = sh.rows; p.w_cols = sh.cols; p.expert_bytes = eb; + p.n = ng; p.xq = xq.p; p.bounds = (const int32_t*) bounds.p + j0; p.ids = (const int32_t*) ids.p; + p.total_rows = T; p.max_rows = maxr; p.dst = (float*) out.p; p.ld_dst = sh.rows; + ctx.run(p, s); + } + ck(cudaStreamSynchronize(s), "layer"); + std::vector h((size_t) T * sh.rows); + ck(cudaMemcpy(h.data(), out.p, h.size() * 4, cudaMemcpyDeviceToHost), "dtoh layer"); + return h; +} + +// tokens whose product row differs between two orders of the same layer +int64_t rows_differing(const Layer& a, const std::vector& ra, const Layer& b, const std::vector& rb, int64_t cols) { + int64_t nd = 0; + for (size_t t = 0; t < a.ids.size(); ++t) + if (std::memcmp(ra.data() + (size_t) a.slot[t] * cols, rb.data() + (size_t) b.slot[t] * cols, (size_t) cols * 4) != 0) ++nd; + return nd; +} + +void order_case(mmq::Context& ctx, const Shape& sh, const std::vector& cnt, bool whole, std::mt19937& rng, cudaStream_t s, + const char* label) { + const size_t eb = mmq::matrix_bytes((int) sh.t, sh.rows, sh.cols); + std::vector> w(cnt.size(), std::vector(eb)); + for (auto& m : w) fill_matrix(m.data(), sh.t, sh.rows, sh.cols, rng); + Layer id = route(cnt, rng); + const int64_t T = (int64_t) id.ids.size(); + Dev x((size_t) T * sh.cols * 4); + { + std::vector hx((size_t) T * sh.cols); + std::normal_distribution nd(0.0f, 1.0f); + for (auto& v : hx) v = nd(rng); + upload(x.p, hx.data(), hx.size() * 4, "x"); + } + Layer full = id, all = id; + namespace d = strata::prefill::detail; + d::mmq_resident_sort_rows(full.ids.data(), T, 1, full.count, full.off, full.order, full.slot.data(), full.src.data(), + d::mmq_resident_sort_span(full.order.size(), G, true)); + d::mmq_resident_sort_rows(all.ids.data(), T, 1, all.count, all.off, all.order, all.slot.data(), all.src.data(), + d::mmq_resident_sort_span(all.order.size(), G, false)); + const size_t n = id.order.size(), tail = n % G; + // the partial group's entries and row range stay where they were + bool kept = std::equal(id.order.end() - (ptrdiff_t) tail, id.order.end(), full.order.end() - (ptrdiff_t) tail); + for (size_t j = n - tail; j < n && kept; ++j) kept = full.off[(size_t) full.order[j]] == id.off[(size_t) id.order[j]]; + const std::vector r_id = run_layer(ctx, sh, id, w, x, s); + const std::vector r_full = run_layer(ctx, sh, full, w, x, s); + const std::vector r_all = run_layer(ctx, sh, all, w, x, s); + const int64_t d_full = rows_differing(id, r_id, full, r_full, sh.rows), d_all = rows_differing(id, r_id, all, r_all, sh.rows); + ++g_cases; + const bool ok = kept && (!whole || d_full == 0); + if (!ok) ++g_fail; + std::printf(" %s %-7s %s: %zu experts (%zu in the partial group), %lld rows: full groups sorted %lld rows differ%s, " + "all sorted %lld rows differ%s\n", ggml_type_name(sh.t), sh.role, label, n, tail, (long long) T, + (long long) d_full, ok ? "" : (kept ? " FAIL" : " FAIL (partial group moved)"), (long long) d_all, + whole ? "" : " (whole_tiles false on this card: reported only)"); +} + +std::vector skewed_counts(int n, int lo, int hi, std::mt19937& rng) { + // prompt-like: most experts few rows, some many (log-uniform) + std::uniform_real_distribution u(std::log((double) lo), std::log((double) hi + 1)); + std::vector c((size_t) n); + for (auto& v : c) v = std::max(lo, (int) std::exp(u(rng))); + return c; +} + } // namespace int main() { @@ -478,6 +602,19 @@ int main() { } } std::printf("mixed groups: %d comparisons, %s\n", g_cases - c0, g_fail == f0 ? "all bitwise identical" : "FAILURES"); + // Part 4 + const int f4 = g_fail, c4 = g_cases; + const Shape order_shapes[] = {{GGML_TYPE_IQ3_S, 1280, 2560, "gate/up"}, {GGML_TYPE_IQ4_XS, 1280, 2560, "gate/up"}, + {GGML_TYPE_IQ4_NL, 2560, 640, "down"}, {GGML_TYPE_Q8_0, 2560, 640, "down"}}; + for (const Shape& sh : order_shapes) { + const bool whole = mmq::whole_tiles((int) sh.t, sh.rows, G); + std::printf("%-8s %-7s whole_tiles(%d experts): %s\n", ggml_type_name(sh.t), sh.role, G, whole ? "yes" : "no"); + order_case(ctx, sh, skewed_counts(147, 1, 40, rng), whole, rng, s, "150-token prompt"); + order_case(ctx, sh, skewed_counts(219, 1, 160, rng), whole, rng, s, "512-token chunk"); + order_case(ctx, sh, skewed_counts(48, 1, 300, rng), whole, rng, s, "no partial group"); + order_case(ctx, sh, skewed_counts(11, 1, 300, rng), whole, rng, s, "partial group only"); + } + std::printf("group order: %d comparisons, %s\n", g_cases - c4, g_fail == f4 ? "all bitwise identical" : "FAILURES"); cudaStreamDestroy(s); std::printf("%d comparisons, %d failed\n", g_cases, g_fail); return g_fail == 0 ? 0 : 1; From 69a05bfb591de2070f58f64892c689c4421cc2d7 Mon Sep 17 00:00:00 2001 From: havok2-htwo Date: Mon, 12 Oct 2026 03:49:00 +0200 Subject: [PATCH 22/33] verify: STRATA_BATCH_SELF_COMMIT=1 lets a one-row-per-slot batch window keep its rows itself A pipelined batch window is followed on its stage's stream by the layout's commit graph, and the stage counts as done only after both. When every row of the window is another slot's one token, that commit is unconditional (each slot keeps its one row; commit_slot_prefixes allows nothing else), and most of the graph only repeats what the window wrote: it puts each indexer tail back from its snapshot and appends the same row again, and copies each PLE history back from the window's own snapshot of it. What it adds is the GDN conv history and recurrence state, which the window ran without writing. With the switch, such a window advances the GDN conv history (gdn_conv_l2_multi with commit) and state (gdn_step_norm_multi with n_keep = 1, the kernel the commit graph runs for a one-row group) itself, as a one-token solo window does, and takes no tail or history snapshots. No commit graph is captured for the layout; batch_launch and commit_slot_prefixes launch none, layout_captured and ensure_batch_layouts do not ask for one. Layouts with proposal rows (--batch-mtp) keep the commit graph. With the switch off every path is unchanged. Measured on 4x RTX 3090, UD-IQ4_XS, T16-142fcb (split 12,24,37), decode of 16 / 32 slots, 30 s each, reference and new build back to back: 653.7 -> 686.0 rows/s (+4.9 %) and 714.1 -> 752.6 rows/s (+5.4 %); the group step period 24.5 -> 23.3 ms and 44.85 -> 42.6 ms. STRATA_VERIFY_PROFILE: the window's GDN recurrence takes 0.09 ms (16) / 0.18 ms (32) longer per stage-window with the state written in it. batch_test16 (16 slots, a 1,200-token prompt) is token-identical to the reference dump; batch_test32 32/32 identical and its dump equal to the switch-off run; batch_overlap_test (STRATA_PIPE_OVERLAP=1) passes and is token- and RESUME-identical to the switch-off run; batch_interleave_test parts 1-3 identical (its part 4 fails at the same point with the reference build). --- src/core/verify.cpp | 44 +++++++++++++++++++++++++++++++++----------- 1 file changed, 33 insertions(+), 11 deletions(-) diff --git a/src/core/verify.cpp b/src/core/verify.cpp index f45bf826..a4a8f352 100644 --- a/src/core/verify.cpp +++ b/src/core/verify.cpp @@ -200,6 +200,21 @@ const bool g_doorbell_store = env_on("STRATA_DOORBELL_STORE"); const bool g_trace = env_on("STRATA_VERIFY_TRACE"); const bool g_no_multi_gr = env_on("STRATA_NO_MULTI_GR"); // #783 PR-g: per-token GR reads/writes and generic-T kernels again const bool g_no_batch_kv = env_on("STRATA_NO_BATCH_KV_STEP"); // #783 PR-d: per-token K/V and indexer appends again +// STRATA_BATCH_SELF_COMMIT=1 (opt-in): a batch window whose rows are each another slot's one token keeps them itself, +// as a one-token window does (record_window): the GDN conv histories and states advance inside the window graph, and +// no commit graph runs after it. Such a window's commit is unconditional (each slot keeps its one row), and the rest +// of the commit graph only repeats what the window wrote: the indexer tails are put back and appended again from the +// same rows, the PLE histories are put back to the window's own snapshot. +const bool g_batch_self_commit = env_on("STRATA_BATCH_SELF_COMMIT"); + +// every row of a batch window is another slot's (no slot has proposal rows) +bool one_row_per_slot(const int* rows, int S) { + for (int i = 0; i < S; ++i) + for (int j = i + 1; j < S; ++j) + if (rows[i] == rows[j]) return false; + return S >= 1; +} +bool batch_self_commits(const int* rows, int S) { return g_batch_self_commit && one_row_per_slot(rows, S); } // The shared expert runs on its own stream, forked off and joined back per layer (`sh_fork` in record_window). The // overlap pays off on CUDA, where it was added (cfd3b72). On HIP a cross-stream event dependency costs more than the @@ -916,6 +931,8 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { // a batch window: row t is slot t, whose state lives in its own session auto slot_ss = [&](int t) -> SessionState& { return batch_rec_ ? *slots_[(size_t) brow_[t]] : ss; }; const int hrow0 = batch_rec_ ? row_base_ : 0; // a slot group's own hand-off rows + // STRATA_BATCH_SELF_COMMIT: the window keeps its rows (no commit graph, nothing to snapshot for one) + const bool keep_rows = batch_rec_ && batch_self_commits(brow_, T); // ---- the window's inputs, from mapped staging. With branches the steps and positions (first read by the first // layer's mixer) cross PCIe on side 1 beside the embedding and the first hyper-connection read. @@ -1081,7 +1098,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { err = std::string("verify PLE: ") + e.what(); return false; } - copy_from_mapped(hist_snap_ + (size_t) t * HS, hist, HS, cs); + if (!keep_rows) copy_from_mapped(hist_snap_ + (size_t) t * HS, hist, HS, cs); } pending = false; } @@ -1169,7 +1186,8 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { const float* cx = sx.gdn_state + (size_t) (gi - sx.gdn_ord0) * gdn_floats + (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size; gdn_conv_l2_multi(cx, qkv + (size_t) first * C, (const float*) wc->data, - hb + (size_t) first * C, (int) C, (int) (2 * HK), EPS, t - first, cs, 0); + hb + (size_t) first * C, (int) C, (int) (2 * HK), EPS, t - first, cs, 0, + keep_rows); } } else // a one-token window keeps its token: it advances the conv history and the state itself (commit) @@ -1204,7 +1222,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { gdn_step_norm_multi(stx, hb + (size_t) first * C, (int) C, gate + (size_t) first * HV, beta + (size_t) first * HV, z_ + (size_t) first * ZV, (const float*) wnm->data, EPS, y_ + (size_t) first * ZV, - (int) HK, (int) HV, t - first, nullptr, cs, 0); + (int) HK, (int) HV, t - first, keep_rows ? one_ : nullptr, cs, 0); } } else gdn_step_norm_multi(state, hb, (int) C, gate, beta, z_, (const float*) wnm->data, EPS, y_, (int) HK, @@ -1289,7 +1307,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { } stamp(l, 8, grp); if (batch_rec_) { // snapshot each slot's indexer tail before its first proposed row - for (int t = tb; t < te; ++t) + for (int t = tb; t < te && !keep_rows; ++t) if (t == tb || brow_[t] != brow_[t - 1]) copy_from_mapped(tail_snap_b_ + ((size_t) brow_[t] * nQall + qi) * TS, slot_ss(t).qsa_states[qi].idx_tail, TS, cs); @@ -2750,8 +2768,8 @@ bool Verifier::init_slots(const std::vector& slots, std::string& tail_snap_b_ = (float*) ((uint8_t*) d + a); slots_ = slots; slot_sp_.assign(slots.size(), sampling_); // greedy until set_slot_sampling - std::fprintf(stderr, "strata verify: batch windows of up to %lld sequences (layers [%lld, %lld))\n", (long long) S, - (long long) lb_, (long long) le_); + std::fprintf(stderr, "strata verify: batch windows of up to %lld sequences (layers [%lld, %lld))%s\n", (long long) S, + (long long) lb_, (long long) le_, g_batch_self_commit ? ", one-row windows keep their rows" : ""); return true; } @@ -2788,6 +2806,7 @@ bool Verifier::capture_batch(const int* rows, int S, int hbase, std::string& err } bool Verifier::capture_commit_batch(const int* rows, int S, int hbase, std::string& err) { + if (batch_self_commits(rows, S)) return true; // the window keeps its rows: no commit graph cudaGraphExec_t& cex = commit_bm_[bkey(rows, S, hbase)]; if (cex != nullptr) return true; using namespace strata::kernels; @@ -3148,10 +3167,12 @@ bool Verifier::commit_slot_prefixes(const int* keep, std::string& err) { c[2 + j] = j < n ? (int32_t) last_pos_b_[first + j] : -1; } std::atomic_thread_fence(std::memory_order_seq_cst); - const cudaError_t le = cudaGraphLaunch(commit_bm_[bkey(last_rows_, S, row_base_)], cs_); - if (le != cudaSuccess) { err = std::string("verify: batch commit launch: ") + cudaGetErrorString(le); return false; } - const cudaError_t se = cudaStreamSynchronize(cs_); - if (se != cudaSuccess) { err = std::string("verify: batch commit: ") + cudaGetErrorString(se); return false; } + if (!batch_self_commits(last_rows_, S)) { // (else the window has kept its rows) + const cudaError_t le = cudaGraphLaunch(commit_bm_[bkey(last_rows_, S, row_base_)], cs_); + if (le != cudaSuccess) { err = std::string("verify: batch commit launch: ") + cudaGetErrorString(le); return false; } + const cudaError_t se = cudaStreamSynchronize(cs_); + if (se != cudaSuccess) { err = std::string("verify: batch commit: ") + cudaGetErrorString(se); return false; } + } if (ple_stage()) for (int t = 0; t < S;) { const int first = t; @@ -3188,7 +3209,8 @@ bool Verifier::batch_launch(int base, int S, const int32_t* tokens, const int64_ for (int t = 0; t < S && t < 8; ++t) rows[t] = base + t; if (!stage_batch(rows, S, base, tokens, pos, err)) return false; cudaError_t le = cudaGraphLaunch(exec_bm_[bkey(rows, S, base)], cs_); - if (le == cudaSuccess) le = cudaGraphLaunch(commit_bm_[bkey(rows, S, base)], cs_); // right behind it: every row is kept + if (le == cudaSuccess && !batch_self_commits(rows, S)) // (else the window has kept its rows itself) + le = cudaGraphLaunch(commit_bm_[bkey(rows, S, base)], cs_); // right behind it: every row is kept if (le != cudaSuccess) { err = std::string("verify: batch launch: ") + cudaGetErrorString(le); return false; } (void) cudaStreamQuery(cs_); if (ple_stage()) // the host's side of the commit (the hash's last two tokens) From bec9edf1e026db8c32bc71b7f496fa7f52307635 Mon Sep 17 00:00:00 2001 From: havok2-htwo Date: Mon, 12 Oct 2026 04:07:50 +0200 Subject: [PATCH 23/33] prefill: decide STRATA_MMQ_GROUP_SORT per layer once, in the MMQ plan mmq::whole_tiles walks every visible GPU and every tile width through the MMQ config table; the sort hook called it twice for each MoE layer of each prompt chunk, on the host path between the routed-ids download and the expert launches. Its verdict depends only on the layer's weight formats and the device set, so MmqPlan now keeps it as a per-layer flag (taken only when STRATA_MMQ_GROUP_SORT=1 and STRATA_MMQ_RESIDENT_SORT_NE is unset) and logs how many layers qualify. Same order, same bits; without the switch nothing new runs. --- src/prefill/prefill.cpp | 23 +++++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index 4c39f4b9..e52d0f05 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -1019,6 +1019,9 @@ struct MmqPlan { // and the bytes the down product reads past its matrix there (zeroed in the slot's guard before each group) std::vector direct; std::vector d_over; + // STRATA_MMQ_GROUP_SORT=1 (without STRATA_MMQ_RESIDENT_SORT_NE): per MMQ layer, whether both products' 16-expert + // launches run whole tiles on every visible GPU (mmq::whole_tiles), so its full groups may be taken in row-count order + std::vector group_sort; }; const MmqPlan& mmq_plan() { static const MmqPlan plan = [] { @@ -1066,6 +1069,19 @@ const MmqPlan& mmq_plan() { std::fprintf(stderr, "strata: prompt MMQ reads resident experts in place (STRATA_MMQ_DIRECT=1): %lld of %lld " "layers\n", (long long) nd, (long long) layers); } + // the verdict depends only on the layer's formats and the visible GPUs: taken once here, not per chunk + p.group_sort.assign(p.layer.size(), 0); + if (on && detail::mmq_group_sort_requested() && !detail::mmq_resident_sort_requested()) { + int64_t ns = 0; + for (int64_t l = 0; l < layers; ++l) { + if (!p.layer[(size_t) l]) continue; + const int gt = lay.native ? lay.fmt[(size_t) l].gu_type : 42, dt = lay.native ? lay.fmt[(size_t) l].d_type : 42; + p.group_sort[(size_t) l] = mmq::whole_tiles(gt, 1280, MMQ_GROUP) && mmq::whole_tiles(dt, N, MMQ_GROUP); + ns += p.group_sort[(size_t) l]; + } + std::fprintf(stderr, "strata: prompt MMQ sorts the full expert groups (STRATA_MMQ_GROUP_SORT=1): %lld of %lld " + "layers\n", (long long) ns, (long long) layers); + } return p; }(); return plan; @@ -3379,12 +3395,11 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri // (its padded tile rows) is close to its experts' own; slot/src/off are rebuilt coherently // before the upload, the routed ids, weights and the within-expert row order stay as they are. // STRATA_MMQ_GROUP_SORT=1 (opt-in, exact): the same order for the full groups only, where each - // tile is one block's whole K (mmq::whole_tiles); the partial group keeps its ID order and bits. + // tile is one block's whole K (MmqPlan::group_sort); the partial group keeps its ID order and bits. // STRATA_MMQ_RESIDENT_SORT_NE=1 takes precedence (it sorts the partial group too). const bool sort_all = detail::mmq_resident_sort_requested(); - const bool sort_full = !sort_all && detail::mmq_group_sort_requested() && use_mmq && - order.size() >= (size_t) MMQ_GROUP && mmq::whole_tiles(mmq_gt, 1280, MMQ_GROUP) && - mmq::whole_tiles(mmq_dt, N, MMQ_GROUP); + const bool sort_full = !sort_all && use_mmq && mmq_plan().group_sort[(size_t) l] && + order.size() >= (size_t) MMQ_GROUP; if (detail::mmq_resident_sort_eligible((sort_all || sort_full) && on_peer.empty(), use_mmq, lay.native, m.cache != nullptr, m.host_res ? m.host_res + (size_t) l * m.g->n_expert : nullptr, m.g->n_expert, stream_all, !stream_all || seq_start[(size_t) l] == seq_start[(size_t) l + 1])) From f32663a8b3f70de43d060a772a58ace277b46a1c Mon Sep 17 00:00:00 2001 From: havok2-htwo Date: Mon, 12 Oct 2026 04:19:34 +0200 Subject: [PATCH 24/33] tools: batch_interleave_test runs on a pipelined batch (no give-way required there) and checks a turn checkpoint taken from a slot On a layer split with more than one group a batch read never gives way to a BYIELD, so step 4 always failed with 'no such free slot' and steps 5-7 never ran. --yield auto now expects the give-way only on a non-pipelined batch; there D is read whole and E admitted beside it, both still equal to solo. New step 7b: A ends in slot 1, --flush unrelated solo GENs, then F2 can only start from slot 1's turn checkpoint. --dump writes every token list for an A/B of two builds. --- tools/batch_interleave_test.py | 123 +++++++++++++++++++++++++++++---- 1 file changed, 110 insertions(+), 13 deletions(-) diff --git a/tools/batch_interleave_test.py b/tools/batch_interleave_test.py index a59109ae..ef1c40a8 100644 --- a/tools/batch_interleave_test.py +++ b/tools/batch_interleave_test.py @@ -7,12 +7,17 @@ chunks interleaved with their windows), and a conversation's next turn continued tokens must equal its solo tokens 3. A's next turn (BGEN into slot 0, which still holds A): read from the slot, its tokens must equal the solo next turn 4. a long prompt D gives way (BYIELD) at its first chunk boundary, a short E is admitted, D goes on from its slot - while E decodes: both equal their solo tokens + while E decodes: both equal their solo tokens. On a pipelined batch (a layer split, more than one group) a read + never gives way: D is then read whole into slot 2 and E admitted into slot 1 beside it; both must still equal + solo, only the give-way is not required (--yield auto; --yield expect requires it anyway) 6. A in a slot, stopped after 50 tokens and continued on the solo path (GEN of A + its tokens, from the slot): the whole equals solo A (what the server does with a request left alone in a slot) 5. (a measurement) a solo next turn continued from a slot: the drafts accepted 7. F, A's history as a client sends it back without the reply's thinking, from slot 1's turn checkpoint: equal to F solo (which continues from the same checkpoint of the live chain) + (after step 6 the solo path holds A's start, so F's start comes from the live chain or the prompt cache here) + 7b. A in slot 1 to its end, --flush unrelated solo GENs, then F2 (A's question, another reply) into slot 2: its + start can only come from slot 1's turn checkpoint; equal to F2 solo. The engine log line says which source was used. Exact comparisons need the same settings as batch_test.py (this script sets STRATA_IQ_MT_MIN=1): python tools/batch_interleave_test.py --exe build/strata --config strata-.json \\ @@ -20,7 +25,7 @@ Exact comparisons need the same settings as batch_test.py (this script sets STRA Without --no-prefill-borrow the slots decoding during C's read see the expert cache without the slots C's prompt borrowed (those experts run on the CPU, which rounds differently): A's and B's text may then drift from solo. """ -import argparse, json, os, sys, time +import argparse, json, os, re, sys, time from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent)) @@ -48,6 +53,18 @@ def run(eng, out, line, slot=None): raise SystemExit(f"the engine ended during: {line[:40]} (see {eng.log_path})") +def engine_pipelined(eng, extra): + """Does the engine run the batch in pipelined groups (a layer split, more than one group)? Then a BYIELD is + dropped: a pipelined read never gives way.""" + if "--batch-groups" in extra: + v = extra[extra.index("--batch-groups") + 1] if extra.index("--batch-groups") + 1 < len(extra) else "" + if v.isdigit(): + return int(v) > 1 + eng.log.flush() + m = re.search(r"--batch-groups auto: (\d+) groups? of", Path(eng.log_path).read_text(errors="replace")) + return bool(m) and int(m.group(1)) > 1 + + def main(): ap = argparse.ArgumentParser() ap.add_argument("--exe", required=True) @@ -55,6 +72,13 @@ def main(): ap.add_argument("--max-new", type=int, default=200) ap.add_argument("--long", type=int, default=5000, help="tokens of the long prompt C (several prompt chunks)") ap.add_argument("--extra", default="") + ap.add_argument("--yield", dest="yield_mode", choices=("auto", "expect", "skip"), default="auto", + help="step 4's give-way: auto = expect a YIELDED unless the batch is pipelined (the engine log " + "says '--batch-groups auto: N groups' with N > 1, or --extra has --batch-groups N > 1), " + "where a read never gives way; expect = always required; skip = never required") + ap.add_argument("--flush", type=int, default=8, + help="7b: unrelated solo GENs between A in slot 1 and F, so only the slot holds A's start (0: off)") + ap.add_argument("--dump", default="", help="write every solo and slot token list as JSON: an A/B of two builds") a = ap.parse_args() cfg = json.loads(Path(a.config).read_text()) tok = tokenizer(cfg["tokenizer"]) @@ -85,6 +109,10 @@ def main(): F = A[:turn_at] + tok.encode("<|im_start|>assistant\nA short answer.<|im_end|>\n", parse_special=True) + \ chat("Now in Go.") sF, _ = run(eng, out, f"GEN {M} {ids(F)}") + # F2 (step 7b): another reply to A's question - it too shares A only up to A's turn checkpoint + F2 = A[:turn_at] + tok.encode("<|im_start|>assistant\nAnother short answer.<|im_end|>\n", parse_special=True) + \ + chat("Now in C.") + sF2, _ = run(eng, out, f"GEN {M} {ids(F2)}") if a.flush > 0 else ([], None) sB, _ = run(eng, out, f"GEN {M} {ids(B)}") sC, _ = run(eng, out, f"GEN {M} {ids(C)}") sD, _ = run(eng, out, f"GEN {M} {ids(D)}") @@ -139,36 +167,58 @@ def main(): d = next((k for k in range(min(len(got2), len(sA2))) if got2[k] != sA2[k]), None) print(f"A's next turn from its slot: {len(got2)} tokens, solo {len(sA2)}: " f"{'IDENTICAL' if same else f'DIFFERS at {d}'}", flush=True) - # 4. a long prompt D gives way (BYIELD) to a short E at its first chunk boundary, then goes on from its slot + # 4. a long prompt D gives way (BYIELD) to a short E at its first chunk boundary, then goes on from its slot. + # On a pipelined batch (a layer split with more than one group) a read never gives way (generate.cpp: the BYIELD + # is dropped): D is then admitted whole into slot 2 and E goes into the free slot 1 while D decodes - both must + # still equal solo, only the give-way itself is not checked (--yield) + pipelined = engine_pipelined(eng, a.extra.split()) + expect_yield = a.yield_mode == "expect" or (a.yield_mode == "auto" and not pipelined) eng.send(f"BGEN 2 {M} {ids(D)}") eng.send("BYIELD 2") - yielded = None + yielded, firstD, contD = None, [], None for l in out: - if l.startswith("YIELDED "): + if l.startswith("T "): + firstD.append(int(l.split()[1])) + elif l.startswith("YIELDED "): yielded = l elif l.startswith(("BT ", "BDONE ")): eng.pending.append(l) elif l.startswith("ERR"): raise SystemExit("engine: " + l) elif l.startswith("BADM 2 "): + contD = l.split()[2] == "1" break - print(f"D gave way: {yielded}", flush=True) - ok &= yielded is not None + if yielded is not None: + print(f"D gave way: {yielded}", flush=True) + elif expect_yield: + print(f"D gave way: None (expected a YIELDED: batch {'pipelined' if pipelined else 'not pipelined'})", + flush=True) + ok = False + else: + print(f"D gave way: None - the batch is pipelined ({pipelined}), where a read never gives way; D stays in " + f"slot 2 ({len(firstD)} first tokens, {'continues' if contD else 'done'}), E goes into slot 1 beside it", + flush=True) got4 = {1: [], 2: []} first, cont1 = run(eng, out, f"BGEN 1 {M} {ids(E)}", slot=1) got4[1] += first - first, cont2 = run(eng, out, f"BGEN 2 {M} {ids(D)}", slot=2) - got4[2] += first + if yielded is not None: + first, cont2 = run(eng, out, f"BGEN 2 {M} {ids(D)}", slot=2) + got4[2] += first + else: # D never left slot 2: its tokens so far are the read's first ones plus the BT 2 lines kept in pending + got4[2] += firstD + cont2 = contD done4 = {s for s, c in ((1, cont1), (2, cont2)) if not c} while len(done4) < 2: l = eng.pending.pop(0) if eng.pending else next(out) if l.startswith("BT "): _, s, y = l.split() - if int(s) in got4: + if int(s) in got4 and int(s) not in done4: got4[int(s)].append(int(y)) elif l.startswith("BDONE "): done4.add(int(l.split()[1])) - for s, ref, name in ((1, sE, "E (short, admitted while D waited)"), (2, sD, "D (gave way, then went on)")): + elif l.startswith("ERR"): + raise SystemExit("engine: " + l) + for s, ref, name in ((1, sE, "E (short, admitted while D waited)"), (2, sD, "D (gave way, then went on)" if yielded else "D (read whole, E admitted beside it)")): same = got4[s] == ref ok &= same d = next((k for k in range(min(len(got4[s]), len(ref))) if got4[s][k] != ref[k]), None) @@ -208,7 +258,8 @@ def main(): print(f"solo next turn from a slot: drafts accepted {f[6]} of {f[7]} ({f[1]} tokens in {f[4]} ms)", flush=True) break - # 7. F from slot 1's turn checkpoint (slot 1 holds A since step 6): the engine log says "(its turn checkpoint)" + # 7. F, A's history without the reply's thinking, into slot 2 (its start comes from the live chain or the prompt + # cache: step 6's solo continuation took slot 1's contents back; 7b below makes a slot the only source) first, cont = run(eng, out, f"BGEN 2 {M} {ids(F)}", slot=2) got7 = list(first) while cont: @@ -220,8 +271,54 @@ def main(): same = got7 == sF ok &= same d = next((k for k in range(min(len(got7), len(sF))) if got7[k] != sF[k]), None) - print(f"F (A's history without the reply's thinking) from slot 1's turn checkpoint: {len(got7)} tokens, solo " + print(f"F (A's history without the reply's thinking) in slot 2: {len(got7)} tokens, solo " f"{len(sF)}: {'IDENTICAL' if same else f'DIFFERS at {d}'}", flush=True) + # 7b. step 7 where only a SLOT can give the start: after step 6 the solo path took slot 1's contents back, so the + # live chain (or the prompt cache) held A's start in step 7 and F came from there. Here A runs to its end in + # slot 1, then --flush unrelated solo GENs push A out of the live session and the prompt cache's checkpoints; F2 + # (A's question, another reply) into slot 2 can then only start from slot 1's turn checkpoint (slot 2 holds F, + # which shares no more with F2 than A does; the engine log line is printed) - its tokens must equal F2 solo + got7b = [] + if a.flush > 0: + first, cont = run(eng, out, f"BGEN 1 {M} {ids(A)}", slot=1) + gotA = list(first) + while cont: + l = eng.pending.pop(0) if eng.pending else next(out) + if l.startswith("BT 1 "): + gotA.append(int(l.split()[2])) + elif l.startswith("BDONE 1 "): + break + same = gotA == sA + ok &= same + print(f"7b: A in slot 1 to its end: {len(gotA)} tokens, solo {len(sA)}: {'IDENTICAL' if same else 'DIFFERS'}", + flush=True) + for k in range(a.flush): + run(eng, out, f"GEN 8 {ids(chat(f'Unrelated question {k}: name one prime number above {100 * k}.'))}") + eng.log.flush() + mark = len(Path(eng.log_path).read_text(errors="replace")) + first, cont = run(eng, out, f"BGEN 2 {M} {ids(F2)}", slot=2) + got7b = list(first) + while cont: + l = eng.pending.pop(0) if eng.pending else next(out) + if l.startswith("BT 2 "): + got7b.append(int(l.split()[2])) + elif l.startswith("BDONE 2 "): + break + tail = Path(eng.log_path).read_text(errors="replace")[mark:] + src = [l for l in tail.splitlines() if "gave back" in l or "strata serve: prompt" in l][:2] + same = got7b == sF2 + ok &= same + d = next((k for k in range(min(len(got7b), len(sF2))) if got7b[k] != sF2[k]), None) + print(f"7b: F2 after {a.flush} unrelated GENs, from slot 1: {len(got7b)} tokens, solo {len(sF2)}: " + f"{'IDENTICAL' if same else f'DIFFERS at {d}'}", flush=True) + for l in src: + print(" 7b log:", l.split("strata ")[-1][:160], flush=True) + if a.dump: + Path(a.dump).write_text(json.dumps({ + "solo": {"A": sA, "A2": sA2, "B": sB, "C": sC, "D": sD, "E": sE, "F": sF, "F2": sF2}, + "slots": {"A": got[0], "B": got[1], "C": got[2], "A2": got2, "E": got4[1], "D": got4[2], + "A_slot_then_solo": got6 + tail6, "F": got7, "F2": got7b}, + "yielded": yielded is not None, "pipelined": pipelined}), encoding="utf-8") eng.send("QUIT") eng.p.wait(timeout=180) log = Path(eng.log_path).read_text(errors="replace") From 2f4fe20a9a220e8967e73c4d1f8736c469cff13f Mon Sep 17 00:00:00 2001 From: havok2-htwo Date: Mon, 12 Oct 2026 05:24:28 +0200 Subject: [PATCH 25/33] serve: STRATA_SLOT_CKPT_MOVE honours the #879 flush (no resume from a tainted slot's checkpoint) Upstream's non-finite flush only marks running slots `tainted`; their checkpoints stayed. With STRATA_SLOT_CKPT_MOVE a running slot's checkpoints are a resume source (active_source) and a slot's moved turn checkpoint can be restored into the main session (lent_slot), so a request right after the flush, logged as "reading this prompt from token 0", still continued from a pre-flush checkpoint. - the flush drops a running slot's checkpoints too (only with STRATA_SLOT_CKPT_MOVE, the one reader of them; they go back to the checkpoint pool) - active_source and the lent_slot search skip tainted slots Checked with STRATA_NAN_INJECT=600 on the T16-142gsc setup (next turns of chats still running in slots): before, the two requests after the flush resumed 1628 tokens from slots 0 and 8 ("gave back ... its turn checkpoint"); now both read 1661 tokens from token 0. A next turn before the flush still resumes from its running slot. Default path (switch off) unchanged. --- src/program/generate.cpp | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 839fc861..05cb4577 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -11328,6 +11328,13 @@ int main(int argc, char** argv) { if (sl.active) { // a running slot finishes its reply, but is not kept as a cache after it sl.tainted = true; ++n_running; + // STRATA_SLOT_CKPT_MOVE reads a running slot's checkpoints (and a finished one's: lent_slot): + // they predate the flush, so they go now + if (slot_ckpt_move_env()) { + if (ckpt_pool.on()) + for (ConvCheckpoint& c : sl.checks) ckpt_pool.give(std::move(c)); + sl.checks.clear(); + } } else if (sl.cached) { sl.cached = false; sl.partial = false; @@ -11358,7 +11365,7 @@ int main(int argc, char** argv) { int64_t moved_in = -1; if (slot_ckpt_move_env() && o.prompt_cache > 0 && want_cvec == cvec_cached && live_ok) for (int b = 0; b < (int) bs.size(); ++b) { - if (bs[(size_t) b].cvec != cvec_cached) continue; + if (bs[(size_t) b].cvec != cvec_cached || bs[(size_t) b].tainted) continue; // (#879) for (const ConvCheckpoint& c : bs[(size_t) b].checks) { const int64_t L = (int64_t) c.ids.size(); if (L > resume && L <= (int64_t) live.size() && starts_with(c.ids, c.imgs) && @@ -11383,7 +11390,8 @@ int main(int argc, char** argv) { const bool idle_source = !sl.active && sl.cached; // (an active slot only where the drafter's rows come along or are not drafted from: the copy // takes the main layers' cells, so the main drafter would keep another conversation's below it) - const bool active_source = sl.active && slot_ckpt_move_env() && (!use_mtp || batch_mtp || admit_slot >= 0); + const bool active_source = sl.active && !sl.tainted && slot_ckpt_move_env() && + (!use_mtp || batch_mtp || admit_slot >= 0); if (sl.cvec != want_cvec || !(idle_source || active_source)) continue; if (idle_source && (int64_t) sl.ids.size() > std::max(resume, slot_tokens) && starts_with(sl.ids, {})) { slot_source = b; From a71ee46cd25a44293c2d18a306ffd4f0c6aaee30 Mon Sep 17 00:00:00 2001 From: havok2-htwo Date: Mon, 12 Oct 2026 06:20:44 +0200 Subject: [PATCH 26/33] verify: STRATA_QSA_SLOTS=1 runs a batch window's QSA block scores, top-k and attention as one launch over its rows In a batch window every row reads its own slot's indexer keys and K/V, so each QSA layer ran the selection and attention once per row: four rows (16 slots) or eight (32 slots) times qsa_block_scores, qsa_block_topk and qsa_decode_attn_batch, each launch small (the top-k on one CTA, the attention on cap/64 x 2 blocks). With the switch, per window (up to 8 rows per launch): - block_scores_slots_kernel: grid (256, rows), blockIdx.y runs the single-query block_scores_multi_kernel body with that row's slot keys (block_scores_multi_kernel is now a wrapper around the same body) - qsa_block_topk over the rows in one call (it only reads the rows' scores and steps) - attn_chunk_slots_kernel: attn_chunk_kernel's body with the row's own QsaAttnPools (an 8-entry table passed by value, blockIdx.z picks), then the existing batched merge Each row is computed by the same kernel body with the same reduction order as its own call. The launchers decline (the per-row calls run) where that call would pick another kernel: STRATA_SCORES_MULTI=0, the pre-sm_75 / gfx103x attention, the gfx906 query swizzle. A streamed KV cache keeps the per-row resolve-then-attend loop. Default (switch off): unchanged. Checked on 4x RTX 3090, T16-143gsc setup (layer split 12,24,37, int8 KV): - SASS (sm_86) of every existing kernel in qsa_select.cu and of the default attn_chunk_kernel and the merge is identical before/after; the opt-in lane-cell instantiations differ only in register allocation - new qsa_slots_parity (ctest, also with STRATA_ATTN_LANECELL=1): fp16, int8, q4_0 and int8-K/q4_0-V pools, 1/2/4/8 rows of different slots with their own page tables and contexts 37..32768: scores, ids and attention bitwise identical to one call per row - batch_test16/32 (greedy and t=0.7), batch_interleave_test and batch_overlap_test (STRATA_PIPE_OVERLAP=1) token-identical to the build without the change; with the switch off batch_test16 is byte-identical too - batch decode rows/s (engine level, 30 s, back to back with the reference): 16 slots 683 -> 726 (+6.3 %), 32 slots 750 -> 802 (+6.9 %); STRATA_VERIFY_PROFILE "QSA projections + attention" per stage-window 0.89 -> 0.52 ms (16) and 1.52 -> 0.79 ms (32) HIP: the new code uses only what the existing kernels use; SYCL has its own sources and only sees the new declarations. Neither was built here. --- CMakeLists.txt | 9 + include/strata/kernels/qsa_decode_attn.hpp | 15 ++ include/strata/kernels/qsa_select.hpp | 7 + src/core/verify.cpp | 43 ++++- src/kernels/cuda/qsa_decode_attn.cu | 114 ++++++++++- src/kernels/cuda/qsa_select.cu | 79 ++++++-- src/kernels/qsa_slots_parity.cpp | 209 +++++++++++++++++++++ 7 files changed, 455 insertions(+), 21 deletions(-) create mode 100644 src/kernels/qsa_slots_parity.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index c044c14b..88aa756a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -417,6 +417,15 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) target_link_libraries(qsa_topk_active_parity PRIVATE strata_kernels CUDA::cudart) add_test(NAME qsa_topk_active_parity COMMAND qsa_topk_active_parity) set_tests_properties(qsa_topk_active_parity PROPERTIES SKIP_RETURN_CODE 77) + # STRATA_QSA_SLOTS: a batch window's scores, top-k and attention as one launch over rows of different slots + # against one call per row, bitwise (synthetic, no model) + add_executable(qsa_slots_parity src/kernels/qsa_slots_parity.cpp) + target_include_directories(qsa_slots_parity PRIVATE ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES}) + target_link_libraries(qsa_slots_parity PRIVATE strata_kernels CUDA::cudart) + add_test(NAME qsa_slots_parity COMMAND qsa_slots_parity) + add_test(NAME qsa_slots_parity_lanecell COMMAND qsa_slots_parity) + set_tests_properties(qsa_slots_parity qsa_slots_parity_lanecell PROPERTIES SKIP_RETURN_CODE 77) + set_tests_properties(qsa_slots_parity_lanecell PROPERTIES ENVIRONMENT "STRATA_ATTN_LANECELL=1") endif() # the QSA selection (block scores on the warp kernel and the tensor-core one, top-k): a GPU bench with a # scorer-vs-scorer comparison and an FP64 accuracy gate (synthetic, no model); the ctest runs a 32K context under a diff --git a/include/strata/kernels/qsa_decode_attn.hpp b/include/strata/kernels/qsa_decode_attn.hpp index 45c0f301..d68bab43 100644 --- a/include/strata/kernels/qsa_decode_attn.hpp +++ b/include/strata/kernels/qsa_decode_attn.hpp @@ -43,4 +43,19 @@ void qsa_decode_attn_step(const float* q, const QsaAttnPools& pools, const int32 void qsa_decode_attn_batch(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps, int64_t cap, const QsaShapes& s, float* scratch, float* attn, int64_t n_q, void* stream); +/// Up to this many queries of different slots in one qsa_decode_attn_slots call. +constexpr int kQsaAttnMaxSlots = 8; + +/// One KV pool set per query of a qsa_decode_attn_slots call (passed by value as a kernel argument). +struct QsaAttnSlotPools { + QsaAttnPools p[kQsaAttnMaxSlots]; +}; + +/// qsa_decode_attn_batch for `n_q` queries that each attend over their OWN pools (`pools.p[i]`, one KV cache per batch +/// slot): one launch instead of one call per query, every block computing exactly what the per-query call computes. +/// The pools must all have one KV format. False (nothing launched) where the per-query call would run another kernel +/// (n_q > kQsaAttnMaxSlots, mixed formats, the pre-sm_75 / gfx103x or gfx906 variants): the caller loops instead. +bool qsa_decode_attn_slots(const float* q, const QsaAttnSlotPools& pools, const int32_t* ids, const int32_t* steps, + int64_t cap, const QsaShapes& s, float* scratch, float* attn, int64_t n_q, void* stream); + } // namespace strata::kernels diff --git a/include/strata/kernels/qsa_select.hpp b/include/strata/kernels/qsa_select.hpp index c36d29cf..3ff769a9 100644 --- a/include/strata/kernels/qsa_select.hpp +++ b/include/strata/kernels/qsa_select.hpp @@ -29,6 +29,13 @@ void qsa_block_scores(const float* pooled, const float* dead, const float* q_idx int64_t active_blocks = -1); ///< perf-review C-1: > 0 launches only this many blocks (the ///< batch's largest n_bid + 1; not for a captured graph) +/// qsa_block_scores for `nq` queries of different slots, query i scoring its own slot's keys (pooled[i], dead[i]; host +/// arrays of device pointers): one launch whose blocks each compute exactly what the single-query call computes. +/// False (nothing launched) where that call would run another kernel (nq > 8, STRATA_SCORES_MULTI=0): loop instead. +bool qsa_block_scores_slots(const float* const* pooled, const float* const* dead, const float* q_idx, + const int32_t* steps, int64_t nq, int64_t max_blocks, const QsaShapes& s, float* scores, + void* stream); + /// The same scores on tensor cores (3xTF32, FP32-level accuracy but another summation order: not bitwise; the tail /// block n_bid is the warp kernel's arithmetic). For the prompt path; false (nothing launched) on another geometry. /// On AMD it is the gfx12 (RDNA4) WMMA kernel (a three-way bf16 split, six products); false on any other AMD target. diff --git a/src/core/verify.cpp b/src/core/verify.cpp index a4a8f352..81cb7322 100644 --- a/src/core/verify.cpp +++ b/src/core/verify.cpp @@ -206,6 +206,11 @@ const bool g_no_batch_kv = env_on("STRATA_NO_BATCH_KV_STEP"); // #783 PR-d: pe // of the commit graph only repeats what the window wrote: the indexer tails are put back and appended again from the // same rows, the PLE histories are put back to the window's own snapshot. const bool g_batch_self_commit = env_on("STRATA_BATCH_SELF_COMMIT"); +// STRATA_QSA_SLOTS=1 (opt-in): in a batch window, a QSA layer's block scores, top-k and attention run as one launch +// each over the window's rows (up to 8 per launch, each row reading its own slot's indexer keys and K/V) instead of +// one call per row; every row is computed by the same kernel with the same arithmetic as its own call. Not with a +// streamed KV cache (a row's block resolve could evict the blocks an earlier row of the same slot selected). +const bool g_qsa_slots = env_on("STRATA_QSA_SLOTS"); // every row of a batch window is another slot's (no slot has proposal rows) bool one_row_per_slot(const int* rows, int S) { @@ -1417,7 +1422,43 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { } } stamp(l, 10, grp); - if (batch_rec_) { // each row selects and attends over its own slot's K/V + bool streamed = false; // a streamed KV cache keeps the per-row resolve-then-attend order + if (batch_rec_ && g_qsa_slots) + for (int t = tb; t < te; ++t) streamed = streamed || slot_ss(t).qsa_states[qi].kv_mode == 1; + if (batch_rec_ && g_qsa_slots && !streamed) { + // the rows' block scores, top-k and attention, up to 8 rows per launch. The rows only read + // their slots' keys and K/V here and write their own scores/sel/scratch/attn rows, so running + // each step for all rows before the next is the per-row loop's result + for (int t0 = tb; t0 < te; t0 += kQsaAttnMaxSlots) { + const int m = std::min(te - t0, kQsaAttnMaxSlots); + const float* pooled[kQsaAttnMaxSlots]; + const float* dead[kQsaAttnMaxSlots]; + QsaAttnSlotPools px; + for (int i = 0; i < m; ++i) { + const QsaState& sx = slot_ss(t0 + i).qsa_states[qi]; + pooled[i] = sx.idx_pooled; + dead[i] = sx.idx_dead; + px.p[i] = qsa_attn_pools(sx); + } + // a launcher that would not run the per-row call's kernel launches nothing: per-row calls + if (!qsa_block_scores_slots(pooled, dead, qidx_ + t0 * IQ * ID, step_ + t0 * kStepCount, m, + max_blocks_, s, scores_ + (size_t) t0 * max_blocks_, cs)) + for (int t = t0; t < t0 + m; ++t) + qsa_block_scores(pooled[t - t0], dead[t - t0], qidx_ + t * IQ * ID, step_ + t * kStepCount, + 1, max_blocks_, s, scores_ + (size_t) t * max_blocks_, cs); + qsa_block_topk(scores_ + (size_t) t0 * max_blocks_, step_ + t0 * kStepCount, m, max_blocks_, + cap_, s, sel_ + (size_t) t0 * cap_, cs); + if (!qsa_decode_attn_slots(qcur_ + t0 * NH * HD, px, sel_ + (size_t) t0 * cap_, + step_ + t0 * kStepCount, cap_, s, + attn_scratch_ + (size_t) t0 * attn_scratch_floats_, + attn_ + t0 * NH * HD, m, cs)) + for (int t = t0; t < t0 + m; ++t) + qsa_decode_attn_batch(qcur_ + t * NH * HD, px.p[t - t0], sel_ + (size_t) t * cap_, + step_ + t * kStepCount, cap_, s, + attn_scratch_ + (size_t) t * attn_scratch_floats_, + attn_ + t * NH * HD, 1, cs); + } + } else if (batch_rec_) { // each row selects and attends over its own slot's K/V for (int t = tb; t < te; ++t) { const QsaState& sx = slot_ss(t).qsa_states[qi]; qsa_block_scores(sx.idx_pooled, sx.idx_dead, qidx_ + t * IQ * ID, step_ + t * kStepCount, 1, diff --git a/src/kernels/cuda/qsa_decode_attn.cu b/src/kernels/cuda/qsa_decode_attn.cu index bff0e420..85257e6c 100644 --- a/src/kernels/cuda/qsa_decode_attn.cu +++ b/src/kernels/cuda/qsa_decode_attn.cu @@ -116,13 +116,14 @@ __device__ __forceinline__ int reduce12_head_of_lane(int lane) { return ((lane >> 4) & 1) * 8 + ((lane >> 3) & 1) * 4 + ((lane >> 2) & 1) * 2 + ((lane >> 1) & 1); } -template -__global__ void __launch_bounds__(THREADS) attn_chunk_kernel(const float* __restrict__ q, QsaAttnPools p, - const int32_t* __restrict__ ids, - const int32_t* __restrict__ step, int n_kv_heads, - int page_size, float scale, float* __restrict__ part_acc, - float* __restrict__ part_m, float* __restrict__ part_l, - int n_chunks, int cap = 0, long long scratch_stride = 0) { +// The chunk kernel's body; `p` is the query's KV pools (the call's one set, or blockIdx.z's slot's set). +template +__device__ __forceinline__ void attn_chunk_body(const float* __restrict__ q, QsaAttnPools p, + const int32_t* __restrict__ ids, const int32_t* __restrict__ step, + int n_kv_heads, int page_size, float scale, + float* __restrict__ part_acc, float* __restrict__ part_m, + float* __restrict__ part_l, int n_chunks, int cap, + long long scratch_stride) { // batched form: query blockIdx.z, with its own q row, selection, step and scratch q += (size_t) blockIdx.z * (size_t) (n_kv_heads * G) * HD; ids += (size_t) blockIdx.z * (size_t) cap; @@ -281,6 +282,33 @@ __global__ void __launch_bounds__(THREADS) attn_chunk_kernel(const float* __rest for (int h = 0; h < G; ++h) part_acc[((size_t) slot * G + h) * HD + t] = acc[h]; } +template +__global__ void __launch_bounds__(THREADS) attn_chunk_kernel(const float* __restrict__ q, QsaAttnPools p, + const int32_t* __restrict__ ids, + const int32_t* __restrict__ step, int n_kv_heads, + int page_size, float scale, float* __restrict__ part_acc, + float* __restrict__ part_m, float* __restrict__ part_l, + int n_chunks, int cap = 0, long long scratch_stride = 0) { + attn_chunk_body(q, p, ids, step, n_kv_heads, page_size, scale, + part_acc, part_m, part_l, n_chunks, cap, + scratch_stride); +} + +// The same blocks for queries of different slots: query blockIdx.z reads its own slot's pools, everything else is +// attn_chunk_kernel's batched form (qsa_decode_attn_slots). +template +__global__ void __launch_bounds__(THREADS) attn_chunk_slots_kernel(const float* __restrict__ q, QsaAttnSlotPools ps, + const int32_t* __restrict__ ids, + const int32_t* __restrict__ step, int n_kv_heads, + int page_size, float scale, + float* __restrict__ part_acc, + float* __restrict__ part_m, + float* __restrict__ part_l, int n_chunks, int cap, + long long scratch_stride) { + attn_chunk_body(q, ps.p[blockIdx.z], ids, step, n_kv_heads, page_size, scale, + part_acc, part_m, part_l, n_chunks, cap, scratch_stride); +} + // PR #540 (sskver): the same attention with fewer shuffles and less shared-memory traffic, bit for bit the kernel // above (same operands, same order); +7% prompt speed on a V100, where this kernel reads every prompt chunk. It // uses more registers (80 vs 38 on sm_70), so on CUDA it runs on cards below sm_75 only, and exists only in the @@ -615,6 +643,17 @@ bool pre75_attn() { #define STRATA_ATTN_CHUNK(M) attn_chunk_kernel #endif +// S25: STRATA_ATTN_LANECELL=1 - the score phase one cell per thread (bit-identical scores, no shuffle reductions) +bool lane_cell_attn() { + static const bool on = [] { const char* v = std::getenv("STRATA_ATTN_LANECELL"); return v && v[0] == '1'; }(); + return on; +} + +// 0 fp16, 1 int8, 2 q4_0, 3 int8 K with q4_0 V +int attn_kv_mode(const QsaAttnPools& p) { + return p.k_q4 != nullptr ? 2 : (p.k_q != nullptr && p.v_q4 != nullptr ? 3 : (p.k_q != nullptr ? 1 : 0)); +} + } // namespace void qsa_decode_attn_batch(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps, @@ -636,8 +675,7 @@ void qsa_decode_attn_batch(const float* q, const QsaAttnPools& pools, const int3 const float scale = 1.0f / sqrtf((float) HD); const dim3 grid((unsigned) n_chunks, (unsigned) s.n_head_kv, (unsigned) n_q); cudaStream_t st = (cudaStream_t) stream; - // S25: STRATA_ATTN_LANECELL=1 - the score phase one cell per thread (bit-identical scores, no shuffle reductions) - static const bool lane_cell = [] { const char* v = std::getenv("STRATA_ATTN_LANECELL"); return v && v[0] == '1'; }(); + const bool lane_cell = lane_cell_attn(); #if defined(STRATA_HIP_GFX906) static const bool query_swizzle = [] { const char* v = std::getenv("STRATA_GFX906_ATTN_QUERY_SWIZZLE"); return v && v[0] == '1'; @@ -710,6 +748,64 @@ void qsa_decode_attn_batch(const float* q, const QsaAttnPools& pools, const int3 } } +bool qsa_decode_attn_slots(const float* q, const QsaAttnSlotPools& pools, const int32_t* ids, const int32_t* steps, + int64_t cap, const QsaShapes& s, float* scratch, float* attn, int64_t n_q, void* stream) { + if (n_q <= 0) return true; + if (n_q > kQsaAttnMaxSlots) return false; + if (s.head_dim != HD || s.n_head != (int64_t) G * s.n_head_kv || cap <= 0 || !scratch || !ids || !steps) { + std::fprintf(stderr, "qsa_decode_attn_slots: unsupported geometry or missing buffers\n"); + std::exit(1); + } + const int kv_mode = attn_kv_mode(pools.p[0]); + for (int64_t z = 0; z < n_q; ++z) { + if (!pools.p[z].page_table) { + std::fprintf(stderr, "qsa_decode_attn_slots: missing page table\n"); + std::exit(1); + } + if (attn_kv_mode(pools.p[z]) != kv_mode) return false; + } + const bool lane_cell = lane_cell_attn(); + // only where qsa_decode_attn_batch runs attn_chunk_kernel; its other variants keep the per-query calls +#if defined(STRATA_ATTN_PRE75_BUILT) + if (!lane_cell && pre75_attn()) return false; +#endif +#if defined(STRATA_HIP_GFX906) + static const bool query_swizzle = [] { + const char* v = std::getenv("STRATA_GFX906_ATTN_QUERY_SWIZZLE"); return v && v[0] == '1'; + }(); + if (query_swizzle && !lane_cell && kv_mode == 1 && query_swizzle_gfx906_device()) return false; +#endif + const int n_chunks = (int) ((cap + CHUNK - 1) / CHUNK); + const long long stride = (long long) qsa_decode_attn_scratch_floats(cap, s); + float* part_acc = scratch; + float* part_m = scratch + (size_t) n_chunks * s.n_head * HD; + float* part_l = part_m + (size_t) n_chunks * s.n_head; + const float scale = 1.0f / sqrtf((float) HD); + const dim3 grid((unsigned) n_chunks, (unsigned) s.n_head_kv, (unsigned) n_q); + cudaStream_t st = (cudaStream_t) stream; +#define STRATA_ATTN_SLOTS(M, LC) attn_chunk_slots_kernel<<>>(q, pools, ids, steps, (int) s.n_head_kv, (int) s.page_size, scale, part_acc, part_m, part_l, n_chunks, (int) cap, stride) + if (lane_cell) { + if (kv_mode == 3) STRATA_ATTN_SLOTS(3, true); + else if (kv_mode == 2) STRATA_ATTN_SLOTS(2, true); + else if (kv_mode == 1) STRATA_ATTN_SLOTS(1, true); + else STRATA_ATTN_SLOTS(0, true); + } else { + if (kv_mode == 3) STRATA_ATTN_SLOTS(3, false); + else if (kv_mode == 2) STRATA_ATTN_SLOTS(2, false); + else if (kv_mode == 1) STRATA_ATTN_SLOTS(1, false); + else STRATA_ATTN_SLOTS(0, false); + } +#undef STRATA_ATTN_SLOTS + attn_merge_kernel<<>>(part_acc, part_m, part_l, n_chunks, + attn, stride); + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) { + std::fprintf(stderr, "qsa_decode_attn_slots: %s\n", cudaGetErrorString(e)); + std::exit(1); + } + return true; +} + uint64_t qsa_decode_attn_scratch_floats(int64_t cap, const QsaShapes& s) { const int64_t chunks = (cap + CHUNK - 1) / CHUNK; return (uint64_t) chunks * (uint64_t) s.n_head * (HD + 2) + 64; diff --git a/src/kernels/cuda/qsa_select.cu b/src/kernels/cuda/qsa_select.cu index cb06396a..d5514172 100644 --- a/src/kernels/cuda/qsa_select.cu +++ b/src/kernels/cuda/qsa_select.cu @@ -816,12 +816,11 @@ __global__ void __launch_bounds__(TK_T) block_topk_wide_kernel(const float* __re // qsa_block_scores takes it for every call without an active-block count and at most MQ queries: the captured decode // window, the uncaptured decode, and prefill's pooled16 call. constexpr int MQ = 8; -__global__ void __launch_bounds__(SCORE_WARPS * 32) block_scores_multi_kernel(const float* __restrict__ pooled, - const float* __restrict__ dead, - const float* __restrict__ q_idx, - const int32_t* __restrict__ steps, int nq, - int64_t max_blocks, float* __restrict__ out, - bool early_exit) { +__device__ __forceinline__ void block_scores_multi_body(const float* __restrict__ pooled, + const float* __restrict__ dead, + const float* __restrict__ q_idx, + const int32_t* __restrict__ steps, int nq, int64_t max_blocks, + float* __restrict__ out, bool early_exit) { __shared__ __align__(16) float qs[MQ * IDX_HEADS * IDX_DIM]; __shared__ int64_t s_nkv[MQ], s_nbid[MQ]; if (!early_exit) @@ -868,6 +867,37 @@ __global__ void __launch_bounds__(SCORE_WARPS * 32) block_scores_multi_kernel(co } } +__global__ void __launch_bounds__(SCORE_WARPS * 32) block_scores_multi_kernel(const float* __restrict__ pooled, + const float* __restrict__ dead, + const float* __restrict__ q_idx, + const int32_t* __restrict__ steps, int nq, + int64_t max_blocks, float* __restrict__ out, + bool early_exit) { + block_scores_multi_body(pooled, dead, q_idx, steps, nq, max_blocks, out, early_exit); +} + +// Queries of different slots, each with its own indexer keys: blockIdx.y is the query, and its CTAs run exactly the +// single-query call of block_scores_multi_kernel (qsa_block_scores_slots). +struct ScoreSlotKeys { + const float* pooled[MQ]; + const float* dead[MQ]; +}; +__global__ void __launch_bounds__(SCORE_WARPS * 32) block_scores_slots_kernel(ScoreSlotKeys keys, + const float* __restrict__ q_idx, + const int32_t* __restrict__ steps, + int64_t max_blocks, float* __restrict__ out, + bool early_exit) { + const unsigned z = blockIdx.y; + // the slot's pointers picked by unrolled selects: indexing the argument array by z would copy it to local memory + const float* pooled = keys.pooled[0]; + const float* dead = keys.dead[0]; +#pragma unroll + for (unsigned i = 1; i < MQ; ++i) + if (z == i) { pooled = keys.pooled[i]; dead = keys.dead[i]; } + block_scores_multi_body(pooled, dead, q_idx + (size_t) z * IDX_HEADS * IDX_DIM, + steps + (size_t) z * kStepCount, 1, max_blocks, out + (size_t) z * max_blocks, early_exit); +} + #if !defined(__HIPCC__) // ---- the decode top-k on a thread-block cluster (sm_90+; S19). One CTA per query (block_topk_reg_kernel, or // block_topk_kernel above 33,792 blocks: a --max-context over ~135K) makes four radix passes and two scans over up to @@ -1090,8 +1120,38 @@ __global__ void __launch_bounds__(CL_T) block_topk_cluster_kernel(const float* _ #endif } #endif // !__HIPCC__ +bool scores_multi_on() { + static const bool on = [] { const char* v = std::getenv("STRATA_SCORES_MULTI"); return v == nullptr || std::atoi(v) != 0; }(); + return on; +} +// STRATA_QSA_EARLY_EXIT=0 keeps the old staging (every CTA loads the queries first); the scores are the same bits +bool scores_early_exit() { + static const bool on = [] { const char* v = std::getenv("STRATA_QSA_EARLY_EXIT"); return v == nullptr || std::atoi(v) != 0; }(); + return on; +} } // namespace +bool qsa_block_scores_slots(const float* const* pooled, const float* const* dead, const float* q_idx, + const int32_t* steps, int64_t nq, int64_t max_blocks, const QsaShapes& s, float* scores, + void* stream) { + if (nq <= 0) return true; + if (s.idx_dim != IDX_DIM || s.idx_n_head != IDX_HEADS || s.idx_block != R) { + std::fprintf(stderr, "qsa_block_scores_slots: unsupported indexer geometry\n"); + std::exit(1); + } + if (nq > MQ || !scores_multi_on()) return false; // the single-query call would not run the multi kernel + ScoreSlotKeys keys{}; + for (int64_t z = 0; z < nq; ++z) { + keys.pooled[z] = pooled[z]; + keys.dead[z] = dead[z]; + } + block_scores_slots_kernel<<>>( + keys, q_idx, steps, max_blocks, scores, scores_early_exit()); + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) { std::fprintf(stderr, "qsa_block_scores_slots: %s\n", cudaGetErrorString(e)); std::exit(1); } + return true; +} + void qsa_block_scores(const float* pooled, const float* dead, const float* q_idx, const int32_t* steps, int64_t nq, int64_t max_blocks, const QsaShapes& s, float* scores, void* stream, int64_t active_blocks) { if (nq <= 0) return; @@ -1100,12 +1160,9 @@ void qsa_block_scores(const float* pooled, const float* dead, const float* q_idx std::exit(1); } // a block past a query's n_bid returns at once: the grid need only reach the batch's largest n_bid (C-1) - static const bool multi = [] { const char* v = std::getenv("STRATA_SCORES_MULTI"); return v == nullptr || std::atoi(v) != 0; }(); - if (multi && nq <= MQ && active_blocks <= 0) { // no active count: decode (captured or not) and prefill's pooled16 - // STRATA_QSA_EARLY_EXIT=0 keeps the old staging (every CTA loads the queries first); the scores are the same bits - static const bool early = [] { const char* v = std::getenv("STRATA_QSA_EARLY_EXIT"); return v == nullptr || std::atoi(v) != 0; }(); + if (scores_multi_on() && nq <= MQ && active_blocks <= 0) { // no active count: decode (captured or not) and prefill's pooled16 block_scores_multi_kernel<<<256, SCORE_WARPS * 32, 0, (cudaStream_t) stream>>>(pooled, dead, q_idx, steps, (int) nq, - max_blocks, scores, early); + max_blocks, scores, scores_early_exit()); const cudaError_t e = cudaGetLastError(); if (e != cudaSuccess) { std::fprintf(stderr, "qsa_block_scores multi: %s\n", cudaGetErrorString(e)); std::exit(1); } return; diff --git a/src/kernels/qsa_slots_parity.cpp b/src/kernels/qsa_slots_parity.cpp new file mode 100644 index 00000000..d204a699 --- /dev/null +++ b/src/kernels/qsa_slots_parity.cpp @@ -0,0 +1,209 @@ +// src/kernels/qsa_slots_parity.cpp - STRATA_QSA_SLOTS: a batch window's block scores, top-k and attention as one +// launch over rows of different slots (qsa_block_scores_slots, qsa_block_topk over the rows, qsa_decode_attn_slots) +// against one call per row, as verify.cpp makes them without the switch. Every slot has its own indexer keys, page +// table and K/V pools (fp16, int8, q4_0 and int8-K/q4_0-V) and its own context length; scores, selected ids and the +// attention output must be bitwise identical. Synthetic data, no model. Run it once more with +// STRATA_ATTN_LANECELL=1 for the lane-cell kernels. +#include "strata/kernels/kv_q4.hpp" +#include "strata/kernels/kv_q8.hpp" +#include "strata/kernels/qsa.hpp" +#include "strata/kernels/qsa_decode_attn.hpp" +#include "strata/kernels/qsa_select.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace k = strata::kernels; +namespace { + +void ck(cudaError_t e) { + if (e != cudaSuccess) { + std::fprintf(stderr, "CUDA: %s\n", cudaGetErrorString(e)); + std::exit(2); + } +} +template T* up(const std::vector& h) { + T* d = nullptr; + ck(cudaMalloc(&d, h.size() * sizeof(T))); + ck(cudaMemcpy(d, h.data(), h.size() * sizeof(T), cudaMemcpyHostToDevice)); + return d; +} +template std::vector down(const T* d, size_t n) { + std::vector h(n); + ck(cudaMemcpy(h.data(), d, n * sizeof(T), cudaMemcpyDeviceToHost)); + return h; +} +// a finite fp16 of magnitude 2^-5 .. 2^2 +uint16_t rnd_half(std::mt19937& r) { + const uint32_t x = r(); + return (uint16_t) (((x & 1u) << 15) | ((10u + (x >> 1) % 7u) << 10) | ((x >> 4) & 0x3ffu)); +} + +constexpr int64_t kMaxCells = 32768; + +struct Slot { + float *pooled = nullptr, *dead = nullptr; + int32_t* page_table = nullptr; + void* bufs[6] = {}; + k::QsaAttnPools pools; +}; + +Slot make_slot(int fmt, const k::QsaShapes& s, int64_t max_blocks, std::mt19937& r) { + Slot sl; + std::normal_distribution nd(0.f, 1.f); + std::vector pooled((size_t) (max_blocks * s.idx_dim)), dead((size_t) s.idx_dim); + for (auto& v : pooled) v = nd(r); + for (auto& v : dead) v = nd(r); + sl.pooled = up(pooled); + sl.dead = up(dead); + const int64_t pages = kMaxCells / s.page_size; + std::vector pt((size_t) pages); + std::iota(pt.begin(), pt.end(), 0); + std::shuffle(pt.begin(), pt.end(), r); + for (int i = 0; i < 3; ++i) pt[(size_t) (r() % pages)] = -1; // a few non-resident pages (masked cells) + sl.page_table = up(pt); + sl.pools.page_table = sl.page_table; + const size_t rows = (size_t) (pages * s.n_head_kv * s.page_size), hd = (size_t) s.head_dim; + auto halves = [&](size_t n) { std::vector h(n); for (auto& v : h) v = rnd_half(r); return h; }; + auto codes = [&](size_t n) { std::vector h(n); for (auto& v : h) v = (int8_t) (r() & 0xff); return h; }; + auto q4 = [&](size_t n_rows) { + std::vector h(n_rows * (size_t) k::kv_q4_bytes_per_head((int) hd)); + k::block_q4_0* b = reinterpret_cast(h.data()); + for (size_t i = 0; i < h.size() / sizeof(k::block_q4_0); ++i) { + b[i].d = rnd_half(r); + for (auto& q : b[i].qs) q = (uint8_t) (r() & 0xff); + } + return h; + }; + if (fmt == 0) { + sl.pools.k_pool = (const uint16_t*) (sl.bufs[0] = up(halves(rows * hd))); + sl.pools.v_pool = (const uint16_t*) (sl.bufs[1] = up(halves(rows * hd))); + } else if (fmt == 1 || fmt == 3) { + sl.pools.k_q = (const int8_t*) (sl.bufs[0] = up(codes(rows * hd))); + sl.pools.k_scale = (const uint16_t*) (sl.bufs[1] = up(halves(rows * hd / k::KV_Q8_GROUP))); + if (fmt == 1) { + sl.pools.v_q = (const int8_t*) (sl.bufs[2] = up(codes(rows * hd))); + sl.pools.v_scale = (const uint16_t*) (sl.bufs[3] = up(halves(rows * hd / k::KV_Q8_GROUP))); + } else { + sl.pools.v_q4 = (const uint8_t*) (sl.bufs[2] = up(q4(rows))); + } + } else { + sl.pools.k_q4 = (const uint8_t*) (sl.bufs[0] = up(q4(rows))); + sl.pools.v_q4 = (const uint8_t*) (sl.bufs[1] = up(q4(rows))); + } + return sl; +} + +void free_slot(Slot& sl) { + ck(cudaFree(sl.pooled)); ck(cudaFree(sl.dead)); ck(cudaFree(sl.page_table)); + for (void* b : sl.bufs) if (b) ck(cudaFree(b)); +} + +// one case: `m` rows of different slots, KV format `fmt`, contexts `ctx[i]` +bool check(int fmt, int m, const int64_t* ctx, uint32_t seed) { + const k::QsaShapes s = k::qsa_real_shapes(); + const int64_t cap = k::qsa_selection_width(k::kTopkMaxCells, s); + const int64_t max_blocks = kMaxCells / s.idx_block + 2; + const int64_t NH = s.n_head, HD = s.head_dim, QI = s.idx_n_head * s.idx_dim; + const int64_t sf = (int64_t) k::qsa_decode_attn_scratch_floats(cap, s); + std::mt19937 r(seed); + std::normal_distribution nd(0.f, 1.f); + std::vector slots; + for (int i = 0; i < m; ++i) slots.push_back(make_slot(fmt, s, max_blocks, r)); + std::vector qidx((size_t) (m * QI)), qcur((size_t) (m * NH * HD)); + for (auto& v : qidx) v = nd(r); + for (auto& v : qcur) v = nd(r); + std::vector steps((size_t) (m * k::kStepCount)); + for (int i = 0; i < m; ++i) k::qsa_step_fill(steps.data() + i * k::kStepCount, ctx[i] - 1, s); + float* d_qidx = up(qidx); + float* d_qcur = up(qcur); + int32_t* d_steps = up(steps); + float *sc[2], *scratch[2], *attn[2]; + int32_t* sel[2]; + for (int v = 0; v < 2; ++v) { + ck(cudaMalloc(&sc[v], (size_t) (m * max_blocks) * 4)); + ck(cudaMalloc(&sel[v], (size_t) (m * cap) * 4)); + ck(cudaMalloc(&scratch[v], (size_t) (m * sf) * 4)); + ck(cudaMalloc(&attn[v], (size_t) (m * NH * HD) * 4)); + ck(cudaMemset(sc[v], 0, (size_t) (m * max_blocks) * 4)); + ck(cudaMemset(sel[v], 0, (size_t) (m * cap) * 4)); + ck(cudaMemset(attn[v], 0, (size_t) (m * NH * HD) * 4)); + } + // 0: one call per row (verify.cpp's batch-window loop) + for (int t = 0; t < m; ++t) { + k::qsa_block_scores(slots[t].pooled, slots[t].dead, d_qidx + t * QI, d_steps + t * k::kStepCount, 1, + max_blocks, s, sc[0] + t * max_blocks, nullptr); + k::qsa_block_topk(sc[0] + t * max_blocks, d_steps + t * k::kStepCount, 1, max_blocks, cap, s, sel[0] + t * cap, + nullptr); + k::qsa_decode_attn_batch(d_qcur + t * NH * HD, slots[t].pools, sel[0] + t * cap, d_steps + t * k::kStepCount, + cap, s, scratch[0] + t * sf, attn[0] + t * NH * HD, 1, nullptr); + } + // 1: one launch per step over the rows + const float* pooled[k::kQsaAttnMaxSlots]; + const float* dead[k::kQsaAttnMaxSlots]; + k::QsaAttnSlotPools px; + for (int t = 0; t < m; ++t) { pooled[t] = slots[t].pooled; dead[t] = slots[t].dead; px.p[t] = slots[t].pools; } + if (!k::qsa_block_scores_slots(pooled, dead, d_qidx, d_steps, m, max_blocks, s, sc[1], nullptr)) { + std::fprintf(stderr, "FAIL: qsa_block_scores_slots declined (STRATA_SCORES_MULTI=0?)\n"); + return false; + } + k::qsa_block_topk(sc[1], d_steps, m, max_blocks, cap, s, sel[1], nullptr); + if (!k::qsa_decode_attn_slots(d_qcur, px, sel[1], d_steps, cap, s, scratch[1], attn[1], m, nullptr)) { + std::fprintf(stderr, "FAIL: qsa_decode_attn_slots declined (a pre-sm_75 card or STRATA_ATTN_PRE75=1?)\n"); + return false; + } + ck(cudaDeviceSynchronize()); + bool ok = true; + const auto s0 = down(sc[0], (size_t) (m * max_blocks)), s1 = down(sc[1], (size_t) (m * max_blocks)); + const auto i0 = down(sel[0], (size_t) (m * cap)), i1 = down(sel[1], (size_t) (m * cap)); + const auto a0 = down(attn[0], (size_t) (m * NH * HD)), a1 = down(attn[1], (size_t) (m * NH * HD)); + for (int t = 0; t < m && ok; ++t) { + const int64_t nb = steps[(size_t) (t * k::kStepCount + k::kStepNBid)] + 1; + const int64_t w = steps[(size_t) (t * k::kStepCount + k::kStepWidth)]; + const char* what = nullptr; + if (std::memcmp(&s0[(size_t) (t * max_blocks)], &s1[(size_t) (t * max_blocks)], (size_t) nb * 4)) what = "scores"; + else if (std::memcmp(&i0[(size_t) (t * cap)], &i1[(size_t) (t * cap)], (size_t) w * 4)) what = "ids"; + else if (std::memcmp(&a0[(size_t) (t * NH * HD)], &a1[(size_t) (t * NH * HD)], (size_t) (NH * HD) * 4)) + what = "attention"; + if (what) { + std::fprintf(stderr, "FAIL fmt=%d rows=%d row=%d ctx=%lld: %s differ\n", fmt, m, t, (long long) ctx[t], what); + ok = false; + } + } + double mag = 0; // the attention output is not trivially zero + for (float v : a0) mag += std::fabs(v); + if (ok && !(mag > 0)) { std::fprintf(stderr, "FAIL fmt=%d rows=%d: attention output is zero\n", fmt, m); ok = false; } + for (int v = 0; v < 2; ++v) { ck(cudaFree(sc[v])); ck(cudaFree(sel[v])); ck(cudaFree(scratch[v])); ck(cudaFree(attn[v])); } + ck(cudaFree(d_qidx)); ck(cudaFree(d_qcur)); ck(cudaFree(d_steps)); + for (auto& sl : slots) free_slot(sl); + return ok; +} + +} // namespace + +int main() { + int devices = 0; + if (cudaGetDeviceCount(&devices) != cudaSuccess || devices == 0) { + std::puts("SKIP: no CUDA device"); + return 77; + } + // contexts per row: under and over the selection width (2048 cells), partial and complete indexer blocks + const int64_t ctx[8] = {1500, 37, 9000, 2049, 32768, 300, 20001, 4096}; + int cases = 0; + for (int fmt = 0; fmt < 4; ++fmt) + for (int m : {1, 2, 4, 8}) { + if (!check(fmt, m, ctx, 1000u * (uint32_t) fmt + (uint32_t) m)) return 1; + ++cases; + } + std::printf("PASS: %d cases (4 KV formats x 1/2/4/8 rows of different slots%s): scores, ids and attention bitwise " + "identical to one call per row\n", cases, std::getenv("STRATA_ATTN_LANECELL") ? ", lane-cell" : ""); + return 0; +} From 6959adf40469535f9bcfce91b891a1566e8c8dd7 Mon Sep 17 00:00:00 2001 From: havok2-htwo Date: Mon, 12 Oct 2026 06:26:25 +0200 Subject: [PATCH 27/33] tests: qsa_slots_parity skips where a slots launcher declines by design STRATA_SCORES_MULTI=0, the pre-sm_75 attention (STRATA_EXPERIMENTAL_SM60 builds on a V100/P100) and the gfx906 query swizzle make qsa_block_scores_slots or qsa_decode_attn_slots decline; the engine keeps its per-row calls there, so a decline is no failure. A declined case prints SKIP, the test exits 77 when every case was declined, and STRATA_SCORES_MULTI=0 skips up front. --- src/kernels/qsa_slots_parity.cpp | 48 +++++++++++++++++++++----------- 1 file changed, 32 insertions(+), 16 deletions(-) diff --git a/src/kernels/qsa_slots_parity.cpp b/src/kernels/qsa_slots_parity.cpp index d204a699..bd804cb2 100644 --- a/src/kernels/qsa_slots_parity.cpp +++ b/src/kernels/qsa_slots_parity.cpp @@ -3,7 +3,8 @@ // against one call per row, as verify.cpp makes them without the switch. Every slot has its own indexer keys, page // table and K/V pools (fp16, int8, q4_0 and int8-K/q4_0-V) and its own context length; scores, selected ids and the // attention output must be bitwise identical. Synthetic data, no model. Run it once more with -// STRATA_ATTN_LANECELL=1 for the lane-cell kernels. +// STRATA_ATTN_LANECELL=1 for the lane-cell kernels. Where a launcher declines by design (STRATA_SCORES_MULTI=0, the +// pre-sm_75 attention, the gfx906 query swizzle) the engine keeps its per-row calls and the test skips (77). #include "strata/kernels/kv_q4.hpp" #include "strata/kernels/kv_q8.hpp" #include "strata/kernels/qsa.hpp" @@ -107,8 +108,10 @@ void free_slot(Slot& sl) { for (void* b : sl.bufs) if (b) ck(cudaFree(b)); } +enum Result { kPass, kFail, kSkip }; + // one case: `m` rows of different slots, KV format `fmt`, contexts `ctx[i]` -bool check(int fmt, int m, const int64_t* ctx, uint32_t seed) { +Result check(int fmt, int m, const int64_t* ctx, uint32_t seed) { const k::QsaShapes s = k::qsa_real_shapes(); const int64_t cap = k::qsa_selection_width(k::kTopkMaxCells, s); const int64_t max_blocks = kMaxCells / s.idx_block + 2; @@ -151,17 +154,22 @@ bool check(int fmt, int m, const int64_t* ctx, uint32_t seed) { const float* dead[k::kQsaAttnMaxSlots]; k::QsaAttnSlotPools px; for (int t = 0; t < m; ++t) { pooled[t] = slots[t].pooled; dead[t] = slots[t].dead; px.p[t] = slots[t].pools; } + // a declined launch is no failure: the engine runs the per-row calls there (STRATA_SCORES_MULTI=0, the pre-sm_75 + // attention, the gfx906 query swizzle) + Result res = kPass; if (!k::qsa_block_scores_slots(pooled, dead, d_qidx, d_steps, m, max_blocks, s, sc[1], nullptr)) { - std::fprintf(stderr, "FAIL: qsa_block_scores_slots declined (STRATA_SCORES_MULTI=0?)\n"); - return false; - } - k::qsa_block_topk(sc[1], d_steps, m, max_blocks, cap, s, sel[1], nullptr); - if (!k::qsa_decode_attn_slots(d_qcur, px, sel[1], d_steps, cap, s, scratch[1], attn[1], m, nullptr)) { - std::fprintf(stderr, "FAIL: qsa_decode_attn_slots declined (a pre-sm_75 card or STRATA_ATTN_PRE75=1?)\n"); - return false; + std::puts("SKIP: qsa_block_scores_slots declined (STRATA_SCORES_MULTI=0); the engine keeps the per-row calls"); + res = kSkip; + } else { + k::qsa_block_topk(sc[1], d_steps, m, max_blocks, cap, s, sel[1], nullptr); + if (!k::qsa_decode_attn_slots(d_qcur, px, sel[1], d_steps, cap, s, scratch[1], attn[1], m, nullptr)) { + std::puts("SKIP: qsa_decode_attn_slots declined (the pre-sm_75 or gfx906 query-swizzle attention); the " + "engine keeps the per-row calls"); + res = kSkip; + } } ck(cudaDeviceSynchronize()); - bool ok = true; + bool ok = res == kPass; const auto s0 = down(sc[0], (size_t) (m * max_blocks)), s1 = down(sc[1], (size_t) (m * max_blocks)); const auto i0 = down(sel[0], (size_t) (m * cap)), i1 = down(sel[1], (size_t) (m * cap)); const auto a0 = down(attn[0], (size_t) (m * NH * HD)), a1 = down(attn[1], (size_t) (m * NH * HD)); @@ -181,10 +189,11 @@ bool check(int fmt, int m, const int64_t* ctx, uint32_t seed) { double mag = 0; // the attention output is not trivially zero for (float v : a0) mag += std::fabs(v); if (ok && !(mag > 0)) { std::fprintf(stderr, "FAIL fmt=%d rows=%d: attention output is zero\n", fmt, m); ok = false; } + if (res == kPass && !ok) res = kFail; for (int v = 0; v < 2; ++v) { ck(cudaFree(sc[v])); ck(cudaFree(sel[v])); ck(cudaFree(scratch[v])); ck(cudaFree(attn[v])); } ck(cudaFree(d_qidx)); ck(cudaFree(d_qcur)); ck(cudaFree(d_steps)); for (auto& sl : slots) free_slot(sl); - return ok; + return res; } } // namespace @@ -195,15 +204,22 @@ int main() { std::puts("SKIP: no CUDA device"); return 77; } + if (const char* v = std::getenv("STRATA_SCORES_MULTI"); v && std::atoi(v) == 0) { + std::puts("SKIP: STRATA_SCORES_MULTI=0 (the slots launch is off; the engine keeps the per-row calls)"); + return 77; + } // contexts per row: under and over the selection width (2048 cells), partial and complete indexer blocks const int64_t ctx[8] = {1500, 37, 9000, 2049, 32768, 300, 20001, 4096}; - int cases = 0; + int cases = 0, skipped = 0; // the gfx906 query swizzle declines only the int8 K/V format for (int fmt = 0; fmt < 4; ++fmt) for (int m : {1, 2, 4, 8}) { - if (!check(fmt, m, ctx, 1000u * (uint32_t) fmt + (uint32_t) m)) return 1; - ++cases; + const Result res = check(fmt, m, ctx, 1000u * (uint32_t) fmt + (uint32_t) m); + if (res == kFail) return 1; + ++(res == kSkip ? skipped : cases); } - std::printf("PASS: %d cases (4 KV formats x 1/2/4/8 rows of different slots%s): scores, ids and attention bitwise " - "identical to one call per row\n", cases, std::getenv("STRATA_ATTN_LANECELL") ? ", lane-cell" : ""); + if (cases == 0) return 77; + std::printf("PASS: %d cases (4 KV formats x 1/2/4/8 rows of different slots%s, %d declined): scores, ids and " + "attention bitwise identical to one call per row\n", cases, + std::getenv("STRATA_ATTN_LANECELL") ? ", lane-cell" : "", skipped); return 0; } From 1d9758f897601fb6d2be45f65b01071951321e33 Mon Sep 17 00:00:00 2001 From: havok2-htwo Date: Mon, 12 Oct 2026 12:46:01 +0200 Subject: [PATCH 28/33] prefill: STRATA_HANDOFF_PIPE=P hands a layer split's chunk on in P pieces, gated by events, on a persistent thread A layer split hands each prompt chunk's rows (21 MB per 512 tokens) to the next card through a pinned host buffer: one D2H, a host stream sync, a new std::async thread, then one H2D before the next stage's first kernel. The 3090s here have no P2P (topo: CNS) and cudaMemcpyPeerAsync is driver-staged and slower (3.4 ms vs 3.2 ms for D2H + H2D), so the copy stays on the host route; nsys showed 3.8-4.0 ms per 512-row hop, of which ~1-1.4 ms was the thread start alone. With STRATA_HANDOFF_PIPE=P (2..16, opt-in; unset = unchanged): - the sending stage records an event when its chunk's work is done and one after each of P row-piece downloads into the same pinned buffer, and waits on the host only for the first (on_stage_chunk's checkpoint parts and the error check need the state, not the copy); - the next stage waits on the GPU for each piece's event (cross-device cudaStreamWaitEvent) before that piece's upload, so its uploads overlap the remaining downloads (separate PCIe links); a smaller receiving chunk waits for every piece, then copies as before; - the next stage's chunks run on one worker thread per sending stage, started and pinned once, whose packaged_task futures carry the same results and exceptions as std::async's (it clears the CUDA error state after each job, as a thread's end did). STRATA_HANDOFF_PIPE_WORKER=0 keeps std::async (A/B). Same bytes in the same rows before the next stage's first kernel: exact. No device memory (events only, the existing two pinned buffers per stage). Measured (T16-143l5, P=8): 512-row hops 3.8-4.0 -> 1.85-1.89 ms, 143-row hops 1.6 -> 1.0 ms; reads 1.2K about -1.5 %, 150 about -1 %, 9K (agent, --kv-resident) -3 %; decode rows/s unchanged. batch_test16/32 (greedy and temperature 0.7), batch_interleave_test and batch_overlap_test (+ the stage fault arm) byte-/token-identical to the reference dumps; an agent-config run with checkpoint parts byte-identical to the reference binary. --- include/strata/prefill/prefill.hpp | 4 + src/prefill/prefill.cpp | 149 ++++++++++++++++++++++++++++- 2 files changed, 150 insertions(+), 3 deletions(-) diff --git a/include/strata/prefill/prefill.hpp b/include/strata/prefill/prefill.hpp index dc392990..9b2893fa 100644 --- a/include/strata/prefill/prefill.hpp +++ b/include/strata/prefill/prefill.hpp @@ -208,6 +208,10 @@ private: bool single_chunk_ = false; ///< a later stage: the prompt is one chunk (set by the stage before) bool bind_stage_helper(int64_t T); // binds the helper's buffers for a one-chunk prompt of T tokens const float* hand_in_ = nullptr; ///< the previous stage's rows of the chunk being read (host, pinned) + /// STRATA_HANDOFF_PIPE: the previous stage's per-piece "landed in hand_in_" events (cudaEvent_t[hand_pieces_], + /// on its device) when it copies the chunk in pieces without a host wait; null with the one-copy hand-off + const void* hand_ev_ = nullptr; + int hand_pieces_ = 0; std::string next_err_; std::future next_run_; diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index e52d0f05..b3529c71 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -47,6 +47,7 @@ #include #include #include +#include #include #include #include @@ -335,6 +336,77 @@ inline int bf16x2_mode(bool f16_io) { return f16_io ? 0 : v; } inline bool bf16x2(bool f16_io) { return bf16x2_mode(f16_io) != 0; } +// STRATA_HANDOFF_PIPE=P (opt-in, 2..16; unset/0/1 = the one copy): a layer split hands a chunk's rows on in P row pieces. +// The stage records an event when its chunk's work is done and one after each piece's copy into the pinned hand-off +// buffer, waits on the host only for the first (what on_stage_chunk's checkpoint parts and the error check need), and +// starts the next stage at once: that stage's upload of piece i waits on piece i's event on the GPU, so its uploads +// overlap the remaining downloads (separate PCIe links; the 3090s here have no P2P) and the thread start is hidden +// behind them. The same bytes land in the same rows before the next stage's first kernel: exact. No device memory; +// the events and the existing two pinned buffers per stage only. +static constexpr int kHandPiecesMax = 16; +static int handoff_pipe_pieces() { + static const int v = [] { + const char* e = std::getenv("STRATA_HANDOFF_PIPE"); + const int p = e ? std::atoi(e) : 0; + return p >= 2 ? std::min(p, kHandPiecesMax) : 0; + }(); + return v; +} +// rows [r0, r0 + nr) of piece i of a T-row chunk in P pieces (the same split on both sides of a hand-off) +static void handoff_piece(int64_t T, int P, int i, int64_t& r0, int64_t& nr) { + const int64_t per = (T + P - 1) / P; + r0 = std::min(T, (int64_t) i * per); + nr = std::min(T, r0 + per) - r0; +} +// STRATA_HANDOFF_PIPE: the next stage's chunks run on one thread of the stage's own, started once and pinned once +// (std::async started a thread per chunk: ~1 ms from the hand-off to the next stage's first call, measured with nsys). +// The futures are the same (run_impl's result, or what it threw), so the chain's waits do not change. +// (STRATA_HANDOFF_PIPE_WORKER=0: a thread per chunk again, for an A/B of the two halves.) +static bool handoff_pipe_worker() { + static const bool v = [] { const char* e = std::getenv("STRATA_HANDOFF_PIPE_WORKER"); return !e || std::atoi(e) != 0; }(); + return handoff_pipe_pieces() > 0 && v; +} +struct HandWorker { + std::mutex mu; + std::condition_variable cv; + std::deque> jobs; + bool stop = false; + std::thread th; + HandWorker() { + th = std::thread([this] { + strata::aux_cpus::pin_current_thread(); + for (;;) { + std::packaged_task job; + { + std::unique_lock lk(mu); + cv.wait(lk, [this] { return stop || !jobs.empty(); }); + if (jobs.empty()) return; // stopped, and every job taken has run (no broken promise) + job = std::move(jobs.front()); + jobs.pop_front(); + } + job(); + } + }); + } + std::future submit(std::packaged_task job) { + std::future f = job.get_future(); + { + std::lock_guard lk(mu); + jobs.push_back(std::move(job)); + } + cv.notify_one(); + return f; + } + ~HandWorker() { + { + std::lock_guard lk(mu); + stop = true; + } + cv.notify_one(); + if (th.joinable()) th.join(); + } +}; + // S23 (opt-in STRATA_HC_UPMIX=1): the hyper-connection read's up projection and gr_mix_r as one kernel (gr_upmix, gfx11); // STRATA_HC_UPMIX_CHECK=N also runs the default pair on the first N reads and reports the difference of `mixed` static int64_t pf_switch_min_t() { // S23: STRATA_PF_SWITCH_MIN_T=N - the rounding-level prompt switches only on chunks of @@ -882,6 +954,11 @@ struct Prefill::Impl { // layer split: the device, and the hand-off to the next stage (two pinned chunk buffers, used in turn) int device = -1; float* hand[2] = {}; + // STRATA_HANDOFF_PIPE: per hand-off buffer, "the chunk's work is done" and one "landed" event per piece + int hand_pieces = 0; + cudaEvent_t hand_done[2] = {}; + cudaEvent_t hand_ev[2][kHandPiecesMax] = {}; + std::unique_ptr hand_worker; // STRATA_HANDOFF_PIPE: the next stage's chunks' thread (lazily) // C-4: the chunk's token ids on the device, for one batched embedding gather int32_t* tok_dev = nullptr; std::vector tok_host; @@ -945,6 +1022,7 @@ void Prefill::reset() { void Prefill::release() { if (!impl_) return; + impl_->hand_worker.reset(); // idle here (run drains the chain before it returns); joins its thread if (impl_->cs) cudaStreamSynchronize(impl_->cs); if (impl_->copy) cudaStreamSynchronize(impl_->copy); if (impl_->kv_copy) cudaStreamSynchronize(impl_->kv_copy); @@ -954,6 +1032,9 @@ void Prefill::release() { } for (int b = 0; b < 2; ++b) { if (impl_->hand[b]) cudaFreeHost(impl_->hand[b]); + if (impl_->hand_done[b]) cudaEventDestroy(impl_->hand_done[b]); + for (cudaEvent_t& e : impl_->hand_ev[b]) + if (e) cudaEventDestroy(e); if (impl_->ple_copied[b]) cudaEventDestroy(impl_->ple_copied[b]); if (impl_->ple_emb_host[b] && impl_->ple_pageable[b].empty()) cudaFreeHost(impl_->ple_emb_host[b]); } @@ -1156,6 +1237,16 @@ bool Prefill::init(const core::WeightTable& wt, const core::ModelGeometry& g, co err = "prefill: the layer split's hand-off buffers"; return false; } + if (next_ != nullptr && handoff_pipe_pieces() > 0 && m.hand_pieces == 0) { // events only: no device memory + bool ok = true; + auto make = [](cudaEvent_t& e) { return e != nullptr || cudaEventCreateWithFlags(&e, cudaEventDisableTiming) == cudaSuccess; }; + for (int b = 0; b < 2; ++b) { // (a retry after a failed init keeps the events it made) + ok = ok && make(m.hand_done[b]); + for (int i = 0; ok && i < handoff_pipe_pieces(); ++i) ok = make(m.hand_ev[b][i]); + } + if (!ok) { err = "prefill: the layer split's hand-off events (STRATA_HANDOFF_PIPE)"; return false; } + m.hand_pieces = handoff_pipe_pieces(); + } if (m.tok_dev == nullptr) { if (const cudaError_t e = cudaMalloc((void**) &m.tok_dev, (size_t) chunk * sizeof(int32_t)); e != cudaSuccess) { err = std::string("prefill: the token id buffer (") + cudaGetErrorString(e) + ")"; @@ -2235,7 +2326,30 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri const auto tsetup = Clock::now(); // ---- embeddings, broadcast to the four streams - or, in a later stage of a layer split, the rows the // previous stage handed on - if (hand_in_ != nullptr) { + if (hand_in_ != nullptr && hand_ev_ != nullptr) { + // STRATA_HANDOFF_PIPE: each piece's upload waits on the GPU for its download on the stage before. The + // stage before split the chunk it handed on (n rows); one chunk here is all of it, otherwise (a smaller + // chunk here) every piece is waited for before the one copy. + const auto* ev = static_cast(hand_ev_); + const bool whole = c0 == 0 && T == n; + bool ok = true; + for (int i = 0; ok && i < hand_pieces_; ++i) { + int64_t r0 = 0, nr = 0; + handoff_piece(n, hand_pieces_, i, r0, nr); + ok = cudaStreamWaitEvent(m.cs, ev[i], 0) == cudaSuccess; + if (ok && whole && nr > 0) + ok = cudaMemcpyAsync(m.R + (size_t) r0 * D, hand_in_ + (size_t) r0 * D, (size_t) nr * D * 4, + cudaMemcpyHostToDevice, m.cs) == cudaSuccess; + } + if (ok && !whole) + ok = cudaMemcpyAsync(m.R, hand_in_ + (size_t) c0 * D, (size_t) T * D * 4, cudaMemcpyHostToDevice, + m.cs) == cudaSuccess; + if (!ok) { + err = std::string("prefill: the layer split's hand-off upload failed (STRATA_HANDOFF_PIPE): ") + + cudaGetErrorString(cudaGetLastError()); + return false; + } + } else if (hand_in_ != nullptr) { if (cudaMemcpyAsync(m.R, hand_in_ + (size_t) c0 * D, (size_t) T * D * 4, cudaMemcpyHostToDevice, m.cs) != cudaSuccess) { err = "prefill: the layer split's hand-off upload failed"; @@ -4272,8 +4386,25 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri if (next_ != nullptr) { // The current hand-off slot was used two chunks ago. float* h = m.hand[hand_buf_]; - if (cudaMemcpyAsync(h, m.R, (size_t) T * D * 4, cudaMemcpyDeviceToHost, m.cs) != cudaSuccess || - cudaStreamSynchronize(m.cs) != cudaSuccess) { + const int hp = m.hand_pieces; + if (hp > 0) { + // STRATA_HANDOFF_PIPE: the pieces' downloads stay queued; the host waits for the chunk's work only (the + // state on_stage_chunk saves, the error check), the next stage's uploads wait on the pieces' events + bool ok = cudaEventRecord(m.hand_done[hand_buf_], m.cs) == cudaSuccess; + for (int i = 0; ok && i < hp; ++i) { + int64_t r0 = 0, nr = 0; + handoff_piece(T, hp, i, r0, nr); + if (nr > 0) + ok = cudaMemcpyAsync(h + (size_t) r0 * D, m.R + (size_t) r0 * D, (size_t) nr * D * 4, + cudaMemcpyDeviceToHost, m.cs) == cudaSuccess; + ok = ok && cudaEventRecord(m.hand_ev[hand_buf_][i], m.cs) == cudaSuccess; + } + if (!ok || cudaEventSynchronize(m.hand_done[hand_buf_]) != cudaSuccess) { + err = std::string("prefill: the layer split's hand-off: ") + cudaGetErrorString(cudaGetLastError()); + return false; + } + } else if (cudaMemcpyAsync(h, m.R, (size_t) T * D * 4, cudaMemcpyDeviceToHost, m.cs) != cudaSuccess || + cudaStreamSynchronize(m.cs) != cudaSuccess) { err = std::string("prefill: the layer split's hand-off: ") + cudaGetErrorString(cudaGetLastError()); return false; } @@ -4283,7 +4414,19 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri if (next_run_.valid() && !next_run_.get()) { err = next_err_; return false; } next_err_.clear(); next_->hand_in_ = h; + next_->hand_ev_ = hp > 0 ? static_cast(m.hand_ev[hand_buf_]) : nullptr; + next_->hand_pieces_ = hp; next_->single_chunk_ = single_chunk; + if (handoff_pipe_worker()) { + if (!m.hand_worker) m.hand_worker = std::make_unique(); + next_run_ = m.hand_worker->submit(std::packaged_task([this, tokens, c0, T, p0] { + const bool r = next_->run_impl(tokens + c0, T, p0, next_err_); + int none = 0; // keep the first fault for chain_cuda_error, then clear what a thread's end cleared + if (const int e = (int) cudaPeekAtLastError(); e != 0) next_->cuda_err_.compare_exchange_strong(none, e); + (void) cudaGetLastError(); + return r; + })); + } else next_run_ = std::async(std::launch::async, [this, tokens, c0, T, p0] { strata::aux_cpus::pin_current_thread(); return next_->run_impl(tokens + c0, T, p0, next_err_); From ed4fa42a8014dec5c6a4aafc7581838e955823f1 Mon Sep 17 00:00:00 2001 From: havok2-htwo Date: Wed, 14 Oct 2026 07:02:42 +0200 Subject: [PATCH 29/33] serve: STRATA_ADMIT_SHORT_FIRST= admits short prompts before long ones (opt-in) New requests took the control lines in whatever order the lock fell, so a 500-token chat question could wait behind several agent reads. With the env, a prompt of at most that many tokens goes first (arrival order within each class); a longer one that waited STRATA_ADMIT_MAX_WAIT_S (30 s) counts as short. A request already in acquire() gives the lines back when a shorter one came. Only the order changes, never what is read. Ported from havok2-htwo/Strata 08830ddf onto 0.1.44.1: _take_control has no image-request line here, so its gate is only the ordering; the first admission passes new=True. --- serve/server.py | 40 +++++++++++-- serve/test_admit_order.py | 119 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 155 insertions(+), 4 deletions(-) create mode 100644 serve/test_admit_order.py diff --git a/serve/server.py b/serve/server.py index 5ca7f4e4..2cb99bb6 100644 --- a/serve/server.py +++ b/serve/server.py @@ -254,6 +254,15 @@ def _timeout_env(name: str, default: float) -> float | None: # still working is never ended by this, only reported once (the recommendation: engine_silence_s, or this variable). # STRATA_ENGINE_STALL_S overrides it (0 = off). Needs psutil (setup installs it); without it nothing is ended. ENGINE_STALL_S = _timeout_env("STRATA_ENGINE_STALL_S", 90.0) +# --batch: new requests take the control lines (one prompt read at a time) short prompts first: a prompt of at most +# STRATA_ADMIT_SHORT_FIRST tokens goes before longer ones (opt-in; unset or 0: whoever gets the lock first), and a +# longer one that waited STRATA_ADMIT_MAX_WAIT_S (default 30) counts as short. A chat question then waits for the one +# read in progress, not for every agent read that came before it. +try: + ADMIT_SHORT_FIRST = max(0, int(os.environ.get("STRATA_ADMIT_SHORT_FIRST") or 0)) +except ValueError: + ADMIT_SHORT_FIRST = 0 +ADMIT_MAX_WAIT_S = _timeout_env("STRATA_ADMIT_MAX_WAIT_S", 30.0) or 0.0 STALL_CPU_EPS_S = 0.5 # CPU seconds the engine may use in the whole stall window and still count as frozen STALL_IO_EPS_B = 1 << 20 # bytes read or written in that window @@ -1416,10 +1425,11 @@ class StrataEngine: YIELDS_MAX = 2 # #656: how often one request's prompt read gives way to a shorter waiting one - def _take_control(self, cancel, plen: int, after_epoch: int | None = None): + def _take_control(self, cancel, plen: int, after_epoch: int | None = None, new: bool = False): """Waits for the control lines (one prompt read at a time), yielding None heartbeats; False when cancelled. - `after_epoch`: a request whose read gave way lets the requests waiting then go first.""" - entry = [plen] + `after_epoch`: a request whose read gave way lets the requests waiting then go first. + `new`: the request's first admission (STRATA_ADMIT_SHORT_FIRST orders only these).""" + entry = [plen, time.monotonic(), new] # (length, arrival, ordered: STRATA_ADMIT_SHORT_FIRST) with self.slot_cv: self.waiting += 1 self.wait_lens.append(entry) @@ -1433,7 +1443,17 @@ class StrataEngine: raise EngineDied("the engine stopped while this request waited; it was not sent") with self.slot_cv: turn = after_epoch is None or self.ctl_epoch > after_epoch or self.waiting <= 1 + if turn and new and ADMIT_SHORT_FIRST > 0: + turn = self._admit_next() is entry if turn and self.ctl.acquire(timeout=0.5): + if new and ADMIT_SHORT_FIRST > 0: + with self.slot_cv: # a shorter one came while this one waited in acquire() + first = self._admit_next() is entry + if not first: + self.ctl.release() + with self.slot_cv: + self.slot_cv.notify_all() + continue if self.alive(): break self.ctl.release() # it died (or is being restarted) while this one was getting @@ -1456,6 +1476,18 @@ class StrataEngine: self.slot_cv.notify_all() return True + def _admit_next(self): + """STRATA_ADMIT_SHORT_FIRST= (the caller holds slot_cv): the new request that takes the control lines + next - one whose prompt is at most that long (it reads little) before a longer one, in arrival order within + each; a longer one that has waited STRATA_ADMIT_MAX_WAIT_S counts as short (it is never held back for good). + Off (unset or 0): whoever gets the lock first, as before. Only the order changes, never what is read.""" + now = time.monotonic() + ordered = [e for e in self.wait_lens if len(e) > 2 and e[2]] + if not ordered: + return None + return min(ordered, key=lambda e: (0 if e[0] <= ADMIT_SHORT_FIRST or now - e[1] >= ADMIT_MAX_WAIT_S else 1, + e[1])) + SOLO_AGAIN_MAX = 2 # how often a request left alone in a slot goes back to the solo path SOLO_AGAIN_MIN_LEFT = 32 # ... only with at least this many tokens still allowed (max_tokens) @@ -1493,7 +1525,7 @@ class StrataEngine: prompt, left = list(ids), int(max_new) reused0 = None # the first read's reused tokens: a continued leg's count includes this request's own output carry = {} # #1869: the figures of the legs that ended in a hand-back to the solo path (the final DONE adds to them) - ok = yield from self._take_control(cancel, len(prompt)) + ok = yield from self._take_control(cancel, len(prompt), new=True) if not ok: return holding, born = True, self.gen # (the engine it now has the control lines of) diff --git a/serve/test_admit_order.py b/serve/test_admit_order.py new file mode 100644 index 00000000..67766e55 --- /dev/null +++ b/serve/test_admit_order.py @@ -0,0 +1,119 @@ +"""serve/test_admit_order.py - STRATA_ADMIT_SHORT_FIRST: new requests take the control lines short prompts first +(StrataEngine._take_control / _admit_next; no process, no GPU). + + python -m unittest serve.test_admit_order -v +""" +from __future__ import annotations + +import sys +import threading +import time +import unittest +from pathlib import Path +from unittest import mock + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +import serve.server as server # noqa: E402 +from serve.server import StrataEngine # noqa: E402 + + +def engine_without_process(n=2): + """A StrataEngine with the admission state of a started one and no process: alive() is `e.up`.""" + e = StrataEngine("missing-executable", [], lazy=True) + e.batch = n + e.slot_busy = [False] * n + e.slot_claims, e.slot_releasing, e._orphan_seen = set(), set(), {} + e.slot_cv = threading.Condition() + e.waiting, e.admitting, e.wait_lens, e.ctl_epoch = 0, 0, [], 0 + e.ctl = threading.Lock() + e.gen = 1 + e.up = True + e.alive = lambda: e.up + return e + + +class AdmitOrderTest(unittest.TestCase): + def setUp(self): + self.e = engine_without_process(16) + self.order, self.cancels = [], [] + self.order_lock = threading.Lock() + + def tearDown(self): + for c in self.cancels: + c.set() + + def take(self, name, plen, **kw): + """A request waiting for the control lines; once it has them it notes its name and gives them back.""" + c = threading.Event() + self.cancels.append(c) + + def go(): + gen = self.e._take_control(c, plen, **kw) + try: + while True: + next(gen) + except StopIteration as s: + if s.value: + with self.order_lock: + self.order.append(name) + time.sleep(0.05) # its read + self.e.ctl.release() + threading.Thread(target=go, daemon=True).start() + + def until(self, cond, s=5.0): + end = time.time() + s + while time.time() < end and not cond(): + time.sleep(0.01) + self.assertTrue(cond()) + + def queue(self, *reqs): + """While a long read holds the control lines, the requests arrive in this order; then the read ends.""" + self.assertTrue(self.e.ctl.acquire(timeout=1)) + for name, plen in reqs: + self.take(name, plen, new=True) + self.until(lambda n=len(self.order) + sum(1 for _ in self.e.wait_lens): self.e.waiting >= 1) + time.sleep(0.02) # (distinct arrival times) + self.until(lambda: self.e.waiting == len(reqs)) + self.e.ctl.release() + self.until(lambda: len(self.order) == len(reqs), s=15.0) + return self.order + + def test_short_first_puts_the_chat_before_the_agent_reads(self): + with mock.patch.object(server, "ADMIT_SHORT_FIRST", 8192), mock.patch.object(server, "ADMIT_MAX_WAIT_S", 60.0): + order = self.queue(("agent1", 120000), ("agent2", 190000), ("chat", 500), ("agent3", 150000)) + self.assertEqual(order[0], "chat") + self.assertEqual(order[1:], ["agent1", "agent2", "agent3"]) # arrival order among the long ones + + def test_a_long_request_that_waited_too_long_goes_first(self): + with mock.patch.object(server, "ADMIT_SHORT_FIRST", 8192), mock.patch.object(server, "ADMIT_MAX_WAIT_S", 0.2): + self.assertTrue(self.e.ctl.acquire(timeout=1)) + self.take("agent", 120000, new=True) + self.until(lambda: self.e.waiting == 1) + time.sleep(0.4) # past STRATA_ADMIT_MAX_WAIT_S + self.take("chat", 500, new=True) + self.until(lambda: self.e.waiting == 2) + self.e.ctl.release() + self.until(lambda: len(self.order) == 2, s=15.0) + self.assertEqual(self.order, ["agent", "chat"]) + + def test_off_by_default(self): + self.assertEqual(server.ADMIT_SHORT_FIRST if "STRATA_ADMIT_SHORT_FIRST" not in __import__("os").environ + else 0, 0) + with mock.patch.object(server, "ADMIT_SHORT_FIRST", 0): + order = self.queue(("agent1", 120000), ("chat", 500)) + self.assertEqual(sorted(order), ["agent1", "chat"]) # both get their turn, in any order + + def test_a_continuation_is_not_held_back(self): + """A request already admitted once (new=False: promoted from the solo path) is not part of the order.""" + with mock.patch.object(server, "ADMIT_SHORT_FIRST", 8192), mock.patch.object(server, "ADMIT_MAX_WAIT_S", 60.0): + self.assertTrue(self.e.ctl.acquire(timeout=1)) + self.take("chat", 500, new=True) + self.take("continuation", 190000) + self.until(lambda: self.e.waiting == 2) + self.e.ctl.release() + self.until(lambda: len(self.order) == 2, s=15.0) + self.assertEqual(sorted(self.order), ["chat", "continuation"]) + + +if __name__ == "__main__": + unittest.main() From 8ccc4a0fe63b649d6c0e44f019644ad6a51cba8c Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Wed, 14 Oct 2026 07:03:56 +0200 Subject: [PATCH 30/33] Verifier::ar_live and no Prefill::cuda_err_ in the hand-off worker (the two pieces of the unported STRATA_PIPE_OVERLAP series that STRATA_ADMIT_MERGE_FIRST and STRATA_HANDOFF_PIPE name) --- include/strata/core/verify.hpp | 3 +++ src/prefill/prefill.cpp | 4 +--- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/include/strata/core/verify.hpp b/include/strata/core/verify.hpp index c988da3e..e3d26155 100644 --- a/include/strata/core/verify.hpp +++ b/include/strata/core/verify.hpp @@ -175,6 +175,9 @@ public: /// The rows the hand-off buffers of `set_stage` hold (0: kVerifyMaxT, the default). More than --batch's 8 slots on a /// layer split: the pipelined slot groups write their rows at hbase = group * rows-per-group, one row per slot. void set_handoff_rows(int rows) { handoff_rows_ = rows; } + /// Is the zero-doorbell graph the one a batch window would run now (every expert of the stage in VRAM by the host + /// table)? Looks at the table, as each window does. (STRATA_ADMIT_MERGE_FIRST's gate.) + bool ar_live() { refresh_ar(); return ar_on(); } /// The next stage: `run` and `commit` continue into it (its pool calls get `next_user`); sampling settings /// and `final_R` are the last stage's. void set_next(Verifier* next, void* next_user) { next_ = next; next_user_ = next_user; } diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index b3529c71..3d6d0ec1 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -4421,9 +4421,7 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri if (!m.hand_worker) m.hand_worker = std::make_unique(); next_run_ = m.hand_worker->submit(std::packaged_task([this, tokens, c0, T, p0] { const bool r = next_->run_impl(tokens + c0, T, p0, next_err_); - int none = 0; // keep the first fault for chain_cuda_error, then clear what a thread's end cleared - if (const int e = (int) cudaPeekAtLastError(); e != 0) next_->cuda_err_.compare_exchange_strong(none, e); - (void) cudaGetLastError(); + (void) cudaGetLastError(); // clear what a thread's end cleared (std::async) return r; })); } else From db568409fc9240f3505d3b28765c12654d2f4bbd Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Wed, 14 Oct 2026 07:07:06 +0200 Subject: [PATCH 31/33] tools: batch_test.py takes up to 32 prompts (folds in havok2-htwo's batch_test16.py and batch_test32.py) --- docs/DETAILS.md | 2 +- tools/batch_test.py | 10 +++ tools/batch_test16.py | 181 ----------------------------------------- tools/batch_test32.py | 183 ------------------------------------------ 4 files changed, 11 insertions(+), 365 deletions(-) delete mode 100644 tools/batch_test16.py delete mode 100644 tools/batch_test32.py diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 69b7cdf8..1693cfc0 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -1821,7 +1821,7 @@ the pairs in which the switched arm won). They are here so you can try them on y 180-2,619 tokens - on the 4-GPU split with `--prefill 2048` (chunks of 1,024 tokens and more: the streamed walk), the same with 9 GB less expert cache per GPU (20-31% of the expert reads streamed, so groups mix in-place, copied and mid-group flushed experts), and on one GPU with `--expert-cache-per-layer`; the 150 greedy tokens of each of - `tools/batch_test16.py`'s 16 prompts (solo and batch) were identical too, and to those of a build without the + `tools/batch_test.py --n 16` prompts (solo and batch) were identical too, and to those of a build without the option. The uniform cache (no profile) holds no resident expert when a native pack's prompt is read (serve needs the profile, and a one-shot run fills the cache only while it decodes), so `expert_cache_slot_guard_test` covers it. diff --git a/tools/batch_test.py b/tools/batch_test.py index 5dd61f54..78060b3d 100644 --- a/tools/batch_test.py +++ b/tools/batch_test.py @@ -20,7 +20,17 @@ QUESTIONS = [ "Explain how a transformer's attention works, step by step.", "Donne une recette de tarte aux pommes, etape par etape.", "Describe the life cycle of a star like the Sun.", + "Erklaere ausfuehrlich, wie ein Dieselmotor funktioniert.", + "Write a Rust function that parses a CSV line with quoted fields, then explain it.", + "What were the main consequences of the invention of the printing press?", + "Explique le theoreme de Pythagore avec trois demonstrations differentes.", + "Describe how the immune system responds to a viral infection.", + "Explain the difference between processes and threads in an operating system.", + "Beschreibe die Geschichte des Roemischen Reiches in Grundzuegen.", + "How does public-key cryptography work? Give an example with RSA.", ] +# more than 16 slots: the same questions again, asked to answer in German +QUESTIONS = QUESTIONS + [q + " Answer in German." for q in QUESTIONS] def tokenizer(path): diff --git a/tools/batch_test16.py b/tools/batch_test16.py deleted file mode 100644 index 77686d5c..00000000 --- a/tools/batch_test16.py +++ /dev/null @@ -1,181 +0,0 @@ -#!/usr/bin/env python3 -"""Batching test: the same prompts decoded alone (GEN, the usual path with drafts) and together in the batch -windows (BGEN), greedy. Every slot's tokens must equal its solo tokens; prints the aggregate decode rate. - - python3 tools/batch_test.py --exe engine/strata --config strata-.json --batch 4 --n 4 \ - --extra "--layer-split 12,24,36 --trim-stage-weights --pcie-frac 0 --adapt-every 1000000" -""" -import argparse, json, os, subprocess, sys, tempfile, threading, time -from pathlib import Path - -sys.path.insert(0, str(Path(__file__).resolve().parent)) -import strata_tokenizer as ST # noqa: E402 - -QUESTIONS = [ - "Explique en detail le fonctionnement d'un B-tree.", - "Write a Python function that merges overlapping intervals, then explain it.", - "Compare TCP and QUIC: handshake, congestion control, multiplexing.", - "Raconte l'histoire du calcul de pi, d'Archimede a nos jours.", - "What are the main causes of the French Revolution?", - "Explain how a transformer's attention works, step by step.", - "Donne une recette de tarte aux pommes, etape par etape.", - "Describe the life cycle of a star like the Sun.", - "Erklaere ausfuehrlich, wie ein Dieselmotor funktioniert.", - "Write a Rust function that parses a CSV line with quoted fields, then explain it.", - "What were the main consequences of the invention of the printing press?", - "Explique le theoreme de Pythagore avec trois demonstrations differentes.", - "Describe how the immune system responds to a viral infection.", - "Explain the difference between processes and threads in an operating system.", - "Beschreibe die Geschichte des Roemischen Reiches in Grundzuegen.", - "How does public-key cryptography work? Give an example with RSA.", -] - - -def tokenizer(path): - t = Path(path) - vocab = json.loads((t / "vocab.json").read_text(encoding="utf-8")) - tokens = [None] * len(vocab) - for s, i in vocab.items(): - tokens[i] = s - merges = (t / "merges.txt").read_text(encoding="utf-8").split("\n") - types = json.loads((t / "token_type.json").read_text()) - return ST.Tokenizer(tokens, merges, types) - - -class Engine: - def __init__(self, exe, cfg, batch, extra_env, extra_args): - args = list(cfg["args"]) - if len(cfg.get("gpu") or []) > 1: - args += ["--layer-split", str(cfg.get("layer_split") or "auto")] - if batch: - args += ["--batch", str(batch)] - args += extra_args - env = dict(os.environ, **extra_env) - env["LD_LIBRARY_PATH"] = ":".join(cfg.get("lib_dirs", []) + [env.get("LD_LIBRARY_PATH", "")]) - if os.name == "nt": - env["PATH"] = os.pathsep.join(cfg.get("lib_dirs", []) + [env.get("PATH", "")]) - self.log_path = os.environ.get("BATCH_TEST_LOG") or os.path.join(tempfile.gettempdir(), "batch_test_engine.log") - self.log = open(self.log_path, "w") - self.p = subprocess.Popen([exe, "--serve", *args], cwd=cfg.get("cwd"), stdin=subprocess.PIPE, - stdout=subprocess.PIPE, stderr=self.log, text=True, bufsize=1, env=env) - for line in self.p.stdout: - if line.startswith("READY"): - return - raise SystemExit(f"the engine ended before READY - see {self.log_path}") - - def send(self, line): - self.p.stdin.write(line + "\n") - self.p.stdin.flush() - - def lines(self): - for line in self.p.stdout: - yield line.rstrip("\n") - - -def main(): - ap = argparse.ArgumentParser() - ap.add_argument("--exe", required=True) - ap.add_argument("--config", required=True) - ap.add_argument("--batch", type=int, default=4) - ap.add_argument("--n", type=int, default=4, help="prompts (<= --batch)") - ap.add_argument("--max-new", type=int, default=64) - ap.add_argument("--skip-solo", action="store_true") - ap.add_argument("--keys", default="", help='sampling keys for every request, e.g. "temperature=0.7 top_k=20"') - ap.add_argument("--extra", default="", help='more engine arguments in one string, e.g. "--adapt-every 1000000"') - ap.add_argument("--dump", default="", help="write every slot's tokens (solo and batch) as JSON: an A/B of two engine builds") - ap.add_argument("--long-tokens", type=int, default=0, - help="the LAST prompt is read from about this many tokens of filler text first: its chunks run " - "beside the earlier slots' windows (the prompt path lends experts then)") - ap.add_argument("--mt-min", default="1", help="STRATA_IQ_MT_MIN for the engine (1: exact; empty: the default)") - a = ap.parse_args() - cfg = json.loads(Path(a.config).read_text()) - tok = tokenizer(cfg["tokenizer"]) - prompts = [] - for q in QUESTIONS[: a.n]: - text = f"<|im_start|>user\n{q}<|im_end|>\n<|im_start|>assistant\n\n\n\n\n" - if a.long_tokens and q is QUESTIONS[a.n - 1]: - para = ("The committee reviewed item %d of the long agenda, noting the budget, the schedule and the open " - "risks, and asked the staff to report back next quarter. ") - per = max(1, len(tok.encode(para % 100))) - filler = "".join(para % i for i in range(a.long_tokens // per + 1)) - text = f"<|im_start|>user\n{filler}\n\n{q}<|im_end|>\n<|im_start|>assistant\n\n\n\n\n" - prompts.append(tok.encode(text, parse_special=True)) - env = {"STRATA_DECODE_TIMING": "1", **({"STRATA_VERIFY_PROFILE": "1"} if os.environ.get("PROF") else {})} - if a.mt_min: - env["STRATA_IQ_MT_MIN"] = a.mt_min - eng = Engine(a.exe, cfg, a.batch, env, a.extra.split()) - out = eng.lines() - - solo = [] - if not a.skip_solo: - for i, ids in enumerate(prompts): - eng.send(" ".join(x for x in ("GEN", str(a.max_new), a.keys, ",".join(map(str, ids))) if x)) - got, t0 = [], time.time() - for line in out: - if line.startswith("T "): - got.append(int(line.split()[1])) - elif line.startswith("DONE") or line.startswith("ERR"): - print(f"solo {i}: {len(got)} tokens in {time.time() - t0:.1f}s {line[:60]}", flush=True) - break - solo.append(got) - - # batch: admit every prompt, then the slots decode together - got = {i: [] for i in range(len(prompts))} - done = {} - t_admit = time.time() - first_bt = None - for i, ids in enumerate(prompts): - eng.send(" ".join(x for x in ("BGEN", str(i), str(a.max_new), a.keys, ",".join(map(str, ids))) if x)) - for line in out: - if line.startswith("T "): - got[i].append(int(line.split()[1])) - elif line.startswith("BT "): - _, s, y = line.split() - got[int(s)].append(int(y)) - first_bt = first_bt or time.time() - elif line.startswith("BDONE "): - done[int(line.split()[1])] = line - elif line.startswith("ERR"): - print("batch:", line) - return 1 - elif line.startswith("BADM "): - if line.split()[2] == "0": - done[i] = line - break - t_admitted = time.time() - for line in out: - if line.startswith("BT "): - _, s, y = line.split() - got[int(s)].append(int(y)) - first_bt = first_bt or time.time() - elif line.startswith("BDONE "): - done[int(line.split()[1])] = line - if len(done) == len(prompts): - break - elif line.startswith("ERR"): - print("batch:", line) - return 1 - t_end = time.time() - total = sum(len(v) for v in got.values()) - print(f"batch: {len(prompts)} slots, {total} tokens; admissions {t_admitted - t_admit:.1f}s; " - f"then {t_end - t_admitted:.1f}s -> aggregate {total / max(t_end - t_admit, 1e-9):.1f} tok/s overall, " - f"{sum(len(v) for v in got.values()) / max(t_end - (first_bt or t_admit), 1e-9):.1f} tok/s from the first batch token", - flush=True) - ok = True - for i in range(len(prompts)): - b = got[i] - if solo: - same = b == solo[i] - ok &= same - first_diff = next((k for k in range(min(len(b), len(solo[i]))) if b[k] != solo[i][k]), None) - print(f"slot {i}: {len(b)} tokens, solo {len(solo[i])}: {'IDENTICAL' if same else f'DIFFERS at {first_diff}'}") - print(" ", ascii(tok.decode(b)[:160])) - if a.dump: - Path(a.dump).write_text(json.dumps({"solo": solo, "batch": [got[i] for i in range(len(prompts))]}), encoding="utf-8") - eng.send("QUIT") - eng.p.wait(timeout=180) # the next run needs the GPUs back - return 0 if ok else 2 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/tools/batch_test32.py b/tools/batch_test32.py deleted file mode 100644 index fd60e26b..00000000 --- a/tools/batch_test32.py +++ /dev/null @@ -1,183 +0,0 @@ -#!/usr/bin/env python3 -"""Batching test: the same prompts decoded alone (GEN, the usual path with drafts) and together in the batch -windows (BGEN), greedy. Every slot's tokens must equal its solo tokens; prints the aggregate decode rate. - - python3 tools/batch_test.py --exe engine/strata --config strata-.json --batch 4 --n 4 \ - --extra "--layer-split 12,24,36 --trim-stage-weights --pcie-frac 0 --adapt-every 1000000" -""" -import argparse, json, os, subprocess, sys, tempfile, threading, time -from pathlib import Path - -sys.path.insert(0, str(Path(__file__).resolve().parent)) -import strata_tokenizer as ST # noqa: E402 - -QUESTIONS = [ - "Explique en detail le fonctionnement d'un B-tree.", - "Write a Python function that merges overlapping intervals, then explain it.", - "Compare TCP and QUIC: handshake, congestion control, multiplexing.", - "Raconte l'histoire du calcul de pi, d'Archimede a nos jours.", - "What are the main causes of the French Revolution?", - "Explain how a transformer's attention works, step by step.", - "Donne une recette de tarte aux pommes, etape par etape.", - "Describe the life cycle of a star like the Sun.", - "Erklaere ausfuehrlich, wie ein Dieselmotor funktioniert.", - "Write a Rust function that parses a CSV line with quoted fields, then explain it.", - "What were the main consequences of the invention of the printing press?", - "Explique le theoreme de Pythagore avec trois demonstrations differentes.", - "Describe how the immune system responds to a viral infection.", - "Explain the difference between processes and threads in an operating system.", - "Beschreibe die Geschichte des Roemischen Reiches in Grundzuegen.", - "How does public-key cryptography work? Give an example with RSA.", -] - -QUESTIONS = QUESTIONS + [q + " Answer in German." for q in QUESTIONS] - - -def tokenizer(path): - t = Path(path) - vocab = json.loads((t / "vocab.json").read_text(encoding="utf-8")) - tokens = [None] * len(vocab) - for s, i in vocab.items(): - tokens[i] = s - merges = (t / "merges.txt").read_text(encoding="utf-8").split("\n") - types = json.loads((t / "token_type.json").read_text()) - return ST.Tokenizer(tokens, merges, types) - - -class Engine: - def __init__(self, exe, cfg, batch, extra_env, extra_args): - args = list(cfg["args"]) - if len(cfg.get("gpu") or []) > 1: - args += ["--layer-split", str(cfg.get("layer_split") or "auto")] - if batch: - args += ["--batch", str(batch)] - args += extra_args - env = dict(os.environ, **extra_env) - env["LD_LIBRARY_PATH"] = ":".join(cfg.get("lib_dirs", []) + [env.get("LD_LIBRARY_PATH", "")]) - if os.name == "nt": - env["PATH"] = os.pathsep.join(cfg.get("lib_dirs", []) + [env.get("PATH", "")]) - self.log_path = os.environ.get("BATCH_TEST_LOG") or os.path.join(tempfile.gettempdir(), "batch_test_engine.log") - self.log = open(self.log_path, "w") - self.p = subprocess.Popen([exe, "--serve", *args], cwd=cfg.get("cwd"), stdin=subprocess.PIPE, - stdout=subprocess.PIPE, stderr=self.log, text=True, bufsize=1, env=env) - for line in self.p.stdout: - if line.startswith("READY"): - return - raise SystemExit(f"the engine ended before READY - see {self.log_path}") - - def send(self, line): - self.p.stdin.write(line + "\n") - self.p.stdin.flush() - - def lines(self): - for line in self.p.stdout: - yield line.rstrip("\n") - - -def main(): - ap = argparse.ArgumentParser() - ap.add_argument("--exe", required=True) - ap.add_argument("--config", required=True) - ap.add_argument("--batch", type=int, default=4) - ap.add_argument("--n", type=int, default=4, help="prompts (<= --batch)") - ap.add_argument("--max-new", type=int, default=64) - ap.add_argument("--skip-solo", action="store_true") - ap.add_argument("--keys", default="", help='sampling keys for every request, e.g. "temperature=0.7 top_k=20"') - ap.add_argument("--extra", default="", help='more engine arguments in one string, e.g. "--adapt-every 1000000"') - ap.add_argument("--dump", default="", help="write every slot's tokens (solo and batch) as JSON: an A/B of two engine builds") - ap.add_argument("--long-tokens", type=int, default=0, - help="the LAST prompt is read from about this many tokens of filler text first: its chunks run " - "beside the earlier slots' windows (the prompt path lends experts then)") - ap.add_argument("--mt-min", default="1", help="STRATA_IQ_MT_MIN for the engine (1: exact; empty: the default)") - a = ap.parse_args() - cfg = json.loads(Path(a.config).read_text()) - tok = tokenizer(cfg["tokenizer"]) - prompts = [] - for q in QUESTIONS[: a.n]: - text = f"<|im_start|>user\n{q}<|im_end|>\n<|im_start|>assistant\n\n\n\n\n" - if a.long_tokens and q is QUESTIONS[a.n - 1]: - para = ("The committee reviewed item %d of the long agenda, noting the budget, the schedule and the open " - "risks, and asked the staff to report back next quarter. ") - per = max(1, len(tok.encode(para % 100))) - filler = "".join(para % i for i in range(a.long_tokens // per + 1)) - text = f"<|im_start|>user\n{filler}\n\n{q}<|im_end|>\n<|im_start|>assistant\n\n\n\n\n" - prompts.append(tok.encode(text, parse_special=True)) - env = {"STRATA_DECODE_TIMING": "1", **({"STRATA_VERIFY_PROFILE": "1"} if os.environ.get("PROF") else {})} - if a.mt_min: - env["STRATA_IQ_MT_MIN"] = a.mt_min - eng = Engine(a.exe, cfg, a.batch, env, a.extra.split()) - out = eng.lines() - - solo = [] - if not a.skip_solo: - for i, ids in enumerate(prompts): - eng.send(" ".join(x for x in ("GEN", str(a.max_new), a.keys, ",".join(map(str, ids))) if x)) - got, t0 = [], time.time() - for line in out: - if line.startswith("T "): - got.append(int(line.split()[1])) - elif line.startswith("DONE") or line.startswith("ERR"): - print(f"solo {i}: {len(got)} tokens in {time.time() - t0:.1f}s {line[:60]}", flush=True) - break - solo.append(got) - - # batch: admit every prompt, then the slots decode together - got = {i: [] for i in range(len(prompts))} - done = {} - t_admit = time.time() - first_bt = None - for i, ids in enumerate(prompts): - eng.send(" ".join(x for x in ("BGEN", str(i), str(a.max_new), a.keys, ",".join(map(str, ids))) if x)) - for line in out: - if line.startswith("T "): - got[i].append(int(line.split()[1])) - elif line.startswith("BT "): - _, s, y = line.split() - got[int(s)].append(int(y)) - first_bt = first_bt or time.time() - elif line.startswith("BDONE "): - done[int(line.split()[1])] = line - elif line.startswith("ERR"): - print("batch:", line) - return 1 - elif line.startswith("BADM "): - if line.split()[2] == "0": - done[i] = line - break - t_admitted = time.time() - for line in out: - if line.startswith("BT "): - _, s, y = line.split() - got[int(s)].append(int(y)) - first_bt = first_bt or time.time() - elif line.startswith("BDONE "): - done[int(line.split()[1])] = line - if len(done) == len(prompts): - break - elif line.startswith("ERR"): - print("batch:", line) - return 1 - t_end = time.time() - total = sum(len(v) for v in got.values()) - print(f"batch: {len(prompts)} slots, {total} tokens; admissions {t_admitted - t_admit:.1f}s; " - f"then {t_end - t_admitted:.1f}s -> aggregate {total / max(t_end - t_admit, 1e-9):.1f} tok/s overall, " - f"{sum(len(v) for v in got.values()) / max(t_end - (first_bt or t_admit), 1e-9):.1f} tok/s from the first batch token", - flush=True) - ok = True - for i in range(len(prompts)): - b = got[i] - if solo: - same = b == solo[i] - ok &= same - first_diff = next((k for k in range(min(len(b), len(solo[i]))) if b[k] != solo[i][k]), None) - print(f"slot {i}: {len(b)} tokens, solo {len(solo[i])}: {'IDENTICAL' if same else f'DIFFERS at {first_diff}'}") - print(" ", ascii(tok.decode(b)[:160])) - if a.dump: - Path(a.dump).write_text(json.dumps({"solo": solo, "batch": [got[i] for i in range(len(prompts))]}), encoding="utf-8") - eng.send("QUIT") - eng.p.wait(timeout=180) # the next run needs the GPUs back - return 0 if ok else 2 - - -if __name__ == "__main__": - sys.exit(main()) From 79e5cd1827b45812394329df1a2e512239454bf0 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Wed, 14 Oct 2026 21:40:11 +0200 Subject: [PATCH 32/33] docs/BATCHING.md: more than 8 slots on a layer split, the opt-in admission and decode switches, and the 4x R9700 numbers (PR #2364 port) --- docs/BATCHING.md | 50 +++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 47 insertions(+), 3 deletions(-) diff --git a/docs/BATCHING.md b/docs/BATCHING.md index 69e5e2f7..0a764d2f 100644 --- a/docs/BATCHING.md +++ b/docs/BATCHING.md @@ -84,15 +84,59 @@ With a layer split, the engine options go into the config's `args`: | Option | What it does | | --- | --- | -| `"parallel": N` / `--batch N` / `--slots N` (2..8 normally) | up to N conversations have batch slots; more requests wait for a free slot. Each slot gets its own state (a session carved like the stage's own: GDN recurrence, QSA K/V and indexer, PLE history) on every GPU of the split. With grouped MTP, more than 8 slots can rotate through eight-row windows if memory permits. | +| `"parallel": N` / `--batch N` / `--slots N` (2..8 normally; with a layer split up to 8 per group, see below) | up to N conversations have batch slots; more requests wait for a free slot. Each slot gets its own state (a session carved like the stage's own: GDN recurrence, QSA K/V and indexer, PLE history) on every GPU of the split. With grouped MTP, more than 8 slots can rotate through eight-row windows if memory permits. | | `--batch-groups G` | with a layer split (default: auto, below): the N slots in G groups that flow through the GPUs as a pipeline (GPU k runs one group while GPU k+1 runs another). G must divide N. 1 = all slots in one window, GPU after GPU. | | `--batch-groups auto` | the default on a layer split since 0.1.41 (give no `--batch-groups`): the engine pipelines one group per GPU stage (the most that divide the slots; 8 slots on 4 GPUs = 4 groups of 2) and says so (`INFO batch_groups=G`). `--batch-groups 1` turns it off (all slots in one window, GPU after GPU). Measured, 8 clients, total tok/s against one group: 4 x R9700 166 against 86, 2 GPUs 109 against 78, 3 GPUs 110 against 78. With `--adapt-async 1` and no `--batch-groups` the default is one group (the adaptive tier between batch windows does not run in pipelined groups) and the log says so; with `--batch-mtp` and no `--batch-groups` the pipeline wins and `--batch-mtp` is left off (`--batch-groups 1` or `STRATA_BATCH_MTP_SERIAL=1` keeps it); `--batch-groups G` or `--batch-groups auto` given with `--batch-mtp` pipelines the groups and turns `--batch-mtp` off, and given with `--adapt-async 1` pipelines the groups and turns `--adapt-async` off (the pipelined path does not adapt). | | `--trim-stage-weights` | with an **explicit** `--layer-split` (e.g. `12,24,36`, not `auto`): every GPU loads only the dense weights of its own layers instead of the whole model's (the same as `STRATA_STAGE_TRIM=1`, PR #639). The VRAM this frees goes to the expert cache. Useful without `--batch` too. | -The engine never refuses a count it cannot run: it says so in its log and runs what it can - at most 8 slots by -default (a window holds 8 rows), as many as fit in VRAM, or none (one request at a time) when not two fit. The server reads +The engine never refuses a count it cannot run: it says so in its log and runs what it can - at most 8 slots without a +layer split (a window holds 8 rows; with a layer split and pipelined groups, 8 per group), as many as fit in VRAM, or none (one request at a time) when not two fit. The server reads the count the engine reports (`INFO batch_slots=N`), and `GET /v1/status` says it (`concurrency.serving`). +## More than 8 slots on a layer split, and the opt-in admission and decode switches + +(From havok2-htwo's patch series, PR #2364.) + +**More than 8 slots.** With a layer split a pipelined window holds at most 8 rows, but each group of the pipeline is its +own window, so `--batch 16` on 4 GPUs runs 4 groups of 4 slots (`--batch-groups auto`), `--batch 32` runs 4 groups of 8. +Until 0.1.44.1 the engine cut such a request down to 8 slots and said so; it now runs what is asked for, as many slots +as fit in VRAM and at most 8 per group (`INFO batch_slots=N`). `--batch-mtp` keeps its limit (rows per window are +doubled by the proposals). Nothing changes for 8 slots or fewer. Every slot of a 16-slot pipelined batch decodes +exactly the tokens it decodes alone (`tools/batch_test.py --n 16`, which now takes up to 32 prompts). + +**Opt-in switches** (environment of the engine, i.e. `"env"` in the config; none is on by default). Each one changes +how the work is scheduled or copied, not what is computed; the identity gates and `tools/batch_test.py` are in +`phaseA-tests/review-havok.md`. + +| Switch | What it does | +|---|---| +| `STRATA_SLOT_COPY_DIRECT=1` | an admission (and a slot's resume) copies the running state and the QSA K/V device to device, instead of through host images | +| `STRATA_SLOT_COPY_BATCHSYNC=1` | with the above: queue the ~116 copies and synchronize each device once | +| `STRATA_SLOT_CKPT_MOVE=1` | the admission's turn checkpoint moves into the slot (no 112 MB copy); it also keeps the dropped checkpoints' storage, as `STRATA_CKPT_POOL` does; a session SAVE or parked conversation taken right after an admission lacks the moved checkpoint (the slot holds it) | +| `STRATA_CKPT_POOL=1`, `STRATA_CKPT_THREADS=1` | a checkpoint is saved into the vectors of a dropped one; a split's stage parts are saved at once | +| `STRATA_ADMIT_MERGE_FIRST=1` | an admission reads its last prompt tokens and its first token in one window (all experts resident only) | +| `STRATA_PIPE_BYIELD_NODRAIN=1` | a BYIELD that reaches a pipelined batch is dropped without draining the groups | +| `STRATA_BATCH_SELF_COMMIT=1` | a one-row-per-slot window advances the GDN state itself, no commit graph | +| `STRATA_QSA_SLOTS=1` | a window's QSA block scores, top-k and attention run as one launch over its rows | +| `STRATA_HANDOFF_PIPE=P` | a layer split hands a prompt chunk to the next card in P pieces (2..16), gated by events, on a persistent thread | +| `STRATA_ADMIT_SHORT_FIRST=N` (server) | a new prompt of at most N tokens takes the control lines before longer ones (a longer one that waited `STRATA_ADMIT_MAX_WAIT_S`, default 30, counts as short) | +| `STRATA_TRACE=1` | one line per admission with its phases (drain, prompt, first window, slot copy, checkpoint copy) | +| `STRATA_MMQ_DIRECT=1`, `STRATA_MMQ_GROUP_SORT=1` | CUDA, needs the build option `-DSTRATA_MMQ_TAB=ON`: the prompt MMQ reads resident experts in their cache slots; full MMQ groups sorted by row count (docs/DETAILS.md) | + +Measured (4x R9700 32 GB, HIP, IQ3_S all experts resident, layer split 12,25,37, 3 interleaved rounds per arm, 0.1.44.1 +with 8 slots against the same build with 16 slots and the switches above; aggregate output tok/s, TTFT p50 in seconds): + +| users (prompt) | 0.1.44.1, 8 slots | 16 slots, no switch | 16 slots, all switches | +|---|---|---|---| +| 8 (147 tokens) | 209 / 2.70 s | 209 / 2.72 s | 251 / 1.82 s | +| 16 (147 tokens) | 208 / 20.6 s | 252 / 5.4 s | 324 / 2.0 s | +| 16 (1.2K tokens) | 145 / 23.9 s | 167 / 10.6 s | 204 / 5.3 s | +| 16 agents x 3 turns, follow-up TTFT | 50 tok/s / 21.2 s | 53 / 7.1 s | 56 / 5.7 s | + +One user alone is unchanged (73-74 tok/s). Each slot's session takes VRAM from the expert cache, so on a card or split +where the experts do not all fit, 16 slots cost the single-user speed (see docs above on what a slot costs). + + ### What a slot costs, and what setup recommends Every slot's session takes VRAM that the expert cache would otherwise hold: 0.56 GiB at a 32K context with 8-bit From 8e2c70a1323eff92a21a3ea3539857e2ea41873d Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Wed, 14 Oct 2026 21:42:05 +0200 Subject: [PATCH 33/33] metal: STRATA_QSA_SLOTS launchers decline (no Metal kernel); the shared verify.cpp links again --- metal/src/engine/stubs_144.cpp | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/metal/src/engine/stubs_144.cpp b/metal/src/engine/stubs_144.cpp index f4750d37..a4a151b7 100644 --- a/metal/src/engine/stubs_144.cpp +++ b/metal/src/engine/stubs_144.cpp @@ -11,6 +11,8 @@ #include "strata/kernels/cpu/nvfp4_avx512.hpp" #include "strata/kernels/iq_kernels.hpp" #include "strata/kernels/native_qsa_indexer.hpp" +#include "strata/kernels/qsa_decode_attn.hpp" +#include "strata/kernels/qsa_select.hpp" #include "strata/kernels/verify_kernels.hpp" #include "strata/prefill/kernels.hpp" @@ -51,3 +53,12 @@ void nvfp4_512_rows(const uint8_t*, size_t, int, const void* const*, int, float* strata::metal_engine::missing("strata::kernels::cpu::nvfp4_512_rows"); } } // namespace strata::kernels::cpu + +// STRATA_QSA_SLOTS (PR #2364): the one-launch-over-the-rows QSA launchers have no Metal kernel; false = "run the per-row calls", +// which is what Verifier::record_window does on a decline. +namespace strata::kernels { +bool qsa_block_scores_slots(const float* const*, const float* const*, const float*, const int32_t*, int64_t, int64_t, + const QsaShapes&, float*, void*) { return false; } +bool qsa_decode_attn_slots(const float*, const QsaAttnSlotPools&, const int32_t*, const int32_t*, int64_t, const QsaShapes&, + float*, float*, int64_t, void*) { return false; } +} // namespace strata::kernels