Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
fix(vae): MIOpen working-memory constants for the FLUX.1 autoencoder
Alexander Eichhorn67f23477694a
diff --git a/invokeai/app/invocations/vae/flux_vae_decode.py b/invokeai/app/invocations/vae/flux_vae_decode.pyindex 69a59564aa..fdcb507c46 100644--- a/invokeai/app/invocations/vae/flux_vae_decode.py+++ b/invokeai/app/invocations/vae/flux_vae_decode.py@@ -54,7 +54,11 @@ class FluxVaeDecodeInvocation(BaseInvocation, WithMetadata, WithBoard):# Only estimate working memory for BFL AutoEncoder (diffusers VAE handles this internally)if isinstance(vae_info.model, AutoEncoder):estimated_working_memory = estimate_vae_working_memory_flux(- operation="decode", image_tensor=latents, vae=vae_info.model, tile_size=tile_size+ operation="decode",+ image_tensor=latents,+ vae=vae_info.model,+ tile_size=tile_size,+ device=vae_info.compute_device,)else:estimated_working_memory = 0diff --git a/invokeai/app/invocations/vae/flux_vae_encode.py b/invokeai/app/invocations/vae/flux_vae_encode.pyindex 4ec0365c2c..cfa471697a 100644--- a/invokeai/app/invocations/vae/flux_vae_encode.py+++ b/invokeai/app/invocations/vae/flux_vae_encode.py@@ -44,7 +44,7 @@ class FluxVaeEncodeInvocation(BaseInvocation):# should be used for VAE encode sampling.assert isinstance(vae_info.model, AutoEncoder)estimated_working_memory = estimate_vae_working_memory_flux(- operation="encode", image_tensor=image_tensor, vae=vae_info.model+ operation="encode", image_tensor=image_tensor, vae=vae_info.model, device=vae_info.compute_device)generator = torch.Generator(device=TorchDevice.choose_torch_device()).manual_seed(0)with vae_info.model_on_device(working_mem_bytes=estimated_working_memory) as (_, vae):diff --git a/invokeai/app/invocations/vae/z_image_image_to_latents.py b/invokeai/app/invocations/vae/z_image_image_to_latents.pyindex 263346e296..48d65d3ee7 100644--- a/invokeai/app/invocations/vae/z_image_image_to_latents.py+++ b/invokeai/app/invocations/vae/z_image_image_to_latents.py@@ -53,6 +53,7 @@ class ZImageImageToLatentsInvocation(BaseInvocation, WithMetadata, WithBoard):operation="encode",image_tensor=image_tensor,vae=vae_info.model,+ device=vae_info.compute_device,)with vae_info.model_on_device(working_mem_bytes=estimated_working_memory) as (_, vae):diff --git a/invokeai/app/invocations/vae/z_image_latents_to_image.py b/invokeai/app/invocations/vae/z_image_latents_to_image.pyindex 91805d0a1d..74213f2233 100644--- a/invokeai/app/invocations/vae/z_image_latents_to_image.py+++ b/invokeai/app/invocations/vae/z_image_latents_to_image.py@@ -68,6 +68,7 @@ class ZImageLatentsToImageInvocation(BaseInvocation, WithMetadata, WithBoard):image_tensor=latents,vae=vae_info.model,tile_size=self.tile_size if use_tiling else None,+ device=vae_info.compute_device,)# FLUX VAE doesn't support seamless, so only apply for AutoencoderKLdiff --git a/invokeai/backend/util/vae_working_memory.py b/invokeai/backend/util/vae_working_memory.pyindex e2e2dd4442..715799fa11 100644--- a/invokeai/backend/util/vae_working_memory.py+++ b/invokeai/backend/util/vae_working_memory.py@@ -137,6 +137,7 @@ def estimate_vae_working_memory_flux(image_tensor: torch.Tensor,vae: AutoEncoder,tile_size: int | None = None,+ device: torch.device | None = None,) -> int:"""Estimate the working memory required by the invocation in bytes.@@ -148,14 +149,18 @@ def estimate_vae_working_memory_flux(Only `decode` tiles: `AutoEncoder.encode` never consults `use_tiling`. So a `tile_size` with`operation="encode"` would price a tiled encode that cannot happen, and no call site passes one.++ `device` is where the VAE will run (a `cpu_only` VAE runs on the CPU); it picks the convolution+ backend's constant. Defaults to the session device."""latent_scale_factor_for_operation = LATENT_SCALE_FACTOR if operation == "decode" else 1element_size = next(vae.parameters()).element_size()- # This constant is determined experimentally and takes into consideration both allocated and reserved memory. See #8414- # Encoding uses ~45% the working memory as decoding.- scaling_constant = 2200 if operation == "decode" else 1100+ # The FLUX.1 autoencoder shares the FLUX.2 VAE's convolution stack and measures the same constants on both+ # backends; see `_FLUX_VAE_SCALING_CONSTANTS`.+ device = device if device is not None else TorchDevice.choose_torch_device()+ scaling_constant = _flux_vae_scaling_constant(operation, device)out_h = latent_scale_factor_for_operation * image_tensor.shape[-2]out_w = latent_scale_factor_for_operation * image_tensor.shape[-1]@@ -186,7 +191,7 @@ def estimate_vae_working_memory_flux(# 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).dtype = next(vae.parameters()).dtype- return int(max(working_memory, _vae_mid_block_score_matrix_bytes(score_h, score_w, dtype)))+ return int(max(working_memory, _vae_mid_block_score_matrix_bytes(score_h, score_w, dtype, device=device)))# The FLUX.2 VAE runs one attention block at the bottom of the encoder and one at the top of the@@ -198,17 +203,21 @@ _FLUX2_VAE_MID_BLOCK_HEADS = 1_FLUX2_VAE_MID_BLOCK_HEAD_DIM = 512_FLUX2_VAE_SPATIAL_COMPRESSION = 8-# Peak reserved bytes per output pixel per element byte, per conv backend and operation. Fitted with-# `scripts/calibrate_flux2_working_memory.py --only vae`, which reproduces this table on any build:+# Peak reserved bytes per output pixel per element byte, per conv backend and operation, for the FLUX.2 VAE and the+# FLUX.1 autoencoder alike. Fitted with `scripts/calibrate_flux2_working_memory.py --only vae`, which reproduces+# this table on any build:#-# decode encode encode/decode-# cuDNN RTX 4090, torch 2.7.1 2185 1072 0.49-# MIOpen RX 9070 XT, torch 2.10 3453 2688 0.78-# MIOpen PRO W7900, torch 2.10 3525 2688 0.76+# decode encode encode/decode+# cuDNN RTX 4090, torch 2.7.1 2185 1072 0.49+# MIOpen RX 9070 XT, torch 2.10 3453 2688 0.78+# MIOpen PRO W7900, torch 2.10 3525 2688 0.76+# MIOpen RX 9060 XT, torch 2.12, Windows, FLUX.1 VAE 3451 2688 0.78## Two AMD generations (RDNA3 and RDNA4), the same numbers: the encode column agrees to the byte and# the decode column to 2%. So this is MIOpen, not a per-card quirk, and the column below is fitted-# to the larger with ~2% headroom.+# to the larger with ~2% headroom. The FLUX.1 row (bf16, 768-1536px, Invoke's ROCm SDPA guard installed,+# `MIOPEN_FIND_MODE=FAST`) lands on the same numbers: the two VAEs share their convolution stack. The+# cuDNN column is the FLUX.1 constant this estimator shipped with before.## MIOpen's convolution workspaces are simply larger than cuDNN's. This is not the attention term --# it shows up identically on the fused path, and the implied constants are flat across resolution on@@ -219,16 +228,18 @@ _FLUX2_VAE_SPATIAL_COMPRESSION = 8# Shipping the MIOpen numbers everywhere would add ~60% to every cuDNN decode for nothing, so the# constant follows the backend.#-# Caveat for AMD users: `MIOPEN_FIND_MODE=2` selects convolution algorithms heuristically instead of-# by benchmark, and measured a uniform 1.28x more memory at every resolution. It is not the default-# and is not budgeted for here -- raise `device_working_mem_gb` if you set it.-_FLUX2_VAE_SCALING_CONSTANTS: dict[str, dict[str, int]] = {+# Caveat for AMD users: `MIOPEN_FIND_MODE=2` (FAST) selects convolution algorithms heuristically instead of+# by benchmark, and measured a uniform 1.28x more memory at every resolution when these constants were+# first fitted. Invoke has since made FAST its default (`run_app.py`); the RX 9060 XT row above was taken+# under it and did not show the 1.28x. If you see decodes exceed their reservation on another card, raise+# `device_working_mem_gb`.+_FLUX_VAE_SCALING_CONSTANTS: dict[str, dict[str, int]] = {"cudnn": {"decode": 2200, "encode": 1100},"miopen": {"decode": 3600, "encode": 2750},}-def _flux2_vae_scaling_constant(operation: Literal["encode", "decode"], device: torch.device) -> int:+def _flux_vae_scaling_constant(operation: Literal["encode", "decode"], device: torch.device) -> int:"""Pick the pixel-area constant for the convolution backend this device will actually use.A HIP build reports ``device.type == "cuda"``, so the torch build -- not the device string -- is@@ -236,7 +247,7 @@ def _flux2_vae_scaling_constant(operation: Literal["encode", "decode"], device:that pairs with a score-matrix term the probe always charges there, so the total is not thin."""is_rocm = device.type == "cuda" and torch.version.hip is not None- return _FLUX2_VAE_SCALING_CONSTANTS["miopen" if is_rocm else "cudnn"][operation]+ return _FLUX_VAE_SCALING_CONSTANTS["miopen" if is_rocm else "cudnn"][operation]def estimate_vae_working_memory_flux2(@@ -251,7 +262,7 @@ def estimate_vae_working_memory_flux2(Peak memory scales linearly with pixel area and element size, as it does for the FLUX.1 VAE, andthe implied constant is flat across 512-1536px on every backend measured. What is *not* constantis the constant itself: MIOpen's convolution workspaces cost ~1.6x cuDNN's for a decode and ~2.4x- for an encode, so it is looked up per backend -- see ``_FLUX2_VAE_SCALING_CONSTANTS`` for the+ for an encode, so it is looked up per backend -- see ``_FLUX_VAE_SCALING_CONSTANTS`` for thefitted table and the caveats. Peak *reserved* memory is what is measured throughout, theconservative quantity that includes allocator overhead.@@ -289,7 +300,7 @@ def estimate_vae_working_memory_flux2(element_size = param.element_size()device = device if device is not None else TorchDevice.choose_torch_device()- scaling_constant = _flux2_vae_scaling_constant(operation, device)+ scaling_constant = _flux_vae_scaling_constant(operation, device)batch_size = image_tensor.shape[0] if image_tensor.dim() >= 4 else 1if tile_size is not None:diff --git a/scripts/calibrate_flux2_working_memory.py b/scripts/calibrate_flux2_working_memory.pyindex f4d532d60f..d7d6ca3434 100644--- a/scripts/calibrate_flux2_working_memory.py+++ b/scripts/calibrate_flux2_working_memory.py@@ -68,7 +68,7 @@ from invokeai.backend.model_manager.configs.flux2_variant import flux2_hidden_sifrom invokeai.backend.model_manager.taxonomy import Flux2VariantTypefrom invokeai.backend.util.attention import SDPA_MATH_BYTES_PER_SCORE_ELEMENT, sdpa_score_matrix_bytesfrom invokeai.backend.util.vae_working_memory import (- _flux2_vae_scaling_constant,+ _flux_vae_scaling_constant,estimate_vae_working_memory_flux2,)@@ -457,8 +457,8 @@ def report_sdpa(shapes: list[tuple[int, int, int]], dtype_name: str) -> list[dicdef report_vae(pxs: list[int], dtype_name: str, vae_path: str | None) -> list[dict]:- decode_k = _flux2_vae_scaling_constant("decode", torch.device("cuda"))- encode_k = _flux2_vae_scaling_constant("encode", torch.device("cuda"))+ decode_k = _flux_vae_scaling_constant("decode", torch.device("cuda"))+ encode_k = _flux_vae_scaling_constant("encode", torch.device("cuda"))print(f"\n=== 3. VAE linear constants (this build selects {decode_k} decode / {encode_k} encode) ===")print("`implied_k` is the measured peak over pixel area, directly comparable to those literals;")print("fit on the rows whose `math` column matches what this build really does (section 1).")@@ -495,7 +495,7 @@ def report_vae(pxs: list[int], dtype_name: str, vae_path: str | None) -> list[di_flag_non_monotonic(rows)for operation in ("decode", "encode"):# Compare against the column this build actually selects, not against a hard-coded number.- shipped = _flux2_vae_scaling_constant(operation, torch.device("cuda"))+ shipped = _flux_vae_scaling_constant(operation, torch.device("cuda"))for force_math in (False, True):ks = [r["implied_linear_constant"]diff --git a/tests/app/invocations/test_flux2_working_memory.py b/tests/app/invocations/test_flux2_working_memory.pyindex dea23d130d..cd1e3e0ace 100644--- a/tests/app/invocations/test_flux2_working_memory.py+++ b/tests/app/invocations/test_flux2_working_memory.py@@ -34,7 +34,7 @@ from invokeai.backend.util.attention import (sdpa_score_matrix_bytes,)from invokeai.backend.util.vae_working_memory import (- _FLUX2_VAE_SCALING_CONSTANTS,+ _FLUX_VAE_SCALING_CONSTANTS,estimate_vae_working_memory_flux2,)@@ -368,7 +368,7 @@ class TestVaeConstantsFollowTheConvBackend:def test_the_constant_upper_bounds_its_own_backend(self, backend, operation, px, measured_gib):"""Each column has to bound the hardware it was fitted on. Before this the cuDNN column wasused everywhere, leaving a 2.3 GiB shortfall on a 1024px MIOpen decode."""- constant = _FLUX2_VAE_SCALING_CONSTANTS[backend][operation]+ constant = _FLUX_VAE_SCALING_CONSTANTS[backend][operation]estimate = px * px * 2 * constant # bf16 element sizeassert estimate >= measured_gib * GBassert estimate <= 1.3 * measured_gib * GB@@ -376,14 +376,14 @@ class TestVaeConstantsFollowTheConvBackend:def test_the_cudnn_constant_would_not_cover_miopen(self):"""The regression this guards: a 1024px MIOpen decode needs 6.58 GiB and the cuDNN constantreserves 4.30. That is the same class of shortfall #9500 reports, one backend over."""- cudnn = _FLUX2_VAE_SCALING_CONSTANTS["cudnn"]["decode"]+ cudnn = _FLUX_VAE_SCALING_CONSTANTS["cudnn"]["decode"]assert 1024 * 1024 * 2 * cudnn < 6.578 * GBdef test_the_encode_ratio_is_not_architectural(self):"""cuDNN's encode is half its decode; MIOpen's is four fifths. A shared ratio cannot expressboth, which is why the table carries the two operations separately."""ratios = {- backend: consts["encode"] / consts["decode"] for backend, consts in _FLUX2_VAE_SCALING_CONSTANTS.items()+ backend: consts["encode"] / consts["decode"] for backend, consts in _FLUX_VAE_SCALING_CONSTANTS.items()}assert ratios["cudnn"] == pytest.approx(0.50, abs=0.02)assert ratios["miopen"] == pytest.approx(0.76, abs=0.03)@@ -856,7 +856,7 @@ class TestVaeTermsDoNotAdd:@pytest.mark.parametrize("px, measured_gib", MEASURED_W7900_DECODE)def test_the_max_model_bounds_the_measured_miopen_peak(self, px, measured_gib):- linear = px * px * 2 * _FLUX2_VAE_SCALING_CONSTANTS["miopen"]["decode"]+ linear = px * px * 2 * _FLUX_VAE_SCALING_CONSTANTS["miopen"]["decode"]score = (px // 8) ** 4 * SDPA_MATH_BYTES_PER_SCORE_ELEMENTassert max(linear, score) >= measured_gib * GBassert max(linear, score) <= 1.15 * measured_gib * GB@@ -864,7 +864,7 @@ class TestVaeTermsDoNotAdd:def test_the_sum_model_would_have_over_reserved_by_two_thirds(self):"""At 1024px the sum reserves 11.1GiB for a decode that measures 6.7 -- on a 16GB card thatis the difference between the transformer staying resident and being evicted."""- linear = 1024 * 1024 * 2 * _FLUX2_VAE_SCALING_CONSTANTS["miopen"]["decode"]+ linear = 1024 * 1024 * 2 * _FLUX_VAE_SCALING_CONSTANTS["miopen"]["decode"]score = 16384 * 16384 * SDPA_MATH_BYTES_PER_SCORE_ELEMENTassert (linear + score) / (6.703 * GB) > 1.6assert max(linear, score) / (6.703 * GB) < 1.15@@ -872,7 +872,7 @@ class TestVaeTermsDoNotAdd:def test_the_estimate_is_the_larger_term_not_the_sum(self):"""At 1024px the two are within 2% of each other on the cuDNN column, which makes this thesharpest place to tell the models apart."""- linear = 1024 * 1024 * 2 * _FLUX2_VAE_SCALING_CONSTANTS["cudnn"]["decode"]+ linear = 1024 * 1024 * 2 * _FLUX_VAE_SCALING_CONSTANTS["cudnn"]["decode"]score = 16384 * 16384 * SDPA_MATH_BYTES_PER_SCORE_ELEMENTassert self._estimate(1024, MATERIALIZING, materializing=True) == max(linear, score)assert self._estimate(1024, MATERIALIZING, materializing=True) < linear + score@@ -895,7 +895,7 @@ class TestVaeTermsDoNotAdd:because the cache floors every reservation at `device_working_mem_gb` and the whole crossoverregion sits below that floor. Reproducible to three decimals across runs, so this is themodel's real shape, not noise -- which is why it is pinned rather than rounded away."""- constant = _FLUX2_VAE_SCALING_CONSTANTS["cudnn"][operation]+ constant = _FLUX_VAE_SCALING_CONSTANTS["cudnn"][operation]area = px * px if operation == "decode" else px * pxlinear = area * 2 * constantscore = (px // 8) ** 4 * SDPA_MATH_BYTES_PER_SCORE_ELEMENT@@ -905,7 +905,7 @@ class TestVaeTermsDoNotAdd:def test_a_fused_build_is_unaffected(self):"""The max only ever removes reservation, never adds it: with no score matrix the estimate isthe linear term, exactly as before."""- linear = 1024 * 1024 * 2 * _FLUX2_VAE_SCALING_CONSTANTS["cudnn"]["decode"]+ linear = 1024 * 1024 * 2 * _FLUX_VAE_SCALING_CONSTANTS["cudnn"]["decode"]assert self._estimate(1024, FUSED, materializing=False) == lineardef test_regional_prompting_adds_the_score_matrix(self):diff --git a/tests/app/invocations/test_z_image_tiled_decode.py b/tests/app/invocations/test_z_image_tiled_decode.pyindex 9bc792a3e1..9fafbb2fad 100644--- a/tests/app/invocations/test_z_image_tiled_decode.py+++ b/tests/app/invocations/test_z_image_tiled_decode.py@@ -22,6 +22,37 @@ def _mock_flux_vae(element_size_bytes: int = 2) -> MagicMock:class TestFluxWorkingMemoryEstimate:+ @pytest.fixture(autouse=True)+ def _cudnn_column(self, monkeypatch):+ """These pin the cuDNN-column arithmetic; on a ROCm machine the session device would select MIOpen's."""+ import invokeai.backend.util.vae_working_memory as vwm++ monkeypatch.setattr(vwm.TorchDevice, "choose_torch_device", classmethod(lambda cls: torch.device("cpu")))++ @pytest.mark.parametrize(+ ("hip", "operation", "constant"),+ [(None, "decode", 2200), (None, "encode", 1100), ("7.14.0", "decode", 3600), ("7.14.0", "encode", 2750)],+ ids=["cudnn-decode", "cudnn-encode", "miopen-decode", "miopen-encode"],+ )+ def test_the_convolution_backend_of_the_vaes_device_picks_the_constant(self, monkeypatch, hip, operation, constant):+ """MIOpen's workspaces are larger than cuDNN's: measured 3451 decode / 2688 encode on an RX 9060 XT, the same+ as the FLUX.2 VAE. A HIP build reports its GPU as "cuda", so the torch build decides, for the VAE's device."""+ import invokeai.backend.util.vae_working_memory as vwm++ monkeypatch.setattr(torch.version, "hip", hip)+ monkeypatch.setattr(vwm, "_vae_mid_block_score_matrix_bytes", lambda *args, **kwargs: 0)+ tensor = torch.zeros(1, 16, 64, 64) if operation == "decode" else torch.zeros(1, 3, 512, 512)++ estimate = estimate_vae_working_memory_flux(+ operation=operation, image_tensor=tensor, vae=_mock_flux_vae(), device=torch.device("cuda", 0)+ )+ on_cpu = estimate_vae_working_memory_flux(+ operation=operation, image_tensor=tensor, vae=_mock_flux_vae(), device=torch.device("cpu")+ )++ assert estimate == 512 * 512 * 2 * constant+ assert on_cpu == 512 * 512 * 2 * (2200 if operation == "decode" else 1100), "a cpu_only VAE runs on cuDNN terms"+def test_the_default_reproduces_the_untiled_estimate(self):"""Regression guard for the six call sites that pass no tile_size at all."""latents = torch.zeros(1, 16, 128, 128)