Kyojin: open-source engine that runs 100 GB-class open models (GLM-5.3, Qwen3.8, DeepSeek V4.1) on one desktop machine. AMD Strix Halo, NVIDIA RTX and Apple Mac. OpenAI API, built on ExLlamaV3.
Python amdapple-siliconcudadeepseekexl3exllamav3glminferencellmllm-inferencelocal-llmnvidiaopenai-apiquantizationqwenrocmstrix-halo
Allocator and OOM guard
Resyntha5f28bca2b7a
diff --git a/doc/env_vars.md b/doc/env_vars.mdindex c406ae5..3ecfe6e 100644--- a/doc/env_vars.md+++ b/doc/env_vars.md@@ -709,8 +709,72 @@ Enable GPU/CPU handoff profiling, for debug purposes.### `EXL3_EXPANDABLE_SEGMENTS` (default: `1`)-Use expandable segments for all Torch allocations. Opt out with a value of 1 or by explicitly-setting `PYTORCH_CUDA_ALLOC_CONF`.+Use expandable segments for all Torch allocations. Opt out with a value of `0` or by explicitly+setting `PYTORCH_CUDA_ALLOC_CONF`. On a unified-memory box, disabling expandable segments can+recover about **0.5 GiB** of allocator fragmentation around a large cache (a measured 512K+GLM cache loads with it off but failed with the default); it does not add capacity.++The serve and split entry points expose the same choice before the library import:+`--expandable-segments auto|on|off` (env fallback `KYOJIN_EXPANDABLE_SEGMENTS`). `auto` leaves+expandable segments on except for large-context unified loads where a documented estimate is+within 8 GiB of the observed usable ceiling; set `KYOJIN_EXPANDABLE_SEGMENTS_AUTO_OFF=1` to+force that decision on, or use `--expandable-segments on|off` to override it.++### `KYOJIN_EXPANDABLE_SEGMENTS_AUTO_CTX` (default: `524288`)++Context gate for the `--expandable-segments auto` heuristic. Below this token count, `auto`+keeps expandable segments on. The estimate also requires a unified/GTT device and a model that+is close to the usable ceiling (default `KYOJIN_OOM_GUARD_USABLE_CEILING_GIB=113.3` on a+118 GiB Strix Halo iGPU).++### `KYOJIN_OOM_GUARD` (default: `auto` for split, `warn` for single-device)++Pre-flight per-device memory guard: `auto` refuses an impossible load before any weights,+cache or reserve slab are allocated; `warn` only logs the table; `off` disables the check.+The guard is read-only and never changes allocator settings or outputs. See+`KYOJIN_OOM_GUARD_*` below and `doc/split.md` for the flags.++### `KYOJIN_OOM_GUARD_RESERVE_GIB` (default: `4.5` unified, `0.8` dedicated)++Per-device headroom kept out of the pre-flight capacity. Accepts the split's device-selector+syntax, for example `gfx1151=4.5,gfx1201=0.8`; `cuda:N`, a UUID or a name substring also work.+A bare number applies to every device. The part0 load slab (`--part0-reserve-gb`) is estimated+separately and is not double-counted.++### `KYOJIN_OOM_GUARD_WORKSPACE_GIB` (default: `2.0` bulk device, `1.5` other)++Estimated prefill workspace per device. The device carrying the bulk of the layers gets 2.0+GiB and the other 1.5 GiB unless a selector list overrides them, e.g.+`cuda:0=4,cuda:1=3.5`. These defaults were calibrated on the measured box: 4.0 GiB refused+the measured-good 8K MTP-on and 128K points, while 2.0 GiB brackets their measured peaks+and still refuses 512K/640K at the usable ceiling. Raise them to be more conservative near+the cliff.++### `KYOJIN_OOM_GUARD_SAFETY_GIB` (default: `0`)++Extra per-device capacity margin on top of the reserve and workspace.++### `KYOJIN_OOM_GUARD_DEVICE_FLOOR` (default: `0`)++Per-device free-memory floor used by the pre-flight guard and by the supervisor when a serve+script passes it through. Same selector syntax as the reserve. `0` disables the floor.++### `KYOJIN_OOM_GUARD_HOST_FLOOR_GIB` (default: `6`)++Host `MemAvailable` floor used when a unified device is part of the load; the summed GTT+footprint must fit in `MemAvailable - floor`. `exllamav3/guard.py` uses the same default for its+external host floor.++### `KYOJIN_OOM_GUARD_USABLE_CEILING_GIB` (default: `113.3`)++Observed usable ceiling of a 118 GiB unified device. The guard caps a unified device's planned+capacity at this value; the default reserve of 4.5 GiB is already the raw-minus-usable gap, so+the reserve is not subtracted twice. Raise it only after measuring the actual ceiling.++### `KYOJIN_OOM_GUARD_TOLERANCE_GIB` (default: `0.25`)++Small band by which a byte estimate may exceed capacity before `auto` refuses (the estimator is+byte accounting, not a measurement).### `EXL3_LOAD_ARENA` (default: `1`)diff --git a/doc/split.md b/doc/split.mdindex ed53251..0f1b93b 100644--- a/doc/split.md+++ b/doc/split.md@@ -53,6 +53,12 @@ KYOJIN_PART1_DEVICE=gfx1151 \| `--part0-reserve-gb` | `KYOJIN_PART0_RESERVE_GB` | VRAM held as a load-time slab on `part0` for workspace (default 1.2) || `--split-preset auto\|glm\|qwen\|ds41\|none` | `KYOJIN_SPLIT_PRESET` | per-model unsafe-environment preset; GLM needs none today || `--split-graphs auto\|on\|off` | - | reserved for per-segment capture; split currently runs graphs off |+| `--expandable-segments auto\|on\|off` | `KYOJIN_EXPANDABLE_SEGMENTS` | allocator mode, applied before `import exllamav3`; `auto` only turns it off for large-context unified loads |+| `--oom-guard auto\|warn\|off` | `KYOJIN_OOM_GUARD` | pre-flight per-device guard (`auto` refuses, `warn` logs, `off` disables) |+| `--oom-guard-reserve-gib` | `KYOJIN_OOM_GUARD_RESERVE_GIB` | per-device headroom, e.g. `gfx1151=4.5,gfx1201=0.8` (default 4.5 unified / 0.8 dedicated) |+| `--oom-guard-workspace-gib` | `KYOJIN_OOM_GUARD_WORKSPACE_GIB` | per-device prefill workspace margin (default 2.0 bulk / 1.5 other) |+| `--oom-guard-safety-gib` | `KYOJIN_OOM_GUARD_SAFETY_GIB` | extra per-device capacity margin |+| `--oom-guard-device-floor` | `KYOJIN_OOM_GUARD_DEVICE_FLOOR` | per-device free-memory floor, shared with the supervisor |`cuda:N` is the torch device index **after** `HIP_VISIBLE_DEVICES`, not the `rocm-smi`index. Explicit selectors win in either position: `part0=cuda:1/part1=cuda:0` and@@ -85,8 +91,62 @@ Text endcaps are selected by a class/key allowlist, not by per-model placement imodule. Size it to the part0 card.- Split mode runs eager. Whole-forward and per-block graphs are disabled; per-segmentcapture is not implemented yet.-- Use `util/memguard.py` when loading near the limit. It help save you from the dreaded OOM but slight adverse- performance effects have been noted (to be investigated further.)++The measured 118 GiB Strix Halo iGPU has a usable ceiling of about **113.3 GiB** (the+~4.5 GiB gap is driver/allocator overhead, not free capacity). Recorded failure points on+the measured GLM pack: 128K split runs complete (peak ~110.7 GiB on the iGPU); a 512K+cache needs `expandable_segments:False` to load; 640K is killed by the supervisor before+a torch OOM; 768K hard-locked the box. Do not probe above 128K for MTP-on runs.++### Pre-flight guard++The loader estimates each device's footprint from actual bytes: layer/endcap/component+weights, KV/recurrent cache, the part0 reserve slab and a prefill workspace margin. It+compares that with the device's usable/free memory and, for unified devices, with host+`MemAvailable - 6 GiB`. `--oom-guard auto` (the split default) refuses before allocating+weights, cache or slabs, and prints a per-device table plus the chosen N/context and the+largest N/context that fits. `warn` only logs; `off` disables it. The check is read-only:+it changes no allocator setting and no split-off path.++Defaults are tuning values, not architecture rules: `4.5` GiB reserve on a unified/GTT+device, `0.8` GiB on dedicated VRAM, `2.0`/`1.5` GiB prefill workspace on the bulk/other+device (calibrated: 4.0 GiB refused measured-good 8K MTP-on/128K points and 2.0 brackets+their peaks), and a `6` GiB host floor. All accept per-device selector lists, e.g.+`--oom-guard-reserve-gib gfx1151=4.5,gfx1201=0.8`.++### Allocator mode++`--expandable-segments off` (or `EXL3_EXPANDABLE_SEGMENTS=0`, or+`PYTORCH_CUDA_ALLOC_CONF=expandable_segments:False`) is applied before the library import.+It recovers about **0.5 GiB** of fragmentation around a large cache and is the mode that+loaded the 512K case; it does not add capacity. The pre-flight workspace estimate is+conservative, so `auto` may still refuse a load-only 512K run that fits at 113.28 GiB+measured: pass `--oom-guard warn` (or a lower `--oom-guard-workspace-gib`) for that+measured point once the supervisor is armed. `auto` keeps expandable segments on+except for unified loads at 512K context or above whose estimate is within 8 GiB of the+usable ceiling. `on`/`off` are explicit overrides.++### External supervisor++Use `exllamav3/guard.py` (the compatibility path `util/memguard.py` execs it) when loading+near the limit. It watches host `MemAvailable`, per-device free memory (`mem_info_gtt_*`/+`mem_info_vram_*` on AMD, `nvidia-smi` on NVIDIA) and can release page cache:++```sh+python exllamav3/guard.py --floor-gib 6 --device-floor-gib 4 \+ --fadvise-dir /path/to/model -- python tools/glm/serve.py ...+```++Per-device supervisor floors use `--device-floor card1=4.5,nvidia:0=2` (or+`--device-floor-gib` for every watched device); the supervisor has no torch selector, so+`cardN`, `nvidia:N`, `amd`, `nvidia` and `default` are accepted, and it degrades to the host+floor when a per-device query is unavailable. On a host with several visible devices a+global `--device-floor-gib` is ignored (with a warning): use explicit selectors so an+unrelated GPU cannot trigger a kill. The serve scripts use a+`MEMGUARD=auto|1|0` wrapper: `auto` enables it for a unified/GTT device or a large model+and logs the chosen floors. Keep the supervisor external; an+in-process watchdog cannot be relied on while the allocator or kernel is stalled. Do not+run MTP-on probing with the retired `split_bench_ctx.py`; use `split_eval.py --bench-depth`.## Model supportdiff --git a/doc/strix-halo.md b/doc/strix-halo.mdindex 53d2dfe..a73ecea 100644--- a/doc/strix-halo.md+++ b/doc/strix-halo.md@@ -231,6 +231,26 @@ still launch 16 warps and index this buffer by warp id, so a 4-warp buffer givesand `eval/ppl.py` still reports the correct 4.2259 on that broken build. Only `bench_mtp.py`catches it.+## Unified memory safety++The 128 GB pool reports about 118 GiB to torch, but the practically usable ceiling is+about **113.3 GiB**; the gap is driver/allocator overhead. Large loads should use the+pre-flight guard and the external supervisor described in [split.md](split.md#memory-and-capacity):++- `--oom-guard auto` (split default) estimates weights, cache, slab and workspace per+ device and refuses a load that cannot fit before allocating anything. The workspace+ default is 2.0 GiB on the bulk device and 1.5 GiB on the other (calibrated on this box). The workspace+ default is 2.0 GiB on the bulk device and 1.5 GiB on the other (calibrated on this box).+- `--expandable-segments off` (or `EXL3_EXPANDABLE_SEGMENTS=0`) recovers about 0.5 GiB of+ allocator fragmentation around a large cache (the 512K GLM case), not capacity.+- `python exllamav3/guard.py --floor-gib 6 --device-floor-gib 4 --fadvise-dir <model> -- ...`+ SIGKILLs the child before the host or a device floor is breached and releases page cache.+ The serve scripts wrap this with `MEMGUARD=auto|1|0`.++Cutoffs observed on GLM: 128K split is the validated long-context point; 640K is refused+by the pre-flight guard; 768K previously hard-locked the box. Do not probe above 128K with+MTP on.+## Build```bashdiff --git a/examples/mimo_v2_6/serve.sh b/examples/mimo_v2_6/serve.shindex ff1ed94..73614ca 100755--- a/examples/mimo_v2_6/serve.sh+++ b/examples/mimo_v2_6/serve.sh@@ -62,8 +62,10 @@# EXL3_LOAD_DEVICE=cuda:0 single-device load, bypassing the autosplit budget# arithmetic (which reads MemFree, not MemAvailable).# Set to "" to restore stock autosplit.-# MEMGUARD=auto auto | 1 | 0. `auto` enables util/memguard.py on Linux.+# MEMGUARD=auto auto | 1 | 0. `auto` enables exllamav3/guard.py on Linux for a+# unified/GTT device or a large model.# MEMGUARD_FLOOR=8 SIGKILL the server below this MemAvailable, in GiB+# MEMGUARD_DEVICE_FLOOR=0 per-device free-memory floor, in GiB (0 = off)# MIN_AVAIL_GIB=12 refuse to start below this MemAvailable, in GiB# FOREGROUND=1 0 backgrounds it and writes $LOG#@@ -117,6 +119,7 @@ DRAFT_CACHE_MODE="${DRAFT_CACHE_MODE:-FP16}"DRAFT_RING="${DRAFT_RING:-1}"MEMGUARD="${MEMGUARD:-auto}"MEMGUARD_FLOOR="${MEMGUARD_FLOOR:-8}"+MEMGUARD_DEVICE_FLOOR="${MEMGUARD_DEVICE_FLOOR:-0}"MIN_AVAIL_GIB="${MIN_AVAIL_GIB:-12}"FOREGROUND="${FOREGROUND:-1}"CONFIG_OUT="${CONFIG_OUT:-$TABBY_DIR/mimo-tabby-config.yml}"@@ -239,17 +242,27 @@ export EXL3_DFLASH_RING="$DRAFT_RING"export EXL3_LOAD_DEVICE="${EXL3_LOAD_DEVICE-cuda:0}"[ -n "$EXL3_LOAD_DEVICE" ] && echo " -- EXL3_LOAD_DEVICE=$EXL3_LOAD_DEVICE (single-device load)"-# memguard: SIGKILL the server's process group if MemAvailable falls below the floor,-# and fadvise(DONTNEED) the shards every 5 s so the ~86 GiB of buffered-pread page-# cache never shadows the same 86 GiB of weights in one unified pool.+# memguard: SIGKILL the server's process group if MemAvailable or a device's free+# memory falls below its floor, and fadvise(DONTNEED) the shards every 5 s so the+# ~86 GiB of buffered-pread page cache never shadows the same weights in one pool.use_mg=0case "$MEMGUARD" in1) use_mg=1 ;;- auto) [ -r /proc/meminfo ] && use_mg=1 ;;+ auto)+ if compgen -G "/sys/class/drm/card*/device/mem_info_gtt_total" > /dev/null; then+ use_mg=1+ elif [ -r /proc/meminfo ]; then+ model_bytes=$(du -sb --apparent-size "$MODEL_DIR"/*.safetensors 2> /dev/null | awk '{s+=$1} END {print s+0}')+ [ "${model_bytes:-0}" -ge $((48 * 1024 * 1024 * 1024)) ] && use_mg=1+ fi+ ;;esac-if [ "$use_mg" = "1" ] && [ -f "$REPO/util/memguard.py" ]; then- MG=(python "$REPO/util/memguard.py" --floor-gib "$MEMGUARD_FLOOR"- --fadvise-dir "$MODEL_DIR" --fadvise-every 5 --label tabbyapi --)+if [ "$use_mg" = "1" ] && [ -f "$REPO/exllamav3/guard.py" ]; then+ MG=(python "$REPO/exllamav3/guard.py" --floor-gib "$MEMGUARD_FLOOR"+ --fadvise-dir "$MODEL_DIR" --fadvise-every 5 --label tabbyapi)+ [ "$MEMGUARD_DEVICE_FLOOR" != "0" ] && MG+=(--device-floor-gib "$MEMGUARD_DEVICE_FLOOR")+ MG+=(--)+ echo " -- MEMGUARD=on host floor ${MEMGUARD_FLOOR} GiB device floor ${MEMGUARD_DEVICE_FLOOR} GiB"elseMG=()[ "$use_mg" = "1" ] || echo " !! memguard disabled (MEMGUARD=$MEMGUARD)"diff --git a/exllamav3/device_map.py b/exllamav3/device_map.pyindex dfb9cd0..6f2ea07 100644--- a/exllamav3/device_map.py+++ b/exllamav3/device_map.py@@ -43,6 +43,15 @@ from dataclasses import dataclass, fieldimport torch+from .memory_guard import (+ DeviceBudget,+ OOMGuard,+ check_single_device,+ device_free_bytes,+ device_total_bytes,+ host_available_bytes,+ is_unified_device,+)from .util.arch_list import device_archGIB = 1024 ** 3@@ -395,6 +404,25 @@ def _cache_bytes_by_layer(cache) -> dict[int, int]:return out+def component_weight_bytes(model, config = None, cache = None) -> tuple[int, int]:+ """Actual weight and cache bytes of one component (read-only, no allocation)."""+ stc = getattr(config, "stc", None) if config is not None else None+ weights = sum(_module_bytes(m, stc) for m in getattr(model, "modules", ())+ if not getattr(m, "caps", {}).get("prefer_cpu"))+ layers = sum(1 for m in getattr(model, "modules", ())+ if getattr(m, "layer_idx", None) is not None)+ return int(weights), int(_cache_bytes_for(cache, layers))+++def check_single_device_guard(model, config = None, cache = None, device = 0,+ budget: DeviceBudget | None = None,+ arch: str = "", logger = print):+ """Pre-flight guard for a single-device load (default mode: warn)."""+ weights, cache_bytes = component_weight_bytes(model, config, cache)+ return check_single_device(weights, cache_bytes, device, budget = budget,+ arch = arch, logger = logger)++# ---------------------------------------------------------------------------------------------------------# Component map# ---------------------------------------------------------------------------------------------------------@@ -709,6 +737,7 @@ class SplitPlan:part1_reserve_gb: float = 0.0,preset: str = "auto",auto_cap: int | None = None,+ guard_budget: DeviceBudget | None = None,logger = print,):self.devices = devices@@ -720,6 +749,10 @@ class SplitPlan:self.part1_reserve_gb = float(part1_reserve_gb)self.preset = (preset or "auto").strip().lower()self.auto_cap = None if auto_cap is None else max(0, int(auto_cap))+ self.guard_budget = guard_budget or DeviceBudget.from_env()+ self.guard_report = None+ self._guard_key = None+ self._module_byte_cache: dict[tuple[int, int], int] = {}self.logger = loggerself.maps: dict[str, ComponentMap] = {}self._decls: dict[str, tuple] = {}@@ -764,6 +797,10 @@ class SplitPlan:# A late component (vision/MTP after the target load) must not reset the# already-chosen auto-N plan.self._built = was_built+ if was_built:+ # Check only the components that have not loaded yet; the loaded+ # target's bytes are already reflected in the device's free memory.+ self.check_guard()return cmapdef register_config(self, config) -> None:@@ -797,6 +834,7 @@ class SplitPlan:)self._assign_owner()self.apply_policies()+ self.check_guard()self._built = Truereturn self@@ -885,6 +923,186 @@ class SplitPlan:out += _module_bytes(m, stc)return out+ # -- pre-flight guard --------------------------------------------------++ def _guard_context(self) -> int | None:+ values = [int(m.cache.max_num_tokens) for m in self.maps.values()+ if m.cache is not None+ and getattr(m.cache, "max_num_tokens", None) is not None]+ return max(values) if values else None++ def _guard_infos(self) -> list[DeviceInfo]:+ infos = list(self.devices.inventory)+ known = {d.index for d in infos}+ for index in self._guard_device_ids():+ if index not in known:+ arch = self.devices.part0_arch if self.devices.part0 is not None \+ and index == self.devices.part0.index else self.devices.part1_arch+ infos.append(DeviceInfo(index = index, arch = arch or ""))+ return infos++ def _guard_device_ids(self) -> list[int]:+ ids = {self.devices.part1.index}+ if self.devices.part0 is not None:+ ids.add(self.devices.part0.index)+ for cmap in self.maps.values():+ for module in cmap._module_refs:+ device = cmap.device_for(module)+ if device.type == "cuda" and device.index is not None:+ ids.add(int(device.index))+ return sorted(ids)++ def _guard_bytes(self, part0_layers: int | None = None,+ skip_components: set[str] | None = None) -> tuple[dict[int, int],+ dict[int, int],+ dict[int, int]]:+ """Per-device weight, cache and reserve bytes for the current maps."""+ weights: dict[int, int] = {}+ cache_bytes: dict[int, int] = {}+ reserve: dict[int, int] = {}+ skip = skip_components or set()+ text = next((m for m in self.maps.values() if m.policy_or_default.kind == "text"), None)+ saved = None+ if text is not None and part0_layers is not None:+ saved = text.part0_layers+ text.part0_layers = max(0, min(int(part0_layers), text.layer_count))+ try:+ for name, cmap in self.maps.items():+ if name in skip:+ continue+ stc = getattr(cmap.config, "stc", None)+ for module in cmap._module_refs:+ device = cmap.device_for(module)+ if device.type == "cuda" and device.index is not None:+ key = (id(module), id(stc))+ size = self._module_byte_cache.get(key)+ if size is None:+ size = self._module_byte_cache[key] = _module_bytes(module, stc)+ weights[int(device.index)] = weights.get(int(device.index), 0) + size+ for idx, size in cmap._cache_by_layer.items():+ device = self._expected_layer_device(cmap, idx)+ if device.type == "cuda" and device.index is not None:+ cache_bytes[int(device.index)] = cache_bytes.get(int(device.index), 0) + int(size)+ for index, size in cmap.reserve_bytes.items():+ reserve[int(index)] = reserve.get(int(index), 0) + int(size)+ finally:+ if text is not None and saved is not None:+ text.part0_layers = saved+ return weights, cache_bytes, reserve++ def _guard_footprints(self, guard: OOMGuard, *, part0_layers: int | None = None,+ probe: dict[int, tuple[int | None, int | None]] | None = None,+ skip_components: set[str] | None = None,+ infos: list[DeviceInfo] | None = None):+ weights, cache_bytes, reserve = self._guard_bytes(+ part0_layers = part0_layers, skip_components = skip_components)+ infos = {d.index: d for d in (infos or self._guard_infos())}+ out = []+ for index in self._guard_device_ids():+ total, free = (probe.get(index, (None, None))+ if probe is not None else (None, None))+ info = infos.get(index)+ out.append(guard.footprint(+ index, arch = getattr(info, "arch", "") or "",+ name = getattr(info, "name", "") or "",+ total_bytes = total, free_bytes = free,+ weights_bytes = weights.get(index, 0),+ cache_bytes = cache_bytes.get(index, 0),+ reserve_bytes = reserve.get(index, 0),+ ))+ return out++ def _guard_probe(self) -> dict[int, tuple[int | None, int | None]]:+ return {index: (device_total_bytes(index), device_free_bytes(index))+ for index in self._guard_device_ids()}++ def _largest_guard_n(self, guard: OOMGuard, probe, host_available, infos,+ skip_components: set[str]) -> int | None:+ text = next((m for m in self.maps.values() if m.policy_or_default.kind == "text"), None)+ if text is None or text.layer_count == 0 or "text" in skip_components:+ return None+ # More part0 layers move weight off the constrained unified device; search from+ # the top so the answer is the largest feasible N, not merely a smaller one.+ for n in range(text.layer_count, -1, -1):+ if guard.evaluate(self._guard_footprints(+ guard, part0_layers = n, probe = probe,+ skip_components = skip_components, infos = infos),+ host_available = host_available).ok:+ return n+ return None++ def _largest_guard_context(self, report, context: int | None) -> int | None:+ if not context or context <= 0:+ return None+ limits = []+ for result in report.device_results:+ fp = result.footprint+ if result.capacity_bytes is None or fp.cache_bytes <= 0:+ continue+ headroom = result.capacity_bytes - (fp.weights_bytes + fp.slab_bytes + fp.workspace_bytes)+ if headroom < 0:+ limits.append(0)+ continue+ limits.append(int(context * headroom / fp.cache_bytes))+ host = report.host_result+ if host is not None and host.capacity_bytes is not None:+ cache_total = sum(r.footprint.cache_bytes for r in report.device_results+ if r.footprint.unified)+ fixed_total = sum(r.footprint.weights_bytes + r.footprint.slab_bytes+ + r.footprint.workspace_bytes for r in report.device_results+ if r.footprint.unified)+ if cache_total > 0:+ headroom = host.capacity_bytes - fixed_total+ limits.append(0 if headroom < 0 else+ int(context * headroom / cache_total))+ if not limits:+ return None+ return max(0, (min(limits) // 256) * 256)++ def check_guard(self) -> None:+ """Refuse or warn before any allocation: read-only and idempotent."""+ if self.guard_budget.mode == "off" or not self.maps:+ return+ try:+ if not torch.cuda.is_available():+ return+ except Exception: # noqa: BLE001 - CPU test environment+ return+ context = self._guard_context()+ loaded = {r.component for r in self.records}+ text = next((m for m in self.maps.values() if m.policy_or_default.kind == "text"), None)+ chosen_n = text.part0_layers if text is not None else None+ probe = self._guard_probe()+ infos = self._guard_infos()+ arch_of = {d.index: d.arch for d in infos}+ unified = {index: is_unified_device(index, arch_of.get(index, ""), probe[index][0])+ for index in probe}+ weights, _cache, _reserve = self._guard_bytes(skip_components = loaded)+ bulk = max(weights, key = weights.get) if weights else self.devices.part1.index+ guard = OOMGuard.from_budget(+ self.guard_budget, infos,+ lambda key: _select_device(key, "oom-guard", infos, "KYOJIN_OOM_GUARD_DEVICE"),+ unified = unified, bulk_index = bulk, logger = self.logger)+ key = (tuple(sorted((name, m.part0_layers) for name, m in self.maps.items())),+ context, tuple(sorted(probe.items())), self.guard_budget.mode,+ tuple(sorted(loaded)))+ if key == self._guard_key:+ return+ host_available = host_available_bytes()+ footprints = self._guard_footprints(guard, probe = probe,+ skip_components = loaded, infos = infos)+ report = guard.evaluate(footprints, host_available = host_available)+ largest_n = None+ if not report.ok and text is not None and self.guard_budget.mode != "warn":+ largest_n = self._largest_guard_n(guard, probe, host_available, infos, loaded)+ if largest_n is None:+ largest_n = -1+ largest_ctx = self._largest_guard_context(report, context) if not report.ok else None+ self.guard_report = guard.check(+ footprints, host_available = host_available, context = context,+ chosen_n = chosen_n, largest_n = largest_n, largest_ctx = largest_ctx)+ self._guard_key = key+# -- runtime -----------------------------------------------------------def map(self, component: str) -> ComponentMap | None:@@ -900,6 +1118,9 @@ class SplitPlan:# not allocate a second one.if self._budget_engaged_once:return+ # Re-check after late component declarations (split harnesses add MTP/vision+ # after build); still before the first slab allocation.+ self.check_guard()if self._owner is not None and self._owner in self.maps:self.maps[self._owner].engage_budget()self._budget_engaged_once = Truediff --git a/exllamav3/guard.py b/exllamav3/guard.pynew file mode 100755index 0000000..c383389--- /dev/null+++ b/exllamav3/guard.py@@ -0,0 +1,490 @@+#!/usr/bin/env python3+"""+guard.py -- an external supervisor that SIGKILLs its child before the box dies.++Why this exists+---------------+On unified-memory boxes (DGX Spark/GB10, Strix Halo) the GPU and the host share one+pool. There is no separate VRAM, and when the pool is exhausted the kernel can starve+rather than OOM-kill, costing a physical power cycle. `torch.cuda.mem_get_info()`+reports MemFree, not MemAvailable, so nothing inside the process notices. This+supervisor watches /proc/meminfo and the per-device free memory from the OUTSIDE, in a+process that allocates nothing, and kills the child while there is still room to+recover.++It is also the page-cache release: exllamav3 reads shards with buffered pread, so on+unified memory the shards end up resident twice -- once on the device, once in page+cache -- and the page cache half grows DURING the load, before any in-process hook+could run.++Usage+-----+ python exllamav3/guard.py [options] -- <command> [args...]++Options+-------+ --floor-gib F kill when host MemAvailable < F GiB (default 6)+ --device-floor-gib F kill when any watched device free < F GiB (default 0 = off)+ --device-floor SPEC per-device floors, e.g. card1=4.5,nvidia:0=2+ --interval S poll period in seconds (default 0.5)+ --warn-gib F log a warning below this (default floor + 8)+ --log PATH also append the sampler trace here+ --grace S seconds to wait after SIGKILL (default 30)+ --fadvise-dir DIR release DIR/*.safetensors page cache periodically+ --fadvise-every S page-cache release period (default 5)+ --selftest print what it would do++Exit code+---------+ the child's exit code, or 137 if guard killed it (and a loud explanation on+ stderr / in --log).++`util/memguard.py` remains as a compatibility wrapper that execs this file without+importing the package (so it does not initialize torch or the allocator).+"""++from __future__ import annotations++import argparse+import glob+import os+import signal+import subprocess+import sys+import time++GIB = 1024.0 * 1024.0 * 1024.0+++def meminfo() -> dict[str, int]:+ """Return /proc/meminfo in bytes. Cheap: one read of a ~1.5 kB pseudo-file."""+ out = {}+ try:+ with open("/proc/meminfo", "r", encoding = "ascii") as f:+ for line in f:+ k, _, rest = line.partition(":")+ rest = rest.strip()+ if rest.endswith(" kB"):+ out[k] = int(rest[:-3]) * 1024+ else:+ try:+ out[k] = int(rest)+ except ValueError:+ pass+ except OSError:+ pass+ return out+++def fmt_gib(x: float) -> str:+ return f"{x / GIB:6.1f}"+++def proc_rss(pid: int) -> int:+ try:+ with open(f"/proc/{pid}/status", "r", encoding = "ascii") as f:+ for line in f:+ if line.startswith("VmRSS:"):+ return int(line.split()[1]) * 1024+ except (OSError, ValueError):+ pass+ return 0+++class Logger:+ def __init__(self, path: str | None):+ self.fh = open(path, "a", buffering = 1) if path else None # noqa: SIM115++ def __call__(self, msg: str) -> None:+ line = f"[guard {time.strftime('%H:%M:%S')}] {msg}"+ print(line, file = sys.stderr, flush = True)+ if self.fh:+ self.fh.write(line + "\n")+++def kill_tree(pid: int, sig: int) -> None:+ """Signal the child's whole process group (it is a session leader, see start_new_session)."""+ try:+ os.killpg(os.getpgid(pid), sig)+ except (ProcessLookupError, PermissionError):+ try:+ os.kill(pid, sig)+ except ProcessLookupError:+ pass+++def _read_int(path: str) -> int | None:+ try:+ with open(path, "r", encoding = "ascii") as f:+ return int(f.read().strip())+ except (OSError, ValueError):+ return None+++def amd_device_free() -> dict[str, int]:+ """Free memory of every AMD DRM card, in bytes.++ An APU's unified pool is the GTT aperture, whose total is close to host RAM. A+ discrete card also exposes ``mem_info_gtt_*`` (a host-RAM aperture), but its real+ budget is VRAM, so choose by pool size rather than by file presence.+ """+ out: dict[str, int] = {}+ host_total = meminfo().get("MemTotal", 0)+ for card in sorted(glob.glob("/sys/class/drm/card[0-9]*")):+ device = os.path.join(card, "device")+ name = os.path.basename(card)+ gtt_total = _read_int(os.path.join(device, "mem_info_gtt_total"))+ gtt_used = _read_int(os.path.join(device, "mem_info_gtt_used"))+ vram_total = _read_int(os.path.join(device, "mem_info_vram_total"))+ vram_used = _read_int(os.path.join(device, "mem_info_vram_used"))+ total = used = None+ if gtt_total is not None and host_total and gtt_total >= 0.9 * host_total:+ total, used = gtt_total, gtt_used+ elif vram_total is not None:+ total, used = vram_total, vram_used+ elif gtt_total is not None:+ total, used = gtt_total, gtt_used+ if total is not None and used is not None:+ out[name] = max(0, total - used)+ return out+++_NVIDIA_CACHE: dict[str, object] = {"t": -1e9, "data": {}, "unavailable": False,+ "last_try": -1e9}+NVIDIA_QUERY_INTERVAL_S = 5.0+NVIDIA_RETRY_S = 60.0+++def nvidia_device_free(now: float | None = None, force: bool = False) -> dict[str, int]:+ """Cached NVIDIA query; ``nvidia-smi`` is not spawned on every supervisor poll."""+ now = time.monotonic() if now is None else now+ if not force:+ if _NVIDIA_CACHE["unavailable"] and now - float(_NVIDIA_CACHE["last_try"]) < NVIDIA_RETRY_S:+ return {}+ if now - float(_NVIDIA_CACHE["t"]) < NVIDIA_QUERY_INTERVAL_S:+ return dict(_NVIDIA_CACHE["data"])+ _NVIDIA_CACHE["last_try"] = now+ try:+ result = subprocess.run(+ ["nvidia-smi", "--query-gpu=index,memory.total,memory.used",+ "--format=csv,noheader,nounits"],+ capture_output = True, text = True, timeout = 5, check = False)+ except (OSError, subprocess.TimeoutExpired):+ _NVIDIA_CACHE.update(unavailable = True, t = now, data = {})+ return {}+ if result.returncode != 0:+ _NVIDIA_CACHE.update(unavailable = True, t = now, data = {})+ return {}+ out: dict[str, int] = {}+ for line in result.stdout.splitlines():+ parts = [p.strip() for p in line.split(",")]+ if len(parts) != 3:+ continue+ try:+ index, total_mib, used_mib = int(parts[0]), float(parts[1]), float(parts[2])+ except ValueError:+ continue+ out[f"nvidia:{index}"] = int(max(0.0, total_mib - used_mib) * 1024 * 1024)+ _NVIDIA_CACHE.update(unavailable = False, t = now, data = out)+ return dict(out)+++def device_free(floors: dict[str, float] | None = None, now: float | None = None,+ force_nvidia: bool = False) -> dict[str, int]:+ out = amd_device_free()+ wanted = floors or {}+ want_nvidia = force_nvidia or not wanted or any(+ key.startswith("nvidia") or key in ("default", "nvidia") for key in wanted)+ if want_nvidia:+ out.update(nvidia_device_free(now = now, force = force_nvidia))+ return out+++def parse_device_floors(specs: list[str] | None, global_gib: float) -> dict[str, float]:+ """Parse ``card1=4.5,nvidia:0=2`` plus a global fallback, in GiB."""+ floors: dict[str, float] = {}+ for spec in specs or []:+ for item in spec.split(","):+ item = item.strip()+ if not item:+ continue+ key, sep, raw = item.partition("=")+ if not sep:+ raise SystemExit(f"--device-floor expected selector=GiB, got {item!r}")+ try:+ floors[key.strip().lower()] = float(raw)+ except ValueError as exc:+ raise SystemExit(f"--device-floor bad value for {key!r}: {raw!r}") from exc+ if global_gib > 0:+ floors.setdefault("default", float(global_gib))+ return floors+++def floor_for(name: str, floors: dict[str, float]) -> float:+ key = name.lower()+ if key in floors:+ return floors[key]+ if key.startswith("nvidia:") and "nvidia" in floors:+ return floors["nvidia"]+ if key.startswith("card") and "amd" in floors:+ return floors["amd"]+ return floors.get("default", 0.0)+++def effective_floor(name: str, floors: dict[str, float], multiple: bool) -> float:+ """A global floor is not safe on a multi-device host: use explicit selectors."""+ key = name.lower()+ if key in floors:+ return floors[key]+ if key.startswith("nvidia:") and "nvidia" in floors:+ return floors["nvidia"]+ if key.startswith("card") and "amd" in floors:+ return floors["amd"]+ return 0.0 if multiple else floors.get("default", 0.0)+++def main() -> int:+ ap = argparse.ArgumentParser(add_help = True)+ ap.add_argument("--floor-gib", type = float, default = 6.0)+ ap.add_argument("--warn-gib", type = float, default = None)+ ap.add_argument("--interval", type = float, default = 0.5)+ ap.add_argument("--log", type = str, default = None)+ ap.add_argument("--grace", type = float, default = 30.0)+ ap.add_argument("--label", type = str, default = None)+ ap.add_argument("--device-floor-gib", type = float, default = 0.0,+ help = "free-memory floor for every watched device, in GiB (0 = off)")+ ap.add_argument("--device-floor", action = "append", default = [],+ help = "per-device floors, e.g. card1=4.5,nvidia:0=2")+ ap.add_argument(+ "--fadvise-dir",+ action = "append",+ default = [],+ help = "model dir whose *.safetensors should be dropped from page cache periodically "+ "while the child runs. exllamav3 reads shards with buffered pread, so on unified "+ "memory the shards end up resident twice -- once on the device, once in page "+ "cache -- and the page cache half grows DURING the load, i.e. before any "+ "in-process hook could run. Doing it from the supervisor covers every loader.",+ )+ ap.add_argument("--fadvise-every", type = float, default = 5.0)+ ap.add_argument("--selftest", action = "store_true")+ ap.add_argument("cmd", nargs = argparse.REMAINDER)+ args = ap.parse_args()++ log = Logger(args.log)+ floors = parse_device_floors(args.device_floor, args.device_floor_gib)++ if args.selftest:+ mi = meminfo()+ log(+ f"selftest: MemAvailable {fmt_gib(mi.get('MemAvailable', 0))} GiB "+ f"MemFree {fmt_gib(mi.get('MemFree', 0))} GiB Cached {fmt_gib(mi.get('Cached', 0))} GiB "+ f"floor {args.floor_gib} GiB -> would "+ f"{'KILL' if mi.get('MemAvailable', 0) < args.floor_gib * GIB else 'run'}"+ )+ dev = device_free(floors, force_nvidia = True)+ for name, free in sorted(dev.items()):+ floor = effective_floor(name, floors, len(dev) > 1)+ log(f"selftest: {name} free {fmt_gib(free)} GiB, device floor {floor:.1f} GiB")+ return 0++ cmd = args.cmd+ if cmd and cmd[0] == "--":+ cmd = cmd[1:]+ if not cmd:+ ap.error("no command given (use: guard.py [opts] -- cmd args...)")++ floor = args.floor_gib * GIB+ warn = (args.warn_gib if args.warn_gib is not None else args.floor_gib + 8.0) * GIB++ mi = meminfo()+ label = args.label or os.path.basename(cmd[-1] if len(cmd) > 1 else cmd[0])+ log(+ f"start [{label}] host floor={args.floor_gib:.1f} GiB every {args.interval}s; "+ f"MemAvailable {fmt_gib(mi.get('MemAvailable', 0))} GiB, Cached {fmt_gib(mi.get('Cached', 0))} GiB"+ )+ if floors:+ dev = device_free(floors)+ if dev:+ multiple = len(dev) > 1+ if multiple and floors.get("default", 0) > 0:+ log("WARNING: a global device floor is ignored on a multi-device host; "+ "use --device-floor <cardN|nvidia:N>=GiB to select devices")+ log("device floors: " + ", ".join(+ f"{name}={effective_floor(name, floors, multiple):.1f} GiB "+ f"(free {fmt_gib(free)})"+ for name, free in sorted(dev.items())))+ else:+ log("device floors requested but no per-device query is available; "+ "using the host floor only")+ log("cmd: " + " ".join(cmd))++ if mi.get("MemAvailable", 0) < floor:+ log(+ f"REFUSING TO START: MemAvailable {fmt_gib(mi.get('MemAvailable', 0))} GiB is already "+ f"below the {args.floor_gib:.1f} GiB floor"+ )+ return 3++ t0 = time.time()+ # start_new_session so the child gets its own process group; a model load spawns+ # worker threads/processes and we want to kill all of them at once.+ child = subprocess.Popen(cmd, start_new_session = True)++ lowest = mi.get("MemAvailable", 0)+ peak_rss = 0+ last_warn = 0.0+ last_beat = 0.0+ last_fadv = 0.0+ killed = False+ device_warned = False++ fadvise_files: list[str] = []+ for d in args.fadvise_dir:+ if os.path.isdir(d):+ fadvise_files += sorted(+ os.path.join(d, f) for f in os.listdir(d) if f.endswith(".safetensors")+ )+ elif os.path.isfile(d):+ fadvise_files.append(d)+ if fadvise_files:+ log(+ f"page-cache release armed for {len(fadvise_files)} shard(s) every "+ f"{args.fadvise_every}s"+ )++ def fadvise_now() -> int:+ n = 0+ for p in fadvise_files:+ try:+ fd = os.open(p, os.O_RDONLY)+ except OSError:+ continue+ try:+ os.posix_fadvise(fd, 0, 0, os.POSIX_FADV_DONTNEED)+ n += 1+ except OSError:+ pass+ finally:+ os.close(fd)+ return n++ try:+ while True:+ rc = child.poll()+ if rc is not None:+ break+ mi = meminfo()+ avail = mi.get("MemAvailable", 0)+ lowest = min(lowest, avail)+ rss = proc_rss(child.pid)+ peak_rss = max(peak_rss, rss)+ now = time.time()++ if avail < floor:+ log(+ "*** MEMORY FLOOR BREACHED -- KILLING CHILD ***\n"+ f" MemAvailable {fmt_gib(avail)} GiB < floor {args.floor_gib:.1f} GiB\n"+ f" MemFree {fmt_gib(mi.get('MemFree', 0))} GiB "+ f"Cached {fmt_gib(mi.get('Cached', 0))} GiB "+ f"Dirty {fmt_gib(mi.get('Dirty', 0))} GiB\n"+ f" child pid {child.pid} RSS {fmt_gib(rss)} GiB, alive {now - t0:.1f}s\n"+ " This box may have unified memory and does NOT OOM-kill; starving it "+ "costs a physical power cycle. Killing now."+ )+ killed = True+ kill_tree(child.pid, signal.SIGKILL)+ # Drop clean page cache immediately -- it is the cheapest memory to get back+ # and it is usually what is squeezing us.+ try:+ with open("/proc/sys/vm/drop_caches", "w", encoding = "ascii") as f:+ f.write("1\n")+ log(" dropped clean page cache (vm.drop_caches=1)")+ except OSError:+ pass+ break++ if floors:+ dev = device_free(floors, now = now)+ if not dev and not device_warned:+ device_warned = True+ log("device-floor query unavailable; falling back to the host floor")+ multiple = len(dev) > 1+ for name, free in sorted(dev.items()):+ dev_floor = effective_floor(name, floors, multiple)+ if dev_floor > 0 and free < dev_floor * GIB:+ log(+ "*** DEVICE MEMORY FLOOR BREACHED -- KILLING CHILD ***\n"+ f" {name} free {fmt_gib(free)} GiB < floor {dev_floor:.1f} GiB\n"+ f" host MemAvailable {fmt_gib(avail)} GiB\n"+ f" child pid {child.pid} RSS {fmt_gib(rss)} GiB, "+ f"alive {now - t0:.1f}s\n"+ " Killing before the unified pool starves the box."+ )+ killed = True+ kill_tree(child.pid, signal.SIGKILL)+ break+ if killed:+ break++ if fadvise_files and now - last_fadv >= args.fadvise_every:+ last_fadv = now+ cached_before = mi.get("Cached", 0)+ fadvise_now()+ after = meminfo()+ freed = cached_before - after.get("Cached", 0)+ if freed > 2 * GIB:+ log(+ f"page-cache release: Cached {fmt_gib(cached_before)} -> "+ f"{fmt_gib(after.get('Cached', 0))} GiB, "+ f"MemAvailable {fmt_gib(after.get('MemAvailable', 0))} GiB"+ )++ if avail < warn and now - last_warn > 10.0:+ last_warn = now+ log(+ f"WARNING MemAvailable {fmt_gib(avail)} GiB (floor {args.floor_gib:.1f}), "+ f"Cached {fmt_gib(mi.get('Cached', 0))}, child RSS {fmt_gib(rss)}"+ )+ elif now - last_beat > 60.0:+ last_beat = now+ log(+ f"ok MemAvailable {fmt_gib(avail)} GiB Cached {fmt_gib(mi.get('Cached', 0))} GiB "+ f"child RSS {fmt_gib(rss)} GiB t+{now - t0:.0f}s"+ )++ time.sleep(args.interval)+ except KeyboardInterrupt:+ log("interrupted -- terminating child")+ kill_tree(child.pid, signal.SIGTERM)+ try:+ child.wait(timeout = 10)+ except subprocess.TimeoutExpired:+ kill_tree(child.pid, signal.SIGKILL)+ return 130++ if killed:+ deadline = time.time() + args.grace+ while time.time() < deadline:+ if child.poll() is not None:+ break+ time.sleep(0.2)+ mi = meminfo()+ log(+ f"child killed. MemAvailable now {fmt_gib(mi.get('MemAvailable', 0))} GiB. "+ f"lowest seen {fmt_gib(lowest)} GiB, peak child RSS {fmt_gib(peak_rss)} GiB, "+ f"wall {time.time() - t0:.1f}s"+ )+ return 137++ rc = child.wait()+ mi = meminfo()+ log(+ f"child exited rc={rc} after {time.time() - t0:.1f}s; "+ f"lowest MemAvailable seen {fmt_gib(lowest)} GiB, peak child RSS {fmt_gib(peak_rss)} GiB; "+ f"MemAvailable now {fmt_gib(mi.get('MemAvailable', 0))} GiB"+ )+ return rc+++if __name__ == "__main__":+ sys.exit(main())diff --git a/exllamav3/memory_guard.py b/exllamav3/memory_guard.pynew file mode 100644index 0000000..35af88d--- /dev/null+++ b/exllamav3/memory_guard.py@@ -0,0 +1,604 @@+from __future__ import annotations++"""Read-only pre-flight memory guard for unified and dedicated devices.++The guard is deliberately independent of the split placement code: ``device_map``+estimates what each device will hold (weights, cache, reserve slabs and the prefill+workspace) and hands the numbers to :class:`OOMGuard`. The guard only compares them+with the device and host budgets and either refuses the load, logs a warning, or does+nothing. It never allocates, changes an allocator setting or mutates the plan.++The arithmetic is kept in one place so the split adapters cannot drift:++* dedicated VRAM: ``capacity = min(total, free) - reserve - safety - floor``+* unified/GTT: the observed usable ceiling (default 113.3 GiB of a reported 118 GiB,+ i.e. the ~4.5 GiB reserve) is the hard cap; the current free memory is a second cap:+ ``capacity = min(usable_ceiling, free - reserve) - safety - floor``. The reserve is+ not subtracted twice: the ceiling already accounts for the unified overhead.+* unified devices additionally consume the host pool, so the summed GTT footprint is+ compared with ``MemAvailable - host_floor``.++Per-device settings accept the split's device-selector syntax:+``gfx1151=4.5,gfx1201=0.8``, ``cuda:0=4`` or a bare number for every device.+"""++import dataclasses+import os+import sys+from collections.abc import Callable, Iterable+from dataclasses import dataclass, field++GIB = 1024 ** 3++# Calibrated, overridable tuning values from the measured Strix Halo + RX 9070 pair.+DEFAULT_UNIFIED_RESERVE_GIB = 4.5+DEFAULT_DEDICATED_RESERVE_GIB = 0.8+DEFAULT_BULK_WORKSPACE_GIB = 2.0+DEFAULT_OTHER_WORKSPACE_GIB = 1.5+DEFAULT_SAFETY_GIB = 0.0+DEFAULT_DEVICE_FLOOR_GIB = 0.0+DEFAULT_HOST_FLOOR_GIB = 6.0+DEFAULT_UNIFIED_CEILING_GIB = 113.3++# Do not refuse a load that misses the estimate by a hair: the estimator is byte+# accounting, not a measurement. The band is small enough that the measured 640K+# failure is still refused while a measured-fits 500K point is not.+DEFAULT_TOLERANCE_GIB = 0.25++MODES = ("auto", "warn", "off")+++class OOMGuardError(RuntimeError):+ """The estimated footprint cannot fit; raised before any allocation."""+++# ---------------------------------------------------------------------------------------------------------+# Device settings+# ---------------------------------------------------------------------------------------------------------++def parse_device_spec(value) -> tuple[float | None, dict[str, float]]:+ """Parse a scalar or ``selector=value,selector=value`` device setting.++ Returns ``(default, overrides)``. ``default`` applies to every device that does+ not match an override. ``None`` means the caller's per-device default is used.+ """+ if value is None or value == "":+ return None, {}+ if isinstance(value, (int, float)):+ return float(value), {}+ text = str(value).strip()+ if not text:+ return None, {}+ if "=" not in text:+ try:+ return float(text), {}+ except ValueError as exc:+ raise ValueError(+ f"expected a number or selector=value list, got {value!r}") from exc+ default = None+ overrides: dict[str, float] = {}+ for item in text.split(","):+ item = item.strip()+ if not item:+ continue+ key, sep, raw = item.partition("=")+ if not sep:+ raise ValueError(f"expected selector=value, got {item!r}")+ try:+ number = float(raw)+ except ValueError as exc:+ raise ValueError(f"expected a number on the right of {key!r}, got {raw!r}") from exc+ key = key.strip().lower()+ if key in ("default", "all", "*"):+ default = number+ else:+ overrides[key] = number+ return default, overrides+++def resolve_device_spec(+ value,+ *,+ infos: Iterable,+ select: Callable[[str], int],+ default: Callable[[int], float],+) -> dict[int, float]:+ """Resolve a device spec to ``{torch_index: value}`` using the split selector.++ ``infos`` is the visible inventory (objects with ``.index``); ``select`` is the+ adapter's selector callback so ``gfxXXXX``/``cuda:N``/name/UUID semantics are+ exactly the split's.+ """+ scalar, overrides = parse_device_spec(value)+ out = {int(info.index): (float(scalar) if scalar is not None else float(default(info.index)))+ for info in infos}+ for key, number in overrides.items():+ index = int(select(key))+ out[index] = float(number)+ return out+++@dataclass+class DeviceBudget:+ """Per-device pre-flight policy.++ ``reserve``, ``workspace``, ``safety`` and ``device_floor`` may be a number, a+ selector list or ``None`` (use the mode-dependent defaults).+ """++ mode: str = "auto"+ reserve: str | float | None = None+ workspace: str | float | None = None+ safety: str | float | None = None+ device_floor: str | float | None = None+ unified_reserve_gib: float = DEFAULT_UNIFIED_RESERVE_GIB+ dedicated_reserve_gib: float = DEFAULT_DEDICATED_RESERVE_GIB+ bulk_workspace_gib: float = DEFAULT_BULK_WORKSPACE_GIB+ other_workspace_gib: float = DEFAULT_OTHER_WORKSPACE_GIB+ safety_gib: float = DEFAULT_SAFETY_GIB+ device_floor_gib: float = DEFAULT_DEVICE_FLOOR_GIB+ host_floor_gib: float = DEFAULT_HOST_FLOOR_GIB+ unified_ceiling_gib: float = DEFAULT_UNIFIED_CEILING_GIB+ tolerance_gib: float = DEFAULT_TOLERANCE_GIB++ def __post_init__(self) -> None:+ self.mode = (self.mode or "auto").strip().lower()+ if self.mode not in MODES:+ raise ValueError(f"oom guard mode must be one of {MODES}, not {self.mode!r}")++ @classmethod+ def from_env(cls, default_mode: str = "auto") -> DeviceBudget:+ """Build from ``KYOJIN_OOM_GUARD*`` environment fallbacks."""+ def f(name, fallback):+ try:+ return float(os.environ.get(name, fallback))+ except ValueError:+ return float(fallback)++ return cls(+ mode=os.environ.get("KYOJIN_OOM_GUARD", default_mode),+ reserve=os.environ.get("KYOJIN_OOM_GUARD_RESERVE_GIB"),+ workspace=os.environ.get("KYOJIN_OOM_GUARD_WORKSPACE_GIB"),+ safety=os.environ.get("KYOJIN_OOM_GUARD_SAFETY_GIB"),+ device_floor=os.environ.get("KYOJIN_OOM_GUARD_DEVICE_FLOOR"),+ unified_reserve_gib=f("KYOJIN_OOM_GUARD_UNIFIED_RESERVE_GIB", DEFAULT_UNIFIED_RESERVE_GIB),+ dedicated_reserve_gib=f("KYOJIN_OOM_GUARD_DEDICATED_RESERVE_GIB", DEFAULT_DEDICATED_RESERVE_GIB),+ bulk_workspace_gib=f("KYOJIN_OOM_GUARD_BULK_WORKSPACE_GIB", DEFAULT_BULK_WORKSPACE_GIB),+ other_workspace_gib=f("KYOJIN_OOM_GUARD_OTHER_WORKSPACE_GIB", DEFAULT_OTHER_WORKSPACE_GIB),+ safety_gib=f("KYOJIN_OOM_GUARD_DEFAULT_SAFETY_GIB", DEFAULT_SAFETY_GIB),+ device_floor_gib=f("KYOJIN_OOM_GUARD_DEFAULT_DEVICE_FLOOR_GIB", DEFAULT_DEVICE_FLOOR_GIB),+ host_floor_gib=f("KYOJIN_OOM_GUARD_HOST_FLOOR_GIB", DEFAULT_HOST_FLOOR_GIB),+ unified_ceiling_gib=f("KYOJIN_OOM_GUARD_USABLE_CEILING_GIB", DEFAULT_UNIFIED_CEILING_GIB),+ tolerance_gib=f("KYOJIN_OOM_GUARD_TOLERANCE_GIB", DEFAULT_TOLERANCE_GIB),+ )++ def resolve(+ self,+ infos: Iterable,+ select: Callable[[str], int],+ *,+ unified: dict[int, bool],+ bulk_index: int | None,+ ) -> dict[str, dict[int, float]]:+ """Resolve every setting to a per-device byte map."""+ def is_unified(index: int) -> bool:+ return bool(unified.get(int(index), False))++ def reserve_default(index: int) -> float:+ return self.unified_reserve_gib if is_unified(index) else self.dedicated_reserve_gib++ def workspace_default(index: int) -> float:+ return self.bulk_workspace_gib if bulk_index is not None and int(index) == int(bulk_index) \+ else self.other_workspace_gib++ def safety_default(_index: int) -> float:+ return self.safety_gib++ def floor_default(_index: int) -> float:+ return self.device_floor_gib++ return {+ "reserve": resolve_device_spec(self.reserve, infos = infos, select = select,+ default = reserve_default),+ "workspace": resolve_device_spec(self.workspace, infos = infos, select = select,+ default = workspace_default),+ "safety": resolve_device_spec(self.safety, infos = infos, select = select,+ default = safety_default),+ "device_floor": resolve_device_spec(self.device_floor, infos = infos, select = select,+ default = floor_default),+ }+++# ---------------------------------------------------------------------------------------------------------+# Device/host probes (monkeypatchable in CPU tests)+# ---------------------------------------------------------------------------------------------------------++def _torch():+ import torch+ return torch+++def meminfo() -> dict[str, int]:+ """Return ``/proc/meminfo`` in bytes (empty when unavailable)."""+ out: dict[str, int] = {}+ try:+ with open("/proc/meminfo", "r", encoding = "ascii") as f:+ for line in f:+ key, _, rest = line.partition(":")+ rest = rest.strip()+ if rest.endswith(" kB"):+ out[key] = int(rest[:-3]) * 1024+ else:+ try:+ out[key] = int(rest)+ except ValueError:+ pass+ except OSError:+ pass+ return out+++def host_available_bytes() -> int | None:+ value = meminfo().get("MemAvailable")+ return int(value) if value is not None else None+++def host_total_bytes() -> int | None:+ value = meminfo().get("MemTotal")+ return int(value) if value is not None else None+++def device_total_bytes(index: int) -> int | None:+ try:+ torch = _torch()+ return int(torch.cuda.get_device_properties(int(index)).total_memory)+ except Exception: # noqa: BLE001 - CPU tests / unavailable probe+ return None+++def device_free_bytes(index: int) -> int | None:+ try:+ torch = _torch()+ free, _total = torch.cuda.mem_get_info(int(index))+ return int(free)+ except Exception: # noqa: BLE001 - CPU tests / unavailable probe+ return None+++def is_unified_device(index: int, arch: str | None = None, total: int | None = None) -> bool:+ """Positive unified/GTT detection, independent of a hardcoded device index.++ Large dedicated GPUs can have more than half of host RAM in VRAM, so a bare+ total/host ratio is not enough. Require an APU arch/property, or a near-host+ total together with a GTT sysfs pool, so a discrete card is never put on the+ host-pool budget.+ """+ arch_key = (arch or "").strip().lower()+ if arch_key.startswith("gfx115"):+ return True+ props = None+ try:+ props = _torch().cuda.get_device_properties(int(index))+ except Exception: # noqa: BLE001, S110 - unavailable probe+ pass+ if props is not None:+ if getattr(props, "is_integrated", False) or getattr(props, "integrated", False):+ return True+ name = (getattr(props, "name", "") or "").lower()+ if "gb10" in name or "dgx spark" in name:+ return True+ total = device_total_bytes(index) if total is None else total+ host = host_total_bytes()+ if total is not None and host is not None and total >= 0.9 * host:+ import glob+ if glob.glob("/sys/class/drm/card*/device/mem_info_gtt_total"):+ return True+ return False+++# ---------------------------------------------------------------------------------------------------------+# Footprints and comparison+# ---------------------------------------------------------------------------------------------------------++@dataclass+class DeviceFootprint:+ index: int+ arch: str = ""+ name: str = ""+ unified: bool = False+ total_bytes: int | None = None+ free_bytes: int | None = None+ weights_bytes: int = 0+ cache_bytes: int = 0+ slab_bytes: int = 0 # actually held during the load (the part0 reserve slab)+ reserve_bytes: int = 0 # headroom policy: reduces capacity, not footprint+ workspace_bytes: int = 0+ safety_bytes: int = 0+ floor_bytes: int = 0++ @property+ def need_bytes(self) -> int:+ """Estimated resident footprint (headroom is a capacity reduction, not a byte)."""+ return (int(self.weights_bytes) + int(self.cache_bytes) + int(self.slab_bytes)+ + int(self.workspace_bytes))++ def capacity_bytes(self, unified_ceiling_gib: float) -> int | None:+ """Usable bytes for this device, or None when nothing can be probed."""+ reserve = int(self.reserve_bytes)+ if self.unified:+ hard = int(unified_ceiling_gib * GIB)+ if self.total_bytes is not None:+ hard = min(hard, int(self.total_bytes))+ if self.free_bytes is not None:+ hard = min(hard, int(self.free_bytes) - reserve)+ else:+ hard -= reserve+ else:+ if self.total_bytes is None and self.free_bytes is None:+ return None+ if self.free_bytes is None:+ base = int(self.total_bytes)+ elif self.total_bytes is None:+ base = int(self.free_bytes)+ else:+ base = min(int(self.total_bytes), int(self.free_bytes))+ hard = base - reserve+ hard -= int(self.safety_bytes) + int(self.floor_bytes)+ return max(0, hard)++ def describe(self) -> str:+ parts = [f"cuda:{self.index}"]+ if self.arch:+ parts.append(self.arch)+ if self.name:+ parts.append(self.name)+ if self.unified:+ parts.append("unified")+ return " ".join(parts)+++@dataclass+class DeviceResult:+ footprint: DeviceFootprint+ capacity_bytes: int | None++ @property+ def deficit_bytes(self) -> int:+ if self.capacity_bytes is None:+ return 0+ return max(0, self.footprint.need_bytes - self.capacity_bytes)++++@dataclass+class HostResult:+ available_bytes: int | None+ need_bytes: int+ floor_bytes: int++ @property+ def capacity_bytes(self) -> int | None:+ if self.available_bytes is None:+ return None+ return max(0, int(self.available_bytes) - int(self.floor_bytes))++ @property+ def deficit_bytes(self) -> int:+ if self.capacity_bytes is None:+ return 0+ return max(0, int(self.need_bytes) - int(self.capacity_bytes))++++@dataclass+class GuardReport:+ device_results: list[DeviceResult] = field(default_factory = list)+ host_result: HostResult | None = None+ tolerance_gib: float = DEFAULT_TOLERANCE_GIB++ @property+ def issues(self) -> list[str]:+ out = []+ band = int(self.tolerance_gib * GIB)+ for result in self.device_results:+ if result.capacity_bytes is not None and result.deficit_bytes > band:+ out.append(f"cuda:{result.footprint.index} needs "+ f"{result.footprint.need_bytes / GIB:.2f} GiB, capacity "+ f"{result.capacity_bytes / GIB:.2f} GiB "+ f"(deficit {result.deficit_bytes / GIB:.2f} GiB)")+ if self.host_result is not None and self.host_result.capacity_bytes is not None \+ and self.host_result.deficit_bytes > band:+ out.append(f"host needs {self.host_result.need_bytes / GIB:.2f} GiB GTT, "+ f"capacity {self.host_result.capacity_bytes / GIB:.2f} GiB "+ f"(deficit {self.host_result.deficit_bytes / GIB:.2f} GiB)")+ return out++ @property+ def ok(self) -> bool:+ return not self.issues+++def _format_report(report: GuardReport, *, context: int | None,+ chosen_n: int | None, largest_n: int | None,+ largest_ctx: int | None) -> str:+ lines = ["device arch need capacity free total reserve workspace slab deficit"]+ for result in report.device_results:+ fp = result.footprint+ free = "?" if fp.free_bytes is None else f"{fp.free_bytes / GIB:8.2f}"+ total = "?" if fp.total_bytes is None else f"{fp.total_bytes / GIB:8.2f}"+ cap = "?" if result.capacity_bytes is None else f"{result.capacity_bytes / GIB:8.2f}"+ lines.append(+ f"{fp.describe():18s} {fp.need_bytes / GIB:8.2f} {cap:>10s} {free:>8s} {total:>8s} "+ f"{fp.reserve_bytes / GIB:7.2f} {fp.workspace_bytes / GIB:10.2f} "+ f"{fp.slab_bytes / GIB:5.2f} {result.deficit_bytes / GIB:8.2f}")+ if report.host_result is not None and report.host_result.capacity_bytes is not None:+ h = report.host_result+ lines.append(f"host MemAvailable {h.available_bytes / GIB:.2f} GiB, GTT need "+ f"{h.need_bytes / GIB:.2f} GiB, floor {h.floor_bytes / GIB:.2f} GiB, "+ f"capacity {h.capacity_bytes / GIB:.2f} GiB, deficit "+ f"{h.deficit_bytes / GIB:.2f} GiB")+ if context is not None:+ lines.append(f"chosen: part0 N={chosen_n} at -c {context}")+ if largest_n is not None:+ shown = "none" if largest_n < 0 else str(largest_n)+ lines.append(f"largest part0 N that fits at this context: {shown}")+ if largest_ctx is not None:+ lines.append(f"largest context that fits at this N: {largest_ctx}")+ return "\n".join(lines)+++class OOMGuard:+ """Compare prepared footprints with the per-device and host budgets."""++ def __init__(self, budget: DeviceBudget, resolved: dict[str, dict[int, float]],+ logger: Callable[[str], None] = print):+ self.budget = budget+ self.resolved = resolved+ self.logger = logger++ @classmethod+ def from_budget(cls, budget: DeviceBudget, infos, select, *,+ unified: dict[int, bool], bulk_index: int | None,+ logger: Callable[[str], None] = print) -> OOMGuard:+ return cls(budget, budget.resolve(infos, select, unified = unified,+ bulk_index = bulk_index), logger = logger)++ @property+ def mode(self) -> str:+ return self.budget.mode++ def footprint(self, index: int, arch: str = "", name: str = "", *,+ total_bytes: int | None = None,+ free_bytes: int | None = None, weights_bytes: int = 0,+ cache_bytes: int = 0, reserve_bytes: int = 0) -> DeviceFootprint:+ index = int(index)+ unified = is_unified_device(index, arch, total_bytes)+ if total_bytes is None:+ total_bytes = device_total_bytes(index)+ if free_bytes is None:+ free_bytes = device_free_bytes(index)+ reserve = self.resolved["reserve"].get(index, 0.0)+ workspace = self.resolved["workspace"].get(index, 0.0)+ safety = self.resolved["safety"].get(index, 0.0)+ floor = self.resolved["device_floor"].get(index, 0.0)+ return DeviceFootprint(+ index = index, arch = arch, name = name, unified = bool(unified),+ total_bytes = total_bytes, free_bytes = free_bytes,+ weights_bytes = int(weights_bytes), cache_bytes = int(cache_bytes),+ slab_bytes = int(reserve_bytes),+ reserve_bytes = int(reserve * GIB),+ workspace_bytes = int(workspace * GIB),+ safety_bytes = int(safety * GIB),+ floor_bytes = int(floor * GIB),+ )++ def evaluate(self, footprints: Iterable[DeviceFootprint],+ host_available: int | None = None) -> GuardReport:+ footprints = list(footprints)+ results = [DeviceResult(fp, fp.capacity_bytes(self.budget.unified_ceiling_gib))+ for fp in footprints]+ host_need = sum(fp.need_bytes for fp in footprints if fp.unified)+ host = None+ if any(fp.unified for fp in footprints):+ if host_available is None:+ host_available = host_available_bytes()+ host = HostResult(available_bytes = host_available, need_bytes = host_need,+ floor_bytes = int(self.budget.host_floor_gib * GIB))+ return GuardReport(device_results = results, host_result = host,+ tolerance_gib = self.budget.tolerance_gib)++ def check(self, footprints: Iterable[DeviceFootprint], *,+ host_available: int | None = None,+ context: int | None = None,+ chosen_n: int | None = None,+ largest_n: int | None = None,+ largest_ctx: int | None = None) -> GuardReport:+ report = self.evaluate(footprints, host_available = host_available)+ if self.mode == "off":+ return report+ for result in report.device_results:+ fp = result.footprint+ if result.capacity_bytes is None:+ self.logger(f"[oom-guard] {fp.describe()}: capacity unavailable; skipped")+ continue+ self.logger(f"[oom-guard] {fp.describe()}: need {fp.need_bytes / GIB:.2f} GiB "+ f"(weights {fp.weights_bytes / GIB:.2f}, cache {fp.cache_bytes / GIB:.2f}, "+ f"reserve {fp.reserve_bytes / GIB:.2f}, workspace {fp.workspace_bytes / GIB:.2f}, "+ f"slab {fp.slab_bytes / GIB:.2f}) "+ f"of {result.capacity_bytes / GIB:.2f} GiB")+ if report.host_result is not None and report.host_result.capacity_bytes is not None:+ h = report.host_result+ self.logger(f"[oom-guard] host: GTT need {h.need_bytes / GIB:.2f} GiB of "+ f"{h.capacity_bytes / GIB:.2f} GiB (MemAvailable "+ f"{h.available_bytes / GIB:.2f} - floor {h.floor_bytes / GIB:.2f})")+ if report.ok:+ return report+ message = _format_report(report, context = context, chosen_n = chosen_n,+ largest_n = largest_n, largest_ctx = largest_ctx)+ if self.mode == "warn":+ self.logger("[oom-guard] WARNING: estimated footprint does not fit "+ f"(mode=warn, continuing):\n{message}")+ return report+ raise OOMGuardError(+ "pre-flight OOM guard refused the load before allocating anything "+ f"(mode={self.mode}):\n{message}\n"+ "Lower -c/--max-ctx or --part0-layers, raise the reserve/workspace only if "+ "they are wrong, or set --oom-guard warn/off (KYOJIN_OOM_GUARD=warn|off).")+++def check_single_device(+ weights_bytes: int,+ cache_bytes: int,+ device,+ *,+ budget: DeviceBudget | None = None,+ arch: str = "",+ name: str = "",+ context: int | None = None,+ logger: Callable[[str], None] = print,+) -> GuardReport:+ """Best-effort guard for a single-device load (default mode ``warn``).++ Single-device defaults are not calibrated on every host, so an unset+ ``KYOJIN_OOM_GUARD`` mode means ``warn`` here. Split loads use ``auto``.+ """+ try:+ index = int(device)+ except (TypeError, ValueError):+ text = str(device)+ index = int(text.split(":", 1)[1]) if text.startswith("cuda:") else 0+ budget = budget or DeviceBudget.from_env(default_mode = "warn")+ if budget.mode == "off":+ return GuardReport()+ infos = [dataclasses.make_dataclass("_Info", [("index", int)])(index = index)]+ unified = {index: is_unified_device(index, arch)}+ guard = OOMGuard.from_budget(budget, infos, lambda _key: index,+ unified = unified, bulk_index = index,+ logger = logger)+ fp = guard.footprint(index, arch = arch, name = name, weights_bytes = weights_bytes,+ cache_bytes = cache_bytes)+ return guard.check([fp], context = context)+++def main(argv: list[str] | None = None) -> int:+ """Allow ``python -m exllamav3.memory_guard --selftest`` style probing."""+ import argparse+ ap = argparse.ArgumentParser(description = "pre-flight OOM guard self-test")+ ap.add_argument("--selftest", action = "store_true")+ ap.add_argument("--gib", type = float, default = 0.0,+ help = "simulate a single unified device needing this many GiB")+ args = ap.parse_args(argv)+ if not args.selftest:+ ap.error("nothing to do (use --selftest)")+ budget = DeviceBudget.from_env()+ guard = OOMGuard(budget, {"reserve": {}, "workspace": {}, "safety": {}, "device_floor": {}})+ fp = DeviceFootprint(index = 0, arch = "selftest", unified = True,+ total_bytes = 118 * GIB, free_bytes = 118 * GIB,+ weights_bytes = int(args.gib * GIB))+ report = guard.check([fp], context = 131072, chosen_n = 6)+ print("fits" if report.ok else "does not fit")+ return 0 if report.ok else 1+++if __name__ == "__main__":+ sys.exit(main())diff --git a/exllamav3/model_init.py b/exllamav3/model_init.pyindex 01471e6..44c46e1 100755--- a/exllamav3/model_init.py+++ b/exllamav3/model_init.py@@ -383,6 +383,12 @@ def init(printp(not quiet, f" -- layer split: {text_map.describe()}")if split_plan.auto:printp(not quiet, f" -- layer split: auto chose {text_map.part0_layers} part0 layer(s)")+ elif single_device and not args.tensor_parallel:+ # Single-device loads default to the guard's warn mode until the defaults are+ # calibrated on the host; an explicit KYOJIN_OOM_GUARD=auto/warn/off wins.+ from .device_map import check_single_device_guard+ check_single_device_guard(model, config, cache, single_device,+ logger = lambda m: printp(not quiet, m))# Parallelism optionstp_options = {diff --git a/exllamav3/serve_split.py b/exllamav3/serve_split.pyindex c6b20a4..93e947b 100644--- a/exllamav3/serve_split.py+++ b/exllamav3/serve_split.py@@ -14,6 +14,7 @@ exllamav3 imports are deliberately deferred to call time."""import argparse+import globimport osimport timefrom dataclasses import dataclass@@ -48,6 +49,145 @@ GRAPH_ENV_OFF = {"EXL3_HIP_GRAPH": "0",}+# ---------------------------------------------------------------------------------------------------------+# Allocator mode (applied before `import exllamav3`, process-global)+# ---------------------------------------------------------------------------------------------------------++EXPANDABLE_SEGMENTS_MODES = ("auto", "on", "off")++# `auto` turns expandable segments off only for large-context unified loads, the+# measured case where the default allocator's fragmentation costs the last ~0.5 GiB+# (512K loaded with expandable_segments:False and failed with the default). Both the+# context gate and the estimate are deliberately conservative and overridable:+# KYOJIN_EXPANDABLE_SEGMENTS_AUTO_CTX / _AUTO_OFF / --expandable-segments on|off.+AUTO_EXPANDABLE_MIN_CTX = 512 * 1024+AUTO_EXPANDABLE_CACHE_BYTES_PER_TOKEN = 16 * 1024 # upper band for MLA/MoE caches+AUTO_EXPANDABLE_BAND_GIB = 8.0+UNIFIED_USABLE_CEILING_GIB = 113.3+++def _meminfo_bytes(key: str) -> int | None:+ try:+ with open("/proc/meminfo", "r", encoding = "ascii") as f:+ for line in f:+ if line.startswith(key + ":"):+ return int(line.split()[1]) * 1024+ except OSError:+ pass+ return None+++def _has_gtt_device() -> bool:+ return bool(glob.glob("/sys/class/drm/card*/device/mem_info_gtt_total"))+++def _model_dir_bytes(path: str | None) -> int:+ if not path or not os.path.isdir(path):+ return 0+ total = 0+ try:+ for name in os.listdir(path):+ if name.endswith(".safetensors"):+ try:+ total += os.path.getsize(os.path.join(path, name))+ except OSError:+ pass+ except OSError:+ pass+ return total+++def _auto_expandable_off(model_dir: str | None, ctx: int | None,+ reserve_gib: float = 4.5) -> tuple[bool, str]:+ """Documented `auto` heuristic; returns ``(off, reason)``.++ Only large-context unified loads are considered. The estimate is the model's+ safetensors bytes plus a deliberately high cache-per-token band, so a model that+ clearly sits below the usable ceiling keeps Kyojin's normal default (expandable on).+ """+ try:+ min_ctx = int(os.environ.get("KYOJIN_EXPANDABLE_SEGMENTS_AUTO_CTX",+ str(AUTO_EXPANDABLE_MIN_CTX)))+ except ValueError:+ min_ctx = AUTO_EXPANDABLE_MIN_CTX+ if not ctx or ctx < min_ctx:+ return False, f"context below the {min_ctx} token auto-off gate"+ if not _has_gtt_device():+ return False, "no unified/GTT device detected"+ host_total = _meminfo_bytes("MemTotal")+ model_bytes = _model_dir_bytes(model_dir)+ if not host_total or not model_bytes:+ return False, "model size or host total unavailable"+ usable = min(host_total, int(UNIFIED_USABLE_CEILING_GIB * 1024 ** 3))+ estimate = model_bytes + int(ctx * AUTO_EXPANDABLE_CACHE_BYTES_PER_TOKEN) + int(reserve_gib * 1024 ** 3)+ band = int(AUTO_EXPANDABLE_BAND_GIB * 1024 ** 3)+ off = estimate >= usable - band+ return off, (f"estimate {estimate / 1024 ** 3:.1f} GiB vs usable "+ f"{usable / 1024 ** 3:.1f} GiB at -c {ctx}")+++def _merge_allocator_conf(conf: str | None, value: bool) -> str:+ """Return PYTORCH_CUDA_ALLOC_CONF with expandable_segments forced to ``value``."""+ parts = [p.strip() for p in (conf or "").split(",") if p.strip()]+ parts = [p for p in parts if not p.lower().startswith("expandable_segments:")]+ parts.append(f"expandable_segments:{'True' if value else 'False'}")+ return ",".join(parts)+++def apply_allocator_env(settings: "SplitSettings", *, model_dir: str | None = None,+ ctx: int | None = None, logger = print) -> str:+ """Apply ``--expandable-segments`` before the first ``import exllamav3``.++ Returns the chosen mode (``on`` or ``off``). ``auto`` never changes anything+ unless the documented large-context unified heuristic fires; an explicit+ ``EXL3_EXPANDABLE_SEGMENTS=0`` is always honoured.+ """+ mode = (getattr(settings, "expandable_segments", None) or "auto").strip().lower()+ if mode not in EXPANDABLE_SEGMENTS_MODES:+ raise ValueError(f"--expandable-segments must be one of {EXPANDABLE_SEGMENTS_MODES}, "+ f"not {mode!r}")+ if os.environ.get("EXL3_EXPANDABLE_SEGMENTS", "").strip() == "0":+ logger("[allocator] EXL3_EXPANDABLE_SEGMENTS=0: expandable segments off")+ return "off"+ conf = os.environ.get("PYTORCH_CUDA_ALLOC_CONF", "").replace(" ", "").lower()+ if mode == "auto" and "expandable_segments:false" in conf:+ logger("[allocator] expandable segments off (PYTORCH_CUDA_ALLOC_CONF)")+ return "off"+ reason = ""+ if mode == "auto":+ forced = os.environ.get("KYOJIN_EXPANDABLE_SEGMENTS_AUTO_OFF", "").strip().lower()+ if forced in ("1", "on", "true", "yes"):+ off = True+ reason = "KYOJIN_EXPANDABLE_SEGMENTS_AUTO_OFF is set"+ else:+ off, reason = _auto_expandable_off(+ model_dir, ctx,+ reserve_gib=float(getattr(settings, "part0_reserve_gb", 1.2) or 1.2))+ if not off:+ logger(f"[allocator] expandable segments on (auto: {reason})")+ return "on"+ elif mode == "on":+ off = False+ reason = "explicit --expandable-segments on"+ else:+ off = True+ reason = "explicit --expandable-segments off"++ if off:+ os.environ["EXL3_EXPANDABLE_SEGMENTS"] = "0"+ os.environ["PYTORCH_CUDA_ALLOC_CONF"] = _merge_allocator_conf(+ os.environ.get("PYTORCH_CUDA_ALLOC_CONF"), False)+ logger(f"[allocator] expandable segments off ({reason}); this recovers about "+ "0.5 GiB of fragmentation, not additional capacity")+ return "off"++ os.environ["EXL3_EXPANDABLE_SEGMENTS"] = "1"+ if "PYTORCH_CUDA_ALLOC_CONF" in os.environ:+ os.environ["PYTORCH_CUDA_ALLOC_CONF"] = _merge_allocator_conf(+ os.environ.get("PYTORCH_CUDA_ALLOC_CONF"), True)+ logger(f"[allocator] expandable segments on ({reason})")+ return "on"+# Per-model unsafe-env presets. Stage 1 only needs the GLM adapter; the empty# entries are the declared slots for the later adapters.SPLIT_PRESETS: dict[str, dict[str, str]] = {@@ -84,6 +224,12 @@ class SplitSettings:part0_reserve_gb: float = DEFAULT_PART0_RESERVE_GBpreset: str = "auto"split_graphs: str = "auto"+ expandable_segments: str = "auto"+ oom_guard: str | None = None+ oom_guard_reserve_gib: str | None = None+ oom_guard_workspace_gib: str | None = None+ oom_guard_safety_gib: str | None = None+ oom_guard_device_floor: str | None = None@propertydef enabled(self) -> bool:@@ -93,12 +239,33 @@ class SplitSettings:def auto(self) -> bool:return self.part0_layers == "auto"+ @property+ def guard_mode(self) -> str:+ return self.oom_guard or ("auto" if self.enabled else "warn")++ def guard_budget(self):+ """Per-device pre-flight policy, with ``KYOJIN_OOM_GUARD*`` fallbacks."""+ from exllamav3.memory_guard import DeviceBudget+ budget = DeviceBudget.from_env(default_mode = self.guard_mode)+ if self.oom_guard:+ budget.mode = self.oom_guard.strip().lower()+ if self.oom_guard_reserve_gib is not None:+ budget.reserve = self.oom_guard_reserve_gib+ if self.oom_guard_workspace_gib is not None:+ budget.workspace = self.oom_guard_workspace_gib+ if self.oom_guard_safety_gib is not None:+ budget.safety = self.oom_guard_safety_gib+ if self.oom_guard_device_floor is not None:+ budget.device_floor = self.oom_guard_device_floor+ return budget+def describe(self) -> str:return (f"part0_layers={self.part0_layers} part1_device={self.part1_device} "f"part0_device={self.part0_device} "f"endcaps={'on' if self.endcaps else 'off'} "f"reserve={self.part0_reserve_gb:.2f}GiB preset={self.preset} "- f"graphs={self.split_graphs}")+ f"graphs={self.split_graphs} allocator={self.expandable_segments} "+ f"oom_guard={self.guard_mode}")def add_split_arguments(parser: argparse.ArgumentParser) -> None:@@ -123,6 +290,26 @@ def add_split_arguments(parser: argparse.ArgumentParser) -> None:help = "per-model split preset (default: KYOJIN_SPLIT_PRESET, else auto)")parser.add_argument("--split-graphs", choices = ("auto", "on", "off"), default = None,help = "per-segment graphs (Stage 6); auto forces graphs off for now")+ parser.add_argument("--expandable-segments", choices = EXPANDABLE_SEGMENTS_MODES, default = None,+ help = "allocator mode, applied before exllamav3/torch import: auto leaves "+ "expandable segments on except for large-context unified loads, on/off "+ "override it (default: KYOJIN_EXPANDABLE_SEGMENTS, else auto). Disabling "+ "recovers about 0.5 GiB of fragmentation, not capacity")+ parser.add_argument("--oom-guard", choices = ("auto", "warn", "off"), default = None,+ help = "pre-flight per-device memory guard: auto refuses an impossible load "+ "before allocating, warn only logs, off disables (default: "+ "KYOJIN_OOM_GUARD, else auto for split and warn for single-device)")+ parser.add_argument("--oom-guard-reserve-gib", type = str, default = None,+ help = "per-device headroom, e.g. 4.5 or cuda:0=4.5,cuda:1=0.8 "+ "(default: KYOJIN_OOM_GUARD_RESERVE_GIB, else 4.5 unified / 0.8 dedicated)")+ parser.add_argument("--oom-guard-workspace-gib", type = str, default = None,+ help = "per-device prefill workspace margin, e.g. cuda:0=4,cuda:1=3.5 "+ "(default: KYOJIN_OOM_GUARD_WORKSPACE_GIB, else 4.0 bulk / 3.5 other)")+ parser.add_argument("--oom-guard-safety-gib", type = str, default = None,+ help = "extra per-device safety margin (default: KYOJIN_OOM_GUARD_SAFETY_GIB, else 0)")+ parser.add_argument("--oom-guard-device-floor", type = str, default = None,+ help = "free-memory floor per device, for the preflight and the supervisor "+ "(default: KYOJIN_OOM_GUARD_DEVICE_FLOOR, else 0)")def settings_from_namespace(args) -> SplitSettings:@@ -139,6 +326,8 @@ def settings_from_namespace(args) -> SplitSettings:reserve = getattr(args, "part0_reserve_gb", None)if reserve is None:reserve = float(os.environ.get("KYOJIN_PART0_RESERVE_GB", str(DEFAULT_PART0_RESERVE_GB)))+ allocator = getattr(args, "expandable_segments", None) \+ or os.environ.get("KYOJIN_EXPANDABLE_SEGMENTS") or "auto"return SplitSettings(part0_layers = parse_part0_layers(raw),part1_device = getattr(args, "part1_device", None) or os.environ.get("KYOJIN_PART1_DEVICE") or "auto",@@ -147,6 +336,16 @@ def settings_from_namespace(args) -> SplitSettings:part0_reserve_gb = float(reserve),preset = (preset or "auto").strip().lower(),split_graphs = graphs,+ expandable_segments = (allocator or "auto").strip().lower(),+ oom_guard = getattr(args, "oom_guard", None) or os.environ.get("KYOJIN_OOM_GUARD"),+ oom_guard_reserve_gib = getattr(args, "oom_guard_reserve_gib", None)+ or os.environ.get("KYOJIN_OOM_GUARD_RESERVE_GIB"),+ oom_guard_workspace_gib = getattr(args, "oom_guard_workspace_gib", None)+ or os.environ.get("KYOJIN_OOM_GUARD_WORKSPACE_GIB"),+ oom_guard_safety_gib = getattr(args, "oom_guard_safety_gib", None)+ or os.environ.get("KYOJIN_OOM_GUARD_SAFETY_GIB"),+ oom_guard_device_floor = getattr(args, "oom_guard_device_floor", None)+ or os.environ.get("KYOJIN_OOM_GUARD_DEVICE_FLOOR"),)@@ -204,6 +403,7 @@ class SplitController:part0_layers = self.settings.part0_layers,part0_reserve_gb = self.settings.part0_reserve_gb,preset = self.settings.preset,+ guard_budget = self.settings.guard_budget(),logger = self.logger,)return self.plandiff --git a/tests/test_memory_guard_cpu.py b/tests/test_memory_guard_cpu.pynew file mode 100644index 0000000..6667186--- /dev/null+++ b/tests/test_memory_guard_cpu.py@@ -0,0 +1,251 @@+"""CPU tests for the pre-flight memory guard and the allocator-mode entry point.++The guard must be testable without a GPU: capacity arithmetic, per-device parsing,+refusal/warn/off behavior and the allocator env merge are pure Python.+"""+from __future__ import annotations++import importlib.util+import os+import sys+from pathlib import Path+from types import SimpleNamespace++import pytest++ROOT = Path(__file__).resolve().parents[1]+GIB = 1024 ** 3+++def _load(name: str, path: Path):+ spec = importlib.util.spec_from_file_location(name, path)+ assert spec is not None and spec.loader is not None+ module = importlib.util.module_from_spec(spec)+ sys.modules[name] = module+ spec.loader.exec_module(module)+ return module++[email protected](scope = "module")+def mg():+ module = _load("kyojin_memory_guard", ROOT / "exllamav3" / "memory_guard.py")+ yield module+ sys.modules.pop("kyojin_memory_guard", None)++[email protected](scope = "module")+def guard_mod():+ module = _load("kyojin_guard", ROOT / "exllamav3" / "guard.py")+ yield module+ sys.modules.pop("kyojin_guard", None)++[email protected](scope = "module")+def split_mod():+ module = _load("kyojin_serve_split_cpu", ROOT / "exllamav3" / "serve_split.py")+ yield module+ sys.modules.pop("kyojin_serve_split_cpu", None)+++def test_parse_device_spec_scalar_and_list(mg):+ assert mg.parse_device_spec(None) == (None, {})+ assert mg.parse_device_spec("4.5") == (4.5, {})+ assert mg.parse_device_spec("gfx1151=4.5,gfx1201=0.8") == (None, {"gfx1151": 4.5, "gfx1201": 0.8})+ assert mg.parse_device_spec("default=1,cuda:1=2") == (1.0, {"cuda:1": 2.0})+ with pytest.raises(ValueError):+ mg.parse_device_spec("gfx1151")+ with pytest.raises(ValueError):+ mg.parse_device_spec("gfx1151=big")+++def test_resolve_device_spec_uses_the_split_selector(mg):+ infos = [SimpleNamespace(index = 0), SimpleNamespace(index = 1)]+ seen = []++ def select(key):+ seen.append(key)+ return {"gfx1151": 1, "gfx1201": 0}[key]++ out = mg.resolve_device_spec("gfx1151=4.5,gfx1201=0.8", infos = infos, select = select,+ default = lambda _i: 1.0)+ assert out == {0: 0.8, 1: 4.5}+ assert seen == ["gfx1151", "gfx1201"]+++def test_budget_defaults_follow_unified_and_bulk(mg):+ infos = [SimpleNamespace(index = 0), SimpleNamespace(index = 1)]+ budget = mg.DeviceBudget(mode = "auto")+ resolved = budget.resolve(infos, lambda key: int(key.split(":")[1]),+ unified = {0: False, 1: True}, bulk_index = 1)+ assert resolved["reserve"] == {0: 0.8, 1: 4.5}+ assert resolved["workspace"] == {0: 1.5, 1: 2.0}+ assert resolved["safety"] == {0: 0.0, 1: 0.0}+ assert resolved["device_floor"] == {0: 0.0, 1: 0.0}+++def test_explicit_per_device_values_override_defaults(mg):+ infos = [SimpleNamespace(index = 0), SimpleNamespace(index = 1)]+ budget = mg.DeviceBudget(mode = "warn", reserve = "gfx1151=6",+ workspace = "cuda:0=1.5", safety = "2",+ device_floor = "gfx1151=1")+ resolved = budget.resolve(infos, lambda key: {"gfx1151": 1, "cuda:0": 0}[key],+ unified = {0: False, 1: True}, bulk_index = 1)+ assert resolved["reserve"] == {0: 0.8, 1: 6.0}+ assert resolved["workspace"] == {0: 1.5, 1: 2.0}+ assert resolved["safety"] == {0: 2.0, 1: 2.0}+ assert resolved["device_floor"] == {0: 0.0, 1: 1.0}+++def _footprint(mg, **overrides):+ values = {"index": 0, "arch": "gfx1151", "unified": True,+ "total_bytes": 118 * GIB, "free_bytes": 118 * GIB,+ "weights_bytes": 0, "cache_bytes": 0, "slab_bytes": 0,+ "reserve_bytes": 0, "workspace_bytes": 0, "safety_bytes": 0,+ "floor_bytes": 0}+ values.update(overrides)+ return mg.DeviceFootprint(**values)+++def test_unified_capacity_uses_the_usable_ceiling_without_double_counting(mg):+ fp = _footprint(mg, reserve_bytes = int(4.5 * GIB), weights_bytes = 100 * GIB,+ workspace_bytes = int(4 * GIB))+ capacity = fp.capacity_bytes(113.3)+ assert capacity == int(113.3 * GIB)+ assert fp.need_bytes == 104 * GIB+ assert fp.need_bytes < capacity++ # The same ceiling still caps a box that reports more raw memory.+ fp2 = _footprint(mg, total_bytes = 124 * GIB, free_bytes = 124 * GIB,+ reserve_bytes = int(4.5 * GIB))+ assert fp2.capacity_bytes(113.3) == int(113.3 * GIB)++ # Current free memory is a second cap; the reserve is subtracted from free only.+ fp3 = _footprint(mg, free_bytes = 100 * GIB, reserve_bytes = int(4.5 * GIB))+ assert fp3.capacity_bytes(113.3) == int(95.5 * GIB)+++def test_dedicated_capacity_subtracts_reserve_and_floor(mg):+ fp = _footprint(mg, arch = "gfx1201", unified = False, total_bytes = int(15.92 * GIB),+ free_bytes = int(15.92 * GIB), reserve_bytes = int(0.8 * GIB),+ floor_bytes = int(0.5 * GIB))+ assert fp.capacity_bytes(113.3) == int(15.92 * GIB) - int(0.8 * GIB) - int(0.5 * GIB)+++def _guard(mg, mode, reserve = "4.5", host_floor = 6.0):+ budget = mg.DeviceBudget(mode = mode, reserve = reserve, host_floor_gib = host_floor)+ resolved = {"reserve": {0: 4.5}, "workspace": {0: 4.0},+ "safety": {0: 0.0}, "device_floor": {0: 0.0}}+ return mg.OOMGuard(budget, resolved, logger = lambda *_a: None)+++def test_auto_refuses_and_warn_only_logs(mg):+ fp = _footprint(mg, weights_bytes = 112 * GIB, workspace_bytes = int(4 * GIB),+ reserve_bytes = int(4.5 * GIB))+ with pytest.raises(mg.OOMGuardError, match = "refused the load"):+ _guard(mg, "auto").check([fp], host_available = 120 * GIB,+ context = 786432, chosen_n = 5)+ report = _guard(mg, "warn").check([fp], host_available = 120 * GIB,+ context = 786432, chosen_n = 5)+ assert not report.ok+ off_report = _guard(mg, "off").check([fp], host_available = 1)+ assert not off_report.ok # off reports the estimate but never raises+++def test_host_pool_is_checked_even_when_the_device_fits(mg):+ fp = _footprint(mg, weights_bytes = 100 * GIB, workspace_bytes = int(4 * GIB))+ # Device capacity 113.3 fits, but only 104 GiB is available on the host.+ with pytest.raises(mg.OOMGuardError, match = "host MemAvailable"):+ _guard(mg, "auto").check([fp], host_available = 104 * GIB)+++def test_refusal_message_contains_table_and_largest_fit(mg):+ fp = _footprint(mg, weights_bytes = 112 * GIB, workspace_bytes = int(4 * GIB))+ guard = _guard(mg, "auto")+ with pytest.raises(mg.OOMGuardError) as exc:+ guard.check([fp], host_available = 120 * GIB, context = 786432,+ chosen_n = 5, largest_n = 3, largest_ctx = 524288)+ text = str(exc.value)+ assert "device" in text and "capacity" in text+ assert "largest part0 N that fits" in text and "3" in text+ assert "largest context that fits" in text and "524288" in text+++def test_single_device_default_mode_is_warn(mg, monkeypatch):+ monkeypatch.delenv("KYOJIN_OOM_GUARD", raising = False)+ monkeypatch.setattr(mg, "device_total_bytes", lambda _i: 118 * GIB)+ monkeypatch.setattr(mg, "device_free_bytes", lambda _i: 118 * GIB)+ monkeypatch.setattr(mg, "host_available_bytes", lambda: 120 * GIB)+ report = mg.check_single_device(116 * GIB, 0, 0, logger = lambda *_a: None)+ assert report is not None and not report.ok+++def test_allocator_off_sets_the_existing_opt_out_without_clobbering(mg, split_mod, monkeypatch):+ for key in ("EXL3_EXPANDABLE_SEGMENTS", "PYTORCH_CUDA_ALLOC_CONF"):+ monkeypatch.delenv(key, raising = False)+ monkeypatch.setenv("PYTORCH_CUDA_ALLOC_CONF", "max_split_size_mb:128")+ settings = split_mod.SplitSettings(part0_layers = 1, expandable_segments = "off")+ assert split_mod.apply_allocator_env(settings, logger = lambda *_a: None) == "off"+ assert os.environ["EXL3_EXPANDABLE_SEGMENTS"] == "0"+ conf = os.environ["PYTORCH_CUDA_ALLOC_CONF"]+ assert "max_split_size_mb:128" in conf and conf.endswith("expandable_segments:False")+ assert conf.count("expandable_segments:") == 1+++def test_allocator_on_overrides_a_false_allocator_conf(mg, split_mod, monkeypatch):+ monkeypatch.delenv("EXL3_EXPANDABLE_SEGMENTS", raising = False)+ monkeypatch.setenv("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:False,garbage_collection_threshold:0.8")+ settings = split_mod.SplitSettings(part0_layers = 1, expandable_segments = "on")+ assert split_mod.apply_allocator_env(settings, logger = lambda *_a: None) == "on"+ conf = os.environ["PYTORCH_CUDA_ALLOC_CONF"]+ assert conf.count("expandable_segments:") == 1+ assert "expandable_segments:True" in conf+ assert "garbage_collection_threshold:0.8" in conf+++def test_allocator_auto_stays_on_below_the_large_context_gate(split_mod, monkeypatch):+ monkeypatch.delenv("EXL3_EXPANDABLE_SEGMENTS", raising = False)+ monkeypatch.setenv("PYTORCH_CUDA_ALLOC_CONF", "max_split_size_mb:128")+ settings = split_mod.SplitSettings(part0_layers = 1, expandable_segments = "auto")+ assert split_mod.apply_allocator_env(settings, model_dir = "/nonexistent", ctx = 131072,+ logger = lambda *_a: None) == "on"+ assert "expandable_segments:" not in os.environ["PYTORCH_CUDA_ALLOC_CONF"]+++def test_allocator_auto_off_for_large_unified_load(split_mod, monkeypatch):+ monkeypatch.delenv("EXL3_EXPANDABLE_SEGMENTS", raising = False)+ monkeypatch.delenv("PYTORCH_CUDA_ALLOC_CONF", raising = False)+ monkeypatch.setattr(split_mod, "_has_gtt_device", lambda: True)+ monkeypatch.setattr(split_mod, "_model_dir_bytes", lambda _p: 119 * GIB)+ monkeypatch.setattr(split_mod, "_meminfo_bytes", lambda _k: 124 * GIB)+ settings = split_mod.SplitSettings(part0_layers = 1, expandable_segments = "auto")+ assert split_mod.apply_allocator_env(settings, model_dir = "/model", ctx = 512 * 1024,+ logger = lambda *_a: None) == "off"+ assert os.environ["EXL3_EXPANDABLE_SEGMENTS"] == "0"+ assert "expandable_segments:False" in os.environ["PYTORCH_CUDA_ALLOC_CONF"]+++def test_guard_device_floor_parsing(guard_mod):+ floors = guard_mod.parse_device_floors(["card1=4.5,nvidia:0=2"], global_gib = 1.0)+ assert floors["card1"] == 4.5 and floors["nvidia:0"] == 2.0+ assert guard_mod.floor_for("card2", floors) == 1.0+ assert guard_mod.floor_for("nvidia:1", floors) == 1.0+ floors["amd"] = 3.0+ assert guard_mod.floor_for("card9", floors) == 3.0+++def test_unified_detection_does_not_flag_a_large_dedicated_gpu(mg, monkeypatch):+ monkeypatch.setattr(mg, "device_total_bytes", lambda _i: 80 * GIB)+ monkeypatch.setattr(mg, "host_total_bytes", lambda: 128 * GIB)+ monkeypatch.setattr(mg, "_torch", lambda: SimpleNamespace(cuda = SimpleNamespace(+ get_device_properties = lambda _i: (_ for _ in ()).throw(RuntimeError("no gpu")))))+ monkeypatch.setattr(mg, "glob", SimpleNamespace(glob = lambda _p: []), raising = False)+ assert mg.is_unified_device(0, "gfx1201", 80 * GIB) is False+ assert mg.is_unified_device(0, "gfx1151", 80 * GIB) is True+++def test_effective_floor_ignores_global_floor_on_multiple_devices(guard_mod):+ floors = guard_mod.parse_device_floors([], global_gib = 4.0)+ assert guard_mod.effective_floor("card0", floors, multiple = False) == 4.0+ assert guard_mod.effective_floor("card0", floors, multiple = True) == 0.0+ floors["card1"] = 2.5+ assert guard_mod.effective_floor("card1", floors, multiple = True) == 2.5diff --git a/tests/test_split_plan_cpu.py b/tests/test_split_plan_cpu.pyindex d48e233..9ccdb17 100644--- a/tests/test_split_plan_cpu.py+++ b/tests/test_split_plan_cpu.py@@ -140,6 +140,17 @@ def _infos(dm, *pairs):return out[email protected](autouse = True)+def _disable_default_oom_guard(split_modules, monkeypatch):+ """The CPU placement tests are not guard tests: keep the pre-flight check off.++ The guard integration test passes an explicit DeviceBudget, so it is unaffected.+ """+ dm = split_modules[0]+ monkeypatch.setattr(dm.DeviceBudget, "from_env",+ classmethod(lambda cls, default_mode = "auto": cls(mode = "off")))++@pytest.fixturedef clean_split_env(monkeypatch):for key in ("KYOJIN_PART0_DEVICE", "KYOJIN_PART1_DEVICE", "KYOJIN_PART0_LAYERS", "KYOJIN_ENDCAPS"):@@ -723,3 +734,61 @@ def test_split_settings_off_is_a_noop(split_modules, monkeypatch):assert os.environ["EXL3_PF_HC_FUSE"] == "0"assert os.environ["EXL3_PF_GR_FUSE"] == "0"assert os.environ["EXL3_GR_PF_FUSE"] == "0"+++def _fake_guard_probe(dm, monkeypatch, *, part0_total=16 * 1024 ** 3,+ part1_total=118 * 1024 ** 3, host_available=120 * 1024 ** 3):+ monkeypatch.setattr(dm.torch.cuda, "is_available", lambda: True)+ monkeypatch.setattr(dm, "device_total_bytes",+ lambda i: part0_total if i == 1 else part1_total)+ monkeypatch.setattr(dm, "device_free_bytes",+ lambda i: part0_total if i == 1 else part1_total)+ monkeypatch.setattr(dm, "is_unified_device",+ lambda i, arch=None, total=None: i == 0)+ monkeypatch.setattr(dm, "host_available_bytes", lambda: host_available)+++def test_split_plan_guard_passes_or_refuses_before_allocation(split_modules, monkeypatch):+ dm, _bridge, _split = split_modules+ mg = __import__("exllamav3.memory_guard", fromlist = ["OOMGuardError"])+ gib = dm.GIB++ small = FakeModel([FakeModule(f"layer.{i}", layer_idx = i) for i in range(4)])+ small_cfg = FakeConfig({f"layer.{i}": gib // 2 for i in range(4)})+ _fake_guard_probe(dm, monkeypatch)+ plan = dm.SplitPlan(_devices(dm), endcaps = True, part0_layers = 2,+ guard_budget = dm.DeviceBudget(mode = "auto"),+ logger = lambda *_a: None)+ plan.add("text", small, config = small_cfg)+ plan.build()+ assert plan.guard_report is not None and plan.guard_report.ok++ huge = FakeModel([FakeModule(f"layer.{i}", layer_idx = i) for i in range(4)])+ huge_cfg = FakeConfig({f"layer.{i}": 40 * gib for i in range(4)})+ plan = dm.SplitPlan(_devices(dm), endcaps = True, part0_layers = 2,+ guard_budget = dm.DeviceBudget(mode = "auto"),+ logger = lambda *_a: None)+ plan.add("text", huge, config = huge_cfg)+ with pytest.raises(mg.OOMGuardError, match = "pre-flight OOM guard"):+ plan.build()++ # warn downgrades the same refusal; off skips the check entirely.+ warn = dm.SplitPlan(_devices(dm), endcaps = True, part0_layers = 2,+ guard_budget = dm.DeviceBudget(mode = "warn"),+ logger = lambda *_a: None)+ warn.add("text", huge, config = huge_cfg)+ warn.build()+ assert warn.guard_report is not None and not warn.guard_report.ok++ off = dm.SplitPlan(_devices(dm), endcaps = True, part0_layers = 2,+ guard_budget = dm.DeviceBudget(mode = "off"),+ logger = lambda *_a: None)+ off.add("text", huge, config = huge_cfg)+ off.build()+ assert off.guard_report is None+++def test_guard_mode_is_normalized_from_env_style_values(split_modules):+ _dm, _bridge, split = split_modules+ assert split.SplitSettings(part0_layers = 1, oom_guard = "OFF").guard_budget().mode == "off"+ assert split.SplitSettings(part0_layers = 1, oom_guard = "Warn").guard_budget().mode == "warn"diff --git a/tools/glm/serve.py b/tools/glm/serve.pyindex f5f7b3a..3b159cd 100644--- a/tools/glm/serve.py+++ b/tools/glm/serve.py@@ -27,8 +27,8 @@ sys.path.append(str(Path(__file__).resolve().parent.parent))import startup_health # noqa: E402 (GET /health with load progress while the model loads)# Shared split helper: pure stdlib at import, it loads exllamav3 lazily after SPEED_ENV.from kyojin_serve_split import ( # noqa: E402- SplitController, SplitSettings, add_split_arguments, apply_split_env, parse_part0_layers,- settings_from_namespace,+ SplitController, SplitSettings, add_split_arguments, apply_allocator_env, apply_split_env,+ parse_part0_layers, settings_from_namespace,)from loopguard import AnswerTap, loop_guard_default # noqa: E402 (answer-phase loop guard shared with the Qwen server)import serve_compat # noqa: E402 (vLLM-style token-id prompts, cache_salt, /tokenize, usage details)@@ -843,6 +843,10 @@ class ResidentEngine:self.split.load("text", self.model, progressbar=False,callback=startup_health.load_callback(), max_chunk_size=4096)else:+ from exllamav3.device_map import check_single_device_guard+ check_single_device_guard(self.model, self.config, self.cache, "cuda:0",+ budget=split_settings.guard_budget(),+ logger=lambda m: print(f"serve: {m}", flush=True))self.model.load(device="cuda:0", progressbar=False, callback=startup_health.load_callback())if num_draft > 0:self.draft_model = draft_model@@ -2299,6 +2303,8 @@ def main() -> None:help="thinking effort when a request omits it (default: medium)")args = parser.parse_args()split_settings = settings_from_namespace(args)+ apply_allocator_env(split_settings, model_dir=args.model, ctx=args.max_ctx,+ logger=lambda m: print(f"serve: {m}", flush=True))if split_settings.enabled:apply_split_env(split_settings, logger=lambda m: print(f"serve: {m}", flush=True))if args.kv_mode == "fp16":diff --git a/tools/glm/serve_lane.sh b/tools/glm/serve_lane.shindex b84b0d6..f6488c3 100755--- a/tools/glm/serve_lane.sh+++ b/tools/glm/serve_lane.sh@@ -5,4 +5,46 @@ LANE_ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)source "$LANE_ROOT/tools/strix_halo/env.sh"export EXL3_ROOT="$LANE_ROOT" EXL3_REPO="$LANE_ROOT" PYTHONPATH="$LANE_ROOT" TMPDIR="$LANE_ROOT/scratch/glm-serve" TQDM_DISABLE=1mkdir -p "$TMPDIR"++# External supervisor (exllamav3/guard.py): the reliable backstop for a unified pool.+# auto = a unified/GTT device is visible, or the model is large enough to threaten it.+MEMGUARD="${MEMGUARD:-auto}"+MEMGUARD_FLOOR="${MEMGUARD_FLOOR:-6}"+MEMGUARD_DEVICE_FLOOR="${MEMGUARD_DEVICE_FLOOR:-0}"+MODEL=""+args=("$@")+for ((i = 0; i < ${#args[@]}; i++)); do+ case "${args[$i]}" in+ --model) MODEL="${args[$((i + 1))]:-}" ;;+ --model=*) MODEL="${args[$i]#--model=}" ;;+ esac+done+use_mg=0+case "$MEMGUARD" in+ 1) use_mg=1 ;;+ auto)+ if compgen -G "/sys/class/drm/card*/device/mem_info_gtt_total" > /dev/null; then+ use_mg=1+ elif [ -n "$MODEL" ] && [ -d "$MODEL" ]; then+ model_bytes=$(du -sb --apparent-size "$MODEL"/*.safetensors 2> /dev/null | awk '{s+=$1} END {print s+0}' || true)+ if [ "${model_bytes:-0}" -ge $((48 * 1024 * 1024 * 1024)) ]; then use_mg=1; fi+ fi+ ;;+ 0) ;;+esac+MG=()+if [ "$use_mg" = "1" ] && [ -f "$LANE_ROOT/exllamav3/guard.py" ]; then+ MG=(python "$LANE_ROOT/exllamav3/guard.py" --floor-gib "$MEMGUARD_FLOOR"+ --label glm --fadvise-every 5)+ [ -n "$MODEL" ] && [ -d "$MODEL" ] && MG+=(--fadvise-dir "$MODEL")+ [ "$MEMGUARD_DEVICE_FLOOR" != "0" ] && MG+=(--device-floor-gib "$MEMGUARD_DEVICE_FLOOR")+ MG+=(--)+ echo "serve_lane: MEMGUARD=on host floor ${MEMGUARD_FLOOR} GiB device floor ${MEMGUARD_DEVICE_FLOOR} GiB" >&2+elif [ "$MEMGUARD" = "1" ]; then+ echo "serve_lane: MEMGUARD=1 requested but exllamav3/guard.py is missing" >&2+ exit 1+fi+if [ ${#MG[@]} -gt 0 ]; then+ exec "${MG[@]}" "${EXL3_VENV:-$LANE_ROOT/.venv}/bin/python" "$LANE_ROOT/tools/glm/serve.py" "$@"+fiexec "${EXL3_VENV:-$LANE_ROOT/.venv}/bin/python" "$LANE_ROOT/tools/glm/serve.py" "$@"diff --git a/tools/mimo/serve_lane.sh b/tools/mimo/serve_lane.shindex aeee3fd..c87697d 100755--- a/tools/mimo/serve_lane.sh+++ b/tools/mimo/serve_lane.sh@@ -5,4 +5,37 @@ LANE_ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)source "$LANE_ROOT/tools/strix_halo/env.sh"export EXL3_ROOT="$LANE_ROOT" EXL3_REPO="$LANE_ROOT" PYTHONPATH="$LANE_ROOT" TMPDIR="$LANE_ROOT/scratch/msrv-lane" TQDM_DISABLE=1mkdir -p "$TMPDIR"++# External supervisor: unified-memory boxes do not reliably OOM-kill.+MEMGUARD="${MEMGUARD:-auto}"+MEMGUARD_FLOOR="${MEMGUARD_FLOOR:-6}"+MEMGUARD_DEVICE_FLOOR="${MEMGUARD_DEVICE_FLOOR:-0}"+MODEL=""+mg_args=("$@")+for ((i = 0; i < ${#mg_args[@]}; i++)); do+ case "${mg_args[$i]}" in+ --model) MODEL="${mg_args[$((i + 1))]:-}" ;;+ --model=*) MODEL="${mg_args[$i]#--model=}" ;;+ esac+done+use_mg=0+case "$MEMGUARD" in+ 1) use_mg=1 ;;+ auto) compgen -G "/sys/class/drm/card*/device/mem_info_gtt_total" > /dev/null && use_mg=1 ;;+esac+MG=()+if [ "$use_mg" = "1" ] && [ -f "$LANE_ROOT/exllamav3/guard.py" ]; then+ MG=(python "$LANE_ROOT/exllamav3/guard.py" --floor-gib "$MEMGUARD_FLOOR"+ --label mimo --fadvise-every 5)+ [ -n "$MODEL" ] && [ -d "$MODEL" ] && MG+=(--fadvise-dir "$MODEL")+ [ "$MEMGUARD_DEVICE_FLOOR" != "0" ] && MG+=(--device-floor-gib "$MEMGUARD_DEVICE_FLOOR")+ MG+=(--)+ echo "serve_lane: MEMGUARD=on host floor ${MEMGUARD_FLOOR} GiB device floor ${MEMGUARD_DEVICE_FLOOR} GiB" >&2+elif [ "$MEMGUARD" = "1" ]; then+ echo "serve_lane: MEMGUARD=1 requested but exllamav3/guard.py is missing" >&2+ exit 1+fi+if [ ${#MG[@]} -gt 0 ]; then+ exec "${MG[@]}" "${EXL3_VENV:-$LANE_ROOT/.venv}/bin/python" "$LANE_ROOT/tools/mimo/serve.py" "$@"+fiexec "${EXL3_VENV:-$LANE_ROOT/.venv}/bin/python" "$LANE_ROOT/tools/mimo/serve.py" "$@"diff --git a/tools/strix_halo/split_eval.py b/tools/strix_halo/split_eval.pyindex aaf7772..f193a45 100644--- a/tools/strix_halo/split_eval.py+++ b/tools/strix_halo/split_eval.py@@ -30,12 +30,14 @@ correctness; per-segment capture is Phase 6).from __future__ import annotationsimport argparse+import importlib.utilimport jsonimport osimport reimport sysimport time-+from pathlib import Path+from types import SimpleNamespace# Kept in sync with exllamav3/serve_split.py:GRAPH_ENV_OFF; the consistency test# asserts the key sets match so a new graph flag cannot silently bypass this gate.@@ -96,6 +98,16 @@ def parse_args() -> argparse.Namespace:p.add_argument("--endcaps", choices=("on", "off"), default="on")p.add_argument("--part0-reserve-gb", type=float, default=1.2)p.add_argument("--part1-reserve-gb", type=float, default=0.0)+ p.add_argument("--expandable-segments", choices=("auto", "on", "off"), default=None,+ help="allocator mode, applied before exllamav3 import "+ "(default: KYOJIN_EXPANDABLE_SEGMENTS, else auto)")+ p.add_argument("--oom-guard", choices=("auto", "warn", "off"), default=None,+ help="pre-flight per-device guard (default: KYOJIN_OOM_GUARD, else auto)")+ p.add_argument("--oom-guard-reserve-gib", default=None,+ help="per-device reserve, e.g. gfx1151=4.5,gfx1201=0.8")+ p.add_argument("--oom-guard-workspace-gib", default=None)+ p.add_argument("--oom-guard-safety-gib", default=None)+ p.add_argument("--oom-guard-device-floor", default=None)p.add_argument("-c", "--max-ctx", type=int, default=131072)p.add_argument("--num-draft", type=int, default=2)p.add_argument("--no-vision", action="store_true")@@ -146,8 +158,31 @@ def parse_args() -> argparse.Namespace:return args+def _allocator_env_module():+ """Load the pure-stdlib shared allocator helper without importing exllamav3."""+ path = Path(__file__).resolve().parents[2] / "exllamav3" / "serve_split.py"+ spec = importlib.util.spec_from_file_location("_kyojin_allocator_env", path)+ assert spec is not None and spec.loader is not None+ module = importlib.util.module_from_spec(spec)+ sys.modules[spec.name] = module+ spec.loader.exec_module(module)+ return module+++def _apply_allocator_env(args: argparse.Namespace) -> str:+ settings = SimpleNamespace(+ expandable_segments=(args.expandable_segments+ or os.environ.get("KYOJIN_EXPANDABLE_SEGMENTS") or "auto"),+ part0_reserve_gb=getattr(args, "part0_reserve_gb", 1.2),+ )+ return _allocator_env_module().apply_allocator_env(+ settings, model_dir=args.model, ctx=args.max_ctx,+ logger=lambda m: print(f"[harness] {m}", flush=True))++def configure_env(args: argparse.Namespace) -> None:"""Set everything exllamav3 reads at import time, before the first import."""+ _apply_allocator_env(args)if args.no_graphs or not args.baseline:for k in GRAPH_ENV_OFF:os.environ[k] = "0"@@ -176,6 +211,7 @@ def ids_of(text: str, tokenizer) -> torch.Tensor:def run_job(gen, job_cls, ids, n: int):import torch+from exllamav3.generator.sampler import GreedySamplerjob = job_cls(input_ids = ids, max_new_tokens = n, sampler = GreedySampler(),stop_conditions = gen.model.config.eos_token_id_list)@@ -373,8 +409,18 @@ def main() -> None:configure_env(args)import torch- from exllamav3 import Cache, CacheLayer_quant, Config, Generator, Job, Model, Tokenizer++ from exllamav3 import (+ Cache,+ CacheLayer_quant,+ Config,+ Generator,+ Job,+ Model,+ Tokenizer,+ )from exllamav3.generator import generator as GM+ from exllamav3.memory_guard import DeviceBudgettorch.set_grad_enabled(False)@@ -383,7 +429,8 @@ def main() -> None:model = Model.from_config(config)qkw = dict(layer_type = CacheLayer_quant, k_bits = 6, v_bits = 6)- from exllamav3.cache.tq import CacheLayer_tq, supported as tq_supported+ from exllamav3.cache.tq import CacheLayer_tq+ from exllamav3.cache.tq import supported as tq_supportedif tq_supported(512, 6):qkw = dict(layer_type = CacheLayer_tq, k_bits = 6, v_bits = 6)max_history = max(args.num_draft, 1)@@ -395,10 +442,21 @@ def main() -> None:if not args.baseline:from exllamav3.device_map import SplitPlan, resolve_devicesdevices = resolve_devices(args.part0_device, args.part1_device)+ budget = DeviceBudget.from_env(default_mode = "auto")+ if args.oom_guard:+ budget.mode = args.oom_guard+ if args.oom_guard_reserve_gib is not None:+ budget.reserve = args.oom_guard_reserve_gib+ if args.oom_guard_workspace_gib is not None:+ budget.workspace = args.oom_guard_workspace_gib+ if args.oom_guard_safety_gib is not None:+ budget.safety = args.oom_guard_safety_gib+ if args.oom_guard_device_floor is not None:+ budget.device_floor = args.oom_guard_device_floorplan = SplitPlan(devices, endcaps = args.endcaps == "on", part0_layers = args.part0_layers,part0_reserve_gb = 0.0 if args.no_budget else args.part0_reserve_gb,- part1_reserve_gb = args.part1_reserve_gb)+ part1_reserve_gb = args.part1_reserve_gb, guard_budget = budget)plan.add("text", model, config = config, cache = cache, load_order = 0)plan.build()text_map = plan.map("text")diff --git a/tools/strix_halo/split_load.py b/tools/strix_halo/split_load.pyindex 0bff538..c9b6e69 100644--- a/tools/strix_halo/split_load.py+++ b/tools/strix_halo/split_load.py@@ -12,9 +12,13 @@ Usage (from the repo root, after `source tools/strix_halo/env.sh`):from __future__ import annotationsimport argparse+import importlib.utilimport osimport resource+import sysimport time+from pathlib import Path+from types import SimpleNamespacedef mem_available_gib() -> float:@@ -27,6 +31,23 @@ def mem_available_gib() -> float:return 0.0+def _apply_allocator_env(args: argparse.Namespace) -> str:+ """Load the shared allocator helper without importing exllamav3 first."""+ path = Path(__file__).resolve().parents[2] / "exllamav3" / "serve_split.py"+ spec = importlib.util.spec_from_file_location("_kyojin_allocator_env", path)+ assert spec is not None and spec.loader is not None+ module = importlib.util.module_from_spec(spec)+ sys.modules[spec.name] = module+ spec.loader.exec_module(module)+ settings = SimpleNamespace(+ expandable_segments=(args.expandable_segments+ or os.environ.get("KYOJIN_EXPANDABLE_SEGMENTS") or "auto"),+ part0_reserve_gb=args.part0_reserve_gb,+ )+ return module.apply_allocator_env(settings, model_dir=args.model, ctx=args.cache_size,+ logger=lambda m: print(f"[split_load] {m}", flush=True))++def main() -> None:p = argparse.ArgumentParser()p.add_argument("-m", "--model", required=True)@@ -39,11 +60,21 @@ def main() -> None:p.add_argument("--num-draft", type=int, default=2)p.add_argument("--no-vision", action="store_true")p.add_argument("--baseline", action="store_true", help="load everything on cuda:0, for the host-RAM comparison")+ p.add_argument("--expandable-segments", choices=("auto", "on", "off"), default=None)+ p.add_argument("--oom-guard", choices=("auto", "warn", "off"), default=None)+ p.add_argument("--oom-guard-reserve-gib", default=None)+ p.add_argument("--oom-guard-workspace-gib", default=None)+ p.add_argument("--oom-guard-safety-gib", default=None)+ p.add_argument("--oom-guard-device-floor", default=None)args = p.parse_args()+ _apply_allocator_env(args)+import torch+from exllamav3 import Cache, CacheLayer_quant, Config, Modelfrom exllamav3.device_map import SplitPlan, resolve_devices+ from exllamav3.memory_guard import DeviceBudgettorch.set_grad_enabled(False)endcaps = args.endcaps == "on"@@ -54,7 +85,8 @@ def main() -> None:# Same cache format as tools/glm/serve.py defaults: TurboQuant 6-bit latent.qkw = dict(layer_type=CacheLayer_quant, k_bits=6, v_bits=6)- from exllamav3.cache.tq import CacheLayer_tq, supported as tq_supported+ from exllamav3.cache.tq import CacheLayer_tq+ from exllamav3.cache.tq import supported as tq_supportedif tq_supported(512, 6):qkw = dict(layer_type=CacheLayer_tq, k_bits=6, v_bits=6)max_history = max(args.num_draft, 1)@@ -83,8 +115,19 @@ def main() -> None:returndevices = resolve_devices(args.part0_device, args.part1_device)+ budget = DeviceBudget.from_env(default_mode="auto")+ if args.oom_guard:+ budget.mode = args.oom_guard+ if args.oom_guard_reserve_gib is not None:+ budget.reserve = args.oom_guard_reserve_gib+ if args.oom_guard_workspace_gib is not None:+ budget.workspace = args.oom_guard_workspace_gib+ if args.oom_guard_safety_gib is not None:+ budget.safety = args.oom_guard_safety_gib+ if args.oom_guard_device_floor is not None:+ budget.device_floor = args.oom_guard_device_floorplan = SplitPlan(devices, endcaps=endcaps, part0_layers=args.part0_layers,- part0_reserve_gb=args.part0_reserve_gb)+ part0_reserve_gb=args.part0_reserve_gb, guard_budget=budget)plan.add("text", model, config=config, cache=cache, load_order=0)plan.build()text_map = plan.map("text")diff --git a/util/memguard.py b/util/memguard.pyindex e2b1f04..6cc6f67 100755--- a/util/memguard.py+++ b/util/memguard.py@@ -1,310 +1,15 @@#!/usr/bin/env python3-"""-memguard.py -- a tiny supervisor that SIGKILLs its child before the box dies.--Why this exists-----------------On the DGX Spark (GB10) the GPU and the host share ONE 121.6 GiB pool. There is no-separate VRAM. When that pool is exhausted the kernel does not OOM-kill anything ---it starves, the NVIDIA driver logs NV_ERR_NO_MEMORY, and recovery is a physical-power cycle. On 2026-09-22 03:1x exactly that happened while loading the 87 GiB-EXL3 quant: the shards' pages stayed in page cache while the same bytes were also-pinned on the device.--`torch.cuda.mem_get_info()` reports MemFree, not MemAvailable, so nothing inside-the process notices. This supervisor watches /proc/meminfo from the OUTSIDE, in a-process that allocates nothing, and kills the child while there is still room to-recover.--Usage------- python util/memguard.py [options] -- <command> [args...]--Options--------- --floor-gib F kill when MemAvailable < F GiB (default 8)- --interval S poll period in seconds (default 0.5)- --warn-gib F log a warning below this (default floor + 8)- --log PATH also append the sampler trace here- --grace S seconds to wait after SIGKILL before giving up (default 30)- --cgroup-limit (informational) also print the child's peak RSS+"""Compatibility wrapper for the package guard entry point.-Exit code----------- the child's exit code, or 137 if memguard killed it (and a loud explanation on- stderr / in --log).--Self-test----------- python util/memguard.py --selftest-prints what it would do, and-- python util/memguard.py --floor-gib 999 -- sleep 60-must kill immediately (999 GiB floor can never be satisfied) -- that is the-"prove it kills" check.+The supervisor lives in ``exllamav3/guard.py``. Exec the file instead of importing+it: importing the package would initialize torch and apply allocator settings in a+process that must stay tiny and allocation-free."""-from __future__ import annotations--import argparseimport os-import signal-import subprocessimport sys-import time--GIB = 1024.0 * 1024.0 * 1024.0---def meminfo() -> dict[str, int]:- """Return /proc/meminfo in bytes. Cheap: one read of a ~1.5 kB pseudo-file."""- out = {}- with open("/proc/meminfo", "r") as f:- for line in f:- k, _, rest = line.partition(":")- rest = rest.strip()- if rest.endswith(" kB"):- out[k] = int(rest[:-3]) * 1024- else:- try:- out[k] = int(rest)- except ValueError:- pass- return out---def fmt_gib(x: int | float) -> str:- return f"{x / GIB:6.1f}"---def proc_rss(pid: int) -> int:- try:- with open(f"/proc/{pid}/status", "r") as f:- for line in f:- if line.startswith("VmRSS:"):- return int(line.split()[1]) * 1024- except (OSError, ValueError):- pass- return 0---class Logger:- def __init__(self, path: str | None):- self.fh = open(path, "a", buffering=1) if path else None-- def __call__(self, msg: str) -> None:- line = f"[memguard {time.strftime('%H:%M:%S')}] {msg}"- print(line, file=sys.stderr, flush=True)- if self.fh:- self.fh.write(line + "\n")---def kill_tree(pid: int, sig: int) -> None:- """Signal the child's whole process group (it is a session leader, see start_new_session)."""- try:- os.killpg(os.getpgid(pid), sig)- except (ProcessLookupError, PermissionError):- try:- os.kill(pid, sig)- except ProcessLookupError:- pass---def main() -> int:- ap = argparse.ArgumentParser(add_help=True)- ap.add_argument("--floor-gib", type=float, default=8.0)- ap.add_argument("--warn-gib", type=float, default=None)- ap.add_argument("--interval", type=float, default=0.5)- ap.add_argument("--log", type=str, default=None)- ap.add_argument("--grace", type=float, default=30.0)- ap.add_argument("--label", type=str, default=None)- ap.add_argument(- "--fadvise-dir",- action="append",- default=[],- help="model dir whose *.safetensors should be dropped from page cache periodically "- "while the child runs. exllamav3 reads shards with buffered pread, so on unified "- "memory the shards end up resident twice -- once on the device, once in page cache "- "-- and the page cache half grows DURING the load, i.e. before any in-process hook "- "could run. Doing it from the supervisor covers every loader, TabbyAPI included.",- )- ap.add_argument("--fadvise-every", type=float, default=5.0)- ap.add_argument("--selftest", action="store_true")- ap.add_argument("cmd", nargs=argparse.REMAINDER)- args = ap.parse_args()-- log = Logger(args.log)-- if args.selftest:- mi = meminfo()- log(- f"selftest: MemAvailable {fmt_gib(mi['MemAvailable'])} GiB "- f"MemFree {fmt_gib(mi['MemFree'])} GiB Cached {fmt_gib(mi['Cached'])} GiB "- f"floor {args.floor_gib} GiB -> would "- f"{'KILL' if mi['MemAvailable'] < args.floor_gib * GIB else 'run'}"- )- return 0-- cmd = args.cmd- if cmd and cmd[0] == "--":- cmd = cmd[1:]- if not cmd:- ap.error("no command given (use: memguard.py [opts] -- cmd args...)")-- floor = args.floor_gib * GIB- warn = (args.warn_gib if args.warn_gib is not None else args.floor_gib + 8.0) * GIB-- mi = meminfo()- label = args.label or os.path.basename(cmd[-1] if len(cmd) > 1 else cmd[0])- log(- f"start [{label}] floor={args.floor_gib:.1f} GiB every {args.interval}s; "- f"MemAvailable {fmt_gib(mi['MemAvailable'])} GiB, Cached {fmt_gib(mi['Cached'])} GiB"- )- log("cmd: " + " ".join(cmd))-- if mi["MemAvailable"] < floor:- log(- f"REFUSING TO START: MemAvailable {fmt_gib(mi['MemAvailable'])} GiB is already "- f"below the {args.floor_gib:.1f} GiB floor"- )- return 3-- t0 = time.time()- # start_new_session so the child gets its own process group; a model load spawns- # worker threads/processes and we want to kill all of them at once.- child = subprocess.Popen(cmd, start_new_session=True)-- lowest = mi["MemAvailable"]- peak_rss = 0- last_warn = 0.0- last_beat = 0.0- last_fadv = 0.0- fadv_total = 0- killed = False-- fadvise_files: list[str] = []- for d in args.fadvise_dir:- if os.path.isdir(d):- fadvise_files += sorted(- os.path.join(d, f) for f in os.listdir(d) if f.endswith(".safetensors")- )- elif os.path.isfile(d):- fadvise_files.append(d)- if fadvise_files:- log(- f"page-cache release armed for {len(fadvise_files)} shard(s) every "- f"{args.fadvise_every}s"- )-- def fadvise_now() -> int:- n = 0- for p in fadvise_files:- try:- fd = os.open(p, os.O_RDONLY)- except OSError:- continue- try:- os.posix_fadvise(fd, 0, 0, os.POSIX_FADV_DONTNEED)- n += 1- except OSError:- pass- finally:- os.close(fd)- return n-- try:- while True:- rc = child.poll()- if rc is not None:- break- mi = meminfo()- avail = mi["MemAvailable"]- lowest = min(lowest, avail)- rss = proc_rss(child.pid)- peak_rss = max(peak_rss, rss)- now = time.time()-- if avail < floor:- log(- "*** MEMORY FLOOR BREACHED -- KILLING CHILD ***\n"- f" MemAvailable {fmt_gib(avail)} GiB < floor {args.floor_gib:.1f} GiB\n"- f" MemFree {fmt_gib(mi['MemFree'])} GiB Cached {fmt_gib(mi['Cached'])} GiB "- f"Dirty {fmt_gib(mi.get('Dirty', 0))} GiB\n"- f" child pid {child.pid} RSS {fmt_gib(rss)} GiB, alive {now - t0:.1f}s\n"- " This box has unified memory and does NOT OOM-kill; starving it costs a "- "physical power cycle. Killing now."- )- killed = True- kill_tree(child.pid, signal.SIGKILL)- # Drop clean page cache immediately -- it is the cheapest memory to get back- # and it is usually what is squeezing us.- try:- with open("/proc/sys/vm/drop_caches", "w") as f:- f.write("1\n")- log(" dropped clean page cache (vm.drop_caches=1)")- except OSError:- pass- break-- if fadvise_files and now - last_fadv >= args.fadvise_every:- last_fadv = now- cached_before = mi["Cached"]- fadvise_now()- fadv_total += 1- after = meminfo()- freed = cached_before - after["Cached"]- if freed > 2 * GIB:- log(- f"page-cache release: Cached {fmt_gib(cached_before)} -> "- f"{fmt_gib(after['Cached'])} GiB, MemAvailable {fmt_gib(after['MemAvailable'])} GiB"- )-- if avail < warn and now - last_warn > 10.0:- last_warn = now- log(- f"WARNING MemAvailable {fmt_gib(avail)} GiB (floor {args.floor_gib:.1f}), "- f"Cached {fmt_gib(mi['Cached'])}, child RSS {fmt_gib(rss)}"- )- elif now - last_beat > 60.0:- last_beat = now- log(- f"ok MemAvailable {fmt_gib(avail)} GiB Cached {fmt_gib(mi['Cached'])} GiB "- f"child RSS {fmt_gib(rss)} GiB t+{now - t0:.0f}s"- )-- time.sleep(args.interval)- except KeyboardInterrupt:- log("interrupted -- terminating child")- kill_tree(child.pid, signal.SIGTERM)- try:- child.wait(timeout=10)- except subprocess.TimeoutExpired:- kill_tree(child.pid, signal.SIGKILL)- return 130-- if killed:- deadline = time.time() + args.grace- while time.time() < deadline:- if child.poll() is not None:- break- time.sleep(0.2)- mi = meminfo()- log(- f"child killed. MemAvailable now {fmt_gib(mi['MemAvailable'])} GiB. "- f"lowest seen {fmt_gib(lowest)} GiB, peak child RSS {fmt_gib(peak_rss)} GiB, "- f"wall {time.time() - t0:.1f}s"- )- return 137-- rc = child.wait()- mi = meminfo()- log(- f"child exited rc={rc} after {time.time() - t0:.1f}s; "- f"lowest MemAvailable seen {fmt_gib(lowest)} GiB, peak child RSS {fmt_gib(peak_rss)} GiB; "- f"MemAvailable now {fmt_gib(mi['MemAvailable'])} GiB"- )- return rc+_TARGET = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),+ "exllamav3", "guard.py")-if __name__ == "__main__":- sys.exit(main())+os.execv(sys.executable, [sys.executable, _TARGET, *sys.argv[1:]])