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(vae): bound the pre-tiling ceiling by residency, not by usage Windows has paged out

Alexander Eichhorn5878d9d102c5
diff --git a/invokeai/backend/util/vae_working_memory.py b/invokeai/backend/util/vae_working_memory.py
index 335889948c..f1b321a20a 100644
--- a/invokeai/backend/util/vae_working_memory.py
+++ b/invokeai/backend/util/vae_working_memory.py
@@ -32,24 +32,34 @@ def should_pretile_vae_decode(
memory) is never tiled on these grounds.
On Windows the ceiling is the video-memory budget rather than the card's nameplate total -- the budget is the point
- past which Windows pages this process out. With one correction: a budget *below* what this process already holds is
+ past which Windows pages this process out. With one correction: a budget *below* what this process keeps resident is
Windows asking it to trim itself, and the cache does exactly that to honour the reservation, so the ceiling is then
- what it holds. Measured on an RX 9060 XT (16 GB): with Invoke holding 12 GiB and nothing else on the card the
+ that residency. Measured on an RX 9060 XT (16 GB): with Invoke holding 12 GiB and nothing else on the card the
budget read 7.62 GiB, and comparing against that tiled a 7.0 GiB decode that fits, changing output that had been
pixel-identical.
- Known limit: a foreign process that takes memory without the budget moving is invisible here. Windows keeps
- reporting 15.09 GiB next to an 8 GiB holder, torch's free figure ignores other processes, and the adapter-wide
- performance counter contradicts itself between processes (15.66 GiB read from the holding process against 0.18 GiB
- from another, same instance, same instant), so there is no reading to base it on. Such a decode pages, and the
- end-of-session paging warning is what surfaces it.
+ Residency, not ``CurrentUsage``: that also counts what Windows has already paged out, which a foreign process forces
+ exactly when the budget carries its pressure (next to an 8 GiB holder the budget stepped down to 7.58 GiB while our
+ ``CurrentUsage`` kept growing past our 7.70 GiB in VRAM). So the override is ``CurrentUsage`` minus this process's
+ paged bytes, and where either is unknown -- ``CurrentUsage`` beyond the card, or no counter reading -- the budget
+ alone decides (so a transient counter failure can tile a decode that the next run leaves untiled).
+
+ Known limit: the budget reacts to a foreign process only once this process grows into the memory it holds -- it
+ stays at 15.09 GiB next to an 8 GiB holder while Invoke holds little -- torch's free figure ignores other processes,
+ and the adapter-wide performance counter contradicts itself between processes (15.66 GiB read from the holding
+ process against 0.18 GiB from another, same instance, same instant). A decode sized before that point can still
+ page, and the end-of-session paging warning is what surfaces it.
"""
if device.type == "cuda":
total_bytes = torch.cuda.get_device_properties(device).total_memory
local = wddm.local_video_memory(device)
if local is not None:
budget_bytes, usage_bytes = local
- total_bytes = min(total_bytes, max(budget_bytes, usage_bytes))
+ ceiling_bytes = budget_bytes
+ paged = wddm.paged_bytes(device) if usage_bytes is not None else None
+ if paged is not None:
+ ceiling_bytes = max(budget_bytes, usage_bytes - paged)
+ total_bytes = min(total_bytes, ceiling_bytes)
elif device.type == "xpu":
total_bytes = torch.xpu.get_device_properties(device).total_memory
else:
diff --git a/invokeai/backend/util/wddm.py b/invokeai/backend/util/wddm.py
index 64405508ac..ec39f7b738 100644
--- a/invokeai/backend/util/wddm.py
+++ b/invokeai/backend/util/wddm.py
@@ -7,11 +7,16 @@ system memory, silently and for as long as the allocation lives. What it will ke
``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. 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.
+once the committed local usage passes budget + 0.38 GiB; once the process itself holds about 12 GiB the budget drops to
+7.62 GiB without anything being paged -- Windows asking it to trim, not a limit it has hit. Next to another GPU process
+the budget is not "total minus the other process": it stays at 15.09 GiB while this process holds little and steps down
+once the two together pass about 12 GiB -- next to an 8 GiB holder, from 15.09 at 3.25 GiB of our own down to 7.58 at
+7.5 GiB, where this process then starts to page. So by the time this process could page, the budget is its share of the
+card.
+
+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 bytes
as local); it is visible in the ``GPU Process Memory`` performance counters Task Manager shows, read here through PDH.
@@ -141,7 +146,6 @@ _adapters: dict[int, Optional[_Adapter]] = {}
_pdh_lock = threading.Lock()
# One PDH query per counter path, opened on first use: path -> (query, counter) or None when that counter is absent.
-# Per counter so that a counter this build does not have disables only what reads it.
_pdh_queries: dict[str, Optional[tuple[ctypes.c_void_p, ctypes.c_void_p]]] = {}
@@ -279,11 +283,12 @@ 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]]:
+def local_video_memory(device: torch.device) -> Optional[tuple[int, Optional[int]]]:
"""``(budget, current_usage)`` for this process on the device's adapter, both driver-side figures in bytes.
- ``None`` off Windows ROCm, and whenever the driver cannot answer or answers something implausible. Called per
- generation and per decode, so every failure answers "unknown" here rather than reaching those callers.
+ ``None`` off Windows ROCm, and whenever the driver cannot answer or answers a budget that is implausible. The usage
+ alone is ``None`` when it exceeds the adapter (see below). Called per generation and per decode, so every failure
+ answers "unknown" here rather than reaching those callers.
"""
if not _supported(device):
return None
@@ -297,10 +302,11 @@ def local_video_memory(device: torch.device) -> Optional[tuple[int, int]]:
return None
if not 0 < info.Budget <= adapter.total_bytes:
return None
- # Clamped, not rejected: `CurrentUsage` counts bytes Windows has already paged out, so it can exceed the
- # adapter's own size exactly when the process over-commits -- and dropping the pair there would also take the
- # budget away from the model cache's free-VRAM cap, which is the caller that needs it most in that state.
- return int(info.Budget), max(0, min(int(info.CurrentUsage), adapter.total_bytes))
+ # `CurrentUsage` counts bytes Windows has already paged out, so it exceeds the adapter's own size exactly when
+ # the process over-commits. It says nothing about residency then, so it is reported as unknown; the budget
+ # stands, since the model cache's free-VRAM cap is the caller that needs it most in that state.
+ usage = int(info.CurrentUsage)
+ return int(info.Budget), usage if 0 <= usage <= adapter.total_bytes else None
except Exception:
InvokeAILogger.get_logger(__name__).debug(f"WDDM memory lookup for {device} failed", exc_info=True)
return None
diff --git a/tests/app/invocations/test_qwen_image_working_memory.py b/tests/app/invocations/test_qwen_image_working_memory.py
index 49fd219fa0..246477618f 100644
--- a/tests/app/invocations/test_qwen_image_working_memory.py
+++ b/tests/app/invocations/test_qwen_image_working_memory.py
@@ -584,8 +584,19 @@ class TestMeasuredDecodePeak:
assert at_1280 == pytest.approx(at_1024 + span * (1280**2 - 1024**2), rel=1e-6)
def test_a_smaller_image_is_never_priced_above_a_larger_one(self):
- """1728x1856 against 1792^2 on CUDA: 0.13% less area, and bracket-max interpolation made it 2.3 GiB dearer."""
+ """1728x1856 against 1792^2 on CUDA: 0.13% less area, and bracket-max interpolation made it 2.3 GiB dearer.
+ 1600x1472 against 1024x2304 is the ROCm counterpart: 20.05 GiB against 14.38 GiB before."""
assert self._peak_hw(1728, 1856, hip=None) <= self._peak_hw(1792, 1792, hip=None)
+ assert self._peak_hw(1600, 1472) <= self._peak_hw(1024, 2304)
+
+ @pytest.mark.parametrize("hip", ["7.2.0", None], ids=["rocm", "cuda"])
+ def test_the_price_never_falls_as_the_area_grows(self, hip):
+ """Across the whole grid of sizes the decision sees, a larger output area is never priced lower -- the
+ property the single pairs above are instances of, for both backends' curves."""
+ sizes = range(512, 2561, 64)
+ prices = sorted((h * w, self._peak_hw(h, w, hip=hip)) for h in sizes for w in sizes)
+ inversions = [(a, b) for a, b in zip(prices, prices[1:], strict=False) if b[1] < a[1]]
+ assert inversions == []
def test_past_the_measured_range_takes_the_reservation_constant(self):
"""Nothing was measured there, so the decision uses the figure the reservation uses -- guessing low would
diff --git a/tests/backend/util/test_vae_pretile.py b/tests/backend/util/test_vae_pretile.py
index 0900aea209..4aba3c32e7 100644
--- a/tests/backend/util/test_vae_pretile.py
+++ b/tests/backend/util/test_vae_pretile.py
@@ -45,10 +45,8 @@ def test_the_pretile_gate_uses_the_memory_the_device_will_keep_resident(monkeypa
This is the platform the feature was written for: the docstring justifies up-front tiling with
"on Windows, drivers page an allocation that does not fit into system memory instead of failing
- it (always for ROCm)". Windows pages once the process passes its WDDM budget, and another GPU
- process lowers that budget within about a second -- which is exactly why this PR added
- `TorchDevice.cuda_mem_get_info` to cap the model cache's free figure by `wddm.video_memory_budget`.
- The tiling gate consults neither that budget nor free memory, only `total_memory`.
+ it (always for ROCm)". Windows pages once the process passes its WDDM budget, so the gate has to
+ compare against that budget rather than `total_memory`.
A 16 GiB card whose budget is down to 12.5 GiB pages a 13.3 GiB decode (FLUX.1 at 1408px on
MIOpen). No out-of-memory error is raised there, so the nodes' tiled retry never fires and the
@@ -60,12 +58,9 @@ def test_the_pretile_gate_uses_the_memory_the_device_will_keep_resident(monkeypa
estimate = 1408 * 1408 * 2 * 3600 # 13.3 GiB: under 90% of the card, over the budget
monkeypatch.setattr("torch.cuda.get_device_properties", lambda device: MagicMock(total_memory=total_bytes))
- # torch cannot see the shortfall: on Windows ROCm its free figure is the device total minus this
- # process's own live allocations, and this process has allocated nothing yet.
- monkeypatch.setattr("torch.cuda.mem_get_info", lambda device: (total_bytes, total_bytes))
- # Patch both binding sites: `devices` imports its own name, and the gate reads the budget/usage pair.
- monkeypatch.setattr("invokeai.backend.util.devices.video_memory_budget", lambda device: budget_bytes)
+ # This process has allocated nothing yet, so its residency cannot lift the ceiling above the budget.
monkeypatch.setattr("invokeai.backend.util.wddm.local_video_memory", lambda device: (budget_bytes, 0))
+ monkeypatch.setattr("invokeai.backend.util.wddm.paged_bytes", lambda device: 0)
assert estimate < VAE_PRETILE_VRAM_FRACTION * total_bytes, "test shape must look fine against the card total"
assert estimate > budget_bytes, "test shape must exceed what Windows would keep resident"
@@ -82,8 +77,8 @@ def test_a_budget_below_our_own_residency_does_not_tile_a_decode_that_fits(monke
estimate = 7 * 2**30
monkeypatch.setattr("torch.cuda.get_device_properties", lambda device: MagicMock(total_memory=total_bytes))
- monkeypatch.setattr("torch.cuda.mem_get_info", lambda device: (4 * 2**30, total_bytes))
monkeypatch.setattr("invokeai.backend.util.wddm.local_video_memory", lambda device: (int(7.6 * 2**30), 12 * 2**30))
+ monkeypatch.setattr("invokeai.backend.util.wddm.paged_bytes", lambda device: 0) # alone: nothing paged out
assert should_pretile_vae_decode(torch.device("cuda", 0), estimate) is False
@@ -95,15 +90,52 @@ def test_a_decode_beyond_both_the_budget_and_our_residency_is_tiled(monkeypatch)
estimate = int(8.93 * 2**30) # a Qwen-Image 1024px decode peak
monkeypatch.setattr("torch.cuda.get_device_properties", lambda device: MagicMock(total_memory=total_bytes))
- monkeypatch.setattr("torch.cuda.mem_get_info", lambda device: (int(7.8 * 2**30), total_bytes))
monkeypatch.setattr(
"invokeai.backend.util.wddm.local_video_memory", lambda device: (int(7.55 * 2**30), int(8.2 * 2**30))
)
+ monkeypatch.setattr("invokeai.backend.util.wddm.paged_bytes", lambda device: 0)
assert estimate < VAE_PRETILE_VRAM_FRACTION * total_bytes, "the card total alone would let this through"
assert should_pretile_vae_decode(torch.device("cuda", 0), estimate) is True
+QWEN_1024_DECODE = int(8.93 * 2**30)
+
+
+def _windows_rocm(monkeypatch, budget: float, usage: float | None, paged: float | None) -> None:
+ monkeypatch.setattr("torch.cuda.get_device_properties", lambda device: MagicMock(total_memory=16 * 2**30))
+ usage_bytes = None if usage is None else int(usage * 2**30)
+ monkeypatch.setattr(
+ "invokeai.backend.util.wddm.local_video_memory", lambda device: (int(budget * 2**30), usage_bytes)
+ )
+ paged_bytes = None if paged is None else int(paged * 2**30)
+ monkeypatch.setattr("invokeai.backend.util.wddm.paged_bytes", lambda device: paged_bytes)
+
+
+def test_usage_windows_has_paged_out_does_not_lift_the_ceiling(monkeypatch):
+ """Next to an 8 GiB holder the budget steps down to its share of the card while `CurrentUsage` keeps counting what
+ Windows paged out (measured: budget 7.58 GiB, usage 9.65 GiB, 7.70 GiB actually in VRAM). Only the resident part
+ may override the budget; taking the whole usage priced this decode against a 12 GiB ceiling and let it page."""
+ _windows_rocm(monkeypatch, budget=7.6, usage=12.0, paged=4.3)
+
+ assert should_pretile_vae_decode(torch.device("cuda", 0), QWEN_1024_DECODE) is True
+
+
+def test_usage_beyond_the_card_leaves_the_budget_in_charge(monkeypatch):
+ """An over-committed process reports more usage than the card has; that says nothing about residency, and
+ clamping it to the card size switched the correction off exactly while Windows was paging."""
+ _windows_rocm(monkeypatch, budget=7.6, usage=None, paged=4.3)
+
+ assert should_pretile_vae_decode(torch.device("cuda", 0), QWEN_1024_DECODE) is True
+
+
+def test_residency_unknown_leaves_the_budget_in_charge(monkeypatch):
+ """Without a paged-bytes reading the resident part is unknown, so a budget below our usage is taken as it is."""
+ _windows_rocm(monkeypatch, budget=7.6, usage=12.0, paged=None)
+
+ assert should_pretile_vae_decode(torch.device("cuda", 0), 7 * 2**30) is True
+
+
def test_the_card_total_stands_when_windows_does_not_answer(monkeypatch):
"""Off Windows ROCm, and whenever the driver cannot answer, the rule is the card's own size."""
total_bytes = 16 * 2**30
diff --git a/tests/backend/util/test_wddm.py b/tests/backend/util/test_wddm.py
index 2ec16a9ae1..a2c53b65ea 100644
--- a/tests/backend/util/test_wddm.py
+++ b/tests/backend/util/test_wddm.py
@@ -151,13 +151,13 @@ def test_resolves_the_adapter_once(windows_rocm):
assert gdi32.enum_calls == 2, "one count call and one fill call, for the first query only"
-def test_usage_beyond_the_card_is_clamped_and_keeps_the_budget(windows_rocm):
+def test_usage_beyond_the_card_is_unknown_and_keeps_the_budget(windows_rocm):
"""`CurrentUsage` counts bytes Windows has already paged out, so it can exceed the adapter's own size when the
- process over-commits. Dropping the pair there would take the budget away from the model cache's free-VRAM cap in
- exactly that state, so the usage is clamped instead."""
+ process over-commits. It says nothing about residency then, but the budget must survive: the model cache's
+ free-VRAM cap needs it most in exactly that state."""
windows_rocm(_FakeGdi32([(20, OUR_BUS, OUR_DEVICE)], budget=15 * GIB, usage=17 * GIB))
- assert wddm.local_video_memory(DEVICE) == (15 * GIB, 16 * GIB) # the adapter's total
+ assert wddm.local_video_memory(DEVICE) == (15 * GIB, None)
assert wddm.video_memory_budget(DEVICE) == 15 * GIB
@@ -237,14 +237,13 @@ def test_paged_bytes_reads_this_process_on_the_devices_adapter(windows_rocm, mon
assert pdh.closed == 1
-def test_a_counter_this_build_does_not_have_only_disables_what_reads_it(windows_rocm, monkeypatch):
- """One query per counter: sharing one meant any missing counter took every PDH-backed answer with it."""
+def test_a_missing_counter_answers_unknown(windows_rocm, monkeypatch):
+ """A Windows without the ``GPU Process Memory`` counters makes the paged amount unknown instead of failing."""
windows_rocm(_FakeGdi32([(20, OUR_BUS, OUR_DEVICE)]))
pdh = _FakePdh({_instance(os.getpid(), 20): 3 * GIB}, unavailable=(r"\GPU Process Memory(*)\Shared Usage",))
monkeypatch.setattr(wddm, "_load_pdh", functools.lru_cache(maxsize=1)(lambda: pdh))
assert wddm.paged_bytes(DEVICE) is None
- assert wddm.local_video_memory(DEVICE) is not None, "a D3DKMT answer does not depend on the counters"
def test_an_instance_with_invalid_data_is_skipped(windows_rocm, monkeypatch):