Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio video: MiniMax-H3 fused VAE decoder follows the mixed-precision load, and encode overlaps decode (#14986)

Daniel Han7f322412f9ed
diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.py
index 2395f594b8f..a2ead652948 100644
--- a/studio/backend/core/inference/video.py
+++ b/studio/backend/core/inference/video.py
@@ -294,7 +294,12 @@ from .video_minimax_h3_te import (
)
from .video_encode import encode_x264
from .video_nvenc import encode_nvenc, nvenc_gpu
-from .video_stream_encode import claim_stream, offer_stream, open_stream_encode
+from .video_stream_encode import (
+ claim_stream,
+ offer_stream,
+ open_h3_stream_encode,
+ open_stream_encode,
+)
from utils.hardware import clear_gpu_cache
from core.inference.inference_gate import holds_inference, pauses_background_embedding
@@ -12411,6 +12416,11 @@ class VideoBackend:
and not fam.has_audio
and ltx25_render_call is None,
logger = logger,
+ ) or open_h3_stream_encode(
+ pipe,
+ out_fps,
+ engage = fam.modular_workflow and ltx25_render_call is None,
+ logger = logger,
)
previewer = LatentPreviewer.create(
family = fam.name,
@@ -12471,8 +12481,8 @@ class VideoBackend:
audio = getattr(output, "audio", None)
audio_track = audio[0] if fam.has_audio and audio is not None else None
audio_sample_rate = None
- # Encoded during the decode when its frames are exactly these (_encode_mp4 claims it).
- with offer_stream(stream_session if audio_track is None else None):
+ # Encoded during the decode when its frames (and soundtrack) are exactly these (_encode_mp4 claims it).
+ with offer_stream(stream_session):
if audio_sample_rate is None:
mp4_bytes = self._encode_mp4(
video_frames, out_fps, audio_track, pipe if fam.has_audio else None
@@ -13224,6 +13234,11 @@ class VideoBackend:
streamed = claim_stream(video_frames, fps)
if streamed is not None:
return streamed
+ elif pipe is not None and audio_sample_rate:
+ # MiniMax-H3: encoded during the decode with this soundtrack's stream declared up front
+ streamed = claim_stream(video_frames, fps, audio, int(audio_sample_rate))
+ if streamed is not None:
+ return streamed
from diffusers.utils.export_utils import encode_video
tmp = tempfile.NamedTemporaryFile(suffix = ".mp4", delete = False)
diff --git a/studio/backend/core/inference/video_minimax_h3_vae.py b/studio/backend/core/inference/video_minimax_h3_vae.py
index de2e7e0aadd..9e1467f03b8 100644
--- a/studio/backend/core/inference/video_minimax_h3_vae.py
+++ b/studio/backend/core/inference/video_minimax_h3_vae.py
@@ -844,13 +844,25 @@ def _swiglu(x: Any) -> Any:
return out
+def _residual_dtype(hidden_states: Any, blocks: Any) -> Any:
+ """Stock ``h + out * scale`` promotes to float32 ``scale1`` / ``scale2`` under diffusers' mixed load."""
+ import torch
+
+ dtype = hidden_states.dtype
+ for name in ("scale1", "scale2"):
+ scale = getattr(blocks[0], name, None)
+ if isinstance(scale, torch.Tensor):
+ dtype = torch.promote_types(dtype, scale.dtype)
+ return dtype
+
+
def _fast_block_stack(decoder: Any, hidden_states: Any, cos: Any, sin: Any, gemm_dtype: Any) -> Any:
"""The transformer blocks; the kernels store normed activations in ``gemm_dtype``."""
import torch.nn.functional as F
blocks = decoder.transformer_blocks
batch, seq, dim = hidden_states.shape
- h = hidden_states.contiguous()
+ h = hidden_states.to(_residual_dtype(hidden_states, blocks)).contiguous()
normed = _add_rmsnorm(h, None, None, blocks[0].norm1, gemm_dtype)
cos2 = cos.reshape(-1, cos.shape[-1])
sin2 = sin.reshape(-1, sin.shape[-1])
@@ -874,10 +886,18 @@ def _fast_block_stack(decoder: Any, hidden_states: Any, cos: Any, sin: Any, gemm
if i + 1 < len(blocks):
normed = _add_rmsnorm(h, out, block.scale2, blocks[i + 1].norm1, gemm_dtype)
else:
- h.addcmul_(out, block.scale2)
+ # not addcmul: stock rounds the product separately
+ h.add_(out * block.scale2)
return h
+def _weight_dtype(module: Any, default: Any) -> Any:
+ """``default`` for an int8 Linear (weight dropped) or a missing weight."""
+ weight = getattr(module, "weight", None)
+ dtype = getattr(weight, "dtype", None)
+ return dtype if dtype is not None and dtype.is_floating_point else default
+
+
def _fast_decoder_forward(self: Any, hidden_states: Any) -> Any:
"""``MiniMaxH3VideoViTDecoder3d.forward`` with the block stack over the fused kernels."""
import torch
@@ -894,7 +914,7 @@ def _fast_decoder_body(self: Any, hidden_states: Any) -> Any:
)
hidden_states = self.proj_in(hidden_states)
num_patches = hidden_states.shape[1]
- register_tokens = self.register_tokens.expand(batch_size, -1, -1)
+ register_tokens = self.register_tokens.expand(batch_size, -1, -1).to(hidden_states.dtype)
cls_token = torch.zeros_like(hidden_states[:, :1, :])
hidden_states = torch.cat([hidden_states, register_tokens, cls_token], dim = 1)
grids = [
@@ -911,12 +931,15 @@ def _fast_decoder_body(self: Any, hidden_states: Any) -> Any:
q_dtype = (
torch.get_autocast_dtype("cuda")
if torch.is_autocast_enabled("cuda")
- else hidden_states.dtype
+ else _weight_dtype(self.transformer_blocks[0].attn.to_q, hidden_states.dtype)
)
cos = cos.to(q_dtype).contiguous()
sin = sin.to(q_dtype).contiguous()
hidden_states = _fast_block_stack(self, hidden_states, cos, sin, q_dtype)
- hidden_states = self.norm_out(hidden_states)
+ # stock casts float32-pinned norm_out to proj_out's dtype
+ hidden_states = self.norm_out(hidden_states).to(
+ _weight_dtype(self.proj_out, hidden_states.dtype)
+ )
hidden_states = self.proj_out(hidden_states)
hidden_states = hidden_states[:, :num_patches, :]
p, pt = self.patch_size, self.patch_size_t
diff --git a/studio/backend/core/inference/video_stream_encode.py b/studio/backend/core/inference/video_stream_encode.py
index 22780964ca3..4cf2f6c0491 100644
--- a/studio/backend/core/inference/video_stream_encode.py
+++ b/studio/backend/core/inference/video_stream_encode.py
@@ -1,11 +1,11 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-"""Encode a Wan clip while its VAE is still decoding.
+"""Encode a Wan or MiniMax-H3 clip while its VAE is still decoding.
-A decoder forward hook converts each chunk to uint8 with the pipeline's exact ops, copies it to pinned memory on a
-side stream and feeds a libx264 thread. The streamed mp4 is used only when its frames equal the final frames bit for
-bit; otherwise the clip is encoded as before. ``UNSLOTH_STUDIO_VIDEO_STREAM_ENCODE=0`` turns it off.
+The streamed mp4 is used only when its frames equal the final frames bit for bit, else the clip is encoded as
+before. H3 declares its audio stream up front as ``encode_x264`` does and muxes the soundtrack at the end.
+``UNSLOTH_STUDIO_VIDEO_STREAM_ENCODE=0`` turns it off.
"""
from __future__ import annotations
@@ -46,10 +46,18 @@ class StreamEncode:
processor: Any,
fps: int,
logger: Any = None,
+ *,
+ audio_sample_rate: Optional[int] = None,
) -> None:
import torch
self._torch = torch
+ # the soundtrack's rate, declared before the first frame like encode_x264; None = a video-only file
+ self.audio_sample_rate = int(audio_sample_rate) if audio_sample_rate else None
+ # the last frames may come from the final clip at take() (H3 finishes its tail only when the decode ends)
+ self._tail_ok = False
+ self._container = None
+ self._audio_stream = None
self.vae = vae
self.processor = processor
self.fps = int(fps)
@@ -109,32 +117,30 @@ class StreamEncode:
x = x.float()
x = torch.clamp(x, min = -1.0, max = 1.0)
x = self.processor.postprocess(x[0].permute(1, 0, 2, 3), "pt")
- x = (
- (x.to(torch.float32) * 255)
- .round_()
- .to(torch.uint8)
- .permute(0, 2, 3, 1)
- .contiguous()
- )
- device = x.device
- done = None
- if device.type == "cuda":
- if self._side is None:
- self._side = torch.cuda.Stream(device = device)
- ready = torch.cuda.Event()
- ready.record(torch.cuda.current_stream(device))
- host = torch.empty(x.shape, dtype = torch.uint8, pin_memory = True)
- with torch.cuda.stream(self._side):
- self._side.wait_event(ready)
- host.copy_(x, non_blocking = True)
- done = torch.cuda.Event()
- done.record(self._side)
- x.record_stream(self._side)
- else:
- host = x.cpu() if device.type != "cpu" else x
+ self._push_uint8(x)
except Exception as exc: # noqa: BLE001 - streaming is an optimisation; the normal encode still runs
self.invalidate(f"chunk failed: {type(exc).__name__}")
- return
+
+ def _push_uint8(self, x: Any) -> None:
+ """(F, C, H, W) in [0, 1] -> uint8 (F, H, W, C) with the export's exact ops."""
+ torch = self._torch
+ x = (x.to(torch.float32) * 255).round_().to(torch.uint8).permute(0, 2, 3, 1).contiguous()
+ device = x.device
+ done = None
+ if device.type == "cuda":
+ if self._side is None:
+ self._side = torch.cuda.Stream(device = device)
+ ready = torch.cuda.Event()
+ ready.record(torch.cuda.current_stream(device))
+ host = torch.empty(x.shape, dtype = torch.uint8, pin_memory = True)
+ with torch.cuda.stream(self._side):
+ self._side.wait_event(ready)
+ host.copy_(x, non_blocking = True)
+ done = torch.cuda.Event()
+ done.record(self._side)
+ x.record_stream(self._side)
+ else:
+ host = x.cpu() if device.type != "cpu" else x
self.chunks.append((host, done))
if self._thread is None:
self._thread = threading.Thread(
@@ -230,6 +236,11 @@ class StreamEncode:
stream.height = int(frames.shape[1])
stream.pix_fmt = "yuv420p"
stream.codec_context.thread_type = "FRAME"
+ if self.audio_sample_rate is not None:
+ from diffusers.utils.export_utils import _prepare_audio_stream
+ self._audio_stream = _prepare_audio_stream(
+ container, self.audio_sample_rate
+ )
for frame in frames:
for packet in stream.encode(av.VideoFrame.from_ndarray(frame, format = "rgb24")):
container.mux(packet)
@@ -243,10 +254,13 @@ class StreamEncode:
pass
finally:
if container is not None:
- try:
- container.close()
- except Exception: # noqa: BLE001
- self._failed = True
+ if self._audio_stream is not None and not self._failed and self.valid:
+ self._container = container
+ else:
+ try:
+ container.close()
+ except Exception: # noqa: BLE001
+ self._failed = True
def _join(self) -> None:
if self._thread is not None:
@@ -254,6 +268,14 @@ class StreamEncode:
self._thread.join()
self._thread = None
+ def _close_container(self) -> None:
+ container, self._container = self._container, None
+ if container is not None:
+ try:
+ container.close()
+ except Exception: # noqa: BLE001
+ self._failed = True
+
def _matches(self, video_frames: Any) -> bool:
torch = self._torch
if not isinstance(video_frames, torch.Tensor) or video_frames.dtype != torch.uint8:
@@ -266,7 +288,8 @@ class StreamEncode:
if done is not None:
done.synchronize()
streamed = [host for host, _ in self.chunks]
- if sum(len(h) for h in streamed) != len(video_frames):
+ count = sum(len(h) for h in streamed)
+ if count > len(video_frames) or (count != len(video_frames) and not self._tail_ok):
self.invalidate("frame count differs")
return False
import numpy as np
@@ -281,15 +304,46 @@ class StreamEncode:
start += len(host)
return True
- def take(self, video_frames: Any, fps: int) -> Optional[bytes]:
- """The streamed mp4 when its frames are exactly ``video_frames`` at ``fps``; None (caller encodes) otherwise."""
+ def take(
+ self,
+ video_frames: Any,
+ fps: int,
+ audio: Any = None,
+ audio_sample_rate: Optional[int] = None,
+ ) -> Optional[bytes]:
+ """The streamed mp4 when its frames are exactly ``video_frames`` at ``fps`` and its declared audio stream is
+ ``audio`` at ``audio_sample_rate``; None (caller encodes) otherwise."""
try:
if self.valid and int(fps) != self.fps:
self.invalidate("fps differs")
+ if self.valid and (audio is None) != (self.audio_sample_rate is None):
+ self.invalidate("audio differs")
+ if (
+ self.valid
+ and audio is not None
+ and (audio_sample_rate is None or int(audio_sample_rate) != self.audio_sample_rate)
+ ):
+ self.invalidate("audio rate differs")
if self.valid and not self._decoded:
self.invalidate("no decode")
if self.valid and self._matches(video_frames):
+ streamed = sum(len(host) for host, _ in self.chunks)
+ if streamed < len(video_frames):
+ self._queue.put((video_frames[streamed:], None))
self._join()
+ if audio is not None and not self._failed and self.valid:
+ try:
+ import av
+ from diffusers.utils.export_utils import _write_audio
+
+ if self._container is None or self._audio_stream is None:
+ raise RuntimeError("no open container")
+ _write_audio(
+ self._container, self._audio_stream, audio, self.audio_sample_rate, av
+ )
+ except Exception as exc: # noqa: BLE001 - the stock exporter writes the clip instead
+ self.invalidate(f"audio mux failed: {type(exc).__name__}")
+ self._close_container()
if not self._failed and self.valid:
data = Path(self.path).read_bytes()
count = _mp4_frame_count(data, video_frames.shape[1:3])
@@ -307,6 +361,7 @@ class StreamEncode:
def close(self) -> None:
self.invalidate(self.reason or "closed")
self._join()
+ self._close_container()
self.chunks = []
try:
os.unlink(self.path)
@@ -314,6 +369,145 @@ class StreamEncode:
pass
+class H3StreamEncode(StreamEncode):
+ """Passive ``_decode_clip`` hook replaying H3's clip split and ``_blend`` on the side; decode output untouched."""
+
+ def __init__(
+ self,
+ vae: Any,
+ processor: Any,
+ fps: int,
+ logger: Any = None,
+ **kwargs: Any,
+ ) -> None:
+ pixel_mean = kwargs.pop("pixel_mean")
+ pixel_std = kwargs.pop("pixel_std")
+ super().__init__(vae, processor, fps, logger, **kwargs)
+ self._tail_ok = True
+ self._pixel = (tuple(float(v) for v in pixel_mean), tuple(float(v) for v in pixel_std))
+ self._overlap = None
+ self._clips = 0
+
+ def _pixel_tensors(self, device: Any) -> tuple:
+ """Built once: a pageable ``torch.tensor(..., device=)`` per clip would block the host on the GPU."""
+ torch = self._torch
+ held = getattr(self, "_pixel_on", None)
+ if held is None or held[0] != device:
+ pair = []
+ for values in self._pixel:
+ host = torch.tensor(values, dtype = torch.float32)
+ if device.type == "cuda":
+ host = host.pin_memory()
+ pair.append(host.to(device, non_blocking = True).view(1, -1, 1, 1, 1))
+ held = (device, tuple(pair))
+ self._pixel_on = held
+ return held[1]
+
+ def _on_clip(self, clip: Any) -> None:
+ if not self.valid or not self._decoding:
+ return
+ torch = self._torch
+ try:
+ if self._failed:
+ self.invalidate("encoder failed")
+ return
+ if not torch.is_tensor(clip) or clip.ndim != 5 or clip.shape[0] != 1:
+ self.invalidate("unexpected decoder output")
+ return
+ vae = self.vae
+ chunk_frames = int(vae.tokens_chunk_size) * int(vae.temporal_compression_ratio)
+ splits = int(int(vae.config.token_drop) > 0) + 1
+ pre = int(vae.frame_pre_padding)
+ mean, std = self._pixel_tensors(clip.device)
+ self._clips += 1
+ for j in range(splits):
+ chunk = clip[:, :, j * chunk_frames : (j + 1) * chunk_frames][:, :, pre:]
+ if j:
+ self._overlap = chunk
+ continue
+ if self._overlap is not None:
+ chunk = vae._blend(self._overlap, chunk, vae.frame_overlap, dim = -3)
+ self._overlap = None
+ # MiniMaxH3VideoDecodeStep's denormalise, then the uint8 export's postprocess
+ x = (chunk.float() * std + mean).clamp(0, 1)
+ self._push_uint8(self.processor.postprocess(x[0].permute(1, 0, 2, 3), "pt"))
+ except Exception as exc: # noqa: BLE001 - streaming is an optimisation; the normal encode still runs
+ self.invalidate(f"chunk failed: {type(exc).__name__}")
+
+ @contextlib.contextmanager
+ def hooks(self) -> Iterator[None]:
+ """Arm the clip hook for the outermost ``vae.decode``; a second ``_decode`` in that window disarms it."""
+ vae = self.vae
+ restore: list = []
+ state = {"inner": 0}
+
+ def _wrap(name: str, make: Any) -> None:
+ original = getattr(vae, name, None)
+ if not callable(original):
+ raise AttributeError(name)
+ had_own = name in getattr(vae, "__dict__", {})
+ setattr(vae, name, make(original))
+ restore.append((name, original, had_own))
+
+ def _decode_wrapper(original: Any) -> Any:
+ def decode(*args: Any, **kwargs: Any) -> Any:
+ if self._decoding:
+ return original(*args, **kwargs)
+ if self._decoded:
+ self.invalidate("second decode")
+ self._decoding = True
+ try:
+ return original(*args, **kwargs)
+ finally:
+ self._decoding = False
+ self._decoded = True
+
+ return decode
+
+ def _inner_wrapper(original: Any) -> Any:
+ def _decode(*args: Any, **kwargs: Any) -> Any:
+ if self._decoding:
+ state["inner"] += 1
+ if state["inner"] > 1:
+ # an OOM retry or a sliced batch: the clips so far belong to another pass
+ self.invalidate("decoder restarted")
+ return original(*args, **kwargs)
+
+ return _decode
+
+ # one eager island under a compiled decode, as the Wan hook is
+ on_clip = self._torch.compiler.disable(self._on_clip)
+
+ def _clip_wrapper(original: Any) -> Any:
+ def _decode_clip(*args: Any, **kwargs: Any) -> Any:
+ out = original(*args, **kwargs)
+ on_clip(out)
+ return out
+
+ return _decode_clip
+
+ try:
+ _wrap("decode", _decode_wrapper)
+ _wrap("_decode", _inner_wrapper)
+ _wrap("_decode_clip", _clip_wrapper)
+ except Exception: # noqa: BLE001 - a VAE without the clip loop just encodes afterwards
+ self.invalidate("hooks refused")
+ try:
+ yield
+ except BaseException:
+ self.close()
+ raise
+ finally:
+ for name, original, had_own in reversed(restore):
+ try:
+ if had_own:
+ setattr(vae, name, original)
+ else:
+ delattr(vae, name)
+ except Exception: # noqa: BLE001 - cleanup is best-effort
+ pass
+
+
def _mp4_frame_count(data: bytes, size: Any) -> Optional[int]:
"""Video packets in ``data`` when its video stream is ``size`` (H, W); None when it does not demux."""
if not data:
@@ -349,13 +543,20 @@ def offer_stream(session: Optional[StreamEncode]) -> Iterator[None]:
_offered.session = previous
-def claim_stream(video_frames: Any, fps: int) -> Optional[bytes]:
- """The offered session's mp4 for exactly these frames, once; None (encode normally) otherwise."""
+def claim_stream(
+ video_frames: Any,
+ fps: int,
+ audio: Any = None,
+ audio_sample_rate: Optional[int] = None,
+) -> Optional[bytes]:
+ """The offered session's mp4 for exactly these frames (and soundtrack), once; None (encode normally) otherwise."""
session = getattr(_offered, "session", None)
if session is None:
return None
_offered.session = None
- return session.take(video_frames, fps)
+ if audio is None:
+ return session.take(video_frames, fps)
+ return session.take(video_frames, fps, audio, audio_sample_rate)
def open_stream_encode(
@@ -391,3 +592,64 @@ def open_stream_encode(
return StreamEncode(vae, processor, fps, logger)
except Exception: # noqa: BLE001 - no PyAV, no CUDA or no parameters: encode afterwards
return None
+
+
+_H3_CLIP_ATTRS = (
+ "tokens_chunk_size",
+ "temporal_compression_ratio",
+ "frame_pre_padding",
+ "frame_overlap",
+ "_blend",
+ "_decode",
+ "_decode_clip",
+)
+
+
+def open_h3_stream_encode(
+ pipe: Any,
+ fps: int,
+ *,
+ engage: bool,
+ logger: Any = None,
+) -> Optional[StreamEncode]:
+ """A session for a resident CUDA ``AutoencoderKLMiniMaxH3`` whose soundtrack is muxed at the end, or None."""
+ if not engage or not stream_encode_enabled():
+ return None
+ from .video_encode import frame_threads_enabled
+ from .video_nvenc import nvenc_requested
+
+ if not frame_threads_enabled() or nvenc_requested():
+ return None
+ vae = getattr(pipe, "vae", None)
+ processor = getattr(pipe, "video_processor", None)
+ if type(vae).__name__ != "AutoencoderKLMiniMaxH3" or not callable(
+ getattr(processor, "postprocess", None)
+ ):
+ return None
+ if not all(hasattr(vae, name) for name in _H3_CLIP_ATTRS):
+ return None
+ try:
+ import av # noqa: F401
+ import torch
+ from diffusers.utils.export_utils import _prepare_audio_stream, _write_audio # noqa: F401
+
+ if getattr(vae, "use_slicing", False) or not torch.cuda.is_available():
+ return None
+ # a VAE parked on the host between renders (pinned swap) still decodes on the execution device
+ device = next(vae.decoder.parameters()).device
+ if device.type != "cuda":
+ device = torch.device(getattr(pipe, "_execution_device", None) or "cpu")
+ if device.type != "cuda":
+ return None
+ rate = getattr(pipe, "audio_sampling_rate", None)
+ return H3StreamEncode(
+ vae,
+ processor,
+ fps,
+ logger,
+ audio_sample_rate = int(rate) if rate else None,
+ pixel_mean = pipe.pixel_mean,
+ pixel_std = pipe.pixel_std,
+ )
+ except Exception: # noqa: BLE001 - no PyAV, no CUDA or no parameters: encode afterwards
+ return None
diff --git a/studio/backend/tests/test_video_minimax_h3_vae.py b/studio/backend/tests/test_video_minimax_h3_vae.py
index 68ba0e9eb7e..eb522311827 100644
--- a/studio/backend/tests/test_video_minimax_h3_vae.py
+++ b/studio/backend/tests/test_video_minimax_h3_vae.py
@@ -281,7 +281,8 @@ def test_the_decoder_residual_stream_stays_float32_under_the_decode_autocast(mon
with torch.no_grad(), torch.autocast("cuda", dtype = torch.float16):
got, want = vae.decoder(z), ref.decoder(z)
assert not getattr(vae.decoder, "_unsloth_fast_failed", False)
- assert seen == [torch.float32, torch.float32]
+ # the stock forward aligns register_tokens with proj_in's autocast output, then the float32 anchors promote
+ assert seen == [torch.float16, torch.float32]
assert got.dtype == want.dtype
torch.testing.assert_close(got.float(), want.float(), rtol = 2e-3, atol = 2e-3)
@@ -359,6 +360,46 @@ def test_fused_decoder_matches_the_stock_decoder(device):
torch.testing.assert_close(got, ref, rtol = 1e-4, atol = 1e-4)
+def _mixed_precision_vae(tmp_path, device):
+ """The tiny VAE through diffusers' own bfloat16 load: ``_keep_in_fp32_modules`` pins the norms and the
+ ``scale1`` / ``scale2`` anchors to float32 while the decoder GEMMs load in bfloat16, as Studio's H3 load does."""
+ _tiny_vae().save_pretrained(tmp_path / "vae")
+ vae = type(_tiny_vae()).from_pretrained(tmp_path / "vae", torch_dtype = torch.bfloat16)
+ return vae.to(device).eval()
+
+
[email protected]("device", DEVICES)
+def test_fused_decoder_follows_the_mixed_precision_load(tmp_path, device):
+ vae = _mixed_precision_vae(tmp_path, device)
+ block = vae.decoder.transformer_blocks[0]
+ if (
+ block.scale1.dtype is not torch.float32
+ or block.attn.to_q.weight.dtype is not torch.bfloat16
+ ):
+ pytest.skip("this diffusers loads the H3 VAE without the float32 anchors")
+ fast = copy.deepcopy(vae)
+ assert H._install_decoder(fast)
+ seen = []
+ stack = H._fast_block_stack
+
+ def spy(decoder, hidden_states, *args):
+ out = stack(decoder, hidden_states, *args)
+ seen.append(out.dtype)
+ return out
+
+ z = torch.randn(1, 8, 3, 4, 5, device = device, dtype = torch.bfloat16)
+ with torch.no_grad(), pytest.MonkeyPatch.context() as mp:
+ mp.setattr(H, "_fast_block_stack", spy)
+ ref = vae.decoder(z)
+ got = fast.decoder(z)
+ assert not getattr(
+ fast.decoder, "_unsloth_fast_failed", False
+ ), "the fused decoder fell back to stock on the bfloat16 / float32 mixed load"
+ assert seen == [torch.float32], "the residual stream must stay float32 like the stock blocks"
+ assert got.dtype == ref.dtype and got.shape == ref.shape
+ torch.testing.assert_close(got.float(), ref.float(), rtol = 2e-2, atol = 2e-2)
+
+
def test_tile_batching_matches_the_stock_tile_loop(monkeypatch):
vae = _tiny_vae()
fast = copy.deepcopy(vae)
diff --git a/studio/backend/tests/test_video_stream_encode.py b/studio/backend/tests/test_video_stream_encode.py
index 98217afa9be..1c8a67b70ea 100644
--- a/studio/backend/tests/test_video_stream_encode.py
+++ b/studio/backend/tests/test_video_stream_encode.py
@@ -5,6 +5,7 @@
from __future__ import annotations
+import io
import os
import numpy as np
@@ -309,3 +310,209 @@ def test_rocm_bf16_decode_streams_the_exported_frames(monkeypatch, tmp_path):
assert data is not None, vse.STATS["last"]
assert vse.STATS["streamed"] == before + 1
assert len(_mp4_frames(data, tmp_path)) == 13
+
+
+# MiniMax-H3: temporal clips cross-faded into each other, a soundtrack muxed at the end.
+_H3_RATE = 16000
+_H3_PIXEL = ((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))
+
+
+def _h3_vae():
+ cls = getattr(diffusers, "AutoencoderKLMiniMaxH3", None)
+ if cls is None:
+ pytest.skip("diffusers without AutoencoderKLMiniMaxH3")
+ torch.manual_seed(0)
+ vae = cls(
+ block_out_channels = (16, 32),
+ layers_per_block = 1,
+ spatial_downsample_factors = (2, 2),
+ temporal_downsample_factors = (2, 1),
+ norm_num_groups = 8,
+ latent_channels = 8,
+ decoder_num_layers = 1,
+ decoder_num_attention_heads = 2,
+ decoder_attention_head_dim = 16,
+ decoder_num_register_tokens = 2,
+ decoder_ffn_mult = 2,
+ clip_length = 9,
+ token_drop = 1,
+ ).eval()
+ vae.tile_sample_min_height = vae.tile_sample_min_width = 16
+ vae.tile_sample_min_overlap_height = vae.tile_sample_min_overlap_width = 4
+ return vae
+
+
+class _H3Pipe:
+ """MiniMaxH3VideoDecodeStep's tail: decode, ImageNet denormalise, postprocess_video to np."""
+
+ pixel_mean, pixel_std = _H3_PIXEL
+ audio_sampling_rate = _H3_RATE
+
+ def __init__(self, vae):
+ self.vae = vae
+ self.video_processor = VideoProcessor(vae_scale_factor = 16, do_normalize = False)
+
+ def __call__(self, z):
+ video = self.vae.decode(z, return_dict = False)[0]
+ mean = torch.tensor(self.pixel_mean).view(1, -1, 1, 1, 1)
+ std = torch.tensor(self.pixel_std).view(1, -1, 1, 1, 1)
+ video = (video.float() * std + mean).clamp(0, 1)
+ return self.video_processor.postprocess_video(video, output_type = "np")[0]
+
+
+def _h3_session(pipe, **kw):
+ return vse.H3StreamEncode(
+ pipe.vae,
+ pipe.video_processor,
+ 8,
+ audio_sample_rate = kw.get("rate", _H3_RATE),
+ pixel_mean = pipe.pixel_mean,
+ pixel_std = pipe.pixel_std,
+ )
+
+
+def _h3_render(
+ pipe,
+ session,
+ latent_frames = 14,
+):
+ torch.manual_seed(1)
+ z = torch.randn(1, 8, latent_frames, 4, 6)
+ with torch.inference_mode(), uint8_video_frames(pipe), session.hooks():
+ return pipe(z)
+
+
+def _audio(frames):
+ torch.manual_seed(2)
+ return (torch.rand(2, _H3_RATE * frames // 8) * 2 - 1) * 0.5
+
+
+def _mp4_layout(data):
+ """What two encodes of the same frames and soundtrack with the same settings must share. Video packet bytes
+ are not in it: libx264 through PyAV is not run-to-run byte-reproducible here (two stock exports of one clip
+ can differ in a rate-control decision), so they would make the comparison flaky."""
+ import re
+
+ with av.open(io.BytesIO(data)) as c:
+ streams = []
+ for s in c.streams:
+ cc = s.codec_context
+ shape = (
+ (cc.width, cc.height, str(cc.pix_fmt))
+ if s.type == "video"
+ else (cc.sample_rate, cc.channels)
+ )
+ streams.append((s.index, s.type, cc.name, shape, str(s.time_base)))
+ video = [p for p in c.demux(video = 0) if p.size]
+ c.seek(0)
+ audio = [bytes(p) for p in c.demux(audio = 0) if p.size]
+ c.seek(0)
+ decoded = sum(1 for _ in c.decode(video = 0))
+ extradata = bytes(c.streams.video[0].codec_context.extradata or b"")
+ settings = re.search(
+ rb"x264 - core [^\x00]*", extradata + b"".join(bytes(p) for p in video[:1])
+ )
+ return {
+ "streams": streams,
+ "x264_settings": settings.group(0) if settings else None,
+ "video_packets": len(video),
+ "decoded_frames": decoded,
+ "audio_packets": audio,
+ }
+
+
+def test_h3_streamed_mp4_matches_the_x264_export(tmp_path):
+ from core.inference.video_encode import encode_x264
+
+ pipe = _H3Pipe(_h3_vae())
+ session = _h3_session(pipe)
+ frames = _h3_render(pipe, session)
+ assert isinstance(frames, torch.Tensor) and frames.dtype == torch.uint8
+ streamed = sum(len(host) for host, _ in session.chunks)
+ # two clips stream while decoding; the final cross-fade tail comes from the exported clip
+ assert 0 < streamed < len(frames)
+ audio = _audio(len(frames))
+ data = session.take(frames, 8, audio, _H3_RATE)
+ assert data is not None, vse.STATS["last"]
+ reference = tmp_path / "reference.mp4"
+ assert encode_x264(frames, 8, str(reference), audio, _H3_RATE)
+ got, want = _mp4_layout(data), _mp4_layout(reference.read_bytes())
+ assert want["x264_settings"] is not None and want["decoded_frames"] == len(frames)
+ # same streams in the same order, same encoder settings, same frame count, the soundtrack byte for byte
+ assert got == want
+
+
+def test_h3_soundtrack_mismatch_falls_back():
+ pipe = _H3Pipe(_h3_vae())
+ for audio, rate in ((None, None), ("audio", _H3_RATE + 1)):
+ session = _h3_session(pipe)
+ frames = _h3_render(pipe, session)
+ track = _audio(len(frames)) if audio else None
+ assert session.take(frames, 8, track, rate) is None
+ assert vse.STATS["last"] in ("audio differs", "audio rate differs")
+
+
+def test_h3_differing_frames_fall_back():
+ pipe = _H3Pipe(_h3_vae())
+ session = _h3_session(pipe)
+ frames = _h3_render(pipe, session).clone()
+ frames[1, 0, 0, 0] ^= 1
+ assert session.take(frames, 8, _audio(len(frames)), _H3_RATE) is None
+ assert vse.STATS["last"] == "frames differ"
+
+
+def test_h3_a_second_decode_pass_falls_back():
+ pipe = _H3Pipe(_h3_vae())
+ session = _h3_session(pipe)
+ vae = pipe.vae
+
+ def retried(z, return_dict = True):
+ # the OOM scope's retry: a second _decode pass inside one outermost decode
+ vae._decode(z)
+ return (vae._decode(z),)
+
+ vae.decode = retried
+ frames = _h3_render(pipe, session)
+ assert session.take(frames, 8, _audio(len(frames)), _H3_RATE) is None
+ assert vse.STATS["last"] == "decoder restarted"
+
+
+def test_h3_hooks_leave_the_decode_output_and_the_vae_untouched():
+ pipe = _H3Pipe(_h3_vae())
+ before = {name: pipe.vae.__dict__.get(name) for name in ("decode", "_decode", "_decode_clip")}
+ torch.manual_seed(1)
+ z = torch.randn(1, 8, 14, 4, 6)
+ with torch.inference_mode(), uint8_video_frames(pipe):
+ reference = pipe(z)
+ session = _h3_session(pipe)
+ frames = _h3_render(pipe, session)
+ session.close()
+ assert torch.equal(frames, reference)
+ assert {name: pipe.vae.__dict__.get(name) for name in before} == before
+
+
+def test_h3_engagement_gates(monkeypatch):
+ pipe = _H3Pipe(_h3_vae())
+ assert vse.open_h3_stream_encode(pipe, 8, engage = False) is None
+ monkeypatch.setenv(vse.STREAM_ENCODE_ENV, "0")
+ assert vse.open_h3_stream_encode(pipe, 8, engage = True) is None
+ monkeypatch.delenv(vse.STREAM_ENCODE_ENV)
+ # a Wan VAE never takes the H3 session, and an H3 VAE never takes the Wan one
+ assert vse.open_h3_stream_encode(_Pipe(_vae()), 8, engage = True) is None
+ assert vse.open_stream_encode(pipe, 8, engage = True) is None
+
+
+def test_encode_mp4_claims_an_h3_stream_with_its_soundtrack():
+ from core.inference.video import VideoBackend
+
+ pipe = _H3Pipe(_h3_vae())
+ session = _h3_session(pipe)
+ frames = _h3_render(pipe, session)
+ audio = _audio(len(frames))
+ before = vse.STATS["streamed"]
+ with vse.offer_stream(session):
+ data = VideoBackend._encode_mp4(frames, 8, audio, pipe, audio_sample_rate = _H3_RATE)
+ assert vse.STATS["streamed"] == before + 1
+ with av.open(io.BytesIO(data)) as c:
+ assert len(c.streams.audio) == 1
+ assert vse._mp4_frame_count(data, frames.shape[1:3]) == len(frames)