diff --git a/docs/BACKENDS.md b/docs/BACKENDS.md index ac8b91522..ba6a78689 100644 --- a/docs/BACKENDS.md +++ b/docs/BACKENDS.md @@ -2229,7 +2229,9 @@ thread's lines how much more it locked later. The engine makes no mirror on an AMD card or a Mac, with the layers split over cards, with `STRATA_POLY_MIRROR=0`, on Windows without `--lock-experts` unless `STRATA_POLY_MIRROR=1`, or when the experts outside VRAM and 4 GiB more do -not fit in the free RAM. There it locks the experts' pages in the +not fit in the free RAM. Inkling 2's mirror holds the experts in VRAM too where the RAM keeps max(8 GiB, 20%) free +beside it, unless `--no-full-mirror` ([Inkling](models/inkling.md)). Where none is +made, it locks the experts' pages in the mapped file once the load has read them in, as up to 0.1.45-poly.10 (mlock under Linux, VirtualLock under Windows), and between requests unlocks the ones the cache has taken and locks the ones it has given up. Linux locks no more than `ulimit -l` allows; past it the engine says how much it locked, gives the limit and how to raise it, and the diff --git a/docs/models/inkling.md b/docs/models/inkling.md index 815746520..eb0a380bf 100644 --- a/docs/models/inkling.md +++ b/docs/models/inkling.md @@ -96,6 +96,14 @@ by a kernel, so they no longer wait behind the experts copied over the bus. The added. On an RTX 2070 Super 8 GB a 2,048-token prompt reads 6.5% faster with IQ4_NL (477 against 448 tokens/s) and 2.7% faster with UD-Q2_K_XL; 32,768 tokens read as fast as before. `STRATA_INK_KERNEL_TABLES=0` turns it off. +A prompt read gives up hundreds of the experts in VRAM for its rows and its wider staging buffer, and the next request +takes them back. Where the RAM has room, the engine keeps a pinned copy of every expert, the ones in VRAM too +(NVIDIA, where the engine makes a mirror: Linux by default, Windows with `STRATA_POLY_MIRROR=1`): an expert the cache gives up then needs no copy back from the card, and goes back to it straight +from pinned memory. The start line says `mirror: all experts (… GiB pinned …)`. It is made when the RAM free to the +engine (under WSL or in a container, theirs) keeps max(8 GiB, 20% of it) free beside the copy; IQ4_NL takes about +4.7 GiB more than the copy of the experts outside VRAM alone. The answers are the same. `--no-full-mirror` keeps +the copy to the experts outside VRAM, as before. + On a laptop with an RTX 4070 Laptop (8 GB), a Core i7-14700HX and 32 GB of RAM, on Windows, UD-Q3_K_XL has 1,216 of its 3,072 experts on the card and the rest are computed on the CPU. On a card that does not hold every expert, setup gives Inkling 2 Mini three settings that read fewer bytes for each token: `--attn-requant q5_0` (the attention's diff --git a/engine/src/poly/engine.cpp b/engine/src/poly/engine.cpp index 35005b37e..b4455711d 100644 --- a/engine/src/poly/engine.cpp +++ b/engine/src/poly/engine.cpp @@ -826,6 +826,51 @@ size_t ram_available(bool* own = nullptr) { #endif } +// The RAM the machine has, or under a cgroup's limit (a container, WSL's VM shows its own in /proc/meminfo) that +// limit if it is less; 0 when it cannot tell. +size_t ram_total() { +#if defined(STRATA_GPU_METAL) + return 0; +#elif defined(_WIN32) + MEMORYSTATUSEX st{}; + st.dwLength = sizeof(st); + return GlobalMemoryStatusEx(&st) ? (size_t) st.ullTotalPhys : 0; +#else + size_t kb = 0; + if (FILE* f = std::fopen("/proc/meminfo", "r")) { + char line[128]; + while (std::fgets(line, sizeof(line), f)) + if (std::sscanf(line, "MemTotal: %zu kB", &kb) == 1) break; + std::fclose(f); + } + size_t total = kb << 10; +#ifdef __linux__ + std::string path; + if (FILE* f = std::fopen("/proc/self/cgroup", "r")) { + char line[512]; + while (std::fgets(line, sizeof(line), f)) + if (std::strncmp(line, "0::", 3) == 0) { + path = line + 3; + while (!path.empty() && (path.back() == '\n' || path.back() == '\r')) path.pop_back(); + } + std::fclose(f); + } + // the tightest limit on the way to the root, as cgroup_room() + while (!path.empty()) { + if (FILE* f = std::fopen(("/sys/fs/cgroup" + path + "/memory.max").c_str(), "r")) { + unsigned long long max = 0; + if (std::fscanf(f, "%llu", &max) == 1 && max > 0) total = std::min(total, (size_t) max); + std::fclose(f); + } + if (path == "/") break; + const size_t cut = path.find_last_of('/'); + path = cut == 0 ? "/" : path.substr(0, cut); + } +#endif + return total; +#endif +} + } // namespace // One expert on its way into the cache. The engine's thread asks, the follower copies and sends, and the engine's @@ -3057,7 +3102,8 @@ 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 (s.mirror && !(s.adds && refills_mirror())) mirror_give(s.il, s.e); + // its copy stays where the mirror keeps them (a refill with --lock-experts, every expert with mirror_all_) + if (s.mirror && !(refills_mirror() && (s.adds || mirror_all_))) mirror_give(s.il, s.e); if (s.spare) mirror_of_[(size_t) s.out] = s.spare; s.mirror = nullptr; s.spare = nullptr; @@ -5885,30 +5931,52 @@ void Engine::build_mirror() { std::vector> want((size_t) n_trade_); std::vector stride((size_t) n_trade_, 0), cached((size_t) n_trade_, 0), spares((size_t) n_trade_, 0); size_t cached_all = 0; - for (int il = 0; il < (int) layers_.size(); ++il) { - const Layer& L = layers_[(size_t) il]; - if (L.trade < 0) continue; - stride[(size_t) L.trade] = (L.slot_bytes + 63) / 64 * 64; - for (int e = 0; e < n_expert_; ++e) { - if (L.slot[(size_t) e]) { - ++cached[(size_t) L.trade]; - ++cached_all; - } else { - want[(size_t) L.trade].push_back({il, e}); - } - } - } - size_t total = 0; - for (size_t c = 0; c < (size_t) n_trade_; ++c) { - if (!stride[c]) continue; - spares[c] = 1 + (size_t) (64.0 * (cached_all ? (double) cached[c] / (double) cached_all : 1.0)); - total += (want[c].size() + spares[c]) * stride[c]; - } constexpr size_t kHeadroom = size_t(4) << 30; // as the RAM budget's (load()) size_t avail = ram_available(); #ifdef _WIN32 if (avail) avail -= std::min(avail, cached_file_bytes()); // as the budget counts them (load()) #endif + // The whole mirror (full_mirror_default(), unless --no-full-mirror): the cached + // experts have their copies too, where the RAM free to this process keeps max(8 GiB, 20% of its RAM) beside them. + // The RAM is the process's: under WSL or a container, the VM's or the group's, not the host's. + const bool partial_asked = !opt_.full_mirror; + const size_t ram = ram_total(), keep = std::max(size_t(8) << 30, ram / 5); + size_t total = 0; + for (int pass = full_mirror_default() && !partial_asked && !mirror_short_ ? 0 : 1; pass < 2; ++pass) { + mirror_all_ = pass == 0; + for (auto& w : want) w.clear(); + std::fill(cached.begin(), cached.end(), 0); + cached_all = 0; + for (int il = 0; il < (int) layers_.size(); ++il) { + const Layer& L = layers_[(size_t) il]; + if (L.trade < 0) continue; + stride[(size_t) L.trade] = (L.slot_bytes + 63) / 64 * 64; + for (int e = 0; e < n_expert_; ++e) { + if (L.slot[(size_t) e]) { + ++cached[(size_t) L.trade]; + ++cached_all; + } + if (!L.slot[(size_t) e] || mirror_all_) want[(size_t) L.trade].push_back({il, e}); + } + } + total = 0; + for (size_t c = 0; c < (size_t) n_trade_; ++c) { + if (!stride[c]) continue; + spares[c] = 1 + (size_t) (64.0 * (cached_all ? (double) cached[c] / (double) cached_all : 1.0)); + total += (want[c].size() + spares[c]) * stride[c]; + } + if (!mirror_all_) break; + if (ram && avail >= total + keep) { + std::fprintf(stderr, "strata-poly: mirror: all experts (%.1f GiB pinned; %.1f of %.1f GiB of RAM free " + "before it)\n", + (double) total / (1 << 30), (double) avail / (1 << 30), (double) ram / (1 << 30)); + break; + } + std::fprintf(stderr, "strata-poly: mirror: the experts outside VRAM only, RAM short for all of them (%.1f GiB " + "would leave %.1f of %.1f GiB free, under the %.1f kept)\n", + (double) total / (1 << 30), (double) (avail > total ? avail - total : 0) / (1 << 30), + (double) ram / (1 << 30), (double) keep / (1 << 30)); + } if (!avail || total + kHeadroom > avail) { std::fprintf(stderr, "strata-poly: %.1f GiB of RAM available for a %.1f GiB pinned copy of the experts outside VRAM: " "prompts are staged from the mapped files%s\n", @@ -5993,6 +6061,12 @@ void Engine::build_mirror() { if (failed.load()) { cudaGetLastError(); free_pieces(got); + if (mirror_all_) { // the whole copy did not get its memory: the one of the experts outside VRAM, as before + std::fprintf(stderr, "strata-poly: mirror: no memory for all experts, the experts outside VRAM only\n"); + mirror_all_ = false; + mirror_short_ = true; + return build_mirror(); + } std::fprintf(stderr, "strata-poly: no pinned copy of the experts outside VRAM: no memory for it%s\n", opt_.lock_experts ? ", so --lock-experts locks their pages in the model file" : ""); return; @@ -6020,13 +6094,14 @@ void Engine::build_mirror() { mirror_spare_ = std::move(spare); mirror_stride_ = std::move(stride); mirror_registered_ = same != 0; - std::fprintf(stderr, "strata-poly: the %zu experts outside VRAM in %.1f GiB of pinned memory in %.1f s\n", n, - (double) total / (1 << 30), ms_since(t0) / 1000.0); + std::fprintf(stderr, "strata-poly: the %zu experts %s in %.1f GiB of pinned memory in %.1f s\n", n, + mirror_all_ ? "of the model" : "outside VRAM", (double) total / (1 << 30), ms_since(t0) / 1000.0); if (opt_.lock_experts) { - std::fprintf(stderr, "strata-poly: --lock-experts: copied the %zu experts outside VRAM into %.1f GiB of RAM and " + std::fprintf(stderr, "strata-poly: --lock-experts: copied the %zu experts %s into %.1f GiB of RAM and " "locked all of it: pinned for the card, which the system does not page out%s; one that " "leaves VRAM later is copied in too, from the model file, between requests\n", - n, (double) total / (1 << 30), memlock_note().c_str()); + n, mirror_all_ ? "of the model" : "outside VRAM", (double) total / (1 << 30), + memlock_note().c_str()); lock_asked_.assign(layers_.size() * ne, 0); lock_thread_ = std::thread([this] { lock_loop(); }); } diff --git a/engine/src/poly/engine.hpp b/engine/src/poly/engine.hpp index ab0e27454..1ebe8fc88 100644 --- a/engine/src/poly/engine.hpp +++ b/engine/src/poly/engine.hpp @@ -102,6 +102,9 @@ struct Options { bool lock_experts = false; ///< the experts outside VRAM kept in RAM, so the system cannot give it to another ///< program: copied into the pinned mirror (Engine::build_mirror()), or where there ///< is none, their pages in the file locked (Linux: up to ulimit -l) + bool full_mirror = true; ///< --no-full-mirror makes it false: where the model's engine asks for it + ///< (Engine::full_mirror_default()), the pinned mirror holds the cached experts too + ///< when the RAM keeps enough free beside it (Engine::build_mirror()) bool stay_near = true; ///< with several NUMA nodes, keep the CPU threads on the one that holds the experts bool graphs = true; ///< a token's fixed launches are recorded once, a CUDA graph a layer, and replayed bool kv_grow = true; ///< the attention caches get VRAM as the sequence grows, where the card can map it @@ -536,6 +539,8 @@ class Engine { /// gives, with the group's rows and these on the card (read_groups()). carry_at() points the architecture's /// buffers of them at a call's: carry_rows() blocks of rows_ rows each from `at`, or back at its own with null. virtual int carry_rows() const { return 0; } + /// The pinned mirror holds every expert, the cached ones too, when the RAM has room (build_mirror()). + virtual bool full_mirror_default() const { return false; } virtual void carry_at(float* at) { (void) at; } /// The architecture's block i of those rows as they are now (carry_at()), rows_ rows. On a layer split they cross /// to the next card beside the rows of r_ (carry_out(), carry_in()). @@ -752,8 +757,8 @@ class Engine { void stage(const Layer& L, const int32_t* experts, int m, void* stream, bool alone = false); void stage_rest(const Layer& L, const int32_t* experts, const std::vector& which, int m, void* stream, bool alone); - // The pinned mirror (build_mirror()): the routed experts the card does not hold, in pinned host memory in a - // card slot's layout. + // The pinned mirror (build_mirror()): the routed experts the card does not hold (with mirror_all_ every routed + // expert), in pinned host memory in a card slot's layout. void build_mirror(); const uint8_t* mirror(int il, int e) const { return mirror_of_.empty() ? nullptr : mirror_of_[(size_t) il * (size_t) n_expert_ + (size_t) e]; @@ -766,7 +771,12 @@ class Engine { /// experts the next long read takes from the cache again (widen_stage(), take_prompt()), which then go with no copy /// back from the card: given back, the copies held every 4,833-token read of Qwen3.6 UD-Q3_K_M on a 4090 2-3% /// under the default's. - bool refills_mirror() const { return opt_.lock_experts; } + /// + /// mirror_all_ (build_mirror()): every expert has its copy from the load on, and one that comes onto the card keeps + /// it, so an expert the cache gives up needs no copy back and no staging through the pinned buffers. + bool refills_mirror() const { return opt_.lock_experts || mirror_all_; } + bool mirror_all_ = false; + bool mirror_short_ = false; ///< the whole mirror's memory could not be had: build_mirror() makes the partial one void mirror_give(int il, int e); ///< the expert is on the card: its slot is a spare again void mirror_keep(int il, int e, const uint8_t* vram); ///< the expert leaves the card: its slot copied back GatherPiece* gather_slot(); diff --git a/engine/src/poly/inkling2.hpp b/engine/src/poly/inkling2.hpp index 9b3b44293..f366cc678 100644 --- a/engine/src/poly/inkling2.hpp +++ b/engine/src/poly/inkling2.hpp @@ -67,6 +67,10 @@ class Inkling2 final : public Engine { // A call's residual streams and the core's bank from one layer run to the next: read() takes the calls through // the runs a group at a time. Not with the drafter, whose taps of three runs are a call's too. int carry_rows() const override { return ds_file_ ? 0 : kBlocks + 2; } + // A read gives up hundreds of cached experts (the carried rows, the wider staging buffer) and the next request + // takes them back: with a copy of each kept in pinned memory they need no copy back from the card, and none goes + // to the card through the two pinned buffers, whose turns wait behind the next layer run's experts (prestage). + bool full_mirror_default() const override { return true; } void carry_at(float* at) override; float* carried(int i) override; void save_run(int il, int64_t pos, uint8_t* dst) override; diff --git a/engine/src/poly/main.cpp b/engine/src/poly/main.cpp index e7eff913c..3689f131f 100644 --- a/engine/src/poly/main.cpp +++ b/engine/src/poly/main.cpp @@ -1698,6 +1698,8 @@ void usage() { " --lock-experts keep the experts outside VRAM in RAM, so the system cannot give it to other\n" " programs: copied into pinned memory for the card where the RAM that is free\n" " holds them, else their pages in the model file locked (Linux: up to ulimit -l)\n" + " --no-full-mirror Inkling 2: the pinned copy of the experts holds only the ones outside VRAM\n" + " (default: every expert where the RAM keeps max(8 GiB, 20%%) free beside it)\n" " --prompt-batch N prompt tokens read at a time (default 1024); about 1.4 MiB of VRAM each\n" " --stage-mib N VRAM the experts outside the cache pass through in a prompt batch (default\n" " 128 on an NVIDIA card where a longer read widens it, else 2048; never more\n" @@ -1864,6 +1866,7 @@ int main(int argc, char** argv) { else if (a == "--no-gpu-experts") o.gpu_experts = false; else if (a == "--any-node") o.stay_near = false; else if (a == "--lock-experts") o.lock_experts = true; + else if (a == "--no-full-mirror") o.full_mirror = false; else if (a == "--no-graphs") o.graphs = false; else if (a == "--kv-whole") o.kv_grow = false; else if (a == "--kv-resident") o.kv_resident = std::atoi(val()); diff --git a/terminal/data/settings-register.json b/terminal/data/settings-register.json index 1b115a170..2aeffb15f 100644 --- a/terminal/data/settings-register.json +++ b/terminal/data/settings-register.json @@ -34319,7 +34319,7 @@ "last_date": "2026-11-20", "status": "default", "owner": "poly", - "note": "[reviewed] the host mirror of the experts outside VRAM that the card reads (CUDA, unified addressing), on where it applies unless =0; on Windows off unless =1 or --lock-experts (engine/src/poly/engine.cpp:5100)", + "note": "[reviewed] the host mirror of the experts outside VRAM that the card reads (CUDA, unified addressing), on where it applies unless =0; on Windows off unless =1 or --lock-experts (engine/src/poly/engine.cpp:5100). Inkling 2: the mirror holds the cached experts too where the RAM keeps max(8 GiB, 20%) free beside it; --no-full-mirror keeps it to the experts outside VRAM", "retire_after": "", "retired_in": "" },