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.

perf(minimax_h3): fp16-autocast the video VAE encode on CUDA-type devices

Lincoln Steinf15a6323e4c5
diff --git a/invokeai/backend/minimax_h3/keyframe_conditioning.py b/invokeai/backend/minimax_h3/keyframe_conditioning.py
index 9618cea38b..763aba4be4 100644
--- a/invokeai/backend/minimax_h3/keyframe_conditioning.py
+++ b/invokeai/backend/minimax_h3/keyframe_conditioning.py
@@ -12,6 +12,8 @@ The rows returned here are CLEAN (not yet noise-augmented): the denoise state no
reproducibility order in one place (see :mod:`invokeai.backend.minimax_h3.sampling`).
"""
+import contextlib
+
import numpy as np
import torch
from diffusers.models.autoencoders.vae import DiagonalGaussianDistribution
@@ -53,6 +55,26 @@ def prepare_keyframes(
return keyframes, tuple(anchors)
+def vae_encode_autocast(device: torch.device) -> contextlib.AbstractContextManager[None]:
+ """The precision context every H3 video-VAE *encode* runs under.
+
+ The encoder is a 180M-parameter 3D-conv ResNet whose weights are pinned float32. On CUDA-type
+ devices (NVIDIA and ROCm both report ``"cuda"``) the convolutions run under float16 autocast
+ over those float32 weights — the same recipe the decode path uses. Measured on a 5060 Ti for one
+ 17-frame 768x448 chunk: 4.6 s -> 3.2 s with TF32 convs, 9.2 s -> 3.2 s without (ROCm has no
+ TF32 path), and ~0.5 GiB less peak VRAM. ``cache_enabled=False`` keeps autocast from pinning
+ float16 copies of the whole encoder for the duration of a long reference encode.
+
+ Numerics: the autocast encode drifts ~1.5e-3 RMS (relative) from the float32 one. Visual
+ conditioning rows are noise-augmented to ``t = 0.999`` before the transformer sees them, so
+ the clean encode contributes 0.1% of each row and the drift lands at ~1e-6 of the row
+ magnitude. MPS/CPU encode in the weights' dtype.
+ """
+ if device.type == "cuda":
+ return torch.autocast(device_type="cuda", dtype=torch.float16, cache_enabled=False)
+ return contextlib.nullcontext()
+
+
@torch.no_grad()
def encode_keyframes(
vae: AutoencoderKLMiniMaxH3,
@@ -70,7 +92,9 @@ def encode_keyframes(
pixels = torch.from_numpy(np.array(image)).to(device).permute(2, 0, 1)[None, :, None]
pixels = (pixels.to(torch.float32).div(255.0) - pixel_mean) / pixel_std
# A keyframe is one frame: the (tiled) spatial encoder alone, no 17-frame temporal chunking.
- moments = vae._encode_clip(pixels)
+ with vae_encode_autocast(device):
+ moments = vae._encode_clip(pixels)
+ moments = moments.float()
posterior = DiagonalGaussianDistribution(moments)
latents = posterior.sample(generator=torch.Generator().manual_seed(MINIMAX_H3_KEYFRAME_ENCODE_SEED))
# The fp16 rounding before normalization is a checkpoint contract (~11 bits of every
diff --git a/invokeai/backend/minimax_h3/reference_conditioning.py b/invokeai/backend/minimax_h3/reference_conditioning.py
index fd91742571..806d8dcaee 100644
--- a/invokeai/backend/minimax_h3/reference_conditioning.py
+++ b/invokeai/backend/minimax_h3/reference_conditioning.py
@@ -32,6 +32,7 @@ from PIL import Image, ImageOps
from invokeai.backend.minimax_h3.audio_resample import resample_sinc
from invokeai.backend.minimax_h3.autoencoder_kl_minimax_h3 import AutoencoderKLMiniMaxH3
from invokeai.backend.minimax_h3.autoencoder_kl_minimax_h3_audio import AutoencoderKLMiniMaxH3Audio
+from invokeai.backend.minimax_h3.keyframe_conditioning import vae_encode_autocast
from invokeai.backend.minimax_h3.packing import (
MINIMAX_H3_CANVAS_MULTIPLE,
MINIMAX_H3_FPS,
@@ -260,8 +261,9 @@ def encode_reference_image(
like a keyframe.
"""
pixels = torch.from_numpy(np.array(image)).to(device).permute(2, 0, 1)[None, :, None]
- moments = vae._encode_clip(_normalize_pixels(pixels, device))
- return _encode_condition_moments(vae, moments)
+ with vae_encode_autocast(device):
+ moments = vae._encode_clip(_normalize_pixels(pixels, device))
+ return _encode_condition_moments(vae, moments.float())
@torch.no_grad()
@@ -273,8 +275,9 @@ def encode_reference_video(
Returns ``(rows, (num_latent_frames, latent_height, latent_width))``. The frame count is
snapped DOWN to ``17 * n + 5`` first, then the stack goes through the VAE's temporal
chunking. The pixels move to the device one 17-frame chunk at a time — each chunk encodes
- independently, so the result is bit-identical to ``vae._encode`` over the whole stack
- while never materializing the full float32 pixel tensor on the device.
+ independently, so the result is bit-identical to ``vae._encode`` over the whole stack under
+ the same :func:`vae_encode_autocast` precision, while never materializing the full float32
+ pixel tensor on the device.
"""
frames = frames[: snap_reference_num_frames(frames.shape[0])]
@@ -291,7 +294,9 @@ def encode_reference_video(
# the whole stack to a multiple of `clip_length`.
pad = pixels[:, :, -1:].repeat(1, 1, clip_length - pixels.shape[2], 1, 1)
pixels = torch.cat([pixels, pad], dim=2)
- chunk_moments.append(vae._encode_clip(_normalize_pixels(pixels, device)).cpu())
+ with vae_encode_autocast(device):
+ moments = vae._encode_clip(_normalize_pixels(pixels, device))
+ chunk_moments.append(moments.float().cpu())
moments = torch.cat(chunk_moments, dim=2)
if vae.config.token_drop > 0:
diff --git a/tests/backend/minimax_h3/test_reference_conditioning.py b/tests/backend/minimax_h3/test_reference_conditioning.py
index 0982f5c227..d9cbe4b8de 100644
--- a/tests/backend/minimax_h3/test_reference_conditioning.py
+++ b/tests/backend/minimax_h3/test_reference_conditioning.py
@@ -7,12 +7,15 @@ order, torchaudio-parity resampling (against baked torchaudio 2.11 vectors), the
conditioner sampling, and the per-modality label presentation. No models are loaded.
"""
+import warnings
+
import numpy as np
import pytest
import torch
from PIL import Image
from invokeai.backend.minimax_h3.audio_resample import resample_sinc
+from invokeai.backend.minimax_h3.keyframe_conditioning import vae_encode_autocast
from invokeai.backend.minimax_h3.reference_conditioning import (
normalize_reference_audio,
normalize_reference_image,
@@ -320,3 +323,19 @@ class TestPresentation:
video_block_timestamps=[[0.25]],
)
assert tokenizer.texts == ["<Video 1>: ", "<0.2 seconds>", "P"]
+
+
+def test_vae_encode_autocast_is_fp16_on_cuda_devices_and_a_no_op_elsewhere() -> None:
+ with warnings.catch_warnings():
+ # CPU-only torch builds warn "CUDA is not available. Disabling" on construction (and set
+ # enabled=False) - the recipe's attributes are still recorded, which is what is under test.
+ warnings.simplefilter("ignore")
+ cuda = vae_encode_autocast(torch.device("cuda"))
+ assert isinstance(cuda, torch.autocast)
+ assert cuda.fast_dtype == torch.float16
+ assert cuda.device == "cuda"
+ # The weight-cast cache would pin float16 copies of the whole encoder for a long encode.
+ assert cuda._cache_enabled is False
+ for device in (torch.device("cpu"), torch.device("mps"), torch.device("meta")):
+ with vae_encode_autocast(device):
+ assert not torch.is_autocast_enabled("cpu")