Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

fix(rocm): make the offload, the budget lookup and the ROCm checks hold up

Alexander Eichhorn39baf58bfd75
diff --git a/invokeai/app/util/torch_cuda_allocator.py b/invokeai/app/util/torch_cuda_allocator.py
index a6f1d30fbf..7e94be5790 100644
--- a/invokeai/app/util/torch_cuda_allocator.py
+++ b/invokeai/app/util/torch_cuda_allocator.py
@@ -1,7 +1,10 @@
import importlib.metadata
+import importlib.util
import logging
import os
+import re
import sys
+from pathlib import Path
# Every variable torch reads its caching-allocator configuration from. `ModelCache._expandable_segments_enabled` keeps
# its own copy of this list: the model cache imports torch, and this module must not.
@@ -18,6 +21,33 @@ def _installed_torch_version() -> str | None:
return None
+def _installed_torch_is_rocm() -> bool:
+ """Whether the installed torch is a ROCm build, without importing torch.
+
+ AMD's published wheels carry `+rocm` in the distribution version, but a wheel built locally is versioned like
+ `2.8.0a0+gitfc14c65`. Both record a `hip` version in torch's own `version.py`, which is read as a file -- the same
+ value `torch.version.hip` returns, which is what `invokeai.backend.util.wddm` gates on. Keeping the two answers
+ together matters: a build that gets the video-memory budget but not this allocator default fragments its way into
+ system memory with nothing in the log to say why.
+ """
+ version = _installed_torch_version()
+ if version is not None and "+rocm" in version:
+ return True
+ try:
+ spec = importlib.util.find_spec("torch") # locates the package; does not execute it
+ locations = list(spec.submodule_search_locations or []) if spec is not None else []
+ for location in locations:
+ source = Path(location, "version.py")
+ if source.is_file():
+ return (
+ re.search(r"^hip\s*(?::[^=]+)?=\s*['\"]", source.read_text(encoding="utf-8"), re.MULTILINE)
+ is not None
+ )
+ except Exception:
+ return False
+ return False
+
+
def apply_rocm_windows_allocator_default(logger: logging.Logger) -> None:
"""Default a ROCm build on Windows to the expandable-segments allocator, unless the allocator is configured already.
@@ -33,8 +63,7 @@ def apply_rocm_windows_allocator_default(logger: logging.Logger) -> None:
"""
if sys.platform != "win32" or any(os.environ.get(var) for var in _ALLOCATOR_CONF_ENV_VARS):
return
- torch_version = _installed_torch_version()
- if torch_version is None or "+rocm" not in torch_version:
+ if not _installed_torch_is_rocm():
return
if "torch" in sys.modules:
# Setting the variable now would change nothing but the model cache's reading of it.
diff --git a/invokeai/backend/model_manager/load/model_cache/model_cache.py b/invokeai/backend/model_manager/load/model_cache/model_cache.py
index eea4522cfe..fa049ef659 100644
--- a/invokeai/backend/model_manager/load/model_cache/model_cache.py
+++ b/invokeai/backend/model_manager/load/model_cache/model_cache.py
@@ -2342,9 +2342,11 @@ class ModelCache:
Best-effort: 0 when the backend does not expose allocator stats, and 0 under
expandable-segments mode — there, freed blocks inside a segment are NOT counted as
- inactive splits, empty_cache() reclaims nothing, and a large allocation cannot use the
- holes, so the whole (reserved - allocated) figure is untrustworthy (a measured hard OOM
- on an allocation the credited budget claimed would fit).
+ inactive splits and a large allocation cannot use the holes, so the whole
+ (reserved - allocated) figure is untrustworthy (a measured hard OOM on an allocation the
+ credited budget claimed would fit). empty_cache() does unmap the freed pages, which is why
+ `_offload_unlocked_models` runs one after each offload in that mode; what it cannot do is
+ make the credit trustworthy before it runs.
"""
if _expandable_segments_enabled():
return 0
@@ -2554,13 +2556,16 @@ class ModelCache:
vram_bytes_freed = 0
# Under expandable segments the measurement credits no allocator-held blocks, so an offload
# only shows up once empty_cache() unmaps its pages; without it every unlocked model would
- # be unloaded by the full shortfall.
+ # be unloaded by the full shortfall. When a peer device is mid-session that release is
+ # deferred, and the bytes just freed are credited to the measurement instead -- they sit in
+ # this process's allocator, which reuses them for the load this is making room for.
empty_cache_per_offload = _expandable_segments_enabled()
+ vram_bytes_freed_uncounted = 0
# TODO(ryand): Give more thought to the offloading policy used here.
cache_entries_increasing_size = sorted(self._cached_models.values(), key=lambda x: x.cached_model.total_bytes())
for cache_entry in cache_entries_increasing_size:
# We do not fully trust the count of bytes freed, so we check again on each iteration.
- vram_available = vram_available_fn()
+ vram_available = vram_available_fn() + vram_bytes_freed_uncounted
vram_bytes_to_free = vram_bytes_required - vram_available
if vram_bytes_to_free <= 0:
break
@@ -2574,7 +2579,10 @@ class ModelCache:
f"Unloaded {cache_entry.key} from VRAM to free {(cache_entry_bytes_freed / MB):.0f} MB."
)
if empty_cache_per_offload:
- TorchDevice.empty_cache()
+ if TorchDevice.empty_cache():
+ vram_bytes_freed_uncounted = 0
+ else:
+ vram_bytes_freed_uncounted += cache_entry_bytes_freed
vram_bytes_freed += cache_entry_bytes_freed
# Only pay for empty_cache() when something was actually offloaded. Paced VRAM moves run
diff --git a/invokeai/backend/util/attention.py b/invokeai/backend/util/attention.py
index d98f558b90..35b1f048c2 100644
--- a/invokeai/backend/util/attention.py
+++ b/invokeai/backend/util/attention.py
@@ -132,8 +132,8 @@ _ROCM_SDPA_GUARD_SENTINEL = "_invokeai_rocm_sdpa_guard"
# (`_chunked_sdpa`). Where no fused kernel exists -- ROCm on Windows has none, measured on an RX 9060 XT with torch
# 2.12+rocm7.14 -- an unchunked call costs heads x seq^2 x ~12-17 bytes: 8 GiB for Z-Image at 1024px, 12.9 GiB for
# Krea-2, 40 GiB for Z-Image at 1536px, against a 16 GB card. Measured per call at 1 GiB, against unchunked: Z-Image
-# shape +8 % time, bitwise identical output; FLUX VAE mid-block (one 512-wide head, 1024px) +12 %, within one bf16
-# ulp. Read at call time, so tests can lower it.
+# shape +8 % time, FLUX VAE mid-block (one 512-wide head, 1024px) +12 %; both within one bf16 ulp of the unchunked
+# result. Read at call time, so tests can lower it.
SDPA_MATH_CHUNK_BYTES = 1 << 30
@@ -228,12 +228,14 @@ def _chunked_sdpa(
) -> torch.Tensor:
"""Run a 4-D `(batch, heads, seq, dim)` attention as calls whose score matrices stay within `SDPA_MATH_CHUNK_BYTES`.
- Softmax normalizes each query row over all keys, so splitting heads or query rows is exact. Head groups come
- first: every call keeps its full `query x key` shape, so the result is bitwise the unchunked one. Query rows are
- split only when a single head (or GQA group) alone exceeds the budget -- the one-head VAE mid-block -- or when K/V
- are broadcast across heads rather than grouped; there the GEMM tiling changes by up to one bf16 ulp. A mask is
- sliced along the axis being split wherever it is not broadcast there. The output is allocated from the first
- chunk's result, which carries the dtype autocast chose.
+ Softmax normalizes each query row over all keys, so splitting heads or query rows is exact in exact arithmetic,
+ and both orders agree to within one bf16 ulp in practice. Head groups come first: every call keeps its full
+ `query x key` shape, which is bitwise the unchunked result wherever the kernel's arithmetic does not depend on
+ the batch it runs over (it does on CPU; a rocBLAS batched GEMM re-tiles when 30 head-batches become groups of 2,
+ measured at 0.0005 on a bf16 Z-Image shape). Query rows are split only when a single head (or GQA group) alone
+ exceeds the budget -- the one-head VAE mid-block -- or when K/V are broadcast across heads rather than grouped. A
+ mask is sliced along the axis being split wherever it is not broadcast there. The output is allocated from the
+ first chunk's result, which carries the dtype autocast chose.
"""
budget = SDPA_MATH_CHUNK_BYTES
batch, heads, query_len, _ = query.shape
@@ -521,7 +523,10 @@ def sdpa_score_matrix_bytes(
the model is loaded and outside any `attention_backend()` scope.
Where the ROCm guard computes math attention in chunks (`rocm_sdpa_chunks_math`), one chunk is
- what is alive at a time, so the term is capped at ``SDPA_MATH_CHUNK_BYTES``.
+ what is alive at a time, so the term is capped at ``SDPA_MATH_CHUNK_BYTES``. That cap assumes the
+ call is one the guard will chunk: a plain 4-D, non-causal, dropout-free call with K/V of the
+ query's batch, which is what every caller here prices. A causal or dropout call, or one with
+ broadcast K/V, runs whole and would need the full figure.
"""
if seq_len <= 0 or num_heads <= 0:
return 0
diff --git a/invokeai/backend/util/devices.py b/invokeai/backend/util/devices.py
index 93de46aa4b..ff68067eb8 100644
--- a/invokeai/backend/util/devices.py
+++ b/invokeai/backend/util/devices.py
@@ -334,8 +334,8 @@ class TorchDevice:
return device
@classmethod
- def empty_cache(cls) -> None:
- """Clear the GPU device cache — unless another generation device is mid-session.
+ def empty_cache(cls) -> bool:
+ """Clear the GPU device cache — unless another generation device is mid-session. Says whether it ran.
``torch.cuda.empty_cache()`` is process-global: it takes EVERY device's
caching-allocator mutex and cudaFree/hipFrees their cached blocks, and a free on a
@@ -367,7 +367,7 @@ class TorchDevice:
InvokeAILogger.get_logger(cls.__name__).debug(
"Deferring empty_cache: another generation device is mid-session."
)
- return
+ return False
# Clear before running: a skip that races in after this point re-sets the flag, so a
# request is never lost, only (harmlessly) repeated.
cls._empty_cache_deferred.clear()
@@ -377,6 +377,7 @@ class TorchDevice:
torch.cuda.empty_cache()
if _xpu_is_available():
torch.xpu.empty_cache()
+ return True
@classmethod
def flush_deferred_empty_cache(cls) -> None:
diff --git a/invokeai/backend/util/wddm.py b/invokeai/backend/util/wddm.py
index be9c37859d..fc042211cd 100644
--- a/invokeai/backend/util/wddm.py
+++ b/invokeai/backend/util/wddm.py
@@ -220,21 +220,27 @@ def _resolve_adapter(lib: ctypes.CDLL, index: int) -> Optional[_Adapter]:
return None
matches: list[_AdapterInfo] = []
- for info in infos[: enum.NumAdapters]:
- address = _AdapterAddress()
- query = _QueryAdapterInfo(
- info.hAdapter,
- _KMTQAITYPE_ADAPTERADDRESS,
- ctypes.cast(ctypes.byref(address), ctypes.c_void_p),
- ctypes.sizeof(address),
- )
- if (
- lib.D3DKMTQueryAdapterInfo(ctypes.byref(query)) == 0
- and (address.BusNumber, address.DeviceNumber) == location
- ):
- matches.append(info)
- else:
+ try:
+ for info in infos[: enum.NumAdapters]:
+ address = _AdapterAddress()
+ query = _QueryAdapterInfo(
+ info.hAdapter,
+ _KMTQAITYPE_ADAPTERADDRESS,
+ ctypes.cast(ctypes.byref(address), ctypes.c_void_p),
+ ctypes.sizeof(address),
+ )
+ if (
+ lib.D3DKMTQueryAdapterInfo(ctypes.byref(query)) == 0
+ and (address.BusNumber, address.DeviceNumber) == location
+ ):
+ matches.append(info)
+ else:
+ _close(lib, info.hAdapter)
+ except Exception:
+ # Every handle opened by the enumeration belongs to this process until it is closed.
+ for info in matches:
_close(lib, info.hAdapter)
+ raise
if len(matches) != 1:
for info in matches:
@@ -266,23 +272,25 @@ def _adapter_for(device: torch.device) -> Optional[tuple[ctypes.CDLL, _Adapter]]
def video_memory_budget(device: torch.device) -> Optional[int]:
"""This process's WDDM budget on the device's adapter, in bytes: what Windows keeps resident before paging.
- ``None`` off Windows ROCm, and whenever the driver cannot answer or answers something implausible.
+ ``None`` off Windows ROCm, and whenever the driver cannot answer or answers something implausible. It is called
+ per generation and per decode, so every failure answers "unknown" here rather than reaching those callers.
"""
if not _supported(device):
return None
- resolved = _adapter_for(device)
- if resolved is None:
- return None
- lib, adapter = resolved
- info = _QueryVideoMemoryInfo(None, adapter.handle, _MEMORY_SEGMENT_GROUP_LOCAL)
try:
+ resolved = _adapter_for(device)
+ if resolved is None:
+ return None
+ lib, adapter = resolved
+ info = _QueryVideoMemoryInfo(None, adapter.handle, _MEMORY_SEGMENT_GROUP_LOCAL)
if lib.D3DKMTQueryVideoMemoryInfo(ctypes.byref(info)) != 0:
return None
+ if not 0 < info.Budget <= adapter.total_bytes:
+ return None
+ return int(info.Budget)
except Exception:
+ InvokeAILogger.get_logger(__name__).debug(f"WDDM budget lookup for {device} failed", exc_info=True)
return None
- if not 0 < info.Budget <= adapter.total_bytes:
- return None
- return int(info.Budget)
def _open_shared_usage_query(pdh: ctypes.CDLL) -> Optional[tuple[ctypes.c_void_p, ctypes.c_void_p]]:
@@ -332,12 +340,12 @@ def paged_bytes(device: torch.device) -> Optional[int]:
luid = resolved[1].luid
instance = f"pid_{os.getpid()}_luid_0x{(luid >> 32) & 0xFFFFFFFF:08x}_0x{luid & 0xFFFFFFFF:08x}_phys_0"
with _pdh_lock:
- if not _pdh_attempted:
- _pdh_attempted = True
- _pdh_query = _open_shared_usage_query(pdh)
- if _pdh_query is None:
- return None
try:
+ if not _pdh_attempted:
+ _pdh_attempted = True
+ _pdh_query = _open_shared_usage_query(pdh)
+ if _pdh_query is None:
+ return None
return _shared_usage_by_instance(pdh, *_pdh_query).get(instance)
except Exception:
return None
diff --git a/invokeai/backend/wan/rocm_causal_conv3d.py b/invokeai/backend/wan/rocm_causal_conv3d.py
index 7d9499431f..8280c82578 100644
--- a/invokeai/backend/wan/rocm_causal_conv3d.py
+++ b/invokeai/backend/wan/rocm_causal_conv3d.py
@@ -140,7 +140,7 @@ def patch_wan_causal_conv3d_for_rocm() -> None:
implicit-GEMM conv3d kernels, so CUDA builds keep the stock path. There is
deliberately no HIP-version gate (see the module docstring). The row tearing once
blamed on this decomposition on HIP 7.2 has two known causes, both since fixed: the
- ROCm fused-SDPA head-dim defect (``install_rocm_sdpa_head_dim_guard`` in
+ ROCm fused-SDPA head-dim defect (``install_rocm_sdpa_guard`` in
``invokeai.backend.util.attention``; the Wan VAE mid-block attention is wider than its
threshold) and MIOpen faulting on the strided views the decomposition used to hand it
(see ``_decomposed_conv3d``). With both in place the decomposition matches native
diff --git a/tests/app/util/test_torch_cuda_allocator.py b/tests/app/util/test_torch_cuda_allocator.py
index 3e2ddf8715..a226f889d4 100644
--- a/tests/app/util/test_torch_cuda_allocator.py
+++ b/tests/app/util/test_torch_cuda_allocator.py
@@ -1,5 +1,6 @@
import os
import sys
+from types import SimpleNamespace
from unittest.mock import MagicMock
import pytest
@@ -72,6 +73,39 @@ class TestRocmWindowsAllocatorDefault:
logger.warning.assert_called_once()
+class TestRocmBuildDetection:
+ """A locally built Windows ROCm wheel is versioned like `2.8.0a0+gitfc14c65`, so the distribution version alone
+ would leave it on the default allocator while `wddm` (which reads `torch.version.hip`) still caps its budget."""
+
+ @pytest.mark.parametrize(
+ ("hip_line", "expected"),
+ [("hip: Optional[str] = '7.14.60850'", True), ("hip: Optional[str] = None", False)],
+ ids=["rocm-build", "cuda-build"],
+ )
+ def test_a_build_without_rocm_in_its_version_is_read_from_torchs_version_file(
+ self, monkeypatch, tmp_path, hip_line, expected
+ ):
+ package = tmp_path / "torch"
+ package.mkdir()
+ (package / "version.py").write_text(f"__version__ = '2.8.0a0+gitfc14c65'\n{hip_line}\n", encoding="utf-8")
+ monkeypatch.setattr(torch_cuda_allocator, "_installed_torch_version", lambda: "2.8.0a0+gitfc14c65")
+ monkeypatch.setattr(
+ torch_cuda_allocator.importlib.util,
+ "find_spec",
+ lambda name: SimpleNamespace(submodule_search_locations=[str(package)]),
+ )
+
+ assert torch_cuda_allocator._installed_torch_is_rocm() is expected
+
+ def test_an_unreadable_installation_is_not_rocm(self, monkeypatch):
+ monkeypatch.setattr(torch_cuda_allocator, "_installed_torch_version", lambda: "2.8.0a0+gitfc14c65")
+ monkeypatch.setattr(
+ torch_cuda_allocator.importlib.util, "find_spec", MagicMock(side_effect=ValueError("no spec"))
+ )
+
+ assert torch_cuda_allocator._installed_torch_is_rocm() is False
+
+
# These tests are a bit fiddly, because the depend on the import behaviour of torch. They use subprocesses to isolate
# the import behaviour of torch, and then check that the function behaves as expected. We have to hack in some logging
# to check that the tested function is behaving as expected.
diff --git a/tests/backend/model_manager/load/model_cache/test_model_cache_vram_accounting.py b/tests/backend/model_manager/load/model_cache/test_model_cache_vram_accounting.py
index 933d539c9b..b7f3023b8c 100644
--- a/tests/backend/model_manager/load/model_cache/test_model_cache_vram_accounting.py
+++ b/tests/backend/model_manager/load/model_cache/test_model_cache_vram_accounting.py
@@ -214,9 +214,13 @@ def test_the_windows_video_memory_budget_caps_the_measured_free_vram(monkeypatch
assert cache._get_vram_available(None) == 6 * GB
-def test_offloading_under_expandable_segments_stops_once_enough_is_free(monkeypatch: pytest.MonkeyPatch):
[email protected]("peer_busy", [False, True], ids=["alone", "peer-device-busy"])
+def test_offloading_under_expandable_segments_stops_once_enough_is_free(monkeypatch: pytest.MonkeyPatch, peer_busy):
"""Under expandable segments the driver sees an offloaded model's pages only after empty_cache(), and no
- allocator credit stands in for them. Re-measuring without it saw no progress and unloaded every unlocked model."""
+ allocator credit stands in for them. Re-measuring without it saw no progress and unloaded every unlocked model.
+
+ `empty_cache` is peer-aware: while another generation device is mid-session it defers instead of releasing, so
+ the measurement cannot see the offload at all and the freed bytes are credited to it directly."""
cache = ModelCache(
execution_device_working_mem_gb=1.0,
enable_partial_loading=True,
@@ -234,9 +238,12 @@ def test_offloading_under_expandable_segments_stops_once_enough_is_free(monkeypa
device["unmappable"] += 4 * GB
return 4 * GB
- def empty_cache():
+ def empty_cache() -> bool:
+ if peer_busy: # deferred: nothing is released, and the driver keeps reporting the old figure
+ return False
device["free"] += device["unmappable"]
device["unmappable"] = 0
+ return True
monkeypatch.setenv("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
monkeypatch.setattr(torch.cuda, "mem_get_info", lambda d: (device["free"], 16 * GB))
diff --git a/tests/backend/util/test_rocm_sdpa_head_dim_guard.py b/tests/backend/util/test_rocm_sdpa_head_dim_guard.py
index d02979d014..79c3e92015 100644
--- a/tests/backend/util/test_rocm_sdpa_head_dim_guard.py
+++ b/tests/backend/util/test_rocm_sdpa_head_dim_guard.py
@@ -201,7 +201,9 @@ def _scores(shape_pair: tuple[torch.Size, torch.Size]) -> int:
class TestChunking:
"""Math-kernel attention over the budget runs in chunks; every chunk stays within it, together they are exact."""
- def test_heads_are_split_first_and_the_result_is_bitwise_unchunked(self, monkeypatch):
+ def test_heads_are_split_first_and_the_result_matches_the_unchunked_call(self, monkeypatch):
+ """Bitwise here because the CPU kernel's arithmetic does not depend on the batch it runs over; on a ROCm
+ card the batched GEMM re-tiles with the group count and lands within a bf16 ulp instead."""
per_head = 64 * 48 * BYTES
shapes = _install_chunking(monkeypatch, budget=2 * per_head)
torch.manual_seed(0)