From 42bc3dd9ad51eee7473ecf0a5bfa74cd257cc8de Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 2 Oct 2026 09:31:35 +0200 Subject: [PATCH 1/2] engine: the low-RAM resident mode engages on Windows 32 GB PCs (#467) - Windows: the process working set is trimmed before the resident complement's RAM reading, so the experts the GPU cache pre-fill touched through the mapping count as available again (standby list); one line prints the reading before and after. - --resident-experts (soft): when the whole complement does not fit, a second try keeps what fits, by profile rank, through the #403 budget path (RAM room minus the 256 MiB margin) instead of falling back to mmap entirely; a WARNING names it. Same file bytes either way, so the answers are unchanged. - Only the resident mode calls pin_cache_complement: the default and mmap paths are untouched. --- include/strata/core/expert_source.hpp | 4 ++++ src/core/expert_source.cpp | 34 +++++++++++++++++++++++---- src/program/generate.cpp | 22 +++++++++++++++-- 3 files changed, 54 insertions(+), 6 deletions(-) diff --git a/include/strata/core/expert_source.hpp b/include/strata/core/expert_source.hpp index 84339efc..307edd98 100644 --- a/include/strata/core/expert_source.hpp +++ b/include/strata/core/expert_source.hpp @@ -421,6 +421,10 @@ public: /// CS-T, `budget_bytes` > 0 (`--resident-budget-gib`): only as many of those experts as fit `budget_bytes`, taken /// in `rank` order (the expert profile: the hottest after the GPU cache's), are copied; the rest stay on the /// mapped files (the SSD tier). No lend region then (a lent slot's expert is read from the files). + /// #467: `budget_bytes` = `kResidentWhatFits` is that path sized by the RAM alone (available minus the headroom + /// and the #403 margin) - the soft --resident-experts mode's second try when the whole complement does not fit; + /// false when not even one expert fits. On Windows the mapped experts leave the working set before any reading. + static constexpr uint64_t kResidentWhatFits = ~0ull; bool pin_cache_complement( const ExpertCache& cache, std::string& err, bool pin = true, const std::vector>& additional_gpu_pairs = {}, int64_t lend_from_slot = -1, diff --git a/src/core/expert_source.cpp b/src/core/expert_source.cpp index 5197e1e2..087854ed 100644 --- a/src/core/expert_source.cpp +++ b/src/core/expert_source.cpp @@ -1024,6 +1024,22 @@ bool FileExpertSource::pin_cache_complement( uint64_t bytes = 0; if (!detail::make_cache_complement_plan(n_layers_, n_expert_, layer_blob_bytes_, primary_gpu_pairs, additional_gpu_pairs, offsets, bytes, err)) return false; +#if defined(_WIN32) + // #467: the GPU cache's pre-fill touched its experts through the mapping (~19 GiB on a 24 GB card), and Windows + // counts those file pages in this process's working set, not as available: a 32 GB PC read 0.44 GiB here + // (20.7 GiB before the start). Trimmed, they move to the standby list (still cached, counted as available). + // Resident mode only: nothing else calls this function. Locked/pinned pages stay; the rest fault back softly. + { + uint64_t before = 0, after = 0; + const bool read_before = available_memory_bytes(before); + (void) SetProcessWorkingSetSize(GetCurrentProcess(), (SIZE_T) -1, (SIZE_T) -1); + if (read_before && available_memory_bytes(after)) + std::fprintf(stderr, "FileExpertSource: available RAM %.2f GiB, %.2f GiB after the mapped experts left the " + "process working set (#467)\n", + (double) before / 1073741824.0, (double) after / 1073741824.0); + } +#endif + const bool what_fits = budget_bytes == kResidentWhatFits; // #467: the soft mode's second try uint64_t budget_physical = 0; // #403: the RAM reading a budget was sized from (0: no budget) if (budget_bytes > 0) { // CS-T: a RAM budget. The complement's experts in `rank` order (the expert profile, hottest first) while @@ -1041,10 +1057,16 @@ bool FileExpertSource::pin_cache_complement( // lower). An unclamped budget is unchanged. const uint64_t margin = 256ull << 20; const uint64_t clamped = room > margin ? room - margin : 0; - std::fprintf(stderr, "FileExpertSource: --resident-budget-gib %.2f is more than the RAM has room for " - "(%.2f GiB available minus %.0f GiB headroom and a 0.25 GiB margin): %.2f GiB\n", - (double) budget_bytes / 1073741824.0, (double) physical / 1073741824.0, - (double) headroom_bytes / 1073741824.0, (double) clamped / 1073741824.0); + if (what_fits) + std::fprintf(stderr, "FileExpertSource: RAM room for the complement: %.2f GiB (%.2f GiB available " + "minus %.0f GiB headroom and a 0.25 GiB margin)\n", + (double) clamped / 1073741824.0, (double) physical / 1073741824.0, + (double) headroom_bytes / 1073741824.0); + else + std::fprintf(stderr, "FileExpertSource: --resident-budget-gib %.2f is more than the RAM has room for " + "(%.2f GiB available minus %.0f GiB headroom and a 0.25 GiB margin): %.2f GiB\n", + (double) budget_bytes / 1073741824.0, (double) physical / 1073741824.0, + (double) headroom_bytes / 1073741824.0, (double) clamped / 1073741824.0); budget_bytes = clamped; } std::vector ranked(offsets.size(), kNoComplement); @@ -1061,6 +1083,10 @@ bool FileExpertSource::pin_cache_complement( at += b; ++held; } + if (what_fits && held == 0) { // #467: nothing to keep - the caller's plain mmap fallback, not an empty copy + err = "FileExpertSource: the RAM has no room for any expert of the complement"; + return false; + } std::fprintf(stderr, "FileExpertSource: RAM budget %.2f GiB: %lld of the %.2f GiB of experts the GPU cache does " "not hold, by profile rank; the rest are read from the files\n", (double) budget_bytes / 1073741824.0, (long long) held, (double) bytes / 1073741824.0); diff --git a/src/program/generate.cpp b/src/program/generate.cpp index fa52c6bc..0475a5ed 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -3780,8 +3780,26 @@ int main(int argc, char** argv) { const int64_t k = plan_lend(chunk); if (k > 0) lend_from = xcache.slots() - k; } - if (src.pin_cache_complement(xcache, err, o.resident_pin, {}, lend_from, o.resident_headroom, - o.resident_budget, &profile)) { + bool resident_ok = src.pin_cache_complement(xcache, err, o.resident_pin, {}, lend_from, o.resident_headroom, + o.resident_budget, &profile); + 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); + 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 " + "kept in RAM and the rest are read from the model folder through the OS file " + "cache\n", + whole_err.c_str(), (double) src.resident_bytes() / 1073741824.0); + else + err = whole_err + "; " + err; + } + if (resident_ok) { if (o.adapt_every > 0 && o.adapt_swaps > 0 && !src.reserve_exchanges(std::min(o.adapt_swaps, 96), err)) { std::fprintf(stderr, "strata generate: CPU expert residency: %s\n", err.c_str()); From 22ee8d0e9ae7d9050662c9e869da70a2dd93a6ac Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 2 Oct 2026 09:35:59 +0200 Subject: [PATCH 2/2] serve, setup: name the small split card that caps the prompt chunk; setup recommends the big card alone (#448) - engine (layer splits only): when a stage's cache cannot fund the chunk CUDA0 alone would choose, a WARNING names it (CUDA index, name, cache slots, the slots the chunk borrows) and points at the helper cache (--expert-cache-device1, docs/SECOND_GPU.md). The chunk choice itself is unchanged: fits() is split into fits_one() with the same tests; one GPU never reaches the new log. - setup: a pair whose second card is under 12 GB beside a first card of 12 GB or more is still offered, but the first card alone is recommended (the default with --yes and Enter; offer_together asks "n" by default), with a note. A named --gpus pair is kept. Equal pairs (2x 8/16/24 GB) are unchanged. - The automatic drop of the small card from an auto split is not done: stages load their weights before the boundary search and the exact prompt-buffer bytes need the sessions made after it. --- setup.py | 32 +++++++++++++++++-- src/program/generate.cpp | 66 +++++++++++++++++++++++++++++++--------- tools/test_setup_risk.py | 36 ++++++++++++++++++++++ 3 files changed, 117 insertions(+), 17 deletions(-) diff --git a/setup.py b/setup.py index 67fdd4f5..4f57e2e3 100644 --- a/setup.py +++ b/setup.py @@ -390,6 +390,10 @@ def gpus(): GPU_PICK = None # --gpu N (issue #51); None: the card with the most VRAM SPLIT_MIN_VRAM_GB = 8 # a card sharing a model holds the dense weights and its own # prompt buffers too (docs/MULTI_GPU.md) +SPLIT_PROMPT_VRAM_GB = 12 # #448: a split stage lends a prompt chunk's buffers from its + # own cache; below this one cannot fund a 4096-token chunk + # (a 10 GB RTX 3080 beside a 32 GB card: 512 tokens, prompts + # 6.2x slower), while the big card alone could def cc(g) -> str: @@ -441,6 +445,20 @@ def together_ok(found) -> list: return ok_ if len(ok_) >= 2 else [] +def split_short(cards) -> list: + """#448: the later cards of a split that would cap its prompt chunk below what the first card alone reads (a card + under SPLIT_PROMPT_VRAM_GB beside one that has it). Empty: the split is recommended as before.""" + if len(cards) < 2 or cards[0]["vram_gb"] < SPLIT_PROMPT_VRAM_GB - 0.5: + return [] + return [g for g in cards[1:] if g["vram_gb"] < SPLIT_PROMPT_VRAM_GB - 0.5] + + +def split_short_note(g) -> str: + return (f"GPU {g['index']} ({g['name']}, {g['vram_gb']:.0f} GB) is too small to lend a split its prompt buffers: " + "it would cap prompt reading at 512-2048-token chunks, several times slower than the first card alone " + "(#448). It can serve as a helper expert cache instead (docs/SECOND_GPU.md)") + + def parse_gpus(text, found) -> list: """--gpus / --gpu with several: "0,2" or "all" (every card that can share the model).""" if str(text).strip().lower() == "all": @@ -549,13 +567,18 @@ def choose_gpus(a, found) -> list: say(" experts of its own layers, so together they hold about twice as many, and prompts are read about 20%") say(" faster (details: docs/MULTI_GPU.md). A much slower extra card can also make it slower.") opts = [can[:2]] + ([can] if len(can) > 2 else []) + [[g] for g in single] + # #448: a pair whose second card cannot lend a 4096-token chunk recommends the first card alone (still offered) + short = split_short(can[:2]) + rec = next(i for i, o in enumerate(opts, 1) if o == [can[0]]) if short else 1 for i, o in enumerate(opts, 1): label = (" + ".join(gpu_name(g) for g in o) + " together") if len(o) > 1 else gpu_name(o[0]) + " only" - say(f" {i}) {label}" + (" (recommended)" if i == 1 else "")) + say(f" {i}) {label}" + (" (recommended)" if i == rec else "")) for g in found: if gpu_problem(g, together=True) is not None: say(f" (GPU {g['index']}, {g['name']}: {gpu_problem(g, together=True)})") - pick = opts[int(ask("Which GPUs?", [str(i) for i in range(1, len(opts) + 1)], "1", a.yes or a.check)) - 1] + for g in short: + say(f" ({split_short_note(g)})") + pick = opts[int(ask("Which GPUs?", [str(i) for i in range(1, len(opts) + 1)], str(rec), a.yes or a.check)) - 1] return [g["index"] for g in pick] @@ -595,12 +618,15 @@ def offer_together(cfg_path: Path, cfg: dict, yes: bool) -> dict: say(" This model runs in the low-RAM mode with its experts kept in RAM, on one GPU (recommended: steady RAM") say(" use). On both, the experts the GPUs do not hold are read through the OS file cache instead: faster in") say(" two reports (#364, #384), but RAM can fill up to 0 free during long prompts.") + short = split_short(pair) # #448: one card recommended (asked "n" by default), as for --resident + for g in short: + say(f" {split_short_note(g)}.") missing = [g for g in pair if not engine_runs_on(g)] if missing: say(" The installed engine has no code for " + ", ".join(g["name"] for g in missing) + ": to use them " "together, run START-HERE.bat --setup --gpus " + ",".join(str(g["index"]) for g in pair)) elif ask(" Use both from now on? (you can change it later: START-HERE.bat --gpu N for one card)", - ["y", "n"], "n" if resident else "y", yes) == "y": + ["y", "n"], "n" if resident or short else "y", yes) == "y": cfg["gpu"] = [g["index"] for g in pair] cfg["layer_split"] = cfg.get("layer_split") or "auto" split_mmap(cfg) diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 0475a5ed..f9828c1a 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -3905,24 +3905,62 @@ int main(int argc, char** argv) { // 128-slot floor. The percentage cap is an AUTO-chunk rule and only the auto scan applies it - an // explicit --prefill is the operator's number, and a loan of it only has to fit. With one participant // (no split) this reduces to plan_lend exactly, so the single-GPU loan is unchanged from main. - auto fits = [&](int64_t c, bool cap) -> bool { - for (const PfPart& p : pf_parts) { - const int64_t k = part_slots(p, c); - if (k <= 0 || k + 128 > p.cache->slots()) return false; - if (cap && k * 100 > kAutoLendPct * p.cache->slots()) return false; - } + auto fits_one = [&](const PfPart& p, int64_t c, bool cap) -> bool { + const int64_t k = part_slots(p, c); + if (k <= 0 || k + 128 > p.cache->slots()) return false; + return !(cap && k * 100 > kAutoLendPct * p.cache->slots()); + }; + // `only`: CUDA0's cache alone (#448: what one GPU would choose, for the log below); null: every one + auto fits = [&](int64_t c, bool cap, const PfPart* only = nullptr) -> bool { + if (only != nullptr) return fits_one(*only, c, cap); + for (const PfPart& p : pf_parts) + if (!fits_one(p, c, cap)) return false; return true; }; static constexpr int64_t kAutoChunks[] = {32768, 16384, 8192, 6144, 4096, 3072, 2048, 1024, 512, 256}; - int64_t chunk = 0; - if (o.prefill_auto) { - for (const int64_t c : kAutoChunks) { - if (c > 8192 && (c > o.prefill_auto_max || c > o.max_context)) continue; // #282, as plan_lend - if (fits(c, true)) { chunk = c; break; } + auto pick = [&](const PfPart* only) -> int64_t { + if (o.prefill_auto) { + for (const int64_t c : kAutoChunks) { + if (c > 8192 && (c > o.prefill_auto_max || c > o.max_context)) continue; // #282, as plan_lend + if (fits(c, true, only)) return c; + } + } else { + for (int64_t c = o.prefill_chunk; c >= 256; c /= 2) + if (fits(c, false, only)) return c; + } + return 0; + }; + const int64_t chunk = pick(nullptr); + // #448: a small card in a layer split caps every stage's chunk (an RTX 3080's 512-slot cache held a + // 32 GB card's split to 512 tokens: prompts 6.2x slower, decode the same). Named when it bites, so the + // regression is one log line: each stage that cannot fund the chunk CUDA0 alone would read in. + if (pf_parts.size() > 1) { + const int64_t alone = pick(&pf_parts[0]); + if (alone > chunk) { + for (size_t i = 1; i < pf_parts.size(); ++i) { + const PfPart& p = pf_parts[i]; + if (fits_one(p, alone, o.prefill_auto)) continue; + const int dev = p.dev < 0 ? 0 : p.dev; + cudaDeviceProp prop{}; + if (cudaGetDeviceProperties(&prop, dev) != cudaSuccess) { + (void) cudaGetLastError(); + prop.name[0] = 0; + } + const std::string pct = + o.prefill_auto ? ", and lend at most " + std::to_string(kAutoLendPct) + "%" : ""; + std::fprintf(stderr, "strata serve: WARNING: prompt chunk %lld tokens, not %lld: CUDA%d (%s) " + "has %lld expert-cache slots, and a %lld-token chunk borrows %lld of them " + "(it must keep 128%s) - prompts read slower than on CUDA0 alone (#448)\n", + (long long) chunk, (long long) alone, dev, prop.name, + (long long) p.cache->slots(), (long long) alone, + (long long) part_slots(p, alone), pct.c_str()); + // the helper tiers start at CUDA1 without a split (and are enabled in order) + std::fprintf(stderr, "strata serve: a card this small can serve as a helper expert cache " + "instead of a split stage: without --layer-split, with %s " + "(docs/SECOND_GPU.md)\n", + dev == 1 ? "--expert-cache-device1 N" : "--expert-cache-device1..3 N, in order"); + } } - } else { - for (int64_t c = o.prefill_chunk; c >= 256; c /= 2) - if (fits(c, false)) { chunk = c; break; } } if (chunk > 0) { if (o.prefill_auto) diff --git a/tools/test_setup_risk.py b/tools/test_setup_risk.py index 05aa399e..1fbb59de 100644 --- a/tools/test_setup_risk.py +++ b/tools/test_setup_risk.py @@ -277,6 +277,42 @@ class SmallCard(unittest.TestCase): self.assertEqual(cfg["gpu"], 0) # one card: as before +class SplitShortCard(unittest.TestCase): + """#448: a second card too small to lend a split's prompt chunk: the first card alone recommended, the pair kept + when named.""" + FOUND = [card(0, "NVIDIA RTX PRO 4500 Blackwell", 31.8, "120"), card(1, "NVIDIA GeForce RTX 3080", 10.0, "86")] + + def test_rule(self): + self.assertEqual([g["index"] for g in setup.split_short(self.FOUND)], [1]) + self.assertEqual(setup.split_short(PROFILES["32GB-2x24GB"][1]), []) + self.assertEqual(setup.split_short(PROFILES["47GB-2x16GB"][1]), []) + eights = [card(i, "NVIDIA GeForce RTX 3070", 8.0, "86") for i in range(2)] + self.assertEqual(setup.split_short(eights), []) # neither card alone reads more + + def test_yes_takes_the_first_card(self): + code, out, cfg, _ = install(127.8, self.FOUND, ["--family", "qwen", "--model", "Q2_0", "--no-start"]) + self.assertEqual(code, 0, out) + self.assertEqual(cfg["gpu"], 0) + self.assertIn("too small to lend a split its prompt buffers", out) + + def test_named_pair_is_kept(self): + code, out, cfg, _ = install(127.8, self.FOUND, ["--family", "qwen", "--model", "Q2_0", "--no-start", + "--gpus", "0,1"]) + self.assertEqual(code, 0, out) + self.assertEqual(cfg["gpu"], [0, 1]) + + def test_offer_together_defaults_to_one(self): + with tempfile.TemporaryDirectory() as d: + p = Path(d) / "strata-q2_0.json" + with mock.patch.object(setup, "gpus", lambda: self.FOUND), \ + mock.patch.object(setup, "engine_runs_on", lambda g: True): + code, out, asked = run(setup.offer_together, p, {"args": ["--mmap-experts"]}, True) + cfg = json.loads(p.read_text()) + self.assertIsNone(code, out) + self.assertNotIn("gpu", cfg) + self.assertIn("#448", out) + + class RamFloor(unittest.TestCase): """S7: less RAM than the smallest model needs: a stop with --yes alone, a risk with --model.""" FOUND = [card(0, "NVIDIA GeForce RTX 3060", 8.0, "86")]