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): honour the requested tile size on diffusers VAEs, and free the failed decode

Alexander Eichhorn72e39c1f5dfa
diff --git a/invokeai/app/invocations/anima_latents_to_image.py b/invokeai/app/invocations/anima_latents_to_image.py
index b5189f6d23..d457de3c2b 100644
--- a/invokeai/app/invocations/anima_latents_to_image.py
+++ b/invokeai/app/invocations/anima_latents_to_image.py
@@ -167,6 +167,14 @@ class AnimaLatentsToImageInvocation(BaseInvocation, WithMetadata, WithBoard):
raise
# The working-memory estimate was insufficient on this system;
# retry once with tiling, which caps the peak allocation.
+ # Drop the failed attempt's traceback before retrying. It pins that
+ # decode's frames, and their locals hold the full-resolution
+ # activations -- exception/traceback/frame is a reference cycle rooted
+ # on the stack, so `empty_cache()` frees nothing while `e` is bound and
+ # the retry has to fit on top of it. Measured at 1536px: 1.4 GiB held,
+ # and a retry that fails with it and succeeds without. Same reasoning as
+ # `ModelConfigFactory._detach_traceback`.
+ e.__traceback__ = None
TorchDevice.empty_cache()
vae.enable_tiling(
tile_sample_min_height=ANIMA_VAE_TILE_SIZE,
diff --git a/invokeai/app/invocations/flux_vae_decode.py b/invokeai/app/invocations/flux_vae_decode.py
index 6748750e8a..6a234cda7c 100644
--- a/invokeai/app/invocations/flux_vae_decode.py
+++ b/invokeai/app/invocations/flux_vae_decode.py
@@ -91,6 +91,14 @@ class FluxVaeDecodeInvocation(BaseInvocation, WithMetadata, WithBoard):
raise
# The working-memory estimate was insufficient on this system. Retry once with
# tiling, which caps the peak allocation regardless of resolution.
+ # Drop the failed attempt's traceback before retrying. It pins that
+ # decode's frames, and their locals hold the full-resolution
+ # activations -- exception/traceback/frame is a reference cycle rooted
+ # on the stack, so `empty_cache()` frees nothing while `e` is bound and
+ # the retry has to fit on top of it. Measured at 1536px: 1.4 GiB held,
+ # and a retry that fails with it and succeeds without. Same reasoning as
+ # `ModelConfigFactory._detach_traceback`.
+ e.__traceback__ = None
TorchDevice.empty_cache()
with scoped_vae_tiling(vae, 0):
img = decode()
diff --git a/invokeai/app/invocations/z_image_latents_to_image.py b/invokeai/app/invocations/z_image_latents_to_image.py
index f2c53cb0c8..107a4c9caf 100644
--- a/invokeai/app/invocations/z_image_latents_to_image.py
+++ b/invokeai/app/invocations/z_image_latents_to_image.py
@@ -121,6 +121,14 @@ class ZImageLatentsToImageInvocation(BaseInvocation, WithMetadata, WithBoard):
# The working-memory estimate was insufficient on this system. Retry once with
# tiling, which caps the peak allocation regardless of resolution.
context.util.signal_progress("VAE decode ran out of memory, retrying tiled")
+ # Drop the failed attempt's traceback before retrying. It pins that
+ # decode's frames, and their locals hold the full-resolution
+ # activations -- exception/traceback/frame is a reference cycle rooted
+ # on the stack, so `empty_cache()` frees nothing while `e` is bound and
+ # the retry has to fit on top of it. Measured at 1536px: 1.4 GiB held,
+ # and a retry that fails with it and succeeds without. Same reasoning as
+ # `ModelConfigFactory._detach_traceback`.
+ e.__traceback__ = None
TorchDevice.empty_cache()
with scoped_vae_tiling(vae, self.tile_size):
img = decode()
diff --git a/invokeai/backend/util/vae_tiling_scope.py b/invokeai/backend/util/vae_tiling_scope.py
index 6f76f2dade..3fb92627aa 100644
--- a/invokeai/backend/util/vae_tiling_scope.py
+++ b/invokeai/backend/util/vae_tiling_scope.py
@@ -47,9 +47,17 @@ def scoped_vae_tiling(vae: Any, tile_size: int | None) -> Iterator[None]:
# gets the same answer for the same field value.
vae.enable_tiling(tile_sample_min_size=resolve_tile_size(tile_size))
else:
- # This class does not expose a settable size -- diffusers' AutoencoderKL.enable_tiling()
- # takes no arguments and uses its own geometry.
+ # Diffusers' `AutoencoderKL.enable_tiling()` takes no arguments and leaves the geometry
+ # at the VAE's own `sample_size` -- 1024 for Z-Image, which means a 1024px decode does
+ # not tile at all while the caller's working-memory reservation assumes it did. Setting
+ # the two attributes afterwards is how the rest of this codebase sizes a diffusers VAE's
+ # tiles; see `flux2/ref_image_extension.py`, which forces 512 for the same reason. Both
+ # are in `_TILING_ATTRS`, so the finally block puts them back.
+ resolved = resolve_tile_size(tile_size)
vae.enable_tiling()
+ vae.tile_sample_min_size = resolved
+ downsample = 2 ** (len(vae.config.block_out_channels) - 1)
+ vae.tile_latent_min_size = max(1, resolved // downsample)
yield
finally:
for name, value in original.items():
diff --git a/tests/backend/util/test_vae_tiling_scope.py b/tests/backend/util/test_vae_tiling_scope.py
index ff39f3f963..be53fa2ba2 100644
--- a/tests/backend/util/test_vae_tiling_scope.py
+++ b/tests/backend/util/test_vae_tiling_scope.py
@@ -130,18 +130,60 @@ class TestStateIsRestored:
class TestDiffusersVaesAreHandledToo:
- def test_a_class_without_a_settable_size_is_enabled_without_arguments(self):
- # diffusers' AutoencoderKL.enable_tiling() takes no parameters; passing one would raise.
- vae = AutoencoderKL(
+ """`AutoencoderKL.enable_tiling()` takes no arguments, so the size has to be set afterwards.
+
+ Leaving it out is not a smaller tile than asked for -- it is the VAE's own `sample_size`, which
+ for Z-Image is 1024, so a 1024px decode does not tile at all while the caller has already
+ reserved working memory on the assumption that it did. Asserting `use_tiling is True` alone does
+ not see that: it held while every requested size was being discarded.
+ """
+
+ @staticmethod
+ def _vae(block_out_channels=(32, 64, 128, 128), sample_size=1024) -> AutoencoderKL:
+ return AutoencoderKL(
in_channels=3,
out_channels=3,
latent_channels=4,
- block_out_channels=(32,),
- down_block_types=("DownEncoderBlock2D",),
- up_block_types=("UpDecoderBlock2D",),
+ block_out_channels=block_out_channels,
+ down_block_types=("DownEncoderBlock2D",) * len(block_out_channels),
+ up_block_types=("UpDecoderBlock2D",) * len(block_out_channels),
layers_per_block=1,
norm_num_groups=32,
+ sample_size=sample_size,
)
- with scoped_vae_tiling(vae, 384):
+
+ @pytest.mark.parametrize(
+ ("requested", "expected_sample"), [(384, 384), (256, 256), (0, DEFAULT_TILE_SAMPLE_MIN_SIZE)]
+ )
+ def test_the_requested_size_reaches_the_vae(self, requested, expected_sample):
+ vae = self._vae()
+ # Four blocks, so the latent grid is 8x smaller than the pixel grid.
+ downsample = 2 ** (len(vae.config.block_out_channels) - 1)
+
+ with scoped_vae_tiling(vae, requested):
assert vae.use_tiling is True
- assert vae.use_tiling is False
+ assert vae.tile_sample_min_size == expected_sample
+ assert vae.tile_latent_min_size == expected_sample // downsample
+
+ def test_the_vaes_own_geometry_is_restored(self):
+ vae = self._vae()
+ before = (vae.use_tiling, vae.tile_sample_min_size, vae.tile_latent_min_size)
+
+ with scoped_vae_tiling(vae, 256):
+ pass
+
+ assert (vae.use_tiling, vae.tile_sample_min_size, vae.tile_latent_min_size) == before
+
+ def test_a_decode_at_the_vaes_default_resolution_actually_tiles(self):
+ """The case the missing size costs: a 1024px decode against a VAE whose default tile is also
+ 1024 stays in the single-pass path, which is the one the reservation was sized against."""
+ vae = self._vae().eval()
+ calls = []
+ real = vae.tiled_decode
+ vae.tiled_decode = lambda z, return_dict=True: (calls.append(1), real(z, return_dict=return_dict))[1]
+
+ latent = torch.zeros(1, 4, 1024 // 8, 1024 // 8)
+ with torch.no_grad(), scoped_vae_tiling(vae, 0):
+ vae.decode(latent)
+
+ assert calls, "the decode did not tile, so the tile size never reached the VAE"