diff --git a/docs/AMD_HIP_PERFORMANCE.md b/docs/AMD_HIP_PERFORMANCE.md index d1ed1843..1816c2f9 100644 --- a/docs/AMD_HIP_PERFORMANCE.md +++ b/docs/AMD_HIP_PERFORMANCE.md @@ -34,9 +34,12 @@ GGUF/tokenizer/template, `--mmap-experts --resident-cpu-experts`, fixed ranked and `--vram-reserve-mib 1024`. Keep PLE on SSD. `--resident-cpu-experts` copies the complement of the static GPU cache to ordinary -RAM. It requires mmap, a fixed expert profile, and disabled adaptation. It does -not lock all data into RAM: temporary prefill borrowing and cache refill may -still use the mapped fallback. Allocation needs sufficient available RAM; +RAM. It requires mmap and a fixed expert profile. The slots the prompt path may +borrow keep their experts in RAM too as far as the budget below allows (the rest +use the mapped fallback while borrowed and for their refill), and adaptive swaps +(`--adapt-every`) exchange experts between VRAM and the RAM copy without reading +the file. The copy is pageable; `--resident-experts` (CUDA, chosen by setup) +page-locks it and uses 4 GiB of headroom. Allocation needs sufficient available RAM; on Linux this option requires readable standard cgroup-v2 mounts. For each finite cgroup ancestor, the guard credits only `inactive_file` after subtracting `file_dirty` and `file_writeback`, capped by current usage; it remains bounded by diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 1217072e..54bbef77 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -86,6 +86,24 @@ On the Coder the engine's committed memory drops from 36 to ~13 GB, with the sam experts come from the SSD and it is much slower (setup says so). `START-HERE.bat --setup --low-ram on|off` overrides the choice. +**Low-RAM mode, resident (engine 0.1.30):** when the experts the GPU does not hold fit the RAM (with the same ~10 GB +beside them), setup picks the resident variant instead (`--resident-experts`): at start the engine copies exactly those +experts from `experts.bin` into RAM (page-locked when the driver allows, else locked in RAM), so while it answers +nothing is read from the SSD, however little RAM the OS leaves for its file cache. Examples with setup's context: a +32 GB PC with a 24 GB GPU runs Q2_0, IQ2_XS and the Coder this way (~16-18 GB of experts in RAM, the GPU holds the +other ~18 GB), a 32 GB PC with a 12-16 GB GPU the Coder; IQ3_XXS on a 32 GB PC stays mapped. The details: +- The prompt path borrows room in the GPU's expert cache for its buffers and puts those experts back after the prompt; + as far as the RAM allows, their experts are kept in RAM too (so a prompt reads nothing from the SSD either). +- The cache still follows the conversation (`--adapt-every`): a swap copies the evicted expert back from VRAM into the + RAM place of the one that replaces it, so the RAM copy keeps holding exactly what the GPU does not. +- The answers are the plain mapped mode's for the same expert placement: the bytes are the file's. With a page-locked + copy the GPU also takes its usual share of the misses over PCIe (`--pcie-frac`), as with enough RAM; `--pcie-frac 0` + (or `STRATA_RESIDENT_PIN=0`) gives the mapped mode's exact tokens. +- The engine leaves 4 GB of the RAM it finds free (`STRATA_RESIDENT_HEADROOM_GIB`); when even the experts the GPU does + not hold do not fit, it says so and runs the plain mapped mode. The server log shows, per request, how many expert + reads went to the file (`resident RAM: ... blob reads from the file`: 0 in steady use). +- `--low-ram resident|mmap` forces one variant (also on a PC with enough RAM, e.g. to try it). + Time to first token is prompt length / prompt speed: with Q2_0 about 4 s at 4K, 25 s at 32K, under 2 minutes at 128K and 4.5 minutes at 262K (engine 0.1.13 made long prompts about twice as fast, below). diff --git a/include/strata/core/expert_source.hpp b/include/strata/core/expert_source.hpp index 0b357a1b..56ed618a 100644 --- a/include/strata/core/expert_source.hpp +++ b/include/strata/core/expert_source.hpp @@ -25,6 +25,7 @@ #include "strata/core/hit_hook.hpp" #include "strata/kernels/cpu/pool.hpp" +#include #include #include #include @@ -66,6 +67,18 @@ const uint8_t* cache_complement_blob_or_fallback( size_t index, const std::vector& offsets, const uint8_t* complement_host, const uint8_t* mapped_fallback); +/// The resident RAM mode: which GPU-cache slots' experts are kept in RAM too. The prompt path lends the cache's +/// LAST slots (from `lend_from` on; a short prompt lends only the last few), and a lent slot's expert is streamed +/// from RAM during the prompt and copied back into its slot after it. `base_bytes` (every expert no slot holds) +/// must fit `budget`; slots are then added from the end down to `lend_from` while they still fit. Returns the +/// first slot kept in RAM (`slot_bytes.size()` = none), or -1 when `base_bytes` alone exceeds `budget`. +int64_t choose_resident_keep_from(const std::vector& slot_bytes, uint64_t base_bytes, uint64_t budget, + int64_t lend_from); + +/// The adaptive tier swapped `in` into a GPU slot and `out` out of it: `out` takes `in`'s place in the compact copy +/// (the caller copies out's bytes there). False, and nothing changed, unless `in` is in the copy and `out` is not. +bool exchange_cache_complement(std::vector& offsets, size_t in, size_t out); + } // namespace detail @@ -98,6 +111,10 @@ public: virtual void begin_layer(int64_t layer, const int32_t* ids, int64_t k) { (void) layer; (void) ids; (void) k; } /// Plan v0.3 P6: the DEVICE address of a pinned, mapped blob (the GPU can read it over PCIe), or null. virtual const uint8_t* device_alias(int64_t layer, int64_t expert) const { (void) layer; (void) expert; return nullptr; } + /// Whether the verify window may give the GPU a PCIe share of this layer's misses at all (each expert is still + /// checked with `pinned`). The arena answers per layer through its expert 0; the resident RAM mode's compact + /// copy has no expert 0 when the GPU cache holds it, so it answers for the whole copy. + virtual bool pcie_layer(int64_t layer) const { return device_alias(layer, 0) != nullptr; } }; /// Plan v0.3 P6: what the GPU computes in a verify window's layer, written by the pool (mapped host memory) right @@ -315,9 +332,20 @@ public: bool open(const std::string& pack_dir, int64_t n_layers, int64_t n_expert, std::string& err); /// Pin a compact host mirror of experts absent from a fully filled static GPU cache. The mmap remains open /// as a fallback for later cache reloads. This is opt-in because the complement may still be a large allocation. + /// + /// The resident RAM mode (`--resident-experts`, `--resident-cpu-experts`): + /// - `pin`: page-locked and mapped (`cudaHostAlloc`), so the prompt path copies it by DMA and the verify + /// window may read a share of the misses over PCIe; when the driver refuses, ordinary memory locked in the + /// working set instead. `pin = false` is ordinary pageable memory (the ROCm arm: large pinned allocations + /// can fail there, and it is what the HIP measurements used). + /// - `lend_from_slot` >= 0: the GPU-cache slots from there to the end are the prompt path's lend region; their + /// experts are kept in RAM too, from the last slot down, as far as `available RAM - headroom_bytes` allows + /// (a lent slot's expert is streamed during the prompt and copied back after it). + /// - the rest (the experts no slot holds) must fit that budget, or nothing is allocated and this returns false. bool pin_cache_complement( const ExpertCache& cache, std::string& err, bool pin = true, - const std::vector>& additional_gpu_pairs = {}); + const std::vector>& additional_gpu_pairs = {}, int64_t lend_from_slot = -1, + uint64_t headroom_bytes = 8ull << 30); void close(); bool mapped() const { return base_ != nullptr; } @@ -325,10 +353,35 @@ public: uint64_t pinned_bytes() const { return complement_pinned_ ? complement_bytes_ : 0; } uint64_t resident_bytes() const { return complement_bytes_; } bool complement_pinned() const { return complement_pinned_; } + bool complement_ready() const { return complement_ready_; } + uint64_t locked_bytes() const { return complement_locked_; } + /// Lend-region slots whose experts the compact copy holds (the last ones of the cache). + int64_t resident_lent_slots() const { return complement_lent_slots_; } + + // ---- the resident RAM mode and the adaptive tier. A swap puts `in` (held here) into a GPU slot and evicts + // `out` (held only by that slot). Before the slot is overwritten the caller copies it back into an exchange + // buffer and calls `stage_exchange`: `out` is then read from that buffer, and `in` still from here (the CPU + // computes both until the swap lands). Once the slot copy has landed, `commit_exchanges` moves `out` into + // `in`'s place, so the copy keeps holding exactly the experts the GPU does not - with no read of the file. + /// Whether the compact copy holds `(layer, expert)`. + bool has_resident(int64_t layer, int64_t expert) const; + /// Host room for `n` evicted blobs (page-locked when possible). Idempotent for the same or a smaller `n`. + bool reserve_exchanges(int64_t n, std::string& err); + int64_t exchange_capacity() const { return xstage_cap_; } + uint8_t* exchange_buffer(int64_t q) const; + /// Requires `has_resident(layer, in)`, `!has_resident(layer, out)` and `exchange_buffer(q)` holding out's blob. + bool stage_exchange(int64_t layer, int64_t in, int64_t out, int64_t q); + /// After the GPU copies of every staged swap have landed. Returns how many exchanges were applied. + int64_t commit_exchanges(); + int64_t exchanges() const { return exchanges_; } + /// With the compact copy ready: blobs read from the mapped file since (what the plain mmap mode may read from + /// the SSD). 0 in a steady resident mode; lend-region experts that did not fit the RAM count here. + int64_t file_reads() const { return file_reads_.load(std::memory_order_relaxed); } const uint8_t* blob(int64_t layer, int64_t expert) override; bool pinned(int64_t layer, int64_t expert) const override; const uint8_t* device_alias(int64_t layer, int64_t expert) const override; + bool pcie_layer(int64_t layer) const override; /// Blobs touched, for the driver to report. With `h = 0` this is `48 * k` per token and the number is only /// interesting once Phase 3 makes it not so. @@ -350,6 +403,17 @@ private: std::vector complement_offsets_; bool complement_pinned_ = false; bool complement_ready_ = false; + uint64_t complement_locked_ = 0; ///< bytes held in the working set (pin refused) + int64_t complement_lent_slots_ = 0; + std::vector override_; ///< staged exchanges: an evicted expert read from its exchange buffer + struct Exchange { size_t in, out; int64_t q; uint64_t bytes; }; + std::vector staged_; + uint8_t* xstage_ = nullptr; ///< exchange buffers, `xstage_cap_ x xstage_blob_` + bool xstage_pinned_ = false; + int64_t xstage_cap_ = 0; + uint64_t xstage_blob_ = 0; + int64_t exchanges_ = 0; + std::atomic file_reads_{0}; int64_t reads_ = 0; #if defined(_WIN32) void* file_ = nullptr; diff --git a/setup.py b/setup.py index e05cda39..d04188a3 100644 --- a/setup.py +++ b/setup.py @@ -1119,6 +1119,7 @@ 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) def low_ram_needed(model, ram) -> bool: @@ -1127,9 +1128,26 @@ def low_ram_needed(model, ram) -> bool: return ram < MODELS[model]["arena_gb"] + LOW_RAM_HEADROOM_GB -def low_ram_gpu_share(model, vram_gb) -> float: - """About how much of the model's experts the GPU holds (VRAM minus ~5 GB for the dense weights, KV, buffers).""" - return max(0.0, min(1.0, (vram_gb - 5) / MODELS[model]["arena_gb"])) +def low_ram_gpu_gb(model, vram_gb, ctx=32768, kv="int8") -> float: + """About how many GB of the model's experts the GPU's cache holds: its VRAM minus ~5 GB for the dense weights, + buffers and a 32K context's KV cache, minus the KV cache of a longer context (in VRAM in the low-RAM mode: its RAM + has no room for KV streaming).""" + kv_tok = 13 * (576 if kv == "q4_0" else 1056) # bytes per context token: 12 QSA layers + the draft layer + longer = max(0, ctx - 32768) * kv_tok / 1e9 + return max(0.0, min(MODELS[model]["arena_gb"], vram_gb - 5 - longer)) + + +def low_ram_gpu_share(model, vram_gb, ctx=32768, kv="int8") -> float: + """About how much of the model's experts the GPU holds.""" + return low_ram_gpu_gb(model, vram_gb, ctx, kv) / MODELS[model]["arena_gb"] + + +def low_ram_resident(model, ram, vram_gb, ctx=32768, kv="int8") -> bool: + """In the low-RAM mode: the experts the GPU does not hold fit the RAM with the usual room beside them, so they are + copied into RAM once (the resident variant, `--resident-experts`) instead of being read through the OS file cache + (plain `--mmap-experts`, which a PC this short of RAM keeps re-reading from the SSD).""" + rest = MODELS[model]["arena_gb"] - low_ram_gpu_gb(model, vram_gb, ctx, kv) + return ram >= rest + LOW_RAM_HEADROOM_GB def low_ram_fits(model, ram, vram_gb) -> bool: @@ -1623,9 +1641,11 @@ def main() -> int: ap.add_argument("--draft-vocab", choices=list(DRAFT_VOCABS), help="the draft layer's tokens: cjk = with Chinese, Japanese and Korean (default), en = English " "and code only (~110 MiB less VRAM, English answers 1-2%% faster)") - ap.add_argument("--low-ram", choices=["auto", "on", "off"], default="auto", - help="map the model's experts from its folder instead of copying them into RAM (for a PC with a big " - "GPU and little RAM); auto: when the experts would not fit the RAM") + ap.add_argument("--low-ram", choices=["auto", "on", "off", "resident", "mmap"], default="auto", + help="read the model's experts from one file in its folder instead of copying them all into RAM " + "(for a PC with a big GPU and little RAM); auto: when the experts would not fit the RAM. In " + "this mode the experts the GPU does not hold are copied into RAM once when they fit (resident), " + "else read through the OS file cache (mmap); resident / mmap force one of the two") ap.add_argument("--backend", choices=["cuda", "hip"], help="cuda = NVIDIA (default), hip = AMD RX 7900 XT/XTX on Linux (experimental; chosen by itself " "when the PC has no NVIDIA card Strata can use)") @@ -1786,7 +1806,8 @@ def main() -> int: verdict = "fits" if ram >= d["ram_gb"] else "tight" if ram >= d["ram_gb"] - 8 else "does not fit" if low_ram_needed(m, ram) and low_ram_fits(m, ram, gpu["vram_gb"]) and a.low_ram != "off": verdict = (f"fits in the low-RAM mode (the GPU holds ~{100 * low_ram_gpu_share(m, gpu['vram_gb']):.0f}% " - "of its experts)") + "of its experts, " + ("the rest stays in RAM)" if low_ram_resident(m, ram, gpu["vram_gb"]) + else "the rest is read from the SSD as needed)")) say(f" {m:8s} needs ~{d['ram_gb']} GB RAM: {verdict}") say("\nThis PC can run Strata. Run it again without --check to install.") return 0 @@ -1813,22 +1834,17 @@ def main() -> int: d = MODELS[m] fit = "" if ram >= d["ram_gb"] else f" <- needs {d['ram_gb']} GB RAM, you have {ram:.0f}" if low_ram_needed(m, ram) and low_ram_fits(m, ram, gpu["vram_gb"]) and a.low_ram != "off": - fit = f" <- fits in the low-RAM mode (the GPU holds ~{100 * low_ram_gpu_share(m, gpu['vram_gb']):.0f}%)" + fit = (f" <- fits in the low-RAM mode (the GPU holds ~{100 * low_ram_gpu_share(m, gpu['vram_gb']):.0f}%, " + + ("the rest in RAM)" if low_ram_resident(m, ram, gpu["vram_gb"]) else "the rest from the SSD)")) say(f" {i}) {m:8s} {d['about']}; download {d['download_gb']:.0f} GB, uses ~{d['arena_gb']:.0f} GB of RAM{fit}") rec = str(names.index("IQ3_XXS") + 1) if ram >= 60 and "IQ3_XXS" in names else "1" model = a.model or names[int(ask("Which size?", [str(i) for i in range(1, len(names) + 1)], rec, a.yes)) - 1] - low_ram = a.low_ram == "on" or (a.low_ram == "auto" and low_ram_needed(model, ram)) + low_ram = a.low_ram in ("on", "resident", "mmap") or (a.low_ram == "auto" and low_ram_needed(model, ram)) if low_ram and multi: warn("the low-RAM mode runs on one GPU: using " + gpu_name(gpu) + " only") multi, sel, chosen = [], [gpu["index"]], [gpu] - if low_ram: - share = low_ram_gpu_share(model, gpu["vram_gb"]) - ok(f"low-RAM mode: {model}'s experts ({MODELS[model]['arena_gb']:.0f} GB) are read from the model folder " - f"through the OS file cache instead of a copy in RAM ({ram:.0f} GB); the GPU holds ~{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 ram < MODELS[model]["ram_gb"] - 4: + # (the low-RAM mode's variant is decided once the context is known, below) + if not low_ram and ram < MODELS[model]["ram_gb"] - 4: # #125: a warning and a question, not a stop: the user may accept paging (asked, "no" by default, so an # unattended --yes install still stops here) need_gb, arena = MODELS[model]["ram_gb"], MODELS[model]["arena_gb"] @@ -1886,6 +1902,27 @@ def main() -> int: say(" download and keeps ~1.4 GB of VRAM free for the image encoder, so text is a few % slower.") vision = "gpu" if ask("Do you want images?", ["y", "n"], "n", a.yes) == "y" else "none" ok("images: " + {"none": "off", "gpu": "on", "cpu": "on (encoder on the CPU)"}[vision]) + # The low-RAM mode's two variants. resident: the experts the GPU's cache does not hold (and, as far as RAM allows, + # the ones the prompt path borrows cache room from) are copied from the pack's experts.bin into RAM once, so + # nothing is read from the SSD while it answers (engine 0.1.30, --resident-experts; the engine falls back to mmap + # with a warning when they do not fit the RAM it finds free). mmap: they are read through the OS file cache. + # The GPU's share: its VRAM less the dense weights and buffers, this context's KV cache and the image encoder's room. + resident = False + if low_ram: + arena = MODELS[model]["arena_gb"] + vram = gpu["vram_gb"] - (VISION[vision]["reserve_mib"] / 1024 if vision != "none" else 0) + 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 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") + else: + ok(f"low-RAM mode: {model}'s experts ({arena:.0f} GB) are read from the model folder through the OS file " + f"cache instead of a copy in RAM ({ram:.0f} GB); the GPU holds ~{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)") # EXPERIMENTAL: the experimental-speed-projection control vector (data/experimental-speed-projection), off unless # chosen here; with it loaded, the web app and the API switch it off per request esp = None @@ -2028,8 +2065,13 @@ def main() -> int: "--max-context", str(ctx)] if ctx > 8192: args += ["--kv", kv] - if low_ram: - args += ["--mmap-experts"] # the experts from the pack's experts.bin, not copied into RAM + engine_ver = tuple(int(x) for x in str(meta.get("version", "0")).split(".")[:3] if x.isdigit()) + if resident and a.low_ram != "resident" and engine_ver < RESIDENT_ENGINE: + resident = False # an engine from before --resident-experts would refuse it + ok(f"low-RAM mode: engine {meta.get('version')} has no resident variant yet; the experts are read through " + "the OS file cache (run setup again after the next engine update)") + if low_ram: # the experts from the pack's experts.bin: the ones the GPU does not hold copied into RAM, or mapped + args += ["--resident-experts" if resident else "--mmap-experts"] # KV streaming: from 64K up the whole KV cache lives in RAM and only the part the attention reads (32K positions # per layer) stays in VRAM; the VRAM it frees holds more experts (+6% at 128K, +23% at 262K with Q2_0). It # costs ~13.7 KB of RAM per context token with 8-bit KV (1.7 GB at 128K), 7.5 KB with 4-bit, so only when it fits. diff --git a/src/core/expert_source.cpp b/src/core/expert_source.cpp index d235b958..613a1315 100644 --- a/src/core/expert_source.cpp +++ b/src/core/expert_source.cpp @@ -4,6 +4,7 @@ #include "strata/kernels/cpu/expert_layout.hpp" #include "strata/core/pinned.hpp" +#include "strata/platform/memory.hpp" #include "strata/kernels/elementwise.hpp" #include "strata/kernels/quantize_act.hpp" #include "strata/kernels/s2_expert_grouped.hpp" @@ -20,6 +21,7 @@ #include #include #include +#include #include #include #include @@ -136,10 +138,33 @@ const uint8_t* cache_complement_blob_or_fallback( return mapped_fallback; } +int64_t choose_resident_keep_from(const std::vector& slot_bytes, uint64_t base_bytes, uint64_t budget, + int64_t lend_from) { + if (base_bytes > budget) return -1; + const int64_t slots = (int64_t) slot_bytes.size(); + if (lend_from < 0 || lend_from > slots) lend_from = slots; // no lend region: only the experts no slot holds + int64_t keep = slots; + uint64_t bytes = base_bytes; + while (keep > lend_from) { + const uint64_t b = slot_bytes[(size_t) keep - 1]; + if (b > budget - bytes) break; + bytes += b; + --keep; + } + return keep; +} + +bool exchange_cache_complement(std::vector& offsets, size_t in, size_t out) { + if (in == out || in >= offsets.size() || out >= offsets.size() || offsets[in] == kNoCacheComplement || + offsets[out] != kNoCacheComplement) return false; + offsets[out] = offsets[in]; + offsets[in] = kNoCacheComplement; + return true; +} + } // namespace detail namespace { -constexpr uint64_t kPinnedMemoryHeadroom = 8ull << 30; #if defined(__linux__) bool read_cgroup_memory_stat(const std::filesystem::path& path, uint64_t current, @@ -411,8 +436,23 @@ bool FileExpertSource::open(const std::string& pack_dir, int64_t n_layers, int64 void FileExpertSource::close() { if (complement_arena_ != nullptr) { if (complement_pinned_) (void) cudaFreeHost(complement_arena_); - else std::free(complement_arena_); + else { + if (complement_locked_ > 0) strata::platform::unlock_resident(complement_arena_, complement_locked_); + std::free(complement_arena_); + } } + if (xstage_ != nullptr) { + if (xstage_pinned_) (void) cudaFreeHost(xstage_); + else std::free(xstage_); + } + xstage_ = nullptr; + xstage_pinned_ = false; + xstage_cap_ = 0; + xstage_blob_ = 0; + override_.clear(); + staged_.clear(); + exchanges_ = 0; + file_reads_.store(0); complement_arena_ = nullptr; complement_host_ = nullptr; complement_device_ = nullptr; @@ -420,6 +460,8 @@ void FileExpertSource::close() { complement_offsets_.clear(); complement_pinned_ = false; complement_ready_ = false; + complement_locked_ = 0; + complement_lent_slots_ = 0; #if defined(_WIN32) if (base_ != nullptr) UnmapViewOfFile((LPCVOID) base_); if (mapping_ != nullptr) CloseHandle((HANDLE) mapping_); @@ -457,7 +499,8 @@ const uint8_t* FileExpertSource::mapped_blob(int64_t layer, int64_t expert) cons bool FileExpertSource::pin_cache_complement( const ExpertCache& cache, std::string& err, bool pin, - const std::vector>& additional_gpu_pairs) { + const std::vector>& additional_gpu_pairs, int64_t lend_from_slot, + uint64_t headroom_bytes) { err.clear(); if (base_ == nullptr) { err = "FileExpertSource: open the mapped experts before pinning a complement"; return false; } if (complement_ready_) { err = "FileExpertSource: the cache complement is already pinned"; return false; } @@ -473,12 +516,20 @@ bool FileExpertSource::pin_cache_complement( return false; } + // The GPU cache's experts, and the bytes each slot's expert takes here (for the lend region below). + const int64_t n_slots = cache.slots(); std::vector> primary_gpu_pairs; + std::vector pair_slot; + std::vector slot_bytes((size_t) std::max(n_slots, 0), 0); primary_gpu_pairs.reserve((size_t) cache.resident()); + pair_slot.reserve((size_t) cache.resident()); for (int64_t layer = 0; layer < n_layers_; ++layer) { for (int64_t expert = 0; expert < n_expert_; ++expert) { - if (cache.slot_of(layer, expert) != kNotResident) - primary_gpu_pairs.emplace_back((int32_t) layer, (int32_t) expert); + const int32_t slot = cache.slot_of(layer, expert); + if (slot == kNotResident) continue; + primary_gpu_pairs.emplace_back((int32_t) layer, (int32_t) expert); + pair_slot.push_back(slot); + if (slot >= 0 && slot < n_slots) slot_bytes[(size_t) slot] = layer_blob_bytes_[(size_t) layer]; } } std::vector offsets; @@ -486,136 +537,199 @@ bool FileExpertSource::pin_cache_complement( 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 (bytes > 0) { + const bool lend = lend_from_slot >= 0 && lend_from_slot < n_slots && additional_gpu_pairs.empty(); + uint64_t budget = std::numeric_limits::max(); + if (bytes > 0 || lend) { uint64_t physical = 0; if (!available_memory_bytes(physical)) { err = "FileExpertSource: cannot determine available RAM for the resident-memory safety check"; return false; } - if (physical <= kPinnedMemoryHeadroom || bytes > physical - kPinnedMemoryHeadroom) { - char message[256]; + budget = physical > headroom_bytes ? physical - headroom_bytes : 0; + if (bytes > budget) { + char message[320]; std::snprintf(message, sizeof message, - "FileExpertSource: resident complement %.2f GiB exceeds available RAM minus the 8 GiB safety headroom", - (double) bytes / 1073741824.0); + "FileExpertSource: resident complement %.2f GiB exceeds available RAM (%.2f GiB) minus the " + "%.0f GiB safety headroom", + (double) bytes / 1073741824.0, (double) physical / 1073741824.0, + (double) headroom_bytes / 1073741824.0); err = message; return false; } } + // The prompt path's lend region: its slots' experts are streamed from here during a prompt and copied back into + // their slots after it, so the ones that fit are kept here too (from the last slot down: a short prompt lends + // only the last few). The rest keep the mapped-file fallback. + int64_t keep_from = n_slots; + if (lend) { + keep_from = detail::choose_resident_keep_from(slot_bytes, bytes, budget, lend_from_slot); + if (keep_from < 0) keep_from = n_slots; + if (keep_from < n_slots) { + std::vector> core; + core.reserve(primary_gpu_pairs.size()); + for (size_t i = 0; i < primary_gpu_pairs.size(); ++i) + if (pair_slot[i] < keep_from) core.push_back(primary_gpu_pairs[i]); + if (!detail::make_cache_complement_plan(n_layers_, n_expert_, layer_blob_bytes_, core, + additional_gpu_pairs, offsets, bytes, err)) return false; + } + } void* arena = nullptr; const uint8_t* host = nullptr; const uint8_t* device = nullptr; + bool pinned_ok = false; + uint64_t locked = 0; + std::string note; + auto release = [&]() { + if (arena == nullptr) return; + if (pinned_ok) (void) cudaFreeHost(arena); + else { + if (locked > 0) strata::platform::unlock_resident(arena, locked); + std::free(arena); + } + arena = nullptr; + }; if (bytes > 0) { std::fprintf(stderr, "FileExpertSource: allocating %.2f GiB %s cache complement\n", - (double) bytes / 1073741824.0, pin ? "mapped pinned" : "pageable resident"); + (double) bytes / 1073741824.0, pin ? "page-locked" : "pageable resident"); std::fflush(stderr); if (pin) { const cudaError_t allocated = cudaHostAlloc(&arena, (size_t) bytes, cudaHostAllocMapped | cudaHostAllocPortable); - if (allocated != cudaSuccess) { - err = std::string("FileExpertSource: mapped pinned complement allocation failed: ") + - cudaGetErrorString(allocated); - std::fprintf(stderr, "%s\n", err.c_str()); - std::fflush(stderr); + if (allocated == cudaSuccess) { + void* alias = nullptr; + const cudaError_t aliased = cudaHostGetDevicePointer(&alias, arena, 0); + if (aliased == cudaSuccess && alias != nullptr) { + device = (const uint8_t*) alias; + pinned_ok = true; + note = "page-locked and mapped"; + } else { + note = std::string("no device alias (") + cudaGetErrorString(aliased) + ")"; + (void) cudaGetLastError(); + (void) cudaFreeHost(arena); + arena = nullptr; + } + } else { + // Refused (the driver's page-locked limit): the same bytes in ordinary memory, locked in the working + // set instead, as the arena does - resident either way, only copied by the CPU instead of by DMA. + note = std::string("page-locking refused (") + cudaGetErrorString(allocated) + ")"; (void) cudaGetLastError(); - return false; + arena = nullptr; } - host = (const uint8_t*) arena; - void* alias = nullptr; - const cudaError_t aliased = cudaHostGetDevicePointer(&alias, arena, 0); - if (aliased != cudaSuccess || alias == nullptr) { - err = std::string("FileExpertSource: mapped pinned complement device alias failed: ") + - cudaGetErrorString(aliased); - std::fprintf(stderr, "%s\n", err.c_str()); - std::fflush(stderr); - (void) cudaGetLastError(); - (void) cudaFreeHost(arena); - return false; - } - device = (const uint8_t*) alias; - } else { + } + if (arena == nullptr) { arena = std::malloc((size_t) bytes); if (arena == nullptr) { err = "FileExpertSource: pageable resident complement allocation failed"; return false; } - host = (const uint8_t*) arena; + if (pin) { + const strata::platform::LockResult lr = strata::platform::lock_resident(arena, bytes); + locked = lr.locked_bytes; + note += (note.empty() ? "" : "; ") + lr.note; + } } + host = (const uint8_t*) arena; } - uint64_t copied = 0; - for (int64_t layer = 0; layer < n_layers_; ++layer) { - const uint64_t blob_bytes = layer_blob_bytes_[(size_t) layer]; - for (int64_t expert = 0; expert < n_expert_; ++expert) { - const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert; - const uint64_t offset = offsets[index]; - if (offset == kNoComplement) continue; - const uint8_t* source = mapped_blob(layer, expert); - if (source == nullptr || offset > bytes || blob_bytes > bytes - offset) { - err = "FileExpertSource: invalid blob bounds while building the cache complement"; - if (arena != nullptr) { - if (pin) (void) cudaFreeHost(arena); - else std::free(arena); - } - return false; - } - std::memcpy((uint8_t*) host + (size_t) offset, source, (size_t) blob_bytes); - copied += blob_bytes; - } + // Copied layer by layer on a few threads: the page faults of the mapped file are the cost, and they overlap. #if !defined(_WIN32) - const uint64_t layer_offset = layer_offsets_[(size_t) layer]; - const uint64_t layer_bytes = blob_bytes * (uint64_t) n_expert_; - const uint64_t layer_end = layer_offset + layer_bytes; - const long page_bytes = sysconf(_SC_PAGESIZE); - if (page_bytes <= 0) { - err = "FileExpertSource: cannot determine page size for mapped-page release"; - if (arena != nullptr) { - if (pin) (void) cudaFreeHost(arena); - else std::free(arena); - } - return false; - } - const uint64_t page = (uint64_t) page_bytes; - const uint64_t advice_start = layer_offset - layer_offset % page; - const uint64_t end_remainder = layer_end % page; - const uint64_t extra = end_remainder == 0 ? 0 : page - end_remainder; - const uint64_t advice_end = extra > mapped_bytes_ - layer_end ? mapped_bytes_ : layer_end + extra; - if (advice_end > advice_start && - madvise((void*) (base_ + (size_t) advice_start), (size_t) (advice_end - advice_start), MADV_DONTNEED) != 0) { - err = "FileExpertSource: madvise could not release mapped expert layer " + std::to_string(layer); - if (arena != nullptr) { - if (pin) (void) cudaFreeHost(arena); - else std::free(arena); - } - return false; - } - const int advice = posix_fadvise(fd_, (off_t) layer_offset, (off_t) layer_bytes, POSIX_FADV_DONTNEED); - if (advice != 0) { - err = "FileExpertSource: posix_fadvise could not release expert layer " + std::to_string(layer); - if (arena != nullptr) { - if (pin) (void) cudaFreeHost(arena); - else std::free(arena); - } - return false; - } -#endif - if ((layer + 1) % 8 == 0 || layer + 1 == n_layers_) { - std::fprintf(stderr, "FileExpertSource: copied cache complement through layer %lld/%lld (%.2f GiB)\n", - (long long) (layer + 1), (long long) n_layers_, (double) copied / 1073741824.0); - std::fflush(stderr); - } + const long page_size = sysconf(_SC_PAGESIZE); + if (page_size <= 0) { + err = "FileExpertSource: cannot determine page size for mapped-page release"; + release(); + return false; } +#endif + std::atomic next_layer{0}, layers_done{0}; + std::atomic copied{0}; + std::atomic failed{false}; + std::mutex fail_mu; + std::string fail_msg; + auto fail = [&](const std::string& m) { + std::lock_guard lock(fail_mu); + if (fail_msg.empty()) fail_msg = m; + failed.store(true); + }; + auto worker = [&]() { + for (;;) { + const int64_t layer = next_layer.fetch_add(1); + if (layer >= n_layers_ || failed.load()) return; + const uint64_t blob_bytes = layer_blob_bytes_[(size_t) layer]; + for (int64_t expert = 0; expert < n_expert_; ++expert) { + const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert; + const uint64_t offset = offsets[index]; + if (offset == kNoComplement) continue; + const uint8_t* source = mapped_blob(layer, expert); + if (source == nullptr || offset > bytes || blob_bytes > bytes - offset) { + fail("FileExpertSource: invalid blob bounds while building the cache complement"); + return; + } + std::memcpy((uint8_t*) host + (size_t) offset, source, (size_t) blob_bytes); + copied.fetch_add(blob_bytes); + } +#if !defined(_WIN32) + const uint64_t layer_offset = layer_offsets_[(size_t) layer]; + const uint64_t layer_bytes = blob_bytes * (uint64_t) n_expert_; + const uint64_t layer_end = layer_offset + layer_bytes; + const uint64_t page = (uint64_t) page_size; + const uint64_t advice_start = layer_offset - layer_offset % page; + const uint64_t end_remainder = layer_end % page; + const uint64_t extra = end_remainder == 0 ? 0 : page - end_remainder; + const uint64_t advice_end = extra > mapped_bytes_ - layer_end ? mapped_bytes_ : layer_end + extra; + if (advice_end > advice_start && + madvise((void*) (base_ + (size_t) advice_start), (size_t) (advice_end - advice_start), MADV_DONTNEED) != 0) { + fail("FileExpertSource: madvise could not release mapped expert layer " + std::to_string(layer)); + return; + } + if (posix_fadvise(fd_, (off_t) layer_offset, (off_t) layer_bytes, POSIX_FADV_DONTNEED) != 0) { + fail("FileExpertSource: posix_fadvise could not release expert layer " + std::to_string(layer)); + return; + } +#endif + const int64_t done = layers_done.fetch_add(1) + 1; + if (done % 8 == 0 || done == n_layers_) + std::fprintf(stderr, "FileExpertSource: copied cache complement through layer %lld/%lld (%.2f GiB)\n", + (long long) done, (long long) n_layers_, (double) copied.load() / 1073741824.0); + } + }; + { + const int threads = (int) std::max(1, std::min(6, n_layers_)); + std::vector pool; + for (int i = 1; i < threads; ++i) pool.emplace_back(worker); + worker(); + for (auto& t : pool) t.join(); + } + std::fflush(stderr); + if (failed.load()) { + err = fail_msg; + release(); + return false; + } +#if defined(_WIN32) + // The mapped pages this process touched (the GPU cache's fill and this copy) leave its working set for the + // standby list: VirtualUnlock on pages that are not locked does exactly that (it then reports ERROR_NOT_LOCKED). + (void) VirtualUnlock((LPVOID) base_, (SIZE_T) mapped_bytes_); +#endif complement_arena_ = arena; complement_host_ = host; complement_device_ = device; complement_bytes_ = bytes; complement_offsets_ = std::move(offsets); - complement_pinned_ = pin && bytes > 0; + complement_pinned_ = pinned_ok && bytes > 0; + complement_locked_ = locked; + complement_lent_slots_ = lend ? n_slots - keep_from : 0; complement_ready_ = true; - std::fprintf(stderr, "FileExpertSource: %s cache complement ready: resident %.2f GiB, pinned %.2f GiB\n", - complement_pinned_ ? "mapped pinned" : "pageable resident", - (double) resident_bytes() / 1073741824.0, (double) pinned_bytes() / 1073741824.0); + std::fprintf(stderr, "FileExpertSource: %s cache complement ready: resident %.2f GiB, pinned %.2f GiB%s%s\n", + complement_pinned_ ? "mapped pinned" : pin ? "locked resident" : "pageable resident", + (double) resident_bytes() / 1073741824.0, (double) pinned_bytes() / 1073741824.0, + note.empty() ? "" : "; ", note.c_str()); + if (lend) + std::fprintf(stderr, "FileExpertSource: %lld of the prompt path's %lld lendable slots keep their experts in RAM " + "too%s\n", (long long) complement_lent_slots_, (long long) (n_slots - lend_from_slot), + complement_lent_slots_ < n_slots - lend_from_slot + ? " (the others are read from the file when lent: not enough RAM for them)" : ""); if (!additional_gpu_pairs.empty()) { std::fprintf(stderr, "FileExpertSource: %zu verified additional-GPU experts remain on the mmap fallback\n", additional_gpu_pairs.size()); @@ -624,13 +738,88 @@ bool FileExpertSource::pin_cache_complement( return true; } +bool FileExpertSource::has_resident(int64_t layer, int64_t expert) const { + if (!complement_ready_ || layer < 0 || expert < 0 || layer >= n_layers_ || expert >= n_expert_) return false; + const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert; + return index < complement_offsets_.size() && complement_offsets_[index] != kNoComplement; +} + +bool FileExpertSource::reserve_exchanges(int64_t n, std::string& err) { + err.clear(); + if (n <= xstage_cap_) return true; + if (!staged_.empty()) { err = "FileExpertSource: exchange buffers are in use"; return false; } + uint64_t blob = 0; + for (const uint64_t b : layer_blob_bytes_) blob = std::max(blob, b); + if (blob == 0 || n <= 0) { err = "FileExpertSource: no expert geometry for the exchange buffers"; return false; } + if (xstage_ != nullptr) { + if (xstage_pinned_) (void) cudaFreeHost(xstage_); + else std::free(xstage_); + xstage_ = nullptr; + xstage_cap_ = 0; + } + const size_t total = (size_t) n * (size_t) blob; + void* p = nullptr; + if (cudaHostAlloc(&p, total, cudaHostAllocDefault) == cudaSuccess && p != nullptr) { + xstage_pinned_ = true; + } else { + (void) cudaGetLastError(); + p = std::malloc(total); + xstage_pinned_ = false; + if (p == nullptr) { err = "FileExpertSource: cannot allocate the exchange buffers"; return false; } + } + xstage_ = (uint8_t*) p; + xstage_cap_ = n; + xstage_blob_ = blob; + return true; +} + +uint8_t* FileExpertSource::exchange_buffer(int64_t q) const { + if (xstage_ == nullptr || q < 0 || q >= xstage_cap_) return nullptr; + return xstage_ + (size_t) q * (size_t) xstage_blob_; +} + +bool FileExpertSource::stage_exchange(int64_t layer, int64_t in, int64_t out, int64_t q) { + if (!has_resident(layer, in) || has_resident(layer, out) || exchange_buffer(q) == nullptr) return false; + const size_t i_in = (size_t) layer * (size_t) n_expert_ + (size_t) in; + const size_t i_out = (size_t) layer * (size_t) n_expert_ + (size_t) out; + if (override_.empty()) override_.assign((size_t) blobs_, nullptr); + if (override_[i_out] != nullptr) return false; + for (const Exchange& x : staged_) + if (x.in == i_in || x.q == q) return false; + override_[i_out] = exchange_buffer(q); + staged_.push_back({i_in, i_out, q, layer_blob_bytes_[(size_t) layer]}); + return true; +} + +int64_t FileExpertSource::commit_exchanges() { + int64_t n = 0; + for (const Exchange& x : staged_) { + const uint8_t* src = override_[x.out]; + const uint64_t at = complement_offsets_[x.in]; + if (src != nullptr && at != kNoComplement && at <= complement_bytes_ && x.bytes <= complement_bytes_ - at && + complement_host_ != nullptr) { + std::memcpy((uint8_t*) complement_host_ + (size_t) at, src, (size_t) x.bytes); + if (detail::exchange_cache_complement(complement_offsets_, x.in, x.out)) ++n; + } + override_[x.out] = nullptr; + } + staged_.clear(); + exchanges_ += n; + return n; +} + const uint8_t* FileExpertSource::blob(int64_t layer, int64_t expert) { if (base_ == nullptr || layer < 0 || expert < 0 || layer >= n_layers_ || expert >= n_expert_) return nullptr; const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert; const uint8_t* mapped_fallback = mapped_blob(layer, expert); - const uint8_t* result = complement_ready_ - ? detail::cache_complement_blob_or_fallback(index, complement_offsets_, complement_host_, mapped_fallback) - : mapped_fallback; + const uint8_t* result = mapped_fallback; + if (complement_ready_) { + result = detail::cache_complement_blob_or_fallback(index, complement_offsets_, complement_host_, nullptr); + if (result == nullptr) { + result = !override_.empty() && override_[index] != nullptr ? override_[index] : mapped_fallback; + if (result == mapped_fallback && result != nullptr) file_reads_.fetch_add(1, std::memory_order_relaxed); + } + } if (result != nullptr) ++reads_; return result; } @@ -648,6 +837,12 @@ const uint8_t* FileExpertSource::device_alias(int64_t layer, int64_t expert) con return complement_device_ + (size_t) complement_offsets_[index]; } +bool FileExpertSource::pcie_layer(int64_t layer) const { + if (complement_ready_ && complement_pinned_ && complement_device_ != nullptr) + return layer >= 0 && layer < n_layers_; + return device_alias(layer, 0) != nullptr; +} + // ================================ THE ADAPTER ================================ void expert_pool_dispatch(void* user, const float* x_f, const int32_t* ids, const float* weights, int64_t n_embd, @@ -830,7 +1025,7 @@ void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32 if (e >= 0 && e < d.n_expert && d.host_res[(size_t) d.layers * (size_t) d.n_expert + (size_t) e] < 0) ++nmiss; } } - const bool pcie_ok = d.pcie_num > 0 && d.src->device_alias(d.layers, 0) != nullptr; + const bool pcie_ok = d.pcie_num > 0 && d.src->pcie_layer(d.layers); const int m = pcie_ok ? (nmiss * d.pcie_num) >> 8 : 0; int miss_rank = 0, groups = 0, entries = 0, fetches = 0; GpuPlanSink& P = *d.plan; diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 60700870..43e4f0d5 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -97,6 +97,44 @@ bool refill_blocking() { using Clock = std::chrono::steady_clock; +// The resident RAM mode and the adaptive tier. A swap copies `in` (held in RAM) into the slot of `out` (held only +// by that slot). Before the slot is overwritten, `out`'s bytes are copied back from it into an exchange buffer, so +// the CPU computes `out` from RAM while the swap is in flight; when the swap has landed, `commit_exchanges` moves +// them into `in`'s place in RAM. The RAM copy then again holds exactly the experts no core slot does, and no swap +// 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) { + if (!src.complement_ready() || swaps.empty()) return true; + struct Staged { int32_t layer, in, out; int64_t q; }; + std::vector staged; + std::vector kept; + kept.reserve(swaps.size()); + for (const Swap& s : swaps) { + if (!src.has_resident(s.layer, s.in) || src.has_resident(s.layer, s.out)) { kept.push_back(s); continue; } + const int64_t q = (int64_t) staged.size(); + 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), + (size_t) strata::kernels::cpu::expert_layout().blob_bytes(s.layer), cudaMemcpyDeviceToHost, + stream) != cudaSuccess) + return false; + 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 Staged& x : staged) + if (!src.stage_exchange(x.layer, x.in, x.out, x.q)) return false; + } + swaps.swap(kept); + return true; +} + struct Options { std::string pack = "pack/full"; std::vector tokens; // the prompt, PRE-TOKENIZED @@ -183,6 +221,12 @@ struct Options { bool no_host_worker = false; bool mmap_experts = false; ///< R2.1: opt OUT of the resident arena, back to MapViewOfFile bool resident_cpu_experts = false; ///< mmap-backed static-cache misses copied into ordinary RAM + /// `--resident-experts` (the low-RAM PC's resident mode, chosen by setup): `--resident-cpu-experts` with the copy + /// page-locked when the driver allows (else locked in the working set), 4 GiB of RAM headroom, and plain mmap + /// (with a warning) when even the experts no slot holds do not fit. + bool resident_pin = false; + uint64_t resident_headroom = 8ull << 30; + bool resident_soft = false; /// R4: slots of VRAM-resident experts. **0 = off, and off is the default.** /// **THE COMMENT THAT USED TO BE HERE WAS FALSE AND ROUND 328 MEASURED IT.** It said "the cache has no /// consumer yet - `moe_hit_grouped_s2` does not exist - so switching it on costs the fill traffic and @@ -436,8 +480,12 @@ void usage() { " --mmap-experts R2.1: opt OUT of the resident expert arena, back to MapViewOfFile.\n" " The A/B arm: the mmap's rate depends on the OS page cache holding\n" " 34 GB, and measured 71.97 vs 34.78 ms/token cold vs warm.\n" - " --resident-cpu-experts with mmap and a static profile, keep CPU misses resident in ordinary RAM.\n" - " Borrowed GPU-cache entries may read from mmap during prompt prefill.\n"); + " --resident-cpu-experts with mmap and a static profile, keep the experts the GPU cache does not\n" + " hold resident in ordinary RAM (and the prompt path's lend region as far as\n" + " RAM allows); adaptive swaps exchange them, so none is read from the file again.\n" + " --resident-experts the low-RAM PC's resident mode (setup): --mmap-experts --resident-cpu-experts\n" + " with the copy page-locked when possible, 4 GiB headroom, plain mmap if it\n" + " does not fit. Same answers as --mmap-experts for the same placement.\n"); } /// All shards of a split GGUF, from shard 1's path ("...-00001-of-00002.gguf"); just the path when it is not split. @@ -1072,6 +1120,16 @@ int main(int argc, char** argv) { else if (a == "--gpu-stages") o.gpu_stages = true; else if (a == "--mmap-experts") o.mmap_experts = true; else if (a == "--resident-cpu-experts") o.resident_cpu_experts = true; + else if (a == "--resident-experts") { + o.mmap_experts = o.resident_cpu_experts = o.resident_pin = o.resident_soft = true; + o.resident_headroom = 4ull << 30; + // A/B arms: STRATA_RESIDENT_PIN=0 keeps the copy pageable (the --resident-cpu-experts form); + // STRATA_RESIDENT_HEADROOM_GIB=N leaves N GiB of the available RAM free instead of 4 + if (const char* v = std::getenv("STRATA_RESIDENT_PIN"); v != nullptr && std::string(v) == "0") + o.resident_pin = false; + if (const char* v = std::getenv("STRATA_RESIDENT_HEADROOM_GIB"); v != nullptr && std::atof(v) >= 0.0) + o.resident_headroom = (uint64_t) (std::atof(v) * 1073741824.0); + } else if (a == "--stats") o.stats = true; else if (a == "--shared-late") o.shared_late = true; else if (a == "--keep-canonical") o.keep_canonical = true; @@ -1140,8 +1198,8 @@ int main(int argc, char** argv) { } } const bool multi_gpu = !split_devs.empty() && !split_same; - if (o.resident_cpu_experts && (!o.mmap_experts || o.expert_profile.empty() || o.adapt_every != 0)) { - std::fprintf(stderr, "strata generate: --resident-cpu-experts requires --mmap-experts, a static --expert-profile and --adapt-every 0\n"); + if (o.resident_cpu_experts && (!o.mmap_experts || o.expert_profile.empty())) { + std::fprintf(stderr, "strata generate: --resident-cpu-experts requires --mmap-experts and a static --expert-profile\n"); return 2; } if (o.resident_cpu_experts && @@ -2224,14 +2282,6 @@ int main(int argc, char** argv) { (long long) prefilled, (long long) want); } - if (o.resident_cpu_experts) { - if (!src.pin_cache_complement(xcache, err, /*pin=*/false)) { - std::fprintf(stderr, "strata generate: CPU expert residency: %s\n", err.c_str()); - return 1; - } - std::fprintf(stderr, "strata generate: steady-state CPU cache misses are resident in ordinary RAM; borrowed cache entries may use mmap during prompt prefill\n"); - } - for (auto& stp : stages) { GpuStage& st = *stp; const auto& lay = strata::kernels::cpu::expert_layout(); @@ -3083,6 +3133,42 @@ int main(int argc, char** argv) { } return 0; }; + // ---- the resident RAM mode (--resident-experts / --resident-cpu-experts): the experts the GPU cache does not + // hold are copied from experts.bin into RAM once, so no decode or prompt step reads the file (the plain mmap + // mode reads them through the OS file cache, which a small-RAM PC keeps giving back to the SSD). Built here, + // after the prompt path's lend plan is known: the slots it may lend (the cache's last ones) have their experts + // streamed during a prompt and copied back after it, so those are kept in RAM too as far as RAM allows. The + // bytes are the file's bytes and the placement is the same, so the answers are the plain mmap mode's; the + // share-of-pinned figure above (which sizes the prompt path) is left as the mmap mode's for the same reason. + if (o.resident_cpu_experts) { + int64_t lend_from = -1; + if (o.prefill_chunk > 0 && !o.no_prefill_borrow && d_res != nullptr && xcache.slots() > 0) { + int64_t chunk = o.prefill_chunk; + 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)) { + 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()); + return 1; + } + std::fprintf(stderr, "strata generate: resident RAM mode: %.2f GiB of experts in RAM (%s), %lld in the GPU " + "cache; adaptive swaps %s\n", + (double) src.resident_bytes() / 1073741824.0, + src.complement_pinned() ? "page-locked" : src.locked_bytes() > 0 ? "locked" : "pageable", + (long long) xcache.resident(), + o.adapt_every > 0 && o.adapt_swaps > 0 ? "exchange them with the GPU cache (no file reads)" + : "off"); + } else if (o.resident_soft) { + std::fprintf(stderr, "strata generate: WARNING: the resident RAM mode does not fit (%s); the experts the " + "GPU does not hold are read from the model folder through the OS file cache " + "(--mmap-experts), which is slower when the RAM cannot keep them\n", err.c_str()); + } else { + std::fprintf(stderr, "strata generate: CPU expert residency: %s\n", err.c_str()); + return 1; + } + } if (o.serve) { if (o.spec < 2 || o.mtp.empty() || o.prefill_chunk <= 0 || (graph_hits && (thits.d_res == nullptr || host_res.empty()))) { @@ -3398,6 +3484,7 @@ int main(int argc, char** argv) { else if (cudaEventQuery(st->adapt_ev) != cudaSuccess) return; } for (auto& st : stages) st->adapt_live = false; + src.commit_exchanges(); // the resident RAM mode: the evicted experts take their places in RAM for (const auto& [i, slot] : pending) host_res[(size_t) i] = slot; pending.clear(); res_upload(); @@ -3429,6 +3516,7 @@ 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; bool main_live = false; for (const Swap& s : swaps) { const size_t in = (size_t) s.layer * g.n_expert + s.in, out = (size_t) s.layer * g.n_expert + s.out; @@ -3548,7 +3636,8 @@ int main(int argc, char** argv) { ? ss.qsa_states[0].n_slots * 4 : 0), (long long) xcache.slots(), (long long) (xcache.bytes() >> 20), o.spec, o.mtp_max_t, o.suffix_draft, (long long) (free_b >> 20), cvec_summary.c_str(), - (long long) (strata::kernels::cpu::expert_layout().total >> 20), pool.workers(), o.pcie_frac, + (long long) ((o.mmap_experts ? src.resident_bytes() : strata::kernels::cpu::expert_layout().total) >> 20), + pool.workers(), o.pcie_frac, o.spec_min_p); } // issue #29: a request whose heartbeat (tokens, prompt chunks, verify windows) stops for this long is stuck on @@ -4332,6 +4421,13 @@ int main(int argc, char** argv) { 100.0 * (double) req_hits / (double) req_look, (long long) req_hits, (long long) req_look); } + // the resident RAM mode, cumulative: experts read from experts.bin since the copy was made (what the plain + // mmap mode reads through the OS file cache, from the SSD when the RAM could not keep it) + if (src.complement_ready()) + std::fprintf(stderr, "strata serve: resident RAM: %.2f GiB of experts in RAM, %lld exchanged with the " + "VRAM tier, %lld blob reads from the file\n", + (double) src.resident_bytes() / 1073741824.0, (long long) src.exchanges(), + (long long) src.file_reads()); // STRATA_SPLIT_TIMING: where each verify stage's host time went, cumulative per window since the start // (waiting for its GPU to ring a layer, the CPU pool and plan per layer, staging the window) if (static const bool st_timing = std::getenv("STRATA_SPLIT_TIMING") != nullptr; st_timing) @@ -4761,6 +4857,7 @@ int main(int argc, char** argv) { if (pending.empty()) return; if (wait) cudaEventSynchronize(adapt_ev); else if (cudaEventQuery(adapt_ev) != cudaSuccess) return; + src.commit_exchanges(); // the resident RAM mode: the evicted experts take their places in RAM for (const auto& [i, slot] : pending) host_res[(size_t) i] = slot; pending.clear(); if (d_res != nullptr) @@ -4796,6 +4893,10 @@ 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)) { + std::fprintf(stderr, "strata generate: an adaptive refill failed (copying evicted experts back)\n"); + return false; + } for (const Swap& s : swaps) { const size_t in = (size_t) s.layer * g.n_expert + s.in, out = (size_t) s.layer * g.n_expert + s.out; const int32_t slot = host_res[out]; @@ -4975,6 +5076,10 @@ int main(int argc, char** argv) { if (rounds > 0 && !drive.d.usage.empty()) std::printf("%-24s %lld experts swapped into the VRAM tier (every %d rounds, %.3f ms/round)\n", "adaptive tier", (long long) swaps_total, o.adapt_every, ms_adapt / rounds); + if (src.complement_ready()) + std::printf("%-24s %.2f GiB of experts in RAM, %lld exchanged with the VRAM tier, %lld blob reads from " + "the file\n", "resident RAM", (double) src.resident_bytes() / 1073741824.0, + (long long) src.exchanges(), (long long) src.file_reads()); if (rounds > 0 && drive.d.pcie_num > 0) std::printf("%-24s %.2f distinct experts per layer read over PCIe (share %d/256 of the misses)\n", "pcie experts", (double) (drive.d.pcie_experts - pcie0) / (double) (rounds * g.n_layers), diff --git a/tests/core/file_expert_source_test.cpp b/tests/core/file_expert_source_test.cpp index be0f0912..e86acc16 100644 --- a/tests/core/file_expert_source_test.cpp +++ b/tests/core/file_expert_source_test.cpp @@ -7,6 +7,7 @@ #include "ggml.h" #endif +#include #include #include #include @@ -206,6 +207,52 @@ void test_complement_plan() { require(!make_cache_complement_plan(2, 3, {0, 5}, {}, {}, offsets, bytes, error), "zero-size layer accepted"); } +void test_resident_lend_region() { + using namespace strata::core::detail; + // four slots (sizes 5, 3, 3, 5); the experts no slot holds take 10 bytes + const std::vector slots{5, 3, 3, 5}; + require(choose_resident_keep_from(slots, 10, 9, 1) == -1, "a base larger than the budget was accepted"); + require(choose_resident_keep_from(slots, 10, 10, 1) == 4, "no room: the lend region must stay on the file"); + require(choose_resident_keep_from(slots, 10, 15, 1) == 3, "the last slot fits and must be kept first"); + require(choose_resident_keep_from(slots, 10, 17, 1) == 3, "a slot that does not fit ends the lend region's walk"); + require(choose_resident_keep_from(slots, 10, 18, 1) == 2, "two slots fit"); + require(choose_resident_keep_from(slots, 10, 100, 1) == 1, "the walk must stop at the lend region's first slot"); + require(choose_resident_keep_from(slots, 10, 100, -1) == 4, "no lend region kept slots in RAM"); + require(choose_resident_keep_from(slots, 10, 100, 9) == 4, "an out-of-range lend region kept slots in RAM"); + require(choose_resident_keep_from({}, 0, 0, 0) == 0, "an empty cache"); +} + +void test_resident_exchange() { + using namespace strata::core; + using namespace strata::core::detail; + // 2 layers x 3 experts; the GPU holds (0,1) and (1,2): the compact copy holds the other four + std::vector offsets; + uint64_t bytes = 0; + std::string error; + require(make_cache_complement_plan(2, 3, {3, 5}, {{0, 1}, {1, 2}}, {}, offsets, bytes, error), error); + const std::vector before = offsets; + // (1,0) moves into the GPU, (1,2) leaves it: (1,2) takes (1,0)'s bytes' place + require(exchange_cache_complement(offsets, 3, 5), "a valid exchange was refused"); + require(offsets[5] == before[3] && offsets[3] == kNoCacheComplement, "the exchange did not move the place"); + for (size_t i : {0u, 1u, 2u, 4u}) require(offsets[i] == before[i], "an exchange touched another expert"); + // the copy's size and its set of places are unchanged + std::vector a, b; + for (uint64_t o : before) if (o != kNoCacheComplement) a.push_back(o); + for (uint64_t o : offsets) if (o != kNoCacheComplement) b.push_back(o); + std::sort(a.begin(), a.end()); + std::sort(b.begin(), b.end()); + require(a == b, "an exchange changed the compact copy's places"); + const std::vector after = offsets; + require(!exchange_cache_complement(offsets, 3, 0), "an `in` the copy does not hold was accepted"); + require(!exchange_cache_complement(offsets, 0, 2), "an `out` the copy holds already was accepted"); + require(!exchange_cache_complement(offsets, 0, 0), "a self-exchange was accepted"); + require(!exchange_cache_complement(offsets, 0, 6), "an out-of-range `out` was accepted"); + require(offsets == after, "a refused exchange changed the offsets"); + // and back: the copy is again what the plan makes for the original placement + require(exchange_cache_complement(offsets, 5, 3), "the reverse exchange was refused"); + require(offsets == before, "exchanging back did not restore the plan"); +} + void test_cgroup_memory_budget() { using namespace strata::core::detail; constexpr uint64_t GiB = 1ull << 30; @@ -246,6 +293,8 @@ void test_cgroup_memory_budget() { int main() { try { test_complement_plan(); + test_resident_lend_region(); + test_resident_exchange(); test_cgroup_memory_budget(); test_canonical_layout(); #if defined(STRATA_NATIVE_EXPERTS)