Skip to content

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.

Simplify OOM guard

Resynth4441c3c5beac
diff --git a/doc/env_vars.md b/doc/env_vars.md
index b2537c4..bbf7116 100644
--- a/doc/env_vars.md
+++ b/doc/env_vars.md
@@ -710,77 +710,41 @@ 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 `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.
+setting `PYTORCH_CUDA_ALLOC_CONF=expandable_segments:False`. 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. Set it in the lane profile before `import exllamav3` for that case.
-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_OOM_GUARD` (default: `auto`)
-### `KYOJIN_EXPANDABLE_SEGMENTS_AUTO_CTX` (default: `524288`)
+Pre-flight memory guard: `auto` refuses a load whose measured weights, cache, part0 slab and
+prefill workspace do not fit before allocating anything; `off` disables the check. The guard is
+read-only and never changes allocator settings or outputs.
-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).
+There is no per-device GTT or VRAM reserve. Each device's cap is its own reported
+`min(mem_get_info().free, mem_get_info().total)`. A dedicated-VRAM allocation failure is a
+process-level error; the host floor is what protects the unified-memory box from kernel
+starvation.
-### `KYOJIN_OOM_GUARD` (default: `auto` for split, `warn` for single-device)
+### `KYOJIN_OOM_GUARD_HOST_FREE_GIB` (default: `7`)
-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.
+The host `MemAvailable` floor, used by both the pre-flight guard and `exllamav3/guard.py`.
+The preflight plans against `MemAvailable - (floor + margin)`; the supervisor SIGKILLs when
+`MemAvailable < floor`. Raise this for a hungrier OS or more background services; lower it
+only after measuring. Seven GiB is the measured boundary on this box: the 8K MTP-on N=7 run
+completed at 7.26 GiB host available, while the fatal N=6 run reached the kernel OOM zone.
-### `KYOJIN_OOM_GUARD_RESERVE_GIB` (default: `8.0` unified, `0.8` dedicated)
+### `KYOJIN_OOM_GUARD_PREFLIGHT_MARGIN_GIB` (default: `1`)
-Per-device free-memory floor kept out of the pre-flight capacity. On a unified device this is
-one subtraction from the GTT pool, not a second reserve on top of the 113.3 GiB ceiling: the
-measured 128K N=5 load completed with **8.7 GiB** GTT free, while the fatal MTP-on event ran
-at about **4.3 GiB** free. Eight GiB is the measured boundary (0.7 GiB below the known-safe
-point, 3.7 GiB above the fatal one), so MTP-on that needs more space is refused and moved to
-a larger part0 N. Accepts the split's device-selector syntax, for example
-`gfx1151=8,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.
+Planning headroom above the supervisor floor. It keeps the preflight from deliberately
+planning at the kill threshold and covers ordinary estimator error. Set it to `0` to plan
+exactly at the floor.
-### `KYOJIN_OOM_GUARD_WORKSPACE_GIB` (default: `2.0` bulk device, `1.5` other)
+### `KYOJIN_OOM_GUARD_WORKSPACE_GIB` (default: `2.0`)
-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: `7`)
-
-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. Seven GiB is measured: the completed MTP-on N=7 8K run bottomed at
-7.26 GiB host available and 7.10 GiB GTT free; the fatal N=6 run was at ~4.3 GiB GTT free.
-
-### `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 after the reserve is subtracted. The 8 GiB unified reserve is the
-measured free-memory floor; the ceiling remains a hard upper bound for larger reported pools. 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).
+Estimated transient prefill workspace added to every device footprint. This is model/context
+dependent; raise it for a model with a larger prefill scratch area. It is not a reserve: the
+device cap remains its own reported free memory.
### `EXL3_LOAD_ARENA` (default: `1`)
diff --git a/doc/split.md b/doc/split.md
index 2c3977a..5a21335 100644
--- a/doc/split.md
+++ b/doc/split.md
@@ -53,12 +53,7 @@ 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 free floor, e.g. `gfx1151=8,gfx1201=0.8` (default 8.0 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 |
+| `--oom-guard auto\|off` | `KYOJIN_OOM_GUARD` | pre-flight memory guard (`auto` refuses, `off` disables) |
`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
@@ -92,71 +87,68 @@ Text endcaps are selected by a class/key allowlist, not by per-model placement i
- Split mode runs eager. Whole-forward and per-block graphs are disabled; per-segment
capture is not implemented yet.
-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. A 2026-11-16 8K MTP-on N=6 probe still caused a
-kernel OOM at ~113.7 GiB GPU-active / ~4.3 GiB GTT free with the old 4.5 GiB reserve and
-6 GiB host floor. The measured fix is: pre-flight reserve 8 GiB (MTP-on N=6 is refused and
-N=7 is recommended), supervisor GTT floor 7 GiB (N=7 8K completed at 7.10 GiB free) and
-host floor 7 GiB (completed at 7.2 GiB available). With `--oom-guard warn`, the old N=6
-case is SIGKILLed by the supervisor at 6.8 GiB GTT free / 8.1 GiB host available instead
-of invoking the kernel OOM killer. Longer MTP-on contexts still need the guard's
-recommendation rather than a hand-picked N, and the supervisor must stay armed.
+The measured 118 GiB Strix Halo iGPU has a practical usable point of about **113 GiB**
+(the gap to the 118 GiB aperture is driver/allocator overhead). Recorded failure points on
+the measured GLM pack: 128K split runs complete (peak ~109.3 GiB on the iGPU); a 512K cache
+needs `expandable_segments:False` to load; 640K is refused by the pre-flight guard; 768K
+hard-locked the box. A 2026-11-16 8K MTP-on N=6 probe caused a kernel OOM at ~4.3 GiB GTT
+free under the old configuration. The host-only supervisor now catches that case: an N=6
+run allowed past preflight was SIGKILLed at 7.0 GiB host available / 5.3 GiB GTT free,
+with no kernel OOM.
### 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 - 7 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.
+The guard estimates each device's footprint from actual bytes: weights, KV/recurrent cache,
+the part0 load slab and a prefill workspace. The device cap is the device itself:
-Defaults are measured boundaries, not architecture rules: `8.0` GiB free on a unified/GTT
-device (128K N=5 completed with 8.7 GiB free; the fatal MTP-on run had ~4.3 GiB free),
-`0.8` GiB on dedicated VRAM, `2.0`/`1.5` GiB prefill workspace on the bulk/other device,
-and a `7` GiB host floor as the last resort. All accept per-device selector lists, e.g.
-`--oom-guard-reserve-gib gfx1151=8,gfx1201=0.8`.
+```text
+device_cap = min(mem_get_info().free, mem_get_info().total)
+host_cap = MemAvailable - (host_floor + preflight_margin)
+```
+
+There is **no GTT or VRAM reserve**. A dedicated-VRAM allocation failure is a process-level
+error; the host floor is what prevents the unified-memory box from starving. The only
+tunables are `KYOJIN_OOM_GUARD_HOST_FREE_GIB` (default 7), the planning margin (default 1)
+and the prefill workspace (default 2.0 GiB). The host floor is shared with the supervisor;
+the margin keeps the planner above the supervisor's kill threshold.
+
+`--oom-guard auto` 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. `off` disables it. The
+check is read-only.
+
+Measured budget on the GLM pack at idle: 128K N=5 needs ~111 GiB (passes); 640K N=5 needs
+~115.2 GiB and is refused by the host planning cap (~114.6 GiB); MTP-on N=6 needs ~110.4 GiB
+and is allowed to start, with the supervisor as the runtime backstop; MTP-on N=7 needs
+~107.7 GiB and completed at 7.2 GiB host / 7.1 GiB GTT free.
### 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.
+The 512K case needs expandable segments off. Use the existing
+`EXL3_EXPANDABLE_SEGMENTS=0` (or `PYTORCH_CUDA_ALLOC_CONF=expandable_segments:False`) in that
+lane profile before the library import. It recovers about **0.5 GiB** of fragmentation, not
+capacity. There is no automatic allocator heuristic.
+
+512K is also at the preflight planning boundary (the measured 512K load used 113.28 GiB).
+If the host cap refuses it on a particular boot, set
+`KYOJIN_OOM_GUARD_PREFLIGHT_MARGIN_GIB=0` or `KYOJIN_OOM_GUARD=off` for that lane; the external
+supervisor floor is unchanged and still protects the box. Do not disable the supervisor.
### 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:
+Use `exllamav3/guard.py` (the compatibility path `util/memguard.py` execs it). It watches host
+`MemAvailable` and page cache; it has no device floors and no torch import:
```sh
-python exllamav3/guard.py --floor-gib 6 --device-floor-gib 4 \
- --fadvise-dir /path/to/model -- python tools/glm/serve.py ...
+python exllamav3/guard.py --fadvise-dir /path/to/model -- python tools/glm/serve.py ...
```
-Per-device supervisor floors use `--device-floor card0=8,nvidia:0=2` (or
-`--device-floor-gib` for every watched device). On an APU the supervisor automatically keeps
-a **7 GiB GTT free floor** when no explicit device floor is given. This is the measured
-boundary: MTP-on N=7 8K completed at 7.10 GiB GTT free, 128K N=5 at 8.7 GiB, and the fatal
-MTP-on N=6 event was ~4.3 GiB free. 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`.
+The host floor defaults to 7 GiB (or `KYOJIN_OOM_GUARD_HOST_FREE_GIB`) and is the same value
+the preflight plans around. The supervisor logs a sample to `--log`; the serve lanes pass
+`$TMPDIR/memguard.log` so a future event leaves evidence. The serve scripts use a
+`MEMGUARD=auto|1|0` wrapper: `auto` enables it for a unified/GTT device or a large model.
+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 support
diff --git a/doc/strix-halo.md b/doc/strix-halo.md
index 08e990a..3a14ae7 100644
--- a/doc/strix-halo.md
+++ b/doc/strix-halo.md
@@ -233,27 +233,27 @@ 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 unified free floor is 7.0 GiB (the MTP-on N=7 8K load completed at 7.1 GiB GTT free and
- the 128K N=5 load at 8.7 GiB; the fatal MTP-on N=6 event had ~4.3 GiB). The workspace default is 2.0 GiB on the bulk device and
- 1.5 GiB on the other. The unified free floor is 7.0 GiB (the MTP-on N=7 8K load completed at 7.1 GiB GTT free and
- the 128K N=5 load at 8.7 GiB; the fatal MTP-on N=6 event had ~4.3 GiB). The workspace default is 2.0 GiB on the bulk device and
- 1.5 GiB on the other.
-- `--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. An 8K MTP-on N=6 probe
-OOM-killed the kernel at ~4.3 GiB GTT free; the guard now refuses it and N=7 completes at
-7.10 GiB free. Do not hand-pick an N for MTP-on: use the guard's largest-N/context output
-and keep the supervisor armed (auto GTT floor 7 GiB).
+The 128 GB pool reports about 118 GiB to torch, but the practical usable point is about
+**113 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` (default) estimates weights, cache, part0 slab and workspace, caps each
+ device at its own `min(free, total)`, and caps the host at `MemAvailable - 7 GiB` (plus a
+ 1 GiB planning margin). It refuses before allocating anything.
+- There is no GTT or VRAM reserve. A dedicated-VRAM OOM is a process-level error; the host
+ floor is what prevents kernel starvation on the unified pool.
+- `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 --fadvise-dir <model> -- ...` SIGKILLs the child when host
+ `MemAvailable` falls below 7 GiB (`KYOJIN_OOM_GUARD_HOST_FREE_GIB`) and releases page
+ cache. The serve scripts wrap this with `MEMGUARD=auto|1|0` and log to
+ `$TMPDIR/memguard.log`.
+
+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. An 8K MTP-on N=6 probe was killed
+by the host floor at 7.0 GiB available before the kernel OOM zone (~4.3 GiB GTT free); N=7
+completed at 7.2 GiB host / 7.1 GiB GTT free. Do not hand-pick an N for MTP-on: use the
+guard's largest-N/context output and keep the supervisor armed.
## Build
diff --git a/examples/mimo_v2_6/serve.sh b/examples/mimo_v2_6/serve.sh
index a9e7e7d..793b30e 100755
--- a/examples/mimo_v2_6/serve.sh
+++ b/examples/mimo_v2_6/serve.sh
@@ -64,8 +64,7 @@
# Set to "" to restore stock autosplit.
# 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)
+# KYOJIN_OOM_GUARD_HOST_FREE_GIB=7 SIGKILL the server below this MemAvailable, in GiB
# MIN_AVAIL_GIB=12 refuse to start below this MemAvailable, in GiB
# FOREGROUND=1 0 backgrounds it and writes $LOG
#
@@ -118,8 +117,6 @@ DYNAMIC_DRAFT="${DYNAMIC_DRAFT:-1}"
DRAFT_CACHE_MODE="${DRAFT_CACHE_MODE:-FP16}"
DRAFT_RING="${DRAFT_RING:-1}"
MEMGUARD="${MEMGUARD:-auto}"
-MEMGUARD_FLOOR="${MEMGUARD_FLOOR:-7}"
-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}"
@@ -258,11 +255,11 @@ case "$MEMGUARD" in
;;
esac
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=(python "$REPO/exllamav3/guard.py"
+ --fadvise-dir "$MODEL_DIR" --fadvise-every 5 --label tabbyapi
+ --sample-every 5 --log "${TMPDIR:-/tmp}/memguard.log")
MG+=(--)
- echo " -- MEMGUARD=on host floor ${MEMGUARD_FLOOR} GiB device floor ${MEMGUARD_DEVICE_FLOOR} GiB"
+ echo " -- MEMGUARD=on (host floor ${KYOJIN_OOM_GUARD_HOST_FREE_GIB:-7} GiB)"
else
MG=()
[ "$use_mg" = "1" ] || echo " !! memguard disabled (MEMGUARD=$MEMGUARD)"
diff --git a/exllamav3/device_map.py b/exllamav3/device_map.py
index 6f2ea07..327a08b 100644
--- a/exllamav3/device_map.py
+++ b/exllamav3/device_map.py
@@ -44,13 +44,12 @@ from dataclasses import dataclass, field
import torch
from .memory_guard import (
- DeviceBudget,
+ GuardPolicy,
OOMGuard,
check_single_device,
device_free_bytes,
device_total_bytes,
host_available_bytes,
- is_unified_device,
)
from .util.arch_list import device_arch
@@ -415,11 +414,12 @@ def component_weight_bytes(model, config = None, cache = None) -> tuple[int, int
def check_single_device_guard(model, config = None, cache = None, device = 0,
- budget: DeviceBudget | None = None,
+ guard_mode: str | None = None,
arch: str = "", logger = print):
- """Pre-flight guard for a single-device load (default mode: warn)."""
+ """Pre-flight guard for a single-device load."""
weights, cache_bytes = component_weight_bytes(model, config, cache)
- return check_single_device(weights, cache_bytes, device, budget = budget,
+ policy = GuardPolicy.from_env(default_mode = guard_mode or "auto")
+ return check_single_device(weights, cache_bytes, device, policy = policy,
arch = arch, logger = logger)
@@ -737,7 +737,8 @@ class SplitPlan:
part1_reserve_gb: float = 0.0,
preset: str = "auto",
auto_cap: int | None = None,
- guard_budget: DeviceBudget | None = None,
+ guard_mode: str | None = None,
+ guard: OOMGuard | None = None,
logger = print,
):
self.devices = devices
@@ -749,11 +750,12 @@ 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 = logger
+ self.guard = guard or OOMGuard(
+ GuardPolicy.from_env(default_mode = guard_mode or "auto"), logger = self.logger)
self.maps: dict[str, ComponentMap] = {}
self._decls: dict[str, tuple] = {}
self.configs: list[object] = []
@@ -1060,8 +1062,8 @@ class SplitPlan:
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:
+ """Refuse before allocation: read-only and idempotent."""
+ if self.guard.policy.mode == "off" or not self.maps:
return
try:
if not torch.cuda.is_available():
@@ -1074,31 +1076,22 @@ class SplitPlan:
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,
+ context, tuple(sorted(probe.items())), self.guard.policy.mode,
tuple(sorted(loaded)))
if key == self._guard_key:
return
host_available = host_available_bytes()
- footprints = self._guard_footprints(guard, probe = probe,
+ footprints = self._guard_footprints(self.guard, probe = probe,
skip_components = loaded, infos = infos)
- report = guard.evaluate(footprints, host_available = host_available)
+ report = self.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 not report.ok and text is not None:
+ largest_n = self._largest_guard_n(self.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(
+ self.guard_report = self.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
diff --git a/exllamav3/guard.py b/exllamav3/guard.py
index f2ff048..19bf312 100755
--- a/exllamav3/guard.py
+++ b/exllamav3/guard.py
@@ -4,18 +4,16 @@ 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.
+On unified-memory boxes the GPU and host share one pool. When that pool is exhausted
+the kernel may starve rather than cleanly OOM-kill, costing a physical power cycle.
+`torch.cuda.mem_get_info()` reports device/free numbers, not the host's ability to
+service the kernel and background processes. This supervisor watches
+/proc/meminfo from the OUTSIDE, in a process that allocates nothing, and kills the
+child while the host still has its configured floor.
+
+The device side is handled by the in-process pre-flight guard: it caps each device at
+that device's own free/total memory. The supervisor owns only the host floor, because
+that is the resource whose exhaustion hangs a unified-memory box.
Usage
-----
@@ -23,30 +21,28 @@ Usage
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)
+ --floor-gib F kill when MemAvailable < F GiB (default 7 or
+ KYOJIN_OOM_GUARD_HOST_FREE_GIB)
+ --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 trace here
+ --grace S seconds to wait after SIGKILL (default 30)
+ --sample-every S append a host-memory sample to the log every S seconds
--fadvise-dir DIR release DIR/*.safetensors page cache periodically
- --fadvise-every S page-cache release period (default 5)
+ --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).
+ the child's exit code, or 137 if guard killed it.
-`util/memguard.py` remains as a compatibility wrapper that execs this file without
+`util/memguard.py` remains 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
@@ -54,21 +50,29 @@ import sys
import time
GIB = 1024.0 * 1024.0 * 1024.0
+DEFAULT_FLOOR_GIB = 7.0
+
+
+def _env_float(name: str, fallback: float) -> float:
+ try:
+ return float(os.environ.get(name, fallback))
+ except ValueError:
+ return float(fallback)
def meminfo() -> dict[str, int]:
"""Return /proc/meminfo in bytes. Cheap: one read of a ~1.5 kB pseudo-file."""
- out = {}
+ out: dict[str, int] = {}
try:
with open("/proc/meminfo", "r", encoding = "ascii") as f:
for line in f:
- k, _, rest = line.partition(":")
+ key, _, rest = line.partition(":")
rest = rest.strip()
if rest.endswith(" kB"):
- out[k] = int(rest[:-3]) * 1024
+ out[key] = int(rest[:-3]) * 1024
else:
try:
- out[k] = int(rest)
+ out[key] = int(rest)
except ValueError:
pass
except OSError:
@@ -103,7 +107,6 @@ class Logger:
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):
@@ -113,189 +116,33 @@ def kill_tree(pid: int, sig: int) -> None:
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_memory() -> dict[str, dict[str, object]]:
- """Free/total memory and APU-vs-dedicated classification for every AMD card."""
- out: dict[str, dict[str, object]] = {}
- 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
- # A discrete card has a significant VRAM pool; an APU's VRAM is a small
- # carve-out and its real budget is the GTT aperture.
- dedicated = (vram_total is not None and vram_total >= 8 * 1024 ** 3
- and gtt_total is not None and vram_total >= 0.05 * gtt_total)
- if dedicated:
- total, used = vram_total, vram_used
- elif gtt_total is not None:
- total, used = gtt_total, gtt_used
- elif vram_total is not None:
- total, used = vram_total, vram_used
- if total is not None and used is not None:
- out[name] = {"free": max(0, total - used), "total": total,
- "dedicated": bool(dedicated)}
- return out
-
-
-def amd_device_free() -> dict[str, int]:
- return {name: int(info["free"]) for name, info in amd_device_memory().items()}
-
-
-_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)
-
-
-AUTO_UNIFIED_DEVICE_FLOOR_GIB = 7.0
-
-
-def auto_unified_floors(floors: dict[str, float]) -> tuple[dict[str, float], bool]:
- """Use the measured unified GTT free floor when the operator gave no device floor.
-
- The 128K N=5 load completed with ~8.7 GiB GTT free and MTP-on N=7 8K completed at
- ~7.1 GiB; the fatal MTP-on event had only ~4.3 GiB. Seven GiB is the measured
- boundary, not a generic cushion.
- """
- if floors:
- return floors, False
- devices = amd_device_memory()
- auto = {name: AUTO_UNIFIED_DEVICE_FLOOR_GIB for name, info in devices.items()
- if not bool(info["dedicated"])}
- return auto, bool(auto)
-
-
-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:
+ default_floor = _env_float("KYOJIN_OOM_GUARD_HOST_FREE_GIB", DEFAULT_FLOOR_GIB)
ap = argparse.ArgumentParser(add_help = True)
- ap.add_argument("--floor-gib", type = float, default = 7.0)
+ ap.add_argument("--floor-gib", type = float, default = default_floor)
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("--sample-every", type = float, default = 0.0,
+ help = "append a MemAvailable/MemFree host sample to --log this often")
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.",
+ "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.",
)
ap.add_argument("--fadvise-every", type = float, default = 5.0)
- ap.add_argument("--sample-every", type = float, default = 5.0,
- help = "append a MemAvailable/MemFree/GTT sample to --log this often")
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)
- floors, auto_floors = auto_unified_floors(floors)
if args.selftest:
mi = meminfo()
@@ -305,10 +152,6 @@ def main() -> int:
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
@@ -324,25 +167,9 @@ def main() -> int:
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"
+ f"MemAvailable {fmt_gib(mi.get('MemAvailable', 0))} GiB, "
+ f"Cached {fmt_gib(mi.get('Cached', 0))} GiB"
)
- if floors:
- if auto_floors:
- log("auto unified/GTT floor: " + ", ".join(
- f"{name}={value:.1f} GiB" for name, value in sorted(floors.items())))
- 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:
@@ -353,8 +180,6 @@ def main() -> int:
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)
@@ -364,7 +189,6 @@ def main() -> int:
last_fadv = 0.0
last_sample = 0.0
killed = False
- device_warned = False
fadvise_files: list[str] = []
for d in args.fadvise_dir:
@@ -380,21 +204,18 @@ def main() -> int:
f"{args.fadvise_every}s"
)
- def fadvise_now() -> int:
- n = 0
- for p in fadvise_files:
+ def fadvise_now() -> None:
+ for path in fadvise_files:
try:
- fd = os.open(p, os.O_RDONLY)
+ fd = os.open(path, 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:
@@ -407,19 +228,14 @@ def main() -> int:
rss = proc_rss(child.pid)
peak_rss = max(peak_rss, rss)
now = time.time()
- mono = time.monotonic()
- dev = device_free(floors, now = mono) if (floors or args.sample_every > 0) else {}
- if (args.sample_every > 0 and now - last_sample >= args.sample_every):
+ if args.sample_every > 0 and now - last_sample >= args.sample_every:
last_sample = now
- device_text = " ".join(
- f"{name}_free={free / GIB:.2f}" for name, free in sorted(dev.items()))
log(f"sample t+{now - t0:.1f}s MemAvailable={avail / GIB:.2f} "
f"MemFree={mi.get('MemFree', 0) / GIB:.2f} "
f"Cached={mi.get('Cached', 0) / GIB:.2f} "
f"Dirty={mi.get('Dirty', 0) / GIB:.2f} "
- f"Unevictable={mi.get('Unevictable', 0) / GIB:.2f} "
- f"{device_text}".rstrip())
+ f"Unevictable={mi.get('Unevictable', 0) / GIB:.2f}")
if avail < floor:
log(
@@ -427,15 +243,13 @@ def main() -> int:
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"Dirty {fmt_gib(mi.get('Dirty', 0))} GiB "
+ f"Unevictable {fmt_gib(mi.get('Unevictable', 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."
+ " Killing now, before the unified pool starves the kernel."
)
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")
@@ -444,28 +258,6 @@ def main() -> int:
pass
break
- if floors:
- 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)
diff --git a/exllamav3/memory_guard.py b/exllamav3/memory_guard.py
index 31af569..7252168 100644
--- a/exllamav3/memory_guard.py
+++ b/exllamav3/memory_guard.py
@@ -1,155 +1,56 @@
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: ``capacity = min(total, free) - reserve``, capped by the observed usable
- ceiling (default 113.3 GiB). The measured 8 GiB unified reserve is the free-memory
- floor, not a second subtraction on top of the ceiling; the 128K N=5 load completed at
- 8.7 GiB GTT free and the fatal MTP-on event had ~4.3 GiB.
-* 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.
+"""Read-only pre-flight memory guard.
+
+The device cap is the device itself: ``min(mem_get_info().free, total)``. There is no
+GTT/VRAM reserve on this branch. The only memory budget the guard owns is the host
+floor: the process must leave enough host memory for the OS, the driver and background
+processes. A supervisor enforces the same floor from outside the process; the preflight
+adds a small planning margin so it does not deliberately plan at the kill threshold.
+
+Models are loaded from actual measured bytes: module weights, cache/recurrent bytes, the
+part0 load slab and a prefill workspace. A dedicated-VRAM OOM is left to the process
+(and is normally a recoverable allocation error); the host floor is what prevents the
+unified-memory box from starving.
"""
-import dataclasses
+import glob
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 = 8.0
-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
+MODES = ("auto", "off")
DEFAULT_HOST_FLOOR_GIB = 7.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")
+DEFAULT_PREFLIGHT_MARGIN_GIB = 1.0
+DEFAULT_WORKSPACE_GIB = 2.0
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
+ """The pre-flight estimate does not fit; raised before allocation."""
@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).
- """
+class GuardPolicy:
+ """The only tunables: host reserve, planner margin and the prefill workspace."""
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
+ preflight_margin_gib: float = DEFAULT_PREFLIGHT_MARGIN_GIB
+ workspace_gib: float = DEFAULT_WORKSPACE_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}")
+ self.host_floor_gib = max(0.0, float(self.host_floor_gib))
+ self.preflight_margin_gib = max(0.0, float(self.preflight_margin_gib))
+ self.workspace_gib = max(0.0, float(self.workspace_gib))
@classmethod
- def from_env(cls, default_mode: str = "auto") -> DeviceBudget:
- """Build from ``KYOJIN_OOM_GUARD*`` environment fallbacks."""
- def f(name, fallback):
+ def from_env(cls, default_mode: str = "auto") -> GuardPolicy:
+ def value(name: str, fallback: float) -> float:
try:
return float(os.environ.get(name, fallback))
except ValueError:
@@ -157,60 +58,19 @@ class DeviceBudget:
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),
+ host_floor_gib=value("KYOJIN_OOM_GUARD_HOST_FREE_GIB", DEFAULT_HOST_FLOOR_GIB),
+ preflight_margin_gib=value("KYOJIN_OOM_GUARD_PREFLIGHT_MARGIN_GIB",
+ DEFAULT_PREFLIGHT_MARGIN_GIB),
+ workspace_gib=value("KYOJIN_OOM_GUARD_WORKSPACE_GIB", DEFAULT_WORKSPACE_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),
- }
+ @property
+ def preflight_host_floor_gib(self) -> float:
+ return self.host_floor_gib + self.preflight_margin_gib
# ---------------------------------------------------------------------------------------------------------
-# Device/host probes (monkeypatchable in CPU tests)
+# Probes (monkeypatchable from CPU tests)
# ---------------------------------------------------------------------------------------------------------
def _torch():
@@ -219,7 +79,6 @@ def _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:
@@ -250,29 +109,21 @@ def host_total_bytes() -> int | 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 int(_torch().cuda.get_device_properties(int(index)).total_memory)
+ except Exception: # noqa: BLE001 - unavailable probe
return None
def device_free_bytes(index: int) -> int | None:
try:
- torch = _torch()
- free, _total = torch.cuda.mem_get_info(int(index))
+ free, _total = _torch().cuda.mem_get_info(int(index))
return int(free)
- except Exception: # noqa: BLE001 - CPU tests / unavailable probe
+ except Exception: # noqa: BLE001 - 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.
- """
+ """Positive unified/GTT detection, independent of a hardcoded device index."""
arch_key = (arch or "").strip().lower()
if arch_key.startswith("gfx115"):
return True
@@ -289,11 +140,10 @@ def is_unified_device(index: int, arch: str | None = None, total: int | None = N
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
+ # A dedicated GPU can be more than half of host RAM, so require a near-host total
+ # together with an AMD GTT pool before treating it as unified.
+ return (total is not None and host is not None and total >= 0.9 * host
+ and bool(glob.glob("/sys/class/drm/card*/device/mem_info_gtt_total")))
# ---------------------------------------------------------------------------------------------------------
@@ -310,37 +160,23 @@ class DeviceFootprint:
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
+ slab_bytes: int = 0
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))
+ 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)
+ def capacity_bytes(self) -> int | None:
+ """The device cap is its own free/total memory; no device reserve."""
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))
- # The reserve is the free-memory floor we keep below the device's usable
- # capacity. For a unified device that floor covers both the GTT pool and the
- # host kernel's own allocation needs, so it is one subtraction, not two.
- hard = base - reserve
- if self.unified:
- hard = min(hard, int(unified_ceiling_gib * GIB))
- hard -= int(self.safety_bytes) + int(self.floor_bytes)
- return max(0, hard)
+ return int(self.total_bytes)
+ if self.total_bytes is None:
+ return int(self.free_bytes)
+ return min(int(self.total_bytes), int(self.free_bytes))
def describe(self) -> str:
parts = [f"cuda:{self.index}"]
@@ -365,7 +201,6 @@ class DeviceResult:
return max(0, self.footprint.need_bytes - self.capacity_bytes)
-
@dataclass
class HostResult:
available_bytes: int | None
@@ -385,28 +220,25 @@ class HostResult:
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:
+ if result.capacity_bytes is not None and result.deficit_bytes > 0:
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)")
+ host = self.host_result
+ if host is not None and host.capacity_bytes is not None and host.deficit_bytes > 0:
+ out.append(f"host needs {host.need_bytes / GIB:.2f} GiB, capacity "
+ f"{host.capacity_bytes / GIB:.2f} GiB "
+ f"(deficit {host.deficit_bytes / GIB:.2f} GiB)")
return out
@property
@@ -417,7 +249,7 @@ class GuardReport:
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"]
+ lines = ["device arch need capacity free total slab workspace 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}"
@@ -425,14 +257,15 @@ def _format_report(report: GuardReport, *, context: int | None,
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")
+ f"{fp.slab_bytes / GIB:5.2f} {fp.workspace_bytes / GIB:10.2f} "
+ f"{result.deficit_bytes / GIB:8.2f}")
+ host = report.host_result
+ if host is not None and host.capacity_bytes is not None:
+ lines.append(f"host MemAvailable {host.available_bytes / GIB:.2f} GiB, GTT need "
+ f"{host.need_bytes / GIB:.2f} GiB, planning floor "
+ f"{host.floor_bytes / GIB:.2f} GiB, capacity "
+ f"{host.capacity_bytes / GIB:.2f} GiB, deficit "
+ f"{host.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:
@@ -444,64 +277,40 @@ def _format_report(report: GuardReport, *, context: int | None,
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
+ def __init__(self, policy: GuardPolicy, logger: Callable[[str], None] = print):
+ self.policy = policy
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:
+ 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),
+ index = index, arch = arch, name = name,
+ unified = is_unified_device(index, arch, total_bytes),
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),
+ workspace_bytes = int(self.policy.workspace_gib * 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)
+ results = [DeviceResult(fp, fp.capacity_bytes()) for fp in footprints]
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)
+ host = HostResult(available_bytes = host_available,
+ need_bytes = sum(fp.need_bytes for fp in footprints if fp.unified),
+ floor_bytes = int(self.policy.preflight_host_floor_gib * GIB))
+ return GuardReport(device_results = results, host_result = host)
def check(self, footprints: Iterable[DeviceFootprint], *,
host_available: int | None = None,
@@ -510,7 +319,7 @@ class OOMGuard:
largest_n: int | None = None,
largest_ctx: int | None = None) -> GuardReport:
report = self.evaluate(footprints, host_available = host_available)
- if self.mode == "off":
+ if self.policy.mode == "off":
return report
for result in report.device_results:
fp = result.footprint
@@ -519,27 +328,24 @@ class OOMGuard:
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"slab {fp.slab_bytes / GIB:.2f}, workspace {fp.workspace_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})")
+ host = report.host_result
+ if host is not None and host.capacity_bytes is not None:
+ self.logger(f"[oom-guard] host: GTT need {host.need_bytes / GIB:.2f} GiB of "
+ f"{host.capacity_bytes / GIB:.2f} GiB (MemAvailable "
+ f"{host.available_bytes / GIB:.2f} - planning floor "
+ f"{host.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).")
+ f"(mode={self.policy.mode}):\n{message}\n"
+ "Lower -c/--max-ctx or --part0-layers, raise KYOJIN_OOM_GUARD_HOST_FREE_GIB/"
+ "KYOJIN_OOM_GUARD_PREFLIGHT_MARGIN_GIB if they are wrong, or set "
+ "KYOJIN_OOM_GUARD=off to disable the preflight.")
def check_single_device(
@@ -547,54 +353,17 @@ def check_single_device(
cache_bytes: int,
device,
*,
- budget: DeviceBudget | None = None,
+ policy: GuardPolicy | 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,
+ guard = OOMGuard(policy or GuardPolicy.from_env(), logger = logger)
+ fp = guard.footprint(index, arch = arch, 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.py
index 44c46e1..773f26e 100755
--- a/exllamav3/model_init.py
+++ b/exllamav3/model_init.py
@@ -384,8 +384,8 @@ def init(
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.
+ # Single-device loads use the same automatic preflight; KYOJIN_OOM_GUARD=off
+ # disables it.
from .device_map import check_single_device_guard
check_single_device_guard(model, config, cache, single_device,
logger = lambda m: printp(not quiet, m))
diff --git a/exllamav3/serve_split.py b/exllamav3/serve_split.py
index c9ea8ec..b6c5699 100644
--- a/exllamav3/serve_split.py
+++ b/exllamav3/serve_split.py
@@ -14,7 +14,6 @@ exllamav3 imports are deliberately deferred to call time.
"""
import argparse
-import glob
import os
import time
from dataclasses import dataclass
@@ -49,145 +48,6 @@ 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]] = {
@@ -224,12 +84,7 @@ class SplitSettings:
part0_reserve_gb: float = DEFAULT_PART0_RESERVE_GB
preset: 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
@property
def enabled(self) -> bool:
@@ -241,31 +96,14 @@ class SplitSettings:
@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
+ return (self.oom_guard or "auto").strip().lower()
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} allocator={self.expandable_segments} "
- f"oom_guard={self.guard_mode}")
+ f"graphs={self.split_graphs} oom_guard={self.guard_mode}")
def add_split_arguments(parser: argparse.ArgumentParser) -> None:
@@ -290,26 +128,9 @@ 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 8.0 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)")
+ parser.add_argument("--oom-guard", choices = ("auto", "off"), default = None,
+ help = "pre-flight memory guard: auto refuses before allocating, off disables "
+ "(default: KYOJIN_OOM_GUARD, else auto)")
def settings_from_namespace(args) -> SplitSettings:
@@ -326,8 +147,6 @@ 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",
@@ -336,16 +155,7 @@ 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"),
)
@@ -403,7 +213,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(),
+ guard_mode = self.settings.guard_mode,
logger = self.logger,
)
return self.plan
diff --git a/tests/test_memory_guard_cpu.py b/tests/test_memory_guard_cpu.py
index 635f963..0ec34ed 100644
--- a/tests/test_memory_guard_cpu.py
+++ b/tests/test_memory_guard_cpu.py
@@ -1,12 +1,11 @@
-"""CPU tests for the pre-flight memory guard and the allocator-mode entry point.
+"""CPU tests for the pre-flight memory guard and the host-only supervisor.
-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.
+The guard must be testable without a GPU: device caps, host floor, strict refusal and
+off mode are pure Python.
"""
from __future__ import annotations
import importlib.util
-import os
import sys
from pathlib import Path
from types import SimpleNamespace
@@ -40,233 +39,119 @@ def guard_mod():
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: 8.0}
- 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}
+ "workspace_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_measured_unified_reserve_leaves_seven_gib_of_free_pool(mg):
- # 118 GiB GTT total, 8 GiB pre-flight reserve -> 110 GiB planned, still under the
- # 113.3 GiB hard ceiling; the supervisor's last-resort GTT floor is 7 GiB.
- fp = _footprint(mg, reserve_bytes = int(8.0 * GIB), weights_bytes = int(107 * GIB),
- workspace_bytes = int(2 * GIB))
- assert fp.capacity_bytes(113.3) == int(110 * GIB)
- assert fp.need_bytes == int(109 * 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)
+def _guard(mg, mode="auto", host_floor=7.0, margin=1.0, workspace=2.0):
+ policy = mg.GuardPolicy(mode=mode, host_floor_gib=host_floor,
+ preflight_margin_gib=margin, workspace_gib=workspace)
+ return mg.OOMGuard(policy, logger=lambda *_a: None)
+
+
+def test_policy_env_defaults_and_overrides(mg, monkeypatch):
+ for key in ("KYOJIN_OOM_GUARD", "KYOJIN_OOM_GUARD_HOST_FREE_GIB",
+ "KYOJIN_OOM_GUARD_PREFLIGHT_MARGIN_GIB", "KYOJIN_OOM_GUARD_WORKSPACE_GIB"):
+ monkeypatch.delenv(key, raising=False)
+ policy = mg.GuardPolicy.from_env()
+ assert policy.mode == "auto"
+ assert policy.host_floor_gib == 7.0
+ assert policy.preflight_margin_gib == 1.0
+ assert policy.workspace_gib == 2.0
+
+ monkeypatch.setenv("KYOJIN_OOM_GUARD", "OFF")
+ monkeypatch.setenv("KYOJIN_OOM_GUARD_HOST_FREE_GIB", "9.5")
+ monkeypatch.setenv("KYOJIN_OOM_GUARD_PREFLIGHT_MARGIN_GIB", "0.5")
+ monkeypatch.setenv("KYOJIN_OOM_GUARD_WORKSPACE_GIB", "3")
+ policy = mg.GuardPolicy.from_env()
+ assert policy.mode == "off"
+ assert policy.host_floor_gib == 9.5
+ assert policy.preflight_host_floor_gib == 10.0
+ assert policy.workspace_gib == 3.0
+
+
+def test_device_capacity_is_free_or_total_not_a_reserve(mg):
+ fp = _footprint(mg, total_bytes=118 * GIB, free_bytes=110 * GIB,
+ weights_bytes=100 * GIB, cache_bytes=8 * GIB,
+ slab_bytes=GIB, workspace_bytes=2 * GIB)
+ assert fp.capacity_bytes() == 110 * GIB
+ assert fp.need_bytes == 111 * GIB
+
+ # Another process using the card lowers free memory; the cap follows it.
+ fp = _footprint(mg, total_bytes=16 * GIB, free_bytes=12 * GIB)
+ assert fp.capacity_bytes() == 12 * GIB
+
+ # No probe data means no opinion, not a hard-coded size.
+ fp = _footprint(mg, total_bytes=None, free_bytes=None)
+ assert fp.capacity_bytes() is None
+
+
+def test_preflight_refuses_strictly_when_need_exceeds_host_capacity(mg):
+ # Device fits (need 108 < 118), host planning capacity is 120 - (7 + 1) = 112.
+ fp = _footprint(mg, weights_bytes=106 * GIB, workspace_bytes=2 * GIB)
+ guard = _guard(mg)
+ assert guard.check([fp], host_available=120 * GIB).ok
+
+ # 0.1 GiB over is refused; there is no tolerance band.
+ fp = _footprint(mg, weights_bytes=110.1 * GIB, workspace_bytes=2 * GIB)
+ with pytest.raises(mg.OOMGuardError, match="refused the load"):
+ guard.check([fp], host_available=120 * GIB)
+
+
+def test_device_cap_refuses_even_when_the_host_is_fine(mg):
+ fp = _footprint(mg, total_bytes=16 * GIB, free_bytes=15 * GIB,
+ weights_bytes=14.5 * GIB, workspace_bytes=2 * GIB)
+ with pytest.raises(mg.OOMGuardError, match="deficit"):
+ _guard(mg).check([fp], host_available=120 * GIB)
+
+
+def test_mode_off_returns_a_report_without_raising(mg):
+ fp = _footprint(mg, total_bytes=16 * GIB, free_bytes=15 * GIB,
+ weights_bytes=20 * GIB)
+ report = _guard(mg, mode="off").check([fp], host_available=1)
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")
+ fp = _footprint(mg, weights_bytes=116 * GIB, workspace_bytes=2 * GIB)
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)
+ _guard(mg).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)
+def test_single_device_uses_the_automatic_policy(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
+ monkeypatch.setattr(mg, "is_unified_device", lambda *_a, **_k: True)
+ # Device fits, host planning capacity (112) does not.
+ with pytest.raises(mg.OOMGuardError, match="refused the load"):
+ mg.check_single_device(116 * GIB, 0, 0, logger=lambda *_a: None)
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)
+ monkeypatch.setattr(mg, "_torch", lambda: SimpleNamespace(cuda=SimpleNamespace(
+ get_device_properties=lambda _i: (_ for _ in ()).throw(RuntimeError("no gpu")))))
assert mg.is_unified_device(0, "gfx1201", 80 * GIB) is False
assert mg.is_unified_device(0, "gfx1151", 80 * GIB) is True
-def test_auto_unified_floor_only_targets_the_apu(guard_mod, monkeypatch):
- monkeypatch.setattr(guard_mod, "amd_device_memory", lambda: {
- "card0": {"free": 118 * GIB, "total": 118 * GIB, "dedicated": False},
- "card1": {"free": 16 * GIB, "total": 16 * GIB, "dedicated": True},
- })
- floors, active = guard_mod.auto_unified_floors({})
- assert active and floors == {"card0": 7.0}
- explicit = {"card0": 3.0}
- floors, active = guard_mod.auto_unified_floors(explicit)
- assert not active and floors == explicit
-
-
-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.5
+def test_supervisor_host_floor_is_env_tunable(guard_mod, monkeypatch):
+ monkeypatch.delenv("KYOJIN_OOM_GUARD_HOST_FREE_GIB", raising=False)
+ assert guard_mod._env_float("KYOJIN_OOM_GUARD_HOST_FREE_GIB",
+ guard_mod.DEFAULT_FLOOR_GIB) == 7.0
+ monkeypatch.setenv("KYOJIN_OOM_GUARD_HOST_FREE_GIB", "9.5")
+ assert guard_mod._env_float("KYOJIN_OOM_GUARD_HOST_FREE_GIB",
+ guard_mod.DEFAULT_FLOOR_GIB) == 9.5
diff --git a/tests/test_split_plan_cpu.py b/tests/test_split_plan_cpu.py
index 9ccdb17..08bfa70 100644
--- a/tests/test_split_plan_cpu.py
+++ b/tests/test_split_plan_cpu.py
@@ -144,10 +144,10 @@ def _infos(dm, *pairs):
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.
+ The guard integration test passes an explicit guard, so it is unaffected.
"""
dm = split_modules[0]
- monkeypatch.setattr(dm.DeviceBudget, "from_env",
+ monkeypatch.setattr(dm.GuardPolicy, "from_env",
classmethod(lambda cls, default_mode = "auto": cls(mode = "off")))
@@ -736,14 +736,14 @@ def test_split_settings_off_is_a_noop(split_modules, monkeypatch):
assert os.environ["EXL3_GR_PF_FUSE"] == "0"
-def _fake_guard_probe(dm, monkeypatch, *, part0_total=16 * 1024 ** 3,
+def _fake_guard_probe(dm, monkeypatch, *, mg, 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",
+ monkeypatch.setattr(mg, "is_unified_device",
lambda i, arch=None, total=None: i == 0)
monkeypatch.setattr(dm, "host_available_bytes", lambda: host_available)
@@ -755,9 +755,10 @@ def test_split_plan_guard_passes_or_refuses_before_allocation(split_modules, mon
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)
+ _fake_guard_probe(dm, monkeypatch, mg=mg)
plan = dm.SplitPlan(_devices(dm), endcaps = True, part0_layers = 2,
- guard_budget = dm.DeviceBudget(mode = "auto"),
+ guard = dm.OOMGuard(dm.GuardPolicy(mode = "auto"),
+ logger = lambda *_a: None),
logger = lambda *_a: None)
plan.add("text", small, config = small_cfg)
plan.build()
@@ -766,22 +767,17 @@ def test_split_plan_guard_passes_or_refuses_before_allocation(split_modules, mon
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"),
+ guard = dm.OOMGuard(dm.GuardPolicy(mode = "auto"),
+ logger = lambda *_a: None),
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 skips the check entirely.
off = dm.SplitPlan(_devices(dm), endcaps = True, part0_layers = 2,
- guard_budget = dm.DeviceBudget(mode = "off"),
+ guard = dm.OOMGuard(dm.GuardPolicy(mode = "off"),
+ logger = lambda *_a: None),
logger = lambda *_a: None)
off.add("text", huge, config = huge_cfg)
off.build()
@@ -790,5 +786,4 @@ def test_split_plan_guard_passes_or_refuses_before_allocation(split_modules, mon
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"
+ assert split.SplitSettings(part0_layers = 1, oom_guard = "OFF").guard_mode == "off"
diff --git a/tools/glm/serve.py b/tools/glm/serve.py
index 3b159cd..a78d85f 100644
--- a/tools/glm/serve.py
+++ b/tools/glm/serve.py
@@ -27,7 +27,7 @@ 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_allocator_env, apply_split_env,
+ SplitController, SplitSettings, add_split_arguments, 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)
@@ -845,7 +845,7 @@ class ResidentEngine:
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(),
+ guard_mode=split_settings.guard_mode,
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:
@@ -2303,8 +2303,6 @@ 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.sh
index 1927980..bb49338 100755
--- a/tools/glm/serve_lane.sh
+++ b/tools/glm/serve_lane.sh
@@ -9,8 +9,6 @@ mkdir -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:-7}"
-MEMGUARD_DEVICE_FLOOR="${MEMGUARD_DEVICE_FLOOR:-0}"
MODEL=""
args=("$@")
for ((i = 0; i < ${#args[@]}; i++)); do
@@ -34,12 +32,11 @@ case "$MEMGUARD" in
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)
+ MG=(python "$LANE_ROOT/exllamav3/guard.py" --label glm
+ --log "$TMPDIR/memguard.log" --sample-every 5 --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
+ echo "serve_lane: MEMGUARD=on (host floor ${KYOJIN_OOM_GUARD_HOST_FREE_GIB:-7} GiB, log $TMPDIR/memguard.log)" >&2
elif [ "$MEMGUARD" = "1" ]; then
echo "serve_lane: MEMGUARD=1 requested but exllamav3/guard.py is missing" >&2
exit 1
diff --git a/tools/mimo/serve_lane.sh b/tools/mimo/serve_lane.sh
index 3fa92ad..ceca277 100755
--- a/tools/mimo/serve_lane.sh
+++ b/tools/mimo/serve_lane.sh
@@ -8,8 +8,6 @@ mkdir -p "$TMPDIR"
# External supervisor: unified-memory boxes do not reliably OOM-kill.
MEMGUARD="${MEMGUARD:-auto}"
-MEMGUARD_FLOOR="${MEMGUARD_FLOOR:-7}"
-MEMGUARD_DEVICE_FLOOR="${MEMGUARD_DEVICE_FLOOR:-0}"
MODEL=""
mg_args=("$@")
for ((i = 0; i < ${#mg_args[@]}; i++)); do
@@ -21,16 +19,22 @@ 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 ;;
+ 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
+ ;;
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)
+ MG=(python "$LANE_ROOT/exllamav3/guard.py" --label mimo
+ --log "$TMPDIR/memguard.log" --sample-every 5 --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
+ echo "serve_lane: MEMGUARD=on (host floor ${KYOJIN_OOM_GUARD_HOST_FREE_GIB:-7} GiB, log $TMPDIR/memguard.log)" >&2
elif [ "$MEMGUARD" = "1" ]; then
echo "serve_lane: MEMGUARD=1 requested but exllamav3/guard.py is missing" >&2
exit 1
diff --git a/tools/strix_halo/split_eval.py b/tools/strix_halo/split_eval.py
index ac20bc4..d54498d 100644
--- a/tools/strix_halo/split_eval.py
+++ b/tools/strix_halo/split_eval.py
@@ -30,14 +30,10 @@ correctness; per-segment capture is Phase 6).
from __future__ import annotations
import argparse
-import importlib.util
import json
import os
import re
-import sys
import 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.
@@ -98,16 +94,8 @@ 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("--oom-guard", choices=("auto", "off"), default=None,
+ help="pre-flight memory guard (default: KYOJIN_OOM_GUARD, else auto)")
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")
@@ -158,31 +146,8 @@ 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"
@@ -420,7 +385,6 @@ def main() -> None:
Tokenizer,
)
from exllamav3.generator import generator as GM
- from exllamav3.memory_guard import DeviceBudget
torch.set_grad_enabled(False)
@@ -457,21 +421,10 @@ def main() -> None:
if not args.baseline:
from exllamav3.device_map import SplitPlan, resolve_devices
devices = 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_floor
plan = 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, guard_budget = budget)
+ part1_reserve_gb = args.part1_reserve_gb, guard_mode = args.oom_guard)
if draft is not None:
plan.add("mtp", draft, config = config, cache = draft_cache, load_order = 1)
if vision is not None:
diff --git a/tools/strix_halo/split_load.py b/tools/strix_halo/split_load.py
index 7e119c8..8b1910e 100644
--- a/tools/strix_halo/split_load.py
+++ b/tools/strix_halo/split_load.py
@@ -12,13 +12,8 @@ Usage (from the repo root, after `source tools/strix_halo/env.sh`):
from __future__ import annotations
import argparse
-import importlib.util
-import os
import resource
-import sys
import time
-from pathlib import Path
-from types import SimpleNamespace
def mem_available_gib() -> float:
@@ -31,23 +26,6 @@ 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)
@@ -60,21 +38,13 @@ 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)
+ p.add_argument("--oom-guard", choices=("auto", "off"), default=None)
args = p.parse_args()
- _apply_allocator_env(args)
-
import torch
from exllamav3 import Cache, CacheLayer_quant, Config, Model
from exllamav3.device_map import SplitPlan, resolve_devices
- from exllamav3.memory_guard import DeviceBudget
torch.set_grad_enabled(False)
endcaps = args.endcaps == "on"
@@ -104,7 +74,7 @@ def main() -> None:
try:
vision = Model.from_config(config, component="vision")
vision.load(device="cuda:0", progressbar=True)
- except Exception as exc: # noqa: BLE001
+ except Exception as exc:
print(f"[baseline] vision not loaded: {type(exc).__name__}: {exc}", flush=True)
print(f"[baseline] load {time.perf_counter() - t0:.1f} s; "
f"cuda:0 allocated {torch.cuda.memory_allocated(torch.device('cuda:0')) / 2**30:.2f} GiB; "
@@ -115,17 +85,6 @@ def main() -> None:
return
devices = 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_floor
# Declare MTP/vision before build so the pre-flight guard includes them.
draft = draft_cache = None
if args.num_draft > 0:
@@ -137,11 +96,11 @@ def main() -> None:
if not args.no_vision:
try:
vision = Model.from_config(config, component="vision")
- except Exception as exc: # noqa: BLE001
+ except Exception as exc:
vision_error = exc
plan = SplitPlan(devices, endcaps=endcaps, part0_layers=args.part0_layers,
- part0_reserve_gb=args.part0_reserve_gb, guard_budget=budget)
+ part0_reserve_gb=args.part0_reserve_gb, guard_mode=args.oom_guard)
if draft is not None:
plan.add("mtp", draft, config=config, cache=draft_cache, load_order=1)
if vision is not None:
@@ -174,7 +133,7 @@ def main() -> None:
plan.record_load("vision", time.perf_counter() - t1)
print(f"[split] vision loaded in {time.perf_counter() - t1:.1f} s "
f"on {plan.map('vision').placed_devices}", flush=True)
- except Exception as exc: # noqa: BLE001
+ except Exception as exc:
print(f"[split] vision not loaded: {type(exc).__name__}: {exc}", flush=True)
vision = None