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): encode images to the posterior's mean instead of an unseeded sample (#10293)

Alexander Eichhornf5fc12c47b7a
diff --git a/invokeai/app/invocations/vae/anima_image_to_latents.py b/invokeai/app/invocations/vae/anima_image_to_latents.py
index b995a50042..c8f569dcb4 100644
--- a/invokeai/app/invocations/vae/anima_image_to_latents.py
+++ b/invokeai/app/invocations/vae/anima_image_to_latents.py
@@ -104,7 +104,7 @@ class AnimaImageToLatentsInvocation(BaseInvocation, WithMetadata, WithBoard):
image_tensor = image_tensor.unsqueeze(2) # [B, C, H, W] -> [B, C, 1, H, W]
encoded = vae.encode(image_tensor, return_dict=False)[0]
- latents = encoded.sample().to(dtype=vae_dtype)
+ latents = encoded.mode().to(dtype=vae_dtype)
# Normalize to denoiser space: (latents - mean) / std
# This is the inverse of the denormalization in anima_latents_to_image.py
diff --git a/invokeai/app/invocations/vae/cogview4_image_to_latents.py b/invokeai/app/invocations/vae/cogview4_image_to_latents.py
index 117d00a790..3f52fb7b1e 100644
--- a/invokeai/app/invocations/vae/cogview4_image_to_latents.py
+++ b/invokeai/app/invocations/vae/cogview4_image_to_latents.py
@@ -50,8 +50,7 @@ class CogView4ImageToLatentsInvocation(BaseInvocation, WithMetadata, WithBoard):
image_tensor = image_tensor.to(device=vae_info.compute_device, dtype=vae.dtype)
with torch.inference_mode():
image_tensor_dist = vae.encode(image_tensor).latent_dist
- # TODO: Use seed to make sampling reproducible.
- latents: torch.Tensor = image_tensor_dist.sample().to(dtype=vae.dtype)
+ latents: torch.Tensor = image_tensor_dist.mode().to(dtype=vae.dtype)
latents = vae.config.scaling_factor * latents
diff --git a/invokeai/app/invocations/vae/image_to_latents.py b/invokeai/app/invocations/vae/image_to_latents.py
index 94fbada10e..ccd0ca4c77 100644
--- a/invokeai/app/invocations/vae/image_to_latents.py
+++ b/invokeai/app/invocations/vae/image_to_latents.py
@@ -169,9 +169,7 @@ class ImageToLatentsInvocation(BaseInvocation):
def _encode_to_tensor(vae: AutoencoderKL, image_tensor: torch.FloatTensor) -> torch.FloatTensor:
assert isinstance(vae, torch.nn.Module)
image_tensor_dist = vae.encode(image_tensor).latent_dist
- latents: torch.Tensor = image_tensor_dist.sample().to(
- dtype=vae.dtype
- ) # FIXME: uses torch.randn. make reproducible!
+ latents: torch.Tensor = image_tensor_dist.mode().to(dtype=vae.dtype)
return latents
@_encode_to_tensor.register
diff --git a/invokeai/app/invocations/vae/sd3_image_to_latents.py b/invokeai/app/invocations/vae/sd3_image_to_latents.py
index feda46b0e6..a3bdd1628d 100644
--- a/invokeai/app/invocations/vae/sd3_image_to_latents.py
+++ b/invokeai/app/invocations/vae/sd3_image_to_latents.py
@@ -46,8 +46,7 @@ class SD3ImageToLatentsInvocation(BaseInvocation, WithMetadata, WithBoard):
image_tensor = image_tensor.to(device=vae_info.compute_device, dtype=vae.dtype)
with torch.inference_mode():
image_tensor_dist = vae.encode(image_tensor).latent_dist
- # TODO: Use seed to make sampling reproducible.
- latents: torch.Tensor = image_tensor_dist.sample().to(dtype=vae.dtype)
+ latents: torch.Tensor = image_tensor_dist.mode().to(dtype=vae.dtype)
latents = vae.config.scaling_factor * latents
diff --git a/invokeai/app/invocations/vae/wan_image_to_latents.py b/invokeai/app/invocations/vae/wan_image_to_latents.py
index 22543205af..4c3cb9991f 100644
--- a/invokeai/app/invocations/vae/wan_image_to_latents.py
+++ b/invokeai/app/invocations/vae/wan_image_to_latents.py
@@ -74,7 +74,7 @@ class WanImageToLatentsInvocation(BaseInvocation, WithMetadata, WithBoard):
image_tensor = image_tensor.unsqueeze(2) # [B, C, H, W] -> [B, C, 1, H, W]
encoded = vae.encode(image_tensor, return_dict=False)[0]
- latents = encoded.sample().to(dtype=vae_dtype)
+ latents = encoded.mode().to(dtype=vae_dtype)
# Normalise to the denoiser's expected zero-centred space:
# (latents - mean) / std
diff --git a/invokeai/app/invocations/vae/z_image_image_to_latents.py b/invokeai/app/invocations/vae/z_image_image_to_latents.py
index 84d59f59c4..03a1f474f8 100644
--- a/invokeai/app/invocations/vae/z_image_image_to_latents.py
+++ b/invokeai/app/invocations/vae/z_image_image_to_latents.py
@@ -50,12 +50,11 @@ class ZImageImageToLatentsInvocation(BaseInvocation, WithMetadata, WithBoard):
image_tensor: torch.Tensor,
tiled: bool = False,
tile_size: int = 0,
- deterministic: bool = False,
) -> torch.Tensor:
- """Encode an image to a Z-Image latent: a sample of the encoder's distribution, or its mode when
- ``deterministic``.
+ """Encode an image to a Z-Image latent: the mode of the encoder's distribution, so the same image always
+ encodes to the same latent.
- `z_image_denoise` also encodes its control image here, deterministically as VideoX-Fun does, at
+ `z_image_denoise` also encodes its control image here, as VideoX-Fun does, at
generation resolution. That is usually small enough to encode whole, but an upscale's generation
resolution is the enlarged frame, so the control field carries its own `tiled` and `tile_size`.
"""
@@ -90,9 +89,7 @@ class ZImageImageToLatentsInvocation(BaseInvocation, WithMetadata, WithBoard):
# state is scoped and restored rather than switched off by hand and left behind.
with torch.inference_mode(), scoped_vae_tiling(vae, effective_tile_size):
latent_dist = vae.encode(image_tensor).latent_dist
- latents: torch.Tensor = (latent_dist.mode() if deterministic else latent_dist.sample()).to(
- dtype=vae.dtype
- )
+ latents: torch.Tensor = latent_dist.mode().to(dtype=vae.dtype)
# Apply scaling_factor and shift_factor from VAE config.
# Z-Image uses: latents = (latents - shift_factor) * scaling_factor
diff --git a/invokeai/app/invocations/z_image/z_image_denoise.py b/invokeai/app/invocations/z_image/z_image_denoise.py
index 453112c1af..20c8a92f18 100644
--- a/invokeai/app/invocations/z_image/z_image_denoise.py
+++ b/invokeai/app/invocations/z_image/z_image_denoise.py
@@ -781,7 +781,7 @@ class ZImageDenoiseInvocation(BaseInvocation, WithMetadata):
def encode(pixels: torch.Tensor) -> torch.Tensor:
return ZImageImageToLatentsInvocation.vae_encode(
- vae_info=vae_info, image_tensor=pixels, tiled=tiled, tile_size=field.tile_size, deterministic=True
+ vae_info=vae_info, image_tensor=pixels, tiled=tiled, tile_size=field.tile_size
)
image = context.images.get_pil(field.image_name).convert("RGB")
diff --git a/invokeai/backend/wan/extensions/wan_ref_image_extension.py b/invokeai/backend/wan/extensions/wan_ref_image_extension.py
index 867325b6f1..af44c973b6 100644
--- a/invokeai/backend/wan/extensions/wan_ref_image_extension.py
+++ b/invokeai/backend/wan/extensions/wan_ref_image_extension.py
@@ -66,7 +66,7 @@ def encode_reference_image_to_ti2v_condition(
with torch.inference_mode():
encoded = vae.encode(pixel, return_dict=False)[0]
- latents = encoded.sample() # [1, 48, 1, H_lat, W_lat]
+ latents = encoded.mode() # [1, 48, 1, H_lat, W_lat]
latents_mean = torch.tensor(vae.config.latents_mean).view(1, -1, 1, 1, 1).to(latents.device, latents.dtype)
latents_std = torch.tensor(vae.config.latents_std).view(1, -1, 1, 1, 1).to(latents.device, latents.dtype)
@@ -98,7 +98,7 @@ def encode_reference_image_to_condition(
with torch.inference_mode():
encoded = vae.encode(pixel, return_dict=False)[0]
- latents = encoded.sample() # [1, 16, 1, H_lat, W_lat]
+ latents = encoded.mode() # [1, 16, 1, H_lat, W_lat]
# Normalise against the VAE's per-channel mean/std, matching diffusers'
# ``WanImageToVideoPipeline.prepare_latents`` (lines 440-459). Note the
@@ -189,7 +189,7 @@ def encode_reference_image_to_video_condition(
with torch.inference_mode():
encoded = vae.encode(video_condition, return_dict=False)[0]
- latents = encoded.sample() # [1, 16, T_lat, H_lat, W_lat]
+ latents = encoded.mode() # [1, 16, T_lat, H_lat, W_lat]
latents_mean = torch.tensor(vae.config.latents_mean).view(1, -1, 1, 1, 1).to(latents.device, latents.dtype)
latents_std = torch.tensor(vae.config.latents_std).view(1, -1, 1, 1, 1).to(latents.device, latents.dtype)
diff --git a/tests/app/invocations/test_anima_vae.py b/tests/app/invocations/test_anima_vae.py
index 76c946b764..cff2ee858b 100644
--- a/tests/app/invocations/test_anima_vae.py
+++ b/tests/app/invocations/test_anima_vae.py
@@ -185,7 +185,7 @@ class TestAnimaAcceptsBothWan21VaeLayouts:
vae.config.latents_mean = [1.0] * 16
vae.config.latents_std = [2.0] * 16
posterior = MagicMock()
- posterior.sample.return_value = torch.full((1, 16, 1, 4, 4), 3.0)
+ posterior.mode.return_value = torch.full((1, 16, 1, 4, 4), 3.0)
vae.encode.return_value = (posterior,)
with patch.object(TorchDevice, "choose_torch_device", return_value=torch.device("cpu")):
@@ -388,7 +388,7 @@ class TestAnimaImageToLatentsEncode:
def test_encode_disables_tiling_and_requests_working_memory(self):
vae = _mock_vae(dtype=torch.float32)
mock_dist = MagicMock()
- mock_dist.sample.return_value = torch.zeros(1, 16, 1, 4, 4)
+ mock_dist.mode.return_value = torch.zeros(1, 16, 1, 4, 4)
vae.encode.return_value = (mock_dist,)
vae_info = _mock_vae_info(vae)
diff --git a/tests/app/invocations/test_vae_encode_deterministic.py b/tests/app/invocations/test_vae_encode_deterministic.py
new file mode 100644
index 0000000000..7e00ca85bf
--- /dev/null
+++ b/tests/app/invocations/test_vae_encode_deterministic.py
@@ -0,0 +1,136 @@
+"""The image-to-latents encoders take the mean of the VAE's posterior, so an image encodes to one latent.
+
+A sample of the posterior adds noise of its own that no seed controls, so img2img and inpaint from the same image,
+seed and settings would not repeat. Each cell runs the real encode twice against a small, randomly initialised VAE of
+the real class and expects the same bits.
+"""
+
+from unittest.mock import MagicMock, patch
+
+import pytest
+import torch
+from diffusers.models.autoencoders import AutoencoderKLWan
+from PIL import Image
+
+from invokeai.app.invocations.vae.anima_image_to_latents import AnimaImageToLatentsInvocation
+from invokeai.app.invocations.vae.cogview4_image_to_latents import CogView4ImageToLatentsInvocation
+from invokeai.app.invocations.vae.image_to_latents import ImageToLatentsInvocation
+from invokeai.app.invocations.vae.sd3_image_to_latents import SD3ImageToLatentsInvocation
+from invokeai.app.invocations.vae.wan_image_to_latents import WanImageToLatentsInvocation
+from invokeai.app.invocations.vae.z_image_image_to_latents import ZImageImageToLatentsInvocation
+from invokeai.backend.util.devices import TorchDevice
+from invokeai.backend.wan.extensions.wan_ref_image_extension import (
+ encode_reference_image_to_condition,
+ encode_reference_image_to_ti2v_condition,
+ encode_reference_image_to_video_condition,
+)
+
+
+def _wan_vae() -> AutoencoderKLWan:
+ """A real Wan VAE with the A14B geometry (8x spatial, 4x temporal, 16 channels) and next to no weight."""
+ return AutoencoderKLWan(
+ base_dim=4,
+ z_dim=16,
+ dim_mult=[1, 2, 2, 2],
+ num_res_blocks=1,
+ attn_scales=[],
+ temperal_downsample=[False, True, True],
+ latents_mean=[0.0] * 16,
+ latents_std=[1.0] * 16,
+ )
+
+
+def _vae_info(vae: torch.nn.Module) -> MagicMock:
+ 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
+ return vae_info
+
+
+def _pixels(frames: int | None = None) -> torch.Tensor:
+ generator = torch.Generator().manual_seed(0)
+ shape = (1, 3, 64, 64) if frames is None else (1, 3, frames, 64, 64)
+ return torch.rand(shape, generator=generator) * 2 - 1
+
+
+def _image() -> Image.Image:
+ return Image.fromarray((_pixels()[0].permute(1, 2, 0).numpy() * 127.5 + 127.5).astype("uint8"))
+
+
+# Each builder takes the `flux_shaped_vae` factory and returns a callable that encodes the same image once.
+def _kl_encode(node_encode, estimator: str | None = None):
+ """`estimator` names a working-memory estimator with no fp32 line, which the CPU VAE here computes in."""
+
+ def build(flux_shaped_vae):
+ vae = flux_shaped_vae()
+
+ def encode():
+ if estimator is None:
+ return node_encode(_vae_info(vae), _pixels())
+ with patch(estimator, return_value=0):
+ return node_encode(_vae_info(vae), _pixels())
+
+ return encode
+
+ return build
+
+
+def _sd_encode(flux_shaped_vae):
+ vae = flux_shaped_vae()
+ return lambda: ImageToLatentsInvocation._encode_to_tensor(vae, _pixels())
+
+
+def _anima_encode(_):
+ vae_info = _vae_info(_wan_vae())
+ return lambda: AnimaImageToLatentsInvocation.vae_encode(vae_info, _pixels())
+
+
+def _wan_encode(_):
+ vae_info = _vae_info(_wan_vae())
+ return lambda: WanImageToLatentsInvocation.vae_encode(vae_info, _pixels())
+
+
+def _wan_ref(encode):
+ def build(_):
+ vae = _wan_vae()
+ return lambda: encode(vae)
+
+ return build
+
+
+_CPU = {"device": torch.device("cpu"), "dtype": torch.float32}
+
+ENCODERS = {
+ "sd1-sdxl": _sd_encode,
+ "sd3": _kl_encode(
+ SD3ImageToLatentsInvocation.vae_encode,
+ "invokeai.app.invocations.vae.sd3_image_to_latents.estimate_vae_working_memory_sd3",
+ ),
+ "cogview4": _kl_encode(
+ CogView4ImageToLatentsInvocation.vae_encode,
+ "invokeai.app.invocations.vae.cogview4_image_to_latents.estimate_vae_working_memory_cogview4",
+ ),
+ "z-image": _kl_encode(ZImageImageToLatentsInvocation.vae_encode),
+ "anima": _anima_encode,
+ "wan": _wan_encode,
+ "wan-ref-i2v": _wan_ref(lambda vae: encode_reference_image_to_condition(_image(), vae, 64, 64, **_CPU)),
+ "wan-ref-video": _wan_ref(
+ lambda vae: encode_reference_image_to_video_condition(_image(), vae, 64, 64, num_frames=5, **_CPU)
+ ),
+ "wan-ref-ti2v": _wan_ref(lambda vae: encode_reference_image_to_ti2v_condition(_image(), vae, 64, 64, **_CPU)),
+}
+
+
[email protected]("family", ENCODERS)
+def test_encoding_the_same_image_twice_gives_identical_latents(family, flux_shaped_vae):
+ encode_once = ENCODERS[family](flux_shaped_vae)
+
+ with patch.object(TorchDevice, "choose_torch_device", return_value=torch.device("cpu")):
+ first, second = encode_once(), encode_once()
+
+ assert first.numel() > 0
+ assert torch.equal(first, second)
diff --git a/tests/app/invocations/test_z_image_denoise_working_memory.py b/tests/app/invocations/test_z_image_denoise_working_memory.py
index a86fcd59b4..a7363cb2be 100644
--- a/tests/app/invocations/test_z_image_denoise_working_memory.py
+++ b/tests/app/invocations/test_z_image_denoise_working_memory.py
@@ -649,7 +649,6 @@ class TestNodeReservation:
run = self._run(control_blocks=15)
assert run.order == ["encode", "transformer lock"]
- assert run.control_encode["deterministic"] is True
def test_the_control_fields_tiling_reaches_the_control_encode(self):
"""The control image is encoded at generation size. For an upscale that is the enlarged frame, whose untiled
diff --git a/tests/backend/wan/test_wan_ref_image_extension.py b/tests/backend/wan/test_wan_ref_image_extension.py
index fda879bb0d..46d52325ab 100644
--- a/tests/backend/wan/test_wan_ref_image_extension.py
+++ b/tests/backend/wan/test_wan_ref_image_extension.py
@@ -16,7 +16,7 @@ from invokeai.backend.wan.extensions.wan_ref_image_extension import (
def _make_fake_vae(z_dim: int = 16, spatial_scale: int = 8, temporal_scale: int = 4) -> MagicMock:
"""Stand-in for ``AutoencoderKLWan`` that returns deterministic latents.
- ``encode(pixel)`` returns a fake distribution whose ``sample()`` yields
+ ``encode(pixel)`` returns a fake distribution whose ``mode()`` yields
a tensor sized exactly as the real Wan VAE would: ``[B, z_dim, T_lat, H/8, W/8]``.
"""
vae = MagicMock()
@@ -38,7 +38,7 @@ def _make_fake_vae(z_dim: int = 16, spatial_scale: int = 8, temporal_scale: int
latents = torch.zeros(b, z_dim, t_lat, h_lat, w_lat, dtype=pixel.dtype)
dist = MagicMock()
- dist.sample = MagicMock(return_value=latents)
+ dist.mode = MagicMock(return_value=latents)
# The pipeline does ``vae.encode(...)[0]`` for non-dict returns.
return (dist,) if return_dict is False else MagicMock(latent_dist=dist)