Skip to content

Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.

C++

The expert arena checks the host RAM before it is allocated; the RAM probe reads cgroup v1 too (#633)

Niko122116a6d77ed48e
diff --git a/include/strata/core/expert_source.hpp b/include/strata/core/expert_source.hpp
index 3fe753f23..0872f49a2 100644
--- a/include/strata/core/expert_source.hpp
+++ b/include/strata/core/expert_source.hpp
@@ -65,6 +65,22 @@ struct CgroupMemoryStat {
/// Returns false when the required memory.stat counters were unavailable.
bool cgroup_available_bytes(uint64_t limit, const CgroupMemoryStat& stat, uint64_t& bytes);
+/// #633: the RAM this process can get. `available`: MemAvailable (Windows: the available physical memory), lowered
+/// to the room under the tightest cgroup limit; `cgroup_limit`: that tightest limit itself (v2 memory.max of the group
+/// and its ancestors, or v1 memory.limit_in_bytes), ~0 when there is none - what a container can never exceed.
+struct HostMemory {
+ uint64_t available = 0;
+ uint64_t cgroup_limit = ~uint64_t{0};
+};
+
+/// Linux reads `meminfo`, `self_cgroup` and the cgroup tree under `cgroup_root` (the parameters are for tests; the
+/// defaults are the real files). cgroup v2 as before (an unreadable limit of a group that has one fails); cgroup v1's
+/// memory controller (`<root>/memory/<path>`: memory.limit_in_bytes - memory.usage_in_bytes); no cgroup line at all is
+/// MemAvailable alone. False when the RAM cannot be determined.
+bool host_available_memory(HostMemory& m, const std::string& meminfo = "/proc/meminfo",
+ const std::string& self_cgroup = "/proc/self/cgroup",
+ const std::string& cgroup_root = "/sys/fs/cgroup");
+
/// Build compact offsets for experts absent from both the primary GPU cache and an optional second GPU tier.
/// Kept CPU-only so selection and byte accounting can be tested without initializing a GPU.
bool make_cache_complement_plan(
@@ -652,6 +668,8 @@ public:
/// What backing was obtained and why, for the startup print. "The engine adapts to the machine it is on" is
/// only true if the engine says what it got.
const std::string& note() const { return note_; }
+ /// #633: set by `open` when the RAM available is less than the arena needs (a recommendation; it still loads)
+ const std::string& ram_warning() const { return ram_warning_; }
double load_gib_per_second() const { return gib_per_s_; }
// Loader fix: the load, split. `load_seconds()` is the wall clock of the load loop; the other two are
// sums over the reader threads (see LoadStats), so on their own they say how much of that wall was spent
@@ -669,6 +687,7 @@ private:
int64_t n_expert_ = 0;
int64_t reads_ = 0;
std::string note_;
+ std::string ram_warning_;
double gib_per_s_ = 0.0;
double load_seconds_ = 0.0;
double load_read_s_ = 0.0;
diff --git a/src/core/expert_source.cpp b/src/core/expert_source.cpp
index bb3badfcc..ee759515b 100644
--- a/src/core/expert_source.cpp
+++ b/src/core/expert_source.cpp
@@ -217,18 +217,25 @@ bool read_cgroup_memory_stat(const std::filesystem::path& path, uint64_t current
}
#endif
-bool available_memory_bytes(uint64_t& bytes) {
+} // namespace
+
+namespace detail {
+
+bool host_available_memory(HostMemory& m, const std::string& meminfo, const std::string& self_cgroup,
+ const std::string& cgroup_root) {
+ m = HostMemory{};
#if defined(_WIN32)
+ (void) meminfo; (void) self_cgroup; (void) cgroup_root;
MEMORYSTATUSEX status{};
status.dwLength = sizeof(status);
if (!GlobalMemoryStatusEx(&status)) return false;
- bytes = (uint64_t) status.ullAvailPhys;
- return bytes > 0;
+ m.available = (uint64_t) status.ullAvailPhys;
+ return m.available > 0;
#elif defined(__linux__)
// MemAvailable includes reclaimable page cache, unlike _SC_AVPHYS_PAGES.
- std::ifstream info("/proc/meminfo");
+ std::ifstream info(meminfo);
std::string line;
- bytes = 0;
+ uint64_t bytes = 0;
while (std::getline(info, line)) {
std::istringstream fields(line);
std::string key, unit;
@@ -237,17 +244,26 @@ bool available_memory_bytes(uint64_t& bytes) {
value <= std::numeric_limits<uint64_t>::max() / 1024) bytes = value * 1024;
}
if (bytes == 0) return false;
- // Account for the tightest cgroup-v2 ancestor limit when its normal mount is visible.
+ // Account for the tightest cgroup ancestor limit when its normal mount is visible.
// This is a point-in-time guard, not a reservation against concurrent allocations.
- std::ifstream groups("/proc/self/cgroup");
+ std::ifstream groups(self_cgroup);
if (!groups) return false;
- bool resolved_v2 = false;
+ const std::filesystem::path root(cgroup_root);
+ bool v2 = false;
+ std::string v1_path; // the memory controller's group (cgroup v1), when there is no v2 line
while (std::getline(groups, line)) {
- if (line.rfind("0::/", 0) != 0) continue;
- const std::filesystem::path root("/sys/fs/cgroup");
+ if (line.rfind("0::/", 0) != 0) {
+ // v1: "N:controller[,controller]:/path"
+ const size_t c1 = line.find(':'), c2 = c1 == std::string::npos ? c1 : line.find(':', c1 + 1);
+ if (c2 == std::string::npos) continue;
+ std::istringstream ctl(line.substr(c1 + 1, c2 - c1 - 1));
+ for (std::string c; std::getline(ctl, c, ',');)
+ if (c == "memory") v1_path = line.substr(c2 + 1);
+ continue;
+ }
auto path = (root / line.substr(4)).lexically_normal();
if (path.string().rfind(root.string(), 0) != 0 || !std::filesystem::is_directory(path)) return false;
- resolved_v2 = true;
+ v2 = true;
while (path.string().rfind(root.string(), 0) == 0) {
std::ifstream limit_file(path / "memory.max"), current_file(path / "memory.current");
std::string limit;
@@ -261,28 +277,59 @@ bool available_memory_bytes(uint64_t& bytes) {
size_t consumed = 0;
const uint64_t cap = std::stoull(limit, &consumed);
if (consumed != limit.size()) return false;
- detail::CgroupMemoryStat stat;
+ CgroupMemoryStat stat;
if (!read_cgroup_memory_stat(path, current, stat)) return false;
uint64_t cgroup_available = 0;
- if (!detail::cgroup_available_bytes(cap, stat, cgroup_available)) return false;
+ if (!cgroup_available_bytes(cap, stat, cgroup_available)) return false;
bytes = std::min(bytes, cgroup_available);
+ m.cgroup_limit = std::min(m.cgroup_limit, cap);
} catch (...) { return false; }
}
if (path == root) break;
path = path.parent_path();
}
}
- return resolved_v2;
+ if (!v2 && !v1_path.empty()) {
+ // #633: cgroup v1 (older Docker hosts, RHEL 7/8): the memory controller's group and its ancestors. An
+ // unlimited group says a number near 2^63 (rounded to its page size); a group whose files are not
+ // visible (no mount in this namespace) is skipped - MemAvailable alone, as with no cgroup at all.
+ const std::filesystem::path mroot = root / "memory";
+ auto path = (mroot / v1_path.substr(v1_path.rfind('/', 0) == 0 ? 1 : 0)).lexically_normal();
+ while (path.string().rfind(mroot.string(), 0) == 0) {
+ std::ifstream limit_file(path / "memory.limit_in_bytes"), usage_file(path / "memory.usage_in_bytes");
+ uint64_t cap = 0, usage = 0;
+ if (limit_file >> cap && usage_file >> usage && cap < (1ull << 62)) {
+ bytes = std::min(bytes, usage < cap ? cap - usage : 0);
+ m.cgroup_limit = std::min(m.cgroup_limit, cap);
+ }
+ if (path == mroot) break;
+ path = path.parent_path();
+ }
+ }
+ m.available = bytes;
+ return true;
#else
+ (void) meminfo; (void) self_cgroup; (void) cgroup_root;
const long pages = sysconf(_SC_AVPHYS_PAGES);
const long page_bytes = sysconf(_SC_PAGESIZE);
if (pages <= 0 || page_bytes <= 0 ||
(uint64_t) pages > std::numeric_limits<uint64_t>::max() / (uint64_t) page_bytes) return false;
- bytes = (uint64_t) pages * (uint64_t) page_bytes;
- return bytes > 0;
+ m.available = (uint64_t) pages * (uint64_t) page_bytes;
+ return m.available > 0;
#endif
}
+} // namespace detail
+
+namespace {
+
+bool available_memory_bytes(uint64_t& bytes) {
+ detail::HostMemory m;
+ if (!detail::host_available_memory(m)) return false;
+ bytes = m.available;
+ return bytes > 0;
+}
+
} // namespace
// ================================ THE FILE-BACKED SOURCE ================================
@@ -2633,6 +2680,37 @@ bool ArenaExpertSource::open(const std::string& pack_dir, int64_t n_layers, int6
}
}
+ // #633: THE RAM BEFORE THE ALLOCATION. On Linux the arena is an anonymous mapping that succeeds whatever the host
+ // has; its pages are committed as the load writes them, so a container whose memory limit is below the arena was
+ // killed by the OOM killer part-way through the load, without a message. A hard cgroup limit below it is
+ // certain to end that way: refused, with the numbers. Less RAM available than the arena (another program, an
+ // engine still exiting) is only a warning - the OS may make room - per the recommend-not-force rule.
+ ram_warning_.clear();
+ // (a shared arena, --shared-expert-arena, may already be in RAM for another engine: not checked)
+ if (detail::HostMemory hm; shared_arena_file.empty() && detail::host_available_memory(hm)) {
+ const uint64_t need = want + (uint64_t) blob;
+ const double gib = 1073741824.0;
+ char buf[512];
+ if (hm.cgroup_limit < need) {
+ std::snprintf(buf, sizeof buf,
+ "ArenaExpertSource: the expert arena needs %.2f GiB of RAM but this process's memory limit "
+ "(cgroup memory.max / memory.limit_in_bytes) is %.2f GiB: it would be killed while loading. "
+ "Raise the container's limit, or run with less RAM: --mmap-experts with "
+ "--resident-budget-gib N keeps only the hottest experts in RAM",
+ (double) need / gib, (double) hm.cgroup_limit / gib);
+ err = buf;
+ return false;
+ }
+ if (hm.available < need) {
+ std::snprintf(buf, sizeof buf,
+ "the expert arena needs %.2f GiB of RAM but %.2f GiB is available (%.2f GiB short): the load "
+ "may swap or be stopped by the OS. Close other programs (or wait for an engine that is "
+ "still exiting), or run with less RAM: --mmap-experts with --resident-budget-gib N",
+ (double) need / gib, (double) hm.available / gib, (double) (need - hm.available) / gib);
+ ram_warning_ = buf;
+ }
+ }
+
uint64_t pack_hash = 0;
if (!shared_arena_file.empty() &&
!shared_arena_pack_hash(pack_dir, path, gguf_, lay, pack_hash, err)) return false;
diff --git a/src/program/generate.cpp b/src/program/generate.cpp
index 593825410..e71a3e8db 100644
--- a/src/program/generate.cpp
+++ b/src/program/generate.cpp
@@ -2893,6 +2893,8 @@ int main(int argc, char** argv) {
std::fprintf(stderr, "strata generate: %s\n", err.c_str());
return 1;
}
+ if (!arena_src.ram_warning().empty()) // #633: said before the load's numbers, which it explains
+ std::fprintf(stderr, "strata generate: WARNING: %s\n", arena_src.ram_warning().c_str());
std::fprintf(stderr, "strata generate: expert arena: %s\n", arena_src.note().c_str());
std::fprintf(stderr, "strata generate: loaded %.2f GiB at %.2f GiB/s\n",
(double) strata::kernels::cpu::expert_layout().total / (1024.0 * 1024 * 1024),
diff --git a/tests/core/file_expert_source_test.cpp b/tests/core/file_expert_source_test.cpp
index e86acc164..104507d13 100644
--- a/tests/core/file_expert_source_test.cpp
+++ b/tests/core/file_expert_source_test.cpp
@@ -288,6 +288,56 @@ void test_cgroup_memory_budget() {
"missing memory.stat counters did not fail closed");
}
+// #633: the host RAM probe with fake /proc and cgroup trees: v2 (a limit, "max", a missing or malformed limit), v1
+// (a limit, unlimited), and no cgroup line at all. Elsewhere than Linux it reads the machine's RAM.
+void test_host_memory() {
+ using namespace strata::core::detail;
+ constexpr uint64_t GiB = 1ull << 30;
+ HostMemory m;
+#if defined(__linux__)
+ TempDirectory t;
+ auto put = [&](const fs::path& rel, const std::string& text) {
+ fs::create_directories((t.path / rel).parent_path());
+ std::ofstream(t.path / rel) << text;
+ };
+ put("meminfo", "MemTotal: 134217728 kB\nMemAvailable: 104857600 kB\n"); // 100 GiB available
+ const std::string mi = (t.path / "meminfo").string(), cg = (t.path / "cgroup").string(),
+ root = (t.path / "fs").string();
+ auto probe = [&](const std::string& self) {
+ put("cgroup", self);
+ return host_available_memory(m, mi, cg, root);
+ };
+ // no cgroup line at all: MemAvailable alone (before #633: "cannot determine")
+ require(probe("") && m.available == 100 * GiB && m.cgroup_limit == ~0ull, "no cgroup: MemAvailable alone");
+ // v2, a 48 GiB limit with 16 GiB charged, 4 GiB of it clean cache
+ put("fs/cgroup.controllers", "memory\n");
+ 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");
+ 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");
+ require(!probe("0::/box\n"), "v2 malformed limit accepted");
+ fs::remove(t.path / "fs/box/memory.max");
+ require(!probe("0::/box\n"), "v2 group without memory.max accepted");
+ // v1: the memory controller's group (a hybrid line list), a 32 GiB limit with 10 GiB used
+ put("fs/memory/docker/abc/memory.limit_in_bytes", std::to_string(32 * GiB) + "\n");
+ put("fs/memory/docker/abc/memory.usage_in_bytes", std::to_string(10 * GiB) + "\n");
+ put("fs/memory/memory.limit_in_bytes", "9223372036854771712\n"); // the root: unlimited
+ put("fs/memory/memory.usage_in_bytes", std::to_string(50 * GiB) + "\n");
+ require(probe("12:cpu,cpuacct:/docker/abc\n4:memory:/docker/abc\n1:name=systemd:/docker/abc\n") &&
+ m.available == 22 * GiB && m.cgroup_limit == 32 * GiB, "v1 limit");
+ put("fs/memory/docker/abc/memory.limit_in_bytes", "9223372036854771712\n");
+ require(probe("4:memory:/docker/abc\n") && m.available == 100 * GiB && m.cgroup_limit == ~0ull, "v1 unlimited");
+ // a v1 group not visible here (another namespace): MemAvailable alone
+ require(probe("4:memory:/elsewhere\n") && m.available == 100 * GiB, "v1 group not mounted");
+#else
+ require(host_available_memory(m) && m.available > 0 && m.cgroup_limit == ~0ull, "this PC's RAM");
+ (void) GiB;
+#endif
+}
+
} // namespace
int main() {
@@ -296,6 +346,7 @@ int main() {
test_resident_lend_region();
test_resident_exchange();
test_cgroup_memory_budget();
+ test_host_memory();
test_canonical_layout();
#if defined(STRATA_NATIVE_EXPERTS)
test_native_variable_layout();