From 3782008944a5648a15242ded95fc20128a3fcf8e Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 30 Oct 2026 04:46:51 +0100 Subject: [PATCH] shared arena: memfd backing (not limited by the /dev/shm size), one engine reads the experts and the others skip the read, RAM check before the pages are taken --- include/strata/core/pinned.hpp | 3 ++ serve/replicas.py | 61 ++++++++++++++++++++++++++++------ serve/test_replicas.py | 24 ++++++++++++- src/core/expert_source.cpp | 53 ++++++++++++++++++++++++++++- src/core/pinned.cu | 61 ++++++++++++++++++++++++++++++++++ 5 files changed, 190 insertions(+), 12 deletions(-) diff --git a/include/strata/core/pinned.hpp b/include/strata/core/pinned.hpp index c9d7da07..f97f3c52 100644 --- a/include/strata/core/pinned.hpp +++ b/include/strata/core/pinned.hpp @@ -90,6 +90,9 @@ struct PinnedArena { std::vector slice_starts; void* mapping_base = nullptr; ///< actual mapping start; differs from base when a shared-file header exists uint64_t mapping_bytes = 0; ///< bytes to release from mapping_base + /// shared-file arena only: the load state word in the file's header (0: nobody has loaded it, a pid: that engine is + /// loading it, ~0: it is complete). Shared by every engine that maps the file; null for a private arena. + std::atomic* shared_state = nullptr; ~PinnedArena(); PinnedArena(const PinnedArena&) = delete; PinnedArena& operator=(const PinnedArena&) = delete; diff --git a/serve/replicas.py b/serve/replicas.py index 9229a64d..93309875 100644 --- a/serve/replicas.py +++ b/serve/replicas.py @@ -20,12 +20,15 @@ the prompts and answers it served (the engine itself checks the real prefix, as Host RAM. Every engine keeps its own copy of the experts in RAM (about 47 GiB for Qwen3.8-Flash-Next IQ3_S), so two replicas need two copies and four need four. "replica_shared_arena": true (or STRATA_REPLICA_SHARED_ARENA=1; opt-in) -backs the experts' arena of all replicas with ONE file in /dev/shm (the engine's --shared-expert-arena, MAP_SHARED): -the experts are in RAM once, whatever the number of replicas. Every engine still reads the experts into the file -itself (the same bytes, so a replica that starts, restarts or dies at any time never leaves another one with half an -arena), the pack hash in the file's header refuses another model, the file is unlinked when the server ends (a -running engine keeps its mapping: the kernel frees the pages with the last one) and a file whose server is gone is -removed at the next start. See shared_arena_plan. +backs the experts' arena of all replicas with ONE shared memory object (the engine's --shared-expert-arena, MAP_SHARED): +the experts are in RAM once, whatever the number of replicas. On Linux the object is a memfd the server creates +(os.memfd_create): it is not a file on a mount, so the size of /dev/shm does not limit it; the engines open it as +/proc//fd/. Without memfd (an old kernel, a sandbox that refuses it) a file in /dev/shm is used instead. +The pack hash in the header refuses another model; the first engine to start reads the experts into it and the others +wait for it and skip the read (a state word in the header: nobody / a pid reading / filled; an engine whose reader died +takes the read over); the server closes the memfd (or unlinks the file) when it ends - an engine that still maps it +keeps its pages, the kernel frees them with the last mapping - and a /dev/shm file whose server is gone is removed at +the next start. See shared_arena_plan. CPU cores. On Linux the replicas get disjoint physical cores (serve/cpu_affinity.py, from PR #1436 by agorevski), so the host threads of the engines (the expert workers) do not compete. "replica_cpus": false turns it off. @@ -92,6 +95,8 @@ def _cards(g) -> list[int]: ARENA_PREFIX = "strata-replicas-" +_MEMFDS: dict = {} # the memfds this server created: path (/proc//fd/) -> fd +ARENA_MIN_RAM = 8 << 30 # a memfd arena: at least this much free RAM to try (the engine reserves the real size) ARENA_MIN_FREE = 8 << 30 # /dev/shm must have at least this much free to try (the engine reserves the real size) ARENA_INCOMPATIBLE = ("--mmap-experts", "--resident-experts", "--shared-expert-arena", "--resident-budget-gib") @@ -142,8 +147,19 @@ def _free(path: str) -> int: return 0 +def _mem_available() -> int: + try: + with open("/proc/meminfo") as f: + for line in f: + if line.startswith("MemAvailable:"): + return int(line.split()[1]) * 1024 + except (OSError, ValueError, IndexError): + pass + return 0 + + def shared_arena_plan(cfg: dict, n_replicas: int, *, shm: str = "/dev/shm", platform: str | None = None, - environ=None, free_bytes=None) -> tuple[str | None, str]: + environ=None, free_bytes=None, use_memfd: bool | None = None) -> tuple[str | None, str]: """(the file for --shared-expert-arena or None, a line for the log). Opt-in: "replica_shared_arena": true (or STRATA_REPLICA_SHARED_ARENA=1). Only on Linux (the engine's MAP_SHARED backing), for Qwen's arena (not DeepSeek, not the mapped or budgeted RAM modes, which have no arena), and with room in /dev/shm. The engine checks the real @@ -164,6 +180,22 @@ def shared_arena_plan(cfg: dict, n_replicas: int, *, shm: str = "/dev/shm", plat args += [str(a) for a in e.get("args") or []] if cfg.get("arch") == "deepseek41" or any(a in args for a in ARENA_INCOMPATIBLE): return None, "shared expert arena: this model/config has no private expert arena to share; each replica as before" + if use_memfd is None: + use_memfd = hasattr(os, "memfd_create") and str(cfg.get("replica_shared_arena")).lower() != "devshm" + if use_memfd: + avail = free_bytes if free_bytes is not None else _mem_available() + if avail < ARENA_MIN_RAM: + return None, (f"shared expert arena: only {avail / 2**30:.1f} GiB of RAM is free; each replica keeps its own " + "copy of the experts in RAM") + try: + fd = os.memfd_create("strata-replicas-arena", os.MFD_CLOEXEC) + except OSError: + fd = -1 + if fd >= 0: + path = f"/proc/{os.getpid()}/fd/{fd}" + _MEMFDS[path] = fd + return path, (f"one shared expert arena for {n_replicas} replicas (memory object of the server, not limited by " + "the size of /dev/shm): the experts are in RAM once") if not (os.path.isdir(shm) and os.access(shm, os.W_OK)): return None, f"shared expert arena: {shm} is not usable; each replica keeps its own copy of the experts in RAM" free = free_bytes if free_bytes is not None else _free(shm) @@ -177,12 +209,21 @@ def shared_arena_plan(cfg: dict, n_replicas: int, *, shm: str = "/dev/shm", plat def remove_arena(path: str | None) -> None: - """Unlink the arena file (the server's end, or a start that fell back): engines that map it keep their pages.""" - if path: + """Close the memfd / unlink the arena file (the server's end, or a start that fell back): engines that map it keep + their pages.""" + if not path: + return + fd = _MEMFDS.pop(path, None) + if fd is not None: try: - os.unlink(path) + os.close(fd) except OSError: pass + return + try: + os.unlink(path) + except OSError: + pass def _suffixed(path, i: int): diff --git a/serve/test_replicas.py b/serve/test_replicas.py index 7791adbd..ae1d3e0c 100644 --- a/serve/test_replicas.py +++ b/serve/test_replicas.py @@ -317,7 +317,8 @@ class SharedArena(unittest.TestCase): def plan(self, cfg=None, n=2, tmp=None, **kw): return shared_arena_plan(cfg or self.CFG, n, shm=tmp, platform=kw.pop("platform", "linux"), - environ=kw.pop("environ", {}), free_bytes=kw.pop("free_bytes", 100 << 30), **kw) + environ=kw.pop("environ", {}), free_bytes=kw.pop("free_bytes", 100 << 30), + use_memfd=kw.pop("use_memfd", False), **kw) def test_off_by_default_and_for_one_engine(self): with tempfile.TemporaryDirectory() as d: @@ -367,6 +368,27 @@ class SharedArena(unittest.TestCase): self.assertFalse(dead.exists()) self.assertTrue(live.exists() and other.exists() and junk.exists()) + @unittest.skipUnless(hasattr(__import__("os"), "memfd_create") and sys.platform.startswith("linux"), "Linux memfd") + def test_a_memfd_is_not_limited_by_dev_shm_and_is_closed_at_the_end(self): + import os + path, note = shared_arena_plan(self.CFG, 2, platform="linux", environ={}, free_bytes=100 << 30, use_memfd=True) + self.assertTrue(path and path.startswith(f"/proc/{os.getpid()}/fd/"), path) + fd = int(path.rsplit("/", 1)[1]) + os.ftruncate(fd, 1 << 20) + self.assertEqual(os.fstat(fd).st_size, 1 << 20) + with open(path, "r+b") as other: # (how an engine opens it) + other.seek(100) + other.write(b"x") + remove_arena(path) + with self.assertRaises(OSError): + os.fstat(fd) + remove_arena(path) # (twice: harmless) + + def test_a_memfd_needs_free_ram(self): + path, note = shared_arena_plan(self.CFG, 2, platform="linux", environ={}, free_bytes=2 << 30, use_memfd=True) + self.assertIsNone(path) + self.assertIn("2.0 GiB of RAM", note) + def test_removing_twice_or_nothing_is_harmless(self): with tempfile.TemporaryDirectory() as d: f = Path(d) / "a.bin" diff --git a/src/core/expert_source.cpp b/src/core/expert_source.cpp index 583ee07f..3eee2116 100644 --- a/src/core/expert_source.cpp +++ b/src/core/expert_source.cpp @@ -20,6 +20,10 @@ #include "strata/kernels/cpu/pool.hpp" #include +#ifndef _WIN32 +#include +#include +#endif #include #include @@ -6000,6 +6004,45 @@ bool ArenaExpertSource::open(const std::string& pack_dir, int64_t n_layers, int6 const bool unbuffered = experts_unbuffered(files, want + (uint64_t) blob, why); const int readers = unbuffered ? std::max(threads, 16) : threads; // 16 keep a PCIe 5 drive's queue full LoadStats st; + // A shared arena (--shared-expert-arena, the replicas): ONE engine reads the experts into it, the others wait and skip the + // read. The state word in the file's header says who: 0 nobody, a pid loading, ~0 filled. An engine that finds a + // pid that is gone takes the load over (the previous one died mid-read: the arena is read again from the start), so a + // dead loader never leaves the others waiting, and an engine that waits too long loads it itself. + constexpr uint64_t kArenaFilled = ~uint64_t{0}; + std::atomic* arena_state = padded_ ? nullptr : a->shared_state; + bool arena_leader = false, arena_skip = false; +#ifndef _WIN32 + if (arena_state != nullptr) { + const uint64_t me = (uint64_t) getpid(); + const auto t_begin = std::chrono::steady_clock::now(); + bool said = false; + for (;;) { + uint64_t cur = arena_state->load(std::memory_order_acquire); + if (cur == kArenaFilled) { arena_skip = true; break; } + if (cur == 0 || cur == me) { + if (arena_state->compare_exchange_strong(cur, me, std::memory_order_acq_rel)) { arena_leader = true; break; } + continue; + } + const bool alive = !(kill((pid_t) cur, 0) != 0 && errno == ESRCH); + if (!alive) { + if (arena_state->compare_exchange_strong(cur, me, std::memory_order_acq_rel)) { + std::fprintf(stderr, "strata generate: shared expert arena: engine %llu died while reading it; reading it again\n", + (unsigned long long) cur); + arena_leader = true; + break; + } + continue; + } + if (std::chrono::steady_clock::now() - t_begin > std::chrono::minutes(45)) break; // (loads it on its own) + if (!said) { + said = true; + std::fprintf(stderr, "strata generate: shared expert arena: engine %llu is reading the experts; waiting for it " + "instead of reading them again\n", (unsigned long long) cur); + } + std::this_thread::sleep_for(std::chrono::milliseconds(200)); + } + } +#endif std::atomic ready{0}; std::thread reg; if (deferred) { @@ -6011,7 +6054,12 @@ bool ArenaExpertSource::open(const std::string& pack_dir, int64_t n_layers, int6 }); } const std::atomic* rp = deferred ? &ready : nullptr; - if (from_gguf) { + if (arena_skip) { + st.ok = true; + st.bytes = want; + st.seconds = 0.0; + std::fprintf(stderr, "strata generate: shared expert arena: already filled by another engine; the read is skipped\n"); + } else if (from_gguf) { st = load_experts_gguf(gguf_, a->data(), lay, readers, unbuffered, rp, padded_ ? &pad_ : nullptr); } else { if (unbuffered && !padded_) st = load_experts_direct(path, a->data(), loff, lbytes, readers, /*chunk=*/8u << 20, rp); @@ -6022,15 +6070,18 @@ bool ArenaExpertSource::open(const std::string& pack_dir, int64_t n_layers, int6 std::fprintf(stderr, "strata generate: expert arena read %s (%s)\n", unbuffered ? "unbuffered" : "through the file cache", why.c_str()); if (!st.ok) { + if (arena_leader) arena_state->store(0, std::memory_order_release); // (somebody else may try) delete a; err = "ArenaExpertSource: the expert load was refused: " + (st.error.empty() ? std::string("unknown") : st.error); return false; } if (st.bytes != want) { + if (arena_leader) arena_state->store(0, std::memory_order_release); delete a; err = "ArenaExpertSource: the load read " + std::to_string(st.bytes) + " B of " + std::to_string(want); return false; } + if (arena_leader) arena_state->store(kArenaFilled, std::memory_order_release); // the others may use (and skip reading) it if (std::getenv("STRATA_VERIFY_ARENA") != nullptr) { // tests: the loaded arena's checksum, any loader std::fprintf(stderr, "strata generate: expert arena checksum %016llx (%.2f GiB)\n", (unsigned long long) fnv1a64(a->data(), want), (double) want / (1ull << 30)); diff --git a/src/core/pinned.cu b/src/core/pinned.cu index ae6b9bbd..468971c4 100644 --- a/src/core/pinned.cu +++ b/src/core/pinned.cu @@ -2,6 +2,7 @@ #include "strata/core/pinned.hpp" #include "strata/platform/memory.hpp" #include "strata/core/pin_budget.hpp" +#include #include @@ -57,6 +58,45 @@ struct SharedArenaHeader { }; static_assert(sizeof(SharedArenaHeader) <= kSharedArenaHeaderBytes); +#ifndef _WIN32 +// MemAvailable and, in a cgroup v2 group with a limit, the room left under it; ~0 when neither can be read +uint64_t free_ram_room() { + uint64_t room = ~uint64_t{0}; + if (std::FILE* f = std::fopen("/proc/meminfo", "r")) { + char line[256]; + while (std::fgets(line, sizeof line, f) != nullptr) { + unsigned long long kb = 0; + if (std::sscanf(line, "MemAvailable: %llu kB", &kb) == 1) { room = (uint64_t) kb * 1024u; break; } + } + std::fclose(f); + } + std::string cg; + if (std::FILE* f = std::fopen("/proc/self/cgroup", "r")) { + char line[512]; + while (std::fgets(line, sizeof line, f) != nullptr) + if (std::strncmp(line, "0::", 3) == 0) { cg = line + 3; break; } + std::fclose(f); + } + while (!cg.empty() && (cg.back() == '\n' || cg.back() == '\r')) cg.pop_back(); + if (!cg.empty()) { + unsigned long long lim = 0, cur = 0; + bool have_lim = false; + if (std::FILE* f = std::fopen(("/sys/fs/cgroup" + cg + "/memory.max").c_str(), "r")) { + have_lim = std::fscanf(f, "%llu", &lim) == 1; // ("max" does not parse: no limit) + std::fclose(f); + } + if (have_lim) { + if (std::FILE* f = std::fopen(("/sys/fs/cgroup" + cg + "/memory.current").c_str(), "r")) { + if (std::fscanf(f, "%llu", &cur) != 1) cur = 0; + std::fclose(f); + } + room = std::min(room, lim > cur ? (uint64_t) (lim - cur) : 0); + } + } + return room; +} +#endif + #ifndef _WIN32 // bytes in free blocks of 2 MiB or more (/proc/buddyinfo, order >= 9): what MADV_HUGEPAGE can get without compaction uint64_t free_huge_bytes() { @@ -247,6 +287,21 @@ void* reserve(uint64_t bytes, PageBacking& got, std::string& note, const std::st { struct statfs sf{}; if (fstatfs(fd, &sf) == 0 && (unsigned long) sf.f_type == 0x01021994ul) { + // a memfd (or any tmpfs file not capped by a mount size) would take the RAM and then the OOM killer: check the + // free RAM and the cgroup's room for the pages that are not there yet before taking them + struct stat st2{}; + const uint64_t have = fstat(fd, &st2) == 0 ? (uint64_t) st2.st_blocks * 512u : 0; + const uint64_t need = file_bytes > have ? file_bytes - have : 0; + if (need > 0) { + const uint64_t room = free_ram_room(); + if (room != ~uint64_t{0} && need + (2ull << 30) > room) { + close(fd); + note = "not enough free RAM for the shared arena " + shared_file + ": it needs " + + std::to_string((unsigned long long) (need >> 20)) + " MiB more and " + + std::to_string((unsigned long long) (room >> 20)) + " MiB are free (2 GiB are kept back)"; + return nullptr; + } + } const int fe = posix_fallocate(fd, 0, (off_t) file_bytes); if (fe != 0 && fe != EOPNOTSUPP && fe != EINVAL) { close(fd); @@ -446,6 +501,9 @@ PinnedArena::PinnedArena(uint64_t bytes, const std::vector& bounds, uint64_t shared_pack_hash) : capacity(bytes) { if (bytes == 0) return; base = reserve(bytes, backing, note, shared_file, shared_pack_hash, mapping_base, mapping_bytes); + if (!shared_file.empty() && base != nullptr && mapping_base != nullptr) + shared_state = reinterpret_cast*>(static_cast(mapping_base) + + offsetof(SharedArenaHeader, reserved)); if (base != nullptr && mapping_base == nullptr) { mapping_base = base; mapping_bytes = bytes; @@ -565,6 +623,9 @@ PinnedArena::PinnedArena(uint64_t bytes, ByNeed, const std::vector*>(static_cast(mapping_base) + + offsetof(SharedArenaHeader, reserved)); if (base != nullptr && mapping_base == nullptr) { mapping_base = base; mapping_bytes = bytes;