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.

feat(rocm): warn when Windows keeps VRAM in system memory

Alexander Eichhorn0d0f708636da
diff --git a/docs/src/content/docs/configuration/low-vram-mode.mdx b/docs/src/content/docs/configuration/low-vram-mode.mdx
index abe6e0d2b2..2d31c70e88 100644
--- a/docs/src/content/docs/configuration/low-vram-mode.mdx
+++ b/docs/src/content/docs/configuration/low-vram-mode.mdx
@@ -204,6 +204,14 @@ It is strongly suggested to disable this feature:
Unfortunately, the Nvidia implementation is not optimized for applications like Invoke and does more harm than good.
:::
+### AMD GPUs on Windows (ROCm)
+
+Invoke does not officially support ROCm on Windows (see the [System Requirements](../../start-here/system-requirements)). If you run a ROCm build of PyTorch there anyway, Windows behaves as if the Nvidia sysmem fallback were always on: an allocation that does not fit is moved into much slower system memory instead of failing, and it stays there. Task Manager shows it as shared GPU memory. Invoke works around this where it can:
+
+- The model cache plans against the video-memory budget Windows grants Invoke, not against the card's total VRAM.
+- The PyTorch allocator defaults to `expandable_segments:True` (see [PyTorch CUDA allocator config](#pytorch-cuda-allocator-config)), so fragmented VRAM does not force allocations out.
+- When a generation ends with part of Invoke's GPU memory in system memory, the log says so. Other programs using the same GPU, like games or browsers, can push Invoke's memory out as well. Close them, or restart Invoke to get the memory back into VRAM.
+
## Troubleshooting
### Windows page file
diff --git a/invokeai/app/services/session_processor/session_processor_default.py b/invokeai/app/services/session_processor/session_processor_default.py
index affefc84d6..6580e2e19c 100644
--- a/invokeai/app/services/session_processor/session_processor_default.py
+++ b/invokeai/app/services/session_processor/session_processor_default.py
@@ -43,6 +43,11 @@ from invokeai.app.services.shared.invocation_context import InvocationContextDat
from invokeai.app.util.profiler import Profiler
from invokeai.backend.util.device_pool import GENERATION_DEVICE_POOL
from invokeai.backend.util.devices import TorchDevice, disable_conv_benchmark_empty_cache
+from invokeai.backend.util.wddm import paged_bytes
+
+# Paged-out VRAM worth a warning. Weight uploads page a few hundred MB for an instant (0.25-0.36 GiB measured on an
+# RX 9060 XT), so the threshold sits above that; a session that ends with more than this paged has lost real VRAM.
+_VRAM_PAGING_WARNING_BYTES = 512 * 2**20
# A failed owner lookup is retried before the item is refused, so that a transient error
# — a busy-timeout on the shared SQLite connection under multi-GPU write contention, say —
@@ -554,6 +559,8 @@ class _SessionWorker:
self.cancel_event = ThreadEvent()
self.queue_item: Optional[SessionQueueItem] = None
self.thread: Optional[Thread] = None
+ # Paged-out VRAM at the last warning; only this worker's thread reads or writes it.
+ self.paging_warned_bytes = 0
@property
def label(self) -> str:
@@ -841,6 +848,35 @@ class DefaultSessionProcessor(SessionProcessorBase):
f"Could not release cached VRAM after the session on {worker.label}", exc_info=True
)
+ def _warn_if_vram_paged(self, worker: _SessionWorker) -> None:
+ """Say so when Windows keeps part of this worker's GPU memory in shared system memory after a session.
+
+ On a ROCm build under Windows an allocation that does not fit the video-memory budget, or finds no contiguous
+ VRAM, is placed in system memory instead of failing -- and another program on the same GPU can push this
+ process's memory out the same way. It stays there, and every generation that touches it slows down, with
+ nothing else in the log to explain why. Warns once per episode: again only after it grew by the threshold,
+ and re-armed once it drops below it. Measured after the session's VRAM release, so the transient paging of a
+ weight upload is over. `paged_bytes` answers None everywhere else, which keeps this silent there.
+ """
+ try:
+ paged = paged_bytes(worker.device or TorchDevice.choose_torch_device())
+ except Exception:
+ self._invoker.services.logger.debug(f"Could not read paged VRAM on {worker.label}", exc_info=True)
+ return
+ if paged is None:
+ return
+ if paged < _VRAM_PAGING_WARNING_BYTES:
+ worker.paging_warned_bytes = 0
+ return
+ if paged < worker.paging_warned_bytes + _VRAM_PAGING_WARNING_BYTES:
+ return
+ worker.paging_warned_bytes = paged
+ self._invoker.services.logger.warning(
+ f"Windows is keeping {paged / 2**30:.1f} GiB of Invoke's GPU memory on {worker.label} in shared system "
+ "memory, which makes generations much slower. Close other programs that use this GPU; if it persists, "
+ "restart Invoke to get the memory back into VRAM."
+ )
+
def resume(self) -> SessionProcessorStatus:
if not self._resume_event.is_set():
self._resume_event.set()
@@ -1054,6 +1090,7 @@ class DefaultSessionProcessor(SessionProcessorBase):
finally:
GENERATION_DEVICE_POOL.release_session(worker.device)
self._release_vram_after_session(worker)
+ self._warn_if_vram_paged(worker)
except Exception as e:
error_type = e.__class__.__name__
diff --git a/invokeai/backend/util/wddm.py b/invokeai/backend/util/wddm.py
index 93a6a6dbef..bde1c06989 100644
--- a/invokeai/backend/util/wddm.py
+++ b/invokeai/backend/util/wddm.py
@@ -11,12 +11,16 @@ once the committed local usage passes budget + 0.38 GiB; next to another GPU pro
about a second. ``CurrentUsage`` is the committed usage, including bytes already paged out, so budget minus usage is
what this process can still allocate before paging.
+Whether Windows has actually paged this process out is not visible through D3DKMT (``CurrentUsage`` counts paged bytes
+as local); it is visible in the ``GPU Process Memory`` performance counters Task Manager shows, read here through PDH.
+
Everything here is best-effort: any failure yields ``None`` ("unknown") rather than raising, and callers must keep their
existing behaviour when the answer is unknown.
"""
import ctypes
import functools
+import os
import sys
import threading
from dataclasses import dataclass
@@ -28,6 +32,10 @@ from invokeai.backend.util.logging import InvokeAILogger
_KMTQAITYPE_ADAPTERADDRESS = 6
_MEMORY_SEGMENT_GROUP_LOCAL = 0
+_PDH_FMT_LARGE = 0x00000400
+_PDH_MORE_DATA = 0x800007D2
+# The English counter path; PdhAddEnglishCounterW resolves it on a localized Windows too.
+_PDH_SHARED_USAGE_COUNTER = r"\GPU Process Memory(*)\Shared Usage"
# Win32 types spelled as fixed-width ctypes, so this module imports on every platform.
@@ -96,6 +104,18 @@ class _QueryVideoMemoryInfo(ctypes.Structure):
]
+class _PdhCounterValue(ctypes.Structure):
+ """``PDH_FMT_COUNTERVALUE`` read as ``PDH_FMT_LARGE``."""
+
+ _fields_ = [("CStatus", ctypes.c_uint32), ("largeValue", ctypes.c_int64)]
+
+
+class _PdhCounterValueItem(ctypes.Structure):
+ """``PDH_FMT_COUNTERVALUE_ITEM_W``."""
+
+ _fields_ = [("szName", ctypes.c_wchar_p), ("FmtValue", _PdhCounterValue)]
+
+
_GDI32_FUNCTIONS = (
"D3DKMTEnumAdapters2",
"D3DKMTQueryAdapterInfo",
@@ -107,6 +127,7 @@ _GDI32_FUNCTIONS = (
@dataclass(frozen=True)
class _Adapter:
handle: int
+ luid: int
total_bytes: int
@@ -114,6 +135,11 @@ _lock = threading.Lock()
# Per torch device index: the matching WDDM adapter, or None once resolution has failed.
_adapters: dict[int, Optional[_Adapter]] = {}
+_pdh_lock = threading.Lock()
+# One PDH query over every process's shared usage, as (query, counter), opened on first use; None if that failed.
+_pdh_query: Optional[tuple[ctypes.c_void_p, ctypes.c_void_p]] = None
+_pdh_attempted = False
+
def _supported(device: torch.device) -> bool:
return sys.platform == "win32" and torch.version.hip is not None and device.type == "cuda"
@@ -134,6 +160,39 @@ def _load_gdi32() -> Optional[ctypes.CDLL]:
return lib
[email protected]_cache(maxsize=1)
+def _load_pdh() -> Optional[ctypes.CDLL]:
+ """Open pdh once and declare the few entry points used; every one returns a PDH_STATUS."""
+ try:
+ lib = ctypes.WinDLL("pdh")
+ prototypes = {
+ "PdhOpenQueryW": [ctypes.c_wchar_p, ctypes.c_void_p, ctypes.POINTER(ctypes.c_void_p)],
+ "PdhAddEnglishCounterW": [
+ ctypes.c_void_p,
+ ctypes.c_wchar_p,
+ ctypes.c_void_p,
+ ctypes.POINTER(ctypes.c_void_p),
+ ],
+ "PdhCollectQueryData": [ctypes.c_void_p],
+ "PdhGetFormattedCounterArrayW": [
+ ctypes.c_void_p,
+ ctypes.c_uint32,
+ ctypes.POINTER(ctypes.c_uint32),
+ ctypes.POINTER(ctypes.c_uint32),
+ ctypes.c_void_p,
+ ],
+ "PdhCloseQuery": [ctypes.c_void_p],
+ }
+ for name, argtypes in prototypes.items():
+ fn = getattr(lib, name)
+ fn.argtypes = argtypes
+ fn.restype = ctypes.c_uint32
+ except (AttributeError, OSError) as exc:
+ InvokeAILogger.get_logger(__name__).debug(f"PDH unavailable: {exc}")
+ return None
+ return lib
+
+
def _close(lib: ctypes.CDLL, handle: int) -> None:
try:
lib.D3DKMTCloseAdapter(ctypes.byref(_CloseAdapter(handle)))
@@ -179,7 +238,8 @@ def _resolve_adapter(lib: ctypes.CDLL, index: int) -> Optional[_Adapter]:
for info in matches:
_close(lib, info.hAdapter)
return None
- return _Adapter(handle=matches[0].hAdapter, total_bytes=int(props.total_memory))
+ luid = (matches[0].AdapterLuid.HighPart << 32) | matches[0].AdapterLuid.LowPart
+ return _Adapter(handle=matches[0].hAdapter, luid=luid, total_bytes=int(props.total_memory))
def _adapter_for(device: torch.device) -> Optional[tuple[ctypes.CDLL, _Adapter]]:
@@ -223,8 +283,68 @@ def local_video_memory(device: torch.device) -> Optional[tuple[int, int]]:
return int(info.Budget), int(info.CurrentUsage)
+def _open_shared_usage_query(pdh: ctypes.CDLL) -> Optional[tuple[ctypes.c_void_p, ctypes.c_void_p]]:
+ query = ctypes.c_void_p()
+ if pdh.PdhOpenQueryW(None, None, ctypes.byref(query)) != 0:
+ return None
+ counter = ctypes.c_void_p()
+ if pdh.PdhAddEnglishCounterW(query, _PDH_SHARED_USAGE_COUNTER, None, ctypes.byref(counter)) != 0:
+ pdh.PdhCloseQuery(query)
+ return None
+ return query, counter
+
+
+def _shared_usage_by_instance(pdh: ctypes.CDLL, query: ctypes.c_void_p, counter: ctypes.c_void_p) -> dict[str, int]:
+ """Collect the query once; every ``GPU Process Memory`` instance's shared usage, keyed by its lower-case name."""
+ if pdh.PdhCollectQueryData(query) != 0:
+ return {}
+ size, count = ctypes.c_uint32(0), ctypes.c_uint32(0)
+ status = pdh.PdhGetFormattedCounterArrayW(counter, _PDH_FMT_LARGE, ctypes.byref(size), ctypes.byref(count), None)
+ if status != _PDH_MORE_DATA:
+ return {}
+ buffer = (ctypes.c_byte * size.value)()
+ status = pdh.PdhGetFormattedCounterArrayW(counter, _PDH_FMT_LARGE, ctypes.byref(size), ctypes.byref(count), buffer)
+ if status != 0:
+ return {}
+ items = ctypes.cast(buffer, ctypes.POINTER(_PdhCounterValueItem))
+ return {items[i].szName.lower(): int(items[i].FmtValue.largeValue) for i in range(count.value) if items[i].szName}
+
+
+def paged_bytes(device: torch.device) -> Optional[int]:
+ """Bytes of this process's memory on the device's adapter that Windows currently keeps in shared system memory.
+
+ Allocations land there when they did not fit the budget or found no contiguous VRAM, and they stay there; a few
+ hundred MB also appear briefly while weights are copied in. ``None`` off Windows ROCm and whenever the counters
+ cannot answer, including before this process has used the adapter at all.
+
+ The first call opens the PDH query (~0.3 s); each later call collects it once (~0.3 ms).
+ """
+ global _pdh_query, _pdh_attempted
+
+ if not _supported(device):
+ return None
+ resolved = _adapter_for(device)
+ pdh = _load_pdh()
+ if resolved is None or pdh is None:
+ return None
+ 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:
+ return _shared_usage_by_instance(pdh, *_pdh_query).get(instance)
+ except Exception:
+ return None
+
+
def reset_cache() -> None:
- """Close the cached adapter handles and forget the loader (tests only)."""
+ """Close the cached adapter handles and the PDH query, and forget the loaders (tests only)."""
+ global _pdh_query, _pdh_attempted
+
with _lock:
opened = [adapter for adapter in _adapters.values() if adapter is not None]
_adapters.clear()
@@ -233,3 +353,10 @@ def reset_cache() -> None:
for adapter in opened:
_close(lib, adapter.handle)
_load_gdi32.cache_clear()
+
+ with _pdh_lock:
+ query, _pdh_query, _pdh_attempted = _pdh_query, None, False
+ pdh = _load_pdh() if query is not None else None
+ if pdh is not None and query is not None:
+ pdh.PdhCloseQuery(query[0])
+ _load_pdh.cache_clear()
diff --git a/tests/app/services/session_processor/test_vram_paging_warning.py b/tests/app/services/session_processor/test_vram_paging_warning.py
new file mode 100644
index 0000000000..a12a0386d1
--- /dev/null
+++ b/tests/app/services/session_processor/test_vram_paging_warning.py
@@ -0,0 +1,92 @@
+"""The end-of-session warning when Windows keeps part of a worker's VRAM in shared system memory.
+
+It must speak once per episode (again only after the paged amount grew by the threshold, re-armed once it fell below
+it), say nothing where the answer is unknown, and never fail the worker.
+"""
+
+from types import SimpleNamespace
+
+import pytest
+import torch
+
+import invokeai.app.services.session_processor.session_processor_default as processor_module
+from invokeai.app.services.session_processor.session_processor_default import (
+ _VRAM_PAGING_WARNING_BYTES,
+ DefaultSessionProcessor,
+ _SessionWorker,
+)
+
+MIB = 2**20
+DEVICE = torch.device("cuda", 0)
+
+
+class _Logger:
+ def __init__(self) -> None:
+ self.warnings: list[str] = []
+ self.debugs: list[str] = []
+
+ def warning(self, message: str, **kwargs) -> None:
+ self.warnings.append(message)
+
+ def debug(self, message: str, **kwargs) -> None:
+ self.debugs.append(message)
+
+
+def processor() -> tuple[DefaultSessionProcessor, _Logger]:
+ logger = _Logger()
+ processor = DefaultSessionProcessor()
+ processor._invoker = SimpleNamespace(services=SimpleNamespace(logger=logger)) # type: ignore[attr-defined]
+ return processor, logger
+
+
+def _warned_after_each_session(monkeypatch, processor, readings) -> list[bool]:
+ """End one session per scripted `paged_bytes` reading on one worker; whether each one warned."""
+ processor, logger = processor
+ worker = _SessionWorker(DEVICE, runner=SimpleNamespace()) # type: ignore[arg-type]
+ values = iter(readings)
+
+ def paged_bytes(device):
+ assert device == DEVICE, "the worker's own device is the one asked"
+ return next(values)
+
+ monkeypatch.setattr(processor_module, "paged_bytes", paged_bytes)
+ warned = []
+ for _ in readings:
+ before = len(logger.warnings)
+ processor._warn_if_vram_paged(worker)
+ warned.append(len(logger.warnings) > before)
+ return warned
+
+
+def test_warns_once_per_episode_and_again_only_after_growth(monkeypatch, processor):
+ threshold = _VRAM_PAGING_WARNING_BYTES
+ readings = [
+ 6 * MIB, # an idle process
+ threshold + 100 * MIB, # paged: warn
+ threshold + 300 * MIB, # grew by less than the threshold since the warning
+ 2 * threshold + 200 * MIB, # grew by the threshold: warn again
+ 100 * MIB, # recovered below the threshold: re-armed
+ threshold, # a new episode: warn
+ ]
+
+ assert _warned_after_each_session(monkeypatch, processor, readings) == [False, True, False, True, False, True]
+ assert "cuda:0" in processor[1].warnings[0]
+
+
+def test_silent_where_the_answer_is_unknown(monkeypatch, processor):
+ assert _warned_after_each_session(monkeypatch, processor, [None, None]) == [False, False]
+
+
+def test_a_failing_counter_is_logged_at_debug_and_does_not_fail_the_worker(monkeypatch, processor):
+ processor_instance, logger = processor
+
+ def broken(device):
+ raise OSError("PDH query failed")
+
+ monkeypatch.setattr(processor_module, "paged_bytes", broken)
+
+ processor_instance._warn_if_vram_paged(_SessionWorker(DEVICE, runner=SimpleNamespace())) # type: ignore[arg-type]
+
+ assert logger.warnings == []
+ assert len(logger.debugs) == 1
diff --git a/tests/backend/util/test_wddm.py b/tests/backend/util/test_wddm.py
index d35427e319..7b9035c331 100644
--- a/tests/backend/util/test_wddm.py
+++ b/tests/backend/util/test_wddm.py
@@ -1,11 +1,12 @@
-"""The Windows video-memory budget reader, against a scripted stand-in for the gdi32 kernel thunks.
+"""The Windows video-memory readers, against scripted stand-ins for the gdi32 kernel thunks and for PDH.
-The thunks are driven through the same ctypes structures the module passes, so struct layout, the two-call adapter
-enumeration, the PCI match and handle cleanup are exercised; only the kernel behind them is fake.
+The stand-ins are driven through the same ctypes structures the module passes, so struct layout, the two-call adapter
+enumeration, the PCI match, handle cleanup and the counter-instance naming are exercised; only the OS behind them is fake.
"""
import ctypes
import functools
+import os
import sys
from types import SimpleNamespace
@@ -19,6 +20,50 @@ DEVICE = torch.device("cuda", 0)
OUR_BUS, OUR_DEVICE = 3, 0
+def _luid_low(handle: int) -> int:
+ return 0x22A00 + handle
+
+
+class _FakePdh:
+ """A PDH that reports the given ``GPU Process Memory`` instances' shared usage."""
+
+ def __init__(self, instances: dict[str, int]):
+ self.instances = instances
+ self.counter_paths: list[str] = []
+ self.closed = 0
+ self._alive: list[object] = []
+
+ def PdhOpenQueryW(self, source, user_data, query_ref):
+ query_ref._obj.value = 1
+ return 0
+
+ def PdhAddEnglishCounterW(self, query, path, user_data, counter_ref):
+ self.counter_paths.append(path)
+ counter_ref._obj.value = 2
+ return 0
+
+ def PdhCollectQueryData(self, query):
+ return 0
+
+ def PdhGetFormattedCounterArrayW(self, counter, fmt, size_ref, count_ref, buffer):
+ count = len(self.instances)
+ if buffer is None:
+ size_ref._obj.value = ctypes.sizeof(wddm._PdhCounterValueItem) * count
+ count_ref._obj.value = count
+ return wddm._PDH_MORE_DATA
+ items = (wddm._PdhCounterValueItem * count).from_buffer(buffer)
+ for item, (name, value) in zip(items, self.instances.items(), strict=True):
+ item.szName = name
+ item.FmtValue.largeValue = value
+ self._alive.append(items) # the name buffers live as long as the array object
+ count_ref._obj.value = count
+ return 0
+
+ def PdhCloseQuery(self, query):
+ self.closed += 1
+ return 0
+
+
class _FakeGdi32:
"""Adapters as (handle, bus, device); every thunk returns NTSTATUS 0 unless told otherwise."""
@@ -38,6 +83,8 @@ class _FakeGdi32:
return 0
for i, (handle, _bus, _device) in enumerate(self.adapters):
enum.pAdapters[i].hAdapter = handle
+ enum.pAdapters[i].AdapterLuid.LowPart = _luid_low(handle)
+ enum.pAdapters[i].AdapterLuid.HighPart = 0
return 0
def D3DKMTQueryAdapterInfo(self, ref):
@@ -142,6 +189,48 @@ def test_reset_closes_the_cached_handle(windows_rocm):
assert gdi32.closed == [20]
+def _instance(pid: int, handle: int) -> str:
+ return f"pid_{pid}_luid_0x00000000_0x{_luid_low(handle):08X}_phys_0"
+
+
+def test_paged_bytes_reads_this_process_on_the_devices_adapter(windows_rocm, monkeypatch):
+ windows_rocm(_FakeGdi32([(10, 7, 0), (20, OUR_BUS, OUR_DEVICE)]))
+ me = os.getpid()
+ pdh = _FakePdh(
+ {
+ _instance(me, 10): 5 * GIB, # this process, other adapter
+ _instance(me + 1, 20): 7 * GIB, # another process, our adapter
+ _instance(me, 20): 3 * GIB, # this process, our adapter (PDH may report upper-case hex)
+ }
+ )
+ monkeypatch.setattr(wddm, "_load_pdh", functools.lru_cache(maxsize=1)(lambda: pdh))
+
+ assert wddm.paged_bytes(DEVICE) == 3 * GIB
+ assert wddm.paged_bytes(DEVICE) == 3 * GIB
+ assert pdh.counter_paths == [r"\GPU Process Memory(*)\Shared Usage"], "one query, opened on first use"
+
+ wddm.reset_cache()
+ assert pdh.closed == 1
+
+
+def test_paged_bytes_is_unknown_before_this_process_used_the_adapter(windows_rocm, monkeypatch):
+ windows_rocm(_FakeGdi32([(20, OUR_BUS, OUR_DEVICE)]))
+ pdh = _FakePdh({_instance(os.getpid() + 1, 20): GIB})
+ monkeypatch.setattr(wddm, "_load_pdh", functools.lru_cache(maxsize=1)(lambda: pdh))
+
+ assert wddm.paged_bytes(DEVICE) is None
+
+
+def test_paged_bytes_elsewhere_never_touches_pdh(monkeypatch):
+ def loader():
+ raise AssertionError("pdh must not be loaded outside Windows ROCm")
+
+ monkeypatch.setattr(wddm, "_load_pdh", functools.lru_cache(maxsize=1)(loader))
+ monkeypatch.setattr(sys, "platform", "linux")
+
+ assert wddm.paged_bytes(DEVICE) is None
+
+
def test_structures_match_the_d3dkmt_layout():
"""The kernel reads these by offset: a shifted field would read a neighbour's bytes, not fail."""
assert ctypes.sizeof(wddm._AdapterInfo) == 20