From 661ff2933941eb25418e02bfa6736d00a49494c7 Mon Sep 17 00:00:00 2001 From: Krypto-Whitehat <108442815+Krypto-Whitehat@users.noreply.github.com> Date: Mon, 12 Oct 2026 01:55:02 +0200 Subject: [PATCH 01/67] STRATA_ADAPT_OVERLAP: opt-in on every backend (RTX 5090 Laptop, Linux CUDA: 84.6 vs 106.6 tok/s decode median with it, 5 generations of 256 tokens from one build); log the state in both directions Linux CUDA had it on by default since 0.1.43, measured on an RTX A4000 (+5.5..8.3% decode) and a Tesla P100 (+4.4%). An RTX 5090 Laptop with a native IQ3_XXS pack and --expert-cache-per-layer decodes 21% slower with it, and the overlap is the default only there. The switch is now =1 turns it on everywhere, and the startup log names the state (with the reason when it cannot run), so a decode-rate drop is not the only way to see it. Unchanged: the copy path, the gate predicates and the tokens (same tokens with or without it). Fixes #2010 --- docs/DETAILS.md | 12 ++++++++---- src/program/generate.cpp | 41 ++++++++++++++++++++++------------------ 2 files changed, 31 insertions(+), 22 deletions(-) diff --git a/docs/DETAILS.md b/docs/DETAILS.md index bcdad031..7b8bc701 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -1697,14 +1697,18 @@ the pairs in which the switched arm won). They are here so you can try them on y -0.1% (5/6). Boxes that hold all experts in RAM never use the stage buffers. - **`STRATA_ADAPT_LAG=2`: the adaptive tier's copies are waited for one window later** (#764). Decode, 6 pairs: Tesla P100 (PCIe 3.0 x16) +3.5% (6/6 pairs faster), RTX 5070 +0.2% (4/6), RTX 3060 -1.3% (0/6), so it stays opt-in. -- **`STRATA_ADAPT_OVERLAP` (CUDA on Linux: on, `=0` turns it off; CUDA on Windows and HIP: `=1` turns it on, since an RTX 5070 on Windows decoded Q2_0 2.6% slower with it and IQ3_XXS no faster): the adaptive tier's copies land while the next +- **`STRATA_ADAPT_OVERLAP` (`=1` turns it on, on every backend; the startup log names the state and, when it cannot run, why): the adaptive tier's copies land while the next window runs, with the same tokens.** The window takes the swaps at the same moment as with #463's wait (so the same experts run on the GPU and the CPU in every window), but the copies go in layer order and the verify window holds a layer's plan back until that layer's copies have landed, instead of the whole window waiting for the round (about 10 ms every fourth window on an A4000, PCIe 3.0 x16). One GPU, the whole arena in RAM, no `--adapt-async`, `--pipeline-windows`, `STRATA_ADAPT_LAG`, - `STRATA_ADAPT_NOWAIT` or `STRATA_DMA_BATCH`; otherwise the log says why it is off. RTX A4000, 6 interleaved pairs each, - decode median tok/s: Q2_0 16 GB 62.5 -> 66.2 (+5.9%), Q2_0 as a 12 GB card 51.3 -> 54.2 (+5.7%), IQ3_XXS 16 GB 48.6 -> 52.6 (+8.3%), - IQ3_XXS as 12 GB 39.3 -> 41.5 (+5.5%), 6/6 pairs faster every time. + `STRATA_ADAPT_NOWAIT` or `STRATA_DMA_BATCH`. On by default on CUDA on Linux since 0.1.43, opt-in on Windows and HIP; + opt-in on every backend since #2010, after an RTX 5090 Laptop lost 21% decode with it. What it is worth per box: an RTX A4000 (6 + interleaved pairs each, decode median tok/s: Q2_0 16 GB 62.5 -> 66.2 (+5.9%), Q2_0 as a 12 GB card 51.3 -> 54.2 (+5.7%), + IQ3_XXS 16 GB 48.6 -> 52.6 (+8.3%), IQ3_XXS as 12 GB 39.3 -> 41.5 (+5.5%), 6/6 pairs faster every time) and a Tesla P100 + (+4.4%) gain, but an RTX 5070 on Windows loses 2.6% on Q2_0 (IQ3_XXS no faster) and an RTX 5090 Laptop (WSL2, Core Ultra 9 + 275HX, native IQ3_XXS pack, `--expert-cache-per-layer`) loses 21%: 84.6 vs 106.6 tok/s medians of 5 generations of 256 + tokens from one build, the slowest of the fast run above the fastest of the slow one (#2010). - **`STRATA_ADAPT_CALLBACK_WARMUP` (Linux, on by default since 0.1.43.1; =0 turns it off): start the GPU host-callback thread before the CPU pool pins the host thread.** A callback thread created later can inherit the host's one-CPU affinity and compete with the verifier spinning for its signal (#1975). The warm-up runs and synchronizes one no-op host callback before diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 99489893..339128cc 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -1336,21 +1336,21 @@ int adapt_lag() { return v; } -/// 0.1.43 STRATA_ADAPT_OVERLAP=1: the adaptive tier's copies land while the next decode window already runs. The window +/// STRATA_ADAPT_OVERLAP=1: the adaptive tier's copies land while the next decode window already runs. The window /// sees the swapped-in experts as resident from its first layer, exactly as after #463's wait (so the tokens are the same /// ones); what changes is only when the bytes arrive: the copies go in layer order and the verify window holds a layer's /// plan back until that layer's copies have landed (AdaptGate in strata/core/verify.hpp). The ~10 ms a 96-swap round -/// took at the next window's start (PCIe 3.0 x16, Q2_0) is then hidden behind the window. On for CUDA (=0 turns it off), opt-in on HIP. +/// took at the next window's start (PCIe 3.0 x16, Q2_0) is then hidden behind the window. Opt-in on every backend +/// (=1 turns it on); the startup log names the state, and why when it cannot run. bool adapt_overlap() { static const bool v = [] { const char* e = std::getenv("STRATA_ADAPT_OVERLAP"); -#if defined(STRATA_USE_HIP) - return e && e[0] == '1'; // HIP: not measured yet, opt-in -#elif defined(_WIN32) - return e && e[0] == '1'; // Windows CUDA: opt-in (RTX 5070, Q2_0: -2.6% story decode with it, IQ3_XXS neutral) -#else - return !(e && e[0] == '0'); // Linux CUDA: on since 0.1.43 (same tokens, +5.5..8.3% decode on an A4000, +4.4% P100); =0 turns it off -#endif + // Opt-in on every backend (#2010). Windows CUDA since 0.1.43: an RTX 5070 decoded Q2_0 2.6% slower with it + // (story decode, -2.1% code), IQ3_XXS no faster. Linux CUDA was on by default from 0.1.43 (same tokens, +5.5..8.3% + // decode on an A4000, +4.4% on a P100) until an RTX 5090 Laptop (WSL2, Core Ultra 9 275HX, native IQ3_XXS pack, + // --expert-cache-per-layer) decoded 21% slower with it: 84.6 vs 106.6 tok/s medians of 5 generations of 256 + // tokens from one build, the slowest of the fast run above the fastest of the slow one. + return e && e[0] == '1'; }(); return v; } @@ -8307,8 +8307,10 @@ int main(int argc, char** argv) { bool aflipped = false; // the pending swaps are in the tables and their copies may still be landing bool aov = false; int64_t aov_flips = 0; - if (adapt_overlap()) { - const char* why = multi_gpu || !stages.empty() ? "not on a layer split" + // #2010: the overlap is opt-in on every backend now, so the off state is the default and has to be visible too. + // The predicates are side-effect free, so they are read in both states: they name why it could not run. + const bool aov_want = adapt_overlap(); + const char* aov_why = multi_gpu || !stages.empty() ? "not on a layer split" : peer.valid() ? "not with --peer-device" : remote_opt ? "not with --remote-expert-opt" : o.adapt_async ? "not with --adapt-async" @@ -8323,12 +8325,13 @@ int main(int argc, char** argv) { ? "not in the resident RAM mode unless STRATA_ADAPT_OVERLAP_RESIDENT=1" : drive.d.usage.empty() ? "the adaptive tier is off" : nullptr; - if (why == nullptr) { + if (aov_want) { + if (aov_why == nullptr) { agate.ticks.resize((size_t) g.n_layers + 1); for (int64_t l = 0; l <= g.n_layers; ++l) agate.ticks[(size_t) l] = {&agate, (int32_t) l}; agate.has.assign((size_t) g.n_layers, 0); - if (!ver.set_adapt_gate(&agate)) why = "the device-planned layers (STRATA_VERIFY_DEVICE_PLAN) are on"; - if (why == nullptr && !(std::getenv("STRATA_ADAPT_SIGNAL") && std::getenv("STRATA_ADAPT_SIGNAL")[0] == 'h')) { + if (!ver.set_adapt_gate(&agate)) aov_why = "the device-planned layers (STRATA_VERIFY_DEVICE_PLAN) are on"; + if (aov_why == nullptr && !(std::getenv("STRATA_ADAPT_SIGNAL") && std::getenv("STRATA_ADAPT_SIGNAL")[0] == 'h')) { // the landing of each layer's copies is told by a stream-ordered D2H copy of the layer number into pinned memory // (STRATA_ADAPT_SIGNAL=host: a host function instead). No callback thread has to be scheduled while the pool's workers spin on every other CPU int32_t* vals = nullptr; void* hp = nullptr; @@ -8344,13 +8347,15 @@ int main(int argc, char** argv) { } else { (void) cudaGetLastError(); } } } - aov = why == nullptr; + aov = aov_why == nullptr; if (aov) std::fprintf(stderr, "strata serve: adaptive overlap (STRATA_ADAPT_OVERLAP=0 turns it off): the adaptive tier's copies land while the next window runs " "(same tokens, a layer waits for its own copies)\n"); - else if (std::getenv("STRATA_ADAPT_OVERLAP") != nullptr) // quiet when it was only the default - std::fprintf(stderr, "strata serve: STRATA_ADAPT_OVERLAP=1 is off: %s\n", why); - } + else if (std::getenv("STRATA_ADAPT_OVERLAP") != nullptr) // the env var was set: say what stopped it + std::fprintf(stderr, "strata serve: STRATA_ADAPT_OVERLAP=1 is off: %s\n", aov_why); + } else + std::fprintf(stderr, "strata serve: adaptive overlap: off%s%s\n", + aov_why ? ": " : " (STRATA_ADAPT_OVERLAP=1 turns it on)", aov_why); // a layer split's later stages keep a copy of the residency table on their devices, and swap on their own auto res_upload = [&]() { if (d_res != nullptr) From 0cf3d51030e3c80f51a1224692b0a3f2dd33fcd3 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 12 Oct 2026 09:44:07 +0200 Subject: [PATCH 02/67] ple: the slow-direct probe only warns on every platform (#2040: a SATA SSD tops out under the NVMe-calibrated 15K rows/s bar and mmap was 7x slower there); STRATA_PLE_AUTO_MMAP=1 keeps the 0.1.42 switch --- docs/DETAILS.md | 2 +- src/program/generate.cpp | 9 ++++----- sycl/src/program/generate.cpp | 9 ++++----- 3 files changed, 9 insertions(+), 11 deletions(-) diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 7b8bc701..2b55a404 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -1844,7 +1844,7 @@ the document, +0.4% on the chat. Details: `bench/results/2026-09-27-esp/`. - **RAM:** all 24,576 experts, pinned. The CPU computes the experts that are not on the GPU **in place**, at the same time as the GPU works on the cached ones (AVX-512 / AVX2 kernels, ggml's for the i-quants). - **SSD:** the 28.8 GB n-gram table, a few rows per token, read unbuffered past the OS cache (`--ple-io direct`, the - default, made for SSDs; on a rotational disk `--ple-io ram` keeps the table in RAM, #605). The engine reads the table + default, made for SSDs; on a rotational disk `--ple-io ram` keeps the table in RAM, #605). A start-up probe warns when direct reads measure slow (under 15K rows/s) but never switches by itself (since 0.1.43.1; `STRATA_PLE_AUTO_MMAP=1` brings back the 0.1.42 switch to `--ple-io mmap`): the bar is calibrated for NVMe, a SATA SSD tops out at 10-14K rows/s with direct's 16 reads in flight, and on one (Linux, 77.8K-token prompt) mmap read 2.1K rows/s against direct's 14.4K (#2040), while on a Windows box with a slow mapped file mmap stalled prompts (#1984). The engine reads the table in the format the GGUF has it: IQ4_NL (the default table), Q4_0, Q5_0, Q5_1, Q8_0, FP8 (E4M3 with a scale) or BF16. Measured on 4,000 random rows against the checkpoint's own BF16 table, the mean per-row error is Q8_0 0.53%, FP8 2.64%, Q5_1 3.78%, Q5_0 4.25%, IQ4_NL 7.60%, Q4_1 7.80%, Q4_0 8.55% (a Q8_0 table is 54 GB, an IQ4_NL one 28.8 GB). On the Q2_0 model, 700 teacher-forced tokens, the mean KL against the BF16 table is 0.0117 (Q5_0), 0.0121 (Q5_1), 0.0125 diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 339128cc..1b330b6e 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -3186,13 +3186,12 @@ int main(int argc, char** argv) { if (rps >= kSlowRowsPerS) std::fprintf(stderr, "strata generate: PLE direct read probe: %.0f rows/s (fine)\n", rps); if (rps > 0 && rps < kSlowRowsPerS) { - // #1984 #1971: on Windows the mapped reads stalled prompts (the first chunk waits for 16 serial page faults - // a token from a cold table with no progress mark), so there the switch is only made when asked for + // #1984 #1971 #2040: on no platform is the switch made on its own. Windows: the mapped reads stalled prompts (the first chunk waits for 16 serial page faults + // a token from a cold table with no progress mark). Linux SATA SSD: the 15K rows/s bar is NVMe-calibrated, a SATA SSD + // tops out at 10-14K with direct's 16 reads in flight and mapped reads were 7x slower. The switch is only made when asked for // (STRATA_PLE_AUTO_MMAP=1, the 0.1.42 behaviour); otherwise the slow probe warns and direct is kept. bool auto_mmap = !o.ple_io_explicit; -#if defined(_WIN32) if (const char* am = std::getenv("STRATA_PLE_AUTO_MMAP"); am == nullptr || std::atoi(am) == 0) auto_mmap = false; -#endif if (auto_mmap) { std::fprintf(stderr, "strata generate: --ple-io direct measures slow here (%.0f rows/s, about %.0f MB/s of " "random 4 KiB reads): using --ple-io mmap instead (the OS file cache holds the pages; " @@ -3208,7 +3207,7 @@ int main(int argc, char** argv) { } else { std::fprintf(stderr, "strata generate: WARNING: --ple-io direct measures slow here (%.0f rows/s, about %.0f " "MB/s of random 4 KiB reads): a prompt can spend minutes reading layer 1 and trip the " - "stall watchdog (#1425, #1629). --ple-io mmap was 40-100x faster on such drives; " + "stall watchdog (#1425, #1629). --ple-io mmap was 40-100x faster on some DRAM-less NVMe drives but 7x slower on a SATA SSD (#2040), so it is not chosen for you; " "--ple-io ram needs the RAM for the table%s\n", rps, rps * 4096.0 / 1e6, o.ple_io_explicit ? "" : " (kept direct: pass --ple-io mmap or --ple-io ram to change it)"); } diff --git a/sycl/src/program/generate.cpp b/sycl/src/program/generate.cpp index 32488963..b1a77d5b 100644 --- a/sycl/src/program/generate.cpp +++ b/sycl/src/program/generate.cpp @@ -3003,13 +3003,12 @@ int main(int argc, char **argv) try { if (rps >= kSlowRowsPerS) std::fprintf(stderr, "strata generate: PLE direct read probe: %.0f rows/s (fine)\n", rps); if (rps > 0 && rps < kSlowRowsPerS) { - // #1984 #1971: on Windows the mapped reads stalled prompts (the first chunk waits for 16 serial page faults - // a token from a cold table with no progress mark), so there the switch is only made when asked for + // #1984 #1971 #2040: on no platform is the switch made on its own. Windows: the mapped reads stalled prompts (the first chunk waits for 16 serial page faults + // a token from a cold table with no progress mark). Linux SATA SSD: the 15K rows/s bar is NVMe-calibrated, a SATA SSD + // tops out at 10-14K with direct's 16 reads in flight and mapped reads were 7x slower. The switch is only made when asked for // (STRATA_PLE_AUTO_MMAP=1, the 0.1.42 behaviour); otherwise the slow probe warns and direct is kept. bool auto_mmap = !o.ple_io_explicit; -#if defined(_WIN32) if (const char* am = std::getenv("STRATA_PLE_AUTO_MMAP"); am == nullptr || std::atoi(am) == 0) auto_mmap = false; -#endif if (auto_mmap) { std::fprintf(stderr, "strata generate: --ple-io direct measures slow here (%.0f rows/s, about %.0f MB/s of " "random 4 KiB reads): using --ple-io mmap instead (the OS file cache holds the pages; " @@ -3025,7 +3024,7 @@ int main(int argc, char **argv) try { } else { std::fprintf(stderr, "strata generate: WARNING: --ple-io direct measures slow here (%.0f rows/s, about %.0f " "MB/s of random 4 KiB reads): a prompt can spend minutes reading layer 1 and trip the " - "stall watchdog (#1425, #1629). --ple-io mmap was 40-100x faster on such drives; " + "stall watchdog (#1425, #1629). --ple-io mmap was 40-100x faster on some DRAM-less NVMe drives but 7x slower on a SATA SSD (#2040), so it is not chosen for you; " "--ple-io ram needs the RAM for the table%s\n", rps, rps * 4096.0 / 1e6, o.ple_io_explicit ? "" : " (kept direct: pass --ple-io mmap or --ple-io ram to change it)"); } From d1ab65a18b9a83ba7ade4ebc519f013245e13278 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 12 Oct 2026 09:46:02 +0200 Subject: [PATCH 03/67] setup: a BUILD.json is trusted only beside an engine binary of the source's version; a build that leaves the old binary is neither stamped nor installed (#2054) --- setup.py | 34 +++++++- tools/test_setup_stale_stamp.py | 144 ++++++++++++++++++++++++++++++++ 2 files changed, 174 insertions(+), 4 deletions(-) create mode 100644 tools/test_setup_stale_stamp.py diff --git a/setup.py b/setup.py index 5fbe72c8..e5082989 100644 --- a/setup.py +++ b/setup.py @@ -2642,7 +2642,7 @@ def build_engine_hip(gpu, llama, vision="none") -> Path: has_archs = set(archs) <= set(meta.get("archs", [])) floor = cpu_floor(cpu_info()[1]) # "" on an AVX2 CPU: the normal engine engine_ok = meta.get("backend") == "hip" and (eng / EXE).exists() and meta.get("src") == src and has_archs and \ - (meta.get("isa_floor") or "") == floor + (meta.get("isa_floor") or "") == floor and not stale_binary(eng / EXE) vision_ok = vision == "none" or ((eng / VEXE).exists() and meta.get("vision_src") == vsrc) if engine_ok and vision_ok: ok("engine already built for this PC") @@ -2671,6 +2671,10 @@ def build_engine_hip(gpu, llama, vision="none") -> Path: "-DCMAKE_PREFIX_PATH=" + ";".join([str(root), *libs]), f"-DCMAKE_HIP_FLAGS=--rocm-path={root} --rocm-device-lib-path={bitcode}", f"-DSTRATA_GGML_DIR={llama}", *isa_floor_defs(floor, ROOT / "build-hip", meta)], None, "") + if stale_binary(ROOT / "build-hip" / EXE): # #2054: no stamp for a binary of another version + fail(f"the engine build finished without a new engine ({EXE} is version " + f"{binary_engine_version(ROOT / 'build-hip' / EXE)}, this source is {source_version()}): " + "the installed engine is left as it was", "delete the folder build-hip and run this again") shutil.copy2(ROOT / "build-hip" / EXE, eng / EXE) meta = {"source": "local-hip", "backend": "hip", "version": source_version(), "archs": archs, "vision": "none", "lib_dirs": dirs, "src": src, **({"isa_floor": floor} if floor else {})} @@ -3108,7 +3112,7 @@ def update_installed_engine(url_base, toolkit=None) -> None: "starting the installed one") return if meta.get("backend") == "hip": # AMD: compiled here, again when its source changed - if meta.get("src") != source_hash(ENGINE_SOURCES): + if meta.get("src") != source_hash(ENGINE_SOURCES) or stale_binary(eng / EXE): try: usable = [x for x in amd_gpus() if amd_problem(x) is None] g = next((x for x in usable if x["arch"] in meta.get("archs", [])), usable[0] if usable else None) @@ -3125,7 +3129,7 @@ def update_installed_engine(url_base, toolkit=None) -> None: local = meta.get("source") == "local" vision = meta.get("vision") or "none" if local: # compiled here: is it older than the source (a git pull)? - if meta.get("src") == source_hash(ENGINE_SOURCES) and \ + if meta.get("src") == source_hash(ENGINE_SOURCES) and not stale_binary(eng / EXE) and \ (vision == "none" or meta.get("vision_src") == source_hash(VISION_SOURCES)): return elif ver >= MIN_ENGINE: @@ -3400,7 +3404,7 @@ def build_engine(gpu, vision, yes, llama, toolkit=None) -> Path: new_arch = local and not set(archs) <= built floor = cpu_floor(cpu_info()[1]) # "" on an AVX2 CPU: the normal engine engine_ok = local and (eng / EXE).exists() and meta.get("src") == src and not new_arch and \ - (meta.get("isa_floor") or "") == floor + (meta.get("isa_floor") or "") == floor and not stale_binary(eng / EXE) vision_ok = not want_vision or ((eng / VEXE).exists() and (not local or meta.get("vision_src") == vsrc)) if engine_ok and vision_ok: ok("engine already built for this PC") @@ -3421,6 +3425,10 @@ def build_engine(gpu, vision, yes, llama, toolkit=None) -> Path: *host_compiler_defs(True), *engine_defs(archs, toolkit), *isa_floor_defs(floor, bdir, meta)], vcvars, "build-strata-cuda12.bat" if t12 else "build-strata.bat") + if stale_binary(bdir / EXE): # #2054: the stamp below is written only for a binary of this source + fail(f"the engine build finished without a new engine ({EXE} is version {binary_engine_version(bdir / EXE)}, " + f"this source is {source_version()}): the installed engine and its stamp are left as they were", + "the build folder " + str(bdir) + " may be configured for something else: delete it and run this again") shutil.copy2(bdir / EXE, eng / EXE) if not vision_ok: say(" Compiling the image encoder" + (" with CUDA (10-20 minutes, once) ..." if vision == "gpu" else " ...")) @@ -4067,6 +4075,24 @@ def source_version() -> str: return m.group(1) if m else "0" +def binary_engine_version(exe) -> str | None: + """The version compiled into an engine binary (the `engine=X.Y.Z` line it prints at start; 0.1.13 and newer carry + it), read from the file without running it. None: unreadable, or a binary without it.""" + try: + m = re.search(rb"engine=(\d+\.\d+\.\d+(?:\.\d+)?)\n", Path(exe).read_bytes()) + except OSError: + return None + return m.group(1).decode() if m else None + + +def stale_binary(exe) -> bool: + """#2054: the engine binary is of another version than this source tree builds. A BUILD.json that carries the + source's hash and version cannot be trusted alone: a build that stopped (a host compiler the toolkit rejects) can + leave the old binary beside a stamp of the new source, and nothing would ever compile it again.""" + v = binary_engine_version(exe) + return v is not None and v != source_version() + + def engine_version(exe: Path) -> tuple: """The version in the engine folder's BUILD.json, or else the one compiled into the binary. A locally compiled engine is not necessarily the source's version: when compiling a `git pull` fails, the previous engine is kept diff --git a/tools/test_setup_stale_stamp.py b/tools/test_setup_stale_stamp.py new file mode 100644 index 00000000..b282215d --- /dev/null +++ b/tools/test_setup_stale_stamp.py @@ -0,0 +1,144 @@ +"""#2054: BUILD.json is trusted only beside a binary of the source's version. + +A build that stopped (nvcc rejecting a newer host gcc) once left the old engine next to a stamp of the new source, and +every later update said "engine already built for this PC" for good. `stale_binary` reads the version compiled into the +binary; `build_engine` refuses to stamp or install a binary of another version and compiles again when the installed +one is stale. + + python -m unittest tools.test_setup_stale_stamp +""" +from __future__ import annotations + +import json +import sys +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) +import setup # noqa: E402 + +GPU = {"arch": 86, "archs": [86], "name": "RTX 3060"} + + +def binary(version: str | None) -> bytes: + return b"\x7fELF....tail_role_token=0 vram_elastic=0 engine=" + version.encode() + b"\n...." if version else b"old binary" + + +class StaleBinary(unittest.TestCase): + def test_reads_the_compiled_in_version(self): + with tempfile.TemporaryDirectory() as d, mock.patch.object(setup, "source_version", lambda: "0.1.43"): + exe = Path(d) / "strata" + exe.write_bytes(binary("0.1.42")) + self.assertEqual(setup.binary_engine_version(exe), "0.1.42") + self.assertTrue(setup.stale_binary(exe)) + exe.write_bytes(binary("0.1.43")) + self.assertFalse(setup.stale_binary(exe)) + + def test_four_part_version_and_unknowns(self): + with tempfile.TemporaryDirectory() as d, mock.patch.object(setup, "source_version", lambda: "0.1.43.1"): + exe = Path(d) / "strata" + exe.write_bytes(binary("0.1.43.1")) + self.assertFalse(setup.stale_binary(exe)) + exe.write_bytes(binary("0.1.43")) + self.assertTrue(setup.stale_binary(exe)) + exe.write_bytes(binary(None)) # a binary that carries no version: not judged + self.assertFalse(setup.stale_binary(exe)) + self.assertFalse(setup.stale_binary(Path(d) / "missing")) + + +class BuildEngineStamp(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.root = Path(tmp.name) + self.eng = self.root / "engine" + self.eng.mkdir() + (self.eng / setup.EXE).write_bytes(binary("0.1.42")) + self.old_stamp = {"source": "local", "version": "0.1.42", "archs": [86], "vision": "none", + "cuda_dirs": [], "src": "oldhash", "vision_src": None} + (self.eng / "BUILD.json").write_text(json.dumps(self.old_stamp)) + self.built = binary("0.1.43") # what the fake compile leaves in the build folder + self.compiles = 0 + patches = [mock.patch.object(setup, "ROOT", self.root), + mock.patch.object(setup, "source_hash", lambda parts: "newhash"), + mock.patch.object(setup, "source_version", lambda: "0.1.43"), + mock.patch.object(setup, "install_build_tools", lambda gpu, yes: ("nvcc", None)), + mock.patch.object(setup, "toolkit_root_defs", lambda nvcc: []), + mock.patch.object(setup, "host_compiler_defs", lambda cuda: []), + mock.patch.object(setup, "engine_defs", lambda archs, tk=13: []), + mock.patch.object(setup, "isa_floor_defs", lambda *a: []), + mock.patch.object(setup, "cpu_floor", lambda avx2: ""), + mock.patch.object(setup, "cpu_info", lambda: ("cpu", True)), + mock.patch.object(setup, "cmake_build", self.fake_build), + mock.patch.object(setup, "say", lambda *a, **k: None), + mock.patch.object(setup, "ok", lambda *a, **k: None)] + for p in patches: + p.start() + self.addCleanup(p.stop) + + def fake_build(self, src, bdir, target, defs, vcvars, bat): + self.compiles += 1 + bdir.mkdir(parents=True, exist_ok=True) + (bdir / setup.EXE).write_bytes(self.built) + + def stamp(self): + return json.loads((self.eng / "BUILD.json").read_text()) + + def test_a_good_build_is_stamped(self): + setup.build_engine(GPU, "none", True, Path("llama"), toolkit=13) + self.assertEqual(self.compiles, 1) + self.assertEqual(self.stamp()["src"], "newhash") + self.assertEqual(self.stamp()["version"], "0.1.43") + self.assertEqual((self.eng / setup.EXE).read_bytes(), self.built) + + def test_a_build_that_leaves_the_old_binary_is_not_stamped_or_installed(self): + self.built = binary("0.1.42") # the build "succeeded" without producing the new engine + with self.assertRaises(SystemExit): + setup.build_engine(GPU, "none", True, Path("llama"), toolkit=13) + self.assertEqual(self.stamp(), self.old_stamp) # still the old hash: the next update compiles again + self.assertEqual((self.eng / setup.EXE).read_bytes(), binary("0.1.42")) + + def test_a_poisoned_stamp_is_compiled_again(self): + """The state #2054 found: the new source hash and version in BUILD.json, the old binary beside it.""" + (self.eng / "BUILD.json").write_text(json.dumps({**self.old_stamp, "version": "0.1.43", "src": "newhash"})) + setup.build_engine(GPU, "none", True, Path("llama"), toolkit=13) + self.assertEqual(self.compiles, 1) + self.assertEqual((self.eng / setup.EXE).read_bytes(), self.built) + + def test_a_healthy_install_is_left_alone(self): + (self.eng / setup.EXE).write_bytes(binary("0.1.43")) + (self.eng / "BUILD.json").write_text(json.dumps({**self.old_stamp, "version": "0.1.43", "src": "newhash"})) + setup.build_engine(GPU, "none", True, Path("llama"), toolkit=13) + self.assertEqual(self.compiles, 0) + + +class UpdateInstalledEngine(unittest.TestCase): + def test_a_poisoned_stamp_makes_the_update_compile(self): + with tempfile.TemporaryDirectory() as d: + root = Path(d) + eng = root / "engine" + eng.mkdir() + (eng / setup.EXE).write_bytes(binary("0.1.42")) + (eng / "BUILD.json").write_text(json.dumps({"source": "local", "version": "0.1.43", "archs": [86], + "vision": "none", "src": "newhash"})) + built = [] + with mock.patch.object(setup, "ROOT", root), \ + mock.patch.object(setup, "source_hash", lambda parts: "newhash"), \ + mock.patch.object(setup, "source_version", lambda: "0.1.43"), \ + mock.patch.object(setup, "update_engine_gpu", lambda tk: dict(GPU)), \ + mock.patch.object(setup, "get_llama_cpp", lambda: Path("llama")), \ + mock.patch.object(setup, "build_engine", lambda *a, **k: built.append(a)), \ + mock.patch.object(setup, "say", lambda *a, **k: None): + setup.update_installed_engine("http://x", 13) + self.assertEqual(len(built), 1) + built.clear() + (eng / setup.EXE).write_bytes(binary("0.1.43")) + setup.update_installed_engine("http://x", 13) + self.assertEqual(built, []) + + +if __name__ == "__main__": + unittest.main() From d320fecc854aea48bb6685504b5f6f0bd129fa20 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 12 Oct 2026 10:10:26 +0200 Subject: [PATCH 04/67] serve: the adaptive overlap's off line printed (null) after the hint (a null reason went to %s) --- src/program/generate.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 1b330b6e..d29959ab 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -8354,7 +8354,7 @@ int main(int argc, char** argv) { std::fprintf(stderr, "strata serve: STRATA_ADAPT_OVERLAP=1 is off: %s\n", aov_why); } else std::fprintf(stderr, "strata serve: adaptive overlap: off%s%s\n", - aov_why ? ": " : " (STRATA_ADAPT_OVERLAP=1 turns it on)", aov_why); + aov_why ? ": " : " (STRATA_ADAPT_OVERLAP=1 turns it on)", aov_why ? aov_why : ""); // a layer split's later stages keep a copy of the residency table on their devices, and swap on their own auto res_upload = [&]() { if (d_res != nullptr) From a683000875b0d701ec8d41e479741d16b145d73f Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 12 Oct 2026 09:47:34 +0200 Subject: [PATCH 05/67] serve: a quoted in a message is text, not the end-of-call token (#2026) --- serve/frontend.py | 14 ++++++++++---- serve/test_frontend.py | 31 +++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 4 deletions(-) diff --git a/serve/frontend.py b/serve/frontend.py index 39fa317a..27c747ff 100644 --- a/serve/frontend.py +++ b/serve/frontend.py @@ -242,7 +242,11 @@ THINK_TAGS = {"": "\U000F0E01", "": "\U000F0E02"} # the same special ids, so text with <|vision_start|><|image_pad|> before a picture took that picture's embeddings VISION_TAGS = {"<|vision_start|>": "\U000F0E03", "<|image_pad|>": "\U000F0E04", "<|vision_end|>": "\U000F0E05", "<|video_pad|>": "\U000F0E06"} -LITERAL_TAGS = {**THINK_TAGS, **VISION_TAGS} +# #2026: `` the same way. A user asking for the string verbatim handed the model the real end-of-call token +# (type 4, matched everywhere); it copied that token into its answer and the reply came back empty. An assistant +# message keeps its own: a client replaying the model's raw call text sends the tokens the model wrote. +TOOL_LITERAL_TAGS = {"": "\U000F0E07"} +LITERAL_TAGS = {**THINK_TAGS, **VISION_TAGS, **TOOL_LITERAL_TAGS} THINK_MARKS = {v: k for k, v in LITERAL_TAGS.items()} CONTROL_MARK0 = 0xF0E10 # the control tokens' marks start here, clear of the two sets above @@ -292,17 +296,19 @@ def mark_think_literals(messages: list[dict], tools: list[dict] | None, tags: di if not _has_tag(messages, tags) and not _has_tag(tools, tags): return messages, tools, False out = [] + own = {t: v for t, v in tags.items() if t not in TOOL_LITERAL_TAGS} # what an assistant message keeps as written for m in messages: m = dict(m) content = m.get("content") + mine = own if m.get("role") == "assistant" else tags for k, v in m.items(): if k != "role": - m[k] = _mark_deep(v, tags) + m[k] = _mark_deep(v, mine) if m.get("role") == "assistant" and isinstance(content, str) and content.lstrip().startswith("") \ and "" in content: i, j = content.index("") + len(""), content.index("") - m["content"] = (content[:i] + _mark(content[i:j], tags) + "" + - _mark(content[j + len(""):], tags)) + m["content"] = (content[:i] + _mark(content[i:j], own) + "" + + _mark(content[j + len(""):], own)) out.append(m) return out, _mark_deep(tools, tags), True diff --git a/serve/test_frontend.py b/serve/test_frontend.py index fc7113e6..801ad8c9 100644 --- a/serve/test_frontend.py +++ b/serve/test_frontend.py @@ -201,3 +201,34 @@ class ForcedCallOpening(unittest.TestCase): self.assertTrue(forced_call("required", one).endswith("\n")) self.assertTrue(forced_call("required", two).endswith("` a user quotes is text, not the end-of-call token (type 4: matched even without + parse_special); an assistant message replaying raw call text keeps the model's own tokens.""" + + def setUp(self): + import sys + sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tools")) + import strata_tokenizer as ST + b2u = ST.bytes_to_unicode() + self.tok = ST.Tokenizer([b2u[b] for b in range(256)] + ["", "<|im_end|>"], [], [1] * 256 + [4, 3]) + self.tags = __import__("serve.frontend", fromlist=["literal_tags"]).literal_tags(self.tok.control_tokens) + + def encode(self, role, text): + from serve.frontend import mark_think_literals, unmark_think_literals + marked, _, changed = mark_think_literals([{"role": role, "content": text}], None, self.tags) + prompt, plain = unmark_think_literals(marked[0]["content"], self.tags) + return self.tok.encode(prompt, parse_special=True, plain=plain), changed + + def test_user_text_stays_text(self): + text = "output verbatim: ." + ids, changed = self.encode("user", text) + self.assertTrue(changed) + self.assertEqual(ids, [*text.encode()]) + self.assertNotEqual(self.tok.encode(text, parse_special=True), ids) # unmarked, it was the special token + + def test_assistant_replay_keeps_its_token(self): + text = "x" + ids, _ = self.encode("assistant", text) + self.assertEqual(ids, self.tok.encode(text, parse_special=True)) From de603bb8bd4391a60ed31f3ed216c04a503f50c0 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 12 Oct 2026 09:48:19 +0200 Subject: [PATCH 06/67] serve: tool_call_recovery reads a declared tool's JSON call in a Markdown fence inside (#2037) --- serve/frontend.py | 19 ++++++++++++++++++- serve/test_frontend.py | 40 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+), 1 deletion(-) diff --git a/serve/frontend.py b/serve/frontend.py index 27c747ff..e8cc2335 100644 --- a/serve/frontend.py +++ b/serve/frontend.py @@ -722,9 +722,17 @@ def function_end(text: str) -> int: return -1 +_JSON_FENCE = re.compile(r"```[ \t]*(?:json)?[ \t]*\r?\n\s*", re.I) + + def json_tool_call(body: str, schemas: dict) -> ToolCall | None: """`{"name": N, "arguments": {...}}` (or "parameters", or the arguments as a JSON string) of a declared tool -> its - call; anything else -> None.""" + call; anything else -> None. #2037: the object may sit in a Markdown fence (```json ... ```).""" + body = body.strip() + m = _JSON_FENCE.match(body) + if m: + body = body[m.end():].rstrip() + body = body[:-3] if body.endswith("```") else body try: obj = json.loads(body) except ValueError: @@ -828,6 +836,15 @@ class OutputParser: return "param" if after[len(PARAM_START):gt] in self.schemas else "text" if after.startswith("{"): return "json" if self.schemas else "text" + if after.startswith("```") or (after and "```".startswith(after)): + # #2037: the JSON call inside a Markdown fence (```json ... ```) in the explicit wrapper + m = _JSON_FENCE.match(after) + if m: + rest = after[m.end():] + if rest.startswith("{"): + return "json" if self.schemas else "text" + return "wait" if not rest else "text" + return "wait" if "\n" not in after else "text" if not after or FUNC_START.startswith(after) or PARAM_START.startswith(after): return "wait" return "text" diff --git a/serve/test_frontend.py b/serve/test_frontend.py index 801ad8c9..f4fe3e68 100644 --- a/serve/test_frontend.py +++ b/serve/test_frontend.py @@ -232,3 +232,43 @@ class QuotedToolCallCloser(unittest.TestCase): text = "x" ids, _ = self.encode("assistant", text) self.assertEqual(ids, self.tok.encode(text, parse_special=True)) + + +class FencedJsonCallInWrapper(unittest.TestCase): + """#2037: with recovery on, a declared tool's JSON call in a Markdown fence inside is the call.""" + TOOLS = [{"name": "write_file", "parameters": {"type": "object", "properties": {"content": {"type": "string"}}}}] + PAYLOAD = '{"name": "write_file", "arguments": {"content": "hello `world`"}}' + + def run_parser(self, raw, chunk, stream_tools, recover=True, tools=None): + from serve.frontend import OutputParser + p = OutputParser(thinking=False, tools=self.TOOLS if tools is None else tools, recover=recover, + stream_tools=stream_tools) + events = [] + for i in range(0, len(raw), chunk): + events += p.feed(raw[i:i + chunk]) + events += p.finish() + return ([e.call.arguments for e in events if e.kind == "tool_call"], + "".join(e.text for e in events if e.kind == "content")) + + def test_fenced_and_bare_agree(self): + for fence in ("```json\n", "```\n", "```JSON\r\n"): + raw = f"\n{fence}{self.PAYLOAD}\n```\n" + for chunk in (len(raw), 1, 7): + for st in (False, True): + with self.subTest(fence=fence, chunk=chunk, stream_tools=st): + self.assertEqual(self.run_parser(raw, chunk, st), ([{"content": "hello `world`"}], "")) + + def test_other_fences_and_prose_stay_text(self): + raw = "\n```python\nx = 1\n```\n" + for chunk in (len(raw), 1): + self.assertEqual(self.run_parser(raw, chunk, False), ([], raw)) + raw = f"Here:\n```json\n{self.PAYLOAD}\n```\n" # no wrapper: just text + self.assertEqual(self.run_parser(raw, len(raw), False), ([], raw)) + + def test_off_without_recovery_or_for_an_undeclared_tool(self): + raw = f"\n```json\n{self.PAYLOAD}\n```\n" + calls, text = self.run_parser(raw, len(raw), False, recover=False) + self.assertEqual((calls, text), ([], raw)) + other = [{"name": "other", "parameters": {}}] + calls, text = self.run_parser(raw, len(raw), False, tools=other) + self.assertEqual((calls, text), ([], raw)) From 873a0d66b6f81186e9b1065a80f2f75232955e10 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 12 Oct 2026 09:53:25 +0200 Subject: [PATCH 07/67] serve: a client that leaves while its pictures are downloaded, waiting for the turn or encoded stops the preparation: cancel exists before prepare() (#1999) --- serve/server.py | 87 ++++++++++++++++++++++++++++++++------------ serve/test_server.py | 69 +++++++++++++++++++++++++++++++++++ 2 files changed, 133 insertions(+), 23 deletions(-) diff --git a/serve/server.py b/serve/server.py index 8e61c180..ff1b935c 100644 --- a/serve/server.py +++ b/serve/server.py @@ -305,6 +305,11 @@ class EngineStarting(RuntimeError): not a 400 about the prompt.""" +class ClientGone(Exception): + """#1999: the client hung up while its request was being prepared (an image URL downloading, a picture encoding or + waiting for its turn): nothing is left to answer.""" + + class ModelBusy(RuntimeError): """Explicit model controls must not interrupt active or queued requests.""" @@ -2229,12 +2234,14 @@ class Vision: im.save(out, format="PNG") return out.getvalue() - def encode_all(self, sources: list) -> list[tuple[Path, int]]: + def encode_all(self, sources: list, cancel=None) -> list[tuple[Path, int]]: """encode() for every image of one request: the files of this request's earlier images are never evicted to make room for a later one (#1072: with more than 64 unique images the first was deleted before the request - had read it).""" + had read it). `cancel` (#1999): a request whose client left does not encode its next pictures.""" out: list[tuple[Path, int]] = [] for src in sources: + if cancel is not None and cancel.is_set(): + raise ClientGone() out.append(self.encode(src, keep=[p for p, _ in out])) return out @@ -3538,7 +3545,22 @@ class Service: prompt, plain = unmark_think_literals(prompt, self.literals) return self.tok.encode(prompt, parse_special=True, plain=plain) - def _note_unreadable_tool_images(self, messages): + @contextlib.contextmanager + def _turn(self, cancel=None): + """The engine's single turn (self.fifo) for an image encode. #1999: a client that leaves while this request + waits for it gives its place up (ClientGone), as a queued generation does (#1619).""" + if cancel is None: + self.fifo.acquire() + else: + while not self.fifo.acquire(timeout=0.25): + if cancel.is_set(): + raise ClientGone() + try: + yield + finally: + self.fifo.release() + + def _note_unreadable_tool_images(self, messages, cancel=None): """A picture a tool returned (Claude Code's Read of an image file) that this server cannot read - it has no image encoder, or the encoder refuses that picture - becomes a short note in its place instead of a 400. Clients resend the whole history every turn, so one unreadable tool picture would fail every later request of @@ -3556,9 +3578,11 @@ class Service: if why is None: src = item["source"] try: + if cancel is not None and cancel.is_set(): + raise ClientGone() if src.startswith(("http://", "https://")): src = fetched[item["source"]] = Vision.download(src) # outside the FIFO, as in prepare() - with self.fifo: # the encoder takes its turn with the requests (see below) + with self._turn(cancel): # the encoder takes its turn with the requests (see below) self.vision.encode(src) except (ValueError, OSError) as e: why = str(e) @@ -3567,11 +3591,13 @@ class Service: content[n] = {"type": "text", "text": f"[image omitted: {why}]"} return fetched - def prepare(self, messages, tools, kwargs, max_new=None, force=None, req=None): + def prepare(self, messages, tools, kwargs, max_new=None, force=None, req=None, cancel=None): """-> (ids, thinking, max_new). An unset or non-positive max_new (some clients send -1) means "unlimited": the rest of the context. `force` (forced_call): without thinking the reply starts with it, so it ends the prompt; with thinking, Service.run writes it once the thinking is over.""" - fetched = self._note_unreadable_tool_images(messages) + # `cancel` (#1999): set when the client hangs up; the downloads, the wait for the turn and the encodes stop + # between pictures and raise ClientGone + fetched = self._note_unreadable_tool_images(messages, cancel) ids = self.encode_prompt(messages, tools, kwargs) if force and kwargs.get("enable_thinking", True) is False: ids = ids + self.tok.encode(force, parse_special=True) @@ -3585,14 +3611,18 @@ class Service: start = self.tok.encode(VISION_START, parse_special=True)[0] # An image URL is downloaded first, outside the FIFO: under it, a slow server held every other request # for as long as urlopen waited. - images = [fetched[src] if src in fetched else Vision.download(src) if src.startswith(("http://", "https://")) - else src for src in images] + def fetch(src): + if cancel is not None and cancel.is_set(): + raise ClientGone() + return fetched[src] if src in fetched else Vision.download(src) \ + if src.startswith(("http://", "https://")) else src + images = [fetch(src) for src in images] # Encode only while the engine is idle: the engine and the image encoder (a separate process) must not # run on the GPU at the same time - an encode during a running request left that request stuck at # "reading the prompt" with CPU and GPU busy, for good (reproduced). So encoding takes its turn in the # same FIFO as the requests. - with self.fifo: - encoded = (self.vision.encode_all(images) if hasattr(self.vision, "encode_all") + with self._turn(cancel): + encoded = (self.vision.encode_all(images, cancel) if hasattr(self.vision, "encode_all") else [self.vision.encode(src) for src in images]) # one <|image_pad|> per image -> one per image token. Only the markers the template writes for an image # (right after <|vision_start|>) are images: the same text inside a message (an agent reading these docs, @@ -4401,7 +4431,11 @@ def run_with_mcp(svc: Service, hub, messages, tools, kw, ids, thinking, max_new, **({"reasoning_content": "".join(reasoning).strip()} if reasoning else {}), "tool_calls": [{"function": {"name": c.name, "arguments": c.arguments}} for c in calls]}) messages += [{"role": "tool", "content": r} for r in results] - ids, thinking, max_new = svc.prepare(messages, tools, kw, max_req) + try: + ids, thinking, max_new = svc.prepare(messages, tools, kw, max_req, cancel=cancel) + except ClientGone: # #1999: the client left while a picture was prepared + done = {**done, "finish": "cancel"} + break yield "done", {**done, "completion_tokens": total, "prompt_tokens": len(ids)} @@ -5240,6 +5274,8 @@ def make_handler(svc: Service): except EngineStuck as e: # an unload or restart that could not end the engine self._json(503, {"error": {"type": "server_error", "message": str(e)}}) + except ClientGone: # #1999: the client left while the request was prepared + self._note(outcome="disconnected") except OSError: self._note(outcome="disconnected") raise # as before #332: the server's own handling @@ -5483,10 +5519,10 @@ def make_handler(svc: Service): svc.reasoning_budget(req) # a bad value is a 400 before anything is sent stop_strings(req) # ... and so is a bad stop / stop_sequences check_request_sampling(req) # ... and a sampling field of the wrong type - ids, thinking, max_new = svc.prepare(messages, tools, kw, max_new, force=force, req=req) - _debug_req("openai", req, messages, tools, max_new, thinking, len(ids)) cancel = threading.Event() - self._watch_client(cancel) # #430 #431 + self._watch_client(cancel) # #430 #431 (#1999: before prepare, which can take long) + ids, thinking, max_new = svc.prepare(messages, tools, kw, max_new, force=force, req=req, cancel=cancel) + _debug_req("openai", req, messages, tools, max_new, thinking, len(ids)) run = run_with_mcp(svc, svc.mcp, messages, tools, kw, ids, thinking, max_new, max_req, req, cancel, {t["name"] for t in extra}) if use_mcp else None chunks = openai_chunks(svc, req, ids, thinking, tools, max_new, cancel, run=run, force=force) @@ -5544,16 +5580,19 @@ def make_handler(svc: Service): return self._json(e.status, e.body()) if title is not None: return self._responses_ready(req, title) + cancel = threading.Event() + self._watch_client(cancel) # #430 #431 (#1999: before prepare, which can take long) try: - ids, thinking, tools, max_new, asm, validator, req = self._responses_prepare(req) + ids, thinking, tools, max_new, asm, validator, req = self._responses_prepare(req, cancel) + except ClientGone: + self._note(outcome="disconnected") + return except ResponsesError as e: return self._json(e.status, e.body()) except ModelBusy as e: return self._json(409, responses_error_body(str(e), "server_error", code="model_busy")) except (GpuBusy, EngineStarting, EngineStuck, EngineDied) as e: return self._json(503, responses_error_body(str(e), "server_error", code="server_error")) - cancel = threading.Event() - self._watch_client(cancel) # #430 #431 def check(text, finish): return validated_json(text, validator, finish) @@ -5626,7 +5665,7 @@ def make_handler(svc: Service): except OSError: pass - def _responses_prepare(self, req): + def _responses_prepare(self, req, cancel=None): responses_api.check_request(req) messages = responses_api.input_messages(req) tools, names, skipped = responses_api.request_tools(req) @@ -5664,12 +5703,14 @@ def make_handler(svc: Service): shown = responses_api.prompt_tools(req, tools) if svc.codex_compaction_cache else tools try: try: - ids, thinking, max_new = svc.prepare(messages, shown, kw, req.get("max_output_tokens") or 0, req=req) + ids, thinking, max_new = svc.prepare(messages, shown, kw, req.get("max_output_tokens") or 0, req=req, + cancel=cancel) except ValueError: if shown is tools: raise shown = tools # too long with the kept tools: the request as sent - ids, thinking, max_new = svc.prepare(messages, shown, kw, req.get("max_output_tokens") or 0, req=req) + ids, thinking, max_new = svc.prepare(messages, shown, kw, req.get("max_output_tokens") or 0, req=req, + cancel=cancel) except ResponsesError: raise except ValueError as e: # too long for the context, an image without vision @@ -5705,10 +5746,10 @@ def make_handler(svc: Service): svc.reasoning_budget(req) # a bad value is a 400 before anything is sent stop_strings(req) # ... and so is a bad stop / stop_sequences check_request_sampling(req) # ... and a sampling field of the wrong type - ids, thinking, max_new = svc.prepare(messages, tools, kw, max_new, force=force, req=req) - _debug_req("anthropic", req, messages, tools, max_new, thinking, len(ids)) cancel = threading.Event() - self._watch_client(cancel) # #430 #431 + self._watch_client(cancel) # #430 #431 (#1999: before prepare, which can take long) + ids, thinking, max_new = svc.prepare(messages, tools, kw, max_new, force=force, req=req, cancel=cancel) + _debug_req("anthropic", req, messages, tools, max_new, thinking, len(ids)) events = anthropic_events(svc, req, ids, thinking, tools, max_new, cancel, force=force) events = self._capture(events, "anthropic") if not req.get("stream"): diff --git a/serve/test_server.py b/serve/test_server.py index 8f5c7373..bbb176ad 100644 --- a/serve/test_server.py +++ b/serve/test_server.py @@ -5439,3 +5439,72 @@ class UntimedReads(unittest.TestCase): if __name__ == "__main__": unittest.main() + + +class PrepareCancelled(unittest.TestCase): + """#1999: a client that leaves while its pictures are prepared gives the turn up and encodes nothing more.""" + + def make(self, d, vision): + tok = ByteTokenizer() + return Service(MockEngine(tok, "ok", max_context=CTX), tok, ChatTemplate(ROOT / "serve/chat_template.jinja"), + vision=vision(d)) + + @staticmethod + def msgs(n=2): + return [{"role": "user", "content": [{"type": "text", "text": "look"}] + + [{"type": "image", "source": f"{i}.png"} for i in range(n)]}] + + def test_cancel_before_the_encode_runs_none(self): + import tempfile + calls = [] + + class V(ImageMarkers.FakeVision): + def encode(self, source): + calls.append(source) + return self.rows, 3 + with tempfile.TemporaryDirectory() as d: + svc = self.make(d, V) + cancel = threading.Event() + cancel.set() + from serve.server import ClientGone + with self.assertRaises(ClientGone): + svc.prepare(self.msgs(), None, {}, cancel=cancel) + self.assertEqual(calls, []) + self.assertTrue(svc.fifo.acquire(blocking=False)) # the turn was not left held + svc.fifo.release() + + def test_cancel_while_waiting_for_the_turn(self): + import tempfile + from serve.server import ClientGone + with tempfile.TemporaryDirectory() as d: + svc = self.make(d, ImageMarkers.FakeVision) + cancel = threading.Event() + threading.Timer(0.3, cancel.set).start() + with svc.fifo: # another request holds the engine + t0 = time.perf_counter() + with self.assertRaises(ClientGone): + svc.prepare(self.msgs(1), None, {}, cancel=cancel) + self.assertLess(time.perf_counter() - t0, 3) + + def test_cancel_between_pictures_stops_the_next_encode(self): + import tempfile + from serve.server import ClientGone, Vision + cancel, seen = threading.Event(), [] + v = Vision.__new__(Vision) + + def encode(src, keep=()): + seen.append(src) + cancel.set() # the client leaves during the first encode + return Path("x"), 3 + v.encode = encode + with self.assertRaises(ClientGone): + v.encode_all([b"a", b"b", b"c"], cancel) + self.assertEqual(seen, [b"a"]) + + def test_without_cancel_nothing_changes(self): + import tempfile + with tempfile.TemporaryDirectory() as d: + svc = self.make(d, ImageMarkers.FakeVision) + ids, _, _ = svc.prepare(self.msgs(), None, {}, cancel=threading.Event()) + self.assertEqual(ids.count(ByteTokenizer().encode("<|image_pad|>", parse_special=True)[0]), 6) + svc.embeddings.path.unlink(missing_ok=True) From 6956f6052cb813a9bf32c318141ce14b39368723 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 12 Oct 2026 09:53:26 +0200 Subject: [PATCH 08/67] setup: --calibrate with --model/--family tunes that installed model, an uninstalled one is an error, --calibrate with --setup/--check or nothing installed says it does nothing (#2036) --- setup.py | 24 ++++++++++++++++++- tools/test_setup_choices.py | 47 +++++++++++++++++++++++++++++++++++++ 2 files changed, 70 insertions(+), 1 deletion(-) diff --git a/setup.py b/setup.py index e5082989..7d291e1c 100644 --- a/setup.py +++ b/setup.py @@ -4039,6 +4039,18 @@ def choices_from_config(cfg_path: Path) -> dict: vis is None or int(val("--vram-reserve-mib")) != VISION["gpu"]["reserve_mib"]) else None} +def calibration_targets(have: list, model: str | None, family: str | None) -> list: + """#2036: the installed configs `--calibrate --model X` (and/or --family) means; every config with neither.""" + if not (model or family): + return list(have) + out = [] + for c in have: + ch = choices_from_config(c) + if (not model or ch["model"] == model) and (not family or ch["family"] == family): + out.append(c) + return out + + def find_in(roots: list, rel: str): """The first of roots/rel that exists.""" for r in roots: @@ -4981,7 +4993,17 @@ def main() -> int: # choice, and asked once when the PC has cards that could share the model run_gpu = start_gpus(a.gpus) or a.gpu port = a.port or 8080 # a new install's port (issue #32: --port for an existing one) - if have and a.calibrate and not (a.setup or a.model or a.family or a.check): + if a.calibrate and (a.setup or a.check or not have): # #2036: said, not dropped + why = ("--setup" if a.setup else "--check" if a.check else "no model is installed yet") + warn(f"--calibrate does nothing with {why}: it tunes a model that is already installed. Run setup first, " + "then " + ("START-HERE.bat" if WIN else "./setup.sh") + " --calibrate [--model NAME]") + if have and a.calibrate and not (a.setup or a.check): + targets = calibration_targets(have, a.model, a.family) + if not targets: # #2036: --model names a model that is not installed + names = ", ".join(sorted({choices_from_config(c)["model"] or c.stem for c in have})) + fail(f"--calibrate: {a.model or a.family} is not installed (installed: {names})", + "calibrate an installed model, or set this one up first without --calibrate") + have = targets if not a.build: update_installed_engine(a.prebuilt) pick_cfg = have[0] diff --git a/tools/test_setup_choices.py b/tools/test_setup_choices.py index 124b7853..1d1fd992 100644 --- a/tools/test_setup_choices.py +++ b/tools/test_setup_choices.py @@ -614,3 +614,50 @@ class HostCompilers(unittest.TestCase): if __name__ == "__main__": unittest.main() + + +class CalibrateWithModel(unittest.TestCase): + """#2036: --calibrate --model X tunes model X (it used to fall through to a plain re-setup); a model that is not + installed is an error that says so; --calibrate with --setup or --check says it does nothing.""" + + def run_main(self, *argv, installed=("iq3_xxs", "q2_0")): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + cfgs = [] + for tag in installed: + p = Path(tmp.name) / f"strata-{tag}.json" + p.write_text(json.dumps({"exe": "x", "args": ["--max-context", "8192"], "model_name": tag})) + cfgs.append(p) + tuned = [] + with mock.patch.object(sys, "argv", ["setup.py", *argv]), \ + mock.patch.object(setup, "installed_configs", lambda: cfgs), \ + mock.patch.object(setup, "update_installed_engine", lambda *a, **k: None), \ + mock.patch.object(setup, "calibrate_config", lambda c: tuned.append(c.name) or True), \ + mock.patch.object(setup, "start", lambda *a, **k: 0), \ + mock.patch.object(setup, "data_folder", lambda d: (Path(tmp.name), [])), \ + mock.patch.object(setup, "step", side_effect=SystemExit("reached the plain setup")): + try: + code, out = quiet(setup.main) + except SystemExit as e: + code, out = e.code, "" + return code, tuned + + def test_model_is_the_target(self): + code, tuned = self.run_main("--calibrate", "--model", "IQ3_XXS", "--yes", "--no-start") + self.assertEqual((code, tuned), (0, ["strata-iq3_xxs.json"])) + + def test_a_model_not_installed_is_an_error(self): + code, tuned = self.run_main("--calibrate", "--model", "IQ3_S", "--yes", "--no-start") + self.assertEqual((code, tuned), (1, [])) + + def test_targets(self): + with tempfile.TemporaryDirectory() as d: + ps = [] + for tag in ("iq3_xxs", "q2_0"): + p = Path(d) / f"strata-{tag}.json" + p.write_text(json.dumps({"args": []})) + ps.append(p) + self.assertEqual(setup.calibration_targets(ps, None, None), ps) + self.assertEqual(setup.calibration_targets(ps, "Q2_0", None), [ps[1]]) + self.assertEqual(setup.calibration_targets(ps, "Q2_0", "qwen"), [ps[1]]) + self.assertEqual(setup.calibration_targets(ps, "Q4_K_M", None), []) From 17d8a171da0adbcb911d2c4c4b00d530c4e801f2 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 12 Oct 2026 09:53:49 +0200 Subject: [PATCH 09/67] CMake: STRATA_NATIVE_EXPERTS is defined with the other options, before the GPU section reads it, so the first configure registers the four native-expert tests (#2027) --- CMakeLists.txt | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index b7f6a8da..0f6426a4 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -99,6 +99,9 @@ endif() option(STRATA_BUILD_TESTS "Build the test suite" ${_strata_tests_default}) option(STRATA_BUILD_CONVERSATION_TESTS "Build standalone conversation cache tests" OFF) option(STRATA_WERROR "Treat compiler warnings as errors" OFF) +# #2027: defined here, before the GPU section reads it to register the native-expert tests (it was defined at the +# native-experts section far below, so a first configure registered four tests fewer than the second) +option(STRATA_NATIVE_EXPERTS "Native (IQ) expert support through ggml-cpu" ON) if(STRATA_BUILD_CONVERSATION_TESTS) enable_testing() @@ -1207,7 +1210,6 @@ target_link_libraries(strata_kernels_cpu PUBLIC Threads::Threads) # The CPU computes a native expert with ggml-cpu's own dot products (`ggml_get_type_traits_cpu`), so an IQ # weight means exactly what it means in llama.cpp. ggml is built static from a llama.cpp checkout: a local one # with -DSTRATA_GGML_DIR=..., otherwise the pinned upstream commit (third_party/ggml/VERSION.txt). -option(STRATA_NATIVE_EXPERTS "Native (IQ) expert support through ggml-cpu" ON) set(STRATA_GGML_DIR "" CACHE PATH "llama.cpp checkout to take ggml from (empty: fetch the pinned commit)") if(STRATA_PREFILL_MMQ AND NOT STRATA_NATIVE_EXPERTS) message(FATAL_ERROR "STRATA_PREFILL_MMQ requires STRATA_NATIVE_EXPERTS=ON for GGML sources") From 905a60588b9e099e7b2d242a0c81f8cf24fd9127 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 12 Oct 2026 09:56:26 +0200 Subject: [PATCH 10/67] bench and monitor: name the GPUs the engine uses - mixed cards one by one in the report, the server's own card when it is not an NVIDIA one, the Intel reader first on the SYCL server (#2062 #2001) --- sycl/serve/server_intel.py | 11 +++++------ sycl/serve/xe_telemetry.py | 20 +++++++++++++++++--- tools/strata_bench.py | 25 +++++++++++++++++++++---- tools/test_strata_bench.py | 20 ++++++++++++++++++++ 4 files changed, 63 insertions(+), 13 deletions(-) diff --git a/sycl/serve/server_intel.py b/sycl/serve/server_intel.py index 1b775c5d..baae26c2 100644 --- a/sycl/serve/server_intel.py +++ b/sycl/serve/server_intel.py @@ -5,7 +5,7 @@ Every argument is serve/server.py's. Nothing in serve/ is edited (the SYCL port keeps out of the shared files so upstream merges stay clean); this wrapper adds, at run time: - - the Monitor tab's GPU readings on an Intel Arc (sycl/serve/xe_telemetry.py) when no NVIDIA card answers; + - the Monitor tab's GPU readings on an Intel Arc (sycl/serve/xe_telemetry.py) (also on a PC with an NVIDIA card: the engine runs on the Intel one); - a model menu in the web app's header, for a host that swaps models on one GPU: the config names the RPC that does the swap as "model_switcher" (it takes {"mode": m} and answers {"mode", "up", "starting", "choices", "urls"}); the menu offers the models served on this server's port. Without that key nothing changes; @@ -35,15 +35,14 @@ from xe_telemetry import _XeGpu # noqa: E402 def install_xe_reader(): - """telemetry.gpu_reader -> the xe reader when NVML has no card and an Intel Arc is there.""" + """telemetry.gpu_reader -> the xe reader whenever an Intel Arc is there. #2001: this server runs the SYCL engine, + so the cards it reports are the Intel ones; before, an NVIDIA card in the same PC answered first and the Monitor + (and the benchmark report, which takes the card's name from it) showed the GeForce the engine never used.""" orig = T.gpu_reader def gpu_reader(index=0, amd=False): - g = orig(index, amd) - if g.ok(): - return g xe = _XeGpu(index) - return xe if xe.ok() else g + return xe if xe.ok() else orig(index, amd) T.gpu_reader = gpu_reader diff --git a/sycl/serve/xe_telemetry.py b/sycl/serve/xe_telemetry.py index 3eb3b61a..137667e9 100644 --- a/sycl/serve/xe_telemetry.py +++ b/sycl/serve/xe_telemetry.py @@ -12,6 +12,12 @@ import sys import time +# the cards sycl/setup_intel.py names by PCI id (INTEL_ARC) +ARC_NAMES = {"e223": "Arc Pro B70", "e221": "Arc Pro B60", "e211": "Arc Pro B60", "e20b": "Arc B580", "e20c": "Arc B570", + "e212": "Arc B50", "56a0": "Arc A770", "56a1": "Arc A750", "56a2": "Arc A580", "56a5": "Arc A380", + "56a6": "Arc A310", "5690": "Arc A770M"} + + class _XeGpu: """The Intel Arc readings in NVML's shape. Load and VRAM come from /run/gpustat.json (a root sampler: the only VRAM accounting xe exposes is per-client fdinfo, readable by root only); temperature, power and the PCIe link are @@ -21,13 +27,15 @@ class _XeGpu: def __init__(self, index=0): import glob self.dev = None + cards = [] # #2001: the Intel cards in sysfs order, as setup numbers them for d in sorted(glob.glob("/sys/class/drm/card[0-9]*/device")): try: if open(f"{d}/vendor").read().strip() == "0x8086" and os.path.isdir(f"{d}/tile0"): - self.dev = os.path.realpath(d) - break + cards.append(os.path.realpath(d)) except OSError: continue + if 0 <= index < len(cards): + self.dev = cards[index] self.hwmon = None for n in glob.glob(f"{self.dev}/hwmon/hwmon*/name") if self.dev else []: self.hwmon = os.path.dirname(n) @@ -38,7 +46,13 @@ class _XeGpu: def name(self): st = self._stat() - return (st or {}).get("name") or "Intel Arc GPU" + if (st or {}).get("name"): + return st["name"] + try: # the PCI id's name (setup_intel.INTEL_ARC), not a generic one + with open(f"{self.dev}/device") as f: + return "Intel " + ARC_NAMES.get(f.read().strip().lower().replace("0x", ""), "Arc GPU") + except (OSError, TypeError): + return "Intel Arc GPU" def _stat(self): try: diff --git a/tools/strata_bench.py b/tools/strata_bench.py index 557af920..ac9d39b2 100644 --- a/tools/strata_bench.py +++ b/tools/strata_bench.py @@ -606,7 +606,14 @@ def collect_machine(base: str, key: str, cfg: dict | None, gpu_arg: str | None = gpu_names = [g["name"] for g in used] or ([static["gpu_name"]] if static.get("gpu_name") else []) m = status.get("machine") or {} vram_mib = (m.get("gpu") or {}).get("total_mib") or None - if used and used[0].get("vram_mib"): + # #2001: the server names the cards it reads (" + " between them). A name nvidia-smi does not list means the + # engine runs on another vendor's card (an Intel Arc beside a GeForce): the server's names are the right ones, and + # so is its VRAM total - the PC's NVIDIA cards were not used. + served = [n for n in (static.get("gpu_name") or "").split(" + ") if n and n != "?"] + if served and not all(n in {g["name"] for g in local["gpus"]} for n in served): + gpu_names, used = served, [] + local = {**local, "cuda": None} # the PC's CUDA belongs to cards the engine did not use + elif used and used[0].get("vram_mib"): vram_mib = sum(g.get("vram_mib") or 0 for g in used) n_ctx = None for d in models.get("data") or []: @@ -702,9 +709,19 @@ def gpu_slug(machine: dict) -> str: names = machine.get("gpu") or [] if not names: return "cpu" - n = re.sub(r"(?i)\b(nvidia|geforce|amd|radeon|intel|graphics|corporation)\b", " ", names[0]) - s = slug(n, 30) - return s if len(names) == 1 else f"{len(names)}x-{s}" + # #2062: the cards one by one when they differ (rtx-5070-ti-plus-rtx-a4000), "2x-" only for identical ones + groups: list[list] = [] # [name, count], in the order the cards are listed + for name in names: + same = next((g for g in groups if g[0] == name), None) + if same: + same[1] += 1 + else: + groups.append([name, 1]) + parts = [] + for name, count in groups: + n = re.sub(r"(?i)\b(nvidia|geforce|amd|radeon|intel|graphics|corporation)\b", " ", name) + parts.append(slug(n, 30) if count == 1 else f"{count}x-{slug(n, 30)}") + return "-plus-".join(parts)[:80].strip("-") def model_label(machine: dict) -> str: diff --git a/tools/test_strata_bench.py b/tools/test_strata_bench.py index 80fc2d70..d0449f68 100644 --- a/tools/test_strata_bench.py +++ b/tools/test_strata_bench.py @@ -276,6 +276,26 @@ class ReportTests(unittest.TestCase): self.assertEqual(B.gpu_selection({"gpu": "0,2"}), [0, 2]) self.assertEqual(B.gpu_selection({}, None), []) + def test_the_slug_names_mixed_cards_one_by_one(self): + """#2062: two different cards are not N copies of the first.""" + a, b = "NVIDIA GeForce RTX 5070 Ti", "NVIDIA RTX A4000" + self.assertEqual(B.gpu_slug({"gpu": [a]}), "rtx-5070-ti") + self.assertEqual(B.gpu_slug({"gpu": [a, b]}), "rtx-5070-ti-plus-rtx-a4000") + self.assertEqual(B.gpu_slug({"gpu": [b, a]}), "rtx-a4000-plus-rtx-5070-ti") + self.assertEqual(B.gpu_slug({"gpu": [b, b]}), "2x-rtx-a4000") + self.assertEqual(B.gpu_slug({"gpu": [b, a, b]}), "2x-rtx-a4000-plus-rtx-5070-ti") + + def test_a_card_the_pc_s_nvidia_smi_does_not_list_is_the_servers_own(self): + """#2001: the engine on an Intel Arc beside a GeForce: the report names the Arc (the name the server reads).""" + srv = FakeStrata() + self.addCleanup(srv.stop) + nv = {"gpus": [{"name": "NVIDIA GeForce RTX 3080 Ti", "vram_mib": 12288, "driver": "560.1"}], "cuda": "12.6"} + with mock.patch.object(B, "gpu_info_local", return_value=nv), mock.patch.object( + B, "try_json", side_effect=lambda base, path, *a, **k: ( + {"hardware_static": {"gpu_name": "Intel Arc Pro B70"}} if path == "/metrics" else {})): + m = B.collect_machine(srv.base, "", {"backend": "sycl"}) + self.assertEqual((m["gpu"], m["cuda"]), (["Intel Arc Pro B70"], None)) + def test_names(self): m = {"gpu": ["NVIDIA GeForce RTX 3060"], "model": "Qwen3.8 Flash-Next", "quant": "IQ3_XXS"} self.assertEqual(B.results_dir_name(m, "2026-10-10"), "2026-10-10-community-rtx-3060-qwen3-8-flash-next-iq3-xxs") From 798f3006bbc6d40b041c6ecc4490c1ac82ef5337 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 12 Oct 2026 09:51:18 +0200 Subject: [PATCH 11/67] Tests: STRATA_TEST_SLOW_COPY_US makes a parked conversation's checkpoint copy as slow as paged-out memory (for the #2049 repro) --- src/core/conversation_copy.hpp | 22 ++++++++++++++++++++++ src/core/conversation_state.cpp | 4 ++-- 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/src/core/conversation_copy.hpp b/src/core/conversation_copy.hpp index e15b1197..7f5bd266 100644 --- a/src/core/conversation_copy.hpp +++ b/src/core/conversation_copy.hpp @@ -1,8 +1,13 @@ #pragma once +#include "strata/core/conversation_cache.hpp" + #include +#include #include +#include +#include #include namespace strata::core::conversation_detail { @@ -29,4 +34,21 @@ inline cudaError_t copy_nonblocking(void* dst, const void* src, size_t bytes) { return cudaStreamSynchronize(s); } +/// STRATA_TEST_SLOW_COPY_US=N (tests only): a parked conversation's running checkpoints copy as slowly as when the OS +/// has paged them out - N microseconds per MiB copied. Unset: a plain copy. +inline long test_slow_copy_us() { + static const long v = [] { const char* e = std::getenv("STRATA_TEST_SLOW_COPY_US"); return e ? std::atol(e) : 0L; }(); + return v; +} + +inline std::vector copy_checkpoints(const std::vector& cs) { + std::vector out = cs; + if (const long us = test_slow_copy_us(); us > 0) { + size_t bytes = 0; + for (const auto& c : out) bytes += c.bytes(); + std::this_thread::sleep_for(std::chrono::microseconds(us * (long) (bytes >> 20))); + } + return out; +} + } // namespace strata::core::conversation_detail diff --git a/src/core/conversation_state.cpp b/src/core/conversation_state.cpp index 9c2342f8..8356cee8 100644 --- a/src/core/conversation_state.cpp +++ b/src/core/conversation_state.cpp @@ -257,7 +257,7 @@ bool conversation_snapshot_save(SavedConversation& image, const ConversationView captured.geometry = geometry_key(g); captured.layer_lo = ss.layer_lo; captured.layer_hi = ss.layer_hi; captured.live.ids = view.ids; captured.live.imgs = view.images; - captured.cvec = view.cvec; captured.checkpoints = view.checkpoints; + captured.cvec = view.cvec; captured.checkpoints = conversation_detail::copy_checkpoints(view.checkpoints); const int64_t unchanged = reuse.kv.empty() ? 0 : reuse.unchanged_tokens; captured.kv = std::move(reuse.kv); const size_t layers = owned_qsa(ss); @@ -283,7 +283,7 @@ bool conversation_snapshot_sources(SavedConversation& meta, std::vector Date: Mon, 12 Oct 2026 09:58:24 +0200 Subject: [PATCH 12/67] Parking a conversation beats the watchdog: its checkpoint and K/V copies report progress, the stage is named, Windows counts hard page faults as file-tier activity, and the stall report and each request say how little VRAM is free (#2049 #2065) --- include/strata/core/conversation_buffer.hpp | 3 ++ src/core/conversation_copy.hpp | 54 +++++++++++++++++---- src/core/conversation_state.cpp | 4 +- src/program/generate.cpp | 49 ++++++++++++++++++- 4 files changed, 97 insertions(+), 13 deletions(-) diff --git a/include/strata/core/conversation_buffer.hpp b/include/strata/core/conversation_buffer.hpp index 1cb8af77..88a010b4 100644 --- a/include/strata/core/conversation_buffer.hpp +++ b/include/strata/core/conversation_buffer.hpp @@ -1,5 +1,7 @@ #pragma once +#include "strata/core/progress.hpp" + #include #include #include @@ -78,6 +80,7 @@ public: segment.resize(count, value); segments_.push_back(std::move(segment)); size_ += count; + progress_beat(); // #2049: zero-filling 16 MiB of fresh pages is slow when the host is paging } } else { while (!segments_.empty() && size_ - segments_.back().size() >= n) { diff --git a/src/core/conversation_copy.hpp b/src/core/conversation_copy.hpp index 7f5bd266..0dea46a3 100644 --- a/src/core/conversation_copy.hpp +++ b/src/core/conversation_copy.hpp @@ -1,9 +1,11 @@ #pragma once #include "strata/core/conversation_cache.hpp" +#include "strata/core/progress.hpp" #include +#include #include #include #include @@ -31,24 +33,58 @@ inline cudaError_t copy_nonblocking(void* dst, const void* src, size_t bytes) { cudaStream_t s = streams[(size_t) dev]; e = cudaMemcpyAsync(dst, src, bytes, cudaMemcpyDefault, s); if (e != cudaSuccess) return e; - return cudaStreamSynchronize(s); + e = cudaStreamSynchronize(s); + core::progress_beat(); // #2049: a parked conversation is many of these; each one that lands is progress + return e; } -/// STRATA_TEST_SLOW_COPY_US=N (tests only): a parked conversation's running checkpoints copy as slowly as when the OS -/// has paged them out - N microseconds per MiB copied. Unset: a plain copy. +/// #2049 #2065 #1971: a host-to-host copy that tells the watchdog it is moving. Parked state (the running +/// checkpoints, the K/V segments) sits in ordinary pageable memory for the whole session; when the OS has written +/// it to the pagefile, copying it back runs at the drive's page-in speed (measured in the reports: ~190 hard faults +/// a second, under 1 MB/s) and one memcpy of it stays silent past the 60 s limit, so the watchdog ended an engine +/// that was only slow. One beat per 1 MiB slice keeps a copy that moves alive and still lets a real stall show. +/// STRATA_TEST_SLOW_COPY_US=N (tests only): every 1 MiB slice of a checkpoint copy takes N microseconds more, as when +/// the OS has paged the checkpoints out and each slice is read back from the drive. Unset: no delay. inline long test_slow_copy_us() { static const long v = [] { const char* e = std::getenv("STRATA_TEST_SLOW_COPY_US"); return e ? std::atol(e) : 0L; }(); return v; } -inline std::vector copy_checkpoints(const std::vector& cs) { - std::vector out = cs; - if (const long us = test_slow_copy_us(); us > 0) { - size_t bytes = 0; - for (const auto& c : out) bytes += c.bytes(); - std::this_thread::sleep_for(std::chrono::microseconds(us * (long) (bytes >> 20))); +template +inline std::vector copy_beating(const std::vector& src) { + std::vector out; + out.reserve(src.size()); + const size_t step = std::max(1, ((size_t) 1 << 20) / sizeof(T)); + for (size_t at = 0; at < src.size(); at += step) { + out.insert(out.end(), src.begin() + (std::ptrdiff_t) at, + src.begin() + (std::ptrdiff_t) std::min(src.size(), at + step)); + if (const long us = test_slow_copy_us(); us > 0) std::this_thread::sleep_for(std::chrono::microseconds(us)); + core::progress_beat(); } return out; } +inline ConversationCheckpoint copy_checkpoint_beating(const ConversationCheckpoint& c) { + ConversationCheckpoint o; + o.ids = copy_beating(c.ids); + o.imgs = copy_beating(c.imgs); + o.gdn = copy_beating(c.gdn); + o.ple = copy_beating(c.ple); + o.tails = copy_beating(c.tails); + o.dead = copy_beating(c.dead); + o.block_pos = copy_beating(c.block_pos); + o.used = c.used; + o.pinned = c.pinned; + o.stage_parts.reserve(c.stage_parts.size()); + for (const auto& part : c.stage_parts) o.stage_parts.push_back(copy_checkpoint_beating(part)); + return o; +} + +inline std::vector copy_checkpoints_beating(const std::vector& cs) { + std::vector out; + out.reserve(cs.size()); + for (const auto& c : cs) out.push_back(copy_checkpoint_beating(c)); + return out; +} + } // namespace strata::core::conversation_detail diff --git a/src/core/conversation_state.cpp b/src/core/conversation_state.cpp index 8356cee8..4fbcf88b 100644 --- a/src/core/conversation_state.cpp +++ b/src/core/conversation_state.cpp @@ -257,7 +257,7 @@ bool conversation_snapshot_save(SavedConversation& image, const ConversationView captured.geometry = geometry_key(g); captured.layer_lo = ss.layer_lo; captured.layer_hi = ss.layer_hi; captured.live.ids = view.ids; captured.live.imgs = view.images; - captured.cvec = view.cvec; captured.checkpoints = conversation_detail::copy_checkpoints(view.checkpoints); + captured.cvec = view.cvec; captured.checkpoints = conversation_detail::copy_checkpoints_beating(view.checkpoints); const int64_t unchanged = reuse.kv.empty() ? 0 : reuse.unchanged_tokens; captured.kv = std::move(reuse.kv); const size_t layers = owned_qsa(ss); @@ -283,7 +283,7 @@ bool conversation_snapshot_sources(SavedConversation& meta, std::vector> 20; PROCESS_MEMORY_COUNTERS pmc{}; - if (K32GetProcessMemoryInfo(GetCurrentProcess(), &pmc, sizeof pmc)) total += pmc.PageFaultCount >> 6; + // >> 3, not >> 6: a host that pages hard reads from the pagefile at ~200 faults a second (#2049: 190/s, one + // thread waiting on one page at a time), which at >> 6 is 3 a second and never counted as busy + if (K32GetProcessMemoryInfo(GetCurrentProcess(), &pmc, sizeof pmc)) total += pmc.PageFaultCount >> 3; return total; #else return 0; @@ -1261,12 +1263,29 @@ bool launch_blocking() { #endif } +/// #2065: the VRAM free when the current request began (-1 before the first); the stall report prints it, because a +/// card this full is the one measured cause of a window that never finishes (the driver pages GPU memory). +std::atomic g_req_vram_free_mib{-1}; +constexpr int64_t kVramSafeMib = +#ifdef _WIN32 + 1024; // WDDM pages instead of failing (docs/DETAILS.md, the sysmem fallback): the line #2065 fell below +#else + 512; +#endif + void stall_report(std::FILE* f, uint64_t layers_during) { strata::core::Progress& p = strata::core::progress(); std::fprintf(f, "strata serve: stall report (engine %s): stage \"%s\" for %lld s; %llu layers served since the " "last finished step (0 = stopped, more = slow)\n", STRATA_VERSION, stage_text().c_str(), (long long) ((strata::core::progress_now_ms() - p.since_ms.load()) / 1000), (unsigned long long) layers_during); + if (const int64_t vf = g_req_vram_free_mib.load(); vf >= 0) { + std::fprintf(f, " VRAM free when this request began: %lld MiB%s\n", (long long) vf, + vf >= kVramSafeMib ? "" : " - LOW: a card this full can page GPU memory to system RAM (decode " + "falls to a few tok/s, then a window never finishes, #2065); a larger --vram-reserve-mib, a " + "smaller --max-context, or 'Prefer No Sysmem Fallback' for the engine in the NVIDIA control panel " + "(docs/DETAILS.md) leaves room"); + } for (int pass = 0; pass < 2; ++pass) { if (pass == 1) { std::this_thread::sleep_for(std::chrono::seconds(2)); @@ -7844,6 +7863,14 @@ int main(int argc, char** argv) { // addresses change: all parked images live in ordinary host vectors. auto park_current_body = [&](size_t held) -> bool { if (!conversations.enabled() || !live_ok || live.empty()) return true; + // #2049: parking copies the outgoing conversation's running checkpoints and K/V into host memory, which + // is a silent stretch of the "request" stage; when the OS has paged that memory out it takes minutes. + // Named, so a stall report says "parking"; its copies beat (conversation_copy.hpp), so the watchdog + // sees a park that moves and ends one that does not. + struct ParkStage { + ParkStage() { strata::core::progress_at("request: parking the previous conversation"); } + ~ParkStage() { strata::core::progress_at("request"); strata::core::progress_beat(); } + } park_stage; // --conversation-cache-min-tokens: a short conversation is not worth one of the slots. Parking is a // switch-time decision, so a client's small side requests would otherwise park themselves and, once the // cache is full, evict the long conversation they were interleaved with (oldest first) - the reuse it @@ -9819,6 +9846,24 @@ int main(int argc, char** argv) { strata::core::progress_at("idle"); } } busy_scope; + { // #2065: said, never changed - the free VRAM now (the verify windows' captures and the batch layouts + // eat into what startup reported), once per 128 MiB lower it gets + size_t vf_b = 0, vt_b = 0; + if (cudaMemGetInfo(&vf_b, &vt_b) == cudaSuccess) { + const int64_t vf = (int64_t) (vf_b >> 20); + g_req_vram_free_mib.store(vf); + static int64_t low_said_at = INT64_MAX; + if (vf < kVramSafeMib && vf + 128 <= low_said_at) { + low_said_at = vf; + std::fprintf(stderr, "strata serve: WARNING: only %lld MiB of VRAM free at the start of this request " + "(below %lld MiB): when the card is this full the driver can page GPU memory " + "to system RAM, decode falls to a few tok/s and a window may never finish " + "(#2065). Add --vram-reserve-mib %lld to the config's args, or lower " + "--max-context / --batch\n", (long long) vf, (long long) kVramSafeMib, + (long long) ((o.vram_reserve_mib + (kVramSafeMib - vf) + 63) / 64 * 64)); + } + } + } stop_req.store(false); // a STOP that arrived between requests is stale err.clear(); // Disk sessions: SAVE | RESTORE , between requests (the path runs to the end of the line, From 0613cc00bcb370ccca00590b71f51d0d0185c50c Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 12 Oct 2026 10:01:40 +0200 Subject: [PATCH 13/67] Stall report: an MTP draft wait is named (it read as the verify window before it); docs: the free VRAM moves after startup, and a stall in "request" can be the OS paging the parked conversation (#2049 #2065) --- docs/DETAILS.md | 22 ++++++++++++++++++++++ src/core/mtp.cpp | 3 +++ 2 files changed, 25 insertions(+) diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 2b55a404..66cef80c 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -642,6 +642,28 @@ with the fallback off it still starts and degrades instead of failing - the slac worth more than the extra slots, which is the same ordering measured above (enkynakamura, #781; one 256-token sample per step, so the upper rows are noisy). +**The free figure moves after startup.** The `... MiB of VRAM free with everything loaded` line is read before the +verify windows are captured (each captured window, and each `--batch` slot layout, takes some tens of MiB: 538 MiB at +that line was 395 MiB after the last capture in #2065, an RTX 4090 D with `--batch 2` at 262,144 context). Below about +a gigabyte on Windows the driver can page GPU memory to system RAM instead of failing: decode fell from 91 to 3 tok/s +at 70K tokens and then a window never finished, the watchdog stopping the engine after 60 s. From 0.1.43.1 each request +re-reads the free VRAM, says `WARNING: only N MiB of VRAM free at the start of this request` once it is under 1 GiB +(512 MiB elsewhere) with the `--vram-reserve-mib` that would leave room, and the stall report prints the figure. The +engine only says it; the fix is a larger `--vram-reserve-mib`, a smaller `--max-context` or `--batch`, or +`Prefer No Sysmem Fallback` for the engine. + +**A stall named "request" can be the OS paging the engine's own memory.** Before a request that switches +conversation, the engine parks the outgoing one in RAM: copies of its running checkpoints and K/V, which then sit in +ordinary memory until the conversation comes back. On a 64 GB PC with `--resident-budget-gib 40`, an 8 GiB conversation +cache and a 256K context, the working set was 8-30 GB of 56 GB committed and the engine took about 190 page faults +a second (under 1 MB/s if each is a pagefile read) in #2049: one silent step of more than 60 s, five times, on 0.1.41 +and 0.1.43 alike (thread dumps: the main thread inside the copy of the checkpoints, at the same instruction each time). The log's `verify window (last window, not the +current stage) ... host at layer step 48; the GPU rang 48` line in that report is the previous request's last window, +not the stalled one. From 0.1.43.1 the park is named in the stage (`request: parking the previous conversation`), its +copies report progress to the watchdog, and Windows counts page faults at 8 a unit instead of 64 when it decides +whether the file tier is busy. The cure for the slowness itself is memory: a smaller `--resident-budget-gib`, a smaller +`--conversation-cache-mib`, or the pagefile on an SSD. + --- ## Using it diff --git a/src/core/mtp.cpp b/src/core/mtp.cpp index d37163be..89f8b519 100644 --- a/src/core/mtp.cpp +++ b/src/core/mtp.cpp @@ -3,6 +3,7 @@ #include "strata/core/coupled_draft.hpp" #include "strata/core/spec_prob.hpp" #include "strata/core/on_device.hpp" +#include "strata/core/progress.hpp" #include "strata/core/native_head.hpp" #include "strata/core/peer_experts.hpp" @@ -1317,6 +1318,7 @@ bool MtpDrafter::draft(int T, const int32_t* tokens, int64_t p, int a, int32_t* } (void) cudaStreamQuery(cs_); prefetch_ple(tokens[a]); + progress_at("mtp draft: waiting for the GPU"); // #2065 for (int j = 0; j + 1 < max_steps; ++j) { uint32_t spins = 0; while (((volatile int32_t*) h_out_)[j] < 0) { @@ -1345,6 +1347,7 @@ bool MtpDrafter::draft(int T, const int32_t* tokens, int64_t p, int a, int32_t* } (void) cudaStreamQuery(cs_); prefetch_ple(tokens[a]); + progress_at("mtp draft: waiting for the GPU"); // #2065: a stall here read as "decode", the verify window before it auto wait_step = [&](int j) { uint32_t spins = 0; while (((volatile int32_t*) h_out_)[j] < 0) { From 665d484236bd7797698860d644fe9016a28dbd9c Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 12 Oct 2026 10:39:33 +0200 Subject: [PATCH 14/67] SYCL: resident_stage_swaps copies the evicted expert back to its exchange buffer again (#2014) The dpct migration had dropped the cudaMemcpyAsync D2H and the stream sync, so the resident RAM mode with adaptive swaps committed whatever the exchange buffer held as the evicted expert (lost expert, wrong weights on a later CPU read). STRATA_CHECK_SWAPS=1 is a test aid: it compares each staged buffer with the model file and audits the RAM copy at the end of a run. --- sycl/include/strata/core/expert_source.hpp | 5 ++ sycl/src/program/generate.cpp | 68 +++++++++++++++++++--- 2 files changed, 66 insertions(+), 7 deletions(-) diff --git a/sycl/include/strata/core/expert_source.hpp b/sycl/include/strata/core/expert_source.hpp index 2a8731ae..78870cf8 100644 --- a/sycl/include/strata/core/expert_source.hpp +++ b/sycl/include/strata/core/expert_source.hpp @@ -570,6 +570,11 @@ public: bool pcie_layer(int64_t layer) const override; bool transient(int64_t layer, int64_t expert) const override; bool copy_blob(int64_t layer, int64_t expert, uint8_t* dst) override; + /// The blob read from the model file(s) only, never from the RAM copy or an exchange buffer (STRATA_CHECK_SWAPS). + bool copy_blob_from_file(int64_t layer, int64_t expert, uint8_t* dst) const { + return base_ != nullptr && dst != nullptr && layer >= 0 && expert >= 0 && layer < n_layers_ && expert < n_expert_ && + copy_from_files(layer, expert, dst); + } /// CS-T: advances the assembled blobs' age (see staged_blob). void begin_layer(int64_t layer, const int32_t* ids, int64_t k) override; /// CS-T: the GGUF in place assembles the missed experts on `fetch_threads_` threads. diff --git a/sycl/src/program/generate.cpp b/sycl/src/program/generate.cpp index b1a77d5b..4adbda2b 100644 --- a/sycl/src/program/generate.cpp +++ b/sycl/src/program/generate.cpp @@ -333,13 +333,16 @@ bool resident_stage_swaps(strata::core::FileExpertSource &src, if (slot < 0) continue; const SwapHome home = locate(s.layer); const strata::core::OnDevice on(home.dev); - /* - DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API. - While the origin API might be synchronous, it depends on the type of - operand memory, so you may need to call wait() on event return by memcpy - API to ensure synchronization behavior. - */ - + // the evicted expert's bytes go back into exchange buffer q BEFORE its slot is overwritten + // (CUDA: cudaMemcpyAsync D2H on the owning card's stream; the dpct migration had dropped the call) + try { + home.stream->memcpy(src.exchange_buffer(q), home.cache->device_slot(slot), + (size_t) strata::kernels::cpu::expert_layout().blob_bytes(s.layer)); + } catch (sycl::exception const& e) { + std::fprintf(stderr, "strata: copy back of layer %d slot %d (device %d) failed: %s\n", (int) s.layer, + (int) slot, home.dev, e.what()); + return false; + } bool seen = false; for (const SwapHome& u : used) seen = seen || u.stream == home.stream; if (!seen) used.push_back(home); @@ -349,6 +352,32 @@ bool resident_stage_swaps(strata::core::FileExpertSource &src, if (!staged.empty()) { for (const SwapHome& u : used) { const strata::core::OnDevice on(u.dev); + try { + u.stream->wait(); + } catch (sycl::exception const& e) { + std::fprintf(stderr, "strata: copy back sync (device %d) failed: %s\n", u.dev, e.what()); + return false; + } + } + // STRATA_CHECK_SWAPS=1 (a test aid): each evicted expert's exchange buffer must hold the model file's bytes + if (const char* chk = std::getenv("STRATA_CHECK_SWAPS"); chk != nullptr && chk[0] != '\0' && chk[0] != '0') { + static std::atomic n_ok{0}, n_bad{0}; + std::vector ref; + int64_t bad = 0; + for (const Staged& x : staged) { + ref.resize((size_t) strata::kernels::cpu::expert_layout().blob_bytes(x.layer)); + if (!src.copy_blob_from_file(x.layer, x.out, ref.data()) || + std::memcmp(ref.data(), src.exchange_buffer(x.q), ref.size()) != 0) { + ++bad; + std::fprintf(stderr, "strata: STRATA_CHECK_SWAPS: layer %d expert %d: the exchange buffer differs from the file\n", + (int) x.layer, (int) x.out); + } else { + ++n_ok; + } + } + n_bad += bad; + std::fprintf(stderr, "strata: STRATA_CHECK_SWAPS: %zu staged, %lld differ (total %lld ok, %lld differ)\n", + staged.size(), (long long) bad, (long long) n_ok.load(), (long long) n_bad.load()); } for (const Staged& x : staged) if (!src.stage_exchange(x.layer, x.in, x.out, x.q)) { @@ -12564,6 +12593,31 @@ int main(int argc, char **argv) try { std::printf("%-24s %.2f GiB of experts in RAM, %lld exchanged with the VRAM tier, %lld blob reads from " "the file\n", "resident RAM", (double) src.resident_bytes() / 1073741824.0, (long long) src.exchanges(), (long long) src.file_reads()); + // STRATA_CHECK_SWAPS=1 (a test aid): after the run every expert must be held (the GPU cache or the RAM copy), + // and every RAM-copy blob must equal the model file's bytes (nothing lost, nothing stale after the swaps) + if (src.complement_ready()) + if (const char* chk = std::getenv("STRATA_CHECK_SWAPS"); chk != nullptr && chk[0] != '\0' && chk[0] != '0') { + int64_t held_ram = 0, held_gpu = 0, lost = 0, stale = 0; + std::vector ref; + for (int64_t l = 0; l < g.n_layers; ++l) + for (int64_t e = 0; e < g.n_expert; ++e) { + const bool ram = src.has_resident(l, e); + const bool gpu = host_res[(size_t) l * (size_t) g.n_expert + (size_t) e] >= 0; + held_ram += ram; + held_gpu += gpu; + if (!ram && !gpu) { ++lost; continue; } + if (!ram) continue; + ref.resize((size_t) strata::kernels::cpu::expert_layout().blob_bytes(l)); + if (!src.copy_blob_from_file(l, e, ref.data()) || + std::memcmp(ref.data(), src.resident_blob(l, e), ref.size()) != 0) { + if (stale++ < 8) + std::fprintf(stderr, "strata: STRATA_CHECK_SWAPS: layer %d expert %d: the RAM copy differs from the file\n", + (int) l, (int) e); + } + } + std::printf("%-24s audit: %lld experts in RAM, %lld in the GPU cache, %lld held by neither, %lld RAM blobs differ from the file\n", + "STRATA_CHECK_SWAPS", (long long) held_ram, (long long) held_gpu, (long long) lost, (long long) stale); + } if (srcp == &src) { // CS-T: the RAM and file tiers (the GPU cache's share is the hit rate above) const double fms = src.file_ms() - fms0, fmb = (double) (src.file_blob_bytes() - fbytes0) / 1e6; std::printf("%-24s decode: RAM %lld blobs, files %lld blobs, %.1f MB read from the files (%.2f MB/round, " From 8b271f24b53187f6c4341f367aa42cf1dbe33561 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 12 Oct 2026 10:39:33 +0200 Subject: [PATCH 15/67] STRATA_TRACE=2: wait for the device at each startup mark and name the first step after which it reports an error (#2013) --- src/program/generate.cpp | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 5f54eb10..eeb842cb 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -1332,11 +1332,21 @@ void stall_report(std::FILE* f, uint64_t layers_during) { /// STRATA_TRACE=1: the VRAM left at a step of the startup (finds what fills the card after the cache is sized) void mem_mark(const char* where) { - static const bool on = std::getenv("STRATA_TRACE") != nullptr; - if (!on) return; + static const char* const env = std::getenv("STRATA_TRACE"); + if (env == nullptr) return; size_t free_b = 0, total_b = 0; cudaMemGetInfo(&free_b, &total_b); std::fprintf(stderr, "strata trace: %lld MiB free after %s\n", (long long) (free_b >> 20), where); + // STRATA_TRACE=2: also wait for the device here and name the first step after which it reports an error. A + // "sticky" failure (#2013: unspecified launch failure surfacing in a later, unrelated call) is then pinned to + // the step that ran the faulting work. Only a diagnostic: it adds a synchronisation per mark. + if (env[0] == '2') { + const cudaError_t sync_e = cudaDeviceSynchronize(); + const cudaError_t last_e = cudaGetLastError(); + std::fprintf(stderr, "strata trace: device %s after %s (sync: %s, last error: %s)\n", + sync_e == cudaSuccess && last_e == cudaSuccess ? "ok" : "ERROR", where, cudaGetErrorString(sync_e), + cudaGetErrorString(last_e)); + } } /// #463's A/B: STRATA_ADAPT_NOWAIT=1 lets a verify window start before the adaptive tier's copies have landed (0.1.37) @@ -7308,6 +7318,7 @@ int main(int argc, char** argv) { } } } + mem_mark("before the prompt path init"); for (;;) { const int r = init_prompt_paths(); if (r == 0) break; From a86aa7476366163b7508fa0d662a3f95ff4429b0 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 12 Oct 2026 12:52:32 +0200 Subject: [PATCH 16/67] Tests: STRATA_TEST_PINNED_SHARE sets the pinned share the prompt ring rule reads (#2090 repro) --- src/program/generate.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/program/generate.cpp b/src/program/generate.cpp index eeb842cb..5070952d 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -6287,7 +6287,9 @@ int main(int argc, char** argv) { total += b; if (srcp->pinned(l, e)) pinned += b; } - strata::prefill::Prefill::set_pinned_share(total ? (double) pinned / (double) total : 1.0); + double share = total ? (double) pinned / (double) total : 1.0; + if (const char* t = std::getenv("STRATA_TEST_PINNED_SHARE")) share = std::atof(t); // tests: the Windows-like ring rule + strata::prefill::Prefill::set_pinned_share(share); } // bytes -> slots for CUDA0's cache: exact when it knows its per-slot offsets (a native pack's blobs differ // per layer), otherwise max_blob each. From af6affb871bd219daff3b9a120176b2c199f344f Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 12 Oct 2026 12:21:24 +0200 Subject: [PATCH 17/67] Prompt loan: a request's smaller chunk can need more slots than the auto chunk's region (a chunk at or below small_max gets 0.1.39's bigger ring), so the loan starts where the chunk needs it and a chunk that still cannot be lent is halved, instead of ending the engine (#2090) --- src/program/generate.cpp | 27 +++++++++++++++++++++++---- 1 file changed, 23 insertions(+), 4 deletions(-) diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 5070952d..1695b0e9 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -10913,9 +10913,28 @@ int main(int argc, char** argv) { if (!refill_one(p, e)) return false; } const strata::core::OnDevice on(p.dev); - const int32_t first = std::max(p.first, (int32_t) (p.cache->slots() - part_slots(p, want))); - if (want != p.sp->chunk() || first != p.first_now) { - if (!p.sp->relayout(want, p.cache->device_slot(first), part_bytes(p, first), e)) return false; + // #2090: the loan a chunk needs is NOT monotonic in the chunk: a chunk above the scan's small_max + // lays out the byte-budget ring (199 slots at 5120), one at or below it 0.1.39's (384 at 4096), so + // a request's smaller chunk can need MORE slots than the auto chunk's region (p.first) holds. The + // loan starts where the chunk itself needs it (the 128-slot floor aside); a chunk that cannot be + // lent even then is halved until it can, instead of ending the engine. + int64_t want_p = want; + int64_t need_p = part_slots(p, want_p); + while ((need_p <= 0 || need_p + 128 > p.cache->slots()) && want_p > 256) { + want_p = std::max(256, want_p / 2 / 256 * 256); + need_p = part_slots(p, want_p); + } + if (need_p <= 0 || need_p + 128 > p.cache->slots()) { + e = "prefill: no chunk of this request fits the slots that can be lent (#2090)"; + return false; + } + if (want_p != want) + std::fprintf(stderr, "strata serve: prompt chunk %lld -> %lld tokens for this request: its " + "buffers do not fit the slots that can be lent (#2090)\n", (long long) want, + (long long) want_p); + const int32_t first = (int32_t) (p.cache->slots() - need_p); + if (want_p != p.sp->chunk() || first != p.first_now) { + if (!p.sp->relayout(want_p, p.cache->device_slot(first), part_bytes(p, first), e)) return false; p.first_now = first; } for (int64_t l = p.lb; l < p.le; ++l) // THIS participant's layers only @@ -10927,7 +10946,7 @@ int main(int argc, char** argv) { any = true; } } - p.lent_chunk = want; + p.lent_chunk = want_p; } if (any) res_upload(); if (trace) { From 4468e0e62c68defcde39aec397ef71353e7073c1 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 12 Oct 2026 13:06:52 +0200 Subject: [PATCH 18/67] Prompt loan: say when a chunk's loan is larger than the auto chunk's (#2090) --- src/program/generate.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 1695b0e9..f7f1b167 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -10932,6 +10932,10 @@ int main(int argc, char** argv) { std::fprintf(stderr, "strata serve: prompt chunk %lld -> %lld tokens for this request: its " "buffers do not fit the slots that can be lent (#2090)\n", (long long) want, (long long) want_p); + if (need_p > p.cache->slots() - p.first) // the case that ended the engine before (#2090) + std::fprintf(stderr, "strata serve: the loan for a chunk of %lld tokens (%lld slots) is larger than the " + "auto chunk's (%lld slots): starting it earlier (#2090)\n", (long long) want_p, + (long long) need_p, (long long) (p.cache->slots() - p.first)); const int32_t first = (int32_t) (p.cache->slots() - need_p); if (want_p != p.sp->chunk() || first != p.first_now) { if (!p.sp->relayout(want_p, p.cache->device_slot(first), part_bytes(p, first), e)) return false; From 017a672ae11f95f7436c6d01546d47c8ab699f4f Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 12 Oct 2026 14:21:19 +0200 Subject: [PATCH 19/67] bench: the server the bench starts runs without --expert-profile-save, so it never saves a profile learned from its short prompts over the user's (#2088) --- tools/strata_bench.py | 28 ++++++++++++++++++++++++++++ tools/test_strata_bench.py | 30 ++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+) diff --git a/tools/strata_bench.py b/tools/strata_bench.py index ac9d39b2..67bd63a0 100644 --- a/tools/strata_bench.py +++ b/tools/strata_bench.py @@ -656,7 +656,35 @@ def is_strata(base: str, key: str) -> bool: return bool(h and h.get("service") == "strata") +def without_profile_save(cfg: dict) -> tuple[dict, bool]: + """#2088: the config without `--expert-profile-save FILE` (and its value) - the engine writes that profile when the + server quits, and a benchmark's short prompts must not replace the user's calibrated one. -> (config, removed).""" + args = list(cfg.get("args") or []) + out, i, removed = [], 0, False + while i < len(args): + if args[i] == "--expert-profile-save": + i, removed = i + 2, True + elif isinstance(args[i], str) and args[i].startswith("--expert-profile-save="): + i, removed = i + 1, True + else: + out.append(args[i]) + i += 1 + return ({**cfg, "args": out} if removed else cfg), removed + + def start_server(cfg_path: Path, port: int, gpu: str | None, log_path: Path): + try: + cfg = json.loads(cfg_path.read_text(encoding="utf-8-sig")) + except (OSError, ValueError): + cfg = None + if isinstance(cfg, dict): + safe, removed = without_profile_save(cfg) + if removed: # a copy beside the log: the user's config file is not touched + print("Note: the bench starts this model without --expert-profile-save, so its short prompts do not " + "overwrite your saved expert profile.", file=sys.stderr) + tmp = log_path.with_suffix(".config.json") + tmp.write_text(json.dumps(safe), encoding="utf-8") + cfg_path = tmp cmd = [sys.executable, str(ROOT / "serve" / "server.py"), "--engine", "strata", "--config", str(cfg_path), "--port", str(port)] if gpu: cmd += ["--gpu", gpu] diff --git a/tools/test_strata_bench.py b/tools/test_strata_bench.py index d0449f68..30d3978b 100644 --- a/tools/test_strata_bench.py +++ b/tools/test_strata_bench.py @@ -2,6 +2,8 @@ writing and the comparison. Light: no GPU, no Strata server, a few seconds.""" from __future__ import annotations +import contextlib +import io import json import os import sys @@ -296,6 +298,34 @@ class ReportTests(unittest.TestCase): m = B.collect_machine(srv.base, "", {"backend": "sycl"}) self.assertEqual((m["gpu"], m["cuda"]), (["Intel Arc Pro B70"], None)) + def test_a_bench_server_never_saves_over_the_users_profile(self): + """#2088: --expert-profile-save writes the profile at quit; the bench's own server runs without it.""" + cfg = {"args": ["--expert-profile", "p.bin", "--expert-profile-save", "p.bin", "--spec", "4"]} + safe, removed = B.without_profile_save(cfg) + self.assertTrue(removed) + self.assertEqual(safe["args"], ["--expert-profile", "p.bin", "--spec", "4"]) + self.assertEqual(cfg["args"][3], "p.bin") # the input is not changed + safe, removed = B.without_profile_save({"args": ["--expert-profile-save=p.bin", "--spec", "4"]}) + self.assertEqual((safe["args"], removed), (["--spec", "4"], True)) + same = {"args": ["--spec", "4"]} + self.assertEqual(B.without_profile_save(same), (same, False)) + with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as d: + c = Path(d) / "strata-x.json" + c.write_text(json.dumps(cfg)) + with mock.patch.object(B.subprocess, "Popen") as popen, contextlib.redirect_stderr(io.StringIO()): + B.start_server(c, 8080, None, Path(d) / "run.log") + used = Path(popen.call_args[0][0][popen.call_args[0][0].index("--config") + 1]) + self.assertNotIn("--expert-profile-save", json.loads(used.read_text())["args"]) + self.assertIn("--expert-profile-save", json.loads(c.read_text())["args"]) # the user's file is as it was + + def test_an_attached_server_is_not_stopped(self): + """#2088: with --url the bench only reads; the server it did not start keeps running.""" + srv = FakeStrata() + self.addCleanup(srv.stop) + with tempfile.TemporaryDirectory() as d, mock.patch.object(B, "stop_server") as stop: + self.assertEqual(self.run_main(srv, d), 0) + stop.assert_not_called() + def test_names(self): m = {"gpu": ["NVIDIA GeForce RTX 3060"], "model": "Qwen3.8 Flash-Next", "quant": "IQ3_XXS"} self.assertEqual(B.results_dir_name(m, "2026-10-10"), "2026-10-10-community-rtx-3060-qwen3-8-flash-next-iq3-xxs") From 85f839d80c0a5a4ccfab278faa1e2e3945a7016d Mon Sep 17 00:00:00 2001 From: Oleksandr Dovhoselets <248732669+did-technomancer@users.noreply.github.com> Date: Mon, 12 Oct 2026 09:51:54 +0200 Subject: [PATCH 20/67] hip: gfx103x creates the MTP drafter's side stream again (#2055) #1240 stopped creating the drafter's branch stream and its two events on HIP: nothing uses them there, and an R9700 lost prompt speed with them. On gfx103x the stream's existence alone makes prompts read faster. RX 6800, Windows, STRATA_HIP_PROMPT_F16=1, IQ3_XXS, two runs each: a 7.9K-token prompt at 798-808 tok/s with the stream and 584-596 without, a 30.4K-token one at 855-863 against 553-600; all of it is in the prompt path's "wait copy" phase. The two events change nothing, so they stay out. gfx103x creates the stream; other HIP cards do not, as before. STRATA_MTP_SIDE_STREAM=1 / =0 forces either. CUDA is unchanged. Measured on one card under Windows only. --- docs/AMD_HIP.md | 8 ++++++++ src/core/mtp.cpp | 19 ++++++++++++++++++- 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/docs/AMD_HIP.md b/docs/AMD_HIP.md index 66250f25..a8fe8834 100644 --- a/docs/AMD_HIP.md +++ b/docs/AMD_HIP.md @@ -216,6 +216,14 @@ of decode (one card 47.5 / 46.9 / 48.3 -> 50.5 / 48.5 / 51.3 tok/s with it on). `bench/results/2026-10-04-community-rx-6800-windows`): on was 12-22% slower. 4x R9700: fork off was 13-45% faster. Linux RX 6000 users can try `STRATA_SH_STREAM=1`; the output is identical either way. +**The draft's side stream (`STRATA_MTP_SIDE_STREAM`):** HIP does not use the MTP drafter's branch stream, and since +0.1.40.2 it does not create it (#1240: an R9700 lost prompt speed with it). gfx103x is the exception and creates it: on +an RX 6800 under Windows (`STRATA_HIP_PROMPT_F16=1`, IQ3_XXS, two runs each) a 7.9K-token prompt reads at 798-808 tok/s +with the stream and 584-596 without, and a 30.4K-token one at 855-863 against 553-600; `STRATA_PREFILL_TIMING=1` puts +the whole difference in the "wait copy" phase (3,081 -> 75 ms and 12,642 -> 288 ms). Decode and the output are the same. +`STRATA_MTP_SIDE_STREAM=0` turns it off on gfx103x, `=1` creates it on another HIP card. Measured on one card and one +OS; a Linux gfx103x number is welcome. + **Long prompts on a big card: check the lend-coverage line (#1389, measured by the reporter on an RX 7900 XTX, gfx1100, v0.1.40.2, 50 GB RAM).** With `--resident-experts` the prompt path borrows cache slots, and the experts of those slots must also sit in RAM. After the first request of a start the engine prints diff --git a/src/core/mtp.cpp b/src/core/mtp.cpp index 89f8b519..971cc3e7 100644 --- a/src/core/mtp.cpp +++ b/src/core/mtp.cpp @@ -432,13 +432,30 @@ bool MtpDrafter::load(const std::string& rt_dir, const ModelGeometry& g, Session #endif if (!prio && cudaStreamCreateWithFlags(&cs_, cudaStreamNonBlocking) != cudaSuccess) { err = "mtp: stream"; return false; } #if !defined(STRATA_USE_HIP) - // HIP keeps the shared expert on cs_; only CUDA needs this branch stream. if (cudaStreamCreateWithFlags(&side_, cudaStreamNonBlocking) != cudaSuccess || cudaEventCreateWithFlags(&sh_fork_, cudaEventDisableTiming) != cudaSuccess || cudaEventCreateWithFlags(&sh_join_, cudaEventDisableTiming) != cudaSuccess) { err = "mtp: streams"; return false; } +#else + // HIP keeps the shared expert on cs_, so nothing uses this branch stream, and #1240 stopped creating it and its two + // events (an R9700 lost prompt speed with them after the first request). On gfx103x the stream's existence alone + // makes prompts read faster: RX 6800, Windows, STRATA_HIP_PROMPT_F16=1, a 7.9K-token prompt at 798-808 tok/s + // with it and 584-596 without, all of it in the prompt path's "wait copy" phase (3,081 -> 75 ms); the two events + // change nothing. So gfx103x creates the stream and no other HIP card does. STRATA_MTP_SIDE_STREAM=1 / =0 forces + // either. + { + int dev = 0; + cudaDeviceProp prop{}; + bool on = cudaGetDevice(&dev) == cudaSuccess && cudaGetDeviceProperties(&prop, dev) == cudaSuccess && + std::strncmp(prop.gcnArchName, "gfx103", 6) == 0; + if (const char* v = std::getenv("STRATA_MTP_SIDE_STREAM"); v != nullptr && *v != 0) on = std::atoi(v) != 0; + if (on && cudaStreamCreateWithFlags(&side_, cudaStreamNonBlocking) != cudaSuccess) { + err = "mtp: streams"; + return false; + } + } #endif const double files_s = std::chrono::duration(std::chrono::steady_clock::now() - t_files).count(); if (shared != nullptr) { From a0116b2782a5b82622358c04a06496485d12b2d6 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 12 Oct 2026 15:20:20 +0200 Subject: [PATCH 21/67] Layer split + --batch: the default pipeline wins over --batch-mtp (STRATA_BATCH_MTP_SERIAL=1 or --batch-groups 1 keeps the serial MTP windows) (#2038) 0.1.42 let --batch-mtp run on a layer split and made the --batch-groups auto default give way to it: one serial group. On 2x RTX A4000 (IQ3_XXS, 3 pairs) four streams aggregated 62.2 tok/s against 92.7 on 0.1.41's pipelined groups (-33%, 0/3 pairs faster), two streams 55.7 against 71.4 (-22%). With --batch-groups 2 (which turns --batch-mtp off) 88.3 and 71.1. The start-up line says why --batch-mtp is off and how to keep it. --adapt-async 1 still gives one group. Solo decode and the answers are untouched. --- docs/BATCHING.md | 4 ++-- include/strata/program/batch_groups.hpp | 14 ++++++++++---- src/program/batch_groups_test.cpp | 14 ++++++++++---- src/program/generate.cpp | 8 +++++++- 4 files changed, 29 insertions(+), 11 deletions(-) diff --git a/docs/BATCHING.md b/docs/BATCHING.md index 7e79c05d..69e5e2f7 100644 --- a/docs/BATCHING.md +++ b/docs/BATCHING.md @@ -35,7 +35,7 @@ drafter's does). A window carries two rows per active slot (its token and its pr four slots are in one window; more slots (`--batch` up to what fits) rotate through. The windows run through the stages one after the other (`--batch-groups 1`): on 0.1.41 a layer split with `--batch` 2 or more pipelines the slots in groups by default, and the pipelined path does not run the slots' MTP drafts, so with `--batch-mtp` and no `--batch-groups` the -engine runs one group and says so; `--batch-groups G` (G above 1) or `--batch-groups auto` given on the command line +engine (0.1.43.1) pipelines and leaves `--batch-mtp` off, and says so (0.1.42/0.1.43 ran one serial group with it: 4 streams on 2x A4000 aggregated 63.9 tok/s against 91.8 pipelined, 85.8 pipelined without `--batch-mtp`; #2038). `--batch-groups 1` or `STRATA_BATCH_MTP_SERIAL=1` keeps `--batch-mtp` with serial windows, which is the better choice for about two streams as measured below; `--batch-groups G` (G above 1) or `--batch-groups auto` given on the command line keeps the pipeline and turns `--batch-mtp` off. Only a layer split of two stages on two GPUs has been run. Measured on a layer split of 2x RTX 3080 20 GB (220 W cap) with a Xeon E5-2696 v4, UD-Q4_K_XL, `"layer_split": "23"`, @@ -86,7 +86,7 @@ With a layer split, the engine options go into the config's `args`: | --- | --- | | `"parallel": N` / `--batch N` / `--slots N` (2..8 normally) | up to N conversations have batch slots; more requests wait for a free slot. Each slot gets its own state (a session carved like the stage's own: GDN recurrence, QSA K/V and indexer, PLE history) on every GPU of the split. With grouped MTP, more than 8 slots can rotate through eight-row windows if memory permits. | | `--batch-groups G` | with a layer split (default: auto, below): the N slots in G groups that flow through the GPUs as a pipeline (GPU k runs one group while GPU k+1 runs another). G must divide N. 1 = all slots in one window, GPU after GPU. | -| `--batch-groups auto` | the default on a layer split since 0.1.41 (give no `--batch-groups`): the engine pipelines one group per GPU stage (the most that divide the slots; 8 slots on 4 GPUs = 4 groups of 2) and says so (`INFO batch_groups=G`). `--batch-groups 1` turns it off (all slots in one window, GPU after GPU). Measured, 8 clients, total tok/s against one group: 4 x R9700 166 against 86, 2 GPUs 109 against 78, 3 GPUs 110 against 78. With `--batch-mtp` or `--adapt-async 1` and no `--batch-groups` the default is one group (the slots' MTP drafts and the adaptive tier between batch windows do not run in pipelined groups) and the log says so; `--batch-groups G` or `--batch-groups auto` given with `--batch-mtp` pipelines the groups and turns `--batch-mtp` off, and given with `--adapt-async 1` pipelines the groups and turns `--adapt-async` off (the pipelined path does not adapt). | +| `--batch-groups auto` | the default on a layer split since 0.1.41 (give no `--batch-groups`): the engine pipelines one group per GPU stage (the most that divide the slots; 8 slots on 4 GPUs = 4 groups of 2) and says so (`INFO batch_groups=G`). `--batch-groups 1` turns it off (all slots in one window, GPU after GPU). Measured, 8 clients, total tok/s against one group: 4 x R9700 166 against 86, 2 GPUs 109 against 78, 3 GPUs 110 against 78. With `--adapt-async 1` and no `--batch-groups` the default is one group (the adaptive tier between batch windows does not run in pipelined groups) and the log says so; with `--batch-mtp` and no `--batch-groups` the pipeline wins and `--batch-mtp` is left off (`--batch-groups 1` or `STRATA_BATCH_MTP_SERIAL=1` keeps it); `--batch-groups G` or `--batch-groups auto` given with `--batch-mtp` pipelines the groups and turns `--batch-mtp` off, and given with `--adapt-async 1` pipelines the groups and turns `--adapt-async` off (the pipelined path does not adapt). | | `--trim-stage-weights` | with an **explicit** `--layer-split` (e.g. `12,24,36`, not `auto`): every GPU loads only the dense weights of its own layers instead of the whole model's (the same as `STRATA_STAGE_TRIM=1`, PR #639). The VRAM this frees goes to the expert cache. Useful without `--batch` too. | The engine never refuses a count it cannot run: it says so in its log and runs what it can - at most 8 slots by diff --git a/include/strata/program/batch_groups.hpp b/include/strata/program/batch_groups.hpp index e0d87589..0abff1f8 100644 --- a/include/strata/program/batch_groups.hpp +++ b/include/strata/program/batch_groups.hpp @@ -3,9 +3,12 @@ // `--batch-groups N` pipelines N groups of slots through the stages of a layer split; `--batch-groups auto` picks the // most groups (at most one per stage) that divide the slots. Since 0.1.41 a layer split with `--batch` >= 2 and no // `--batch-groups` at all means `auto`. The pipelined path does not run `--batch-mtp`'s drafts or the batch -// adaptive tier (`--adapt-async 1` between batch windows), so when one of those is asked for and the number of groups -// was NOT given, `auto` resolves to one group (the serial windows they run in) and says why. A number or `auto` -// given on the command line is honoured as before. +// adaptive tier (`--adapt-async 1` between batch windows). `--adapt-async 1` with the number of groups NOT given still +// makes `auto` resolve to one group (and says why). `--batch-mtp` does not any more (0.1.43.1): on 2x A4000 and 2x RTX +// 3090 four concurrent streams lost 25-30% with the serial MTP windows against the pipelined default, so the default +// pipelines and `--batch-mtp` is left off there (said at start); STRATA_BATCH_MTP_SERIAL=1 or `--batch-groups 1` keeps +// the serial windows with the slots' drafts (the 0.1.42/0.1.43 behaviour). A number or `auto` given on the command line +// is honoured as before. // // Pure (no GPU, no environment read): generate.cpp passes in what it knows. #pragma once @@ -23,6 +26,7 @@ struct Input { int later_stages = 0; ///< the layer split's stages after CUDA0 (0: no layer split) bool batch_mtp = false; ///< --batch-mtp is on (it passed the gates that do not concern the groups) bool adapt_async = false; ///< --adapt-async 1 was asked for + bool mtp_serial = false; ///< STRATA_BATCH_MTP_SERIAL=1: --batch-mtp with no --batch-groups runs one serial group (0.1.43) }; struct Result { @@ -30,6 +34,7 @@ struct Result { bool from_auto = false; ///< the number came from `auto` (given or the 0.1.41 default) Serial serial = Serial::None; ///< `auto` would have pipelined, but this feature needs the serial windows int would_be = 1; ///< what `auto` would have picked without it (== groups unless `serial`) + bool mtp_dropped = false; ///< --batch-mtp met the default pipeline: the pipeline wins, --batch-mtp is off }; /// The most groups, at most one per stage of the layer split (`later_stages` + 1 GPUs), that divide `batch`. @@ -51,8 +56,9 @@ inline Result resolve(const Input& in) { r.would_be = auto_groups(in.later_stages, in.batch); r.groups = r.would_be; if (!in.set && r.would_be > 1) { // only the default gives way; `--batch-groups auto` asked for the pipeline - if (in.batch_mtp) r.serial = Serial::BatchMtp; + if (in.batch_mtp && in.mtp_serial) r.serial = Serial::BatchMtp; else if (in.adapt_async) r.serial = Serial::AdaptAsync; + r.mtp_dropped = in.batch_mtp && r.serial == Serial::None; if (r.serial != Serial::None) r.groups = 1; } return r; diff --git a/src/program/batch_groups_test.cpp b/src/program/batch_groups_test.cpp index 19145638..ecc51929 100644 --- a/src/program/batch_groups_test.cpp +++ b/src/program/batch_groups_test.cpp @@ -49,9 +49,13 @@ int main() { { // the production shape: parallel 2 on a 2-GPU split with --batch-mtp bg::Input i = in(2, 1); i.batch_mtp = true; - const auto r = bg::resolve(i); - check(r.groups == 1 && r.from_auto && r.serial == bg::Serial::BatchMtp && r.would_be == 2, - "--batch-mtp, nothing given: one group, because of --batch-mtp"); + auto r = bg::resolve(i); + check(r.groups == 2 && r.from_auto && r.serial == bg::Serial::None && r.mtp_dropped, + "--batch-mtp, nothing given: the pipeline wins, --batch-mtp is dropped"); + i.mtp_serial = true; + r = bg::resolve(i); + check(r.groups == 1 && r.from_auto && r.serial == bg::Serial::BatchMtp && r.would_be == 2 && !r.mtp_dropped, + "STRATA_BATCH_MTP_SERIAL: one group, because of --batch-mtp"); check(bg::serial_what(r.serial)[0] == '-', "the reason names the feature"); } { @@ -64,7 +68,9 @@ int main() { bg::Input i = in(2, 1); i.batch_mtp = true; i.adapt_async = true; - check(bg::resolve(i).serial == bg::Serial::BatchMtp, "both: --batch-mtp is named"); + check(bg::resolve(i).serial == bg::Serial::AdaptAsync, "both: --adapt-async 1 still gives one group"); + i.mtp_serial = true; + check(bg::resolve(i).serial == bg::Serial::BatchMtp, "both with STRATA_BATCH_MTP_SERIAL: --batch-mtp is named"); } { // nothing to give way: the slots do not divide, so auto is one group anyway and there is nothing to say bg::Input i = in(3, 1); diff --git a/src/program/generate.cpp b/src/program/generate.cpp index f7f1b167..1e5299e5 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -4360,6 +4360,7 @@ int main(int argc, char** argv) { bin.later_stages = (int) stages.size(); bin.batch_mtp = mtp_on; bin.adapt_async = o.adapt_async != 0; + { const char* ms = std::getenv("STRATA_BATCH_MTP_SERIAL"); bin.mtp_serial = ms != nullptr && ms[0] != '\0' && ms[0] != '0'; } return strata::program::batch_groups::resolve(bin); }; const char* batch_mtp_env = std::getenv("STRATA_BATCH_MTP"); @@ -4372,7 +4373,12 @@ int main(int argc, char** argv) { : !o.serve ? "it needs --serve" : nullptr; // the groups it would run with (the default gives way to it: one group; a number or auto given pipelines) if (why == nullptr && !stages.empty() && batch_groups_for(true).groups > 1) - why = "it does not combine with --batch-groups (pipelined slot groups) yet"; + why = batch_groups_for(true).mtp_dropped + ? "a layer split with --batch pipelines the slots in groups by default and the pipelined groups run no slot " + "drafts (4 streams on 2 GPUs: 25-30% faster than the serial MTP windows); --batch-groups 1 or " + "STRATA_BATCH_MTP_SERIAL=1 keeps --batch-mtp with serial windows (fewer streams, or when prompts arrive " + "rarely, it can be the faster choice)" + : "it does not combine with --batch-groups (pipelined slot groups) yet"; // (a layer split with helper-GPU expert caches or --remote-expert-opt has not been run with slot drafters) if (why == nullptr && !stages.empty() && (remote_caches || o.remote_expert_opt)) why = "it is not run with helper expert caches on a layer split"; From 0601072dfc924eaa0c1e845d2bfbc3100cda7e46 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 12 Oct 2026 20:19:49 +0200 Subject: [PATCH 22/67] test_setup_strix_halo: gfx1103 is in the gfx11 WMMA list since the 780M change --- tools/test_setup_strix_halo.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tools/test_setup_strix_halo.py b/tools/test_setup_strix_halo.py index 86cbf50c..0fb83051 100644 --- a/tools/test_setup_strix_halo.py +++ b/tools/test_setup_strix_halo.py @@ -91,12 +91,12 @@ class ExactArch(unittest.TestCase): def test_matches_the_engines_header(self): """include/strata/kernels/gfx_arch.hpp is the reference: gfx1151 has the WMMA kernels and the gfx1151 defaults; - gfx1103 and gfx1152 are outside its list.""" + gfx1103 (Radeon 780M/760M, 0.1.44) shares the gfx11 WMMA kernels; gfx1152 is outside the list.""" hpp = (ROOT / "include/strata/kernels/gfx_arch.hpp").read_text(encoding="utf-8") wmma = re.search(r"gfx_arch_is_gfx11_wmma.*?\n}", hpp, re.S).group(0) listed = set(re.findall(r'"(gfx\d+)"', wmma)) self.assertIn("gfx1151", listed) - self.assertNotIn("gfx1103", listed) + self.assertIn("gfx1103", listed) # 0.1.44: the 780M runs the gfx11 WMMA kernels (decode x1.53) self.assertNotIn("gfx1152", listed) self.assertIn('gfx_arch_is(gcn, "gfx1151")', hpp) self.assertEqual(setup.STRIX_HALO_ARCH, "gfx1151") From 6b395578a22209b0867443e4cd2d3bf58a11466a Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 12 Oct 2026 18:20:48 +0200 Subject: [PATCH 23/67] Expert arena: MADV_HUGEPAGE is not requested when free 2 MiB blocks cover less than half of it (direct compaction stalled a 62 GB box's load at 100% system time); STRATA_ARENA_THP=1 asks anyway (#2126) --- src/core/pinned.cu | Bin 39455 -> 42474 bytes 1 file changed, 0 insertions(+), 0 deletions(-) diff --git a/src/core/pinned.cu b/src/core/pinned.cu index 12cda84758845ca8f761d2aa19e6d7445f61c376..a1a94da62ce2a68c963a16a3811c703d8523f95a 100644 GIT binary patch delta 9089 zcmb7KdvH@%daoe{Y%FZ>TYeo0u;mxBjIqHlkg+iag9$cZFt)gst}G$xURk=b5yqH6 zp1jRT2%9e1ot@b<)1)lB-JQ1Cc9Qguv}v;0&32QSWD+J!(rucZ&Cq72?J~)x-|yZl zOR}AIt6@H0oqNuAzW4V#M||hUOFnyJ$<_TShS~jQB1-vEL%L!1PmMG5Cw;9~a{41K zk+lkn9Pm2Z6Nj9BZ@{aBlgGqRNRpF>!ivl99bGWyT`(==mB!|#HDFhFSP6+jU~Uj& zfruiWNE%T*G|5Fn27WZh~k?A=&z;KfV2SJ0s74~zIx${$-| zHex_>dEJ__N%LP`lIw`gPcVerDJlL9o+JUn(XcfT5Tr$h!-}BH8;(d`G6@EG?b3pL zRZt0%?y>K4>^#uj<*47&VcA4hl|@k#Ph?Xl{1OA(2f%h4?#s z<+qn^Bx`)Uv>86-r4JPK7}6PioE{;>0>YTrIb>@bZqWuKUP;+l?@-u;7z%r3Y5uT> zY%GQxqftc+w;1^82aIGraKpmJ23kl$`5Yc0?4j4UA26mG(x>U^XAgAgvE){@)cuie zwKA0#^GeJe5=A!Zmz};alijSI?eTUnnPh}!7HcphJFTM;mn-U(+;R=QAxT(!8{1OZ z%qBg8LZ<6HsM>Cyy}OG!1&NJ`3Y+vQ9yy}04yPO-;S|!!kUl3aHg$L+W1^;$r4lww zQb>^%!Oz-Q9jWpBhV_NXa+qtFIb^QHGM-}1&e>$EkJ%DjCOuxi$g8Y%U#W~rk0ZLES-RI=*o@o$`CqB(z3!OF`SEx?!90uq7Tqj*FH@hZX$fu$Ko zm5+a~BF|63V;d$prs~Mes^Qdk5MNT5q}eTL+)XaEw9uw76P`9O#gk-I) zOipw%G35bEe!0e5-y$R`k&vWuAt7i~&w9QlH9%1`lPVMaJk>|^@Uju2f3?i{09f#U zKcCBA-=!&(%H08Dypz5CBbKDr8Kl6eU#|&^tD7Usq}WbYne8QUrsOJ zwv`q1iaf;wE4_GPx%@XP`>A4sPwX>o;Jq28Iq^Z=NU)qHOA-Hzj4ibO*BNf2y@o2H z6NX`;|7_?cYFq{G=T^a7pRd|Uv@!D#(My>}iH@@}z9MUNc6lW40@o zmt|-0iLA}^?N(M^Mtm+w_f{6zH?4*lR%Ms)S63gQr|~rnyl)M4QhLHRcj_BfQD)8M zF_~#qc3-B(X_}!M!F0#7cjEN}_Ndz~Eodel-!($vlHwww9~l|HSpe1ED_{#_XL%u}))e+&!(*idscpu*v-ld^#(y4^y`Ng#Ct|^=7?@T75vlK|xX1g8_$ssE_3sR|m(FV87>oCKbRm49x zXV9|y=3PWP*KQ%SqgouBJiPW84Su517wc;On1p+O-Bwxx`Sud1(Nn|1)`|Ng2?q) zijx(;Y>{aAOUp>S7#yn%($Fs|;pMGWy+m)jP5i~GmGpGxR1SZms(_w8u5uEkl0o!% zHJtZUHFEjytM?IIQ`1DWr>2YO<(d|vuh*0j{j>(f>p-o7ky`AqdBZ`Xmp34hpWkqp zXo?j@z08VLggkgy{XT0&c)xG8&#NNT)8e9UuY)08tlLZUejQ5nLmR_HpR*x^Kd>Qu zQT(m-NNzlxu7@M<)OYZ*L&lkbo%_s{2`GqwO590sK7AH~xK*kd!8PFxih^9X%tM)aho$oD^b6hq z6C@YGG!-wVPl*0F}T7dOO&d;FZWA{est3L*iAs zSpUF&`+(hH-`};@?jX0d*_aTfGXmC-K?Nx~DMU9c7F|^h)!BRd2FN+%5s~C}H8WZA zN4f1{PVd5)X>Vs6slQdnwb7!BQNf0cB)WP;N${K|gaC#!+BxR`Vxl^;CKe)e79l&p zv2;Wvgcvg@vn-;tt_4DbJfNvv$t-F-SDKelp}bR%gYUvDt7_P>PSZ-S%t>HEJNnWa z%J~M%W^E$MpNW8wHWQ#D=^(8plx0Hpx(H(Hhr!Pp)@_Y}6ZL%{B2ju+f;HL{K;PI2 z7Q3ZSs|Sp^<0=H`+O(}u6JYLy<^k9jMHlJ!?M)TAaqoE8NE-_ddC{xh-Beb&n1*x; z1%ysM6!U_{t=7f1PY0w|J>($R>~IP}$C!6iJrnY?ji_BeZL|{otPvG#xCy0vx~Yhu zz=A#I*^B?A$xo9_n?pqTW>ncFTfii;#YObJEvT%w-37d+d3A-Rh}MiFZoM6=7KMB+ z5yu~#Mulcn{b)1l{mtf$M1RpN5Vf@ct(vW+{EWf zYirvVip5qq}qdko?BY$OE8jozV&3ywp{Cpd5OZ$;(zR3fUP<&@+tFzM zV>^&lVP_4|u1;GrFgVi**z-@F0B~P-0%f?n(B)^lfFpj^RZjGaE4#2e+ zcA&c#boUeWbpw>&JD+DzFYUk=q6^Usa~MbMM+n@-|%);Y4fHs=1fy2{qbZZ|dL z*xeIs#{+}gXEo?hMyS3u1#M{4ngbZm53xW5nOKm{&`SMZ-7 zs;6(i>(jX9@*iAX#*Yq~)ER}`cdV1Yvro4J|Jy;JF03pwE$3Sw%-fW#2{f9gT*BA* zX%X5z^I(U{D~I2E5Kz{-f6wYo`TPB-J-+^Nq961FPxcOA{H1}iMb>;e zfapDR08s41qX^172e7j5ppWQF2N7jJf`y0hZrdS*$w$UQ-4ZE-ov0S}eNB9N5GnM+ zAW8|H7@#mcr3~gQnbKA?9d6JoUd)$?>T2512>nBz4$|UJ4kOwON02=2N02s)Wn|{O zjO3#b9gaE!cRHJK;+UnIS>pu+DK>qe<$+ca}c>Ynu^sb{PN|J5sjJSmU zh|@{1O-*XD6HA^kKjtacO~dQK`s!{|s$ZlS=lNQ$h`XrmKX1GCY8Zrl67c zk04}1BM9Q(jv(199WXdf{SuWk=&MIr~bPq^yP%}g@Y z3v-olRw!MpUcD@wOHdxAOs&h>rKzg?@aW-0-g9T*uRC-32cxT#E7^aII`n&E_`4;CaT{WI_%IZ@1TUPGDQ<|>a>4Qd+vAy+rO{72Ua(QbEq)S9tWO4eKYxRv~u{6E4IfF z!9VqtVBxVV`TU;Gi$`D3G_U&1;k`wYQM}G=orn7Ncd{{A(R1#!gvx?DjjtuOa#E#z)0aVGcKHm^S7n@H zR|gLebqC8Ek~0k)=Vu$nC~oivA9~~uX5?geVt24~W6j?Wq9=Y8wCk5HIF*PY3$BrS z$MH%Yhm&T<;ng>;7wwGmqW~e#&>@7bi&YP4+ss|n%|((fLoA>a6&~>)K9vj1{??NY ziU|Em?`%k>o7)&j20tCssJw`efv1Pj_{YQQC0g2{Dt;%th6e71(Wij_a-B_Rd_#wI9fUZ>km%g z4&mm+L88wdH}RZFRAt26g~@b!a`-I#?9tAl`D7CQOg({m-FN~W<@yP%`256f zqKKs4C=w+xZdRre3Lr`DMr|c=lfxqOe({s9tUz|qd0)u}sy=SGSjrI#<&*`ZC=DpL%Rt=}8@unHgqWS!}nG(G} zX<(Z+AT545(-04uj5B*_>5((*^xG>vWajFY{^Ow-8T-5D@5M?u45qwXRX6L^gcrt1#>OVJbe0R7U>7W7xF#aYtP| zM(Jn0h*M$P{c@NtH>Tn*z+?yABUUj4_VbUoCR}t+Gp9O#%8jD*`^T#jj%xGEZf`V= z_diig8_Q21nPa85gKs$xFs3C`CO>-~NQ>Y;zjYq-=qW8IhxKxM?>y4cbYYn2=?hk( zdg;|#L;?Tm!tSbM;TN?61}U_7Fp!%Wpt~D1takl(0_}8=#(#7XZ3^GMxM&4``@Ves zihmj3b_pBHm*6M_ZQwQn!wx{S8~)jxrEeH^$uZ|&3yXG9(BBk z|H~D-{$#%ju7t3Q7WfR(;zOVZ;`~IN3B}tBm-Cca#AVeiRv(^CmWlEEv#WX++5-lq zpZXFHE7}eSn3z3k7fv7n_Fc0iqoT9dEVT2VU$f{nftT19V3^=|Tv nIvAIlnHIhc+9?|JoHfkkXncX9!GhVYtkGrc<%LBVA%4ipH zn;5YgJl5boKJGSq%z0;bDGwXDC zxGpW5)3zI2E^@5IQ>YS(^~??-9$FnK&^~2KBB~-wF&UY>hVPrhg~)My73qX6%8p+~ zjjH(YEdS5cZ>j5SXm1p}&IzLGn6lYiUbh~`=ux~IorO>7FFM8qPfP>$u1&yCV?^jS zCZK(NcXWURBQuBB*DKZshUWMiV_u55*v;sOwcw4|Jp5bi5UMsbujbSE_4*{-+R%Y# z8z!(Pt_64EcH^tKLDXFrFcZH%Hb73a2x^x`n8mgDeB8=QfI}0B-^FiQOpT9pNk*20 zXh;xoH^Gh}O*%Fw4ur`TXG`(p#7y?mjMAidoUbfHmnMo_;hb znvDt0@;BVq#-TQ~5U~q!SV*l;49qiqEheE-C}v7Cg`dg8@u$?R2-0J;fW$H zhC)^_lMgv?=w+BxCHi*O)2?*^+H*48>Ws%^8l@658vAj66rEPa?q(XxkFd$a=%pkP zmM%wn`XC-&PJ$~XVtD{4GPCi1`Zn5|o|U|+O3>-CNl}jjifr6g6p@ULNXjVvX3}Re zc9Q3l@u!S7KZ}fjgiJ~)sQ8=TXUBzYKCx2pc9wFD=n*o7d`>22Rs~U+5qSTRQtc=E zb&@|($T5;xfR{2WNW=@u1pFei8p&DC5c)0OM4&=d&X=83rTaGjvnqi&XW$R2CjQ)= zy@@|x&(0+qCa)OP`)Q?ola4ZIbBruDWI?y$eoh>Il%ov9#L8Sfc{e9OBWR-lVi+j8 zs|ev-dK}GFk$kt}<>)Vt#C%}_KF%#ix_WaU@b{|s;`{XXpuF%K(&Q~o4Yz4rULAV# zGJGkic`g-ypEriyd=U@xM~J6#trB$wP0Tvs@(7pHY2zS~;QmlvWL_B_|O~waWBTHFWiu3VKaRRg?z*@#1lb6V;`=Qn?AK&TQF21(Tpw@LF9XcBjd# z$Gy^i$jTJZl<8Tj;oh1xI7r|8y{rNsm(?xFuc5*uztlbDBH6N&^ftT{hnT8tG*@`= zRz(H=SW!(-+J%LUQv^!mU$f%FswM@ON^)u_1o6sCncP~fF5^pB1}h07rA5n%17D$@ zc8VsA;450+sa9?Dm1UMt_9+Jih}u;k&1)FU`FP0Y1VO760%cT&sG3@I)+E7FliSNl zGYVE=xJq#C5q%X@8pbw-?zs{(g;B|YOcale6kjR~&0^q=5^uI>@gFUv%238MH}||#*SF?D+}41* z+Xh$CJl3~%l7Uk3xHSTYTXnwoA}pBVu)Zwn$#S!X#iyT)*;OX@Tp zb>;fHmG{QvYkb+0y1fa8?QZ;RyB%A1bmP*FEPQWACO+7awY+m)ztf9jJE!s0P7hq& zec?X4<4JcF`HQM7-qJ=u+oR?EmA9vqKi}?of%jQ$y{YV(JWB2PM6l6e*~NZyc)7PQ zf*YBA;=M8D3WpwF^k%CAgM8hRFCN)r;^>~zk|8~6cMVcCiO2n21~N89-0mU%{O;~n zdJ1sGM?l%vLSn=tW;OqXN&@Aquw z@-+~xS^HDghn#R0LB1{V6u@VQvW zI~~^UQv}hdeYA$GACI4o3;2B84Z}nMk6yCs^QVtT6B4Er+I&ZoP+S4z#Y za7ZB?hpBy7a{F-ZkP2@c%E7M=lbUHkA$K-Mg3}z;}4R)7}r-H6R57m4&TIUtg z$%oBb3?45_lLEoPvjs=yjre$8LxsE72Tb?8sW`rngYPcvqDWFA`*0tRrW=PND4NuG zpPs)wtiYFtm5?9Nq2tJ2+&$8V@S|-Uu343J9&HT?jTnjr9gl+t$8uI0$RDhqfALru z9vsu)lVce{SYUR_&!@_odVDxoS^pom3r*`0dxA>gi2@9t=;AHl4^C7g>|~$RGDDlp~Zg%sWxyTOOT2ymUJc?RcDf=>5#ak zL!Ef01Oz@5h6F!Bh}>|t94%)xaGy2d=V$W@IpMz%lL%%Ah&s-dVE&vFU!0r7==lje zKJP%)g+aV>!G(2;WvE>&k#uHmXC=eJnp_{;Gt?pEBB}09=Vk;`ldXLYvJj0)%wq%} zBILG(Ep6J?-k2v49>rX&47LMvf{_7;d)C4Z5*PD>M}#Gq7sq?X2N%=utBWcL_rySu zYpJ{X!^??Sduhwky38&$rRzzjRFg1zNr#JM;IfJCCX$z5l6-ub-5vNF z)`BZ}zAwiWwmEDv32$C0$7fgA^<5**ek&T+zvV>KE8|i>_)0uS*O=MW3~YT!8?|_~ zgO1Y{<^SSsSmHKL(6>p4K=E6sMqqCq8$Azz)kEKY)9SBK>e$k48B|VF2>Z4 z$i8IpOGCqd6RP9!tDCX*=4NcYSqwsMDLF#0pA7NI&0z_NyS;QYum{RN25)Jkdqm=9 zv`#tLwJv|^as5`BG{rkOzK<@e85rToEj_8?U}{MB2~6e?j_gx{yWrk>V(c}mb39b% z@cwNRS!Cc&E&acFr`z8=ta(jA1FU_>zoVhpc=o0S#07aGIH~;_u From e000fe5d9c58d287cc57fd72b68f3b009d4f97e9 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 12 Oct 2026 20:23:20 +0200 Subject: [PATCH 24/67] Expert arena: say at once that huge pages were skipped (#2126) --- src/core/pinned.cu | Bin 42474 -> 42604 bytes 1 file changed, 0 insertions(+), 0 deletions(-) diff --git a/src/core/pinned.cu b/src/core/pinned.cu index a1a94da62ce2a68c963a16a3811c703d8523f95a..64d4792a15b09e6adc3690db21afb029e52d9e9d 100644 GIT binary patch delta 120 zcmaELn(56MrVWvtjJ%s8Ic Date: Tue, 13 Oct 2026 00:26:51 +0200 Subject: [PATCH 25/67] Sources: no raw NUL bytes (expert_source.cpp, pinned.cu) + a test that scans for them expert_source.cpp's Linux-only STRATA_TEST_UNMAP_GGUF check had a literal 0x00 byte as its character constant (since 0.1.43; gcc warned "null character(s) preserved in literal"), and the #2126 buddyinfo parser in pinned.cu got one the same way (a heredoc dropped the backslash). Both are the escaped character now. Git took pinned.cu for a binary file because of the byte, so it was committed with CRLF line endings; it is back to LF (no other change). tools/test_source_nul_bytes.py fails when any tracked source file holds a NUL byte again. --- src/core/expert_source.cpp | 2 +- src/core/pinned.cu | Bin 42604 -> 41762 bytes tools/test_source_nul_bytes.py | 55 +++++++++++++++++++++++++++++++++ 3 files changed, 56 insertions(+), 1 deletion(-) create mode 100644 tools/test_source_nul_bytes.py diff --git a/src/core/expert_source.cpp b/src/core/expert_source.cpp index ad28f56f..1e3788d9 100644 --- a/src/core/expert_source.cpp +++ b/src/core/expert_source.cpp @@ -1721,7 +1721,7 @@ bool FileExpertSource::drop_mapping(std::string& why) { // Linux's page cache has no such lock: only the tests close the GGUF views (STRATA_TEST_UNMAP_GGUF=1), to run the // unmapped path the Windows file tier takes const char* t = std::getenv("STRATA_TEST_UNMAP_GGUF"); - if (t == nullptr || t[0] == '' || std::atoi(t) == 0 || role_ptr_.empty()) { why = "not Windows"; return false; } + if (t == nullptr || t[0] == '\0' || std::atoi(t) == 0 || role_ptr_.empty()) { why = "not Windows"; return false; } if (direct_.empty()) { why = "the reads are not unbuffered"; return false; } if (unmapped_) { why = "already closed"; return true; } for (Map& m : maps_) { diff --git a/src/core/pinned.cu b/src/core/pinned.cu index 64d4792a15b09e6adc3690db21afb029e52d9e9d..c9fef89451afdb32ca7fcc1f9adc2582b05dcefe 100644 GIT binary patch delta 6765 zcmai22~eEpc^)AFVnH0@*oB4NpL@BN8)-QuZUI6@FaLSGRRp7d*BO z>$Hxz(`lu6I-R6bk7acdxyi_}J)KS_j_g>Sq;)ODmfeosbQ-7c_y2n$J7H$||NlGQ z_x;}E`JV54`Y`OqgRrw(7YDKyXY*Ew7O$o46N$3THl1ZgZ{X@RZoAd2YYb}9S#)K z$yqg%X5C16&6tXBn=#wml@)3?H*0XZ%y!$dRulQk;8bhp-3FHmcUGlU`)Acu(Jaz7 zr8a3?rocSD-Dz+coU;b~NEPYvsIVfuEuQxuzaFovhr?&_es~5x50~JL%3KsjNF=;? zzp)mx%`j43UNNS^ctj&!lP2Pa5jptR2!;1OLNv`aaC^8Su1bZh$m|UNd?sVgWVRSM zMd37;*}&zGDxr-mz{$vBamXn00B0j9N)EeIg=?$Du_1yzc(A%N+TY|6VZ20~#eaMF|4xH@#%bf+cDKet zZt_JHJEJUkC(4dm(G+fq#t{~+qd5M)Ta3NYEqFUR9Un!Dw*kN5`#jn?BbNH?W{y$qwXG>pePaD}XMXRyRSS${=Qw4pj z7VpGn;|cxZ;`HJCa6FBbU@4?w#?ZL714q`H@oeoBMiV=6J8=j8m^g|pvmEv$#V7a$n2nsmQNS(WN>UN6E7L= zj-=KH4ftKElnsar4B+2Tek>6!X(h0y4F*z_t=p*Q>NzDXURd`tX(axT*34uGVPpXm z9L(Mb24{3`dT7|c1u8#}G@A-0lT0|Bo#Hj*nRFu)5SpLq#mRo7c*Ru6Cg$|l($`Z} zh+|o?P(^S&Xj8#(Qphq!(Q-iySx(gQ43KB#;)9GX(kRQ8tZLxORaht62#+imH)W-K z4gXG70g1fw`-GpCZ>99o`4q_g)`c$FAGf1im)EFNyp^39VRms@ToH+oEDgu;8L%r; z9{l+rQ{fZ-UDh+m8Oo}{sjM1W#R1Bo53?GPnr#o#()oP?YICajVaIbaypv;3M8#-} zIhT2l!EWTV#aPUho@;6X>+q zT?R^{0u>(Qu{>bq!_sI~K7sRhq~iVPMC{LBg%|U4@YneY94JY~r}@>8Db_{uQVGp8 ziV6G^{q9wlpub?vcT~}v1x?J?NGfc>V4*yybbnNsM0%H%?dOG)7%Vd5?IJa}ViTFU z7%7c%*zFbpp6?cOc)xfP(o5|3+CcJ}zU3N;Qp1WfATxlkrzd2|fF}~NH7J&iEyAfrsmvQ*R$#$c$5SAR`ol&= z6+eXGLna}zFo@tVgdMTzidnl^Pdlf;9*UcCYQ6l3by{a^R*gg9C>Ht)7@m4{h&&uu zR>t}Hj0k6%n(=;<7@s!fZ|9XW2_|m5fpd(Qy;MeMDkPLqu3J}KUS3mCS5aP0ffsg$ zkS&+^iYJ6H!P4B6@Vwr8&1v|sc^#5k%Fx>4!jD@x{HjHov21qe+L5xsfj-R_=mn?{Ci({@Rpvvxf{04)ws2J5;6TgO48e(@721+B#rQ9{^kC5+@Fx* z+x{IG++xK~whTbBHJg_IMR#%xe{1;xL;E&cWOgf9|ky z3UCVc#b@oLSvyimgq$CT6(>^g(O?U$Btf5u${iZoz-0Kl9b-rsGVvVFkraiSLu8jc zX=zx)9#GbYV_`T3n%#-GG@Qz|exmge_>)GUlyN&XnBKV=_jj^s$!ON)lh{;DjEwW& zuj}O0pN{y^l!_2@pEo(M03SmTEVYkr;7xfj+JuO)-T)J0BFf63AG6_K#++y$pT>{J z9Vk%Sa6v79Zrnes?WmiWp!MJ1o<}jBMx|y7*EH>Zz^6q~@1KV2FrjV0RqZBxrfuby z+&7hpNnI(<>6C2CXUhqYFMcULGAheRMXtU|C=k}e{(_dqJAuk2P!zw=(+N;tfR%=F zDuyCV7)t+QLA<+#L$NWPFRngg15O%?h4nIMG7CHK&y2<19AsQIcCrb5le^PHf}kVZ z8ko`P3@#T>SjjQMmLizVEk8(+)!bkX`b~6!fQ7+yyke^L7imj>2EH;kdjY= z{!LM^+4KCch`aVq{EvMcI~*JNC|q|~d1BbCTaD`JM*sVzX-Oq7vd6B`4-n0F5ziMY z(&aAYPjE&Jonw~m$;5>6kl-A~l(Pa?opQY8l;D@nD#W-3FyW%?bnQZvJJUy^WT&$* zd#eT~-I=)K77NK4Onc}Mpu!{fHk8k_VQyv^AIzlT>5QHVe++kL3n&1a_f%lbTm~MU zmtZH7uw!mJwSKUWN$f9C7TA^o*=)2sIfY8aA3BJ9i+5+BdUp|lg&zO$$_A{SFGKx{ z8QA|~3LGy+V{Sf{-t+J`^U2bXJZ#;ud21^-X?F{m`|99vT+g?u! zUcasOU0wa3$DZorQ%rG?1gf{=dnfVb-VNlBFEoWv?^_G!zG7V4SC2>gWWp(zHuYdS zhlKq(sM()~G5Q_epNSvr&&9+2GCbLzitqzEm=6?q^Zg@tHQqfS#d~Lx@$CU6$_@@v zPGsWsgG2m=z#WRB+)zZ(dBttEG22HE$*^!J6ITwEljmFnku47N$PiE_((mb1Eq5O-MYT8*XGV6{8vS!vF=+IB1QtS+*NajbWaO7O|i z&HQ`ou|^y^Hk8O)AzaS6CIw1}XUB4vP86c~cs~}8>jeN|R})Jo<|%2#SUkZF1&r=R z;n|5H{(a)53<0nOwq|urs&M+HDql|g{G~pmp3D)@+M5tQnD8-gTz5z?dvd!UYL>yy zTHe+W*x{FQ@l-DEostOMl$kv75eo0gsR|I1P_hx01hDSq)7AL-=>qym5qGAGJ>ztC z$GqC+QoClX3reaL0-Y3I;d0O+1Rsii8x zX)NBjSDB1YmXb33@#gO~*u|drri4-$LA9XsgfB!MGGNiB0M;YX@tG34iF^o zH49(oPP&?5!+d}3T|I4uoKc0vm+J$Yx`)#-P;f378JB;#NQgX}69jr&&ZVRIm2`}~ zlH&zEGgU$zE7tC0TtAm1ywS1P#XDGN|KD>`q?{jv`+OPo`(W|&+5G#rj+7fT_3)s8c-?&3i+?otv1P1eQZDA6;9 zpPoxwdHj5GsfB-bUZ%@a8kQB281SLbIUcXlNIbZ#@LC&wMTwd#%#1|LUkOsrVfEEm z;l%Bm&z@}cMHD`EO_C_JYRoov4liLXA%XBfdsPv6C<__YFG4V3CkGd6ZT%Rg0+-$)m_c*@1kqbqqAJ17p^pwz3+!W%bwnBBsG zof#9PmA8#|Lty?!Qtmb=@(8X(*m_e>E_igS8GpFB%|{B3-Dbx&MhpJ-RspdFF+RUl yij3Ps&vPsq%9h(KxIdtz)j*|VpI0y?%m~)g?lc$_dY9YV6l5kjr}qbRfA;^+7&Sxy delta 8004 zcmai332;=TYt&kPOG0Sh5g-AgwF|Ua5+D$$)$0B&HR|r)>TU@H2qZS! zV-|~x&2FSrlFB$^3MMn2dDahb`)u3%5auJIU8?)m?Bt6RvE zU#hG3-+%AE`|fh?eXsxWtp%UIyWoY65Y1Fa8WV5kLQRBb>T=>?{uhyMbDHfV7ExGl z@=6Yyd1GLg*=}>#yq@4b(d~9h!CfA&#cu0=qR;lkFt^P);2&0oRjnScTQoWRo#=Cn zc*T7|J>EecWZ^Ci?F!iwqM^4!8lxep)goF2%;`njE6XWipEbE63zDRaBTIw7i%KMx%J+nx)@cx@-BV$ zNLxJ0!d+OLJeQ4E@|x_z2BC;2zg)8NY~Et}W^s%<$}hg%<`jEY7niX3loq;?S%v6g z=uZQoG!~k|Z|6g^X8R(CncsdPS19Ar!!O3t*P&7Tm0Mvs!-9T;u<9=;ZAmtFZCR4H zLfIBp!o#~0oT@mdmvD^GjV0+!XD%kt@0JvCD=`f38^RK^f@fkj78X@i;vLVph7N`` zJ~ca-JKhh|sZP52Pg)`(uFKZ!6e&_s}_ zDS_T?il#M@#oRdbVWlgA4gl6Rxit8 zYG1aS>Fs3=Orw|En2s%nx;|ar$TTlzd#JK1-Au@!pTrMzcsS;R z$};*UUgI02Pbi5}bu0j(uv%Zj=2^YpNHFrOC~XGg1q4&w1B+E?i28#T3}j=TSL#kPQmfHJHWVZBfUjX)Q%BxEk3-o#A` zi&e9VQ!N8=8LCFiUjAnSIRIR^n~10h(di+{8!7QVfxvC6ZoR^7X%IIJ{X&e z4<#oveKxs<={w0QnLbJ`UzKmPH(w9TG9}004leUpNo=!vL z2Ck#0xOA*FFTXwMtNp`oEQzB#>0v&8U!=$JCxnbXqh4*D$UtPE?~@Gh)c0!__Ord2 zck&M_0SRjRN*TVcr6k484m2b3+2uIo>31t-XHk5vnt4Cr*u!=$O=m8`C;JL|Ju}i5 z;L%!m+oR0QOeP)EYNc6 zqXIKi#uTP~g}F?tisERx5Z};xudtF^VMRdusv=;)u_E-`D#C8>76JLU6noKAj8zIs zwk0Wg<@%^lOShvNcl}kN&p(!tW*?=p!20~TPYyR_cmRMZy%Hz z0;VYGa(1Wd%4~kqt);tV%X!A5vUNi3BTlXXvRrw}5M)tbQGwMW#s#6UQ1BO#2#&^$n^g4omwAI+I(S6U!Umn3j-j7! zj136aL7{hp;OeoVEc<98k-wyM%P0d zMfF%>px)Z1OrOgxm=znrZ~rGuAAFdg5Gjtb8;W@^XHUhF)DXt&>}^1(PEM!MYYni= zXAPy9%DU=0jQg7Ko1ugRM zmrY6NGw0IU%`n*|GeVnDKeXTE0mK0I?`;kZ#P`oP!`wYvoXZv25J?y<7Y!e60TNd? zqf+)XXEVLh43PTYX5_A<79eJ0OK~vz9Bn}wd9MX|aX~8p-PWpBhOzYHR?PgMHIwPr zt;mWGdUdqDZ9BKFw*fPC?VU`W?Z`+|?LhXwZ%=>n!1`%BV5s|P9FyLE8qR9y=nnUr zjHWv_a35-rwj)uruoJ@PbvCM7hvQJIxPktmvw=T^biqKtyy>w}jx&4?eAuIQcjfz1 z&WEk3biFGqkd@1tlovdW%@xQ&j+X&je@`jSWSrL06Deh@0nUH3JBB=4O)P*xN};c| zq9{kpu?>1esqiQ!g6?laQ6AD2%jHfKr3@rc|904zdzPmO4Yum+N+FHUa8Ah!OTW1t zw!!xQG>{)CY5rgtN!>sTY`01XqrTXu=x!ej@=dq0MjZ7?VYJbP7&1sJ$Z4ykf8PO| z!JJzr^rQ7ZrsVSAZDPxFb{_ERFXog@U)_l+1zY<4&MIz|^t3DsW>;9Kq0>E1{`OrD zu*ta#8RXtB7t^-g=zo28>O6D)dpDeVXD{;CeGwk_pcgYcj5y!CZiL?{In-~|{K2&} z(FeVtCRTL<^L*EhLKm7en%cN^-2_14x{adt#0Qky^49&;s=mJ^pw^$G7F8wukN*(V z-OTY}KV0<7rWi^$12_z3MA{F9FnhYnlrq`{Dzzl}Afm$p$3J7qQ}qH=wkeoQZ(HCM zQ!BJ|m_jL5#CBW6eaXRE2WoeYn9ZWcBclLoP#-*^pRbgL0x+1jLDnw7dXp87Bw2Ap zIB8uIAm-K9WO``rf=Y|GC(^b7c+tqf0j7@zP#)wBjw<1RV(;t@cm!-@H0imu+XnmJ zvE?a4VxathQz#3dsDoDT*~LByy+*X#oKDeVaEng9209e*mL;FgFd+!--rRFEKoj`n zv2*HDZUkga^bPF@T-0yvw}&!=G4R_VW5AUR@RTj!9I@M7UN=YQupQ}W%C6J+ zGr5Ev70q7By}sQhn#GNR3;+1;OE!eR9FnUo)%z~Hkj?J6fbVI;@KWP2s=(XB`q^^z z(J&ytat4{J(XCg@D|tQnZd2epRHI{rWtwou!5JbCucmk0DQNZ`PNYSi9G+R=fxHh+ z0<&g3C}M!48D12*7bdb69^lbm?k(ZBUwYxH|LL6s1LqigZAurTSNEaD82;h0N^T*m zvQqX1_~x4!=k5 zB(JKY$-O|R8|T*elFcnIayrm<$3A>ANIJT=54jbs!ZB0FQexXb4lzHKa{Jmz@& zsd3=f&2gym-(>oD90%&Nr;=9r%1l?18429pVBk(U>@~kZ&=v?0_Itq!v!G08xI4!^5KAIYUX_%Lr%h%iVhoim0 zn8yAy8>WYkm8s6wQrFVfv7@ug(6zO*u3K<;*L+(=}5VB_YA1#3EFf*zID2v9#02PK%F=Ye0`!t6-oY`f{P;ga}13>1HKsY z@iX9yR`Ih+NtHl9el}Ung-XHi@C@+&e*J9Otiwe;hq`+Aa~W!)Q{BxEjOyGtz5;p69F(#Oy1$Z)brZTS6-gyM!55GRxmOg zzl;sPdO0gnF)oM!^=*L|r(jZ5So^-c|&49pSg zrVFp4#2u9B%vJ1~^Gv+5a^P?|u&ZD0AIGmX()9A>xW^VC5)+zkvmsAc7x$u^M)2(3-@rqfQ9wZ$N zB~QZ(C#U7};-@p6vpAeIli~vh9x*%vzqvGnY;$j>I{?>tgQ`k+27hHWSbZj#UA9)_ lYe{J=OI{Y^@u}V|idno%U;dk`x49P>_&LM>%c~~h{{Vk2awz}+ diff --git a/tools/test_source_nul_bytes.py b/tools/test_source_nul_bytes.py new file mode 100644 index 00000000..1f054ebc --- /dev/null +++ b/tools/test_source_nul_bytes.py @@ -0,0 +1,55 @@ +"""No raw NUL byte in a source file. A shell heredoc that loses the backslash of '\\0' leaves a literal 0x00 inside a +character constant: gcc only warns ("null character(s) preserved in literal"), MSVC stops with an error (0.1.43.1's +generate.cpp; expert_source.cpp and pinned.cu after it). No binary, no GPU. + + python -m unittest tools.test_source_nul_bytes +""" +from __future__ import annotations + +import subprocess +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +SOURCE_SUFFIXES = {".c", ".cc", ".cpp", ".cxx", ".h", ".hpp", ".cu", ".cuh", ".hip", ".mm", ".metal", ".py", ".cmake", + ".txt", ".sh", ".bat", ".ps1", ".js", ".html", ".css", ".json", ".jinja", ".md", ".in"} +SOURCE_DIRS = ("src", "include", "sycl", "metal", "serve", "tools", "tests", "cmake", "bench", "docs") + + +def source_files() -> list[Path]: + try: + out = subprocess.run(["git", "ls-files", "-z", "--", *SOURCE_DIRS, "*.py", "*.txt", "*.sh", "*.bat"], + cwd=ROOT, capture_output=True, check=True).stdout + names = [n.decode("utf-8", "surrogateescape") for n in out.split(b"\0") if n] + paths = [ROOT / n for n in names] + except (OSError, subprocess.CalledProcessError): # not a git checkout (a release zip): walk the tree instead + paths = [p for d in SOURCE_DIRS if (ROOT / d).is_dir() for p in (ROOT / d).rglob("*")] + paths += [p for p in ROOT.iterdir() if p.is_file()] + return sorted({p for p in paths if p.is_file() and p.suffix.lower() in SOURCE_SUFFIXES}) + + +def nul_lines(path: Path) -> list[int]: + data = path.read_bytes() + if b"\0" not in data: + return [] + return [i + 1 for i, line in enumerate(data.split(b"\n")) if b"\0" in line] + + +class SourceNulBytes(unittest.TestCase): + def test_no_source_file_holds_a_nul_byte(self): + files = source_files() + self.assertGreater(len(files), 50, "the source scan found almost nothing") + bad = {str(p.relative_to(ROOT)): nul_lines(p) for p in files} + bad = {k: v for k, v in bad.items() if v} + self.assertEqual(bad, {}, "raw NUL bytes (write '\\0' instead) at file: [lines]") + + def test_the_check_sees_a_nul(self): + import tempfile + with tempfile.TemporaryDirectory() as d: + p = Path(d) / "x.cpp" + p.write_bytes(b"int a;\nchar c = '\0';\n") + self.assertEqual(nul_lines(p), [2]) + + +if __name__ == "__main__": + unittest.main() From 6339e8610da7d55b09e78e1b9517ce0aaf597924 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 13 Oct 2026 00:28:26 +0200 Subject: [PATCH 26/67] serve: the stdin reader shares its state with main instead of borrowing main's locals (QUIT race) The stdin reader thread is detached and captured main's stop flag, mutex, condition variable, line queue and EOF flag by reference. The server writes QUIT and closes stdin right after it, so the reader often wakes with EOF while main is returning: it then locked a destroyed mutex and wrote to a destroyed deque (undefined behaviour on every platform; the Metal port aborted on it). The state now lives in a shared_ptr that the thread holds a copy of, so it outlives main's frame for as long as the reader runs. CUDA/HIP and SYCL engines alike; no change to what the engine reads or answers. --- src/program/generate.cpp | 37 +++++++++++++++++++++++------------ sycl/src/program/generate.cpp | 37 +++++++++++++++++++++++------------ 2 files changed, 48 insertions(+), 26 deletions(-) diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 7a93c0a3..7dbb4226 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -9042,12 +9042,23 @@ int main(int argc, char** argv) { }; // stdin is read on its own thread, so a STOP line reaches a request that is still running (the client went // away, or pressed Esc): the flag is checked between prompt chunks and between verify windows. - std::atomic stop_req{false}; - std::mutex in_mu; - std::condition_variable in_cv; - std::deque in_lines; - bool in_eof = false; - std::thread([&] { + // 0.1.44: the reader is detached and may sit in read(2) past QUIT (the server writes more, or closes stdin, while + // main returns and the process exits), so what it touches is shared with it, never main's locals: a line or + // EOF after QUIT used to lock a destroyed mutex (undefined behaviour; an abort on macOS). + struct StdinShared { + std::atomic stop_req{false}; + std::mutex mu; + std::condition_variable cv; + std::deque lines; + bool eof = false; + }; + const auto in_shared = std::make_shared(); + std::atomic& stop_req = in_shared->stop_req; + std::mutex& in_mu = in_shared->mu; + std::condition_variable& in_cv = in_shared->cv; + std::deque& in_lines = in_shared->lines; + bool& in_eof = in_shared->eof; + std::thread([st = in_shared] { strata::aux_cpus::pin_current_thread(); // read(2) on the descriptor, not std::cin: glibc's exit() flushes every stdio stream and waits for // stdin's lock, which getline holds while it waits for input - an engine ending on an error (every @@ -9079,14 +9090,14 @@ int main(int argc, char** argv) { }; while (getline_fd(l)) { if (!l.empty() && l.back() == '\r') l.pop_back(); - if (l == "STOP") { stop_req.store(true); continue; } - std::lock_guard lk(in_mu); - in_lines.push_back(l); - in_cv.notify_one(); + if (l == "STOP") { st->stop_req.store(true); continue; } + std::lock_guard lk(st->mu); + st->lines.push_back(l); + st->cv.notify_one(); } - std::lock_guard lk(in_mu); - in_eof = true; - in_cv.notify_one(); + std::lock_guard lk(st->mu); + st->eof = true; + st->cv.notify_one(); }).detach(); auto next_line = [&](std::string& out) -> bool { std::unique_lock lk(in_mu); diff --git a/sycl/src/program/generate.cpp b/sycl/src/program/generate.cpp index 5d6f5866..4d97cb30 100644 --- a/sycl/src/program/generate.cpp +++ b/sycl/src/program/generate.cpp @@ -8402,12 +8402,23 @@ int main(int argc, char **argv) try { }; // stdin is read on its own thread, so a STOP line reaches a request that is still running (the client went // away, or pressed Esc): the flag is checked between prompt chunks and between verify windows. - std::atomic stop_req{false}; - std::mutex in_mu; - std::condition_variable in_cv; - std::deque in_lines; - bool in_eof = false; - std::thread([&] { + // 0.1.44: the reader is detached and may sit in read(2) past QUIT (the server writes more, or closes stdin, while + // main returns and the process exits), so what it touches is shared with it, never main's locals: a line or + // EOF after QUIT used to lock a destroyed mutex (undefined behaviour; an abort on macOS). + struct StdinShared { + std::atomic stop_req{false}; + std::mutex mu; + std::condition_variable cv; + std::deque lines; + bool eof = false; + }; + const auto in_shared = std::make_shared(); + std::atomic& stop_req = in_shared->stop_req; + std::mutex& in_mu = in_shared->mu; + std::condition_variable& in_cv = in_shared->cv; + std::deque& in_lines = in_shared->lines; + bool& in_eof = in_shared->eof; + std::thread([st = in_shared] { // read(2) on the descriptor, not std::cin: glibc's exit() flushes every stdio stream and waits for // stdin's lock, which getline holds while it waits for input - an engine ending on an error (every // std::exit) would hang in exit() on Linux, and the server would wait for it forever @@ -8438,14 +8449,14 @@ int main(int argc, char **argv) try { }; while (getline_fd(l)) { if (!l.empty() && l.back() == '\r') l.pop_back(); - if (l == "STOP") { stop_req.store(true); continue; } - std::lock_guard lk(in_mu); - in_lines.push_back(l); - in_cv.notify_one(); + if (l == "STOP") { st->stop_req.store(true); continue; } + std::lock_guard lk(st->mu); + st->lines.push_back(l); + st->cv.notify_one(); } - std::lock_guard lk(in_mu); - in_eof = true; - in_cv.notify_one(); + std::lock_guard lk(st->mu); + st->eof = true; + st->cv.notify_one(); }).detach(); auto next_line = [&](std::string& out) -> bool { std::unique_lock lk(in_mu); From 277be72a7f65cabdab3f8af188ac0f58c63da6d9 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 13 Oct 2026 00:31:21 +0200 Subject: [PATCH 27/67] Foresight swap: an exchange holds the experts whose bytes it moves, so no slot is served with another expert's bytes (#2134) With STRATA_FS_SLOTS > 0 and the resident RAM mode's adaptive exchanges, a slot copy issued from an expert's RAM place (note_miss / the router look-ahead's predict) could land after an exchange rewrote that place with the outgoing expert's bytes; take() then served expert Y's bytes for expert X (FS_VERIFY: 19 BAD on clean v0.1.43, reported in #2134). commit_exchanges, commit_copies and commit_flip now hold every staged expert (in and out) in the swap space while their bytes move: its slot is dropped (never served again) and no copy of it is issued until the commit is done (commit_copies holds until commit_flip, so the asynchronous tier's half-done exchange is covered, and the rotation path too). Unlike the patch in the issue, a dropped slot is not handed out at once: it waits the same `depth` finished windows as any slot a window may still read, since a window planned before the exchange can be reading it. "N dropped by exchanges" joins the swap space's report. Foresight is opt-in; with STRATA_FS_SLOTS unset nothing here runs. Test: file_expert_source_test --rotation-gpu (both commit paths, the depth rule, the bytes after). Based on the analysis and patch in #2134. Co-authored-by: radoslawsz <49882412+radoslawsz@users.noreply.github.com> --- include/strata/core/expert_source.hpp | 6 ++ include/strata/core/foresight_swap.hpp | 9 +++ src/core/expert_source.cpp | 42 +++++++++++- src/program/generate.cpp | 9 ++- tests/core/file_expert_source_test.cpp | 95 ++++++++++++++++++++++++++ 5 files changed, 156 insertions(+), 5 deletions(-) diff --git a/include/strata/core/expert_source.hpp b/include/strata/core/expert_source.hpp index 5d16d997..9ea48175 100644 --- a/include/strata/core/expert_source.hpp +++ b/include/strata/core/expert_source.hpp @@ -625,6 +625,10 @@ public: /// (the caller's thread, between windows) points `out` there and drops the staging. Returns how many were applied. void commit_copies(); int64_t commit_flip(); + /// #2134: the Foresight swap space (STRATA_FS_SLOTS), null = none. Each commit above holds the staged experts in it + /// (ForesightSwap::hold: their slots are dropped and not refilled) while their bytes move, so no slot is served + /// with bytes copied from a place an exchange rewrote. + void set_foresight_swap(ForesightSwap* fs) { fs_swap_.store(fs, std::memory_order_release); } /// The compact copy's blob of `(layer, expert)`, or null; not counted as a read (any thread). const uint8_t* resident_blob(int64_t layer, int64_t expert) const; int64_t exchanges() const { return exchanges_; } @@ -871,6 +875,8 @@ private: std::vector override_; ///< staged exchanges: an evicted expert read from its exchange buffer struct Exchange { size_t in, out; int64_t q; uint64_t bytes; }; std::vector staged_; + std::atomic fs_swap_{nullptr}; ///< set_foresight_swap + void fs_hold_staged(bool hold); std::vector soft_in_; ///< soft_commit_exchanges: per `out` index, the `in` whose place it will take (SIZE_MAX: none) const uint8_t* xstage_dev_ = nullptr; ///< the exchange buffers' device alias (soft_commit_exchanges) uint8_t* xstage_ = nullptr; ///< exchange buffers, `xstage_cap_ x xstage_blob_` diff --git a/include/strata/core/foresight_swap.hpp b/include/strata/core/foresight_swap.hpp index 379f4079..93f4c675 100644 --- a/include/strata/core/foresight_swap.hpp +++ b/include/strata/core/foresight_swap.hpp @@ -64,6 +64,9 @@ struct ForesightSwap { uint64_t hits = 0, copies = 0, busy = 0, over_budget = 0, pending = 0, predicted = 0; // (under smu_) bool verify = false; ///< STRATA_FS_VERIFY=1: read every landed slot back and compare (slow, tests) uint64_t verify_ok = 0, verify_bad = 0; + uint64_t dropped = 0; ///< slots dropped because an exchange moved their expert's bytes (under smu_) + static constexpr int16_t kHeld = -2; ///< `where`: an exchange is moving this expert's bytes, no copy now (#2134) + static constexpr int32_t kDropped = -2; ///< Slot::expert: dropped by `hold`, reusable under the same depth rule /// Allocates the slots on each card and starts the filler. `card_of_layer[l]` indexes `devices` (CUDA ids). bool init(int slots_per_layer, int64_t layers, int64_t experts, const std::vector& card_of_layer, @@ -79,6 +82,12 @@ struct ForesightSwap { /// with note_miss (the same slots, budget and reuse rule); a prediction only ever moves bytes, the plan is still made /// by the host pool and the model's own router stays authoritative. void predict(ExpertSource* src, int64_t layer, int32_t expert); + /// #2134: the adaptive tier moves this expert's bytes in the RAM copy (an exchange, its two halves or a rotation), + /// so a copy issued from its old place may land holding another expert's bytes. Its slot is dropped (never served; + /// refilled only once `depth` windows finished, like any slot a window may still read; a copy in flight finishes + /// first) and no copy of it is issued until `unhold`, when its bytes sit at their new place. Any thread. + void hold(int64_t layer, int32_t expert); + void unhold(int64_t layer, int32_t expert); std::string report() const; private: diff --git a/src/core/expert_source.cpp b/src/core/expert_source.cpp index 1e3788d9..16b67702 100644 --- a/src/core/expert_source.cpp +++ b/src/core/expert_source.cpp @@ -3317,8 +3317,21 @@ bool FileExpertSource::soft_commit_exchanges() { return true; } +void FileExpertSource::fs_hold_staged(bool hold) { + ForesightSwap* fs = fs_swap_.load(std::memory_order_acquire); + if (fs == nullptr || n_expert_ <= 0) return; + for (const Exchange& x : staged_) + for (const size_t i : {x.in, x.out}) { + const int64_t layer = (int64_t) (i / (size_t) n_expert_); + const int32_t expert = (int32_t) (i % (size_t) n_expert_); + if (hold) fs->hold(layer, expert); + else fs->unhold(layer, expert); + } +} + int64_t FileExpertSource::commit_exchanges() { int64_t n = 0; + fs_hold_staged(true); // #2134: both experts' bytes move (in's place takes out's bytes, out leaves its buffer) for (const Exchange& x : staged_) if (!soft_in_.empty()) soft_in_[x.out] = SIZE_MAX; for (const Exchange& x : staged_) { @@ -3341,12 +3354,14 @@ int64_t FileExpertSource::commit_exchanges() { } override_[x.out] = nullptr; } + fs_hold_staged(false); staged_.clear(); exchanges_ += n; return n; } void FileExpertSource::commit_copies() { + fs_hold_staged(true); // #2134: held until commit_flip has pointed `out` at its new place if (exchange_storage_.active()) return; // STRATA_EXCHANGE_ROTATE: ownership moves in commit_flip, nothing to copy for (const Exchange& x : staged_) { const uint8_t* src = override_.empty() ? nullptr : override_[x.out]; @@ -3359,6 +3374,7 @@ void FileExpertSource::commit_copies() { int64_t FileExpertSource::commit_flip() { int64_t n = 0; + fs_hold_staged(true); // (already held by commit_copies; idempotent) for (const Exchange& x : staged_) { const uint8_t* src = override_[x.out]; if (exchange_storage_.active()) { // STRATA_EXCHANGE_ROTATE: the same ownership transfer as commit_exchanges @@ -3377,6 +3393,7 @@ int64_t FileExpertSource::commit_flip() { ++n; override_[x.out] = nullptr; } + fs_hold_staged(false); staged_.clear(); exchanges_ += n; return n; @@ -4873,6 +4890,26 @@ bool ForesightSwap::take(int64_t layer, int32_t expert, unsigned long long& ptr) return true; } +void ForesightSwap::hold(int64_t layer, int32_t expert) { + if (layer < 0 || layer >= n_layers || expert < 0 || expert >= n_expert) return; + std::lock_guard smu_lk(smu_); + const size_t key = (size_t) (layer * n_expert + expert); + const int s = where[key]; + where[key] = kHeld; + if (s < 0) return; + Slot& sl = slot[(size_t) (layer * slots + s)]; + sl.expert = kDropped; // `loading` and `last_ref` stay: a copy in flight and a window that read it are waited for + sl.ready = false; + ++dropped; +} + +void ForesightSwap::unhold(int64_t layer, int32_t expert) { + if (layer < 0 || layer >= n_layers || expert < 0 || expert >= n_expert) return; + std::lock_guard smu_lk(smu_); + int16_t& w = where[(size_t) (layer * n_expert + expert)]; + if (w == kHeld) w = -1; +} + void ForesightSwap::note_miss(ExpertSource* src, int64_t layer, int32_t expert) { std::lock_guard smu_lk(smu_); request_locked(src, layer, expert, false); @@ -4887,7 +4924,7 @@ void ForesightSwap::predict(ExpertSource* src, int64_t layer, int32_t expert) { void ForesightSwap::request_locked(ExpertSource* src, int64_t layer, int32_t expert, bool predicted_copy) { if (failed.load(std::memory_order_relaxed)) return; const size_t key = (size_t) (layer * n_expert + expert); - if (where[key] >= 0) return; // already on its way + if (where[key] != -1) return; // already on its way, or held by an exchange (#2134) const uint64_t now = completed.load(std::memory_order_acquire); if (admit > 1 && !predicted_copy) { if (now > miss_at[key] + 4) miss_cnt[key] = 0; @@ -4912,7 +4949,7 @@ void ForesightSwap::request_locked(ExpertSource* src, int64_t layer, int32_t exp sl.loading = false; sl.ready = true; } - if (sl.expert < 0) { best = s; break; } + if (sl.expert == -1) { best = s; break; } // never used (a dropped slot, kDropped, waits like a used one) if (sl.last_ref + (uint64_t) depth > now) continue; if (sl.last_ref < best_ref) { best_ref = sl.last_ref; best = s; } } @@ -4944,6 +4981,7 @@ std::string ForesightSwap::report() const { (unsigned long long) hits, (unsigned long long) copies, (unsigned long long) predicted, (unsigned long long) pending, (unsigned long long) busy, (unsigned long long) over_budget, verify ? "" : ""); std::string r = buf; + if (dropped > 0) r += ", " + std::to_string(dropped) + " dropped by exchanges"; if (verify) r += ", verified " + std::to_string(verify_ok) + " ok / " + std::to_string(verify_bad) + " BAD"; return r; } diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 7dbb4226..2cd885c9 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -8326,12 +8326,15 @@ int main(int argc, char** argv) { fs_swap.reset(strata::core::foresight_swap_from_env(g.n_layers, g.n_expert, card, devs)); drive.d.fs = fs_swap.get(); if (fs_swap && drive.d.lookahead != nullptr) lookahead.set_foresight(fs_swap.get()); + src.set_foresight_swap(fs_swap.get()); // #2134: the exchanges hold the experts whose bytes they move } - // the look-ahead thread must not touch the swap space once it is gone (declared after it: destroyed first) + // the look-ahead thread and the exchanges must not touch the swap space once it is gone (declared after it: + // destroyed first) struct FsDetach { strata::core::RouterLookahead* la; - ~FsDetach() { la->set_foresight(nullptr); } - } fs_detach{&lookahead}; + strata::core::FileExpertSource* src; + ~FsDetach() { la->set_foresight(nullptr); src->set_foresight_swap(nullptr); } + } fs_detach{&lookahead, &src}; drive.d.pcie_num = std::max(0, std::min(256, (int) (o.pcie_frac * 256.0 + 0.5))); const bool all_experts_resident = !host_res.empty() && std::all_of(host_res.begin(), host_res.end(), [](int32_t r) { return r >= 0; }); diff --git a/tests/core/file_expert_source_test.cpp b/tests/core/file_expert_source_test.cpp index d3b21369..51a4ee1e 100644 --- a/tests/core/file_expert_source_test.cpp +++ b/tests/core/file_expert_source_test.cpp @@ -1,4 +1,5 @@ #include "strata/core/expert_source.hpp" +#include "strata/core/foresight_swap.hpp" #include "strata/kernels/cpu/expert.hpp" #include "strata/kernels/cpu/expert_layout.hpp" @@ -26,6 +27,7 @@ #include #include #include +#include #include #include @@ -737,6 +739,97 @@ void test_rotating_source(bool rotate, bool pin) { require(!src.has_resident(0, 0) && !src.exchange_rotation(), "reopen retained residency"); } +// #2134: a Foresight slot copied from an expert's RAM place before an exchange rewrote that place is never served; the +// experts an exchange moves get no copy between commit_copies and commit_flip; and a dropped slot that a window may +// still read waits `depth` finished windows before it is refilled. +void test_foresight_exchange(bool two_phase) { + using namespace strata::core; + using namespace strata::kernels::cpu; +#if defined(_WIN32) + _putenv_s("STRATA_EXCHANGE_ROTATE", "0"); +#else + setenv("STRATA_EXCHANGE_ROTATE", "0", 1); +#endif + TempDirectory dir; + std::string err; + require(expert_layout_load(dir.path.string(), 1, 5, err), err); + const size_t bytes = (size_t) BLOB; + std::vector> truth(5, std::vector(bytes)); + { + std::ofstream out(dir.path / "experts.bin", std::ios::binary); + for (size_t e = 0; e < truth.size(); ++e) { + for (size_t i = 0; i < bytes; ++i) truth[e][i] = (uint8_t) ((i * 131u + e * 37u) ^ (i >> 8)); + out.write((const char*) truth[e].data(), (std::streamsize) bytes); + } + require((bool) out, "fixture write failed"); + } + FileExpertSource src; + ExpertCache cache; + require(src.open(dir.path.string(), 1, 5, err), err); + require(cache.open(2, 1, 5, BLOB, err), err); + for (int e : {2, 3}) { + const int slot = cache.admit(0, e); + require(slot >= 0 && cache.fill_slot_blocking(slot, truth[e].data(), err), err); + } + const std::vector> rank{{0,0},{0,1},{0,2},{0,3},{0,4}}; + require(src.pin_cache_complement(cache, err, true, {}, -1, 0, 2 * bytes, &rank), err); + require(src.reserve_exchanges(1, err), err); + require(src.pinned(0, 0), "expert 0 is not in the pinned RAM copy"); + int dev = 0; + cudaGetDevice(&dev); + ForesightSwap fs; + require(fs.init(1, 1, 5, {0}, {dev}, err), err); // one slot, depth 4 + fs.verify = true; + src.set_foresight_swap(&fs); + unsigned long long ptr = 0; + auto landed = [&](int32_t e) { + for (int i = 0; i < 5000; ++i) { + if (fs.take(0, e, ptr)) return true; + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } + return false; + }; + fs.note_miss(&src, 0, 0); // expert 0 -> the slot, from its RAM place + require(landed(0) && fs.verify_ok == 1, "the first copy did not land"); + // the adaptive tier swaps expert 0 into cache slot 0 and evicts expert 2 into the exchange buffer + uint8_t* eviction = src.exchange_buffer(0); + const uint8_t* prior = src.blob(0, 0); + require(cudaMemcpy(eviction, cache.device_slot(0), bytes, cudaMemcpyDeviceToHost) == cudaSuccess, "D2H eviction failed"); + require(src.stage_exchange(0, 0, 2, 0), "stage rejected"); + require(cache.fill_slot_blocking(0, prior, err), err); + if (two_phase) { + src.commit_copies(); // 0's place holds 2's bytes from here on + const uint64_t c0 = fs.copies; + fs.completed.fetch_add(8); + fs.note_miss(&src, 0, 2); + fs.predict(&src, 0, 0); + require(fs.copies == c0, "an expert was copied while its exchange was half done"); + require(!fs.take(0, 0, ptr), "a slot dropped by commit_copies was served"); + require(src.commit_flip() == 1, "flip count wrong"); + } else { + require(src.commit_exchanges() == 1, "commit count wrong"); + } + require(fs.dropped == 1, "the exchange did not drop the slot"); + require(!fs.take(0, 0, ptr), "a slot copied before the exchange was served"); + if (!two_phase) { // the slot was served at window 0: no refill before window 0 + depth + const uint64_t c0 = fs.copies, b0 = fs.busy; + fs.note_miss(&src, 0, 2); + require(fs.copies == c0 && fs.busy == b0 + 1, "a dropped slot was refilled while a window may still read it"); + fs.completed.fetch_add(4); + } + require(src.has_resident(0, 2) && !src.has_resident(0, 0), "residency wrong"); + fs.note_miss(&src, 0, 2); // expert 2, now at 0's old place + require(landed(2), "the copy after the exchange did not land"); + std::vector back(bytes); + require(cudaMemcpy(back.data(), (const void*) ptr, bytes, cudaMemcpyDeviceToHost) == cudaSuccess && back == truth[2], + "the slot does not hold expert 2's bytes"); + require(fs.verify_bad == 0 && fs.verify_ok == 2, "verify counted a bad slot"); + src.set_foresight_swap(nullptr); + std::cout << "foresight exchange (" << (two_phase ? "commit_copies + commit_flip" : "commit_exchanges") + << "): dropped " << fs.dropped << ", " << fs.report() << ": PASS\n"; + src.close(); +} + } // namespace int main(int argc, char** argv) { @@ -759,6 +852,8 @@ int main(int argc, char** argv) { test_rotating_source(false, true); test_rotating_source(true, true); test_rotating_source(true, false); + test_foresight_exchange(false); + test_foresight_exchange(true); } std::cout << "file_expert_source_test: PASS\n"; return 0; From 62185aab77ea5fc6d24641fd416e47dc63250ad9 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 13 Oct 2026 00:40:31 +0200 Subject: [PATCH 28/67] serve: a quoted , or is text too (#2026 follow-up) The three are USER_DEFINED (type 4) tokens like (ids 248058, 248066, 248070), so the tokenizer matched them inside a message's text as the real call / tool-result markers. They join TOOL_LITERAL_TAGS: inside a user, system or tool message (and the tool list) they are encoded as ordinary text; an assistant message replaying raw call text keeps its tokens, as for . One exception keeps the template's behaviour: a user message whose whole text is ... (a client that formats tool results itself) keeps that outer pair as the markers, since the template tells such a turn from a real question by exactly that pair (last_query_index); the text inside is still marked. Found by 47Hunter47 in #2026. Tests: serve/test_frontend.py QuotedToolCallCloser (every tag and role, the assistant replay, the outer pair as string or text parts). --- serve/frontend.py | 48 +++++++++++++++++++++++++++++++++- serve/test_frontend.py | 58 ++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 103 insertions(+), 3 deletions(-) diff --git a/serve/frontend.py b/serve/frontend.py index e8cc2335..c781dd57 100644 --- a/serve/frontend.py +++ b/serve/frontend.py @@ -245,7 +245,11 @@ VISION_TAGS = {"<|vision_start|>": "\U000F0E03", "<|image_pad|>": "\U000F0E04", # #2026: `` the same way. A user asking for the string verbatim handed the model the real end-of-call token # (type 4, matched everywhere); it copied that token into its answer and the reply came back empty. An assistant # message keeps its own: a client replaying the model's raw call text sends the tokens the model wrote. -TOOL_LITERAL_TAGS = {"": "\U000F0E07"} +# 0.1.44: ``, `` and `` are type 4 too (ids 248058, 248066, 248070), so a quoted +# one handed the model the real call / tool-result marker in the same way (found by 47Hunter47 in #2026). The template +# writes the tool-result markers around a tool message itself; only the text inside a message is marked. +TOOL_LITERAL_TAGS = {"": "\U000F0E07", "": "\U000F0E08", "": "\U000F0E09", + "": "\U000F0E0A"} LITERAL_TAGS = {**THINK_TAGS, **VISION_TAGS, **TOOL_LITERAL_TAGS} THINK_MARKS = {v: k for k, v in LITERAL_TAGS.items()} CONTROL_MARK0 = 0xF0E10 # the control tokens' marks start here, clear of the two sets above @@ -287,6 +291,44 @@ def _has_tag(v, tags: dict[str, str] = LITERAL_TAGS) -> bool: return False +_TOOL_RESULT_OPEN, _TOOL_RESULT_CLOSE = "", "" + + +def _keep_tool_result_wrap(content, tags: dict[str, str]): + """A user message whose whole text is ... (a client that formats a tool result the way + the template does for a tool message) keeps that outer pair as the markers - the template tells such a turn from a + real question by exactly that pair - and only the text inside is marked. None: not such a message.""" + o, c = _TOOL_RESULT_OPEN, _TOOL_RESULT_CLOSE + + def wrap(text: str, first: bool, last: bool) -> str: + i = text.index(o) + len(o) if first else 0 + j = text.rindex(c) if last else len(text) + head = _mark(text[:i - len(o)], tags) + o if first else "" + tail = c + _mark(text[j + len(c):], tags) if last else "" + return head + _mark(text[i:j], tags) + tail + + if isinstance(content, str): + body = content.strip() + if len(body) >= len(o) + len(c) and body.startswith(o) and body.endswith(c): + return wrap(content, True, True) + return None + if not (isinstance(content, list) and content and all(isinstance(x, dict) and "text" in x for x in content)): + return None + texts = [x["text"] for x in content] + if not all(isinstance(t, str) for t in texts): + return None + body = "".join(texts).strip() + if not (len(body) >= len(o) + len(c) and body.startswith(o) and body.endswith(c)): + return None + if not (texts[0].lstrip().startswith(o) and texts[-1].rstrip().endswith(c)): + return None # the pair is split across parts: mark it all, as before + if len(content) == 1: + return [{**content[0], "text": wrap(texts[0], True, True)}] + return ([{**content[0], "text": wrap(texts[0], True, False)}] + + [_mark_deep(x, tags) for x in content[1:-1]] + + [{**content[-1], "text": wrap(texts[-1], False, True)}]) + + def mark_think_literals(messages: list[dict], tools: list[dict] | None, tags: dict[str, str] = LITERAL_TAGS): """#537: (messages, tools) with every literal / (#554: and vision marker) in their text swapped for LITERAL_TAGS' marks (or `tags`': literal_tags() adds the control tokens' texts), and @@ -304,6 +346,10 @@ def mark_think_literals(messages: list[dict], tools: list[dict] | None, tags: di for k, v in m.items(): if k != "role": m[k] = _mark_deep(v, mine) + if m.get("role") == "user": + kept = _keep_tool_result_wrap(content, tags) + if kept is not None: + m["content"] = kept if m.get("role") == "assistant" and isinstance(content, str) and content.lstrip().startswith("") \ and "" in content: i, j = content.index("") + len(""), content.index("") diff --git a/serve/test_frontend.py b/serve/test_frontend.py index f4fe3e68..5eb1a2e7 100644 --- a/serve/test_frontend.py +++ b/serve/test_frontend.py @@ -212,15 +212,69 @@ class QuotedToolCallCloser(unittest.TestCase): sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tools")) import strata_tokenizer as ST b2u = ST.bytes_to_unicode() - self.tok = ST.Tokenizer([b2u[b] for b in range(256)] + ["", "<|im_end|>"], [], [1] * 256 + [4, 3]) + self.tool_tags = ["", "", "", ""] + self.tok = ST.Tokenizer([b2u[b] for b in range(256)] + self.tool_tags + ["<|im_end|>"], [], + [1] * 256 + [4] * len(self.tool_tags) + [3]) self.tags = __import__("serve.frontend", fromlist=["literal_tags"]).literal_tags(self.tok.control_tokens) def encode(self, role, text): from serve.frontend import mark_think_literals, unmark_think_literals marked, _, changed = mark_think_literals([{"role": role, "content": text}], None, self.tags) - prompt, plain = unmark_think_literals(marked[0]["content"], self.tags) + content = marked[0]["content"] + if isinstance(content, list): + content = "".join(x["text"] for x in content) + prompt, plain = unmark_think_literals(content, self.tags) return self.tok.encode(prompt, parse_special=True, plain=plain), changed + def special(self, tag): + return self.tok.encode(tag, parse_special=True) + + def test_every_tool_tag_a_user_quotes_stays_text(self): + # 0.1.44: , and are type 4 like (47Hunter47, #2026) + for role in ("user", "system", "tool"): + for tag in self.tool_tags: + with self.subTest(role=role, tag=tag): + text = f"output verbatim: {tag}." + self.assertEqual(len(self.special(tag)), 1) + ids, changed = self.encode(role, text) + self.assertTrue(changed) + self.assertEqual(ids, [*text.encode()]) + + def test_assistant_replay_keeps_every_tool_tag(self): + text = "x then y" + ids, _ = self.encode("assistant", text) + self.assertEqual(ids, self.tok.encode(text, parse_special=True)) + + def test_user_tool_result_keeps_its_outer_markers(self): + # the template tells a tool result sent as a user turn from a question by this outer pair (last_query_index) + inner = "\nthe log says and \n" + for content in (f"{inner}", f" {inner}\n", + [{"type": "text", "text": f"{inner}"}], + [{"type": "text", "text": "\nthe log"}, + {"type": "text", "text": " says and \n"}]): + with self.subTest(content=content): + ids, _ = self.encode("user", content) + text = content if isinstance(content, str) else "".join(x["text"] for x in content) + o, c = self.special(""), self.special("") + lead = len(text) - len(text.lstrip()) + tail = len(text) - len(text.rstrip()) + self.assertEqual(ids[lead:lead + 1], o) + self.assertEqual(ids[len(ids) - tail - 1:len(ids) - tail], c) + middle = ids[lead + 1:len(ids) - tail - 1] + self.assertEqual(middle, [*inner.encode()]) # the quoted tags inside are text + + def test_template_keeps_seeing_a_tool_result_turn(self): + from serve.frontend import mark_think_literals + msgs = [{"role": "user", "content": "q"}, {"role": "assistant", "content": "a"}, + {"role": "user", "content": "\nok\n"}] + marked, _, changed = mark_think_literals(msgs, None, self.tags) + self.assertTrue(changed) + self.assertTrue(marked[2]["content"].startswith("")) + self.assertTrue(marked[2]["content"].endswith("")) + # a question that only mentions the pair is still marked through + marked, _, _ = mark_think_literals([{"role": "user", "content": "what is ?"}], None, self.tags) + self.assertNotIn("", marked[0]["content"]) + def test_user_text_stays_text(self): text = "output verbatim: ." ids, changed = self.encode("user", text) From 9c5a45f8794caf0d1016bde7aa17cd02b4832230 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 13 Oct 2026 00:44:27 +0200 Subject: [PATCH 29/67] SYCL layer split auto: among near-tied placements, the one that leaves its tightest card the most room (#1440) On two equal cards every K whose caches hold all the profiled pairs predicts the same window time, and the search kept the first one tried: the smallest K, which gives the last stage (it also carries the MTP drafter) the most layers and lets its cache fill the card to the reserve. 2x Arc Pro B70 with IQ3_S: auto K=24, CUDA1 at 31.8 of 31.9 GiB, ~11 tok/s; --layer-split 30 ~54 tok/s (agnaylor in #1440). A full xe card does not fail an allocation, it moves buffers to system memory. The SYCL search now scores every placement it tries with its smallest spare room (a stage's room after its session minus every expert of its layers) and, among the placements within STRATA_SPLIT_HEADROOM_TOL (default 0.2%) of the best predicted time, takes the one with the most (split_rules::pick_with_headroom). A log line names both picks when it moves the split. STRATA_SPLIT_HEADROOM=0 keeps the old pick. CUDA/HIP placement is unchanged. Test: split_rules_test (a 48-layer two-card model of the report: plain K=24 with 664 MiB spare on the last card, headroom K=25 with 1728 MiB; tolerance and tie rules). --- include/strata/program/split_rules.hpp | 54 ++++++++++++++++++++++++++ sycl/src/program/generate.cpp | 50 ++++++++++++++++++++++++ tests/program/split_rules_test.cpp | 46 ++++++++++++++++++++++ 3 files changed, 150 insertions(+) diff --git a/include/strata/program/split_rules.hpp b/include/strata/program/split_rules.hpp index b9382272..6cff00b9 100644 --- a/include/strata/program/split_rules.hpp +++ b/include/strata/program/split_rules.hpp @@ -35,4 +35,58 @@ inline bool has_tiny_stage(const std::vector& cuts, int64_t n_layers) { return smallest_stage(cuts, n_layers) < kMinStageLayers; } +// ---- #1440: headroom among (near-)ties. The search scores a placement by its predicted window time alone, so on two +// equal cards every K whose caches hold all the profiled pairs ties, and the first one tried wins: the smallest K, which +// gives the LAST stage (the one that also carries the MTP drafter) the most layers and lets its cache fill the card to +// the reserve. On Linux xe a card that runs out of VRAM does not fail an allocation, the driver moves buffers to system +// memory: 2x Arc Pro B70, IQ3_S, auto picked K=24 with CUDA1 at 31.8 of 31.9 GiB and decoded ~11 tok/s, against ~54 with +// --layer-split 30. So among the placements within `tol` of the best predicted time, the one whose tightest stage +// keeps the most VRAM beyond all of its layers' experts wins (ties on that: the faster, then the first). + +/// One scored placement: its cuts, its predicted window time and the smallest spare room over its stages (bytes; a +/// stage's room after its session minus every expert of its layers; negative when its cache cannot hold them all). +struct Placement { + std::vector cuts; + double ms = 0.0; + int64_t min_spare = 0; +}; + +/// The index of the plain pick (the first with the lowest time) in `c`, or 0 when `c` is empty. +inline size_t fastest(const std::vector& c) { + size_t best = 0; + for (size_t i = 1; i < c.size(); ++i) + if (c[i].ms < c[best].ms) best = i; + return best; +} + +/// The index of the pick with headroom: of the placements within `tol` (a fraction) of the fastest, the one with the +/// largest `min_spare`. tol <= 0 still breaks exact ties. 0 when `c` is empty. +inline size_t pick_with_headroom(const std::vector& c, double tol) { + if (c.empty()) return 0; + const size_t best = fastest(c); + const double limit = c[best].ms + c[best].ms * (tol > 0.0 ? tol : 0.0); + size_t pick = best; + for (size_t i = 0; i < c.size(); ++i) { + if (c[i].ms > limit) continue; + if (c[i].min_spare > c[pick].min_spare || (c[i].min_spare == c[pick].min_spare && c[i].ms < c[pick].ms)) + pick = i; + } + return pick; +} + +/// The smallest spare room over the stages of `cuts`: room[i] - session(lb, le) - need(lb, le), where `need_prefix[l]` +/// is the bytes of every expert of layers [0, l) (n_layers + 1 entries). +template +inline int64_t min_spare(const std::vector& cuts, int64_t n_layers, const std::vector& room, + const std::vector& need_prefix, Session&& session) { + int64_t lo = INT64_MAX; + for (size_t i = 0; i <= cuts.size(); ++i) { + const int64_t lb = i == 0 ? 0 : cuts[i - 1]; + const int64_t le = i < cuts.size() ? cuts[i] : n_layers; + const int64_t spare = room[i] - session(lb, le) - (need_prefix[(size_t) le] - need_prefix[(size_t) lb]); + if (spare < lo) lo = spare; + } + return lo; +} + } // namespace strata::program::split_rules diff --git a/sycl/src/program/generate.cpp b/sycl/src/program/generate.cpp index 4d97cb30..666a35c4 100644 --- a/sycl/src/program/generate.cpp +++ b/sycl/src/program/generate.cpp @@ -65,6 +65,7 @@ namespace strata::prefill { void set_nonresident_share(double share); } // SYC #include "strata/kernels/native_rope.hpp" #include "strata/kernels/mrope.hpp" #include "strata/kernels/kv_q4.hpp" +#include "strata/program/split_rules.hpp" #include "strata/kernels/qsa.hpp" #include "strata/core/native_head.hpp" #include "strata/core/verify.hpp" @@ -3641,11 +3642,38 @@ int main(int argc, char **argv) try { std::vector best, at((size_t) ns - 1); double best_ms = 1e30, best_mass = 0; int64_t best_held = 0, tried = 0; + // #1440: of the placements within STRATA_SPLIT_HEADROOM_TOL (default 0.2%) of the best predicted time, the one + // whose tightest card keeps the most VRAM beyond all its layers' experts (split_rules::pick_with_headroom). + // On by default here (a full xe card moves buffers to system memory instead of failing); STRATA_SPLIT_HEADROOM=0 + // keeps the first best, as before. + static const bool split_headroom = [] { + const char* v = std::getenv("STRATA_SPLIT_HEADROOM"); + return v == nullptr || std::atoi(v) != 0; + }(); + const double headroom_tol = + std::getenv("STRATA_SPLIT_HEADROOM_TOL") ? std::atof(std::getenv("STRATA_SPLIT_HEADROOM_TOL")) : 0.002; + std::vector need_prefix((size_t) g.n_layers + 1, 0); + for (int64_t l = 0; l < g.n_layers; ++l) + need_prefix[(size_t) l + 1] = need_prefix[(size_t) l] + (int64_t) g.n_expert * cost(l); + auto range_session = [&](int64_t lb, int64_t le) -> int64_t { + return (int64_t) strata::core::session_bytes(g, o.max_context, K, lb, le); + }; + std::vector scored; + std::vector scored_mass; + std::vector scored_held; + auto score = [&](const std::vector& cuts, double ms, double hm, int64_t held) { + if (!split_headroom) return; + scored.push_back({cuts, ms, strata::program::split_rules::min_spare(cuts, g.n_layers, cap, need_prefix, + range_session)}); + scored_mass.push_back(hm); + scored_held.push_back(held); + }; auto consider = [&]() { double hm = 0; int64_t held = 0; const double ms = predict(at, hm, held); ++tried; + score(at, ms, hm, held); if (ms < best_ms) { best = at; best_ms = ms; best_mass = hm; best_held = held; } }; const int64_t L = g.n_layers; @@ -3722,6 +3750,7 @@ int main(int argc, char **argv) try { (double) k1 * layer_ms[0] + (double) (k2 - k1) * layer_ms[1] + (double) (k3 - k2) * layer_ms[2] + (double) (L - k3) * layer_ms[3]; ++tried; + score({k1, k2, k3}, ms, hm / denom, held_at[a] + held_at[b] + held_at[c] + held_at[d]); if (ms < best_ms) { best = {k1, k2, k3}; best_ms = ms; @@ -3737,6 +3766,27 @@ int main(int argc, char **argv) try { // 163,185 at five). Nothing on this rig reaches it. proportional(); } + if (split_headroom && scored.size() > 1) { + const size_t first = strata::program::split_rules::fastest(scored); + const size_t pick = strata::program::split_rules::pick_with_headroom(scored, headroom_tol); + if (pick != first && scored[first].cuts == best) { + auto fmt_k = [](const std::vector& v) { + std::string s; + for (const int64_t k : v) s += (s.empty() ? "" : ",") + std::to_string(k); + return s; + }; + std::fprintf(stderr, "strata generate: layer split auto: K=%s instead of K=%s (predicted %.1f vs %.1f ms): its " + "tightest card keeps %.2f GiB beyond all its layers' experts, against %.2f GiB " + "(#1440: a full card can page to system memory); STRATA_SPLIT_HEADROOM=0 keeps K=%s\n", + fmt_k(scored[pick].cuts).c_str(), fmt_k(best).c_str(), scored[pick].ms, best_ms, + (double) scored[pick].min_spare / 1073741824.0, + (double) scored[first].min_spare / 1073741824.0, fmt_k(best).c_str()); + best = scored[pick].cuts; + best_ms = scored[pick].ms; + best_mass = scored_mass[pick]; + best_held = scored_held[pick]; + } + } split_at = best; std::string ks; for (const int64_t k : split_at) ks += (ks.empty() ? "" : ",") + std::to_string(k); diff --git a/tests/program/split_rules_test.cpp b/tests/program/split_rules_test.cpp index 4c3140a2..beef1255 100644 --- a/tests/program/split_rules_test.cpp +++ b/tests/program/split_rules_test.cpp @@ -29,6 +29,52 @@ int main() { CHECK(restriction_possible(12, 4)); CHECK(!restriction_possible(11, 4)); CHECK(!restriction_possible(48, 1)); + + // #1440: two equal cards, 48 layers x 512 experts of ~2 MiB (IQ3_S-like). Card 0 has more room than card 1 (the + // last stage also carries the drafter). Every K whose two caches hold all their pairs predicts the same time. + { + const int64_t L = 48, E = 512, blob = 2 << 20, MiB = 1 << 20; + const std::vector room{29000 * MiB, 26200 * MiB}; + std::vector need(L + 1, 0); + for (int64_t l = 0; l < L; ++l) need[(size_t) l + 1] = need[(size_t) l] + E * blob; + auto session = [&](int64_t lb, int64_t le) { return (le - lb) * 40 * MiB; }; + std::vector c; + for (int64_t k = 2; k < L; ++k) { + Placement p; + p.cuts = {k}; + p.min_spare = min_spare(p.cuts, L, room, need, session); + // the miss term: the pairs a stage's cache cannot hold (each costs the same here) + double missing = 0; + for (int i = 0; i < 2; ++i) { + const int64_t lb = i == 0 ? 0 : k, le = i == 0 ? k : L; + const int64_t fit = (room[(size_t) i] - session(lb, le)) / blob; + const int64_t want = (le - lb) * E; + if (fit < want) missing += (double) (want - (fit > 0 ? fit : 0)); + } + p.ms = 48 * 0.5 + 190.0 * missing / (double) (L * E); + c.push_back(p); + } + const size_t plain = fastest(c), head = pick_with_headroom(c, 0.002); + // the plain pick is the first full placement, and it leaves card 1 (almost) nothing + CHECK(c[plain].ms == c[head].ms); + CHECK(c[plain].cuts[0] < c[head].cuts[0]); + CHECK(c[plain].min_spare < 1024 * MiB); + CHECK(c[head].min_spare > 1536 * MiB); + // the pick is the most balanced full placement: no other full one keeps more on its tightest card + for (const Placement& p : c) + if (p.ms == c[plain].ms) CHECK(p.min_spare <= c[head].min_spare); + std::printf("split_rules_test: #1440 plain K=%lld (spare %lld MiB), headroom K=%lld (spare %lld MiB)\n", + (long long) c[plain].cuts[0], (long long) (c[plain].min_spare / MiB), (long long) c[head].cuts[0], + (long long) (c[head].min_spare / MiB)); + // a slower placement is never taken for its headroom beyond the tolerance + std::vector two{{{10}, 100.0, 0}, {{20}, 101.0, 5000 * MiB}}; + CHECK(pick_with_headroom(two, 0.002) == 0); + CHECK(pick_with_headroom(two, 0.02) == 1); + // exact ties with equal spare keep the first (the old pick) + std::vector same{{{10}, 100.0, 7}, {{20}, 100.0, 7}}; + CHECK(pick_with_headroom(same, 0.0) == 0); + CHECK(pick_with_headroom({}, 0.1) == 0); + } if (failed == 0) std::printf("split_rules_test: ok\n"); return failed ? 1 : 0; } From ac21812c1a620b868102642e681aed99b2efd960 Mon Sep 17 00:00:00 2001 From: SuperDistance <43229543+SuperDistance@users.noreply.github.com> Date: Mon, 12 Oct 2026 07:16:13 -0700 Subject: [PATCH 30/67] serve: a long read gives way to a short request at the next chunk, not a chunk later or never (#656) The server sends BYIELD for a waiting request under half as long only when a PP line (or the 10 s heartbeat) arrives, and the engine looks for it at its next boundary. Where a boundary's own PP line is the only line for a while - every chunk of a --batch read on one GPU, and #2050's pipelined pieces - the BYIELD answers that line and reaches the engine after it has looked: the read gives way one boundary later, or never when that was the last one it could take. It is in time only where the engine saves a periodic checkpoint after the PP line (every 16,384 tokens by default). _control() now also calls on_quiet() whenever the engine has been quiet for half a second (its existing poll), and the solo and admission reads run the same check there as at a PP line. A BYIELD for a read that has ended is ignored by the engine, as before. serve/test_parallel.py: the fake engine takes --pp-every K (a PP line and a boundary every K chunks); a solo read and an admission must give way at their first boundary (both fail on main), and the rule (only to a much shorter request) holds on the poll too. Measured on one RTX 5090 (Swift 1.5 IQ3_S, --batch 4, the engine built from main), main's server and this one, two engine starts each (M F F M): a one-line request sent 0.2-8.6 s into a cold ~33K read, with nothing else decoding and with one stream decoding. Late (a boundary passed after the request waited): 28 of 40 runs on main, 12 of which never gave way; 4 of 40 with this change, all requests that started waiting 0.02-0.10 s before that boundary's PP line. Where main was late the short request's TTFT went 3.56 -> 1.70 s (nothing decoding) and 4.40 -> 1.57 s (one stream); where main never gave way 4.60 -> 1.51 s and 7.59 -> 2.35 s. Where both gave way at the same boundary, both requests' TTFTs were the same (medians within 0.02 s). On 2x RTX 5090 with #2050's STRATA_PIPED_READ_PIECE=8192: 6 of 12 late without it, none with it. --- serve/server.py | 45 ++++++++++++++++++++++++++---------------- serve/test_parallel.py | 42 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 70 insertions(+), 17 deletions(-) diff --git a/serve/server.py b/serve/server.py index ff1b935c..34269e42 100644 --- a/serve/server.py +++ b/serve/server.py @@ -1064,10 +1064,11 @@ class StrataEngine: except (OSError, AttributeError): # the pipe is gone (or a restart's close() took the process): raise EngineDied(f"the engine stopped unexpectedly (exit code {self.exit_code()})") from None - def _control(self, cancel, on_token, stop_when=None): + def _control(self, cancel, on_token, stop_when=None, on_quiet=None): """Reads the control lines of the request on them (GEN / BGEN), yielding None heartbeats. Calls on_token(id) for each `T`; returns ("done", None) at DONE, or ("badm", continues) at BADM (after DONE). `stop_when()` - true sends STOP once (the request is then read to its DONE).""" + true sends STOP once (the request is then read to its DONE). `on_quiet()` runs whenever the engine has been + quiet for half a second: between two PP lines of a read whose chunks take longer than that.""" stopped = False beat = time.monotonic() while True: @@ -1079,6 +1080,8 @@ class StrataEngine: if cancel.is_set() and not stopped: self._send("STOP") stopped = True + if on_quiet is not None: + on_quiet() if time.monotonic() - beat >= 10.0: beat = time.monotonic() yield None @@ -1370,21 +1373,25 @@ class StrataEngine: def others(): with self.slot_cv: return self.waiting > 0 - for x in self._control(cancel, pending.append, stop_when=others): + + def give_way(): # at a PP line, and between two far apart (the engine takes it at its next boundary) + nonlocal reserved + if (reserved is None and not out and not embeddings and yields < self.YIELDS_MAX and + self._shorter_waiting(len(prompt))): + with self.slot_cv: # the slot the part read will wait in + reserved = self.pick_slot(prompt) + if reserved is not None: + self.slot_busy[reserved] = True + self.slot_claims.add(reserved) + if reserved is not None: + self._send(f"BYIELD {reserved}") + for x in self._control(cancel, pending.append, stop_when=others, on_quiet=give_way): while pending: t = pending.pop(0) out.append(t) yield t if x is None: # a heartbeat (False: a token, flushed above) - if (reserved is None and not out and not embeddings and yields < self.YIELDS_MAX and - self._shorter_waiting(len(prompt))): - with self.slot_cv: # the slot the part read will wait in - reserved = self.pick_slot(prompt) - if reserved is not None: - self.slot_busy[reserved] = True - self.slot_claims.add(reserved) - if reserved is not None: - self._send(f"BYIELD {reserved}") + give_way() yield None phase = "none" # its DONE is read while pending: @@ -1480,17 +1487,21 @@ class StrataEngine: self._ctl_mode, self._ctl_result, self._yielded = "batch", None, None self._ctl_erred = False asked = False + + def ask(): # as give_way above, for the slot this admission reads into + nonlocal asked + if (not asked and not embeddings and yields < self.YIELDS_MAX and + self._shorter_waiting(len(prompt))): + self._send(f"BYIELD {slot}") + asked = True try: - for x in self._control(cancel, pending.append): + for x in self._control(cancel, pending.append, on_quiet=ask): while pending: t = pending.pop(0) out.append(t) yield t if x is None: - if (not asked and not embeddings and yields < self.YIELDS_MAX and - self._shorter_waiting(len(prompt))): - self._send(f"BYIELD {slot}") - asked = True + ask() yield None except ValueError as e: # #1994: the engine says this slot is not free (its view and ours differ for a moment, or a diff --git a/serve/test_parallel.py b/serve/test_parallel.py index fbc8fb1c..1a638919 100644 --- a/serve/test_parallel.py +++ b/serve/test_parallel.py @@ -78,6 +78,7 @@ def window(): # one batch window: every active slot one token else: active[b] = [left, max_new, produced] log = open(args[args.index("--log") + 1], "a") if "--log" in args else None +PPK = int(args[args.index("--pp-every") + 1]) if "--pp-every" in args else 1 READF = "--readfield" in args # DONE's 15th field: the prompt tokens the engine read (a continued prompt: the 1 it copies) REUSE = "--reuse" in args # DONE's reused field as the engine gives it: a continued prompt is all held but its last def reused(ids): # token (the request's own output included), a fresh one the first 3 tokens @@ -131,6 +132,8 @@ while True: given = None for q in range(CH, len(ids) - 1, CH): time.sleep(STEP / 2) + if (q // CH) % PPK: # --pp-every K: a PP line and a boundary every K chunks (the pipelined groups' pieces) + continue print(f"PP {q} {len(ids)} 1 1", flush=True) held = [] while True: @@ -497,6 +500,19 @@ class ParallelService(unittest.TestCase): self.assertEqual(len(self.svc.history), 2) self.assertFalse(any(self.engine.slot_busy)) + def test_the_way_is_asked_between_far_apart_progress_lines(self): + """#656 when the PP lines come far apart (the pipelined groups' read in pieces of one chunk: one PP per piece, + at its end): the BYIELD goes out while the engine is quiet, so the read gives way at the first boundary after + the short request came. Asked only at a PP line, it reached the engine after that boundary's check and the + read gave way one piece later.""" + self.start(2, more=["--pp-every", "80"]) # a boundary every 80 chunks (~0.8 s): one in this read + long_q, short_q = "long " * 600, "short" + res = self.race(long_q, short_q) + self.assertEqual(res[long_q][0], "ok, done.") + self.assertEqual(res[short_q][0], "ok, done.") + yields = [x for x in self.log.read_text().splitlines() if x.startswith("YIELD ")] + self.assertEqual([int(x.split()[2]) for x in yields], [80 * 32], yields) + def test_three_requests_long_long_short_do_not_deadlock(self): """ENGINE_REVIEW finding 1 (0.1.41 check): two long prompts fill both slots, a short one arrives a moment later and wants one of them (the yield path). The reviewer's repro: long, long, short at 0.25 s steps. Every @@ -542,6 +558,25 @@ class ParallelService(unittest.TestCase): self.assertTrue(any(x.startswith("YIELD ") for x in log), log) self.assertFalse(any(self.engine.slot_busy)) + def test_an_admission_is_asked_between_far_apart_progress_lines(self): + """As above for a read admitted beside a decoding slot (BGEN, `ask()`): with one PP line per 80 chunks the + short request's BYIELD still reaches the first boundary.""" + self.start(3, more=["--pp-every", "80"]) + bg = threading.Thread(target=lambda: self.chat("LONGREPLY background", max_tokens=60)) + bg.start() + time.sleep(0.05) + long_q, short_q = "long " * 600, "short" + res = self.race(long_q, short_q) + bg.join(30) + self.assertEqual(res[long_q][0], "ok, done.") + self.assertEqual(res[short_q][0], "ok, done.") + log = self.log.read_text().splitlines() + admitted = [x.split() for x in log if x.startswith("BGEN ") and int(x.split()[2]) > 2600] + self.assertTrue(admitted, log) # the long read was an admission + yields = [x.split()[1:] for x in log if x.startswith("YIELD ")] + self.assertEqual(yields[:1], [[admitted[0][1], str(80 * 32)]], log) + self.assertFalse(any(self.engine.slot_busy)) + def test_no_way_given_to_a_long_one(self): """Two prompts of about the same length: no BYIELD (it only goes to a much shorter one).""" self.start(2) @@ -549,6 +584,13 @@ class ParallelService(unittest.TestCase): self.assertEqual(sorted(r[0] for r in res.values()), ["ok, done."] * 2) self.assertFalse(any(x.startswith("YIELD ") for x in self.log.read_text().splitlines())) + def test_no_way_given_to_a_long_one_between_far_apart_progress_lines(self): + """The ask between PP lines keeps the rule: a waiting request about as long gets no BYIELD there either.""" + self.start(2, more=["--pp-every", "80"]) + res = self.race("long " * 600, "lung " * 600) + self.assertEqual(sorted(r[0] for r in res.values()), ["ok, done."] * 2) + self.assertFalse(any(x.startswith("YIELD ") for x in self.log.read_text().splitlines())) + def test_left_alone_it_goes_back_to_the_solo_path(self): """A request decoding in a slot whose neighbour finished goes back to the solo path (MTP drafts), continued from its slot - only with an engine that keeps the slots' conversations (INFO slot_cache=1).""" From d8a49433e3ce71269146f3e663a4f91303cb6627 Mon Sep 17 00:00:00 2001 From: zsariboga Date: Tue, 13 Oct 2026 00:22:08 +0300 Subject: [PATCH 31/67] serve: "env_to_user" (opt-in) moves opencode's block into the first user message, so a new folder or day reuses the cached system prompt (11.9 -> 1.1 s first request) opencode puts its block (working directory, today's date) near the start of the system message, before ~40K characters that never change. The prefix cache only matches a prompt's start, so each new folder or day read the whole system turn again. With the switch the block goes to the front of the first user message (string or content parts), for OpenAI and Anthropic requests. Off by default; serve/test_env_to_user.py; docs/DETAILS.md. --- docs/DETAILS.md | 7 +++++ serve/frontend.py | 40 ++++++++++++++++++++++-- serve/server.py | 5 +++ serve/test_env_to_user.py | 66 +++++++++++++++++++++++++++++++++++++++ 4 files changed, 116 insertions(+), 2 deletions(-) create mode 100644 serve/test_env_to_user.py diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 61f27890..ac59d0c8 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -834,6 +834,13 @@ print(r.choices[0].message.content) second call's parameters merge into the first). Anything else in those forms stays the text it is. Measured on 1,462 agent turns (Qwen3.8 under Claude Code, from signalnine/q27's drift corpus): 98.3% read as intended with it, 92.9% without. Off by default, so what a client gets back is unchanged unless you turn it on. +- **opencode's environment block in the user turn (opt-in).** opencode writes an `` block (working directory, + today's date) near the start of its system message, ahead of ~40K characters of instructions and tool definitions that + are the same in every session. The prefix cache only reuses a prompt's start, so every new folder and every new day + read ~14K tokens again. `"env_to_user": true` moves that block to the front of the first user message: the system + turn is then the same for every session and the disk prefix cache restores it. Measured (RTX 5070 Ti Laptop, Swift 1.5 + IQ3_XXS, a new opencode session in a second folder): first request 14,073 tokens with 13,693 from the cache, 1.1 s, + against 14,753 read, 11.9 s, without it; the model still answered the folder and date correctly (3/3). Off by default. - **Prefill progress in the stream (opt-in).** `"return_progress": true` puts that progress on the stream instead of sending only the keep-alive, as one extra field on a chunk with an empty delta: `prompt_progress` with `total`, `cache`, `processed` and `time_ms`. Those are llama.cpp's four fields and mean the same there (`time_ms` is the time diff --git a/serve/frontend.py b/serve/frontend.py index c781dd57..9023e1b5 100644 --- a/serve/frontend.py +++ b/serve/frontend.py @@ -380,6 +380,42 @@ def unmark_think_literals(prompt: str, tags: dict[str, str] = LITERAL_TAGS) -> t return "".join(out), spans +# Config "env_to_user" (opt-in): opencode writes its block (working directory, today's date) near the START of +# the system message, before ~40K characters of instructions and tool definitions that are the same in every session. +# The prefix cache only reuses a prompt's start, so a new folder or a new day read all of it again (~14K tokens, 8-11 s). +# Moved to the front of the first user message, the system turn (and the tools the template writes into it) is the same +# for every session and the disk prefix cache restores it. The model still sees the same lines, one turn later. +ENV_TO_USER = False +_ENV_BLOCK = re.compile(r"(?:[^\n]*environment you are running in:\n)?\n.*?\n\n?", re.S) + + +def _env_to_user(messages: list[dict]) -> list[dict]: + if not ENV_TO_USER or not messages or messages[0].get("role") != "system": + return messages + sys_text = messages[0].get("content") + if not isinstance(sys_text, str): + return messages + m = _ENV_BLOCK.search(sys_text) + if m is None: + return messages + for i in range(1, len(messages)): + if messages[i].get("role") != "user": + continue + block = m.group(0).rstrip("\n") + c = messages[i].get("content") + if isinstance(c, str): + nc = block + "\n\n" + c + elif isinstance(c, list): + nc = [{"type": "text", "text": block + "\n\n"}] + c + else: + return messages + out = list(messages) + out[0] = dict(messages[0], content=sys_text[:m.start()] + sys_text[m.end():]) + out[i] = dict(messages[i], content=nc) + return out + return messages + + def _late_system_to_user(messages: list[dict]) -> list[dict]: """The chat template takes a system message only at the start ("System message must be at the beginning"). Clients also send them mid-conversation - Claude Code's hook context as {"role": "system"} after the first user @@ -517,7 +553,7 @@ def openai_to_messages(req: dict) -> tuple[list[dict], list[dict] | None, dict]: kwargs = {"enable_thinking": False} elif k == "reasoning_effort" and "enable_thinking" not in kwargs: kwargs.update(effort_kwargs(v)) - return _late_system_to_user(messages), tools, kwargs + return _env_to_user(_late_system_to_user(messages)), tools, kwargs BILLING_HEADER = "x-anthropic-billing-header:" @@ -613,7 +649,7 @@ def anthropic_to_messages(req: dict, think_unasked: bool = True) -> tuple[list[d # A config's reasoning_effort still applies: Service.with_shared sets output_config before this runs. A # request that gives its own reasoning_budget_tokens (#123) asks for thinking, so it thinks as before. kwargs["enable_thinking"] = False - return _late_system_to_user(messages), tools, kwargs + return _env_to_user(_late_system_to_user(messages)), tools, kwargs # ------------------------------------------------------------------------------------------------ output parser diff --git a/serve/server.py b/serve/server.py index 34269e42..20edde13 100644 --- a/serve/server.py +++ b/serve/server.py @@ -6533,6 +6533,11 @@ def main() -> int: if not isinstance(recovery, bool): raise SystemExit(f"[strata] config \"tool_call_recovery\" must be true or false, not {recovery!r}") svc.tool_call_recovery = recovery + etu = cfg.get("env_to_user", False) # opt-in: see frontend._env_to_user + if not isinstance(etu, bool): + raise SystemExit(f"[strata] config \"env_to_user\" must be true or false, not {etu!r}") + import serve.frontend as _frontend + _frontend.ENV_TO_USER = etu rs = cfg.get("repeat_stop_tokens", REPEAT_STOP_TOKENS) # #606: opt-out with 0 if isinstance(rs, bool) or not isinstance(rs, int) or rs < 0: raise SystemExit(f"[strata] config \"repeat_stop_tokens\" must be a whole number >= 0 (0 = off), not {rs!r}") diff --git a/serve/test_env_to_user.py b/serve/test_env_to_user.py new file mode 100644 index 00000000..270a1c46 --- /dev/null +++ b/serve/test_env_to_user.py @@ -0,0 +1,66 @@ +"""Config "env_to_user": opencode's block (working directory, date) leaves the system message for the first user +message, so the system turn is the same in every session and the prefix cache keeps it. Off (the default), nothing moves.""" +import sys +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +import serve.frontend as fe # noqa: E402 + +SYS = ("You are opencode.\n" + "Here is some useful information about the environment you are running in:\n" + "\n" + " Working directory: C:/a\n" + " Today's date: Mon Oct 12 2026\n" + "\n" + "Instructions that never change.") + + +class EnvBlockToUser(unittest.TestCase): + def setUp(self): + self.addCleanup(setattr, fe, "ENV_TO_USER", fe.ENV_TO_USER) + + def convert(self, on, system=SYS, user="hi"): + fe.ENV_TO_USER = on + msgs, _, _ = fe.openai_to_messages({"messages": [{"role": "system", "content": system}, + {"role": "user", "content": user}]}) + return msgs + + def test_moved_to_the_first_user_message(self): + msgs = self.convert(True) + self.assertEqual(msgs[0]["content"], "You are opencode.\nInstructions that never change.") + self.assertTrue(msgs[1]["content"].startswith( + "Here is some useful information about the environment you are running in:\n\n Working directory: C:/a")) + self.assertTrue(msgs[1]["content"].endswith("\n\nhi")) + + def test_two_folders_share_the_system_turn(self): + a = self.convert(True)[0]["content"] + b = self.convert(True, system=SYS.replace("C:/a", "D:/b"))[0]["content"] + self.assertEqual(a, b) + + def test_content_parts_get_a_leading_text_part(self): + fe.ENV_TO_USER = True + out = fe._env_to_user([{"role": "system", "content": SYS}, + {"role": "user", "content": [{"type": "image", "image": "x.png"}, {"type": "text", "text": "hi"}]}]) + self.assertEqual(out[1]["content"][0]["type"], "text") + self.assertIn("", out[1]["content"][0]["text"]) + self.assertEqual(out[1]["content"][1:], [{"type": "image", "image": "x.png"}, {"type": "text", "text": "hi"}]) + + def test_text_parts_are_read_as_one_text(self): + msgs = self.convert(True, user=[{"type": "text", "text": "hi"}]) + self.assertIn("", msgs[1]["content"] if isinstance(msgs[1]["content"], str) else msgs[1]["content"][0]["text"]) + + def test_anthropic_requests_too(self): + fe.ENV_TO_USER = True + msgs, _, _ = fe.anthropic_to_messages({"system": SYS, "messages": [{"role": "user", "content": "hi"}]}) + self.assertNotIn("", msgs[0]["content"]) + self.assertIn("", msgs[1]["content"]) + + def test_off_and_no_block_change_nothing(self): + self.assertEqual(self.convert(False)[0]["content"], SYS) + self.assertEqual(self.convert(True, system="Plain system prompt.")[0]["content"], "Plain system prompt.") + + +if __name__ == "__main__": + unittest.main() From fb7ee724718c4b8aa394027a53eb52ecb43554da Mon Sep 17 00:00:00 2001 From: Gabriel Popa Date: Mon, 12 Oct 2026 17:34:51 -0400 Subject: [PATCH 32/67] setup: install the CUDA Toolkit on Debian 12/13 too, not Ubuntu only The CUDA apt repo keyring and cuda-toolkit-13-x packages exist for debian12/debian13 as well as ubuntu2204/ubuntu2404, so derive the repo name from /etc/os-release instead of hardcoding ubuntu. Debian 13's repo carries no cuda-toolkit-13-0, so try 13-0..13-5 in order (Ubuntu still gets 13-0 first, same as before). Checked with tools/test_setup_cuda_repo.py (4 tests, no GPU or network needed): repo mapping for ubuntu/debian/other and the minor-version fallback. --- docs/AI_SETUP.md | 2 +- docs/DETAILS.md | 2 +- docs/INSTALL.md | 2 +- setup.py | 21 ++++++--- tools/test_setup_cuda_repo.py | 85 +++++++++++++++++++++++++++++++++++ 5 files changed, 104 insertions(+), 8 deletions(-) create mode 100644 tools/test_setup_cuda_repo.py diff --git a/docs/AI_SETUP.md b/docs/AI_SETUP.md index 43325358..236d7fb5 100644 --- a/docs/AI_SETUP.md +++ b/docs/AI_SETUP.md @@ -50,7 +50,7 @@ Requirements (details: [INSTALL.md](INSTALL.md#what-you-need)): driver. If the driver is missing or too old, tell the user to update it (NVIDIA App / nvidia.com/drivers, or AMD Software) and restart; do not install drivers yourself unless they ask. - **RAM:** 32 GB or more (see step 3). **Disk:** ~80 GB free, ideally on an NVMe SSD. **CPU:** x86-64 with AVX2. Without AVX2 (Xeon E5 v1/v2 and older) setup still installs, as an experimental and slow build it compiles on the PC (10-20 minutes): tell the user that before starting ([INSTALL.md](INSTALL.md#older-cpus-experimental)). -- **OS:** Windows 10/11 or Linux (Ubuntu 22.04/24.04 are fully automatic). +- **OS:** Windows 10/11 or Linux (Ubuntu 22.04/24.04 and Debian 12/13 are fully automatic; Debian 13 gets the oldest CUDA 13 its NVIDIA repo has, currently 13.1). If the PC does not meet them, say which part is missing and stop. diff --git a/docs/DETAILS.md b/docs/DETAILS.md index ac59d0c8..998d661e 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -418,7 +418,7 @@ Everything else is installed for you the first time. | RAM | **64 GB** recommended (see the table above). | | CPU | x86-64 with AVX2 (any Intel/AMD desktop CPU from the last ~8 years). AVX-512 (Ryzen 7000/9000) is a bit faster. Older CPUs without AVX2 are experimental and slow: [Older CPUs](INSTALL.md#older-cpus-experimental). | | Disk | ~70-80 GB free for the model, ~6 GB for the MTP layer (+1 GB with images). **Q2_0 on an AVX-512 CPU** also writes a one-time ~40 GB pack for the fast CPU kernel (34 GB of experts in its layout, plus the dense weights). An NVMe SSD is strongly recommended. | -| OS | Windows 10/11, or Linux (Ubuntu 22.04/24.04 get everything installed automatically). | +| OS | Windows 10/11, or Linux (Ubuntu 22.04/24.04 and Debian 12/13 get everything installed automatically). | What the first start installs: in this folder `.venv/`, `engine/` and `third_party/`; the model files (`models/`, `packs/`, `mtp/`, 70-120 GB) in **`Strata-data` next to this folder**, so a new copy of Strata (an update unzipped diff --git a/docs/INSTALL.md b/docs/INSTALL.md index 11f0e0fd..b148e23a 100644 --- a/docs/INSTALL.md +++ b/docs/INSTALL.md @@ -17,7 +17,7 @@ this for you with [AI_SETUP.md](AI_SETUP.md). | **RAM** | Enough for the size you pick ([which model](MODELS.md#pick-by-ram)); **64 GB** runs every size. A big GPU makes up for less RAM - the [low-RAM mode](MODELS.md#a-big-graphics-card-and-little-ram). | | **CPU** | x86-64 with AVX2 (any Intel/AMD desktop CPU from the last ~8 years). AVX-512 (Ryzen 7000/9000) is a bit faster. Older CPUs without AVX2 are experimental and slow: [Older CPUs](#older-cpus-experimental). | | **Disk** | ~70-80 GB free for the model, ~6 GB for the MTP layer (+1 GB with images). **Q2_0 on an AVX-512 CPU** also writes a one-time ~40 GB copy of its experts for the fast CPU kernel. On Linux with an AMD card, ROCm takes ~10 GB more when setup installs it. An NVMe SSD is strongly recommended: it makes the first start much faster. | -| **OS** | Windows 10/11, or Linux (Ubuntu 22.04/24.04 get everything installed automatically). | +| **OS** | Windows 10/11, or Linux (Ubuntu 22.04/24.04 and Debian 12/13 get everything installed automatically). | | **Driver** | **NVIDIA:** a current driver, version 580 or newer ([nvidia.com/drivers](https://www.nvidia.com/drivers) or the NVIDIA App). **AMD:** on Linux the kernel's amdgpu driver (no ROCm install needed); on Windows a current AMD Software: Adrenalin Edition driver ([amd.com/support](https://www.amd.com/en/support)). | The driver is the only thing you install yourself. Everything else - Python, the engine, the model - is set up for diff --git a/setup.py b/setup.py index 7d291e1c..3a3bc2de 100644 --- a/setup.py +++ b/setup.py @@ -3212,6 +3212,14 @@ def sm120_nvcc(nvcc, cuda_v, archs): return nvcc, cuda_v +def cuda_apt_repo(osr): + """The NVIDIA apt repo for this distribution ("ubuntu2404", "debian13") from /etc/os-release, or None when it is + not one setup adds the CUDA keyring for. Both families publish cuda-keyring and CUDA 13.x.""" + ver = osr.get("VERSION_ID", "").strip('"').replace(".", "") + repo = {"ubuntu": "ubuntu", "debian": "debian"}.get(osr.get("ID", ""), "") + ver + return repo if repo in ("ubuntu2204", "ubuntu2404", "debian12", "debian13") else None + + def install_build_tools(gpu, yes): """The compiler and the CUDA toolkit, installed for the user (asks once). Returns (nvcc, vcvars).""" archs = [int(x) for x in gpu.get("archs", [gpu["arch"]])] @@ -3270,16 +3278,19 @@ def install_build_tools(gpu, yes): run(["sudo", "apt-get", "install", "-y", "build-essential"]) if nvcc is None or cuda_v < need_cuda: osr = dict(line.split("=", 1) for line in open("/etc/os-release").read().splitlines() if "=" in line) - ver = osr.get("VERSION_ID", "").strip('"').replace(".", "") - if osr.get("ID") != "ubuntu" or ver not in ("2204", "2404"): - fail("the CUDA Toolkit can be installed automatically on Ubuntu 22.04 / 24.04 only", + repo = cuda_apt_repo(osr) + if repo is None: + fail("the CUDA Toolkit can be installed automatically on Ubuntu 22.04 / 24.04 and Debian 12 / 13 only", "install it from https://developer.nvidia.com/cuda-downloads and run it again") deb = Path("/tmp/cuda-keyring.deb") - download(f"https://developer.download.nvidia.com/compute/cuda/repos/ubuntu{ver}/x86_64/cuda-keyring_1.1-1_all.deb", + download(f"https://developer.download.nvidia.com/compute/cuda/repos/{repo}/x86_64/cuda-keyring_1.1-1_all.deb", deb, "CUDA repository key") run(["sudo", "dpkg", "-i", str(deb)]) run(["sudo", "apt-get", "update"]) - run(["sudo", "apt-get", "install", "-y", "cuda-toolkit-13-0"]) + # Debian 13's CUDA repo carries no 13.0 package: take the oldest 13.x minor it has (Ubuntu still gets 13.0). + for minor in range(5): + if run(["sudo", "apt-get", "install", "-y", f"cuda-toolkit-13-{minor}"], check=False).returncode == 0: + break nvcc, cuda_v = find_nvcc(below=(13, 0)) if old else find_nvcc() if (WIN and find_vcvars(cuda_v) is None) or (not WIN and shutil.which("g++") is None): fail("the C++ build tools did not install", "install them by hand (README.md) and run it again") diff --git a/tools/test_setup_cuda_repo.py b/tools/test_setup_cuda_repo.py new file mode 100644 index 00000000..5853a869 --- /dev/null +++ b/tools/test_setup_cuda_repo.py @@ -0,0 +1,85 @@ +"""The CUDA Toolkit apt install: which distros it covers and which 13.x package it picks +(Debian 13's repo has no cuda-toolkit-13-0). No GPU, downloads or installs are used. + + python -m unittest tools.test_setup_cuda_repo +""" +from __future__ import annotations + +import contextlib +import io +import sys +import types +import unittest +from pathlib import Path +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) +import setup # noqa: E402 + + +class AptRepo(unittest.TestCase): + def test_known_and_unknown_distros(self): + for osr, want in ({"ID": "ubuntu", "VERSION_ID": '"22.04"'}, "ubuntu2204"), \ + ({"ID": "ubuntu", "VERSION_ID": '"24.04"'}, "ubuntu2404"), \ + ({"ID": "debian", "VERSION_ID": '"12"'}, "debian12"), \ + ({"ID": "debian", "VERSION_ID": '"13"'}, "debian13"), \ + ({"ID": "debian", "VERSION_ID": '"11"'}, None), \ + ({"ID": "fedora", "VERSION_ID": '"42"'}, None), \ + ({}, None): + with self.subTest(osr=osr): + self.assertEqual(setup.cuda_apt_repo(osr), want) + + def test_debian_13_falls_back_to_the_oldest_13_x_it_has(self): + # the repo has no 13-0: apt fails on it, setup must try 13-1 and stop there (not install 13-2+) + installed = [] + + def fake_run(cmd, **kw): + installed.append(cmd[-1]) + return types.SimpleNamespace(returncode=100 if cmd[-1] == "cuda-toolkit-13-0" else 0) + + with mock.patch.object(setup, "WIN", False), \ + mock.patch.object(setup, "find_nvcc", side_effect=[(None, (0, 0)), ("/usr/local/cuda-13.1/bin/nvcc", (13, 1))]), \ + mock.patch.object(setup.shutil, "which", lambda n: "/usr/bin/" + n), \ + mock.patch("builtins.open", mock.mock_open(read_data='ID=debian\nVERSION_ID="13"\n')), \ + mock.patch.object(setup, "download") as download, \ + mock.patch.object(setup, "run", side_effect=fake_run), \ + contextlib.redirect_stdout(io.StringIO()): + nvcc, _ = setup.install_build_tools({"arch": "86", "archs": [86]}, True) + self.assertEqual(nvcc, "/usr/local/cuda-13.1/bin/nvcc") + self.assertIn("repos/debian13/x86_64/cuda-keyring_1.1-1_all.deb", download.call_args[0][0]) + self.assertEqual(installed[-2:], ["cuda-toolkit-13-0", "cuda-toolkit-13-1"]) + + def test_ubuntu_still_installs_exactly_13_0(self): + installed = [] + + def fake_run(cmd, **kw): + if cmd[0:2] == ["sudo", "apt-get"] and cmd[2] == "install": + installed.append(cmd[-1]) + return types.SimpleNamespace(returncode=0) + + with mock.patch.object(setup, "WIN", False), \ + mock.patch.object(setup, "find_nvcc", side_effect=[(None, (0, 0)), ("/usr/local/cuda-13.0/bin/nvcc", (13, 0))]), \ + mock.patch.object(setup.shutil, "which", lambda n: "/usr/bin/" + n), \ + mock.patch("builtins.open", mock.mock_open(read_data='ID=ubuntu\nVERSION_ID="24.04"\n')), \ + mock.patch.object(setup, "download"), \ + mock.patch.object(setup, "run", side_effect=fake_run), \ + contextlib.redirect_stdout(io.StringIO()): + setup.install_build_tools({"arch": "86", "archs": [86]}, True) + self.assertEqual(installed, ["cuda-toolkit-13-0"]) + + def test_unknown_distro_stops_with_guidance(self): + out = io.StringIO() + with mock.patch.object(setup, "WIN", False), \ + mock.patch.object(setup, "find_nvcc", return_value=(None, (0, 0))), \ + mock.patch.object(setup.shutil, "which", lambda n: "/usr/bin/" + n), \ + mock.patch("builtins.open", mock.mock_open(read_data='ID=fedora\nVERSION_ID="42"\n')), \ + mock.patch.object(setup, "download", side_effect=AssertionError("download started")), \ + contextlib.redirect_stdout(out): + with self.assertRaises(SystemExit): + setup.install_build_tools({"arch": "86", "archs": [86]}, True) + self.assertIn("Debian 12 / 13", out.getvalue()) + + +if __name__ == "__main__": + unittest.main() From 20b501743d6fdba2b5be33d175c5a1e4781b2fc9 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 13 Oct 2026 00:49:11 +0200 Subject: [PATCH 33/67] setup: Ubuntu keeps its checked cuda-toolkit-13-0 install; Debian stops with a message when no 13.x installs (#2172 follow-up) The Debian fallback loop ran with check=False on Ubuntu too, so a failed 13.0 install (a network or apt lock error) went on to 13-1..13-4 and then past the loop without a word. Ubuntu is back to the single checked install of 0.1.43; Debian tries 13-0..13-9 and fails with guidance when none installs. Checked against NVIDIA's repos today: debian12 and ubuntu2404 carry 13-0..13-3, debian13 starts at 13-1 (up to 13-4). Two tests added. --- setup.py | 14 ++++++++++---- tools/test_setup_cuda_repo.py | 30 ++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 4 deletions(-) diff --git a/setup.py b/setup.py index 3a3bc2de..dc67e41c 100644 --- a/setup.py +++ b/setup.py @@ -3287,10 +3287,16 @@ def install_build_tools(gpu, yes): deb, "CUDA repository key") run(["sudo", "dpkg", "-i", str(deb)]) run(["sudo", "apt-get", "update"]) - # Debian 13's CUDA repo carries no 13.0 package: take the oldest 13.x minor it has (Ubuntu still gets 13.0). - for minor in range(5): - if run(["sudo", "apt-get", "install", "-y", f"cuda-toolkit-13-{minor}"], check=False).returncode == 0: - break + if repo.startswith("ubuntu"): # as before: 13.0, and a failed install stops setup here + run(["sudo", "apt-get", "install", "-y", "cuda-toolkit-13-0"]) + else: + # Debian 13's CUDA repo carries no 13.0 package: take the oldest 13.x minor it has + for minor in range(10): + if run(["sudo", "apt-get", "install", "-y", f"cuda-toolkit-13-{minor}"], check=False).returncode == 0: + break + else: + fail(f"no cuda-toolkit-13-x package could be installed from NVIDIA's {repo} repository", + "install the CUDA Toolkit 13 from https://developer.nvidia.com/cuda-downloads and run it again") nvcc, cuda_v = find_nvcc(below=(13, 0)) if old else find_nvcc() if (WIN and find_vcvars(cuda_v) is None) or (not WIN and shutil.which("g++") is None): fail("the C++ build tools did not install", "install them by hand (README.md) and run it again") diff --git a/tools/test_setup_cuda_repo.py b/tools/test_setup_cuda_repo.py index 5853a869..1c59cf74 100644 --- a/tools/test_setup_cuda_repo.py +++ b/tools/test_setup_cuda_repo.py @@ -68,6 +68,36 @@ class AptRepo(unittest.TestCase): setup.install_build_tools({"arch": "86", "archs": [86]}, True) self.assertEqual(installed, ["cuda-toolkit-13-0"]) + def test_debian_without_any_13_x_stops_with_guidance(self): + out = io.StringIO() + with mock.patch.object(setup, "WIN", False), \ + mock.patch.object(setup, "find_nvcc", return_value=(None, (0, 0))), \ + mock.patch.object(setup.shutil, "which", lambda n: "/usr/bin/" + n), \ + mock.patch("builtins.open", mock.mock_open(read_data='ID=debian\nVERSION_ID="12"\n')), \ + mock.patch.object(setup, "download"), \ + mock.patch.object(setup, "run", return_value=types.SimpleNamespace(returncode=100)), \ + contextlib.redirect_stdout(out): + with self.assertRaises(SystemExit): + setup.install_build_tools({"arch": "86", "archs": [86]}, True) + self.assertIn("no cuda-toolkit-13-x package", out.getvalue()) + + def test_ubuntu_install_failure_still_stops_setup(self): + def fake_run(cmd, check=True, **kw): + failed = cmd[-1] == "cuda-toolkit-13-0" + if failed and check: + raise SystemExit(1) # setup.run's own fail() on a checked command + return types.SimpleNamespace(returncode=100 if failed else 0) + + with mock.patch.object(setup, "WIN", False), \ + mock.patch.object(setup, "find_nvcc", return_value=(None, (0, 0))), \ + mock.patch.object(setup.shutil, "which", lambda n: "/usr/bin/" + n), \ + mock.patch("builtins.open", mock.mock_open(read_data='ID=ubuntu\nVERSION_ID="22.04"\n')), \ + mock.patch.object(setup, "download"), \ + mock.patch.object(setup, "run", side_effect=fake_run), \ + contextlib.redirect_stdout(io.StringIO()): + with self.assertRaises(SystemExit): + setup.install_build_tools({"arch": "86", "archs": [86]}, True) + def test_unknown_distro_stops_with_guidance(self): out = io.StringIO() with mock.patch.object(setup, "WIN", False), \ From f812e9a16249352805534caf2574a55af1545848 Mon Sep 17 00:00:00 2001 From: Shawn Jackson Date: Mon, 12 Oct 2026 13:05:44 -0700 Subject: [PATCH 34/67] core: the model's geometry is read from its GGUF metadata and checked against the shape the kernels are compiled for read_geometry (gguf_reader.hpp) fills ModelGeometry from the qwen4exp.* keys, under llama.cpp's names: layers, widths, GDN, attention, indexer (heads, key width, pooling block from compress_ratios, top-k), rope width, hyper-connections, experts, RMS epsilon, and the vocabulary from tokenizer.ggml.tokens. The six keys the guard always required stay required; any other absent key keeps the compiled value. Keys that state one thing twice must agree (the interval and compress_ratios, key and value head widths, routed and shared expert widths, ssm.inner_size and state x v heads). check_architecture no longer hard-codes 48 / 2560 / 24 / 2: it reads the geometry and refuses a file the kernels are not compiled for, naming the key ("qwen4exp.block_count = 40, the kernels are compiled for 48"). Only the expert count, the experts per token (1..64) and the vocabulary may differ. ModelGeometry moves to core/geometry.hpp (no dependencies), with kCompiledGeometry; the kernels that fix a dimension at compile time static_assert it there, in the CUDA/HIP tree and the SYCL copies (plus qsa_prompt_attn_xmx). generate.cpp takes the geometry and K from read_geometry, and the native embedding takes n_embd / n_vocab from it instead of a literal 248320. The QSA kernel shapes come from one qsa_shapes(g) (layout.hpp) in layer, mtp, session, verify and prefill, so n_rot, idx_block and idx_top_k follow the geometry too. Mirrored in sycl/. Tested: tests/core/gguf_geometry_test.cpp (new, synthetic GGUFs) 28/28, gguf_split_test and gguf_reader_test pass, built with MSVC /W4 /WX on Windows. `gguf_geometry_test --real` on Unsloth's Qwen3.8-Flash-Next UD-IQ4_XS shard 1 reads exactly the compiled shape and the guard accepts it. Not built here: the engine (no CUDA, HIP or oneAPI compiler on this PC), so generate/layer/mtp/session/verify/prefill and the kernel asserts are reviewed, not compiled. --- CMakeLists.txt | 4 + include/strata/artifact/gguf_reader.hpp | 196 +++++++++++-- include/strata/core/geometry.hpp | 70 +++++ include/strata/core/layout.hpp | 55 +--- include/strata/kernels/cpu/expert.hpp | 4 + src/core/layer.cpp | 4 +- src/core/mtp.cpp | 10 +- src/core/session.cpp | 7 +- src/core/verify.cpp | 10 +- src/kernels/cuda/fused_gdn.cu | 2 + src/kernels/cuda/fused_gr.cu | 2 + src/kernels/cuda/native_gdn.cu | 2 + src/kernels/cuda/native_ple_postops.cu | 2 + src/kernels/cuda/native_qsa_indexer.cu | 3 + src/kernels/cuda/native_qsa_score.cu | 3 + src/kernels/cuda/qsa_decode_attn.cu | 2 + src/kernels/cuda/qsa_prompt_attn.cu | 2 + src/kernels/cuda/qsa_select.cu | 3 + src/kernels/cuda/s2_expert_grouped.cu | 2 + src/kernels/cuda/verify_kernels.cu | 2 + src/prefill/prefill.cpp | 16 +- src/program/generate.cpp | 26 +- sycl/src/core/layer.cpp | 4 +- sycl/src/core/mtp.cpp | 10 +- sycl/src/core/session.cpp | 7 +- sycl/src/core/verify.cpp | 10 +- sycl/src/kernels/cuda/fused_gdn.dp.cpp | 2 + sycl/src/kernels/cuda/fused_gr.dp.cpp | 2 + sycl/src/kernels/cuda/native_gdn.dp.cpp | 2 + .../kernels/cuda/native_ple_postops.dp.cpp | 2 + .../kernels/cuda/native_qsa_indexer.dp.cpp | 3 + sycl/src/kernels/cuda/native_qsa_score.dp.cpp | 3 + sycl/src/kernels/cuda/qsa_decode_attn.dp.cpp | 2 + sycl/src/kernels/cuda/qsa_prompt_attn.dp.cpp | 2 + .../kernels/cuda/qsa_prompt_attn_xmx.dp.cpp | 3 + sycl/src/kernels/cuda/qsa_select.dp.cpp | 3 + .../src/kernels/cuda/s2_expert_grouped.dp.cpp | 2 + sycl/src/kernels/cuda/verify_kernels.dp.cpp | 2 + sycl/src/prefill/prefill.cpp | 16 +- sycl/src/program/generate.cpp | 26 +- tests/core/gguf_fixture.hpp | 27 +- tests/core/gguf_geometry_test.cpp | 258 ++++++++++++++++++ 42 files changed, 644 insertions(+), 169 deletions(-) create mode 100644 include/strata/core/geometry.hpp create mode 100644 tests/core/gguf_geometry_test.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 0f6426a4..7723a0d2 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -257,6 +257,10 @@ if(STRATA_BUILD_TESTS) add_executable(batch_read_test tests/program/batch_read_test.cpp) target_include_directories(batch_read_test PRIVATE include) add_test(NAME batch_read_test COMMAND batch_read_test) + # the model's geometry from its metadata, and the check against the kernels' compiled shape (synthetic) + add_executable(gguf_geometry_test tests/core/gguf_geometry_test.cpp) + target_link_libraries(gguf_geometry_test PRIVATE strata_artifact) + add_test(NAME gguf_geometry_test COMMAND gguf_geometry_test) # the hipBLASLt tuning header's architecture gate: RDNA4 siblings share solution IDs, RDNA3 siblings share # theirs, cross-family pairs and version mismatches stay rejected (synthetic tables: no model, no GPU) diff --git a/include/strata/artifact/gguf_reader.hpp b/include/strata/artifact/gguf_reader.hpp index 1be01432..4b5baef0 100644 --- a/include/strata/artifact/gguf_reader.hpp +++ b/include/strata/artifact/gguf_reader.hpp @@ -20,6 +20,7 @@ // // Build: scripts/build_artifact.bat Run: gguf_reader.exe [--check] +#include #include #include #include @@ -33,6 +34,7 @@ #include #include "strata/artifact/gguf_split.hpp" +#include "strata/core/geometry.hpp" #ifdef _WIN32 #define WIN32_LEAN_AND_MEAN @@ -577,37 +579,175 @@ private: std::map> index_; }; -// ---- architecture guard (P1.S2). The engine is specialised to ONE model; anything else must be -// refused with a precise error rather than silently mis-run. -struct Qwen4ExpGuard { - uint32_t block_count = 48, hidden = 2560, experts = 0, experts_used = 0, head_count = 24, - head_count_kv = 2; // 0 = presence-only: pruned variants (GSQ-RCO Coder) legitimately ship - // fewer experts than the canonical 512; the graph reads the true value -}; +// ---- the model's geometry from its metadata, and the architecture guard (P1.S2). The engine runs ONE +// architecture, qwen4exp. Its dimensions are read from the file (llama.cpp's key names under the arch prefix) +// and then checked against the shape the kernels are compiled for (core/geometry.hpp), so a file of another +// shape is refused with the key that differs rather than silently mis-run. -inline std::string check_architecture(const GgufFile& g, const Qwen4ExpGuard& want = {}) { - const MetaValue* arch = g.get("general.architecture"); +/// Fills `g` from the metadata shard `f`. Returns "" or the first problem. The six keys every qwen4exp file +/// has carried since the first guard are required; any other key the file does not carry keeps the compiled +/// value. The keys that describe one thing twice (the interval and `compress_ratios`, the key and value head +/// widths, the routed and shared expert widths) must agree. +inline std::string read_geometry(const GgufFile& f, core::ModelGeometry& g) { + g = core::kCompiledGeometry; + const std::string p = "qwen4exp."; + std::string err; + // an integer key into `out`: present and positive, or absent and not `required` + auto read_int = [&](const char* key, int64_t& out, bool required) { + const MetaValue* v = f.get(p + key); + if (!v) { + if (required) err = "missing " + p + key; + return !required; + } + if (!v->is_num() || v->type == MetaType::F32 || v->type == MetaType::F64 || v->type == MetaType::BOOL) { + err = p + key + " is not an integer"; + return false; + } + if ((int64_t) v->u <= 0) { + err = p + key + " = " + std::to_string((int64_t) v->u) + ", it must be positive"; + return false; + } + out = (int64_t) v->u; + return true; + }; + struct Key { + const char* key; + int64_t core::ModelGeometry::*field; + bool required; + }; + const Key keys[] = { + {"block_count", &core::ModelGeometry::n_layers, true}, + {"embedding_length", &core::ModelGeometry::n_embd, true}, + {"expert_count", &core::ModelGeometry::n_expert, true}, + {"expert_used_count", &core::ModelGeometry::n_expert_used, true}, + {"attention.head_count", &core::ModelGeometry::n_head, true}, + {"attention.head_count_kv", &core::ModelGeometry::n_head_kv, true}, + {"full_attention_interval", &core::ModelGeometry::qsa_interval, false}, + {"ssm.state_size", &core::ModelGeometry::ssm_state_size, false}, + {"ssm.group_count", &core::ModelGeometry::ssm_k_heads, false}, + {"ssm.time_step_rank", &core::ModelGeometry::ssm_v_heads, false}, + {"ssm.conv_kernel", &core::ModelGeometry::ssm_d_conv, false}, + {"ssm.inner_size", &core::ModelGeometry::ssm_value_dim, false}, + {"attention.key_length", &core::ModelGeometry::head_dim, false}, + {"rope.dimension_count", &core::ModelGeometry::n_rot, false}, + {"attention.indexer.head_count", &core::ModelGeometry::idx_q_heads, false}, + {"attention.indexer.key_length", &core::ModelGeometry::idx_key_dim, false}, + {"attention.indexer.top_k", &core::ModelGeometry::idx_top_k, false}, + {"hyper_connection.count", &core::ModelGeometry::hc, false}, + {"hyper_connection.low_rank", &core::ModelGeometry::hc_lr, false}, + {"expert_feed_forward_length", &core::ModelGeometry::n_ff, false}, + }; + for (const Key& k : keys) + if (!read_int(k.key, g.*k.field, k.required)) return err; + + int64_t value_length = g.head_dim, ff_shexp = g.n_ff; + if (!read_int("attention.value_length", value_length, false) || + !read_int("expert_shared_feed_forward_length", ff_shexp, false)) + return err; + if (value_length != g.head_dim) + return p + "attention.value_length = " + std::to_string(value_length) + " and attention.key_length = " + + std::to_string(g.head_dim) + ": the attention kernels use one head width for both"; + if (ff_shexp != g.n_ff) + return p + "expert_shared_feed_forward_length = " + std::to_string(ff_shexp) + + " and expert_feed_forward_length = " + std::to_string(g.n_ff) + + ": the shared expert is read with the routed experts' width"; + if (const MetaValue* v = f.get(p + "attention.layer_norm_rms_epsilon")) { + if (!v->is_num() || !(v->num() > 0)) return p + "attention.layer_norm_rms_epsilon must be a positive number"; + g.rms_eps = v->num(); + } + if (const MetaValue* v = f.get("tokenizer.ggml.tokens")) { + if (v->type != MetaType::ARRAY || v->count == 0) return "tokenizer.ggml.tokens is not a list of tokens"; + g.n_vocab = (int64_t) v->count; + } + + if (g.n_head % g.n_head_kv != 0) + return p + "attention.head_count = " + std::to_string(g.n_head) + " is not a multiple of head_count_kv = " + + std::to_string(g.n_head_kv); + // GDN's value heads are as wide as its key heads (the state is square) + if (g.ssm_value_dim != g.ssm_state_size * g.ssm_v_heads) + return p + "ssm.inner_size = " + std::to_string(g.ssm_value_dim) + ", but ssm.state_size x ssm.time_step_rank = " + + std::to_string(g.ssm_state_size * g.ssm_v_heads) + ": the GDN kernels take square heads"; + g.ssm_conv_channels = 2 * g.ssm_state_size * g.ssm_k_heads + g.ssm_value_dim; + if (g.n_expert_used > g.n_expert || g.n_expert_used > 64) + return p + "expert_used_count = " + std::to_string(g.n_expert_used) + ", the router takes 1.." + + std::to_string(std::min(g.n_expert, 64)) + " of " + std::to_string(g.n_expert) + " experts"; + if (g.n_rot > g.head_dim || g.n_rot > g.idx_key_dim || g.n_rot % 2) + return p + "rope.dimension_count = " + std::to_string(g.n_rot) + " is not an even slice of the head widths"; + + // The layer split, twice over: the interval, and a ratio per layer that is non-zero (the indexer's pooling + // block) exactly on the full-attention layers. + if (const MetaValue* v = f.get(p + "attention.compress_ratios")) { + if (v->type != MetaType::ARRAY || v->count != (uint64_t) g.n_layers || v->items.size() != v->count) + return p + "attention.compress_ratios must list one entry for each of the " + std::to_string(g.n_layers) + + " layers"; + int64_t block = 0; + for (int64_t l = 0; l < g.n_layers; ++l) { + const int64_t r = (int64_t) v->items[(size_t) l].u; + if ((r != 0) != core::is_qsa_layer(g, l) || r < 0 || (block && r && r != block)) + return p + "attention.compress_ratios[" + std::to_string(l) + "] = " + std::to_string(r) + + ", but full_attention_interval = " + std::to_string(g.qsa_interval) + " makes layer " + + std::to_string(l) + (core::is_qsa_layer(g, l) ? " full attention" : " linear attention") + + (block && r ? " (and the other full-attention layers pool " + std::to_string(block) + ")" : ""); + if (r) block = r; + } + if (block) g.idx_block = block; + } + return {}; +} + +/// Returns "" when the compiled kernels can run `g`, else the first metadata key whose value they are not +/// compiled for. Only the expert count and the experts per token are free (the router and the expert paths +/// take them at run time); the vocabulary is free because the head and the embedding take their tensors' shapes. +inline std::string geometry_unsupported(const core::ModelGeometry& g) { + const core::ModelGeometry& c = core::kCompiledGeometry; + struct Pin { + const char* key; + int64_t core::ModelGeometry::*field; + }; + const Pin pins[] = { + {"block_count", &core::ModelGeometry::n_layers}, + {"embedding_length", &core::ModelGeometry::n_embd}, + {"full_attention_interval", &core::ModelGeometry::qsa_interval}, + {"ssm.state_size", &core::ModelGeometry::ssm_state_size}, + {"ssm.group_count", &core::ModelGeometry::ssm_k_heads}, + {"ssm.time_step_rank", &core::ModelGeometry::ssm_v_heads}, + {"ssm.conv_kernel", &core::ModelGeometry::ssm_d_conv}, + {"ssm.inner_size", &core::ModelGeometry::ssm_value_dim}, + {"attention.head_count", &core::ModelGeometry::n_head}, + {"attention.head_count_kv", &core::ModelGeometry::n_head_kv}, + {"attention.key_length", &core::ModelGeometry::head_dim}, + {"rope.dimension_count", &core::ModelGeometry::n_rot}, + {"attention.indexer.head_count", &core::ModelGeometry::idx_q_heads}, + {"attention.indexer.key_length", &core::ModelGeometry::idx_key_dim}, + {"attention.compress_ratios", &core::ModelGeometry::idx_block}, + {"attention.indexer.top_k", &core::ModelGeometry::idx_top_k}, + {"hyper_connection.count", &core::ModelGeometry::hc}, + {"hyper_connection.low_rank", &core::ModelGeometry::hc_lr}, + {"expert_feed_forward_length", &core::ModelGeometry::n_ff}, + }; + for (const Pin& pin : pins) + if (g.*pin.field != c.*pin.field) + return std::string("qwen4exp.") + pin.key + " = " + std::to_string(g.*pin.field) + + ", the kernels are compiled for " + std::to_string(c.*pin.field); + // one constant in the norm kernels; the files carry it as an f32, so compare at f32 precision + if (std::abs(g.rms_eps - c.rms_eps) > 1e-6 * c.rms_eps) { + char buf[160]; + std::snprintf(buf, sizeof buf, "qwen4exp.attention.layer_norm_rms_epsilon = %g, the kernels are compiled for %g", + g.rms_eps, c.rms_eps); + return buf; + } + return {}; +} + +/// The architecture guard: "" when the engine can run the model whose metadata shard is `f`. +inline std::string check_architecture(const GgufFile& f) { + const MetaValue* arch = f.get("general.architecture"); if (!arch) return "missing general.architecture"; if (arch->s != "qwen4exp") return "architecture is '" + arch->s + "', this engine requires 'qwen4exp'"; - struct Req { - const char* key; - uint64_t want; - }; - const Req reqs[] = { - {"qwen4exp.block_count", want.block_count}, - {"qwen4exp.embedding_length", want.hidden}, - {"qwen4exp.expert_count", want.experts}, - {"qwen4exp.expert_used_count", want.experts_used}, - {"qwen4exp.attention.head_count", want.head_count}, - {"qwen4exp.attention.head_count_kv", want.head_count_kv}, - }; - for (const auto& r : reqs) { - const MetaValue* v = g.get(r.key); - if (!v) return std::string("missing ") + r.key; - if (r.want && v->u != r.want) - return std::string(r.key) + " = " + std::to_string(v->u) + ", expected " + std::to_string(r.want); - } - return {}; // empty == ok + core::ModelGeometry g; + std::string err = read_geometry(f, g); + if (err.empty()) err = geometry_unsupported(g); + return err; } } // namespace strata diff --git a/include/strata/core/geometry.hpp b/include/strata/core/geometry.hpp new file mode 100644 index 00000000..d3916d6e --- /dev/null +++ b/include/strata/core/geometry.hpp @@ -0,0 +1,70 @@ +// include/strata/core/geometry.hpp - the model's geometry: one struct for the shape a model file declares and +// the shape the kernels are compiled for. +// +// A model file's geometry is read from its own metadata (`strata::read_geometry`, gguf_reader.hpp), and the +// engine passes that struct everywhere it needs a dimension. The CUDA/HIP kernels still fix most of these +// numbers at compile time (`constexpr int N = 2560` and the like); `kCompiledGeometry` is that shape, written +// once, and each kernel that pins a number `static_assert`s it against this struct. So a kernel and this file +// cannot drift apart without the build failing, and a model file of another shape is refused at load with the +// metadata key that differs (`strata::geometry_unsupported`) instead of mis-running. +// +// Dependency-free on purpose: the kernels include it. +#pragma once + +#include + +namespace strata::core { + +/// Every field is a number a kernel depends on, so a change to the compiled values is a change to a kernel +/// contract and not a tuning knob. The defaults are Qwen3.8-Flash-Next's (qwen4exp), the shape the kernels +/// are compiled for; the GGUF key each field is read from is named beside it. +struct ModelGeometry { + int64_t n_embd = 2560; ///< embedding_length + int64_t n_layers = 48; ///< block_count + int64_t qsa_interval = 4; ///< full_attention_interval: every 4th layer is full attention, 3, 7, ... 47 + int64_t n_vocab = 248320; ///< the length of tokenizer.ggml.tokens + double rms_eps = 1e-6; ///< attention.layer_norm_rms_epsilon + + // GDN (36 layers) + int64_t ssm_state_size = 128; ///< ssm.state_size: the key head width, and the value head width + int64_t ssm_k_heads = 16; ///< ssm.group_count + int64_t ssm_v_heads = 48; ///< ssm.time_step_rank + int64_t ssm_d_conv = 4; ///< ssm.conv_kernel + int64_t ssm_conv_channels = 10240; ///< 2*128*16 + 128*48, derived + int64_t ssm_value_dim = 6144; ///< ssm.inner_size, 128 * 48 + + // QSA (12 layers) + int64_t n_head = 24; ///< attention.head_count + int64_t n_head_kv = 2; ///< attention.head_count_kv + int64_t head_dim = 256; ///< attention.key_length (= attention.value_length) + int64_t n_rot = 64; ///< rope.dimension_count: the rotated slice of head_dim and of idx_key_dim + int64_t idx_q_heads = 4; ///< attention.indexer.head_count + int64_t idx_key_dim = 128; ///< attention.indexer.key_length + int64_t idx_block = 4; ///< the non-zero attention.compress_ratios entry: one pooled key per 4 cells + int64_t idx_top_k = 2048; ///< attention.indexer.top_k: cells of selection budget + + // gated residual, on every layer + int64_t hc = 4; ///< hyper_connection.count + int64_t hc_lr = 320; ///< hyper_connection.low_rank + + // MoE, on every layer + int64_t n_expert = 512; ///< expert_count; pruned variants (GSQ-RCO Coder) ship fewer + int64_t n_expert_used = 10; ///< expert_used_count + int64_t n_ff = 640; ///< expert_feed_forward_length (= expert_shared_feed_forward_length) + + constexpr int64_t hc_dim() const { return hc * n_embd; } + /// `layer % qsa_interval == qsa_interval - 1` is full attention. Derived, not a second list. + constexpr int64_t n_qsa_layers() const { return n_layers / qsa_interval; } + constexpr int64_t n_gdn_layers() const { return n_layers - n_qsa_layers(); } +}; + +/// The shape the kernels are compiled for. A kernel that fixes a dimension at compile time asserts it here. +inline constexpr ModelGeometry kCompiledGeometry{}; + +/// True for the full-attention layers. `docs/semantics.md` gives this twice over - `full_attention_interval +/// = 4` and an explicit `attention.compress_ratios` array - and `read_geometry` checks that the two agree. +inline bool is_qsa_layer(const ModelGeometry& g, int64_t layer) { + return layer % g.qsa_interval == g.qsa_interval - 1; +} + +} // namespace strata::core diff --git a/include/strata/core/layout.hpp b/include/strata/core/layout.hpp index 7b27fec9..e9a91f9b 100644 --- a/include/strata/core/layout.hpp +++ b/include/strata/core/layout.hpp @@ -15,53 +15,28 @@ // at LOAD time - not as a wrong number inside a GEMV at token 4000. #pragma once +#include "strata/core/geometry.hpp" #include "strata/core/weights.hpp" +#include "strata/kernels/qsa.hpp" #include #include namespace strata::core { -/// The model's geometry, taken from `docs/semantics.md` and the artifact's own metadata. Every field here -/// is a number a kernel depends on, so a change is a change to a kernel contract and not a tuning knob. -struct ModelGeometry { - int64_t n_embd = 2560; - int64_t n_layers = 48; - int64_t qsa_interval = 4; ///< every 4th layer is full attention: layers 3, 7, ... 47 - - // GDN (36 layers) - int64_t ssm_state_size = 128; - int64_t ssm_k_heads = 16; - int64_t ssm_v_heads = 48; - int64_t ssm_d_conv = 4; - int64_t ssm_conv_channels = 10240; ///< 2*128*16 + 128*48 - int64_t ssm_value_dim = 6144; ///< 128 * 48 - - // QSA (12 layers) - int64_t n_head = 24; - int64_t n_head_kv = 2; - int64_t head_dim = 256; - int64_t idx_q_heads = 4; - int64_t idx_key_dim = 128; - - // gated residual, on every layer - int64_t hc = 4; - int64_t hc_lr = 320; - - // MoE, on every layer - int64_t n_expert = 512; - int64_t n_ff = 640; - - int64_t hc_dim() const { return hc * n_embd; } - /// `layer % qsa_interval == qsa_interval - 1` is full attention. Derived, not a second list. - int64_t n_qsa_layers() const { return n_layers / qsa_interval; } - int64_t n_gdn_layers() const { return n_layers - n_qsa_layers(); } -}; - -/// True for the full-attention layers. `docs/semantics.md` gives this twice over - `full_attention_interval -/// = 4` and an explicit `attention.compress_ratios` array - and this is the first of the two. -inline bool is_qsa_layer(const ModelGeometry& g, int64_t layer) { - return layer % g.qsa_interval == g.qsa_interval - 1; +/// The shapes the QSA kernels want, every one from the model's geometry; only the KV page size is the +/// kernels' own choice (`qsa_real_shapes`). +inline strata::kernels::QsaShapes qsa_shapes(const ModelGeometry& g) { + strata::kernels::QsaShapes s = strata::kernels::qsa_real_shapes(); + s.n_head = g.n_head; + s.n_head_kv = g.n_head_kv; + s.head_dim = g.head_dim; + s.n_rot = g.n_rot; + s.idx_n_head = g.idx_q_heads; + s.idx_dim = g.idx_key_dim; + s.idx_block = g.idx_block; + s.idx_top_k = g.idx_top_k; + return s; } /// One layer's tensors, resolved by NAME. `get("attn_qkv.weight")` looks up `blk..attn_qkv.weight` diff --git a/include/strata/kernels/cpu/expert.hpp b/include/strata/kernels/cpu/expert.hpp index 441dfac0..16dcabd5 100644 --- a/include/strata/kernels/cpu/expert.hpp +++ b/include/strata/kernels/cpu/expert.hpp @@ -25,6 +25,8 @@ // per weight block is the natural-looking mistake. #pragma once +#include "strata/core/geometry.hpp" + #include #include @@ -34,6 +36,8 @@ namespace strata::kernels::cpu { inline constexpr int H = 2560; // n_embd inline constexpr int FF = 640; // expert intermediate width inline constexpr int NE = 512; // routed experts per layer +static_assert(H == strata::core::kCompiledGeometry.n_embd && FF == strata::core::kCompiledGeometry.n_ff, + "the CPU expert path is compiled for core/geometry.hpp"); inline constexpr int QK = 64; // QK2_0: weights per fp16 scale inline constexpr int QKA = 32; // QK8_1/QK8_0: ACTIVATION elements per scale inline constexpr int BB = 18; // bytes per 64-weight Q2_0 block: 2 fp16-scale + 16 codes diff --git a/src/core/layer.cpp b/src/core/layer.cpp index 45f19c08..1e6b3b93 100644 --- a/src/core/layer.cpp +++ b/src/core/layer.cpp @@ -503,9 +503,7 @@ bool moe_layer(const WeightTable& tables, const ModelGeometry& g, int64_t layer, if (!moe_route(tables, g, layer, k, b, x, stream, err, db)) return false; return moe_finish(tables, g, layer, k, b, x, parts, out, stream, err);} // ================================ the QSA mixer ================================ namespace {using strata::kernels::QsaIndexerBuffers;using strata::kernels::QsaShapes; -/// The geometry the QSA kernels want, from the one place that defines it. `ModelGeometry` carries the widths -/// the LAYOUT needs; `QsaShapes` adds `n_rot`, `idx_block` and `idx_top_k`, which are kernel contracts. -QsaShapes qsa_shapes(const ModelGeometry& g) { QsaShapes s = strata::kernels::qsa_real_shapes(); s.n_head = g.n_head; s.n_head_kv = g.n_head_kv; s.head_dim = g.head_dim; s.idx_n_head = g.idx_q_heads; s.idx_dim = g.idx_key_dim; return s;} +// `qsa_shapes(g)` (layout.hpp): the geometry the QSA kernels want, every field from the model's geometry uint64_t align_up16(uint64_t n) { return (n + 15) & ~15ull; } /// One cursor over an arena, so every region is 16-byte aligned without a list of hand-added offsets. struct Cursor { uint8_t* p; uint64_t used = 0; template T* take(uint64_t count) { T* r = (T*) (p + used); used = align_up16(used + count * sizeof(T)); return r; } uint8_t* take_bytes(uint64_t n) { uint8_t* r = p + used; used = align_up16(used + n); return r; }}; diff --git a/src/core/mtp.cpp b/src/core/mtp.cpp index 0ca8cd18..dbf60882 100644 --- a/src/core/mtp.cpp +++ b/src/core/mtp.cpp @@ -85,15 +85,7 @@ bool mapped(size_t bytes, void** h, void** d) { return cudaHostGetDevicePointer(d, *h, 0) == cudaSuccess; } -strata::kernels::QsaShapes shapes_of(const ModelGeometry& g) { - strata::kernels::QsaShapes s = strata::kernels::qsa_real_shapes(); - s.n_head = g.n_head; - s.n_head_kv = g.n_head_kv; - s.head_dim = g.head_dim; - s.idx_n_head = g.idx_q_heads; - s.idx_dim = g.idx_key_dim; - return s; -} +strata::kernels::QsaShapes shapes_of(const ModelGeometry& g) { return qsa_shapes(g); } // 64-bit seek/tell on a `FILE*`: `fseek`/`ftell` take a 32-bit `long` on Windows and would wrap past 2 GiB. #if defined(_WIN32) diff --git a/src/core/session.cpp b/src/core/session.cpp index 8d1fad91..55317c78 100644 --- a/src/core/session.cpp +++ b/src/core/session.cpp @@ -176,12 +176,7 @@ void gdn_point_at(const ModelGeometry& g, int64_t layer, SessionState& s) { /// The per-token staging every QSA layer's captured H2D reads FROM. Must run before each replay: the graphs /// captured the SOURCE POINTER, not the value, and that is exactly why the buffers are pinned and fixed. void stage_token(const ModelGeometry& g, int64_t pos, int32_t pos_base, SessionState& s) { - strata::kernels::QsaShapes sh = strata::kernels::qsa_real_shapes(); - sh.n_head = g.n_head; - sh.n_head_kv = g.n_head_kv; - sh.head_dim = g.head_dim; - sh.idx_n_head = g.idx_q_heads; - sh.idx_dim = g.idx_key_dim; + const strata::kernels::QsaShapes sh = qsa_shapes(g); for (int64_t j = 0; j < s.qsa_alloc; ++j) { QsaState& q = s.qsa_states[s.qsa_ord0 + j]; qsa_step_fill(q.host_step, pos, sh); diff --git a/src/core/verify.cpp b/src/core/verify.cpp index 3995ae9d..bb108338 100644 --- a/src/core/verify.cpp +++ b/src/core/verify.cpp @@ -305,15 +305,7 @@ bool mapped(size_t bytes, void** h, void** d) { return cudaHostGetDevicePointer(d, *h, 0) == cudaSuccess; } -strata::kernels::QsaShapes shapes_of(const ModelGeometry& g) { - strata::kernels::QsaShapes s = strata::kernels::qsa_real_shapes(); - s.n_head = g.n_head; - s.n_head_kv = g.n_head_kv; - s.head_dim = g.head_dim; - s.idx_n_head = g.idx_q_heads; - s.idx_dim = g.idx_key_dim; - return s; -} +strata::kernels::QsaShapes shapes_of(const ModelGeometry& g) { return qsa_shapes(g); } const WeightRef* need(const LayerView& v, const char* suffix, std::string& err) { const WeightRef* r = v.get(suffix); diff --git a/src/kernels/cuda/fused_gdn.cu b/src/kernels/cuda/fused_gdn.cu index 5d39cd2d..d3311c25 100644 --- a/src/kernels/cuda/fused_gdn.cu +++ b/src/kernels/cuda/fused_gdn.cu @@ -1,5 +1,6 @@ // src/kernels/cuda/fused_gdn.cu - see include/strata/kernels/fused_gdn.hpp. #include "strata/kernels/fused_gdn.hpp" +#include "strata/core/geometry.hpp" #include @@ -10,6 +11,7 @@ namespace strata::kernels { namespace { constexpr int S = 128; // state size (rows = cols = 128) +static_assert(S == strata::core::kCompiledGeometry.ssm_state_size, "fused_gdn is compiled for core/geometry.hpp"); constexpr int RG = 4; // row groups constexpr int RPG = S / RG; // 32 rows per thread diff --git a/src/kernels/cuda/fused_gr.cu b/src/kernels/cuda/fused_gr.cu index ab984240..c3c2fc8d 100644 --- a/src/kernels/cuda/fused_gr.cu +++ b/src/kernels/cuda/fused_gr.cu @@ -1,6 +1,7 @@ // src/kernels/cuda/fused_gr.cu - see include/strata/kernels/fused_gr.hpp. #include "strata/core/emulate.hpp" #include "strata/kernels/q8_1_finite.hpp" // #606: q8_1_ds +#include "strata/core/geometry.hpp" #include "strata/kernels/fused_gr.hpp" #include "strata/kernels/bf16_bits.hpp" #include "strata/kernels/verify_kernels.hpp" @@ -31,6 +32,7 @@ constexpr int LR = 320; // hc_lr #else #define STRATA_GR_FAST_BUILD 0 #endif +static_assert(N == strata::core::kCompiledGeometry.n_embd && HC == strata::core::kCompiledGeometry.hc && LR == strata::core::kCompiledGeometry.hc_lr, "fused_gr is compiled for core/geometry.hpp"); constexpr int THREADS = 256; constexpr int WARPS = THREADS / 32; constexpr int DOWN_BLOCKS = LR / WARPS; // 40 blocks of 8 rows; one more for the inject rows diff --git a/src/kernels/cuda/native_gdn.cu b/src/kernels/cuda/native_gdn.cu index 6661d50f..7dae8c8c 100644 --- a/src/kernels/cuda/native_gdn.cu +++ b/src/kernels/cuda/native_gdn.cu @@ -24,6 +24,7 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #include "strata/kernels/native_gdn.hpp" +#include "strata/core/geometry.hpp" #include #include #include @@ -35,6 +36,7 @@ namespace strata::kernels { namespace { std::atomic enabled{false}; constexpr int S = 128; +static_assert(S == strata::core::kCompiledGeometry.ssm_state_size, "native_gdn is compiled for core/geometry.hpp"); __device__ __forceinline__ float warp_sum(float value) { #pragma unroll diff --git a/src/kernels/cuda/native_ple_postops.cu b/src/kernels/cuda/native_ple_postops.cu index d9aae46b..4f2db940 100644 --- a/src/kernels/cuda/native_ple_postops.cu +++ b/src/kernels/cuda/native_ple_postops.cu @@ -19,6 +19,7 @@ // SOFTWARE. #include "strata/kernels/native_ple_postops.hpp" +#include "strata/core/geometry.hpp" #include "strata/kernels/native_gr_norm.hpp" #include "strata/kernels/ngram.hpp" #include @@ -33,6 +34,7 @@ namespace strata::kernels { namespace { constexpr int N = 2560, H = 4, D = N * H, HISTORY = 9; +static_assert(N == strata::core::kCompiledGeometry.n_embd && H == strata::core::kCompiledGeometry.hc, "native_ple_postops is compiled for core/geometry.hpp"); __device__ float warp_sum(float x) { for (int offset = 16; offset; offset >>= 1) x += __shfl_xor_sync(0xffffffffu, x, offset); return x; diff --git a/src/kernels/cuda/native_qsa_indexer.cu b/src/kernels/cuda/native_qsa_indexer.cu index f919e8ca..5d0dad42 100644 --- a/src/kernels/cuda/native_qsa_indexer.cu +++ b/src/kernels/cuda/native_qsa_indexer.cu @@ -19,6 +19,7 @@ // SOFTWARE. #include "strata/kernels/native_qsa_indexer.hpp" +#include "strata/core/geometry.hpp" #include "strata/kernels/mrope.hpp" #include #include @@ -33,6 +34,8 @@ namespace strata::kernels { namespace { std::atomic enabled{false}; constexpr int D = 128, R = 4, ROT = 64, THREADS = 256; +static_assert(D == strata::core::kCompiledGeometry.idx_key_dim && R == strata::core::kCompiledGeometry.idx_block && ROT == strata::core::kCompiledGeometry.n_rot, + "native_qsa_indexer is compiled for core/geometry.hpp"); __device__ float warp_sum(float x) { #pragma unroll for (int offset = 16; offset; offset >>= 1) diff --git a/src/kernels/cuda/native_qsa_score.cu b/src/kernels/cuda/native_qsa_score.cu index cdcfeadd..4d10757e 100644 --- a/src/kernels/cuda/native_qsa_score.cu +++ b/src/kernels/cuda/native_qsa_score.cu @@ -19,6 +19,7 @@ // SOFTWARE. #include "strata/kernels/native_qsa_score.hpp" +#include "strata/core/geometry.hpp" #include #include #include @@ -29,6 +30,8 @@ namespace strata::kernels { namespace { std::atomic enabled{false}; constexpr int D=128, HEADS=4, R=4, ROWS=32, WARPS=2, STRIDE=36, COMBINE=68; +static_assert(D == strata::core::kCompiledGeometry.idx_key_dim && HEADS == strata::core::kCompiledGeometry.idx_q_heads && R == strata::core::kCompiledGeometry.idx_block, + "native_qsa_score is compiled for core/geometry.hpp"); struct TileA { uint32_t x[4]; }; struct TileB { uint32_t x[2]; }; struct TileC { float x[4]={0.0f,0.0f,0.0f,0.0f}; }; diff --git a/src/kernels/cuda/qsa_decode_attn.cu b/src/kernels/cuda/qsa_decode_attn.cu index 624036c6..bff0e420 100644 --- a/src/kernels/cuda/qsa_decode_attn.cu +++ b/src/kernels/cuda/qsa_decode_attn.cu @@ -1,5 +1,6 @@ // src/kernels/cuda/qsa_decode_attn.cu - see include/strata/kernels/qsa_decode_attn.hpp. #include "strata/kernels/qsa_decode_attn.hpp" +#include "strata/core/geometry.hpp" #include "strata/kernels/kv_q8.hpp" #include "strata/kernels/kv_q4.hpp" #if defined(STRATA_HIP_GFX906) @@ -19,6 +20,7 @@ namespace { constexpr int HD = 256; // head_dim constexpr int G = 12; // query heads per KV head (24 / 2) +static_assert(HD == strata::core::kCompiledGeometry.head_dim && G == strata::core::kCompiledGeometry.n_head / strata::core::kCompiledGeometry.n_head_kv, "qsa_decode_attn is compiled for core/geometry.hpp"); constexpr int CHUNK = 64; // cells per block constexpr int THREADS = 256; constexpr int WARPS = THREADS / 32; diff --git a/src/kernels/cuda/qsa_prompt_attn.cu b/src/kernels/cuda/qsa_prompt_attn.cu index 3a0a8e38..bd99609d 100644 --- a/src/kernels/cuda/qsa_prompt_attn.cu +++ b/src/kernels/cuda/qsa_prompt_attn.cu @@ -1,5 +1,6 @@ // src/kernels/cuda/qsa_prompt_attn.cu - see include/strata/kernels/qsa_prompt_attn.hpp. #include "strata/core/emulate.hpp" +#include "strata/core/geometry.hpp" #include #include #include "strata/kernels/qsa_prompt_attn.hpp" @@ -21,6 +22,7 @@ namespace { constexpr int HD = 256; // head_dim constexpr int G = 12; // query heads per KV head +static_assert(HD == strata::core::kCompiledGeometry.head_dim && G == strata::core::kCompiledGeometry.n_head / strata::core::kCompiledGeometry.n_head_kv, "qsa_prompt_attn is compiled for core/geometry.hpp"); #ifndef D1_CH #define D1_CH 32 #endif diff --git a/src/kernels/cuda/qsa_select.cu b/src/kernels/cuda/qsa_select.cu index d880fc6e..cb06396a 100644 --- a/src/kernels/cuda/qsa_select.cu +++ b/src/kernels/cuda/qsa_select.cu @@ -1,5 +1,6 @@ // src/kernels/cuda/qsa_select.cu - see include/strata/kernels/qsa_select.hpp. #include "strata/core/emulate.hpp" +#include "strata/core/geometry.hpp" #include #include #include "strata/kernels/qsa_select.hpp" @@ -16,6 +17,8 @@ namespace strata::kernels { namespace { constexpr int IDX_DIM = 128, IDX_HEADS = 4, R = 4; +static_assert(IDX_DIM == strata::core::kCompiledGeometry.idx_key_dim && IDX_HEADS == strata::core::kCompiledGeometry.idx_q_heads && R == strata::core::kCompiledGeometry.idx_block, + "qsa_select is compiled for core/geometry.hpp"); constexpr int SCORE_WARPS = 8; constexpr int TOPK_T = 256; diff --git a/src/kernels/cuda/s2_expert_grouped.cu b/src/kernels/cuda/s2_expert_grouped.cu index bb889029..77bd5d27 100644 --- a/src/kernels/cuda/s2_expert_grouped.cu +++ b/src/kernels/cuda/s2_expert_grouped.cu @@ -14,6 +14,7 @@ // The two agree to float rounding and not to the bit, which is the same contract `s_gemv_parity` carries for // the same reason. `bench/micro/moe_hit_parity.cu` is the check. #include "strata/kernels/s2_expert_grouped.hpp" +#include "strata/core/geometry.hpp" #include "strata/kernels/dp4a.hpp" #include "strata/kernels/f16_bits.hpp" @@ -37,6 +38,7 @@ namespace { // are what the CPU kernel's indexing computes, and `moe_hit_parity` compares the two end to end. constexpr int H = 2560; constexpr int FF = 640; +static_assert(H == strata::core::kCompiledGeometry.n_embd && FF == strata::core::kCompiledGeometry.n_ff, "s2_expert_grouped is compiled for core/geometry.hpp"); constexpr int QK = 64; // Q2_0's group: one fp16 scale per 64 weights constexpr int ROW_GU = H / 4; // 640 B of codes per gate/up row (2 bits per element) constexpr int ROW_D = FF / 4; // 160 B per down row diff --git a/src/kernels/cuda/verify_kernels.cu b/src/kernels/cuda/verify_kernels.cu index ac2855d7..32ce40a1 100644 --- a/src/kernels/cuda/verify_kernels.cu +++ b/src/kernels/cuda/verify_kernels.cu @@ -3,6 +3,7 @@ // The per-token arithmetic of every kernel here is transcribed from its single-token original (fused_gdn.cu, // elementwise.cu) with the same operation order, so a verify window reproduces plain decode bit for bit. #include "strata/kernels/verify_kernels.hpp" +#include "strata/core/geometry.hpp" #include "strata/core/emulate.hpp" #include "strata/kernels/q8_1_finite.hpp" // #606: q8_1_ds #include "strata/kernels/dp4a.hpp" @@ -24,6 +25,7 @@ namespace strata::kernels { namespace { constexpr int S = 128; // GDN state size +static_assert(S == strata::core::kCompiledGeometry.ssm_state_size, "verify_kernels is compiled for core/geometry.hpp"); constexpr int RG = 4; constexpr int RPG = S / RG; diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index d13fdd19..3f537abd 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -1228,9 +1228,7 @@ bool Prefill::carve(size_t T, void* alloc) { if (bf16x2_hc(m.f16_io)) { m.xn16_lo = o.take(T * D, ok); m.lo16_lo = o.take(T * LR, ok); } if (bf16x2(m.f16_io)) m.mixed_bf_lo = o.take(T * N, ok); m.steps_dev = o.take(T * strata::kernels::kStepCount, ok); - strata::kernels::QsaShapes s = strata::kernels::qsa_real_shapes(); - s.n_head = g.n_head; s.n_head_kv = g.n_head_kv; s.head_dim = g.head_dim; s.idx_n_head = g.idx_q_heads; - s.idx_dim = g.idx_key_dim; + strata::kernels::QsaShapes s = core::qsa_shapes(g); m.cap = strata::kernels::qsa_selection_width(strata::kernels::kTopkMaxCells, s); m.max_blocks = ss.qsa_states[ss.qsa_primary()].max_cells / s.idx_block + 2; { @@ -1427,9 +1425,7 @@ bool Prefill::draft_kv(core::MtpDrafter& mtp, const float* R_rows, const int32_t if (!mtp.idle(err)) return false; // the drafter's own stream (its graph uploads) before this writes its K/V const double ms_idle = ms_since(ti0); const auto tl0 = Clock::now(); - strata::kernels::QsaShapes s = strata::kernels::qsa_real_shapes(); - s.n_head = g.n_head; s.n_head_kv = g.n_head_kv; s.head_dim = g.head_dim; s.idx_n_head = g.idx_q_heads; - s.idx_dim = g.idx_key_dim; + strata::kernels::QsaShapes s = core::qsa_shapes(g); std::vector tk((size_t) B); if (q8) { if (!m.mmq_ctx) m.mmq_ctx = std::make_unique(); @@ -1864,9 +1860,7 @@ uint64_t Prefill::bytes_needed_impl(const core::ModelGeometry& g, const core::Se if (bf16x2_hc(f16_io)) { o.take(T * D, ok); o.take(T * LR, ok); } if (bf16x2(f16_io)) o.take(T * N, ok); o.take(T * strata::kernels::kStepCount, ok); - strata::kernels::QsaShapes s = strata::kernels::qsa_real_shapes(); - s.n_head = g.n_head; s.n_head_kv = g.n_head_kv; s.head_dim = g.head_dim; s.idx_n_head = g.idx_q_heads; - s.idx_dim = g.idx_key_dim; + strata::kernels::QsaShapes s = core::qsa_shapes(g); const int64_t cap = strata::kernels::qsa_selection_width(strata::kernels::kTopkMaxCells, s); const int64_t max_blocks = ss.qsa_states[ss.qsa_primary()].max_cells / s.idx_block + 2; o.take((size_t) std::max({gdn_set_bytes(T), qsa_set_bytes(T, cap, max_blocks, 256, 32, s), @@ -2055,9 +2049,7 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri // The direct successor's future lives on the Prefill object. Intermediate // stages therefore do not drain the complete remaining GPU chain here. double host_sync_ms = 0, host_chunk_ms = 0, host_setup_ms = 0; // STRATA_PREFILL_TIMING: the host's share - strata::kernels::QsaShapes s = strata::kernels::qsa_real_shapes(); - s.n_head = g.n_head; s.n_head_kv = g.n_head_kv; s.head_dim = g.head_dim; s.idx_n_head = g.idx_q_heads; - s.idx_dim = g.idx_key_dim; + strata::kernels::QsaShapes s = core::qsa_shapes(g); // read once (STRATA_KV_PREFETCH=1/0: the next streamed layer's KV prefix is staged on its own stream) static const bool kv_prefetch_on = [] { const char* e = std::getenv("STRATA_KV_PREFETCH"); diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 2cd885c9..734837fc 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -2831,8 +2831,10 @@ int main(int argc, char** argv) { ? "AVX1 128-bit (iq_avx1, the older-CPU build)" : "ggml-cpu vec_dot (no AVX2: the older-CPU build)") : std::getenv("STRATA_NO_IQ256") == nullptr ? "AVX-2" : "ggml-cpu vec_dot (STRATA_NO_IQ256 set)"); - strata::core::ModelGeometry g; // canonical defaults; the model file overrides the MoE shape below - int64_t K = 10; + // the compiled shape; a native model's file replaces it below with its own metadata (read_geometry), which a + // pruned variant (GSQ-RCO Coder, fewer than 512 experts) differs from + strata::core::ModelGeometry g; + int64_t K = g.n_expert_used; // THE ROPE CONFIG RESOLVES HERE, BEFORE ANY WEIGHT MOVES - the CLI and the model file have both spoken, // and `session_init` below builds the rope table from it and captures the kernels reading its constants // (rope_scaling.hpp); the only hard constraint is "set before that", and dying on a bad rope key beats @@ -2845,19 +2847,24 @@ int main(int argc, char** argv) { std::string gguf_rope_type; double gguf_rope_base = 0, gguf_rope_factor = 0, gguf_rope_orig_ctx = 0; if (!o.native_preset.empty()) { - // a pruned variant (GSQ-RCO Coder) ships fewer experts than the canonical 512x10; the model file - // is the authority on its own MoE shape - everything else in the geometry is unchanged + // the model file is the authority on its own geometry; the kernels' compiled shape is checked against + // it before any weight moves, naming the key that differs try { strata::GgufFile model_gguf(o.native_shards.front()); // the metadata shard - if (const strata::MetaValue* v = model_gguf.get("qwen4exp.expert_count")) g.n_expert = (int64_t) v->u; - if (const strata::MetaValue* v = model_gguf.get("qwen4exp.expert_used_count")) K = (int64_t) v->u; + std::string gerr = strata::read_geometry(model_gguf, g); + if (gerr.empty()) gerr = strata::geometry_unsupported(g); + if (!gerr.empty()) { + std::fprintf(stderr, "strata generate: %s: %s\n", o.native_shards.front().c_str(), gerr.c_str()); + return 1; + } + K = g.n_expert_used; if (const strata::MetaValue* v = model_gguf.get("qwen4exp.rope.freq_base")) gguf_rope_base = v->num(); if (const strata::MetaValue* v = model_gguf.get("qwen4exp.rope.scaling.type")) gguf_rope_type = v->s; if (const strata::MetaValue* v = model_gguf.get("qwen4exp.rope.scaling.factor")) gguf_rope_factor = v->num(); if (const strata::MetaValue* v = model_gguf.get("qwen4exp.rope.scaling.original_context_length")) gguf_rope_orig_ctx = v->num(); } catch (const std::exception& e) { - std::fprintf(stderr, "strata generate: reading the model's expert shape from %s: %s\n", + std::fprintf(stderr, "strata generate: reading the model's geometry from %s: %s\n", o.native_preset.c_str(), e.what()); return 1; } @@ -2942,10 +2949,9 @@ int main(int argc, char** argv) { "and --prefill CHUNK\n", o.pack.c_str()); return 2; } - const strata::core::ModelGeometry g0; const auto embed_t0 = std::chrono::steady_clock::now(); - if (!native_embed.load(o.embd_gguf.empty() ? o.native_shards : std::vector{o.embd_gguf}, g0.n_embd, - 248320, err)) { + if (!native_embed.load(o.embd_gguf.empty() ? o.native_shards : std::vector{o.embd_gguf}, g.n_embd, + g.n_vocab, err)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } diff --git a/sycl/src/core/layer.cpp b/sycl/src/core/layer.cpp index 5cb981f8..78adeb54 100644 --- a/sycl/src/core/layer.cpp +++ b/sycl/src/core/layer.cpp @@ -563,9 +563,7 @@ bool moe_layer(const WeightTable& tables, const ModelGeometry& g, int64_t layer, if (!moe_route(tables, g, layer, k, b, x, stream, err, db)) return false; return moe_finish(tables, g, layer, k, b, x, parts, out, stream, err);} // ================================ the QSA mixer ================================ namespace {using strata::kernels::QsaIndexerBuffers;using strata::kernels::QsaShapes; -/// The geometry the QSA kernels want, from the one place that defines it. `ModelGeometry` carries the widths -/// the LAYOUT needs; `QsaShapes` adds `n_rot`, `idx_block` and `idx_top_k`, which are kernel contracts. -QsaShapes qsa_shapes(const ModelGeometry& g) { QsaShapes s = strata::kernels::qsa_real_shapes(); s.n_head = g.n_head; s.n_head_kv = g.n_head_kv; s.head_dim = g.head_dim; s.idx_n_head = g.idx_q_heads; s.idx_dim = g.idx_key_dim; return s;} +// `qsa_shapes(g)` (layout.hpp): the geometry the QSA kernels want, every field from the model's geometry uint64_t align_up16(uint64_t n) { return (n + 15) & ~15ull; } /// One cursor over an arena, so every region is 16-byte aligned without a list of hand-added offsets. struct Cursor { uint8_t* p; uint64_t used = 0; template T* take(uint64_t count) { T* r = (T*) (p + used); used = align_up16(used + count * sizeof(T)); return r; } uint8_t* take_bytes(uint64_t n) { uint8_t* r = p + used; used = align_up16(used + n); return r; }}; diff --git a/sycl/src/core/mtp.cpp b/sycl/src/core/mtp.cpp index 2d97cc3c..773f54f5 100644 --- a/sycl/src/core/mtp.cpp +++ b/sycl/src/core/mtp.cpp @@ -99,15 +99,7 @@ catch (sycl::exception const &exc) { std::exit(1); } -strata::kernels::QsaShapes shapes_of(const ModelGeometry& g) { - strata::kernels::QsaShapes s = strata::kernels::qsa_real_shapes(); - s.n_head = g.n_head; - s.n_head_kv = g.n_head_kv; - s.head_dim = g.head_dim; - s.idx_n_head = g.idx_q_heads; - s.idx_dim = g.idx_key_dim; - return s; -} +strata::kernels::QsaShapes shapes_of(const ModelGeometry& g) { return qsa_shapes(g); } // 64-bit seek/tell on a `FILE*`: `fseek`/`ftell` take a 32-bit `long` on Windows and would wrap past 2 GiB. #if defined(_WIN32) diff --git a/sycl/src/core/session.cpp b/sycl/src/core/session.cpp index 9edd8082..933468cf 100644 --- a/sycl/src/core/session.cpp +++ b/sycl/src/core/session.cpp @@ -183,12 +183,7 @@ void gdn_point_at(const ModelGeometry& g, int64_t layer, SessionState& s) { /// The per-token staging every QSA layer's captured H2D reads FROM. Must run before each replay: the graphs /// captured the SOURCE POINTER, not the value, and that is exactly why the buffers are pinned and fixed. void stage_token(const ModelGeometry& g, int64_t pos, int32_t pos_base, SessionState& s) { - strata::kernels::QsaShapes sh = strata::kernels::qsa_real_shapes(); - sh.n_head = g.n_head; - sh.n_head_kv = g.n_head_kv; - sh.head_dim = g.head_dim; - sh.idx_n_head = g.idx_q_heads; - sh.idx_dim = g.idx_key_dim; + const strata::kernels::QsaShapes sh = qsa_shapes(g); for (int64_t j = 0; j < s.qsa_alloc; ++j) { QsaState& q = s.qsa_states[s.qsa_ord0 + j]; qsa_step_fill(q.host_step, pos, sh); diff --git a/sycl/src/core/verify.cpp b/sycl/src/core/verify.cpp index 71f8cce9..93728004 100644 --- a/sycl/src/core/verify.cpp +++ b/sycl/src/core/verify.cpp @@ -246,15 +246,7 @@ catch (sycl::exception const &exc) { std::exit(1); } -strata::kernels::QsaShapes shapes_of(const ModelGeometry& g) { - strata::kernels::QsaShapes s = strata::kernels::qsa_real_shapes(); - s.n_head = g.n_head; - s.n_head_kv = g.n_head_kv; - s.head_dim = g.head_dim; - s.idx_n_head = g.idx_q_heads; - s.idx_dim = g.idx_key_dim; - return s; -} +strata::kernels::QsaShapes shapes_of(const ModelGeometry& g) { return qsa_shapes(g); } const WeightRef* need(const LayerView& v, const char* suffix, std::string& err) { const WeightRef* r = v.get(suffix); diff --git a/sycl/src/kernels/cuda/fused_gdn.dp.cpp b/sycl/src/kernels/cuda/fused_gdn.dp.cpp index ba549952..8ce9ff3b 100644 --- a/sycl/src/kernels/cuda/fused_gdn.dp.cpp +++ b/sycl/src/kernels/cuda/fused_gdn.dp.cpp @@ -1,6 +1,7 @@ // src/kernels/cuda/fused_gdn.cu - see include/strata/kernels/fused_gdn.hpp. #define DPCT_PROFILING_ENABLED #include +#include "strata/core/geometry.hpp" #include #include "strata/sycl_queue.hpp" #include "strata/kernels/fused_gdn.hpp" @@ -12,6 +13,7 @@ namespace strata::kernels { namespace { constexpr int S = 128; // state size (rows = cols = 128) +static_assert(S == strata::core::kCompiledGeometry.ssm_state_size, "fused_gdn is compiled for core/geometry.hpp"); constexpr int RG = 4; // row groups constexpr int RPG = S / RG; // 32 rows per thread diff --git a/sycl/src/kernels/cuda/fused_gr.dp.cpp b/sycl/src/kernels/cuda/fused_gr.dp.cpp index 2c8d1246..ef018e2d 100644 --- a/sycl/src/kernels/cuda/fused_gr.dp.cpp +++ b/sycl/src/kernels/cuda/fused_gr.dp.cpp @@ -1,6 +1,7 @@ // src/kernels/cuda/fused_gr.cu - see include/strata/kernels/fused_gr.hpp. #define DPCT_PROFILING_ENABLED #include +#include "strata/core/geometry.hpp" #include #include #include @@ -25,6 +26,7 @@ constexpr int N = 2560; // n_embd constexpr int HC = 4; // streams constexpr int D = N * HC; // 10240 constexpr int LR = 320; // hc_lr +static_assert(N == strata::core::kCompiledGeometry.n_embd && HC == strata::core::kCompiledGeometry.hc && LR == strata::core::kCompiledGeometry.hc_lr, "fused_gr is compiled for core/geometry.hpp"); constexpr int THREADS = 256; constexpr int WARPS = THREADS / 32; #if defined(__HIPCC__) diff --git a/sycl/src/kernels/cuda/native_gdn.dp.cpp b/sycl/src/kernels/cuda/native_gdn.dp.cpp index 4faf25a3..4099841a 100644 --- a/sycl/src/kernels/cuda/native_gdn.dp.cpp +++ b/sycl/src/kernels/cuda/native_gdn.dp.cpp @@ -25,6 +25,7 @@ // SOFTWARE. #define DPCT_PROFILING_ENABLED #include +#include "strata/core/geometry.hpp" #include #include "strata/sycl_queue.hpp" #include "strata/kernels/native_gdn.hpp" @@ -38,6 +39,7 @@ namespace strata::kernels { namespace { std::atomic enabled{false}; constexpr int S = 128; +static_assert(S == strata::core::kCompiledGeometry.ssm_state_size, "native_gdn is compiled for core/geometry.hpp"); __dpct_inline__ float warp_sum(float value) { #pragma unroll diff --git a/sycl/src/kernels/cuda/native_ple_postops.dp.cpp b/sycl/src/kernels/cuda/native_ple_postops.dp.cpp index a55748bd..12101526 100644 --- a/sycl/src/kernels/cuda/native_ple_postops.dp.cpp +++ b/sycl/src/kernels/cuda/native_ple_postops.dp.cpp @@ -20,6 +20,7 @@ #define DPCT_PROFILING_ENABLED #include +#include "strata/core/geometry.hpp" #include #include "strata/sycl_queue.hpp" #include "strata/kernels/native_ple_postops.hpp" @@ -35,6 +36,7 @@ namespace strata::kernels { namespace { constexpr int N = 2560, H = 4, D = N * H, HISTORY = 9; +static_assert(N == strata::core::kCompiledGeometry.n_embd && H == strata::core::kCompiledGeometry.hc, "native_ple_postops is compiled for core/geometry.hpp"); inline float warp_sum(float x) { /* DPCT1108: '__shfl_xor_sync' was migrated with the experimental feature masked diff --git a/sycl/src/kernels/cuda/native_qsa_indexer.dp.cpp b/sycl/src/kernels/cuda/native_qsa_indexer.dp.cpp index c1d89635..c63948f6 100644 --- a/sycl/src/kernels/cuda/native_qsa_indexer.dp.cpp +++ b/sycl/src/kernels/cuda/native_qsa_indexer.dp.cpp @@ -20,6 +20,7 @@ #define DPCT_PROFILING_ENABLED #include +#include "strata/core/geometry.hpp" #include #include "strata/sycl_queue.hpp" #include "strata/kernels/native_qsa_indexer.hpp" @@ -35,6 +36,8 @@ namespace strata::kernels { namespace { std::atomic enabled{false}; constexpr int D = 128, R = 4, ROT = 64, THREADS = 256; +static_assert(D == strata::core::kCompiledGeometry.idx_key_dim && R == strata::core::kCompiledGeometry.idx_block && ROT == strata::core::kCompiledGeometry.n_rot, + "native_qsa_indexer is compiled for core/geometry.hpp"); inline float warp_sum(float x) { #pragma unroll for (int offset = 16; offset; offset >>= 1) diff --git a/sycl/src/kernels/cuda/native_qsa_score.dp.cpp b/sycl/src/kernels/cuda/native_qsa_score.dp.cpp index fe729bc0..d15b3ed7 100644 --- a/sycl/src/kernels/cuda/native_qsa_score.dp.cpp +++ b/sycl/src/kernels/cuda/native_qsa_score.dp.cpp @@ -20,6 +20,7 @@ #define DPCT_PROFILING_ENABLED #include +#include "strata/core/geometry.hpp" #include #include "strata/sycl_queue.hpp" #include "strata/kernels/native_qsa_score.hpp" @@ -32,6 +33,8 @@ namespace strata::kernels { namespace { std::atomic enabled{false}; constexpr int D=128, HEADS=4, R=4, ROWS=32, WARPS=2, STRIDE=36, COMBINE=68; +static_assert(D == strata::core::kCompiledGeometry.idx_key_dim && HEADS == strata::core::kCompiledGeometry.idx_q_heads && R == strata::core::kCompiledGeometry.idx_block, + "native_qsa_score is compiled for core/geometry.hpp"); struct TileA { uint32_t x[4]; }; struct TileB { uint32_t x[2]; }; struct TileC { float x[4]={0.0f,0.0f,0.0f,0.0f}; }; diff --git a/sycl/src/kernels/cuda/qsa_decode_attn.dp.cpp b/sycl/src/kernels/cuda/qsa_decode_attn.dp.cpp index 552c4a7d..c4c3d8c6 100644 --- a/sycl/src/kernels/cuda/qsa_decode_attn.dp.cpp +++ b/sycl/src/kernels/cuda/qsa_decode_attn.dp.cpp @@ -1,6 +1,7 @@ // src/kernels/cuda/qsa_decode_attn.cu - see include/strata/kernels/qsa_decode_attn.hpp. #define DPCT_PROFILING_ENABLED #include +#include "strata/core/geometry.hpp" #include #include "strata/sycl_queue.hpp" #include "strata/kernels/qsa_decode_attn.hpp" @@ -17,6 +18,7 @@ namespace { constexpr int HD = 256; // head_dim constexpr int G = 12; // query heads per KV head (24 / 2) +static_assert(HD == strata::core::kCompiledGeometry.head_dim && G == strata::core::kCompiledGeometry.n_head / strata::core::kCompiledGeometry.n_head_kv, "qsa_decode_attn is compiled for core/geometry.hpp"); constexpr int CHUNK = 64; // cells per block constexpr int THREADS = 256; constexpr int WARPS = THREADS / 32; diff --git a/sycl/src/kernels/cuda/qsa_prompt_attn.dp.cpp b/sycl/src/kernels/cuda/qsa_prompt_attn.dp.cpp index f4a6533b..e459919a 100644 --- a/sycl/src/kernels/cuda/qsa_prompt_attn.dp.cpp +++ b/sycl/src/kernels/cuda/qsa_prompt_attn.dp.cpp @@ -1,6 +1,7 @@ // src/kernels/cuda/qsa_prompt_attn.cu - see include/strata/kernels/qsa_prompt_attn.hpp. #define DPCT_PROFILING_ENABLED #include +#include "strata/core/geometry.hpp" #include #include "strata/sycl_queue.hpp" #include "strata/core/emulate.hpp" @@ -24,6 +25,7 @@ namespace { constexpr int HD = 256; // head_dim constexpr int G = 12; // query heads per KV head +static_assert(HD == strata::core::kCompiledGeometry.head_dim && G == strata::core::kCompiledGeometry.n_head / strata::core::kCompiledGeometry.n_head_kv, "qsa_prompt_attn is compiled for core/geometry.hpp"); #ifndef D1_CH #define D1_CH 32 #endif diff --git a/sycl/src/kernels/cuda/qsa_prompt_attn_xmx.dp.cpp b/sycl/src/kernels/cuda/qsa_prompt_attn_xmx.dp.cpp index 15516ee7..1aa9d2d3 100644 --- a/sycl/src/kernels/cuda/qsa_prompt_attn_xmx.dp.cpp +++ b/sycl/src/kernels/cuda/qsa_prompt_attn_xmx.dp.cpp @@ -13,6 +13,7 @@ // K^T packed as 4-byte pairs with INT8 converted on the load, hi and lo halves of Q accumulated into one accumulator per // scale group, and one accumulator update per chunk after the whole P.V product has run in registers. #include "strata/kernels/qsa_prompt_attn_xmx.hpp" +#include "strata/core/geometry.hpp" #include "strata/kernels/qsa_decode_attn.hpp" #include "strata/kernels/qsa.hpp" #include "strata/kernels/kv_q8.hpp" @@ -29,6 +30,8 @@ namespace strata::kernels { namespace { namespace jm = sycl::ext::oneapi::experimental::matrix; constexpr int HD = 256, G = 12, SG = 16, NSG = 8, THREADS = SG * NSG, QS = HD + 8; +static_assert(HD == strata::core::kCompiledGeometry.head_dim && G == strata::core::kCompiledGeometry.n_head / strata::core::kCompiledGeometry.n_head_kv, + "qsa_prompt_attn_xmx is compiled for core/geometry.hpp"); constexpr int QK4_0 = 32; struct q4_0_block { uint16_t d; uint8_t qs[QK4_0 / 2]; }; diff --git a/sycl/src/kernels/cuda/qsa_select.dp.cpp b/sycl/src/kernels/cuda/qsa_select.dp.cpp index 481963bf..adafc898 100644 --- a/sycl/src/kernels/cuda/qsa_select.dp.cpp +++ b/sycl/src/kernels/cuda/qsa_select.dp.cpp @@ -1,6 +1,7 @@ // src/kernels/cuda/qsa_select.cu - see include/strata/kernels/qsa_select.hpp. #define DPCT_PROFILING_ENABLED #include +#include "strata/core/geometry.hpp" #include #include "strata/sycl_queue.hpp" #include "strata/core/emulate.hpp" @@ -18,6 +19,8 @@ namespace strata::kernels { namespace { constexpr int IDX_DIM = 128, IDX_HEADS = 4, R = 4; +static_assert(IDX_DIM == strata::core::kCompiledGeometry.idx_key_dim && IDX_HEADS == strata::core::kCompiledGeometry.idx_q_heads && R == strata::core::kCompiledGeometry.idx_block, + "qsa_select is compiled for core/geometry.hpp"); constexpr int SCORE_WARPS = 8; constexpr int TOPK_T = 256; diff --git a/sycl/src/kernels/cuda/s2_expert_grouped.dp.cpp b/sycl/src/kernels/cuda/s2_expert_grouped.dp.cpp index 2da553b6..ec445df9 100644 --- a/sycl/src/kernels/cuda/s2_expert_grouped.dp.cpp +++ b/sycl/src/kernels/cuda/s2_expert_grouped.dp.cpp @@ -15,6 +15,7 @@ // the same reason. `bench/micro/moe_hit_parity.cu` is the check. #define DPCT_PROFILING_ENABLED #include +#include "strata/core/geometry.hpp" #include #include "strata/sycl_math.hpp" #include "strata/sycl_queue.hpp" @@ -39,6 +40,7 @@ namespace { // are what the CPU kernel's indexing computes, and `moe_hit_parity` compares the two end to end. constexpr int H = 2560; constexpr int FF = 640; +static_assert(H == strata::core::kCompiledGeometry.n_embd && FF == strata::core::kCompiledGeometry.n_ff, "s2_expert_grouped is compiled for core/geometry.hpp"); constexpr int QK = 64; // Q2_0's group: one fp16 scale per 64 weights constexpr int ROW_GU = H / 4; // 640 B of codes per gate/up row (2 bits per element) constexpr int ROW_D = FF / 4; // 160 B per down row diff --git a/sycl/src/kernels/cuda/verify_kernels.dp.cpp b/sycl/src/kernels/cuda/verify_kernels.dp.cpp index 558477f9..a268cd69 100644 --- a/sycl/src/kernels/cuda/verify_kernels.dp.cpp +++ b/sycl/src/kernels/cuda/verify_kernels.dp.cpp @@ -4,6 +4,7 @@ // elementwise.cu) with the same operation order, so a verify window reproduces plain decode bit for bit. #define DPCT_PROFILING_ENABLED #include +#include "strata/core/geometry.hpp" #include #include "strata/sycl_queue.hpp" #include "strata/sycl_doorbell.hpp" @@ -30,6 +31,7 @@ namespace strata::kernels { namespace { constexpr int S = 128; // GDN state size +static_assert(S == strata::core::kCompiledGeometry.ssm_state_size, "verify_kernels is compiled for core/geometry.hpp"); constexpr int RG = 4; constexpr int RPG = S / RG; diff --git a/sycl/src/prefill/prefill.cpp b/sycl/src/prefill/prefill.cpp index 93bde7dd..bebb039f 100644 --- a/sycl/src/prefill/prefill.cpp +++ b/sycl/src/prefill/prefill.cpp @@ -1164,9 +1164,7 @@ bool Prefill::carve(size_t T, void* alloc) { if (bf16x2_hc(m.f16_io)) { m.xn16_lo = o.take(T * D, ok); m.lo16_lo = o.take(T * LR, ok); } if (bf16x2(m.f16_io)) m.mixed_bf_lo = o.take(T * N, ok); m.steps_dev = o.take(T * strata::kernels::kStepCount, ok); - strata::kernels::QsaShapes s = strata::kernels::qsa_real_shapes(); - s.n_head = g.n_head; s.n_head_kv = g.n_head_kv; s.head_dim = g.head_dim; s.idx_n_head = g.idx_q_heads; - s.idx_dim = g.idx_key_dim; + strata::kernels::QsaShapes s = core::qsa_shapes(g); m.cap = strata::kernels::qsa_selection_width(strata::kernels::kTopkMaxCells, s); m.max_blocks = ss.qsa_states[ss.qsa_primary()].max_cells / s.idx_block + 2; { @@ -1384,9 +1382,7 @@ bool Prefill::draft_kv(core::MtpDrafter& mtp, const float* R_rows, const int32_t if (!mtp.idle(err)) return false; // the drafter's own stream (its graph uploads) before this writes its K/V const double ms_idle = ms_since(ti0); const auto tl0 = Clock::now(); - strata::kernels::QsaShapes s = strata::kernels::qsa_real_shapes(); - s.n_head = g.n_head; s.n_head_kv = g.n_head_kv; s.head_dim = g.head_dim; s.idx_n_head = g.idx_q_heads; - s.idx_dim = g.idx_key_dim; + strata::kernels::QsaShapes s = core::qsa_shapes(g); std::vector tk((size_t) B); if (q8) { if (!m.mmq_ctx) m.mmq_ctx = std::make_unique(); @@ -1888,9 +1884,7 @@ uint64_t Prefill::bytes_needed_impl(const core::ModelGeometry& g, const core::Se if (bf16x2_hc(f16_io)) { o.take(T * D, ok); o.take(T * LR, ok); } if (bf16x2(f16_io)) o.take(T * N, ok); o.take(T * strata::kernels::kStepCount, ok); - strata::kernels::QsaShapes s = strata::kernels::qsa_real_shapes(); - s.n_head = g.n_head; s.n_head_kv = g.n_head_kv; s.head_dim = g.head_dim; s.idx_n_head = g.idx_q_heads; - s.idx_dim = g.idx_key_dim; + strata::kernels::QsaShapes s = core::qsa_shapes(g); const int64_t cap = strata::kernels::qsa_selection_width(strata::kernels::kTopkMaxCells, s); const int64_t max_blocks = ss.qsa_states[ss.qsa_primary()].max_cells / s.idx_block + 2; o.take((size_t) std::max({gdn_set_bytes(T), qsa_set_bytes(T, cap, max_blocks, 256, 32, s), @@ -2111,9 +2105,7 @@ bool Prefill::run_impl(const int64_t *tokens, int64_t n, int64_t pos0, // stages therefore do not drain the complete remaining GPU chain here. double host_sync_ms = 0, host_chunk_ms = 0, host_setup_ms = 0; // STRATA_PREFILL_TIMING: the host's share double grp_wait_ms = 0, grp_cpu_ms = 0; // the per-layer grouping: the drain wait, the host's loops - strata::kernels::QsaShapes s = strata::kernels::qsa_real_shapes(); - s.n_head = g.n_head; s.n_head_kv = g.n_head_kv; s.head_dim = g.head_dim; s.idx_n_head = g.idx_q_heads; - s.idx_dim = g.idx_key_dim; + strata::kernels::QsaShapes s = core::qsa_shapes(g); // read once (STRATA_KV_PREFETCH=1/0: the next streamed layer's KV prefix is staged on its own stream) static const bool kv_prefetch_on = [] { const char* e = std::getenv("STRATA_KV_PREFETCH"); diff --git a/sycl/src/program/generate.cpp b/sycl/src/program/generate.cpp index 666a35c4..9f1d3783 100644 --- a/sycl/src/program/generate.cpp +++ b/sycl/src/program/generate.cpp @@ -2606,8 +2606,10 @@ int main(int argc, char **argv) try { "(multi-token for the i-quant gate/up rows)\n", !strata::kernels::cpu::cpu_avx2_ok() ? "ggml-cpu vec_dot (no AVX2: the older-CPU build)" : std::getenv("STRATA_NO_IQ256") == nullptr ? "AVX-2" : "ggml-cpu vec_dot (STRATA_NO_IQ256 set)"); - strata::core::ModelGeometry g; // canonical defaults; the model file overrides the MoE shape below - int64_t K = 10; + // the compiled shape; a native model's file replaces it below with its own metadata (read_geometry), which a + // pruned variant (GSQ-RCO Coder, fewer than 512 experts) differs from + strata::core::ModelGeometry g; + int64_t K = g.n_expert_used; // THE ROPE CONFIG RESOLVES HERE, BEFORE ANY WEIGHT MOVES - the CLI and the model file have both spoken, // and `session_init` below builds the rope table from it and captures the kernels reading its constants // (rope_scaling.hpp); the only hard constraint is "set before that", and dying on a bad rope key beats @@ -2620,19 +2622,24 @@ int main(int argc, char **argv) try { std::string gguf_rope_type; double gguf_rope_base = 0, gguf_rope_factor = 0, gguf_rope_orig_ctx = 0; if (!o.native_preset.empty()) { - // a pruned variant (GSQ-RCO Coder) ships fewer experts than the canonical 512x10; the model file - // is the authority on its own MoE shape - everything else in the geometry is unchanged + // the model file is the authority on its own geometry; the kernels' compiled shape is checked against + // it before any weight moves, naming the key that differs try { strata::GgufFile model_gguf(o.native_shards.front()); // the metadata shard - if (const strata::MetaValue* v = model_gguf.get("qwen4exp.expert_count")) g.n_expert = (int64_t) v->u; - if (const strata::MetaValue* v = model_gguf.get("qwen4exp.expert_used_count")) K = (int64_t) v->u; + std::string gerr = strata::read_geometry(model_gguf, g); + if (gerr.empty()) gerr = strata::geometry_unsupported(g); + if (!gerr.empty()) { + std::fprintf(stderr, "strata generate: %s: %s\n", o.native_shards.front().c_str(), gerr.c_str()); + return 1; + } + K = g.n_expert_used; if (const strata::MetaValue* v = model_gguf.get("qwen4exp.rope.freq_base")) gguf_rope_base = v->num(); if (const strata::MetaValue* v = model_gguf.get("qwen4exp.rope.scaling.type")) gguf_rope_type = v->s; if (const strata::MetaValue* v = model_gguf.get("qwen4exp.rope.scaling.factor")) gguf_rope_factor = v->num(); if (const strata::MetaValue* v = model_gguf.get("qwen4exp.rope.scaling.original_context_length")) gguf_rope_orig_ctx = v->num(); } catch (const std::exception& e) { - std::fprintf(stderr, "strata generate: reading the model's expert shape from %s: %s\n", + std::fprintf(stderr, "strata generate: reading the model's geometry from %s: %s\n", o.native_preset.c_str(), e.what()); return 1; } @@ -2717,10 +2724,9 @@ int main(int argc, char **argv) try { "and --prefill CHUNK\n", o.pack.c_str()); return 2; } - const strata::core::ModelGeometry g0; const auto embed_t0 = std::chrono::steady_clock::now(); - if (!native_embed.load(o.embd_gguf.empty() ? o.native_shards : std::vector{o.embd_gguf}, g0.n_embd, - 248320, err)) { + if (!native_embed.load(o.embd_gguf.empty() ? o.native_shards : std::vector{o.embd_gguf}, g.n_embd, + g.n_vocab, err)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } diff --git a/tests/core/gguf_fixture.hpp b/tests/core/gguf_fixture.hpp index 677a5cd8..30c67bbf 100644 --- a/tests/core/gguf_fixture.hpp +++ b/tests/core/gguf_fixture.hpp @@ -1,6 +1,6 @@ // tests/core/gguf_fixture.hpp - synthetic GGUF v3 files for the loader tests (no gguf-py, no model, no GPU). // -// A file is a header, metadata (strings and integers only), a tensor directory whose offsets are 32-byte aligned +// A file is a header, metadata (strings, integers, f32, and arrays of u32 or strings), a tensor directory whose offsets are 32-byte aligned // in the data section, and the tensors' payloads, each filled with a pattern the test can recognise. #pragma once @@ -18,14 +18,26 @@ namespace fixture { struct Kv { std::string key; - uint32_t type = 8; ///< GGUF value type: 8 string, 2 u16, 4 u32, 5 i32 + uint32_t type = 8; ///< GGUF value type: 8 string, 2 u16, 4 u32, 5 i32, 6 f32, 9 array std::string s; uint64_t u = 0; + float f = 0; + uint32_t elem = 4; ///< arrays: 4 u32 (`arr`) or 8 string (`sarr`) + std::vector arr; + std::vector sarr; }; inline Kv str(const std::string& k, const std::string& v) { return Kv{k, 8, v, 0}; } inline Kv u16(const std::string& k, uint64_t v) { return Kv{k, 2, {}, v}; } inline Kv i32(const std::string& k, uint64_t v) { return Kv{k, 5, {}, v}; } inline Kv u32(const std::string& k, uint64_t v) { return Kv{k, 4, {}, v}; } +inline Kv f32(const std::string& k, float v) { Kv r{k, 6}; r.f = v; return r; } +inline Kv u32s(const std::string& k, std::vector v) { Kv r{k, 9}; r.arr = std::move(v); return r; } +inline Kv strs(const std::string& k, std::vector v) { + Kv r{k, 9}; + r.elem = 8; + r.sarr = std::move(v); + return r; +} struct Tensor { std::string name; @@ -65,7 +77,16 @@ inline Written write(const std::filesystem::path& path, const std::vector& k if (k.type == 8) puts(k.s); else if (k.type == 2) { const uint16_t v = (uint16_t) k.u; put(&v, 2); } else if (k.type == 4 || k.type == 5) { const uint32_t v = (uint32_t) k.u; put(&v, 4); } - else throw std::runtime_error("fixture: unsupported metadata type"); + else if (k.type == 6) put(&k.f, 4); + else if (k.type == 9 && k.elem == 4) { + put32(4); + put64(k.arr.size()); + for (uint64_t x : k.arr) put32((uint32_t) x); + } else if (k.type == 9 && k.elem == 8) { + put32(8); + put64(k.sarr.size()); + for (const auto& x : k.sarr) puts(x); + } else throw std::runtime_error("fixture: unsupported metadata type"); } Written w; std::vector bytes; diff --git a/tests/core/gguf_geometry_test.cpp b/tests/core/gguf_geometry_test.cpp new file mode 100644 index 00000000..564a46a7 --- /dev/null +++ b/tests/core/gguf_geometry_test.cpp @@ -0,0 +1,258 @@ +// tests/core/gguf_geometry_test.cpp - the model's geometry from its GGUF metadata (strata::read_geometry) and the +// check against the shape the kernels are compiled for (strata::geometry_unsupported, check_architecture), on +// synthetic GGUFs: no model, no GPU. +// +// The full key set is the one Unsloth's Qwen3.8-Flash-Next UD-IQ4_XS carries (read from its first shard). Then +// the cases: a file with only the six keys the guard has always required, a pruned expert count, keys that +// describe one thing twice and disagree, and a shape the kernels are not compiled for. +// +// `gguf_geometry_test --real SHARD1`: the geometry a real model's metadata shard declares, and the verdict. +#include "gguf_fixture.hpp" + +#include +#include +#include +#include +#include +#include + +namespace fs = std::filesystem; +using strata::core::ModelGeometry; + +namespace { +int g_fail = 0; +void check(bool ok, const std::string& what) { + std::printf(" %-90s %s\n", what.c_str(), ok ? "ok" : "FAIL"); + if (!ok) ++g_fail; +} + +struct TempDir { + fs::path path; + TempDir() { + path = fs::temp_directory_path() / + ("strata-gguf-geometry-test-" + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count())); + fs::create_directories(path); + } + ~TempDir() { + std::error_code ignored; + fs::remove_all(path, ignored); + } +}; + +std::vector ratios(int64_t layers, int64_t interval, uint64_t block) { + std::vector r((size_t) layers, 0); + for (int64_t l = 0; l < layers; ++l) + if (l % interval == interval - 1) r[(size_t) l] = block; + return r; +} + +/// Qwen3.8-Flash-Next's metadata as its GGUF carries it (the PLE and rope-section keys the reader does not use +/// are left out), with a vocabulary of `vocab` tokens. +std::vector full_keys(size_t vocab = 1000) { + using namespace fixture; + const std::string p = "qwen4exp."; + std::vector tokens(vocab); + for (size_t i = 0; i < vocab; ++i) tokens[i] = "t" + std::to_string(i); + return {str("general.architecture", "qwen4exp"), + u32(p + "block_count", 48), + u32(p + "context_length", 262144), + u32(p + "embedding_length", 2560), + u32(p + "attention.head_count", 24), + u32(p + "attention.head_count_kv", 2), + f32(p + "rope.freq_base", 1e7f), + f32(p + "attention.layer_norm_rms_epsilon", 1e-6f), + u32(p + "expert_count", 512), + u32(p + "expert_used_count", 10), + u32(p + "attention.key_length", 256), + u32(p + "attention.value_length", 256), + u32(p + "expert_feed_forward_length", 640), + u32(p + "expert_shared_feed_forward_length", 640), + u32(p + "ssm.conv_kernel", 4), + u32(p + "ssm.state_size", 128), + u32(p + "ssm.group_count", 16), + u32(p + "ssm.time_step_rank", 48), + u32(p + "ssm.inner_size", 6144), + u32(p + "full_attention_interval", 4), + u32(p + "rope.dimension_count", 64), + u32(p + "hyper_connection.count", 4), + u32(p + "hyper_connection.low_rank", 320), + u32(p + "attention.indexer.head_count", 4), + u32(p + "attention.indexer.key_length", 128), + u32(p + "attention.indexer.top_k", 2048), + u32s(p + "attention.compress_ratios", ratios(48, 4, 4)), + str("tokenizer.ggml.model", "gpt2"), + strs("tokenizer.ggml.tokens", tokens)}; +} + +/// `kv` with `key` replaced by `v` (or removed, when `v` is null). +std::vector with(std::vector kv, const std::string& key, const fixture::Kv* v) { + for (auto it = kv.begin(); it != kv.end(); ++it) + if (it->key == key) { + if (v) *it = *v; + else kv.erase(it); + return kv; + } + if (v) kv.push_back(*v); + return kv; +} + +struct Result { + std::string read_err, unsupported, guard; + ModelGeometry g; +}; +Result run(const fs::path& dir, const std::vector& kv) { + static int n = 0; + const fs::path p = dir / ("m" + std::to_string(n++) + ".gguf"); + fixture::write(p, kv, {}); + Result r; + const strata::GgufFile f(p.string()); + r.read_err = strata::read_geometry(f, r.g); + if (r.read_err.empty()) r.unsupported = strata::geometry_unsupported(r.g); + r.guard = strata::check_architecture(f); + return r; +} +bool has(const std::string& s, const char* part) { return s.find(part) != std::string::npos; } + +bool same_shape(const ModelGeometry& a, const ModelGeometry& b) { + return a.n_embd == b.n_embd && a.n_layers == b.n_layers && a.qsa_interval == b.qsa_interval && + a.n_vocab == b.n_vocab && a.ssm_state_size == b.ssm_state_size && a.ssm_k_heads == b.ssm_k_heads && + a.ssm_v_heads == b.ssm_v_heads && a.ssm_d_conv == b.ssm_d_conv && + a.ssm_conv_channels == b.ssm_conv_channels && a.ssm_value_dim == b.ssm_value_dim && a.n_head == b.n_head && + a.n_head_kv == b.n_head_kv && a.head_dim == b.head_dim && a.n_rot == b.n_rot && + a.idx_q_heads == b.idx_q_heads && a.idx_key_dim == b.idx_key_dim && a.idx_block == b.idx_block && + a.idx_top_k == b.idx_top_k && a.hc == b.hc && a.hc_lr == b.hc_lr && a.n_expert == b.n_expert && + a.n_expert_used == b.n_expert_used && a.n_ff == b.n_ff; +} + +int real_model(const std::string& shard) { + try { + const strata::GgufFile f(shard); + ModelGeometry g; + const std::string err = strata::read_geometry(f, g); + if (!err.empty()) { + std::printf(" refused: %s\n", err.c_str()); + return 1; + } + std::printf(" n_embd %lld, layers %lld (attention every %lld), vocab %lld, rms_eps %g\n", (long long) g.n_embd, + (long long) g.n_layers, (long long) g.qsa_interval, (long long) g.n_vocab, g.rms_eps); + std::printf(" GDN: state %lld, k heads %lld, v heads %lld, conv %lld (%lld channels, values %lld)\n", + (long long) g.ssm_state_size, (long long) g.ssm_k_heads, (long long) g.ssm_v_heads, + (long long) g.ssm_d_conv, (long long) g.ssm_conv_channels, (long long) g.ssm_value_dim); + std::printf(" QSA: heads %lld/%lld x %lld, rope %lld, indexer %lld x %lld, block %lld, top-k %lld\n", + (long long) g.n_head, (long long) g.n_head_kv, (long long) g.head_dim, (long long) g.n_rot, + (long long) g.idx_q_heads, (long long) g.idx_key_dim, (long long) g.idx_block, + (long long) g.idx_top_k); + std::printf(" HC %lld (rank %lld); MoE %lld experts, %lld per token, ff %lld\n", (long long) g.hc, + (long long) g.hc_lr, (long long) g.n_expert, (long long) g.n_expert_used, (long long) g.n_ff); + const std::string why = strata::geometry_unsupported(g); + std::printf(" the compiled kernels: %s\n", why.empty() ? "can run it" : why.c_str()); + return why.empty() ? 0 : 1; + } catch (const std::exception& e) { + std::printf(" refused: %s\n", e.what()); + return 1; + } +} +} // namespace + +int main(int argc, char** argv) { + if (argc == 3 && std::string(argv[1]) == "--real") return real_model(argv[2]); + std::printf("gguf_geometry_test\n"); + TempDir d; + const std::string p = "qwen4exp."; + { + const Result r = run(d.path, full_keys()); + ModelGeometry want = strata::core::kCompiledGeometry; + want.n_vocab = 1000; + check(r.read_err.empty(), "the full key set reads" + (r.read_err.empty() ? "" : ": " + r.read_err)); + check(same_shape(r.g, want), " and gives the compiled shape (vocabulary from tokenizer.ggml.tokens)"); + check(r.g.ssm_conv_channels == 10240, " conv channels derived: 2 x 128 x 16 + 6144 = 10240"); + check(r.unsupported.empty() && r.guard.empty(), " which the kernels run, and the guard passes"); + } + { + // the six keys tests/core/native_dense_ple_key_test.cpp writes: everything else is the compiled value + const std::vector six = { + fixture::str("general.architecture", "qwen4exp"), fixture::u32(p + "block_count", 48), + fixture::u32(p + "embedding_length", 2560), fixture::u32(p + "expert_count", 512), + fixture::u32(p + "expert_used_count", 10), fixture::u32(p + "attention.head_count", 24), + fixture::u32(p + "attention.head_count_kv", 2)}; + const Result r = run(d.path, six); + check(r.read_err.empty() && same_shape(r.g, strata::core::kCompiledGeometry) && r.guard.empty(), + "only the six required keys: the rest keeps the compiled values"); + for (const char* key : {"block_count", "embedding_length", "expert_count", "expert_used_count", + "attention.head_count", "attention.head_count_kv"}) { + const Result m = run(d.path, with(six, p + key, nullptr)); + check(has(m.read_err, "missing") && has(m.read_err, key) && m.guard == m.read_err, + std::string("a file without ") + key + " is refused, naming it"); + } + } + { + // GSQ-RCO Coder: fewer experts, read from the file and run by the same kernels + const fixture::Kv e = fixture::u32(p + "expert_count", 384), k = fixture::u32(p + "expert_used_count", 8); + const Result r = run(d.path, with(with(full_keys(), e.key, &e), k.key, &k)); + check(r.read_err.empty() && r.g.n_expert == 384 && r.g.n_expert_used == 8 && r.guard.empty(), + "a pruned variant: 384 experts, 8 per token, read and accepted"); + const fixture::Kv k65 = fixture::u32(p + "expert_used_count", 65); + check(has(run(d.path, with(full_keys(), k65.key, &k65)).read_err, "expert_used_count = 65"), + "65 experts per token is refused (the router takes 1..64)"); + const fixture::Kv k0 = fixture::u32(p + "expert_used_count", 0); + check(has(run(d.path, with(full_keys(), k0.key, &k0)).read_err, "must be positive"), + "0 experts per token is refused"); + } + { + // keys that describe one thing twice must agree + const fixture::Kv vl = fixture::u32(p + "attention.value_length", 128); + check(has(run(d.path, with(full_keys(), vl.key, &vl)).read_err, "attention.value_length = 128"), + "a value head width other than the key head width is refused"); + const fixture::Kv sh = fixture::u32(p + "expert_shared_feed_forward_length", 1280); + check(has(run(d.path, with(full_keys(), sh.key, &sh)).read_err, "expert_shared_feed_forward_length = 1280"), + "a shared expert wider than the routed ones is refused"); + const fixture::Kv in = fixture::u32(p + "ssm.inner_size", 4096); + check(has(run(d.path, with(full_keys(), in.key, &in)).read_err, "square heads"), + "ssm.inner_size other than state_size x time_step_rank is refused"); + std::vector shifted = ratios(48, 4, 4); + shifted[3] = 0; + shifted[2] = 4; + const fixture::Kv cr = fixture::u32s(p + "attention.compress_ratios", shifted); + check(has(run(d.path, with(full_keys(), cr.key, &cr)).read_err, "compress_ratios[2] = 4"), + "compress_ratios that disagree with full_attention_interval are refused at the first layer"); + const fixture::Kv short_cr = fixture::u32s(p + "attention.compress_ratios", ratios(40, 4, 4)); + check(has(run(d.path, with(full_keys(), short_cr.key, &short_cr)).read_err, "one entry for each of the 48"), + "compress_ratios of another length are refused"); + std::vector mixed = ratios(48, 4, 4); + mixed[7] = 8; + const fixture::Kv mx = fixture::u32s(p + "attention.compress_ratios", mixed); + check(has(run(d.path, with(full_keys(), mx.key, &mx)).read_err, "compress_ratios[7] = 8"), + "two pooling blocks in one model are refused"); + const fixture::Kv fl = fixture::f32(p + "block_count", 48.0f); + check(has(run(d.path, with(full_keys(), fl.key, &fl)).read_err, "is not an integer"), + "a float where a count belongs is refused"); + } + { + // a consistent file of another shape reads, and the kernels refuse it naming the key + const fixture::Kv bc = fixture::u32(p + "block_count", 40); + const fixture::Kv cr = fixture::u32s(p + "attention.compress_ratios", ratios(40, 4, 4)); + const Result r = run(d.path, with(with(full_keys(), bc.key, &bc), cr.key, &cr)); + check(r.read_err.empty() && r.g.n_layers == 40 && r.g.n_qsa_layers() == 10, "40 layers read: 10 QSA, 30 GDN"); + check(r.unsupported == "qwen4exp.block_count = 40, the kernels are compiled for 48" && r.guard == r.unsupported, + " and refused: " + r.unsupported); + const fixture::Kv hd = fixture::u32(p + "attention.key_length", 128), vd = fixture::u32(p + "attention.value_length", 128); + const Result h = run(d.path, with(with(full_keys(), hd.key, &hd), vd.key, &vd)); + check(h.read_err.empty() && h.g.head_dim == 128 && has(h.guard, "attention.key_length = 128"), + "head width 128 reads and is refused: " + h.guard); + const fixture::Kv tk = fixture::u32(p + "attention.indexer.top_k", 1024); + check(has(run(d.path, with(full_keys(), tk.key, &tk)).guard, "attention.indexer.top_k = 1024"), + "an indexer budget of 1024 is refused"); + const fixture::Kv eps = fixture::f32(p + "attention.layer_norm_rms_epsilon", 1e-5f); + check(has(run(d.path, with(full_keys(), eps.key, &eps)).guard, "layer_norm_rms_epsilon = 1e-05"), + "an rms epsilon of 1e-5 is refused"); + const fixture::Kv vocab = fixture::u32(p + "embedding_length", 2560); + check(run(d.path, with(full_keys(151936), vocab.key, &vocab)).guard.empty(), + "another vocabulary size is accepted (the head and embedding take their tensors' shapes)"); + const fixture::Kv arch = fixture::str("general.architecture", "glm5next"); + check(run(d.path, with(full_keys(), arch.key, &arch)).guard == + "architecture is 'glm5next', this engine requires 'qwen4exp'", + "another architecture is refused by name"); + } + std::printf(g_fail ? "gguf_geometry_test: %d FAILED\n" : "gguf_geometry_test: all passed\n", g_fail); + return g_fail ? 1 : 0; +} From fc72322bd13f1e9bca83090f2ca1b5b0d010ca55 Mon Sep 17 00:00:00 2001 From: Shawn Jackson Date: Mon, 12 Oct 2026 14:12:24 -0700 Subject: [PATCH 35/67] tests: the GGUF fixture's metadata helpers set fields by name The f32 and array members added for gguf_geometry_test left the braced Kv{...} initialisers short of the struct, which clang's -Wextra reports as -Wmissing-field-initializers in every test that includes the fixture (MSVC /W4 does not). make_kv() sets the key and type, and each helper sets its own value. Built with the HIP toolchain (gfx1151): gguf_geometry_test, gguf_split_test, gguf_reader_test and native_dense_ple_key_test pass, with no warning from the fixture. --- tests/core/gguf_fixture.hpp | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/tests/core/gguf_fixture.hpp b/tests/core/gguf_fixture.hpp index 30c67bbf..d3415c5e 100644 --- a/tests/core/gguf_fixture.hpp +++ b/tests/core/gguf_fixture.hpp @@ -26,14 +26,21 @@ struct Kv { std::vector arr; std::vector sarr; }; -inline Kv str(const std::string& k, const std::string& v) { return Kv{k, 8, v, 0}; } -inline Kv u16(const std::string& k, uint64_t v) { return Kv{k, 2, {}, v}; } -inline Kv i32(const std::string& k, uint64_t v) { return Kv{k, 5, {}, v}; } -inline Kv u32(const std::string& k, uint64_t v) { return Kv{k, 4, {}, v}; } -inline Kv f32(const std::string& k, float v) { Kv r{k, 6}; r.f = v; return r; } -inline Kv u32s(const std::string& k, std::vector v) { Kv r{k, 9}; r.arr = std::move(v); return r; } +// fields set by name: a braced Kv{...} that stops short warns under -Wmissing-field-initializers (clang -Wextra) +inline Kv make_kv(const std::string& k, uint32_t type) { + Kv r; + r.key = k; + r.type = type; + return r; +} +inline Kv str(const std::string& k, const std::string& v) { Kv r = make_kv(k, 8); r.s = v; return r; } +inline Kv u16(const std::string& k, uint64_t v) { Kv r = make_kv(k, 2); r.u = v; return r; } +inline Kv i32(const std::string& k, uint64_t v) { Kv r = make_kv(k, 5); r.u = v; return r; } +inline Kv u32(const std::string& k, uint64_t v) { Kv r = make_kv(k, 4); r.u = v; return r; } +inline Kv f32(const std::string& k, float v) { Kv r = make_kv(k, 6); r.f = v; return r; } +inline Kv u32s(const std::string& k, std::vector v) { Kv r = make_kv(k, 9); r.arr = std::move(v); return r; } inline Kv strs(const std::string& k, std::vector v) { - Kv r{k, 9}; + Kv r = make_kv(k, 9); r.elem = 8; r.sarr = std::move(v); return r; From 51329cff3c1c3fd2a30ce853a8180837f142fd75 Mon Sep 17 00:00:00 2001 From: Shawn Jackson Date: Mon, 12 Oct 2026 14:36:40 -0700 Subject: [PATCH 36/67] artifact: read_geometry refuses another architecture by name before reading any qwen4exp key generate.cpp reads the geometry before anything else looks at the model, so a model of another architecture was refused as "missing qwen4exp.block_count" where 0.1.40.2 said "architecture is 'qwen35', this engine requires 'qwen4exp'" (found running Qwen3.8-27B through --native). read_geometry now checks general.architecture first, and check_architecture is read_geometry plus geometry_unsupported. gguf_geometry_test: a dense qwen35 file (Qwen3.8-27B's keys) and a file without general.architecture. Tested on gfx1151 (HIP build of this branch, Windows): the GGUF tests pass; Qwen3.8-27B UD-Q6_K_XL, Q8_0 and HauhauCS Q4_K_P are refused by architecture in 0.5 s; Qwen3.8-Flash-Next UD-IQ4_XS, greedy, 256 tokens on three prompts (39, 48 and 5,568 tokens), gives output identical to the installed 0.1.40.2. --- include/strata/artifact/gguf_reader.hpp | 15 ++++++++------- tests/core/gguf_geometry_test.cpp | 19 ++++++++++++++++--- 2 files changed, 24 insertions(+), 10 deletions(-) diff --git a/include/strata/artifact/gguf_reader.hpp b/include/strata/artifact/gguf_reader.hpp index 4b5baef0..e756c3fd 100644 --- a/include/strata/artifact/gguf_reader.hpp +++ b/include/strata/artifact/gguf_reader.hpp @@ -584,12 +584,16 @@ private: // and then checked against the shape the kernels are compiled for (core/geometry.hpp), so a file of another // shape is refused with the key that differs rather than silently mis-run. -/// Fills `g` from the metadata shard `f`. Returns "" or the first problem. The six keys every qwen4exp file -/// has carried since the first guard are required; any other key the file does not carry keeps the compiled -/// value. The keys that describe one thing twice (the interval and `compress_ratios`, the key and value head -/// widths, the routed and shared expert widths) must agree. +/// Fills `g` from the metadata shard `f`. Returns "" or the first problem. Another architecture is refused by +/// name first: its keys carry another prefix, and "missing qwen4exp.block_count" would hide what is wrong. The six +/// keys every qwen4exp file has carried since the first guard are required; any other key the file does not carry +/// keeps the compiled value. The keys that describe one thing twice (the interval and `compress_ratios`, the key +/// and value head widths, the routed and shared expert widths) must agree. inline std::string read_geometry(const GgufFile& f, core::ModelGeometry& g) { g = core::kCompiledGeometry; + const MetaValue* arch = f.get("general.architecture"); + if (!arch) return "missing general.architecture"; + if (arch->s != "qwen4exp") return "architecture is '" + arch->s + "', this engine requires 'qwen4exp'"; const std::string p = "qwen4exp."; std::string err; // an integer key into `out`: present and positive, or absent and not `required` @@ -741,9 +745,6 @@ inline std::string geometry_unsupported(const core::ModelGeometry& g) { /// The architecture guard: "" when the engine can run the model whose metadata shard is `f`. inline std::string check_architecture(const GgufFile& f) { - const MetaValue* arch = f.get("general.architecture"); - if (!arch) return "missing general.architecture"; - if (arch->s != "qwen4exp") return "architecture is '" + arch->s + "', this engine requires 'qwen4exp'"; core::ModelGeometry g; std::string err = read_geometry(f, g); if (err.empty()) err = geometry_unsupported(g); diff --git a/tests/core/gguf_geometry_test.cpp b/tests/core/gguf_geometry_test.cpp index 564a46a7..49d94601 100644 --- a/tests/core/gguf_geometry_test.cpp +++ b/tests/core/gguf_geometry_test.cpp @@ -249,9 +249,22 @@ int main(int argc, char** argv) { check(run(d.path, with(full_keys(151936), vocab.key, &vocab)).guard.empty(), "another vocabulary size is accepted (the head and embedding take their tensors' shapes)"); const fixture::Kv arch = fixture::str("general.architecture", "glm5next"); - check(run(d.path, with(full_keys(), arch.key, &arch)).guard == - "architecture is 'glm5next', this engine requires 'qwen4exp'", - "another architecture is refused by name"); + const Result a = run(d.path, with(full_keys(), arch.key, &arch)); + check(a.read_err == "architecture is 'glm5next', this engine requires 'qwen4exp'" && a.guard == a.read_err, + "another architecture is refused by name, by the reader and the guard"); + } + { + // Qwen3.8-27B's own keys (qwen35, dense): the reader names the architecture, not the first qwen4exp key it + // misses (which is what generate printed before the reader checked the name) + const std::vector dense = { + fixture::str("general.architecture", "qwen35"), fixture::u32("qwen35.block_count", 65), + fixture::u32("qwen35.embedding_length", 5120), fixture::u32("qwen35.feed_forward_length", 17408), + fixture::u32("qwen35.attention.head_count", 24), fixture::u32("qwen35.attention.head_count_kv", 4)}; + const Result r = run(d.path, dense); + check(r.read_err == "architecture is 'qwen35', this engine requires 'qwen4exp'", + "a dense qwen35 file is refused by its architecture: " + r.read_err); + const Result none = run(d.path, with(dense, "general.architecture", nullptr)); + check(none.read_err == "missing general.architecture", "a file without general.architecture says so"); } std::printf(g_fail ? "gguf_geometry_test: %d FAILED\n" : "gguf_geometry_test: all passed\n", g_fail); return g_fail ? 1 : 0; From 8825d337c1688b7096a149f315fc872c52440dfc Mon Sep 17 00:00:00 2001 From: Shawn Jackson Date: Mon, 12 Oct 2026 14:41:04 -0700 Subject: [PATCH 37/67] generate: the prompt-chunk sizing and the state fingerprint take their QSA shapes from qsa_shapes(g) Two places upstream builds QsaShapes by hand from the geometry (chunk_bytes, added since the geometry change was written, and the conversation-state fingerprint, in both trees). They now call qsa_shapes(g) like layer, mtp, session, verify and prefill; for every file the guard accepts the values are the ones they built before. --- src/program/generate.cpp | 10 ++-------- sycl/src/program/generate.cpp | 6 +----- 2 files changed, 3 insertions(+), 13 deletions(-) diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 734837fc..0328b387 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -3894,9 +3894,7 @@ int main(int argc, char** argv) { // fields directly, replicating kv_plan's arithmetic (layer.cpp:634) with the public getters. auto chunk_bytes = [&](int64_t lb, int64_t c) -> uint64_t { strata::core::qsa_set_kv_resident(o.kv_resident); - strata::kernels::QsaShapes s = strata::kernels::qsa_real_shapes(); - s.n_head = g.n_head; s.n_head_kv = g.n_head_kv; s.head_dim = g.head_dim; - s.idx_n_head = g.idx_q_heads; s.idx_dim = g.idx_key_dim; + const strata::kernels::QsaShapes s = strata::core::qsa_shapes(g); const int64_t pages = (o.max_context + s.page_size - 1) / s.page_size; int mode = 0; const int64_t kv_res = strata::core::qsa_kv_resident(); @@ -12314,11 +12312,7 @@ int main(int argc, char** argv) { return 1; } const int64_t L = (int64_t) live.size(); - const strata::kernels::QsaShapes qs = [&] { - strata::kernels::QsaShapes s = strata::kernels::qsa_real_shapes(); - s.n_head_kv = g.n_head_kv; s.head_dim = g.head_dim; s.idx_dim = g.idx_key_dim; - return s; - }(); + const strata::kernels::QsaShapes qs = strata::core::qsa_shapes(g); bool hash_ok = true; std::array hash_buffer; auto hash_dev = [&](const void* p, size_t bytes, uint64_t h) { diff --git a/sycl/src/program/generate.cpp b/sycl/src/program/generate.cpp index 9f1d3783..07852748 100644 --- a/sycl/src/program/generate.cpp +++ b/sycl/src/program/generate.cpp @@ -11484,11 +11484,7 @@ int main(int argc, char **argv) try { return 1; } const int64_t L = (int64_t) live.size(); - const strata::kernels::QsaShapes qs = [&] { - strata::kernels::QsaShapes s = strata::kernels::qsa_real_shapes(); - s.n_head_kv = g.n_head_kv; s.head_dim = g.head_dim; s.idx_dim = g.idx_key_dim; - return s; - }(); + const strata::kernels::QsaShapes qs = strata::core::qsa_shapes(g); bool hash_ok = true; std::array hash_buffer; auto hash_dev = [&](const void *p, size_t bytes, uint64_t h) { From caf1856bd985ca04c170f6dd6b74c00a8f36a29b Mon Sep 17 00:00:00 2001 From: zsariboga Date: Tue, 13 Oct 2026 00:22:07 +0300 Subject: [PATCH 38/67] pool: STRATA_POOL_UMWAIT= - parked workers wait with UMONITOR/UMWAIT instead of spinning (opt-in, x86 WAITPKG, MSVC x64) A parked pool worker watches the epoch's cache line with UMONITOR and sleeps in UMWAIT (C0.1) until the host publishes or the cycles run out. On a laptop whose CPU and GPU share one power budget the spin's power goes back to the GPU. Unset, 0, no WAITPKG or a non-MSVC build: the spin, unchanged. STRATA_POOL_UMWAIT_C02=1 picks the deeper C0.2 state, STRATA_POOL_UMWAIT_ESC= C0.1 first and C0.2 after. --- src/kernels/cpu/pool.cpp | 59 ++++++++++++++++++++++++++++++++++++++-- 1 file changed, 57 insertions(+), 2 deletions(-) diff --git a/src/kernels/cpu/pool.cpp b/src/kernels/cpu/pool.cpp index af1eb5a5..840b4f81 100644 --- a/src/kernels/cpu/pool.cpp +++ b/src/kernels/cpu/pool.cpp @@ -9,6 +9,9 @@ #include #include #include +#if defined(_MSC_VER) +#include // __cpuidex, __rdtsc (STRATA_POOL_UMWAIT) +#endif #include #include @@ -27,6 +30,41 @@ namespace strata::kernels::cpu { namespace { +// STRATA_POOL_UMWAIT= (experimental, x86 WAITPKG only): a parked worker waits with UMONITOR/UMWAIT on the +// epoch's cache line instead of spinning on _mm_pause. It wakes when the host publishes (a write to that line) or +// after the cycles, in the light C0.1 state; on a laptop the CPU then gives back the power the spin took, which the +// GPU's share of the budget gets. 0 or unset (or no WAITPKG): the spin, unchanged. STRATA_POOL_UMWAIT_C02=1: the +// deeper C0.2 state (slower wake). MSVC x64 only for now (the intrinsics need no target flag there); other builds spin. +uint64_t umwait_cycles() { + static const uint64_t c = [] { + const char* e = std::getenv("STRATA_POOL_UMWAIT"); + if (e == nullptr || std::atoll(e) <= 0) return (uint64_t) 0; +#if defined(_MSC_VER) && defined(_M_X64) + int r[4] = {0, 0, 0, 0}; + __cpuidex(r, 7, 0); + if (((r[2] >> 5) & 1) == 0) { + std::fprintf(stderr, "strata: STRATA_POOL_UMWAIT: this CPU has no WAITPKG, the workers spin\n"); + return (uint64_t) 0; + } + std::fprintf(stderr, "strata: STRATA_POOL_UMWAIT: parked workers wait with UMWAIT (%lld cycles)\n", std::atoll(e)); + return (uint64_t) std::atoll(e); +#else + return (uint64_t) 0; +#endif + }(); + return c; +} +unsigned umwait_state() { + static const unsigned s = [] { const char* e = std::getenv("STRATA_POOL_UMWAIT_C02"); return e && *e == '1' ? 0u : 1u; }(); + return s; // 1 = C0.1 (light), 0 = C0.2 +} +// STRATA_POOL_UMWAIT_ESC= (experimental): an escalating wait - C0.1 for the first cycles of a park, C0.2 after +// (a wait that has lasted that long is a GPU phase, a draft or a prompt read, where a slower wake costs little). +uint64_t umwait_escalate() { + static const uint64_t c = [] { const char* e = std::getenv("STRATA_POOL_UMWAIT_ESC"); return e ? (uint64_t) (std::max)(0LL, std::atoll(e)) : (uint64_t) 0; }(); + return c; +} + constexpr uint64_t pack_head(uint32_t epoch, uint32_t n, uint32_t i) { return ((uint64_t) epoch << 32) | ((uint64_t) n << 16) | (uint64_t) i; } @@ -509,10 +547,27 @@ void ExpertPool::worker(int id) { // every 1024 pauses, so the spin itself is unchanged. const auto parked_at = std::chrono::steady_clock::now(); uint32_t spins = 0; + const uint64_t um = umwait_cycles(); +#if defined(_MSC_VER) && defined(_M_X64) + const uint64_t um_esc = umwait_escalate(); + const uint64_t um_t0 = um != 0 && um_esc != 0 ? __rdtsc() : 0; +#endif while (epoch_.load(std::memory_order_acquire) == seen) { if (stop_.load(std::memory_order_relaxed)) return; - _mm_pause(); - if ((++spins & 1023u) != 0) continue; +#if defined(_MSC_VER) && defined(_M_X64) + if (um != 0) { // STRATA_POOL_UMWAIT: wake on the publish's write to epoch_, or after `um` cycles + _umonitor((void*) &epoch_); + if (epoch_.load(std::memory_order_acquire) != seen) break; + const uint64_t now = __rdtsc(); + const unsigned st = um_esc != 0 ? (now - um_t0 < um_esc ? 1u : 0u) : umwait_state(); + _umwait(st, now + um); + if ((++spins & 15u) != 0) continue; // each wait is ~um cycles: look at the clock more often + } else +#endif + { + _mm_pause(); + if ((++spins & 1023u) != 0) continue; + } if (std::chrono::steady_clock::now() - parked_at < spin_before_sleep_) continue; std::unique_lock lk(sleep_mu_); wstate_[(size_t) id].store(kSleeping, std::memory_order_relaxed); From 9c5bbc36d0198b7ec582874f2ae90eccafc98179 Mon Sep 17 00:00:00 2001 From: Techannel <20737840+Techannel@users.noreply.github.com> Date: Mon, 12 Oct 2026 23:40:45 +0200 Subject: [PATCH 39/67] dequant: a thread per 8 values for Q4_K / Q5_K / Q6_K / IQ4_XS, sm_61's default (bitwise; Q6_K 7.2 -> 0.33 ms on a Tesla P40) dequant_kernel's thread reads its 32-value group a byte at a time and writes 32 two-byte values one by one, 64 bytes from its neighbour's. On a Tesla P40 that is 10 GB/s for Q6_K, and the IQ3_S pack's dense weights cost every prompt chunk ~0.5 s of it, whatever the chunk's length (a fifth of a 560-token prompt). The wide kernel takes 8 values a thread: 16-bit loads, one 16-byte store, the same expression per value. dequant_wide_parity: 360 cases bitwise (FP16 / BF16 / FP32 out, a padded stride, row slices, sane and raw random blocks); --bench on the P40: Q6_K 10240 x 2560 7.25 -> 0.33 ms, Q4_K 5.2x, Q5_K 3.8x, IQ4_XS 3.6x. On by default on compute capability 6.1 only (where it was measured); STRATA_DEQUANT_WIDE=0 / =1 for any card. --- CMakeLists.txt | 6 + include/strata/kernels/dequant_bf16.hpp | 4 + src/kernels/cuda/dequant_bf16.cu | 124 ++++++++++++++++++++ src/kernels/dequant_wide_parity.cpp | 145 ++++++++++++++++++++++++ 4 files changed, 279 insertions(+) create mode 100644 src/kernels/dequant_wide_parity.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 7723a0d2..f55befec 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -786,6 +786,12 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) target_include_directories(mmvq_il_parity PRIVATE ${_strata_gpu_include_directories}) target_link_libraries(mmvq_il_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) add_test(NAME mmvq_il_parity COMMAND mmvq_il_parity) + # the wide dequant kernels (a thread per 8 values; sm_61's default), bitwise vs the per-group ones (GPU, synthetic, + # no model; --bench adds old/new timings) + add_executable(dequant_wide_parity src/kernels/dequant_wide_parity.cpp) + target_include_directories(dequant_wide_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(dequant_wide_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_test(NAME dequant_wide_parity COMMAND dequant_wide_parity) endif() # programmatic dependent launch (pdl.hpp) in a captured verify-shaped chain: bitwise vs ordinary launches over # replays with poisoned buffers, and only kernel-to-kernel programmatic edges (GPU, synthetic, no model; the edges diff --git a/include/strata/kernels/dequant_bf16.hpp b/include/strata/kernels/dequant_bf16.hpp index bcc7e38f..ee88298f 100644 --- a/include/strata/kernels/dequant_bf16.hpp +++ b/include/strata/kernels/dequant_bf16.hpp @@ -29,4 +29,8 @@ bool dequant_f16_ld(int ggml_type, const void* blocks, int64_t row0, int64_t row /// The same into FP32 (tests and small tensors). void dequant_f32(int ggml_type, const void* blocks, int64_t row0, int64_t rows, int64_t cols, float* out, void* stream); +/// The wide kernels (a thread per 8 values, bitwise the same output; Q4_K, Q5_K, Q6_K, IQ4_XS): 0 off, 1 on, -1 the +/// default (STRATA_DEQUANT_WIDE, else on for compute capability 6.1). For dequant_wide_parity. +void dequant_set_wide(int mode); + } // namespace strata::kernels diff --git a/src/kernels/cuda/dequant_bf16.cu b/src/kernels/cuda/dequant_bf16.cu index a6fe910e..95e9d152 100644 --- a/src/kernels/cuda/dequant_bf16.cu +++ b/src/kernels/cuda/dequant_bf16.cu @@ -175,6 +175,112 @@ __global__ void dequant_kernel(const uint8_t* __restrict__ blocks, int64_t row_b group32(blocks + (row0 + r) * row_bytes, (int) gi, out + r * ld + gi * 32); } +// ---- the wide kernels: a thread per 8 values (Pascal, sm_61) -------------------------------------------------------- +// dequant_kernel's thread reads its 32-value group a byte at a time and writes 32 two-byte values one by one, 64 bytes +// from its neighbour's. On a Tesla P40 (sm_61) that is 7.2 ms for a 10240 x 2560 Q6_K weight (10 GB/s), and the IQ3_S +// pack's dense weights cost every prompt chunk ~0.5 s of it, whatever the chunk's length (a fifth of a 560-token prompt). +// Here a thread takes 8 consecutive values: its code bytes as 16-bit loads (the GGUF blocks are 2-byte aligned) and +// one 16-byte store (two for FP32), so a warp writes 512 consecutive bytes. The arithmetic per value is group32's - +// the same expression on the same operands - so the output is bitwise the same (dequant_wide_parity). On the P40: +// Q6_K 7.2 -> 0.33 ms (227 GB/s), Q4_K 1.67 -> 0.32 ms, Q5_K 1.24 -> 0.33 ms, IQ4_XS 1.21 -> 0.34 ms for that shape. +// Q4_K, Q5_K, Q6_K and IQ4_XS. On by default on compute capability 6.1, where it was measured; +// STRATA_DEQUANT_WIDE=0 / =1 turns it off / on for every card. +__device__ __forceinline__ uint64_t ld8(const uint8_t* p) { // 8 bytes at a 2-byte aligned address + const uint16_t* q = reinterpret_cast(p); + return (uint64_t) q[0] | ((uint64_t) q[1] << 16) | ((uint64_t) q[2] << 32) | ((uint64_t) q[3] << 48); +} +// values [8 piece, 8 piece + 8) of the 32-element group `gi_in_row`, as group32 computes them +template +__device__ __forceinline__ void wide8(const uint8_t* row_blocks, int gi_in_row, int piece, T* v) { + const int l0 = 8 * piece; + if constexpr (TYPE == 12) { // Q4_K: d dmin scales[12] qs[128] + const uint8_t* b = row_blocks + (size_t) (gi_in_row / 8) * 144; + const int gi = gi_in_row % 8, j64 = gi / 2, hi = gi % 2; + const float d = h2f(b), dmin = h2f(b + 2); + int sc, m; + scale_min_k4(gi, b + 4, sc, m); + const float d1 = d * (float) sc, m1 = dmin * (float) m; + const uint64_t q = ld8(b + 16 + 32 * j64 + l0); +#pragma unroll + for (int k = 0; k < 8; ++k) { + const int lb = (int) (q >> (8 * k)) & 0xFF; + put(v, k, d1 * (float) (hi ? (lb >> 4) : (lb & 0xF)) - m1); + } + } else if constexpr (TYPE == 13) { // Q5_K: d dmin scales[12] qh[32] qs[128] + const uint8_t* b = row_blocks + (size_t) (gi_in_row / 8) * 176; + const int gi = gi_in_row % 8, j64 = gi / 2, hi = gi % 2; + const float d = h2f(b), dmin = h2f(b + 2); + int sc, m; + scale_min_k4(gi, b + 4, sc, m); + const float d1 = d * (float) sc, m1 = dmin * (float) m; + const uint64_t qh = ld8(b + 16 + l0), ql = ld8(b + 48 + 32 * j64 + l0); + const int ub = 2 * j64 + hi; +#pragma unroll + for (int k = 0; k < 8; ++k) { + const int lb = (int) (ql >> (8 * k)) & 0xFF, hb = (int) (qh >> (8 * k)) & 0xFF; + const int nib = hi ? (lb >> 4) : (lb & 0xF); + put(v, k, d1 * (float) (nib + (((hb >> ub) & 1) ? 16 : 0)) - m1); + } + } else if constexpr (TYPE == 14) { // Q6_K: ql[128] qh[64] scales[16] d + const uint8_t* b = row_blocks + (size_t) (gi_in_row / 8) * 210; + const int gi = gi_in_row % 8, n = gi / 4, qu = gi % 4; + const uint64_t ql = ld8(b + 64 * n + ((qu & 1) ? 32 : 0) + l0); + const uint64_t qh = ld8(b + 128 + 32 * n + l0); + const int8_t* sc = reinterpret_cast(b + 192) + 8 * n; + const float d = h2f(b + 208); + const float ds = d * (float) sc[l0 / 16 + 2 * qu]; +#pragma unroll + for (int k = 0; k < 8; ++k) { + const int lb = (int) (ql >> (8 * k)) & 0xFF, hb = (int) (qh >> (8 * k)) & 0xFF; + const int q = ((qu >= 2) ? (lb >> 4) : (lb & 0xF)) | (((hb >> (2 * qu)) & 3) << 4); + put(v, k, ds * (float) (q - 32)); + } + } else if constexpr (TYPE == 23) { // IQ4_XS: d scales_h scales_l[4] qs[128] + const uint8_t* b = row_blocks + (size_t) (gi_in_row / 8) * 136; + const int ib = gi_in_row % 8; + const float d = h2f(b); + const uint16_t scales_h = (uint16_t) (b[2] | (b[3] << 8)); + const int ls = ((b[4 + ib / 2] >> (4 * (ib % 2))) & 0xf) | (((scales_h >> (2 * ib)) & 3) << 4); + const float dl = d * (float) (ls - 32); + const uint64_t qs = ld8(b + 8 + 16 * ib + 8 * (piece & 1)); // pieces 0, 1: the low nibbles; 2, 3: the high ones +#pragma unroll + for (int k = 0; k < 8; ++k) { + const int lb = (int) (qs >> (8 * k)) & 0xFF; + put(v, k, dl * (float) kv_iq4nl[piece >= 2 ? (lb >> 4) : (lb & 0xf)]); + } + } +} +template +__global__ void dequant_wide_kernel(const uint8_t* __restrict__ blocks, int64_t row_bytes, int64_t row0, uint32_t rows, + uint32_t groups_per_row, int64_t ld, T* __restrict__ out) { + const uint32_t i = blockIdx.x * blockDim.x + threadIdx.x; // launch(): 4 * rows * groups_per_row < 2^31 + const uint32_t g = i >> 2, r = g / groups_per_row, gi = g - r * groups_per_row; + if (r >= rows) return; + const int piece = (int) (i & 3); + __align__(16) T v[8]; + wide8(blocks + (row0 + (int64_t) r) * row_bytes, (int) gi, piece, v); + uint4* o = (uint4*) (out + (int64_t) r * ld + (int64_t) gi * 32 + 8 * piece); +#pragma unroll + for (int k = 0; k < (int) (8 * sizeof(T) / 16); ++k) o[k] = ((const uint4*) v)[k]; +} +bool wide_type(int type) { return type == 12 || type == 13 || type == 14 || type == 23; } +int g_dequant_wide = -1; // dequant_set_wide (the parity test); -1 = STRATA_DEQUANT_WIDE, else the card's default +bool dequant_wide_on() { + static const int env = [] { const char* v = std::getenv("STRATA_DEQUANT_WIDE"); return v != nullptr && v[0] != '\0' ? (std::atoi(v) != 0 ? 1 : 0) : -1; }(); + if (g_dequant_wide >= 0) return g_dequant_wide != 0; + if (env >= 0) return env != 0; + static int per_dev[64]; // 0 unknown, 1 no, 2 yes: sm_61, measured on a Tesla P40 + int dev = 0; + if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return false; } + if (!per_dev[dev]) { + int major = 0, minor = 0; + if (cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) != cudaSuccess || + cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, dev) != cudaSuccess) { cudaGetLastError(); return false; } + per_dev[dev] = major == 6 && minor == 1 ? 2 : 1; + } + return per_dev[dev] == 2; +} + // Q8_0 with four threads per block, 8 values each: the warp reads 8 consecutive blocks and writes 512 consecutive // bytes (a thread per block wrote 2-byte values 64 bytes apart: ~110 GB/s, a quarter of a prompt projection's time) template @@ -237,6 +343,22 @@ void launch(int type, const void* blocks, int64_t row0, int64_t rows, int64_t co if (e != cudaSuccess) { std::fprintf(stderr, "dequant launch: %s\n", cudaGetErrorString(e)); std::exit(1); } return; } + // the wide kernels: even block addresses, 16-byte stores at every row (contiguous or a stride of whole stores) + if (wide_type(type) && (reinterpret_cast(blocks) & 1) == 0 && (reinterpret_cast(out) & 15) == 0 && + ((size_t) ld * sizeof(T)) % 16 == 0 && 4 * total < (1ll << 31) && dequant_wide_on()) { + const unsigned wgrid = (unsigned) ((4 * total + 255) / 256); +#define STRATA_DQW(TY) dequant_wide_kernel<<>>(p, row_bytes, row0, (uint32_t) rows, (uint32_t) gpr, ld, out); break + switch (type) { + case 12: STRATA_DQW(12); + case 13: STRATA_DQW(13); + case 14: STRATA_DQW(14); + case 23: STRATA_DQW(23); + } +#undef STRATA_DQW + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) { std::fprintf(stderr, "dequant launch: %s\n", cudaGetErrorString(e)); std::exit(1); } + return; + } #define STRATA_DQ(TY) dequant_kernel<<>>(p, row_bytes, row0, rows, gpr, ld, out); break switch (type) { case 2: STRATA_DQ(2); @@ -258,6 +380,8 @@ void launch(int type, const void* blocks, int64_t row0, int64_t rows, int64_t co } // namespace +void dequant_set_wide(int mode) { g_dequant_wide = mode; } + bool dequant_bf16_supported(int ggml_type) noexcept { int a, b; return geometry(ggml_type, a, b); diff --git a/src/kernels/dequant_wide_parity.cpp b/src/kernels/dequant_wide_parity.cpp new file mode 100644 index 00000000..b462eb29 --- /dev/null +++ b/src/kernels/dequant_wide_parity.cpp @@ -0,0 +1,145 @@ +// src/kernels/dequant_wide_parity.cpp - the wide dequant kernels (a thread per 8 values, dequant_bf16.cu) against the +// per-group ones, bitwise, for Q4_K / Q5_K / Q6_K / IQ4_XS into FP16, BF16 and FP32: whole tensors, row slices and a +// padded row stride, on blocks with sane fields and on raw random bytes (NaN and Inf scales included). +// +// build/dequant_wide_parity [--bench] +// --bench adds each kernel's time per call on the prompt path's shapes (FP16 out). Exit 0: every case bitwise equal. +#include "strata/kernels/dequant_bf16.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace K = strata::kernels; + +static void ck(cudaError_t e, const char* what) { + if (e != cudaSuccess) { std::fprintf(stderr, "dequant_wide_parity: %s: %s\n", what, cudaGetErrorString(e)); std::exit(2); } +} +static uint16_t f2h(float f) { // FP32 -> FP16 bits, round to nearest even (normal range only: the scales below) + uint32_t u; + std::memcpy(&u, &f, 4); + const uint32_t sign = (u >> 16) & 0x8000u; + int e = (int) ((u >> 23) & 0xff) - 127 + 15; + uint32_t m = u & 0x7fffffu; + if (e <= 0) return (uint16_t) sign; + if (e >= 31) return (uint16_t) (sign | 0x7c00u); + uint32_t h = sign | ((uint32_t) e << 10) | (m >> 13); + if ((m & 0x1fffu) > 0x1000u || ((m & 0x1fffu) == 0x1000u && (h & 1u))) ++h; + return (uint16_t) h; +} +struct Type { int id; const char* name; int block_bytes; }; +static const Type kTypes[] = {{12, "Q4_K", 144}, {13, "Q5_K", 176}, {14, "Q6_K", 210}, {23, "IQ4_XS", 136}}; + +// `sane`: random codes and scales with a block scale in a weight's range; else raw random bytes +static std::vector make_blocks(const Type& t, int64_t rows, int64_t cols, bool sane, uint32_t seed) { + std::mt19937 rng(seed); + const int64_t nb = rows * (cols / 256); + std::vector b((size_t) nb * t.block_bytes); + for (size_t i = 0; i + 4 <= b.size(); i += 4) { const uint32_t r = rng(); std::memcpy(&b[i], &r, 4); } + for (size_t i = b.size() & ~(size_t) 3; i < b.size(); ++i) b[i] = (uint8_t) rng(); + if (sane) { + std::uniform_real_distribution ud(1e-4f, 3e-2f); + for (int64_t k = 0; k < nb; ++k) { + uint8_t* p = b.data() + (size_t) k * t.block_bytes; + const uint16_t d = f2h((rng() & 1 ? 1.0f : -1.0f) * ud(rng)), dm = f2h(-ud(rng)); + if (t.id == 14) std::memcpy(p + 208, &d, 2); + else if (t.id == 23) std::memcpy(p, &d, 2); + else { std::memcpy(p, &d, 2); std::memcpy(p + 2, &dm, 2); } + } + } + return b; +} + +int main(int argc, char** argv) { + setvbuf(stdout, nullptr, _IONBF, 0); + const bool bench = argc > 1 && std::string(argv[1]) == "--bench"; + cudaStream_t s; + ck(cudaStreamCreate(&s), "stream"); + struct Shape { int64_t rows, cols; }; + const Shape shapes[] = {{10240, 2560}, {6144, 2560}, {2560, 6144}, {12288, 2560}, {512, 2560}, {2560, 4096}, {320, 10240}, {7, 256}, {33, 768}}; + int cases = 0, failures = 0; + for (const Type& t : kTypes) { + for (const Shape& sh : shapes) { + for (int sane = 1; sane >= 0; --sane) { + const int64_t rows = sh.rows, cols = sh.cols, n = rows * cols; + const std::vector hb = make_blocks(t, rows, cols, sane != 0, (uint32_t) (t.id * 1000003 + rows * 31 + cols + sane)); + uint8_t* db = nullptr; + ck(cudaMalloc((void**) &db, hb.size()), "blocks"); + ck(cudaMemcpy(db, hb.data(), hb.size(), cudaMemcpyHostToDevice), "upload"); + const int64_t ldp = cols + 64; // the padded stride (dequant_f16_ld) + const size_t cap = (size_t) rows * (size_t) ldp * 4; + uint8_t *o0 = nullptr, *o1 = nullptr; + ck(cudaMalloc((void**) &o0, cap), "out0"); + ck(cudaMalloc((void**) &o1, cap), "out1"); + std::vector h0(cap), h1(cap); + // what: 0 FP16, 1 BF16, 2 FP32, 3 FP16 with the padded stride, 4 FP16 of a row slice + for (int what = 0; what < 5; ++what) { + const int64_t r0 = what == 4 ? rows / 3 : 0, nr = what == 4 ? rows - rows / 3 - rows / 5 : rows; + if (nr <= 0) continue; + for (int wide = 0; wide < 2; ++wide) { + uint8_t* o = wide ? o1 : o0; + ck(cudaMemsetAsync(o, 0xA5, cap, s), "memset"); + K::dequant_set_wide(wide); + if (what == 0 || what == 4) K::dequant_f16(t.id, db, r0, nr, cols, (uint16_t*) o, s); + else if (what == 1) K::dequant_bf16(t.id, db, r0, nr, cols, (uint16_t*) o, s); + else if (what == 2) K::dequant_f32(t.id, db, r0, nr, cols, (float*) o, s); + else if (!K::dequant_f16_ld(t.id, db, r0, nr, cols, ldp, (uint16_t*) o, s)) { std::printf("FAIL %s: dequant_f16_ld refused\n", t.name); ++failures; } + ck(cudaMemcpyAsync(wide ? h1.data() : h0.data(), o, cap, cudaMemcpyDeviceToHost, s), "download"); + } + ck(cudaStreamSynchronize(s), "sync"); + ++cases; + if (std::memcmp(h0.data(), h1.data(), cap) != 0) { + size_t nd = 0, first = 0; + for (size_t i = 0; i < cap; ++i) if (h0[i] != h1[i]) { if (!nd) first = i; ++nd; } + std::printf("FAIL %s %lldx%lld %s what %d: %zu bytes differ, first at %zu\n", t.name, (long long) rows, (long long) cols, + sane ? "sane" : "raw", what, nd, first); + ++failures; + } + // the default-pattern bytes outside the written values must be untouched by both (the padded stride's gaps) + if (what == 3) { + size_t bad = 0; + for (int64_t r = 0; r < nr; ++r) + for (int64_t c = cols; c < ldp; ++c) + if (h1[(size_t) (r * ldp + c) * 2] != 0xA5 || h1[(size_t) (r * ldp + c) * 2 + 1] != 0xA5) ++bad; + if (bad) { std::printf("FAIL %s %lldx%lld: the wide kernel wrote %zu values into the row padding\n", t.name, (long long) rows, (long long) cols, bad); ++failures; } + } + } + if (bench && sane && rows >= 512) { + cudaEvent_t e0, e1; + cudaEventCreate(&e0); + cudaEventCreate(&e1); + double ms[2] = {0, 0}; + const int reps = 20; + for (int wide = 0; wide < 2; ++wide) { + K::dequant_set_wide(wide); + for (int i = 0; i < 3; ++i) K::dequant_f16(t.id, db, 0, rows, cols, (uint16_t*) o0, s); + cudaEventRecord(e0, s); + for (int i = 0; i < reps; ++i) K::dequant_f16(t.id, db, 0, rows, cols, (uint16_t*) o0, s); + cudaEventRecord(e1, s); + ck(cudaEventSynchronize(e1), "bench sync"); + float tms = 0; + cudaEventElapsedTime(&tms, e0, e1); + ms[wide] = tms / reps; + } + const double bytes = (double) hb.size() + (double) n * 2; + std::printf("BENCH %-6s %6lldx%-6lld per-group %8.3f ms (%5.1f GB/s) | wide %8.3f ms (%5.1f GB/s) | %.2fx\n", t.name, (long long) rows, + (long long) cols, ms[0], bytes / ms[0] / 1e6, ms[1], bytes / ms[1] / 1e6, ms[0] / ms[1]); + cudaEventDestroy(e0); + cudaEventDestroy(e1); + } + cudaFree(db); + cudaFree(o0); + cudaFree(o1); + } + } + } + K::dequant_set_wide(-1); + std::printf("dequant_wide_parity: %d cases, %s\n", cases, failures ? "FAILED" : "OK (bitwise)"); + return failures ? 1 : 0; +} From 40ba0cf93d93c5d47d6eb719e66b78c8d41ac949 Mon Sep 17 00:00:00 2001 From: Techannel <20737840+Techannel@users.noreply.github.com> Date: Mon, 12 Oct 2026 23:40:45 +0200 Subject: [PATCH 40/67] prefill gemm: opt-in STRATA_DENSE_F32=1 on Pascal - the large dense GEMMs as cublasSgemm on FP32 copies For FP16 operands with FP32 sums cuBLAS 12.4 has two Maxwell kernels on a Tesla P40 and picks the slow one for most chunk sizes: qkv (10240 x 2560) runs at 7.6 TFLOPS for T 7030-7040 and at 4.3 from T 7041 (49 -> 85 ms), so a 7K-token prompt reads in 16.3 or 19.5 s by its token count. cublasSgemm on FP32 copies runs at 8.4-9.8 TFLOPS from T 512. For the five shapes and the sizes the route takes, the result is bitwise the FP16 call's: gemm_f32_parity, 5,201 chunk sizes through Gemm::f16. That is a property of the cuBLAS build (12.4.5.8 measured), hence opt-in. --- CMakeLists.txt | 5 ++ include/strata/prefill/gemm.hpp | 6 ++ src/prefill/gemm.cu | 82 ++++++++++++++++++++ src/prefill/gemm_f32_parity.cu | 129 ++++++++++++++++++++++++++++++++ 4 files changed, 222 insertions(+) create mode 100644 src/prefill/gemm_f32_parity.cu diff --git a/CMakeLists.txt b/CMakeLists.txt index f55befec..49a45ee1 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -831,6 +831,11 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) add_executable(gemm_bf16_parity src/prefill/gemm_bf16_parity.cu) target_link_libraries(gemm_bf16_parity PRIVATE strata_prefill ) add_test(NAME gemm_bf16_parity COMMAND gemm_bf16_parity) + # Pascal, opt-in STRATA_DENSE_F32=1: the dense projections' FP16 GEMMs as cublasSgemm on FP32 copies, bitwise vs + # the cuBLAS FP16 call over a sweep of chunk sizes (GPU, synthetic, no model; --full sweeps every size, --bench + # adds timings). Not a ctest: whether the two agree is a property of the cuBLAS build, which this checks. + add_executable(gemm_f32_parity src/prefill/gemm_f32_parity.cu) + target_link_libraries(gemm_f32_parity PRIVATE strata_prefill ) endif() # native_expert_grouped's group stride and fused SwiGLU + q8_1, bitwise vs the launches before them (GPU, synthetic, # no model; --bench adds v1/new timings of a window's 48 calls in a graph) diff --git a/include/strata/prefill/gemm.hpp b/include/strata/prefill/gemm.hpp index 935f1a9a..0740fd0d 100644 --- a/include/strata/prefill/gemm.hpp +++ b/include/strata/prefill/gemm.hpp @@ -89,6 +89,12 @@ private: void f16_inplace(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64_t N, int64_t K, int64_t ldy); }; +/// Pascal, opt-in: Gemm::f16's large dense shapes as cublasSgemm on FP32 copies (gemm.cu; bitwise the FP16 call's +/// result at the sizes it takes with the cuBLAS it was measured on). 0 off, 1 on (any card), -1 the default +/// (STRATA_DENSE_F32=1 on compute capability 6.x, else off). For gemm_f32_parity; a no-op outside the experimental +/// CUDA 12 build. +void gemm_set_dense_f32(int mode); + /// HIP on gfx103x (RDNA2), for the current device: rocBLAS's tuned GEMMs there are FP16 in -> FP16 out only (FP16 or /// BF16 in -> FP32 out runs ~6x slower), so the prompt path's 16-bit GEMMs run in FP16 (Gemm::set_f16_io, /// set_act_f16). Cached per device (a layer split can mix cards). STRATA_HIP_PROMPT_F16=0/1 overrides. diff --git a/src/prefill/gemm.cu b/src/prefill/gemm.cu index 88ecb793..300da53b 100644 --- a/src/prefill/gemm.cu +++ b/src/prefill/gemm.cu @@ -539,8 +539,61 @@ bool grow(uint16_t*& p, int64_t& have, int64_t want) { // `have`, `want`: 2-by return true; } constexpr int64_t kXSliceElems = 16ll << 20; // 32 MiB of FP16 activations per slice (64 MiB as fp32) + +#if defined(STRATA_EXPERIMENTAL_SM60) +// ---- Pascal, opt-in (STRATA_DENSE_F32=1): the dense projections' FP16-operand GEMMs as cublasSgemm ---------------- +// Measured on a Tesla P40 (sm_61) with cuBLAS 12.4.5.8 (bench/results/2026-10-12-p40-sm61-kernels). For FP16 +// operands with FP32 sums cuBLAS has two Maxwell kernels there, maxwell_sgemm_fp16_64x64 and _32x128, and picks the +// slow one for most chunk sizes: the 10240 x 2560 qkv projection runs at 7.6 TFLOPS for T 7030-7040 and at 4.3 from +// T 7041 (49 -> 85 ms), and at 4.3-4.6 for two thirds of the T between 256 and 8192; the 12288-row query projection +// likewise. A 7K-token prompt reads in 16.3 or 19.5 s by its token count. cublasSgemm on FP32 copies +// (maxwell_sgemm_128x64) runs at 8.4-9.8 TFLOPS for every T from 512 (6.7+ from 256). The copies are exact +// (FP16 -> FP32), and for the shapes and sizes taken here the two kernels add every output's products in the same +// order: the result is bitwise the cuBLAS FP16 call's (gemm_f32_parity: 5,201 chunk sizes on a P40 with cuBLAS 12.4, a +// measurement of this library, not a guarantee of cuBLAS's; below the sizes taken here - T under +// ~144 at 6144+ rows, under ~408 at 2560 rows - cuBLAS switches one of them to another kernel family and the bits +// differ, so those keep the FP16 call). The weight goes through the BF16 path's conversion buffer (126 MiB for the +// largest, 21 MiB more than that path's own), the activations through its slices. +// Opt-in, and on Pascal (compute capability 6.x) only: the equality belongs to the cuBLAS build, so run +// gemm_f32_parity with yours before turning it on; newer cards have tensor cores for the FP16 call. +__global__ void f16_to_f32_kernel(const uint16_t* __restrict__ in, float* __restrict__ out, int64_t n) { + const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; + if (i < n) out[i] = __half2float(__ushort_as_half(in[i])); +} +void f16_to_f32(const uint16_t* in, float* out, int64_t n, cudaStream_t st) { + if (n <= 0) return; + f16_to_f32_kernel<<<(unsigned) ((n + 255) / 256), 256, 0, st>>>(in, out, n); +} +int g_dense_f32 = -1; // gemm_set_dense_f32 (the parity test: 0 / 1 on any card); -1 = STRATA_DENSE_F32 +bool dense_f32_on() { + static const bool env = [] { + const char* v = std::getenv("STRATA_DENSE_F32"); + return v != nullptr && std::atoi(v) != 0; + }(); + if (g_dense_f32 >= 0) return g_dense_f32 != 0; + if (!env) return false; + const int cc = current_cc(); + return cc >= 60 && cc < 70; +} +// The smallest T taken for a weight of N rows and K columns (0: never): the measured shapes only - the 2560-column +// qkv (10240 rows), query (12288) and gate (6144) projections and the 2560-row output projections (6144 and 4096 +// columns), each from a T where the FP32 route (its conversions included) is the faster one or within ~7% of the FP16 +// call (the gate projection below ~1300 tokens, the 4096-column output projection near 4096) and well above the T +// where the two stop agreeing bitwise. Every other shape (a row slice of a weight too) keeps the FP16 call. +int64_t dense_f32_min_t(int64_t N, int64_t K) { + if (K == 2560 && (N == 10240 || N == 12288)) return 256; + if (K == 2560 && N == 6144) return 512; + if (N == 2560 && (K == 6144 || K == 4096)) return 4096; + return 0; +} +#endif } // namespace #endif +#if !defined(__HIPCC__) && defined(STRATA_EXPERIMENTAL_SM60) +void gemm_set_dense_f32(int mode) { g_dense_f32 = mode; } +#else +void gemm_set_dense_f32(int) {} +#endif bool Gemm::bf16_hcd_exact(const uint16_t* X, int64_t ldx, const uint16_t* W, float* Y, int64_t T, int64_t N, int64_t K) { #if defined(__HIPCC__) && defined(STRATA_HIPBLASLT_AVAILABLE) static std::atomic told{false}; @@ -698,6 +751,35 @@ void Gemm::f16(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64_ return; } #endif +#if !defined(__HIPCC__) && defined(STRATA_EXPERIMENTAL_SM60) + // Pascal, STRATA_DENSE_F32=1: cublasSgemm on FP32 copies (dense_f32_on above: where it is bitwise the FP16 call) + if (const int64_t min_t = beta == 0.0f ? dense_f32_min_t(N, K) : 0; min_t > 0 && T >= min_t && dense_f32_on()) { + const int64_t n_sl = (T * K + kXSliceElems - 1) / kXSliceElems; // even slices of at most 64 MiB as fp32 + const int64_t x_rows = (T + n_sl - 1) / n_sl; + // grow() frees a buffer an earlier GEMM on this stream may still read + if (tc_w_elems_ < 2 * N * K || tc_x_elems_ < 2 * x_rows * K) cudaStreamSynchronize((cudaStream_t) stream_); + if (grow(tc_w_, tc_w_elems_, 2 * N * K) && grow(tc_x_, tc_x_elems_, 2 * x_rows * K)) { + static bool said = false; + if (!said) { + said = true; + std::fprintf(stderr, "prefill gemm: the dense projections' FP16 GEMMs run as cublasSgemm on FP32 copies " + "(STRATA_DENSE_F32=1; gemm_f32_parity checks the bits against this cuBLAS)\n"); + } + float* const wf = reinterpret_cast(tc_w_); + float* const xf = reinterpret_cast(tc_x_); + f16_to_f32(W, wf, N * K, (cudaStream_t) stream_); + for (int64_t t0 = 0; t0 < T; t0 += x_rows) { + const int64_t n = std::min(x_rows, T - t0); + f16_to_f32(X + t0 * K, xf, n * K, (cudaStream_t) stream_); + ck(cublasSgemm((cublasHandle_t) handle_, CUBLAS_OP_T, CUBLAS_OP_N, (int) N, (int) n, (int) K, &alpha, wf, (int) K, + xf, (int) K, &beta, Y + t0 * ldy, (int) ldy), + "cublasSgemm (FP16 operands, STRATA_DENSE_F32)"); + } + return; + } + cudaGetLastError(); // no room for the copies: the FP16 call below + } +#endif #if !defined(__HIPCC__) const auto f16_gemm = [&](cublasGemmAlgo_t algo) { return cublasGemmEx((cublasHandle_t) handle_, CUBLAS_OP_T, CUBLAS_OP_N, (int) N, (int) T, (int) K, &alpha, diff --git a/src/prefill/gemm_f32_parity.cu b/src/prefill/gemm_f32_parity.cu new file mode 100644 index 00000000..ee4eb87d --- /dev/null +++ b/src/prefill/gemm_f32_parity.cu @@ -0,0 +1,129 @@ +// src/prefill/gemm_f32_parity.cu - Pascal: Gemm::f16's opt-in FP32 route (cublasSgemm on FP32 copies of the FP16 +// operands, STRATA_DENSE_F32=1) against the cuBLAS FP16-operand call it replaces, bitwise, over the dense projections' +// shapes and a sweep of chunk sizes T (GPU, synthetic, no model). Whether the two agree is a property of the cuBLAS +// build (measured: 12.4.5.8 on a Tesla P40, 5,201 sizes): run this before setting STRATA_DENSE_F32=1. +// +// build/gemm_f32_parity [--quick | --full] [--bench] +// default: every 7th T from the route's first to 8192, every T of 7000-7100 and around the powers of two, 8192; +// --quick: every 251st T; --full: every T. --bench prints both times for a few T. Exit 0: every output bitwise +// equal (or the route is not built here: not the experimental CUDA 12 engine). +#include "strata/prefill/gemm.hpp" + +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace { +__global__ void fill_f16(__half* p, int64_t n, unsigned seed, float scale) { + const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; + if (i >= n) return; + unsigned x = (unsigned) i * 2654435761u + seed; + x ^= x >> 16; x *= 2246822519u; x ^= x >> 13; x *= 3266489917u; x ^= x >> 16; + p[i] = __float2half(((float) (x & 0xffff) / 32768.0f - 1.0f) * scale); +} +__global__ void count_diff(const unsigned* a, const unsigned* b, int64_t n, unsigned* out) { + const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; + if (i < n && a[i] != b[i]) atomicAdd(out, 1u); +} +bool ok(cudaError_t e, const char* what) { + if (e != cudaSuccess) std::printf("FAIL: %s: %s\n", what, cudaGetErrorString(e)); + return e == cudaSuccess; +} +struct Shape { const char* what; int64_t N, K, t_min; }; +} // namespace + +int main(int argc, char** argv) { + setvbuf(stdout, nullptr, _IONBF, 0); + bool quick = false, full = false, bench = false; + for (int i = 1; i < argc; ++i) { + const std::string a = argv[i]; + quick |= a == "--quick"; full |= a == "--full"; bench |= a == "--bench"; + } + int dev = 0, maj = 0, min = 0; + cudaGetDevice(&dev); + cudaDeviceGetAttribute(&maj, cudaDevAttrComputeCapabilityMajor, dev); + cudaDeviceGetAttribute(&min, cudaDevAttrComputeCapabilityMinor, dev); + std::printf("gemm_f32_parity: compute capability %d.%d\n", maj, min); + cudaStream_t st = nullptr; + if (!ok(cudaStreamCreate(&st), "stream")) return 1; + strata::prefill::Gemm gemm; + std::string err; + if (!gemm.init(st, 0, err)) { std::printf("FAIL: %s\n", err.c_str()); return 1; } + // the shapes the route takes and its first T for each (gemm.cu, dense_f32_min_t) + const Shape shapes[] = {{"gdn qkv", 10240, 2560, 256}, {"qsa query", 12288, 2560, 256}, {"gdn gate", 6144, 2560, 512}, + {"gdn out", 2560, 6144, 4096}, {"qsa out", 2560, 4096, 4096}}; + const int64_t TMAX = 8192; + unsigned* cnt = nullptr; + if (!ok(cudaMalloc((void**) &cnt, 4), "counter")) return 1; + cudaEvent_t e0, e1; + cudaEventCreate(&e0); + cudaEventCreate(&e1); + long long cases = 0, bad_cases = 0; + for (const Shape& s : shapes) { + const int64_t N = s.N, K = s.K; + uint16_t *W = nullptr, *X = nullptr; + float *Ya = nullptr, *Yb = nullptr; + if (!ok(cudaMalloc((void**) &W, (size_t) N * K * 2), "W") || !ok(cudaMalloc((void**) &X, (size_t) TMAX * K * 2), "X") || + !ok(cudaMalloc((void**) &Ya, (size_t) TMAX * N * 4), "Ya") || !ok(cudaMalloc((void**) &Yb, (size_t) TMAX * N * 4), "Yb")) return 1; + fill_f16<<<(unsigned) ((N * K + 255) / 256), 256, 0, st>>>((__half*) W, N * K, 1u + (unsigned) N, 0.05f); + fill_f16<<<(unsigned) ((TMAX * K + 255) / 256), 256, 0, st>>>((__half*) X, TMAX * K, 7u + (unsigned) K, 2.0f); + std::set ts; + const int64_t step = full ? 1 : quick ? 251 : 7; + for (int64_t t = s.t_min; t <= TMAX; t += step) ts.insert(t); + ts.insert(s.t_min); ts.insert(TMAX); + if (!quick) { + for (int64_t t = 7000; t <= 7100; ++t) if (t >= s.t_min) ts.insert(t); + for (int64_t p = 256; p <= TMAX; p *= 2) for (int64_t d = -3; d <= 3; ++d) if (p + d >= s.t_min && p + d <= TMAX) ts.insert(p + d); + for (int64_t t = 6540; t <= 6570; ++t) if (t >= s.t_min) ts.insert(t); // around the activation slices' first split (K 2560) + } + long long bad = 0, bad_outputs = 0; + int64_t first_bad = 0; + for (int64_t T : ts) { + strata::prefill::gemm_set_dense_f32(0); + gemm.f16(X, W, Ya, T, N, K); + strata::prefill::gemm_set_dense_f32(1); + gemm.f16(X, W, Yb, T, N, K); + cudaMemsetAsync(cnt, 0, 4, st); + count_diff<<<(unsigned) ((T * N + 255) / 256), 256, 0, st>>>((const unsigned*) Ya, (const unsigned*) Yb, T * N, cnt); + unsigned nd = 0; + cudaMemcpyAsync(&nd, cnt, 4, cudaMemcpyDeviceToHost, st); + if (!ok(cudaStreamSynchronize(st), "sync")) return 1; + ++cases; + if (nd) { if (!bad) first_bad = T; ++bad; bad_outputs += nd; } + } + std::printf("%-10s %5lld x %-5lld: %zu sizes from T %lld to %lld, %lld with different bits%s\n", s.what, (long long) N, (long long) K, ts.size(), + (long long) *ts.begin(), (long long) *ts.rbegin(), bad, bad ? "" : " (bitwise equal)"); + if (bad) std::printf("FAIL %s: first at T %lld, %lld outputs in all\n", s.what, (long long) first_bad, bad_outputs); + bad_cases += bad; + if (bench) { + for (int64_t T : {(int64_t) 560, (int64_t) 2048, (int64_t) 4096, (int64_t) 7040, (int64_t) 7041}) { + if (T < s.t_min) continue; + double ms[2] = {0, 0}; + for (int on = 0; on < 2; ++on) { + strata::prefill::gemm_set_dense_f32(on); + gemm.f16(X, W, Ya, T, N, K); + cudaEventRecord(e0, st); + for (int i = 0; i < 3; ++i) gemm.f16(X, W, Ya, T, N, K); + cudaEventRecord(e1, st); + cudaEventSynchronize(e1); + float t = 0; + cudaEventElapsedTime(&t, e0, e1); + ms[on] = t / 3; + } + std::printf("BENCH %-10s T %5lld | cuBLAS FP16 %7.2f ms | FP32 copies %7.2f ms (the conversions included) | %.2fx\n", s.what, (long long) T, ms[0], + ms[1], ms[0] / ms[1]); + } + } + cudaFree(W); cudaFree(X); cudaFree(Ya); cudaFree(Yb); + } + strata::prefill::gemm_set_dense_f32(-1); + std::printf("gemm_f32_parity: %lld sizes, %s\n", cases, bad_cases ? "FAILED" : "OK (bitwise)"); + return bad_cases ? 1 : 0; +} From 221616136262ecd41f3d35a3935dbe0c899e2f62 Mon Sep 17 00:00:00 2001 From: Techannel <20737840+Techannel@users.noreply.github.com> Date: Mon, 12 Oct 2026 23:40:45 +0200 Subject: [PATCH 41/67] sm_61: expert mode 8 and its own interleaved-matvec tables by default (bitwise; STRATA_SM61_TABLE=0) As sm_60 got with STRATA_SM60_TABLE, measured on a Tesla P40 (native dp4a): - native_expert_bench, 18 groups at 2 tokens on the IQ3_S pack's layers, mode 0 -> mode 8, bitwise: IQ3_S 390 -> 255 us, IQ3_XXS 345 -> 252, IQ2_S 290 -> 238, IQ4_XS 328 -> 261. - kIlRows_61 / kIl1Rows_61 from three runs of mmvq_il_parity --bench --emit-table (identical but two Q3_K cells; a cell is non-zero only where every run gained 3%). --- src/kernels/cuda/iq_kernels.cu | 7 ++++++- src/kernels/cuda/native_mmvq.cu | 29 ++++++++++++++++++++++++++--- 2 files changed, 32 insertions(+), 4 deletions(-) diff --git a/src/kernels/cuda/iq_kernels.cu b/src/kernels/cuda/iq_kernels.cu index c2e44270..439119f5 100644 --- a/src/kernels/cuda/iq_kernels.cu +++ b/src/kernels/cuda/iq_kernels.cu @@ -3425,7 +3425,12 @@ int exp_mode() { // projection 116 -> 94 us and IQ3_S gate/up 360 -> 229 us in a 28-group VRAM call); STRATA_SM60_TABLE=0 keeps the CUDA layout const char* sm60 = std::getenv("STRATA_SM60_TABLE"); const bool p100 = major == 6 && minor == 0 && (sm60 == nullptr || std::atoi(sm60) != 0); - per_dev[dev] = 1 + ((major == 7 && minor == 0 && sm70 != nullptr && std::atoi(sm70) != 0) || p100 ? 8 : kExpModeDefault); + // Pascal with dp4a (sm_61): mode 8 as well, on by default (Tesla P40, native_expert_bench on the IQ3_S pack's + // layers, an 18-group call at 2 tokens: IQ3_S 390 -> 255 us, IQ3_XXS 345 -> 252 us, IQ2_S 290 -> 238 us, + // IQ4_XS 328 -> 261 us, bitwise equal); STRATA_SM61_TABLE=0 keeps the CUDA layout + const char* sm61 = std::getenv("STRATA_SM61_TABLE"); + const bool p40 = major == 6 && minor == 1 && (sm61 == nullptr || std::atoi(sm61) != 0); + per_dev[dev] = 1 + ((major == 7 && minor == 0 && sm70 != nullptr && std::atoi(sm70) != 0) || p100 || p40 ? 8 : kExpModeDefault); } return per_dev[dev] - 1; #endif diff --git a/src/kernels/cuda/native_mmvq.cu b/src/kernels/cuda/native_mmvq.cu index ef942b20..5463d069 100644 --- a/src/kernels/cuda/native_mmvq.cu +++ b/src/kernels/cuda/native_mmvq.cu @@ -2574,6 +2574,17 @@ constexpr IlRows kIlRows_60[] = { {13, {{0, 2, 2, 2, 2}, {0, 4, 2, 2, 4}, {0, 2, 2, 2, 2}}}, // Q5_K {14, {{0, 2, 2, 2, 4}, {0, 0, 0, 4, 4}, {0, 0, 0, 4, 4}}}, // Q6_K }; +// Pascal with dp4a (sm_61), read off mmvq_il_parity --bench --emit-table on a Tesla P40 (three runs: a cell is non-zero +// only where every run picked a rows count that takes at least 3% off native_mmvq's time; where the runs disagreed on +// the count, the one that won twice). E.g. IQ4_XS 2560x10240 at 2 columns 112 -> 65 us, Q6_K 12288x2560 at 4 +// columns 189 -> 127 us, the Q5_K head at 3 columns 2545 -> 1766 us. Bitwise equal to native_mmvq. +constexpr IlRows kIlRows_61[] = { + {23, {{2, 4, 4, 4, 4}, {4, 4, 4, 4, 4}, {2, 2, 2, 2, 2}}}, // IQ4_XS + {12, {{2, 0, 4, 4, 4}, {2, 2, 2, 2, 2}, {2, 2, 2, 2, 2}}}, // Q4_K + {13, {{2, 0, 4, 4, 4}, {2, 2, 2, 2, 2}, {2, 2, 2, 2, 2}}}, // Q5_K + {14, {{0, 0, 2, 2, 2}, {0, 4, 4, 4, 4}, {2, 4, 2, 2, 2}}}, // Q6_K + {11, {{2, 2, 2, 2, 2}, {2, 2, 2, 2, 2}, {1, 1, 1, 1, 1}}}, // Q3_K +}; // RTX 30-series (sm_86), 143-dense: read off mmvq_il_parity --bench --emit-table on an RTX A4000 with the engine's real // shapes (the output projections have 6144 inputs, not 4096), per cell the rows count whose worst measured shape is under // 0.97 of native_mmvq's time. The four older rows are the shared table's; Q3_K (the Q2_0 pack's main dense type) is new. @@ -2589,8 +2600,15 @@ struct Il1Rows { int type; uint8_t r[5]; }; constexpr Il1Rows kIl1Rows_86[] = { {11, {0, 1, 1, 1, 1}}, // Q3_K: 2560x10240 60 -> 43 us, 6144x2560 30 -> 26 us on the A4000 }; +// Tesla P40 (sm_61), the same three runs: IQ4_XS 2560x10240 102 -> 58 us, the Q5_K head 1754 -> 1507 us +constexpr Il1Rows kIl1Rows_61[] = { + {23, {2, 2, 4, 4, 4}}, // IQ4_XS + {13, {0, 0, 0, 2, 2}}, // Q5_K + {11, {0, 0, 2, 2, 2}}, // Q3_K +}; struct Il1Arch { int cc; const Il1Rows* t; size_t n; }; constexpr Il1Arch kIl1Arch[] = { + {61, kIl1Rows_61, sizeof(kIl1Rows_61) / sizeof(Il1Rows)}, {86, kIl1Rows_86, sizeof(kIl1Rows_86) / sizeof(Il1Rows)}, }; bool il_env_on(const char* name) { @@ -2602,6 +2620,7 @@ bool il_q3k_on() { static const bool on = il_env_on("STRATA_MMVQ_IL_Q3K"); retur struct IlArch { int cc; const IlRows* t; size_t n; }; constexpr IlArch kIlArch[] = { {60, kIlRows_60, sizeof(kIlRows_60) / sizeof(IlRows)}, // Pascal GP100: measured on a Tesla P100 + {61, kIlRows_61, sizeof(kIlRows_61) / sizeof(IlRows)}, // Pascal with dp4a: measured on a Tesla P40 {70, kIlRows_70, sizeof(kIlRows_70) / sizeof(IlRows)}, // Volta: PR 1401, measured on a V100-SXM2 {86, kIlRows_86, sizeof(kIlRows_86) / sizeof(IlRows)}, // 143-dense: RTX A4000 with the real shapes (Q3_K added) }; @@ -2680,13 +2699,16 @@ int g_tune_rows = 0; // native_mmvq_il_tune (tests, benchmarks): rows a warp f void native_mmvq_il_tune(int rows) { g_tune_rows = rows; } namespace { -// sm_80 and newer (measured on sm_86 and sm_120) and Volta (sm_70, its own table above); Pascal/Turing keep -// native_mmvq's kernels unchanged +// sm_80 and newer (measured on sm_86 and sm_120), Volta (sm_70) and Pascal (sm_60, sm_61), each with its own table +// above; Turing keeps native_mmvq's kernels unchanged // Volta (PR 1401): opt-in with STRATA_SM70_TABLE=1 until the author confirms on a V100 with the final code bool sm70_opt_in() { const char* v = std::getenv("STRATA_SM70_TABLE"); return v != nullptr && std::atoi(v) != 0; } // Pascal (sm_60, GP100): the same interleaved kernels (bitwise equal to native_mmvq's, mmvq_il_parity), its own table // kIlRows_60. STRATA_SM60_TABLE=0 keeps native_mmvq's kernels on a P100; any other value (or unset) uses the table. bool sm60_table_on() { const char* v = std::getenv("STRATA_SM60_TABLE"); return v == nullptr || std::atoi(v) != 0; } +// Pascal (sm_61: Tesla P40 / P4, GTX 10 series; native dp4a): the same interleaved kernels (bitwise equal to +// native_mmvq's, mmvq_il_parity), its own table kIlRows_61. STRATA_SM61_TABLE=0 keeps native_mmvq's kernels. +bool sm61_table_on() { const char* v = std::getenv("STRATA_SM61_TABLE"); return v == nullptr || std::atoi(v) != 0; } bool il_arch_ok() { static int ok[16] = {}; // 0 unknown, 1 yes, -1 no, by device ordinal int dev = 0; @@ -2696,7 +2718,8 @@ bool il_arch_ok() { int minor = 0; cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, dev); ok[dev] = (cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) == cudaSuccess && - (major >= 8 || (major == 7 && minor == 0 && sm70_opt_in()) || (major == 6 && minor == 0 && sm60_table_on()))) ? 1 : -1; + (major >= 8 || (major == 7 && minor == 0 && sm70_opt_in()) || (major == 6 && minor == 0 && sm60_table_on()) || + (major == 6 && minor == 1 && sm61_table_on()))) ? 1 : -1; } return ok[dev] > 0; } From 5025324c2b315e9c4f98e32072514a3e23b2935c Mon Sep 17 00:00:00 2001 From: Techannel <20737840+Techannel@users.noreply.github.com> Date: Mon, 12 Oct 2026 23:40:45 +0200 Subject: [PATCH 42/67] docs + bench: the Tesla P40 (sm_61) profile, the four changes and their measurements bench/results/2026-10-12-p40-sm61-kernels: where a prompt and a decode window spend their time on a P40, the kernel benches and parity runs, every request of the engine A/B (565-token prompt 205 -> 255 tok/s, decode 34-35 -> 37-38 tok/s; with STRATA_DENSE_F32=1 a 7K prompt 360-432 -> 464-474 tok/s), the byte comparison of the answers, and what was not tested. docs/OLDER_GPUS.md: the sm_61 section and switches, and two traps when measuring on such a card. --- .../2026-10-12-p40-sm61-kernels/README.md | 188 ++++ .../2026-10-12-p40-sm61-kernels/bench.py | 28 + .../dequant-wide-parity.txt | 25 + .../engine-runs.txt | 105 ++ .../equal_check.py | 27 + .../fused-gr-bench.txt | 37 + .../gemm-f32-parity.txt | 28 + .../gemm-sweep.txt | 923 ++++++++++++++++++ .../2026-10-12-p40-sm61-kernels/gemm_sweep.cu | 86 ++ .../mmvq-il-bench-p40-run1.txt | 133 +++ .../mmvq-il-bench-p40-run2.txt | 133 +++ .../mmvq-il-bench-p40-run3.txt | 133 +++ .../native-expert-bench.txt | 55 ++ .../nvprof-base.txt | 280 ++++++ .../profile-base.txt | 32 + .../profile-new.txt | 32 + docs/COMMUNITY_BENCHMARKS.md | 3 + docs/OLDER_GPUS.md | 52 +- 18 files changed, 2298 insertions(+), 2 deletions(-) create mode 100644 bench/results/2026-10-12-p40-sm61-kernels/README.md create mode 100644 bench/results/2026-10-12-p40-sm61-kernels/bench.py create mode 100644 bench/results/2026-10-12-p40-sm61-kernels/dequant-wide-parity.txt create mode 100644 bench/results/2026-10-12-p40-sm61-kernels/engine-runs.txt create mode 100755 bench/results/2026-10-12-p40-sm61-kernels/equal_check.py create mode 100644 bench/results/2026-10-12-p40-sm61-kernels/fused-gr-bench.txt create mode 100644 bench/results/2026-10-12-p40-sm61-kernels/gemm-f32-parity.txt create mode 100644 bench/results/2026-10-12-p40-sm61-kernels/gemm-sweep.txt create mode 100644 bench/results/2026-10-12-p40-sm61-kernels/gemm_sweep.cu create mode 100644 bench/results/2026-10-12-p40-sm61-kernels/mmvq-il-bench-p40-run1.txt create mode 100644 bench/results/2026-10-12-p40-sm61-kernels/mmvq-il-bench-p40-run2.txt create mode 100644 bench/results/2026-10-12-p40-sm61-kernels/mmvq-il-bench-p40-run3.txt create mode 100644 bench/results/2026-10-12-p40-sm61-kernels/native-expert-bench.txt create mode 100644 bench/results/2026-10-12-p40-sm61-kernels/nvprof-base.txt create mode 100644 bench/results/2026-10-12-p40-sm61-kernels/profile-base.txt create mode 100644 bench/results/2026-10-12-p40-sm61-kernels/profile-new.txt diff --git a/bench/results/2026-10-12-p40-sm61-kernels/README.md b/bench/results/2026-10-12-p40-sm61-kernels/README.md new file mode 100644 index 00000000..e5843878 --- /dev/null +++ b/bench/results/2026-10-12-p40-sm61-kernels/README.md @@ -0,0 +1,188 @@ +# Tesla P40 (sm_61): wide dequantization, the dense GEMMs as cublasSgemm (opt-in), expert mode 8 and a matvec table (2026-10-12) + +One Tesla P40 with IQ3_S. The card is the bottleneck of the prompt and of the decode, so the profile was read first +and four things were changed where it pointed. Each gives exactly the bits of what it replaces. + +| What | Was on sm_61 | Now on sm_61 | Switch | +| --- | --- | --- | --- | +| Dequantization of the dense weights for the prompt GEMMs (Q4_K / Q5_K / Q6_K / IQ4_XS) | a thread per 32 values, byte loads, 2-byte stores 64 bytes apart | a thread per 8 values, 16-bit loads, one 16-byte store | on by default, `STRATA_DEQUANT_WIDE=0` | +| The large dense prompt GEMMs (qkv, query, gate and output projections) | `cublasGemmEx` on FP16 operands | `cublasSgemm` on FP32 copies | **opt-in**, `STRATA_DENSE_F32=1` | +| Routed experts in VRAM (`native_expert_grouped`) | the CUDA layout (mode 0) | mode 8 | on by default, `STRATA_SM61_TABLE=0` | +| Dense 1-4 column GEMVs and the head (`native_mmvq_il`) | `native_mmvq` | the interleaved kernel with a table read off the P40 (`kIlRows_61`, `kIl1Rows_61`) | on by default, `STRATA_SM61_TABLE=0` | + +Through the server, medians of 3 requests, two runs per build alternated, every run started with the card at 65 C: + +| | `a0116b2` | this change (defaults) | this change + `STRATA_DENSE_F32=1` | +| --- | ---: | ---: | ---: | +| 565-token prompt, tok/s | 203 / 205 and 205 / 210 | 256 / 255 | 254 / 252 | +| 7,047-token prompt, tok/s | 360-365 or 430-432, by the token count (below) | 369-374 or 437-443, by the token count | 464-474 at every count | +| decode after the short prompt, tok/s | 35.0 / 34.2 and 35.4 / 34.4 | 38.2 / 37.2 | 37.7 / 37.9 | +| decode after the long prompt, tok/s | 33.1 / 33.3 and 32.1 / 33.4 | 33.5 / 35.6 | 35.9 / 34.0 | + +The decode gain is small (+6-10% after the short prompt) and inside the spread of single requests; it is the same +size in the GPU stage profile (49.1 -> 45.6 ms per window), which is the steadier measurement. + +## Rig + +- Tesla P40 24 GB (sm_61, PCIe gen3 x16, 250 W limit), driver 550.163.01. A Proxmox VM with the card passed through: + 20 vCPUs of a Xeon E5-2695 v4 (AVX2, no AVX-512), 98 GB RAM, Debian 13, kernel 6.12. The model is on a virtual + disk that reads as rotational; every run had the files in the page cache. Nothing else used the card. +- CUDA 12.4.131 (Debian's toolkit; **cuBLAS 12.4.5.8**), GCC 14.2. +- Engine: `main` at `a0116b2` (0.1.43.1), `-DCMAKE_CUDA_ARCHITECTURES=61 -DSTRATA_EXPERIMENTAL_SM60=ON`, built + unchanged ("base") and with this change. The server and everything else unchanged. +- Model: setup's IQ3_S (`ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF`, both shards, the native pack, the shipped + expert profile and MTP head). Setup's config after `setup.sh --calibrate`: `--expert-cache auto --prefill auto + --spec 4 --spec-min-p 0.70 --mtp --max-context 262144 --kv int8 --kv-resident 32768 --vision --vram-reserve-mib 700 + --pcie-frac 0.00 --conversation-cache-mib 8192 --conversation-cache-slots 4`, **with the experimental speed + projection on** (layers 4-44, project mode). 8,225 expert slots in VRAM (15.6 GiB), 46.8 GiB of experts in RAM, + 19 pool workers, prompt chunks of up to 8,192 tokens. +- Requests: `bench.py` (here): a ~565-token prompt with 200 new tokens and a ~7,047-token prompt with 60, three + each, greedy, `reasoning_effort` none, a random first line so nothing is reused. Speeds are the engine's own lines. + +## Where the time goes on a P40 (base build) + +`STRATA_PREFILL_TIMING=1 STRATA_DECODE_TIMING=1 STRATA_VERIFY_PROFILE=1` ([profile-base.txt](profile-base.txt)), and +one run under `nvprof` for the kernels' names. + +- The prompt's GPU timeline equals its wall time (7,038 tokens: 16,005 of 16,070 ms). Waiting for expert copies is + 0.2% of it, the host's grouping 0.2%. The dense projections' GEMMs (GDN in and out, QSA) are 36%, the experts + (MMQ: gate/up, down, combine) 28%, the hyper-connection read 13%, the attention 12%. +- A 559-token prompt (2,469 ms) spends 24% in the GDN input projections and 21% in the experts' gate/up, and about + 0.5 s of it in `dequant_kernel`: every dense weight is dequantized once per chunk, whatever the chunk's + length (768 calls and 2.72 s over six prompts under nvprof, 3.5 ms a call). +- A decode window is 49 ms of GPU stages with 1-3 ms of CPU experts (hit rate 99%): dense GEMVs ~15 ms, the experts + in VRAM ~12.5 ms, the hyper-connection reads ~8.5 ms, the head 2.9 ms. + +What that leaves alone: `cublasSgemm` already runs at 8.5-10 TFLOPS on this card (11.8 at its boost clock), ggml's +MMQ has its own Pascal dp4a configuration, and the decode GEMVs sit at 60-90% of the memory bandwidth the wide +dequant kernel reaches (227 GB/s). No larger kernel lever was found. + +## Kernels (no engine) + +**Dequantization**, `dequant_wide_parity --bench` ([dequant-wide-parity.txt](dequant-wide-parity.txt)): 360 cases +bitwise (FP16, BF16, FP32 out, a padded row stride, row slices; sane blocks and raw random bytes), FP16 out: + +| Shape | per-group | wide | | +| --- | ---: | ---: | ---: | +| Q6_K 10240 x 2560 | 7.25 ms (10 GB/s) | 0.33 ms (227 GB/s) | 22.3x | +| Q6_K 2560 x 6144 | 4.45 ms | 0.20 ms | 22.5x | +| Q4_K 10240 x 2560 | 1.67 ms | 0.32 ms | 5.2x | +| Q5_K 10240 x 2560 | 1.24 ms | 0.33 ms | 3.8x | +| IQ4_XS 10240 x 2560 | 1.21 ms | 0.34 ms | 3.6x | + +**The FP16-operand GEMM**, a sweep of the chunk size T ([gemm-sweep.txt](gemm-sweep.txt), `gemm_sweep.cu`, cuBLAS +only). cuBLAS 12.4 has two kernels for FP16 operands with FP32 sums on this card, `maxwell_sgemm_fp16_64x64_tn` and +`_32x128_tn`, and for most T it picks the slower one: + +| Shape | `cublasGemmEx` FP16 operands | `cublasSgemm` FP32 copies | +| --- | --- | --- | +| qkv 10240 x 2560 | 7.6 TFLOPS at 27 of the 76 sizes sampled from T 256 (T 7,030-7,040 among them), **4.3-4.6 at the others** (49 -> 85 ms from T 7,040 to 7,041) | 6.8-10.0 from T 256, 8.4-9.6 from 512 (39-42 ms at 7K) | +| query 12288 x 2560 | 7.5 at 24 of the 76 sizes, 3.8-4.7 at the others (103 ms at 7,041) | 6.7-9.8 from 256, 8.4-9.8 from 512 (47-50 ms at 7K) | +| gate 6144 x 2560 | 7.3-7.8 at 26 of the 65 sizes from T 512 (up to ~1,100, and 7,030-7,040), 4.5-6.1 at the others | 8.2-9.7 from 512 | +| out 2560 x 6144 | 7-8 at 23 of the 47 sizes from T 4,096, 4.4-6.2 at the others | 8.3-9.2 from 4,096 | + +So the base build reads a 7K-token prompt in 16.3 s when its chunk has 7,040 tokens or fewer and in 19.5 s when it +has 7,041 or more. The two results are bitwise equal wherever both run a Maxwell kernel; below T ~144 (6,144+ rows) +or ~408 (2,560 rows) cuBLAS takes another kernel family for one of them and the bits differ, so the route starts at +T 256 / 512 / 4,096 for the three groups of shapes. `gemm_f32_parity --bench` +([gemm-f32-parity.txt](gemm-f32-parity.txt)) runs `Gemm::f16` both ways: **5,201 chunk sizes bitwise** (every 7th T +to 8,192, every T of 7,000-7,100, around the powers of two and the activation slices' split), and with the +conversions included qkv at T 7,041 85.4 -> 44.7 ms, at 560 6.5 -> 4.4 ms; the gate projection at 560 and the +4,096-column output projection at 4,096 are 5-7% slower that way (2.9 -> 3.05 ms, 12.3 -> 13.3 ms). + +**That equality is a property of this cuBLAS build**, not of the code: which kernel cuBLAS picks, and that both +add in the same order, was measured with 12.4.5.8 only. Hence opt-in. `gemm_f32_parity` is the check for another +library (CUDA 12.9's, the ready-made CUDA 12 engine's). + +**Experts**, `native_expert_bench 0,5,11,17,23,29,35,41,47 18 2 0 8` (18 groups, 2 tokens, the model's real +rows, bitwise on all nine layers; [native-expert-bench.txt](native-expert-bench.txt)): + +| Layer gate/up / down | mode 0 | mode 8 | +| --- | ---: | ---: | +| IQ3_S / IQ4_NL | 390 us | 255 us | +| IQ3_XXS / IQ4_NL | 345 us | 252 us | +| IQ2_S / IQ4_NL | 290 us | 238 us | +| IQ4_XS / IQ4_NL | 328 us | 261 us | + +Modes 2, 5 and 6 are slower than mode 0 here, mode 7 is 3-6% behind mode 8. + +**Dense GEMVs**, `mmvq_il_parity --bench --emit-table`, three runs +([mmvq-il-bench-p40-run1.txt](mmvq-il-bench-p40-run1.txt), run2, run3). The three emitted tables are identical but +for two Q3_K cells (4 columns below 2,048 rows: 1, 1, 2 -> 1; one column at 2,048-4,095 rows: 2, 2, 0 -> 0). A few +cells of run 1: + +| Shape | columns | `native_mmvq` | interleaved | +| --- | ---: | ---: | ---: | +| IQ4_XS 2560 x 10,240 | 2 | 111.8 us | 65.0 us (rows 4) | +| Q6_K 2560 x 12,288 | 4 | 189.3 us | 127.4 us (rows 2) | +| Q6_K 2560 x 10,240 | 1 | 92.6 us | 109.7 us (rows 2): the table keeps `native_mmvq` for one Q6_K column | +| Q5_K head 2560 x 248,320 | 3 | 2,545 us | 1,766 us (rows 2) | +| Q5_K head 2560 x 248,320 | 1 | 1,754 us | 1,507 us (rows 2) | + +**Not taken**: the latency-hidden hyper-connection read ([fused-gr-bench.txt](fused-gr-bench.txt), bitwise): 82.0 +-> 88.2 us at one token, 92.4 -> 102.6 at two, faster only from five (192 -> 181 us). sm_61 keeps the plain one. + +## Engine + +[engine-runs.txt](engine-runs.txt) has every request. Each run is one server start; before it the card cooled to +65 C (it ends a run at 82-84 C). Two builds of the change were run: without the GEMM route (what this change does by +default) and with it (`STRATA_DENSE_F32=1`). + +Prompt read time by the prompt's token count, engine ms (a chunk has 7 tokens fewer): + +| prompt tokens | base | defaults | + `STRATA_DENSE_F32=1` | +| ---: | --- | --- | --- | +| 7,043 | 16,374 / 16,370 | 15,905 | 14,845 | +| 7,046 | 16,352 / 16,334 | 15,963 | 15,065 | +| 7,047 | 16,325 / 16,318 | 16,136 | 15,191 / 14,863 | +| 7,048 | 19,540 / 19,384 / 19,600 / 19,489 / 19,334 | 19,081 / 18,902 / 18,856 | (no request of this size) | +| 7,049 | 19,533 | (no request of this size) | 14,861 / 14,914 | + +GPU stages per verify window (`STRATA_VERIFY_PROFILE=1`; three requests after the short prompt 49.2 / 48.3 / 49.1 -> +46.8 / 45.6 / 45.0 ms, after the long one 48.2 / 49.5 / 49.0 -> 45.2 / 45.2 / 44.9 ms). VRAM hits 9.6 + +3.1 -> 7.5 + 2.5 ms, the GDN qkv / gate GEMVs 4.2 + 2.5 -> 3.9 + 2.2 ms, the QSA query GEMV 1.83 -> 1.60 ms, the +head 2.87 -> 2.45 ms; the other stages unchanged ([profile-base.txt](profile-base.txt), +[profile-new.txt](profile-new.txt)). + +With `STRATA_DEQUANT_WIDE=0 STRATA_SM61_TABLE=0 STRATA_DENSE_F32=0` the changed build measures as the base one: +210 tok/s short, 360 / 431 / 365 tok/s long (7,048 / 7,047 / 7,048 tokens), decode 33.3 tok/s. + +## Answers + +Seven fixed prompts (`equal_check.py`: code, prose, arithmetic, JSON, Italian, a 2.6K-token summary, a needle in 3K +tokens), greedy, first requests after a start. With `--prompt-cache 0 --adapt-swaps 0 --pcie-frac 0 +STRATA_PREFILL_CPU_SHARE=0 STRATA_ROUTE_TAIL_SKIP=0 STRATA_IQ_MT_MIN=1`, two runs of the base build and two of the +changed one (GEMM route on) give **byte-identical answers, 4 of 4 runs on 7 of 7 prompts** (2,900 characters each). + +Without `STRATA_IQ_MT_MIN=1` that comparison cannot be made on this CPU: the same build gave two different answers +to the Italian prompt in two runs (drafts accepted 34 of 65 against 33 of 69). 60% of that prompt's experts run on +the CPU, where a lone token's rows round differently from a group's (`native_gu_mt_min`), and how many drafts a +window holds depends on timing. + +## Two traps on such a card + +- **Temperature.** This P40 reaches 87-89 C within minutes of work; at 89 C `nvidia-smi -q -d PERFORMANCE` shows + `SW Thermal Slowdown: Active` and the clock goes from 1,531 to ~1,300 MHz. Runs made one after another without the + cool-down gave the later arm 10-20% less on the long prompt. +- **The token count.** Before the GEMM route, a long prompt's speed has two values, and a random nonce in the prompt + moves it across the 7,040-token line: what looks like 20% of run-to-run noise is one cuBLAS kernel choice. + +## Not tested + +- Any other sm_61 card (Tesla P4, GTX 10 series), Windows, two cards or a layer split, `--batch`. +- cuBLAS other than 12.4.5.8 (see above), the CUDA 13 build, HIP and SYCL: only the sm_61 CUDA 12.4 build (and a + compile of the two libraries without `STRATA_EXPERIMENTAL_SM60`) was built here. +- Prompts above 7K tokens, the 32K / 128K sweep, long-context needles, a quality suite: one needle at 3K tokens and + the byte comparison above are all there is. +- The engine A/B above was made with two builds of this code that differ from the commits here only in the GEMM + route's default (absent in the first, on by default in the second, where it is `STRATA_DENSE_F32=1` here). On the + commits as they are: the three parity tools on the P40 (`gemm_f32_parity --quick`, 134 sizes) and one engine pass + each way, the last lines of `engine-runs.txt`: by default 261 tok/s short, 439-446 tok/s long (7,045-7,047 tokens, + the fast side of the line), decode 38.1 / 36.0 tok/s; with `STRATA_DENSE_F32=1` 250 tok/s short, 465-473 long, + decode 37.6 / 34.3. + +## Files + +`engine-runs.txt` (every request), `profile-base.txt`, `profile-new.txt` (the timing lines), the kernel outputs +named above, `nvprof-base.txt` (the base build's kernels over three short and three long prompts), `bench.py`, +`equal_check.py`, `gemm_sweep.cu`. diff --git a/bench/results/2026-10-12-p40-sm61-kernels/bench.py b/bench/results/2026-10-12-p40-sm61-kernels/bench.py new file mode 100644 index 00000000..32ddc4ac --- /dev/null +++ b/bench/results/2026-10-12-p40-sm61-kernels/bench.py @@ -0,0 +1,28 @@ +#!/usr/bin/env python3 +"""bench.py LOGFILE LABEL [--runs 3] - fixed prompts straight to the engine (BENCH_PORT, default 8081): thinking off, +temperature 0, a random first line so nothing is reused from the prompt / conversation cache; then the speeds the +engine itself logged. short = ~565-token prompt + 200 tokens out; long = ~7,047-token prompt + 60 tokens out. +Prints every request and the medians: prompt tok/s and decode tok/s per case.""" +import json, os, random, re, statistics, sys, time, urllib.request +LOG, LABEL = sys.argv[1], sys.argv[2]; RUNS = int(sys.argv[sys.argv.index("--runs") + 1]) if "--runs" in sys.argv else 3 +WORDS = ("the engine reads a prompt and writes an answer while the cache keeps the experts that were used most often " + "in the last rounds so a second request with a different first line has to be read again from the start").split() +def text(n, seed): + r = random.Random(seed); return " ".join(r.choice(WORDS) for _ in range(n)) +def ask(prompt, max_tokens): + body = {"model": "qwen3.8-flash-next-iq3_s", "messages": [{"role": "user", "content": prompt}], "max_tokens": max_tokens, "temperature": 0, + "reasoning_effort": "none", "stream": False} + req = urllib.request.Request("http://127.0.0.1:%s/v1/chat/completions" % os.environ.get("BENCH_PORT", "8081"), json.dumps(body).encode(), {"Content-Type": "application/json"}) + t = time.time(); out = json.load(urllib.request.urlopen(req, timeout=1800)); return time.time() - t, out +PAT = re.compile(r"prompt (\d+) tokens = (\d+) reused \+ (\d+) read in (\d+) ms \(([\d.]+) tok/s\), (\d+) generated in (\d+) ms \(([\d.]+) tok/s\)") +res = {} +for case, n, mt in (("short", 520, 200), ("long", 7000, 60)): + for i in range(RUNS): + nonce = "%016x" % random.getrandbits(64); before = sum(1 for _ in open(LOG, errors="replace")) + wall, out = ask(f"Run {nonce}. Continue this text with a long plain description of a harbour town, no lists.\n\n" + text(n, case), mt) + time.sleep(1.5); lines = open(LOG, errors="replace").read().split("\n")[before:]; m = [PAT.search(l) for l in lines]; m = [x for x in m if x] + if not m: print(case, i, "no log line", wall); continue + g = m[-1].groups(); res.setdefault(case, []).append((float(g[4]), float(g[7]), int(g[0]), int(g[2]), int(g[5]), wall)) + print(f"{LABEL} {case} run {i}: prompt {g[0]} tok ({g[2]} read) at {g[4]} tok/s | {g[5]} generated at {g[7]} tok/s | wall {wall:.1f}s", flush=True) +for case, v in res.items(): + print(f"== {LABEL} {case}: prompt median {statistics.median(x[0] for x in v):.0f} tok/s | decode median {statistics.median(x[1] for x in v):.1f} tok/s | n={len(v)}") diff --git a/bench/results/2026-10-12-p40-sm61-kernels/dequant-wide-parity.txt b/bench/results/2026-10-12-p40-sm61-kernels/dequant-wide-parity.txt new file mode 100644 index 00000000..9ae9bc7c --- /dev/null +++ b/bench/results/2026-10-12-p40-sm61-kernels/dequant-wide-parity.txt @@ -0,0 +1,25 @@ +BENCH Q4_K 10240x2560 per-group 1.671 ms ( 40.2 GB/s) | wide 0.323 ms (208.0 GB/s) | 5.18x +BENCH Q4_K 6144x2560 per-group 1.083 ms ( 37.2 GB/s) | wide 0.194 ms (207.4 GB/s) | 5.57x +BENCH Q4_K 2560x6144 per-group 1.074 ms ( 37.5 GB/s) | wide 0.194 ms (207.5 GB/s) | 5.53x +BENCH Q4_K 12288x2560 per-group 1.933 ms ( 41.7 GB/s) | wide 0.385 ms (209.1 GB/s) | 5.02x +BENCH Q4_K 512x2560 per-group 0.070 ms ( 48.3 GB/s) | wide 0.019 ms (179.2 GB/s) | 3.71x +BENCH Q4_K 2560x4096 per-group 0.753 ms ( 35.7 GB/s) | wide 0.130 ms (206.0 GB/s) | 5.77x +BENCH Q5_K 10240x2560 per-group 1.238 ms ( 56.9 GB/s) | wide 0.330 ms (213.4 GB/s) | 3.75x +BENCH Q5_K 6144x2560 per-group 0.747 ms ( 56.6 GB/s) | wide 0.199 ms (212.1 GB/s) | 3.75x +BENCH Q5_K 2560x6144 per-group 0.746 ms ( 56.6 GB/s) | wide 0.199 ms (211.9 GB/s) | 3.74x +BENCH Q5_K 12288x2560 per-group 1.482 ms ( 57.0 GB/s) | wide 0.396 ms (213.7 GB/s) | 3.75x +BENCH Q5_K 512x2560 per-group 0.069 ms ( 50.8 GB/s) | wide 0.019 ms (182.5 GB/s) | 3.59x +BENCH Q5_K 2560x4096 per-group 0.502 ms ( 56.1 GB/s) | wide 0.134 ms (210.2 GB/s) | 3.75x +BENCH Q6_K 10240x2560 per-group 7.248 ms ( 10.2 GB/s) | wide 0.326 ms (227.0 GB/s) | 22.25x +BENCH Q6_K 6144x2560 per-group 4.448 ms ( 10.0 GB/s) | wide 0.197 ms (224.7 GB/s) | 22.53x +BENCH Q6_K 2560x6144 per-group 4.450 ms ( 10.0 GB/s) | wide 0.198 ms (224.5 GB/s) | 22.51x +BENCH Q6_K 12288x2560 per-group 8.667 ms ( 10.2 GB/s) | wide 0.392 ms (226.6 GB/s) | 22.14x +BENCH Q6_K 512x2560 per-group 0.085 ms ( 43.6 GB/s) | wide 0.020 ms (187.5 GB/s) | 4.30x +BENCH Q6_K 2560x4096 per-group 2.908 ms ( 10.2 GB/s) | wide 0.133 ms (222.2 GB/s) | 21.86x +BENCH IQ4_XS 10240x2560 per-group 1.209 ms ( 54.9 GB/s) | wide 0.337 ms (197.2 GB/s) | 3.59x +BENCH IQ4_XS 6144x2560 per-group 0.732 ms ( 54.4 GB/s) | wide 0.204 ms (195.6 GB/s) | 3.60x +BENCH IQ4_XS 2560x6144 per-group 0.732 ms ( 54.4 GB/s) | wide 0.204 ms (195.5 GB/s) | 3.59x +BENCH IQ4_XS 12288x2560 per-group 1.448 ms ( 55.0 GB/s) | wide 0.403 ms (197.7 GB/s) | 3.60x +BENCH IQ4_XS 512x2560 per-group 0.068 ms ( 48.9 GB/s) | wide 0.021 ms (160.0 GB/s) | 3.27x +BENCH IQ4_XS 2560x4096 per-group 0.494 ms ( 53.7 GB/s) | wide 0.137 ms (193.4 GB/s) | 3.60x +dequant_wide_parity: 360 cases, OK (bitwise) diff --git a/bench/results/2026-10-12-p40-sm61-kernels/engine-runs.txt b/bench/results/2026-10-12-p40-sm61-kernels/engine-runs.txt new file mode 100644 index 00000000..3236e2fa --- /dev/null +++ b/bench/results/2026-10-12-p40-sm61-kernels/engine-runs.txt @@ -0,0 +1,105 @@ +# Every request of the engine A/B (bench.py). One server start per label; the card at 65 C before each. +# A3..A6-base: a0116b2 unchanged. B3-new, B4-new: the change without the GEMM route (its defaults). +# B5-new, B6-new: with the GEMM route (STRATA_DENSE_F32=1 here). off-switches: the B5/B6 build with +# STRATA_DEQUANT_WIDE=0 STRATA_SM61_TABLE=0 STRATA_DENSE_F32=0. Order as run: A3 B3 A4 B4, then A5 B5 A6 B6 off. +# PR-default, PR-dense: the commits as pushed, one pass each, without and with STRATA_DENSE_F32=1 (the first +# started at 54 C, the second at 64 C). +A3-base-p1 short run 0: prompt 565 tok (565 read) at 208.4 tok/s | 200 generated at 32.1 tok/s | wall 9.0s +A3-base-p1 short run 1: prompt 565 tok (565 read) at 202.9 tok/s | 200 generated at 35.0 tok/s | wall 8.5s +A3-base-p1 short run 2: prompt 566 tok (566 read) at 185.9 tok/s | 200 generated at 36.2 tok/s | wall 8.6s +A3-base-p1 long run 0: prompt 7048 tok (7048 read) at 360.7 tok/s | 60 generated at 32.4 tok/s | wall 21.4s +A3-base-p1 long run 1: prompt 7047 tok (7047 read) at 431.7 tok/s | 60 generated at 33.3 tok/s | wall 18.1s +A3-base-p1 long run 2: prompt 7048 tok (7048 read) at 363.6 tok/s | 60 generated at 33.1 tok/s | wall 21.2s +== A3-base-p1 short: prompt median 203 tok/s | decode median 35.0 tok/s | n=3 +== A3-base-p1 long: prompt median 364 tok/s | decode median 33.1 tok/s | n=3 +A3-base: GPU at the end 83 C; clock under load (util >= 90): mean 1515 MHz, min 1392 MHz, 43 samples +B3-new-p1 short run 0: prompt 565 tok (565 read) at 251.3 tok/s | 200 generated at 34.5 tok/s | wall 8.1s +B3-new-p1 short run 1: prompt 567 tok (567 read) at 256.6 tok/s | 200 generated at 38.2 tok/s | wall 7.5s +B3-new-p1 short run 2: prompt 566 tok (566 read) at 255.8 tok/s | 200 generated at 38.6 tok/s | wall 7.4s +B3-new-p1 long run 0: prompt 7048 tok (7048 read) at 369.4 tok/s | 60 generated at 33.5 tok/s | wall 20.9s +B3-new-p1 long run 1: prompt 7048 tok (7048 read) at 372.9 tok/s | 60 generated at 33.5 tok/s | wall 20.7s +B3-new-p1 long run 2: prompt 7043 tok (7043 read) at 442.8 tok/s | 60 generated at 37.3 tok/s | wall 17.5s +== B3-new-p1 short: prompt median 256 tok/s | decode median 38.2 tok/s | n=3 +== B3-new-p1 long: prompt median 373 tok/s | decode median 33.5 tok/s | n=3 +B3-new: GPU at the end 83 C; clock under load (util >= 90): mean 1512 MHz, min 1379 MHz, 41 samples +A4-base-p1 short run 0: prompt 567 tok (567 read) at 197.6 tok/s | 200 generated at 32.0 tok/s | wall 9.1s +A4-base-p1 short run 1: prompt 567 tok (567 read) at 210.2 tok/s | 200 generated at 34.2 tok/s | wall 8.6s +A4-base-p1 short run 2: prompt 566 tok (566 read) at 205.4 tok/s | 200 generated at 34.7 tok/s | wall 8.5s +A4-base-p1 long run 0: prompt 7049 tok (7049 read) at 360.9 tok/s | 60 generated at 34.1 tok/s | wall 21.3s +A4-base-p1 long run 1: prompt 7047 tok (7047 read) at 431.9 tok/s | 60 generated at 33.3 tok/s | wall 18.1s +A4-base-p1 long run 2: prompt 7043 tok (7043 read) at 430.1 tok/s | 60 generated at 32.9 tok/s | wall 18.2s +== A4-base-p1 short: prompt median 205 tok/s | decode median 34.2 tok/s | n=3 +== A4-base-p1 long: prompt median 430 tok/s | decode median 33.3 tok/s | n=3 +A4-base: GPU at the end 83 C; clock under load (util >= 90): mean 1495 MHz, min 1379 MHz, 40 samples +B4-new-p1 short run 0: prompt 565 tok (565 read) at 254.7 tok/s | 200 generated at 34.0 tok/s | wall 8.1s +B4-new-p1 short run 1: prompt 564 tok (564 read) at 242.4 tok/s | 200 generated at 37.2 tok/s | wall 7.7s +B4-new-p1 short run 2: prompt 565 tok (565 read) at 255.2 tok/s | 200 generated at 37.8 tok/s | wall 7.5s +B4-new-p1 long run 0: prompt 7047 tok (7047 read) at 436.7 tok/s | 60 generated at 34.9 tok/s | wall 17.9s +B4-new-p1 long run 1: prompt 7046 tok (7046 read) at 441.4 tok/s | 60 generated at 36.6 tok/s | wall 17.6s +B4-new-p1 long run 2: prompt 7048 tok (7048 read) at 373.8 tok/s | 60 generated at 35.6 tok/s | wall 20.6s +== B4-new-p1 short: prompt median 255 tok/s | decode median 37.2 tok/s | n=3 +== B4-new-p1 long: prompt median 437 tok/s | decode median 35.6 tok/s | n=3 +B4-new: GPU at the end 83 C; clock under load (util >= 90): mean 1487 MHz, min 1379 MHz, 36 samples +A5-base-p1 short run 0: prompt 564 tok (564 read) at 206.6 tok/s | 200 generated at 29.9 tok/s | wall 9.5s +A5-base-p1 short run 1: prompt 567 tok (567 read) at 199.3 tok/s | 200 generated at 35.4 tok/s | wall 8.5s +A5-base-p1 short run 2: prompt 566 tok (566 read) at 204.6 tok/s | 200 generated at 35.7 tok/s | wall 8.4s +A5-base-p1 long run 0: prompt 7048 tok (7048 read) at 359.6 tok/s | 60 generated at 32.0 tok/s | wall 21.5s +A5-base-p1 long run 1: prompt 7046 tok (7046 read) at 430.9 tok/s | 60 generated at 33.4 tok/s | wall 18.2s +A5-base-p1 long run 2: prompt 7043 tok (7043 read) at 430.2 tok/s | 60 generated at 32.1 tok/s | wall 18.3s +== A5-base-p1 short: prompt median 205 tok/s | decode median 35.4 tok/s | n=3 +== A5-base-p1 long: prompt median 430 tok/s | decode median 32.1 tok/s | n=3 +A5-base: GPU at the end 84 C; clock under load (util >= 90): mean 1498 MHz, min 1379 MHz, 40 samples +B5-new-p1 short run 0: prompt 565 tok (565 read) at 253.8 tok/s | 200 generated at 34.7 tok/s | wall 8.0s +B5-new-p1 short run 1: prompt 565 tok (565 read) at 243.7 tok/s | 200 generated at 37.7 tok/s | wall 7.6s +B5-new-p1 short run 2: prompt 562 tok (562 read) at 274.2 tok/s | 200 generated at 37.9 tok/s | wall 7.3s +B5-new-p1 long run 0: prompt 7046 tok (7046 read) at 467.7 tok/s | 60 generated at 33.9 tok/s | wall 16.9s +B5-new-p1 long run 1: prompt 7043 tok (7043 read) at 474.4 tok/s | 60 generated at 37.1 tok/s | wall 16.5s +B5-new-p1 long run 2: prompt 7049 tok (7049 read) at 474.3 tok/s | 60 generated at 35.9 tok/s | wall 16.5s +== B5-new-p1 short: prompt median 254 tok/s | decode median 37.7 tok/s | n=3 +== B5-new-p1 long: prompt median 474 tok/s | decode median 35.9 tok/s | n=3 +B5-new: GPU at the end 83 C; clock under load (util >= 90): mean 1525 MHz, min 1493 MHz, 37 samples +A6-base-p1 short run 0: prompt 567 tok (567 read) at 209.9 tok/s | 200 generated at 30.0 tok/s | wall 9.4s +A6-base-p1 short run 1: prompt 567 tok (567 read) at 198.8 tok/s | 200 generated at 34.4 tok/s | wall 8.7s +A6-base-p1 short run 2: prompt 565 tok (565 read) at 214.6 tok/s | 200 generated at 35.3 tok/s | wall 8.3s +A6-base-p1 long run 0: prompt 7048 tok (7048 read) at 361.6 tok/s | 60 generated at 33.6 tok/s | wall 21.3s +A6-base-p1 long run 1: prompt 7048 tok (7048 read) at 364.5 tok/s | 60 generated at 33.4 tok/s | wall 21.1s +A6-base-p1 long run 2: prompt 7046 tok (7046 read) at 431.4 tok/s | 60 generated at 32.7 tok/s | wall 18.2s +== A6-base-p1 short: prompt median 210 tok/s | decode median 34.4 tok/s | n=3 +== A6-base-p1 long: prompt median 364 tok/s | decode median 33.4 tok/s | n=3 +A6-base: GPU at the end 84 C; clock under load (util >= 90): mean 1512 MHz, min 1379 MHz, 40 samples +B6-new-p1 short run 0: prompt 565 tok (565 read) at 251.6 tok/s | 200 generated at 34.8 tok/s | wall 8.0s +B6-new-p1 short run 1: prompt 567 tok (567 read) at 252.2 tok/s | 200 generated at 38.4 tok/s | wall 7.5s +B6-new-p1 short run 2: prompt 565 tok (565 read) at 254.7 tok/s | 200 generated at 37.9 tok/s | wall 7.5s +B6-new-p1 long run 0: prompt 7047 tok (7047 read) at 463.9 tok/s | 60 generated at 34.0 tok/s | wall 17.0s +B6-new-p1 long run 1: prompt 7047 tok (7047 read) at 474.1 tok/s | 60 generated at 35.9 tok/s | wall 16.5s +B6-new-p1 long run 2: prompt 7049 tok (7049 read) at 472.6 tok/s | 60 generated at 33.0 tok/s | wall 16.7s +== B6-new-p1 short: prompt median 252 tok/s | decode median 37.9 tok/s | n=3 +== B6-new-p1 long: prompt median 473 tok/s | decode median 34.0 tok/s | n=3 +B6-new: GPU at the end 82 C; clock under load (util >= 90): mean 1527 MHz, min 1506 MHz, 35 samples +off-switches-p1 short run 0: prompt 567 tok (567 read) at 210.4 tok/s | 200 generated at 33.3 tok/s | wall 8.7s +off-switches-p1 short run 1: prompt 565 tok (565 read) at 201.0 tok/s | 200 generated at 34.8 tok/s | wall 8.6s +off-switches-p1 short run 2: prompt 565 tok (565 read) at 213.5 tok/s | 200 generated at 32.0 tok/s | wall 8.9s +off-switches-p1 long run 0: prompt 7048 tok (7048 read) at 359.8 tok/s | 60 generated at 33.4 tok/s | wall 21.4s +off-switches-p1 long run 1: prompt 7047 tok (7047 read) at 430.8 tok/s | 60 generated at 33.5 tok/s | wall 18.2s +off-switches-p1 long run 2: prompt 7048 tok (7048 read) at 364.8 tok/s | 60 generated at 31.0 tok/s | wall 21.3s +== off-switches-p1 short: prompt median 210 tok/s | decode median 33.3 tok/s | n=3 +== off-switches-p1 long: prompt median 365 tok/s | decode median 33.4 tok/s | n=3 +off-switches: GPU at the end 84 C; clock under load (util >= 90): mean 1517 MHz, min 1417 MHz, 41 samples +PR-default-p1 short run 0: prompt 565 tok (565 read) at 223.3 tok/s | 200 generated at 35.0 tok/s | wall 8.3s +PR-default-p1 short run 1: prompt 565 tok (565 read) at 260.8 tok/s | 200 generated at 38.3 tok/s | wall 7.4s +PR-default-p1 short run 2: prompt 563 tok (563 read) at 262.0 tok/s | 200 generated at 38.1 tok/s | wall 7.4s +PR-default-p1 long run 0: prompt 7045 tok (7045 read) at 439.4 tok/s | 60 generated at 36.0 tok/s | wall 17.7s +PR-default-p1 long run 1: prompt 7047 tok (7047 read) at 444.6 tok/s | 60 generated at 34.7 tok/s | wall 17.6s +PR-default-p1 long run 2: prompt 7047 tok (7047 read) at 445.5 tok/s | 60 generated at 37.1 tok/s | wall 17.4s +== PR-default-p1 short: prompt median 261 tok/s | decode median 38.1 tok/s | n=3 +== PR-default-p1 long: prompt median 445 tok/s | decode median 36.0 tok/s | n=3 +PR-default: GPU at the end 75 C; clock under load (util >= 90): mean 1465 MHz, min 1392 MHz, 36 samples +PR-dense-p1 short run 0: prompt 565 tok (565 read) at 264.7 tok/s | 200 generated at 31.2 tok/s | wall 8.6s +PR-dense-p1 short run 1: prompt 567 tok (567 read) at 249.5 tok/s | 200 generated at 37.6 tok/s | wall 7.6s +PR-dense-p1 short run 2: prompt 567 tok (567 read) at 245.9 tok/s | 200 generated at 38.6 tok/s | wall 7.5s +PR-dense-p1 long run 0: prompt 7047 tok (7047 read) at 464.6 tok/s | 60 generated at 34.3 tok/s | wall 16.9s +PR-dense-p1 long run 1: prompt 7047 tok (7047 read) at 471.9 tok/s | 60 generated at 37.5 tok/s | wall 16.5s +PR-dense-p1 long run 2: prompt 7047 tok (7047 read) at 473.0 tok/s | 60 generated at 34.1 tok/s | wall 16.7s +== PR-dense-p1 short: prompt median 250 tok/s | decode median 37.6 tok/s | n=3 +== PR-dense-p1 long: prompt median 472 tok/s | decode median 34.3 tok/s | n=3 +PR-dense: GPU at the end 81 C; clock under load (util >= 90): mean 1528 MHz, min 1506 MHz, 35 samples diff --git a/bench/results/2026-10-12-p40-sm61-kernels/equal_check.py b/bench/results/2026-10-12-p40-sm61-kernels/equal_check.py new file mode 100755 index 00000000..fec1558f --- /dev/null +++ b/bench/results/2026-10-12-p40-sm61-kernels/equal_check.py @@ -0,0 +1,27 @@ +#!/usr/bin/env python3 +"""equal_check.py OUT.json — fixed prompts at temperature 0 straight to the dev engine (BENCH_PORT), the answers saved for a +byte comparison between two engines. Run it first after a fresh start so both engines have the same history.""" +import json, os, random, sys, urllib.request +OUT = sys.argv[1]; PORT = os.environ.get("BENCH_PORT", "8082") +WORDS = ("the engine reads a prompt and writes an answer while the cache keeps the experts that were used most often " + "in the last rounds so a second request with a different first line has to be read again from the start").split() +def text(n, seed): + r = random.Random(seed); return " ".join(r.choice(WORDS) for _ in range(n)) +PROMPTS = [ + ("code", "Write a Python function that merges two sorted lists into one sorted list without using sort(). Then explain its complexity.", 160), + ("prose", "Describe a small harbour town at dawn in plain prose, no lists.", 160), + ("math", "A train leaves at 9:40 and travels 150 km at 75 km/h, waits 25 minutes, then travels 90 km at 60 km/h. When does it arrive? Show the steps.", 160), + ("json", "Return a JSON object with the keys name, year and tags describing the first Moon landing. JSON only.", 100), + ("italian", "Spiega in italiano, in poche frasi, la differenza tra IVA a debito e IVA a credito.", 140), + ("long", "Summarise the following text in three sentences.\n\n" + text(2600, "eq-long"), 120), + ("needle", text(1500, "eq-a") + "\n\nThe access code for the archive room is 7391-KESTREL.\n\n" + text(1500, "eq-b") + "\n\nWhat is the access code for the archive room? Answer with the code only.", 40), +] +res = {} +for name, prompt, mt in PROMPTS: + body = {"model": "qwen3.8-flash-next-iq3_s", "messages": [{"role": "user", "content": prompt}], "max_tokens": mt, "temperature": 0, + "reasoning_effort": "none", "stream": False} + req = urllib.request.Request("http://127.0.0.1:%s/v1/chat/completions" % PORT, json.dumps(body).encode(), {"Content-Type": "application/json"}) + out = json.load(urllib.request.urlopen(req, timeout=1800)) + res[name] = out["choices"][0]["message"].get("content") or "" + print(f"eq {name}: {len(res[name])} chars: {res[name][:70]!r}", flush=True) +json.dump(res, open(OUT, "w"), indent=1, ensure_ascii=False) diff --git a/bench/results/2026-10-12-p40-sm61-kernels/fused-gr-bench.txt b/bench/results/2026-10-12-p40-sm61-kernels/fused-gr-bench.txt new file mode 100644 index 00000000..a9a0130b --- /dev/null +++ b/bench/results/2026-10-12-p40-sm61-kernels/fused-gr-bench.txt @@ -0,0 +1,37 @@ +T 1 apply 0 inject 0 | old 82.0 us fast 88.2 us | bitwise equal | hash 3b6a40f358273fc7 +T 1 apply 0 inject 1 | old 82.4 us fast 87.7 us | bitwise equal | hash d89aaf8f8a29b1ca +T 1 apply 1 inject 0 | old 86.4 us fast 92.7 us | bitwise equal | hash 244ca8d38fc20acb +T 1 apply 1 inject 1 | old 87.0 us fast 93.4 us | bitwise equal | hash 032cee1fb5ebb356 +T 2 apply 0 inject 0 | old 92.4 us fast 102.6 us | bitwise equal | hash c205fed067c34594 +T 2 apply 0 inject 1 | old 93.7 us fast 103.0 us | bitwise equal | hash 2760f7098d2ab3fe +T 2 apply 1 inject 0 | old 98.9 us fast 107.1 us | bitwise equal | hash b9e0ac8e75ac7128 +T 2 apply 1 inject 1 | old 100.3 us fast 106.8 us | bitwise equal | hash 6ef0e08a291dc600 +T 3 apply 0 inject 0 | old 107.7 us fast 117.8 us | bitwise equal | hash 64c37a5c5a4595d5 +T 3 apply 0 inject 1 | old 108.2 us fast 120.3 us | bitwise equal | hash d2559a578d205048 +T 3 apply 1 inject 0 | old 114.7 us fast 123.1 us | bitwise equal | hash 6716ef3bd60accde +T 3 apply 1 inject 1 | old 114.9 us fast 125.1 us | bitwise equal | hash cfc5902711fce549 +T 4 apply 0 inject 0 | old 119.1 us fast 131.3 us | bitwise equal | hash f1a133902db07a6f +T 4 apply 0 inject 1 | old 119.2 us fast 134.0 us | bitwise equal | hash b0b733dab4d44c71 +T 4 apply 1 inject 0 | old 125.7 us fast 136.6 us | bitwise equal | hash a5d36b69ac08ff84 +T 4 apply 1 inject 1 | old 125.8 us fast 138.9 us | bitwise equal | hash 9970362c2541e29a +T 5 apply 0 inject 0 | old 192.2 us fast 180.5 us | bitwise equal | hash a72a0230dc9fe66c +T 5 apply 0 inject 1 | old 190.9 us fast 182.9 us | bitwise equal | hash 20d0c6378bfb1105 +T 5 apply 1 inject 0 | old 192.8 us fast 186.2 us | bitwise equal | hash 12389bbed13d809e +T 5 apply 1 inject 1 | old 192.0 us fast 188.4 us | bitwise equal | hash 20c5ab4e8a222ca7 +T 6 apply 0 inject 0 | old 197.6 us fast 192.7 us | bitwise equal | hash 673139d39fd067f4 +T 6 apply 0 inject 1 | old 203.5 us fast 197.3 us | bitwise equal | hash af84afae3cefb733 +T 6 apply 1 inject 0 | old 207.2 us fast 198.6 us | bitwise equal | hash 98ffa7a944a3546e +T 6 apply 1 inject 1 | old 213.7 us fast 203.3 us | bitwise equal | hash aa3d90cb6f876497 +COLD(48 sets) fast 0 T 1 | read 88.3 us (events) | stamps median: norm 16.4 down 47.1 up 29.7 us (incl. a stamp kernel each) +COLD(48 sets) fast 1 T 1 | read 94.2 us (events) | stamps median: norm 12.3 down 48.9 up 37.5 us (incl. a stamp kernel each) +COLD(48 sets) fast 0 T 2 | read 101.3 us (events) | stamps median: norm 15.8 down 54.3 up 34.8 us (incl. a stamp kernel each) +COLD(48 sets) fast 1 T 2 | read 106.7 us (events) | stamps median: norm 12.3 down 52.3 up 44.0 us (incl. a stamp kernel each) +COLD(48 sets) fast 0 T 3 | read 115.8 us (events) | stamps median: norm 15.8 down 61.4 up 42.0 us (incl. a stamp kernel each) +COLD(48 sets) fast 1 T 3 | read 126.0 us (events) | stamps median: norm 13.3 down 65.5 up 51.2 us (incl. a stamp kernel each) +COLD(48 sets) fast 0 T 4 | read 126.1 us (events) | stamps median: norm 15.8 down 65.5 up 49.2 us (incl. a stamp kernel each) +COLD(48 sets) fast 1 T 4 | read 140.0 us (events) | stamps median: norm 13.3 down 73.7 up 56.3 us (incl. a stamp kernel each) +COLD(48 sets) fast 0 T 5 | read 192.3 us (events) | stamps median: norm 16.4 down 105.5 up 75.8 us (incl. a stamp kernel each) +COLD(48 sets) fast 1 T 5 | read 188.8 us (events) | stamps median: norm 13.3 down 114.7 up 64.5 us (incl. a stamp kernel each) +COLD(48 sets) fast 0 T 6 | read 213.5 us (events) | stamps median: norm 16.4 down 119.8 up 78.8 us (incl. a stamp kernel each) +COLD(48 sets) fast 1 T 6 | read 203.9 us (events) | stamps median: norm 13.3 down 123.9 up 69.6 us (incl. a stamp kernel each) +fused_gr_bench: 0 differing diff --git a/bench/results/2026-10-12-p40-sm61-kernels/gemm-f32-parity.txt b/bench/results/2026-10-12-p40-sm61-kernels/gemm-f32-parity.txt new file mode 100644 index 00000000..2e925633 --- /dev/null +++ b/bench/results/2026-10-12-p40-sm61-kernels/gemm-f32-parity.txt @@ -0,0 +1,28 @@ +gemm_f32_parity: compute capability 6.1 +gdn qkv 10240 x 2560 : 1278 sizes from T 256 to 8192, 0 with different bits (bitwise equal) +BENCH gdn qkv T 560 | cuBLAS FP16 6.48 ms | FP32 copies 4.44 ms (the conversions included) | 1.46x +BENCH gdn qkv T 2048 | cuBLAS FP16 15.43 ms | FP32 copies 14.21 ms (the conversions included) | 1.09x +BENCH gdn qkv T 4096 | cuBLAS FP16 49.01 ms | FP32 copies 25.54 ms (the conversions included) | 1.92x +BENCH gdn qkv T 7040 | cuBLAS FP16 55.75 ms | FP32 copies 46.52 ms (the conversions included) | 1.20x +BENCH gdn qkv T 7041 | cuBLAS FP16 85.38 ms | FP32 copies 44.74 ms (the conversions included) | 1.91x +qsa query 12288 x 2560 : 1278 sizes from T 256 to 8192, 0 with different bits (bitwise equal) +BENCH qsa query T 560 | cuBLAS FP16 8.26 ms | FP32 copies 6.27 ms (the conversions included) | 1.32x +BENCH qsa query T 2048 | cuBLAS FP16 29.38 ms | FP32 copies 19.08 ms (the conversions included) | 1.54x +BENCH qsa query T 4096 | cuBLAS FP16 48.58 ms | FP32 copies 38.18 ms (the conversions included) | 1.27x +BENCH qsa query T 7040 | cuBLAS FP16 79.49 ms | FP32 copies 61.34 ms (the conversions included) | 1.30x +BENCH qsa query T 7041 | cuBLAS FP16 102.37 ms | FP32 copies 64.72 ms (the conversions included) | 1.58x +gdn gate 6144 x 2560 : 1235 sizes from T 512 to 8192, 0 with different bits (bitwise equal) +BENCH gdn gate T 560 | cuBLAS FP16 2.90 ms | FP32 copies 3.05 ms (the conversions included) | 0.95x +BENCH gdn gate T 2048 | cuBLAS FP16 12.10 ms | FP32 copies 8.96 ms (the conversions included) | 1.35x +BENCH gdn gate T 4096 | cuBLAS FP16 26.77 ms | FP32 copies 17.70 ms (the conversions included) | 1.51x +BENCH gdn gate T 7040 | cuBLAS FP16 39.19 ms | FP32 copies 33.55 ms (the conversions included) | 1.17x +BENCH gdn gate T 7041 | cuBLAS FP16 47.23 ms | FP32 copies 33.52 ms (the conversions included) | 1.41x +gdn out 2560 x 6144 : 705 sizes from T 4096 to 8192, 0 with different bits (bitwise equal) +BENCH gdn out T 4096 | cuBLAS FP16 24.59 ms | FP32 copies 18.34 ms (the conversions included) | 1.34x +BENCH gdn out T 7040 | cuBLAS FP16 35.33 ms | FP32 copies 30.60 ms (the conversions included) | 1.15x +BENCH gdn out T 7041 | cuBLAS FP16 48.76 ms | FP32 copies 33.42 ms (the conversions included) | 1.46x +qsa out 2560 x 4096 : 705 sizes from T 4096 to 8192, 0 with different bits (bitwise equal) +BENCH qsa out T 4096 | cuBLAS FP16 12.29 ms | FP32 copies 13.29 ms (the conversions included) | 0.93x +BENCH qsa out T 7040 | cuBLAS FP16 26.60 ms | FP32 copies 22.31 ms (the conversions included) | 1.19x +BENCH qsa out T 7041 | cuBLAS FP16 22.26 ms | FP32 copies 22.36 ms (the conversions included) | 1.00x +gemm_f32_parity: 5201 sizes, OK (bitwise) diff --git a/bench/results/2026-10-12-p40-sm61-kernels/gemm-sweep.txt b/bench/results/2026-10-12-p40-sm61-kernels/gemm-sweep.txt new file mode 100644 index 00000000..4957ba0b --- /dev/null +++ b/bench/results/2026-10-12-p40-sm61-kernels/gemm-sweep.txt @@ -0,0 +1,923 @@ +SWEEP gdn qkv N 10240 K 2560 T 1 | f16 0.209 ms 0.25 TFLOPS | f32 0.353 ms 0.15 TFLOPS | 0.59x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 2 | f16 0.801 ms 0.13 TFLOPS | f32 0.354 ms 0.30 TFLOPS | 2.26x | DIFFERENT + 19441 of 20480 outputs differ +SWEEP gdn qkv N 10240 K 2560 T 3 | f16 0.801 ms 0.20 TFLOPS | f32 0.359 ms 0.44 TFLOPS | 2.23x | DIFFERENT + 29148 of 30720 outputs differ +SWEEP gdn qkv N 10240 K 2560 T 4 | f16 0.806 ms 0.26 TFLOPS | f32 0.359 ms 0.58 TFLOPS | 2.24x | DIFFERENT + 38889 of 40960 outputs differ +SWEEP gdn qkv N 10240 K 2560 T 5 | f16 0.806 ms 0.33 TFLOPS | f32 0.408 ms 0.64 TFLOPS | 1.98x | DIFFERENT + 48823 of 51200 outputs differ +SWEEP gdn qkv N 10240 K 2560 T 6 | f16 0.809 ms 0.39 TFLOPS | f32 0.406 ms 0.77 TFLOPS | 1.99x | DIFFERENT + 58559 of 61440 outputs differ +SWEEP gdn qkv N 10240 K 2560 T 7 | f16 0.807 ms 0.45 TFLOPS | f32 0.409 ms 0.90 TFLOPS | 1.97x | DIFFERENT + 68325 of 71680 outputs differ +SWEEP gdn qkv N 10240 K 2560 T 8 | f16 0.811 ms 0.52 TFLOPS | f32 0.408 ms 1.03 TFLOPS | 1.99x | DIFFERENT + 78113 of 81920 outputs differ +SWEEP gdn qkv N 10240 K 2560 T 9 | f16 0.809 ms 0.58 TFLOPS | f32 0.411 ms 1.15 TFLOPS | 1.97x | DIFFERENT + 87823 of 92160 outputs differ +SWEEP gdn qkv N 10240 K 2560 T 10 | f16 0.812 ms 0.65 TFLOPS | f32 0.412 ms 1.27 TFLOPS | 1.97x | DIFFERENT + 97570 of 102400 outputs differ +SWEEP gdn qkv N 10240 K 2560 T 11 | f16 0.810 ms 0.71 TFLOPS | f32 0.412 ms 1.40 TFLOPS | 1.97x | DIFFERENT + 107330 of 112640 outputs differ +SWEEP gdn qkv N 10240 K 2560 T 12 | f16 0.812 ms 0.77 TFLOPS | f32 0.411 ms 1.53 TFLOPS | 1.98x | DIFFERENT + 117091 of 122880 outputs differ +SWEEP gdn qkv N 10240 K 2560 T 13 | f16 0.815 ms 0.84 TFLOPS | f32 0.414 ms 1.65 TFLOPS | 1.97x | DIFFERENT + 126834 of 133120 outputs differ +SWEEP gdn qkv N 10240 K 2560 T 14 | f16 0.811 ms 0.91 TFLOPS | f32 0.413 ms 1.78 TFLOPS | 1.97x | DIFFERENT + 136599 of 143360 outputs differ +SWEEP gdn qkv N 10240 K 2560 T 15 | f16 0.816 ms 0.96 TFLOPS | f32 0.415 ms 1.90 TFLOPS | 1.97x | DIFFERENT + 146342 of 153600 outputs differ +SWEEP gdn qkv N 10240 K 2560 T 16 | f16 0.818 ms 1.03 TFLOPS | f32 0.413 ms 2.03 TFLOPS | 1.98x | DIFFERENT + 156116 of 163840 outputs differ +SWEEP gdn qkv N 10240 K 2560 T 24 | f16 0.824 ms 1.53 TFLOPS | f32 0.417 ms 3.01 TFLOPS | 1.97x | DIFFERENT + 234191 of 245760 outputs differ +SWEEP gdn qkv N 10240 K 2560 T 48 | f16 0.848 ms 2.97 TFLOPS | f32 0.577 ms 4.36 TFLOPS | 1.47x | DIFFERENT + 468355 of 491520 outputs differ +SWEEP gdn qkv N 10240 K 2560 T 72 | f16 0.979 ms 3.86 TFLOPS | f32 0.749 ms 5.04 TFLOPS | 1.31x | DIFFERENT + 713353 of 737280 outputs differ +SWEEP gdn qkv N 10240 K 2560 T 96 | f16 0.985 ms 5.11 TFLOPS | f32 1.167 ms 4.31 TFLOPS | 0.84x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 120 | f16 0.993 ms 6.33 TFLOPS | f32 1.168 ms 5.38 TFLOPS | 0.85x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 144 | f16 1.650 ms 4.58 TFLOPS | f32 1.591 ms 4.74 TFLOPS | 1.04x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 168 | f16 1.701 ms 5.18 TFLOPS | f32 1.598 ms 5.51 TFLOPS | 1.06x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 192 | f16 1.748 ms 5.76 TFLOPS | f32 1.599 ms 6.29 TFLOPS | 1.09x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 216 | f16 2.471 ms 4.58 TFLOPS | f32 1.599 ms 7.08 TFLOPS | 1.54x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 240 | f16 2.450 ms 5.13 TFLOPS | f32 1.610 ms 7.82 TFLOPS | 1.52x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 264 | f16 3.160 ms 4.38 TFLOPS | f32 2.030 ms 6.82 TFLOPS | 1.56x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 288 | f16 3.349 ms 4.51 TFLOPS | f32 2.005 ms 7.53 TFLOPS | 1.67x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 312 | f16 3.253 ms 5.03 TFLOPS | f32 2.006 ms 8.16 TFLOPS | 1.62x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 336 | f16 2.589 ms 6.81 TFLOPS | f32 2.010 ms 8.76 TFLOPS | 1.29x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 360 | f16 2.604 ms 7.25 TFLOPS | f32 2.015 ms 9.37 TFLOPS | 1.29x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 384 | f16 2.609 ms 7.72 TFLOPS | f32 2.017 ms 9.98 TFLOPS | 1.29x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 408 | f16 4.736 ms 4.52 TFLOPS | f32 3.098 ms 6.90 TFLOPS | 1.53x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 432 | f16 4.748 ms 4.77 TFLOPS | f32 3.113 ms 7.28 TFLOPS | 1.53x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 456 | f16 3.568 ms 6.70 TFLOPS | f32 3.108 ms 7.69 TFLOPS | 1.15x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 480 | f16 3.568 ms 7.05 TFLOPS | f32 3.099 ms 8.12 TFLOPS | 1.15x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 504 | f16 3.555 ms 7.43 TFLOPS | f32 3.077 ms 8.59 TFLOPS | 1.16x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 560 | f16 6.419 ms 4.57 TFLOPS | f32 3.508 ms 8.37 TFLOPS | 1.83x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 813 | f16 9.309 ms 4.58 TFLOPS | f32 4.864 ms 8.76 TFLOPS | 1.91x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 1066 | f16 12.582 ms 4.44 TFLOPS | f32 6.066 ms 9.21 TFLOPS | 2.07x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 1319 | f16 15.526 ms 4.45 TFLOPS | f32 7.433 ms 9.30 TFLOPS | 2.09x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 1572 | f16 18.767 ms 4.39 TFLOPS | f32 8.946 ms 9.21 TFLOPS | 2.10x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 1825 | f16 21.878 ms 4.37 TFLOPS | f32 10.099 ms 9.47 TFLOPS | 2.17x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 2078 | f16 25.000 ms 4.36 TFLOPS | f32 11.779 ms 9.25 TFLOPS | 2.12x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 2331 | f16 27.976 ms 4.37 TFLOPS | f32 13.072 ms 9.35 TFLOPS | 2.14x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 2584 | f16 31.126 ms 4.35 TFLOPS | f32 14.557 ms 9.31 TFLOPS | 2.14x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 2837 | f16 34.188 ms 4.35 TFLOPS | f32 16.194 ms 9.19 TFLOPS | 2.11x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 3090 | f16 37.229 ms 4.35 TFLOPS | f32 17.510 ms 9.25 TFLOPS | 2.13x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 3343 | f16 40.426 ms 4.34 TFLOPS | f32 18.750 ms 9.35 TFLOPS | 2.16x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 3596 | f16 43.510 ms 4.33 TFLOPS | f32 19.900 ms 9.47 TFLOPS | 2.19x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 3849 | f16 46.542 ms 4.34 TFLOPS | f32 21.923 ms 9.20 TFLOPS | 2.12x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 4102 | f16 49.769 ms 4.32 TFLOPS | f32 23.697 ms 9.08 TFLOPS | 2.10x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 4355 | f16 52.902 ms 4.32 TFLOPS | f32 24.159 ms 9.45 TFLOPS | 2.19x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 4608 | f16 32.192 ms 7.50 TFLOPS | f32 26.342 ms 9.17 TFLOPS | 1.22x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 4861 | f16 58.311 ms 4.37 TFLOPS | f32 27.092 ms 9.41 TFLOPS | 2.15x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 5114 | f16 35.660 ms 7.52 TFLOPS | f32 29.580 ms 9.06 TFLOPS | 1.21x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 5367 | f16 37.326 ms 7.54 TFLOPS | f32 30.610 ms 9.19 TFLOPS | 1.22x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 5620 | f16 67.616 ms 4.36 TFLOPS | f32 32.514 ms 9.06 TFLOPS | 2.08x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 5873 | f16 41.055 ms 7.50 TFLOPS | f32 34.574 ms 8.91 TFLOPS | 1.19x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 6126 | f16 42.943 ms 7.48 TFLOPS | f32 35.717 ms 8.99 TFLOPS | 1.20x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 6379 | f16 77.034 ms 4.34 TFLOPS | f32 35.650 ms 9.38 TFLOPS | 2.16x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 6632 | f16 46.361 ms 7.50 TFLOPS | f32 38.757 ms 8.97 TFLOPS | 1.20x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 6885 | f16 47.899 ms 7.54 TFLOPS | f32 40.561 ms 8.90 TFLOPS | 1.18x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 7138 | f16 86.139 ms 4.34 TFLOPS | f32 38.988 ms 9.60 TFLOPS | 2.21x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 7391 | f16 51.377 ms 7.54 TFLOPS | f32 42.681 ms 9.08 TFLOPS | 1.20x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 7644 | f16 53.817 ms 7.45 TFLOPS | f32 44.008 ms 9.11 TFLOPS | 1.22x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 7897 | f16 95.323 ms 4.34 TFLOPS | f32 42.952 ms 9.64 TFLOPS | 2.22x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 8150 | f16 57.011 ms 7.49 TFLOPS | f32 47.212 ms 9.05 TFLOPS | 1.21x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 7030 | f16 49.224 ms 7.49 TFLOPS | f32 40.679 ms 9.06 TFLOPS | 1.21x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 7031 | f16 48.852 ms 7.55 TFLOPS | f32 40.577 ms 9.08 TFLOPS | 1.20x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 7032 | f16 49.059 ms 7.52 TFLOPS | f32 40.921 ms 9.01 TFLOPS | 1.20x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 7033 | f16 49.237 ms 7.49 TFLOPS | f32 41.437 ms 8.90 TFLOPS | 1.19x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 7034 | f16 49.261 ms 7.49 TFLOPS | f32 40.890 ms 9.02 TFLOPS | 1.20x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 7035 | f16 49.157 ms 7.50 TFLOPS | f32 41.090 ms 8.98 TFLOPS | 1.20x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 7036 | f16 49.085 ms 7.52 TFLOPS | f32 40.726 ms 9.06 TFLOPS | 1.21x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 7037 | f16 49.310 ms 7.48 TFLOPS | f32 41.708 ms 8.85 TFLOPS | 1.18x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 7038 | f16 48.699 ms 7.58 TFLOPS | f32 41.955 ms 8.79 TFLOPS | 1.16x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 7039 | f16 48.866 ms 7.55 TFLOPS | f32 41.359 ms 8.92 TFLOPS | 1.18x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 7040 | f16 49.526 ms 7.45 TFLOPS | f32 40.867 ms 9.03 TFLOPS | 1.21x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 7041 | f16 85.275 ms 4.33 TFLOPS | f32 38.479 ms 9.59 TFLOPS | 2.22x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 7042 | f16 85.359 ms 4.33 TFLOPS | f32 41.483 ms 8.90 TFLOPS | 2.06x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 7043 | f16 85.352 ms 4.33 TFLOPS | f32 40.122 ms 9.20 TFLOPS | 2.13x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 7044 | f16 85.364 ms 4.33 TFLOPS | f32 39.345 ms 9.39 TFLOPS | 2.17x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 7045 | f16 85.272 ms 4.33 TFLOPS | f32 38.839 ms 9.51 TFLOPS | 2.20x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 7046 | f16 85.290 ms 4.33 TFLOPS | f32 41.416 ms 8.92 TFLOPS | 2.06x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 7047 | f16 85.354 ms 4.33 TFLOPS | f32 38.478 ms 9.60 TFLOPS | 2.22x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 7048 | f16 85.274 ms 4.33 TFLOPS | f32 38.356 ms 9.63 TFLOPS | 2.22x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 7049 | f16 85.369 ms 4.33 TFLOPS | f32 38.954 ms 9.49 TFLOPS | 2.19x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 7050 | f16 85.317 ms 4.33 TFLOPS | f32 38.858 ms 9.51 TFLOPS | 2.20x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 7051 | f16 85.311 ms 4.33 TFLOPS | f32 38.705 ms 9.55 TFLOPS | 2.20x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 7052 | f16 85.330 ms 4.33 TFLOPS | f32 39.215 ms 9.43 TFLOPS | 2.18x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 7053 | f16 85.274 ms 4.34 TFLOPS | f32 39.633 ms 9.33 TFLOPS | 2.15x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 7054 | f16 85.237 ms 4.34 TFLOPS | f32 39.067 ms 9.47 TFLOPS | 2.18x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 7055 | f16 85.353 ms 4.33 TFLOPS | f32 39.108 ms 9.46 TFLOPS | 2.18x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 7056 | f16 85.305 ms 4.34 TFLOPS | f32 40.664 ms 9.10 TFLOPS | 2.10x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 1024 | f16 11.759 ms 4.57 TFLOPS | f32 5.605 ms 9.58 TFLOPS | 2.10x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 2048 | f16 14.232 ms 7.54 TFLOPS | f32 11.841 ms 9.07 TFLOPS | 1.20x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 4096 | f16 48.902 ms 4.39 TFLOPS | f32 22.556 ms 9.52 TFLOPS | 2.17x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 8192 | f16 57.580 ms 7.46 TFLOPS | f32 48.122 ms 8.93 TFLOPS | 1.20x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 1000 | f16 11.811 ms 4.44 TFLOPS | f32 5.890 ms 8.90 TFLOPS | 2.01x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 3000 | f16 35.762 ms 4.40 TFLOPS | f32 16.589 ms 9.48 TFLOPS | 2.16x | bitwise equal +SWEEP gdn qkv N 10240 K 2560 T 5000 | f16 60.547 ms 4.33 TFLOPS | f32 27.531 ms 9.52 TFLOPS | 2.20x | bitwise equal +SUMMARY gdn qkv : 84 of 102 T values bitwise equal; f16 below 6 TFLOPS at 47 of the T >= 256; total f16 3514 ms, f32 2037 ms +SWEEP gdn gate z N 6144 K 2560 T 1 | f16 0.127 ms 0.25 TFLOPS | f32 0.216 ms 0.15 TFLOPS | 0.59x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 2 | f16 0.468 ms 0.13 TFLOPS | f32 0.217 ms 0.29 TFLOPS | 2.15x | DIFFERENT + 11505 of 12288 outputs differ +SWEEP gdn gate z N 6144 K 2560 T 3 | f16 0.472 ms 0.20 TFLOPS | f32 0.232 ms 0.41 TFLOPS | 2.03x | DIFFERENT + 17299 of 18432 outputs differ +SWEEP gdn gate z N 6144 K 2560 T 4 | f16 0.470 ms 0.27 TFLOPS | f32 0.226 ms 0.56 TFLOPS | 2.08x | DIFFERENT + 23089 of 24576 outputs differ +SWEEP gdn gate z N 6144 K 2560 T 5 | f16 0.472 ms 0.33 TFLOPS | f32 0.281 ms 0.56 TFLOPS | 1.68x | DIFFERENT + 29112 of 30720 outputs differ +SWEEP gdn gate z N 6144 K 2560 T 6 | f16 0.471 ms 0.40 TFLOPS | f32 0.280 ms 0.68 TFLOPS | 1.68x | DIFFERENT + 34930 of 36864 outputs differ +SWEEP gdn gate z N 6144 K 2560 T 7 | f16 0.473 ms 0.47 TFLOPS | f32 0.281 ms 0.78 TFLOPS | 1.68x | DIFFERENT + 40751 of 43008 outputs differ +SWEEP gdn gate z N 6144 K 2560 T 8 | f16 0.475 ms 0.53 TFLOPS | f32 0.283 ms 0.89 TFLOPS | 1.68x | DIFFERENT + 46546 of 49152 outputs differ +SWEEP gdn gate z N 6144 K 2560 T 9 | f16 0.471 ms 0.60 TFLOPS | f32 0.283 ms 1.00 TFLOPS | 1.67x | DIFFERENT + 52336 of 55296 outputs differ +SWEEP gdn gate z N 6144 K 2560 T 10 | f16 0.476 ms 0.66 TFLOPS | f32 0.273 ms 1.15 TFLOPS | 1.74x | DIFFERENT + 58127 of 61440 outputs differ +SWEEP gdn gate z N 6144 K 2560 T 11 | f16 0.474 ms 0.73 TFLOPS | f32 0.283 ms 1.22 TFLOPS | 1.68x | DIFFERENT + 63924 of 67584 outputs differ +SWEEP gdn gate z N 6144 K 2560 T 12 | f16 0.475 ms 0.79 TFLOPS | f32 0.276 ms 1.37 TFLOPS | 1.72x | DIFFERENT + 69744 of 73728 outputs differ +SWEEP gdn gate z N 6144 K 2560 T 13 | f16 0.477 ms 0.86 TFLOPS | f32 0.281 ms 1.46 TFLOPS | 1.70x | DIFFERENT + 75537 of 79872 outputs differ +SWEEP gdn gate z N 6144 K 2560 T 14 | f16 0.476 ms 0.92 TFLOPS | f32 0.278 ms 1.58 TFLOPS | 1.71x | DIFFERENT + 81332 of 86016 outputs differ +SWEEP gdn gate z N 6144 K 2560 T 15 | f16 0.478 ms 0.99 TFLOPS | f32 0.284 ms 1.66 TFLOPS | 1.69x | DIFFERENT + 87148 of 92160 outputs differ +SWEEP gdn gate z N 6144 K 2560 T 16 | f16 0.481 ms 1.05 TFLOPS | f32 0.283 ms 1.78 TFLOPS | 1.70x | DIFFERENT + 92934 of 98304 outputs differ +SWEEP gdn gate z N 6144 K 2560 T 24 | f16 0.488 ms 1.55 TFLOPS | f32 0.287 ms 2.63 TFLOPS | 1.70x | DIFFERENT + 139354 of 147456 outputs differ +SWEEP gdn gate z N 6144 K 2560 T 48 | f16 0.569 ms 2.65 TFLOPS | f32 0.354 ms 4.26 TFLOPS | 1.61x | DIFFERENT + 278655 of 294912 outputs differ +SWEEP gdn gate z N 6144 K 2560 T 72 | f16 0.670 ms 3.38 TFLOPS | f32 1.459 ms 1.55 TFLOPS | 0.46x | DIFFERENT + 420017 of 442368 outputs differ +SWEEP gdn gate z N 6144 K 2560 T 96 | f16 0.676 ms 4.47 TFLOPS | f32 1.452 ms 2.08 TFLOPS | 0.47x | DIFFERENT + 560081 of 589824 outputs differ +SWEEP gdn gate z N 6144 K 2560 T 120 | f16 0.701 ms 5.38 TFLOPS | f32 1.535 ms 2.46 TFLOPS | 0.46x | DIFFERENT + 699975 of 737280 outputs differ +SWEEP gdn gate z N 6144 K 2560 T 144 | f16 0.904 ms 5.01 TFLOPS | f32 1.027 ms 4.41 TFLOPS | 0.88x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 168 | f16 0.903 ms 5.85 TFLOPS | f32 1.019 ms 5.19 TFLOPS | 0.89x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 192 | f16 0.922 ms 6.55 TFLOPS | f32 1.020 ms 5.92 TFLOPS | 0.90x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 216 | f16 1.142 ms 5.95 TFLOPS | f32 1.021 ms 6.66 TFLOPS | 1.12x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 240 | f16 1.158 ms 6.52 TFLOPS | f32 1.019 ms 7.41 TFLOPS | 1.14x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 264 | f16 1.156 ms 7.19 TFLOPS | f32 1.355 ms 6.13 TFLOPS | 0.85x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 288 | f16 1.134 ms 7.99 TFLOPS | f32 1.488 ms 6.09 TFLOPS | 0.76x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 312 | f16 1.154 ms 8.51 TFLOPS | f32 1.496 ms 6.56 TFLOPS | 0.77x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 336 | f16 1.615 ms 6.55 TFLOPS | f32 1.493 ms 7.08 TFLOPS | 1.08x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 360 | f16 1.622 ms 6.98 TFLOPS | f32 1.495 ms 7.58 TFLOPS | 1.08x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 384 | f16 1.620 ms 7.46 TFLOPS | f32 1.369 ms 8.82 TFLOPS | 1.18x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 408 | f16 1.788 ms 7.18 TFLOPS | f32 1.895 ms 6.77 TFLOPS | 0.94x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 432 | f16 1.786 ms 7.61 TFLOPS | f32 1.893 ms 7.18 TFLOPS | 0.94x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 456 | f16 2.243 ms 6.39 TFLOPS | f32 1.894 ms 7.57 TFLOPS | 1.18x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 480 | f16 2.248 ms 6.72 TFLOPS | f32 1.929 ms 7.83 TFLOPS | 1.17x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 504 | f16 2.269 ms 6.99 TFLOPS | f32 1.939 ms 8.17 TFLOPS | 1.17x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 560 | f16 2.421 ms 7.28 TFLOPS | f32 2.030 ms 8.68 TFLOPS | 1.19x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 813 | f16 3.290 ms 7.77 TFLOPS | f32 3.020 ms 8.47 TFLOPS | 1.09x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 1066 | f16 4.787 ms 7.01 TFLOPS | f32 3.993 ms 8.40 TFLOPS | 1.20x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 1319 | f16 6.759 ms 6.14 TFLOPS | f32 4.530 ms 9.16 TFLOPS | 1.49x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 1572 | f16 8.585 ms 5.76 TFLOPS | f32 5.427 ms 9.11 TFLOPS | 1.58x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 1825 | f16 10.684 ms 5.37 TFLOPS | f32 6.015 ms 9.54 TFLOPS | 1.78x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 2078 | f16 12.284 ms 5.32 TFLOPS | f32 7.050 ms 9.27 TFLOPS | 1.74x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 2331 | f16 13.863 ms 5.29 TFLOPS | f32 7.968 ms 9.20 TFLOPS | 1.74x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 2584 | f16 15.839 ms 5.13 TFLOPS | f32 8.648 ms 9.40 TFLOPS | 1.83x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 2837 | f16 17.468 ms 5.11 TFLOPS | f32 9.696 ms 9.20 TFLOPS | 1.80x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 3090 | f16 19.539 ms 4.97 TFLOPS | f32 10.458 ms 9.29 TFLOPS | 1.87x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 3343 | f16 21.398 ms 4.91 TFLOPS | f32 11.179 ms 9.41 TFLOPS | 1.91x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 3596 | f16 23.285 ms 4.86 TFLOPS | f32 12.208 ms 9.27 TFLOPS | 1.91x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 3849 | f16 24.975 ms 4.85 TFLOPS | f32 12.843 ms 9.43 TFLOPS | 1.94x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 4102 | f16 26.638 ms 4.84 TFLOPS | f32 13.631 ms 9.47 TFLOPS | 1.95x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 4355 | f16 29.001 ms 4.72 TFLOPS | f32 14.635 ms 9.36 TFLOPS | 1.98x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 4608 | f16 30.270 ms 4.79 TFLOPS | f32 14.923 ms 9.71 TFLOPS | 2.03x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 4861 | f16 20.340 ms 7.52 TFLOPS | f32 16.945 ms 9.02 TFLOPS | 1.20x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 5114 | f16 21.333 ms 7.54 TFLOPS | f32 17.430 ms 9.23 TFLOPS | 1.22x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 5367 | f16 36.094 ms 4.68 TFLOPS | f32 17.717 ms 9.53 TFLOPS | 2.04x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 5620 | f16 23.568 ms 7.50 TFLOPS | f32 19.618 ms 9.01 TFLOPS | 1.20x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 5873 | f16 39.197 ms 4.71 TFLOPS | f32 19.130 ms 9.66 TFLOPS | 2.05x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 6126 | f16 25.696 ms 7.50 TFLOPS | f32 21.248 ms 9.07 TFLOPS | 1.21x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 6379 | f16 26.952 ms 7.45 TFLOPS | f32 21.928 ms 9.15 TFLOPS | 1.23x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 6632 | f16 45.445 ms 4.59 TFLOPS | f32 22.211 ms 9.39 TFLOPS | 2.05x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 6885 | f16 29.148 ms 7.43 TFLOPS | f32 23.917 ms 9.06 TFLOPS | 1.22x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 7138 | f16 48.927 ms 4.59 TFLOPS | f32 23.386 ms 9.60 TFLOPS | 2.09x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 7391 | f16 31.163 ms 7.46 TFLOPS | f32 25.913 ms 8.97 TFLOPS | 1.20x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 7644 | f16 32.521 ms 7.39 TFLOPS | f32 26.809 ms 8.97 TFLOPS | 1.21x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 7897 | f16 54.826 ms 4.53 TFLOPS | f32 25.800 ms 9.63 TFLOPS | 2.13x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 8150 | f16 34.492 ms 7.43 TFLOPS | f32 28.776 ms 8.91 TFLOPS | 1.20x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 7030 | f16 29.559 ms 7.48 TFLOPS | f32 24.813 ms 8.91 TFLOPS | 1.19x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 7031 | f16 29.608 ms 7.47 TFLOPS | f32 24.933 ms 8.87 TFLOPS | 1.19x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 7032 | f16 29.695 ms 7.45 TFLOPS | f32 24.653 ms 8.97 TFLOPS | 1.20x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 7033 | f16 29.637 ms 7.46 TFLOPS | f32 24.519 ms 9.02 TFLOPS | 1.21x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 7034 | f16 29.617 ms 7.47 TFLOPS | f32 24.590 ms 9.00 TFLOPS | 1.20x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 7035 | f16 29.599 ms 7.48 TFLOPS | f32 24.661 ms 8.97 TFLOPS | 1.20x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 7036 | f16 29.772 ms 7.43 TFLOPS | f32 24.496 ms 9.04 TFLOPS | 1.22x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 7037 | f16 29.577 ms 7.48 TFLOPS | f32 24.373 ms 9.08 TFLOPS | 1.21x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 7038 | f16 29.678 ms 7.46 TFLOPS | f32 24.677 ms 8.97 TFLOPS | 1.20x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 7039 | f16 29.580 ms 7.49 TFLOPS | f32 24.598 ms 9.00 TFLOPS | 1.20x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 7040 | f16 29.336 ms 7.55 TFLOPS | f32 24.580 ms 9.01 TFLOPS | 1.19x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 7041 | f16 47.772 ms 4.64 TFLOPS | f32 23.830 ms 9.29 TFLOPS | 2.00x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 7042 | f16 48.404 ms 4.58 TFLOPS | f32 23.114 ms 9.58 TFLOPS | 2.09x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 7043 | f16 48.344 ms 4.58 TFLOPS | f32 23.252 ms 9.53 TFLOPS | 2.08x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 7044 | f16 47.593 ms 4.66 TFLOPS | f32 23.245 ms 9.53 TFLOPS | 2.05x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 7045 | f16 48.683 ms 4.55 TFLOPS | f32 23.072 ms 9.61 TFLOPS | 2.11x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 7046 | f16 48.025 ms 4.62 TFLOPS | f32 23.043 ms 9.62 TFLOPS | 2.08x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 7047 | f16 47.845 ms 4.63 TFLOPS | f32 23.237 ms 9.54 TFLOPS | 2.06x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 7048 | f16 48.769 ms 4.55 TFLOPS | f32 24.179 ms 9.17 TFLOPS | 2.02x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 7049 | f16 48.384 ms 4.58 TFLOPS | f32 23.429 ms 9.46 TFLOPS | 2.07x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 7050 | f16 48.373 ms 4.58 TFLOPS | f32 23.260 ms 9.53 TFLOPS | 2.08x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 7051 | f16 47.833 ms 4.64 TFLOPS | f32 23.142 ms 9.58 TFLOPS | 2.07x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 7052 | f16 47.778 ms 4.64 TFLOPS | f32 23.510 ms 9.44 TFLOPS | 2.03x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 7053 | f16 48.603 ms 4.56 TFLOPS | f32 23.573 ms 9.41 TFLOPS | 2.06x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 7054 | f16 48.781 ms 4.55 TFLOPS | f32 23.892 ms 9.29 TFLOPS | 2.04x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 7055 | f16 47.913 ms 4.63 TFLOPS | f32 23.586 ms 9.41 TFLOPS | 2.03x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 7056 | f16 48.427 ms 4.58 TFLOPS | f32 23.382 ms 9.49 TFLOPS | 2.07x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 1024 | f16 4.221 ms 7.63 TFLOPS | f32 3.611 ms 8.92 TFLOPS | 1.17x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 2048 | f16 12.361 ms 5.21 TFLOPS | f32 6.837 ms 9.42 TFLOPS | 1.81x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 4096 | f16 26.501 ms 4.86 TFLOPS | f32 13.621 ms 9.46 TFLOPS | 1.95x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 8192 | f16 34.441 ms 7.48 TFLOPS | f32 28.453 ms 9.06 TFLOPS | 1.21x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 1000 | f16 4.386 ms 7.17 TFLOPS | f32 3.812 ms 8.25 TFLOPS | 1.15x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 3000 | f16 17.455 ms 5.41 TFLOPS | f32 10.764 ms 8.77 TFLOPS | 1.62x | bitwise equal +SWEEP gdn gate z N 6144 K 2560 T 5000 | f16 33.920 ms 4.64 TFLOPS | f32 16.712 ms 9.41 TFLOPS | 2.03x | bitwise equal +SUMMARY gdn gate z : 82 of 102 T values bitwise equal; f16 below 6 TFLOPS at 38 of the T >= 256; total f16 2005 ms, f32 1221 ms +SWEEP qsa q N 12288 K 2560 T 1 | f16 0.231 ms 0.27 TFLOPS | f32 0.421 ms 0.15 TFLOPS | 0.55x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 2 | f16 0.895 ms 0.14 TFLOPS | f32 0.425 ms 0.30 TFLOPS | 2.11x | DIFFERENT + 23327 of 24576 outputs differ +SWEEP qsa q N 12288 K 2560 T 3 | f16 0.888 ms 0.21 TFLOPS | f32 0.428 ms 0.44 TFLOPS | 2.07x | DIFFERENT + 34986 of 36864 outputs differ +SWEEP qsa q N 12288 K 2560 T 4 | f16 0.899 ms 0.28 TFLOPS | f32 0.430 ms 0.59 TFLOPS | 2.09x | DIFFERENT + 46665 of 49152 outputs differ +SWEEP qsa q N 12288 K 2560 T 5 | f16 0.891 ms 0.35 TFLOPS | f32 0.497 ms 0.63 TFLOPS | 1.79x | DIFFERENT + 58589 of 61440 outputs differ +SWEEP qsa q N 12288 K 2560 T 6 | f16 0.894 ms 0.42 TFLOPS | f32 0.498 ms 0.76 TFLOPS | 1.80x | DIFFERENT + 70266 of 73728 outputs differ +SWEEP qsa q N 12288 K 2560 T 7 | f16 0.901 ms 0.49 TFLOPS | f32 0.501 ms 0.88 TFLOPS | 1.80x | DIFFERENT + 81983 of 86016 outputs differ +SWEEP qsa q N 12288 K 2560 T 8 | f16 0.893 ms 0.56 TFLOPS | f32 0.499 ms 1.01 TFLOPS | 1.79x | DIFFERENT + 93731 of 98304 outputs differ +SWEEP qsa q N 12288 K 2560 T 9 | f16 0.897 ms 0.63 TFLOPS | f32 0.502 ms 1.13 TFLOPS | 1.79x | DIFFERENT + 105400 of 110592 outputs differ +SWEEP qsa q N 12288 K 2560 T 10 | f16 0.910 ms 0.69 TFLOPS | f32 0.503 ms 1.25 TFLOPS | 1.81x | DIFFERENT + 117094 of 122880 outputs differ +SWEEP qsa q N 12288 K 2560 T 11 | f16 0.903 ms 0.77 TFLOPS | f32 0.505 ms 1.37 TFLOPS | 1.79x | DIFFERENT + 128787 of 135168 outputs differ +SWEEP qsa q N 12288 K 2560 T 12 | f16 0.913 ms 0.83 TFLOPS | f32 0.505 ms 1.50 TFLOPS | 1.81x | DIFFERENT + 140507 of 147456 outputs differ +SWEEP qsa q N 12288 K 2560 T 13 | f16 0.905 ms 0.90 TFLOPS | f32 0.504 ms 1.62 TFLOPS | 1.80x | DIFFERENT + 152206 of 159744 outputs differ +SWEEP qsa q N 12288 K 2560 T 14 | f16 0.911 ms 0.97 TFLOPS | f32 0.505 ms 1.74 TFLOPS | 1.81x | DIFFERENT + 163944 of 172032 outputs differ +SWEEP qsa q N 12288 K 2560 T 15 | f16 0.911 ms 1.04 TFLOPS | f32 0.507 ms 1.86 TFLOPS | 1.80x | DIFFERENT + 175646 of 184320 outputs differ +SWEEP qsa q N 12288 K 2560 T 16 | f16 0.907 ms 1.11 TFLOPS | f32 0.507 ms 1.99 TFLOPS | 1.79x | DIFFERENT + 187364 of 196608 outputs differ +SWEEP qsa q N 12288 K 2560 T 24 | f16 0.920 ms 1.64 TFLOPS | f32 0.508 ms 2.97 TFLOPS | 1.81x | DIFFERENT + 281071 of 294912 outputs differ +SWEEP qsa q N 12288 K 2560 T 48 | f16 0.957 ms 3.15 TFLOPS | f32 0.645 ms 4.68 TFLOPS | 1.48x | DIFFERENT + 562108 of 589824 outputs differ +SWEEP qsa q N 12288 K 2560 T 72 | f16 1.598 ms 2.83 TFLOPS | f32 0.855 ms 5.30 TFLOPS | 1.87x | DIFFERENT + 855977 of 884736 outputs differ +SWEEP qsa q N 12288 K 2560 T 96 | f16 1.606 ms 3.76 TFLOPS | f32 1.154 ms 5.23 TFLOPS | 1.39x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 120 | f16 1.641 ms 4.60 TFLOPS | f32 1.165 ms 6.48 TFLOPS | 1.41x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 144 | f16 2.493 ms 3.63 TFLOPS | f32 1.870 ms 4.85 TFLOPS | 1.33x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 168 | f16 2.525 ms 4.19 TFLOPS | f32 1.880 ms 5.62 TFLOPS | 1.34x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 192 | f16 2.568 ms 4.70 TFLOPS | f32 2.006 ms 6.02 TFLOPS | 1.28x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 216 | f16 2.234 ms 6.08 TFLOPS | f32 1.894 ms 7.17 TFLOPS | 1.18x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 240 | f16 2.239 ms 6.74 TFLOPS | f32 1.893 ms 7.97 TFLOPS | 1.18x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 264 | f16 4.351 ms 3.82 TFLOPS | f32 2.486 ms 6.68 TFLOPS | 1.75x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 288 | f16 4.344 ms 4.17 TFLOPS | f32 2.493 ms 7.27 TFLOPS | 1.74x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 312 | f16 4.376 ms 4.49 TFLOPS | f32 2.495 ms 7.87 TFLOPS | 1.75x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 336 | f16 5.254 ms 4.02 TFLOPS | f32 2.496 ms 8.47 TFLOPS | 2.10x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 360 | f16 5.273 ms 4.30 TFLOPS | f32 2.500 ms 9.06 TFLOPS | 2.11x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 384 | f16 5.265 ms 4.59 TFLOPS | f32 2.506 ms 9.64 TFLOPS | 2.10x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 408 | f16 6.203 ms 4.14 TFLOPS | f32 3.546 ms 7.24 TFLOPS | 1.75x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 432 | f16 6.227 ms 4.36 TFLOPS | f32 3.546 ms 7.66 TFLOPS | 1.76x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 456 | f16 4.168 ms 6.88 TFLOPS | f32 3.548 ms 8.09 TFLOPS | 1.17x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 480 | f16 4.243 ms 7.12 TFLOPS | f32 3.630 ms 8.32 TFLOPS | 1.17x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 504 | f16 4.306 ms 7.36 TFLOPS | f32 3.717 ms 8.53 TFLOPS | 1.16x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 560 | f16 8.105 ms 4.35 TFLOPS | f32 4.162 ms 8.46 TFLOPS | 1.95x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 813 | f16 11.839 ms 4.32 TFLOPS | f32 5.954 ms 8.59 TFLOPS | 1.99x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 1066 | f16 15.540 ms 4.32 TFLOPS | f32 7.448 ms 9.00 TFLOPS | 2.09x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 1319 | f16 19.195 ms 4.32 TFLOPS | f32 9.004 ms 9.22 TFLOPS | 2.13x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 1572 | f16 22.952 ms 4.31 TFLOPS | f32 10.715 ms 9.23 TFLOPS | 2.14x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 1825 | f16 26.671 ms 4.30 TFLOPS | f32 12.299 ms 9.34 TFLOPS | 2.17x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 2078 | f16 30.319 ms 4.31 TFLOPS | f32 14.193 ms 9.21 TFLOPS | 2.14x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 2331 | f16 34.130 ms 4.30 TFLOPS | f32 16.269 ms 9.01 TFLOPS | 2.10x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 2584 | f16 37.851 ms 4.30 TFLOPS | f32 17.218 ms 9.44 TFLOPS | 2.20x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 2837 | f16 41.534 ms 4.30 TFLOPS | f32 19.594 ms 9.11 TFLOPS | 2.12x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 3090 | f16 45.244 ms 4.30 TFLOPS | f32 21.199 ms 9.17 TFLOPS | 2.13x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 3343 | f16 48.907 ms 4.30 TFLOPS | f32 22.612 ms 9.30 TFLOPS | 2.16x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 3596 | f16 52.671 ms 4.30 TFLOPS | f32 24.905 ms 9.08 TFLOPS | 2.11x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 3849 | f16 56.385 ms 4.29 TFLOPS | f32 27.053 ms 8.95 TFLOPS | 2.08x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 4102 | f16 60.076 ms 4.30 TFLOPS | f32 27.552 ms 9.37 TFLOPS | 2.18x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 4355 | f16 63.858 ms 4.29 TFLOPS | f32 29.210 ms 9.38 TFLOPS | 2.19x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 4608 | f16 66.660 ms 4.35 TFLOPS | f32 30.324 ms 9.56 TFLOPS | 2.20x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 4861 | f16 70.430 ms 4.34 TFLOPS | f32 31.215 ms 9.80 TFLOPS | 2.26x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 5114 | f16 43.612 ms 7.38 TFLOPS | f32 36.364 ms 8.85 TFLOPS | 1.20x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 5367 | f16 45.582 ms 7.41 TFLOPS | f32 38.119 ms 8.86 TFLOPS | 1.20x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 5620 | f16 47.891 ms 7.38 TFLOPS | f32 40.712 ms 8.68 TFLOPS | 1.18x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 5873 | f16 85.218 ms 4.34 TFLOPS | f32 38.242 ms 9.66 TFLOPS | 2.23x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 6126 | f16 89.061 ms 4.33 TFLOPS | f32 43.400 ms 8.88 TFLOPS | 2.05x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 6379 | f16 54.101 ms 7.42 TFLOPS | f32 45.317 ms 8.86 TFLOPS | 1.19x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 6632 | f16 56.306 ms 7.41 TFLOPS | f32 47.576 ms 8.77 TFLOPS | 1.18x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 6885 | f16 58.460 ms 7.41 TFLOPS | f32 48.579 ms 8.92 TFLOPS | 1.20x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 7138 | f16 103.832 ms 4.33 TFLOPS | f32 47.606 ms 9.43 TFLOPS | 2.18x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 7391 | f16 107.581 ms 4.32 TFLOPS | f32 50.603 ms 9.19 TFLOPS | 2.13x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 7644 | f16 64.961 ms 7.40 TFLOPS | f32 54.347 ms 8.85 TFLOPS | 1.20x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 7897 | f16 67.523 ms 7.36 TFLOPS | f32 56.408 ms 8.81 TFLOPS | 1.20x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 8150 | f16 68.677 ms 7.47 TFLOPS | f32 59.803 ms 8.57 TFLOPS | 1.15x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 7030 | f16 59.469 ms 7.44 TFLOPS | f32 49.591 ms 8.92 TFLOPS | 1.20x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 7031 | f16 59.758 ms 7.40 TFLOPS | f32 50.225 ms 8.81 TFLOPS | 1.19x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 7032 | f16 59.675 ms 7.41 TFLOPS | f32 49.957 ms 8.86 TFLOPS | 1.19x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 7033 | f16 59.649 ms 7.42 TFLOPS | f32 50.305 ms 8.80 TFLOPS | 1.19x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 7034 | f16 59.689 ms 7.41 TFLOPS | f32 49.204 ms 8.99 TFLOPS | 1.21x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 7035 | f16 59.647 ms 7.42 TFLOPS | f32 50.858 ms 8.70 TFLOPS | 1.17x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 7036 | f16 59.565 ms 7.43 TFLOPS | f32 50.340 ms 8.79 TFLOPS | 1.18x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 7037 | f16 59.186 ms 7.48 TFLOPS | f32 50.705 ms 8.73 TFLOPS | 1.17x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 7038 | f16 59.678 ms 7.42 TFLOPS | f32 49.815 ms 8.89 TFLOPS | 1.20x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 7039 | f16 59.658 ms 7.42 TFLOPS | f32 49.638 ms 8.92 TFLOPS | 1.20x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 7040 | f16 59.692 ms 7.42 TFLOPS | f32 49.935 ms 8.87 TFLOPS | 1.20x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 7041 | f16 102.860 ms 4.31 TFLOPS | f32 48.731 ms 9.09 TFLOPS | 2.11x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 7042 | f16 102.935 ms 4.30 TFLOPS | f32 49.690 ms 8.92 TFLOPS | 2.07x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 7043 | f16 102.900 ms 4.31 TFLOPS | f32 48.379 ms 9.16 TFLOPS | 2.13x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 7044 | f16 102.850 ms 4.31 TFLOPS | f32 50.537 ms 8.77 TFLOPS | 2.04x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 7045 | f16 102.848 ms 4.31 TFLOPS | f32 47.425 ms 9.35 TFLOPS | 2.17x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 7046 | f16 102.791 ms 4.31 TFLOPS | f32 47.316 ms 9.37 TFLOPS | 2.17x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 7047 | f16 102.816 ms 4.31 TFLOPS | f32 47.852 ms 9.27 TFLOPS | 2.15x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 7048 | f16 102.785 ms 4.31 TFLOPS | f32 47.336 ms 9.37 TFLOPS | 2.17x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 7049 | f16 102.857 ms 4.31 TFLOPS | f32 47.433 ms 9.35 TFLOPS | 2.17x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 7050 | f16 102.920 ms 4.31 TFLOPS | f32 46.811 ms 9.48 TFLOPS | 2.20x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 7051 | f16 102.764 ms 4.32 TFLOPS | f32 47.087 ms 9.42 TFLOPS | 2.18x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 7052 | f16 102.897 ms 4.31 TFLOPS | f32 49.484 ms 8.97 TFLOPS | 2.08x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 7053 | f16 102.807 ms 4.32 TFLOPS | f32 50.444 ms 8.80 TFLOPS | 2.04x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 7054 | f16 102.871 ms 4.31 TFLOPS | f32 50.258 ms 8.83 TFLOPS | 2.05x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 7055 | f16 102.851 ms 4.32 TFLOPS | f32 48.771 ms 9.10 TFLOPS | 2.11x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 7056 | f16 102.857 ms 4.32 TFLOPS | f32 47.643 ms 9.32 TFLOPS | 2.16x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 1024 | f16 14.599 ms 4.41 TFLOPS | f32 6.719 ms 9.59 TFLOPS | 2.17x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 2048 | f16 29.473 ms 4.37 TFLOPS | f32 13.282 ms 9.70 TFLOPS | 2.22x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 4096 | f16 34.717 ms 7.42 TFLOPS | f32 28.596 ms 9.01 TFLOPS | 1.21x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 8192 | f16 69.171 ms 7.45 TFLOPS | f32 61.231 ms 8.42 TFLOPS | 1.13x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 1000 | f16 14.614 ms 4.30 TFLOPS | f32 6.873 ms 9.15 TFLOPS | 2.13x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 3000 | f16 43.462 ms 4.34 TFLOPS | f32 20.385 ms 9.26 TFLOPS | 2.13x | bitwise equal +SWEEP qsa q N 12288 K 2560 T 5000 | f16 73.131 ms 4.30 TFLOPS | f32 33.639 ms 9.35 TFLOPS | 2.17x | bitwise equal +SUMMARY qsa q : 84 of 102 T values bitwise equal; f16 below 6 TFLOPS at 51 of the T >= 256; total f16 4272 ms, f32 2489 ms +SWEEP gdn out N 2560 K 6144 T 1 | f16 0.132 ms 0.24 TFLOPS | f32 0.240 ms 0.13 TFLOPS | 0.55x | bitwise equal +SWEEP gdn out N 2560 K 6144 T 2 | f16 0.423 ms 0.15 TFLOPS | f32 0.244 ms 0.26 TFLOPS | 1.74x | DIFFERENT + 4858 of 5120 outputs differ +SWEEP gdn out N 2560 K 6144 T 3 | f16 0.425 ms 0.22 TFLOPS | f32 0.245 ms 0.39 TFLOPS | 1.73x | DIFFERENT + 7276 of 7680 outputs differ +SWEEP gdn out N 2560 K 6144 T 4 | f16 0.424 ms 0.30 TFLOPS | f32 0.244 ms 0.52 TFLOPS | 1.74x | DIFFERENT + 9688 of 10240 outputs differ +SWEEP gdn out N 2560 K 6144 T 5 | f16 0.427 ms 0.37 TFLOPS | f32 0.260 ms 0.60 TFLOPS | 1.64x | DIFFERENT + 12263 of 12800 outputs differ +SWEEP gdn out N 2560 K 6144 T 6 | f16 0.429 ms 0.44 TFLOPS | f32 0.261 ms 0.72 TFLOPS | 1.64x | DIFFERENT + 14707 of 15360 outputs differ +SWEEP gdn out N 2560 K 6144 T 7 | f16 0.423 ms 0.52 TFLOPS | f32 0.260 ms 0.85 TFLOPS | 1.63x | DIFFERENT + 17142 of 17920 outputs differ +SWEEP gdn out N 2560 K 6144 T 8 | f16 0.426 ms 0.59 TFLOPS | f32 0.261 ms 0.96 TFLOPS | 1.63x | DIFFERENT + 19605 of 20480 outputs differ +SWEEP gdn out N 2560 K 6144 T 9 | f16 0.430 ms 0.66 TFLOPS | f32 0.262 ms 1.08 TFLOPS | 1.64x | DIFFERENT + 22060 of 23040 outputs differ +SWEEP gdn out N 2560 K 6144 T 10 | f16 0.423 ms 0.74 TFLOPS | f32 0.260 ms 1.21 TFLOPS | 1.62x | DIFFERENT + 24512 of 25600 outputs differ +SWEEP gdn out N 2560 K 6144 T 11 | f16 0.431 ms 0.80 TFLOPS | f32 0.260 ms 1.33 TFLOPS | 1.66x | DIFFERENT + 26960 of 28160 outputs differ +SWEEP gdn out N 2560 K 6144 T 12 | f16 0.433 ms 0.87 TFLOPS | f32 0.262 ms 1.44 TFLOPS | 1.65x | DIFFERENT + 29409 of 30720 outputs differ +SWEEP gdn out N 2560 K 6144 T 13 | f16 0.434 ms 0.94 TFLOPS | f32 0.263 ms 1.56 TFLOPS | 1.65x | DIFFERENT + 31860 of 33280 outputs differ +SWEEP gdn out N 2560 K 6144 T 14 | f16 0.430 ms 1.02 TFLOPS | f32 0.263 ms 1.67 TFLOPS | 1.63x | DIFFERENT + 34306 of 35840 outputs differ +SWEEP gdn out N 2560 K 6144 T 15 | f16 0.431 ms 1.10 TFLOPS | f32 0.263 ms 1.79 TFLOPS | 1.64x | DIFFERENT + 36775 of 38400 outputs differ +SWEEP gdn out N 2560 K 6144 T 16 | f16 0.437 ms 1.15 TFLOPS | f32 0.266 ms 1.89 TFLOPS | 1.64x | DIFFERENT + 39226 of 40960 outputs differ +SWEEP gdn out N 2560 K 6144 T 24 | f16 0.440 ms 1.71 TFLOPS | f32 0.264 ms 2.86 TFLOPS | 1.67x | DIFFERENT + 58815 of 61440 outputs differ +SWEEP gdn out N 2560 K 6144 T 48 | f16 0.494 ms 3.06 TFLOPS | f32 0.342 ms 4.41 TFLOPS | 1.44x | DIFFERENT + 117618 of 122880 outputs differ +SWEEP gdn out N 2560 K 6144 T 72 | f16 0.756 ms 3.00 TFLOPS | f32 1.017 ms 2.23 TFLOPS | 0.74x | DIFFERENT + 178529 of 184320 outputs differ +SWEEP gdn out N 2560 K 6144 T 96 | f16 0.764 ms 3.96 TFLOPS | f32 1.053 ms 2.87 TFLOPS | 0.73x | DIFFERENT + 238062 of 245760 outputs differ +SWEEP gdn out N 2560 K 6144 T 120 | f16 0.769 ms 4.91 TFLOPS | f32 1.091 ms 3.46 TFLOPS | 0.70x | DIFFERENT + 297560 of 307200 outputs differ +SWEEP gdn out N 2560 K 6144 T 144 | f16 0.672 ms 6.74 TFLOPS | f32 1.534 ms 2.95 TFLOPS | 0.44x | DIFFERENT + 357032 of 368640 outputs differ +SWEEP gdn out N 2560 K 6144 T 168 | f16 0.666 ms 7.93 TFLOPS | f32 1.488 ms 3.55 TFLOPS | 0.45x | DIFFERENT + 416540 of 430080 outputs differ +SWEEP gdn out N 2560 K 6144 T 192 | f16 0.681 ms 8.87 TFLOPS | f32 1.525 ms 3.96 TFLOPS | 0.45x | DIFFERENT + 476101 of 491520 outputs differ +SWEEP gdn out N 2560 K 6144 T 216 | f16 1.140 ms 5.96 TFLOPS | f32 1.538 ms 4.42 TFLOPS | 0.74x | DIFFERENT + 535739 of 552960 outputs differ +SWEEP gdn out N 2560 K 6144 T 240 | f16 1.125 ms 6.71 TFLOPS | f32 1.549 ms 4.87 TFLOPS | 0.73x | DIFFERENT + 595208 of 614400 outputs differ +SWEEP gdn out N 2560 K 6144 T 264 | f16 1.253 ms 6.63 TFLOPS | f32 1.407 ms 5.90 TFLOPS | 0.89x | DIFFERENT + 654681 of 675840 outputs differ +SWEEP gdn out N 2560 K 6144 T 288 | f16 1.280 ms 7.08 TFLOPS | f32 1.430 ms 6.33 TFLOPS | 0.89x | DIFFERENT + 714176 of 737280 outputs differ +SWEEP gdn out N 2560 K 6144 T 312 | f16 1.274 ms 7.71 TFLOPS | f32 1.458 ms 6.73 TFLOPS | 0.87x | DIFFERENT + 773722 of 798720 outputs differ +SWEEP gdn out N 2560 K 6144 T 336 | f16 1.464 ms 7.22 TFLOPS | f32 1.477 ms 7.16 TFLOPS | 0.99x | DIFFERENT + 841382 of 860160 outputs differ +SWEEP gdn out N 2560 K 6144 T 360 | f16 1.462 ms 7.74 TFLOPS | f32 1.506 ms 7.52 TFLOPS | 0.97x | DIFFERENT + 901458 of 921600 outputs differ +SWEEP gdn out N 2560 K 6144 T 384 | f16 1.496 ms 8.07 TFLOPS | f32 1.541 ms 7.84 TFLOPS | 0.97x | DIFFERENT + 961528 of 983040 outputs differ +SWEEP gdn out N 2560 K 6144 T 408 | f16 1.996 ms 6.43 TFLOPS | f32 2.109 ms 6.08 TFLOPS | 0.95x | bitwise equal +SWEEP gdn out N 2560 K 6144 T 432 | f16 2.023 ms 6.72 TFLOPS | f32 2.115 ms 6.43 TFLOPS | 0.96x | bitwise equal +SWEEP gdn out N 2560 K 6144 T 456 | f16 2.237 ms 6.41 TFLOPS | f32 2.114 ms 6.79 TFLOPS | 1.06x | bitwise equal +SWEEP gdn out N 2560 K 6144 T 480 | f16 2.234 ms 6.76 TFLOPS | f32 2.118 ms 7.13 TFLOPS | 1.05x | bitwise equal +SWEEP gdn out N 2560 K 6144 T 504 | f16 2.245 ms 7.06 TFLOPS | f32 2.123 ms 7.47 TFLOPS | 1.06x | bitwise equal +SWEEP gdn out N 2560 K 6144 T 560 | f16 2.467 ms 7.14 TFLOPS | f32 2.450 ms 7.19 TFLOPS | 1.01x | bitwise equal +SWEEP gdn out N 2560 K 6144 T 813 | f16 3.156 ms 8.10 TFLOPS | f32 3.302 ms 7.75 TFLOPS | 0.96x | bitwise equal +SWEEP gdn out N 2560 K 6144 T 1066 | f16 3.670 ms 9.14 TFLOPS | f32 3.611 ms 9.29 TFLOPS | 1.02x | bitwise equal +SWEEP gdn out N 2560 K 6144 T 1319 | f16 4.955 ms 8.37 TFLOPS | f32 4.927 ms 8.42 TFLOPS | 1.01x | bitwise equal +SWEEP gdn out N 2560 K 6144 T 1572 | f16 5.688 ms 8.69 TFLOPS | f32 6.180 ms 8.00 TFLOPS | 0.92x | bitwise equal +SWEEP gdn out N 2560 K 6144 T 1825 | f16 6.382 ms 9.00 TFLOPS | f32 6.254 ms 9.18 TFLOPS | 1.02x | bitwise equal +SWEEP gdn out N 2560 K 6144 T 2078 | f16 7.592 ms 8.61 TFLOPS | f32 7.501 ms 8.71 TFLOPS | 1.01x | bitwise equal +SWEEP gdn out N 2560 K 6144 T 2331 | f16 8.440 ms 8.69 TFLOPS | f32 8.876 ms 8.26 TFLOPS | 0.95x | bitwise equal +SWEEP gdn out N 2560 K 6144 T 2584 | f16 8.910 ms 9.12 TFLOPS | f32 9.283 ms 8.76 TFLOPS | 0.96x | bitwise equal +SWEEP gdn out N 2560 K 6144 T 2837 | f16 11.476 ms 7.78 TFLOPS | f32 10.430 ms 8.56 TFLOPS | 1.10x | bitwise equal +SWEEP gdn out N 2560 K 6144 T 3090 | f16 12.175 ms 7.98 TFLOPS | f32 11.609 ms 8.37 TFLOPS | 1.05x | bitwise equal +SWEEP gdn out N 2560 K 6144 T 3343 | f16 14.133 ms 7.44 TFLOPS | f32 11.618 ms 9.05 TFLOPS | 1.22x | bitwise equal +SWEEP gdn out N 2560 K 6144 T 3596 | f16 14.027 ms 8.06 TFLOPS | f32 12.800 ms 8.84 TFLOPS | 1.10x | bitwise equal +SWEEP gdn out N 2560 K 6144 T 3849 | f16 17.151 ms 7.06 TFLOPS | f32 14.220 ms 8.51 TFLOPS | 1.21x | bitwise equal +SWEEP gdn out N 2560 K 6144 T 4102 | f16 17.164 ms 7.52 TFLOPS | f32 14.794 ms 8.72 TFLOPS | 1.16x | bitwise equal +SWEEP gdn out N 2560 K 6144 T 4355 | f16 22.184 ms 6.18 TFLOPS | f32 15.327 ms 8.94 TFLOPS | 1.45x | bitwise equal +SWEEP gdn out N 2560 K 6144 T 4608 | f16 18.064 ms 8.02 TFLOPS | f32 15.977 ms 9.07 TFLOPS | 1.13x | bitwise equal +SWEEP gdn out N 2560 K 6144 T 4861 | f16 26.058 ms 5.87 TFLOPS | f32 17.343 ms 8.82 TFLOPS | 1.50x | bitwise equal +SWEEP gdn out N 2560 K 6144 T 5114 | f16 20.382 ms 7.89 TFLOPS | f32 18.723 ms 8.59 TFLOPS | 1.09x | bitwise equal +SWEEP gdn out N 2560 K 6144 T 5367 | f16 21.436 ms 7.88 TFLOPS | f32 18.907 ms 8.93 TFLOPS | 1.13x | bitwise equal +SWEEP gdn out N 2560 K 6144 T 5620 | f16 34.136 ms 5.18 TFLOPS | f32 19.367 ms 9.13 TFLOPS | 1.76x | bitwise equal +SWEEP gdn out N 2560 K 6144 T 5873 | f16 23.856 ms 7.74 TFLOPS | f32 21.787 ms 8.48 TFLOPS | 1.09x | bitwise equal +SWEEP gdn out N 2560 K 6144 T 6126 | f16 24.751 ms 7.79 TFLOPS | f32 21.973 ms 8.77 TFLOPS | 1.13x | bitwise equal +SWEEP gdn out N 2560 K 6144 T 6379 | f16 36.689 ms 5.47 TFLOPS | f32 22.604 ms 8.88 TFLOPS | 1.62x | bitwise equal +SWEEP gdn out N 2560 K 6144 T 6632 | f16 27.043 ms 7.71 TFLOPS | f32 25.141 ms 8.30 TFLOPS | 1.08x | bitwise equal +SWEEP gdn out N 2560 K 6144 T 6885 | f16 28.238 ms 7.67 TFLOPS | f32 25.631 ms 8.45 TFLOPS | 1.10x | bitwise equal +SWEEP gdn out N 2560 K 6144 T 7138 | f16 48.719 ms 4.61 TFLOPS | f32 26.032 ms 8.63 TFLOPS | 1.87x | bitwise equal +SWEEP gdn out N 2560 K 6144 T 7391 | f16 30.148 ms 7.71 TFLOPS | f32 27.407 ms 8.48 TFLOPS | 1.10x | bitwise equal +SWEEP gdn out N 2560 K 6144 T 7644 | f16 31.076 ms 7.74 TFLOPS | f32 28.435 ms 8.46 TFLOPS | 1.09x | bitwise equal +SWEEP gdn out N 2560 K 6144 T 7897 | f16 55.494 ms 4.48 TFLOPS | f32 28.076 ms 8.85 TFLOPS | 1.98x | bitwise equal +SWEEP gdn out N 2560 K 6144 T 8150 | f16 34.057 ms 7.53 TFLOPS | f32 29.751 ms 8.62 TFLOPS | 1.14x | bitwise equal +SWEEP gdn out N 2560 K 6144 T 7030 | f16 28.590 ms 7.74 TFLOPS | f32 25.361 ms 8.72 TFLOPS | 1.13x | bitwise equal +SWEEP gdn out N 2560 K 6144 T 7031 | f16 28.606 ms 7.73 TFLOPS | f32 26.592 ms 8.32 TFLOPS | 1.08x | bitwise equal +SWEEP gdn out N 2560 K 6144 T 7032 | f16 28.625 ms 7.73 TFLOPS | f32 25.736 ms 8.60 TFLOPS | 1.11x | bitwise equal +SWEEP gdn out N 2560 K 6144 T 7033 | f16 28.619 ms 7.73 TFLOPS | f32 25.252 ms 8.76 TFLOPS | 1.13x | bitwise equal +SWEEP gdn out N 2560 K 6144 T 7034 | f16 28.588 ms 7.74 TFLOPS | f32 26.150 ms 8.46 TFLOPS | 1.09x | bitwise equal +SWEEP gdn out N 2560 K 6144 T 7035 | f16 28.611 ms 7.73 TFLOPS | f32 26.057 ms 8.49 TFLOPS | 1.10x | bitwise equal +SWEEP gdn out N 2560 K 6144 T 7036 | f16 29.350 ms 7.54 TFLOPS | f32 25.072 ms 8.83 TFLOPS | 1.17x | bitwise equal +SWEEP gdn out N 2560 K 6144 T 7037 | f16 28.611 ms 7.74 TFLOPS | f32 26.780 ms 8.27 TFLOPS | 1.07x | bitwise equal +SWEEP gdn out N 2560 K 6144 T 7038 | f16 28.605 ms 7.74 TFLOPS | f32 25.626 ms 8.64 TFLOPS | 1.12x | bitwise equal +SWEEP gdn out N 2560 K 6144 T 7039 | f16 28.823 ms 7.68 TFLOPS | f32 25.842 ms 8.57 TFLOPS | 1.12x | bitwise equal +SWEEP gdn out N 2560 K 6144 T 7040 | f16 28.906 ms 7.66 TFLOPS | f32 26.181 ms 8.46 TFLOPS | 1.10x | bitwise equal +SWEEP gdn out N 2560 K 6144 T 7041 | f16 48.473 ms 4.57 TFLOPS | f32 25.036 ms 8.85 TFLOPS | 1.94x | bitwise equal +SWEEP gdn out N 2560 K 6144 T 7042 | f16 49.709 ms 4.46 TFLOPS | f32 26.096 ms 8.49 TFLOPS | 1.90x | bitwise equal +SWEEP gdn out N 2560 K 6144 T 7043 | f16 48.097 ms 4.61 TFLOPS | f32 25.185 ms 8.80 TFLOPS | 1.91x | bitwise equal +SWEEP gdn out N 2560 K 6144 T 7044 | f16 43.843 ms 5.05 TFLOPS | f32 24.807 ms 8.93 TFLOPS | 1.77x | bitwise equal +SWEEP gdn out N 2560 K 6144 T 7045 | f16 49.106 ms 4.51 TFLOPS | f32 25.630 ms 8.65 TFLOPS | 1.92x | bitwise equal +SWEEP gdn out N 2560 K 6144 T 7046 | f16 50.561 ms 4.38 TFLOPS | f32 25.341 ms 8.75 TFLOPS | 2.00x | bitwise equal +SWEEP gdn out N 2560 K 6144 T 7047 | f16 46.851 ms 4.73 TFLOPS | f32 25.758 ms 8.61 TFLOPS | 1.82x | bitwise equal +SWEEP gdn out N 2560 K 6144 T 7048 | f16 47.575 ms 4.66 TFLOPS | f32 25.340 ms 8.75 TFLOPS | 1.88x | bitwise equal +SWEEP gdn out N 2560 K 6144 T 7049 | f16 47.115 ms 4.71 TFLOPS | f32 24.701 ms 8.98 TFLOPS | 1.91x | bitwise equal +SWEEP gdn out N 2560 K 6144 T 7050 | f16 47.151 ms 4.70 TFLOPS | f32 26.556 ms 8.35 TFLOPS | 1.78x | bitwise equal +SWEEP gdn out N 2560 K 6144 T 7051 | f16 47.789 ms 4.64 TFLOPS | f32 25.043 ms 8.86 TFLOPS | 1.91x | bitwise equal +SWEEP gdn out N 2560 K 6144 T 7052 | f16 49.345 ms 4.50 TFLOPS | f32 25.609 ms 8.66 TFLOPS | 1.93x | bitwise equal +SWEEP gdn out N 2560 K 6144 T 7053 | f16 46.835 ms 4.74 TFLOPS | f32 24.960 ms 8.89 TFLOPS | 1.88x | bitwise equal +SWEEP gdn out N 2560 K 6144 T 7054 | f16 46.682 ms 4.75 TFLOPS | f32 25.798 ms 8.60 TFLOPS | 1.81x | bitwise equal +SWEEP gdn out N 2560 K 6144 T 7055 | f16 48.006 ms 4.62 TFLOPS | f32 25.839 ms 8.59 TFLOPS | 1.86x | bitwise equal +SWEEP gdn out N 2560 K 6144 T 7056 | f16 46.022 ms 4.82 TFLOPS | f32 25.126 ms 8.83 TFLOPS | 1.83x | bitwise equal +SWEEP gdn out N 2560 K 6144 T 1024 | f16 3.771 ms 8.54 TFLOPS | f32 3.743 ms 8.61 TFLOPS | 1.01x | bitwise equal +SWEEP gdn out N 2560 K 6144 T 2048 | f16 8.301 ms 7.76 TFLOPS | f32 7.303 ms 8.82 TFLOPS | 1.14x | bitwise equal +SWEEP gdn out N 2560 K 6144 T 4096 | f16 21.549 ms 5.98 TFLOPS | f32 14.073 ms 9.16 TFLOPS | 1.53x | bitwise equal +SWEEP gdn out N 2560 K 6144 T 8192 | f16 33.480 ms 7.70 TFLOPS | f32 29.797 ms 8.65 TFLOPS | 1.12x | bitwise equal +SWEEP gdn out N 2560 K 6144 T 1000 | f16 4.047 ms 7.77 TFLOPS | f32 3.974 ms 7.92 TFLOPS | 1.02x | bitwise equal +SWEEP gdn out N 2560 K 6144 T 3000 | f16 12.551 ms 7.52 TFLOPS | f32 10.412 ms 9.06 TFLOPS | 1.21x | bitwise equal +SWEEP gdn out N 2560 K 6144 T 5000 | f16 30.297 ms 5.19 TFLOPS | f32 17.915 ms 8.78 TFLOPS | 1.69x | bitwise equal +SUMMARY gdn out : 71 of 102 T values bitwise equal; f16 below 6 TFLOPS at 23 of the T >= 256; total f16 1846 ms, f32 1304 ms +SWEEP qsa out N 2560 K 4096 T 1 | f16 0.092 ms 0.23 TFLOPS | f32 0.157 ms 0.13 TFLOPS | 0.59x | bitwise equal +SWEEP qsa out N 2560 K 4096 T 2 | f16 0.180 ms 0.23 TFLOPS | f32 0.155 ms 0.27 TFLOPS | 1.16x | DIFFERENT + 4786 of 5120 outputs differ +SWEEP qsa out N 2560 K 4096 T 3 | f16 0.182 ms 0.34 TFLOPS | f32 0.161 ms 0.39 TFLOPS | 1.14x | DIFFERENT + 7163 of 7680 outputs differ +SWEEP qsa out N 2560 K 4096 T 4 | f16 0.180 ms 0.47 TFLOPS | f32 0.159 ms 0.53 TFLOPS | 1.14x | DIFFERENT + 9568 of 10240 outputs differ +SWEEP qsa out N 2560 K 4096 T 5 | f16 0.182 ms 0.58 TFLOPS | f32 0.158 ms 0.66 TFLOPS | 1.16x | DIFFERENT + 12089 of 12800 outputs differ +SWEEP qsa out N 2560 K 4096 T 6 | f16 0.184 ms 0.68 TFLOPS | f32 0.158 ms 0.80 TFLOPS | 1.17x | DIFFERENT + 14509 of 15360 outputs differ +SWEEP qsa out N 2560 K 4096 T 7 | f16 0.182 ms 0.81 TFLOPS | f32 0.157 ms 0.94 TFLOPS | 1.16x | DIFFERENT + 16932 of 17920 outputs differ +SWEEP qsa out N 2560 K 4096 T 8 | f16 0.184 ms 0.91 TFLOPS | f32 0.160 ms 1.05 TFLOPS | 1.15x | DIFFERENT + 19346 of 20480 outputs differ +SWEEP qsa out N 2560 K 4096 T 9 | f16 0.182 ms 1.04 TFLOPS | f32 0.157 ms 1.20 TFLOPS | 1.16x | DIFFERENT + 21779 of 23040 outputs differ +SWEEP qsa out N 2560 K 4096 T 10 | f16 0.182 ms 1.15 TFLOPS | f32 0.157 ms 1.34 TFLOPS | 1.16x | DIFFERENT + 24204 of 25600 outputs differ +SWEEP qsa out N 2560 K 4096 T 11 | f16 0.184 ms 1.25 TFLOPS | f32 0.160 ms 1.44 TFLOPS | 1.15x | DIFFERENT + 26628 of 28160 outputs differ +SWEEP qsa out N 2560 K 4096 T 12 | f16 0.184 ms 1.37 TFLOPS | f32 0.158 ms 1.60 TFLOPS | 1.17x | DIFFERENT + 29038 of 30720 outputs differ +SWEEP qsa out N 2560 K 4096 T 13 | f16 0.186 ms 1.46 TFLOPS | f32 0.159 ms 1.71 TFLOPS | 1.17x | DIFFERENT + 31448 of 33280 outputs differ +SWEEP qsa out N 2560 K 4096 T 14 | f16 0.187 ms 1.57 TFLOPS | f32 0.158 ms 1.85 TFLOPS | 1.18x | DIFFERENT + 33874 of 35840 outputs differ +SWEEP qsa out N 2560 K 4096 T 15 | f16 0.185 ms 1.70 TFLOPS | f32 0.159 ms 1.97 TFLOPS | 1.16x | DIFFERENT + 36302 of 38400 outputs differ +SWEEP qsa out N 2560 K 4096 T 16 | f16 0.185 ms 1.81 TFLOPS | f32 0.160 ms 2.10 TFLOPS | 1.16x | DIFFERENT + 38739 of 40960 outputs differ +SWEEP qsa out N 2560 K 4096 T 24 | f16 0.189 ms 2.66 TFLOPS | f32 0.159 ms 3.16 TFLOPS | 1.19x | DIFFERENT + 58184 of 61440 outputs differ +SWEEP qsa out N 2560 K 4096 T 48 | f16 0.203 ms 4.95 TFLOPS | f32 0.219 ms 4.59 TFLOPS | 0.93x | DIFFERENT + 116400 of 122880 outputs differ +SWEEP qsa out N 2560 K 4096 T 72 | f16 0.419 ms 3.61 TFLOPS | f32 0.372 ms 4.06 TFLOPS | 1.13x | DIFFERENT + 177026 of 184320 outputs differ +SWEEP qsa out N 2560 K 4096 T 96 | f16 0.424 ms 4.75 TFLOPS | f32 0.393 ms 5.13 TFLOPS | 1.08x | DIFFERENT + 236087 of 245760 outputs differ +SWEEP qsa out N 2560 K 4096 T 120 | f16 0.430 ms 5.86 TFLOPS | f32 0.394 ms 6.38 TFLOPS | 1.09x | DIFFERENT + 295169 of 307200 outputs differ +SWEEP qsa out N 2560 K 4096 T 144 | f16 0.441 ms 6.85 TFLOPS | f32 0.635 ms 4.76 TFLOPS | 0.69x | DIFFERENT + 354111 of 368640 outputs differ +SWEEP qsa out N 2560 K 4096 T 168 | f16 0.439 ms 8.02 TFLOPS | f32 0.646 ms 5.46 TFLOPS | 0.68x | DIFFERENT + 413021 of 430080 outputs differ +SWEEP qsa out N 2560 K 4096 T 192 | f16 0.445 ms 9.05 TFLOPS | f32 0.650 ms 6.19 TFLOPS | 0.68x | DIFFERENT + 471998 of 491520 outputs differ +SWEEP qsa out N 2560 K 4096 T 216 | f16 0.684 ms 6.62 TFLOPS | f32 0.662 ms 6.85 TFLOPS | 1.03x | DIFFERENT + 530991 of 552960 outputs differ +SWEEP qsa out N 2560 K 4096 T 240 | f16 0.685 ms 7.35 TFLOPS | f32 0.667 ms 7.55 TFLOPS | 1.03x | DIFFERENT + 589942 of 614400 outputs differ +SWEEP qsa out N 2560 K 4096 T 264 | f16 0.837 ms 6.62 TFLOPS | f32 0.868 ms 6.38 TFLOPS | 0.96x | DIFFERENT + 648923 of 675840 outputs differ +SWEEP qsa out N 2560 K 4096 T 288 | f16 0.834 ms 7.24 TFLOPS | f32 0.871 ms 6.93 TFLOPS | 0.96x | DIFFERENT + 707948 of 737280 outputs differ +SWEEP qsa out N 2560 K 4096 T 312 | f16 0.834 ms 7.85 TFLOPS | f32 0.883 ms 7.41 TFLOPS | 0.94x | DIFFERENT + 766891 of 798720 outputs differ +SWEEP qsa out N 2560 K 4096 T 336 | f16 0.955 ms 7.38 TFLOPS | f32 0.894 ms 7.88 TFLOPS | 1.07x | DIFFERENT + 836661 of 860160 outputs differ +SWEEP qsa out N 2560 K 4096 T 360 | f16 0.957 ms 7.89 TFLOPS | f32 0.908 ms 8.32 TFLOPS | 1.05x | DIFFERENT + 896450 of 921600 outputs differ +SWEEP qsa out N 2560 K 4096 T 384 | f16 0.988 ms 8.15 TFLOPS | f32 0.951 ms 8.47 TFLOPS | 1.04x | DIFFERENT + 956289 of 983040 outputs differ +SWEEP qsa out N 2560 K 4096 T 408 | f16 1.214 ms 7.05 TFLOPS | f32 1.606 ms 5.33 TFLOPS | 0.76x | bitwise equal +SWEEP qsa out N 2560 K 4096 T 432 | f16 1.316 ms 6.89 TFLOPS | f32 1.395 ms 6.50 TFLOPS | 0.94x | bitwise equal +SWEEP qsa out N 2560 K 4096 T 456 | f16 1.485 ms 6.44 TFLOPS | f32 1.606 ms 5.96 TFLOPS | 0.92x | bitwise equal +SWEEP qsa out N 2560 K 4096 T 480 | f16 1.486 ms 6.77 TFLOPS | f32 1.391 ms 7.24 TFLOPS | 1.07x | bitwise equal +SWEEP qsa out N 2560 K 4096 T 504 | f16 1.450 ms 7.29 TFLOPS | f32 1.366 ms 7.74 TFLOPS | 1.06x | bitwise equal +SWEEP qsa out N 2560 K 4096 T 560 | f16 1.430 ms 8.22 TFLOPS | f32 1.591 ms 7.38 TFLOPS | 0.90x | bitwise equal +SWEEP qsa out N 2560 K 4096 T 813 | f16 2.083 ms 8.19 TFLOPS | f32 2.361 ms 7.22 TFLOPS | 0.88x | bitwise equal +SWEEP qsa out N 2560 K 4096 T 1066 | f16 2.398 ms 9.32 TFLOPS | f32 2.411 ms 9.27 TFLOPS | 0.99x | bitwise equal +SWEEP qsa out N 2560 K 4096 T 1319 | f16 3.056 ms 9.05 TFLOPS | f32 3.266 ms 8.47 TFLOPS | 0.94x | bitwise equal +SWEEP qsa out N 2560 K 4096 T 1572 | f16 3.742 ms 8.81 TFLOPS | f32 4.029 ms 8.18 TFLOPS | 0.93x | bitwise equal +SWEEP qsa out N 2560 K 4096 T 1825 | f16 4.076 ms 9.39 TFLOPS | f32 4.097 ms 9.34 TFLOPS | 1.00x | bitwise equal +SWEEP qsa out N 2560 K 4096 T 2078 | f16 4.737 ms 9.20 TFLOPS | f32 4.866 ms 8.96 TFLOPS | 0.97x | bitwise equal +SWEEP qsa out N 2560 K 4096 T 2331 | f16 5.425 ms 9.01 TFLOPS | f32 5.453 ms 8.97 TFLOPS | 0.99x | bitwise equal +SWEEP qsa out N 2560 K 4096 T 2584 | f16 5.770 ms 9.39 TFLOPS | f32 5.765 ms 9.40 TFLOPS | 1.00x | bitwise equal +SWEEP qsa out N 2560 K 4096 T 2837 | f16 6.599 ms 9.02 TFLOPS | f32 6.685 ms 8.90 TFLOPS | 0.99x | bitwise equal +SWEEP qsa out N 2560 K 4096 T 3090 | f16 7.402 ms 8.75 TFLOPS | f32 7.244 ms 8.95 TFLOPS | 1.02x | bitwise equal +SWEEP qsa out N 2560 K 4096 T 3343 | f16 7.628 ms 9.19 TFLOPS | f32 7.518 ms 9.32 TFLOPS | 1.01x | bitwise equal +SWEEP qsa out N 2560 K 4096 T 3596 | f16 8.365 ms 9.02 TFLOPS | f32 8.379 ms 9.00 TFLOPS | 1.00x | bitwise equal +SWEEP qsa out N 2560 K 4096 T 3849 | f16 9.423 ms 8.57 TFLOPS | f32 9.149 ms 8.82 TFLOPS | 1.03x | bitwise equal +SWEEP qsa out N 2560 K 4096 T 4102 | f16 9.652 ms 8.91 TFLOPS | f32 9.515 ms 9.04 TFLOPS | 1.01x | bitwise equal +SWEEP qsa out N 2560 K 4096 T 4355 | f16 10.370 ms 8.81 TFLOPS | f32 10.222 ms 8.94 TFLOPS | 1.01x | bitwise equal +SWEEP qsa out N 2560 K 4096 T 4608 | f16 13.146 ms 7.35 TFLOPS | f32 10.815 ms 8.94 TFLOPS | 1.22x | bitwise equal +SWEEP qsa out N 2560 K 4096 T 4861 | f16 11.738 ms 8.68 TFLOPS | f32 11.391 ms 8.95 TFLOPS | 1.03x | bitwise equal +SWEEP qsa out N 2560 K 4096 T 5114 | f16 14.623 ms 7.33 TFLOPS | f32 12.432 ms 8.63 TFLOPS | 1.18x | bitwise equal +SWEEP qsa out N 2560 K 4096 T 5367 | f16 16.164 ms 6.96 TFLOPS | f32 13.309 ms 8.46 TFLOPS | 1.21x | bitwise equal +SWEEP qsa out N 2560 K 4096 T 5620 | f16 14.314 ms 8.23 TFLOPS | f32 13.713 ms 8.59 TFLOPS | 1.04x | bitwise equal +SWEEP qsa out N 2560 K 4096 T 5873 | f16 17.403 ms 7.08 TFLOPS | f32 14.636 ms 8.42 TFLOPS | 1.19x | bitwise equal +SWEEP qsa out N 2560 K 4096 T 6126 | f16 18.188 ms 7.06 TFLOPS | f32 14.874 ms 8.64 TFLOPS | 1.22x | bitwise equal +SWEEP qsa out N 2560 K 4096 T 6379 | f16 15.897 ms 8.42 TFLOPS | f32 15.383 ms 8.70 TFLOPS | 1.03x | bitwise equal +SWEEP qsa out N 2560 K 4096 T 6632 | f16 19.491 ms 7.14 TFLOPS | f32 16.409 ms 8.48 TFLOPS | 1.19x | bitwise equal +SWEEP qsa out N 2560 K 4096 T 6885 | f16 20.060 ms 7.20 TFLOPS | f32 16.662 ms 8.67 TFLOPS | 1.20x | bitwise equal +SWEEP qsa out N 2560 K 4096 T 7138 | f16 17.559 ms 8.53 TFLOPS | f32 17.064 ms 8.77 TFLOPS | 1.03x | bitwise equal +SWEEP qsa out N 2560 K 4096 T 7391 | f16 21.445 ms 7.23 TFLOPS | f32 18.161 ms 8.53 TFLOPS | 1.18x | bitwise equal +SWEEP qsa out N 2560 K 4096 T 7644 | f16 22.261 ms 7.20 TFLOPS | f32 18.365 ms 8.73 TFLOPS | 1.21x | bitwise equal +SWEEP qsa out N 2560 K 4096 T 7897 | f16 19.482 ms 8.50 TFLOPS | f32 18.711 ms 8.85 TFLOPS | 1.04x | bitwise equal +SWEEP qsa out N 2560 K 4096 T 8150 | f16 23.279 ms 7.34 TFLOPS | f32 19.534 ms 8.75 TFLOPS | 1.19x | bitwise equal +SWEEP qsa out N 2560 K 4096 T 7030 | f16 19.845 ms 7.43 TFLOPS | f32 16.620 ms 8.87 TFLOPS | 1.19x | bitwise equal +SWEEP qsa out N 2560 K 4096 T 7031 | f16 20.348 ms 7.25 TFLOPS | f32 16.908 ms 8.72 TFLOPS | 1.20x | bitwise equal +SWEEP qsa out N 2560 K 4096 T 7032 | f16 19.847 ms 7.43 TFLOPS | f32 16.458 ms 8.96 TFLOPS | 1.21x | bitwise equal +SWEEP qsa out N 2560 K 4096 T 7033 | f16 20.001 ms 7.37 TFLOPS | f32 16.645 ms 8.86 TFLOPS | 1.20x | bitwise equal +SWEEP qsa out N 2560 K 4096 T 7034 | f16 19.845 ms 7.43 TFLOPS | f32 16.637 ms 8.87 TFLOPS | 1.19x | bitwise equal +SWEEP qsa out N 2560 K 4096 T 7035 | f16 20.031 ms 7.37 TFLOPS | f32 16.714 ms 8.83 TFLOPS | 1.20x | bitwise equal +SWEEP qsa out N 2560 K 4096 T 7036 | f16 20.011 ms 7.37 TFLOPS | f32 16.464 ms 8.96 TFLOPS | 1.22x | bitwise equal +SWEEP qsa out N 2560 K 4096 T 7037 | f16 20.431 ms 7.22 TFLOPS | f32 17.201 ms 8.58 TFLOPS | 1.19x | bitwise equal +SWEEP qsa out N 2560 K 4096 T 7038 | f16 20.524 ms 7.19 TFLOPS | f32 16.969 ms 8.70 TFLOPS | 1.21x | bitwise equal +SWEEP qsa out N 2560 K 4096 T 7039 | f16 20.398 ms 7.24 TFLOPS | f32 17.132 ms 8.62 TFLOPS | 1.19x | bitwise equal +SWEEP qsa out N 2560 K 4096 T 7040 | f16 20.609 ms 7.16 TFLOPS | f32 17.319 ms 8.52 TFLOPS | 1.19x | bitwise equal +SWEEP qsa out N 2560 K 4096 T 7041 | f16 17.639 ms 8.37 TFLOPS | f32 17.087 ms 8.64 TFLOPS | 1.03x | bitwise equal +SWEEP qsa out N 2560 K 4096 T 7042 | f16 17.878 ms 8.26 TFLOPS | f32 17.200 ms 8.59 TFLOPS | 1.04x | bitwise equal +SWEEP qsa out N 2560 K 4096 T 7043 | f16 17.778 ms 8.31 TFLOPS | f32 17.445 ms 8.47 TFLOPS | 1.02x | bitwise equal +SWEEP qsa out N 2560 K 4096 T 7044 | f16 18.811 ms 7.85 TFLOPS | f32 18.474 ms 8.00 TFLOPS | 1.02x | bitwise equal +SWEEP qsa out N 2560 K 4096 T 7045 | f16 19.067 ms 7.75 TFLOPS | f32 18.462 ms 8.00 TFLOPS | 1.03x | bitwise equal +SWEEP qsa out N 2560 K 4096 T 7046 | f16 18.397 ms 8.03 TFLOPS | f32 18.020 ms 8.20 TFLOPS | 1.02x | bitwise equal +SWEEP qsa out N 2560 K 4096 T 7047 | f16 18.406 ms 8.03 TFLOPS | f32 18.183 ms 8.13 TFLOPS | 1.01x | bitwise equal +SWEEP qsa out N 2560 K 4096 T 7048 | f16 18.325 ms 8.07 TFLOPS | f32 17.757 ms 8.32 TFLOPS | 1.03x | bitwise equal +SWEEP qsa out N 2560 K 4096 T 7049 | f16 18.378 ms 8.04 TFLOPS | f32 17.809 ms 8.30 TFLOPS | 1.03x | bitwise equal +SWEEP qsa out N 2560 K 4096 T 7050 | f16 18.668 ms 7.92 TFLOPS | f32 17.667 ms 8.37 TFLOPS | 1.06x | bitwise equal +SWEEP qsa out N 2560 K 4096 T 7051 | f16 17.948 ms 8.24 TFLOPS | f32 17.254 ms 8.57 TFLOPS | 1.04x | bitwise equal +SWEEP qsa out N 2560 K 4096 T 7052 | f16 17.802 ms 8.31 TFLOPS | f32 17.568 ms 8.42 TFLOPS | 1.01x | bitwise equal +SWEEP qsa out N 2560 K 4096 T 7053 | f16 17.549 ms 8.43 TFLOPS | f32 17.194 ms 8.60 TFLOPS | 1.02x | bitwise equal +SWEEP qsa out N 2560 K 4096 T 7054 | f16 17.981 ms 8.23 TFLOPS | f32 17.202 ms 8.60 TFLOPS | 1.05x | bitwise equal +SWEEP qsa out N 2560 K 4096 T 7055 | f16 17.511 ms 8.45 TFLOPS | f32 17.350 ms 8.53 TFLOPS | 1.01x | bitwise equal +SWEEP qsa out N 2560 K 4096 T 7056 | f16 17.502 ms 8.45 TFLOPS | f32 17.171 ms 8.62 TFLOPS | 1.02x | bitwise equal +SWEEP qsa out N 2560 K 4096 T 1024 | f16 2.751 ms 7.81 TFLOPS | f32 2.731 ms 7.86 TFLOPS | 1.01x | bitwise equal +SWEEP qsa out N 2560 K 4096 T 2048 | f16 6.135 ms 7.00 TFLOPS | f32 5.481 ms 7.84 TFLOPS | 1.12x | bitwise equal +SWEEP qsa out N 2560 K 4096 T 4096 | f16 10.376 ms 8.28 TFLOPS | f32 10.281 ms 8.36 TFLOPS | 1.01x | bitwise equal +SWEEP qsa out N 2560 K 4096 T 8192 | f16 24.831 ms 6.92 TFLOPS | f32 20.740 ms 8.28 TFLOPS | 1.20x | bitwise equal +SWEEP qsa out N 2560 K 4096 T 1000 | f16 2.777 ms 7.55 TFLOPS | f32 2.756 ms 7.61 TFLOPS | 1.01x | bitwise equal +SWEEP qsa out N 2560 K 4096 T 3000 | f16 7.415 ms 8.49 TFLOPS | f32 7.482 ms 8.41 TFLOPS | 0.99x | bitwise equal +SWEEP qsa out N 2560 K 4096 T 5000 | f16 12.930 ms 8.11 TFLOPS | f32 12.965 ms 8.09 TFLOPS | 1.00x | bitwise equal +SUMMARY qsa out : 71 of 102 T values bitwise equal; f16 below 6 TFLOPS at 0 of the T >= 256; total f16 956 ms, f32 873 ms +SWEEP qsa k/v N 512 K 2560 T 1 | f16 0.027 ms 0.10 TFLOPS | f32 0.032 ms 0.08 TFLOPS | 0.84x | bitwise equal +SWEEP qsa k/v N 512 K 2560 T 2 | f16 0.033 ms 0.16 TFLOPS | f32 0.030 ms 0.18 TFLOPS | 1.10x | DIFFERENT + 876 of 1024 outputs differ +SWEEP qsa k/v N 512 K 2560 T 3 | f16 0.033 ms 0.24 TFLOPS | f32 0.032 ms 0.25 TFLOPS | 1.03x | DIFFERENT + 1326 of 1536 outputs differ +SWEEP qsa k/v N 512 K 2560 T 4 | f16 0.033 ms 0.31 TFLOPS | f32 0.032 ms 0.33 TFLOPS | 1.05x | DIFFERENT + 1779 of 2048 outputs differ +SWEEP qsa k/v N 512 K 2560 T 5 | f16 0.037 ms 0.36 TFLOPS | f32 0.067 ms 0.20 TFLOPS | 0.55x | DIFFERENT + 2311 of 2560 outputs differ +SWEEP qsa k/v N 512 K 2560 T 6 | f16 0.034 ms 0.47 TFLOPS | f32 0.068 ms 0.23 TFLOPS | 0.50x | DIFFERENT + 2781 of 3072 outputs differ +SWEEP qsa k/v N 512 K 2560 T 7 | f16 0.035 ms 0.53 TFLOPS | f32 0.068 ms 0.27 TFLOPS | 0.51x | DIFFERENT + 3257 of 3584 outputs differ +SWEEP qsa k/v N 512 K 2560 T 8 | f16 0.034 ms 0.62 TFLOPS | f32 0.067 ms 0.31 TFLOPS | 0.50x | DIFFERENT + 3722 of 4096 outputs differ +SWEEP qsa k/v N 512 K 2560 T 9 | f16 0.040 ms 0.59 TFLOPS | f32 0.068 ms 0.34 TFLOPS | 0.58x | DIFFERENT + 4203 of 4608 outputs differ +SWEEP qsa k/v N 512 K 2560 T 10 | f16 0.035 ms 0.75 TFLOPS | f32 0.069 ms 0.38 TFLOPS | 0.51x | DIFFERENT + 4676 of 5120 outputs differ +SWEEP qsa k/v N 512 K 2560 T 11 | f16 0.034 ms 0.85 TFLOPS | f32 0.070 ms 0.41 TFLOPS | 0.49x | DIFFERENT + 5151 of 5632 outputs differ +SWEEP qsa k/v N 512 K 2560 T 12 | f16 0.037 ms 0.86 TFLOPS | f32 0.069 ms 0.46 TFLOPS | 0.53x | DIFFERENT + 5617 of 6144 outputs differ +SWEEP qsa k/v N 512 K 2560 T 13 | f16 0.034 ms 1.01 TFLOPS | f32 0.069 ms 0.50 TFLOPS | 0.49x | DIFFERENT + 6087 of 6656 outputs differ +SWEEP qsa k/v N 512 K 2560 T 14 | f16 0.035 ms 1.05 TFLOPS | f32 0.069 ms 0.53 TFLOPS | 0.51x | DIFFERENT + 6554 of 7168 outputs differ +SWEEP qsa k/v N 512 K 2560 T 15 | f16 0.035 ms 1.13 TFLOPS | f32 0.069 ms 0.57 TFLOPS | 0.51x | DIFFERENT + 7029 of 7680 outputs differ +SWEEP qsa k/v N 512 K 2560 T 16 | f16 0.036 ms 1.17 TFLOPS | f32 0.071 ms 0.59 TFLOPS | 0.51x | DIFFERENT + 7500 of 8192 outputs differ +SWEEP qsa k/v N 512 K 2560 T 24 | f16 0.036 ms 1.76 TFLOPS | f32 0.071 ms 0.89 TFLOPS | 0.51x | DIFFERENT + 11241 of 12288 outputs differ +SWEEP qsa k/v N 512 K 2560 T 48 | f16 0.047 ms 2.67 TFLOPS | f32 0.073 ms 1.73 TFLOPS | 0.65x | DIFFERENT + 22634 of 24576 outputs differ +SWEEP qsa k/v N 512 K 2560 T 72 | f16 0.057 ms 3.29 TFLOPS | f32 0.074 ms 2.56 TFLOPS | 0.78x | DIFFERENT + 34088 of 36864 outputs differ +SWEEP qsa k/v N 512 K 2560 T 96 | f16 0.058 ms 4.31 TFLOPS | f32 0.074 ms 3.41 TFLOPS | 0.79x | DIFFERENT + 45471 of 49152 outputs differ +SWEEP qsa k/v N 512 K 2560 T 120 | f16 0.087 ms 3.62 TFLOPS | f32 0.077 ms 4.09 TFLOPS | 1.13x | DIFFERENT + 57002 of 61440 outputs differ +SWEEP qsa k/v N 512 K 2560 T 144 | f16 0.084 ms 4.50 TFLOPS | f32 0.081 ms 4.67 TFLOPS | 1.04x | DIFFERENT + 68912 of 73728 outputs differ +SWEEP qsa k/v N 512 K 2560 T 168 | f16 0.100 ms 4.40 TFLOPS | f32 0.137 ms 3.22 TFLOPS | 0.73x | DIFFERENT + 80587 of 86016 outputs differ +SWEEP qsa k/v N 512 K 2560 T 192 | f16 0.093 ms 5.40 TFLOPS | f32 0.139 ms 3.61 TFLOPS | 0.67x | DIFFERENT + 92080 of 98304 outputs differ +SWEEP qsa k/v N 512 K 2560 T 216 | f16 0.128 ms 4.42 TFLOPS | f32 0.143 ms 3.95 TFLOPS | 0.89x | DIFFERENT + 103580 of 110592 outputs differ +SWEEP qsa k/v N 512 K 2560 T 240 | f16 0.151 ms 4.18 TFLOPS | f32 0.143 ms 4.38 TFLOPS | 1.05x | DIFFERENT + 115570 of 122880 outputs differ +SWEEP qsa k/v N 512 K 2560 T 264 | f16 0.163 ms 4.25 TFLOPS | f32 0.149 ms 4.63 TFLOPS | 1.09x | DIFFERENT + 127141 of 135168 outputs differ +SWEEP qsa k/v N 512 K 2560 T 288 | f16 0.163 ms 4.64 TFLOPS | f32 0.149 ms 5.06 TFLOPS | 1.09x | DIFFERENT + 138708 of 147456 outputs differ +SWEEP qsa k/v N 512 K 2560 T 312 | f16 0.146 ms 5.59 TFLOPS | f32 0.151 ms 5.43 TFLOPS | 0.97x | DIFFERENT + 149387 of 159744 outputs differ +SWEEP qsa k/v N 512 K 2560 T 336 | f16 0.160 ms 5.49 TFLOPS | f32 0.152 ms 5.81 TFLOPS | 1.06x | DIFFERENT + 161061 of 172032 outputs differ +SWEEP qsa k/v N 512 K 2560 T 360 | f16 0.161 ms 5.87 TFLOPS | f32 0.209 ms 4.52 TFLOPS | 0.77x | DIFFERENT + 172489 of 184320 outputs differ +SWEEP qsa k/v N 512 K 2560 T 384 | f16 0.163 ms 6.18 TFLOPS | f32 0.209 ms 4.82 TFLOPS | 0.78x | DIFFERENT + 184001 of 196608 outputs differ +SWEEP qsa k/v N 512 K 2560 T 408 | f16 0.223 ms 4.79 TFLOPS | f32 0.202 ms 5.30 TFLOPS | 1.11x | bitwise equal +SWEEP qsa k/v N 512 K 2560 T 432 | f16 0.224 ms 5.05 TFLOPS | f32 0.200 ms 5.67 TFLOPS | 1.12x | bitwise equal +SWEEP qsa k/v N 512 K 2560 T 456 | f16 0.239 ms 5.01 TFLOPS | f32 0.241 ms 4.97 TFLOPS | 0.99x | DIFFERENT + 217395 of 233472 outputs differ +SWEEP qsa k/v N 512 K 2560 T 480 | f16 0.239 ms 5.26 TFLOPS | f32 0.221 ms 5.70 TFLOPS | 1.08x | DIFFERENT + 228852 of 245760 outputs differ +SWEEP qsa k/v N 512 K 2560 T 504 | f16 0.242 ms 5.45 TFLOPS | f32 0.219 ms 6.03 TFLOPS | 1.11x | DIFFERENT + 240302 of 258048 outputs differ +SWEEP qsa k/v N 512 K 2560 T 560 | f16 0.268 ms 5.47 TFLOPS | f32 0.240 ms 6.13 TFLOPS | 1.12x | DIFFERENT + 266927 of 286720 outputs differ +SWEEP qsa k/v N 512 K 2560 T 813 | f16 0.384 ms 5.55 TFLOPS | f32 0.327 ms 6.53 TFLOPS | 1.18x | DIFFERENT + 395262 of 416256 outputs differ +SWEEP qsa k/v N 512 K 2560 T 1066 | f16 0.449 ms 6.22 TFLOPS | f32 0.390 ms 7.16 TFLOPS | 1.15x | DIFFERENT + 518307 of 545792 outputs differ +SWEEP qsa k/v N 512 K 2560 T 1319 | f16 0.506 ms 6.84 TFLOPS | f32 0.485 ms 7.12 TFLOPS | 1.04x | DIFFERENT + 641391 of 675328 outputs differ +SWEEP qsa k/v N 512 K 2560 T 1572 | f16 0.576 ms 7.16 TFLOPS | f32 0.575 ms 7.16 TFLOPS | 1.00x | DIFFERENT + 764341 of 804864 outputs differ +SWEEP qsa k/v N 512 K 2560 T 1825 | f16 0.656 ms 7.29 TFLOPS | f32 0.597 ms 8.01 TFLOPS | 1.10x | DIFFERENT + 892861 of 934400 outputs differ +SWEEP qsa k/v N 512 K 2560 T 2078 | f16 0.822 ms 6.63 TFLOPS | f32 0.992 ms 5.49 TFLOPS | 0.83x | bitwise equal +SWEEP qsa k/v N 512 K 2560 T 2331 | f16 1.047 ms 5.84 TFLOPS | f32 1.020 ms 5.99 TFLOPS | 1.03x | bitwise equal +SWEEP qsa k/v N 512 K 2560 T 2584 | f16 1.048 ms 6.47 TFLOPS | f32 1.178 ms 5.75 TFLOPS | 0.89x | bitwise equal +SWEEP qsa k/v N 512 K 2560 T 2837 | f16 1.019 ms 7.30 TFLOPS | f32 1.161 ms 6.41 TFLOPS | 0.88x | bitwise equal +SWEEP qsa k/v N 512 K 2560 T 3090 | f16 1.036 ms 7.82 TFLOPS | f32 1.172 ms 6.91 TFLOPS | 0.88x | bitwise equal +SWEEP qsa k/v N 512 K 2560 T 3343 | f16 1.078 ms 8.13 TFLOPS | f32 1.107 ms 7.92 TFLOPS | 0.97x | bitwise equal +SWEEP qsa k/v N 512 K 2560 T 3596 | f16 1.088 ms 8.66 TFLOPS | f32 1.103 ms 8.55 TFLOPS | 0.99x | bitwise equal +SWEEP qsa k/v N 512 K 2560 T 3849 | f16 1.312 ms 7.69 TFLOPS | f32 1.466 ms 6.88 TFLOPS | 0.90x | bitwise equal +SWEEP qsa k/v N 512 K 2560 T 4102 | f16 1.362 ms 7.90 TFLOPS | f32 1.495 ms 7.19 TFLOPS | 0.91x | bitwise equal +SWEEP qsa k/v N 512 K 2560 T 4355 | f16 1.632 ms 7.00 TFLOPS | f32 1.544 ms 7.39 TFLOPS | 1.06x | bitwise equal +SWEEP qsa k/v N 512 K 2560 T 4608 | f16 1.641 ms 7.36 TFLOPS | f32 1.484 ms 8.14 TFLOPS | 1.11x | bitwise equal +SWEEP qsa k/v N 512 K 2560 T 4861 | f16 1.511 ms 8.43 TFLOPS | f32 1.650 ms 7.72 TFLOPS | 0.92x | bitwise equal +SWEEP qsa k/v N 512 K 2560 T 5114 | f16 1.693 ms 7.92 TFLOPS | f32 1.707 ms 7.85 TFLOPS | 0.99x | bitwise equal +SWEEP qsa k/v N 512 K 2560 T 5367 | f16 1.702 ms 8.27 TFLOPS | f32 1.715 ms 8.20 TFLOPS | 0.99x | bitwise equal +SWEEP qsa k/v N 512 K 2560 T 5620 | f16 1.734 ms 8.50 TFLOPS | f32 1.744 ms 8.45 TFLOPS | 0.99x | bitwise equal +SWEEP qsa k/v N 512 K 2560 T 5873 | f16 2.024 ms 7.60 TFLOPS | f32 2.096 ms 7.35 TFLOPS | 0.97x | bitwise equal +SWEEP qsa k/v N 512 K 2560 T 6126 | f16 2.404 ms 6.68 TFLOPS | f32 2.104 ms 7.63 TFLOPS | 1.14x | bitwise equal +SWEEP qsa k/v N 512 K 2560 T 6379 | f16 2.406 ms 6.95 TFLOPS | f32 2.267 ms 7.38 TFLOPS | 1.06x | bitwise equal +SWEEP qsa k/v N 512 K 2560 T 6632 | f16 2.416 ms 7.19 TFLOPS | f32 2.285 ms 7.61 TFLOPS | 1.06x | bitwise equal +SWEEP qsa k/v N 512 K 2560 T 6885 | f16 2.174 ms 8.30 TFLOPS | f32 2.284 ms 7.90 TFLOPS | 0.95x | bitwise equal +SWEEP qsa k/v N 512 K 2560 T 7138 | f16 2.289 ms 8.17 TFLOPS | f32 2.281 ms 8.20 TFLOPS | 1.00x | bitwise equal +SWEEP qsa k/v N 512 K 2560 T 7391 | f16 2.279 ms 8.50 TFLOPS | f32 2.282 ms 8.49 TFLOPS | 1.00x | bitwise equal +SWEEP qsa k/v N 512 K 2560 T 7644 | f16 2.748 ms 7.29 TFLOPS | f32 2.293 ms 8.74 TFLOPS | 1.20x | bitwise equal +SWEEP qsa k/v N 512 K 2560 T 7897 | f16 2.987 ms 6.93 TFLOPS | f32 2.650 ms 7.81 TFLOPS | 1.13x | bitwise equal +SWEEP qsa k/v N 512 K 2560 T 8150 | f16 3.054 ms 7.00 TFLOPS | f32 2.646 ms 8.07 TFLOPS | 1.15x | bitwise equal +SWEEP qsa k/v N 512 K 2560 T 7030 | f16 2.250 ms 8.19 TFLOPS | f32 2.313 ms 7.97 TFLOPS | 0.97x | bitwise equal +SWEEP qsa k/v N 512 K 2560 T 7031 | f16 2.257 ms 8.17 TFLOPS | f32 2.291 ms 8.05 TFLOPS | 0.99x | bitwise equal +SWEEP qsa k/v N 512 K 2560 T 7032 | f16 2.254 ms 8.18 TFLOPS | f32 2.265 ms 8.14 TFLOPS | 0.99x | bitwise equal +SWEEP qsa k/v N 512 K 2560 T 7033 | f16 2.234 ms 8.25 TFLOPS | f32 2.265 ms 8.14 TFLOPS | 0.99x | bitwise equal +SWEEP qsa k/v N 512 K 2560 T 7034 | f16 2.139 ms 8.62 TFLOPS | f32 2.267 ms 8.13 TFLOPS | 0.94x | bitwise equal +SWEEP qsa k/v N 512 K 2560 T 7035 | f16 2.236 ms 8.25 TFLOPS | f32 2.278 ms 8.09 TFLOPS | 0.98x | bitwise equal +SWEEP qsa k/v N 512 K 2560 T 7036 | f16 2.236 ms 8.25 TFLOPS | f32 2.271 ms 8.12 TFLOPS | 0.98x | bitwise equal +SWEEP qsa k/v N 512 K 2560 T 7037 | f16 2.233 ms 8.26 TFLOPS | f32 2.274 ms 8.11 TFLOPS | 0.98x | bitwise equal +SWEEP qsa k/v N 512 K 2560 T 7038 | f16 2.130 ms 8.66 TFLOPS | f32 2.282 ms 8.08 TFLOPS | 0.93x | bitwise equal +SWEEP qsa k/v N 512 K 2560 T 7039 | f16 2.230 ms 8.27 TFLOPS | f32 2.295 ms 8.04 TFLOPS | 0.97x | bitwise equal +SWEEP qsa k/v N 512 K 2560 T 7040 | f16 2.231 ms 8.27 TFLOPS | f32 2.277 ms 8.10 TFLOPS | 0.98x | bitwise equal +SWEEP qsa k/v N 512 K 2560 T 7041 | f16 2.233 ms 8.27 TFLOPS | f32 2.247 ms 8.22 TFLOPS | 0.99x | bitwise equal +SWEEP qsa k/v N 512 K 2560 T 7042 | f16 2.236 ms 8.25 TFLOPS | f32 2.251 ms 8.20 TFLOPS | 0.99x | bitwise equal +SWEEP qsa k/v N 512 K 2560 T 7043 | f16 2.228 ms 8.29 TFLOPS | f32 2.268 ms 8.14 TFLOPS | 0.98x | bitwise equal +SWEEP qsa k/v N 512 K 2560 T 7044 | f16 2.241 ms 8.24 TFLOPS | f32 2.248 ms 8.22 TFLOPS | 1.00x | bitwise equal +SWEEP qsa k/v N 512 K 2560 T 7045 | f16 2.234 ms 8.27 TFLOPS | f32 2.252 ms 8.20 TFLOPS | 0.99x | bitwise equal +SWEEP qsa k/v N 512 K 2560 T 7046 | f16 2.234 ms 8.27 TFLOPS | f32 2.245 ms 8.23 TFLOPS | 1.00x | bitwise equal +SWEEP qsa k/v N 512 K 2560 T 7047 | f16 2.236 ms 8.26 TFLOPS | f32 2.254 ms 8.20 TFLOPS | 0.99x | bitwise equal +SWEEP qsa k/v N 512 K 2560 T 7048 | f16 2.238 ms 8.25 TFLOPS | f32 2.256 ms 8.19 TFLOPS | 0.99x | bitwise equal +SWEEP qsa k/v N 512 K 2560 T 7049 | f16 2.231 ms 8.28 TFLOPS | f32 2.251 ms 8.21 TFLOPS | 0.99x | bitwise equal +SWEEP qsa k/v N 512 K 2560 T 7050 | f16 2.233 ms 8.28 TFLOPS | f32 2.248 ms 8.22 TFLOPS | 0.99x | bitwise equal +SWEEP qsa k/v N 512 K 2560 T 7051 | f16 2.238 ms 8.26 TFLOPS | f32 2.262 ms 8.17 TFLOPS | 0.99x | bitwise equal +SWEEP qsa k/v N 512 K 2560 T 7052 | f16 2.232 ms 8.28 TFLOPS | f32 2.258 ms 8.19 TFLOPS | 0.99x | bitwise equal +SWEEP qsa k/v N 512 K 2560 T 7053 | f16 2.309 ms 8.01 TFLOPS | f32 2.332 ms 7.93 TFLOPS | 0.99x | bitwise equal +SWEEP qsa k/v N 512 K 2560 T 7054 | f16 2.327 ms 7.95 TFLOPS | f32 2.337 ms 7.91 TFLOPS | 1.00x | bitwise equal +SWEEP qsa k/v N 512 K 2560 T 7055 | f16 2.327 ms 7.95 TFLOPS | f32 2.348 ms 7.88 TFLOPS | 0.99x | bitwise equal +SWEEP qsa k/v N 512 K 2560 T 7056 | f16 2.190 ms 8.44 TFLOPS | f32 2.317 ms 7.98 TFLOPS | 0.95x | bitwise equal +SWEEP qsa k/v N 512 K 2560 T 1024 | f16 0.467 ms 5.75 TFLOPS | f32 0.403 ms 6.65 TFLOPS | 1.16x | DIFFERENT + 497905 of 524288 outputs differ +SWEEP qsa k/v N 512 K 2560 T 2048 | f16 0.842 ms 6.37 TFLOPS | f32 0.991 ms 5.42 TFLOPS | 0.85x | bitwise equal +SWEEP qsa k/v N 512 K 2560 T 4096 | f16 1.474 ms 7.29 TFLOPS | f32 1.558 ms 6.89 TFLOPS | 0.95x | bitwise equal +SWEEP qsa k/v N 512 K 2560 T 8192 | f16 3.113 ms 6.90 TFLOPS | f32 2.846 ms 7.55 TFLOPS | 1.09x | bitwise equal +SWEEP qsa k/v N 512 K 2560 T 1000 | f16 0.440 ms 5.96 TFLOPS | f32 0.385 ms 6.81 TFLOPS | 1.14x | DIFFERENT + 486258 of 512000 outputs differ +SWEEP qsa k/v N 512 K 2560 T 3000 | f16 1.035 ms 7.60 TFLOPS | f32 1.164 ms 6.75 TFLOPS | 0.89x | bitwise equal +SWEEP qsa k/v N 512 K 2560 T 5000 | f16 1.606 ms 8.16 TFLOPS | f32 1.738 ms 7.54 TFLOPS | 0.92x | bitwise equal +SUMMARY qsa k/v : 60 of 102 T values bitwise equal; f16 below 6 TFLOPS at 15 of the T >= 256; total f16 120 ms, f32 121 ms +SWEEP shexp gate/up N 640 K 2560 T 1 | f16 0.029 ms 0.11 TFLOPS | f32 0.035 ms 0.09 TFLOPS | 0.82x | bitwise equal +SWEEP shexp gate/up N 640 K 2560 T 2 | f16 0.039 ms 0.17 TFLOPS | f32 0.034 ms 0.20 TFLOPS | 1.16x | DIFFERENT + 1111 of 1280 outputs differ +SWEEP shexp gate/up N 640 K 2560 T 3 | f16 0.038 ms 0.26 TFLOPS | f32 0.035 ms 0.28 TFLOPS | 1.08x | DIFFERENT + 1673 of 1920 outputs differ +SWEEP shexp gate/up N 640 K 2560 T 4 | f16 0.038 ms 0.35 TFLOPS | f32 0.034 ms 0.39 TFLOPS | 1.12x | DIFFERENT + 2243 of 2560 outputs differ +SWEEP shexp gate/up N 640 K 2560 T 5 | f16 0.040 ms 0.41 TFLOPS | f32 0.067 ms 0.25 TFLOPS | 0.60x | DIFFERENT + 2945 of 3200 outputs differ +SWEEP shexp gate/up N 640 K 2560 T 6 | f16 0.039 ms 0.51 TFLOPS | f32 0.067 ms 0.30 TFLOPS | 0.58x | DIFFERENT + 3549 of 3840 outputs differ +SWEEP shexp gate/up N 640 K 2560 T 7 | f16 0.038 ms 0.60 TFLOPS | f32 0.067 ms 0.34 TFLOPS | 0.57x | DIFFERENT + 4142 of 4480 outputs differ +SWEEP shexp gate/up N 640 K 2560 T 8 | f16 0.040 ms 0.66 TFLOPS | f32 0.067 ms 0.39 TFLOPS | 0.59x | DIFFERENT + 4739 of 5120 outputs differ +SWEEP shexp gate/up N 640 K 2560 T 9 | f16 0.039 ms 0.76 TFLOPS | f32 0.067 ms 0.44 TFLOPS | 0.58x | DIFFERENT + 5326 of 5760 outputs differ +SWEEP shexp gate/up N 640 K 2560 T 10 | f16 0.039 ms 0.84 TFLOPS | f32 0.067 ms 0.49 TFLOPS | 0.58x | DIFFERENT + 5911 of 6400 outputs differ +SWEEP shexp gate/up N 640 K 2560 T 11 | f16 0.040 ms 0.90 TFLOPS | f32 0.069 ms 0.53 TFLOPS | 0.58x | DIFFERENT + 6501 of 7040 outputs differ +SWEEP shexp gate/up N 640 K 2560 T 12 | f16 0.041 ms 0.97 TFLOPS | f32 0.068 ms 0.58 TFLOPS | 0.60x | DIFFERENT + 7098 of 7680 outputs differ +SWEEP shexp gate/up N 640 K 2560 T 13 | f16 0.040 ms 1.07 TFLOPS | f32 0.069 ms 0.62 TFLOPS | 0.58x | DIFFERENT + 7686 of 8320 outputs differ +SWEEP shexp gate/up N 640 K 2560 T 14 | f16 0.040 ms 1.16 TFLOPS | f32 0.069 ms 0.67 TFLOPS | 0.58x | DIFFERENT + 8278 of 8960 outputs differ +SWEEP shexp gate/up N 640 K 2560 T 15 | f16 0.041 ms 1.20 TFLOPS | f32 0.070 ms 0.71 TFLOPS | 0.59x | DIFFERENT + 8865 of 9600 outputs differ +SWEEP shexp gate/up N 640 K 2560 T 16 | f16 0.045 ms 1.16 TFLOPS | f32 0.069 ms 0.76 TFLOPS | 0.65x | DIFFERENT + 9456 of 10240 outputs differ +SWEEP shexp gate/up N 640 K 2560 T 24 | f16 0.042 ms 1.88 TFLOPS | f32 0.071 ms 1.10 TFLOPS | 0.59x | DIFFERENT + 14140 of 15360 outputs differ +SWEEP shexp gate/up N 640 K 2560 T 48 | f16 0.054 ms 2.90 TFLOPS | f32 0.071 ms 2.20 TFLOPS | 0.76x | DIFFERENT + 28413 of 30720 outputs differ +SWEEP shexp gate/up N 640 K 2560 T 72 | f16 0.066 ms 3.55 TFLOPS | f32 0.073 ms 3.25 TFLOPS | 0.91x | DIFFERENT + 42748 of 46080 outputs differ +SWEEP shexp gate/up N 640 K 2560 T 96 | f16 0.075 ms 4.21 TFLOPS | f32 0.075 ms 4.21 TFLOPS | 1.00x | DIFFERENT + 57019 of 61440 outputs differ +SWEEP shexp gate/up N 640 K 2560 T 120 | f16 0.084 ms 4.70 TFLOPS | f32 0.079 ms 4.99 TFLOPS | 1.06x | DIFFERENT + 71688 of 76800 outputs differ +SWEEP shexp gate/up N 640 K 2560 T 144 | f16 0.124 ms 3.82 TFLOPS | f32 0.135 ms 3.49 TFLOPS | 0.91x | DIFFERENT + 86377 of 92160 outputs differ +SWEEP shexp gate/up N 640 K 2560 T 168 | f16 0.108 ms 5.12 TFLOPS | f32 0.139 ms 3.95 TFLOPS | 0.77x | DIFFERENT + 101128 of 107520 outputs differ +SWEEP shexp gate/up N 640 K 2560 T 192 | f16 0.113 ms 5.59 TFLOPS | f32 0.146 ms 4.31 TFLOPS | 0.77x | DIFFERENT + 115524 of 122880 outputs differ +SWEEP shexp gate/up N 640 K 2560 T 216 | f16 0.153 ms 4.64 TFLOPS | f32 0.143 ms 4.94 TFLOPS | 1.06x | DIFFERENT + 129984 of 138240 outputs differ +SWEEP shexp gate/up N 640 K 2560 T 240 | f16 0.141 ms 5.58 TFLOPS | f32 0.148 ms 5.30 TFLOPS | 0.95x | DIFFERENT + 143519 of 153600 outputs differ +SWEEP shexp gate/up N 640 K 2560 T 264 | f16 0.193 ms 4.47 TFLOPS | f32 0.152 ms 5.71 TFLOPS | 1.28x | DIFFERENT + 158235 of 168960 outputs differ +SWEEP shexp gate/up N 640 K 2560 T 288 | f16 0.194 ms 4.88 TFLOPS | f32 0.154 ms 6.14 TFLOPS | 1.26x | DIFFERENT + 172584 of 184320 outputs differ +SWEEP shexp gate/up N 640 K 2560 T 312 | f16 0.196 ms 5.21 TFLOPS | f32 0.212 ms 4.83 TFLOPS | 0.93x | DIFFERENT + 186928 of 199680 outputs differ +SWEEP shexp gate/up N 640 K 2560 T 336 | f16 0.188 ms 5.84 TFLOPS | f32 0.210 ms 5.24 TFLOPS | 0.90x | DIFFERENT + 202266 of 215040 outputs differ +SWEEP shexp gate/up N 640 K 2560 T 360 | f16 0.186 ms 6.33 TFLOPS | f32 0.215 ms 5.49 TFLOPS | 0.87x | DIFFERENT + 216677 of 230400 outputs differ +SWEEP shexp gate/up N 640 K 2560 T 384 | f16 0.187 ms 6.73 TFLOPS | f32 0.216 ms 5.82 TFLOPS | 0.87x | DIFFERENT + 231156 of 245760 outputs differ +SWEEP shexp gate/up N 640 K 2560 T 408 | f16 0.258 ms 5.18 TFLOPS | f32 0.221 ms 6.05 TFLOPS | 1.17x | DIFFERENT + 243212 of 261120 outputs differ +SWEEP shexp gate/up N 640 K 2560 T 432 | f16 0.262 ms 5.40 TFLOPS | f32 0.233 ms 6.07 TFLOPS | 1.12x | DIFFERENT + 257465 of 276480 outputs differ +SWEEP shexp gate/up N 640 K 2560 T 456 | f16 0.301 ms 4.96 TFLOPS | f32 0.235 ms 6.37 TFLOPS | 1.28x | DIFFERENT + 277137 of 291840 outputs differ +SWEEP shexp gate/up N 640 K 2560 T 480 | f16 0.328 ms 4.80 TFLOPS | f32 0.234 ms 6.71 TFLOPS | 1.40x | DIFFERENT + 291681 of 307200 outputs differ +SWEEP shexp gate/up N 640 K 2560 T 504 | f16 0.333 ms 4.96 TFLOPS | f32 0.234 ms 7.04 TFLOPS | 1.42x | DIFFERENT + 306259 of 322560 outputs differ +SWEEP shexp gate/up N 640 K 2560 T 560 | f16 0.368 ms 4.99 TFLOPS | f32 0.259 ms 7.08 TFLOPS | 1.42x | DIFFERENT + 340279 of 358400 outputs differ +SWEEP shexp gate/up N 640 K 2560 T 813 | f16 0.434 ms 6.14 TFLOPS | f32 0.378 ms 7.05 TFLOPS | 1.15x | DIFFERENT + 494061 of 520320 outputs differ +SWEEP shexp gate/up N 640 K 2560 T 1066 | f16 0.492 ms 7.09 TFLOPS | f32 0.476 ms 7.34 TFLOPS | 1.03x | DIFFERENT + 647873 of 682240 outputs differ +SWEEP shexp gate/up N 640 K 2560 T 1319 | f16 0.618 ms 6.99 TFLOPS | f32 0.594 ms 7.28 TFLOPS | 1.04x | DIFFERENT + 801691 of 844160 outputs differ +SWEEP shexp gate/up N 640 K 2560 T 1572 | f16 0.817 ms 6.30 TFLOPS | f32 0.961 ms 5.36 TFLOPS | 0.85x | bitwise equal +SWEEP shexp gate/up N 640 K 2560 T 1825 | f16 0.870 ms 6.87 TFLOPS | f32 1.047 ms 5.71 TFLOPS | 0.83x | bitwise equal +SWEEP shexp gate/up N 640 K 2560 T 2078 | f16 1.017 ms 6.70 TFLOPS | f32 1.171 ms 5.81 TFLOPS | 0.87x | bitwise equal +SWEEP shexp gate/up N 640 K 2560 T 2331 | f16 0.996 ms 7.67 TFLOPS | f32 1.133 ms 6.74 TFLOPS | 0.88x | bitwise equal +SWEEP shexp gate/up N 640 K 2560 T 2584 | f16 1.124 ms 7.53 TFLOPS | f32 1.159 ms 7.31 TFLOPS | 0.97x | bitwise equal +SWEEP shexp gate/up N 640 K 2560 T 2837 | f16 1.130 ms 8.22 TFLOPS | f32 1.138 ms 8.17 TFLOPS | 0.99x | bitwise equal +SWEEP shexp gate/up N 640 K 2560 T 3090 | f16 1.380 ms 7.34 TFLOPS | f32 1.531 ms 6.61 TFLOPS | 0.90x | bitwise equal +SWEEP shexp gate/up N 640 K 2560 T 3343 | f16 1.450 ms 7.55 TFLOPS | f32 1.585 ms 6.91 TFLOPS | 0.91x | bitwise equal +SWEEP shexp gate/up N 640 K 2560 T 3596 | f16 1.658 ms 7.11 TFLOPS | f32 1.759 ms 6.70 TFLOPS | 0.94x | bitwise equal +SWEEP shexp gate/up N 640 K 2560 T 3849 | f16 1.527 ms 8.26 TFLOPS | f32 1.789 ms 7.05 TFLOPS | 0.85x | bitwise equal +SWEEP shexp gate/up N 640 K 2560 T 4102 | f16 1.645 ms 8.17 TFLOPS | f32 1.736 ms 7.74 TFLOPS | 0.95x | bitwise equal +SWEEP shexp gate/up N 640 K 2560 T 4355 | f16 1.663 ms 8.58 TFLOPS | f32 1.718 ms 8.31 TFLOPS | 0.97x | bitwise equal +SWEEP shexp gate/up N 640 K 2560 T 4608 | f16 1.991 ms 7.59 TFLOPS | f32 1.672 ms 9.03 TFLOPS | 1.19x | bitwise equal +SWEEP shexp gate/up N 640 K 2560 T 4861 | f16 2.251 ms 7.08 TFLOPS | f32 2.152 ms 7.40 TFLOPS | 1.05x | bitwise equal +SWEEP shexp gate/up N 640 K 2560 T 5114 | f16 2.450 ms 6.84 TFLOPS | f32 2.162 ms 7.75 TFLOPS | 1.13x | bitwise equal +SWEEP shexp gate/up N 640 K 2560 T 5367 | f16 2.448 ms 7.18 TFLOPS | f32 2.299 ms 7.65 TFLOPS | 1.07x | bitwise equal +SWEEP shexp gate/up N 640 K 2560 T 5620 | f16 2.290 ms 8.04 TFLOPS | f32 2.310 ms 7.97 TFLOPS | 0.99x | bitwise equal +SWEEP shexp gate/up N 640 K 2560 T 5873 | f16 2.325 ms 8.28 TFLOPS | f32 2.314 ms 8.32 TFLOPS | 1.00x | bitwise equal +SWEEP shexp gate/up N 640 K 2560 T 6126 | f16 2.789 ms 7.20 TFLOPS | f32 2.324 ms 8.64 TFLOPS | 1.20x | bitwise equal +SWEEP shexp gate/up N 640 K 2560 T 6379 | f16 3.036 ms 6.88 TFLOPS | f32 2.695 ms 7.76 TFLOPS | 1.13x | bitwise equal +SWEEP shexp gate/up N 640 K 2560 T 6632 | f16 3.119 ms 6.97 TFLOPS | f32 2.842 ms 7.65 TFLOPS | 1.10x | bitwise equal +SWEEP shexp gate/up N 640 K 2560 T 6885 | f16 3.095 ms 7.29 TFLOPS | f32 2.836 ms 7.95 TFLOPS | 1.09x | bitwise equal +SWEEP shexp gate/up N 640 K 2560 T 7138 | f16 2.832 ms 8.26 TFLOPS | f32 2.843 ms 8.23 TFLOPS | 1.00x | bitwise equal +SWEEP shexp gate/up N 640 K 2560 T 7391 | f16 2.865 ms 8.45 TFLOPS | f32 2.857 ms 8.48 TFLOPS | 1.00x | bitwise equal +SWEEP shexp gate/up N 640 K 2560 T 7644 | f16 3.432 ms 7.30 TFLOPS | f32 2.854 ms 8.78 TFLOPS | 1.20x | bitwise equal +SWEEP shexp gate/up N 640 K 2560 T 7897 | f16 3.737 ms 6.93 TFLOPS | f32 3.212 ms 8.06 TFLOPS | 1.16x | bitwise equal +SWEEP shexp gate/up N 640 K 2560 T 8150 | f16 3.735 ms 7.15 TFLOPS | f32 3.211 ms 8.32 TFLOPS | 1.16x | bitwise equal +SWEEP shexp gate/up N 640 K 2560 T 7030 | f16 2.712 ms 8.50 TFLOPS | f32 3.180 ms 7.25 TFLOPS | 0.85x | bitwise equal +SWEEP shexp gate/up N 640 K 2560 T 7031 | f16 2.696 ms 8.55 TFLOPS | f32 3.185 ms 7.23 TFLOPS | 0.85x | bitwise equal +SWEEP shexp gate/up N 640 K 2560 T 7032 | f16 2.702 ms 8.53 TFLOPS | f32 3.185 ms 7.24 TFLOPS | 0.85x | bitwise equal +SWEEP shexp gate/up N 640 K 2560 T 7033 | f16 2.676 ms 8.61 TFLOPS | f32 3.158 ms 7.30 TFLOPS | 0.85x | bitwise equal +SWEEP shexp gate/up N 640 K 2560 T 7034 | f16 2.678 ms 8.61 TFLOPS | f32 3.188 ms 7.23 TFLOPS | 0.84x | bitwise equal +SWEEP shexp gate/up N 640 K 2560 T 7035 | f16 2.754 ms 8.37 TFLOPS | f32 3.215 ms 7.17 TFLOPS | 0.86x | bitwise equal +SWEEP shexp gate/up N 640 K 2560 T 7036 | f16 2.737 ms 8.42 TFLOPS | f32 3.218 ms 7.16 TFLOPS | 0.85x | bitwise equal +SWEEP shexp gate/up N 640 K 2560 T 7037 | f16 2.742 ms 8.41 TFLOPS | f32 3.190 ms 7.23 TFLOPS | 0.86x | bitwise equal +SWEEP shexp gate/up N 640 K 2560 T 7038 | f16 2.755 ms 8.37 TFLOPS | f32 3.197 ms 7.21 TFLOPS | 0.86x | bitwise equal +SWEEP shexp gate/up N 640 K 2560 T 7039 | f16 2.835 ms 8.13 TFLOPS | f32 3.219 ms 7.16 TFLOPS | 0.88x | bitwise equal +SWEEP shexp gate/up N 640 K 2560 T 7040 | f16 2.690 ms 8.58 TFLOPS | f32 3.213 ms 7.18 TFLOPS | 0.84x | bitwise equal +SWEEP shexp gate/up N 640 K 2560 T 7041 | f16 2.714 ms 8.50 TFLOPS | f32 2.824 ms 8.17 TFLOPS | 0.96x | bitwise equal +SWEEP shexp gate/up N 640 K 2560 T 7042 | f16 2.697 ms 8.56 TFLOPS | f32 2.832 ms 8.15 TFLOPS | 0.95x | bitwise equal +SWEEP shexp gate/up N 640 K 2560 T 7043 | f16 2.786 ms 8.28 TFLOPS | f32 2.907 ms 7.94 TFLOPS | 0.96x | bitwise equal +SWEEP shexp gate/up N 640 K 2560 T 7044 | f16 2.891 ms 7.99 TFLOPS | f32 2.906 ms 7.94 TFLOPS | 0.99x | bitwise equal +SWEEP shexp gate/up N 640 K 2560 T 7045 | f16 2.859 ms 8.07 TFLOPS | f32 2.883 ms 8.01 TFLOPS | 0.99x | bitwise equal +SWEEP shexp gate/up N 640 K 2560 T 7046 | f16 2.883 ms 8.01 TFLOPS | f32 2.911 ms 7.93 TFLOPS | 0.99x | bitwise equal +SWEEP shexp gate/up N 640 K 2560 T 7047 | f16 2.896 ms 7.97 TFLOPS | f32 2.901 ms 7.96 TFLOPS | 1.00x | bitwise equal +SWEEP shexp gate/up N 640 K 2560 T 7048 | f16 2.892 ms 7.99 TFLOPS | f32 2.908 ms 7.94 TFLOPS | 0.99x | bitwise equal +SWEEP shexp gate/up N 640 K 2560 T 7049 | f16 2.755 ms 8.39 TFLOPS | f32 2.876 ms 8.03 TFLOPS | 0.96x | bitwise equal +SWEEP shexp gate/up N 640 K 2560 T 7050 | f16 2.863 ms 8.07 TFLOPS | f32 2.875 ms 8.03 TFLOPS | 1.00x | bitwise equal +SWEEP shexp gate/up N 640 K 2560 T 7051 | f16 2.854 ms 8.10 TFLOPS | f32 2.885 ms 8.01 TFLOPS | 0.99x | bitwise equal +SWEEP shexp gate/up N 640 K 2560 T 7052 | f16 2.783 ms 8.30 TFLOPS | f32 2.912 ms 7.93 TFLOPS | 0.96x | bitwise equal +SWEEP shexp gate/up N 640 K 2560 T 7053 | f16 2.794 ms 8.27 TFLOPS | f32 2.905 ms 7.96 TFLOPS | 0.96x | bitwise equal +SWEEP shexp gate/up N 640 K 2560 T 7054 | f16 2.785 ms 8.30 TFLOPS | f32 2.903 ms 7.96 TFLOPS | 0.96x | bitwise equal +SWEEP shexp gate/up N 640 K 2560 T 7055 | f16 2.882 ms 8.02 TFLOPS | f32 2.913 ms 7.94 TFLOPS | 0.99x | bitwise equal +SWEEP shexp gate/up N 640 K 2560 T 7056 | f16 2.774 ms 8.33 TFLOPS | f32 2.917 ms 7.93 TFLOPS | 0.95x | bitwise equal +SWEEP shexp gate/up N 640 K 2560 T 1024 | f16 0.506 ms 6.64 TFLOPS | f32 0.474 ms 7.08 TFLOPS | 1.07x | DIFFERENT + 622353 of 655360 outputs differ +SWEEP shexp gate/up N 640 K 2560 T 2048 | f16 1.057 ms 6.35 TFLOPS | f32 1.150 ms 5.84 TFLOPS | 0.92x | bitwise equal +SWEEP shexp gate/up N 640 K 2560 T 4096 | f16 1.608 ms 8.35 TFLOPS | f32 1.731 ms 7.76 TFLOPS | 0.93x | bitwise equal +SWEEP shexp gate/up N 640 K 2560 T 8192 | f16 3.806 ms 7.05 TFLOPS | f32 3.279 ms 8.19 TFLOPS | 1.16x | bitwise equal +SWEEP shexp gate/up N 640 K 2560 T 1000 | f16 0.506 ms 6.48 TFLOPS | f32 0.476 ms 6.88 TFLOPS | 1.06x | DIFFERENT + 607813 of 640000 outputs differ +SWEEP shexp gate/up N 640 K 2560 T 3000 | f16 1.180 ms 8.33 TFLOPS | f32 1.178 ms 8.35 TFLOPS | 1.00x | bitwise equal +SWEEP shexp gate/up N 640 K 2560 T 5000 | f16 2.053 ms 7.98 TFLOPS | f32 2.127 ms 7.70 TFLOPS | 0.97x | bitwise equal +SUMMARY shexp gate/up : 60 of 102 T values bitwise equal; f16 below 6 TFLOPS at 10 of the T >= 256; total f16 150 ms, f32 153 ms diff --git a/bench/results/2026-10-12-p40-sm61-kernels/gemm_sweep.cu b/bench/results/2026-10-12-p40-sm61-kernels/gemm_sweep.cu new file mode 100644 index 00000000..38edb244 --- /dev/null +++ b/bench/results/2026-10-12-p40-sm61-kernels/gemm_sweep.cu @@ -0,0 +1,86 @@ +// gemm_sweep.cu - P40: cublasGemmEx (FP16 operands, FP32 sums) against cublasSgemm on FP32 copies, a sweep over T for +// the dense prompt projections' shapes: time of each and whether the two outputs are bitwise equal. +// nvcc -O3 -arch=sm_61 gemm_sweep.cu -o gemm_sweep -lcublas && ./gemm_sweep +#include +#include +#include +#include +#include +#include +#include +#include + +__global__ void fill_f16(__half* p, long n, unsigned seed, float scale) { + long i = (long) blockIdx.x * blockDim.x + threadIdx.x; + if (i >= n) return; + unsigned x = (unsigned) i * 2654435761u + seed; x ^= x >> 16; x *= 2246822519u; x ^= x >> 13; x *= 3266489917u; x ^= x >> 16; + p[i] = __float2half(((float) (x & 0xffff) / 32768.0f - 1.0f) * scale); +} +__global__ void f16_to_f32(const __half* in, float* out, long n) { + long i = (long) blockIdx.x * blockDim.x + threadIdx.x; + if (i < n) out[i] = __half2float(in[i]); +} +__global__ void count_diff(const unsigned* a, const unsigned* b, long n, unsigned* out) { + long i = (long) blockIdx.x * blockDim.x + threadIdx.x; + if (i < n && a[i] != b[i]) atomicAdd(out, 1u); +} +static double ms(cudaEvent_t a, cudaEvent_t b) { float t = 0; cudaEventElapsedTime(&t, a, b); return t; } +#define CK(x) do { auto s_ = (x); if (s_ != 0) { std::fprintf(stderr, "FAIL %s = %d line %d\n", #x, (int) s_, __LINE__); std::exit(1); } } while (0) + +int main() { + setvbuf(stdout, nullptr, _IONBF, 0); + struct Shape { const char* name; long N, K; }; + const Shape shapes[] = {{"gdn qkv", 10240, 2560}, {"gdn gate z", 6144, 2560}, {"qsa q", 12288, 2560}, {"gdn out", 2560, 6144}, {"qsa out", 2560, 4096}, + {"qsa k/v", 512, 2560}, {"shexp gate/up", 640, 2560}}; + std::vector Ts; + for (long t = 1; t <= 16; ++t) Ts.push_back(t); + for (long t = 24; t <= 512; t += 24) Ts.push_back(t); + for (long t = 560; t <= 8192; t += 253) Ts.push_back(t); + for (long t = 7030; t <= 7056; ++t) Ts.push_back(t); + for (long t : {1024L, 2048L, 4096L, 8192L, 1000L, 3000L, 5000L}) Ts.push_back(t); + const long TMAX = 8192; + cublasHandle_t h; CK(cublasCreate(&h)); + cudaStream_t st; CK(cudaStreamCreate(&st)); CK(cublasSetStream(h, st)); + void* ws; CK(cudaMalloc(&ws, 32u << 20)); CK(cublasSetWorkspace(h, ws, 32u << 20)); + cudaEvent_t e0, e1; cudaEventCreate(&e0); cudaEventCreate(&e1); + unsigned* cnt; CK(cudaMalloc(&cnt, 4)); + for (const Shape& s : shapes) { + const long N = s.N, K = s.K; + __half *W16, *X16; float *Wf, *Xf, *Ya, *Yb; + CK(cudaMalloc(&W16, N * K * 2)); CK(cudaMalloc(&X16, TMAX * K * 2)); CK(cudaMalloc(&Wf, N * K * 4)); CK(cudaMalloc(&Xf, TMAX * K * 4)); + CK(cudaMalloc(&Ya, TMAX * N * 4)); CK(cudaMalloc(&Yb, TMAX * N * 4)); + fill_f16<<<(unsigned) ((N * K + 255) / 256), 256, 0, st>>>(W16, N * K, 1u, 0.05f); + fill_f16<<<(unsigned) ((TMAX * K + 255) / 256), 256, 0, st>>>(X16, TMAX * K, 7u, 2.0f); + f16_to_f32<<<(unsigned) ((N * K + 255) / 256), 256, 0, st>>>(W16, Wf, N * K); + f16_to_f32<<<(unsigned) ((TMAX * K + 255) / 256), 256, 0, st>>>(X16, Xf, TMAX * K); + const float one = 1.0f, zero = 0.0f; + int n_equal = 0, n_all = 0, n_slow = 0; + double sum_a = 0, sum_b = 0; + for (long T : Ts) { + double ta = 1e30, tb = 1e30; + for (int r = 0; r < 3; ++r) { + cudaEventRecord(e0, st); + CK(cublasGemmEx(h, CUBLAS_OP_T, CUBLAS_OP_N, (int) N, (int) T, (int) K, &one, W16, CUDA_R_16F, (int) K, X16, CUDA_R_16F, (int) K, + &zero, Ya, CUDA_R_32F, (int) N, CUBLAS_COMPUTE_32F, CUBLAS_GEMM_DEFAULT)); + cudaEventRecord(e1, st); CK(cudaEventSynchronize(e1)); + if (r) ta = fmin(ta, ms(e0, e1)); + cudaEventRecord(e0, st); + CK(cublasSgemm(h, CUBLAS_OP_T, CUBLAS_OP_N, (int) N, (int) T, (int) K, &one, Wf, (int) K, Xf, (int) K, &zero, Yb, (int) N)); + cudaEventRecord(e1, st); CK(cudaEventSynchronize(e1)); + if (r) tb = fmin(tb, ms(e0, e1)); + } + CK(cudaMemsetAsync(cnt, 0, 4, st)); + count_diff<<<(unsigned) ((T * N + 255) / 256), 256, 0, st>>>((const unsigned*) Ya, (const unsigned*) Yb, T * N, cnt); + unsigned nd = 0; CK(cudaMemcpyAsync(&nd, cnt, 4, cudaMemcpyDeviceToHost, st)); CK(cudaStreamSynchronize(st)); + const double fl = 2.0 * N * K * T / 1e12, fa = fl / (ta / 1e3), fb = fl / (tb / 1e3); + ++n_all; n_equal += nd == 0; n_slow += fa < 6.0 && T >= 256; sum_a += ta; sum_b += tb; + std::printf("SWEEP %-14s N %5ld K %5ld T %5ld | f16 %8.3f ms %5.2f TFLOPS | f32 %8.3f ms %5.2f TFLOPS | %5.2fx | %s\n", s.name, N, K, T, ta, fa, tb, + fb, ta / tb, nd == 0 ? "bitwise equal" : "DIFFERENT"); + if (nd) std::printf(" %u of %ld outputs differ\n", nd, T * N); + } + std::printf("SUMMARY %-14s: %d of %d T values bitwise equal; f16 below 6 TFLOPS at %d of the T >= 256; total f16 %.0f ms, f32 %.0f ms\n", s.name, n_equal, + n_all, n_slow, sum_a, sum_b); + cudaFree(W16); cudaFree(X16); cudaFree(Wf); cudaFree(Xf); cudaFree(Ya); cudaFree(Yb); + } + return 0; +} diff --git a/bench/results/2026-10-12-p40-sm61-kernels/mmvq-il-bench-p40-run1.txt b/bench/results/2026-10-12-p40-sm61-kernels/mmvq-il-bench-p40-run1.txt new file mode 100644 index 00000000..b4737bbe --- /dev/null +++ b/bench/results/2026-10-12-p40-sm61-kernels/mmvq-il-bench-p40-run1.txt @@ -0,0 +1,133 @@ +BENCH IQ4_XS 2560x10240 T=1 multi 101.8 us | il rows1 102.9 rows2 62.8 rows4 58.1 us +BENCH IQ4_XS 2560x10240 T=2 multi 111.8 us | il rows1 106.3 rows2 70.1 rows4 65.0 us +BENCH IQ4_XS 2560x10240 T=3 multi 116.6 us | il rows1 112.9 rows2 79.7 rows4 61.8 us +BENCH IQ4_XS 2560x10240 T=4 multi 130.4 us | il rows1 113.0 rows2 74.6 rows4 81.4 us +BENCH IQ4_XS 2560x6144 T=1 multi 62.7 us | il rows1 63.3 rows2 40.5 rows4 36.6 us +BENCH IQ4_XS 2560x6144 T=2 multi 64.0 us | il rows1 64.5 rows2 46.6 rows4 42.9 us +BENCH IQ4_XS 2560x6144 T=3 multi 71.9 us | il rows1 74.4 rows2 52.4 rows4 40.2 us +BENCH IQ4_XS 2560x6144 T=4 multi 82.2 us | il rows1 70.6 rows2 46.7 rows4 50.3 us +BENCH IQ4_XS 6144x2560 T=1 multi 59.3 us | il rows1 58.9 rows2 36.5 rows4 42.5 us +BENCH IQ4_XS 6144x2560 T=2 multi 70.1 us | il rows1 57.6 rows2 44.7 rows4 41.5 us +BENCH IQ4_XS 6144x2560 T=3 multi 70.3 us | il rows1 64.0 rows2 57.1 rows4 35.4 us +BENCH IQ4_XS 6144x2560 T=4 multi 87.3 us | il rows1 67.3 rows2 43.0 rows4 47.8 us +BENCH IQ4_XS 2560x512 T=1 multi 7.8 us | il rows1 7.9 rows2 6.6 rows4 8.1 us +BENCH IQ4_XS 2560x512 T=2 multi 10.4 us | il rows1 7.9 rows2 7.4 rows4 9.0 us +BENCH IQ4_XS 2560x512 T=3 multi 11.2 us | il rows1 9.4 rows2 8.7 rows4 8.4 us +BENCH IQ4_XS 2560x512 T=4 multi 12.0 us | il rows1 8.6 rows2 7.8 rows4 9.4 us +BENCH Q4_K 2560x10240 T=1 multi 58.1 us | il rows1 65.2 rows2 58.6 rows4 60.9 us +BENCH Q4_K 2560x10240 T=2 multi 78.3 us | il rows1 92.5 rows2 74.3 rows4 69.2 us +BENCH Q4_K 2560x10240 T=3 multi 104.1 us | il rows1 89.0 rows2 67.4 rows4 112.3 us +BENCH Q4_K 2560x10240 T=4 multi 125.1 us | il rows1 97.9 rows2 77.3 rows4 116.0 us +BENCH Q4_K 6144x2560 T=1 multi 36.6 us | il rows1 46.3 rows2 47.4 rows4 36.4 us +BENCH Q4_K 6144x2560 T=2 multi 45.2 us | il rows1 58.8 rows2 45.2 rows4 49.0 us +BENCH Q4_K 6144x2560 T=3 multi 56.7 us | il rows1 52.6 rows2 42.3 rows4 83.9 us +BENCH Q4_K 6144x2560 T=4 multi 67.8 us | il rows1 56.3 rows2 48.3 rows4 73.4 us +BENCH Q5_K 2560x12288 T=1 multi 89.9 us | il rows1 94.5 rows2 82.2 rows4 99.2 us +BENCH Q5_K 2560x12288 T=2 multi 108.3 us | il rows1 102.2 rows2 97.5 rows4 88.0 us +BENCH Q5_K 2560x12288 T=3 multi 131.7 us | il rows1 113.5 rows2 91.2 rows4 96.2 us +BENCH Q5_K 2560x12288 T=4 multi 174.8 us | il rows1 157.9 rows2 126.5 rows4 164.1 us +BENCH Q5_K 2560x6144 T=1 multi 47.0 us | il rows1 51.5 rows2 45.9 rows4 57.6 us +BENCH Q5_K 2560x6144 T=2 multi 58.2 us | il rows1 53.4 rows2 52.8 rows4 49.4 us +BENCH Q5_K 2560x6144 T=3 multi 69.3 us | il rows1 59.2 rows2 48.3 rows4 52.5 us +BENCH Q5_K 2560x6144 T=4 multi 91.4 us | il rows1 80.7 rows2 65.3 rows4 98.0 us +BENCH Q5_K 6144x2560 T=1 multi 47.3 us | il rows1 55.3 rows2 56.9 rows4 53.3 us +BENCH Q5_K 6144x2560 T=2 multi 55.7 us | il rows1 56.6 rows2 55.6 rows4 58.3 us +BENCH Q5_K 6144x2560 T=3 multi 64.9 us | il rows1 60.9 rows2 53.6 rows4 55.1 us +BENCH Q5_K 6144x2560 T=4 multi 77.1 us | il rows1 69.9 rows2 64.5 rows4 110.0 us +BENCH Q5_K head 2560x248320 T=1 multi 1754.1 us | il rows1 1786.3 rows2 1506.8 rows4 1737.9 us +BENCH Q5_K head 2560x248320 T=2 multi 2059.9 us | il rows1 1963.3 rows2 1835.9 rows4 1596.7 us +BENCH Q5_K head 2560x248320 T=3 multi 2545.4 us | il rows1 2211.2 rows2 1766.2 rows4 1793.0 us +BENCH Q5_K head 2560x248320 T=4 multi 3370.8 us | il rows1 3099.2 rows2 2435.3 rows4 3350.6 us +BENCH Q6_K 2560x12288 T=1 multi 109.4 us | il rows1 133.8 rows2 128.0 rows4 153.1 us +BENCH Q6_K 2560x12288 T=2 multi 136.4 us | il rows1 158.9 rows2 123.0 rows4 142.9 us +BENCH Q6_K 2560x12288 T=3 multi 162.8 us | il rows1 182.6 rows2 163.0 rows4 121.7 us +BENCH Q6_K 2560x12288 T=4 multi 189.3 us | il rows1 188.0 rows2 127.4 rows4 133.9 us +BENCH Q6_K 2560x10240 T=1 multi 92.6 us | il rows1 114.5 rows2 109.7 rows4 144.3 us +BENCH Q6_K 2560x10240 T=2 multi 114.4 us | il rows1 132.5 rows2 105.1 rows4 119.2 us +BENCH Q6_K 2560x10240 T=3 multi 135.7 us | il rows1 156.3 rows2 136.0 rows4 104.3 us +BENCH Q6_K 2560x10240 T=4 multi 157.8 us | il rows1 161.1 rows2 108.0 rows4 115.1 us +BENCH Q6_K 6144x2560 T=1 multi 57.8 us | il rows1 77.3 rows2 80.8 rows4 88.4 us +BENCH Q6_K 6144x2560 T=2 multi 71.6 us | il rows1 81.5 rows2 69.9 rows4 102.2 us +BENCH Q6_K 6144x2560 T=3 multi 85.8 us | il rows1 98.4 rows2 99.5 rows4 75.7 us +BENCH Q6_K 6144x2560 T=4 multi 98.2 us | il rows1 99.5 rows2 75.3 rows4 70.1 us +BENCH Q6_K 2560x512 T=1 multi 8.4 us | il rows1 10.0 rows2 15.1 rows4 29.2 us +BENCH Q6_K 2560x512 T=2 multi 8.8 us | il rows1 10.1 rows2 13.5 rows4 21.6 us +BENCH Q6_K 2560x512 T=3 multi 11.6 us | il rows1 10.5 rows2 14.7 rows4 15.1 us +BENCH Q6_K 2560x512 T=4 multi 13.4 us | il rows1 10.5 rows2 11.4 rows4 15.7 us +BENCH IQ4_XS 2560x12288 T=1 multi 121.0 us | il rows1 122.2 rows2 73.3 rows4 68.3 us +BENCH IQ4_XS 2560x12288 T=2 multi 122.4 us | il rows1 124.2 rows2 83.9 rows4 75.9 us +BENCH IQ4_XS 2560x12288 T=3 multi 138.0 us | il rows1 143.9 rows2 95.3 rows4 71.5 us +BENCH IQ4_XS 2560x12288 T=4 multi 156.5 us | il rows1 134.7 rows2 87.7 rows4 95.3 us +BENCH IQ4_XS 2560x640 T=1 multi 9.1 us | il rows1 9.2 rows2 7.1 rows4 8.4 us +BENCH IQ4_XS 2560x640 T=2 multi 10.8 us | il rows1 9.3 rows2 7.9 rows4 9.5 us +BENCH IQ4_XS 2560x640 T=3 multi 11.1 us | il rows1 10.5 rows2 9.1 rows4 8.6 us +BENCH IQ4_XS 2560x640 T=4 multi 14.1 us | il rows1 12.9 rows2 8.6 rows4 9.5 us +BENCH Q4_K 2560x6144 T=1 multi 36.7 us | il rows1 41.8 rows2 37.0 rows4 35.9 us +BENCH Q4_K 2560x6144 T=2 multi 50.0 us | il rows1 58.1 rows2 47.2 rows4 45.8 us +BENCH Q4_K 2560x6144 T=3 multi 66.0 us | il rows1 54.8 rows2 42.0 rows4 73.9 us +BENCH Q4_K 2560x6144 T=4 multi 78.8 us | il rows1 60.5 rows2 48.2 rows4 73.7 us +BENCH Q4_K 2560x640 T=1 multi 6.9 us | il rows1 7.6 rows2 9.0 rows4 11.1 us +BENCH Q4_K 2560x640 T=2 multi 9.5 us | il rows1 12.0 rows2 8.0 rows4 10.8 us +BENCH Q4_K 2560x640 T=3 multi 10.1 us | il rows1 9.4 rows2 8.0 rows4 18.0 us +BENCH Q4_K 2560x640 T=4 multi 11.7 us | il rows1 10.4 rows2 9.0 rows4 12.8 us +BENCH Q4_K 2560x512 T=1 multi 6.5 us | il rows1 7.0 rows2 8.5 rows4 10.7 us +BENCH Q4_K 2560x512 T=2 multi 8.9 us | il rows1 7.7 rows2 7.7 rows4 10.5 us +BENCH Q4_K 2560x512 T=3 multi 9.3 us | il rows1 9.1 rows2 8.0 rows4 17.4 us +BENCH Q4_K 2560x512 T=4 multi 10.8 us | il rows1 9.7 rows2 8.9 rows4 12.8 us +BENCH Q5_K 2560x10240 T=1 multi 75.5 us | il rows1 80.1 rows2 70.0 rows4 81.4 us +BENCH Q5_K 2560x10240 T=2 multi 91.4 us | il rows1 86.1 rows2 82.3 rows4 75.1 us +BENCH Q5_K 2560x10240 T=3 multi 111.4 us | il rows1 95.3 rows2 77.6 rows4 82.6 us +BENCH Q5_K 2560x10240 T=4 multi 148.4 us | il rows1 133.3 rows2 106.9 rows4 156.2 us +BENCH Q5_K 2560x640 T=1 multi 7.8 us | il rows1 8.3 rows2 8.5 rows4 15.3 us +BENCH Q5_K 2560x640 T=2 multi 9.7 us | il rows1 9.8 rows2 8.4 rows4 11.7 us +BENCH Q5_K 2560x640 T=3 multi 10.8 us | il rows1 10.0 rows2 8.8 rows4 12.0 us +BENCH Q5_K 2560x640 T=4 multi 14.4 us | il rows1 11.4 rows2 9.7 rows4 18.2 us +BENCH Q5_K 2560x512 T=1 multi 7.2 us | il rows1 7.6 rows2 8.3 rows4 14.7 us +BENCH Q5_K 2560x512 T=2 multi 9.0 us | il rows1 8.9 rows2 8.1 rows4 11.3 us +BENCH Q5_K 2560x512 T=3 multi 9.7 us | il rows1 9.6 rows2 8.5 rows4 11.8 us +BENCH Q5_K 2560x512 T=4 multi 11.0 us | il rows1 10.5 rows2 9.3 rows4 18.3 us +BENCH Q6_K 2560x6144 T=1 multi 57.1 us | il rows1 70.8 rows2 71.6 rows4 78.9 us +BENCH Q6_K 2560x6144 T=2 multi 71.4 us | il rows1 80.9 rows2 63.1 rows4 73.2 us +BENCH Q6_K 2560x6144 T=3 multi 84.2 us | il rows1 95.9 rows2 88.5 rows4 68.4 us +BENCH Q6_K 2560x6144 T=4 multi 96.8 us | il rows1 97.9 rows2 69.8 rows4 72.3 us +BENCH Q6_K 2560x640 T=1 multi 8.8 us | il rows1 10.6 rows2 15.4 rows4 29.9 us +BENCH Q6_K 2560x640 T=2 multi 12.0 us | il rows1 10.8 rows2 13.8 rows4 21.6 us +BENCH Q6_K 2560x640 T=3 multi 13.3 us | il rows1 16.8 rows2 15.4 rows4 15.8 us +BENCH Q6_K 2560x640 T=4 multi 15.7 us | il rows1 17.4 rows2 11.7 rows4 16.1 us +BENCH Q3_K 2560x10240 T=1 multi 93.5 us | il rows1 127.5 rows2 72.2 rows4 131.6 us +BENCH Q3_K 2560x10240 T=2 multi 110.0 us | il rows1 102.9 rows2 90.4 rows4 109.5 us +BENCH Q3_K 2560x10240 T=3 multi 152.5 us | il rows1 119.9 rows2 107.7 rows4 117.9 us +BENCH Q3_K 2560x10240 T=4 multi 217.6 us | il rows1 134.8 rows2 163.3 rows4 177.0 us +BENCH Q3_K 2560x12288 T=1 multi 111.5 us | il rows1 151.7 rows2 85.7 rows4 150.4 us +BENCH Q3_K 2560x12288 T=2 multi 131.1 us | il rows1 122.4 rows2 107.3 rows4 127.8 us +BENCH Q3_K 2560x12288 T=3 multi 183.5 us | il rows1 145.1 rows2 130.3 rows4 141.1 us +BENCH Q3_K 2560x12288 T=4 multi 262.4 us | il rows1 163.3 rows2 195.4 rows4 217.0 us +BENCH Q3_K 2560x6144 T=1 multi 57.7 us | il rows1 77.9 rows2 46.2 rows4 83.7 us +BENCH Q3_K 2560x6144 T=2 multi 68.4 us | il rows1 63.4 rows2 56.4 rows4 67.1 us +BENCH Q3_K 2560x6144 T=3 multi 94.7 us | il rows1 74.7 rows2 67.1 rows4 75.0 us +BENCH Q3_K 2560x6144 T=4 multi 133.4 us | il rows1 83.3 rows2 100.7 rows4 117.5 us +BENCH Q3_K 6144x2560 T=1 multi 46.3 us | il rows1 78.0 rows2 44.9 rows4 74.8 us +BENCH Q3_K 6144x2560 T=2 multi 60.6 us | il rows1 63.0 rows2 56.2 rows4 65.7 us +BENCH Q3_K 6144x2560 T=3 multi 77.2 us | il rows1 75.5 rows2 63.7 rows4 70.6 us +BENCH Q3_K 6144x2560 T=4 multi 99.1 us | il rows1 79.7 rows2 98.3 rows4 113.1 us +BENCH Q3_K 2560x640 T=1 multi 8.9 us | il rows1 10.3 rows2 8.1 rows4 16.9 us +BENCH Q3_K 2560x640 T=2 multi 10.8 us | il rows1 10.7 rows2 8.6 rows4 12.0 us +BENCH Q3_K 2560x640 T=3 multi 14.8 us | il rows1 11.7 rows2 9.5 rows4 12.3 us +BENCH Q3_K 2560x640 T=4 multi 17.1 us | il rows1 13.5 rows2 12.9 rows4 18.0 us +BENCH Q3_K 2560x512 T=1 multi 7.7 us | il rows1 9.5 rows2 7.7 rows4 16.3 us +BENCH Q3_K 2560x512 T=2 multi 9.7 us | il rows1 10.1 rows2 8.6 rows4 11.8 us +BENCH Q3_K 2560x512 T=3 multi 11.3 us | il rows1 11.1 rows2 9.3 rows4 12.3 us +BENCH Q3_K 2560x512 T=4 multi 16.1 us | il rows1 12.3 rows2 12.7 rows4 18.1 us +// measured on this card by mmvq_il_parity --bench --emit-table + {23, {{2, 4, 4, 4, 4}, {4, 4, 4, 4, 4}, {2, 2, 2, 2, 2}}}, // IQ4_XS + {12, {{2, 0, 4, 4, 4}, {2, 2, 2, 2, 2}, {2, 2, 2, 2, 2}}}, // Q4_K + {13, {{2, 0, 4, 4, 4}, {2, 2, 2, 2, 2}, {2, 2, 2, 2, 2}}}, // Q5_K + {14, {{0, 0, 2, 2, 2}, {0, 4, 4, 4, 4}, {2, 4, 2, 2, 2}}}, // Q6_K + {11, {{2, 2, 2, 2, 2}, {2, 2, 2, 2, 2}, {1, 1, 1, 1, 1}}}, // Q3_K +// one column (kIl1RowsShared): + {23, {2, 2, 4, 4, 4}}, // IQ4_XS + {12, {0, 0, 0, 0, 0}}, // Q4_K + {13, {0, 0, 0, 2, 2}}, // Q5_K + {14, {0, 0, 0, 0, 0}}, // Q6_K + {11, {0, 2, 2, 2, 2}}, // Q3_K +mmvq_il_parity: OK (every case, T 1-4, rows 1/2/4 and the table, bitwise) diff --git a/bench/results/2026-10-12-p40-sm61-kernels/mmvq-il-bench-p40-run2.txt b/bench/results/2026-10-12-p40-sm61-kernels/mmvq-il-bench-p40-run2.txt new file mode 100644 index 00000000..fd662f66 --- /dev/null +++ b/bench/results/2026-10-12-p40-sm61-kernels/mmvq-il-bench-p40-run2.txt @@ -0,0 +1,133 @@ +BENCH IQ4_XS 2560x10240 T=1 multi 112.0 us | il rows1 120.8 rows2 68.9 rows4 59.6 us +BENCH IQ4_XS 2560x10240 T=2 multi 112.5 us | il rows1 115.8 rows2 75.4 rows4 65.2 us +BENCH IQ4_XS 2560x10240 T=3 multi 116.3 us | il rows1 112.8 rows2 79.7 rows4 61.8 us +BENCH IQ4_XS 2560x10240 T=4 multi 130.3 us | il rows1 112.6 rows2 74.2 rows4 81.3 us +BENCH IQ4_XS 2560x6144 T=1 multi 62.6 us | il rows1 63.2 rows2 40.3 rows4 36.6 us +BENCH IQ4_XS 2560x6144 T=2 multi 63.9 us | il rows1 64.3 rows2 46.5 rows4 42.9 us +BENCH IQ4_XS 2560x6144 T=3 multi 71.8 us | il rows1 74.3 rows2 52.2 rows4 40.2 us +BENCH IQ4_XS 2560x6144 T=4 multi 82.0 us | il rows1 70.4 rows2 46.5 rows4 50.2 us +BENCH IQ4_XS 6144x2560 T=1 multi 59.2 us | il rows1 58.8 rows2 36.4 rows4 42.5 us +BENCH IQ4_XS 6144x2560 T=2 multi 70.1 us | il rows1 57.5 rows2 44.7 rows4 41.5 us +BENCH IQ4_XS 6144x2560 T=3 multi 70.3 us | il rows1 63.9 rows2 57.3 rows4 35.3 us +BENCH IQ4_XS 6144x2560 T=4 multi 87.1 us | il rows1 67.3 rows2 43.0 rows4 48.3 us +BENCH IQ4_XS 2560x512 T=1 multi 7.7 us | il rows1 8.0 rows2 6.7 rows4 7.9 us +BENCH IQ4_XS 2560x512 T=2 multi 10.4 us | il rows1 8.0 rows2 7.5 rows4 9.1 us +BENCH IQ4_XS 2560x512 T=3 multi 11.2 us | il rows1 9.4 rows2 9.0 rows4 8.4 us +BENCH IQ4_XS 2560x512 T=4 multi 11.9 us | il rows1 8.6 rows2 8.0 rows4 9.3 us +BENCH Q4_K 2560x10240 T=1 multi 58.1 us | il rows1 65.1 rows2 58.6 rows4 60.9 us +BENCH Q4_K 2560x10240 T=2 multi 78.7 us | il rows1 92.6 rows2 74.3 rows4 69.1 us +BENCH Q4_K 2560x10240 T=3 multi 104.1 us | il rows1 89.0 rows2 67.3 rows4 112.3 us +BENCH Q4_K 2560x10240 T=4 multi 125.1 us | il rows1 97.9 rows2 77.3 rows4 116.1 us +BENCH Q4_K 6144x2560 T=1 multi 36.7 us | il rows1 46.5 rows2 47.4 rows4 36.4 us +BENCH Q4_K 6144x2560 T=2 multi 45.1 us | il rows1 58.8 rows2 45.2 rows4 49.1 us +BENCH Q4_K 6144x2560 T=3 multi 56.7 us | il rows1 52.5 rows2 42.2 rows4 83.8 us +BENCH Q4_K 6144x2560 T=4 multi 67.7 us | il rows1 56.3 rows2 48.1 rows4 73.2 us +BENCH Q5_K 2560x12288 T=1 multi 89.9 us | il rows1 94.5 rows2 82.2 rows4 99.2 us +BENCH Q5_K 2560x12288 T=2 multi 108.3 us | il rows1 102.0 rows2 97.5 rows4 87.9 us +BENCH Q5_K 2560x12288 T=3 multi 130.2 us | il rows1 113.2 rows2 90.4 rows4 95.0 us +BENCH Q5_K 2560x12288 T=4 multi 174.3 us | il rows1 157.2 rows2 125.1 rows4 164.2 us +BENCH Q5_K 2560x6144 T=1 multi 47.1 us | il rows1 51.2 rows2 45.9 rows4 57.5 us +BENCH Q5_K 2560x6144 T=2 multi 58.1 us | il rows1 53.1 rows2 52.6 rows4 49.5 us +BENCH Q5_K 2560x6144 T=3 multi 69.2 us | il rows1 58.8 rows2 48.1 rows4 52.4 us +BENCH Q5_K 2560x6144 T=4 multi 91.3 us | il rows1 80.6 rows2 65.2 rows4 97.8 us +BENCH Q5_K 6144x2560 T=1 multi 47.3 us | il rows1 55.3 rows2 56.8 rows4 53.2 us +BENCH Q5_K 6144x2560 T=2 multi 55.6 us | il rows1 56.6 rows2 55.6 rows4 58.4 us +BENCH Q5_K 6144x2560 T=3 multi 64.8 us | il rows1 60.8 rows2 53.6 rows4 55.0 us +BENCH Q5_K 6144x2560 T=4 multi 76.9 us | il rows1 69.9 rows2 64.4 rows4 110.5 us +BENCH Q5_K head 2560x248320 T=1 multi 1745.4 us | il rows1 1783.3 rows2 1506.2 rows4 1736.8 us +BENCH Q5_K head 2560x248320 T=2 multi 2023.5 us | il rows1 1963.3 rows2 1840.0 rows4 1597.1 us +BENCH Q5_K head 2560x248320 T=3 multi 2501.6 us | il rows1 2198.1 rows2 1739.9 rows4 1792.7 us +BENCH Q5_K head 2560x248320 T=4 multi 3364.4 us | il rows1 3092.4 rows2 2429.2 rows4 3339.7 us +BENCH Q6_K 2560x12288 T=1 multi 109.2 us | il rows1 133.8 rows2 127.9 rows4 153.0 us +BENCH Q6_K 2560x12288 T=2 multi 136.0 us | il rows1 157.0 rows2 122.0 rows4 142.0 us +BENCH Q6_K 2560x12288 T=3 multi 161.1 us | il rows1 182.3 rows2 162.8 rows4 121.5 us +BENCH Q6_K 2560x12288 T=4 multi 186.2 us | il rows1 185.6 rows2 126.5 rows4 132.8 us +BENCH Q6_K 2560x10240 T=1 multi 91.8 us | il rows1 113.3 rows2 109.0 rows4 143.6 us +BENCH Q6_K 2560x10240 T=2 multi 114.3 us | il rows1 132.2 rows2 104.8 rows4 119.1 us +BENCH Q6_K 2560x10240 T=3 multi 135.0 us | il rows1 154.1 rows2 134.9 rows4 103.8 us +BENCH Q6_K 2560x10240 T=4 multi 156.5 us | il rows1 157.3 rows2 105.8 rows4 113.3 us +BENCH Q6_K 6144x2560 T=1 multi 57.8 us | il rows1 76.9 rows2 80.8 rows4 88.4 us +BENCH Q6_K 6144x2560 T=2 multi 71.5 us | il rows1 81.3 rows2 69.8 rows4 102.1 us +BENCH Q6_K 6144x2560 T=3 multi 85.6 us | il rows1 98.2 rows2 99.4 rows4 75.5 us +BENCH Q6_K 6144x2560 T=4 multi 98.3 us | il rows1 99.4 rows2 75.1 rows4 70.1 us +BENCH Q6_K 2560x512 T=1 multi 8.4 us | il rows1 9.9 rows2 15.0 rows4 29.2 us +BENCH Q6_K 2560x512 T=2 multi 8.8 us | il rows1 10.1 rows2 13.5 rows4 21.6 us +BENCH Q6_K 2560x512 T=3 multi 11.7 us | il rows1 10.4 rows2 14.7 rows4 15.1 us +BENCH Q6_K 2560x512 T=4 multi 13.4 us | il rows1 10.5 rows2 11.4 rows4 15.8 us +BENCH IQ4_XS 2560x12288 T=1 multi 121.1 us | il rows1 122.2 rows2 73.3 rows4 68.2 us +BENCH IQ4_XS 2560x12288 T=2 multi 122.4 us | il rows1 124.2 rows2 83.9 rows4 75.9 us +BENCH IQ4_XS 2560x12288 T=3 multi 138.0 us | il rows1 143.9 rows2 95.2 rows4 71.5 us +BENCH IQ4_XS 2560x12288 T=4 multi 156.6 us | il rows1 134.7 rows2 87.6 rows4 95.2 us +BENCH IQ4_XS 2560x640 T=1 multi 9.2 us | il rows1 9.3 rows2 7.5 rows4 8.5 us +BENCH IQ4_XS 2560x640 T=2 multi 10.8 us | il rows1 9.3 rows2 8.1 rows4 9.4 us +BENCH IQ4_XS 2560x640 T=3 multi 11.2 us | il rows1 10.4 rows2 9.1 rows4 8.6 us +BENCH IQ4_XS 2560x640 T=4 multi 14.1 us | il rows1 12.9 rows2 8.5 rows4 9.5 us +BENCH Q4_K 2560x6144 T=1 multi 36.8 us | il rows1 41.9 rows2 37.0 rows4 35.9 us +BENCH Q4_K 2560x6144 T=2 multi 50.0 us | il rows1 58.2 rows2 47.3 rows4 45.8 us +BENCH Q4_K 2560x6144 T=3 multi 66.1 us | il rows1 54.8 rows2 41.8 rows4 73.9 us +BENCH Q4_K 2560x6144 T=4 multi 78.7 us | il rows1 60.5 rows2 48.2 rows4 73.8 us +BENCH Q4_K 2560x640 T=1 multi 7.1 us | il rows1 7.9 rows2 8.9 rows4 11.1 us +BENCH Q4_K 2560x640 T=2 multi 9.5 us | il rows1 12.0 rows2 8.1 rows4 10.9 us +BENCH Q4_K 2560x640 T=3 multi 10.1 us | il rows1 9.3 rows2 8.0 rows4 18.1 us +BENCH Q4_K 2560x640 T=4 multi 11.7 us | il rows1 10.5 rows2 9.2 rows4 12.8 us +BENCH Q4_K 2560x512 T=1 multi 6.6 us | il rows1 6.9 rows2 8.7 rows4 10.9 us +BENCH Q4_K 2560x512 T=2 multi 9.0 us | il rows1 7.8 rows2 7.7 rows4 10.5 us +BENCH Q4_K 2560x512 T=3 multi 9.5 us | il rows1 8.9 rows2 8.1 rows4 17.4 us +BENCH Q4_K 2560x512 T=4 multi 10.9 us | il rows1 9.7 rows2 8.8 rows4 12.8 us +BENCH Q5_K 2560x10240 T=1 multi 75.4 us | il rows1 80.1 rows2 70.1 rows4 81.4 us +BENCH Q5_K 2560x10240 T=2 multi 91.3 us | il rows1 86.0 rows2 82.4 rows4 75.0 us +BENCH Q5_K 2560x10240 T=3 multi 109.6 us | il rows1 95.2 rows2 76.3 rows4 81.4 us +BENCH Q5_K 2560x10240 T=4 multi 146.8 us | il rows1 131.0 rows2 105.2 rows4 155.1 us +BENCH Q5_K 2560x640 T=1 multi 7.8 us | il rows1 8.4 rows2 8.5 rows4 15.2 us +BENCH Q5_K 2560x640 T=2 multi 9.7 us | il rows1 9.7 rows2 8.4 rows4 11.7 us +BENCH Q5_K 2560x640 T=3 multi 10.6 us | il rows1 10.0 rows2 8.7 rows4 12.0 us +BENCH Q5_K 2560x640 T=4 multi 14.4 us | il rows1 11.4 rows2 9.7 rows4 18.2 us +BENCH Q5_K 2560x512 T=1 multi 6.9 us | il rows1 7.8 rows2 8.2 rows4 14.8 us +BENCH Q5_K 2560x512 T=2 multi 9.1 us | il rows1 8.8 rows2 8.2 rows4 11.4 us +BENCH Q5_K 2560x512 T=3 multi 9.8 us | il rows1 9.4 rows2 8.6 rows4 11.8 us +BENCH Q5_K 2560x512 T=4 multi 11.1 us | il rows1 10.6 rows2 9.5 rows4 18.2 us +BENCH Q6_K 2560x6144 T=1 multi 57.0 us | il rows1 70.7 rows2 71.6 rows4 78.8 us +BENCH Q6_K 2560x6144 T=2 multi 71.3 us | il rows1 80.8 rows2 63.0 rows4 73.1 us +BENCH Q6_K 2560x6144 T=3 multi 84.1 us | il rows1 95.8 rows2 88.4 rows4 68.3 us +BENCH Q6_K 2560x6144 T=4 multi 96.7 us | il rows1 97.7 rows2 68.6 rows4 72.1 us +BENCH Q6_K 2560x640 T=1 multi 8.9 us | il rows1 10.7 rows2 15.4 rows4 29.9 us +BENCH Q6_K 2560x640 T=2 multi 12.0 us | il rows1 10.7 rows2 13.8 rows4 21.6 us +BENCH Q6_K 2560x640 T=3 multi 13.3 us | il rows1 16.7 rows2 15.3 rows4 15.8 us +BENCH Q6_K 2560x640 T=4 multi 15.6 us | il rows1 17.4 rows2 11.7 rows4 16.1 us +BENCH Q3_K 2560x10240 T=1 multi 93.5 us | il rows1 127.5 rows2 72.3 rows4 131.6 us +BENCH Q3_K 2560x10240 T=2 multi 110.0 us | il rows1 103.0 rows2 91.3 rows4 109.5 us +BENCH Q3_K 2560x10240 T=3 multi 152.5 us | il rows1 119.4 rows2 108.0 rows4 118.5 us +BENCH Q3_K 2560x10240 T=4 multi 218.1 us | il rows1 134.8 rows2 163.3 rows4 177.3 us +BENCH Q3_K 2560x12288 T=1 multi 111.5 us | il rows1 151.8 rows2 85.8 rows4 150.4 us +BENCH Q3_K 2560x12288 T=2 multi 131.2 us | il rows1 122.4 rows2 108.2 rows4 127.8 us +BENCH Q3_K 2560x12288 T=3 multi 181.9 us | il rows1 141.9 rows2 129.3 rows4 140.3 us +BENCH Q3_K 2560x12288 T=4 multi 261.2 us | il rows1 161.3 rows2 194.4 rows4 216.2 us +BENCH Q3_K 2560x6144 T=1 multi 57.5 us | il rows1 77.7 rows2 46.0 rows4 83.6 us +BENCH Q3_K 2560x6144 T=2 multi 68.1 us | il rows1 63.3 rows2 56.5 rows4 66.8 us +BENCH Q3_K 2560x6144 T=3 multi 94.3 us | il rows1 73.8 rows2 67.0 rows4 75.2 us +BENCH Q3_K 2560x6144 T=4 multi 132.8 us | il rows1 83.1 rows2 100.4 rows4 117.1 us +BENCH Q3_K 6144x2560 T=1 multi 46.2 us | il rows1 77.7 rows2 44.7 rows4 74.7 us +BENCH Q3_K 6144x2560 T=2 multi 60.5 us | il rows1 62.6 rows2 56.6 rows4 65.4 us +BENCH Q3_K 6144x2560 T=3 multi 77.0 us | il rows1 75.3 rows2 63.8 rows4 70.4 us +BENCH Q3_K 6144x2560 T=4 multi 99.0 us | il rows1 79.5 rows2 98.2 rows4 113.0 us +BENCH Q3_K 2560x640 T=1 multi 8.8 us | il rows1 10.4 rows2 7.9 rows4 17.0 us +BENCH Q3_K 2560x640 T=2 multi 11.0 us | il rows1 10.7 rows2 8.7 rows4 11.8 us +BENCH Q3_K 2560x640 T=3 multi 14.8 us | il rows1 11.7 rows2 9.3 rows4 12.2 us +BENCH Q3_K 2560x640 T=4 multi 17.1 us | il rows1 13.4 rows2 12.8 rows4 17.9 us +BENCH Q3_K 2560x512 T=1 multi 7.6 us | il rows1 9.6 rows2 7.6 rows4 16.2 us +BENCH Q3_K 2560x512 T=2 multi 9.9 us | il rows1 9.9 rows2 8.6 rows4 11.6 us +BENCH Q3_K 2560x512 T=3 multi 11.4 us | il rows1 11.2 rows2 9.3 rows4 12.3 us +BENCH Q3_K 2560x512 T=4 multi 16.1 us | il rows1 12.3 rows2 12.8 rows4 18.0 us +// measured on this card by mmvq_il_parity --bench --emit-table + {23, {{2, 4, 4, 4, 4}, {4, 4, 4, 4, 4}, {2, 2, 2, 2, 2}}}, // IQ4_XS + {12, {{2, 0, 4, 4, 4}, {2, 2, 2, 2, 2}, {2, 2, 2, 2, 2}}}, // Q4_K + {13, {{2, 0, 4, 4, 4}, {2, 2, 2, 2, 2}, {2, 2, 2, 2, 2}}}, // Q5_K + {14, {{0, 0, 2, 2, 2}, {0, 4, 4, 4, 4}, {2, 4, 2, 2, 2}}}, // Q6_K + {11, {{2, 2, 2, 2, 2}, {2, 2, 2, 2, 2}, {1, 1, 1, 1, 1}}}, // Q3_K +// one column (kIl1RowsShared): + {23, {2, 2, 4, 4, 4}}, // IQ4_XS + {12, {0, 0, 0, 0, 0}}, // Q4_K + {13, {0, 0, 0, 2, 2}}, // Q5_K + {14, {0, 0, 0, 0, 0}}, // Q6_K + {11, {0, 2, 2, 2, 2}}, // Q3_K +mmvq_il_parity: OK (every case, T 1-4, rows 1/2/4 and the table, bitwise) diff --git a/bench/results/2026-10-12-p40-sm61-kernels/mmvq-il-bench-p40-run3.txt b/bench/results/2026-10-12-p40-sm61-kernels/mmvq-il-bench-p40-run3.txt new file mode 100644 index 00000000..f06d7c3c --- /dev/null +++ b/bench/results/2026-10-12-p40-sm61-kernels/mmvq-il-bench-p40-run3.txt @@ -0,0 +1,133 @@ +BENCH IQ4_XS 2560x10240 T=1 multi 101.6 us | il rows1 102.9 rows2 62.8 rows4 58.2 us +BENCH IQ4_XS 2560x10240 T=2 multi 111.8 us | il rows1 107.4 rows2 70.3 rows4 65.0 us +BENCH IQ4_XS 2560x10240 T=3 multi 116.4 us | il rows1 112.7 rows2 79.6 rows4 61.8 us +BENCH IQ4_XS 2560x10240 T=4 multi 131.4 us | il rows1 112.1 rows2 74.2 rows4 81.4 us +BENCH IQ4_XS 2560x6144 T=1 multi 62.6 us | il rows1 63.3 rows2 40.4 rows4 36.6 us +BENCH IQ4_XS 2560x6144 T=2 multi 63.9 us | il rows1 64.9 rows2 46.5 rows4 42.9 us +BENCH IQ4_XS 2560x6144 T=3 multi 72.1 us | il rows1 74.3 rows2 52.2 rows4 40.2 us +BENCH IQ4_XS 2560x6144 T=4 multi 82.6 us | il rows1 69.3 rows2 46.5 rows4 50.2 us +BENCH IQ4_XS 6144x2560 T=1 multi 59.2 us | il rows1 58.6 rows2 36.3 rows4 42.5 us +BENCH IQ4_XS 6144x2560 T=2 multi 70.0 us | il rows1 57.5 rows2 44.6 rows4 41.5 us +BENCH IQ4_XS 6144x2560 T=3 multi 70.0 us | il rows1 63.9 rows2 57.3 rows4 35.4 us +BENCH IQ4_XS 6144x2560 T=4 multi 86.9 us | il rows1 67.2 rows2 42.9 rows4 49.6 us +BENCH IQ4_XS 2560x512 T=1 multi 7.9 us | il rows1 7.9 rows2 6.7 rows4 8.0 us +BENCH IQ4_XS 2560x512 T=2 multi 10.3 us | il rows1 7.9 rows2 7.4 rows4 9.0 us +BENCH IQ4_XS 2560x512 T=3 multi 11.2 us | il rows1 9.3 rows2 8.8 rows4 8.5 us +BENCH IQ4_XS 2560x512 T=4 multi 12.0 us | il rows1 8.6 rows2 7.8 rows4 9.4 us +BENCH Q4_K 2560x10240 T=1 multi 58.1 us | il rows1 65.1 rows2 58.6 rows4 60.8 us +BENCH Q4_K 2560x10240 T=2 multi 78.6 us | il rows1 92.5 rows2 74.2 rows4 69.0 us +BENCH Q4_K 2560x10240 T=3 multi 104.1 us | il rows1 88.9 rows2 67.1 rows4 112.3 us +BENCH Q4_K 2560x10240 T=4 multi 124.9 us | il rows1 97.8 rows2 77.1 rows4 115.8 us +BENCH Q4_K 6144x2560 T=1 multi 36.6 us | il rows1 46.4 rows2 47.3 rows4 36.5 us +BENCH Q4_K 6144x2560 T=2 multi 45.2 us | il rows1 58.7 rows2 45.1 rows4 49.1 us +BENCH Q4_K 6144x2560 T=3 multi 56.7 us | il rows1 52.6 rows2 42.2 rows4 83.7 us +BENCH Q4_K 6144x2560 T=4 multi 67.7 us | il rows1 56.2 rows2 48.2 rows4 73.2 us +BENCH Q5_K 2560x12288 T=1 multi 90.3 us | il rows1 94.6 rows2 82.2 rows4 99.2 us +BENCH Q5_K 2560x12288 T=2 multi 109.2 us | il rows1 102.0 rows2 97.5 rows4 88.0 us +BENCH Q5_K 2560x12288 T=3 multi 131.3 us | il rows1 113.2 rows2 90.4 rows4 95.0 us +BENCH Q5_K 2560x12288 T=4 multi 174.4 us | il rows1 157.1 rows2 125.1 rows4 164.8 us +BENCH Q5_K 2560x6144 T=1 multi 47.1 us | il rows1 51.3 rows2 45.8 rows4 57.5 us +BENCH Q5_K 2560x6144 T=2 multi 58.1 us | il rows1 53.1 rows2 52.6 rows4 49.4 us +BENCH Q5_K 2560x6144 T=3 multi 69.2 us | il rows1 58.9 rows2 48.2 rows4 52.4 us +BENCH Q5_K 2560x6144 T=4 multi 91.3 us | il rows1 80.6 rows2 65.2 rows4 97.7 us +BENCH Q5_K 6144x2560 T=1 multi 47.4 us | il rows1 55.2 rows2 56.8 rows4 53.3 us +BENCH Q5_K 6144x2560 T=2 multi 55.7 us | il rows1 56.6 rows2 55.5 rows4 58.3 us +BENCH Q5_K 6144x2560 T=3 multi 64.8 us | il rows1 60.8 rows2 53.5 rows4 55.0 us +BENCH Q5_K 6144x2560 T=4 multi 76.9 us | il rows1 69.9 rows2 64.5 rows4 110.6 us +BENCH Q5_K head 2560x248320 T=1 multi 1754.4 us | il rows1 1787.3 rows2 1506.6 rows4 1737.1 us +BENCH Q5_K head 2560x248320 T=2 multi 2039.4 us | il rows1 1965.4 rows2 1840.6 rows4 1597.2 us +BENCH Q5_K head 2560x248320 T=3 multi 2535.5 us | il rows1 2199.1 rows2 1750.6 rows4 1791.4 us +BENCH Q5_K head 2560x248320 T=4 multi 3362.7 us | il rows1 3087.3 rows2 2424.5 rows4 3342.0 us +BENCH Q6_K 2560x12288 T=1 multi 109.4 us | il rows1 133.4 rows2 127.8 rows4 152.9 us +BENCH Q6_K 2560x12288 T=2 multi 136.1 us | il rows1 157.1 rows2 122.1 rows4 142.0 us +BENCH Q6_K 2560x12288 T=3 multi 161.3 us | il rows1 182.2 rows2 162.6 rows4 121.5 us +BENCH Q6_K 2560x12288 T=4 multi 186.1 us | il rows1 185.7 rows2 126.5 rows4 132.9 us +BENCH Q6_K 2560x10240 T=1 multi 92.0 us | il rows1 114.3 rows2 109.8 rows4 144.3 us +BENCH Q6_K 2560x10240 T=2 multi 114.3 us | il rows1 132.4 rows2 104.9 rows4 119.1 us +BENCH Q6_K 2560x10240 T=3 multi 135.0 us | il rows1 154.2 rows2 135.0 rows4 103.8 us +BENCH Q6_K 2560x10240 T=4 multi 156.7 us | il rows1 157.3 rows2 105.9 rows4 113.3 us +BENCH Q6_K 6144x2560 T=1 multi 57.8 us | il rows1 76.9 rows2 80.7 rows4 88.3 us +BENCH Q6_K 6144x2560 T=2 multi 71.5 us | il rows1 81.4 rows2 69.9 rows4 102.1 us +BENCH Q6_K 6144x2560 T=3 multi 85.6 us | il rows1 98.3 rows2 99.4 rows4 75.6 us +BENCH Q6_K 6144x2560 T=4 multi 98.2 us | il rows1 99.3 rows2 75.1 rows4 70.1 us +BENCH Q6_K 2560x512 T=1 multi 8.3 us | il rows1 9.9 rows2 15.0 rows4 29.2 us +BENCH Q6_K 2560x512 T=2 multi 9.0 us | il rows1 10.2 rows2 13.4 rows4 21.6 us +BENCH Q6_K 2560x512 T=3 multi 11.7 us | il rows1 10.6 rows2 14.7 rows4 15.3 us +BENCH Q6_K 2560x512 T=4 multi 13.4 us | il rows1 10.6 rows2 11.2 rows4 15.7 us +BENCH IQ4_XS 2560x12288 T=1 multi 121.0 us | il rows1 122.2 rows2 73.2 rows4 68.2 us +BENCH IQ4_XS 2560x12288 T=2 multi 122.3 us | il rows1 125.5 rows2 83.9 rows4 75.9 us +BENCH IQ4_XS 2560x12288 T=3 multi 138.5 us | il rows1 143.9 rows2 95.2 rows4 71.5 us +BENCH IQ4_XS 2560x12288 T=4 multi 157.7 us | il rows1 132.5 rows2 87.5 rows4 95.2 us +BENCH IQ4_XS 2560x640 T=1 multi 9.1 us | il rows1 9.2 rows2 7.1 rows4 8.3 us +BENCH IQ4_XS 2560x640 T=2 multi 10.7 us | il rows1 9.2 rows2 7.9 rows4 9.6 us +BENCH IQ4_XS 2560x640 T=3 multi 11.2 us | il rows1 10.5 rows2 9.2 rows4 8.6 us +BENCH IQ4_XS 2560x640 T=4 multi 14.2 us | il rows1 12.9 rows2 8.4 rows4 9.5 us +BENCH Q4_K 2560x6144 T=1 multi 36.7 us | il rows1 41.8 rows2 37.0 rows4 35.8 us +BENCH Q4_K 2560x6144 T=2 multi 50.1 us | il rows1 58.2 rows2 47.2 rows4 45.7 us +BENCH Q4_K 2560x6144 T=3 multi 66.0 us | il rows1 54.8 rows2 41.8 rows4 73.9 us +BENCH Q4_K 2560x6144 T=4 multi 78.8 us | il rows1 60.4 rows2 48.1 rows4 73.6 us +BENCH Q4_K 2560x640 T=1 multi 6.9 us | il rows1 7.8 rows2 8.8 rows4 11.0 us +BENCH Q4_K 2560x640 T=2 multi 9.3 us | il rows1 12.0 rows2 8.0 rows4 10.8 us +BENCH Q4_K 2560x640 T=3 multi 10.1 us | il rows1 9.3 rows2 7.9 rows4 18.1 us +BENCH Q4_K 2560x640 T=4 multi 11.6 us | il rows1 10.4 rows2 9.1 rows4 12.8 us +BENCH Q4_K 2560x512 T=1 multi 6.4 us | il rows1 6.8 rows2 8.5 rows4 10.8 us +BENCH Q4_K 2560x512 T=2 multi 8.8 us | il rows1 7.8 rows2 7.8 rows4 10.5 us +BENCH Q4_K 2560x512 T=3 multi 9.3 us | il rows1 8.8 rows2 8.2 rows4 17.3 us +BENCH Q4_K 2560x512 T=4 multi 10.7 us | il rows1 9.8 rows2 8.9 rows4 12.8 us +BENCH Q5_K 2560x10240 T=1 multi 75.4 us | il rows1 80.0 rows2 70.0 rows4 81.4 us +BENCH Q5_K 2560x10240 T=2 multi 91.4 us | il rows1 86.0 rows2 82.4 rows4 75.0 us +BENCH Q5_K 2560x10240 T=3 multi 109.5 us | il rows1 95.1 rows2 76.2 rows4 81.3 us +BENCH Q5_K 2560x10240 T=4 multi 146.7 us | il rows1 130.9 rows2 105.2 rows4 155.2 us +BENCH Q5_K 2560x640 T=1 multi 7.7 us | il rows1 8.3 rows2 8.6 rows4 15.2 us +BENCH Q5_K 2560x640 T=2 multi 9.6 us | il rows1 9.9 rows2 8.3 rows4 11.6 us +BENCH Q5_K 2560x640 T=3 multi 10.6 us | il rows1 9.9 rows2 8.5 rows4 11.9 us +BENCH Q5_K 2560x640 T=4 multi 14.5 us | il rows1 11.4 rows2 9.7 rows4 18.2 us +BENCH Q5_K 2560x512 T=1 multi 7.0 us | il rows1 7.9 rows2 8.3 rows4 14.6 us +BENCH Q5_K 2560x512 T=2 multi 8.9 us | il rows1 8.9 rows2 8.0 rows4 11.3 us +BENCH Q5_K 2560x512 T=3 multi 9.6 us | il rows1 9.6 rows2 8.5 rows4 11.8 us +BENCH Q5_K 2560x512 T=4 multi 11.0 us | il rows1 10.5 rows2 9.3 rows4 18.2 us +BENCH Q6_K 2560x6144 T=1 multi 56.9 us | il rows1 70.7 rows2 71.5 rows4 78.8 us +BENCH Q6_K 2560x6144 T=2 multi 71.3 us | il rows1 80.7 rows2 62.9 rows4 73.1 us +BENCH Q6_K 2560x6144 T=3 multi 84.1 us | il rows1 95.7 rows2 88.4 rows4 68.2 us +BENCH Q6_K 2560x6144 T=4 multi 96.6 us | il rows1 97.6 rows2 68.6 rows4 72.1 us +BENCH Q6_K 2560x640 T=1 multi 8.9 us | il rows1 10.6 rows2 15.4 rows4 29.8 us +BENCH Q6_K 2560x640 T=2 multi 12.0 us | il rows1 10.8 rows2 13.8 rows4 21.6 us +BENCH Q6_K 2560x640 T=3 multi 13.2 us | il rows1 16.8 rows2 15.3 rows4 15.7 us +BENCH Q6_K 2560x640 T=4 multi 15.7 us | il rows1 17.4 rows2 12.0 rows4 16.1 us +BENCH Q3_K 2560x10240 T=1 multi 93.5 us | il rows1 127.4 rows2 72.4 rows4 131.6 us +BENCH Q3_K 2560x10240 T=2 multi 110.1 us | il rows1 102.9 rows2 91.2 rows4 109.5 us +BENCH Q3_K 2560x10240 T=3 multi 152.5 us | il rows1 119.3 rows2 107.8 rows4 117.5 us +BENCH Q3_K 2560x10240 T=4 multi 218.0 us | il rows1 134.8 rows2 163.3 rows4 177.2 us +BENCH Q3_K 2560x12288 T=1 multi 111.5 us | il rows1 151.8 rows2 85.9 rows4 150.4 us +BENCH Q3_K 2560x12288 T=2 multi 131.2 us | il rows1 122.4 rows2 108.2 rows4 127.8 us +BENCH Q3_K 2560x12288 T=3 multi 181.9 us | il rows1 141.9 rows2 129.3 rows4 140.8 us +BENCH Q3_K 2560x12288 T=4 multi 261.3 us | il rows1 161.4 rows2 194.5 rows4 216.6 us +BENCH Q3_K 2560x6144 T=1 multi 57.6 us | il rows1 78.1 rows2 46.1 rows4 83.4 us +BENCH Q3_K 2560x6144 T=2 multi 68.5 us | il rows1 63.3 rows2 56.5 rows4 66.9 us +BENCH Q3_K 2560x6144 T=3 multi 95.4 us | il rows1 73.9 rows2 67.0 rows4 75.0 us +BENCH Q3_K 2560x6144 T=4 multi 134.2 us | il rows1 83.1 rows2 100.4 rows4 117.3 us +BENCH Q3_K 6144x2560 T=1 multi 46.1 us | il rows1 77.6 rows2 44.8 rows4 74.7 us +BENCH Q3_K 6144x2560 T=2 multi 60.4 us | il rows1 62.7 rows2 56.7 rows4 65.4 us +BENCH Q3_K 6144x2560 T=3 multi 77.0 us | il rows1 75.5 rows2 63.9 rows4 70.6 us +BENCH Q3_K 6144x2560 T=4 multi 99.1 us | il rows1 79.7 rows2 98.2 rows4 113.1 us +BENCH Q3_K 2560x640 T=1 multi 8.8 us | il rows1 10.3 rows2 7.8 rows4 17.0 us +BENCH Q3_K 2560x640 T=2 multi 10.8 us | il rows1 10.8 rows2 8.7 rows4 11.9 us +BENCH Q3_K 2560x640 T=3 multi 14.8 us | il rows1 11.8 rows2 9.4 rows4 12.3 us +BENCH Q3_K 2560x640 T=4 multi 17.1 us | il rows1 13.6 rows2 12.9 rows4 18.0 us +BENCH Q3_K 2560x512 T=1 multi 7.7 us | il rows1 9.5 rows2 7.6 rows4 16.2 us +BENCH Q3_K 2560x512 T=2 multi 10.0 us | il rows1 9.9 rows2 8.6 rows4 11.6 us +BENCH Q3_K 2560x512 T=3 multi 11.4 us | il rows1 11.1 rows2 9.2 rows4 12.4 us +BENCH Q3_K 2560x512 T=4 multi 16.0 us | il rows1 12.3 rows2 12.7 rows4 18.0 us +// measured on this card by mmvq_il_parity --bench --emit-table + {23, {{2, 4, 4, 4, 4}, {4, 4, 4, 4, 4}, {2, 2, 2, 2, 2}}}, // IQ4_XS + {12, {{2, 0, 4, 4, 4}, {2, 2, 2, 2, 2}, {2, 2, 2, 2, 2}}}, // Q4_K + {13, {{2, 0, 4, 4, 4}, {2, 2, 2, 2, 2}, {2, 2, 2, 2, 2}}}, // Q5_K + {14, {{0, 0, 2, 2, 2}, {0, 4, 4, 4, 4}, {2, 4, 2, 2, 2}}}, // Q6_K + {11, {{2, 2, 2, 2, 2}, {2, 2, 2, 2, 2}, {2, 1, 1, 1, 1}}}, // Q3_K +// one column (kIl1RowsShared): + {23, {2, 2, 4, 4, 4}}, // IQ4_XS + {12, {0, 0, 0, 0, 0}}, // Q4_K + {13, {0, 0, 0, 2, 2}}, // Q5_K + {14, {0, 0, 0, 0, 0}}, // Q6_K + {11, {0, 0, 2, 2, 2}}, // Q3_K +mmvq_il_parity: OK (every case, T 1-4, rows 1/2/4 and the table, bitwise) diff --git a/bench/results/2026-10-12-p40-sm61-kernels/native-expert-bench.txt b/bench/results/2026-10-12-p40-sm61-kernels/native-expert-bench.txt new file mode 100644 index 00000000..bc2724e2 --- /dev/null +++ b/bench/results/2026-10-12-p40-sm61-kernels/native-expert-bench.txt @@ -0,0 +1,55 @@ +== native_expert_bench 0,5,11,17,23,29,35,41,47 18 2 0 2 200 +layer 0 iq3_xxs/iq4_nl G 18 T 2 | mode 0: all 346.9 us gu 229.3 us ( 98 GB/s) down 116.2 us (143 GB/s) | mode 2: all 576.7 us gu 349.3 us ( 65 GB/s) down 227.3 us ( 73 GB/s) | bitwise equal +layer 5 iq2_s /iq4_nl G 18 T 2 | mode 0: all 288.9 us gu 171.6 us (110 GB/s) down 116.0 us (143 GB/s) | mode 2: all 602.8 us gu 375.7 us ( 50 GB/s) down 226.7 us ( 73 GB/s) | bitwise equal +layer 11 iq2_s /iq4_nl G 18 T 2 | mode 0: all 288.9 us gu 171.5 us (110 GB/s) down 116.0 us (143 GB/s) | mode 2: all 603.5 us gu 375.8 us ( 50 GB/s) down 226.8 us ( 73 GB/s) | bitwise equal +layer 17 iq3_s /iq4_nl G 18 T 2 | mode 0: all 388.9 us gu 271.2 us ( 93 GB/s) down 116.2 us (143 GB/s) | mode 2: all 683.4 us gu 454.8 us ( 56 GB/s) down 228.0 us ( 73 GB/s) | bitwise equal +layer 23 iq2_s /iq4_nl G 18 T 2 | mode 0: all 288.9 us gu 171.6 us (110 GB/s) down 116.0 us (143 GB/s) | mode 2: all 602.8 us gu 375.7 us ( 50 GB/s) down 226.8 us ( 73 GB/s) | bitwise equal +layer 29 iq3_s /iq4_nl G 18 T 2 | mode 0: all 389.1 us gu 271.1 us ( 93 GB/s) down 116.2 us (143 GB/s) | mode 2: all 683.4 us gu 455.0 us ( 56 GB/s) down 228.0 us ( 73 GB/s) | bitwise equal +layer 35 iq3_s /iq4_nl G 18 T 2 | mode 0: all 389.0 us gu 271.1 us ( 93 GB/s) down 116.2 us (143 GB/s) | mode 2: all 683.3 us gu 454.9 us ( 56 GB/s) down 228.0 us ( 73 GB/s) | bitwise equal +layer 41 iq3_xxs/iq4_nl G 18 T 2 | mode 0: all 347.1 us gu 229.6 us ( 98 GB/s) down 116.2 us (143 GB/s) | mode 2: all 576.8 us gu 349.4 us ( 65 GB/s) down 227.3 us ( 73 GB/s) | bitwise equal +layer 47 iq4_xs /iq4_nl G 18 T 2 | mode 0: all 327.8 us gu 211.3 us (148 GB/s) down 116.1 us (143 GB/s) | mode 2: all 608.2 us gu 379.8 us ( 83 GB/s) down 228.2 us ( 73 GB/s) | bitwise equal +native_expert_bench: 0 differing +== native_expert_bench 0,5,11,17,23,29,35,41,47 18 2 0 5 200 +layer 0 iq3_xxs/iq4_nl G 18 T 2 | mode 0: all 347.0 us gu 229.4 us ( 98 GB/s) down 116.3 us (143 GB/s) | mode 5: all 348.9 us gu 231.2 us ( 98 GB/s) down 116.2 us (143 GB/s) | bitwise equal +layer 5 iq2_s /iq4_nl G 18 T 2 | mode 0: all 289.6 us gu 171.5 us (110 GB/s) down 116.1 us (143 GB/s) | mode 5: all 317.2 us gu 200.0 us ( 94 GB/s) down 116.0 us (143 GB/s) | bitwise equal +layer 11 iq2_s /iq4_nl G 18 T 2 | mode 0: all 289.4 us gu 171.5 us (110 GB/s) down 116.1 us (143 GB/s) | mode 5: all 317.4 us gu 200.0 us ( 94 GB/s) down 116.1 us (143 GB/s) | bitwise equal +layer 17 iq3_s /iq4_nl G 18 T 2 | mode 0: all 388.4 us gu 271.4 us ( 93 GB/s) down 116.2 us (143 GB/s) | mode 5: all 383.3 us gu 266.5 us ( 95 GB/s) down 116.3 us (143 GB/s) | bitwise equal +layer 23 iq2_s /iq4_nl G 18 T 2 | mode 0: all 289.0 us gu 171.4 us (110 GB/s) down 116.0 us (143 GB/s) | mode 5: all 317.0 us gu 200.0 us ( 94 GB/s) down 116.0 us (143 GB/s) | bitwise equal +layer 29 iq3_s /iq4_nl G 18 T 2 | mode 0: all 387.8 us gu 270.8 us ( 94 GB/s) down 116.0 us (143 GB/s) | mode 5: all 382.9 us gu 266.3 us ( 95 GB/s) down 116.1 us (143 GB/s) | bitwise equal +layer 35 iq3_s /iq4_nl G 18 T 2 | mode 0: all 387.7 us gu 270.8 us ( 94 GB/s) down 116.1 us (143 GB/s) | mode 5: all 382.6 us gu 266.4 us ( 95 GB/s) down 116.1 us (143 GB/s) | bitwise equal +layer 41 iq3_xxs/iq4_nl G 18 T 2 | mode 0: all 346.7 us gu 229.3 us ( 98 GB/s) down 116.0 us (143 GB/s) | mode 5: all 348.8 us gu 230.9 us ( 98 GB/s) down 116.1 us (143 GB/s) | bitwise equal +layer 47 iq4_xs /iq4_nl G 18 T 2 | mode 0: all 328.2 us gu 210.7 us (149 GB/s) down 116.0 us (143 GB/s) | mode 5: all 410.1 us gu 293.8 us (107 GB/s) down 116.1 us (143 GB/s) | bitwise equal +native_expert_bench: 0 differing +== native_expert_bench 0,5,11,17,23,29,35,41,47 18 2 0 6 200 +layer 0 iq3_xxs/iq4_nl G 18 T 2 | mode 0: all 347.4 us gu 229.7 us ( 98 GB/s) down 116.3 us (143 GB/s) | mode 6: all 347.1 us gu 229.4 us ( 98 GB/s) down 116.4 us (143 GB/s) | bitwise equal +layer 5 iq2_s /iq4_nl G 18 T 2 | mode 0: all 289.0 us gu 171.2 us (110 GB/s) down 115.9 us (143 GB/s) | mode 6: all 320.8 us gu 203.9 us ( 93 GB/s) down 115.9 us (143 GB/s) | bitwise equal +layer 11 iq2_s /iq4_nl G 18 T 2 | mode 0: all 289.1 us gu 171.2 us (110 GB/s) down 115.9 us (143 GB/s) | mode 6: all 321.0 us gu 203.9 us ( 93 GB/s) down 115.9 us (143 GB/s) | bitwise equal +layer 17 iq3_s /iq4_nl G 18 T 2 | mode 0: all 387.7 us gu 270.6 us ( 94 GB/s) down 116.1 us (143 GB/s) | mode 6: all 379.4 us gu 262.4 us ( 97 GB/s) down 116.1 us (143 GB/s) | bitwise equal +layer 23 iq2_s /iq4_nl G 18 T 2 | mode 0: all 289.2 us gu 171.4 us (110 GB/s) down 115.9 us (143 GB/s) | mode 6: all 321.0 us gu 204.1 us ( 93 GB/s) down 116.0 us (143 GB/s) | bitwise equal +layer 29 iq3_s /iq4_nl G 18 T 2 | mode 0: all 387.8 us gu 270.8 us ( 94 GB/s) down 116.1 us (143 GB/s) | mode 6: all 379.2 us gu 262.2 us ( 97 GB/s) down 116.0 us (143 GB/s) | bitwise equal +layer 35 iq3_s /iq4_nl G 18 T 2 | mode 0: all 387.8 us gu 270.7 us ( 94 GB/s) down 116.0 us (143 GB/s) | mode 6: all 379.2 us gu 262.1 us ( 97 GB/s) down 116.1 us (143 GB/s) | bitwise equal +layer 41 iq3_xxs/iq4_nl G 18 T 2 | mode 0: all 346.9 us gu 229.5 us ( 98 GB/s) down 116.2 us (143 GB/s) | mode 6: all 346.5 us gu 229.1 us ( 99 GB/s) down 116.1 us (143 GB/s) | bitwise equal +layer 47 iq4_xs /iq4_nl G 18 T 2 | mode 0: all 327.1 us gu 210.6 us (149 GB/s) down 116.1 us (143 GB/s) | mode 6: all 410.2 us gu 293.9 us (107 GB/s) down 116.1 us (143 GB/s) | bitwise equal +native_expert_bench: 0 differing +== native_expert_bench 0,5,11,17,23,29,35,41,47 18 2 0 7 200 +layer 0 iq3_xxs/iq4_nl G 18 T 2 | mode 0: all 346.7 us gu 229.2 us ( 99 GB/s) down 116.1 us (143 GB/s) | mode 7: all 259.9 us gu 149.3 us (151 GB/s) down 108.8 us (153 GB/s) | bitwise equal +layer 5 iq2_s /iq4_nl G 18 T 2 | mode 0: all 288.6 us gu 171.4 us (110 GB/s) down 115.9 us (143 GB/s) | mode 7: all 244.8 us gu 135.2 us (140 GB/s) down 109.1 us (152 GB/s) | bitwise equal +layer 11 iq2_s /iq4_nl G 18 T 2 | mode 0: all 288.7 us gu 171.3 us (110 GB/s) down 116.0 us (143 GB/s) | mode 7: all 245.0 us gu 135.4 us (140 GB/s) down 109.1 us (152 GB/s) | bitwise equal +layer 17 iq3_s /iq4_nl G 18 T 2 | mode 0: all 388.8 us gu 271.0 us ( 94 GB/s) down 116.3 us (143 GB/s) | mode 7: all 270.8 us gu 161.2 us (157 GB/s) down 109.4 us (152 GB/s) | bitwise equal +layer 23 iq2_s /iq4_nl G 18 T 2 | mode 0: all 288.6 us gu 171.4 us (110 GB/s) down 116.0 us (143 GB/s) | mode 7: all 244.8 us gu 135.2 us (140 GB/s) down 109.0 us (152 GB/s) | bitwise equal +layer 29 iq3_s /iq4_nl G 18 T 2 | mode 0: all 388.8 us gu 270.9 us ( 94 GB/s) down 116.2 us (143 GB/s) | mode 7: all 270.9 us gu 161.2 us (157 GB/s) down 109.4 us (152 GB/s) | bitwise equal +layer 35 iq3_s /iq4_nl G 18 T 2 | mode 0: all 389.0 us gu 270.9 us ( 94 GB/s) down 116.2 us (143 GB/s) | mode 7: all 270.9 us gu 161.5 us (157 GB/s) down 109.4 us (152 GB/s) | bitwise equal +layer 41 iq3_xxs/iq4_nl G 18 T 2 | mode 0: all 347.0 us gu 229.5 us ( 98 GB/s) down 116.2 us (143 GB/s) | mode 7: all 260.0 us gu 149.3 us (151 GB/s) down 108.8 us (152 GB/s) | bitwise equal +layer 47 iq4_xs /iq4_nl G 18 T 2 | mode 0: all 328.1 us gu 210.9 us (149 GB/s) down 116.2 us (143 GB/s) | mode 7: all 270.9 us gu 161.0 us (195 GB/s) down 109.5 us (151 GB/s) | bitwise equal +native_expert_bench: 0 differing +== native_expert_bench 0,5,11,17,23,29,35,41,47 18 2 0 8 200 +layer 0 iq3_xxs/iq4_nl G 18 T 2 | mode 0: all 345.0 us gu 227.4 us ( 99 GB/s) down 116.3 us (143 GB/s) | mode 8: all 252.0 us gu 142.5 us (158 GB/s) down 108.8 us (153 GB/s) | bitwise equal +layer 5 iq2_s /iq4_nl G 18 T 2 | mode 0: all 290.0 us gu 172.6 us (109 GB/s) down 116.0 us (143 GB/s) | mode 8: all 237.5 us gu 127.5 us (148 GB/s) down 108.9 us (152 GB/s) | bitwise equal +layer 11 iq2_s /iq4_nl G 18 T 2 | mode 0: all 290.1 us gu 172.8 us (109 GB/s) down 116.0 us (143 GB/s) | mode 8: all 237.6 us gu 127.5 us (148 GB/s) down 109.0 us (152 GB/s) | bitwise equal +layer 17 iq3_s /iq4_nl G 18 T 2 | mode 0: all 389.6 us gu 272.0 us ( 93 GB/s) down 116.1 us (143 GB/s) | mode 8: all 254.8 us gu 145.6 us (174 GB/s) down 109.6 us (151 GB/s) | bitwise equal +layer 23 iq2_s /iq4_nl G 18 T 2 | mode 0: all 290.2 us gu 172.7 us (109 GB/s) down 116.0 us (143 GB/s) | mode 8: all 237.4 us gu 127.5 us (148 GB/s) down 109.0 us (152 GB/s) | bitwise equal +layer 29 iq3_s /iq4_nl G 18 T 2 | mode 0: all 389.6 us gu 272.0 us ( 93 GB/s) down 116.2 us (143 GB/s) | mode 8: all 254.8 us gu 145.3 us (174 GB/s) down 110.6 us (150 GB/s) | bitwise equal +layer 35 iq3_s /iq4_nl G 18 T 2 | mode 0: all 390.4 us gu 272.6 us ( 93 GB/s) down 116.5 us (142 GB/s) | mode 8: all 255.3 us gu 145.4 us (174 GB/s) down 110.4 us (150 GB/s) | bitwise equal +layer 41 iq3_xxs/iq4_nl G 18 T 2 | mode 0: all 345.3 us gu 227.7 us ( 99 GB/s) down 116.3 us (143 GB/s) | mode 8: all 252.0 us gu 142.4 us (159 GB/s) down 108.8 us (152 GB/s) | bitwise equal +layer 47 iq4_xs /iq4_nl G 18 T 2 | mode 0: all 327.8 us gu 211.3 us (148 GB/s) down 116.2 us (143 GB/s) | mode 8: all 261.0 us gu 151.5 us (207 GB/s) down 109.5 us (151 GB/s) | bitwise equal +native_expert_bench: 0 differing diff --git a/bench/results/2026-10-12-p40-sm61-kernels/nvprof-base.txt b/bench/results/2026-10-12-p40-sm61-kernels/nvprof-base.txt new file mode 100644 index 00000000..3948f321 --- /dev/null +++ b/bench/results/2026-10-12-p40-sm61-kernels/nvprof-base.txt @@ -0,0 +1,280 @@ +==1223237== Profiling result: + Type Time(%) Time Calls Avg Min Max Name + GPU activities: 16.08% 15.1883s 83954 180.91us 256ns 92.642ms [CUDA memcpy HtoD] + 11.51% 10.8694s 1152 9.4352ms 200.55us 103.18ms maxwell_sgemm_fp16_64x64_tn + 10.96% 10.3471s 648 15.968ms 300.33us 65.592ms maxwell_sgemm_fp16_32x128_tn + 5.31% 5.01486s 14965 335.11us 25.217us 768.42us void attn_chunk_kernel_pre75(float const *, strata::kernels::QsaAttnPools, int const *, int const , int, int, float, float*, int const *, int const *, int, int, __int64) + 3.46% 3.26976s 3266 1.0012ms 43.841us 5.4238ms void mul_mat_q(char const *, int const *, int const *, int const *, float*, float*, float const *, uint3, int, int, int, int, int, uint3, uint3, int, int, int, uint3, uint3, int, int, int, uint3) + 2.88% 2.71582s 768 3.5362ms 93.220us 9.2698ms void dequant_kernel(unsigned char const *, long, long, long, long, long, H16*) + 2.86% 2.70045s 1655 1.6317ms 178.76us 7.7256ms void mul_mat_q(char const *, int const *, int const *, int const *, float*, float*, float const *, uint3, int, int, int, int, int, uint3, uint3, int, int, int, uint3, uint3, int, int, int, uint3) + 2.50% 2.36509s 23827 99.261us 8.0960us 2.1880ms void native_q6_k_mmvq_kernel(Q6KBlock const *, Q81Block const *, float*, int, int) + 2.40% 2.26797s 1443 1.5717ms 171.05us 8.1444ms void mul_mat_q(char const *, int const *, int const *, int const *, float*, float*, float const *, uint3, int, int, int, int, int, uint3, uint3, int, int, int, uint3, uint3, int, int, int, uint3) + 2.32% 2.19528s 783 2.8037ms 464.18us 41.079ms sgemm_128x128x8_NT_vec + 2.08% 1.96923s 1527 1.2896ms 194.35us 1.8325ms maxwell_sgemm_128x64_tn + 1.84% 1.74172s 35880 48.542us 2.3680us 246.70us void native_down_multi_kernel(__int64 const *, int const *, int const , int const , block_q8_1 const *, strata::kernels::NativeExpertLayout, float*) + 1.51% 1.42466s 17415 81.806us 8.3520us 2.6303ms void native_mmvq_multi_kernel(Q6KTraitsBlock const *, Q81Block const *, float*, int, int, Q6KTraitsBlock const , Q81Block const *) + 1.47% 1.38727s 15640 88.699us 2.4960us 421.49us void native_gu_multi_kernel(__int64 const *, int const *, int const , int const , block_q8_1 const *, strata::kernels::NativeExpertLayout, float*, strata::kernels::NativeExpertLayout) + 1.46% 1.37823s 847 1.6272ms 85.635us 6.2062ms void mul_mat_q(char const *, int const *, int const *, int const *, float*, float*, float const *, uint3, int, int, int, int, int, uint3, uint3, int, int, int, uint3, uint3, int, int, int, uint3) + 1.38% 1.30607s 8715 149.86us 2.0160us 553.62us bf16_to_f32_kernel(unsigned short const *, float*, long) + 1.34% 1.26231s 216 5.8440ms 806.40us 14.335ms gdn_rec_cols_pipe_kernel(float*, float const *, float const *, float const *, float*, long) + 1.31% 1.23884s 18400 67.328us 2.4960us 318.57us void native_gu_multi_kernel(__int64 const *, int const *, int const , int const , block_q8_1 const *, strata::kernels::NativeExpertLayout, float*, strata::kernels::NativeExpertLayout) + 1.22% 1.15237s 66240 17.396us 3.0400us 13.483ms wait_flag_ge_kernel(unsigned int volatile *, unsigned int) + 1.14% 1.07248s 10965 97.809us 11.521us 3.1190ms void native_mmvq_multi_kernel(Q6KTraitsBlock const *, Q81Block const *, float*, int, int, Q6KTraitsBlock const , Q81Block const *) + 1.07% 1.00929s 14965 67.443us 8.8000us 288.49us attn_merge_kernel(float const *, float const *, float const *, int, float*, __int64) + 0.95% 901.77ms 9200 98.018us 2.4960us 449.91us void native_gu_multi_kernel(__int64 const *, int const *, int const , int const , block_q8_1 const *, strata::kernels::NativeExpertLayout, float*, strata::kernels::NativeExpertLayout) + 0.95% 893.97ms 3063 291.86us 58.691us 826.76us sgemm_32x32x32_NT_vec + 0.87% 818.43ms 7224 113.29us 12.929us 3.7616ms void native_mmvq_multi_kernel(Q6KTraitsBlock const *, Q81Block const *, float*, int, int, Q6KTraitsBlock const , Q81Block const *) + 0.86% 813.56ms 318 2.5584ms 375.60us 5.0059ms gr_write_norm_rs_kernel(float*, float const *, float const *, long, float const *, float, float*, unsigned short*, unsigned short*, long) + 0.81% 765.62ms 585 1.3087ms 190.44us 2.5104ms gr_mix_r_kernel(float const *, float const *, float const *, float const *, float*, unsigned short*, long, unsigned short*, unsigned short*) + 0.80% 753.09ms 736 1.0232ms 101.83us 4.8352ms void mul_mat_q(char const *, int const *, int const *, int const *, float*, float*, float const *, uint3, int, int, int, int, int, uint3, uint3, int, int, int, uint3, uint3, int, int, int, uint3) + 0.73% 688.81ms 14891 46.256us 7.2650us 267.60us copy16_group_kernel(GroupArgs, int, long, long, uint4*, uint4*) + 0.68% 643.54ms 19644 32.760us 28.769us 62.243us void gr_down_staged_kernel(GrMulti) + 0.67% 632.89ms 4743 133.44us 2.0170us 3.1120ms void quantize_mmq_q8_1(float const *, int const *, void*, long, long, long, long, long, int, int, int) + 0.61% 574.43ms 19646 29.239us 26.913us 55.234us void gr_up_multi_kernel(GrMulti) + 0.56% 526.06ms 13832 38.031us 33.602us 67.779us void gr_down_staged_kernel(GrMulti) + 0.49% 463.64ms 19106 24.266us 8.8000us 2.2939ms cvec_kernel(float*, float const *, float const *, int const *, int, long, int, int, long, float const *, long, float const *, long, int) + 0.48% 453.68ms 288 1.5753ms 232.91us 3.0165ms moe_combine4_kernel(float const *, int const *, float const *, float4 const *, float const *, float4*, long) + 0.48% 451.28ms 13246 34.069us 28.833us 49.378us void gr_up_multi_kernel(GrMulti) + 0.39% 370.36ms 47253 7.8370us 6.7200us 25.633us gr_norm_split_kernel(GrMulti) + 0.37% 350.74ms 258 1.3595ms 198.12us 2.7444ms gr_write_kernel(float*, float const *, float const *, long, long) + 0.36% 341.39ms 8280 41.230us 3.4560us 178.31us void native_down_multi_kernel(__int64 const *, int const *, int const , int const , block_q8_1 const *, strata::kernels::NativeExpertLayout, float*) + 0.36% 337.55ms 8303 40.653us 35.874us 66.883us void gr_down_staged_kernel(GrMulti) + 0.35% 333.23ms 8305 40.124us 36.386us 49.538us void gr_up_multi_kernel(GrMulti) + 0.35% 326.02ms 22038 14.793us 5.4410us 20.833us copy16_kernel(uint4 const *, long, uint4 const *, long, uint4*, uint4 const *, long, uint4*) + 0.32% 303.13ms 1116 271.62us 10.592us 710.37us block_scores_kernel(float const *, float const *, float const *, int const *, long, float*) + 0.32% 297.68ms 267 1.1149ms 161.80us 2.4074ms gr_norm_rs_kernel(float const *, float const *, float, float*, unsigned short*, unsigned short*, long) + 0.31% 290.21ms 4419 65.672us 2.0480us 511.51us swiglu_kernel(float const *, float*, long, long, bool) + 0.29% 275.61ms 6054 45.524us 38.946us 72.355us void gr_down_staged_kernel(GrMulti) + 0.29% 274.67ms 6230 44.089us 7.6160us 90.628us void native_q5_k_mmvq_kernel(Q5KBlock const *, Q81Block const *, float*, int, int) + 0.29% 271.89ms 10152 26.781us 22.593us 40.513us void gdn_step_norm_multi_kernel(float*, float const *, int, float const , float const , float const , float const , float, gdn_step_norm_multi_kernel, int, int, int, int const *, int, GdnQ81*) + 0.28% 269.04ms 4725 56.940us 9.5360us 117.00us void native_mmvq_multi_kernel(Q5KTraitsBlock const *, Q81Block const *, float*, int, int, Q5KTraitsBlock const , Q81Block const *) + 0.28% 263.98ms 10152 26.002us 17.537us 53.667us void gdn_step_commit_kernel(float*, float const *, int, float const , float const , int, int, int const *, int) + 0.28% 262.43ms 7476 35.103us 9.1520us 127.97us void native_iq4_xs_mmvq_kernel(IQ4XSBlock const *, Q81Block const *, float*, int, int) + 0.27% 257.71ms 13536 19.038us 18.464us 19.745us route_multi(float const *, int*, float*, int) + 0.27% 257.10ms 5460 47.087us 42.978us 57.282us void gr_up_multi_kernel(GrMulti) + 0.27% 250.36ms 23446 10.678us 2.9120us 173.38us void bf16_f32_mmvf_kernel(float const *, unsigned short const *, float*, int) + 0.26% 242.97ms 216 1.1249ms 162.66us 2.0993ms gdn_conv_tiled_kernel(float const *, float const *, float const *, float*, long) + 0.23% 213.21ms 5392 39.542us 8.0000us 141.61us void native_small_mmvq_kernel(Q80Block const *, Q81Block const *, float*, int, int) + 0.22% 211.22ms 2975 70.999us 11.232us 147.27us void native_mmvq_multi_kernel(Q5KTraitsBlock const *, Q81Block const *, float*, int, int, Q5KTraitsBlock const , Q81Block const *) + 0.22% 204.15ms 5670 36.005us 10.721us 128.42us void native_mmvq_multi_kernel(IQ4XSTraitsBlock const *, Q81Block const *, float*, int, int, IQ4XSTraitsBlock const , Q81Block const *) + 0.21% 194.83ms 16470 11.829us 3.3280us 207.08us void bf16_f32_mmvf_multi_kernel(float const *, long, unsigned short const *, float*, long, int, int) + 0.20% 192.60ms 9409 20.469us 18.689us 64.099us route(float const *, int*, float*) + 0.20% 190.54ms 72217 2.6380us 1.8240us 13.569us native_quantize_q8_1_kernel(float const *, Q81Block*, int) + 0.20% 189.65ms 6345 29.889us 8.7690us 102.50us void native_mmvq_multi_kernel(Q4KTraitsBlock const *, Q81Block const *, float*, int, int, Q4KTraitsBlock const , Q81Block const *) + 0.19% 181.85ms 8366 21.736us 6.8480us 73.475us void native_q4_k_mmvq_kernel(Q4KBlock const *, Q81Block const *, float*, int, int) + 0.19% 181.38ms 1960 92.538us 14.945us 199.72us void native_mmvq_multi_kernel(Q5KTraitsBlock const *, Q81Block const *, float*, int, int, Q5KTraitsBlock const , Q81Block const *) + 0.19% 177.26ms 1027 172.60us 768ns 11.505ms [CUDA memcpy DtoH] + 0.19% 177.22ms 8366 21.183us 19.009us 26.785us void native_small_mmvq_kernel(IQ4NLBlock const *, Q81Block const *, float*, int, int) + 0.18% 174.48ms 216 807.79us 127.59us 1.5118ms gdn_out_norm_kernel(float const *, float const *, float, float*, unsigned short*, long) + 0.17% 156.96ms 3995 39.288us 10.497us 139.46us void native_mmvq_multi_kernel(Q4KTraitsBlock const *, Q81Block const *, float*, int, int, Q4KTraitsBlock const , Q81Block const *) + 0.16% 150.29ms 3570 42.097us 11.105us 147.91us void native_mmvq_multi_kernel(IQ4XSTraitsBlock const *, Q81Block const *, float*, int, int, IQ4XSTraitsBlock const , Q81Block const *) + 0.16% 149.33ms 210 711.08us 73.347us 1.6177ms void dequant_kernel(unsigned char const *, long, long, long, long, long, H16*) + 0.16% 147.13ms 10370 14.188us 3.8080us 236.62us void bf16_f32_mmvf_multi_kernel(float const *, long, unsigned short const *, float*, long, int, int) + 0.15% 145.45ms 282 515.77us 106.41us 1.9985ms void dequant_kernel(unsigned char const *, long, long, long, long, long, H16*) + 0.15% 142.85ms 44160 3.2340us 1.6640us 8.2240us swiglu_q8_1_entries_kernel(float const *, float const *, int const *, int const *, int, block_q8_1*) + 0.15% 136.99ms 11050 12.397us 288ns 53.049ms [CUDA memset] + 0.14% 132.99ms 22080 6.0220us 3.0720us 37.121us strata::kernels::copy_rows_from_mapped_kernel(float4*, float4 volatile *, long, int const *, int const *, unsigned int volatile *, unsigned int) + 0.14% 132.01ms 22080 5.9780us 4.3200us 21.313us strata::kernels::doorbell_publish_res_kernel(float const *, int const *, int const *, int, int, int, float*, int*, unsigned int*) + 0.14% 130.80ms 23742 5.5090us 1.8560us 21.153us strata::kernels::copy_i32_from_mapped_kernel(int*, int volatile *, int) + 0.14% 128.30ms 2632 48.746us 12.353us 172.74us void native_mmvq_multi_kernel(Q4KTraitsBlock const *, Q81Block const *, float*, int, int, Q4KTraitsBlock const , Q81Block const *) + 0.13% 126.34ms 6408 19.715us 18.593us 21.313us void gdn_step_norm_multi_kernel(float*, float const *, int, float const , float const , float const , float const , float, gdn_step_norm_multi_kernel, int, int, int, int const *, int, GdnQ81*) + 0.13% 124.09ms 6345 19.556us 18.528us 24.353us void native_mmvq_multi_kernel, int=2, int=4, int=2, bool=0, bool=0>(IQ4NLBlockBlock const *, Q81Block const *, float*, int, int, IQ4NLBlockBlock const , Q81Block const *) + 0.13% 123.47ms 774 159.52us 15.584us 5.2336ms void native_mmvq_multi_kernel(Q6KTraitsBlock const *, Q81Block const *, float*, int, int, Q6KTraitsBlock const , Q81Block const *) + 0.13% 119.44ms 57 2.0955ms 232.87us 8.2103ms void mul_mat_q(char const *, int const *, int const *, int const *, float*, float*, float const *, uint3, int, int, int, int, int, uint3, uint3, int, int, int, uint3, uint3, int, int, int, uint3) + 0.12% 115.53ms 2352 49.120us 13.440us 171.11us void native_mmvq_multi_kernel(IQ4XSTraitsBlock const *, Q81Block const *, float*, int, int, IQ4XSTraitsBlock const , Q81Block const *) + 0.11% 105.97ms 6832 15.510us 4.9600us 302.93us void bf16_f32_mmvf_multi_kernel(float const *, long, unsigned short const *, float*, long, int, int) + 0.11% 104.25ms 36 2.8959ms 137.86us 21.939ms void mul_mat_q(char const *, int const *, int const *, int const *, float*, float*, float const *, uint3, int, int, int, int, int, uint3, uint3, int, int, int, uint3, uint3, int, int, int, uint3) + 0.10% 98.225ms 252 389.78us 81.444us 1.5700ms void dequant_kernel(unsigned char const *, long, long, long, long, long, H16*) + 0.10% 96.556ms 243 397.35us 13.920us 2.5645ms rms_rows_kernel(float*, float const *, long, long, float) + 0.10% 93.514ms 216 432.94us 65.731us 834.95us gdn_l2_kernel(float*, float) + 0.09% 86.435ms 920 93.951us 2.7520us 374.06us void native_gu_multi_kernel(__int64 const *, int const *, int const , int const , block_q8_1 const *, strata::kernels::NativeExpertLayout, float*, strata::kernels::NativeExpertLayout) + 0.09% 86.198ms 3995 21.576us 20.320us 24.961us void native_mmvq_multi_kernel, int=3, int=4, int=2, bool=0, bool=0>(IQ4NLBlockBlock const *, Q81Block const *, float*, int, int, IQ4NLBlockBlock const , Q81Block const *) + 0.08% 80.147ms 1116 71.816us 1.4720us 157.74us block_topk_kernel(float const *, int const *, long, long, int*) + 0.08% 76.701ms 16560 4.6310us 4.0320us 6.1130us gdn_conv_l2_multi_kernel(float*, float const *, float const *, float*, int, int, float, int, bool) + 0.08% 75.984ms 22080 3.4410us 1.9520us 6.4330us add_hits_kernel(float*, float const *, int const *, int const *, int) + 0.08% 73.100ms 1325 55.169us 38.082us 91.940us sampler_greedy_kernel(float const *, int, int const *, int, strata::kernels::SamplerParams, int, int, int*) + 0.08% 72.744ms 22945 3.1700us 2.8480us 10.048us combine_k10_vec4(float4 const *, float const *, float4 const *, float4*, long) + 0.07% 70.310ms 72 976.53us 144.13us 1.9930ms gate_attn_kernel(float const *, float const *, unsigned short*, long, long) + 0.07% 69.594ms 22945 3.0330us 2.2720us 9.9210us native_swiglu_quantize_q8_1_kernel(float const *, float const *, Q81Block*, int) + 0.07% 69.070ms 81 852.72us 124.39us 1.9369ms kv_append_kernel(float const *, float const *, long, int const *, long, unsigned short*, unsigned short*, char*, char*, unsigned short*, unsigned short*, strata::kernels::KvHostPools, strata::kernels::KvHostPools) + 0.07% 65.188ms 18069 3.6070us 2.4640us 12.256us void norm_rope_kernel(float const *, int, float const , float*, int, int, float, float, float, float, float, float, float, int const *, int const , strata::kernels::RopeTab) + 0.07% 64.725ms 22080 2.9310us 2.6240us 4.0320us quantize_q8_1_kernel(float const *, block_q8_1*, __int64) + 0.07% 62.977ms 5520 11.408us 2.0160us 50.530us block_topk_wide_kernel(float const *, int const *, long, long, int*) + 0.07% 62.592ms 2632 23.781us 22.977us 26.145us void native_mmvq_multi_kernel, int=4, int=4, int=2, bool=0, bool=0>(IQ4NLBlockBlock const *, Q81Block const *, float*, int, int, IQ4NLBlockBlock const , Q81Block const *) + 0.06% 60.525ms 22080 2.7410us 2.4960us 3.6160us fetch_blobs_kernel(__int64 const *, int const *, uint4*, __int64) + 0.06% 56.291ms 22945 2.4530us 1.6960us 8.5440us sigmoid_scale_rows_vec4_kernel(float4*, float const *, int) + 0.06% 56.151ms 72 779.87us 108.13us 1.8545ms split_q_kernel(float const *, float*, long) + 0.06% 52.257ms 5520 9.4660us 2.5600us 416.85us copy_kernel(strata::kernels::KvStreamMap, Runs) + 0.05% 48.225ms 5520 8.7360us 4.6400us 26.625us resolve_kernel(strata::kernels::KvStreamMap, int const *, int const *, int, int, int) + 0.05% 45.454ms 594 76.522us 68.995us 96.804us void gr_up_multi_kernel(GrMulti) + 0.05% 45.005ms 8904 5.0540us 2.8480us 29.122us void append(float const *, int const *, int, int, int, float const , float, float*, int const *, int const *, int*, int, float, float, float, float, float, float, int const , strata::kernels::RopeTab) + 0.05% 44.243ms 6391 6.9220us 5.7600us 23.137us void kv_append_q8_kernel(char*, kv_append_q8_kernel, unsigned short*, char*, int const *, int const , float const *, float const , int, int, int, strata::kernels::KvHostPools, int, int) + 0.05% 42.842ms 93 460.66us 85.027us 643.87us void mul_mat_q(char const *, int const *, int const *, int const *, float*, float*, float const *, uint3, int, int, int, int, int, uint3, uint3, int, int, int, uint3, uint3, int, int, int, uint3) + 0.05% 42.821ms 170 251.89us 80.676us 348.46us void mul_mat_q(char const *, int const *, int const *, int const *, float*, float*, float const *, uint3, int, int, int, int, int, uint3, uint3, int, int, int, uint3, uint3, int, int, int, uint3) + 0.04% 42.429ms 432 98.215us 25.249us 241.35us void gemv2T_kernel_val, cublasGemvTensorStridedBatched, cublasGemvTensorStridedBatched, float>>(int, float, float) + 0.04% 42.074ms 10152 4.1440us 2.6240us 16.673us gdn_conv_commit_kernel(float*, float const *, int, int const *) + 0.04% 41.542ms 4860 8.5470us 8.1600us 9.0570us void gdn_ab_multi_kernel(float const *, unsigned short const *, unsigned short const , float const , float const , float*, unsigned short const *, int, int, int) + 0.04% 41.389ms 260 159.19us 4.1040us 921.39us [CUDA memcpy HtoH] + 0.04% 41.151ms 6408 6.4210us 6.0800us 6.9760us void gdn_ab_multi_kernel(float const *, unsigned short const *, unsigned short const , float const , float const , float*, unsigned short const *, int, int, int) + 0.04% 40.021ms 5520 7.2500us 4.5760us 24.193us block_scores_multi_kernel(float const *, float const *, float const *, int const *, int, long, float*, bool) + 0.04% 39.737ms 22080 1.7990us 1.6640us 2.0800us rebase_ptrs_kernel(__int64*, int const *, __int64, __int64) + 0.04% 39.394ms 865 45.542us 42.210us 59.394us gu_grouped_t_kernel(__int64 const *, int const *, int const *, int const *, unsigned char const *, float const *, float*, int) + 0.04% 36.952ms 81 456.20us 149.06us 636.09us void mul_mat_q(char const *, int const *, int const *, int const *, float*, float*, float const *, uint3, int, int, int, int, int, uint3, uint3, int, int, int, uint3, uint3, int, int, int, uint3) + 0.04% 34.262ms 820 41.783us 10.368us 61.059us void native_mmvq_multi_kernel, int=4, int=4, int=2, bool=0, bool=0>(Q80BlockBlock const *, Q81Block const *, float*, int, int, Q80BlockBlock const , Q81Block const *) + 0.03% 32.035ms 3060 10.468us 9.8890us 11.072us void gdn_ab_multi_kernel(float const *, unsigned short const *, unsigned short const , float const , float const , float*, unsigned short const *, int, int, int) + 0.03% 31.333ms 282 111.11us 103.43us 124.29us void dequant_kernel(unsigned char const *, long, long, long, long, long, H16*) + 0.03% 30.770ms 10327 2.9790us 1.9530us 19.648us strata::kernels::copy_from_mapped_kernel(float4*, float4 volatile *, long) + 0.03% 29.655ms 210 141.22us 20.289us 303.82us void native_mmvq_multi_kernel(Q5KTraitsBlock const *, Q81Block const *, float*, int, int, Q5KTraitsBlock const , Q81Block const *) + 0.03% 26.401ms 2016 13.095us 12.417us 13.921us void gdn_ab_multi_kernel(float const *, unsigned short const *, unsigned short const , float const , float const , float*, unsigned short const *, int, int, int) + 0.03% 25.124ms 288 87.235us 14.337us 162.09us swiglu_pair_kernel(float const *, float const *, unsigned short*, long) + 0.03% 24.584ms 865 28.421us 25.761us 44.866us down_grouped_t_kernel(__int64 const *, int const *, int const *, int const *, unsigned char const *, float const *, float*) + 0.03% 24.430ms 109 224.13us 24.961us 287.24us void mul_mat_q(char const *, int const *, int const *, int const *, float*, float*, float const *, uint3, int, int, int, int, int, uint3, uint3, int, int, int, uint3, uint3, int, int, int, uint3) + 0.02% 22.804ms 62 367.81us 94.532us 481.81us void mul_mat_q(char const *, int const *, int const *, int const *, float*, float*, float const *, uint3, int, int, int, int, int, uint3, uint3, int, int, int, uint3, uint3, int, int, int, uint3) + 0.02% 22.443ms 261 85.988us 71.651us 96.420us void native_mmvq_multi_kernel, int=8, int=4, int=2, bool=0, bool=0>(Q80BlockBlock const *, Q81Block const *, float*, int, int, Q80BlockBlock const , Q81Block const *) + 0.02% 22.019ms 282 78.081us 19.489us 299.98us void native_mmvq_multi_kernel(Q4KTraitsBlock const *, Q81Block const *, float*, int, int, Q4KTraitsBlock const , Q81Block const *) + 0.02% 21.086ms 18 1.1714ms 171.21us 2.2095ms rms_rep_kernel(float const *, float const *, float*) + 0.02% 20.825ms 6385 3.2610us 2.6240us 11.136us gate(float const *, float const *, float*, int, int) + 0.02% 20.374ms 252 80.848us 20.161us 299.08us void native_mmvq_multi_kernel(IQ4XSTraitsBlock const *, Q81Block const *, float*, int, int, IQ4XSTraitsBlock const , Q81Block const *) + 0.02% 19.788ms 1346 14.701us 4.9600us 1.5624ms embed_rows_kernel(int, unsigned char const *, unsigned long, int const *, long, float*) + 0.02% 19.197ms 288 66.655us 20.161us 131.01us void route_kernel(float const *, int*, float*, long) + 0.02% 18.390ms 225 81.734us 5.6000us 416.72us void rope_kernel(float*, long, long, long, long, float, float, float, float, float, float, int const *, strata::kernels::RopeTab) + 0.02% 16.898ms 1152 14.668us 2.9440us 59.331us copy_i32_kernel(int*, int const *, long) + 0.02% 16.282ms 732 22.242us 6.1760us 386.35us void bf16_f32_mmvf_multi_kernel(float const *, long, unsigned short const *, float*, long, int, int) + 0.02% 15.597ms 585 26.661us 5.2160us 53.922us gr_silu_kernel(float const *, unsigned short*, unsigned short*, long) + 0.02% 15.079ms 38 396.83us 146.79us 483.57us void mul_mat_q(char const *, int const *, int const *, int const *, float*, float*, float const *, uint3, int, int, int, int, int, uint3, uint3, int, int, int, uint3, uint3, int, int, int, uint3) + 0.02% 14.533ms 1043 13.933us 12.288us 22.529us void native_small_mmvq_kernel(Q80Block const *, Q81Block const *, float*, int, int) + 0.01% 13.575ms 6 2.2626ms 343.57us 4.1859ms conv_residual_batch_kernel(float const *, float const *, unsigned short const *, float*, float const *, int) + 0.01% 13.447ms 28 480.26us 177.00us 627.45us void mul_mat_q(char const *, int const *, int const *, int const *, float*, float*, float const *, uint3, int, int, int, int, int, uint3, uint3, int, int, int, uint3, uint3, int, int, int, uint3) + 0.01% 13.086ms 570 22.958us 8.8320us 48.930us void native_mmvq_multi_kernel, int=2, int=4, int=2, bool=0, bool=0>(Q80BlockBlock const *, Q81Block const *, float*, int, int, Q80BlockBlock const , Q81Block const *) + 0.01% 12.675ms 1742 7.2760us 4.4160us 21.313us void norm(float const *, float const , float*, int, float) + 0.01% 11.833ms 31 381.71us 57.091us 486.87us void mul_mat_q(char const *, int const *, int const *, int const *, float*, float*, float const *, uint3, int, int, int, int, int, uint3, uint3, int, int, int, uint3, uint3, int, int, int, uint3) + 0.01% 11.316ms 880 12.858us 2.8480us 1.9722ms add_streams_broadcast_kernel(float const *, float const *, float*, long, int) + 0.01% 11.205ms 2889 3.8780us 3.2960us 5.1520us void weighted_rms_norm(float const *, float const , float*, int, float) + 0.01% 9.5658ms 282 33.921us 33.185us 35.105us void native_mmvq_multi_kernel, int=6, int=4, int=2, bool=0, bool=0>(IQ4NLBlockBlock const *, Q81Block const *, float*, int, int, IQ4NLBlockBlock const , Q81Block const *) + 0.01% 9.2924ms 865 10.742us 9.7290us 23.169us mtp_select_kernel(float const *, long, int const *, int const *, float*, int*, int*, int, float const *, float*) + 0.01% 9.2746ms 35 264.99us 49.826us 345.17us void mul_mat_q(char const *, int const *, int const *, int const *, float*, float*, float const *, uint3, int, int, int, int, int, uint3, uint3, int, int, int, uint3, uint3, int, int, int, uint3) + 0.01% 8.8519ms 969 9.1350us 2.3040us 1.8318ms gate_kernel(float const *, float const *, float*, float) + 0.01% 8.8496ms 963 9.1890us 8.7360us 10.017us history_advance_kernel(float*, float const *) + 0.01% 7.9552ms 865 9.1960us 7.6480us 23.617us group_resident_kernel(int const *, int, int, unsigned char const *, __int64, __int64*, int*, int*, int*, int*) + 0.01% 7.6550ms 865 8.8490us 8.6080us 20.896us row_top_prob_split_kernel(float const *, int, int const *, float*, TopRow*) + 0.01% 7.4022ms 30 246.74us 76.804us 366.51us void mul_mat_q(char const *, int const *, int const *, int const *, float*, float*, float const *, uint3, int, int, int, int, int, uint3, uint3, int, int, int, uint3, uint3, int, int, int, uint3) + 0.01% 6.8682ms 211 32.550us 1.7920us 1.6933ms [CUDA memcpy DtoD] + 0.01% 6.8484ms 360 19.023us 16.737us 23.521us void cublasLt::splitKreduce_kernel(cublasLt::cublasSplitKParams, float const *, float const *, float const **, cublasLt::cublasSplitKParams const *, cublasLt::cublasSplitKParams const , float const *, float const , cublasLt::cublasSplitKParams const **, void*, long, cublasLt::cublasSplitKParams*, int*) + 0.01% 6.2034ms 1785 3.4750us 3.1360us 10.464us post(float const *, float const *, float const *, float*, int, int, float) + 0.01% 5.9702ms 6 995.04us 148.04us 1.8592ms broadcast_batch_kernel(float const *, float const *, float*, int) + 0.01% 5.5813ms 247 22.596us 9.4720us 51.938us void native_mmvq_multi_kernel, int=3, int=4, int=2, bool=0, bool=0>(Q80BlockBlock const *, Q81Block const *, float*, int, int, Q80BlockBlock const , Q81Block const *) + 0.01% 5.3085ms 6 884.76us 132.97us 1.6393ms gr_broadcast_kernel(float const *, float*, long) + 0.01% 5.0026ms 24 208.44us 100.33us 266.41us void mul_mat_q(char const *, int const *, int const *, int const *, float*, float*, float const *, uint3, int, int, int, int, int, uint3, uint3, int, int, int, uint3, uint3, int, int, int, uint3) + 0.00% 4.5550ms 34 133.97us 32.033us 198.02us void mul_mat_q(char const *, int const *, int const *, int const *, float*, float*, float const *, uint3, int, int, int, int, int, uint3, uint3, int, int, int, uint3, uint3, int, int, int, uint3) + 0.00% 4.4299ms 865 5.1210us 3.2640us 17.057us strata::kernels::copy_from_mapped_multi_kernel(strata::kernels::MappedCopies) + 0.00% 4.2614ms 216 19.728us 19.361us 20.193us void gdn_ab_multi_kernel(float const *, unsigned short const *, unsigned short const , float const , float const , float*, unsigned short const *, int, int, int) + 0.00% 3.9744ms 865 4.5940us 3.7440us 10.785us swiglu_quantize_q8_0_scaled_kernel(float*, __int64, unsigned char*, float*) + 0.00% 3.7185ms 460 8.0830us 6.8160us 20.641us logits_nonfinite_kernel(float const *, int, int, unsigned int*) + 0.00% 3.5315ms 963 3.6670us 3.1680us 4.7040us conv_residual_kernel(float const *, float const *, unsigned short const *, float const *, float const *, float*, float*) + 0.00% 3.2981ms 865 3.8120us 2.7840us 10.976us quantize_q8_0_scaled_kernel(float const *, unsigned char*, float*, __int64) + 0.00% 3.0594ms 48 63.737us 38.689us 80.067us void gr_down_multi_kernel(GrMulti) + 0.00% 2.8767ms 9 319.64us 128.36us 359.34us void mul_mat_q(char const *, int const *, int const *, int const *, float*, float*, float const *, uint3, int, int, int, int, int, uint3, uint3, int, int, int, uint3, uint3, int, int, int, uint3) + 0.00% 2.8028ms 221 12.682us 5.4720us 21.505us copy_row_to_first_kernel(int const *, float*, long, float*, long, float*, long) + 0.00% 2.5620ms 576 4.4470us 1.9200us 11.201us void apply(float const *, float*, int, int, int, float, float, float, float, float, float, int const *, int const , strata::kernels::RopeTab) + 0.00% 2.4951ms 865 2.8840us 2.2400us 8.1280us window_ids_kernel(int*, int, int*, __int64) + 0.00% 2.4254ms 216 11.228us 3.6800us 21.569us gdn_gates_kernel(float const *, float const *, float const *, float*, float*, long) + 0.00% 2.2568ms 282 8.0020us 5.4400us 23.297us copy_indexed_kernel(float*, float const *, long, int const *, long) + 0.00% 2.0714ms 1 2.0714ms 2.0714ms 2.0714ms void gather_rows_kernel(unsigned int const *, __int64, int const *, __int64, gather_rows_kernel*) + 0.00% 2.0578ms 963 2.1360us 1.8880us 2.4010us broadcast_kernel(float const *, float const *, float*) + 0.00% 1.8639ms 865 2.1540us 2.0480us 8.9280us map_ids_kernel(int*, int const *, int) + 0.00% 1.5668ms 8 195.85us 74.851us 275.60us void mul_mat_q(char const *, int const *, int const *, int const *, float*, float*, float const *, uint3, int, int, int, int, int, uint3, uint3, int, int, int, uint3, uint3, int, int, int, uint3) + 0.00% 1.3734ms 227 6.0500us 4.0640us 14.144us void norm(float const *, float const , float*, int, float) + 0.00% 1.2722ms 3 424.08us 393.07us 480.98us void mul_mat_q(char const *, int const *, int const *, int const *, float*, float*, float const *, uint3, int, int, int, int, int, uint3, uint3, int, int, int, uint3, uint3, int, int, int, uint3) + 0.00% 1.2578ms 460 2.7340us 2.4960us 3.3280us broadcast_streams_kernel(float const *, float*, long, int) + 0.00% 1.2074ms 8 150.93us 96.132us 168.30us void mul_mat_q(char const *, int const *, int const *, int const *, float*, float*, float const *, uint3, int, int, int, int, int, uint3, uint3, int, int, int, uint3, uint3, int, int, int, uint3) + 0.00% 1.2001ms 6 200.01us 35.362us 364.53us to_bf16_kernel(float const *, unsigned short*, unsigned short*, long) + 0.00% 1.1690ms 72 16.236us 3.5840us 32.162us void append_blocks(float const *, long, long, int, float const , float, float const , float const , float*, int*, long, long, float, float, float, float, float, float, int const *, strata::kernels::RopeTab) + 0.00% 1.0715ms 12 89.291us 27.969us 149.00us void mul_mat_q(char const *, int const *, int const *, int const *, float*, float*, float const *, uint3, int, int, int, int, int, uint3, uint3, int, int, int, uint3, uint3, int, int, int, uint3) + 0.00% 936.74us 12 78.062us 71.235us 84.548us void gr_up_multi_kernel(GrMulti) + 0.00% 891.56us 24 37.148us 22.849us 68.451us void native_mmvq_multi_kernel, int=6, int=4, int=2, bool=0, bool=0>(Q80BlockBlock const *, Q81Block const *, float*, int, int, Q80BlockBlock const , Q81Block const *) + 0.00% 859.56us 5 171.91us 62.307us 272.56us void mul_mat_q(char const *, int const *, int const *, int const *, float*, float*, float const *, uint3, int, int, int, int, int, uint3, uint3, int, int, int, uint3, uint3, int, int, int, uint3) + 0.00% 802.24us 3 267.41us 156.42us 323.34us void mul_mat_q(char const *, int const *, int const *, int const *, float*, float*, float const *, uint3, int, int, int, int, int, uint3, uint3, int, int, int, uint3, uint3, int, int, int, uint3) + 0.00% 794.62us 216 3.6780us 3.2640us 13.984us gdn_conv_hist_kernel(float*, float const *, long) + 0.00% 710.91us 5 142.18us 78.435us 236.36us void mul_mat_q(char const *, int const *, int const *, int const *, float*, float*, float const *, uint3, int, int, int, int, int, uint3, uint3, int, int, int, uint3, uint3, int, int, int, uint3) + 0.00% 671.04us 2 335.52us 309.39us 361.65us void mul_mat_q(char const *, int const *, int const *, int const *, float*, float*, float const *, uint3, int, int, int, int, int, uint3, uint3, int, int, int, uint3, uint3, int, int, int, uint3) + 0.00% 476.82us 6 79.470us 70.595us 88.068us void gr_up_multi_kernel(GrMulti) + 0.00% 359.05us 13 27.619us 18.432us 47.554us void mul_mat_q(char const *, int const *, int const *, int const *, float*, float*, float const *, uint3, int, int, int, int, int, uint3, uint3, int, int, int, uint3, uint3, int, int, int, uint3) + 0.00% 349.30us 7 49.899us 34.370us 91.396us void mul_mat_q(char const *, int const *, int const *, int const *, float*, float*, float const *, uint3, int, int, int, int, int, uint3, uint3, int, int, int, uint3, uint3, int, int, int, uint3) + 0.00% 347.79us 5 69.558us 41.826us 131.17us void mul_mat_q(char const *, int const *, int const *, int const *, float*, float*, float const *, uint3, int, int, int, int, int, uint3, uint3, int, int, int, uint3, uint3, int, int, int, uint3) + 0.00% 336.27us 6 56.045us 37.058us 95.268us void mul_mat_q(char const *, int const *, int const *, int const *, float*, float*, float const *, uint3, int, int, int, int, int, uint3, uint3, int, int, int, uint3, uint3, int, int, int, uint3) + 0.00% 260.24us 2 130.12us 113.51us 146.73us void mul_mat_q(char const *, int const *, int const *, int const *, float*, float*, float const *, uint3, int, int, int, int, int, uint3, uint3, int, int, int, uint3, uint3, int, int, int, uint3) + 0.00% 240.97us 96 2.5100us 2.2400us 5.2800us reset_kernel(strata::kernels::KvStreamMap) + 0.00% 231.14us 16 14.446us 12.320us 16.896us gr_norm_multi_kernel(GrMulti) + 0.00% 227.95us 3 75.982us 63.235us 90.244us void mul_mat_q(char const *, int const *, int const *, int const *, float*, float*, float const *, uint3, int, int, int, int, int, uint3, uint3, int, int, int, uint3, uint3, int, int, int, uint3) + 0.00% 196.62us 72 2.7300us 2.3680us 3.8720us void append_first(float const *, float const , float, float*, float const *, float, float, float, float, float, float, int const *, strata::kernels::RopeTab) + 0.00% 168.26us 3 56.088us 45.570us 72.643us void mul_mat_q(char const *, int const *, int const *, int const *, float*, float*, float const *, uint3, int, int, int, int, int, uint3, uint3, int, int, int, uint3, uint3, int, int, int, uint3) + 0.00% 151.49us 1 151.49us 151.49us 151.49us void mul_mat_q(char const *, int const *, int const *, int const *, float*, float*, float const *, uint3, int, int, int, int, int, uint3, uint3, int, int, int, uint3, uint3, int, int, int, uint3) + 0.00% 138.60us 72 1.9240us 1.5360us 2.7520us append_tail(float const *, long, long, float*) + 0.00% 104.32us 6 17.387us 16.609us 18.209us void dequant_q8_0_kernel(unsigned char const *, long, long, long, long, H16*) + 0.00% 102.73us 2 51.362us 40.930us 61.795us void mul_mat_q(char const *, int const *, int const *, int const *, float*, float*, float const *, uint3, int, int, int, int, int, uint3, uint3, int, int, int, uint3, uint3, int, int, int, uint3) + 0.00% 71.330us 2 35.665us 34.209us 37.121us gr_down_kernel(strata::kernels::FusedGrArgs) + 0.00% 68.996us 2 34.498us 31.682us 37.314us gr_up_kernel(strata::kernels::FusedGrArgs) + 0.00% 60.965us 6 10.160us 10.016us 10.305us history_batch_kernel(float*, float const *, int) + 0.00% 59.971us 2 29.985us 18.881us 41.090us void mul_mat_q(char const *, int const *, int const *, int const *, float*, float*, float const *, uint3, int, int, int, int, int, uint3, uint3, int, int, int, uint3, uint3, int, int, int, uint3) + 0.00% 22.304us 12 1.8580us 1.5680us 2.2400us iota_kernel(int*, long) + 0.00% 5.7280us 1 5.7280us 5.7280us 5.7280us ring_kernel(int*, __int64, __int64) + API calls: 72.73% 57.5789s 2311 24.915ms 925ns 486.64ms cudaStreamSynchronize + 12.65% 10.0172s 1 10.0172s 10.0172s 10.0172s cudaHostRegister + 3.25% 2.57530s 1613 1.5966ms 80.307us 12.039ms cudaGraphLaunch + 2.77% 2.19627s 9519 230.72us 6.3160us 92.873ms cudaMemcpy + 2.21% 1.75303s 102 17.187ms 3.6050us 333.57ms cudaHostAlloc + 1.76% 1.39535s 1 1.39535s 1.39535s 1.39535s cudaHostUnregister + 1.31% 1.03335s 75756 13.640us 2.1320us 11.684ms cudaMemcpyAsync + 0.79% 627.04ms 111034 5.6470us 1.0990us 5.1993ms cudaLaunchKernel + 0.67% 532.87ms 840 634.37us 2.3280us 16.214ms cuLibraryLoadData + 0.44% 349.49ms 152 2.2993ms 1.0720us 14.530ms cudaEventSynchronize + 0.41% 322.96ms 325 993.72us 3.3320us 105.07ms cudaFree + 0.17% 131.25ms 133532 982ns 577ns 932.01us cudaStreamQuery + 0.14% 112.54ms 109712 1.0250us 487ns 6.1790ms cudaEventRecord + 0.14% 111.56ms 33 3.3807ms 1.2690us 106.07ms cudaDeviceSynchronize + 0.11% 90.434ms 58 1.5592ms 2.6850us 41.455ms cudaFreeHost + 0.10% 80.396ms 85393 941ns 546ns 5.0005ms cudaStreamWaitEvent + 0.10% 77.039ms 13 5.9261ms 135.21us 18.463ms cudaGraphInstantiate + 0.06% 50.793ms 345 147.23us 5.0700us 7.1931ms cudaMalloc + 0.05% 39.806ms 11045 3.6030us 1.1590us 4.0262ms cudaMemsetAsync + 0.03% 26.792ms 56868 471ns 190ns 1.9371ms cudaGetDevice + 0.02% 18.994ms 13 1.4611ms 56.948us 3.5016ms cudaGraphExecDestroy + 0.02% 13.623ms 90989 149ns 88ns 914.77us cudaGetLastError + 0.01% 11.292ms 12 941.02us 36.599us 2.6578ms cudaGraphUpload + 0.01% 7.2248ms 1 7.2248ms 7.2248ms 7.2248ms cudaGetSymbolAddress + 0.01% 5.1335ms 13 394.88us 13.327us 1.5816ms cudaGraphDestroy + 0.00% 1.2095ms 13 93.040us 3.5320us 263.02us cudaStreamEndCapture + 0.00% 1.1356ms 276 4.1140us 1.0860us 32.397us cudaEventElapsedTime + 0.00% 944.11us 18 52.450us 10.075us 94.039us cudaMemGetInfo + 0.00% 714.45us 1082 660ns 316ns 18.403us cudaEventDestroy + 0.00% 692.30us 1076 643ns 396ns 18.055us cudaEventCreateWithFlags + 0.00% 465.17us 3 155.06us 127.32us 196.18us cudaGetDeviceProperties + 0.00% 426.85us 336 1.2700us 124ns 55.613us cuDeviceGetAttribute + 0.00% 374.09us 294 1.2720us 350ns 17.693us cudaOccupancyMaxActiveBlocksPerMultiprocessor + 0.00% 366.46us 10 36.646us 2.6200us 241.22us cudaStreamCreateWithFlags + 0.00% 259.89us 1 259.89us 259.89us 259.89us cudaLaunchHostFunc + 0.00% 239.12us 810 295ns 128ns 17.956us cuGetProcAddress + 0.00% 200.88us 85 2.3630us 836ns 20.574us cudaFuncSetAttribute + 0.00% 139.59us 5 27.918us 8.6910us 60.795us cudaMemset + 0.00% 114.41us 44 2.6000us 404ns 16.080us cudaHostGetDevicePointer + 0.00% 101.48us 4 25.369us 16.955us 34.216us cuDeviceGetName + 0.00% 86.476us 451 191ns 107ns 489ns cudaPeekAtLastError + 0.00% 64.638us 13 4.9720us 1.7100us 8.6090us cudaStreamBeginCapture + 0.00% 55.793us 7 7.9700us 2.8940us 15.221us cudaStreamDestroy + 0.00% 47.916us 50 958ns 209ns 17.301us cudaDeviceGetAttribute + 0.00% 43.809us 7 6.2580us 1.2000us 19.487us cudaOccupancyMaxActiveBlocksPerMultiprocessorWithFlags + 0.00% 22.746us 5 4.5490us 1.4480us 12.216us cudaSetDevice + 0.00% 18.421us 8 2.3020us 745ns 6.4930us cudaEventCreate + 0.00% 14.124us 1 14.124us 14.124us 14.124us cudaFuncGetAttributes + 0.00% 8.9660us 3 2.9880us 2.8230us 3.2960us cuInit + 0.00% 6.2470us 1 6.2470us 6.2470us 6.2470us cuDeviceGetPCIBusId + 0.00% 3.8420us 10 384ns 80ns 1.0980us cudaGetErrorString + 0.00% 2.2600us 2 1.1300us 558ns 1.7020us cudaGetDriverEntryPoint + 0.00% 1.8180us 3 606ns 517ns 707ns cuDeviceTotalMem + 0.00% 1.7590us 4 439ns 224ns 906ns cuDeviceGetCount + 0.00% 1.2580us 3 419ns 249ns 590ns cuModuleGetLoadingMode + 0.00% 897ns 5 179ns 143ns 232ns cuDeviceGet + 0.00% 726ns 3 242ns 215ns 269ns cuDeviceGetUuid + 0.00% 421ns 1 421ns 421ns 421ns cudaGetDeviceCount + 0.00% 381ns 2 190ns 184ns 197ns cuDriverGetVersion + 0.00% 333ns 1 333ns 333ns 333ns cudaRuntimeGetVersion diff --git a/bench/results/2026-10-12-p40-sm61-kernels/profile-base.txt b/bench/results/2026-10-12-p40-sm61-kernels/profile-base.txt new file mode 100644 index 00000000..82f00f22 --- /dev/null +++ b/bench/results/2026-10-12-p40-sm61-kernels/profile-base.txt @@ -0,0 +1,32 @@ +# a0116b2 unchanged, STRATA_PREFILL_TIMING=1 STRATA_DECODE_TIMING=1 STRATA_VERIFY_PROFILE=1: three short and three long requests +strata serve: prompt chunk auto: 8192 tokens, a 384-slot ring +strata prefill timing: 559 tokens, GPU timeline 2469 ms, wall 2476 ms, host staging 11 ms: embed+steps 0 (0.0%) hc read 177 (7.2%) gdn 587 (23.8%) qsa proj 253 (10.3%) qsa indexer 0 (0.0%) qsa select 1 (0.0%) qsa attn 31 (1.3%) router+shared 82 (3.3%) host grouping 126 (5.1%) gather 8 (0.3%) wait copy 39 (1.6%) dequant 139 (5.6%) gemm gate/up 527 (21.3%) gemm down 160 (6.5%) combine 57 (2.3%) ple 7 (0.3%) kv stage 0 (0.0%) gdn conv+gates 9 (0.3%) gdn recurrence 34 (1.4%) gdn out proj 231 (9.4%) +strata prefill timing: host: chunk setup (PLE rows, the expert stream plan) 0 ms, waiting for each chunk 10 ms, after each chunk (the draft layer, progress) 7 ms, PLE 53 ms +strata decode timing: 116 windows, avg T 2.14, 1.72 tokens/window, 56.22 ms/window = verify 49.54 (GPU-reach wait 35.56 + per-layer host 8.48 [plan 0.18 actq 0.20 jobs 0.07 CPU 7.43] + stage 0.58) + commit/emit 0.36 + draft 4.04; per layer-window: CPU experts 1.80 (2.37 entries), VRAM hits 17.57, PCIe 0.00 +strata decode GPU stages (ms/window): GDN layers: q8+qkv/q-idx gemv 4.24 conv 0.20 ab 0.36 z 2.50 rec 0.91 out-proj 2.79 router+plan+bell 1.53 shared+quant 2.23 waitA 1.14 VRAM hits 8.49 waitB 0.31 PCIe grp 0.27 waitCPU 2.50 copy+combine 0.57 (gap) 0.34 head 2.87 hc0 norm 0.65 hc0 down 1.43 hc0 up 1.30 hc1 norm 0.33 hc1 down 1.40 hc1 up 1.38 | QSA layers: q8+kv-idx 0.13 k/v+norm-rope 0.35 kv+idx append 0.17 q+q-idx 1.83 scores+topk 0.11 kv-resolve 0.17 attention 0.57 gate 0.05 out-proj 0.98 router+plan+bell 0.51 shared+quant 0.73 waitA 0.11 VRAM hits 2.67 waitB 0.11 PCIe grp 0.09 waitCPU 0.54 copy+combine 0.19 (gap) 0.11 hc0 norm 0.10 hc0 down 0.48 hc0 up 0.43 hc1 norm 0.11 hc1 down 0.47 hc1 up 0.46 | total 49.21 ms/window over 117 windows +strata serve: prompt 566 tokens = 0 reused + 566 read in 2742 ms (206.4 tok/s), 200 generated in 6522 ms (30.7 tok/s), drafts accepted 85 of 132, 1 checkpoints +strata prefill timing: 557 tokens, GPU timeline 2372 ms, wall 2378 ms, host staging 20 ms: embed+steps 1 (0.0%) hc read 176 (7.4%) gdn 583 (24.6%) qsa proj 254 (10.7%) qsa indexer 0 (0.0%) qsa select 1 (0.0%) qsa attn 31 (1.3%) router+shared 80 (3.4%) host grouping 113 (4.8%) gather 8 (0.4%) wait copy 45 (1.9%) dequant 131 (5.5%) gemm gate/up 474 (20.0%) gemm down 156 (6.6%) combine 40 (1.7%) ple 6 (0.3%) kv stage 0 (0.0%) gdn conv+gates 9 (0.4%) gdn recurrence 34 (1.4%) gdn out proj 230 (9.7%) +strata prefill timing: host: chunk setup (PLE rows, the expert stream plan) 1 ms, waiting for each chunk 12 ms, after each chunk (the draft layer, progress) 5 ms, PLE 53 ms +strata decode timing: 113 windows, avg T 2.05, 1.77 tokens/window, 52.66 ms/window = verify 47.92 (GPU-reach wait 39.99 + per-layer host 3.31 [plan 0.16 actq 0.14 jobs 0.03 CPU 2.41] + stage 0.56) + commit/emit 0.27 + draft 3.86; per layer-window: CPU experts 0.47 (0.54 entries), VRAM hits 19.44, PCIe 0.00 +strata decode GPU stages (ms/window): GDN layers: q8+qkv/q-idx gemv 4.17 conv 0.20 ab 0.36 z 2.46 rec 0.89 out-proj 2.74 router+plan+bell 1.50 shared+quant 2.21 waitA 1.18 VRAM hits 9.59 waitB 0.31 PCIe grp 0.27 waitCPU 0.93 copy+combine 0.49 (gap) 0.34 head 2.83 hc0 norm 0.64 hc0 down 1.42 hc0 up 1.28 hc1 norm 0.33 hc1 down 1.39 hc1 up 1.36 | QSA layers: q8+kv-idx 0.13 k/v+norm-rope 0.34 kv+idx append 0.17 q+q-idx 1.80 scores+topk 0.10 kv-resolve 0.17 attention 0.57 gate 0.05 out-proj 0.97 router+plan+bell 0.50 shared+quant 0.73 waitA 0.12 VRAM hits 3.06 waitB 0.11 PCIe grp 0.09 waitCPU 0.17 copy+combine 0.16 (gap) 0.11 hc0 norm 0.10 hc0 down 0.47 hc0 up 0.43 hc1 norm 0.11 hc1 down 0.46 hc1 up 0.45 | total 48.27 ms/window over 114 windows +strata serve: prompt 564 tokens = 0 reused + 564 read in 2667 ms (211.5 tok/s), 200 generated in 5951 ms (33.6 tok/s), drafts accepted 87 of 119, 1 checkpoints +strata prefill timing: 560 tokens, GPU timeline 2369 ms, wall 2375 ms, host staging 29 ms: embed+steps 1 (0.0%) hc read 177 (7.5%) gdn 583 (24.6%) qsa proj 253 (10.7%) qsa indexer 0 (0.0%) qsa select 1 (0.0%) qsa attn 31 (1.3%) router+shared 80 (3.4%) host grouping 106 (4.5%) gather 8 (0.4%) wait copy 34 (1.4%) dequant 133 (5.6%) gemm gate/up 477 (20.1%) gemm down 157 (6.6%) combine 48 (2.0%) ple 6 (0.3%) kv stage 0 (0.0%) gdn conv+gates 9 (0.4%) gdn recurrence 34 (1.4%) gdn out proj 230 (9.7%) +strata prefill timing: host: chunk setup (PLE rows, the expert stream plan) 1 ms, waiting for each chunk 13 ms, after each chunk (the draft layer, progress) 5 ms, PLE 53 ms +strata decode timing: 112 windows, avg T 2.19, 1.79 tokens/window, 53.39 ms/window = verify 48.87 (GPU-reach wait 42.04 + per-layer host 2.23 [plan 0.16 actq 0.10 jobs 0.02 CPU 1.37] + stage 0.56) + commit/emit 0.22 + draft 4.11; per layer-window: CPU experts 0.25 (0.29 entries), VRAM hits 21.24, PCIe 0.00 +strata decode GPU stages (ms/window): GDN layers: q8+qkv/q-idx gemv 4.28 conv 0.21 ab 0.37 z 2.52 rec 0.91 out-proj 2.80 router+plan+bell 1.49 shared+quant 2.25 waitA 1.11 VRAM hits 10.16 waitB 0.32 PCIe grp 0.27 waitCPU 0.68 copy+combine 0.47 (gap) 0.34 head 2.90 hc0 norm 0.66 hc0 down 1.44 hc0 up 1.30 hc1 norm 0.33 hc1 down 1.42 hc1 up 1.39 | QSA layers: q8+kv-idx 0.13 k/v+norm-rope 0.35 kv+idx append 0.17 q+q-idx 1.85 scores+topk 0.11 kv-resolve 0.17 attention 0.58 gate 0.05 out-proj 0.99 router+plan+bell 0.50 shared+quant 0.74 waitA 0.12 VRAM hits 3.21 waitB 0.11 PCIe grp 0.09 waitCPU 0.06 copy+combine 0.15 (gap) 0.11 hc0 norm 0.10 hc0 down 0.48 hc0 up 0.44 hc1 norm 0.11 hc1 down 0.47 hc1 up 0.46 | total 49.13 ms/window over 113 windows +strata serve: prompt 567 tokens = 0 reused + 567 read in 2654 ms (213.7 tok/s), 200 generated in 5980 ms (33.4 tok/s), drafts accepted 88 of 133, 1 checkpoints +strata prefill timing: 7038 tokens, GPU timeline 16005 ms, wall 16070 ms, host staging 79 ms: embed+steps 8 (0.1%) hc read 2046 (12.8%) gdn 3129 (19.6%) qsa proj 1363 (8.5%) qsa indexer 0 (0.0%) qsa select 122 (0.8%) qsa attn 1858 (11.6%) router+shared 583 (3.6%) host grouping 39 (0.2%) gather 147 (0.9%) wait copy 28 (0.2%) dequant 305 (1.9%) gemm gate/up 2567 (16.0%) gemm down 1204 (7.5%) combine 665 (4.2%) ple 69 (0.4%) kv stage 0 (0.0%) gdn conv+gates 105 (0.7%) gdn recurrence 443 (2.8%) gdn out proj 1324 (8.3%) +strata prefill timing: host: chunk setup (PLE rows, the expert stream plan) 7 ms, waiting for each chunk 73 ms, after each chunk (the draft layer, progress) 63 ms, PLE 449 ms +strata decode timing: 37 windows, avg T 1.86, 1.62 tokens/window, 50.87 ms/window = verify 47.09 (GPU-reach wait 41.50 + per-layer host 1.20 [plan 0.13 actq 0.06 jobs 0.02 CPU 0.84] + stage 0.14) + commit/emit 0.16 + draft 3.50; per layer-window: CPU experts 0.14 (0.14 entries), VRAM hits 18.26, PCIe 0.00 +strata decode GPU stages (ms/window): GDN layers: q8+qkv/q-idx gemv 4.10 conv 0.20 ab 0.35 z 2.43 rec 0.88 out-proj 2.70 router+plan+bell 1.48 shared+quant 2.19 waitA 1.10 VRAM hits 9.55 waitB 0.32 PCIe grp 0.27 waitCPU 0.32 copy+combine 0.45 (gap) 0.34 head 2.79 hc0 norm 0.64 hc0 down 1.42 hc0 up 1.27 hc1 norm 0.33 hc1 down 1.39 hc1 up 1.35 | QSA layers: q8+kv-idx 0.13 k/v+norm-rope 0.33 kv+idx append 0.17 q+q-idx 1.79 scores+topk 0.62 kv-resolve 0.43 attention 0.97 gate 0.05 out-proj 0.95 router+plan+bell 0.49 shared+quant 0.72 waitA 0.12 VRAM hits 3.06 waitB 0.11 PCIe grp 0.09 waitCPU 0.06 copy+combine 0.15 (gap) 0.11 hc0 norm 0.10 hc0 down 0.47 hc0 up 0.42 hc1 norm 0.11 hc1 down 0.46 hc1 up 0.45 | total 48.21 ms/window over 38 windows +strata serve: prompt 7045 tokens = 0 reused + 7045 read in 16672 ms (422.6 tok/s), 60 generated in 1882 ms (31.9 tok/s), drafts accepted 25 of 32, 1 checkpoints +strata prefill timing: 7039 tokens, GPU timeline 15730 ms, wall 15794 ms, host staging 130 ms: embed+steps 6 (0.0%) hc read 1989 (12.6%) gdn 3136 (19.9%) qsa proj 1367 (8.7%) qsa indexer 0 (0.0%) qsa select 122 (0.8%) qsa attn 1860 (11.8%) router+shared 590 (3.8%) host grouping 40 (0.3%) gather 147 (0.9%) wait copy 22 (0.1%) dequant 307 (2.0%) gemm gate/up 2601 (16.5%) gemm down 1223 (7.8%) combine 363 (2.3%) ple 71 (0.5%) kv stage 0 (0.0%) gdn conv+gates 105 (0.7%) gdn recurrence 447 (2.8%) gdn out proj 1334 (8.5%) +strata prefill timing: host: chunk setup (PLE rows, the expert stream plan) 6 ms, waiting for each chunk 73 ms, after each chunk (the draft layer, progress) 63 ms, PLE 449 ms +strata decode timing: 38 windows, avg T 1.87, 1.58 tokens/window, 52.52 ms/window = verify 48.44 (GPU-reach wait 41.42 + per-layer host 2.52 [plan 0.16 actq 0.08 jobs 0.02 CPU 1.28] + stage 0.96) + commit/emit 0.28 + draft 3.70; per layer-window: CPU experts 0.19 (0.20 entries), VRAM hits 18.22, PCIe 0.00 +strata decode GPU stages (ms/window): GDN layers: q8+qkv/q-idx gemv 4.09 conv 0.20 ab 0.35 z 2.42 rec 0.88 out-proj 2.69 router+plan+bell 1.48 shared+quant 2.19 waitA 1.43 VRAM hits 9.56 waitB 0.32 PCIe grp 0.27 waitCPU 1.27 copy+combine 0.46 (gap) 0.34 head 2.78 hc0 norm 0.63 hc0 down 1.42 hc0 up 1.26 hc1 norm 0.33 hc1 down 1.39 hc1 up 1.34 | QSA layers: q8+kv-idx 0.13 k/v+norm-rope 0.33 kv+idx append 0.17 q+q-idx 1.78 scores+topk 0.62 kv-resolve 0.42 attention 0.98 gate 0.05 out-proj 0.95 router+plan+bell 0.49 shared+quant 0.72 waitA 0.18 VRAM hits 3.04 waitB 0.11 PCIe grp 0.09 waitCPU 0.06 copy+combine 0.15 (gap) 0.11 hc0 norm 0.10 hc0 down 0.47 hc0 up 0.42 hc1 norm 0.11 hc1 down 0.46 hc1 up 0.45 | total 49.49 ms/window over 39 windows +strata serve: prompt 7046 tokens = 0 reused + 7046 read in 16450 ms (428.3 tok/s), 60 generated in 1996 ms (30.1 tok/s), drafts accepted 22 of 33, 1 checkpoints +strata prefill timing: 7039 tokens, GPU timeline 15732 ms, wall 15796 ms, host staging 179 ms: embed+steps 3 (0.0%) hc read 1989 (12.6%) gdn 3141 (20.0%) qsa proj 1367 (8.7%) qsa indexer 0 (0.0%) qsa select 123 (0.8%) qsa attn 1860 (11.8%) router+shared 590 (3.8%) host grouping 39 (0.2%) gather 147 (0.9%) wait copy 24 (0.2%) dequant 307 (1.9%) gemm gate/up 2596 (16.5%) gemm down 1222 (7.8%) combine 363 (2.3%) ple 70 (0.4%) kv stage 0 (0.0%) gdn conv+gates 105 (0.7%) gdn recurrence 449 (2.9%) gdn out proj 1336 (8.5%) +strata prefill timing: host: chunk setup (PLE rows, the expert stream plan) 3 ms, waiting for each chunk 75 ms, after each chunk (the draft layer, progress) 63 ms, PLE 449 ms +strata decode timing: 39 windows, avg T 1.87, 1.54 tokens/window, 51.93 ms/window = verify 47.94 (GPU-reach wait 41.20 + per-layer host 2.13 [plan 0.17 actq 0.08 jobs 0.02 CPU 1.16] + stage 0.67) + commit/emit 0.19 + draft 3.67; per layer-window: CPU experts 0.17 (0.18 entries), VRAM hits 18.31, PCIe 0.00 +strata decode GPU stages (ms/window): GDN layers: q8+qkv/q-idx gemv 4.09 conv 0.20 ab 0.35 z 2.42 rec 0.88 out-proj 2.70 router+plan+bell 1.48 shared+quant 2.19 waitA 1.23 VRAM hits 9.60 waitB 0.32 PCIe grp 0.27 waitCPU 0.91 copy+combine 0.45 (gap) 0.34 head 2.78 hc0 norm 0.63 hc0 down 1.42 hc0 up 1.27 hc1 norm 0.33 hc1 down 1.38 hc1 up 1.34 | QSA layers: q8+kv-idx 0.13 k/v+norm-rope 0.33 kv+idx append 0.17 q+q-idx 1.78 scores+topk 0.63 kv-resolve 0.42 attention 0.97 gate 0.05 out-proj 0.95 router+plan+bell 0.49 shared+quant 0.72 waitA 0.12 VRAM hits 3.06 waitB 0.11 PCIe grp 0.09 waitCPU 0.13 copy+combine 0.15 (gap) 0.11 hc0 norm 0.10 hc0 down 0.47 hc0 up 0.42 hc1 norm 0.11 hc1 down 0.46 hc1 up 0.45 | total 48.99 ms/window over 40 windows +strata serve: prompt 7046 tokens = 0 reused + 7046 read in 16437 ms (428.7 tok/s), 60 generated in 2025 ms (29.6 tok/s), drafts accepted 21 of 34, 1 checkpoints diff --git a/bench/results/2026-10-12-p40-sm61-kernels/profile-new.txt b/bench/results/2026-10-12-p40-sm61-kernels/profile-new.txt new file mode 100644 index 00000000..320c6891 --- /dev/null +++ b/bench/results/2026-10-12-p40-sm61-kernels/profile-new.txt @@ -0,0 +1,32 @@ +# the change with the GEMM route on, the same switches and requests +strata serve: prompt chunk auto: 8192 tokens, a 384-slot ring +strata prefill timing: 560 tokens, GPU timeline 1904 ms, wall 1911 ms, host staging 11 ms: embed+steps 4 (0.2%) hc read 175 (9.2%) gdn 257 (13.5%) qsa proj 116 (6.1%) qsa indexer 0 (0.0%) qsa select 1 (0.0%) qsa attn 31 (1.6%) router+shared 70 (3.7%) host grouping 147 (7.7%) gather 9 (0.4%) wait copy 42 (2.2%) dequant 139 (7.3%) gemm gate/up 524 (27.5%) gemm down 160 (8.4%) combine 77 (4.0%) ple 6 (0.3%) kv stage 0 (0.0%) gdn conv+gates 9 (0.5%) gdn recurrence 34 (1.8%) gdn out proj 103 (5.4%) +strata prefill timing: host: chunk setup (PLE rows, the expert stream plan) 4 ms, waiting for each chunk 12 ms, after each chunk (the draft layer, progress) 7 ms, PLE 73 ms +strata decode timing: 110 windows, avg T 2.14, 1.82 tokens/window, 54.70 ms/window = verify 47.64 (GPU-reach wait 32.24 + per-layer host 9.72 [plan 0.22 actq 0.24 jobs 0.07 CPU 8.81] + stage 0.35) + commit/emit 0.39 + draft 4.08; per layer-window: CPU experts 1.77 (2.32 entries), VRAM hits 17.56, PCIe 0.00 +strata decode GPU stages (ms/window): GDN layers: q8+qkv/q-idx gemv 3.86 conv 0.21 ab 0.36 z 2.21 rec 0.91 out-proj 2.75 router+plan+bell 1.52 shared+quant 2.23 waitA 1.37 VRAM hits 6.39 waitB 0.32 PCIe grp 0.30 waitCPU 2.98 copy+combine 0.56 (gap) 0.32 head 2.45 hc0 norm 0.65 hc0 down 1.44 hc0 up 1.29 hc1 norm 0.34 hc1 down 1.40 hc1 up 1.38 | QSA layers: q8+kv-idx 0.12 k/v+norm-rope 0.37 kv+idx append 0.17 q+q-idx 1.59 scores+topk 0.11 kv-resolve 0.17 attention 0.58 gate 0.05 out-proj 0.97 router+plan+bell 0.51 shared+quant 0.73 waitA 0.12 VRAM hits 2.09 waitB 0.10 PCIe grp 0.10 waitCPU 1.40 copy+combine 0.19 (gap) 0.10 hc0 norm 0.10 hc0 down 0.48 hc0 up 0.43 hc1 norm 0.11 hc1 down 0.47 hc1 up 0.46 | total 46.77 ms/window over 111 windows +strata serve: prompt 567 tokens = 0 reused + 567 read in 2157 ms (262.9 tok/s), 200 generated in 6017 ms (33.2 tok/s), drafts accepted 91 of 125, 1 checkpoints +strata prefill timing: 559 tokens, GPU timeline 1971 ms, wall 1977 ms, host staging 28 ms: embed+steps 0 (0.0%) hc read 175 (8.9%) gdn 256 (13.0%) qsa proj 113 (5.7%) qsa indexer 0 (0.0%) qsa select 1 (0.0%) qsa attn 31 (1.6%) router+shared 69 (3.5%) host grouping 134 (6.8%) gather 9 (0.4%) wait copy 53 (2.7%) dequant 138 (7.0%) gemm gate/up 497 (25.2%) gemm down 161 (8.2%) combine 184 (9.3%) ple 6 (0.3%) kv stage 0 (0.0%) gdn conv+gates 9 (0.4%) gdn recurrence 34 (1.7%) gdn out proj 101 (5.1%) +strata prefill timing: host: chunk setup (PLE rows, the expert stream plan) 0 ms, waiting for each chunk 11 ms, after each chunk (the draft layer, progress) 6 ms, PLE 73 ms +strata decode timing: 112 windows, avg T 2.21, 1.79 tokens/window, 50.26 ms/window = verify 45.34 (GPU-reach wait 37.54 + per-layer host 3.39 [plan 0.20 actq 0.19 jobs 0.03 CPU 2.15] + stage 0.80) + commit/emit 0.36 + draft 4.08; per layer-window: CPU experts 0.44 (0.51 entries), VRAM hits 21.02, PCIe 0.00 +strata decode GPU stages (ms/window): GDN layers: q8+qkv/q-idx gemv 3.87 conv 0.21 ab 0.37 z 2.22 rec 0.91 out-proj 2.78 router+plan+bell 1.51 shared+quant 2.24 waitA 1.75 VRAM hits 7.48 waitB 0.32 PCIe grp 0.30 waitCPU 1.10 copy+combine 0.49 (gap) 0.32 head 2.45 hc0 norm 0.66 hc0 down 1.45 hc0 up 1.30 hc1 norm 0.34 hc1 down 1.41 hc1 up 1.40 | QSA layers: q8+kv-idx 0.13 k/v+norm-rope 0.37 kv+idx append 0.17 q+q-idx 1.60 scores+topk 0.11 kv-resolve 0.17 attention 0.58 gate 0.05 out-proj 0.98 router+plan+bell 0.50 shared+quant 0.74 waitA 0.18 VRAM hits 2.46 waitB 0.11 PCIe grp 0.10 waitCPU 0.11 copy+combine 0.16 (gap) 0.10 hc0 norm 0.10 hc0 down 0.48 hc0 up 0.44 hc1 norm 0.11 hc1 down 0.47 hc1 up 0.47 | total 45.58 ms/window over 113 windows +strata serve: prompt 566 tokens = 0 reused + 566 read in 2258 ms (250.7 tok/s), 200 generated in 5629 ms (35.5 tok/s), drafts accepted 90 of 135, 1 checkpoints +strata prefill timing: 560 tokens, GPU timeline 1799 ms, wall 1805 ms, host staging 43 ms: embed+steps 0 (0.0%) hc read 175 (9.7%) gdn 257 (14.3%) qsa proj 112 (6.2%) qsa indexer 0 (0.0%) qsa select 1 (0.0%) qsa attn 31 (1.7%) router+shared 68 (3.8%) host grouping 142 (7.9%) gather 9 (0.5%) wait copy 46 (2.6%) dequant 133 (7.4%) gemm gate/up 477 (26.5%) gemm down 157 (8.7%) combine 39 (2.2%) ple 6 (0.4%) kv stage 0 (0.0%) gdn conv+gates 9 (0.5%) gdn recurrence 34 (1.9%) gdn out proj 103 (5.7%) +strata prefill timing: host: chunk setup (PLE rows, the expert stream plan) 0 ms, waiting for each chunk 12 ms, after each chunk (the draft layer, progress) 5 ms, PLE 73 ms +strata decode timing: 109 windows, avg T 2.24, 1.83 tokens/window, 49.29 ms/window = verify 44.71 (GPU-reach wait 38.14 + per-layer host 2.30 [plan 0.20 actq 0.12 jobs 0.02 CPU 1.39] + stage 0.55) + commit/emit 0.28 + draft 4.03; per layer-window: CPU experts 0.26 (0.30 entries), VRAM hits 21.71, PCIe 0.00 +strata decode GPU stages (ms/window): GDN layers: q8+qkv/q-idx gemv 3.89 conv 0.21 ab 0.37 z 2.23 rec 0.92 out-proj 2.80 router+plan+bell 1.50 shared+quant 2.25 waitA 1.20 VRAM hits 7.69 waitB 0.32 PCIe grp 0.30 waitCPU 0.73 copy+combine 0.47 (gap) 0.32 head 2.45 hc0 norm 0.66 hc0 down 1.45 hc0 up 1.31 hc1 norm 0.34 hc1 down 1.42 hc1 up 1.41 | QSA layers: q8+kv-idx 0.13 k/v+norm-rope 0.38 kv+idx append 0.17 q+q-idx 1.60 scores+topk 0.11 kv-resolve 0.17 attention 0.58 gate 0.05 out-proj 0.99 router+plan+bell 0.50 shared+quant 0.74 waitA 0.13 VRAM hits 2.52 waitB 0.11 PCIe grp 0.10 waitCPU 0.10 copy+combine 0.15 (gap) 0.10 hc0 norm 0.10 hc0 down 0.49 hc0 up 0.44 hc1 norm 0.11 hc1 down 0.48 hc1 up 0.47 | total 44.96 ms/window over 110 windows +strata serve: prompt 567 tokens = 0 reused + 567 read in 2101 ms (269.9 tok/s), 200 generated in 5373 ms (37.2 tok/s), drafts accepted 92 of 135, 1 checkpoints +strata prefill timing: 7042 tokens, GPU timeline 14615 ms, wall 14679 ms, host staging 95 ms: embed+steps 8 (0.1%) hc read 2029 (13.9%) gdn 2447 (16.7%) qsa proj 1139 (7.8%) qsa indexer 0 (0.0%) qsa select 112 (0.8%) qsa attn 1767 (12.1%) router+shared 530 (3.6%) host grouping 41 (0.3%) gather 147 (1.0%) wait copy 21 (0.1%) dequant 307 (2.1%) gemm gate/up 2515 (17.2%) gemm down 1162 (8.0%) combine 670 (4.6%) ple 67 (0.5%) kv stage 0 (0.0%) gdn conv+gates 106 (0.7%) gdn recurrence 415 (2.8%) gdn out proj 1131 (7.7%) +strata prefill timing: host: chunk setup (PLE rows, the expert stream plan) 7 ms, waiting for each chunk 71 ms, after each chunk (the draft layer, progress) 63 ms, PLE 475 ms +strata decode timing: 37 windows, avg T 2.03, 1.62 tokens/window, 48.39 ms/window = verify 44.15 (GPU-reach wait 38.54 + per-layer host 1.57 [plan 0.15 actq 0.06 jobs 0.02 CPU 0.97] + stage 0.36) + commit/emit 0.22 + draft 3.74; per layer-window: CPU experts 0.18 (0.19 entries), VRAM hits 19.79, PCIe 0.00 +strata decode GPU stages (ms/window): GDN layers: q8+qkv/q-idx gemv 3.88 conv 0.21 ab 0.36 z 2.23 rec 0.90 out-proj 2.75 router+plan+bell 1.49 shared+quant 2.22 waitA 1.02 VRAM hits 7.42 waitB 0.32 PCIe grp 0.30 waitCPU 0.53 copy+combine 0.46 (gap) 0.32 head 2.48 hc0 norm 0.65 hc0 down 1.45 hc0 up 1.30 hc1 norm 0.34 hc1 down 1.41 hc1 up 1.39 | QSA layers: q8+kv-idx 0.13 k/v+norm-rope 0.37 kv+idx append 0.18 q+q-idx 1.61 scores+topk 0.64 kv-resolve 0.43 attention 1.02 gate 0.05 out-proj 0.96 router+plan+bell 0.50 shared+quant 0.73 waitA 0.12 VRAM hits 2.44 waitB 0.11 PCIe grp 0.10 waitCPU 0.07 copy+combine 0.15 (gap) 0.10 hc0 norm 0.10 hc0 down 0.49 hc0 up 0.44 hc1 norm 0.11 hc1 down 0.47 hc1 up 0.46 | total 45.19 ms/window over 38 windows +strata serve: prompt 7049 tokens = 0 reused + 7049 read in 15293 ms (460.9 tok/s), 60 generated in 1790 ms (33.5 tok/s), drafts accepted 23 of 38, 1 checkpoints +strata prefill timing: 7042 tokens, GPU timeline 14264 ms, wall 14328 ms, host staging 143 ms: embed+steps 6 (0.0%) hc read 1973 (13.8%) gdn 2450 (17.2%) qsa proj 1153 (8.1%) qsa indexer 0 (0.0%) qsa select 112 (0.8%) qsa attn 1770 (12.4%) router+shared 532 (3.7%) host grouping 40 (0.3%) gather 147 (1.0%) wait copy 24 (0.2%) dequant 306 (2.1%) gemm gate/up 2496 (17.5%) gemm down 1165 (8.2%) combine 362 (2.5%) ple 68 (0.5%) kv stage 0 (0.0%) gdn conv+gates 105 (0.7%) gdn recurrence 417 (2.9%) gdn out proj 1138 (8.0%) +strata prefill timing: host: chunk setup (PLE rows, the expert stream plan) 6 ms, waiting for each chunk 71 ms, after each chunk (the draft layer, progress) 63 ms, PLE 475 ms +strata decode timing: 36 windows, avg T 2.00, 1.67 tokens/window, 48.02 ms/window = verify 44.10 (GPU-reach wait 38.67 + per-layer host 1.41 [plan 0.14 actq 0.06 jobs 0.02 CPU 0.95] + stage 0.23) + commit/emit 0.16 + draft 3.73; per layer-window: CPU experts 0.17 (0.17 entries), VRAM hits 19.58, PCIe 0.00 +strata decode GPU stages (ms/window): GDN layers: q8+qkv/q-idx gemv 3.88 conv 0.21 ab 0.36 z 2.23 rec 0.90 out-proj 2.74 router+plan+bell 1.49 shared+quant 2.22 waitA 1.02 VRAM hits 7.51 waitB 0.32 PCIe grp 0.30 waitCPU 0.42 copy+combine 0.45 (gap) 0.32 head 2.49 hc0 norm 0.65 hc0 down 1.45 hc0 up 1.30 hc1 norm 0.34 hc1 down 1.41 hc1 up 1.38 | QSA layers: q8+kv-idx 0.13 k/v+norm-rope 0.36 kv+idx append 0.18 q+q-idx 1.61 scores+topk 0.64 kv-resolve 0.44 attention 1.02 gate 0.05 out-proj 0.96 router+plan+bell 0.50 shared+quant 0.73 waitA 0.12 VRAM hits 2.48 waitB 0.11 PCIe grp 0.10 waitCPU 0.08 copy+combine 0.15 (gap) 0.10 hc0 norm 0.10 hc0 down 0.48 hc0 up 0.44 hc1 norm 0.11 hc1 down 0.47 hc1 up 0.46 | total 45.19 ms/window over 37 windows +strata serve: prompt 7049 tokens = 0 reused + 7049 read in 14979 ms (470.6 tok/s), 60 generated in 1729 ms (34.7 tok/s), drafts accepted 24 of 36, 1 checkpoints +strata prefill timing: 7039 tokens, GPU timeline 14315 ms, wall 14379 ms, host staging 193 ms: embed+steps 6 (0.0%) hc read 1940 (13.5%) gdn 2449 (17.1%) qsa proj 1154 (8.1%) qsa indexer 0 (0.0%) qsa select 113 (0.8%) qsa attn 1776 (12.4%) router+shared 548 (3.8%) host grouping 41 (0.3%) gather 147 (1.0%) wait copy 21 (0.1%) dequant 311 (2.2%) gemm gate/up 2546 (17.8%) gemm down 1167 (8.2%) combine 361 (2.5%) ple 66 (0.5%) kv stage 0 (0.0%) gdn conv+gates 105 (0.7%) gdn recurrence 419 (2.9%) gdn out proj 1146 (8.0%) +strata prefill timing: host: chunk setup (PLE rows, the expert stream plan) 6 ms, waiting for each chunk 71 ms, after each chunk (the draft layer, progress) 63 ms, PLE 475 ms +strata decode timing: 37 windows, avg T 1.95, 1.62 tokens/window, 47.57 ms/window = verify 43.70 (GPU-reach wait 38.33 + per-layer host 1.22 [plan 0.14 actq 0.05 jobs 0.02 CPU 0.97] + stage 0.01) + commit/emit 0.18 + draft 3.68; per layer-window: CPU experts 0.16 (0.16 entries), VRAM hits 19.07, PCIe 0.00 +strata decode GPU stages (ms/window): GDN layers: q8+qkv/q-idx gemv 3.86 conv 0.21 ab 0.36 z 2.22 rec 0.89 out-proj 2.73 router+plan+bell 1.48 shared+quant 2.20 waitA 1.18 VRAM hits 7.37 waitB 0.32 PCIe grp 0.30 waitCPU 0.33 copy+combine 0.45 (gap) 0.32 head 2.48 hc0 norm 0.64 hc0 down 1.44 hc0 up 1.28 hc1 norm 0.34 hc1 down 1.40 hc1 up 1.37 | QSA layers: q8+kv-idx 0.12 k/v+norm-rope 0.36 kv+idx append 0.18 q+q-idx 1.60 scores+topk 0.63 kv-resolve 0.43 attention 1.00 gate 0.05 out-proj 0.95 router+plan+bell 0.49 shared+quant 0.73 waitA 0.13 VRAM hits 2.43 waitB 0.11 PCIe grp 0.10 waitCPU 0.10 copy+combine 0.15 (gap) 0.10 hc0 norm 0.10 hc0 down 0.48 hc0 up 0.43 hc1 norm 0.11 hc1 down 0.47 hc1 up 0.46 | total 44.87 ms/window over 38 windows +strata serve: prompt 7046 tokens = 0 reused + 7046 read in 15010 ms (469.4 tok/s), 60 generated in 1760 ms (34.1 tok/s), drafts accepted 23 of 35, 1 checkpoints diff --git a/docs/COMMUNITY_BENCHMARKS.md b/docs/COMMUNITY_BENCHMARKS.md index c11e5b7e..13d016c9 100644 --- a/docs/COMMUNITY_BENCHMARKS.md +++ b/docs/COMMUNITY_BENCHMARKS.md @@ -53,6 +53,9 @@ and their limits. Report what you actually measured and label estimates separate Strata 0.1.40.3 prebuilt Windows HIP engine, Flash-Next IQ2_XS and IQ3_XXS: a prefill-size sweep (8,192 best), a matched 32K coding comparison (9/9 tasks each, IQ2_XS about 17% faster decode), one 113K recall request. Sanitized data, fixtures and scripts included. - [2026-10-10: 2x Tesla P40 24 GB, Xeon E5-2699 v3, 125 GB RAM](../bench/results/2026-10-10-community-2x-p40-iq3_s/README.md): Strata 0.1.41 CUDA 12 source build (sm_61), Flash-Next IQ3_S, 131,072-token context, layer split; decode 35.0 tok/s, prompt 350/558 tok/s at 3.9K/21.9K, needles 6/6, conversation checkpoints. +- [2026-10-12: Tesla P40 24 GB (sm_61), 20 vCPUs of a Xeon E5-2695 v4 without AVX-512, 98 GB RAM](../bench/results/2026-10-12-p40-sm61-kernels/README.md): + Strata `a0116b2` (0.1.43.1) CUDA 12.4 source build, Flash-Next IQ3_S, 262,144-token context, the profile of a prompt and of a decode window on Pascal and four bitwise changes for sm_61: + a 565-token prompt 205 -> 255 tok/s, decode 34-35 -> 37-38 tok/s, and with the opt-in `STRATA_DENSE_F32=1` a 7K prompt 360-432 -> 464-474 tok/s. Short and 7K prompts only; cuBLAS 12.4 only. - [2026-10-09: RTX 5060 Ti 16 GB + Xeon E5-2680 v4 (Windows 10)](../bench/results/2026-10-09-community-rtx-5060-ti-e5-2680-v4/README.md): Strata 0.1.41, Coder IQ1_M and abliterated Q2_0 at 262K; prompt and decode at 4K / 32K / 128K. - [2026-10-09: RTX 5060 Ti 16 GB under WSL2, Ryzen 7 3700X, 128 GB RAM](../bench/results/2026-10-09-community-rtx-5060ti-wsl2-iq3_s-0141/README.md): diff --git a/docs/OLDER_GPUS.md b/docs/OLDER_GPUS.md index 558d24e0..dc811c9b 100644 --- a/docs/OLDER_GPUS.md +++ b/docs/OLDER_GPUS.md @@ -12,7 +12,7 @@ and their output stay exactly as they were. Numbers are the reporters' own, on o | Cards | Compute capability | How it runs | What is different on it | Reported | | --- | --- | --- | --- | --- | | Tesla P100 | 6.0 | the CUDA 12 engine | `__dp4a` emulated (bit-exact); BF16 projections through fp32 | 2x P100, IQ3_S, engine 0.1.39: prompt 526-532 tok/s, decode 28-32 tok/s at 128K prompt tokens, 3 of 3 needle checks at 122K ([report](../bench/results/2026-10-06-community-2x-p100/README.md), #1157) | -| Tesla P40 / P4, GTX 10 series | 6.1 | the CUDA 12 engine | BF16 projections through fp32 (cuBLAS has no BF16 GEMM there, #395) | P40, IQ3_S, engine 0.1.30: prompt 217-374 tok/s, decode 30-33 tok/s (#395) | +| Tesla P40 / P4, GTX 10 series | 6.1 | the CUDA 12 engine | BF16 projections through fp32 (cuBLAS has no BF16 GEMM there, #395); the dense weights dequantized by a wide kernel, expert mode 8 and its own interleaved-matvec table; opt-in `STRATA_DENSE_F32=1`: the large dense GEMMs as `cublasSgemm` ([below](#tesla-p40-sm_61-what-was-measured-and-changed)) | P40, IQ3_S, engine 0.1.30: prompt 217-374 tok/s, decode 30-33 tok/s (#395); 0.1.43.1 with the sm_61 changes: prompt 255 tok/s at 565 tokens (was 205), decode 37-38 tok/s (was 34-35); with `STRATA_DENSE_F32=1` 464-474 tok/s at 7K tokens (was 360-432) | | Tesla V100, Titan V | 7.0 | the CUDA 12 engine | BF16 projections on the FP16 tensor cores (#655, #540); the prompt attention on `mma.m8n8k4` (#600); a leaner attention kernel (#540) | V100-PCIE-32GB, UD-IQ4_XS: prompt 1,123-1,251 tok/s (#600); V100 32GB, IQ2_XS: prompt +22% from #540 | | RTX 20 (Turing) | 7.5 | **supported**, the ready-made engine | opt-in: `STRATA_BF16_TC=1` runs the BF16 projections on the FP16 tensor cores | RTX 2080 Ti, Q2_0: prompt +15-18% (#655) | @@ -95,10 +95,58 @@ sums round differently): #540 measured a mean KL of 8.4e-3 on the next-token dis (the same top-1 in 23), the size of other summation-order changes; #655 a worst relative difference of 3.5e-5 per product on an RTX 2080 Ti. -A/B switches: `STRATA_BF16_TC=0|1`, `STRATA_PROMPT_ATTN_OLD=1` (the decode kernel for prompts), `STRATA_ATTN_PRE75=0` +A/B switches: `STRATA_DEQUANT_WIDE=0`, `STRATA_SM61_TABLE=0` (sm_61: the kernels 0.1.43.1 ran), `STRATA_DENSE_F32=1` (Pascal, opt-in), +`STRATA_BF16_TC=0|1`, `STRATA_PROMPT_ATTN_OLD=1` (the decode kernel for prompts), `STRATA_ATTN_PRE75=0` (#540's kernel off; on gfx103x with HIP that kernel is the default, see the AMD table above, and `=1` turns it on for another wave32 AMD card). [NVIDIA_V100.md](NVIDIA_V100.md) has the V100 build, its measurements and the parity test. +### Tesla P40 (sm_61): what was measured and changed + +One Tesla P40 24 GB in a 20-vCPU VM (Xeon E5-2695 v4, 98 GB RAM), CUDA 12.4 (cuBLAS 12.4.5.8), IQ3_S with MTP +(`--spec 4`), int8 KV, `--max-context 262144`, engine 0.1.43.1; the numbers and every run are in +[bench/results/2026-10-12-p40-sm61-kernels](../bench/results/2026-10-12-p40-sm61-kernels/README.md). +`STRATA_PREFILL_TIMING=1`, `STRATA_DECODE_TIMING=1` and `STRATA_VERIFY_PROFILE=1` show a card that is the bottleneck +everywhere: the prompt's GPU timeline equals its wall time (waiting for expert copies 0.2%, host grouping 0.2% of a +7K-token prompt) and a decode window is 49 ms of GPU stages with 1-3 ms of CPU experts. Of a 7K-token prompt, 36% is +the dense projections' GEMMs, 28% the experts (ggml's MMQ, which has its own Pascal dp4a configuration), 13% the +hyper-connection read and 12% the attention. + +Three things run differently on compute capability 6.1 by default and a fourth is opt-in. Each gives the same bits as +what it replaces: + +| Change | What it replaces | Measured on the P40 | Switch | +| --- | --- | --- | --- | +| Wide dequantization (a thread per 8 values, 16-bit loads, 16-byte stores) for Q4_K / Q5_K / Q6_K / IQ4_XS | a thread per 32 values with byte loads: 0.5 s of every prompt chunk, whatever its length | Q6_K 10240 x 2560: 7.2 -> 0.33 ms (10 -> 227 GB/s); Q4_K 5.2x, Q5_K 3.8x, IQ4_XS 3.6x; `dequant_wide_parity` 360 cases bitwise | on; `STRATA_DEQUANT_WIDE=0` | +| Expert mode 8 for the experts in VRAM (decode and verify windows) | the CUDA layout | an 18-expert call at 2 tokens: IQ3_S 390 -> 255 us, IQ3_XXS 345 -> 252, IQ2_S 290 -> 238, IQ4_XS 328 -> 261; `native_expert_bench` bitwise | on; `STRATA_SM61_TABLE=0` (or `STRATA_EXP_MODE=0`) | +| The interleaved small-batch matvec with a table measured on the P40 (`kIlRows_61`) | `native_mmvq` | IQ4_XS 2560 x 10240 at 2 columns 112 -> 65 us, Q6_K 12288 x 2560 at 4 columns 189 -> 127 us, the Q5_K head at 3 columns 2,545 -> 1,766 us; `mmvq_il_parity` bitwise | on; `STRATA_SM61_TABLE=0` (or `STRATA_MMVQ_IL=0`) | +| The large dense GEMMs (qkv, query, gate, output projections) as `cublasSgemm` on FP32 copies of the FP16 operands | cuBLAS's FP16-operand kernels, which run at 4.3 TFLOPS instead of 7.6 for most chunk sizes (a 7K-token prompt reads in 16.3 or 19.5 s by its exact token count) | 8.4-9.8 TFLOPS at every size from 512 tokens; qkv at 7,041 tokens 85 -> 45 ms; `gemm_f32_parity` 5,201 chunk sizes bitwise | **opt-in**, `STRATA_DENSE_F32=1` | + +The GEMM route is opt-in because its equality is a property of the cuBLAS build, not of the code: it was measured with +cuBLAS 12.4.5.8 only. Run `gemm_f32_parity` (a build with `-DSTRATA_BUILD_TESTS=ON`; exit 0 = every size bitwise) with +your toolkit's library before you set it. + +Through the server, medians of 3 requests per run, two runs per build alternated, each run started with the card at +65 C (see below). By default: a 565-token prompt 203 / 205 -> 256 / 255 tok/s, decode after it 35.0 / 34.2 -> 38.2 / +37.2 tok/s, a 7,047-token prompt 1-3% faster at the same token count. With `STRATA_DENSE_F32=1` as well: the +7,047-token prompt 430 / 364 -> 474 / 473 tok/s (the old build reads it at ~361 or ~431 tok/s depending on whether the +chunk has more than 7,040 tokens; with the route every request read at 464-474), decode after it 32.1 / 33.4 -> 35.9 / +34.0. With `STRATA_DEQUANT_WIDE=0 STRATA_SM61_TABLE=0` and the route off the new build measures as the old one (210 / +365 tok/s, 33.3 tok/s). + +Measured and **not** changed: the latency-hidden hyper-connection read (`STRATA_GR_FAST=1`) is slower on the P40 below +5 tokens (82 -> 88 us at one); `STRATA_PREFILL_CPU_SHARE=auto` and `STRATA_ADAPT_OVERLAP=1` gave nothing. + +Two things to know when measuring on such a card: + +- **Temperature.** A P40 has no fan of its own. This one reaches 87-89 C in a few minutes of work; at 89 C the driver + reports `SW Thermal Slowdown: Active` and the clock falls from 1,531 to ~1,300 MHz (`nvidia-smi -q -d PERFORMANCE`, + `nvidia-smi --query-gpu=temperature.gpu,clocks.gr --format=csv -l 2`). Start every arm of an A/B at the same + temperature, or the later arm loses. +- **Greedy answers are not identical run to run on a CPU without AVX-512**, even with `--prompt-cache 0 + --adapt-swaps 0 --pcie-frac 0`: an expert computed on the CPU rounds differently for a lone token than in a window + of several (`native_gu_mt_min`), and how many drafts a window holds depends on timing. Add `STRATA_IQ_MT_MIN=1` + (and `STRATA_PREFILL_CPU_SHARE=0`, `STRATA_ROUTE_TAIL_SKIP=0`) to compare two builds' answers byte for byte. + ### Quadro RTX 8000: measurements of existing switches The Quadro RTX 8000 is Turing (sm_75): it has FP16 tensor cores, but no native BF16 or TF32 tensor cores. Two From 8af75e1a390f404e6e78499e6409464651b886f6 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 13 Oct 2026 01:05:11 +0200 Subject: [PATCH 43/67] dequant_wide_on: (void) on the cleared CUDA errors (HIP marks hipGetLastError nodiscard: two new warnings) (#2178 port) --- src/kernels/cuda/dequant_bf16.cu | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/kernels/cuda/dequant_bf16.cu b/src/kernels/cuda/dequant_bf16.cu index 95e9d152..97759ae7 100644 --- a/src/kernels/cuda/dequant_bf16.cu +++ b/src/kernels/cuda/dequant_bf16.cu @@ -271,11 +271,11 @@ bool dequant_wide_on() { if (env >= 0) return env != 0; static int per_dev[64]; // 0 unknown, 1 no, 2 yes: sm_61, measured on a Tesla P40 int dev = 0; - if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return false; } + if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { (void) cudaGetLastError(); return false; } if (!per_dev[dev]) { int major = 0, minor = 0; if (cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) != cudaSuccess || - cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, dev) != cudaSuccess) { cudaGetLastError(); return false; } + cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, dev) != cudaSuccess) { (void) cudaGetLastError(); return false; } per_dev[dev] = major == 6 && minor == 1 ? 2 : 1; } return per_dev[dev] == 2; From c18d4c2bd50d895dd8260785a45f14f1fd20da80 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 13 Oct 2026 01:08:16 +0200 Subject: [PATCH 44/67] docs/INTEL_ARC: the auto split's headroom pick on equal cards (#1440) --- docs/INTEL_ARC.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/docs/INTEL_ARC.md b/docs/INTEL_ARC.md index 9b7bb85c..cc434b6e 100644 --- a/docs/INTEL_ARC.md +++ b/docs/INTEL_ARC.md @@ -139,6 +139,12 @@ Things that matter on an Arc (details in INTEL.md): - `SYCL_CACHE_PERSISTENT=0`: the persistent JIT cache crashed on Xe2 during the first compile. - Two cards: `ONEAPI_DEVICE_SELECTOR=level_zero:*` (the image pins `level_zero:0`; `strata-sycl.sh` now passes the variable through) and `--layer-split`. +- **`--layer-split auto` on two equal cards (0.1.44, #1440):** when several splits hold all the experts and predict the + same speed, the search now takes the one that leaves its fullest card the most VRAM to spare (within 0.2% of the best + predicted time, `STRATA_SPLIT_HEADROOM_TOL`). It used to take the first one tried, which filled the second card to its + last MiB. A full card under `xe` moves buffers to system memory instead of failing: 2x B70 with IQ3_S, auto picked + K=24 (~11 tok/s) where `--layer-split 30` ran ~54. The startup line names both splits when the choice moves. + `STRATA_SPLIT_HEADROOM=0` keeps the old pick. - **Arc Pro B60:** the PCI id is `8086:e211` (`lspci -nn`, the kernel's `xe` id list files it with the BMG-G21 cards), `sycl-ls` prints `Intel(R) Arc(TM) Pro B60 Graphics 20.1.0`, and `ocloc ids bmg-g21` prints 20.1.0, so `-DSTRATA_SYCL_AOT=bmg-g21` is the right target. `setup_intel.py` knows both B60 ids, `e211` and `e221` (both seen on B60 cards). On a `--layer-split` the startup line "N experts are neither in VRAM nor mirrored" From cb22a53e0e7bec08c74a0a04025be293149ae143 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 13 Oct 2026 01:18:33 +0200 Subject: [PATCH 45/67] Adaptive overlap: the host-function signal is the Windows default, and the copy stream is flushed after the swaps are queued (#2188) Under WDDM a stream's work sits in the driver's command buffer until a driver call flushes it. With the stream-ordered signal the verify window only spins on a pinned int, so the last layers' copies and their 4-byte signal copies were never submitted: the first request stopped with "the adaptive tier's copies for layer 45 never landed" (RTX 4070 SUPER, 0.1.43.1, opt-in STRATA_ADAPT_OVERLAP=1). STRATA_ADAPT_SIGNAL=host worked. - Windows: the host function is the default signal; STRATA_ADAPT_SIGNAL=copy asks for the copy. - Every platform: one cudaStreamQuery on the copy stream after the swaps and their signals are queued (a no-op for the results; it submits the batch under WDDM). Linux keeps the copy signal as before. Needs a Windows run with STRATA_ADAPT_OVERLAP=1 STRATA_ADAPT_SIGNAL=copy to confirm the flush. --- docs/DETAILS.md | 5 +++++ src/program/generate.cpp | 18 +++++++++++++++++- 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 998d661e..1c570419 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -1748,6 +1748,11 @@ the pairs in which the switched arm won). They are here so you can try them on y - **`STRATA_ADAPT_SIGNAL=host`: the overlap's per-layer "landed" signal as a host function** (the 0.1.43 way). From 0.1.43.1 the default is a 4-byte stream-ordered copy into pinned memory, which needs no driver callback thread: on a 20-core desktop (RTX 3060) the host functions still cost ~7 ms per window with the thread started early, because the pool's workers occupy every other CPU. + **On Windows the host function stays the default** (0.1.44, #2188): under WDDM the copy and its signal waited in the + driver's command buffer while the window spun on the pinned int, and the first request stopped with "the adaptive + tier's copies for layer 45 never landed" (RTX 4070 SUPER, driver 617.42). `STRATA_ADAPT_SIGNAL=copy` asks for the copy + there; the engine now flushes the copy stream after queueing the swaps, which is meant to fix it but has not been run + on Windows yet. ## Thread placement: `--aux-cpus` (Linux, off by default) diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 0328b387..adf97122 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -8471,7 +8471,20 @@ int main(int argc, char** argv) { for (int64_t l = 0; l <= g.n_layers; ++l) agate.ticks[(size_t) l] = {&agate, (int32_t) l}; agate.has.assign((size_t) g.n_layers, 0); if (!ver.set_adapt_gate(&agate)) aov_why = "the device-planned layers (STRATA_VERIFY_DEVICE_PLAN) are on"; - if (aov_why == nullptr && !(std::getenv("STRATA_ADAPT_SIGNAL") && std::getenv("STRATA_ADAPT_SIGNAL")[0] == 'h')) { + // #2188: on Windows the default is the host function. Under WDDM a stream's work sits in the driver's + // command buffer until something flushes it, and nothing does while the host only spins on the pinned + // int: the first request stopped with "copies for layer 45 never landed". STRATA_ADAPT_SIGNAL=copy asks + // for the stream-ordered copy there too (the enqueue then flushes the stream), =host everywhere. + const char* asig = std::getenv("STRATA_ADAPT_SIGNAL"); +#if defined(_WIN32) + const bool sig_copy = asig != nullptr && asig[0] == 'c'; +#else + const bool sig_copy = !(asig != nullptr && asig[0] == 'h'); +#endif + if (aov_why == nullptr && !sig_copy) + std::fprintf(stderr, "strata serve: adaptive overlap signal: host functions%s\n", + asig == nullptr ? " (the Windows default, #2188; STRATA_ADAPT_SIGNAL=copy: a stream-ordered copy)" : ""); + if (aov_why == nullptr && sig_copy) { // the landing of each layer's copies is told by a stream-ordered D2H copy of the layer number into pinned memory // (STRATA_ADAPT_SIGNAL=host: a host function instead). No callback thread has to be scheduled while the pool's workers spin on every other CPU int32_t* vals = nullptr; void* hp = nullptr; @@ -8661,6 +8674,9 @@ int main(int argc, char** argv) { return false; } if (!swaps.empty()) cudaEventRecord(adapt_ev, adapt_stream); + // #2188: hand the copies and their landing signals to the GPU now. WDDM batches a stream's work until a + // driver call flushes it, and the verify window only spins on the pinned int (Linux submits at once: no-op) + if (aov && agate.hland != nullptr && !swaps.empty()) (void) cudaStreamQuery(adapt_stream); (void) main_live; for (auto& st : stages) if (st->adapt_live) { From 1955774783e74add84601fdb1a491ab9e1d74642 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 13 Oct 2026 01:20:48 +0200 Subject: [PATCH 46/67] SYCL layer split: a REFUSED start exits cleanly, and a later stage's misses no longer read the first stage's mirror table (#1980) - refuse_exit: after the REFUSED message the engine waits for the queued device work, flushes and _Exit(2)s instead of returning from main. Returning ran the stages' destructors in an order the UR loader did not survive: on a 2x Arc Pro B60 pair every REFUSED start segfaulted in libur_loader, and a trimmed one also left an xe page fault (bcs CAT error) on the second card that hung the next start (jds1-ai in #1980). - resident_plan_set_mirror takes the table's length; resident_plan uses the mirror and the usage counts only for a residency slice inside the table they were set for. A later stage passes its own residency table, so the slice was taken as an offset across allocations and read (and counted into) another buffer: the stage-1 xe faults with STRATA_VERIFY_NO_HOST=0 and no trim (10 of 10 requests, 0 tokens). Such a miss is now a plain miss, served by the host. Patch shape as jds1-ai proposed it. Compile-checked only (no two-card Intel box here). --- .../strata/kernels/resident_plan_mirror.hpp | 7 +++++- sycl/src/kernels/cuda/verify_kernels.dp.cpp | 14 +++++++---- sycl/src/program/generate.cpp | 23 +++++++++++++++---- 3 files changed, 35 insertions(+), 9 deletions(-) diff --git a/sycl/include/strata/kernels/resident_plan_mirror.hpp b/sycl/include/strata/kernels/resident_plan_mirror.hpp index b974c1a7..63cc95b8 100644 --- a/sycl/include/strata/kernels/resident_plan_mirror.hpp +++ b/sycl/include/strata/kernels/resident_plan_mirror.hpp @@ -6,5 +6,10 @@ namespace strata::kernels { /// that is not in the VRAM cache but has a non-zero entry in `mirror_table` ([n_layers][n_expert] device-readable /// addresses, 0 = none) as planned: the expert kernels read it from that address, over PCIe. `d_res` is the residency /// table whose per-layer slices resident_plan receives, so the layer of a call is found from its pointer. -void resident_plan_set_mirror(const int32_t* d_res, const unsigned long long* mirror_table, int32_t* usage = nullptr); +/// `entries` (#1980): the length of `d_res`, `mirror_table` and `usage` (n_layers x n_expert). A call whose residency +/// slice lies outside `d_res` - a later layer-split stage's own table - gets no mirror and no counts (a plain miss): the +/// slice used to be taken as an offset from `d_res` anyway and read another allocation (xe page fault on the second card). +/// 0: unchecked, as before. +void resident_plan_set_mirror(const int32_t* d_res, const unsigned long long* mirror_table, int32_t* usage = nullptr, + long long entries = 0); } diff --git a/sycl/src/kernels/cuda/verify_kernels.dp.cpp b/sycl/src/kernels/cuda/verify_kernels.dp.cpp index a268cd69..229b0f8b 100644 --- a/sycl/src/kernels/cuda/verify_kernels.dp.cpp +++ b/sycl/src/kernels/cuda/verify_kernels.dp.cpp @@ -2366,8 +2366,15 @@ namespace { const int32_t* g_mirror_res = nullptr; const unsigned long long* g_mirror_table = nullptr; int32_t* g_usage = nullptr; +long long g_mirror_entries = 0; // 0: unchecked +// #1980: the layer slice `res_layer` belongs to the table the mirror was set for (a later stage passes its own) +bool in_mirror_table(const int32_t* res_layer) { + if (g_mirror_res == nullptr || res_layer < g_mirror_res) return false; + return g_mirror_entries <= 0 || res_layer - g_mirror_res < g_mirror_entries; } -void resident_plan_set_mirror(const int32_t* d_res, const unsigned long long* mirror_table, int32_t* usage) { +} +void resident_plan_set_mirror(const int32_t* d_res, const unsigned long long* mirror_table, int32_t* usage, long long entries) { + g_mirror_entries = entries; g_usage = usage; g_mirror_res = d_res; g_mirror_table = mirror_table; @@ -2377,9 +2384,8 @@ void resident_plan(const int32_t* ids, int n_entries, int k, const int32_t* res_ long long capx, uint32_t* skip, uint32_t ring, void* stream, uint32_t* plan_err) { const unsigned long long* mir = nullptr; // SYCL port: the layer's slice of the host-mirror table, if any int32_t* use = nullptr; // the layer's slice of the device routing counts, if on - if (g_mirror_table != nullptr && g_mirror_res != nullptr && res_layer >= g_mirror_res) - mir = g_mirror_table + (res_layer - g_mirror_res); - if (g_usage != nullptr && g_mirror_res != nullptr && res_layer >= g_mirror_res) use = g_usage + (res_layer - g_mirror_res); + if (g_mirror_table != nullptr && in_mirror_table(res_layer)) mir = g_mirror_table + (res_layer - g_mirror_res); + if (g_usage != nullptr && in_mirror_table(res_layer)) use = g_usage + (res_layer - g_mirror_res); { auto exp_props = sycl::ext::oneapi::experimental::properties{ sycl::ext::oneapi::experimental::use_root_sync}; diff --git a/sycl/src/program/generate.cpp b/sycl/src/program/generate.cpp index 07852748..933b55ca 100644 --- a/sycl/src/program/generate.cpp +++ b/sycl/src/program/generate.cpp @@ -1654,6 +1654,21 @@ static double ple_direct_rows_per_s(strata::kernels::PleTable& t) { return el > 0 ? (double) done / el : -1.0; } +// #1980: a start-up refusal ends the process here instead of returning from main. Returning ran main's destructors +// (the stages' caches, queues and Level Zero objects) in an order the UR loader did not survive: 2x Arc Pro B60, every +// REFUSED start segfaulted in libur_loader after its message, and a trimmed one also left an xe page fault (bcs CAT error) +// on the second card that hung the next start. The device work queued so far finishes first; nothing is freed. +[[noreturn]] static void refuse_exit(int code) { + std::fflush(stdout); + std::fflush(stderr); + try { + for (unsigned int d = 0; d < dpct::device_count(); ++d) dpct::get_device(d).queues_wait_and_throw(); + } catch (...) { + } + std::fflush(stderr); + std::_Exit(code); +} + int main(int argc, char **argv) try { // **UNBUFFERED, BECAUSE THE INTERESTING OUTPUT IS THE OUTPUT BEFORE A CRASH.** `stdout` redirected to a // pipe or a file is block-buffered, so a program that dies loses every line it had already printed - which @@ -4932,7 +4947,7 @@ int main(int argc, char **argv) try { std::fprintf(stderr, "strata generate: REFUSED: %lld experts are neither in VRAM nor mirrored; with STRATA_VERIFY_NO_HOST " "the device plan cannot run them and generation would lack a safe host fallback - raise " "STRATA_MIRROR_MIB or the free RAM, or lower --max-context\n", (long long) unmirrored_misses); - return 2; + refuse_exit(2); } // The same rule after the start: the mirror holds the start's misses only, so an expert an adaptive swap moves // out of VRAM would be in neither, and the device plan would wait for a host that never serves it (every token @@ -5040,7 +5055,7 @@ int main(int argc, char **argv) try { "and the card is lost at the first verify window - set STRATA_STAGE_TRIM=1 (with --layer-split N) to free " "each card's duplicate dense weights, lower --max-context or --vram-reserve-mib, or unset " "STRATA_VERIFY_NO_HOST\n", (long long) later_misses); - return 2; + refuse_exit(2); } if (later_misses > 0) std::fprintf(stderr, "strata generate: layer split: %lld experts of the later stages are not in VRAM (served by the host)\n", @@ -7079,7 +7094,7 @@ int main(int argc, char **argv) try { usage_dev_srv = sycl::malloc_device((size_t) (g.n_layers * g.n_expert), dpct::get_in_order_queue()); dpct::get_in_order_queue().memset(usage_dev_srv, 0, (size_t) (g.n_layers * g.n_expert) * 4).wait(); } - if (mirror_table_d) strata::kernels::resident_plan_set_mirror(thits.d_res, mirror_table_d, usage_dev_srv); + if (mirror_table_d) strata::kernels::resident_plan_set_mirror(thits.d_res, mirror_table_d, usage_dev_srv, (long long) (g.n_layers * g.n_expert)); vh.h_res = host_res.empty() ? nullptr : host_res.data(); vh.cache_base = thits.cache_base; vh.blob = thits.blob; @@ -12225,7 +12240,7 @@ int main(int argc, char **argv) try { usage_dev = sycl::malloc_device((size_t) (g.n_layers * g.n_expert), dpct::get_in_order_queue()); dpct::get_in_order_queue().memset(usage_dev, 0, (size_t) (g.n_layers * g.n_expert) * 4).wait(); } - if (mirror_table_d) strata::kernels::resident_plan_set_mirror(thits.d_res, mirror_table_d, usage_dev); + if (mirror_table_d) strata::kernels::resident_plan_set_mirror(thits.d_res, mirror_table_d, usage_dev, (long long) (g.n_layers * g.n_expert)); vh.h_res = host_res.empty() ? nullptr : host_res.data(); vh.cache_base = thits.cache_base; vh.blob = thits.blob; From 23db5f9555a60222e6d915aecffcf33dfbcc8ff7 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 13 Oct 2026 01:22:19 +0200 Subject: [PATCH 47/67] setup_intel: a layer split whose experts will likely not fit writes STRATA_VERIFY_NO_HOST=0 and says so (#1980) The stock split shape (STRATA_STAGE_TRIM=1, 1024 MiB reserve, NO_HOST=1 from strata-sycl.sh) is refused at the start on a 2x Arc Pro B60 24 GB pair with IQ3_XXS: the second stage is 2230-3731 experts short and the host mirror covers the first stage only. The same config with NO_HOST=0 runs at 39-50 tok/s with 0 faults (jds1-ai in #1980). When the model's experts take more than 80% of the split cards' VRAM, setup now writes NO_HOST=0 into the config (a value the user set is kept) and prints why and how to turn it back. IQ2_XS on the same pair (74%) keeps NO_HOST=1. Test: tools/test_setup_sycl.py test_split_short_rule. --- sycl/setup_intel.py | 24 ++++++++++++++++++++++++ tools/test_setup_sycl.py | 10 ++++++++++ 2 files changed, 34 insertions(+) diff --git a/sycl/setup_intel.py b/sycl/setup_intel.py index 8c0ed962..1fd8bb87 100644 --- a/sycl/setup_intel.py +++ b/sycl/setup_intel.py @@ -131,6 +131,20 @@ def small_card(vram_gb: float, driver: str) -> bool: return 0 < vram_gb < SMALL_CARD_GB or driver == "i915" +# #1980: on a layer split the host mirror covers the first stage only, so with STRATA_VERIFY_NO_HOST=1 (strata-sycl.sh's +# default) a later stage that cannot hold all of its layers' experts is REFUSED at the start. Measured on 2x Arc Pro B60 +# 24 GB with the trim and a 1024 MiB reserve: IQ3_XXS (42.9 GB of experts, 89% of the 48 GB) stage 1 2230-3731 experts +# short and refused; NO_HOST=0 runs it at 39-50 tok/s with 0 faults. IQ2_XS (35.5 GB, 74%) loads 100% resident. +SPLIT_SHORT_FRACTION = 0.80 + + +def split_likely_short(arena_gb: float, vram_gbs: list) -> bool: + """True when the model's experts take so much of the split cards' VRAM that a later stage will not hold all of its + layers' experts (the dense weights, the KV, the prompt buffers, the drafter and the reserve take the rest).""" + total = sum(v for v in vram_gbs if v and v > 0) + return arena_gb > 0 and total > 0 and arena_gb > SPLIT_SHORT_FRACTION * total + + def to_sycl(cfg: dict, exe: Path, ram: float, keep: dict, vram_gb: float = 0.0, driver: str = "xe", devid: str = "") -> dict: """setup's config (written for its HIP path) -> the SYCL port's: the container's paths, experts streamed from the @@ -295,6 +309,16 @@ def install(argv) -> None: # #1980: without it every card keeps a full copy of the dense weights (1.4 GiB each on Flash-Next IQ2_XS) and the # load stops at 96-97% resident; the later stage's missing experts have no host mirror (STRATA_VERIFY_NO_HOST) cfg.setdefault("env", {}).setdefault("STRATA_STAGE_TRIM", "1") + # #1980: a later stage short of VRAM is refused under NO_HOST=1; with the host path on it runs (the host + # computes those experts). Only when the experts will likely not fit; a value the user set is kept. + cards = [intel[i]["vram_gb"] for i in gsel if isinstance(i, int) and 0 <= i < len(intel)] + arena = S.MODELS.get(model, {}).get("arena_gb", 0) + if split_likely_short(arena, cards) and "STRATA_VERIFY_NO_HOST" not in cfg["env"]: + cfg["env"]["STRATA_VERIFY_NO_HOST"] = "0" + S.say(f" {model}'s {arena:.0f} GB of experts will likely not all fit the {len(cards)} cards' " + f"{sum(cards):.0f} GB of VRAM: the config sets STRATA_VERIFY_NO_HOST=0, so the CPU computes the " + "experts the later card does not hold instead of the start being refused (#1980). Set it to 1 " + "in the config's env if your cards hold everything; a smaller model fits fully (docs/INTEL_ARC.md)") need = S.MODELS.get(model, {}).get("ram_gb", 0) sel_alch = sel["driver"] == "i915" or sel.get("devid") in ALCHEMIST_IDS if sel_alch and need and real_ram < need: diff --git a/tools/test_setup_sycl.py b/tools/test_setup_sycl.py index 0de2799d..1c993a6a 100644 --- a/tools/test_setup_sycl.py +++ b/tools/test_setup_sycl.py @@ -206,6 +206,16 @@ class ToSycl(unittest.TestCase): self.assertEqual(c["env"]["STRATA_VERIFY_NO_HOST"], "0") self.assertEqual(c["env"]["STRATA_SYCL_BIN"], "build-sycl/strata") + def test_split_short_rule(self): + # #1980: 2x B60 24 GB - IQ3_XXS (42.9 GB) was refused under NO_HOST=1, IQ2_XS (35.5 GB) loads fully + m = self.mod() + self.assertTrue(m.split_likely_short(42.9, [24.0, 24.0])) + self.assertFalse(m.split_likely_short(35.5, [24.0, 24.0])) + self.assertFalse(m.split_likely_short(50.3, [32.0, 32.0])) # IQ3_S on 2x B70: 79% + self.assertTrue(m.split_likely_short(77.0, [32.0, 32.0])) + self.assertFalse(m.split_likely_short(0, [24.0])) + self.assertFalse(m.split_likely_short(40.0, [])) + def test_small_card_rule(self): m = self.mod() self.assertTrue(m.small_card(8.0, "i915")) From fb654ba3e81bc8ef49dbeb7726bed30fb458fd01 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 13 Oct 2026 01:29:25 +0200 Subject: [PATCH 48/67] Windows AMD: the card's name and VRAM from the registry's display class, in the server's hardware_static and in strata_bench (#1587) On Windows with only an AMD card neither NVML nor the amdgpu sysfs files answer, so hardware_static.gpu_name was None and strata_bench (no nvidia-smi, no rocm-smi on Windows) labelled the run "CPU only" although the engine ran on the card (ByteJuggler in #1587: RX 6900 XT). telemetry.windows_display_adapters reads DriverDesc, ProviderName, DriverVersion and the memory size from HKLM's display class (no subprocess, no vendor library); windows_amd_cards drops a Ryzen's integrated Radeon (512 MiB here) when a real card sits beside it. hardware_static gets the name and gpu_vram_total_mib; strata_bench uses the same list when nvidia-smi and rocm-smi give nothing. Load, VRAM use, temperature and power stay unread on Windows AMD (that is the reader of #1224 / #1434 / #1871). Checked against this PC's registry (RTX 5070 + the Ryzen 7600's iGPU: both listed, the iGPU's 512 MiB read); tools/test_windows_amd_gpu.py with a fake registry. --- serve/telemetry.py | 69 +++++++++++++++++++++++- tools/strata_bench.py | 11 ++++ tools/test_windows_amd_gpu.py | 98 +++++++++++++++++++++++++++++++++++ 3 files changed, 177 insertions(+), 1 deletion(-) create mode 100644 tools/test_windows_amd_gpu.py diff --git a/serve/telemetry.py b/serve/telemetry.py index b0d1bae2..3232c63c 100644 --- a/serve/telemetry.py +++ b/serve/telemetry.py @@ -251,6 +251,63 @@ def gpu_reader(index=0, amd=False): return _Amd(index) if amd else _Nvml(index) +_DISPLAY_CLASS = r"SYSTEM\CurrentControlSet\Control\Class\{4d36e968-e325-11ce-bfc1-08002be10318}" + + +def windows_display_adapters(vendor=None) -> list: + """#1587: the display adapters Windows has drivers for, from the registry's display class (no subprocess, no vendor + library): [{"name", "provider", "driver", "vram_bytes"}] in the class's order. `vendor`: "amd", "nvidia" or + "intel" keeps that vendor's cards. [] off Windows or when nothing can be read.""" + if os.name != "nt": + return [] + try: + import winreg + root = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, _DISPLAY_CLASS) + except OSError: + return [] + out = [] + i = 0 + while True: + try: + sub = winreg.EnumKey(root, i) + except OSError: + break + i += 1 + if not sub.isdigit(): + continue + try: + k = winreg.OpenKey(root, sub) + except OSError: + continue + + def val(name, k=k): + try: + return winreg.QueryValueEx(k, name)[0] + except OSError: + return None + name = val("DriverDesc") + if not isinstance(name, str) or not name.strip(): + continue + mem = val("HardwareInformation.qwMemorySize") + if mem is None: + mem = val("HardwareInformation.MemorySize") + if isinstance(mem, (bytes, bytearray)): + mem = int.from_bytes(bytes(mem[:8]), "little") if mem else None + out.append({"name": name.strip(), "provider": str(val("ProviderName") or ""), "driver": val("DriverVersion"), + "vram_bytes": mem if isinstance(mem, int) and mem > 0 else None}) + if vendor: + keys = {"amd": ("advanced micro devices", "amd", "radeon"), "nvidia": ("nvidia",), "intel": ("intel",)}[vendor] + out = [a for a in out if any(s in (a["provider"] + " " + a["name"]).lower() for s in keys)] + return out + + +def windows_amd_cards(adapters=None) -> list: + """The AMD cards HIP runs on, as windows_display_adapters lists them. A Ryzen's integrated Radeon is listed too + (512 MiB on a Ryzen 5 7600): beside a card with 2 GiB or more it is left out (an APU alone keeps it).""" + cards = windows_display_adapters("amd") if adapters is None else adapters + return [c for c in cards if (c["vram_bytes"] or 0) >= 2 << 30] or cards + + def free_vram_mib(index=0, amd=False): """Free VRAM of a card in MiB, or None when it cannot be read.""" g = gpu_reader(index, amd) @@ -348,8 +405,18 @@ class Telemetry: except ImportError: self.ps = None self.fallback = _CpuRamFallback() + gpu_name = " + ".join(g.name() or "?" for _, g in self.gpus) if self.gpu.ok() else None + win_amd = None + if gpu_name is None and amd and os.name == "nt": + # #1587: no readings for an AMD card on Windows yet, but its name (and VRAM size) are in the registry, so the + # dashboard and strata_bench do not call the run "CPU only". The class order is taken as HIP's order. + cards = windows_amd_cards() + win_amd = [cards[i] for i in idx if 0 <= i < len(cards)] or cards[:1] + gpu_name = " + ".join(c["name"] for c in win_amd) if win_amd else None self.static = { - "gpu_name": " + ".join(g.name() or "?" for _, g in self.gpus) if self.gpu.ok() else None, + "gpu_name": gpu_name, + "gpu_vram_total_mib": (sum(c["vram_bytes"] for c in win_amd) >> 20 + if win_amd and all(c["vram_bytes"] for c in win_amd) else None), "gpu_count": len(self.gpus), # #1380: the AMD readings are the amdgpu driver's Linux sysfs files; a Windows AMD card has none yet, and the # dashboard said "not readable (NVML)" or showed empty tiles with no word why diff --git a/tools/strata_bench.py b/tools/strata_bench.py index 67bd63a0..63c66c7b 100644 --- a/tools/strata_bench.py +++ b/tools/strata_bench.py @@ -500,6 +500,17 @@ def gpu_info_local() -> dict: m2 = re.search(r"Driver version:\s*(\S+)", v) if m2: info["rocm_driver"] = m2.group(1) + if not info["gpus"] and os.name == "nt": + # #1587: Windows with only an AMD card has neither nvidia-smi nor rocm-smi; the display class in the registry + # names the card, its VRAM and its driver (the run was labelled "CPU only" before) + try: + if str(ROOT) not in sys.path: + sys.path.insert(0, str(ROOT)) + from serve.telemetry import windows_amd_cards + info["gpus"] = [{"name": c["name"], "vram_mib": (c["vram_bytes"] >> 20) if c["vram_bytes"] else None, + "driver": c["driver"]} for c in windows_amd_cards()] + except Exception: # noqa: BLE001 - a report without the card's name is still a report + pass return info diff --git a/tools/test_windows_amd_gpu.py b/tools/test_windows_amd_gpu.py new file mode 100644 index 00000000..e6802d58 --- /dev/null +++ b/tools/test_windows_amd_gpu.py @@ -0,0 +1,98 @@ +"""#1587: a Windows PC with only an AMD card - the server's hardware_static names the card from the registry's display +class, and strata_bench no longer labels the run "CPU only". No GPU, no registry needed (a fake winreg). + + python -m unittest tools.test_windows_amd_gpu +""" +from __future__ import annotations + +import sys +import types +import unittest +from pathlib import Path +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) +sys.path.insert(0, str(ROOT / "tools")) +from serve import telemetry as T # noqa: E402 + +GB = 1 << 30 + + +def fake_winreg(adapters): + """A winreg with the display class holding `adapters` (dicts of value name -> value) under 0000, 0001, ...""" + w = types.ModuleType("winreg") + w.HKEY_LOCAL_MACHINE = "HKLM" + keys = {f"{i:04d}": a for i, a in enumerate(adapters)} + subs = list(keys) + ["Properties"] + + def OpenKey(root, sub): + if root == "HKLM": + return "CLASS" + if root == "CLASS" and sub in keys: + return keys[sub] + raise OSError("denied") + + def EnumKey(k, i): + if i >= len(subs): + raise OSError("no more") + return subs[i] + + def QueryValueEx(k, name): + if name not in k: + raise OSError("no value") + return k[name], 1 + w.OpenKey, w.EnumKey, w.QueryValueEx = OpenKey, EnumKey, QueryValueEx + return w + + +IGPU = {"DriverDesc": "AMD Radeon(TM) Graphics", "ProviderName": "Advanced Micro Devices, Inc.", + "DriverVersion": "32.0.13066.12", "HardwareInformation.qwMemorySize": 512 << 20} +CARD = {"DriverDesc": "AMD Radeon RX 6900 XT", "ProviderName": "Advanced Micro Devices, Inc.", + "DriverVersion": "32.0.21001.9024", "HardwareInformation.MemorySize": (16 * GB).to_bytes(8, "little")} +GEFORCE = {"DriverDesc": "NVIDIA GeForce RTX 5070", "ProviderName": "NVIDIA", "DriverVersion": "32.0.16.1047", + "HardwareInformation.qwMemorySize": 12 * GB} + + +class Adapters(unittest.TestCase): + def read(self, adapters, vendor=None): + with mock.patch.dict(sys.modules, {"winreg": fake_winreg(adapters)}), mock.patch.object(T.os, "name", "nt"): + return T.windows_display_adapters(vendor) + + def test_reads_names_vram_and_drivers(self): + a = self.read([IGPU, CARD, GEFORCE]) + self.assertEqual([x["name"] for x in a], ["AMD Radeon(TM) Graphics", "AMD Radeon RX 6900 XT", "NVIDIA GeForce RTX 5070"]) + self.assertEqual(a[1]["vram_bytes"], 16 * GB) # the binary form of the memory size + self.assertEqual(a[2]["vram_bytes"], 12 * GB) + self.assertEqual([x["name"] for x in self.read([IGPU, CARD, GEFORCE], "amd")], + ["AMD Radeon(TM) Graphics", "AMD Radeon RX 6900 XT"]) + + def test_the_integrated_radeon_is_left_out_beside_a_card(self): + self.assertEqual([c["name"] for c in T.windows_amd_cards(self.read([IGPU, CARD], "amd"))], ["AMD Radeon RX 6900 XT"]) + self.assertEqual([c["name"] for c in T.windows_amd_cards(self.read([IGPU], "amd"))], ["AMD Radeon(TM) Graphics"]) + + def test_off_windows_nothing(self): + with mock.patch.object(T.os, "name", "posix"): + self.assertEqual(T.windows_display_adapters(), []) + + def test_hardware_static_names_the_card(self): + cards = [{"name": "AMD Radeon RX 6900 XT", "provider": "AMD", "driver": "x", "vram_bytes": 16 * GB}] + with mock.patch.object(T.os, "name", "nt"), mock.patch.object(T, "windows_amd_cards", return_value=cards), \ + mock.patch.object(T, "gpu_reader", return_value=mock.Mock(ok=lambda: False)), \ + mock.patch.object(T, "_CpuRamFallback"), mock.patch.object(T, "_cpu_name", return_value="cpu"), \ + mock.patch.object(T.threading, "Thread"): + t = T.Telemetry(amd=True) + self.assertEqual(t.static["gpu_name"], "AMD Radeon RX 6900 XT") + self.assertEqual(t.static["gpu_vram_total_mib"], 16384) + + def test_bench_labels_the_card(self): + import strata_bench as B + cards = [{"name": "AMD Radeon RX 6900 XT", "provider": "AMD", "driver": "32.0.21001.9024", "vram_bytes": 16 * GB}] + with mock.patch.object(B, "run_cmd", return_value=""), mock.patch.object(B.os, "name", "nt"), \ + mock.patch.object(T, "windows_amd_cards", return_value=cards): + info = B.gpu_info_local() + self.assertEqual(info["gpus"], [{"name": "AMD Radeon RX 6900 XT", "vram_mib": 16384, "driver": "32.0.21001.9024"}]) + + +if __name__ == "__main__": + unittest.main() From b5217c8bb7423e0e40f95af05777a554ca750894 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 13 Oct 2026 02:23:22 +0200 Subject: [PATCH 49/67] serve: the VRAM-free check at start covers a layer split's later cards too (#2192) The 'MiB of VRAM free with everything loaded' line and its LOW warning read CUDA0 alone. In #2192 (2x RTX 2080 Ti 22 GB, Windows, IQ3_S, --batch 4, --layer-split auto, 0.1.43) CUDA0 had 740 MiB free while CUDA1 began its window captures at 153 MiB and fell to 52; the first batch window then never finished. Both stall dumps show the host thread inside cudaGraphLaunch called from Verifier::run_slot_rows (the stage still 'idle': it had not reached its per-layer wait), the pool asleep and the watchdog firing after 60 s - a page-in under WDDM while the other card's graph spins on a host flag. Each later card now gets its own line, and below 512 MiB a LOW warning with the --vram-reserve-later-mib value that leaves ~768 MiB. Said, never changed. --- src/program/generate.cpp | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/src/program/generate.cpp b/src/program/generate.cpp index adf97122..6b31bfb0 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -9174,6 +9174,31 @@ int main(int argc, char** argv) { "slots are written - leaves room; decode can be several times slower with the " "card this full\n", (long long) xcache.slots()); } + // #2192: the same check on a layer split's later cards. The line above reads CUDA0 alone: on 2x RTX 2080 Ti + // (WDDM, --batch 4) CUDA0 had 740 MiB free while CUDA1 started its window captures at 153 MiB and fell to + // 52, and the first batch window on it never finished (the host stuck in cudaGraphLaunch: a page-in while the + // other card's graph spins on a host flag). Said, never changed. + for (const auto& stp : stages) { + const strata::core::OnDevice on(stp->dev); + size_t sf = 0, stot = 0; + if (cudaMemGetInfo(&sf, &stot) != cudaSuccess) { (void) cudaGetLastError(); continue; } + const int64_t sf_mib = (int64_t) (sf >> 20); + const int later_reserve = o.vram_reserve_later_mib >= 0 ? o.vram_reserve_later_mib : o.vram_reserve_mib; + if (sf_mib >= 512) + std::fprintf(stderr, "strata serve: CUDA%d: %lld MiB of VRAM free with everything loaded\n", stp->dev, + (long long) sf_mib); + else + std::fprintf(stderr, "strata serve: CUDA%d: %lld MiB of VRAM free with everything loaded - LOW: its window " + "graphs are captured on first use and need room too, and %s; add " + "--vram-reserve-later-mib %lld to the config's args (or lower --max-context)\n", + stp->dev, (long long) sf_mib, +#ifdef _WIN32 + "under WDDM a full card pages instead of failing, which can stall a request for good (#2192)", +#else + "a full card can stall a request", +#endif + (long long) (later_reserve + 768 - sf_mib)); + } } // what the server's Monitor tab shows (servers before 0.1.8 skip unknown lines until READY) { From 1a55fc3788c07c736890ee954dba5d9021f9fefb Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 13 Oct 2026 04:14:11 +0200 Subject: [PATCH 50/67] gfx12: the 16384 auto prompt chunk stays at 8192 when the RAM available does not cover its extra prompt loan (#2090) The gfx12 default (0.1.43) lets a bare --prefill auto reach 16384, which lends the prompt path about twice the cache slots of 8192 (R9700, Swift 1.5 IQ3_XXS: 3,907 slots / 6.38 GiB against 2,068 / 3.37 GiB); the lent slots' experts are read from the RAM side during the read. On a 30 GB PC with --resident-experts 38-47K prompts went 20 GB into swap with 1.5M major faults and the engine was killed; --prefill 8192 ran them at ~95 tok/s (bdwilton in #2090). At start, when the engine's own 16384 ceiling is in effect, the extra slots of a 16384 loan over an 8192 one are priced at the largest blob; if the RAM available (the cgroup or --memory-limit-mib cap included) is below that plus 4 GiB, the ceiling stays at 8192 and a line says why. STRATA_GFX12_CHUNK=1 keeps 16384; an explicit --prefill N / auto:N is never touched (the 16384 default only applies to a bare auto). --- src/program/generate.cpp | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 6b31bfb0..a7a97499 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -6420,6 +6420,28 @@ int main(int argc, char** argv) { o.prefill_chunk = std::min(o.prefill_chunk, 8192); } } + // #2090 (bdwilton): the gfx12 16384 ceiling lends the prompt path about twice the slots of 8192 (R9700, Swift 1.5 + // IQ3_XXS: 3,907 slots / 6.38 GiB against 2,068 / 3.37 GiB), and every lent slot's expert is read from the RAM side + // during the read. On a 30 GB PC with --resident-experts that was 3.4 GB available, 20 GB in swap, 1.5M major faults + // and a killed engine on 38-47K prompts; 8192 ran them at 95 tok/s. The ceiling is the engine's default, not the + // user's pick, so when the RAM available now does not cover the extra loan plus 4 GiB the default stays at 8192. + // STRATA_GFX12_CHUNK=1 keeps 16384 anyway. + if (o.prefill_gfx12_16k && auto_ceiling > 8192) { + static const char* force16 = std::getenv("STRATA_GFX12_CHUNK"); + const int64_t extra_slots = std::max(0, lend_slots(16384) - lend_slots(8192)); + const uint64_t extra_mib = ((uint64_t) extra_slots * strata::kernels::cpu::expert_layout().max_blob) >> 20; + const auto hm = strata::core::sample_host_memory(); // the cgroup / --memory-limit-mib cap counts too + const uint64_t avail_mib = hm ? hm->available >> 20 : mem_sample().avail_mib; + if (avail_mib > 0 && avail_mib < extra_mib + 4096 && !(force16 != nullptr && force16[0] == '1')) { + auto_ceiling = std::min(auto_ceiling, 8192); + o.prefill_auto_max = std::min(o.prefill_auto_max, 8192); + o.prefill_chunk = std::min(o.prefill_chunk, 8192); + std::fprintf(stderr, "strata generate: gfx12: prompt chunks stay at 8192: 16384 would lend %lld more cache slots " + "(%llu MiB read from RAM during a prompt) and %llu MiB of RAM is available (#2090; " + "STRATA_GFX12_CHUNK=1 takes 16384 anyway)\n", + (long long) extra_slots, (unsigned long long) extra_mib, (unsigned long long) avail_mib); + } + } if (o.prefill_auto_cap > 0) auto_ceiling = std::min(auto_ceiling, o.prefill_auto_cap); // #1630 // The auto scan used to walk a fixed list of sizes - 32768, 16384, 8192, 6144, ... - and take the first that // fit. That list is coarse exactly where a rig needs it: this one affords ~8,700 tokens and was handed 8192, From 987548ce2cf0869bc77abbc96fb3dfde730f030b Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 13 Oct 2026 04:28:32 +0200 Subject: [PATCH 51/67] gfx12 chunk rule: with --resident-experts the RAM copy to come (every uncached expert plus the loan) counts, and the margin is 6 GiB (#2090) The first version compared only the extra loan with the RAM available at that point, but the resident RAM copy is pinned after it and holds the lent slots' experts too: in a 30 GB scope on an R9700 (IQ3_XXS, --resident-experts) 30 GiB were available before the 23.35 GiB copy, so the rule never fired. The reporter's PC thrashed with 3.4 GB left at 16384 and ran with ~6.4 GB at 8192, hence 6 GiB. --- src/program/generate.cpp | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/src/program/generate.cpp b/src/program/generate.cpp index a7a97499..94e5ff0f 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -6424,7 +6424,8 @@ int main(int argc, char** argv) { // IQ3_XXS: 3,907 slots / 6.38 GiB against 2,068 / 3.37 GiB), and every lent slot's expert is read from the RAM side // during the read. On a 30 GB PC with --resident-experts that was 3.4 GB available, 20 GB in swap, 1.5M major faults // and a killed engine on 38-47K prompts; 8192 ran them at 95 tok/s. The ceiling is the engine's default, not the - // user's pick, so when the RAM available now does not cover the extra loan plus 4 GiB the default stays at 8192. + // user's pick, so when the RAM available now does not cover the extra loan plus 6 GiB (that PC thrashed with 3.4 GB left and + // ran with ~6.4) the default stays at 8192. // STRATA_GFX12_CHUNK=1 keeps 16384 anyway. if (o.prefill_gfx12_16k && auto_ceiling > 8192) { static const char* force16 = std::getenv("STRATA_GFX12_CHUNK"); @@ -6432,14 +6433,24 @@ int main(int argc, char** argv) { const uint64_t extra_mib = ((uint64_t) extra_slots * strata::kernels::cpu::expert_layout().max_blob) >> 20; const auto hm = strata::core::sample_host_memory(); // the cgroup / --memory-limit-mib cap counts too const uint64_t avail_mib = hm ? hm->available >> 20 : mem_sample().avail_mib; - if (avail_mib > 0 && avail_mib < extra_mib + 4096 && !(force16 != nullptr && force16[0] == '1')) { + // --resident-experts pins its RAM copy after this point, and that copy also holds the lent slots' experts: what + // has to fit is every expert the cache does not hold plus the 16384 loan (R9700 IQ3_XXS: 23.35 GiB at 16384) + uint64_t pin_mib = 0; + if (o.resident_cpu_experts) { + const uint64_t total = strata::kernels::cpu::expert_layout().total; + const uint64_t cached = (uint64_t) std::max(0, (int64_t) xcache.bytes()); + pin_mib = ((total > cached ? total - cached : 0) + + (uint64_t) std::max(0, lend_slots(8192)) * strata::kernels::cpu::expert_layout().max_blob) >> 20; + } + if (avail_mib > 0 && avail_mib < pin_mib + extra_mib + 6144 && !(force16 != nullptr && force16[0] == '1')) { auto_ceiling = std::min(auto_ceiling, 8192); o.prefill_auto_max = std::min(o.prefill_auto_max, 8192); o.prefill_chunk = std::min(o.prefill_chunk, 8192); std::fprintf(stderr, "strata generate: gfx12: prompt chunks stay at 8192: 16384 would lend %lld more cache slots " - "(%llu MiB read from RAM during a prompt) and %llu MiB of RAM is available (#2090; " - "STRATA_GFX12_CHUNK=1 takes 16384 anyway)\n", - (long long) extra_slots, (unsigned long long) extra_mib, (unsigned long long) avail_mib); + "(%llu MiB more held in RAM during a prompt), and %llu MiB of RAM is available for %llu MiB " + "of resident experts plus that (#2090; STRATA_GFX12_CHUNK=1 takes 16384 anyway)\n", + (long long) extra_slots, (unsigned long long) extra_mib, (unsigned long long) avail_mib, + (unsigned long long) pin_mib); } } if (o.prefill_auto_cap > 0) auto_ceiling = std::min(auto_ceiling, o.prefill_auto_cap); // #1630 From ea73bc2522b85ec52e474ac3a23d1b0d47265e64 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 13 Oct 2026 04:35:37 +0200 Subject: [PATCH 52/67] Windows HIP: hipKernelNameRefByPtr is resolved at run time (STRATA_VERIFY_NODES), so a runtime DLL without it still starts (#2183) Some amdhip64_7.dll builds (AMD TheRock wheels / ROCm 10.2 / 7.2.4 nightly) do not export hipKernelNameRefByPtr although their import library has it, so strata.exe failed to load with STATUS_ENTRYPOINT_NOT_FOUND before main. It is only used to name graph nodes under STRATA_VERIFY_NODES; on Windows it is now looked up with GetProcAddress and a missing one leaves the node unnamed. From #2183, its verify.cpp part only. The PR's other part (Windows HIP --pcie-mode auto as DMA) changes the default path of every Windows AMD user and was not measured on our side; it is left out. Co-authored-by: dvasdekis <19279397+dvasdekis@users.noreply.github.com> --- src/core/verify.cpp | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/core/verify.cpp b/src/core/verify.cpp index bb108338..0513a824 100644 --- a/src/core/verify.cpp +++ b/src/core/verify.cpp @@ -6,6 +6,10 @@ #include "strata/core/dma_batch.hpp" #include "strata/core/spec_prob.hpp" #if defined(_WIN32) +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include #include #endif @@ -1878,7 +1882,14 @@ bool Verifier::capture(int T, std::string& err) { if (ty == hipGraphNodeTypeKernel) { hipKernelNodeParams kp{}; if (hipGraphKernelNodeGetParams(nd, &kp) == hipSuccess && kp.func != nullptr) { +#if defined(_WIN32) + using Fn_hipKernelNameRefByPtr = const char* (*)(const void*, hipStream_t); + static auto p_hipKernelNameRefByPtr = reinterpret_cast( + GetProcAddress(GetModuleHandleA("amdhip64_7.dll"), "hipKernelNameRefByPtr")); + const char* fn = p_hipKernelNameRefByPtr ? p_hipKernelNameRefByPtr(kp.func, nullptr) : nullptr; +#else const char* fn = hipKernelNameRefByPtr(kp.func, nullptr); +#endif if (fn != nullptr) name = fn; } } else if (ty == hipGraphNodeTypeMemcpy) name = "memcpy"; From 2f335a5eab3d82145fdfc16cdb93b3d2bdc255bc Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 13 Oct 2026 04:36:04 +0200 Subject: [PATCH 53/67] tools/windows/enable_large_pages.ps1: grant "Lock pages in memory" to the current account (#2185) A helper for the large-page arena (#1412): run as Administrator, it adds the account to SeLockMemoryPrivilege with secedit, says that a new logon is needed, and prints the secpol.msc steps when it cannot run. Changed from the PR: secedit /configure is limited to /areas USER_RIGHTS (the exported policy is not re-applied as a whole), and the description no longer claims a speed-up we have not measured. docs/DETAILS.md points to it. Not run on our side (no Windows box for it). Co-authored-by: dvasdekis <19279397+dvasdekis@users.noreply.github.com> --- docs/DETAILS.md | 2 +- tools/windows/enable_large_pages.ps1 | 89 ++++++++++++++++++++++++++++ 2 files changed, 90 insertions(+), 1 deletion(-) create mode 100644 tools/windows/enable_large_pages.ps1 diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 1c570419..968ba586 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -521,7 +521,7 @@ In the task's properties set both of these (the defaults are the opposite): (Both were changed at once, so the isolated effect of each is not measured.) If the model still starts slowly, the engine prints a hint under its `loaded ... GiB at ...` line naming this cause. -**Large pages need a new logon (#1412).** Granting "Lock pages in memory" (`secpol.msc`, User Rights Assignment) to the account that runs the engine takes effect at the next logon: Windows puts the privilege in the access token when the session starts, so log off and on (or reboot) after granting it. Until then the startup log still says the large pages were refused. +**Large pages need a new logon (#1412).** Granting "Lock pages in memory" (`secpol.msc`, User Rights Assignment) to the account that runs the engine takes effect at the next logon: Windows puts the privilege in the access token when the session starts, so log off and on (or reboot) after granting it. Until then the startup log still says the large pages were refused. `tools\windows\enable_large_pages.ps1` (run as Administrator) grants it to the current account with `secedit`. ### Chat in the terminal (optional) diff --git a/tools/windows/enable_large_pages.ps1 b/tools/windows/enable_large_pages.ps1 new file mode 100644 index 00000000..046d2d83 --- /dev/null +++ b/tools/windows/enable_large_pages.ps1 @@ -0,0 +1,89 @@ +<# +.SYNOPSIS + Enables the 'Lock pages in memory' privilege (SeLockMemoryPrivilege) on Windows. +.DESCRIPTION + Strata keeps the experts the GPU does not hold in a host memory arena. With SeLockMemoryPrivilege + granted, Windows lets it allocate that arena in 2 MB large pages (MEM_LARGE_PAGES); without it the + engine says at start that the large pages were refused and uses 4 KB pages (docs/DETAILS.md, #1412). + The same can be done by hand with secpol.msc (User Rights Assignment, "Lock pages in memory"). + + NOTE: Windows applies security token privilege changes ONLY after sign-out/sign-in or reboot. +#> + +[CmdletBinding()] +param ( + [string]$AccountName = $env:USERNAME +) + +function Test-IsAdmin { + $currentPrincipal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent()) + return $currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) +} + +if (-not (Test-IsAdmin)) { + Write-Host "[!] This script must be run as Administrator." -ForegroundColor Yellow + Write-Host " Right-click PowerShell -> 'Run as Administrator', then run:" + Write-Host " .\tools\windows\enable_large_pages.ps1" + Write-Host "" + Write-Host " GUI Alternative:" + Write-Host " 1. Press Win + R, type 'secpol.msc' and press Enter." + Write-Host " 2. Navigate to: Security Settings -> Local Policies -> User Rights Assignment" + Write-Host " 3. Double-click 'Lock pages in memory'." + Write-Host " 4. Click 'Add User or Group...', add '$AccountName', and click OK." + Write-Host " 5. Sign out of Windows and sign back in." + exit 1 +} + +Write-Host "=== Configuring 'Lock pages in memory' (SeLockMemoryPrivilege) for $AccountName ===" -ForegroundColor Cyan + +$tempInf = [System.IO.Path]::GetTempFileName() +$tempSdb = [System.IO.Path]::ChangeExtension($tempInf, ".sdb") + +try { + Write-Host "1. Exporting current security policy..." + secedit /export /cfg $tempInf | Out-Null + + $content = Get-Content $tempInf -Raw + $userSid = (New-Object System.Security.Principal.NTAccount($AccountName)).Translate([System.Security.Principal.SecurityIdentifier]).Value + + if ($content -match "SeLockMemoryPrivilege\s*=\s*(.*)") { + $currentList = $matches[1].Trim() + if ($currentList -match [regex]::Escape($userSid) -or $currentList -match [regex]::Escape($AccountName)) { + Write-Host "[OK] $AccountName already possesses SeLockMemoryPrivilege." -ForegroundColor Green + Write-Host " If 'whoami /priv' still shows it as missing, please SIGN OUT and sign back in to refresh your token." + return + } + $newList = "$currentList,*$userSid" + $content = $content -replace "SeLockMemoryPrivilege\s*=.*", "SeLockMemoryPrivilege = $newList" + } else { + # Section [Privilege Rights] + if ($content -match "\[Privilege Rights\]") { + $content = $content -replace "\[Privilege Rights\]", "[Privilege Rights]`r`nSeLockMemoryPrivilege = *$userSid" + } else { + $content += "`r`n[Privilege Rights]`r`nSeLockMemoryPrivilege = *$userSid`r`n" + } + } + + Set-Content -Path $tempInf -Value $content -Encoding ASCII + + Write-Host "2. Importing updated policy database..." + secedit /import /db $tempSdb /cfg $tempInf | Out-Null + + Write-Host "3. Applying updated policy to Windows system..." + secedit /configure /db $tempSdb /cfg $tempInf /areas USER_RIGHTS | Out-Null # only the user rights, nothing else of the exported policy + + Write-Host "" + Write-Host "[SUCCESS] SeLockMemoryPrivilege has been granted to $AccountName ($userSid)!" -ForegroundColor Green + Write-Host "==========================================================================" -ForegroundColor Cyan + Write-Host "IMPORTANT: You MUST sign out of Windows and sign back in (or restart)" -ForegroundColor Yellow + Write-Host " for the new privilege to take effect on your user session." -ForegroundColor Yellow + Write-Host "==========================================================================" -ForegroundColor Cyan +} +catch { + Write-Host "[ERROR] Failed to configure privilege automatically: $_" -ForegroundColor Red + Write-Host "Please use the GUI steps via secpol.msc outlined above." +} +finally { + if (Test-Path $tempInf) { Remove-Item $tempInf -Force -ErrorAction SilentlyContinue } + if (Test-Path $tempSdb) { Remove-Item $tempSdb -Force -ErrorAction SilentlyContinue } +} From c04627331821606753a10936faf11f0997cc241a Mon Sep 17 00:00:00 2001 From: bulhenvaster Date: Tue, 13 Oct 2026 06:34:47 +0700 Subject: [PATCH 54/67] setup --update: an MTP folder shared by several configs keeps the draft subset of the most recently used one (the oldest config's default subset replaced cyrillic: Russian decode 68 -> 54 tok/s on an RTX 5060 Ti + RTX 3060, IQ3_XXS) update_install refreshed the draft subset once per installed config, newest first, so a folder that two configs name ended with the subset of the config used longest ago. A config without "draft_vocab" (cjk) then put the default subset over the cyrillic one of the config in use. Now the first config that names a folder decides; separate folders and a start (which installs its own config's subset) are as before. Checked: tools/test_setup_draft_vocab.py (3 new tests, 10 pass), test_setup_config and test_setup_configs (18 pass). Measured on the affected install, two alternating runs each, greedy 600-token Russian story: 54.0 / 54.0 tok/s with the default subset installed by the update, 68.7 / 68.6 with the cyrillic one (1.39 -> 1.90 tokens per window). --- setup.py | 23 +++++++++++++++-- tools/test_setup_draft_vocab.py | 44 +++++++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+), 2 deletions(-) diff --git a/setup.py b/setup.py index dc67e41c..e1a0df4b 100644 --- a/setup.py +++ b/setup.py @@ -4289,10 +4289,10 @@ def update_install(have: list, a) -> int: "numpy, jinja2, regex, pyyaml, tqdm, requests, cmake, ninja, pillow, psutil") if not a.build: update_installed_engine(a.prebuilt) + mtp_done: set = set() for cfg_path in have: cfg = upgrade_config(cfg_path, json.loads(cfg_path.read_text(encoding="utf-8-sig"))) - if "--mtp" in cfg["args"][:-1]: - refresh_draft_vocab(Path(cfg["args"][cfg["args"].index("--mtp") + 1]), cfg.get("draft_vocab", "cjk")) + refresh_shared_draft_vocab(cfg, mtp_done) if cfg.get("backend") == "hip" and WIN: hip_runtime_beside_exe(Path(cfg["exe"]).parent) # #468 #461 ok(f"{cfg.get('model_name', cfg_path.stem)}: up to date") @@ -4696,6 +4696,25 @@ def refresh_draft_vocab(rt: Path, choice: str = "cjk") -> None: shutil.copyfile(new, dst) +def refresh_shared_draft_vocab(cfg: dict, done: set) -> None: + """update_install's draft subset of one config, for configs taken most recently used first (installed_configs' + order): an MTP folder already in `done` is left alone. Several configs can name one MTP folder (a second config of + the same model: another GPU mode, another context), each with its own "draft_vocab". Refreshed once per config, + the folder ended with the subset of the config used LONGEST ago: a config without the key (cjk) put the default + subset over the cyrillic one of the config in use, and its Russian answers were drafted without Cyrillic tokens. + The folder takes the subset of the most recently used config that names it; a start still installs its own + config's.""" + args = cfg.get("args") or [] + if "--mtp" not in args[:-1]: + return + rt = Path(args[args.index("--mtp") + 1]) + key = os.path.normcase(os.path.abspath(rt)) + if key in done: + return + done.add(key) + refresh_draft_vocab(rt, cfg.get("draft_vocab", "cjk")) + + def ensure_engine_for(cards, cfg_path: Path, cfg: dict, yes: bool) -> dict: """The installed engine must have code for every card the model starts on: a card added later (--gpus with an older or newer generation, #128) or a new GPU in the PC otherwise stops the start with 'no kernel image'. Such a diff --git a/tools/test_setup_draft_vocab.py b/tools/test_setup_draft_vocab.py index 09cac429..33a7638f 100644 --- a/tools/test_setup_draft_vocab.py +++ b/tools/test_setup_draft_vocab.py @@ -80,6 +80,50 @@ class Refresh(unittest.TestCase): self.assertEqual(fr[len(en):], sorted(fr[len(en):])) +class SharedFolder(unittest.TestCase): + """setup.py --update refreshes the draft subset of every installed config, most recently used first. Two configs + that name one MTP folder: the folder keeps the subset of the one used last, not of the one used longest ago.""" + + def setUp(self): + self.data = ROOT / "data" + if not all((self.data / setup.DRAFT_VOCABS[c]).exists() for c in ("cjk", "cyrillic", "en")): + self.skipTest("the shipped draft subsets are not in this checkout") + self.sha = lambda p: hashlib.sha256(p.read_bytes()).hexdigest() # noqa: E731 + + def run_update(self, rt, cfgs): + done: set = set() + for cfg in cfgs: # update_install's loop, newest first + setup.refresh_shared_draft_vocab(cfg, done) + return self.sha(rt / "draft_vocab.bin") + + def test_the_most_recently_used_config_decides(self): + with tempfile.TemporaryDirectory() as d: + rt = Path(d) + (rt / "draft_vocab.bin").write_bytes((self.data / setup.DRAFT_VOCABS["cyrillic"]).read_bytes()) + in_use = {"args": ["--mtp", str(rt), "--spec", "4"], "draft_vocab": "cyrillic"} + older = {"args": ["--mtp", str(rt), "--spec", "4"]} # no key: the default subset (cjk) + self.assertEqual(self.run_update(rt, [in_use, older]), self.sha(self.data / setup.DRAFT_VOCABS["cyrillic"])) + self.assertEqual(self.run_update(rt, [older, in_use]), self.sha(self.data / setup.DRAFT_VOCABS["cjk"])) + + def test_separate_folders_each_keep_their_own(self): + with tempfile.TemporaryDirectory() as d: + a, b = Path(d) / "a", Path(d) / "b" + for rt in (a, b): + rt.mkdir() + (rt / "draft_vocab.bin").write_bytes((self.data / setup.DRAFT_VOCABS["cjk"]).read_bytes()) + done: set = set() + setup.refresh_shared_draft_vocab({"args": ["--mtp", str(a), "--spec", "4"], "draft_vocab": "cyrillic"}, done) + setup.refresh_shared_draft_vocab({"args": ["--mtp", str(b), "--spec", "4"], "draft_vocab": "en"}, done) + self.assertEqual(self.sha(a / "draft_vocab.bin"), self.sha(self.data / setup.DRAFT_VOCABS["cyrillic"])) + self.assertEqual(self.sha(b / "draft_vocab.bin"), self.sha(self.data / setup.DRAFT_VOCABS["en"])) + + def test_a_config_without_a_draft_layer_is_skipped(self): + done: set = set() + setup.refresh_shared_draft_vocab({"args": ["--spec", "0"]}, done) + setup.refresh_shared_draft_vocab({}, done) + self.assertEqual(done, set()) + + class SmallCardNote(unittest.TestCase): """#474: a card under 14 GB is told about a smaller draft subset - a note only, and not when one was chosen.""" From 01249588f40bbf5e14507a54d9312248392c6ba1 Mon Sep 17 00:00:00 2001 From: Coby Tamayo Date: Mon, 12 Oct 2026 16:54:23 -0700 Subject: [PATCH 55/67] Nix environment --- flake.lock | 27 +++++++++++++++++++++++++++ flake.nix | 53 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 80 insertions(+) create mode 100644 flake.lock create mode 100644 flake.nix diff --git a/flake.lock b/flake.lock new file mode 100644 index 00000000..43cbb9f5 --- /dev/null +++ b/flake.lock @@ -0,0 +1,27 @@ +{ + "nodes": { + "nixpkgs": { + "locked": { + "lastModified": 1791594108, + "narHash": "sha256-XK4KceonkwD8LuMAt/vNrz982mXJM5jeHAxMwsUXXAQ=", + "owner": "nixos", + "repo": "nixpkgs", + "rev": "6510408d147d8c5e6d76043e899e9251756f6a75", + "type": "github" + }, + "original": { + "owner": "nixos", + "ref": "nixos-unstable", + "repo": "nixpkgs", + "type": "github" + } + }, + "root": { + "inputs": { + "nixpkgs": "nixpkgs" + } + } + }, + "root": "root", + "version": 7 +} diff --git a/flake.nix b/flake.nix new file mode 100644 index 00000000..34607fcc --- /dev/null +++ b/flake.nix @@ -0,0 +1,53 @@ +{ + description = "Nix environment for Strata"; + + inputs = { + nixpkgs.url = "github:nixos/nixpkgs/nixos-unstable"; + }; + + outputs = { self, nixpkgs, ... }: + let + system = "x86_64-linux"; + pkgs = import nixpkgs { + inherit system; + # Claude Code plus NVIDIA's CUDA toolkit (nvcc, cudart, cuBLAS, ...). + config.allowUnfree = true; + config.cudaSupport = true; + }; + + # setup.py wants CUDA 13.0: the ready-made engine is built with 13.0.88, and 13.2.0/13.2.1 miscompile for sm_120. + cudaPackages = pkgs.cudaPackages_13_0; + # One merged toolkit root (bin/nvcc, include/, lib/ with cudart and cuBLAS) for CUDA_HOME / CUDAToolkit_ROOT. + cuda = cudaPackages.cudatoolkit; + # The gcc that this nvcc supports as its host compiler. + stdenv = cudaPackages.backendStdenv; + + in + { + devShells."${system}" = { + # Full development environment. + default = (pkgs.mkShell.override { inherit stdenv; }) { + packages = with pkgs; [ + claude-code + + # ./setup.sh: makes .venv and runs setup.py + python3 + git + + # setup.py's engine build. cmake/ninja from PATH: the pip wheels' binaries do not run on NixOS. + cuda + cmake + ninja + ]; + + shellHook = '' + export CUDA_HOME=${cuda} + export CUDA_PATH=${cuda} + export CUDAHOSTCXX=${stdenv.cc}/bin/c++ + # The pip wheels in .venv (numpy, pillow, ...) need libstdc++ and zlib; the engine needs the driver's libcuda. + export LD_LIBRARY_PATH=/run/opengl-driver/lib:${pkgs.lib.makeLibraryPath [ stdenv.cc.cc.lib pkgs.zlib ]}''${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH} + ''; + }; + }; + }; +} From 6a99330817ccaefc904d4454e8c6962352cc5776 Mon Sep 17 00:00:00 2001 From: Coby Tamayo Date: Mon, 12 Oct 2026 17:06:03 -0700 Subject: [PATCH 56/67] rm claude-code --- flake.nix | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/flake.nix b/flake.nix index 34607fcc..f1101a60 100644 --- a/flake.nix +++ b/flake.nix @@ -10,7 +10,7 @@ system = "x86_64-linux"; pkgs = import nixpkgs { inherit system; - # Claude Code plus NVIDIA's CUDA toolkit (nvcc, cudart, cuBLAS, ...). + # Allow NVIDIA's CUDA toolkit (nvcc, cudart, cuBLAS, ...). config.allowUnfree = true; config.cudaSupport = true; }; @@ -28,8 +28,6 @@ # Full development environment. default = (pkgs.mkShell.override { inherit stdenv; }) { packages = with pkgs; [ - claude-code - # ./setup.sh: makes .venv and runs setup.py python3 git From 68140bbdee4b4d7d63250e04176895769308242f Mon Sep 17 00:00:00 2001 From: Coby Tamayo Date: Mon, 12 Oct 2026 17:17:40 -0700 Subject: [PATCH 57/67] document Nix install --- docs/INSTALL.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/docs/INSTALL.md b/docs/INSTALL.md index b148e23a..1a7a4309 100644 --- a/docs/INSTALL.md +++ b/docs/INSTALL.md @@ -57,6 +57,12 @@ the build tools), and the same start: `http://127.0.0.1:8080`. Later runs of `./ start the model directly; `./setup.sh --setup` installs another model or changes the settings. Other distributions, WSL and compiling: [details](DETAILS.md#linux). +On Nix/NixOS, you can use the flake: + +```bash +nix develop -c ./setup.sh +``` + ## AMD cards The steps are the same as with NVIDIA: `START-HERE.bat` on Windows, `./setup.sh` on Linux. Setup finds the Radeon From a55fd1f24e855309db3957f72488c4eceeb1be66 Mon Sep 17 00:00:00 2001 From: Coby Tamayo Date: Mon, 12 Oct 2026 17:20:42 -0700 Subject: [PATCH 58/67] rm confusing comment --- flake.nix | 1 - 1 file changed, 1 deletion(-) diff --git a/flake.nix b/flake.nix index f1101a60..37c03aee 100644 --- a/flake.nix +++ b/flake.nix @@ -25,7 +25,6 @@ in { devShells."${system}" = { - # Full development environment. default = (pkgs.mkShell.override { inherit stdenv; }) { packages = with pkgs; [ # ./setup.sh: makes .venv and runs setup.py From e8b455117329e92498d3a22ccba0eb87f11ebe70 Mon Sep 17 00:00:00 2001 From: Coby Tamayo Date: Mon, 12 Oct 2026 17:22:59 -0700 Subject: [PATCH 59/67] rm git dep --- flake.nix | 1 - 1 file changed, 1 deletion(-) diff --git a/flake.nix b/flake.nix index 37c03aee..e5f6fc92 100644 --- a/flake.nix +++ b/flake.nix @@ -29,7 +29,6 @@ packages = with pkgs; [ # ./setup.sh: makes .venv and runs setup.py python3 - git # setup.py's engine build. cmake/ninja from PATH: the pip wheels' binaries do not run on NixOS. cuda From ca41a6b95780fa7189e6ec45d42f9e8d3dbab68e Mon Sep 17 00:00:00 2001 From: Vladimir <291339861+i-Vladimir-i@users.noreply.github.com> Date: Tue, 13 Oct 2026 03:10:34 +0300 Subject: [PATCH 60/67] serve: the image encoder only while there are pictures ("elastic": true in the vision section) Opt-in, with the config's "vram_elastic": the GPU encoder does not start with the server or a load. A picture's turn makes the expert cache keep "elastic_mib" (default 2048) free on top of the reserve and starts the encoder; after "elastic_idle_s" (default 120) without a picture a thread stops it between requests and the cache grows back to the reserve (0 when no POST /v1/vram was made: the start's reserve left it a segment or more smaller). A POST /v1/vram while the encoder runs stacks on its share; an unload stops it. Without "vram_elastic" the server says so and starts the encoder as before. serve/test_vision_elastic.py pins each case; docs in VRAM_ELASTIC.md and DETAILS.md. --- docs/DETAILS.md | 10 +++ docs/VRAM_ELASTIC.md | 19 ++++++ serve/server.py | 109 ++++++++++++++++++++++++++++--- serve/test_vision_elastic.py | 123 +++++++++++++++++++++++++++++++++++ 4 files changed, 253 insertions(+), 8 deletions(-) create mode 100644 serve/test_vision_elastic.py diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 968ba586..6525c0e9 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -1506,6 +1506,16 @@ like `nvidia-smi`) to the `"vision"` section of `strata-.json`: the encod `--vram-reserve-mib` in `"args"` to 700 as well, so the engine's cards keep that VRAM for the expert cache. The encoder's card needs code in the ready-made encoder (RTX 20/30/40/50). +**The encoder only while there are pictures (opt-in, `"elastic": true` in the `"vision"` section, with the config's +`"vram_elastic": true`; [VRAM_ELASTIC.md](VRAM_ELASTIC.md#the-image-encoder-on-demand)):** the GPU encoder does not start +with the server, so the expert cache keeps all of the VRAM. The first picture's turn makes the cache keep +`"elastic_mib"` (default 2048) free and starts the encoder there (a few seconds); later pictures use it as it is, and +after `"elastic_idle_s"` (default 120) without a picture it stops and the cache takes the VRAM back. Measured on an R9700 +32 GB (gfx1201, Linux, UD-IQ4_XS, the BF16 encoder at up to 1,024 tokens, #2189 for HIP's virtual memory): the encoder +took 1,339 MiB and started in 4.7 s (2.7 s the next time); a request with one picture took 8.6 s with the start and +5.0 s on a later cold start, and 2 / 5 / 10 pictures with the encoder running took 3.8 / 5.6 / 9.0 s (~0.45 s to encode +each, the same as on a second card). Without the key nothing changes. + ### Sending a picture **Terminal chat:** type `/image `, press Enter, then type your question. diff --git a/docs/VRAM_ELASTIC.md b/docs/VRAM_ELASTIC.md index 0b255a97..64ea795e 100644 --- a/docs/VRAM_ELASTIC.md +++ b/docs/VRAM_ELASTIC.md @@ -105,6 +105,25 @@ expert outside the cache), but I have not run a fault-injection test of these tw - `GET /v1/status` has a `vram` object with the last figures the engine reported (empty until the first successful call) and `elastic`. +## The image encoder on demand + +With `"elastic": true` in the config's `"vision"` section (and `"vram_elastic": true`; without it the server says so +and starts the encoder with the model, as before) the GPU encoder is not started with the server or with a load: + +- **A picture's turn** (the same FIFO turn an encode always takes): if the encoder is not running, the engine's + `VRAM` command first keeps `"elastic_mib"` (default 2048) free on top of the reserve - the last `POST /v1/vram`, or 0 + when none was made - and then the encoder starts. If the cache cannot shrink (the resident low-RAM mode, an engine + without `--vram-elastic`) it starts anyway, as a non-elastic encoder would, and the log says why. +- **Idle** for `"elastic_idle_s"` (default 120) without a picture: a thread stops the encoder between requests and + sends `VRAM` with that reserve again, so the cache grows back to the size it had (0, not the start's reserve: that + would leave it a segment or more smaller). +- **`POST /v1/vram` while the encoder runs** keeps the asked reserve on top of the encoder's share; the encoder's stop + then goes back to the asked reserve. +- An unload of the model stops the encoder too. The log lines start with `[strata] images:` **(code; the unit tests in + `serve/test_vision_elastic.py` pin each case)**. + +`--vram-elastic` turns `--kv-grow` off (the engine says so at start): with both asked, the whole K/V is in VRAM. + ## What to build on For automation: treat only `200` with `status: "ok"` as a call that ran, then check `vram_free_mib >= reserve_mib` diff --git a/serve/server.py b/serve/server.py index 20edde13..67d76527 100644 --- a/serve/server.py +++ b/serve/server.py @@ -2094,7 +2094,13 @@ class Vision: self.stopped = True self.lock = threading.Lock() self.cache: dict[str, tuple[Path, int]] = {} - if not lazy: + # opt-in (the vision section's "elastic": true, with the config's "vram_elastic"): the encoder starts with the + # first picture and stops after elastic_idle_s without one; while it runs, the engine's expert cache keeps + # elastic_mib of VRAM free for it (Service._vision_up / _vision_idle_down) + self.elastic = cfg.get("elastic") is True + self.elastic_mib = int(cfg.get("elastic_mib") or 2048) + self.elastic_idle_s = float(cfg.get("elastic_idle_s") or 120) + if not lazy and not self.elastic: self._start() def _start(self): @@ -2937,6 +2943,9 @@ class Service: self.vram_free_wait_s = 15.0 # how long a full card is waited on (memory given back) self.before_load_strict = False # #1997: refuse (503) whenever it fails self.vram_reserve = None # #533: the last POST /v1/vram reserve (None: the start's) + self.vram_reserve_asked = False # a POST /v1/vram was made (vram_reserve None is then asked) + self.vision_held = False # an elastic encoder holds VRAM the expert cache gave it + self.last_image_at = 0.0 # when an image turn last ended (the elastic encoder's idle) self.reasoning_loop_recovery = False self.reasoning_budget_tokens = 0 # #123: the config's default thinking budget (0: none) self.repeat_stop_tokens = REPEAT_STOP_TOKENS # #606: one token this many times in a row ends a reply (0: off) @@ -3060,7 +3069,78 @@ class Service: return value if value > 0 else None def _vision_down(self) -> bool: - return self.vision is not None and hasattr(self.vision, "alive") and not self.vision.alive() + """The encoder should run and does not (the engine's load starts it again). An elastic encoder is down + between pictures by design: it starts in the image turn (_vision_up), not with the engine.""" + return (self.vision is not None and hasattr(self.vision, "alive") and not self.vision.alive() + and not getattr(self.vision, "elastic", False)) + + def _engine_reserve(self) -> int | None: + """The VRAM the engine keeps free for other programs outside an elastic encoder's turn: the last POST /v1/vram + reserve, or 0 when none was asked (the cache grows back to its full size; None would leave the reserve the engine + started with, a segment or more below the size it had).""" + return self.vram_reserve if self.vram_reserve_asked else 0 + + def _vision_up(self): + """The image turn's start for an elastic encoder that is not running (the caller holds self.fifo): the expert + cache first keeps the encoder's elastic_mib of VRAM free on top of the reserve, then the encoder starts (load and + warm-up, a few seconds). If the cache cannot shrink (an engine without --vram-elastic, the resident low-RAM mode) + the encoder starts anyway, as a non-elastic one would.""" + v = self.vision + if not getattr(v, "elastic", False) or v.alive(): + return + if hasattr(self.engine, "vram") and self.loaded(): + try: + out = self.engine.vram((self._engine_reserve() or 0) + v.elastic_mib) + self.vision_held = True + print(f"[strata] images: the expert cache keeps {v.elastic_mib} MiB free for the image encoder " + f"({out.get('expert_cache_mib')} of {out.get('expert_cache_full_mib')} MiB left)", flush=True) + except ValueError as e: + print(f"[strata] images: the expert cache did not make room for the image encoder ({e}); starting " + "it anyway", flush=True) + free0, t0 = self.free_vram_mib(), time.time() + v.restart() + free1 = self.free_vram_mib() + took = f", {free0 - free1} MiB of VRAM" if free0 is not None and free1 is not None else "" + print(f"[strata] images: the image encoder started in {time.time() - t0:.1f} s{took}", flush=True) + + def _vision_idle_down(self, force: bool = False) -> str: + """An elastic encoder idle for elastic_idle_s (or force) stops, and the expert cache takes its VRAM back: + "down", "busy" (a request holds the turn, or a picture came more recently) or "nothing" (not elastic or not + holding anything).""" + v = self.vision + if not getattr(v, "elastic", False) or not (self.vision_held or v.alive()): + return "nothing" + if not force and time.time() - self.last_image_at < v.elastic_idle_s: + return "busy" + if not self.fifo.acquire(blocking=False): + return "busy" + try: + v.unload() + if self.vision_held and hasattr(self.engine, "vram") and self.loaded(): + out = self.engine.vram(self._engine_reserve()) + print(f"[strata] images: the image encoder stopped after {v.elastic_idle_s:g} s without a picture; " + f"the expert cache took its VRAM back ({out.get('expert_cache_mib')} of " + f"{out.get('expert_cache_full_mib')} MiB)", flush=True) + self.vision_held = False + return "down" + finally: + self.fifo.release() + + def start_vision_idle(self): + v = self.vision + if not getattr(v, "elastic", False): + return + print(f"[strata] images: the image encoder starts with the first picture and stops after {v.elastic_idle_s:g} s " + f"without one; while it runs the expert cache keeps {v.elastic_mib} MiB free for it", flush=True) + + def loop(): + while True: + time.sleep(max(1.0, min(30.0, v.elastic_idle_s / 4))) + try: + self._vision_idle_down() + except Exception as e: # tried again at the next turn; the thread keeps running + print(f"[strata] images: stopping the idle image encoder: {e}", flush=True) + threading.Thread(target=loop, daemon=True).start() def free_vram_mib(self) -> int | None: """Free VRAM on the engine's (first) GPU, from NVML (AMD backend: amdgpu's sysfs files, #301); None when it can't @@ -3182,11 +3262,12 @@ class Service: raise ModelBusy("a request is still running; try again when it has finished") try: if not self.loaded(): - self.vram_reserve = reserve_mib + self.vram_reserve, self.vram_reserve_asked = reserve_mib, True return {"status": "not loaded", "reserve_mib": reserve_mib, "note": "applied when the model loads"} - out = self.engine.vram(reserve_mib) - self.vram_reserve = reserve_mib + # an elastic encoder that runs keeps its VRAM on top of the asked reserve + out = self.engine.vram((reserve_mib or 0) + self.vision.elastic_mib if self.vision_held else reserve_mib) + self.vram_reserve, self.vram_reserve_asked = reserve_mib, True print(f"[strata] VRAM: {out.get('vram_free_mib')} MiB free, expert cache {out.get('expert_cache_mib')} of " f"{out.get('expert_cache_full_mib')} MiB ({out.get('expert_slots')} experts)", flush=True) return {"status": "ok", **out} @@ -3265,6 +3346,7 @@ class Service: self.engine.unload() if self.vision is not None and hasattr(self.vision, "unload"): self.vision.unload() + self.vision_held = False print(f"[strata] model unloaded{f' after {idle_for:.0f} s idle' if idle_for else ''}; " "the next request loads it again", flush=True) return "unloaded" @@ -3633,8 +3715,12 @@ class Service: # "reading the prompt" with CPU and GPU busy, for good (reproduced). So encoding takes its turn in the # same FIFO as the requests. with self._turn(cancel): - encoded = (self.vision.encode_all(images, cancel) if hasattr(self.vision, "encode_all") - else [self.vision.encode(src) for src in images]) + self._vision_up() + try: + encoded = (self.vision.encode_all(images, cancel) if hasattr(self.vision, "encode_all") + else [self.vision.encode(src) for src in images]) + finally: + self.last_image_at = time.time() # one <|image_pad|> per image -> one per image token. Only the markers the template writes for an image # (right after <|vision_start|>) are images: the same text inside a message (an agent reading these docs, # #150) is kept as plain text, or it took an image's place and the counts no longer matched. @@ -6394,12 +6480,18 @@ def main() -> int: print(f"[strata] sampling defaults from the config: {pretty}", flush=True) lazy = a.lazy or cfg.get("lazy_load") is True if cfg.get("vision"): - print("loading the vision encoder ..." if not lazy else + elastic = cfg["vision"].get("elastic") is True and cfg.get("vram_elastic") is True + print("the vision encoder starts with the first picture (elastic) ..." if elastic else + "loading the vision encoder ..." if not lazy else "vision encoder unloaded; it starts with the model ...", flush=True) # relative paths are the config's cwd's, as for the engine below vcfg = {k: (os.path.abspath(os.path.join(cfg.get("cwd") or ".", v)) if k in ("exe", "mmproj", "model") and isinstance(v, str) and not os.path.isabs(v) else v) for k, v in cfg["vision"].items()} + if vcfg.get("elastic") is True and cfg.get("vram_elastic") is not True: + print('[strata] the vision section\'s "elastic" needs "vram_elastic": true (the expert cache gives the ' + "encoder its VRAM): the encoder starts with the model instead", flush=True) + vcfg["elastic"] = False vision = Vision(vcfg, log=open(cfg["log"], "a", encoding="utf-8") if cfg.get("log") else None, env=vision_env(cfg, env), lazy=lazy) print("model unloaded; the first request loads it ..." if lazy else @@ -6585,6 +6677,7 @@ def main() -> int: atexit.register(hub.close) # the servers Strata started end with it httpd = serve(svc, host=a.host, port=a.port) svc.start_idle_unload() + svc.start_vision_idle() here = "127.0.0.1" if a.host in ("0.0.0.0", "", "::") else a.host print(f"ready: http://{here}:{a.port}/v1 (OpenAI: /v1/chat/completions, Anthropic: /v1/messages, " f"context {engine.max_context} tokens{', images on' if vision else ''}" diff --git a/serve/test_vision_elastic.py b/serve/test_vision_elastic.py new file mode 100644 index 00000000..b8516b1a --- /dev/null +++ b/serve/test_vision_elastic.py @@ -0,0 +1,123 @@ +"""The elastic image encoder (the vision section's "elastic": true with "vram_elastic"): the first picture makes the +expert cache keep the encoder's VRAM free and then starts it, later pictures use it as it is, an idle encoder stops and +the cache takes its VRAM back, a POST /v1/vram reserve stacks on the encoder's share, and the engine's load never starts +it on its own.""" +import tempfile +import time +import unittest +from pathlib import Path + +from serve.frontend import ChatTemplate +from serve.server import ByteTokenizer, Service, Vision +from serve.test_vram import VramEngine + +ROOT = Path(__file__).resolve().parents[1] +IMAGE = {"type": "image", "source": "x.png"} + + +class ElasticVision: + """An encoder process stand-in: starts, stops, and turns every picture into three image tokens.""" + def __init__(self, d, elastic=True): + self.elastic, self.elastic_mib, self.elastic_idle_s = elastic, 2048, 60.0 + self.up, self.starts, self.unloads = False, 0, 0 + self.dir = Path(d) + self.rows = self.dir / "img.sve" + self.rows.write_bytes(b"rows") + + def alive(self): + return self.up + + def restart(self): + self.up, self.starts = True, self.starts + 1 + + def unload(self): + self.up, self.unloads = False, self.unloads + 1 + + def encode(self, source): + assert self.up, "a picture reached an encoder that was not started" + return self.rows, 3 + + +class Elastic(unittest.TestCase): + def setUp(self): + d = tempfile.mkdtemp() + self.tok = ByteTokenizer() + self.engine = VramEngine(self.tok) + self.engine.loaded = True + self.vision = ElasticVision(d) + self.svc = Service(self.engine, self.tok, ChatTemplate(ROOT / "serve/chat_template.jinja"), vision=self.vision) + self.addCleanup(self.drop_embeddings) + + def drop_embeddings(self): + path = getattr(getattr(self.svc, "embeddings", None), "path", None) + if path is not None: + path.unlink(missing_ok=True) + + def picture(self): + self.svc.prepare([{"role": "user", "content": [{"type": "text", "text": "what is it"}, IMAGE]}], None, {}) + + def test_the_first_picture_makes_room_then_starts_the_encoder(self): + self.picture() + self.assertEqual(self.engine.calls, [2048]) # the cache keeps the encoder's share free first + self.assertEqual(self.vision.starts, 1) + self.assertTrue(self.svc.vision_held) + self.picture() # the next one uses the running encoder + self.assertEqual(self.engine.calls, [2048]) + self.assertEqual(self.vision.starts, 1) + + def test_an_idle_encoder_stops_and_the_cache_grows_back_whole(self): + self.picture() + self.assertEqual(self.svc._vision_idle_down(), "busy") # a picture came just now + self.svc.last_image_at = time.time() - 61 + with self.svc.fifo: # a request holds the turn + self.assertEqual(self.svc._vision_idle_down(), "busy") + self.assertEqual(self.svc._vision_idle_down(), "down") + self.assertFalse(self.vision.up) + self.assertFalse(self.svc.vision_held) + self.assertEqual(self.engine.calls, [2048, 0]) # 0, not None: the full size, not the start's reserve + self.assertEqual(self.svc._vision_idle_down(), "nothing") + self.picture() # and the next picture starts it again + self.assertEqual(self.vision.starts, 2) + self.assertEqual(self.engine.calls, [2048, 0, 2048]) + + def test_a_vram_reserve_stacks_on_the_encoders_share(self): + self.svc.vram(4000) + self.picture() + self.assertEqual(self.engine.calls, [4000, 6048]) + self.svc.vram(1000) # asked while the encoder runs + self.assertEqual(self.engine.calls[-1], 3048) + self.svc.last_image_at = 0 + self.svc._vision_idle_down() + self.assertEqual(self.engine.calls[-1], 1000) # back to the asked reserve, not to 0 + + def test_an_engine_that_cannot_shrink_still_gets_its_encoder(self): + self.engine.elastic = False + self.picture() + self.assertEqual(self.vision.starts, 1) + self.assertFalse(self.svc.vision_held) + self.svc.last_image_at = 0 + self.assertEqual(self.svc._vision_idle_down(), "down") + self.assertEqual(self.engine.calls, [2048]) # the refused shrink only: nothing to give back + + def test_the_load_never_starts_an_elastic_encoder(self): + self.assertFalse(self.svc._vision_down()) + self.svc.vision = ElasticVision(tempfile.mkdtemp(), elastic=False) + self.assertTrue(self.svc._vision_down()) # a non-elastic encoder that is down is started again + + def test_an_unload_lets_go_of_the_share(self): + self.picture() + self.assertEqual(self.svc.unload(), "unloaded") + self.assertFalse(self.svc.vision_held) + self.assertFalse(self.vision.up) + + def test_the_config_keys(self): + v = Vision({"exe": "e", "mmproj": "m", "model": "t", "elastic": True, "elastic_mib": 3000, + "elastic_idle_s": 30}, lazy=False) # elastic: nothing starts with the server + self.assertTrue(v.elastic and v.elastic_mib == 3000 and v.elastic_idle_s == 30 and not v.alive()) + v = Vision({"exe": "e", "mmproj": "m", "model": "t"}, lazy=True) + self.assertFalse(v.elastic) + self.assertEqual((v.elastic_mib, v.elastic_idle_s), (2048, 120.0)) + + +if __name__ == "__main__": + unittest.main() From 8488c06bba598c4874105912a93c62c731077064 Mon Sep 17 00:00:00 2001 From: Vladimir <291339861+i-Vladimir-i@users.noreply.github.com> Date: Tue, 13 Oct 2026 03:48:02 +0300 Subject: [PATCH 61/67] serve: the elastic encoder's VRAM figure after the driver's counter caught up The figure in "[strata] images: the image encoder started in N s, M MiB of VRAM" read the free VRAM right after the cache's shrink, before the driver's counter showed it (amdgpu sysfs), so it came out low (286-362 MiB against the 1,339 measured otherwise). A 0.2 s wait before that reading, only on a start that shrank the cache. --- serve/server.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/serve/server.py b/serve/server.py index 67d76527..eec1bf36 100644 --- a/serve/server.py +++ b/serve/server.py @@ -3097,6 +3097,8 @@ class Service: except ValueError as e: print(f"[strata] images: the expert cache did not make room for the image encoder ({e}); starting " "it anyway", flush=True) + if self.vision_held: + time.sleep(0.2) # the driver's free-VRAM counter shows the cache's release a moment later free0, t0 = self.free_vram_mib(), time.time() v.restart() free1 = self.free_vram_mib() From 640ac438be9e79af219c8fb022cbb03cf3a477c5 Mon Sep 17 00:00:00 2001 From: Maxim Mazurok Date: Tue, 13 Oct 2026 09:29:20 +1100 Subject: [PATCH 62/67] --prefill-head-alias (opt-in, --serve, one GPU): the output head's VRAM holds the prompt buffers while a prompt is read The native output head is needed only to generate, the batched prompt path's buffers only to read a prompt. With the flag the head is unloaded while a prompt is read (its VRAM counted into the auto cache and the prompt path's hybrid borrowed/owned layout) and read back in before the first decode window. On an 8 GB RTX PRO 2000 Laptop (Windows, IQ3_XXS, 590 MiB reserve) the prompt chunk went from 512 to 2,048 tokens and prefill from 292.5 to 667.1 tok/s on a 29,854-token prompt; reads of up to 512 fresh tokens cost about 0.6-0.75 s more. Off by default: every new path is behind the flag. docs/PREFILL_HEAD_ALIAS.md has the measurements and limits. --- docs/DETAILS.md | 6 + docs/PREFILL_HEAD_ALIAS.md | 170 ++++++++++++++++++++++++++++ include/strata/core/mtp.hpp | 1 + include/strata/core/native_head.hpp | 1 + include/strata/prefill/prefill.hpp | 3 +- src/core/native_head.cpp | 6 + src/prefill/prefill.cpp | 16 ++- src/program/generate.cpp | 143 ++++++++++++++++++----- sycl/src/prefill/prefill.cpp | 6 +- 9 files changed, 319 insertions(+), 33 deletions(-) create mode 100644 docs/PREFILL_HEAD_ALIAS.md diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 6525c0e9..d703d9c0 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -1763,6 +1763,12 @@ the pairs in which the switched arm won). They are here so you can try them on y tier's copies for layer 45 never landed" (RTX 4070 SUPER, driver 617.42). `STRATA_ADAPT_SIGNAL=copy` asks for the copy there; the engine now flushes the copy stream after queueing the swaps, which is meant to fix it but has not been run on Windows yet. +- **`--prefill-head-alias` (`--serve`, one GPU): the output head's VRAM holds the prompt buffers while a prompt is read**, + and the head is read back in before the first generated token. It was not measured with the paired method above. On + an 8 GB RTX PRO 2000 Laptop (Windows, IQ3_XXS, 590 MiB reserve) it let the prompt path use 2,048-token chunks + instead of 512: prefill 292.5 -> 667.1 tok/s on a 29,854-token prompt (medians of 12 and 6 fresh-engine trials). + Reads of up to 512 fresh tokens cost about 0.6-0.75 s more per request, and the card had 0 MiB free while decoding. + Details, limits and the measurement: [PREFILL_HEAD_ALIAS.md](PREFILL_HEAD_ALIAS.md). ## Thread placement: `--aux-cpus` (Linux, off by default) diff --git a/docs/PREFILL_HEAD_ALIAS.md b/docs/PREFILL_HEAD_ALIAS.md new file mode 100644 index 00000000..b0506303 --- /dev/null +++ b/docs/PREFILL_HEAD_ALIAS.md @@ -0,0 +1,170 @@ +# Lend the output head's VRAM to the prompt path (`--prefill-head-alias`, opt-in) + +Two large VRAM users never work at the same time. The native output head (417 MiB for the Q5_K head of +IQ3_XXS) turns the last hidden state into logits, so it is needed only while tokens are generated. The batched prompt +path's buffers are needed only while a prompt is read. With `--prefill-head-alias` the engine takes turns: the head's +VRAM holds prompt buffers while a prompt is read, and the head is read back in before the first generated token. + +The flag is off by default. With it off, the engine does exactly what it did before. + +## Why + +On an 8 GB card the prompt chunk is as large as the free VRAM allows, and prefill speed follows the chunk closely. Here +is the same 29,854-token prompt with a fresh engine per trial and one request each. The card and settings are listed +under [Measurements](#measurements). + +| Prompt chunk | Trials | Prefill, median (range) | How the engine got there | Free VRAM after start | +|---:|---:|---:|---|---:| +| 256 | 4 | 185.5 (177.8-195.9) tok/s | `--prefill auto`, reserve 686-745 MiB | 383-443 MiB | +| 512 | 12 | 292.5 (281.0-306.1) tok/s | `--prefill auto`, reserve 442-667 MiB (590 is our tuned value) | 137-365 MiB | +| 768 | 7 | 387.4 (375.8-397.2) tok/s | `--prefill auto`, reserve 331-405 MiB | 27-103 MiB | +| 1,024 | 4 | 442.9 (440.8-444.1) tok/s | `--prefill auto`, reserve 239-295 MiB | 0 MiB | +| 1,280 | 5 | 514.5 (512.8-517.3) tok/s | `--prefill auto`, reserve 147-221 MiB | 0 MiB | +| 1,536 | 2 | 573.6 (571.0-576.3) tok/s | `--prefill auto`, reserve 73-110 MiB | 0 MiB | +| 1,792 | 3 | 631.4 (628.7-632.9) tok/s | `--prefill auto`, reserve 0-36 MiB | 0 MiB | +| **2,048** | **6** | **667.1 (661.5-667.7) tok/s** | **`--prefill-head-alias`, reserve 590 MiB** | **289 MiB** | + +Without the flag, every chunk above 768 tokens came only from lowering `--vram-reserve-mib`, and that left 0 MiB free. +Under WDDM that is the state in which Windows starts paging. With the flag, the 2,048-token chunk came with the 590 MiB +reserve unchanged. + +## What it does + +1. **At start**, after the MTP draft layer has copied its draft-head rows from the output head, the head is unloaded. + The auto expert cache is then sized with the head's VRAM counted as free (on our card: 749 slots instead of 508). + The prompt path borrows cache slots 1 to N (slot 0 stays). Whatever does not fit there is allocated by the prompt + path itself, which makes a "hybrid" layout. The chunk is the largest of 2,048, 1,536, 1,024 and 512 tokens whose + buffers fit in the borrowed slots plus free VRAM with 512 MiB to spare. +2. **For each request**: + 1. If the head is loaded, unload it and lay the prompt path out again (median 20 ms). + 2. Read the prompt. + 3. Refill the lent slots and free the prompt path's own buffers. + 4. Load the head again (median 255 ms) before the first decode window. +3. **Graph safety.** The verify windows' CUDA graphs are captured during the first decode and hold the head's address. + If a later reload puts the head at a different address, the engine stops with an error, and the server starts it + again. It does not run graphs that point at freed memory. We never saw this happen; see + [Open questions](#open-questions). + +The engine refuses the flag, with the reason, without `--serve`, with more than one GPU or a layer split, with +`--batch`, with `--pipeline-windows`, with `--short-read` above 0, with a fixed `--expert-cache` above 1, without `--mtp`, +or without the native output head. + +## Costs + +- **Short reads get slower.** Each request reloads the head (median 255 ms over 2,717 restores, p90 261 ms, max + 495 ms) and rebuilds the prompt path (20 ms). It also lends and then refills almost the whole cache, even for a few + tokens. The engine's own prompt time, which includes all of this, by fresh tokens read (production, medians): + + | Fresh tokens read | Default | Head alias | + |---:|---:|---:| + | 1-64 | 671 ms (293 requests) | 1,311 ms (614) | + | 65-512 | 1,703 ms (409) | 2,453 ms (955) | + | 513-2,048 | 4,062 ms (278) | 3,331 ms (618) | + | 2,049-8,192 | 15,206 ms (118) | 6,876 ms (277) | + + So the flag costs about 0.6-0.75 s on reads of up to 512 tokens and pays off from somewhere between 513 and 2,048 + tokens. In the agent loop, 614 of 2,717 requests read 64 fresh tokens or fewer. +- **Less free VRAM while decoding.** In the default run, the verify windows were captured with 207-287 MiB free. With + the flag, they were captured with 0 MiB free. Over 2,717 requests (about 26 hours) we saw no paging symptoms: decode + held about 29 tok/s from the first request to the last (table below). This is the main risk on other cards and + drivers. +- **More slots to refill after each prompt.** The prompt path borrows almost the whole cache (748 of 749 slots instead + of 328 of 508), so more experts are copied back after each prompt. That time is counted in the prompt time above. + +## Measurements + +Card and settings for every number on this page: + +- NVIDIA RTX PRO 2000 Blackwell Laptop GPU, 8,151 MiB, Windows 11 Pro (WDDM, driver 597.16), CUDA 13.0, sm_120. +- Intel Core Ultra 9 285H (AVX2), 64 GiB RAM, PCIe probe 25 GB/s (`pcie_frac` 0.55 picked by auto). +- Qwen3.8-Flash-Next IQ3_XXS native pack, `--max-context 262144`, `--kv q4_0`, `--kv-resident 32768`, `--spec 4`, + `--spec-min-p 0.5`, MTP with the English draft vocabulary, `--prompt-cache 3`, `--vram-reserve-mib 590`, + `--expert-cache auto`, `--prefill auto`. +- The engine was a local 0.1.41 build with this change. Both sides also used a local `STRATA_ARENA_REGISTER=0` switch + that is not part of this change: it skips `cudaHostRegister` of the 40 GiB arena on this machine. + +### Controlled: one prompt, one forced output + +Each trial ran a fresh engine on the 29,854-token prompt. The same 3,072-token continuation was forced one verify row per +token, with no speculative drafts, so the decode numbers compare the same work. A local benchmark switch did the forcing; +it is not part of this change. + +| Setting | Trials | Expert slots | Prompt chunk | Prefill | Decode | Expert-cache hits | +|---|---:|---:|---:|---:|---:|---:| +| 1-slot cache | 4 | 1 | 1,024 (own buffers) | 441.0 tok/s | 22.26 tok/s | 0.2% | +| 1-slot cache + head alias | 2 | 1 | 2,048 | 666.3 tok/s | 24.50 tok/s | 0.2% | +| auto cache + head alias | 3 | 749 | 2,048 | 667.7 tok/s | 26.21 tok/s | 24.9% | + +We did not run the default (auto cache, no head alias) in this forced mode. Its free-running result on the same prompt +is the 512-token row of the first table: one trial at the 590 MiB reserve read 306.1 tok/s and decoded 27.9 tok/s, and +six head-alias trials decoded 26.6-29.0 tok/s (median 27.9). Free-running outputs differ from trial to trial, so their +decode rates are only a rough comparison. + +### Production: an agent loop + +The workload was OpenCode agents (worker, reviewer and retrospective) running a coding loop against `/v1/chat/completions`. +Prompts went up to about 150K tokens, with `--prompt-cache 3` prefix reuse. + +- Default: 1,200 requests over 8 loop cycles. +- `--prefill-head-alias`: 2,649 requests over 20 cycles. + +The flag also needs `--short-read 0`; the default run had 64. Everything else was the same. Rates come from the engine's +own lines (`reading the prompt` progress over at least 5 s, and the decode rate of requests with at least 32 output +tokens). They are compared inside 16K-token context bands, so a heavier or lighter mix of prompts on either side does not +count as a speed change. Intervals are 95% bootstrap intervals. + +| | Default | Head alias | Change within context bands | +|---|---:|---:|---:| +| Prefill, median | 256 tok/s | 583 tok/s | +125% (+123% to +129%) | +| Decode, median | 24.8 tok/s | 29.2 tok/s | +19% (+17% to +23%) | +| Expert-cache hits, median | 20.8% | 25.9% | 508 -> 749 slots | + +The decode difference needs care. The default runs alternated between long stretches near 27.5 tok/s and long stretches +near 19.5 tok/s. A rolling median over 51 requests showed plateaus of hundreds of requests each, and in one run the +switch from slow to fast came with no engine restart. In the head-alias run, each twelfth of the 2,649 requests had a +median decode of 28.7-29.8 tok/s. Against the default's +fast stretches only, decode was about 6% faster. We do not know what caused the slow stretches, so we do not claim that +this change removes them. + +The engine binary was also rebuilt between the two runs, to add prompt-cache support to this change. The controlled +table above is the comparison that holds the binary fixed. + +## Port check on 0.1.43.1 + +This change was moved to upstream main (0.1.43.1) and checked on the same PC. Both runs used the same build, a fresh +engine each, and `STRATA_ARENA_PIN_GIB=auto`: without it, the full sliced arena pin on this 64 GB PC left WDDM with +0 GiB free for the cache (#243). The requests were the 29,842-token prompt cold, then a 31-token follow-up on its +prefix, two 45-token prompts, and the long prompt again. Output was capped at 768 tokens with low reasoning, and +generation was free (not forced). + +| | Default | Head alias | +|---|---:|---:| +| Expert slots, prompt chunk | 507, 512 | 753, 2,048 | +| Free VRAM when the verify windows were captured | 207-245 MiB | 0 MiB | +| Cold 29,842-token prompt, two runs | 276.5, 277.1 tok/s | 643.1, 649.7 tok/s | +| Decode on those two | 35.7, 34.7 tok/s | 34.1, 31.6 tok/s | +| 31-token follow-up (29,837 reused), prompt time | 632 ms | 1,721 ms | +| 45-46-token prompts, prompt time | 871, 1,005 ms | 1,780, 1,424 ms | + +All five requests completed with coherent answers. The head came back at the same address every time, so the guard +never fired. 0.1.43.1's new start-of-request warning ("below 1024 MiB free") appears with both settings, at 289 MiB +for the default and 0 MiB with the flag. + +## Open questions + +- **A fixed address for the head.** The head goes back with `cudaMalloc`, which does not promise the same address. The + check above makes a moved head a clean engine restart. A cleaner design would keep the head's virtual range and swap + its backing (CUDA VMM), or lay prompt buffers directly into the head's allocation instead of freeing it. +- **Skip the swap for short reads.** A request that reads a few dozen fresh tokens pays about 0.6 s (table above) for a + 2,048-token chunk it does not need. A threshold on fresh tokens, below which the head stays and the read goes through + the decode windows as `--short-read` does, would remove that cost. +- **Other cards.** We measured only the 8 GB card above, on Windows. A larger card already gets a large chunk without + the flag, so we expect the gain to be smaller there. + +## Not tested + +- This change on upstream main (0.1.43.1) was compiled for CUDA (13.0, sm_120, MSVC, Windows) and checked with the + short run above. The longer measurements come from the 0.1.41 build. +- HIP (the same sources) and SYCL. On SYCL, `Prefill::init` refuses the hybrid layout; the SYCL engine has no flag + for it. +- Linux, multi-GPU, `--batch` and `--pipeline-windows` (all refused), and models other than Qwen3.8-Flash-Next IQ3_XXS. diff --git a/include/strata/core/mtp.hpp b/include/strata/core/mtp.hpp index 205f2385..d3c05a98 100644 --- a/include/strata/core/mtp.hpp +++ b/include/strata/core/mtp.hpp @@ -82,6 +82,7 @@ public: /// 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, const MtpDrafter* shared = nullptr); + void set_window_R(const float* window_R) { window_R_ = window_R; } /// Prompt cells [cell0, cell0 + n): residual rows `R_rows` (device, hc*n_embd each) and `next_tokens` (host, /// the token at position cell+1). Runs in batches of up to max_t rows. `sync` false: returns without waiting diff --git a/include/strata/core/native_head.hpp b/include/strata/core/native_head.hpp index 54562949..501f6ec2 100644 --- a/include/strata/core/native_head.hpp +++ b/include/strata/core/native_head.hpp @@ -20,6 +20,7 @@ public: NativeHead& operator=(const NativeHead&) = delete; bool load(const std::vector& shards, int64_t n_in, int64_t n_out, std::string& err); + void unload(); bool run(const float* mixed, float* logits, void* stream, std::string& err) const; uint64_t weight_bytes() const { return bytes_; } bool loaded() const { return weights_ != nullptr; } diff --git a/include/strata/prefill/prefill.hpp b/include/strata/prefill/prefill.hpp index 1f0ad13f..b4f100df 100644 --- a/include/strata/prefill/prefill.hpp +++ b/include/strata/prefill/prefill.hpp @@ -69,7 +69,8 @@ public: /// lent for the prompt and refilled after it); null = allocate normally. bool init(const core::WeightTable& wt, const core::ModelGeometry& g, core::SessionState& ss, core::ExpertSource* src, const core::ExpertCache* cache, const int32_t* host_res, int64_t chunk, - void* stream, std::string& err, void* borrow = nullptr, uint64_t borrow_bytes = 0); + void* stream, std::string& err, void* borrow = nullptr, uint64_t borrow_bytes = 0, + bool borrow_spill = false); /// With borrowed buffers: lay them out again for chunks of `chunk` tokens (at most `init`'s) in `borrow` - a /// request lends only the slots its prompt needs. The stream must be idle (between prompts). diff --git a/src/core/native_head.cpp b/src/core/native_head.cpp index 93ec0fd2..daa381e7 100644 --- a/src/core/native_head.cpp +++ b/src/core/native_head.cpp @@ -13,9 +13,15 @@ namespace strata::core { NativeHead::~NativeHead() { + unload(); +} + +void NativeHead::unload() { if (weights_) strata::kernels::native_q6_k_unpack(weights_); if (scratch_) cudaFree(scratch_); if (weights_) cudaFree(weights_); + scratch_ = nullptr; + weights_ = nullptr; } bool NativeHead::load(const std::vector& shards, int64_t n_in, int64_t n_out, std::string& err) { diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index 3f537abd..87614659 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -376,6 +376,7 @@ struct Alloc { uint64_t failed_bytes = 0; ///< the take that could not be allocated; the failure message names it uint64_t granule = 0; ///< count_only: each take rounds up to this (cudaMalloc's 2 MiB pages: owned buffers) bool count_only = false; + bool spill = false, spilled = false; std::vector* owned = nullptr; template T* take(size_t n, bool& ok) { uint64_t bytes = ((uint64_t) n * sizeof(T) + 256 + 255) & ~255ull; @@ -384,14 +385,15 @@ struct Alloc { used += bytes; return nullptr; } - if (base != nullptr) { - if (used + bytes > cap) { ok = false; failed_bytes = bytes; return nullptr; } + if (base != nullptr && !spilled && used + bytes <= cap) { T* p = (T*) (base + used); used += bytes; return p; } + if (base != nullptr && !spill) { ok = false; failed_bytes = bytes; return nullptr; } void* p = nullptr; if (cudaMalloc(&p, bytes) != cudaSuccess) { ok = false; failed_bytes = bytes; return nullptr; } + spilled = true; owned->push_back(p); used += bytes; return (T*) p; @@ -746,7 +748,7 @@ struct Prefill::Impl { const core::ExpertCache* cache = nullptr; const int32_t* host_res = nullptr; int64_t T = 0, T_max = 0; - bool borrowed = false; + bool borrowed = false, borrow_spill = false; cudaStream_t cs = nullptr, copy = nullptr; Gemm gemm; std::vector owned; @@ -1060,7 +1062,7 @@ uint64_t moe_set_bytes(size_t T, int64_t n_expert, bool fused) { bool Prefill::init(const core::WeightTable& wt, const core::ModelGeometry& g, core::SessionState& ss, core::ExpertSource* src, const core::ExpertCache* cache, const int32_t* host_res, int64_t chunk, - void* stream, std::string& err, void* borrow, uint64_t borrow_bytes) { + void* stream, std::string& err, void* borrow, uint64_t borrow_bytes, bool borrow_spill) { Impl& m = *impl_; m.wt = &wt; m.g = &g; m.ss = &ss; m.src = src; m.cache = cache; m.host_res = host_res; m.T = chunk; m.cs = (cudaStream_t) stream; m.stats = &stats_; @@ -1093,6 +1095,7 @@ bool Prefill::init(const core::WeightTable& wt, const core::ModelGeometry& g, co const size_t T = (size_t) chunk; m.T_max = chunk; m.borrowed = borrow != nullptr; + m.borrow_spill = m.borrowed && borrow_spill; bool ok = true; // one-time: events, the stager, the host buffers (for the largest chunk), the identity page table for (int i = 0; i < ring_cap(); ++i) { @@ -1182,6 +1185,7 @@ bool Prefill::init(const core::WeightTable& wt, const core::ModelGeometry& g, co Alloc o; o.base = (uint8_t*) borrow; o.cap = borrow_bytes; + o.spill = m.borrow_spill; o.owned = &m.owned; { uint16_t* gs = o.take((size_t) GEMM_SCRATCH, ok); @@ -1310,6 +1314,10 @@ bool Prefill::carve(size_t T, void* alloc) { bool Prefill::relayout(int64_t chunk, void* borrow, uint64_t borrow_bytes, std::string& err) { Impl& m = *impl_; + if (m.borrow_spill) { + err = "prefill: a hybrid borrowed/owned layout cannot be changed between requests"; + return false; + } if (!m.borrowed || borrow == nullptr || chunk <= 0 || chunk > m.T_max) { err = "prefill: relayout needs borrowed buffers and a chunk of at most " + std::to_string(m.T_max); return false; diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 94e5ff0f..b417aab3 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -645,6 +645,7 @@ struct Options { /// result) goes through the verify windows, S tokens at a time, instead of the batched prompt path (0 = always /// the batched path) int64_t short_read = 64; + bool prefill_head_alias = false; // lend the native output head's VRAM to prompt buffers between request phases /// --pipeline-windows N (--serve, a layer split on exactly two GPUs; opt-in): 1 = a prompt's short reads through /// the verify windows run with the stages overlapped (stage 0 reads window K+1 while stage 1 reads window K); /// 2 = the decode windows too: stage 0 runs window K+1 speculatively while stage 1 verifies window K (rolled back @@ -800,6 +801,8 @@ void usage() { " the conversation checkpoint (a trailing effort turn; default -1 = off)\n" " --short-read N --serve: read at most N fresh text tokens through the decode windows instead\n" " of the batched prompt path (default 64, 0 = off)\n" + " --prefill-head-alias --serve: unload the native output head while each fresh prompt is read,\n" + " then release prompt buffers and reload it before decode\n" " --suffix-draft N prompt lookup: draft from an earlier repeat of the last N+ tokens of context\n" " when it pays (default 3; 0 = MTP only)\n" " --mtp-max-t M cap the MTP's windows at M tokens (0 = --spec; longer ones come from suffixes)\n" @@ -2083,6 +2086,7 @@ int main(int argc, char** argv) { else if (a == "--turn-token") o.turn_token = std::atoll(next("--turn-token")); else if (a == "--tail-role-token") o.tail_role_token = std::atoll(next("--tail-role-token")); else if (a == "--short-read") o.short_read = std::max(0LL, std::atoll(next("--short-read"))); + else if (a == "--prefill-head-alias") o.prefill_head_alias = true; else if (a == "--pipeline-windows") o.pipeline_windows = std::max(0, std::min(2, std::atoi(next("--pipeline-windows")))); else if (a == "--suffix-draft") o.suffix_draft = std::max(0, std::atoi(next("--suffix-draft"))); else if (a == "--mtp-max-t") o.mtp_max_t = std::max(0, std::atoi(next("--mtp-max-t"))); @@ -4598,6 +4602,31 @@ int main(int argc, char** argv) { std::fprintf(stderr, "strata generate: the logits buffer failed%s\n", vram_free_note().c_str()); return 1; } + bool prefill_head_alias_bound = false; + const void* prefill_head_alias_at = nullptr; // where the head came back the first time + if (o.prefill_head_alias) { + const char* why = !o.serve ? "it needs --serve" + : multi_gpu || !stages.empty() ? "it supports one GPU only" + : o.batch > 0 ? "it does not support --batch" + : o.pipeline_windows > 0 ? "it does not support --pipeline-windows" + : o.short_read > 0 ? "it needs --short-read 0" + : o.expert_cache != 1 && o.expert_cache >= 0 ? "it needs --expert-cache 1 or auto" + : o.mtp.empty() ? "it needs --mtp" + : !native_head.loaded() ? "it needs the native output head" + : nullptr; + if (why != nullptr) { + std::fprintf(stderr, "strata generate: --prefill-head-alias is unavailable: %s\n", why); + return 2; + } + if (!mtp.bind(wt, &native_head, nullptr, err)) { + std::fprintf(stderr, "strata generate: --prefill-head-alias: %s\n", err.c_str()); + return 1; + } + native_head.unload(); + prefill_head_alias_bound = true; + std::fprintf(stderr, "strata generate: --prefill-head-alias: the %llu-byte output head is prompt workspace\n", + (unsigned long long) native_head.weight_bytes()); + } // 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 && !early_remote) { @@ -4909,6 +4938,10 @@ int main(int argc, char** argv) { if (o.expert_cache < 0) { size_t free_b = 0, total_b = 0; free_b = strata::core::device_free_bytes(); (void) total_b; + if (free_b == 0 && o.prefill_head_alias) { + (void) cudaGetLastError(); + free_b = strata::core::device_free_bytes(); + } // Plan v0.3 P5: the batched prompt path's chunk buffers are allocated later, so they are reserved here - // under WDDM an over-subscribed allocation does not fail, it pages to system memory and crawls. // (with borrowing - the default with a profile - the prompt path lends cache slots instead; `pf_borrow` is @@ -7309,6 +7342,27 @@ int main(int argc, char** argv) { } else if (o.prefill_auto && d_res == nullptr) { o.prefill_chunk = 1024; // #85: no expert cache at all (a full 8 GB card): small buffers of its own } + if (o.prefill_head_alias) { + for (PfPart& p : pf_parts) { + p.first = p.cache->slots() > 1 ? 1 : -1; + p.first_now = p.first; + } + lend_first = pf_parts[0].first; + borrow = lend_first >= 0 ? xcache.device_slot(lend_first) : nullptr; + borrow_bytes = lend_first >= 0 ? part_bytes(pf_parts[0], lend_first) : 0; + size_t free_b = 0, total_b = 0; + cudaMemGetInfo(&free_b, &total_b); + static constexpr int64_t candidates[] = {2048, 1536, 1024, 512}; + for (const int64_t candidate : candidates) + if (strata::prefill::Prefill::bytes_needed(g, ss, candidate) + (512ull << 20) <= + free_b + borrow_bytes) { + o.prefill_chunk = candidate; + break; + } + std::fprintf(stderr, "strata serve: prompt chunk head alias: %lld tokens with %lld MiB borrowed and " + "%lld MiB free\n", + (long long) o.prefill_chunk, (long long) (borrow_bytes >> 20), (long long) (free_b >> 20)); + } bool any_loan = borrow != nullptr; for (size_t i = 1; i < pf_parts.size(); ++i) any_loan = any_loan || pf_parts[i].first >= 0; if (any_loan) { @@ -7369,7 +7423,8 @@ int main(int argc, char** argv) { } if (multi_gpu) sp.set_stage(0, split_at[0], &stages[0]->sp); if (share_pool) sp.set_cpu_pool(&pool); - if (!sp.init(wt, g, ss, prefill_src, &xcache, host_res.data(), o.prefill_chunk, main_cs, err, borrow, borrow_bytes)) + if (!sp.init(wt, g, ss, prefill_src, &xcache, host_res.data(), o.prefill_chunk, main_cs, err, borrow, borrow_bytes, + o.prefill_head_alias)) return err.find("do not fit") != std::string::npos ? 2 : 1; return 0; }; @@ -7700,13 +7755,14 @@ int main(int argc, char** argv) { } ver.set_remote_expert_opt(remote_opt.get()); if (batch_mtp) ver.set_batch_graph_limit(64); // --batch-mtp only: slot rotation makes many layouts (LRU); 0.1.39 keeps all - if (!ver.init(wt, g, ss, vh, native_head.loaded() ? &native_head : nullptr, + if (!ver.init(wt, g, ss, vh, native_head.loaded() || prefill_head_alias_bound ? &native_head : nullptr, batch_mtp ? strata::kernels::kVerifyMaxT : std::max(o.spec, o.batch), err) || - (use_mtp && !mtp.bind(last_st && !mtp_first ? last_st->wt : wt, last_st ? &last_st->head : &native_head, + (use_mtp && !prefill_head_alias_bound && !mtp.bind(last_st && !mtp_first ? last_st->wt : wt, last_st ? &last_st->head : &native_head, pipe ? pl_mtp_R : ver.final_R_all(), err))) { std::fprintf(stderr, "strata serve: %s\n", err.c_str()); return 1; } + if (prefill_head_alias_bound) mtp.set_window_R(ver.final_R_all()); if (pipe) mtp.set_source_R(ver.final_R_all()); // the serial decode's rows (the last stage's even verifier) auto free_slot_mtp_rows = [](float* p) { if (p != nullptr) (void) cudaFree(p); }; std::vector> slot_mtp_rows; @@ -10515,6 +10571,17 @@ int main(int argc, char** argv) { std::printf("ERR %s\n", err.c_str()); return 1; } + if (o.prefill_head_alias && native_head.loaded()) { + const auto head_t0 = Clock::now(); + native_head.unload(); + sp.reset(); + if (init_prompt_paths() != 0) { + std::printf("ERR rebuilding the head-alias prompt path failed: %s\n", err.c_str()); + return 1; + } + std::fprintf(stderr, "strata serve: --prefill-head-alias: prompt workspace rebuilt in %.1f ms\n", + std::chrono::duration(Clock::now() - head_t0).count()); + } auto kv_quiesce = [&] { cudaDeviceSynchronize(); apply_pending(true); }; if (kvg.on) { // the elastic K/V: this prompt's cells (it gives back what it does not need below) // a failed growth may leave the tier half-changed: the engine stops (as for any CUDA failure) @@ -11082,8 +11149,9 @@ int main(int argc, char** argv) { // prompt needs, so a large chunk costs a short prompt nothing const int64_t want_full = equal_chunk(tokens, o.prefill_chunk); // #340: a short enough request reads in the stages' own S-token chunks (nothing lent) - const int64_t want = split_small > 0 && tokens <= split_small_max ? std::min(want_full, split_small) - : want_full; + const int64_t want = o.prefill_head_alias ? o.prefill_chunk + : split_small > 0 && tokens <= split_small_max ? std::min(want_full, split_small) + : want_full; if (want <= 0) { e = "prefill: cannot lend buffers for an empty request segment"; return false; @@ -11099,30 +11167,34 @@ int main(int argc, char** argv) { if (!refill_one(p, e)) return false; } const strata::core::OnDevice on(p.dev); - // #2090: the loan a chunk needs is NOT monotonic in the chunk: a chunk above the scan's small_max - // lays out the byte-budget ring (199 slots at 5120), one at or below it 0.1.39's (384 at 4096), so - // a request's smaller chunk can need MORE slots than the auto chunk's region (p.first) holds. The - // loan starts where the chunk itself needs it (the 128-slot floor aside); a chunk that cannot be - // lent even then is halved until it can, instead of ending the engine. int64_t want_p = want; - int64_t need_p = part_slots(p, want_p); - while ((need_p <= 0 || need_p + 128 > p.cache->slots()) && want_p > 256) { - want_p = std::max(256, want_p / 2 / 256 * 256); - need_p = part_slots(p, want_p); + int32_t first = p.first_now; + // --prefill-head-alias: the loan laid out at start (slot 1 on) is kept; a hybrid layout cannot relayout + if (!o.prefill_head_alias) { + // #2090: the loan a chunk needs is NOT monotonic in the chunk: a chunk above the scan's small_max + // lays out the byte-budget ring (199 slots at 5120), one at or below it 0.1.39's (384 at 4096), so + // a request's smaller chunk can need MORE slots than the auto chunk's region (p.first) holds. The + // loan starts where the chunk itself needs it (the 128-slot floor aside); a chunk that cannot be + // lent even then is halved until it can, instead of ending the engine. + int64_t need_p = part_slots(p, want_p); + while ((need_p <= 0 || need_p + 128 > p.cache->slots()) && want_p > 256) { + want_p = std::max(256, want_p / 2 / 256 * 256); + need_p = part_slots(p, want_p); + } + if (need_p <= 0 || need_p + 128 > p.cache->slots()) { + e = "prefill: no chunk of this request fits the slots that can be lent (#2090)"; + return false; + } + if (want_p != want) + std::fprintf(stderr, "strata serve: prompt chunk %lld -> %lld tokens for this request: its " + "buffers do not fit the slots that can be lent (#2090)\n", (long long) want, + (long long) want_p); + if (need_p > p.cache->slots() - p.first) // the case that ended the engine before (#2090) + std::fprintf(stderr, "strata serve: the loan for a chunk of %lld tokens (%lld slots) is larger than the " + "auto chunk's (%lld slots): starting it earlier (#2090)\n", (long long) want_p, + (long long) need_p, (long long) (p.cache->slots() - p.first)); + first = (int32_t) (p.cache->slots() - need_p); } - if (need_p <= 0 || need_p + 128 > p.cache->slots()) { - e = "prefill: no chunk of this request fits the slots that can be lent (#2090)"; - return false; - } - if (want_p != want) - std::fprintf(stderr, "strata serve: prompt chunk %lld -> %lld tokens for this request: its " - "buffers do not fit the slots that can be lent (#2090)\n", (long long) want, - (long long) want_p); - if (need_p > p.cache->slots() - p.first) // the case that ended the engine before (#2090) - std::fprintf(stderr, "strata serve: the loan for a chunk of %lld tokens (%lld slots) is larger than the " - "auto chunk's (%lld slots): starting it earlier (#2090)\n", (long long) want_p, - (long long) need_p, (long long) (p.cache->slots() - p.first)); - const int32_t first = (int32_t) (p.cache->slots() - need_p); if (want_p != p.sp->chunk() || first != p.first_now) { if (!p.sp->relayout(want_p, p.cache->device_slot(first), part_bytes(p, first), e)) return false; p.first_now = first; @@ -11421,6 +11493,23 @@ int main(int argc, char** argv) { std::printf("ERR refilling a lent slot failed: %s\n", err.c_str()); return 1; } + if (o.prefill_head_alias) { + sp.reset(); + const auto head_t0 = Clock::now(); + if (!native_head.load(o.native_head_shards, g.n_embd, n_vocab, err)) { + std::printf("ERR restoring the native output head failed: %s\n", err.c_str()); + return 1; + } + // the verify windows' captured graphs read the head at the address of their capture + if (prefill_head_alias_at == nullptr) prefill_head_alias_at = native_head.weights(); + if (native_head.weights() != prefill_head_alias_at) { + std::printf("ERR --prefill-head-alias: the output head was reloaded at another address, so the " + "captured verify graphs would read freed memory\n"); + return 1; + } + std::fprintf(stderr, "strata serve: --prefill-head-alias: output head restored in %.1f ms before decode\n", + std::chrono::duration(Clock::now() - head_t0).count()); + } tr("prompt done (slots refilled)"); if (il_parts > 0) std::fprintf(stderr, "strata batch: the prompt was read in %lld parts, the slots decoding %.0f ms between " diff --git a/sycl/src/prefill/prefill.cpp b/sycl/src/prefill/prefill.cpp index bebb039f..8b0b3892 100644 --- a/sycl/src/prefill/prefill.cpp +++ b/sycl/src/prefill/prefill.cpp @@ -930,7 +930,11 @@ bool Prefill::init(const core::WeightTable &wt, const core::ModelGeometry &g, core::SessionState &ss, core::ExpertSource *src, const core::ExpertCache *cache, const int32_t *host_res, int64_t chunk, void *stream, std::string &err, void *borrow, - uint64_t borrow_bytes) try { + uint64_t borrow_bytes, bool borrow_spill) try { + if (borrow_spill) { + err = "prefill: a hybrid borrowed/owned layout (--prefill-head-alias) is not in the SYCL port"; + return false; + } Impl& m = *impl_; m.wt = &wt; m.g = &g; m.ss = &ss; m.src = src; m.cache = cache; m.host_res = host_res; m.T = chunk; m.cs = strata::q_of(stream); m.stats = &stats_; From 9d41e18bd913f81c3a7644206f7bb3fe9b4f6ecb Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 13 Oct 2026 05:25:31 +0200 Subject: [PATCH 63/67] layer split auto (CUDA): a stage's link scales its miss cost only against the fastest stage's link and from a 4x gap on (#2007) 0.1.41 (0391e478) scaled each stage's miss term by 20 GB/s / its probed link, for 2x 4090 D with CUDA1 on a physical x1 link (1.6 GB/s: x12, K 22 -> 38, prompt ~350 -> ~1400 tok/s). On 2x Tesla T10 the same rule moved auto from K=23 to K=14: CUDA1 runs 34 of 48 layers, and as the prompt path is a pipeline the slower stage sets the rate - 256K prompt 1035 -> 795 tok/s, decode 46.8 -> 39.5; --layer-split 23 on 0.1.43 restores both (xiake-1 in #2007). split_rules::link_miss_scale: the scale is the fastest stage's link over this stage's, applied only from a 4x gap (a riser or chipset x1/x4 slot beside an x16 one), capped at 64. A symmetric rig keeps the fitted formula whatever its link speed; the x1 case still gets ~x15. STRATA_SPLIT_LINK_ABS=1 restores the 0.1.41 rule. SYCL has no link term (unchanged). Test: split_rules_test (the x1 case, equal gen3 cards, a 2x gap, caps, unprobed stages). Not run on the reporter's T10s: the reply asks for the 'link ... -> miss cost' lines. --- include/strata/program/split_rules.hpp | 23 +++++++++++++++++++++++ src/program/generate.cpp | 17 +++++++++++------ tests/program/split_rules_test.cpp | 16 ++++++++++++++++ 3 files changed, 50 insertions(+), 6 deletions(-) diff --git a/include/strata/program/split_rules.hpp b/include/strata/program/split_rules.hpp index 6cff00b9..682255d9 100644 --- a/include/strata/program/split_rules.hpp +++ b/include/strata/program/split_rules.hpp @@ -74,6 +74,29 @@ inline size_t pick_with_headroom(const std::vector& c, double tol) { return pick; } +// ---- #2007: the miss cost of a stage on a narrower link. 0.1.41 scaled each stage's miss term by 20 GB/s / its probed +// link (clamped to 1..64), for 2x 4090 D with CUDA1 on a physical x1 link (1.6 GB/s: x12, auto K 22 -> 38, prompt +// ~350 -> ~1400 tok/s). The same scale moved 2x Tesla T10 from K=23 to K=14: prompt -23%, decode -15% (xiake-1). +// So the scale is now relative to the stage with the fastest link (a symmetric rig keeps the fitted formula, whatever +// its link speed) and applies only from kLinkScaleMin on (a narrow riser or a chipset x1/x4 slot against an x16 one); +// below that the probe's noise and the formula's fit are the larger effects. + +constexpr double kLinkScaleMin = 4.0; + +/// Per stage: the factor on its miss term, from the probed H2D GB/s of each stage (<= 0: not probed -> 1.0). +inline std::vector link_miss_scale(const std::vector& gbps, double min_ratio = kLinkScaleMin) { + double fastest = 0.0; + for (const double b : gbps) fastest = b > fastest ? b : fastest; + std::vector s(gbps.size(), 1.0); + if (fastest <= 0.0) return s; + for (size_t i = 0; i < gbps.size(); ++i) { + if (gbps[i] <= 0.0) continue; + const double r = fastest / gbps[i]; + s[i] = r >= min_ratio ? (r > 64.0 ? 64.0 : r) : 1.0; + } + return s; +} + /// The smallest spare room over the stages of `cuts`: room[i] - session(lb, le) - need(lb, le), where `need_prefix[l]` /// is the bytes of every expert of layers [0, l) (n_layers + 1 entries). template diff --git a/src/program/generate.cpp b/src/program/generate.cpp index b417aab3..56ac01d1 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -3761,17 +3761,22 @@ int main(int argc, char** argv) { } // The per-stage link, measured here (the stage-setup probes are skipped when --pcie-frac is given, and the // search needs the reading either way). - std::vector link_scale((size_t) ns, 1.0); + std::vector link_gbps((size_t) ns, -1.0); for (int i = 0; i < ns; ++i) { const int dev = i == 0 ? 0 : stages[(size_t) i - 1]->dev; const strata::core::OnDevice on(dev); std::string bursts; - const double bw = native_pack ? probe_pcie_h2d_gbps(&bursts) : -1.0; - // Never below 1.0: a link at or above the 20 GB/s reference keeps the fitted cost exactly (a x16 - // gen4/5 reads 26-28 and must not credit misses below the formula the sweep's K was fitted with). - if (bw > 0.0) link_scale[(size_t) i] = std::clamp(20.0 / bw, 1.0, 64.0); + link_gbps[(size_t) i] = native_pack ? probe_pcie_h2d_gbps(&bursts) : -1.0; + } + // #2007: relative to the fastest stage's link and only from a 4x gap on (split_rules::link_miss_scale): a + // symmetric rig, or a moderate gap, keeps the fitted formula. STRATA_SPLIT_LINK_ABS=1: 0.1.41's 20 GB/s rule. + static const bool link_abs = [] { const char* v = std::getenv("STRATA_SPLIT_LINK_ABS"); return v && v[0] == '1'; }(); + std::vector link_scale = strata::program::split_rules::link_miss_scale(link_gbps); + for (int i = 0; i < ns; ++i) { + const double bw = link_gbps[(size_t) i]; + if (link_abs) link_scale[(size_t) i] = bw > 0.0 ? std::clamp(20.0 / bw, 1.0, 64.0) : 1.0; std::fprintf(stderr, "strata generate: layer split auto: CUDA%d link %.1f GB/s -> miss cost x%.2f\n", - dev, bw, link_scale[(size_t) i]); + i == 0 ? 0 : stages[(size_t) i - 1]->dev, bw, link_scale[(size_t) i]); } const double miss_ms = std::getenv("STRATA_SPLIT_MISS_MS") ? std::atof(std::getenv("STRATA_SPLIT_MISS_MS")) : 190.0; // ---- THE COVERAGE CURVE: HOW MUCH ROUTED MASS A CACHE HOLDS, AND WHY IT IS NO LONGER A POWER LAW. diff --git a/tests/program/split_rules_test.cpp b/tests/program/split_rules_test.cpp index beef1255..2ac80464 100644 --- a/tests/program/split_rules_test.cpp +++ b/tests/program/split_rules_test.cpp @@ -75,6 +75,22 @@ int main() { CHECK(pick_with_headroom(same, 0.0) == 0); CHECK(pick_with_headroom({}, 0.1) == 0); } + // #2007: the miss scale per link + { + // the case 0.1.41's scale was made for: CUDA1 on a physical x1 link beside an x16 one + const std::vector x1 = link_miss_scale({24.0, 1.6}); + CHECK(x1[0] == 1.0 && x1[1] > 14.9 && x1[1] < 15.1); + // two equal cards on gen3 x16 (2x Tesla T10, P100s): the fitted formula, whatever the link speed + const std::vector eq = link_miss_scale({12.0, 12.0}); + CHECK(eq[0] == 1.0 && eq[1] == 1.0); + // a moderate gap (x8 beside x16, or the probe's noise): no scale + const std::vector mod = link_miss_scale({11.4, 5.9}); + CHECK(mod[0] == 1.0 && mod[1] == 1.0); + // a 4x gap and more scales by the ratio, capped at 64; unprobed stages stay 1 + const std::vector big = link_miss_scale({26.0, 6.0, 0.2, -1.0}); + CHECK(big[0] == 1.0 && big[1] > 4.3 && big[1] < 4.4 && big[2] == 64.0 && big[3] == 1.0); + CHECK(link_miss_scale({-1.0, -1.0})[1] == 1.0); + } if (failed == 0) std::printf("split_rules_test: ok\n"); return failed ? 1 : 0; } From d8684360b82efae7aa99568c172737a002b63b26 Mon Sep 17 00:00:00 2001 From: David Date: Mon, 12 Oct 2026 22:39:34 -0400 Subject: [PATCH 64/67] CUDA: service CPU doorbells while instrumented graph launches block --- CMakeLists.txt | 7 ++ docs/DETAILS.md | 17 +++++ include/strata/core/host_graph_launch.hpp | 64 ++++++++++++++++++ src/core/verify.cpp | 33 +++++++++ tests/core/host_graph_launch_test.cu | 82 +++++++++++++++++++++++ 5 files changed, 203 insertions(+) create mode 100644 include/strata/core/host_graph_launch.hpp create mode 100644 tests/core/host_graph_launch_test.cu diff --git a/CMakeLists.txt b/CMakeLists.txt index 49a45ee1..3b78cc26 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -483,6 +483,13 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) src/core/arch_defaults.cpp src/core/vmm.cpp src/core/conversation_file.cpp) target_include_directories(strata_engine PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include) target_link_libraries(strata_engine PUBLIC strata_core strata_kernels strata_kernels_cpu ${_strata_gpu_runtime_target}) + if(STRATA_BUILD_TESTS AND STRATA_ENABLE_CUDA AND NOT STRATA_HIP_GFX906) + add_executable(host_graph_launch_test tests/core/host_graph_launch_test.cu) + target_include_directories(host_graph_launch_test PRIVATE include) + target_link_libraries(host_graph_launch_test PRIVATE CUDA::cudart Threads::Threads) + add_test(NAME host_graph_launch_test COMMAND host_graph_launch_test) + set_tests_properties(host_graph_launch_test PROPERTIES TIMEOUT 30) + endif() if(STRATA_BUILD_TESTS AND EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tests/core/exchange_storage_test.cpp") add_executable(exchange_storage_test tests/core/exchange_storage_test.cpp) target_include_directories(exchange_storage_test PRIVATE include) diff --git a/docs/DETAILS.md b/docs/DETAILS.md index d703d9c0..12f70e17 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -2011,3 +2011,20 @@ The prompt path's half-output buffer `bo` reuses the embedding buffer `emb`, whi **Fused int8 prompt experts on gfx12 (RDNA4, R9700): on by default for IQ3_S and IQ3_XXS packs.** `STRATA_PF_FUSED=0` turns them off (back to the MMQ prompt kernels, the previous bits). R9700, 1 card: prompt 4K +15.7%, 16K +13..+17%, 32K +19..+20%, a 96K prompt +16% (answers identical text); first-token KL against the FP16 prompt path over 96 prompts is equal to MMQ within noise (IQ3_XXS 0.00613 against 0.00683, IQ3_S 0.00416 against 0.00372). Other quants and other GPUs are unchanged; `STRATA_PF_FUSED=1` still opts in every covered format. **gfx12 (Linux): a bare `--prefill auto` may take 16384-token chunks.** Explicit `--prefill N`, `auto:N` and `STRATA_PREFILL_AUTO_MAX` are untouched; `STRATA_GFX12_CHUNK=0` or `STRATA_GFX12_DEFAULTS=0` keeps 8192. + +### CUDA diagnostics: a host thread for the verify-window launch + +`STRATA_VERIFY_ASYNC_LAUNCH=1` runs `Verifier::run`'s CUDA graph launch on a separate +host thread. This lets its caller serve the CPU expert doorbells while an +instrumented `cudaGraphLaunch` blocks waiting for the graph. The caller joins the +launch and checks its real error before returning a frontier; an early service +failure releases the mapped GPU waits before joining. The switch is off by +default and applies to this single-request verifier entry point. Direct batch +and pipelined graph launches and the HIP/SYCL paths retain their existing scheduling. + +For Compute Sanitizer, set this variable before running the usual model command +under `compute-sanitizer --tool memcheck --error-exitcode 86`. Build with +`STRATA_BUILD_TESTS=ON` and run `host_graph_launch_test` for the CUDA graph/CPU +signal, early cleanup and `--errors` error-propagation checks. Its `--synchronous` +mode is the negative control under memcheck: an eight-second watchdog releases +the original launch/service deadlock and the test fails. diff --git a/include/strata/core/host_graph_launch.hpp b/include/strata/core/host_graph_launch.hpp new file mode 100644 index 00000000..2993997a --- /dev/null +++ b/include/strata/core/host_graph_launch.hpp @@ -0,0 +1,64 @@ +#pragma once + +#include +#include +#include +#include +#include + +namespace strata::core { + +// Instrumented cudaGraphLaunch may block until device work completes. A graph +// which waits for CPU doorbells must therefore launch outside its service thread. +// The caller still services exactly the same graph and observes the real launch +// error before synchronizing or publishing its output. +class HostGraphLaunch { +public: + HostGraphLaunch(cudaGraphExec_t graph, cudaStream_t stream, int device, + bool threaded, std::function release_waits) + : stream_(stream), release_waits_(std::move(release_waits)) { + if (threaded) { + pending_.store(true); + worker_ = std::thread([this, graph, device] { + auto error = cudaSetDevice(device); + if (error == cudaSuccess) error = cudaGraphLaunch(graph, stream_); + error_ = error; + pending_.store(false, std::memory_order_release); + }); + } else { + error_ = cudaGraphLaunch(graph, stream_); + } + } + HostGraphLaunch(const HostGraphLaunch&) = delete; + HostGraphLaunch& operator=(const HostGraphLaunch&) = delete; + + ~HostGraphLaunch() { + // On an early service failure, release the GPU's mapped waits before + // joining a launcher that may be blocked behind those waits. + if (worker_.joinable() && !finished_) release_waits_(); + if (worker_.joinable()) worker_.join(); + } + + bool pending() const { return pending_.load(std::memory_order_acquire); } + cudaError_t status() const { return pending() ? cudaSuccess : error_; } + cudaError_t query() const { + if (pending()) return cudaErrorNotReady; + if (error_ != cudaSuccess) return error_; + return cudaStreamQuery(stream_); + } + cudaError_t finish() { + if (worker_.joinable()) worker_.join(); + finished_ = true; + return error_; + } + +private: + cudaStream_t stream_; + std::function release_waits_; + std::atomic pending_{false}; + cudaError_t error_ = cudaSuccess; + std::thread worker_; + bool finished_ = false; +}; + +} // namespace strata::core diff --git a/src/core/verify.cpp b/src/core/verify.cpp index 0513a824..66de8cc8 100644 --- a/src/core/verify.cpp +++ b/src/core/verify.cpp @@ -2,6 +2,9 @@ #include "strata/core/batch_rows.hpp" #include "strata/kernels/gfx_arch.hpp" #include "strata/core/verify.hpp" +#if !defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906) +#include "strata/core/host_graph_launch.hpp" +#endif #include "strata/core/remote_expert_opt.hpp" #include "strata/core/dma_batch.hpp" #include "strata/core/spec_prob.hpp" @@ -2172,10 +2175,25 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, // 0.1.43: with the all-resident graph the host serves no layer, so nothing can hold a layer back: every copy first if (adapt_gate_ != nullptr && adapt_gate_->active.load(std::memory_order_acquire) && ar_on() && !adapt_gate_wait((int32_t) g.n_layers, err)) return false; +#if !defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906) + // A blocking instrumented launch cannot also serve the graph's CPU doorbells. + static const bool threaded_launch = [] { + const char* value = std::getenv("STRATA_VERIFY_ASYNC_LAUNCH"); + return value != nullptr && value[0] == '1'; + }(); + HostGraphLaunch launch(ar_off_ ? exec_nr_[T] : exec_[T], cs_, device_, threaded_launch, + [this] { (void) release_gpu_waits(5000); }); + const cudaError_t le = launch.status(); +#else const cudaError_t le = cudaGraphLaunch(ar_off_ ? exec_nr_[T] : exec_[T], cs_); +#endif trace_ev("LAUNCHED", -1, -1, (int64_t) le); if (le != cudaSuccess) { err = std::string("verify: launch: ") + cudaGetErrorString(le); return false; } +#if !defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906) + (void) launch.query(); +#else (void) cudaStreamQuery(cs_); +#endif VDBG("launched\n"); volatile uint32_t* const seq = h_seq_; volatile uint32_t* const flag = h_flag_; @@ -2209,7 +2227,11 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, const auto now = Clock::now(); if (now - last_flush > std::chrono::microseconds(2000)) { last_flush = now; +#if !defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906) + const cudaError_t q = launch.query(); +#else const cudaError_t q = cudaStreamQuery(cs_); +#endif if (q != cudaErrorNotReady && *seq < want) { trace_ev("NEVER-RANG", k, l, (int64_t) q); trace_dump(stderr); @@ -2220,7 +2242,11 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, } if (now - a > std::chrono::seconds(20)) { // #267: the caller ends the engine; no spin kernel may outlive it +#if !defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906) + trace_ev("TIMEOUT", k, l, (int64_t) launch.query()); +#else trace_ev("TIMEOUT", k, l, (int64_t) cudaStreamQuery(cs_)); +#endif if (g_trace) { diag(stderr); // the words and the breadcrumbs before the release ... const bool drained = release_gpu_waits(5000); @@ -2285,6 +2311,13 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, // spin kernel outlives the process - the case that left Windows GPUs "lost" until a power cycle. The wait // itself stays a blocking sync: a cudaStreamQuery poll here cost IQ3_S ~3% decode (a core calling the driver // beside the expert workers). +#if !defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906) + const cudaError_t launch_result = launch.finish(); + if (launch_result != cudaSuccess) { + err = std::string("verify: launch: ") + cudaGetErrorString(launch_result); + return false; + } +#endif trace_ev("SYNC", -1, -1, 0); const cudaError_t se = cudaStreamSynchronize(cs_); trace_ev("SYNCED", -1, -1, (int64_t) se); diff --git a/tests/core/host_graph_launch_test.cu b/tests/core/host_graph_launch_test.cu new file mode 100644 index 00000000..39a79e8f --- /dev/null +++ b/tests/core/host_graph_launch_test.cu @@ -0,0 +1,82 @@ +#include "strata/core/host_graph_launch.hpp" +#include +#include +#include +#include +#include +#include + +static void check(bool ok, const char* what) { + if (!ok) { std::fprintf(stderr, "FAIL: %s\n", what); std::exit(1); } +} +static void gpu(cudaError_t e) { check(e == cudaSuccess, cudaGetErrorString(e)); } +__global__ void wait_for_cpu(volatile unsigned* flag) { + while (*flag == 0) { } +} +__global__ void tick(unsigned* value) { ++*value; } + +int main(int argc, char** argv) { + const bool threaded = !(argc > 1 && std::strcmp(argv[1], "--synchronous") == 0); + cudaStream_t stream; + gpu(cudaStreamCreateWithFlags(&stream, cudaStreamNonBlocking)); + unsigned *host, *flag, *value; + gpu(cudaHostAlloc(&host, sizeof(unsigned), cudaHostAllocMapped)); + gpu(cudaHostGetDevicePointer(&flag, host, 0)); + gpu(cudaMalloc(&value, sizeof(unsigned))); + gpu(cudaMemset(value, 0, sizeof(unsigned))); + *host = 0; + cudaGraph_t graph; + cudaGraphExec_t exec; + gpu(cudaStreamBeginCapture(stream, cudaStreamCaptureModeGlobal)); + wait_for_cpu<<<1, 1, 0, stream>>>(flag); + // Enough nodes to exercise launch backpressure under Compute Sanitizer. + for (int i = 0; i < 4096; ++i) tick<<<1, 1, 0, stream>>>(value); + gpu(cudaStreamEndCapture(stream, &graph)); + gpu(cudaGraphInstantiate(&exec, graph, nullptr, nullptr, 0)); + std::atomic done{false}, timed_out{false}; + std::thread watchdog([&] { + const auto start = std::chrono::steady_clock::now(); + while (!done && std::chrono::steady_clock::now() - start < std::chrono::seconds(8)) + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + if (!done) { timed_out = true; *(volatile unsigned*)host = 1; } + }); + { + strata::core::HostGraphLaunch launch(exec, stream, 0, threaded, + [&] { *(volatile unsigned*)host = 1; }); + gpu(launch.status()); + check(launch.query() == cudaErrorNotReady, "graph waits for CPU service"); + *(volatile unsigned*)host = 1; + gpu(launch.finish()); + gpu(cudaStreamSynchronize(stream)); + } + done = true; + watchdog.join(); + check(!timed_out, "CPU service proceeds without launch deadlock"); + unsigned count = 0; + gpu(cudaMemcpy(&count, value, sizeof(unsigned), cudaMemcpyDeviceToHost)); + check(count == 4096, "all graph nodes executed"); + if (threaded) { + // An early service failure must release the graph before joining. + *host = 0; + std::atomic released{false}; + { + strata::core::HostGraphLaunch launch(exec, stream, 0, true, + [&] { released = true; *(volatile unsigned*)host = 1; }); + } + check(released, "early return releases device waits"); + gpu(cudaStreamSynchronize(stream)); + gpu(cudaMemcpy(&count, value, sizeof(unsigned), cudaMemcpyDeviceToHost)); + check(count == 8192, "early return drains the actual graph"); + if (argc > 1 && std::strcmp(argv[1], "--errors") == 0) { + strata::core::HostGraphLaunch invalid(exec, stream, -1, true, [] {}); + check(invalid.finish() == cudaErrorInvalidDevice, "launch-thread device error propagated"); + (void)cudaGetLastError(); + } + } + gpu(cudaGraphExecDestroy(exec)); + gpu(cudaGraphDestroy(graph)); + gpu(cudaFree(value)); + gpu(cudaFreeHost(host)); + gpu(cudaStreamDestroy(stream)); + std::puts("PASS: graph launch, CPU doorbell service and cleanup"); +} From a0e577de958307e723ff9d94619589cf01f82116 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 13 Oct 2026 07:16:25 +0200 Subject: [PATCH 65/67] test: a user asking for (or the other tool tags) verbatim gets the text, the outer-pair exception included (#2026) 47Hunter47 measured asked verbatim at 0/15 on 0.1.43.1 (it reached the model as the real closer). 62185aab already marks it; this pins the cases next to the exception that keeps a wholly wrapped tool result's outer pair: the bare closer, a request that quotes a whole pair, a message that only starts with the opener, two closers in one sentence. --- serve/test_frontend.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/serve/test_frontend.py b/serve/test_frontend.py index 5eb1a2e7..676f23f1 100644 --- a/serve/test_frontend.py +++ b/serve/test_frontend.py @@ -263,6 +263,20 @@ class QuotedToolCallCloser(unittest.TestCase): middle = ids[lead + 1:len(ids) - tail - 1] self.assertEqual(middle, [*inner.encode()]) # the quoted tags inside are text + def test_a_user_asking_for_a_closer_verbatim_gets_text(self): + # #2026 (47Hunter47): "" asked verbatim came back 0/15 while it reached the model as the real + # closer. The outer-pair exception must not swallow such a request: only a message wholly wrapped in the pair is + # a tool result. + for text in ("Please output the following string verbatim: .", + "", + "Repeat exactly: x", + " is how a result opens; what closes it?", + "the closer is , then "): + with self.subTest(text=text): + ids, changed = self.encode("user", text) + self.assertTrue(changed) + self.assertEqual(ids, [*text.encode()]) + def test_template_keeps_seeing_a_tool_result_turn(self): from serve.frontend import mark_think_literals msgs = [{"role": "user", "content": "q"}, {"role": "assistant", "content": "a"}, From ee6d8baccf8f12c2fe59374113929315d1d6ce92 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 13 Oct 2026 07:20:05 +0200 Subject: [PATCH 66/67] serve: say when a reusable state is rejected only because a picture's embeddings changed (#2228) A checkpoint (or the live state) is reused only when the prompt starts with its tokens AND its pictures, and a picture is its grid plus the hash of its embedding floats. In #2228 (screenshot-heavy agent, CPU image encoder) the cache fell back to checkpoints a long way back although the client's messages were byte-identical; one explanation is a picture encoded again with other bits. When the deepest state whose tokens match is rejected for a picture, the engine now logs which picture and where, once per request, so the next log tells this apart from a rewritten history. Log only; what is reused does not change. --- src/program/generate.cpp | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 56ac01d1..9737cad4 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -10656,6 +10656,40 @@ int main(int argc, char** argv) { slot_ck = &c; } } + // #2228: a checkpoint or the live state whose TOKENS this prompt starts with, deeper than what is reused, but + // whose pictures differ (a picture is its grid and the hash of its embeddings: an image encoded again with + // other bits - another encoder start, a CPU encoder that is not bit-reproducible - no longer matches). The + // reuse then falls back to a checkpoint before that picture; said once per request, so the log tells this + // apart from a client that rewrote its history. + if (o.prompt_cache > 0 && !req_imgs.empty()) { + int64_t deep = 0; + const std::vector* deep_imgs = nullptr; + auto tokens_match = [&](const std::vector& pre) { + const int64_t L = (int64_t) pre.size(); + if (L < 1 || L > n - 1) return false; + for (int64_t i = 0; i < L; ++i) + if ((int32_t) ids[(size_t) i] != pre[(size_t) i]) return false; + return true; + }; + auto consider = [&](const std::vector& pre, const std::vector& pre_imgs) { + if ((int64_t) pre.size() > std::max(deep, resume) && tokens_match(pre) && + imgs_below(req_imgs, (int64_t) pre.size()) != pre_imgs) { + deep = (int64_t) pre.size(); + deep_imgs = &pre_imgs; + } + }; + if (live_ok) consider(live, live_imgs); + for (const ConvCheckpoint& c : checks) consider(c.ids, c.imgs); + if (deep_imgs != nullptr) { + const std::vector now = imgs_below(req_imgs, deep); + size_t k = 0; + while (k < now.size() && k < deep_imgs->size() && now[k] == (*deep_imgs)[k]) ++k; + std::fprintf(stderr, "strata serve: conversation cache: the state at %lld tokens has this prompt's " + "tokens but picture %zu (at token %lld) is not the same as when it was saved " + "(its embeddings changed): it cannot be reused (#2228)\n", (long long) deep, + k + 1, (long long) (k < now.size() ? now[k].start : -1)); + } + } const auto parked = conversations.best(ids, req_imgs, want_cvec); std::optional incoming; if (parked.tokens > std::max(resume, slot_tokens)) incoming.emplace(conversations.take(parked.index)); From cf1b0edf913f7d534f8c1a32872fcd2123d480be Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 13 Oct 2026 07:33:16 +0200 Subject: [PATCH 67/67] Conversation cache: a picture is matched by its bytes' hash (from the server) and its grid, not by its embedding floats (#2228) The server already keys its encoder cache by the normalized picture bytes (sha256, the .sve file name); it now sends those keys with the request (img_keys=,..., in prompt order), and the engine's conversation cache uses key + grid for a picture when the count matches. Without the key (an older server) it hashes the embeddings as before. Old engines skip the unknown key. Measured for #2228 (one 1600x1000 screenshot-like picture, strata-vision, fresh processes and twice in one process): the CPU encoder gives the same bits on a TR PRO 3975WX at 8/15/16/32 threads and on a Xeon E5-2643 v3 (e2357d8e...), the GPU encoder on an RTX A4000 is reproducible too (92cf7818...), but CPU and GPU differ. So a picture's embeddings change when the encoder moves between CPU and GPU, or after an encoder update, and no longer on its own; with the byte key the cache's matching does not depend on that at all. CUDA/HIP and SYCL. Test: serve/test_server.py test_pictures_are_keyed_by_their_bytes_for_the_engine. --- serve/server.py | 13 +++++++++++++ serve/test_server.py | 25 +++++++++++++++++++++++++ src/program/generate.cpp | 21 ++++++++++++++++++++- sycl/src/program/generate.cpp | 20 +++++++++++++++++++- 4 files changed, 77 insertions(+), 2 deletions(-) diff --git a/serve/server.py b/serve/server.py index eec1bf36..843dc092 100644 --- a/serve/server.py +++ b/serve/server.py @@ -1039,6 +1039,11 @@ class StrataEngine: # extends: no conversation checkpoint for it (#830). It still reuses a cached prefix. Absent = as before. if sampling.get("strata_checkpoint") is False: keys += " ckpt=0" + # #2228: the pictures' keys (hex, in prompt order): the engine matches a picture by them, not by its embeddings + ik = sampling.get("strata_img_keys") + if isinstance(ik, list) and ik and all(isinstance(k, str) and k and all(c in "0123456789abcdef" for c in k) + for k in ik): + keys += " img_keys=" + ",".join(ik) # "strata_prefix" (resolved by Service.resolve_prefix to {"tokens": N}): the first N prompt tokens are a shared # prefix - the engine pins the checkpoint there. Absent or unresolved = as before. prefix = sampling.get("strata_prefix") @@ -3697,6 +3702,7 @@ class Service: if force and kwargs.get("enable_thinking", True) is False: ids = ids + self.tok.encode(force, parse_special=True) self.embeddings.path = None + self.embeddings.keys = None images = images_of(messages) if images: if self.vision is None: @@ -3772,6 +3778,10 @@ class Service: # one more for every retry of a 503. run() deletes it; drop_embeddings() if run() never starts. combined = combined_embeddings_path(self.vision.dir, sum(Path(p).stat().st_size for p, _ in encoded)) self.embeddings.path = combined # first, so a half-written one is found as well + # #2228: each picture's key is its normalized bytes' hash (the encoder's file name), so the engine's + # conversation cache matches a picture by what it is, not by its embedding floats: a picture encoded again + # (an encoder restart, the cache's eviction) with other bits still matches its checkpoints + self.embeddings.keys = [Path(p).stem[:16] for p, _ in encoded] write_temporary(combined, [p for p, _ in encoded]) if req is not None and req.get("strata_prefix") is not None: req["strata_prefix"] = self.resolve_prefix(req["strata_prefix"], messages, tools, kwargs, ids, bool(images)) @@ -3962,6 +3972,9 @@ class Service: looped, next_loop_check = False, LOOP_CHECK_EVERY # #728: reasoning that repeats whole passages raw_ids = [] # every generated id (STRATA_DEBUG: dump raw model text) emb, self.embeddings.path = getattr(self.embeddings, "path", None), None # this run's to delete now + img_keys, self.embeddings.keys = getattr(self.embeddings, "keys", None), None + if emb and img_keys: + sampling = {**(sampling or {}), "strata_img_keys": img_keys} # #2228: sent beside the embeddings file # Only a DONE line replaces engine.last, so a request that died, errored or was disconnected must not have # the PREVIOUS request's decode figures recorded as its own: each pass keeps its own DONE (a segment) if # one arrived. A reasoning-budget continuation is another native generation, not another API request, diff --git a/serve/test_server.py b/serve/test_server.py index bbb176ad..93dcb26d 100644 --- a/serve/test_server.py +++ b/serve/test_server.py @@ -324,6 +324,31 @@ class ImageMarkers(unittest.TestCase): self.assertIn("<|image_pad|> marks" if "docs" in text else "plain", tok.decode(ids)) svc.embeddings.path.unlink(missing_ok=True) + def test_pictures_are_keyed_by_their_bytes_for_the_engine(self): + """#2228: each picture's key (its normalized bytes' hash: the encoder's file name) goes to the engine as + img_keys=, in prompt order, so the conversation cache does not depend on the embedding floats.""" + import tempfile + tok = ByteTokenizer() + with tempfile.TemporaryDirectory() as d: + class Keyed(self.FakeVision): + def encode(self, source): + p = self.dir / ("0123456789abcdef0123456789abcdef.sve" if source == "a.png" else + "fedcba9876543210fedcba9876543210.sve") + p.write_bytes(b"rows") + return p, 3 + svc = Service(MockEngine(tok, "ok", max_context=CTX), tok, ChatTemplate(ROOT / "serve/chat_template.jinja"), + vision=Keyed(d)) + msgs = [{"role": "user", "content": [{"type": "image", "source": "b.png"}, {"type": "text", "text": "and"}, + {"type": "image", "source": "a.png"}]}] + svc.prepare(msgs, None, {}) + self.assertEqual(svc.embeddings.keys, ["fedcba9876543210", "0123456789abcdef"]) + svc.embeddings.path.unlink(missing_ok=True) + keys = StrataEngine.sampling_keys({"strata_img_keys": ["fedcba9876543210", "0123456789abcdef"]}) + self.assertEqual(keys, " img_keys=fedcba9876543210,0123456789abcdef") + for bad in ([], ["XYZ"], ["ab cd"], "abc", [3]): # never sent malformed: the engine falls back to the embeddings + with self.subTest(bad=bad): + self.assertNotIn("img_keys", StrataEngine.sampling_keys({"strata_img_keys": bad})) + def test_anthropic_tool_result_image(self): """Claude Code's Read of a picture returns it inside a tool_result: it reaches the encoder, in place.""" import tempfile diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 9737cad4..20e6b17a 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -10391,6 +10391,10 @@ int main(int argc, char** argv) { // the missed experts and the draft-probability floor, for this request only double req_pcie_frac = o.pcie_frac, req_spec_min_p = o.spec_min_p; int req_aux_cpus = -1; // aux_cpus=0|1: --aux-cpus for this request (-1 = the start-up value) + // #2228: img_keys=,,... (GENI): each picture's key from the server (its normalized bytes' hash), + // in prompt order. With them the conversation cache matches a picture by its key and grid, not by its + // embedding floats, so a picture encoded again with other bits still matches. Absent: the embeddings' hash. + std::vector req_img_keys; if (endp != nullptr) { // GENI takes the same keys (#75: image requests were always greedy); its // embedding file path is the first token without an = for (;;) { @@ -10419,6 +10423,18 @@ int main(int argc, char** argv) { else if (key == "pcie_frac") req_pcie_frac = std::clamp((double) fv, 0.0, 1.0); else if (key == "spec_min_p") req_spec_min_p = std::clamp((double) fv, 0.0, 1.0); else if (key == "aux_cpus") req_aux_cpus = std::atoi(tok.c_str() + eq + 1) != 0 ? 1 : 0; + else if (key == "img_keys") { + req_img_keys.clear(); + const char* q = tok.c_str() + eq + 1; + while (*q != '\0') { + char* qe = nullptr; + const unsigned long long v = std::strtoull(q, &qe, 16); + if (qe == q) { req_img_keys.clear(); break; } + req_img_keys.push_back((uint64_t) v); + q = *qe == ',' ? qe + 1 : qe; + if (*qe != ',' && *qe != '\0') { req_img_keys.clear(); break; } + } + } // unknown keys are skipped: the ids start at the first token without '=' } } @@ -10487,7 +10503,10 @@ int main(int argc, char** argv) { { // what the conversation cache compares: a picture is its grid and its embeddings const int64_t grid[3] = {im.n, im.nx, im.ny}; uint64_t h = fnv1a(grid, sizeof grid); - h = fnv1a(img_rows.data() + im.off, (size_t) im.n * (size_t) g.n_embd * sizeof(float), h); + if (req_img_keys.size() == imgs.size()) // #2228: the server's key for picture k + h = fnv1a(&req_img_keys[k - 1], sizeof(uint64_t), h); + else + h = fnv1a(img_rows.data() + im.off, (size_t) im.n * (size_t) g.n_embd * sizeof(float), h); req_imgs.push_back({i, h}); } for (int64_t j = 0; j < im.n && ve.empty(); ++j) diff --git a/sycl/src/program/generate.cpp b/sycl/src/program/generate.cpp index 933b55ca..29a07e66 100644 --- a/sycl/src/program/generate.cpp +++ b/sycl/src/program/generate.cpp @@ -9544,6 +9544,9 @@ int main(int argc, char **argv) try { int req_ckpt = 1; // tuning keys (setup's calibration measures settings without restarting the engine): the PCIe share of // the missed experts and the draft-probability floor, for this request only + // #2228: img_keys=,,... (GENI): each picture's key from the server (its normalized bytes' hash), in + // prompt order; the conversation cache matches a picture by it and its grid instead of its embedding floats + std::vector req_img_keys; double req_pcie_frac = o.pcie_frac, req_spec_min_p = o.spec_min_p; if (endp != nullptr) { // GENI takes the same keys (#75: image requests were always greedy); its // embedding file path is the first token without an = @@ -9571,6 +9574,18 @@ int main(int argc, char **argv) try { else if (key == "logprobs") req_logprobs = std::clamp(std::atoi(tok.c_str() + eq + 1), -1, 20); else if (key == "pcie_frac") req_pcie_frac = std::clamp((double) fv, 0.0, 1.0); else if (key == "spec_min_p") req_spec_min_p = std::clamp((double) fv, 0.0, 1.0); + else if (key == "img_keys") { + req_img_keys.clear(); + const char* q = tok.c_str() + eq + 1; + while (*q != '\0') { + char* qe = nullptr; + const unsigned long long v = std::strtoull(q, &qe, 16); + if (qe == q) { req_img_keys.clear(); break; } + req_img_keys.push_back((uint64_t) v); + q = *qe == ',' ? qe + 1 : qe; + if (*qe != ',' && *qe != '\0') { req_img_keys.clear(); break; } + } + } // unknown keys are skipped: the ids start at the first token without '=' } } @@ -9632,7 +9647,10 @@ int main(int argc, char **argv) try { { // what the conversation cache compares: a picture is its grid and its embeddings const int64_t grid[3] = {im.n, im.nx, im.ny}; uint64_t h = fnv1a(grid, sizeof grid); - h = fnv1a(img_rows.data() + im.off, (size_t) im.n * (size_t) g.n_embd * sizeof(float), h); + if (req_img_keys.size() == imgs.size()) // #2228: the server's key for picture k + h = fnv1a(&req_img_keys[k - 1], sizeof(uint64_t), h); + else + h = fnv1a(img_rows.data() + im.off, (size_t) im.n * (size_t) g.n_embd * sizeof(float), h); req_imgs.push_back({i, h}); } for (int64_t j = 0; j < im.n && ve.empty(); ++j)