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): price up-front tiling from the measured peak and a stable ceiling

Alexander Eichhornfeb4d8e2ab20
diff --git a/invokeai/app/invocations/vae/qwen_image_latents_to_image.py b/invokeai/app/invocations/vae/qwen_image_latents_to_image.py
index f1f8312380..62b9f5eced 100644
--- a/invokeai/app/invocations/vae/qwen_image_latents_to_image.py
+++ b/invokeai/app/invocations/vae/qwen_image_latents_to_image.py
@@ -24,6 +24,7 @@ from invokeai.backend.util.qwen_image_vae import (
)
from invokeai.backend.util.vae_working_memory import (
estimate_vae_working_memory_qwen_image,
+ qwen_image_untiled_decode_peak_bytes,
should_pretile_vae_decode,
)
@@ -77,10 +78,15 @@ class QwenImageLatentsToImageInvocation(BaseInvocation, WithMetadata, WithBoard)
tile_size=effective_tile_size,
device=vae_info.compute_device,
)
+ # The tiling decision is priced from the measured peak, not from the reservation above: that one carries the
+ # headroom and cross-card conservatism a reservation needs, and tiling is not pixel-identical.
if (
not tiled
and config.auto_tiled_decode
- and should_pretile_vae_decode(vae_info.compute_device, estimated_working_memory)
+ and should_pretile_vae_decode(
+ vae_info.compute_device,
+ qwen_image_untiled_decode_peak_bytes(latents, vae_info.model, vae_info.compute_device),
+ )
):
tiled = True
effective_tile_size = resolve_qwen_image_vae_tile_size(self.tile_size)
diff --git a/invokeai/backend/util/vae_working_memory.py b/invokeai/backend/util/vae_working_memory.py
index 1bb90aa16c..18ccd0ea4a 100644
--- a/invokeai/backend/util/vae_working_memory.py
+++ b/invokeai/backend/util/vae_working_memory.py
@@ -10,7 +10,7 @@ from diffusers.models.autoencoders.autoencoder_tiny import AutoencoderTiny
from invokeai.app.invocations.constants import LATENT_SCALE_FACTOR
from invokeai.backend.flux.modules.autoencoder import AutoEncoder, resolve_tile_size
from invokeai.backend.util import wddm
-from invokeai.backend.util.attention import rocm_sdpa_chunks_math, sdpa_score_matrix_bytes
+from invokeai.backend.util.attention import sdpa_score_matrix_bytes
from invokeai.backend.util.devices import TorchDevice
from invokeai.backend.util.logging import InvokeAILogger
@@ -31,15 +31,20 @@ 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.
- The comparison is against the Windows video-memory budget where there is one, not the card's nameplate total:
- that budget is the point past which Windows pages this process out, and another GPU process lowers it within
- about a second. A decode measured against the total alone would look like it fits and then crawl.
+ 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).
"""
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:
- total_bytes = min(total_bytes, budget_bytes)
+ # 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))
elif device.type == "xpu":
total_bytes = torch.xpu.get_device_properties(device).total_memory
else:
@@ -121,7 +126,7 @@ def estimate_vae_working_memory_sd15_sdxl(
# max, not sum: the mid-block attention and the full-resolution convolutions peak in
# different phases of the forward (see the FLUX.2 estimator for the measurements).
score_dtype = torch.float32 if fp32 else next(vae.parameters()).dtype
- working_memory = max(working_memory, _vae_mid_block_score_matrix_bytes(h, w, score_dtype))
+ working_memory = max(working_memory, _vae_mid_block_score_matrix_bytes(h, w, score_dtype, device=device))
if fp32:
# If we are running in FP32, then we should account for the likely increase in model size (~250MB).
@@ -151,7 +156,9 @@ def estimate_vae_working_memory_cogview4(
# max, not sum: the mid-block attention and the full-resolution convolutions peak in different
# phases of the forward (see the FLUX.2 estimator for the measurements).
- return int(max(working_memory, _vae_mid_block_score_matrix_bytes(h, w, next(vae.parameters()).dtype)))
+ return int(
+ max(working_memory, _vae_mid_block_score_matrix_bytes(h, w, next(vae.parameters()).dtype, device=device))
+ )
# What a tiled decode does *not* bound: the assembled image, several times over, per output pixel.
@@ -549,6 +556,60 @@ def estimate_vae_working_memory_wan(
return int(per_frame + clip_bytes)
+# 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.
+#
+# 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
+
+
+def qwen_image_untiled_decode_peak_bytes(
+ image_tensor: torch.Tensor, vae: AutoencoderKLQwenImage, device: torch.device
+) -> int:
+ """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.
+ """
+ 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
+
+ area = h * w
+ measured = dict(_QWEN_VAE_MEASURED_DECODE_PEAKS)
+ if area in measured:
+ constant = measured[area]
+ elif area > _QWEN_VAE_MEASURED_DECODE_PEAKS[-1][0]:
+ constant = max(measured.values())
+ else:
+ previous = _QWEN_VAE_MEASURED_DECODE_PEAKS[0][1]
+ constant = previous
+ for measured_area, peak in _QWEN_VAE_MEASURED_DECODE_PEAKS:
+ if measured_area > area:
+ constant = max(previous, peak)
+ break
+ previous = peak
+ return h * w * element_size * constant
+
+
def estimate_vae_working_memory_qwen_image(
operation: Literal["encode", "decode"],
image_tensor: torch.Tensor,
@@ -608,20 +669,18 @@ def estimate_vae_working_memory_qwen_image(
# materialised seq^2 score matrix), i.e. XPU gets an efficient kernel and is in the same
# O(area) regime as CUDA. If a future driver regresses to math attention, this branch --
# not the constants -- is what needs to change.
- # On ROCm the figures above were measured while a math-kernel attention call built its whole score matrix. Where
- # the guard bounds that call (`rocm_sdpa_chunks_math`), the super-linear term is gone and the curve is flat and
- # linear again -- measured 2026-09-23 on an RX 9060 XT (gfx1200, torch 2.12+rocm7.14, fp16, the same script):
- # decode 2650-2772 across 512^2 to 2048^2, encode 1541-1552, i.e. what CUDA measures (2660 decode). Shipping the
- # unbounded figures there costs two things at once: eviction of models the decode does not need out of the way,
- # and -- since the same figure decides it -- tiling a decode that fits, which is not pixel-identical.
+ # - A second ROCm card measures far below the shipped pair: on an RX 9060 XT (gfx1200, torch 2.12+rocm7.14,
+ # fp16, 2026-09-23, the same script with the attention guard installed) the implied constant is flat at
+ # 2650-2772 for decode and 1541-1552 for encode, all the way to 2048^2. The shipped figures stay at the
+ # W7900's, which is the card that needs them; what the spread means is that the reservation carries
+ # cross-card conservatism, so it must not double as the up-front tiling decision -- see
+ # `qwen_image_untiled_decode_peak_bytes`, which prices that decision from the measured curve instead.
device = device if device is not None else TorchDevice.choose_torch_device()
is_rocm = device.type == "cuda" and torch.version.hip is not None
- if is_rocm and rocm_sdpa_chunks_math(device.type):
- scaling_constant = 3000 if operation == "decode" else 1700
- elif is_rocm:
- scaling_constant = 5500 if operation == "decode" else 6300
- else:
- scaling_constant = 2900 if operation == "decode" else 1600
+ if operation == "decode":
+ scaling_constant = 5500 if is_rocm else 2900
+ else: # encode
+ scaling_constant = 6300 if is_rocm else 1600
if tile_size is not None and tile_size > 0:
# Bounded by one tile (plus overlap) rather than the full frame.
@@ -667,4 +726,6 @@ def estimate_vae_working_memory_sd3(
# max, not sum: the mid-block attention and the full-resolution convolutions peak in different
# phases of the forward (see the FLUX.2 estimator for the measurements).
- return int(max(working_memory, _vae_mid_block_score_matrix_bytes(h, w, next(vae.parameters()).dtype)))
+ return int(
+ max(working_memory, _vae_mid_block_score_matrix_bytes(h, w, next(vae.parameters()).dtype, device=device))
+ )
diff --git a/invokeai/backend/util/wddm.py b/invokeai/backend/util/wddm.py
index fc042211cd..376c900399 100644
--- a/invokeai/backend/util/wddm.py
+++ b/invokeai/backend/util/wddm.py
@@ -220,8 +220,10 @@ def _resolve_adapter(lib: ctypes.CDLL, index: int) -> Optional[_Adapter]:
return None
matches: list[_AdapterInfo] = []
+ pending = list(infos[: enum.NumAdapters])
try:
- for info in infos[: enum.NumAdapters]:
+ while pending:
+ info = pending.pop()
address = _AdapterAddress()
query = _QueryAdapterInfo(
info.hAdapter,
@@ -237,8 +239,9 @@ def _resolve_adapter(lib: ctypes.CDLL, index: int) -> Optional[_Adapter]:
else:
_close(lib, info.hAdapter)
except Exception:
- # Every handle opened by the enumeration belongs to this process until it is closed.
- for info in matches:
+ # 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:
_close(lib, info.hAdapter)
raise
diff --git a/tests/app/invocations/test_qwen_image_working_memory.py b/tests/app/invocations/test_qwen_image_working_memory.py
index b476221672..0a019b7d91 100644
--- a/tests/app/invocations/test_qwen_image_working_memory.py
+++ b/tests/app/invocations/test_qwen_image_working_memory.py
@@ -14,7 +14,10 @@ from invokeai.backend.util.qwen_image_vae import (
QWEN_IMAGE_VAE_DEFAULT_TILE_SIZE,
patch_qwen_image_vae_tiling,
)
-from invokeai.backend.util.vae_working_memory import estimate_vae_working_memory_qwen_image
+from invokeai.backend.util.vae_working_memory import (
+ estimate_vae_working_memory_qwen_image,
+ qwen_image_untiled_decode_peak_bytes,
+)
class TestQwenImageWorkingMemoryEstimate:
@@ -28,27 +31,15 @@ class TestQwenImageWorkingMemoryEstimate:
# (operation, latent_h, latent_w) -> the estimator scales pixel area (latent * 8 for decode,
# raw for encode) by element_size and the constant.
@pytest.mark.parametrize(
- "operation, is_rocm, chunked, expected_constant",
+ "operation, is_rocm, expected_constant",
[
- ("decode", True, True, 3000),
- ("decode", True, False, 5500),
- ("decode", False, False, 2900),
- ("encode", True, True, 1700),
- ("encode", True, False, 6300),
- ("encode", False, False, 1600),
- ],
- ids=[
- "rocm-decode-chunked",
- "rocm-decode-whole",
- "cuda-decode",
- "rocm-encode-chunked",
- "rocm-encode-whole",
- "cuda-encode",
+ ("decode", True, 5500),
+ ("decode", False, 2900),
+ ("encode", True, 6300),
+ ("encode", False, 1600),
],
)
- def test_constant_selected_per_backend(self, operation, is_rocm, chunked, expected_constant):
- """The ROCm figures split by whether math attention is chunked: the larger pair was measured while a single
- call built its whole score matrix, which is the super-linear term the guard removes."""
+ def test_constant_selected_per_backend(self, operation, is_rocm, expected_constant):
mock_vae = MagicMock(spec=AutoencoderKLQwenImage)
mock_vae.parameters.return_value = iter([torch.zeros(1, dtype=torch.float16)]) # element_size == 2
@@ -61,10 +52,7 @@ class TestQwenImageWorkingMemoryEstimate:
h = w = 512
hip_value = "7.1.0" if is_rocm else None
- with (
- patch("torch.version.hip", hip_value),
- patch("invokeai.backend.util.vae_working_memory.rocm_sdpa_chunks_math", return_value=chunked),
- ):
+ with patch("torch.version.hip", hip_value):
result = estimate_vae_working_memory_qwen_image(
operation=operation, image_tensor=image_tensor, vae=mock_vae, device=torch.device("cuda")
)
@@ -449,6 +437,7 @@ class TestQwenImageWorkingMemory:
with (
patch(f"{module}.estimate_vae_working_memory_qwen_image", side_effect=[20 * 2**30, 2 * 2**30]) as estimate,
+ patch(f"{module}.qwen_image_untiled_decode_peak_bytes", return_value=14 * 2**30) as peak,
patch(f"{module}.should_pretile_vae_decode", return_value=True) as pretile,
patch(f"{module}.SeamlessExt.static_patch_model", return_value=nullcontext()),
):
@@ -462,11 +451,14 @@ class TestQwenImageWorkingMemory:
invocation.invoke(mock_context)
if auto:
- pretile.assert_called_once_with(mock_vae_info.compute_device, 20 * 2**30)
+ # The decision is priced from the measured peak, not from the reservation, which is deliberately padded.
+ peak.assert_called_once()
+ pretile.assert_called_once_with(mock_vae_info.compute_device, 14 * 2**30)
assert estimate.call_args.kwargs["tile_size"] == QWEN_IMAGE_VAE_DEFAULT_TILE_SIZE
mock_vae_info.model_on_device.assert_called_once_with(working_mem_bytes=2 * 2**30)
mock_vae.enable_tiling.assert_called_once()
else:
+ peak.assert_not_called()
pretile.assert_not_called()
assert estimate.call_count == 1
mock_vae.enable_tiling.assert_not_called()
@@ -479,6 +471,46 @@ class TestQwenImageWorkingMemory:
MEASURED_ROCM_DECODE_CONSTANT = {512: 5132, 768: 4596, 1024: 4570, 1536: 3273, 1792: 3735, 2048: 4813}
+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(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)])
+ with patch("torch.version.hip", hip):
+ return qwen_image_untiled_decode_peak_bytes(
+ torch.zeros(1, 16, 1, px // 8, px // 8), mock_vae, torch.device(device)
+ )
+
+ @pytest.mark.parametrize("px, constant", [(512, 5132), (1024, 4570), (1536, 3273), (2048, 4813)])
+ 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_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_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."""
+ mock_vae = MagicMock(spec=AutoencoderKLQwenImage)
+ mock_vae.parameters.side_effect = lambda: iter([torch.zeros(1, dtype=torch.float16)])
+ latents = torch.zeros(1, 16, 1, 192, 192)
+ with patch("torch.version.hip", "7.2.0"):
+ reserved = estimate_vae_working_memory_qwen_image(
+ operation="decode", image_tensor=latents, vae=mock_vae, device=torch.device("cuda")
+ )
+ peak = qwen_image_untiled_decode_peak_bytes(latents, mock_vae, torch.device("cuda"))
+
+ assert peak < reserved
+
+
class TestPretilingDoesNotFireOnReservationHeadroom:
"""A decode whose real peak fits the card must not be tiled.
@@ -496,11 +528,8 @@ class TestPretilingDoesNotFireOnReservationHeadroom:
total_bytes = total_gib * 2**30
latents = torch.zeros(1, 16, 1, px // 8, px // 8)
- # The constants are measured per backend, so pin it rather than inheriting the host's build. A running app
- # always has the ROCm attention guard installed (`apply_monkeypatches`), and the ROCm constants differ by
- # whether it is: measured 2650-2772 with math attention chunked against 5500 with the whole score matrix.
+ # The constants are measured per backend, so pin it rather than inheriting the host's build.
monkeypatch.setattr(torch.version, "hip", "7.2.0")
- monkeypatch.setattr("invokeai.backend.util.vae_working_memory.rocm_sdpa_chunks_math", lambda device: True)
monkeypatch.setattr("torch.cuda.get_device_properties", lambda device: MagicMock(total_memory=total_bytes))
# The measured table is fp16, and the estimator runs once here and once inside the node,
diff --git a/tests/backend/util/test_vae_pretile.py b/tests/backend/util/test_vae_pretile.py
index a0213b2808..76fd578fff 100644
--- a/tests/backend/util/test_vae_pretile.py
+++ b/tests/backend/util/test_vae_pretile.py
@@ -72,3 +72,18 @@ def test_the_pretile_gate_uses_the_memory_the_device_will_keep_resident(monkeypa
assert estimate > budget_bytes, "test shape must exceed what Windows would keep resident"
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."""
+ 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.
+ 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))
+
+ assert should_pretile_vae_decode(torch.device("cuda", 0), estimate) is False