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
"""Tiling controls, the OOM fallback, and the tile-aware working-memory estimate for Z-Image."""
from unittest.mock import MagicMock, patch
import pytest
import torch
from diffusers.models.autoencoders.autoencoder_kl import AutoencoderKL
from invokeai.app.invocations.vae.z_image_image_to_latents import ZImageImageToLatentsInvocation
from invokeai.app.invocations.vae.z_image_latents_to_image import ZImageLatentsToImageInvocation
from invokeai.backend.util.devices import TorchDevice
from invokeai.backend.util.vae_tiling_scope import DEFAULT_TILE_SAMPLE_MIN_SIZE, MIN_TILE_SAMPLE_SIZE
from invokeai.backend.util.vae_working_memory import VAE_FLUX_SPEC, estimate_vae_working_memory_flux
from invokeai.backend.working_memory import spec as spec_module
from invokeai.backend.working_memory.coefficients import shipped_coefficients
from invokeai.backend.working_memory.platform import Platform
def _flux_reservation(*args, **kwargs) -> int:
"""What `estimate_vae_working_memory_flux` reserves; the estimator cells are about its size."""
return estimate_vae_working_memory_flux(*args, **kwargs).reservation_bytes
CPU = Platform("cpu", "native", "linux")
def _line(platform: Platform, operation: str, pixels: float, dtype: str = "bf16") -> float:
"""What the shipped FLUX.1 VAE line the estimator resolves on `platform` prices over `pixels` output pixels."""
values = shipped_coefficients(VAE_FLUX_SPEC, platform).values
return values[f"k_{operation}_{dtype}"] * pixels + values[f"b_{operation}_{dtype}"]
def _mock_flux_vae(element_size_bytes: int = 2) -> MagicMock:
"""A stand-in for the estimator cells only: they read the parameter dtype, and the geometry a
tiled estimate snaps its tile with as `scoped_vae_tiling` does, set here to the stock 8x
downsample and 0.25 overlap.
The node-wiring cells below use a real `AutoencoderKL`, because they are about the tiling state
`scoped_vae_tiling` sets and restores: the class keeps it in attributes `__init__` sets, so a
spec'd mock has only what is set on it by hand, as the two attributes here are.
"""
vae = MagicMock(spec=AutoencoderKL)
dtype = torch.bfloat16 if element_size_bytes == 2 else torch.float32
# A fresh iterator per call: the decode path reads `parameters()` after the estimator already
# has, and a single stored iterator would be exhausted by then.
vae.parameters.side_effect = lambda: iter([torch.zeros(1, dtype=dtype)])
vae.config.block_out_channels = (128, 256, 512, 512)
vae.tile_overlap_factor = 0.25
return vae
class TestFluxWorkingMemoryEstimate:
@pytest.fixture(autouse=True)
def _fused_non_rocm_build(self, monkeypatch):
"""`estimate_vae_working_memory_flux` resolves a device when the caller passes none, and prices the mid-block
score matrix for it. On a ROCm rig that resolves to `cuda`, where the head-dim guard charges 4.25GiB for the
1024px case below -- which the expected value here clears by 1%, so these exact-value assertions turn
build-dependent the moment either constant moves. Pin the fused, non-HIP regime they are written for, which
also selects the cuDNN coefficients; `TestClassicVaeEstimators` in
`tests/backend/util/test_rocm_sdpa_head_dim_guard.py` owns the ROCm side of this estimator.
"""
import invokeai.backend.util.attention as attention
import invokeai.backend.util.vae_working_memory as vwm
monkeypatch.setattr(attention, "_IS_ROCM", False)
monkeypatch.setattr(vwm.TorchDevice, "choose_torch_device", classmethod(lambda cls: torch.device("cpu")))
@pytest.mark.parametrize(
("hip", "operation", "conv_backend"),
[
(None, "decode", "cudnn"),
(None, "encode", "cudnn"),
("7.14.0", "decode", "miopen"),
("7.14.0", "encode", "miopen"),
],
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, conv_backend
):
"""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 = _flux_reservation(
operation=operation, image_tensor=tensor, vae=_mock_flux_vae(), device=torch.device("cuda", 0)
)
on_cpu = _flux_reservation(
operation=operation, image_tensor=tensor, vae=_mock_flux_vae(), device=torch.device("cpu")
)
assert estimate == int(_line(Platform(conv_backend, "native", "linux"), operation, 512 * 512))
assert on_cpu == int(_line(CPU, operation, 512 * 512)), "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)
# The bf16 decode line over 1024x1024 output pixels
expected = int(_line(CPU, "decode", 1024 * 1024))
actual = _flux_reservation(operation="decode", image_tensor=latents, vae=_mock_flux_vae())
assert actual == expected
def test_every_tiled_term_follows_the_vaes_dtype(self):
"""An fp32 VAE prices its tile, its tiled line and its assembly line at fp32."""
latents = torch.zeros(1, 16, 192, 192)
fp32 = estimate_vae_working_memory_flux(
operation="decode", image_tensor=latents, vae=_mock_flux_vae(element_size_bytes=4), tile_size=512
)
coefficients = {term.coefficient for term in fp32.terms if term.coefficient is not None}
assert fp32.features["dtype"] == "fp32"
assert {name.rsplit("_", 1)[1] for name in coefficients} == {"fp32"}
assert {name.split("_", 1)[1].rsplit("_", 1)[0] for name in coefficients} == {
"decode",
"tiled_decode",
"assembled_decode",
}
@pytest.mark.parametrize("latent_hw", [(128, 128), (192, 192), (256, 256)])
def test_a_tiled_estimate_stays_a_fraction_of_the_untiled_one(self, latent_hw):
"""The point of the bound: the decode itself costs one tile, whatever the resolution.
Not a flat number -- the assembled image and the node's post-processing are full-resolution
however small the tile is, so an O(image) term rides along. That term is small next to the
decode the bound removes, and this pins how small across a 4x span of image area, on the
RTX 4090's measured lines. (A platform nothing is measured on floors each tiled and assembly
value at its largest over the measured ones, which can lift a small tiled decode above half
the single pass: a conservative stand-in, not this bound.)
"""
latents = torch.zeros(1, 16, *latent_hw)
with patch.object(spec_module, "platform_for", return_value=Platform("cudnn", "native", "linux")):
untiled = _flux_reservation(operation="decode", image_tensor=latents, vae=_mock_flux_vae())
tiled = _flux_reservation(operation="decode", image_tensor=latents, vae=_mock_flux_vae(), tile_size=512)
assert tiled < untiled / 2
def test_a_tile_larger_than_the_image_is_not_estimated_as_tiled(self):
"""`_tiled_decode` short-circuits once the tile covers the image, so the reservation has to.
`tile_size` has no upper bound, and the quadratic tile term ran away from the decode that
would actually happen: a 4096px tile on a 1024px image reserved ~23GB for a single-pass
decode needing ~4.6GB, evicting the transformer from the cache to make room for nothing.
"""
latents = torch.zeros(1, 16, 128, 128) # 1024px
untiled = _flux_reservation(operation="decode", image_tensor=latents, vae=_mock_flux_vae())
oversized = _flux_reservation(operation="decode", image_tensor=latents, vae=_mock_flux_vae(), tile_size=4096)
assert oversized == untiled
def test_a_tile_wider_than_one_axis_is_priced_at_the_clamped_tile(self):
"""`calc_tiles_min_overlap` clamps the tile to the image on each axis independently.
A 1024x8192 image tiled with a 4096px tile therefore decodes 1024x4096 tiles, never
4096x4096 ones. Pricing the requested tile squared put the reservation 2.5x *above* the
single-pass decode that tiling is there to avoid -- ~92GB against ~37GB.
"""
latents = torch.zeros(1, 16, 128, 1024) # 1024 x 8192 px: only the long axis exceeds the tile
tiled = _flux_reservation(operation="decode", image_tensor=latents, vae=_mock_flux_vae(), tile_size=4096)
untiled = _flux_reservation(operation="decode", image_tensor=latents, vae=_mock_flux_vae())
assert tiled < untiled
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."""
latents = torch.zeros(1, 16, 192, 192)
vae = _mock_flux_vae()
vae.tile_sample_min_size = 384 # as if a previous run had set it
estimate = _flux_reservation(operation="decode", image_tensor=latents, vae=vae, tile_size=0)
assert estimate == _flux_reservation(
operation="decode", image_tensor=latents, vae=_mock_flux_vae(), tile_size=DEFAULT_TILE_SAMPLE_MIN_SIZE
)
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.
latents = torch.zeros(1, 16, 192, 192)
vae = _mock_flux_vae()
del vae.tile_sample_min_size
estimate = _flux_reservation(operation="decode", image_tensor=latents, vae=vae, tile_size=0)
assert estimate == _flux_reservation(
operation="decode", image_tensor=latents, vae=_mock_flux_vae(), tile_size=DEFAULT_TILE_SAMPLE_MIN_SIZE
)
def test_a_tile_below_the_cost_floor_is_estimated_at_the_floor(self):
latents = torch.zeros(1, 16, 192, 192)
estimate = _flux_reservation(operation="decode", image_tensor=latents, vae=_mock_flux_vae(), tile_size=8)
assert estimate == _flux_reservation(
operation="decode", image_tensor=latents, vae=_mock_flux_vae(), tile_size=MIN_TILE_SAMPLE_SIZE
)
class TestTheEncodeEstimate:
"""Nothing exercised this estimator with `operation="encode"` before the FLUX.1 VAE could tile
an encode at all -- its docstring said as much: "a `tile_size` with `operation="encode"` would
price a tiled encode that cannot happen, and no call site passes one".
The tile is priced the same way for either operation. What tiling adds on top is not: a decode
assembles an image and converts it to bytes, while an encode slices its input and assembles
moments at 1/64 the area. Each operation has its own tiled line.
"""
@pytest.fixture(autouse=True)
def _fused_non_rocm_build(self, monkeypatch):
import invokeai.backend.util.vae_working_memory as vwm
monkeypatch.setattr("invokeai.backend.util.vae_working_memory.sdpa_score_matrix_bytes", lambda *a, **k: 0)
monkeypatch.setattr(torch.version, "hip", None, raising=False)
# Priced on the CPU whatever the machine: a GPU would select its own coefficients.
monkeypatch.setattr(vwm.TorchDevice, "choose_torch_device", classmethod(lambda cls: torch.device("cpu")))
def test_an_untiled_encode_is_the_whole_image_at_the_encode_coefficient(self):
"""What the call sites that pass no tile reserve: the full image, priced at the cuDNN encode coefficient."""
image = torch.zeros(1, 3, 1024, 1024)
assert _flux_reservation("encode", image, _mock_flux_vae()) == int(_line(CPU, "encode", 1024 * 1024))
def test_a_tiled_estimate_is_flat_in_the_image_size_where_the_untiled_one_is_not(self):
vae = _mock_flux_vae()
estimates = [
_flux_reservation("encode", torch.zeros(1, 3, edge, edge), vae, tile_size=512)
for edge in (1024, 2048, 3072)
]
# Not exactly equal: the input image and the assembled latent are not bounded by tiling.
# But they are a rounding error beside the tile term, which is what "flat" has to mean.
assert max(estimates) < min(estimates) * 1.2
untiled = [_flux_reservation("encode", torch.zeros(1, 3, edge, edge), vae) for edge in (1024, 3072)]
assert untiled == [int(_line(CPU, "encode", edge * edge)) for edge in (1024, 3072)]
def test_a_tile_larger_than_the_image_is_priced_as_the_untiled_encode(self):
"""`scoped_vae_tiling` hands the VAE a tile it will not use below its own threshold, and an
oversized tile would otherwise reserve for a pass that never runs."""
vae = _mock_flux_vae()
image = torch.zeros(1, 3, 512, 512)
assert _flux_reservation("encode", image, vae, tile_size=1024) == _flux_reservation("encode", image, vae)
def _build_decode_mocks(vae, latents: torch.Tensor, decoded: torch.Tensor, force_tiled_decode: bool = False):
"""Wire ZImageLatentsToImageInvocation.invoke to run end-to-end on CPU against a real tiny VAE.
`decode` is replaced so the test controls the result and can raise, and so the tiling state at
the moment of the call is recorded -- that is the thing under test, and the scope has restored
it by the time `invoke` returns.
"""
tiling_state: list[dict] = []
def record_and_return(latents_arg, return_dict=True):
tiling_state.append({"use_tiling": vae.use_tiling, "tile_sample_min_size": vae.tile_sample_min_size})
return (decoded,) if return_dict is False else MagicMock(sample=decoded)
vae.decode = MagicMock(side_effect=record_and_return)
vae_info = MagicMock()
vae_info.model = vae
vae_info.compute_device = torch.device("cpu")
cm = MagicMock()
cm.__enter__ = MagicMock(return_value=(None, vae))
cm.__exit__ = MagicMock(return_value=None)
vae_info.model_on_device.return_value = cm
context = MagicMock()
context.models.load.return_value = vae_info
context.tensors.load.return_value = latents
# A bare MagicMock config would read as truthy and silently tile everything.
context.config.get.return_value.force_tiled_decode = force_tiled_decode
image_dto = MagicMock()
image_dto.image_name = "test.png"
image_dto.width = decoded.shape[-1]
image_dto.height = decoded.shape[-2]
context.images.save.return_value = image_dto
return vae_info, context, tiling_state
def _build_invocation(tiled: bool = False, tile_size: int = 0) -> ZImageLatentsToImageInvocation:
# `seamless_axes=[]` rather than a MagicMock: the node patches seamless for every VAE it accepts
# now that there is only one class, and `SeamlessExt` would iterate a MagicMock.
return ZImageLatentsToImageInvocation.model_construct(
latents=MagicMock(latents_name="test_latents"),
vae=MagicMock(vae=MagicMock(), seamless_axes=[]),
tiled=tiled,
tile_size=tile_size,
)
class TestTilingIsWired:
def test_the_default_decodes_untiled(self, flux_shaped_vae):
vae = flux_shaped_vae()
_, context, state = _build_decode_mocks(vae, torch.zeros(1, 16, 64, 64), torch.zeros(1, 3, 512, 512))
_build_invocation().invoke(context)
assert state[0]["use_tiling"] is False
def test_the_node_field_reaches_the_tiled_path(self, flux_shaped_vae):
vae = flux_shaped_vae()
_, context, state = _build_decode_mocks(vae, torch.zeros(1, 16, 64, 64), torch.zeros(1, 3, 512, 512))
_build_invocation(tiled=True).invoke(context)
assert state[0]["use_tiling"] is True
assert state[0]["tile_sample_min_size"] == DEFAULT_TILE_SAMPLE_MIN_SIZE
def test_a_batch_of_latents_decodes_and_is_priced_as_its_first_sample(self, flux_shaped_vae):
"""The node returns the first image only, so the VAE and the estimate see one sample, not the whole batch."""
path = "invokeai.app.invocations.vae.z_image_latents_to_image.estimate_vae_working_memory_flux"
vae = flux_shaped_vae()
batch = torch.cat([torch.zeros(1, 16, 64, 64), torch.ones(1, 16, 64, 64)])
_, context, _ = _build_decode_mocks(vae, batch, torch.zeros(1, 3, 512, 512))
with patch(path, wraps=estimate_vae_working_memory_flux) as estimate:
_build_invocation(tiled=True).invoke(context)
assert estimate.call_args.kwargs["image_tensor"].shape[0] == 1
decoded_input = vae.decode.call_args.args[0]
assert decoded_input.shape[0] == 1
assert torch.allclose(decoded_input, (batch[:1] / vae.config.scaling_factor) + (vae.config.shift_factor or 0.0))
def test_force_tiled_decode_reaches_the_tiled_path(self, flux_shaped_vae):
"""The config switch a small-VRAM user actually has; the node field is not the only way in."""
vae = flux_shaped_vae()
_, context, state = _build_decode_mocks(
vae, torch.zeros(1, 16, 64, 64), torch.zeros(1, 3, 512, 512), force_tiled_decode=True
)
_build_invocation().invoke(context)
assert state[0]["use_tiling"] is True
assert state[0]["tile_sample_min_size"] == DEFAULT_TILE_SAMPLE_MIN_SIZE
def test_a_requested_tile_size_is_passed_through(self, flux_shaped_vae):
vae = flux_shaped_vae()
_, context, state = _build_decode_mocks(vae, torch.zeros(1, 16, 64, 64), torch.zeros(1, 3, 512, 512))
_build_invocation(tiled=True, tile_size=384).invoke(context)
assert state[0]["tile_sample_min_size"] == 384
def test_the_tiling_state_is_restored_afterwards(self, flux_shaped_vae):
"""The VAE is shared with the encode node and with FLUX.1; a tiled decode must not leak."""
vae = flux_shaped_vae()
_, context, _ = _build_decode_mocks(vae, torch.zeros(1, 16, 64, 64), torch.zeros(1, 3, 512, 512))
before = (vae.use_tiling, vae.tile_sample_min_size, vae.tile_latent_min_size)
_build_invocation(tiled=True, tile_size=384).invoke(context)
assert (vae.use_tiling, vae.tile_sample_min_size, vae.tile_latent_min_size) == before
@pytest.mark.parametrize("auto", [True, False], ids=["auto-tiled-decode-on", "auto-tiled-decode-off"])
def test_a_decode_too_large_for_its_gpu_is_tiled_up_front_unless_switched_off(
self, auto, flux_shaped_vae, fixed_working_memory
):
"""Where the driver pages instead of raising an OOM, the retry below never fires: the estimate decides."""
module = "invokeai.app.invocations.vae.z_image_latents_to_image"
vae_info, context, state = _build_decode_mocks(
flux_shaped_vae(), torch.zeros(1, 16, 64, 64), torch.zeros(1, 3, 512, 512)
)
context.config.get.return_value.auto_tiled_decode = auto
untiled, tiled = fixed_working_memory(20 * 2**30), fixed_working_memory(2 * 2**30)
with (
patch(f"{module}.estimate_vae_working_memory_flux", side_effect=[untiled, tiled]) as estimate,
patch(f"{module}.should_pretile_vae_decode", return_value=True) as pretile,
):
_build_invocation().invoke(context)
if auto:
pretile.assert_called_once_with(vae_info.compute_device, 20 * 2**30)
assert estimate.call_args.kwargs["tile_size"] == 0
vae_info.model_on_device.assert_called_once_with(working_memory=tiled)
assert state[0]["use_tiling"] is True
else:
pretile.assert_not_called()
assert estimate.call_count == 1
vae_info.model_on_device.assert_called_once_with(working_memory=untiled)
assert state[0]["use_tiling"] is False
def test_requested_tiling_skips_the_untiled_estimate(self, flux_shaped_vae, fixed_working_memory):
module = "invokeai.app.invocations.vae.z_image_latents_to_image"
_, context, _ = _build_decode_mocks(flux_shaped_vae(), torch.zeros(1, 16, 64, 64), torch.zeros(1, 3, 512, 512))
with (
patch(
f"{module}.estimate_vae_working_memory_flux", return_value=fixed_working_memory(2 * 2**30)
) as estimate,
patch(f"{module}.should_pretile_vae_decode") as pretile,
):
_build_invocation(tiled=True).invoke(context)
assert estimate.call_count == 1
pretile.assert_not_called()
@pytest.mark.parametrize("tiled,expected_tile_size", [(False, None), (True, 0)])
def test_the_estimate_is_tile_bounded_only_when_tiling(
self, flux_shaped_vae, fixed_working_memory, tiled, expected_tile_size
):
path = "invokeai.app.invocations.vae.z_image_latents_to_image.estimate_vae_working_memory_flux"
vae = flux_shaped_vae()
_, context, _ = _build_decode_mocks(vae, torch.zeros(1, 16, 64, 64), torch.zeros(1, 3, 512, 512))
with patch(path, return_value=fixed_working_memory(1024)) as estimate:
_build_invocation(tiled=tiled).invoke(context)
assert estimate.call_args.kwargs["tile_size"] == expected_tile_size
class TestOomFallback:
@pytest.mark.parametrize(
"oom_error",
[
torch.cuda.OutOfMemoryError("CUDA out of memory. Tried to allocate 5.9 GiB"),
RuntimeError("CUDA error: out of memory"),
RuntimeError("cuDNN error: CUDNN_STATUS_ALLOC_FAILED"),
RuntimeError("Native API failed. Native API returns: UR_RESULT_ERROR_OUT_OF_DEVICE_MEMORY"),
],
)
def test_an_untiled_oom_retries_once_tiled(self, flux_shaped_vae, oom_error):
vae = flux_shaped_vae()
decoded = torch.zeros(1, 3, 512, 512)
_, context, state = _build_decode_mocks(vae, torch.zeros(1, 16, 64, 64), decoded)
calls = {"n": 0}
record = vae.decode.side_effect
def fail_then_succeed(latents_arg, return_dict=True):
calls["n"] += 1
result = record(latents_arg, return_dict=return_dict)
if calls["n"] == 1:
raise oom_error
return result
vae.decode = MagicMock(side_effect=fail_then_succeed)
result = _build_invocation().invoke(context)
assert vae.decode.call_count == 2
assert [call["use_tiling"] for call in state] == [False, True]
assert result.width == 512
# The user gets a different image than they asked for, so both channels have to carry it: the
# progress line while it happens, and a log line a bug report can still be read off afterwards.
context.util.signal_progress.assert_any_call("VAE decode ran out of memory, retrying tiled")
assert "not identical to an untiled decode" in context.logger.warning.call_args[0][0]
def test_a_non_oom_error_propagates_without_a_retry(self, flux_shaped_vae):
vae = flux_shaped_vae()
_, context, state = _build_decode_mocks(vae, torch.zeros(1, 16, 64, 64), torch.zeros(1, 3, 512, 512))
vae.decode = MagicMock(side_effect=RuntimeError("Input type (float) and weight type (half) should be the same"))
with pytest.raises(RuntimeError, match="weight type"):
_build_invocation().invoke(context)
assert vae.decode.call_count == 1
assert state == []
def test_an_oom_while_already_tiled_reraises(self, flux_shaped_vae):
vae = flux_shaped_vae()
_, context, state = _build_decode_mocks(vae, torch.zeros(1, 16, 64, 64), torch.zeros(1, 3, 512, 512))
record = vae.decode.side_effect
def record_then_fail(latents_arg, return_dict=True):
record(latents_arg, return_dict=return_dict)
raise torch.cuda.OutOfMemoryError("CUDA out of memory")
vae.decode = MagicMock(side_effect=record_then_fail)
with pytest.raises(torch.cuda.OutOfMemoryError):
_build_invocation(tiled=True).invoke(context)
# One attempt, and it was already the tiled one -- retrying it tiled again would only burn
# the time a second full decode costs before failing the same way.
assert vae.decode.call_count == 1
assert [call["use_tiling"] for call in state] == [True]
class TestTheEncodeNodeTiling:
"""The encode node called a bare `vae.disable_tiling()` and offered no way to ask for tiling.
That line predates the node having any tiling fields; it was there to give the shared cached VAE
a deterministic state, which the scope now does in both directions.
"""
@staticmethod
def _encode(vae, tiled: bool = False, tile_size: int = 0):
seen: list[dict] = []
real_encode = vae.encode
def record(x, return_dict=True):
seen.append({"use_tiling": vae.use_tiling, "tile_sample_min_size": vae.tile_sample_min_size})
return real_encode(x, return_dict=return_dict)
vae.encode = record
vae_info = MagicMock()
vae_info.model = vae
# A real device: the node places the image on the VAE's own device rather than the session's.
vae_info.compute_device = torch.device("cpu")
cm = MagicMock()
cm.__enter__ = MagicMock(return_value=(None, vae))
cm.__exit__ = MagicMock(return_value=None)
vae_info.model_on_device.return_value = cm
with patch.object(TorchDevice, "choose_torch_device", return_value=torch.device("cpu")):
ZImageImageToLatentsInvocation.vae_encode(
vae_info=vae_info, image_tensor=torch.zeros(1, 3, 512, 512), tiled=tiled, tile_size=tile_size
)
return seen
def test_the_default_encodes_untiled(self, flux_shaped_vae):
vae = flux_shaped_vae()
assert self._encode(vae)[0]["use_tiling"] is False
def test_the_field_reaches_the_tiled_path_and_the_state_is_restored(self, flux_shaped_vae):
vae = flux_shaped_vae()
before = (vae.use_tiling, vae.tile_sample_min_size, vae.tile_latent_min_size)
seen = self._encode(vae, tiled=True, tile_size=384)
assert seen[0]["use_tiling"] is True
assert seen[0]["tile_sample_min_size"] == 384
# Shared with the decode node and with every FLUX.1 node, most of which never touch the flag.
assert (vae.use_tiling, vae.tile_sample_min_size, vae.tile_latent_min_size) == before