diff --git a/metal/setup_mac.py b/metal/setup_mac.py index d75d47d5..f263809a 100644 --- a/metal/setup_mac.py +++ b/metal/setup_mac.py @@ -18,6 +18,7 @@ Everything shared - the model table, the downloader, the config and run-script w from __future__ import annotations import argparse +import atexit import hashlib import json import os @@ -97,6 +98,14 @@ OVERHEAD_GB = 8.0 # the share of the unified memory Metal lets one process keep resident (recommendedMaxWorkingSetSize): 107.5 of 128 GB # measured on the M5 Max; 3/4 is the conservative rule for the other sizes GPU_SHARE = 0.75 +# what a Mac of BIG_MAC_GB or more leaves to macOS, its file cache and the user's other programs when the pack stays RESIDENT +# (the engine's resident_cap in arena_budget.h, the same rule). A resident pack is mapped file pages: clean, so macOS can +# drop them, never compress them. Measured on the 128 GB M5 Max, UD-Q4_K_XL resident (wired 91.7 GB, 67%) with a 40 GB file +# write and a 16 GB program beside it: no swap-out, nothing compressed. (The streaming arena is anonymous memory and gets a +# tighter cap in the engine: 40% left, from the same measurements.) +RESIDENT_LEAVE_SHARE = 0.30 +BIG_MAC_GB = 64.0 +GIB_GB = 1.073741824 # a GiB in GB: ram_gb is binary, the model sizes are decimal CONTEXTS = [8192, 32768, 65536, 131072] MAC_ABOUT = {"Q2_0": "2-bit, the fastest", "IQ3_XXS": "3-bit i-quant, better quality", "IQ3_S": "3.5-bit i-quant, the best quality (matches the full model), the slowest", @@ -155,7 +164,12 @@ def mac_problems(info: dict) -> list[str]: def gpu_budget_gb(ram_gb: float) -> float: - return ram_gb * GPU_SHARE + """The most a resident pack may hold, in GB: Metal's working set, and on a big Mac the RAM less what macOS and the file + cache keep (the engine's resident_cap: min of the two).""" + ws = ram_gb * GPU_SHARE * GIB_GB + if ram_gb >= BIG_MAC_GB: + return min(ws, ram_gb * GIB_GB * (1.0 - RESIDENT_LEAVE_SHARE)) + return ws def model_need_gb(model: str) -> float: @@ -398,12 +412,62 @@ def mac_configs() -> list[Path]: return out +REPACK_LOCK = ".repack.lock" # metal_repack.py: .repack.lock holds the repack's pid while it runs +PREPARE_LOCK = ".preparing.lock" # setup: beside the repacked file, holds setup's pid from the repack to the end of the pack + + +def _pid_alive(pid: int) -> bool: + try: + os.kill(pid, 0) + except PermissionError: + return True # it exists, it is somebody else's + except OSError: + return False + return True + + +def repack_running(folder: Path) -> list[int]: + """Pids of repacks (metal_repack.py) or setup's own model preparation (repack + pack) still running for the files in + `folder`. A stale lock (its process gone) is removed. The repack and the pack move 100+ GB through the disk and one + holds up to 20 GB of memory: an engine with a 70-90 GB footprint beside them is what froze the 128 GB M5 Max twice + (watchdog panics, 2026-10-13).""" + pids = [] + if not folder.is_dir(): + return pids + for lock in [*folder.glob("*" + REPACK_LOCK), folder / PREPARE_LOCK]: + try: + pid = int(lock.read_text().strip()) + except (OSError, ValueError): + continue + if pid != os.getpid() and _pid_alive(pid): + pids.append(pid) + elif pid != os.getpid(): + try: + lock.unlink() + except OSError: + pass + return pids + + +def engine_pids(run=subprocess.run) -> list[int]: + """Pids of the running Metal engines (`strata`, the executable setup builds).""" + try: + out = run(["pgrep", "-x", "strata"], capture_output=True, text=True, timeout=10).stdout + except (OSError, subprocess.SubprocessError): + return [] + return [int(x) for x in out.split() if x.isdigit() and int(x) != os.getpid()] + + def start(cfg_path: Path, port: int | None, open_browser: bool = True) -> int: """serve/server.py with this config (setup.py's start without the NVIDIA / AMD card checks).""" cfg = json.loads(cfg_path.read_text(encoding="utf-8-sig")) missing = [p for p in [cfg["exe"], *[a for a in cfg["args"] if a.endswith(".gguf")]] if not Path(p).exists()] if missing: S.fail(f"{cfg_path.name} refers to missing files: {missing[0]}", "run ./setup.sh --setup to repair it") + busy = [p for g in cfg["args"] if g.endswith(".gguf") for p in repack_running(Path(g).parent)] + if busy: # never start an engine while a repack (or the pack after it) is writing: wait would hide a stuck one + S.fail(f"a model repack is still running here (pid {busy[0]}): the engine is not started beside it", + "wait for it to finish (or stop it), then start again") cfg_path.touch() if "--mtp" in cfg["args"][:-1]: S.refresh_draft_vocab(Path(cfg["args"][cfg["args"].index("--mtp") + 1]), cfg.get("draft_vocab", "cjk")) @@ -543,6 +607,22 @@ def main(argv=None) -> int: S.step(6, "preparing the model for Strata") pack = S.find_in(roots, f"packs/{tag.lower()}") or data / "packs" / tag.lower() env = dict(os.environ, STRATA_GGUF_PY=str(llama / "gguf-py")) + # The repack and the pack move 100+ GB through the disk and the pack's python holds up to 20 GB: no engine may run beside + # them (an engine of 70-90 GB with a repack froze the 128 GB M5 Max twice). A lock beside the GPU's file tells the engine + # and start() to wait; a running engine stops setup here. + lock_dir = data / "metal" if len(files) > 2 else files[0].parent + native0 = data / "metal" / f"{tag.lower()}-metal.gguf" + work = (len(files) > 2 and not (native0.exists() and S.done(native0))) or \ + not ((pack / "native_experts.txt").exists() and (pack / "tokenizer" / "vocab.json").exists()) + prep_lock = lock_dir / PREPARE_LOCK + if work: + running = engine_pids() + if running: + S.fail(f"a Strata engine is running (pid {running[0]}): preparing a model beside it can freeze this Mac", + "stop the server (close its window), then run ./setup.sh --setup again") + lock_dir.mkdir(parents=True, exist_ok=True) + prep_lock.write_text(str(os.getpid())) + atexit.register(lambda: prep_lock.unlink() if prep_lock.exists() else None) if len(files) > 2: # many shards: the experts and dense tensors into one GGUF the GPU maps (or streams), the n-gram table read # from its own shard (every tensor checked byte for byte: --verify) @@ -562,6 +642,7 @@ def main(argv=None) -> int: S.run([sys.executable, str(ROOT / "tools" / "iq_pack.py"), "--gguf", str(shards[0]), "--out", str(pack), *fam.get("pack_args", [])], env=env) # Unsloth: --compat-bf16 (the host's copies; the GPU reads the file) S.ok(f"model prepared: {pack}") + prep_lock.unlink(missing_ok=True) mtp = (S.find_in(roots, "mtp/mtp-q2_0.gguf") or data / "mtp" / "mtp-q2_0.gguf").parent rt = mtp / "rt" stream = streams(model, info["ram_gb"]) diff --git a/metal/src/engine/arena_budget.h b/metal/src/engine/arena_budget.h index fbb1c221..bdf7e0c6 100644 --- a/metal/src/engine/arena_budget.h +++ b/metal/src/engine/arena_budget.h @@ -1,8 +1,8 @@ -// metal/src/engine/arena_budget.h - how big the SSD-streaming expert arena may be (stream.h), as plain arithmetic so it -// can be tested without a Mac (metal/tests/arena_budget_test.cpp). +// metal/src/engine/arena_budget.h - how big the SSD-streaming expert arena may be (stream.h), and how much the engine may +// hold resident in all, as plain arithmetic so it can be tested without a Mac (metal/tests/arena_budget_test.cpp). // -// The arena is anonymous memory the GPU keeps resident: macOS cannot page it out or drop it like file cache. It must -// leave room for macOS and the desktop, and for the other big memory the engine itself uses while it runs: +// The arena is anonymous memory the GPU needs resident while a command buffer runs. It must leave room for macOS and the +// desktop, and for the other big memory the engine itself uses while it runs: // keep macOS and the desktop: max(7 GB, 15% of the RAM) - STRATA_METAL_KEEP_FREE_GB sets it. The M5 Max // (128 GB) froze with an 89 GB arena and 7 GB kept beside a 50 GB n-gram table; with 15% it keeps 20.6 GB. // The 32 GB M4 (IQ3_XXS after a 6K prompt, 5 interleaved runs, memory_pressure every 3 s, vm_stat @@ -12,18 +12,24 @@ // ple the n-gram table: mapped whole in RAM (--ple-io ram) it is all of it; read row by row (the default, // F_NOCACHE: no file cache) only its bounded row cache, 1M rows of at most 192 bytes: 0.5 GB reserved. // GPU the Metal working set less what is already allocated, less 1 GB. -// STRATA_METAL_ARENA_GB sets the arena outright. The arena is placed just before it is filled, and the memory macOS -// can give is asked again then: when it has dropped (another program), the arena shrinks (arena_shrink). +// footprint the engine's WHOLE anonymous footprint - arena + every Metal buffer + what the process holds beside them +// (host memory) - stays under footprint_cap() (below): on a big Mac 60% of the RAM. The 67% rule it replaces +// counted only the Metal buffers (cx.allocated(), 7.5 GB) while the process held 11-15 GB, and 67% was too +// much anyway (see kLeaveShare). +// STRATA_METAL_ARENA_GB sets the arena outright (the engine says when that goes over the cap; it is the user's choice). +// The arena is placed just before it is filled, and the memory macOS can give is asked again then: when it has dropped +// (another program), the arena shrinks (arena_shrink). // "Available" (arena_avail) counts free and purgeable pages and the file cache macOS drops without writing anything: // inactive pages, but no more of them than there are file-backed pages. Inactive anonymous memory (other programs') // is left out: macOS frees it only by compressing or swapping it (the soak's 93 MB swapped out while an arena planned // with every inactive page filled). Free + purgeable alone is too little: at the engine's start the model file's own -// pages fill the cache (6.4 GB free + purgeable on the 32 GB M4 against 15 GB a minute later). The arena is filled in steps (STRATA_METAL_ARENA_STEP_GB, default 1.5): before each step the free -// memory is asked again, and the fill stops - the rest of the arena's slots unused - when a step would take macOS -// below what it keeps (arena_grow). +// pages fill the cache (6.4 GB free + purgeable on the 32 GB M4 against 15 GB a minute later). The arena is filled in +// steps (STRATA_METAL_ARENA_STEP_GB, default 1.5): before each step the free memory is asked again, and the fill stops - +// the rest of the arena's slots unused - when a step would take macOS below what it keeps (arena_grow). #pragma once #include +#include namespace strata::metal_engine { @@ -33,17 +39,61 @@ struct ArenaMem { double allocated = 0; // already allocated by the engine (Metal buffers) double available = 0; // what macOS can give now without paging anything out (arena_avail) double ple_mapped = 0; // the n-gram table's bytes when it is mapped whole in RAM, else 0 + double proc_footprint = 0; // what the process holds right now, whatever it is (task_info phys_footprint); 0: unknown + double filecache_min = 0; // sysctl vm.vm_page_filecache_min in bytes: the file cache macOS keeps before it compresses (0: unknown) double keep_gb = -1; // STRATA_METAL_KEEP_FREE_GB (< 0: unset) double arena_gb = -1; // STRATA_METAL_ARENA_GB (< 0: unset) + double leave_share = -1; // STRATA_METAL_LEAVE_SHARE: the share of the RAM a big Mac leaves to macOS (< 0: kLeaveShare) }; constexpr double kGB = 1e9; -// The GPU keeps the whole arena (and the engine's other buffers) resident through a residency set, i.e. wired. Measured on the -// M5 Max (137.4 GB), UD-Q6_K_XL: 84 GB of arena + 7.5 GB allocated (91.5 GB, 67%) ran with no swap-out; 90 GB + 7.5 GB (97.5 GB) -// made macOS swap 29,000 pages in 8 s with a "warn" pressure level and the Mac went on to freeze; UD-Q5 with 90 GB + 5.7 GB ran, -// near the edge. So arena + allocated stay under this share of the RAM, whatever the free-memory count says. -constexpr double kWiredShare = 0.67; +// Why a cap at all. macOS keeps a floor of file cache (vm.vm_page_filecache_min: 37.2 GB, 27% of the 128 GB M5 Max) and, +// when anonymous memory wants more than the rest, compresses the anonymous pages (then swaps) instead of dropping file +// cache below it. The arena is anonymous and the GPU wires it only while a command buffer runs: while it is being filled, +// or idle, it is ordinary pageable memory. Measured on the M5 Max (UD-Q6_K_XL streaming, memwatch every second): +// the old build, a 100 GB arena (what it planned after a fresh boot): 19 GB of the arena compressed in 7 s, 29,000 pages +// swapped out, pressure "warn" - the signature of the two panics (compressor at 3.9M pages, free memory 13 MB, the +// engine 95.3 and 89.9 GiB resident, watchdogd starved for 92 s); +// the old build, auto arena 69 GB, a 40 GB file write and a 16 GB program beside it: compressor 21k -> 4.07M pages in +// 10 s, swapouts +29,000, pressure warn (stopped by the watchdog); +// footprint cap at 70% of the RAM (wired 94.5 GB), 40 GB file write: compressor 1.8M pages, swapouts +12,000, stopped; +// 35% left (89 GB): clear with the write alone (compressor 0.28M pages, 316 pages swapped), not with more beside it; +// 40% left (cap 82.5 GB, footprint 77 GB): 40 GB write + 16 GB program, swapouts 0, compressor 0.3M pages, decode and +// prompt speed equal to the 80 GB arena's (51 tok/s story, 1,020 tok/s for 15K). +// A pack that stays RESIDENT is different: its bytes are clean file pages (macOS drops them, never compresses them) and they +// count as file cache, not against the floor. UD-Q4_K_XL resident on the M5 Max (wired 91.7 GB, 67%), 40 GB write + 16 GB +// program beside it: swapouts 0, compressor 5,500 pages, 63 tok/s. So two caps: +// footprint_cap anonymous memory (the streaming arena, Metal buffers, host memory): kLeaveShare = 40% of the RAM left +// on a big Mac (at least the file-cache floor + 12 GB) +// resident_cap a resident pack's mapped bytes: kResidentLeaveShare = 30% left (the old rule, measured as above) +constexpr double kLeaveShare = 0.40; +constexpr double kResidentLeaveShare = 0.30; +constexpr double kBigMac = 64.0 * kGB; +constexpr double kFileCacheHeadroom = 12.0 * kGB; // beside the file-cache floor: macOS itself (~6 GB) and one more program + +inline double arena_keep(const ArenaMem& m) { + return m.keep_gb >= 0 ? m.keep_gb * kGB : std::max(7.0 * kGB, 0.15 * m.phys); +} + +/// The most the engine may hold as anonymous memory, all counted (arena + Metal buffers + host memory). +inline double footprint_cap(const ArenaMem& m) { + const double share = m.leave_share >= 0 ? m.leave_share : kLeaveShare; + double leave = arena_keep(m); + if (m.phys >= kBigMac) leave = std::max({leave, share * m.phys, m.filecache_min > 0 ? m.filecache_min + kFileCacheHeadroom : 0.0}); + return std::min(m.working_set, m.phys - leave); +} + +/// The most a resident pack (its mapped bytes + the engine's buffers) may hold. +inline double resident_cap(const ArenaMem& m) { + double leave = arena_keep(m); + if (m.phys >= kBigMac) leave = std::max(leave, kResidentLeaveShare * m.phys); + return std::min(m.working_set, m.phys - leave); +} + +/// What the engine holds before the arena: the Metal buffers (alloc + wrap) or, when the process holds more, all of it +/// (host memory, mapped tables). +inline double footprint_base(const ArenaMem& m) { return std::max(m.allocated, m.proc_footprint); } /// Bytes macOS can give without compressing or swapping: free + purgeable + the clean file cache (inactive and /// speculative pages, at most the file-backed ones). @@ -51,19 +101,39 @@ inline double arena_avail(double free_b, double purgeable_b, double inactive_b, return free_b + purgeable_b + std::min(inactive_b + speculative_b, file_b); } -inline double arena_keep(const ArenaMem& m) { - return m.keep_gb >= 0 ? m.keep_gb * kGB : std::max(7.0 * kGB, 0.15 * m.phys); -} - inline double arena_ple_reserve(const ArenaMem& m) { return m.ple_mapped > 0 ? m.ple_mapped : 0.5 * kGB; } /// The arena's bytes (at least 1 GB: a smaller arena still runs, at a low hit rate). inline double arena_budget(const ArenaMem& m) { if (m.arena_gb >= 0) return m.arena_gb * kGB; - const double gpu = m.working_set - m.allocated - 1.0 * kGB; + const double gpu = m.working_set - footprint_base(m) - 1.0 * kGB; const double ram = m.available - arena_keep(m) - arena_ple_reserve(m); - const double wired = kWiredShare * m.phys - m.allocated; - return std::max(1.0 * kGB, std::min(std::min(gpu, ram), wired)); + const double foot = footprint_cap(m) - footprint_base(m) - arena_ple_reserve(m); // the whole footprint under the cap + return std::max(1.0 * kGB, std::min(std::min(gpu, ram), foot)); +} + +/// The plan as numbers, for the log line and the tests: what the engine will hold with `arena` bytes of arena. +struct FootprintPlan { + double arena = 0, base = 0, ple = 0, total = 0, cap = 0; + bool over() const { return total > cap + 1e6; } +}; +inline FootprintPlan footprint_plan(const ArenaMem& m, double arena) { + FootprintPlan p; + p.arena = arena; + p.base = footprint_base(m); + p.ple = arena_ple_reserve(m); + p.total = p.arena + p.base + p.ple; + p.cap = footprint_cap(m); + return p; +} + +/// A pack that stays resident (no SSD streaming) holds its mapped bytes plus `overhead` (the prompt buffers, KV, the draft +/// layer, ...): does that fit under the resident cap? (stream.cpp: ExpertStream::wanted) +inline bool resident_fits(double phys, double working_set, double model_bytes, double overhead) { + ArenaMem m; + m.phys = phys; + m.working_set = working_set; + return model_bytes + overhead <= resident_cap(m); } /// Just before the arena is filled: the bytes it may still have when macOS can now give `available_now` (it shrinks, diff --git a/metal/src/engine/stream.cpp b/metal/src/engine/stream.cpp index d5fa2003..f25d4e4f 100644 --- a/metal/src/engine/stream.cpp +++ b/metal/src/engine/stream.cpp @@ -2,6 +2,9 @@ #include "stream.h" #include "ref_quant.h" +#include "arena_budget.h" + +#include #include #include @@ -32,12 +35,16 @@ bool ExpertStream::wanted(const gguf::File& f, const mtl::Context& cx) { if (e && std::string(e) == "1") return true; if (e && std::string(e) == "0") return false; // auto: stream when the mapped weights (experts and dense) and ~12 GiB beside them (the prompt buffers, KV, the - // draft layer, macOS) do not fit the GPU working set. M5 Max (115.4 GB): GSQ packs, IQ3_S and UD-Q4_K_XL stay - // resident, UD-Q5/Q6_K_XL stream; M4 32 GB (26.8 GB): every pack streams. + // draft layer, macOS) do not fit the resident footprint cap: the GPU working set, or on a big Mac the RAM less the + // 30% macOS and its file cache keep (arena_budget.h: footprint_cap). M5 Max (115.4 GB working set, 96.2 GB cap): + // GSQ packs, IQ3_S and UD-Q4_K_XL stay resident, UD-Q5/Q6_K_XL stream; M4 32 GB (26.8 GB): every pack streams. uint64_t all = 0; for (const auto& kv : f.tensors) if (kv.first != "per_layer_token_embd.weight") all += kv.second.bytes; - return (double) all + 12.0 * (1ull << 30) > (double) cx.recommended_working_set(); + uint64_t phys = 0; + size_t len = sizeof phys; + sysctlbyname("hw.memsize", &phys, &len, nullptr, 0); + return !resident_fits((double) phys, (double) cx.recommended_working_set(), (double) all, 12.0 * (1ull << 30)); } ExpertStream::~ExpertStream() { @@ -523,6 +530,7 @@ bool ExpertStream::make_arena(mtl::Context& cx, uint64_t budget, const std::stri if (stopped) std::fprintf(stderr, "strata metal stream: the arena's fill stopped after %.2f GB: macOS's free memory reached what it " "keeps; %.2f GB of the arena (%zu slots) stay unused\n", filled / 1e9, retired_bytes / 1e9, nretired); + arena_live_ = arena_bytes_ - retired_bytes; fill_s_ = (now_ms() - t0) / 1e3; fill_bytes_ = bytes_read_.load(); uint64_t pairs = 0; diff --git a/metal/src/engine/stream.h b/metal/src/engine/stream.h index 46317d3a..2806938a 100644 --- a/metal/src/engine/stream.h +++ b/metal/src/engine/stream.h @@ -52,6 +52,7 @@ public: const std::function& recheck = {}, const std::function& grow = {}); uint64_t shrink_to() const { return shrink_to_; } + uint64_t arena_used_bytes() const { return arena_live_; } // the arena's bytes in use (its retired slots left out) bool ready() const { return !chunks_.empty(); } // the arena's buffers (at most 4, each within the device's maxBufferLength): chunk(i) for i >= count is chunk 0 const mtl::Buffer& chunk(int i) const { return chunks_[(size_t) i < chunks_.size() ? (size_t) i : 0]; } @@ -107,6 +108,7 @@ private: std::vector host_; // slot -> its CPU address mtl::Buffer smap_; uint64_t arena_bytes_ = 0; + uint64_t arena_live_ = 0; // the I/O threads std::vector io_; std::mutex mu_; diff --git a/metal/src/engine/window.cpp b/metal/src/engine/window.cpp index c9654b9c..5b064520 100644 --- a/metal/src/engine/window.cpp +++ b/metal/src/engine/window.cpp @@ -29,7 +29,11 @@ #include #include #include +#include +#include #include +#include +#include #include #include #include @@ -379,6 +383,28 @@ private: mtl::Buffer dout_, dprob_, posv_, dmap_; }; +namespace { +// A repack (metal_repack.py: .repack.lock) or setup's model preparation (.preparing.lock) beside the GPU's file holds a lock +// with its pid. The repack and the pack move 100+ GB through the disk and one holds up to 20 GB of memory: an engine of 70-90 GB +// beside them is what froze the 128 GB M5 Max twice (watchdog panics, 2026-10-13). Returns the pid of a live one, else 0. +// STRATA_METAL_IGNORE_REPACK=1 starts anyway (your choice). +long repack_pid_running(const std::string& model_file) { + namespace fs = std::filesystem; + std::error_code ec; + const fs::path dir = fs::path(model_file).parent_path().empty() ? fs::path(".") : fs::path(model_file).parent_path(); + for (const auto& e : fs::directory_iterator(dir, ec)) { + const std::string n = e.path().filename().string(); + const bool lock = n == ".preparing.lock" || (n.size() > 12 && n.compare(n.size() - 12, 12, ".repack.lock") == 0); + if (!lock) continue; + std::FILE* f = std::fopen(e.path().string().c_str(), "r"); + long pid = 0; + if (f) { if (std::fscanf(f, "%ld", &pid) != 1) pid = 0; std::fclose(f); } + if (pid > 0 && pid != (long) getpid() && (kill((pid_t) pid, 0) == 0 || errno == EPERM)) return pid; + } + return 0; +} +} // namespace + bool Window::init(const strata::core::ModelGeometry& g, strata::core::SessionState& ss, const std::string& shard1, int max_t, int64_t max_cells, std::string& err) { ss_ = &ss; @@ -390,6 +416,11 @@ bool Window::init(const strata::core::ModelGeometry& g, strata::core::SessionSta } eps_ = 1e-6f; const double t0 = now_ms(); + if (const long rp = repack_pid_running(shard1); rp > 0 && !(std::getenv("STRATA_METAL_IGNORE_REPACK") && std::string(std::getenv("STRATA_METAL_IGNORE_REPACK")) == "1")) { + err = "metal window: a model repack or setup's preparation is running here (pid " + std::to_string(rp) + "): the engine is not started " + "beside it (it froze a 128 GB Mac twice); wait for it to finish, or set STRATA_METAL_IGNORE_REPACK=1"; + return false; + } if (!f_.open(shard1, err)) return false; cx_ = std::make_unique(); stream_ = ExpertStream::wanted(f_, *cx_); @@ -1068,6 +1099,21 @@ double Window::run_ds(Cached& c) { namespace { Window* g_stream_window = nullptr; +// What the process holds now, all of it (task_info TASK_VM_INFO): phys_footprint is its anonymous + wired + compressed memory +// (not the clean file pages it only maps), resident_size is the RSS (those pages too). Bytes; 0 when the call fails. +struct ProcMem { + double footprint = 0, rss = 0; +}; +ProcMem proc_mem() { + task_vm_info_data_t ti; + mach_msg_type_number_t cnt = TASK_VM_INFO_COUNT; + ProcMem r; + if (task_info(mach_task_self(), TASK_VM_INFO, (task_info_t) &ti, &cnt) == KERN_SUCCESS) { + r.footprint = (double) ti.phys_footprint; + r.rss = (double) ti.resident_size; + } + return r; +} void stream_atexit() { if (g_stream_window) g_stream_window->stream_report(stderr); } @@ -1104,11 +1150,19 @@ bool Window::stream_arena(std::string& err) { am.phys = (double) phys; am.working_set = (double) cx_->recommended_working_set(); am.allocated = used; + const ProcMem pm0 = proc_mem(); // everything the process holds, not only the Metal buffers (the old 67% rule missed it) + am.proc_footprint = pm0.footprint; + { // the file cache macOS keeps before it compresses anonymous memory (a 4-byte count of pages, read into a zeroed 8) + unsigned long long pages = 0; + size_t pl = sizeof pages; + if (sysctlbyname("vm.vm_page_filecache_min", &pages, &pl, nullptr, 0) == 0) am.filecache_min = (double) pages * (double) vm_page_size; + } am.available = avail_now(); if (ss_ && ss_->ple.table && ss_->ple.table->mode() == strata::kernels::PleIo::Mmap) am.ple_mapped = (double) ss_->ple.table->rows() * 192.0; // a row is at most 192 bytes (Q8_0 + its scale) if (const char* e = std::getenv("STRATA_METAL_KEEP_FREE_GB")) am.keep_gb = std::atof(e); if (const char* e = std::getenv("STRATA_METAL_ARENA_GB")) am.arena_gb = std::atof(e); + if (const char* e = std::getenv("STRATA_METAL_LEAVE_SHARE")) am.leave_share = std::atof(e); // for measuring; the default is kLeaveShare const double keep = arena_keep(am); const double avail = am.available; double budget = arena_budget(am); @@ -1121,9 +1175,21 @@ bool Window::stream_arena(std::string& err) { std::string prof; if (const char* e = std::getenv("STRATA_METAL_EXPERT_PROFILE")) prof = e; else prof = std::string(STRATA_METAL_DATA_DEFAULT) + "/expert-profile.bin"; - std::fprintf(stderr, "strata metal stream: %.2f GB allocated before the arena; RAM %.1f GB (%.1f GB available, %.1f GB kept " - "for macOS), GPU working set %.1f GB\n", used / gb, phys / gb, avail / gb, keep / gb, - cx_->recommended_working_set() / gb); + std::fprintf(stderr, "strata metal stream: %.2f GB allocated before the arena (the process holds %.2f GB, %.2f GB resident); " + "RAM %.1f GB (%.1f GB available, %.1f GB kept for macOS), GPU working set %.1f GB\n", used / gb, + pm0.footprint / gb, pm0.rss / gb, phys / gb, avail / gb, keep / gb, cx_->recommended_working_set() / gb); + { // the planned total: arena + the Metal buffers (or the process's own count when it is more) + the n-gram table's + // reserve, against the cap (arena_budget.h: footprint_cap) + const FootprintPlan fp = footprint_plan(am, budget); + std::fprintf(stderr, "strata metal stream: planned resident footprint %.1f GB = arena %.1f + %.1f held before it + %.1f " + "reserved for the n-gram table; cap %.1f GB = the lesser of the GPU working set %.1f GB and the RAM " + "%.1f GB less %.1f GB left to macOS and its file cache%s\n", + fp.total / gb, fp.arena / gb, fp.base / gb, fp.ple / gb, fp.cap / gb, cx_->recommended_working_set() / gb, + phys / gb, (am.phys - fp.cap) / gb, + am.arena_gb >= 0 && fp.over() ? " - STRATA_METAL_ARENA_GB is above the cap: kept as set (your choice), but " + "a Mac that runs short of memory can freeze (watchdog panics seen at 90+ GB " + "resident of 128)" : ""); + } const char* epg = std::getenv("STRATA_METAL_PROMPT_GEMM"); const bool pg_on = !(epg && std::string(epg) == "0"); bool minimal = false; // the arena's least layout (the min slots) is not shrunk further: it goes ahead, filled in steps @@ -1140,6 +1206,14 @@ bool Window::stream_arena(std::string& err) { budget = (double) st_->shrink_to(); } if (pg_on && !prompt_gemm_init(err)) return false; + { // what the process really holds now, against the plan and the cap (a number that disagrees is a bug in the count) + const ProcMem pm1 = proc_mem(); + const double cap = footprint_cap(am); + std::fprintf(stderr, "strata metal stream: resident footprint after the fill: the process holds %.1f GB (%.1f GB resident), " + "planned %.1f GB, cap %.1f GB%s\n", pm1.footprint / gb, pm1.rss / gb, + footprint_plan(am, (double) st_->arena_used_bytes()).total / gb, cap / gb, + pm1.footprint > cap ? " - OVER THE CAP" : ""); + } g_stream_window = this; std::atexit(stream_atexit); return true; diff --git a/metal/tests/arena_budget_test.cpp b/metal/tests/arena_budget_test.cpp index 6a91a16b..a3be1773 100644 --- a/metal/tests/arena_budget_test.cpp +++ b/metal/tests/arena_budget_test.cpp @@ -41,13 +41,63 @@ int main() { // never below 1 GB; the GPU working set bounds it too ArenaMem tiny{16 * kGB, 10 * kGB, 9.5 * kGB, 8 * kGB}; check(std::fabs(arena_budget(tiny) - 1.0 * kGB) < 1e6, "a 16 GB Mac with nothing left: 1 GB (low hit rate)", arena_budget(tiny)); + // the caps. Anonymous memory (arena, Metal buffers, host memory): 40% of the RAM left on a big Mac; a resident pack: 30%. + check(std::fabs(footprint_cap(m5) - 0.60 * 137.4 * kGB) < 1e6, "M5 Max: the footprint cap is 60% of the RAM (82.4 GB; 40% left)", footprint_cap(m5)); + check(std::fabs(resident_cap(m5) - 0.70 * 137.4 * kGB) < 1e6, "M5 Max: a resident pack may hold 70% (30% left)", resident_cap(m5)); + check(std::fabs(footprint_cap(m4) - 26.8 * kGB) < 1e6, "M4 32 GB: the cap is its 26.8 GB working set (7 GB left, as measured)", footprint_cap(m4)); + check(std::fabs(resident_cap(m4) - 26.8 * kGB) < 1e6, "M4 32 GB: same for a resident pack", resident_cap(m4)); + ArenaMem fc = m5; // the kernel's file-cache floor (37.2 GB here) + 12 GB: never less than that is left + fc.filecache_min = 37.2 * kGB; + check(std::fabs(footprint_cap(fc) - 0.60 * 137.4 * kGB) < 1e6, "M5 Max with its 37.2 GB file-cache floor: 49.2 GB < 55 GB, the share binds", footprint_cap(fc)); + fc.filecache_min = 50.0 * kGB; // a macOS that keeps more: 62 GB left + check(std::fabs(footprint_cap(fc) - (137.4 - 62.0) * kGB) < 1e6, "a larger file-cache floor (50 GB): the cap follows it (75.4 GB)", footprint_cap(fc)); ArenaMem gpu = m5; gpu.available = 200 * kGB; - check(std::fabs(arena_budget(gpu) - (0.67 * 137.4 - 7.0) * kGB) < 1e6, "plenty free: the wired share (67% of the RAM) bounds it", arena_budget(gpu)); - ArenaMem q6 = m5; // UD-Q6_K_XL after a reboot: 7.5 GB allocated, 125 GB "available" (cache): 84 GB ran, 90 GB swapped + check(std::fabs(arena_budget(gpu) - (0.60 * 137.4 - 7.0 - 0.5) * kGB) < 1e6, "plenty free: the footprint cap bounds it (cap - 7 GB held - 0.5 reserve)", arena_budget(gpu)); + ArenaMem q6 = m5; // UD-Q6_K_XL after a reboot: 7.5 GB allocated, 125 GB "available" (cache); 84 GB ran, 90 GB swapped q6.allocated = 7.5 * kGB; q6.available = 125 * kGB; - check(arena_budget(q6) <= 84.7 * kGB && arena_budget(q6) > 84.0 * kGB, "M5 Max, UD-Q6 with 125 GB available: 84.6 GB, not 104", arena_budget(q6)); + check(arena_budget(q6) <= 74.5 * kGB && arena_budget(q6) > 74.0 * kGB, "M5 Max, UD-Q6 with 125 GB available: 74.4 GB, not 104", arena_budget(q6)); + // the process holds more than the Metal buffers (host memory): the larger count is the base. UD-Q6 on the M5 held 11.6-15.1 GB + // against 7.5 GB of Metal buffers; the arena gives up the difference, so the total stays at the cap + ArenaMem held = q6; + held.proc_footprint = 15.1 * kGB; + check(std::fabs(arena_budget(held) - (arena_budget(q6) - 7.6 * kGB)) < 1e6, "the process holds 15.1 GB against 7.5 GB of Metal buffers: the arena gives up the 7.6 GB", arena_budget(held)); + FootprintPlan fp = footprint_plan(held, arena_budget(held)); + check(!fp.over() && std::fabs(fp.total - fp.cap) < 1e6, "the planned total (arena + held + n-gram reserve) ends at the cap, not over it", fp.total); + check(137.4 * kGB - fp.total >= 0.40 * 137.4 * kGB - 1e6, "RAM less the planned total is at least 40% of the RAM", 137.4 * kGB - fp.total); + check(std::fabs(fp.total - 82.4 * kGB) < 0.1 * kGB && std::fabs(fp.arena - 66.8 * kGB) < 0.1 * kGB, "= the measured 66.8 GB arena / 82.4 GB total of the clear run", fp.total); + // a footprint smaller than the Metal buffers never makes the arena grow + ArenaMem less = q6; + less.proc_footprint = 1.0 * kGB; + check(std::fabs(arena_budget(less) - arena_budget(q6)) < 1e6, "a smaller process count than the Metal buffers changes nothing", arena_budget(less)); + // little free memory (a 24 GB program already running): the free-memory rule binds below the cap + ArenaMem busy = held; + busy.available = 60 * kGB; + check(arena_budget(busy) < arena_budget(held) && std::fabs(arena_budget(busy) - (60.0 - 20.61 - 0.5) * kGB) < 0.1 * kGB, "a program already holds memory: the free-memory rule binds (38.9 GB)", arena_budget(busy)); + // the explicit arena is kept (never forced) but the plan says it is over the cap + ArenaMem ex = q6; + ex.arena_gb = 90.0; + fp = footprint_plan(ex, arena_budget(ex)); + check(std::fabs(fp.arena - 90.0 * kGB) < 1e6 && fp.over(), "STRATA_METAL_ARENA_GB=90 on the M5: kept, and flagged over the cap", fp.total); + ex.arena_gb = 60.0; + check(!footprint_plan(ex, arena_budget(ex)).over(), "STRATA_METAL_ARENA_GB=60: under the cap", footprint_plan(ex, arena_budget(ex)).total); + ArenaMem sh = q6; // STRATA_METAL_LEAVE_SHARE (for measuring) + sh.leave_share = 0.30; + check(std::fabs(footprint_cap(sh) - 0.70 * 137.4 * kGB) < 1e6, "STRATA_METAL_LEAVE_SHARE=0.30: the old 30% (96.2 GB)", footprint_cap(sh)); + // the working set still binds where it is tighter than the RAM share + ArenaMem m64{68.7 * kGB, 48.0 * kGB, 5.0 * kGB, 55.0 * kGB}; + check(std::fabs(footprint_cap(m64) - 41.2 * kGB) < 0.1 * kGB, "64 GB Mac: 60% of the RAM (41.2 GB), under the 48 GB working set", footprint_cap(m64)); + check(std::fabs(resident_cap(m64) - 48.0 * kGB) < 1e6, "64 GB Mac: a resident pack: the 48 GB working set (30% left would give 48.1)", resident_cap(m64)); + ArenaMem m96{103.1 * kGB, 77.3 * kGB, 6.0 * kGB, 90.0 * kGB}; + check(std::fabs(footprint_cap(m96) - 0.60 * 103.1 * kGB) < 1e6, "96 GB Mac: 60% of the RAM (61.9 GB)", footprint_cap(m96)); + check(std::fabs(resident_cap(m96) - 0.70 * 103.1 * kGB) < 1e6, "96 GB Mac: resident 70% (72.2 GB), under its 77.3 GB working set", resident_cap(m96)); + // a resident pack: its bytes + 12 GiB must fit the resident cap (stream.cpp: wanted) + const double G12 = 12.0 * 1073741824.0; + check(resident_fits(137.4 * kGB, 115.4 * kGB, 54.8 * kGB, G12), "M5 Max: IQ3_S (54.8 GB) stays resident", 54.8 * kGB); + check(resident_fits(137.4 * kGB, 115.4 * kGB, 82.5 * kGB, G12), "M5 Max: UD-Q4_K_XL (82.5 GB) stays resident (measured: wired 91.7 GB, nothing compressed)", 82.5 * kGB); + check(!resident_fits(137.4 * kGB, 115.4 * kGB, 103.9 * kGB, G12), "M5 Max: UD-Q5_K_XL (103.9 GB) streams", 103.9 * kGB); + check(!resident_fits(34.4 * kGB, 26.8 * kGB, 37.6 * kGB, G12), "M4 32 GB: Q2_0 (37.6 GB) streams", 37.6 * kGB); // memory taken between planning and committing: it shrinks, never grows const double s1 = arena_shrink(m5, b5, 60.0 * kGB); check(s1 < b5 && std::fabs(s1 - (60.0 - 20.61 - 0.5) * kGB) < 0.1 * kGB, "less free when committing: it shrinks", s1); diff --git a/metal/tools/metal_repack.py b/metal/tools/metal_repack.py index b6064077..b006868d 100644 --- a/metal/tools/metal_repack.py +++ b/metal/tools/metal_repack.py @@ -15,6 +15,7 @@ on a 16 KiB boundary (general.alignment = 16384: Apple Silicon's page). Prints t from __future__ import annotations import argparse +import atexit import hashlib import os import re @@ -23,6 +24,9 @@ import sys from pathlib import Path ALIGN = 16384 +SYNC_EVERY = 1 << 30 # the output is flushed to the disk every GiB: at most this much (plus a chunk) is ever dirty +CHUNK = 64 << 20 +LOCK_SUFFIX = ".repack.lock" # .repack.lock holds the repack's pid while it runs (setup_mac.py and the engine look) # GGML type -> (bytes per block, values per block) TYPE_SIZE = {0: (4, 1), 1: (2, 1), 30: (2, 1), 2: (18, 32), 3: (20, 32), 6: (22, 32), 7: (24, 32), 8: (34, 32), 10: (84, 256), 11: (110, 256), 12: (144, 256), 13: (176, 256), 14: (210, 256), 16: (66, 256), @@ -31,6 +35,33 @@ TYPE_SIZE = {0: (4, 1), 1: (2, 1), 30: (2, 1), 2: (18, 32), 3: (20, 32), 6: (22, PLE = "per_layer_token_embd.weight" +def nocache(f) -> None: + """Reads and writes through this file skip the page cache (macOS F_NOCACHE). A repack moves 100+ GB: through the cache it + fills every free page with source and dirty output pages, which on the 128 GB M5 Max (the kernel keeps a 37 GB file-cache + floor) pushed the other programs' memory into the compressor and, with an engine running, ended in a watchdog panic + (2026-10-13).""" + try: + import fcntl + fcntl.fcntl(f.fileno(), getattr(fcntl, "F_NOCACHE", 48), 1) + except (ImportError, OSError, ValueError): + pass + + +def drop_cache(f) -> None: + """Where F_NOCACHE does not exist (Linux, the BSDs): ask the kernel to drop this file's cached pages.""" + if hasattr(os, "posix_fadvise"): + try: + os.posix_fadvise(f.fileno(), 0, 0, os.POSIX_FADV_DONTNEED) + except OSError: + pass + + +def write_all(o, buf) -> None: + mv = memoryview(buf) + while len(mv): + mv = mv[o.write(mv):] + + class Reader: def __init__(self, path: Path): self.path = path @@ -68,6 +99,7 @@ class Reader: t["bytes"] = ne // q * b t["src"] = self t["abs"] = self.data + t["off"] + nocache(self.f) # the header is read; the tensors' bytes are read once, uncached def _str(self) -> str: n = struct.unpack(" str: h = hashlib.sha256() f.seek(pos) while n: - buf = f.read(min(n, 64 << 20)) + buf = f.read(min(n, CHUNK)) if not buf: break h.update(buf) @@ -107,7 +139,8 @@ def verify(out: Path, data0: int, order: list) -> list[str]: """The names of the tensors whose bytes in `out` differ from their source shard's (SHA-256 each).""" bad = [] with open(out, "rb") as o: - r = Reader(out) # the output's own table, as a reader sees it + nocache(o) + r = Reader(out) # the output's own table, as a reader sees it table = {t["name"]: t for t in r.tensors} for i, t in enumerate(order): mine = table.get(t["name"]) @@ -158,25 +191,39 @@ def main() -> int: data0 = (len(head) + ALIGN - 1) // ALIGN * ALIGN total = data0 + off tmp = a.out.with_name(a.out.name + ".part") - with open(tmp, "wb") as o: - o.write(head) - o.write(b"\0" * (data0 - len(head))) + lock = a.out.with_name(a.out.name + LOCK_SUFFIX) + lock.write_text(str(os.getpid())) + atexit.register(lambda: lock.unlink() if lock.exists() else None) + # unbuffered writes (a write() is a write), uncached, flushed every SYNC_EVERY bytes: the dirty pages stay a chunk or two, + # wherever the other programs' memory stands (the old buffered, cached write left 2+ GB dirty and filled the RAM) + with open(tmp, "wb", buffering=0) as o: + nocache(o) + write_all(o, head) + write_all(o, b"\0" * (data0 - len(head))) done = 0 + since = 0 for t in order: o.seek(data0 + t["new"]) src = t["src"].f src.seek(t["abs"]) left = t["bytes"] while left: - buf = src.read(min(left, 64 << 20)) + buf = src.read(min(left, CHUNK)) if not buf: sys.exit(f"{t['src'].path}: short read in {t['name']}") - o.write(buf) + write_all(o, buf) left -= len(buf) + since += len(buf) + if since >= SYNC_EVERY: + os.fsync(o.fileno()) + drop_cache(o) + drop_cache(src) + since = 0 done += t["bytes"] if t is order[-1] or t["name"].endswith("ffn_down_exps.weight"): print(f"\r {done / 2**30:6.1f} / {sum(x['bytes'] for x in order) / 2**30:.1f} GiB", end="", flush=True) o.truncate(total) + os.fsync(o.fileno()) print() if a.verify: bad = verify(tmp, data0, order) diff --git a/tools/test_setup_mac.py b/tools/test_setup_mac.py index ce63dc08..9f887eb8 100644 --- a/tools/test_setup_mac.py +++ b/tools/test_setup_mac.py @@ -193,5 +193,61 @@ class HandOver(unittest.TestCase): self.assertIn("83dcb04777c798bd95f3687acf9ae84b09860272ee6bdfb05be8bcf9447f75b8", sh) +class RepackGuard(unittest.TestCase): + """No engine beside a repack: the locks, and the resident rule that matches the engine's arena_budget.h.""" + + def test_resident_rule_matches_the_engine(self): + # the resident cap: Metal's working set (3/4), and on a Mac of 64 GB or more the RAM less 30% + self.assertAlmostEqual(M.gpu_budget_gb(128), 128 * 1.073741824 * 0.70, places=3) # 96.2 GB, as arena_budget.h + self.assertAlmostEqual(M.gpu_budget_gb(96), 96 * 1.073741824 * 0.70, places=3) + self.assertAlmostEqual(M.gpu_budget_gb(32), 32 * 1.073741824 * 0.75, places=3) # a small Mac: the working set + self.assertFalse(M.streams("UD-Q4_K_XL", 128)) # 82.6 + 8 GB: resident (measured: nothing compressed) + self.assertTrue(M.streams("UD-Q5_K_XL", 128)) + self.assertTrue(M.streams("UD-Q4_K_XL", 96)) + + @unittest.skipIf(sys.platform == "win32", "os.kill(pid, 0) is a probe on macOS and Linux only") + def test_a_live_lock_is_seen_a_stale_one_is_dropped(self): + import os + import tempfile + with tempfile.TemporaryDirectory() as d: + d = Path(d) + self.assertEqual(M.repack_running(d), []) + (d / "m-metal.gguf.repack.lock").write_text(str(os.getppid())) # a live process that is not us + self.assertEqual(M.repack_running(d), [os.getppid()]) + (d / "m-metal.gguf.repack.lock").write_text("999999999") # no such process + self.assertEqual(M.repack_running(d), []) + self.assertFalse((d / "m-metal.gguf.repack.lock").exists()) # the stale lock was removed + (d / M.PREPARE_LOCK).write_text(str(os.getppid())) + self.assertEqual(M.repack_running(d), [os.getppid()]) + (d / M.PREPARE_LOCK).write_text(str(os.getpid())) # our own setup's lock does not stop us + self.assertEqual(M.repack_running(d), []) + + @unittest.skipIf(sys.platform == "win32", "os.kill(pid, 0) is a probe on macOS and Linux only") + def test_start_refuses_while_a_repack_runs(self): + import json + import os + import tempfile + with tempfile.TemporaryDirectory() as d: + d = Path(d) + gguf, exe = d / "m-metal.gguf", d / "strata" + gguf.write_bytes(b"x") + exe.write_bytes(b"x") + cfg = d / "strata-x.json" + cfg.write_text(json.dumps({"exe": str(exe), "args": ["--native", str(gguf)], "port": 8080})) + (d / "m-metal.gguf.repack.lock").write_text(str(os.getppid())) + with mock.patch.object(M.subprocess, "call", side_effect=AssertionError("started")), \ + mock.patch.object(M.S, "fail", side_effect=SystemExit("refused")) as fail: + with self.assertRaises(SystemExit): + M.start(cfg, None, False) + self.assertIn("repack is still running", fail.call_args[0][0]) + + def test_the_repack_writes_in_bounded_pieces(self): + src = (ROOT / "metal" / "tools" / "metal_repack.py").read_text(encoding="utf-8") + self.assertIn("SYNC_EVERY = 1 << 30", src) # flushed every GiB + self.assertIn("nocache(o)", src) # F_NOCACHE on the output + self.assertIn("buffering=0", src) # write() is a write + self.assertNotIn("mmap", src) # no dirty mapping of the output + + if __name__ == "__main__": unittest.main()