[1/2] 35b-a3b perf -- auto CPU/GPU split on expert cache misses (#27)

* strata-poly: hybrid expert streaming while an answer is written (--stage-rows, --stage-overlap)

An answer's decode windows can take the prompt path's hybrid handling of the experts outside VRAM
(--stage-rows 1): the misses go through the pinned staging buffer to the card and run there by MMQ,
an adaptive --cpu-share of them computed on the CPU meanwhile, instead of every miss on the CPU.
--stage-overlap (default on) copies a single staging round on the upload stream, under the cached
experts' kernels. STRATA_WORKER_SPINS=N shortens the workers' spin before they sleep;
STRATA_BLOCKING_SYNC=1 has the waiting thread sleep on the card (set before the single-card path).

On a GTX 1060 6 GB laptop (Qwen3.6-35B-A3B UD-IQ3_XXS, 128K q8_0 KV, 4K prompt, 512-token decode,
nvprof): 20.6 -> 26.5-29.3 tok/s, CPU 6.2 -> 2.5-3.6 cores, CPU throttle events 2389 -> 484, PCIe
0.3-0.7 GB/s at decode, GPU 82-85% busy.

Fixes the streamed path needed: a streamed window never takes the halves pipelining (it corrupted
output); it feeds recent_ so the cache keeps trading for the answer's experts; the pinned copies go
to a few stager threads so the expert workers sleep.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* strata-poly: a streamed window applies --tail-skip as moe() did

With --stage-rows under 32 an answer's windows take moe_rows(), which computed every routed expert: the
tail-rank skip lived only in moe(), so lowering --stage-rows silently turned --tail-skip off while the startup
line still claimed it.  moe_rows() now leaves out an expert outside VRAM that every token of the window ranks
at tail_skip or later, counts it in tail_experts, and zeroes its rows' places.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* strata-poly: an answer's streamed misses count as misses in the stats

A window through moe_rows() counted its cached rows as gpu_experts and nothing for the rows staged to the
card, and the front end's DONE line and the run summary take hits over gpu_experts + cpu_experts: a window of
two hits and six streamed misses reported 100% from VRAM.  Stats::staged_experts holds them and both totals
include it.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* strata-poly: the MMQ path is set up from --stage-rows rows, not 32

alloc() gave a layer its MMQ tiles only when a call could hold kStageRows rows, so --prompt-batch 16
--stage-rows 1 (or a context that small) accepted both flags and streamed nothing: mmq_ was never made and
batched() was always false.  The buffers are sized from rows_ either way.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* strata-poly: STRATA_BLOCKING_SYNC leaves the caller's device selected

The flag loop ended on the last card it visited, so an unsplit engine opened from device 1 with the variable
set loaded on device 0.  The device that was current is restored after the loop.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* strata-poly: make staging overlap opt-in

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
Robert KarlandClaude Fable 5.1 authored and GitHub committed 2026-11-05 16:37:45 -08:00
1 parent 22abfdb87f
commit 1fe9bec4cd
4 files changed
+95 -11

No files matched your search

+7 -1
View File
@@ -4,6 +4,7 @@
#include "ggml.h"
#include "ggml-cpu.h"
#include <cstdlib>
#include <algorithm>
#include <cmath>
#include <cstring>
@@ -18,7 +19,12 @@ namespace {
// idle at the end of every layer: 64 rows gave Tiel's 512-row experts 8 tasks each, and its down products 32 tasks.
constexpr int kRowsPerTask = 32;
constexpr int kRowsPerDownTask = 16;
constexpr int kSpinsBeforeSleep = 20000; // about a millisecond of pause instructions
// About a millisecond of pause instructions before a worker sleeps; STRATA_WORKER_SPINS=N for another count (a
// laptop whose CPU is not the lane that matters cools down with a few hundred).
const int kSpinsBeforeSleep = [] {
const char* v = std::getenv("STRATA_WORKER_SPINS");
return v && std::atoi(v) >= 0 ? std::atoi(v) : 20000;
}();
const ggml_type_traits_cpu* traits(int type) { return ggml_get_type_traits_cpu((ggml_type) type); }
+71 -8
View File
@@ -1011,6 +1011,20 @@ std::unique_ptr<Engine> Engine::open(const Options& o) {
starts = layer_starts(o.layer_split, file, (int) blocks->u - (nextn ? (int) nextn->u : 0), cards);
ck(cudaSetDevice(was), "cudaSetDevice");
}
// STRATA_BLOCKING_SYNC=1: the thread that waits for the card sleeps on it instead of spinning (a laptop whose
// CPU shares the card's heat); a wake costs some microseconds a wait.
if (const char* v = std::getenv("STRATA_BLOCKING_SYNC"); v && std::atoi(v) != 0) {
int was = 0; // an unsplit engine loads on the caller's card: leave it selected
ck(cudaGetDevice(&was), "cudaGetDevice");
for (int d = 0; d < std::max(1, devices); ++d) {
ck(cudaSetDevice(d), "cudaSetDevice");
if (cudaSetDeviceFlags(cudaDeviceScheduleBlockingSync) != cudaSuccess) {
cudaGetLastError();
std::fprintf(stderr, "strata-poly: card %d: could not set blocking sync\n", d);
}
}
ck(cudaSetDevice(was), "cudaSetDevice");
}
if (starts.empty()) {
std::unique_ptr<Engine> engine = make();
engine->load(o);
@@ -1587,6 +1601,8 @@ void Engine::load(const Options& o) {
throw std::runtime_error("a prompt batch is 1 to 4096 tokens");
if (opt_.stage_mib < 1) throw std::runtime_error("the staging buffer must be at least 1 MiB");
if (opt_.stage_ahead < 0) throw std::runtime_error("the batch size to stage ahead from cannot be negative");
if (opt_.stage_rows < 1 || opt_.stage_rows > kStageRows)
throw std::runtime_error("--stage-rows takes 1 to " + std::to_string(kStageRows));
if (opt_.expert_swaps < 0 || opt_.expert_swaps > 64)
throw std::runtime_error("0 to 64 experts can be on their way into the cache at a time");
if (opt_.window < 0 || opt_.window > 8)
@@ -1838,7 +1854,7 @@ void Engine::alloc() {
for (int il = 0; il < n_layer_; ++il) {
Layer& L = layers_[(size_t) il];
if (!L.moe) continue;
L.mmq = opt_.gpu_experts && rows_ >= kStageRows && Mmq::fits((int) L.gu_type, 2 * n_ff_exp_, n_embd_) &&
L.mmq = opt_.gpu_experts && rows_ >= opt_.stage_rows && Mmq::fits((int) L.gu_type, 2 * n_ff_exp_, n_embd_) &&
Mmq::fits((int) L.d_type, n_embd_, n_ff_exp_);
tiles = tiles || L.mmq;
one_expert = std::max(one_expert, 2 * L.gu_bytes + L.d_bytes);
@@ -2008,6 +2024,7 @@ const Stats& Engine::stats() const {
const Stats& s = e->stats_;
all_stats_.gpu_experts += s.gpu_experts;
all_stats_.cpu_experts += s.cpu_experts;
all_stats_.staged_experts += s.staged_experts;
all_stats_.batch_cached += s.batch_cached;
all_stats_.batch_staged += s.batch_staged;
all_stats_.swapped_experts += s.swapped_experts;
@@ -2105,7 +2122,7 @@ void Engine::lin(const Dev& w, const float* x, float* y, int n, const void* xq,
void Engine::router_scores(const Layer& L, int n) { lin(L.gate_inp, xn_, rl_, n, xq_); }
bool Engine::batched(const Layer& L, int n) const { return mmq_ && L.mmq && n >= kStageRows; }
bool Engine::batched(const Layer& L, int n) const { return mmq_ && L.mmq && n >= opt_.stage_rows; }
// The router's scores, and the copies of them and of the experts' input to the host.
void Engine::moe_router(const Layer& L, int n) {
@@ -2406,9 +2423,29 @@ void Engine::moe_rows(Layer& L, int il, int n) {
w + (size_t) t * n_used_, tmp);
});
count_.assign((size_t) n_expert_, 0);
const bool answer = n < kStageRows; // an answer's window through this path (--stage-rows), not a prompt batch
for (int i = 0; i < rr; ++i) {
++count_[(size_t) ids_[(size_t) i]];
++use_[(size_t) il * n_expert_ + (size_t) ids_[(size_t) i]];
// what moe() counts for follow(): the cache keeps trading for the experts the answer uses
if (answer && n_swap_ > 0) recent_[(size_t) il * n_expert_ + (size_t) ids_[(size_t) i]] += 1.f;
}
// Options::tail_skip, as moe() applies it to the calls that went through it before --stage-rows was lowered: an
// expert outside VRAM that every token of the window ranks at tail_skip or later is left out. Its rows keep no
// weight and take no place among the card's or the CPU's.
int n_tail = 0;
left_out_.assign((size_t) n_expert_, 0);
if (answer && opt_.tail_skip > 0) {
for (int i = 0; i < rr; ++i)
if (i % n_used_ < opt_.tail_skip) left_out_[(size_t) ids_[(size_t) i]] = 2; // ranked high by a token: kept
for (int e = 0; e < n_expert_; ++e) {
const bool out = count_[(size_t) e] > 0 && !L.slot[(size_t) e] && left_out_[(size_t) e] != 2;
left_out_[(size_t) e] = out;
if (!out) continue;
stats_.tail_experts += count_[(size_t) e];
n_tail += count_[(size_t) e];
count_[(size_t) e] = 0;
}
}
// The CPU computes some of the routed experts outside VRAM while the others are copied: the ones the fewest
// tokens chose, whose copy costs as much as any other's and which cost the CPU about as much as their tokens.
@@ -2459,6 +2496,10 @@ void Engine::moe_rows(Layer& L, int il, int n) {
host_.clear();
for (int i = 0; i < rr; ++i) {
const size_t e = (size_t) ids_[(size_t) i];
if (left_out_[e]) { // left out (tail_skip): no row, and nothing of it in the sum
w[i] = 0.f;
continue;
}
if (on_cpu_[e]) { // by token, as cpu_experts() takes them, and nothing of it in the card's sum
host_.push_back({L.exp_gate + e * L.gu_stride, L.exp_up + e * L.gu_stride, L.exp_down + e * L.d_bytes,
w[i], i / n_used_});
@@ -2496,16 +2537,22 @@ void Engine::moe_rows(Layer& L, int il, int n) {
"expert rows");
const int rc = bounds[n_cached]; // the rows of the cached experts
stats_.batch_cached += rc;
stats_.batch_staged += rg - rc;
if (answer) { // an answer's window: counted as decoding, the staged rows as misses
stats_.gpu_experts += rc;
stats_.staged_experts += rg - rc;
} else {
stats_.batch_cached += rc;
stats_.batch_staged += rg - rc;
}
const float limit = clamp_exp_[(size_t) il];
const int gt = (int) L.gu_type, dt = (int) L.d_type;
const int64_t ff = n_ff_exp_, ff2 = 2 * ff;
int holds = -1; // the round in the buffer when this call is done
// The card's part. With the CPU's beside it, the rows of its experts' places are left at nothing.
// The card's part. With the CPU's beside it, or experts left out, the rows of those places are left at nothing.
const auto card = [&] {
if (n_cpu > 0) ck(cudaMemsetAsync(dx_, 0, (size_t) rr * n_embd_ * sizeof(float), cs(st_)), "expert rows");
if (n_cpu > 0 || n_tail > 0)
ck(cudaMemsetAsync(dx_, 0, (size_t) rr * n_embd_ * sizeof(float), cs(st_)), "expert rows");
if (rg > 0) Mmq::quantize(xn_, d_tok, mq_, gt, n_embd_, n_embd_, rg, st_);
// The cached experts whose slots lie one behind the other are the matrices of one launch, as the experts of
@@ -2556,7 +2603,19 @@ void Engine::moe_rows(Layer& L, int il, int n) {
} else if (r == 0 && early) {
ck(cudaStreamWaitEvent(cs(st_), (cudaEvent_t) ev_ahead_, 0), "expert staging");
} else if (rows > 0) {
stage(L, group_.data() + g0, m, st_, n_cpu > 0);
// an answer's window: the four stagers copy, so the expert workers sleep instead of spinning
if (answer && !stagers_) stagers_ = std::make_unique<Workers>(4);
if (n_round == 1 && opt_.stage_overlap) {
// One round: its copy goes on the upload stream, under the cached experts' kernels queued
// above, and the compute stream takes it up when it lands. More rounds reuse the buffer, so
// a round's copy has to follow the round before it on the compute stream.
ck(cudaStreamWaitEvent(cs(up_), (cudaEvent_t) ev_free_, 0), "expert staging");
stage(L, group_.data() + g0, m, up_, n_cpu > 0 || answer);
ck(cudaEventRecord((cudaEvent_t) ev_ahead_, cs(up_)), "expert staging");
ck(cudaStreamWaitEvent(cs(st_), (cudaEvent_t) ev_ahead_, 0), "expert staging");
} else {
stage(L, group_.data() + g0, m, st_, n_cpu > 0 || answer);
}
holds = r;
}
if (rows == 0) continue; // nothing routed to the experts that go ahead
@@ -2732,7 +2791,11 @@ void Engine::run(const int32_t* tokens, int n) {
//
// A half's launches are the ones its tokens have in a call of their own, at their rows of the buffers
// (shift_rows()), so each token comes out as it would alone.
if (n > 1 && windowed_ && !all_cached() && halves_) {
// With --stage-rows under kStageRows a window's experts take the batch path (moe_rows(), below), whose call
// does the shared expert and the routing itself: up() leaves them out, and moe() would then miss them, so
// the halves (which call moe() directly) are not for such a window.
const bool streamed = mmq_ && n >= opt_.stage_rows && opt_.stage_rows < kStageRows;
if (n > 1 && windowed_ && !all_cached() && halves_ && !streamed) {
const int first[3] = {0, (n + 1) / 2, n}; // half k is the tokens [first[k], first[k + 1])
const unsigned bits = snap_bits_; // the window's tokens that leave the recurrent state
int at = 0;
+8
View File
@@ -61,6 +61,11 @@ struct Options {
float cpu_share = -1; ///< of the experts outside VRAM that such a call routes to, the share the CPU
///< computes while the others are copied: the ones the fewest tokens chose;
///< below 0: as the two took the time between them; 0: none
int stage_rows = 32; ///< from this many tokens (kStageRows) a call takes its routed experts as a prompt batch
///< (moe_rows(): the cached ones by MMQ, the others through the staging buffer
///< with the CPU's share computed meanwhile); under it the CPU computes every
///< expert outside VRAM (moe()). 1: an answer's windows stream their misses too
bool stage_overlap = false; ///< opt-in: copy a single staging round under the cached experts' kernels
int expert_swaps = 64; ///< experts on their way into the cache at a time while an answer is written, each
///< to the slot of one the answer uses less; 0: the cache stays as it was loaded
bool stay_near = true; ///< with several NUMA nodes, keep the CPU threads on the one that holds the experts
@@ -134,6 +139,8 @@ struct Layer {
/// (gpu_experts, cpu_experts), and in a prompt batch from the cache or the staging buffer (batch_*).
struct Stats {
int64_t tokens = 0, gpu_experts = 0, cpu_experts = 0, batch_cached = 0, batch_staged = 0;
int64_t staged_experts = 0; ///< an answer's experts outside VRAM copied to the card and computed there
///< (--stage-rows): misses, like cpu_experts
int64_t swapped_experts = 0; ///< experts that took a cached one's slot (follow())
int64_t tail_experts = 0; ///< a token's experts left out by Options::tail_skip
double cpu_ms = 0, route_wait_ms = 0;
@@ -697,6 +704,7 @@ protected:
std::vector<uint8_t> sent_;
// A call that copies only the experts it routes to leaves some of those outside VRAM to the CPU (moe_rows()).
std::vector<uint8_t> on_cpu_; ///< per expert of the layer: the CPU's
std::vector<uint8_t> left_out_; ///< per expert of the layer: left out by Options::tail_skip
std::vector<int32_t> spare_; ///< the layer's routed experts outside VRAM, the fewest tokens' first
std::vector<CpuExpert> host_; ///< their uses, by token
double share_[5] = {0.25, 0.25, 0.25, 0.25, 0.25}; ///< the CPU's share of spare_, by the call's tokens:
+9 -2
View File
@@ -877,7 +877,7 @@ int serve(Session& ss) {
const strata::poly::Stats& now = engine.stats();
// the cache's share of the experts looked up while answering: a prompt batch's go through VRAM either way
const long long hits = now.gpu_experts - before.gpu_experts;
const long long misses = now.cpu_experts - before.cpu_experts;
const long long misses = (now.cpu_experts - before.cpu_experts) + (now.staged_experts - before.staged_experts);
std::printf("DONE %lld %lld %.1f %.1f %s %lld %lld %lld %lld %lld 0 0 0.0 %lld 0\n", (long long) r.produced, n,
r.prompt_ms, r.decode_ms, r.finish, (long long) r.guessed_right, (long long) r.guessed,
(long long) r.resume, hits, hits + misses, (long long) r.read);
@@ -953,7 +953,7 @@ int once(Session& ss, const std::vector<int32_t>& ids, const Pictures& pictures,
[](int64_t, int64_t, double, bool) {});
std::printf("%s\n", out.c_str());
const strata::poly::Stats& st = ss.engine.stats();
const double experts = (double) std::max<int64_t>(st.gpu_experts + st.cpu_experts, 1);
const double experts = (double) std::max<int64_t>(st.gpu_experts + st.cpu_experts + st.staged_experts, 1);
std::fprintf(stderr,
"prompt %lld tokens %.1f tok/s, generated %lld tokens %.2f tok/s (%s); experts from VRAM %.1f%%, "
"CPU experts %.1f ms/token, router wait %.1f ms/token, %lld experts swapped into VRAM, "
@@ -1063,6 +1063,11 @@ void usage() {
" of them are copied after the layer has routed\n"
" --stage-ahead N from N tokens, a batch copies those experts before it routes (default 1024,\n"
" 0 = never)\n"
" --stage-rows N from N tokens a call copies the experts outside the cache to the card\n"
" (--stage-mib) and computes them there, the CPU taking its share meanwhile;\n"
" under N the CPU computes all of them (default 32; 1 = also while an\n"
" answer is written, which keeps the card and the bus busy instead of the CPU)\n"
" --stage-overlap 0|1 copy a single staging round under the cached experts' kernels (default 0)\n"
" --cpu-share F under that, the share of those experts the CPU computes meanwhile, the\n"
" ones the fewest tokens chose (default: as the times say; 0 = none)\n"
" --prompt-cache N checkpoints kept of a conversation, about 150 MB of RAM each (default 6;\n"
@@ -1162,6 +1167,8 @@ int main(int argc, char** argv) {
else if (a == "--prompt-batch") o.prompt_batch = std::atoi(val());
else if (a == "--stage-mib") o.stage_mib = std::atoi(val());
else if (a == "--stage-ahead") o.stage_ahead = std::atoi(val());
else if (a == "--stage-rows") o.stage_rows = std::atoi(val());
else if (a == "--stage-overlap") o.stage_overlap = std::atoi(val()) != 0;
else if (a == "--cpu-share") o.cpu_share = (float) std::atof(val());
else if (a == "--prompt-cache") cache.o.checkpoints = std::atoi(val());
else if (a == "--prompt-cache-every") cache.o.every = std::atoll(val());