From 481b69246f70e1c44a6c65a85ee5473e3c199985 Mon Sep 17 00:00:00 2001 From: Pravesh Khatana Date: Wed, 30 Sep 2026 12:36:50 +0530 Subject: [PATCH 01/32] fix(engine): clear stale error/cancellation state between requests and before prompt prefill When a request is cancelled during prompt reading (e.g. client disconnect or timeout), err is set to 'cancelled'. Because err is declared in main() and was never cleared between requests, any subsequent request in v0.1.26+ evaluated 'if (!e.empty())' in sp.on_chunk on its first chunk, immediately failing with 'strata serve: cancelled' and terminating the engine with code 1. Clearing err at the start of each request, before prompt segment runs, and on entry to Prefill::run prevents state pollution across requests. --- src/prefill/prefill.cpp | 1 + src/program/generate.cpp | 2 ++ 2 files changed, 3 insertions(+) diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index 2dcdb543..6731b3c8 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -927,6 +927,7 @@ struct PfTimer { } // namespace bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& err) { + err.clear(); Impl& m = *impl_; const core::OnDevice on_device(m.device); const core::ModelGeometry& g = *m.g; diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 0bbc92e0..3b0bba44 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -3559,6 +3559,7 @@ int main(int argc, char** argv) { ~BusyScope() { strata::core::progress().busy.store(false); strata::core::progress_at("idle"); } } busy_scope; stop_req.store(false); // a STOP that arrived between requests is stale + err.clear(); const bool geni = line.rfind("GENI ", 0) == 0; if (!geni && line.rfind("GEN ", 0) != 0) { std::printf("ERR expected: GEN or GENI \n"); @@ -3976,6 +3977,7 @@ int main(int argc, char** argv) { int64_t at = read_from; for (const int64_t to : {reread_to, root_at, turn_at, n - 1}) { if (to <= at) continue; + err.clear(); const bool win = windows_ok(at, to); if (win && !refill(err)) { std::printf("ERR refilling a lent slot failed: %s\n", err.c_str()); From 0425829226f327fcc2ffbf2e34d08eb0e2078ccf Mon Sep 17 00:00:00 2001 From: GioStrives Date: Wed, 30 Sep 2026 09:11:34 +0200 Subject: [PATCH 02/32] verify: cudaFuncGetName only with CUDA 12.3+ (an sm_75 build with CUDA 12.0 failed) It names kernels only for the STRATA_VERIFY_NODES debug dump. --- src/core/verify.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/core/verify.cpp b/src/core/verify.cpp index 54df72b4..3422127f 100644 --- a/src/core/verify.cpp +++ b/src/core/verify.cpp @@ -850,8 +850,10 @@ bool Verifier::capture(int T, std::string& err) { if (ty == cudaGraphNodeTypeKernel) { cudaKernelNodeParams kp{}; if (cudaGraphKernelNodeGetParams(nd, &kp) == cudaSuccess) { +#if CUDART_VERSION >= 12030 // cudaFuncGetName arrived in CUDA 12.3 const char* fn = nullptr; if (cudaFuncGetName(&fn, kp.func) == cudaSuccess && fn) name = fn; +#endif } } else if (ty == cudaGraphNodeTypeMemcpy) name = "memcpy"; else if (ty == cudaGraphNodeTypeMemset) name = "memset"; From 7980d3719fb4048e8ca10f57a2ae3a7649b975a6 Mon Sep 17 00:00:00 2001 From: Oluwabori Olaleye <40204337+borexola@users.noreply.github.com> Date: Wed, 30 Sep 2026 10:46:55 +0200 Subject: [PATCH 03/32] Expert cache on WDDM: 1 GiB steps before quarter steps (~4 GiB more cache on a 32 GB card); Ctrl+C stops the server on Windows; no stack trace when a client hangs up (#153) Squashed from PR #153. --- serve/server.py | 24 ++++++++++++++++-------- setup.py | 2 +- src/program/generate.cpp | 7 +++++-- 3 files changed, 22 insertions(+), 11 deletions(-) diff --git a/serve/server.py b/serve/server.py index cb261765..f35ca86d 100644 --- a/serve/server.py +++ b/serve/server.py @@ -1501,6 +1501,10 @@ class Server(ThreadingHTTPServer): # either one (a forgotten second start of run-.bat). Without it the second start fails loudly instead. allow_reuse_address = os.name != "nt" + def handle_error(self, request, client_address): + if not isinstance(sys.exc_info()[1], ConnectionError): # a client that hangs up needs no stack trace + super().handle_error(request, client_address) + def warn_tight_ram(arena_mib) -> None: """The model's experts live in RAM (INFO arena_mib, engine 0.1.10+). With less than ~6 GB left beside them for the @@ -1768,15 +1772,19 @@ def main() -> int: import webbrowser webbrowser.open(f"http://{'127.0.0.1' if a.host in ('0.0.0.0', '') else a.host}:{a.port}/") try: - threading.Event().wait() + while True: + time.sleep(1) # Windows never delivers Ctrl+C to an untimed Event.wait() except KeyboardInterrupt: - httpd.shutdown() - if hasattr(engine, "close"): - engine.close() - if vision: - vision.close() - if hub is not None: - hub.close() + print("\n[strata] stopping (Ctrl+C again to end the engine at once) ...", flush=True) + closers = [httpd.shutdown, getattr(engine, "close", None), vision.close if vision else None, + hub.close if hub is not None else None] + for close in filter(None, closers): + try: + close() + except KeyboardInterrupt: # a second Ctrl+C: don't wait for the engine to free its memory + if getattr(engine, "proc", None): + engine.proc.kill() + print("[strata] stopped", flush=True) return 0 diff --git a/setup.py b/setup.py index 0c30e244..be3f2f83 100644 --- a/setup.py +++ b/setup.py @@ -1531,7 +1531,7 @@ def write_run_script(model, cfg_path, port): if WIN: script = ROOT / f"run-{model.lower()}.bat" script.write_text("@echo off\r\ntitle Strata " + model + "\r\ncd /d \"" + str(ROOT) + "\"\r\n" + - " ".join(f'"{x}"' for x in serve) + "\r\npause\r\n", encoding="utf-8") + " ".join(f'"{x}"' for x in serve) + "\r\nif errorlevel 1 pause\r\n", encoding="utf-8") else: script = ROOT / f"run-{model.lower()}.sh" script.write_text("#!/bin/sh\ncd \"" + str(ROOT) + "\"\nexec " + " ".join(f'"{x}"' for x in serve) + "\n", diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 3b0bba44..9a93edd3 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -2064,6 +2064,7 @@ int main(int argc, char** argv) { // STRATA_TEST_CACHE_FAIL=N: the first N opens fail as an out-of-commit cudaMalloc does (tests the retry) int fake_fails = std::getenv("STRATA_TEST_CACHE_FAIL") ? std::atoi(std::getenv("STRATA_TEST_CACHE_FAIL")) : 0; int failed = 0; + int zero_reads = 0; for (int attempt = 0;; ++attempt) { bool ok = false; if (fake_fails > 0) { @@ -2107,9 +2108,11 @@ int main(int argc, char** argv) { cudaMemGetInfo(&free_b, &total_b); const int64_t want = (int64_t) o.vram_reserve_mib << 20; if ((int64_t) free_b >= want - (64ll << 20)) break; - // short by (want - free); a figure of 0 only says "at least", so then give back a quarter as well + // short by (want - free); a figure of 0 only says "at least": the first two such reads give back 1 GiB + // each (under WDDM the free figure read before the allocation runs ~0.7 GiB high), later ones a quarter int64_t give = want - (int64_t) free_b + (64ll << 20); - if (free_b < ((size_t) 16 << 20)) give = std::max(give, xcache.bytes() / 4); + if (free_b < ((size_t) 16 << 20)) + give = std::max(give, ++zero_reads <= 2 ? 1ll << 30 : xcache.bytes() / 4); const int64_t keep_bytes = xcache.bytes() - give; std::fprintf(stderr, "strata generate: only %lld MiB free once the slots are written (reserve %d MiB); " "shrinking the expert cache\n", (long long) (free_b >> 20), o.vram_reserve_mib); From eef241178c936e3fee33c281e36fe14927aebf51 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Wed, 30 Sep 2026 10:54:45 +0200 Subject: [PATCH 04/32] engine: the expert cache reserves the draft head's VRAM (0.1.27's CJK subset came out of the 700 MiB reserve, #199); a clear message when no VRAM is left for the cache (#174); the prompt's verify-window stage has its own label (#217) --- include/strata/core/mtp.hpp | 3 +++ src/core/mtp.cpp | 13 +++++++++++++ src/core/verify.cpp | 3 ++- src/program/generate.cpp | 15 ++++++++++++--- 4 files changed, 30 insertions(+), 4 deletions(-) diff --git a/include/strata/core/mtp.hpp b/include/strata/core/mtp.hpp index 6df843ba..2224060e 100644 --- a/include/strata/core/mtp.hpp +++ b/include/strata/core/mtp.hpp @@ -53,6 +53,9 @@ public: /// KV streaming: refill the ring of the drafter's window from its host copy for a sequence that continues at /// `upto` (a conversation-cache resume). No-op unless the drafter's K/V is a ring. void kv_restore(int64_t upto); + /// The VRAM bind() will allocate for a native head of `head_row_bytes` per vocabulary row: the draft logits and + /// the draft head over rt/draft_vocab.bin's subset. The expert cache is sized before bind(), so it reserves this. + uint64_t bind_bytes(uint64_t head_row_bytes, int64_t n_vocab) const; /// The main model's embedding and head, and the verify window's final residuals (T rows, hc*n_embd each). bool bind(const WeightTable& wt, const NativeHead* head, const float* window_R, std::string& err); diff --git a/src/core/mtp.cpp b/src/core/mtp.cpp index 11d16f79..2b1d79ef 100644 --- a/src/core/mtp.cpp +++ b/src/core/mtp.cpp @@ -292,6 +292,19 @@ bool MtpDrafter::load(const std::string& rt_dir, const ModelGeometry& g, Session return true; } +uint64_t MtpDrafter::bind_bytes(uint64_t head_row_bytes, int64_t n_vocab) const { + uint64_t bytes = head_logits_ ? 0 : (uint64_t) max_t_ * (uint64_t) n_vocab * sizeof(float); + if (dhead_ == nullptr) { + if (FILE* f = std::fopen((rt_dir_ + "/draft_vocab.bin").c_str(), "rb")) { + std::fseek(f, 0, SEEK_END); + const long size = std::ftell(f); + std::fclose(f); + if (size >= 4 && size % 4 == 0) bytes += (uint64_t) (size / 4) * head_row_bytes + (uint64_t) size; + } + } + return bytes; +} + bool MtpDrafter::bind(const WeightTable& wt, const NativeHead* head, const float* window_R, std::string& err) { const OnDevice on_device(device_); wt_ = &wt; diff --git a/src/core/verify.cpp b/src/core/verify.cpp index 3422127f..085135a9 100644 --- a/src/core/verify.cpp +++ b/src/core/verify.cpp @@ -148,7 +148,8 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState& return false; } if (hits.d_res == nullptr || hits.cache_base == nullptr || hits.blob <= 0) { - err = "verify: needs the profile-filled VRAM expert tier (--expert-profile and --expert-cache)"; + err = "verify: needs the profile-filled VRAM expert tier (--expert-profile and --expert-cache); with " + "--expert-cache auto, no VRAM was left for it: lower --max-context, use --kv k8v4 or images on the CPU"; return false; } std::string why; diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 9a93edd3..3b091eb2 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -1993,12 +1993,20 @@ int main(int argc, char** argv) { // (with borrowing - the default with a profile - the prompt path lends cache slots instead) const bool borrow = !o.no_prefill_borrow && !o.expert_profile.empty(); const int64_t prefill_mib = (o.prefill_chunk > 0 && !borrow) ? 160 + (o.prefill_chunk * 680) / 1024 : 0; - const int64_t reserve = ((int64_t) o.vram_reserve_mib + prefill_mib) << 20; + // the draft layer's head and logits are allocated when it binds, after this: 0.1.27's CJK subset made them + // ~110-180 MiB larger, and out of the reserve they left 16 GB cards below the stall line (#199) + const int64_t mtp_bind = (!o.mtp.empty() && native_head.loaded()) + ? (int64_t) mtp.bind_bytes(native_head.row_bytes(), n_vocab) : 0; + const int64_t reserve = (((int64_t) o.vram_reserve_mib + prefill_mib) << 20) + mtp_bind; int64_t slots = ((int64_t) free_b - reserve) / (int64_t) strata::kernels::cpu::expert_layout().max_blob; if (!profile.empty()) slots = std::min(slots, (int64_t) profile.size()); o.expert_cache = (int) std::max(slots, 0); - std::fprintf(stderr, "strata generate: expert cache auto: %.2f GiB free, %d MiB reserved -> %d slots\n", - (double) free_b / 1073741824.0, o.vram_reserve_mib, o.expert_cache); + std::fprintf(stderr, "strata generate: expert cache auto: %.2f GiB free, %d MiB reserved (+%lld MiB for the " + "draft head) -> %d slots\n", + (double) free_b / 1073741824.0, o.vram_reserve_mib, (long long) (mtp_bind >> 20), o.expert_cache); + if (o.expert_cache == 0) // the verify window cannot start without it (#174): say what makes room + std::fprintf(stderr, "strata generate: no VRAM is left for the expert cache: lower --max-context, use " + "--kv k8v4, run images on the CPU, or close other programs that use the GPU\n"); } else if (multi_gpu && o.expert_cache > 0) { // a layer split's prompt path has its own buffers (it borrows no slots): an explicit cache size leaves room // for them and the reserve, or the first prompt fails with "device buffers ... do not fit" @@ -3848,6 +3856,7 @@ int main(int argc, char** argv) { }; // tokens [a, b) through the windows: commit all of them, then give the draft layer their residuals auto read_windows = [&](int64_t a, int64_t b, std::string& e) -> bool { + strata::core::progress_at("reading the prompt (verify windows), from token", a); // #217: not "batched" // every token is committed and the picks are discarded: no head sampling (see set_head_sampling) struct NoHeadSampling { strata::core::Verifier& v; From fa59b3f3a9a993f6cf9b16c958d5a81084b2763e Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Wed, 30 Sep 2026 10:54:45 +0200 Subject: [PATCH 05/32] server: /status needs the API key and forgets the answer's end (#212); constant-time key check, an explicitly empty key refuses to start (#213); an engine exit quotes its last log line (#215); tool calls end at their own and , so values may contain them (#210) --- serve/frontend.py | 72 +++++++++++++++++++++++++++++++++++++++----- serve/server.py | 18 ++++++++++- serve/test_server.py | 55 +++++++++++++++++++++++++++++++++ 3 files changed, 136 insertions(+), 9 deletions(-) diff --git a/serve/frontend.py b/serve/frontend.py index 670bcfbe..23144e40 100644 --- a/serve/frontend.py +++ b/serve/frontend.py @@ -242,6 +242,61 @@ CALL_START = "" CALL_END = "" +PARAM_END = "" +FUNC_END = "" + + +def param_end(text: str, final: bool = False) -> int: + """Where a parameter value in `text` ends: the first `` followed (after whitespace) by the next + `` - the same text inside a value (a file that documents the call format, #210) is + part of the value. -1: none yet; -2: a candidate whose follower has not arrived (streaming; `final` accepts it).""" + at = text.find(PARAM_END) + while at >= 0: + after = text[at + len(PARAM_END):].lstrip() + if after.startswith(("` after the call's own ``, found by walking + its parameters with param_end, so a value may contain either tag. -1: not complete yet. A body that is not in + the call format ends at the first ``, as before.""" + s = text.lstrip() + pos = len(text) - len(s) + if not s.startswith("", pos) + if gt < 0: + return -1 + pos = gt + 1 + while True: + rest = text[pos:] + s = rest.lstrip() + pos += len(rest) - len(s) + if s.startswith("", pos) + if gt < 0: + return -1 + end = param_end(text[gt + 1:]) + if end < 0: + return -1 + pos = gt + 1 + end + len(PARAM_END) + elif s.startswith(FUNC_END): + rest = text[pos + len(FUNC_END):] + s = rest.lstrip() + if s.startswith(CALL_END): + return pos + len(FUNC_END) + len(rest) - len(s) + return -1 if CALL_END.startswith(s) else text.find(CALL_END, pos) + elif not s or " ToolCall: """`\\n\\nVALUE\\n...` -> ToolCall. Values are JSON-decoded when the tool's schema says the parameter is not a string (or, without a schema, when they parse as JSON @@ -257,9 +312,9 @@ def parse_tool_call(body: str, schema: dict | None = None) -> ToolCall: rest = rest[rest.index("")] rest = rest[rest.index(">") + 1:] - end = rest.find("") + end = param_end(rest, final=True) value = rest[:end] if end >= 0 else rest - rest = rest[end + len(""):] if end >= 0 else "" + rest = rest[end + len(PARAM_END):] if end >= 0 else "" if value.startswith("\n"): value = value[1:] if value.endswith("\n"): @@ -351,16 +406,17 @@ class OutputParser: self.sp += 1 rest = rest[1:] self.sval_started = True - end = rest.find("") + end = param_end(rest) if end >= 0: value = rest[:end] if value.endswith("\n"): value = value[:-1] args(json.dumps(value)[1:-1] + '"') - self.sp += end + len("") + self.sp += end + len(PARAM_END) self.ss = "between" continue - safe = len(rest) - self._hold(rest, ("",)) + # an undecided (-2) is held from its start, like a tag still arriving + safe = rest.find(PARAM_END) if end == -2 else len(rest) - self._hold(rest, (PARAM_END,)) if safe > 0 and rest[safe - 1] == "\n": # may be the trailing newline before safe -= 1 if safe > 0: @@ -368,7 +424,7 @@ class OutputParser: self.sp += safe return out elif self.ss == "raw": - end = rest.find("") + end = param_end(rest) if end < 0: return out value = rest[:end] @@ -381,7 +437,7 @@ class OutputParser: except ValueError: v = value args(json.dumps(v, ensure_ascii=False)) - self.sp += end + len("") + self.sp += end + len(PARAM_END) self.ss = "between" else: return out @@ -449,7 +505,7 @@ class OutputParser: self.buf = self.buf[i + len(CALL_START):] self.state = "call" else: - i = self.buf.find(CALL_END) + i = call_end(self.buf) if self.stream_tools: if i >= 0: whole, self.buf = self.buf, self.buf[:i] # scan only the body diff --git a/serve/server.py b/serve/server.py index f35ca86d..89b88b59 100644 --- a/serve/server.py +++ b/serve/server.py @@ -24,6 +24,7 @@ import argparse import collections import base64 import hashlib +import hmac import codecs import json import os @@ -216,6 +217,11 @@ class StrataEngine: if "issue #29" in line: return ("The engine stopped itself because it had stopped making progress - a hang it caught. Its log " "line: " + line.strip() + " - please report it at github.com/Niko1221/Strata/issues.") + rc = self.proc.poll() + last = next((x.strip() for x in reversed(tail.splitlines()) if x.strip().startswith(("strata", "ERR"))), "") + if rc is not None and rc >= 0 and last: # it ended by itself: its own last words say why (#215) + return (f"The engine exited (code {rc}). Its last log line: {last} - if that does not explain it, please " + "report it at github.com/Niko1221/Strata/issues with the log.") return ("The usual cause is running out of RAM: Linux then ends the biggest program (check: sudo dmesg | " "grep -i -E 'killed process|out of memory'); Windows slows down instead. Close other programs or use a " "smaller model (Q2_0 / IQ2_XS).") @@ -914,6 +920,8 @@ class Service: if os.environ.get("STRATA_DEBUG") and raw_ids: print(f"[strata] raw: {self.tok.decode(raw_ids)!r}", flush=True) self.status["busy"] = False + self.status.pop("tail", None) # #212: the answer's end is not kept once it is done + self.status.pop("tool", None) for ev in parser.finish(): yield "event", ev yield "done", {"finish": finish, "completion_tokens": n, "reused": (timings or {}).get("cache_n", 0), @@ -1245,7 +1253,7 @@ def make_handler(svc: Service): return True auth = self.headers.get("Authorization", "") given = auth[7:].strip() if auth.lower().startswith("bearer ") else self.headers.get("x-api-key", "") - if given == svc.api_key: + if hmac.compare_digest(given.encode(), svc.api_key.encode()): # #213: constant-time return True self._json(401, {"error": {"type": "authentication_error", "message": "missing or wrong API key"}}) return False @@ -1310,6 +1318,8 @@ def make_handler(svc: Service): self._json(200, {"status": "ok", "max_context": svc.engine.max_context, "model": svc.model, "images": svc.vision is not None, "api_key": bool(svc.api_key)}) elif path == "/status": + if not self._authorized(): # #212: it shows the end of the last answer + return with svc.status_lock: s = dict(svc.status) now = time.time() @@ -1728,6 +1738,12 @@ def main() -> int: model_name=cfg.get("model_name", "qwen3.8-flash-next"), vision=vision, sampling_defaults=sampling_defaults, fit_max_tokens=a.fit_max_tokens or cfg.get("fit_max_tokens") is True) + if ("STRATA_API_KEY" in os.environ and not os.environ["STRATA_API_KEY"].strip()) or any(x == "--api-key" and i + 1 < len(sys.argv) and not sys.argv[i + 1].strip() or x.strip() == "--api-key=" + for i, x in enumerate(sys.argv)): + # #213: an empty key would switch authentication off without a word + print("[strata] an API key was given but it is empty: set a key, or leave --api-key / STRATA_API_KEY out", + file=sys.stderr) + return 2 svc.api_key = a.api_key or cfg.get("api_key", "") svc.gpu_index = (gpu_list(cfg) or [0])[0] # the Monitor reads the card the engine runs on (issue #51) svc.gpu_indices = gpu_list(cfg) # ... or every card of a layer split (issue #112) diff --git a/serve/test_server.py b/serve/test_server.py index 4320e726..b3f70c55 100644 --- a/serve/test_server.py +++ b/serve/test_server.py @@ -196,6 +196,61 @@ class ImageMarkers(unittest.TestCase): svc.embeddings.path.unlink(missing_ok=True) +class StatusNeedsTheKey(unittest.TestCase): + """#212: /status shows the end of the answer being written, so it needs the key like /v1/*.""" + + def test_status(self): + tok = ByteTokenizer() + svc = Service(MockEngine(tok, "ok", max_context=CTX), tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) + svc.api_key = "k3y" + httpd = serve(svc, port=0) + base = f"http://127.0.0.1:{httpd.server_address[1]}/status" + try: + with self.assertRaises(urllib.error.HTTPError) as e: + urllib.request.urlopen(base, timeout=10) + self.assertEqual(e.exception.code, 401) + e.exception.close() + req = urllib.request.Request(base, headers={"Authorization": "Bearer k3y"}) + with urllib.request.urlopen(req, timeout=10) as r: + self.assertEqual(r.status, 200) + self.assertNotIn("tail", json.loads(r.read())) + finally: + httpd.shutdown() + httpd.server_close() + + +class ToolCallTerminators(unittest.TestCase): + """#210: a value that contains or (a file documenting the call format) is kept whole.""" + CONTENT = ("Close each value with and the call with .\n" + "\nnot a parameter\n\nend") + SCHEMA = [{"name": "write", "parameters": {"properties": {"path": {"type": "string"}, + "content": {"type": "string"}}}}] + + def run_parser(self, stream_tools, step): + from serve.frontend import OutputParser + text = ("\n\n\n\n\ndoc.md\n\n" + f"\n{self.CONTENT}\n\n\n") + p = OutputParser(thinking=True, tools=self.SCHEMA, stream_tools=stream_tools) + evs = [] + for i in range(0, len(text), step): + evs += p.feed(text[i:i + step]) + evs += p.finish() + return evs + + def test_values_keep_the_terminators(self): + for stream_tools in (False, True): + for step in (1, 7, 10_000): + with self.subTest(stream_tools=stream_tools, step=step): + evs = self.run_parser(stream_tools, step) + calls = [e.call for e in evs if e.kind == "tool_call"] + self.assertEqual(len(calls), 1) + self.assertEqual(calls[0].arguments, {"path": "doc.md", "content": self.CONTENT}) + self.assertFalse([e for e in evs if e.kind == "content" and e.text.strip()]) + if stream_tools: + streamed = "".join(e.text for e in evs if e.kind == "tool_args") + self.assertEqual(json.loads(streamed), {"path": "doc.md", "content": self.CONTENT}) + + class ClientShapes(unittest.TestCase): """What real clients send: Claude Code posts /v1/messages?beta=true (issue #55) and puts hook context into the conversation as a mid-conversation system message (issue #56); some OpenAI clients send a late developer message.""" From 75e6efeb779c0f26a7a4b586cbed8aaec262ec92 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Wed, 30 Sep 2026 10:54:45 +0200 Subject: [PATCH 06/32] setup: --host/--api-key/--draft-vocab on a start are kept for the model (#179); --draft-vocab en keeps the English/code subset (~110 MiB less VRAM); CUDA 13.0 for RTX 50 builds (#220); llama.cpp's web UI is not unpacked (Windows path limit, #206); Swift Q2_0 hidden (#171); the earlier data folder and nested Strata-data move into --data-dir (#198); whole shards without a finish mark count (#173) --- data/draft_vocab_en.bin | Bin 0 -> 162100 bytes setup.py | 85 ++++++++++++++++++++++++++++++++-------- 2 files changed, 69 insertions(+), 16 deletions(-) create mode 100644 data/draft_vocab_en.bin diff --git a/data/draft_vocab_en.bin b/data/draft_vocab_en.bin new file mode 100644 index 0000000000000000000000000000000000000000..c588b567f6e35fac0e9472a0772d2d03898a93ef GIT binary patch literal 162100 zcmWjM(-I)t5(LmYwr$(CZQHhO+qP}nwr$(?%w6YUeL_X=h_1@~-~ayizW@Xz5P=Co zP=XPh5QHQYp$S7+!V#VbL?jZCi9%GO5uF&sBo?uWLtNq!p9CZ%5s67cQj(FJ6r>~- zsYydx(vhAFWF!-r$wF4Lk)0gmBp12KLtgTcp8^!55QQm1QHoKV5|pGAr71&M%2A#Q zRHPD>sX|q%QJosp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GINE = (0, 1, 27) # v0.1.27: RTX 20 (sm_75) in the ready-ma PY_PACKAGES = ["numpy", "jinja2", "regex", "pyyaml", "tqdm", "requests", "cmake", "ninja", "pillow", "psutil"] MODELS = { - "Q2_0": {"about": "2-bit, the fastest", "download_gb": 66.4, "ram_gb": 48, "arena_gb": 34.0}, + # the original model only for now: Swift 1.5's Q2_0 files split one layer's experts across the two shards, which + # the pack tool (tools/iq_pack.py) cannot prepare yet (#171) + "Q2_0": {"about": "2-bit, the fastest", "download_gb": 66.4, "ram_gb": 48, "arena_gb": 34.0, "families": ("qwen",)}, "IQ2_XS": {"about": "2-bit i-quant, a little better quality, close in speed", "download_gb": 68.0, "ram_gb": 48, "arena_gb": 35.5}, "IQ3_XXS": {"about": "3-bit i-quant, better quality, slower (more CPU work per token)", "download_gb": 75.8, @@ -607,6 +609,18 @@ def download(url, dst: Path, what=None): ok(f"{what or dst.name} downloaded") +def whole_shard(s: Path) -> bool: + """A shard as long as its own tensor directory says (check_shards' test, without stopping setup).""" + sys.path.insert(0, str(ROOT / "tools")) + from gguf_reader import GGUFFile + try: + g = GGUFFile(s) + return s.stat().st_size >= g.data_start + max((t.offset + (t.expected_bytes() or 0) for t in g.tensors), + default=0) + except (OSError, ValueError, struct.error): + return False + + def check_shards(shards): """Every shard present and whole, or setup stops naming the file and the numbers. Whole means as long as its own tensor directory says (the header is read, the data is not): a truncated copy (--gguf-dir, a .part @@ -638,7 +652,9 @@ def get_llama_cpp(): tmp = ROOT / "third_party" / "_unpack" shutil.rmtree(tmp, ignore_errors=True) with zipfile.ZipFile(z) as f: - f.extractall(tmp) + # llama.cpp's own web UI (tools/ui) is not used, and its deep paths passed Windows' 260-character limit in a + # folder like Downloads\Strata-main\Strata-main (#206) + f.extractall(tmp, [m for m in f.namelist() if "/tools/ui/" not in m]) top = next(tmp.iterdir()) shutil.rmtree(llama, ignore_errors=True) # PR #63: on Windows a rename can fail with PermissionError while an antivirus scanner still holds a file of the @@ -948,7 +964,8 @@ def update_installed_engine(url_base) -> None: def install_build_tools(gpu, yes): """The compiler and the CUDA toolkit, installed for the user (asks once). Returns (nvcc, vcvars).""" nvcc, cuda_v = find_nvcc() - need_cuda = (12, 8) if max(int(x) for x in gpu.get("archs", [gpu["arch"]])) >= 120 else (12, 0) + # RTX 50 (sm_120): CUDA 13.0 - an engine built with 12.8 crashed in the prompt path on Linux (#220) + need_cuda = (13, 0) if max(int(x) for x in gpu.get("archs", [gpu["arch"]])) >= 120 else (12, 0) vcvars = find_vcvars() if WIN else None have_cc = vcvars is not None if WIN else shutil.which("g++") is not None missing = [] @@ -1243,7 +1260,18 @@ def data_folder(requested: str | None) -> tuple: warn(f"cannot use {dest} for the model files ({e}): keeping them in {ROOT}") dest = ROOT elsewhere = [] - for folder in [ROOT, *other_installs(settings)]: + # #198: the data folder remembered before (a --data-dir to a new place) is a source too, and so is a Strata-data + # folder nested in any of them (an install that kept its models one level down) + sources = [ROOT, *other_installs(settings)] + if settings.get("data_dir") and Path(settings["data_dir"]) != dest: + sources.append(Path(settings["data_dir"])) + sources += [f / "Strata-data" for f in list(sources) if (f / "Strata-data") != dest] + seen = set() + for folder in sources: + key = os.path.normcase(str(folder)) + if key in seen: + continue + seen.add(key) if folder == dest or not has_data(folder): continue if not same_drive(folder, dest): @@ -1416,14 +1444,21 @@ def upgrade_config(cfg_path: Path, cfg: dict) -> dict: def start(cfg_path: Path, port: int | None, gpu: int | list | None = None, open_browser=True, yes=False, - layer_split=None) -> int: + layer_split=None, keep=None) -> int: + """keep: settings given on this start that the model keeps from now on (--host, --api-key, --draft-vocab).""" cfg = upgrade_config(cfg_path, json.loads(cfg_path.read_text(encoding="utf-8-sig"))) missing = [p for p in [cfg["exe"], *[a for a in cfg["args"] if a.endswith(".gguf")]] if not Path(p).exists()] if missing: fail(f"{cfg_path.name} refers to missing files: {missing[0]}", "run it again with --setup to repair") + keep = {k: v for k, v in (keep or {}).items() if v is not None} + if keep and any(cfg.get(k) != v for k, v in keep.items()): # #179: a --host/--api-key on a start was ignored + cfg.update(keep) + cfg_path.write_text(json.dumps(cfg, indent=1), encoding="utf-8") + ok("saved for this model: " + ", ".join("api key" if k == "api_key" else f"{k.replace('_', ' ')} {v}" + for k, v in keep.items())) cfg_path.touch() # the most recently used model if "--mtp" in cfg["args"][:-1]: - refresh_draft_vocab(Path(cfg["args"][cfg["args"].index("--mtp") + 1])) + refresh_draft_vocab(Path(cfg["args"][cfg["args"].index("--mtp") + 1]), cfg.get("draft_vocab", "cjk")) cmd = [sys.executable, str(ROOT / "serve" / "server.py"), "--engine", "strata", "--config", str(cfg_path), "--port", str(port or cfg.get("port", 8080))] if cfg.get("backend") == "hip": # AMD: one card, numbered as HIP numbers them @@ -1489,17 +1524,24 @@ def start(cfg_path: Path, port: int | None, gpu: int | list | None = None, open_ OLD_DRAFT_VOCABS = {"369151522226a5edaa5f12cfd1e2ae7db8f4fbdbd222f3dcf327dced9597fb25"} # to 0.1.26: 27 Han tokens -def refresh_draft_vocab(rt: Path) -> None: - """The draft layer's token subset (data/draft_vocab.bin) in the MTP folder: copied when missing, and an older - shipped one is replaced, so an update reaches existing installs (0.1.27 added the CJK scripts, #137).""" - new, dst = ROOT / "data" / "draft_vocab.bin", rt / "draft_vocab.bin" +DRAFT_VOCABS = {"cjk": "draft_vocab.bin", "en": "draft_vocab_en.bin"} + + +def refresh_draft_vocab(rt: Path, choice: str = "cjk") -> None: + """The draft layer's token subset in the MTP folder: `cjk` (data/draft_vocab.bin, since 0.1.27, #137) or `en` + (data/draft_vocab_en.bin, the English/code subset before it: ~110 MiB less VRAM, English answers 1-2% faster). + Copied when missing or when a shipped subset other than the chosen one is there; a subset made by hand is kept.""" + new, dst = ROOT / "data" / DRAFT_VOCABS.get(choice, "draft_vocab.bin"), rt / "draft_vocab.bin" if not new.exists() or not rt.is_dir(): return if dst.exists(): old = hashlib.sha256(dst.read_bytes()).hexdigest() - if old not in OLD_DRAFT_VOCABS or old == hashlib.sha256(new.read_bytes()).hexdigest(): + shipped = OLD_DRAFT_VOCABS | {hashlib.sha256((ROOT / "data" / f).read_bytes()).hexdigest() + for f in DRAFT_VOCABS.values() if (ROOT / "data" / f).exists()} + if old not in shipped or old == hashlib.sha256(new.read_bytes()).hexdigest(): return - ok("draft layer: the token subset now includes Chinese, Japanese and Korean") + ok("draft layer: the token subset " + ("with Chinese, Japanese and Korean" if choice == "cjk" else + "for English and code (less VRAM)")) shutil.copyfile(new, dst) @@ -1578,6 +1620,9 @@ def main() -> int: ap.add_argument("--check", action="store_true", help="only check this PC and exit") ap.add_argument("--calibrate", action="store_true", help="tune the engine's settings for this PC (about 5-10 minutes), then start the model") + ap.add_argument("--draft-vocab", choices=list(DRAFT_VOCABS), + help="the draft layer's tokens: cjk = with Chinese, Japanese and Korean (default), en = English " + "and code only (~110 MiB less VRAM, English answers 1-2%% faster)") ap.add_argument("--low-ram", choices=["auto", "on", "off"], default="auto", help="map the model's experts from its folder instead of copying them into RAM (for a PC with a big " "GPU and little RAM); auto: when the experts would not fit the RAM") @@ -1637,19 +1682,22 @@ def main() -> int: say(f" {i}) {json.loads(c.read_text(encoding='utf-8-sig')).get('model_name', c.stem)}") pick_cfg = have[int(ask("Tune which one?", [str(i) for i in range(1, len(have) + 1)], "1", a.yes)) - 1] calibrate_config(pick_cfg) - return 0 if a.no_start else start(pick_cfg, a.port, run_gpu, yes=a.yes, layer_split=a.layer_split) + return 0 if a.no_start else start(pick_cfg, a.port, run_gpu, yes=a.yes, layer_split=a.layer_split, + keep={"host": a.host, "api_key": a.api_key, "draft_vocab": a.draft_vocab}) if have and not (a.setup or a.model or a.family or a.check or a.no_start): if not a.build: update_installed_engine(a.prebuilt) if len(have) == 1: - return start(have[0], a.port, run_gpu, yes=a.yes, layer_split=a.layer_split) + return start(have[0], a.port, run_gpu, yes=a.yes, layer_split=a.layer_split, + keep={"host": a.host, "api_key": a.api_key, "draft_vocab": a.draft_vocab}) say() for i, c in enumerate(have, 1): say(f" {i}) {json.loads(c.read_text(encoding='utf-8-sig')).get('model_name', c.stem)}") say(f" {len(have) + 1}) install another model / change settings") pick = int(ask("Which one?", [str(i) for i in range(1, len(have) + 2)], "1", a.yes)) if pick <= len(have): - return start(have[pick - 1], a.port, run_gpu, yes=a.yes, layer_split=a.layer_split) + return start(have[pick - 1], a.port, run_gpu, yes=a.yes, layer_split=a.layer_split, + keep={"host": a.host, "api_key": a.api_key, "draft_vocab": a.draft_vocab}) # ---- 1. the PC step(1, "checking your PC") @@ -1861,6 +1909,9 @@ def main() -> int: models_dir, shards = cand[0].parent, cand ok(f"model files found in {models_dir}") break + for s in shards: # #173: a whole file copied in by hand has no finish mark + if s.exists() and not done(s) and whole_shard(s): + mark(s, "whole (checked against its own tensor directory)") have_model = all(s.exists() and (done(s) or a.gguf_dir) for s in shards) need = (0 if a.gguf_dir or have_model else MODELS[model]["download_gb"]) + 8 + \ (40 if model == "Q2_0" and avx512 and family == "qwen" else 0) + (1 if vision != "none" else 0) + \ @@ -1956,7 +2007,7 @@ def main() -> int: "--out", str(mtp / "mtp-q2_0.gguf")], env=env) run([sys.executable, str(ROOT / "tools" / "mtp_rt.py"), "--gguf", str(mtp / "mtp-q2_0.gguf"), "--out", str(rt)], env=env) - refresh_draft_vocab(rt) + refresh_draft_vocab(rt, a.draft_vocab or "cjk") ok(f"MTP draft layer: {rt}") # ---- 7. the start script @@ -2016,6 +2067,8 @@ def main() -> int: cfg["host"] = a.host if a.api_key: cfg["api_key"] = a.api_key + if a.draft_vocab: + cfg["draft_vocab"] = a.draft_vocab if vision != "none": cfg["vision"] = {"exe": str(eng / VEXE), "mmproj": str(mmproj), "model": str(shards[0]), "gpu": vision == "gpu", "max_tokens": VISION[vision]["max_tokens"]} From 03939f1c067c352f3e21fb634ae91514610b0a6b Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Wed, 30 Sep 2026 11:18:54 +0200 Subject: [PATCH 07/32] docs: the draft layer's token subset and --draft-vocab --- docs/DETAILS.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/docs/DETAILS.md b/docs/DETAILS.md index c55d13e9..1217072e 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -70,6 +70,13 @@ VRAM. RTX 3090, the Coder at 198K context: 99 instead of 85 tokens/s output, the slower. It does not stream its KV cache (KV streaming is on by default from 64K), so it pays off mostly on large cards at long contexts. +**The draft layer's tokens (0.1.27, `--draft-vocab`):** the MTP draft layer can only propose tokens from a subset +of the vocabulary (`mtp/rt/draft_vocab.bin`). Since 0.1.27 the subset includes every Chinese, Japanese and Korean +token (106,299 ids), so answers in those languages are 15-38% faster (Q2_0, RTX 5070). Its head takes ~180 MiB of +VRAM, which the expert cache leaves free for it (0.1.28). `START-HERE.bat --setup --draft-vocab en` keeps the +English/code subset from before (40,525 ids, ~110 MiB less VRAM, English answers 1-2% faster; CJK answers get +almost no drafts). `tools/draft_vocab.py` builds and inspects subsets. + **Low-RAM mode (engine 0.1.26, chosen by setup):** normally all of a model's experts are copied into RAM (23-50 GB, pinned) and the GPU holds a copy of the most-used ones. On a PC whose RAM cannot hold them beside the system (the experts plus ~10 GB), setup instead maps them from one file in the model's folder (`--mmap-experts`, the pack's From 10409135dde890606a6fe6e5a2835658a75ef371 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Wed, 30 Sep 2026 10:54:59 +0200 Subject: [PATCH 08/32] Engine 0.1.28: the expert cache reserves the draft head's VRAM (0.1.27 left 16 GB cards below the stall line), a cancelled request no longer fails the next one, the API key protects /status; setup requires it --- CMakeLists.txt | 2 +- setup.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 74ae6916..22e4528a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -8,7 +8,7 @@ # below refuses anything older: silently building for a pre-Ampere arch would produce a binary that runs # and is wrong about its own performance, which is the worst of both outcomes. cmake_minimum_required(VERSION 3.24) -project(strata VERSION 0.1.27 LANGUAGES CXX) +project(strata VERSION 0.1.28 LANGUAGES CXX) add_compile_definitions(STRATA_VERSION="${PROJECT_VERSION}") # issue #31: release builds keep a PDB beside the exe (not shipped in it), so a minidump from a stalled engine can # be read back to the exact source line diff --git a/setup.py b/setup.py index 373941f3..94080d20 100644 --- a/setup.py +++ b/setup.py @@ -58,7 +58,7 @@ PREBUILT_ASSET = "strata-windows-x64.zip" if WIN else "strata-linux-x64.zip" # the CUDA libraries the ready-made engine loads (the same CUDA 13.0 it is built with), from NVIDIA's pip packages CUDA_WHEELS = ["nvidia-cublas==13.0.2.14", "nvidia-cuda-runtime==13.0.96"] MIN_DRIVER = 580 # CUDA 13.0 -MIN_ENGINE = (0, 1, 27) # v0.1.27: RTX 20 (sm_75) in the ready-made engine, the HIP build without CUDA headers; v0.1.26: the draft layer's prompt pass in batches; v0.1.25: faster prompts (grouping off the copy engine, fused hyper-connection kernels), AMD HIP backend, --kv k8v4; v0.1.24: long prompts faster (QSA select on tensor cores); v0.1.23: image requests honor sampling, 8 GB cards start, batched verify window; v0.1.22: faster prompts (tensor-core attention), multi-GPU across images/steering/KV streaming; v0.1.21: multi-GPU layer split (--gpus); v0.1.20: system-prompt checkpoint, PCIe probe, hit rate; v0.1.19: penalties +MIN_ENGINE = (0, 1, 28) # v0.1.28: the expert cache reserves the draft head, a cancelled request no longer fails the next; v0.1.27: RTX 20 (sm_75) in the ready-made engine, the HIP build without CUDA headers; v0.1.26: the draft layer's prompt pass in batches; v0.1.25: faster prompts (grouping off the copy engine, fused hyper-connection kernels), AMD HIP backend, --kv k8v4; v0.1.24: long prompts faster (QSA select on tensor cores); v0.1.23: image requests honor sampling, 8 GB cards start, batched verify window; v0.1.22: faster prompts (tensor-core attention), multi-GPU across images/steering/KV streaming; v0.1.21: multi-GPU layer split (--gpus); v0.1.20: system-prompt checkpoint, PCIe probe, hit rate; v0.1.19: penalties PY_PACKAGES = ["numpy", "jinja2", "regex", "pyyaml", "tqdm", "requests", "cmake", "ninja", "pillow", "psutil"] MODELS = { From 91e8d21227a765661b0889551f0c86104c2dfb73 Mon Sep 17 00:00:00 2001 From: Guillaume PUTIER Date: Tue, 29 Sep 2026 19:09:21 +0200 Subject: [PATCH 09/32] s_gemv: the q8 split kernel reaches its barrier before a rowless warp returns --- src/kernels/cuda/s_gemv.cu | 14 +++- src/kernels/s_gemv_q8k_parity.cpp | 107 ++++++++++++++++++++++++++++++ 2 files changed, 118 insertions(+), 3 deletions(-) diff --git a/src/kernels/cuda/s_gemv.cu b/src/kernels/cuda/s_gemv.cu index cdfa4d0b..d0db1783 100644 --- a/src/kernels/cuda/s_gemv.cu +++ b/src/kernels/cuda/s_gemv.cu @@ -147,14 +147,20 @@ __global__ void s_gemv_q8_split_kernel(const uint8_t* __restrict__ x, const uint constexpr int PER_BYTE = 8 / CODE_BITS; const int warps_per_block = (int) (blockDim.x >> 5); const long long o = (long long) blockIdx.x * warps_per_block + (threadIdx.x >> 5); - if (o >= n_out) return; const int lane = threadIdx.x & 31; // THE CODEBOOK, IN SHARED MEMORY. 16 bytes, loaded once per block by the first 16 threads, instead of a // divergent constant read per element - measured at 2.12x of this whole kernel (see the note on `kIq4Nl`). + // + // THE LOAD AND THE BARRIER COME BEFORE THE EARLY RETURN, as in `s_gemv_q8k_kernel`. The return used to + // sit above them, so whenever `n_out % 8 != 0` the last block's surplus warps left before a barrier the + // others still waited at - undefined behaviour that every shape in the pack (a multiple of 8) happened to + // avoid. `o` is per-WARP, so the return below keeps whole warps together and the shuffle reduction's + // full mask stays valid. __shared__ signed char s_iq4nl[16]; if (threadIdx.x < 16) s_iq4nl[threadIdx.x] = kIq4Nl[threadIdx.x]; __syncthreads(); + if (o >= n_out) return; const long long n_groups = n_in >> group_shift; const long long codes_per_row = n_in / PER_BYTE; @@ -655,8 +661,10 @@ void s_gemv_q8_0_split(const uint8_t* x_q8_0, const uint8_t* codes, const float* form.group_elems); std::exit(1); } - if (form.group_elems % 4 != 0) { - std::fprintf(stderr, "s_gemv_q8_0_split: group_elems %d is not a multiple of 4\n", form.group_elems); + // SIXTEEN, NOT FOUR: a lane-iteration takes QE = 16 consecutive elements under ONE scale (see the kernel), + // so a group of 4 or 8 would read the wrong scale for most of them. The Q8_K launcher already said 16. + if (form.group_elems % 16 != 0) { + std::fprintf(stderr, "s_gemv_q8_0_split: group_elems %d is not a multiple of 16\n", form.group_elems); std::exit(1); } int group_shift = 0; diff --git a/src/kernels/s_gemv_q8k_parity.cpp b/src/kernels/s_gemv_q8k_parity.cpp index 882122b0..5bfb475a 100644 --- a/src/kernels/s_gemv_q8k_parity.cpp +++ b/src/kernels/s_gemv_q8k_parity.cpp @@ -72,6 +72,108 @@ struct Case { bool has_offset; }; +/// THE RAGGED LAST BLOCK. The split kernels give each warp one row and a block eight warps, so with +/// `n_out % 8 != 0` the last block holds warps that have no row. Those warps used to return BEFORE the +/// codebook barrier - undefined behaviour that every real shape (a multiple of 8) avoided. Here `n_out` is +/// deliberately ragged, every row is checked against the host reference over the same bytes, and a guard +/// band past `n_out` must come back untouched: a warp without a row must neither hang the block nor write. +/// (`compute-sanitizer --tool synccheck` on this binary is the direct check of the barrier itself.) +int ragged_rows(const Case& cs, long long n_out) { + const long long n_in = 512; + const long long guard = 64; + std::mt19937 rng(77 + (unsigned) n_out); + std::normal_distribution g(0.0f, 1.0f); + std::vector xf((size_t) n_in); + for (auto& v : xf) v = g(rng); + SForm f; + f.code_bits = cs.bits; + f.code_bias = cs.bias; + f.group_elems = cs.group; + f.codebook = cs.cb; + f.has_offset = cs.has_offset; + const int per_byte = 8 / cs.bits; + std::vector codes((size_t) (n_out * n_in / per_byte)); + for (auto& v : codes) v = (uint8_t) (rng() & 0xFF); + const long long n_groups = n_in / cs.group; + std::vector scales((size_t) (n_out * n_groups)), offs((size_t) (n_out * n_groups)); + for (auto& v : scales) v = 0.01f + 0.001f * (float) (rng() % 20); + for (auto& v : offs) v = 0.2f * g(rng); + + float* d_xf = nullptr; + uint8_t *d_xk = nullptr, *d_x0 = nullptr, *d_codes = nullptr; + float *d_scales = nullptr, *d_offs = nullptr, *d_y = nullptr; + std::vector xk((size_t) (n_in / 256) * 292), x0((size_t) (n_in / 32) * 34); + check(cudaMalloc(&d_xf, (size_t) n_in * 4), "rxf"); + check(cudaMalloc(&d_xk, xk.size()), "rxk"); + check(cudaMalloc(&d_x0, x0.size()), "rx0"); + check(cudaMalloc(&d_codes, codes.size()), "rcodes"); + check(cudaMalloc(&d_scales, scales.size() * 4), "rscales"); + check(cudaMalloc(&d_offs, offs.size() * 4), "roffs"); + check(cudaMalloc(&d_y, (size_t) (n_out + guard) * 4), "ry"); + check(cudaMemcpy(d_xf, xf.data(), (size_t) n_in * 4, cudaMemcpyHostToDevice), "rcxf"); + check(cudaMemcpy(d_codes, codes.data(), codes.size(), cudaMemcpyHostToDevice), "rcc"); + check(cudaMemcpy(d_scales, scales.data(), scales.size() * 4, cudaMemcpyHostToDevice), "rcs"); + check(cudaMemcpy(d_offs, offs.data(), offs.size() * 4, cudaMemcpyHostToDevice), "rco"); + strata::kernels::quantize_q8_K(d_xf, d_xk, n_in, nullptr); + strata::kernels::quantize_q8_0(d_xf, d_x0, n_in, nullptr); + check(cudaMemcpy(xk.data(), d_xk, xk.size(), cudaMemcpyDeviceToHost), "rcxk"); + check(cudaMemcpy(x0.data(), d_x0, x0.size(), cudaMemcpyDeviceToHost), "rcx0"); + + int bad = 0; + for (int kind = 0; kind < 2; ++kind) { // 0: Q8_K activation, 1: Q8_0 activation + std::vector want((size_t) n_out); + std::vector mag((size_t) n_out); // sum |w_i a_i| per row: a row whose sum cancels near 0 + for (long long o = 0; o < n_out; ++o) { // must not turn f32 rounding into a relative failure + double acc = 0, am = 0; + for (long long i = 0; i < n_in; ++i) { + double a; + if (kind == 0) { + a = q8k_at(xk, i); + } else { + const uint8_t* blk = x0.data() + (size_t) (i / 32) * 34; + uint16_t dbits; + std::memcpy(&dbits, blk, 2); + a = (double) strata::kernels::f32_from_f16(dbits) * (double) ((const int8_t*) (blk + 2))[i % 32]; + } + const double wa = weight_at(codes, scales, offs, f, n_in, o, i) * a; + acc += wa; + am += std::fabs(wa); + } + want[(size_t) o] = (float) acc; + mag[(size_t) o] = am; + } + // the guard band holds a NaN pattern; any write there shows up as a changed bit + std::vector sentinel((size_t) (n_out + guard), 0x7FC0DEADu); + check(cudaMemcpy(d_y, sentinel.data(), sentinel.size() * 4, cudaMemcpyHostToDevice), "rsent"); + if (kind == 0) + strata::kernels::s_gemv_q8k_split(d_xk, d_codes, d_scales, cs.has_offset ? d_offs : nullptr, d_y, n_in, + n_out, f, nullptr); + else + strata::kernels::s_gemv_q8_0_split(d_x0, d_codes, d_scales, cs.has_offset ? d_offs : nullptr, d_y, n_in, + n_out, f, nullptr); + check(cudaDeviceSynchronize(), "ragged split"); + std::vector got_bits(sentinel.size()); + check(cudaMemcpy(got_bits.data(), d_y, got_bits.size() * 4, cudaMemcpyDeviceToHost), "rcy"); + double m = 0, d = 0; + for (long long o = 0; o < n_out; ++o) { + float v; + std::memcpy(&v, &got_bits[(size_t) o], 4); + m += mag[(size_t) o]; + d += std::fabs((double) want[(size_t) o] - (double) v); + } + long long touched = 0; + for (long long o = n_out; o < n_out + guard; ++o) touched += got_bits[(size_t) o] != 0x7FC0DEADu; + const double rel = d / (m > 1e-30 ? m : 1e-30); + const bool ok = rel <= 1e-5 && touched == 0; + std::printf(" %-28s %s n_out %3lld: rel %.3e, guard words written %lld %s\n", cs.what, + kind == 0 ? "Q8_K" : "Q8_0", n_out, rel, touched, ok ? "ok" : "*** WRONG ***"); + if (!ok) ++bad; + } + cudaFree(d_xf); cudaFree(d_xk); cudaFree(d_x0); cudaFree(d_codes); cudaFree(d_scales); cudaFree(d_offs); + cudaFree(d_y); + return bad; +} + } // namespace int main(int argc, char** argv) { @@ -229,6 +331,11 @@ int main(int argc, char** argv) { cudaFree(d_xf); cudaFree(d_xq); cudaFree(d_codes); cudaFree(d_scales); cudaFree(d_offs); cudaFree(d_y); } + // ---- 4. output widths that are NOT a multiple of the eight rows per block + std::printf("\n"); + for (const Case& cs : cases) + for (long long n_out : {1LL, 7LL, 9LL, 61LL}) bad += ragged_rows(cs, n_out); + std::printf("\ns_gemv_q8k: %d failures\n", bad); if (bad) return 1; if (selftest) std::printf("s_gemv_q8k_parity OK\n"); From e2b0cbcde9ad991ad7c6f7d43fa1edad9a5cbf23 Mon Sep 17 00:00:00 2001 From: Guillaume PUTIER Date: Tue, 29 Sep 2026 19:09:21 +0200 Subject: [PATCH 10/32] bf16: a NaN stays a quiet NaN in f32 -> bf16, as in ggml --- CMakeLists.txt | 4 ++ include/strata/kernels/bf16_bits.hpp | 7 +++ src/kernels/bf16_bits_test.cpp | 80 ++++++++++++++++++++++++++++ src/kernels/cuda/dequant_bf16.cu | 3 ++ src/kernels/elementwise_parity.cpp | 59 ++++++++++++++++++++ 5 files changed, 153 insertions(+) create mode 100644 src/kernels/bf16_bits_test.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 22e4528a..f3320864 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -579,6 +579,10 @@ if(STRATA_BUILD_TESTS) add_executable(conv_cache_test src/program/conv_cache_test.cpp) target_include_directories(conv_cache_test PRIVATE include) add_test(NAME conv_cache_test COMMAND conv_cache_test) + # the f32 -> bf16 rounding against ggml's, NaN included, over every f32 bit pattern (header-only, CPU) + add_executable(bf16_bits_test src/kernels/bf16_bits_test.cpp) + target_include_directories(bf16_bits_test PRIVATE include) + add_test(NAME bf16_bits_test COMMAND bf16_bits_test) endif() add_library(strata_kernels_cpu STATIC src/kernels/cpu/expert.cpp src/kernels/cpu/pool.cpp diff --git a/include/strata/kernels/bf16_bits.hpp b/include/strata/kernels/bf16_bits.hpp index 5c37701f..5c32532f 100644 --- a/include/strata/kernels/bf16_bits.hpp +++ b/include/strata/kernels/bf16_bits.hpp @@ -28,6 +28,12 @@ namespace strata::kernels { /// Round-to-nearest-even f32 -> bf16, returned as raw bits in the LOW half of the uint16. +/// +/// **A NaN IS PASSED THROUGH, QUIETED, AS `ggml_compute_fp32_to_bf16` DOES.** The rounding add alone +/// carries out of the mantissa for a NaN: 0x7FFFFFFF became 0x8000 (-0) and 0x7F800001 became 0x7F80 (+inf), so +/// a NaN upstream was masked instead of propagated. The test is on the magnitude bits, the result keeps the +/// sign and the top mantissa bits and sets the quiet bit (64 = bit 6 of the bf16). Every non-NaN input, +/// infinities included, rounds exactly as before. STRATA_BF16_HD inline uint16_t bf16_from_f32(float f) { uint32_t i; #if defined(__HIP_DEVICE_COMPILE__) @@ -35,6 +41,7 @@ STRATA_BF16_HD inline uint16_t bf16_from_f32(float f) { #else std::memcpy(&i, &f, 4); #endif + if ((i & 0x7FFFFFFFu) > 0x7F800000u) return (uint16_t) ((i >> 16) | 64u); i = (i + ((i >> 16) & 1u) + 0x7FFFu) & 0xFFFF0000u; return (uint16_t) (i >> 16); } diff --git a/src/kernels/bf16_bits_test.cpp b/src/kernels/bf16_bits_test.cpp new file mode 100644 index 00000000..f996463f --- /dev/null +++ b/src/kernels/bf16_bits_test.cpp @@ -0,0 +1,80 @@ +// src/kernels/bf16_bits_test.cpp - `bf16_bits.hpp` against ggml's rule, over EVERY f32 bit pattern (CPU only). +// +// the rounding add `i + 0x7FFF + bit16` carries out of the mantissa for a NaN, so 0x7FFFFFFF came back as +// -0 and 0x7F800001 as +inf - an upstream NaN was masked instead of propagated. `ggml_compute_fp32_to_bf16` +// (ggml-impl.h at the pinned llama.cpp) tests the NaN first and returns `(i >> 16) | 64`. Three checks, all +// exhaustive (2^32 inputs, a few seconds): +// +// 1. the header equals ggml's function, transcribed below, on every input; +// 2. on every NON-NaN input it equals the previous rounding, so the change cannot move a finite value or an +// infinity by a single bit; +// 3. every NaN input gives a quiet NaN of the same sign. +// +// And the round trip over all 65,536 bf16 patterns: a non-NaN bf16 survives f32 and back unchanged. +#include "strata/kernels/bf16_bits.hpp" + +#include +#include +#include + +namespace { + +/// ggml_compute_fp32_to_bf16, ggml/src/ggml-impl.h (MIT, the ggml authors), on raw bits. +uint16_t ggml_bf16(uint32_t u) { + if ((u & 0x7fffffffu) > 0x7f800000u) return (uint16_t) ((u >> 16) | 64); + return (uint16_t) ((u + (0x7fffu + ((u >> 16) & 1u))) >> 16); +} + +/// The rule before this fix, kept only to prove the change is confined to NaN inputs. +uint16_t previous_bf16(uint32_t u) { + u = (u + ((u >> 16) & 1u) + 0x7FFFu) & 0xFFFF0000u; + return (uint16_t) (u >> 16); +} + +bool is_nan_bits(uint32_t u) { return (u & 0x7fffffffu) > 0x7f800000u; } + +} // namespace + +int main() { + unsigned long long vs_ggml = 0, vs_previous = 0, nan_lost = 0, nan_inputs = 0, previous_masked = 0; + uint32_t first_bad = 0; + bool have_bad = false; + for (uint64_t k = 0; k <= 0xFFFFFFFFull; ++k) { + const uint32_t u = (uint32_t) k; + float f; + std::memcpy(&f, &u, 4); + const uint16_t got = strata::kernels::bf16_from_f32(f); + if (got != ggml_bf16(u)) { + ++vs_ggml; + if (!have_bad) { first_bad = u; have_bad = true; } + } + if (is_nan_bits(u)) { + ++nan_inputs; + const uint32_t back = (uint32_t) got << 16; + // a quiet NaN (bit 22 of the f32) with the input's sign + if (!is_nan_bits(back) || (back & 0x00400000u) == 0 || (back >> 31) != (u >> 31)) ++nan_lost; + if (!is_nan_bits((uint32_t) previous_bf16(u) << 16)) ++previous_masked; + } else if (got != previous_bf16(u)) { + ++vs_previous; + if (!have_bad) { first_bad = u; have_bad = true; } + } + } + std::printf(" f32 -> bf16 over 2^32 inputs: %llu differ from ggml, %llu non-NaN differ from the previous rule\n", + vs_ggml, vs_previous); + std::printf(" NaN inputs: %llu, not a quiet same-sign NaN now: %llu (the previous rule masked %llu of them)\n", + nan_inputs, nan_lost, previous_masked); + if (have_bad) std::printf(" first mismatch at input 0x%08x\n", first_bad); + + unsigned long long trip_bad = 0; + for (uint32_t h = 0; h <= 0xFFFFu; ++h) { + const float f = strata::kernels::f32_from_bf16((uint16_t) h); + const uint16_t back = strata::kernels::bf16_from_f32(f); + const bool nan = is_nan_bits(h << 16); + if (back != (nan ? (uint16_t) (h | 64u) : (uint16_t) h)) ++trip_bad; + } + std::printf(" bf16 -> f32 -> bf16 over 65536 patterns: %llu wrong\n", trip_bad); + + const bool ok = vs_ggml == 0 && vs_previous == 0 && nan_lost == 0 && trip_bad == 0 && previous_masked > 0; + std::printf("\nbf16_bits_test %s\n", ok ? "OK" : "FAILED"); + return ok ? 0 : 1; +} diff --git a/src/kernels/cuda/dequant_bf16.cu b/src/kernels/cuda/dequant_bf16.cu index 849d5118..faac2ab4 100644 --- a/src/kernels/cuda/dequant_bf16.cu +++ b/src/kernels/cuda/dequant_bf16.cu @@ -19,6 +19,9 @@ __device__ __forceinline__ float h2f(const uint8_t* p) { } __device__ __forceinline__ uint16_t f2bf(float f) { uint32_t u = __float_as_uint(f); + // a NaN (a NaN scale in the block) stays a quiet NaN, as in ggml_compute_fp32_to_bf16 and `bf16_from_f32`: + // the rounding add below would carry it into -0 or inf + if ((u & 0x7fffffffu) > 0x7f800000u) return (uint16_t) ((u >> 16) | 64u); u += 0x7fffu + ((u >> 16) & 1u); // round to nearest even return (uint16_t) (u >> 16); } diff --git a/src/kernels/elementwise_parity.cpp b/src/kernels/elementwise_parity.cpp index 58a2c36d..9a8fc3f3 100644 --- a/src/kernels/elementwise_parity.cpp +++ b/src/kernels/elementwise_parity.cpp @@ -12,6 +12,7 @@ // instead of decaying, so the sign is checked as a property and not assumed. // 3. `silu` IS COMPUTED IN DOUBLE then cast, because `ref/gdn.py`'s numpy does. f32 `expf` differs in the // last bits, and the test measures that rather than asserting it away. +#include "strata/kernels/dequant_bf16.hpp" #include "strata/kernels/elementwise.hpp" #include "strata/kernels/f16_bits.hpp" @@ -409,6 +410,64 @@ int main(int argc, char** argv) { if (mismatches || guards || fma_diff == 0) ++bad; } + // ---- THE f32 -> bf16 CONVERSIONS KEEP A NaN A NaN. `f32_to_bf16_bulk` (the header's `bf16_from_f32` + // on the device) and the prompt path's dequantizer (its own `f2bf`) against ggml_compute_fp32_to_bf16's rule; + // before the fix 0x7FFFFFFF came back as -0 and 0x7F800001 as +inf. `bf16_bits_test` covers every f32 on + // the host; this is the same header compiled by nvcc, plus the second copy in dequant_bf16.cu. + { + auto ggml_bf16 = [](uint32_t u) -> uint16_t { + if ((u & 0x7fffffffu) > 0x7f800000u) return (uint16_t) ((u >> 16) | 64); + return (uint16_t) ((u + (0x7fffu + ((u >> 16) & 1u))) >> 16); + }; + std::vector bits = {0x7FFFFFFFu, 0xFFFFFFFFu, 0x7F800001u, 0xFF800001u, 0x7FC00000u, 0x7FBFFFFFu, + 0x7F800000u, 0xFF800000u, 0x7F7FFFFFu, 0x00000000u, 0x80000000u, 0x3F808000u, + 0x3F818000u, 0x00008000u, 0x7F7F8000u}; + std::mt19937 rng(13); + while (bits.size() < 4096) bits.push_back((uint32_t) rng()); + const size_t n = bits.size(); + float* dx = nullptr; + uint16_t* dy = nullptr; + check(cudaMalloc(&dx, n * 4), "bf16 x"); + check(cudaMalloc(&dy, n * 2), "bf16 y"); + check(cudaMemcpy(dx, bits.data(), n * 4, cudaMemcpyHostToDevice), "bf16 cx"); + strata::kernels::f32_to_bf16_bulk(dx, dy, (int64_t) n, nullptr); + std::vector got(n); + check(cudaMemcpy(got.data(), dy, n * 2, cudaMemcpyDeviceToHost), "bf16 cy"); + int wrong = 0; + for (size_t i = 0; i < n; ++i) wrong += got[i] != ggml_bf16(bits[i]); + + // A Q8_0 block (type 8) whose fp16 scale is a NaN: every dequantized value is NaN * q, a NaN, and it must + // still be one in BF16. A second block with an ordinary scale checks the finite path did not move. + std::vector blk(2 * 34, 0); + blk[0] = 0x00; blk[1] = 0x7E; // fp16 quiet NaN + blk[34] = 0x00; blk[35] = 0x3C; // fp16 1.0 + for (int j = 0; j < 32; ++j) { + blk[(size_t) (2 + j)] = (uint8_t) (int8_t) (j - 16); + blk[(size_t) (36 + j)] = (uint8_t) (int8_t) (3 * j - 50); + } + uint8_t* db = nullptr; + uint16_t* dq = nullptr; + check(cudaMalloc(&db, blk.size()), "q8 blk"); + check(cudaMalloc(&dq, 64 * 2), "q8 out"); + check(cudaMemcpy(db, blk.data(), blk.size(), cudaMemcpyHostToDevice), "q8 cblk"); + strata::kernels::dequant_bf16(8, db, 0, 2, 32, dq, nullptr); + check(cudaDeviceSynchronize(), "dequant_bf16"); + std::vector q(64); + check(cudaMemcpy(q.data(), dq, 64 * 2, cudaMemcpyDeviceToHost), "q8 cout"); + int dq_wrong = 0; + for (int j = 0; j < 32; ++j) { + if (!((q[(size_t) j] & 0x7FFFu) > 0x7F80u)) ++dq_wrong; // row 0: NaN scale -> NaN + const float v = (float) (3 * j - 50); // row 1: d = 1.0 -> the integer + uint32_t vb; + std::memcpy(&vb, &v, 4); + if (q[(size_t) (32 + j)] != ggml_bf16(vb)) ++dq_wrong; + } + std::printf(" f32 -> bf16 (NaN kept): bulk %d of %zu differ from ggml, dequant_bf16 %d of 64 wrong\n", + wrong, n, dq_wrong); + if (wrong || dq_wrong) ++bad; + cudaFree(dx); cudaFree(dy); cudaFree(db); cudaFree(dq); + } + std::printf("\nelementwise: %d failures\n", bad); if (bad) return 1; if (selftest) std::printf("elementwise_parity OK\n"); From a8d79afab7225d14ab9d0a4ae517cc28807cc9bc Mon Sep 17 00:00:00 2001 From: Guillaume PUTIER Date: Tue, 29 Sep 2026 19:09:21 +0200 Subject: [PATCH 11/32] qsa: mask cells whose page did not resolve; refuse a clock sweep over fewer slots than the resolve block --- src/kernels/cuda/kv_stream.cu | 8 ++++++++ src/kernels/cuda/qsa_decode_attn.cu | 11 +++++++---- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/src/kernels/cuda/kv_stream.cu b/src/kernels/cuda/kv_stream.cu index 5787001f..ec01ff22 100644 --- a/src/kernels/cuda/kv_stream.cu +++ b/src/kernels/cuda/kv_stream.cu @@ -209,6 +209,14 @@ void kv_stream_resolve(const KvStreamMap& m, const QsaAttnPools& slots, const Kv std::fprintf(stderr, "kv_stream: a block's scale run must be a multiple of 16 bytes\n"); std::exit(1); } + // one sweep step looks at RT consecutive slots `(hand + thread) % n_slots`; with fewer slots than RT two + // threads see the same slot and may both take it for two different misses. The engine never streams with fewer + // than qsa_kv_resident_min() / page_size = 5,120 slots, so this is a guard, not a limit. + if (m.n_slots < RT) { + std::fprintf(stderr, "kv_stream: %lld slots is fewer than the resolve block (%d): the clock sweep would take a " + "slot twice\n", (long long) m.n_slots, RT); + std::exit(1); + } resolve_kernel<<<1, RT, 0, (cudaStream_t) stream>>>(m, ids, steps, (int) n_q, (int) cap, (int) s.page_size); check("resolve"); copy_kernel<<<96, 128, 0, (cudaStream_t) stream>>>(m, runs_of(slots, host, fmt, s)); diff --git a/src/kernels/cuda/qsa_decode_attn.cu b/src/kernels/cuda/qsa_decode_attn.cu index 9f7fb884..4035999a 100644 --- a/src/kernels/cuda/qsa_decode_attn.cu +++ b/src/kernels/cuda/qsa_decode_attn.cu @@ -113,14 +113,16 @@ __global__ void __launch_bounds__(THREADS) attn_chunk_kernel(const float* __rest if (t < n_here) { const int cell = ids[c0 + t]; const long long page = (long long) p.page_table[cell / page_size]; - r = (page * n_kv_heads + kvh) * page_size + (cell % page_size); + // a block the KV streaming could not make resident keeps page -1 (ctl[3]); its cells are masked + // (score -FLT_MAX, weight 0) instead of being read from before the pool. + if (page >= 0) r = (page * n_kv_heads + kvh) * page_size + (cell % page_size); } srow[t] = r; } __syncthreads(); // scores: each warp takes cells warp, warp+8, ...; each lane holds 8 of the 256 dimensions. for (int c = warp; c < CHUNK; c += WARPS) { - if (c >= n_here) { + if (c >= n_here || srow[c] < 0) { if (lane < G) sp[lane][c] = -FLT_MAX; continue; } @@ -141,8 +143,8 @@ __global__ void __launch_bounds__(THREADS) attn_chunk_kernel(const float* __rest for (int h = warp; h < G; h += WARPS) { const float a = sp[h][lane], b = sp[h][lane + 32]; const float m = warp_max(fmaxf(a, b)); - const float ea = (lane < n_here) ? __expf(a - m) : 0.0f; - const float eb = (lane + 32 < n_here) ? __expf(b - m) : 0.0f; + const float ea = (lane < n_here && srow[lane] >= 0) ? __expf(a - m) : 0.0f; + const float eb = (lane + 32 < n_here && srow[lane + 32] >= 0) ? __expf(b - m) : 0.0f; sp[h][lane] = ea; sp[h][lane + 32] = eb; const float l = warp_sum(ea + eb); @@ -154,6 +156,7 @@ __global__ void __launch_bounds__(THREADS) attn_chunk_kernel(const float* __rest #pragma unroll for (int h = 0; h < G; ++h) acc[h] = 0.0f; for (int c = 0; c < n_here; ++c) { + if (srow[c] < 0) continue; // masked above, weight 0 float v; if constexpr (KV_MODE == 0) { v = __half2float(__ushort_as_half(p.v_pool[srow[c] * HD + t])); From c9d3fd68774c468237e45a182a59af7b906e4b17 Mon Sep 17 00:00:00 2001 From: Guillaume PUTIER Date: Tue, 29 Sep 2026 19:09:21 +0200 Subject: [PATCH 12/32] expert_source, s2_expert_grouped: guard the verify window's fixed tables --- src/core/expert_source.cpp | 20 +++++++++++++++++--- src/kernels/cuda/s2_expert_grouped.cu | 4 ++++ 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/src/core/expert_source.cpp b/src/core/expert_source.cpp index 6e007928..d235b958 100644 --- a/src/core/expert_source.cpp +++ b/src/core/expert_source.cpp @@ -772,6 +772,14 @@ void expert_pool_dispatch(void* user, const float* x_f, const int32_t* ids, cons d.experts += k; } +namespace { +// the verify window's per-entry tables in `expert_pool_dispatch_multi` (`kind`, `distinct`, `first_of`) +// are fixed arrays of this many entries: MAXT tokens of the model's 10 routed experts must fit, and a larger k is +// refused at run time rather than written past them. +constexpr int64_t kMaxWindowEntries = 128; +static_assert(strata::kernels::cpu::MAXT * 10 <= kMaxWindowEntries, "a verify window's entries overflow the tables"); +} // namespace + void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32_t* ids, int64_t n_tok, int64_t k, float* out) { using namespace strata::kernels::cpu; @@ -782,6 +790,12 @@ void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32 d.fail_layer = d.layers; return; } + if (k < 1 || n_tok * k > kMaxWindowEntries) { + d.failed = true; + d.fail = "a verify window routes more entries than the expert pool's window tables hold"; + d.fail_layer = d.layers; + return; + } if ((int64_t) d.act_multi.size() < n_tok) d.act_multi.resize((size_t) MAXT); const ExpertLayout& lay = expert_layout(); const bool native = lay.native; @@ -802,9 +816,9 @@ void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32 // ---- plan v0.3 P6: the GPU's share, decided and published FIRST so the GPU starts while the CPU works. // Distinct experts in routing order; resident ones and the last pcie_num/256 of the missed ones go to the GPU. const int64_t n = n_tok * k; - int32_t kind[128]; // per entry: -1 CPU, 0 VRAM, 1 PCIe - if (d.plan != nullptr && n <= 128 && n <= d.plan->cap) { - int64_t distinct[128], first_of[128]; + int32_t kind[kMaxWindowEntries]; // per entry: -1 CPU, 0 VRAM, 1 PCIe + if (d.plan != nullptr && n <= kMaxWindowEntries && n <= d.plan->cap) { + int64_t distinct[kMaxWindowEntries], first_of[kMaxWindowEntries]; int nd = 0, nmiss = 0; for (int64_t i = 0; i < n; ++i) { first_of[i] = i; diff --git a/src/kernels/cuda/s2_expert_grouped.cu b/src/kernels/cuda/s2_expert_grouped.cu index 90761ae6..3cbf6125 100644 --- a/src/kernels/cuda/s2_expert_grouped.cu +++ b/src/kernels/cuda/s2_expert_grouped.cu @@ -16,6 +16,7 @@ #include "strata/kernels/s2_expert_grouped.hpp" #include "strata/kernels/quantize_act.hpp" +#include "strata/kernels/verify_kernels.hpp" #include #include @@ -512,6 +513,9 @@ namespace { // hit kernel's. constexpr int GU_CHUNKS = (H / 32 + 31) / 32; // 3: chunks of a gate/up row per lane (80 chunks / 32 lanes) constexpr int GMAX = 8; // entries per group (tokens routed to one expert in a window) +// a group holds one entry per token of the window routed to its expert, and the kernels below keep at +// most GMAX of them (`min(..., GMAX)`): a longer window would drop entries without a word. +static_assert(GMAX >= kVerifyMaxT, "a verify window's group can exceed GMAX entries"); constexpr int GU_ROWS = 32; // gate/up rows per block: 4 per warp constexpr int D_ROWS = 64; // down rows per block: 8 per warp From 255bf03d3ec4b7cd79e91fb513a2019184dd6854 Mon Sep 17 00:00:00 2001 From: Guillaume PUTIER Date: Tue, 29 Sep 2026 19:09:21 +0200 Subject: [PATCH 13/32] gguf_reader.hpp: define NOMINMAX before windows.h --- include/strata/artifact/gguf_reader.hpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/include/strata/artifact/gguf_reader.hpp b/include/strata/artifact/gguf_reader.hpp index b7f35910..ee76f3c0 100644 --- a/include/strata/artifact/gguf_reader.hpp +++ b/include/strata/artifact/gguf_reader.hpp @@ -32,6 +32,9 @@ #ifdef _WIN32 #define WIN32_LEAN_AND_MEAN +#ifndef NOMINMAX +#define NOMINMAX // windows.h's min/max macros would break std::min/std::max in every file that includes this one +#endif #include #else #include From 5b9a5029dce0fe85c494a1bd11bc72129ce360c9 Mon Sep 17 00:00:00 2001 From: Guillaume PUTIER Date: Tue, 29 Sep 2026 19:10:57 +0200 Subject: [PATCH 14/32] build: guard the last two bench/micro targets on their file, as upstream does for the others --- CMakeLists.txt | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index f3320864..28e19d8c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -495,11 +495,11 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) add_test(NAME cvec_parity COMMAND cvec_parity) # Plan v0.3 P3: native MMVQ for 1..8 tokens (bitwise selftest + --bench timing); synthetic data, no model. - if(STRATA_BUILD_TESTS) - add_executable(native_mmvq_multi bench/micro/native_mmvq_multi.cpp) - target_include_directories(native_mmvq_multi PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(native_mmvq_multi PRIVATE strata_kernels ${_strata_gpu_runtime_target}) - add_test(NAME native_mmvq_multi COMMAND native_mmvq_multi --selftest) + if(STRATA_BUILD_TESTS AND EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/bench/micro/native_mmvq_multi.cpp") + add_executable(native_mmvq_multi bench/micro/native_mmvq_multi.cpp) + target_include_directories(native_mmvq_multi PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(native_mmvq_multi PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_test(NAME native_mmvq_multi COMMAND native_mmvq_multi --selftest) endif() # Plan v0.3 P0.1: working-set lock of a host region (CPU only). @@ -730,7 +730,7 @@ if(STRATA_NATIVE_EXPERTS) endif() endif() -if(STRATA_ENABLE_CUDA AND STRATA_BUILD_TESTS) +if(STRATA_ENABLE_CUDA AND STRATA_BUILD_TESTS AND EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/bench/micro/hit_cpu_order_parity.cu") add_executable(hit_cpu_order_parity bench/micro/hit_cpu_order_parity.cu) target_link_libraries(hit_cpu_order_parity PRIVATE strata_kernels strata_kernels_cpu ${_strata_gpu_runtime_target}) endif() From 95883f46e82d290b9a322e0057bca14684d86a7d Mon Sep 17 00:00:00 2001 From: pipeob0 Date: Wed, 30 Sep 2026 09:05:24 +0200 Subject: [PATCH 15/32] E-2 on the AVX-2 path too: prefetch the i-quant expert rows (same switch, CPUs without AVX-512) 24d4013 put the software prefetch in iq_avx512.cpp, so it only reaches CPUs with AVX-512; the AVX-2 kernels, which is what a Zen 3 / Haswell / Skylake-client box actually runs the i-quant rows on, had none. Same env, same default, same hint: STRATA_IQ_PREFETCH is the distance in bytes, 0 = off, default 2048. Measured on a Ryzen 7 5700X3D (AVX-2 only, 64 GB DDR4-2666, 4 KB pages - large pages refused) with IQ3_S decode, 4 rounds interleaved, outputs identical: gate/up phase 13.571 -> 13.024 ms/round (-4.0%) rows 25.1 -> 26.1 GB/s (+1.0) whole round 45.54 -> 44.94 ms/round (-1.3%) and with the pool cold (first round after the arena is built) the round is -2.4%. The same 4 rounds with STRATA_IQ_PREFETCH=0 land within 0.1% of the unpatched binary, so the patch itself costs nothing. native_expert_parity: 0 failures with the prefetch on and off. The non-temporal hint was measured worse than T0 at the same distance (-0.7% vs -1.3%, +0.5 vs +1.0 GB/s), so this keeps T0. 4096 is a little worse than 1024/2048, which is why the default stays 2048 as in the AVX-512 file. --- src/kernels/cpu/iq_avx2.cpp | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/src/kernels/cpu/iq_avx2.cpp b/src/kernels/cpu/iq_avx2.cpp index 05816e9a..790d9dcd 100644 --- a/src/kernels/cpu/iq_avx2.cpp +++ b/src/kernels/cpu/iq_avx2.cpp @@ -19,6 +19,7 @@ #include #include +#include #include namespace strata::kernels::cpu { @@ -77,6 +78,23 @@ inline float hsum8(__m256 v) { return _mm_cvtss_f32(s); } +// E-2 (iq_avx512.cpp) on the AVX-2 path: the pool streams the expert rows from DRAM at ~25 GB/s (4 KB pages +// when large pages are refused), so ask for the bytes a few blocks before the decode needs them - 2048 B is +// two gate/up rows ahead, a row is ~1 KB. Same switch as the AVX-512 kernels: STRATA_IQ_PREFETCH is the +// distance in bytes, 0 = off, default 2048. Measured on a Zen 3 5700X3D (no AVX-512) on IQ3_S decode: -4% on +// the gate/up phase, +1.0 GB/s over the rows, -1.3% ms/round end to end. The non-temporal hint measured +// worse than T0 at the same distance, so this keeps T0. +const int prefetch_ahead = [] { + const char* v = std::getenv("STRATA_IQ_PREFETCH"); + return v ? std::atoi(v) : 2048; +}(); + +inline void rows_ahead(const uint8_t* p) { + if (prefetch_ahead <= 0) return; + _mm_prefetch((const char*) p, _MM_HINT_T0); + _mm_prefetch((const char*) p + 64, _MM_HINT_T0); +} + // ---- per format: one 32-value half (values 64*j + 32*half .. +31) -> grid magnitudes, sign vector, scales template struct Fmt32; @@ -165,6 +183,7 @@ inline void row_dot(const uint8_t* row, int nblocks, const block_q8_K* const* y, for (int t = 0; t < NT; ++t) accf[t] = _mm256_setzero_ps(); for (int i = 0; i < nblocks; ++i) { const uint8_t* blk = row + (size_t) i * Fmt32::bytes; + rows_ahead(blk + prefetch_ahead); __m256i acci[NT]; for (int t = 0; t < NT; ++t) acci[t] = _mm256_setzero_si256(); for (int j = 0; j < 4; ++j) { @@ -229,6 +248,7 @@ inline void row_dot_iq2xs(const uint8_t* row, int nblocks, const block_q8_K* con for (int t = 0; t < NT; ++t) accf[t] = _mm256_setzero_ps(); for (int i = 0; i < nblocks; ++i) { const uint8_t* blk = row + (size_t) i * 74; + rows_ahead(blk + prefetch_ahead); // the 8 scale bytes -> 16 half-scales of 2*s+1, interleaved [a0, b0, a1, b1, ...] (ggml's unpack) __m128i st = _mm_set1_epi64x((long long) u64(blk + 66)); st = _mm_unpacklo_epi8(_mm_and_si128(st, m4), _mm_and_si128(_mm_srli_epi16(st, 4), m4)); @@ -382,6 +402,7 @@ void iq4nl_rows(const uint8_t* w, size_t row_bytes, int n, const block_q8_0* con for (int t = 0; t < NT; ++t) accf[t] = _mm256_setzero_ps(); for (int ib = 0; ib < nb; ++ib) { const uint8_t* blk = row + (size_t) ib * sizeof(block_iq4_nl); + rows_ahead(blk + prefetch_ahead); const __m128i bits = _mm_loadu_si128((const __m128i*) (blk + 2)); const __m128i lo = _mm_and_si128(bits, m4b); // values 0..15 const __m128i hi = _mm_and_si128(_mm_srli_epi16(bits, 4), m4b); // values 16..31 From 18106b1c316660f2f0c064580ae28263682fd97a Mon Sep 17 00:00:00 2001 From: Andy Date: Wed, 30 Sep 2026 07:04:25 +0400 Subject: [PATCH 16/32] prefill: software-pipelined loads in the column-split GDN recurrence (bit-identical; STRATA_GDN_PIPELINE=0 = old kernel) --- src/prefill/kernels.cu | 69 +++++++++++++++++++++++++++++++++++++++++- 1 file changed, 68 insertions(+), 1 deletion(-) diff --git a/src/prefill/kernels.cu b/src/prefill/kernels.cu index fb7418a6..e03343dc 100644 --- a/src/prefill/kernels.cu +++ b/src/prefill/kernels.cu @@ -340,6 +340,66 @@ __global__ void __launch_bounds__(CB * RG) gdn_rec_cols_kernel(float* __restrict #pragma unroll for (int r = 0; r < RPG; ++r) base[r * rs] = s[r]; } +// dual-3090: gdn_rec_cols_kernel with the next token's inputs (q/k rows, v, gate, beta) loaded into registers while +// this token computes (software pipelining). The same arithmetic in the same order: the same bits. CBT = columns +// per block (32: upstream's split; 16: twice the blocks, STRATA_GDN_CB=16). STRATA_GDN_PIPELINE=0: upstream's kernel. +template +__global__ void __launch_bounds__(CBT * RG) gdn_rec_cols_pipe_kernel(float* __restrict__ state, const float* __restrict__ h, + const float* __restrict__ gate, + const float* __restrict__ beta, + float* __restrict__ oc_out, int64_t T) { + constexpr int NT = CBT * RG, LPT = S / NT, NCBT = S / CBT; // threads, q/k rows loaded per thread + __shared__ float sk[S], sq[S], red[RG][CBT]; + const int head = blockIdx.x / NCBT, cb = blockIdx.x % NCBT; + const int c = threadIdx.x, rg = threadIdx.y, tid = rg * CBT + c, col = cb * CBT + c; + const int qh = head % HK; + float s[RPG]; + float* base = state + ((size_t) (rg * RPG) * HV + head) * S + col; + const size_t rs = (size_t) HV * S; +#pragma unroll + for (int r = 0; r < RPG; ++r) s[r] = base[r * rs]; + float nq[LPT], nk[LPT], nv = 0.0f, ng = 0.0f, nb = 0.0f; + auto fetch = [&](int64_t t) { + const float* ht = h + t * C; +#pragma unroll + for (int u = 0; u < LPT; ++u) { nq[u] = ht[qh * S + tid + u * NT]; nk[u] = ht[HK * S + qh * S + tid + u * NT]; } + nv = ht[2 * HK * S + head * S + col]; + ng = gate[t * HV + head]; + nb = beta[t * HV + head]; + }; + if (T > 0) fetch(0); + for (int64_t t = 0; t < T; ++t) { + float cq[LPT], ck[LPT]; +#pragma unroll + for (int u = 0; u < LPT; ++u) { cq[u] = nq[u]; ck[u] = nk[u]; } + const float cv = nv, cg = ng, cbt = nb; + __syncthreads(); +#pragma unroll + for (int u = 0; u < LPT; ++u) { sq[tid + u * NT] = cq[u]; sk[tid + u * NT] = ck[u]; } + __syncthreads(); + if (t + 1 < T) fetch(t + 1); + const float g = __expf(cg); + float kv = 0.0f; +#pragma unroll + for (int r = 0; r < RPG; ++r) kv = fmaf(s[r], sk[rg * RPG + r], kv); + red[rg][c] = kv; + __syncthreads(); + const float kv_col = red[0][c] + red[1][c] + red[2][c] + red[3][c]; + const float delta = (cv - g * kv_col) * cbt; + float o = 0.0f; +#pragma unroll + for (int r = 0; r < RPG; ++r) { + s[r] = fmaf(g, s[r], sk[rg * RPG + r] * delta); + o = fmaf(s[r], sq[rg * RPG + r], o); + } + __syncthreads(); + red[rg][c] = o; + __syncthreads(); + if (rg == 0) oc_out[t * HV * S + head * S + col] = (red[0][c] + red[1][c] + red[2][c] + red[3][c]) * rsqrtf((float) S); + } +#pragma unroll + for (int r = 0; r < RPG; ++r) base[r * rs] = s[r]; +} __global__ void __launch_bounds__(S) gdn_out_norm_kernel(const float* __restrict__ z, const float* __restrict__ gamma, float eps, float* __restrict__ y, uint16_t* __restrict__ y16) { __shared__ float wsum[4]; @@ -636,7 +696,14 @@ void gdn_recurrence(float* state, const float* h, const float* gate, const float if (serial || T <= 0) { gdn_rec_kernel<<>>(state, h, gate, beta, z, gamma, eps, y, y16, T); } else { - gdn_rec_cols_kernel<<>>(state, h, gate, beta, y, T); + static const bool pipe = [] { const char* v = std::getenv("STRATA_GDN_PIPELINE"); return v == nullptr || std::atoi(v) != 0; }(); + static const int cbt = [] { const char* v = std::getenv("STRATA_GDN_CB"); return v != nullptr && std::atoi(v) == 16 ? 16 : 32; }(); + if (pipe && cbt == 16) // dual-3090: the software-pipelined loads, 16 columns per block + gdn_rec_cols_pipe_kernel<16><<>>(state, h, gate, beta, y, T); + else if (pipe) + gdn_rec_cols_pipe_kernel<32><<>>(state, h, gate, beta, y, T); + else + gdn_rec_cols_kernel<<>>(state, h, gate, beta, y, T); gdn_out_norm_kernel<<>>(z, gamma, eps, y, y16); } check("gdn_recurrence"); From 4305fdc3fbb3549ab57d81bfcd7dd561de5d8a57 Mon Sep 17 00:00:00 2001 From: Andy Date: Wed, 30 Sep 2026 07:04:25 +0400 Subject: [PATCH 17/32] decode: QSA block scores read each key block once for all of a window's queries (bit-identical; STRATA_SCORES_MULTI=0 = old grid) --- src/kernels/cuda/qsa_select.cu | 54 ++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/src/kernels/cuda/qsa_select.cu b/src/kernels/cuda/qsa_select.cu index 85b7342c..57fa33da 100644 --- a/src/kernels/cuda/qsa_select.cu +++ b/src/kernels/cuda/qsa_select.cu @@ -429,6 +429,52 @@ __global__ void __launch_bounds__(TK_T) block_topk_reg_kernel(const float* __res } } + +// dual-3090 (session 8): the decode window's scores - every key block read ONCE for all the window's queries (the +// grid above is (max_blocks / 8) x nq: ~24,600 mostly-idle blocks per layer, each key re-read per query). A fixed +// grid strides over the blocks; per (block, query) the same arithmetic in the same order as block_scores_kernel. +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) { + __shared__ __align__(16) float qs[MQ * IDX_HEADS * IDX_DIM]; + __shared__ int64_t s_nkv[MQ], s_nbid[MQ]; + for (int i = threadIdx.x; i < nq * IDX_HEADS * IDX_DIM; i += blockDim.x) qs[i] = q_idx[i]; + if (threadIdx.x < nq) { + s_nkv[threadIdx.x] = steps[threadIdx.x * kStepCount + kStepNKv]; + s_nbid[threadIdx.x] = steps[threadIdx.x * kStepCount + kStepNBid]; + } + __syncthreads(); + int64_t top = 0; + for (int q = 0; q < nq; ++q) top = s_nbid[q] > top ? s_nbid[q] : top; + const int lane = threadIdx.x & 31; + const int64_t wstride = (int64_t) gridDim.x * SCORE_WARPS; + for (int64_t b = (int64_t) blockIdx.x * SCORE_WARPS + (threadIdx.x >> 5); b <= top && b < max_blocks; b += wstride) { + const float4 kp = *reinterpret_cast(pooled + b * IDX_DIM + lane * 4); + const float4 kd = *reinterpret_cast(dead + lane * 4); + for (int qi = 0; qi < nq; ++qi) { + const int64_t n_bid = s_nbid[qi]; + if (b > n_bid) continue; + const float4 k4 = (b == n_bid) ? kd : kp; + const float* q = qs + qi * IDX_HEADS * IDX_DIM + lane * 4; + float score = 0.0f; +#pragma unroll + for (int h = 0; h < IDX_HEADS; ++h) { + const float4 q4 = *reinterpret_cast(q + h * IDX_DIM); + float d = k4.x * q4.x + k4.y * q4.y + k4.z * q4.z + k4.w * q4.w; +#pragma unroll + for (int o = 16; o > 0; o >>= 1) d += __shfl_xor_sync(0xffffffffu, d, o); + score += d > 0.0f ? d : 0.0f; + } + if (lane == 0) { + if (b == n_bid && s_nkv[qi] % R != 0) score += 1e9f; + out[qi * max_blocks + b] = score; + } + } + } +} } // namespace void qsa_block_scores(const float* pooled, const float* dead, const float* q_idx, const int32_t* steps, int64_t nq, @@ -439,6 +485,14 @@ 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) { // the decode window (a captured graph: no active count) + block_scores_multi_kernel<<<256, SCORE_WARPS * 32, 0, (cudaStream_t) stream>>>(pooled, dead, q_idx, steps, (int) nq, + max_blocks, scores); + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) { std::fprintf(stderr, "qsa_block_scores multi: %s\n", cudaGetErrorString(e)); std::exit(1); } + return; + } const int64_t reach = active_blocks > 0 && active_blocks < max_blocks ? active_blocks : max_blocks; const dim3 grid((unsigned) ((reach + SCORE_WARPS - 1) / SCORE_WARPS), (unsigned) nq); block_scores_kernel<<>>(pooled, dead, q_idx, steps, max_blocks, From 05d4cb11a516809dc74266dff756100b32764215 Mon Sep 17 00:00:00 2001 From: Guillaume PUTIER Date: Wed, 30 Sep 2026 07:39:14 +0200 Subject: [PATCH 18/32] sampler: top_k by lexicographic threshold, split over the whole GPU The sampled path (penalties, top_k, top_p, min_p, temperature, draw) kept one row on one SM: sampler_kernel excluded the logits already kept by sweeping the kept list for every logit of every round, O(k^2 x n_vocab) shared-memory compares per row, and ran the double-precision tail on all 1,024 threads. Three implementations now pick the same token: - Split (new default): stage 1 cuts each row into 4,096-logit blocks (61 per row at 248,320 logits), each warp keeps the top_k of its 1,024 penalised logits in registers, and the block merges its four warp lists. Stage 2, one warp per row, merges the block lists and runs the tail on one warp. - sampler_one_block_kernel: one block per row, top_k rounds that each take the logits strictly after the previous pick in the selection order (value descending, id ascending). It is the fallback when the split cannot run (stream under graph capture, vocabulary above 262,144, more than 64 rows, no scratch) and is selectable with STRATA_SAMPLER_ONE_BLOCK=1. - sampler_kernel, the previous kernel, kept unchanged as the reference and selectable with STRATA_OLD_SAMPLER=1. The list, its order and the pick are unchanged: the first k of a union lie within the first k of each part, and a merge of ordered lists is ordered. The tail keeps the same arithmetic, with the exps and quotients shared across one warp and the ordered sums and scans run by lane 0. The block lists live in a per-stream scratch buffer grown on demand. A grown-out buffer is retired rather than freed, and a failed grow is remembered so later calls of that size do not retry cudaMalloc. sampler_parity is the parity test. Fixtures 16 to 18 pin the whole top_k list position by position under ties (+inf, -inf, NaN, +0/-0, sentinel id 0, penalised tokens landing on other tokens' values), tied draws through the whole chain, and the automatic fallbacks (graph capture, row cap). Each pick is an integer token id compared for equality with a host reference. ctest runs the binary once per path: sampler_parity (split), sampler_parity_one_block and sampler_parity_old, so all three paths are held to the same expected ids. hip_compat/cuda_runtime.h: map cudaStreamIsCapturing, cudaStreamCaptureStatus and cudaStreamCaptureStatusNone to their hip equivalents, which the new capture check needs on HIP builds. --- CMakeLists.txt | 6 + include/strata/hip_compat/cuda_runtime.h | 3 + src/kernels/cuda/sampler.cu | 470 ++++++++++++++++++++++- src/kernels/sampler_parity.cpp | 435 ++++++++++++++++++++- 4 files changed, 908 insertions(+), 6 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 28e19d8c..f5acedc1 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -409,6 +409,12 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) target_include_directories(sampler_parity PRIVATE ${_strata_gpu_include_directories}) target_link_libraries(sampler_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) add_test(NAME sampler_parity COMMAND sampler_parity --selftest) + set_tests_properties(sampler_parity PROPERTIES ENVIRONMENT "STRATA_OLD_SAMPLER=0;STRATA_SAMPLER_ONE_BLOCK=0") + # the same fixtures on the other two sampled paths: the one-block kernel and the 0.1.20 kernel + add_test(NAME sampler_parity_one_block COMMAND sampler_parity --selftest) + set_tests_properties(sampler_parity_one_block PROPERTIES ENVIRONMENT "STRATA_OLD_SAMPLER=0;STRATA_SAMPLER_ONE_BLOCK=1") + add_test(NAME sampler_parity_old COMMAND sampler_parity --selftest) + set_tests_properties(sampler_parity_old PROPERTIES ENVIRONMENT "STRATA_OLD_SAMPLER=1;STRATA_SAMPLER_ONE_BLOCK=0") add_executable(rope_parity src/kernels/rope_parity.cpp) target_include_directories(rope_parity PRIVATE ${_strata_gpu_include_directories}) diff --git a/include/strata/hip_compat/cuda_runtime.h b/include/strata/hip_compat/cuda_runtime.h index 7cfe335e..aebe2e8c 100644 --- a/include/strata/hip_compat/cuda_runtime.h +++ b/include/strata/hip_compat/cuda_runtime.h @@ -67,10 +67,13 @@ #define cudaSetDevice hipSetDevice #define cudaStreamBeginCapture hipStreamBeginCapture #define cudaStreamCaptureModeThreadLocal hipStreamCaptureModeThreadLocal +#define cudaStreamCaptureStatus hipStreamCaptureStatus +#define cudaStreamCaptureStatusNone hipStreamCaptureStatusNone #define cudaStreamCreate hipStreamCreate #define cudaStreamCreateWithFlags hipStreamCreateWithFlags #define cudaStreamDestroy hipStreamDestroy #define cudaStreamEndCapture hipStreamEndCapture +#define cudaStreamIsCapturing hipStreamIsCapturing #define cudaStreamNonBlocking hipStreamNonBlocking #define cudaStreamQuery hipStreamQuery #define cudaStreamSynchronize hipStreamSynchronize diff --git a/src/kernels/cuda/sampler.cu b/src/kernels/cuda/sampler.cu index 76a7873e..e7ea426b 100644 --- a/src/kernels/cuda/sampler.cu +++ b/src/kernels/cuda/sampler.cu @@ -10,9 +10,14 @@ // produces a valid token, so only a comparison at the distribution level can tell them apart; the parity test // does that against an independently computed distribution. // -// Both kernels put ONE BLOCK per token over the vocabulary: `sampler_greedy_kernel` is the plain argmax, -// `sampler_kernel` runs the sampled chain as `top_k` block-argmax rounds followed by the top_p / temperature / -// draw chain (its header says why the selection must be parallel and why the tie rule keeps the semantics). +// `sampler_greedy_kernel` is the plain argmax, one block per token over the vocabulary. The sampled chain has +// three implementations that pick the same token, bit for bit: +// - the SPLIT top_k (default): `sampler_split_part_kernel` cuts each row into 4,096-logit blocks over the whole +// GPU, each keeps its own top_k, and `sampler_split_merge_kernel` merges those lists and runs the tail; +// - `sampler_one_block_kernel` (`STRATA_SAMPLER_ONE_BLOCK=1`, and the fallback when the split cannot run): one +// block per token, `top_k` block-argmax rounds, each over the logits after the previous pick; +// - `sampler_kernel` (`STRATA_OLD_SAMPLER=1`), the kernel of engine 0.1.20, kept as the reference. +// The two new ones share `sampled_tail_warp` (top_p / min_p / temperature / draw on one warp). #include "strata/kernels/sampler.hpp" #include @@ -20,6 +25,9 @@ #include #include #include +#include +#include +#include namespace strata::kernels { namespace { @@ -170,6 +178,11 @@ __global__ void sampler_greedy_kernel(const float* __restrict__ logits, int n_vo /// serial scan's strict `>` keeps the first maximum it meets), so the kept sequence - both its set and its /// order - is unchanged; `top_p`'s cut reads that order in double arithmetic as before; temperature and the /// Philox draw apply after the cut. `sampler_parity` pins all of it against the host reference. +/// +/// **KEPT AS THE REFERENCE, BEHIND `STRATA_OLD_SAMPLER=1`.** Two costs remain in it: the `taken` +/// sweep is O(k) per logit per round, O(k^2 x n_vocab) per row (47 M shared-memory compares at k = 20, 500 M at +/// 64), and the double-precision tail runs on all 1,024 threads where one warp suffices - GeForce issues FP64 at +/// 1/64 of FP32. The kernels after this one remove both and select the same list in the same order. __global__ void sampler_kernel(const float* __restrict__ logits, int n_vocab, int n_tokens, const int* __restrict__ history, int history_len, const SamplerParams p, int* __restrict__ out) { @@ -302,6 +315,433 @@ __global__ void sampler_kernel(const float* __restrict__ logits, int n_vocab, in if (threadIdx.x == 0) out[t] = pick; } +// ---- the same list, in the same order, without the `taken` sweep ---- +// +// THE SELECTION ORDER. `sampler_kernel`'s rounds rank a candidate (value, id) before (value', id') when value > +// value', or value == value' and id < id' - each thread's ascending scan keeps the first maximum it meets (strict +// `>`), and the reductions resolve a tie to the lower id. That is a strict total order (-0 and +0 compare equal and +// fall to the id, as there), so round i picks the i-th logit of the order. NaN and -inf are never picked (`s > bv` +// from -inf fails); a round that finds nothing yields the SENTINEL (-inf, n_vocab), stored as id 0. + +constexpr int kSelMax = 64; // the widest top_k list, `sampler_kernel`'s KMAX +constexpr unsigned kFullMask = 0xFFFFFFFFu; + +// top_k 1..64 as given; 0 ("off") and anything wider keep 64; never more than the vocabulary +__host__ __device__ __forceinline__ int sampled_k(int top_k, int n_vocab) { + int k = (top_k > 0 && top_k < kSelMax) ? top_k : kSelMax; + return k > n_vocab ? n_vocab : k; +} + +// (bv, bi) <- the first of (bv, bi) and (ov, oi) in the selection order +__device__ __forceinline__ void take_first(float& bv, int& bi, float ov, int oi) { + if (ov > bv || (ov == bv && oi < bi)) { bv = ov; bi = oi; } +} + +// The first of the warp's 32 candidates, left in EVERY lane. An XOR butterfly is exact here: "the first of two" is +// associative and commutative in a strict total order (two lanes never hold different candidates that compare +// equal - an id is in one lane at most, and two sentinels are the same pair), so every lane ends with the same pair. +__device__ __forceinline__ void warp_first(float& bv, int& bi) { +#pragma unroll + for (int off = 16; off > 0; off >>= 1) { + const float ov = __shfl_xor_sync(kFullMask, bv, off); + const int oi = __shfl_xor_sync(kFullMask, bi, off); + take_first(bv, bi, ov, oi); + } +} + +/// **THE TAIL ON ONE WARP, WITH `sampler_kernel`'S ARITHMETIC.** `sel_ids` / `sel_logit` (shared, `k` entries) are +/// the top_k list in selection order; the 32 lanes of one warp call this and lane 0 writes `out[t]`. The old tail +/// ran on all 1,024 threads, each computing the same ~4k double `exp`s - FP64 issues at 1/64 of FP32 on GeForce. +/// Here the lanes share the `exp`s (one per entry, into `ex`) and then the quotients, and lane 0 alone runs the two +/// ORDERED sums and the two cumulative scans. Every double is the one the old chain computed: the same `exp` of +/// the same argument, the sums in the same order, `cum += e / sum` with the same correctly rounded quotient - so +/// the cut, the survivors and the pick are the same. (`n_keep == 0`, reachable only with min_p > 1, which the +/// callers clamp, read `sel_ids[-1]` in the old tail; it reads `sel_ids[0]` here.) +__device__ void sampled_tail_warp(const int* sel_ids, const float* sel_logit, int k, const SamplerParams& p, int t, + int* __restrict__ out, double* ex) { + const int lane = (int) (threadIdx.x & 31); + const float inv_t = p.temperature > 0.0f ? 1.0f / p.temperature : 0.0f; + int n_keep = k; + float mx = sel_logit[0]; + for (int i = 1; i < k; ++i) mx = fmaxf(mx, sel_logit[i]); + if (p.top_p < 1.0f) { + for (int i = lane; i < k; i += 32) ex[i] = exp((double) sel_logit[i] - (double) mx); + __syncwarp(); + double sum = 0.0; + if (lane == 0) + for (int i = 0; i < k; ++i) sum += ex[i]; + sum = __shfl_sync(kFullMask, sum, 0); + __syncwarp(); // lane 0 has read every `ex` before it is overwritten + for (int i = lane; i < k; i += 32) ex[i] = ex[i] / sum; + __syncwarp(); + int cut = k; + if (lane == 0) { + double cum = 0.0; + for (int i = 0; i < k; ++i) { + cum += ex[i]; + if (cum >= (double) p.top_p) { cut = i + 1; break; } + } + } + cut = __shfl_sync(kFullMask, cut, 0); + if (cut < p.min_keep) cut = p.min_keep < k ? p.min_keep : k; + n_keep = cut; + __syncwarp(); // `ex` is written again below + } + // min_p on top_p's survivors, as in `sampler_kernel` (every lane, the same float arithmetic) + if (p.min_p > 0.0f) { + const float thresh = sel_logit[0] + logf(p.min_p); + for (int i = 0; i < n_keep; ++i) + if (sel_logit[i] < thresh) { n_keep = i; break; } + } + // temperature, then one Philox draw + float smx = sel_logit[0] * inv_t; + for (int i = 1; i < n_keep; ++i) smx = fmaxf(smx, sel_logit[i] * inv_t); + for (int i = lane; i < n_keep; i += 32) ex[i] = exp((double) (sel_logit[i] * inv_t) - (double) smx); + __syncwarp(); + double sum = 0.0; + if (lane == 0) + for (int i = 0; i < n_keep; ++i) sum += ex[i]; + sum = __shfl_sync(kFullMask, sum, 0); + __syncwarp(); + for (int i = lane; i < n_keep; i += 32) ex[i] = ex[i] / sum; + __syncwarp(); + if (lane == 0) { + const float u = philox_uniform(p.seed, p.counter + (uint64_t) t); + double cum = 0.0; + int pick = sel_ids[n_keep > 0 ? n_keep - 1 : 0]; + for (int i = 0; i < n_keep; ++i) { + cum += ex[i]; + if ((double) u < cum) { pick = sel_ids[i]; break; } + } + out[t] = pick; + } +} + +/// **THE ONE-BLOCK SAMPLED PATH: `sampler_kernel` WITHOUT THE `taken` SWEEP.** Round i's candidates are the logits +/// strictly AFTER round i-1's pick in the selection order, `s < prev_v || (s == prev_v && v > prev_i)`, which is +/// exactly the set `taken` left: the picks so far are the first i of the order, so what comes after the last one is +/// what has not been picked. The round is then the same block argmax with the same tie rule, so the list is the +/// same list in the same order. An empty round leaves (-inf, id 0) as before, and every round after it is empty +/// in both versions (nothing after -inf beats -inf). O(k x n_vocab) per row instead of O(k^2 x n_vocab), then warp +/// 0 runs the tail. `STRATA_SAMPLER_ONE_BLOCK=1`, and the fallback when the split path cannot run. +__global__ void __launch_bounds__(1024) +sampler_one_block_kernel(const float* __restrict__ logits, int n_vocab, const int* __restrict__ history, + int history_len, const SamplerParams p, int* __restrict__ out) { + const int t = blockIdx.x; + const float* l = logits + (size_t) t * n_vocab; + + // the penalty window and its membership bitmap, exactly as in `sampler_kernel` + const int* hrow = history ? history + (size_t) t * history_len : nullptr; + int hlen = 0; + if (hrow) { + hlen = p.penalty_last_n < history_len ? p.penalty_last_n : history_len; + if (hlen < 0) hlen = 0; + hrow += history_len - hlen; // the window is the TAIL + } + extern __shared__ unsigned int penal_bits[]; + const int bits_words = (int) ((n_vocab + 31) / 32); + const bool use_bits = hrow != nullptr && hlen > 0 && bits_words > 0; + if (use_bits) { + for (int w = threadIdx.x; w < bits_words; w += blockDim.x) penal_bits[w] = 0u; + __syncthreads(); + for (int i = threadIdx.x; i < hlen; i += blockDim.x) + if (hrow[i] >= 0 && hrow[i] < n_vocab) // an id outside the vocabulary is never a candidate + atomicOr(&penal_bits[hrow[i] >> 5], 1u << (hrow[i] & 31)); + __syncthreads(); + } + auto hit_count = [&](int v) -> int { + if (!use_bits || !(penal_bits[v >> 5] & (1u << (v & 31)))) return 0; + return history_count(hrow, hlen, v); + }; + + const int k = sampled_k(p.top_k, n_vocab); + __shared__ int sel_ids[kSelMax]; + __shared__ float sel_logit[kSelMax]; + __shared__ double ex[kSelMax]; + __shared__ float sv[32]; + __shared__ int si[32]; + const int warp = (int) (threadIdx.x >> 5), lane = (int) (threadIdx.x & 31); + float prev_v = __int_as_float(0x7f800000); // +inf and id -1: round 0 takes every logit + int prev_i = -1; + for (int i = 0; i < k; ++i) { + float bv = __int_as_float(0xff800000); // -inf + int best = n_vocab; + for (int v = threadIdx.x; v < n_vocab; v += blockDim.x) { + const float s = apply_penalties(l[v], hit_count(v), p); + if ((s < prev_v || (s == prev_v && v > prev_i)) && s > bv) { bv = s; best = v; } + } + for (int off = 16; off > 0; off >>= 1) { + const float ov = __shfl_down_sync(0xFFFFFFFFu, bv, off); + const int oi = __shfl_down_sync(0xFFFFFFFFu, best, off); + if (ov > bv || (ov == bv && oi < best)) { bv = ov; best = oi; } + } + if (lane == 0) { sv[warp] = bv; si[warp] = best; } + __syncthreads(); + if (warp == 0) { + const int nw = (int) ((blockDim.x + 31) >> 5); + float wv = lane < nw ? sv[lane] : __int_as_float(0xff800000); + int wi = lane < nw ? si[lane] : n_vocab; + for (int off = 16; off > 0; off >>= 1) { + const float ov = __shfl_down_sync(0xFFFFFFFFu, wv, off); + const int oi = __shfl_down_sync(0xFFFFFFFFu, wi, off); + if (ov > wv || (ov == wv && oi < wi)) { wv = ov; wi = oi; } + } + if (lane == 0) { sel_ids[i] = (wi < n_vocab) ? wi : 0; sel_logit[i] = wv; } + } + __syncthreads(); + // An empty round leaves (-inf, 0): nothing comes after it, as nothing was left untaken. + prev_v = sel_logit[i]; + prev_i = sel_ids[i]; + } + if (warp != 0) return; + sampled_tail_warp(sel_ids, sel_logit, k, p, t, out, ex); +} + +// ---- THE SPLIT top_k. `sampler_kernel` and the one-block kernel keep a row on ONE SM of 170 (5090) and walk its +// 248,320 logits k times. Here a warp keeps the top_k of 1,024 logits held in registers, four warps make a block of +// 4,096 logits that merges their lists, and a row is 61 such blocks over the whole GPU; one warp per row then +// merges the 61 lists and runs the tail. Exact, because the first k of a union are within the first k of each part +// and a merge of ordered lists is ordered - the selection order being a strict total order (above). +constexpr int kSplitPerLane = 32; // logits per lane, in registers +constexpr int kSplitWarpSpan = 32 * kSplitPerLane; // 1,024 logits per warp +constexpr int kSplitWarps = 4; +constexpr int kSplitBlockSpan = kSplitWarps * kSplitWarpSpan; // 4,096 logits per block +constexpr int kSplitMaxBlocks = 64; // lists the merge holds: n_vocab <= 262,144 +constexpr int kSplitMaxRows = 64; // rows per split launch (the scratch's bound) + +/// Merge `nl` (<= 64) lists of `k` candidates - list L at `lists[L * stride]`, each in the selection order and +/// padded with sentinels - into their first `k`: `sink(i, value, id)` runs in every lane for i = 0..k-1 with the +/// same pair. Lane owns lists `lane` and `lane + 32`; a round takes the first of all heads and advances the list +/// it came from. An id is in one list at most (the lists cover disjoint logits), so exactly one head matches. +template +__device__ __forceinline__ void warp_merge_lists(const int2* lists, int nl, int stride, int k, int n_vocab, + Sink&& sink) { + const int lane = (int) (threadIdx.x & 31); + float hv[2]; + int hi[2], pos[2]; +#pragma unroll + for (int m = 0; m < 2; ++m) { + const int L = lane + 32 * m; + pos[m] = 0; + hv[m] = __int_as_float(0xff800000); + hi[m] = n_vocab; + if (L < nl) { + const int2 c = lists[(size_t) L * stride]; + hi[m] = c.x; + hv[m] = __int_as_float(c.y); + } + } + for (int i = 0; i < k; ++i) { + float bv = hv[0]; + int bi = hi[0]; + take_first(bv, bi, hv[1], hi[1]); + warp_first(bv, bi); + sink(i, bv, bi); + if (bi < n_vocab) { +#pragma unroll + for (int m = 0; m < 2; ++m) { + if (hi[m] != bi) continue; + if (++pos[m] < k) { + const int2 c = lists[(size_t) (lane + 32 * m) * stride + pos[m]]; + hi[m] = c.x; + hv[m] = __int_as_float(c.y); + } else { + hi[m] = n_vocab; + hv[m] = __int_as_float(0xff800000); + } + } + } + } +} + +/// **SPLIT STAGE 1: THE top_k OF EACH 4,096-LOGIT BLOCK.** Grid (blocks per row, rows), 128 threads. Each warp +/// loads its 1,024 penalised logits once into registers (lane + 32 j: every load is one coalesced 128-byte line) +/// and runs `k` warp-argmax rounds over them with the threshold of `sampler_one_block_kernel` - no shared memory +/// and no block barrier per round. Warp 0 then merges the four warp lists into the block's list in `cand` +/// (row-major: row t, block b, entry i at `(t * n_blocks + b) * k + i`, as (id, value bits)). +__global__ void __launch_bounds__(kSplitWarps * 32) +sampler_split_part_kernel(const float* __restrict__ logits, int n_vocab, const int* __restrict__ history, + int history_len, const SamplerParams p, int k, int n_blocks, int2* __restrict__ cand) { + const int t = blockIdx.y; + const float* l = logits + (size_t) t * n_vocab; + const int warp = (int) (threadIdx.x >> 5), lane = (int) (threadIdx.x & 31); + const int blo = (int) blockIdx.x * kSplitBlockSpan; + + const int* hrow = history ? history + (size_t) t * history_len : nullptr; + int hlen = 0; + if (hrow) { + hlen = p.penalty_last_n < history_len ? p.penalty_last_n : history_len; + if (hlen < 0) hlen = 0; + hrow += history_len - hlen; // the window is the TAIL + } + // The membership bitmap of THIS BLOCK'S 4,096 logits (512 bytes, not the vocabulary's 31 KB): the same test, + // and a hit pays the same exact count over the whole window. + __shared__ unsigned int bits[kSplitBlockSpan / 32]; + const bool use_bits = hrow != nullptr && hlen > 0; + if (use_bits) { + for (int w = threadIdx.x; w < kSplitBlockSpan / 32; w += blockDim.x) bits[w] = 0u; + __syncthreads(); + for (int i = threadIdx.x; i < hlen; i += blockDim.x) { + const int h = hrow[i]; + if (h >= 0 && h < n_vocab && h >= blo && h - blo < kSplitBlockSpan) + atomicOr(&bits[(h - blo) >> 5], 1u << ((h - blo) & 31)); + } + __syncthreads(); + } + + // This warp's logits, penalised: `apply_penalties` with a zero count returns the logit unchanged, so only the + // bitmap's hits go through it. Past the vocabulary: -inf, which no round picks. + const int lo = blo + warp * kSplitWarpSpan; + float s[kSplitPerLane]; +#pragma unroll + for (int j = 0; j < kSplitPerLane; ++j) { + const int v = lo + 32 * j + lane; + s[j] = v < n_vocab ? l[v] : __int_as_float(0xff800000); + } + if (use_bits) { +#pragma unroll + for (int j = 0; j < kSplitPerLane; ++j) { + const int v = lo + 32 * j + lane, b = v - blo; + if (v < n_vocab && (bits[b >> 5] & (1u << (b & 31)))) + s[j] = apply_penalties(s[j], history_count(hrow, hlen, v), p); + } + } + + __shared__ int2 wl[kSplitWarps][kSelMax]; + float prev_v = __int_as_float(0x7f800000); // +inf and id -1: round 0 takes every logit + int prev_i = -1; + int i = 0; + for (; i < k; ++i) { + // two chains (even and odd j), each walked in ascending id with a strict `>`, so each keeps its first in + // the order; `take_first` then orders the two + float b0 = __int_as_float(0xff800000), b1 = __int_as_float(0xff800000); + int i0 = n_vocab, i1 = n_vocab; +#pragma unroll + for (int j = 0; j < kSplitPerLane; j += 2) { + const int v0 = lo + 32 * j + lane, v1 = v0 + 32; + const float x0 = s[j], x1 = s[j + 1]; + if ((x0 < prev_v || (x0 == prev_v && v0 > prev_i)) && x0 > b0) { b0 = x0; i0 = v0; } + if ((x1 < prev_v || (x1 == prev_v && v1 > prev_i)) && x1 > b1) { b1 = x1; i1 = v1; } + } + take_first(b0, i0, b1, i1); + warp_first(b0, i0); + if (i0 >= n_vocab) break; // the same in every lane: nothing left in these 1,024 logits + if (lane == 0) wl[warp][i] = make_int2(i0, __float_as_int(b0)); + prev_v = b0; + prev_i = i0; + } + for (int r = i + lane; r < k; r += 32) wl[warp][r] = make_int2(n_vocab, (int) 0xff800000u); // sentinels + __syncthreads(); + if (warp == 0) { + int2* dst = cand + ((size_t) t * n_blocks + blockIdx.x) * k; + warp_merge_lists(&wl[0][0], kSplitWarps, kSelMax, k, n_vocab, [&](int r, float v, int id) { + if (lane == 0) dst[r] = make_int2(id, __float_as_int(v)); + }); + } +} + +/// **SPLIT STAGE 2: ONE WARP PER ROW MERGES THE BLOCK LISTS, THEN RUNS THE TAIL.** The row's lists (at most 64 x +/// 64 entries, 32 KB) are copied to shared memory, merged into the row's top_k list, and `sampled_tail_warp` picks. +__global__ void __launch_bounds__(32) +sampler_split_merge_kernel(const int2* __restrict__ cand, int n_blocks, int n_vocab, const SamplerParams p, int k, + int* __restrict__ out) { + const int t = blockIdx.x; + const int lane = (int) threadIdx.x; + __shared__ int2 lists[kSplitMaxBlocks * kSelMax]; + __shared__ int sel_ids[kSelMax]; + __shared__ float sel_logit[kSelMax]; + __shared__ double ex[kSelMax]; + const int2* src = cand + (size_t) t * n_blocks * k; + for (int e = lane; e < n_blocks * k; e += 32) lists[e] = src[e]; + __syncwarp(); + warp_merge_lists(lists, n_blocks, k, k, n_vocab, [&](int i, float v, int id) { + if (lane == 0) { sel_ids[i] = id < n_vocab ? id : 0; sel_logit[i] = v; } + }); + __syncwarp(); + sampled_tail_warp(sel_ids, sel_logit, k, p, t, out, ex); +} + +// Which sampled path runs, read once: `STRATA_OLD_SAMPLER=1` is `sampler_kernel` (engine 0.1.20), +// `STRATA_SAMPLER_ONE_BLOCK=1` the one-block kernel; by default the split top_k wherever it applies. +enum class SampledPath { Split, OneBlock, Old }; + +bool env_flag(const char* name) { + const char* e = std::getenv(name); + return e != nullptr && *e != '\0' && std::strcmp(e, "0") != 0; +} + +SampledPath sampled_path() { + static const SampledPath path = env_flag("STRATA_OLD_SAMPLER") ? SampledPath::Old + : env_flag("STRATA_SAMPLER_ONE_BLOCK") ? SampledPath::OneBlock + : SampledPath::Split; + return path; +} + +// A stream being captured into a graph must not reach `split_scratch` (cudaMalloc): it +// gets the one-block kernel, which needs no memory of its own. The legacy stream cannot be captured. +bool stream_capturing(void* stream) { + if (stream == nullptr) return false; + cudaStreamCaptureStatus st = cudaStreamCaptureStatusNone; + if (cudaStreamIsCapturing((cudaStream_t) stream, &st) != cudaSuccess) { + (void) cudaGetLastError(); + return true; + } + return st != cudaStreamCaptureStatusNone; +} + +// The split's block lists, one buffer per (device, stream): launches on one stream run in order, so a stream reuses +// its buffer with no sync, and two streams never share one. Grown on demand (at least doubling, up to the size of +// `kSplitMaxRows` rows at the widest vocabulary: 2 MB), never shrunk. A grown-out buffer is retired, not freed: a +// pointer handed out earlier (to another host thread on the same stream, say) may still be waiting for its launch, +// and freeing it would need a sync that proves nothing about that thread. Doubling keeps a slot's retired buffers +// smaller than its live one, so a slot holds about 4 MB at most (0.5 MB for the engine's <= 16 rows). nullptr +// when the memory cannot be had, and the caller falls back to the one-block kernel; a failed grow is remembered, so +// later calls of that size do not retry cudaMalloc each time. +int2* split_scratch(void* stream, size_t entries) { + struct Slot { + int device; + void* stream; + int2* ptr; + size_t entries; + size_t failed; // the smallest size cudaMalloc refused (0: none) + }; + static std::mutex mu; + static std::vector slots; + static std::vector retired; + int device = 0; + if (cudaGetDevice(&device) != cudaSuccess) { + (void) cudaGetLastError(); + return nullptr; + } + std::lock_guard lock(mu); + Slot* slot = nullptr; + for (Slot& s : slots) + if (s.device == device && s.stream == stream) slot = &s; + if (slot == nullptr) { + slots.push_back({device, stream, nullptr, 0, 0}); + slot = &slots.back(); + } + if (slot->entries >= entries) return slot->ptr; + if (slot->failed != 0 && entries >= slot->failed) return nullptr; + constexpr size_t kCap = (size_t) kSplitMaxRows * kSplitMaxBlocks * kSelMax; + size_t want = 2 * slot->entries < kCap ? 2 * slot->entries : kCap; + if (want < entries) want = entries; + int2* ptr = nullptr; + if (cudaMalloc(&ptr, want * sizeof(int2)) != cudaSuccess) { + (void) cudaGetLastError(); + want = entries; + if (cudaMalloc(&ptr, want * sizeof(int2)) != cudaSuccess) { + (void) cudaGetLastError(); + slot->failed = entries; + return nullptr; + } + } + if (slot->ptr != nullptr) retired.push_back(slot->ptr); + slot->ptr = ptr; + slot->entries = want; + return ptr; +} + } // namespace void sample_tokens(const float* logits, int n_tokens, int n_vocab, const int* history, int history_len, @@ -320,11 +760,33 @@ void sample_tokens(const float* logits, int n_tokens, int n_vocab, const int* hi const int gthreads = 1024; sampler_greedy_kernel<<<(unsigned) n_tokens, gthreads, shmem, (cudaStream_t) stream>>>( logits, n_vocab, history, history_len, p, p.penalty_last_n, p.penalty_last_n, out); - } else { + } else if (sampled_path() == SampledPath::Old) { // The same block-per-token shape: the selection's k argmax rounds reduce inside the block. See // `sampler_kernel`'s header for what the old one-thread-per-token launch cost. sampler_kernel<<<(unsigned) n_tokens, 1024, shmem, (cudaStream_t) stream>>>( logits, n_vocab, n_tokens, history, history_len, p, out); + } else { + // The split top_k by default: stage 1 over (61 blocks x rows) for 248,320 logits, stage 2 one warp per + // row. The one-block kernel when asked for, or when the split cannot run: a wider vocabulary than the merge + // holds, more than `kSplitMaxRows` rows (the engine samples at most a verify window), a stream under capture, + // no scratch. + const int k = sampled_k(p.top_k, n_vocab); + const int n_blocks = (n_vocab + kSplitBlockSpan - 1) / kSplitBlockSpan; + int2* scratch = nullptr; + if (sampled_path() == SampledPath::Split && n_blocks <= kSplitMaxBlocks && n_tokens <= kSplitMaxRows && + !stream_capturing(stream)) + // sized for 16 rows and 64 entries at least, so a verify window or a wider top_k does not regrow it + scratch = split_scratch(stream, (size_t) (n_tokens > 16 ? n_tokens : 16) * n_blocks * kSelMax); + if (scratch != nullptr) { + sampler_split_part_kernel<<>>(logits, n_vocab, history, history_len, p, k, + n_blocks, scratch); + sampler_split_merge_kernel<<<(unsigned) n_tokens, 32, 0, (cudaStream_t) stream>>>( + scratch, n_blocks, n_vocab, p, k, out); + } else { + sampler_one_block_kernel<<<(unsigned) n_tokens, 1024, shmem, (cudaStream_t) stream>>>( + logits, n_vocab, history, history_len, p, out); + } } const cudaError_t e = cudaGetLastError(); if (e != cudaSuccess) { diff --git a/src/kernels/sampler_parity.cpp b/src/kernels/sampler_parity.cpp index 4a7d5901..2351722b 100644 --- a/src/kernels/sampler_parity.cpp +++ b/src/kernels/sampler_parity.cpp @@ -17,6 +17,7 @@ #include #include #include +#include #include #include #include @@ -264,13 +265,191 @@ int sampled_cut(const std::vector& l, const std::vector& hist, const return cut; } +// ---- the kernel's own semantics, for the fixtures ---- +// +// `sampled_reference` picks the first unpicked logit even when it is -inf or NaN; the kernels never pick either, and +// a round that finds nothing stores id 0 with a -inf logit (and later rounds treat id 0 as taken, as `sampler_kernel` +// does). The mirror below follows the kernels, so rows with -inf, NaN, +inf and more requested than finite logits +// can be pinned exactly. On rows without those it is `sampled_reference`. +struct SelList { + std::vector ids; + std::vector logit; +}; + +// The top_k list of `sampler_kernel` for one row: `window` is the counted history (the row's last penalty_last_n). +SelList mirror_select(const float* l, int nv, const std::vector& window, const strata::kernels::SamplerParams& p, + int k) { + std::vector s((size_t) nv); + for (int v = 0; v < nv; ++v) { + int c = 0; + for (int h : window) c += h == v; + float x = l[v]; + if (c > 0) { + if (x <= 0.0f) x *= p.penalty_repeat; else x /= p.penalty_repeat; + x -= (float) c * p.penalty_freq + (c > 0 ? 1.0f : 0.0f) * p.penalty_present; + } + s[(size_t) v] = x; + } + SelList out; + std::vector taken((size_t) nv, 0); + for (int i = 0; i < k; ++i) { + int best = nv; + float bv = -std::numeric_limits::infinity(); + for (int v = 0; v < nv; ++v) + if (!taken[(size_t) v] && s[(size_t) v] > bv) { bv = s[(size_t) v]; best = v; } + const int id = best < nv ? best : 0; + taken[(size_t) id] = 1; + out.ids.push_back(id); + out.logit.push_back(bv); + } + return out; +} + +// The tail of `sampler_kernel` over a list (its first `k` entries): top_p, min_p, temperature, the Philox draw. +int mirror_pick(const SelList& sel, int k, const strata::kernels::SamplerParams& p, int row) { + int n_keep = k; + float mx = sel.logit[0]; + for (int i = 1; i < k; ++i) mx = std::fmax(mx, sel.logit[(size_t) i]); + if (p.top_p < 1.0f) { + double sum = 0.0; + for (int i = 0; i < k; ++i) sum += std::exp((double) sel.logit[(size_t) i] - (double) mx); + double cum = 0.0; + int cut = k; + for (int i = 0; i < k; ++i) { + cum += std::exp((double) sel.logit[(size_t) i] - (double) mx) / sum; + if (cum >= (double) p.top_p) { cut = i + 1; break; } + } + if (cut < p.min_keep) cut = p.min_keep < k ? p.min_keep : k; + n_keep = cut; + } + if (p.min_p > 0.0f) { + const float thresh = sel.logit[0] + std::log(p.min_p); + for (int i = 0; i < n_keep; ++i) + if (sel.logit[(size_t) i] < thresh) { n_keep = i; break; } + } + const float inv_t = p.temperature > 0.0f ? 1.0f / p.temperature : 0.0f; + auto scaled = [&](int i) { return sel.logit[(size_t) i] * inv_t; }; + float smx = scaled(0); + for (int i = 1; i < n_keep; ++i) smx = std::fmax(smx, scaled(i)); + double sum = 0.0; + for (int i = 0; i < n_keep; ++i) sum += std::exp((double) scaled(i) - (double) smx); + const float u = host_philox_uniform(p.seed, p.counter + (uint64_t) row); + double cum = 0.0; + int pick = sel.ids[(size_t) (n_keep > 0 ? n_keep - 1 : 0)]; + for (int i = 0; i < n_keep; ++i) { + cum += std::exp((double) scaled(i) - (double) smx) / sum; + if ((double) u < cum) { pick = sel.ids[(size_t) i]; break; } + } + return pick; +} + +int sampled_k(int top_k, int nv) { return std::min(nv, (top_k > 0 && top_k < 64) ? top_k : 64); } + +// Rows uploaded once and sampled under many parameter sets: `sample` returns the picks of one launch on `stream` +// (nullptr: the legacy stream), -1 prefilled as in `run`. +struct DeviceRows { + float* l = nullptr; + int* h = nullptr; + int* o = nullptr; + int n_tokens = 0, nv = 0, hist_len = 0; + DeviceRows(const std::vector& logits, int n_tokens_, const std::vector& hist, int hist_len_) + : n_tokens(n_tokens_), nv((int) (logits.size() / (size_t) n_tokens_)), hist_len(hist_len_) { + check(cudaMalloc(&l, logits.size() * sizeof(float)), "malloc logits"); + check(cudaMalloc(&o, (size_t) n_tokens * sizeof(int)), "malloc out"); + check(cudaMemcpy(l, logits.data(), logits.size() * sizeof(float), cudaMemcpyHostToDevice), "copy"); + if (hist_len > 0) { + check(cudaMalloc(&h, hist.size() * sizeof(int)), "malloc hist"); + check(cudaMemcpy(h, hist.data(), hist.size() * sizeof(int), cudaMemcpyHostToDevice), "copy hist"); + } + } + DeviceRows(const DeviceRows&) = delete; + DeviceRows& operator=(const DeviceRows&) = delete; + ~DeviceRows() { + cudaFree(l); + cudaFree(o); + if (h) cudaFree(h); + } + std::vector sample(const strata::kernels::SamplerParams& p, cudaStream_t stream) { + check(cudaMemset(o, 0xFF, (size_t) n_tokens * sizeof(int)), "fill out"); + strata::kernels::sample_tokens(l, n_tokens, nv, h, hist_len, p, o, stream); + if (stream != nullptr) check(cudaStreamSynchronize(stream), "stream sync"); + std::vector got((size_t) n_tokens); + check(cudaMemcpy(got.data(), o, got.size() * sizeof(int), cudaMemcpyDeviceToHost), "back"); + return got; + } +}; + +// The counted window of row t: the last min(penalty_last_n, hist_len) entries (none without penalties). +std::vector window_of(const std::vector& hist, int hist_len, int t, int last_n) { + if (hist_len <= 0 || last_n <= 0) return {}; + const int h = std::min(last_n, hist_len); + const int* row = hist.data() + (size_t) t * hist_len; + return std::vector(row + (hist_len - h), row + hist_len); +} + +// `--bench`: the sampled path alone at the engine's vocabulary, per call, on the path the environment selects. +void bench_sampled() { + const int NV = 248320; + cudaStream_t s = nullptr; + check(cudaStreamCreate(&s), "stream"); + std::mt19937 rng(20); + std::normal_distribution g(0.0f, 3.0f); + for (int T : {1, 4, 8}) { + std::vector l((size_t) NV * T); + for (auto& v : l) v = g(rng); + float* d_l = nullptr; + int* d_o = nullptr; + check(cudaMalloc(&d_l, l.size() * sizeof(float)), "bench logits"); + check(cudaMalloc(&d_o, (size_t) T * sizeof(int)), "bench out"); + check(cudaMemcpy(d_l, l.data(), l.size() * sizeof(float), cudaMemcpyHostToDevice), "bench copy"); + for (int k : {20, 64}) { + strata::kernels::SamplerParams p; + p.top_k = k; p.top_p = 0.95f; p.temperature = 0.7f; p.seed = 1; + for (int w = 0; w < 3; ++w) strata::kernels::sample_tokens(d_l, T, NV, nullptr, 0, p, d_o, s); + check(cudaStreamSynchronize(s), "bench warmup"); + cudaEvent_t e0, e1; + check(cudaEventCreate(&e0), "event"); + check(cudaEventCreate(&e1), "event"); + const int iters = 50; + check(cudaEventRecord(e0, s), "record"); + for (int it = 0; it < iters; ++it) { + p.counter = (uint64_t) it; + strata::kernels::sample_tokens(d_l, T, NV, nullptr, 0, p, d_o, s); + } + check(cudaEventRecord(e1, s), "record"); + check(cudaEventSynchronize(e1), "bench sync"); + float ms = 0.0f; + check(cudaEventElapsedTime(&ms, e0, e1), "elapsed"); + std::printf(" bench: n_vocab %d, rows %d, top_k %2d, top_p 0.95: %8.1f us per call\n", NV, T, k, + 1000.0 * (double) ms / iters); + cudaEventDestroy(e0); + cudaEventDestroy(e1); + } + cudaFree(d_l); + cudaFree(d_o); + } + cudaStreamDestroy(s); +} + } // namespace int main(int argc, char** argv) { - bool selftest = false; + bool selftest = false, bench = false; for (int i = 1; i < argc; ++i) { if (std::string(argv[i]) == "--selftest") selftest = true; - else { std::fprintf(stderr, "usage: sampler_parity [--selftest]\n"); return 2; } + else if (std::string(argv[i]) == "--bench") bench = true; + else { std::fprintf(stderr, "usage: sampler_parity [--selftest] [--bench]\n"); return 2; } + } + { + // the sampled path under test; ctest runs this binary once per path + auto on = [](const char* n) { const char* e = std::getenv(n); return e && *e && std::strcmp(e, "0") != 0; }; + std::printf(" sampled path: %s\n", on("STRATA_OLD_SAMPLER") ? "sampler_kernel (STRATA_OLD_SAMPLER)" + : on("STRATA_SAMPLER_ONE_BLOCK") ? "one block (STRATA_SAMPLER_ONE_BLOCK)" + : "split top_k (default)"); + } + if (bench) { + bench_sampled(); + return 0; } int bad = 0; const int NV = 512, NT = 4; @@ -846,6 +1025,258 @@ int main(int argc, char** argv) { cudaFree(input); cudaFree(output); } + // ---- fixture 16: THE WHOLE top_k LIST, POSITION BY POSITION, UNDER TIES. A pick shows the list + // through one draw; this reads the list itself. Every row holds a +inf logit, so the tail's arithmetic is NaN + // (inf - inf), no cut fires and no draw lands: the chain returns its LAST kept entry, sel_ids[k - 1]. Launching + // top_k = 1..64 then reads the list one position at a time - its set and its order. The rows make the order + // rest on the tie rule: hundreds of logits share the top finite values, spread over every split block, warp and + // lane; -0 and +0 tie; -inf and NaN are mixed in; a row has fewer finite logits than 64 (the sentinel id 0 must + // come out); a penalised row lands its penalised tokens exactly on other tokens' values. Vocabularies: the + // engine's 248,320 (a partial last split block), 100,003, 262,144 (the widest split), 262,145 (one more: the + // one-block fallback) and 1,000. + { + const float inf = std::numeric_limits::infinity(); + const float qnan = std::numeric_limits::quiet_NaN(); + int wrong = 0, probes = 0, sentinels = 0; + for (int nv : {248320, 100003, 262144, 262145, 1000}) { + const int T = 4, H = 64; + std::mt19937 rng((unsigned) (1600 + nv)); + std::normal_distribution g(0.0f, 1.0f); + std::vector l((size_t) nv * T); + for (auto& v : l) v = std::floor(g(rng) * 4.0f) / 4.0f; // quarter steps: ties everywhere + auto spread = [&](int j) { return (int) (((int64_t) j * 7919 + 13) % nv); }; + // row 0: 20 logits at 6.25 and 300 at 6.0 over the whole row, two +inf + float* r0 = l.data(); + for (int j = 0; j < 320; ++j) r0[spread(j)] = j < 20 ? 6.25f : 6.0f; + r0[nv / 2] = inf; + r0[nv - 1] = inf; + // row 1: nothing above 0, every zero signed by its id's parity (-0 at even ids), one +inf + float* r1 = l.data() + (size_t) nv; + for (int v = 0; v < nv; ++v) { + r1[v] = -std::fabs(r1[v]); + if (r1[v] == 0.0f) r1[v] = (v & 1) ? 0.0f : -0.0f; + } + r1[3] = inf; + // row 2: -inf everywhere but ten finite logits (two values), two NaN and a +inf: 11 candidates in all + float* r2 = l.data() + (size_t) 2 * nv; + for (int v = 0; v < nv; ++v) r2[v] = -inf; + for (int j = 0; j < 10; ++j) r2[spread(j + 400)] = j < 5 ? 1.0f : 0.5f; + r2[spread(500)] = qnan; + r2[spread(501)] = qnan; + r2[spread(502)] = inf; + // row 3: penalties. Window ids on block and warp edges, repeats, and ids outside the vocabulary; the + // penalised tokens sit at 9.0, which repeat 2 / freq 0.25 / present 0.5 turns into 4.0 - 0.25 x count + // (3.75, 3.5, ...), values the quarter-step logits share. + float* r3 = l.data() + (size_t) 3 * nv; + std::vector hist((size_t) T * H, -1); + int* h3 = hist.data() + (size_t) 3 * H; + const int edges[] = {0, 1023, 1024, 4095, 4096, 8191, 8192, 12345, nv / 2 + 1, nv - 2}; + int hn = 0; + for (int e : edges) + if (e < nv && e != nv / 2) { + h3[hn++] = e; + if (hn % 3 == 0) h3[hn++] = e; // counted twice + r3[e] = 9.0f; + } + h3[hn++] = nv; // ignored: outside + h3[hn++] = nv + 77; + h3[hn++] = -5; + for (int j = 0; j < 30; ++j) r3[spread(j + 600)] = j < 15 ? 3.75f : 3.5f; + r3[nv / 2] = inf; // not in the window + + strata::kernels::SamplerParams base; + base.top_p = 1.0f; base.min_p = 0.0f; base.temperature = 0.8f; base.seed = 16; + base.penalty_last_n = H; base.penalty_repeat = 2.0f; base.penalty_freq = 0.25f; + base.penalty_present = 0.5f; + const int kmax = sampled_k(64, nv); + std::vector lists; + for (int t = 0; t < T; ++t) + lists.push_back(mirror_select(l.data() + (size_t) t * nv, nv, window_of(hist, H, t, H), base, kmax)); + DeviceRows rows(l, T, hist, H); + for (int top_k = 0; top_k <= 66; ++top_k) { + strata::kernels::SamplerParams p = base; + p.top_k = top_k == 65 ? 100 : top_k == 66 ? -3 : top_k; // 0, 100 and -3 mean 64 + p.top_p = (top_k & 1) ? 0.5f : 1.0f; // both tail branches (NaN: no cut) + p.counter = (uint64_t) top_k; + const int k = sampled_k(p.top_k, nv); + const std::vector got = rows.sample(p, nullptr); + for (int t = 0; t < T; ++t) { + const int want = lists[(size_t) t].ids[(size_t) (k - 1)]; + sentinels += (t == 2 && k > 11); + ++probes; + if (got[(size_t) t] != want) { + if (wrong < 8) + std::printf(" n_vocab %d row %d top_k %d: position %d want id %d got %d\n", nv, t, + p.top_k, k - 1, want, got[(size_t) t]); + ++wrong; + } + } + } + } + // the fixture must reach the sentinel (row 2 has 11 candidates) or it cannot see the "nothing left" rule + std::printf(" %-34s %s (%d of %d positions differ; %d sentinel positions)\n", "top_k list under ties", + wrong || !sentinels ? "*** WRONG ***" : "matches", wrong, probes, sentinels); + bad += wrong + (sentinels == 0); + } + + // ---- fixture 17: SAMPLED DRAWS UNDER TIES. The realistic chain - finite logits on half steps, + // so dozens of tokens share each value near the top - through every stage: top_k 1 / 20 / 64, top_p 0.9 / 1, + // min_p 0 / 0.05, a hot temperature that spreads the draws over the whole list, penalties off and on (half of + // each window on the row's head, so they reorder it). 17 rows (the split's scratch is first sized for 16: this + // regrows it), on the legacy stream and on a created one. Observability: some picks must be tokens that tie + // with another kept token, or the tie rule would go untested. + { + const int T = 17, H = 64; + cudaStream_t cs = nullptr; + check(cudaStreamCreate(&cs), "fixture 17 stream"); + int wrong = 0, draws = 0, tied = 0; + for (int nv : {248320, 512}) { + std::mt19937 rng((unsigned) (1700 + nv)); + std::normal_distribution g(0.0f, 1.5f); + std::vector l((size_t) nv * T); + for (auto& v : l) v = std::floor(g(rng) * 2.0f) / 2.0f; + if (nv == 512) + for (auto& v : l) v = std::floor(v / 2.0f); // whole steps: a few big tie groups + std::vector hist((size_t) T * H); + for (int t = 0; t < T; ++t) { + const float* row = l.data() + (size_t) t * nv; + const float mx = *std::max_element(row, row + nv); + std::vector head; + for (int v = 0; v < nv; ++v) + if (row[v] >= mx - 1.0f) head.push_back(v); + for (int j = 0; j < H; ++j) + hist[(size_t) t * H + j] = (j & 1) ? (int) (rng() % (unsigned) nv) + : head[(size_t) (rng() % (unsigned) head.size())]; + } + DeviceRows rows(l, T, hist, H); + int config = 0; + for (int pen = 0; pen < 2; ++pen) { + strata::kernels::SamplerParams base; + base.temperature = 2.5f; base.seed = 17; + base.penalty_last_n = pen ? H : 0; + base.penalty_repeat = 1.25f; base.penalty_freq = 0.25f; base.penalty_present = 0.5f; + const int kmax = sampled_k(64, nv); + std::vector lists; + for (int t = 0; t < T; ++t) + lists.push_back(mirror_select(l.data() + (size_t) t * nv, nv, window_of(hist, H, t, base.penalty_last_n), + base, kmax)); + for (int top_k : {1, 20, 64}) + for (float top_p : {0.9f, 1.0f}) + for (float min_p : {0.0f, 0.05f}) + for (cudaStream_t st : {(cudaStream_t) nullptr, cs}) { + strata::kernels::SamplerParams p = base; + p.top_k = top_k; p.top_p = top_p; p.min_p = min_p; + p.counter = (uint64_t) (1000 * ++config); + const int k = sampled_k(top_k, nv); + const std::vector got = rows.sample(p, st); + for (int t = 0; t < T; ++t) { + const SelList& sl = lists[(size_t) t]; + const int want = mirror_pick(sl, k, p, t); + ++draws; + int same = 0; + for (int i = 0; i < k; ++i) { + if (sl.ids[(size_t) i] != want) continue; + for (int j = 0; j < k; ++j) same += sl.logit[(size_t) j] == sl.logit[(size_t) i]; + break; + } + tied += same > 1; + if (got[(size_t) t] != want) { + if (wrong < 8) + std::printf(" n_vocab %d row %d top_k %d top_p %.2f min_p %.2f pen %d: " + "want %d got %d\n", nv, t, top_k, (double) top_p, + (double) min_p, pen, want, got[(size_t) t]); + ++wrong; + } + } + } + } + } + cudaStreamDestroy(cs); + std::printf(" %-34s %s (%d of %d draws differ; %d picks tie with another kept token)\n", + "sampled draws under ties", wrong || !tied ? "*** WRONG ***" : "matches", wrong, draws, tied); + bad += wrong + (tied == 0); + } + + // ---- fixture 18: THE DEFAULT PATH'S AUTOMATIC FALLBACKS. (a) A stream under graph capture + // (ThreadLocal mode) gets the one-block kernel, penalty bitmap in dynamic shared memory, inside the graph: the + // capture must succeed and the replayed graph (twice) must pick the mirror's tokens; the same stream uncaptured + // then takes the split path (its scratch is first allocated after the capture) and picks the same. (b) More + // rows than a split launch takes (64) fall back to one block; exactly 64 stay split. + { + int wrong = 0, draws = 0; + const int H = 64; + auto compare = [&](const char* what, const std::vector& got, const std::vector& lists, int k, + const strata::kernels::SamplerParams& p) { + for (size_t t = 0; t < got.size(); ++t) { + const int want = mirror_pick(lists[t], k, p, (int) t); + ++draws; + if (got[t] != want) { + if (wrong < 8) std::printf(" %s row %zu: want %d got %d\n", what, t, want, got[t]); + ++wrong; + } + } + }; + auto make = [&](int nv, int T, unsigned seed, std::vector& l, std::vector& hist) { + std::mt19937 rng(seed); + std::normal_distribution g(0.0f, 1.5f); + l.assign((size_t) nv * T, 0.0f); + for (auto& v : l) v = std::floor(g(rng) * 2.0f) / 2.0f; + hist.assign((size_t) T * H, 0); + for (auto& h : hist) h = (int) (rng() % (unsigned) nv); + }; + { + const int nv = 248320, T = 3; + std::vector l; + std::vector hist; + make(nv, T, 1800u, l, hist); + strata::kernels::SamplerParams p; + p.top_k = 20; p.top_p = 0.9f; p.temperature = 2.5f; p.seed = 18; p.counter = 77; + p.penalty_last_n = H; p.penalty_repeat = 1.25f; p.penalty_freq = 0.25f; p.penalty_present = 0.5f; + const int k = sampled_k(p.top_k, nv); + std::vector lists; + for (int t = 0; t < T; ++t) + lists.push_back(mirror_select(l.data() + (size_t) t * nv, nv, window_of(hist, H, t, H), p, k)); + DeviceRows rows(l, T, hist, H); + cudaStream_t cs = nullptr; + check(cudaStreamCreate(&cs), "fixture 18 stream"); + check(cudaMemset(rows.o, 0xFF, (size_t) T * sizeof(int)), "fixture 18 fill"); + cudaGraph_t graph = nullptr; + cudaGraphExec_t exec = nullptr; + check(cudaStreamBeginCapture(cs, cudaStreamCaptureModeThreadLocal), "begin capture"); + strata::kernels::sample_tokens(rows.l, T, nv, rows.h, H, p, rows.o, cs); + check(cudaStreamEndCapture(cs, &graph), "end capture"); + check(cudaGraphInstantiate(&exec, graph, 0), "instantiate"); + for (int replay = 0; replay < 2; ++replay) { + check(cudaMemset(rows.o, 0xFF, (size_t) T * sizeof(int)), "fixture 18 refill"); + check(cudaGraphLaunch(exec, cs), "graph launch"); + check(cudaStreamSynchronize(cs), "graph sync"); + std::vector got((size_t) T); + check(cudaMemcpy(got.data(), rows.o, got.size() * sizeof(int), cudaMemcpyDeviceToHost), "back"); + compare("captured graph", got, lists, k, p); + } + cudaGraphExecDestroy(exec); + cudaGraphDestroy(graph); + compare("same stream, uncaptured", rows.sample(p, cs), lists, k, p); + cudaStreamDestroy(cs); + } + for (int T : {64, 70}) { + const int nv = 512; + std::vector l; + std::vector hist; + make(nv, T, 1810u + (unsigned) T, l, hist); + strata::kernels::SamplerParams p; + p.top_k = 64; p.top_p = 1.0f; p.temperature = 2.5f; p.seed = 18; p.counter = (uint64_t) T; + const int k = sampled_k(p.top_k, nv); + std::vector lists; + for (int t = 0; t < T; ++t) lists.push_back(mirror_select(l.data() + (size_t) t * nv, nv, {}, p, k)); + DeviceRows rows(l, T, hist, 0); + compare(T > 64 ? "70 rows (one block)" : "64 rows (split)", rows.sample(p, nullptr), lists, k, p); + } + std::printf(" %-34s %s (%d of %d draws differ)\n", "fallbacks: graph capture, row cap", + wrong ? "*** WRONG ***" : "matches", wrong, draws); + bad += wrong; + } + std::printf("\nsampler: %d failures\n", bad); if (bad) return 1; if (selftest) std::printf("sampler_parity OK\n"); From 4ff986a0aa27f1e20680df7005e135736f82ba1f Mon Sep 17 00:00:00 2001 From: Apposite245 <102203339+Apposite245@users.noreply.github.com> Date: Tue, 29 Sep 2026 22:10:48 -0400 Subject: [PATCH 19/32] serve: on Windows the engine, vision encoder and MCP servers end with the server Closing the console window (or a crash, or Task Manager) ends the server without its cleanup, and strata --serve, strata-vision and the MCP servers kept running with their VRAM and RAM. Each child now goes into a job object that kills everything in it when its only handle - the server's - closes; what the children start joins it too. The server itself stays out, so a browser --open starts is not tied to it. A no-op elsewhere. serve/test_winjob.py: a contained child and its grandchild end when the process that contained them is killed. --- serve/mcp.py | 3 ++ serve/server.py | 3 ++ serve/test_winjob.py | 67 +++++++++++++++++++++++++++++++++++++++ serve/winjob.py | 74 ++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 147 insertions(+) create mode 100644 serve/test_winjob.py create mode 100644 serve/winjob.py diff --git a/serve/mcp.py b/serve/mcp.py index 327216fe..610eac61 100644 --- a/serve/mcp.py +++ b/serve/mcp.py @@ -31,6 +31,8 @@ import time import urllib.error import urllib.request +from serve.winjob import contain + PROTOCOL = "2025-06-18" # the MCP revision Strata asks for; the server's answer is used as given DEFAULTS = {"timeout_s": 60.0, "max_result_chars": 20000, "max_rounds": 8, "start_timeout_s": 120.0} @@ -105,6 +107,7 @@ class StdioTransport: env=env, **extra) except OSError as e: raise McpError(f"could not start {command!r}: {e}") from None + contain(self.proc) # ends with the server, however it ends (Windows) threading.Thread(target=self._read, daemon=True).start() threading.Thread(target=self._read_stderr, daemon=True).start() diff --git a/serve/server.py b/serve/server.py index 89b88b59..fd5ad3ad 100644 --- a/serve/server.py +++ b/serve/server.py @@ -47,6 +47,7 @@ sys.path.insert(0, str(ROOT)) # run as a script (run-.bat) as well as a from serve.frontend import (ChatTemplate, Event, OutputParser, anthropic_to_messages, # noqa: E402 images_of, openai_to_messages) from serve.mcp import McpCancelled, hub_from_config # noqa: E402 +from serve.winjob import contain # noqa: E402 IM_END = "<|im_end|>" IMAGE_PAD = "<|image_pad|>" @@ -167,6 +168,7 @@ class StrataEngine: daemon=True).start() self.proc = subprocess.Popen([exe, "--serve", *args], cwd=cwd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=self.log, text=True, encoding="utf-8", bufsize=1, env=env) + contain(self.proc) # ends with the server, however it ends (Windows) self.max_context = 0 self.can_stop = False # the engine honours a STOP line mid-request (READY stop) self.last = {} @@ -394,6 +396,7 @@ class Vision: self.dir = Path(tempfile.mkdtemp(prefix="strata-vision-")) self.proc = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=log or subprocess.DEVNULL, text=True, encoding="utf-8", bufsize=1, env=env) + contain(self.proc) line = self.proc.stdout.readline() if not line.startswith("READY"): raise RuntimeError("the vision encoder did not start: " + line.strip()) diff --git a/serve/test_winjob.py b/serve/test_winjob.py new file mode 100644 index 00000000..31b617ab --- /dev/null +++ b/serve/test_winjob.py @@ -0,0 +1,67 @@ +"""serve/winjob.py: a contained child - and whatever it starts - ends when the process that contained it ends, even +when that process is killed outright (the console window closed, Task Manager), with no cleanup of its own. + + python -m unittest serve.test_winjob (Windows only; skipped elsewhere) +""" +import os +import subprocess +import sys +import time +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(ROOT)) + +# stands in for the server: contains a child that starts a grandchild, prints both pids, then waits to be killed +PARENT = f""" +import subprocess, sys, time +sys.path.insert(0, {str(ROOT)!r}) +from serve.winjob import contain +code = ("import subprocess, sys, time; g = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(120)']); " + "print(g.pid, flush=True); time.sleep(120)") +child = subprocess.Popen([sys.executable, "-c", code], stdout=subprocess.PIPE, text=True) +ok = contain(child) +print(ok, child.pid, child.stdout.readline().strip(), flush=True) +time.sleep(120) +""" + + +def running(pid: int) -> bool: + out = subprocess.run(["tasklist", "/FI", f"PID eq {pid}", "/NH"], capture_output=True, text=True).stdout + return str(pid) in out + + +@unittest.skipUnless(os.name == "nt", "job objects are Windows-only") +class TestWinJob(unittest.TestCase): + def test_children_end_with_a_killed_server(self): + # a venv's python.exe is a launcher that runs the real interpreter as its child: kill() must reach the latter + python = getattr(sys, "_base_executable", None) or sys.executable + parent = subprocess.Popen([python, "-c", PARENT], stdout=subprocess.PIPE, text=True) + child = grandchild = None + try: + ok, child, grandchild = parent.stdout.readline().split() + child, grandchild = int(child), int(grandchild) + self.assertEqual(ok, "True") + self.assertTrue(running(child) and running(grandchild)) + parent.kill() # TerminateProcess: no atexit, no finally - like closing the window + parent.wait(10) + deadline = time.monotonic() + 10 + while (running(child) or running(grandchild)) and time.monotonic() < deadline: + time.sleep(0.2) + self.assertFalse(running(child), "the child outlived the server") + self.assertFalse(running(grandchild), "the grandchild outlived the server") + finally: + if parent.poll() is None: + parent.kill() + for pid in (child, grandchild): # on a failure, don't leave them sleeping + if pid and running(pid): + subprocess.run(["taskkill", "/PID", str(pid), "/F"], capture_output=True) + + def test_elsewhere_or_without_a_process_it_is_a_no_op(self): + from serve.winjob import contain + self.assertFalse(contain(None)) + + +if __name__ == "__main__": + unittest.main() diff --git a/serve/winjob.py b/serve/winjob.py new file mode 100644 index 00000000..008642a0 --- /dev/null +++ b/serve/winjob.py @@ -0,0 +1,74 @@ +"""serve/winjob.py - on Windows, tie the processes Strata starts to the server's own lifetime. + +Closing the console window, Task Manager or a crash end the server without running its cleanup, and the engine, +the vision encoder and the MCP servers kept running on their own. `contain(proc)` puts a child in a job object that +is set to kill everything in it when its last handle closes - and the only handle is this process's, which the OS +closes however the server ends. Processes the child starts later join the same job. The server itself stays out of +the job, so a browser that `--open` starts is not tied to it. Elsewhere, and if the job cannot be made, a no-op. +""" +from __future__ import annotations + +import os +import threading + +_job = None +_lock = threading.Lock() + +if os.name == "nt": + import ctypes + from ctypes import wintypes + + _k32 = ctypes.WinDLL("kernel32", use_last_error=True) + + class _IoCounters(ctypes.Structure): + _fields_ = [(n, ctypes.c_ulonglong) for n in ("ReadOperationCount", "WriteOperationCount", + "OtherOperationCount", "ReadTransferCount", + "WriteTransferCount", "OtherTransferCount")] + + class _BasicLimits(ctypes.Structure): + _fields_ = [("PerProcessUserTimeLimit", ctypes.c_longlong), ("PerJobUserTimeLimit", ctypes.c_longlong), + ("LimitFlags", wintypes.DWORD), ("MinimumWorkingSetSize", ctypes.c_size_t), + ("MaximumWorkingSetSize", ctypes.c_size_t), ("ActiveProcessLimit", wintypes.DWORD), + ("Affinity", ctypes.c_size_t), ("PriorityClass", wintypes.DWORD), + ("SchedulingClass", wintypes.DWORD)] + + class _ExtendedLimits(ctypes.Structure): + _fields_ = [("BasicLimitInformation", _BasicLimits), ("IoInfo", _IoCounters), + ("ProcessMemoryLimit", ctypes.c_size_t), ("JobMemoryLimit", ctypes.c_size_t), + ("PeakProcessMemoryUsed", ctypes.c_size_t), ("PeakJobMemoryUsed", ctypes.c_size_t)] + + _JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x2000 + _JobObjectExtendedLimitInformation = 9 + + _k32.CreateJobObjectW.restype = wintypes.HANDLE + _k32.CreateJobObjectW.argtypes = (wintypes.LPVOID, wintypes.LPCWSTR) + _k32.SetInformationJobObject.argtypes = (wintypes.HANDLE, ctypes.c_int, wintypes.LPVOID, wintypes.DWORD) + _k32.AssignProcessToJobObject.argtypes = (wintypes.HANDLE, wintypes.HANDLE) + + def _make_job(): + job = _k32.CreateJobObjectW(None, None) # no security attributes: the handle is not inherited + if not job: + return None + info = _ExtendedLimits() + info.BasicLimitInformation.LimitFlags = _JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE + if not _k32.SetInformationJobObject(job, _JobObjectExtendedLimitInformation, ctypes.byref(info), + ctypes.sizeof(info)): + _k32.CloseHandle(job) + return None + return job + + +def contain(proc) -> bool: + """Put a started subprocess.Popen in the kill-on-close job. True if it is in; False (harmlessly) otherwise.""" + global _job + if os.name != "nt" or proc is None: + return False + with _lock: + if _job is None: + _job = _make_job() or 0 + if not _job: + return False + try: + return bool(_k32.AssignProcessToJobObject(_job, int(proc._handle))) + except (AttributeError, OSError, ValueError): + return False From ab50d19c9b03365086918851860e6852746864b2 Mon Sep 17 00:00:00 2001 From: Andy Date: Wed, 30 Sep 2026 14:13:01 +0400 Subject: [PATCH 20/32] decode: QSA scores multi - comment names every caller that takes it (decode captured or not, prefill's pooled16); no box-specific note (review) --- src/kernels/cuda/qsa_select.cu | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/kernels/cuda/qsa_select.cu b/src/kernels/cuda/qsa_select.cu index 57fa33da..dd3ba537 100644 --- a/src/kernels/cuda/qsa_select.cu +++ b/src/kernels/cuda/qsa_select.cu @@ -430,9 +430,11 @@ __global__ void __launch_bounds__(TK_T) block_topk_reg_kernel(const float* __res } -// dual-3090 (session 8): the decode window's scores - every key block read ONCE for all the window's queries (the -// grid above is (max_blocks / 8) x nq: ~24,600 mostly-idle blocks per layer, each key re-read per query). A fixed +// Block scores with every key block read ONCE for all of a call's queries (block_scores_kernel's grid is +// (max_blocks / 8) x nq: ~24,600 mostly-idle blocks per layer at a decode window, each key re-read per query). A fixed // grid strides over the blocks; per (block, query) the same arithmetic in the same order as block_scores_kernel. +// 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, @@ -486,7 +488,7 @@ void qsa_block_scores(const float* pooled, const float* dead, const float* q_idx } // 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) { // the decode window (a captured graph: no active count) + if (multi && 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); const cudaError_t e = cudaGetLastError(); From 802c6619df3ab26cab42bca4d44b2204847e077d Mon Sep 17 00:00:00 2001 From: Andy Date: Wed, 30 Sep 2026 14:13:20 +0400 Subject: [PATCH 21/32] prefill: GDN recurrence pipelining - the neutral 16-column variant (STRATA_GDN_CB) dropped, one kernel on upstream's split (review) --- src/prefill/kernels.cu | 24 ++++++++++-------------- 1 file changed, 10 insertions(+), 14 deletions(-) diff --git a/src/prefill/kernels.cu b/src/prefill/kernels.cu index e03343dc..50984ec9 100644 --- a/src/prefill/kernels.cu +++ b/src/prefill/kernels.cu @@ -340,18 +340,17 @@ __global__ void __launch_bounds__(CB * RG) gdn_rec_cols_kernel(float* __restrict #pragma unroll for (int r = 0; r < RPG; ++r) base[r * rs] = s[r]; } -// dual-3090: gdn_rec_cols_kernel with the next token's inputs (q/k rows, v, gate, beta) loaded into registers while -// this token computes (software pipelining). The same arithmetic in the same order: the same bits. CBT = columns -// per block (32: upstream's split; 16: twice the blocks, STRATA_GDN_CB=16). STRATA_GDN_PIPELINE=0: upstream's kernel. -template -__global__ void __launch_bounds__(CBT * RG) gdn_rec_cols_pipe_kernel(float* __restrict__ state, const float* __restrict__ h, +// gdn_rec_cols_kernel with the next token's inputs (q/k rows, v, gate, beta) loaded into registers while this token +// computes (software pipelining). The same arithmetic in the same order: the same bits, and the same CB-column split. +// STRATA_GDN_PIPELINE=0: gdn_rec_cols_kernel. +__global__ void __launch_bounds__(CB * RG) gdn_rec_cols_pipe_kernel(float* __restrict__ state, const float* __restrict__ h, const float* __restrict__ gate, const float* __restrict__ beta, float* __restrict__ oc_out, int64_t T) { - constexpr int NT = CBT * RG, LPT = S / NT, NCBT = S / CBT; // threads, q/k rows loaded per thread - __shared__ float sk[S], sq[S], red[RG][CBT]; - const int head = blockIdx.x / NCBT, cb = blockIdx.x % NCBT; - const int c = threadIdx.x, rg = threadIdx.y, tid = rg * CBT + c, col = cb * CBT + c; + constexpr int NT = CB * RG, LPT = S / NT; // threads, q/k rows loaded per thread + __shared__ float sk[S], sq[S], red[RG][CB]; + const int head = blockIdx.x / NCB, cb = blockIdx.x % NCB; + const int c = threadIdx.x, rg = threadIdx.y, tid = rg * CB + c, col = cb * CB + c; const int qh = head % HK; float s[RPG]; float* base = state + ((size_t) (rg * RPG) * HV + head) * S + col; @@ -697,11 +696,8 @@ void gdn_recurrence(float* state, const float* h, const float* gate, const float gdn_rec_kernel<<>>(state, h, gate, beta, z, gamma, eps, y, y16, T); } else { static const bool pipe = [] { const char* v = std::getenv("STRATA_GDN_PIPELINE"); return v == nullptr || std::atoi(v) != 0; }(); - static const int cbt = [] { const char* v = std::getenv("STRATA_GDN_CB"); return v != nullptr && std::atoi(v) == 16 ? 16 : 32; }(); - if (pipe && cbt == 16) // dual-3090: the software-pipelined loads, 16 columns per block - gdn_rec_cols_pipe_kernel<16><<>>(state, h, gate, beta, y, T); - else if (pipe) - gdn_rec_cols_pipe_kernel<32><<>>(state, h, gate, beta, y, T); + if (pipe) // the software-pipelined loads (same bits) + gdn_rec_cols_pipe_kernel<<>>(state, h, gate, beta, y, T); else gdn_rec_cols_kernel<<>>(state, h, gate, beta, y, T); gdn_out_norm_kernel<<>>(z, gamma, eps, y, y16); From 0d40c17d2fb43405d468e14bda84c4a494534d76 Mon Sep 17 00:00:00 2001 From: dsh Date: Mon, 28 Sep 2026 11:14:37 +0400 Subject: [PATCH 22/32] ple: --ple-io ram locks the n-gram table in RAM (no SSD read on the prompt/token path) --- include/strata/kernels/ngram.hpp | 3 +++ src/kernels/ngram.cpp | 18 ++++++++++++++++++ src/program/generate.cpp | 11 ++++++++--- 3 files changed, 29 insertions(+), 3 deletions(-) diff --git a/include/strata/kernels/ngram.hpp b/include/strata/kernels/ngram.hpp index d15491de..8e6702a2 100644 --- a/include/strata/kernels/ngram.hpp +++ b/include/strata/kernels/ngram.hpp @@ -110,6 +110,9 @@ struct PleIoOptions { uint32_t max_inflight = 64; ///< outstanding SSD reads (decode needs 16; prefill chunks use more) uint64_t cache_rows = 1u << 20; ///< bounded row cache: 1,048,576 rows x 90 B ~ 95 MB; 0 disables bool io_thread = true; ///< reads submitted by a worker thread, not the caller + /// dual-3090 (--ple-io ram): mmap mode with the whole table locked in RAM at open (a box with RAM to spare: + /// no SSD read ever sits on the prompt or token path) + bool lock = false; }; /// The PLE table. Held by pointer-to-impl so this header does not drag `` into every diff --git a/src/kernels/ngram.cpp b/src/kernels/ngram.cpp index b1bd98b2..d9076888 100644 --- a/src/kernels/ngram.cpp +++ b/src/kernels/ngram.cpp @@ -6,8 +6,12 @@ #include "strata/kernels/f16_bits.hpp" #include "strata/ngram/ple_reader.hpp" +#include #include #include +#if !defined(_WIN32) +#include +#endif #include #include @@ -195,6 +199,20 @@ bool PleTable::open(const std::string& gguf_path, std::string& err, const PleIoO } impl_->n_rows = n_rows; } + if (io.mode == PleIo::Mmap && io.lock && impl_->data != nullptr) { +#if !defined(_WIN32) + const uint64_t page = 4096; + const uintptr_t a0 = (uintptr_t) impl_->data & ~(uintptr_t) (page - 1); + const uintptr_t a1 = (uintptr_t) impl_->data + (uintptr_t) need; + madvise((void*) a0, a1 - a0, MADV_WILLNEED); + if (mlock((const void*) a0, a1 - a0) != 0) { + std::fprintf(stderr, "strata: PLE table mlock failed (%s): touching its pages instead\n", std::strerror(errno)); + volatile uint8_t sink = 0; + for (uintptr_t p = a0; p < a1; p += page) sink = sink + *(const volatile uint8_t*) p; + (void) sink; + } +#endif + } impl_->mode = io.mode; return true; } diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 3b091eb2..0bc03bc6 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -319,7 +319,7 @@ void usage() { " --tokens-file PATH pretokenized prompt, commas or whitespace (alternative to --tokens)\n" " --ple-gguf PATH required PLE table (original second GGUF shard)\n" " --no-ple explicit diagnostic ablation of the PLE layer\n" - " --ple-io direct|mmap n-gram table reads (plan v0.3 P2). direct (default): unbuffered SSD\n" + " --ple-io direct|mmap|ram n-gram table reads (ram = mmap, locked in RAM at start); (plan v0.3 P2). direct (default): unbuffered SSD\n" " reads, the table never enters RAM or the file cache; mmap: A/B arm\n" " --ple-row-cache N bounded cache of fetched rows, 90 B each (default 1048576; 0 = off)\n" " --ple-inflight N outstanding SSD reads (default 64)\n" @@ -1195,7 +1195,7 @@ int main(int argc, char** argv) { return 2; } - if ((o.ple_io != "direct" && o.ple_io != "mmap") || o.ple_row_cache < 0 || o.ple_inflight < 1 || + if ((o.ple_io != "direct" && o.ple_io != "mmap" && o.ple_io != "ram") || o.ple_row_cache < 0 || o.ple_inflight < 1 || o.ple_inflight > 1024 || !(o.ple_delay_us >= 0)) { std::fprintf(stderr, "strata generate: invalid --ple-io/--ple-row-cache/--ple-inflight/--ple-delay-us\n"); return 2; @@ -1564,7 +1564,9 @@ int main(int argc, char** argv) { float* ple_scratch = nullptr; if (!o.ple_gguf.empty()) { strata::kernels::PleIoOptions pio; - pio.mode = o.ple_io == "mmap" ? strata::kernels::PleIo::Mmap : strata::kernels::PleIo::Direct; + pio.mode = o.ple_io == "mmap" || o.ple_io == "ram" ? strata::kernels::PleIo::Mmap : strata::kernels::PleIo::Direct; + pio.lock = o.ple_io == "ram"; // dual-3090: the whole table locked in RAM + const auto tpl = Clock::now(); pio.max_inflight = (uint32_t) o.ple_inflight; pio.cache_rows = (uint64_t) o.ple_row_cache; pio.io_thread = !o.ple_sync_submit; @@ -1572,6 +1574,9 @@ int main(int argc, char** argv) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } + if (pio.lock) + std::fprintf(stderr, "strata generate: PLE table locked in RAM (--ple-io ram) in %.1f s\n", + std::chrono::duration(Clock::now() - tpl).count()); const strata::core::WeightRef* wk = wt.find("blk.1.ple_key.weight"); const strata::core::WeightRef* wv = wt.find("blk.1.ple_value.weight"); const strata::core::WeightRef* wnk = wt.find("blk.1.ple_norm_key.weight"); From be41a09e5bd2a19e8304c3ee37c8dc9a71ed937e Mon Sep 17 00:00:00 2001 From: Andy Date: Wed, 30 Sep 2026 14:10:05 +0400 Subject: [PATCH 23/32] ple: --ple-io ram: refused on Windows (no mlock), 'locked' only when mlock succeeded else 'loaded (not locked)', neutral comments + --help (review) --- include/strata/kernels/ngram.hpp | 6 ++++-- src/kernels/ngram.cpp | 10 ++++++++-- src/program/generate.cpp | 16 ++++++++++++---- 3 files changed, 24 insertions(+), 8 deletions(-) diff --git a/include/strata/kernels/ngram.hpp b/include/strata/kernels/ngram.hpp index 8e6702a2..29698422 100644 --- a/include/strata/kernels/ngram.hpp +++ b/include/strata/kernels/ngram.hpp @@ -110,8 +110,8 @@ struct PleIoOptions { uint32_t max_inflight = 64; ///< outstanding SSD reads (decode needs 16; prefill chunks use more) uint64_t cache_rows = 1u << 20; ///< bounded row cache: 1,048,576 rows x 90 B ~ 95 MB; 0 disables bool io_thread = true; ///< reads submitted by a worker thread, not the caller - /// dual-3090 (--ple-io ram): mmap mode with the whole table locked in RAM at open (a box with RAM to spare: - /// no SSD read ever sits on the prompt or token path) + /// Mmap mode only (`--ple-io ram`): lock the whole mapped table in RAM at open, so no SSD read ever sits on + /// the prompt or token path. Needs RAM for the full table. POSIX only (mlock); `locked()` reports the outcome. bool lock = false; }; @@ -147,6 +147,8 @@ public: bool open(const std::string& gguf_path, std::string& err); void close(); bool is_open() const; + /// True when `PleIoOptions::lock` was asked for and mlock succeeded (false: pages only pre-touched). + bool locked() const; uint64_t rows() const; /// 16 row indices -> 2560 floats. The gathered rows are flattened HEAD-SLOWEST: row h's 160 values diff --git a/src/kernels/ngram.cpp b/src/kernels/ngram.cpp index d9076888..9def3309 100644 --- a/src/kernels/ngram.cpp +++ b/src/kernels/ngram.cpp @@ -123,6 +123,7 @@ struct PleTable::Impl { strata::ngram::PleReader reader; strata::ngram::PleReader::Ticket ticket; bool pending = false; + bool locked = false; uint32_t rows[PLE_N_HEADS] = {}; uint8_t raw[PLE_N_HEADS * PLE_ROW_BYTES] = {}; }; @@ -205,8 +206,11 @@ bool PleTable::open(const std::string& gguf_path, std::string& err, const PleIoO const uintptr_t a0 = (uintptr_t) impl_->data & ~(uintptr_t) (page - 1); const uintptr_t a1 = (uintptr_t) impl_->data + (uintptr_t) need; madvise((void*) a0, a1 - a0, MADV_WILLNEED); - if (mlock((const void*) a0, a1 - a0) != 0) { - std::fprintf(stderr, "strata: PLE table mlock failed (%s): touching its pages instead\n", std::strerror(errno)); + if (mlock((const void*) a0, a1 - a0) == 0) { + impl_->locked = true; + } else { + std::fprintf(stderr, "strata: PLE table mlock failed (%s; raise `ulimit -l`): touching its pages instead\n", + std::strerror(errno)); volatile uint8_t sink = 0; for (uintptr_t p = a0; p < a1; p += page) sink = sink + *(const volatile uint8_t*) p; (void) sink; @@ -220,6 +224,7 @@ bool PleTable::open(const std::string& gguf_path, std::string& err, const PleIoO void PleTable::close() { impl_->reader.close(); impl_->pending = false; + impl_->locked = false; // the unmap below releases the lock impl_->mode = PleIo::Mmap; delete impl_->file; impl_->file = nullptr; @@ -228,6 +233,7 @@ void PleTable::close() { } bool PleTable::is_open() const { return impl_->data != nullptr || impl_->reader.is_open(); } +bool PleTable::locked() const { return impl_->locked; } PleIo PleTable::mode() const { return impl_->mode; } uint64_t PleTable::rows() const { return impl_->n_rows; } uint64_t PleTable::bytes_read() const { return impl_->bytes_read; } diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 0bc03bc6..092327c0 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -319,8 +319,9 @@ void usage() { " --tokens-file PATH pretokenized prompt, commas or whitespace (alternative to --tokens)\n" " --ple-gguf PATH required PLE table (original second GGUF shard)\n" " --no-ple explicit diagnostic ablation of the PLE layer\n" - " --ple-io direct|mmap|ram n-gram table reads (ram = mmap, locked in RAM at start); (plan v0.3 P2). direct (default): unbuffered SSD\n" - " reads, the table never enters RAM or the file cache; mmap: A/B arm\n" + " --ple-io direct|mmap|ram n-gram table reads (plan v0.3 P2). direct (default): unbuffered SSD\n" + " reads, the table never enters RAM or the file cache; mmap: A/B arm;\n" + " ram: mmap with the whole table locked in RAM at start (Linux/macOS)\n" " --ple-row-cache N bounded cache of fetched rows, 90 B each (default 1048576; 0 = off)\n" " --ple-inflight N outstanding SSD reads (default 64)\n" " --ple-delay-us U fault injection: each row read completes no earlier than U us\n" @@ -1200,6 +1201,12 @@ int main(int argc, char** argv) { std::fprintf(stderr, "strata generate: invalid --ple-io/--ple-row-cache/--ple-inflight/--ple-delay-us\n"); return 2; } +#if defined(_WIN32) + if (o.ple_io == "ram") { + std::fprintf(stderr, "strata generate: --ple-io ram is not available on Windows (no mlock); use --ple-io mmap\n"); + return 2; + } +#endif if (o.kv == "q4") o.kv = "q4_0"; if (o.kv != "fp16" && o.kv != "int8" && o.kv != "q4_0" && o.kv != "k8v4") { std::fprintf(stderr, "strata generate: --kv must be fp16, int8, q4_0 or k8v4\n"); @@ -1565,7 +1572,7 @@ int main(int argc, char** argv) { if (!o.ple_gguf.empty()) { strata::kernels::PleIoOptions pio; pio.mode = o.ple_io == "mmap" || o.ple_io == "ram" ? strata::kernels::PleIo::Mmap : strata::kernels::PleIo::Direct; - pio.lock = o.ple_io == "ram"; // dual-3090: the whole table locked in RAM + pio.lock = o.ple_io == "ram"; const auto tpl = Clock::now(); pio.max_inflight = (uint32_t) o.ple_inflight; pio.cache_rows = (uint64_t) o.ple_row_cache; @@ -1575,7 +1582,8 @@ int main(int argc, char** argv) { return 1; } if (pio.lock) - std::fprintf(stderr, "strata generate: PLE table locked in RAM (--ple-io ram) in %.1f s\n", + std::fprintf(stderr, "strata generate: PLE table %s (--ple-io ram) in %.1f s\n", + ple_table.locked() ? "locked in RAM" : "loaded (not locked)", std::chrono::duration(Clock::now() - tpl).count()); const strata::core::WeightRef* wk = wt.find("blk.1.ple_key.weight"); const strata::core::WeightRef* wv = wt.find("blk.1.ple_value.weight"); From e258e6ec5b7eddda4284373e0df5511b9e960889 Mon Sep 17 00:00:00 2001 From: Hasegawa Takuya Date: Wed, 30 Sep 2026 19:21:01 +0900 Subject: [PATCH 24/32] perf(prefill): allow explicit routed-only staging for large chunks --- src/prefill/prefill.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index 6731b3c8..bdfd9e7a 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -82,6 +82,7 @@ double g_pinned_share = 1.0; inline int ring_slots(size_t T) { const char* v = std::getenv("STRATA_PREFILL_RING"); const int r = v ? std::atoi(v) : (g_pinned_share >= 0.9 ? 384 : 96); + if (v && r == STAGE) return STAGE; // Explicit opt-in to routed-only staging, including large chunks. const int big = r < 16 ? 16 : r > RING_MAX ? RING_MAX : r; return (int64_t) T >= STREAM_ALL_MIN ? big : STAGE; } From 1564404f62f59e0591bbbe6fad0d68c8a75e1bc6 Mon Sep 17 00:00:00 2001 From: "Joost R." Date: Tue, 29 Sep 2026 21:04:38 +0200 Subject: [PATCH 25/32] WSL2: survive the driver's ~1 GiB pinned host budget with 3 GPUs Under WSL2 the NVIDIA driver can pin/map only about 1 GiB of host memory in total (dmesg: "dxgk: create_existing_sysmem: establish_gpadl failed: -122"). With --expert-cache-device1/2 the startup ran out of it twice: - CUDA2's context is created after CUDA0's weights and MTP, whose mapped host buffers have spent the budget: "CUDA2 experts: cudaSetDevice(2) failed: out of memory". STRATA_EARLY_REMOTE_CONTEXTS=1 now creates every secondary context up front, like CUDA1's (opt-in: the default order is unchanged). - With three contexts up, the 260 MiB mapped native embedding no longer fits: "native embedding: cannot pin 260 MiB". It now falls back to a device copy on the current GPU instead of failing the start. Measured in Docker Desktop (WSL2), RTX 5070 Ti + 2x RTX 5060 Ti, Swift 1.5 IQ3_XXS: starts and serves with both helper caches (5000 experts each). --- src/core/native_head.cpp | 34 +++++++++++++++++++++++++--------- src/program/generate.cpp | 13 +++++++++---- 2 files changed, 34 insertions(+), 13 deletions(-) diff --git a/src/core/native_head.cpp b/src/core/native_head.cpp index fc9f694f..2f58cfbd 100644 --- a/src/core/native_head.cpp +++ b/src/core/native_head.cpp @@ -5,6 +5,7 @@ #include #include +#include #include #include @@ -102,6 +103,7 @@ const NativeEmbed* native_embed() { return g_embed; } NativeEmbed::~NativeEmbed() { if (host_) cudaFreeHost(host_); + else if (dev_) cudaFree(const_cast(dev_)); // the VRAM fallback below } bool NativeEmbed::load(const std::string& path, int64_t n_embd, int64_t n_vocab, std::string& err) { @@ -119,17 +121,31 @@ bool NativeEmbed::load(const std::string& path, int64_t n_embd, int64_t n_vocab, row_ = strata::kernels::iq_row_bytes((int) t->type, n_embd); bytes_ = (uint64_t) row_ * (uint64_t) n_vocab; if (cudaHostAlloc(&host_, bytes_, cudaHostAllocMapped | cudaHostAllocPortable) != cudaSuccess) { + // Under WSL2 the driver's pinned/mapped host budget (~1 GiB) can be spent by the GPU contexts + // themselves (three cards). The table is only gathered from, so keep it in the current device's VRAM + // instead: it costs its size there and reads faster than over PCIe. + cudaGetLastError(); host_ = nullptr; - err = "native embedding: cannot pin " + std::to_string(bytes_ >> 20) + " MiB"; - return false; + void* d = nullptr; + if (cudaMalloc(&d, bytes_) != cudaSuccess || + cudaMemcpy(d, gguf.tensor_data(*t), bytes_, cudaMemcpyHostToDevice) != cudaSuccess) { + if (d) cudaFree(d); + cudaGetLastError(); + err = "native embedding: cannot pin " + std::to_string(bytes_ >> 20) + " MiB, nor place it in VRAM"; + return false; + } + std::fprintf(stderr, "strata: native embedding: cannot pin %llu MiB, kept in VRAM instead\n", + (unsigned long long) (bytes_ >> 20)); + dev_ = d; + } else { + std::memcpy(host_, gguf.tensor_data(*t), bytes_); + void* d = nullptr; + if (cudaHostGetDevicePointer(&d, host_, 0) != cudaSuccess) { + err = "native embedding: no device alias for the mapped table"; + return false; + } + dev_ = d; } - std::memcpy(host_, gguf.tensor_data(*t), bytes_); - void* d = nullptr; - if (cudaHostGetDevicePointer(&d, host_, 0) != cudaSuccess) { - err = "native embedding: no device alias for the mapped table"; - return false; - } - dev_ = d; type_ = (int) t->type; n_embd_ = n_embd; n_vocab_ = n_vocab; diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 092327c0..3a7b57f9 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -1331,16 +1331,21 @@ int main(int argc, char** argv) { } } const bool native_pack = strata::kernels::cpu::expert_layout().native; - if (o.expert_cache_remote[0] > 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"). + const char* early_env = std::getenv("STRATA_EARLY_REMOTE_CONTEXTS"); + const bool early_remote = early_env && early_env[0] == '1'; + for (int r = 0; r < 3; ++r) if (o.expert_cache_remote[(size_t) r] > 0 && (r == 0 || early_remote)) { // Keep CUDA1's proven startup order: initialise its context before // allocating GPU0 weights or mapping the large host expert arena. double free_gib = 0; - if (!strata::core::RemoteExperts::preflight(remote_dev[0], free_gib, err)) { + if (!strata::core::RemoteExperts::preflight(remote_dev[r], free_gib, err)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } std::fprintf(stderr, "strata generate: CUDA%d context ready, %.2f GiB free before expert arena registration\n", - remote_dev[0], free_gib); + remote_dev[r], free_gib); } // plan v0.3 P6: the PCIe share of the missed experts, measured per kind of pack (the paper, finding on PCIe). // PR #44: a x8 link carries half of what the native default assumes - the GPU's SMs read that share over the @@ -1743,7 +1748,7 @@ int main(int argc, char** argv) { } // Create the additional contexts after MTP has secured CUDA0 memory, but // before the host arena maps its expert pages into their address spaces. - for (int r = 1; r < 3; ++r) if (o.expert_cache_remote[(size_t) r] > 0) { + for (int r = 1; r < 3; ++r) if (o.expert_cache_remote[(size_t) r] > 0 && !early_remote) { double free_gib = 0; if (!strata::core::RemoteExperts::preflight(remote_dev[r], free_gib, err)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); From ba1c8099482ccd2cc6cc38c881a606bc0a1acd36 Mon Sep 17 00:00:00 2001 From: Hendrik Polczynski Date: Tue, 29 Sep 2026 22:17:58 +0200 Subject: [PATCH 26/32] Show prefill speed alongside decode speed in dashboard Display both rates in t/s with independent graph scales and a darker prefill curve. Expose prefill_tok_s_mean using the engine's existing rate, excluding cached tokens. Co-authored-by: Codex (gpt-6-astra-medium) --- serve/server.py | 13 ++++++++++++- serve/telemetry.py | 2 +- serve/test_server.py | 35 +++++++++++++++++++++++++++++++++++ serve/web/app.css | 5 +++++ serve/web/app.js | 22 +++++++++++++++++----- 5 files changed, 70 insertions(+), 7 deletions(-) diff --git a/serve/server.py b/serve/server.py index fd5ad3ad..9393f2d5 100644 --- a/serve/server.py +++ b/serve/server.py @@ -173,6 +173,7 @@ class StrataEngine: self.can_stop = False # the engine honours a STOP line mid-request (READY stop) self.last = {} self.info = {} # INFO key=value facts (engine 0.1.8+): kv, expert slots, ... (Monitor tab) + self.prefill_tok_s_mean = None self.progress = None # (read, total) prompt tokens while a prompt is read, from PP lines try: # a ready-made engine's BUILD.json says its version self.info["version"] = json.loads((Path(exe).parent / "BUILD.json").read_text()).get("version") @@ -316,6 +317,7 @@ class StrataEngine: the HTTP layer turns it into an SSE comment, which keeps clients' watchdogs calm and notices a client that has gone. A consumer that stops early (or `cancel`) makes the engine STOP, so it does not run to max_new.""" self.progress = None + self.prefill_tok_s_mean = None # an image request takes the same sampling keys as text (#75: it used to decode greedily whatever was asked) head = f"GENI {int(max_new)}{self.sampling_keys(sampling or {})} {embeddings}" if embeddings else \ f"GEN {int(max_new)}{self.sampling_keys(sampling or {})}" @@ -345,6 +347,7 @@ class StrataEngine: f = line.split() if len(f) >= 3 and f[1].isdigit() and f[2].isdigit(): self.progress = (int(f[1]), int(f[2])) # prompt progress, one per chunk: also a heartbeat (the + self.prefill_tok_s_mean = float(f[4]) if len(f) >= 5 else None if cancel.is_set(): # lines reset the 10 s wait, so without this a long prompt return # would send no keep-alives at all) yield None @@ -624,7 +627,8 @@ class Service: """The hardware sampler behind GET /metrics (serve/telemetry.py), recording this server's tok/s too.""" if getattr(self, "telemetry", None) is None: from serve.telemetry import Telemetry - self.telemetry = Telemetry(extra=lambda: {"tok_s": self._tok_s(), "tok_s_mean": self._tok_s_mean()}, + self.telemetry = Telemetry(extra=lambda: {"tok_s": self._tok_s(), "tok_s_mean": self._tok_s_mean(), + "prefill_tok_s_mean": self._prefill_tok_s_mean()}, gpu_index=int(getattr(self, "gpu_index", 0) or 0), gpu_indices=getattr(self, "gpu_indices", None)) @@ -650,6 +654,12 @@ class Service: return 0.0 return s["generated"] / max(1e-6, time.time() - s["first_token"]) + def _prefill_tok_s_mean(self): + """Engine-reported mean over newly read tokens, excluding the cached prefix.""" + with self.status_lock: + reading = self.status.get("busy") and self.status.get("first_token") is None + return getattr(self.engine, "prefill_tok_s_mean", None) if reading else 0.0 + def metrics(self, all_requests=False) -> dict: """GET /metrics: what the Monitor tab shows - the engine's facts, what it is doing, the last requests, and the hardware (with a minute of history per series).""" @@ -672,6 +682,7 @@ class Service: "elapsed_s": round(now - s["started"], 1) if s.get("busy") and s.get("started") else None, "tok_s": round(self._tok_s(), 1) if state == "generating" else None, "tok_s_mean": round(self._tok_s_mean(), 1) if state == "generating" else None, + "prefill_tok_s_mean": getattr(self.engine, "prefill_tok_s_mean", None) if s.get("busy") else None, "tok_s_window_s": RATE_WINDOW_S if state == "generating" else None} if state == "reading" and progress: live["prompt_read"], live["prompt_total"] = progress diff --git a/serve/telemetry.py b/serve/telemetry.py index e746b12a..6cfd0e3b 100644 --- a/serve/telemetry.py +++ b/serve/telemetry.py @@ -256,7 +256,7 @@ class Telemetry: with self.lock: self.now = s for k in ("gpu_util", "gpu_mem_used", "gpu_temp", "gpu_power", "gpu_pcie_rx_mb", "cpu", "ram_used", - "disk_read_mb", "tok_s"): + "disk_read_mb", "tok_s", "prefill_tok_s_mean"): v = s.get(k) self.hist[k].append(round(v, 2) if isinstance(v, float) else v) time.sleep(1.0) diff --git a/serve/test_server.py b/serve/test_server.py index b3f70c55..76aa9aa2 100644 --- a/serve/test_server.py +++ b/serve/test_server.py @@ -480,6 +480,41 @@ class LiveRate(unittest.TestCase): with urllib.request.urlopen(self.base + "/metrics", timeout=10) as r: return json.loads(r.read()) + def test_prefill_rate_excludes_cached_tokens(self): + import io + import queue + from types import SimpleNamespace + engine = StrataEngine.__new__(StrataEngine) + engine.proc = SimpleNamespace(stdin=io.StringIO()) + engine.lines = queue.Queue() + engine.can_stop = False + engine.max_context = 262144 + engine.prefill_tok_s_mean = 9999.0 + engine.lines.put("PP 10000 12000 2000 1000.0") # 8000 cached, 2000 newly read in two seconds + engine.lines.put("DONE 1 12000 4000 10 stop 0 0 8000") + gen = engine.generate([1], 1, {}, threading.Event()) + self.assertIsNone(next(gen)) + self.assertEqual(engine.progress, (10000, 12000)) + self.assertEqual(engine.prefill_tok_s_mean, 1000.0) + self.svc.engine = engine + self.svc.status.update(busy=True, first_token=None) + self.assertEqual(self.metrics()["live"]["prefill_tok_s_mean"], 1000.0) + self.assertNotIn("prefill_tok_s", self.metrics()["live"]) + self.assertEqual(self.svc._prefill_tok_s_mean(), 1000.0) + self.svc.status.update(first_token=time.time(), generated=1) + self.assertEqual(self.svc._prefill_tok_s_mean(), 0.0) + self.assertEqual(list(gen), []) + timings = request_timings(12000, 1, engine.last) + self.assertEqual(timings["prompt_per_second"], 1000.0) + engine.lines.put("PP 8000 12000") + engine.lines.put("DONE 0 12000 0 0 stop 0 0 12000") + gen = engine.generate([1], 1, {}, threading.Event()) + next(gen) + self.assertIsNone(engine.prefill_tok_s_mean) + list(gen) + self.svc.status["busy"] = False + self.assertIsNone(self.metrics()["live"]["prefill_tok_s_mean"]) + def test_the_live_number_is_a_rate(self): live_samples, stop = [], threading.Event() diff --git a/serve/web/app.css b/serve/web/app.css index 82f1f2a9..4e8363d4 100644 --- a/serve/web/app.css +++ b/serve/web/app.css @@ -92,6 +92,11 @@ main { flex: 1; min-height: 0; display: flex; } .st-metric__value small { font-size: var(--st-fs-md); font-weight: var(--st-fw-medium); color: var(--st-ink-muted); margin-left: 4px; } .st-metric__sub { font-size: var(--st-fs-xs); color: var(--st-ink-muted); font-variant-numeric: tabular-nums; min-height: 1em; } .st-metric__spark { display: block; overflow: visible; } +.speed-values { display: flex; justify-content: space-between; gap: var(--st-s-3); } +.speed-values > div { display: flex; flex-direction: column; gap: 10px; min-width: 0; } +.speed-values > div:last-child { text-align: right; } +.speed-values .st-metric__value { font-size: clamp(20px, 2.2vw, var(--st-fs-stat)); } +.st-metric__spark .speed-prefill { color: color-mix(in srgb, var(--st-accent) 65%, black); } .st-metric__spark[data-tone="warn"] { color: var(--st-warn); } .st-metric__spark[data-tone="info"] { color: var(--st-info); } .monitor-row { display: grid; grid-template-columns: minmax(260px, 1fr) minmax(0, 2.4fr); gap: var(--st-s-4); } diff --git a/serve/web/app.js b/serve/web/app.js index d992389c..6e8fa6b2 100644 --- a/serve/web/app.js +++ b/serve/web/app.js @@ -109,7 +109,7 @@ async function loadHealth() { // ------------------------------------------------------------------ Monitor const METRICS = [ - {key: "speed", label: "Speed", icon: "gauge", unit: "tok/s", series: "tok_s"}, + {key: "speed", label: "Speed", icon: "gauge", unit: "t/s", series: "tok_s"}, {key: "gpu", label: "GPU load", icon: "gpu", unit: "%", series: "gpu_util", max: 100}, {key: "vram", label: "VRAM", icon: "layers", unit: "GB", series: "gpu_mem_used"}, {key: "temp", label: "GPU temp", icon: "thermometer", unit: "°C", series: "gpu_temp", tone: "warn"}, @@ -121,11 +121,17 @@ const METRICS = [ $("metrics").innerHTML = METRICS.map((m) => `
${icon(m.icon, "st-icon st-icon--sm")}${esc(m.label)} - – - + ${m.key === "speed" ? `
+
-Decode
+
-Prefill
+
` : `– + `} + stroke-width="1.6" stroke-linejoin="round" stroke-linecap="round" vector-effect="non-scaling-stroke"/> + ${m.key === "speed" ? ` + ` : ""}
`).join(""); function spark(id, values, max) { @@ -226,8 +232,14 @@ function renderMonitor(live, hw, st, eng, h, last, requests, totals, kept) { // the eight cards const speed = live.state === "generating" ? live.tok_s : last ? last.decode_tok_s : null; - setMetric("speed", speed == null ? null : fmt(speed, 1), "tok/s", live.state === "generating" ? "now" : last ? "last request" : ""); + setMetric("speed", speed == null ? null : fmt(speed, 1), "t/s", + live.state === "generating" ? "Decode now" : last ? "Decode last request" : "Decode"); + const prefill = live.state !== "idle" ? live.prefill_tok_s_mean + : last && last.prompt_ms > 0 ? Math.max(0, last.prompt_tokens - (last.reused || 0)) / (last.prompt_ms / 1000) : null; + setMetric("prefill", prefill == null ? null : fmt(prefill), "t/s", + live.state === "reading" ? "Prefill now" : live.state === "generating" ? "Prefill this request" : last ? "Prefill last request" : "Prefill"); spark("sp-speed", h.tok_s); + spark("sp-prefill", h.prefill_tok_s_mean); // a model split across several cards (issue #112): the cards show their total / mean / hottest, and each card's own const per = (f) => (hw.gpus || []).map((g) => `GPU ${g.index} ${f(g)}`).join(" · "); const multi = (hw.gpus || []).length > 1; From b353a06128f15bfb8af1a438ab3c3ab1adb20959 Mon Sep 17 00:00:00 2001 From: architectds Date: Tue, 29 Sep 2026 07:06:19 -0500 Subject: [PATCH 27/32] setup: the 3-bit models' 262K context is counted against RAM, not a fixed 90 GB IQ3_S and IQ3_XXS asked for 262K were cut to 128K on any machine under 90 GB of RAM. The limit is now counted: the experts' arena, plus the context's 8-bit KV (in RAM with KV streaming, ~13.7 KB a token), plus 24 GB of room. - A 64 GB PC still gets 128K for both models, as before. - A box with ~84 GB keeps the 262K it asked for. A Colab A100-40G (83.5 GiB) runs IQ3_S at 262K, with images, in 56 GiB. --- setup.py | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/setup.py b/setup.py index 94080d20..6b29c568 100644 --- a/setup.py +++ b/setup.py @@ -1853,9 +1853,14 @@ def main() -> int: for i, c in enumerate(CONTEXTS, 1): say(f" {i}) {c // 1024}K tokens" + (" (recommended for your GPU)" if c == rec_ctx else "")) ctx = CONTEXTS[int(ask("Context?", [str(i) for i in range(1, 6)], str(CONTEXTS.index(rec_ctx) + 1), a.yes)) - 1] - if model in ("IQ3_XXS", "IQ3_S") and ram < 90 and ctx > 131072: - warn(f"{model} with a 262K context needs more than 64 GB of RAM ({MODELS[model]['arena_gb']:.0f} GB of experts " - "+ the context): using 128K") + # The experts' arena plus the context's KV (in RAM from 64K up: ~13.7 KB/token at 8 bits) must fit, with room + # for everything else. Counted, not a fixed 90 GB: 24 GB of room keeps the rule for 64 GB PCs as it was (128K + # for both 3-bit models), while a box with ~84 GB keeps the 262K it asked for (measured: a Colab A100-40G runs + # IQ3_S at 262K with images in 56 of its 83.5 GiB). + need_gb = MODELS[model].get("arena_gb", 0) + ctx * 13 * 1056 / 1e9 + 24 + if model in ("IQ3_XXS", "IQ3_S") and ram < need_gb and ctx > 131072: + warn(f"{model} with a {ctx // 1024}K context needs about {need_gb:.0f} GB of RAM " + f"({MODELS[model]['arena_gb']:.0f} GB of experts + the context + room for the rest): using 128K") ctx = 131072 ok(f"context: {ctx} tokens") # the KV cache (the model's memory of the conversation): 8-bit, or 4-bit after a Hadamard rotation (PR #21) From 0ace554231ad55043762df5ad11f57f3698fab02 Mon Sep 17 00:00:00 2001 From: samuelishida Date: Tue, 29 Sep 2026 17:39:55 -0300 Subject: [PATCH 28/32] generate: zero session state for a native pack before the prompt path The canonical path zeroes session state from put_input at position 0, but a native pack breaks out of that loop before the first put_input and runs verify windows instead, leaving cudaMalloc'd state uninitialized. On a reused allocation that produced NaN/overflow and degenerate identical-token output. Zero the state explicitly when native_pack is set. Also removes an unused argmax() helper that emitted a compiler warning, and ignores the local .pi/ harness directory. --- .gitignore | 3 +++ src/program/generate.cpp | 15 +++++++++++++++ 2 files changed, 18 insertions(+) diff --git a/.gitignore b/.gitignore index 16f92c6b..540d401a 100644 --- a/.gitignore +++ b/.gitignore @@ -18,6 +18,9 @@ __pycache__/ # plan v0.3 P1 (repository hygiene, review E1): profiler captures and large diagnostic dumps stay out of git. *.nsys-rep + +# Pi harness metadata (local session state, not project source) +.pi/ *.sqlite *.npz *.occ1 diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 3a7b57f9..60fb76c7 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -1528,6 +1528,21 @@ int main(int argc, char** argv) { std::fprintf(stderr, "strata generate: session_init failed\n"); return 1; } + // **A GENERATE RUN ON A NATIVE PACK NEVER ZEROED THE SESSION STATE.** The canonical path zeroes it from + // `put_input` at position 0 (`session_zero`, with the embedding as `R`), but a native pack breaks out of that + // loop before the first `put_input` - it runs verify windows instead - and neither the batched prompt path + // nor the verifier zeroes anything. `sbuf` is `cudaMalloc`'d, so the GDN recurrence, the QSA KV/indexer + // state, the PLE history and `R` all started from whatever the allocator last held: finite on a fresh + // allocation and overflow/NaN after reuse, which surfaced as the whole layer stack saturating and every + // prompt decoding to the same token. `--serve` zeroes exactly this state when `resume == 0`; generate mode + // always starts from an empty sequence, so it must too. + if (native_pack) { + strata::core::session_zero(ss, g, nullptr, main_cs); + if (cudaDeviceSynchronize() != cudaSuccess) { + std::fprintf(stderr, "strata generate: zeroing the session state failed\n"); + return 1; + } + } if (g.n_qsa_layers() > 0 && ss.qsa_states[0].kv_mode == 1) std::fprintf(stderr, "strata generate: KV streaming: %lld of %lld cells per QSA layer in VRAM, the K/V in " "%.2f GiB of pinned RAM\n", (long long) (ss.qsa_states[0].n_slots * 4), From 15dd501b05a13efe92ace3461f5182ef78f57acc Mon Sep 17 00:00:00 2001 From: Enky Date: Wed, 30 Sep 2026 13:28:14 +0200 Subject: [PATCH 29/32] tests: bitwise check of native_mmvq's multi_exact contract, with a negative control (#148; CMake on the backend variables, CUDA-only) --- CMakeLists.txt | 8 + src/kernels/mmvq_multi_parity.cpp | 251 ++++++++++++++++++++++++++++++ 2 files changed, 259 insertions(+) create mode 100644 src/kernels/mmvq_multi_parity.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index f5acedc1..83682627 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -385,6 +385,14 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) add_executable(iq_parity src/kernels/iq_parity.cpp) target_include_directories(iq_parity PRIVATE ${_strata_gpu_include_directories}) target_link_libraries(iq_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + if(STRATA_ENABLE_CUDA) + # native_mmvq's multi_exact contract, bitwise: a T-column call against T single-column calls on the same Q8_1 + # bytes, with the flag off as the negative control (synthetic, GPU, no model; the control assumes 32-lane warps) + add_executable(mmvq_multi_parity src/kernels/mmvq_multi_parity.cpp) + target_include_directories(mmvq_multi_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(mmvq_multi_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_test(NAME mmvq_multi_parity COMMAND mmvq_multi_parity) + endif() add_executable(shared_expert_parity src/kernels/shared_expert_parity.cpp) target_include_directories(shared_expert_parity PRIVATE ${_strata_gpu_include_directories}) target_link_libraries(shared_expert_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) diff --git a/src/kernels/mmvq_multi_parity.cpp b/src/kernels/mmvq_multi_parity.cpp new file mode 100644 index 00000000..4902670b --- /dev/null +++ b/src/kernels/mmvq_multi_parity.cpp @@ -0,0 +1,251 @@ +// src/kernels/mmvq_multi_parity.cpp - the multi_exact contract of native_mmvq, tested bitwise. +// +// build/mmvq_multi_parity +// +// WHY IT EXISTS. `include/strata/kernels/native_mmvq.hpp` says of `native_mmvq_set_multi_exact`: +// +// "true (default): the ncols == 1 layout, every column bitwise equal to a single-column call" +// +// and `include/strata/core/verify.hpp` counts "multi-column MMVQ in exact mode" among the reasons the verify window +// produces what greedy decode would, bit for bit. Nothing tested that sentence: `iq_parity` calls `native_mmvq` +// with two columns and compares against a float64 reference at 2e-2, which cannot see a difference between one +// column and T columns. +// +// WHAT IT COMPARES. The SAME Q8_1 bytes: one T-column call against T single-column calls, each reading column j +// from the same buffer (the header: "its Q8_1 blocks at j * n_in / 32"). The quantization is shared, so the only +// thing under test is how the columns are laid out. +// +// THE DATA. The weights are random bytes, except each block's fp16 scales (`d`, and `dmin` where the format has +// one), which are rewritten as normal fp16 values in +-[2^-10, 2^-5): random bytes there would put inf and NaN in +// the outputs, and on the GPU every NaN comes out as the same canonical bit pattern, so a NaN output compares equal +// whatever operations produced it and proves nothing. With finite scales and finite normal activations (the +// precondition the header puts on the input) every output is finite, and a non-finite one fails the test. +// +// THE NEGATIVE CONTROL. The same comparison with `multi_exact` off must find differences, or the test has no power +// and its pass means nothing. Where it has power depends on T: in `native_mmvq.cu` the generic layout uses +// `NW = NCOLS <= 4 ? 4 : 2` warps, and with `WARPS = 4` and `BPI = F::BPI * NW / WARPS` it coincides with the +// exact layout at T <= 4. So the control is ASSERTED on T > 4 for every case, and at T <= 4 its silence is +// reported as that coincidence rather than skipped. The control needs a row long enough for the two layouts to +// group blocks differently: IQ4_XS takes 16 blocks per iteration with 4 warps and 8 with 2, so at n_in = 2048 (8 +// blocks of 256) each thread holds at most one block in both layouts and they coincide; its case uses n_in = 4096. +#include "strata/kernels/iq_kernels.hpp" +#include "strata/kernels/native_mmvq.hpp" + +#include + +#include +#include +#include +#include +#include +#include + +namespace { + +struct Case { + const char* name; + int type; // stable GGML type id, from the list in native_mmvq.hpp + int n_in; + int n_out; + int block_elems; // elements per weight block + int block_bytes; + int scale_at[2]; // byte offsets of the block's fp16 scales in native_mmvq.cu's block structs; -1 = none +}; + +// the types a head or a projection can have in this model +const Case CASES[] = { + {"Q4_0", 2, 2048, 512, 32, 18, {0, -1}}, // Q40Block: half d + {"Q8_0", 8, 2048, 512, 32, 34, {0, -1}}, // Q80Block: half d + {"Q4_K", 12, 2048, 512, 256, 144, {0, 2}}, // Q4KBlock: half2 dm + {"Q5_K", 13, 2048, 512, 256, 176, {0, 2}}, // Q5KBlock: half2 dm + {"Q6_K", 14, 2048, 512, 256, 210, {208, -1}}, // Q6KBlock: half d after ql, qh, scales + {"IQ4_XS", 23, 4096, 512, 256, 136, {0, -1}}, // IQ4XSBlock: half d; n_in 4096, see THE NEGATIVE CONTROL + {"Q5_K wide", 13, 4096, 2048, 256, 176, {0, 2}}, +}; + +// a normal fp16 in +-[2^-10, 2^-5): exponent field 5..9 (bias 15), any mantissa, either sign +uint16_t sane_half(std::mt19937& rng) { + const uint32_t r = rng(); + return (uint16_t) (((r >> 31) << 15) | ((5u + (r >> 10) % 5u) << 10) | (r & 0x3ffu)); +} + +// T = 4 is the last width where the two layouts coincide, T = 5 the first where they differ +const int WIDTHS[] = {1, 2, 3, 4, 5, 6, 8}; +constexpr int COINCIDE_MAX_T = 4; + +bool ck(cudaError_t e, const char* what) { + if (e == cudaSuccess) return true; + std::printf("CUDA: %s: %s\n", what, cudaGetErrorString(e)); + return false; +} + +// Returns the number of outputs that differ bit for bit; counts the non-finite outputs and the differences on +// outputs that are finite in both paths. +long long compare(const Case& c, int T, cudaStream_t s, long long& nonfinite, long long& diff_finite, bool& ran) { + ran = false; + if (!strata::kernels::native_mmvq_supported(c.type)) return -1; + + const std::size_t wbytes = strata::kernels::native_mmvq_weight_bytes(c.type, c.n_in, c.n_out); + const std::size_t qcol = strata::kernels::native_q8_1_bytes(c.n_in, 1); // Q8_1 bytes of ONE column + const std::size_t qall = strata::kernels::native_q8_1_bytes(c.n_in, T); + if (qall != qcol * (std::size_t) T) { + std::printf("%-12s T=%d: the Q8_1 bytes of T columns (%zu) are not T times those of one (%zu): the test " + "assumes contiguous columns and they are not\n", c.name, T, qall, qcol); + return -1; + } + + std::mt19937 rng(1234u + (unsigned) c.type * 97u + (unsigned) T); + std::vector w(wbytes); + for (auto& b : w) b = (uint8_t) (rng() & 0xff); + const std::size_t n_blocks = (std::size_t) c.n_out * (std::size_t) (c.n_in / c.block_elems); + if (n_blocks * (std::size_t) c.block_bytes != wbytes) { + std::printf("%-12s T=%d: %zu blocks of %d bytes are not the %zu weight bytes native_mmvq expects\n", c.name, + T, n_blocks, c.block_bytes, wbytes); + return -1; + } + for (std::size_t k = 0; k < n_blocks; ++k) + for (int at : c.scale_at) + if (at >= 0) { + const uint16_t h = sane_half(rng); + std::memcpy(&w[k * (std::size_t) c.block_bytes + (std::size_t) at], &h, 2); + } + std::vector x((std::size_t) T * c.n_in); + std::normal_distribution nd(0.f, 1.f); + for (auto& v : x) v = nd(rng); + + void* dw = nullptr; + void* xq = nullptr; + float* dx = nullptr; + float* dmulti = nullptr; + float* dsingle = nullptr; + const std::size_t ybytes = (std::size_t) T * c.n_out * 4; + if (!ck(cudaMalloc(&dw, wbytes), "malloc w") || !ck(cudaMalloc(&xq, qall), "malloc xq") || + !ck(cudaMalloc(&dx, x.size() * 4), "malloc x") || !ck(cudaMalloc(&dmulti, ybytes), "malloc multi") || + !ck(cudaMalloc(&dsingle, ybytes), "malloc single")) + return -1; + if (!ck(cudaMemcpy(dw, w.data(), wbytes, cudaMemcpyHostToDevice), "copy w") || + !ck(cudaMemcpy(dx, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "copy x")) + return -1; + + // ONE quantization, shared by both paths: the quantization is not under test + strata::kernels::quantize_q8_1_rows(dx, T, c.n_in, xq, s); + if (!ck(cudaStreamSynchronize(s), "quantize")) return -1; + + try { + strata::kernels::native_mmvq(c.type, dw, xq, dmulti, c.n_in, c.n_out, T, s); + for (int j = 0; j < T; ++j) + strata::kernels::native_mmvq(c.type, dw, (const uint8_t*) xq + (std::size_t) j * qcol, + dsingle + (std::size_t) j * c.n_out, c.n_in, c.n_out, 1, s); + } catch (const std::exception& e) { + std::printf("%-12s T=%d: %s\n", c.name, T, e.what()); + return -1; + } + if (!ck(cudaStreamSynchronize(s), "mmvq")) return -1; + + std::vector a((std::size_t) T * c.n_out), b(a.size()); + if (!ck(cudaMemcpy(a.data(), dmulti, ybytes, cudaMemcpyDeviceToHost), "read multi") || + !ck(cudaMemcpy(b.data(), dsingle, ybytes, cudaMemcpyDeviceToHost), "read single")) + return -1; + + long long diff = 0; + nonfinite = 0; + diff_finite = 0; + for (std::size_t i = 0; i < a.size(); ++i) { + float fa, fb; + std::memcpy(&fa, &a[i], 4); + std::memcpy(&fb, &b[i], 4); + const bool both_finite = std::isfinite(fa) && std::isfinite(fb); + if (!both_finite) ++nonfinite; + if (a[i] != b[i]) { + ++diff; + if (both_finite) ++diff_finite; + } + } + cudaFree(dw); cudaFree(xq); cudaFree(dx); cudaFree(dmulti); cudaFree(dsingle); + ran = true; + return diff; +} + +struct Totals { + long long checked = 0, diff = 0, diff_finite = 0, nonfinite = 0; // all widths + long long diff_finite_wide = 0; // T > COINCIDE_MAX_T only + int powerless_cases = 0; // cases where the control found no difference at any T > COINCIDE_MAX_T +}; + +int sweep(bool exact, cudaStream_t s, Totals& t) { + strata::kernels::native_mmvq_set_multi_exact(exact); + if (strata::kernels::native_mmvq_multi_exact() != exact) { + std::printf("native_mmvq_multi_exact() does not reflect what was set\n"); + return 1; + } + std::printf("\n=== multi_exact %s ===\n", exact ? "ON (the default)" : "off (negative control)"); + std::printf("%-12s %3s %10s %10s %14s %10s\n", "type", "T", "outputs", "bits diff", "finite diff", "nonfinite"); + int bad = 0; + for (const Case& c : CASES) { + long long case_wide = 0; + for (int T : WIDTHS) { + long long nf = 0, dfin = 0; + bool ran = false; + const long long diff = compare(c, T, s, nf, dfin, ran); + if (!ran) { ++bad; continue; } + const long long n = (long long) T * c.n_out; + t.checked += n; + t.diff += diff; + t.diff_finite += dfin; + t.nonfinite += nf; + if (T > COINCIDE_MAX_T) { t.diff_finite_wide += dfin; case_wide += dfin; } + const char* verdict; + if (exact) verdict = diff == 0 ? "ok" : "FAIL"; + else if (dfin > 0) verdict = "control sees it"; + else verdict = T <= COINCIDE_MAX_T ? "layouts coincide here (NW = 4)" : "no power at this T"; + std::printf("%-12s %3d %10lld %10lld %14lld %10lld %s\n", c.name, T, n, diff, dfin, nf, verdict); + if (exact && diff != 0) ++bad; + } + if (!exact && case_wide == 0) ++t.powerless_cases; + } + return bad; +} + +} // namespace + +int main() { + cudaStream_t s; + if (!ck(cudaStreamCreate(&s), "stream create")) return 1; + + Totals on, off; + const int bad = sweep(true, s, on); + const int bad_off = sweep(false, s, off); + strata::kernels::native_mmvq_set_multi_exact(true); // back to the default + + std::printf("\nmulti_exact on: %lld outputs compared, %lld differ bitwise, %lld non-finite\n", + on.checked, on.diff, on.nonfinite); + std::printf("multi_exact off: %lld outputs compared, %lld differ bitwise (%lld on finite outputs, %lld at T > %d)\n", + off.checked, off.diff, off.diff_finite, off.diff_finite_wide, COINCIDE_MAX_T); + + if (on.nonfinite != 0 || off.nonfinite != 0) { + std::printf("\nmmvq_multi_parity: FAILED. %lld non-finite outputs from finite scales and activations: the " + "bit comparison is only meaningful on finite outputs.\n", on.nonfinite + off.nonfinite); + return 1; + } + if (bad != 0 || bad_off != 0) { + std::printf("\nmmvq_multi_parity: FAILED. %d case(s) with multi_exact on differ from single-column calls " + "or did not run, %d case(s) did not run with it off. If they differ, the sentence in " + "native_mmvq.hpp does not hold, and neither does the bit-exactness verify.hpp claims.\n", + bad, bad_off); + return 1; + } + // THE NEGATIVE CONTROL, asserted where it can see something: past T = 4 the generic layout is a different one, + // so if it still finds no difference the comparison cannot tell the layouts apart and the pass proves nothing. + if (off.powerless_cases != 0) { + std::printf("\nmmvq_multi_parity: FAILED (no power). In %d case(s) no output differs with multi_exact off at " + "any T > %d, where the generic layout is not the exact one: for those cases this comparison " + "cannot tell the two layouts apart, so their pass above proves nothing.\n", off.powerless_cases, + COINCIDE_MAX_T); + return 1; + } + std::printf("\nmmvq_multi_parity: ok. With multi_exact on every column is bitwise equal to a single-column " + "call; with it off the control finds differences at T > %d in every case, so the comparison has " + "power.\n", + COINCIDE_MAX_T); + return 0; +} From c3242f095c18c51805093b86941e95dbed9573cc Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Wed, 30 Sep 2026 13:28:30 +0200 Subject: [PATCH 30/32] generate: the session state is zeroed for every pack in CLI generate mode (#167 follow-up); no .pi/ ignore line --- .gitignore | 1 - src/program/generate.cpp | 12 ++++++------ 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/.gitignore b/.gitignore index 540d401a..cb227e32 100644 --- a/.gitignore +++ b/.gitignore @@ -20,7 +20,6 @@ __pycache__/ *.nsys-rep # Pi harness metadata (local session state, not project source) -.pi/ *.sqlite *.npz *.occ1 diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 60fb76c7..5d7894c7 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -1536,12 +1536,12 @@ int main(int argc, char** argv) { // allocation and overflow/NaN after reuse, which surfaced as the whole layer stack saturating and every // prompt decoding to the same token. `--serve` zeroes exactly this state when `resume == 0`; generate mode // always starts from an empty sequence, so it must too. - if (native_pack) { - strata::core::session_zero(ss, g, nullptr, main_cs); - if (cudaDeviceSynchronize() != cudaSuccess) { - std::fprintf(stderr, "strata generate: zeroing the session state failed\n"); - return 1; - } + // (#167) Every pack, not only a native one: a canonical pack whose prompt goes through the batched prompt path + // (--prefill) starts at position 0 without a put_input, so it never zeroed the state either. + strata::core::session_zero(ss, g, nullptr, main_cs); + if (cudaDeviceSynchronize() != cudaSuccess) { + std::fprintf(stderr, "strata generate: zeroing the session state failed\n"); + return 1; } if (g.n_qsa_layers() > 0 && ss.qsa_states[0].kv_mode == 1) std::fprintf(stderr, "strata generate: KV streaming: %lld of %lld cells per QSA layer in VRAM, the K/V in " From bb628ce12fe44aa98044e56747ce396484dfebd0 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Wed, 30 Sep 2026 13:29:18 +0200 Subject: [PATCH 31/32] A fatal CUDA fault in the prompt path exits at once instead of hanging until the watchdog (#224); CMake warns when sm_120 is built with CUDA < 13.0 (#220, #224); iq_pack writes native_experts.txt under a temporary name, so a stop part-way leaves no partial pack (#172) --- CMakeLists.txt | 5 +++++ src/program/generate.cpp | 7 +++++++ tools/iq_pack.py | 8 +++++++- 3 files changed, 19 insertions(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 83682627..e74f6bfc 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -73,6 +73,11 @@ if(STRATA_ENABLE_CUDA) "Strata needs an NVIDIA GPU of compute capability 7.5 or newer (RTX 20 / 30 / 40 / 50 series), but " "CMAKE_CUDA_ARCHITECTURES is '${CMAKE_CUDA_ARCHITECTURES}'.") endif() + # #220 / #224: RTX 50 engines built with CUDA 12.8 crashed in the prompt path on Linux (13.0 and newer did not) + if(_base GREATER_EQUAL 120 AND CMAKE_CUDA_COMPILER_VERSION VERSION_LESS 13.0) + message(WARNING "Building for sm_${_base} (RTX 50) with CUDA ${CMAKE_CUDA_COMPILER_VERSION}: engines built with " + "CUDA 12.8 crashed on long prompts on these cards (issues #220, #224). Use CUDA 13.0 or newer.") + endif() endforeach() message(STATUS "Strata: CUDA enabled, arch ${CMAKE_CUDA_ARCHITECTURES}") set(_strata_gpu_runtime_target CUDA::cudart) diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 5d7894c7..60700870 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -4044,6 +4044,13 @@ int main(int argc, char** argv) { if (!stop_req.load()) { std::fprintf(stderr, "strata serve: %s\n", err.c_str()); std::printf("ERR %s\n", err.c_str()); + // #224: a CUDA fault (an illegal address) poisons the context for the whole process, and + // unwinding the destructors on it could hang until the 60 s watchdog: leave at once + if (cudaPeekAtLastError() != cudaSuccess) { + std::fflush(stdout); + std::fflush(stderr); + std::_Exit(1); + } return 1; } cancelled = true; // stopped while reading the prompt: refill the lent slots below, then DONE cancel diff --git a/tools/iq_pack.py b/tools/iq_pack.py index d86f53c4..f0ff890b 100644 --- a/tools/iq_pack.py +++ b/tools/iq_pack.py @@ -308,7 +308,10 @@ def main() -> int: blob = per[0] + per[1] + per[2] layout.append((l, ts[0].type_id, ts[2].type_id, offset, blob, ts)) offset += blob * n_expert - with open(out / "native_experts.txt", "w", encoding="utf-8", newline="\n") as fo: + # written to a temporary name and renamed only when every layer is in: a stop part-way (a layer split across + # shards, #171) left a partial native_experts.txt that the next setup run took as a finished pack (#172) + tmp = out / "native_experts.txt.tmp" + with open(tmp, "w", encoding="utf-8", newline="\n") as fo: fo.write("# strata native experts v3: layer gu_type d_type offset blob_bytes gate_off up_off down_off [shard] " "(n_expert %d, total %d; absolute offsets in %s, or in the named shard beside it)\n" % (n_expert, offset, src.name)) @@ -316,10 +319,13 @@ def main() -> int: ws = [model.where[t.name] for t in ts] if len({w[3] for w in ws}) != 1: print("layer %d: its gate/up/down tensors are in different shards" % l) + fo.close() + tmp.unlink() return 1 gg, shard = ws[0][0], ws[0][3] line = "%d %d %d %d %d %d %d %d" % (l, gt, dt, off, blob, *[gg.data_start + t.offset for t in ts]) fo.write(line + ("" if shard == src else " " + shard.name) + "\n") + tmp.replace(out / "native_experts.txt") if a.skip_experts or not a.experts_bin: if (out / "experts.bin").exists() and not a.experts_bin: print("note: %s/experts.bin exists; the engine reads it instead of the GGUF" % out) From 0ea2fc3176e3f8bf571c3bd2731c0d476cd20b10 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Wed, 30 Sep 2026 11:46:25 +0200 Subject: [PATCH 32/32] Engine 0.1.29: sampled answers up to 40% faster with the same tokens (#197), faster prompt kernels (#187, #188, #207), correctness fixes (#154); setup requires it --- CMakeLists.txt | 2 +- setup.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index e74f6bfc..10cdc871 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -8,7 +8,7 @@ # below refuses anything older: silently building for a pre-Ampere arch would produce a binary that runs # and is wrong about its own performance, which is the worst of both outcomes. cmake_minimum_required(VERSION 3.24) -project(strata VERSION 0.1.28 LANGUAGES CXX) +project(strata VERSION 0.1.29 LANGUAGES CXX) add_compile_definitions(STRATA_VERSION="${PROJECT_VERSION}") # issue #31: release builds keep a PDB beside the exe (not shipped in it), so a minidump from a stalled engine can # be read back to the exact source line diff --git a/setup.py b/setup.py index 6b29c568..e05cda39 100644 --- a/setup.py +++ b/setup.py @@ -58,7 +58,7 @@ PREBUILT_ASSET = "strata-windows-x64.zip" if WIN else "strata-linux-x64.zip" # the CUDA libraries the ready-made engine loads (the same CUDA 13.0 it is built with), from NVIDIA's pip packages CUDA_WHEELS = ["nvidia-cublas==13.0.2.14", "nvidia-cuda-runtime==13.0.96"] MIN_DRIVER = 580 # CUDA 13.0 -MIN_ENGINE = (0, 1, 28) # v0.1.28: the expert cache reserves the draft head, a cancelled request no longer fails the next; v0.1.27: RTX 20 (sm_75) in the ready-made engine, the HIP build without CUDA headers; v0.1.26: the draft layer's prompt pass in batches; v0.1.25: faster prompts (grouping off the copy engine, fused hyper-connection kernels), AMD HIP backend, --kv k8v4; v0.1.24: long prompts faster (QSA select on tensor cores); v0.1.23: image requests honor sampling, 8 GB cards start, batched verify window; v0.1.22: faster prompts (tensor-core attention), multi-GPU across images/steering/KV streaming; v0.1.21: multi-GPU layer split (--gpus); v0.1.20: system-prompt checkpoint, PCIe probe, hit rate; v0.1.19: penalties +MIN_ENGINE = (0, 1, 29) # v0.1.29: sampled answers faster (split top-k), #154 correctness fixes; v0.1.28: the expert cache reserves the draft head, a cancelled request no longer fails the next; v0.1.27: RTX 20 (sm_75) in the ready-made engine, the HIP build without CUDA headers; v0.1.26: the draft layer's prompt pass in batches; v0.1.25: faster prompts (grouping off the copy engine, fused hyper-connection kernels), AMD HIP backend, --kv k8v4; v0.1.24: long prompts faster (QSA select on tensor cores); v0.1.23: image requests honor sampling, 8 GB cards start, batched verify window; v0.1.22: faster prompts (tensor-core attention), multi-GPU across images/steering/KV streaming; v0.1.21: multi-GPU layer split (--gpus); v0.1.20: system-prompt checkpoint, PCIe probe, hit rate; v0.1.19: penalties PY_PACKAGES = ["numpy", "jinja2", "regex", "pyyaml", "tqdm", "requests", "cmake", "ninja", "pillow", "psutil"] MODELS = {