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.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
feat(rocm): keep the model cache within the Windows video-memory budget
Alexander Eichhorn9b0a53429983
diff --git a/docs/src/content/docs/configuration/low-vram-mode.mdx b/docs/src/content/docs/configuration/low-vram-mode.mdxindex e4cc56492d..abe6e0d2b2 100644--- a/docs/src/content/docs/configuration/low-vram-mode.mdx+++ b/docs/src/content/docs/configuration/low-vram-mode.mdx@@ -114,7 +114,8 @@ But, if your GPU has enough VRAM to hold models fully, you might get a perf boosmax_cache_ram_gb: 28# The default max cache VRAM size is adjusted dynamically based on the amount of available VRAM (taking into-# consideration the VRAM used by other processes).+# consideration the VRAM used by other processes; with a ROCm build on Windows, the video-memory budget Windows grants+# Invoke, beyond which it would move allocations into system memory).# You can override the default value by setting `max_cache_vram_gb`.# CAUTION: Most users should not manually set this value. See warning below.max_cache_vram_gb: 16diff --git a/invokeai/backend/model_manager/load/model_cache/model_cache.py b/invokeai/backend/model_manager/load/model_cache/model_cache.pyindex 3c1dce5641..7a72611f46 100644--- a/invokeai/backend/model_manager/load/model_cache/model_cache.py+++ b/invokeai/backend/model_manager/load/model_cache/model_cache.py@@ -2301,7 +2301,7 @@ class ModelCache:if self._execution_device.type == "cuda":vram_allocated = torch.cuda.memory_allocated(self._execution_device)- vram_free, _vram_total = torch.cuda.mem_get_info(self._execution_device)+ vram_free, _vram_total = TorchDevice.cuda_mem_get_info(self._execution_device)# Blocks the caching allocator holds but is not using are just as available to this# process as driver-free memory: the allocator reuses them directly, and empty_cache()# returns whole unoccupied segments to the driver. mem_get_info() alone counts them asdiff --git a/invokeai/backend/util/devices.py b/invokeai/backend/util/devices.pyindex 7a28973344..aa0c60f99a 100644--- a/invokeai/backend/util/devices.py+++ b/invokeai/backend/util/devices.py@@ -9,6 +9,7 @@ from deprecated import deprecatedfrom invokeai.app.services.config.config_default import get_configfrom invokeai.backend.util.level_zero import xpu_device_is_integrated, xpu_memory_infofrom invokeai.backend.util.logging import InvokeAILogger+from invokeai.backend.util.wddm import local_video_memory# legacy APIsTorchPrecisionNames = Literal["float32", "float16", "bfloat16"]@@ -458,6 +459,22 @@ class TorchDevice:return (max(total_bytes - reserved_bytes, 0), total_bytes)+ @classmethod+ def cuda_mem_get_info(cls, device: torch.device) -> tuple[int, int]:+ """Return ``(free, total)`` VRAM in bytes for a CUDA or ROCm device.++ ``torch.cuda.mem_get_info``, except that on a ROCm build under Windows the free figure is capped by what the+ Windows video-memory budget still allows this process (`wddm.local_video_memory`). There, torch's figure is+ the device total minus this process's own usage: it ignores other processes, and Windows pages allocations+ into shared system memory well before it is exhausted instead of failing them.+ """+ free, total = torch.cuda.mem_get_info(device)+ budget = local_video_memory(device)+ if budget is not None:+ budget_bytes, usage_bytes = budget+ free = min(free, max(budget_bytes - usage_bytes, 0))+ return free, total+@classmethoddef _to_dtype(cls, precision_name: TorchPrecisionNames) -> torch.dtype:return NAME_TO_PRECISION[precision_name]diff --git a/invokeai/backend/util/wddm.py b/invokeai/backend/util/wddm.pynew file mode 100644index 0000000000..93a6a6dbef--- /dev/null+++ b/invokeai/backend/util/wddm.py@@ -0,0 +1,235 @@+"""The Windows video-memory budget of a ROCm device, read from the WDDM kernel thunks in gdi32.++On a ROCm build under Windows, ``torch.cuda.mem_get_info`` reports the device total minus this process's own usage. It+does not see other processes, and it keeps reporting free memory after Windows has started to page this process's+allocations out -- Windows does not fail an allocation that exceeds what it will keep resident, it places it in shared+system memory, silently and for as long as the allocation lives. What it will keep resident is the per-process budget+``D3DKMTQueryVideoMemoryInfo`` reports (the figure ``IDXGIAdapter3::QueryVideoMemoryInfo`` returns, without COM).++Measured on an RX 9060 XT (16 GB, torch 2.12+rocm7.14): alone, the budget is 15.09 of 15.92 GiB and paging starts+once the committed local usage passes budget + 0.38 GiB; next to another GPU process, Windows lowers the budget within+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.++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 sys+import threading+from dataclasses import dataclass+from typing import Optional++import torch++from invokeai.backend.util.logging import InvokeAILogger++_KMTQAITYPE_ADAPTERADDRESS = 6+_MEMORY_SEGMENT_GROUP_LOCAL = 0+++# Win32 types spelled as fixed-width ctypes, so this module imports on every platform.+_UINT = ctypes.c_uint32+_ULONG = ctypes.c_uint32+_LONG = ctypes.c_int32+_BOOL = ctypes.c_int32+++class _Luid(ctypes.Structure):+ _fields_ = [("LowPart", _UINT), ("HighPart", _LONG)]+++class _AdapterInfo(ctypes.Structure):+ """``D3DKMT_ADAPTERINFO``."""++ _fields_ = [+ ("hAdapter", _UINT),+ ("AdapterLuid", _Luid),+ ("NumOfSources", _ULONG),+ ("bPrecisePresentRegionsPreferred", _BOOL),+ ]+++class _EnumAdapters2(ctypes.Structure):+ """``D3DKMT_ENUMADAPTERS2``."""++ _fields_ = [("NumAdapters", _ULONG), ("pAdapters", ctypes.POINTER(_AdapterInfo))]+++class _QueryAdapterInfo(ctypes.Structure):+ """``D3DKMT_QUERYADAPTERINFO``."""++ _fields_ = [+ ("hAdapter", _UINT),+ ("Type", ctypes.c_int),+ ("pPrivateDriverData", ctypes.c_void_p),+ ("PrivateDriverDataSize", _UINT),+ ]+++class _AdapterAddress(ctypes.Structure):+ """``D3DKMT_ADAPTERADDRESS``: the adapter's PCI location."""++ _fields_ = [("BusNumber", _UINT), ("DeviceNumber", _UINT), ("FunctionNumber", _UINT)]+++class _CloseAdapter(ctypes.Structure):+ """``D3DKMT_CLOSEADAPTER``."""++ _fields_ = [("hAdapter", _UINT)]+++class _QueryVideoMemoryInfo(ctypes.Structure):+ """``D3DKMT_QUERYVIDEOMEMORYINFO``. A null ``hProcess`` means the calling process."""++ _fields_ = [+ ("hProcess", ctypes.c_void_p),+ ("hAdapter", _UINT),+ ("MemorySegmentGroup", ctypes.c_int),+ ("Budget", ctypes.c_uint64),+ ("CurrentUsage", ctypes.c_uint64),+ ("CurrentReservation", ctypes.c_uint64),+ ("AvailableForReservation", ctypes.c_uint64),+ ("PhysicalAdapterIndex", _UINT),+ ]+++_GDI32_FUNCTIONS = (+ "D3DKMTEnumAdapters2",+ "D3DKMTQueryAdapterInfo",+ "D3DKMTQueryVideoMemoryInfo",+ "D3DKMTCloseAdapter",+)+++@dataclass(frozen=True)+class _Adapter:+ handle: int+ total_bytes: int+++_lock = threading.Lock()+# Per torch device index: the matching WDDM adapter, or None once resolution has failed.+_adapters: dict[int, Optional[_Adapter]] = {}+++def _supported(device: torch.device) -> bool:+ return sys.platform == "win32" and torch.version.hip is not None and device.type == "cuda"++[email protected]_cache(maxsize=1)+def _load_gdi32() -> Optional[ctypes.CDLL]:+ """Open gdi32 once and declare every thunk as taking a struct pointer and returning an NTSTATUS."""+ try:+ lib = ctypes.WinDLL("gdi32")+ for name in _GDI32_FUNCTIONS:+ fn = getattr(lib, name)+ fn.argtypes = [ctypes.c_void_p]+ fn.restype = ctypes.c_long+ except (AttributeError, OSError) as exc:+ InvokeAILogger.get_logger(__name__).debug(f"WDDM thunks unavailable: {exc}")+ return None+ return lib+++def _close(lib: ctypes.CDLL, handle: int) -> None:+ try:+ lib.D3DKMTCloseAdapter(ctypes.byref(_CloseAdapter(handle)))+ except Exception:+ pass+++def _resolve_adapter(lib: ctypes.CDLL, index: int) -> Optional[_Adapter]:+ """Open the WDDM adapter at the torch device's PCI location, closing every other handle the enumeration opened.++ ROCm's device properties carry no LUID, so the PCI bus and device numbers are the link. Anything but exactly one+ match is treated as unknown rather than guessed.+ """+ props = torch.cuda.get_device_properties(index)+ location = (int(props.pci_bus_id), int(props.pci_device_id))++ enum = _EnumAdapters2(0, None)+ if lib.D3DKMTEnumAdapters2(ctypes.byref(enum)) != 0:+ return None+ infos = (_AdapterInfo * enum.NumAdapters)()+ enum.pAdapters = infos+ if lib.D3DKMTEnumAdapters2(ctypes.byref(enum)) != 0:+ 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:+ _close(lib, info.hAdapter)++ if len(matches) != 1:+ for info in matches:+ _close(lib, info.hAdapter)+ return None+ return _Adapter(handle=matches[0].hAdapter, total_bytes=int(props.total_memory))+++def _adapter_for(device: torch.device) -> Optional[tuple[ctypes.CDLL, _Adapter]]:+ lib = _load_gdi32()+ if lib is None:+ return None+ try:+ index = device.index if device.index is not None else torch.cuda.current_device()+ except Exception:+ return None+ with _lock:+ if index not in _adapters:+ try:+ _adapters[index] = _resolve_adapter(lib, index)+ except Exception as exc:+ InvokeAILogger.get_logger(__name__).debug(f"WDDM adapter lookup for {device} failed: {exc}")+ _adapters[index] = None+ adapter = _adapters[index]+ return None if adapter is None else (lib, adapter)+++def local_video_memory(device: torch.device) -> Optional[tuple[int, int]]:+ """This process's WDDM budget and committed local usage on the device's adapter, as ``(budget, usage)`` in bytes.++ ``None`` off Windows ROCm, and whenever the driver cannot answer or answers something implausible.+ """+ 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:+ if lib.D3DKMTQueryVideoMemoryInfo(ctypes.byref(info)) != 0:+ return None+ except Exception:+ return None+ if not 0 < info.Budget <= adapter.total_bytes:+ return None+ return int(info.Budget), int(info.CurrentUsage)+++def reset_cache() -> None:+ """Close the cached adapter handles and forget the loader (tests only)."""+ with _lock:+ opened = [adapter for adapter in _adapters.values() if adapter is not None]+ _adapters.clear()+ lib = _load_gdi32() if opened else None+ if lib is not None:+ for adapter in opened:+ _close(lib, adapter.handle)+ _load_gdi32.cache_clear()diff --git a/tests/backend/model_manager/load/model_cache/conftest.py b/tests/backend/model_manager/load/model_cache/conftest.pynew file mode 100644index 0000000000..fdfc3de15f--- /dev/null+++ b/tests/backend/model_manager/load/model_cache/conftest.py@@ -0,0 +1,12 @@+import pytest++[email protected](autouse=True)+def _no_windows_video_memory_budget(monkeypatch: pytest.MonkeyPatch) -> None:+ """Keep the cache's VRAM arithmetic on whatever each test patches into ``torch.cuda``.++ Many of these tests fake a ``cuda`` execution device and patch ``torch.cuda.mem_get_info``. On a ROCm build under+ Windows, ``TorchDevice.cuda_mem_get_info`` would additionally cap that fake with the real adapter's WDDM budget,+ making the expected figures depend on the machine running the suite. Tests of the cap patch it back in.+ """+ monkeypatch.setattr("invokeai.backend.util.devices.local_video_memory", lambda device: None)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.pyindex 2274fb0109..0a39ddfa0a 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@@ -187,3 +187,27 @@ def test_physical_availability_shares_the_reclaimable_credit_policy(monkeypatch:monkeypatch.setenv("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")assert cache._get_physical_vram_available() == 3 * GB+++def test_the_windows_video_memory_budget_caps_the_measured_free_vram(monkeypatch: pytest.MonkeyPatch):+ """On Windows ROCm, torch reports the device total minus this process's usage. Windows pages allocations into+ shared system memory once the process passes its video-memory budget, so the budget's headroom is what the cache+ may plan with -- not the larger figure torch reports."""+ cache = ModelCache(+ execution_device_working_mem_gb=1.0,+ enable_partial_loading=True,+ keep_ram_copy_of_weights=True,+ execution_device="cpu",+ storage_device="cpu",+ logger=MagicMock(),+ shared_cpu_weights=None,+ )+ cache._execution_device = torch.device("cuda") # policy only; every VRAM query below is patched out+ monkeypatch.setattr(torch.cuda, "mem_get_info", lambda device: (12 * GB, 16 * GB))+ monkeypatch.setattr(torch.cuda, "memory_allocated", lambda device: 2 * GB)+ monkeypatch.setattr(torch.cuda, "memory_reserved", lambda device: 2 * GB)+ monkeypatch.setattr(torch.cuda, "memory_stats", lambda device: {"inactive_split_bytes.all.current": 0})+ monkeypatch.setattr("invokeai.backend.util.devices.local_video_memory", lambda device: (15 * GB, 7 * GB))++ # 8 GB of budget headroom + 2 GB allocated - 1 GB working - 2 GB in use, not the 12 GB torch reports.+ assert cache._get_vram_available(None) == 7 * GBdiff --git a/tests/backend/util/test_devices.py b/tests/backend/util/test_devices.pyindex b4716084ae..1a1847f8dc 100644--- a/tests/backend/util/test_devices.py+++ b/tests/backend/util/test_devices.py@@ -550,6 +550,24 @@ def test_xpu_mem_get_info_estimates_when_native_and_sysman_both_fail(native_erroassert TorchDevice.xpu_mem_get_info(torch.device("xpu")) == (30 * gib, 32 * gib)+ ("budget", "expected_free_gib"),+ [(None, 10), ((15, 8), 7), ((15, 4), 10), ((15, 16), 0)],+ ids=["no-budget", "budget-is-tighter", "torch-is-tighter", "over-budget"],+)+def test_cuda_mem_get_info_is_capped_by_the_windows_video_memory_budget(budget, expected_free_gib):+ """On Windows ROCm, torch's free figure ignores other processes and the point where Windows starts paging."""+ gib = 1024**3+ device = torch.device("cuda", 0)+ reported = None if budget is None else (budget[0] * gib, budget[1] * gib)+ with (+ patch.object(torch.cuda, "mem_get_info", return_value=(10 * gib, 16 * gib)),+ patch("invokeai.backend.util.devices.local_video_memory", return_value=reported) as mock_budget,+ ):+ assert TorchDevice.cuda_mem_get_info(device) == (expected_free_gib * gib, 16 * gib)+ mock_budget.assert_called_once_with(device)++def test_get_generation_devices_auto_expands_to_all_xpu():"""With no CUDA, `auto` enumerates every visible XPU device."""config = get_config()diff --git a/tests/backend/util/test_wddm.py b/tests/backend/util/test_wddm.pynew file mode 100644index 0000000000..d35427e319--- /dev/null+++ b/tests/backend/util/test_wddm.py@@ -0,0 +1,172 @@+"""The Windows video-memory budget reader, against a scripted stand-in for the gdi32 kernel thunks.++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.+"""++import ctypes+import functools+import sys+from types import SimpleNamespace++import pytest+import torch++from invokeai.backend.util import wddm++GIB = 1024**3+DEVICE = torch.device("cuda", 0)+OUR_BUS, OUR_DEVICE = 3, 0+++class _FakeGdi32:+ """Adapters as (handle, bus, device); every thunk returns NTSTATUS 0 unless told otherwise."""++ def __init__(self, adapters, budget=15 * GIB, usage=2 * GIB, query_status=0):+ self.adapters = adapters+ self.budget = budget+ self.usage = usage+ self.query_status = query_status+ self.enum_calls = 0+ self.closed: list[int] = []++ def D3DKMTEnumAdapters2(self, ref):+ self.enum_calls += 1+ enum = ref._obj+ if not enum.pAdapters:+ enum.NumAdapters = len(self.adapters)+ return 0+ for i, (handle, _bus, _device) in enumerate(self.adapters):+ enum.pAdapters[i].hAdapter = handle+ return 0++ def D3DKMTQueryAdapterInfo(self, ref):+ query = ref._obj+ address = wddm._AdapterAddress.from_address(query.pPrivateDriverData)+ _handle, bus, device = next(a for a in self.adapters if a[0] == query.hAdapter)+ address.BusNumber, address.DeviceNumber = bus, device+ return 0++ def D3DKMTQueryVideoMemoryInfo(self, ref):+ info = ref._obj+ info.Budget, info.CurrentUsage = self.budget, self.usage+ return self.query_status++ def D3DKMTCloseAdapter(self, ref):+ self.closed.append(ref._obj.hAdapter)+ return 0+++def windows_rocm(monkeypatch: pytest.MonkeyPatch):+ """A Windows ROCm build whose device 0 sits at PCI bus 3 with 16 GiB. Returns an installer for a fake gdi32."""+ monkeypatch.setattr(sys, "platform", "win32")+ monkeypatch.setattr(torch.version, "hip", "7.14.0")+ props = SimpleNamespace(pci_bus_id=OUR_BUS, pci_device_id=OUR_DEVICE, total_memory=16 * GIB)+ monkeypatch.setattr(torch.cuda, "get_device_properties", lambda index: props)+ wddm.reset_cache()++ def install(fake: _FakeGdi32) -> _FakeGdi32:+ monkeypatch.setattr(wddm, "_load_gdi32", functools.lru_cache(maxsize=1)(lambda: fake))+ return fake++ yield install+ wddm.reset_cache()+++def test_reads_the_budget_of_the_adapter_at_the_devices_pci_location(windows_rocm):+ gdi32 = windows_rocm(+ _FakeGdi32([(10, 7, 0), (20, OUR_BUS, OUR_DEVICE), (30, 0xFFFFFFFF, 0xFFFF)], budget=15 * GIB, usage=2 * GIB)+ )++ assert wddm.local_video_memory(DEVICE) == (15 * GIB, 2 * GIB)+ assert sorted(gdi32.closed) == [10, 30], "the other adapters' handles are closed, ours stays open"+++def test_resolves_the_adapter_once(windows_rocm):+ gdi32 = windows_rocm(_FakeGdi32([(20, OUR_BUS, OUR_DEVICE)]))++ wddm.local_video_memory(DEVICE)+ gdi32.usage = 5 * GIB+ assert wddm.local_video_memory(DEVICE) == (15 * GIB, 5 * GIB)+ assert gdi32.enum_calls == 2, "one count call and one fill call, for the first query only"+++ ("adapters", "kwargs"),+ [+ ([(10, 7, 0)], {}),+ ([(20, OUR_BUS, OUR_DEVICE), (21, OUR_BUS, OUR_DEVICE)], {}),+ ([(20, OUR_BUS, OUR_DEVICE)], {"query_status": -1073741823}),+ ([(20, OUR_BUS, OUR_DEVICE)], {"budget": 0}),+ ([(20, OUR_BUS, OUR_DEVICE)], {"budget": 17 * GIB}),+ ],+ ids=[+ "no-adapter-at-the-location",+ "two-adapters-at-the-location",+ "query-fails",+ "zero-budget",+ "budget-over-total",+ ],+)+def test_unknown_rather_than_guessed(windows_rocm, adapters, kwargs):+ gdi32 = windows_rocm(_FakeGdi32(adapters, **kwargs))++ assert wddm.local_video_memory(DEVICE) is None+ if len(adapters) == 2:+ assert sorted(gdi32.closed) == [20, 21], "an ambiguous match must not leak either handle"+++ ("platform", "hip", "device"),+ [("linux", "7.2.0", DEVICE), ("win32", None, DEVICE), ("win32", "7.14.0", torch.device("cpu"))],+ ids=["linux-rocm", "windows-cuda", "cpu-device"],+)+def test_elsewhere_gdi32_is_never_touched(windows_rocm, monkeypatch, platform, hip, device):+ def loader():+ raise AssertionError("gdi32 must not be loaded outside Windows ROCm")++ monkeypatch.setattr(wddm, "_load_gdi32", functools.lru_cache(maxsize=1)(loader))+ monkeypatch.setattr(sys, "platform", platform)+ monkeypatch.setattr(torch.version, "hip", hip)++ assert wddm.local_video_memory(device) is None+++def test_reset_closes_the_cached_handle(windows_rocm):+ gdi32 = windows_rocm(_FakeGdi32([(20, OUR_BUS, OUR_DEVICE)]))+ wddm.local_video_memory(DEVICE)++ wddm.reset_cache()++ assert gdi32.closed == [20]+++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+ assert wddm._QueryVideoMemoryInfo.Budget.offset == 16+ assert ctypes.sizeof(wddm._QueryVideoMemoryInfo) == 56+++needs_windows_rocm = pytest.mark.skipif(+ sys.platform != "win32" or torch.version.hip is None or not torch.cuda.is_available(),+ reason="needs a ROCm GPU under Windows",+)+++@needs_windows_rocm+def test_on_hardware_the_usage_follows_an_allocation():+ wddm.reset_cache()+ device = torch.device("cuda", 0)+ torch.empty(1, device=device)+ before = wddm.local_video_memory(device)+ assert before is not None and before[0] > 0++ block = torch.empty(256 * 2**20, dtype=torch.uint8, device=device).fill_(1)+ torch.cuda.synchronize()+ after = wddm.local_video_memory(device)++ assert after is not None+ assert after[1] - before[1] >= 0.9 * block.numel()