From aea6e45c6424d1e149c6894088cbc0c2b8a2cefa Mon Sep 17 00:00:00 2001 From: sergiywith Date: Wed, 30 Sep 2026 22:25:38 +0300 Subject: [PATCH 01/48] diagnostics: STRATA_DUMP_FIRST_LOGITS writes the first generated token's logits STRATA_DUMP_FIRST_LOGITS=: the logits of the first window's first position (the token the prompt predicts), n_vocab float32, written once per run. Two engine variants run on the same prompt then give a first-token KL divergence: how far a prompt-path change moves the model's distribution, not only whether its top token changed. On a layer split the last stage's verifier writes it. --- include/strata/core/verify.hpp | 3 +++ src/core/verify.cpp | 7 +++++++ src/program/generate.cpp | 10 ++++++++++ 3 files changed, 20 insertions(+) diff --git a/include/strata/core/verify.hpp b/include/strata/core/verify.hpp index eec48133..187a296a 100644 --- a/include/strata/core/verify.hpp +++ b/include/strata/core/verify.hpp @@ -74,6 +74,9 @@ public: /// One window: `tokens[0..T)` at positions pos0.., the pool served per layer; `out[t]` = argmax after token t. /// The PLE rows are gathered here from `ss.ple_prev` and the tokens. Captures the T-token graph on first use. bool run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, void* user, int32_t* out, std::string& err); + /// Diagnostics: row `t` of the last window's head logits (n_vocab floats) to the host. Valid after run(). + bool copy_logits(int t, float* host) const; + int64_t vocab() const { return next_ ? next_->vocab() : n_vocab_; } /// The sampling the verify window's head applies (temperature / top_p / top_k / seed). Set per /// request; greedy by default. The sampling itself runs OUTSIDE the captured graph - its /// parameters would otherwise be baked forever - so this can change between requests freely. diff --git a/src/core/verify.cpp b/src/core/verify.cpp index 96bfdbee..6c7f1c0c 100644 --- a/src/core/verify.cpp +++ b/src/core/verify.cpp @@ -1303,4 +1303,11 @@ bool Verifier::commit(int n_keep, std::string& err) { return next_ == nullptr || next_->commit(n_keep, err); } +bool Verifier::copy_logits(int t, float* host) const { + if (next_ != nullptr) return next_->copy_logits(t, host); // a layer split: the head is on the last stage + if (head_logits_ == nullptr || host == nullptr || t < 0 || n_vocab_ <= 0) return false; + return cudaMemcpy(host, head_logits_ + (size_t) t * (size_t) n_vocab_, (size_t) n_vocab_ * sizeof(float), + cudaMemcpyDeviceToHost) == cudaSuccess; +} + } // namespace strata::core diff --git a/src/program/generate.cpp b/src/program/generate.cpp index caf47d6b..58236eda 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -5833,6 +5833,16 @@ int main(int argc, char** argv) { if (first_window) { first_window = false; ttft_ms = std::chrono::duration(Clock::now() - t_start).count(); + // Diagnostics: the first window runs the prompt's last token over the state the prompt path left + // (keys, values, recurrent state), so its logits carry whatever that path did. A native pack never + // runs the per-token loop --dump-logits reads; this is where prompt paths can be compared by output. + if (const char* fl = std::getenv("STRATA_DUMP_FIRST_LOGITS")) { + std::vector row((size_t) ver.vocab()); + std::FILE* f = ver.copy_logits(0, row.data()) ? std::fopen(fl, "wb") : nullptr; + if (f == nullptr || std::fwrite(row.data(), sizeof(float), row.size(), f) != row.size()) + std::fprintf(stderr, "strata generate: STRATA_DUMP_FIRST_LOGITS: cannot write %s\n", fl); + if (f) std::fclose(f); + } } // plan v0.3 P6: the adaptive tier's host work (ranking, copy submission) runs on its own thread while the // GPU commits and drafts; it touches only the residency tables, which nothing reads until the next window From a606e3a9668c5e32a93351747fa2caa9495a3a06 Mon Sep 17 00:00:00 2001 From: sergiywith Date: Wed, 30 Sep 2026 22:25:39 +0300 Subject: [PATCH 02/48] Start: name the GPU and stop at once when the build has no code for it; STRATA_EMULATE_CC for tests - generate.cpp: before the expert arena loads, the engine names the card and its compute capability and checks that the build has code for it (device_code_error: cudaFuncGetAttributes on a kernel). A binary built for other GPUs used to fail at the first kernel, after the whole arena had loaded; now it stops in ~0.3 s and says why. - include/strata/core/emulate.hpp: STRATA_EMULATE_CC=75|80|86|89 makes the host's device queries (compute capability, shared memory per block) answer as that generation, for a PTX build of it JIT-compiled on a newer card - ggml's MMQ config, the QSA kernels' choice, fused_gr's shared memory. Tests only. - STRATA_QSA_WARP=1|select|attn: the pre-sm_80 QSA kernels on any card (A/B). --- include/strata/core/device.hpp | 4 ++++ include/strata/core/emulate.hpp | 36 +++++++++++++++++++++++++++++ src/core/device.cu | 9 ++++++++ src/kernels/cuda/fused_gr.cu | 2 ++ src/kernels/cuda/qsa.cu | 2 ++ src/kernels/cuda/qsa_prompt_attn.cu | 7 +++++- src/kernels/cuda/qsa_select.cu | 7 +++++- src/prefill/ggml_cuda_host.cu | 5 ++-- src/program/generate.cpp | 17 ++++++++++++++ 9 files changed, 85 insertions(+), 4 deletions(-) create mode 100644 include/strata/core/emulate.hpp diff --git a/include/strata/core/device.hpp b/include/strata/core/device.hpp index 8fb93ad6..2c180263 100644 --- a/include/strata/core/device.hpp +++ b/include/strata/core/device.hpp @@ -43,6 +43,10 @@ const char* compiled_gpu_archs(); // this is the matching check at run time (a binary can be carried to a different machine). DeviceInfo device_info(int ordinal = 0); +/// "" when this build has device code for the current device, else CUDA's error: a build for other GPUs would +/// otherwise fail at its first kernel launch, with nothing that names the cause. +std::string device_code_error(); + class CudaError : public std::runtime_error { public: CudaError(const std::string& what, int code) : std::runtime_error(what), code_(code) {} diff --git a/include/strata/core/emulate.hpp b/include/strata/core/emulate.hpp new file mode 100644 index 00000000..6f28b97f --- /dev/null +++ b/include/strata/core/emulate.hpp @@ -0,0 +1,36 @@ +// strata/core/emulate.hpp - STRATA_EMULATE_CC: another GPU generation's code paths, run on this card (tests only). +// +// A build whose device code is PTX for an older architecture (CMAKE_CUDA_ARCHITECTURES=86-virtual) runs on a newer +// card through the driver's JIT, and every kernel then sees __CUDA_ARCH__ = 860. What the host decides from the +// device must agree with that, or it picks paths and shared-memory sizes the device code was not built for: +// STRATA_EMULATE_CC=75|80|86|89 makes each such query (compute capability, shared memory per block) answer as that +// card would. Speed under it says nothing about the real card; results do - the kernels are the real card's. +#pragma once + +#include + +namespace strata { + +/// the emulated compute capability as 10 * major + minor, or 0 (off) +inline int emulated_cc() { + static const int cc = [] { + const char* e = std::getenv("STRATA_EMULATE_CC"); + const int v = e ? std::atoi(e) : 0; + return v >= 75 && v < 120 ? v : 0; + }(); + return cc; +} +inline int cc_major_of(int real_major) { return emulated_cc() ? emulated_cc() / 10 : real_major; } +inline int cc_minor_of(int real_minor) { return emulated_cc() ? emulated_cc() % 10 : real_minor; } +/// cudaDevAttrMaxSharedMemoryPerBlockOptin as the emulated card reports it: 64 KB on Turing, 163 KB on the A100, +/// 99 KB on the other Ampere and Ada cards +inline int smem_optin_of(int real) { + switch (emulated_cc()) { + case 0: return real; + case 75: return 65536; + case 80: return 166912; + default: return real < 101376 ? real : 101376; + } +} + +} // namespace strata diff --git a/src/core/device.cu b/src/core/device.cu index 010aee0f..4d8e350e 100644 --- a/src/core/device.cu +++ b/src/core/device.cu @@ -92,6 +92,15 @@ std::string gpu_arch_problem(int ordinal) { #endif } +std::string device_code_error() { + // every .cu of the engine is compiled for the same CMAKE_CUDA_ARCHITECTURES, so this kernel stands for all + cudaFuncAttributes a{}; + const cudaError_t e = cudaFuncGetAttributes(&a, poison_kernel); + if (e == cudaSuccess) return {}; + cudaGetLastError(); + return cudaGetErrorString(e); +} + DeviceInfo device_info(int ordinal) { int count = 0; check(cudaGetDeviceCount(&count), "cudaGetDeviceCount"); diff --git a/src/kernels/cuda/fused_gr.cu b/src/kernels/cuda/fused_gr.cu index c022beca..7b346b09 100644 --- a/src/kernels/cuda/fused_gr.cu +++ b/src/kernels/cuda/fused_gr.cu @@ -1,4 +1,5 @@ // src/kernels/cuda/fused_gr.cu - see include/strata/kernels/fused_gr.hpp. +#include "strata/core/emulate.hpp" #include "strata/kernels/fused_gr.hpp" #include "strata/kernels/bf16_bits.hpp" #include "strata/kernels/verify_kernels.hpp" @@ -563,6 +564,7 @@ void fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, voi if (dev >= 0 && dev < 64 && !attr[dev]) { int optin = 0; cudaDeviceGetAttribute(&optin, cudaDevAttrMaxSharedMemoryPerBlockOptin, dev); + optin = strata::smem_optin_of(optin); // the down kernel stages n_tok*TILEV floats of dynamic shared memory - 80 KB at the full 8 tokens of the // CUDA tile. sm_75 gets the smaller tile: all eight tokens fit one 40 KiB launch there (no more slicing), // the TQ-5 prefetch holds half the registers, and the smaller blocks raise how many of the 41-block grid diff --git a/src/kernels/cuda/qsa.cu b/src/kernels/cuda/qsa.cu index d1338969..a635e81e 100644 --- a/src/kernels/cuda/qsa.cu +++ b/src/kernels/cuda/qsa.cu @@ -40,6 +40,7 @@ // Every comparison still passed at any sane tolerance, the spare key landing 0.4 f32 ulp away; only a // BIT-EXACT assertion plus a full-precision probe of the intermediate found it. That is the strongest // argument in this file for keeping both. +#include "strata/core/emulate.hpp" #include "strata/kernels/qsa.hpp" #include "strata/kernels/f16_bits.hpp" @@ -673,6 +674,7 @@ void qsa_attend_step(const float* q, const uint16_t* k_scratch, const uint16_t* int dev = 0, max_shared = 0; cudaGetDevice(&dev); cudaDeviceGetAttribute(&max_shared, cudaDevAttrMaxSharedMemoryPerBlockOptin, dev); + max_shared = strata::smem_optin_of(max_shared); if ((int) smem > max_shared) { std::fprintf(stderr, "qsa: qsa_attend: max_ids %lld needs %zu B of shared, over the %d B limit\n", (long long) max_ids, smem, max_shared); diff --git a/src/kernels/cuda/qsa_prompt_attn.cu b/src/kernels/cuda/qsa_prompt_attn.cu index e87ec02c..482713ed 100644 --- a/src/kernels/cuda/qsa_prompt_attn.cu +++ b/src/kernels/cuda/qsa_prompt_attn.cu @@ -1,4 +1,7 @@ // src/kernels/cuda/qsa_prompt_attn.cu - see include/strata/kernels/qsa_prompt_attn.hpp. +#include "strata/core/emulate.hpp" +#include +#include #include "strata/kernels/qsa_prompt_attn.hpp" #include "strata/kernels/kv_q8.hpp" #include "strata/kernels/kv_q4.hpp" @@ -703,7 +706,9 @@ bool qsa_prompt_attn_batch(const float* q, const QsaAttnPools& pools, const int3 cudaGetLastError(); return false; } - cc_major[dev] = major; + // STRATA_QSA_WARP=1|attn (an A/B arm): the pre-sm_80 kernels on any card, as RTX 20 runs them + const char* w = std::getenv("STRATA_QSA_WARP"); + cc_major[dev] = w && (!std::strcmp(w, "1") || !std::strcmp(w, "attn")) ? 7 : strata::cc_major_of(major); } if (cc_major[dev] < 7) return false; turing = cc_major[dev] < 8; diff --git a/src/kernels/cuda/qsa_select.cu b/src/kernels/cuda/qsa_select.cu index dd3ba537..a780fc87 100644 --- a/src/kernels/cuda/qsa_select.cu +++ b/src/kernels/cuda/qsa_select.cu @@ -1,4 +1,7 @@ // src/kernels/cuda/qsa_select.cu - see include/strata/kernels/qsa_select.hpp. +#include "strata/core/emulate.hpp" +#include +#include #include "strata/kernels/qsa_select.hpp" #include @@ -517,7 +520,9 @@ bool qsa_block_scores_tc(const float* pooled, const float* dead, const float* q_ cudaGetLastError(); return false; } - cc_major[dev] = major; + // STRATA_QSA_WARP=1|select (an A/B arm): the pre-sm_80 kernels on any card, as RTX 20 runs them + const char* w = std::getenv("STRATA_QSA_WARP"); + cc_major[dev] = w && (!std::strcmp(w, "1") || !std::strcmp(w, "select")) ? 7 : strata::cc_major_of(major); } if (cc_major[dev] < 8) return false; } diff --git a/src/prefill/ggml_cuda_host.cu b/src/prefill/ggml_cuda_host.cu index 12f4c8af..c8f8284b 100644 --- a/src/prefill/ggml_cuda_host.cu +++ b/src/prefill/ggml_cuda_host.cu @@ -1,5 +1,6 @@ // src/prefill/ggml_cuda_host.cu - prompt-speed plan step 2b: the host-side symbols of llama.cpp's ggml-cuda that its MMQ // and quantize code reference, for the MMQ kernels compiled into strata_mmq without the rest of ggml-cuda.cu. +#include "strata/core/emulate.hpp" #include "common.cuh" #include @@ -80,8 +81,8 @@ const ggml_cuda_device_info & ggml_cuda_info() { d.integrated = false; d.supports_cooperative_launch = false; #else - d.cc = 100 * prop.major + 10 * prop.minor; - d.smpbo = prop.sharedMemPerBlockOptin; + d.cc = 100 * strata::cc_major_of(prop.major) + 10 * strata::cc_minor_of(prop.minor); // STRATA_EMULATE_CC + d.smpbo = strata::smem_optin_of((int) prop.sharedMemPerBlockOptin); d.integrated = prop.integrated != 0; d.supports_cooperative_launch = prop.cooperativeLaunch != 0; #endif diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 58236eda..5c127d84 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -55,6 +55,8 @@ #include "strata/spec/suffix_drafter.hpp" #include "strata/kernels/cvec.hpp" #include "strata/core/progress.hpp" +#include "strata/core/device.hpp" +#include "strata/core/emulate.hpp" #ifndef NOMINMAX #define NOMINMAX // gguf_reader.hpp includes windows.h #endif @@ -2391,6 +2393,21 @@ int main(int argc, char** argv) { // CUDA error left set by the failed `cudaHostRegister` and read later by `gr_read`'s launch check. See the // note in `pinned.cu`. strata::core::FileExpertSource src; + { // the card, and whether this build has code for it (a binary built for other GPUs fails at its first kernel + // otherwise, after the whole expert arena has loaded) - before the arena starts loading + int dev = 0; + cudaDeviceProp p{}; + if (cudaGetDevice(&dev) == cudaSuccess && cudaGetDeviceProperties(&p, dev) == cudaSuccess) + std::fprintf(stderr, "strata generate: GPU %d: %s, compute capability %d.%d%s\n", dev, p.name, + strata::cc_major_of(p.major), strata::cc_minor_of(p.minor), + strata::emulated_cc() ? " (STRATA_EMULATE_CC: a test mode, the card is emulated)" : ""); + const std::string e = strata::core::device_code_error(); + if (!e.empty()) { + std::fprintf(stderr, "strata generate: this engine has no code for %s (sm_%d%d): %s - rebuild it for this " + "card (setup does: START-HERE.bat --setup)\n", p.name, p.major, p.minor, e.c_str()); + return 1; + } + } strata::core::ArenaExpertSource arena_src; strata::core::ExpertSource* srcp = nullptr; if (o.mmap_experts) { From 158e85bf439c66e5cf26a3a80c3989a6fb55d837 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Thu, 1 Oct 2026 08:11:39 +0200 Subject: [PATCH 03/48] #289 follow-up: a placeholder GPU name when the properties query fails; HIP builds compile (no device_code_error probe) - generate.cpp: the startup line names "(an unnamed GPU)" when cudaGetDevice/cudaGetDeviceProperties fail (the error is cleared), and the "no code for" message uses the same name; a HIP build prints the gfx architecture instead of a CUDA compute capability. - device.cu: device_code_error() returns "" on HIP - cudaFuncAttributes/cudaFuncGetAttributes have no mapping in hip_compat, and gpu_arch_problem() already stops a HIP run on an architecture the build lacks. - fused_gr.cu: STRATA_EMULATE_CC also answers the two compute-capability queries there (small tile, the sm_70 capacity rule), as the PR's description promises; with the variable unset nothing changes. --- src/core/device.cu | 4 ++++ src/kernels/cuda/fused_gr.cu | 5 +++-- src/program/generate.cpp | 16 +++++++++++----- 3 files changed, 18 insertions(+), 7 deletions(-) diff --git a/src/core/device.cu b/src/core/device.cu index 4d8e350e..814635a6 100644 --- a/src/core/device.cu +++ b/src/core/device.cu @@ -93,12 +93,16 @@ std::string gpu_arch_problem(int ordinal) { } std::string device_code_error() { +#if defined(STRATA_USE_HIP) + return ""; // gpu_arch_problem() checks the HIP architectures against STRATA_HIP_ARCHS, before this point +#else // every .cu of the engine is compiled for the same CMAKE_CUDA_ARCHITECTURES, so this kernel stands for all cudaFuncAttributes a{}; const cudaError_t e = cudaFuncGetAttributes(&a, poison_kernel); if (e == cudaSuccess) return {}; cudaGetLastError(); return cudaGetErrorString(e); +#endif } DeviceInfo device_info(int ordinal) { diff --git a/src/kernels/cuda/fused_gr.cu b/src/kernels/cuda/fused_gr.cu index 7b346b09..fa8a8adc 100644 --- a/src/kernels/cuda/fused_gr.cu +++ b/src/kernels/cuda/fused_gr.cu @@ -564,7 +564,7 @@ void fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, voi if (dev >= 0 && dev < 64 && !attr[dev]) { int optin = 0; cudaDeviceGetAttribute(&optin, cudaDevAttrMaxSharedMemoryPerBlockOptin, dev); - optin = strata::smem_optin_of(optin); + optin = strata::smem_optin_of(optin); // STRATA_EMULATE_CC (tests only) // the down kernel stages n_tok*TILEV floats of dynamic shared memory - 80 KB at the full 8 tokens of the // CUDA tile. sm_75 gets the smaller tile: all eight tokens fit one 40 KiB launch there (no more slicing), // the TQ-5 prefetch holds half the registers, and the smaller blocks raise how many of the 41-block grid @@ -577,7 +577,7 @@ void fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, voi int cc_maj = 0, cc_min = 0; cudaDeviceGetAttribute(&cc_maj, cudaDevAttrComputeCapabilityMajor, dev); cudaDeviceGetAttribute(&cc_min, cudaDevAttrComputeCapabilityMinor, dev); - const bool small_tile = cc_maj * 10 + cc_min == 75; + const bool small_tile = strata::cc_major_of(cc_maj) * 10 + strata::cc_minor_of(cc_min) == 75; #endif const int tv = small_tile ? 1280 : 2560; tile[dev] = tv; @@ -599,6 +599,7 @@ void fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, voi int cc = 0, per_block = 0; cudaDeviceGetAttribute(&cc, cudaDevAttrComputeCapabilityMajor, dev); cudaDeviceGetAttribute(&per_block, cudaDevAttrMaxSharedMemoryPerBlock, dev); + cc = strata::cc_major_of(cc); const int usable = (cc >= 7 && optin > 0) ? optin : per_block; #endif const int capacity = usable / (int) (tv * sizeof(float)); diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 5c127d84..ce58147e 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -2397,14 +2397,20 @@ int main(int argc, char** argv) { // otherwise, after the whole expert arena has loaded) - before the arena starts loading int dev = 0; cudaDeviceProp p{}; - if (cudaGetDevice(&dev) == cudaSuccess && cudaGetDeviceProperties(&p, dev) == cudaSuccess) - std::fprintf(stderr, "strata generate: GPU %d: %s, compute capability %d.%d%s\n", dev, p.name, - strata::cc_major_of(p.major), strata::cc_minor_of(p.minor), - strata::emulated_cc() ? " (STRATA_EMULATE_CC: a test mode, the card is emulated)" : ""); + const bool named = cudaGetDevice(&dev) == cudaSuccess && cudaGetDeviceProperties(&p, dev) == cudaSuccess; + if (!named) cudaGetLastError(); + const char* name = named && p.name[0] ? p.name : "(an unnamed GPU)"; +#if defined(STRATA_USE_HIP) + std::fprintf(stderr, "strata generate: GPU %d: %s (%s)\n", dev, name, named ? p.gcnArchName : "?"); +#else + std::fprintf(stderr, "strata generate: GPU %d: %s, compute capability %d.%d%s\n", dev, name, + strata::cc_major_of(p.major), strata::cc_minor_of(p.minor), + strata::emulated_cc() ? " (STRATA_EMULATE_CC: a test mode, the card is emulated)" : ""); +#endif const std::string e = strata::core::device_code_error(); if (!e.empty()) { std::fprintf(stderr, "strata generate: this engine has no code for %s (sm_%d%d): %s - rebuild it for this " - "card (setup does: START-HERE.bat --setup)\n", p.name, p.major, p.minor, e.c_str()); + "card (setup does: START-HERE.bat --setup)\n", name, p.major, p.minor, e.c_str()); return 1; } } From 4c2cd14f5f85bafd38b3d25f774f2797f123346a Mon Sep 17 00:00:00 2001 From: sergiywith Date: Wed, 30 Sep 2026 22:25:38 +0300 Subject: [PATCH 04/48] serve: /v1/messages/count_tokens, Anthropic thinking only when asked, STRATA_REQUEST_LINES, a relative exe Found by running Claude Code against the server (claude -p, three tool turns) and by starting a config with a relative engine path: - POST /v1/messages/count_tokens answered 404; Claude Code asks it for its context figures. It now renders and tokenizes the request exactly as /v1/messages would, without running the model. - A /v1/messages request with no "thinking" (and no effort) got the template's default, which thinks: Claude Code's helper calls (a ~60-token session title) came back with a thinking block and no text. Anthropic's thinking is opt-in, so such a request now renders with enable_thinking false. A config's reasoning_effort still applies; "thinking" set, or an effort, behave as before. - STRATA_REQUEST_LINES=1: a thread follows the engine log and re-states each request's summary line on stdout, for supervisors that only see the server's stdout (a tray, llama-swap). Off by default. - A relative "exe" in the config failed in Windows' CreateProcess (WinError 2): it is made absolute against the config's cwd, as the engine's cwd already is. Tests: count_tokens equals the input_tokens /v1/messages reports for the same request; the request line pattern parses the engine's summary. python -m unittest serve.test_server: 44 OK. --- serve/frontend.py | 5 +++++ serve/server.py | 45 +++++++++++++++++++++++++++++++++++++++++++- serve/test_server.py | 17 +++++++++++++++++ 3 files changed, 66 insertions(+), 1 deletion(-) diff --git a/serve/frontend.py b/serve/frontend.py index 48dc2dbf..edcddb79 100644 --- a/serve/frontend.py +++ b/serve/frontend.py @@ -219,6 +219,11 @@ def anthropic_to_messages(req: dict) -> tuple[list[dict], list[dict] | None, dic kwargs.update(effort_kwargs(effort)) elif isinstance(thinking, dict) and thinking.get("budget_tokens"): kwargs.update(budget_effort(thinking["budget_tokens"])) + elif thinking is None: + # Anthropic's thinking is opt-in. Claude Code's helper calls (a session title, a topic check) ask for none + # and allow a few dozen tokens, which the model otherwise spent thinking and answered with no text at all. + # A config's reasoning_effort still applies: Service.with_shared sets output_config before this runs. + kwargs["enable_thinking"] = False return _late_system_to_user(messages), tools, kwargs diff --git a/serve/server.py b/serve/server.py index af666570..3637651c 100644 --- a/serve/server.py +++ b/serve/server.py @@ -30,6 +30,7 @@ import ctypes import json import os import queue +import re import signal import subprocess import sys @@ -104,6 +105,33 @@ class GpuBusy(RuntimeError): model server) is using it, so the engine is not started into the little that is left.""" +ENGINE_REQUEST = re.compile( + r"prompt (?P\d+) tokens = (?P\d+) reused \+ \d+ read in (?P[\d.]+) ms \((?P[\d.]+) tok/s\), " + r"(?P\d+) generated in (?P[\d.]+) ms \((?P[\d.]+) tok/s\)") + + +def echo_requests(log_path: str, offset: int) -> None: + """STRATA_REQUEST_LINES=1: one stdout line per finished request, from the engine's own summary in its log. + + The engine's stderr goes to the log file (the start narrator reads it), so a supervisor that only sees this + process's output - a tray, llama-swap - has no per-request numbers. This re-states the engine's line with the + total the two times make: `request prompt P cached C output O ttft T ms total S ms prefill X tok/s decode Y tok/s`. + """ + with open(log_path, "r", encoding="utf-8", errors="replace") as f: + f.seek(offset) + while True: + line = f.readline() + if not line: + time.sleep(0.2) + continue + m = ENGINE_REQUEST.search(line) + if m: + read_ms, gen_ms = float(m["read"]), float(m["gen_ms"]) + print("[strata] request prompt %s cached %s output %s ttft %.0f ms total %.0f ms prefill %s tok/s " + "decode %s tok/s" % (m["prompt"], m["reused"], m["gen"], read_ms, read_ms + gen_ms, m["pp"], m["tg"]), + flush=True) + + def narrate_start(log_path: str, offset: int, args: list, done: threading.Event, heartbeat=20.0) -> None: """While the engine starts, say in the server window what it is doing, from its log: the start reads tens of GB into RAM and locks part of it for the GPU, and on many PCs everything is slow or frozen for a minute or more - @@ -175,6 +203,8 @@ class StrataEngine: if log: threading.Thread(target=narrate_start, args=(log, os.path.getsize(log), args, loading), daemon=True).start() + if os.environ.get("STRATA_REQUEST_LINES"): + threading.Thread(target=echo_requests, args=(log, os.path.getsize(log)), daemon=True).start() self.proc = subprocess.Popen([exe, "--serve", *args], cwd=cwd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=self.log, text=True, encoding="utf-8", bufsize=1, env=env) contain(self.proc) # ends with the server, however it ends (Windows) @@ -1633,6 +1663,8 @@ def make_handler(svc: Service): self._openai(req) elif path == "/v1/messages": self._anthropic(req) + elif path == "/v1/messages/count_tokens": + self._count_tokens(req) else: self._json(404, {"error": {"message": "not found"}}) except ValueError as e: @@ -1741,6 +1773,14 @@ def make_handler(svc: Service): err = {"error": {"type": "server_error", "message": str(e)}} # headers are sent, so no 400 now self.wfile.write(b"data: " + json.dumps(err).encode() + b"\n\ndata: [DONE]\n\n") + def _count_tokens(self, req): + """Anthropic's token count, which Claude Code asks for its context figures: the prompt this server would + read for the same request, rendered and tokenized - the model does not run.""" + req = svc.with_shared(req, "anthropic") + messages, tools, kw = anthropic_to_messages(req) + prompt = svc.template.render(messages, tools=tools, **kw) + self._json(200, {"input_tokens": len(svc.tok.encode(prompt, parse_special=True))}) + def _anthropic(self, req): req = svc.with_shared(req, "anthropic") messages, tools, kw = anthropic_to_messages(req) @@ -2005,7 +2045,10 @@ def main() -> int: print("loading the model (the first start takes a minute or two) ...", flush=True) if len(gpu_list(cfg)) > 1: print(f"[strata] layer split across GPUs {gpu_list(cfg)} ({cfg.get('layer_split') or 'auto'})", flush=True) - engine = StrataEngine(cfg["exe"], engine_args(cfg), cwd=cfg.get("cwd"), log=cfg.get("log"), env=env) + # a relative "exe" is the config's cwd's: Windows' CreateProcess resolves "engine/strata.exe" against nothing + # it is told about (WinError 2), so it is made absolute here + exe = cfg["exe"] if os.path.isabs(cfg["exe"]) else os.path.abspath(os.path.join(cfg.get("cwd") or ".", cfg["exe"])) + engine = StrataEngine(exe, engine_args(cfg), cwd=cfg.get("cwd"), log=cfg.get("log"), env=env) warn_tight_ram(engine.info.get("arena_mib")) else: engine, vision, sampling_defaults = MockEngine(tok, a.script or [ diff --git a/serve/test_server.py b/serve/test_server.py index d84ebff4..e5d31184 100644 --- a/serve/test_server.py +++ b/serve/test_server.py @@ -65,6 +65,23 @@ class MaxTokens(unittest.TestCase): u = b.get("usage", {}) return s, b, u.get("input_tokens"), u.get("output_tokens") + def test_count_tokens_is_the_prompt_messages_reads(self): + # /v1/messages/count_tokens renders and tokenizes the same prompt /v1/messages would read, without running it + msgs = [{"role": "user", "content": "how many tokens is this?"}] + s, b = self.post("/v1/messages/count_tokens", {"model": "m", "messages": msgs}) + self.assertEqual(s, 200) + s2, _, n_in, _ = self.call("anthropic", "how many tokens is this?", max_tokens=8) + self.assertEqual(s2, 200) + self.assertEqual(b["input_tokens"], n_in) + + def test_request_line_parses_the_engine_summary(self): + line = ("strata serve: prompt 1200 tokens = 1000 reused + 200 read in 50 ms (4000.0 tok/s), 30 generated in " + "300 ms (100.0 tok/s), drafts accepted 20 of 28, 2 checkpoints") + from serve.server import ENGINE_REQUEST + m = ENGINE_REQUEST.search(line) + self.assertIsNotNone(m) + self.assertEqual((m["prompt"], m["reused"], m["gen"], m["tg"]), ("1200", "1000", "30", "100.0")) + def test_unset_budget_is_the_rest_of_the_context(self): cases = {"openai": [{"max_tokens": -1}, {"max_tokens": 0}, {}, {"max_tokens": None}, {"max_completion_tokens": -1}, {"max_completion_tokens": None, "max_tokens": None}], From 7f49b76680ab67a83da10f7d23d409e6b565d4c5 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Thu, 1 Oct 2026 08:12:35 +0200 Subject: [PATCH 05/48] #278 follow-up: the request-line follower starts once per log; its time field is prompt_read, not ttft - StrataEngine.restart() runs __init__ again (after a crash, an idle unload's reload), which started one more STRATA_REQUEST_LINES follower each time and printed every request line once per restart: a follower is started once per log path (the log is opened for append, so the first follower keeps reading the same file). - The field the follower printed as "ttft" is the engine's prompt read time (the new tokens only, without the queue, the template, the first decode step): it is named prompt_read. --- serve/server.py | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/serve/server.py b/serve/server.py index 3637651c..47f4a3ca 100644 --- a/serve/server.py +++ b/serve/server.py @@ -110,12 +110,16 @@ ENGINE_REQUEST = re.compile( r"(?P\d+) generated in (?P[\d.]+) ms \((?P[\d.]+) tok/s\)") +_echoing: set[str] = set() # the logs echo_requests already follows (restart() runs StrataEngine.__init__ again) + + def echo_requests(log_path: str, offset: int) -> None: """STRATA_REQUEST_LINES=1: one stdout line per finished request, from the engine's own summary in its log. The engine's stderr goes to the log file (the start narrator reads it), so a supervisor that only sees this process's output - a tray, llama-swap - has no per-request numbers. This re-states the engine's line with the - total the two times make: `request prompt P cached C output O ttft T ms total S ms prefill X tok/s decode Y tok/s`. + total the two times make: `request prompt P cached C output O prompt_read R ms total S ms prefill X tok/s decode Y + tok/s` (prompt_read: the time the engine spent reading the prompt's new tokens, not a time to first token). """ with open(log_path, "r", encoding="utf-8", errors="replace") as f: f.seek(offset) @@ -127,9 +131,9 @@ def echo_requests(log_path: str, offset: int) -> None: m = ENGINE_REQUEST.search(line) if m: read_ms, gen_ms = float(m["read"]), float(m["gen_ms"]) - print("[strata] request prompt %s cached %s output %s ttft %.0f ms total %.0f ms prefill %s tok/s " - "decode %s tok/s" % (m["prompt"], m["reused"], m["gen"], read_ms, read_ms + gen_ms, m["pp"], m["tg"]), - flush=True) + print("[strata] request prompt %s cached %s output %s prompt_read %.0f ms total %.0f ms prefill %s " + "tok/s decode %s tok/s" % (m["prompt"], m["reused"], m["gen"], read_ms, read_ms + gen_ms, m["pp"], + m["tg"]), flush=True) def narrate_start(log_path: str, offset: int, args: list, done: threading.Event, heartbeat=20.0) -> None: @@ -203,7 +207,9 @@ class StrataEngine: if log: threading.Thread(target=narrate_start, args=(log, os.path.getsize(log), args, loading), daemon=True).start() - if os.environ.get("STRATA_REQUEST_LINES"): + # once per log: the follower keeps reading the same (appended) log across restarts and reloads + if os.environ.get("STRATA_REQUEST_LINES") and os.path.abspath(log) not in _echoing: + _echoing.add(os.path.abspath(log)) threading.Thread(target=echo_requests, args=(log, os.path.getsize(log)), daemon=True).start() self.proc = subprocess.Popen([exe, "--serve", *args], cwd=cwd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=self.log, text=True, encoding="utf-8", bufsize=1, env=env) From fcef1b0dbd50a4783b583c9593a45203d4049185 Mon Sep 17 00:00:00 2001 From: sergiywith Date: Wed, 30 Sep 2026 22:25:39 +0300 Subject: [PATCH 06/48] strata-vision: --flash-attn on|off|auto; on the CPU no CUDA context, no warm-up, a thread per core - --flash-attn on|off|auto (mtmd's flash_attn_type): flash attention keeps K and V in FP16. On the NVFP4 fork the vision tower's output was 11.2% off with it on the GPU; FP32 attention (CPU) 0.1%. - On the CPU a CUDA build keeps the GPU unseen (CUDA_VISIBLE_DEVICES=-1 before the runtime starts): it otherwise opened a context there, 0.4-0.7 GB of VRAM the expert cache loses. - On the CPU without --threads: one thread per core (mtmd's default is 4); no warm-up encode (~6 s of start). - serve/server.py: relative exe/mmproj/model paths in the vision config are the config's cwd's, as the engine's are. --- serve/server.py | 7 +++++-- tools/vision/strata_vision.cpp | 29 ++++++++++++++++++++++++++--- 2 files changed, 31 insertions(+), 5 deletions(-) diff --git a/serve/server.py b/serve/server.py index 47f4a3ca..bcb14381 100644 --- a/serve/server.py +++ b/serve/server.py @@ -2046,8 +2046,11 @@ def main() -> int: print(f"[strata] sampling defaults from the config: {pretty}", flush=True) if cfg.get("vision"): print("loading the vision encoder ...", flush=True) - vision = Vision(cfg["vision"], log=open(cfg["log"], "a", encoding="utf-8") if cfg.get("log") else None, - env=env) + # 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()} + vision = Vision(vcfg, log=open(cfg["log"], "a", encoding="utf-8") if cfg.get("log") else None, env=env) print("loading the model (the first start takes a minute or two) ...", flush=True) if len(gpu_list(cfg)) > 1: print(f"[strata] layer split across GPUs {gpu_list(cfg)} ({cfg.get('layer_split') or 'auto'})", flush=True) diff --git a/tools/vision/strata_vision.cpp b/tools/vision/strata_vision.cpp index a2a32c1e..6be3f44b 100644 --- a/tools/vision/strata_vision.cpp +++ b/tools/vision/strata_vision.cpp @@ -5,7 +5,7 @@ // rows at the image's pad tokens and gives them their 2-D M-RoPE positions (see --serve GENI in generate.cpp). // // strata-vision --mmproj --model [--gpu] [--threads N] -// [--max-tokens N] +// [--max-tokens N] [--flash-attn on|off|auto] // // Resident: prints "READY ", then per stdin line // ENC -> "OK " or "ERR " @@ -17,6 +17,7 @@ #include "mtmd.h" #include "mtmd-helper.h" +#include #include #include #include @@ -24,6 +25,7 @@ #include #include #include +#include #include namespace { @@ -50,6 +52,7 @@ int main(int argc, char** argv) { std::string mmproj, model; bool gpu = false; int threads = 0, max_tokens = 0; + llama_flash_attn_type fa = LLAMA_FLASH_ATTN_TYPE_AUTO; for (int i = 1; i < argc; ++i) { const std::string a = argv[i]; auto next = [&]() -> std::string { @@ -61,13 +64,27 @@ int main(int argc, char** argv) { else if (a == "--gpu") gpu = true; else if (a == "--threads") threads = std::atoi(next().c_str()); else if (a == "--max-tokens") max_tokens = std::atoi(next().c_str()); + else if (a == "--flash-attn") { // FA keeps K and V in FP16; off = the attention in FP32 + const std::string v = next(); + fa = v == "on" ? LLAMA_FLASH_ATTN_TYPE_ENABLED : v == "off" ? LLAMA_FLASH_ATTN_TYPE_DISABLED + : LLAMA_FLASH_ATTN_TYPE_AUTO; + } else { std::fprintf(stderr, "unknown argument %s\n", a.c_str()); return 2; } } if (mmproj.empty() || model.empty()) { std::fprintf(stderr, "usage: strata-vision --mmproj --model [--gpu] [--threads N] " - "[--max-tokens N]\n"); + "[--max-tokens N] [--flash-attn on|off|auto]\n"); return 2; } + // On the CPU the GPU stays unseen: a CUDA build otherwise opens a context there (measured: 0.4-0.7 GB of VRAM, + // 150-260 expert slots less for the engine beside it). Before anything reaches the CUDA runtime. + if (!gpu) { +#ifdef _WIN32 + _putenv_s("CUDA_VISIBLE_DEVICES", "-1"); +#else + setenv("CUDA_VISIBLE_DEVICES", "-1", 1); +#endif + } llama_log_set(quiet_log, nullptr); mtmd_helper_log_set(quiet_log, nullptr); llama_backend_init(); @@ -81,6 +98,9 @@ int main(int argc, char** argv) { cp.use_gpu = gpu; cp.print_timings = false; cp.warmup = false; + cp.flash_attn_type = fa; + // on the CPU without --threads: one per core (mtmd's own default is 4 threads) + if (threads <= 0 && !gpu) threads = std::max(1u, std::thread::hardware_concurrency() / 2); if (threads > 0) cp.n_threads = threads; if (max_tokens > 0) cp.image_max_tokens = max_tokens; mtmd_context* ctx = mtmd_init_from_file(mmproj.c_str(), text, cp); @@ -103,7 +123,10 @@ int main(int argc, char** argv) { // real picture. The server starts this process before the engine, so the engine sizes its expert cache from // what is really left; allocating ~1 GB later, on a GPU the engine has filled, made Windows page GPU memory and // the engine crawl to a standstill. (A square image well above any cap; mtmd scales it to the token limit.) - { + // On the CPU there is no VRAM to reserve, and the warm-up would only delay the engine's start by one encode + // (~6 s at 1,024 tokens). + if (!gpu) std::fprintf(stderr, "strata-vision: on the CPU, %d threads, no warm-up\n", threads); + else { const uint32_t side = 2048; std::vector rgb((size_t) side * side * 3, 128); mtmd_bitmap* bm = mtmd_bitmap_init(side, side, rgb.data()); From 79aa0bb11b9200c6574c4a773c12a9b7c5f373c3 Mon Sep 17 00:00:00 2001 From: sergiywith Date: Wed, 30 Sep 2026 22:25:39 +0300 Subject: [PATCH 07/48] setup: --draft-vocab cyrillic - the English/code subset plus the whole Cyrillic script The shipped draft subsets hold 142 of the vocabulary's 18,580 Cyrillic tokens, so an answer in Ukrainian, Russian, Bulgarian or Serbian drafted almost nothing. data/draft_vocab_cyrillic.bin is draft_vocab_en.bin plus every token whose text is Cyrillic (58,963 ids), built with the repository's own tool: python tools/draft_vocab.py --gguf --base data/draft_vocab_en.bin --add cyrillic - tools/draft_vocab.py: a "cyrillic" script (U+0400-052F, 1C80-1C8F, 2DE0-2DFF, A640-A69F). - setup.py: --draft-vocab cyrillic; docs/DETAILS.md. On the NVFP4 fork: 1.4 -> 2.1 tokens per round, 83 -> 109 tok/s in Ukrainian answers, English unchanged. --- data/draft_vocab_cyrillic.bin | Bin 0 -> 235852 bytes docs/DETAILS.md | 5 ++++- setup.py | 16 ++++++++++------ tools/draft_vocab.py | 6 ++++-- 4 files changed, 18 insertions(+), 9 deletions(-) create mode 100644 data/draft_vocab_cyrillic.bin diff --git a/data/draft_vocab_cyrillic.bin b/data/draft_vocab_cyrillic.bin new file mode 100644 index 0000000000000000000000000000000000000000..06e22cbf9c5220a1347c65c4af7df106fe570e4f GIT binary patch literal 235852 zcmWjM(-I)t5(LmYwr$(CZQHhO+qP}nwr$(?%w6YUeL_X=h_1@~-~ayizW@Xz5P=Co zP=XPh5QHQYp$S7+!V#VbL?jZCi9%GO5uF&sBo?uWLtNq!p9CZ%5s67cQj(FJ6r>~- zsYydx(vhAFWF!-r$wF4Lk)0gmBp12KLtgTcp8^!55QQm1QHoKV5|pGAr71&M%2A#Q zRHPD>sX|q%QJospq!zWQLtW}op9VCf5shg=Q<~A77PO=lt!YDB+R>g4bfgoV=|We! z(VZUjq!+#ELtpyQp8*VH5Q7=QP=+y_5sYLMqZz|k#xb4=Ok@(1nZi`2F`XIAWEQiT z!(8Sup9L&r5sO*EQkJot6|7_xt69TZ*0G)qY-AIg*}_(~v7H_4WEZ>H!(R5Wp937^ z5QjO!QI2t(6P)A}r#Zt}&T*a#T;vj$xx!Vhah)675P}kn;DjI~p$JVF z!V-?~L?9xOh)fis5{>A@ASSVhO&sD9kN6}YA&E##5|WaP>6Q1&n=e*!0uXxQH-tvz3 zeBdLW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gjq) zfJE7VtmGgkg(*WNYEp~ZG@uo&=}0HK5<)0__>=(*<~t&YWGYeo!d&LDl;2oJJnJ|> z3a7ZmZBj|&wJq)*Z;*o`1W|^HRH7OUX-f#9^x;$bGJtS~FqF?3K?L6u&2kc0%SJY_ znS-3+EO)ub6P}V`tL#D+UZ)HdsY6}r(VP~vqz&z8PhUP`Aj28KmrP_5)0j>aKk^ex zh-Eo(tY8)KY+x@*9ON`txXNu(dB`K4@q&!oWCya7gMt*IB$cQ}J?hhd4`@U?I?{=r z^kN``7|d`+FotoAXEIZn#gEJ(nssbv2Zu=J2uDfb3}?B?9sc13FL`ad`jds%$x1HX zCO3J=OMZeV!+TVx2JPv<$8@9%A%xPOForOeZ%2j30x3puN>P^gsLqEpp(+2SIl=U%AN>hq6r&kW1d)8tEN1f)bNHE95?IRy64}Bo zlGw+74se8HoaP+oxy1t>lVg{jk&8FULjlTCh3dRd1Deu|5PC71vCL!^KQV`2SxOx7 WB(jzL9N-woxy60b$+kN~!2ba1x!?T& literal 0 HcmV?d00001 diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 35008e74..8b9f75e2 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -83,7 +83,10 @@ of the vocabulary (`mtp/rt/draft_vocab.bin`). Since 0.1.27 the subset includes e token (106,299 ids), so answers in those languages are 15-38% faster (Q2_0, RTX 5070). Its head takes ~180 MiB of VRAM, which the expert cache leaves free for it (0.1.28). `START-HERE.bat --setup --draft-vocab en` keeps the English/code subset from before (40,525 ids, ~110 MiB less VRAM, English answers 1-2% faster; CJK answers get -almost no drafts). `tools/draft_vocab.py` builds and inspects subsets. +almost no drafts). `--draft-vocab cyrillic` takes the English/code subset plus the whole Cyrillic script (58,963 +ids): the shipped subsets hold 142 of the vocabulary's 18,580 Cyrillic tokens, so Ukrainian or Russian answers got +1.4 tokens a round; with it 2.1, and 83 -> 109 tokens/s (RTX 5090, the NVFP4 fork), English unchanged. +`tools/draft_vocab.py` builds and inspects subsets. **Low-RAM mode (engine 0.1.26, chosen by setup):** normally all of a model's experts are copied into RAM (23-50 GB, pinned) and the GPU holds a copy of the most-used ones. On a PC whose RAM cannot hold them beside the system (the diff --git a/setup.py b/setup.py index eac1f554..060edab4 100644 --- a/setup.py +++ b/setup.py @@ -1811,12 +1811,14 @@ def start(cfg_path: Path, port: int | None, gpu: int | list | None = None, open_ OLD_DRAFT_VOCABS = {"369151522226a5edaa5f12cfd1e2ae7db8f4fbdbd222f3dcf327dced9597fb25"} # to 0.1.26: 27 Han tokens -DRAFT_VOCABS = {"cjk": "draft_vocab.bin", "en": "draft_vocab_en.bin"} +DRAFT_VOCABS = {"cjk": "draft_vocab.bin", "en": "draft_vocab_en.bin", "cyrillic": "draft_vocab_cyrillic.bin"} def refresh_draft_vocab(rt: Path, choice: str = "cjk") -> None: - """The draft layer's token subset in the MTP folder: `cjk` (data/draft_vocab.bin, since 0.1.27, #137) or `en` - (data/draft_vocab_en.bin, the English/code subset before it: ~110 MiB less VRAM, English answers 1-2% faster). + """The draft layer's token subset in the MTP folder: `cjk` (data/draft_vocab.bin, since 0.1.27, #137), `en` + (data/draft_vocab_en.bin, the English/code subset before it: ~110 MiB less VRAM, English answers 1-2% faster) or + `cyrillic` (data/draft_vocab_cyrillic.bin: English/code and the whole Cyrillic script, for Ukrainian, Russian, + Bulgarian, Serbian... answers). Copied when missing or when a shipped subset other than the chosen one is there; a subset made by hand is kept.""" new, dst = ROOT / "data" / DRAFT_VOCABS.get(choice, "draft_vocab.bin"), rt / "draft_vocab.bin" if not new.exists() or not rt.is_dir(): @@ -1827,8 +1829,9 @@ def refresh_draft_vocab(rt: Path, choice: str = "cjk") -> None: for f in DRAFT_VOCABS.values() if (ROOT / "data" / f).exists()} if old not in shipped or old == hashlib.sha256(new.read_bytes()).hexdigest(): return - ok("draft layer: the token subset " + ("with Chinese, Japanese and Korean" if choice == "cjk" else - "for English and code (less VRAM)")) + ok("draft layer: the token subset " + {"cjk": "with Chinese, Japanese and Korean", + "cyrillic": "with the Cyrillic script"}.get(choice, + "for English and code (less VRAM)")) shutil.copyfile(new, dst) @@ -1953,7 +1956,8 @@ def main() -> int: help="tune the engine's settings for this PC (about 5-10 minutes), then start the model") ap.add_argument("--draft-vocab", choices=list(DRAFT_VOCABS), help="the draft layer's tokens: cjk = with Chinese, Japanese and Korean (default), en = English " - "and code only (~110 MiB less VRAM, English answers 1-2%% faster)") + "and code only (~110 MiB less VRAM, English answers 1-2%% faster), cyrillic = English, code " + "and the Cyrillic script (Ukrainian, Russian... answers decode ~30%% faster)") ap.add_argument("--low-ram", choices=["auto", "on", "off", "resident", "mmap"], default="auto", help="read the model's experts from one file in its folder instead of copying them all into RAM " "(for a PC with a big GPU and little RAM); auto: when the experts would not fit the RAM. In " diff --git a/tools/draft_vocab.py b/tools/draft_vocab.py index e04ea7b0..77fa6b98 100644 --- a/tools/draft_vocab.py +++ b/tools/draft_vocab.py @@ -8,7 +8,7 @@ Chinese drafted almost nothing (#137). This adds whole scripts to a subset: python tools/draft_vocab.py --gguf -00001-of-0000N.gguf --base data/draft_vocab.bin --add cjk \ --out data/draft_vocab.bin ---add takes han, kana, hangul, cjk_punct, or cjk (all four). The base ids keep their order; the added ones follow in +--add takes han, kana, hangul, cjk_punct, cjk (those four) or cyrillic. The base ids keep their order; the added ones follow in id order. --stats prints what a subset holds. """ from __future__ import annotations @@ -26,6 +26,8 @@ SCRIPTS = { "kana": [(0x3040, 0x30FF), (0x31F0, 0x31FF), (0xFF66, 0xFF9F)], "hangul": [(0x1100, 0x11FF), (0x3130, 0x318F), (0xAC00, 0xD7AF)], "cjk_punct": [(0x3000, 0x303F), (0xFF00, 0xFF65), (0xFFA0, 0xFFEF)], + # Ukrainian, Russian, Bulgarian, Serbian...: the shipped subset held 142 of the vocabulary's 18,580 Cyrillic tokens + "cyrillic": [(0x0400, 0x04FF), (0x0500, 0x052F), (0x1C80, 0x1C8F), (0x2DE0, 0x2DFF), (0xA640, 0xA69F)], } GROUPS = {"cjk": ["han", "kana", "hangul", "cjk_punct"]} @@ -52,7 +54,7 @@ def main() -> int: ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("--gguf", required=True, help="the model's (first) GGUF file: its vocabulary") ap.add_argument("--base", help="the subset to extend (int32 ids)") - ap.add_argument("--add", default="", help="comma list: han, kana, hangul, cjk_punct, cjk") + ap.add_argument("--add", default="", help="comma list: han, kana, hangul, cjk_punct, cjk, cyrillic") ap.add_argument("--out", help="where to write the new subset") ap.add_argument("--stats", action="store_true", help="print what the base (and the new) subset holds") a = ap.parse_args() From d672a5f44380689fb2574ead8225f496830a44fa Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Thu, 1 Oct 2026 08:14:00 +0200 Subject: [PATCH 08/48] #287 follow-up: setup run again without --draft-vocab keeps the model's earlier choice The full setup rewrites the model's config and refreshed the MTP folder's subset with `a.draft_vocab or "cjk"`, so running it again without the flag put the CJK subset back over a cyrillic (or en) choice, and dropped draft_vocab from the config. saved_draft_vocab() reads the choice the config holds; the flag still wins. tools/test_setup_draft_vocab.py. --- setup.py | 18 +++++++++-- tools/test_setup_draft_vocab.py | 53 +++++++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+), 3 deletions(-) create mode 100644 tools/test_setup_draft_vocab.py diff --git a/setup.py b/setup.py index 060edab4..a5cbb38b 100644 --- a/setup.py +++ b/setup.py @@ -1814,6 +1814,16 @@ OLD_DRAFT_VOCABS = {"369151522226a5edaa5f12cfd1e2ae7db8f4fbdbd222f3dcf327dced959 DRAFT_VOCABS = {"cjk": "draft_vocab.bin", "en": "draft_vocab_en.bin", "cyrillic": "draft_vocab_cyrillic.bin"} +def saved_draft_vocab(cfg_path: Path) -> str | None: + """The draft subset a model's config chose earlier (--draft-vocab), or None: a setup run again without the flag + rewrites the config, and would otherwise put the default subset back.""" + try: + v = json.loads(cfg_path.read_text(encoding="utf-8-sig")).get("draft_vocab") + except (OSError, ValueError, AttributeError): + return None + return v if v in DRAFT_VOCABS else None + + def refresh_draft_vocab(rt: Path, choice: str = "cjk") -> None: """The draft layer's token subset in the MTP folder: `cjk` (data/draft_vocab.bin, since 0.1.27, #137), `en` (data/draft_vocab_en.bin, the English/code subset before it: ~110 MiB less VRAM, English answers 1-2% faster) or @@ -2393,7 +2403,9 @@ def main() -> int: "--out", str(mtp / "mtp-q2_0.gguf")], env=env) run([sys.executable, str(ROOT / "tools" / "mtp_rt.py"), "--gguf", str(mtp / "mtp-q2_0.gguf"), "--out", str(rt)], env=env) - refresh_draft_vocab(rt, a.draft_vocab or "cjk") + # a setup run again without --draft-vocab keeps the subset this model's config chose before (cyrillic, en) + draft_vocab = a.draft_vocab or saved_draft_vocab(ROOT / f"strata-{tag.lower()}.json") + refresh_draft_vocab(rt, draft_vocab or "cjk") ok(f"MTP draft layer: {rt}") # ---- 7. the start script @@ -2463,8 +2475,8 @@ def main() -> int: cfg["host"] = a.host if a.api_key: cfg["api_key"] = a.api_key - if a.draft_vocab: - cfg["draft_vocab"] = a.draft_vocab + if draft_vocab: + cfg["draft_vocab"] = draft_vocab if vision != "none": cfg["vision"] = {"exe": str(eng / VEXE), "mmproj": str(mmproj), "model": str(shards[0]), "gpu": vision == "gpu", "max_tokens": VISION[vision]["max_tokens"]} diff --git a/tools/test_setup_draft_vocab.py b/tools/test_setup_draft_vocab.py new file mode 100644 index 00000000..f0b75692 --- /dev/null +++ b/tools/test_setup_draft_vocab.py @@ -0,0 +1,53 @@ +"""Tests for setup.py's draft-vocabulary choice (#287): a setup run again without --draft-vocab keeps the subset the +model's config chose before (cyrillic, en), and refresh_draft_vocab copies the chosen shipped subset. Pure file work +in a temporary folder - no GPU, no downloads, no prompts. + + python -m unittest tools.test_setup_draft_vocab +""" +from __future__ import annotations + +import hashlib +import json +import sys +import tempfile +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) +import setup # noqa: E402 + + +class SavedChoice(unittest.TestCase): + def test_a_config_keeps_its_choice(self): + with tempfile.TemporaryDirectory() as d: + for choice in setup.DRAFT_VOCABS: + p = Path(d) / "strata-x.json" + p.write_text(json.dumps({"args": [], "draft_vocab": choice}), encoding="utf-8") + self.assertEqual(setup.saved_draft_vocab(p), choice) + + def test_no_choice_without_a_valid_config(self): + with tempfile.TemporaryDirectory() as d: + self.assertIsNone(setup.saved_draft_vocab(Path(d) / "missing.json")) + for text in ("{}", "[1]", "not json", json.dumps({"draft_vocab": "klingon"})): + p = Path(d) / "strata-y.json" + p.write_text(text, encoding="utf-8") + self.assertIsNone(setup.saved_draft_vocab(p), text) + + +class Refresh(unittest.TestCase): + def test_cyrillic_replaces_a_shipped_subset_and_stays(self): + if not (ROOT / "data" / setup.DRAFT_VOCABS["cyrillic"]).exists(): + self.skipTest("data/draft_vocab_cyrillic.bin is not in this checkout") + want = hashlib.sha256((ROOT / "data" / setup.DRAFT_VOCABS["cyrillic"]).read_bytes()).hexdigest() + with tempfile.TemporaryDirectory() as d: + rt = Path(d) + (rt / "draft_vocab.bin").write_bytes((ROOT / "data" / setup.DRAFT_VOCABS["cjk"]).read_bytes()) + setup.refresh_draft_vocab(rt, "cyrillic") + self.assertEqual(hashlib.sha256((rt / "draft_vocab.bin").read_bytes()).hexdigest(), want) + setup.refresh_draft_vocab(rt, "cyrillic") # again: nothing changes + self.assertEqual(hashlib.sha256((rt / "draft_vocab.bin").read_bytes()).hexdigest(), want) + + +if __name__ == "__main__": + unittest.main() From 7f2c76e18db5ff81ab8cb3b422b4bbef172cd531 Mon Sep 17 00:00:00 2001 From: sergiywith Date: Wed, 30 Sep 2026 22:25:38 +0300 Subject: [PATCH 09/48] iq_pack: keep experts.bin only when its blobs match the GGUF An existing experts.bin was kept whenever its size matched the layout. A different checkpoint with the same geometry (a re-quantization or a fine-tune packed into the same folder) has the same size, so the engine silently served the old experts with the new model's dense weights. Before keeping the file, the first and last blobs of the first, middle and last layers are now compared with the GGUF; a mismatch rewrites it. The check reads six blobs, so an unchanged pack is still reused at once. Test: test_experts_bin_is_kept_only_with_this_ggufs_blobs packs two GGUFs of the same geometry into one folder (it fails on the previous code). Rebased onto 0.1.31 (Niko1221): 0.1.31 already refuses an experts.bin whose sidecar (experts.bin.src.json: shard names and sizes, the hash of native_experts.txt) does not match, so the six-blob comparison runs only when the sidecar says "reuse" - it catches the case the sidecar cannot (a re-quantized or fine-tuned checkpoint under the same file names and sizes). It reads each of the six expert blobs on its own instead of concatenating the whole layer. The test packs the second model under the first one's file name, so it reaches the new check. --- tools/iq_pack.py | 24 ++++++++++++++++++++---- tools/test_iq_pack.py | 40 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+), 4 deletions(-) diff --git a/tools/iq_pack.py b/tools/iq_pack.py index 43994075..86766755 100644 --- a/tools/iq_pack.py +++ b/tools/iq_pack.py @@ -526,6 +526,25 @@ def main() -> int: sidecar = out / "experts.bin.src.json" want = experts_source(model, text, offset) reuse = path.exists() and path.stat().st_size == offset and read_json(sidecar) == want + + def layer_blobs(blob, ts): + chunk = np.concatenate([model.bytes(t.name).reshape(n_expert, -1) for t in ts], axis=1) + assert chunk.shape == (n_expert, blob) # (n_expert, blob): gate | up | down per expert + return chunk + + if reuse: + # the sidecar names the shards by name and size, which a re-quantized or fine-tuned checkpoint of the same + # geometry packed into the same folder can share: compare the first and last blobs of the first, middle and + # last layers with the GGUF too (six blobs, so an unchanged pack is still reused at once) + with open(path, "rb") as f: + for l, gt, dt, off, blob, ts in (layout[0], layout[len(layout) // 2], layout[-1]): + for e in (0, n_expert - 1): + f.seek(off + e * blob) + want_blob = b"".join(model.bytes(t.name).reshape(n_expert, -1)[e].tobytes() for t in ts) + if f.read(blob) != want_blob: + reuse = False + if not reuse: + print("%s matches %s but not this GGUF's expert blobs" % (path, sidecar.name)) if path.exists() and not reuse and not a.experts_bin: if sidecar.exists(): print("%s was cut from another source than this model (%s): the engine would read it instead of " @@ -567,10 +586,7 @@ def main() -> int: part = out / "experts.bin.tmp" with open(part, "wb") as fo: for l, gt, dt, off, blob, ts in layout: - parts = [model.bytes(t.name).reshape(n_expert, -1) for t in ts] - chunk = np.concatenate(parts, axis=1) # (n_expert, blob): gate | up | down per expert - assert chunk.shape == (n_expert, blob) - fo.write(chunk.tobytes()) + fo.write(layer_blobs(blob, ts).tobytes()) if l % 8 == 0: print(" layer %2d %-8s/%-7s blob %8d at %.2f GiB" % (l, ts[0].type_name, ts[2].type_name, blob, off / 2**30), flush=True) diff --git a/tools/test_iq_pack.py b/tools/test_iq_pack.py index 72339813..1c83db47 100644 --- a/tools/test_iq_pack.py +++ b/tools/test_iq_pack.py @@ -126,6 +126,46 @@ class CompatibilityTests(unittest.TestCase): "per_layer_token_embd.weight", "blk.0.attn_qkv.weight"]: self.assertFalse(iq_pack.needs_bf16(name, "IQ3_XXS")) + def test_experts_bin_is_kept_only_with_this_ggufs_blobs(self): + with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: + root = Path(tmp) + out = root / "pack" + (out / "tokenizer").mkdir(parents=True) + for name in ["vocab.json", "chat_template.jinja"]: + (out / "tokenizer" / name).touch() + + def model(name, scale): + path = root / name + write_gguf(path, [("blk.%d.hc_attn_down.weight" % l, np.ones((2, 32), np.float32), Q.BF16) + for l in range(3)] + + [("blk.%d.ffn_gate_inp.weight" % l, np.ones((4, 32), np.float32), Q.BF16) + for l in range(3)] + + [("blk.%d.ffn_%s_exps.weight" % (l, r), + scale * np.arange(4 * 2 * 32, dtype=np.float32).reshape(4, 2, 32) / 256, Q.Q8_0) + for l in range(3) for r in ("gate", "up", "down")]) + return path + + def pack(path): + log = io.StringIO() + argv = ["iq_pack.py", "--gguf", str(path), "--out", str(out), "--experts-bin"] + with patch.object(sys, "argv", argv), contextlib.redirect_stdout(log): + self.assertEqual(iq_pack.main(), 0) + return log.getvalue() + + first = model("a.gguf", 1) + pack(first) + written = (out / "experts.bin").read_bytes() + self.assertIn("not rewritten", pack(first)) + self.assertEqual((out / "experts.bin").read_bytes(), written) + # the same geometry with other weights under the same file name: the size and the sidecar (shard names + # and sizes, native_experts.txt) match, the contents do not + second = model("a.gguf", -1) + self.assertIn("not this GGUF's expert blobs", pack(second)) + rewritten = (out / "experts.bin").read_bytes() + self.assertEqual(len(rewritten), len(written)) + self.assertNotEqual(rewritten, written) + self.assertIn("not rewritten", pack(second)) + def test_snapshot_symlinks_keep_split_discovery(self): with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: root = Path(tmp) From 4e1a7c5982b484312870a84e3da4fd00697cd9c4 Mon Sep 17 00:00:00 2001 From: Zac Chen Date: Wed, 30 Sep 2026 19:36:42 +0800 Subject: [PATCH 10/48] verify: profile columns stop wrapping (unsigned stamp deltas) and the hc-read second half stops overwriting the next layer's base stamp kProfPer 32 -> 33: fused_gr_read_multi writes three stamps per half and the second half's base was 30, so its up-stamp landed at slot 32 = (l+1)*32 + 0, the next layer's stage-0 base. Derived columns (gap/head/hc0) also wrapped to ~1.8e19 ns whenever a slot was unstamped, printing ~1e14 ms per window. A delta now counts only when both stamps are nonzero and monotonic; the hc0 split replaces the single hc-read0 column only when the split chain is complete. Metrics-only: no computed model value changes. Reason recorded in PORTING.md 19. --- include/strata/core/verify.hpp | 3 ++- src/core/verify.cpp | 24 +++++++++++++++++------- 2 files changed, 19 insertions(+), 8 deletions(-) diff --git a/include/strata/core/verify.hpp b/include/strata/core/verify.hpp index 187a296a..f478191a 100644 --- a/include/strata/core/verify.hpp +++ b/include/strata/core/verify.hpp @@ -176,7 +176,8 @@ private: bool ple_stage() const { return lb_ <= 1 && 1 < le_; } ///< holds layer 1, where the PLE block runs bool capture_commit(std::string& err); bool record_window(int T, cudaStream_t cs, std::string& err); - static constexpr int kProfPer = 32; // stamps per layer + static constexpr int kProfPer = 33; // stamps per layer (32 left the hc-read second + // half's up-stamp at slot 32 = the next layer's slot 0: D8) bool prof_on_ = false; unsigned long long* prof_ = nullptr; // device: n_layers * kProfPer + 4 stamps std::vector prof_h_; diff --git a/src/core/verify.cpp b/src/core/verify.cpp index 6c7f1c0c..179a7752 100644 --- a/src/core/verify.cpp +++ b/src/core/verify.cpp @@ -857,7 +857,7 @@ std::string Verifier::profile_report() { "k/v+norm-rope", "kv+idx append", "q+q-idx", "scores+topk", "kv-resolve", "attention", "gate", "", "out-proj", "hc-read1+router", "shared+quant", "waitA", "VRAM hits", "waitB", "PCIe grp", "waitCPU", "copy+combine", - "(gap)", "head", " hc0 norm", " hc0 down", " hc0 up", "", ""}; + "(gap)", "head", " hc0 norm", " hc0 down", " hc0 up", "", "", ""}; std::string out; char b[80]; double total = 0; @@ -1126,6 +1126,13 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, cudaMemcpy(prof_h_.data(), prof_, prof_h_.size() * 8, cudaMemcpyDeviceToHost); const int64_t L = g.n_layers; auto at = [&](int64_t l, int i) { return prof_h_[(size_t) (l * kProfPer + i)]; }; + // D8: the derived columns below read stamps the hc-read kernels write themselves or the next + // layer's first. A slot no kernel stamped is 0 and its unsigned difference wrapped to ~1e19 ns - + // which is why (gap)/head/hc0 printed ~1e14 ms per window. A missing or out-of-order stamp now + // contributes nothing. + const auto gap = [](unsigned long long to, unsigned long long from) { + return (from != 0 && to != 0 && to >= from) ? (double) (to - from) : 0.0; + }; for (int64_t l = 0; l < L; ++l) { const int kind = is_qsa_layer(g, l) ? 1 : 0; unsigned long long prev = at(l, 0); @@ -1135,13 +1142,16 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, prof_sum_[kind][i] += (double) (x - prev); prev = x; } - if (l + 1 < L) prof_sum_[kind][25] += (double) (at(l + 1, 0) - at(l, 24)); - prof_sum_[kind][27] += (double) (at(l, 27) - at(l, 0)); // hc-read0: norm - prof_sum_[kind][28] += (double) (at(l, 28) - at(l, 27)); // down - prof_sum_[kind][29] += (double) (at(l, 1) - at(l, 28)); // up - prof_sum_[kind][1] -= (double) (at(l, 1) - at(l, 0)); // (hc-read0 shown split) + if (l + 1 < L) prof_sum_[kind][25] += gap(at(l + 1, 0), at(l, 24)); + const double dn = gap(at(l, 27), at(l, 0)), dd = gap(at(l, 28), at(l, 27)), du = gap(at(l, 1), at(l, 28)); + if (dn > 0 && dd > 0 && du > 0) { // the split exists: show it split, not twice + prof_sum_[kind][27] += dn; // hc-read0: norm + prof_sum_[kind][28] += dd; // down + prof_sum_[kind][29] += du; // up (through both halves, as before) + prof_sum_[kind][1] -= gap(at(l, 1), at(l, 0)); // (hc-read0 shown split) + } } - prof_sum_[0][26] += (double) (at(L, 1) - at(L, 0)); + prof_sum_[0][26] += gap(at(L, 1), at(L, 0)); ++prof_windows_; } // ---- a sampled or penalized request: the head's sampling again, host-side so its parameters are this call's From 43cd140ecdd0af5f10b2b7d99fc6bf19e8189b4a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hoz=C3=A1k=20Martin?= Date: Thu, 1 Oct 2026 06:14:10 +0200 Subject: [PATCH 11/48] bench: BF16 GEMV via Turing tensor cores on sm_75 - measured negative Isolated benchmark (no inference-path changes) comparing the production bf16_gemv warp kernel against an mma.sync.m16n8k8 tensor-core variant with BF16->FP16 conversion, on the real decode GEMV shapes (n_in = 2560). Three TC variants (W preconverted / inline conversion / fused output) and a full k-split occupancy sweep; parity against an fp64 reference. Result: the TC variant is 1.3-2.2x slower on every real shape even at its best config - the warp kernel is already bandwidth-bound (374 GB/s) and a single-token GEMV wastes 15/16 of the m16 MMA tile. Keeping the warp kernel; the benchmark is checked in so this does not have to be measured twice. --- .../results/2026-09-30-tc-gemv-sm75/README.md | 57 ++++ .../2026-09-30-tc-gemv-sm75/bench_tc_gemv.cu | 305 ++++++++++++++++++ 2 files changed, 362 insertions(+) create mode 100644 bench/results/2026-09-30-tc-gemv-sm75/README.md create mode 100644 bench/results/2026-09-30-tc-gemv-sm75/bench_tc_gemv.cu diff --git a/bench/results/2026-09-30-tc-gemv-sm75/README.md b/bench/results/2026-09-30-tc-gemv-sm75/README.md new file mode 100644 index 00000000..8eaf9026 --- /dev/null +++ b/bench/results/2026-09-30-tc-gemv-sm75/README.md @@ -0,0 +1,57 @@ +# BF16 GEMV on Turing tensor cores (sm_75): measured negative + +i7-8700K + RTX 2070 8 GB (sm_75, 36 SMs), engine 0.1.27 tree (`bf16_gemv.cu` is unchanged through 0.1.30), +qwen3.8-flash-next (~125.7B MoE, GGUF-verified) Q2_0 in production. Isolated benchmark only - +[`bench_tc_gemv.cu`](bench_tc_gemv.cu) touches nothing in the inference path. Question: the QSA prompt attention +already rides the Turing tensor cores (`mma.sync.m16n8k8`, the #270 path); can the decode GEMVs do the same? + +## Setup + +- Baseline: the production `bf16_gemv` warp kernel, transcribed verbatim +- TC variant: `mma.sync.aligned.m16n8k8.row.col.f32.f16.f16.f32` on BF16->FP16 (the sm_75 MMA has native f16 only). + BF16->FP16 conversion is exact (0 / 2,000,000 values inexact - bf16's 7-bit mantissa fits in fp16's 10 bits); the + A-fragment packing is the same one #270 validated (`a0` = row `gid`, k columns `2t..2t+1`; broadcast makes + `a0 == a1 == {x[2t], x[2t+1]}`) +- Three TC variants to cover the conversion overhead from every angle: W preconverted to fp16 once at load + (`pc`), W converted in-register every call (`in`), and a fused ks=1 form that writes the output directly and skips + the reduce kernel (`fused`) +- The k-split across blocks (`ks`) is swept over all values that divide n_in, and the best is reported - the TC + kernel gets its best occupancy +- Parity against an fp64 host reference; 2000 iterations x 3 reps, warmed CUDA events + +## Results (best TC config per shape) + +| Shape (decode, n_in = 2560, BF16 W) | Baseline us | Best TC us | Speedup | Config | +| --- | ---: | ---: | ---: | --- | +| ssm_alpha/beta [2560, 48] | 8.73 | 11.32 | 0.77x | pc, ks=16 | +| indexer.k_proj [2560, 128] | 7.14 | 12.09 | 0.59x | pc, ks=16 | +| indexer.q_proj / router [2560, 512] | 9.48 | 15.78 | 0.60x | pc, ks=4 | +| ple_value [2560, 2560] | 35.08 | 77.73 | 0.45x | pc, ks=40 | + +- Numerics pass: TC max error vs fp64 reference 1.7e-6 .. 7.2e-6 (fp16-accumulation level), baseline + 0.7e-6 .. 2.3e-6. The TC variant computes the same thing, it is just slower. +- The warp kernel is already bandwidth-bound at 276-374 GB/s effective W bandwidth (374 GB/s on the 13 MB + [2560, 2560] shape); the TC path reaches only 166-169 GB/s (4-byte lane loads, conversion instructions, in-tile + launch overhead). +- A single-token GEMV broadcasts one token across the whole m16 MMA tile, so 15/16 of the MMA throughput is thrown + away - but the baseline is not compute-bound, so the wasted throughput buys nothing. The k-split sweep and the + fused variant do not recover it. +- One-time W conversion cost is negligible (2 ms for 13 MB), so preconverting W for the TC path does not help. + +## How to rerun + +``` +nvcc -arch=sm_75 -O3 -o bench_tc_gemv.exe bench_tc_gemv.cu +./bench_tc_gemv.exe +``` + +Prints the table above, per-shape latency/parity and the conversion exactness scan. On a newer card, adjust +`-arch`; the packed-A layout comment in the source documents the fragment mapping it relies on. + +## Conclusion + +**Keep the warp kernel. Tensor cores are not a promising direction for the decode GEMVs on sm_75**, and this was a +measured loss (1.3-2.2x slower), not a failed attempt to optimize. The Turing MMA stays worthwhile where the input +really has m16 rows of work: the QSA prompt-attention tiles, which is where #270 uses it. Someone looking to +re-evaluate on future hardware (a card with native bf16 or denser GEMV batching) can rerun this instead of +rebuilding it. \ No newline at end of file diff --git a/bench/results/2026-09-30-tc-gemv-sm75/bench_tc_gemv.cu b/bench/results/2026-09-30-tc-gemv-sm75/bench_tc_gemv.cu new file mode 100644 index 00000000..bead5e33 --- /dev/null +++ b/bench/results/2026-09-30-tc-gemv-sm75/bench_tc_gemv.cu @@ -0,0 +1,305 @@ +// bench_tc_gemv.cu - ISOLATED benchmark: BF16 GEMV baseline vs Tensor Core (mma.m16n8k8, BF16->FP16) on sm_75. +// Nothing in the engine changes. Shapes are the REAL Strata decode GEMVs (BF16 weights, n_in = n_embd = 2560): +// ssm_alpha / ssm_beta [2560, 48] project_bf16(split=true) -> bf16_gemv_split(TPR=32) -> warp kernel +// indexer.k_proj [2560, 128] project_bf16(split=false) -> bf16_gemv -> warp kernel +// indexer.q_proj / ffn_gate_inp / mlp.gate [2560, 512] warp / split(TPR=32) -> warp kernel +// ple_value [2560, 2560] warp +// Baseline = bf16_gemv_warp_kernel transcribed verbatim from src/kernels/cuda/bf16_gemv.cu (production). +// TC variant = same maths; A = x broadcast down m16 (single-token GEMV), k-chunk = 8; +// (a) W preconverted bf16->fp16 once, x converted in-kernel (timed) [tc_preconv] +// (b) fully inline: W read as bf16 and converted in-register [tc_inline] +// Numerics: fp64 host reference; max abs err for baseline and both TC variants; bf16->fp16 exactness scan. +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define CHECK(e) do { cudaError_t err_ = (e); if (err_ != cudaSuccess) { \ + fprintf(stderr, "CUDA %s:%d %s\n", __FILE__, __LINE__, cudaGetErrorString(err_)); exit(1); } } while (0) + +__device__ __forceinline__ float bf16_f32(uint16_t v) { return __int_as_float((int) ((unsigned) v << 16)); } +static float bf16_f32_host(uint16_t v) { unsigned u = (unsigned) v << 16; float f; memcpy(&f, &u, 4); return f; } +static uint16_t f32_bf16_host(float f) { + unsigned u, r; memcpy(&u, &f, 4); + r = ((u >> 16) ^ (u >> 15)) & 1; u += 0x7fff + r; + return (uint16_t) (u >> 16); +} + +// ============ baseline: production warp kernel (verbatim semantics from bf16_gemv.cu) ============ +__global__ void gemv_warp(const uint16_t* __restrict__ x, const uint16_t* __restrict__ w, + float* __restrict__ y, long long n_in, long long n_out) { + const long long o = (long long) blockIdx.x * (blockDim.x >> 5) + (threadIdx.x >> 5); + if (o >= n_out) return; + const int lane = threadIdx.x & 31; + const uint16_t* row = w + o * n_in; + float acc = 0.0f; + for (long long i = lane; i < n_in; i += 32) + acc += bf16_f32(x[i]) * bf16_f32(row[i]); + for (int off = 16; off > 0; off >>= 1) acc += __shfl_down_sync(0xFFFFFFFFu, acc, off); + if (lane == 0) y[o] = acc; +} + +// ============ TC: A(x) broadcast, k-split over blocks, partial D row 0 -> scratch ============ +// A fragment (m16n8k8, .f16): lane l: a0 = A[m=l>>2][k=2(l&3)], a1 = A[m][k=2(l&3)+1], +// a2/a3 = same cols at row m+8. Broadcast => a2=a0, a3=a1. +// B fragment (.f16, col-major): lane l: b0 = B[k=2(l&3)][n=(l>>2)], b1 = B[k=2(l&3)+1][n]. +// B[k][n] = W[n][k], so lane l loads W[n][2(l&3)], W[n][2(l&3)+1] - coalesced within the row. +// D fragment: c0/c1 = D[m=l>>2][cols 2(l&3), +1], c2/c3 = row m+8. All m rows identical -> row 0. +__global__ void tc_preconv(const uint16_t* __restrict__ x_b, const uint16_t* __restrict__ w_f, + float* __restrict__ partials, long long n_in, long long n_out, int ks) { + const int tile = blockIdx.x, ks_i = blockIdx.y, lane = threadIdx.x & 31; + const long long n_base = (long long) tile * 8; + const long long k_per = n_in / (long long) ks; + const long long k0 = (long long) ks_i * k_per; + const int t2 = 2 * (lane & 3); + float c0 = 0.f, c1 = 0.f, c2 = 0.f, c3 = 0.f; + for (long long kk0 = k0; kk0 < k0 + k_per; kk0 += 8) { + // A (2 x f16x2): a0 = {A[m][2t], A[m+8][2t]}, a1 = {A[m][2t+1], A[m+8][2t+1]} (broadcast -> dup halves) + unsigned xh = (unsigned) x_b[kk0 + t2] | ((unsigned) x_b[kk0 + t2 + 1] << 16); + // fp16 conversion in-register: bf16 -> f32 -> f16 (exact within fp16 range) + __half2 ha = __floats2half2_rn(bf16_f32((uint16_t) (xh & 0xFFFF)), bf16_f32((uint16_t) (xh >> 16))); + __half2 hb = __floats2half2_rn(bf16_f32((uint16_t) (xh & 0xFFFF)), bf16_f32((uint16_t) (xh >> 16))); + unsigned a0 = *reinterpret_cast(&ha); + unsigned a1 = *reinterpret_cast(&hb); + // B is already fp16 here: load as __half2 directly (bf16 path must NOT convert twice) + __half2 wbh = *reinterpret_cast(&w_f[(n_base + (lane >> 2)) * n_in + kk0 + t2]); + unsigned b0 = *reinterpret_cast(&wbh); + asm volatile("mma.sync.aligned.m16n8k8.row.col.f32.f16.f16.f32 {%0,%1,%2,%3}, {%4,%5}, {%6}, {%0,%1,%2,%3};\n" + : "+f"(c0), "+f"(c1), "+f"(c2), "+f"(c3) + : "r"(a0), "r"(a1), "r"(b0)); + } + if (lane < 4) { float* p = partials + (size_t) (tile * ks + ks_i) * 8; p[t2] = c0; p[t2 + 1] = c1; } +} + +// same, but W stays bf16 and converts in-register (fully fair per-call cost) +__global__ void tc_inline(const uint16_t* __restrict__ x_b, const uint16_t* __restrict__ w_b, + float* __restrict__ partials, long long n_in, long long n_out, int ks) { + const int tile = blockIdx.x, ks_i = blockIdx.y, lane = threadIdx.x & 31; + const long long n_base = (long long) tile * 8; + const long long k_per = n_in / (long long) ks; + const long long k0 = (long long) ks_i * k_per; + const int t2 = 2 * (lane & 3); + float c0 = 0.f, c1 = 0.f, c2 = 0.f, c3 = 0.f; + for (long long kk0 = k0; kk0 < k0 + k_per; kk0 += 8) { + unsigned xh = (unsigned) x_b[kk0 + t2] | ((unsigned) x_b[kk0 + t2 + 1] << 16); + __half2 ha = __floats2half2_rn(bf16_f32((uint16_t) (xh & 0xFFFF)), bf16_f32((uint16_t) (xh >> 16))); + __half2 hb = __floats2half2_rn(bf16_f32((uint16_t) (xh & 0xFFFF)), bf16_f32((uint16_t) (xh >> 16))); + unsigned a0 = *reinterpret_cast(&ha); + unsigned a1 = *reinterpret_cast(&hb); + const uint16_t* wbv = w_b + (n_base + (lane >> 2)) * n_in + kk0 + t2; + __half2 wbh = __floats2half2_rn(bf16_f32(wbv[0]), bf16_f32(wbv[1])); + unsigned b0 = *reinterpret_cast(&wbh); + asm volatile("mma.sync.aligned.m16n8k8.row.col.f32.f16.f16.f32 {%0,%1,%2,%3}, {%4,%5}, {%6}, {%0,%1,%2,%3};\n" + : "+f"(c0), "+f"(c1), "+f"(c2), "+f"(c3) + : "r"(a0), "r"(a1), "r"(b0)); + } + if (lane < 4) { float* p = partials + (size_t) (tile * ks + ks_i) * 8; p[t2] = c0; p[t2 + 1] = c1; } +} + +__global__ void tc_reduce(const float* __restrict__ partials, float* __restrict__ y, long long n_out, int ks) { + const long long o = blockIdx.x * blockDim.x + threadIdx.x; + if (o >= n_out) return; + float s = 0.f; + for (int q = 0; q < ks; ++q) s += partials[(size_t) ((o >> 3) * ks + q) * 8 + (o & 7)]; + y[o] = s; +} + +// variant with the OTHER candidate A layout: a0 = {A[gid][2t], A[gid+8][2t]} (same k-col, two rows), +// a1 = same for col 2t+1. Broadcast => both halves of a0 hold x[2t], both halves of a1 hold x[2t+1]. +__global__ void tc_dupcol(const uint16_t* __restrict__ x_b, const uint16_t* __restrict__ w_b, + float* __restrict__ partials, long long n_in, long long n_out, int ks) { + const int tile = blockIdx.x, ks_i = blockIdx.y, lane = threadIdx.x & 31; + const long long n_base = (long long) tile * 8; + const long long k_per = n_in / (long long) ks; + const long long k0 = (long long) ks_i * k_per; + const int t2 = 2 * (lane & 3); + float c0 = 0.f, c1 = 0.f, c2 = 0.f, c3 = 0.f; + for (long long kk0 = k0; kk0 < k0 + k_per; kk0 += 8) { + __half2 ha = __floats2half2_rn(bf16_f32(x_b[kk0 + t2]), bf16_f32(x_b[kk0 + t2])); + __half2 hb = __floats2half2_rn(bf16_f32(x_b[kk0 + t2 + 1]), bf16_f32(x_b[kk0 + t2 + 1])); + unsigned a0 = *reinterpret_cast(&ha); + unsigned a1 = *reinterpret_cast(&hb); + const uint16_t* wbv = w_b + (n_base + (lane >> 2)) * n_in + kk0 + t2; + __half2 wbh = __floats2half2_rn(bf16_f32(wbv[0]), bf16_f32(wbv[1])); + unsigned b0 = *reinterpret_cast(&wbh); + asm volatile("mma.sync.aligned.m16n8k8.row.col.f32.f16.f16.f32 {%0,%1,%2,%3}, {%4,%5}, {%6}, {%0,%1,%2,%3};\n" + : "+f"(c0), "+f"(c1), "+f"(c2), "+f"(c3) + : "r"(a0), "r"(a1), "r"(b0)); + } + if (lane < 4) { float* p = partials + (size_t) (tile * ks + ks_i) * 8; p[t2] = c0; p[t2 + 1] = c1; } +} + +// FUSED, ks=1 only: with a single k-fragment the partial IS the answer -> write y directly, no reduce kernel, +// no scratch. Fully inline bf16 W conversion (fairest per-call TC cost). +__global__ void tc_fused(const uint16_t* __restrict__ x_b, const uint16_t* __restrict__ w_b, + float* __restrict__ y, long long n_in, long long n_out) { + const int tile = blockIdx.x, lane = threadIdx.x & 31; + const long long n_base = (long long) tile * 8; + const int t2 = 2 * (lane & 3); + float c0 = 0.f, c1 = 0.f, c2 = 0.f, c3 = 0.f; + for (long long kk0 = 0; kk0 < n_in; kk0 += 8) { + __half2 ha = __floats2half2_rn(bf16_f32(x_b[kk0 + t2]), bf16_f32(x_b[kk0 + t2 + 1])); + __half2 hb = ha; // broadcast: row gid+8 = row gid (single-token GEMV) + unsigned a0 = *reinterpret_cast(&ha); + unsigned a1 = *reinterpret_cast(&hb); + const uint16_t* wbv = w_b + (n_base + (lane >> 2)) * n_in + kk0 + t2; + __half2 wbh = __floats2half2_rn(bf16_f32(wbv[0]), bf16_f32(wbv[1])); + unsigned b0 = *reinterpret_cast(&wbh); + asm volatile("mma.sync.aligned.m16n8k8.row.col.f32.f16.f16.f32 {%0,%1,%2,%3}, {%4,%5}, {%6}, {%0,%1,%2,%3};\n" + : "+f"(c0), "+f"(c1), "+f"(c2), "+f"(c3) + : "r"(a0), "r"(a1), "r"(b0)); + } + if (lane < 4) { y[n_base + t2] = c0; y[n_base + t2 + 1] = c1; } +} + +int main() { + CHECK(cudaSetDevice(0)); + cudaDeviceProp prop; CHECK(cudaGetDeviceProperties(&prop, 0)); + printf("device: %s, SMs %d, capability %d.%d\n", prop.name, prop.multiProcessorCount, prop.major, prop.minor); + + struct Shape { const char* name; long long n_in, n_out; }; + Shape shapes[] = { + {"ssm_alpha/beta [2560,48]", 2560, 48}, + {"indexer.k_proj [2560,128]", 2560, 128}, + {"q_proj/router [2560,512]", 2560, 512}, + {"ple_value [2560,2560]", 2560, 2560}, + }; + auto rng = [](unsigned& s) { s = s * 1664525u + 1013904223u; return (float) ((s >> 8) & 0xFFFF) / 65535.0f - 0.5f; }; + const int ITERS = 2000, WARM = 300; + + printf("\n%-26s %13s | %s\n", "shape", "baseline us", "tc variants (pc = W preconverted, in = inline conversion, fused = no reduce), speedup vs baseline"); + printf("%s\n", std::string(150, '-').c_str()); + + for (auto& sh : shapes) { + const long long n_in = sh.n_in, n_out = sh.n_out; + const size_t wn = (size_t) n_out * n_in; + std::vector hw(wn), hx(n_in), hf(wn); + std::vector hyb(n_out), hypc(n_out), hyin(n_out), hyfu(n_out); + std::vector href(n_out); + unsigned seed = 991u + (unsigned) (n_out & 0xFFF); + for (size_t i = 0; i < wn; ++i) hw[i] = f32_bf16_host(rng(seed) * 0.3f); + for (long long i = 0; i < n_in; ++i) hx[i] = f32_bf16_host(rng(seed) * 3.0f); + for (long long o = 0; o < n_out; ++o) { + double s = 0.0; + for (long long i = 0; i < n_in; ++i) s += (double) bf16_f32_host(hx[i]) * (double) bf16_f32_host(hw[(size_t) o * n_in + i]); + href[o] = s; + } + // preconvert W to fp16 (bf16 -> fp16 is exact within fp16 range) + for (size_t i = 0; i < wn; ++i) { __half h = __float2half_rn(bf16_f32_host(hw[i])); memcpy(&hf[i], &h, 2); } + + uint16_t *dx, *dw, *dwf; float *dy, *dyp; + CHECK(cudaMalloc(&dx, n_in * 2)); + CHECK(cudaMalloc(&dw, wn * 2)); CHECK(cudaMalloc(&dwf, wn * 2)); + CHECK(cudaMalloc(&dy, n_out * 4)); + CHECK(cudaMalloc(&dyp, (size_t)(n_out / 8) * 65 * 8 * 4)); + CHECK(cudaMemcpy(dx, hx.data(), n_in * 2, cudaMemcpyHostToDevice)); + CHECK(cudaMemcpy(dw, hw.data(), wn * 2, cudaMemcpyHostToDevice)); + CHECK(cudaMemcpy(dwf, hf.data(), wn * 2, cudaMemcpyHostToDevice)); + + // one-time W conversion cost (host->device, reported separately; the engine would fold this + // into the weight load exactly like Gemm::bf16 does for sm<80) + { + cudaEvent_t e0, e1; CHECK(cudaEventCreate(&e0)); CHECK(cudaEventCreate(&e1)); + CHECK(cudaEventRecord(e0)); + CHECK(cudaMemcpy(dwf, hf.data(), wn * 2, cudaMemcpyHostToDevice)); + CHECK(cudaEventRecord(e1)); CHECK(cudaEventSynchronize(e1)); + float ms = 0; CHECK(cudaEventElapsedTime(&ms, e0, e1)); + printf("%-26s one-time W convert: %.2f ms (%.1f MB), tiles=%lld\n", sh.name, ms, wn * 2 / 1e6, n_out / 8); + } + + int tiles = (int) (n_out / 8); + // valid ks must divide n_in so each k-chunk is a multiple of 8; sweep ALL of them, report the best + const int cands[11] = {1, 2, 4, 5, 8, 10, 16, 20, 32, 40, 64}; + + auto timeit = [&](const char* tag, const std::function& fn) -> double { + for (int i = 0; i < WARM; ++i) fn(); + CHECK(cudaDeviceSynchronize()); + double best = 1e30; + for (int rep = 0; rep < 3; ++rep) { + cudaEvent_t e0, e1; CHECK(cudaEventCreate(&e0)); CHECK(cudaEventCreate(&e1)); + CHECK(cudaEventRecord(e0)); + for (int i = 0; i < ITERS; ++i) fn(); + CHECK(cudaEventRecord(e1)); CHECK(cudaEventSynchronize(e1)); + float ms = 0; CHECK(cudaEventElapsedTime(&ms, e0, e1)); + double us = ms * 1000.0 / ITERS; + if (us < best) best = us; + } + (void) tag; return best; + }; + + double t_base = timeit("base", [&]{ gemv_warp<<<(unsigned) ((n_out + 7) / 8), 256>>>(dx, dw, dy, n_in, n_out); }); + gemv_warp<<<(unsigned) ((n_out + 7) / 8), 256>>>(dx, dw, dy, n_in, n_out); + CHECK(cudaMemcpy(hyb.data(), dy, n_out * 4, cudaMemcpyDeviceToHost)); + + // occupancy sweep over k-chunk count for the preconverted-W TC kernel + int best_ks = 1; double t_pc = 1e30; + for (int i = 0; i < 11; ++i) { + const int ksv = cands[i]; + if (n_in % ksv != 0) continue; + dim3 g((unsigned) tiles, (unsigned) ksv); + double t = timeit("pcs", [&]{ tc_preconv<<>>(dx, dwf, dyp, n_in, n_out, ksv); + tc_reduce<<<(unsigned) ((n_out + 255) / 256), 256>>>(dyp, dy, n_out, ksv); }); + if (t < t_pc) { t_pc = t; best_ks = ksv; } + } + dim3 gtc((unsigned) tiles, (unsigned) best_ks); + tc_preconv<<>>(dx, dwf, dyp, n_in, n_out, best_ks); + tc_reduce<<<(unsigned) ((n_out + 255) / 256), 256>>>(dyp, dy, n_out, best_ks); + CHECK(cudaMemcpy(hypc.data(), dy, n_out * 4, cudaMemcpyDeviceToHost)); + + double t_ti = timeit("tci", [&]{ tc_inline<<>>(dx, dw, dyp, n_in, n_out, best_ks); + tc_reduce<<<(unsigned) ((n_out + 255) / 256), 256>>>(dyp, dy, n_out, best_ks); }); + tc_inline<<>>(dx, dw, dyp, n_in, n_out, best_ks); + tc_reduce<<<(unsigned) ((n_out + 255) / 256), 256>>>(dyp, dy, n_out, best_ks); + CHECK(cudaMemcpy(hyin.data(), dy, n_out * 4, cudaMemcpyDeviceToHost)); + + double t_fu = timeit("tcf", [&]{ tc_fused<<<(unsigned) tiles, 32>>>(dx, dw, dy, n_in, n_out); }); + tc_fused<<<(unsigned) tiles, 32>>>(dx, dw, dy, n_in, n_out); + CHECK(cudaMemcpy(hyfu.data(), dy, n_out * 4, cudaMemcpyDeviceToHost)); + + double best_tc = t_pc; const char* best_var = "preconv"; + if (t_ti < best_tc) { best_tc = t_ti; best_var = "inline"; } + if (t_fu < best_tc) { best_tc = t_fu; best_var = "fused"; } + + double e_tc = 0, e_base = 0, sc = 0; + if (strcmp(best_var, "preconv") == 0) { + for (long long o = 0; o < n_out; ++o) { e_tc = std::max(e_tc, std::fabs((double) hypc[o] - href[o])); } + } else if (strcmp(best_var, "inline") == 0) { + for (long long o = 0; o < n_out; ++o) { e_tc = std::max(e_tc, std::fabs((double) hyin[o] - href[o])); } + } else { + for (long long o = 0; o < n_out; ++o) { e_tc = std::max(e_tc, std::fabs((double) hyfu[o] - href[o])); } + } + for (long long o = 0; o < n_out; ++o) { + e_base = std::max(e_base, std::fabs((double) hyb[o] - href[o])); + sc = std::max(sc, std::fabs(href[o])); + } + double gb_base = (double) (wn * 2) / t_base / 1e3; + double gb_tc = (double) (wn * 2) / best_tc / 1e3; + printf("%-26s %13.3f | pc %13.3f (ks=%d) | in %13.3f | fused %13.3f | BEST %s %7.3fx | maxerr tc %.2e base %.2e (scale %.1f, BW base %.0f tc %.0f GB/s)\n", + sh.name, t_base, t_pc, best_ks, t_ti, t_fu, best_var, t_base / best_tc, + e_tc, e_base, sc, gb_base, gb_tc); + + CHECK(cudaFree(dx)); CHECK(cudaFree(dw)); CHECK(cudaFree(dwf)); CHECK(cudaFree(dy)); CHECK(cudaFree(dyp)); + } + + { // bf16 -> fp16 exactness scan + unsigned seed = 777u; double worst = 0; int bad = 0, n = 2000000; + for (int i = 0; i < n; ++i) { + float f = (rng(seed) * 2.0f - 1.0f) * 100.0f; + uint16_t b = f32_bf16_host(f); + __half h = __float2half_rn(bf16_f32_host(b)); + if ((double) __half2float(h) != (double) bf16_f32_host(b)) { + bad++; worst = std::max(worst, std::fabs((double) __half2float(h) - (double) bf16_f32_host(b))); + } + } + printf("\nbf16->fp16 conversion exactness: %d / %d inexact, worst %.3g\n", bad, n, worst); + } + printf("BENCH_DONE\n"); + return 0; +} From b0711943b2c7a689e8f803a419952e62ae04171e Mon Sep 17 00:00:00 2001 From: Pravesh Khatana Date: Thu, 1 Oct 2026 00:30:27 +0530 Subject: [PATCH 12/48] feat(mtp): add --coupled-draft and --no-coupled-draft CLI options for coupled speculative sampling - Add set_coupled_draft() and coupled_draft_state() in include/strata/core/coupled_draft.hpp - Add --coupled-draft and --no-coupled-draft CLI options to src/program/generate.cpp - Default option to STRATA_SPEC_COUPLED environment variable for full backward compatibility - Update usage() help text with option descriptions --- include/strata/core/coupled_draft.hpp | 14 +++++++++++--- src/program/generate.cpp | 7 +++++++ 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/include/strata/core/coupled_draft.hpp b/include/strata/core/coupled_draft.hpp index 4758674b..d095e3a0 100644 --- a/include/strata/core/coupled_draft.hpp +++ b/include/strata/core/coupled_draft.hpp @@ -49,15 +49,23 @@ namespace strata::core { /// The longest penalty window the coupled drafter mirrors (serve's kPenaltyWindowCap). inline constexpr int kCoupledHistCap = 4096; -/// STRATA_SPEC_COUPLED=1 (any value but empty or "0"): read once. -inline bool coupled_draft_env() { - static const bool on = [] { +inline bool& coupled_draft_state() { + static bool on = [] { const char* e = std::getenv("STRATA_SPEC_COUPLED"); return e != nullptr && *e != '\0' && std::strcmp(e, "0") != 0; }(); return on; } +/// Whether coupled draft sampling is enabled (via STRATA_SPEC_COUPLED=1 or --coupled-draft CLI flag). +inline bool coupled_draft_env() { + return coupled_draft_state(); +} + +inline void set_coupled_draft(bool on) { + coupled_draft_state() = on; +} + /// The MTP cell of chain step j after a window at `p` with `a` drafts accepted (draft() runs step j there). STRATA_COUPLED_HD inline int64_t coupled_draft_cell(int64_t p, int a, int j) { return p + a + j; } diff --git a/src/program/generate.cpp b/src/program/generate.cpp index ce58147e..ee915d27 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -18,6 +18,7 @@ #include "strata/core/expert_cache.hpp" #include "strata/core/conversation_snapshot.hpp" #include "strata/core/conversation_memory.hpp" +#include "strata/core/coupled_draft.hpp" #include "strata/core/expert_source.hpp" #include "strata/core/pinned.hpp" #include "strata/core/remote_experts.hpp" @@ -257,6 +258,7 @@ struct Options { /// pool's own drain: 33.7 GB/s against 5/6 x 44.14 = 36.8 for five workers, on a machine whose sixth core /// is reserved for a host thread that has nothing to do while the drain runs. bool no_host_worker = false; + bool coupled_draft = strata::core::coupled_draft_env(); ///< Coupled draft sampling for MTP drafter under sampling bool mmap_experts = false; ///< R2.1: opt OUT of the resident arena, back to MapViewOfFile std::string shared_expert_arena; ///< Linux: optional file backing for the resident arena shared by processes bool resident_cpu_experts = false; ///< mmap-backed static-cache misses copied into ordinary RAM @@ -542,6 +544,8 @@ void usage() { " --pool-workers N R2.2: CPU expert pool worker count. Default 0 = every physical core\n" " except the one the host loop spins on. A sweep is how the pool's\n" " deviation from `cpu_s2` is attributed.\n" + " --coupled-draft enable coupled draft sampling for MTP drafter under sampling (STRATA_SPEC_COUPLED)\n" + " --no-coupled-draft disable coupled draft sampling (propose argmax drafts)\n" " --mmap-experts R2.1: opt OUT of the resident expert arena, back to MapViewOfFile.\n" " The A/B arm: the mmap's rate depends on the OS page cache holding\n" " 34 GB, and measured 71.97 vs 34.78 ms/token cold vs warm.\n" @@ -1070,6 +1074,8 @@ int main(int argc, char** argv) { else if (a == "--pool-workers") o.pool_workers = std::atoi(next("--pool-workers")); else if (a == "--no-host-worker") o.no_host_worker = true; else if (a == "--no-ple-prefetch") o.no_ple_prefetch = true; + else if (a == "--coupled-draft") o.coupled_draft = true; + else if (a == "--no-coupled-draft") o.coupled_draft = false; else parsed = false; // The chain continues here in a second statement: one chain of 120+ `else if` passed MSVC's limit of 128 // nested blocks (C1061). The order of the tests and what each does are unchanged. @@ -1216,6 +1222,7 @@ int main(int argc, char** argv) { } } } + strata::core::set_coupled_draft(o.coupled_draft); if (o.serve && o.conversation_cache_mib > 0 && (o.prompt_cache == 0 || o.conversation_cache_slots == 0)) std::fprintf(stderr, "strata serve: warning: conversation caching is disabled by %s\n", o.prompt_cache == 0 ? "--prompt-cache 0" : "--conversation-cache-slots 0"); From 6cd29d9850ad7a3fcd2c8af88d5e4f73d087f307 Mon Sep 17 00:00:00 2001 From: Developer Date: Wed, 30 Sep 2026 17:31:45 -0500 Subject: [PATCH 13/48] serve: keep retained K/V through the cache capacity gate park_current dropped the retained K/V whenever can_fit failed and fell back to a full snapshot capture. The gate duplicates what make_room decides immediately after, with harsher arithmetic: the slot term fires when make_room enforces the same cap, and the byte term compares the with-reuse estimate against headroom that ignores the parked image replacing the retained buffers. make_room already implements the stated policy - pressure drops the optional retained storage before evicting any parked conversation (the priority the cache tests pin). With a full cache the fallback buys nothing: the fresh estimate forces the same or more eviction, plus a whole-snapshot recapture instead of the growth - hundreds of ms per park at ~100K tokens where one long conversation round-trips while short-lived conversations keep the cache full. The with-reuse estimate stays uncapped: it counts the retained buffers' capacity and directories, and put() charges that same true size, so a capped figure would under-evict and overfill the budget. --- src/program/generate.cpp | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/src/program/generate.cpp b/src/program/generate.cpp index ee915d27..74c47759 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -4006,11 +4006,12 @@ int main(int argc, char** argv) { estimate = fresh_estimate; err.clear(); } - if (!reuse.kv.empty() && !conversations.can_fit(estimate, held)) { - // Optional growth capacity must not evict useful conversations. - reuse = {}; - estimate = fresh_estimate; - } + // A park carrying its own retained K/V replaces memory the cache + // already held, so capacity is make_room's call - it runs next either + // way, and put()'s accounting still bounds the budget. The with-reuse + // estimate must stay uncapped: it counts the retained buffers' + // capacity and directories, and put() charges that same true size - + // a capped figure would under-evict and overfill the budget. if (!conversations.make_room(estimate, held)) { std::fprintf(stderr, "strata serve: conversation cache: skip parking (snapshot %zu MiB exceeds available budget)\n", estimate >> 20); From ca85ebdee2a7707a091ad3a233e61c59e89e7d97 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Thu, 1 Oct 2026 08:18:19 +0200 Subject: [PATCH 14/48] #278 follow-up: an Anthropic request with its own reasoning_budget_tokens still thinks "thinking" absent meant no thinking, also for a request that gives reasoning_budget_tokens (#123), which asks for thinking with a cap (serve.test_server's test_anthropic_stream failed: no thinking at all). Such a request renders as before. test_anthropic_thinks_only_when_asked pins the five cases. --- serve/frontend.py | 5 +++-- serve/test_server.py | 11 +++++++++++ 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/serve/frontend.py b/serve/frontend.py index edcddb79..84310811 100644 --- a/serve/frontend.py +++ b/serve/frontend.py @@ -219,10 +219,11 @@ def anthropic_to_messages(req: dict) -> tuple[list[dict], list[dict] | None, dic kwargs.update(effort_kwargs(effort)) elif isinstance(thinking, dict) and thinking.get("budget_tokens"): kwargs.update(budget_effort(thinking["budget_tokens"])) - elif thinking is None: + elif thinking is None and not req.get("reasoning_budget_tokens"): # Anthropic's thinking is opt-in. Claude Code's helper calls (a session title, a topic check) ask for none # and allow a few dozen tokens, which the model otherwise spent thinking and answered with no text at all. - # A config's reasoning_effort still applies: Service.with_shared sets output_config before this runs. + # 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 diff --git a/serve/test_server.py b/serve/test_server.py index e5d31184..123e0780 100644 --- a/serve/test_server.py +++ b/serve/test_server.py @@ -65,6 +65,17 @@ class MaxTokens(unittest.TestCase): u = b.get("usage", {}) return s, b, u.get("input_tokens"), u.get("output_tokens") + def test_anthropic_thinks_only_when_asked(self): + # #278: Anthropic's thinking is opt-in; "thinking", an effort or a reasoning_budget_tokens (#123) asks for it + from serve.frontend import anthropic_to_messages + msgs = [{"role": "user", "content": "u"}] + kw = lambda **r: anthropic_to_messages({"messages": msgs, **r})[2] # noqa: E731 + self.assertEqual(kw(), {"enable_thinking": False}) + self.assertEqual(kw(thinking={"type": "disabled"}), {"enable_thinking": False}) + self.assertNotIn("enable_thinking", kw(thinking={"type": "enabled", "budget_tokens": 2048})) + self.assertNotIn("enable_thinking", kw(output_config={"effort": "high"})) + self.assertNotIn("enable_thinking", kw(reasoning_budget_tokens=30)) + def test_count_tokens_is_the_prompt_messages_reads(self): # /v1/messages/count_tokens renders and tokenizes the same prompt /v1/messages would read, without running it msgs = [{"role": "user", "content": "how many tokens is this?"}] From 392e32c46b41d716b2fb3540b52c4bdb3631af18 Mon Sep 17 00:00:00 2001 From: BlitzenCats <235even.right@gmail.com> Date: Wed, 30 Sep 2026 17:22:09 -0700 Subject: [PATCH 15/48] serve: add CORS preflight (OPTIONS), reverse-proxy header support, and X-Accel-Buffering for SSE - Implement do_OPTIONS (204 No Content) and add Access-Control-Allow-* headers to allow web-based clients (Open WebUI, LibreChat, browser extensions) to query endpoints. - Update _own_page to recognize reverse proxies and tunnels (Cloudflare Tunnel, Tailscale Funnel, Nginx) via X-Forwarded-Host, CF-Ray, and forwarded headers, preventing 403 CSRF false-positives when serving remotely. - Add X-Accel-Buffering: no to SSE streaming responses to prevent reverse proxies from buffering real-time token generation. - Add unit tests in serve/test_server.py covering CORS preflight, CORS headers, and reverse proxy origin checks. Co-authored-by: Gemini --- serve/server.py | 23 ++++++++++++++++++++--- serve/test_server.py | 22 ++++++++++++++++++++++ 2 files changed, 42 insertions(+), 3 deletions(-) diff --git a/serve/server.py b/serve/server.py index bcb14381..353fca91 100644 --- a/serve/server.py +++ b/serve/server.py @@ -1524,10 +1524,20 @@ def make_handler(svc: Service): def log_message(self, fmt, *args): pass + def do_OPTIONS(self): + self.send_response(204) + self.send_header("Access-Control-Allow-Origin", "*") + self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS") + self.send_header("Access-Control-Allow-Headers", "*") + self.end_headers() + def _json(self, code, obj): body = json.dumps(obj, ensure_ascii=False).encode() self.send_response(code) self.send_header("Content-Type", "application/json") + self.send_header("Access-Control-Allow-Origin", "*") + self.send_header("Access-Control-Allow-Headers", "*") + self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS") self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body) @@ -1712,9 +1722,13 @@ def make_handler(svc: Service): self._json(415, {"error": {"message": "send application/json"}}) return False origin = self.headers.get("Origin") - if origin and origin.split("://", 1)[-1] != self.headers.get("Host", ""): - self._json(403, {"error": {"message": f"{what} only from Strata's own page"}}) - return False + if origin: + origin_host = origin.split("://", 1)[-1].split("/")[0] + host = self.headers.get("X-Forwarded-Host") or self.headers.get("Host", "") + if origin_host != host and origin_host.split(":")[0] != host.split(":")[0]: + if not (self.headers.get("CF-Ray") or self.headers.get("X-Forwarded-For") or self.headers.get("CF-Connecting-IP")): + self._json(403, {"error": {"message": f"{what} only from Strata's own page"}}) + return False return True def _settings(self): @@ -1736,6 +1750,9 @@ def make_handler(svc: Service): self.send_response(200) self.send_header("Content-Type", "text/event-stream") self.send_header("Cache-Control", "no-cache") + self.send_header("X-Accel-Buffering", "no") + self.send_header("Access-Control-Allow-Origin", "*") + self.send_header("Access-Control-Allow-Headers", "*") self.end_headers() def _openai(self, req): diff --git a/serve/test_server.py b/serve/test_server.py index 123e0780..0f281646 100644 --- a/serve/test_server.py +++ b/serve/test_server.py @@ -811,6 +811,16 @@ class SharedSettings(unittest.TestCase): finally: self.svc.api_key = "" + def test_reverse_proxy_origin_allowed(self): + # A tunnel or reverse-proxy with matching X-Forwarded-Host + code, _ = self.req("/settings", {"defaults": {"temperature": 1}}, + {"Origin": "https://proxy.example.com", "X-Forwarded-Host": "proxy.example.com"}) + self.assertEqual(code, 200) + # Cloudflare Tunnel passing CF-Ray + code, _ = self.req("/settings", {"defaults": {"temperature": 1}}, + {"Origin": "https://random-name.trycloudflare.com", "CF-Ray": "1234567890"}) + self.assertEqual(code, 200) + class WebApp(unittest.TestCase): """The web app (PR #22's dashboard idea, rebuilt): its page and files, and GET /metrics.""" @@ -1004,6 +1014,18 @@ class UsageAndStatus(unittest.TestCase): return [json.loads(line[6:]) for line in raw.decode().splitlines() if line.startswith("data: {")] + def test_cors_preflight_options(self): + req = urllib.request.Request(self.base + "/v1/chat/completions", method="OPTIONS") + with urllib.request.urlopen(req, timeout=10) as r: + self.assertEqual(r.status, 204) + self.assertEqual(r.headers.get("Access-Control-Allow-Origin"), "*") + self.assertIn("OPTIONS", r.headers.get("Access-Control-Allow-Methods", "")) + + def test_cors_headers(self): + req = urllib.request.Request(self.base + "/health") + with urllib.request.urlopen(req, timeout=10) as r: + self.assertEqual(r.headers.get("Access-Control-Allow-Origin"), "*") + def test_openai(self): b = self.chat("/v1/chat/completions") u, t = b["usage"], b["timings"] From a8d5a16c3565ea1c54f3fe1234d7c5bc10aea297 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Thu, 1 Oct 2026 08:23:27 +0200 Subject: [PATCH 16/48] #321 follow-up: CORS only on /v1/* for configured origins; no own-page bypass for proxy headers - The Origin check of /settings and the MCP tools let any page through when the request carried X-Forwarded-For, CF-Ray or CF-Connecting-IP (headers every reverse proxy or tunnel adds), and compared hosts without their ports (a page on another local port passed): any web page could then change the shared settings or run MCP tools with the user's rights. Removed. The Origin must be this server's host:port, or an origin in the config's new "trusted_origins" (the web app behind a proxy or tunnel); a proxy header alone opens nothing. - CORS is opt-in: "cors_origins" in the config (an origin, a list, or "*"). Only /v1/* answers with Access-Control-Allow-Origin (the origin itself, or "*"), never /settings, /unload or the app's files; the preflight echoes the headers asked for ("*" does not cover Authorization). OPTIONS is answered 204 either way. - X-Accel-Buffering: no on SSE stays. origins_of() checks both lists at start (scheme://host[:port], no paths; "*" only for cors_origins). docs/DETAILS.md; tests for the bypasses, the trusted origin, CORS off/on, the header. --- docs/DETAILS.md | 7 +++- serve/server.py | 89 +++++++++++++++++++++++++++++++++++--------- serve/test_server.py | 89 +++++++++++++++++++++++++++++++++++--------- 3 files changed, 148 insertions(+), 37 deletions(-) diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 8b9f75e2..2454069f 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -447,7 +447,12 @@ print(r.choices[0].message.content) - **From the internet.** Put a tunnel in front of it, for example [cloudflared](https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/do-more-with-tunnels/trycloudflare/): `cloudflared tunnel --url http://127.0.0.1:8080`. **Set a key first**, or anyone with the link can use your PC: add `"api_key": "some-long-secret"` to `strata-.json` (or set the `STRATA_API_KEY` environment variable); - clients then send it as their API key. + clients then send it as their API key. Streamed answers carry `X-Accel-Buffering: no`, so nginx-style proxies pass + each token on at once. The web app's settings and MCP tools only answer Strata's own page: when you open it through + a proxy or tunnel whose address differs, add that address, e.g. `"trusted_origins": ["https://strata.example.com"]`. +- **From web apps in a browser (CORS).** Off by default. `"cors_origins": ["https://chat.example.com"]` lets pages of + those origins call `/v1/*` from the browser (Open WebUI's direct connections, browser extensions); `["*"]` lets any + page do it - only sensible with an API key. It never opens `/settings`, `/unload` or the MCP tools. **Conversation cache.** A request that continues a chat reads only the part after what the engine already holds: the live session, or one of the checkpoints it keeps in RAM (up to 6, ~118 MB each, taken at the start of each new diff --git a/serve/server.py b/serve/server.py index 353fca91..5c5fbd10 100644 --- a/serve/server.py +++ b/serve/server.py @@ -673,6 +673,12 @@ class Service: self.fifo = threading.Lock() self.embeddings = threading.local() # the current request's image embeddings file (GENI) self.api_key = "" # when set, /v1/* needs it (Bearer or x-api-key) + # #321: browser pages of these origins may call /v1/* (CORS; "*" = any page - only with an api_key that + # matters); empty = no CORS headers at all, as before + self.cors_origins: list[str] = [] + # #321: origins that count as Strata's own page for /settings and MCP tools, e.g. the web app reached through a + # reverse proxy or tunnel whose Host differs ("https://strata.example.com"); never a wildcard + self.trusted_origins: list[str] = [] self.status = {"busy": False, "queued": 0} # GET /status: what the model is doing right now self.rate = collections.deque(maxlen=32) # (time, generated) samples for the live tok/s window self.history = collections.deque(maxlen=500) # the last finished requests, newest last (GET /metrics) @@ -1524,20 +1530,39 @@ def make_handler(svc: Service): def log_message(self, fmt, *args): pass - def do_OPTIONS(self): - self.send_response(204) - self.send_header("Access-Control-Allow-Origin", "*") + def _cors(self): + """#321: CORS headers for an API path (/v1/*) and an origin the config lists in cors_origins - nothing + otherwise, so a browser keeps every other page away from the API, /settings, /unload and the MCP tools.""" + if not svc.cors_origins or not self.path.split("?")[0].startswith("/v1/"): + return + origin = (self.headers.get("Origin") or "").rstrip("/") + if "*" in svc.cors_origins: + allow = "*" + elif origin and origin in svc.cors_origins: + allow = origin + self.send_header("Vary", "Origin") + else: + return + self.send_header("Access-Control-Allow-Origin", allow) self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS") - self.send_header("Access-Control-Allow-Headers", "*") + # the headers the preflight asks for (SDKs add their own; "*" does not cover Authorization) + asked = self.headers.get("Access-Control-Request-Headers") + self.send_header("Access-Control-Allow-Headers", + asked or "Authorization, Content-Type, x-api-key, anthropic-version, anthropic-beta") + self.send_header("Access-Control-Max-Age", "600") + + def do_OPTIONS(self): + # a CORS preflight: no credentials come with it, so no API key; the headers only for cors_origins + self.send_response(204) + self._cors() + self.send_header("Content-Length", "0") self.end_headers() def _json(self, code, obj): body = json.dumps(obj, ensure_ascii=False).encode() self.send_response(code) self.send_header("Content-Type", "application/json") - self.send_header("Access-Control-Allow-Origin", "*") - self.send_header("Access-Control-Allow-Headers", "*") - self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS") + self._cors() self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body) @@ -1721,14 +1746,15 @@ def make_handler(svc: Service): if not self.headers.get("Content-Type", "").startswith("application/json"): self._json(415, {"error": {"message": "send application/json"}}) return False - origin = self.headers.get("Origin") - if origin: - origin_host = origin.split("://", 1)[-1].split("/")[0] - host = self.headers.get("X-Forwarded-Host") or self.headers.get("Host", "") - if origin_host != host and origin_host.split(":")[0] != host.split(":")[0]: - if not (self.headers.get("CF-Ray") or self.headers.get("X-Forwarded-For") or self.headers.get("CF-Connecting-IP")): - self._json(403, {"error": {"message": f"{what} only from Strata's own page"}}) - return False + # The Origin must be this server's own address (host and port), or an origin the config trusts + # (trusted_origins: the web app behind a reverse proxy or tunnel). Headers a proxy adds (X-Forwarded-*, + # CF-Ray, CF-Connecting-IP) prove nothing about the page that sent the request, so they open nothing. + origin = (self.headers.get("Origin") or "").rstrip("/") + if origin and origin.split("://", 1)[-1] != self.headers.get("Host", "") and \ + origin not in svc.trusted_origins: + self._json(403, {"error": {"message": f"{what} only from Strata's own page (or an origin in the " + f"config's trusted_origins)"}}) + return False return True def _settings(self): @@ -1750,9 +1776,8 @@ def make_handler(svc: Service): self.send_response(200) self.send_header("Content-Type", "text/event-stream") self.send_header("Cache-Control", "no-cache") - self.send_header("X-Accel-Buffering", "no") - self.send_header("Access-Control-Allow-Origin", "*") - self.send_header("Access-Control-Allow-Headers", "*") + self.send_header("X-Accel-Buffering", "no") # nginx and similar proxies pass each event at once + self._cors() self.end_headers() def _openai(self, req): @@ -1894,6 +1919,28 @@ def serve(svc: Service, host="127.0.0.1", port=8095) -> ThreadingHTTPServer: return httpd +def origins_of(value, key: str, wildcard: bool) -> list[str]: + """#321: a config's origin list ("https://chat.example.com" or a list of them) - scheme://host[:port], no path; + "*" only where `wildcard` allows it. A wrong entry stops the start rather than opening less or more than meant.""" + if value is None or value == "" or value == []: + return [] + items = [value] if isinstance(value, str) else value + if not isinstance(items, list) or not all(isinstance(x, str) for x in items): + raise SystemExit(f"[strata] {key}: expected an origin or a list of origins") + out = [] + for x in items: + x = x.strip().rstrip("/") + if x == "*" and wildcard: + out.append(x) + continue + scheme, sep, rest = x.partition("://") + if scheme not in ("http", "https") or not sep or not rest or "/" in rest or "*" in rest: + raise SystemExit(f"[strata] {key}: {x!r} is not an origin like https://chat.example.com" + + ("" if wildcard else " (no wildcards here)")) + out.append(x) + return out + + SHARED_KEYS = ("reasoning_effort", "temperature", "top_p", "top_k", "seed", "max_tokens", "experimental_speed_projection") @@ -2092,6 +2139,12 @@ def main() -> int: file=sys.stderr) return 2 svc.api_key = a.api_key or cfg.get("api_key", "") + svc.cors_origins = origins_of(cfg.get("cors_origins"), "cors_origins", wildcard=True) + svc.trusted_origins = origins_of(cfg.get("trusted_origins"), "trusted_origins", wildcard=False) + if svc.cors_origins: + print(f"[strata] CORS on /v1/* for {', '.join(svc.cors_origins)}" + + ("" if svc.api_key or "*" not in svc.cors_origins else + " - WARNING: any web page may use the model (no API key)"), flush=True) svc.idle_unload_s = a.idle_unload if a.idle_unload is not None else float(cfg.get("idle_unload_s") or 0) svc.min_free_vram_mib = a.min_free_vram_mib if a.min_free_vram_mib is not None else \ int(cfg.get("min_free_vram_mib") or 0) diff --git a/serve/test_server.py b/serve/test_server.py index 0f281646..2f364631 100644 --- a/serve/test_server.py +++ b/serve/test_server.py @@ -811,15 +811,28 @@ class SharedSettings(unittest.TestCase): finally: self.svc.api_key = "" - def test_reverse_proxy_origin_allowed(self): - # A tunnel or reverse-proxy with matching X-Forwarded-Host - code, _ = self.req("/settings", {"defaults": {"temperature": 1}}, - {"Origin": "https://proxy.example.com", "X-Forwarded-Host": "proxy.example.com"}) - self.assertEqual(code, 200) - # Cloudflare Tunnel passing CF-Ray - code, _ = self.req("/settings", {"defaults": {"temperature": 1}}, - {"Origin": "https://random-name.trycloudflare.com", "CF-Ray": "1234567890"}) - self.assertEqual(code, 200) + def test_proxy_headers_do_not_make_a_page_strata_s_own(self): + # #321: X-Forwarded-*, CF-Ray or CF-Connecting-IP say nothing about the page that sent the request - any web + # page behind any proxy would otherwise change the settings (or run MCP tools) + for extra in ({"X-Forwarded-Host": "proxy.example.com"}, {"CF-Ray": "1234567890"}, + {"X-Forwarded-For": "203.0.113.9"}, {"CF-Connecting-IP": "203.0.113.9"}): + code, _ = self.req("/settings", {"defaults": {"temperature": 1}}, + {"Origin": "https://proxy.example.com", **extra}) + self.assertEqual(code, 403, extra) + # another port on the same host is another site (a local dev server's page) + code, _ = self.req("/settings", {"defaults": {"temperature": 1}}, {"Origin": "http://127.0.0.1:1"}) + self.assertEqual(code, 403) + + def test_a_trusted_origin_is_strata_s_own_page(self): + # the web app behind a reverse proxy or tunnel: the config's trusted_origins + self.svc.trusted_origins = ["https://strata.example.com"] + try: + code, _ = self.req("/settings", {"defaults": {}}, {"Origin": "https://strata.example.com"}) + self.assertEqual(code, 200) + code, _ = self.req("/settings", {"defaults": {}}, {"Origin": "https://evil.example.com"}) + self.assertEqual(code, 403) + finally: + self.svc.trusted_origins = [] class WebApp(unittest.TestCase): @@ -1014,17 +1027,57 @@ class UsageAndStatus(unittest.TestCase): return [json.loads(line[6:]) for line in raw.decode().splitlines() if line.startswith("data: {")] - def test_cors_preflight_options(self): - req = urllib.request.Request(self.base + "/v1/chat/completions", method="OPTIONS") + def preflight(self, path, origin="https://chat.example.com"): + req = urllib.request.Request(self.base + path, method="OPTIONS", + headers={"Origin": origin, "Access-Control-Request-Method": "POST", + "Access-Control-Request-Headers": "authorization, content-type"}) with urllib.request.urlopen(req, timeout=10) as r: - self.assertEqual(r.status, 204) - self.assertEqual(r.headers.get("Access-Control-Allow-Origin"), "*") - self.assertIn("OPTIONS", r.headers.get("Access-Control-Allow-Methods", "")) + return r.status, r.headers - def test_cors_headers(self): - req = urllib.request.Request(self.base + "/health") - with urllib.request.urlopen(req, timeout=10) as r: - self.assertEqual(r.headers.get("Access-Control-Allow-Origin"), "*") + def test_cors_is_off_by_default(self): + # #321: OPTIONS is answered, but without cors_origins no page of another origin is let in + status, h = self.preflight("/v1/chat/completions") + self.assertEqual(status, 204) + self.assertIsNone(h.get("Access-Control-Allow-Origin")) + with urllib.request.urlopen(self.base + "/health", timeout=10) as r: + self.assertIsNone(r.headers.get("Access-Control-Allow-Origin")) + + def test_cors_for_the_configured_origins_on_the_api_only(self): + self.svc.cors_origins = ["https://chat.example.com"] + try: + status, h = self.preflight("/v1/chat/completions") + self.assertEqual((status, h.get("Access-Control-Allow-Origin")), (204, "https://chat.example.com")) + self.assertIn("OPTIONS", h.get("Access-Control-Allow-Methods", "")) + self.assertIn("authorization", h.get("Access-Control-Allow-Headers", "")) + self.assertIsNone(self.preflight("/v1/chat/completions", "https://evil.example.com")[1] + .get("Access-Control-Allow-Origin")) + # never on the app's own endpoints (/settings, /unload, ...) + self.assertIsNone(self.preflight("/settings")[1].get("Access-Control-Allow-Origin")) + req = urllib.request.Request(self.base + "/v1/models", headers={"Origin": "https://chat.example.com"}) + with urllib.request.urlopen(req, timeout=10) as r: + self.assertEqual(r.headers.get("Access-Control-Allow-Origin"), "https://chat.example.com") + self.svc.cors_origins = ["*"] + self.assertEqual(self.preflight("/v1/messages", "https://any.example.com")[1] + .get("Access-Control-Allow-Origin"), "*") + finally: + self.svc.cors_origins = [] + + def test_sse_is_not_buffered_by_proxies(self): + req = urllib.request.Request(self.base + "/v1/chat/completions", headers={"Content-Type": "application/json"}, + data=json.dumps({"model": "m", "stream": True, + "messages": [{"role": "user", "content": "hi"}]}).encode()) + with urllib.request.urlopen(req, timeout=30) as r: + self.assertEqual(r.headers.get("X-Accel-Buffering"), "no") + r.read() + + def test_origin_lists_are_checked(self): + from serve.server import origins_of + self.assertEqual(origins_of(None, "k", True), []) + self.assertEqual(origins_of("https://a.example.com/", "k", False), ["https://a.example.com"]) + self.assertEqual(origins_of(["*", "http://localhost:3000"], "k", True), ["*", "http://localhost:3000"]) + for bad in ("*", "a.example.com", "https://a.example.com/path", "https://*.example.com", 5): + with self.assertRaises(SystemExit): + origins_of(bad, "k", False) def test_openai(self): b = self.chat("/v1/chat/completions") From 7f3a09189526ad4c6f609fd5840fdd2a6932ff14 Mon Sep 17 00:00:00 2001 From: Ricardo Ambrogi <11719845+KadoBOT@users.noreply.github.com> Date: Thu, 1 Oct 2026 04:47:30 +0200 Subject: [PATCH 17/48] serve: add lazy startup and reliable Windows model cleanup --- docs/DETAILS.md | 17 +++++ serve/server.py | 134 ++++++++++++++++++++++++------------ serve/test_lifecycle.py | 147 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 256 insertions(+), 42 deletions(-) create mode 100644 serve/test_lifecycle.py diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 2454069f..3619c9d7 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -778,3 +778,20 @@ Strata itself: [MIT](../LICENSE). The model files are not part of it; their lice `serve/web/fonts/OFL.txt`). Its Monitor tab started from @code-martin's dashboard idea (PR #22). - The experimental speed projection's vector (`data/experimental-speed-projection/`): Qwen Community License 1.0, made from the model's activations (see its README). + +### Start the text API without occupying the GPU + +`serve/server.py --engine strata --config strata-.json --lazy` (or `"lazy_load": true` in that +config) starts the lightweight HTTP API without spawning the native engine. The first generation request +loads it through the existing reload path, including `before_load` and `min_free_vram_mib`. Eager startup +remains the default. This option is text-only: a vision configuration with lazy startup is rejected explicitly. + +`POST /v1/load` and `/v1/unload` are JSON control aliases for integrations, accepting `{}` or +`{"model":""}` and returning model status. They require the configured API key, +`application/json`, and no foreign browser Origin. They return **409** while a request is active or queued, +and **404** for an unknown model. Existing `/load` and `/unload` behavior is preserved. `/api/health` aliases +`/health`; `/v1/status` exposes `loaded` and `auto_load`. The unloaded model remains discoverable. + +Unloading and shutdown close the native engine's stdin after sending `QUIT`, allowing Windows' detached +stdin reader to see EOF. Cleanup waits for process exit before releasing handles; if forced shutdown still +times out, the server keeps ownership and reports an error rather than claiming the model was unloaded. diff --git a/serve/server.py b/serve/server.py index 5c5fbd10..32ef0648 100644 --- a/serve/server.py +++ b/serve/server.py @@ -100,6 +100,10 @@ class EngineDied(RuntimeError): """The engine process ended in the middle of a request (issue #27: on Linux, the out-of-memory killer).""" +class ModelBusy(RuntimeError): + """Explicit model controls must not interrupt active or queued requests.""" + + class GpuBusy(RuntimeError): """The model is unloaded and the GPU has less free VRAM than min_free_vram_mib: something else (a game, another model server) is using it, so the engine is not started into the little that is left.""" @@ -197,11 +201,26 @@ class StrataEngine: """ def __init__(self, exe: str, args: list[str], cwd: str | None = None, log: str | None = None, - env: dict | None = None): + env: dict | None = None, lazy: bool = False): self.spawn = (exe, list(args), cwd, log, env) # to start it again after it died (issue #27) paths = {k: v for k, v in zip(args, args[1:]) if k in ("--native", "--pack")} self.model_path = paths.get("--native") or paths.get("--pack", "pack/full") self.log_path = log + self.proc, self.pump, self.log = None, None, None + self.ended, self.unloaded = True, True + self.max_context = int(args[args.index("--max-context") + 1]) if "--max-context" in args else 4096 + self.can_stop = False # the engine honours a STOP line mid-request (READY stop) + self.last = {} + self.info = {} # INFO key=value facts (engine 0.1.8+): kv, expert slots, ... (Monitor tab) + self.prefill_tok_s_mean = None + self.progress = None # (read, total) prompt tokens while a prompt is read, from PP lines + try: # a ready-made engine's BUILD.json says its version + self.info["version"] = json.loads((Path(exe).parent / "BUILD.json").read_text()).get("version") + except (OSError, ValueError): + self.info["version"] = None + if lazy: + return + self.ended, self.unloaded = False, False self.log = open(log, "a", encoding="utf-8") if log else subprocess.DEVNULL loading = threading.Event() # set once READY: the narrator below stops if log: @@ -215,16 +234,6 @@ class StrataEngine: stderr=self.log, text=True, encoding="utf-8", bufsize=1, env=env) contain(self.proc) # ends with the server, however it ends (Windows) self.max_context = 0 - self.unloaded = False # stopped on purpose (idle unload, POST /unload), not crashed - self.can_stop = False # the engine honours a STOP line mid-request (READY stop) - self.last = {} - self.info = {} # INFO key=value facts (engine 0.1.8+): kv, expert slots, ... (Monitor tab) - self.prefill_tok_s_mean = None - self.progress = None # (read, total) prompt tokens while a prompt is read, from PP lines - try: # a ready-made engine's BUILD.json says its version - self.info["version"] = json.loads((Path(exe).parent / "BUILD.json").read_text()).get("version") - except (OSError, ValueError): - self.info["version"] = None for line in self.proc.stdout: if line.startswith("INFO "): for kv in line.split()[1:]: @@ -244,7 +253,8 @@ class StrataEngine: self.info["version"] = str(self.info["engine"]) # the engine's stdout on a thread, so a request can wait with a timeout (heartbeats, cancel checks) self.lines: queue.Queue = queue.Queue() - threading.Thread(target=self._pump, daemon=True).start() + self.pump = threading.Thread(target=self._pump, daemon=True) + self.pump.start() def _pump(self): for line in self.proc.stdout: @@ -276,39 +286,24 @@ class StrataEngine: "smaller model (Q2_0 / IQ2_XS).") def alive(self) -> bool: - return not getattr(self, "ended", False) and self.proc.poll() is None + return self.proc is not None and not getattr(self, "ended", False) and self.proc.poll() is None def exit_code(self): + if self.proc is None: + return None try: return self.proc.wait(timeout=5) except subprocess.TimeoutExpired: return None def unload(self): - """Stop the engine process so its VRAM and RAM go back to the system (idle unload, POST /unload); the next - request starts it again with restart(). Only between requests: the caller holds the service's fifo.""" - try: - try: # QUIT first, as close() does: the engine frees its memory - self.proc.stdin.write("QUIT\n") - self.proc.stdin.flush() - self.proc.wait(timeout=20) - except (OSError, ValueError, subprocess.TimeoutExpired): - self.proc.terminate() - self.proc.wait(timeout=20) - except subprocess.TimeoutExpired: - self.proc.kill() - self.proc.wait(timeout=20) - except OSError: - pass - self.ended = True + """Release GPU/RAM between requests, retaining the spawn config for automatic reloading.""" + self.close() self.unloaded = True def restart(self): """Start the engine again (the same command) after it died; the new process has its own line queue.""" - try: - self.proc.kill() - except OSError: - pass + self.close() info = dict(self.info) self.ended = False self.__init__(*self.spawn) @@ -442,12 +437,31 @@ class StrataEngine: break def close(self): + if self.proc is None: + return try: - self.proc.stdin.write("QUIT\n") - self.proc.stdin.flush() - self.proc.wait(timeout=10) - except Exception: + if self.proc.poll() is None: + self.proc.stdin.write("QUIT\n") + self.proc.stdin.flush() + self.proc.stdin.close() # Windows' detached stdin reader must see EOF before shutdown + self.proc.wait(timeout=10) + except (OSError, ValueError, subprocess.TimeoutExpired): self.proc.kill() + try: + self.proc.wait(timeout=5) + except subprocess.TimeoutExpired: + raise RuntimeError("Strata is still releasing GPU/RAM; retry unloading after it exits") from None + finally: + if self.proc.poll() is not None: + if self.pump is not None: + self.pump.join(timeout=2) + self.proc.stdin.close() + self.proc.stdout.close() + if self.log not in (None, subprocess.DEVNULL): + self.log.close() + self.proc = None + self.ended = True + self.progress, self.last = None, {} class Vision: @@ -937,6 +951,7 @@ class Service: images = self.vision is not None return { "service": "strata", "model": self.model, + "loaded": self.loaded(), "auto_load": hasattr(self.engine, "restart"), "engine": (getattr(self.engine, "info", {}) or {}).get("version"), "started": int(self.started_at), "uptime_s": int(time.time() - self.started_at), "cache_max_tokens": ctx, @@ -1633,10 +1648,10 @@ def make_handler(svc: Service): self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body) - elif path == "/health": + elif path in ("/health", "/api/health"): self._json(200, {"status": "ok", "max_context": svc.engine.max_context, "model": svc.model, "images": svc.vision is not None, "api_key": bool(svc.api_key), - "loaded": svc.loaded()}) + "loaded": svc.loaded(), "service": "strata"}) elif path == "/status": if not self._authorized(): # #212: it shows the end of the last answer return @@ -1698,6 +1713,32 @@ def make_handler(svc: Service): return try: req = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0))) or b"{}") + if not isinstance(req, dict): + raise ValueError("send a JSON object") + if path in ("/v1/load", "/v1/unload"): + if not self._own_page("the model can be loaded or unloaded"): + return + if req.get("model") not in (None, svc.model): + self._json(404, {"error": {"message": "model not found"}}) + return + if path == "/v1/unload": + result = svc.unload() + if result == "busy": + raise ModelBusy("a request is running or queued") + else: + if not svc.fifo.acquire(blocking=False): + raise ModelBusy("a request is running or queued") + try: + with svc.status_lock: + if svc.status.get("busy") or svc.status.get("queued"): + raise ModelBusy("a request is running or queued") + svc.ensure_loaded() + svc.last_request_at = time.time() + finally: + svc.fifo.release() + result = "loaded" + self._json(200, {"status": result, **svc.v1_status()}) + return if path in ("/v1/chat/completions", "/v1/messages"): svc.load() # unloaded: load first (or 503 while the GPU is busy) if path == "/v1/chat/completions": @@ -1710,10 +1751,14 @@ def make_handler(svc: Service): self._json(404, {"error": {"message": "not found"}}) except ValueError as e: self._json(400, {"error": {"type": "invalid_request_error", "message": str(e)}}) + except ModelBusy as e: + self._json(409, {"error": {"type": "model_busy", "message": str(e)}}) except GpuBusy as e: self._json(503, {"error": {"type": "server_error", "message": str(e)}}) except EngineDied as e: # before the answer started (not streamed) self._json(503, {"error": {"type": "server_error", "message": f"{e}; the next request restarts it"}}) + except RuntimeError as e: + self._json(503, {"error": {"type": "server_error", "message": str(e)}}) def _props(self): model = parse_qs(urlsplit(self.path).query).get("model", [svc.model])[0] @@ -1731,7 +1776,7 @@ def make_handler(svc: Service): params["n_predict"] = svc.shared.get("max_tokens", -1) props = {"default_generation_settings": {"n_ctx": svc.engine.max_context, "params": params}, "total_slots": 1, "model_alias": svc.model, "chat_template": svc.template.source, - "modalities": {"vision": svc.vision is not None}, "models_autoload": False, + "modalities": {"vision": svc.vision is not None}, "models_autoload": hasattr(svc.engine, "restart"), "is_sleeping": not svc.loaded()} if getattr(svc.engine, "model_path", None): props["model_path"] = svc.engine.model_path @@ -2064,6 +2109,7 @@ def main() -> int: ap.add_argument("--mcp-config", help="a JSON file with MCP servers in Claude Desktop's format ({\"mcpServers\": " "{...}}); the web app's chat can use their tools (also \"mcp_servers\" in " "the config)") + ap.add_argument("--lazy", action="store_true", help="start the text-only API unloaded; load on first request") ap.add_argument("--idle-unload", type=float, default=None, metavar="SECONDS", help="unload the model after this many seconds without requests, so other programs (games, other " "model servers) can use the VRAM; the next request loads it again (also \"idle_unload_s\" " @@ -2108,6 +2154,9 @@ def main() -> int: if sampling_defaults: pretty = ", ".join(f"{k}={v}" for k, v in sampling_defaults.items()) print(f"[strata] sampling defaults from the config: {pretty}", flush=True) + lazy = a.lazy or cfg.get("lazy_load") is True + if lazy and cfg.get("vision"): + ap.error("lazy loading is text-only; disable vision in the config") if cfg.get("vision"): print("loading the vision encoder ...", flush=True) # relative paths are the config's cwd's, as for the engine below @@ -2115,13 +2164,14 @@ def main() -> int: 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()} vision = Vision(vcfg, log=open(cfg["log"], "a", encoding="utf-8") if cfg.get("log") else None, env=env) - print("loading the model (the first start takes a minute or two) ...", flush=True) + print("model unloaded; the first request loads it ..." if lazy else + "loading the model (the first start takes a minute or two) ...", flush=True) if len(gpu_list(cfg)) > 1: print(f"[strata] layer split across GPUs {gpu_list(cfg)} ({cfg.get('layer_split') or 'auto'})", flush=True) # a relative "exe" is the config's cwd's: Windows' CreateProcess resolves "engine/strata.exe" against nothing # it is told about (WinError 2), so it is made absolute here exe = cfg["exe"] if os.path.isabs(cfg["exe"]) else os.path.abspath(os.path.join(cfg.get("cwd") or ".", cfg["exe"])) - engine = StrataEngine(exe, engine_args(cfg), cwd=cfg.get("cwd"), log=cfg.get("log"), env=env) + engine = StrataEngine(exe, engine_args(cfg), cwd=cfg.get("cwd"), log=cfg.get("log"), env=env, lazy=lazy) warn_tight_ram(engine.info.get("arena_mib")) else: engine, vision, sampling_defaults = MockEngine(tok, a.script or [ diff --git a/serve/test_lifecycle.py b/serve/test_lifecycle.py new file mode 100644 index 00000000..6e54fd8f --- /dev/null +++ b/serve/test_lifecycle.py @@ -0,0 +1,147 @@ +"""Model discovery, on-demand loading and safe unloading over the actual HTTP API.""" +import json +import io +import subprocess +import time +import unittest +import urllib.error +import urllib.request +from pathlib import Path +from unittest import mock + +from serve.frontend import ChatTemplate +from serve.server import ByteTokenizer, MockEngine, Service, StrataEngine, serve + + +class ResidentEngine(StrataEngine): + def __init__(self, tok): + self.reply = MockEngine(tok, "Hello.", max_context=4096) + self.max_context, self.info, self.last = 4096, {}, {} + self.loaded, self.starts, self.closes = False, 0, 0 + self.unloaded = True + self.progress = None + + def alive(self): + return self.loaded + + def exit_code(self): + return None + + def restart(self): + self.loaded = True + self.starts += 1 + self.unloaded = False + + def close(self): + self.loaded = False + self.closes += 1 + + def unload(self): + self.close() + self.unloaded = True + + def generate(self, *args, **kwargs): + yield from self.reply.generate(*args, **kwargs) + + +class Lifecycle(unittest.TestCase): + def test_close_sends_eof_before_waiting_for_windows_reader(self): + engine = StrataEngine("missing-executable", [], lazy=True) + proc = mock.Mock() + proc.stdin, proc.stdout = io.StringIO(), io.StringIO() + proc.poll.side_effect = [None, 0] + proc.wait.side_effect = lambda **kwargs: self.assertTrue(proc.stdin.closed) + engine.proc = proc + engine.close() + self.assertIsNone(engine.proc) + proc.kill.assert_not_called() + + def test_close_does_not_forget_a_process_still_exiting(self): + engine = StrataEngine("missing-executable", [], lazy=True) + proc = mock.Mock() + proc.stdin, proc.stdout = io.StringIO(), io.StringIO() + proc.poll.return_value = None + proc.wait.side_effect = subprocess.TimeoutExpired("engine", 2) + engine.proc = proc + with self.assertRaisesRegex(RuntimeError, "still releasing"): + engine.close() + self.assertIs(engine.proc, proc) + proc.kill.assert_called_once() + + def test_native_lazy_constructor_does_not_start_a_process(self): + engine = StrataEngine("missing-executable", ["--max-context", "16384"], lazy=True) + self.assertFalse(engine.alive()) + self.assertEqual(engine.max_context, 16384) + self.assertIsNone(engine.exit_code()) + engine.close() + + def setUp(self): + tok = ByteTokenizer() + self.engine = ResidentEngine(tok) + self.svc = Service(self.engine, tok, ChatTemplate(Path(__file__).parent / "chat_template.jinja")) + self.httpd = serve(self.svc, port=0) + self.base = f"http://127.0.0.1:{self.httpd.server_address[1]}" + + def tearDown(self): + self.httpd.shutdown() + self.httpd.server_close() + + def request(self, path, body=None, headers=None): + req = urllib.request.Request(self.base + path, data=json.dumps(body).encode() if body is not None else None, + headers={"Content-Type": "application/json", **(headers or {})}) + try: + response = urllib.request.urlopen(req, timeout=10) + except urllib.error.HTTPError as error: + response = error + with response: + data = response.read().decode() + return response.status, data if "event-stream" in response.headers.get("Content-Type", "") else json.loads(data) + + def test_discover_chat_unload_and_stream_reload(self): + self.assertEqual(self.request("/api/health")[1]["service"], "strata") + self.assertFalse(self.request("/v1/status")[1]["loaded"]) + self.assertEqual(self.request("/v1/models")[1]["data"][0]["status"]["value"], "unloaded") + self.assertTrue(self.request("/props")[1]["models_autoload"]) + self.assertEqual(self.engine.starts, 0) + chat = {"messages": [{"role": "user", "content": "Hello"}], "max_tokens": 32, "reasoning_effort": "none"} + for _ in range(2): + code, answer = self.request("/v1/chat/completions", chat) + self.assertEqual(code, 200) + self.assertEqual(answer["choices"][0]["message"]["content"], "Hello.") + self.assertEqual(self.engine.starts, 1) + self.assertFalse(self.request("/v1/unload", {})[1]["loaded"]) + code, stream = self.request("/v1/chat/completions", {**chat, "stream": True}) + self.assertEqual(code, 200) + self.assertIn("data: [DONE]", stream) + self.assertEqual(self.engine.starts, 2) + + def test_busy_auth_and_foreign_origin_cannot_unload(self): + self.engine.loaded = True + with self.svc.fifo: + self.assertEqual(self.request("/v1/unload", {})[0], 409) + self.svc.api_key = "local-secret" + self.assertEqual(self.request("/v1/unload", {})[0], 401) + self.assertEqual(self.request("/v1/unload", {}, {"Authorization": "Bearer local-secret", + "Origin": "https://other.example"})[0], 403) + self.assertEqual(self.engine.closes, 0) + self.assertTrue(self.engine.loaded) + self.assertEqual(self.request("/v1/unload", {}, {"Authorization": "Bearer local-secret"})[0], 200) + + def test_explicit_load_and_model_matching(self): + self.assertEqual(self.request("/v1/load", {"model": "other-model"})[0], 404) + self.assertEqual(self.engine.starts, 0) + before = time.time() + code, status = self.request("/v1/load", {"model": self.svc.model}) + self.assertEqual(code, 200) + self.assertTrue(status["loaded"]) + self.assertEqual(self.engine.starts, 1) + self.assertGreaterEqual(self.svc.last_request_at, before) + self.svc.status["queued"] = 1 + self.assertEqual(self.request("/v1/load", {})[0], 409) + self.assertEqual(self.request("/v1/unload", {})[0], 409) + self.assertEqual(self.engine.closes, 0) + self.assertEqual(self.request("/v1/load", {}, {"Content-Type": "text/plain"})[0], 415) + + +if __name__ == "__main__": + unittest.main() From bd9a1bc1267356a8a3bcbb489f6f7cf701e99418 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Thu, 1 Oct 2026 08:26:28 +0200 Subject: [PATCH 18/48] #333 follow-up: the unload keeps its terminate/kill fallback; EngineStuck instead of a catch-all RuntimeError - StrataEngine.close() (now also the unload and the restart): QUIT and EOF, then terminate, then kill, each with 20 s as the unload had (#333 went from QUIT straight to kill after 10 s; an engine unpinning tens of GB can need more). A process that outlives all three raises EngineStuck and stays owned. - do_POST caught every RuntimeError as a 503 - EngineDied, GpuBusy and ModelBusy are RuntimeErrors too, and any other failure was turned into a vague 503. Only EngineStuck is caught now (also around POST /unload, and the idle-unload thread survives it); EngineDied keeps its own answer. - test_lifecycle: terminate before kill, EngineStuck, an EngineDied on load answered as such. --- serve/server.py | 40 ++++++++++++++++++++++++++++++---------- serve/test_lifecycle.py | 27 +++++++++++++++++++++++++-- 2 files changed, 55 insertions(+), 12 deletions(-) diff --git a/serve/server.py b/serve/server.py index 32ef0648..e86e27a6 100644 --- a/serve/server.py +++ b/serve/server.py @@ -104,6 +104,11 @@ class ModelBusy(RuntimeError): """Explicit model controls must not interrupt active or queued requests.""" +class EngineStuck(RuntimeError): + """The engine process did not end after QUIT, terminate and kill: the server keeps it (and says so) rather than + reporting its GPU and RAM as given back.""" + + class GpuBusy(RuntimeError): """The model is unloaded and the GPU has less free VRAM than min_free_vram_mib: something else (a game, another model server) is using it, so the engine is not started into the little that is left.""" @@ -437,20 +442,28 @@ class StrataEngine: break def close(self): + """End the engine process: QUIT first (the engine frees its memory itself - unpinning tens of GB can take + a while), then terminate, then kill, each given 20 s. Raises EngineStuck when it still runs after all three.""" if self.proc is None: return try: if self.proc.poll() is None: - self.proc.stdin.write("QUIT\n") - self.proc.stdin.flush() - self.proc.stdin.close() # Windows' detached stdin reader must see EOF before shutdown - self.proc.wait(timeout=10) - except (OSError, ValueError, subprocess.TimeoutExpired): + try: + self.proc.stdin.write("QUIT\n") + self.proc.stdin.flush() + self.proc.stdin.close() # Windows' detached stdin reader must see EOF before shutdown + self.proc.wait(timeout=20) + except (OSError, ValueError, subprocess.TimeoutExpired): + self.proc.terminate() + self.proc.wait(timeout=20) + except subprocess.TimeoutExpired: self.proc.kill() try: - self.proc.wait(timeout=5) + self.proc.wait(timeout=20) except subprocess.TimeoutExpired: - raise RuntimeError("Strata is still releasing GPU/RAM; retry unloading after it exits") from None + raise EngineStuck("Strata is still releasing GPU/RAM; retry unloading after it exits") from None + except OSError: + pass finally: if self.proc.poll() is not None: if self.pump is not None: @@ -823,7 +836,10 @@ class Service: def loop(): while True: time.sleep(max(1.0, min(30.0, self.idle_unload_s / 4))) - self.unload(idle_for=self.idle_unload_s) + try: + self.unload(idle_for=self.idle_unload_s) + except EngineStuck as e: # tried again at the next turn; the thread keeps running + print(f"[strata] idle unload: {e}", flush=True) threading.Thread(target=loop, daemon=True).start() def set_shared(self, defaults) -> dict: @@ -1701,7 +1717,11 @@ def make_handler(svc: Service): self._settings() return if path == "/unload": # give the GPU back now (between requests) - r = svc.unload() + try: + r = svc.unload() + except EngineStuck as e: + self._json(503, {"error": {"type": "server_error", "message": str(e)}}) + return self._json(409 if r == "busy" else 200, {"status": r}) return if path == "/load": # load now, e.g. ahead of a request @@ -1757,7 +1777,7 @@ def make_handler(svc: Service): self._json(503, {"error": {"type": "server_error", "message": str(e)}}) except EngineDied as e: # before the answer started (not streamed) self._json(503, {"error": {"type": "server_error", "message": f"{e}; the next request restarts it"}}) - except RuntimeError as e: + except EngineStuck as e: # an unload or restart that could not end the engine self._json(503, {"error": {"type": "server_error", "message": str(e)}}) def _props(self): diff --git a/serve/test_lifecycle.py b/serve/test_lifecycle.py index 6e54fd8f..1d9f58c4 100644 --- a/serve/test_lifecycle.py +++ b/serve/test_lifecycle.py @@ -10,7 +10,7 @@ from pathlib import Path from unittest import mock from serve.frontend import ChatTemplate -from serve.server import ByteTokenizer, MockEngine, Service, StrataEngine, serve +from serve.server import ByteTokenizer, EngineDied, EngineStuck, MockEngine, Service, StrataEngine, serve class ResidentEngine(StrataEngine): @@ -63,11 +63,25 @@ class Lifecycle(unittest.TestCase): proc.poll.return_value = None proc.wait.side_effect = subprocess.TimeoutExpired("engine", 2) engine.proc = proc - with self.assertRaisesRegex(RuntimeError, "still releasing"): + with self.assertRaisesRegex(EngineStuck, "still releasing"): engine.close() self.assertIs(engine.proc, proc) + proc.terminate.assert_called_once() proc.kill.assert_called_once() + def test_close_terminates_before_it_kills(self): + # an engine that does not end on QUIT is terminated first (as the unload always did); kill is the last resort + engine = StrataEngine("missing-executable", [], lazy=True) + proc = mock.Mock() + proc.stdin, proc.stdout = io.StringIO(), io.StringIO() + proc.poll.side_effect = [None, 0] + proc.wait.side_effect = [subprocess.TimeoutExpired("engine", 20), 0] + engine.proc = proc + engine.close() + proc.terminate.assert_called_once() + proc.kill.assert_not_called() + self.assertIsNone(engine.proc) + def test_native_lazy_constructor_does_not_start_a_process(self): engine = StrataEngine("missing-executable", ["--max-context", "16384"], lazy=True) self.assertFalse(engine.alive()) @@ -127,6 +141,15 @@ class Lifecycle(unittest.TestCase): self.assertTrue(self.engine.loaded) self.assertEqual(self.request("/v1/unload", {}, {"Authorization": "Bearer local-secret"})[0], 200) + def test_an_engine_that_died_on_load_is_reported_as_such(self): + # EngineDied is a RuntimeError: it keeps its own answer ("the next request restarts it") + def died(): + raise EngineDied("the engine ended while it started") + self.engine.restart = died + code, body = self.request("/v1/chat/completions", {"messages": [{"role": "user", "content": "Hello"}]}) + self.assertEqual(code, 503) + self.assertIn("the next request restarts it", body["error"]["message"]) + def test_explicit_load_and_model_matching(self): self.assertEqual(self.request("/v1/load", {"model": "other-model"})[0], 404) self.assertEqual(self.engine.starts, 0) From c87a9cb0ce6aa935527c8a767cfc8d0f60117483 Mon Sep 17 00:00:00 2001 From: Ricardo Ambrogi <11719845+KadoBOT@users.noreply.github.com> Date: Thu, 1 Oct 2026 04:47:33 +0200 Subject: [PATCH 19/48] serve: validate JSON response formats before delivery --- docs/DETAILS.md | 19 ++++++ serve/server.py | 42 +++++++++++- serve/structured.py | 105 +++++++++++++++++++++++++++++ serve/test_structured.py | 138 +++++++++++++++++++++++++++++++++++++++ 4 files changed, 302 insertions(+), 2 deletions(-) create mode 100644 serve/structured.py create mode 100644 serve/test_structured.py diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 3619c9d7..76dc4f9a 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -795,3 +795,22 @@ and **404** for an unknown model. Existing `/load` and `/unload` behavior is pre Unloading and shutdown close the native engine's stdin after sending `QUIT`, allowing Windows' detached stdin reader to see EOF. Cleanup waits for process exit before releasing handles; if forced shutdown still times out, the server keeps ownership and reports an error rather than claiming the model was unloaded. + +### JSON response formats + +`POST /v1/chat/completions` accepts `response_format: {"type":"json_object"}` or +`{"type":"json_schema","json_schema":{"name":"answer","strict":true,"schema":{"type":"object","properties":{"answer":{"type":"integer"}},"required":["answer"],"additionalProperties":false}}}`. +The schema must describe an object at its root. Local `#` references work; remote references are refused. +`json_schema` is checked with the Python package `jsonschema` when it is installed (`python -m pip install +"jsonschema>=4.23,<5"`; setup does not add it); without it the answer is only checked to be one JSON object, and the +server says so once. + +This is **schema prompting followed by server validation**, not grammar-constrained decoding. One generation +is made per request, with no hidden retry. Successful responses contain a validated JSON object. Malformed JSON, +duplicate keys, non-finite numbers, schema violations and incomplete generations return **502** with +`error.code: structured_output_failed`; invalid request schemas return **400**. JSON formats combined with +tools/MCP are refused explicitly. Without `response_format`, ordinary text and tool behavior stays the same. + +Structured SSE buffers the answer while sending keep-alive comments. It emits content only after validation, +then usage/timings and `[DONE]`; failures emit an SSE error and `[DONE]` without invalid content deltas. +`/v1/status.structured_output` advertises the formats, validation method and buffered streaming behavior. diff --git a/serve/server.py b/serve/server.py index e86e27a6..6638d442 100644 --- a/serve/server.py +++ b/serve/server.py @@ -51,6 +51,7 @@ from serve.frontend import (ChatTemplate, Event, OutputParser, anthropic_to_mess images_of, openai_to_messages) from serve.mcp import McpCancelled, hub_from_config # noqa: E402 from serve.winjob import contain # noqa: E402 +from serve.structured import StructuredOutputError, prepare_format, validated_json # noqa: E402 IM_END = "<|im_end|>" IMAGE_PAD = "<|image_pad|>" @@ -968,6 +969,8 @@ class Service: return { "service": "strata", "model": self.model, "loaded": self.loaded(), "auto_load": hasattr(self.engine, "restart"), + "structured_output": {"formats": ["json_object", "json_schema"], "method": "prompt_and_validate", + "constrained_decoding": False, "stream_buffered": True}, "engine": (getattr(self.engine, "info", {}) or {}).get("version"), "started": int(self.started_at), "uptime_s": int(time.time() - self.started_at), "cache_max_tokens": ctx, @@ -1455,6 +1458,30 @@ def openai_collect(chunks) -> dict: return out +def structured_chunks(chunks, validator): + """Buffer structured streams so a client never receives unvalidated content.""" + buffered = [] + heartbeat = time.monotonic() + try: + for chunk in chunks: + if chunk is not None: + buffered.append(chunk) + if chunk is None or time.monotonic() - heartbeat >= 1: + heartbeat = time.monotonic() + yield None + result = openai_collect(buffered) + choice = result["choices"][0] + content = validated_json(choice["message"]["content"], validator, choice["finish_reason"]) + yield buffered[0] + delta = {"content": content} + if choice["message"].get("reasoning_content"): + delta["reasoning_content"] = choice["message"]["reasoning_content"] + yield {**buffered[0], "choices": [{"index": 0, "delta": delta, "finish_reason": None}]} + yield buffered[-1] + finally: + chunks.close() + + # ------------------------------------------------------------------------------------------------ Anthropic def anthropic_events(svc: Service, req: dict, ids, thinking, tools, max_new, cancel): mid = "msg_" + uuid.uuid4().hex[:24] @@ -1759,8 +1786,6 @@ def make_handler(svc: Service): result = "loaded" self._json(200, {"status": result, **svc.v1_status()}) return - if path in ("/v1/chat/completions", "/v1/messages"): - svc.load() # unloaded: load first (or 503 while the GPU is busy) if path == "/v1/chat/completions": self._openai(req) elif path == "/v1/messages": @@ -1773,6 +1798,9 @@ def make_handler(svc: Service): self._json(400, {"error": {"type": "invalid_request_error", "message": str(e)}}) except ModelBusy as e: self._json(409, {"error": {"type": "model_busy", "message": str(e)}}) + except StructuredOutputError as e: + self._json(502, {"error": {"type": "structured_output_failed", "code": "structured_output_failed", + "message": str(e)}}) except GpuBusy as e: self._json(503, {"error": {"type": "server_error", "message": str(e)}}) except EngineDied as e: # before the answer started (not streamed) @@ -1848,6 +1876,10 @@ def make_handler(svc: Service): def _openai(self, req): req = svc.with_shared(req, "openai") messages, tools, kw = openai_to_messages(req) + messages, validator = prepare_format(req.get("response_format"), messages) + if validator is not None and (tools or req.get("strata_mcp")): + raise ValueError("structured response_format with tools/MCP is not supported") + svc.load() max_req = max_new = int(req.get("max_completion_tokens") or req.get("max_tokens") or 0) # 0/-1: the rest use_mcp = req.get("strata_mcp") is True and svc.mcp is not None # the web app's opt-in (serve/mcp.py) own = {t.get("name") for t in tools or []} @@ -1865,6 +1897,8 @@ def make_handler(svc: Service): 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) + if validator is not None: + chunks = structured_chunks(chunks, validator) if not req.get("stream"): return self._json(200, openai_collect(chunks)) self._sse() @@ -1882,6 +1916,9 @@ def make_handler(svc: Service): except EngineDied as e: # mid-stream: say so, then end the stream properly err = {"error": {"type": "server_error", "message": f"{e}; the next request restarts it"}} self.wfile.write(b"data: " + json.dumps(err).encode() + b"\n\ndata: [DONE]\n\n") + except StructuredOutputError as e: + err = {"error": {"type": "structured_output_failed", "code": "structured_output_failed", "message": str(e)}} + self.wfile.write(b"data: " + json.dumps(err).encode() + b"\n\ndata: [DONE]\n\n") except ValueError as e: # the engine's ERR after the stream started: the err = {"error": {"type": "server_error", "message": str(e)}} # headers are sent, so no 400 now self.wfile.write(b"data: " + json.dumps(err).encode() + b"\n\ndata: [DONE]\n\n") @@ -1895,6 +1932,7 @@ def make_handler(svc: Service): self._json(200, {"input_tokens": len(svc.tok.encode(prompt, parse_special=True))}) def _anthropic(self, req): + svc.load() req = svc.with_shared(req, "anthropic") messages, tools, kw = anthropic_to_messages(req) max_new = int(req.get("max_tokens") or 0) # 0/-1: the rest of the context diff --git a/serve/structured.py b/serve/structured.py new file mode 100644 index 00000000..bc9ad786 --- /dev/null +++ b/serve/structured.py @@ -0,0 +1,105 @@ +"""JSON response formats at the HTTP boundary: prompt once, validate before delivery. + +The native engine has no grammar decoder. Failed generations are errors, never +silently retried or returned as successful structured output. +""" +import json + +from jsonschema import validators +from jsonschema.exceptions import SchemaError +from referencing import Registry +from referencing.exceptions import NoSuchResource + + +class StructuredOutputError(RuntimeError): + pass + + +def _no_remote(uri): + raise NoSuchResource(ref=uri) + + +def prepare_format(response_format, messages): + if response_format is None: + return messages, None + if not isinstance(response_format, dict): + raise ValueError("response_format must be an object") + kind = response_format.get("type") + if kind == "text": + return messages, None + if kind == "json_object": + schema = {"type": "object"} + elif kind == "json_schema": + spec = response_format.get("json_schema") + if not isinstance(spec, dict) or not isinstance(spec.get("schema"), dict): + raise ValueError("response_format.json_schema needs a schema object") + if not isinstance(spec.get("name"), str) or not spec["name"]: + raise ValueError("response_format.json_schema needs a name") + if "strict" in spec and not isinstance(spec["strict"], bool): + raise ValueError("response_format.json_schema.strict must be boolean") + schema = spec["schema"] + if schema.get("type") != "object": + raise ValueError("response_format schema must have type object at its root") + else: + raise ValueError("response_format.type must be text, json_object or json_schema") + + def check_refs(node): + if isinstance(node, dict): + for key, value in node.items(): + if key in ("$ref", "$dynamicRef") and isinstance(value, str) and not value.startswith("#"): + raise ValueError("response_format supports only local schema references (#...)") + check_refs(value) + elif isinstance(node, list): + for value in node: + check_refs(value) + check_refs(schema) + try: + cls = validators.validator_for(schema) + cls.check_schema(schema) + validator = cls(schema, registry=Registry(retrieve=_no_remote)) + except SchemaError as exc: + raise ValueError(f"invalid response_format schema: {exc.message}") from exc + directive = ("OUTPUT FORMAT REQUIREMENT: Return exactly one JSON object matching the JSON Schema below. " + "No Markdown, headings, code fences, commentary, or text outside the JSON. " + "Use every required field, correct types, and only allowed fields. " + "Put all requested writing inside the appropriate JSON string fields.\nJSON Schema:\n" + + json.dumps(schema, ensure_ascii=False, allow_nan=False, separators=(",", ":"))) + messages = [dict(message) for message in messages] + if messages and messages[0].get("role") == "system": + content = messages[0].get("content") or "" + if isinstance(content, list): + messages[0]["content"] = content + [{"type": "text", "text": directive}] + else: + messages[0]["content"] = content + "\n\n" + directive + else: + messages.insert(0, {"role": "system", "content": directive}) + return messages, validator + + +def validated_json(text, validator, finish): + def pairs(items): + obj = {} + for key, value in items: + if key in obj: + raise ValueError(f"duplicate JSON key: {key}") + obj[key] = value + return obj + + def constant(value): + raise ValueError(f"invalid JSON constant: {value}") + + if finish != "stop": + raise StructuredOutputError(f"structured output was incomplete (finish_reason={finish}); increase the output budget") + try: + value = json.loads(text or "", object_pairs_hook=pairs, parse_constant=constant) + canonical = json.dumps(value, ensure_ascii=False, allow_nan=False, separators=(",", ":")) + except (ValueError, TypeError) as exc: + raise StructuredOutputError(f"model did not return valid JSON: {exc}") from exc + try: + error = next(validator.iter_errors(value), None) + except Exception as exc: + raise StructuredOutputError(f"could not validate structured output: {exc}") from exc + if error is not None: + path = "/" + "/".join(str(part) for part in error.absolute_path) + raise StructuredOutputError(f"model output failed the JSON Schema at {path}: {error.message}") + return canonical diff --git a/serve/test_structured.py b/serve/test_structured.py new file mode 100644 index 00000000..644a4b4e --- /dev/null +++ b/serve/test_structured.py @@ -0,0 +1,138 @@ +"""Exercise the JSON contract through HTTP, including H3's strict Story shape.""" +import json +import unittest +import urllib.error +import urllib.request +from pathlib import Path +from unittest import mock + +from serve.frontend import ChatTemplate +from serve.server import ByteTokenizer, MockEngine, Service, serve + + +STORY = {"title": "Photobooth", "sheet": "A single continuous shot.", "cast": [], + "boxes": [{"box": 1, "duration_ms": 15000, "new_shot": True, "beat": "Hailee changes poses.", + "on_screen": ["Hailee"], "references": [], "ends": "She smiles."}], "suggestions": []} + + +def object_schema(properties): + return {"type": "object", "properties": properties, "required": list(properties), "additionalProperties": False} + + +TEXT = {"type": "string"} +STORY_SCHEMA = object_schema({ + "title": TEXT, "sheet": TEXT, "cast": {"type": "array", "items": object_schema({"name": TEXT, + "references": {"type": "array", "items": TEXT, "maxItems": 0}})}, + "boxes": {"type": "array", "minItems": 1, "maxItems": 1, "items": object_schema({ + "box": {"type": "integer", "minimum": 1, "maximum": 1}, + "duration_ms": {"type": "integer", "minimum": 1, "maximum": 15000}, "new_shot": {"type": "boolean"}, + "beat": TEXT, "on_screen": {"type": "array", "items": TEXT}, + "references": {"type": "array", "items": TEXT, "maxItems": 0}, "ends": TEXT})}, + "suggestions": {"type": "array", "items": object_schema({"what": TEXT, "why": TEXT, + "boxes": {"type": "array", "items": {"type": "integer"}}, "description": TEXT})}}) +FORMAT = {"type": "json_schema", "json_schema": {"name": "h3_story", "strict": True, "schema": STORY_SCHEMA}} + + +class Structured(unittest.TestCase): + def request(self, path, body=None, headers=None): + req = urllib.request.Request(self.base + path, data=json.dumps(body).encode() if body is not None else None, + headers={"Content-Type": "application/json", **(headers or {})}) + try: + response = urllib.request.urlopen(req, timeout=10) + except urllib.error.HTTPError as error: + response = error + with response: + data = response.read().decode() + return response.status, data if "event-stream" in response.headers.get("Content-Type", "") else json.loads(data) + + def setUp(self): + self.tok = ByteTokenizer() + self.engine = MockEngine(self.tok, json.dumps(STORY), max_context=16384) + self.svc = Service(self.engine, self.tok, ChatTemplate(Path(__file__).parent / "chat_template.jinja")) + self.httpd = serve(self.svc, port=0) + self.base = f"http://127.0.0.1:{self.httpd.server_address[1]}" + + def tearDown(self): + self.httpd.shutdown() + self.httpd.server_close() + + def chat(self, script=None, **kwargs): + if script is not None: + self.engine = self.svc.engine = MockEngine(self.tok, script, max_context=16384) + req = {"messages": [{"role": "system", "content": "Write a film plan."}, + {"role": "user", "content": "Photobooth. 15 seconds."}], + "response_format": FORMAT, "reasoning_effort": "none", **kwargs} + return self.request("/v1/chat/completions", req) + + def test_h3_schema_success_and_stream_with_reasoning(self): + code, reply = self.chat() + self.assertEqual(code, 200) + self.assertEqual(json.loads(reply["choices"][0]["message"]["content"]), STORY) + prompt = self.tok.decode(self.engine.last_prompt) + self.assertIn("OUTPUT FORMAT REQUIREMENT", prompt) + self.assertIn('"duration_ms"', prompt) + code, raw = self.chat("Consider the shot.\n" + json.dumps(STORY), stream=True, reasoning_effort="low") + self.assertEqual(code, 200) + chunks = [json.loads(line[6:]) for line in raw.splitlines() if line.startswith("data: {")] + content = "".join(c["choices"][0]["delta"].get("content", "") for c in chunks) + self.assertEqual(json.loads(content), STORY) + self.assertIn("reasoning_content", raw) + self.assertIn("data: [DONE]", raw) + + def test_invalid_generation_is_an_error_and_never_streams_content(self): + for script in ("## Film Plan - Photobooth", '{"title":"Only a title"}', + json.dumps({**STORY, "extra": True}), + json.dumps({**STORY, "boxes": [{**STORY["boxes"][0], "duration_ms": "15000"}]})): + with self.subTest(script=script): + code, reply = self.chat(script) + self.assertEqual(code, 502) + self.assertEqual(reply["error"]["code"], "structured_output_failed") + _, raw = self.chat(script, stream=True) + self.assertIn('"structured_output_failed"', raw) + self.assertNotIn('"delta"', raw) + self.assertIn("data: [DONE]", raw) + + def test_object_mode_strict_json_and_truncation(self): + fmt = {"type": "json_object"} + self.assertEqual(self.chat('{"answer":4}', response_format=fmt)[0], 200) + for script in ('[]', '{"x":NaN}', '{"x":1,"x":2}', '{"x":1e999}', '```json\n{}\n```'): + self.assertEqual(self.chat(script, response_format=fmt)[0], 502) + self.assertEqual(self.chat('{"answer":4}', response_format=fmt, max_tokens=5)[0], 502) + # Plain text callers retain normal streaming, without a JSON validation gate. + self.assertEqual(self.chat("Prose.", response_format={"type": "text"})[0], 200) + + def test_rejected_schema_does_not_load_the_engine_or_retry(self): + with mock.patch.object(self.svc, "load") as load: + code, _ = self.chat(response_format={"type": "json_schema"}) + self.assertEqual(code, 400) + load.assert_not_called() + self.engine = self.svc.engine = MockEngine(self.tok, "Markdown is not JSON", max_context=16384) + with mock.patch.object(self.engine, "generate", wraps=self.engine.generate) as generate: + self.assertEqual(self.chat()[0], 502) + self.assertEqual(generate.call_count, 1) + + def test_invalid_schema_is_400_and_local_refs_work(self): + for schema in ({"type": "object", "properties": {"x": {"type": "invalid"}}}, + {"type": "object", "$ref": "https://other.example/schema"}): + fmt = {"type": "json_schema", "json_schema": {"name": "test", "strict": True, "schema": schema}} + self.assertEqual(self.chat(response_format=fmt)[0], 400) + schema = object_schema({"answer": {"$ref": "#/$defs/n"}}) + schema["$defs"] = {"n": {"type": "integer"}} + fmt = {"type": "json_schema", "json_schema": {"name": "local", "schema": schema}} + self.assertEqual(self.chat('{"answer":4}', response_format=fmt)[0], 200) + + def test_malformed_formats_and_tools_are_rejected_before_loading(self): + formats = ([], {"type": "unsupported"}, + {"type": "json_schema", "json_schema": {"schema": {"type": "object"}}}, + {"type": "json_schema", "json_schema": {"name": "x", "strict": "true", "schema": {"type": "object"}}}) + with mock.patch.object(self.svc, "load") as load: + for fmt in formats: + with self.subTest(fmt=fmt): + self.assertEqual(self.chat(response_format=fmt)[0], 400) + self.assertEqual(self.chat(tools=[{"type": "function", "function": {"name": "search", "parameters": {"type": "object"}}}])[0], 400) + self.assertEqual(self.chat(strata_mcp=True)[0], 400) + self.assertEqual(self.request("/v1/chat/completions", [])[0], 400) + load.assert_not_called() + +if __name__ == "__main__": + unittest.main() From d3bf912ea068738ded56f0958cdf62274e34c129 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Thu, 1 Oct 2026 08:27:57 +0200 Subject: [PATCH 20/48] #334 follow-up: jsonschema is an optional, lazily imported package (no new hard dependency) - The rebase keeps 0.1.31's requirements.txt install in setup.py and the Dockerfile: jsonschema is not added. - serve/structured.py imports jsonschema on the first json_schema request, not at server start (a server without it started fine before #334 and still does). json_object never needs it; json_schema without it is checked to be one JSON object, and the server window says once how to get full schema validation. - test_structured: the two schema-violation tests skip without jsonschema; new tests for the object-only fallback and for "import serve.server" not importing jsonschema. docs/DETAILS.md says it is optional. --- serve/structured.py | 68 ++++++++++++++++++++++++++++++++-------- serve/test_structured.py | 29 +++++++++++++++++ 2 files changed, 84 insertions(+), 13 deletions(-) diff --git a/serve/structured.py b/serve/structured.py index bc9ad786..b5f079cc 100644 --- a/serve/structured.py +++ b/serve/structured.py @@ -2,21 +2,53 @@ The native engine has no grammar decoder. Failed generations are errors, never silently retried or returned as successful structured output. + +`jsonschema` is optional (no new hard dependency of the server): json_object needs only the standard library, and +json_schema is checked against its schema when the package is installed - without it, only that the answer is one +JSON object, and the server says so once. """ import json - -from jsonschema import validators -from jsonschema.exceptions import SchemaError -from referencing import Registry -from referencing.exceptions import NoSuchResource +import threading class StructuredOutputError(RuntimeError): pass -def _no_remote(uri): - raise NoSuchResource(ref=uri) +class _ObjectOnly: + """The validator for json_object, and for json_schema without jsonschema: one JSON object.""" + + def iter_errors(self, value): + if not isinstance(value, dict): + yield _ObjectError() + + +class _ObjectError: + absolute_path = () + message = "the answer is not a JSON object" + + +_jsonschema = None # (validators, SchemaError, Registry, NoSuchResource), False when not installed +_jsonschema_lock = threading.Lock() + + +def jsonschema_modules(): + """jsonschema, imported on first use; None when it is not installed (said once, in the server window).""" + global _jsonschema + with _jsonschema_lock: + if _jsonschema is None: + try: + from jsonschema import validators + from jsonschema.exceptions import SchemaError + from referencing import Registry + from referencing.exceptions import NoSuchResource + _jsonschema = (validators, SchemaError, Registry, NoSuchResource) + except ImportError: + _jsonschema = False + print('[strata] response_format json_schema: the Python package jsonschema is not installed, so ' + 'answers are only checked to be one JSON object (python -m pip install "jsonschema>=4.23,<5")', + flush=True) + return _jsonschema or None def prepare_format(response_format, messages): @@ -29,6 +61,7 @@ def prepare_format(response_format, messages): return messages, None if kind == "json_object": schema = {"type": "object"} + modules = None # the standard library is enough for "one JSON object" elif kind == "json_schema": spec = response_format.get("json_schema") if not isinstance(spec, dict) or not isinstance(spec.get("schema"), dict): @@ -40,6 +73,7 @@ def prepare_format(response_format, messages): schema = spec["schema"] if schema.get("type") != "object": raise ValueError("response_format schema must have type object at its root") + modules = jsonschema_modules() else: raise ValueError("response_format.type must be text, json_object or json_schema") @@ -53,12 +87,20 @@ def prepare_format(response_format, messages): for value in node: check_refs(value) check_refs(schema) - try: - cls = validators.validator_for(schema) - cls.check_schema(schema) - validator = cls(schema, registry=Registry(retrieve=_no_remote)) - except SchemaError as exc: - raise ValueError(f"invalid response_format schema: {exc.message}") from exc + if modules is None: + validator = _ObjectOnly() + else: + validators, SchemaError, Registry, NoSuchResource = modules + + def no_remote(uri): + raise NoSuchResource(ref=uri) + + try: + cls = validators.validator_for(schema) + cls.check_schema(schema) + validator = cls(schema, registry=Registry(retrieve=no_remote)) + except SchemaError as exc: + raise ValueError(f"invalid response_format schema: {exc.message}") from exc directive = ("OUTPUT FORMAT REQUIREMENT: Return exactly one JSON object matching the JSON Schema below. " "No Markdown, headings, code fences, commentary, or text outside the JSON. " "Use every required field, correct types, and only allowed fields. " diff --git a/serve/test_structured.py b/serve/test_structured.py index 644a4b4e..cc157a76 100644 --- a/serve/test_structured.py +++ b/serve/test_structured.py @@ -7,8 +7,15 @@ from pathlib import Path from unittest import mock from serve.frontend import ChatTemplate +from serve import structured from serve.server import ByteTokenizer, MockEngine, Service, serve +try: + import jsonschema # noqa: F401 + HAVE_JSONSCHEMA = True +except ImportError: # optional: json_schema answers are then only checked to be one object + HAVE_JSONSCHEMA = False + STORY = {"title": "Photobooth", "sheet": "A single continuous shot.", "cast": [], "boxes": [{"box": 1, "duration_ms": 15000, "new_shot": True, "beat": "Hailee changes poses.", @@ -79,6 +86,7 @@ class Structured(unittest.TestCase): self.assertIn("reasoning_content", raw) self.assertIn("data: [DONE]", raw) + @unittest.skipUnless(HAVE_JSONSCHEMA, "jsonschema is not installed") def test_invalid_generation_is_an_error_and_never_streams_content(self): for script in ("## Film Plan - Photobooth", '{"title":"Only a title"}', json.dumps({**STORY, "extra": True}), @@ -111,6 +119,7 @@ class Structured(unittest.TestCase): self.assertEqual(self.chat()[0], 502) self.assertEqual(generate.call_count, 1) + @unittest.skipUnless(HAVE_JSONSCHEMA, "jsonschema is not installed") def test_invalid_schema_is_400_and_local_refs_work(self): for schema in ({"type": "object", "properties": {"x": {"type": "invalid"}}}, {"type": "object", "$ref": "https://other.example/schema"}): @@ -134,5 +143,25 @@ class Structured(unittest.TestCase): self.assertEqual(self.request("/v1/chat/completions", [])[0], 400) load.assert_not_called() + def test_without_jsonschema_an_object_is_still_required(self): + # jsonschema is optional: without it json_schema answers are checked to be one JSON object, json_object + # never needs it, and nothing is imported at server start + with mock.patch.object(structured, "_jsonschema", False): + self.assertEqual(self.chat()[0], 200) + for script in ("## Film Plan - Photobooth", "[1, 2]"): + code, reply = self.chat(script) + self.assertEqual(code, 502, script) + self.assertEqual(reply["error"]["code"], "structured_output_failed") + self.assertEqual(self.chat('{"answer":4}', response_format={"type": "json_object"})[0], 200) + + def test_the_server_does_not_import_jsonschema_at_start(self): + import subprocess + import sys + code = ("import sys; import serve.server; " + "sys.exit(1 if any(m == 'jsonschema' or m.startswith('jsonschema.') for m in sys.modules) else 0)") + r = subprocess.run([sys.executable, "-c", code], cwd=str(Path(__file__).resolve().parents[1])) + self.assertEqual(r.returncode, 0) + + if __name__ == "__main__": unittest.main() From 24d011807c718df2d5227bbeee3eea3fec7d14ca Mon Sep 17 00:00:00 2001 From: Ricardo Ambrogi <11719845+KadoBOT@users.noreply.github.com> Date: Thu, 1 Oct 2026 04:45:38 +0200 Subject: [PATCH 21/48] serve: add standalone API request monitor --- docs/DETAILS.md | 14 ++++ serve/server.py | 126 +++++++++++++++++++++++++++++- serve/test_monitor.py | 170 +++++++++++++++++++++++++++++++++++++++++ serve/web/monitor.html | 37 +++++++++ serve/web/monitor.js | 111 +++++++++++++++++++++++++++ 5 files changed, 455 insertions(+), 3 deletions(-) create mode 100644 serve/test_monitor.py create mode 100644 serve/web/monitor.html create mode 100644 serve/web/monitor.js diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 76dc4f9a..7693f959 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -814,3 +814,17 @@ tools/MCP are refused explicitly. Without `response_format`, ordinary text and t Structured SSE buffers the answer while sending keep-alive comments. It emits content only after validation, then usage/timings and `[DONE]`; failures emit an SSE error and `[DONE]` without invalid content deltas. `/v1/status.structured_output` advertises the formats, validation method and buffered streaming behavior. + +### API request monitor + +Open `/api-monitor` to inspect API traffic without opening a chat. It shows the model state, safe +load/unload controls, active/queued requests, original request bodies, output, separate reasoning and +non-stream response bodies. Total wall-clock includes FIFO waits and automatic loading; load, queue, +first-token, prompt/output tokens and engine decode timing are shown separately. + +`GET /api/requests` returns compact summaries; `GET /api/requests?id=` returns one retained request. +Both use the existing API-key check. The monitor retains the newest **100 requests in memory** until restart, +with **262,144 characters per input/output/reasoning/response field** and visible truncation flags. The actual API +responses are unaffected. Headers are not recorded, and the monitor key is kept in this tab's session storage. +Treat request history as sensitive input/output when exposing Strata on a network: set an API key as above. +The page uses relative URLs and works through the existing host binding or a reverse proxy. diff --git a/serve/server.py b/serve/server.py index 6638d442..48f37c2c 100644 --- a/serve/server.py +++ b/serve/server.py @@ -709,6 +709,8 @@ class Service: self.trusted_origins: list[str] = [] self.status = {"busy": False, "queued": 0} # GET /status: what the model is doing right now self.rate = collections.deque(maxlen=32) # (time, generated) samples for the live tok/s window + self.api_requests = collections.deque(maxlen=100) # bounded I/O in memory; no headers or API keys + self.request_trace = threading.local() self.history = collections.deque(maxlen=500) # the last finished requests, newest last (GET /metrics) # since the server started (the Monitor's totals, issue #35) self.totals = {"since": time.time(), "requests": 0, "prompt_tokens": 0, "reused": 0, "output_tokens": 0, @@ -802,8 +804,21 @@ class Service: self.last_request_at = time.time() if self.loaded() and not self._vision_down(): return + trace = getattr(self.request_trace, "record", None) + waiting = time.perf_counter() with self.fifo: - self.ensure_loaded() + loading = time.perf_counter() + if trace is not None: + with self.status_lock: + trace["queue_s"] += round(loading - waiting, 3) + trace["state"] = "loading" + try: + self.ensure_loaded() + finally: + if trace is not None: + with self.status_lock: + trace["load_s"] += round(time.perf_counter() - loading, 3) + trace["state"] = "queued" def unload(self, idle_for: float | None = None) -> str: """Stop the engine between requests: "unloaded", "not loaded", "busy" (a request is running or waiting, or @@ -915,6 +930,34 @@ class Service: reading = self.status.get("busy") and self.status.get("first_token") is None return getattr(self.engine, "prefill_tok_s_mean", None) if reading else 0.0 + def begin_request(self, path, req): + raw = json.dumps(req, ensure_ascii=False, indent=2) + record = {"id": uuid.uuid4().hex[:12], "path": path, "model": req.get("model") or self.model, + "started_at": time.time(), "state": "queued", "stream": bool(req.get("stream")), + "response_format": (req.get("response_format") or {}).get("type") + if isinstance(req.get("response_format"), dict) else None, + "input": raw[:262144], "input_truncated": len(raw) > 262144, + "output": "", "reasoning": "", "output_truncated": False, "reasoning_truncated": False, + "queue_s": 0.0, "load_s": 0.0, "first_token_s": None, + "_clock": time.perf_counter()} + with self.status_lock: + self.api_requests.append(record) + self.request_trace.record = record + return record + + def request_records(self, request_id=None): + with self.status_lock: + records = list(self.api_requests) + if request_id: + record = next((r for r in records if r["id"] == request_id), None) + if record is None: + return None + return {k: v for k, v in record.items() if not k.startswith("_")} + return [{k: v for k, v in r.items() + if k not in ("input", "output", "reasoning", "response") and not k.startswith("_")} + | {"wallclock_s": r.get("wallclock_s", round(time.perf_counter() - r["_clock"], 3))} + for r in reversed(records)] + def metrics(self, all_requests=False) -> dict: """GET /metrics: what the Monitor tab shows - the engine's facts, what it is doing, the last requests, and the hardware (with a minute of history per series).""" @@ -1093,12 +1136,17 @@ class Service: # Identity token: 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. engine_last0 = getattr(self.engine, "last", None) + trace = getattr(self.request_trace, "record", None) + waiting = time.perf_counter() with self.status_lock: self.status["queued"] += 1 try: with self.fifo: try: with self.status_lock: + if trace is not None: + trace["queue_s"] += round(time.perf_counter() - waiting, 3) + trace["state"] = "generating" self.status["queued"] -= 1 # issue #27: it died in an earlier request (or was unloaded) - start it again instead of failing self.ensure_loaded() @@ -1122,6 +1170,9 @@ class Service: yield "ping", None continue n += 1 + if trace is not None and trace["first_token_s"] is None: + with self.status_lock: + trace["first_token_s"] = round(time.perf_counter() - trace["_clock"], 3) if t in self.stop_ids: finish = "stop" raw_ids.append(t) @@ -1617,6 +1668,14 @@ def make_handler(svc: Service): self.end_headers() def _json(self, code, obj): + if getattr(self, "record", None) is not None: + with svc.status_lock: + self.record["http_status"] = code + raw = json.dumps(obj, ensure_ascii=False, indent=2) + self.record.update(response=raw[:262144], response_truncated=len(raw) > 262144) + for key in ("error", "usage", "timings"): + if key in obj: + self.record[key] = obj[key] body = json.dumps(obj, ensure_ascii=False).encode() self.send_response(code) self.send_header("Content-Type", "application/json") @@ -1675,6 +1734,15 @@ def make_handler(svc: Service): # the last 12 requests; `?requests=all` every one kept (the Monitor's "Show all", issue #35) self._json(200, svc.metrics(all_requests="requests=all" in self.path)) return + if path == "/api/requests": + if self._authorized(): + request_id = parse_qs(urlsplit(self.path).query).get("id", [None])[0] + records = svc.request_records(request_id) + self._json(404 if records is None else 200, + {"error": {"message": "request no longer retained"}} if records is None else + records if request_id else {"requests": records, "retention": 100, "persistent": False, + "loaded": svc.loaded(), "auto_load": hasattr(svc.engine, "restart")}) + return if path == "/settings": if self._authorized(): self._json(200, {"shared": bool(svc.shared), "defaults": svc.shared}) @@ -1684,8 +1752,8 @@ def make_handler(svc: Service): if self._authorized(): self._json(200, svc.mcp.status() if svc.mcp else {"servers": [], "tools": 0}) return - if path == "": - body = (ROOT / "serve" / "web" / "index.html").read_bytes() + if path in ("", "/api-monitor"): + body = (ROOT / "serve" / "web" / ("monitor.html" if path else "index.html")).read_bytes() self.send_response(200) self.send_header("Content-Type", "text/html; charset=utf-8") self.send_header("Content-Length", str(len(body))) @@ -1786,6 +1854,8 @@ def make_handler(svc: Service): result = "loaded" self._json(200, {"status": result, **svc.v1_status()}) return + if path in ("/v1/chat/completions", "/v1/messages"): + self.record = svc.begin_request(path, req) if path == "/v1/chat/completions": self._openai(req) elif path == "/v1/messages": @@ -1808,6 +1878,18 @@ 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 OSError: + if getattr(self, "record", None) is not None: + self.record["outcome"] = "disconnected" + finally: + record = getattr(self, "record", None) + if record is not None: + with svc.status_lock: + record["wallclock_s"] = round(time.perf_counter() - record["_clock"], 3) + record["finished_at"] = time.time() + record["state"] = "error" if record.get("error") else record.get("outcome", "completed") + svc.request_trace.record = None + def _props(self): model = parse_qs(urlsplit(self.path).query).get("model", [svc.model])[0] if model != svc.model: @@ -1866,6 +1948,8 @@ def make_handler(svc: Service): self._json(200, {"shared": bool(shared), "defaults": shared}) def _sse(self): + if getattr(self, "record", None) is not None: + self.record["http_status"] = 200 self.send_response(200) self.send_header("Content-Type", "text/event-stream") self.send_header("Cache-Control", "no-cache") @@ -1873,6 +1957,34 @@ def make_handler(svc: Service): self._cors() self.end_headers() + def _capture(self, items, api): + """Retain bounded input/output for the monitor without changing the API response.""" + try: + for item in items: + if item is not None: + if api == "openai": + delta = item["choices"][0]["delta"] + content, reasoning = delta.get("content", ""), delta.get("reasoning_content", "") + usage, timings = item.get("usage"), item.get("timings") + else: + _, event = item + delta = event.get("delta", {}) + content, reasoning = delta.get("text", ""), delta.get("thinking", "") + usage, timings = event.get("usage"), None + with svc.status_lock: + for name, value in (("output", content), ("reasoning", reasoning)): + if value: + combined = self.record[name] + value + self.record[name] = combined[:262144] + self.record[name + "_truncated"] |= len(combined) > 262144 + if usage: + self.record["usage"] = usage + if timings: + self.record["timings"] = timings + yield item + finally: + items.close() + def _openai(self, req): req = svc.with_shared(req, "openai") messages, tools, kw = openai_to_messages(req) @@ -1899,6 +2011,7 @@ def make_handler(svc: Service): chunks = openai_chunks(svc, req, ids, thinking, tools, max_new, cancel, run=run) if validator is not None: chunks = structured_chunks(chunks, validator) + chunks = self._capture(chunks, "openai") if not req.get("stream"): return self._json(200, openai_collect(chunks)) self._sse() @@ -1911,16 +2024,19 @@ def make_handler(svc: Service): self.wfile.flush() self.wfile.write(b"data: [DONE]\n\n") except OSError: + self.record["outcome"] = "disconnected" cancel.set() # client went away: stop the engine chunks.close() except EngineDied as e: # mid-stream: say so, then end the stream properly err = {"error": {"type": "server_error", "message": f"{e}; the next request restarts it"}} + self.record["error"] = err["error"] self.wfile.write(b"data: " + json.dumps(err).encode() + b"\n\ndata: [DONE]\n\n") except StructuredOutputError as e: err = {"error": {"type": "structured_output_failed", "code": "structured_output_failed", "message": str(e)}} self.wfile.write(b"data: " + json.dumps(err).encode() + b"\n\ndata: [DONE]\n\n") except ValueError as e: # the engine's ERR after the stream started: the err = {"error": {"type": "server_error", "message": str(e)}} # headers are sent, so no 400 now + self.record["error"] = err["error"] self.wfile.write(b"data: " + json.dumps(err).encode() + b"\n\ndata: [DONE]\n\n") def _count_tokens(self, req): @@ -1941,6 +2057,7 @@ def make_handler(svc: Service): _debug_req("anthropic", req, messages, tools, max_new, thinking, len(ids)) cancel = threading.Event() events = anthropic_events(svc, req, ids, thinking, tools, max_new, cancel) + events = self._capture(events, "anthropic") if not req.get("stream"): return self._json(200, anthropic_collect(events)) self._sse() @@ -1954,13 +2071,16 @@ def make_handler(svc: Service): json.dumps(e, ensure_ascii=False).encode() + b"\n\n") self.wfile.flush() except OSError: + self.record["outcome"] = "disconnected" cancel.set() events.close() except EngineDied as e: # mid-stream: Anthropic's error event err = {"type": "error", "error": {"type": "api_error", "message": f"{e}; the next request restarts it"}} + self.record["error"] = err["error"] self.wfile.write(b"event: error\ndata: " + json.dumps(err).encode() + b"\n\n") except ValueError as e: # the engine's ERR after the stream started err = {"type": "error", "error": {"type": "api_error", "message": str(e)}} + self.record["error"] = err["error"] self.wfile.write(b"event: error\ndata: " + json.dumps(err).encode() + b"\n\n") return Handler diff --git a/serve/test_monitor.py b/serve/test_monitor.py new file mode 100644 index 00000000..2c2df39d --- /dev/null +++ b/serve/test_monitor.py @@ -0,0 +1,170 @@ +"""Request inspection through HTTP; no native model or GPU is required.""" +import json +import threading +import time +import unittest +import urllib.error +import urllib.request +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path +from unittest import mock + +from serve.frontend import ChatTemplate +from serve.server import ByteTokenizer, EngineDied, MockEngine, Service, serve + + +class ReloadableEngine(MockEngine): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.running, self.unloaded = True, False + + def alive(self): + return self.running + + def unload(self): + self.running, self.unloaded = False, True + + def restart(self): + self.running, self.unloaded = True, False + + +class Monitor(unittest.TestCase): + def setUp(self): + self.tok = ByteTokenizer() + self.engine = ReloadableEngine(self.tok, "Thought.\nHello .", max_context=16384) + self.svc = Service(self.engine, self.tok, ChatTemplate(Path(__file__).parent / "chat_template.jinja")) + self.httpd = serve(self.svc, port=0) + self.base = f"http://127.0.0.1:{self.httpd.server_address[1]}" + + def tearDown(self): + self.httpd.shutdown() + self.httpd.server_close() + + def request(self, path, body=None, headers=None): + req = urllib.request.Request(self.base + path, data=json.dumps(body).encode() if body is not None else None, + headers={"Content-Type": "application/json", **(headers or {})}) + try: + response = urllib.request.urlopen(req, timeout=10) + except urllib.error.HTTPError as error: + response = error + with response: + raw = response.read().decode() + return response.status, json.loads(raw) if "application/json" in response.headers.get("Content-Type", "") else raw + + def chat(self, api="openai", **kwargs): + return self.request("/v1/messages" if api == "anthropic" else "/v1/chat/completions", + {"messages": [{"role": "user", "content": "Say hello."}], + "max_tokens": 256, "reasoning_effort": "low", **kwargs}) + + def latest(self): + summary = self.request("/api/requests")[1]["requests"][0] + return self.request("/api/requests?id=" + summary["id"])[1] + + def test_output_and_reasoning_for_both_dialects_and_stream_modes(self): + for api in ("openai", "anthropic"): + for stream in (False, True): + with self.subTest(api=api, stream=stream): + code, reply = self.chat(api, stream=stream) + self.assertEqual(code, 200) + record = self.latest() + self.assertEqual(record["state"], "completed") + self.assertEqual(record["http_status"], 200) + self.assertIn("Say hello.", record["input"]) + self.assertIn("", record["output"]) + self.assertIn("Thought.", record["reasoning"]) + self.assertGreater(record["usage"].get("completion_tokens", record["usage"].get("output_tokens", 0)), 0) + self.assertGreaterEqual(record["wallclock_s"], record["first_token_s"]) + self.assertNotIn("_clock", record) + if not stream: + self.assertEqual(json.loads(record["response"]), reply) + else: + self.assertNotIn("response", record) + + def test_error_and_engine_death_are_not_successes(self): + self.assertEqual(self.chat(max_tokens=20000)[0], 400) + self.assertEqual(self.latest()["state"], "error") + for api in ("openai", "anthropic"): + for stream in (False, True): + with self.subTest(api=api, stream=stream), mock.patch.object(self.engine, "generate", side_effect=EngineDied("stopped")): + self.chat(api, stream=stream) + record = self.latest() + self.assertEqual(record["state"], "error") + self.assertIn("stopped", record["error"]["message"]) + self.assertEqual(record["output"], "") + self.assertNotIn("timings", record) + + def test_history_is_authorized_and_does_not_capture_headers(self): + self.svc.api_key = "secret" + auth = {"Authorization": "Bearer secret"} + self.assertEqual(self.request("/api/requests")[0], 401) + self.assertEqual(self.request("/api/requests?id=missing")[0], 401) + self.assertEqual(len(self.svc.api_requests), 0) + self.assertEqual(self.request("/v1/chat/completions", {"messages": [{"role": "user", "content": "hi"}]}, auth)[0], 200) + summary = self.request("/api/requests", headers=auth)[1]["requests"][0] + self.assertNotIn("input", summary) + self.assertNotIn("output", summary) + self.assertEqual(self.request("/api/requests?id=" + summary["id"])[0], 401) + detail = self.request("/api/requests?id=" + summary["id"], headers=auth)[1] + self.assertNotIn("secret", json.dumps(detail)) + + def test_capture_is_bounded_and_eviction_returns_404(self): + huge = "x" * 262200 + first = self.svc.begin_request("/v1/chat/completions", {"messages": [{"content": huge}]}) + self.assertEqual(len(first["input"]), 262144) + self.assertTrue(first["input_truncated"]) + for _ in range(100): + self.svc.begin_request("/v1/chat/completions", {"messages": []}) + self.assertEqual(len(self.request("/api/requests")[1]["requests"]), 100) + self.assertEqual(self.request("/api/requests?id=" + first["id"])[0], 404) + # Exercise output capture without making a mock engine emit 262K tokens. + handler = object.__new__(self.httpd.RequestHandlerClass) + handler.record = self.svc.api_requests[-1] + chunk = {"choices": [{"delta": {"content": huge, "reasoning_content": huge}}]} + list(handler._capture((item for item in [chunk]), "openai")) + for field in ("output", "reasoning"): + self.assertEqual(len(handler.record[field]), 262144) + self.assertTrue(handler.record[field + "_truncated"]) + + def test_queue_wait_and_loading_are_attributed_separately(self): + self.engine.unload() + entered, release = threading.Event(), threading.Event() + original = self.engine.restart + def restart(): + entered.set() + self.assertTrue(release.wait(5)) + original() + with mock.patch.object(self.engine, "restart", side_effect=restart), ThreadPoolExecutor(max_workers=2) as pool: + first = pool.submit(self.chat) + self.assertTrue(entered.wait(5)) + second = pool.submit(self.chat) + deadline = time.monotonic() + 5 + while len(self.svc.api_requests) < 2 and time.monotonic() < deadline: + time.sleep(0.01) + self.assertEqual(len(self.svc.api_requests), 2) + history = self.request("/api/requests")[1] + self.assertEqual({r["state"] for r in history["requests"]}, {"queued", "loading"}) + self.assertFalse(history["loaded"]) + self.assertTrue(history["auto_load"]) + time.sleep(0.03) + release.set() + self.assertEqual(first.result()[0], 200) + self.assertEqual(second.result()[0], 200) + records = list(self.svc.api_requests) + self.assertGreater(records[0]["load_s"], 0.02) + self.assertGreater(records[1]["queue_s"], 0.02) + self.assertLess(records[1]["load_s"], records[0]["load_s"]) + self.assertTrue(all(r["state"] == "completed" for r in records)) + + def test_page_and_relative_assets_are_served(self): + code, html = self.request("/api-monitor") + self.assertEqual(code, 200) + self.assertIn('src="/web/monitor.js"', html) + code, script = self.request("/web/monitor.js") + self.assertEqual(code, 200) + self.assertIn("textContent", script) + self.assertNotIn("innerHTML", script) + self.assertEqual(self.request("/web/../server.py")[0], 404) + + +if __name__ == "__main__": + unittest.main() diff --git a/serve/web/monitor.html b/serve/web/monitor.html new file mode 100644 index 00000000..b05b29f8 --- /dev/null +++ b/serve/web/monitor.html @@ -0,0 +1,37 @@ + + + + +Strata API Monitor + + + + + +
Strata Local inference
+
+

API Monitor

Model status and every request, in one place.

+ + +
+
Model
Connecting…
127.0.0.1:5001/v1
+
Requests retained
—
Waiting for server
+
Last wall-clock
—
Includes queue and model loading
+
Last decode speed
—
Engine timing · tokens / second
+
+

Requests

+
+
Inspect a requestSelect a request to see its input, output, and timings.
+ +
+
Last 100 requests kept in memory until restart. Inputs and outputs stay on this machine.Connecting…
+
+ diff --git a/serve/web/monitor.js b/serve/web/monitor.js new file mode 100644 index 00000000..5543b94b --- /dev/null +++ b/serve/web/monitor.js @@ -0,0 +1,111 @@ +"use strict"; +const $ = id => document.getElementById(id); +let selected = null, detail = null, pane = "input", records = [], state = null, operating = false, stamp = "", actionError = ""; +let apiKey = sessionStorage.getItem("strata.monitor.key") || ""; +document.documentElement.dataset.theme = localStorage.getItem("strata.theme") || "dark"; +const seconds = n => typeof n === "number" ? `${n.toFixed(2)} s` : "—"; +const speed = n => typeof n === "number" ? n.toFixed(1) : "—"; +const active = r => !["completed", "error", "disconnected"].includes(r.state); +function text(id, value) { const el = $(id); if (el.textContent !== String(value)) el.textContent = value; } +async function api(path, body) { + const response = await fetch(path, {cache:"no-store", headers:{...(apiKey ? {Authorization:`Bearer ${apiKey}`} : {}), ...(body !== undefined ? {"Content-Type":"application/json"} : {})}, ...(body !== undefined ? {method:"POST", body:JSON.stringify(body)} : {})}); + const value = await response.json(); + if (!response.ok) { + if (response.status === 401) $("auth").hidden = false; + throw new Error(value.error?.message || `HTTP ${response.status}`); + } + return value; +} +function notice(message) { $("error").hidden = !message; text("error", message || ""); } +function list() { + const query = $("search").value.toLowerCase(), filter = $("filter").value; + const visible = records.filter(r => `${r.id} ${r.path} ${r.model}`.toLowerCase().includes(query) && (filter === "all" || (filter === "active" ? active(r) : r.state === filter))); + const nextStamp = JSON.stringify([visible, selected]); + if (stamp === nextStamp) return; + stamp = nextStamp; + const focusId = document.activeElement?.dataset.request; + $("requests").replaceChildren(); + if (!visible.length) { + const empty = document.createElement("div"); empty.className = "empty"; + empty.textContent = records.length ? "No matching requests." : "No requests yet. API calls will appear here automatically."; + $("requests").append(empty); + } + for (const r of visible) { + const button = document.createElement("button"); button.className = `request${selected === r.id ? " selected" : ""}`; + button.dataset.request = r.id; button.setAttribute("aria-label", `Request ${r.id}`); button.setAttribute("aria-pressed", String(selected === r.id)); + const row = document.createElement("div"); row.className = "row"; + const time = document.createElement("span"); time.textContent = new Date(r.started_at * 1000).toLocaleTimeString(); + const tag = document.createElement("span"); tag.className = `tag ${r.state}`; tag.textContent = r.state; + row.append(time, tag); + const endpoint = document.createElement("div"); endpoint.className = "endpoint"; endpoint.textContent = `POST ${r.path}`; + const meta = document.createElement("div"); meta.className = "small"; + meta.textContent = `${r.id} · ${seconds(r.wallclock_s)} · ${r.stream ? "stream" : "JSON response"}${r.http_status ? ` · HTTP ${r.http_status}` : ""}`; + button.append(row, endpoint, meta); + button.onclick = async () => { selected = r.id; detail = null; list(); await showDetail(); }; + $("requests").append(button); + if (focusId === r.id) button.focus({preventScroll:true}); + } +} +function content() { + if (!detail) return; + let value = detail[pane] || (pane === "response" && detail.stream ? "Streaming response: see Output and the request error, if any." : "No content."); + if (pane === "output") { try { value = JSON.stringify(JSON.parse(value), null, 2); } catch (_) {} } + text("content", value); + const note = pane === "output" && detail.error ? "Raw model output retained for diagnosis. The API returned an error." : pane === "input" ? "Original request body." : pane === "output" ? "Model answer. JSON is formatted here for readability." : pane === "reasoning" ? "Separate reasoning content, when enabled." : "API response body."; + text("content-note", note + (detail[`${pane}_truncated`] ? " Monitor capture truncated at 256K characters; the API response was not shortened." : "")); +} +async function showDetail() { + if (!selected) return; + const id = selected; + const value = await api(`/api/requests?id=${encodeURIComponent(id)}`); + if (selected !== id) return; + detail = value; $("selection").hidden = false; $("no-selection").hidden = true; + text("detail-title", `${value.id} · ${value.path}`); + text("detail-status", value.state); $("detail-status").className = `tag ${value.state}`; + text("detail-time", new Date(value.started_at * 1000).toLocaleString()); + text("detail-wall", seconds(value.wallclock_s ?? ((Date.now() / 1000) - value.started_at))); + text("detail-load", seconds(value.load_s)); text("detail-queue", seconds(value.queue_s)); text("detail-first", seconds(value.first_token_s)); + text("detail-prompt", value.usage?.prompt_tokens ?? value.usage?.input_tokens ?? "—"); + text("detail-tokens", value.usage?.completion_tokens ?? value.usage?.output_tokens ?? "—"); + text("detail-speed", speed(value.timings?.predicted_per_second)); text("detail-format", value.response_format || "text"); + $("detail-error").hidden = !value.error; text("detail-error", value.error?.message || ""); content(); +} +async function refresh() { + try { + const [status, history] = await Promise.all([api("/v1/status"), api("/api/requests")]); + state = status; records = history.requests; + status.loaded = history.loaded; status.auto_load = history.auto_load; + if (selected && !records.some(r => r.id === selected)) { + selected = detail = null; $("selection").hidden = true; $("no-selection").hidden = false; + } + const inflight = Math.max(status.activity.in_flight, records.filter(active).length); + const loading = records.some(r => r.state === "loading"); + text("loaded", loading ? "Loading…" : inflight ? "In use" : status.loaded ? "Loaded" : "Unloaded"); + $("model-state").className = `value ${inflight || loading ? "busy" : status.loaded ? "loaded" : ""}`; + text("model", status.model); text("count", records.length); + text("active", inflight ? `${inflight} active / queued` : status.auto_load ? "Loads automatically on the next request" : "No active requests"); + const last = records.find(r => !active(r)); + text("wall", last ? seconds(last.wallclock_s) : "—"); text("speed", speed(last?.timings?.predicted_per_second)); + $("load").disabled = operating || Boolean(inflight) || status.loaded; $("unload").disabled = operating || Boolean(inflight) || !status.loaded; + list(); if (selected) await showDetail(); + text("updated", `Live · updated ${new Date().toLocaleTimeString()}`); + if (!operating) notice(actionError); + } catch (error) { notice(error.message); text("updated", "Disconnected · retrying"); $("load").disabled = $("unload").disabled = true; } +} +async function control(load) { + actionError = ""; + operating = true; $("load").disabled = $("unload").disabled = true; + text("loaded", load ? "Loading…" : "Unloading…"); + try { await api(load ? "/load" : "/unload", {}); notice(""); } + catch (error) { actionError = error.message; notice(actionError); } + finally { operating = false; await refresh(); } +} +$("load").onclick = () => control(true); $("unload").onclick = () => control(false); +$("key").onclick = () => { $("auth").hidden = !$("auth").hidden; if (!$("auth").hidden) $("api-key").focus(); }; +$("auth").onsubmit = async event => { event.preventDefault(); apiKey = $("api-key").value.trim(); sessionStorage.setItem("strata.monitor.key", apiKey); $("auth").hidden = true; await refresh(); }; +$("theme").onclick = () => { const theme = document.documentElement.dataset.theme === "dark" ? "light" : "dark"; document.documentElement.dataset.theme = theme; localStorage.setItem("strata.theme", theme); }; +$("search").oninput = list; $("filter").onchange = list; +document.querySelectorAll("[data-pane]").forEach(button => { button.onclick = () => { pane = button.dataset.pane; document.querySelectorAll("[data-pane]").forEach(b => b.setAttribute("aria-selected", String(b === button))); content(); }; }); +$("copy").onclick = async () => { try { await navigator.clipboard.writeText($("content").textContent); text("copy", "Copied"); setTimeout(() => text("copy", "Copy"), 1500); } catch (_) { notice("Clipboard unavailable; select the text to copy it."); } }; +async function poll() { await refresh(); setTimeout(poll, 2000); } +poll(); From 272c16c76780c3822a7f7457f3f3811bdb018767 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Thu, 1 Oct 2026 08:32:01 +0200 Subject: [PATCH 22/48] #332 follow-up: the API request monitor is opt-in ("api_monitor": true / --api-monitor), off by default It keeps the last 100 requests' prompts, answers and reasoning in memory. Off (the default): begin_request() keeps nothing, the streams are not wrapped, GET /api/requests and /api-monitor answer 404. Every record write goes through _note(), which does nothing without a record (the PR's direct self.record[...] writes in the stream error paths would have failed with the monitor off). A client disconnect in do_POST is marked and then re-raised, as the server handled it before. The start line says when it is on (and that anyone can read the history without an API key). test_monitor: turns it on; MonitorOff checks the default; Anthropic requests ask for thinking with "thinking" (#278). --- docs/DETAILS.md | 3 +++ serve/server.py | 58 ++++++++++++++++++++++++++++++++----------- serve/test_monitor.py | 30 +++++++++++++++++++++- 3 files changed, 75 insertions(+), 16 deletions(-) diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 7693f959..c58be4d3 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -817,6 +817,9 @@ then usage/timings and `[DONE]`; failures emit an SSE error and `[DONE]` without ### API request monitor +Off by default, since it keeps prompts and answers in memory: turn it on with `"api_monitor": true` in +`strata-.json` (or `serve/server.py --api-monitor`); otherwise nothing is recorded and the two endpoints below +answer 404. Open `/api-monitor` to inspect API traffic without opening a chat. It shows the model state, safe load/unload controls, active/queued requests, original request bodies, output, separate reasoning and non-stream response bodies. Total wall-clock includes FIFO waits and automatic loading; load, queue, diff --git a/serve/server.py b/serve/server.py index 48f37c2c..5b5af5b0 100644 --- a/serve/server.py +++ b/serve/server.py @@ -709,6 +709,9 @@ class Service: self.trusted_origins: list[str] = [] self.status = {"busy": False, "queued": 0} # GET /status: what the model is doing right now self.rate = collections.deque(maxlen=32) # (time, generated) samples for the live tok/s window + # #332: the API request monitor (/api-monitor) keeps the last 100 requests' prompts and answers in memory, + # so it is off unless the config's "api_monitor" (or --api-monitor) turns it on + self.api_monitor = False self.api_requests = collections.deque(maxlen=100) # bounded I/O in memory; no headers or API keys self.request_trace = threading.local() self.history = collections.deque(maxlen=500) # the last finished requests, newest last (GET /metrics) @@ -931,6 +934,9 @@ class Service: return getattr(self.engine, "prefill_tok_s_mean", None) if reading else 0.0 def begin_request(self, path, req): + """#332: a monitor record for this request, or None when the monitor is off (nothing is kept then).""" + if not self.api_monitor: + return None raw = json.dumps(req, ensure_ascii=False, indent=2) record = {"id": uuid.uuid4().hex[:12], "path": path, "model": req.get("model") or self.model, "started_at": time.time(), "state": "queued", "stream": bool(req.get("stream")), @@ -1636,9 +1642,17 @@ def make_handler(svc: Service): class Handler(BaseHTTPRequestHandler): protocol_version = "HTTP/1.0" # SSE ends by closing the connection + record = None # #332: this request's monitor record, if kept + def log_message(self, fmt, *args): pass + def _note(self, **values): + """#332: what the monitor shows about this request (nothing when the monitor is off).""" + if self.record is not None: + with svc.status_lock: + self.record.update(values) + def _cors(self): """#321: CORS headers for an API path (/v1/*) and an origin the config lists in cors_origins - nothing otherwise, so a browser keeps every other page away from the API, /settings, /unload and the MCP tools.""" @@ -1668,7 +1682,7 @@ def make_handler(svc: Service): self.end_headers() def _json(self, code, obj): - if getattr(self, "record", None) is not None: + if self.record is not None: with svc.status_lock: self.record["http_status"] = code raw = json.dumps(obj, ensure_ascii=False, indent=2) @@ -1734,7 +1748,7 @@ def make_handler(svc: Service): # the last 12 requests; `?requests=all` every one kept (the Monitor's "Show all", issue #35) self._json(200, svc.metrics(all_requests="requests=all" in self.path)) return - if path == "/api/requests": + if path == "/api/requests" and svc.api_monitor: if self._authorized(): request_id = parse_qs(urlsplit(self.path).query).get("id", [None])[0] records = svc.request_records(request_id) @@ -1752,7 +1766,7 @@ def make_handler(svc: Service): if self._authorized(): self._json(200, svc.mcp.status() if svc.mcp else {"servers": [], "tools": 0}) return - if path in ("", "/api-monitor"): + if path == "" or (path == "/api-monitor" and svc.api_monitor): body = (ROOT / "serve" / "web" / ("monitor.html" if path else "index.html")).read_bytes() self.send_response(200) self.send_header("Content-Type", "text/html; charset=utf-8") @@ -1879,10 +1893,10 @@ def make_handler(svc: Service): self._json(503, {"error": {"type": "server_error", "message": str(e)}}) except OSError: - if getattr(self, "record", None) is not None: - self.record["outcome"] = "disconnected" + self._note(outcome="disconnected") + raise # as before #332: the server's own handling finally: - record = getattr(self, "record", None) + record = self.record if record is not None: with svc.status_lock: record["wallclock_s"] = round(time.perf_counter() - record["_clock"], 3) @@ -1948,8 +1962,7 @@ def make_handler(svc: Service): self._json(200, {"shared": bool(shared), "defaults": shared}) def _sse(self): - if getattr(self, "record", None) is not None: - self.record["http_status"] = 200 + self._note(http_status=200) self.send_response(200) self.send_header("Content-Type", "text/event-stream") self.send_header("Cache-Control", "no-cache") @@ -1958,7 +1971,13 @@ def make_handler(svc: Service): self.end_headers() def _capture(self, items, api): - """Retain bounded input/output for the monitor without changing the API response.""" + """Retain bounded input/output for the monitor without changing the API response (the items as they + are when the monitor is off).""" + if self.record is None: + return items + return self._captured(items, api) + + def _captured(self, items, api): try: for item in items: if item is not None: @@ -2024,19 +2043,20 @@ def make_handler(svc: Service): self.wfile.flush() self.wfile.write(b"data: [DONE]\n\n") except OSError: - self.record["outcome"] = "disconnected" + self._note(outcome="disconnected") cancel.set() # client went away: stop the engine chunks.close() except EngineDied as e: # mid-stream: say so, then end the stream properly err = {"error": {"type": "server_error", "message": f"{e}; the next request restarts it"}} - self.record["error"] = err["error"] + self._note(error=err["error"]) self.wfile.write(b"data: " + json.dumps(err).encode() + b"\n\ndata: [DONE]\n\n") except StructuredOutputError as e: err = {"error": {"type": "structured_output_failed", "code": "structured_output_failed", "message": str(e)}} + self._note(error=err["error"]) self.wfile.write(b"data: " + json.dumps(err).encode() + b"\n\ndata: [DONE]\n\n") except ValueError as e: # the engine's ERR after the stream started: the err = {"error": {"type": "server_error", "message": str(e)}} # headers are sent, so no 400 now - self.record["error"] = err["error"] + self._note(error=err["error"]) self.wfile.write(b"data: " + json.dumps(err).encode() + b"\n\ndata: [DONE]\n\n") def _count_tokens(self, req): @@ -2071,16 +2091,16 @@ def make_handler(svc: Service): json.dumps(e, ensure_ascii=False).encode() + b"\n\n") self.wfile.flush() except OSError: - self.record["outcome"] = "disconnected" + self._note(outcome="disconnected") cancel.set() events.close() except EngineDied as e: # mid-stream: Anthropic's error event err = {"type": "error", "error": {"type": "api_error", "message": f"{e}; the next request restarts it"}} - self.record["error"] = err["error"] + self._note(error=err["error"]) self.wfile.write(b"event: error\ndata: " + json.dumps(err).encode() + b"\n\n") except ValueError as e: # the engine's ERR after the stream started err = {"type": "error", "error": {"type": "api_error", "message": str(e)}} - self.record["error"] = err["error"] + self._note(error=err["error"]) self.wfile.write(b"event: error\ndata: " + json.dumps(err).encode() + b"\n\n") return Handler @@ -2288,6 +2308,9 @@ def main() -> int: "{...}}); the web app's chat can use their tools (also \"mcp_servers\" in " "the config)") ap.add_argument("--lazy", action="store_true", help="start the text-only API unloaded; load on first request") + ap.add_argument("--api-monitor", action="store_true", + help="the API request monitor at /api-monitor: keeps the last 100 requests' prompts and answers in " + "memory (also \"api_monitor\": true in the config; off by default)") ap.add_argument("--idle-unload", type=float, default=None, metavar="SECONDS", help="unload the model after this many seconds without requests, so other programs (games, other " "model servers) can use the VRAM; the next request loads it again (also \"idle_unload_s\" " @@ -2369,6 +2392,11 @@ def main() -> int: svc.api_key = a.api_key or cfg.get("api_key", "") svc.cors_origins = origins_of(cfg.get("cors_origins"), "cors_origins", wildcard=True) svc.trusted_origins = origins_of(cfg.get("trusted_origins"), "trusted_origins", wildcard=False) + svc.api_monitor = a.api_monitor or cfg.get("api_monitor") is True + if svc.api_monitor: + print("[strata] API request monitor on (/api-monitor): the last 100 requests' prompts and answers are kept in " + "memory" + ("" if svc.api_key else "; anyone who can reach this server can read them (no API key)"), + flush=True) if svc.cors_origins: print(f"[strata] CORS on /v1/* for {', '.join(svc.cors_origins)}" + ("" if svc.api_key or "*" not in svc.cors_origins else diff --git a/serve/test_monitor.py b/serve/test_monitor.py index 2c2df39d..ad554e00 100644 --- a/serve/test_monitor.py +++ b/serve/test_monitor.py @@ -28,11 +28,37 @@ class ReloadableEngine(MockEngine): self.running, self.unloaded = True, False +class MonitorOff(unittest.TestCase): + """#332 is opt-in: by default no prompt or answer is kept, and the monitor's endpoints do not exist.""" + + def test_off_by_default(self): + tok = ByteTokenizer() + svc = Service(MockEngine(tok, "Hello.", max_context=4096), tok, + ChatTemplate(Path(__file__).parent / "chat_template.jinja")) + httpd = serve(svc, port=0) + base = f"http://127.0.0.1:{httpd.server_address[1]}" + try: + req = urllib.request.Request(base + "/v1/chat/completions", headers={"Content-Type": "application/json"}, + data=json.dumps({"messages": [{"role": "user", "content": "secret"}]}).encode()) + with urllib.request.urlopen(req, timeout=10) as r: + self.assertEqual(r.status, 200) + self.assertEqual(len(svc.api_requests), 0) + for path in ("/api/requests", "/api-monitor"): + with self.assertRaises(urllib.error.HTTPError) as e: + urllib.request.urlopen(base + path, timeout=10) + self.assertEqual(e.exception.code, 404, path) + e.exception.close() + finally: + httpd.shutdown() + httpd.server_close() + + class Monitor(unittest.TestCase): def setUp(self): self.tok = ByteTokenizer() self.engine = ReloadableEngine(self.tok, "Thought.\nHello .", max_context=16384) self.svc = Service(self.engine, self.tok, ChatTemplate(Path(__file__).parent / "chat_template.jinja")) + self.svc.api_monitor = True # opt-in ("api_monitor": true / --api-monitor) self.httpd = serve(self.svc, port=0) self.base = f"http://127.0.0.1:{self.httpd.server_address[1]}" @@ -52,9 +78,11 @@ class Monitor(unittest.TestCase): return response.status, json.loads(raw) if "application/json" in response.headers.get("Content-Type", "") else raw def chat(self, api="openai", **kwargs): + # Anthropic thinks only when asked (#278): "thinking" there, reasoning_effort for OpenAI + think = {"thinking": {"type": "enabled", "budget_tokens": 1024}} if api == "anthropic" else {"reasoning_effort": "low"} return self.request("/v1/messages" if api == "anthropic" else "/v1/chat/completions", {"messages": [{"role": "user", "content": "Say hello."}], - "max_tokens": 256, "reasoning_effort": "low", **kwargs}) + "max_tokens": 256, **think, **kwargs}) def latest(self): summary = self.request("/api/requests")[1]["requests"][0] From a1e4fb4c80f8e2f220deb12962952d685bbff533 Mon Sep 17 00:00:00 2001 From: sergiywith Date: Wed, 30 Sep 2026 22:25:39 +0300 Subject: [PATCH 23/48] Verify: the commit graph no longer waits; it overlaps the MTP draft The commit's cudaStreamSynchronize held the host ~0.45 ms a round. The next window follows it on the same stream and the drafter (its own stream) reads only this window's final rows and its own K/V, so a single-GPU session (Verifier::set_commit_async) returns at once. Whatever touches the session from another stream or the host afterwards synchronizes the device: the start of each --serve request (checkpoint restore, zeroing, the prompt path) and the end of a generate run; checkpoint saves already did. A layer split keeps the wait, as does STRATA_COMMIT_SYNC=1. IQ2_XS, 400-token answers, 3 runs each: 128.6 -> 135.8 tok/s decode (+5.6%), the same tokens. NVFP4 pack +0.8%. --- include/strata/core/verify.hpp | 5 +++++ src/core/verify.cpp | 12 ++++++++++-- src/program/generate.cpp | 5 +++++ 3 files changed, 20 insertions(+), 2 deletions(-) diff --git a/include/strata/core/verify.hpp b/include/strata/core/verify.hpp index f478191a..4ddc5269 100644 --- a/include/strata/core/verify.hpp +++ b/include/strata/core/verify.hpp @@ -119,6 +119,11 @@ public: /// Keep the first `n_keep` (1..T) tokens of the last window; advances `ss.ple_prev` by them. bool commit(int n_keep, std::string& err); + /// commit() returns without waiting for its graph (a single-GPU session sets it): the next window follows it on + /// the same stream and the drafter reads nothing it writes, so it overlaps the draft. Whoever reads or writes + /// the session from another stream or the host afterwards (a new request, a checkpoint) synchronizes the device + /// first. STRATA_COMMIT_SYNC=1 keeps the wait. + static void set_commit_async(bool on); /// Measurement hook (STRATA_LOGPOS): after run(), write one line per row t of the last window's head - /// "pos target logprob top top_logprob hit extra_logprob target_logprob_without_extra" - where row t is the diff --git a/src/core/verify.cpp b/src/core/verify.cpp index 179a7752..06f8ceaf 100644 --- a/src/core/verify.cpp +++ b/src/core/verify.cpp @@ -1292,6 +1292,9 @@ bool Verifier::window_logprobs(const int32_t* targets, int T, int64_t pos0, int3 return true; } +namespace { bool g_commit_async = false; } +void Verifier::set_commit_async(bool on) { g_commit_async = on && std::getenv("STRATA_COMMIT_SYNC") == nullptr; } + bool Verifier::commit(int n_keep, std::string& err) { const OnDevice on_device(device_); if (n_keep < 1 || n_keep > last_t_) { err = "verify: commit count out of range"; return false; } @@ -1302,8 +1305,13 @@ bool Verifier::commit(int n_keep, std::string& err) { std::atomic_thread_fence(std::memory_order_seq_cst); const cudaError_t le = cudaGraphLaunch(commit_exec_, cs_); if (le != cudaSuccess) { err = std::string("verify: commit launch: ") + cudaGetErrorString(le); return false; } - const cudaError_t se = cudaStreamSynchronize(cs_); - if (se != cudaSuccess) { err = std::string("verify: commit: ") + cudaGetErrorString(se); return false; } + // set_commit_async: no wait here - the next window runs on the same stream after it, and the drafter (its own + // stream) reads only this window's final rows and its own K/V. h_commit_ is next written after the next window's + // results are read, i.e. after this graph has run. + if (!g_commit_async) { + const cudaError_t se = cudaStreamSynchronize(cs_); + if (se != cudaSuccess) { err = std::string("verify: commit: ") + cudaGetErrorString(se); return false; } + } if (ple_stage()) // stages that share one session must advance it once for (int t = 0; t < n_keep; ++t) { ss_->ple_prev[0] = ss_->ple_prev[1]; diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 74c47759..1ec6690b 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -2054,6 +2054,7 @@ int main(int argc, char** argv) { } } } + strata::core::Verifier::set_commit_async(!multi_gpu); // see Verifier::set_commit_async // ---- layer split across GPUs: each later stage's own copy of the dense weights, its session and (the last) the // head, made on its device before the host arena is mapped (as the drafter below, for the same WDDM reason) std::vector> stages; @@ -4607,6 +4608,9 @@ int main(int argc, char** argv) { return imgs_below(req_imgs, L) == pre_imgs; }; const bool want_cvec = strata::kernels::cvec().loaded() ? req_cvec != 0 : true; + // the last request's final commit may still be running on the verifier's stream (set_commit_async): + // everything below reads, restores or zeroes the session from other streams and the host + cudaDeviceSynchronize(); int64_t resume = 0; bool from_live = false; if (o.prompt_cache > 0 && want_cvec == cvec_cached) { @@ -6016,6 +6020,7 @@ int main(int argc, char** argv) { for (int64_t t : produced) std::printf(" %lld", (long long) t); std::printf("\n"); const double decode_ms = decoded > 0 ? total_ms / (double) decoded : 0.0; + cudaDeviceSynchronize(); // the last commit (set_commit_async) before anything reads the session std::printf("%-24s %lld tokens in %.1f ms -> %.2f tok/s\n", "decode", (long long) decoded, total_ms, decode_ms > 0.0 ? 1000.0 / decode_ms : 0.0); if (n_prompt > 1) From bd84d0bc6d5556d7464e55fc1e3779715b9fd5af Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Thu, 1 Oct 2026 08:34:33 +0200 Subject: [PATCH 24/48] #284 follow-up: wait for the async commit on an event, at every point that touches the session afterwards The commit graph writes the GDN state and conv tail, the QSA indexer's tail/dead/pooled/block_pos and the PLE history; with #284 it may still run when commit() returns. Verifier::commit records commit_done_ after it, and Verifier::wait_commit() synchronizes that event (not the device; a no-op when nothing is pending, recursing into a layer split's later stages). A layer split's first stage keeps the synchronous commit (next_ set). Audited, and where the wait now is: - the serve decode loop's end (end of turn, max tokens, STOP/cancel): wait before the live session, the state fingerprint (STRATA_STATE_HASH) and the DONE line - so the next request's park (conversation snapshot capture), restore, checkpoint restore and zeroing never see a running commit; - the prompt read by verify windows (serve): wait at its end - the batched prompt path (other streams), prompt checkpoints (cudaDeviceSynchronize already) and snapshots may follow; - the start of each serve request: an event wait replaces #284's cudaDeviceSynchronize (covers error paths); - the end of a generate run: wait right after the decode loop, before the stats and the dumps (#284 synchronized only later, after the routing dump); - unchanged and safe: the next window (same stream), the MTP draft (its own stream; reads the window's final rows and its own K/V, which commit does not write), the adaptive tier thread (expert slots and residency tables only), STRATA_LOGPOS / STRATA_DUMP_FIRST_LOGITS (read run()'s head logits after run() synchronized), QUIT and /unload (the Verifier destructor synchronizes its streams before freeing). --- include/strata/core/verify.hpp | 9 +++++++-- src/core/verify.cpp | 23 +++++++++++++++++++++-- src/program/generate.cpp | 21 ++++++++++++++++++--- 3 files changed, 46 insertions(+), 7 deletions(-) diff --git a/include/strata/core/verify.hpp b/include/strata/core/verify.hpp index 4ddc5269..5717eb4f 100644 --- a/include/strata/core/verify.hpp +++ b/include/strata/core/verify.hpp @@ -121,9 +121,12 @@ public: bool commit(int n_keep, std::string& err); /// commit() returns without waiting for its graph (a single-GPU session sets it): the next window follows it on /// the same stream and the drafter reads nothing it writes, so it overlaps the draft. Whoever reads or writes - /// the session from another stream or the host afterwards (a new request, a checkpoint) synchronizes the device - /// first. STRATA_COMMIT_SYNC=1 keeps the wait. + /// the session from another stream or the host afterwards (a new request, a checkpoint, a snapshot, the prompt + /// path, the end of a run) calls wait_commit() first. STRATA_COMMIT_SYNC=1 keeps the wait. static void set_commit_async(bool on); + /// Waits for the last commit graph when commit() did not (an event recorded after it, not the whole device); + /// false with `err` when it failed. Free when nothing is pending. + bool wait_commit(std::string& err); /// Measurement hook (STRATA_LOGPOS): after run(), write one line per row t of the last window's head - /// "pos target logprob top top_logprob hit extra_logprob target_logprob_without_extra" - where row t is the @@ -217,6 +220,8 @@ private: uint32_t* h_flag_ = nullptr; uint32_t* m_flag_ = nullptr; uint32_t* h_flagA_ = nullptr; uint32_t* m_flagA_ = nullptr; // the GPU plan is in place uint32_t* h_flagB_ = nullptr; uint32_t* m_flagB_ = nullptr; // the PCIe share's DMA copies have landed + cudaEvent_t commit_done_ = nullptr; // recorded after an async commit (set_commit_async); see wait_commit + bool commit_pending_ = false; cudaStream_t copy_ = nullptr; // the copy engine's stream (DMA of missed experts) struct FlagSet { uint32_t* flag; uint32_t value; }; FlagSet flag_sets_[2 * 64 * 2] = {}; // host-function arguments, one per (layer, group) diff --git a/src/core/verify.cpp b/src/core/verify.cpp index 06f8ceaf..839151d6 100644 --- a/src/core/verify.cpp +++ b/src/core/verify.cpp @@ -177,6 +177,7 @@ Verifier::~Verifier() { if (commit_exec_) cudaGraphExecDestroy(commit_exec_); if (cs_) cudaStreamDestroy(cs_); if (copy_) { cudaStreamSynchronize(copy_); cudaStreamDestroy(copy_); } + if (commit_done_) cudaEventDestroy(commit_done_); if (arena_) cudaFree(arena_); void* hosts[] = {h_tok_, h_step_, h_pos_, h_commit_, h_ple_, h_out_, h_x_, h_ids_, h_w_, h_seq_, h_flag_, h_ymiss_, h_flagA_, h_plan_, h_flagB_}; @@ -346,6 +347,10 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState& err = "verify: stream create failed"; return false; } + if (cudaEventCreateWithFlags(&commit_done_, cudaEventDisableTiming) != cudaSuccess) { + err = "verify: event create failed"; + return false; + } // E-6: a layer whose routed experts are all resident is planned on the device (STRATA_VERIFY_DEVICE_PLAN=1: on; // exact, but neutral on RIBPC 1-2 GPUs: off by default) { @@ -1307,10 +1312,14 @@ bool Verifier::commit(int n_keep, std::string& err) { if (le != cudaSuccess) { err = std::string("verify: commit launch: ") + cudaGetErrorString(le); return false; } // set_commit_async: no wait here - the next window runs on the same stream after it, and the drafter (its own // stream) reads only this window's final rows and its own K/V. h_commit_ is next written after the next window's - // results are read, i.e. after this graph has run. - if (!g_commit_async) { + // results are read, i.e. after this graph has run. Everything else waits on commit_done_ (wait_commit). + if (!g_commit_async || next_ != nullptr) { const cudaError_t se = cudaStreamSynchronize(cs_); if (se != cudaSuccess) { err = std::string("verify: commit: ") + cudaGetErrorString(se); return false; } + } else { + const cudaError_t re = cudaEventRecord(commit_done_, cs_); + if (re != cudaSuccess) { err = std::string("verify: commit event: ") + cudaGetErrorString(re); return false; } + commit_pending_ = true; } if (ple_stage()) // stages that share one session must advance it once for (int t = 0; t < n_keep; ++t) { @@ -1321,6 +1330,16 @@ bool Verifier::commit(int n_keep, std::string& err) { return next_ == nullptr || next_->commit(n_keep, err); } +bool Verifier::wait_commit(std::string& err) { + if (commit_pending_) { + const OnDevice on_device(device_); + commit_pending_ = false; + const cudaError_t se = cudaEventSynchronize(commit_done_); + if (se != cudaSuccess) { err = std::string("verify: commit: ") + cudaGetErrorString(se); return false; } + } + return next_ == nullptr || next_->wait_commit(err); +} + bool Verifier::copy_logits(int t, float* host) const { if (next_ != nullptr) return next_->copy_logits(t, host); // a layer split: the head is on the last stage if (head_logits_ == nullptr || host == nullptr || t < 0 || n_vocab_ <= 0) return false; diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 1ec6690b..0eb5ee84 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -4609,8 +4609,12 @@ int main(int argc, char** argv) { }; const bool want_cvec = strata::kernels::cvec().loaded() ? req_cvec != 0 : true; // the last request's final commit may still be running on the verifier's stream (set_commit_async): - // everything below reads, restores or zeroes the session from other streams and the host - cudaDeviceSynchronize(); + // everything below reads, restores or zeroes the session from other streams and the host (the end of the + // last request waited already; this covers a request that ended on an error path) + if (!ver.wait_commit(err)) { + std::printf("ERR %s\n", err.c_str()); + return 1; + } int64_t resume = 0; bool from_live = false; if (o.prompt_cache > 0 && want_cvec == cvec_cached) { @@ -4802,6 +4806,8 @@ int main(int argc, char** argv) { if (!ver.commit(T, e) || !mtp.prefill(ver.final_R_all(), nxt.data(), T, q, e)) return false; q += T; } + // the batched prompt path (other streams), checkpoints and snapshots may follow: the last commit first + if (!ver.wait_commit(e)) return false; const double ms = std::chrono::duration(Clock::now() - pp_t0).count(); std::printf("PP %lld %lld %.0f %.1f\n", (long long) b, (long long) pp_total, ms, ms > 0.0 ? 1000.0 * (double) (b - pp_from) / ms : 0.0); @@ -5121,6 +5127,11 @@ int main(int argc, char** argv) { p += a + 1; } const double decode_ms = std::chrono::duration(Clock::now() - d0).count(); + // the last commit (set_commit_async): the session is complete before anything reads or copies it + if (!ver.wait_commit(err)) { + std::printf("ERR %s\n", err.c_str()); + return 1; + } if (dec_timing && dec_windows > 0) { const DecSnap d1 = dec_snap(); const double w = (double) dec_windows, L = (double) g.n_layers; @@ -5923,6 +5934,11 @@ int main(int argc, char** argv) { std::fprintf(stderr, "strata generate: position %lld, %lld tokens, %lld rounds\n", (long long) p, (long long) produced.size(), (long long) rounds); } + // the last commit (set_commit_async) before anything reads the session again + if (!ver.wait_commit(err)) { + std::fprintf(stderr, "strata generate: %s\n", err.c_str()); + return 1; + } std::printf("%-24s %lld rounds of %d, drafts accepted %lld of %lld (%.3f), %.2f tokens per round\n", "speculation", (long long) rounds, o.spec, (long long) drafts_ok, (long long) drafts_total, drafts_total > 0 ? (double) drafts_ok / (double) drafts_total : 0.0, @@ -6020,7 +6036,6 @@ int main(int argc, char** argv) { for (int64_t t : produced) std::printf(" %lld", (long long) t); std::printf("\n"); const double decode_ms = decoded > 0 ? total_ms / (double) decoded : 0.0; - cudaDeviceSynchronize(); // the last commit (set_commit_async) before anything reads the session std::printf("%-24s %lld tokens in %.1f ms -> %.2f tok/s\n", "decode", (long long) decoded, total_ms, decode_ms > 0.0 ? 1000.0 / decode_ms : 0.0); if (n_prompt > 1) From 2cf197f894a488e03b1f201f906b6c8617ab120e Mon Sep 17 00:00:00 2001 From: BlueKingMuch <53972523+BlueKingMuch@users.noreply.github.com> Date: Wed, 30 Sep 2026 20:21:15 +0000 Subject: [PATCH 25/48] hc: the multi-token hyper-connection read split finer, checked bit for bit on each card (STRATA_HC_V2) The multi-token read (verify windows, the MTP drafter) keeps v1's arithmetic exactly - every sum over the same elements in the same order - and only splits the work differently: - the norm (v2, v3): one block per token and stream instead of one per token. Each thread visits the elements of its stream in the order it did in v1, so every sum of squares and rs is v1's; R' * w_norm is recomputed and scaled once (the same two roundings as v1's store and in-place scale). On an RTX 4080 SUPER: 0.58 -> 0.23 ms per 4-token round. - the down projection (v3): v1's rows per block and lane order, but the activations arrive by cp.async in half-stream tiles, two in flight, in a bank-conflict-free two-plane layout, and the next tile's weights load while the current one is used. A tile is 160 = 5 x 32 chunks, so a lane still accumulates its chunks lane + 32 q in ascending order. Before sm_80 and on HIP the staging is a plain copy (the same bits). Verifier::init runs fused_gr_check once per card: v1, v2, v3 and the single-token read on random bf16 weights and inputs (1..8 tokens, with and without the pending write), every output compared bit for bit; the newest variant that agrees runs on that card and the log says which. A card that has not been checked runs v1. STRATA_HC_V2=0 keeps v1, =2 stops at v2. The down kernels carry as many tokens per launch as the card's shared memory allows (v3: 10 KB per token), as v1 did. Rebased onto 0.1.31 (Niko1221): v1 is 0.1.31's default read unchanged - the TILEV 1280/2560 down kernel (sm_75's small tile), the pre-Volta capacity rule, STRATA_EMULATE_CC - moved into down_chunk()/launch_multi(); main's opt-in STRATA_GR_V3 path (#186, another summation order) still comes first in fused_gr_read_multi, and the card's check calls launch_multi(1) directly, so it compares against the default read whatever STRATA_GR_V3 says. --- include/strata/kernels/fused_gr.hpp | 11 + src/core/verify.cpp | 1 + src/kernels/cuda/fused_gr.cu | 569 ++++++++++++++++++++++++---- 3 files changed, 501 insertions(+), 80 deletions(-) diff --git a/include/strata/kernels/fused_gr.hpp b/include/strata/kernels/fused_gr.hpp index ba4e7c9d..1860f824 100644 --- a/include/strata/kernels/fused_gr.hpp +++ b/include/strata/kernels/fused_gr.hpp @@ -49,4 +49,15 @@ constexpr int kFusedGrMaxT = 8; void fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, void* stream, unsigned long long* stamp_buf = nullptr, int stamp_i0 = 0); +/// The multi read's variants, all computing every output with v1's operations in v1's order, so bitwise v1's and the +/// single-token read's: v1 (the norm one block per token, the down projection on 41 blocks), v2 (the norm one block +/// per token and stream, then v1's down projection) and v3 (v2's norm, and the down projection's activations staged +/// ahead by cp.async, two half-stream tiles in flight, bank-conflict-free). `fused_gr_check` runs all of them and +/// the single-token read on the current card with random weights and inputs (1..8 tokens, with and without the +/// pending write) and from then on uses there the newest one that agrees with v1 bit for bit; STRATA_HC_V2=0 keeps +/// v1, =2 stops at v2. It runs once per card (Verifier::init calls it) and prints which one runs. On a card it +/// has not checked, `fused_gr_variant` is v1 unless STRATA_HC_V2=2 or 3 names a variant. +void fused_gr_check(); +int fused_gr_variant(); + } // namespace strata::kernels diff --git a/src/core/verify.cpp b/src/core/verify.cpp index 839151d6..ebe0c897 100644 --- a/src/core/verify.cpp +++ b/src/core/verify.cpp @@ -195,6 +195,7 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState& } release_gpu_fn().store(&release_live_verifiers); cudaGetDevice(&device_); // a layer split's stage on another GPU: its streams, graphs and buffers live there + strata::kernels::fused_gr_check(); // once per card: which bitwise-equal hyper-connection read runs there wt_ = &wt; g_ = &g; ss_ = &ss; diff --git a/src/kernels/cuda/fused_gr.cu b/src/kernels/cuda/fused_gr.cu index fa8a8adc..5a0c6b4f 100644 --- a/src/kernels/cuda/fused_gr.cu +++ b/src/kernels/cuda/fused_gr.cu @@ -6,8 +6,13 @@ #include +#include #include #include +#include +#include +#include +#include namespace strata::kernels { namespace { @@ -490,6 +495,306 @@ __global__ void __launch_bounds__(THREADS) gr_up_v3_kernel(GrMulti m, const floa m.a[k].mixed[d0 + col] = sum / (float) HC; } } +// ================================ v2 / v3: the same arithmetic, split differently ================================ +// Every variant computes each output with exactly v1's operations in v1's order (so bitwise v1 and the single-token +// read); only who does what, and when, changes. `fused_gr_check` compares them on the card before a verify window +// uses them (STRATA_HC_V2 below). +// - the norm (v2 and v3): one block per token AND stream instead of one per token. Each thread visits exactly the +// elements, in the order, it visited for that stream in v1, so every sum of squares and rs is the same; then it +// recomputes its R' * w_norm and writes it times rs (v1 stored the product and scaled it in place: the same two +// roundings). On an RTX 4080 SUPER, v1's norm took 0.58 ms per 4-token round (96 launches of 1-4 blocks), this +// one 0.23 ms. +// - the down projection, v2: v1's kernel. +// - the down projection, v3: v1's 8 rows per block and lane order, but the activations arrive by cp.async in +// half-stream tiles, two in flight, so no thread waits on a chain of loads, and they sit in shared memory as two +// planes (floats 0-3 and 4-7 of every 8), so a warp's reads hit no bank twice. The next tile's weights are +// loaded while the current one is used. A tile is 160 = 5 x 32 chunks of 8, so a lane still accumulates its +// chunks lane + 32 q in ascending order, as in v1 with either tile. Before sm_80 (and on HIP) the staging is a +// plain copy: the same bits, only not asynchronous. +constexpr int H_TILE = 1280; // v3 tile: half a stream = 160 chunks of 8, 5 per lane +constexpr int HQ = H_TILE / 8 / 32; +constexpr int N_HTILES = D / H_TILE; // 8 +static_assert(N % H_TILE == 0, "a v3 tile never straddles two streams"); +static_assert(H_TILE % 256 == 0, "a v3 tile holds whole rounds of 32 chunks: the lane order stays v1's"); + +__global__ void __launch_bounds__(THREADS) gr_norm_multi2_kernel(GrMulti m) { + __shared__ float part[WARPS]; + __shared__ float s_rs; + const FusedGrArgs& a = m.a[blockIdx.x]; + const int c = blockIdx.y; + float* xn = m.xn + (size_t) blockIdx.x * D; + const int t = threadIdx.x, lane = t & 31, warp = t >> 5; + const float gw = a.apply ? 2.0f * sigmoidf_(a.inj_prev[c] / (float) HC) : 0.0f; + float ss = 0.0f; + for (int i = t * 4; i < D; i += THREADS * 4) { + if (i / N != c) continue; // another stream's element: another block's + const int d = i - c * N; + float4 r = *reinterpret_cast(a.R + i); + if (a.apply) { + const float4 b = *reinterpret_cast(a.bo_prev + d); + r.x = fmaf(b.x, gw, r.x); r.y = fmaf(b.y, gw, r.y); + r.z = fmaf(b.z, gw, r.z); r.w = fmaf(b.w, gw, r.w); + } + const float sq = r.x * r.x + r.y * r.y + r.z * r.z + r.w * r.w; + ss += sq; + } + const float v = warp_sum(ss); + if (lane == 0) part[warp] = v; + __syncthreads(); + if (t == 0) { + float s = 0.0f; + for (int w = 0; w < WARPS; ++w) s += part[w]; + s_rs = rsqrtf(s / (float) N + a.eps); + a.rs[c] = s_rs; + } + __syncthreads(); + const float rs = s_rs; + for (int i = t * 4; i < D; i += THREADS * 4) { + if (i / N != c) continue; + const int d = i - c * N; + float4 r = *reinterpret_cast(a.R + i); + if (a.apply) { + const float4 b = *reinterpret_cast(a.bo_prev + d); + r.x = fmaf(b.x, gw, r.x); r.y = fmaf(b.y, gw, r.y); + r.z = fmaf(b.z, gw, r.z); r.w = fmaf(b.w, gw, r.w); + } + const float4 g = *reinterpret_cast(a.w_norm + i); + const float px = r.x * g.x, py = r.y * g.y, pz = r.z * g.z, pw = r.w * g.w; + *reinterpret_cast(xn + i) = make_float4(px * rs, py * rs, pz * rs, pw * rs); + } +} + +#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800 && !defined(__HIPCC__) +#define STRATA_GR_CP_ASYNC 1 +#endif +__device__ __forceinline__ void cp_async16(void* smem, const void* gmem) { +#if defined(STRATA_GR_CP_ASYNC) + const unsigned sa = (unsigned) __cvta_generic_to_shared(smem); + asm volatile("cp.async.cg.shared.global [%0], [%1], 16;\n" ::"r"(sa), "l"(gmem) : "memory"); +#else + *reinterpret_cast(smem) = *reinterpret_cast(gmem); +#endif +} +__device__ __forceinline__ void cp_async_commit() { +#if defined(STRATA_GR_CP_ASYNC) + asm volatile("cp.async.commit_group;\n" ::: "memory"); +#endif +} +__device__ __forceinline__ void cp_async_wait1() { +#if defined(STRATA_GR_CP_ASYNC) + asm volatile("cp.async.wait_group 1;\n" ::: "memory"); +#endif +} +__device__ __forceinline__ void cp_async_wait0() { +#if defined(STRATA_GR_CP_ASYNC) + asm volatile("cp.async.wait_group 0;\n" ::: "memory"); +#endif +} + +// `dot8` with its 8 activations as two float4: the same eight fmaf in the same order +__device__ __forceinline__ float dot8v(const uint4 w, const float4 x0, const float4 x1) { + float acc = 0.0f; + acc = fmaf(__uint_as_float(w.x << 16), x0.x, acc); + acc = fmaf(__uint_as_float(w.x & 0xffff0000u), x0.y, acc); + acc = fmaf(__uint_as_float(w.y << 16), x0.z, acc); + acc = fmaf(__uint_as_float(w.y & 0xffff0000u), x0.w, acc); + acc = fmaf(__uint_as_float(w.z << 16), x1.x, acc); + acc = fmaf(__uint_as_float(w.z & 0xffff0000u), x1.y, acc); + acc = fmaf(__uint_as_float(w.w << 16), x1.z, acc); + acc = fmaf(__uint_as_float(w.w & 0xffff0000u), x1.w, acc); + return acc; +} + +// Stage tile `h` of every token into `buf`: [T][2 planes][160 chunks] float4, plane 0 = floats 0-3 of a chunk. +__device__ __forceinline__ void stage_htile(const GrMulti& m, int T, int h, float4* buf, int t) { + for (int i = t; i < T * (H_TILE / 4); i += THREADS) { + const int k = i / (H_TILE / 4), s4 = i - k * (H_TILE / 4); // s4: float4 of the tile, chunk s4/2, half s4&1 + const float* src = m.xn + (size_t) k * D + (size_t) h * H_TILE + (size_t) s4 * 4; + cp_async16(buf + (size_t) k * (H_TILE / 4) + (s4 & 1) * (H_TILE / 8) + (s4 >> 1), src); + } +} + +__global__ void __launch_bounds__(THREADS) gr_down_multi3_kernel(GrMulti m) { + extern __shared__ __align__(16) float4 hbuf[]; // 2 buffers x [T][2][160] float4 + const int t = threadIdx.x, lane = t & 31, warp = t >> 5; + const int T = m.T; + const bool inject_block = blockIdx.x == DOWN_BLOCKS; + const int row = inject_block ? warp : blockIdx.x * WARPS + warp; + const bool active = !(inject_block && (m.a[0].w_inject == nullptr || warp >= HC)); + const uint16_t* wrow = (inject_block ? m.a[0].w_inject : m.a[0].w_down) + (size_t) (active ? row : 0) * D; + const uint4* w4 = reinterpret_cast(wrow); + const size_t buf_f4 = (size_t) T * (H_TILE / 4); // float4 per buffer (the second one follows the first) + float acc[kFusedGrMaxT]; +#pragma unroll + for (int k = 0; k < kFusedGrMaxT; ++k) acc[k] = 0.0f; + uint4 wv[HQ], wnext[HQ]; + if (active) { +#pragma unroll + for (int q = 0; q < HQ; ++q) wv[q] = __ldg(w4 + lane + 32 * q); + } + stage_htile(m, T, 0, hbuf, t); + cp_async_commit(); + stage_htile(m, T, 1, hbuf + buf_f4, t); + cp_async_commit(); +#pragma unroll 1 + for (int h = 0; h < N_HTILES; ++h) { + if (active && h + 1 < N_HTILES) { +#pragma unroll + for (int q = 0; q < HQ; ++q) wnext[q] = __ldg(w4 + (h + 1) * (H_TILE / 8) + lane + 32 * q); + } + if (h + 1 < N_HTILES) cp_async_wait1(); // tile h has landed (h + 1 may still be on its way) + else cp_async_wait0(); + __syncthreads(); + const float4* cur = hbuf + (h & 1) * buf_f4; + if (active) { +#pragma unroll + for (int q = 0; q < HQ; ++q) { + const int j = lane + 32 * q; +#pragma unroll + for (int k = 0; k < kFusedGrMaxT; ++k) { + if (k < T) { + const float4* pk = cur + (size_t) k * (H_TILE / 4); + acc[k] += dot8v(wv[q], pk[j], pk[H_TILE / 8 + j]); + } + } + } + } + __syncthreads(); // every warp is done with buffer h & 1 + if (h + 2 < N_HTILES) stage_htile(m, T, h + 2, hbuf + (h & 1) * buf_f4, t); + cp_async_commit(); // an empty group at the end keeps the wait counts simple + if (h + 1 < N_HTILES) { +#pragma unroll + for (int q = 0; q < HQ; ++q) wv[q] = wnext[q]; + } + } + if (!active) return; + float s[kFusedGrMaxT]; +#pragma unroll + for (int k = 0; k < kFusedGrMaxT; ++k) s[k] = k < T ? warp_sum(acc[k]) : 0.0f; + // lane k writes token k (every lane holds every sum after the xor reduction) +#pragma unroll + for (int k = 0; k < kFusedGrMaxT; ++k) { + if (k >= T || lane != k) continue; + if (inject_block) { + m.a[k].inject_out[row] = s[k]; + } else { + const float x = s[k] / (float) HC; + m.a[k].lo[row] = x / (1.0f + __expf(-x)); + } + } +} + +// The tokens a down kernel may carry in one launch on the current card, and (v1) its tile: v1 stages n_tok * TILEV +// floats (1280 on sm_75, 2560 elsewhere), v3 two tiles of n_tok * H_TILE. The shared-memory opt-in is set here once +// per device (a per-DEVICE setting: a layer split runs these kernels on two cards). +int down_chunk(bool v3, int* tile_out) { + static bool attr[64] = {}; + static int chunk[64] = {}; // tokens the v1 down kernel may carry in one launch on this card + static int chunk3[64] = {}; // the same for v3 + static int tile[64] = {}; // the v1 down kernel's TILEV on this card (1280 on sm_75, 2560 elsewhere; see above) + int dev = 0; + cudaGetDevice(&dev); + if (dev < 0 || dev >= 64) { + *tile_out = 2560; + return kFusedGrMaxT; + } + if (!attr[dev]) { + int optin = 0; + cudaDeviceGetAttribute(&optin, cudaDevAttrMaxSharedMemoryPerBlockOptin, dev); + optin = strata::smem_optin_of(optin); // STRATA_EMULATE_CC (tests only) + // the down kernel stages n_tok*TILEV floats of dynamic shared memory - 80 KB at the full 8 tokens of the + // CUDA tile. sm_75 gets the smaller tile: all eight tokens fit one 40 KiB launch there (no more slicing), + // the TQ-5 prefetch holds half the registers, and the smaller blocks raise how many of the 41-block grid + // share an SM. Cards whose opt-in is still below that (or that report no opt-in at all) slice the tokens; + // the down kernel's outputs (lo, inject_out) are strictly per-token, so the chunk boundaries are safe, and + // the up kernel below still sees every token of the batch in one launch. +#if defined(__HIPCC__) + const bool small_tile = true; // all eight tokens fit gfx1100's 64 KiB LDS at this tile +#else + int cc_maj = 0, cc_min = 0; + cudaDeviceGetAttribute(&cc_maj, cudaDevAttrComputeCapabilityMajor, dev); + cudaDeviceGetAttribute(&cc_min, cudaDevAttrComputeCapabilityMinor, dev); + const bool small_tile = strata::cc_major_of(cc_maj) * 10 + strata::cc_minor_of(cc_min) == 75; +#endif + const int tv = small_tile ? 1280 : 2560; + tile[dev] = tv; + int want = (int) (kFusedGrMaxT * tv * sizeof(float)); + if (optin > 0 && want > optin) want = optin; + if (small_tile) { + cudaFuncSetAttribute(gr_down_multi_kernel<1280>, cudaFuncAttributeMaxDynamicSharedMemorySize, want); + } else { + cudaFuncSetAttribute(gr_down_multi_kernel<2560>, cudaFuncAttributeMaxDynamicSharedMemorySize, want); + } + int want3 = (int) (2 * kFusedGrMaxT * H_TILE * sizeof(float)); + if (optin > 0 && want3 > optin) want3 = optin; + cudaFuncSetAttribute(gr_down_multi3_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, want3); + cudaGetLastError(); // drop any error the attempt left behind + // The opt-in is a promise a pre-Volta card does not keep: an sm_60 answers 65536 and accepts the + // cudaFuncSetAttribute for 61440 B, then fails the LAUNCH with "invalid argument". What such a card + // will launch is its per-block limit, so the capacity comes from that below sm_70 - the same tokens + // the "no opt-in" branch assumes, but taken from the attribute that is actually enforced. +#if defined(__HIPCC__) + const int usable = optin > 0 ? optin : 48 * 1024; +#else + int cc = 0, per_block = 0; + cudaDeviceGetAttribute(&cc, cudaDevAttrComputeCapabilityMajor, dev); + cudaDeviceGetAttribute(&per_block, cudaDevAttrMaxSharedMemoryPerBlock, dev); + cc = strata::cc_major_of(cc); + const int usable = (cc >= 7 && optin > 0) ? optin : per_block; +#endif + const int capacity = usable / (int) (tv * sizeof(float)); + chunk[dev] = capacity < 1 ? 1 : (capacity > kFusedGrMaxT ? kFusedGrMaxT : capacity); + const int capacity3 = usable / (int) (2 * H_TILE * sizeof(float)); + chunk3[dev] = capacity3 < 1 ? 1 : (capacity3 > kFusedGrMaxT ? kFusedGrMaxT : capacity3); + attr[dev] = true; + } + *tile_out = tile[dev] ? tile[dev] : 2560; + return v3 ? chunk3[dev] : chunk[dev]; +} + +// The multi read as `variant` (1, 2 or 3): the norm, the down projection in launches of as many tokens as fit the +// card, the up projection; the profile's stamps after the norm and after the down projection. Variant 1 is the +// default read exactly as before (never main's opt-in STRATA_GR_V3 path, which fused_gr_read_multi takes first). +void launch_multi(const GrMulti& m, int variant, cudaStream_t st, unsigned long long* stamp_buf, int stamp_i0) { + const int n_tok = m.T; + if (variant >= 2) gr_norm_multi2_kernel<<>>(m); + else gr_norm_multi_kernel<<>>(m); + if (stamp_buf) gpu_stamp(stamp_buf, stamp_i0, (void*) st); + const bool v3 = variant >= 3; + int tv = 2560; + const int chunk_tok = down_chunk(v3, &tv); + const size_t per_tok = (v3 ? (size_t) 2 * H_TILE : (size_t) tv) * sizeof(float); + for (int c0 = 0; c0 < n_tok; c0 += chunk_tok) { + const int ct = n_tok - c0 < chunk_tok ? n_tok - c0 : chunk_tok; + GrMulti c{}; + if (ct == n_tok) { + c = m; + } else { + c.xn = m.xn + (size_t) c0 * D; + c.T = ct; + for (int k = 0; k < ct; ++k) c.a[k] = m.a[c0 + k]; + } + const size_t smem = (size_t) ct * per_tok; + if (v3) gr_down_multi3_kernel<<>>(c); + else if (tv == 1280) gr_down_multi_kernel<1280><<>>(c); + else gr_down_multi_kernel<2560><<>>(c); + } + if (stamp_buf) gpu_stamp(stamp_buf, stamp_i0 + 1, (void*) st); + gr_up_multi_kernel<<>>(m); +} + +/// STRATA_HC_V2: unset = the newest the check accepts (3), 0 = v1, 2 = at most v2, 3 = v3 +int env_variant() { + const char* e = std::getenv("STRATA_HC_V2"); + if (e == nullptr || e[0] == '\0') return 3; + if (e[0] == '0' || e[0] == '1') return 1; + if (e[0] == '2') return 2; + return 3; +} + +// per device: the variant `fused_gr_check` chose (0 = not checked yet) +std::atomic g_variant[64]; + } // namespace void fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, void* stream, unsigned long long* stamp_buf, @@ -552,86 +857,8 @@ void fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, voi } return; } - gr_norm_multi_kernel<<>>(m); - if (stamp_buf) gpu_stamp(stamp_buf, stamp_i0, stream); - // the shared-memory opt-in is a per-DEVICE setting: once per device, not once per process (a layer split - // runs this kernel on two cards) - static bool attr[64] = {}; - static int chunk[64] = {}; // tokens the down kernel may carry in one launch on this card - static int tile[64] = {}; // the down kernel's TILEV on this card (1280 on sm_75, 2560 elsewhere; see above) - int dev = 0; - cudaGetDevice(&dev); - if (dev >= 0 && dev < 64 && !attr[dev]) { - int optin = 0; - cudaDeviceGetAttribute(&optin, cudaDevAttrMaxSharedMemoryPerBlockOptin, dev); - optin = strata::smem_optin_of(optin); // STRATA_EMULATE_CC (tests only) - // the down kernel stages n_tok*TILEV floats of dynamic shared memory - 80 KB at the full 8 tokens of the - // CUDA tile. sm_75 gets the smaller tile: all eight tokens fit one 40 KiB launch there (no more slicing), - // the TQ-5 prefetch holds half the registers, and the smaller blocks raise how many of the 41-block grid - // share an SM. Cards whose opt-in is still below that (or that report no opt-in at all) slice the tokens; - // the down kernel's outputs (lo, inject_out) are strictly per-token, so the chunk boundaries are safe, and - // the up kernel below still sees every token of the batch in one launch. -#if defined(__HIPCC__) - const bool small_tile = true; // all eight tokens fit gfx1100's 64 KiB LDS at this tile -#else - int cc_maj = 0, cc_min = 0; - cudaDeviceGetAttribute(&cc_maj, cudaDevAttrComputeCapabilityMajor, dev); - cudaDeviceGetAttribute(&cc_min, cudaDevAttrComputeCapabilityMinor, dev); - const bool small_tile = strata::cc_major_of(cc_maj) * 10 + strata::cc_minor_of(cc_min) == 75; -#endif - const int tv = small_tile ? 1280 : 2560; - tile[dev] = tv; - int want = (int) (kFusedGrMaxT * tv * sizeof(float)); - if (optin > 0 && want > optin) want = optin; - if (small_tile) { - cudaFuncSetAttribute(gr_down_multi_kernel<1280>, cudaFuncAttributeMaxDynamicSharedMemorySize, want); - } else { - cudaFuncSetAttribute(gr_down_multi_kernel<2560>, cudaFuncAttributeMaxDynamicSharedMemorySize, want); - } - cudaGetLastError(); // drop any error the attempt left behind - // The opt-in is a promise a pre-Volta card does not keep: an sm_60 answers 65536 and accepts the - // cudaFuncSetAttribute for 61440 B, then fails the LAUNCH with "invalid argument". What such a card - // will launch is its per-block limit, so the capacity comes from that below sm_70 - the same tokens - // the "no opt-in" branch assumes, but taken from the attribute that is actually enforced. -#if defined(__HIPCC__) - const int usable = optin > 0 ? optin : 48 * 1024; -#else - int cc = 0, per_block = 0; - cudaDeviceGetAttribute(&cc, cudaDevAttrComputeCapabilityMajor, dev); - cudaDeviceGetAttribute(&per_block, cudaDevAttrMaxSharedMemoryPerBlock, dev); - cc = strata::cc_major_of(cc); - const int usable = (cc >= 7 && optin > 0) ? optin : per_block; -#endif - const int capacity = usable / (int) (tv * sizeof(float)); - chunk[dev] = capacity < 1 ? 1 : (capacity > kFusedGrMaxT ? kFusedGrMaxT : capacity); - attr[dev] = true; - } - const int tv = (dev >= 0 && dev < 64 && tile[dev]) ? tile[dev] : 2560; - const int chunk_tok = (dev >= 0 && dev < 64 && chunk[dev]) ? chunk[dev] : kFusedGrMaxT; - if (chunk_tok >= n_tok) { - const size_t smem = (size_t) n_tok * tv * sizeof(float); - if (tv == 1280) { - gr_down_multi_kernel<1280><<>>(m); - } else { - gr_down_multi_kernel<2560><<>>(m); - } - } else { - for (int c0 = 0; c0 < n_tok; c0 += chunk_tok) { - const int ct = n_tok - c0 < chunk_tok ? n_tok - c0 : chunk_tok; - GrMulti c{}; - c.xn = xn_scratch + (size_t) c0 * D; - c.T = ct; - for (int k = 0; k < ct; ++k) c.a[k] = a[c0 + k]; - const size_t smem = (size_t) ct * tv * sizeof(float); - if (tv == 1280) { - gr_down_multi_kernel<1280><<>>(c); - } else { - gr_down_multi_kernel<2560><<>>(c); - } - } - } - if (stamp_buf) gpu_stamp(stamp_buf, stamp_i0 + 1, stream); - gr_up_multi_kernel<<>>(m); + // the default read (STRATA_GR_V3 unset): v1, or the bitwise-equal v2 / v3 this card's check accepted + launch_multi(m, fused_gr_variant(), st, stamp_buf, stamp_i0); const cudaError_t e = cudaGetLastError(); if (e != cudaSuccess) { std::fprintf(stderr, "fused_gr_read_multi: %s\n", cudaGetErrorString(e)); @@ -660,4 +887,186 @@ void fused_gr_read(const FusedGrArgs& a, void* stream) { } } + +namespace { + +/// v1, v2, v3 and (for one token) the single-token read on random bf16 weights and random inputs, 1..8 tokens, +/// with and without the pending write; every output of v2 and v3 compared with v1's bit for bit (and v1's with the +/// single-token read's). `why[v]` gets the first difference of variant v; false if the check itself could not run. +bool fused_gr_selftest(bool ok_variant[4], std::string why[4]) { + constexpr int TM = kFusedGrMaxT; + constexpr int NV = 4; // sets: 0 = v1, 1 = v2, 2 = v3, 3 = the single-token read + std::mt19937 rng(20260930u); + std::normal_distribution nd(0.0f, 1.0f); + std::vector h_down((size_t) LR * D), h_up((size_t) D * LR), h_inj((size_t) HC * D); + std::vector h_norm(D), h_R((size_t) TM * D), h_bo((size_t) TM * N), h_ip((size_t) TM * HC); + for (auto& w : h_down) w = bf16_from_f32(0.02f * nd(rng)); + for (auto& w : h_up) w = bf16_from_f32(0.05f * nd(rng)); + for (auto& w : h_inj) w = bf16_from_f32(0.02f * nd(rng)); + for (auto& w : h_norm) w = 1.0f + 0.1f * nd(rng); + for (auto& x : h_R) x = nd(rng); + for (auto& x : h_bo) x = 0.5f * nd(rng); + for (auto& x : h_ip) x = 2.0f * nd(rng); + for (int v = 0; v < 4; ++v) { ok_variant[v] = v == 1; why[v].clear(); } + + const size_t n_set = (size_t) TM * (D + D + LR + HC + HC + N); // R_out, xn, lo, rs, inject, mixed (floats) + const size_t bytes = h_down.size() * 2 + h_up.size() * 2 + h_inj.size() * 2 + + (h_norm.size() + h_R.size() + h_bo.size() + h_ip.size() + NV * n_set) * 4 + 32 * 256; + uint8_t* base = nullptr; + if (cudaMalloc((void**) &base, bytes) != cudaSuccess) { + cudaGetLastError(); + why[0] = "no room for the check (" + std::to_string(bytes >> 20) + " MiB)"; + return false; + } + size_t off = 0; + auto take = [&](size_t b) { void* p = base + off; off += (b + 255) / 256 * 256; return p; }; + uint16_t* d_down = (uint16_t*) take(h_down.size() * 2); + uint16_t* d_up = (uint16_t*) take(h_up.size() * 2); + uint16_t* d_inj = (uint16_t*) take(h_inj.size() * 2); + float* d_norm = (float*) take(h_norm.size() * 4); + float* d_R = (float*) take(h_R.size() * 4); + float* d_bo = (float*) take(h_bo.size() * 4); + float* d_ip = (float*) take(h_ip.size() * 4); + struct Set { float *R_out, *xn, *lo, *rs, *inj, *mixed; } set[NV]; + for (Set& x : set) { + x.R_out = (float*) take((size_t) TM * D * 4); x.xn = (float*) take((size_t) TM * D * 4); + x.lo = (float*) take((size_t) TM * LR * 4); x.rs = (float*) take((size_t) TM * HC * 4); + x.inj = (float*) take((size_t) TM * HC * 4); x.mixed = (float*) take((size_t) TM * N * 4); + } + cudaStream_t st = nullptr; + bool ok = off <= bytes && cudaStreamCreateWithFlags(&st, cudaStreamNonBlocking) == cudaSuccess && + cudaMemcpyAsync(d_down, h_down.data(), h_down.size() * 2, cudaMemcpyHostToDevice, st) == cudaSuccess && + cudaMemcpyAsync(d_up, h_up.data(), h_up.size() * 2, cudaMemcpyHostToDevice, st) == cudaSuccess && + cudaMemcpyAsync(d_inj, h_inj.data(), h_inj.size() * 2, cudaMemcpyHostToDevice, st) == cudaSuccess && + cudaMemcpyAsync(d_norm, h_norm.data(), h_norm.size() * 4, cudaMemcpyHostToDevice, st) == cudaSuccess && + cudaMemcpyAsync(d_R, h_R.data(), h_R.size() * 4, cudaMemcpyHostToDevice, st) == cudaSuccess && + cudaMemcpyAsync(d_bo, h_bo.data(), h_bo.size() * 4, cudaMemcpyHostToDevice, st) == cudaSuccess && + cudaMemcpyAsync(d_ip, h_ip.data(), h_ip.size() * 4, cudaMemcpyHostToDevice, st) == cudaSuccess; + if (!ok) why[0] = "setting up the check failed"; + std::vector h1, h2; + // true when equal; false with the first difference in `w` (or a read-back failure in `ok`) + auto same = [&](const float* d1, const float* d2, size_t n, const char* what, int T, int apply, std::string& w) { + h1.resize(n); + h2.resize(n); + if (cudaMemcpyAsync(h1.data(), d1, n * 4, cudaMemcpyDeviceToHost, st) != cudaSuccess || + cudaMemcpyAsync(h2.data(), d2, n * 4, cudaMemcpyDeviceToHost, st) != cudaSuccess || + cudaStreamSynchronize(st) != cudaSuccess) { + why[0] = "reading back the check failed"; + ok = false; + return false; + } + for (size_t i = 0; i < n; ++i) { + uint32_t u1, u2; + std::memcpy(&u1, &h1[i], 4); + std::memcpy(&u2, &h2[i], 4); + if (u1 != u2) { + char buf[192]; + std::snprintf(buf, sizeof buf, "%s differs for %d token(s)%s at %zu (%08x, not %08x)", what, T, + apply ? " with the pending write" : "", i, u2, u1); + w = buf; + return false; + } + } + return true; + }; + auto all_same = [&](const Set& s1, const Set& s2, int T, int apply, std::string& w) { + return same(s1.lo, s2.lo, (size_t) T * LR, "lo", T, apply, w) && + same(s1.rs, s2.rs, (size_t) T * HC, "rs", T, apply, w) && + same(s1.inj, s2.inj, (size_t) T * HC, "inject", T, apply, w) && + same(s1.mixed, s2.mixed, (size_t) T * N, "mixed", T, apply, w) && + same(s1.R_out, s2.R_out, (size_t) T * D, "R", T, apply, w); + }; + ok_variant[2] = ok_variant[3] = ok; + bool single_ok = ok; + for (int apply = 0; apply < 2 && ok; ++apply) { + for (int T = 1; T <= TM && ok; ++T) { + FusedGrArgs a[NV][TM]; + for (int v = 0; v < NV; ++v) { + const size_t span = (size_t) ((uint8_t*) (set[v].mixed + (size_t) TM * N) - (uint8_t*) set[v].R_out); + ok = ok && cudaMemsetAsync(set[v].R_out, 0xFF, span, st) == cudaSuccess; // the whole set + for (int k = 0; k < T; ++k) { + FusedGrArgs& x = a[v][k]; + x.R = d_R + (size_t) k * D; x.R_out = set[v].R_out + (size_t) k * D; x.apply = apply != 0; + x.bo_prev = d_bo + (size_t) k * N; x.inj_prev = d_ip + (size_t) k * HC; + x.w_norm = d_norm; x.w_down = d_down; x.w_up = d_up; x.w_inject = d_inj; x.eps = 1e-6f; + x.lo = set[v].lo + (size_t) k * LR; x.rs = set[v].rs + (size_t) k * HC; + x.inject_out = set[v].inj + (size_t) k * HC; x.mixed = set[v].mixed + (size_t) k * N; + } + } + for (int v = 0; v < 3; ++v) { + GrMulti m; + for (int k = 0; k < T; ++k) m.a[k] = a[v][k]; + m.xn = set[v].xn; + m.T = T; + launch_multi(m, v + 1, st, nullptr, 0); + } + if (T == 1) fused_gr_read(a[3][0], st); + if (cudaGetLastError() != cudaSuccess || cudaStreamSynchronize(st) != cudaSuccess) { + why[0] = "a kernel of the check failed"; + ok = false; + break; + } + if (ok_variant[2] && !all_same(set[0], set[1], T, apply, why[2])) ok_variant[2] = false; + if (ok && ok_variant[3] && !all_same(set[0], set[2], T, apply, why[3])) ok_variant[3] = false; + if (ok && T == 1 && single_ok && !all_same(set[3], set[0], T, apply, why[1])) single_ok = false; + } + } + if (!single_ok && ok) { // v1 itself disagrees with the single-token read + why[2] = why[3] = "v1 differs from the single-token read: " + why[1]; + ok_variant[2] = ok_variant[3] = false; + } + if (st != nullptr) { + cudaStreamSynchronize(st); + cudaStreamDestroy(st); + } + cudaFree(base); + cudaGetLastError(); + if (!ok) ok_variant[2] = ok_variant[3] = false; + return ok; +} + +} // namespace + +int fused_gr_variant() { + int dev = 0; + cudaGetDevice(&dev); + const int v = dev >= 0 && dev < 64 ? g_variant[dev].load() : 0; + if (v > 0) return v; + // not checked on this card: v1, unless STRATA_HC_V2 names a variant (a test such as gr_parity) + const char* e = std::getenv("STRATA_HC_V2"); + return e != nullptr && (e[0] == '2' || e[0] == '3') ? env_variant() : 1; +} + +void fused_gr_check() { + int dev = 0; + cudaGetDevice(&dev); + if (dev < 0 || dev >= 64 || g_variant[dev].load() > 0) return; + const int want = env_variant(); + if (want == 1) { + g_variant[dev].store(1); + std::fprintf(stderr, "strata hc: CUDA%d: the hyper-connection read runs as v1 (STRATA_HC_V2=0)\n", dev); + return; + } + bool okv[4]; + std::string why[4]; + const bool ran = fused_gr_selftest(okv, why); + int use = 1; + if (want >= 3 && okv[3]) use = 3; + else if (okv[2]) use = 2; + g_variant[dev].store(use); + if (!ran) std::fprintf(stderr, "strata hc: CUDA%d: the check of v2/v3 could not run (%s)\n", dev, why[0].c_str()); + for (int v = 3; v >= 2; --v) + if (v <= want && !okv[v] && ran) + std::fprintf(stderr, "strata hc: CUDA%d: v%d differs from v1 on this card - not used: %s\n", dev, v, + why[v].c_str()); + static const char* const what[4] = { + "", "v1 (the norm per token, the down projection on 41 blocks)", + "v2 (the norm per token and stream, then v1's down projection)", + "v3 (the norm per token and stream, the down projection's activations staged ahead by cp.async)"}; + std::fprintf(stderr, "strata hc: CUDA%d: the hyper-connection read runs as %s%s\n", dev, what[use], + use >= 2 ? "; checked bit for bit against v1 on this card (STRATA_HC_V2=2 or 0 for the earlier ones)" + : ""); +} + + } // namespace strata::kernels From 9d0b28df545a2484846716c9540f1be9bd325fb1 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Thu, 1 Oct 2026 08:38:22 +0200 Subject: [PATCH 26/48] #315 follow-up: its variants and switch renamed (plain / split / staged, STRATA_HC_SPLIT) - no clash with STRATA_GR_V3 main already has an opt-in "v3" hyper-connection read (#186, STRATA_GR_V3=1, another summation order); #315's "v2"/"v3" and STRATA_HC_V2 read as the same thing. Now: the plain read (0.1.31's default), split (the norm per token and stream) and staged (split + the down projection's activations staged by cp.async), kHcPlain/kHcSplit/ kHcStaged, gr_norm_split_kernel / gr_down_staged_kernel, and STRATA_HC_SPLIT: unset or 2 = the newest the card's check accepts, 1 = at most split, 0 = the plain read. The check compares against the plain read (launch_multi with kHcPlain) and the single-token read, never against what STRATA_GR_V3 selects; with STRATA_GR_V3=1 that opt-in read still runs first, unchanged. --- include/strata/kernels/fused_gr.hpp | 18 ++-- src/kernels/cuda/fused_gr.cu | 151 +++++++++++++++------------- 2 files changed, 89 insertions(+), 80 deletions(-) diff --git a/include/strata/kernels/fused_gr.hpp b/include/strata/kernels/fused_gr.hpp index 1860f824..40eff30f 100644 --- a/include/strata/kernels/fused_gr.hpp +++ b/include/strata/kernels/fused_gr.hpp @@ -49,14 +49,16 @@ constexpr int kFusedGrMaxT = 8; void fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, void* stream, unsigned long long* stamp_buf = nullptr, int stamp_i0 = 0); -/// The multi read's variants, all computing every output with v1's operations in v1's order, so bitwise v1's and the -/// single-token read's: v1 (the norm one block per token, the down projection on 41 blocks), v2 (the norm one block -/// per token and stream, then v1's down projection) and v3 (v2's norm, and the down projection's activations staged -/// ahead by cp.async, two half-stream tiles in flight, bank-conflict-free). `fused_gr_check` runs all of them and -/// the single-token read on the current card with random weights and inputs (1..8 tokens, with and without the -/// pending write) and from then on uses there the newest one that agrees with v1 bit for bit; STRATA_HC_V2=0 keeps -/// v1, =2 stops at v2. It runs once per card (Verifier::init calls it) and prints which one runs. On a card it -/// has not checked, `fused_gr_variant` is v1 unless STRATA_HC_V2=2 or 3 names a variant. +/// The multi read's variants (#315; not main's opt-in STRATA_GR_V3 read, which sums in another order), all computing +/// every output with the plain read's operations in its order, so bitwise the plain read's and the single-token +/// read's: plain (0.1.31's default: the norm one block per token, the down projection on 41 blocks), split (the norm +/// one block per token and stream, then the plain down projection) and staged (split's norm, and the down +/// projection's activations staged ahead by cp.async, two half-stream tiles in flight, bank-conflict-free). +/// `fused_gr_check` runs all of them and the single-token read on the current card with random weights and inputs +/// (1..8 tokens, with and without the pending write) and from then on uses there the newest one that agrees with the +/// plain read bit for bit; STRATA_HC_SPLIT=0 keeps the plain read, =1 stops at split. It runs once per card +/// (Verifier::init calls it) and prints which one runs. On a card it has not checked, `fused_gr_variant` is the +/// plain read unless STRATA_HC_SPLIT=1 or 2 names a variant. void fused_gr_check(); int fused_gr_variant(); diff --git a/src/kernels/cuda/fused_gr.cu b/src/kernels/cuda/fused_gr.cu index 5a0c6b4f..56bb2f57 100644 --- a/src/kernels/cuda/fused_gr.cu +++ b/src/kernels/cuda/fused_gr.cu @@ -495,29 +495,31 @@ __global__ void __launch_bounds__(THREADS) gr_up_v3_kernel(GrMulti m, const floa m.a[k].mixed[d0 + col] = sum / (float) HC; } } -// ================================ v2 / v3: the same arithmetic, split differently ================================ -// Every variant computes each output with exactly v1's operations in v1's order (so bitwise v1 and the single-token -// read); only who does what, and when, changes. `fused_gr_check` compares them on the card before a verify window -// uses them (STRATA_HC_V2 below). -// - the norm (v2 and v3): one block per token AND stream instead of one per token. Each thread visits exactly the -// elements, in the order, it visited for that stream in v1, so every sum of squares and rs is the same; then it -// recomputes its R' * w_norm and writes it times rs (v1 stored the product and scaled it in place: the same two -// roundings). On an RTX 4080 SUPER, v1's norm took 0.58 ms per 4-token round (96 launches of 1-4 blocks), this -// one 0.23 ms. -// - the down projection, v2: v1's kernel. -// - the down projection, v3: v1's 8 rows per block and lane order, but the activations arrive by cp.async in -// half-stream tiles, two in flight, so no thread waits on a chain of loads, and they sit in shared memory as two -// planes (floats 0-3 and 4-7 of every 8), so a warp's reads hit no bank twice. The next tile's weights are -// loaded while the current one is used. A tile is 160 = 5 x 32 chunks of 8, so a lane still accumulates its -// chunks lane + 32 q in ascending order, as in v1 with either tile. Before sm_80 (and on HIP) the staging is a -// plain copy: the same bits, only not asynchronous. -constexpr int H_TILE = 1280; // v3 tile: half a stream = 160 chunks of 8, 5 per lane +// ================================ #315: split / staged - the same arithmetic, split differently ================== +// The multi read's variants beside the plain read (0.1.31's default; not main's opt-in STRATA_GR_V3 read, which sums +// in another order). Every variant computes each output with exactly the plain read's operations in its order (so +// bitwise the plain read and the single-token read); only who does what, and when, changes. `fused_gr_check` +// compares them on the card before a verify window uses them (STRATA_HC_SPLIT below). +// - the norm (split and staged): one block per token AND stream instead of one per token. Each thread visits +// exactly the elements, in the order, it visited for that stream in the plain read, so every sum of squares and rs +// is the same; then it recomputes its R' * w_norm and writes it times rs (the plain read stored the product and +// scaled it in place: the same two roundings). On an RTX 4080 SUPER, the plain read's norm took 0.58 ms per +// 4-token round (96 launches of 1-4 blocks), this one 0.23 ms. +// - the down projection, split: the plain read's kernel. +// - the down projection, staged: the plain read's 8 rows per block and lane order, but the activations arrive by +// cp.async in half-stream tiles, two in flight, so no thread waits on a chain of loads, and they sit in shared +// memory as two planes (floats 0-3 and 4-7 of every 8), so a warp's reads hit no bank twice. The next tile's +// weights are loaded while the current one is used. A tile is 160 = 5 x 32 chunks of 8, so a lane still +// accumulates its chunks lane + 32 q in ascending order, as in the plain read with either tile. Before sm_80 +// (and on HIP) the staging is a plain copy: the same bits, only not asynchronous. +constexpr int kHcPlain = 1, kHcSplit = 2, kHcStaged = 3; +constexpr int H_TILE = 1280; // staged tile: half a stream = 160 chunks of 8, 5 per lane constexpr int HQ = H_TILE / 8 / 32; constexpr int N_HTILES = D / H_TILE; // 8 -static_assert(N % H_TILE == 0, "a v3 tile never straddles two streams"); -static_assert(H_TILE % 256 == 0, "a v3 tile holds whole rounds of 32 chunks: the lane order stays v1's"); +static_assert(N % H_TILE == 0, "a staged tile never straddles two streams"); +static_assert(H_TILE % 256 == 0, "a staged tile holds whole rounds of 32 chunks: the plain read's lane order"); -__global__ void __launch_bounds__(THREADS) gr_norm_multi2_kernel(GrMulti m) { +__global__ void __launch_bounds__(THREADS) gr_norm_split_kernel(GrMulti m) { __shared__ float part[WARPS]; __shared__ float s_rs; const FusedGrArgs& a = m.a[blockIdx.x]; @@ -614,7 +616,7 @@ __device__ __forceinline__ void stage_htile(const GrMulti& m, int T, int h, floa } } -__global__ void __launch_bounds__(THREADS) gr_down_multi3_kernel(GrMulti m) { +__global__ void __launch_bounds__(THREADS) gr_down_staged_kernel(GrMulti m) { extern __shared__ __align__(16) float4 hbuf[]; // 2 buffers x [T][2][160] float4 const int t = threadIdx.x, lane = t & 31, warp = t >> 5; const int T = m.T; @@ -684,14 +686,14 @@ __global__ void __launch_bounds__(THREADS) gr_down_multi3_kernel(GrMulti m) { } } -// The tokens a down kernel may carry in one launch on the current card, and (v1) its tile: v1 stages n_tok * TILEV -// floats (1280 on sm_75, 2560 elsewhere), v3 two tiles of n_tok * H_TILE. The shared-memory opt-in is set here once -// per device (a per-DEVICE setting: a layer split runs these kernels on two cards). -int down_chunk(bool v3, int* tile_out) { +// The tokens a down kernel may carry in one launch on the current card, and the plain read's tile: the plain read +// stages n_tok * TILEV floats (1280 on sm_75, 2560 elsewhere), staged two tiles of n_tok * H_TILE. The shared-memory +// opt-in is set here once per device (a per-DEVICE setting: a layer split runs these kernels on two cards). +int down_chunk(bool staged, int* tile_out) { static bool attr[64] = {}; - static int chunk[64] = {}; // tokens the v1 down kernel may carry in one launch on this card - static int chunk3[64] = {}; // the same for v3 - static int tile[64] = {}; // the v1 down kernel's TILEV on this card (1280 on sm_75, 2560 elsewhere; see above) + static int chunk[64] = {}; // tokens the plain down kernel may carry in one launch on this card + static int chunk_staged[64] = {}; // the same for staged + static int tile[64] = {}; // the plain down kernel's TILEV on this card (1280 on sm_75, 2560 elsewhere) int dev = 0; cudaGetDevice(&dev); if (dev < 0 || dev >= 64) { @@ -725,9 +727,9 @@ int down_chunk(bool v3, int* tile_out) { } else { cudaFuncSetAttribute(gr_down_multi_kernel<2560>, cudaFuncAttributeMaxDynamicSharedMemorySize, want); } - int want3 = (int) (2 * kFusedGrMaxT * H_TILE * sizeof(float)); - if (optin > 0 && want3 > optin) want3 = optin; - cudaFuncSetAttribute(gr_down_multi3_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, want3); + int want_staged = (int) (2 * kFusedGrMaxT * H_TILE * sizeof(float)); + if (optin > 0 && want_staged > optin) want_staged = optin; + cudaFuncSetAttribute(gr_down_staged_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, want_staged); cudaGetLastError(); // drop any error the attempt left behind // The opt-in is a promise a pre-Volta card does not keep: an sm_60 answers 65536 and accepts the // cudaFuncSetAttribute for 61440 B, then fails the LAUNCH with "invalid argument". What such a card @@ -744,26 +746,27 @@ int down_chunk(bool v3, int* tile_out) { #endif const int capacity = usable / (int) (tv * sizeof(float)); chunk[dev] = capacity < 1 ? 1 : (capacity > kFusedGrMaxT ? kFusedGrMaxT : capacity); - const int capacity3 = usable / (int) (2 * H_TILE * sizeof(float)); - chunk3[dev] = capacity3 < 1 ? 1 : (capacity3 > kFusedGrMaxT ? kFusedGrMaxT : capacity3); + const int capacity_staged = usable / (int) (2 * H_TILE * sizeof(float)); + chunk_staged[dev] = capacity_staged < 1 ? 1 : (capacity_staged > kFusedGrMaxT ? kFusedGrMaxT : capacity_staged); attr[dev] = true; } *tile_out = tile[dev] ? tile[dev] : 2560; - return v3 ? chunk3[dev] : chunk[dev]; + return staged ? chunk_staged[dev] : chunk[dev]; } -// The multi read as `variant` (1, 2 or 3): the norm, the down projection in launches of as many tokens as fit the -// card, the up projection; the profile's stamps after the norm and after the down projection. Variant 1 is the -// default read exactly as before (never main's opt-in STRATA_GR_V3 path, which fused_gr_read_multi takes first). +// The multi read as `variant` (kHcPlain, kHcSplit or kHcStaged): the norm, the down projection in launches of as +// many tokens as fit the card, the up projection; the profile's stamps after the norm and after the down projection. +// kHcPlain is the default read exactly as before (never main's opt-in STRATA_GR_V3 path, which fused_gr_read_multi +// takes first). void launch_multi(const GrMulti& m, int variant, cudaStream_t st, unsigned long long* stamp_buf, int stamp_i0) { const int n_tok = m.T; - if (variant >= 2) gr_norm_multi2_kernel<<>>(m); + if (variant >= kHcSplit) gr_norm_split_kernel<<>>(m); else gr_norm_multi_kernel<<>>(m); if (stamp_buf) gpu_stamp(stamp_buf, stamp_i0, (void*) st); - const bool v3 = variant >= 3; + const bool staged = variant >= kHcStaged; int tv = 2560; - const int chunk_tok = down_chunk(v3, &tv); - const size_t per_tok = (v3 ? (size_t) 2 * H_TILE : (size_t) tv) * sizeof(float); + const int chunk_tok = down_chunk(staged, &tv); + const size_t per_tok = (staged ? (size_t) 2 * H_TILE : (size_t) tv) * sizeof(float); for (int c0 = 0; c0 < n_tok; c0 += chunk_tok) { const int ct = n_tok - c0 < chunk_tok ? n_tok - c0 : chunk_tok; GrMulti c{}; @@ -775,7 +778,7 @@ void launch_multi(const GrMulti& m, int variant, cudaStream_t st, unsigned long for (int k = 0; k < ct; ++k) c.a[k] = m.a[c0 + k]; } const size_t smem = (size_t) ct * per_tok; - if (v3) gr_down_multi3_kernel<<>>(c); + if (staged) gr_down_staged_kernel<<>>(c); else if (tv == 1280) gr_down_multi_kernel<1280><<>>(c); else gr_down_multi_kernel<2560><<>>(c); } @@ -783,13 +786,13 @@ void launch_multi(const GrMulti& m, int variant, cudaStream_t st, unsigned long gr_up_multi_kernel<<>>(m); } -/// STRATA_HC_V2: unset = the newest the check accepts (3), 0 = v1, 2 = at most v2, 3 = v3 +/// STRATA_HC_SPLIT: unset or 2 = the newest the check accepts (staged), 1 = at most split, 0 = the plain read int env_variant() { - const char* e = std::getenv("STRATA_HC_V2"); - if (e == nullptr || e[0] == '\0') return 3; - if (e[0] == '0' || e[0] == '1') return 1; - if (e[0] == '2') return 2; - return 3; + const char* e = std::getenv("STRATA_HC_SPLIT"); + if (e == nullptr || e[0] == '\0') return kHcStaged; + if (e[0] == '0') return kHcPlain; + if (e[0] == '1') return kHcSplit; + return kHcStaged; } // per device: the variant `fused_gr_check` chose (0 = not checked yet) @@ -890,12 +893,13 @@ void fused_gr_read(const FusedGrArgs& a, void* stream) { namespace { -/// v1, v2, v3 and (for one token) the single-token read on random bf16 weights and random inputs, 1..8 tokens, -/// with and without the pending write; every output of v2 and v3 compared with v1's bit for bit (and v1's with the -/// single-token read's). `why[v]` gets the first difference of variant v; false if the check itself could not run. +/// The plain read, split, staged and (for one token) the single-token read on random bf16 weights and random inputs, +/// 1..8 tokens, with and without the pending write; every output of split and staged compared with the plain read's +/// bit for bit (and the plain read's with the single-token read's). `why[v]` gets the first difference of variant +/// v; false if the check itself could not run. bool fused_gr_selftest(bool ok_variant[4], std::string why[4]) { constexpr int TM = kFusedGrMaxT; - constexpr int NV = 4; // sets: 0 = v1, 1 = v2, 2 = v3, 3 = the single-token read + constexpr int NV = 4; // sets: 0 = plain, 1 = split, 2 = staged, 3 = single-token std::mt19937 rng(20260930u); std::normal_distribution nd(0.0f, 1.0f); std::vector h_down((size_t) LR * D), h_up((size_t) D * LR), h_inj((size_t) HC * D); @@ -1011,8 +1015,8 @@ bool fused_gr_selftest(bool ok_variant[4], std::string why[4]) { if (ok && T == 1 && single_ok && !all_same(set[3], set[0], T, apply, why[1])) single_ok = false; } } - if (!single_ok && ok) { // v1 itself disagrees with the single-token read - why[2] = why[3] = "v1 differs from the single-token read: " + why[1]; + if (!single_ok && ok) { // the plain read itself disagrees with the single-token read + why[2] = why[3] = "the plain read differs from the single-token read: " + why[1]; ok_variant[2] = ok_variant[3] = false; } if (st != nullptr) { @@ -1032,9 +1036,9 @@ int fused_gr_variant() { cudaGetDevice(&dev); const int v = dev >= 0 && dev < 64 ? g_variant[dev].load() : 0; if (v > 0) return v; - // not checked on this card: v1, unless STRATA_HC_V2 names a variant (a test such as gr_parity) - const char* e = std::getenv("STRATA_HC_V2"); - return e != nullptr && (e[0] == '2' || e[0] == '3') ? env_variant() : 1; + // not checked on this card: the plain read, unless STRATA_HC_SPLIT names a variant (a test such as gr_parity) + const char* e = std::getenv("STRATA_HC_SPLIT"); + return e != nullptr && (e[0] == '1' || e[0] == '2') ? env_variant() : kHcPlain; } void fused_gr_check() { @@ -1042,30 +1046,33 @@ void fused_gr_check() { cudaGetDevice(&dev); if (dev < 0 || dev >= 64 || g_variant[dev].load() > 0) return; const int want = env_variant(); - if (want == 1) { - g_variant[dev].store(1); - std::fprintf(stderr, "strata hc: CUDA%d: the hyper-connection read runs as v1 (STRATA_HC_V2=0)\n", dev); + if (want == kHcPlain) { + g_variant[dev].store(kHcPlain); + std::fprintf(stderr, "strata hc: CUDA%d: the hyper-connection read runs as the plain one (STRATA_HC_SPLIT=0)\n", + dev); return; } bool okv[4]; std::string why[4]; const bool ran = fused_gr_selftest(okv, why); - int use = 1; - if (want >= 3 && okv[3]) use = 3; - else if (okv[2]) use = 2; + int use = kHcPlain; + if (want >= kHcStaged && okv[kHcStaged]) use = kHcStaged; + else if (okv[kHcSplit]) use = kHcSplit; g_variant[dev].store(use); - if (!ran) std::fprintf(stderr, "strata hc: CUDA%d: the check of v2/v3 could not run (%s)\n", dev, why[0].c_str()); - for (int v = 3; v >= 2; --v) + if (!ran) + std::fprintf(stderr, "strata hc: CUDA%d: the check of split/staged could not run (%s)\n", dev, why[0].c_str()); + static const char* const name[4] = {"", "plain", "split", "staged"}; + for (int v = kHcStaged; v >= kHcSplit; --v) if (v <= want && !okv[v] && ran) - std::fprintf(stderr, "strata hc: CUDA%d: v%d differs from v1 on this card - not used: %s\n", dev, v, - why[v].c_str()); + std::fprintf(stderr, "strata hc: CUDA%d: the %s read differs from the plain read on this card - not used: " + "%s\n", dev, name[v], why[v].c_str()); static const char* const what[4] = { - "", "v1 (the norm per token, the down projection on 41 blocks)", - "v2 (the norm per token and stream, then v1's down projection)", - "v3 (the norm per token and stream, the down projection's activations staged ahead by cp.async)"}; + "", "the plain read (the norm per token, the down projection on 41 blocks)", + "split (the norm per token and stream, then the plain read's down projection)", + "staged (the norm per token and stream, the down projection's activations staged ahead by cp.async)"}; std::fprintf(stderr, "strata hc: CUDA%d: the hyper-connection read runs as %s%s\n", dev, what[use], - use >= 2 ? "; checked bit for bit against v1 on this card (STRATA_HC_V2=2 or 0 for the earlier ones)" - : ""); + use >= kHcSplit ? "; checked bit for bit against the plain read on this card (STRATA_HC_SPLIT=1 or 0 " + "for the earlier ones)" : ""); } From 4da8bfcbf9e0a8f7c025728b0e473b42d4d2f585 Mon Sep 17 00:00:00 2001 From: BlueKingMuch <53972523+BlueKingMuch@users.noreply.github.com> Date: Wed, 30 Sep 2026 06:42:51 +0000 Subject: [PATCH 27/48] ple: keep the SSD awake while rows are read (STRATA_SSD_KEEPALIVE) Some SSDs (here a WD_BLACK SN7100 on Windows 11) drop into a power state after ~250 ms without a command and stall the next reads 50-150 ms; the NVMe idle timeouts of Windows' power plan do not change it. In decode that hits the first read after a pause: at the start of a request, or after a few rounds whose rows all came from the row cache. --ple-io ram, which avoids the reads altogether, is not available on Windows. The reader's worker now reads one page of the table (a different one each time) when no read has gone out for 100 ms, until 60 s after the last issue; then the SSD may sleep until the next request re-arms it. A keep-alive read counts when it completes and stays out of the row-read counters and latencies; the "ple io" line adds "SSD kept awake by N reads (slowest X ms)". A keep-alive read that fails, or cannot be submitted, turns the keep-alive off instead of failing the reader. STRATA_SSD_KEEPALIVE=0 turns it off, =50 shortens the period; STRATA_SSD_KEEPALIVE_WINDOW sets the window in seconds. Only with the I/O worker (the default), not with --ple-sync-submit or --ple-io mmap/ram. The reader's statistics are now copied and reset under the worker's lock (snapshot()), since the worker may be counting a keep-alive read. The selftest checks the period, the window, the re-arm by a ticket the row cache serves, that rows and read counters are untouched, and that the caller-thread mode has none. A scan on that PC (reads after pauses of every length): 0 of 211 bursts stalled after pauses under 200 ms, 35 of 73 after 200 ms and more, 0 of 68 of those with the keep-alive on. --- include/strata/kernels/ngram.hpp | 5 ++ include/strata/ngram/ple_reader.hpp | 14 ++++- src/kernels/ngram.cpp | 10 ++- src/ngram/ple_reader.cpp | 98 +++++++++++++++++++++++++++-- src/ngram/ple_reader_test.cpp | 52 +++++++++++++++ src/program/generate.cpp | 17 +++++ 6 files changed, 186 insertions(+), 10 deletions(-) diff --git a/include/strata/kernels/ngram.hpp b/include/strata/kernels/ngram.hpp index 29698422..33f3eb02 100644 --- a/include/strata/kernels/ngram.hpp +++ b/include/strata/kernels/ngram.hpp @@ -113,6 +113,11 @@ struct PleIoOptions { /// Mmap mode only (`--ple-io ram`): lock the whole mapped table in RAM at open, so no SSD read ever sits on /// the prompt or token path. Needs RAM for the full table. POSIX only (mlock); `locked()` reports the outcome. bool lock = false; + /// Direct mode with the I/O worker only: keep the SSD awake while rows are asked for - one page of the table + /// after this long without a read (0 = off), until `keepalive_window_s` after the last request for rows + /// (see PleReader::set_keepalive). + double keepalive_ms = 0; + double keepalive_window_s = 60; }; /// The PLE table. Held by pointer-to-impl so this header does not drag `` into every diff --git a/include/strata/ngram/ple_reader.hpp b/include/strata/ngram/ple_reader.hpp index 0552ff1e..721645c0 100644 --- a/include/strata/ngram/ple_reader.hpp +++ b/include/strata/ngram/ple_reader.hpp @@ -37,6 +37,8 @@ struct ReaderStats { double submit_us = 0; ///< time spent inside the read submission call (non-zero = it blocks) double read_us_sum = 0; ///< sum of per-read latencies (issue to completion) uint64_t late_injected = 0; ///< reads delayed by fault injection + uint64_t keepalive_reads = 0; ///< pages read only to keep the SSD awake (not in `reads`, `bytes` or latencies) + double keepalive_us_max = 0; ///< the slowest of them std::vector read_us; ///< last <= 65,536 read latencies, for percentiles double percentile(double q) const; }; @@ -68,12 +70,22 @@ public: /// Block until every row of the ticket is in `out_raw`. Returns false on an I/O error (message in `err`). bool collect(Ticket t, std::string& err); + /// Keep the SSD awake while the table is in use (io_thread mode only; call after `open`): when no read has + /// gone out for `period_ms`, the worker reads one page of the table, until `window_s` after the last `issue`. + /// Some SSDs drop into a power state after ~250 ms without a command and stall the next reads 50-150 ms + /// (a WD_BLACK SN7100 on Windows 11; the NVMe idle timeouts of the power plan did not change it), which in + /// decode happens after a few rounds whose rows all came from the row cache. 0 turns it off (the reader's + /// default; generate turns it on, see STRATA_SSD_KEEPALIVE). A keep-alive read that fails turns it off. + void set_keepalive(double period_ms, double window_s); + /// Fault injection for tests and for the plan's P2 exit check: every read completes no earlier than /// `delay_us` after it was issued. 0 disables. void set_injected_delay_us(double delay_us); - /// Read with no ticket in flight (the worker updates these while reads are outstanding). + /// Read with no ticket in flight (the worker updates these while reads are outstanding; with the keep-alive + /// on it may also be counting a keep-alive read - `snapshot` takes a consistent copy). const ReaderStats& stats() const; + ReaderStats snapshot() const; void reset_stats(); uint64_t cache_capacity() const; uint64_t cache_size() const; diff --git a/src/kernels/ngram.cpp b/src/kernels/ngram.cpp index 9def3309..4831f63d 100644 --- a/src/kernels/ngram.cpp +++ b/src/kernels/ngram.cpp @@ -198,6 +198,7 @@ bool PleTable::open(const std::string& gguf_path, std::string& err, const PleIoO close(); return false; } + impl_->reader.set_keepalive(io.keepalive_ms, io.keepalive_window_s); impl_->n_rows = n_rows; } if (io.mode == PleIo::Mmap && io.lock && impl_->data != nullptr) { @@ -317,15 +318,18 @@ void PleTable::set_injected_delay_us(double us) { impl_->reader.set_injected_del std::string PleTable::io_report() const { if (impl_->mode != PleIo::Direct || !impl_->reader.is_open()) return {}; - const strata::ngram::ReaderStats& s = impl_->reader.stats(); - char buf[320]; - std::snprintf(buf, sizeof buf, + const strata::ngram::ReaderStats s = impl_->reader.snapshot(); + char buf[400]; + int n = std::snprintf(buf, sizeof buf, "ple io: %llu rows, %.1f%% row-cache hits, %llu SSD reads (%.1f MB), read p50 %.0f us p99 %.0f us, " "blocked %.3f ms total (submit %.3f ms), cache %llu/%llu rows", (unsigned long long) s.requests, s.requests ? 100.0 * (double) s.cache_hits / (double) s.requests : 0.0, (unsigned long long) s.reads, (double) s.bytes / 1e6, s.percentile(0.5), s.percentile(0.99), s.wait_us / 1000.0, s.submit_us / 1000.0, (unsigned long long) impl_->reader.cache_size(), (unsigned long long) impl_->reader.cache_capacity()); + if (s.keepalive_reads > 0 && n > 0 && n < (int) sizeof buf) + std::snprintf(buf + n, sizeof buf - (size_t) n, ", SSD kept awake by %llu reads (slowest %.1f ms)", + (unsigned long long) s.keepalive_reads, s.keepalive_us_max / 1000.0); return buf; } diff --git a/src/ngram/ple_reader.cpp b/src/ngram/ple_reader.cpp index ff6d5139..e7a3101f 100644 --- a/src/ngram/ple_reader.cpp +++ b/src/ngram/ple_reader.cpp @@ -2,6 +2,7 @@ #include "strata/ngram/ple_reader.hpp" #include +#include #include #include #include @@ -79,6 +80,7 @@ struct Job { uint32_t ticket = 0; std::vector uses; double issued_us = 0; + bool keepalive = false;// no rows and no ticket: it only keeps the SSD awake (`set_keepalive`) }; struct TicketState { @@ -108,6 +110,12 @@ struct PleReader::Impl { size_t ring_pos = 0; double delay_us = 0; std::string error; + // the keep-alive (`set_keepalive`), steady-clock microseconds; `keep_us` 0 = off + double keep_us = 0; + double keep_window_us = 0; + double last_issue_us = 0; // the last `issue` + double last_read_us = 0; // the last read that went out, rows or keep-alive + uint64_t rng = 0x9E3779B97F4A7C15ull; bool threaded = false; bool stop = false; @@ -141,7 +149,14 @@ struct PleReader::Impl { queue.pop_front(); Job& j = inflight[s]; j.issued_us = now_us(); - if (!file.submit(j.offset, slot_buf(s), j.length, s, error)) { + std::string kerr; // a keep-alive read that cannot go out must not fail the reader + if (!file.submit(j.offset, slot_buf(s), j.length, s, j.keepalive ? kerr : error)) { + if (j.keepalive) { // no more of them: the SSD may sleep as before + keep_us = 0; + j.keepalive = false; + free_slots.push_back(s); + continue; + } j.uses.clear(); auto it = tickets.find(j.ticket); if (it != tickets.end() && it->second.pending > 0) --it->second.pending; @@ -149,12 +164,35 @@ struct PleReader::Impl { cancel_queued(); return false; } - stats.submit_us += now_us() - j.issued_us; - ++stats.reads; + last_read_us = j.issued_us; + if (!j.keepalive) { // a keep-alive read counts when it completes (`finish`) + stats.submit_us += now_us() - j.issued_us; + ++stats.reads; + } } return true; } + /// When the next keep-alive read is due, or < 0 when none is: it is off, the reader failed, or no rows + /// were asked for within the window (then the SSD may sleep; the next `issue` re-arms it). + double keepalive_due(double now) const { + if (keep_us <= 0 || !error.empty() || last_issue_us <= 0 || now - last_issue_us > keep_window_us) return -1; + return last_read_us + keep_us; + } + + /// One page of the table, a different one each time, so the SSD really reads (not its controller's buffer). + void queue_keepalive() { + rng ^= rng << 13; + rng ^= rng >> 7; + rng ^= rng << 17; + const uint64_t first = table_offset / PAGE, end = (table_offset + n_rows * (uint64_t) ROW_BYTES) / PAGE; + Job j; + j.offset = (first + (end > first ? rng % (end - first) : 0)) * PAGE; + j.length = PAGE; + j.keepalive = true; + queue.push_back(std::move(j)); + } + bool finish(const Completion& c) { const uint32_t s = (uint32_t) c.tag; if (s >= inflight.size()) { @@ -163,6 +201,17 @@ struct PleReader::Impl { return false; } Job& j = inflight[s]; + if (j.keepalive) { // no rows: it counts once it is done, with how long it took; + if (c.ok) { // a failed one turns the keep-alive off, not the reader + ++stats.keepalive_reads; + stats.keepalive_us_max = std::max(stats.keepalive_us_max, now_us() - j.issued_us); + } else { + keep_us = 0; + } + j.keepalive = false; + free_slots.push_back(s); + return error.empty() ? pump() : true; + } if (!c.ok) { error = "PleReader: a table read failed"; cancel_queued(); @@ -246,7 +295,14 @@ struct PleReader::Impl { void worker_loop() { std::unique_lock lk(mu); for (;;) { - cv_work.wait(lk, [&] { return stop || !queue.empty() || busy(); }); + // Idle: wait for work. While rows are being asked for, the wait ends in time for a keep-alive read. + while (!(stop || !queue.empty() || busy())) { + const double now = now_us(); + const double due = keepalive_due(now); + if (due < 0) cv_work.wait(lk); + else if (now >= due) queue_keepalive(); + else cv_work.wait_for(lk, std::chrono::microseconds(std::max(1000, (int64_t) (due - now)))); + } if (stop && !busy()) break; if (error.empty() && !pump() && error.empty()) error = "PleReader: submit failed"; if (!delayed.empty() && !release_delayed() && error.empty()) error = "PleReader: read failed"; @@ -293,6 +349,10 @@ bool PleReader::open(const std::string& path, uint64_t table_offset, uint64_t n_ for (uint32_t s = max_inflight; s-- > 0;) impl_->free_slots.push_back(s); impl_->cache.init(cache_rows); impl_->error.clear(); + impl_->keep_us = 0; + impl_->last_issue_us = impl_->last_read_us = 0; + impl_->rng = 0x9E3779B97F4A7C15ull ^ (uint64_t) now_us(); + if (impl_->rng == 0) impl_->rng = 1; reset_stats(); impl_->stop = false; impl_->threaded = io_thread; @@ -346,6 +406,8 @@ void PleReader::close() { m.cache.init(0); m.threaded = false; m.stop = false; + m.keep_us = 0; + m.last_issue_us = m.last_read_us = 0; } bool PleReader::is_open() const { return impl_->file.is_open(); } @@ -356,6 +418,9 @@ PleReader::Ticket PleReader::issue(const uint32_t* rows, size_t n, uint8_t* out_ if (m.threaded) lk.lock(); const uint32_t id = m.next_ticket++; if (m.next_ticket == 0) m.next_ticket = 1; + const double now = now_us(); + const bool rearm = m.keep_us > 0 && (m.last_issue_us <= 0 || now - m.last_issue_us > m.keep_window_us); + m.last_issue_us = now; TicketState& ts = m.tickets[id]; std::unordered_map by_page; // aligned offset -> index in `jobs` std::vector jobs; @@ -400,6 +465,8 @@ PleReader::Ticket PleReader::issue(const uint32_t* rows, size_t n, uint8_t* out_ if (has_jobs) { m.cv_work.notify_one(); m.file.wake(); // in case the worker is blocked in the port + } else if (rearm) { + m.cv_work.notify_one(); // the keep-alive had lapsed: start it again } } else if (!m.pump() && m.error.empty()) { m.error = "PleReader: submit failed"; @@ -439,14 +506,33 @@ bool PleReader::collect(Ticket t, std::string& err) { return true; } +void PleReader::set_keepalive(double period_ms, double window_s) { + Impl& m = *impl_; + { + std::lock_guard lk(m.mu); + m.keep_us = m.threaded && period_ms > 0 ? period_ms * 1000.0 : 0.0; + m.keep_window_us = window_s > 0 ? window_s * 1e6 : 0.0; + } + m.cv_work.notify_all(); +} + void PleReader::set_injected_delay_us(double delay_us) { std::lock_guard lk(impl_->mu); impl_->delay_us = delay_us < 0 ? 0 : delay_us; } const ReaderStats& PleReader::stats() const { return impl_->stats; } +ReaderStats PleReader::snapshot() const { + Impl& m = *impl_; + std::unique_lock lk(m.mu, std::defer_lock); + if (m.threaded) lk.lock(); + return m.stats; +} void PleReader::reset_stats() { - impl_->stats = ReaderStats{}; - impl_->ring_pos = 0; + Impl& m = *impl_; + std::unique_lock lk(m.mu, std::defer_lock); + if (m.threaded) lk.lock(); // the worker may be counting a keep-alive read + m.stats = ReaderStats{}; + m.ring_pos = 0; } uint64_t PleReader::cache_capacity() const { return impl_->cache.sets * WAYS; } uint64_t PleReader::cache_size() const { return impl_->cache.used; } diff --git a/src/ngram/ple_reader_test.cpp b/src/ngram/ple_reader_test.cpp index 37e55f3b..86b48624 100644 --- a/src/ngram/ple_reader_test.cpp +++ b/src/ngram/ple_reader_test.cpp @@ -10,6 +10,7 @@ #include "strata/ngram/ple_reader.hpp" #include "strata/platform/direct_file.hpp" +#include #include #include #include @@ -18,6 +19,7 @@ #include #include #include +#include #include namespace ng = strata::ngram; @@ -135,6 +137,56 @@ int selftest(const std::string& dir) { CHECK(now_us() - t0 >= 3000, "injected delay not observed (%.0f us)", now_us() - t0); CHECK(rd.stats().late_injected > 0, "no read was held back"); } + // keep-alive: while rows are asked for, a page goes out after `period` without a read; it stops once the + // window after the last issue has passed, starts again with the next issue (even one the row cache serves), + // and never shows up as a row read or changes a row + { + ng::PleReader rd; + std::string err; + CHECK(rd.open(path, HEADER, N, 16, 4096, err, true), "open: %s", err.c_str()); + rd.set_keepalive(20.0, 0.5); + std::vector rows(16); + for (auto& r : rows) r = rng() % N; + check_rows(rd, rows, N, "keep-alive, first ticket"); + const uint64_t reads0 = rd.snapshot().reads; + const auto nap = [](int ms) { std::this_thread::sleep_for(std::chrono::milliseconds(ms)); }; + nap(300); + const uint64_t k1 = rd.snapshot().keepalive_reads; + CHECK(k1 >= 8 && k1 <= 20, "keep-alive: %llu reads in 300 ms at a 20 ms period", (unsigned long long) k1); + CHECK(rd.snapshot().reads == reads0, "keep-alive reads were counted as row reads"); + nap(600); // the 0.5 s window has passed + const uint64_t k2 = rd.snapshot().keepalive_reads; + nap(300); + const uint64_t k3 = rd.snapshot().keepalive_reads; + CHECK(k3 == k2, "keep-alive went on after the window (%llu -> %llu)", (unsigned long long) k2, + (unsigned long long) k3); + CHECK(k2 <= k1 + 20, "keep-alive: %llu reads by the end of a 0.5 s window", (unsigned long long) k2); + check_rows(rd, rows, N, "keep-alive, cached ticket"); // the row cache serves all 16: no row read + CHECK(rd.snapshot().reads == reads0, "cached rows were read again"); + nap(200); + CHECK(rd.snapshot().keepalive_reads >= k3 + 5, "the keep-alive did not start again (%llu -> %llu)", + (unsigned long long) k3, (unsigned long long) rd.snapshot().keepalive_reads); + std::vector more(2000); + for (auto& r : more) r = rng() % N; + check_rows(rd, more, N, "keep-alive, rows afterwards"); + rd.set_keepalive(0, 0.5); // off + const uint64_t k4 = rd.snapshot().keepalive_reads; + nap(200); + CHECK(rd.snapshot().keepalive_reads <= k4 + 1, "keep-alive went on after it was turned off"); + rd.reset_stats(); + CHECK(rd.snapshot().keepalive_reads == 0 && rd.snapshot().keepalive_us_max == 0, "reset_stats kept keep-alive counts"); + } + { // the caller's thread does the reads: no worker, so no keep-alive + ng::PleReader rd; + std::string err; + CHECK(rd.open(path, HEADER, N, 16, 0, err, false), "open: %s", err.c_str()); + rd.set_keepalive(20.0, 1.0); + std::vector rows(16); + for (auto& r : rows) r = rng() % N; + check_rows(rd, rows, N, "keep-alive, caller thread"); + std::this_thread::sleep_for(std::chrono::milliseconds(150)); + CHECK(rd.snapshot().keepalive_reads == 0, "keep-alive without the worker thread"); + } std::filesystem::remove(path); std::printf("ple_reader selftest: %s\n", g_fail ? "FAILED" : "OK"); return g_fail ? 1 : 0; diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 0eb5ee84..9a468b4e 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -1923,6 +1923,17 @@ int main(int argc, char** argv) { pio.max_inflight = (uint32_t) o.ple_inflight; pio.cache_rows = (uint64_t) o.ple_row_cache; pio.io_thread = !o.ple_sync_submit; + // Keep the SSD awake while rows are being asked for (PleReader::set_keepalive): some SSDs stall the first + // reads 50-150 ms after ~250 ms without a command. STRATA_SSD_KEEPALIVE = ms without a read before one + // page is read anyway (default 100, 0 = off), STRATA_SSD_KEEPALIVE_WINDOW = seconds after the last row + // request that this goes on (default 60; then the SSD may sleep until the next request). + { + const char* ka = std::getenv("STRATA_SSD_KEEPALIVE"); + const char* kw = std::getenv("STRATA_SSD_KEEPALIVE_WINDOW"); + pio.keepalive_ms = ka != nullptr && *ka ? std::clamp(std::atof(ka), 0.0, 10000.0) : 100.0; + pio.keepalive_window_s = kw != nullptr && *kw ? std::clamp(std::atof(kw), 1.0, 86400.0) : 60.0; + if (pio.mode != strata::kernels::PleIo::Direct || !pio.io_thread) pio.keepalive_ms = 0; + } if (!ple_table.open(o.ple_gguf, err, pio)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; @@ -1931,6 +1942,12 @@ int main(int argc, char** argv) { std::fprintf(stderr, "strata generate: PLE table %s (--ple-io ram) in %.1f s\n", ple_table.locked() ? "locked in RAM" : "loaded (not locked)", std::chrono::duration(Clock::now() - tpl).count()); + if (pio.keepalive_ms > 0) + std::fprintf(stderr, "strata generate: the SSD is kept awake while rows are read: one page of the table after " + "%.0f ms without a read, until %.0f s after the last request " + "(STRATA_SSD_KEEPALIVE=0 turns it off)\n", pio.keepalive_ms, pio.keepalive_window_s); + else if (pio.mode == strata::kernels::PleIo::Direct) + std::fprintf(stderr, "strata generate: SSD keep-alive off: the SSD may fall asleep between reads\n"); const strata::core::WeightRef* wk = wt.find("blk.1.ple_key.weight"); const strata::core::WeightRef* wv = wt.find("blk.1.ple_value.weight"); const strata::core::WeightRef* wnk = wt.find("blk.1.ple_norm_key.weight"); From c517862ce24aa567502d8e35884a3fffe2f76edd Mon Sep 17 00:00:00 2001 From: sergiywith Date: Wed, 30 Sep 2026 22:25:39 +0300 Subject: [PATCH 28/48] numerics: saturate the prompt path's FP16 SwiGLU products; log1pf in the unfused GDN gate - prefill/kernels.cu: the SwiGLU products that feed the prompt path's FP16 down projection are clamped to FP16's range (+-65504) before rounding. A token with a massive activation otherwise becomes inf there and NaN after the GEMM, where decode's q8_1 path (range ~8e6) stays finite. - native_gdn_preprocess.cu: the unfused gate softplus used logf(1 + expf(v)), which returns 0 for v below ~-16 (1 + e^v rounds to 1); the fused kernels, gdn.cu and verify_kernels.cu already use log1pf(expf(v)). The two paths now agree. On ordinary prompts nothing moves: first-token KL to main 0, 0.00013, 0 (the run-to-run noise). --- src/kernels/cuda/native_gdn_preprocess.cu | 2 +- src/prefill/kernels.cu | 7 +++++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/src/kernels/cuda/native_gdn_preprocess.cu b/src/kernels/cuda/native_gdn_preprocess.cu index 535cb31d..86b10453 100644 --- a/src/kernels/cuda/native_gdn_preprocess.cu +++ b/src/kernels/cuda/native_gdn_preprocess.cu @@ -92,7 +92,7 @@ __global__ void gate_softplus(const float* __restrict__ alpha, const float* __re const int i = blockIdx.x * blockDim.x + threadIdx.x; if (i >= count) return; const float value = __fadd_rn(alpha[i], dt[i]); - const float softplus = value > 20.0f ? value : logf(1.0f + expf(value)); + const float softplus = value > 20.0f ? value : log1pf(expf(value)); // 1 + e^v loses e^v below ~1e-7 gate[i] = softplus * ssm_a[i]; } diff --git a/src/prefill/kernels.cu b/src/prefill/kernels.cu index 25226735..310a209d 100644 --- a/src/prefill/kernels.cu +++ b/src/prefill/kernels.cu @@ -34,6 +34,9 @@ __device__ __forceinline__ uint16_t bf(float f) { } __device__ __forceinline__ float sigm(float x) { return 1.0f / (1.0f + __expf(-x)); } __device__ __forceinline__ uint16_t hf(float f) { return __half_as_ushort(__float2half_rn(f)); } +// A SwiGLU product for an FP16 GEMM: saturated, so a token with a massive activation cannot turn into inf and then +// NaN in the down projection (decode's q8_1 has room to ~8e6; FP16 ends at 65504) +__device__ __forceinline__ uint16_t hf_sat(float f) { return hf(fminf(fmaxf(f, -65504.0f), 65504.0f)); } // block-wide sum for blockDim.x <= 1024, result broadcast __device__ float block_sum(float v, float* sh) { const int lane = threadIdx.x & 31, w = threadIdx.x >> 5; @@ -486,14 +489,14 @@ __global__ void swiglu_il_kernel(const float* __restrict__ gu, uint16_t* __restr if (i >= n * 640) return; const int64_t r = i / 640, k = i % 640; const float g = gu[r * 1280 + 2 * k], u = gu[r * 1280 + 2 * k + 1]; - h16[i] = hf(g / (1.0f + __expf(-g)) * u); + h16[i] = hf_sat(g / (1.0f + __expf(-g)) * u); } __global__ void swiglu_pair_kernel(const float* __restrict__ g, const float* __restrict__ u, uint16_t* __restrict__ h16, int64_t n) { const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; if (i >= n * 640) return; const float a = g[i]; - h16[i] = hf(a / (1.0f + __expf(-a)) * u[i]); + h16[i] = hf_sat(a / (1.0f + __expf(-a)) * u[i]); } __global__ void gather_rows16_kernel(const uint16_t* __restrict__ x, const int32_t* __restrict__ src, uint16_t* __restrict__ dst, int64_t n, int64_t width) { From 6280f653c8b0a7de1e0a1724ad073d8e35247afb Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Thu, 1 Oct 2026 08:38:59 +0200 Subject: [PATCH 29/48] #281 follow-up: the saturated FP16 SwiGLU product keeps a NaN a NaN fmaxf(NaN, -65504) is -65504, so #281's clamp turned a NaN product into -65504 and the prompt path went on with a plausible value where it used to show the NaN (STRATA_DBG_NAN and the NaN checks find it there). isnan(x) ? x : clamp(x): only +-inf (and finite values from 65520 up, which rounded to inf) saturate; everything else is unchanged. --- src/prefill/kernels.cu | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/prefill/kernels.cu b/src/prefill/kernels.cu index 310a209d..28e8d139 100644 --- a/src/prefill/kernels.cu +++ b/src/prefill/kernels.cu @@ -35,8 +35,9 @@ __device__ __forceinline__ uint16_t bf(float f) { __device__ __forceinline__ float sigm(float x) { return 1.0f / (1.0f + __expf(-x)); } __device__ __forceinline__ uint16_t hf(float f) { return __half_as_ushort(__float2half_rn(f)); } // A SwiGLU product for an FP16 GEMM: saturated, so a token with a massive activation cannot turn into inf and then -// NaN in the down projection (decode's q8_1 has room to ~8e6; FP16 ends at 65504) -__device__ __forceinline__ uint16_t hf_sat(float f) { return hf(fminf(fmaxf(f, -65504.0f), 65504.0f)); } +// NaN in the down projection (decode's q8_1 has room to ~8e6; FP16 ends at 65504). A NaN stays NaN (fminf/fmaxf +// would make it -65504 and hide where it came from); finite values below 65504 round exactly as before. +__device__ __forceinline__ uint16_t hf_sat(float f) { return hf(isnan(f) ? f : fminf(fmaxf(f, -65504.0f), 65504.0f)); } // block-wide sum for blockDim.x <= 1024, result broadcast __device__ float block_sum(float v, float* sh) { const int lane = threadIdx.x & 31, w = threadIdx.x >> 5; From 1e5e84d9191d29cd787552a0e24506c4dc357034 Mon Sep 17 00:00:00 2001 From: sergiywith Date: Wed, 30 Sep 2026 22:25:39 +0300 Subject: [PATCH 30/48] prefill auto: chunks up to 32768 (was 8192) Every chunk streams again each expert it routes to, so a long prompt read in 8192-token chunks crossed PCIe with nearly all experts of every layer four times per 32K. The auto list now starts at 32768 and 16384, still bounded by the lend rule and by --max-context; a request lends only what its prompt needs, so short prompts are unaffected. IQ2_XS, RTX 5090, 64K context, a 32K prompt (3 runs each): 5,624 -> 6,465 tok/s, 40K -> 18K experts streamed. NVFP4 pack at 262K: 3,535 -> 5,201 tok/s. --- src/program/generate.cpp | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 9a468b4e..2a9a97e4 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -319,7 +319,7 @@ struct Options { int vram_reserve_mib = 700; /// Plan v0.3 P5: batched prompt processing in chunks of this many tokens (0 = the token path). int64_t prefill_chunk = 0; - /// `--prefill auto`: the largest chunk (up to 8192) whose buffers the expert cache can lend. Every expert a chunk + /// `--prefill auto`: the largest chunk (up to 32768) whose buffers the expert cache can lend. Every expert a chunk /// routes to is streamed once per chunk, so a bigger chunk streams fewer bytes per token (the "ubatch" effect). bool prefill_auto = false; bool no_split_rows = false; ///< plan v0.3 P4 A/B: one whole expert per pool thread @@ -501,7 +501,7 @@ void usage() { " --no-token-graph A/B: two graphs per layer (the host launches each) instead of one per token\n" " --no-fused-gr A/B: the six-kernel hyper-connection read and a separate write (native)\n" " --prefill CHUNK batched prompt processing in chunks of CHUNK tokens (needs --native); auto =\n" - " the largest chunk up to 8192 whose buffers the expert cache can lend\n" + " the largest chunk up to 32768 whose buffers the expert cache can lend\n" " --no-pool skip the CPU expert pool (the GPU-only floor)\n" " --sync-every-layer debug: synchronise after every layer\n" " --ple-gguf PATH the n-gram/PLE shard. WITHOUT IT LAYER 1's PLE IS SILENTLY SKIPPED,\n" @@ -3603,10 +3603,13 @@ int main(int argc, char** argv) { : (int64_t) (strata::prefill::Prefill::pinned_share() >= 0.9 ? 90 : 85); }(); auto plan_lend = [&](int64_t& chunk) -> int64_t { - static constexpr int64_t kAutoChunks[] = {8192, 6144, 4096, 3072, 2048, 1024, 512, 256}; + // 32768 and 16384: a 32K prompt with IQ2_XS (RTX 5090, 64K context) read at 5,624 tok/s in 8192-token chunks + // and 6,465 in one 32768 chunk (40K -> 18K experts streamed; an NVFP4 pack at 262K: 3,535 -> 5,201) + static constexpr int64_t kAutoChunks[] = {32768, 16384, 8192, 6144, 4096, 3072, 2048, 1024, 512, 256}; auto slots_for = lend_slots; if (o.prefill_auto) { for (const int64_t c : kAutoChunks) { + if (c > o.max_context && c > 256) continue; // no prompt is longer than the context const int64_t k = slots_for(c); if (k + 128 <= xcache.slots() && k * 100 <= kAutoLendPct * xcache.slots()) { chunk = c; return k; } } From da95ad29d844c4c76f077074697316a18bb2c4a2 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Thu, 1 Oct 2026 08:39:58 +0200 Subject: [PATCH 31/48] #282 follow-up: chunks above 8192 are opt-in (--prefill auto:16384 / auto:32768, or STRATA_PREFILL_AUTO_MAX) A bigger chunk reads a long prompt in a different order of chunks (other expert loans, other rounding of the batched path), so it stays out of the default: plain --prefill auto picks from 8192 down exactly as 0.1.31 did (the PR's "no chunk past the context" rule, which also moved the choice below 8192 for small contexts, now applies only to the new sizes). auto:N (16384 or 32768) or STRATA_PREFILL_AUTO_MAX with auto sets the ceiling; o.prefill_chunk starts at that ceiling for the buffer estimates. Both kAutoChunks lists - plan_lend and the serve path's per-stage fits() - take the same sizes under the same rule. --- src/program/generate.cpp | 31 ++++++++++++++++++++++--------- 1 file changed, 22 insertions(+), 9 deletions(-) diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 2a9a97e4..18668d66 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -319,9 +319,12 @@ struct Options { int vram_reserve_mib = 700; /// Plan v0.3 P5: batched prompt processing in chunks of this many tokens (0 = the token path). int64_t prefill_chunk = 0; - /// `--prefill auto`: the largest chunk (up to 32768) whose buffers the expert cache can lend. Every expert a chunk + /// `--prefill auto`: the largest chunk (up to 8192) whose buffers the expert cache can lend. Every expert a chunk /// routes to is streamed once per chunk, so a bigger chunk streams fewer bytes per token (the "ubatch" effect). bool prefill_auto = false; + /// #282, opt-in: the largest chunk `--prefill auto` may take - 8192 by default; `--prefill auto:16384` or + /// `auto:32768` (or STRATA_PREFILL_AUTO_MAX) lets it go further, never past the context + int64_t prefill_auto_max = 8192; bool no_split_rows = false; ///< plan v0.3 P4 A/B: one whole expert per pool thread /// Plan v0.3 P5: the prompt path borrows the top expert-cache slots for its buffers and refills them after /// the prompt (default); `--no-prefill-borrow` reserves the buffers' VRAM for the whole session instead. @@ -501,7 +504,8 @@ void usage() { " --no-token-graph A/B: two graphs per layer (the host launches each) instead of one per token\n" " --no-fused-gr A/B: the six-kernel hyper-connection read and a separate write (native)\n" " --prefill CHUNK batched prompt processing in chunks of CHUNK tokens (needs --native); auto =\n" - " the largest chunk up to 32768 whose buffers the expert cache can lend\n" + " the largest chunk up to 8192 whose buffers the expert cache can lend;\n" + " auto:16384 / auto:32768 (or STRATA_PREFILL_AUTO_MAX) allow bigger ones\n" " --no-pool skip the CPU expert pool (the GPU-only floor)\n" " --sync-every-layer debug: synchronise after every layer\n" " --ple-gguf PATH the n-gram/PLE shard. WITHOUT IT LAYER 1's PLE IS SILENTLY SKIPPED,\n" @@ -1092,8 +1096,13 @@ int main(int argc, char** argv) { else if (a == "--vram-reserve-mib") o.vram_reserve_mib = std::atoi(next("--vram-reserve-mib")); else if (a == "--prefill") { const std::string v = next("--prefill"); - o.prefill_auto = v == "auto"; - o.prefill_chunk = o.prefill_auto ? 8192 : std::atoll(v.c_str()); + o.prefill_auto = v == "auto" || v.rfind("auto:", 0) == 0; + // #282: auto:N (N = 16384 or 32768) or STRATA_PREFILL_AUTO_MAX lets auto take chunks above 8192 + const char* env_max = std::getenv("STRATA_PREFILL_AUTO_MAX"); + const long long want_max = v.rfind("auto:", 0) == 0 ? std::atoll(v.c_str() + 5) + : (o.prefill_auto && env_max != nullptr ? std::atoll(env_max) : 8192); + o.prefill_auto_max = want_max >= 32768 ? 32768 : want_max >= 16384 ? 16384 : 8192; + o.prefill_chunk = o.prefill_auto ? o.prefill_auto_max : std::atoll(v.c_str()); } else if (a == "--no-split-rows") o.no_split_rows = true; else if (a == "--no-prefill-borrow") o.no_prefill_borrow = true; @@ -3603,13 +3612,15 @@ int main(int argc, char** argv) { : (int64_t) (strata::prefill::Prefill::pinned_share() >= 0.9 ? 90 : 85); }(); auto plan_lend = [&](int64_t& chunk) -> int64_t { - // 32768 and 16384: a 32K prompt with IQ2_XS (RTX 5090, 64K context) read at 5,624 tok/s in 8192-token chunks - // and 6,465 in one 32768 chunk (40K -> 18K experts streamed; an NVFP4 pack at 262K: 3,535 -> 5,201) + // 32768 and 16384 (#282, opt-in: --prefill auto:32768): a 32K prompt with IQ2_XS (RTX 5090, 64K context) + // read at 5,624 tok/s in 8192-token chunks and 6,465 in one 32768 chunk (40K -> 18K experts streamed; an + // NVFP4 pack at 262K: 3,535 -> 5,201) static constexpr int64_t kAutoChunks[] = {32768, 16384, 8192, 6144, 4096, 3072, 2048, 1024, 512, 256}; auto slots_for = lend_slots; if (o.prefill_auto) { for (const int64_t c : kAutoChunks) { - if (c > o.max_context && c > 256) continue; // no prompt is longer than the context + // above 8192: only when asked for, and only when a prompt of the context can use it + if (c > 8192 && (c > o.prefill_auto_max || c > o.max_context)) continue; const int64_t k = slots_for(c); if (k + 128 <= xcache.slots() && k * 100 <= kAutoLendPct * xcache.slots()) { chunk = c; return k; } } @@ -3728,11 +3739,13 @@ int main(int argc, char** argv) { } return true; }; - static constexpr int64_t kAutoChunks[] = {8192, 6144, 4096, 3072, 2048, 1024, 512, 256}; + static constexpr int64_t kAutoChunks[] = {32768, 16384, 8192, 6144, 4096, 3072, 2048, 1024, 512, 256}; int64_t chunk = 0; if (o.prefill_auto) { - for (const int64_t c : kAutoChunks) + for (const int64_t c : kAutoChunks) { + if (c > 8192 && (c > o.prefill_auto_max || c > o.max_context)) continue; // #282, as plan_lend if (fits(c, true)) { chunk = c; break; } + } } else { for (int64_t c = o.prefill_chunk; c >= 256; c /= 2) if (fits(c, false)) { chunk = c; break; } From a86bc853f36ef9b0804ecac73a7972e99df3b163 Mon Sep 17 00:00:00 2001 From: sergiywith Date: Wed, 30 Sep 2026 22:25:39 +0300 Subject: [PATCH 32/48] Prompt path: BF16 projections get the activation's BF16 remainder too The prompt path fed BF16-rounded activations (2^-9 relative) to the BF16-weight projections, where decode feeds FP32: the router (a discrete top-10), the indexer (a discrete block selection), SSM alpha/beta, the shared-expert gate, the PLE key/value and the hyper-connection. Each now takes x as hi + lo, both BF16 (lo = bf16(x - hi)), in two GEMMs summed in FP32: ~16 mantissa bits, decode's FP32 x to within ~1e-5. STRATA_PREFILL_BF16X2: 2 (default) all but the hyper-connection, 1 all, 0 off. IQ2_XS, first-token KL to mode 1: short prompts main 0.0028/0.0069/0.0009, mode 2 0.0014/0.0024/0.0012; a 32K prompt 0.074 and 0.072 (the hyper-connection is what matters there). --- include/strata/prefill/kernels.hpp | 17 +++--- src/prefill/kernels.cu | 94 +++++++++++++++++++++--------- src/prefill/prefill.cpp | 62 ++++++++++++++------ 3 files changed, 119 insertions(+), 54 deletions(-) diff --git a/include/strata/prefill/kernels.hpp b/include/strata/prefill/kernels.hpp index 3a4d1ca6..8f6145bf 100644 --- a/include/strata/prefill/kernels.hpp +++ b/include/strata/prefill/kernels.hpp @@ -14,21 +14,24 @@ namespace strata::prefill { // ---- hyper-connection (n_embd 2560, hc 4, hc_lr 320) /// xn[t, c*2560 + d] = R[t,c,d] * rsqrt(mean_d R[t,c,:]^2 + eps) * w_norm[c*2560 + d]; also its BF16 image. -void gr_norm(const float* R, const float* w_norm, float eps, float* xn, uint16_t* xn16, int64_t T, void* stream); +/// `xn16_lo` (null: none) takes bf16(x - xn16): W.xn16 + W.xn16_lo is the product with ~16 mantissa bits of x. +void gr_norm(const float* R, const float* w_norm, float eps, float* xn, uint16_t* xn16, int64_t T, void* stream, + uint16_t* xn16_lo = nullptr); /// F-1: gr_norm without its FP32 output: the row scales rs[t*4 + c] and the BF16 image; gr_mix_r then reads R. -void gr_norm_rs(const float* R, const float* w_norm, float eps, float* rs, uint16_t* xn16, int64_t T, void* stream); +void gr_norm_rs(const float* R, const float* w_norm, float eps, float* rs, uint16_t* xn16, int64_t T, void* stream, + uint16_t* xn16_lo = nullptr); /// gr_mix with xn recomputed from R, rs and w_norm exactly as gr_norm computes it (the same bits). void gr_mix_r(const float* R, const float* rs, const float* w_norm, const float* gated, float* mixed, uint16_t* mixed16, - int64_t T, void* stream, uint16_t* mixed_h = nullptr); + int64_t T, void* stream, uint16_t* mixed_h = nullptr, uint16_t* mixed16_lo = nullptr); /// F-2: gr_write, then gr_norm_rs of the next half (its norm weights) over the rows just written - the same bits as /// the two calls, without reading R back. void gr_write_norm_rs(float* R, const float* bo, const float* inj, int64_t inj_ld, const float* w_norm_next, float eps, - float* rs, uint16_t* xn16, int64_t T, void* stream); + float* rs, uint16_t* xn16, int64_t T, void* stream, uint16_t* xn16_lo = nullptr); /// lo16[t, k] = bf16(silu(lo[t, k] / hc)) -void gr_silu(const float* lo, uint16_t* lo16, int64_t T, void* stream); +void gr_silu(const float* lo, uint16_t* lo16, int64_t T, void* stream, uint16_t* lo16_lo = nullptr); /// mixed[t, d] = mean_c xn[t, c, d] * sigmoid(gated[t, c, d]); FP32, BF16 and FP16 (either image may be null). void gr_mix(const float* xn, const float* gated, float* mixed, uint16_t* mixed16, int64_t T, void* stream, - uint16_t* mixed_h = nullptr); + uint16_t* mixed_h = nullptr, uint16_t* mixed16_lo = nullptr); /// R[t, c, d] += bo[t, d] * 2 sigmoid(inj[t, c] / hc) (inj has row stride inj_ld) void gr_write(float* R, const float* bo, const float* inj, int64_t inj_ld, int64_t T, void* stream); /// R[t, c, :] = e[t, :] for all four streams (the embedding broadcast). @@ -85,7 +88,7 @@ void kv_append(const float* K, const float* V, int64_t T, int64_t pos0, const in /// fp32 -> fp16 bits and fp32 -> bf16, n elements (the two activation images of the prompt GEMMs). void to_f16(const float* x, uint16_t* y, int64_t n, void* stream); -void to_bf16(const float* x, uint16_t* y, int64_t n, void* stream); +void to_bf16(const float* x, uint16_t* y, int64_t n, void* stream, uint16_t* ylo = nullptr); /// y = fp32(fp16(x)): what an FP16 store of x would read back (the FP16 indexer-key experiment) void round_f16(const float* x, float* y, int64_t n, void* stream); /// Expert blob -> FP16 (Q2_0 values are exact in FP16). diff --git a/src/prefill/kernels.cu b/src/prefill/kernels.cu index 28e8d139..25c12004 100644 --- a/src/prefill/kernels.cu +++ b/src/prefill/kernels.cu @@ -32,6 +32,9 @@ __device__ __forceinline__ uint16_t bf(float f) { u += 0x7fffu + ((u >> 16) & 1u); return (uint16_t) (u >> 16); } +// The BF16 GEMMs' second operand (STRATA_PREFILL_BF16X2): what the BF16 image `hi` left out of f, itself in BF16. +// W.hi + W.lo carries ~16 mantissa bits of the activation - the decode path's FP32 x to within ~1e-5. +__device__ __forceinline__ uint16_t bf_lo(float f, uint16_t hi) { return bf(f - __uint_as_float((uint32_t) hi << 16)); } __device__ __forceinline__ float sigm(float x) { return 1.0f / (1.0f + __expf(-x)); } __device__ __forceinline__ uint16_t hf(float f) { return __half_as_ushort(__float2half_rn(f)); } // A SwiGLU product for an FP16 GEMM: saturated, so a token with a massive activation cannot turn into inf and then @@ -60,7 +63,7 @@ unsigned blocks_for(int64_t n, int t = 256) { return (unsigned) ((n + t - 1) / t // ---------------------------------------------------------------- hyper-connection __global__ void gr_norm_kernel(const float* __restrict__ R, const float* __restrict__ w, float eps, - float* __restrict__ xn, uint16_t* __restrict__ xn16) { + float* __restrict__ xn, uint16_t* __restrict__ xn16, uint16_t* __restrict__ xn16_lo) { __shared__ float sh[32]; const int64_t row = blockIdx.x; // t * 4 + c const int c = (int) (row % HC); @@ -71,13 +74,16 @@ __global__ void gr_norm_kernel(const float* __restrict__ R, const float* __restr for (int d = threadIdx.x; d < N; d += blockDim.x) { const float v = r[d] * rs * w[c * N + d]; xn[row * N + d] = v; - xn16[row * N + d] = bf(v); + const uint16_t h = bf(v); + xn16[row * N + d] = h; + if (xn16_lo) xn16_lo[row * N + d] = bf_lo(v, h); } } // F-1: the row scale only (and the BF16 image); gr_mix_r_kernel recomputes r * rs * w itself, in the same order, // so the FP32 copy of the normalized rows (T x 10240 floats) is neither written nor read __global__ void gr_norm_rs_kernel(const float* __restrict__ R, const float* __restrict__ w, float eps, - float* __restrict__ rs_out, uint16_t* __restrict__ xn16) { + float* __restrict__ rs_out, uint16_t* __restrict__ xn16, + uint16_t* __restrict__ xn16_lo) { __shared__ float sh[32]; const int64_t row = blockIdx.x; // t * 4 + c const int c = (int) (row % HC); @@ -86,11 +92,16 @@ __global__ void gr_norm_rs_kernel(const float* __restrict__ R, const float* __re for (int d = threadIdx.x; d < N; d += blockDim.x) ss += r[d] * r[d]; const float rs = rsqrtf(block_sum(ss, sh) / (float) N + eps); if (threadIdx.x == 0) rs_out[row] = rs; - for (int d = threadIdx.x; d < N; d += blockDim.x) xn16[row * N + d] = bf(r[d] * rs * w[c * N + d]); + for (int d = threadIdx.x; d < N; d += blockDim.x) { + const float v = r[d] * rs * w[c * N + d]; + const uint16_t h = bf(v); + xn16[row * N + d] = h; + if (xn16_lo) xn16_lo[row * N + d] = bf_lo(v, h); + } } __global__ void gr_mix_r_kernel(const float* __restrict__ R, const float* __restrict__ rs, const float* __restrict__ w, const float* __restrict__ g, float* __restrict__ mixed, uint16_t* __restrict__ mixed16, - int64_t T, uint16_t* __restrict__ mixed_h) { + int64_t T, uint16_t* __restrict__ mixed_h, uint16_t* __restrict__ mixed16_lo) { const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; if (i >= T * N) return; const int64_t t = i / N, d = i % N; @@ -103,7 +114,11 @@ __global__ void gr_mix_r_kernel(const float* __restrict__ R, const float* __rest } s /= (float) HC; mixed[i] = s; - if (mixed16) mixed16[i] = bf(s); + if (mixed16) { + const uint16_t h = bf(s); + mixed16[i] = h; + if (mixed16_lo) mixed16_lo[i] = bf_lo(s, h); + } if (mixed_h) mixed_h[i] = hf(s); } // F-2: gr_write_kernel for one row (t, c), then gr_norm_rs_kernel's reduction over it with the next half's norm @@ -113,7 +128,8 @@ constexpr int GRW_PER = (N + 255) / 256; __global__ void __launch_bounds__(256) gr_write_norm_rs_kernel(float* __restrict__ R, const float* __restrict__ bo, const float* __restrict__ inj, int64_t inj_ld, const float* __restrict__ w, float eps, - float* __restrict__ rs_out, uint16_t* __restrict__ xn16) { + float* __restrict__ rs_out, uint16_t* __restrict__ xn16, + uint16_t* __restrict__ xn16_lo) { __shared__ float sh[32]; const int64_t row = blockIdx.x; // t * 4 + c const int64_t t = row / HC; @@ -134,16 +150,26 @@ __global__ void __launch_bounds__(256) gr_write_norm_rs_kernel(float* __restrict if (threadIdx.x == 0) rs_out[row] = rs; k = 0; #pragma unroll - for (int d = threadIdx.x; d < N; d += 256, ++k) xn16[row * N + d] = bf(v[k] * rs * w[c * N + d]); + for (int d = threadIdx.x; d < N; d += 256, ++k) { + const float x = v[k] * rs * w[c * N + d]; + const uint16_t h = bf(x); + xn16[row * N + d] = h; + if (xn16_lo) xn16_lo[row * N + d] = bf_lo(x, h); + } } -__global__ void gr_silu_kernel(const float* __restrict__ lo, uint16_t* __restrict__ lo16, int64_t n) { +__global__ void gr_silu_kernel(const float* __restrict__ lo, uint16_t* __restrict__ lo16, uint16_t* __restrict__ lo16_lo, + int64_t n) { const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; if (i >= n) return; const float x = lo[i] / (float) HC; - lo16[i] = bf(x / (1.0f + __expf(-x))); + const float v = x / (1.0f + __expf(-x)); + const uint16_t h = bf(v); + lo16[i] = h; + if (lo16_lo) lo16_lo[i] = bf_lo(v, h); } __global__ void gr_mix_kernel(const float* __restrict__ xn, const float* __restrict__ g, float* __restrict__ mixed, - uint16_t* __restrict__ mixed16, int64_t T, uint16_t* __restrict__ mixed_h) { + uint16_t* __restrict__ mixed16, int64_t T, uint16_t* __restrict__ mixed_h, + uint16_t* __restrict__ mixed16_lo) { const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; if (i >= T * N) return; const int64_t t = i / N, d = i % N; @@ -155,7 +181,11 @@ __global__ void gr_mix_kernel(const float* __restrict__ xn, const float* __restr } s /= (float) HC; mixed[i] = s; - if (mixed16) mixed16[i] = bf(s); + if (mixed16) { + const uint16_t h = bf(s); + mixed16[i] = h; + if (mixed16_lo) mixed16_lo[i] = bf_lo(s, h); + } if (mixed_h) mixed_h[i] = hf(s); } __global__ void gr_write_kernel(float* __restrict__ R, const float* __restrict__ bo, const float* __restrict__ inj, @@ -612,9 +642,13 @@ __global__ void round_f16_kernel(const float* __restrict__ x, float* __restrict_ for (int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (int64_t) gridDim.x * blockDim.x) y[i] = __half2float(__float2half_rn(x[i])); } -__global__ void to_bf16_kernel(const float* __restrict__ x, uint16_t* __restrict__ y, int64_t n) { - for (int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (int64_t) gridDim.x * blockDim.x) - y[i] = bf(x[i]); +__global__ void to_bf16_kernel(const float* __restrict__ x, uint16_t* __restrict__ y, uint16_t* __restrict__ ylo, + int64_t n) { + for (int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (int64_t) gridDim.x * blockDim.x) { + const uint16_t h = bf(x[i]); + y[i] = h; + if (ylo) ylo[i] = bf_lo(x[i], h); + } } } // namespace @@ -638,39 +672,41 @@ void round_f16(const float* x, float* y, int64_t n, void* stream) { round_f16_kernel<<<(unsigned) ((n + 255) / 256 < 4096 ? (n + 255) / 256 : 4096), 256, 0, (cudaStream_t) stream>>>(x, y, n); check("round_f16"); } -void to_bf16(const float* x, uint16_t* y, int64_t n, void* stream) { +void to_bf16(const float* x, uint16_t* y, int64_t n, void* stream, uint16_t* ylo) { if (n <= 0) return; - to_bf16_kernel<<<(unsigned) ((n + 255) / 256 < 4096 ? (n + 255) / 256 : 4096), 256, 0, (cudaStream_t) stream>>>(x, y, n); + to_bf16_kernel<<<(unsigned) ((n + 255) / 256 < 4096 ? (n + 255) / 256 : 4096), 256, 0, (cudaStream_t) stream>>>(x, y, ylo, n); check("to_bf16"); } -void gr_norm(const float* R, const float* w_norm, float eps, float* xn, uint16_t* xn16, int64_t T, void* stream) { - gr_norm_kernel<<<(unsigned) (T * HC), 256, 0, (cudaStream_t) stream>>>(R, w_norm, eps, xn, xn16); +void gr_norm(const float* R, const float* w_norm, float eps, float* xn, uint16_t* xn16, int64_t T, void* stream, + uint16_t* xn16_lo) { + gr_norm_kernel<<<(unsigned) (T * HC), 256, 0, (cudaStream_t) stream>>>(R, w_norm, eps, xn, xn16, xn16_lo); check("gr_norm"); } -void gr_norm_rs(const float* R, const float* w_norm, float eps, float* rs, uint16_t* xn16, int64_t T, void* stream) { - gr_norm_rs_kernel<<<(unsigned) (T * HC), 256, 0, (cudaStream_t) stream>>>(R, w_norm, eps, rs, xn16); +void gr_norm_rs(const float* R, const float* w_norm, float eps, float* rs, uint16_t* xn16, int64_t T, void* stream, + uint16_t* xn16_lo) { + gr_norm_rs_kernel<<<(unsigned) (T * HC), 256, 0, (cudaStream_t) stream>>>(R, w_norm, eps, rs, xn16, xn16_lo); check("gr_norm_rs"); } void gr_mix_r(const float* R, const float* rs, const float* w_norm, const float* gated, float* mixed, uint16_t* mixed16, - int64_t T, void* stream, uint16_t* mixed_h) { + int64_t T, void* stream, uint16_t* mixed_h, uint16_t* mixed16_lo) { gr_mix_r_kernel<<>>(R, rs, w_norm, gated, mixed, mixed16, T, - mixed_h); + mixed_h, mixed16_lo); check("gr_mix_r"); } void gr_write_norm_rs(float* R, const float* bo, const float* inj, int64_t inj_ld, const float* w_norm_next, float eps, - float* rs, uint16_t* xn16, int64_t T, void* stream) { + float* rs, uint16_t* xn16, int64_t T, void* stream, uint16_t* xn16_lo) { gr_write_norm_rs_kernel<<<(unsigned) (T * HC), 256, 0, (cudaStream_t) stream>>>(R, bo, inj, inj_ld, w_norm_next, eps, - rs, xn16); + rs, xn16, xn16_lo); check("gr_write_norm_rs"); } -void gr_silu(const float* lo, uint16_t* lo16, int64_t T, void* stream) { - gr_silu_kernel<<>>(lo, lo16, T * LR); +void gr_silu(const float* lo, uint16_t* lo16, int64_t T, void* stream, uint16_t* lo16_lo) { + gr_silu_kernel<<>>(lo, lo16, lo16_lo, T * LR); check("gr_silu"); } void gr_mix(const float* xn, const float* gated, float* mixed, uint16_t* mixed16, int64_t T, void* stream, - uint16_t* mixed_h) { - gr_mix_kernel<<>>(xn, gated, mixed, mixed16, T, mixed_h); + uint16_t* mixed_h, uint16_t* mixed16_lo) { + gr_mix_kernel<<>>(xn, gated, mixed, mixed16, T, mixed_h, mixed16_lo); check("gr_mix"); } void gr_write(float* R, const float* bo, const float* inj, int64_t inj_ld, int64_t T, void* stream) { diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index 117cae95..6f53169a 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -94,6 +94,20 @@ inline int ring_slots(size_t T) { return (int64_t) T >= stream_all_min() ? big : STAGE; } constexpr int DQ = 2; // dequantized-expert ring (FP16 gate/up + down) +// The BF16-weight projections (hyper-connection, SSM alpha/beta, indexer, router, shared gate, PLE key/value) take +// BF16 activations here and FP32 ones in decode. STRATA_PREFILL_BF16X2=1 adds each activation's BF16 remainder as a +// second GEMM (Y = W.hi + W.lo, ~16 mantissa bits): a router that picks its top 10 from the same x decode would. +// 2 (the default) = all but the hyper-connection's; 1 = the hyper-connection's too (its activations are 10240 wide +// and its up projection writes as much: slower); 0 = off. +inline int bf16x2_mode() { + static const int v = [] { + const char* e = std::getenv("STRATA_PREFILL_BF16X2"); + return e != nullptr ? std::atoi(e) : 2; + }(); + return v; +} +inline bool bf16x2() { return bf16x2_mode() != 0; } +inline bool bf16x2_hc() { return bf16x2_mode() == 1; } // F-1: STRATA_GR_UNFUSED=1 keeps the FP32 copy of the normalized rows (gr_norm + gr_mix), the A/B arm inline bool gr_unfused() { @@ -278,6 +292,7 @@ struct Prefill::Impl { uint16_t *xn16 = nullptr, *lo16 = nullptr; float* mixed = nullptr; uint16_t *mixed_bf = nullptr, *mixed_h = nullptr; + uint16_t *xn16_lo = nullptr, *lo16_lo = nullptr, *mixed_bf_lo = nullptr; // bf16x2(): the BF16 GEMMs' low parts float* bo = nullptr; // GDN float *qkv = nullptr, *z = nullptr, *ab = nullptr, *gate = nullptr, *beta = nullptr, *hbuf = nullptr, *y = nullptr; @@ -604,6 +619,8 @@ bool Prefill::carve(size_t T, void* alloc) { m.gated = o.take(T * D, ok); m.inj = o.take(T * HC, ok); m.mixed = o.take(T * N, ok); m.mixed_bf = o.take(T * N, ok); m.mixed_h = o.take(T * N, ok); m.bo = o.take(T * N, ok); + if (bf16x2_hc()) { m.xn16_lo = o.take(T * D, ok); m.lo16_lo = o.take(T * LR, ok); } + if (bf16x2()) 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; @@ -856,6 +873,8 @@ uint64_t Prefill::bytes_needed(const core::ModelGeometry& g, const core::Session auto f = [&](size_t n) { o.take(n, ok); }; f(T * N); f(T * D); f(T * D); o.take(T * D, ok); f(T * LR); o.take(T * LR, ok); f(T * D); f(T * HC); f(T * N); o.take(T * N, ok); o.take(T * N, ok); f(T * N); + if (bf16x2_hc()) { o.take(T * D, ok); o.take(T * LR, ok); } + if (bf16x2()) 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; @@ -894,9 +913,10 @@ bool native_proj(Gemm& gm, const core::WeightRef* w, const uint16_t* X, float* Y return true; } bool bf16_proj(Gemm& gm, const core::WeightRef* w, const uint16_t* X, float* Y, int64_t T, const std::string& name, - std::string& err, int64_t ldy = 0) { + std::string& err, int64_t ldy = 0, const uint16_t* X_lo = nullptr) { if (w->kind != core::WeightKind::Bf16InF32 || !w->data) { err = "prefill: " + name + " is not a resident BF16 tensor"; return false; } gm.bf16(X, (const uint16_t*) w->data, Y, T, w->ne1 > 0 ? w->ne1 : 1, w->ne0, ldy); + if (X_lo) gm.bf16(X_lo, (const uint16_t*) w->data, Y, T, w->ne1 > 0 ? w->ne1 : 1, w->ne0, ldy, 1.0f); return true; } @@ -1231,7 +1251,7 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e const auto tp = Clock::now(); const strata::kernels::PleWeights& pw = ss.ple.w; constexpr int64_t HD = strata::kernels::NG_HC_DIM; - const uint64_t per_token = (uint64_t) (3 * HD + N + 4) * 4 + (uint64_t) N * 2 + 4096; + const uint64_t per_token = (uint64_t) (3 * HD + N + 4) * 4 + (uint64_t) N * (bf16x2() ? 4 : 2) + 4096; const int64_t SB = std::min(T, (int64_t) (m.region_bytes / per_token)); for (int64_t s0 = 0; s0 < T; s0 += SB) { const int64_t nb = std::min(SB, T - s0); @@ -1243,16 +1263,19 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e float* val = carve_f((size_t) nb * N); float* gate = carve_f((size_t) nb * 4); uint16_t* e16 = (uint16_t*) carve_f((size_t) nb * N / 2); + uint16_t* e16_lo = bf16x2() ? (uint16_t*) carve_f((size_t) nb * N / 2) : nullptr; const float* emb = m.ple_emb + s0 * N; if (pw.key_bf16 != nullptr) { - to_bf16(emb, e16, nb * N, m.cs); + to_bf16(emb, e16, nb * N, m.cs, e16_lo); m.gemm.bf16(e16, pw.key_bf16, key, nb, HD, N); + if (e16_lo) m.gemm.bf16(e16_lo, pw.key_bf16, key, nb, HD, N, 0, 1.0f); } else { to_f16(emb, e16, nb * N, m.cs); m.gemm.native(e16, pw.key_native_type, pw.key_native_data, key, nb, HD, N); - to_bf16(emb, e16, nb * N, m.cs); + to_bf16(emb, e16, nb * N, m.cs, e16_lo); } m.gemm.bf16(e16, pw.value_bf16, val, nb, N, N); + if (e16_lo) m.gemm.bf16(e16_lo, pw.value_bf16, val, nb, N, N, 0, 1.0f); try { strata::kernels::native_ple_postops_batch(key, m.R + s0 * D, val, ss.ple.hist, pw, qn, gated, gate, (int) nb, m.cs); @@ -1283,15 +1306,16 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e *wu = need(v, su.c_str(), err), *wi = need(v, si.c_str(), err); if (!wn || !wd || !wu || !wi) return false; pt.mark(kPfHc, cs); - if (gr_unfused()) gr_norm(m.R, (const float*) wn->data, EPS, m.xn, m.xn16, T, m.cs); - else if (!normed) gr_norm_rs(m.R, (const float*) wn->data, EPS, m.grs, m.xn16, T, m.cs); + if (gr_unfused()) gr_norm(m.R, (const float*) wn->data, EPS, m.xn, m.xn16, T, m.cs, m.xn16_lo); + else if (!normed) gr_norm_rs(m.R, (const float*) wn->data, EPS, m.grs, m.xn16, T, m.cs, m.xn16_lo); normed = false; - if (!bf16_proj(m.gemm, wd, m.xn16, m.lo, T, sd, err)) return false; - gr_silu(m.lo, m.lo16, T, m.cs); - if (!bf16_proj(m.gemm, wu, m.lo16, m.gated, T, su, err)) return false; - if (!bf16_proj(m.gemm, wi, m.xn16, m.inj, T, si, err)) return false; - if (gr_unfused()) gr_mix(m.xn, m.gated, m.mixed, m.mixed_bf, T, m.cs, m.mixed_h); - else gr_mix_r(m.R, m.grs, (const float*) wn->data, m.gated, m.mixed, m.mixed_bf, T, m.cs, m.mixed_h); + if (!bf16_proj(m.gemm, wd, m.xn16, m.lo, T, sd, err, 0, m.xn16_lo)) return false; + gr_silu(m.lo, m.lo16, T, m.cs, m.lo16_lo); + if (!bf16_proj(m.gemm, wu, m.lo16, m.gated, T, su, err, 0, m.lo16_lo)) return false; + if (!bf16_proj(m.gemm, wi, m.xn16, m.inj, T, si, err, 0, m.xn16_lo)) return false; + if (gr_unfused()) gr_mix(m.xn, m.gated, m.mixed, m.mixed_bf, T, m.cs, m.mixed_h, m.mixed_bf_lo); + else gr_mix_r(m.R, m.grs, (const float*) wn->data, m.gated, m.mixed, m.mixed_bf, T, m.cs, m.mixed_h, + m.mixed_bf_lo); if (half == 0 && !core::is_qsa_layer(g, l)) { // ======================= GDN ======================= @@ -1306,8 +1330,8 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e float* conv = state + (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size; if (!native_proj(m.gemm, wqkv, m.mixed_h, m.qkv, T, v.name("attn_qkv.weight"), err)) return false; if (!native_proj(m.gemm, wg, m.mixed_h, m.z, T, v.name("attn_gate.weight"), err)) return false; - if (!bf16_proj(m.gemm, wa, m.mixed_bf, m.ab, T, v.name("ssm_alpha.weight"), err, 2 * HV)) return false; - if (!bf16_proj(m.gemm, wb, m.mixed_bf, m.ab + HV, T, v.name("ssm_beta.weight"), err, 2 * HV)) return false; + if (!bf16_proj(m.gemm, wa, m.mixed_bf, m.ab, T, v.name("ssm_alpha.weight"), err, 2 * HV, m.mixed_bf_lo)) return false; + if (!bf16_proj(m.gemm, wb, m.mixed_bf, m.ab + HV, T, v.name("ssm_beta.weight"), err, 2 * HV, m.mixed_bf_lo)) return false; pt.mark(kPfGdnConv, cs); // "gdn" is the projections in; the rest on their own lines gdn_gates(m.ab, (const float*) wdt->data, (const float*) wsa->data, m.gate, m.beta, T, m.cs); gdn_conv(conv, m.qkv, (const float*) wc->data, m.hbuf, T, EPS, m.cs); @@ -1331,8 +1355,8 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e if (!native_proj(m.gemm, wk, m.mixed_h, m.Kc, T, v.name("attn_k.weight"), err)) return false; if (!native_proj(m.gemm, wv, m.mixed_h, m.Vc, T, v.name("attn_v.weight"), err)) return false; if (!native_proj(m.gemm, wq, m.mixed_h, m.Qf, T, v.name("attn_q.weight"), err)) return false; - if (!bf16_proj(m.gemm, wik, m.mixed_bf, m.idx_raw, T, v.name("indexer.k_proj.weight"), err)) return false; - if (!bf16_proj(m.gemm, wiq, m.mixed_bf, m.q_idx, T, v.name("indexer.q_proj.weight"), err)) return false; + if (!bf16_proj(m.gemm, wik, m.mixed_bf, m.idx_raw, T, v.name("indexer.k_proj.weight"), err, 0, m.mixed_bf_lo)) return false; + if (!bf16_proj(m.gemm, wiq, m.mixed_bf, m.q_idx, T, v.name("indexer.q_proj.weight"), err, 0, m.mixed_bf_lo)) return false; rms_rows(m.Kc, (const float*) wkn->data, T * 2, 256, 256, EPS, m.cs); rope(m.Kc, T, 2, 256, 512, p0, strata::kernels::rope_scaling(), m.cs); // KV streaming: this layer's cells [0, p0) come in from the host copy to the staging pool, and the @@ -1520,7 +1544,7 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e *wsd = need(v, "ffn_down_shexp.weight", err); if (!wr || !wgi || !wsg || !wsu || !wsd) return false; pt.mark(kPfRouter, cs); - if (!bf16_proj(m.gemm, wr, m.mixed_bf, m.logits, T, v.name("ffn_gate_inp.weight"), err)) return false; + if (!bf16_proj(m.gemm, wr, m.mixed_bf, m.logits, T, v.name("ffn_gate_inp.weight"), err, 0, m.mixed_bf_lo)) return false; route(m.logits, m.ids, m.w, T, m.g->n_expert, m.cs); // the shared expert and its scalar gate if (!native_proj(m.gemm, wsg, m.mixed_h, m.sgate, T, v.name("ffn_gate_shexp.weight"), err)) return false; @@ -1529,6 +1553,7 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e if (!native_proj(m.gemm, wsd, m.sh_h, m.shared, T, v.name("ffn_down_shexp.weight"), err)) return false; if (wgi->kind != core::WeightKind::Bf16InF32) { err = "prefill: shared gate is not BF16"; return false; } m.gemm.bf16(m.mixed_bf, (const uint16_t*) wgi->data, m.sg, T, 1, N); + if (m.mixed_bf_lo) m.gemm.bf16(m.mixed_bf_lo, (const uint16_t*) wgi->data, m.sg, T, 1, N, 0, 1.0f); // group the (token, k) pairs by expert on the host pt.mark(kPfHostGroup, cs); // (the sync below also orders this layer's writes of slot/src/bounds after the previous @@ -1796,7 +1821,8 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e if (!wnn) return false; } if (wnn) { - gr_write_norm_rs(m.R, m.bo, m.inj, HC, (const float*) wnn->data, EPS, m.grs, m.xn16, T, m.cs); + gr_write_norm_rs(m.R, m.bo, m.inj, HC, (const float*) wnn->data, EPS, m.grs, m.xn16, T, m.cs, + m.xn16_lo); normed = true; } else { gr_write(m.R, m.bo, m.inj, HC, T, m.cs); From 7d746a088775813b44d8e5b2d33c74ed5f80aff2 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Thu, 1 Oct 2026 08:40:29 +0200 Subject: [PATCH 33/48] #283 follow-up: STRATA_PREFILL_BF16X2 defaults to 0 (off) - the prompt path's numbers stay 0.1.31's The second (remainder) GEMM changes what the prompt path computes, so it is opt-in: 2 = all but the hyper-connection's projections, 1 = all. With 0 every lo pointer is null: no extra buffers in carve()/bytes_needed(), the PLE batch size as before, and every kernel writes exactly the BF16 images it wrote before. --- src/prefill/prefill.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index 6f53169a..bd8ae5e7 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -97,12 +97,12 @@ constexpr int DQ = 2; // dequantized-expert ring (FP16 gate/up + do // The BF16-weight projections (hyper-connection, SSM alpha/beta, indexer, router, shared gate, PLE key/value) take // BF16 activations here and FP32 ones in decode. STRATA_PREFILL_BF16X2=1 adds each activation's BF16 remainder as a // second GEMM (Y = W.hi + W.lo, ~16 mantissa bits): a router that picks its top 10 from the same x decode would. -// 2 (the default) = all but the hyper-connection's; 1 = the hyper-connection's too (its activations are 10240 wide -// and its up projection writes as much: slower); 0 = off. +// 2 = all but the hyper-connection's; 1 = the hyper-connection's too (its activations are 10240 wide and its up +// projection writes as much: slower); 0 (the default: opt-in, it changes the prompt path's numbers) = off. inline int bf16x2_mode() { static const int v = [] { const char* e = std::getenv("STRATA_PREFILL_BF16X2"); - return e != nullptr ? std::atoi(e) : 2; + return e != nullptr ? std::atoi(e) : 0; }(); return v; } From 16a369b5744a4b0a57508e10bd5a2de84d91c15b Mon Sep 17 00:00:00 2001 From: sergiywith Date: Wed, 30 Sep 2026 22:25:39 +0300 Subject: [PATCH 34/48] RoPE: every kernel reads the session's float64 angle table The native decode/verify rope and the indexer's pooled keys computed pos * powf(...) with cosf/sinf under --use_fast_math (0.0014 rad off at 32K, ~0.02 at 262K), the prompt path with precise float libm, and the float64 table the session builds was read only by the non-native path. rope_table_set registers that table per device (mrope.hpp); rope_cs reads it, or computes in float64 past its end. Measured on main with IQ2_XS: first-token KL of the old angles against the table 0.0045 on a 32K prompt (two runs of main: 0 to 0.00013 on short prompts). On an NVFP4 pack: 0.0063 at 32K and at 125K. Speed unchanged. STRATA_ROPE_LEGACY=1 brings the old float angles back for A/B. Rebased onto 0.1.31 (Niko1221): 0.1.31's rope scaling (#84: linear / YaRN, rope_scaled_angle) is in every rope kernel and in the session's table (build_rope_table with the RopeScaling), so a kernel reads the table only when it was built with the scaling it was given, and otherwise - or past the table's end - computes the angle exactly as 0.1.31 does (no separate float64 device path); rope_table_set registers the scaling with the table. --- include/strata/kernels/mrope.hpp | 25 ++++++++++++++++++ src/core/layer.cpp | 3 +++ src/kernels/cuda/native_qsa_indexer.cu | 32 +++++++++++++---------- src/kernels/cuda/native_rope.cu | 36 +++++++++++++++++++++++--- src/prefill/kernels.cu | 15 ++++++----- 5 files changed, 88 insertions(+), 23 deletions(-) diff --git a/include/strata/kernels/mrope.hpp b/include/strata/kernels/mrope.hpp index fb00bf41..8f456e43 100644 --- a/include/strata/kernels/mrope.hpp +++ b/include/strata/kernels/mrope.hpp @@ -16,18 +16,43 @@ #include +#include "strata/kernels/rope_scaling.hpp" + namespace strata::kernels { /// The table of the CURRENT device (a layer split sets one per device; null = the identity). void mrope_table_set(const int32_t* device_table); const int32_t* mrope_table(); +/// The rotation angles, 32 pairs of a 64-wide rotary slice: the session's float64 table (build_rope_table, +/// [max_pos][32] cos and sin in VRAM, the rope scaling inside) of the CURRENT device. With it the rope kernels +/// rotate by the table's exact angles; without it they compute pos * powf(...) with cosf/sinf, which under +/// --use_fast_math is 0.0014 rad off at 32K and ~0.02 at 262K, and the prompt path (precise libm) and decode +/// (fast-math) disagree with each other. +struct RopeTab { + const float* cos = nullptr; ///< null: no table, the kernels compute the angle as they always did + const float* sin = nullptr; + int max_pos = 0; +}; +/// Registers the table the session just built with `scaling` (the latest one of the device wins). +void rope_table_set(const float* cos_tab, const float* sin_tab, int max_pos, const RopeScaling& scaling); +/// The registered table when the rope kernels are to read it and it was built with `scaling`; otherwise none. +RopeTab rope_table_for(const RopeScaling& scaling); + #if defined(__CUDACC__) || defined(__HIPCC__) /// ggml rope_multi, is_imrope, sections {11, 11, 10, 0}: sector = pair % 32; sector % 3 == 1 -> h (sector < 33), /// == 2 -> w (sector < 30), == 0 -> t (sector < 33). For pairs 0..31 all three bounds hold, so it is pair % 3. __device__ __forceinline__ int mrope_pos(const int32_t* tab, int pos, int pair) { return tab ? __ldg(tab + (size_t) pos * 3 + pair % 3) : pos; } +/// cos and sin of rotary position p, pair `pair` (0..31) from the table (scaling and magnitude included); false +/// when there is no table or p lies past it - then the caller computes the angle as it always did +__device__ __forceinline__ bool rope_tab_cs(const RopeTab& t, int p, int pair, float& c, float& s) { + if (t.cos == nullptr || p < 0 || p >= t.max_pos) return false; + c = __ldg(t.cos + (size_t) p * 32 + pair); + s = __ldg(t.sin + (size_t) p * 32 + pair); + return true; +} #endif } // namespace strata::kernels diff --git a/src/core/layer.cpp b/src/core/layer.cpp index 8ad9f41a..e1d0490a 100644 --- a/src/core/layer.cpp +++ b/src/core/layer.cpp @@ -22,6 +22,7 @@ #include "strata/kernels/native_router.hpp" #include "strata/kernels/native_qsa.hpp" #include "strata/kernels/native_qsa_indexer.hpp" +#include "strata/kernels/mrope.hpp" #include "strata/kernels/native_rope.hpp" #include "strata/kernels/native_flash_attn.hpp" #include "strata/kernels/fused_gr.hpp" @@ -662,6 +663,8 @@ uint64_t qsa_state_init(const ModelGeometry& g, int64_t max_cells, void* base, Q hc.data(), hs.data()); cudaMemcpy(st.cos_tab, hc.data(), hc.size() * 4, cudaMemcpyHostToDevice); cudaMemcpy(st.sin_tab, hs.data(), hs.size() * 4, cudaMemcpyHostToDevice); + if (s.n_rot == 64) // the native and prompt-path rope kernels read it (mrope.hpp) + strata::kernels::rope_table_set(st.cos_tab, st.sin_tab, (int) max_cells, strata::kernels::rope_scaling()); } // the page table starts as the IDENTITY, which is the simplest legal mapping and what a caller that does // not page at all wants; a streamed state starts with nothing resident, a ring at `block % n_slots`. diff --git a/src/kernels/cuda/native_qsa_indexer.cu b/src/kernels/cuda/native_qsa_indexer.cu index 299199a9..b91fdbd5 100644 --- a/src/kernels/cuda/native_qsa_indexer.cu +++ b/src/kernels/cuda/native_qsa_indexer.cu @@ -45,7 +45,7 @@ __global__ void append(const float* __restrict__ raw, const int32_t* __restrict_ float* __restrict__ pooled, int32_t* __restrict__ block_pos, int max_cells, float theta_scale, float freq_scale, float corr_low, float corr_high, float ext_factor, float mscale, - const int32_t* __restrict__ mtab) { + const int32_t* __restrict__ mtab, RopeTab rt) { const int pos = *pos_dev, d = threadIdx.x; if (pos < 0 || pos >= max_cells) return; const int slot = pos % R; @@ -87,9 +87,11 @@ __global__ void append(const float* __restrict__ raw, const int32_t* __restrict_ const int pair = d % (ROT / 2); // The spare (pos == 0) keeps its zero angle; under YaRN the mscale magnitude still rides in // through cos(0) - which is exactly what the queries are scaled by, so the top-k is unmoved. - const float theta_extrap = (pos == 0 ? 0 : mrope_pos(mtab, rope_pos, pair)) * powf(theta_scale, float(pair)); float c, s; - rope_scaled_angle(theta_extrap, freq_scale, corr_low, corr_high, ext_factor, mscale, pair, c, s); + if (!rope_tab_cs(rt, pos == 0 ? 0 : mrope_pos(mtab, rope_pos, pair), pair, c, s)) { + const float theta_extrap = (pos == 0 ? 0 : mrope_pos(mtab, rope_pos, pair)) * powf(theta_scale, float(pair)); + rope_scaled_angle(theta_extrap, freq_scale, corr_low, corr_high, ext_factor, mscale, pair, c, s); + } const float a = values[pair], z = values[pair + ROT / 2]; y = d < ROT / 2 ? a * c - z * s : a * s + z * c; } @@ -105,16 +107,19 @@ __global__ void append(const float* __restrict__ raw, const int32_t* __restrict_ // spare after it (every earlier one's is overwritten by the next block in order). __device__ __forceinline__ float pooled_value(const float* values, int d, int rope_pos, float theta_scale, float freq_scale, float corr_low, float corr_high, - float ext_factor, float mscale, const int32_t* mtab, bool zero_pos) { + float ext_factor, float mscale, const int32_t* mtab, bool zero_pos, + const RopeTab& rt) { float y = values[d]; if (d < ROT) { const int pair = d % (ROT / 2); // The same rotation the single append applies, rope_scaling.hpp's helper shared: under none this is // today's cosf/sinf; under linear/YaRN the pooled keys move with the cache's K, and the spare's zero // angle carries the mscale magnitude through cos(0) exactly as the single append's does. - const float theta_extrap = (zero_pos ? 0 : mrope_pos(mtab, rope_pos, pair)) * powf(theta_scale, float(pair)); float c, s; - rope_scaled_angle(theta_extrap, freq_scale, corr_low, corr_high, ext_factor, mscale, pair, c, s); + if (!rope_tab_cs(rt, zero_pos ? 0 : mrope_pos(mtab, rope_pos, pair), pair, c, s)) { + const float theta_extrap = (zero_pos ? 0 : mrope_pos(mtab, rope_pos, pair)) * powf(theta_scale, float(pair)); + rope_scaled_angle(theta_extrap, freq_scale, corr_low, corr_high, ext_factor, mscale, pair, c, s); + } const float a = values[pair], z = values[pair + ROT / 2]; y = d < ROT / 2 ? a * c - z * s : a * s + z * c; } @@ -134,7 +139,7 @@ __device__ __forceinline__ float norm_scale(float mean, float* partials, int d) __global__ void append_first(const float* __restrict__ raw, const float* __restrict__ gamma, float epsilon, float* __restrict__ dead, float* __restrict__ pooled, float theta_scale, float freq_scale, float corr_low, float corr_high, float ext_factor, float mscale, - const int32_t* __restrict__ mtab) { + const int32_t* __restrict__ mtab, RopeTab rt) { const int d = threadIdx.x; __shared__ float values[D]; __shared__ float partials[32]; @@ -152,7 +157,7 @@ __global__ void append_first(const float* __restrict__ raw, const float* __restr __syncthreads(); if (d >= D) return; const float y = pooled_value(values, d, 0, theta_scale, freq_scale, corr_low, corr_high, ext_factor, mscale, - mtab, true); + mtab, true, rt); pooled[d] = y; dead[d] = y; } @@ -161,7 +166,7 @@ __global__ void append_blocks(const float* __restrict__ raw, int64_t n, int64_t const float* __restrict__ dead, float* __restrict__ pooled, int32_t* __restrict__ block_pos, int64_t first_block, int64_t last_block, float theta_scale, float freq_scale, float corr_low, float corr_high, float ext_factor, float mscale, - const int32_t* __restrict__ mtab) { + const int32_t* __restrict__ mtab, RopeTab rt) { const int64_t b = first_block + blockIdx.x; const int d = threadIdx.x; __shared__ float values[D]; @@ -184,7 +189,7 @@ __global__ void append_blocks(const float* __restrict__ raw, int64_t n, int64_t if (d >= D) return; const int rope_pos = pos_base + R * (int) b; pooled[std::size_t(b) * D + d] = pooled_value(values, d, rope_pos, theta_scale, freq_scale, corr_low, corr_high, - ext_factor, mscale, mtab, false); + ext_factor, mscale, mtab, false, rt); if (b == last_block) { pooled[std::size_t(b + 1) * D + d] = dead[d]; if (d == 0) *block_pos = rope_pos; @@ -230,7 +235,7 @@ void native_qsa_indexer_append(const float* raw, const int32_t* relative_pos_dev const RopeKernelArgs k = scaling.kernel_args(ROT); // none: the identity constants append<<<1,THREADS,0,static_cast(stream)>>>(raw,relative_pos_device,pos_base,gamma,epsilon, b.tail,b.dead,b.pooled,b.block_pos,int(max_cells),theta_scale,k.freq_scale, - k.corr_low,k.corr_high,k.ext_factor,k.attn_factor,mrope_table()); + k.corr_low,k.corr_high,k.ext_factor,k.attn_factor,mrope_table(),rope_table_for(scaling)); const auto error = cudaGetLastError(); if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error)); } @@ -247,15 +252,16 @@ void native_qsa_indexer_append_batch(const float* raw, int64_t n, int64_t p0, in const float fsf = k.freq_scale, cl = k.corr_low, ch = k.corr_high, ef = k.ext_factor, ms = k.attn_factor; const cudaStream_t st = static_cast(stream); const int32_t* mtab = mrope_table(); + const RopeTab rt = rope_table_for(scaling); if (p0 == 0) append_first<<<1, THREADS, 0, st>>>(raw, gamma, epsilon, b.dead, b.pooled, theta_scale, - fsf, cl, ch, ef, ms, mtab); + fsf, cl, ch, ef, ms, mtab, rt); // completed blocks: those whose last cell (4b+3) lies in [p0, p0 + n) const int64_t first = p0 <= R - 1 ? 0 : (p0 - (R - 1) + R - 1) / R; // the smallest b with 4b+3 >= p0 const int64_t hi = p0 + n - 1 >= R - 1 ? (p0 + n - 1 - (R - 1)) / R : -1; // the largest b with 4b+3 <= p0+n-1 if (hi >= first) append_blocks<<<(unsigned) (hi - first + 1), THREADS, 0, st>>>(raw, n, p0, pos_base, gamma, epsilon, b.tail, b.dead, b.pooled, b.block_pos, first, hi, - theta_scale, fsf, cl, ch, ef, ms, mtab); + theta_scale, fsf, cl, ch, ef, ms, mtab, rt); append_tail<<>>(raw, n, p0, b.tail); const auto error = cudaGetLastError(); if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error)); diff --git a/src/kernels/cuda/native_rope.cu b/src/kernels/cuda/native_rope.cu index 46311720..44418401 100644 --- a/src/kernels/cuda/native_rope.cu +++ b/src/kernels/cuda/native_rope.cu @@ -28,6 +28,7 @@ #include #include #include +#include #include #include @@ -40,7 +41,7 @@ bool overlaps(const void* a, size_t an, const void* b, size_t bn) { } __global__ void apply(const float* x, float* out, int rows, int width, int n_rot, float theta_scale, float freq_scale, float corr_low, float corr_high, - float ext_factor, float mscale, const int* positions, const int32_t* mtab) { + float ext_factor, float mscale, const int* positions, const int32_t* mtab, RopeTab rt) { const int row = blockIdx.y; const int pair = blockIdx.x * blockDim.x + threadIdx.x; if (row >= rows || pair >= width / 2) return; @@ -52,9 +53,11 @@ __global__ void apply(const float* x, float* out, int rows, int width, } return; } - const float theta_extrap = mrope_pos(mtab, positions[row], pair) * powf(theta_scale, float(pair)); float c, s; - rope_scaled_angle(theta_extrap, freq_scale, corr_low, corr_high, ext_factor, mscale, pair, c, s); + if (!rope_tab_cs(rt, mrope_pos(mtab, positions[row], pair), pair, c, s)) { + const float theta_extrap = mrope_pos(mtab, positions[row], pair) * powf(theta_scale, float(pair)); + rope_scaled_angle(theta_extrap, freq_scale, corr_low, corr_high, ext_factor, mscale, pair, c, s); + } const float a = x[start + pair], b = x[start + pair + n_rot / 2]; out[start + pair] = a * c - b * s; out[start + pair + n_rot / 2] = a * s + b * c; @@ -72,6 +75,31 @@ int mrope_dev() { } // namespace void mrope_table_set(const int32_t* device_table) { mrope_tab[mrope_dev()].store(device_table, std::memory_order_relaxed); } const int32_t* mrope_table() { return mrope_tab[mrope_dev()].load(std::memory_order_relaxed); } +namespace { +// #280: the float64 angle table of each device, set at session init (before any graph is captured) +struct RopeReg { + RopeTab tab; + RopeScaling scaling; +}; +RopeReg rope_tab[kMropeDevices] = {}; +bool same_scaling(const RopeScaling& a, const RopeScaling& b) { + return a.type == b.type && a.freq_base == b.freq_base && a.factor == b.factor && a.freq_scale_in == b.freq_scale_in && + a.orig_ctx == b.orig_ctx && a.ext_factor == b.ext_factor && a.attn_factor == b.attn_factor && + a.beta_fast == b.beta_fast && a.beta_slow == b.beta_slow; +} +bool rope_table_enabled() { + static const bool on = std::getenv("STRATA_ROPE_LEGACY") == nullptr; // STRATA_ROPE_LEGACY=1: the A/B arm + return on; +} +} // namespace +void rope_table_set(const float* cos_tab, const float* sin_tab, int max_pos, const RopeScaling& scaling) { + rope_tab[mrope_dev()] = RopeReg{RopeTab{cos_tab, sin_tab, max_pos}, scaling}; +} +RopeTab rope_table_for(const RopeScaling& scaling) { + if (!rope_table_enabled()) return {}; + const RopeReg& r = rope_tab[mrope_dev()]; + return r.tab.cos != nullptr && same_scaling(r.scaling, scaling) ? r.tab : RopeTab{}; +} void native_rope_set_enabled(bool value) { enabled.store(value, std::memory_order_relaxed); } bool native_rope_enabled() { return enabled.load(std::memory_order_relaxed); } void native_rope_apply(const float* x, float* out, int rows, int head_dim, @@ -95,7 +123,7 @@ void native_rope_apply(const float* x, float* out, int rows, int head_dim, apply<<(stream)>>>(x, out, rows, head_dim, n_rot, theta_scale, k.freq_scale, k.corr_low, k.corr_high, k.ext_factor, - k.attn_factor, positions, mrope_table()); + k.attn_factor, positions, mrope_table(), rope_table_for(scaling)); const auto error = cudaGetLastError(); if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error)); } diff --git a/src/prefill/kernels.cu b/src/prefill/kernels.cu index 25c12004..0035833b 100644 --- a/src/prefill/kernels.cu +++ b/src/prefill/kernels.cu @@ -561,16 +561,19 @@ __global__ void rms_rows_kernel(float* __restrict__ x, const float* __restrict__ } __global__ void rope_kernel(float* __restrict__ x, int64_t heads, int64_t dim, int64_t ld, int64_t pos0, float theta_scale, float freq_scale, float corr_low, float corr_high, - float ext_factor, float mscale, const int32_t* __restrict__ mtab) { + float ext_factor, float mscale, const int32_t* __restrict__ mtab, + strata::kernels::RopeTab rt) { const int64_t row = blockIdx.x; // t * heads + h const int pair = threadIdx.x; // 0..31 const int64_t t = row / heads, h = row % heads; float* p = x + t * ld + h * dim; - const float theta_extrap = - (float) strata::kernels::mrope_pos(mtab, (int) (pos0 + t), pair) * powf(theta_scale, (float) pair); float c, s; - strata::kernels::rope_scaled_angle(theta_extrap, freq_scale, corr_low, corr_high, ext_factor, mscale, - pair, c, s); + if (!strata::kernels::rope_tab_cs(rt, strata::kernels::mrope_pos(mtab, (int) (pos0 + t), pair), pair, c, s)) { + const float theta_extrap = + (float) strata::kernels::mrope_pos(mtab, (int) (pos0 + t), pair) * powf(theta_scale, (float) pair); + strata::kernels::rope_scaled_angle(theta_extrap, freq_scale, corr_low, corr_high, ext_factor, mscale, + pair, c, s); + } const float a = p[pair], b = p[pair + 32]; p[pair] = a * c - b * s; p[pair + 32] = a * s + b * c; @@ -813,7 +816,7 @@ void rope(float* x, int64_t T, int64_t heads, int64_t dim, int64_t ld, int64_t p const strata::kernels::RopeKernelArgs k = scaling.kernel_args(64); // none: the identity constants rope_kernel<<<(unsigned) (T * heads), 32, 0, (cudaStream_t) stream>>>( x, heads, dim, ld, pos0, theta_scale, k.freq_scale, k.corr_low, k.corr_high, k.ext_factor, k.attn_factor, - strata::kernels::mrope_table()); + strata::kernels::mrope_table(), strata::kernels::rope_table_for(scaling)); check("rope"); } void split_q(const float* q_full, float* q, int64_t T, void* stream) { From 0f461187d2c52185c178ca1db4859bff8c9f3625 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Thu, 1 Oct 2026 08:43:38 +0200 Subject: [PATCH 35/48] #280 follow-up: the float64 RoPE table is opt-in (STRATA_ROPE_TABLE=1); a freed session's table is forgotten - The table's angles differ from the fast-math cosf/sinf ones in the last bits, so every output moves: off by default (the kernels compute the angle exactly as 0.1.31), STRATA_ROPE_TABLE=1 turns it on (replaces the PR's STRATA_ROPE_LEGACY A/B switch). - The per-device registration was a raw pointer into the session's arena that outlived it: QsaState::owns_rope marks the state that built the table (not one that borrowed it with share_rope, like the MTP drafter's), and session_release() - to be called before a session's memory is freed - clears every device's entry pointing at it (rope_table_release). The latest session of a device now wins, instead of the longest table. --- include/strata/core/layer.hpp | 1 + include/strata/core/session.hpp | 3 +++ include/strata/kernels/mrope.hpp | 11 +++++++---- src/core/layer.cpp | 3 ++- src/core/session.cpp | 9 +++++++++ src/kernels/cuda/native_rope.cu | 11 ++++++++++- 6 files changed, 32 insertions(+), 6 deletions(-) diff --git a/include/strata/core/layer.hpp b/include/strata/core/layer.hpp index 1669256f..34254a61 100644 --- a/include/strata/core/layer.hpp +++ b/include/strata/core/layer.hpp @@ -237,6 +237,7 @@ struct QsaState { int32_t* idx_block_pos = nullptr; float* cos_tab = nullptr; ///< (max_cells, n_rot/2), built on the HOST in float64 + bool owns_rope = false; ///< built the table above (not borrowed with share_rope): it releases it float* sin_tab = nullptr; /// THE PER-TOKEN COUNTS, IN DEVICE MEMORY - the whole reason this layer can be a graph. `qsa_step_fill` diff --git a/include/strata/core/session.hpp b/include/strata/core/session.hpp index c05d7e99..6d1becfa 100644 --- a/include/strata/core/session.hpp +++ b/include/strata/core/session.hpp @@ -99,6 +99,9 @@ uint64_t session_bytes(const ModelGeometry& g, int64_t max_cells, int64_t k, int /// Carves `base` (DEVICE memory) into `s`. Returns the bytes used. Same range convention as `session_bytes`. uint64_t session_init(const ModelGeometry& g, int64_t max_cells, int64_t k, void* base, SessionState& s, int64_t layer_lo = 0, int64_t layer_hi = -1); +/// Before the memory `session_init` carved is freed: forgets what points into it from outside the session (the +/// rope kernels' registered angle table, #280), so a later session never rotates by freed memory. +void session_release(SessionState& s); /// Zeroes every layer's state - the residual to `R_init`, everything else to zero, so a fresh sequence starts /// from the reference's own `zeros()`. void session_zero(SessionState& s, const ModelGeometry& g, const float* R_init, void* stream); diff --git a/include/strata/kernels/mrope.hpp b/include/strata/kernels/mrope.hpp index 8f456e43..cb1451c4 100644 --- a/include/strata/kernels/mrope.hpp +++ b/include/strata/kernels/mrope.hpp @@ -24,9 +24,9 @@ namespace strata::kernels { void mrope_table_set(const int32_t* device_table); const int32_t* mrope_table(); -/// The rotation angles, 32 pairs of a 64-wide rotary slice: the session's float64 table (build_rope_table, -/// [max_pos][32] cos and sin in VRAM, the rope scaling inside) of the CURRENT device. With it the rope kernels -/// rotate by the table's exact angles; without it they compute pos * powf(...) with cosf/sinf, which under +/// #280, opt-in (STRATA_ROPE_TABLE=1): the rotation angles, 32 pairs of a 64-wide rotary slice, from the session's +/// float64 table (build_rope_table, [max_pos][32] cos and sin in VRAM, the rope scaling inside) of the CURRENT +/// device. With it the rope kernels rotate by the table's exact angles; without it they compute pos * powf(...) with cosf/sinf, which under /// --use_fast_math is 0.0014 rad off at 32K and ~0.02 at 262K, and the prompt path (precise libm) and decode /// (fast-math) disagree with each other. struct RopeTab { @@ -36,7 +36,10 @@ struct RopeTab { }; /// Registers the table the session just built with `scaling` (the latest one of the device wins). void rope_table_set(const float* cos_tab, const float* sin_tab, int max_pos, const RopeScaling& scaling); -/// The registered table when the rope kernels are to read it and it was built with `scaling`; otherwise none. +/// Forgets the table `cos_tab` (on every device) - before the memory that holds it is freed (session_release). +void rope_table_release(const float* cos_tab); +/// The registered table when STRATA_ROPE_TABLE=1 and it was built with `scaling`; otherwise none (the default: the +/// kernels compute the angle exactly as before). RopeTab rope_table_for(const RopeScaling& scaling); #if defined(__CUDACC__) || defined(__HIPCC__) diff --git a/src/core/layer.cpp b/src/core/layer.cpp index e1d0490a..e816da1c 100644 --- a/src/core/layer.cpp +++ b/src/core/layer.cpp @@ -663,7 +663,8 @@ uint64_t qsa_state_init(const ModelGeometry& g, int64_t max_cells, void* base, Q hc.data(), hs.data()); cudaMemcpy(st.cos_tab, hc.data(), hc.size() * 4, cudaMemcpyHostToDevice); cudaMemcpy(st.sin_tab, hs.data(), hs.size() * 4, cudaMemcpyHostToDevice); - if (s.n_rot == 64) // the native and prompt-path rope kernels read it (mrope.hpp) + st.owns_rope = true; + if (s.n_rot == 64) // the native and prompt-path rope kernels read it (mrope.hpp, STRATA_ROPE_TABLE=1) strata::kernels::rope_table_set(st.cos_tab, st.sin_tab, (int) max_cells, strata::kernels::rope_scaling()); } // the page table starts as the IDENTITY, which is the simplest legal mapping and what a caller that does diff --git a/src/core/session.cpp b/src/core/session.cpp index 2211e9ba..14c61663 100644 --- a/src/core/session.cpp +++ b/src/core/session.cpp @@ -1,5 +1,6 @@ // src/core/session.cpp - one token through all 48 layers. See the header for why the graphs are per-layer. #include "strata/core/session.hpp" +#include "strata/kernels/mrope.hpp" #include "strata/core/progress.hpp" #include "strata/kernels/qsa.hpp" @@ -127,6 +128,14 @@ uint64_t session_init(const ModelGeometry& g, int64_t max_cells, int64_t k, void return used; } +void session_release(SessionState& s) { + for (int64_t j = 0; s.qsa_states != nullptr && j < s.qsa_alloc; ++j) + if (s.qsa_states[j].owns_rope) { + strata::kernels::rope_table_release(s.qsa_states[j].cos_tab); + s.qsa_states[j].owns_rope = false; + } +} + void session_zero(SessionState& s, const ModelGeometry& g, const float* R_init, void* stream) { cudaStream_t cs = (cudaStream_t) stream; // the residual: `hc` copies of the one vector a caller hands in. A real sequence's first token is the diff --git a/src/kernels/cuda/native_rope.cu b/src/kernels/cuda/native_rope.cu index 44418401..b34f4e67 100644 --- a/src/kernels/cuda/native_rope.cu +++ b/src/kernels/cuda/native_rope.cu @@ -87,14 +87,23 @@ bool same_scaling(const RopeScaling& a, const RopeScaling& b) { a.orig_ctx == b.orig_ctx && a.ext_factor == b.ext_factor && a.attn_factor == b.attn_factor && a.beta_fast == b.beta_fast && a.beta_slow == b.beta_slow; } +// opt-in: STRATA_ROPE_TABLE=1 (the table's angles differ from the fast-math ones in the last bits, so outputs move) bool rope_table_enabled() { - static const bool on = std::getenv("STRATA_ROPE_LEGACY") == nullptr; // STRATA_ROPE_LEGACY=1: the A/B arm + static const bool on = [] { + const char* e = std::getenv("STRATA_ROPE_TABLE"); + return e != nullptr && e[0] == '1'; + }(); return on; } } // namespace void rope_table_set(const float* cos_tab, const float* sin_tab, int max_pos, const RopeScaling& scaling) { rope_tab[mrope_dev()] = RopeReg{RopeTab{cos_tab, sin_tab, max_pos}, scaling}; } +void rope_table_release(const float* cos_tab) { + // every device's entry that points at it (the caller may free it from another current device) + for (RopeReg& r : rope_tab) + if (cos_tab != nullptr && r.tab.cos == cos_tab) r = RopeReg{}; +} RopeTab rope_table_for(const RopeScaling& scaling) { if (!rope_table_enabled()) return {}; const RopeReg& r = rope_tab[mrope_dev()]; From f133c655a865244d966e5f53735719419471c376 Mon Sep 17 00:00:00 2001 From: sergiywith Date: Wed, 30 Sep 2026 22:25:39 +0300 Subject: [PATCH 36/48] KV: optional Hadamard rotation for int8 K/V (STRATA_KV_ROT=1); the drafter and the batched verify rotation-consistent INT8 K and V can go through the Walsh-Hadamard rotation --kv q4_0 already uses (kv_q4.hpp): it spreads outlier channels over the 64-value scale groups before quantization; the queries are rotated too ( = ) and the output rotated back. - QsaState::kv_rot: Q4_0 always, INT8 with STRATA_KV_ROT=1 (off by default: the same tokens as main). - Every writer and reader follows it: decode, the verify window, the prompt path, the MTP drafter, and the drafter's batched prompt pass (Prefill::draft_kv) - which rotated only for Q4_0. - verify.cpp: the batched window path (qb) never rotated its queries; it did not matter while Q4_0 was kept off it. First-token KL to fp16 K/V, 4 prompts incl. 32K: NVFP4 pack 0.0066 -> 0.0051; IQ2_XS 0.0022 -> 0.0054. Hence opt-in. --- include/strata/core/layer.hpp | 5 +++++ src/core/layer.cpp | 17 +++++++++++------ src/core/mtp.cpp | 6 +++--- src/core/verify.cpp | 7 ++++--- src/prefill/prefill.cpp | 27 ++++++++++++++++----------- src/program/generate.cpp | 6 +++++- 6 files changed, 44 insertions(+), 24 deletions(-) diff --git a/include/strata/core/layer.hpp b/include/strata/core/layer.hpp index 34254a61..a8965da1 100644 --- a/include/strata/core/layer.hpp +++ b/include/strata/core/layer.hpp @@ -217,6 +217,9 @@ struct QsaState { /// Uses k_q/k_scale + v_q4. Mode 0 only (no KV streaming, no ring); under this setting the MTP drafter's /// ring state stays plain INT8, so the block movers never see the hybrid layout. bool kv_hybrid = false; + /// K and V go through kv_q4.hpp's Walsh-Hadamard rotation before they are stored, the queries too, the output + /// back: always for Q4_0, for INT8 by qsa_set_kv_int8_rotate (spreads outlier channels over the scale groups) + bool kv_rot = false; int32_t* page_table = nullptr; ///< (n_pages,) logical page -> physical page (-1: not resident, streamed) int64_t n_pages = 0; int64_t max_cells = 0; @@ -279,6 +282,8 @@ uint64_t qsa_kv_host_bytes(); /// Plan v0.3 P7: store K/V as INT8 with FP16 scales per 64 values (half the VRAM of FP16). Set before sizing and /// initializing the session; default off until gate G-C accepts it. void qsa_set_kv_int8(bool enabled); +/// INT8 K/V through the Hadamard rotation (off by default: STRATA_KV_ROT=1) +void qsa_set_kv_int8_rotate(bool enabled); bool qsa_kv_int8(); /// PR #21: store K/V as Q4_0 after a Hadamard rotation (`--kv q4_0`): 576 B per cell, vs 1,056 in INT8. void qsa_set_kv_q4(bool enabled); diff --git a/src/core/layer.cpp b/src/core/layer.cpp index e816da1c..ff7fc17b 100644 --- a/src/core/layer.cpp +++ b/src/core/layer.cpp @@ -173,8 +173,9 @@ if (!w.wants_q8k()) { s_gemv_q8_0_split(x80, p.codes, p.scales, p.offset, // namespace void layer_set_native_bf16(bool enabled) { native_bf16_projections = enabled; } void layer_set_native_flash_attn_short(bool enabled) { native_flash_attn_short = enabled; } -namespace { bool g_kv_int8 = false, g_kv_q4 = false, g_kv_hybrid = false; } +namespace { bool g_kv_int8 = false, g_kv_q4 = false, g_kv_hybrid = false, g_kv_int8_rot = false; } void qsa_set_kv_int8(bool enabled) { g_kv_int8 = enabled; } +void qsa_set_kv_int8_rotate(bool enabled) { g_kv_int8_rot = enabled; } bool qsa_kv_int8() { return g_kv_int8; } void qsa_set_kv_q4(bool enabled) { g_kv_q4 = enabled; } bool qsa_kv_q4() { return g_kv_q4; } @@ -564,6 +565,7 @@ uint64_t qsa_state_init(const ModelGeometry& g, int64_t max_cells, void* base, Q st.kv_int8 = false; st.kv_q4 = false; } + st.kv_rot = st.kv_q4 || (st.kv_int8 && g_kv_int8_rot); // K8V4 rotates only V (below) st.kv_mode = p.mode; st.n_slots = p.slots; const uint64_t rows = (uint64_t) p.slots * s.n_head_kv * s.page_size; // VRAM rows: the slots @@ -903,11 +905,14 @@ if (st.kv_hybrid) { strata::kernels::fwht256_inplace_cuda(b.vcur, g.n_head_kv, stream); kv_append_q8_step(st.k_q, st.k_q, st.k_scale, st.k_scale, st.page_table, st.step, b.kcur, b.kcur, s, stream, nullptr); // mode 0: no host mirror strata::kernels::kv_append_q4_step(st.v_q4, st.v_q4, st.page_table, st.step, b.vcur, b.vcur, s, stream, nullptr); -} else if (st.kv_q4) { - strata::kernels::fwht256_inplace_cuda(b.kcur, g.n_head_kv, stream); // Q4_0: rotated K and V (kv_q4.hpp) +} else { +if (st.kv_rot) { // rotated K and V (kv_q4.hpp): Q4_0, and INT8 with STRATA_KV_ROT=1 + strata::kernels::fwht256_inplace_cuda(b.kcur, g.n_head_kv, stream); strata::kernels::fwht256_inplace_cuda(b.vcur, g.n_head_kv, stream); +} +if (st.kv_q4) { strata::kernels::kv_append_q4_step(st.k_q4, st.v_q4, st.page_table, st.step, b.kcur, b.vcur, s, stream, &st.host); -} else if (st.kv_int8) kv_append_q8_step(st.k_q, st.v_q, st.k_scale, st.v_scale, st.page_table, st.step, b.kcur, b.vcur, s, stream, &st.host); else kv_append_step(st.k_pool, st.v_pool, st.page_table, st.step, b.kcur, b.vcur, s, stream, &st.host); { const uint64_t nvk = (uint64_t) g.n_head_kv * g.head_dim; const uint64_t base = (uint64_t) 2 * g.n_embd + 2 * g.hc + (uint64_t) g.n_head * g.head_dim + 2 * nvk + 8; if (!st.kv_int8 && !st.kv_hybrid) dump_slot(dump, g, layer, (const float*) st.k_pool, base, nvk / 2, stream); if (!st.kv_int8 && !st.kv_hybrid) dump_slot(dump, g, layer, (const float*) st.v_pool, base + nvk / 2, nvk / 2, stream); dump_slot(dump, g, layer, b.vcur, base + nvk, nvk, stream); dump_slot(dump, g, layer, b.kcur, base + 2 * nvk, nvk, stream); } { const QsaIndexerBuffers ib{st.idx_tail, st.idx_dead, st.idx_pooled, st.idx_block_pos}; if (native_qsa_indexer_enabled()) { +} else if (st.kv_int8) kv_append_q8_step(st.k_q, st.v_q, st.k_scale, st.v_scale, st.page_table, st.step, b.kcur, b.vcur, s, stream, &st.host); else kv_append_step(st.k_pool, st.v_pool, st.page_table, st.step, b.kcur, b.vcur, s, stream, &st.host); } /* not K8V4 */ { const uint64_t nvk = (uint64_t) g.n_head_kv * g.head_dim; const uint64_t base = (uint64_t) 2 * g.n_embd + 2 * g.hc + (uint64_t) g.n_head * g.head_dim + 2 * nvk + 8; if (!st.kv_int8 && !st.kv_hybrid) dump_slot(dump, g, layer, (const float*) st.k_pool, base, nvk / 2, stream); if (!st.kv_int8 && !st.kv_hybrid) dump_slot(dump, g, layer, (const float*) st.v_pool, base + nvk / 2, nvk / 2, stream); dump_slot(dump, g, layer, b.vcur, base + nvk, nvk, stream); dump_slot(dump, g, layer, b.kcur, base + 2 * nvk, nvk, stream); } { const QsaIndexerBuffers ib{st.idx_tail, st.idx_dead, st.idx_pooled, st.idx_block_pos}; if (native_qsa_indexer_enabled()) { try { native_qsa_indexer_append(b.idx_raw, st.step + kStepPos, pos_base, (const float*) w_ikn->data, RMS_EPS, ib, s, st.max_cells, rope_scaling(), stream); @@ -941,7 +946,7 @@ int64_t max_blocks = (st.max_cells / s.idx_block) + 2; } // KV streaming: every block the selection names is made resident before anything reads it qsa_kv_resolve(st, g, b.ids, st.step, 1, cap, stream); - if (st.kv_q4) strata::kernels::fwht256_inplace_cuda(b.qcur, g.n_head, stream); // = + if (st.kv_rot) strata::kernels::fwht256_inplace_cuda(b.qcur, g.n_head, stream); // = if (g_fast_attn && !native_flash_attn_short && dump == nullptr) { const strata::kernels::QsaAttnPools pools = qsa_attn_pools(st); strata::kernels::qsa_decode_attn_step(b.qcur, pools, b.ids, st.step, cap, s, b.attn_scratch, b.attn, stream); @@ -968,7 +973,7 @@ int64_t max_blocks = (st.max_cells / s.idx_block) + 2; } } else qsa_attend_step(b.qcur, b.k_scratch, b.v_scratch, st.step, cap, s, b.attn, nullptr, stream); } - if (st.kv_q4 || st.kv_hybrid) strata::kernels::fwht256_inplace_cuda(b.attn, g.n_head, stream); // the output back: H is self-inverse + if (st.kv_rot || st.kv_hybrid) strata::kernels::fwht256_inplace_cuda(b.attn, g.n_head, stream); // the output back: H is self-inverse dump_slot(dump, g, layer, b.attn, (uint64_t) 2 * g.n_embd + 2 * g.hc, (uint64_t) g.n_head * g.head_dim, stream); { const uint64_t vs = (uint64_t) 2 * g.n_embd + 2 * g.hc + (uint64_t) g.n_head * g.head_dim + (uint64_t) 2 * g.n_head_kv * g.head_dim; dump_slot(dump, g, layer, (const float*) b.v_scratch, vs, (uint64_t) g.n_head_kv * g.head_dim / 2, stream); dump_slot(dump, g, layer, (const float*) b.ids, vs + (uint64_t) g.n_head_kv * g.head_dim / 2, 4, stream); dump_slot(dump, g, layer, (const float*) st.step, vs + (uint64_t) g.n_head_kv * g.head_dim / 2 + 4, 4, stream); } // ---- 9. Gate the attention output before its projection. Native CUDA keeps F32 // sigmoid/multiply arithmetic and uses Q8_1 for the native quantized projection. diff --git a/src/core/mtp.cpp b/src/core/mtp.cpp index 56678374..90be8162 100644 --- a/src/core/mtp.cpp +++ b/src/core/mtp.cpp @@ -471,7 +471,7 @@ bool MtpDrafter::record_forward(int T, int step_row0, cudaStream_t cs, std::stri native_mmvq(GGML_Q8_0, q8("self_attn.v_proj.weight"), xq_, vcur_, (int) N, (int) (NKV * HD), T, cs); for (int t = 0; t < T; ++t) { norm_rope(kcur_ + t * NKV * HD, f32("self_attn.k_norm.weight"), (int) NKV, (int) HD, pos + t * NH); - if (st_.kv_q4) { // Q4_0 KV (kv_q4.hpp): rotated K and V + if (st_.kv_rot) { // rotated K and V (kv_q4.hpp) fwht256_inplace_cuda(kcur_ + t * NKV * HD, NKV, cs); fwht256_inplace_cuda(vcur_ + t * NKV * HD, NKV, cs); kv_append_q4_step(st_.k_q4, st_.v_q4, st_.page_table, step + t * 4, kcur_ + t * NKV * HD, @@ -493,12 +493,12 @@ bool MtpDrafter::record_forward(int T, int step_row0, cudaStream_t cs, std::stri return false; } norm_rope(qc, f32("self_attn.q_norm.weight"), (int) NH, (int) HD, pos + t * NH); - if (st_.kv_q4) fwht256_inplace_cuda(qc, NH, cs); + if (st_.kv_rot) fwht256_inplace_cuda(qc, NH, cs); } const QsaAttnPools pools = qsa_attn_pools(st_); if (window_ > 0) window_ids(const_cast(step), T, (int) window_, ident_, cap_, cs); qsa_decode_attn_batch(qcur_, pools, ident_, step, cap_, s, attn_scratch_, attn_, T, cs); - if (st_.kv_q4) fwht256_inplace_cuda(attn_, (int64_t) T * NH, cs); + if (st_.kv_rot) fwht256_inplace_cuda(attn_, (int64_t) T * NH, cs); for (int t = 0; t < T; ++t) native_qsa_gate_apply(attn_ + t * NH * HD, qfull_ + t * NH * 2 * HD, attn32_ + t * NH * HD, (int) NH, (int) HD, cs); native_quantize_q8_1(attn32_, xq_, (int) (NH * HD), T, cs); diff --git a/src/core/verify.cpp b/src/core/verify.cpp index ebe0c897..76f4e488 100644 --- a/src/core/verify.cpp +++ b/src/core/verify.cpp @@ -573,7 +573,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { native_mmvq(wv->native_type, wv->native_data, xq_, vcur_ + tb * NKV * HD, (int) N, (int) (NKV * HD), n, cs); if (qb) norm_rope(kcur_ + tb * NKV * HD, wkn, (int) (n * NKV), (int) HD, pos_k + tb * NKV); else for (int t = tb; t < te; ++t) norm_rope(kcur_ + t * NKV * HD, wkn, (int) NKV, (int) HD, pos_ + t * NH); - if (st.kv_q4) { // Q4_0 KV (kv_q4.hpp): K and V rotated before they are stored + if (st.kv_rot) { // K and V rotated before they are stored (kv_q4.hpp) fwht256_inplace_cuda(kcur_ + tb * NKV * HD, (int64_t) n * NKV, cs); fwht256_inplace_cuda(vcur_ + tb * NKV * HD, (int64_t) n * NKV, cs); } else if (st.kv_hybrid) { // K8V4: only V is rotated @@ -613,6 +613,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { return false; } norm_rope(qcur_ + tb * NH * HD, wqn, (int) (n * NH), (int) HD, pos_ + tb * NH); + if (st.kv_rot) fwht256_inplace_cuda(qcur_ + tb * NH * HD, (int64_t) n * NH, cs); // = bf16_gemv_fp32_mmvf_multi(mixed_ + tb * N, N, (const uint16_t*) wiq->data, qidx_ + tb * IQ * ID, IQ * ID, N, IQ * ID, n, cs); norm_rope(qidx_ + tb * IQ * ID, wiqn, (int) (n * IQ), (int) ID, pos_i + tb * IQ); @@ -625,7 +626,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { return false; } norm_rope(qc, wqn, (int) NH, (int) HD, pos_ + t * NH); - if (st.kv_q4) fwht256_inplace_cuda(qc, NH, cs); // = + if (st.kv_rot) fwht256_inplace_cuda(qc, NH, cs); // = } for (int t = tb; t < te; ++t) { float* qx = qidx_ + t * IQ * ID; @@ -646,7 +647,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { qsa_decode_attn_batch(qcur_ + tb * NH * HD, pools, sel_ + (size_t) tb * cap_, step_ + tb * kStepCount, cap_, s, attn_scratch_ + (size_t) tb * attn_scratch_floats_, attn_ + tb * NH * HD, n, cs); stamp(l, 13, grp); - if (st.kv_q4 || st.kv_hybrid) fwht256_inplace_cuda(attn_ + tb * NH * HD, (int64_t) n * NH, cs); // back: H^-1 = H + if (st.kv_rot || st.kv_hybrid) fwht256_inplace_cuda(attn_ + tb * NH * HD, (int64_t) n * NH, cs); // back: H^-1 = H if (qb) native_qsa_gate_apply(attn_ + tb * NH * HD, qfull_ + tb * NH * 2 * HD, attn32_ + tb * NH * HD, (int) (n * NH), (int) HD, cs); else diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index bd8ae5e7..74bf26f8 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -843,9 +843,11 @@ bool Prefill::draft_kv(core::MtpDrafter& mtp, const float* R_rows, const int32_t proj(mixed, mixed_h, w_v, Vc, nb, KV, Nn, 0); rms_rows(Kc, w_kn, nb * g.n_head_kv, g.head_dim, g.head_dim, EPS, m.cs); rope(Kc, nb, g.n_head_kv, g.head_dim, KV, c0, strata::kernels::rope_scaling(), m.cs); - if (st.kv_q4) { + if (st.kv_rot) { // rotated as the drafter's own decode stores them (mtp.cpp) strata::kernels::fwht256_inplace_cuda(Kc, nb * g.n_head_kv, m.cs); strata::kernels::fwht256_inplace_cuda(Vc, nb * g.n_head_kv, m.cs); + } + if (st.kv_q4) { strata::kernels::kv_append_q4(st.k_q4, st.v_q4, st.page_table, c0, nb, Kc, Vc, s, m.cs, &st.host); } else { kv_append(Kc, Vc, nb, c0, st.page_table, s.page_size, st.kv_int8 ? nullptr : st.k_pool, @@ -1376,20 +1378,23 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e staged ? &m.stage : nullptr); strata::kernels::kv_append_q4(st.v_q4, st.v_q4, st.page_table, p0, T, m.Vc, m.Vc, s, m.cs, nullptr, staged ? &m.stage : nullptr); - } else if (st.kv_q4) { // Q4_0 KV (kv_q4.hpp): rotated K and V, the queries below too, the output back - strata::kernels::fwht256_inplace_cuda(m.Kc, T * 2, m.cs); - strata::kernels::fwht256_inplace_cuda(m.Vc, T * 2, m.cs); - strata::kernels::kv_append_q4(st.k_q4, st.v_q4, st.page_table, p0, T, m.Kc, m.Vc, s, m.cs, - &st.host, staged ? &m.stage : nullptr); } else { - kv_append(m.Kc, m.Vc, T, p0, st.page_table, s.page_size, st.kv_int8 ? nullptr : st.k_pool, - st.kv_int8 ? nullptr : st.v_pool, st.k_q, st.v_q, st.k_scale, st.v_scale, m.cs, - &st.host, staged ? &m.stage : nullptr); + if (st.kv_rot) { // rotated K and V (kv_q4.hpp), the queries below too, the output back + strata::kernels::fwht256_inplace_cuda(m.Kc, T * 2, m.cs); + strata::kernels::fwht256_inplace_cuda(m.Vc, T * 2, m.cs); + } + if (st.kv_q4) + strata::kernels::kv_append_q4(st.k_q4, st.v_q4, st.page_table, p0, T, m.Kc, m.Vc, s, m.cs, + &st.host, staged ? &m.stage : nullptr); + else + kv_append(m.Kc, m.Vc, T, p0, st.page_table, s.page_size, st.kv_int8 ? nullptr : st.k_pool, + st.kv_int8 ? nullptr : st.v_pool, st.k_q, st.v_q, st.k_scale, st.v_scale, m.cs, + &st.host, staged ? &m.stage : nullptr); } split_q(m.Qf, m.q, T, m.cs); rms_rows(m.q, (const float*) wqn->data, T * 24, 256, 256, EPS, m.cs); rope(m.q, T, 24, 256, 6144, p0, strata::kernels::rope_scaling(), m.cs); - if (st.kv_q4) strata::kernels::fwht256_inplace_cuda(m.q, T * 24, m.cs); + if (st.kv_rot) strata::kernels::fwht256_inplace_cuda(m.q, T * 24, m.cs); rms_rows(m.q_idx, (const float*) wiqn->data, T * 4, 128, 128, EPS, m.cs); rope(m.q_idx, T, 4, 128, 512, p0, strata::kernels::rope_scaling(), m.cs); // the indexer appends, token by token; then scores + selection for many queries at once: @@ -1530,7 +1535,7 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e m.steps_dev + t0 * strata::kernels::kStepCount, m.cap, s, m.attn_scratch, m.attn + t0 * ZV, nb, m.cs); } - if (st.kv_q4 || st.kv_hybrid) strata::kernels::fwht256_inplace_cuda(m.attn, T * 24, m.cs); + if (st.kv_rot || st.kv_hybrid) strata::kernels::fwht256_inplace_cuda(m.attn, T * 24, m.cs); pt.mark(kPfQsa, cs); gate_attn(m.attn, m.Qf, m.attn_h, T, m.cs); if (!native_proj(m.gemm, wo, m.attn_h, m.bo, T, v.name("attn_output.weight"), err)) return false; diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 18668d66..e3cf26a5 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -1391,7 +1391,11 @@ int main(int argc, char** argv) { return 2; } strata::core::qsa_set_kv_int8(o.kv == "int8"); - strata::core::qsa_set_kv_q4(o.kv == "q4_0"); // PR #21: 4-bit codes after a Hadamard rotation (kv_q4.hpp) + strata::core::qsa_set_kv_q4(o.kv == "q4_0"); + // STRATA_KV_ROT=1: INT8 K/V through the Hadamard rotation --kv q4_0 already uses. Opt-in: first-token KL to + // fp16 K/V improved on an NVFP4 pack (0.0066 -> 0.0051) but not on IQ2_XS (0.0022 -> 0.0054) + const char* kv_rot = std::getenv("STRATA_KV_ROT"); + strata::core::qsa_set_kv_int8_rotate(kv_rot != nullptr && kv_rot[0] == '1'); // PR #21: 4-bit codes after a Hadamard rotation (kv_q4.hpp) strata::core::qsa_set_kv_hybrid(o.kv == "k8v4"); // K8V4: INT8 K + rotated Q4_0 V, 816 B/cell if (o.kv_resident < 0) { std::fprintf(stderr, "strata generate: --kv-resident must be >= 0\n"); From c81244d4e9ac4195286a3a510ed44f5ecd1abc3b Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Thu, 1 Oct 2026 08:45:09 +0200 Subject: [PATCH 37/48] #293 follow-up: the drafter stores rotated INT8 K/V as INT8; the rotation is part of the snapshot format - mtp.cpp record_forward: the `if (st_.kv_rot)` branch rotated K and V and then always appended with kv_append_q4_step - for INT8 + STRATA_KV_ROT=1 into Q4_0 pools the state does not have. The rotation and the append are separate now: rotate when kv_rot, then append in the state's own format (Q4_0, INT8, FP16). - conversation_snapshot.cpp: rotated INT8 K/V is its own snapshot format (+16), so a conversation snapshot or prompt checkpoint taken with the rotation is refused by a state without it and the reverse ("incompatible K/V geometry"); without the rotation the format is unchanged. conversation_snapshot_test checks both directions. - generate: says when STRATA_KV_ROT=1 applies; the q4_0 line's comment back. --- src/core/conversation_snapshot.cpp | 8 ++++++-- src/core/conversation_snapshot_test.cpp | 11 +++++++++++ src/core/mtp.cpp | 7 +++++-- src/program/generate.cpp | 6 ++++-- 4 files changed, 26 insertions(+), 6 deletions(-) diff --git a/src/core/conversation_snapshot.cpp b/src/core/conversation_snapshot.cpp index f7bc0988..759daa65 100644 --- a/src/core/conversation_snapshot.cpp +++ b/src/core/conversation_snapshot.cpp @@ -43,8 +43,12 @@ bool layout(const QsaState& st, const ModelGeometry& g, int64_t upto, bool index // Include the moving spare row, not only completed blocks. The checkpoint // restore reconstructs that row when rewinding to an earlier prefix. const int64_t pooled = index && upto > 0 ? upto / s.idx_block + 1 : 0; - // Format 3 identifies snapshot K8V4 only; never pass it to the block movers. - l = {st.kv_hybrid ? 3 : qsa_kv_format(st), cells, pooled, s.page_size, 0, 0, 0, 0, 0}; + // Format 3 identifies snapshot K8V4 only; never pass it to the block movers. Rotated INT8 K/V (#293, + // STRATA_KV_ROT=1) is another format too (+16): its bytes mean nothing to a state that does not rotate, so a + // snapshot or prompt checkpoint taken with the rotation never restores into one without it, nor the reverse. + // (Q4_0 is always rotated: nothing to tell apart; without the rotation the format is the one it always was.) + const int rotated = st.kv_rot && !st.kv_q4 && !st.kv_hybrid ? 16 : 0; + l = {(st.kv_hybrid ? 3 : qsa_kv_format(st)) + rotated, cells, pooled, s.page_size, 0, 0, 0, 0, 0}; using conversation_detail::product; if (!product(l.data, {(uint64_t) cells, (uint64_t) g.n_head_kv, per}) || !product(l.scales, {(uint64_t) cells, (uint64_t) g.n_head_kv, diff --git a/src/core/conversation_snapshot_test.cpp b/src/core/conversation_snapshot_test.cpp index bf732f3f..da95113c 100644 --- a/src/core/conversation_snapshot_test.cpp +++ b/src/core/conversation_snapshot_test.cpp @@ -259,6 +259,17 @@ int main() { } auto bad=a; bad.head_dim++; check(!conversation_kv_restore(bad,f.state,f.g,upto,index,err),"reject incompatible geometry"); + if (fmt==kKvInt8) { + // #293: INT8 K/V saved through the Hadamard rotation (STRATA_KV_ROT=1) never restores into a state + // without it, nor the reverse + f.state.kv_rot=true; + ConversationKv rotated; + check(conversation_kv_save(rotated,f.state,f.g,upto,index,err),"save rotated INT8"); + check(!conversation_kv_restore(a,f.state,f.g,upto,index,err),"unrotated image into a rotated state rejected"); + f.state.kv_rot=false; + check(!conversation_kv_restore(rotated,f.state,f.g,upto,index,err),"rotated image into an unrotated state rejected"); + check(conversation_kv_restore(a,f.state,f.g,upto,index,err),"unrotated image still restores"); + } if (!a.k.empty()) { bad=a; bad.k.pop_back(); check(!conversation_kv_restore(bad,f.state,f.g,upto,index,err),"reject malformed payload"); diff --git a/src/core/mtp.cpp b/src/core/mtp.cpp index 90be8162..17e36556 100644 --- a/src/core/mtp.cpp +++ b/src/core/mtp.cpp @@ -471,12 +471,15 @@ bool MtpDrafter::record_forward(int T, int step_row0, cudaStream_t cs, std::stri native_mmvq(GGML_Q8_0, q8("self_attn.v_proj.weight"), xq_, vcur_, (int) N, (int) (NKV * HD), T, cs); for (int t = 0; t < T; ++t) { norm_rope(kcur_ + t * NKV * HD, f32("self_attn.k_norm.weight"), (int) NKV, (int) HD, pos + t * NH); - if (st_.kv_rot) { // rotated K and V (kv_q4.hpp) + if (st_.kv_rot) { // rotated K and V (kv_q4.hpp): Q4_0, and INT8 with STRATA_KV_ROT=1 fwht256_inplace_cuda(kcur_ + t * NKV * HD, NKV, cs); fwht256_inplace_cuda(vcur_ + t * NKV * HD, NKV, cs); + } + // stored in the state's own format (#293 appended rotated INT8 K/V as Q4_0, into pools INT8 never has) + if (st_.kv_q4) kv_append_q4_step(st_.k_q4, st_.v_q4, st_.page_table, step + t * 4, kcur_ + t * NKV * HD, vcur_ + t * NKV * HD, s, cs, &st_.host); - } else if (st_.kv_int8) + else if (st_.kv_int8) kv_append_q8_step(st_.k_q, st_.v_q, st_.k_scale, st_.v_scale, st_.page_table, step + t * 4, kcur_ + t * NKV * HD, vcur_ + t * NKV * HD, s, cs, &st_.host); else diff --git a/src/program/generate.cpp b/src/program/generate.cpp index e3cf26a5..f91a9177 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -1391,11 +1391,13 @@ int main(int argc, char** argv) { return 2; } strata::core::qsa_set_kv_int8(o.kv == "int8"); - strata::core::qsa_set_kv_q4(o.kv == "q4_0"); + strata::core::qsa_set_kv_q4(o.kv == "q4_0"); // PR #21: 4-bit codes after a Hadamard rotation (kv_q4.hpp) // STRATA_KV_ROT=1: INT8 K/V through the Hadamard rotation --kv q4_0 already uses. Opt-in: first-token KL to // fp16 K/V improved on an NVFP4 pack (0.0066 -> 0.0051) but not on IQ2_XS (0.0022 -> 0.0054) const char* kv_rot = std::getenv("STRATA_KV_ROT"); - strata::core::qsa_set_kv_int8_rotate(kv_rot != nullptr && kv_rot[0] == '1'); // PR #21: 4-bit codes after a Hadamard rotation (kv_q4.hpp) + strata::core::qsa_set_kv_int8_rotate(kv_rot != nullptr && kv_rot[0] == '1'); + if (kv_rot != nullptr && kv_rot[0] == '1' && o.kv == "int8") + std::fprintf(stderr, "strata generate: STRATA_KV_ROT=1: INT8 K/V through the Hadamard rotation (opt-in)\n"); strata::core::qsa_set_kv_hybrid(o.kv == "k8v4"); // K8V4: INT8 K + rotated Q4_0 V, 816 B/cell if (o.kv_resident < 0) { std::fprintf(stderr, "strata generate: --kv-resident must be >= 0\n"); From 32727a7a9461aa00e83a366b9c0dd8b290fcad71 Mon Sep 17 00:00:00 2001 From: sergiywith Date: Wed, 30 Sep 2026 22:25:39 +0300 Subject: [PATCH 38/48] Token embedding in BF16 from the checkpoint (--embd-gguf) - tools/embd_bf16_pack.py copies embed_tokens (BF16, as the checkpoint ships it) into a one-tensor GGUF; only the safetensors shard that holds it is needed (3 GB for Qwen/Qwen3.8-Flash-Next). - --embd-gguf PATH: NativeEmbed reads token_embd from that file; iq_embed_rows and iq_dequant_f32 decode BF16 (embed_type_supported). Mapped host memory as before (1.2 GiB instead of 0.3 for IQ4_XS), no VRAM. First-token KL of the GGUF's IQ4_XS embedding against the BF16 one: 0.0015 (1K), 0.0089 (2K; the top token changes), 0.0010 (4K), 0.037 (32K); mean 0.012, ~100x the run-to-run noise. On the NVFP4 fork, whose GGUF embedding is Q8_0, the same comparison gave 0.0025. Decode and prompt speed are unchanged (fork); the start takes ~0.2 s more. Rebased onto 0.1.31 (Niko1221): NativeEmbed::load takes the shard list (one file for --embd-gguf) and checks the model's architecture since 0.1.31 - the one-tensor file says "strata-embd", so only its tensor is checked there; the Q4_K/Q5_K/Q5_1/Q8_0 decoders 0.1.31 added stay beside the BF16 one. --- include/strata/kernels/iq_kernels.hpp | 2 + src/core/native_head.cpp | 6 +- src/kernels/cuda/iq_kernels.cu | 17 +++++- src/program/generate.cpp | 12 +++- tools/embd_bf16_pack.py | 87 +++++++++++++++++++++++++++ 5 files changed, 116 insertions(+), 8 deletions(-) create mode 100644 tools/embd_bf16_pack.py diff --git a/include/strata/kernels/iq_kernels.hpp b/include/strata/kernels/iq_kernels.hpp index 1beb9a14..c2bb2b5c 100644 --- a/include/strata/kernels/iq_kernels.hpp +++ b/include/strata/kernels/iq_kernels.hpp @@ -14,6 +14,8 @@ namespace strata::kernels { /// ggml type ids handled here. bool iq_supported(int ggml_type) noexcept; +/// The token-embedding types iq_embed_rows and iq_dequant_f32 read: the i-quants above and BF16 (30). +bool embed_type_supported(int ggml_type) noexcept; /// Bytes of one row of `n` values of `ggml_type` (n a multiple of the type's block). size_t iq_row_bytes(int ggml_type, int64_t n) noexcept; diff --git a/src/core/native_head.cpp b/src/core/native_head.cpp index 5eed99d1..e47dfe14 100644 --- a/src/core/native_head.cpp +++ b/src/core/native_head.cpp @@ -108,13 +108,15 @@ NativeEmbed::~NativeEmbed() { bool NativeEmbed::load(const std::vector& shards, int64_t n_embd, int64_t n_vocab, std::string& err) { try { const strata::GgufModel model(shards); - err = strata::check_architecture(model.meta()); + // --embd-gguf's one-tensor file (tools/embd_bf16_pack.py) says "strata-embd": only its tensor is checked + const strata::MetaValue* arch = model.meta().get("general.architecture"); + err = arch != nullptr && arch->s == "strata-embd" ? std::string() : strata::check_architecture(model.meta()); if (!err.empty()) { err = "native embedding: " + err; return false; } size_t at = 0; const strata::TensorInfo* t = model.find("token_embd.weight", &at); const strata::GgufFile& gguf = model.shard(at); if (!t || t->shape.size() != 2 || t->shape[0] != (uint64_t) n_embd || t->shape[1] != (uint64_t) n_vocab || - !strata::kernels::iq_supported((int) t->type) || n_embd % 256) { + !strata::kernels::embed_type_supported((int) t->type) || n_embd % 256) { err = "native embedding: token_embd.weight is absent, of another shape, or of a type without a GPU " "dequantizer"; return false; diff --git a/src/kernels/cuda/iq_kernels.cu b/src/kernels/cuda/iq_kernels.cu index 61ace84a..3081c82c 100644 --- a/src/kernels/cuda/iq_kernels.cu +++ b/src/kernels/cuda/iq_kernels.cu @@ -1218,7 +1218,15 @@ __device__ void dq_q8_0(const void* vx, int64_t ibs, dst_t* yy, int tid) { for (int j = 0; j < 8; ++j) y[j] = cvt((float) x[ib].qs[8 * il + j] * d); } -// Every type below must also be in is_iq(): the host entry points refuse the others, so the default is unreachable. +// BF16 (the token embedding as the checkpoint ships it, tools/embd_bf16_pack.py): 8 values per thread. +template +__device__ void dq_bf16(const void* vx, int64_t ibs, dst_t* yy, int tid) { + const uint16_t* x = (const uint16_t*) vx + ibs * 256 + tid * 8; + for (int j = 0; j < 8; ++j) yy[tid * 8 + j] = cvt(__uint_as_float((uint32_t) x[j] << 16)); +} + +// Every type below must also be in is_iq() (BF16: embed_type_supported): the host entry points refuse the others, +// so the default is unreachable. template __device__ __forceinline__ void dq_dispatch(int ty, const void* vx, int64_t ibs, dst_t* y, int tid) { switch (ty) { @@ -1236,6 +1244,7 @@ __device__ __forceinline__ void dq_dispatch(int ty, const void* vx, int64_t ibs, case 13: dq_q5_k(vx, ibs, y, tid); break; case 7: dq_q5_1(vx, ibs, y, tid); break; case 8: dq_q8_0(vx, ibs, y, tid); break; + case 30: dq_bf16(vx, ibs, y, tid); break; default: break; } } @@ -1321,6 +1330,7 @@ void iq_set_old_kernels(bool old) { g_old_kernels = old; } bool iq_old_kernels() { return g_old_kernels; } bool iq_supported(int t) noexcept { return is_iq(t); } +bool embed_type_supported(int t) noexcept { return is_iq(t) || t == 30; } size_t iq_row_bytes(int t, int64_t n) noexcept { switch (t) { @@ -1338,6 +1348,7 @@ size_t iq_row_bytes(int t, int64_t n) noexcept { case 13: return (size_t) (n / 256) * sizeof(block_q5_K); case 7: return (size_t) (n / 32) * sizeof(block_q5_1); case 8: return (size_t) (n / 32) * sizeof(block_q8_0); + case 30: return (size_t) n * 2; // BF16: the token embedding only (iq_embed_rows, iq_dequant_f32) default: return 0; } } @@ -1382,14 +1393,14 @@ __global__ void embed_rows_kernel(int ty, const uint8_t* __restrict__ table, siz void iq_embed_rows(int t, const void* table, size_t row_bytes, const int32_t* tokens, int64_t n_tok, int64_t n_embd, float* out, void* stream) { if (n_tok <= 0) return; - if (n_embd % 256 != 0 || !is_iq(t)) { std::fprintf(stderr, "iq_embed_rows: bad arguments\n"); std::exit(1); } + if (n_embd % 256 != 0 || !embed_type_supported(t)) { std::fprintf(stderr, "iq_embed_rows: bad arguments\n"); std::exit(1); } embed_rows_kernel<<>>( t, (const uint8_t*) table, row_bytes, tokens, n_embd, out); check("iq_embed_rows"); } void iq_dequant_f32(int t, const void* src, int64_t n, float* dst, void* stream) { - if (n % 256 != 0 || !is_iq(t)) { std::fprintf(stderr, "iq_dequant_f32: bad arguments\n"); std::exit(1); } + if (n % 256 != 0 || !embed_type_supported(t)) { std::fprintf(stderr, "iq_dequant_f32: bad arguments\n"); std::exit(1); } dequant_flat_kernel<<<(unsigned) (n / 256), 32, 0, (cudaStream_t) stream>>>(t, src, dst); check("iq_dequant_f32"); } diff --git a/src/program/generate.cpp b/src/program/generate.cpp index f91a9177..45412f90 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -216,6 +216,8 @@ struct Options { /// combination recorded in bench/results/2026-09-23-attention-ple plus the native indexer, and never the /// <=256-token attention adapter. It becomes the default once P0 shows it is not slower. std::string native_preset; + /// The token embedding from this GGUF instead of --native's (tools/embd_bf16_pack.py: BF16 as shipped) + std::string embd_gguf; /// Plan v0.3 P2: how the n-gram table is read. Direct (default) = unbuffered SSD reads, table never in RAM. std::string ple_io = "direct"; int64_t ple_row_cache = 1 << 20; ///< bounded row cache (rows of 90 B); 0 disables @@ -456,6 +458,8 @@ void usage() { " indexer, RoPE, PLE postops, and the CPU q8_0 contract unless the\n" " expert cache is on. Individual --native-* flags stay for A/B.\n" " --native-head-gguf PATH native Q5_K head from model shard 1; requires --stream-token\n" + " --embd-gguf PATH the token embedding from this GGUF instead of --native's (tools/embd_bf16_pack.py:\n" + " BF16 as the checkpoint ships it; mapped host memory, no VRAM)\n" " --native-dense-gguf PATH native GDN/QSA/shared projections; repeat for each source model shard\n" " --expert-cache-cpu-order experimental GPU expert reduction matching CPU order\n" " --max-new N tokens to generate (default 16)\n" @@ -1068,6 +1072,7 @@ int main(int argc, char** argv) { else if (a == "--cpu-oracle-q8-0") o.cpu_oracle_q8_0 = true; else if (a == "--native") o.native_preset = next("--native"); else if (a == "--native-head-gguf") o.native_head_gguf = next("--native-head-gguf"); + else if (a == "--embd-gguf") o.embd_gguf = next("--embd-gguf"); else if (a == "--native-dense-gguf") o.native_dense_gguf.push_back(next("--native-dense-gguf")); else if (a == "--no-capture") o.no_capture = true; else if (a == "--no-pool") o.no_pool = true; @@ -1766,15 +1771,16 @@ int main(int argc, char** argv) { return 2; } const strata::core::ModelGeometry g0; - if (!native_embed.load(o.native_shards, g0.n_embd, 248320, err)) { + if (!native_embed.load(o.embd_gguf.empty() ? o.native_shards : std::vector{o.embd_gguf}, g0.n_embd, + 248320, err)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } strata::core::set_native_embed(&native_embed); std::fprintf(stderr, "strata generate: native pack: %s experts (largest blob %.2f MB), token embedding " - "type %d in mapped host memory (%.0f MiB)\n", + "%s in mapped host memory (%.0f MiB)\n", o.pack.c_str(), (double) strata::kernels::cpu::expert_layout().max_blob / 1e6, - native_embed.type(), (double) native_embed.bytes() / 1048576.0); + strata::ggml_type_name((uint32_t) native_embed.type()), (double) native_embed.bytes() / 1048576.0); } // Plan v0.3 P1: tensors served in native form are not also loaded in canonical form (~2.7 GB of VRAM back // to the expert cache with --native). `--keep-canonical` loads both, as before. diff --git a/tools/embd_bf16_pack.py b/tools/embd_bf16_pack.py new file mode 100644 index 00000000..1ed2d642 --- /dev/null +++ b/tools/embd_bf16_pack.py @@ -0,0 +1,87 @@ +"""tools/embd_bf16_pack.py - the token embedding exactly as the checkpoint ships it (BF16), as a GGUF the engine reads. + + python tools/embd_bf16_pack.py --model --out + +nvfp4_convert.py stores token_embd as Q8_0 (0.56% off per value). The engine keeps the table in mapped host memory +and reads one row per token, so BF16 costs 0.6 GB of RAM more and no VRAM; `--embd-gguf` takes it from this file. + +The output is a one-tensor GGUF: `token_embd.weight`, ne = [n_embd, n_vocab], type BF16, the bytes copied straight +out of the safetensors file - nothing decoded or rounded. +""" +import argparse +import json +import pathlib +import struct +import sys + +GGUF_TYPE_STRING = 8 +GGML_TYPE_BF16 = 30 +ALIGN = 32 +CHUNK = 64 << 20 + + +def safetensors_header(path): + with open(path, "rb") as f: + n = struct.unpack(" Date: Thu, 1 Oct 2026 08:46:48 +0200 Subject: [PATCH 39/48] #290 follow-up: a BF16-row parity test (native_expert_parity --bf16-embd) iq_embed_rows (97 rows gathered out of order, with repeats) and iq_dequant_f32 on a random BF16 table, every value compared bit for bit with the exact widening (bits << 16); embed_type_supported(30) / iq_supported(30) / iq_row_bytes(30). ctest native_expert_parity_bf16_embd. --- CMakeLists.txt | 2 + src/kernels/native_expert_parity.cpp | 57 +++++++++++++++++++++++++++- 2 files changed, 58 insertions(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index a47c32e6..4d26b383 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -884,6 +884,8 @@ if(STRATA_NATIVE_EXPERTS) set_tests_properties(native_expert_parity_${_name} PROPERTIES TIMEOUT 120) endforeach() add_test(NAME native_expert_parity_q5_1_min COMMAND native_expert_parity --q5_1-min) + # #290: the BF16 token embedding (--embd-gguf) gathered and dequantized bit for bit + add_test(NAME native_expert_parity_bf16_embd COMMAND native_expert_parity --bf16-embd) # a pair without GPU kernels (Q6_K gate/up) is refused by native_expert_supported, not run add_test(NAME native_expert_parity_refuses_q6_K COMMAND native_expert_parity --synthetic q6_K/q8_0) set_tests_properties(native_expert_parity_refuses_q6_K PROPERTIES WILL_FAIL TRUE) diff --git a/src/kernels/native_expert_parity.cpp b/src/kernels/native_expert_parity.cpp index 2425062e..153df365 100644 --- a/src/kernels/native_expert_parity.cpp +++ b/src/kernels/native_expert_parity.cpp @@ -467,6 +467,58 @@ int check_q5_1_min(cudaStream_t s) { "(largest per-block sum shift %.3g) %s\n", e_q, e_s, shift, ok ? "ok" : "FAIL"); return ok ? 0 : 1; } +// #290: the BF16 token embedding (--embd-gguf) - iq_embed_rows and iq_dequant_f32 on a random BF16 table against +// the exact widening (bits << 16), every bit; rows gathered out of order, with repeats +int check_bf16_embd(cudaStream_t s) { + constexpr int kBf16 = 30; + const int64_t H = 2560, V = 61, NT = 97; + int failures = 0; + if (!strata::kernels::embed_type_supported(kBf16) || strata::kernels::iq_supported(kBf16) || + strata::kernels::iq_row_bytes(kBf16, H) != (size_t) H * 2) { + std::printf("bf16 embedding: type support / row bytes wrong\n"); + return 1; + } + std::mt19937 rng(290); + std::vector table((size_t) (V * H)); + for (auto& v : table) { // any bit pattern but NaN (a NaN's payload is not what the test is about) + do v = (uint16_t) (rng() & 0xffff); while ((v & 0x7f80) == 0x7f80 && (v & 0x7f)); + } + std::vector tok((size_t) NT); + for (auto& t : tok) t = (int32_t) (rng() % V); + void* dt = nullptr; + int32_t* dtok = nullptr; + float* dout = nullptr; + cudaMalloc(&dt, table.size() * 2); + cudaMalloc((void**) &dtok, tok.size() * 4); + cudaMalloc((void**) &dout, (size_t) (V * H) * 4); + cudaMemcpy(dt, table.data(), table.size() * 2, cudaMemcpyHostToDevice); + cudaMemcpy(dtok, tok.data(), tok.size() * 4, cudaMemcpyHostToDevice); + auto widen = [](uint16_t b) { const uint32_t u = (uint32_t) b << 16; float f; std::memcpy(&f, &u, 4); return f; }; + std::vector got((size_t) (V * H)); + strata::kernels::iq_embed_rows(kBf16, dt, (size_t) H * 2, dtok, NT, H, dout, s); + cudaStreamSynchronize(s); + cudaMemcpy(got.data(), dout, (size_t) (NT * H) * 4, cudaMemcpyDeviceToHost); + size_t rows_differ = 0; + for (int64_t r = 0; r < NT; ++r) + for (int64_t d = 0; d < H; ++d) { + const float want = widen(table[(size_t) (tok[(size_t) r] * H + d)]); + if (std::memcmp(&got[(size_t) (r * H + d)], &want, 4) != 0) { ++rows_differ; break; } + } + strata::kernels::iq_dequant_f32(kBf16, dt, V * H, dout, s); + cudaStreamSynchronize(s); + cudaMemcpy(got.data(), dout, got.size() * 4, cudaMemcpyDeviceToHost); + size_t values_differ = 0; + for (size_t i = 0; i < table.size(); ++i) { + const float want = widen(table[i]); + values_differ += std::memcmp(&got[i], &want, 4) != 0; + } + cudaFree(dt); cudaFree(dtok); cudaFree(dout); + std::printf("bf16 embedding: %lld gathered rows, %zu differ; dequant of %lld values, %zu differ in any bit\n", + (long long) NT, rows_differ, (long long) (V * H), values_differ); + if (rows_differ || values_differ) ++failures; + return failures; +} + } // namespace int main(int argc, char** argv) { @@ -474,7 +526,8 @@ int main(int argc, char** argv) { if (argc < 2) { std::fprintf(stderr, "usage: native_expert_parity [layer ...]\n" " native_expert_parity --synthetic GU/DOWN ... (ggml type names, e.g. q4_K/q5_1)\n" - " native_expert_parity --q5_1-min\n"); + " native_expert_parity --q5_1-min\n" + " native_expert_parity --bf16-embd\n"); return 2; } // #152's width check tests the opt-in rule (the multi-token kernels from one token on) @@ -491,6 +544,8 @@ int main(int argc, char** argv) { const std::string mode = argv[1]; if (mode == "--q5_1-min") { failures += check_q5_1_min(s); + } else if (mode == "--bf16-embd") { + failures += check_bf16_embd(s); } else if (mode == "--synthetic") { for (int i = 2; i < argc; ++i) { const std::string arg = argv[i]; From 69743d3a5ccc9812841bdccb48e4d5e29cd12fd2 Mon Sep 17 00:00:00 2001 From: Pravesh Khatana Date: Wed, 30 Sep 2026 23:45:29 +0530 Subject: [PATCH 40/48] feat(cpu): add hybrid architecture awareness and --pool-affinity for P/E-core CPUs - Add detect_cpu_topology() for Windows (GetLogicalProcessorInformationEx) and Linux (/sys/devices/system/cpu/cpu*/cpu_capacity) - Identify hybrid P/E-core topology and SMT sibling structures - Prioritize primary P-cores for worker allocation, reserving core 0 for host thread - Default pool_workers to (p_cores - 1) on hybrid CPUs when unspecified - Add --pool-affinity auto|p-cores|all CLI option - Maintain 100% backward compatibility on non-hybrid CPUs and default configs --- include/strata/kernels/cpu/pool.hpp | 35 ++++- src/kernels/cpu/pool.cpp | 235 ++++++++++++++++++++++++---- src/program/generate.cpp | 26 ++- 3 files changed, 261 insertions(+), 35 deletions(-) diff --git a/include/strata/kernels/cpu/pool.hpp b/include/strata/kernels/cpu/pool.hpp index dce9c2bf..f3cd54e2 100644 --- a/include/strata/kernels/cpu/pool.hpp +++ b/include/strata/kernels/cpu/pool.hpp @@ -63,13 +63,35 @@ struct ExpertJobMulti { const void* nact[MAXT] = {}; }; +/// One logical processor per PHYSICAL core, so a worker is never scheduled onto an SMT sibling of another +/// worker. On the 6-core/12-thread machine this project measures on, `hardware_concurrency()/2` workers on +/// logical processors 0..5 would put every worker on a sibling pair and halve the useful bandwidth - which is +/// exactly the kind of error that shows up as "the CPU path is slower than the model says" with no clue why. +/// How worker threads are allocated across physical/logical CPU cores. +enum class PoolAffinity { + Auto, ///< Hybrid: prioritize physical P-cores, then SMT, then E-cores (defaults to P-core count) + PCores, ///< Restrict workers strictly to Performance cores and their SMT siblings + All, ///< Legacy behavior: linear physical core order without hybrid distinction +}; + +struct CpuTopology { + bool is_hybrid = false; + int p_cores = 0; ///< Physical performance cores + int p_threads = 0; ///< Total logical threads on performance cores + int e_cores = 0; ///< Efficient cores + std::vector worker_cores; ///< Ordered logical core IDs for workers (excluding host if skip_first) + int host_core = -1; ///< Logical core reserved for host thread +}; + +CpuTopology detect_cpu_topology(bool skip_first, PoolAffinity affinity = PoolAffinity::Auto); + /// One logical processor per PHYSICAL core, so a worker is never scheduled onto an SMT sibling of another /// worker. On the 6-core/12-thread machine this project measures on, `hardware_concurrency()/2` workers on /// logical processors 0..5 would put every worker on a sibling pair and halve the useful bandwidth - which is /// exactly the kind of error that shows up as "the CPU path is slower than the model says" with no clue why. /// /// `skip_first` drops the first core, which P2.S3 reserves for the host loop. -std::vector physical_cores(bool skip_first); +std::vector physical_cores(bool skip_first, PoolAffinity affinity = PoolAffinity::Auto); /// **THE RESERVATION IS A FICTION UNLESS THE HOST IS ACTUALLY PUT THERE.** /// @@ -101,7 +123,8 @@ public: /// With `host_works`, `run()` claims jobs itself instead of spinning on `done_`, and the pool is six /// threads on six cores. `false` is the A/B arm and exists so the change is measurable rather than /// asserted - the counter it moves is `pool phases ... drain`, which is host-side and needs no profiler. - explicit ExpertPool(int n_workers = 0, bool pin = true, bool host_works = true); + explicit ExpertPool(int n_workers = 0, bool pin = true, bool host_works = true, + PoolAffinity affinity = PoolAffinity::Auto); /// The watchdog's view of the pool (issue #31): the batch, the counters, every thread's state. void diag(std::FILE* f) const; ~ExpertPool(); @@ -113,6 +136,12 @@ public: /// is on" is only true if the engine says which adaptation it took. bool host_works() const { return host_works_; } + bool is_hybrid() const { return topo_.is_hybrid; } + int p_cores() const { return topo_.p_cores; } + int p_threads() const { return topo_.p_threads; } + int e_cores() const { return topo_.e_cores; } + PoolAffinity affinity() const { return affinity_; } + /// Publish `n` jobs, then block until every one has been claimed AND every worker has parked. /// `jobs` must outlive the call (it does, and the workers never touch it afterwards). void run(ExpertJob* jobs, int n); @@ -239,6 +268,8 @@ private: }; const NativeFmt* nfmt_ = nullptr; std::vector split_multi_; + PoolAffinity affinity_ = PoolAffinity::Auto; + CpuTopology topo_; }; } // namespace strata::kernels::cpu diff --git a/src/kernels/cpu/pool.cpp b/src/kernels/cpu/pool.cpp index e2e5023e..45e43470 100644 --- a/src/kernels/cpu/pool.cpp +++ b/src/kernels/cpu/pool.cpp @@ -27,8 +27,8 @@ constexpr uint64_t pack_head(uint32_t epoch, uint32_t n, uint32_t i) { } } // namespace -std::vector physical_cores(bool skip_first) { - std::vector cores; +CpuTopology detect_cpu_topology(bool skip_first, PoolAffinity affinity) { + CpuTopology topo; #if defined(_WIN32) // Ask the OS rather than assuming a layout. `hardware_concurrency()` returns LOGICAL processors, and on // every SMT machine half of them are siblings - pinning one worker to each of the first N would put two @@ -36,30 +36,111 @@ std::vector physical_cores(bool skip_first) { DWORD len = 0; GetLogicalProcessorInformationEx(RelationProcessorCore, nullptr, &len); if (len == 0) { - for (unsigned i = 0; i < std::thread::hardware_concurrency(); ++i) cores.push_back((int) i); - } else { - std::vector buf(len); - if (GetLogicalProcessorInformationEx(RelationProcessorCore, - (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX) buf.data(), &len)) { - const char* p = buf.data(); - const char* end = p + len; - while (p < end) { - const auto* e = (const SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX*) p; - if (e->Relationship == RelationProcessorCore) { - const GROUP_AFFINITY& g = e->Processor.GroupMask[0]; - for (int bit = 0; bit < 64; ++bit) - if (g.Mask & (1ull << bit)) { cores.push_back((int) (g.Group * 64 + bit)); break; } + for (unsigned i = 0; i < std::thread::hardware_concurrency(); ++i) topo.worker_cores.push_back((int) i); + if (skip_first && !topo.worker_cores.empty()) { + topo.host_core = topo.worker_cores.front(); + topo.worker_cores.erase(topo.worker_cores.begin()); + } + return topo; + } + std::vector buf(len); + if (GetLogicalProcessorInformationEx(RelationProcessorCore, + (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX) buf.data(), &len)) { + const char* p = buf.data(); + const char* end = p + len; + struct CoreDesc { + uint8_t efficiency = 0; + bool has_smt = false; + std::vector lps; + }; + std::vector descs; + while (p < end) { + const auto* e = (const SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX*) p; + if (e->Relationship == RelationProcessorCore) { + CoreDesc cd; + cd.efficiency = e->Processor.EfficiencyClass; + cd.has_smt = (e->Processor.Flags & LTP_PC_SMT) != 0; + const GROUP_AFFINITY& g = e->Processor.GroupMask[0]; + for (int bit = 0; bit < 64; ++bit) { + if (g.Mask & (1ull << bit)) { + cd.lps.push_back((int) (g.Group * 64 + bit)); + } } - p += e->Size; + if (!cd.lps.empty()) { + descs.push_back(std::move(cd)); + } + } + p += e->Size; + } + + uint8_t min_eff = 255, max_eff = 0; + for (const auto& c : descs) { + min_eff = (std::min)(min_eff, c.efficiency); + max_eff = (std::max)(max_eff, c.efficiency); + } + + topo.is_hybrid = (max_eff > min_eff); + if (topo.is_hybrid) { + for (const auto& c : descs) { + if (c.efficiency == max_eff) { + topo.p_cores++; + topo.p_threads += (int) c.lps.size(); + } else { + topo.e_cores++; + } + } + } else { + topo.p_cores = (int) descs.size(); + for (const auto& c : descs) topo.p_threads += (int) c.lps.size(); + } + + if (affinity == PoolAffinity::All || !topo.is_hybrid) { + for (const auto& c : descs) topo.worker_cores.push_back(c.lps[0]); + if (skip_first && !topo.worker_cores.empty()) { + topo.host_core = topo.worker_cores.front(); + topo.worker_cores.erase(topo.worker_cores.begin()); + } + return topo; + } + + // Hybrid CPU with Auto or PCores affinity: + // Prioritize Performance cores: + // 1. Primary logical processor of each P-core (avoids SMT resource contention) + // 2. SMT sibling logical processors of P-cores + // 3. E-cores (only as overflow in Auto mode) + std::vector p_primaries; + std::vector p_siblings; + std::vector e_cores; + + for (const auto& c : descs) { + if (c.efficiency == max_eff) { + p_primaries.push_back(c.lps[0]); + for (size_t s = 1; s < c.lps.size(); ++s) { + p_siblings.push_back(c.lps[s]); + } + } else { + for (int lp : c.lps) e_cores.push_back(lp); } } + + if (skip_first && !p_primaries.empty()) { + topo.host_core = p_primaries.front(); + p_primaries.erase(p_primaries.begin()); + } + + for (int cpu : p_primaries) topo.worker_cores.push_back(cpu); + for (int cpu : p_siblings) topo.worker_cores.push_back(cpu); + if (affinity != PoolAffinity::PCores) { + for (int cpu : e_cores) topo.worker_cores.push_back(cpu); + } + return topo; } #else // The logical CPUs this process may run on, ONE PER PHYSICAL CORE (issue #40): SMT siblings share a core's // load/store bandwidth, so a worker on each would put two workers on one core, as the Windows branch above // explains. sysfs names each CPU's (package, core); the first allowed CPU of each pair is kept, so a taskset // that leaves out the first sibling still gets its core. Without sysfs every allowed CPU counts, as before. - auto topo = [](int cpu, const char* what) -> long { + auto topo_read = [](int cpu, const char* what) -> long { char path[96]; std::snprintf(path, sizeof path, "/sys/devices/system/cpu/cpu%d/topology/%s", cpu, what); long v = -1; @@ -69,6 +150,17 @@ std::vector physical_cores(bool skip_first) { } return v; }; + auto cap_read = [](int cpu) -> long { + char path[96]; + std::snprintf(path, sizeof path, "/sys/devices/system/cpu/cpu%d/cpu_capacity", cpu); + long v = -1; + if (std::FILE* f = std::fopen(path, "r")) { + if (std::fscanf(f, "%ld", &v) != 1) v = -1; + std::fclose(f); + } + return v; + }; + std::vector allowed; cpu_set_t set; CPU_ZERO(&set); @@ -78,19 +170,96 @@ std::vector physical_cores(bool skip_first) { } else { for (unsigned i = 0; i < std::thread::hardware_concurrency(); ++i) allowed.push_back((int) i); } - std::vector> seen; + + struct CoreLinux { + int cpu = -1; + long pkg = -1; + long core = -1; + long cap = -1; + bool is_sibling = false; + }; + std::vector all_cpus; + std::vector> seen_phys; + long max_cap = 0, min_cap = 1000000; + for (int cpu : allowed) { - const long pkg = topo(cpu, "physical_package_id"), core = topo(cpu, "core_id"); - if (pkg >= 0 && core >= 0) { - const std::pair key{pkg, core}; - if (std::find(seen.begin(), seen.end(), key) != seen.end()) continue; // an SMT sibling - seen.push_back(key); + CoreLinux cl; + cl.cpu = cpu; + cl.pkg = topo_read(cpu, "physical_package_id"); + cl.core = topo_read(cpu, "core_id"); + cl.cap = cap_read(cpu); + if (cl.cap > 0) { + max_cap = (std::max)(max_cap, cl.cap); + min_cap = (std::min)(min_cap, cl.cap); } - cores.push_back(cpu); + if (cl.pkg >= 0 && cl.core >= 0) { + const std::pair key{cl.pkg, cl.core}; + if (std::find(seen_phys.begin(), seen_phys.end(), key) != seen_phys.end()) { + cl.is_sibling = true; + } else { + seen_phys.push_back(key); + } + } + all_cpus.push_back(cl); } + + topo.is_hybrid = (max_cap > 0 && max_cap > min_cap); + if (topo.is_hybrid) { + for (const auto& cl : all_cpus) { + if (cl.cap == max_cap) { + if (!cl.is_sibling) topo.p_cores++; + topo.p_threads++; + } else { + if (!cl.is_sibling) topo.e_cores++; + } + } + } else { + topo.p_cores = (int) seen_phys.size(); + topo.p_threads = (int) all_cpus.size(); + } + + if (affinity == PoolAffinity::All || !topo.is_hybrid) { + for (const auto& cl : all_cpus) { + if (!cl.is_sibling) topo.worker_cores.push_back(cl.cpu); + } + if (skip_first && !topo.worker_cores.empty()) { + topo.host_core = topo.worker_cores.front(); + topo.worker_cores.erase(topo.worker_cores.begin()); + } + return topo; + } + + // Hybrid CPU on Linux: + std::vector p_primaries; + std::vector p_siblings; + std::vector e_cores; + + for (const auto& cl : all_cpus) { + if (cl.cap == max_cap) { + if (!cl.is_sibling) p_primaries.push_back(cl.cpu); + else p_siblings.push_back(cl.cpu); + } else { + e_cores.push_back(cl.cpu); + } + } + + if (skip_first && !p_primaries.empty()) { + topo.host_core = p_primaries.front(); + p_primaries.erase(p_primaries.begin()); + } + + for (int cpu : p_primaries) topo.worker_cores.push_back(cpu); + for (int cpu : p_siblings) topo.worker_cores.push_back(cpu); + if (affinity != PoolAffinity::PCores) { + for (int cpu : e_cores) topo.worker_cores.push_back(cpu); + } + return topo; #endif - if (skip_first && !cores.empty()) cores.erase(cores.begin()); - return cores; + return topo; +} + +std::vector physical_cores(bool skip_first, PoolAffinity affinity) { + return detect_cpu_topology(skip_first, affinity).worker_cores; } namespace { @@ -173,11 +342,17 @@ void ExpertPool::diag(std::FILE* f) const { std::fprintf(f, " for %lld ms\n", (long long) (now_ms() - hstate_ms_.load())); } -ExpertPool::ExpertPool(int n_workers, bool pin, bool host_works) : host_works_(host_works) { +ExpertPool::ExpertPool(int n_workers, bool pin, bool host_works, PoolAffinity affinity) + : host_works_(host_works), affinity_(affinity), topo_(detect_cpu_topology(true, affinity)) { if (const char* e = std::getenv("STRATA_POOL_SPIN_US")) // a test knob; see kSpinBeforeSleep spin_before_sleep_ = std::chrono::microseconds((std::max)(0, std::atoi(e))); - const std::vector cores = physical_cores(true); - n_ = n_workers > 0 ? n_workers : (int) cores.size(); + if (n_workers > 0) { + n_ = n_workers; + } else if (topo_.is_hybrid && affinity_ != PoolAffinity::All) { + n_ = (std::max)(1, topo_.p_cores - 1); + } else { + n_ = (int) topo_.worker_cores.size(); + } if (n_ < 1) n_ = 1; scratch_.resize((size_t) n_); wstate_.reset(new std::atomic[(size_t) n_]); @@ -189,7 +364,7 @@ ExpertPool::ExpertPool(int n_workers, bool pin, bool host_works) : host_works_(h split_multi_.resize((size_t) kMaxSplitMulti); threads_.reserve((size_t) n_); for (int i = 0; i < n_; ++i) { - const int core = pin ? (i < (int) cores.size() ? cores[(size_t) i] : -1) : -1; + const int core = pin ? (i < (int) topo_.worker_cores.size() ? topo_.worker_cores[(size_t) i] : -1) : -1; threads_.emplace_back([this, i, core] { pin_this_thread(core); worker(i); diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 45412f90..74095203 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -256,6 +256,7 @@ struct Options { bool graph_only = false; bool gpu_only_full = false; ///< R0.3: pre + post + head, the true per-token GPU floor int pool_workers = 0; ///< R2.2: 0 = "all physical cores minus the host's"; >0 overrides + strata::kernels::cpu::PoolAffinity pool_affinity = strata::kernels::cpu::PoolAffinity::Auto; /// R2.2's first half, as an A/B arm. **ON by default**, because the measurement that justifies it is the /// pool's own drain: 33.7 GB/s against 5/6 x 44.14 = 36.8 for five workers, on a machine whose sixth core /// is reserved for a host thread that has nothing to do while the drain runs. @@ -550,8 +551,11 @@ void usage() { " pool is six threads on six cores instead of five plus an idle core;\n" " this flag restores the five-worker form for comparison on `pool phases`.\n" " --pool-workers N R2.2: CPU expert pool worker count. Default 0 = every physical core\n" - " except the one the host loop spins on. A sweep is how the pool's\n" - " deviation from `cpu_s2` is attributed.\n" + " except the one the host loop spins on (or P-core count minus 1 on\n" + " hybrid CPUs). A sweep is how the pool's deviation from `cpu_s2` is attributed.\n" + " --pool-affinity MODE Worker CPU affinity: auto (default: prioritize P-cores), p-cores\n" + " (strictly performance cores), or all (all physical cores without\n" + " hybrid distinction).\n" " --coupled-draft enable coupled draft sampling for MTP drafter under sampling (STRATA_SPEC_COUPLED)\n" " --no-coupled-draft disable coupled draft sampling (propose argmax drafts)\n" " --mmap-experts R2.1: opt OUT of the resident expert arena, back to MapViewOfFile.\n" @@ -1081,6 +1085,16 @@ int main(int argc, char** argv) { else if (a == "--graph-only") o.graph_only = true; else if (a == "--gpu-only-full") o.gpu_only_full = true; else if (a == "--pool-workers") o.pool_workers = std::atoi(next("--pool-workers")); + else if (a == "--pool-affinity") { + const std::string v = next("--pool-affinity"); + if (v == "auto") o.pool_affinity = strata::kernels::cpu::PoolAffinity::Auto; + else if (v == "p-cores" || v == "pcores") o.pool_affinity = strata::kernels::cpu::PoolAffinity::PCores; + else if (v == "all") o.pool_affinity = strata::kernels::cpu::PoolAffinity::All; + else { + std::fprintf(stderr, "strata generate: unknown --pool-affinity value '%s' (expected auto, p-cores, or all)\n", v.c_str()); + return 2; + } + } else if (a == "--no-host-worker") o.no_host_worker = true; else if (a == "--no-ple-prefetch") o.no_ple_prefetch = true; else if (a == "--coupled-draft") o.coupled_draft = true; @@ -2521,7 +2535,13 @@ int main(int argc, char** argv) { #endif srcp = &arena_src; } - strata::kernels::cpu::ExpertPool pool(o.pool_workers, /*pin=*/true, /*host_works=*/!o.no_host_worker); + strata::kernels::cpu::ExpertPool pool(o.pool_workers, /*pin=*/true, /*host_works=*/!o.no_host_worker, o.pool_affinity); + if (pool.is_hybrid()) { + const char* aff_str = pool.affinity() == strata::kernels::cpu::PoolAffinity::PCores ? "p-cores" : + pool.affinity() == strata::kernels::cpu::PoolAffinity::All ? "all" : "auto"; + std::fprintf(stderr, "strata generate: hybrid CPU detected (%d P-cores / %d threads, %d E-cores), pool workers: %d, affinity: %s\n", + pool.p_cores(), pool.p_threads(), pool.e_cores(), pool.workers(), aff_str); + } if (o.no_ple_prefetch) strata::kernels::ple_prefetch_enable(false); // ---- R4's slot storage. Allocated AFTER the weights and the session, so `cudaMemGetInfo` inside `open` // sees the memory this process actually has left rather than the card's idle figure - and refuses with both From cf3b351c195f36e2ef71d0b0f8af0fc380b0f0d7 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Thu, 1 Oct 2026 08:47:56 +0200 Subject: [PATCH 41/48] #272 follow-up: --pool-affinity all (the pool's layout so far) is the default; auto and p-cores are opt-in #272 made Auto the default, which on a hybrid CPU moves the workers (P-core primaries, then SMT siblings, then E-cores) and cuts their number to P-cores - 1: a speed change nobody has measured here, on the machines most users have. The default is All - the same cores in the same order as before on every CPU (Windows: the first logical processor of each core; Linux: one allowed CPU per (package, core)), and the same worker count - in Options, ExpertPool, physical_cores() and detect_cpu_topology(). --pool-affinity auto | p-cores opts in; the hybrid line is printed only then. Usage text says so. --- include/strata/kernels/cpu/pool.hpp | 17 +++++++---------- src/program/generate.cpp | 16 +++++++++------- 2 files changed, 16 insertions(+), 17 deletions(-) diff --git a/include/strata/kernels/cpu/pool.hpp b/include/strata/kernels/cpu/pool.hpp index f3cd54e2..76bda6de 100644 --- a/include/strata/kernels/cpu/pool.hpp +++ b/include/strata/kernels/cpu/pool.hpp @@ -63,15 +63,12 @@ struct ExpertJobMulti { const void* nact[MAXT] = {}; }; -/// One logical processor per PHYSICAL core, so a worker is never scheduled onto an SMT sibling of another -/// worker. On the 6-core/12-thread machine this project measures on, `hardware_concurrency()/2` workers on -/// logical processors 0..5 would put every worker on a sibling pair and halve the useful bandwidth - which is -/// exactly the kind of error that shows up as "the CPU path is slower than the model says" with no clue why. -/// How worker threads are allocated across physical/logical CPU cores. +/// How worker threads are allocated across physical/logical CPU cores (#272). `All` is the layout the pool has +/// always used and the default; the hybrid-aware ones are opt-in (--pool-affinity auto|p-cores). enum class PoolAffinity { Auto, ///< Hybrid: prioritize physical P-cores, then SMT, then E-cores (defaults to P-core count) PCores, ///< Restrict workers strictly to Performance cores and their SMT siblings - All, ///< Legacy behavior: linear physical core order without hybrid distinction + All, ///< The default: one worker per physical core in the OS's order, without hybrid distinction }; struct CpuTopology { @@ -83,7 +80,7 @@ struct CpuTopology { int host_core = -1; ///< Logical core reserved for host thread }; -CpuTopology detect_cpu_topology(bool skip_first, PoolAffinity affinity = PoolAffinity::Auto); +CpuTopology detect_cpu_topology(bool skip_first, PoolAffinity affinity = PoolAffinity::All); /// One logical processor per PHYSICAL core, so a worker is never scheduled onto an SMT sibling of another /// worker. On the 6-core/12-thread machine this project measures on, `hardware_concurrency()/2` workers on @@ -91,7 +88,7 @@ CpuTopology detect_cpu_topology(bool skip_first, PoolAffinity affinity = PoolAff /// exactly the kind of error that shows up as "the CPU path is slower than the model says" with no clue why. /// /// `skip_first` drops the first core, which P2.S3 reserves for the host loop. -std::vector physical_cores(bool skip_first, PoolAffinity affinity = PoolAffinity::Auto); +std::vector physical_cores(bool skip_first, PoolAffinity affinity = PoolAffinity::All); /// **THE RESERVATION IS A FICTION UNLESS THE HOST IS ACTUALLY PUT THERE.** /// @@ -124,7 +121,7 @@ public: /// threads on six cores. `false` is the A/B arm and exists so the change is measurable rather than /// asserted - the counter it moves is `pool phases ... drain`, which is host-side and needs no profiler. explicit ExpertPool(int n_workers = 0, bool pin = true, bool host_works = true, - PoolAffinity affinity = PoolAffinity::Auto); + PoolAffinity affinity = PoolAffinity::All); /// The watchdog's view of the pool (issue #31): the batch, the counters, every thread's state. void diag(std::FILE* f) const; ~ExpertPool(); @@ -268,7 +265,7 @@ private: }; const NativeFmt* nfmt_ = nullptr; std::vector split_multi_; - PoolAffinity affinity_ = PoolAffinity::Auto; + PoolAffinity affinity_ = PoolAffinity::All; CpuTopology topo_; }; diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 74095203..cdf6e04d 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -256,7 +256,8 @@ struct Options { bool graph_only = false; bool gpu_only_full = false; ///< R0.3: pre + post + head, the true per-token GPU floor int pool_workers = 0; ///< R2.2: 0 = "all physical cores minus the host's"; >0 overrides - strata::kernels::cpu::PoolAffinity pool_affinity = strata::kernels::cpu::PoolAffinity::Auto; + /// #272: the pool's core layout; `all` (the default) is the layout it always had, auto / p-cores are opt-in + strata::kernels::cpu::PoolAffinity pool_affinity = strata::kernels::cpu::PoolAffinity::All; /// R2.2's first half, as an A/B arm. **ON by default**, because the measurement that justifies it is the /// pool's own drain: 33.7 GB/s against 5/6 x 44.14 = 36.8 for five workers, on a machine whose sixth core /// is reserved for a host thread that has nothing to do while the drain runs. @@ -551,11 +552,12 @@ void usage() { " pool is six threads on six cores instead of five plus an idle core;\n" " this flag restores the five-worker form for comparison on `pool phases`.\n" " --pool-workers N R2.2: CPU expert pool worker count. Default 0 = every physical core\n" - " except the one the host loop spins on (or P-core count minus 1 on\n" - " hybrid CPUs). A sweep is how the pool's deviation from `cpu_s2` is attributed.\n" - " --pool-affinity MODE Worker CPU affinity: auto (default: prioritize P-cores), p-cores\n" - " (strictly performance cores), or all (all physical cores without\n" - " hybrid distinction).\n" + " except the one the host loop spins on (with --pool-affinity auto or\n" + " p-cores on a hybrid CPU: P-cores minus 1). A sweep is how the pool's\n" + " deviation from `cpu_s2` is attributed.\n" + " --pool-affinity MODE Worker CPU affinity: all (default: one worker per physical core, as\n" + " always), auto (hybrid CPUs: P-cores first, then their SMT siblings,\n" + " then E-cores) or p-cores (P-cores and their siblings only).\n" " --coupled-draft enable coupled draft sampling for MTP drafter under sampling (STRATA_SPEC_COUPLED)\n" " --no-coupled-draft disable coupled draft sampling (propose argmax drafts)\n" " --mmap-experts R2.1: opt OUT of the resident expert arena, back to MapViewOfFile.\n" @@ -2536,7 +2538,7 @@ int main(int argc, char** argv) { srcp = &arena_src; } strata::kernels::cpu::ExpertPool pool(o.pool_workers, /*pin=*/true, /*host_works=*/!o.no_host_worker, o.pool_affinity); - if (pool.is_hybrid()) { + if (pool.is_hybrid() && pool.affinity() != strata::kernels::cpu::PoolAffinity::All) { const char* aff_str = pool.affinity() == strata::kernels::cpu::PoolAffinity::PCores ? "p-cores" : pool.affinity() == strata::kernels::cpu::PoolAffinity::All ? "all" : "auto"; std::fprintf(stderr, "strata generate: hybrid CPU detected (%d P-cores / %d threads, %d E-cores), pool workers: %d, affinity: %s\n", From 75a39eef3a68bf0725ef8e7f15a3a3c6c9c7f487 Mon Sep 17 00:00:00 2001 From: Suoriks Date: Tue, 29 Sep 2026 14:44:47 +0300 Subject: [PATCH 42/48] feat: support OrcaRouter Q4_K_S Load three-shard Uncensored weights while preserving Q5_0 PLE rows and Q4_K/Q5 expert bytes. Add native CUDA and MMQ paths with real-weight parity checks. Rebased onto 0.1.31 (Niko1221): 0.1.31 already loads each expert role from its own shard (the per-role shard column of native_experts.txt, iq_pack.py, expert_source.cpp, native_expert_parity's multi-shard mode) and has its own Q4_K/Q5_K/Q5_1/Q8_0 GPU expert decoders, so this PR's gguf_role_file / v4 manifest, its iq_pack.py and test_iq_pack.py changes and its iq_kernels.cu decoders are dropped. Kept: Q5_1 in native_mmvq (type 7 through 0.1.31's iq_mmvq) and in the BF16 dequantizer, the Q5_0 PLE table (mapped reader), the Q4_K/Q5_0/Q5_1 MMQ instances under the STRATA_ORCA_Q4KS_MMQ option (OFF), ple_q5_parity / q5_projection_parity and the doc. --- CMakeLists.txt | 25 ++++++++++- docs/ORCA_Q4_K_S.md | 36 ++++++++++++++++ src/kernels/cuda/dequant_bf16.cu | 13 ++++++ src/kernels/cuda/native_mmvq.cu | 4 +- src/kernels/ngram.cpp | 40 +++++++++++++----- src/kernels/ple_q5_parity.cpp | 59 ++++++++++++++++++++++++++ src/kernels/q5_projection_parity.cpp | 62 ++++++++++++++++++++++++++++ src/prefill/moe_mmq.cu | 11 ++++- 8 files changed, 236 insertions(+), 14 deletions(-) create mode 100644 docs/ORCA_Q4_K_S.md create mode 100644 src/kernels/ple_q5_parity.cpp create mode 100644 src/kernels/q5_projection_parity.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 4d26b383..1b3319e3 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -35,6 +35,7 @@ endif() option(STRATA_ENABLE_CUDA "Build the CUDA targets (Phase 2+)" OFF) option(STRATA_ENABLE_HIP "Build the HIP targets for wave32 AMD GPUs (gfx1100, gfx1201)" OFF) option(STRATA_PREFILL_MMQ "Build the optional GGML MMQ prefill path for HIP" OFF) +option(STRATA_ORCA_Q4KS_MMQ "Build extra GGML MMQ instances for OrcaRouter Q4_K_S" OFF) if(STRATA_PREFILL_MMQ AND NOT STRATA_ENABLE_HIP) message(FATAL_ERROR "STRATA_PREFILL_MMQ requires STRATA_ENABLE_HIP=ON") endif() @@ -758,6 +759,9 @@ set(STRATA_GGML_DIR "" CACHE PATH "llama.cpp checkout to take ggml from (empty: if(STRATA_PREFILL_MMQ AND NOT STRATA_NATIVE_EXPERTS) message(FATAL_ERROR "STRATA_PREFILL_MMQ requires STRATA_NATIVE_EXPERTS=ON for GGML sources") endif() +if(STRATA_ORCA_Q4KS_MMQ AND NOT STRATA_NATIVE_EXPERTS) + message(FATAL_ERROR "STRATA_ORCA_Q4KS_MMQ requires STRATA_NATIVE_EXPERTS=ON for GGML sources") +endif() if(STRATA_NATIVE_EXPERTS) enable_language(C) set(BUILD_SHARED_LIBS OFF CACHE BOOL "" FORCE) @@ -806,6 +810,10 @@ if(STRATA_NATIVE_EXPERTS) endif() target_link_libraries(strata_kernels_cpu PUBLIC ggml-cpu ggml-base) target_compile_definitions(strata_kernels_cpu PUBLIC STRATA_NATIVE_EXPERTS=1) + set(_strata_mmq_types q2_0 iq2_xxs iq2_xs iq2_s iq3_xxs iq3_s iq4_nl iq4_xs q8_0) + if(STRATA_ORCA_Q4KS_MMQ) + list(APPEND _strata_mmq_types q4_k q5_0 q5_1) + endif() if(STRATA_ENABLE_CUDA) # prompt-speed plan step 2b: llama.cpp's MMQ kernels (ggml-cuda, MIT) for the prompt path's experts, compiled # from the same checkout as ggml above - only mmq.cuh's instances for the packs' types and the quantizer, with @@ -817,7 +825,7 @@ if(STRATA_NATIVE_EXPERTS) endif() set(_strata_mmq ${_strata_gg}/src/ggml-cuda) add_library(strata_mmq STATIC src/prefill/moe_mmq.cu src/prefill/ggml_cuda_host.cu ${_strata_mmq}/quantize.cu) - foreach(_t q2_0 iq2_xxs iq2_xs iq2_s iq3_xxs iq3_s iq4_nl iq4_xs q8_0) # q8_0: the drafter's matrices (E-9) + foreach(_t IN LISTS _strata_mmq_types) # q8_0: the drafter's matrices (E-9) target_sources(strata_mmq PRIVATE ${_strata_mmq}/template-instances/mmq-instance-${_t}.cu) endforeach() target_include_directories(strata_mmq PRIVATE ${_strata_gg}/include ${_strata_gg}/src ${_strata_mmq} @@ -827,6 +835,9 @@ if(STRATA_NATIVE_EXPERTS) target_compile_options(strata_mmq PRIVATE $<$:-Xcompiler=/bigobj>) endif() target_link_libraries(strata_mmq PUBLIC ggml-base ${_strata_gpu_runtime_target}) + if(STRATA_ORCA_Q4KS_MMQ) + target_compile_definitions(strata_mmq PRIVATE STRATA_ORCA_Q4KS_MMQ=1) + endif() target_link_libraries(strata_prefill PUBLIC strata_mmq) target_compile_definitions(strata_prefill PUBLIC STRATA_PREFILL_MMQ=1) elseif(STRATA_PREFILL_MMQ) @@ -845,7 +856,7 @@ if(STRATA_NATIVE_EXPERTS) src/prefill/moe_mmq.cu src/prefill/ggml_cuda_host.cu "${_strata_mmq}/quantize.cu") - foreach(_t q2_0 iq2_xxs iq2_xs iq2_s iq3_xxs iq3_s iq4_nl iq4_xs q8_0) + foreach(_t IN LISTS _strata_mmq_types) list(APPEND _strata_mmq_sources "${_strata_mmq}/template-instances/mmq-instance-${_t}.cu") endforeach() set_source_files_properties(${_strata_mmq_sources} PROPERTIES LANGUAGE HIP) @@ -854,6 +865,9 @@ if(STRATA_NATIVE_EXPERTS) PRIVATE "${_strata_gg}/include" "${_strata_gg}/src" "${_strata_mmq}" PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include) target_compile_definitions(strata_mmq PRIVATE GGML_USE_HIP=1) + if(STRATA_ORCA_Q4KS_MMQ) + target_compile_definitions(strata_mmq PRIVATE STRATA_ORCA_Q4KS_MMQ=1) + endif() target_link_libraries(strata_mmq PUBLIC ggml-base hip::host roc::hipblas) target_link_libraries(strata_prefill PUBLIC strata_mmq) target_compile_definitions(strata_prefill PUBLIC STRATA_PREFILL_MMQ=1) @@ -891,6 +905,13 @@ if(STRATA_NATIVE_EXPERTS) set_tests_properties(native_expert_parity_refuses_q6_K PROPERTIES WILL_FAIL TRUE) endif() endif() + if(STRATA_ENABLE_CUDA) + add_executable(ple_q5_parity src/kernels/ple_q5_parity.cpp) + target_link_libraries(ple_q5_parity PRIVATE strata_kernels strata_artifact ggml-base ${_strata_gpu_runtime_target}) + add_executable(q5_projection_parity src/kernels/q5_projection_parity.cpp) + target_include_directories(q5_projection_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(q5_projection_parity PRIVATE strata_kernels strata_artifact ggml-base ${_strata_gpu_runtime_target}) + endif() endif() if(STRATA_ENABLE_CUDA AND STRATA_BUILD_TESTS AND EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/bench/micro/hit_cpu_order_parity.cu") diff --git a/docs/ORCA_Q4_K_S.md b/docs/ORCA_Q4_K_S.md new file mode 100644 index 00000000..6a1800e3 --- /dev/null +++ b/docs/ORCA_Q4_K_S.md @@ -0,0 +1,36 @@ +# OrcaRouter Uncensored Q4_K_S (manual setup) + +This path uses the three original `orcarouter/Qwen3.8-Flash-Next-Uncensored-GGUF` Q4_K_S shards without rewriting their expert, embedding or PLE table bytes. It is separate from the installer model menu. Keep all three shard filenames together. + +The ordinary GGUF quantizes some small projections which Strata reads as BF16. `--compat-bf16` dequantizes and rounds those projections to BF16 in the separate pack; it does not restore their original precision. The Q5_0 PLE table remains in the source GGUF and currently uses the mapped reader (`--ple-io mmap`). The Q4_K gate/up experts and Q5_0/Q5_1 down experts remain in GGUF form, including layers whose three tensors cross shard boundaries. + +## Build and prepare + +Build Strata with CUDA, native experts and `STRATA_ORCA_Q4KS_MMQ=ON`. This opt-in compiles the Q4_K, Q5_0 and Q5_1 GGML MMQ instances for CUDA or HIP; the usual Q8_0 draft-layer instance remains in both builds. HIP also needs `STRATA_PREFILL_MMQ=ON`. Select your card's compute capability, for example `89` on an L40S. On Windows with Ninja and CUDA 12.6, use the Visual Studio developer environment and `-DCMAKE_CUDA_RUNTIME_LIBRARY=Shared` to keep the CUDA runtime linkage consistent. The default pinned ggml checkout is supported by the project build. + +```sh +cmake -S . -B build -G Ninja -DSTRATA_ENABLE_CUDA=ON -DSTRATA_NATIVE_EXPERTS=ON -DSTRATA_ORCA_Q4KS_MMQ=ON -DCMAKE_CUDA_ARCHITECTURES=89 -DCMAKE_CUDA_RUNTIME_LIBRARY=Shared -DCMAKE_BUILD_TYPE=Release +cmake --build build --target strata native_expert_parity ple_q5_parity +python tools/iq_pack.py --gguf /models/Qwen3.8-Flash-Next-Uncensored-Q4_K_S-00001-of-00003.gguf --out packs/orca-q4_k_s --compat-bf16 +``` + +`iq_pack.py` needs NumPy and the `gguf-py` module from the pinned llama.cpp dependency (`STRATA_GGUF_PY` can point to that directory). It writes a roughly 1.43 GiB dense pack and a native-expert manifest. The original 112 GB of model shards are read in place; `experts.bin` is optional and is not written by this command. + +Check the changed kernels against the real files before starting the service: + +```sh +build/native_expert_parity /models/Qwen3.8-Flash-Next-Uncensored-Q4_K_S-00001-of-00003.gguf /models/Qwen3.8-Flash-Next-Uncensored-Q4_K_S-00002-of-00003.gguf /models/Qwen3.8-Flash-Next-Uncensored-Q4_K_S-00003-of-00003.gguf 0 5 6 20 47 +build/ple_q5_parity /models/Qwen3.8-Flash-Next-Uncensored-Q4_K_S-00001-of-00003.gguf +``` + +## Engine flags + +Pass the same first shard to `--native` and `--ple-gguf`; Strata discovers the other two shards by name. For a first text-only run, use 32K context and a modest cache. Once that passes, increase the context and cache with memory measurements on the target machine. + +```sh +--pack packs/orca-q4_k_s --native /models/Qwen3.8-Flash-Next-Uncensored-Q4_K_S-00001-of-00003.gguf --ple-gguf /models/Qwen3.8-Flash-Next-Uncensored-Q4_K_S-00001-of-00003.gguf --ple-io mmap --expert-profile data/expert-profile.bin --expert-cache auto --prefill 512 --spec 4 --mtp /path/to/mtp/rt --max-context 32768 --kv int8 +``` + +For two GPUs in persistent server mode, add `--layer-split auto --split-device 1` (with CUDA0 and CUDA1 visible). The usual Strata MTP runtime is built from the original model's draft layer; draft acceptance on the Uncensored fine-tune must be measured. Keep this model's own tokenizer from the pack. Do not combine `--expert-cache-per-layer` with a variable-size native cache: that policy's slot ordering is independent of the pack's per-layer blob sizes. + +This port does not claim that Q4_K_S beats llama.cpp on a given computer. Compare the same model bytes, prompt, context, output length and GPU load; report prefill and decode separately. diff --git a/src/kernels/cuda/dequant_bf16.cu b/src/kernels/cuda/dequant_bf16.cu index faac2ab4..32601d60 100644 --- a/src/kernels/cuda/dequant_bf16.cu +++ b/src/kernels/cuda/dequant_bf16.cu @@ -67,6 +67,17 @@ __device__ __forceinline__ void group32(const uint8_t* row_blocks, int gi_in_row put(out, j, (float) (((b[6 + j] & 0x0F) | xh0) - 16) * d); put(out, j + 16, (float) (((b[6 + j] >> 4) | xh1) - 16) * d); } + } else if constexpr (TYPE == 7) { // Q5_1 + const uint8_t* b = row_blocks + (size_t) gi_in_row * 24; + const float d = h2f(b), m = h2f(b + 2); + const uint32_t qh = (uint32_t) b[4] | ((uint32_t) b[5] << 8) | + ((uint32_t) b[6] << 16) | ((uint32_t) b[7] << 24); + for (int j = 0; j < 16; ++j) { + const int xh0 = ((qh >> j) & 1) << 4; + const int xh1 = ((qh >> (j + 16)) & 1) << 4; + put(out, j, (float) ((b[8 + j] & 15) | xh0) * d + m); + put(out, j + 16, (float) ((b[8 + j] >> 4) | xh1) * d + m); + } } else if constexpr (TYPE == 8) { // Q8_0 const uint8_t* b = row_blocks + (size_t) gi_in_row * 34; const float d = h2f(b); @@ -167,6 +178,7 @@ bool geometry(int type, int& block_elems, int& block_bytes) { switch (type) { case 2: block_elems = 32; block_bytes = 18; return true; case 6: block_elems = 32; block_bytes = 22; return true; + case 7: block_elems = 32; block_bytes = 24; return true; case 8: block_elems = 32; block_bytes = 34; return true; case 20: block_elems = 32; block_bytes = 18; return true; case 11: block_elems = 256; block_bytes = 110; return true; @@ -195,6 +207,7 @@ void launch(int type, const void* blocks, int64_t row0, int64_t rows, int64_t co switch (type) { case 2: STRATA_DQ(2); case 6: STRATA_DQ(6); + case 7: STRATA_DQ(7); case 8: STRATA_DQ(8); case 11: STRATA_DQ(11); case 12: STRATA_DQ(12); diff --git a/src/kernels/cuda/native_mmvq.cu b/src/kernels/cuda/native_mmvq.cu index 219576f7..e0a4c1bd 100644 --- a/src/kernels/cuda/native_mmvq.cu +++ b/src/kernels/cuda/native_mmvq.cu @@ -1439,7 +1439,7 @@ void native_iq4_nl_f32(const void* weights, const float* x, void* scratch_q8_1, } bool native_mmvq_supported(int ggml_type) noexcept { - return ggml_type == 2 || ggml_type == 6 || ggml_type == 8 || ggml_type == 11 || + return ggml_type == 2 || ggml_type == 6 || ggml_type == 7 || ggml_type == 8 || ggml_type == 11 || ggml_type == 12 || ggml_type == 13 || ggml_type == 14 || ggml_type == 20 || ggml_type == 23 || ggml_type == 42 || ggml_type == 16 || ggml_type == 17 || ggml_type == 18 || ggml_type == 21 || ggml_type == 22 || ggml_type == 29; @@ -1450,6 +1450,7 @@ std::size_t native_mmvq_weight_bytes(int ggml_type, int n_in, int n_out) { switch (ggml_type) { case 2: block_elems = 32; block_bytes = 18; break; case 6: block_elems = 32; block_bytes = 22; break; + case 7: block_elems = 32; block_bytes = 24; break; case 8: block_elems = 32; block_bytes = 34; break; case 20: block_elems = 32; block_bytes = 18; break; case 11: block_elems = 256; block_bytes = 110; break; @@ -1476,6 +1477,7 @@ void native_mmvq(int ggml_type, const void* weights, const void* x_q8_1, float* switch (ggml_type) { case 2: native_q4_0_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream); break; case 6: native_q5_0_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream); break; + case 7: iq_mmvq(ggml_type, weights, x_q8_1, y, n_in, n_out, ncols, stream); break; case 8: native_q8_0_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream); break; case 20: native_iq4_nl_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream); break; case 11: native_q3_k_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream); break; diff --git a/src/kernels/ngram.cpp b/src/kernels/ngram.cpp index 4831f63d..bd366c50 100644 --- a/src/kernels/ngram.cpp +++ b/src/kernels/ngram.cpp @@ -3,6 +3,7 @@ // See include/strata/kernels/ngram.hpp for the semantics, the rival readings, and the note on MADV_RANDOM. #include "strata/kernels/ngram.hpp" #include "strata/artifact/gguf_reader.hpp" +#include "strata/artifact/dequant.hpp" #include "strata/kernels/f16_bits.hpp" #include "strata/ngram/ple_reader.hpp" @@ -116,6 +117,8 @@ struct PleTable::Impl { GgufFile* file = nullptr; const uint8_t* data = nullptr; uint64_t n_rows = 0; + uint32_t row_bytes = PLE_ROW_BYTES; + bool q5_0 = false; mutable uint64_t bytes_read = 0; // Direct mode (plan v0.3 P2): the mapping above is released after the header parse and every row comes // from an unbuffered SSD read into `raw`. @@ -155,11 +158,20 @@ bool PleTable::open(const std::string& gguf_path, std::string& err, const PleIoO close(); return false; } - if (std::strcmp(t->type_name(), "IQ4_NL") != 0) { - err = std::string("per_layer_token_embd.weight is ") + t->type_name() + ", not IQ4_NL"; + impl_->q5_0 = std::strcmp(t->type_name(), "Q5_0") == 0; + if (!impl_->q5_0 && std::strcmp(t->type_name(), "IQ4_NL") != 0) { + err = std::string("per_layer_token_embd.weight is ") + t->type_name() + ", expected IQ4_NL or Q5_0"; close(); return false; } + // The direct reader has fixed 90-byte rows. Keep it for IQ4_NL; Q5_0's + // 110-byte rows use the mapped path until that reader supports variable rows. + if (impl_->q5_0 && io.mode == PleIo::Direct) { + err = "Q5_0 PLE requires --ple-io mmap"; + close(); + return false; + } + impl_->row_bytes = impl_->q5_0 ? (PLE_HEAD_DIM / 32) * 22 : PLE_ROW_BYTES; impl_->n_rows = t->shape[1]; impl_->data = impl_->file->tensor_data(*t); @@ -171,7 +183,7 @@ bool PleTable::open(const std::string& gguf_path, std::string& err, const PleIoO // assumed. A wrong data offset would leave a different remainder. // A shard may hold other tensors too (Swift 1.5's shard 1 holds layers 0-12 and the table): the table must // then fit inside the file at its own offset; alone in its shard (the original's shard 2) it fills it exactly. - const uint64_t need = impl_->n_rows * (uint64_t) PLE_ROW_BYTES; + const uint64_t need = impl_->n_rows * (uint64_t) impl_->row_bytes; const uint64_t have = impl_->file->file_size() - impl_->file->data_start(); const bool alone = impl_->file->tensors().size() == 1; if (alone ? need != have : t->offset + need > have) { @@ -179,7 +191,7 @@ bool PleTable::open(const std::string& gguf_path, std::string& err, const PleIoO std::snprintf(buf, sizeof buf, "PLE table size mismatch: %llu rows x %d B = %llu at offset %llu, but the file holds %llu from " "data_start %llu", - (unsigned long long) impl_->n_rows, PLE_ROW_BYTES, (unsigned long long) need, + (unsigned long long) impl_->n_rows, (int) impl_->row_bytes, (unsigned long long) need, (unsigned long long) t->offset, (unsigned long long) have, (unsigned long long) impl_->file->data_start()); err = buf; @@ -231,6 +243,8 @@ void PleTable::close() { impl_->file = nullptr; impl_->data = nullptr; impl_->n_rows = 0; + impl_->row_bytes = PLE_ROW_BYTES; + impl_->q5_0 = false; } bool PleTable::is_open() const { return impl_->data != nullptr || impl_->reader.is_open(); } @@ -256,8 +270,14 @@ void PleTable::read_row(uint32_t row, float* out160) const { std::memset(out160, 0, (size_t) PLE_HEAD_DIM * sizeof(float)); return; } - iq4nl_dequant_row(impl_->data + (size_t) row * PLE_ROW_BYTES, out160); - impl_->bytes_read += PLE_ROW_BYTES; + const uint8_t* raw = impl_->data + (size_t) row * impl_->row_bytes; + if (impl_->q5_0) { + for (int b = 0; b < PLE_HEAD_DIM / 32; ++b) + strata::dequantize_q5_0(raw + (size_t) b * 22, out160 + b * 32); + } else { + iq4nl_dequant_row(raw, out160); + } + impl_->bytes_read += impl_->row_bytes; } bool PleTable::issue(const uint32_t* rows16) { @@ -274,8 +294,8 @@ bool PleTable::issue(const uint32_t* rows16) { ULONG_PTR n = 0; for (int h = 0; h < PLE_N_HEADS; ++h) { if (rows16[h] >= impl_->n_rows) continue; - ranges[n].VirtualAddress = (PVOID) (impl_->data + (size_t) rows16[h] * PLE_ROW_BYTES); - ranges[n].NumberOfBytes = PLE_ROW_BYTES; + ranges[n].VirtualAddress = (PVOID) (impl_->data + (size_t) rows16[h] * impl_->row_bytes); + ranges[n].NumberOfBytes = impl_->row_bytes; ++n; } if (n > 0) (void) PrefetchVirtualMemory(GetCurrentProcess(), n, ranges, 0); @@ -364,8 +384,8 @@ void PleTable::gather(const uint32_t* rows16, float* out2560) const { for (int h = 0; h < PLE_N_HEADS; ++h) { // Out-of-range rows are handled by `read_row` as zeros and have no address to prefetch. if (rows16[h] >= impl_->n_rows) continue; - ranges[n].VirtualAddress = (PVOID) (impl_->data + (size_t) rows16[h] * PLE_ROW_BYTES); - ranges[n].NumberOfBytes = PLE_ROW_BYTES; + ranges[n].VirtualAddress = (PVOID) (impl_->data + (size_t) rows16[h] * impl_->row_bytes); + ranges[n].NumberOfBytes = impl_->row_bytes; ++n; } if (n > 0) (void) PrefetchVirtualMemory(GetCurrentProcess(), n, ranges, 0); diff --git a/src/kernels/ple_q5_parity.cpp b/src/kernels/ple_q5_parity.cpp new file mode 100644 index 00000000..cd387a8e --- /dev/null +++ b/src/kernels/ple_q5_parity.cpp @@ -0,0 +1,59 @@ +// Real-artifact Q5_0 PLE rows against ggml's reference dequantizer. +#define NOMINMAX +#include "strata/artifact/gguf_reader.hpp" +#include "strata/kernels/ngram.hpp" +#include "ggml.h" + +#include +#include +#include +#include +#include + +int main(int argc, char** argv) { + if (argc != 2) { + std::fprintf(stderr, "usage: ple_q5_parity \n"); + return 2; + } + strata::GgufFile gguf(argv[1]); + const auto* tensor = gguf.find("per_layer_token_embd.weight"); + if (!tensor || tensor->type != 6 || tensor->shape.size() != 2 || tensor->shape[0] != 160) { + std::fprintf(stderr, "expected Q5_0 PLE [160, N]\n"); + return 2; + } + strata::kernels::PleIoOptions options; + options.mode = strata::kernels::PleIo::Mmap; + strata::kernels::PleTable table; + std::string err; + if (!table.open(argv[1], err, options)) { + std::fprintf(stderr, "%s\n", err.c_str()); + return 1; + } + const auto* traits = ggml_get_type_traits(GGML_TYPE_Q5_0); + const uint8_t* bytes = gguf.tensor_data(*tensor); + const uint32_t probes[] = {0, 1, 12345, 20000003, (uint32_t) (table.rows() - 1)}; + double max_abs = 0.0; + for (uint32_t row : probes) { + float got[160], want[160]; + table.read_row(row, got); + traits->to_float(bytes + (size_t) row * 110, want, 160); + for (int i = 0; i < 160; ++i) + max_abs = std::max(max_abs, (double) std::fabs(got[i] - want[i])); + } + uint32_t rows[16]; + for (int i = 0; i < 16; ++i) rows[i] = probes[i % 5]; + float batch[16 * 160]; + if (!table.issue(rows) || !table.collect(batch, err)) { + std::fprintf(stderr, "collect: %s\n", err.c_str()); + return 1; + } + for (int h = 0; h < 16; ++h) { + float want[160]; + traits->to_float(bytes + (size_t) rows[h] * 110, want, 160); + for (int i = 0; i < 160; ++i) + max_abs = std::max(max_abs, (double) std::fabs(batch[h * 160 + i] - want[i])); + } + std::printf("Q5_0 PLE: %zu rows, max_abs %.3e %s\n", (size_t) table.rows(), max_abs, + max_abs <= 1e-6 ? "PASS" : "FAIL"); + return max_abs <= 1e-6 ? 0 : 1; +} diff --git a/src/kernels/q5_projection_parity.cpp b/src/kernels/q5_projection_parity.cpp new file mode 100644 index 00000000..20faf995 --- /dev/null +++ b/src/kernels/q5_projection_parity.cpp @@ -0,0 +1,62 @@ +// Q5_1 shared-expert projection: Strata CUDA dequantization vs ggml. +#define NOMINMAX +#include "strata/artifact/gguf_reader.hpp" +#include "strata/kernels/dequant_bf16.hpp" +#include "ggml.h" + +#include +#include +#include +#include +#include +#include +#include + +int main(int argc, char** argv) { + if (argc != 2) { + std::fprintf(stderr, "usage: q5_projection_parity \n"); + return 2; + } + strata::GgufFile gguf(argv[1]); + const auto* t = gguf.find("blk.0.ffn_down_shexp.weight"); + if (!t || t->type != 7 || t->shape.size() != 2) { + std::fprintf(stderr, "expected blk.0.ffn_down_shexp.weight Q5_1\n"); + return 2; + } + const int64_t cols = (int64_t) t->shape[0], rows = std::min(4, (int64_t) t->shape[1]); + const size_t weight_bytes = (size_t) rows * (size_t) (cols / 32) * 24; + const size_t elements = (size_t) rows * (size_t) cols; + const uint8_t* source = gguf.tensor_data(*t); + void *dweight = nullptr, *dfloat = nullptr, *dbf16 = nullptr; + if (cudaMalloc(&dweight, weight_bytes) != cudaSuccess || + cudaMalloc(&dfloat, elements * sizeof(float)) != cudaSuccess || + cudaMalloc(&dbf16, elements * sizeof(uint16_t)) != cudaSuccess) { + std::fprintf(stderr, "CUDA allocation failed\n"); + return 1; + } + cudaMemcpy(dweight, source, weight_bytes, cudaMemcpyHostToDevice); + strata::kernels::dequant_f32(7, dweight, 0, rows, cols, (float*) dfloat, nullptr); + strata::kernels::dequant_bf16(7, dweight, 0, rows, cols, (uint16_t*) dbf16, nullptr); + std::vector got(elements), ref(elements); + std::vector got_bf16(elements); + cudaMemcpy(got.data(), dfloat, elements * sizeof(float), cudaMemcpyDeviceToHost); + cudaMemcpy(got_bf16.data(), dbf16, elements * sizeof(uint16_t), cudaMemcpyDeviceToHost); + cudaFree(dweight); cudaFree(dfloat); cudaFree(dbf16); + const auto* traits = ggml_get_type_traits(GGML_TYPE_Q5_1); + for (int64_t r = 0; r < rows; ++r) + traits->to_float(source + (size_t) r * (size_t) (cols / 32) * 24, + ref.data() + (size_t) r * (size_t) cols, cols); + double max_abs = 0; + size_t bf16_bad = 0; + for (size_t i = 0; i < elements; ++i) { + max_abs = std::max(max_abs, (double) std::fabs(got[i] - ref[i])); + uint32_t bits; + std::memcpy(&bits, &ref[i], sizeof(bits)); + const uint16_t expected = (uint16_t) ((bits + 0x7fffu + ((bits >> 16) & 1u)) >> 16); + if (got_bf16[i] != expected) ++bf16_bad; + } + const bool ok = max_abs <= 1e-6 && bf16_bad == 0; + std::printf("Q5_1 projection: %zu elements, max_abs %.3e, bf16 differences %zu %s\n", + elements, max_abs, bf16_bad, ok ? "PASS" : "FAIL"); + return ok ? 0 : 1; +} diff --git a/src/prefill/moe_mmq.cu b/src/prefill/moe_mmq.cu index ac2daee4..35aa5354 100644 --- a/src/prefill/moe_mmq.cu +++ b/src/prefill/moe_mmq.cu @@ -91,7 +91,11 @@ bool built() { return true; } bool supported(int t) { switch ((ggml_type) t) { - case GGML_TYPE_Q2_0: case GGML_TYPE_IQ2_XXS: case GGML_TYPE_IQ2_XS: case GGML_TYPE_IQ2_S: + case GGML_TYPE_Q2_0: +#ifdef STRATA_ORCA_Q4KS_MMQ + case GGML_TYPE_Q4_K: case GGML_TYPE_Q5_0: case GGML_TYPE_Q5_1: +#endif + case GGML_TYPE_IQ2_XXS: case GGML_TYPE_IQ2_XS: case GGML_TYPE_IQ2_S: case GGML_TYPE_IQ3_XXS: case GGML_TYPE_IQ3_S: case GGML_TYPE_IQ4_NL: case GGML_TYPE_IQ4_XS: case GGML_TYPE_Q8_0: // the draft layer's dense matrices (E-9) return true; @@ -134,6 +138,11 @@ void Context::run(const Product& p, void* stream) { auto& ctx = *(ggml_backend_cuda_context*) ctx_; const cudaStream_t s = (cudaStream_t) stream; switch (t) { +#ifdef STRATA_ORCA_Q4KS_MMQ + case GGML_TYPE_Q4_K: mul_mat_q_case(ctx, a, s); break; + case GGML_TYPE_Q5_0: mul_mat_q_case(ctx, a, s); break; + case GGML_TYPE_Q5_1: mul_mat_q_case(ctx, a, s); break; +#endif case GGML_TYPE_Q2_0: mul_mat_q_case(ctx, a, s); break; case GGML_TYPE_IQ2_XXS: mul_mat_q_case(ctx, a, s); break; case GGML_TYPE_IQ2_XS: mul_mat_q_case(ctx, a, s); break; From 5fd4f2670f10b36d35c78f890a64a717e686fcbe Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Thu, 1 Oct 2026 08:49:15 +0200 Subject: [PATCH 43/48] #296 follow-up: ple_q5_parity / q5_projection_parity build only with STRATA_BUILD_TESTS; the doc says what runs where The two real-weight checks were added to every CUDA build with native experts (a full release build compiled them); they are test programs. docs/ORCA_Q4_K_S.md: the build flag for them, and that 0.1.31's GPU expert kernels take Q4_K gate/up with Q5_1 or Q8_0 downs (Q5_0 is not among them yet: the engine refuses such a pack at start, naming the layer). --- CMakeLists.txt | 3 ++- docs/ORCA_Q4_K_S.md | 4 ++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 1b3319e3..c3bd402f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -905,7 +905,8 @@ if(STRATA_NATIVE_EXPERTS) set_tests_properties(native_expert_parity_refuses_q6_K PROPERTIES WILL_FAIL TRUE) endif() endif() - if(STRATA_ENABLE_CUDA) + # #296's real-weight checks (OrcaRouter Q4_K_S files; docs/ORCA_Q4_K_S.md) - test programs, not part of a release + if(STRATA_ENABLE_CUDA AND STRATA_BUILD_TESTS) add_executable(ple_q5_parity src/kernels/ple_q5_parity.cpp) target_link_libraries(ple_q5_parity PRIVATE strata_kernels strata_artifact ggml-base ${_strata_gpu_runtime_target}) add_executable(q5_projection_parity src/kernels/q5_projection_parity.cpp) diff --git a/docs/ORCA_Q4_K_S.md b/docs/ORCA_Q4_K_S.md index 6a1800e3..78b11358 100644 --- a/docs/ORCA_Q4_K_S.md +++ b/docs/ORCA_Q4_K_S.md @@ -2,11 +2,11 @@ This path uses the three original `orcarouter/Qwen3.8-Flash-Next-Uncensored-GGUF` Q4_K_S shards without rewriting their expert, embedding or PLE table bytes. It is separate from the installer model menu. Keep all three shard filenames together. -The ordinary GGUF quantizes some small projections which Strata reads as BF16. `--compat-bf16` dequantizes and rounds those projections to BF16 in the separate pack; it does not restore their original precision. The Q5_0 PLE table remains in the source GGUF and currently uses the mapped reader (`--ple-io mmap`). The Q4_K gate/up experts and Q5_0/Q5_1 down experts remain in GGUF form, including layers whose three tensors cross shard boundaries. +The ordinary GGUF quantizes some small projections which Strata reads as BF16. `--compat-bf16` dequantizes and rounds those projections to BF16 in the separate pack; it does not restore their original precision. The Q5_0 PLE table remains in the source GGUF and currently uses the mapped reader (`--ple-io mmap`). The Q4_K gate/up experts and Q5_0/Q5_1 down experts remain in GGUF form, including layers whose three tensors cross shard boundaries (each role is read from its own shard). The GPU expert kernels take Q4_K with Q5_1 (or Q8_0) downs; Q5_0 downs are not among them yet, and the engine refuses to start on a pack with such a layer (it names the layer). ## Build and prepare -Build Strata with CUDA, native experts and `STRATA_ORCA_Q4KS_MMQ=ON`. This opt-in compiles the Q4_K, Q5_0 and Q5_1 GGML MMQ instances for CUDA or HIP; the usual Q8_0 draft-layer instance remains in both builds. HIP also needs `STRATA_PREFILL_MMQ=ON`. Select your card's compute capability, for example `89` on an L40S. On Windows with Ninja and CUDA 12.6, use the Visual Studio developer environment and `-DCMAKE_CUDA_RUNTIME_LIBRARY=Shared` to keep the CUDA runtime linkage consistent. The default pinned ggml checkout is supported by the project build. +Build Strata with CUDA, native experts, `STRATA_ORCA_Q4KS_MMQ=ON` (and `STRATA_BUILD_TESTS=ON` for the two parity programs below). This opt-in compiles the Q4_K, Q5_0 and Q5_1 GGML MMQ instances for CUDA or HIP; the usual Q8_0 draft-layer instance remains in both builds. HIP also needs `STRATA_PREFILL_MMQ=ON`. Select your card's compute capability, for example `89` on an L40S. On Windows with Ninja and CUDA 12.6, use the Visual Studio developer environment and `-DCMAKE_CUDA_RUNTIME_LIBRARY=Shared` to keep the CUDA runtime linkage consistent. The default pinned ggml checkout is supported by the project build. ```sh cmake -S . -B build -G Ninja -DSTRATA_ENABLE_CUDA=ON -DSTRATA_NATIVE_EXPERTS=ON -DSTRATA_ORCA_Q4KS_MMQ=ON -DCMAKE_CUDA_ARCHITECTURES=89 -DCMAKE_CUDA_RUNTIME_LIBRARY=Shared -DCMAKE_BUILD_TYPE=Release From d11ea857dfce52f6a5a01f29b9c1e92a8225a320 Mon Sep 17 00:00:00 2001 From: sergiywith Date: Wed, 30 Sep 2026 22:25:39 +0300 Subject: [PATCH 44/48] PLE: the n-gram table in FP8 E4M3, as Qwen ships it The engine read the 51.2e9-value n-gram table only as IQ4_NL (ISTA-DASLab's shard 2, 90 B/row), which is 8.1% off the checkpoint's own values per row (correlation 0.996-0.997 on rows from all 128 shards: same table, same order). The checkpoint stores it as 128 shards of [2500012, 160] F8_E4M3 plus one weight_scale. - tools/ple_fp8_pack.py copies those bytes, unchanged, into a one-tensor GGUF: per_layer_token_embd.weight [160, 320001536] as I8, with strata.ple.format = f8_e4m3 and strata.ple.scale. 51.2 GB, streamed. - PleTable opens either format; the row size (90 / 160) and the decode (IQ4_NL codebook / an E4M3 table times the scale) follow the file. PleReader takes the row size at open; its cache sizes itself by it. GGUF reader: type I8. - A PLE-only table (architecture strata-ple) is not added to the dense-projection sources. - The start line names the table's format. - ple_fp8_parity: rows through Direct, Mmap and gather_batch match torch's decode of the checkpoint bit for bit. First-token KL of the IQ4_NL table against the FP8 one: 0.0009 (1K), 0.0013 (2K), 0.0002 (4K), 0.022 (32K); mean 0.0061, top-1 4/4. Rebased onto 0.1.31 + #317 + #296 (Niko1221): one row size (`rb`) and one decoder in PleTable for the three table formats - IQ4_NL, #296's Q5_0 (110 B rows, the mapped reader only, as #296 has it) and FP8 (160 B) - and #317's SSD keep-alive picks its page inside the table at the table's own row size; 0.1.31's shard list for the dense sources keeps the PLE-only exception; ple_fp8_parity builds with STRATA_BUILD_TESTS beside #296's checks. The "PLE on" start line stays 0.1.31's. --- CMakeLists.txt | 3 + include/strata/artifact/gguf_reader.hpp | 6 ++ include/strata/kernels/ngram.hpp | 11 ++- include/strata/ngram/ple_reader.hpp | 12 ++- src/kernels/ngram.cpp | 101 +++++++++++++------ src/kernels/ple_fp8_parity.cpp | 84 ++++++++++++++++ src/ngram/ple_reader.cpp | 39 +++++--- src/program/generate.cpp | 9 +- tools/ple_fp8_pack.py | 123 ++++++++++++++++++++++++ 9 files changed, 335 insertions(+), 53 deletions(-) create mode 100644 src/kernels/ple_fp8_parity.cpp create mode 100644 tools/ple_fp8_pack.py diff --git a/CMakeLists.txt b/CMakeLists.txt index c3bd402f..07c2f0f3 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -912,6 +912,9 @@ if(STRATA_NATIVE_EXPERTS) add_executable(q5_projection_parity src/kernels/q5_projection_parity.cpp) target_include_directories(q5_projection_parity PRIVATE ${_strata_gpu_include_directories}) target_link_libraries(q5_projection_parity PRIVATE strata_kernels strata_artifact ggml-base ${_strata_gpu_runtime_target}) + # #291: the FP8 PLE table (tools/ple_fp8_pack.py) through PleTable vs the checkpoint's own values + add_executable(ple_fp8_parity src/kernels/ple_fp8_parity.cpp) + target_link_libraries(ple_fp8_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) endif() endif() diff --git a/include/strata/artifact/gguf_reader.hpp b/include/strata/artifact/gguf_reader.hpp index 42e0665e..298dc3bc 100644 --- a/include/strata/artifact/gguf_reader.hpp +++ b/include/strata/artifact/gguf_reader.hpp @@ -96,6 +96,8 @@ inline const char* ggml_type_name(uint32_t t) { return "IQ2_S"; case 23: return "IQ4_XS"; + case 24: + return "I8"; case 30: return "BF16"; case 34: @@ -204,6 +206,10 @@ inline bool block_geometry(uint32_t t, int& elems, int& bytes) { elems = 256; bytes = 56; return true; + case 24: // I8: raw bytes (the FP8 PLE table of tools/ple_fp8_pack.py) + elems = 1; + bytes = 1; + return true; case 42: elems = 64; bytes = 18; diff --git a/include/strata/kernels/ngram.hpp b/include/strata/kernels/ngram.hpp index 33f3eb02..3c6f8fab 100644 --- a/include/strata/kernels/ngram.hpp +++ b/include/strata/kernels/ngram.hpp @@ -44,7 +44,9 @@ inline constexpr float NG_RMS_EPS = 1e-6f; // The table: [160, 320001536] IQ4_NL. ne0 = 160 is the FAST axis, so one row is 160 contiguous elements = // 5 blocks of 32 at 18 bytes = 90 bytes. The head-slowest flatten then makes 16 rows exactly n_embd = 2560. inline constexpr uint64_t PLE_TABLE_ROWS = 320001536ull; -inline constexpr int PLE_ROW_BYTES = (PLE_HEAD_DIM / 32) * 18; // 90 +inline constexpr int PLE_ROW_BYTES = (PLE_HEAD_DIM / 32) * 18; // 90: an IQ4_NL row +inline constexpr int PLE_ROW_BYTES_FP8 = PLE_HEAD_DIM; // 160: an F8_E4M3 row, one byte a value +inline constexpr int PLE_ROW_BYTES_MAX = PLE_ROW_BYTES_FP8; /// The artifact's own hash constants, transcribed from `docs/gguf-dump-shard1.txt`: /// @@ -96,6 +98,11 @@ int iq4nl_code(int code); /// a perfectly plausible embedding of the wrong 160 values. void iq4nl_dequant_row(const uint8_t* row, float* out160); +/// One FP8 row -> 160 floats: each byte an E4M3 value (the "fn" variant: no infinities, 0x7F/0xFF are NaN), times the +/// table's one scale. This is the table as Qwen3.8-Flash-Next ships it (`...ngram_embedding.shard_k`, F8_E4M3, and +/// `weight_scale`), kept byte for byte by tools/ple_fp8_pack.py; IQ4_NL is 8% off it per row. +void fp8_e4m3_dequant_row(const uint8_t* row, float scale, float* out160); + /// How the table's rows are read (plan v0.3 P2). `Direct` is the default: unbuffered 4 KiB reads from the SSD, /// so the table never occupies RAM or the OS file cache. `Mmap` is the earlier memory-mapped path, kept as the /// A/B arm; it returns the same bytes. @@ -155,6 +162,8 @@ public: /// True when `PleIoOptions::lock` was asked for and mlock succeeded (false: pages only pre-touched). bool locked() const; uint64_t rows() const; + /// "IQ4_NL" or "F8_E4M3" (a GGUF from tools/ple_fp8_pack.py: type I8, strata.ple.format = f8_e4m3). + const char* format() const; /// 16 row indices -> 2560 floats. The gathered rows are flattened HEAD-SLOWEST: row h's 160 values /// occupy `out[h*160, (h+1)*160)`, which is what `ggml_get_rows` does and what makes the result a plain diff --git a/include/strata/ngram/ple_reader.hpp b/include/strata/ngram/ple_reader.hpp index 721645c0..2884817e 100644 --- a/include/strata/ngram/ple_reader.hpp +++ b/include/strata/ngram/ple_reader.hpp @@ -1,6 +1,6 @@ // include/strata/ngram/ple_reader.hpp - plan v0.3 P2: the n-gram table read straight from the SSD. // -// The table is 320,001,536 rows of 90 bytes (26.8 GiB) and is never held in RAM: every row comes from an +// The table is 320,001,536 rows of 90 bytes (IQ4_NL, 26.8 GiB) or 160 (FP8 E4M3, 51.2 GB) and is never held in RAM: every row comes from an // unbuffered 4 KiB read (platform::DirectFile). A token needs 16 rows on 16 different pages, and all 16 depend // on the token itself, so the only time to hide them is the embedding plus layer 0. Hence the split API: // @@ -24,7 +24,7 @@ namespace strata::ngram { -inline constexpr uint32_t ROW_BYTES = 90; +inline constexpr uint32_t ROW_BYTES = 90; ///< an IQ4_NL row; `open` takes the table's own size inline constexpr uint32_t PAGE = 4096; struct ReaderStats { @@ -58,13 +58,15 @@ public: /// validated GGUF parse (PleTable::open checks the table exactly fills the file from there). /// `io_thread` (default): a worker thread submits and reaps reads, so `issue` costs the caller no ReadFile /// calls. false: the caller's thread does it (A/B arm). + /// `row_bytes`: one row's size in the file (90 IQ4_NL, 160 FP8), at most one page. bool open(const std::string& path, uint64_t table_offset, uint64_t n_rows, uint32_t max_inflight, - uint64_t cache_rows, std::string& err, bool io_thread = true); + uint64_t cache_rows, std::string& err, bool io_thread = true, uint32_t row_bytes = ROW_BYTES); + uint32_t row_bytes() const; void close(); bool is_open() const; - /// Start fetching `n` rows; row i's 90 raw bytes land at `out_raw + 90 * i`. `out_raw` must stay valid - /// until `collect` returns. Out-of-range rows produce 90 zero bytes (the mmap path's behaviour). + /// Start fetching `n` rows; row i's raw bytes land at `out_raw + row_bytes * i`. `out_raw` must stay valid + /// until `collect` returns. Out-of-range rows produce zero bytes (the mmap path's behaviour). Ticket issue(const uint32_t* rows, size_t n, uint8_t* out_raw); /// Block until every row of the ticket is in `out_raw`. Returns false on an I/O error (message in `err`). diff --git a/src/kernels/ngram.cpp b/src/kernels/ngram.cpp index bd366c50..1a1552bf 100644 --- a/src/kernels/ngram.cpp +++ b/src/kernels/ngram.cpp @@ -8,6 +8,7 @@ #include "strata/ngram/ple_reader.hpp" #include +#include #include #include #if !defined(_WIN32) @@ -112,13 +113,33 @@ void iq4nl_dequant_row(const uint8_t* row, float* out160) { } } +namespace { +struct Fp8Table { + float v[256]; + Fp8Table() { + for (int x = 0; x < 256; ++x) { + const int s = x >> 7, e = (x >> 3) & 15, m = x & 7; + float f; + if (e == 15 && m == 7) f = 0.0f; // NaN in e4m3fn; never in a real table, read as 0 + else if (e == 0) f = std::ldexp((float) m / 8.0f, -6); + else f = std::ldexp(1.0f + (float) m / 8.0f, e - 7); + v[x] = s ? -f : f; + } + } +}; +const Fp8Table kFp8; +} // namespace + +void fp8_e4m3_dequant_row(const uint8_t* row, float scale, float* out160) { + for (int j = 0; j < PLE_HEAD_DIM; ++j) out160[j] = kFp8.v[row[j]] * scale; +} + // --------------------------------------------------------------------------------------------------- struct PleTable::Impl { GgufFile* file = nullptr; const uint8_t* data = nullptr; uint64_t n_rows = 0; - uint32_t row_bytes = PLE_ROW_BYTES; - bool q5_0 = false; + bool q5_0 = false; // #296: Q5_0 rows (110 B), the mapped reader only mutable uint64_t bytes_read = 0; // Direct mode (plan v0.3 P2): the mapping above is released after the header parse and every row comes // from an unbuffered SSD read into `raw`. @@ -128,7 +149,16 @@ struct PleTable::Impl { bool pending = false; bool locked = false; uint32_t rows[PLE_N_HEADS] = {}; - uint8_t raw[PLE_N_HEADS * PLE_ROW_BYTES] = {}; + uint8_t raw[PLE_N_HEADS * PLE_ROW_BYTES_MAX] = {}; + bool fp8 = false; // F8_E4M3 rows (tools/ple_fp8_pack.py); else IQ4_NL + float scale = 1.0f; // the FP8 table's one scale + uint32_t rb = PLE_ROW_BYTES; // bytes per row + void decode(const uint8_t* row, float* out160) const { + if (fp8) fp8_e4m3_dequant_row(row, scale, out160); + else if (q5_0) + for (int b = 0; b < PLE_HEAD_DIM / 32; ++b) strata::dequantize_q5_0(row + (size_t) b * 22, out160 + b * 32); + else iq4nl_dequant_row(row, out160); + } }; PleTable::PleTable() : impl_(new Impl) {} @@ -158,9 +188,24 @@ bool PleTable::open(const std::string& gguf_path, std::string& err, const PleIoO close(); return false; } + // IQ4_NL (ISTA-DASLab's shard 2, the original's own GGUF), Q5_0 (#296: OrcaRouter's GGUF), or the FP8 table as + // shipped: I8 bytes marked strata.ple.format = f8_e4m3 with strata.ple.scale (tools/ple_fp8_pack.py) + impl_->fp8 = false; impl_->q5_0 = std::strcmp(t->type_name(), "Q5_0") == 0; - if (!impl_->q5_0 && std::strcmp(t->type_name(), "IQ4_NL") != 0) { - err = std::string("per_layer_token_embd.weight is ") + t->type_name() + ", expected IQ4_NL or Q5_0"; + impl_->rb = impl_->q5_0 ? (PLE_HEAD_DIM / 32) * 22 : PLE_ROW_BYTES; + if (std::strcmp(t->type_name(), "I8") == 0) { + const MetaValue* f = impl_->file->get("strata.ple.format"); + const MetaValue* s = impl_->file->get("strata.ple.scale"); + if (f == nullptr || f->s != "f8_e4m3" || s == nullptr || !(s->num() > 0.0)) { + err = "per_layer_token_embd.weight is I8 without strata.ple.format = f8_e4m3 and a positive strata.ple.scale"; + close(); + return false; + } + impl_->fp8 = true; + impl_->scale = (float) s->num(); + impl_->rb = PLE_ROW_BYTES_FP8; + } else if (!impl_->q5_0 && std::strcmp(t->type_name(), "IQ4_NL") != 0) { + err = std::string("per_layer_token_embd.weight is ") + t->type_name() + ", not IQ4_NL, Q5_0 or FP8 (I8)"; close(); return false; } @@ -171,7 +216,6 @@ bool PleTable::open(const std::string& gguf_path, std::string& err, const PleIoO close(); return false; } - impl_->row_bytes = impl_->q5_0 ? (PLE_HEAD_DIM / 32) * 22 : PLE_ROW_BYTES; impl_->n_rows = t->shape[1]; impl_->data = impl_->file->tensor_data(*t); @@ -183,7 +227,7 @@ bool PleTable::open(const std::string& gguf_path, std::string& err, const PleIoO // assumed. A wrong data offset would leave a different remainder. // A shard may hold other tensors too (Swift 1.5's shard 1 holds layers 0-12 and the table): the table must // then fit inside the file at its own offset; alone in its shard (the original's shard 2) it fills it exactly. - const uint64_t need = impl_->n_rows * (uint64_t) impl_->row_bytes; + const uint64_t need = impl_->n_rows * (uint64_t) impl_->rb; const uint64_t have = impl_->file->file_size() - impl_->file->data_start(); const bool alone = impl_->file->tensors().size() == 1; if (alone ? need != have : t->offset + need > have) { @@ -191,7 +235,7 @@ bool PleTable::open(const std::string& gguf_path, std::string& err, const PleIoO std::snprintf(buf, sizeof buf, "PLE table size mismatch: %llu rows x %d B = %llu at offset %llu, but the file holds %llu from " "data_start %llu", - (unsigned long long) impl_->n_rows, (int) impl_->row_bytes, (unsigned long long) need, + (unsigned long long) impl_->n_rows, (int) impl_->rb, (unsigned long long) need, (unsigned long long) t->offset, (unsigned long long) have, (unsigned long long) impl_->file->data_start()); err = buf; @@ -206,7 +250,8 @@ bool PleTable::open(const std::string& gguf_path, std::string& err, const PleIoO delete impl_->file; impl_->file = nullptr; impl_->data = nullptr; - if (!impl_->reader.open(gguf_path, table_offset, n_rows, io.max_inflight, io.cache_rows, err, io.io_thread)) { + if (!impl_->reader.open(gguf_path, table_offset, n_rows, io.max_inflight, io.cache_rows, err, io.io_thread, + impl_->rb)) { close(); return false; } @@ -243,41 +288,37 @@ void PleTable::close() { impl_->file = nullptr; impl_->data = nullptr; impl_->n_rows = 0; - impl_->row_bytes = PLE_ROW_BYTES; + impl_->rb = PLE_ROW_BYTES; impl_->q5_0 = false; + impl_->fp8 = false; } bool PleTable::is_open() const { return impl_->data != nullptr || impl_->reader.is_open(); } bool PleTable::locked() const { return impl_->locked; } +const char* PleTable::format() const { return impl_->fp8 ? "F8_E4M3" : impl_->q5_0 ? "Q5_0" : "IQ4_NL"; } PleIo PleTable::mode() const { return impl_->mode; } uint64_t PleTable::rows() const { return impl_->n_rows; } uint64_t PleTable::bytes_read() const { return impl_->bytes_read; } void PleTable::read_row(uint32_t row, float* out160) const { if (impl_->mode == PleIo::Direct && impl_->reader.is_open()) { - uint8_t raw[PLE_ROW_BYTES]; + uint8_t raw[PLE_ROW_BYTES_MAX]; std::string err; const auto t = impl_->reader.issue(&row, 1, raw); if (!impl_->reader.collect(t, err)) { std::memset(out160, 0, (size_t) PLE_HEAD_DIM * sizeof(float)); return; } - iq4nl_dequant_row(raw, out160); - impl_->bytes_read += PLE_ROW_BYTES; + impl_->decode(raw, out160); + impl_->bytes_read += impl_->rb; return; } if (impl_->data == nullptr || row >= impl_->n_rows) { std::memset(out160, 0, (size_t) PLE_HEAD_DIM * sizeof(float)); return; } - const uint8_t* raw = impl_->data + (size_t) row * impl_->row_bytes; - if (impl_->q5_0) { - for (int b = 0; b < PLE_HEAD_DIM / 32; ++b) - strata::dequantize_q5_0(raw + (size_t) b * 22, out160 + b * 32); - } else { - iq4nl_dequant_row(raw, out160); - } - impl_->bytes_read += impl_->row_bytes; + impl_->decode(impl_->data + (size_t) row * impl_->rb, out160); + impl_->bytes_read += impl_->rb; } bool PleTable::issue(const uint32_t* rows16) { @@ -294,8 +335,8 @@ bool PleTable::issue(const uint32_t* rows16) { ULONG_PTR n = 0; for (int h = 0; h < PLE_N_HEADS; ++h) { if (rows16[h] >= impl_->n_rows) continue; - ranges[n].VirtualAddress = (PVOID) (impl_->data + (size_t) rows16[h] * impl_->row_bytes); - ranges[n].NumberOfBytes = impl_->row_bytes; + ranges[n].VirtualAddress = (PVOID) (impl_->data + (size_t) rows16[h] * impl_->rb); + ranges[n].NumberOfBytes = impl_->rb; ++n; } if (n > 0) (void) PrefetchVirtualMemory(GetCurrentProcess(), n, ranges, 0); @@ -311,8 +352,8 @@ bool PleTable::collect(float* out2560, std::string& err) { if (impl_->mode == PleIo::Direct) { if (!impl_->reader.collect(impl_->ticket, err)) return false; for (int h = 0; h < PLE_N_HEADS; ++h) - iq4nl_dequant_row(impl_->raw + (size_t) h * PLE_ROW_BYTES, out2560 + (size_t) h * PLE_HEAD_DIM); - impl_->bytes_read += (uint64_t) PLE_N_HEADS * PLE_ROW_BYTES; + impl_->decode(impl_->raw + (size_t) h * impl_->rb, out2560 + (size_t) h * PLE_HEAD_DIM); + impl_->bytes_read += (uint64_t) PLE_N_HEADS * impl_->rb; return true; } for (int h = 0; h < PLE_N_HEADS; ++h) read_row(impl_->rows[h], out2560 + (size_t) h * PLE_HEAD_DIM); @@ -323,11 +364,11 @@ bool PleTable::gather_batch(const uint32_t* rows, size_t n_tokens, float* out, s if (impl_->pending) { err = "PleTable::gather_batch while a token is in flight"; return false; } const size_t n = n_tokens * (size_t) PLE_N_HEADS; if (impl_->mode == PleIo::Direct) { - std::vector raw(n * PLE_ROW_BYTES); + std::vector raw(n * impl_->rb); const auto ticket = impl_->reader.issue(rows, n, raw.data()); if (!impl_->reader.collect(ticket, err)) return false; - for (size_t i = 0; i < n; ++i) iq4nl_dequant_row(raw.data() + i * PLE_ROW_BYTES, out + i * PLE_HEAD_DIM); - impl_->bytes_read += (uint64_t) n * PLE_ROW_BYTES; + for (size_t i = 0; i < n; ++i) impl_->decode(raw.data() + i * impl_->rb, out + i * PLE_HEAD_DIM); + impl_->bytes_read += (uint64_t) n * impl_->rb; return true; } for (size_t i = 0; i < n; ++i) read_row(rows[i], out + i * PLE_HEAD_DIM); @@ -384,8 +425,8 @@ void PleTable::gather(const uint32_t* rows16, float* out2560) const { for (int h = 0; h < PLE_N_HEADS; ++h) { // Out-of-range rows are handled by `read_row` as zeros and have no address to prefetch. if (rows16[h] >= impl_->n_rows) continue; - ranges[n].VirtualAddress = (PVOID) (impl_->data + (size_t) rows16[h] * impl_->row_bytes); - ranges[n].NumberOfBytes = impl_->row_bytes; + ranges[n].VirtualAddress = (PVOID) (impl_->data + (size_t) rows16[h] * impl_->rb); + ranges[n].NumberOfBytes = impl_->rb; ++n; } if (n > 0) (void) PrefetchVirtualMemory(GetCurrentProcess(), n, ranges, 0); diff --git a/src/kernels/ple_fp8_parity.cpp b/src/kernels/ple_fp8_parity.cpp new file mode 100644 index 00000000..09dd199a --- /dev/null +++ b/src/kernels/ple_fp8_parity.cpp @@ -0,0 +1,84 @@ +// src/kernels/ple_fp8_parity.cpp - the FP8 PLE table (tools/ple_fp8_pack.py) read through PleTable, against values +// decoded from the checkpoint itself, and against the IQ4_NL table it replaces. +// +// ple_fp8_parity [] +// +// reference.bin: int32 n, uint32 rows[n], float32 values[n][160] - the rows as torch decodes the checkpoint's +// F8_E4M3 bytes, times its weight_scale (n a multiple of 16 for the gather_batch check). Every row must match BIT FOR BIT through +// both I/O modes (Direct and Mmap) and through the prompt path's gather_batch. With the IQ4_NL shard the same rows +// are compared too: same table, so a correlation near 0.997 - a shifted row order would be ~0. +#include "strata/kernels/ngram.hpp" + +#include +#include +#include +#include +#include +#include + +namespace k = strata::kernels; + +int main(int argc, char** argv) { + if (argc < 3) { + std::fprintf(stderr, "usage: ple_fp8_parity []\n"); + return 2; + } + std::ifstream f(argv[2], std::ios::binary); + int32_t n = 0; + f.read((char*) &n, 4); + std::vector rows((size_t) n); + std::vector ref((size_t) n * k::PLE_HEAD_DIM); + f.read((char*) rows.data(), (std::streamsize) rows.size() * 4); + f.read((char*) ref.data(), (std::streamsize) ref.size() * 4); + if (!f || n <= 0) { std::fprintf(stderr, "cannot read %s\n", argv[2]); return 2; } + + int bad = 0; + for (const k::PleIo mode : {k::PleIo::Direct, k::PleIo::Mmap}) { + k::PleTable t; + std::string err; + k::PleIoOptions io; + io.mode = mode; + if (!t.open(argv[1], err, io)) { std::fprintf(stderr, "open: %s\n", err.c_str()); return 1; } + std::vector got((size_t) n * k::PLE_HEAD_DIM); + for (int i = 0; i < n; ++i) t.read_row(rows[(size_t) i], got.data() + (size_t) i * k::PLE_HEAD_DIM); + int diff = 0; + for (size_t j = 0; j < got.size(); ++j) diff += std::memcmp(&got[j], &ref[j], 4) != 0; + std::vector batch((size_t) n * k::PLE_HEAD_DIM); // the prompt path: all rows as one request + const bool ok = t.gather_batch(rows.data(), (size_t) n / k::PLE_N_HEADS, batch.data(), err); + int bdiff = 0; + const size_t nb = (size_t) n / k::PLE_N_HEADS * k::PLE_N_HEADS * k::PLE_HEAD_DIM; + for (size_t j = 0; ok && j < nb; ++j) bdiff += std::memcmp(&batch[j], &ref[j], 4) != 0; + std::printf("%-6s %s, %llu rows: read_row %d/%zu values differ, gather_batch %s %d differ\n", + mode == k::PleIo::Direct ? "Direct" : "Mmap", t.format(), (unsigned long long) t.rows(), diff, + got.size(), ok ? "ok," : "FAILED,", bdiff); + bad += diff + bdiff + (ok ? 0 : 1) + (std::strcmp(t.format(), "F8_E4M3") != 0); + } + if (argc > 3) { + k::PleTable q; + std::string err; + if (!q.open(argv[3], err)) { std::fprintf(stderr, "open %s: %s\n", argv[3], err.c_str()); return 1; } + double cmin = 1, rsum = 0; + int counted = 0; + std::vector v(k::PLE_HEAD_DIM); + for (int i = 0; i < n; ++i) { + q.read_row(rows[(size_t) i], v.data()); + const float* r = ref.data() + (size_t) i * k::PLE_HEAD_DIM; + double sa = 0, sb = 0, sab = 0, sa2 = 0, sb2 = 0, e2 = 0, r2 = 0; + for (int j = 0; j < k::PLE_HEAD_DIM; ++j) { + sa += r[j]; sb += v[j]; sab += (double) r[j] * v[j]; sa2 += (double) r[j] * r[j]; sb2 += (double) v[j] * v[j]; + e2 += ((double) v[j] - r[j]) * ((double) v[j] - r[j]); r2 += (double) r[j] * r[j]; + } + if (r2 == 0) continue; // an all-zero row (the table has some) + const double m = k::PLE_HEAD_DIM; + const double c = (sab - sa * sb / m) / std::sqrt((sa2 - sa * sa / m) * (sb2 - sb * sb / m)); + cmin = std::fmin(cmin, c); + rsum += std::sqrt(e2 / r2); + ++counted; + } + std::printf("IQ4_NL table, same rows: correlation min %.4f, error vs FP8 %.1f%% mean (%d non-zero rows)\n", + cmin, 100 * rsum / (counted ? counted : 1), counted); + if (cmin < 0.98) ++bad; + } + std::printf("RESULT: %s\n", bad ? "MISMATCH" : "FP8 rows exact"); + return bad ? 1 : 0; +} diff --git a/src/ngram/ple_reader.cpp b/src/ngram/ple_reader.cpp index e7a3101f..a03e4c04 100644 --- a/src/ngram/ple_reader.cpp +++ b/src/ngram/ple_reader.cpp @@ -34,15 +34,17 @@ constexpr uint32_t EMPTY = 0xFFFFFFFFu; /// Set-associative row cache: 8 ways per set, round-robin replacement inside a set. Bounded by construction. struct RowCache { uint64_t sets = 0; + uint32_t rb = ROW_BYTES; // bytes per row std::vector keys; // sets * WAYS - std::vector data; // sets * WAYS * ROW_BYTES + std::vector data; // sets * WAYS * rb std::vector next; // per-set replacement pointer uint64_t used = 0; - void init(uint64_t rows) { + void init(uint64_t rows, uint32_t row_bytes = ROW_BYTES) { sets = rows / WAYS; + rb = row_bytes; keys.assign(sets * WAYS, EMPTY); - data.assign(sets * WAYS * ROW_BYTES, 0); + data.assign(sets * WAYS * rb, 0); next.assign(sets, 0); used = 0; } @@ -54,7 +56,7 @@ struct RowCache { if (sets == 0) return nullptr; const uint64_t s = mix(row) % sets; for (uint32_t w = 0; w < WAYS; ++w) - if (keys[s * WAYS + w] == row) return &data[(s * WAYS + w) * ROW_BYTES]; + if (keys[s * WAYS + w] == row) return &data[(s * WAYS + w) * rb]; return nullptr; } void insert(uint32_t row, const uint8_t* bytes) { @@ -64,7 +66,7 @@ struct RowCache { next[s] = (uint8_t) ((w + 1) % WAYS); if (keys[s * WAYS + w] == EMPTY) ++used; keys[s * WAYS + w] = row; - std::memcpy(&data[(s * WAYS + w) * ROW_BYTES], bytes, ROW_BYTES); + std::memcpy(&data[(s * WAYS + w) * rb], bytes, rb); } }; @@ -97,6 +99,7 @@ struct PleReader::Impl { DirectFile file; uint64_t table_offset = 0; uint64_t n_rows = 0; + uint32_t row_bytes = ROW_BYTES; uint32_t max_inflight = 0; uint8_t* slab = nullptr; // max_inflight slots of 2 pages std::vector free_slots; @@ -185,7 +188,7 @@ struct PleReader::Impl { rng ^= rng << 13; rng ^= rng >> 7; rng ^= rng << 17; - const uint64_t first = table_offset / PAGE, end = (table_offset + n_rows * (uint64_t) ROW_BYTES) / PAGE; + const uint64_t first = table_offset / PAGE, end = (table_offset + n_rows * (uint64_t) row_bytes) / PAGE; Job j; j.offset = (first + (end > first ? rng % (end - first) : 0)) * PAGE; j.length = PAGE; @@ -225,7 +228,7 @@ struct PleReader::Impl { stats.bytes += c.bytes; const uint8_t* buf = slot_buf(s); for (const Use& u : j.uses) { - if (u.in_page + ROW_BYTES > c.bytes) { + if (u.in_page + row_bytes > c.bytes) { error = "PleReader: short read inside the table"; cancel_queued(); j.uses.clear(); @@ -236,7 +239,7 @@ struct PleReader::Impl { } } for (const Use& u : j.uses) { - std::memcpy(u.dst, buf + u.in_page, ROW_BYTES); + std::memcpy(u.dst, buf + u.in_page, row_bytes); cache.insert(u.row, buf + u.in_page); } auto it = tickets.find(j.ticket); @@ -330,11 +333,13 @@ PleReader::~PleReader() { } bool PleReader::open(const std::string& path, uint64_t table_offset, uint64_t n_rows, uint32_t max_inflight, - uint64_t cache_rows, std::string& err, bool io_thread) { + uint64_t cache_rows, std::string& err, bool io_thread, uint32_t row_bytes) { close(); if (max_inflight == 0 || max_inflight > 1024) { err = "PleReader: max_inflight must be 1..1024"; return false; } + if (row_bytes == 0 || row_bytes > PAGE) { err = "PleReader: row_bytes must be 1..4096"; return false; } if (!impl_->file.open(path, err)) return false; - if (table_offset + n_rows * (uint64_t) ROW_BYTES > impl_->file.size()) { + impl_->row_bytes = row_bytes; + if (table_offset + n_rows * (uint64_t) row_bytes > impl_->file.size()) { err = "PleReader: the table extends past the end of " + path; close(); return false; @@ -347,7 +352,7 @@ bool PleReader::open(const std::string& path, uint64_t table_offset, uint64_t n_ impl_->inflight.assign(max_inflight, Job{}); impl_->free_slots.clear(); for (uint32_t s = max_inflight; s-- > 0;) impl_->free_slots.push_back(s); - impl_->cache.init(cache_rows); + impl_->cache.init(cache_rows, row_bytes); impl_->error.clear(); impl_->keep_us = 0; impl_->last_issue_us = impl_->last_read_us = 0; @@ -411,6 +416,7 @@ void PleReader::close() { } bool PleReader::is_open() const { return impl_->file.is_open(); } +uint32_t PleReader::row_bytes() const { return impl_->row_bytes; } PleReader::Ticket PleReader::issue(const uint32_t* rows, size_t n, uint8_t* out_raw) { Impl& m = *impl_; @@ -425,20 +431,21 @@ PleReader::Ticket PleReader::issue(const uint32_t* rows, size_t n, uint8_t* out_ std::unordered_map by_page; // aligned offset -> index in `jobs` std::vector jobs; for (size_t i = 0; i < n; ++i) { - uint8_t* dst = out_raw + i * ROW_BYTES; + const uint32_t rb = m.row_bytes; + uint8_t* dst = out_raw + i * rb; ++m.stats.requests; if (rows[i] >= m.n_rows) { - std::memset(dst, 0, ROW_BYTES); + std::memset(dst, 0, rb); continue; } if (const uint8_t* hit = m.cache.find(rows[i])) { - std::memcpy(dst, hit, ROW_BYTES); + std::memcpy(dst, hit, rb); ++m.stats.cache_hits; continue; } - const uint64_t at = m.table_offset + (uint64_t) rows[i] * ROW_BYTES; + const uint64_t at = m.table_offset + (uint64_t) rows[i] * rb; const uint64_t first = at / PAGE * PAGE; - const uint32_t length = (uint32_t) ((at + ROW_BYTES - 1) / PAGE * PAGE - first + PAGE); + const uint32_t length = (uint32_t) ((at + rb - 1) / PAGE * PAGE - first + PAGE); auto f = by_page.find(first); if (f != by_page.end()) { Job& j = jobs[f->second]; diff --git a/src/program/generate.cpp b/src/program/generate.cpp index cdf6e04d..d36942f5 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -1468,7 +1468,14 @@ int main(int argc, char** argv) { // every shard of the model (-0000N-of-0000M.gguf beside --native), then the PLE shard: a split // may put any layer in any shard (Swift's GGUFs: layers 13-47 in shard 2, the PLE table in shard 1) o.native_dense_gguf = o.native_shards; - if (std::find(o.native_dense_gguf.begin(), o.native_dense_gguf.end(), o.ple_gguf) == o.native_dense_gguf.end()) + // a PLE-only table (tools/ple_fp8_pack.py: architecture strata-ple) holds no projections + bool ple_only = false; + try { + strata::GgufFile pg(o.ple_gguf); + if (const strata::MetaValue* v = pg.get("general.architecture")) ple_only = v->s == "strata-ple"; + } catch (const std::exception&) {} + if (!ple_only && + std::find(o.native_dense_gguf.begin(), o.native_dense_gguf.end(), o.ple_gguf) == o.native_dense_gguf.end()) o.native_dense_gguf.push_back(o.ple_gguf); } // Plan v0.3 (24 Sep): the CPU experts stay on the VNNI kernel. The llama.cpp-CPU-exact q8_0 contract diff --git a/tools/ple_fp8_pack.py b/tools/ple_fp8_pack.py new file mode 100644 index 00000000..63132731 --- /dev/null +++ b/tools/ple_fp8_pack.py @@ -0,0 +1,123 @@ +"""tools/ple_fp8_pack.py - the PLE n-gram table exactly as Qwen shipped it (FP8 E4M3), as a GGUF the engine reads. + + python tools/ple_fp8_pack.py --model --out + +Qwen3.8-Flash-Next's checkpoint stores the table as 128 shards `...ngram_embedding.shard_{k}.weight` of +[2500012, 160] F8_E4M3 with one BF16 `weight_scale`: 320,001,536 rows of 160 values, 51.2 GB. The engine used to take +it from ISTA-DASLab's GGUF as IQ4_NL (90 B/row), which is 8% off these values per row; this keeps them bit for bit. + +The output is a one-tensor GGUF: `per_layer_token_embd.weight`, ne = [160, 320001536], type I8 holding the FP8 bytes +(GGUF has no FP8 type), with `strata.ple.format` = "f8_e4m3" and `strata.ple.scale` (F32). The bytes are copied +straight out of the safetensors files in shard order - nothing is decoded or rounded - so memory stays flat. +""" +import argparse +import json +import pathlib +import struct +import sys + +GGUF_TYPE_STRING, GGUF_TYPE_F32 = 8, 6 +GGML_TYPE_I8 = 24 +ALIGN = 32 +CHUNK = 64 << 20 + + +def safetensors_header(path): + with open(path, "rb") as f: + n = struct.unpack(" Date: Thu, 1 Oct 2026 09:33:22 +0200 Subject: [PATCH 45/48] #296 follow-up: only the Q5_0 MMQ instance and case stay (Q4_K / Q5_1 come with S5's STRATA_MMQ_KQUANTS) S5's branch (f-132-q4) compiles the Q4_K, Q5_K and Q5_1 MMQ instances on CUDA and enables them with the private define STRATA_MMQ_KQUANTS; with both, moe_mmq.cu would have duplicate case labels. STRATA_ORCA_Q4KS_MMQ now adds only q5_0 (OrcaRouter's Q5_0 expert downs; HIP included) - supported() and run() take Q5_0 under it. --- CMakeLists.txt | 5 +++-- docs/ORCA_Q4_K_S.md | 2 +- src/prefill/moe_mmq.cu | 4 +--- 3 files changed, 5 insertions(+), 6 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 07c2f0f3..cdfaca57 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -35,7 +35,7 @@ endif() option(STRATA_ENABLE_CUDA "Build the CUDA targets (Phase 2+)" OFF) option(STRATA_ENABLE_HIP "Build the HIP targets for wave32 AMD GPUs (gfx1100, gfx1201)" OFF) option(STRATA_PREFILL_MMQ "Build the optional GGML MMQ prefill path for HIP" OFF) -option(STRATA_ORCA_Q4KS_MMQ "Build extra GGML MMQ instances for OrcaRouter Q4_K_S" OFF) +option(STRATA_ORCA_Q4KS_MMQ "Build the GGML Q5_0 MMQ instance for OrcaRouter Q4_K_S" OFF) if(STRATA_PREFILL_MMQ AND NOT STRATA_ENABLE_HIP) message(FATAL_ERROR "STRATA_PREFILL_MMQ requires STRATA_ENABLE_HIP=ON") endif() @@ -811,8 +811,9 @@ if(STRATA_NATIVE_EXPERTS) target_link_libraries(strata_kernels_cpu PUBLIC ggml-cpu ggml-base) target_compile_definitions(strata_kernels_cpu PUBLIC STRATA_NATIVE_EXPERTS=1) set(_strata_mmq_types q2_0 iq2_xxs iq2_xs iq2_s iq3_xxs iq3_s iq4_nl iq4_xs q8_0) + # #296: OrcaRouter Q4_K_S's Q5_0 experts (Q4_K and Q5_1 come with STRATA_MMQ_KQUANTS on CUDA, S5's branch) if(STRATA_ORCA_Q4KS_MMQ) - list(APPEND _strata_mmq_types q4_k q5_0 q5_1) + list(APPEND _strata_mmq_types q5_0) endif() if(STRATA_ENABLE_CUDA) # prompt-speed plan step 2b: llama.cpp's MMQ kernels (ggml-cuda, MIT) for the prompt path's experts, compiled diff --git a/docs/ORCA_Q4_K_S.md b/docs/ORCA_Q4_K_S.md index 78b11358..25815ff1 100644 --- a/docs/ORCA_Q4_K_S.md +++ b/docs/ORCA_Q4_K_S.md @@ -6,7 +6,7 @@ The ordinary GGUF quantizes some small projections which Strata reads as BF16. ` ## Build and prepare -Build Strata with CUDA, native experts, `STRATA_ORCA_Q4KS_MMQ=ON` (and `STRATA_BUILD_TESTS=ON` for the two parity programs below). This opt-in compiles the Q4_K, Q5_0 and Q5_1 GGML MMQ instances for CUDA or HIP; the usual Q8_0 draft-layer instance remains in both builds. HIP also needs `STRATA_PREFILL_MMQ=ON`. Select your card's compute capability, for example `89` on an L40S. On Windows with Ninja and CUDA 12.6, use the Visual Studio developer environment and `-DCMAKE_CUDA_RUNTIME_LIBRARY=Shared` to keep the CUDA runtime linkage consistent. The default pinned ggml checkout is supported by the project build. +Build Strata with CUDA, native experts, `STRATA_ORCA_Q4KS_MMQ=ON` (and `STRATA_BUILD_TESTS=ON` for the two parity programs below). This opt-in compiles the Q5_0 GGML MMQ instance for CUDA or HIP (the Q4_K and Q5_1 instances come with the engine's K-quant MMQ build on CUDA); the usual Q8_0 draft-layer instance remains in both builds. HIP also needs `STRATA_PREFILL_MMQ=ON`. Select your card's compute capability, for example `89` on an L40S. On Windows with Ninja and CUDA 12.6, use the Visual Studio developer environment and `-DCMAKE_CUDA_RUNTIME_LIBRARY=Shared` to keep the CUDA runtime linkage consistent. The default pinned ggml checkout is supported by the project build. ```sh cmake -S . -B build -G Ninja -DSTRATA_ENABLE_CUDA=ON -DSTRATA_NATIVE_EXPERTS=ON -DSTRATA_ORCA_Q4KS_MMQ=ON -DCMAKE_CUDA_ARCHITECTURES=89 -DCMAKE_CUDA_RUNTIME_LIBRARY=Shared -DCMAKE_BUILD_TYPE=Release diff --git a/src/prefill/moe_mmq.cu b/src/prefill/moe_mmq.cu index 35aa5354..f78fdb10 100644 --- a/src/prefill/moe_mmq.cu +++ b/src/prefill/moe_mmq.cu @@ -93,7 +93,7 @@ bool supported(int t) { switch ((ggml_type) t) { case GGML_TYPE_Q2_0: #ifdef STRATA_ORCA_Q4KS_MMQ - case GGML_TYPE_Q4_K: case GGML_TYPE_Q5_0: case GGML_TYPE_Q5_1: + case GGML_TYPE_Q5_0: // #296 (Q4_K and Q5_1: STRATA_MMQ_KQUANTS) #endif case GGML_TYPE_IQ2_XXS: case GGML_TYPE_IQ2_XS: case GGML_TYPE_IQ2_S: case GGML_TYPE_IQ3_XXS: case GGML_TYPE_IQ3_S: case GGML_TYPE_IQ4_NL: case GGML_TYPE_IQ4_XS: @@ -139,9 +139,7 @@ void Context::run(const Product& p, void* stream) { const cudaStream_t s = (cudaStream_t) stream; switch (t) { #ifdef STRATA_ORCA_Q4KS_MMQ - case GGML_TYPE_Q4_K: mul_mat_q_case(ctx, a, s); break; case GGML_TYPE_Q5_0: mul_mat_q_case(ctx, a, s); break; - case GGML_TYPE_Q5_1: mul_mat_q_case(ctx, a, s); break; #endif case GGML_TYPE_Q2_0: mul_mat_q_case(ctx, a, s); break; case GGML_TYPE_IQ2_XXS: mul_mat_q_case(ctx, a, s); break; From 560e4788a1ef8c1e81cc1aa65bd8cd793dbe0aa8 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Thu, 1 Oct 2026 11:06:21 +0200 Subject: [PATCH 46/48] #290 follow-up: --bf16-embd's output buffer holds the 97 gathered rows, not only the 61-row table The gather wrote 97 rows into a 61-row device buffer (and read them back into a 61-row vector); the next launch reported the overrun as "iq_dequant_f32: invalid argument". The buffer is max(gathered, table) rows now. --- src/kernels/native_expert_parity.cpp | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/kernels/native_expert_parity.cpp b/src/kernels/native_expert_parity.cpp index 153df365..14232103 100644 --- a/src/kernels/native_expert_parity.cpp +++ b/src/kernels/native_expert_parity.cpp @@ -490,11 +490,12 @@ int check_bf16_embd(cudaStream_t s) { float* dout = nullptr; cudaMalloc(&dt, table.size() * 2); cudaMalloc((void**) &dtok, tok.size() * 4); - cudaMalloc((void**) &dout, (size_t) (V * H) * 4); + const int64_t out_rows = NT > V ? NT : V; // the gathered rows (NT) and the whole table (V) share the buffer + cudaMalloc((void**) &dout, (size_t) (out_rows * H) * 4); cudaMemcpy(dt, table.data(), table.size() * 2, cudaMemcpyHostToDevice); cudaMemcpy(dtok, tok.data(), tok.size() * 4, cudaMemcpyHostToDevice); auto widen = [](uint16_t b) { const uint32_t u = (uint32_t) b << 16; float f; std::memcpy(&f, &u, 4); return f; }; - std::vector got((size_t) (V * H)); + std::vector got((size_t) (out_rows * H)); strata::kernels::iq_embed_rows(kBf16, dt, (size_t) H * 2, dtok, NT, H, dout, s); cudaStreamSynchronize(s); cudaMemcpy(got.data(), dout, (size_t) (NT * H) * 4, cudaMemcpyDeviceToHost); @@ -506,7 +507,7 @@ int check_bf16_embd(cudaStream_t s) { } strata::kernels::iq_dequant_f32(kBf16, dt, V * H, dout, s); cudaStreamSynchronize(s); - cudaMemcpy(got.data(), dout, got.size() * 4, cudaMemcpyDeviceToHost); + cudaMemcpy(got.data(), dout, table.size() * 4, cudaMemcpyDeviceToHost); size_t values_differ = 0; for (size_t i = 0; i < table.size(); ++i) { const float want = widen(table[i]); From e12ecf6ac87cda5b97f785e7b8ddc198f99eed4f Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Thu, 1 Oct 2026 14:34:20 +0200 Subject: [PATCH 47/48] #280 follow-up: the rope kernels without the table are 0.1.31's code exactly (template ) With STRATA_ROPE_TABLE unset the table was skipped at run time, yet the compiled default kernels changed their results: the model-level parity run (Swift IQ2_XS, tools/conversation_cache_parity.py, STRATA_STATE_HASH) gave the same tokens but other GDN / indexer / K/V state hashes than 0.1.31's (bisected to #280). native_rope's apply, the indexer's append / append_first / append_blocks and the prompt path's rope_kernel are templates on TAB now; the host launches whenever no table applies, and that instantiation has no table read at all. Checked: the same tokens and every state hash as round 1 with the whole branch. --- src/kernels/cuda/native_qsa_indexer.cu | 47 +++++++++++++++++++------- src/kernels/cuda/native_rope.cu | 18 +++++++--- src/prefill/kernels.cu | 19 ++++++++--- 3 files changed, 62 insertions(+), 22 deletions(-) diff --git a/src/kernels/cuda/native_qsa_indexer.cu b/src/kernels/cuda/native_qsa_indexer.cu index b91fdbd5..8147c709 100644 --- a/src/kernels/cuda/native_qsa_indexer.cu +++ b/src/kernels/cuda/native_qsa_indexer.cu @@ -39,6 +39,10 @@ __device__ float warp_sum(float x) { x += __shfl_xor_sync(0xffffffffu, x, offset); return x; } +// TAB (#280, STRATA_ROPE_TABLE=1): the angles from the session's float64 table. The host launches whenever +// no table applies - the default - so the default kernel is 0.1.31's code exactly (the table read is not in it; +// with it merely skipped at run time, the compiled default path changed its results). +template __global__ void append(const float* __restrict__ raw, const int32_t* __restrict__ pos_dev, int pos_base, const float* __restrict__ gamma, float epsilon, float* __restrict__ tail, float* __restrict__ dead, @@ -88,7 +92,7 @@ __global__ void append(const float* __restrict__ raw, const int32_t* __restrict_ // The spare (pos == 0) keeps its zero angle; under YaRN the mscale magnitude still rides in // through cos(0) - which is exactly what the queries are scaled by, so the top-k is unmoved. float c, s; - if (!rope_tab_cs(rt, pos == 0 ? 0 : mrope_pos(mtab, rope_pos, pair), pair, c, s)) { + if (!(TAB && rope_tab_cs(rt, pos == 0 ? 0 : mrope_pos(mtab, rope_pos, pair), pair, c, s))) { const float theta_extrap = (pos == 0 ? 0 : mrope_pos(mtab, rope_pos, pair)) * powf(theta_scale, float(pair)); rope_scaled_angle(theta_extrap, freq_scale, corr_low, corr_high, ext_factor, mscale, pair, c, s); } @@ -105,6 +109,7 @@ __global__ void append(const float* __restrict__ raw, const int32_t* __restrict_ // the RMS norm, gamma, the rotation at pos_base + 4b. `k(j)` is the key of the block's cell j: a row of this batch // (cell >= p0) or the tail the previous batch left (cell < p0). Only the batch's last completed block writes the // spare after it (every earlier one's is overwritten by the next block in order). +template __device__ __forceinline__ float pooled_value(const float* values, int d, int rope_pos, float theta_scale, float freq_scale, float corr_low, float corr_high, float ext_factor, float mscale, const int32_t* mtab, bool zero_pos, @@ -116,7 +121,7 @@ __device__ __forceinline__ float pooled_value(const float* values, int d, int ro // today's cosf/sinf; under linear/YaRN the pooled keys move with the cache's K, and the spare's zero // angle carries the mscale magnitude through cos(0) exactly as the single append's does. float c, s; - if (!rope_tab_cs(rt, zero_pos ? 0 : mrope_pos(mtab, rope_pos, pair), pair, c, s)) { + if (!(TAB && rope_tab_cs(rt, zero_pos ? 0 : mrope_pos(mtab, rope_pos, pair), pair, c, s))) { const float theta_extrap = (zero_pos ? 0 : mrope_pos(mtab, rope_pos, pair)) * powf(theta_scale, float(pair)); rope_scaled_angle(theta_extrap, freq_scale, corr_low, corr_high, ext_factor, mscale, pair, c, s); } @@ -136,6 +141,7 @@ __device__ __forceinline__ float norm_scale(float mean, float* partials, int d) return square_sum; } // cell 0 of a sequence: the spare (every gather index names cell 0), written to pooled[0] and dead +template __global__ void append_first(const float* __restrict__ raw, const float* __restrict__ gamma, float epsilon, float* __restrict__ dead, float* __restrict__ pooled, float theta_scale, float freq_scale, float corr_low, float corr_high, float ext_factor, float mscale, @@ -156,11 +162,12 @@ __global__ void append_first(const float* __restrict__ raw, const float* __restr if (d < D) values[d] = scale * mean * gamma[d]; __syncthreads(); if (d >= D) return; - const float y = pooled_value(values, d, 0, theta_scale, freq_scale, corr_low, corr_high, ext_factor, mscale, + const float y = pooled_value(values, d, 0, theta_scale, freq_scale, corr_low, corr_high, ext_factor, mscale, mtab, true, rt); pooled[d] = y; dead[d] = y; } +template __global__ void append_blocks(const float* __restrict__ raw, int64_t n, int64_t p0, int pos_base, const float* __restrict__ gamma, float epsilon, const float* __restrict__ tail, const float* __restrict__ dead, float* __restrict__ pooled, int32_t* __restrict__ block_pos, @@ -188,7 +195,7 @@ __global__ void append_blocks(const float* __restrict__ raw, int64_t n, int64_t __syncthreads(); if (d >= D) return; const int rope_pos = pos_base + R * (int) b; - pooled[std::size_t(b) * D + d] = pooled_value(values, d, rope_pos, theta_scale, freq_scale, corr_low, corr_high, + pooled[std::size_t(b) * D + d] = pooled_value(values, d, rope_pos, theta_scale, freq_scale, corr_low, corr_high, ext_factor, mscale, mtab, false, rt); if (b == last_block) { pooled[std::size_t(b + 1) * D + d] = dead[d]; @@ -233,9 +240,15 @@ void native_qsa_indexer_append(const float* raw, const int32_t* relative_pos_dev if (overlaps(spans[i], spans[j])) throw std::invalid_argument("native QSA indexer buffers overlap"); const float theta_scale = powf((float) scaling.freq_base, -2.0f / ROT); const RopeKernelArgs k = scaling.kernel_args(ROT); // none: the identity constants - append<<<1,THREADS,0,static_cast(stream)>>>(raw,relative_pos_device,pos_base,gamma,epsilon, - b.tail,b.dead,b.pooled,b.block_pos,int(max_cells),theta_scale,k.freq_scale, - k.corr_low,k.corr_high,k.ext_factor,k.attn_factor,mrope_table(),rope_table_for(scaling)); + const RopeTab rt = rope_table_for(scaling); + if (rt.cos != nullptr) + append<<<1,THREADS,0,static_cast(stream)>>>(raw,relative_pos_device,pos_base,gamma,epsilon, + b.tail,b.dead,b.pooled,b.block_pos,int(max_cells),theta_scale,k.freq_scale, + k.corr_low,k.corr_high,k.ext_factor,k.attn_factor,mrope_table(),rt); + else + append<<<1,THREADS,0,static_cast(stream)>>>(raw,relative_pos_device,pos_base,gamma,epsilon, + b.tail,b.dead,b.pooled,b.block_pos,int(max_cells),theta_scale,k.freq_scale, + k.corr_low,k.corr_high,k.ext_factor,k.attn_factor,mrope_table(),rt); const auto error = cudaGetLastError(); if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error)); } @@ -253,15 +266,23 @@ void native_qsa_indexer_append_batch(const float* raw, int64_t n, int64_t p0, in const cudaStream_t st = static_cast(stream); const int32_t* mtab = mrope_table(); const RopeTab rt = rope_table_for(scaling); - if (p0 == 0) append_first<<<1, THREADS, 0, st>>>(raw, gamma, epsilon, b.dead, b.pooled, theta_scale, - fsf, cl, ch, ef, ms, mtab, rt); + if (p0 == 0) { + if (rt.cos != nullptr) + append_first<<<1, THREADS, 0, st>>>(raw, gamma, epsilon, b.dead, b.pooled, theta_scale, + fsf, cl, ch, ef, ms, mtab, rt); + else + append_first<<<1, THREADS, 0, st>>>(raw, gamma, epsilon, b.dead, b.pooled, theta_scale, + fsf, cl, ch, ef, ms, mtab, rt); + } // completed blocks: those whose last cell (4b+3) lies in [p0, p0 + n) const int64_t first = p0 <= R - 1 ? 0 : (p0 - (R - 1) + R - 1) / R; // the smallest b with 4b+3 >= p0 const int64_t hi = p0 + n - 1 >= R - 1 ? (p0 + n - 1 - (R - 1)) / R : -1; // the largest b with 4b+3 <= p0+n-1 - if (hi >= first) - append_blocks<<<(unsigned) (hi - first + 1), THREADS, 0, st>>>(raw, n, p0, pos_base, gamma, epsilon, b.tail, - b.dead, b.pooled, b.block_pos, first, hi, - theta_scale, fsf, cl, ch, ef, ms, mtab, rt); + if (hi >= first && rt.cos != nullptr) + append_blocks<<<(unsigned) (hi - first + 1), THREADS, 0, st>>>(raw, n, p0, pos_base, gamma, epsilon, + b.tail, b.dead, b.pooled, b.block_pos, first, hi, theta_scale, fsf, cl, ch, ef, ms, mtab, rt); + else if (hi >= first) + append_blocks<<<(unsigned) (hi - first + 1), THREADS, 0, st>>>(raw, n, p0, pos_base, gamma, epsilon, + b.tail, b.dead, b.pooled, b.block_pos, first, hi, theta_scale, fsf, cl, ch, ef, ms, mtab, rt); append_tail<<>>(raw, n, p0, b.tail); const auto error = cudaGetLastError(); if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error)); diff --git a/src/kernels/cuda/native_rope.cu b/src/kernels/cuda/native_rope.cu index b34f4e67..57cbe79f 100644 --- a/src/kernels/cuda/native_rope.cu +++ b/src/kernels/cuda/native_rope.cu @@ -39,6 +39,10 @@ bool overlaps(const void* a, size_t an, const void* b, size_t bn) { auto x = reinterpret_cast(a), y = reinterpret_cast(b); return x <= y ? y - x < an : x - y < bn; } +// TAB (#280, STRATA_ROPE_TABLE=1): the angles from the session's float64 table. The host launches whenever +// no table applies - the default - so the default kernel is 0.1.31's code exactly (the table read is not in it; +// with it merely skipped at run time, the compiled default path changed its results). +template __global__ void apply(const float* x, float* out, int rows, int width, int n_rot, float theta_scale, float freq_scale, float corr_low, float corr_high, float ext_factor, float mscale, const int* positions, const int32_t* mtab, RopeTab rt) { @@ -54,7 +58,7 @@ __global__ void apply(const float* x, float* out, int rows, int width, return; } float c, s; - if (!rope_tab_cs(rt, mrope_pos(mtab, positions[row], pair), pair, c, s)) { + if (!(TAB && rope_tab_cs(rt, mrope_pos(mtab, positions[row], pair), pair, c, s))) { const float theta_extrap = mrope_pos(mtab, positions[row], pair) * powf(theta_scale, float(pair)); rope_scaled_angle(theta_extrap, freq_scale, corr_low, corr_high, ext_factor, mscale, pair, c, s); } @@ -129,10 +133,14 @@ void native_rope_apply(const float* x, float* out, int rows, int head_dim, // Match pinned host-side float powf before device fast powf/trigonometry. const float theta_scale = powf((float) scaling.freq_base, -2.0f / n_rot); const RopeKernelArgs k = scaling.kernel_args(n_rot); // none: the identity constants - apply<<(stream)>>>(x, out, rows, head_dim, n_rot, theta_scale, - k.freq_scale, k.corr_low, k.corr_high, k.ext_factor, - k.attn_factor, positions, mrope_table(), rope_table_for(scaling)); + const RopeTab rt = rope_table_for(scaling); + const dim3 grid((head_dim / 2 + 127) / 128, rows); + if (rt.cos != nullptr) + apply<<(stream)>>>(x, out, rows, head_dim, n_rot, theta_scale, + k.freq_scale, k.corr_low, k.corr_high, k.ext_factor, k.attn_factor, positions, mrope_table(), rt); + else + apply<<(stream)>>>(x, out, rows, head_dim, n_rot, theta_scale, + k.freq_scale, k.corr_low, k.corr_high, k.ext_factor, k.attn_factor, positions, mrope_table(), rt); const auto error = cudaGetLastError(); if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error)); } diff --git a/src/prefill/kernels.cu b/src/prefill/kernels.cu index 0035833b..de833442 100644 --- a/src/prefill/kernels.cu +++ b/src/prefill/kernels.cu @@ -559,6 +559,10 @@ __global__ void rms_rows_kernel(float* __restrict__ x, const float* __restrict__ __syncthreads(); for (int64_t c = threadIdx.x; c < cols; c += blockDim.x) r[c] = s * r[c] * w[c]; } +// TAB (#280, STRATA_ROPE_TABLE=1): the angles from the session's float64 table. The host launches whenever +// no table applies - the default - so the default kernel is 0.1.31's code exactly (the table read is not in it; +// with it merely skipped at run time, the compiled default path changed its results). +template __global__ void rope_kernel(float* __restrict__ x, int64_t heads, int64_t dim, int64_t ld, int64_t pos0, float theta_scale, float freq_scale, float corr_low, float corr_high, float ext_factor, float mscale, const int32_t* __restrict__ mtab, @@ -568,7 +572,8 @@ __global__ void rope_kernel(float* __restrict__ x, int64_t heads, int64_t dim, i const int64_t t = row / heads, h = row % heads; float* p = x + t * ld + h * dim; float c, s; - if (!strata::kernels::rope_tab_cs(rt, strata::kernels::mrope_pos(mtab, (int) (pos0 + t), pair), pair, c, s)) { + if (!(TAB && strata::kernels::rope_tab_cs(rt, strata::kernels::mrope_pos(mtab, (int) (pos0 + t), pair), pair, c, + s))) { const float theta_extrap = (float) strata::kernels::mrope_pos(mtab, (int) (pos0 + t), pair) * powf(theta_scale, (float) pair); strata::kernels::rope_scaled_angle(theta_extrap, freq_scale, corr_low, corr_high, ext_factor, mscale, @@ -814,9 +819,15 @@ void rope(float* x, int64_t T, int64_t heads, int64_t dim, int64_t ld, int64_t p } const float theta_scale = powf((float) scaling.freq_base, -2.0f / 64.0f); const strata::kernels::RopeKernelArgs k = scaling.kernel_args(64); // none: the identity constants - rope_kernel<<<(unsigned) (T * heads), 32, 0, (cudaStream_t) stream>>>( - x, heads, dim, ld, pos0, theta_scale, k.freq_scale, k.corr_low, k.corr_high, k.ext_factor, k.attn_factor, - strata::kernels::mrope_table(), strata::kernels::rope_table_for(scaling)); + const strata::kernels::RopeTab rt = strata::kernels::rope_table_for(scaling); + if (rt.cos != nullptr) + rope_kernel<<<(unsigned) (T * heads), 32, 0, (cudaStream_t) stream>>>( + x, heads, dim, ld, pos0, theta_scale, k.freq_scale, k.corr_low, k.corr_high, k.ext_factor, k.attn_factor, + strata::kernels::mrope_table(), rt); + else + rope_kernel<<<(unsigned) (T * heads), 32, 0, (cudaStream_t) stream>>>( + x, heads, dim, ld, pos0, theta_scale, k.freq_scale, k.corr_low, k.corr_high, k.ext_factor, k.attn_factor, + strata::kernels::mrope_table(), rt); check("rope"); } void split_q(const float* q_full, float* q, int64_t T, void* stream) { From 3b7162131db5ab0cd41de21cbc9d723bb1ff27fa Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Thu, 1 Oct 2026 14:42:53 +0200 Subject: [PATCH 48/48] #278 follow-up: an Anthropic request that doesn't ask for thinking renders without it only with "anthropic_thinking": "on_request" in the config - the default thinks as 0.1.31 did (a client that never asks would otherwise lose the thinking on every turn); docs --- docs/DETAILS.md | 4 ++++ serve/frontend.py | 12 ++++++++---- serve/server.py | 9 +++++++-- serve/test_server.py | 4 +++- 4 files changed, 22 insertions(+), 7 deletions(-) diff --git a/docs/DETAILS.md b/docs/DETAILS.md index c58be4d3..e82de2f8 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -424,6 +424,10 @@ print(r.choices[0].message.content) part of the thinking the client sees and counts as output tokens. `"reasoning_budget_tokens": N` in `strata-.json` sets it for every request; a request's own value wins, and `0` means no budget. Off by default; Anthropic's `"thinking": {"budget_tokens": N}` still only chooses the level, as above. +- **Anthropic requests that don't ask for thinking (opt-in, 0.1.32, #278).** By default a `/v1/messages` request + with no `"thinking"`, effort or budget thinks as the model's template does. `"anthropic_thinking": "on_request"` in + `strata-.json` renders such a request without thinking - Anthropic's own rule, and what Claude Code's short + helper calls (a session title in a few dozen tokens) need; its real turns ask for thinking when it is on there. - **Streaming.** With `"stream": true` everything arrives as it is made: the thinking, the answer, and tool calls (the tool's name first, then its arguments piece by piece, like OpenAI and Anthropic do). While the model reads a long prompt the stream sends keep-alives, so agents do not time out; the server window prints progress every diff --git a/serve/frontend.py b/serve/frontend.py index 84310811..e832be99 100644 --- a/serve/frontend.py +++ b/serve/frontend.py @@ -173,8 +173,10 @@ def openai_to_messages(req: dict) -> tuple[list[dict], list[dict] | None, dict]: return _late_system_to_user(messages), tools, kwargs -def anthropic_to_messages(req: dict) -> tuple[list[dict], list[dict] | None, dict]: - """Anthropic Messages -> (template messages, template tools, template kwargs).""" +def anthropic_to_messages(req: dict, think_unasked: bool = True) -> tuple[list[dict], list[dict] | None, dict]: + """Anthropic Messages -> (template messages, template tools, template kwargs). `think_unasked`: a request + without "thinking", an effort or a budget gets the template's default (it thinks), as through 0.1.31; False + renders it without thinking (#278, the config's "anthropic_thinking": "on_request").""" messages = [] system = req.get("system") if system: @@ -219,8 +221,10 @@ def anthropic_to_messages(req: dict) -> tuple[list[dict], list[dict] | None, dic kwargs.update(effort_kwargs(effort)) elif isinstance(thinking, dict) and thinking.get("budget_tokens"): kwargs.update(budget_effort(thinking["budget_tokens"])) - elif thinking is None and not req.get("reasoning_budget_tokens"): - # Anthropic's thinking is opt-in. Claude Code's helper calls (a session title, a topic check) ask for none + elif thinking is None and not req.get("reasoning_budget_tokens") and not think_unasked: + # Opt-in (the config's "anthropic_thinking": "on_request"; the default thinks as 0.1.31 did, since a + # client that never asks would otherwise lose the thinking on every turn). Anthropic's thinking is + # opt-in there. Claude Code's helper calls (a session title, a topic check) ask for none # and allow a few dozen tokens, which the model otherwise spent thinking and answered with no text at all. # 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. diff --git a/serve/server.py b/serve/server.py index 5b5af5b0..5bba3c0e 100644 --- a/serve/server.py +++ b/serve/server.py @@ -730,6 +730,7 @@ class Service: self.min_free_vram_mib = 0 self.before_load = None self.reasoning_budget_tokens = 0 # #123: the config's default thinking budget (0: none) + self.anthropic_think_unasked = True # #278: "anthropic_thinking": "on_request" -> False self.stop_ids = set(tokenizer.encode(IM_END, parse_special=True) + tokenizer.encode("<|endoftext|>", parse_special=True)) @@ -2063,14 +2064,14 @@ def make_handler(svc: Service): """Anthropic's token count, which Claude Code asks for its context figures: the prompt this server would read for the same request, rendered and tokenized - the model does not run.""" req = svc.with_shared(req, "anthropic") - messages, tools, kw = anthropic_to_messages(req) + messages, tools, kw = anthropic_to_messages(req, svc.anthropic_think_unasked) prompt = svc.template.render(messages, tools=tools, **kw) self._json(200, {"input_tokens": len(svc.tok.encode(prompt, parse_special=True))}) def _anthropic(self, req): svc.load() req = svc.with_shared(req, "anthropic") - messages, tools, kw = anthropic_to_messages(req) + messages, tools, kw = anthropic_to_messages(req, svc.anthropic_think_unasked) max_new = int(req.get("max_tokens") or 0) # 0/-1: the rest of the context svc.reasoning_budget(req) # a bad value is a 400 before anything is sent ids, thinking, max_new = svc.prepare(messages, tools, kw, max_new) @@ -2405,6 +2406,10 @@ def main() -> int: svc.min_free_vram_mib = a.min_free_vram_mib if a.min_free_vram_mib is not None else \ int(cfg.get("min_free_vram_mib") or 0) svc.before_load = a.before_load or cfg.get("before_load") or None + mode = str(cfg.get("anthropic_thinking") or "model") # #278: "on_request" = only when the request asks + if mode not in ("model", "on_request"): + raise SystemExit(f"[strata] config anthropic_thinking must be \"model\" or \"on_request\", not {mode!r}") + svc.anthropic_think_unasked = mode == "model" if cfg.get("reasoning_budget_tokens") is not None: # #123: a default thinking budget for every request try: svc.reasoning_budget_tokens = cfg["reasoning_budget_tokens"] diff --git a/serve/test_server.py b/serve/test_server.py index 2f364631..a05b524f 100644 --- a/serve/test_server.py +++ b/serve/test_server.py @@ -69,7 +69,9 @@ class MaxTokens(unittest.TestCase): # #278: Anthropic's thinking is opt-in; "thinking", an effort or a reasoning_budget_tokens (#123) asks for it from serve.frontend import anthropic_to_messages msgs = [{"role": "user", "content": "u"}] - kw = lambda **r: anthropic_to_messages({"messages": msgs, **r})[2] # noqa: E731 + kw = lambda **r: anthropic_to_messages({"messages": msgs, **r}, think_unasked=False)[2] # noqa: E731 + # the default ("anthropic_thinking": "model") renders an unasked request as 0.1.31 did + self.assertNotIn("enable_thinking", anthropic_to_messages({"messages": msgs})[2]) self.assertEqual(kw(), {"enable_thinking": False}) self.assertEqual(kw(thinking={"type": "disabled"}), {"enable_thinking": False}) self.assertNotIn("enable_thinking", kw(thinking={"type": "enabled", "budget_tokens": 2048}))