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.

device_copy: propagate device OOM instead of caching a bounce verdict

Resynthe3415ff9133c
diff --git a/exllamav3/util/device_copy.py b/exllamav3/util/device_copy.py
index f3f928f..7f4ffee 100644
--- a/exllamav3/util/device_copy.py
+++ b/exllamav3/util/device_copy.py
@@ -22,7 +22,9 @@ whether the copy can go direct or has to bounce through host memory:
Both directions of a pair are probed together, since the fabric can fail one way only.
A probe that raises (some drivers reject the peer copy instead of corrupting) counts as
a failed verdict and the pair bounces through host memory. A later direct-copy failure
-also caches the bounce verdict and retries through the host.
+also caches the bounce verdict and retries through the host. A device OOM is re-raised
+from both the probe and the direct copy: bouncing through host memory would not help an
+exhausted device, so no verdict is cached for it.
"""
_env = os.environ.get("EXLLAMA_NO_P2P_COPY")
@@ -39,7 +41,8 @@ def _probe_direct(src: torch.device, dst: torch.device) -> tuple[bool, bool]:
A probe is diagnostic. Some drivers raise instead of silently corrupting when the
peer path is broken; treat any probe failure as "bounce" rather than letting the
- diagnostic turn the first real cross-device move into a crash.
+ diagnostic turn the first real cross-device move into a crash. A device OOM is
+ re-raised (and caches no verdict): bouncing cannot help an exhausted device.
"""
try:
a = torch.rand(64, dtype = torch.float32, device = src)
@@ -51,6 +54,8 @@ def _probe_direct(src: torch.device, dst: torch.device) -> tuple[bool, bool]:
fwd_ok = torch.equal(a_h, b.cpu())
bwd_ok = fwd_ok and torch.equal(a_h, c.cpu())
return fwd_ok, bwd_ok
+ except (torch.OutOfMemoryError, torch.cuda.OutOfMemoryError):
+ raise # let a real OOM surface, do not cache a verdict
except Exception as exc: # noqa: BLE001 - diagnostic must not crash
print(f" !! P2P probe between {src} and {dst} failed "
f"({type(exc).__name__}: {exc}); routing through system memory "
@@ -104,6 +109,8 @@ def to_device(t: torch.Tensor, device: torch.device | str | int, non_blocking: b
return t.cpu().to(device)
try:
out = t.to(device, non_blocking = non_blocking)
+ except (torch.OutOfMemoryError, torch.cuda.OutOfMemoryError):
+ raise # device OOM is not a fabric fault
except RuntimeError as exc:
# A probe can pass and a later direct copy can still fail on a flaky link.
# Cache the safe verdict and retry through host memory.
diff --git a/tests/test_device_copy_oom_cpu.py b/tests/test_device_copy_oom_cpu.py
new file mode 100644
index 0000000..ba5c52d
--- /dev/null
+++ b/tests/test_device_copy_oom_cpu.py
@@ -0,0 +1,87 @@
+"""CPU contract tests for util/device_copy.to_device's out-of-memory handling.
+
+A device OOM must be re-raised (and cache no bounce verdict), not mistaken for a
+broken P2P fabric: bouncing through host memory would not help an exhausted device,
+so a cached verdict would be wrong and would stick for the process lifetime.
+Runs without a GPU or the built extension.
+"""
+from __future__ import annotations
+
+import sys
+import types
+from pathlib import Path
+
+import pytest
+import torch
+
+ROOT = Path(__file__).resolve().parents[1]
+
+
[email protected](scope = "module")
+def dc():
+ added = []
+ if "exllamav3" not in sys.modules:
+ pkg = types.ModuleType("exllamav3")
+ pkg.__path__ = [str(ROOT / "exllamav3")]
+ sys.modules["exllamav3"] = pkg
+ added.append("exllamav3")
+ if "exllamav3.util" not in sys.modules:
+ util = types.ModuleType("exllamav3.util")
+ util.__path__ = [str(ROOT / "exllamav3" / "util")]
+ sys.modules["exllamav3.util"] = util
+ added.append("exllamav3.util")
+ from exllamav3.util import device_copy as dc
+
+ yield dc
+
+ sys.modules.pop("exllamav3.util.device_copy", None)
+ for name in added:
+ sys.modules.pop(name, None)
+
+
+def clean(dc):
+ old_forced = dc.FORCED
+ dc.reset_verdicts()
+ for k in dc.stats:
+ dc.stats[k] = 0
+ yield
+ dc.FORCED = old_forced
+ dc.reset_verdicts()
+
+
+def test_direct_copy_oom_re_raises_no_verdict(dc, clean):
+ dc.FORCED = False
+
+ class _OOMTensor:
+ device = torch.device("cuda", 0)
+
+ def to(self, _device, non_blocking = False):
+ raise torch.OutOfMemoryError("CUDA out of memory")
+
+ with pytest.raises(torch.OutOfMemoryError):
+ dc.to_device(_OOMTensor(), torch.device("cuda", 1))
+
+ assert dc._verdicts == {}
+ assert dc.stats["probes"] == 0
+ assert dc.stats["bounced"] == 0
+ assert dc.stats["direct"] == 0
+
+
+def test_probe_oom_re_raises_no_verdict(dc, clean, monkeypatch):
+ dc.FORCED = None
+
+ class _Src:
+ device = torch.device("cuda", 0)
+
+ def _oom_rand(*_args, **_kwargs):
+ raise torch.OutOfMemoryError("CUDA out of memory")
+
+ monkeypatch.setattr(dc.torch, "rand", _oom_rand)
+ with pytest.raises(torch.OutOfMemoryError):
+ dc.to_device(_Src(), torch.device("cuda", 1))
+
+ # needs_bounce bumps `probes` before the probe runs; the raise happens inside it,
+ # before any verdict is stored.
+ assert dc._verdicts == {}
+ assert dc.stats["probes"] == 1
\ No newline at end of file