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

Add optional multi-GPU expert caches and compact transfers

Daerdaal109a209e532c
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 929d6a6d2..22512b983 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -245,7 +245,7 @@ if(STRATA_ENABLE_CUDA)
# already links `strata_core` - putting `gdn_layer` in core would make the two mutually dependent. A third
# library is the honest shape of the dependency graph: core knows about devices and weights, kernels know
# about arithmetic, and this one knows the ORDER the arithmetic happens in.
- add_library(strata_engine STATIC src/core/layer.cpp src/core/session.cpp src/core/expert_source.cpp
+ add_library(strata_engine STATIC src/core/layer.cpp src/core/session.cpp src/core/expert_source.cpp src/core/remote_experts.cpp
src/core/expert_cache.cpp src/core/native_head.cpp src/core/native_dense.cpp src/core/verify.cpp src/core/mtp.cpp)
target_include_directories(strata_engine PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include)
target_link_libraries(strata_engine PUBLIC strata_core strata_kernels strata_kernels_cpu CUDA::cudart)
diff --git a/docs/SECOND_GPU.md b/docs/SECOND_GPU.md
new file mode 100644
index 000000000..7eb69dfdd
--- /dev/null
+++ b/docs/SECOND_GPU.md
@@ -0,0 +1,84 @@
+# CUDA1–3 expert experiment
+
+CUDA0 keeps the dense layers, KV/state, MTP and its existing expert cache. Up to
+three independent expert caches fill CUDA1, CUDA2 and CUDA3 in that order. Each
+expert has one owner: CUDA0, one secondary GPU, or the CPU pool. Each secondary
+GPU computes its rows while the CPU pool works; the results return through
+private pinned host buffers before CUDA0 continues the layer. The GPU launches
+can overlap, but each layer waits for all three.
+
+The shipped profile ranks 8,000 `(layer, expert)` pairs. CUDA0 takes its usual
+`--expert-cache auto` allocation. With only CUDA1, it takes the first remaining
+pairs. When CUDA2 or CUDA3 is enabled, the remaining profiled pairs are assigned
+round robin to the secondary GPUs. The ranked list is then extended with all
+other pairs in expert-then-layer order and distributed in the same way. This
+fills the additional VRAM and lets all secondary GPUs see frequent experts, but
+unranked experts may hardly ever be routed. The startup
+log reports slots and GiB per card; each request reports the number of expert
+entries actually computed on each secondary GPU. Remote outputs are packed
+before returning over PCIe/USB4: the request log compares MiB transferred
+with the previous full-row transfer. The input and routing metadata use pinned
+host staging. This reduces transfer traffic and launch overhead, but does not
+release the expert arena in system RAM or significantly change VRAM use.
+
+The optional `--gpu-placement layer` gives each layer to exactly one secondary
+GPU (layer number modulo the number of enabled cards). It fills that card with
+the most frequently routed experts of its layers first, then the unranked ones.
+This can reduce USB4 device switches and synchronization when several secondary
+cards serve the same layer in the default `stripe` mode. All three cards still
+keep their requested expert slots; the primary CUDA0 cache and CPU fallback
+continue to work. The log counts active layer launches on each card, so the
+tradeoff can be measured alongside tokens per second. This placement is
+experimental and may be slower if a given layer needs more than one card's
+compute capacity.
+
+The experiment requires the corresponding visible CUDA devices and a CUDA
+enabled build. Each card must keep at least 512 MiB free. Tiers must be enabled
+in order. On Windows, CUDA registration of the host expert arena is capped at
+8 GiB to leave room for the contexts and MTP on CUDA0. The rest remains
+available to the CPU pool; the PCIe expert path is available only for the
+registered layers. Without secondary GPUs, the original uncapped registration
+behavior applies.
+
+On an existing Linux installation, apply the patch to its source tree, then run:
+
+```sh
+./setup.sh --setup --gpu1-experts 5000 --gpu2-experts 5000 --gpu3-experts 5000
+```
+
+On Windows, from PowerShell in the installation folder:
+
+```powershell
+.\START-HERE.bat --setup --gpu1-experts 5000 --gpu2-experts 5000 --gpu3-experts 5000
+```
+
+To test the layer placement instead, add `--gpu-placement layer` to the setup
+command. To go back, run the same command with `--gpu-placement stripe`. After
+the new engine is built, the mode can also be changed without a rebuild: edit
+`--expert-cache-remote-placement` in `strata-iq3_xxs.json` from `layer` to
+`stripe` or vice versa and restart the server. If the argument is absent, the
+default is `stripe`.
+
+Choose the same model, size, context and image settings as your current
+installation when prompted. Setup recompiles the engine, updates its server
+configuration, and starts it. Later starts keep those settings. To tune the
+slots without recompiling, edit the values after `--expert-cache-device1`,
+`--expert-cache-device2` and `--expert-cache-device3` in the stored
+`strata-iq3_xxs.json`, then restart with `.\run-iq3_xxs.bat`.
+
+Compare identical requests at one, two and four GPUs, preferably with several
+repeats. VRAM use alone does not show useful offload: compare the per-request
+CUDA1–3 counts and tokens per second. More GPU contexts and synchronization
+may lower the speed. Prompt prefill still uses CUDA0; secondary GPUs serve
+decode, including MTP verification. No peer-to-peer access is required.
+
+Longer contexts reserve more KV/state memory on CUDA0, which reduces its
+automatic expert cache. On a 64 GB PC `setup.py` limits IQ3_XXS to 128K even
+if 262K was selected; the secondary caches still require the host expert arena.
+To try 262K on 64 GB, choose Q2_0 or IQ2_XS instead and check that CUDA0 still
+has enough free VRAM after loading. Benchmark long prompts separately from
+short decode requests.
+
+The existing warning about the CUDA0 expert-cache GPU hit path still applies:
+its outputs diverge from cache-off runs. Treat performance as experimental
+until the generated tokens have been validated.
diff --git a/include/strata/core/expert_source.hpp b/include/strata/core/expert_source.hpp
index c64bf4e7d..adec516e6 100644
--- a/include/strata/core/expert_source.hpp
+++ b/include/strata/core/expert_source.hpp
@@ -31,6 +31,8 @@
namespace strata::core {
+class RemoteExperts;
+
/// Where one routed expert's bytes come from.
///
/// Phase 2 has NO cache (`phase-2-correct-engine.md`: hit rate `h = 0`), so the only implementation is a
@@ -92,6 +94,8 @@ struct GpuPlanSink {
struct ExpertDispatch {
strata::kernels::cpu::ExpertPool* pool = nullptr;
ExpertSource* src = nullptr;
+ RemoteExperts* remote[3] = {}; ///< optional CUDA1..3 tiers for otherwise CPU-served rows
+ int remote_count = 0;
int64_t n_expert = strata::kernels::cpu::NE;
/// Counters, for the driver to report rather than for control flow.
@@ -320,7 +324,8 @@ public:
/// Allocates and loads `<pack_dir>/experts.bin`. Prints nothing; the caller reports `note()` and the load
/// rate, because those are the two numbers that say whether the arena is the one that was asked for.
- bool open(const std::string& pack_dir, int64_t n_layers, int64_t n_expert, int threads, std::string& err);
+ bool open(const std::string& pack_dir, int64_t n_layers, int64_t n_expert, int threads, std::string& err,
+ uint64_t max_pinned_bytes = 0);
/// Plan v0.3 P6: a native pack without experts.bin takes its experts from the model's shard 1.
void set_gguf(const std::string& shard1) { gguf_ = shard1; }
void close();
diff --git a/include/strata/core/pinned.hpp b/include/strata/core/pinned.hpp
index af704691e..82b988f52 100644
--- a/include/strata/core/pinned.hpp
+++ b/include/strata/core/pinned.hpp
@@ -39,7 +39,8 @@ struct PinnedArena {
explicit PinnedArena(uint64_t bytes, uint64_t slice = 0);
/// Plan v0.3 P6: slices of different sizes (one per layer of a native pack), given as their start offsets
/// followed by the end of the last one. `slice_starts` holds the registered ones.
- PinnedArena(uint64_t bytes, const std::vector<uint64_t>& bounds);
+ /// `max_pinned_bytes`: optional cap on CUDA registration. 0 preserves the normal unrestricted path.
+ PinnedArena(uint64_t bytes, const std::vector<uint64_t>& bounds, uint64_t max_pinned_bytes = 0);
std::vector<uint64_t> slice_starts;
~PinnedArena();
PinnedArena(const PinnedArena&) = delete;
diff --git a/include/strata/core/remote_experts.hpp b/include/strata/core/remote_experts.hpp
new file mode 100644
index 000000000..4d0e64854
--- /dev/null
+++ b/include/strata/core/remote_experts.hpp
@@ -0,0 +1,78 @@
+#pragma once
+
+#include "strata/core/expert_cache.hpp"
+#include "strata/core/expert_source.hpp"
+
+#include <cuda_runtime.h>
+
+#include <cstdint>
+#include <string>
+#include <utility>
+#include <vector>
+
+namespace strata::core {
+
+/// A static, profile-filled expert tier on another CUDA device. CUDA0 keeps all
+/// dense weights and state; results return through the existing pinned CPU rows.
+class RemoteExperts {
+public:
+ RemoteExperts() = default;
+ ~RemoteExperts();
+ RemoteExperts(const RemoteExperts&) = delete;
+ RemoteExperts& operator=(const RemoteExperts&) = delete;
+
+ /// Initialise the device before the host expert arena registers
+ /// tens of GiB of portable mapped memory with CUDA.
+ static bool preflight(int device, double& free_gib, std::string& err);
+ bool open(int device, int slots, int64_t layers, int64_t experts,
+ const std::vector<std::pair<int32_t, int32_t>>& ranked,
+ const ExpertCache& primary, ExpertSource& source,
+ std::vector<uint8_t>& claimed, std::string& err);
+ void close();
+
+ /// `kind` is the primary verifier's classification (-1 = CPU candidate),
+ /// or null on the one-token path. Entries already served on CUDA0 are excluded.
+ bool begin(int64_t layer, const float* x, const int32_t* ids, int64_t n_tok,
+ int64_t k, const int32_t* kind, const int32_t* primary_res,
+ std::string& err);
+ bool owns(int64_t index) const { return owned_[(size_t) index] != 0; }
+ bool finish(float* out, std::string& err);
+ int64_t resident() const { return cache_.resident(); }
+ int64_t computed() const { return computed_; }
+ int64_t launched_layers() const { return launched_layers_; }
+ double gib() const { return cache_.gib(); }
+ uint64_t returned_bytes() const { return returned_bytes_; }
+ uint64_t full_row_bytes() const { return full_row_bytes_; }
+
+private:
+ int device_ = -1;
+ int64_t n_expert_ = 0;
+ int32_t groups_ = 0;
+ int64_t computed_ = 0;
+ int64_t launched_layers_ = 0;
+ uint64_t returned_bytes_ = 0;
+ uint64_t full_row_bytes_ = 0;
+ ExpertCache cache_;
+ cudaStream_t stream_ = nullptr;
+ float* h_x_ = nullptr;
+ float* h_out_ = nullptr;
+ void* h_meta_ = nullptr;
+ float* d_x_ = nullptr;
+ float* d_out_ = nullptr;
+ uint8_t* d_q8_ = nullptr;
+ float* d_scales_ = nullptr;
+ void* d_scratch_ = nullptr;
+ void* d_meta_ = nullptr; ///< one contiguous upload of grouped indices, instead of five small copies
+ int32_t* d_start_ = nullptr;
+ int32_t* d_dst_ = nullptr;
+ int32_t* d_tok_ = nullptr;
+ int32_t* d_count_ = nullptr;
+ unsigned long long* d_ptr_ = nullptr;
+ std::vector<uint8_t> owned_;
+ std::vector<uint8_t> layers_present_;
+ std::vector<int32_t> group_of_, group_id_;
+ std::vector<int32_t> start_, dst_, tok_, original_row_;
+ std::vector<unsigned long long> ptr_;
+};
+
+} // namespace strata::core
diff --git a/src/core/expert_source.cpp b/src/core/expert_source.cpp
index 0ab1ce13c..6533894b8 100644
--- a/src/core/expert_source.cpp
+++ b/src/core/expert_source.cpp
@@ -1,5 +1,6 @@
// src/core/expert_source.cpp - the adapter. See the header for the three clauses of the contract.
#include "strata/core/expert_source.hpp"
+#include "strata/core/remote_experts.hpp"
#include "strata/kernels/cpu/expert_layout.hpp"
#include "strata/core/pinned.hpp"
@@ -199,6 +200,22 @@ void expert_pool_dispatch(void* user, const float* x_f, const int32_t* ids, cons
const bool use_hits = graph_hits || (d.hits_ready() && d.decided);
int64_t njobs = 0;
+ if (d.remote_count > 0) {
+ int32_t kind[32];
+ if (k > 32) {
+ d.failed = true; d.fail = "remote experts: routing width exceeds 32"; return;
+ }
+ for (int64_t i = 0; i < k; ++i)
+ kind[i] = use_hits && ids[i] >= 0 && ids[i] < d.n_expert && (graph_hits
+ ? d.host_res[(size_t) d.layers * (size_t) d.n_expert + (size_t) ids[i]] >= 0
+ : d.is_hit[(size_t) i] != 0) ? 0 : -1;
+ static thread_local std::string remote_error;
+ for (int r = 0; r < d.remote_count; ++r)
+ if (!d.remote[r]->begin(d.layers, x_f, ids, 1, k, kind, d.host_res, remote_error)) {
+ d.failed = true; d.fail = remote_error.c_str(); d.fail_layer = d.layers; return;
+ }
+ }
+
for (int64_t i = 0; i < k; ++i) {
const int64_t e = ids[i];
if (e < 0 || e >= d.n_expert) {
@@ -231,6 +248,13 @@ void expert_pool_dispatch(void* user, const float* x_f, const int32_t* ids, cons
}
if (graph_hits) ++d.cache_refused; // token graph: a miss (nothing is admitted during a token)
+ bool remote_owns = false;
+ for (int r = 0; r < d.remote_count; ++r) remote_owns |= d.remote[r]->owns(i);
+ if (remote_owns) {
+ std::memset(out + (size_t) i * (size_t) n_embd, 0, (size_t) n_embd * sizeof(float));
+ continue;
+ }
+
// `njobs` indexes the JOB ARRAY and `i` indexes the OUTPUT - they are the same only when nothing is a
// hit, and using one for the other is how a hit's row would get two experts summed into it.
ExpertJob& j = d.jobs[(size_t) njobs++];
@@ -244,6 +268,13 @@ void expert_pool_dispatch(void* user, const float* x_f, const int32_t* ids, cons
// Plan v0.3 P4: rows of every expert across all threads (bitwise the same as `run`).
if (d.split_rows) d.pool->run_split(d.jobs.data(), (int) njobs);
else d.pool->run(d.jobs.data(), (int) njobs);
+ if (d.remote_count > 0) {
+ static thread_local std::string remote_error;
+ for (int r = 0; r < d.remote_count; ++r)
+ if (!d.remote[r]->finish(out, remote_error)) {
+ d.failed = true; d.fail = remote_error.c_str(); d.fail_layer = d.layers; return;
+ }
+ }
++d.layers;
d.experts += k;
}
@@ -366,6 +397,15 @@ void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32
d.host_res[(size_t) d.layers * (size_t) d.n_expert + (size_t) e] >= 0) ? 0 : -1;
}
}
+ if (d.remote_count > 0) {
+ static thread_local std::string remote_error;
+ for (int r = 0; r < d.remote_count; ++r) {
+ if (!d.remote[r]->begin(d.layers, x_f, ids, n_tok, k, kind, d.host_res, remote_error)) {
+ d.failed = true; d.fail = remote_error.c_str(); d.fail_layer = d.layers; return;
+ }
+ for (int64_t i = 0; i < n; ++i) if (d.remote[r]->owns(i)) kind[i] = 2;
+ }
+ }
const auto c1 = std::chrono::steady_clock::now();
if (native && lay.fmt[(size_t) d.layers].gu_type == 42) // a native Q2_0 pack: the Q2_0 kernels' activations
for (int64_t t = 0; t < n_tok; ++t) act_quant_any(x_f + (size_t) t * H, H, d.act_multi[(size_t) t]);
@@ -388,7 +428,7 @@ void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32
d.fail_expert = e;
return;
}
- if (kind[i] >= 0) { // the GPU computes this entry (a VRAM hit or a PCIe read)
+ if (kind[i] >= 0) { // CUDA0, PCIe, or a remote result staged into this row below
if (kind[i] == 0) ++d.cache_hits;
std::memset(row, 0, (size_t) H * sizeof(float));
continue;
@@ -421,6 +461,13 @@ void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32
pt("run", njobs);
if (native) d.pool->run_split_multi_native(lay.fmt[(size_t) d.layers], d.jobs_multi.data(), njobs);
else d.pool->run_split_multi(d.jobs_multi.data(), njobs);
+ if (d.remote_count > 0) {
+ static thread_local std::string remote_error;
+ for (int r = 0; r < d.remote_count; ++r)
+ if (!d.remote[r]->finish(out, remote_error)) {
+ d.failed = true; d.fail = remote_error.c_str(); d.fail_layer = d.layers; return;
+ }
+ }
const auto c4 = std::chrono::steady_clock::now();
pt("ran");
auto ms = [](auto a, auto b) { return std::chrono::duration<double, std::milli>(b - a).count(); };
@@ -616,7 +663,7 @@ LoadStats load_experts_gguf(const std::string& gguf, uint8_t* dst, const strata:
ArenaExpertSource::~ArenaExpertSource() { close(); }
bool ArenaExpertSource::open(const std::string& pack_dir, int64_t n_layers, int64_t n_expert, int threads,
- std::string& err) {
+ std::string& err, uint64_t max_pinned_bytes) {
close();
const std::string path = pack_dir + "/experts.bin";
// plan v0.3 P6: the layout (canonical, or a native pack's per-layer blobs) was loaded by the driver
@@ -657,7 +704,7 @@ bool ArenaExpertSource::open(const std::string& pack_dir, int64_t n_layers, int6
lbytes.push_back(lay.blob_bytes(l) * (uint64_t) n_expert);
}
bounds.push_back(want);
- PinnedArena* a = new PinnedArena(want + (uint64_t) blob, bounds);
+ PinnedArena* a = new PinnedArena(want + (uint64_t) blob, bounds, max_pinned_bytes);
if (!a->valid()) {
delete a;
err = "ArenaExpertSource: the arena could not be reserved (" + std::to_string(want) + " B)";
diff --git a/src/core/mtp.cpp b/src/core/mtp.cpp
index 891f9b909..0e86707b0 100644
--- a/src/core/mtp.cpp
+++ b/src/core/mtp.cpp
@@ -131,7 +131,15 @@ bool MtpDrafter::load(const std::string& rt_dir, const ModelGeometry& g, Session
}
std::vector<uint8_t> blob;
if (!read_file(rt_dir + "/dense.bin", blob)) { err = "mtp: cannot read dense.bin"; return false; }
- if (cudaMalloc((void**) &dense_, blob.size()) != cudaSuccess) { err = "mtp: dense weights do not fit"; return false; }
+ const cudaError_t alloc = cudaMalloc((void**) &dense_, blob.size());
+ if (alloc != cudaSuccess) {
+ size_t free_bytes = 0, total_bytes = 0;
+ const cudaError_t info = cudaMemGetInfo(&free_bytes, &total_bytes);
+ err = "mtp: dense weights allocation failed (" + std::string(cudaGetErrorString(alloc)) +
+ "), requested " + std::to_string(blob.size() >> 20) + " MiB, CUDA0 free " +
+ (info == cudaSuccess ? std::to_string(free_bytes >> 20) + " MiB" : "unknown");
+ return false;
+ }
cudaMemcpy(dense_, blob.data(), blob.size(), cudaMemcpyHostToDevice);
vram_ += blob.size();
}
diff --git a/src/core/pinned.cu b/src/core/pinned.cu
index 90c22d17c..44cd005c7 100644
--- a/src/core/pinned.cu
+++ b/src/core/pinned.cu
@@ -129,23 +129,27 @@ PinnedArena::PinnedArena(uint64_t bytes, uint64_t slice) : PinnedArena(bytes, un
if (slice_bytes) slice_bytes = slice; // sliced registration: record the uniform size
}
-PinnedArena::PinnedArena(uint64_t bytes, const std::vector<uint64_t>& bounds) : capacity(bytes) {
+PinnedArena::PinnedArena(uint64_t bytes, const std::vector<uint64_t>& bounds,
+ uint64_t max_pinned_bytes) : capacity(bytes) {
if (bytes == 0) return;
base = reserve(bytes, backing, note);
// Register with CUDA BEFORE any page is touched: cudaHostRegister pins what is resident now, and a region
// that has already been faulted in page by page is far more expensive to register and may fail outright.
if (base) {
- const cudaError_t e = cudaHostRegister(base, (size_t) bytes, cudaHostRegisterPortable | cudaHostRegisterMapped);
- if (e == cudaSuccess) {
+ const bool capped = max_pinned_bytes > 0 && max_pinned_bytes < bytes && bounds.size() >= 2;
+ const cudaError_t e = capped ? cudaSuccess :
+ cudaHostRegister(base, (size_t) bytes, cudaHostRegisterPortable | cudaHostRegisterMapped);
+ if (!capped && e == cudaSuccess) {
note = "cudaHostRegister PORTABLE ok; " + note;
registered_bytes = bytes;
- } else if (bounds.size() >= 2 && clear_error()) {
+ } else if (bounds.size() >= 2 && (capped || clear_error())) {
// Plan v0.3 P5: the whole range is refused, so pin it slice by slice from the start. The rest stays
// resident through the working-set lock below. (P6: slices may differ in size, one per layer.)
slice_bytes = 1; // sliced; the uniform constructor records the size
for (size_t i = 0; i + 1 < bounds.size(); ++i) {
const uint64_t off = bounds[i], n = bounds[i + 1] - bounds[i];
+ if (capped && (off > max_pinned_bytes || n > max_pinned_bytes - off)) break;
if (cudaHostRegister((uint8_t*) base + off, (size_t) n, cudaHostRegisterPortable | cudaHostRegisterMapped) != cudaSuccess) {
(void) cudaGetLastError();
break;
@@ -154,7 +158,9 @@ PinnedArena::PinnedArena(uint64_t bytes, const std::vector<uint64_t>& bounds) :
registered_bytes = off + n;
++registered_slices;
}
- note = "cudaHostRegister of the whole arena FAILED (" + std::string(cudaGetErrorString(e)) + "); " +
+ note = (capped ? "cudaHostRegister limited to " + std::to_string(max_pinned_bytes >> 30) +
+ " GiB for CUDA1; " :
+ "cudaHostRegister of the whole arena FAILED (" + std::string(cudaGetErrorString(e)) + "); ") +
std::to_string(registered_slices) + " slices pinned (" + std::to_string(registered_bytes >> 30) +
" GiB); " + note;
if (registered_bytes < bytes) {
diff --git a/src/core/remote_experts.cpp b/src/core/remote_experts.cpp
new file mode 100644
index 000000000..10b205f0b
--- /dev/null
+++ b/src/core/remote_experts.cpp
@@ -0,0 +1,305 @@
+#include "strata/core/remote_experts.hpp"
+
+#include "strata/kernels/cpu/expert_layout.hpp"
+#include "strata/kernels/iq_kernels.hpp"
+#include "strata/kernels/quantize_act.hpp"
+#include "strata/kernels/s2_expert_grouped.hpp"
+
+#include <algorithm>
+#include <cstring>
+
+namespace strata::core {
+namespace {
+constexpr int64_t H = strata::kernels::cpu::H;
+constexpr int64_t FF = strata::kernels::cpu::FF;
+constexpr int64_t CAP = strata::kernels::cpu::MAXT * 10;
+
+// Small enough to copy as one pinned buffer per layer. The kernels read the
+// individual arrays through pointers into the same device allocation.
+struct RemoteMeta {
+ unsigned long long ptr[CAP];
+ int32_t start[CAP + 1];
+ int32_t dst[CAP];
+ int32_t tok[CAP];
+ int32_t count;
+};
+
+struct DeviceScope {
+ int previous = -1;
+ bool ok = false;
+ cudaError_t status = cudaSuccess;
+ const char* failed_step = nullptr;
+ explicit DeviceScope(int device) {
+ status = cudaGetDevice(&previous);
+ if (status != cudaSuccess) {
+ previous = -1;
+ failed_step = "cudaGetDevice";
+ return;
+ }
+ status = cudaSetDevice(device);
+ if (status != cudaSuccess) {
+ failed_step = "cudaSetDevice";
+ return;
+ }
+ ok = true;
+ }
+ ~DeviceScope() { if (previous >= 0) cudaSetDevice(previous); }
+ std::string error(int device) const {
+ return std::string("CUDA") + std::to_string(device) + " experts: " +
+ (failed_step ? failed_step : "device switch") +
+ "(" + std::to_string(device) + ") failed: " + cudaGetErrorString(status) +
+ " (CUDA error " + std::to_string((int) status) + ")";
+ }
+};
+
+bool check(cudaError_t result, const char* what, std::string& err, int device) {
+ if (result == cudaSuccess) return true;
+ err = "CUDA" + std::to_string(device) + " experts: " + what + ": " + cudaGetErrorString(result);
+ return false;
+}
+} // namespace
+
+RemoteExperts::~RemoteExperts() { close(); }
+
+bool RemoteExperts::preflight(int device, double& free_gib, std::string& err) {
+ int count = 0;
+ if (!check(cudaGetDeviceCount(&count), "cudaGetDeviceCount", err, device)) return false;
+ if (device < 1 || device >= count) {
+ err = "CUDA" + std::to_string(device) + " experts: CUDA device is not visible";
+ return false;
+ }
+ DeviceScope scope(device);
+ if (!scope.ok) { err = scope.error(device); return false; }
+ size_t free_bytes = 0, total_bytes = 0;
+ if (!check(cudaMemGetInfo(&free_bytes, &total_bytes), "preflight free memory", err, device)) return false;
+ free_gib = (double) free_bytes / 1073741824.0;
+ return true;
+}
+
+void RemoteExperts::close() {
+ if (device_ < 0) return;
+ DeviceScope scope(device_);
+ if (scope.ok) {
+ if (stream_) cudaStreamSynchronize(stream_);
+ cache_.close();
+ if (d_x_) cudaFree(d_x_);
+ if (d_out_) cudaFree(d_out_);
+ if (d_q8_) cudaFree(d_q8_);
+ if (d_scales_) cudaFree(d_scales_);
+ if (d_scratch_) cudaFree(d_scratch_);
+ if (d_meta_) cudaFree(d_meta_);
+ if (h_x_) cudaFreeHost(h_x_);
+ if (h_out_) cudaFreeHost(h_out_);
+ if (h_meta_) cudaFreeHost(h_meta_);
+ if (stream_) cudaStreamDestroy(stream_);
+ }
+ device_ = -1;
+ stream_ = nullptr;
+ h_x_ = h_out_ = d_x_ = d_out_ = nullptr;
+ h_meta_ = d_meta_ = nullptr;
+ d_q8_ = nullptr;
+ d_scales_ = nullptr;
+ d_scratch_ = nullptr;
+ d_start_ = d_dst_ = d_tok_ = d_count_ = nullptr;
+ d_ptr_ = nullptr;
+ original_row_.clear();
+ layers_present_.clear();
+}
+
+bool RemoteExperts::open(int device, int slots, int64_t layers, int64_t experts,
+ const std::vector<std::pair<int32_t, int32_t>>& ranked,
+ const ExpertCache& primary, ExpertSource& source,
+ std::vector<uint8_t>& claimed, std::string& err) {
+ close();
+ int count = 0;
+ if (!check(cudaGetDeviceCount(&count), "cudaGetDeviceCount", err, device)) return false;
+ if (device < 1 || device >= count || slots <= 0 || ranked.empty() ||
+ layers <= 0 || experts <= 0 || claimed.size() != (size_t) layers * (size_t) experts) {
+ err = "CUDA" + std::to_string(device) + " experts: need the device, ranked experts and positive slot count";
+ return false;
+ }
+ DeviceScope scope(device);
+ if (!scope.ok) { err = scope.error(device); return false; }
+ device_ = device;
+ n_expert_ = experts;
+ const auto& lay = strata::kernels::cpu::expert_layout();
+ std::vector<std::pair<int32_t, int32_t>> selected;
+ selected.reserve((size_t) slots);
+ std::vector<uint8_t> picked(claimed.size(), 0);
+ for (const auto& pair : ranked) {
+ if (pair.first < 0 || pair.first >= layers || pair.second < 0 || pair.second >= experts) continue;
+ const size_t index = (size_t) pair.first * (size_t) experts + (size_t) pair.second;
+ if (primary.slot_of(pair.first, pair.second) < 0 && !claimed[index] && !picked[index]) {
+ selected.push_back(pair);
+ picked[index] = 1;
+ if ((int) selected.size() >= slots) break;
+ }
+ }
+ if (selected.empty()) { err = "CUDA" + std::to_string(device) + " experts: no unclaimed experts remain"; close(); return false; }
+ std::vector<int64_t> sizes;
+ if (lay.native) {
+ sizes.reserve(selected.size());
+ for (const auto& pair : selected) sizes.push_back((int64_t) lay.blob_bytes(pair.first));
+ }
+ size_t free_bytes = 0, total_bytes = 0;
+ if (!check(cudaMemGetInfo(&free_bytes, &total_bytes), "free memory", err, device)) { close(); return false; }
+ uint64_t needed = 0;
+ for (const auto& pair : selected)
+ needed += lay.native ? (lay.blob_bytes(pair.first) + 255) / 256 * 256 : lay.max_blob;
+ // Leave room for the CUDA context, staging and later driver allocations, especially under WDDM.
+ if (needed + (512ull << 20) > free_bytes) {
+ err = "CUDA" + std::to_string(device) + " experts: slots leave less than 512 MiB free; reduce --expert-cache-device" + std::to_string(device);
+ close(); return false;
+ }
+ const bool cache_ok = lay.native ? cache_.open_sized(sizes, layers, experts, err)
+ : cache_.open((int64_t) selected.size(), layers, experts,
+ (int64_t) lay.max_blob, err);
+ if (!cache_ok) { err = "CUDA" + std::to_string(device) + " experts: " + err; close(); return false; }
+ for (const auto& pair : selected) {
+ const int32_t slot = cache_.admit(pair.first, pair.second);
+ const uint8_t* blob = source.blob(pair.first, pair.second);
+ if (slot < 0 || !blob || !cache_.fill_slot_blocking(slot, blob, err, (int64_t) lay.blob_bytes(pair.first))) {
+ err = "CUDA" + std::to_string(device) + " experts: " +
+ (err.empty() ? "cache fill failed" : err);
+ close(); return false;
+ }
+ }
+ const auto& first = selected.front();
+ if (!cache_.verify_slot(cache_.slot_of(first.first, first.second), source.blob(first.first, first.second),
+ err, (int64_t) lay.blob_bytes(first.first))) {
+ err = "CUDA" + std::to_string(device) + " experts: " + err;
+ close(); return false;
+ }
+
+ const size_t scratch = std::max<size_t>(
+ (size_t) strata::kernels::moe_hit_grouped_scratch_bytes(CAP, H, FF),
+ strata::kernels::native_expert_scratch_bytes(CAP, FF));
+ const bool allocated =
+ check(cudaStreamCreateWithFlags(&stream_, cudaStreamNonBlocking), "stream", err, device) &&
+ check(cudaHostAlloc((void**) &h_x_, (size_t) CAP * H * sizeof(float), cudaHostAllocPortable), "input staging", err, device) &&
+ check(cudaHostAlloc((void**) &h_out_, (size_t) CAP * H * sizeof(float), cudaHostAllocPortable), "result staging", err, device) &&
+ check(cudaHostAlloc(&h_meta_, sizeof(RemoteMeta), cudaHostAllocPortable), "metadata staging", err, device) &&
+ check(cudaMalloc((void**) &d_x_, (size_t) CAP * H * sizeof(float)), "input", err, device) &&
+ check(cudaMalloc((void**) &d_out_, (size_t) CAP * H * sizeof(float)), "result", err, device) &&
+ check(cudaMalloc((void**) &d_q8_, (size_t) CAP * (H / 32) * 36), "activation", err, device) &&
+ check(cudaMalloc((void**) &d_scales_, (size_t) CAP * (H / 32) * sizeof(float)), "activation scales", err, device) &&
+ check(cudaMalloc(&d_scratch_, scratch), "scratch", err, device) &&
+ check(cudaMalloc(&d_meta_, sizeof(RemoteMeta)), "group metadata", err, device);
+ if (!allocated) { close(); return false; }
+ auto* meta = (RemoteMeta*) d_meta_;
+ d_ptr_ = meta->ptr;
+ d_start_ = meta->start;
+ d_dst_ = meta->dst;
+ d_tok_ = meta->tok;
+ d_count_ = &meta->count;
+ owned_.resize(CAP);
+ layers_present_.assign((size_t) layers, 0);
+ group_of_.resize(CAP);
+ group_id_.reserve(CAP);
+ ptr_.reserve(CAP);
+ start_.reserve(CAP + 1);
+ dst_.reserve(CAP);
+ tok_.reserve(CAP);
+ original_row_.reserve(CAP);
+ computed_ = 0;
+ launched_layers_ = 0;
+ returned_bytes_ = full_row_bytes_ = 0;
+ for (const auto& pair : selected) {
+ layers_present_[(size_t) pair.first] = 1;
+ claimed[(size_t) pair.first * (size_t) experts + (size_t) pair.second] = 1;
+ }
+ return true;
+}
+
+bool RemoteExperts::begin(int64_t layer, const float* x, const int32_t* ids, int64_t n_tok,
+ int64_t k, const int32_t* kind, const int32_t* primary_res,
+ std::string& err) {
+ const int64_t n = n_tok * k;
+ if (n <= 0 || n > CAP || n_tok > strata::kernels::cpu::MAXT || k != 10 || layer < 0 ||
+ (size_t) layer >= layers_present_.size() || device_ < 0) {
+ err = "CUDA" + std::to_string(device_) + " experts: invalid layer, routing width or window size";
+ return false;
+ }
+ std::fill(owned_.begin(), owned_.begin() + n, 0);
+ group_id_.clear(); ptr_.clear(); start_.clear(); dst_.clear(); tok_.clear(); original_row_.clear();
+ if (!layers_present_[(size_t) layer]) return true;
+ std::fill(group_of_.begin(), group_of_.begin() + n, -1);
+ for (int64_t i = 0; i < n; ++i) {
+ const int32_t e = ids[i];
+ if ((kind && kind[i] != -1) || e < 0 || e >= n_expert_ ||
+ (primary_res && primary_res[(size_t) layer * (size_t) n_expert_ + (size_t) e] >= 0)) continue;
+ const int32_t slot = cache_.slot_of(layer, e);
+ if (slot < 0) continue;
+ owned_[(size_t) i] = 1;
+ int32_t group = -1;
+ for (size_t g = 0; g < group_id_.size(); ++g)
+ if (group_id_[g] == e) { group = (int32_t) g; break; }
+ if (group < 0) {
+ group = (int32_t) group_id_.size();
+ group_id_.push_back(e);
+ ptr_.push_back((unsigned long long) cache_.device_slot(slot));
+ }
+ group_of_[(size_t) i] = group;
+ ++computed_;
+ }
+ if (group_id_.empty()) return true;
+ for (size_t g = 0; g < group_id_.size(); ++g) {
+ start_.push_back((int32_t) dst_.size());
+ for (int64_t i = 0; i < n; ++i) if (group_of_[(size_t) i] == (int32_t) g) {
+ // The grouped kernels read the activation from `tok`, so their
+ // output row can instead be packed densely for the USB4 return.
+ original_row_.push_back((int32_t) i);
+ dst_.push_back((int32_t) dst_.size());
+ tok_.push_back((int32_t) (i / k));
+ }
+ }
+ start_.push_back((int32_t) dst_.size());
+ // Private pinned buffers survive until this GPU has consumed them. The CPU
+ // pool can write other output rows without a cross-device race.
+ std::memcpy(h_x_, x, (size_t) n_tok * H * sizeof(float));
+ auto* meta = (RemoteMeta*) h_meta_;
+ std::memcpy(meta->ptr, ptr_.data(), ptr_.size() * sizeof(ptr_[0]));
+ std::memcpy(meta->start, start_.data(), start_.size() * sizeof(start_[0]));
+ std::memcpy(meta->dst, dst_.data(), dst_.size() * sizeof(dst_[0]));
+ std::memcpy(meta->tok, tok_.data(), tok_.size() * sizeof(tok_[0]));
+ meta->count = (int32_t) group_id_.size();
+ DeviceScope scope(device_);
+ if (!scope.ok) { err = scope.error(device_); return false; }
+ groups_ = (int32_t) group_id_.size();
+ const cudaStream_t s = stream_;
+ const bool staged =
+ check(cudaMemcpyAsync(d_x_, h_x_, (size_t) n_tok * H * sizeof(float), cudaMemcpyHostToDevice, s), "copy input", err, device_) &&
+ check(cudaMemcpyAsync(d_meta_, h_meta_, sizeof(RemoteMeta), cudaMemcpyHostToDevice, s), "copy group metadata", err, device_);
+ if (!staged) return false;
+ const auto& lay = strata::kernels::cpu::expert_layout();
+ if (lay.native) {
+ strata::kernels::quantize_q8_1_rows(d_x_, n_tok, H, d_q8_, s);
+ const auto& fmt = lay.fmt[(size_t) layer];
+ auto L = strata::kernels::native_expert_layout(fmt.gu_type, fmt.d_type, fmt.n_embd, fmt.n_ff);
+ strata::kernels::native_expert_grouped(L, d_ptr_, d_start_, d_count_, d_dst_, d_tok_,
+ groups_, (int64_t) dst_.size(), d_q8_, d_scratch_, d_out_, s);
+ } else {
+ strata::kernels::quantize_q8_0_scaled(d_x_, d_q8_, d_scales_, n_tok * H, s);
+ strata::kernels::moe_grouped_s2(d_ptr_, d_start_, d_count_, d_dst_, d_tok_,
+ groups_, (int64_t) dst_.size(), d_q8_, d_scales_, d_scratch_, d_out_, s);
+ }
+ const uint64_t compact_bytes = (uint64_t) dst_.size() * H * sizeof(float);
+ if (!check(cudaMemcpyAsync(h_out_, d_out_, (size_t) compact_bytes, cudaMemcpyDeviceToHost, s),
+ "copy results", err, device_)) return false;
+ ++launched_layers_;
+ returned_bytes_ += compact_bytes;
+ full_row_bytes_ += (uint64_t) n * H * sizeof(float);
+ return true;
+}
+
+bool RemoteExperts::finish(float* out, std::string& err) {
+ if (group_id_.empty()) return true;
+ DeviceScope scope(device_);
+ if (!scope.ok) { err = scope.error(device_); return false; }
+ if (!check(cudaStreamSynchronize(stream_), "finish", err, device_)) return false;
+ for (size_t i = 0; i < original_row_.size(); ++i)
+ std::memcpy(out + (size_t) original_row_[i] * H, h_out_ + i * H, (size_t) H * sizeof(float));
+ return true;
+}
+
+} // namespace strata::core
diff --git a/src/program/generate.cpp b/src/program/generate.cpp
index 6e979d6a4..7de68db88 100644
--- a/src/program/generate.cpp
+++ b/src/program/generate.cpp
@@ -16,6 +16,7 @@
#include "strata/core/expert_cache.hpp"
#include "strata/core/expert_source.hpp"
+#include "strata/core/remote_experts.hpp"
#include "strata/core/layer.hpp"
#include "strata/core/layout.hpp"
#include "strata/core/session.hpp"
@@ -63,6 +64,7 @@
#include <cuda_runtime.h>
+#include <array>
#include <chrono>
#include <algorithm>
#include <iostream>
@@ -180,6 +182,8 @@ struct Options {
/// true is that the ADMISSION POLICY gave every slot to the first position, which is why the earlier
/// measurement found nothing - see `expert_cache_per_layer`.
int expert_cache = 0;
+ std::array<int, 3> expert_cache_remote{}; ///< CUDA1..3 slots; CUDA0 keeps dense/state/MTP
+ std::string expert_cache_remote_placement = "stripe"; ///< stripe experts or assign complete layers to CUDA1..3
bool expert_cache_cpu_order = false;
/// **R4.2g. ROUND 328 MEASURED THAT THE GLOBAL ADMISSION POLICY CANNOT WORK, AND THIS IS THE FIX.**
/// The default policy hands out slots in arrival order from one counter shared by all 48 layers, so the
@@ -394,6 +398,11 @@ void usage() {
" GPU via `moe_hit_grouped_s2`. DEFAULT 0. Measured at 4096 slots\n"
" with --expert-cache-per-layer: 54.4%% hits, CPU pool drain 19.1 -> 10.3\n"
" ms/token, -2.7 ms/token end to end.\n"
+ " --expert-cache-device1 N pre-fill N experts on CUDA1 (experimental)\n"
+ " --expert-cache-device2 N pre-fill N more experts on CUDA2\n"
+ " --expert-cache-device3 N pre-fill N more experts on CUDA3\n"
+ " --expert-cache-remote-placement stripe|layer distribute expert ranks or whole\n"
+ " layers across CUDA1..3 (default: stripe)\n"
" --expert-cache-per-layer R4.2g: give each layer its OWN slots instead of letting the first\n"
" position take all of them. The default policy fills in arrival order\n"
" from one shared counter, so 256 slots went to ~26 layers of position 0\n"
@@ -897,6 +906,11 @@ int main(int argc, char** argv) {
const std::string v = next("--expert-cache");
o.expert_cache = (v == "auto") ? -1 : std::atoi(v.c_str());
}
+ else if (a == "--expert-cache-device1") o.expert_cache_remote[0] = std::atoi(next("--expert-cache-device1"));
+ else if (a == "--expert-cache-device2") o.expert_cache_remote[1] = std::atoi(next("--expert-cache-device2"));
+ else if (a == "--expert-cache-device3") o.expert_cache_remote[2] = std::atoi(next("--expert-cache-device3"));
+ else if (a == "--expert-cache-remote-placement")
+ o.expert_cache_remote_placement = next("--expert-cache-remote-placement");
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");
@@ -1079,10 +1093,18 @@ int main(int argc, char** argv) {
return 2;
}
if (!std::isfinite(o.temperature) || o.temperature < 0 || !std::isfinite(o.top_p) ||
- o.top_p <= 0 || o.top_p > 1 || o.top_k < 0 || o.expert_cache < -1 || o.pool_workers < 0) {
+ o.top_p <= 0 || o.top_p > 1 || o.top_k < 0 || o.expert_cache < -1 ||
+ o.pool_workers < 0 || std::any_of(o.expert_cache_remote.begin(), o.expert_cache_remote.end(),
+ [](int slots) { return slots < 0; }) ||
+ (o.expert_cache_remote[1] > 0 && o.expert_cache_remote[0] == 0) ||
+ (o.expert_cache_remote[2] > 0 && o.expert_cache_remote[1] == 0)) {
std::fprintf(stderr, "strata generate: invalid sampling or resource parameter\n");
return 2;
}
+ if (o.expert_cache_remote_placement != "stripe" && o.expert_cache_remote_placement != "layer") {
+ std::fprintf(stderr, "strata generate: --expert-cache-remote-placement must be stripe or layer\n");
+ return 2;
+ }
if (o.native_flash_attn_short && o.max_context > 256) {
std::fprintf(stderr, "strata generate: --native-flash-attn-short requires --max-context <=256\n");
@@ -1122,6 +1144,17 @@ int main(int argc, char** argv) {
}
}
const bool native_pack = strata::kernels::cpu::expert_layout().native;
+ if (o.expert_cache_remote[0] > 0) {
+ // Keep CUDA1's proven startup order: initialise its context before
+ // allocating GPU0 weights or mapping the large host expert arena.
+ double free_gib = 0;
+ if (!strata::core::RemoteExperts::preflight(1, free_gib, err)) {
+ std::fprintf(stderr, "strata generate: %s\n", err.c_str());
+ return 1;
+ }
+ std::fprintf(stderr, "strata generate: CUDA1 context ready, %.2f GiB free before expert arena registration\n",
+ free_gib);
+ }
// plan v0.3 P6: the PCIe share of the missed experts, measured per kind of pack (the paper, finding on PCIe).
// PR #44: a x8 link carries half of what the native default assumes - the GPU's SMs read that share over the
// link (the copy kernel, since 0.1.14), so on a slower link it must shrink or the window waits for it. The
@@ -1424,6 +1457,32 @@ int main(int argc, char** argv) {
return 1;
}
+ // Secure MTP's CUDA0 allocations before the large host arena is registered with both CUDA contexts.
+ // In particular WDDM can refuse the draft weights after mapping tens of GiB of host pages.
+ strata::core::MtpDrafter mtp;
+ if (!o.mtp.empty()) {
+ if (o.spec < 2) {
+ std::fprintf(stderr, "strata generate: --mtp is ignored without --spec T (T >= 2)\n");
+ o.mtp.clear();
+ }
+ if (!o.mtp.empty()) mtp.set_prompt_len((int64_t) o.tokens.size());
+ // the draft layer is the canonical model's MTP head (512 experts) even when the target is pruned,
+ // so it always sees the canonical geometry; `static` because MtpDrafter keeps a reference
+ static const strata::core::ModelGeometry draft_geometry{};
+ if (!o.mtp.empty() && !mtp.load(o.mtp, draft_geometry, ss, o.spec, err, o.mtp_window)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; }
+ }
+ // Create the additional contexts after MTP has secured CUDA0 memory, but
+ // before the host arena maps its expert pages into their address spaces.
+ for (int r = 1; r < 3; ++r) if (o.expert_cache_remote[(size_t) r] > 0) {
+ double free_gib = 0;
+ if (!strata::core::RemoteExperts::preflight(r + 1, free_gib, err)) {
+ std::fprintf(stderr, "strata generate: %s\n", err.c_str());
+ return 1;
+ }
+ std::fprintf(stderr, "strata generate: CUDA%d context ready, %.2f GiB free before expert arena registration\n",
+ r + 1, free_gib);
+ }
+
// ---- the CPU expert pool
//
// R2.1: the experts are loaded into a RESIDENT ARENA by default. The mmap path is kept behind
@@ -1456,7 +1515,10 @@ int main(int argc, char** argv) {
srcp = &src;
} else {
arena_src.set_gguf(o.native_preset); // plan v0.3 P6: a native pack may take its experts from shard 1
- if (!arena_src.open(o.pack, g.n_layers, g.n_expert, /*threads=*/6, err)) {
+ // On the multi-GPU Windows experiment, start with at most 8 GiB of mapped host pages.
+ // Unregistered layers remain in the resident arena and use the CPU expert path.
+ const uint64_t pin_limit = o.expert_cache_remote[0] > 0 ? (8ull << 30) : 0;
+ if (!arena_src.open(o.pack, g.n_layers, g.n_expert, /*threads=*/6, err, pin_limit)) {
std::fprintf(stderr, "strata generate: %s\n", err.c_str());
return 1;
}
@@ -1466,19 +1528,6 @@ int main(int argc, char** argv) {
arena_src.load_gib_per_second());
srcp = &arena_src;
}
- // Plan v0.3 P6: the MTP draft layer, loaded before the VRAM expert tier is sized from what is left.
- strata::core::MtpDrafter mtp;
- if (!o.mtp.empty()) {
- if (o.spec < 2) {
- std::fprintf(stderr, "strata generate: --mtp is ignored without --spec T (T >= 2)\n");
- o.mtp.clear();
- }
- if (!o.mtp.empty()) mtp.set_prompt_len((int64_t) o.tokens.size());
- // the draft layer is the canonical model's MTP head (512 experts) even when the target is pruned,
- // so it always sees the canonical geometry; `static` because MtpDrafter keeps a reference
- static const strata::core::ModelGeometry draft_geometry{};
- if (!o.mtp.empty() && !mtp.load(o.mtp, draft_geometry, ss, o.spec, err, o.mtp_window)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; }
- }
strata::kernels::cpu::ExpertPool pool(o.pool_workers, /*pin=*/true, /*host_works=*/!o.no_host_worker);
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`
@@ -1704,7 +1753,83 @@ int main(int argc, char** argv) {
(long long) prefilled, (long long) want);
}
+ std::array<strata::core::RemoteExperts, 3> remote_experts;
+ const bool multi_remote = o.expert_cache_remote[1] > 0 || o.expert_cache_remote[2] > 0;
+ if (o.expert_cache_remote[0] > 0) {
+ if (o.expert_cache <= 0 || profile.empty() || o.no_pool) {
+ std::fprintf(stderr, "strata generate: remote experts need --expert-profile, "
+ "a CUDA0 expert cache and the expert pool\n");
+ return 2;
+ }
+ std::vector<std::pair<int32_t, int32_t>> ranked = profile;
+ if (multi_remote) {
+ // The shipped frequency profile names only 8000 of 24576 experts. Once exhausted,
+ // fill remaining VRAM from unranked pairs in expert-then-layer order: this spreads
+ // the tail across all layers instead of concentrating it on layer zero.
+ std::vector<uint8_t> seen((size_t) g.n_layers * (size_t) g.n_expert, 0);
+ for (const auto& pair : ranked)
+ if (pair.first >= 0 && pair.first < g.n_layers && pair.second >= 0 && pair.second < g.n_expert)
+ seen[(size_t) pair.first * (size_t) g.n_expert + (size_t) pair.second] = 1;
+ for (int64_t e = 0; e < g.n_expert; ++e)
+ for (int64_t l = 0; l < g.n_layers; ++l)
+ if (!seen[(size_t) l * (size_t) g.n_expert + (size_t) e])
+ ranked.emplace_back((int32_t) l, (int32_t) e);
+ std::fprintf(stderr, "strata generate: remote ranking: %zu profiled pairs, "
+ "%zu other pairs to fill CUDA1..3\n", profile.size(), ranked.size() - profile.size());
+ }
+ std::array<std::vector<std::pair<int32_t, int32_t>>, 3> by_device;
+ if (multi_remote) {
+ // Either stripe experts for parallel GPU work, or give each layer one
+ // secondary GPU to reduce switches and transfers over shared USB4.
+ std::vector<uint8_t> assigned((size_t) g.n_layers * (size_t) g.n_expert, 0);
+ const int devices = 1 + (o.expert_cache_remote[1] > 0) + (o.expert_cache_remote[2] > 0);
+ int next = 0;
+ for (const auto& pair : ranked) {
+ if (pair.first < 0 || pair.first >= g.n_layers || pair.second < 0 || pair.second >= g.n_expert ||
+ xcache.slot_of(pair.first, pair.second) >= 0) continue;
+ const size_t index = (size_t) pair.first * (size_t) g.n_expert + (size_t) pair.second;
+ if (assigned[index]) continue;
+ int target = -1;
+ if (o.expert_cache_remote_placement == "layer") {
+ target = pair.first % devices;
+ // Other layers' owners may still have room: keep scanning ranks.
+ if (by_device[(size_t) target].size() >=
+ (size_t) o.expert_cache_remote[(size_t) target]) continue;
+ } else {
+ for (int i = 0; i < devices; ++i) {
+ const int r = (next + i) % devices;
+ if (by_device[(size_t) r].size() < (size_t) o.expert_cache_remote[(size_t) r]) {
+ target = r;
+ break;
+ }
+ }
+ if (target < 0) break;
+ }
+ assigned[index] = 1;
+ by_device[(size_t) target].push_back(pair);
+ next = (target + 1) % devices;
+ }
+ std::fprintf(stderr, "strata generate: remote ranks %s across %d CUDA devices\n",
+ o.expert_cache_remote_placement == "layer" ? "grouped by layer" : "striped", devices);
+ } else {
+ by_device[0] = std::move(ranked);
+ }
+ std::vector<uint8_t> claimed((size_t) g.n_layers * (size_t) g.n_expert, 0);
+ for (int r = 0; r < 3; ++r) if (o.expert_cache_remote[(size_t) r] > 0) {
+ if (!remote_experts[(size_t) r].open(r + 1, o.expert_cache_remote[(size_t) r],
+ g.n_layers, g.n_expert, by_device[(size_t) r], xcache, *srcp, claimed, err)) {
+ std::fprintf(stderr, "strata generate: %s\n", err.c_str());
+ return 1;
+ }
+ std::fprintf(stderr, "strata generate: CUDA%d: %lld additional experts, %.2f GiB; "
+ "results return through pinned host rows\n", r + 1,
+ (long long) remote_experts[(size_t) r].resident(), remote_experts[(size_t) r].gib());
+ }
+ }
+
Drive drive;
+ for (int r = 0; r < 3; ++r) if (o.expert_cache_remote[(size_t) r] > 0)
+ drive.d.remote[drive.d.remote_count++] = &remote_experts[(size_t) r];
drive.d.hit_cpu_order = o.expert_cache_cpu_order;
drive.d.split_rows = !o.no_split_rows;
drive.d.pool = &pool;
@@ -2896,6 +3021,16 @@ int main(int argc, char** argv) {
bool bad = false;
for (int64_t t : ids) bad = bad || t < 0 || t >= n_vocab;
if (bad) { std::printf("ERR a token id is outside the vocabulary\n"); continue; }
+ std::array<int64_t, 3> remote_before{};
+ std::array<int64_t, 3> launches_before{};
+ std::array<uint64_t, 3> compact_before{}, full_before{};
+ for (int r = 0; r < 3; ++r) if (o.expert_cache_remote[(size_t) r] > 0)
+ {
+ remote_before[(size_t) r] = remote_experts[(size_t) r].computed();
+ launches_before[(size_t) r] = remote_experts[(size_t) r].launched_layers();
+ compact_before[(size_t) r] = remote_experts[(size_t) r].returned_bytes();
+ full_before[(size_t) r] = remote_experts[(size_t) r].full_row_bytes();
+ }
cur = ids;
const Clock::time_point r0 = Clock::now();
// ---- where this request starts reading: the live session, or a checkpoint, whose tokens AND pictures are
@@ -3381,6 +3516,13 @@ int main(int argc, char** argv) {
if (sfx_windows > 0)
std::fprintf(stderr, "strata serve: suffix drafts: %lld windows, %lld of %lld drafts accepted\n",
(long long) sfx_windows, (long long) sfx_ok, (long long) sfx_drafts);
+ for (int r = 0; r < 3; ++r) if (o.expert_cache_remote[(size_t) r] > 0)
+ std::fprintf(stderr, "strata serve: CUDA%d: %lld expert entries, %lld active layer launches, %.1f MiB returned "
+ "(%.1f MiB with full rows) in this request\n", r + 1,
+ (long long) (remote_experts[(size_t) r].computed() - remote_before[(size_t) r]),
+ (long long) (remote_experts[(size_t) r].launched_layers() - launches_before[(size_t) r]),
+ (double) (remote_experts[(size_t) r].returned_bytes() - compact_before[(size_t) r]) / 1048576.0,
+ (double) (remote_experts[(size_t) r].full_row_bytes() - full_before[(size_t) r]) / 1048576.0);
}
return 0;
}
@@ -4109,6 +4251,9 @@ int main(int argc, char** argv) {
" pool phases", wp / per, dr / per, rp / per);
}
std::printf("%-24s %lld blobs read\n", " expert blobs", (long long) srcp->reads());
+ for (int r = 0; r < 3; ++r) if (o.expert_cache_remote[(size_t) r] > 0)
+ std::printf(" CUDA%d experts %lld routed entries computed\n",
+ r + 1, (long long) remote_experts[(size_t) r].computed());
// ---- **R4's DISPATCH MEASUREMENT: h, ON THE ENGINE'S OWN ROUTING.** No offline trace, no corpus
// question, no k-fold - these are the ids the router actually produced on this run. Reported as
// hits/lookups so it can be read directly as the h the cache would deliver, and alongside `refused`