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.

12.9 KB
Raw Blame
"""Wan 2.2 latents-to-video invocation.

Decodes multi-frame Wan latents with the Wan VAE and encodes the result to an
MP4 file via :mod:`imageio` (backed by the bundled FFmpeg binary from
``imageio-ffmpeg``). The video is then persisted through ``context.videos.save``,
which moves the temp file into ``outputs/videos/`` and records the DTO.

Latent shape on input is 5D ``[B, C, T_lat, H_lat, W_lat]`` (typically B=1).
The VAE expands the temporal dim by 4× during decode minus the initial offset:
``T_pixel = (T_lat - 1) * 4 + 1`` (e.g. T_lat=21 → 81 pixel frames).
"""

import tempfile
from collections.abc import Iterable, Iterator
from pathlib import Path
from typing import Callable, Protocol

import numpy as np
import torch
from diffusers.models.autoencoders import AutoencoderKLWan

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 VideoOutput
from invokeai.app.services.session_processor.session_processor_common import CanceledException
from invokeai.app.services.shared.invocation_context import InvocationContext
from invokeai.app.util.video_encoding import make_mp4_writer
from invokeai.backend.model_manager.load.model_cache.utils import get_effective_device
from invokeai.backend.util.devices import TorchDevice
from invokeai.backend.util.qwen_image_vae import (
    patch_qwen_image_vae_tiling,
    resolve_qwen_image_vae_tile_size,
)
from invokeai.backend.util.vae_working_memory import (
    estimate_vae_working_memory_wan,
    should_pretile_vae_decode,
)
from invokeai.backend.wan.vae_decode import iter_wan_vae_decode_chunks


class _FrameWriter(Protocol):
    def append_data(self, frame: np.ndarray) -> None: ...


def _validate_video_latent_batch(latents: torch.Tensor) -> None:
    if latents.ndim in (4, 5) and latents.shape[0] != 1:
        raise ValueError(f"Wan latents-to-video requires batch size 1; got {latents.shape[0]}.")


def _iter_decoded_frames(decoded: torch.Tensor) -> Iterator[np.ndarray]:
    for index in range(decoded.shape[1]):
        frame = decoded[:, index]
        frame = frame.clamp(-1, 1).permute(1, 2, 0).cpu().float()
        yield (127.5 * (frame + 1.0)).round().clamp(0, 255).byte().numpy()


def _write_video_frames(writer: _FrameWriter, frames: Iterable[np.ndarray], is_canceled: Callable[[], bool]) -> None:
    frames_iter = iter(frames)
    while True:
        if is_canceled():
            raise CanceledException
        try:
            frame = next(frames_iter)
        except StopIteration:
            return
        writer.append_data(np.ascontiguousarray(frame))


@invocation(
    "wan_l2v",
    title="Latents to Video - Wan 2.2",
    tags=["latents", "video", "vae", "l2v", "wan"],
    category="latents",
    version="1.0.0",
    classification=Classification.Prototype,
)
class WanLatentsToVideoInvocation(BaseInvocation, WithMetadata, WithBoard):
    """Decode 5D Wan latents to RGB frames and encode an MP4."""

    latents: LatentsField = InputField(description=FieldDescriptions.latents, input=Input.Connection)
    vae: VAEField = InputField(description=FieldDescriptions.vae, input=Input.Connection)
    fps: int = InputField(
        default=16,
        ge=1,
        le=120,
        description="Frames-per-second for the encoded MP4. Wan 2.2 was trained at 16 FPS.",
    )

    @torch.no_grad()
    def invoke(self, context: InvocationContext) -> VideoOutput:
        latents = context.tensors.load(self.latents.latents_name)
        _validate_video_latent_batch(latents)
        if latents.ndim == 4:
            # Promote 4D (single-frame) to 5D so this node can also serve as a
            # one-frame "video" encode if someone wires it that way.
            latents = latents.unsqueeze(2)
        if latents.ndim != 5:
            raise ValueError(
                f"Wan latents-to-video expects a 5D latent tensor [B, C, T, H, W]; got {tuple(latents.shape)}."
            )
        if any(size == 0 for size in latents.shape[2:]):
            raise ValueError("Wan latents-to-video requires non-empty temporal and spatial dimensions.")

        vae_info = context.models.load(self.vae.vae)
        if not isinstance(vae_info.model, AutoencoderKLWan):
            raise TypeError(f"Expected AutoencoderKLWan for Wan VAE, got {type(vae_info.model).__name__}.")

        if latents.shape[1] != vae_info.model.config.z_dim:
            raise ValueError(
                f"Latent channel mismatch: these latents have {latents.shape[1]} channels but the "
                f"selected VAE expects {vae_info.model.config.z_dim}. A14B models need the 16-channel Wan 2.1 VAE; "
                "TI2V-5B needs the 48-channel Wan 2.2 VAE."
            )

        _, _, t_lat, h_lat, w_lat = latents.shape
        spatial_scale = getattr(vae_info.model.config, "scale_factor_spatial", None) or 8
        temporal_scale = getattr(vae_info.model.config, "scale_factor_temporal", None) or 4
        t_pixel = (t_lat - 1) * temporal_scale + 1
        h_pixel, w_pixel = h_lat * spatial_scale, w_lat * spatial_scale
        optimize_memory = context.config.get().wan_memory_optimization

        estimated_working_memory = estimate_vae_working_memory_wan(
            operation="decode",
            vae=vae_info.model,
            pixel_height=h_pixel,
            pixel_width=w_pixel,
            pixel_frames=t_pixel,
            streaming=optimize_memory,
        )
        # Long/high-res clips can need a working set no card fits. When the full-frame
        # estimate would claim most of what the VAE's device keeps resident, fall back to spatial
        # tiling and budget for the tiled working set instead. (A cpu_only VAE runs in system RAM,
        # where the working set is not the constraint; the helper never tiles off-GPU.)
        use_tiling = context.config.get().auto_tiled_decode and should_pretile_vae_decode(
            vae_info.compute_device, estimated_working_memory
        )
        tile_size: int | None = None
        if use_tiling:
            # Resolved against the module constant, not read off `vae_info.model`: that is the
            # cache's shared instance, so its current geometry is whatever the last invocation
            # left rather than what this decode is about to ask for. The sentinel resolves to
            # 256/192, which is also this VAE class's own default.
            tile_size = resolve_qwen_image_vae_tile_size(0)
            tiled_working_memory = estimate_vae_working_memory_wan(
                operation="decode",
                vae=vae_info.model,
                pixel_height=h_pixel,
                pixel_width=w_pixel,
                pixel_frames=t_pixel,
                tile_size=tile_size,
                streaming=False,
            )
            # Tiling holds six copies of the clip, so a long enough clip (480p from ~440 frames, against
            # streaming) needs more tiled than untiled. Neither fits then, and the lighter decode is the better bet.
            if tiled_working_memory < estimated_working_memory:
                estimated_working_memory = tiled_working_memory
            else:
                context.logger.info(
                    f"Not tiling the Wan VAE decode: tiled it would need ~{tiled_working_memory / 2**30:.1f} GiB, "
                    f"more than the ~{estimated_working_memory / 2**30:.1f} GiB untiled, which is already more than "
                    "the GPU keeps resident."
                )
                use_tiling = False
                tile_size = None

        tmp = tempfile.NamedTemporaryFile(prefix="invokeai_wan_video_", suffix=".mp4", delete=False)
        tmp.close()
        tmp_path = Path(tmp.name)
        try:
            stream_decode = optimize_memory and not use_tiling
            decoded: torch.Tensor | None = None
            num_frames = 0

            # Keep the VAE cache lock while the MP4 writer consumes chunks. The causal decoder's
            # feature cache and weights must remain live for the whole sequence; releasing the
            # lock would require a separate bounded decode/encode queue and would add buffering.
            with vae_info.model_on_device(working_mem_bytes=estimated_working_memory) as (_, vae):
                assert isinstance(vae, AutoencoderKLWan)
                context.logger.info(
                    f"Running Wan VAE decode: {t_lat} latent frames -> {t_pixel} pixel frames at {w_pixel}x{h_pixel}"
                    + (" (tiled)" if use_tiling else " (streaming to MP4)" if stream_decode else "")
                )
                context.util.signal_progress("Running Wan VAE decode (video)")

                vae_dtype = next(iter(vae.parameters())).dtype
                latents = latents.to(device=get_effective_device(vae), dtype=vae_dtype)
                TorchDevice.empty_cache()

                # `AutoencoderKLWan` is the cache's instance, shared with Anima and with the
                # image decode. A bare `enable_tiling()` inherits whatever min/stride pair the
                # module happens to carry, and an inconsistent pair drops whole bands of the frame;
                # `disable_tiling()` clears the flag without restoring the geometry. The scope sets
                # all four explicitly and puts back what was there.
                with patch_qwen_image_vae_tiling(vae, tile_size):
                    with torch.inference_mode():
                        # Denormalise from denoiser space back to VAE space.
                        latents_mean = torch.tensor(vae.config.latents_mean).view(1, -1, 1, 1, 1).to(latents)
                        latents_std = torch.tensor(vae.config.latents_std).view(1, -1, 1, 1, 1).to(latents)
                        latents = latents * latents_std + latents_mean

                        if stream_decode:
                            duration = t_pixel / float(self.fps)
                            context.logger.info(
                                f"Encoding MP4: {t_pixel} frames @ {self.fps} fps "
                                f"({duration:.2f}s) at {w_pixel}x{h_pixel} via libx264"
                            )
                            context.util.signal_progress(f"Encoding MP4 ({t_pixel} frames @ {self.fps} fps)")
                            writer = make_mp4_writer(tmp_path, self.fps)
                            try:
                                for chunk in iter_wan_vae_decode_chunks(vae, latents):
                                    chunk = chunk[0].cpu()
                                    num_frames += chunk.shape[1]
                                    _write_video_frames(writer, _iter_decoded_frames(chunk), context.util.is_canceled)
                            finally:
                                writer.close()
                        else:
                            # [C=3, T_pixel, H, W] in [-1, 1] (roughly), on CPU.
                            decoded = vae.decode(latents, return_dict=False)[0][0].cpu()
                            num_frames = decoded.shape[1]
                        del latents, latents_mean, latents_std

            TorchDevice.empty_cache()

            if context.util.is_canceled():
                raise CanceledException
            if num_frames == 0:
                raise ValueError("Wan VAE decode produced zero frames.")
            if num_frames != t_pixel:
                raise ValueError(f"Wan VAE decode produced {num_frames} frames; expected {t_pixel}.")

            height, width = h_pixel, w_pixel
            duration = num_frames / float(self.fps)
            if decoded is not None:
                context.logger.info(
                    f"Encoding MP4: {num_frames} frames @ {self.fps} fps "
                    f"({duration:.2f}s) at {width}x{height} via libx264"
                )
                context.util.signal_progress(f"Encoding MP4 ({num_frames} frames @ {self.fps} fps)")
                writer = make_mp4_writer(tmp_path, self.fps)
                try:
                    _write_video_frames(writer, _iter_decoded_frames(decoded), context.util.is_canceled)
                finally:
                    writer.close()
                del decoded
                TorchDevice.empty_cache()

            encoded_bytes = tmp_path.stat().st_size
            context.logger.info(f"MP4 encode complete: {encoded_bytes / 1024:.1f} KB")
            video_dto = context.videos.save(
                source_path=tmp_path,
                width=width,
                height=height,
                duration=duration,
                fps=float(self.fps),
            )
            context.logger.info(f"Saved video: {video_dto.video_name}")
            return VideoOutput.build(video_dto)
        finally:
            # If save() moved the file this is a no-op; if it failed earlier, we
            # don't want a lingering temp file.
            try:
                tmp_path.unlink(missing_ok=True)
            except Exception:
                pass