From f71c5307c68e0dc85c3cdf5ea693ea7ef22c2e28 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 9 Oct 2026 03:17:17 +0200 Subject: [PATCH 1/7] Stage buffers: fence a pinned buffer's queued copy before the buffer is recycled (#1237) A page-locked stage buffer is the source of the cache fill's cudaMemcpyAsync, which the DMA reads after the call has returned; a pageable one is staged by the driver before it returns. The pool recycles a buffer after kStageAge layers or 256 assemblies, so a 4096-token prompt read (up to ~500 distinct experts per layer) could overwrite a buffer whose copy had not run yet: the corrupted IQ3_S decode of #1237. note_async_read(blob, stream) records an event per pinned buffer after each queued copy (hit-path fill, peer fill, remote-expert swap); claim_stage waits for it before it hands the buffer out again. Pageable buffers and every other source are unchanged. STRATA_STAGE_PIN stays opt-in. --- include/strata/core/expert_source.hpp | 13 +++++++ src/core/expert_source.cpp | 52 +++++++++++++++++++++++++++ src/core/peer_experts.cpp | 1 + src/core/remote_expert_opt.cu | 7 ++-- 4 files changed, 71 insertions(+), 2 deletions(-) diff --git a/include/strata/core/expert_source.hpp b/include/strata/core/expert_source.hpp index dfc249d8..2168f0ce 100644 --- a/include/strata/core/expert_source.hpp +++ b/include/strata/core/expert_source.hpp @@ -146,6 +146,11 @@ public: /// A blob pointer that stays valid (not recycled) for as long as the source is open: for a copy that runs /// asynchronously long after the call (the adaptive tier's swap-ins). Defaults to `blob`. virtual const uint8_t* blob_stable(int64_t layer, int64_t expert) { return blob(layer, expert); } + /// The caller has queued an asynchronous copy out of `blob` (a pointer this source handed out) on `stream` (a + /// cudaStream_t): the source must not overwrite or recycle that memory until the copy has finished. A source whose + /// pointers are never recycled ignores it. (#1237: a page-locked stage buffer is read by the DMA after the copy call + /// returned, where a pageable one is staged by the driver before it returns.) + virtual void note_async_read(const uint8_t* blob, void* stream) { (void) blob; (void) stream; } /// Blobs touched, for the driver to report. A source that does not count returns 0. virtual int64_t reads() const { return 0; } @@ -603,6 +608,7 @@ public: const uint8_t* blob(int64_t layer, int64_t expert) override; /// With io prefetch in the experts.bin tier, the mapping itself (blob() may hand out a recycled staging buffer). const uint8_t* blob_stable(int64_t layer, int64_t expert) override; + void note_async_read(const uint8_t* blob, void* stream) override; /// Windows, opt-in with STRATA_FILE_RELEASE=1: trim the file mapping's full pages after their expert reaches /// VRAM. Never touches the resident complement or staging buffers. Disabled by default. uint64_t release(int64_t layer, int64_t expert) override; @@ -728,6 +734,13 @@ private: int64_t last_layer_ = -1; bool stage_grew_ = false; bool stage_pin_said_ = false, stage_pin_failed_said_ = false; ///< the one-time notes in claim_stage + // #1237: per stage buffer, the event recorded after the last asynchronous copy out of it (note_async_read); a + // buffer is refilled only once that event has completed. cudaEvent_t, stored untyped (no cuda_runtime.h here). + std::vector stage_ev_; + std::vector stage_ev_live_; ///< a copy was queued since the buffer was last waited for + std::unordered_map stage_idx_; ///< buffer address -> index (the buffers never move) + void stage_free_events(); + std::atomic stage_fence_waits_{0}; ///< refills that had to wait for a queued copy std::atomic ram_reads_{0}; std::atomic file_read_bytes_{0}; // ---- the Linux I/O path (set_io_prefetch) diff --git a/src/core/expert_source.cpp b/src/core/expert_source.cpp index e4b46490..da7a75b8 100644 --- a/src/core/expert_source.cpp +++ b/src/core/expert_source.cpp @@ -958,6 +958,9 @@ void FileExpertSource::close() { direct_.clear(); { std::lock_guard lk(stage_mu_); + // the buffers' last copies end before they are freed (#1237) + if (!stage_ev_.empty()) (void) cudaDeviceSynchronize(); + stage_free_events(); stage_buf_.clear(); stage_key_.clear(); stage_epoch_.clear(); @@ -1207,6 +1210,9 @@ bool FileExpertSource::claim_stage(int64_t key, size_t& v, bool& fill, bool ahea uint8_t* raw = pinned ? (uint8_t*) p : new (std::nothrow) uint8_t[(size_t) stage_blob_]; if (raw == nullptr) return false; stage_buf_.emplace_back(raw, StageBufFree{pinned}); + stage_idx_[raw] = stage_buf_.size() - 1; + stage_ev_.push_back(nullptr); + stage_ev_live_.push_back(0); if (pinned && !stage_pin_said_) { stage_pin_said_ = true; std::fprintf(stderr, "FileExpertSource: the stage buffers are pinned (cudaHostAlloc)\n"); @@ -1228,6 +1234,19 @@ bool FileExpertSource::claim_stage(int64_t key, size_t& v, bool& fill, bool ahea } else { stage_of_.erase(stage_key_[v]); if (stage_pf_[v]) { stage_pf_[v] = 0; io_pf_unused_.fetch_add(1, std::memory_order_relaxed); } // read ahead, never asked for + // #1237: a page-locked buffer is read by the DMA after the copy call returned: it is refilled only once the + // last copy queued out of it (note_async_read) has finished. Rare: the pool is sized so that a buffer asked + // for has long been consumed; a wait here means the stream is more than a pool behind. + if (v < stage_ev_live_.size() && stage_ev_live_[v]) { + stage_ev_live_[v] = 0; + if (stage_ev_[v] != nullptr) { + if (cudaEventQuery((cudaEvent_t) stage_ev_[v]) == cudaErrorNotReady) { + stage_fence_waits_.fetch_add(1, std::memory_order_relaxed); + (void) cudaEventSynchronize((cudaEvent_t) stage_ev_[v]); + } + (void) cudaGetLastError(); + } + } } stage_key_[v] = key; stage_epoch_[v] = epoch_; @@ -1263,6 +1282,38 @@ void FileExpertSource::publish_stage(size_t v, int64_t layer, bool ok, double us stage_cv_.notify_all(); } +void FileExpertSource::note_async_read(const uint8_t* blob, void* stream) { + if (blob == nullptr) return; + std::lock_guard lk(stage_mu_); + const auto it = stage_idx_.find(blob); + if (it == stage_idx_.end()) return; // not a stage buffer: the mapping or the resident arena + const size_t v = it->second; + if (!stage_buf_[v].get_deleter().pinned) return; // pageable: the driver copied it before the call returned + if (stage_ev_[v] == nullptr) { + cudaEvent_t ev = nullptr; + if (cudaEventCreateWithFlags(&ev, cudaEventDisableTiming) != cudaSuccess) { + (void) cudaGetLastError(); + (void) cudaStreamSynchronize((cudaStream_t) stream); // no event: wait for the copy itself + return; + } + stage_ev_[v] = ev; + } + if (cudaEventRecord((cudaEvent_t) stage_ev_[v], (cudaStream_t) stream) != cudaSuccess) { + (void) cudaGetLastError(); + (void) cudaStreamSynchronize((cudaStream_t) stream); + return; + } + stage_ev_live_[v] = 1; +} + +void FileExpertSource::stage_free_events() { + for (void*& e : stage_ev_) + if (e != nullptr) { (void) cudaEventDestroy((cudaEvent_t) e); e = nullptr; } + stage_ev_.clear(); + stage_ev_live_.clear(); + stage_idx_.clear(); +} + const uint8_t* FileExpertSource::staged_blob(int64_t layer, int64_t expert) { const int64_t key = layer * n_expert_ + expert; size_t v = 0; @@ -3422,6 +3473,7 @@ void expert_hit_run(void* user, void* stream, HitPhase phase, const int32_t* ids d.fail_expert = e; return; } + d.src->note_async_read(b, cs); // #1237: a page-locked stage buffer is not recycled under the queued copy ++d.cache_admitted; slot = cand; } else { diff --git a/src/core/peer_experts.cpp b/src/core/peer_experts.cpp index f68a2e0a..6c8f567e 100644 --- a/src/core/peer_experts.cpp +++ b/src/core/peer_experts.cpp @@ -170,6 +170,7 @@ bool PeerExperts::open(int device, const std::vector close(); return false; } + src.note_async_read(b, refill_); // #1237 res_[(size_t) (pr.first * n_expert + pr.second)] = slot; } if (!ck(cudaStreamSynchronize(refill_), "fill", err)) { close(); return false; } diff --git a/src/core/remote_expert_opt.cu b/src/core/remote_expert_opt.cu index 229781c8..7ddb45e2 100644 --- a/src/core/remote_expert_opt.cu +++ b/src/core/remote_expert_opt.cu @@ -178,9 +178,12 @@ bool RemoteExpertOpt::adapt(const std::vector& usage, const std::vector max_swaps) swaps.resize((size_t) max_swaps); if (swaps.empty()) continue; const OnDevice on(r.device_); - for (const auto& s : swaps) - if (!r.cache_.fill_slot(r.cache_.slot_of(s.layer, s.out), source.blob(s.layer, s.in), + for (const auto& s : swaps) { + const uint8_t* in_blob = source.blob(s.layer, s.in); + if (!r.cache_.fill_slot(r.cache_.slot_of(s.layer, s.out), in_blob, r.stream_, err, (int64_t) lay.blob_bytes(s.layer))) return false; + source.note_async_read(in_blob, r.stream_); // #1237 + } if (!check(cudaStreamSynchronize(r.stream_), err)) return false; for (const auto& s : swaps) { r.cache_.replace(s.layer, s.out, s.in); From cec7e2b1f6a5a5036477859b90f8b65dd221c811 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 9 Oct 2026 03:17:31 +0200 Subject: [PATCH 2/7] --batch on a layer split: a BYIELD is taken even when no slot is decoding A prompt read on a layer split with no slot decoding was one run, so the BYIELD of the batch_interleave_test step 4 was dropped at the end of the read; the long prompt kept its slot and the next BGEN failed with 'ERR BGEN: no such free slot' (pre-existing since 0.1.40.4). That read now goes in pieces of STRATA_BATCH_YIELD_CHUNKS chunks (default 8, 0 = one run), the same chunks a single run reads, with the yield check between pieces. batch_read_piece holds the arithmetic; batch_read_test covers it. --- CMakeLists.txt | 4 ++++ include/strata/program/batch_read.hpp | 30 +++++++++++++++++++++++++ src/program/generate.cpp | 13 ++++++++--- tests/program/batch_read_test.cpp | 32 +++++++++++++++++++++++++++ 4 files changed, 76 insertions(+), 3 deletions(-) create mode 100644 include/strata/program/batch_read.hpp create mode 100644 tests/program/batch_read_test.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 6e0ce1c4..f65d8687 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -244,6 +244,10 @@ if(STRATA_BUILD_TESTS) add_executable(gguf_split_test tests/core/gguf_split_test.cpp) target_link_libraries(gguf_split_test PRIVATE strata_artifact) add_test(NAME gguf_split_test COMMAND gguf_split_test) + # how --batch cuts a prompt read into pieces (a layer split with no slot decoding must still reach a BYIELD) + add_executable(batch_read_test tests/program/batch_read_test.cpp) + target_include_directories(batch_read_test PRIVATE include) + add_test(NAME batch_read_test COMMAND batch_read_test) # the hipBLASLt tuning header's architecture gate: RDNA4 siblings share solution IDs, RDNA3 siblings share # theirs, cross-family pairs and version mismatches stay rejected (synthetic tables: no model, no GPU) diff --git a/include/strata/program/batch_read.hpp b/include/strata/program/batch_read.hpp new file mode 100644 index 00000000..c9036138 --- /dev/null +++ b/include/strata/program/batch_read.hpp @@ -0,0 +1,30 @@ +// include/strata/program/batch_read.hpp - how --batch reads a prompt in pieces (header-only: it is arithmetic). +// +// A prompt read with --batch stops between two pieces to (a) let the slots decode and (b) look for a BYIELD (a +// shorter request is waiting). The pieces always end on a multiple of the prompt chunk, so they read exactly the +// chunks a single run would. +#pragma once + +#include +#include + +namespace strata::program { + +/// Tokens of the next piece of a --batch prompt read, or 0 for "the whole rest in one run". +/// beside_slots: some slot is decoding (its windows run between the pieces) +/// layer_split / piped: the read goes through a layer split's stages / the pipelined groups +/// chunks_per_piece: for a layer split with no slot decoding, the pieces' length in chunks (0: one run) +/// A layer split reads its stages as a pipeline over one run's chunks, so a piece costs a pipeline fill; with slots +/// decoding the pieces are single chunks anyway. With no slot decoding a piece is `chunks_per_piece` chunks: long +/// enough to keep the pipeline full, short enough that a BYIELD is taken within a few chunks (it used to wait for the +/// whole prompt, and the long prompt then held its slot: "ERR BGEN: no such free slot" for the request that should +/// have taken over). +inline int64_t batch_read_piece(bool batch, bool piped, bool layer_split, bool beside_slots, int64_t chunk, + int64_t chunks_per_piece) { + if (!batch || piped) return 0; + chunk = std::max(chunk, 1); + if (!layer_split || beside_slots) return chunk; + return chunks_per_piece > 0 ? chunk * chunks_per_piece : 0; +} + +} // namespace strata::program diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 433d3957..1d817846 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -58,6 +58,7 @@ #include "strata/core/mtp.hpp" #include "strata/prefill/prefill.hpp" #include "strata/core/native_dense.hpp" +#include "strata/program/batch_read.hpp" #include "strata/program/logits_selection.hpp" #include "strata/program/conv_cache.hpp" #include "strata/program/message_boundary.hpp" @@ -9702,11 +9703,17 @@ int main(int argc, char** argv) { // the request ends with `YIELDED ` + DONE cancel, and the server sends it again later: it // continues from the slot with the same chunks. #656's cooperative preemption, with a slot as the park. auto read_part = [&](int64_t a0, int64_t b0, std::string& e) -> bool { - // (a layer split reads its stages as a pipeline over one run's chunks: in pieces only beside slots) - if (o.batch <= 0 || piped || (!stages.empty() && !batch_on())) return sp.run(ids.data() + a0, b0 - a0, a0, e); + // (a layer split reads its stages as a pipeline over one run's chunks: beside slots a chunk at a time, with + // none decoding in pieces of STRATA_BATCH_YIELD_CHUNKS chunks (default 8; 0 = one run) so a BYIELD is taken) + static const int64_t yield_chunks = [] { + const char* v = std::getenv("STRATA_BATCH_YIELD_CHUNKS"); + return v != nullptr ? (int64_t) std::max(0, std::atoi(v)) : (int64_t) 8; + }(); const int64_t C = std::max(sp.chunk(), 1); + const int64_t piece = strata::program::batch_read_piece(o.batch > 0, piped, !stages.empty(), batch_on(), C, yield_chunks); + if (piece <= 0) return sp.run(ids.data() + a0, b0 - a0, a0, e); for (int64_t q = a0; q < b0;) { - const int64_t r = std::min(b0, q + C); + const int64_t r = std::min(b0, q + piece); const auto tq = Clock::now(); if (!sp.run(ids.data() + q, r - q, q, e)) return false; q = r; diff --git a/tests/program/batch_read_test.cpp b/tests/program/batch_read_test.cpp new file mode 100644 index 00000000..d9842381 --- /dev/null +++ b/tests/program/batch_read_test.cpp @@ -0,0 +1,32 @@ +// batch_read_piece: the pieces of a --batch prompt read (synthetic: no model, no GPU). +#include "strata/program/batch_read.hpp" + +#include + +using strata::program::batch_read_piece; + +static int fails = 0; +#define CHECK(c) do { if (!(c)) { std::printf("FAIL %s:%d %s\n", __FILE__, __LINE__, #c); ++fails; } } while (0) + +int main() { + // no --batch, or the pipelined groups: one run + CHECK(batch_read_piece(false, false, false, false, 2048, 8) == 0); + CHECK(batch_read_piece(true, true, true, false, 2048, 8) == 0); + // one GPU: a chunk per piece, whether or not a slot decodes (the yield point is the chunk boundary) + CHECK(batch_read_piece(true, false, false, false, 2048, 8) == 2048); + CHECK(batch_read_piece(true, false, false, true, 2048, 8) == 2048); + // layer split with slots decoding: a chunk per piece as before + CHECK(batch_read_piece(true, false, true, true, 2048, 8) == 2048); + // layer split, nobody decoding: pieces of 8 chunks - the BYIELD of a shorter request can be taken (it was one run) + CHECK(batch_read_piece(true, false, true, false, 2048, 8) == 8 * 2048); + CHECK(batch_read_piece(true, false, true, false, 1024, 4) == 4096); + // STRATA_BATCH_YIELD_CHUNKS=0 keeps the old single run + CHECK(batch_read_piece(true, false, true, false, 2048, 0) == 0); + // a degenerate chunk never gives a zero piece + CHECK(batch_read_piece(true, false, false, false, 0, 8) == 1); + // a piece is always a multiple of the chunk + for (int64_t c : {256, 1000, 2048, 4096}) + for (int64_t k : {1, 3, 8, 16}) CHECK(batch_read_piece(true, false, true, false, c, k) % c == 0); + if (fails == 0) std::printf("batch_read_test: ok\n"); + return fails == 0 ? 0 : 1; +} From 8bb250d84628363c455397c68fea56c8a863759b Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 9 Oct 2026 03:17:32 +0200 Subject: [PATCH 3/7] Layer split auto: warn on a near tie between two different splits on a mixed pair (#1428) When the best split and a different one (boundaries at least 3 layers away, startable) are within 4% predicted decode window (STRATA_SPLIT_NEAR_TIE_PCT, 0 = off) and the cards differ in speed or link, print the other K and --layer-split K. The model prices decode only, not the prompt. Print only: the choice is unchanged. --- src/program/generate.cpp | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 1d817846..ff425cfd 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -3556,11 +3556,15 @@ int main(int argc, char** argv) { return parts; }; bool gate_on = true; // off only when no placement can start (below): then the best one is kept and a warning said + // #1428: 2 and 3 GPUs - every placement priced, kept (a few hundred) so the near-tie warning below can name the + // best placement that is really a different one (not the neighbour one layer over) + std::vector>> priced; auto consider = [&]() { double hm = 0; int64_t held = 0; const double ms = predict(at, hm, held); ++tried; + if (ns <= 3) priced.emplace_back(ms, at); const double mx = stage_max(at); if (ms < best_ms - tie_eps || (ms <= best_ms + tie_eps && mx < best_max - tie_eps)) { // feasibility gate: mirrors the serve path (`fits_one` + own_fits) for the 512-token last resort; @@ -3584,6 +3588,7 @@ int main(int argc, char** argv) { consider(); }; auto search = [&]() { + priced.clear(); if (ns == 2) { for (int64_t k = 2; k < L; ++k) { at[0] = k; consider(); } // a model with fewer than three layers enumerates nothing: keep the proportional guess rather than @@ -3721,6 +3726,39 @@ int main(int argc, char** argv) { std::fprintf(stderr, "strata generate: layer split auto: K=%s - predicted %.1f ms per decode window; the caches " "hold %lld of %zu profiled pairs (~%.1f%% of the routed mass), best of %lld placements\n", ks.c_str(), best_ms, (long long) best_held, profile.size(), 100.0 * best_mass, (long long) tried); + // #1428: a near tie on a mixed pair. The model prices a decode window only (the prompt path is not in it), and on + // cards of different speed or link the winner can flip within a few percent of error: say which other split is + // almost as good, so the user can try it. Recommend, never force: this only prints. + { + const double lo = *std::min_element(layer_ms.begin(), layer_ms.end()); + const double hi = *std::max_element(layer_ms.begin(), layer_ms.end()); + const double llo = *std::min_element(link_scale.begin(), link_scale.end()); + const double lhi = *std::max_element(link_scale.begin(), link_scale.end()); + const bool mixed = hi > lo * 1.10 || lhi > llo * 1.10; + const double near_pct = std::getenv("STRATA_SPLIT_NEAR_TIE_PCT") ? std::atof(std::getenv("STRATA_SPLIT_NEAR_TIE_PCT")) : 4.0; + if (mixed && near_pct > 0 && ns <= 3 && best_ms > 0 && !priced.empty()) { + const std::vector* alt = nullptr; + double alt_ms = 1e30; + for (const auto& pc : priced) { + if (pc.first > best_ms * (1.0 + near_pct / 100.0) || pc.first >= alt_ms) continue; + int64_t dist = 0; // how far the other split's boundaries lie from the chosen one's + for (size_t i = 0; i < pc.second.size() && i < best.size(); ++i) + dist = std::max(dist, std::llabs(pc.second[i] - best[i])); + if (dist < 3) continue; // the neighbour one layer over is not a different split + if (gate_on && !can_start(parts_of(pc.second))) continue; + alt = &pc.second; + alt_ms = pc.first; + } + if (alt != nullptr) { + std::string as; + for (const int64_t k : *alt) as += (as.empty() ? "" : ",") + std::to_string(k); + std::fprintf(stderr, "strata generate: layer split auto: NEAR TIE - K=%s is predicted %.1f ms per decode " + "window, within %.1f%% of K=%s (%.1f ms); the cards differ, so the prediction may not " + "rank them (it prices decode, not the prompt). To try the other: --layer-split %s\n", + as.c_str(), alt_ms, 100.0 * (alt_ms / best_ms - 1.0), ks.c_str(), best_ms, as.c_str()); + } + } + } } for (size_t i = 0; i < split_at.size(); ++i) if (split_at[i] >= g.n_layers) { From a26fcbcdba7e905b0052fcd7a9c7087407470ad4 Mon Sep 17 00:00:00 2001 From: sergiywith Date: Fri, 9 Oct 2026 03:17:42 +0200 Subject: [PATCH 4/7] prefill: bytes_needed sizes the MoE buffers for the layout init picks (with or without an expert source) 0.1.39 took this PR's first part with #583 (the xn / grs count, STRATA_RING_BYTES). What is left: bytes_needed counted the fused layout's smaller MoE buffers for every caller (fused_layout(T, true)), while init takes them only when it gets an ExpertSource (fused_layout(T, m.src != nullptr)). A prompt path without one was lent fewer bytes than its unfused buffers take. bytes_needed, bytes_needed_no_ring and (0.1.40) bytes_needed_owned - STRATA_OWNED_PRICE=exact's sizing - now take the same src the callers pass to init. --- include/strata/prefill/prefill.hpp | 14 +++++++++----- src/prefill/prefill.cpp | 20 +++++++++++--------- src/program/generate.cpp | 14 +++++++------- 3 files changed, 27 insertions(+), 21 deletions(-) diff --git a/include/strata/prefill/prefill.hpp b/include/strata/prefill/prefill.hpp index c1b0a911..5be63ac3 100644 --- a/include/strata/prefill/prefill.hpp +++ b/include/strata/prefill/prefill.hpp @@ -88,15 +88,19 @@ public: /// fits it keeps 0.1.39's ring). 0 slots = none. A layer split's set_ring_override and STRATA_PREFILL_RING win. static void set_ring_budget(int slots, int64_t small_max); - /// Device bytes `init` needs for a chunk of `chunk` tokens (what a borrowed region must hold). - static uint64_t bytes_needed(const core::ModelGeometry& g, const core::SessionState& ss, int64_t chunk); + /// Device bytes `init` needs for a chunk of `chunk` tokens (what a borrowed region must hold). `src`: init gets an + /// ExpertSource (carve picks the fused MoE layout only then). + static uint64_t bytes_needed(const core::ModelGeometry& g, const core::SessionState& ss, int64_t chunk, + bool src = true); /// The same without the streamed ring: what the chunk's own buffers cost. The auto chunk scan sizes the chunk /// first and hands the ring what the chunk leaves over, so it needs the chunk priced on its own. /// What `init` allocates when the prompt path OWNS its buffers: each cudaMalloc rounded up to a 2 MiB page and the /// ring as one allocation (the startup sizing of a cache without a loan). - static uint64_t bytes_needed_owned(const core::ModelGeometry& g, const core::SessionState& ss, int64_t chunk); - static uint64_t bytes_needed_no_ring(const core::ModelGeometry& g, const core::SessionState& ss, int64_t chunk); + static uint64_t bytes_needed_owned(const core::ModelGeometry& g, const core::SessionState& ss, int64_t chunk, + bool src = true); + static uint64_t bytes_needed_no_ring(const core::ModelGeometry& g, const core::SessionState& ss, int64_t chunk, + bool src = true); /// The streamed ring's byte budget as a slot count for this pack (the measured slot count x Q2_0's blob, over /// max_blob, never past ring_cap()): @@ -183,7 +187,7 @@ public: private: static uint64_t bytes_needed_impl(const core::ModelGeometry& g, const core::SessionState& ss, int64_t chunk, - bool owned_pages); + bool owned_pages, bool src); kernels::cpu::ExpertPool* cpu_pool_ = nullptr; ///< set_cpu_pool // Stage-1 pipeline: intermediate stages return after handing their chunk to // the direct successor. The public run() drains the chain once at prompt end. diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index 4e03dc8b..89e0b1f0 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -1743,19 +1743,20 @@ void Prefill::set_ring_budget(int slots, int64_t small_max) { double Prefill::pinned_share() { return g_pinned_share; } int64_t Prefill::stream_all_min_tokens() { return stream_all_min(); } -uint64_t Prefill::bytes_needed(const core::ModelGeometry& g, const core::SessionState& ss, int64_t chunk) { - return bytes_needed_impl(g, ss, chunk, false); +uint64_t Prefill::bytes_needed(const core::ModelGeometry& g, const core::SessionState& ss, int64_t chunk, bool src) { + return bytes_needed_impl(g, ss, chunk, false, src); } // What `init` really allocates when the prompt path owns its buffers (no loan): every cudaMalloc rounds up to a 2 MiB // page, and the ring is one allocation (carve). `bytes_needed` stays the borrowed region's sum. -uint64_t Prefill::bytes_needed_owned(const core::ModelGeometry& g, const core::SessionState& ss, int64_t chunk) { - return bytes_needed_impl(g, ss, chunk, true); +uint64_t Prefill::bytes_needed_owned(const core::ModelGeometry& g, const core::SessionState& ss, int64_t chunk, + bool src) { + return bytes_needed_impl(g, ss, chunk, true, src); } uint64_t Prefill::bytes_needed_impl(const core::ModelGeometry& g, const core::SessionState& ss, int64_t chunk, - bool owned_pages) { - // the same allocation sequence as `init`, counted + bool owned_pages, bool src) { + // the same allocation sequence as `init` (`carve`), counted - with the MoE layout `carve` picks for the same source const size_t T = (size_t) chunk; bool ok = true; Alloc o; @@ -1789,7 +1790,7 @@ uint64_t Prefill::bytes_needed_impl(const core::ModelGeometry& g, const core::Se const int64_t cap = strata::kernels::qsa_selection_width(strata::kernels::kTopkMaxCells, s); const int64_t max_blocks = ss.qsa_states[ss.qsa_primary()].max_cells / s.idx_block + 2; o.take((size_t) std::max({gdn_set_bytes(T), qsa_set_bytes(T, cap, max_blocks, 256, 32, s), - moe_set_bytes(T, g.n_expert, fused_layout(T, true))}), ok); + moe_set_bytes(T, g.n_expert, fused_layout(T, src))}), ok); for (int i = 0; i < DQ; ++i) { o.take(1280 * 2560, ok); o.take(2560 * 640, ok); } if (mmq_plan().any) { const MmqPlan& mp = mmq_plan(); @@ -1810,8 +1811,9 @@ uint64_t Prefill::bytes_needed_impl(const core::ModelGeometry& g, const core::Se return o.used + (8u << 20); // alignment slack } -uint64_t Prefill::bytes_needed_no_ring(const core::ModelGeometry& g, const core::SessionState& ss, int64_t chunk) { - return bytes_needed(g, ss, chunk) - (uint64_t) ring_slots((size_t) chunk) * (uint64_t) MAXBLOB(); +uint64_t Prefill::bytes_needed_no_ring(const core::ModelGeometry& g, const core::SessionState& ss, int64_t chunk, + bool src) { + return bytes_needed(g, ss, chunk, src) - (uint64_t) ring_slots((size_t) chunk) * (uint64_t) MAXBLOB(); } int64_t Prefill::ring_default_slots() { diff --git a/src/program/generate.cpp b/src/program/generate.cpp index ff425cfd..dd88845d 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -4336,7 +4336,7 @@ int main(int argc, char** argv) { if (!(o.prefill_chunk > 0 && !pf_borrow)) return 0; static const bool exact = [] { const char* v = std::getenv("STRATA_OWNED_PRICE"); return v != nullptr && std::string(v) == "exact"; }(); if (!exact) return 160 + (o.prefill_chunk * 680) / 1024; - const int64_t mib = ((int64_t) strata::prefill::Prefill::bytes_needed_owned(g, ss, o.prefill_chunk) + (1 << 20) - 1) >> 20; + const int64_t mib = ((int64_t) strata::prefill::Prefill::bytes_needed_owned(g, ss, o.prefill_chunk, srcp != nullptr) + (1 << 20) - 1) >> 20; std::fprintf(stderr, "strata generate: STRATA_OWNED_PRICE=exact: the prompt path's own buffers for a %lld-token chunk: %lld MiB (the 0.1.39 rule: %lld MiB)\n", (long long) o.prefill_chunk, (long long) mib, (long long) (160 + (o.prefill_chunk * 680) / 1024)); return mib + 64; // a margin for the allocator @@ -5749,7 +5749,7 @@ int main(int argc, char** argv) { return (uint64_t) k * (uint64_t) strata::kernels::cpu::expert_layout().max_blob; }; auto lend_slots = [&](int64_t c) -> int64_t { - return slots_from_bytes(strata::prefill::Prefill::bytes_needed(g, ss, c)); + return slots_from_bytes(strata::prefill::Prefill::bytes_needed(g, ss, c, srcp != nullptr)); }; // `lend_bytes` went with the single-cache serve loan: a participant's loan is priced by `part_bytes` from its // OWN cache, and the only other user of the old helper was the serve path's own relayout. @@ -5854,7 +5854,7 @@ int main(int argc, char** argv) { const int64_t blob = (int64_t) strata::kernels::cpu::expert_layout().max_blob; const uint64_t avail = bytes_from_slots(budget); auto room_of = [&](int64_t t) -> int64_t { - const uint64_t nonring = strata::prefill::Prefill::bytes_needed_no_ring(g, ss, t); + const uint64_t nonring = strata::prefill::Prefill::bytes_needed_no_ring(g, ss, t, srcp != nullptr); return std::min((int64_t) ((avail - std::min(avail, nonring)) / (uint64_t) blob), ring_max); }; // `room_of` is capped at ring_max, so "the ring is full" is exactly room == ring_max, and both that @@ -6286,7 +6286,7 @@ int main(int argc, char** argv) { return (int64_t) ((need + (uint64_t) blob - 1) / (uint64_t) blob); }; auto part_slots = [&](const PfPart& p, int64_t c) -> int64_t { - return cache_slots_for(*p.cache, strata::prefill::Prefill::bytes_needed(g, *p.ses, c)); + return cache_slots_for(*p.cache, strata::prefill::Prefill::bytes_needed(g, *p.ses, c, srcp != nullptr)); }; auto part_bytes = [&](const PfPart& p, int32_t first) -> uint64_t { strata::core::ExpertCache& xc = *p.cache; @@ -6359,7 +6359,7 @@ int main(int argc, char** argv) { const int64_t budget = std::max(0, std::min(p.cache->slots() - 128, kAutoLendPct * p.cache->slots() / 100)); const uint64_t avail = part_bytes(p, (int32_t) (p.cache->slots() - budget)); - const uint64_t nonring = strata::prefill::Prefill::bytes_needed_no_ring(g, *p.ses, c); + const uint64_t nonring = strata::prefill::Prefill::bytes_needed_no_ring(g, *p.ses, c, srcp != nullptr); room = std::min(room, (int64_t) ((avail - std::min(avail, nonring)) / (uint64_t) kBlob)); } return room; @@ -6472,7 +6472,7 @@ int main(int argc, char** argv) { const strata::core::OnDevice on(p.dev); size_t fb = 0, tb = 0; if (cudaMemGetInfo(&fb, &tb) != cudaSuccess) { (void) cudaGetLastError(); continue; } - const uint64_t need = strata::prefill::Prefill::bytes_needed(g, *p.ses, chunk); + const uint64_t need = strata::prefill::Prefill::bytes_needed(g, *p.ses, chunk, srcp != nullptr); if ((uint64_t) fb >= need + (3ull << 29)) { std::fprintf(stderr, "strata serve: CUDA%d keeps its own prompt buffers (%.2f GiB of " "%.2f GiB free): no loan\n", p.dev < 0 ? 0 : p.dev, @@ -6562,7 +6562,7 @@ int main(int argc, char** argv) { const strata::core::OnDevice on(dev); size_t fb = 0, tb = 0; cudaMemGetInfo(&fb, &tb); - const int64_t need = (int64_t) strata::prefill::Prefill::bytes_needed(g, i == 0 ? ss : stages[i - 1]->ss, c); + const int64_t need = (int64_t) strata::prefill::Prefill::bytes_needed(g, i == 0 ? ss : stages[i - 1]->ss, c, srcp != nullptr); if (need + kHeadroom > (int64_t) fb) { dev_out = dev < 0 ? 0 : dev; need_out = need; free_out = (int64_t) fb; return false; From 71eaee17b91d7a71407005a8b68a9f18c29173dc Mon Sep 17 00:00:00 2001 From: Hulk Date: Fri, 9 Oct 2026 03:18:07 +0200 Subject: [PATCH 5/7] spec: re-probe stale full chains when shorter chains pay A profitable shorter chained lookup returned before the stale full-size check, so the full chain could stay excluded for good although the policy re-probes stale sizes in the other selection paths (#1252). Check a confident stale full size before returning the profitable shorter chain. The 300-round policy, the EMA, the header and plain lookup are unchanged; a regression test covers the bounded re-probe spacing and the MTP confidence gate. --- src/spec/draft_policy.cpp | 8 ++++++-- src/spec/draft_policy_test.cpp | 24 ++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/src/spec/draft_policy.cpp b/src/spec/draft_policy.cpp index 9b9eb0a8..8d422789 100644 --- a/src/spec/draft_policy.cpp +++ b/src/spec/draft_policy.cpp @@ -128,9 +128,13 @@ int DraftPolicy::chain(int t_mtp, double p_mtp, int k_avail, int match) const { const double r = (e0 + p_mtp * gain) / cost_ms(t_mtp + k); if (r > best) { best = r; best_k = k; } } - if (best_k > 0 && best > base * (1.0 + margin_)) return best_k; - // as choose(): a size whose cost is only guessed is tried a few times when the continuation looks likely const int t_full = t_mtp + kmax; + if (best_k > 0 && best > base * (1.0 + margin_)) { + // As choose(): a profitable shorter chain must not keep a stale full size from being measured again. + if (best_k < kmax && p_mtp * c >= 0.6 && stale(t_full)) return kmax; + return best_k; + } + // as choose(): a size whose cost is only guessed is tried a few times when the continuation looks likely if ((cost_n_[t_full] < kProbes || stale(t_full)) && p_mtp * c >= 0.6) return kmax; return 0; } diff --git a/src/spec/draft_policy_test.cpp b/src/spec/draft_policy_test.cpp index 923fc79d..48a4f795 100644 --- a/src/spec/draft_policy_test.cpp +++ b/src/spec/draft_policy_test.cpp @@ -90,6 +90,30 @@ int main() { check(q.chain(4, 0.9, 3, 4) == 0, "chain: dear rows, never accepted -> none"); check(q.chain(4, 0.9, 0, 4) == 0 && q.chain(8, 1.0, 3, 40) == 0, "chain: nothing proposed / no room -> none"); } + { + // The stale-size check must also run when a shorter chain already pays. Synthetic costs isolate the + // selection policy: even a size that stays expensive is retried, but only once per stale interval. + DraftPolicy p(6); + for (int i = 0; i < 3; ++i) p.observe(false, 4, 3, 0, 40.0); + for (int i = 0; i < 3; ++i) p.observe_chain(4, 1, 4, 40, 42.0); + for (int i = 0; i < 3; ++i) p.observe_chain(4, 2, 5, 40, 1000.0); + check(p.chain(4, 1.0, 2, 40) == 1, "chain: the profitable shorter chain initially wins"); + int probes = 0, last_probe = -1; + bool spaced = true, confident = true; + for (int i = 0; i < 1000; ++i) { + const int k = p.chain(4, 1.0, 2, 40); + if (k == 2) { + ++probes; + spaced &= last_probe < 0 ? i >= 300 : i - last_probe > 300; + last_probe = i; + confident &= p.chain(4, 0.5, 2, 40) < 2; + } + p.observe_chain(4, k, 3 + k, 40, k == 2 ? 1000.0 : 42.0); + } + check(probes > 0 && probes <= 3 && spaced, + "chain: stale full size is re-probed despite a profitable shorter chain"); + check(probes > 0 && confident, "chain: stale re-probes retain the MTP confidence gate"); + } std::printf(g_fail ? "FAIL\n" : "PASS\n"); return g_fail ? 1 : 0; } From 56354964d82adaa379c95c06129b68ff918a4fa5 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 9 Oct 2026 10:11:10 +0200 Subject: [PATCH 6/7] Stage buffers: fence the lent-slot refill copies too (#1237) The refills of the slots a prompt borrowed (and the VRAM-resize refill) queue hundreds of cudaMemcpyAsync out of blob_stable() pointers, which for a GGUF source are the recycled stage buffers. With STRATA_STAGE_PIN=1 the 257th assembly overwrote a buffer whose copy had not run: IQ3_XXS lowmem (budget 12) decoded token id 0 after a 4096-token prompt. Each queued copy now records the fence of its buffer. exact_pp 4096 and 20000 tokens with STRATA_STAGE_PIN=1: EXACT. --- src/program/generate.cpp | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/src/program/generate.cpp b/src/program/generate.cpp index dd88845d..e03cd2d5 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -6700,6 +6700,19 @@ int main(int argc, char** argv) { strata::core::Verifier ver; strata::core::VerifyHits vh; vh.d_res = thits.d_res; + // STRATA_ROUTE_RESIDENT_MTP=1 (EXPERIMENTAL, with STRATA_ROUTE_RESIDENT=; changes the output): the MTP + // draft's router gets the same residency bias, with the last layer's residency row as its table (single GPU) + if (use_mtp && stages.empty() && thits.d_res != nullptr && std::getenv("STRATA_ROUTE_RESIDENT") != nullptr && + std::getenv("STRATA_ROUTE_RESIDENT_MTP") != nullptr && std::atoi(std::getenv("STRATA_ROUTE_RESIDENT_MTP")) != 0) { + const float margin = (float) std::atof(std::getenv("STRATA_ROUTE_RESIDENT")); + int lo = 6, hi = 9; + if (const char* v = std::getenv("STRATA_ROUTE_RESIDENT_RANKS")) std::sscanf(v, "%d-%d", &lo, &hi); + if (margin > 0.0f) { + mtp.set_route_resident(thits.d_res + (size_t) (g.n_layers - 1) * (size_t) g.n_expert, margin, lo, hi); + std::fprintf(stderr, "strata generate: STRATA_ROUTE_RESIDENT_MTP: the MTP draft's router is biased toward layer %lld's resident experts (margin %g, ranks %d-%d; experimental)\n", + (long long) (g.n_layers - 1), margin, lo, hi); + } + } vh.h_res = host_res.empty() ? nullptr : host_res.data(); vh.cache_base = thits.cache_base; vh.blob = thits.blob; @@ -8268,6 +8281,7 @@ int main(int argc, char** argv) { e = "VRAM: refilling the cache failed: " + ferr; return false; } + srcp->note_async_read(b, nullptr); // #1237: the queued copy reads a stage buffer; it is not recycled under it host_res[(size_t) pick] = slot; } vram_evicted.swap(keep_out); @@ -9622,6 +9636,7 @@ int main(int argc, char** argv) { if (b == nullptr || !(refill_blocking() ? p.cache->fill_slot_blocking(slot, b, e, nb) : p.cache->fill_slot_queued(slot, b, e, nb))) return false; + if (!refill_blocking()) srcp->note_async_read(b, nullptr); // #1237 host_res[(size_t) i] = slot; } return true; @@ -11262,6 +11277,7 @@ int main(int argc, char** argv) { std::fprintf(stderr, "strata generate: refilling a lent slot failed: %s\n", err.c_str()); return 1; } + if (!refill_blocking()) srcp->note_async_read(b, nullptr); // #1237 host_res[(size_t) i] = slot; } if (!xcache.sync_queued(err)) { From 8bf203f56be12a6f81855db7a772e0b4ea4d995a Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 9 Oct 2026 10:11:10 +0200 Subject: [PATCH 7/7] STRATA_ROUTE_RESIDENT: per-GPU counters owned by the verifier (#1578) The counter block was one process-wide cudaMalloc on whichever device was current at the first Verifier::init, unreachable from the other stage's kernels on a layer split without P2P. Each verifier now takes its own device's block in init (outside graph capture), keeps the pointer, and a launch never picks by the host thread's device; a failed allocation runs without counters. The exit report prints one block per GPU when there are several (single GPU: the same lines as before). The reporter's rare fault with --pipeline-windows 2 after this fix is not reproduced here (needs two GPUs). STRATA_ROUTE_RESIDENT_MTP=1 (experimental, opt-in, changes the output): the MTP draft's router gets the same residency bias, with the last layer's residency row as its table (single GPU). --- include/strata/core/mtp.hpp | 9 +++++ include/strata/core/verify.hpp | 1 + src/core/mtp.cpp | 5 +++ src/core/verify.cpp | 69 ++++++++++++++++++++++++---------- 4 files changed, 64 insertions(+), 20 deletions(-) diff --git a/include/strata/core/mtp.hpp b/include/strata/core/mtp.hpp index d2266e55..827dac39 100644 --- a/include/strata/core/mtp.hpp +++ b/include/strata/core/mtp.hpp @@ -46,6 +46,12 @@ public: int64_t window = 32768, const MtpDrafter* shared = nullptr); /// The prompt's length: prefill() skips the cells the attention window can never reach again. void set_prompt_len(int64_t n) { prompt_len_ = n; } + /// STRATA_ROUTE_RESIDENT_MTP=1 (EXPERIMENTAL, opt-in, changes the output): the draft layer's router is biased like + /// the verifier's STRATA_ROUTE_RESIDENT, with `res_row` (a device residency row of 512 experts: slot or -1) as the + /// table. nullptr switches it off. + void set_route_resident(const int32_t* res_row, float margin, int lo, int hi) { + rr_res_ = res_row; rr_margin_ = margin; rr_lo_ = lo; rr_hi_ = hi; + } /// At most this many drafts per round (below max_t - 1): a window longer than the MTP's comes from elsewhere. void set_max_drafts(int k) { max_drafts_ = k; } /// --mtp-hnorm stream (opt-in; before the first draft or prefill): pre_fc_norm_hidden normalizes each @@ -251,6 +257,9 @@ private: std::string rt_dir_; int64_t window_ = 0; // attention over the last window_ cells (0 = every cell) int64_t prompt_len_ = 0; + const int32_t* rr_res_ = nullptr; + float rr_margin_ = 0.0f; + int rr_lo_ = 6, rr_hi_ = 9; float* probs_ = nullptr; uint8_t* arg_scratch_ = nullptr; ///< argmax_rows' and row_top_prob_split's partials and counters uint8_t* top_scratch_ = nullptr; diff --git a/include/strata/core/verify.hpp b/include/strata/core/verify.hpp index deb25f0a..16849810 100644 --- a/include/strata/core/verify.hpp +++ b/include/strata/core/verify.hpp @@ -342,6 +342,7 @@ private: int hist_len_ = 0; bool head_sampling_ = true; ///< set_head_sampling int device_ = -1; ///< the device `init` ran on: run/commit switch to it (layer split) + unsigned long long* rr_stats_ = nullptr; ///< STRATA_ROUTE_RESIDENT's counters on device_ (#1578); null: none std::atomic released_{false}; ///< #267: release_gpu_waits ran (maybe on the watchdog thread): no more windows bool all_resident_ = false; ///< 100% of experts in [lb_, le_) resident in VRAM: zero-doorbell graph /// #871: the zero-doorbell graph plans from the device residency table alone, so it is only right while every diff --git a/src/core/mtp.cpp b/src/core/mtp.cpp index e73ce24a..7d46389d 100644 --- a/src/core/mtp.cpp +++ b/src/core/mtp.cpp @@ -900,6 +900,11 @@ bool MtpDrafter::record_rest(int step_row, cudaStream_t cs, std::string& err) { else router_top10(logits_ + t * g.n_expert, 1, (int) g.n_expert, (int) K, ids_ + t * K, w_ + t * K, cs); } } + if (rr_res_ != nullptr && rr_margin_ > 0.0f && g.n_expert == 512 && K == 10) { + try { + native_route_resident(logits_, ids_, w_, rr_res_, T, rr_margin_, rr_lo_, rr_hi_, nullptr, cs); + } catch (const std::exception& e) { err = std::string("mtp route-resident: ") + e.what(); return false; } + } moe_group_resident(ids_, (int) (T * K), (int) K, experts_, (int64_t) strata::kernels::cpu::BLOB, grp_ptr_, grp_start_, grp_counts_, hit_dst_, hit_slot_, cs); quantize_q8_0_scaled(mixed_, hit_xq_, hit_xs_, (int64_t) T * N, cs); diff --git a/src/core/verify.cpp b/src/core/verify.cpp index 71c0c7d0..bc84c361 100644 --- a/src/core/verify.cpp +++ b/src/core/verify.cpp @@ -45,6 +45,7 @@ #include #include #include +#include #include #include #include @@ -70,32 +71,60 @@ RouteResidentCfg& route_resident_cfg(); struct RouteResidentCfg { float margin = 0.0f; int lo = 6, hi = 9; - unsigned long long* d_stats = nullptr; - unsigned long long* stats() { - if (d_stats == nullptr && margin > 0.0f) { - cudaMalloc((void**) &d_stats, 8 * sizeof(unsigned long long)); - cudaMemset(d_stats, 0, 8 * sizeof(unsigned long long)); + // #1578: one counter block per GPU. A layer split inits a verifier per stage; a block allocated on whichever device + // was current at the first init is unreachable from the other stage's kernels without P2P (illegal memory access). + // The Verifier asks for its device's block in init (outside graph capture) and keeps the pointer: a launch never + // picks the block by the host thread's current device. nullptr (the allocation failed): the kernel runs without counters. + std::mutex mu; + std::map blocks; + unsigned long long* stats_on(int dev) { + if (margin <= 0.0f || dev < 0) return nullptr; + std::lock_guard lk(mu); + const auto it = blocks.find(dev); + if (it != blocks.end()) return it->second; + unsigned long long* p = nullptr; + { + const OnDevice on(dev); + if (cudaMalloc((void**) &p, 8 * sizeof(unsigned long long)) != cudaSuccess || + cudaMemset(p, 0, 8 * sizeof(unsigned long long)) != cudaSuccess) { + (void) cudaGetLastError(); + if (p != nullptr) cudaFree(p); + p = nullptr; + std::fprintf(stderr, "route-resident: the counters could not be allocated on GPU %d; it runs without them\n", dev); + } + } + if (blocks.empty()) { std::atexit([] { - unsigned long long h[8] = {}; RouteResidentCfg& c = route_resident_cfg(); - cudaDeviceSynchronize(); - cudaMemcpy(h, c.d_stats, sizeof(h), cudaMemcpyDeviceToHost); - std::fprintf(stderr, "route-resident: margin=%g ranks=%d-%d windows T>8 (prompt reads): tail_nonres=%llu swaps=%llu (%.1f%%) nonres_entries before=%llu after=%llu\n", - c.margin, c.lo, c.hi, h[0], h[1], h[0] ? 100.0 * h[1] / h[0] : 0.0, h[2], h[3]); - std::fprintf(stderr, "route-resident: margin=%g ranks=%d-%d windows T<=8 (decode): tail_nonres=%llu swaps=%llu (%.1f%%) nonres_entries before=%llu after=%llu\n", - c.margin, c.lo, c.hi, h[4], h[5], h[4] ? 100.0 * h[5] / h[4] : 0.0, h[6], h[7]); + for (const auto& kv : c.blocks) { + if (kv.second == nullptr) continue; + unsigned long long h[8] = {}; + if (cudaSetDevice(kv.first) != cudaSuccess || cudaDeviceSynchronize() != cudaSuccess || + cudaMemcpy(h, kv.second, sizeof(h), cudaMemcpyDeviceToHost) != cudaSuccess) { + (void) cudaGetLastError(); + continue; + } + char who[32] = ""; + if (c.blocks.size() > 1) std::snprintf(who, sizeof who, " (GPU %d)", kv.first); + std::fprintf(stderr, "route-resident%s: margin=%g ranks=%d-%d windows T>8 (prompt reads): tail_nonres=%llu swaps=%llu (%.1f%%) nonres_entries before=%llu after=%llu\n", + who, c.margin, c.lo, c.hi, h[0], h[1], h[0] ? 100.0 * h[1] / h[0] : 0.0, h[2], h[3]); + std::fprintf(stderr, "route-resident%s: margin=%g ranks=%d-%d windows T<=8 (decode): tail_nonres=%llu swaps=%llu (%.1f%%) nonres_entries before=%llu after=%llu\n", + who, c.margin, c.lo, c.hi, h[4], h[5], h[4] ? 100.0 * h[5] / h[4] : 0.0, h[6], h[7]); + } }); } - return d_stats; + blocks[dev] = p; + return p; } }; RouteResidentCfg& route_resident_cfg() { - static RouteResidentCfg c = [] { - RouteResidentCfg r; - if (const char* v = std::getenv("STRATA_ROUTE_RESIDENT")) r.margin = (float) std::atof(v); - if (const char* v = std::getenv("STRATA_ROUTE_RESIDENT_RANKS")) std::sscanf(v, "%d-%d", &r.lo, &r.hi); - return r; + static RouteResidentCfg c; + static const bool parsed = [] { + if (const char* v = std::getenv("STRATA_ROUTE_RESIDENT")) c.margin = (float) std::atof(v); + if (const char* v = std::getenv("STRATA_ROUTE_RESIDENT_RANKS")) std::sscanf(v, "%d-%d", &c.lo, &c.hi); + return true; }(); + (void) parsed; return c; } inline bool g_lfuse_gate() { static const bool on = [] { const char* v = std::getenv("STRATA_LFUSE_GATE"); return v == nullptr || v[0] != '0'; }(); return on; } @@ -412,7 +441,6 @@ Verifier::~Verifier() { bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState& ss, const VerifyHits& hits, const NativeHead* head, int max_t, std::string& err) { g_diag_verifier.store(this); - (void) route_resident_cfg().stats(); // STRATA_ROUTE_RESIDENT: the counters are allocated outside graph capture diag_verify_fn().store(&diag_active_verifier); for (auto& slot : g_live) { Verifier* none = nullptr; @@ -420,6 +448,7 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState& } release_gpu_fn().store(&release_live_verifiers); cudaGetDevice(&device_); // a layer split's stage on another GPU: its streams, graphs and buffers live there + rr_stats_ = route_resident_cfg().stats_on(device_); // STRATA_ROUTE_RESIDENT: this GPU's counters, outside graph capture strata::kernels::fused_gr_check(); // once per card: which bitwise-equal hyper-connection read runs there wt_ = &wt; g_ = &g; @@ -1322,7 +1351,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { try { native_route_resident(logits_ + tb * NE, ids_ + tb * K, w_ + tb * K, hits_.d_res + l * g.n_expert, n, route_resident_cfg().margin, route_resident_cfg().lo, route_resident_cfg().hi, - route_resident_cfg().stats() + (n <= 8 ? 4 : 0), cs); + rr_stats_ != nullptr ? rr_stats_ + (n <= 8 ? 4 : 0) : nullptr, cs); } catch (const std::exception& e) { err = "verify route-resident: " + std::string(e.what()); return false; } } if (ar_on()) {