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.

OOM guard fixes, further simplifications, backwards compatability and better Nvidia/Mac compatability

Resynth2e09135b0e55
diff --git a/doc/env_vars.md b/doc/env_vars.md
index bbf7116..1419ba4 100644
--- a/doc/env_vars.md
+++ b/doc/env_vars.md
@@ -726,13 +726,13 @@ There is no per-device GTT or VRAM reserve. Each device's cap is its own reporte
process-level error; the host floor is what protects the unified-memory box from kernel
starvation.
-### `KYOJIN_OOM_GUARD_HOST_FREE_GIB` (default: `7`)
+### `MEMGUARD_FLOOR` (default: `8`)
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.
+`MemAvailable < floor`. The name is the established memguard variable, so existing lanes
+keep working. Raise it for a hungrier OS or more background services; lower it only after
+measuring.
### `KYOJIN_OOM_GUARD_PREFLIGHT_MARGIN_GIB` (default: `1`)
diff --git a/doc/split.md b/doc/split.md
index 5a21335..3e181c2 100644
--- a/doc/split.md
+++ b/doc/split.md
@@ -91,10 +91,10 @@ The measured 118 GiB Strix Halo iGPU has a practical usable point of about **113
(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.
+hard-locked the box. A host-only supervisor catches a run that reaches the configured host
+floor before the kernel OOM zone; the preflight uses the same floor plus a small planning
+margin. The measured case and its explicit floor override are recorded in
+`docs-notes/split-support-matrix.md`.
### Pre-flight guard
@@ -108,7 +108,7 @@ 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)
+tunables are `MEMGUARD_FLOOR` (default 8), 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.
@@ -116,10 +116,8 @@ the margin keeps the planner above the supervisor's kill threshold.
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.
+The preflight's device caps are the devices' own free/full memory; the host cap follows
+the configured floor. A load that reaches the host floor is stopped by the supervisor.
### Allocator mode
@@ -142,10 +140,11 @@ Use `exllamav3/guard.py` (the compatibility path `util/memguard.py` execs it). I
python exllamav3/guard.py --fadvise-dir /path/to/model -- python tools/glm/serve.py ...
```
-The host floor defaults to 7 GiB (or `KYOJIN_OOM_GUARD_HOST_FREE_GIB`) and is the same value
+The host floor defaults to 8 GiB (or `MEMGUARD_FLOOR`) 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.
+`MEMGUARD=auto|1|0` wrapper: `auto` arms `exllamav3/guard.py` on Linux when
+`/proc/meminfo` is readable; use `MEMGUARD=0` to disable it.
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`.
diff --git a/doc/strix-halo.md b/doc/strix-halo.md
index 3a14ae7..95dbd0f 100644
--- a/doc/strix-halo.md
+++ b/doc/strix-halo.md
@@ -238,22 +238,21 @@ The 128 GB pool reports about 118 GiB to torch, but the practical usable point i
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
+ device at its own `min(free, total)`, and caps the host at `MemAvailable - 8 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
+ `MemAvailable` falls below 8 GiB (`MEMGUARD_FLOOR`) 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.
+the pre-flight guard; 768K previously hard-locked the box. Do not hand-pick an N for MTP-on:
+use the guard's largest-N/context output and keep the supervisor armed. The host floor is
+tunable with `MEMGUARD_FLOOR` if the OS/background load differs from the default.
## Build
diff --git a/examples/mimo_v2_6/serve.sh b/examples/mimo_v2_6/serve.sh
index 793b30e..c44f27b 100755
--- a/examples/mimo_v2_6/serve.sh
+++ b/examples/mimo_v2_6/serve.sh
@@ -62,9 +62,8 @@
# EXL3_LOAD_DEVICE=cuda:0 single-device load, bypassing the autosplit budget
# arithmetic (which reads MemFree, not MemAvailable).
# Set to "" to restore stock autosplit.
-# MEMGUARD=auto auto | 1 | 0. `auto` enables exllamav3/guard.py on Linux for a
-# unified/GTT device or a large model.
-# KYOJIN_OOM_GUARD_HOST_FREE_GIB=7 SIGKILL the server below this MemAvailable, in GiB
+# MEMGUARD=auto auto | 1 | 0. `auto` enables exllamav3/guard.py on Linux.
+# MEMGUARD_FLOOR=8 SIGKILL 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
#
@@ -245,21 +244,17 @@ export EXL3_LOAD_DEVICE="${EXL3_LOAD_DEVICE-cuda:0}"
use_mg=0
case "$MEMGUARD" in
1) use_mg=1 ;;
+ 0) ;;
auto)
- if compgen -G "/sys/class/drm/card*/device/mem_info_gtt_total" > /dev/null; then
- use_mg=1
- elif [ -r /proc/meminfo ]; then
- model_bytes=$(du -sb --apparent-size "$MODEL_DIR"/*.safetensors 2> /dev/null | awk '{s+=$1} END {print s+0}')
- [ "${model_bytes:-0}" -ge $((48 * 1024 * 1024 * 1024)) ] && use_mg=1
- fi
+ if [ -r /proc/meminfo ]; then use_mg=1; fi
;;
esac
if [ "$use_mg" = "1" ] && [ -f "$REPO/exllamav3/guard.py" ]; then
MG=(python "$REPO/exllamav3/guard.py"
--fadvise-dir "$MODEL_DIR" --fadvise-every 5 --label tabbyapi
- --sample-every 5 --log "${TMPDIR:-/tmp}/memguard.log")
+ --sample-every 5 --log "$TABBY_DIR/memguard.log")
MG+=(--)
- echo " -- MEMGUARD=on (host floor ${KYOJIN_OOM_GUARD_HOST_FREE_GIB:-7} GiB)"
+ echo " -- MEMGUARD=on (host floor MEMGUARD_FLOOR/default)"
else
MG=()
[ "$use_mg" = "1" ] || echo " !! memguard disabled (MEMGUARD=$MEMGUARD)"
diff --git a/exllamav3/device_map.py b/exllamav3/device_map.py
index 327a08b..2469ab1 100644
--- a/exllamav3/device_map.py
+++ b/exllamav3/device_map.py
@@ -415,10 +415,19 @@ def component_weight_bytes(model, config = None, cache = None) -> tuple[int, int
def check_single_device_guard(model, config = None, cache = None, device = 0,
guard_mode: str | None = None,
- arch: str = "", logger = print):
- """Pre-flight guard for a single-device load."""
+ extra_components = (), arch: str = "", logger = print):
+ """Pre-flight guard for a single-device load.
+
+ ``extra_components`` is an iterable of ``(model, config, cache)`` tuples for the
+ drafter and vision tower that load on the same device after the target.
+ """
weights, cache_bytes = component_weight_bytes(model, config, cache)
- policy = GuardPolicy.from_env(default_mode = guard_mode or "auto")
+ for extra_model, extra_config, extra_cache in extra_components:
+ extra_weights, extra_cache_bytes = component_weight_bytes(
+ extra_model, extra_config, extra_cache)
+ weights += extra_weights
+ cache_bytes += extra_cache_bytes
+ policy = GuardPolicy.from_env(explicit_mode = guard_mode)
return check_single_device(weights, cache_bytes, device, policy = policy,
arch = arch, logger = logger)
@@ -755,7 +764,7 @@ class SplitPlan:
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)
+ GuardPolicy.from_env(explicit_mode = guard_mode), logger = self.logger)
self.maps: dict[str, ComponentMap] = {}
self._decls: dict[str, tuple] = {}
self.configs: list[object] = []
diff --git a/exllamav3/guard.py b/exllamav3/guard.py
index 19bf312..37ac112 100755
--- a/exllamav3/guard.py
+++ b/exllamav3/guard.py
@@ -21,8 +21,8 @@ Usage
Options
-------
- --floor-gib F kill when MemAvailable < F GiB (default 7 or
- KYOJIN_OOM_GUARD_HOST_FREE_GIB)
+ --floor-gib F kill when MemAvailable < F GiB (default 8 or
+ MEMGUARD_FLOOR)
--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
@@ -49,15 +49,13 @@ import subprocess
import sys
import time
-GIB = 1024.0 * 1024.0 * 1024.0
-DEFAULT_FLOOR_GIB = 7.0
-
+# Import the stdlib-only shared floor policy without importing the package/torch.
+_HERE = os.path.dirname(os.path.abspath(__file__))
+if _HERE not in sys.path:
+ sys.path.insert(0, _HERE)
+from guard_common import host_floor_from_env
-def _env_float(name: str, fallback: float) -> float:
- try:
- return float(os.environ.get(name, fallback))
- except ValueError:
- return float(fallback)
+GIB = 1024.0 * 1024.0 * 1024.0
def meminfo() -> dict[str, int]:
@@ -95,9 +93,22 @@ def proc_rss(pid: int) -> int:
return 0
+def _open_log(path: str):
+ flags = os.O_WRONLY | os.O_CREAT | os.O_APPEND
+ if hasattr(os, "O_NOFOLLOW"):
+ flags |= os.O_NOFOLLOW
+ fd = os.open(path, flags, 0o600)
+ return os.fdopen(fd, "a", buffering = 1)
+
+
class Logger:
def __init__(self, path: str | None):
- self.fh = open(path, "a", buffering = 1) if path else None # noqa: SIM115
+ self.fh = None
+ if path:
+ try:
+ self.fh = _open_log(path)
+ except OSError as exc:
+ print(f"[guard] cannot open log {path}: {exc}", file = sys.stderr, flush = True)
def __call__(self, msg: str) -> None:
line = f"[guard {time.strftime('%H:%M:%S')}] {msg}"
@@ -117,7 +128,7 @@ def kill_tree(pid: int, sig: int) -> None:
def main() -> int:
- default_floor = _env_float("KYOJIN_OOM_GUARD_HOST_FREE_GIB", DEFAULT_FLOOR_GIB)
+ default_floor = host_floor_from_env()
ap = argparse.ArgumentParser(add_help = True)
ap.add_argument("--floor-gib", type = float, default = default_floor)
ap.add_argument("--warn-gib", type = float, default = None)
diff --git a/exllamav3/guard_common.py b/exllamav3/guard_common.py
new file mode 100644
index 0000000..a13b9e2
--- /dev/null
+++ b/exllamav3/guard_common.py
@@ -0,0 +1,26 @@
+"""Shared host-floor policy for the preflight and the external supervisor.
+
+This module is stdlib-only: ``exllamav3/guard.py`` imports it as a script sibling so the
+supervisor can start without importing torch or the package.
+"""
+
+from __future__ import annotations
+
+import os
+
+DEFAULT_HOST_FLOOR_GIB = 8.0
+
+
+def host_floor_from_env() -> float:
+ """The one shared host `MemAvailable` floor, in GiB.
+
+ `MEMGUARD_FLOOR` is the established name, so existing lanes keep working. The
+ preflight and supervisor both read this value; they never carry separate defaults.
+ """
+ value = os.environ.get("MEMGUARD_FLOOR")
+ if value:
+ try:
+ return max(0.0, float(value))
+ except ValueError:
+ pass
+ return DEFAULT_HOST_FLOOR_GIB
diff --git a/exllamav3/memory_guard.py b/exllamav3/memory_guard.py
index 7252168..af2bec7 100644
--- a/exllamav3/memory_guard.py
+++ b/exllamav3/memory_guard.py
@@ -19,10 +19,20 @@ import os
from collections.abc import Callable, Iterable
from dataclasses import dataclass, field
+try:
+ from .guard_common import (
+ DEFAULT_HOST_FLOOR_GIB,
+ host_floor_from_env,
+ )
+except ImportError: # loaded as a standalone file in CPU tests
+ from guard_common import (
+ DEFAULT_HOST_FLOOR_GIB,
+ host_floor_from_env,
+ )
+
GIB = 1024 ** 3
MODES = ("auto", "off")
-DEFAULT_HOST_FLOOR_GIB = 7.0
DEFAULT_PREFLIGHT_MARGIN_GIB = 1.0
DEFAULT_WORKSPACE_GIB = 2.0
@@ -49,16 +59,19 @@ class GuardPolicy:
self.workspace_gib = max(0.0, float(self.workspace_gib))
@classmethod
- def from_env(cls, default_mode: str = "auto") -> GuardPolicy:
+ def from_env(cls, default_mode: str = "auto",
+ explicit_mode: str | None = None) -> GuardPolicy:
def value(name: str, fallback: float) -> float:
try:
return float(os.environ.get(name, fallback))
except ValueError:
return float(fallback)
+ mode = explicit_mode if explicit_mode is not None else os.environ.get(
+ "KYOJIN_OOM_GUARD", default_mode)
return cls(
- mode=os.environ.get("KYOJIN_OOM_GUARD", default_mode),
- host_floor_gib=value("KYOJIN_OOM_GUARD_HOST_FREE_GIB", DEFAULT_HOST_FLOOR_GIB),
+ mode=mode,
+ host_floor_gib=host_floor_from_env(),
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),
@@ -343,7 +356,7 @@ class OOMGuard:
raise OOMGuardError(
"pre-flight OOM guard refused the load before allocating anything "
f"(mode={self.policy.mode}):\n{message}\n"
- "Lower -c/--max-ctx or --part0-layers, raise KYOJIN_OOM_GUARD_HOST_FREE_GIB/"
+ "Lower -c/--max-ctx or --part0-layers, raise MEMGUARD_FLOOR/"
"KYOJIN_OOM_GUARD_PREFLIGHT_MARGIN_GIB if they are wrong, or set "
"KYOJIN_OOM_GUARD=off to disable the preflight.")
diff --git a/exllamav3/model_init.py b/exllamav3/model_init.py
index 773f26e..c4caf03 100755
--- a/exllamav3/model_init.py
+++ b/exllamav3/model_init.py
@@ -387,7 +387,9 @@ def init(
# Single-device loads use the same automatic preflight; KYOJIN_OOM_GUARD=off
# disables it.
from .device_map import check_single_device_guard
+ extras = [(draft_model, draft_config or config, draft_cache)] if draft_model is not None else []
check_single_device_guard(model, config, cache, single_device,
+ extra_components = extras,
logger = lambda m: printp(not quiet, m))
# Parallelism options
diff --git a/exllamav3/serve_split.py b/exllamav3/serve_split.py
index b6c5699..7cda84f 100644
--- a/exllamav3/serve_split.py
+++ b/exllamav3/serve_split.py
@@ -95,15 +95,16 @@ class SplitSettings:
return self.part0_layers == "auto"
@property
- def guard_mode(self) -> str:
- return (self.oom_guard or "auto").strip().lower()
+ def guard_mode(self) -> str | None:
+ """CLI mode only; ``None`` lets GuardPolicy read KYOJIN_OOM_GUARD."""
+ return self.oom_guard.strip().lower() if self.oom_guard else None
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} oom_guard={self.guard_mode}")
+ f"graphs={self.split_graphs} oom_guard={self.guard_mode or 'auto/env'}")
def add_split_arguments(parser: argparse.ArgumentParser) -> None:
@@ -155,7 +156,7 @@ def settings_from_namespace(args) -> SplitSettings:
part0_reserve_gb = float(reserve),
preset = (preset or "auto").strip().lower(),
split_graphs = graphs,
- oom_guard = getattr(args, "oom_guard", None) or os.environ.get("KYOJIN_OOM_GUARD"),
+ oom_guard = getattr(args, "oom_guard", None),
)
diff --git a/tests/test_memory_guard_cpu.py b/tests/test_memory_guard_cpu.py
index 0ec34ed..83d3ca1 100644
--- a/tests/test_memory_guard_cpu.py
+++ b/tests/test_memory_guard_cpu.py
@@ -13,6 +13,8 @@ from types import SimpleNamespace
import pytest
ROOT = Path(__file__).resolve().parents[1]
+if str(ROOT / "exllamav3") not in sys.path:
+ sys.path.insert(0, str(ROOT / "exllamav3"))
GIB = 1024 ** 3
@@ -55,9 +57,13 @@ def _guard(mg, mode="auto", host_floor=7.0, margin=1.0, workspace=2.0):
def test_policy_env_defaults_and_overrides(mg, monkeypatch):
- for key in ("KYOJIN_OOM_GUARD", "KYOJIN_OOM_GUARD_HOST_FREE_GIB",
+ for key in ("KYOJIN_OOM_GUARD", "MEMGUARD_FLOOR",
"KYOJIN_OOM_GUARD_PREFLIGHT_MARGIN_GIB", "KYOJIN_OOM_GUARD_WORKSPACE_GIB"):
monkeypatch.delenv(key, raising=False)
+ monkeypatch.delenv("MEMGUARD_FLOOR", raising=False)
+ policy = mg.GuardPolicy.from_env()
+ assert policy.host_floor_gib == 8.0
+ monkeypatch.setenv("MEMGUARD_FLOOR", "7")
policy = mg.GuardPolicy.from_env()
assert policy.mode == "auto"
assert policy.host_floor_gib == 7.0
@@ -65,7 +71,7 @@ def test_policy_env_defaults_and_overrides(mg, monkeypatch):
assert policy.workspace_gib == 2.0
monkeypatch.setenv("KYOJIN_OOM_GUARD", "OFF")
- monkeypatch.setenv("KYOJIN_OOM_GUARD_HOST_FREE_GIB", "9.5")
+ monkeypatch.setenv("MEMGUARD_FLOOR", "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()
@@ -74,6 +80,11 @@ def test_policy_env_defaults_and_overrides(mg, monkeypatch):
assert policy.preflight_host_floor_gib == 10.0
assert policy.workspace_gib == 3.0
+ # An explicit flag wins over the environment.
+ monkeypatch.setenv("KYOJIN_OOM_GUARD", "auto")
+ policy = mg.GuardPolicy.from_env(explicit_mode="off")
+ assert policy.mode == "off"
+
def test_device_capacity_is_free_or_total_not_a_reserve(mg):
fp = _footprint(mg, total_bytes=118 * GIB, free_bytes=110 * GIB,
@@ -149,9 +160,7 @@ def test_unified_detection_does_not_flag_a_large_dedicated_gpu(mg, monkeypatch):
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
+ monkeypatch.delenv("MEMGUARD_FLOOR", raising=False)
+ assert guard_mod.host_floor_from_env() == 8.0
+ monkeypatch.setenv("MEMGUARD_FLOOR", "9.5")
+ assert guard_mod.host_floor_from_env() == 9.5
diff --git a/tests/test_split_plan_cpu.py b/tests/test_split_plan_cpu.py
index 08bfa70..d2a4e56 100644
--- a/tests/test_split_plan_cpu.py
+++ b/tests/test_split_plan_cpu.py
@@ -148,7 +148,8 @@ def _disable_default_oom_guard(split_modules, monkeypatch):
"""
dm = split_modules[0]
monkeypatch.setattr(dm.GuardPolicy, "from_env",
- classmethod(lambda cls, default_mode = "auto": cls(mode = "off")))
+ classmethod(lambda cls, default_mode = "auto", explicit_mode = None:
+ cls(mode = explicit_mode or "off")))
@pytest.fixture
@@ -787,3 +788,26 @@ 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_mode == "off"
+
+
+def test_single_device_guard_includes_extra_components(split_modules, monkeypatch):
+ dm, _bridge, _split = split_modules
+ mg = __import__("exllamav3.memory_guard", fromlist = ["OOMGuardError"])
+ gib = dm.GIB
+ monkeypatch.setattr(dm.torch.cuda, "is_available", lambda: True)
+ 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)
+ monkeypatch.setattr(mg, "is_unified_device", lambda *_a, **_k: True)
+
+ target = FakeModel([FakeModule("layer.0", layer_idx = 0)])
+ target_cfg = FakeConfig({"layer.0": 1 * gib})
+ extra = FakeModel([FakeModule("mtp.0")])
+ extra_cfg = FakeConfig({"mtp.0": 116 * gib})
+
+ dm.check_single_device_guard(target, target_cfg, None, 0, guard_mode = "auto",
+ logger = lambda *_a: None)
+ with pytest.raises(mg.OOMGuardError, match = "refused the load"):
+ dm.check_single_device_guard(target, target_cfg, None, 0, guard_mode = "auto",
+ extra_components = [(extra, extra_cfg, None)],
+ logger = lambda *_a: None)
diff --git a/tools/glm/serve.py b/tools/glm/serve.py
index a78d85f..b76e89c 100644
--- a/tools/glm/serve.py
+++ b/tools/glm/serve.py
@@ -844,8 +844,14 @@ class ResidentEngine:
callback=startup_health.load_callback(), max_chunk_size=4096)
else:
from exllamav3.device_map import check_single_device_guard
+ extras = []
+ if draft_model is not None:
+ extras.append((draft_model, self.config, draft_cache))
+ if vision_tower is not None:
+ extras.append((vision_tower, self.config, None))
check_single_device_guard(self.model, self.config, self.cache, "cuda:0",
guard_mode=split_settings.guard_mode,
+ extra_components=extras,
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:
diff --git a/tools/glm/serve_lane.sh b/tools/glm/serve_lane.sh
index bb49338..122134a 100755
--- a/tools/glm/serve_lane.sh
+++ b/tools/glm/serve_lane.sh
@@ -7,7 +7,7 @@ export EXL3_ROOT="$LANE_ROOT" EXL3_REPO="$LANE_ROOT" PYTHONPATH="$LANE_ROOT" TMP
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.
+# auto = arm on Linux when /proc/meminfo is readable (the previous memguard behavior).
MEMGUARD="${MEMGUARD:-auto}"
MODEL=""
args=("$@")
@@ -20,15 +20,10 @@ done
use_mg=0
case "$MEMGUARD" in
1) use_mg=1 ;;
+ 0) ;;
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
+ if [ -r /proc/meminfo ]; then use_mg=1; fi
;;
- 0) ;;
esac
MG=()
if [ "$use_mg" = "1" ] && [ -f "$LANE_ROOT/exllamav3/guard.py" ]; then
@@ -36,7 +31,7 @@ if [ "$use_mg" = "1" ] && [ -f "$LANE_ROOT/exllamav3/guard.py" ]; then
--log "$TMPDIR/memguard.log" --sample-every 5 --fadvise-every 5)
[ -n "$MODEL" ] && [ -d "$MODEL" ] && MG+=(--fadvise-dir "$MODEL")
MG+=(--)
- echo "serve_lane: MEMGUARD=on (host floor ${KYOJIN_OOM_GUARD_HOST_FREE_GIB:-7} GiB, log $TMPDIR/memguard.log)" >&2
+ echo "serve_lane: MEMGUARD=on (host floor MEMGUARD_FLOOR/default, 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 ceca277..bdb8f19 100755
--- a/tools/mimo/serve_lane.sh
+++ b/tools/mimo/serve_lane.sh
@@ -19,13 +19,9 @@ done
use_mg=0
case "$MEMGUARD" in
1) use_mg=1 ;;
+ 0) ;;
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
+ if [ -r /proc/meminfo ]; then use_mg=1; fi
;;
esac
MG=()
@@ -34,7 +30,7 @@ if [ "$use_mg" = "1" ] && [ -f "$LANE_ROOT/exllamav3/guard.py" ]; then
--log "$TMPDIR/memguard.log" --sample-every 5 --fadvise-every 5)
[ -n "$MODEL" ] && [ -d "$MODEL" ] && MG+=(--fadvise-dir "$MODEL")
MG+=(--)
- echo "serve_lane: MEMGUARD=on (host floor ${KYOJIN_OOM_GUARD_HOST_FREE_GIB:-7} GiB, log $TMPDIR/memguard.log)" >&2
+ echo "serve_lane: MEMGUARD=on (host floor MEMGUARD_FLOOR/default, log $TMPDIR/memguard.log)" >&2
elif [ "$MEMGUARD" = "1" ]; then
echo "serve_lane: MEMGUARD=1 requested but exllamav3/guard.py is missing" >&2
exit 1