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 MiniMax-H3: normalise a reference video one VAE chunk at a time (#17096)

Daniel Han870041c89a46
diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.py
index 6a7d9a76f53..133a105d7a0 100644
--- a/studio/backend/core/inference/video.py
+++ b/studio/backend/core/inference/video.py
@@ -12146,6 +12146,11 @@ class VideoBackend:
speed_optims = speed_optims + tuple(f"h3_vae_{name}" for name in vae_levers)
except Exception as exc: # noqa: BLE001 -- optimisation only, never fail a load
logger.warning("video.h3_vae_fast failed, keeping the stock VAE: %s", exc)
+ try:
+ from .video_minimax_h3_ref_encode import install_h3_chunked_reference_encode
+ install_h3_chunked_reference_encode(logger)
+ except Exception as exc: # noqa: BLE001 -- memory only, never fail a load
+ logger.warning("video.h3_ref_encode: keeping the stock reference encode: %s", exc)
# Opt-in Sol-H3-VAE (UNSLOTH_H3_SOL_VAE=1): the video stream's _decode only, the stock levers above stay as
# its fallback; the audio VAE is untouched.
try:
diff --git a/studio/backend/core/inference/video_minimax_h3_ref_encode.py b/studio/backend/core/inference/video_minimax_h3_ref_encode.py
new file mode 100644
index 00000000000..8099b2f555c
--- /dev/null
+++ b/studio/backend/core/inference/video_minimax_h3_ref_encode.py
@@ -0,0 +1,158 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""MiniMax-H3 reference-video VAE condition normalised per 17-frame chunk, not as one float32 clip; bit-identical
+(elementwise), only over the mirrored diffusers 0.42.1 sources. ``UNSLOTH_H3_CHUNKED_REF_ENCODE=0`` disables."""
+
+from __future__ import annotations
+
+import hashlib
+import inspect
+import os
+import threading
+from typing import Any, Optional
+
+H3_CHUNKED_REF_ENCODE_ENV = "UNSLOTH_H3_CHUNKED_REF_ENCODE"
+_ENCODERS_MODULE = "diffusers.modular_pipelines.minimax_h3.encoders"
+_FUNC = "encode_vae_condition"
+
+# sha256[:16] of inspect.getsource of the mirrored functions (diffusers 0.42.1).
+_KNOWN_SOURCES = {
+ "encode_vae_condition": frozenset({"8dab1fbe60ffab90"}),
+ "encode": frozenset({"7bd0682f1598a640"}),
+ "_encode": frozenset({"591b051aaa5744c4"}),
+}
+
+_LOCK = threading.Lock()
+_VERIFIED: dict = {}
+
+
+def enabled() -> bool:
+ raw = (os.environ.get(H3_CHUNKED_REF_ENCODE_ENV) or "").strip().lower()
+ return raw not in ("0", "off", "false", "no")
+
+
+def _sha(fn: Any) -> Optional[str]:
+ try:
+ return hashlib.sha256(inspect.getsource(fn).encode()).hexdigest()[:16]
+ except Exception: # noqa: BLE001
+ return None
+
+
+def _vae_known(vae: Any) -> bool:
+ cls = type(vae)
+ known = _VERIFIED.get(cls)
+ if known is None:
+ known = cls.__name__ == "AutoencoderKLMiniMaxH3" and all(
+ _sha(getattr(cls, name, None)) in _KNOWN_SOURCES[name] for name in ("encode", "_encode")
+ )
+ _VERIFIED[cls] = known
+ return known and not ({"encode", "_encode"} & set(getattr(vae, "__dict__", {})))
+
+
+def _eligible(vae: Any, pixels: Any) -> bool:
+ import torch
+
+ if not enabled() or not _vae_known(vae):
+ return False
+ config = getattr(vae, "config", None)
+ clip = getattr(config, "clip_length", None)
+ if not isinstance(clip, int) or clip <= 0 or getattr(vae, "encoder", None) is None:
+ return False
+ return (
+ isinstance(pixels, torch.Tensor)
+ and pixels.dtype == torch.uint8
+ and pixels.ndim == 5
+ and pixels.shape[0] == 1
+ and pixels.shape[2] > clip
+ )
+
+
+def _chunked_moments(vae: Any, pixels: Any, pixel_mean: Any, pixel_std: Any) -> Any:
+ """Moments of ``vae.encode`` on the normalised clip, one chunk of float32 at a time."""
+ import torch
+ from diffusers.models.modeling_utils import get_parameter_dtype
+
+ hook = getattr(vae, "_hf_hook", None)
+ if hook is not None and hasattr(hook, "pre_forward"):
+ hook.pre_forward(vae) # as apply_forward_hook on encode
+ clip = vae.config.clip_length
+ dtype = get_parameter_dtype(vae.encoder)
+ num_frames = pixels.shape[2]
+ moments = []
+ for start in range(0, num_frames, clip):
+ part = pixels[:, :, start : start + clip]
+ if part.shape[2] < clip:
+ # stock pads with the last normalised frame: same values
+ part = torch.cat(
+ [part, pixels[:, :, -1:].repeat(1, 1, clip - part.shape[2], 1, 1)], dim = 2
+ )
+ x = ((part.to(torch.float32).div(255.0) - pixel_mean) / pixel_std).to(dtype)
+ del part
+ moments.append(vae._encode_clip(x))
+ del x
+ out = torch.cat(moments, dim = 2)
+ del moments
+ if vae.config.token_drop > 0:
+ out = out[:, :, : -vae.config.token_drop]
+ return out
+
+
+def _make_shim(original: Any) -> Any:
+ def encode_vae_condition(
+ vae: Any,
+ pixels: Any,
+ pixel_mean: tuple,
+ pixel_std: tuple,
+ encode_seed: int = 42,
+ ) -> Any:
+ if not _eligible(vae, pixels):
+ return original(vae, pixels, pixel_mean, pixel_std, encode_seed)
+ import torch
+ from diffusers.models.autoencoders.vae import DiagonalGaussianDistribution
+
+ latents_mean = torch.tensor(vae.config.latents_mean).view(1, -1, 1, 1, 1)
+ latents_std = torch.tensor(vae.config.latents_std).view(1, -1, 1, 1, 1)
+ pixel_mean = torch.tensor(pixel_mean, device = pixels.device).view(1, -1, 1, 1, 1)
+ pixel_std = torch.tensor(pixel_std, device = pixels.device).view(1, -1, 1, 1, 1)
+
+ posterior = DiagonalGaussianDistribution(
+ _chunked_moments(vae, pixels, pixel_mean, pixel_std)
+ )
+ latents = posterior.sample(generator = torch.Generator().manual_seed(encode_seed))
+ latents = latents.to(torch.float16).float().cpu()
+ return (latents - latents_mean) / latents_std
+
+ encode_vae_condition._unsloth_chunked_ref_encode = True
+ encode_vae_condition.__wrapped__ = original
+ try:
+ encode_vae_condition.__signature__ = inspect.signature(original)
+ except (TypeError, ValueError):
+ pass
+ return encode_vae_condition
+
+
+def install_h3_chunked_reference_encode(logger: Any = None) -> bool:
+ """Shims the module global the modular step calls; idempotent, never raises."""
+ if not enabled():
+ return False
+ try:
+ from diffusers.modular_pipelines.minimax_h3 import encoders as module
+ except Exception: # noqa: BLE001 - not an H3-capable diffusers
+ return False
+ with _LOCK:
+ current = getattr(module, _FUNC, None)
+ if not callable(current):
+ return False
+ if getattr(current, "_unsloth_chunked_ref_encode", False):
+ return True
+ if _sha(current) not in _KNOWN_SOURCES["encode_vae_condition"]:
+ if logger is not None:
+ logger.info(
+ "video.h3_ref_encode: unknown encode_vae_condition source, keeping stock"
+ )
+ return False
+ setattr(module, _FUNC, _make_shim(current))
+ if logger is not None:
+ logger.info("video.h3_ref_encode: reference videos normalise one VAE chunk at a time")
+ return True
diff --git a/studio/backend/tests/test_h3_ref_encode.py b/studio/backend/tests/test_h3_ref_encode.py
new file mode 100644
index 00000000000..1fe5b30e5f5
--- /dev/null
+++ b/studio/backend/tests/test_h3_ref_encode.py
@@ -0,0 +1,136 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""CPU tests for the chunked MiniMax-H3 reference-video condition on a tiny random H3 VAE."""
+
+from __future__ import annotations
+
+import pytest
+
+torch = pytest.importorskip("torch")
+encoders = pytest.importorskip("diffusers.modular_pipelines.minimax_h3.encoders")
+vae_mod = pytest.importorskip("diffusers.models.autoencoders.autoencoder_kl_minimax_h3")
+
+from core.inference import video_minimax_h3_ref_encode as ref_encode # noqa: E402
+
+_MEAN = (0.485, 0.456, 0.406)
+_STD = (0.229, 0.224, 0.225)
+
+
+def _vae():
+ torch.manual_seed(0)
+ vae = vae_mod.AutoencoderKLMiniMaxH3(
+ latent_channels = 4,
+ block_out_channels = [8, 8, 16, 16, 16, 16],
+ layers_per_block = 1,
+ norm_num_groups = 4,
+ decoder_num_layers = 1,
+ decoder_num_attention_heads = 2,
+ decoder_attention_head_dim = 8,
+ latents_mean = (0.1, -0.2, 0.3, 0.0),
+ latents_std = (1.5, 0.5, 2.0, 1.0),
+ ).eval()
+ return vae
+
+
+def _pixels(
+ frames,
+ height = 32,
+ width = 48,
+ seed = 0,
+):
+ g = torch.Generator().manual_seed(seed)
+ return torch.randint(0, 256, (1, 3, frames, height, width), generator = g, dtype = torch.uint8)
+
+
+def shim(monkeypatch):
+ monkeypatch.delenv(ref_encode.H3_CHUNKED_REF_ENCODE_ENV, raising = False)
+ original = encoders.encode_vae_condition
+ if ref_encode._sha(original) not in ref_encode._KNOWN_SOURCES["encode_vae_condition"]:
+ pytest.skip("diffusers H3 encoder source this shim does not mirror")
+ monkeypatch.setattr(encoders, "encode_vae_condition", original)
+ assert ref_encode.install_h3_chunked_reference_encode()
+ assert ref_encode.install_h3_chunked_reference_encode()
+ installed = encoders.encode_vae_condition
+ assert installed is not original and installed.__wrapped__ is original
+ return original, installed
+
+
[email protected]("frames", [22, 34, 39, 56])
+def test_chunked_reference_matches_stock_bit_for_bit(shim, frames):
+ original, installed = shim
+ vae = _vae()
+ pixels = _pixels(frames)
+ with torch.no_grad():
+ stock = original(vae, pixels, _MEAN, _STD, 42)
+ calls = {"n": 0}
+ clip = vae._encode_clip
+
+ def counted(x):
+ calls["n"] += 1
+ assert x.shape[2] == vae.config.clip_length and x.is_contiguous()
+ return clip(x)
+
+ vae._encode_clip = counted
+ chunked = installed(vae, pixels, _MEAN, _STD, 42)
+ assert calls["n"] == -(-frames // vae.config.clip_length)
+ assert stock.dtype == chunked.dtype and stock.shape == chunked.shape
+ assert torch.equal(stock, chunked)
+
+
+def test_spatial_tiles_inside_each_chunk_match(shim):
+ original, installed = shim
+ vae = _vae()
+ vae.enable_tiling(
+ tile_sample_min_height = 32,
+ tile_sample_min_width = 32,
+ tile_sample_min_overlap_height = 16,
+ tile_sample_min_overlap_width = 16,
+ )
+ pixels = _pixels(22, height = 48, width = 64, seed = 3)
+ with torch.no_grad():
+ assert torch.equal(
+ original(vae, pixels, _MEAN, _STD, 7), installed(vae, pixels, _MEAN, _STD, 7)
+ )
+
+
+def test_single_frames_short_clips_and_the_switch_keep_stock(shim, monkeypatch):
+ original, installed = shim
+ vae = _vae()
+ seen = []
+ monkeypatch.setattr(ref_encode, "_chunked_moments", lambda *a: seen.append(a) or 1 / 0)
+ with torch.no_grad():
+ for frames in (1, 17):
+ p = _pixels(frames)
+ assert torch.equal(
+ installed(vae, p, _MEAN, _STD, 42), original(vae, p, _MEAN, _STD, 42)
+ )
+ p = _pixels(22)
+ monkeypatch.setenv(ref_encode.H3_CHUNKED_REF_ENCODE_ENV, "0")
+ assert torch.equal(installed(vae, p, _MEAN, _STD, 42), original(vae, p, _MEAN, _STD, 42))
+ monkeypatch.delenv(ref_encode.H3_CHUNKED_REF_ENCODE_ENV)
+ # float pixels or an instance-level encode wrapper are not what the mirror covers
+ assert torch.equal(
+ installed(vae, p.float(), _MEAN, _STD, 42), original(vae, p.float(), _MEAN, _STD, 42)
+ )
+ vae.encode = vae.encode
+ assert torch.equal(installed(vae, p, _MEAN, _STD, 42), original(vae, p, _MEAN, _STD, 42))
+ assert seen == []
+
+
+def test_unknown_source_is_not_shimmed(monkeypatch):
+ monkeypatch.delenv(ref_encode.H3_CHUNKED_REF_ENCODE_ENV, raising = False)
+
+ def encode_vae_condition(
+ vae,
+ pixels,
+ pixel_mean,
+ pixel_std,
+ encode_seed = 42,
+ ):
+ return None
+
+ monkeypatch.setattr(encoders, "encode_vae_condition", encode_vae_condition)
+ assert not ref_encode.install_h3_chunked_reference_encode()
+ assert encoders.encode_vae_condition is encode_vae_condition