Skip to content

Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.

C++

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

Niko12210dac2b9aa1dc
diff --git a/include/strata/core/expert_source.hpp b/include/strata/core/expert_source.hpp
index a604fbb05..84339efcc 100644
--- a/include/strata/core/expert_source.hpp
+++ b/include/strata/core/expert_source.hpp
@@ -31,6 +31,7 @@
#include <condition_variable>
#include <memory>
#include <mutex>
+#include <thread>
#include <unordered_map>
#include <utility>
#include <string>
@@ -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<std::vector<uint16_t>> 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<std::vector<uint16_t>> 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<float> x_;
+ std::atomic<int64_t> predicted_{0}, skipped_{0};
+ std::atomic<uint64_t> 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<uint64_t> file_blob_bytes_{0}, file_us_{0};
+ std::unique_ptr<std::atomic<uint32_t>[]> warm_stamp_; ///< per (layer, expert): epoch_ + 1 when warmed
+ std::atomic<int64_t> warm_hits_{0}, warm_count_{0};
std::unordered_map<int64_t, size_t> 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 0b3074043..01b7a63cc 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 e565b854b..ca172d86c 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 <cuda_runtime.h>
@@ -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<uint32_t>[(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<std::mutex> 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<WIN32_MEMORY_RANGE_ENTRY> 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<std::mutex> lk(mu_);
+ quit_ = true;
+ }
+ cv_.notify_all();
+ if (thread_.joinable()) thread_.join();
+}
+
+bool RouterLookahead::start(std::vector<std::vector<uint16_t>> 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<std::mutex> lk(mu_);
+ if (busy_ || pending_) { skipped_.fetch_add(1, std::memory_order_relaxed); return; }
+ n_tok_ = std::min<int64_t>(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<float> logits((size_t) (8 * n_expert_));
+ std::vector<int32_t> order((size_t) n_expert_);
+ std::vector<int64_t> want;
+ for (;;) {
+ int64_t layer, nt;
+ const int32_t* host_res;
+ {
+ std::unique_lock<std::mutex> 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<double, std::micro>(std::chrono::steady_clock::now() - t0).count(),
+ std::memory_order_relaxed);
+ {
+ std::lock_guard<std::mutex> 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 8f08a2a8c..a34731198 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 0f5225224..7a98d231a 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<std::vector<uint16_t>> 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",