From f8525fa0b0521a9afe396b10ef1882493b1b758b Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Thu, 1 Oct 2026 01:11:50 +0200 Subject: [PATCH 1/5] CS-T: the partial pin at most 24 GiB (STRATA_PARTIAL_PIN_GIB), the Q4_K/Q5_1/Q8_0 multi-token kernels from two tokens on - Registering 30 GiB of a 40 GiB RAM tier left the driver unable to page-lock the prompt path's token id buffer afterwards (RTX 5070, WDDM: "prefill: the token id buffer"); the prefix is now capped at 24 GiB, the size a whole 24 GiB budget page-locks with, and STRATA_PARTIAL_PIN_GIB sets it. - A verify window's expert groups hold ~1.4 tokens on average; one token goes to ggml's own dot (the same bits, without the multi-token kernel's per-token arrays). --- src/core/expert_source.cpp | 8 +++++++- src/kernels/cpu/native_expert.cpp | 4 ++-- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/src/core/expert_source.cpp b/src/core/expert_source.cpp index e4fccea8..295d0de0 100644 --- a/src/core/expert_source.cpp +++ b/src/core/expert_source.cpp @@ -996,9 +996,15 @@ bool FileExpertSource::pin_cache_complement( const char* v = std::getenv("STRATA_PARTIAL_PIN"); // 0: the A/B arm without it return v == nullptr || std::atoi(v) != 0; }(); + // at most STRATA_PARTIAL_PIN_GIB (default 24): registering 30 GiB of a 40 GiB arena left the driver + // unable to page-lock the prompt path's small buffers afterwards (RTX 5070, WDDM) + static const uint64_t pin_cap = [] { + const char* v = std::getenv("STRATA_PARTIAL_PIN_GIB"); + return (uint64_t) ((v != nullptr && std::atof(v) > 0 ? std::atof(v) : 24.0) * 1073741824.0); + }(); if (budget_bytes > 0 && partial_on) { const uint64_t step = 2ull << 30; - for (uint64_t want = bytes; want >= step; want = want > step ? want - step : 0) { + for (uint64_t want = std::min(bytes, pin_cap); want >= step; want = want > step ? want - step : 0) { const uint64_t w = want - want % (64ull << 10); if (cudaHostRegister(arena, (size_t) w, cudaHostRegisterMapped | cudaHostRegisterPortable) == cudaSuccess) { diff --git a/src/kernels/cpu/native_expert.cpp b/src/kernels/cpu/native_expert.cpp index 673d4ec9..2ae3947b 100644 --- a/src/kernels/cpu/native_expert.cpp +++ b/src/kernels/cpu/native_expert.cpp @@ -93,7 +93,7 @@ void native_gu_rows(const NativeFmt& f, const uint8_t* blob, const void* const* // Unsloth UD-Q4_K_XL's Q4_K gate/up: the multi-token kernel is bit-exact against ggml's per-token dot, so it // runs for every group size (no #152 rule). STRATA_NO_KQ256 falls back to ggml's vec_dot. static const bool kq = std::getenv("STRATA_NO_KQ256") == nullptr; - if (kq && f.gu_type == 12) { + if (kq && f.gu_type == 12 && nt >= 2) { // one token: ggml's own dot below (the same bits, less overhead) kq256_gu_rows(f.gu_type, blob, f.gu_row, f.up_off, (int) f.n_embd, act, nt, ff, r0, r1); return; } @@ -128,7 +128,7 @@ void native_down_rows(const NativeFmt& f, const uint8_t* blob, const void* const static const bool iq4nl_mt = std::getenv("STRATA_NO_IQ4NL") == nullptr; static const int mt_min = [] { const char* e = std::getenv("STRATA_IQ_MT_MIN"); return e ? std::atoi(e) : 2; }(); static const bool kq = std::getenv("STRATA_NO_KQ256") == nullptr; - if (kq && (f.d_type == 7 || f.d_type == 8)) { // Q5_1 / Q8_0 down: bit-exact, every group size + if (kq && nt >= 2 && (f.d_type == 7 || f.d_type == 8)) { // Q5_1 / Q8_0 down: bit-exact, any group size kq256_rows(f.d_type, blob + f.down_off, f.d_row, (int) f.n_ff, hq, nt, out, r0, r1); return; } From d484ec735fb9cff20371a000f3eddde4bcdcf49e Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Thu, 1 Oct 2026 01:12:36 +0200 Subject: [PATCH 2/5] CS-T: the GGUF-in-place prefetch asks Windows for all of a layer's missed slices at once (PrefetchVirtualMemory) The copies' page faults read a few clusters each; one PrefetchVirtualMemory call for every role slice about to be copied lets the memory manager queue large reads at once, and the parallel copies then find the pages resident or in flight. Only the GGUF-in-place source's prefetch uses it; STRATA_FETCH_PVM=0 is the A/B arm. --- src/core/expert_source.cpp | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/src/core/expert_source.cpp b/src/core/expert_source.cpp index 295d0de0..dbb60fd1 100644 --- a/src/core/expert_source.cpp +++ b/src/core/expert_source.cpp @@ -751,6 +751,30 @@ void FileExpertSource::prefetch(int64_t layer, const int64_t* experts, int64_t n } } if (todo.empty()) return; +#if defined(_WIN32) + // One PrefetchVirtualMemory call for every slice about to be copied: the memory manager reads them in large + // requests, all queued at once, where the copies' page faults would read a few clusters each. The copies below + // then find the pages resident (or in flight). STRATA_FETCH_PVM=0 is the A/B arm. + { + using Pvm = BOOL(WINAPI*)(HANDLE, ULONG_PTR, PWIN32_MEMORY_RANGE_ENTRY, ULONG); + static const Pvm pvm = [] { + const char* v = std::getenv("STRATA_FETCH_PVM"); + if (v != nullptr && std::atoi(v) == 0) return (Pvm) nullptr; + return (Pvm) (void*) GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "PrefetchVirtualMemory"); + }(); + if (pvm != nullptr) { + std::vector ranges; + ranges.reserve(todo.size() * 3); + for (const Fill& f : todo) + for (int r = 0; r < 3; ++r) { + const size_t i = (size_t) (3 * layer + r); + ranges.push_back({(PVOID) (role_ptr_[i] + (size_t) ((uint64_t) f.e * role_bytes_[i])), + (SIZE_T) role_bytes_[i]}); + } + (void) pvm(GetCurrentProcess(), (ULONG_PTR) ranges.size(), ranges.data(), 0); + } + } +#endif // the page faults of a mapped read are one outstanding request each: several threads keep the SSD's queue full std::atomic next{0}; auto work = [&] { From 7d8fc8fd044b40c1df73c85fd241c3b9ac7c1439 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Thu, 1 Oct 2026 01:58:30 +0200 Subject: [PATCH 3/5] CS-T: the partial pin locks only what it does not register and ends at an expert boundary; the Q4_K/Q5_1/Q8_0 multi-token kernels opt-in (STRATA_KQ256=1) - Locking the whole 40 GiB arena in the working set and then registering its prefix made the next device allocation fail (the prompt path's token id buffer); the registered prefix is page-locked by the driver already, so only the rest is locked now. 24 GiB registered out of a 40 GiB budget then starts and runs. - The registered prefix ends at an expert boundary: a blob that began inside it and ran past it was taken as page-locked by cudaMemcpyAsync and refused (an adaptive refill failed, with 16 GiB registered). - The prompt path's token id buffer error names the CUDA error. - kq_avx2 multi-token kernels: bit-exact, but no faster in the engine (the rows phases stayed at 72 ms per verify round at a 40 GiB budget; a window's expert groups hold ~1.4 tokens and ggml's per-token calls find the weights in L1), so they are opt-in with STRATA_KQ256=1; native_expert_parity still checks them bit for bit. --- include/strata/core/expert_source.hpp | 1 + src/core/expert_source.cpp | 32 ++++++++++++++++++++------- src/kernels/cpu/native_expert.cpp | 9 ++++---- src/prefill/prefill.cpp | 4 ++-- 4 files changed, 32 insertions(+), 14 deletions(-) diff --git a/include/strata/core/expert_source.hpp b/include/strata/core/expert_source.hpp index 485733b2..a604fbb0 100644 --- a/include/strata/core/expert_source.hpp +++ b/include/strata/core/expert_source.hpp @@ -496,6 +496,7 @@ private: bool complement_pinned_ = false; bool complement_partial_ = false; ///< CS-T: only the first complement_pin_limit_ bytes are registered uint64_t complement_pin_limit_ = 0; + uint64_t complement_lock_off_ = 0; ///< the working-set lock covers [lock_off, lock_off + locked) bool complement_ready_ = false; uint64_t complement_locked_ = 0; ///< bytes held in the working set (pin refused) int64_t complement_lent_slots_ = 0; diff --git a/src/core/expert_source.cpp b/src/core/expert_source.cpp index dbb60fd1..e565b854 100644 --- a/src/core/expert_source.cpp +++ b/src/core/expert_source.cpp @@ -451,7 +451,8 @@ void FileExpertSource::close() { if (complement_pinned_ && !complement_partial_) (void) cudaFreeHost(complement_arena_); else { if (complement_partial_) (void) cudaHostUnregister(complement_arena_); - if (complement_locked_ > 0) strata::platform::unlock_resident(complement_arena_, complement_locked_); + if (complement_locked_ > 0) + strata::platform::unlock_resident((uint8_t*) complement_arena_ + complement_lock_off_, complement_locked_); std::free(complement_arena_); } } @@ -475,6 +476,7 @@ void FileExpertSource::close() { complement_pinned_ = false; complement_partial_ = false; complement_pin_limit_ = 0; + complement_lock_off_ = 0; complement_ready_ = false; complement_locked_ = 0; complement_lent_slots_ = 0; @@ -964,13 +966,14 @@ bool FileExpertSource::pin_cache_complement( bool pinned_ok = false; uint64_t locked = 0; uint64_t partial_pin = 0; ///< CS-T: a registered prefix of a locked arena + uint64_t lock_off = 0; ///< where the working-set lock starts (after the registered prefix) std::string note; auto release = [&]() { if (arena == nullptr) return; if (pinned_ok) (void) cudaFreeHost(arena); else { if (partial_pin > 0) (void) cudaHostUnregister(arena); - if (locked > 0) strata::platform::unlock_resident(arena, locked); + if (locked > 0) strata::platform::unlock_resident((uint8_t*) arena + lock_off, locked); std::free(arena); } arena = nullptr; @@ -1010,12 +1013,11 @@ bool FileExpertSource::pin_cache_complement( return false; } if (pin) { - const strata::platform::LockResult lr = strata::platform::lock_resident(arena, bytes); - locked = lr.locked_bytes; - note += (note.empty() ? "" : "; ") + lr.note; // CS-T, a RAM budget: its bytes are in profile order, hottest first, so the driver is asked to - // register the largest prefix it takes (from the whole, down in 2 GiB steps). Those experts can be - // read by the GPU over PCIe (--pcie-frac) and copied by DMA; the rest stay locked-only. + // register the largest prefix it takes (from the cap down in 2 GiB steps). Those experts can be + // read by the GPU over PCIe (--pcie-frac) and copied by DMA; only the rest is locked in the working + // set (the registered prefix is page-locked by the driver already - locking it twice made the next + // device allocation fail). static const bool partial_on = [] { const char* v = std::getenv("STRATA_PARTIAL_PIN"); // 0: the A/B arm without it return v == nullptr || std::atoi(v) != 0; @@ -1029,7 +1031,15 @@ bool FileExpertSource::pin_cache_complement( if (budget_bytes > 0 && partial_on) { const uint64_t step = 2ull << 30; for (uint64_t want = std::min(bytes, pin_cap); want >= step; want = want > step ? want - step : 0) { - const uint64_t w = want - want % (64ull << 10); + // cut at an expert boundary: a blob that started inside the registered range and ran past it + // would be taken as page-locked by a cudaMemcpyAsync and refused ("adaptive refill failed") + uint64_t w = want; + for (size_t i = 0; i < offsets.size(); ++i) { + if (offsets[i] == kNoComplement) continue; + const uint64_t b = layer_blob_bytes_[i / (size_t) n_expert_]; + if (offsets[i] < want && offsets[i] + b > want) { w = offsets[i]; break; } + } + if (w == 0) break; if (cudaHostRegister(arena, (size_t) w, cudaHostRegisterMapped | cudaHostRegisterPortable) == cudaSuccess) { void* alias = nullptr; @@ -1050,6 +1060,11 @@ bool FileExpertSource::pin_cache_complement( (double) partial_pin / 1073741824.0); note += std::string("; ") + msg; } + lock_off = partial_pin; + const strata::platform::LockResult lr = + strata::platform::lock_resident((uint8_t*) arena + lock_off, bytes - lock_off); + locked = lr.locked_bytes; + note += (note.empty() ? "" : "; ") + lr.note; } } host = (const uint8_t*) arena; @@ -1146,6 +1161,7 @@ bool FileExpertSource::pin_cache_complement( complement_pin_limit_ = pinned_ok ? bytes : partial_pin; complement_partial_ = !pinned_ok && partial_pin > 0; complement_locked_ = locked; + complement_lock_off_ = lock_off; complement_lent_slots_ = lend ? n_slots - keep_from : 0; complement_ready_ = true; std::fprintf(stderr, "FileExpertSource: %s cache complement ready: resident %.2f GiB, pinned %.2f GiB%s%s\n", diff --git a/src/kernels/cpu/native_expert.cpp b/src/kernels/cpu/native_expert.cpp index 2ae3947b..2e8d8adb 100644 --- a/src/kernels/cpu/native_expert.cpp +++ b/src/kernels/cpu/native_expert.cpp @@ -90,9 +90,10 @@ void native_gu_rows(const NativeFmt& f, const uint8_t* blob, const void* const* // can depend on how many drafts a verify window held. STRATA_IQ_MT_MIN=1 (opt-in, 0.1.30) uses the multi-token // kernels for every group: output independent of the drafting, at a measured -1..-3% decode on IQ3_S (AVX-512). static const int mt_min = [] { const char* e = std::getenv("STRATA_IQ_MT_MIN"); return e ? std::atoi(e) : 2; }(); - // Unsloth UD-Q4_K_XL's Q4_K gate/up: the multi-token kernel is bit-exact against ggml's per-token dot, so it - // runs for every group size (no #152 rule). STRATA_NO_KQ256 falls back to ggml's vec_dot. - static const bool kq = std::getenv("STRATA_NO_KQ256") == nullptr; + // Unsloth UD-Q4_K_XL's Q4_K gate/up: the multi-token kernel is bit-exact against ggml's per-token dot (any group + // size, no #152 rule). Opt-in, STRATA_KQ256=1: measured no faster in the engine (a window's expert groups hold + // ~1.4 tokens and the weights stay in L1 across ggml's per-token calls; 1.01-1.13x in native_expert_parity). + static const bool kq = [] { const char* v = std::getenv("STRATA_KQ256"); return v != nullptr && std::atoi(v) != 0; }(); if (kq && f.gu_type == 12 && nt >= 2) { // one token: ggml's own dot below (the same bits, less overhead) kq256_gu_rows(f.gu_type, blob, f.gu_row, f.up_off, (int) f.n_embd, act, nt, ff, r0, r1); return; @@ -127,7 +128,7 @@ void native_down_rows(const NativeFmt& f, const uint8_t* blob, const void* const // block instead of once per token; ggml-cpu's dot is single-token. STRATA_NO_IQ4NL falls back to it. static const bool iq4nl_mt = std::getenv("STRATA_NO_IQ4NL") == nullptr; static const int mt_min = [] { const char* e = std::getenv("STRATA_IQ_MT_MIN"); return e ? std::atoi(e) : 2; }(); - static const bool kq = std::getenv("STRATA_NO_KQ256") == nullptr; + static const bool kq = [] { const char* v = std::getenv("STRATA_KQ256"); return v != nullptr && std::atoi(v) != 0; }(); if (kq && nt >= 2 && (f.d_type == 7 || f.d_type == 8)) { // Q5_1 / Q8_0 down: bit-exact, any group size kq256_rows(f.d_type, blob + f.down_off, f.d_row, (int) f.n_ff, hq, nt, out, r0, r1); return; diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index 28981d12..7c36257c 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -496,8 +496,8 @@ bool Prefill::init(const core::WeightTable& wt, const core::ModelGeometry& g, co return false; } if (m.tok_dev == nullptr) { - if (cudaMalloc((void**) &m.tok_dev, (size_t) chunk * sizeof(int32_t)) != cudaSuccess) { - err = "prefill: the token id buffer"; + if (const cudaError_t e = cudaMalloc((void**) &m.tok_dev, (size_t) chunk * sizeof(int32_t)); e != cudaSuccess) { + err = std::string("prefill: the token id buffer (") + cudaGetErrorString(e) + ")"; return false; } m.owned.push_back(m.tok_dev); From 0dac2b9aa1dc6aae2a0b7fb380e4cc41c2fe7d27 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Thu, 1 Oct 2026 02:30:24 +0200 Subject: [PATCH 4/5] CS-T: routing-aware prefetch of the file tier - the next layer's router on this layer's MoE input warms its predicted experts' pages - RouterLookahead: when the CPU pool starts layer l, a worker thread applies layer l+1's router (a BF16 host copy of ffn_gate_inp, 126 MB for 48 layers) to layer l's MoE input - the router's own input - for each token of the window, takes the top STRATA_LOOKAHEAD_K (default 10), drops the experts the GPU cache (host_res) or the RAM copy holds, and asks the source to warm the rest. It never waits: a prediction still running makes the next one skip. STRATA_LOOKAHEAD=0 is the A/B arm. - ExpertSource::warm / warms(): FileExpertSource with the GGUF in place issues one PrefetchVirtualMemory for the predicted slices (madvise(WILLNEED) elsewhere). Pages only: blob(), the experts computed and their bytes do not change (the same answers in every A/B run). Every other source: no-op, and the predictor is not started. - bf16_rows_dot_multi (kq_avx2.cpp, AVX2): the router read once for all tokens of the window. - Stats: experts warmed, how many of the decode's file-tier reads had been warmed, the predictor's time and skips. UD-Q4_K_XL at a 40 GiB budget (single-token-router version): ~48-54% of the file tier's reads had been warmed; reading time 850-968 -> 630-730 ms per verify round; decode 5.31/6.60 tok/s off vs 7.08/6.79/6.91 on. --- include/strata/core/expert_source.hpp | 54 ++++++++++ include/strata/kernels/cpu/kq_avx2.hpp | 5 + src/core/expert_source.cpp | 133 ++++++++++++++++++++++++- src/kernels/cpu/kq_avx2.cpp | 35 +++++++ src/program/generate.cpp | 33 ++++++ 5 files changed, 259 insertions(+), 1 deletion(-) diff --git a/include/strata/core/expert_source.hpp b/include/strata/core/expert_source.hpp index a604fbb0..84339efc 100644 --- a/include/strata/core/expert_source.hpp +++ b/include/strata/core/expert_source.hpp @@ -31,6 +31,7 @@ #include #include #include +#include #include #include #include @@ -136,6 +137,49 @@ public: /// The `n` experts of `layer` the CPU is about to ask `blob` for, all at once: a source that reads a file may /// fetch them in parallel. The bytes `blob` then returns are the same. Default: nothing. virtual void prefetch(int64_t layer, const int64_t* experts, int64_t n) { (void) layer; (void) experts; (void) n; } + /// CS-T: the experts of `layer` a predictor expects next - a source that reads a file may start reading their + /// pages now, in the background. Only warms: what `blob` returns is unchanged. Default: nothing. + virtual void warm(int64_t layer, const int64_t* experts, int64_t n) { (void) layer; (void) experts; (void) n; } + /// Whether `warm` does anything (the predictor is not run otherwise). + virtual bool warms() const { return false; } +}; + +/// CS-T, routing-aware prefetch of the file tier: when the CPU pool starts layer `l`, a worker thread applies layer +/// l+1's router (BF16, host copy) to layer l's MoE input - the residual stream changes little from one layer to the +/// next - takes each token's top `k` experts, drops the ones the GPU cache or the RAM copy holds, and asks the +/// source to `warm` the rest, so their pages are on the way while layer l computes. A prediction only warms pages: +/// it never changes which experts are computed or how. +class RouterLookahead { +public: + RouterLookahead() = default; + ~RouterLookahead(); + RouterLookahead(const RouterLookahead&) = delete; + RouterLookahead& operator=(const RouterLookahead&) = delete; + /// `routers[l]`: layer l's ffn_gate_inp as BF16 bits, n_expert rows of n_embd. + bool start(std::vector> routers, int64_t n_embd, int64_t n_expert, int k, ExpertSource* src, + std::string& err); + /// Layer `layer`'s MoE input for `n_tok` tokens (host floats): predict and warm layer + 1. Never waits: a + /// prediction still running for an earlier layer makes this one skip. + void submit(int64_t layer, const float* x, int64_t n_tok, const int32_t* host_res); + int64_t predicted() const { return predicted_.load(std::memory_order_relaxed); } + int64_t skipped() const { return skipped_.load(std::memory_order_relaxed); } + double busy_ms() const { return (double) busy_us_.load(std::memory_order_relaxed) / 1000.0; } + +private: + void run(); + std::vector> routers_; + int64_t n_embd_ = 0, n_expert_ = 0; + int k_ = 10; + ExpertSource* src_ = nullptr; + std::thread thread_; + std::mutex mu_; + std::condition_variable cv_; + bool quit_ = false, pending_ = false, busy_ = false; + int64_t layer_ = -1, n_tok_ = 0; + const int32_t* host_res_ = nullptr; + std::vector x_; + std::atomic predicted_{0}, skipped_{0}; + std::atomic busy_us_{0}; }; /// Plan v0.3 P6: what the GPU computes in a verify window's layer, written by the pool (mapped host memory) right @@ -169,6 +213,7 @@ struct GpuPlanSink { struct ExpertDispatch { strata::kernels::cpu::ExpertPool* pool = nullptr; ExpertSource* src = nullptr; + RouterLookahead* lookahead = nullptr; ///< CS-T: warms the next layer's predicted file-tier experts RemoteExperts* remote[3] = {}; ///< optional CUDA1..3 tiers for otherwise CPU-served rows int remote_count = 0; int64_t n_expert = strata::kernels::cpu::NE; @@ -433,6 +478,13 @@ public: void begin_layer(int64_t layer, const int32_t* ids, int64_t k) override; /// CS-T: the GGUF in place assembles the missed experts on `fetch_threads_` threads. void prefetch(int64_t layer, const int64_t* experts, int64_t n) override; + /// CS-T: the GGUF in place asks the OS for the predicted experts' pages (PrefetchVirtualMemory on Windows, + /// madvise(WILLNEED) elsewhere), skipping the RAM copy's. + void warm(int64_t layer, const int64_t* experts, int64_t n) override; + bool warms() const override { return !role_ptr_.empty(); } + /// Of the blobs the file tier read for the decode, how many had been warmed for their layer beforehand. + int64_t warmed_hits() const { return warm_hits_.load(std::memory_order_relaxed); } + int64_t warmed() const { return warm_count_.load(std::memory_order_relaxed); } /// Blobs touched, for the driver to report. With `h = 0` this is `48 * k` per token and the number is only /// interesting once Phase 3 makes it not so. @@ -474,6 +526,8 @@ private: std::condition_variable stage_cv_; int fetch_threads_ = 8; std::atomic file_blob_bytes_{0}, file_us_{0}; + std::unique_ptr[]> warm_stamp_; ///< per (layer, expert): epoch_ + 1 when warmed + std::atomic warm_hits_{0}, warm_count_{0}; std::unordered_map stage_of_; uint64_t stage_blob_ = 0; uint64_t stage_seq_ = 0; diff --git a/include/strata/kernels/cpu/kq_avx2.hpp b/include/strata/kernels/cpu/kq_avx2.hpp index 0b307404..01b7a63c 100644 --- a/include/strata/kernels/cpu/kq_avx2.hpp +++ b/include/strata/kernels/cpu/kq_avx2.hpp @@ -17,4 +17,9 @@ void kq256_gu_rows(int ggml_type, const uint8_t* blob, size_t gu_row, size_t up_ void kq256_rows(int ggml_type, const uint8_t* w, size_t row_bytes, int n, const void* const* act, int nt, float* const* out, int r0, int r1); +/// out[r] = w_r . x for BF16 rows (bits), fp32 x: the routing-aware prefetch's router (an estimate only). +void bf16_rows_dot(const uint16_t* w, int rows, int cols, const float* x, float* out); +/// The same for `nt` <= 8 tokens (x: nt rows of cols, cols % 8 == 0), out[t * rows + r]. +void bf16_rows_dot_multi(const uint16_t* w, int rows, int cols, const float* x, int nt, float* out); + } // namespace strata::kernels::cpu diff --git a/src/core/expert_source.cpp b/src/core/expert_source.cpp index e565b854..ca172d86 100644 --- a/src/core/expert_source.cpp +++ b/src/core/expert_source.cpp @@ -9,6 +9,7 @@ #include "strata/kernels/elementwise.hpp" #include "strata/kernels/quantize_act.hpp" #include "strata/kernels/s2_expert_grouped.hpp" +#include "strata/kernels/cpu/kq_avx2.hpp" #include @@ -511,6 +512,9 @@ void FileExpertSource::close() { stage_grew_ = false; } ram_reads_.store(0); + warm_stamp_.reset(); + warm_hits_.store(0); + warm_count_.store(0); file_read_bytes_.store(0); file_blob_bytes_.store(0); file_us_.store(0); @@ -620,6 +624,7 @@ bool FileExpertSource::open_gguf(std::string& err) { } } base_ = maps_.front().base; // "opened"; mapped_blob answers nullptr in this mode + warm_stamp_.reset(new std::atomic[(size_t) (n_layers_ * n_expert_)]()); for (uint64_t b : layer_blob_bytes_) stage_blob_ = std::max(stage_blob_, b); return true; } @@ -749,7 +754,13 @@ void FileExpertSource::prefetch(int64_t layer, const int64_t* experts, int64_t n if (!override_.empty() && override_[index] != nullptr) continue; size_t v = 0; bool fill = false; - if (!claim_stage(layer * n_expert_ + e, v, fill) && fill) todo.push_back({v, e, stage_buf_[v].get()}); + if (!claim_stage(layer * n_expert_ + e, v, fill) && fill) { + todo.push_back({v, e, stage_buf_[v].get()}); + if (warm_stamp_) { + const uint32_t s = warm_stamp_[index].load(std::memory_order_relaxed); + if (s != 0 && (uint64_t) s + 3 >= epoch_ + 1) warm_hits_.fetch_add(1, std::memory_order_relaxed); + } + } } } if (todo.empty()) return; @@ -790,6 +801,125 @@ void FileExpertSource::prefetch(int64_t layer, const int64_t* experts, int64_t n for (auto& t : th) t.join(); } + +void FileExpertSource::warm(int64_t layer, const int64_t* experts, int64_t n) { + if (role_ptr_.empty() || n <= 0 || layer < 0 || layer >= n_layers_) return; + uint32_t stamp; + { + std::lock_guard lk(stage_mu_); + stamp = (uint32_t) epoch_ + 1; + } +#if defined(_WIN32) + using Pvm = BOOL(WINAPI*)(HANDLE, ULONG_PTR, PWIN32_MEMORY_RANGE_ENTRY, ULONG); + static const Pvm pvm = (Pvm) (void*) GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "PrefetchVirtualMemory"); + std::vector ranges; +#endif + for (int64_t j = 0; j < n; ++j) { + const int64_t e = experts[j]; + if (e < 0 || e >= n_expert_) continue; + const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) e; + if (complement_ready_ && index < complement_offsets_.size() && complement_offsets_[index] != kNoComplement) + continue; // in the RAM copy + if (warm_stamp_) warm_stamp_[index].store(stamp, std::memory_order_relaxed); + warm_count_.fetch_add(1, std::memory_order_relaxed); + for (int r = 0; r < 3; ++r) { + const size_t i = (size_t) (3 * layer + r); + const uint8_t* p = role_ptr_[i] + (size_t) ((uint64_t) e * role_bytes_[i]); +#if defined(_WIN32) + ranges.push_back({(PVOID) p, (SIZE_T) role_bytes_[i]}); +#else + const uintptr_t pg = 4096, a = (uintptr_t) p & ~(pg - 1); + (void) madvise((void*) a, (size_t) ((uintptr_t) p + role_bytes_[i] - a), MADV_WILLNEED); +#endif + } + } +#if defined(_WIN32) + if (pvm != nullptr && !ranges.empty()) (void) pvm(GetCurrentProcess(), (ULONG_PTR) ranges.size(), ranges.data(), 0); +#endif +} + +RouterLookahead::~RouterLookahead() { + { + std::lock_guard lk(mu_); + quit_ = true; + } + cv_.notify_all(); + if (thread_.joinable()) thread_.join(); +} + +bool RouterLookahead::start(std::vector> routers, int64_t n_embd, int64_t n_expert, int k, + ExpertSource* src, std::string& err) { + if (src == nullptr || !src->warms()) { err = "RouterLookahead: the expert source does not warm"; return false; } + if (n_embd % 8 != 0) { err = "RouterLookahead: n_embd is not a multiple of 8"; return false; } + for (const auto& r : routers) + if (r.size() != (size_t) (n_embd * n_expert)) { err = "RouterLookahead: a router of another shape"; return false; } + routers_ = std::move(routers); + n_embd_ = n_embd; + n_expert_ = n_expert; + k_ = k < 1 ? 1 : k > (int) n_expert ? (int) n_expert : k; + src_ = src; + x_.assign((size_t) (8 * n_embd), 0.f); + thread_ = std::thread([this] { run(); }); + return true; +} + +void RouterLookahead::submit(int64_t layer, const float* x, int64_t n_tok, const int32_t* host_res) { + if (layer + 1 >= (int64_t) routers_.size() || n_tok <= 0 || x == nullptr) return; + { + std::lock_guard lk(mu_); + if (busy_ || pending_) { skipped_.fetch_add(1, std::memory_order_relaxed); return; } + n_tok_ = std::min(n_tok, 8); + std::memcpy(x_.data(), x, (size_t) (n_tok_ * n_embd_) * sizeof(float)); + layer_ = layer + 1; + host_res_ = host_res; + pending_ = true; + } + cv_.notify_one(); +} + +void RouterLookahead::run() { + std::vector logits((size_t) (8 * n_expert_)); + std::vector order((size_t) n_expert_); + std::vector want; + for (;;) { + int64_t layer, nt; + const int32_t* host_res; + { + std::unique_lock lk(mu_); + cv_.wait(lk, [&] { return quit_ || pending_; }); + if (quit_) return; + pending_ = false; + busy_ = true; + layer = layer_; + nt = n_tok_; + host_res = host_res_; + } + const auto t0 = std::chrono::steady_clock::now(); + want.clear(); + strata::kernels::cpu::bf16_rows_dot_multi(routers_[(size_t) layer].data(), (int) n_expert_, (int) n_embd_, + x_.data(), (int) nt, logits.data()); + for (int64_t t = 0; t < nt; ++t) { + const float* lt = logits.data() + (size_t) (t * n_expert_); + for (int64_t e = 0; e < n_expert_; ++e) order[(size_t) e] = (int32_t) e; + std::partial_sort(order.begin(), order.begin() + k_, order.end(), + [&](int32_t a, int32_t b) { return lt[(size_t) a] > lt[(size_t) b]; }); + for (int j = 0; j < k_; ++j) { + const int64_t e = order[(size_t) j]; + if (host_res != nullptr && host_res[(size_t) (layer * n_expert_ + e)] >= 0) continue; // on the GPU + if (std::find(want.begin(), want.end(), e) == want.end()) want.push_back(e); + } + } + src_->warm(layer, want.data(), (int64_t) want.size()); + predicted_.fetch_add((int64_t) want.size(), std::memory_order_relaxed); + busy_us_.fetch_add((uint64_t) std::chrono::duration(std::chrono::steady_clock::now() - t0).count(), + std::memory_order_relaxed); + { + std::lock_guard lk(mu_); + busy_ = false; + } + } +} + void FileExpertSource::begin_layer(int64_t layer, const int32_t* ids, int64_t k) { (void) ids; (void) k; @@ -1444,6 +1574,7 @@ void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32 d.fail_layer = d.layers; return; } + if (d.lookahead != nullptr) d.lookahead->submit(d.layers, x_f, n_tok, d.host_res); // CS-T: warm layer + 1 if (k < 1 || n_tok * k > kMaxWindowEntries) { d.failed = true; d.fail = "a verify window routes more entries than the expert pool's window tables hold"; diff --git a/src/kernels/cpu/kq_avx2.cpp b/src/kernels/cpu/kq_avx2.cpp index 8f08a2a8..a3473119 100644 --- a/src/kernels/cpu/kq_avx2.cpp +++ b/src/kernels/cpu/kq_avx2.cpp @@ -201,6 +201,41 @@ void dot_rows(int type, const uint8_t* row, int n, const void* const* act, int n bool kq256_supported(int type) noexcept { return type == 12 || type == 7 || type == 8; } +void bf16_rows_dot_multi(const uint16_t* w, int rows, int cols, const float* x, int nt, float* out) { + // each row is read once for all `nt` (<= 8) tokens: the router (2.6 MB per layer) streams once per prediction + for (int r = 0; r < rows; ++r) { + const uint16_t* wr = w + (size_t) r * (size_t) cols; + __m256 acc[8]; + for (int t = 0; t < nt; ++t) acc[t] = _mm256_setzero_ps(); + for (int c = 0; c + 8 <= cols; c += 8) { + const __m256 wf = _mm256_castsi256_ps( + _mm256_slli_epi32(_mm256_cvtepu16_epi32(_mm_loadu_si128((const __m128i*) (wr + c))), 16)); + for (int t = 0; t < nt; ++t) acc[t] = _mm256_fmadd_ps(wf, _mm256_loadu_ps(x + (size_t) t * cols + c), acc[t]); + } + for (int t = 0; t < nt; ++t) out[(size_t) t * rows + r] = hsum_float_8(acc[t]); // cols % 8 == 0 (2560) + } +} + +void bf16_rows_dot(const uint16_t* w, int rows, int cols, const float* x, float* out) { + for (int r = 0; r < rows; ++r) { + const uint16_t* wr = w + (size_t) r * (size_t) cols; + __m256 acc = _mm256_setzero_ps(); + int c = 0; + for (; c + 8 <= cols; c += 8) { + const __m256i h = _mm256_cvtepu16_epi32(_mm_loadu_si128((const __m128i*) (wr + c))); + acc = _mm256_fmadd_ps(_mm256_castsi256_ps(_mm256_slli_epi32(h, 16)), _mm256_loadu_ps(x + c), acc); + } + float s = hsum_float_8(acc); + for (; c < cols; ++c) { + const uint32_t b = (uint32_t) wr[c] << 16; + float f; + std::memcpy(&f, &b, 4); + s += f * x[c]; + } + out[r] = s; + } +} + void kq256_gu_rows(int type, const uint8_t* blob, size_t gu_row, size_t up_off, int n, const void* const* act, int nt, float* const* ff, int r0, int r1) { for (int t0 = 0; t0 < nt; t0 += MAXT) { diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 0f522522..7a98d231 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -2741,6 +2741,32 @@ int main(int argc, char** argv) { drive.d.src = srcp; drive.d.n_expert = g.n_expert; drive.d.jobs.resize((size_t) K); + // CS-T: routing-aware prefetch of the file tier (the GGUF in place): the next layer's router on this layer's MoE + // input predicts its experts and their pages are warmed meanwhile. It only warms pages; STRATA_LOOKAHEAD=0 is + // the A/B arm, STRATA_LOOKAHEAD_K the experts per token (default 10). + strata::core::RouterLookahead lookahead; + if (srcp == &src && src.warms() && [] { const char* v = std::getenv("STRATA_LOOKAHEAD"); return v == nullptr || std::atoi(v) != 0; }()) { + std::vector> routers((size_t) g.n_layers); + bool ok = true; + for (int64_t l = 0; l < g.n_layers && ok; ++l) { + const strata::core::WeightRef* w = wt.find("blk." + std::to_string(l) + ".ffn_gate_inp.weight"); + ok = w != nullptr && w->kind == strata::core::WeightKind::Bf16InF32 && + w->bytes == (uint64_t) (g.n_expert * g.n_embd) * 2; + if (!ok) break; + routers[(size_t) l].resize((size_t) (g.n_expert * g.n_embd)); + ok = cudaMemcpy(routers[(size_t) l].data(), w->data, (size_t) w->bytes, cudaMemcpyDeviceToHost) == cudaSuccess; + } + const char* kv = std::getenv("STRATA_LOOKAHEAD_K"); + if (ok && lookahead.start(std::move(routers), g.n_embd, g.n_expert, kv ? std::atoi(kv) : 10, &src, err)) { + drive.d.lookahead = &lookahead; + std::fprintf(stderr, "strata generate: routing-aware prefetch of the file tier on (the next layer's router)\n"); + } else { + (void) cudaGetLastError(); + std::fprintf(stderr, "strata generate: routing-aware prefetch off (%s)\n", + ok ? err.c_str() : "the routers are not BF16 in the arena"); + err.clear(); + } + } // ---- R4.2c: THE HIT PATH. Every one of these is required for `hits_ready()`, which is all-or-nothing on // purpose: a half-configured hit path would compute some experts twice and others not at all, and a token // built on that is wrong rather than refused. @@ -5730,6 +5756,13 @@ int main(int argc, char** argv) { fmb, rounds > 0 ? fmb / rounds : 0.0, rounds > 0 ? fms / rounds : 0.0, fms > 0 ? fmb / fms : 0.0, src.gguf_mode() ? " (the GGUF in place)" : "", (double) (fall0 - fbytes0) / 1e6); + if (drive.d.lookahead != nullptr) + std::printf("%-24s %lld experts warmed, %lld of the file tier's %lld blob reads had been warmed (%.1f%%); " + "predictor %.1f ms/round on its thread, %lld layers skipped (still busy)\n", "routing prefetch", + (long long) src.warmed(), (long long) src.warmed_hits(), + (long long) (src.file_reads() - files0), + src.file_reads() > files0 ? 100.0 * (double) src.warmed_hits() / (double) (src.file_reads() - files0) : 0.0, + rounds > 0 ? drive.d.lookahead->busy_ms() / rounds : 0.0, (long long) drive.d.lookahead->skipped()); } if (rounds > 0 && drive.d.pcie_num > 0) std::printf("%-24s %.2f distinct experts per layer read over PCIe (share %d/256 of the misses)\n", From a74acb6dd2c9509c0188c2d00f707bedbd29f84e Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Thu, 1 Oct 2026 03:03:17 +0200 Subject: [PATCH 5/5] CS-T: the partial pin of the RAM tier opt-in (STRATA_PARTIAL_PIN=1) On the RTX 5070 / 64 GB PC the GPU computing a share of the misses over PCIe measured no faster than the CPU: 7.30 and 7.44 tok/s with 24 and 16 GiB of a 40 GiB budget registered, against 7.05-7.74 unpinned, and registering costs startup time and driver memory. The default budget mode is now locked-only; the routing-aware prefetch (multi-run A/B: 6.93 -> 7.91 tok/s mean, identical answers) stays on with the GGUF in place. --- src/core/expert_source.cpp | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/core/expert_source.cpp b/src/core/expert_source.cpp index ca172d86..5d8e0556 100644 --- a/src/core/expert_source.cpp +++ b/src/core/expert_source.cpp @@ -1148,9 +1148,12 @@ bool FileExpertSource::pin_cache_complement( // read by the GPU over PCIe (--pcie-frac) and copied by DMA; only the rest is locked in the working // set (the registered prefix is page-locked by the driver already - locking it twice made the next // device allocation fail). + // opt-in (STRATA_PARTIAL_PIN=1): on the RTX 5070 PC the GPU's PCIe share of the misses measured no + // faster than the CPU computing them (7.30 / 7.44 tok/s with 24 / 16 GiB registered against 7.05-7.74 + // unpinned at a 40 GiB budget), and registering adds startup time and driver memory pressure static const bool partial_on = [] { - const char* v = std::getenv("STRATA_PARTIAL_PIN"); // 0: the A/B arm without it - return v == nullptr || std::atoi(v) != 0; + const char* v = std::getenv("STRATA_PARTIAL_PIN"); + return v != nullptr && std::atoi(v) != 0; }(); // at most STRATA_PARTIAL_PIN_GIB (default 24): registering 30 GiB of a 40 GiB arena left the driver // unable to page-lock the prompt path's small buffers afterwards (RTX 5070, WDDM)