From f6601bf83f8cea31a2d77dac23fe491cd974c1a4 Mon Sep 17 00:00:00 2001 From: sergiywith Date: Mon, 5 Oct 2026 00:07:35 +0300 Subject: [PATCH 01/13] #606: the fused SwiGLU q8_1 quantizers keep the block's scale and sum finite too 0.1.39 clamped two q8_1 activation quantizers (#606: an fp16 sum or scale past 65504 rounds to inf, the dot products then read inf * 0 = NaN, and a NaN in the residual ends as one token repeated). Two more store the block unclamped: - native_swiglu_quantize_q8_1_kernel (native_mmvq.cu), the shared expert's fused SwiGLU + q8_1, on by default (STRATA_FUSED_SWIGLU_Q81) in decode and the multi-token pass; - native_gu_fused_kernel (iq_kernels.cu), the routed experts' fused SwiGLU + q8_1 (gfx906 builds, STRATA_EXP_MODE=8). Both now go through q8_1_finite / q8_1_quant / q8_1_ds as their siblings do: every finite block is stored bit for bit as before. iq_multi_parity's #606 check covers the shared expert's one (gate = 32, up = x / 32: its activations are x exactly). rwkeyes found the first one (#606). --- src/kernels/cuda/iq_kernels.cu | 6 +++--- src/kernels/cuda/native_mmvq.cu | 6 +++--- src/kernels/iq_multi_parity.cpp | 25 ++++++++++++++++++------- 3 files changed, 24 insertions(+), 13 deletions(-) diff --git a/src/kernels/cuda/iq_kernels.cu b/src/kernels/cuda/iq_kernels.cu index 5c552fa7..4b662ab0 100644 --- a/src/kernels/cuda/iq_kernels.cu +++ b/src/kernels/cuda/iq_kernels.cu @@ -2413,11 +2413,11 @@ __global__ void __launch_bounds__(256) native_gu_fused_kernel(const unsigned lon amax = fmaxf(amax, __shfl_xor_sync(0xffffffffu, amax, o)); sum += __shfl_xor_sync(0xffffffffu, sum, o); } - const float d = amax / 127.0f; - const int8_t q = amax == 0.0f ? 0 : roundf(xi / d); + const float d = q8_1_finite(amax / 127.0f); // #606, as q8_1_store: finite blocks bit for bit + const int8_t q = q8_1_quant(xi, d, amax); block_q8_1* y = hq + (size_t) (c0 + warp) * hb + blockIdx.x; y->qs[lane] = q; - if (lane == 0) y->ds = make_half2(d, sum); + if (lane == 0) y->ds = q8_1_ds(d, sum); } } } diff --git a/src/kernels/cuda/native_mmvq.cu b/src/kernels/cuda/native_mmvq.cu index e0d11bf1..5878fa71 100644 --- a/src/kernels/cuda/native_mmvq.cu +++ b/src/kernels/cuda/native_mmvq.cu @@ -163,10 +163,10 @@ __global__ void native_swiglu_quantize_q8_1_kernel(const float* __restrict__ gat const float xi = __fmul_rn(__fdividef(gi, __fadd_rn(1.0f, __expf(-gi))), up[i]); const float amax = warp_max(fabsf(xi)); const float sum = warp_sum(xi); - const float d = amax / 127.0f; - const int8_t q = amax == 0.0f ? 0 : roundf(xi / d); + const float d = q8_1_finite(amax / 127.0f); // #606, as native_quantize_q8_1_kernel: finite blocks bit for bit + const int8_t q = q8_1_quant(xi, d, amax); y[i / Q8K].qs[i % Q8K] = q; - if (i % Q8K == 0) y[i / Q8K].ds = make_half2(d, sum); + if (i % Q8K == 0) y[i / Q8K].ds = q8_1_ds(d, sum); } // Exact pinned vec_dot_q5_K_q8_1_impl_vmmq expression and integer dot order. diff --git a/src/kernels/iq_multi_parity.cpp b/src/kernels/iq_multi_parity.cpp index ace6facf..27b06d1e 100644 --- a/src/kernels/iq_multi_parity.cpp +++ b/src/kernels/iq_multi_parity.cpp @@ -326,9 +326,10 @@ void bench(cudaStream_t s, std::mt19937& rng) { } } -// #606: both q8_1 activation quantizers (quantize_q8_1_rows and native_quantize_q8_1) against a host transcription -// of the 0.1.38 formula: every finite block bit for bit; a block whose sum (or scale) overflowed fp16 is now stored -// finite (the largest half, its sign), with its values in the int8 range. +// #606: the q8_1 activation quantizers (quantize_q8_1_rows, native_quantize_q8_1 and the shared expert's fused +// native_swiglu_quantize_q8_1) against a host transcription of the 0.1.38 formula: every finite block bit for bit; a +// block whose sum (or scale) overflowed fp16 is now stored finite (the largest half, its sign), with its values in the +// int8 range. The fused one gets gate = 32 and up = x / 32: silu(32) is 32 in float, so its activations are x exactly. void check_q8_1_finite(cudaStream_t s, std::mt19937& rng) { const int n = 2560, rows = 3, nb = n / 32; std::vector x = random_x((size_t) rows * n, rng); @@ -338,10 +339,17 @@ void check_q8_1_finite(cudaStream_t s, std::mt19937& rng) { x[(size_t) n + 40] = 2.0e7f; // amax / 127 overflowed too float* dx = dalloc(x.size()); ck(cudaMemcpy(dx, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "x"); + std::vector gate(x.size(), 32.0f), up(x.size()); + for (size_t i = 0; i < x.size(); ++i) up[i] = x[i] / 32.0f; + float* dg = dalloc(x.size()); + float* du = dalloc(x.size()); + ck(cudaMemcpy(dg, gate.data(), x.size() * 4, cudaMemcpyHostToDevice), "gate"); + ck(cudaMemcpy(du, up.data(), x.size() * 4, cudaMemcpyHostToDevice), "up"); uint8_t* dq = dalloc((size_t) rows * nb * 36); - for (int path = 0; path < 2; ++path) { + for (int path = 0; path < 3; ++path) { if (path == 0) k::quantize_q8_1_rows(dx, rows, n, dq, s); - else k::native_quantize_q8_1(dx, dq, n, rows, s); + else if (path == 1) k::native_quantize_q8_1(dx, dq, n, rows, s); + else k::native_swiglu_quantize_q8_1(dg, du, dq, n, rows, s); ck(cudaStreamSynchronize(s), "quantize"); std::vector got((size_t) rows * nb * 36); ck(cudaMemcpy(got.data(), dq, got.size(), cudaMemcpyDeviceToHost), "q"); @@ -370,7 +378,7 @@ void check_q8_1_finite(cudaStream_t s, std::mt19937& rng) { want[4 + i] = (uint8_t) (int8_t) (amax == 0.0f ? 0.0f : std::round(v[i] / d)); // native_mmvq.cu is built with --use_fast_math (its divisions are approximate): there the sum must be // the same bits, the scale within one fp16 step and each value within one step - bool near = path == 1 && gs == os && std::abs((int) gd - (int) od) <= 1; + bool near = path >= 1 && gs == os && std::abs((int) gd - (int) od) <= 1; for (int i = 0; near && i < 32; ++i) near = std::abs((int) (int8_t) g[4 + i] - (int) (int8_t) want[4 + i]) <= 1; if (std::memcmp(want, g, 36) == 0 || near) ++same; else { ++bad; std::printf(" q8_1 path %d block %d: changed although it was finite\n", path, b); } @@ -384,10 +392,13 @@ void check_q8_1_finite(cudaStream_t s, std::mt19937& rng) { } } std::printf("q8_1 finite (%s): %d finite blocks as before, %d overflowed blocks clamped finite%s\n", - path == 0 ? "quantize_q8_1_rows" : "native_quantize_q8_1", same, clamped, bad ? " FAIL" : ""); + path == 0 ? "quantize_q8_1_rows" : path == 1 ? "native_quantize_q8_1" : "native_swiglu_quantize_q8_1", + same, clamped, bad ? " FAIL" : ""); g_fail += bad + (clamped != 3); } cudaFree(dx); + cudaFree(dg); + cudaFree(du); cudaFree(dq); } From 1d78e57bd0bb71bd4622e33db050a93e18fd0fa4 Mon Sep 17 00:00:00 2001 From: Strata Contributor Date: Sun, 4 Oct 2026 18:25:57 +0800 Subject: [PATCH 02/13] cache: preserve checkpoints when split allocation fails --- CMakeLists.txt | 3 ++ include/strata/core/conversation_cache.hpp | 34 ++++++++++++--- src/core/conversation_split_failure_test.cpp | 46 ++++++++++++++++++++ src/program/generate.cpp | 7 ++- 4 files changed, 83 insertions(+), 7 deletions(-) create mode 100644 src/core/conversation_split_failure_test.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 0121bb00..4b34aeba 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -98,6 +98,9 @@ if(STRATA_BUILD_CONVERSATION_TESTS) add_executable(conversation_cache_test src/core/conversation_cache_test.cpp) target_include_directories(conversation_cache_test PRIVATE include) add_test(NAME conversation_cache_test COMMAND conversation_cache_test) + add_executable(conversation_split_failure_test src/core/conversation_split_failure_test.cpp) + target_include_directories(conversation_split_failure_test PRIVATE include) + add_test(NAME conversation_split_failure_test COMMAND conversation_split_failure_test) add_executable(conversation_memory_test src/core/conversation_memory_test.cpp src/core/conversation_memory.cpp) target_include_directories(conversation_memory_test PRIVATE include) add_test(NAME conversation_memory_test COMMAND conversation_memory_test) diff --git a/include/strata/core/conversation_cache.hpp b/include/strata/core/conversation_cache.hpp index b105deb6..c28ae01f 100644 --- a/include/strata/core/conversation_cache.hpp +++ b/include/strata/core/conversation_cache.hpp @@ -79,17 +79,39 @@ inline ConversationCheckpointSplit conversation_checkpoints_split(std::vector +#include +#include +static long fail_after=-1; +void* operator new(std::size_t n) { + if(fail_after==0) throw std::bad_alloc(); + if(fail_after>0) --fail_after; + if(void* p=std::malloc(n?n:1)) return p; + throw std::bad_alloc(); +} +void operator delete(void* p) noexcept { std::free(p); } +void operator delete(void* p,std::size_t) noexcept { std::free(p); } +using strata::core::ConversationCheckpoint; +bool equal(const ConversationCheckpoint& a,const ConversationCheckpoint& b) { + if(a.ids!=b.ids || a.imgs!=b.imgs || a.gdn!=b.gdn || a.ple!=b.ple || a.tails!=b.tails || a.dead!=b.dead || a.block_pos!=b.block_pos || a.used!=b.used || a.stage_parts.size()!=b.stage_parts.size()) return false; + for(size_t i=0;i checks(3); + for(size_t i=0;i0?0:3; + } catch(const std::bad_alloc&) { + fail_after=-1;++faults; + if(checks.size()!=backup.size()) return 4; + for(size_t i=0;i 0 ? nullptr : &mtp.kv_state(); auto draft_of = [&](size_t k) -> const strata::core::QsaState* { return k + 1 == n_st ? &mtp.kv_state() : nullptr; }; strata::core::ConversationCheckpointSplit cs; - if (n_st > 0) cs = strata::core::conversation_checkpoints_split(std::move(checks), n_st); + try { + if (n_st > 0) cs = strata::core::conversation_checkpoints_split(std::move(checks), n_st); + } catch (const std::bad_alloc&) { + std::fprintf(stderr, "strata serve: conversation cache: checkpoint split allocation failed; skip parking\n"); + return true; // split preserves every checkpoint on allocation failure + } struct MergeBack { strata::core::ConversationCheckpointSplit& cs; std::vector& checks; bool on; ~MergeBack() { if (on && !strata::core::conversation_checkpoints_merge(std::move(cs), checks)) checks.clear(); } From 1ec615f58551601922945ddc6f78099be9f5272e Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 5 Oct 2026 10:01:02 +0200 Subject: [PATCH 03/13] serve: park_current's try covers the checkpoint split too (#752): a host OOM skips parking Co-authored-by: zengyishou --- src/program/generate.cpp | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/src/program/generate.cpp b/src/program/generate.cpp index f6c47fb5..c676719a 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -5185,7 +5185,7 @@ int main(int argc, char** argv) { (size_t) o.conversation_cache_slots); // Save only on a switch/rewind, not on each continuing request. No graph // addresses change: all parked images live in ordinary host vectors. - auto park_current = [&](size_t held) -> bool { + auto park_current_body = [&](size_t held) -> bool { if (!conversations.enabled() || !live_ok || live.empty()) return true; // #342: before make_room evicts oldest-first, the copies of this conversation a turn back go (they hold // nothing the outgoing chain does not, apart from the tail this conversation rewrote) @@ -5201,12 +5201,7 @@ int main(int argc, char** argv) { const strata::core::QsaState* draft0 = n_st > 0 ? nullptr : &mtp.kv_state(); auto draft_of = [&](size_t k) -> const strata::core::QsaState* { return k + 1 == n_st ? &mtp.kv_state() : nullptr; }; strata::core::ConversationCheckpointSplit cs; - try { - if (n_st > 0) cs = strata::core::conversation_checkpoints_split(std::move(checks), n_st); - } catch (const std::bad_alloc&) { - std::fprintf(stderr, "strata serve: conversation cache: checkpoint split allocation failed; skip parking\n"); - return true; // split preserves every checkpoint on allocation failure - } + if (n_st > 0) cs = strata::core::conversation_checkpoints_split(std::move(checks), n_st); // #752: two-phase; a bad_alloc leaves `checks` whole struct MergeBack { strata::core::ConversationCheckpointSplit& cs; std::vector& checks; bool on; ~MergeBack() { if (on && !strata::core::conversation_checkpoints_merge(std::move(cs), checks)) checks.clear(); } @@ -5310,6 +5305,15 @@ int main(int argc, char** argv) { } return true; }; + // #752: the whole park (the checkpoint split included) is under one try, so a host OOM skips parking instead of + // ending the server + auto park_current = [&](size_t held) -> bool { + try { return park_current_body(held); } + catch (const std::bad_alloc&) { + std::fprintf(stderr, "strata serve: conversation cache: allocation failed; skip parking\n"); + return true; + } + }; int64_t pp_total = 0, pp_from = 0, pp_next_check = 0; // #471: the position the prompt pass has read up to (a chunk's or a window's end): what a request cancelled // mid-read reports as read, instead of the whole prompt From 5c4105c0736471f9ddd5d406e29abd2d74d3a9bd Mon Sep 17 00:00:00 2001 From: Francesco Albano <119073350+Hardin22@users.noreply.github.com> Date: Mon, 5 Oct 2026 00:19:22 +0200 Subject: [PATCH 04/13] Layer split: --vram-reserve-later-mib, a separate reserve for the later cards --vram-reserve-mib is every card's reserve, but the card that drives the monitors needs more headroom than one that drives none: one value has to fit the display card, and the other cards then keep that headroom for nothing. --vram-reserve-later-mib N is the reserve of every card after the first (default: --vram-reserve-mib's value), in the split search and in each later card's cache sizing. RTX 4060 Ti (no display, layers 0-19) + RTX 5080 (display, 20-47), Swift 1.5 IQ3_XXS at 160K: --vram-reserve-mib 1000 gives the 4060 Ti's cache 4551 slots; --vram-reserve-mib 300 --vram-reserve-later-mib 1800 gives it 4867, and the 5080 keeps 1.3 GB free with everything loaded. --- docs/MULTI_GPU.md | 4 ++++ src/program/generate.cpp | 9 ++++++++- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/docs/MULTI_GPU.md b/docs/MULTI_GPU.md index 1270125b..abf2f5a0 100644 --- a/docs/MULTI_GPU.md +++ b/docs/MULTI_GPU.md @@ -102,6 +102,10 @@ it goes). A card holding more experts can change which experts run on the GPU, so the output can differ slightly from a run without it. +**A separate VRAM reserve for the later cards:** `--vram-reserve-later-mib N` (default: `--vram-reserve-mib`'s value). +The card that drives the monitors needs more headroom than one that drives none; with the display on the last card, +`--vram-reserve-mib 300 --vram-reserve-later-mib 1800` gives the first card's cache that VRAM. + **auto** tries every placement (all of them for two or three cards; proportional to the free VRAM beyond that) and keeps the one whose caches would hold the most of the expert profile, hottest pairs weighted most; ties go to the placement that leaves the fullest card the most room. The startup log prints the choice: diff --git a/src/program/generate.cpp b/src/program/generate.cpp index c676719a..ce5d1b0b 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -427,6 +427,9 @@ struct Options { /// `VRAM ` command can give part of it back to other programs and take it again. Off: one cudaMalloc. bool vram_elastic = false; int64_t vram_segment_mib = 512; + /// `--vram-reserve-later-mib N`: the reserve on a layer split's later cards (default: the same as the first). + /// A card that drives no display needs less than the one the monitors are on. + int vram_reserve_later_mib = -1; /// Plan v0.3 P5: batched prompt processing in chunks of this many tokens (0 = the token path). int64_t prefill_chunk = 0; /// `--prefill auto`: the largest chunk (up to 8192) whose buffers the expert cache can lend. Every expert a chunk @@ -1376,6 +1379,8 @@ int main(int argc, char** argv) { 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")); o.vram_reserve_given = true; } + else if (a == "--vram-reserve-later-mib") + o.vram_reserve_later_mib = std::atoi(next("--vram-reserve-later-mib")); else if (a == "--prefill") { const std::string v = next("--prefill"); o.prefill_auto = v == "auto" || v.rfind("auto:", 0) == 0; @@ -2743,7 +2748,9 @@ int main(int argc, char** argv) { std::fprintf(stderr, "strata generate: layer split: CUDA%d free memory: %s\n", dev < 0 ? 0 : dev, cudaGetErrorString(e)); const int64_t pf = search && split_own_auto && !place_with_reserve ? 0 : split_pf_mib; - const int64_t reserve = ((int64_t) o.vram_reserve_mib + pf + (later ? kWindowMib : 0) + + const int64_t base_reserve = + later && o.vram_reserve_later_mib >= 0 ? o.vram_reserve_later_mib : o.vram_reserve_mib; + const int64_t reserve = (base_reserve + pf + (later ? kWindowMib : 0) + (drafter ? kDrafterMib : 0)) << 20; return std::max((int64_t) fb - reserve, 0); }; From fe9c10cad701091081cd876a0faea787a708f5d6 Mon Sep 17 00:00:00 2001 From: Francesco Albano <119073350+Hardin22@users.noreply.github.com> Date: Mon, 5 Oct 2026 00:20:01 +0200 Subject: [PATCH 05/13] Resident RAM mode with a layer split --resident-experts (the low-RAM mode's resident variant) ran as plain --mmap-experts as soon as a layer split was set. It now keeps its RAM copy on a split: - the experts every stage's cache holds are left out of the RAM copy, not only CUDA0's; - when the rest does not fit whole (#467), the copy keeps the hottest by the whole expert profile. Each stage only keeps its own layers' share of the profile, and ranked by CUDA0's share alone the copy held layers 0..K-1's experts and read every later layer's from the files (4.0 GiB in RAM instead of 21.2 on the PC below); - an adaptive swap copies the evicted expert back into RAM from the cache of the card that owns its layer, on that card's stream. host_res holds slot numbers of whichever cache owns the layer: reading a later stage's slot out of CUDA0's cache put another expert's bytes in RAM, and after the first swaps the answers turned to garbage. (Latent until now: the guard kept the mode off a split.) - the decode profile prints every stage's GPU profile, not only CUDA0's. Remote expert caches (--expert-cache-remote) are still refused with it. Swift 1.5 IQ3_XXS at 160K, q4_0 KV, RTX 4060 Ti (layers 0-19) + RTX 5080 (20-47), i9-14900KF, 32 GB of RAM, Windows 11, four greedy prompts, decode tok/s (first round / fourth): - 5080 alone, --resident-experts: 25 / 29 - split, --mmap-experts (what --resident-experts became): 32 / 64 - split, --resident-experts (22 GiB of experts locked in RAM): 71 / 69 With --pcie-frac 0 --adapt-every 0 the split's greedy output is the same as --mmap-experts' (4/4 prompts). With adaptive swaps on, 33 varied requests at temperature 0.6 (thinking on and off, five languages, code, each checked for degenerate output) exchanged 81,783 experts with the two caches and gave no degenerate answer. --- docs/MULTI_GPU.md | 17 +++++++ src/program/generate.cpp | 104 ++++++++++++++++++++++++++++----------- 2 files changed, 92 insertions(+), 29 deletions(-) diff --git a/docs/MULTI_GPU.md b/docs/MULTI_GPU.md index abf2f5a0..9c00ab3f 100644 --- a/docs/MULTI_GPU.md +++ b/docs/MULTI_GPU.md @@ -102,6 +102,23 @@ it goes). A card holding more experts can change which experts run on the GPU, so the output can differ slightly from a run without it. +**The resident RAM mode works on a split** (`--resident-experts`, the low-RAM mode). The RAM copy of the experts +leaves out the ones every card's cache holds, not only the first card's, and when the rest does not fit whole it keeps +the hottest by the expert profile over all the layers. An adaptive swap copies the evicted expert back into RAM from +the card that owns its layer. Before, `--resident-experts` with a split ran as `--mmap-experts`. Swift 1.5 IQ3_XXS at +160K (q4_0 KV, `--prefill 4096`, `--spec 4` with the stock draft layer), RTX 4060 Ti (layers 0-19) + RTX 5080 (20-47), +i9-14900KF, 32 GB of RAM, Windows 11, four greedy prompts at a time, decode tok/s: + +| | first four prompts | after three more rounds | +|---|---|---| +| 5080 alone, `--resident-experts` | 25 | 29 | +| split, `--mmap-experts` (what `--resident-experts` became on a split) | 32 | 64 | +| split, `--resident-experts` (22 GiB of experts locked in RAM) | 71 | 69 | + +The split with `--mmap-experts` catches up once the OS file cache holds the experts, on a PC with nothing else +running; the resident copy is there from the first request and stays locked when other programs need the RAM. With +`--pcie-frac 0 --adapt-every 0` the split's greedy output is the same with either mode. + **A separate VRAM reserve for the later cards:** `--vram-reserve-later-mib N` (default: `--vram-reserve-mib`'s value). The card that drives the monitors needs more headroom than one that drives none; with the display on the last card, `--vram-reserve-mib 300 --vram-reserve-later-mib 1800` gives the first card's cache that VRAM. diff --git a/src/program/generate.cpp b/src/program/generate.cpp index ce5d1b0b..9fff5e5a 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -209,13 +209,23 @@ using Clock = std::chrono::steady_clock; // reads the file. Swaps that need no exchange (`out` in the lend region is held in RAM already; or `in` is not) go // on as before; ones beyond the buffers' room wait for a later round. Runs on the adaptive tier's thread while the // GPU commits and drafts: the copies back are on its stream, and waited for before the refills are queued. -template -bool resident_stage_swaps(strata::core::FileExpertSource& src, strata::core::ExpertCache& cache, - const std::vector& host_res, int64_t n_expert, std::vector& swaps, - cudaStream_t stream) { +// +// With a layer split, `host_res` holds slot numbers of WHICHEVER cache owns the layer, so the copy back must read the +// owning card's cache on that card's stream: `locate(layer)` names them (cache, stream, device; -1 = CUDA0). Reading +// a later stage's slot number out of CUDA0's cache copied another expert's bytes into RAM - the resident mode with a +// split then computed some experts from the wrong weights after the first adaptive swaps (garbage output). +struct SwapHome { + strata::core::ExpertCache* cache; + cudaStream_t stream; + int dev; +}; +template +bool resident_stage_swaps(strata::core::FileExpertSource& src, const std::vector& host_res, + int64_t n_expert, std::vector& swaps, Locate locate) { if (!src.complement_ready() || swaps.empty()) return true; struct Staged { int32_t layer, in, out; int64_t q; }; std::vector staged; + std::vector used; std::vector kept; kept.reserve(swaps.size()); for (const Swap& s : swaps) { @@ -224,17 +234,35 @@ bool resident_stage_swaps(strata::core::FileExpertSource& src, strata::core::Exp if (q >= src.exchange_capacity()) continue; const int32_t slot = host_res[(size_t) s.layer * (size_t) n_expert + (size_t) s.out]; if (slot < 0) continue; - if (cudaMemcpyAsync(src.exchange_buffer(q), cache.device_slot(slot), + const SwapHome home = locate(s.layer); + const strata::core::OnDevice on(home.dev); + if (const cudaError_t e = cudaMemcpyAsync(src.exchange_buffer(q), home.cache->device_slot(slot), (size_t) strata::kernels::cpu::expert_layout().blob_bytes(s.layer), cudaMemcpyDeviceToHost, - stream) != cudaSuccess) + home.stream); e != cudaSuccess) { + std::fprintf(stderr, "strata: copy back of layer %d slot %d (device %d) failed: %s\n", (int) s.layer, + (int) slot, home.dev, cudaGetErrorString(e)); return false; + } + bool seen = false; + for (const SwapHome& u : used) seen = seen || u.stream == home.stream; + if (!seen) used.push_back(home); staged.push_back({s.layer, s.in, s.out, q}); kept.push_back(s); } if (!staged.empty()) { - if (cudaStreamSynchronize(stream) != cudaSuccess) return false; + for (const SwapHome& u : used) { + const strata::core::OnDevice on(u.dev); + if (const cudaError_t e = cudaStreamSynchronize(u.stream); e != cudaSuccess) { + std::fprintf(stderr, "strata: copy back sync (device %d) failed: %s\n", u.dev, cudaGetErrorString(e)); + return false; + } + } for (const Staged& x : staged) - if (!src.stage_exchange(x.layer, x.in, x.out, x.q)) return false; + if (!src.stage_exchange(x.layer, x.in, x.out, x.q)) { + std::fprintf(stderr, "strata: stage_exchange refused layer %d in %d out %d\n", (int) x.layer, + (int) x.in, (int) x.out); + return false; + } } swaps.swap(kept); return true; @@ -1612,19 +1640,10 @@ int main(int argc, char** argv) { } const bool remote_caches = o.expert_cache_remote[0] > 0 || o.expert_cache_remote[1] > 0 || o.expert_cache_remote[2] > 0; - if (o.resident_cpu_experts && !o.layer_split.empty() && !remote_caches && o.resident_soft && - !o.resident_cpu_explicit && o.resident_budget == 0) { - // #364 #384: setup's --resident-experts with a layer split (--gpus at start, or a config edited by hand) runs - // as the plain mmap mode - the placement those users measured 1.3-1.6x faster than one GPU - instead of - // refusing. Exactly --mmap-experts: nothing else reads these flags (the headroom only sizes the copy). - std::fprintf(stderr, "strata generate: WARNING: the resident RAM mode (--resident-experts) does not support a " - "layer split yet: the experts the GPUs do not hold are read through the OS file cache " - "(--mmap-experts), and RAM may fill up during long prompts\n"); - o.resident_cpu_experts = o.resident_pin = o.resident_soft = false; - o.resident_headroom = 8ull << 30; - } - if (o.resident_cpu_experts && (!o.layer_split.empty() || remote_caches)) { - std::fprintf(stderr, "strata generate: --resident-cpu-experts does not support layer splits or remote expert caches\n"); + // A layer split keeps the resident RAM mode: every stage's GPU cache is left out of the RAM copy, and an adaptive + // swap copies an evicted expert back from the card that owns its layer (resident_stage_swaps). + if (o.resident_cpu_experts && remote_caches) { + std::fprintf(stderr, "strata generate: --resident-cpu-experts does not support remote expert caches\n"); return 2; } // the helper-GPU expert caches (--expert-cache-remote, docs/SECOND_GPU.md): CUDA1..3 on one GPU; with a layer @@ -2857,7 +2876,12 @@ int main(int argc, char** argv) { while (st < (int) split_at.size() && l >= split_at[(size_t) st]) ++st; return st; }; + // the whole ranking, hottest first, before each stage takes its own layers' share: the resident RAM copy ranks + // the experts no GPU holds over ALL the layers (with CUDA0's share alone, a copy that did not fit kept only layers + // 0..K-1's experts and read every later layer's from the files) + std::vector> profile_all; if (multi_gpu) { + profile_all = profile; std::vector> mine; for (const auto& pr : profile) { const int st = stage_of(pr.first); @@ -4551,16 +4575,24 @@ int main(int argc, char** argv) { const int64_t k = plan_lend(chunk); if (k > 0) lend_from = xcache.slots() - k; } - bool resident_ok = src.pin_cache_complement(xcache, err, o.resident_pin, {}, lend_from, o.resident_headroom, - o.resident_budget, &profile); + // a layer split: the experts every later stage's cache holds are left out of the RAM copy, as CUDA0's are + // (with them the copy keeps no lend region: pin_cache_complement turns the loan off) + std::vector> stage_pairs; + for (auto& st : stages) + for (int64_t l = st->lb; l < st->le; ++l) + for (int64_t e = 0; e < g.n_expert; ++e) + if (st->cache.slot_of(l, e) >= 0) stage_pairs.emplace_back((int32_t) l, (int32_t) e); + const std::vector>& rank_all = profile_all.empty() ? profile : profile_all; + bool resident_ok = src.pin_cache_complement(xcache, err, o.resident_pin, stage_pairs, lend_from, + o.resident_headroom, o.resident_budget, &rank_all); std::string whole_err; if (!resident_ok && o.resident_soft) { // #467: the whole complement does not fit - keep what does, the hottest by the profile, through the #403 // budget path (sized by the RAM alone) instead of none: the misses outside it read the same file bytes // the mmap fallback reads, so the answers are unchanged. Nothing pinned: the old fallback below. whole_err = err; - resident_ok = src.pin_cache_complement(xcache, err, o.resident_pin, {}, -1, o.resident_headroom, - strata::core::FileExpertSource::kResidentWhatFits, &profile); + resident_ok = src.pin_cache_complement(xcache, err, o.resident_pin, stage_pairs, -1, o.resident_headroom, + strata::core::FileExpertSource::kResidentWhatFits, &rank_all); if (resident_ok) std::fprintf(stderr, "strata generate: WARNING: the whole resident RAM mode does not fit (%s); %.2f " "GiB of the experts the GPU does not hold, the hottest by the expert profile, are " @@ -5531,7 +5563,16 @@ int main(int argc, char** argv) { } std::sort(swaps.begin(), swaps.end(), [](const Swap& a, const Swap& b) { return a.gain > b.gain; }); if ((int) swaps.size() > o.adapt_swaps) swaps.resize((size_t) o.adapt_swaps); - if (!resident_stage_swaps(src, xcache, host_res, g.n_expert, swaps, adapt_stream)) return false; + // the copies back read the cache of the card that owns each layer (see resident_stage_swaps) + auto home_of = [&](int64_t layer) -> SwapHome { + const int stn = multi_gpu ? stage_of(layer) : 0; + if (stn > 0) { + GpuStage* gs = stages[(size_t) stn - 1].get(); + return {&gs->cache, gs->adapt_stream, gs->dev}; + } + return {&xcache, adapt_stream, -1}; + }; + if (!resident_stage_swaps(src, host_res, g.n_expert, swaps, home_of)) return false; if (pin_blobs_on()) { // lock the batch's source pages (a file-backed arena on AMD; see pin_blobs) std::vector> spans; for (const Swap& s : swaps) @@ -7224,8 +7265,11 @@ int main(int argc, char** argv) { (d1.actq - ds0.actq) / w, (d1.jobs - ds0.jobs) / w, (d1.run - ds0.run) / w, (d1.host - ds0.host) / w, dt_commit / w, dt_draft / w, (d1.misses - ds0.misses) / (w * L), (d1.entries - ds0.entries) / (w * L), (d1.hits - ds0.hits) / (w * L), (d1.pcie - ds0.pcie) / (w * L)); - const std::string pr = ver.profile_report(); - if (!pr.empty()) std::fprintf(stderr, "strata decode GPU stages (ms/window):%s\n", pr.c_str()); + for (int st = 0; st < n_stages; ++st) { // every stage's GPU profile, not only the first card's + const std::string pr = stage_ver(st).profile_report(); + if (!pr.empty()) + std::fprintf(stderr, "strata decode GPU stages, stage %d (ms/window):%s\n", st, pr.c_str()); + } } if (!cancelled) { // a prompt stopped halfway leaves the session somewhere between two chunks: nothing to continue from @@ -7949,7 +7993,9 @@ int main(int argc, char** argv) { } std::sort(swaps.begin(), swaps.end(), [](const Swap& a, const Swap& b) { return a.gain > b.gain; }); if ((int) swaps.size() > o.adapt_swaps) swaps.resize((size_t) o.adapt_swaps); - if (!resident_stage_swaps(src, xcache, host_res, g.n_expert, swaps, adapt_stream)) { + // this (non-serve) path refills CUDA0's cache only, so its copies back read CUDA0's cache too + if (!resident_stage_swaps(src, host_res, g.n_expert, swaps, + [&](int64_t) -> SwapHome { return {&xcache, adapt_stream, -1}; })) { std::fprintf(stderr, "strata generate: an adaptive refill failed (copying evicted experts back)\n"); return false; } From 43c8cfa9e25e9b7feac8e0e73f8494dcb97dd973 Mon Sep 17 00:00:00 2001 From: Francesco Albano <119073350+Hardin22@users.noreply.github.com> Date: Mon, 5 Oct 2026 00:20:37 +0200 Subject: [PATCH 06/13] setup: the low-RAM mode's resident variant on several GPUs (#642) With an engine that keeps --resident-experts on a layer split, setup no longer steers a low-RAM PC with two cards to one of them: - at install, the low-RAM mode on several GPUs takes the resident variant by the same rule as on one card (what no card holds fits the RAM with LOW_RAM_HEADROOM_GB beside it), without the one-card question; - at a start, a resident config on several GPUs keeps --resident-experts (split_mmap leaves it alone); - a resident config started on a PC with two cards is offered both, "y" by default, as any other config. It is gated on MIN_ENGINE >= RESIDENT_SPLIT_ENGINE (0.1.40 here, a guess at the release that would carry the engine change), so until then setup behaves as before and the golden configs are unchanged. Two tests run the new paths with MIN_ENGINE patched; tools/test_setup_*.py pass (260 tests). --- docs/MULTI_GPU.md | 4 +++- setup.py | 48 ++++++++++++++++++++++++++++------------ tools/test_setup_risk.py | 30 +++++++++++++++++++++++++ 3 files changed, 67 insertions(+), 15 deletions(-) diff --git a/docs/MULTI_GPU.md b/docs/MULTI_GPU.md index 9c00ab3f..5c128232 100644 --- a/docs/MULTI_GPU.md +++ b/docs/MULTI_GPU.md @@ -105,7 +105,9 @@ without it. **The resident RAM mode works on a split** (`--resident-experts`, the low-RAM mode). The RAM copy of the experts leaves out the ones every card's cache holds, not only the first card's, and when the rest does not fit whole it keeps the hottest by the expert profile over all the layers. An adaptive swap copies the evicted expert back into RAM from -the card that owns its layer. Before, `--resident-experts` with a split ran as `--mmap-experts`. Swift 1.5 IQ3_XXS at +the card that owns its layer. Before, `--resident-experts` with a split ran as `--mmap-experts`, and setup recommended +one card in the low-RAM mode; with an engine that has it (`RESIDENT_SPLIT_ENGINE` in setup.py), setup keeps the cards +together and the experts no card holds in RAM. Swift 1.5 IQ3_XXS at 160K (q4_0 KV, `--prefill 4096`, `--spec 4` with the stock draft layer), RTX 4060 Ti (layers 0-19) + RTX 5080 (20-47), i9-14900KF, 32 GB of RAM, Windows 11, four greedy prompts at a time, decode tok/s: diff --git a/setup.py b/setup.py index 80d1fba5..1368f940 100644 --- a/setup.py +++ b/setup.py @@ -802,9 +802,10 @@ def split_mmap(cfg: dict) -> bool: """#364 #384: the low-RAM mode's resident variant (--resident-experts) has no layer split yet. A config with it that runs on several GPUs reads the experts the GPUs do not hold through the OS file cache instead (--mmap-experts: the placement those reports measured 1.3-1.6x faster than one GPU), said plainly - the engine - used to refuse the pair. True when the config changed.""" + used to refuse the pair. #642: the engines from RESIDENT_SPLIT_ENGINE run it on a split, so it is kept. True + when the config changed.""" a = cfg.get("args", []) - if "--resident-experts" not in a: + if "--resident-experts" not in a or resident_split(): return False a[a.index("--resident-experts")] = "--mmap-experts" warn("the low-RAM mode's resident variant (--resident-experts) has no layer split yet: on several GPUs the experts " @@ -897,8 +898,9 @@ def offer_together(cfg_path: Path, cfg: dict, yes: bool) -> dict: return cfg pair = can[:2] cfg["gpus_asked"] = True - # #364 #384: the resident low-RAM variant stays on one card unless the user says otherwise (its RAM use is steady) - resident = "--resident-experts" in cfg.get("args", []) + # #364 #384: the resident low-RAM variant stays on one card unless the user says otherwise (its RAM use is steady); + # #642: the engines from RESIDENT_SPLIT_ENGINE keep it on both cards, so they are offered as for any config + resident = "--resident-experts" in cfg.get("args", []) and not resident_split() say() say(" This PC has " + " and ".join(gpu_name(g) for g in pair) + ": Strata can share the model across both.") say(" Together they hold about twice the model's experts and read prompts about 20% faster (docs/MULTI_GPU.md).") @@ -2342,6 +2344,14 @@ DATA_ITEMS = ("models", "packs", "mtp") LOW_RAM_HEADROOM_GB = 10 # RAM beside the experts: the OS, the engine's other buffers, the server RESIDENT_ENGINE = (0, 1, 30) # the first engine with --resident-experts (the low-RAM mode's resident variant) +RESIDENT_SPLIT_ENGINE = (0, 1, 40) # #642: the first engine that runs it on a layer split + + +def resident_split() -> bool: + """#642: the engine setup requires runs the low-RAM mode's resident variant on a layer split - each card's cache + holds the most-used experts of its own layers, and the RAM copy leaves out what any card holds. Before it, a + resident config on several GPUs read those experts through the OS file cache (#364 #384).""" + return MIN_ENGINE >= RESIDENT_SPLIT_ENGINE def low_ram_needed(model, ram) -> bool: @@ -3927,9 +3937,11 @@ def main() -> int: "the low-RAM mode") low_ram = budget is None and (a.low_ram in ("on", "resident", "mmap") or (a.low_ram == "auto" and low_ram_needed(model, ram))) - if low_ram and multi and not low_ram_together(a, model, ram, gpu, chosen): + # #642: the engines from RESIDENT_SPLIT_ENGINE run the low-RAM mode on the chosen cards as on one (decided below) + if low_ram and multi and not resident_split() and not low_ram_together(a, model, ram, gpu, chosen): multi, sel, chosen = [], [gpu["index"]], [gpu] - # (the low-RAM mode's variant is decided once the context is known, below; on several GPUs it is the mapped one) + # (the low-RAM mode's variant is decided once the context is known, below; on several GPUs it is the mapped one + # before RESIDENT_SPLIT_ENGINE, #642) if not low_ram and budget is None and ram < MODELS[model]["ram_gb"] - 4: confirm_paging(model, ram, a.low_ram, a.yes, bool(a.model)) ok(f"size: {model}") @@ -4019,16 +4031,24 @@ def main() -> int: share = low_ram_gpu_share(model, vram, ctx, kv) rest = arena - low_ram_gpu_gb(model, vram, ctx, kv) resident = a.low_ram == "resident" or (a.low_ram != "mmap" and low_ram_resident(model, ram, vram, ctx, kv)) - if multi: # #364 #384: every chosen card's share (the image encoder on the main one), the mapped variant + if multi: # every chosen card's share (the image encoder on the main one); #364 #384: the mapped variant held = min(arena, low_ram_gpu_gb(model, vram, ctx, kv) + sum(low_ram_gpu_gb(model, x["vram_gb"], ctx, kv) for x in chosen[1:])) - share, resident = held / arena, False - ok(f"low-RAM mode on {len(chosen)} GPUs: {model}'s experts ({arena:.0f} GB) are read from the model folder " - f"through the OS file cache instead of a copy in RAM ({ram:.0f} GB); the GPUs hold ~{100 * share:.0f}% " - "of them") - if share < 0.6: - warn("most of the experts are read from the SSD while it answers: expect it to be much slower than " - "with enough RAM (a faster SSD and a smaller size help)") + share, rest = held / arena, arena - held + # #642: the resident variant on a split, by the same rule as on one card - what no card holds fits the RAM + resident = resident_split() and (a.low_ram == "resident" or + (a.low_ram != "mmap" and ram >= rest + LOW_RAM_HEADROOM_GB)) + if resident: + ok(f"low-RAM mode on {len(chosen)} GPUs: they hold ~{100 * share:.0f}% of {model}'s experts " + f"({arena:.0f} GB) and the other ~{rest:.0f} GB stay in RAM ({ram:.0f} GB), read once from a copy " + "in the model folder") + else: + ok(f"low-RAM mode on {len(chosen)} GPUs: {model}'s experts ({arena:.0f} GB) are read from the model " + f"folder through the OS file cache instead of a copy in RAM ({ram:.0f} GB); the GPUs hold " + f"~{100 * share:.0f}% of them") + if share < 0.6: + warn("most of the experts are read from the SSD while it answers: expect it to be much slower " + "than with enough RAM (a faster SSD and a smaller size help)") elif resident: ok(f"low-RAM mode: the GPU holds ~{100 * share:.0f}% of {model}'s experts ({arena:.0f} GB) and the other " f"~{rest:.0f} GB stay in RAM ({ram:.0f} GB), read once from a copy in the model folder") diff --git a/tools/test_setup_risk.py b/tools/test_setup_risk.py index 366421d9..3e569a98 100644 --- a/tools/test_setup_risk.py +++ b/tools/test_setup_risk.py @@ -244,6 +244,24 @@ class LowRamGpus(unittest.TestCase): self.assertEqual(cfg["gpu"], 0) self.assertFalse(any("Low-RAM mode" in q for q in asked), asked) + def test_low_ram_on_gpus_with_a_resident_split_engine(self): + """#642: an engine that runs the resident variant on a layer split keeps the cards together, resident.""" + ram, found = PROFILES["32GB-2x24GB"] + with mock.patch.object(setup, "MIN_ENGINE", setup.RESIDENT_SPLIT_ENGINE): + code, out, cfg, asked = install(ram, found, ["--family", "qwen", "--model", "Q2_0", "--no-start"], + answers="") + self.assertEqual(code, 0, out) + self.assertEqual(cfg["gpu"], [0, 1]) + self.assertIn("--resident-experts", cfg["args"]) + self.assertFalse(any("Low-RAM mode" in q for q in asked), asked) + self.assertIn("stay in RAM", out) + code, out, cfg, _ = install(ram, found, ["--family", "qwen", "--model", "Q2_0", "--no-start", + "--gpus", "0,1", "--low-ram", "resident"]) + self.assertEqual(code, 0, out) + self.assertEqual(cfg["gpu"], [0, 1]) + self.assertIn("--resident-experts", cfg["args"]) + self.assertNotIn("no layer split yet", out) + class StartOnSeveralGpus(unittest.TestCase): """A resident low-RAM config started on several GPUs reads the experts through the file cache (#364 #384).""" @@ -280,6 +298,18 @@ class StartOnSeveralGpus(unittest.TestCase): code, out, asked, cfg = self.offer(["--mmap-experts"], None) # other configs: as before self.assertEqual(cfg["gpu"], [0, 1]) + def test_resident_split_engine_keeps_a_resident_config(self): + """#642: from RESIDENT_SPLIT_ENGINE a resident config is offered both cards as any other, and stays resident.""" + with mock.patch.object(setup, "MIN_ENGINE", setup.RESIDENT_SPLIT_ENGINE): + cfg = {"args": ["--pack", "p", "--resident-experts", "--kv", "int8"]} + self.assertFalse(setup.split_mmap(cfg)) + self.assertEqual(cfg["args"], ["--pack", "p", "--resident-experts", "--kv", "int8"]) + code, out, asked, cfg = self.offer(["--resident-experts"], None) # --yes: the recommendation + self.assertIsNone(code, out) + self.assertEqual(cfg["gpu"], [0, 1]) + self.assertEqual(cfg["args"], ["--resident-experts", "--remote-expert-opt"]) + self.assertNotIn("OS file cache", out) + def test_start_with_gpus(self): found = PROFILES["32GB-2x24GB"][1] with tempfile.TemporaryDirectory() as d: From b4405a0eaaab0e95ff42044f7c0d31c8c62f2267 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 5 Oct 2026 10:01:30 +0200 Subject: [PATCH 07/13] serve: a split's stage-0 GPU profile line keeps its text (#848); later stages say which stage --- src/program/generate.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 9fff5e5a..e7cdc14d 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -7267,8 +7267,9 @@ int main(int argc, char** argv) { (d1.entries - ds0.entries) / (w * L), (d1.hits - ds0.hits) / (w * L), (d1.pcie - ds0.pcie) / (w * L)); for (int st = 0; st < n_stages; ++st) { // every stage's GPU profile, not only the first card's const std::string pr = stage_ver(st).profile_report(); - if (!pr.empty()) - std::fprintf(stderr, "strata decode GPU stages, stage %d (ms/window):%s\n", st, pr.c_str()); + if (pr.empty()) continue; + if (st == 0) std::fprintf(stderr, "strata decode GPU stages (ms/window):%s\n", pr.c_str()); // text as before + else std::fprintf(stderr, "strata decode GPU stages, stage %d (ms/window):%s\n", st, pr.c_str()); } } if (!cancelled) { From 53ab5f7161d3b398b119f8343d1dd2ad6fdea820 Mon Sep 17 00:00:00 2001 From: sergiywith Date: Sat, 3 Oct 2026 00:49:33 +0300 Subject: [PATCH 08/13] generate: residency-table uploads wait for their own copy before the non-blocking streams read the table Every upload of the expert residency table (host_res -> d_res, and each stage's) was a plain cudaMemcpy: a pageable copy on the legacy stream, which may return before its DMA has landed, while the kernels that read the table run on streams created cudaStreamNonBlocking, which do not wait for the legacy stream. A kernel enqueued right after could read a table half old, half new: an expert computed by both the GPU and the CPU, or by neither. The ~100 KB copy lands in microseconds, so this rarely fires, but nothing ordered it. The uploads now go through res_put(), which waits for the copy on the current device's legacy stream only. Same values, same output. --- src/program/generate.cpp | 25 ++++++++++++++++--------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/src/program/generate.cpp b/src/program/generate.cpp index e7cdc14d..68762168 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -4292,6 +4292,13 @@ int main(int argc, char** argv) { // Plan v0.3 P4: with a PROFILE-filled cache the residency is static, so the hit decision moves onto the // device and the token graph keeps it. (A cache filled on demand still needs the per-layer host path.) std::vector host_res; + // The residency table is read by kernels on non-blocking streams, which do not wait for the legacy stream a plain + // cudaMemcpy runs on, and a pageable copy can return before its DMA has landed: each upload waits for its own copy + // (the current device's legacy stream - nothing else). + auto res_put = [&host_res](int32_t* dst) -> cudaError_t { + const cudaError_t e = cudaMemcpy(dst, host_res.data(), host_res.size() * sizeof(int32_t), cudaMemcpyHostToDevice); + return e != cudaSuccess ? e : cudaStreamSynchronize(cudaStreamLegacy); + }; int32_t* d_res = nullptr; int32_t* d_hit_count = nullptr; strata::core::TokenHits thits; @@ -4308,7 +4315,7 @@ int main(int argc, char** argv) { } if (cudaMalloc((void**) &d_res, host_res.size() * sizeof(int32_t)) != cudaSuccess || cudaMalloc((void**) &d_hit_count, sizeof(int32_t)) != cudaSuccess || - cudaMemcpy(d_res, host_res.data(), host_res.size() * sizeof(int32_t), cudaMemcpyHostToDevice) != cudaSuccess) { + res_put(d_res) != cudaSuccess) { std::fprintf(stderr, "strata generate: the device residency table could not be staged\n"); return 1; } @@ -4342,7 +4349,7 @@ int main(int argc, char** argv) { for (auto& st : stages) { // layer split across GPUs: the same table on every device const strata::core::OnDevice on(st->dev); if (cudaMalloc((void**) &st->d_res, host_res.size() * sizeof(int32_t)) != cudaSuccess || - cudaMemcpy(st->d_res, host_res.data(), host_res.size() * sizeof(int32_t), cudaMemcpyHostToDevice) != + res_put(st->d_res) != cudaSuccess) { std::fprintf(stderr, "strata generate: layer split: CUDA%d residency table failed\n", st->dev); return 1; @@ -5076,10 +5083,10 @@ int main(int argc, char** argv) { } if (evicted > 0) { if (d_res != nullptr) - cudaMemcpy(d_res, host_res.data(), host_res.size() * sizeof(int32_t), cudaMemcpyHostToDevice); + res_put(d_res); for (auto& st : stages) { const strata::core::OnDevice on(st->dev); - cudaMemcpy(st->d_res, host_res.data(), host_res.size() * sizeof(int32_t), cudaMemcpyHostToDevice); + res_put(st->d_res); } } } @@ -5509,10 +5516,10 @@ int main(int argc, char** argv) { // a layer split's later stages keep a copy of the residency table on their devices, and swap on their own auto res_upload = [&]() { if (d_res != nullptr) - cudaMemcpy(d_res, host_res.data(), host_res.size() * sizeof(int32_t), cudaMemcpyHostToDevice); + res_put(d_res); for (auto& st : stages) { const strata::core::OnDevice on(st->dev); - cudaMemcpy(st->d_res, host_res.data(), host_res.size() * sizeof(int32_t), cudaMemcpyHostToDevice); + res_put(st->d_res); } }; auto apply_pending = [&](bool wait) { @@ -7565,7 +7572,7 @@ int main(int argc, char** argv) { lent.emplace_back((int32_t) i, host_res[i]); host_res[i] = strata::core::kNotResident; } - cudaMemcpy(d_res, host_res.data(), host_res.size() * sizeof(int32_t), cudaMemcpyHostToDevice); + res_put(d_res); borrow = xcache.device_slot(first); borrow_bytes = xcache.slot_offsets() ? (uint64_t) (xcache.bytes() - (int64_t) xcache.slot_offsets()[first]) : (uint64_t) k * (uint64_t) blob; @@ -7616,7 +7623,7 @@ int main(int argc, char** argv) { std::fprintf(stderr, "strata generate: refilling the lent slots failed: %s\n", err.c_str()); return 1; } - cudaMemcpy(d_res, host_res.data(), host_res.size() * sizeof(int32_t), cudaMemcpyHostToDevice); + res_put(d_res); std::fprintf(stderr, "strata generate: %zu lent slots refilled in %.1f ms\n", lent.size(), std::chrono::duration(Clock::now() - tr).count()); } @@ -7951,7 +7958,7 @@ int main(int argc, char** argv) { } pending.clear(); if (d_res != nullptr) - cudaMemcpy(d_res, host_res.data(), host_res.size() * sizeof(int32_t), cudaMemcpyHostToDevice); + res_put(d_res); }; // Plan v0.3 P6: the VRAM tier follows the conversation. Candidates are missing experts routed at least // twice (decayed); each is paired with its layer's least-routed resident expert and swapped when it was From 82bc5de6325310e90164a143ad6b060d8ee901ef Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 5 Oct 2026 10:01:53 +0200 Subject: [PATCH 09/13] generate: res_put syncs stream 0 (HIP has no cudaStreamLegacy) (#550) --- src/program/generate.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 68762168..c30713cf 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -4294,10 +4294,10 @@ int main(int argc, char** argv) { std::vector host_res; // The residency table is read by kernels on non-blocking streams, which do not wait for the legacy stream a plain // cudaMemcpy runs on, and a pageable copy can return before its DMA has landed: each upload waits for its own copy - // (the current device's legacy stream - nothing else). + // (the current device's legacy stream, stream 0 - nothing else; HIP has no cudaStreamLegacy name, #550). auto res_put = [&host_res](int32_t* dst) -> cudaError_t { const cudaError_t e = cudaMemcpy(dst, host_res.data(), host_res.size() * sizeof(int32_t), cudaMemcpyHostToDevice); - return e != cudaSuccess ? e : cudaStreamSynchronize(cudaStreamLegacy); + return e != cudaSuccess ? e : cudaStreamSynchronize(nullptr); }; int32_t* d_res = nullptr; int32_t* d_hit_count = nullptr; From 6f7f680529d63aa128313c5d0615ad6d59754470 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 5 Oct 2026 10:11:08 +0200 Subject: [PATCH 10/13] verify: the all-resident graph runs only while every expert is in VRAM; a -1 raises a plan error flag (#871) A prompt loan, a VRAM shrink or an adaptive swap marks experts -1 in the residency table. The zero-doorbell graph planned from the device table and returned silently on a -1, so the window ran a stale plan (!!!! at 100% residency). refresh_ar() checks the host table before each window and runs the doorbell graph (its own captured variant) while any expert is out; resident_plan also writes a mapped error flag the host checks after the window. --- include/strata/core/verify.hpp | 13 +++++ include/strata/kernels/verify_kernels.hpp | 4 +- src/core/verify.cpp | 60 ++++++++++++++++++----- src/kernels/cuda/verify_kernels.cu | 10 ++-- 4 files changed, 70 insertions(+), 17 deletions(-) diff --git a/include/strata/core/verify.hpp b/include/strata/core/verify.hpp index e68f7b3a..51c5972f 100644 --- a/include/strata/core/verify.hpp +++ b/include/strata/core/verify.hpp @@ -223,6 +223,9 @@ private: bool last_batch_ = false; ///< the last run was a batch window (set_plan_slot: one group) std::map exec_bm_, commit_bm_; ///< key: batch_key(rows, S, hand-off base) int last_rows_[8] = {}; ///< the slots of the last batch window's rows + uint64_t bkey(const int* rows, int S, int hbase) const { // #871: the doorbell variant has its own graphs + return batch_key(rows, S, hbase) | (ar_off_ ? (1ull << 63) : 0ull); + } static uint64_t batch_key(const int* rows, int S, int hbase) { uint64_t k = (uint64_t) hbase << 40 | (uint64_t) S << 32; for (int t = 0; t < S; ++t) k |= (uint64_t) (rows[t] & 15) << (4 * t); @@ -256,6 +259,15 @@ private: int device_ = -1; ///< the device `init` ran on: run/commit switch to it (layer split) 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 + /// expert of the stage is in VRAM. A prompt loan, a VRAM shrink or an adaptive swap marks some -1 for a while: + /// every window then runs the doorbell graph (exec_nr_ / the batch key's top bit), the same as a stage that never + /// was all-resident. refresh_ar() looks at the host table before each window. + bool ar_off_ = false; + bool ar_on() const { return all_resident_ && !ar_off_; } + void refresh_ar(); + uint32_t* h_plan_err_ = nullptr; uint32_t* m_plan_err_ = nullptr; // set by resident_plan on a -1 (all-resident graph) + const int32_t* h_res_ = nullptr; ///< the host residency table (VerifyHits::h_res) bool device_plan_ = false; ///< E-6: resident-only layers planned on the device (STRATA_VERIFY_DEVICE_PLAN) uint32_t* skip_ = nullptr; ///< E-6: per group, the ring whose plan the device built (0: the host's) unsigned long long* slot_off_d_ = nullptr; ///< E-6: the slot offsets on the device @@ -298,6 +310,7 @@ private: cudaStream_t sh_cs_ = nullptr; cudaEvent_t ev_fork_ = nullptr, ev_join_ = nullptr; cudaGraphExec_t exec_[9] = {}; + cudaGraphExec_t exec_nr_[9] = {}; // #871: the doorbell variant of a stage that is all-resident otherwise cudaGraphExec_t commit_exec_ = nullptr; // mapped staging (host pointer, device alias) diff --git a/include/strata/kernels/verify_kernels.hpp b/include/strata/kernels/verify_kernels.hpp index 50d951a6..2efb7cf7 100644 --- a/include/strata/kernels/verify_kernels.hpp +++ b/include/strata/kernels/verify_kernels.hpp @@ -45,9 +45,11 @@ void gpu_stamp(unsigned long long* buf, int i, void* stream); /// One group's plan, built on the device when every routed expert of its n*k entries is resident: the host pool's /// layout (counts | start | dst | tok | pad | ptr | ptr2 | start2, `capx` entries) and order (distinct experts in /// routing order, their entries ascending), no PCIe groups. *skip = ring when it did, else 0. +/// #871: without `skip` (the all-resident graph) an entry whose expert is not in VRAM cannot be planned: the plan is +/// left empty and *plan_err (mapped host memory) is set to 1, so the host sees it instead of running a stale plan. void resident_plan(const int32_t* ids, int n_entries, int k, const int32_t* res_layer, int n_expert, const uint8_t* cache_base, const unsigned long long* slot_off, long long blob, int32_t* plan, - long long capx, uint32_t* skip, uint32_t ring, void* stream); + long long capx, uint32_t* skip, uint32_t ring, void* stream, uint32_t* plan_err = nullptr); /// wait_flag_ge that also returns when *skip == value (device memory). void wait_flag_ge_or(const uint32_t* flag, uint32_t value, const uint32_t* skip, void* stream); /// copy_i32_from_mapped unless *skip == value. diff --git a/src/core/verify.cpp b/src/core/verify.cpp index dd5362ba..113c1a4a 100644 --- a/src/core/verify.cpp +++ b/src/core/verify.cpp @@ -278,6 +278,8 @@ Verifier::~Verifier() { if (sh_cs_) cudaStreamSynchronize(sh_cs_); for (auto& e : exec_) if (e) cudaGraphExecDestroy(e); + for (auto& e : exec_nr_) + if (e) cudaGraphExecDestroy(e); if (commit_exec_) cudaGraphExecDestroy(commit_exec_); for (auto& kv : exec_bm_) if (kv.second) cudaGraphExecDestroy(kv.second); @@ -293,7 +295,7 @@ Verifier::~Verifier() { if (ev_join_) cudaEventDestroy(ev_join_); if (arena_) cudaFree(arena_); void* hosts[] = {h_tok_, h_step_, h_pos_, h_commit_, h_ple_, h_out_, h_x_, h_ids_, h_w_, h_seq_, h_flag_, h_ymiss_, - h_flagA_, h_plan_, h_flagB_}; + h_flagA_, h_plan_, h_flagB_, h_plan_err_}; for (void* h : hosts) if (h) cudaFreeHost(h); } @@ -376,6 +378,7 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState& mapped(64, (void**) &h_flag_, (void**) &m_flag_) && mapped(64, (void**) &h_flagA_, (void**) &m_flagA_) && mapped(64, (void**) &h_flagB_, (void**) &m_flagB_) && + mapped(64, (void**) &h_plan_err_, (void**) &m_plan_err_) && mapped(T * K * N * 4, (void**) &h_ymiss_, (void**) &m_ymiss_); if (!ok) { err = "verify: mapped staging allocation failed"; return false; } // the GPU plan: counts(4) | start(cap+1) | dst(cap) | tok(cap) | pad | ptr(cap u64) | ptr2(cap u64) | start2(cap+1) @@ -492,6 +495,9 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState& // When true, every layer plans on device and writes directly into parts_ without any CPU doorbells, // wait_flag_ge spins, PCIe empty launches, or moe_hit_add copies. all_resident_ = false; + ar_off_ = false; + h_res_ = hits.h_res; + if (h_plan_err_ != nullptr) *(volatile uint32_t*) h_plan_err_ = 0; if (hits.h_res != nullptr && hits.d_res != nullptr && hits.cache_base != nullptr) { const char* v_ar = std::getenv("STRATA_VERIFY_ALL_RESIDENT"); if (v_ar == nullptr || std::atoi(v_ar) != 0) { @@ -635,7 +641,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { bool pending = l > 0 && !cvec().covers(l - 1); if (l == 1 && ple_on) { if (grp == 0) { - if (all_resident_) wait_flag_ge(m_flag_, 1, cs); + if (ar_on()) wait_flag_ge(m_flag_, 1, cs); copy_from_mapped(ple_, m_ple_, (int64_t) T * N, cs); } float* normalized = (float*) ((uint8_t*) ss.ple.scratch + ple_block_scratch_bytes()); @@ -934,10 +940,10 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { mb.logits = logits_ + t * NE; mb.ids = ids_ + t * K; mb.weights = w_ + t * K; if (!moe_route(wt, g, l, K, mb, mixed_ + t * N, cs, err, nullptr)) return false; } - if (all_resident_) { + if (ar_on()) { resident_plan(ids_ + tb * K, n * (int) K, (int) K, hits_.d_res + l * g.n_expert, (int) g.n_expert, hits_.cache_base, slot_off_d_, (long long) hits_.blob, - plan_ + (size_t) grp * (size_t) (plan_i32_ + 16), (long long) max_t_ * K, nullptr, 0, cs); + plan_ + (size_t) grp * (size_t) (plan_i32_ + 16), (long long) max_t_ * K, nullptr, 0, cs, m_plan_err_); } else { if (device_plan_) // E-6: every routed expert resident: this group's plan without the host resident_plan(ids_ + tb * K, n * (int) K, (int) K, hits_.d_res + l * g.n_expert, (int) g.n_expert, @@ -1030,7 +1036,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { hit_xs_ + (size_t) tb * (N / 32), hit_scratch_, dst_buf, cs); } }; - if (all_resident_) { + if (ar_on()) { stamp(l, 19, grp); grouped(p_ptr, p_start, p_counts, 0, parts_out); stamp(l, 20, grp); @@ -1199,8 +1205,28 @@ std::string Verifier::profile_report() { return out; } +// #871: is the zero-doorbell graph right for the next window? Only while every expert of [lb_, le_) is in VRAM now +// (the host table is the one the device copy was uploaded from; a loan, a VRAM shrink or a swap in flight has +// marked some -1). Not: the doorbell graph, which asks the pool for what the device does not hold. +void Verifier::refresh_ar() { + if (!all_resident_ || h_res_ == nullptr || g_ == nullptr) return; + const int64_t ne = g_->n_expert; + const int32_t* r = h_res_ + lb_ * ne; + const int64_t n = (le_ < 0 ? g_->n_layers : le_) * ne - lb_ * ne; + int32_t lo = 0; + for (int64_t i = 0; i < n; ++i) lo = std::min(lo, r[i]); + const bool off = lo < 0; + if (off != ar_off_) { + ar_off_ = off; + std::fprintf(stderr, "strata verify: layers [%lld, %lld) %s\n", (long long) lb_, (long long) (le_ < 0 ? g_->n_layers : le_), + off ? "have experts out of VRAM (a prompt loan, a shrink or a swap): the doorbell graph runs the windows" + : "are 100% VRAM resident again: the zero-doorbell graph"); + } +} + bool Verifier::capture(int T, std::string& err) { - if (exec_[T] != nullptr) return true; + cudaGraphExec_t& exec_t = ar_off_ ? exec_nr_[T] : exec_[T]; + if (exec_t != nullptr) return true; if (cudaStreamBeginCapture(cs_, cudaStreamCaptureModeThreadLocal) != cudaSuccess) { err = "verify: begin capture failed"; return false; @@ -1249,13 +1275,13 @@ bool Verifier::capture(int T, std::string& err) { std::fprintf(stderr, "\n"); } #endif - const cudaError_t ie = cudaGraphInstantiate(&exec_[T], graph, 0); + const cudaError_t ie = cudaGraphInstantiate(&exec_t, graph, 0); cudaGraphDestroy(graph); if (ie != cudaSuccess) { err = std::string("verify: instantiate: ") + cudaGetErrorString(ie); return false; } - const cudaError_t ue = cudaGraphUpload(exec_[T], cs_); + const cudaError_t ue = cudaGraphUpload(exec_t, cs_); const cudaError_t us = cudaStreamSynchronize(cs_); std::fprintf(stderr, "strata verify: captured the %d-token window (upload %s, sync %s)\n", T, cudaGetErrorString(ue), cudaGetErrorString(us)); @@ -1397,6 +1423,7 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, const ModelGeometry& g = *g_; SessionState& ss = *ss_; if (pos0 + T > ss.qsa_states[ss.qsa_primary()].max_cells) { err = "verify: the window runs past the context"; return false; } + refresh_ar(); if (!capture(T, err) || !capture_commit(err)) return false; VDBG("captured; staging\n"); const Clock::time_point t0 = Clock::now(); @@ -1418,7 +1445,8 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, trace_ev("WINDOW", -1, -1, pos0 * 16 + T); ms_host += ms_since(t0); VDBG("staged; launching\n"); - const cudaError_t le = cudaGraphLaunch(exec_[T], cs_); + if (ar_on() && h_plan_err_ != nullptr) *(volatile uint32_t*) h_plan_err_ = 0; + const cudaError_t le = cudaGraphLaunch(ar_off_ ? exec_nr_[T] : exec_[T], cs_); trace_ev("LAUNCHED", -1, -1, (int64_t) le); if (le != cudaSuccess) { err = std::string("verify: launch: ") + cudaGetErrorString(le); return false; } (void) cudaStreamQuery(cs_); @@ -1429,7 +1457,7 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, const int gtb[2] = {0, (T + 1) / 2}, gte[2] = {G == 2 ? (T + 1) / 2 : T, T}; const int64_t steps = (le_ - lb_) * G; const bool test_stall = g_test_stall > 0 && windows + 1 == g_test_stall; // #267 test hook (off: false) - if (all_resident_ && !test_stall) { + if (ar_on() && !test_stall) { if (do_ple) { const Clock::time_point tp = Clock::now(); if (!ss.ple.table->gather_batch(ple_rows, (size_t) T, h_ple_, err)) return false; @@ -1532,6 +1560,11 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, const cudaError_t se = cudaStreamSynchronize(cs_); trace_ev("SYNCED", -1, -1, (int64_t) se); if (se != cudaSuccess) { err = std::string("verify: ") + cudaGetErrorString(se); return false; } + if (ar_on() && h_plan_err_ != nullptr && *(volatile uint32_t*) h_plan_err_ != 0) { // #871: refresh_ar saw the table whole + *(volatile uint32_t*) h_plan_err_ = 0; + err = "verify: the all-resident plan met an expert that is not in VRAM (the residency table changed during the window)"; + return false; + } commit_pending_ = false; progress_at("verify window: waiting for the expert copies", (int64_t) T); if (copy_used_) { @@ -1778,7 +1811,7 @@ bool Verifier::init_slots(const std::vector& slots, std::string& } bool Verifier::capture_batch(const int* rows, int S, int hbase, std::string& err) { - cudaGraphExec_t& ex = exec_bm_[batch_key(rows, S, hbase)]; + cudaGraphExec_t& ex = exec_bm_[bkey(rows, S, hbase)]; if (ex != nullptr) return true; if (cudaStreamBeginCapture(cs_, cudaStreamCaptureModeThreadLocal) != cudaSuccess) { err = "verify: begin batch capture failed"; @@ -1904,6 +1937,7 @@ bool Verifier::stage_batch(const int* rows, int S, int hbase, const int32_t* tok err = "verify: slot " + std::to_string(rows[t]) + " runs past its context"; return false; } + refresh_ar(); if (!capture_batch(rows, S, hbase, err) || !capture_commit_batch(rows, S, hbase, err)) return false; const Clock::time_point t0 = Clock::now(); const QsaShapes s = shapes_of(g); @@ -1961,7 +1995,7 @@ bool Verifier::run_slot_rows(const int* rows, int S, const int32_t* tokens, cons const OnDevice on_device(device_); const ModelGeometry& g = *g_; if (!stage_batch(rows, S, 0, tokens, pos, err)) return false; - const cudaError_t le = cudaGraphLaunch(exec_bm_[batch_key(rows, S, 0)], cs_); + const cudaError_t le = cudaGraphLaunch(exec_bm_[bkey(rows, S, 0)], cs_); if (le != cudaSuccess) { err = std::string("verify: batch launch: ") + cudaGetErrorString(le); return false; } (void) cudaStreamQuery(cs_); volatile uint32_t* const seq = h_seq_; @@ -2068,7 +2102,7 @@ bool Verifier::batch_launch(int base, int S, const int32_t* tokens, const int64_ int rows[8] = {}; for (int t = 0; t < S && t < 8; ++t) rows[t] = base + t; if (!stage_batch(rows, S, base, tokens, pos, err)) return false; - cudaError_t le = cudaGraphLaunch(exec_bm_[batch_key(rows, S, base)], cs_); + cudaError_t le = cudaGraphLaunch(exec_bm_[bkey(rows, S, base)], cs_); if (le == cudaSuccess) le = cudaGraphLaunch(commit_bm_[batch_key(rows, S, base)], cs_); // right behind it: every row is kept if (le != cudaSuccess) { err = std::string("verify: batch launch: ") + cudaGetErrorString(le); return false; } (void) cudaStreamQuery(cs_); diff --git a/src/kernels/cuda/verify_kernels.cu b/src/kernels/cuda/verify_kernels.cu index f7c48438..02a8e1f6 100644 --- a/src/kernels/cuda/verify_kernels.cu +++ b/src/kernels/cuda/verify_kernels.cu @@ -507,7 +507,7 @@ static_assert(kVerifyMaxT * 10 <= kResidentPlanMax, "resident_plan: one thread p __global__ void __launch_bounds__(kResidentPlanMax) resident_plan_kernel(const int32_t* __restrict__ ids, int n, int k, const int32_t* __restrict__ res, int n_expert, const uint8_t* cache_base, const unsigned long long* slot_off, long long blob, int32_t* __restrict__ pl, long long capx, uint32_t* skip, - uint32_t ring) { + uint32_t ring, volatile uint32_t* plan_err) { __shared__ int32_t s_ids[kResidentPlanMax]; __shared__ unsigned long long s_ptr[kResidentPlanMax]; __shared__ int32_t s_first[kResidentPlanMax]; @@ -532,6 +532,10 @@ __global__ void __launch_bounds__(kResidentPlanMax) resident_plan_kernel(const i __syncthreads(); if (s_bad) { if (tid == 0 && skip != nullptr) *skip = 0; + if (tid == 0 && skip == nullptr) { // #871: the all-resident graph has no host plan to fall back on + pl[0] = 0; pl[1] = 0; pl[2] = 0; // an empty plan: no expert runs on a stale pointer + if (plan_err != nullptr) { *plan_err = 1; __threadfence_system(); } + } return; } @@ -612,9 +616,9 @@ __global__ void copy_or_zero_kernel(float4* __restrict__ dst, const volatile flo void resident_plan(const int32_t* ids, int n_entries, int k, const int32_t* res_layer, int n_expert, const uint8_t* cache_base, const unsigned long long* slot_off, long long blob, int32_t* plan, - long long capx, uint32_t* skip, uint32_t ring, void* stream) { + long long capx, uint32_t* skip, uint32_t ring, void* stream, uint32_t* plan_err) { resident_plan_kernel<<<1, kResidentPlanMax, 0, (cudaStream_t) stream>>>(ids, n_entries, k, res_layer, n_expert, cache_base, slot_off, - blob, plan, capx, skip, ring); + blob, plan, capx, skip, ring, plan_err); check("resident_plan"); } void wait_flag_ge_or(const uint32_t* flag, uint32_t value, const uint32_t* skip, void* stream) { From cfe09ab5f55f465b26af7c17456c4e3fc670ae56 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 5 Oct 2026 10:11:08 +0200 Subject: [PATCH 11/13] prefill: STRATA_TEST_PAGEABLE=1 forces the pageable fallbacks of Prefill::init (#828 test switch) --- src/prefill/prefill.cpp | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index e76fb6dd..9ef0d25e 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -96,6 +96,12 @@ constexpr int kSplitHelpRing = 48; // layer split help: the helper stage's ring // Step 3: from this chunk size on, every non-resident expert of every layer streams in a fixed order through a // ring_slots()-slot ring (nearly all 512 are routed at such a chunk), so the copy engine keeps working through the // attention halves instead of waiting for each layer's routing. +// #828: STRATA_TEST_PAGEABLE=1 makes every pinned host allocation with a pageable fallback in Prefill::init fail, so the +// fallbacks (what an LXC container's memlock limit forces) run on a PC that can pin - for ASan / MALLOC_CHECK_=3 runs. +inline bool force_pageable() { + static const bool v = [] { const char* e = std::getenv("STRATA_TEST_PAGEABLE"); return e != nullptr && e[0] == '1'; }(); + return v; +} constexpr int RING_MAX = 1024; // the arrays; the ring itself is ring_slots(), at most ring_cap() // The chunk size from which every expert streams: 1024 since 0.1.30 (was 2048). Measured on the 5070, Q2_0 / IQ2_XS, // fixed cache: 1,500-token prompts 621 -> 785 / 612 -> 735 tok/s, 2,000 727 -> 934 / 712 -> 892, 4,000 (its last @@ -285,7 +291,7 @@ struct Stager { dma_done.assign((size_t) kRing, nullptr); pageable.resize(kRing); for (int i = 0; i < kRing; ++i) { - pinned[i] = cudaHostAlloc((void**) &buf[i], blob_bytes, cudaHostAllocDefault) == cudaSuccess; + pinned[i] = !force_pageable() && cudaHostAlloc((void**) &buf[i], blob_bytes, cudaHostAllocDefault) == cudaSuccess; if (!pinned[i]) { cudaGetLastError(); pageable[(size_t) i].resize(blob_bytes); @@ -790,7 +796,8 @@ bool Prefill::init(const core::WeightTable& wt, const core::ModelGeometry& g, co m.grp_host = m.grp_dev = nullptr; m.grp_n = m.grp_tk = 0; void *h = nullptr, *d = nullptr; - if (cudaHostAlloc(&h, need * 4, cudaHostAllocMapped | (core::peer_portable() ? cudaHostAllocPortable : 0)) == cudaSuccess && + if (!force_pageable() && + cudaHostAlloc(&h, need * 4, cudaHostAllocMapped | (core::peer_portable() ? cudaHostAllocPortable : 0)) == cudaSuccess && cudaHostGetDevicePointer(&d, h, 0) == cudaSuccess) { m.grp_host = (int32_t*) h; m.grp_dev = (int32_t*) d; @@ -804,7 +811,7 @@ bool Prefill::init(const core::WeightTable& wt, const core::ModelGeometry& g, co } for (int b = 0; b < 2; ++b) { if (!m.ple_emb_host[b] && - cudaHostAlloc((void**) &m.ple_emb_host[b], (size_t) T * N * 4, cudaHostAllocDefault) != cudaSuccess) { + (force_pageable() || cudaHostAlloc((void**) &m.ple_emb_host[b], (size_t) T * N * 4, cudaHostAllocDefault) != cudaSuccess)) { cudaGetLastError(); m.ple_pageable[b].resize(T * N); // pageable: the upload is staged before it returns m.ple_emb_host[b] = m.ple_pageable[b].data(); From 604056878eda9b159940cca445f6b9e845e39464 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 5 Oct 2026 10:11:08 +0200 Subject: [PATCH 12/13] serve: a Stop during the prompt read goes to the engine at once (#879 abort latency) --- serve/server.py | 5 ++++ serve/test_control_cancel.py | 50 ++++++++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+) create mode 100644 serve/test_control_cancel.py diff --git a/serve/server.py b/serve/server.py index 9e669827..bfc2a4f2 100644 --- a/serve/server.py +++ b/serve/server.py @@ -743,6 +743,11 @@ class StrataEngine: if len(f) >= 3 and f[1].isdigit() and f[2].isdigit(): self.progress = (int(f[1]), int(f[2])) self.prefill_tok_s_mean = float(f[4]) if len(f) >= 5 else None + if not stopped and cancel.is_set(): + # #879: a Stop during the prompt read went out only after the first token (or after 10 s of + # silence, which a stream of PP lines never allows): the engine read the whole prompt first + self._send("STOP") + stopped = True yield None elif line.startswith("DONE"): self._parse_done(line) diff --git a/serve/test_control_cancel.py b/serve/test_control_cancel.py new file mode 100644 index 00000000..2f6b3540 --- /dev/null +++ b/serve/test_control_cancel.py @@ -0,0 +1,50 @@ +"""#879: a Stop that arrives while the engine reads the prompt (PP lines, no tokens yet) is sent at once, not after the +first token.""" +import os +import queue +import sys +import threading +import unittest + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +from serve import server # noqa: E402 + + +class ControlCancelTest(unittest.TestCase): + def _engine(self, lines): + eng = object.__new__(server.StrataEngine) + eng.lines = queue.Queue() + for l in lines: + eng.lines.put(l) + eng.sent = [] + eng._send = eng.sent.append + eng._ctl_mode = "solo" + eng._ctl_result = None + eng.progress = None + eng.prefill_tok_s_mean = None + eng._last_done = None + eng._parse_done = lambda line: None + return eng + + def test_stop_during_prompt_read(self): + cancel = threading.Event() + eng = self._engine(["PP 256 4096 1 100.0", "PP 512 4096 2 100.0", "PP 768 4096 3 100.0", "DONE 0"]) + gen = eng._control(cancel, lambda t: None) + self.assertIsNone(next(gen)) # first PP line, nothing cancelled yet + self.assertEqual(eng.sent, []) + cancel.set() + self.assertIsNone(next(gen)) # the next PP line: STOP goes out now + self.assertEqual(eng.sent, ["STOP"]) + self.assertIsNone(next(gen)) + self.assertEqual(eng.sent, ["STOP"]) # once + + def test_no_stop_without_cancel(self): + eng = self._engine(["PP 256 4096 1 100.0", "DONE 0"]) + for _ in eng._control(threading.Event(), lambda t: None): + pass + self.assertEqual(eng.sent, []) + + +if __name__ == "__main__": + unittest.main() From 258532d6675fb0e99347e729eebc9bce8d44e092 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 5 Oct 2026 10:12:49 +0200 Subject: [PATCH 13/13] test: the checkpoint split's allocation-failure test covers 1-3 stages and an incomplete checkpoint (#752) --- src/core/conversation_split_failure_test.cpp | 60 +++++++++++++------- 1 file changed, 38 insertions(+), 22 deletions(-) diff --git a/src/core/conversation_split_failure_test.cpp b/src/core/conversation_split_failure_test.cpp index a09d177d..c383d837 100644 --- a/src/core/conversation_split_failure_test.cpp +++ b/src/core/conversation_split_failure_test.cpp @@ -18,29 +18,45 @@ bool equal(const ConversationCheckpoint& a,const ConversationCheckpoint& b) { return true; } int main() { - int faults=0; - for(int n=0;n<128;++n) { - std::vector checks(3); - for(size_t i=0;i0?0:3; - } catch(const std::bad_alloc&) { - fail_after=-1;++faults; - if(checks.size()!=backup.size()) return 4; - for(size_t i=0;i checks(4); + for(size_t i=0;i0?0:3; }