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): tile on the budget and our own residency, not on an adapter counter

Alexander Eichhornbbd71a1470c0
diff --git a/invokeai/backend/util/vae_working_memory.py b/invokeai/backend/util/vae_working_memory.py
index 1eb19c55f3..335889948c 100644
--- a/invokeai/backend/util/vae_working_memory.py
+++ b/invokeai/backend/util/vae_working_memory.py
@@ -31,21 +31,25 @@ def should_pretile_vae_decode(
decode just runs very slowly. ``device`` is where the VAE runs: a ``cpu_only`` VAE (and MPS, sharing system
memory) is never tiled on these grounds.
- On Windows the card's nameplate total is not what this decode can have: what the rest of the card is holding is.
- The cache evicts Invoke's own models to honour the reservation, so the ceiling is the total minus what *other*
- processes hold (`wddm.other_process_local_bytes`). Measured on an RX 9060 XT (16 GB), neither figure Windows
- reports answers that on its own: with another program holding 8 GiB and Invoke idle the budget still read
- 15.09 GiB while only ~7.7 GiB could be had, and with Invoke holding 12 GiB and nothing else on the card the
- budget read 7.62 GiB although releasing its own models would have freed almost all of it. Where the counters
- cannot answer, the budget is the fallback: too pessimistic mid-session, but never too optimistic.
+ 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
+ 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
+ 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.
"""
if device.type == "cuda":
total_bytes = torch.cuda.get_device_properties(device).total_memory
- budget_bytes = wddm.video_memory_budget(device)
- if budget_bytes is not None:
- other_bytes = wddm.other_process_local_bytes(device)
- ceiling = total_bytes - other_bytes if other_bytes is not None else budget_bytes
- total_bytes = min(total_bytes, ceiling)
+ 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))
elif device.type == "xpu":
total_bytes = torch.xpu.get_device_properties(device).total_memory
else:
@@ -723,7 +727,9 @@ def qwen_image_untiled_decode_peak_bytes(
"""What an untiled decode of this latent is expected to peak at, for the up-front tiling decision only.
Reservations keep using `estimate_vae_working_memory_qwen_image`, which is deliberately conservative. Between two
- measured points this takes the larger of the two; past the last one it takes that reservation figure, since a
+ measured points this is the chord between them in bytes -- so an interior area can price below either neighbour's
+ per-pixel constant, which is the point: the constant dips while the bytes rise, and taking the larger neighbour
+ priced a smaller image above a larger one. Past the last measured area it takes the reservation figure, since a
decode larger than anything measured is not one to guess low about.
"""
h = LATENT_SCALE_FACTOR * image_tensor.shape[-2]
@@ -733,20 +739,23 @@ def qwen_image_untiled_decode_peak_bytes(
points = _QWEN_VAE_MEASURED_DECODE_PEAKS["rocm" if is_rocm else "cuda"]
area = h * w
- measured = dict(points)
- if area in measured:
- constant = measured[area]
- elif area > points[-1][0]:
+ if area > points[-1][0]:
constant = _QWEN_VAE_RESERVATION_CONSTANTS["rocm" if is_rocm else "cuda"]["decode"]
- else:
- previous = points[0][1]
- constant = previous
- for measured_area, peak in points:
- if measured_area > area:
- constant = max(previous, peak)
- break
- previous = peak
- return h * w * element_size * constant
+ return h * w * element_size * constant
+ # Interpolate the bytes, not the constant: the per-pixel figure dips (ROCm 3273 at 1536^2, CUDA 2281 at 1792^2)
+ # while the bytes themselves rise with area, so taking the larger neighbouring constant priced a smaller image
+ # above a larger one -- a 1728x1856 CUDA decode at 15.96 GiB against 1792^2 at 13.64 GiB. Measured points keep
+ # their measured value.
+ previous_area, previous_bytes = 0, 0
+ for measured_area, peak in points:
+ measured_bytes = measured_area * peak
+ if measured_area >= area:
+ if measured_area == area or previous_area == 0:
+ return int(area * element_size * peak)
+ span = (measured_bytes - previous_bytes) / (measured_area - previous_area)
+ return int(element_size * (previous_bytes + span * (area - previous_area)))
+ previous_area, previous_bytes = measured_area, measured_bytes
+ raise AssertionError("areas past the measured range are handled above")
def estimate_vae_working_memory_qwen_image(
diff --git a/invokeai/backend/util/wddm.py b/invokeai/backend/util/wddm.py
index 89f9d1010b..64405508ac 100644
--- a/invokeai/backend/util/wddm.py
+++ b/invokeai/backend/util/wddm.py
@@ -38,10 +38,8 @@ _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"
-# Adapter-wide, i.e. every process on the adapter. Per-process attribution from `GPU Process Memory` was
-# measured to mix up its instances while two processes shared the card, so what "other processes hold" is
-# derived from this figure and torch's own-usage view instead.
-_PDH_ADAPTER_USAGE_COUNTER = r"\GPU Adapter Memory(*)\Dedicated Usage"
+# PDH_CSTATUS_VALID_DATA and PDH_CSTATUS_NEW_DATA; any other status leaves `largeValue` undefined.
+_PDH_VALID_DATA = (0x00000000, 0x00000001)
# Win32 types spelled as fixed-width ctypes, so this module imports on every platform.
@@ -142,9 +140,9 @@ _lock = threading.Lock()
_adapters: dict[int, Optional[_Adapter]] = {}
_pdh_lock = threading.Lock()
-# The PDH query and its counters, opened on first use: (query, {counter name: handle}).
-_pdh_query: Optional[tuple[ctypes.c_void_p, dict[str, ctypes.c_void_p]]] = None
-_pdh_attempted = False
+# 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]]] = {}
def _supported(device: torch.device) -> bool:
@@ -281,11 +279,11 @@ def _adapter_for(device: torch.device) -> Optional[tuple[ctypes.CDLL, _Adapter]]
return None if adapter is None else (lib, 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.
+def local_video_memory(device: torch.device) -> Optional[tuple[int, 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. It is 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 something implausible. Called per
+ generation and per decode, so every failure answers "unknown" here rather than reaching those callers.
"""
if not _supported(device):
return None
@@ -299,24 +297,47 @@ def video_memory_budget(device: torch.device) -> Optional[int]:
return None
if not 0 < info.Budget <= adapter.total_bytes:
return None
- return int(info.Budget)
+ # 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))
except Exception:
- InvokeAILogger.get_logger(__name__).debug(f"WDDM budget lookup for {device} failed", exc_info=True)
+ InvokeAILogger.get_logger(__name__).debug(f"WDDM memory lookup for {device} failed", exc_info=True)
return None
-def _open_gpu_memory_query(pdh: ctypes.CDLL) -> Optional[tuple[ctypes.c_void_p, dict[str, ctypes.c_void_p]]]:
+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."""
+ local = local_video_memory(device)
+ return None if local is None else local[0]
+
+
+def _open_counter_query(pdh: ctypes.CDLL, path: str) -> 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
- counters: dict[str, ctypes.c_void_p] = {}
- for name, path in (("shared", _PDH_SHARED_USAGE_COUNTER), ("adapter", _PDH_ADAPTER_USAGE_COUNTER)):
- counter = ctypes.c_void_p()
- if pdh.PdhAddEnglishCounterW(query, path, None, ctypes.byref(counter)) != 0:
- pdh.PdhCloseQuery(query)
- return None
- counters[name] = counter
- return query, counters
+ counter = ctypes.c_void_p()
+ if pdh.PdhAddEnglishCounterW(query, path, None, ctypes.byref(counter)) != 0:
+ pdh.PdhCloseQuery(query)
+ return None
+ return query, counter
+
+
+def _counter_values(path: str) -> dict[str, int]:
+ """That counter's value per instance, collected once. ``{}`` when the counter or the loader is unavailable."""
+ pdh = _load_pdh()
+ if pdh is None:
+ return {}
+ with _pdh_lock:
+ try:
+ if path not in _pdh_queries:
+ _pdh_queries[path] = _open_counter_query(pdh, path)
+ opened = _pdh_queries[path]
+ if opened is None:
+ return {}
+ return _usage_by_instance(pdh, *opened)
+ except Exception:
+ return {}
def _usage_by_instance(pdh: ctypes.CDLL, query: ctypes.c_void_p, counter: ctypes.c_void_p) -> dict[str, int]:
@@ -332,7 +353,11 @@ def _usage_by_instance(pdh: ctypes.CDLL, query: ctypes.c_void_p, counter: ctypes
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}
+ return {
+ items[i].szName.lower(): int(items[i].FmtValue.largeValue)
+ for i in range(count.value)
+ if items[i].szName and items[i].FmtValue.CStatus in _PDH_VALID_DATA
+ }
def paged_bytes(device: torch.device) -> Optional[int]:
@@ -342,80 +367,23 @@ def paged_bytes(device: torch.device) -> Optional[int]:
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).
+ The first call opens this counter's 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:
+ if resolved is None:
return None
instance = f"pid_{os.getpid()}_{_adapter_instance(resolved[1].luid)}"
- with _pdh_lock:
- try:
- if not _pdh_attempted:
- _pdh_attempted = True
- _pdh_query = _open_gpu_memory_query(pdh)
- if _pdh_query is None:
- return None
- query, counters = _pdh_query
- return _usage_by_instance(pdh, query, counters["shared"]).get(instance)
- except Exception:
- return None
+ return _counter_values(_PDH_SHARED_USAGE_COUNTER).get(instance)
def _adapter_instance(luid: int) -> str:
return f"luid_0x{(luid >> 32) & 0xFFFFFFFF:08x}_0x{luid & 0xFFFFFFFF:08x}_phys_0"
-def other_process_local_bytes(device: torch.device) -> Optional[int]:
- """Dedicated video memory on the device's adapter held by processes other than this one.
-
- This is what bounds how large an allocation this process could still make after releasing everything of its own,
- and it is the figure the budget does not answer. Measured on an RX 9060 XT (16 GB): with another program holding
- 8 GiB and Invoke idle, the budget still reported 15.09 GiB while only ~7.7 GiB could be had; with Invoke itself
- holding 12 GiB and nothing else on the card, the budget read 7.62 GiB while releasing its own memory would have
- freed almost the whole card.
-
- ``None`` off Windows ROCm and whenever the counters cannot answer. One PDH sample, so a process that takes memory
- in the same instant is missed; the model cache's own per-load measurement is what catches that.
- """
- 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
- instance = _adapter_instance(resolved[1].luid)
- with _pdh_lock:
- try:
- if not _pdh_attempted:
- _pdh_attempted = True
- _pdh_query = _open_gpu_memory_query(pdh)
- if _pdh_query is None:
- return None
- query, counters = _pdh_query
- adapter_bytes = _usage_by_instance(pdh, query, counters["adapter"]).get(instance)
- except Exception:
- return None
- if adapter_bytes is None:
- return None
- try:
- free_bytes, total_bytes = torch.cuda.mem_get_info(device)
- except Exception:
- return None
- # On a ROCm build under Windows torch's free figure is the total minus this process's own allocations.
- return max(0, adapter_bytes - (total_bytes - free_bytes))
-
-
def reset_cache() -> None:
"""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()
@@ -426,8 +394,10 @@ def reset_cache() -> None:
_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])
+ opened_queries = [opened for opened in _pdh_queries.values() if opened is not None]
+ _pdh_queries.clear()
+ pdh = _load_pdh() if opened_queries else None
+ if pdh is not None:
+ for query, _counter in opened_queries:
+ pdh.PdhCloseQuery(query)
_load_pdh.cache_clear()
diff --git a/tests/app/invocations/test_qwen_image_working_memory.py b/tests/app/invocations/test_qwen_image_working_memory.py
index d12c44b19f..49fd219fa0 100644
--- a/tests/app/invocations/test_qwen_image_working_memory.py
+++ b/tests/app/invocations/test_qwen_image_working_memory.py
@@ -551,6 +551,14 @@ class TestMeasuredDecodePeak:
"""`qwen_image_untiled_decode_peak_bytes` prices the tiling decision from the measured curve, so a decode whose
real peak fits is not tiled by a reservation's headroom."""
+ def _peak_hw(self, h: int, w: int, device: str = "cuda", hip: str | None = "7.2.0") -> int:
+ mock_vae = MagicMock(spec=AutoencoderKLQwenImage)
+ mock_vae.parameters.side_effect = lambda: iter([torch.zeros(1, dtype=torch.float16)])
+ with patch("torch.version.hip", hip):
+ return qwen_image_untiled_decode_peak_bytes(
+ torch.zeros(1, 16, 1, h // 8, w // 8), mock_vae, torch.device(device)
+ )
+
def _peak(self, px: int, device: str = "cuda", hip: str | None = "7.2.0") -> int:
mock_vae = MagicMock(spec=AutoencoderKLQwenImage)
mock_vae.parameters.side_effect = lambda: iter([torch.zeros(1, dtype=torch.float16)])
@@ -563,9 +571,21 @@ class TestMeasuredDecodePeak:
def test_a_measured_point_is_its_measured_peak(self, px, constant):
assert self._peak(px) == px * px * 2 * constant
- def test_between_two_points_takes_the_larger(self):
- # 1280^2 sits between the 1024^2 (4570) and 1536^2 (3273) measurements.
- assert self._peak(1280) == 1280 * 1280 * 2 * 4570
+ def test_between_two_points_interpolates_the_bytes(self):
+ """The per-pixel figure dips at 1536^2 while the bytes keep rising, so the bytes are what gets interpolated:
+ taking the larger neighbouring constant priced a smaller image above a larger one."""
+ at_1024 = self._peak(1024)
+ at_1536 = self._peak(1536)
+ at_1280 = self._peak(1280)
+
+ assert at_1024 < at_1280 < at_1536, "monotonic in area"
+ # 1280^2 sits between the 1024^2 and 1536^2 measurements; the chord between them decides it.
+ span = (at_1536 - at_1024) / (1536**2 - 1024**2)
+ 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."""
+ assert self._peak_hw(1728, 1856, hip=None) <= self._peak_hw(1792, 1792, hip=None)
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 ae9404d21a..0900aea209 100644
--- a/tests/backend/util/test_vae_pretile.py
+++ b/tests/backend/util/test_vae_pretile.py
@@ -53,8 +53,7 @@ def test_the_pretile_gate_uses_the_memory_the_device_will_keep_resident(monkeypa
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
generation just crawls. Measured against the card total the decode looks fine (13.3 < 14.4 GiB),
- so it is not tiled. With no adapter-wide reading available this is the budget's own case; the
- tests below cover what the gate does when it can tell whose memory it is.
+ so it is not tiled.
"""
total_bytes = 16 * 2**30
budget_bytes = int(12.5 * 2**30)
@@ -64,12 +63,9 @@ def test_the_pretile_gate_uses_the_memory_the_device_will_keep_resident(monkeypa
# 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 the name directly, so a fix routing through
- # `TorchDevice.cuda_mem_get_info` and one calling `wddm.video_memory_budget` are both covered.
+ # 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)
- monkeypatch.setattr("invokeai.backend.util.wddm.video_memory_budget", lambda device: budget_bytes)
- # Without this the gate reads the real card here, and any foreign usage below ~1.2 GiB flips the case.
- monkeypatch.setattr("invokeai.backend.util.wddm.other_process_local_bytes", lambda device: None)
+ monkeypatch.setattr("invokeai.backend.util.wddm.local_video_memory", lambda device: (budget_bytes, 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"
@@ -77,48 +73,43 @@ def test_the_pretile_gate_uses_the_memory_the_device_will_keep_resident(monkeypa
assert should_pretile_vae_decode(torch.device("cuda", 0), estimate) is True
-def test_a_budget_trimmed_by_our_own_residency_does_not_tile_a_decode_that_fits(monkeypatch):
- """Windows trims the budget when the process itself grows -- measured on an RX 9060 XT, 15.09 GiB until it passes
- about 12 of 16 GiB, then 7.62. The cache evicts those models for the reservation, so a decode that fits must not
- be tiled on that reading: it tiled a 7.0 GiB Z-Image decode against a 6.9 GiB line mid-session, which changed
- output that had been pixel-identical."""
+def test_a_budget_below_our_own_residency_does_not_tile_a_decode_that_fits(monkeypatch):
+ """Windows trims the budget as the process itself grows -- measured on an RX 9060 XT, 15.09 GiB until it passes
+ about 12 of 16 GiB, then 7.62, i.e. below what it already holds. That is an instruction to trim itself, which the
+ cache does for the reservation, so the ceiling is what it holds: comparing against the bare budget tiled a 7.0 GiB
+ Z-Image decode against a 6.9 GiB line mid-session and changed output that had been pixel-identical."""
total_bytes = 16 * 2**30
estimate = 7 * 2**30
monkeypatch.setattr("torch.cuda.get_device_properties", lambda device: MagicMock(total_memory=total_bytes))
- # 12 GiB of our own models resident, and nothing else on the card.
monkeypatch.setattr("torch.cuda.mem_get_info", lambda device: (4 * 2**30, total_bytes))
- monkeypatch.setattr("invokeai.backend.util.wddm.video_memory_budget", lambda device: int(7.6 * 2**30))
- monkeypatch.setattr("invokeai.backend.util.wddm.other_process_local_bytes", lambda device: 0)
+ monkeypatch.setattr("invokeai.backend.util.wddm.local_video_memory", lambda device: (int(7.6 * 2**30), 12 * 2**30))
assert should_pretile_vae_decode(torch.device("cuda", 0), estimate) is False
-def test_another_process_holding_the_card_tiles_even_while_the_budget_looks_fine(monkeypatch):
- """The case the budget does not answer: measured with another program holding 8 GiB and Invoke idle, the budget
- still read 15.09 GiB although only ~7.7 GiB could be had. Evicting Invoke's own models cannot recover memory it
- does not hold, so a 8.9 GiB Qwen-Image decode has to be tiled here."""
+def test_a_decode_beyond_both_the_budget_and_our_residency_is_tiled(monkeypatch):
+ """The combined state -- something else holds part of the card and Invoke holds the rest -- is the one where the
+ budget does carry the foreign pressure: evicting everything of ours reaches our own usage, not the whole card."""
total_bytes = 16 * 2**30
- estimate = int(8.9 * 2**30)
+ 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))
- # Invoke holds almost nothing; torch's free figure does not see the other process at all.
- monkeypatch.setattr("torch.cuda.mem_get_info", lambda device: (total_bytes - 2**28, total_bytes))
- monkeypatch.setattr("invokeai.backend.util.wddm.video_memory_budget", lambda device: int(15.09 * 2**30))
- monkeypatch.setattr("invokeai.backend.util.wddm.other_process_local_bytes", lambda device: 8 * 2**30)
+ 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))
+ )
- assert estimate < VAE_PRETILE_VRAM_FRACTION * total_bytes, "the card total and the budget both look fine"
+ 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
-def test_the_budget_is_the_fallback_when_the_counters_cannot_answer(monkeypatch):
- """No adapter-wide figure means no way to tell whose memory it is; the budget is then the conservative answer."""
+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
- 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.video_memory_budget", lambda device: int(7.6 * 2**30))
- monkeypatch.setattr("invokeai.backend.util.wddm.other_process_local_bytes", lambda device: None)
+ monkeypatch.setattr("invokeai.backend.util.wddm.local_video_memory", lambda device: None)
- assert should_pretile_vae_decode(torch.device("cuda", 0), estimate) is True
+ assert should_pretile_vae_decode(torch.device("cuda", 0), 7 * 2**30) is False
+ assert should_pretile_vae_decode(torch.device("cuda", 0), 15 * 2**30) is True
diff --git a/tests/backend/util/test_wddm.py b/tests/backend/util/test_wddm.py
index de7209c72e..2ec16a9ae1 100644
--- a/tests/backend/util/test_wddm.py
+++ b/tests/backend/util/test_wddm.py
@@ -26,32 +26,38 @@ def _luid_low(handle: int) -> int:
class _FakePdh:
- """A PDH with the module's two counters: per-process shared usage, and adapter-wide dedicated usage."""
-
- def __init__(self, instances: dict[str, int], adapter_instances: dict[str, int] | None = None):
+ """A PDH that reports the given ``GPU Process Memory`` instances' shared usage."""
+
+ def __init__(
+ self,
+ instances: dict[str, int],
+ unavailable: tuple[str, ...] = (),
+ invalid: tuple[str, ...] = (),
+ ):
self.instances = instances
- self.adapter_instances = adapter_instances or {}
+ self.unavailable = unavailable
+ self.invalid = invalid
self.counter_paths: list[str] = []
self.closed = 0
self._alive: list[object] = []
- self._by_handle: dict[int, dict[str, int]] = {}
def PdhOpenQueryW(self, source, user_data, query_ref):
query_ref._obj.value = 1
return 0
def PdhAddEnglishCounterW(self, query, path, user_data, counter_ref):
+ if path in self.unavailable:
+ return -1073738824 # PDH_CSTATUS_NO_COUNTER
self.counter_paths.append(path)
handle = 2 + len(self.counter_paths)
counter_ref._obj.value = handle
- self._by_handle[handle] = self.adapter_instances if "Adapter" in path else self.instances
return 0
def PdhCollectQueryData(self, query):
return 0
def PdhGetFormattedCounterArrayW(self, counter, fmt, size_ref, count_ref, buffer):
- instances = self._by_handle[counter.value if hasattr(counter, "value") else counter]
+ instances = self.instances
count = len(instances)
if buffer is None:
size_ref._obj.value = ctypes.sizeof(wddm._PdhCounterValueItem) * count
@@ -61,6 +67,8 @@ class _FakePdh:
for item, (name, value) in zip(items, instances.items(), strict=True):
item.szName = name
item.FmtValue.largeValue = value
+ if name in self.invalid:
+ item.FmtValue.CStatus = 0xC0000BB8 # PDH_CSTATUS_INVALID_DATA
self._alive.append(items) # the name buffers live as long as the array object
count_ref._obj.value = count
return 0
@@ -73,9 +81,10 @@ class _FakePdh:
class _FakeGdi32:
"""Adapters as (handle, bus, device); every thunk returns NTSTATUS 0 unless told otherwise."""
- def __init__(self, adapters, budget=15 * GIB, query_status=0):
+ def __init__(self, adapters, budget=15 * GIB, usage=0, 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] = []
@@ -101,7 +110,7 @@ class _FakeGdi32:
def D3DKMTQueryVideoMemoryInfo(self, ref):
info = ref._obj
- info.Budget = self.budget
+ info.Budget, info.CurrentUsage = self.budget, self.usage
return self.query_status
def D3DKMTCloseAdapter(self, ref):
@@ -142,6 +151,16 @@ 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):
+ """`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."""
+ 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.video_memory_budget(DEVICE) == 15 * GIB
+
+
@pytest.mark.parametrize(
("adapters", "kwargs"),
[
@@ -210,45 +229,32 @@ def test_paged_bytes_reads_this_process_on_the_devices_adapter(windows_rocm, mon
assert wddm.paged_bytes(DEVICE) == 3 * GIB
assert wddm.paged_bytes(DEVICE) == 3 * GIB
- assert pdh.counter_paths == [
- r"\GPU Process Memory(*)\Shared Usage",
- r"\GPU Adapter Memory(*)\Dedicated Usage",
- ], "one query with both counters, opened on first use"
+ assert pdh.counter_paths == [r"\GPU Process Memory(*)\Shared Usage"], (
+ "only the counter this answer needs, opened once"
+ )
wddm.reset_cache()
assert pdh.closed == 1
-def _adapter_instance(handle: int) -> str:
- return f"luid_0x00000000_0x{_luid_low(handle):08x}_phys_0"
-
-
- ("adapter_gib", "ours_gib", "expected_gib"),
- [(8.4, 0.2, 8.2), (12.2, 12.1, 0.0), (0.2, 6.0, 0.0)],
- ids=["another-process-holds-the-card", "all-of-it-is-ours", "adapter-reads-below-our-own"],
-)
-def test_other_process_local_bytes_subtracts_our_own_usage(
- windows_rocm, monkeypatch, adapter_gib, ours_gib, expected_gib
-):
- """What bounds a decode is what OTHER processes hold: the budget does not track them (measured 15.09 GiB next to
- an 8 GiB holder), and the per-process PDH counter swapped its instances while two processes shared the card, so
- this comes from the adapter-wide figure minus torch's own-usage view. A reading below our own clamps to zero."""
+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."""
windows_rocm(_FakeGdi32([(20, OUR_BUS, OUR_DEVICE)]))
- total = 16 * GIB
- pdh = _FakePdh({}, adapter_instances={_adapter_instance(20): int(adapter_gib * GIB)})
+ 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))
- monkeypatch.setattr(torch.cuda, "mem_get_info", lambda device: (total - int(ours_gib * GIB), total))
- assert wddm.other_process_local_bytes(DEVICE) == pytest.approx(int(expected_gib * GIB), abs=GIB // 10)
+ 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_other_process_local_bytes_is_unknown_without_an_adapter_reading(windows_rocm, monkeypatch):
+def test_an_instance_with_invalid_data_is_skipped(windows_rocm, monkeypatch):
+ """PDH leaves `largeValue` undefined unless the item's status says the data is good."""
windows_rocm(_FakeGdi32([(20, OUR_BUS, OUR_DEVICE)]))
- pdh = _FakePdh({}, adapter_instances={_adapter_instance(21): 8 * GIB}) # a different adapter
+ me = _instance(os.getpid(), 20)
+ pdh = _FakePdh({me: 7 * GIB}, invalid=(me,))
monkeypatch.setattr(wddm, "_load_pdh", functools.lru_cache(maxsize=1)(lambda: pdh))
- assert wddm.other_process_local_bytes(DEVICE) is None
+ assert wddm.paged_bytes(DEVICE) is None
def test_paged_bytes_is_unknown_before_this_process_used_the_adapter(windows_rocm, monkeypatch):