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.

7.7 KB
Raw Blame
import torch
from einops import rearrange
from PIL import Image

from invokeai.app.invocations.baseinvocation import BaseInvocation, Classification, invocation
from invokeai.app.invocations.fields import (
    FieldDescriptions,
    Input,
    InputField,
    LatentsField,
    WithBoard,
    WithMetadata,
)
from invokeai.app.invocations.model import VAEField
from invokeai.app.invocations.primitives import ImageOutput
from invokeai.app.services.shared.invocation_context import InvocationContext
from invokeai.backend.stable_diffusion.extensions.seamless import SeamlessExt
from invokeai.backend.util.devices import TorchDevice
from invokeai.backend.util.qwen_image_vae import (
    QWEN_IMAGE_VAE_MIN_TILE_SIZE,
    as_qwen_image_vae,
    patch_qwen_image_vae_tiling,
    resolve_qwen_image_vae_tile_size,
)
from invokeai.backend.util.vae_working_memory import (
    estimate_vae_working_memory_qwen_image,
    qwen_image_untiled_decode_peak_bytes,
    should_pretile_vae_decode,
)


@invocation(
    "qwen_image_l2i",
    title="Latents to Image - Qwen Image",
    tags=["latents", "image", "vae", "l2i", "qwen_image"],
    category="latents",
    version="1.1.0",
    classification=Classification.Prototype,
)
class QwenImageLatentsToImageInvocation(BaseInvocation, WithMetadata, WithBoard):
    """Generates an image from latents using the Qwen Image VAE."""

    latents: LatentsField = InputField(description=FieldDescriptions.latents, input=Input.Connection)
    vae: VAEField = InputField(description=FieldDescriptions.vae, input=Input.Connection)
    tiled: bool = InputField(default=False, description=FieldDescriptions.tiled)
    # NOTE: tile_size = 0 is a special value meaning "use the model's default", matching the
    # SD/SDXL l2i node. `int | None` is avoided because the workflow UI does not handle it well.
    tile_size: int = InputField(
        default=0,
        multiple_of=8,
        description=f"{FieldDescriptions.vae_tile_size} Values between 1 and "
        f"{QWEN_IMAGE_VAE_MIN_TILE_SIZE} are raised to {QWEN_IMAGE_VAE_MIN_TILE_SIZE}.",
    )

    @torch.no_grad()
    def invoke(self, context: InvocationContext) -> ImageOutput:
        latents = context.tensors.load(self.latents.latents_name)

        vae_info = context.models.load(self.vae.vae)
        config = context.config.get()
        tiled = self.tiled or config.force_tiled_decode
        # Resolve tile_size=0 ("model default") before estimating, so the memory the cache reserves
        # matches the tiles the VAE will actually use. Without this the estimate stays at the
        # full-frame figure (~21 GB at 2560x1440 on CUDA) and tiling frees nothing: the VAE is
        # bounded, but the cache still evicts other models to honour the reservation.
        # Resolved against a constant rather than the module's current tile_sample_min_height, which a
        # previous invocation (including the Anima decode node, which shares this VAE instance) may
        # have overwritten.
        effective_tile_size = resolve_qwen_image_vae_tile_size(self.tile_size) if tiled else None
        # NOTE: vae_info.model may be an AutoencoderKLWan (a native-layout qwen_image_vae single file is
        # classified with the Anima base); it is reinterpreted as AutoencoderKLQwenImage inside the
        # model_on_device context below. The working-memory estimate only reads tensor shape + element
        # size, so it is safe to run on either class here.
        estimated_working_memory = estimate_vae_working_memory_qwen_image(
            operation="decode",
            image_tensor=latents,
            vae=vae_info.model,
            tile_size=effective_tile_size,
            device=vae_info.compute_device,
        )
        # The tiling decision is priced from the measured peak, not from the reservation above: that one carries the
        # headroom and cross-card conservatism a reservation needs, and tiling is not pixel-identical.
        if (
            not tiled
            and config.auto_tiled_decode
            and should_pretile_vae_decode(
                vae_info.compute_device,
                qwen_image_untiled_decode_peak_bytes(latents, vae_info.model, vae_info.compute_device),
            )
        ):
            tiled = True
            effective_tile_size = resolve_qwen_image_vae_tile_size(self.tile_size)
            estimated_working_memory = estimate_vae_working_memory_qwen_image(
                operation="decode",
                image_tensor=latents,
                vae=vae_info.model,
                tile_size=effective_tile_size,
                device=vae_info.compute_device,
            )
        with vae_info.model_on_device(working_mem_bytes=estimated_working_memory) as (_, vae):
            context.util.signal_progress("Running VAE")
            # A native-layout qwen_image_vae single file is classified with the Anima base and loaded
            # as AutoencoderKLWan; reinterpret it as AutoencoderKLQwenImage (identical weights). This is
            # cache-preserving (returns the same module), keeping partial-loading hooks intact.
            vae = as_qwen_image_vae(vae)
            with SeamlessExt.static_patch_model(vae, self.vae.seamless_axes):
                # Use the VAE's intended compute device (CUDA/MPS, or CPU if configured cpu_only). Do NOT infer it
                # from current param residency: partial loading may have temporarily offloaded all weights to RAM,
                # which would wrongly place the latents (and thus the whole decode) on the CPU (see #9373).
                # Keep the per-channel denormalization in fp32; cast only the decoded VAE input to the
                # VAE's configured compute dtype.
                latents = latents.to(device=vae_info.compute_device, dtype=torch.float32)

                # Tiling bounds the VAE's per-tile memory, which is the scalable way to decode very
                # large outputs that would exceed VRAM even after offloading the transformer/text
                # encoder. For normal sizes, leave it off (faster, no tile blending) — the reserved
                # working memory offloads other models so the full-frame decode fits.
                # The tiling state is scoped to this block: the VAE module belongs to the model cache
                # and is shared with later invocations (and with the Anima decode node).
                tiling_context = patch_qwen_image_vae_tiling(vae, effective_tile_size)

                TorchDevice.empty_cache()

                with torch.inference_mode(), tiling_context:
                    # The Qwen Image VAE uses per-channel latents_mean / latents_std
                    # instead of a single scaling_factor.
                    # Latents are 5D: (B, C, num_frames, H, W) — the unpack from the
                    # denoise step already produces this shape.
                    latents_mean = torch.tensor(
                        vae.config.latents_mean, device=latents.device, dtype=torch.float32
                    ).view(1, vae.config.z_dim, 1, 1, 1)
                    latents_std = torch.tensor(vae.config.latents_std, device=latents.device, dtype=torch.float32).view(
                        1, vae.config.z_dim, 1, 1, 1
                    )
                    latents = (latents * latents_std + latents_mean).to(dtype=vae.dtype)

                    img = vae.decode(latents, return_dict=False)[0]
                    # Drop the temporal frame dimension: (B, C, 1, H, W) -> (B, C, H, W)
                    img = img[:, :, 0]

                img = img.clamp(-1, 1)
                img = rearrange(img[0], "c h w -> h w c")
                img_pil = Image.fromarray((127.5 * (img + 1.0)).byte().cpu().numpy())

        TorchDevice.empty_cache()

        image_dto = context.images.save(image=img_pil)

        return ImageOutput.build(image_dto)