From 8b1139d026c9b25255cf008836f02d5b31fdc869 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sun, 18 Oct 2026 15:19:59 +0200 Subject: [PATCH 1/2] 149: STRATA_IO_PF_GATE=1 - the decode's read-ahead only where the page cache has room and it pays (opt-in) With STRATA_IO_PREFETCH=1, the decode's read-ahead (pread on the I/O threads, the look-ahead two layers deep) and its pread demand reads run only while the gate is open; the prompt path is never gated. Checked every 16 decode windows: - room: (the tightest cgroup v2 limit - the group's non-file memory, else MemAvailable) / the experts' bytes; closes below STRATA_IO_PF_GATE_LO 0.55, opens above STRATA_IO_PF_GATE_HI 0.65; - pays: closes when fewer than 128 MB were read ahead in 16 windows, or under STRATA_IO_PF_GATE_USEFUL (0.10) of those bytes were used; then a probe every 256 windows. Closed, the look-ahead predicts one layer and warms with the madvise hint, as without io prefetch. The decode thread (and the fetch threads it starts) is marked by FileExpertSource::DecodeScope. The serve log's file-tier line says the room, the share used, the state and the flips. A request's wait for the adaptive round in flight at its start is logged when >= 1 ms. 5 pairs (Q2_0 GGUF in place, 12 GB card emulated, cold SSD, cgroup RAM caps), mode 4 + IO_PREFETCH + gate vs mode 4 alone: 32 GB 1.16 / 1.21 / 1.70 decode, 1.86 / 1.98 prompts; 16 GB (closed) 1.00 / 1.01 / 1.10, 1.54 / 1.78 prompts; an 18 GiB RAM tier 0.91 / 0.84 / 0.86 (its IO_PREFETCH start re-checks the RAM inside the cgroup and switches the file tier to unbuffered - not the gate's doing). Identity gates vs b829a3189 (fixed flags, Q2_0 and IQ3_S, default and mode 4 + IO_PREFETCH + gate with --mmap-experts): 10/10 and exact_pp 4K / 20K IDENTICAL in all four. --- include/strata/core/expert_source.hpp | 38 ++++++++ src/core/expert_source.cpp | 131 +++++++++++++++++++++++++- src/program/generate.cpp | 16 +++- 3 files changed, 179 insertions(+), 6 deletions(-) diff --git a/include/strata/core/expert_source.hpp b/include/strata/core/expert_source.hpp index 388358d5..74cfdd95 100644 --- a/include/strata/core/expert_source.hpp +++ b/include/strata/core/expert_source.hpp @@ -252,6 +252,8 @@ public: return got; } virtual void prefetch_end() {} + /// 149 STRATA_IO_PF_GATE: whether the decode's read-ahead runs now (the look-ahead then predicts one layer, not two) + virtual bool read_ahead_open() const { return true; } /// 149-cold STRATA_COLD_OVERLAP=3: the last prefetch_begin left this expert unstaged because the page cache holds /// all of it (the GGUF read in place): its gate, up and down rows in the mapping. False: ask `blob`. virtual bool zc_roles(int64_t layer, int64_t expert, const uint8_t** p) { (void) layer; (void) expert; (void) p; return false; } @@ -969,6 +971,42 @@ private: void claim_todo(int64_t layer, const int64_t* experts, int64_t n, std::vector& todo, uint8_t* pending, bool zc = false); std::vector zc_keys_; ///< 149-cold mode 3: the keys the last prefetch_begin left in the mapping +public: + /// 149 STRATA_IO_PF_GATE=1 (with STRATA_IO_PREFETCH=1): the decode's read-ahead and its pread demand reads run only + /// while the page cache can hold enough of the file tier: (the memory available, cgroup limits included, + the + /// file-tier bytes cached now) / the experts' bytes, checked every 16 decode windows; it closes below + /// STRATA_IO_PF_GATE_LO 0.55 and opens above STRATA_IO_PF_GATE_HI 0.65. Closed, the decode reads as without io + /// prefetch; the prompt path is not gated. (A held share at demand would not do: the read-ahead itself raises it.) + /// `DecodeScope` marks the decode thread (and the fetch threads it starts). + double gate_ratio() const { return gate_ratio_; } + struct DecodeScope { + bool prev; + DecodeScope(); + ~DecodeScope(); + }; + static bool in_decode(); + bool gate_open() const { return !gate_on_ || gate_open_.load(std::memory_order_relaxed); } + bool read_ahead_open() const override { return gate_open(); } + bool gate_on() const { return gate_on_; } + double gate_held() const { return gate_ewma_; } + int64_t gate_closed_windows() const { return gate_closed_w_; } + int64_t gate_flips() const { return gate_flips_; } +private: + void gate_tick(); + void gate_capacity(); + bool gate_on_ = false; + double gate_lo_ = 0.55, gate_hi_ = 0.65, gate_ewma_ = -1.0, gate_ratio_ = -1.0; + int64_t gate_win_ = 0, gate_useless_since_ = 0; + uint64_t gate_prev_pf_ = 0, gate_prev_used_ = 0; + double gate_useful_ = 1.0, gate_min_useful_ = 0.10; + bool gate_useless_ = false; +public: + double gate_useful() const { return gate_useful_; } +private: + std::atomic gate_open_{true}; + mutable std::atomic gate_c_{0}, gate_u_{0}; + uint64_t gate_prev_c_ = 0, gate_prev_u_ = 0; + int64_t gate_closed_w_ = 0, gate_flips_ = 0; std::vector async_todo_; std::vector async_th_; std::atomic async_next_{0}; diff --git a/src/core/expert_source.cpp b/src/core/expert_source.cpp index 3f16b2bc..15bc367a 100644 --- a/src/core/expert_source.cpp +++ b/src/core/expert_source.cpp @@ -702,7 +702,7 @@ void FileExpertSource::io_window_tick() { // the queue's fill against the window budget (a busy drive takes only the surer guesses); the window's speculative bytes // stay within the budget; each job carries the layer clock by which it must have started (else the worker drops it). void FileExpertSource::warm_scored(int64_t layer, const int64_t* experts, const float* conf, int64_t n, int ahead) { - if (!io_sched_ || !io_pf_ || !direct_.empty() || !io_ahead_) { warm(layer, experts, n); return; } + if (!io_sched_ || !io_pf_ || !direct_.empty() || !io_ahead_ || !gate_open()) { warm(layer, experts, n); return; } if (n <= 0 || layer < 0 || layer >= n_layers_) return; const uint64_t bytes = layer_blob_bytes_[(size_t) layer]; const uint64_t deadline = io_epoch_.load(std::memory_order_relaxed) + (uint64_t) std::max(1, ahead); @@ -771,6 +771,10 @@ void FileExpertSource::set_io_prefetch(bool on, int threads) { if (const char* m = std::getenv("STRATA_IO_PF_BUDGET_MB")) io_budget_fixed_ = (uint64_t) std::max(0.0, std::atof(m) * 1048576.0); if (const char* m = std::getenv("STRATA_IO_PF_BUDGET_FRAC")) io_budget_frac_ = std::clamp(std::atof(m), 0.01, 4.0); if (const char* m = std::getenv("STRATA_IO_PF_TARGET")) io_target_ = std::clamp(std::atof(m), 0.0, 1.0); + if (const char* m = std::getenv("STRATA_IO_PF_GATE")) gate_on_ = std::atoi(m) != 0; + if (const char* m = std::getenv("STRATA_IO_PF_GATE_LO")) gate_lo_ = std::clamp(std::atof(m), 0.0, 1.0); + if (const char* m = std::getenv("STRATA_IO_PF_GATE_HI")) gate_hi_ = std::clamp(std::atof(m), gate_lo_, 1.0); + if (const char* m = std::getenv("STRATA_IO_PF_GATE_USEFUL")) gate_min_useful_ = std::clamp(std::atof(m), 0.0, 1.0); } if (!pf_mark_) { pf_mark_.reset(new std::atomic[(size_t) (n_layers_ * n_expert_)]); @@ -1364,7 +1368,12 @@ bool FileExpertSource::copy_from_files(int64_t layer, int64_t expert, uint8_t* d const uint64_t res = resident_in(sp[i].p, sp[i].n); io_cached_.fetch_add(res, std::memory_order_relaxed); io_uncached_.fetch_add(sp[i].n - res, std::memory_order_relaxed); - if (io_pf_ && res < sp[i].n && sp[i].fd >= 0) { + const bool dec = in_decode(); + if (gate_on_ && dec) { + gate_c_.fetch_add(res, std::memory_order_relaxed); + gate_u_.fetch_add(sp[i].n - res, std::memory_order_relaxed); + } + if (io_pf_ && res < sp[i].n && sp[i].fd >= 0 && !(dec && !gate_open())) { const auto t0 = std::chrono::steady_clock::now(); const bool ok = pread_full(sp[i].fd, dst + sp[i].at, sp[i].n, sp[i].off); io_pread_us_.fetch_add((uint64_t) std::chrono::duration(std::chrono::steady_clock::now() - t0).count(), @@ -1506,6 +1515,110 @@ bool FileExpertSource::claim_stage(int64_t key, size_t& v, bool& fill, bool ahea return false; } +// 149 STRATA_IO_PF_GATE: whether this thread reads for the decode (the dispatch's thread, and the fetch threads it starts) +namespace { thread_local bool tl_decode = false; } +FileExpertSource::DecodeScope::DecodeScope() : prev(tl_decode) { tl_decode = true; } +FileExpertSource::DecodeScope::~DecodeScope() { tl_decode = prev; } +bool FileExpertSource::in_decode() { return tl_decode; } + +// once a decode window: the share of the window's demand bytes the page cache held, an EWMA, and the gate's state +void FileExpertSource::gate_tick() { + if (!gate_on_) return; + const uint64_t c = gate_c_.load(std::memory_order_relaxed), u = gate_u_.load(std::memory_order_relaxed); + const uint64_t dc = c - gate_prev_c_, du = u - gate_prev_u_; + gate_prev_c_ = c; + gate_prev_u_ = u; + if (dc + du < (64ull << 20)) { // too few bytes read this window to judge; the state stays + if (!gate_open_.load(std::memory_order_relaxed)) ++gate_closed_w_; + return; + } + const double h = (double) dc / (double) (dc + du); + gate_ewma_ = gate_ewma_ < 0.0 ? h : 0.8 * gate_ewma_ + 0.2 * h; // reported only + if (!gate_open_.load(std::memory_order_relaxed)) ++gate_closed_w_; +} + +namespace { +// The room the page cache has for the experts: in a memory-limited cgroup (v2; the tightest limit of the group and its +// ancestors) the limit less what is not page cache (the group's memory.current - its "file" pages); otherwise +// MemAvailable (free + reclaimable cache). 0 when unknown. +uint64_t gate_cache_room() { +#if defined(__linux__) + auto read_u64 = [](const std::string& path, uint64_t& v) { + std::ifstream f(path); + std::string s; + if (!(f >> s) || s == "max") return false; + v = std::strtoull(s.c_str(), nullptr, 10); + return v > 0; + }; + std::string rel; + { + std::ifstream g("/proc/self/cgroup"); + std::string line; + while (std::getline(g, line)) + if (line.rfind("0::", 0) == 0) { rel = line.substr(3); break; } + } + uint64_t best = 0; + if (!rel.empty()) { + const std::string base = "/sys/fs/cgroup"; + for (std::string at = rel;; ) { + const std::string dir = base + (at == "/" ? std::string() : at); + uint64_t mx = 0, cur = 0, file = 0; + if (read_u64(dir + "/memory.max", mx) && read_u64(dir + "/memory.current", cur)) { + std::ifstream st(dir + "/memory.stat"); + std::string k; + uint64_t v = 0; + while (st >> k >> v) + if (k == "file") { file = v; break; } + const uint64_t used = cur > file ? cur - file : 0; + const uint64_t room = mx > used ? mx - used : 0; + if (best == 0 || room < best) best = room; + } + if (at.empty() || at == "/") break; + const size_t cut = at.find_last_of('/'); + at = cut == 0 || cut == std::string::npos ? std::string("/") : at.substr(0, cut); + } + } + if (best > 0) return best; + std::ifstream info("/proc/meminfo"); + std::stringstream text; + text << info.rdbuf(); + return detail::meminfo_bytes(text.str(), "MemAvailable"); +#else + return 0; +#endif +} +} + +void FileExpertSource::gate_capacity() { + if (!gate_on_ || (gate_win_++ % 16) != 0) return; + const uint64_t total = expert_bytes(), room = gate_cache_room(); + if (total == 0 || room == 0) return; // unknown: the state stays + gate_ratio_ = (double) room / (double) total; + // and the read-ahead must pay: the share of its bytes a layer then used, over these 16 windows (64 MB at least read + // ahead to judge). Below STRATA_IO_PF_GATE_USEFUL (0.10) it closes (a RAM tier holds what it would read: an 18 GiB + // RAM tier, 0% used, -9..-15% decode); closed for that reason, it opens again for a probe every 256 windows. + const uint64_t pf = io_pf_bytes_.load(std::memory_order_relaxed), used = io_pf_used_bytes_.load(std::memory_order_relaxed); + const uint64_t dpf = pf - gate_prev_pf_, dused = used - gate_prev_used_; + gate_prev_pf_ = pf; + gate_prev_used_ = used; + if (dpf >= (64ull << 20)) gate_useful_ = (double) dused / (double) dpf; + const bool open = gate_open_.load(std::memory_order_relaxed); + const bool room_ok = open ? gate_ratio_ >= gate_lo_ : gate_ratio_ > gate_hi_; + bool want = room_ok; + // too little to read ahead (< 128 MB in 16 windows: the RAM and VRAM tiers hold what is predicted) costs the look-ahead's + // second layer and the I/O threads for nothing (an 18 GiB RAM tier: 2.5 GB read ahead in a run, -9..-16% decode) + if (room_ok && open && gate_win_ > 16 && (dpf < (128ull << 20) || gate_useful_ < gate_min_useful_)) { + want = false; + gate_useless_ = true; + gate_useless_since_ = gate_win_; + } else if (room_ok && !open && gate_useless_) { + want = gate_win_ - gate_useless_since_ >= 256; // the probe + if (want) gate_useless_ = false; + } + if (!room_ok) gate_useless_ = false; + if (want != open) { gate_open_.store(want, std::memory_order_relaxed); ++gate_flips_; } +} + // Fills buffer `v` (reserved by claim_stage) outside the lock, then publishes it. bool FileExpertSource::fill_stage(size_t v, int64_t layer, int64_t expert, uint8_t* dst) { const auto t0 = std::chrono::steady_clock::now(); @@ -1723,7 +1836,9 @@ int64_t FileExpertSource::prefetch_begin(int64_t layer, const int64_t* experts, async_next_.store(0, std::memory_order_relaxed); async_end_ns_.store(0, std::memory_order_relaxed); const bool direct = !direct_.empty(); - auto work = [this, direct] { + const bool dec = tl_decode; + auto work = [this, direct, dec] { + tl_decode = dec; const std::vector& todo = async_todo_; if (direct) { for (size_t at; (at = async_next_.fetch_add(16)) < todo.size();) { @@ -1780,6 +1895,7 @@ bool FileExpertSource::zc_roles(int64_t layer, int64_t expert, const uint8_t** p if (complement_ready_) file_reads_.fetch_add(1, std::memory_order_relaxed); reads_.fetch_add(1, std::memory_order_relaxed); if (io_stats_) io_cached_.fetch_add(layer_blob_bytes_[(size_t) layer], std::memory_order_relaxed); + if (gate_on_ && tl_decode) gate_c_.fetch_add(layer_blob_bytes_[(size_t) layer], std::memory_order_relaxed); return true; } @@ -1881,7 +1997,9 @@ void FileExpertSource::fill_many(const std::vector& todo) { #endif // the page faults of a mapped read are one outstanding request each: several threads keep the SSD's queue full std::atomic next{0}; + const bool dec = tl_decode; auto work = [&] { + tl_decode = dec; for (size_t i; (i = next.fetch_add(1)) < todo.size();) (void) fill_stage(todo[i].v, todo[i].layer, todo[i].e, todo[i].dst); }; @@ -2467,7 +2585,7 @@ void FileExpertSource::warm(int64_t layer, const int64_t* experts, int64_t n) { continue; // in the RAM copy if (warm_stamp_) warm_stamp_[index].store(stamp, std::memory_order_relaxed); warm_count_.fetch_add(1, std::memory_order_relaxed); - if (io_pf_ && direct_.empty()) { // read it ahead with pread on the I/O threads (instead of an madvise hint) + if (io_pf_ && direct_.empty() && gate_open()) { // read it ahead with pread on the I/O threads (instead of an madvise hint) if (io_ahead_) io_enqueue(layer, e, true); continue; } @@ -2667,7 +2785,8 @@ void RouterLookahead::run() { } const auto t0 = std::chrono::steady_clock::now(); const int64_t layer0 = layer; - for (int dj = 0; dj < depth_ && layer0 + dj < (int64_t) routers_.size(); ++dj) { + const int depth = src_ != nullptr && !src_->read_ahead_open() ? 1 : depth_; // 149: the gate closed + for (int dj = 0; dj < depth && layer0 + dj < (int64_t) routers_.size(); ++dj) { layer = layer0 + dj; want.clear(); wconf.clear(); @@ -2780,6 +2899,7 @@ void FileExpertSource::begin_layer(int64_t layer, const int32_t* ids, int64_t k) } } if (new_window && io_sched_) io_window_tick(); + if (new_window && gate_on_ && tl_decode) { gate_capacity(); gate_tick(); } } bool FileExpertSource::transient(int64_t layer, int64_t expert) const { @@ -4248,6 +4368,7 @@ void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32 if (ptrace) { std::fprintf(stderr, "pool trace: layer %lld %s %lld\n", (long long) d.layers, what, a); std::fflush(stderr); } }; const auto c0 = std::chrono::steady_clock::now(); + const FileExpertSource::DecodeScope decode_scope; // 149 STRATA_IO_PF_GATE: this thread reads for the decode // 149-cold STRATA_COLD_OVERLAP: 0 off (default), 1 overlap, 2 measure only, 3 overlap + zero-copy, 4 zero-copy only static const int cold_env = [] { const char* v = std::getenv("STRATA_COLD_OVERLAP"); diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 06a2281b..47235e07 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -10759,6 +10759,7 @@ int main(int argc, char** argv) { int64_t ba_window = 0, bt_adapt_rounds = 0, bt_adapt_swaps = 0; double bt_adapt_wait = 0; bool in_prompt_read = false; // batch_step runs between a prompt's chunks: the adaptive tier stands still then + double serve_adapt_drain_ms = 0.0; // 149: the request's wait for the adaptive round in flight int64_t bt_a_rounds0 = 0, bt_a_swapped0 = 0; // the asynchronous tier's counters when the timed windows began Clock::time_point bt_start = Clock::now(); int admit_slot = -1; ///< the slot the request being read will continue in (BGEN) @@ -13278,7 +13279,11 @@ int main(int argc, char** argv) { return true; }; apply_pending(true); - if (!adapt_tick(true)) { // --adapt-async: the round in flight lands before the prompt lends any slot + const auto drain_t0 = Clock::now(); + const bool drained_ok = adapt_tick(true); + // 149: how long the request waited for the adaptive round still in flight (in the prompt's time) + serve_adapt_drain_ms = std::chrono::duration(Clock::now() - drain_t0).count(); + if (!drained_ok) { // --adapt-async: the round in flight lands before the prompt lends any slot std::printf("ERR an adaptive refill failed\n"); return 1; } @@ -14845,6 +14850,9 @@ int main(int argc, char** argv) { prompt_ms > 0 ? 1000.0 * read_n / prompt_ms : 0.0, (long long) produced_n, decode_ms, decode_ms > 0 ? 1000.0 * produced_n / decode_ms : 0.0, (long long) draft_accepted, (long long) draft_offered, checks.size(), cancelled ? " (cancelled)" : ""); + if (serve_adapt_drain_ms >= 1.0) + std::fprintf(stderr, "strata serve: the request first waited %.0f ms for the adaptive tier's round in flight\n", + serve_adapt_drain_ms); // the VRAM share of the experts the pool looked up while decoding; experts it sent over PCIe for the GPU // to read (--pcie-frac) are in neither count - #588: so that share is said beside it (raising --pcie-frac // raises the hit rate while the PCIe reads may make the decode slower) @@ -14925,6 +14933,12 @@ int main(int argc, char** argv) { (unsigned long long) (ic.pf_dropped - ic_prev.pf_dropped), (double) (ic.crit_us - ic_prev.crit_us) / 1e3, (unsigned long long) (ic.crit_n - ic_prev.crit_n)); + if (src.io_prefetch() && src.gate_on()) // 149 STRATA_IO_PF_GATE: the decode's held share, the gate + std::fprintf(stderr, "; decode gate: cache room %.2f of the experts, read-ahead used %.0f%%, page cache " + "held %.0f%% of the decode's reads (EWMA), %s, closed in %lld windows so far, %lld flips", + src.gate_ratio(), 100.0 * src.gate_useful(), 100.0 * std::max(0.0, src.gate_held()), + src.gate_open() ? "open" : "closed", (long long) src.gate_closed_windows(), + (long long) src.gate_flips()); if (src.io_prefetch()) // 149-prefetch: bytes read ahead, of them used before their demand; the scheduler's drops std::fprintf(stderr, "; read ahead %.1f MB, %.1f MB of it used; %llu late, %llu not admitted (confidence), " "%llu (budget %.0f MB/window)", From 82c80ac4d76a032ce97ad27ef66c0b41fa39f2bc Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sun, 18 Oct 2026 15:39:41 +0200 Subject: [PATCH 2/2] 149: Linux defaults - zero-copy page-cached experts, io prefetch and its decode gate; cgroup RAM check counts the clean page cache - STRATA_COLD_OVERLAP defaults to 4 on Linux (0 elsewhere), STRATA_IO_PREFETCH to 1 on Linux for the file tier (mapped GGUF in place or experts.bin), STRATA_IO_PF_GATE to 1 with io prefetch. Off switches: STRATA_COLD_OVERLAP=0, STRATA_IO_PREFETCH=0, STRATA_IO_PF_GATE=0. One startup line names them. - cgroup_available_bytes: every clean file page of the group (memory.stat file, active + inactive; else inactive_file) is reclaimable, less min(half of it, limit / 64), as MemAvailable counts page cache on a bare host. A container whose own reads left active cache was judged short of RAM and its file tier switched to unbuffered reads (an 18 GiB RAM tier in a 32 GiB group: 1.2 GiB available instead of ~11). Unit tests with mock memory.stat / memory.max values. - The per-request cold-reads line only with STRATA_COLD_OVERLAP or STRATA_IO_STATS set. - docs/DETAILS.md: the 0.2.0 Linux file-tier defaults. --- docs/DETAILS.md | 23 +++++++++++++++- include/strata/core/expert_source.hpp | 7 ++++- src/core/expert_source.cpp | 31 ++++++++++++++++----- src/program/generate.cpp | 33 +++++++++++++++++------ tests/core/file_expert_source_test.cpp | 37 +++++++++++++++++++++++--- 5 files changed, 111 insertions(+), 20 deletions(-) diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 9951af43..e0861c7c 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -261,7 +261,28 @@ from the GGUF gave identical tokens and logits. An expert read from the GGUF is engine fetches a layer's missing experts on 8 threads (`STRATA_FETCH_THREADS`) with one batched page request (Windows `PrefetchVirtualMemory`). With an `experts.bin` in the pack, nothing changes. Setup does not use this yet. -**Linux file-tier I/O path (opt in, `STRATA_IO_PREFETCH=1`; 0.1.40.2):** the mapped file tier reads experts through +**Linux file tier, 0.2.0 defaults (zero-copy page-cached experts, io prefetch, the decode gate):** when experts are read +from the files (a GGUF read in place, `--mmap-experts`, or an `experts.bin` file tier), Linux now runs three things by default. +(1) **Zero-copy** (`STRATA_COLD_OVERLAP=4`): an expert of a GGUF read in place whose three tensors' pages are all in the page +cache (mincore) is computed straight from the mapping; before, every such expert was first assembled into a staging buffer +(a copy of ~1.5 MB per Q2_0 expert, on the decode's critical path). Same bytes, same rows, same output (identity gates +IDENTICAL). (2) **io prefetch** (`STRATA_IO_PREFETCH=1`, the path described below): whole-blob `pread`s and the router- +predicted experts of the next layers read ahead. (3) **the decode gate** (`STRATA_IO_PF_GATE=1`): every 16 decode windows the +decode's read-ahead is judged - it runs only while the page cache has room for the experts (the memory available, the +tightest cgroup limit included, over the experts' bytes: off below 0.55, on above 0.65, `STRATA_IO_PF_GATE_LO` / `_HI`) and +while it pays (at least 128 MB read ahead in 16 windows and 10% of it used, `STRATA_IO_PF_GATE_USEFUL`; a probe every 256 +windows when it closed for that). Closed, the decode reads as it did without io prefetch (the look-ahead predicts one layer +and warms with an madvise hint); the prompt path keeps its preads either way. Measured on an RTX PRO 5000 emulating a 12 GB +card (`--expert-cache 4448`, Q2_0 GGUF in place, page cache dropped before each engine, RAM limited by a cgroup), 5 pairs, +story / code / doc8k decode, 4K / 20K prompts, against the 0.1.4x defaults: 32 GB of RAM 1.8 / 2.8 / 3.1x decode, 1.5 / 2.0x +prompts; 16 GB 1.2 / 1.4 / 1.4x decode, 1.6 / 1.8x prompts (the gate stays closed there); an 18 GiB RAM tier B32_RESULT. On a real RTX 3060 12 GB (32 GB cgroup, 3 pairs) zero-copy alone gave 1.14 / 1.44 / 1.47x decode, 1.06 / 1.02x +prompts. With it the container RAM check counts a cgroup's clean page cache (active and inactive) as available, as +MemAvailable does on a bare host (before, a 32 GiB container whose own reads left 26 GiB of cache was judged short of RAM +and its file tier switched to unbuffered reads). Off switches: `STRATA_COLD_OVERLAP=0`, `STRATA_IO_PREFETCH=0`, +`STRATA_IO_PF_GATE=0`; the startup log names what is on. Windows and macOS are unchanged. Measured detail: +phaseA-tests/notes-149-l620.md. + +**Linux file-tier I/O path (`STRATA_IO_PREFETCH=1`; 0.1.40.2, on by default on Linux since 0.2.0 - see above):** the mapped file tier reads experts through page faults. With this on, the layer's uncached experts and the router-predicted ones of the next layer (`STRATA_LOOKAHEAD_K`, `STRATA_IO_PREFETCH_DEPTH`, default 2 when on) are read by I/O threads (`STRATA_IO_PF_THREADS`, default 8) with whole-blob `pread`s into the page cache, and the CPU kernels read the mapping as before. The bytes are the same, so the output is the diff --git a/include/strata/core/expert_source.hpp b/include/strata/core/expert_source.hpp index 74cfdd95..ab7ae4a4 100644 --- a/include/strata/core/expert_source.hpp +++ b/include/strata/core/expert_source.hpp @@ -65,9 +65,14 @@ struct CgroupMemoryStat { uint64_t file_dirty = 0; uint64_t file_writeback = 0; bool valid = false; + uint64_t file = 0; ///< 149: memory.stat "file" (active + inactive page cache); 0 when not reported }; -/// Calculate additional bytes under a finite cgroup limit after reclaiming only clean inactive file cache. +/// Calculate additional bytes under a finite cgroup limit after reclaiming the group's clean page cache, as +/// MemAvailable counts it on a bare host: every clean file page (active and inactive: memory.stat "file", else +/// inactive_file), less a low-watermark share the kernel keeps (min(half the clean cache, limit / 64)). A process +/// whose own reads (a GPU cache fill, a read-ahead) left gigabytes of active cache in its group was judged short of +/// RAM before (149: 1.2 GiB "available" of a 32 GiB group, the file tier then switched to unbuffered reads). /// Returns false when the required memory.stat counters were unavailable. bool cgroup_available_bytes(uint64_t limit, const CgroupMemoryStat& stat, uint64_t& bytes); diff --git a/src/core/expert_source.cpp b/src/core/expert_source.cpp index 15bc367a..38b8be0b 100644 --- a/src/core/expert_source.cpp +++ b/src/core/expert_source.cpp @@ -75,10 +75,12 @@ bool cgroup_available_bytes(uint64_t limit, const CgroupMemoryStat& stat, uint64 bytes = 0; if (!stat.valid) return false; - // memory.stat's inactive_file can race memory.current, so bound it to charged usage first. - uint64_t reclaimable = std::min(stat.inactive_file, stat.current); + // memory.stat's counters can race memory.current, so bound them to charged usage first. The whole clean page + // cache is reclaimable (149: MemAvailable counts active file pages too); the kernel keeps a low-watermark share. + uint64_t reclaimable = std::min(std::max(stat.file, stat.inactive_file), stat.current); reclaimable = stat.file_dirty >= reclaimable ? 0 : reclaimable - stat.file_dirty; reclaimable = stat.file_writeback >= reclaimable ? 0 : reclaimable - stat.file_writeback; + reclaimable -= std::min(reclaimable / 2, limit / 64); // Reclaiming clean file pages reduces usage; saturating subtraction also handles a transient over-limit read. const uint64_t usage_after_reclaim = stat.current - reclaimable; @@ -291,7 +293,7 @@ bool read_cgroup_memory_stat(const std::filesystem::path& path, uint64_t current std::ifstream input(path / "memory.stat"); if (!input) return false; - bool inactive_file = false, file_dirty = false, file_writeback = false; + bool inactive_file = false, file_dirty = false, file_writeback = false, file = false; std::string line; while (std::getline(input, line)) { std::istringstream fields(line); @@ -313,6 +315,10 @@ bool read_cgroup_memory_stat(const std::filesystem::path& path, uint64_t current if (file_writeback) return false; file_writeback = true; stat.file_writeback = value; + } else if (key == "file") { // 149: optional (every v2 kernel has it); 0 = inactive_file alone + if (file) return false; + file = true; + stat.file = value; } } if (!input.eof() || !inactive_file || !file_dirty || !file_writeback) return false; @@ -771,7 +777,8 @@ void FileExpertSource::set_io_prefetch(bool on, int threads) { if (const char* m = std::getenv("STRATA_IO_PF_BUDGET_MB")) io_budget_fixed_ = (uint64_t) std::max(0.0, std::atof(m) * 1048576.0); if (const char* m = std::getenv("STRATA_IO_PF_BUDGET_FRAC")) io_budget_frac_ = std::clamp(std::atof(m), 0.01, 4.0); if (const char* m = std::getenv("STRATA_IO_PF_TARGET")) io_target_ = std::clamp(std::atof(m), 0.0, 1.0); - if (const char* m = std::getenv("STRATA_IO_PF_GATE")) gate_on_ = std::atoi(m) != 0; + gate_on_ = true; // 0.2.0: the decode gate comes with io prefetch; STRATA_IO_PF_GATE=0 turns it off + if (const char* m = std::getenv("STRATA_IO_PF_GATE"); m != nullptr && m[0] != '\0') gate_on_ = std::atoi(m) != 0; if (const char* m = std::getenv("STRATA_IO_PF_GATE_LO")) gate_lo_ = std::clamp(std::atof(m), 0.0, 1.0); if (const char* m = std::getenv("STRATA_IO_PF_GATE_HI")) gate_hi_ = std::clamp(std::atof(m), gate_lo_, 1.0); if (const char* m = std::getenv("STRATA_IO_PF_GATE_USEFUL")) gate_min_useful_ = std::clamp(std::atof(m), 0.0, 1.0); @@ -1815,7 +1822,14 @@ int64_t FileExpertSource::prefetch_begin(int64_t layer, const int64_t* experts, prefetch_end(); async_todo_.clear(); async_fill_us_ = 0; - static const int mode = [] { const char* v = std::getenv("STRATA_COLD_OVERLAP"); return v != nullptr ? std::atoi(v) : 0; }(); + static const int mode = [] { // as the dispatch reads it (0.2.0: 4 by default on Linux) + const char* v = std::getenv("STRATA_COLD_OVERLAP"); +#if defined(__linux__) + return v == nullptr || v[0] == '\0' ? 4 : std::atoi(v); +#else + return v == nullptr || v[0] == '\0' ? 0 : std::atoi(v); +#endif + }(); claim_todo(layer, experts, n, async_todo_, pending, mode >= 3); if (mode == 4) { // zero-copy only: the blobs that must be read are read here, as `prefetch` reads them const auto t0 = std::chrono::steady_clock::now(); @@ -4370,9 +4384,14 @@ void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32 const auto c0 = std::chrono::steady_clock::now(); const FileExpertSource::DecodeScope decode_scope; // 149 STRATA_IO_PF_GATE: this thread reads for the decode // 149-cold STRATA_COLD_OVERLAP: 0 off (default), 1 overlap, 2 measure only, 3 overlap + zero-copy, 4 zero-copy only + // 0.2.0: 4 by default on Linux (zero-copy needs the page cache's residency query); elsewhere 0 static const int cold_env = [] { const char* v = std::getenv("STRATA_COLD_OVERLAP"); - return v == nullptr ? 0 : std::clamp(std::atoi(v), 0, 4); +#if defined(__linux__) + return v == nullptr || v[0] == '\0' ? 4 : std::clamp(std::atoi(v), 0, 4); +#else + return v == nullptr || v[0] == '\0' ? 0 : std::clamp(std::atoi(v), 0, 4); +#endif }(); d.cold_mode = cold_env; pt("begin"); diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 47235e07..95975f1a 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -5445,19 +5445,35 @@ int main(int argc, char** argv) { "(%s)\n", why.c_str()); } #endif - // Linux I/O path (opt in): whole-blob preads instead of page faults, and the predicted experts of the next - // layers read ahead on I/O threads while the current layer computes (see FileExpertSource::set_io_prefetch) - if (const char* v = std::getenv("STRATA_IO_PREFETCH"); v != nullptr && std::atoi(v) != 0) { + // Linux I/O path: whole-blob preads instead of page faults, and the predicted experts of the next layers read + // ahead on I/O threads while the current layer computes (see FileExpertSource::set_io_prefetch). 0.2.0: on by + // default on Linux, with the decode gate (STRATA_IO_PF_GATE) and zero-copy page-cached experts + // (STRATA_COLD_OVERLAP=4); STRATA_IO_PREFETCH=0 / STRATA_IO_PF_GATE=0 / STRATA_COLD_OVERLAP=0 turn them off. + const char* io_pf_env = std::getenv("STRATA_IO_PREFETCH"); +#if defined(__linux__) + const bool io_pf_default = io_pf_env == nullptr || io_pf_env[0] == '\0'; +#else + const bool io_pf_default = false; +#endif + if (io_pf_default || (io_pf_env != nullptr && std::atoi(io_pf_env) != 0)) { const char* th = std::getenv("STRATA_IO_PF_THREADS"); src.set_io_prefetch(true, th != nullptr ? std::atoi(th) : 0); - if (src.io_prefetch()) + if (src.io_prefetch() && io_pf_default) { + const char* cv = std::getenv("STRATA_COLD_OVERLAP"); + std::fprintf(stderr, "strata generate: file tier (Linux defaults): page-cached experts computed from the " + "mapping (STRATA_COLD_OVERLAP=%s), io prefetch with whole-blob preads on %s I/O threads, " + "the decode's read-ahead %s; off: STRATA_COLD_OVERLAP=0, STRATA_IO_PREFETCH=0, " + "STRATA_IO_PF_GATE=0\n", cv != nullptr && cv[0] != '\0' ? cv : "4", th != nullptr ? th : "8", + src.gate_on() ? "only while the page cache has room for it and it pays (STRATA_IO_PF_GATE=1)" + : "always (STRATA_IO_PF_GATE=0)"); + } else if (src.io_prefetch()) std::fprintf(stderr, "strata generate: file tier io prefetch ON (STRATA_IO_PREFETCH=1): whole-blob preads, " - "the layer's uncached experts and the predicted ones read by %s I/O threads (STRATA_IO_PF_THREADS, default 8)\n", - th != nullptr ? th : "8"); + "the layer's uncached experts and the predicted ones read by %s I/O threads (STRATA_IO_PF_THREADS, default 8)%s\n", + th != nullptr ? th : "8", src.gate_on() ? "; the decode's read-ahead gated (STRATA_IO_PF_GATE=0: always)" : ""); if (src.io_prefetch() && src.io_sched()) std::fprintf(stderr, "strata generate: io prefetch scheduling ON (STRATA_IO_PF_SCHED=1): a deadline per read, " "confidence admission (STRATA_IO_PF_MINCONF), a per-window byte budget (STRATA_IO_PF_BUDGET_MB / _FRAC)\n"); - if (!src.io_prefetch()) + if (!src.io_prefetch() && !io_pf_default) std::fprintf(stderr, "strata generate: STRATA_IO_PREFETCH=1 is not available here (Linux mapped file tier " "only, not with unbuffered reads); the file tier reads as before\n"); if (src.io_prefetch()) { // recommend, never force: the engine runs as asked @@ -14954,7 +14970,8 @@ int main(int argc, char** argv) { fb_prev = fb; } } - if (drive.d.cold_mode != 0) { // 149-cold STRATA_COLD_OVERLAP: this request's layers that had a blob to read + static const bool cold_log = std::getenv("STRATA_COLD_OVERLAP") != nullptr || std::getenv("STRATA_IO_STATS") != nullptr; + if (drive.d.cold_mode != 0 && cold_log) { // 149-cold STRATA_COLD_OVERLAP: this request's layers that had a blob to read static strata::core::ExpertDispatch cp; const strata::core::ExpertDispatch& c = drive.d; const double nl = (double) std::max(1, c.cold_layers - cp.cold_layers); diff --git a/tests/core/file_expert_source_test.cpp b/tests/core/file_expert_source_test.cpp index c4586c87..83ced92e 100644 --- a/tests/core/file_expert_source_test.cpp +++ b/tests/core/file_expert_source_test.cpp @@ -433,18 +433,41 @@ void test_cgroup_memory_budget() { constexpr uint64_t GiB = 1ull << 30; uint64_t bytes = 0; + // the kernel keeps min(half the clean cache, limit / 64) of it: 56 GiB / 64 = 0.875 GiB here + const uint64_t keep56 = 56 * GiB / 64; CgroupMemoryStat clean_cache{40 * GiB, 32 * GiB, 0, 0, true}; require(cgroup_available_bytes(56 * GiB, clean_cache, bytes), "valid cgroup memory.stat was rejected"); - require(bytes == 48 * GiB, "clean inactive file cache was not credited against the cgroup cap"); + require(bytes == 48 * GiB - keep56, "clean inactive file cache was not credited against the cgroup cap"); CgroupMemoryStat dirty_cache{40 * GiB, 32 * GiB, 4 * GiB, 2 * GiB, true}; require(cgroup_available_bytes(56 * GiB, dirty_cache, bytes), "valid dirty-cache counters were rejected"); - require(bytes == 42 * GiB, "dirty/writeback pages were incorrectly counted as reclaimable"); + require(bytes == 42 * GiB - keep56, "dirty/writeback pages were incorrectly counted as reclaimable"); CgroupMemoryStat oversized_inactive{10 * GiB, 20 * GiB, 0, 0, true}; require(cgroup_available_bytes(12 * GiB, oversized_inactive, bytes), "valid oversized inactive-file counter was rejected"); - require(bytes == 12 * GiB, "inactive-file accounting exceeded charged current usage"); + require(bytes == 12 * GiB - 12 * GiB / 64, "inactive-file accounting exceeded charged current usage"); + + // 149: the ACTIVE page cache is reclaimable too (memory.stat "file" = active + inactive), as MemAvailable counts + // it: a 32 GiB group whose own reads left 26 GiB of cache, 25 GiB of it active, and 4.5 GiB of anonymous memory + CgroupMemoryStat active_cache{30 * GiB + GiB / 2, 1 * GiB, 0, 0, true, 26 * GiB}; + require(cgroup_available_bytes(32 * GiB, active_cache, bytes), "a memory.stat with file was rejected"); + require(bytes == 32 * GiB - (4 * GiB + GiB / 2) - 32 * GiB / 64, "the active page cache was not credited"); + // without "file" (an old kernel's stat): inactive_file alone, as before + CgroupMemoryStat no_file{30 * GiB + GiB / 2, 1 * GiB, 0, 0, true}; + require(cgroup_available_bytes(32 * GiB, no_file, bytes) && bytes == 32 * GiB - (29 * GiB + GiB / 2) - GiB / 2, + "a stat without file did not fall back to inactive_file"); + // dirty and writeback pages of the active cache stay charged; a small cache keeps half of itself + CgroupMemoryStat dirty_active{20 * GiB, 1 * GiB, 2 * GiB, 1 * GiB, true, 10 * GiB}; + require(cgroup_available_bytes(32 * GiB, dirty_active, bytes) && bytes == 32 * GiB - (20 * GiB - 7 * GiB) - GiB / 2, + "dirty / writeback pages of the active cache were counted as reclaimable"); + CgroupMemoryStat tiny_cache{8 * GiB, 0, 0, 0, true, 256ull << 20}; + require(cgroup_available_bytes(32 * GiB, tiny_cache, bytes) && bytes == 32 * GiB - 8 * GiB + (128ull << 20), + "a small clean cache was not kept at half"); + // "file" larger than what is charged (a racy read) is bounded by memory.current + CgroupMemoryStat racy{4 * GiB, 1 * GiB, 0, 0, true, 9 * GiB}; + require(cgroup_available_bytes(32 * GiB, racy, bytes) && bytes == 32 * GiB - GiB / 2, + "a file counter above memory.current escaped the bound"); const uint64_t max = std::numeric_limits::max(); CgroupMemoryStat large_counters{max, max, max - 1, max, true}; @@ -562,7 +585,13 @@ void test_host_memory() { put("fs/box/memory.max", std::to_string(48 * GiB) + "\n"); put("fs/box/memory.current", std::to_string(16 * GiB) + "\n"); put("fs/box/memory.stat", "inactive_file " + std::to_string(4 * GiB) + "\nfile_dirty 0\nfile_writeback 0\n"); - require(probe("0::/box\n") && m.available == 36 * GiB && m.cgroup_limit == 48 * GiB, "v2 limit"); + require(probe("0::/box\n") && m.available == 36 * GiB - 48 * GiB / 64 && m.cgroup_limit == 48 * GiB, "v2 limit"); + // 149: with "file" (active + inactive cache) the active part counts too: 12 GiB of cache, 4 GiB anonymous + put("fs/box/memory.stat", "file " + std::to_string(12 * GiB) + "\ninactive_file " + std::to_string(4 * GiB) + + "\nfile_dirty 0\nfile_writeback 0\n"); + require(probe("0::/box\n") && m.available == 44 * GiB - 48 * GiB / 64 && m.cgroup_limit == 48 * GiB, + "v2 limit, the active page cache credited"); + put("fs/box/memory.stat", "inactive_file " + std::to_string(4 * GiB) + "\nfile_dirty 0\nfile_writeback 0\n"); put("fs/box/memory.max", "max\n"); require(probe("0::/box\n") && m.available == 100 * GiB && m.cgroup_limit == ~0ull, "v2 max"); put("fs/box/memory.max", "48G\n");