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++

prefill: take expert blobs from a helper's VRAM cache when it holds them

W1nge268647d2ec38
diff --git a/include/strata/core/remote_experts.hpp b/include/strata/core/remote_experts.hpp
index 218ff55bb..d499c0315 100644
--- a/include/strata/core/remote_experts.hpp
+++ b/include/strata/core/remote_experts.hpp
@@ -5,7 +5,9 @@
#include <cuda_runtime.h>
+#include <atomic>
#include <cstdint>
+#include <mutex>
#include <string>
#include <utility>
#include <vector>
@@ -51,6 +53,15 @@ public:
double ms_begin() const { return ms_begin_; }
double ms_wait() const { return ms_wait_; }
+ /// STRATA_PREFILL_HELPER_SOURCE (opt-in): copy up to `n` cached blobs into the host buffers `dst[i]`
+ /// on this helper's own stream and wait. `hit[i]` is set where this helper held (layer, expert); the
+ /// bytes are the ones open() filled from the same source, so the prompt path gets identical bytes.
+ /// Misses are left to the caller. False with `err` on a CUDA failure; the hits copied so far are
+ /// complete (the stream is drained), so the caller falls back for the rest. Safe from several threads
+ /// (one stream, one lock): the prompt path's stager is threaded.
+ bool copy_cached_blobs(const int32_t* layers, const int32_t* experts, uint8_t* const* dst, size_t n,
+ uint8_t* hit, std::string& err);
+
private:
friend class RemoteExpertOpt;
RemoteExpertOpt* remote_opt_ = nullptr;
@@ -64,6 +75,8 @@ private:
double ms_begin_ = 0, ms_wait_ = 0;
ExpertCache cache_;
cudaStream_t stream_ = nullptr;
+ cudaStream_t read_stream_ = nullptr; ///< STRATA_PREFILL_HELPER_SOURCE: cache -> host copies
+ std::mutex read_mu_; ///< one cache reader at a time (the stager is threaded)
float* h_x_ = nullptr;
float* h_out_ = nullptr;
void* h_meta_ = nullptr;
@@ -88,4 +101,72 @@ private:
std::vector<unsigned long long> ptr_;
};
+/// STRATA_PREFILL_HELPER_SOURCE (opt-in): the prompt path's view of the expert tiers, where a blob a helper
+/// GPU already holds in its VRAM cache is copied from that cache instead of being read from the files again.
+/// Everything else is forwarded to `fallback` unchanged, so its batched unbuffered reads, its pinned RAM copy
+/// and the prompt path's own decisions keep their meaning. Nothing is cached here: every call asks the
+/// helpers, so an entry an adaptive tier moves between requests is a miss (a file read), never a wrong blob.
+///
+/// The serve loop builds this only for a serial request path (no batch slots, no layer split), while the
+/// helpers are idle: during a prompt read the helper GPUs compute nothing, so their caches can be read
+/// without ordering the copies against their kernel streams.
+class RemotePrefillSource final : public ExpertSource {
+public:
+ RemotePrefillSource(ExpertSource& fallback, const std::vector<RemoteExperts*>& helpers)
+ : fallback_(fallback), helpers_(helpers) {}
+
+ /// Whether any helper's VRAM cache holds (layer, expert) right now.
+ bool from_helper(int64_t layer, int64_t expert) const {
+ for (const RemoteExperts* h : helpers_) if (h->holds(layer, (int32_t) expert)) return true;
+ return false;
+ }
+ /// Blobs / bytes this source has taken from the helpers so far (the per-request evidence line).
+ uint64_t helper_blobs() const { return helper_blobs_.load(std::memory_order_relaxed); }
+ uint64_t helper_bytes() const { return helper_bytes_.load(std::memory_order_relaxed); }
+
+ const uint8_t* blob(int64_t layer, int64_t expert) override { return fallback_.blob(layer, expert); }
+ const uint8_t* blob_stable(int64_t layer, int64_t expert) override {
+ return fallback_.blob_stable(layer, expert);
+ }
+ int64_t reads() const override { return fallback_.reads(); }
+ bool pinned(int64_t layer, int64_t expert) const override {
+ return from_helper(layer, expert) ? false : fallback_.pinned(layer, expert);
+ }
+ void begin_layer(int64_t layer, const int32_t* ids, int64_t k) override {
+ fallback_.begin_layer(layer, ids, k);
+ }
+ const uint8_t* device_alias(int64_t layer, int64_t expert) const override {
+ return from_helper(layer, expert) ? nullptr : fallback_.device_alias(layer, expert);
+ }
+ void prefetch(int64_t layer, int64_t expert) override { fallback_.prefetch(layer, expert); }
+ uint64_t release(int64_t layer, int64_t expert) override {
+ return from_helper(layer, expert) ? 0 : fallback_.release(layer, expert);
+ }
+ bool pcie_layer(int64_t layer) const override { return fallback_.pcie_layer(layer); }
+ /// True where a helper holds the blob: the prompt path's stager must then take the copy_blob(s) route,
+ /// which is where the cache-to-host copy happens. Everywhere else the fallback answers as it always did.
+ bool transient(int64_t layer, int64_t expert) const override {
+ return from_helper(layer, expert) ? true : fallback_.transient(layer, expert);
+ }
+ double cached_share(int64_t samples) const override { return fallback_.cached_share(samples); }
+ bool copy_blob(int64_t layer, int64_t expert, uint8_t* dst) override;
+ bool copy_blobs(const int32_t* layers, const int32_t* experts, uint8_t* const* dst, size_t n) override;
+ void prefetch(int64_t layer, const int64_t* experts, int64_t n) override {
+ fallback_.prefetch(layer, experts, n);
+ }
+ void warm(int64_t layer, const int64_t* experts, int64_t n) override {
+ fallback_.warm(layer, experts, n);
+ }
+ bool warms() const override { return fallback_.warms(); }
+ bool advise_pairs(const std::pair<int32_t, int32_t>* pairs, int64_t n) const override {
+ return fallback_.advise_pairs(pairs, n);
+ }
+
+private:
+ void warn(const std::string& err);
+ ExpertSource& fallback_;
+ std::vector<RemoteExperts*> helpers_;
+ std::atomic<uint64_t> helper_blobs_{0}, helper_bytes_{0};
+ std::atomic<bool> warned_{false};
+};
} // namespace strata::core
diff --git a/src/core/remote_experts.cpp b/src/core/remote_experts.cpp
index 1b6969e82..9af13abfb 100644
--- a/src/core/remote_experts.cpp
+++ b/src/core/remote_experts.cpp
@@ -8,6 +8,7 @@
#include <algorithm>
#include <chrono>
+#include <cstdio>
#include <cstdlib>
#include <cstring>
@@ -93,6 +94,7 @@ void RemoteExperts::close() {
DeviceScope scope(device_);
if (scope.ok) {
if (stream_) cudaStreamSynchronize(stream_);
+ if (read_stream_) cudaStreamSynchronize(read_stream_);
cache_.close();
if (d_x_) cudaFree(d_x_);
if (d_out_) cudaFree(d_out_);
@@ -104,9 +106,11 @@ void RemoteExperts::close() {
if (h_out_) cudaFreeHost(h_out_);
if (h_meta_) cudaFreeHost(h_meta_);
if (stream_) cudaStreamDestroy(stream_);
+ if (read_stream_) cudaStreamDestroy(read_stream_);
}
device_ = -1;
stream_ = nullptr;
+ read_stream_ = nullptr;
h_x_ = h_out_ = d_x_ = d_out_ = nullptr;
h_meta_ = d_meta_ = nullptr;
d_q8_ = nullptr;
@@ -204,6 +208,10 @@ bool RemoteExperts::open(int device, int slots, int64_t layers, int64_t experts,
check(cudaMalloc(&d_scratch_, scratch), "scratch", err, device) &&
check(cudaMalloc(&d_meta_, meta_bytes), "group metadata", err, device);
if (!allocated) { close(); return false; }
+ if (!check(cudaStreamCreateWithFlags(&read_stream_, cudaStreamNonBlocking), "cache read stream", err, device)) {
+ close();
+ return false;
+ }
// Zero-copy: the helper reads its input from, and writes its compact rows into, the pinned host buffers
// directly - two copies fewer per layer, each of which is a PCIe round trip. STRATA_REMOTE_ZEROCOPY=0 copies.
const char* zc = std::getenv("STRATA_REMOTE_ZEROCOPY");
@@ -338,4 +346,111 @@ bool RemoteExperts::finish(float* out, std::string& err) {
return true;
}
+bool RemoteExperts::copy_cached_blobs(const int32_t* layers, const int32_t* experts, uint8_t* const* dst,
+ size_t n, uint8_t* hit, std::string& err) {
+ std::fill(hit, hit + n, 0);
+ if (device_ < 0 || read_stream_ == nullptr || n == 0) return true;
+ const auto& lay = strata::kernels::cpu::expert_layout();
+ DeviceScope scope(device_);
+ if (!scope.ok) { err = scope.error(device_); return false; }
+ std::lock_guard<std::mutex> lock(read_mu_);
+ bool queued = false;
+ for (size_t i = 0; i < n; ++i) {
+ if (dst[i] == nullptr) continue;
+ const int32_t slot = cache_.slot_of(layers[i], experts[i]);
+ if (slot < 0) continue;
+ const size_t bytes = (size_t) lay.blob_bytes(layers[i]);
+ if (!check(cudaMemcpyAsync(dst[i], cache_.device_slot(slot), bytes, cudaMemcpyDeviceToHost, read_stream_),
+ "cache read", err, device_)) {
+ // Nothing may still be writing a caller's buffer when this returns. If the drain succeeds, the
+ // hits queued before the failure are complete and the caller may keep them; if it does not,
+ // forget every hit and let the caller refill all of them from its fallback.
+ if (cudaStreamSynchronize(read_stream_) != cudaSuccess) std::fill(hit, hit + n, 0);
+ return false;
+ }
+ hit[i] = 1;
+ queued = true;
+ }
+ if (queued && !check(cudaStreamSynchronize(read_stream_), "cache read wait", err, device_)) {
+ std::fill(hit, hit + n, 0); // a failed wait means no copied buffer may be trusted
+ return false;
+ }
+ return true;
+}
+
+bool RemotePrefillSource::copy_blob(int64_t layer, int64_t expert, uint8_t* dst) {
+ if (dst != nullptr && from_helper(layer, expert)) {
+ const int32_t l = (int32_t) layer, e = (int32_t) expert;
+ uint8_t* d = dst;
+ std::string err;
+ for (RemoteExperts* h : helpers_) {
+ uint8_t got = 0;
+ const bool ok = h->copy_cached_blobs(&l, &e, &d, 1, &got, err);
+ if (got) {
+ helper_blobs_.fetch_add(1, std::memory_order_relaxed);
+ helper_bytes_.fetch_add(strata::kernels::cpu::expert_layout().blob_bytes(layer),
+ std::memory_order_relaxed);
+ return true;
+ }
+ if (!ok) break;
+ }
+ warn(err);
+ }
+ return fallback_.copy_blob(layer, expert, dst);
+}
+
+bool RemotePrefillSource::copy_blobs(const int32_t* layers, const int32_t* experts, uint8_t* const* dst, size_t n) {
+ if (helpers_.empty() || n == 0) return fallback_.copy_blobs(layers, experts, dst, n);
+ thread_local std::vector<int32_t> hl, he;
+ thread_local std::vector<uint8_t*> hd;
+ thread_local std::vector<size_t> idx;
+ thread_local std::vector<uint8_t> got;
+ thread_local std::vector<uint8_t> served;
+ thread_local std::vector<int32_t> ml, me;
+ thread_local std::vector<uint8_t*> md;
+ thread_local std::vector<int> which;
+ which.assign(n, -1);
+ served.assign(n, 0);
+ for (size_t i = 0; i < n; ++i) {
+ if (dst[i] == nullptr) continue;
+ for (size_t k = 0; k < helpers_.size(); ++k)
+ if (helpers_[k]->holds(layers[i], experts[i])) { which[i] = (int) k; break; }
+ }
+ // One stream batch per helper, so several hits pay one wait; the misses go to the file source in one
+ // call, which keeps its own batched-read merging for them.
+ uint64_t blobs = 0, bytes = 0;
+ const auto& lay = strata::kernels::cpu::expert_layout();
+ for (size_t k = 0; k < helpers_.size(); ++k) {
+ hl.clear(); he.clear(); hd.clear(); idx.clear();
+ for (size_t i = 0; i < n; ++i)
+ if (which[i] == (int) k) {
+ hl.push_back(layers[i]); he.push_back(experts[i]); hd.push_back(dst[i]); idx.push_back(i);
+ }
+ if (hl.empty()) continue;
+ got.assign(hl.size(), 0);
+ std::string err;
+ if (!helpers_[k]->copy_cached_blobs(hl.data(), he.data(), hd.data(), hl.size(), got.data(), err)) warn(err);
+ for (size_t j = 0; j < got.size(); ++j)
+ if (got[j]) {
+ served[idx[j]] = 1;
+ ++blobs;
+ bytes += lay.blob_bytes(hl[j]);
+ }
+ }
+ if (blobs != 0) {
+ helper_blobs_.fetch_add(blobs, std::memory_order_relaxed);
+ helper_bytes_.fetch_add(bytes, std::memory_order_relaxed);
+ }
+ ml.clear(); me.clear(); md.clear();
+ for (size_t i = 0; i < n; ++i)
+ if (!served[i]) { ml.push_back(layers[i]); me.push_back(experts[i]); md.push_back(dst[i]); }
+ if (ml.empty()) return true;
+ return fallback_.copy_blobs(ml.data(), me.data(), md.data(), ml.size());
+}
+
+void RemotePrefillSource::warn(const std::string& err) {
+ if (err.empty() || warned_.exchange(true)) return;
+ std::fprintf(stderr, "prefill: a helper cache read failed (%s); the file source fills that blob instead\n",
+ err.c_str());
+}
} // namespace strata::core
diff --git a/src/program/generate.cpp b/src/program/generate.cpp
index 591edd862..45d5350d6 100644
--- a/src/program/generate.cpp
+++ b/src/program/generate.cpp
@@ -6621,6 +6621,23 @@ int main(int argc, char** argv) {
// neither fires, plain one-token-per-round decoding - slower, never wrong: the verify window still
// confirms every emitted token against the real model regardless of where the draft came from.
const bool use_mtp = !o.mtp.empty();
+ // STRATA_PREFILL_HELPER_SOURCE (opt-in): the prompt path may take a blob a helper's VRAM cache already
+ // holds from that cache instead of reading the files again. The helpers are idle while a prompt is read
+ // (the serve path is serial: no batch slots), so the copy needs no ordering against their kernel streams.
+ // Everything else - the fallback's batched unbuffered reads, its pinned RAM copy, the prompt path's own
+ // decisions - is forwarded unchanged. Default off: the prompt path's source is srcp, exactly as before.
+ std::vector<strata::core::RemoteExperts*> prefill_helpers;
+ for (int r = 0; r < drive.d.remote_count; ++r) prefill_helpers.push_back(drive.d.remote[r]);
+ std::unique_ptr<strata::core::RemotePrefillSource> prefill_helper_src;
+ strata::core::ExpertSource* prefill_src = srcp;
+ uint64_t helper_blobs_before = 0, helper_bytes_before = 0;
+ if (const char* hv = std::getenv("STRATA_PREFILL_HELPER_SOURCE"); hv != nullptr && std::atoi(hv) != 0 &&
+ srcp != nullptr && !multi_gpu && stages.empty() && o.batch <= 0 && !prefill_helpers.empty()) {
+ prefill_helper_src = std::make_unique<strata::core::RemotePrefillSource>(*srcp, prefill_helpers);
+ prefill_src = prefill_helper_src.get();
+ std::fprintf(stderr, "strata serve: the prompt path reads the experts a helper cache holds from that "
+ "cache (STRATA_PREFILL_HELPER_SOURCE)\n");
+ }
strata::prefill::Prefill sp;
// the pool is idle while a prompt is read unless batch slots decode between its parts; with
// STRATA_PREFILL_CPU_SHARE the staged-chunk limit before the chunk below sizes the loans (bytes_needed reads it)
@@ -6949,7 +6966,7 @@ int main(int argc, char** argv) {
}
if (multi_gpu) sp.set_stage(0, split_at[0], &stages[0]->sp);
if (share_pool) sp.set_cpu_pool(&pool);
- if (!sp.init(wt, g, ss, srcp, &xcache, host_res.data(), o.prefill_chunk, main_cs, err, borrow, borrow_bytes))
+ if (!sp.init(wt, g, ss, prefill_src, &xcache, host_res.data(), o.prefill_chunk, main_cs, err, borrow, borrow_bytes))
return err.find("do not fit") != std::string::npos ? 2 : 1;
return 0;
};
@@ -11687,6 +11704,14 @@ int main(int argc, char** argv) {
(double) (remote_experts[(size_t) r].full_row_bytes() - full_before[(size_t) r]) / 1048576.0,
remote_experts[(size_t) r].ms_begin() - begin_before[(size_t) r],
remote_experts[(size_t) r].ms_wait() - wait_before[(size_t) r]);
+ if (prefill_helper_src) {
+ const uint64_t blobs = prefill_helper_src->helper_blobs(), bytes = prefill_helper_src->helper_bytes();
+ std::fprintf(stderr, "strata serve: prefill helper source: %lld blobs / %.1f MiB taken from a helper's "
+ "cache in this request\n",
+ (long long) (blobs - helper_blobs_before), (double) (bytes - helper_bytes_before) / 1048576.0);
+ helper_blobs_before = blobs;
+ helper_bytes_before = bytes;
+ }
}
save_profile("exit"); // #477: QUIT, or the server closed stdin
return 0;