diff --git a/docs/VRAM_ELASTIC.md b/docs/VRAM_ELASTIC.md index 66fd2b830..b7442d7ef 100644 --- a/docs/VRAM_ELASTIC.md +++ b/docs/VRAM_ELASTIC.md @@ -19,9 +19,34 @@ a `--serve` engine, with helper caches on other GPUs (`--peer-device`, an expert (`--vram-elastic is off: the driver or this GPU offers no virtual memory management`) **(code; not run on such a driver)**. Without the flag nothing changes: the same answers as without it. Across a `--layer-split` each card keeps its own segmented cache, so by default one call keeps the reserve on every card at once; pass a `"device"` to free just that CUDA device and leave the others with their full expert cache. -This page is about the Strata project's engine (Qwen3.8). strata-poly, the engine of the models PolyStrata adds, has no flag for -it: its expert cache takes `POST /v1/vram` as it is, and the server does not pass the config's `"vram_elastic"` on to -it (strata-poly ends at an option it does not know). A reserve of 0 leaves strata-poly its smallest one, 256 MiB. +This page is mostly about the Strata project's engine (Qwen3.8). strata-poly, the engine of the models PolyStrata adds +(Inkling 2 Mini, Qwen3.6 on strata-poly, GLM, ...), is covered in the next section. + +## strata-poly (`"vram_elastic": true`, NVIDIA and AMD) + +strata-poly's expert cache is already in VMM pieces of 64 MiB under one address range wherever the card has virtual +memory management (NVIDIA and AMD), and it already resizes at each request's start: it gives back what another program +took when less than half its reserve is free, and takes free VRAM again (`mind_vram`). `POST /v1/vram` fills it again +from nothing at the new size. Between requests nothing watches the free VRAM. + +With `"vram_elastic": true` the server passes `--vram-elastic` to strata-poly (no segment size: its pieces stay 64 MiB), +and **(code; measured in the PR)**: + +- the cache keeps its **whole** reserve free (`--vram-reserve-mib`, or the engine's default). When another program took a + quarter of it (64 MiB at least), the cache gives at least that much back in whole pieces; when a piece and 128 MiB + more are free beyond the reserve it takes them again, the experts it gave up first, so the cache after a shrink and a + grow holds the experts it held before; +- this also happens **while the engine is idle**, every 2 s (`--vram-elastic-watch-ms N`, 100 at least; 0: only at a + request's start. `STRATA_VRAM_WATCH_MS` and `STRATA_VRAM_WATCH=0` do the same from the environment), never inside a request or while batch slots are writing. A freeze (`STRATA_FREEZE_EXPERTS`) gives + way to it as it does to `POST /v1/vram`. The log says `strata-poly: idle: the expert cache A -> B experts ...`; +- `POST /v1/vram` resizes the same way, a piece at a time, instead of filling the cache again; +- on AMD under WSL2 (librocdxg) the kept pieces are not unmapped and mapped again for each shrink: there the VRAM of a + released piece comes back at the release. On native amdgpu that is checked once, at the first shrink + (`STRATA_VMM_READDRESS=0|1` sets it). Under WSL2 no piece is asked for unless its bytes and 256 MiB more are free. + +It needs VMM and is off with `--vram-pool`; the engine says `--vram-elastic is off: ...` then. Without the flag nothing +changes. On an AMD card that drives a Linux desktop the server's note recommends this rather than a fixed +`--vram-reserve-mib 3072`, which costs experts all the time. ## The request diff --git a/engine/src/poly/engine.cpp b/engine/src/poly/engine.cpp index 35005b37e..4f99bb640 100644 --- a/engine/src/poly/engine.cpp +++ b/engine/src/poly/engine.cpp @@ -1027,6 +1027,15 @@ static bool vmm_equal_pieces() { return on; } +// WSL2's GPU (librocdxg): /dev/dxg and no /dev/kfd. Read once. +static bool wsl_dxg() { + static const bool on = [] { + std::error_code ec; + return std::filesystem::exists("/dev/dxg", ec) && !std::filesystem::exists("/dev/kfd", ec); + }(); + return on; +} + // The unit such pieces are made of, 2 MiB like the pool's handles: vmm_reserve() reserves a whole number of them. static size_t vmm_unit(size_t grain) { return up_to(size_t(2) << 20, grain); } @@ -1192,7 +1201,17 @@ void Engine::vmm_map(Mapped& m, size_t bytes, size_t piece, const char* what) { } else if (pool_on_ && pool_claimed_) { throw std::runtime_error("no VRAM for " + std::string(what) + " (" + std::to_string(n >> 20) + " MiB more)"); - } else if (cuMemCreate(&h, n, &prop, 0) != CUDA_SUCCESS) { + } else if ( +#if defined(STRATA_USE_HIP) + // --vram-elastic: under WSL2 an allocation past the card's VRAM hangs instead of failing, so a + // piece of the expert cache is asked for only with its bytes and 256 MiB more free (hipMemGetInfo + // is right there). The other maps keep their own margins (take_prompt(), cover()) + (elastic() && &m == &arena_ && wsl_dxg() && [&] { + size_t f = 0, t = 0; + return cudaMemGetInfo(&f, &t) == cudaSuccess && f < n + (size_t(256) << 20); + }()) || +#endif + cuMemCreate(&h, n, &prop, 0) != CUDA_SUCCESS) { throw std::runtime_error("no VRAM for " + std::string(what) + " (" + std::to_string(n >> 20) + " MiB more)"); } @@ -1228,6 +1247,21 @@ void Engine::vmm_map(Mapped& m, size_t bytes, size_t piece, const char* what) { // Gives back the pieces of m that lie past its first `bytes`. The card must be done with them. void Engine::vmm_unmap(Mapped& m, size_t bytes) { const size_t had = m.mapped; +#ifdef STRATA_VMM_RELEASE_WITH_ADDRESSES + // --vram-elastic: whether released VRAM comes back without its addresses (below), decided once from an expert-cache + // shrink of a whole piece or more. -1 undecided, 0 it does, 1 it does not + static int readdress = [] { + const char* v = std::getenv("STRATA_VMM_READDRESS"); + if (v && v[0]) return v[0] == '0' ? 0 : 1; + return wsl_dxg() ? 0 : -1; + }(); + size_t free0 = 0; + const bool measure = elastic() && readdress < 0 && &m == &arena_ && m.mapped >= bytes + kArenaPiece; + if (measure) { + size_t t = 0; + (void) cudaMemGetInfo(&free0, &t); + } +#endif while (!m.pieces.empty() && m.mapped - m.pieces.back().second >= bytes) { const auto [h, n] = m.pieces.back(); m.mapped -= n; @@ -1244,6 +1278,26 @@ void Engine::vmm_unmap(Mapped& m, size_t bytes) { // has left, the slots, the recorded launches and m point at VRAM that is not there: a step that fails from // there on ends the engine (the server starts it again for the next request) rather than reading that VRAM. if (m.mapped == had || !m.base) return; + // --vram-elastic: whether this driver keeps released VRAM while the addresses stay is read once, at the first + // expert-cache shrink of a piece or more (undecided until then: the cycle below, as without the flag): librocdxg (WSL2) gives it back at the release (an RX 9060 XT's 64 of 64 MiB, ROCm + // 7.2.4), so there the kept pieces are not unmapped and mapped again for every shrink. Never under WSL2 (/dev/dxg + // without /dev/kfd); STRATA_VMM_READDRESS=0|1 sets it. + if (elastic()) { + if (measure) { + const size_t want = free0 + (had - m.mapped) / 8 * 7; + size_t f = 0, t = 0; + for (int i = 0; i < 100; ++i) { + (void) cudaMemGetInfo(&f, &t); + if (f >= want) break; + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } + readdress = f >= want ? 0 : 1; + std::fprintf(stderr, "strata-poly: --vram-elastic: released VRAM %s\n", + readdress ? "comes back only with its addresses: the kept pieces are mapped again for each shrink" + : "comes back at the release"); + } + if (readdress == 0) return; + } const auto must = [](CUresult r, const char* what) { if (r == CUDA_SUCCESS) return; const char* s = nullptr; @@ -1796,10 +1850,12 @@ void Engine::shrink_cache(size_t bytes) { ck(cudaMemcpyAsync(to, from, L.slot_bytes, cudaMemcpyDeviceToDevice, cs(st_)), "the expert cache"); from = to; to = nullptr; + if (give_back_) gave_back_[(size_t) l[k].il * ne + (size_t) l[k].e] = 1; ++k; } else { mirror_keep(x.il, x.e, from); from = nullptr; + if (give_back_) gave_back_[(size_t) x.il * ne + (size_t) x.e] = 1; } --cached_; } @@ -1807,6 +1863,14 @@ void Engine::shrink_cache(size_t bytes) { vmm_unmap(arena_, cut); if (cut > kTail) zero_vram(exp_ + end, kTail); exp_at_ = std::min(exp_at_, end); + if (give_back_) { // --vram-elastic: a slot that crossed `end` left, so the room from the last kept slot is free again + size_t top = 0; + for (const Layer& L : layers_) + if (L.trade >= 0) + for (const uint8_t* q : L.slot) + if (q) top = std::max(top, (size_t) (q - exp_) + L.slot_bytes); + exp_at_ = std::min(exp_at_, top); + } staged_il_ = -1; } @@ -2611,6 +2675,7 @@ void Engine::resize_card_cache(int mib) { std::fill(coming_.begin(), coming_.end(), (uint8_t) 0); for (Layer& L : layers_) std::fill(L.slot.begin(), L.slot.end(), nullptr); refill_.clear(); + gave_back_.clear(); staged_il_ = -1; cached_ = 0; exp_at_ = 0; @@ -2644,6 +2709,67 @@ bool Engine::mind_vram() { return changed; } +// --vram-elastic: the whole reserve stays free. Between requests (and idle) another program that took a quarter of it +// (64 MiB at least) gets at least that back, in whole pieces; a piece and 128 MiB more free and the cache takes them +// again, the experts it gave up first - the two bands never meet, so a cache does not go up and down by itself. The +// VRAM command (`exact`) asks for its number: any shortfall is given back, a piece or more free is taken. An idle grow +// takes 1 GiB at most a time (it reads the experts from the files), so a line that comes waits that long at most. +bool Engine::elastic_card(int64_t free, bool exact) { + const int64_t keep = reserve_mib_; + if (exact ? free < keep : free + std::max(64, keep / 4) < keep) { + if (gave_back_.empty()) gave_back_.assign((size_t) layers_.size() * (size_t) n_expert_, 0); + give_back_ = true; + shrink_cache(size_t(keep - free) << 20); + give_back_ = false; + held_is_budget(); + return true; + } + const int64_t piece = (int64_t) (kArenaPiece >> 20); + if (free < keep + piece + (exact ? 0 : 128)) return false; + const size_t want = size_t(free - keep) << 20; + return grow_cache(exact || !idle_ ? want : std::min(want, size_t(1) << 30)) > 0; +} + +bool Engine::idle_vram(bool served) { + // before the first request nothing is recorded (mind_card_vram()'s grace, which a frozen request start leaves at 0) + if (!elastic() || !served) return false; + for (Engine* e = this; e; e = e->next_.get()) + if (e->minds_ == 0) e->minds_ = 1; + const bool frozen = freeze_experts_asked_ && expert_cap_ < 0; + if (frozen) unfreeze_experts(); + bool changed = false; + idle_ = true; + try { + changed = mind_vram(); + } catch (...) { + idle_ = false; + if (frozen) refreeze_experts(); + throw; + } + idle_ = false; + if (frozen) refreeze_experts(); + return changed; +} + +void Engine::elastic_resize(int mib) { + for (Engine* e = this; e; e = e->next_.get()) { + if (!e->exp_ || !e->elastic()) { // no cache yet (no room at load), or no VMM on this card: filled anew + e->resize_card_cache(mib); + continue; + } + OnCard here(e->device_, e->split_); + e->opt_.vram_reserve_mib = mib < 0 ? e->asked_reserve_mib_ : mib; + // as fill_expert_cache() sizes it (256 at least), without filling the cache again + size_t free_b = 0, total_b = 0; + ck(cudaMemGetInfo(&free_b, &total_b), "cudaMemGetInfo"); + e->reserve_mib_ = e->opt_.vram_reserve_mib >= 0 ? std::max(e->opt_.vram_reserve_mib, 256) + : default_reserve_mib(total_b, e->ram_tight_); + if (e->minds_ == 0) e->minds_ = 1; // the operator's call: no first-request grace + if (e->freeze_experts_) continue; + e->elastic_card((int64_t) (free_b >> 20), true); + } +} + bool Engine::mind_card_vram() { #if defined(STRATA_GPU_METAL) if (opt_.metal_balanced) return metal_mind_memory(); @@ -2670,6 +2796,7 @@ bool Engine::mind_card_vram() { return true; } if (minds_++ == 0) return false; // nothing is recorded before the first request + if (elastic()) return elastic_card(free, false); const int64_t keep = opt_.vram_reserve_mib >= 0 || ram_tight_ ? reserve_mib_ : std::max(reserve_mib_ / 2, 128); if (free < keep / 2) { shrink_cache(size_t(keep - free) << 20); @@ -2840,6 +2967,7 @@ int Engine::grow_cache(size_t bytes, bool later) { struct Cand { int il, e; double value; + bool back = false; ///< --vram-elastic: an elastic shrink took it out (gave_back_): it comes back first }; std::vector cands; for (int il = 0; il < (int) layers_.size(); ++il) { @@ -2849,7 +2977,7 @@ int Engine::grow_cache(size_t bytes, bool later) { const size_t i = (size_t) il * n_expert_ + e; if (L.slot[(size_t) e] || (!coming_.empty() && coming_[i])) continue; const double used = (double) ((prior_.empty() ? 0 : prior_[i]) + use_[i]); - cands.push_back({il, e, used / (double) L.slot_bytes}); + cands.push_back({il, e, used / (double) L.slot_bytes, !gave_back_.empty() && gave_back_[i] != 0}); } } if (cands.empty()) return 0; @@ -2859,8 +2987,9 @@ int Engine::grow_cache(size_t bytes, bool later) { } if (arena_.mapped < exp_at_ + kTail) return 0; zero_vram(exp_ + exp_at_, arena_.mapped - exp_at_); // the new slots' tails - std::stable_sort(cands.begin(), cands.end(), - [](const Cand& a, const Cand& b) { return a.value != b.value ? a.value > b.value : a.e < b.e; }); + std::stable_sort(cands.begin(), cands.end(), [](const Cand& a, const Cand& b) { + return a.back != b.back ? a.back : a.value != b.value ? a.value > b.value : a.e < b.e; + }); std::vector taken; size_t room = arena_.mapped - kTail - exp_at_; for (const Cand& c : cands) { @@ -2892,6 +3021,8 @@ int Engine::grow_cache(size_t bytes, bool later) { L.slot[e] = s; ++cached_; } + if (!gave_back_.empty()) + for (const Cand& c : taken) gave_back_[(size_t) c.il * n_expert_ + c.e] = 0; staged_il_ = -1; held_is_budget(); return (int) taken.size(); @@ -2913,6 +3044,7 @@ void Engine::fill_now() { } L.slot[e] = r.slot; coming_[(size_t) r.il * n_expert_ + e] = 0; + if (!gave_back_.empty()) gave_back_[(size_t) r.il * n_expert_ + e] = 0; ++cached_; } refill_.clear(); @@ -3057,6 +3189,7 @@ void Engine::follow(int written) { ck(arrived, "expert upload"); layers_[(size_t) s.il].slot[(size_t) s.e] = s.slot; coming_[(size_t) s.il * ne + (size_t) s.e] = 0; + if (!gave_back_.empty()) gave_back_[(size_t) s.il * ne + (size_t) s.e] = 0; if (s.mirror && !(s.adds && refills_mirror())) mirror_give(s.il, s.e); if (s.spare) mirror_of_[(size_t) s.out] = s.spare; s.mirror = nullptr; diff --git a/engine/src/poly/engine.hpp b/engine/src/poly/engine.hpp index ab0e27454..daad0edc9 100644 --- a/engine/src/poly/engine.hpp +++ b/engine/src/poly/engine.hpp @@ -66,6 +66,11 @@ struct Options { int max_context = 8192; int threads = 0; ///< 0: the CPUs this process may use int vram_reserve_mib = -1; ///< left free after the expert cache is filled; below 0: by the card's size + /// --vram-elastic (opt-in): the expert cache keeps its whole reserve free while it serves - it gives VRAM back to + /// another program that takes some (between requests, and while the engine waits for one: main.cpp's idle watch) + /// and takes it again when it is free, the experts it gave up first; the VRAM command resizes it the same way + bool vram_elastic = false; + int vram_watch_ms = -1; ///< --vram-elastic-watch-ms: the idle watch's period; 0 off; below 0: STRATA_VRAM_WATCH_MS or 2000 bool vram_pool = false; ///< one pool of VRAM claimed at load, kept for the whole run: the expert cache and the ///< attention caches trade pieces of it and nothing is given back to the card; the ///< reserve above is then the margin left outside it (needs VMM) @@ -435,6 +440,15 @@ class Engine { /// Between requests: the cache gives up VRAM when little is free, and takes VRAM that came free (see the /// definition for how much stays free). True when it changed. bool mind_vram(); + /// --vram-elastic: mind_vram() while the engine waits for its next line (between requests, no batch slot writing). + /// A freeze (STRATA_FREEZE_EXPERTS) gives way to it as to the VRAM command. True when the cache changed. + bool idle_vram(bool served); + /// --vram-elastic: the VRAM command - keep `mib` free (below 0: the reserve load() was given), the cache shrunk or + /// grown a piece at a time rather than filled again. + void elastic_resize(int mib); + bool elastic() const { return opt_.vram_elastic && vmm_ && !pool_on_; } + bool elastic_asked() const { return opt_.vram_elastic; } + int vram_watch_ms() const { return opt_.vram_watch_ms; } /// At a request's start, the engine at the furthest point of its `end` tokens it could come back to: the /// attention caches give back the rows past `end` that the request before did not reach either. One long /// request leaves them grown, and the expert cache would stay that much smaller for every request after it. @@ -1102,6 +1116,12 @@ class Engine { int reserve_mib_ = 0; ///< what the cache was sized to leave free bool ram_tight_ = false; ///< the machine's RAM is within 5 GiB of the model's files (fill_expert_cache()) int minds_ = 0; ///< mind_vram()'s calls + /// --vram-elastic: [layer * n_expert + expert] set for each expert an elastic shrink took out of the cache, which a + /// grow brings back first (the cache before the shrink and after the grow holds the same experts); empty until one + std::vector gave_back_; + bool give_back_ = false; ///< shrink_cache() is an elastic one: it notes what it takes out (gave_back_) + bool idle_ = false; ///< idle_vram() is running (its grows are capped) + bool elastic_card(int64_t free_mib, bool exact); ///< --vram-elastic: mind_card_vram()'s and the VRAM command's step int full_cached_ = 0; ///< the cache as load() filled it: its experts and their bytes size_t full_bytes_ = 0; float* scratch_ = nullptr; diff --git a/engine/src/poly/main.cpp b/engine/src/poly/main.cpp index e7eff913c..b1d99d5e4 100644 --- a/engine/src/poly/main.cpp +++ b/engine/src/poly/main.cpp @@ -1109,10 +1109,44 @@ int serve(Session& ss) { piece_t0 = Clock::now(); return true; }; + // --vram-elastic: while the engine waits for a line with no batch slot writing, every --vram-elastic-watch-ms + // (STRATA_VRAM_WATCH_MS; default 2000) the expert cache gives VRAM back to a program that took some, or takes it again (Engine::idle_vram()). + // Never inside a request. STRATA_VRAM_WATCH=0: only at a request's start, as without the watch. + const int watch_ms = [&] { + const char* v = std::getenv("STRATA_VRAM_WATCH"); + if (!engine.elastic() || (v && v[0] == '0')) return 0; + const char* m = std::getenv("STRATA_VRAM_WATCH_MS"); + const int ms = engine.vram_watch_ms() >= 0 ? engine.vram_watch_ms() : m && m[0] ? std::atoi(m) : 2000; + return ms <= 0 ? 0 : std::max(ms, 100); + }(); + if (watch_ms > 0) + std::fprintf(stderr, "strata-poly: --vram-elastic: while idle the expert cache gives VRAM to other programs and " + "takes it back (checked every %d ms)\n", watch_ms); + else if (engine.elastic_asked() && !engine.elastic()) + std::fprintf(stderr, "strata-poly: --vram-elastic is off: it needs VMM on this card and no --vram-pool\n"); + bool served = false; // a request has run (the idle watch starts after the first) for (;;) { std::string line; if (!writing()) { - line = lines.pop(); + if (watch_ms > 0) { + while (!lines.pop_for(line, watch_ms)) { + const int had = engine.cached_experts(); + const Clock::time_point t0 = Clock::now(); + bool changed = false; + try { + changed = engine.idle_vram(served); + } catch (const std::exception& e) { // as a failed resize at a request's start: the engine ends + std::fprintf(stderr, "strata-poly: the idle VRAM watch failed: %s; the engine ends\n", e.what()); + return 1; + } + if (changed) + std::fprintf(stderr, "strata-poly: idle: the expert cache %d -> %d experts (%.2f GiB) for the VRAM " + "free now, %lld MiB left, in %.0f ms\n", had, engine.cached_experts(), + engine.cached_gib(), (long long) engine.vram_free_mib(), ms_since(t0)); + } + } else { + line = lines.pop(); + } } else if (!lines.try_pop(line) && !(co_due > 0 && lines.pop_for(line, kCoWaitMs))) { co_due = 0; // (they stopped coming: the slots go on) if (!step()) return 1; @@ -1120,6 +1154,7 @@ int serve(Session& ss) { } if (line == "QUIT") break; if (line.empty()) continue; + served = served || line.rfind("GEN", 0) == 0 || line.rfind("BGEN", 0) == 0; // BSTOP : the slot ends with its next token. BYIELD: a long read gives way to a shorter one in the // other engine only; this one reads it to its end. if (line.rfind("BSTOP ", 0) == 0) { @@ -1199,7 +1234,8 @@ int serve(Session& ss) { // The operator's resize is the one thing a freeze gives way to (STRATA_FREEZE_EXPERTS): // the cache it leaves is what every request after reads, and stays frozen again. engine.unfreeze_experts(); - engine.resize_cache((int) reserve); + if (engine.elastic()) engine.elastic_resize((int) reserve); // a piece at a time, not filled again + else engine.resize_cache((int) reserve); engine.refreeze_experts(); const long long free_mib = (long long) engine.vram_free_mib(); std::fprintf(stderr, "strata-poly: VRAM %d MiB kept free: the expert cache %d -> %d of %d experts " @@ -1642,6 +1678,12 @@ void usage() { " thirty-second of the card, 256 to 768, or a sixteenth, 512 to 1024,\n" " when the PC's free RAM is within 4 GiB of the model's files, and then\n" " kept whole; else half of it after the first request)\n" + " --vram-elastic keep the whole reserve free while serving: the expert cache gives VRAM back\n" + " when another program takes some (also while idle, every 2 s) and takes it\n" + " again when it is free, the experts it gave up first (needs VMM; not with\n" + " --vram-pool)\n" + " --vram-elastic-watch-ms N the idle check's period in ms (default 2000, 100 at least; 0: only at a\n" + " request's start)\n" " --vram-pool claim the card's VRAM once at load (what is free but for the reserve above,\n" " which is then the margin left outside), keep it for the whole run and move\n" " it between the expert cache and the attention caches as the context grows\n" @@ -1859,6 +1901,8 @@ int main(int argc, char** argv) { else if (a == "--threads") o.threads = std::atoi(val()); else if (a == "--vram-reserve-mib") o.vram_reserve_mib = std::atoi(val()); else if (a == "--vram-pool") o.vram_pool = true; + else if (a == "--vram-elastic") o.vram_elastic = true; + else if (a == "--vram-elastic-watch-ms") o.vram_watch_ms = std::max(0, std::atoi(val())); else if (a == "--expert-profile") o.profile = val(); else if (a == "--pinned-session") pinned = val(); else if (a == "--no-gpu-experts") o.gpu_experts = false; diff --git a/terminal/data/settings-register.json b/terminal/data/settings-register.json index 1b115a170..fddca3f8a 100644 --- a/terminal/data/settings-register.json +++ b/terminal/data/settings-register.json @@ -51812,6 +51812,41 @@ "retire_after": "", "retired_in": "" }, + { + "name": "STRATA_VMM_READDRESS", + "backends": [ + "cuda-hip" + ], + "reads": [ + { + "file": "engine/src/poly/engine.cpp", + "line": 1254, + "backend": "cuda-hip", + "fn": "getenv" + } + ], + "parse": "flag", + "default_state": null, + "code_default": null, + "engine_sets": [], + "engine_defaults": [], + "launch_files": [], + "launch_sets": [], + "launch_reads": [], + "doc_mentions": [ + "docs/VRAM_ELASTIC.md:45" + ], + "first_commit": null, + "first_date": null, + "since": null, + "last_commit": null, + "last_date": null, + "status": "rollback", + "owner": "", + "note": "HIP on Linux: whether VRAM given back keeps the process's addresses. With --vram-elastic: 1 keeps the unmap-and-map cycle of the kept pieces after a release, 0 skips it. Unset: skipped under WSL2 (librocdxg gives released VRAM back at once), decided at the first shrink on native amdgpu. Set it only to override that.", + "retire_after": "", + "retired_in": "" + }, { "name": "STRATA_VMM_SETTLE", "backends": [ @@ -51951,6 +51986,76 @@ "retire_after": "", "retired_in": "" }, + { + "name": "STRATA_VRAM_WATCH", + "backends": [ + "cuda-hip" + ], + "reads": [ + { + "file": "engine/src/poly/main.cpp", + "line": 1116, + "backend": "cuda-hip", + "fn": "getenv" + } + ], + "parse": "flag", + "default_state": null, + "code_default": null, + "engine_sets": [], + "engine_defaults": [], + "launch_files": [], + "launch_sets": [], + "launch_reads": [], + "doc_mentions": [ + "docs/VRAM_ELASTIC.md:40" + ], + "first_commit": "faa1456a12", + "first_date": "2026-11-24", + "since": null, + "last_commit": "faa1456a12", + "last_date": "2026-11-24", + "status": "rollback", + "owner": "", + "note": "--vram-elastic: 0 turns the idle watch off, the cache then resizes only at a request's start. On unless =0.", + "retire_after": "", + "retired_in": "" + }, + { + "name": "STRATA_VRAM_WATCH_MS", + "backends": [ + "cuda-hip" + ], + "reads": [ + { + "file": "engine/src/poly/main.cpp", + "line": 1118, + "backend": "cuda-hip", + "fn": "getenv" + } + ], + "parse": "int", + "default_state": null, + "code_default": "2000", + "engine_sets": [], + "engine_defaults": [], + "launch_files": [], + "launch_sets": [], + "launch_reads": [], + "doc_mentions": [ + "docs/VRAM_ELASTIC.md:40" + ], + "first_commit": "faa1456a12", + "first_date": "2026-11-24", + "since": null, + "last_commit": "faa1456a12", + "last_date": "2026-11-24", + "status": "opt-in", + "owner": "", + "note": "--vram-elastic: the idle watch's period in ms (default 2000, 100 at least, 0 off); --vram-elastic-watch-ms N does the same and wins.", + "retire_after": "", + "retired_in": "" + }, { "name": "STRATA_W4A8_CFG", "backends": [ diff --git a/terminal/serve/server.py b/terminal/serve/server.py index 698f2368f..1b1d5befb 100644 --- a/terminal/serve/server.py +++ b/terminal/serve/server.py @@ -3812,13 +3812,13 @@ def engine_args(cfg: dict, exe: str | None = None, *, announce: bool = True) -> if layer_split_of(cfg) and cfg.get("split_skip_if_fits") and "--split-skip-if-fits" not in args: args.append("--split-skip-if-fits") # #533 (opt-in): "vram_elastic": true - the expert cache in segments, so POST /v1/vram can give VRAM back to other - # programs and take it back; "vram_segment_mib" sets the segment size (the engine's default: 512). strata-poly - # has neither option and ends at one it does not know: its cache is resized by VRAM as it is (vram_elastic=1 in - # its INFO line) - if cfg.get("vram_elastic") is True and "--vram-elastic" not in args and not poly: + # programs and take it back; "vram_segment_mib" sets the segment size (the engine's default: 512). strata-poly's + # cache is in VMM pieces already (64 MiB): its --vram-elastic keeps the whole reserve free while it serves, idle + # too, and it has no segment size (it ends at an option it does not know) + if cfg.get("vram_elastic") is True and "--vram-elastic" not in args: args.append("--vram-elastic") seg = cfg.get("vram_segment_mib") - if isinstance(seg, int) and not isinstance(seg, bool) and seg > 0 and "--vram-segment-mib" not in args: + if isinstance(seg, int) and not isinstance(seg, bool) and seg > 0 and "--vram-segment-mib" not in args and not poly: args += ["--vram-segment-mib", str(seg)] args += parallel_args(cfg, args) args += pool_cores_args(cfg, args) @@ -9324,6 +9324,8 @@ def apply_vision_defaults(cfg: dict) -> dict: return cfg cfg["vision"] = {**cfg["vision"], "elastic": True} if VISION_NO_RESERVE_BY_DEFAULT and cfg.get("backend") != "hip" and "vram_elastic" not in cfg: + if poly_engine(cfg): + return cfg # strata-poly: its args as before (its "vram_elastic" is the person's choice) cfg["vram_elastic"] = True # the cache gives the reader its room when a picture comes; nothing is held back before return cfg args = list(cfg.get("args") or []) @@ -9576,8 +9578,11 @@ def start_model(cfg: dict, tok, lazy: bool = False): engine = start_engine_or_fallback(cfg, exe, effort_end, env, lazy, tok, offline=offline, batch_telemetry=batch_telemetry) engine.silence_s = silence # an attribute of its own: restart() keeps it warn_tight_ram(engine.info.get("arena_mib")) + # strata-poly can keep its whole reserve free while it serves (--vram-elastic, the config's "vram_elastic") + poly = poly_engine(cfg) note = desktop_vram_note(cfg.get("backend"), engine.info.get("vram_free_mib"), engine.spawn[1], - linux_desktop()) if not groups and not split else None + linux_desktop(), ("--vram-elastic" in engine.spawn[1]) if poly else None + ) if not groups and not split else None if note: # #560 #516: before --open starts a browser on that card print(note, flush=True) return engine, vision, sampling_defaults, effort_end, groups diff --git a/terminal/serve/server_parts/http_api.py b/terminal/serve/server_parts/http_api.py index da7f55912..709c8af77 100644 --- a/terminal/serve/server_parts/http_api.py +++ b/terminal/serve/server_parts/http_api.py @@ -122,19 +122,28 @@ def linux_desktop(env=None) -> bool: return os.name != "nt" and sys.platform != "darwin" and bool(env.get("WAYLAND_DISPLAY") or env.get("DISPLAY")) -def desktop_vram_note(backend, vram_free_mib, args: list, desktop: bool) -> str: +def desktop_vram_note(backend, vram_free_mib, args: list, desktop: bool, elastic=None) -> str: """#560 #516: on Linux, when the desktop needs VRAM the AMD card does not have, amdgpu moves GPU memory (the expert cache, ~24 GB) to system RAM, which the experts already fill - the OOM killer then ends the compositor. The default reserve (700 MiB) is sized for a card without a desktop. A recommendation, nothing changes: "" when it - does not apply.""" + does not apply. `elastic`: None for an engine without strata-poly's --vram-elastic, else whether it runs with it + (then its cache gives the desktop VRAM back by itself, so the note recommends that, not a fixed reserve).""" if backend != "hip" or not desktop or not isinstance(vram_free_mib, int) or vram_free_mib >= DESKTOP_FREE_MIB: return "" + if elastic is True: + return "" try: reserve = int(args[args.index("--vram-reserve-mib") + 1]) if "--vram-reserve-mib" in args else 700 except (ValueError, IndexError): reserve = 700 if reserve >= DESKTOP_RESERVE_MIB: return "" + if elastic is False: + return (f"[strata] note: {vram_free_mib} MiB of VRAM free with the model loaded. If this AMD card also drives your " + "desktop and the desktop or apps crash after the start (the driver moves the expert cache to RAM and " + 'the OOM killer ends the session), add "vram_elastic": true to this model\'s config: the expert cache ' + "then keeps its reserve free, gives VRAM back when the desktop takes some and takes it again later " + f"(rather than a fixed ./setup.sh --vram-reserve-mib {DESKTOP_RESERVE_MIB}, which costs experts)") return (f"[strata] note: {vram_free_mib} MiB of VRAM free with the model loaded. If this AMD card also drives your " "desktop and the desktop or apps crash after the start (the driver moves the expert cache to RAM and " "the OOM killer ends the session), keep more VRAM free: ./setup.sh --vram-reserve-mib " diff --git a/terminal/serve/test_server.py b/terminal/serve/test_server.py index 392f8a884..6880d17d6 100644 --- a/terminal/serve/test_server.py +++ b/terminal/serve/test_server.py @@ -3391,6 +3391,16 @@ def test_when_it_does_not(self): self.assertEqual(desktop_vram_note("hip", 2994, [], True), "") # room left self.assertEqual(desktop_vram_note("hip", None, [], True), "") # lazy start: no INFO yet self.assertEqual(desktop_vram_note("hip", 900, ["--vram-reserve-mib", "4000"], True), "") # already raised + self.assertEqual(desktop_vram_note("hip", 624, ["--vram-elastic"], True, True), "") # strata-poly gives way itself + + def test_strata_poly_is_pointed_at_elastic(self): + from serve.server import desktop_vram_note + note = desktop_vram_note("hip", 624, ["--kv", "int8"], True, False) # strata-poly without --vram-elastic + self.assertIn("624 MiB of VRAM free", note) + self.assertIn('"vram_elastic": true', note) + self.assertNotIn("GB less", note) + self.assertIn("--vram-reserve-mib 3072", desktop_vram_note("hip", 624, [], True, None)) # the Qwen engines + self.assertEqual(desktop_vram_note(None, 624, [], True, False), "") # NVIDIA: unchanged def test_desktop_detection(self): from serve import server diff --git a/terminal/serve/test_vram.py b/terminal/serve/test_vram.py index 78c9a0567..673bae255 100644 --- a/terminal/serve/test_vram.py +++ b/terminal/serve/test_vram.py @@ -96,9 +96,10 @@ def test_config_key(self): self.assertEqual(engine_args({**cfg, "vram_elastic": True, "vram_segment_mib": 256}), ["--max-context", "8192", "--vram-elastic", "--vram-segment-mib", "256"]) self.assertEqual(engine_args({**cfg, "vram_elastic": "yes"}), ["--max-context", "8192"]) - # strata-poly has no such option and ends at one it does not know: its cache is resized as it is + # strata-poly takes --vram-elastic (its cache is in VMM pieces already) but no segment size poly = {**cfg, "exe": "engine-poly/strata-poly.exe", "vram_elastic": True, "vram_segment_mib": 256} - self.assertEqual(engine_args(poly), ["--max-context", "8192"]) + self.assertEqual(engine_args(poly), ["--max-context", "8192", "--vram-elastic"]) + self.assertEqual(engine_args({**poly, "vram_elastic": False}), ["--max-context", "8192"]) class Route(unittest.TestCase):