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): decide tiling on what other processes hold, not on the budget

Alexander Eichhorn355595ffe3a1
diff --git a/invokeai/backend/model_manager/load/model_cache/model_cache.py b/invokeai/backend/model_manager/load/model_cache/model_cache.py
index fa049ef659..c64bc9fe69 100644
--- a/invokeai/backend/model_manager/load/model_cache/model_cache.py
+++ b/invokeai/backend/model_manager/load/model_cache/model_cache.py
@@ -2557,8 +2557,12 @@ class ModelCache:
# 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. When a peer device is mid-session that release is
- # deferred, and the bytes just freed are credited to the measurement instead -- they sit in
- # this process's allocator, which reuses them for the load this is making room for.
+ # deferred, and the bytes just freed are credited to the measurement instead. That credit is
+ # the same optimistic figure `_get_reclaimable_allocator_bytes` refuses to grant -- the
+ # allocator holds those bytes, but a large contiguous allocation may not be servable from
+ # them -- so it is deliberately loop-local: it stops this loop offloading everything, and
+ # the load that follows re-measures for itself (`lock`, `make_room_in_vram`) and streams
+ # from RAM if the room did not materialize.
empty_cache_per_offload = _expandable_segments_enabled()
vram_bytes_freed_uncounted = 0
# TODO(ryand): Give more thought to the offloading policy used here.
diff --git a/invokeai/backend/util/vae_working_memory.py b/invokeai/backend/util/vae_working_memory.py
index 9c0daa81bb..1eb19c55f3 100644
--- a/invokeai/backend/util/vae_working_memory.py
+++ b/invokeai/backend/util/vae_working_memory.py
@@ -31,20 +31,21 @@ 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.
- Where Windows grants a video-memory budget, that budget bounds the card's nameplate total: it is the point past
- which Windows pages this process out, and another GPU process lowers it within about a second. What the decode
- may claim is the budget plus whatever this process already holds, because the cache evicts models to make room
- for the reservation -- measured on an RX 9060 XT, Windows keeps the budget at 15.09 GiB until the process passes
- about 12 GiB and then halves it to 7.62, so comparing against the bare budget mid-session tiles a decode that
- fits (a 7.0 GiB decode against a 6.9 GiB line, with output that is not pixel-identical).
+ 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.
"""
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:
- # On a ROCm build under Windows torch's free figure is the total minus this process's own allocations.
- free_bytes, _total = torch.cuda.mem_get_info(device)
- total_bytes = min(total_bytes, budget_bytes + (total_bytes - free_bytes))
+ 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)
elif device.type == "xpu":
total_bytes = torch.xpu.get_device_properties(device).total_memory
else:
@@ -677,24 +678,43 @@ def estimate_vae_working_memory_wan(
# What a full-frame Qwen-Image VAE decode was actually measured to peak at, per output pixel-byte, against the output
-# area it was measured at. The largest of the measured ROCm cards at each point (the per-point table in
-# `estimate_vae_working_memory_qwen_image`, W7900 column; the RX 9060 XT measures 2650-2772 throughout), and the CUDA
-# maximum for everything else.
+# area it was measured at -- the per-point table in `estimate_vae_working_memory_qwen_image`, taking the larger of the
+# measured ROCm cards at each point (the W7900 column; the RX 9060 XT measures 2650-2772 throughout).
#
# This exists because the shipped constants are one flat figure fitted to the worst point of a curve that is not
# flat, across cards that differ by up to 1.9x. That is the right figure to *reserve* -- a reservation that is too
# small is an out-of-memory error or, on Windows, a decode paged into system memory. It is the wrong figure to decide
# tiling with: a tiled decode is not pixel-identical, so a 1536^2 decode whose real peak is 14.4 GiB must not be
# tiled on a 24 GiB card because a flat 5500 prices it at 24.2 GiB.
-_QWEN_VAE_MEASURED_DECODE_PEAKS: tuple[tuple[int, int], ...] = (
- (512 * 512, 5132),
- (768 * 768, 4596),
- (1024 * 1024, 4570),
- (1536 * 1536, 3273),
- (1792 * 1792, 3735),
- (2048 * 2048, 4813),
-)
-_QWEN_VAE_MEASURED_DECODE_PEAK_CUDA = 2690
+#
+# Neither column is extrapolated. Past its last measured area the decision falls back to the reservation constant,
+# which is what "we have not measured this, assume the conservative figure" has to mean here: CUDA's grid ends at
+# 1792^2 because 2048^2 ran out of memory on the card it was measured on, and carrying a flat maximum past that point
+# priced a 2048^2 decode 0.6 GiB under a 24 GiB card's line while its own reservation exceeded the whole card.
+# What the estimator reserves per output pixel-byte: the worst measured point of each backend's column plus ~8%
+# headroom (the per-point grid is in `estimate_vae_working_memory_qwen_image`).
+_QWEN_VAE_RESERVATION_CONSTANTS: dict[str, dict[str, int]] = {
+ "rocm": {"decode": 5500, "encode": 6300},
+ "cuda": {"decode": 2900, "encode": 1600},
+}
+
+_QWEN_VAE_MEASURED_DECODE_PEAKS: dict[str, tuple[tuple[int, int], ...]] = {
+ "rocm": (
+ (512 * 512, 5132),
+ (768 * 768, 4596),
+ (1024 * 1024, 4570),
+ (1536 * 1536, 3273),
+ (1792 * 1792, 3735),
+ (2048 * 2048, 4813),
+ ),
+ "cuda": (
+ (512 * 512, 2660),
+ (768 * 768, 2519),
+ (1024 * 1024, 2690),
+ (1536 * 1536, 2671),
+ (1792 * 1792, 2281),
+ ),
+}
def qwen_image_untiled_decode_peak_bytes(
@@ -703,26 +723,25 @@ 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, and beyond the largest measured area the largest of all: the
- curve is not monotonic, and a decode that big is tiled on any card either way.
+ measured points this takes the larger of the two; past the last one it takes that reservation figure, since a
+ decode larger than anything measured is not one to guess low about.
"""
h = LATENT_SCALE_FACTOR * image_tensor.shape[-2]
w = LATENT_SCALE_FACTOR * image_tensor.shape[-1]
element_size = next(vae.parameters()).element_size()
is_rocm = device.type == "cuda" and torch.version.hip is not None
- if not is_rocm:
- return h * w * element_size * _QWEN_VAE_MEASURED_DECODE_PEAK_CUDA
+ points = _QWEN_VAE_MEASURED_DECODE_PEAKS["rocm" if is_rocm else "cuda"]
area = h * w
- measured = dict(_QWEN_VAE_MEASURED_DECODE_PEAKS)
+ measured = dict(points)
if area in measured:
constant = measured[area]
- elif area > _QWEN_VAE_MEASURED_DECODE_PEAKS[-1][0]:
- constant = max(measured.values())
+ elif area > points[-1][0]:
+ constant = _QWEN_VAE_RESERVATION_CONSTANTS["rocm" if is_rocm else "cuda"]["decode"]
else:
- previous = _QWEN_VAE_MEASURED_DECODE_PEAKS[0][1]
+ previous = points[0][1]
constant = previous
- for measured_area, peak in _QWEN_VAE_MEASURED_DECODE_PEAKS:
+ for measured_area, peak in points:
if measured_area > area:
constant = max(previous, peak)
break
@@ -799,10 +818,7 @@ def estimate_vae_working_memory_qwen_image(
# the answer stays the build-wide one these constants were always selected by, so callers that pass no device
# (and tests that pin none) keep the figure they had.
is_rocm = torch.version.hip is not None and (device is None or device.type == "cuda")
- if operation == "decode":
- scaling_constant = 5500 if is_rocm else 2900
- else: # encode
- scaling_constant = 6300 if is_rocm else 1600
+ scaling_constant = _QWEN_VAE_RESERVATION_CONSTANTS["rocm" if is_rocm else "cuda"][operation]
if tile_size is not None and tile_size > 0:
# Bounded by one tile (plus overlap) rather than the full frame.
diff --git a/invokeai/backend/util/wddm.py b/invokeai/backend/util/wddm.py
index 376c900399..89f9d1010b 100644
--- a/invokeai/backend/util/wddm.py
+++ b/invokeai/backend/util/wddm.py
@@ -38,6 +38,10 @@ _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"
# Win32 types spelled as fixed-width ctypes, so this module imports on every platform.
@@ -138,8 +142,8 @@ _lock = threading.Lock()
_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
+# 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
@@ -221,9 +225,13 @@ def _resolve_adapter(lib: ctypes.CDLL, index: int) -> Optional[_Adapter]:
matches: list[_AdapterInfo] = []
pending = list(infos[: enum.NumAdapters])
+ current: list[_AdapterInfo] = []
try:
while pending:
- info = pending.pop()
+ # Held in `current` while it is processed: popped from `pending` and not yet in `matches`, a handle whose
+ # query raises would otherwise be the one handle the cleanup below misses.
+ current = [pending.pop()]
+ info = current[0]
address = _AdapterAddress()
query = _QueryAdapterInfo(
info.hAdapter,
@@ -238,10 +246,11 @@ def _resolve_adapter(lib: ctypes.CDLL, index: int) -> Optional[_Adapter]:
matches.append(info)
else:
_close(lib, info.hAdapter)
+ current = []
except Exception:
- # Every handle the enumeration opened belongs to this process until it is closed -- the ones matched so far
- # and the ones this loop never reached.
- for info in matches + pending:
+ # Every handle the enumeration opened belongs to this process until it is closed: the ones matched so far, the
+ # one being processed, and the ones this loop never reached.
+ for info in matches + current + pending:
_close(lib, info.hAdapter)
raise
@@ -296,19 +305,22 @@ def video_memory_budget(device: torch.device) -> Optional[int]:
return None
-def _open_shared_usage_query(pdh: ctypes.CDLL) -> Optional[tuple[ctypes.c_void_p, ctypes.c_void_p]]:
+def _open_gpu_memory_query(pdh: ctypes.CDLL) -> Optional[tuple[ctypes.c_void_p, dict[str, 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
+ 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
-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."""
+def _usage_by_instance(pdh: ctypes.CDLL, query: ctypes.c_void_p, counter: ctypes.c_void_p) -> dict[str, int]:
+ """Collect the query once; that counter's value per instance, keyed by its lower-case instance name."""
if pdh.PdhCollectQueryData(query) != 0:
return {}
size, count = ctypes.c_uint32(0), ctypes.c_uint32(0)
@@ -340,20 +352,66 @@ def paged_bytes(device: torch.device) -> Optional[int]:
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"
+ instance = f"pid_{os.getpid()}_{_adapter_instance(resolved[1].luid)}"
with _pdh_lock:
try:
if not _pdh_attempted:
_pdh_attempted = True
- _pdh_query = _open_shared_usage_query(pdh)
+ _pdh_query = _open_gpu_memory_query(pdh)
if _pdh_query is None:
return None
- return _shared_usage_by_instance(pdh, *_pdh_query).get(instance)
+ query, counters = _pdh_query
+ return _usage_by_instance(pdh, query, counters["shared"]).get(instance)
except Exception:
return None
+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
diff --git a/tests/app/invocations/test_qwen_image_working_memory.py b/tests/app/invocations/test_qwen_image_working_memory.py
index 9a1ae9ad53..d12c44b19f 100644
--- a/tests/app/invocations/test_qwen_image_working_memory.py
+++ b/tests/app/invocations/test_qwen_image_working_memory.py
@@ -567,11 +567,16 @@ class TestMeasuredDecodePeak:
# 1280^2 sits between the 1024^2 (4570) and 1536^2 (3273) measurements.
assert self._peak(1280) == 1280 * 1280 * 2 * 4570
- def test_past_the_measured_range_takes_the_largest(self):
- assert self._peak(3072) == 3072 * 3072 * 2 * 5132
-
- def test_a_cuda_card_is_priced_from_the_cuda_measurements(self):
- assert self._peak(1536, hip=None) == 1536 * 1536 * 2 * 2690
+ 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
+ leave a decode larger than anything measured untiled."""
+ assert self._peak(3072) == 3072 * 3072 * 2 * 5500
+
+ @pytest.mark.parametrize("px, constant", [(1024, 2690), (1536, 2671), (1792, 2281), (2048, 2900)])
+ def test_a_cuda_card_is_priced_from_the_cuda_measurements(self, px, constant):
+ """CUDA has its own curve, and its grid stops at 1792px because 2048px ran out of memory when it was
+ measured; past that point the reservation constant takes over rather than the last value seen."""
+ assert self._peak(px, hip=None) == px * px * 2 * constant
def test_the_peak_stays_under_the_reservation(self):
"""The reservation must remain the conservative figure of the two, or it would stop being an upper bound."""
diff --git a/tests/app/invocations/test_vae_working_memory_backend.py b/tests/app/invocations/test_vae_working_memory_backend.py
new file mode 100644
index 0000000000..5829d061af
--- /dev/null
+++ b/tests/app/invocations/test_vae_working_memory_backend.py
@@ -0,0 +1,63 @@
+"""Which convolution-backend constant the diffusers-AutoencoderKL estimators use.
+
+SD1/SDXL, SD3 and CogView4 run the same AutoencoderKL convolution stack as the FLUX.1 autoencoder, so they take the
+same measured per-backend constants: MIOpen needs ~1.64x what cuDNN does. The change is large enough to matter -- an
+SD1.5 1024px fp32 decode reserves 9.49 GB on cuDNN and 15.36 GB on MIOpen -- and the branch is invisible on a CUDA
+machine, so it is pinned here rather than left to whichever card the suite runs on.
+"""
+
+from unittest.mock import MagicMock, patch
+
+import pytest
+import torch
+from diffusers.models.autoencoders.autoencoder_kl import AutoencoderKL
+
+from invokeai.backend.util.vae_working_memory import (
+ estimate_vae_working_memory_cogview4,
+ estimate_vae_working_memory_sd3,
+ estimate_vae_working_memory_sd15_sdxl,
+)
+
+
+def _vae(dtype: torch.dtype = torch.float16) -> MagicMock:
+ vae = MagicMock(spec=AutoencoderKL)
+ vae.parameters.side_effect = lambda: iter([torch.zeros(1, dtype=dtype)])
+ return vae
+
+
+def _estimate(estimator, device: torch.device, hip: str | None):
+ latents = torch.zeros(1, 4, 64, 64) # 512px output
+ with (
+ patch("torch.version.hip", hip),
+ # The mid-block score matrix is the other term in these estimates and has its own tests; hold it at zero so
+ # the assertions below are about the convolution constant alone.
+ patch("invokeai.backend.util.vae_working_memory._vae_mid_block_score_matrix_bytes", return_value=0),
+ ):
+ if estimator is estimate_vae_working_memory_sd15_sdxl:
+ return estimator(
+ operation="decode", image_tensor=latents, vae=_vae(), tile_size=None, fp32=False, device=device
+ )
+ return estimator(operation="decode", image_tensor=latents, vae=_vae(), device=device)
+
+
+ESTIMATORS = [
+ pytest.param(estimate_vae_working_memory_sd15_sdxl, id="sd15-sdxl"),
+ pytest.param(estimate_vae_working_memory_sd3, id="sd3"),
+ pytest.param(estimate_vae_working_memory_cogview4, id="cogview4"),
+]
+
+
[email protected]("estimator", ESTIMATORS)
+def test_a_rocm_vae_reserves_the_miopen_constant(estimator):
+ assert _estimate(estimator, torch.device("cuda", 0), hip="7.2.0") == 512 * 512 * 2 * 3600
+
+
[email protected]("estimator", ESTIMATORS)
+def test_a_cuda_vae_reserves_the_cudnn_constant(estimator):
+ assert _estimate(estimator, torch.device("cuda", 0), hip=None) == 512 * 512 * 2 * 2200
+
+
[email protected]("estimator", ESTIMATORS)
+def test_a_cpu_only_vae_reserves_the_cudnn_constant_even_on_a_rocm_build(estimator):
+ """A `cpu_only` VAE does not run on MIOpen, so naming its device has to change the answer."""
+ assert _estimate(estimator, torch.device("cpu"), hip="7.2.0") == 512 * 512 * 2 * 2200
diff --git a/tests/app/util/test_torch_cuda_allocator.py b/tests/app/util/test_torch_cuda_allocator.py
index a226f889d4..d3461983ec 100644
--- a/tests/app/util/test_torch_cuda_allocator.py
+++ b/tests/app/util/test_torch_cuda_allocator.py
@@ -14,10 +14,23 @@ _ALLOCATOR_ENV_VARS = ("PYTORCH_ALLOC_CONF", "PYTORCH_CUDA_ALLOC_CONF", "PYTORCH
@pytest.fixture
-def rocm_windows(monkeypatch: pytest.MonkeyPatch):
- """A Windows ROCm install with no allocator configuration in the environment."""
+def rocm_windows(monkeypatch: pytest.MonkeyPatch, tmp_path):
+ """A Windows ROCm install with no allocator configuration in the environment.
+
+ `_installed_torch_is_rocm` has two sources -- the distribution version and `hip` in torch's own `version.py` --
+ so both are stubbed. Leaving the file lookup real made every case that expects "not ROCm" read the host's torch
+ and fail on any ROCm developer machine, which is this change's own test bench.
+ """
monkeypatch.setattr(sys, "platform", "win32")
monkeypatch.setattr(torch_cuda_allocator, "_installed_torch_version", lambda: "2.12.0+rocm7.14.1")
+ cuda_build = tmp_path / "torch"
+ cuda_build.mkdir()
+ (cuda_build / "version.py").write_text("hip: Optional[str] = None\n", encoding="utf-8")
+ monkeypatch.setattr(
+ torch_cuda_allocator.importlib.util,
+ "find_spec",
+ lambda name: SimpleNamespace(submodule_search_locations=[str(cuda_build)]),
+ )
monkeypatch.delitem(sys.modules, "torch") # as at startup, before anything imports it
for var in _ALLOCATOR_ENV_VARS:
# setenv first so teardown also removes what the code under test sets: delenv on an absent
diff --git a/tests/backend/ltx2/test_ltx2_real_files.py b/tests/backend/ltx2/test_ltx2_real_files.py
index 56557d790c..4adb08e4aa 100644
--- a/tests/backend/ltx2/test_ltx2_real_files.py
+++ b/tests/backend/ltx2/test_ltx2_real_files.py
@@ -194,9 +194,9 @@ def _accelerator() -> torch.device:
device = TorchDevice.choose_torch_device()
if device.type == "cpu":
pytest.skip("needs an accelerator")
- from invokeai.backend.util.attention import install_rocm_sdpa_head_dim_guard
+ from invokeai.backend.util.attention import install_rocm_sdpa_guard
- install_rocm_sdpa_head_dim_guard()
+ install_rocm_sdpa_guard()
return device
diff --git a/tests/backend/util/test_vae_pretile.py b/tests/backend/util/test_vae_pretile.py
index 79e208b833..ae9404d21a 100644
--- a/tests/backend/util/test_vae_pretile.py
+++ b/tests/backend/util/test_vae_pretile.py
@@ -53,7 +53,8 @@ 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.
+ 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.
"""
total_bytes = 16 * 2**30
budget_bytes = int(12.5 * 2**30)
@@ -67,6 +68,8 @@ def test_the_pretile_gate_uses_the_memory_the_device_will_keep_resident(monkeypa
# `TorchDevice.cuda_mem_get_info` and one calling `wddm.video_memory_budget` are both covered.
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)
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"
@@ -74,17 +77,48 @@ 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_the_gate_counts_memory_this_process_can_still_release(monkeypatch):
- """Windows halves the budget once the process passes about 12 of 16 GiB, i.e. below what it already holds. The
- cache evicts models for the reservation, so the ceiling is the budget plus this process's own allocations --
- measured: comparing against the bare budget tiled a 7.0 GiB Z-Image decode against a 6.9 GiB line mid-session,
- changing output that had been pixel-identical."""
+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."""
total_bytes = 16 * 2**30
estimate = 7 * 2**30
monkeypatch.setattr("torch.cuda.get_device_properties", lambda device: MagicMock(total_memory=total_bytes))
- # Mid-session: 12 GiB of models resident, and Windows has trimmed the budget to 7.6 GiB in response.
+ # 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)
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."""
+ total_bytes = 16 * 2**30
+ estimate = int(8.9 * 2**30)
+
+ 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)
+
+ assert estimate < VAE_PRETILE_VRAM_FRACTION * total_bytes, "the card total and the budget both look fine"
+ 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."""
+ 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)
+
+ assert should_pretile_vae_decode(torch.device("cuda", 0), estimate) is True
diff --git a/tests/backend/util/test_wddm.py b/tests/backend/util/test_wddm.py
index 5db03b5f52..de7209c72e 100644
--- a/tests/backend/util/test_wddm.py
+++ b/tests/backend/util/test_wddm.py
@@ -26,13 +26,15 @@ def _luid_low(handle: int) -> int:
class _FakePdh:
- """A PDH that reports the given ``GPU Process Memory`` instances' shared usage."""
+ """A PDH with the module's two counters: per-process shared usage, and adapter-wide dedicated usage."""
- def __init__(self, instances: dict[str, int]):
+ def __init__(self, instances: dict[str, int], adapter_instances: dict[str, int] | None = None):
self.instances = instances
+ self.adapter_instances = adapter_instances or {}
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
@@ -40,20 +42,23 @@ class _FakePdh:
def PdhAddEnglishCounterW(self, query, path, user_data, counter_ref):
self.counter_paths.append(path)
- counter_ref._obj.value = 2
+ 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):
- count = len(self.instances)
+ instances = self._by_handle[counter.value if hasattr(counter, "value") else counter]
+ count = len(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):
+ for item, (name, value) in zip(items, 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
@@ -205,12 +210,47 @@ 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"], "one query, opened on first use"
+ 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"
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."""
+ windows_rocm(_FakeGdi32([(20, OUR_BUS, OUR_DEVICE)]))
+ total = 16 * GIB
+ pdh = _FakePdh({}, adapter_instances={_adapter_instance(20): int(adapter_gib * GIB)})
+ 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)
+
+
+def test_other_process_local_bytes_is_unknown_without_an_adapter_reading(windows_rocm, monkeypatch):
+ windows_rocm(_FakeGdi32([(20, OUR_BUS, OUR_DEVICE)]))
+ pdh = _FakePdh({}, adapter_instances={_adapter_instance(21): 8 * GIB}) # a different adapter
+ monkeypatch.setattr(wddm, "_load_pdh", functools.lru_cache(maxsize=1)(lambda: pdh))
+
+ assert wddm.other_process_local_bytes(DEVICE) is None
+
+
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})