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): scope the FLUX autoencoder's tiling state to one decode

Alexander Eichhorn80e340d483f5
diff --git a/invokeai/app/invocations/flux_vae_decode.py b/invokeai/app/invocations/flux_vae_decode.py
index 70fc7fbb78..6748750e8a 100644
--- a/invokeai/app/invocations/flux_vae_decode.py
+++ b/invokeai/app/invocations/flux_vae_decode.py
@@ -19,6 +19,7 @@ from invokeai.backend.flux.modules.autoencoder import AutoEncoder
from invokeai.backend.model_manager.load.load_base import LoadedModel
from invokeai.backend.util.devices import TorchDevice
from invokeai.backend.util.oom import is_oom_error
+from invokeai.backend.util.vae_tiling_scope import scoped_vae_tiling
from invokeai.backend.util.vae_working_memory import estimate_vae_working_memory_flux
@@ -79,19 +80,20 @@ class FluxVaeDecodeInvocation(BaseInvocation, WithMetadata, WithBoard):
return vae.decode(latents)
return vae.decode(latents, return_dict=False)[0]
- # This node has no tiling controls, so the tiling state of the shared, cached VAE
- # instance is set explicitly rather than inherited from whoever decoded last.
- vae.disable_tiling()
+ # This node has no tiling controls, so it decodes untiled -- but says so explicitly
+ # rather than inheriting whatever the last node to touch this shared, cached VAE left
+ # behind, and restores that state afterwards.
try:
- img = decode()
+ with scoped_vae_tiling(vae, None):
+ img = decode()
except RuntimeError as e:
if not is_oom_error(e):
raise
# The working-memory estimate was insufficient on this system. Retry once with
# tiling, which caps the peak allocation regardless of resolution.
TorchDevice.empty_cache()
- vae.enable_tiling()
- img = decode()
+ with scoped_vae_tiling(vae, 0):
+ img = decode()
img = img.clamp(-1, 1)
img = rearrange(img[0], "c h w -> h w c") # noqa: F821
diff --git a/invokeai/app/invocations/z_image_latents_to_image.py b/invokeai/app/invocations/z_image_latents_to_image.py
index 88223a50ce..f2c53cb0c8 100644
--- a/invokeai/app/invocations/z_image_latents_to_image.py
+++ b/invokeai/app/invocations/z_image_latents_to_image.py
@@ -22,6 +22,7 @@ from invokeai.backend.flux.modules.autoencoder import AutoEncoder as FluxAutoEnc
from invokeai.backend.stable_diffusion.extensions.seamless import SeamlessExt
from invokeai.backend.util.devices import TorchDevice
from invokeai.backend.util.oom import is_oom_error
+from invokeai.backend.util.vae_tiling_scope import scoped_vae_tiling
from invokeai.backend.util.vae_working_memory import estimate_vae_working_memory_flux
# Z-Image can use either the Diffusers AutoencoderKL or the FLUX AutoEncoder
@@ -88,10 +89,6 @@ class ZImageLatentsToImageInvocation(BaseInvocation, WithMetadata, WithBoard):
# wrongly place the latents (and thus the whole decode) on the CPU (see #9373).
latents = latents.to(device=vae_info.compute_device, dtype=vae_dtype)
- # The VAE instance is cached and shared across invocations, so the tiling state is always
- # set explicitly -- otherwise one tiled run would leave every later run tiled.
- self._set_tiling(vae, enabled=use_tiling)
-
# Clear memory as VAE decode can request a lot
TorchDevice.empty_cache()
@@ -111,9 +108,13 @@ class ZImageLatentsToImageInvocation(BaseInvocation, WithMetadata, WithBoard):
return vae.decode(latents)
return vae.decode(latents, return_dict=False)[0]
+ # The VAE belongs to the model cache and is shared with every other node that reaches
+ # this class -- FLUX.1 decode and encode, Anima, PiD. Tiling is a property of this one
+ # decode, not of the model, so the state is scoped and restored rather than left behind.
with torch.inference_mode():
try:
- img = decode()
+ with scoped_vae_tiling(vae, self.tile_size if use_tiling else None):
+ img = decode()
except RuntimeError as e:
if use_tiling or not is_oom_error(e):
raise
@@ -121,8 +122,8 @@ class ZImageLatentsToImageInvocation(BaseInvocation, WithMetadata, WithBoard):
# tiling, which caps the peak allocation regardless of resolution.
context.util.signal_progress("VAE decode ran out of memory, retrying tiled")
TorchDevice.empty_cache()
- self._set_tiling(vae, enabled=True)
- img = decode()
+ with scoped_vae_tiling(vae, self.tile_size):
+ img = decode()
img = img.clamp(-1, 1)
img = rearrange(img[0], "c h w -> h w c")
@@ -133,12 +134,3 @@ class ZImageLatentsToImageInvocation(BaseInvocation, WithMetadata, WithBoard):
image_dto = context.images.save(image=img_pil)
return ImageOutput.build(image_dto)
-
- def _set_tiling(self, vae: ZImageVAE, enabled: bool) -> None:
- """Set the VAE's tiling state explicitly, in whichever class's spelling applies."""
- if not enabled:
- vae.disable_tiling()
- elif isinstance(vae, FluxAutoEncoder) and self.tile_size:
- vae.enable_tiling(tile_sample_min_size=self.tile_size)
- else:
- vae.enable_tiling()
diff --git a/invokeai/backend/flux/modules/autoencoder.py b/invokeai/backend/flux/modules/autoencoder.py
index 01b093fd7c..86cb7b78f6 100644
--- a/invokeai/backend/flux/modules/autoencoder.py
+++ b/invokeai/backend/flux/modules/autoencoder.py
@@ -16,6 +16,27 @@ from invokeai.backend.tiles.utils import TBLR, Tile
DEFAULT_TILE_SAMPLE_MIN_SIZE = 512
DEFAULT_TILE_OVERLAP = 128
+# A cost floor, not a correctness one: the geometry stays valid all the way down, but the tile count
+# grows with the inverse square of the tile size. At 2048x2048 a 128px tile already emits 289 tiles;
+# a 16px tile would emit ~16k, and the per-tile kernel-launch overhead dominates long before that.
+# Small tiles are also measurably less accurate (see `enable_tiling`), so the low end of the node
+# field is clamped rather than honoured literally.
+MIN_TILE_SAMPLE_SIZE = 128
+
+
+def resolve_tile_size(tile_size: int) -> int:
+ """Resolve a node's ``tile_size`` field to the size the autoencoder will actually use.
+
+ ``tile_size <= 0`` is the nodes' "use the default" sentinel -- the workflow UI cannot represent
+ ``None`` in a number input and sends 0, and a negative value is not worth failing a generation
+ over. It resolves to the module-level default rather than to whatever is currently set on the
+ VAE: the instance belongs to the model cache, so reading it back would return whatever the
+ previous invocation left there.
+ """
+ if tile_size <= 0:
+ return DEFAULT_TILE_SAMPLE_MIN_SIZE
+ return max(tile_size, MIN_TILE_SAMPLE_SIZE)
+
@dataclass
class AutoEncoderParams:
diff --git a/invokeai/backend/util/vae_tiling_scope.py b/invokeai/backend/util/vae_tiling_scope.py
new file mode 100644
index 0000000000..6f76f2dade
--- /dev/null
+++ b/invokeai/backend/util/vae_tiling_scope.py
@@ -0,0 +1,62 @@
+"""Scoped VAE tiling state.
+
+The VAE instances these helpers take belong to the model cache and are shared across invocations and
+across *nodes*: the FLUX.1 autoencoder is reached by nine call sites, and a diffusers AutoencoderKL
+loaded for Z-Image is reached by several more. Tiling is a property of one decode, not of the model,
+so it has to be restored rather than merely turned off -- `disable_tiling()` clears the flag but
+leaves the geometry, and most of the consumers never touch the flag at all.
+
+Two siblings solve the same problem for their own classes: `patch_qwen_image_vae_tiling` for the
+Qwen-Image VAE, and `stable_diffusion.vae_tiling.patch_vae_tiling_params` for SD's. Neither fits
+here -- the SD one is typed to AutoencoderKL/AutoencoderTiny, patches three diffusers-specific
+attributes the FLUX autoencoder does not have, and leaves `use_tiling` to the caller.
+"""
+
+from contextlib import contextmanager
+from typing import Any, Iterator
+
+from invokeai.backend.flux.modules.autoencoder import AutoEncoder, resolve_tile_size
+
+# Attributes that carry tiling state, across the VAE classes that reach these nodes: InvokeAI's FLUX
+# AutoEncoder and diffusers' AutoencoderKL. Read defensively -- a class that has none of them simply
+# has nothing to restore.
+_TILING_ATTRS = (
+ "use_tiling",
+ "tile_sample_min_size",
+ "tile_overlap",
+ "tile_latent_min_size",
+ "tile_overlap_factor",
+)
+
+_MISSING = object()
+
+
+@contextmanager
+def scoped_vae_tiling(vae: Any, tile_size: int | None) -> Iterator[None]:
+ """Set the VAE's tiling state for the duration of the block, then restore exactly what was there.
+
+ `tile_size=None` decodes in a single pass; `0` means "the VAE's own default"; any other value is
+ the tile size in output pixels.
+ """
+ original = {name: getattr(vae, name, _MISSING) for name in _TILING_ATTRS}
+ try:
+ if tile_size is None:
+ vae.disable_tiling()
+ elif _accepts_tile_size(vae):
+ # resolve_tile_size owns the 0/negative sentinel and the cost floor, so every caller
+ # 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.
+ vae.enable_tiling()
+ yield
+ finally:
+ for name, value in original.items():
+ if value is not _MISSING:
+ setattr(vae, name, value)
+
+
+def _accepts_tile_size(vae: Any) -> bool:
+ """True if `enable_tiling` takes a tile size. Diffusers' AutoencoderKL takes no arguments."""
+ return isinstance(vae, AutoEncoder)
diff --git a/invokeai/backend/util/vae_working_memory.py b/invokeai/backend/util/vae_working_memory.py
index 81d002c61b..513aaf34fa 100644
--- a/invokeai/backend/util/vae_working_memory.py
+++ b/invokeai/backend/util/vae_working_memory.py
@@ -7,7 +7,7 @@ from diffusers.models.autoencoders.autoencoder_kl_wan import AutoencoderKLWan
from diffusers.models.autoencoders.autoencoder_tiny import AutoencoderTiny
from invokeai.app.invocations.constants import LATENT_SCALE_FACTOR
-from invokeai.backend.flux.modules.autoencoder import DEFAULT_TILE_SAMPLE_MIN_SIZE, AutoEncoder
+from invokeai.backend.flux.modules.autoencoder import AutoEncoder, resolve_tile_size
_WAN_VAE_SINGLE_FRAME_DECODE_SCALING_CONSTANT = 2900
_WAN_VAE_VIDEO_DECODE_SCALING_CONSTANT_A14B = 6500
@@ -84,9 +84,8 @@ def estimate_vae_working_memory_flux(
`tile_size` is in output pixels and defaults to None, i.e. a single-pass decode -- the six
existing call sites depend on that signature. When set, the estimate is bounded by one tile
- instead of the whole image, because a tiled decode never holds more than that. `tile_size=0`
- means "whatever the VAE's own default is"; a VAE that has no such default falls back to the
- autoencoder's tile size.
+ instead of the whole image, because a tiled decode never holds more than that. `tile_size <= 0`
+ is the nodes' "use the default" sentinel; see `resolve_tile_size`.
"""
latent_scale_factor_for_operation = LATENT_SCALE_FACTOR if operation == "decode" else 1
@@ -97,14 +96,10 @@ def estimate_vae_working_memory_flux(
scaling_constant = 2200 if operation == "decode" else 1100
if tile_size is not None:
- if tile_size == 0:
- # Not every VAE reaching this estimator is an InvokeAI AutoEncoder -- the Z-Image nodes
- # also pass a diffusers AutoencoderKL -- so this cannot dereference the attribute the way
- # estimate_vae_working_memory_sd15_sdxl does.
- tile_size = getattr(vae, "tile_sample_min_size", DEFAULT_TILE_SAMPLE_MIN_SIZE)
- assert isinstance(tile_size, int)
- out_h = tile_size
- out_w = tile_size
+ # Resolved against a module-level constant, never by reading `vae.tile_sample_min_size`: the
+ # VAE belongs to the model cache, so that attribute reflects whatever the previous
+ # invocation set rather than the default this node is asking for.
+ out_h = out_w = resolve_tile_size(tile_size)
# A 25% margin for tile overlap and the number of tiles, mirroring the SD1/SDXL estimator.
working_memory = out_h * out_w * element_size * scaling_constant * 1.25
else:
diff --git a/tests/app/invocations/test_z_image_tiled_decode.py b/tests/app/invocations/test_z_image_tiled_decode.py
index 9a3939ef91..255cc88ac3 100644
--- a/tests/app/invocations/test_z_image_tiled_decode.py
+++ b/tests/app/invocations/test_z_image_tiled_decode.py
@@ -7,7 +7,7 @@ import torch
from diffusers.models.autoencoders.autoencoder_kl import AutoencoderKL
from invokeai.app.invocations.z_image_latents_to_image import ZImageLatentsToImageInvocation
-from invokeai.backend.flux.modules.autoencoder import DEFAULT_TILE_SAMPLE_MIN_SIZE
+from invokeai.backend.flux.modules.autoencoder import DEFAULT_TILE_SAMPLE_MIN_SIZE, MIN_TILE_SAMPLE_SIZE
from invokeai.backend.flux.modules.autoencoder import AutoEncoder as FluxAutoEncoder
from invokeai.backend.util.vae_working_memory import estimate_vae_working_memory_flux
@@ -47,25 +47,34 @@ class TestFluxWorkingMemoryEstimate:
)
assert tiled < untiled
- def test_tile_size_zero_resolves_against_the_vae(self):
+ def test_the_sentinel_does_not_read_the_size_off_the_vae(self):
+ """Upstream #9427 found this exact shape of bug in the Qwen estimator: reading
+ `vae.tile_sample_min_size` returns whatever the *previous* invocation left on the cached
+ module, not the default this node is asking for."""
vae = _mock_flux_vae()
- vae.tile_sample_min_size = 384
+ vae.tile_sample_min_size = 384 # as if a previous run had set it
estimate = estimate_vae_working_memory_flux(
operation="decode", image_tensor=torch.zeros(1, 16, 192, 192), vae=vae, tile_size=0
)
- assert estimate == int(384 * 384 * 2 * 2200 * 1.25)
+ assert estimate == int(DEFAULT_TILE_SAMPLE_MIN_SIZE**2 * 2 * 2200 * 1.25)
- def test_tile_size_zero_on_a_vae_without_a_default_does_not_raise(self):
+ def test_the_sentinel_works_on_a_vae_without_that_attribute_at_all(self):
# The Z-Image nodes also hand a diffusers AutoencoderKL to this estimator; the SD1/SDXL
# sibling dereferences `vae.tile_sample_min_size` directly and would raise here.
vae = MagicMock(spec=AutoencoderKL)
- vae.parameters.return_value = iter([torch.zeros(1, dtype=torch.float16)])
+ vae.parameters.side_effect = lambda: iter([torch.zeros(1, dtype=torch.float16)])
del vae.tile_sample_min_size
estimate = estimate_vae_working_memory_flux(
operation="decode", image_tensor=torch.zeros(1, 16, 192, 192), vae=vae, tile_size=0
)
assert estimate == int(DEFAULT_TILE_SAMPLE_MIN_SIZE**2 * 2 * 2200 * 1.25)
+ def test_a_tile_below_the_cost_floor_is_estimated_at_the_floor(self):
+ estimate = estimate_vae_working_memory_flux(
+ operation="decode", image_tensor=torch.zeros(1, 16, 192, 192), vae=_mock_flux_vae(), tile_size=8
+ )
+ assert estimate == int(MIN_TILE_SAMPLE_SIZE**2 * 2 * 2200 * 1.25)
+
def _build_decode_mocks(latents: torch.Tensor, decoded: torch.Tensor, force_tiled_decode: bool = False):
"""Wire ZImageLatentsToImageInvocation.invoke to run end-to-end on CPU against a mocked FLUX VAE."""
@@ -109,10 +118,20 @@ class TestTilingIsWired:
vae.disable_tiling.assert_called_once()
vae.enable_tiling.assert_not_called()
+ def test_the_tiling_state_is_restored_after_the_invocation(self):
+ """The VAE belongs to the model cache and is shared with nodes that never touch the flag --
+ FLUX.1 encode, PiD, Anima's FLUX branch. A tiled run must not leave them tiled."""
+ vae, _, context = _build_decode_mocks(torch.zeros(1, 16, 64, 64), torch.zeros(1, 3, 512, 512))
+ vae.use_tiling = False
+ vae.tile_sample_min_size = DEFAULT_TILE_SAMPLE_MIN_SIZE
+ _build_invocation(tiled=True, tile_size=256).invoke(context)
+ assert vae.use_tiling is False
+ assert vae.tile_sample_min_size == DEFAULT_TILE_SAMPLE_MIN_SIZE
+
def test_the_node_field_reaches_the_tiled_path(self):
vae, _, context = _build_decode_mocks(torch.zeros(1, 16, 64, 64), torch.zeros(1, 3, 512, 512))
_build_invocation(tiled=True).invoke(context)
- vae.enable_tiling.assert_called_once_with()
+ vae.enable_tiling.assert_called_once_with(tile_sample_min_size=DEFAULT_TILE_SAMPLE_MIN_SIZE)
vae.disable_tiling.assert_not_called()
def test_force_tiled_decode_reaches_the_tiled_path(self):
@@ -121,7 +140,7 @@ class TestTilingIsWired:
torch.zeros(1, 16, 64, 64), torch.zeros(1, 3, 512, 512), force_tiled_decode=True
)
_build_invocation().invoke(context)
- vae.enable_tiling.assert_called_once_with()
+ vae.enable_tiling.assert_called_once_with(tile_sample_min_size=DEFAULT_TILE_SAMPLE_MIN_SIZE)
def test_a_requested_tile_size_is_passed_through(self):
vae, _, context = _build_decode_mocks(torch.zeros(1, 16, 64, 64), torch.zeros(1, 3, 512, 512))
@@ -155,7 +174,7 @@ class TestOomFallback:
result = _build_invocation().invoke(context)
assert vae.decode.call_count == 2
- vae.enable_tiling.assert_called_once_with()
+ vae.enable_tiling.assert_called_once_with(tile_sample_min_size=DEFAULT_TILE_SAMPLE_MIN_SIZE)
assert result.width == 512
def test_a_non_oom_error_propagates_without_a_retry(self):
diff --git a/tests/backend/util/test_vae_tiling_scope.py b/tests/backend/util/test_vae_tiling_scope.py
new file mode 100644
index 0000000000..ff39f3f963
--- /dev/null
+++ b/tests/backend/util/test_vae_tiling_scope.py
@@ -0,0 +1,147 @@
+"""Scoped tiling state, and the tile-size sentinel.
+
+Both are here because of what the Qwen-Image tiling PR (upstream #9427) found the hard way: an
+`enable_tiling()` call writes through to the model cache's own module, `disable_tiling()` restores
+the flag but not the geometry, and an estimator that reads the size back off the module gets
+whatever the previous invocation left rather than the default it asked for.
+"""
+
+import pytest
+import torch
+from diffusers.models.autoencoders.autoencoder_kl import AutoencoderKL
+
+from invokeai.backend.flux.modules.autoencoder import (
+ DEFAULT_TILE_OVERLAP,
+ DEFAULT_TILE_SAMPLE_MIN_SIZE,
+ MIN_TILE_SAMPLE_SIZE,
+ AutoEncoder,
+ AutoEncoderParams,
+ resolve_tile_size,
+)
+from invokeai.backend.util.vae_tiling_scope import scoped_vae_tiling
+
+
+def _build_autoencoder() -> AutoEncoder:
+ params = AutoEncoderParams(
+ resolution=256,
+ in_channels=3,
+ ch=32,
+ out_ch=3,
+ ch_mult=[1, 2, 4, 4],
+ num_res_blocks=1,
+ z_channels=16,
+ scale_factor=0.3611,
+ shift_factor=0.1159,
+ )
+ torch.manual_seed(0)
+ return AutoEncoder(params).eval()
+
+
+class TestResolveTileSize:
+ @pytest.mark.parametrize("sentinel", [0, -8, -1024])
+ def test_the_sentinel_resolves_to_the_module_default(self, sentinel):
+ # The workflow UI cannot send None, so 0 is "use the default". A negative value is not worth
+ # failing a generation over -- upstream #9427 confirmed the same for the Qwen nodes.
+ assert resolve_tile_size(sentinel) == DEFAULT_TILE_SAMPLE_MIN_SIZE
+
+ @pytest.mark.parametrize("small", [8, 64, MIN_TILE_SAMPLE_SIZE - 8])
+ def test_values_below_the_cost_floor_are_clamped(self, small):
+ # A cost floor, not a correctness one: the tile count grows with the inverse square of the
+ # tile size, and small tiles are also measurably less accurate.
+ assert resolve_tile_size(small) == MIN_TILE_SAMPLE_SIZE
+
+ @pytest.mark.parametrize("size", [128, 256, 384, 512, 1024])
+ def test_usable_values_pass_through(self, size):
+ assert resolve_tile_size(size) == size
+
+
+class TestEveryFieldValueProducesTheRightShape:
+ """The sweep upstream #9427 used to catch silent truncation.
+
+ That bug cannot occur here -- the destination is preallocated at the exact output size and tiles
+ are merged into it, rather than a loop stepping by one quantity and slicing by another -- but the
+ guarantee is worth asserting rather than reasoning about, across the shapes most likely to leave
+ an awkward remainder.
+ """
+
+ @pytest.mark.parametrize("latent_hw", [(2, 2), (10, 10), (50, 50), (34, 18), (128, 72), (18, 34), (150, 10)])
+ @pytest.mark.parametrize("tile_size", [0, 8, 128, 256, 384, 512, 1024])
+ def test_output_shape_is_exact(self, latent_hw, tile_size):
+ ae = _build_autoencoder()
+ h, w = latent_hw
+ z = torch.randn(1, 16, h, w)
+ with torch.no_grad(), scoped_vae_tiling(ae, tile_size):
+ out = ae.decode(z)
+ assert out.shape == (1, 3, h * 8, w * 8)
+
+
+class TestStateIsRestored:
+ def test_the_normal_path_restores_everything(self):
+ ae = _build_autoencoder()
+ before = (ae.use_tiling, ae.tile_sample_min_size, ae.tile_overlap)
+ with scoped_vae_tiling(ae, 256):
+ assert ae.use_tiling is True
+ assert ae.tile_sample_min_size == 256
+ assert (ae.use_tiling, ae.tile_sample_min_size, ae.tile_overlap) == before
+
+ def test_the_untiled_path_restores_everything(self):
+ # Entering with tiling already on: the block must decode untiled and hand the state back.
+ ae = _build_autoencoder()
+ ae.enable_tiling(tile_sample_min_size=256)
+ before = (ae.use_tiling, ae.tile_sample_min_size, ae.tile_overlap)
+ with scoped_vae_tiling(ae, None):
+ assert ae.use_tiling is False
+ assert (ae.use_tiling, ae.tile_sample_min_size, ae.tile_overlap) == before
+
+ def test_an_exception_still_restores(self):
+ # The OOM retry path raises through this context manager, so `finally` is load-bearing.
+ ae = _build_autoencoder()
+ before = (ae.use_tiling, ae.tile_sample_min_size, ae.tile_overlap)
+ with pytest.raises(RuntimeError, match="boom"):
+ with scoped_vae_tiling(ae, 256):
+ raise RuntimeError("boom")
+ assert (ae.use_tiling, ae.tile_sample_min_size, ae.tile_overlap) == before
+
+ def test_geometry_does_not_leak_between_two_scopes(self):
+ """The bug this exists for: `disable_tiling()` clears the flag but keeps the geometry, so a
+ size set once would otherwise silently become the default for everyone afterwards."""
+ ae = _build_autoencoder()
+ with scoped_vae_tiling(ae, 256):
+ pass
+ assert ae.tile_sample_min_size == DEFAULT_TILE_SAMPLE_MIN_SIZE
+ assert ae.tile_overlap == DEFAULT_TILE_OVERLAP
+ with scoped_vae_tiling(ae, 0):
+ assert ae.tile_sample_min_size == DEFAULT_TILE_SAMPLE_MIN_SIZE
+
+ def test_a_tiled_decode_does_not_leave_the_shared_vae_tiled(self):
+ """Nine nodes reach this class and most never touch the tiling flag -- FLUX.1 encode, PiD,
+ and Anima's FLUX branch among them. A leaked flag would silently tile their work."""
+ ae = _build_autoencoder()
+ z = torch.randn(1, 16, 96, 96)
+ with torch.no_grad():
+ with scoped_vae_tiling(ae, 0):
+ ae.decode(z)
+ assert ae.use_tiling is False
+ # What an unguarded consumer would get next, decoded with no tiling call of its own.
+ after = ae.decode(z)
+ ae.disable_tiling()
+ expected = ae.decode(z)
+ assert torch.equal(after, expected)
+
+
+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(
+ in_channels=3,
+ out_channels=3,
+ latent_channels=4,
+ block_out_channels=(32,),
+ down_block_types=("DownEncoderBlock2D",),
+ up_block_types=("UpDecoderBlock2D",),
+ layers_per_block=1,
+ norm_num_groups=32,
+ )
+ with scoped_vae_tiling(vae, 384):
+ assert vae.use_tiling is True
+ assert vae.use_tiling is False