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
fix(rocm): count freed VRAM as headroom on Windows
Alexander Eichhornb424e554c13e
diff --git a/invokeai/backend/model_manager/load/model_cache/model_cache.py b/invokeai/backend/model_manager/load/model_cache/model_cache.pyindex 7a72611f46..eea4522cfe 100644--- a/invokeai/backend/model_manager/load/model_cache/model_cache.py+++ b/invokeai/backend/model_manager/load/model_cache/model_cache.py@@ -2552,6 +2552,10 @@ class ModelCache:f"Offloading unlocked models with goal of making room for {vram_bytes_required / MB:.2f}MB of VRAM.")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.+ empty_cache_per_offload = _expandable_segments_enabled()# 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:@@ -2569,13 +2573,15 @@ class ModelCache:self._logger.debug(f"Unloaded {cache_entry.key} from VRAM to free {(cache_entry_bytes_freed / MB):.0f} MB.")+ if empty_cache_per_offload:+ TorchDevice.empty_cache()vram_bytes_freed += cache_entry_bytes_freed# Only pay for empty_cache() when something was actually offloaded. Paced VRAM moves run# this method once per pass, and on most passes there is nothing left to offload —# an unconditional empty_cache() would return the allocator's blocks to the driver# (and synchronize the device on ROCm) dozens of times per stream for no benefit.- if vram_bytes_freed > 0:+ if vram_bytes_freed > 0 and not empty_cache_per_offload:TorchDevice.empty_cache()return vram_bytes_freeddiff --git a/invokeai/backend/util/devices.py b/invokeai/backend/util/devices.pyindex aa0c60f99a..93de46aa4b 100644--- a/invokeai/backend/util/devices.py+++ b/invokeai/backend/util/devices.py@@ -9,7 +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+from invokeai.backend.util.wddm import video_memory_budget# legacy APIsTorchPrecisionNames = Literal["float32", "float16", "bfloat16"]@@ -464,15 +464,14 @@ class TorchDevice:"""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.+ Windows video-memory budget still allows this process (`wddm.video_memory_budget`). There, torch's figure is+ the device total minus this process's own live allocations: 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)+ budget = video_memory_budget(device)if budget is not None:- budget_bytes, usage_bytes = budget- free = min(free, max(budget_bytes - usage_bytes, 0))+ free = min(free, max(budget - (total - free), 0))return free, total@classmethoddiff --git a/invokeai/backend/util/wddm.py b/invokeai/backend/util/wddm.pyindex bde1c06989..be9c37859d 100644--- a/invokeai/backend/util/wddm.py+++ b/invokeai/backend/util/wddm.py@@ -8,8 +8,10 @@ system memory, silently and for as long as the allocation lives. What it will keMeasured on an RX 9060 XT (16 GB, torch 2.12+rocm7.14): alone, the budget is 15.09 of 15.92 GiB and paging startsonce 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.+about a second. What this process can still allocate before paging is the budget minus its live allocations -- the+device total minus torch's free figure. Not minus ``CurrentUsage``: that also counts memory HIP keeps after a free and+hands back to the next allocation (1-2 GiB measured, still held after ``empty_cache()``), so it would hide what an+offload just freed.Whether Windows has actually paged this process out is not visible through D3DKMT (``CurrentUsage`` counts paged bytesas local); it is visible in the ``GPU Process Memory`` performance counters Task Manager shows, read here through PDH.@@ -261,8 +263,8 @@ def _adapter_for(device: torch.device) -> Optional[tuple[ctypes.CDLL, _Adapter]]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.+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."""@@ -280,7 +282,7 @@ def local_video_memory(device: torch.device) -> Optional[tuple[int, int]]:return Noneif not 0 < info.Budget <= adapter.total_bytes:return None- return int(info.Budget), int(info.CurrentUsage)+ return int(info.Budget)def _open_shared_usage_query(pdh: ctypes.CDLL) -> Optional[tuple[ctypes.c_void_p, ctypes.c_void_p]]:diff --git a/tests/backend/model_manager/load/model_cache/conftest.py b/tests/backend/model_manager/load/model_cache/conftest.pyindex fdfc3de15f..c4240fb922 100644--- a/tests/backend/model_manager/load/model_cache/conftest.py+++ b/tests/backend/model_manager/load/model_cache/conftest.py@@ -9,4 +9,4 @@ def _no_windows_video_memory_budget(monkeypatch: pytest.MonkeyPatch) -> None: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)+ monkeypatch.setattr("invokeai.backend.util.devices.video_memory_budget", 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 0a39ddfa0a..933d539c9b 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@@ -15,6 +15,7 @@ import pytestimport torchfrom invokeai.backend.model_manager.load.model_cache.model_cache import ModelCache+from invokeai.backend.util.devices import TorchDeviceGB = 1024**3MB = 1024**2@@ -207,7 +208,46 @@ def test_the_windows_video_memory_budget_caps_the_measured_free_vram(monkeypatchmonkeypatch.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))+ monkeypatch.setattr("invokeai.backend.util.devices.video_memory_budget", lambda device: 11 * 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 * GB+ # 11 GB budget - 4 GB live = 7 GB headroom, + 2 GB allocated - 1 GB working - 2 GB in use; not torch's 12 GB.+ assert cache._get_vram_available(None) == 6 * GB+++def test_offloading_under_expandable_segments_stops_once_enough_is_free(monkeypatch: pytest.MonkeyPatch):+ """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."""+ 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+ device = {"free": 0, "allocated": 12 * GB, "unmappable": 0}++ def move_to_ram(entry, bytes_to_free):+ device["allocated"] -= 4 * GB+ device["unmappable"] += 4 * GB+ return 4 * GB++ def empty_cache():+ device["free"] += device["unmappable"]+ device["unmappable"] = 0++ monkeypatch.setenv("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")+ monkeypatch.setattr(torch.cuda, "mem_get_info", lambda d: (device["free"], 16 * GB))+ monkeypatch.setattr(torch.cuda, "memory_allocated", lambda d: device["allocated"])+ monkeypatch.setattr(TorchDevice, "empty_cache", empty_cache)+ monkeypatch.setattr(cache, "_move_model_to_ram", MagicMock(side_effect=move_to_ram))+ for key in "ABC":+ entry = MagicMock(key=key, is_locked=False)+ entry.cached_model.total_bytes.return_value = 4 * GB+ cache._cached_models[key] = entry++ # 2 GB needed + 1 GB working memory: one 4 GB model is enough.+ assert cache._offload_unlocked_models(2 * GB) == 4 * GB+ assert cache._move_model_to_ram.call_count == 1diff --git a/tests/backend/util/test_devices.py b/tests/backend/util/test_devices.pyindex 1a1847f8dc..1a22cd0b42 100644--- a/tests/backend/util/test_devices.py+++ b/tests/backend/util/test_devices.py@@ -551,18 +551,19 @@ def test_xpu_mem_get_info_estimates_when_native_and_sysman_both_fail(native_erro@pytest.mark.parametrize(- ("budget", "expected_free_gib"),- [(None, 10), ((15, 8), 7), ((15, 4), 10), ((15, 16), 0)],+ ("budget_gib", "expected_free_gib"),+ [(None, 10), (13, 7), (16, 10), (5, 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."""+def test_cuda_mem_get_info_is_capped_by_the_windows_video_memory_budget(budget_gib, expected_free_gib):+ """On Windows ROCm, torch's free figure ignores other processes and the point where Windows starts paging. The+ headroom is the budget minus this process's live allocations (16 - 10 = 6 GiB here)."""gib = 1024**3device = torch.device("cuda", 0)- reported = None if budget is None else (budget[0] * gib, budget[1] * gib)+ budget = None if budget_gib is None else budget_gib * gibwith (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,+ patch("invokeai.backend.util.devices.video_memory_budget", return_value=budget) as mock_budget,):assert TorchDevice.cuda_mem_get_info(device) == (expected_free_gib * gib, 16 * gib)mock_budget.assert_called_once_with(device)diff --git a/tests/backend/util/test_wddm.py b/tests/backend/util/test_wddm.pyindex 7b9035c331..5db03b5f52 100644--- a/tests/backend/util/test_wddm.py+++ b/tests/backend/util/test_wddm.py@@ -14,6 +14,7 @@ import pytestimport torchfrom invokeai.backend.util import wddm+from invokeai.backend.util.devices import TorchDeviceGIB = 1024**3DEVICE = torch.device("cuda", 0)@@ -67,10 +68,9 @@ class _FakePdh: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):+ def __init__(self, adapters, budget=15 * GIB, query_status=0):self.adapters = adaptersself.budget = budget- self.usage = usageself.query_status = query_statusself.enum_calls = 0self.closed: list[int] = []@@ -96,7 +96,7 @@ class _FakeGdi32:def D3DKMTQueryVideoMemoryInfo(self, ref):info = ref._obj- info.Budget, info.CurrentUsage = self.budget, self.usage+ info.Budget = self.budgetreturn self.query_statusdef D3DKMTCloseAdapter(self, ref):@@ -122,20 +122,18 @@ def windows_rocm(monkeypatch: pytest.MonkeyPatch):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)- )+ gdi32 = windows_rocm(_FakeGdi32([(10, 7, 0), (20, OUR_BUS, OUR_DEVICE), (30, 0xFFFFFFFF, 0xFFFF)], budget=15 * GIB))- assert wddm.local_video_memory(DEVICE) == (15 * GIB, 2 * GIB)+ assert wddm.video_memory_budget(DEVICE) == 15 * GIBassert 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)+ wddm.video_memory_budget(DEVICE)+ gdi32.budget = 12 * GIB # another GPU process started+ assert wddm.video_memory_budget(DEVICE) == 12 * GIBassert gdi32.enum_calls == 2, "one count call and one fill call, for the first query only"@@ -159,7 +157,7 @@ def test_resolves_the_adapter_once(windows_rocm):def test_unknown_rather_than_guessed(windows_rocm, adapters, kwargs):gdi32 = windows_rocm(_FakeGdi32(adapters, **kwargs))- assert wddm.local_video_memory(DEVICE) is None+ assert wddm.video_memory_budget(DEVICE) is Noneif len(adapters) == 2:assert sorted(gdi32.closed) == [20, 21], "an ambiguous match must not leak either handle"@@ -177,12 +175,12 @@ def test_elsewhere_gdi32_is_never_touched(windows_rocm, monkeypatch, platform, hmonkeypatch.setattr(sys, "platform", platform)monkeypatch.setattr(torch.version, "hip", hip)- assert wddm.local_video_memory(device) is None+ assert wddm.video_memory_budget(device) is Nonedef test_reset_closes_the_cached_handle(windows_rocm):gdi32 = windows_rocm(_FakeGdi32([(20, OUR_BUS, OUR_DEVICE)]))- wddm.local_video_memory(DEVICE)+ wddm.video_memory_budget(DEVICE)wddm.reset_cache()@@ -236,6 +234,10 @@ def test_structures_match_the_d3dkmt_layout():assert ctypes.sizeof(wddm._AdapterInfo) == 20assert wddm._QueryVideoMemoryInfo.Budget.offset == 16assert ctypes.sizeof(wddm._QueryVideoMemoryInfo) == 56+ # PDH_FMT_COUNTERVALUE_ITEM_W on 64-bit: a name pointer, then the value whose 8-byte union follows a DWORD status.+ assert wddm._PdhCounterValueItem.FmtValue.offset == 8+ assert wddm._PdhCounterValue.largeValue.offset == 8+ assert ctypes.sizeof(wddm._PdhCounterValueItem) == 24needs_windows_rocm = pytest.mark.skipif(@@ -246,16 +248,38 @@ needs_windows_rocm = pytest.mark.skipif(@pytest.mark.slow@needs_windows_rocm-def test_on_hardware_the_usage_follows_an_allocation():+def test_on_hardware_freed_memory_counts_as_headroom_again():+ """HIP keeps memory after a free and hands it to the next allocation; WDDM still counts it as this process's usage.+ The capped free figure must recover anyway, or an offload the model cache just made would look like no progress."""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+ torch.cuda.empty_cache()+ assert wddm.video_memory_budget(device) is not None+ before, _ = TorchDevice.cuda_mem_get_info(device)++ block = torch.empty(2 * GIB, dtype=torch.uint8, device=device).fill_(1)+ torch.cuda.synchronize()+ held, _ = TorchDevice.cuda_mem_get_info(device)+ del block+ torch.cuda.empty_cache()+ after, _ = TorchDevice.cuda_mem_get_info(device)++ assert before - held >= 1.9 * GIB+ assert after >= before - 64 * 2**20+- block = torch.empty(256 * 2**20, dtype=torch.uint8, device=device).fill_(1)+@needs_windows_rocm+def test_on_hardware_the_paged_amount_of_this_process_is_found():+ """The warning depends on finding this process's instance under the name the code builds; if that is wrong,+ `paged_bytes` quietly answers None forever."""+ wddm.reset_cache()+ device = torch.device("cuda", 0)+ block = torch.empty(64 * 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()+ paged = wddm.paged_bytes(device)++ assert paged is not None and paged >= 0+ del block