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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: add MiniMax H3 video generation (#7989)
oobabooga495ba21ebd41
diff --git a/.github/scripts/assert-nobuild.ps1 b/.github/scripts/assert-nobuild.ps1index 477bb14172f..9cb39ed52ed 100644--- a/.github/scripts/assert-nobuild.ps1+++ b/.github/scripts/assert-nobuild.ps1@@ -18,7 +18,9 @@ if (-not (Test-Path -LiteralPath $LogPath)) {# "Built an sdist" is NOT "needed a compiler": each name was verified against its own# sdist (setuptools.build_meta, no ext_modules, no .c/.cpp/.pyx/.rs), so its PEP 517# build is a pure-Python copy step. clean-machine-assert.sh carries the per-name detail.-$allow = @('openai-whisper', 'argbind', 'randomname', 'antlr4-python3-runtime', 'triton-kernels')+# diffusers is pinned to a source archive because MiniMax-H3 support is not in any release+# yet; remove it here once a release carries H3. clean-machine-assert.sh carries the detail.+$allow = @('openai-whisper', 'argbind', 'randomname', 'antlr4-python3-runtime', 'triton-kernels', 'diffusers')if ($env:UNSLOTH_ALLOW_SDIST) {$allow += ($env:UNSLOTH_ALLOW_SDIST -split '\s+' | Where-Object { $_ })}diff --git a/.github/scripts/clean-machine-assert.sh b/.github/scripts/clean-machine-assert.shindex 76b1aa7157a..40d495634d0 100755--- a/.github/scripts/clean-machine-assert.sh+++ b/.github/scripts/clean-machine-assert.sh@@ -101,9 +101,14 @@ for check in "$@"; do# triton-kernels -- a git URL under the triton repo's python/triton_kernels# subdir: 75 Python files, no setup.py, kernels compiled at runtime. Named by# the installer, not chosen by resolution, and only the Linux legs reach it.+ # diffusers -- pinned to a source archive because MiniMax-H3 support is not in+ # any release yet. Plain setuptools, no ext_modules, and the tree has zero+ # .c/.cpp/.pyx/.rs/.cu files, so the PEP 517 build is a pure-Python copy.+ # REMOVE this entry once a diffusers release carries H3 and the requirement+ # goes back to a version specifier.# UNSLOTH_ALLOW_SDIST extends it. Lowercased and underscore-folded on both sides:# the distribution name and the name uv prints can differ on the separator.- _allow="$(printf '%s' "openai-whisper argbind randomname antlr4-python3-runtime triton-kernels ${UNSLOTH_ALLOW_SDIST:-}" | tr 'A-Z_' 'a-z-')"+ _allow="$(printf '%s' "openai-whisper argbind randomname antlr4-python3-runtime triton-kernels diffusers ${UNSLOTH_ALLOW_SDIST:-}" | tr 'A-Z_' 'a-z-')"if [ ! -f "$LOG" ]; thenfail "nobuild requested but $LOG is missing"elsediff --git a/pyproject.toml b/pyproject.tomlindex 7587d0b8acb..14e9c98c21c 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -103,7 +103,8 @@ studio = ["nest_asyncio","datasets==4.3.0","pyjwt",- "huggingface-hub==0.36.2",+ "huggingface-hub>=1.23.0,<2.0 ; python_version >= '3.10'",+ "huggingface-hub==0.36.2 ; python_version < '3.10'","urllib3>=2.3.0","structlog>=24.1.0","diceware",@@ -144,6 +145,8 @@ huggingfacenotorch = [# workflow raises without it), the cache_context child-registry behavior, and the# Flux2 / Z-Image pipelines. An unversioned entry let an upgrade keep an older# diffusers, so advertised models failed to load until the user upgraded by hand.+ # Studio's installer requirements carry the temporary MiniMax-H3 commit pin. A+ # VCS direct reference cannot enter wheel metadata because PyPI rejects it.# diffusers dropped 3.9 in 0.37, and we still support it (requires-python >= 3.9),# so the floor is conditional: pinning it outright leaves pip no candidate at all# on 3.9 and the whole extra becomes unresolvable.diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.pyindex 614356e0823..9919f801b30 100644--- a/studio/backend/core/inference/diffusion.py+++ b/studio/backend/core/inference/diffusion.py@@ -346,7 +346,7 @@ def resolve_local_single_file(model_path: str) -> Optional[str]:return checkpoints[0] if len(checkpoints) == 1 else None-def _decode_b64_image(data: str, *, mode: str = "RGB") -> Any:+def decode_b64_image(data: str, *, mode: str = "RGB") -> Any:"""Decode a base64 (optionally ``data:`` URL) image string to a PIL image.The image-conditioned workflows (img2img / inpaint / edit) transport the input@@ -4309,17 +4309,17 @@ class DiffusionBackend:"support masks (mask_image).")workflow = "edit"- init_pil = _decode_b64_image(init_image, mode = "RGB")+ init_pil = decode_b64_image(init_image, mode = "RGB")elif mask_image is not None and init_image is not None:workflow = "inpaint"pipe = self._workflow_pipe(state, state.family.inpaint_pipeline_class, workflow)- init_pil = _decode_b64_image(init_image, mode = "RGB")- mask_pil = _decode_b64_image(mask_image, mode = "L")+ init_pil = decode_b64_image(init_image, mode = "RGB")+ mask_pil = decode_b64_image(mask_image, mode = "L")elif init_image is not None and upscale is not None and upscale > 1.0:# Upscale (hires fix): enlarge with Lanczos, then re-run img2img at low strength to add detail.workflow = "upscale"pipe = self._workflow_pipe(state, state.family.img2img_pipeline_class, workflow)- init_pil = _decode_b64_image(init_image, mode = "RGB")+ init_pil = decode_b64_image(init_image, mode = "RGB")iw, ih = init_pil.size# Cap the factor, then the absolute output (longest side 2048); round to a multiple of 16 (VAE downsample + patch).factor = max(1.0, min(float(upscale), 4.0))@@ -4341,15 +4341,15 @@ class DiffusionBackend:elif getattr(state.family, "reference", False) and init_image is not None:# FLUX.2 reference conditioning: the loaded pipe takes the reference via `image` and generates at the REQUESTED size.workflow = "reference"- init_pil = _decode_b64_image(init_image, mode = "RGB")+ init_pil = decode_b64_image(init_image, mode = "RGB")# Additional references (FLUX.2 combines a list); capped to bound VRAM.ref_extra = [- _decode_b64_image(x, mode = "RGB") for x in (reference_images or [])[:3]+ decode_b64_image(x, mode = "RGB") for x in (reference_images or [])[:3]]elif init_image is not None:workflow = "img2img"pipe = self._workflow_pipe(state, state.family.img2img_pipeline_class, workflow)- init_pil = _decode_b64_image(init_image, mode = "RGB")+ init_pil = decode_b64_image(init_image, mode = "RGB")else:workflow = "txt2img"@@ -4381,7 +4381,7 @@ class DiffusionBackend:"ControlNet pipeline; not GGUF-via-diffusers or torchao fp8/int8).")# Decode + preprocess the control image FIRST so a bad image 400s before any CN download, at the OUTPUT size.- src = _decode_b64_image(cn_image_b64, mode = "RGB")+ src = decode_b64_image(cn_image_b64, mode = "RGB")control_pil = diffusion_controlnet.preprocess_control(src, cn_type).resize((width, height), Image.LANCZOS)diff --git a/studio/backend/core/inference/diffusion_prequant.py b/studio/backend/core/inference/diffusion_prequant.pyindex b8e348d2520..fd35d732176 100644--- a/studio/backend/core/inference/diffusion_prequant.py+++ b/studio/backend/core/inference/diffusion_prequant.py@@ -125,6 +125,10 @@ def resolve_prequant_source(Priority: (1) explicit local ``path_override``; (2) the family's hosted repo for``scheme`` (variant-specific when ``base_repo`` names a base with its own bakedcheckpoint); (3) None -> no pre-quant, caller quantises dense. Pure: no IO, no torch.++ Both names are repo-ROOT names. Every hosted prequant repo, image and video alike, keeps its+ checkpoints at the root, so there is no directory to prepend; a repo that nested them would+ 404 on the primary AND on the fallback and the load would silently fall back to dense."""override = (path_override or "").strip()if override:@@ -308,6 +312,7 @@ def load_prequantized_transformer(min_features: Optional[int] = None,fast_accum: Optional[bool] = None,cache_dir: Optional[str] = None,+ prepare_model: Optional[Any] = None,logger: Any = None,) -> Optional[Any]:"""Load the pre-quantized transformer described by ``source`` onto ``device``.@@ -316,6 +321,14 @@ def load_prequantized_transformer(lands under huggingface_hub's import-time constant, so a mid-session cache change re-downloadsinto a root Studio no longer reads.+ ``prepare_model`` (optional) is called as ``prepare_model(transformer, metadata)`` on the+ freshly built skeleton, AFTER ``from_config`` and BEFORE ``load_state_dict``. That window is+ the only one where a family can reshape the module to match how the checkpoint was baked (a+ swapped submodule, a patched attention class): earlier there is no module, and later+ ``strict=True`` has already rejected the mismatch. It gets the checkpoint's own metadata so it+ can key on what was baked rather than on today's defaults. A raising callback falls out to the+ outer handler below, i.e. a warning and a dense fallback, never a failed load.+Returns the placed transformer, or None on any problem (missing / mismatched /unreadable checkpoint, or unsupported meta-init) so the caller falls back todense-quantise. Best-effort: never raises for an unavailable artifact.@@ -355,16 +368,33 @@ def load_prequantized_transformer(config = _load_transformer_config(transformer_cls, base, hf_token, cache_dir, path)from accelerate import init_empty_weights+ metadata = ckpt.get("metadata") or {}with init_empty_weights():transformer = transformer_cls.from_config(config)+ if prepare_model is not None:+ prepare_model(transformer, metadata)# assign=True swaps in the loaded tensors instead of copying into meta (a no-op); strict=True since the saved dict is the full state dict of the same class.transformer.load_state_dict(state_dict, strict = True, assign = True)if _has_meta_tensors(transformer):# Non-persistent buffers (built in __init__, absent from the state dict) stay on meta. Rebuild on CPU so they hold real values, then re-assign the quantized weights; dense bf16 never reaches the GPU.transformer = transformer_cls.from_config(config)+ # The retry REPLACES the module, so the hook has to run again: skipping it here would+ # load the same state dict into a differently shaped model, and this branch is the one+ # families with non-persistent buffers always take -- the mismatch would be the norm,+ # not the corner case, and strict=True would surface it as a bare key error.+ if prepare_model is not None:+ prepare_model(transformer, metadata)transformer.load_state_dict(state_dict, strict = True, assign = True)transformer = transformer.to(device)+ # Same small-M row padding the runtime quantise path applies, and for the same reason: a+ # checkpoint built under the current exclusion set QUANTISES the family's small-M linears,+ # so without the wrappers they would raise inside _int_mm the moment the compiled scope+ # reaches them. After load_state_dict, since wrapping reparents the Linears; after .to()+ # so the granularity probe reads the device tensors the GEMM will actually see.+ from .diffusion_transformer_quant import apply_small_m_padding++ apply_small_m_padding(transformer, scheme, metadata.get("family"), logger = logger)# from_config starts in TRAIN mode while the dense/GGUF paths use from_pretrained (eval()'d). Match it so train/eval-sensitive layers cannot make prequant inference diverge.try:transformer.eval()@@ -703,6 +733,60 @@ def _same_base_model(a: str, b: str) -> bool:return a == b or _tail(a) == _tail(b)+def pin_prequantized_module(+ manager: Any,+ module: Any,+ device: Any,+ *,+ logger: Any = None,+) -> bool:+ """Keep a pre-quantized module resident on ``device``, out of a ComponentsManager's rotation.++ ``ComponentsManager.enable_auto_cpu_offload`` parks every component on the CPU and moves each+ one onto the accelerator inside its own ``pre_forward``, i.e. from within the block that is+ already executing. A torchao-quantized module does not survive that move: the device change+ reaches ``return_and_correct_aliasing``, which tries to alias a CPU storage to an accelerator+ tensor and raises ``Attempted to set the storage of a tensor on device "cuda:0" to a storage+ on different device "cpu"``, and MiniMax-H3's denoise loop dies on its first step. Moving the+ same module at load time, outside any executing block, works -- so the fix is to place it once+ here and take it out of the rotation rather than to move it per forward.++ That is also what a pre-quantized denoiser is for: the hosted H3 checkpoint is ~20 GB against+ 66.3 GB dense, so keeping it resident is the saving being spent. The other components keep+ their hooks, and the strategy sizes its decisions from live free memory, so the encoder and+ the VAEs still offload around it.++ Returns True when the module was pinned. Best-effort on the hook surgery: if the manager does+ not look the way this expects, the module is still placed on ``device`` and False is returned,+ which is the behaviour before pinning existed.+ """+ hooks = list(getattr(manager, "model_hooks", None) or ())+ target = next((hook for hook in hooks if getattr(hook, "model", None) is module), None)+ pinned = False+ if target is not None:+ try:+ # Drop the accelerate hook so no pre_forward/offload ever moves this module again ...+ target.remove()+ # ... and unlist it, so another component's pre_forward cannot pick it as the thing to+ # evict (which would move it to the CPU with no hook left to bring it back).+ for hook in hooks:+ others = getattr(getattr(hook, "hook", None), "other_hooks", None)+ if others:+ hook.hook.other_hooks = [item for item in others if item is not target]+ manager.model_hooks = [hook for hook in hooks if hook is not target]+ pinned = True+ except Exception as exc: # noqa: BLE001 -- placement below still has to happen+ _warn(logger, "pin:hook", exc)+ module.to(device)+ if logger is not None:+ logger.info(+ "diffusion.prequant: pre-quantized denoiser pinned on %s (offload rotation: %s)",+ device,+ "removed" if pinned else "unchanged",+ )+ return pinned++def _has_meta_tensors(module: Any) -> bool:"""True if any parameter or buffer is still on the meta device after loading."""from itertools import chaindiff --git a/studio/backend/core/inference/diffusion_quant_pad.py b/studio/backend/core/inference/diffusion_quant_pad.pynew file mode 100644index 00000000000..c49b6320173--- /dev/null+++ b/studio/backend/core/inference/diffusion_quant_pad.py@@ -0,0 +1,303 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Pad an int8 Linear's activation rows up to ``torch._int_mm``'s floor, instead of skipping it.++``aten::_int_mm`` asserts ``self.size(0) > 16``. torchao's EAGER path never trips this, because+``safe_int_mm`` checks the cuBLAS dimension constraints at runtime and falls back to a widened+``torch.matmul``; inductor lowers the same quantized linear straight to ``_int_mm``, so under+``torch.compile`` any quantized Linear invoked with a small activation row count raises++ RuntimeError: self.size(0) needs to be greater than 16, but got 10++Until now the fix was to leave those Linears dense bf16 (``_INT8_FAMILY_EXCLUDE_NAME_TOKENS`` in+``diffusion_transformer_quant``). That works, but it forfeits the weight-memory saving on a DiT's+whole conditioning front end. This is the alternative: pad the flattened row count up to+``pad_to``, run the GEMM, slice the result back. The module becomes compilable with no change to+the quantization config, and the rows the caller asked for are returned BITWISE unchanged.++Two properties make the padding exact rather than approximately exact, and both are load-bearing:++ * The pad rows REPLICATE row 0 rather than being zeros. An all-zero row has amax 0, hence+ scale 0, hence a division by zero in the activation quantizer. That NaN would stay confined+ to a row that is then discarded, but replication costs the same and keeps the intermediate+ finite -- and finite intermediates are what let the equality be checked at all.+ * The activation scale is PER ROW (torchao quantizes the activations of+ ``Int8DynamicActivationInt8WeightConfig`` with ``_int8_symm_per_token_...``), so each kept+ row's scale is computed from that row alone and extra rows cannot perturb it. Replicating+ row 0 happens to leave a per-TENSOR amax unchanged too, so the two properties overlap for+ that particular granularity -- but a granularity calibrated on anything other than a plain+ amax (a percentile, a mean, a running observer) would shift under duplicated rows and+ silently change every output. ``wrap_small_m_linears`` therefore refuses to wrap a quantized+ Linear whose activation granularity it cannot prove is per row, and RAISES rather than+ quietly leaving it unwrapped: a half-padded transformer is the one outcome worse than either+ end state, since it compiles on the modules that were wrapped and crashes on the rest.++Ordering invariant: wrapping REPARENTS the Linear, so it must happen AFTER a state dict is+loaded and BEFORE nothing in particular. The offline prequant builder+(``scripts/build_prequant_checkpoint.py``) drives ``quantize_`` directly and saves the state+dict, so it never sees a wrapper. As a second line of defence ``PadToMinM`` is state-dict+TRANSPARENT: it saves and loads its inner Linear's tensors under the wrapper's own prefix, so a+checkpoint written from a wrapped transformer still names ``context_embedder.weight`` rather+than ``context_embedder.inner.weight`` and stays loadable by an unwrapped tree.+"""++from __future__ import annotations++from typing import Any, Iterable, Optional++import torch+from torch import nn++# ``_int_mm`` wants strictly more than 16 rows.+INT_MM_MIN_M = 17++# Pad to a warp-friendly constant rather than to exactly INT_MM_MIN_M. Two reasons: 32 tiles+# better than 17, and it pins ONE compiled shape for every activation below it, so prompts of+# differing token counts (H3's seven eval prompts run at M = 10..19) do not each trigger their+# own inductor recompile.+DEFAULT_PAD_TO = 32+++def _weight_tensors(module: Any) -> tuple:+ """The weight objects a granularity/layout probe should look at, most specific first.++ ``quantize_`` assigns ``nn.Parameter(subclass_tensor)``, and Parameter.__new__ returns the+ SUBCLASS itself for a non-plain tensor, so the attributes normally sit on ``weight``. A build+ that produced a real Parameter wrapper instead would hide them one level down, hence ``.data``+ as a second look."""+ weight = getattr(module, "weight", None)+ if weight is None:+ return ()+ data = getattr(weight, "data", None)+ return (weight,) if data is None or data is weight else (weight, data)+++def is_quantized_linear(module: Any) -> bool:+ """True when ``module``'s weight is a torchao tensor subclass rather than a plain tensor.++ A dense Linear needs no padding (``F.linear`` has no row floor), so callers use this to skip+ one rather than to fail on it."""+ if not isinstance(module, nn.Linear):+ return False+ return any(hasattr(t, "__tensor_flatten__") for t in _weight_tensors(module))+++def activation_granularity_is_per_row(module: Any) -> Optional[bool]:+ """Whether ``module`` quantizes ACTIVATIONS per row. None when it cannot be determined.++ torchao spells this two ways depending on the tensor generation, and neither is a public+ accessor, so both are probed and an unrecognised layout answers None (the caller treats that+ as "unproven" and refuses, rather than assuming):++ * v2 tensors (``Float8Tensor`` and friends) carry ``act_quant_kwargs.granularity``, which+ is a ``PerRow`` instance for the per-row configs.+ * v1 ``LinearActivationQuantizedTensor`` (what ``Int8DynamicActivationInt8WeightConfig``+ produces today) carries the activation quantizer as ``input_quant_func``; the per-row+ one is ``_int8_symm_per_token_reduced_range_quant``. Note that this holds regardless of+ the config's ``granularity=`` argument, which sets the WEIGHT granularity -- so the+ function name is the only honest signal here.+ """+ for tensor in _weight_tensors(module):+ kwargs = getattr(tensor, "act_quant_kwargs", None)+ granularity = getattr(kwargs, "granularity", None)+ if granularity is not None:+ return type(granularity).__name__ in ("PerRow", "PerToken")++ quant_fn = getattr(tensor, "input_quant_func", None)+ name = getattr(quant_fn, "__name__", "") if quant_fn is not None else ""+ if name:+ lowered = name.lower()+ if "per_token" in lowered or "per_row" in lowered:+ return True+ if "per_tensor" in lowered:+ return False+ return None+++class PadToMinM(nn.Module):+ """Wrap ``inner`` so its GEMM never sees fewer than ``pad_to`` activation rows (>= ``min_m``).++ Shape-preserving: the caller's leading dims come back untouched. Only the FLATTENED row+ count is padded, and only when it is below ``pad_to``, so a module that is small on one call+ and large on the next pays nothing on the large one.+ """++ def __init__(+ self,+ inner: nn.Linear,+ min_m: int = INT_MM_MIN_M,+ pad_to: Optional[int] = None,+ ) -> None:+ super().__init__()+ self.inner = inner+ self.min_m = int(min_m)+ # pad_to may exceed min_m to buy tiling and shape stability; it may never be below it,+ # or the "padded" activation would still be under the floor it exists to clear.+ self.pad_to = max(int(pad_to or min_m), self.min_m)++ def forward(self, x: torch.Tensor) -> torch.Tensor:+ # Deliberately free of call counters or any other mutable int attribute: dynamo treats an+ # nn.Module's integer attributes as static and guards on their value, so a `+= 1` here+ # would force a recompile on EVERY call until the recompile limit is hit, at which point+ # the module silently drops back to eager. Instrumentation belongs outside.+ lead = x.shape[:-1]+ flat = x.reshape(-1, x.shape[-1])+ m = flat.shape[0]+ if m == 0:+ # No rows to project, and no row 0 to replicate from. torchao returns a zero-row+ # input UNPROJECTED (a quantized 1472 -> 2048 Linear maps [0, 1472] to [0, 1472]),+ # which then breaks a downstream width-sensitive add, so synthesise the empty result+ # at the right width instead of calling through.+ return x.new_empty((*lead, self.inner.out_features))+ if m < self.pad_to:+ # Everything below pad_to normalises to pad_to, not just what is below min_m. Clearing+ # the floor takes only the latter, but pinning ONE row count means one inductor graph+ # covers every prompt length in the range instead of one per length, and the extra+ # rows are free at these sizes (measured on H3's 13 modules: 1.57 ms padded from+ # M = 10 against 1.48 ms unpadded at M = 17, on a 2.4 s render).+ flat = torch.cat([flat, flat[:1].expand(self.pad_to - m, -1)], dim = 0)+ out = self.inner(flat)[:m]+ else:+ out = self.inner(flat)+ return out.reshape(*lead, out.shape[-1])++ def __getattr__(self, name: str) -> Any:+ # Callers reach THROUGH a Linear for weight / bias / in_features / out_features: diffusers'+ # attention processors read `to_q.weight.dtype`, and H3's blocks read+ # `context_embedder.weight`. Without this forward the wrapper is a drop-in only until the+ # first such access, which fails at render time rather than at wrap time.+ # nn.Module.__getattr__ runs first, so parameters, buffers and submodules registered on+ # the wrapper itself still win.+ try:+ return super().__getattr__(name)+ except AttributeError:+ if name == "inner":+ raise+ inner = self._modules.get("inner")+ if inner is None:+ raise+ return getattr(inner, name)++ def state_dict(self, *args: Any, **kwargs: Any) -> Any: # type: ignore[override]+ """Emit the inner Linear's tensors under the WRAPPER's prefix, hiding the ``inner.`` level.++ ``nn.Module.state_dict`` recurses by calling each child's ``state_dict``, so overriding it+ here is enough to keep a checkpoint written from a wrapped transformer loadable by an+ unwrapped one. The wrapper owns no tensors of its own, so there is nothing else to emit."""+ destination = kwargs.pop("destination", args[0] if args else None)+ prefix = kwargs.pop("prefix", args[1] if len(args) > 1 else "")+ keep_vars = kwargs.pop("keep_vars", args[2] if len(args) > 2 else False)+ if destination is None:+ # Top-level call (``wrapper.state_dict()``): let the inner module build the mapping.+ return self.inner.state_dict(prefix = prefix, keep_vars = keep_vars)+ self.inner.state_dict(destination = destination, prefix = prefix, keep_vars = keep_vars)+ return destination++ def _load_from_state_dict(+ self,+ state_dict: Any,+ prefix: str,+ local_metadata: Any,+ strict: bool,+ missing_keys: list,+ unexpected_keys: list,+ error_msgs: list,+ ) -> None:+ """Accept the unwrapped key names ``state_dict`` above writes, and hand them to ``inner``.++ Rewrites ``<prefix>weight`` to ``<prefix>inner.weight`` in place, before+ ``nn.Module.load_state_dict``'s recursion descends into ``inner``, so a state dict saved+ from an UNWRAPPED transformer loads into a wrapped one. Keys already carrying ``inner.``+ are left alone, so a dict written by an older build still loads."""+ for key in [k for k in state_dict if k.startswith(prefix)]:+ leaf = key[len(prefix) :]+ if not leaf or leaf.startswith("inner."):+ continue+ state_dict[prefix + "inner." + leaf] = state_dict.pop(key)+ super()._load_from_state_dict(+ state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs+ )++ def extra_repr(self) -> str:+ return f"min_m = {self.min_m}, pad_to = {self.pad_to}"+++def padding_is_bitwise_exact(+ module: Any,+ m: int,+ *,+ pad_to: int = DEFAULT_PAD_TO,+) -> bool:+ """Run ``module`` at ``m`` rows with and without padding and report bitwise equality.++ The direct form of the property the granularity check infers. Used by the tests; too costly+ for a per-module load-time gate on a 300-Linear DiT, and it cannot replace the granularity+ check anyway (replicating row 0 leaves a per-tensor AMAX unchanged, so a per-tensor amax+ scheme would pass this while a percentile-calibrated one would not)."""+ weight = getattr(module, "weight", None)+ device = getattr(weight, "device", "cpu")+ dtype = getattr(weight, "dtype", torch.bfloat16)+ x = torch.randn(m, module.in_features, device = device, dtype = dtype)+ with torch.no_grad():+ reference = module(x)+ padded = PadToMinM(module, pad_to = pad_to)(x)+ return bool(torch.equal(reference, padded))+++def wrap_small_m_linears(+ model: nn.Module,+ fqns: Iterable[str],+ *,+ min_m: int = INT_MM_MIN_M,+ pad_to: Optional[int] = DEFAULT_PAD_TO,+ require_per_row: bool = True,+) -> tuple[str, ...]:+ """Replace each Linear named in ``fqns`` with a ``PadToMinM`` around it; return those wrapped.++ Surgical by construction: only the fqns handed in are touched, so a DiT's hundreds of+ large-M block linears keep their unwrapped fast path and cannot pay for this.++ A Linear that is NOT quantized is skipped (dense ``F.linear`` has no row floor to clear), as+ is one already wrapped. A QUANTIZED Linear whose activation granularity cannot be proven per+ row raises ``RuntimeError``: see the module docstring for why silence is the wrong answer.+ """+ done: list[str] = []+ for fqn in sorted(set(fqns)):+ parent_name, _, leaf = fqn.rpartition(".")+ try:+ parent = model.get_submodule(parent_name) if parent_name else model+ module = getattr(parent, leaf)+ except AttributeError:+ # A family token that matches nothing on this checkpoint variant is not an error:+ # the pruned and dense H3 trees differ, and callers pass a name list, not a promise.+ continue+ # Skips a dense Linear (``F.linear`` has no row floor to clear, and there is no+ # granularity to prove) and, by the same gate, an already-wrapped one: ``PadToMinM`` is+ # not an ``nn.Linear``, so re-wrapping cannot nest the padding and double the row count.+ if not is_quantized_linear(module):+ continue+ if require_per_row and activation_granularity_is_per_row(module) is not True:+ raise RuntimeError(+ f"{fqn}: refusing to pad a quantized Linear whose activation granularity is not "+ f"provably per row. Padding replicates row 0, which is exact only when each "+ f"kept row's scale is computed from that row alone; under a calibrated or "+ f"per-tensor activation scale it would silently change every output."+ )+ setattr(parent, leaf, PadToMinM(module, min_m = min_m, pad_to = pad_to))+ done.append(fqn)+ return tuple(done)+++def matching_linear_fqns(model: nn.Module, name_tokens: Iterable[str]) -> tuple[str, ...]:+ """Every quantized-Linear fqn in ``model`` containing one of ``name_tokens`` (substring,+ case-insensitive) -- the same matching rule ``make_filter_fn`` uses for exclusions, so the+ pad list and the exclude list are read the same way."""+ tokens = tuple(t.lower() for t in name_tokens if t)+ if not tokens:+ return ()+ return tuple(+ fqn+ for fqn, module in model.named_modules()+ if is_quantized_linear(module) and any(t in fqn.lower() for t in tokens)+ )diff --git a/studio/backend/core/inference/diffusion_transformer_quant.py b/studio/backend/core/inference/diffusion_transformer_quant.pyindex 8aa02ee7a97..84579ecc4a5 100644--- a/studio/backend/core/inference/diffusion_transformer_quant.py+++ b/studio/backend/core/inference/diffusion_transformer_quant.py@@ -91,6 +91,22 @@ _HUNYUAN15_INT8_EXCLUDES = ("to_add_out","ff_context",)+# MiniMax-H3 is the same small-M story with one extra trap. Its adaLN projection is named+# ``adaln_proj``, which no token in _INT8_EXCLUDE_NAME_TOKENS matches: "norm" is the closest and it+# does not appear in the name. On the DENSE checkpoint that projection is Linear(2688 -> 96768), so+# it clears min_features = 512 and gets quantized, then runs at M = 1 and raises+# ``self.size(0) needs to be greater than 16, but got 1`` at the first denoise. Measured: the+# offline builder happily bakes it, and torch.compile then dies on that module.+#+# The pruned-modulation form hides the bug rather than fixing it: there adaln_proj is+# Linear(8 -> 96768), which falls under min_features and is skipped for free (verified on the+# fl2va_pruned build: the filter rejects all 51 of them for min_features, in_features = 8). So the+# exclusion is what makes the DENSE path correct, and is a no-op on the pruned one.+#+# H3's OTHER small-M linears -- context_embedder and the two token_refiner blocks, 13 in total --+# used to be excluded here for the same reason. They are not any more: they are padded instead,+# see _INT8_FAMILY_PAD_NAME_TOKENS below.+_MINIMAX_H3_INT8_EXCLUDES = ("adaln_proj",)# LTX-2 is audiovisual: every block carries an audio-side stream (audio_attn1 / audio_attn2 /# audio_ff, fed by audio_proj_in) plus the a2v / v2a cross attentions. A video-only run feeds a# MINIMAL audio stream -- one token for a still -- so those linears run at M = 1, under the same@@ -110,11 +126,76 @@ _INT8_FAMILY_EXCLUDE_NAME_TOKENS: dict[str, tuple[str, ...]] = {"qwen-image-edit": _QWENIMAGE_INT8_EXCLUDES, # same DiT class + unpadded text stream"hunyuanvideo-1.5": _HUNYUAN15_INT8_EXCLUDES,"hunyuanvideo-1.5-720p": _HUNYUAN15_INT8_EXCLUDES,+ "minimax-h3": _MINIMAX_H3_INT8_EXCLUDES,"ltx-2": _LTX2_INT8_EXCLUDES,"ltx-2.3": _LTX2_INT8_EXCLUDES, # same audiovisual DiT}+# int8 PER-FAMILY row PADDING, the alternative to excluding a small-M Linear. ``_int_mm``'s floor is+# a GEMM shape constraint, not a numerical one: padding the activation up to 32 rows, running the+# matmul and slicing the result back returns the caller's rows BITWISE unchanged (torchao's int8+# dynamic path scales activations per row, so the pad rows cannot reach them -- see+# diffusion_quant_pad for why that is asserted rather than assumed). So a Linear that would have+# been left dense can be quantized after all, and its weights halve.+#+# On MiniMax-H3 that is context_embedder plus the two token_refiner blocks: 13 Linears, 798 M+# parameters, 0.80 GB of bf16 weights, 3.9% of the whole int8 checkpoint. Measured on B200,+# 640x384 x 124 frames (see h3_quant/README_int8.md for the paired numbers).+#+# Scoped to minimax-h3 deliberately. qwen-image, qwen-image-edit and hunyuanvideo-1.5 have the same+# small-M shape and could adopt this, but each has a PUBLISHED int8 prequant checkpoint whose+# metadata bakes the current exclusion set, and _validate_checkpoint compares that set against+# exclude_tokens_for_scheme: changing it invalidates those artifacts, so they move only together+# with a rebuild and republish of each.+_MINIMAX_H3_INT8_PAD_TOKENS = ("context_embedder", "token_refiner")+_INT8_FAMILY_PAD_NAME_TOKENS: dict[str, tuple[str, ...]] = {+ "minimax-h3": _MINIMAX_H3_INT8_PAD_TOKENS,+}+++def pad_tokens_for_scheme(scheme: str, family: Optional[str] = None) -> tuple[str, ...]:+ """Name tokens whose quantized Linears get their activation rows padded to ``_int_mm``'s+ floor rather than being left dense. int8 only (no other scheme has a row floor), and+ per-family. Disjoint from ``exclude_tokens_for_scheme`` by construction: an excluded Linear+ is never quantized, so there is nothing to pad."""+ if scheme != TQ_INT8:+ return ()+ return _INT8_FAMILY_PAD_NAME_TOKENS.get(str(family or "").strip().lower(), ())+++def apply_small_m_padding(+ transformer: Any,+ scheme: str,+ family: Optional[str] = None,+ *,+ logger: Any = None,+) -> tuple[str, ...]:+ """Wrap this family's small-M quantized Linears so their GEMM clears ``_int_mm``'s row floor.++ Call AFTER the weights are quantized and in place -- ``quantize_`` on the runtime path, the+ prequant ``load_state_dict`` on the hosted one -- because it reparents the Linears. Returns+ the fqns wrapped, empty for a family with no pad list.++ RAISES if a Linear that should be padded cannot be proven safe to pad. A half-padded+ transformer compiles on the modules that were wrapped and crashes on the ones that were not,+ which is worse than either end state, so the caller must treat this as a failed quantise."""+ tokens = pad_tokens_for_scheme(scheme, family)+ if not tokens:+ return ()+ from .diffusion_quant_pad import matching_linear_fqns, wrap_small_m_linears++ wrapped = wrap_small_m_linears(transformer, matching_linear_fqns(transformer, tokens))+ if wrapped and logger is not None:+ logger.info(+ "diffusion.transformer_quant: padded %d small-M %s linears on %s",+ len(wrapped),+ scheme,+ family,+ )+ return wrapped++def exclude_tokens_for_scheme(scheme: str, family: Optional[str] = None) -> tuple[str, ...]:"""Name tokens to exclude from quantisation for ``scheme`` (optionally family-specific).int8 (M>16) skips the M=1 modulation / conditioning-embedder projections@@ -713,6 +794,10 @@ def quantize_transformer(require_divisible = divisible,),)+ # Pad this family's small-M linears now that the weights are quantized and in place. Not+ # best-effort: a raise here means the transformer is quantized but not safely compilable,+ # so it falls into the except below and the caller loads GGUF.+ apply_small_m_padding(transformer, scheme, family, logger = logger)# Runtime-only diagnostic marker.try:transformer._unsloth_runtime_quant = schemediff --git a/studio/backend/core/inference/sd_cpp_args.py b/studio/backend/core/inference/sd_cpp_args.pyindex 39d657e30a0..1d96757f7ca 100644--- a/studio/backend/core/inference/sd_cpp_args.py+++ b/studio/backend/core/inference/sd_cpp_args.py@@ -49,10 +49,12 @@ class SdCppModelFiles:diffusion_model: strvae: Optional[str] = None+ audio_vae: Optional[str] = Noneclip_l: Optional[str] = Noneclip_g: Optional[str] = Nonet5xxl: Optional[str] = Nonellm: Optional[str] = None+ llm_vision: Optional[str] = Noneqwen2vl: Optional[str] = None@@ -86,6 +88,32 @@ class SdCppGenParams:lora_apply_mode: Optional[str] = None+@dataclass(frozen = True)+class SdCppVideoGenParams:+ """Video generation parameters for sd-cli's ``vid_gen`` mode.++ Keyframes and Ref2VA references use separate denoiser partitions. Reference videos are+ frame directories, and their WAV soundtracks are paired by index.+ """++ prompt: str+ width: int+ height: int+ num_frames: int+ fps: int = 24+ steps: Optional[int] = None+ cfg_scale: float = 1.0+ seed: Optional[int] = None+ init_img: Optional[str] = None+ end_img: Optional[str] = None+ ref_images: tuple[str, ...] = ()+ ref_videos: tuple[str, ...] = ()+ ref_video_audios: tuple[str, ...] = ()+ ref_audios: tuple[str, ...] = ()+ # sd.cpp exposes only the video schedule shift.+ flow_shift: Optional[float] = None++@dataclass(frozen = True)class SdCppUpscaleParams:"""Inputs for sd-cli's ESRGAN upscale mode (a separate run mode)."""@@ -165,12 +193,17 @@ def offload_flags(*,vae_tiling: bool = False,diffusion_fa: bool = False,+ vae_on_cpu: bool = True,) -> list[str]:"""Translate a diffusers memory policy into sd-cli offload flags.``none``: resident, no flags. ``group``: stream the model (``--offload-to-cpu``) + flashattention. ``model`` / ``sequential``: offload everything, also CLIP/VAE to CPU + VAE tiling.``vae_tiling`` / ``diffusion_fa`` force those flags on regardless of policy.++ ``vae_on_cpu = False`` drops only ``--vae-on-cpu`` from the offload policies. A family whose+ VAE cannot run on the CPU path still wants everything else the policy asks for, and that flag+ is the smallest of the three savings: the denoiser is what dominates."""flags: list[str] = []fa = diffusion_fa@@ -180,7 +213,8 @@ def offload_flags(fa = Trueif policy in (OFFLOAD_MODEL, OFFLOAD_SEQUENTIAL):flags.append("--clip-on-cpu")- flags.append("--vae-on-cpu")+ if vae_on_cpu:+ flags.append("--vae-on-cpu")tile = Trueif fa:flags.append("--diffusion-fa")@@ -287,6 +321,101 @@ def build_sd_cpp_command(return cmd+def build_sd_cpp_video_command(+ binary: str,+ files: SdCppModelFiles,+ params: SdCppVideoGenParams,+ *,+ output_path: str,+ offload: Optional[list[str]] = None,+ verbose: bool = False,+ extra_args: Optional[list[str]] = None,+) -> list[str]:+ """Build one MiniMax-H3 audio-video ``sd-cli`` command (text-only, or keyframe-conditioned)."""+ if not files.diffusion_model:+ raise ValueError("diffusion_model path is required")+ if not files.vae:+ raise ValueError("MiniMax-H3 video generation requires a video VAE")+ if not files.llm:+ raise ValueError("MiniMax-H3 video generation requires its Qwen3-VL text encoder")+ if not (params.prompt or "").strip():+ raise ValueError("prompt is required")+ if params.width <= 0 or params.height <= 0 or params.num_frames <= 0:+ raise ValueError("width, height, and num_frames must be positive")++ cmd = [+ binary,+ "--mode",+ "vid_gen",+ "--diffusion-model",+ files.diffusion_model,+ "--vae",+ files.vae,+ ]+ if files.audio_vae:+ cmd += ["--audio-vae", files.audio_vae]+ cmd += ["--llm", files.llm]+ if files.llm_vision:+ cmd += ["--llm_vision", files.llm_vision]+ # Reject incompatible partitions before loading the model.+ if (params.init_img or params.end_img) and (+ params.ref_images or params.ref_videos or params.ref_audios+ ):+ raise ValueError(+ "MiniMax-H3 keyframes and references cannot be combined: they run against "+ "different denoiser partitions."+ )+ if len(params.ref_video_audios) > len(params.ref_videos):+ raise ValueError("each reference video soundtrack needs a reference video to pair with")+ # Keyframes before the sampling flags, matching the img_gen builder's ordering.+ if params.init_img:+ cmd += ["--init-img", params.init_img]+ if params.end_img:+ cmd += ["--end-img", params.end_img]+ # Preserve the model's image, video, soundtrack, then standalone-audio order.+ for ref in params.ref_images:+ cmd += ["--ref-image", ref]+ for ref in params.ref_videos:+ cmd += ["--ref-video", ref]+ for ref in params.ref_video_audios:+ cmd += ["--ref-video-audio", ref]+ for ref in params.ref_audios:+ cmd += ["--ref-audio", ref]+ cmd += [+ "--prompt",+ params.prompt,+ "--cfg-scale",+ _fmt_float(params.cfg_scale),+ "--width",+ str(int(params.width)),+ "--height",+ str(int(params.height)),+ "--rng",+ "cpu",+ "--fps",+ str(int(params.fps)),+ "--video-frames",+ str(int(params.num_frames)),+ ]+ if params.steps is not None:+ cmd += ["--steps", str(int(params.steps))]+ if params.flow_shift is not None:+ cmd += ["--flow-shift", _fmt_float(params.flow_shift)]+ if params.seed is not None:+ cmd += ["--seed", str(int(params.seed))]+ cmd += ["--output", output_path]+ offload = list(offload or [])+ if offload:+ cmd += offload+ cmd += [f for f in metal_text_encoder_flags() if f not in offload]+ if verbose:+ cmd.append("-v")+ for flag in list(extra_args or []):+ if flag not in cmd:+ cmd.append(flag)+ return cmd++def build_sd_cpp_upscale_command(binary: str,params: SdCppUpscaleParams,diff --git a/studio/backend/core/inference/sd_cpp_backend.py b/studio/backend/core/inference/sd_cpp_backend.pyindex cd3c66c752e..4c8c9fb47cf 100644--- a/studio/backend/core/inference/sd_cpp_backend.py+++ b/studio/backend/core/inference/sd_cpp_backend.py@@ -161,6 +161,122 @@ def _usable_or_discard_managed(binary: str) -> bool:return False+def _sd_cpp_probe_output(binary: str, *args: str) -> Optional[str]:+ """Combined stdout+stderr of ``binary <args>``, or None when it could not be read.++ ``sd-cli`` prints ``--help`` on stdout and exits 0, and logs errors on stderr, so both+ streams are folded together. None means "could not tell" -- cannot exec, timed out, or a+ non-zero exit (which is how an older build rejects a flag it does not know) -- and is never+ evidence that a feature is absent, so every caller has to stay conservative on it."""+ import subprocess++ try:+ proc = subprocess.run(+ [binary, *args],+ capture_output = True,+ text = True,+ encoding = "utf-8",+ errors = "replace",+ timeout = 20,+ env = runtime_env(binary),+ **windows_hidden_subprocess_kwargs(),+ )+ except Exception: # noqa: BLE001 -- cannot exec / timeout: treated as "cannot tell"+ return None+ if proc.returncode != 0:+ return None+ return (proc.stdout or "") + (proc.stderr or "")+++# The ``--help`` token that marks a build carrying MiniMax-H3 support. Upstream added the mode's+# own options (``--ref-video`` / ``--ref-audio``, and the "MiniMax-H3 Ref2VA" wording on+# ``--ref-image``) in the very commit that added H3 upstream, released as+# master-812-ea7f0c8, so their presence is exactly the capability signal. ``--version`` cannot+# stand in for it: the release prebuilts are built without a .git dir and answer "stable-diffusion.cpp+# version unknown, commit unknown", so there is no tag to compare.+_H3_HELP_MARKER = "--ref-video"+++def sd_cpp_supports_minimax_h3(binary: str) -> bool:+ """True unless ``binary``'s ``--help`` demonstrably predates MiniMax-H3 support.++ Conservative by design: an unreadable ``--help`` returns True, because the load's existing+ ``SdCppEngine.version()`` gate already refuses a binary that cannot run, and guessing "no H3"+ from a probe failure would take native video away from a working build."""+ text = _sd_cpp_probe_output(binary, "--help")+ if text is None:+ return True+ return _H3_HELP_MARKER in text+++def sd_cpp_lists_accelerator_device(binary: Optional[str]) -> bool:+ """True unless ``binary`` demonstrably enumerates the CPU ggml device and nothing else.++ ``sd-cli --list-devices`` prints one ``name<TAB>description`` line per available ggml backend+ device and exits 0, a format its own help text documents, so a CPU-only prebuilt answers+ ``CPU\t<cpu model>`` while a CUDA / ROCm / Vulkan / Metal build adds its own device. That is the+ only way to tell the two apart after the fact: ``find_sd_cpp_binary`` returns whatever is+ installed regardless of which accelerator it was asked for.++ Conservative everywhere else -- unreadable output, or an older build that rejects the flag --+ because neither is evidence that the accelerator is missing. A missing binary is False: there+ is nothing to run on the GPU at all."""+ if not binary:+ return False+ text = _sd_cpp_probe_output(binary, "--list-devices")+ if text is None:+ return True+ names = [line.split("\t", 1)[0].strip() for line in text.splitlines() if "\t" in line]+ if not names:+ return True+ return any(name.upper() != "CPU" for name in names)+++def ensure_h3_sd_cpp_binary(+ *, allow_install: bool = True, accelerator: str = "cpu"+) -> Optional[str]:+ """``ensure_sd_cpp_binary`` for the MiniMax-H3 path, which additionally requires the binary to+ ADVERTISE H3 support.++ ``ensure_sd_cpp_binary`` hands back whatever ``find_sd_cpp_binary`` locates and only probes+ runnability, so an install that predates H3 (an upgraded Studio still carrying an older managed+ sd-cli) is returned unchanged, the H3 load reports ready on it, and the first generation fails+ only AFTER the multi-tens-of-GB bundle has downloaded. Only this path is stricter: image+ generation must keep working on any user-supplied build.++ A stale copy we own is deleted so the installer puts the pinned prebuilt back; a user's own+ build is left alone and the load fails with a message naming it, the same ownership split+ ``_usable_or_discard_managed`` makes. Returns None when no H3-capable binary can be produced.+ """+ binary = ensure_sd_cpp_binary(allow_install = allow_install, accelerator = accelerator)+ if not binary or sd_cpp_supports_minimax_h3(binary):+ return binary+ if not is_managed_binary(binary):+ raise RuntimeError(+ f"The stable-diffusion.cpp build at {binary} predates MiniMax-H3 support (its --help "+ f"does not list the H3 options), so generation would fail after the whole H3 bundle "+ f"has downloaded. Point SD_CLI_PATH / UNSLOTH_SD_CPP_PATH at a build from "+ f"master-812-ea7f0c8 or newer, or remove that directory so Studio installs the "+ f"pinned prebuilt."+ )+ if not allow_install:+ # Ours, but replacing it is exactly what auto-install is switched off for.+ logger.warning("managed sd.cpp binary %s predates MiniMax-H3 support", binary)+ return None+ logger.warning(+ "managed sd.cpp binary %s predates MiniMax-H3 support; removing it so it reinstalls", binary+ )+ try:+ Path(binary).unlink()+ except OSError as exc:+ logger.warning("could not remove the stale managed sd.cpp binary %s: %s", binary, exc)+ return None+ binary = ensure_sd_cpp_binary(allow_install = True, accelerator = accelerator)+ if binary and not sd_cpp_supports_minimax_h3(binary):+ return None+ return binary++def _installer_module():"""The installer module, importable from the backend's sys.path. None if unavailable."""import sysdiff --git a/studio/backend/core/inference/sd_cpp_engine.py b/studio/backend/core/inference/sd_cpp_engine.pyindex 541c323aacd..28167083925 100644--- a/studio/backend/core/inference/sd_cpp_engine.py+++ b/studio/backend/core/inference/sd_cpp_engine.py@@ -13,9 +13,11 @@ heavy is reached only inside ``generate`` / ``version``, so import is free and tfrom __future__ import annotations+import codecsimport loggingimport osimport queue+import reimport shutilimport signalimport subprocess@@ -23,7 +25,7 @@ import sysimport threadingimport timefrom pathlib import Path-from typing import Callable, Optional+from typing import Callable, Iterator, Optionalfrom utils.process_lifetime import adopt_pid, child_popen_kwargs, forget_pidfrom utils.native_path_leases import child_env_without_native_path_secret@@ -31,8 +33,10 @@ from core.inference.sd_cpp_args import (SdCppGenParams,SdCppModelFiles,SdCppUpscaleParams,+ SdCppVideoGenParams,build_sd_cpp_command,build_sd_cpp_upscale_command,+ build_sd_cpp_video_command,native_speed_flags,)@@ -52,6 +56,91 @@ OWNER_MARKER = ".unsloth-studio-owned"NATIVE_GENERATION_TIMEOUT_S = 6 * 60 * 60.0+# sd-cli redraws its progress bar IN PLACE. Each redraw is one printf + fflush shaped+# "\r<bar> <step>/<steps> - <speed>\033[K", with a trailing newline only on the final step of a+# phase. So the carriage return LEADS the record and the erase-to-end-of-line CLOSES it.+_ANSI_ERASE = "\x1b[K"+# Any CSI escape (the erase above, plus colour runs some builds emit), stripped before a record+# reaches on_log / the error tail: an escape in the middle of a line corrupts both.+_ANSI_CSI_RE = re.compile(r"\x1b\[[0-9;?]*[ -/]*[@-~]")+# One read1() per redraw in practice; large enough that a burst of finished lines costs one read.+_READ_CHUNK = 4096+++def strip_ansi(text: str) -> str:+ """Drop CSI escape sequences (notably the ``\\033[K`` that closes every progress redraw)."""+ return _ANSI_CSI_RE.sub("", text)+++def split_progress_records(buf: str) -> tuple[list[str], str]:+ """Split raw sd-cli stdout into complete records plus the still-unterminated remainder.++ A record ends at a carriage return, a newline, OR a trailing erase-to-end-of-line. That last+ terminator is the point: an in-place redraw carries no newline, and its carriage return is at+ the FRONT of the *next* redraw, so keying only on CR/LF delivers every sampling step one step+ late (and the final one only once sampling is over). ``\\033[K`` closes the record sd-cli has+ already flushed, so the step is delivered when it happens.++ Returns records in order (still containing their escapes; call ``strip_ansi``) and whatever+ trailing text is not yet terminated, which the caller carries into the next chunk.+ """+ records: list[str] = []+ start = 0+ i = 0+ n = len(buf)+ while i < n:+ ch = buf[i]+ if ch == "\r" or ch == "\n":+ records.append(buf[start:i])+ # CRLF is one terminator, not two (Windows sd-cli builds).+ if ch == "\r" and i + 1 < n and buf[i + 1] == "\n":+ i += 1+ i += 1+ start = i+ continue+ if buf.startswith(_ANSI_ERASE, i):+ i += len(_ANSI_ERASE)+ records.append(buf[start:i])+ start = i+ continue+ i += 1+ return records, buf[start:]+++def iter_sd_cpp_records(stream) -> Iterator[str]:+ """Yield cleaned sd-cli output records from ``stream`` as soon as each is flushed.++ Reads the undecoded pipe via ``buffer.read1`` so a redraw that never sends a newline is not+ stuck behind a blocking readline, decoding incrementally so a multi-byte character split+ across two reads survives. Streams without a raw ``.buffer`` (test doubles, non-pipes) fall+ back to line iteration, which still splits on CR under universal newlines and so still+ reports progress, just one redraw behind.+ """+ raw = getattr(stream, "buffer", None)+ if raw is None or not hasattr(raw, "read1"):+ for line in stream:+ records, rest = split_progress_records(line)+ for rec in records:+ yield strip_ansi(rec)+ if rest:+ yield strip_ansi(rest)+ return+ decoder = codecs.getincrementaldecoder("utf-8")("replace")+ pending = ""+ while True:+ chunk = raw.read1(_READ_CHUNK)+ if not chunk:+ pending += decoder.decode(b"", final = True)+ break+ pending += decoder.decode(chunk)+ records, pending = split_progress_records(pending)+ for rec in records:+ yield strip_ansi(rec)+ # EOF: hand over any final line the child left unterminated.+ if pending:+ yield strip_ansi(pending)++class SdCppCancelled(RuntimeError):"""A generation cancelled via its ``cancel_event`` (unload / superseding load / arbitereviction). Distinct from a *failure* so the caller keeps cancellation semantics."""@@ -361,6 +450,39 @@ class SdCppEngine:cancel_event = cancel_event,)+ def generate_video(+ self,+ files: SdCppModelFiles,+ params: SdCppVideoGenParams,+ *,+ output_path: str,+ offload: Optional[list[str]] = None,+ verbose: bool = False,+ extra_args: Optional[list[str]] = None,+ timeout: Optional[float] = NATIVE_GENERATION_TIMEOUT_S,+ env: Optional[dict[str, str]] = None,+ on_log: Optional[Callable[[str], None]] = None,+ cancel_event: Optional[threading.Event] = None,+ ) -> Path:+ """Run one ``vid_gen`` generation and return its video container."""+ cmd = build_sd_cpp_video_command(+ self._require_binary(),+ files,+ params,+ output_path = str(self._prepare_out(output_path)),+ offload = offload,+ verbose = verbose,+ extra_args = extra_args,+ )+ return self._run(+ cmd,+ output_path,+ timeout = timeout,+ env = env,+ on_log = on_log,+ cancel_event = cancel_event,+ )+# ── internals ─────────────────────────────────────────────────────────────def _require_binary(self) -> str:@@ -417,14 +539,15 @@ class SdCppEngine:# would otherwise leave sd-cli holding VRAM with nothing able to find it.adopt_pid(proc.pid)# Drain stdout on a reader thread so the timeout holds even when the child hangs WITHOUT printing (a plain `for line in proc.stdout` blocks until EOF). Lines, then a None sentinel, go to a queue the main loop polls against a wall-clock deadline.+ # iter_sd_cpp_records also splits sd-cli's in-place progress redraws, which carry no newline of their own, so sampling progress reaches on_log while sampling is still running.tail: list[str] = []line_q: "queue.Queue[Optional[str]]" = queue.Queue()def _drain() -> None:try:assert proc.stdout is not None- for raw in proc.stdout:- line_q.put(raw.rstrip("\n"))+ for rec in iter_sd_cpp_records(proc.stdout):+ line_q.put(rec)finally:line_q.put(None)diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.pyindex dbd7a54fd4e..90abb48d395 100644--- a/studio/backend/core/inference/video.py+++ b/studio/backend/core/inference/video.py@@ -116,6 +116,22 @@ from .video_families import (snap_video_size,supported_video_family_names,validate_video_request_shape,+ video_family_prequant_repo,+ video_family_prequant_schemes,+)+from .video_minimax_h3 import (+ H3_ANCHOR_FIRST,+ H3_ANCHOR_LAST,+ H3_CANVAS_MAX_PIXELS,+ H3_CANVAS_SHORT_EDGE,+ H3_REF_SIZE_MATCH,+ H3_REF_SIZE_MAX,+ H3_TASK_REFERENCES,+ fit_h3_keyframe,+ fit_h3_reference_image,+ h3_canvas_for_aspect,+ h3_conditioning_mode,+ h3_transformer_task,)from utils.hardware import clear_gpu_cache@@ -139,6 +155,7 @@ _TRUSTED_NON_GGUF_VIDEO_REPOS = frozenset(# HunyuanVideo-1.5 community Diffusers repacks (tencent's own repo has no model_index.json)."hunyuanvideo-community/hunyuanvideo-1.5-diffusers-480p_t2v","hunyuanvideo-community/hunyuanvideo-1.5-diffusers-720p_t2v",+ "minimaxai/minimax-h3",})@@ -183,6 +200,14 @@ def assert_video_precision_available(return# One probe for both checks (it reads the live device).target = resolve_diffusion_device_target()+ # A modular-workflow family (MiniMax-H3) never reaches the memory plan the offload refusals+ # below reason about: load_pipeline hands it to _load_h3_modular_pipeline, which always uses+ # the ComponentsManager auto CPU offload and PINS a pre-quantized denoiser resident, so+ # 'balanced' / 'low_vram' do not put the quantised DiT under a Module.to() offload hook.+ # Refusing those picks here would 409 a combination that loads.+ forces_offload = not getattr(fam, "modular_workflow", None) and _memory_request_forces_offload(+ memory_mode, False+ )if pinned is not None and pinned != TQ_AUTO:reason = Noneif model_kind != "pipeline":@@ -192,7 +217,7 @@ def assert_video_precision_available()elif not dense_transformer_supported(target):reason = "this device cannot run a dense torchao quant (it needs a CUDA GPU in bf16)"- elif _memory_request_forces_offload(memory_mode, False):+ elif forces_offload:# balanced and low_vram name their offload policy without measuring anything, and# offload hooks move modules with Module.to(), which torchao tensors do not survive.# load_pipeline therefore skips the dense build and the strict refusal landed after@@ -239,9 +264,7 @@ def assert_video_precision_available("this device does not have the tensor cores that backend needs (a CUDA GPU in ""bf16, plus fp8 / int8 / NVFP4 support depending on the mode)")- elif te_quant_needs_resident_weights(te_effective) and _memory_request_forces_offload(- memory_mode, False- ):+ elif te_quant_needs_resident_weights(te_effective) and forces_offload:# Same fence on the encoder: the loader reports those modes unsupported once offload is# active, and by then the resident model is gone. Layerwise fp8 is a dtype cast.te_reason = (@@ -309,6 +332,34 @@ def _picked_gguf_arch(repo_id: str, gguf_filename: str) -> Optional[str]:return None+# Enough for a 15-second reference video after base64 decoding.+_MAX_REFERENCE_MEDIA_BYTES = 96 * 1024 * 1024+++def _decode_b64_media(data: Optional[str]) -> bytes:+ """Decode a base64 media payload, optionally wrapped in a data URL."""+ import base64+ import binascii++ raw = (data or "").strip()+ if not raw:+ raise ValueError("A reference was sent empty.")+ if raw.startswith("data:"):+ _, _, raw = raw.partition(",")+ try:+ blob = base64.b64decode(raw, validate = False)+ except (binascii.Error, ValueError) as exc:+ raise ValueError(f"Invalid base64 media data: {exc}") from exc+ if not blob:+ raise ValueError("A reference decoded to no data.")+ if len(blob) > _MAX_REFERENCE_MEDIA_BYTES:+ raise ValueError(+ f"A reference is too large ({len(blob) / 1e6:.0f} MB); the limit is "+ f"{_MAX_REFERENCE_MEDIA_BYTES / 1e6:.0f} MB."+ )+ return blob++class _VideoGenerationCancelled(Exception):"""Unwinds a denoise loop that has no cooperative interrupt (no step callback);generate() maps it to the VIDEO_CANCELLED_MSG sentinel the routes 409 on."""@@ -383,7 +434,10 @@ class _VideoLoadState:device: strdtype: strkind: str+ engine: str = "diffusers"gguf_filename: Optional[str] = None+ # Resident MiniMax-H3 denoiser partition, if any.+ h3_task: Optional[str] = Noneoffload_policy: str = "none"vae_tiling: bool = Truememory_mode: str = "auto"@@ -410,6 +464,9 @@ class _VideoLoadingState:base_repo: strexpected_bytes: Optional[int] = Noneerror: Optional[str] = None+ # Companion repos this load is ALSO pulling from, beyond repo_id / base_repo (the native H3+ # GGUF and component repos). Mirrors the image backend's _SdLoading.asset_repos.+ asset_repos: tuple[str, ...] = ()def _progress(phase: Optional[str], **extra: Any) -> dict[str, Any]:@@ -573,6 +630,7 @@ class VideoBackend:model_kind: Optional[str] = None,transformer_quant: Optional[str] = None,text_encoder_quant: Optional[str] = None,+ h3_task: Optional[str] = None,) -> VideoFamily:"""Cheap, network-free validation shared by the route and the load path."""kind = resolve_video_model_kind(gguf_filename, model_kind)@@ -589,10 +647,91 @@ class VideoBackend:f"{', '.join(supported_video_family_names())}. If this is a variant of one "f"of them, pass family_override with that family name.")- # Refuse a too-old diffusers here rather than deep in the load (LTX2Pipeline / HunyuanVideo15Pipeline are 0.39-only).- from .diffusion_families import assert_pipeline_class_available+ # ── modular-workflow refusals, before anything heavier.+ # Deliberately the FIRST thing after the family resolves: everything below reaches into+ # diffusers (assert_pipeline_class_available, the transformer_class probe), so a refusal+ # placed after them would be unreachable on any install whose diffusers cannot even be+ # imported -- and these two are exactly the picks that cost the most to discover late.+ if fam.modular_workflow and kind == "single_file":+ # A modular workflow has no single-file assembly: its components each load through+ # their own from_pretrained from the modular index, and nothing consumes a lone+ # .safetensors DiT. Today that only surfaces inside the loader, i.e. after ~98.7 GB+ # has downloaded AND after the resident pipeline was torn down to make room for it.+ gguf_hint = (+ f", or a .gguf checkpoint from '{fam.gguf_repo}' for a quantized single-file load"+ if fam.gguf_repo+ else ""+ )+ raise ValueError(+ f"'{fam.name}' cannot load from a single .safetensors checkpoint: it is assembled "+ f"by its Modular Diffusers workflow, which builds every component from a repo. "+ f"Load the diffusers pipeline repo '{fam.base_repo}' for the full bfloat16 "+ f"model{gguf_hint}."+ )+ if fam.modular_workflow and kind == "pipeline":+ # Same normaliser the load uses, so a malformed value raises the identical message it+ # would below and only a real scheme reaches the availability check.+ requested_scheme = normalize_transformer_quant(transformer_quant)+ # The base the modular load resolves for a pipeline kind IS repo_id, so a+ # variant-keyed checkpoint is judged against the one the load will ask for and+ # validation can never refuse a load that would have worked.+ quant_base = repo_id+ # "auto" is a request for the backend's own choice, not for a specific scheme, so it is+ # never refused: it simply stays on the released bfloat16 components.+ if requested_scheme is not None and requested_scheme != TQ_AUTO:+ # The hosted checkpoints are FL2VA denoisers. The two partitions share module+ # shapes and the same base model, so a Ref2VA load would install one, pass every+ # metadata check, and have load_components skip the real Ref2VA transformer --+ # generating from the wrong partition instead of failing. Refuse until a matching+ # checkpoint exists; there is no in-place quantise seam to fall back on.+ from .video_minimax_h3 import H3_TASK_REFERENCES+ if (h3_task or "").strip().lower() == H3_TASK_REFERENCES:+ raise ValueError(+ f"transformer_quant '{requested_scheme}' is unavailable for "+ f"'{fam.name}' reference video: the hosted pre-quantized checkpoints are "+ f"keyframe (fl2va) denoisers, and seeding one into the reference workflow "+ f"would generate from the wrong partition. Load reference video without "+ f"transformer_quant, or pick a keyframe task."+ )+ if video_family_prequant_repo(fam, requested_scheme, quant_base) is None:+ # There is no in-place quantise seam here: the workflow's own component loader+ # builds the denoiser, so a scheme without a hosted pre-quantized checkpoint+ # cannot be served at all, and letting it through would download ~98.7 GB of+ # dense weights and then silently ignore the request.+ available = video_family_prequant_schemes(fam)+ hint = (+ f"Use one of: {', '.join(available)}."+ if available+ else "Leave transformer_quant unset for this model."+ )+ raise ValueError(+ f"transformer_quant '{requested_scheme}' is unavailable for "+ f"'{fam.name}': its Modular Diffusers workflow builds the denoiser itself, "+ f"so only schemes with a hosted pre-quantized checkpoint can be applied "+ f"and the dense weights cannot be quantized in place. {hint}"+ )+ from .video_minimax_h3 import is_h3_native, validate_h3_transformer_filename- assert_pipeline_class_available(fam.pipeline_class, fam.name)+ if is_h3_native(fam, kind):+ validate_h3_transformer_filename(gguf_filename or "")+ # The GGUF filename and explicit task must name the same partition.+ picked = h3_transformer_task(gguf_filename or "")+ if h3_task and h3_task != picked:+ raise ValueError(+ f"'{Path(gguf_filename or '').name}' is the {picked} partition, but the "+ f"load asked for {h3_task}. Pick the matching checkpoint."+ )+ else:+ # Refuse a too-old diffusers here rather than deep in the load.+ from .diffusion_families import assert_pipeline_class_available+ assert_pipeline_class_available(fam.pipeline_class, fam.name)+ if fam.modular_workflow:+ import diffusers+ if not hasattr(diffusers, fam.transformer_class):+ raise ValueError(+ "MiniMax-H3 needs the Diffusers revision bundled with this Studio "+ "version. Reinstall Studio dependencies and retry."+ )if kind != "gguf" and not _is_trusted_video_repo(repo_id):raise ValueError(f"Non-GGUF video loads are limited to unsloth/* repos, the official "@@ -660,10 +799,17 @@ class VideoBackend:if kind == "pipeline":root = Path(repo_id).expanduser()# Gate on .exists() (not .is_dir()) so a local FILE picked as a pipeline is rejected too.- if root.exists() and not (root.is_dir() and (root / "model_index.json").is_file()):+ indexes = (+ ("model_index.json", "modular_model_index.json")+ if fam.modular_workflow+ else ("model_index.json",)+ )+ if root.exists() and not (+ root.is_dir() and any((root / name).is_file() for name in indexes)+ ):raise ValueError(f"Local pipeline path is not a diffusers directory "- f"(no model_index.json): {repo_id}"+ f"(no {' or '.join(indexes)}): {repo_id}")# Reject a malformed transformer_quant cheaply, before the handoff (pipeline-kind only, matching the image backend).normalize_transformer_quant(transformer_quant)@@ -690,6 +836,7 @@ class VideoBackend:transformer_quant: Optional[str] = None,text_encoder_quant: Optional[str] = None,model_kind: Optional[str] = None,+ h3_task: Optional[str] = None,) -> dict[str, Any]:"""Validate, then run the (slow) load on a daemon thread. Returns at once."""hf_token = (hf_token.strip() if isinstance(hf_token, str) else hf_token) or None@@ -701,6 +848,7 @@ class VideoBackend:model_kind = model_kind,transformer_quant = transformer_quant,text_encoder_quant = text_encoder_quant,+ h3_task = h3_task,)# Refuse an EXPLICIT precision this host can never honor BEFORE the load starts, so the# route answers 409 with the reason instead of evicting the resident model and pulling@@ -740,6 +888,7 @@ class VideoBackend:transformer_quant = transformer_quant,text_encoder_quant = text_encoder_quant,model_kind = model_kind,+ h3_task = h3_task,_load_token = token,_cancel_event = cancel_event,),@@ -756,6 +905,19 @@ class VideoBackend:kwargs["repo_id"], kwargs.get("gguf_filename"), kwargs.get("family_override"))kind = resolve_video_model_kind(kwargs.get("gguf_filename"), kwargs.get("model_kind"))+ from .video_minimax_h3 import is_h3_native++ if is_h3_native(fam, kind):+ self._run_load_h3_native(+ fam = fam,+ token = token,+ cancel_event = cancel_event,+ **kwargs,+ )+ with self._lock:+ if self._load_token == token:+ self._loading = None+ returnbase = (kwargs["repo_id"]if kind == "pipeline"@@ -764,6 +926,11 @@ class VideoBackend:kwargs["base_repo"] = base# An fp8 encoder request loads a hosted pre-cast checkpoint, so neither the estimate nor the pull includes those dense shards.te_sources = self._te_prequant_sources(fam, kwargs.get("text_encoder_quant"))+ # The same deal for the denoiser: a hosted pre-quantized checkpoint replaces the dense+ # DiT shards, so the estimate and the scoped pull below both drop them.+ skip_transformer_weights = self._denoiser_prequant_covered(+ fam, kwargs.get("transformer_quant"), base+ )expected = self._estimate_download_bytes(kwargs["repo_id"],kwargs.get("gguf_filename"),@@ -771,6 +938,7 @@ class VideoBackend:kwargs.get("hf_token"),kind,te_sources = te_sources,+ skip_transformer_weights = skip_transformer_weights,)with self._lock:if self._load_token == token and self._loading is not None:@@ -818,6 +986,7 @@ class VideoBackend:kind,ltx23 = True,te_sources = te_sources,+ skip_transformer_weights = skip_transformer_weights,)with self._lock:if self._load_token == token and self._loading is not None:@@ -833,6 +1002,7 @@ class VideoBackend:kind,ltx23 = ltx23,skip_te_components = te_skipped,+ skip_transformer_weights = skip_transformer_weights,cancel_event = cancel_event,)# The 2.3 assembly pulls per component from the hub id (its snapshot lacks the base VAEs), so it only gets the warmed cache.@@ -858,6 +1028,208 @@ class VideoBackend:if self._load_token == token and self._loading is not None:self._loading.error = redact_native_paths(str(exc))+ def _run_load_h3_native(+ self,+ *,+ fam: VideoFamily,+ token: Optional[int],+ cancel_event: threading.Event,+ repo_id: str,+ gguf_filename: Optional[str] = None,+ hf_token: Optional[str] = None,+ memory_mode: Optional[str] = None,+ **_: Any,+ ) -> None:+ """Download and commit the four-file stable-diffusion.cpp H3 runtime."""+ from huggingface_hub import HfApi++ from .sd_cpp_args import SdCppModelFiles, offload_flags+ from .diffusion_engine_router import _install_accelerator_for+ from .sd_cpp_backend import (+ _install_allowed,+ ensure_h3_sd_cpp_binary,+ sd_cpp_lists_accelerator_device,+ )+ from .sd_cpp_engine import SdCppEngine+ from .video_minimax_h3 import (+ H3_AUDIO_VAE,+ H3_COMPONENT_REPO,+ H3_GGUF_REPO,+ H3_VIDEO_VAE,+ h3_download_error,+ h3_text_encoder_filename,+ )+ from utils.hf_xet_fallback import hf_hub_download_with_xet_fallback++ filename = gguf_filename or ""+ qwen_filename = h3_text_encoder_filename(filename)+ requests = (+ (repo_id, filename),+ (H3_GGUF_REPO, qwen_filename),+ (H3_COMPONENT_REPO, H3_VIDEO_VAE),+ (H3_COMPONENT_REPO, H3_AUDIO_VAE),+ )+ total = 0+ try:+ api = HfApi(token = hf_token or None)+ for repo, wanted in requests:+ if Path(repo).expanduser().exists():+ continue+ info = api.model_info(repo, files_metadata = True)+ total += sum(+ int(s.size or 0) for s in (info.siblings or []) if s.rfilename == wanted+ )+ except Exception: # noqa: BLE001 -- progress estimate is optional+ total = 0+ with self._lock:+ if self._load_token == token and self._loading is not None:+ self._loading.base_repo = fam.base_repo+ # The download list below pulls from the H3 companion repos too, and neither is+ # repo_id or base_repo, so without this the delete-cached guard would let one be+ # deleted out from under the in-flight load. The committed twin is loaded_repo_ids().+ self._loading.asset_repos = (H3_GGUF_REPO, H3_COMPONENT_REPO)+ self._loading.expected_bytes = total or None++ resolved: list[Path] = []+ for repo, wanted in requests:+ if cancel_event.is_set():+ raise RuntimeError(VIDEO_CANCELLED_MSG)+ root = Path(repo).expanduser()+ if root.is_file():+ local = root+ elif root.is_dir():+ from .diffusion_families import resolve_local_gguf_child+ local = resolve_local_gguf_child(root, wanted)+ else:+ try:+ local = Path(+ hf_hub_download_with_xet_fallback(+ repo, wanted, hf_token, cancel_event = cancel_event+ )+ )+ except Exception as exc: # noqa: BLE001 -- re-raised below, narrowed by name+ raise h3_download_error(repo, wanted, exc) from exc+ resolved.append(local)++ target = resolve_diffusion_device_target()+ allow_install = _install_allowed()+ # The H3-gated ensure, not the plain one: a build that predates H3 runs fine and so clears+ # the version() gate below, then aborts on the first generation, i.e. after the whole+ # bundle has downloaded.+ binary = ensure_h3_sd_cpp_binary(+ allow_install = allow_install,+ accelerator = _install_accelerator_for(target.backend),+ )+ native_device = target.device+ if target.backend not in ("cpu", "mps") and not sd_cpp_lists_accelerator_device(binary):+ # Upstream currently publishes no Linux CUDA archive. Keep the picker+ # functional with the CPU prebuilt when the user has not supplied a+ # locally compiled CUDA binary through the normal sd.cpp discovery path.+ #+ # The test is what the binary actually offers, not whether one was returned: the+ # accelerator install fails only ONCE, and every later load finds the CPU binary this+ # branch put there and gets it back unchanged. "binary is truthy" therefore skipped+ # the fallback from the second load on, left native_device on the GPU, and applied GPU+ # offload policy and held the VIDEO claim while sd-cli ran wholly on the CPU -- so the+ # next chat/image acquire evicted a model to make room for one that was never there.+ binary = ensure_h3_sd_cpp_binary(allow_install = allow_install, accelerator = "cpu")+ native_device = "cpu"+ engine = SdCppEngine(binary)+ if not binary or engine.version() is None:+ raise RuntimeError(+ "stable-diffusion.cpp could not be installed or started for MiniMax-H3."+ )+ requested_mode = normalize_memory_mode(memory_mode) or "auto"+ policy = {+ "auto": "none" if native_device == "cpu" else "group",+ "fast": "none",+ "balanced": "group",+ "low_vram": "model",+ }[requested_mode]+ # NOT --vae-on-cpu. H3 ships an audio VAE, and its 1-D convolutions abort on the CPU+ # path: ggml_conv_1d hardcodes an F16 im2col destination (ggml/src/ggml.c) and+ # ggml_compute_forward_im2col_f16 then asserts the KERNEL is F16, while sd.cpp's+ # audio_conv_weight_type maps only BF16 to F16 and lets F32 through. The result is+ # GGML_ASSERT(src0->type == GGML_TYPE_F16) failed, SIGABRT, exit 134, deterministically.+ # Bisected on the flags: --vae-on-cpu with --audio-vae aborts, without --audio-vae it+ # renders in 95.87s, and converting the audio VAE checkpoint to fp16 does NOT help, so+ # the type is imposed inside sd.cpp rather than by the file and cannot be fixed by+ # shipping a different checkpoint. low_vram is the one mode a small-card user reaches+ # for, so drop the flag rather than the mode; --offload-to-cpu and --clip-on-cpu, which+ # are where the savings actually are, still apply.+ #+ # The abort itself is fixed in the Unsloth sd.cpp fork (it casts F32 conv1d kernels to+ # F16 in-graph on CPU backends), so this is no longer only a crash workaround, and it+ # should not be reverted when that fix reaches the pinned prebuilt. Measured on a build+ # carrying the fix, 640x384, 25 frames, 4 steps, q4_K, with --offload-to-cpu+ # --clip-on-cpu already on: adding --vae-on-cpu moved peak VRAM 12.42 -> 12.42 GiB and+ # wall time 20.9s -> 100.4s. Under --offload-to-cpu the peak is set by the streamed+ # denoiser, so the flag buys nothing and costs 4.8x.+ native_offload = tuple(+ offload_flags(policy, vae_tiling = False, diffusion_fa = True, vae_on_cpu = False)+ )+ from .video_minimax_h3 import MiniMaxH3NativeRuntime++ runtime = MiniMaxH3NativeRuntime(+ engine = engine,+ files = SdCppModelFiles(+ diffusion_model = str(resolved[0]),+ llm = str(resolved[1]),+ vae = str(resolved[2]),+ audio_vae = str(resolved[3]),+ ),+ offload_flags = native_offload,+ )++ with self._lock:+ if token is not None and token != self._load_token:+ raise RuntimeError("Video load was cancelled or superseded.")+ if self._active_generate_cancel is not None:+ self._active_generate_cancel.set()+ self._teardown_waiters += 1+ with self._generate_lock:+ with self._lock:+ try:+ if token is not None and token != self._load_token:+ raise RuntimeError("Video load was cancelled or superseded.")+ self._teardown_state_locked()+ self._state = _VideoLoadState(+ pipe = runtime,+ family = fam,+ repo_id = repo_id,+ base_repo = fam.base_repo,+ device = native_device,+ dtype = Path(filename).stem.split("-")[-1],+ kind = "gguf",+ engine = "sd_cpp",+ h3_task = h3_transformer_task(filename),+ gguf_filename = filename,+ offload_policy = policy,+ vae_tiling = False,+ memory_mode = requested_mode,+ attention_backend = "flash",+ resolved = build_resolved_record(+ {+ "memory_mode": (memory_mode, policy, "native model offload"),+ "attention_backend": (+ None,+ "flash",+ "sd.cpp diffusion flash attention",+ ),+ }+ ),+ )+ finally:+ self._teardown_waiters -= 1+ if native_device == "cpu":+ # /video/load acquired the VIDEO GPU claim off the resolved device target, but no+ # accelerator binary was available and this runtime committed to the CPU build, so it+ # holds no VRAM. Drop the stale claim, or the next chat/image acquire evicts a model+ # that is not on the GPU. release_if keeps the token check atomic against a newer load+ # that took ownership already. Mirrors /images/load's release for a CPU-only native load.+ from .gpu_arbiter import VIDEO, release_if+ release_if(VIDEO, lambda: token is None or token == self._load_token)+def _rollback_precommit_globals(self, token: Optional[int]) -> None:"""Restore process-wide speed globals (cudnn.benchmark / TF32 / the compiledGGUF dequantizer) for a load that died BEFORE committing _VideoLoadState.@@ -891,6 +1263,78 @@ class VideoBackend:target = resolve_diffusion_device_target(),)+ @staticmethod+ def _denoiser_prequant_covered(+ fam: Any, transformer_quant: Optional[str], base: Optional[str]+ ) -> bool:+ """True when a hosted PRE-QUANTIZED denoiser checkpoint replaces the dense DiT shards.++ The one place the plan, the byte estimate and the scoped pull all ask, so none of them can+ stage weights another one skipped. Only a modular-workflow family qualifies: every other+ family quantises its own dense transformer on device and still needs those shards.++ Never raises and never touches the network -- a pure registry lookup -- because it runs on+ the download-planning path, where a failure would cost the whole plan."""+ try:+ if not getattr(fam, "modular_workflow", None):+ return False+ scheme = normalize_transformer_quant(transformer_quant)+ # "auto" leaves the choice to the backend, which keeps the released bfloat16 components+ # for a modular workflow, so it must NOT drop the dense shards that load then wants.+ if scheme is None or scheme == TQ_AUTO:+ return False+ return video_family_prequant_repo(fam, scheme, base) is not None+ except Exception: # noqa: BLE001 -- an unanswerable probe keeps the dense shards+ return False++ @staticmethod+ def _denoiser_prequant_hub_files(+ fam: Any, transformer_quant: Optional[str], base: Optional[str], api: Any+ ) -> tuple[Optional[str], list[tuple[str, int]]]:+ """``(repo_id, [(rfilename, size)])`` for the hosted pre-quantized denoiser, or+ ``(None, [])``.++ The denoiser mirror of ``_te_prequant_hub_files``. ``_denoiser_prequant_covered`` already+ drops the dense DiT shards from the plan, so without this the checkpoint that replaces+ them is in no entry at all: the byte total under-reports by the size of the artifact+ (20.25 GB for H3 int8), the disk preflight passes on a volume that cannot hold it, and an+ offline stage completes without the one file the load needs.++ Same failure rule as the encoder helper: an unreachable repo yields no files and is only+ logged, because the plan is a staging hint and the load still falls back to dense."""+ scheme = (transformer_quant or "").strip().lower()+ if scheme in ("", "auto", "off", "none"):+ return None, []+ try:+ from .diffusion_prequant import resolve_prequant_source+ source = resolve_prequant_source(fam, scheme, base_repo = base)+ except Exception as exc: # noqa: BLE001 -- a bad registry entry must not sink the plan+ logger.warning("video.denoiser_prequant_unresolved: %s", exc)+ return None, []+ # A local override is already on disk; only a hosted checkpoint is staged.+ if source is None or getattr(source, "kind", None) != "repo":+ return None, []+ # The root name first, then the legacy scheme name: resolve_prequant_source hands back both+ # and the load tries them in that order, so the plan must stage whichever one exists.+ wanted = [+ n+ for n in (+ getattr(source, "filename", None),+ getattr(source, "fallback_filename", None),+ )+ if n+ ]+ try:+ info = api.model_info(source.location, files_metadata = True)+ except Exception as exc: # noqa: BLE001 -- unavailable prequant means the dense DiT+ logger.warning("video.denoiser_prequant_unavailable: %s: %s", source.location, exc)+ return None, []+ by_name = {s.rfilename: int(s.size or 0) for s in (info.siblings or [])}+ for name in wanted:+ if name in by_name:+ return source.location, [(name, by_name[name])]+ return None, []+@staticmethoddef _te_prequant_hub_files(sources: dict[str, Any], api: Any@@ -928,6 +1372,7 @@ class VideoBackend:*,ltx23: bool = False,skip_te_components: tuple[str, ...] = (),+ skip_transformer_weights: bool = False,) -> list[tuple[str, int]]:"""The (rfilename, size) list a load actually needs from the base repo.@@ -945,12 +1390,35 @@ class VideoBackend:- the dense weight shards of any ``skip_te_components`` encoder, suppliedinstead by a hosted pre-cast fp8 checkpoint (LTX-2's Gemma3 encoder is~49 GB of the base repo). Their configs stay: the pre-cast loader- meta-inits the encoder from the base repo's component config."""+ meta-inits the encoder from the base repo's component config;+ - the dense ``transformer/`` weight shards under+ ``skip_transformer_weights``, supplied instead by a hosted PRE-QUANTIZED+ denoiser checkpoint (H3's transformer is 66.3 GB of its base repo).+ ``transformer/config.json`` is kept for the same reason the pre-cast+ encoders keep theirs: the pre-quant loader meta-inits the DiT from it,+ so dropping it would break the very load that made the skip safe."""from .diffusion_te_prequant import is_prequant_covered_weight+ siblings = list(info.siblings or [])+ is_h3_modular = any(s.rfilename == "modular_model_index.json" for s in siblings)+ h3_prefixes = (+ "audio_scheduler/",+ "audio_vae/",+ "processor/",+ "scheduler/",+ "text_encoder/",+ "tokenizer/",+ "transformer/",+ "vae/",+ )files: list[tuple[str, int]] = []- for sibling in info.siblings or []:+ for sibling in siblings:name, size = sibling.rfilename, sibling.size or 0+ if is_h3_modular and not (+ name in ("model_index.json", "modular_model_index.json")+ or name.startswith(h3_prefixes)+ ):+ continue# .jinja: tokenizer/chat_template.jinja is needed at generation time; a snapshot without it crashes the first generation.if not name.endswith((".safetensors", ".json", ".model", ".txt", ".jinja")):continue@@ -958,6 +1426,10 @@ class VideoBackend:continueif kind != "pipeline" and name.startswith("transformer/"):continue+ # is_prequant_covered_weight is component-agnostic (it matches "<component>/" against a+ # weight suffix), so the encoder helper serves the denoiser verbatim.+ if skip_transformer_weights and is_prequant_covered_weight(name, ("transformer",)):+ continueif name.startswith("text_encoder/diffusion_pytorch_model"):continueif ltx23 and "/" in name and not name.startswith(VideoBackend._LTX23_BASE_PREFIXES):@@ -976,13 +1448,16 @@ class VideoBackend:kind: str,ltx23: bool = False,te_sources: Optional[dict[str, Any]] = None,+ skip_transformer_weights: bool = False,) -> Optional[int]:"""Total bytes this load will pull (checkpoint + companions), or None.Dense encoder shards covered by an available pre-cast checkpoint are excluded, since- the pull below skips them too. The pre-cast checkpoint's own bytes are deliberately- NOT added: the progress bar counts cached bytes for the checkpoint and base repos- only, so a third repo in the total would leave the bar permanently short of 100%."""+ the pull below skips them too, and so are the dense denoiser shards a hosted+ pre-quantized checkpoint replaces (``skip_transformer_weights``). Neither hosted+ checkpoint's own bytes are added: the progress bar counts cached bytes for the checkpoint+ and base repos only, so a third repo in the total would leave the bar permanently short+ of 100%."""try:from huggingface_hub import HfApi@@ -999,7 +1474,11 @@ class VideoBackend:total += sum(sizefor _, size in self._base_download_files(- info, kind, ltx23 = ltx23, skip_te_components = skip_te_components+ info,+ kind,+ ltx23 = ltx23,+ skip_te_components = skip_te_components,+ skip_transformer_weights = skip_transformer_weights,))return total or None@@ -1015,6 +1494,7 @@ class VideoBackend:family_override: Optional[str] = None,model_kind: Optional[str] = None,hf_token: Optional[str] = None,+ transformer_quant: Optional[str] = None,text_encoder_quant: Optional[str] = None,**load_kwargs: Any,) -> dict[str, Any]:@@ -1025,11 +1505,20 @@ class VideoBackend:``text_encoder_quant`` is read for the same reason the image plan reads the DiTquant: an fp8 request loads a hosted PRE-CAST encoder, so the base repo's denseencoder shards must not be staged (~49 GB of Lightricks/LTX-2) and the pre-cast- checkpoint must be."""+ checkpoint must be.++ ``transformer_quant`` is read for the mirror-image reason on the denoiser: a scheme with a+ hosted PRE-QUANTIZED checkpoint replaces the dense DiT, so staging those shards would cost+ 66.3 GB the load never opens. It used to be swallowed by ``**load_kwargs`` and the plan+ stayed dense-sized."""from huggingface_hub import HfApifam = _detect_load_family(repo_id, gguf_filename, family_override)kind = resolve_video_model_kind(gguf_filename, model_kind)+ from .video_minimax_h3 import is_h3_native++ if is_h3_native(fam, kind):+ return self._h3_native_download_plan(repo_id, gguf_filename or "", hf_token = hf_token)base = repo_id if kind == "pipeline" else resolve_video_base_repo(fam, base_repo)# Only the header tells an LTX-2.3 checkpoint from 2.0 and it is not on disk yet, so narrow the base pull by NAME: a wrong guess costs an inline pull, the wide base list costs gigabytes.ltx23 = self._pick_looks_like_ltx23(fam, repo_id, gguf_filename, kind)@@ -1093,6 +1582,11 @@ class VideoBackend:te_files = self._te_prequant_hub_files(te_sources, api)for component, files in te_files.items():total += add(te_sources[component].location, files)+ # The denoiser's replacement artifact, for the same reason: the base entry below drops+ # the dense DiT shards whenever this resolves, so it has to be staged in their place.+ dq_repo, dq_files = self._denoiser_prequant_hub_files(fam, transformer_quant, base, api)+ if dq_repo:+ total += add(dq_repo, dq_files)if base and not Path(base).expanduser().exists():info = api.model_info(base, files_metadata = True)total += add(@@ -1102,6 +1596,9 @@ class VideoBackend:kind,ltx23 = ltx23,skip_te_components = tuple(te_files),+ skip_transformer_weights = self._denoiser_prequant_covered(+ fam, transformer_quant, base+ ),),)except Exception as exc: # noqa: BLE001 -- an unavailable plan falls back to the inline pull@@ -1109,6 +1606,55 @@ class VideoBackend:return {"entries": [], "total_bytes": 0}return {"entries": list(entries.values()), "total_bytes": total}+ @staticmethod+ def _h3_native_download_plan(+ repo_id: str, gguf_filename: str, *, hf_token: Optional[str]+ ) -> dict[str, Any]:+ from huggingface_hub import HfApi++ from .video_minimax_h3 import (+ H3_AUDIO_VAE,+ H3_COMPONENT_REPO,+ H3_GGUF_REPO,+ H3_VIDEO_VAE,+ h3_text_encoder_filename,+ validate_h3_transformer_filename,+ )++ validate_h3_transformer_filename(gguf_filename)+ wanted = (+ (repo_id, gguf_filename),+ (H3_GGUF_REPO, h3_text_encoder_filename(gguf_filename)),+ (H3_COMPONENT_REPO, H3_VIDEO_VAE),+ (H3_COMPONENT_REPO, H3_AUDIO_VAE),+ )+ grouped: dict[str, dict[str, Any]] = {}+ total = 0+ try:+ api = HfApi(token = hf_token or None)+ for repo, filename in wanted:+ if Path(repo).expanduser().exists():+ continue+ info = api.model_info(repo, files_metadata = True)+ match = next((s for s in (info.siblings or []) if s.rfilename == filename), None)+ if match is None:+ raise ValueError(f"Required MiniMax-H3 component is missing: {repo}/{filename}")+ size = int(match.size or 0)+ entry = grouped.setdefault(+ repo,+ {"repo_id": repo, "files": [], "bytes": 0, "gguf_filename": None},+ )+ if filename not in entry["files"]:+ entry["files"].append(filename)+ entry["bytes"] += size+ total += size+ if filename == gguf_filename:+ entry["gguf_filename"] = filename+ except Exception as exc: # noqa: BLE001 -- inline loading remains the fallback+ logger.warning("video.h3_native_download_plan_failed: %s", exc)+ return {"entries": [], "total_bytes": 0}+ return {"entries": list(grouped.values()), "total_bytes": total}+@staticmethoddef _pick_looks_like_ltx23(fam: Any, repo_id: str, gguf_filename: Optional[str], kind: str@@ -1178,6 +1724,7 @@ class VideoBackend:*,ltx23: bool = False,skip_te_components: tuple[str, ...] = (),+ skip_transformer_weights: bool = False,cancel_event: Optional[threading.Event] = None,) -> Optional[str]:"""Pull exactly the base-repo files the load needs; return the local snapshot dir.@@ -1197,7 +1744,11 @@ class VideoBackend:info = HfApi(token = hf_token or None).model_info(base, files_metadata = True)files = self._base_download_files(- info, kind, ltx23 = ltx23, skip_te_components = skip_te_components+ info,+ kind,+ ltx23 = ltx23,+ skip_te_components = skip_te_components,+ skip_transformer_weights = skip_transformer_weights,)if not any(name == "model_index.json" for name, _ in files):return None@@ -1279,14 +1830,33 @@ class VideoBackend:"""Repo ids an in-flight background load is downloading (empty when idle).The delete-cached guard needs this: during a load ``status()["loaded"]`` is- still False, but deleting the target repo (or its companion base) would yank- blobs and snapshot files from under the download/assembly. Mirrors the image- backend's guard (DiffusionBackend.loading_repo_ids)."""+ still False, but deleting the target repo (or its companion base, or one of the+ native H3 companion repos an H3 load also downloads from) would yank blobs and+ snapshot files from under the download/assembly. The in-flight twin of+ loaded_repo_ids(); mirrors the image backend's guard+ (DiffusionBackend.loading_repo_ids)."""with self._lock:loading = self._loadingif loading is None or loading.error is not None:return ()- return tuple(r for r in (loading.repo_id, loading.base_repo) if r)+ ids = (loading.repo_id, loading.base_repo, *loading.asset_repos)+ return tuple(r for r in ids if r)++ def loaded_repo_ids(self) -> tuple[str, ...]:+ """Repo ids the COMMITTED model reads from disk (empty unless a native model is loaded).++ The one-shot sd-cli re-reads H3's Qwen encoder and both VAEs from the cache on every+ generation, and those live in companion repos that are neither ``repo_id`` nor the BF16+ ``base_repo`` ``status()`` publishes, so the delete-cached guard must refuse them too.+ Mirrors the image backend's guard (SdCppBackend.loaded_repo_ids)."""+ with self._lock:+ state = self._state+ if state is None or state.engine != "sd_cpp":+ return ()+ repo_id = state.repo_id+ from .video_minimax_h3 import H3_COMPONENT_REPO, H3_GGUF_REPO++ return (repo_id, H3_GGUF_REPO, H3_COMPONENT_REPO)# ── the load itself ──────────────────────────────────────────────────────@@ -1306,13 +1876,11 @@ class VideoBackend:transformer_quant: Optional[str] = None,text_encoder_quant: Optional[str] = None,model_kind: Optional[str] = None,+ h3_task: Optional[str] = None,_load_token: Optional[int] = None,_base_local_dir: Optional[str] = None,_te_prequant_skipped: tuple[str, ...] = (),) -> dict[str, Any]:- import diffusers- import torch-fam = self.validate_load_request(repo_id,gguf_filename = gguf_filename,@@ -1321,8 +1889,26 @@ class VideoBackend:model_kind = model_kind,transformer_quant = transformer_quant,text_encoder_quant = text_encoder_quant,+ h3_task = h3_task,)kind = resolve_video_model_kind(gguf_filename, model_kind)+ from .video_minimax_h3 import is_h3_native++ if is_h3_native(fam, kind):+ self._run_load_h3_native(+ fam = fam,+ token = _load_token,+ cancel_event = threading.Event(),+ repo_id = repo_id,+ gguf_filename = gguf_filename,+ hf_token = hf_token,+ memory_mode = memory_mode,+ )+ return self.status()++ import diffusers+ import torch+base = repo_id if kind == "pipeline" else resolve_video_base_repo(fam, base_repo)with self._lock:@@ -1355,6 +1941,28 @@ class VideoBackend:# Size tables below are bf16 (2-byte), so scale dense estimates when the promotion lands fp32 on an accelerator.dtype_scale = 2.0 if device != "cpu" and dtype is torch.float32 else 1.0+ if fam.modular_workflow:+ return self._load_h3_modular_pipeline(+ diffusers = diffusers,+ torch = torch,+ fam = fam,+ repo_id = repo_id,+ base = base,+ kind = kind,+ dtype = dtype,+ device = device,+ hf_token = hf_token,+ memory_mode = memory_mode,+ # transformer_quant is only normalised BELOW this dispatch, and the modular branch+ # returns before reaching that, so normalise here with the same function rather+ # than moving the dispatch past a block written for the conventional path (its+ # speed_mode/auto-ladder defaulting means nothing to a modular workflow).+ transformer_quant = normalize_transformer_quant(transformer_quant),+ h3_task = h3_task,+ _load_token = _load_token,+ _base_local_dir = _base_local_dir,+ )+# What the CALLER asked for, before the rewrite below. The record has to report this, not# the internal value: an omitted precision under speed_mode="off" becomes "off" here, and# reporting that as the request makes the resolved record say the user pinned bf16. The@@ -1925,6 +2533,228 @@ class VideoBackend:)return self.status()+ def _load_h3_modular_pipeline(+ self,+ *,+ diffusers: Any,+ torch: Any,+ fam: VideoFamily,+ repo_id: str,+ base: str,+ kind: str,+ dtype: Any,+ device: str,+ hf_token: Optional[str],+ memory_mode: Optional[str],+ transformer_quant: Optional[str] = None,+ h3_task: Optional[str] = None,+ _load_token: Optional[int] = None,+ _base_local_dir: Optional[str] = None,+ ) -> dict[str, Any]:+ """Load MiniMax-H3 through its official Modular Diffusers workflow.++ ``transformer_quant`` is an ALREADY-normalised scheme (or None / "auto"). A scheme with a+ hosted pre-quantized denoiser checkpoint is built here and pre-seeded into the pipeline;+ anything else keeps the released bfloat16 components."""+ # Defence in depth: validate_load_request now refuses a single_file modular pick outright,+ # so this is unreachable from the routes. It stays because this method is also reachable+ # directly, and by the time it runs the resident pipeline has already been torn down.+ if kind != "pipeline":+ raise ValueError("MiniMax-H3 Diffusers loading requires the pipeline artifact.")+ # Load one denoiser partition. fl2va also covers text-only generation.+ workflow = h3_task or fam.modular_workflow+ manager = diffusers.ComponentsManager()+ load_kwargs: dict[str, Any] = {+ "components_manager": manager,+ "cache_dir": hub_cache_dir(),+ }+ if hf_token:+ load_kwargs["token"] = hf_token+ pipe = diffusers.ModularPipeline.from_pretrained(_base_local_dir or repo_id, **load_kwargs)+ # ── hosted pre-quantized denoiser, BEFORE load_components builds a dense one.+ transformer_quant_engaged: Optional[str] = None+ transformer_quant_reason = "released bfloat16 components"+ # "auto" asks the backend to choose, and the auto ladder quantises a DENSE module on device+ # -- something this workflow never materialises -- so it stays on the released components.+ # Only an explicitly requested scheme takes the hosted path.+ scheme = transformer_quant if transformer_quant not in (None, TQ_AUTO) else None+ # The hosted checkpoints are keyframe (fl2va) denoisers. validate_load_request refuses this+ # pairing on the route; a direct call lands here, and seeding one would silently generate+ # the wrong partition rather than fail, so drop to the released components instead.+ if scheme is not None and workflow == H3_TASK_REFERENCES:+ transformer_quant_reason = (+ f"no hosted pre-quantized {scheme} checkpoint for {fam.name} reference video"+ )+ scheme = None+ if scheme is not None:+ from .diffusion_prequant import load_prequantized_transformer, resolve_prequant_source+ from .diffusion_transformer_quant import DEFAULT_MIN_LINEAR_FEATURES+ from .video_minimax_h3_adaln import h3_prepare_prequant_model++ source = resolve_prequant_source(fam, scheme, base_repo = base)+ if source is None:+ # validate_load_request already refused this on the route; a direct call lands here.+ transformer_quant_reason = (+ f"no hosted pre-quantized {scheme} checkpoint for {fam.name}"+ )+ else:+ transformer = load_prequantized_transformer(+ getattr(diffusers, fam.transformer_class),+ base,+ source,+ # CPU: enable_auto_cpu_offload below owns placement for every component, so a+ # pre-placed denoiser would just be moved again (and a 66 GB pin on a device the+ # manager wanted to offload from is how this OOMs). Same as the pre-cast text+ # encoder path, which also hands the pipeline a CPU-resident module.+ device = "cpu",+ dtype = dtype,+ hf_token = hf_token,+ scheme = scheme,+ # Reject a checkpoint baked under a different Linear filter, exactly as the+ # image path does, so prequant and runtime-quant stay the same model.+ min_features = DEFAULT_MIN_LINEAR_FEATURES,+ # Pin the live cache root, as every other loader call does: unset, the fetch+ # lands under huggingface_hub's import-time constant and a later cache change+ # re-downloads multiple GB into a root Studio no longer reads.+ cache_dir = hub_cache_dir(),+ # The hosted H3 denoisers carry the PRUNED (curve-form) adaLN: the modulation is+ # a rank-8 factorization of the time-embedding curve plus a shared table, which+ # is where ~40% of the released model's parameters went. Built from the base+ # repo's dense config, the model is 4 keys short, 1 over and 51 shapes wrong, so+ # without this reshape the strict load fails and every hosted checkpoint falls+ # back to the dense download it exists to avoid.+ prepare_model = h3_prepare_prequant_model(logger),+ logger = logger,+ )+ if transformer is None:+ # Best-effort by contract (missing / mismatched / unreadable checkpoint), so the+ # load continues dense rather than failing after the teardown.+ transformer_quant_reason = (+ f"hosted pre-quantized {scheme} checkpoint unusable; "+ f"loaded the released bfloat16 denoiser instead"+ )+ else:+ # Seeding is what actually saves the download: load_components(names=None) skips+ # every component whose attribute is already set, so the dense 66.3 GB+ # transformer is never fetched. It must happen BEFORE load_components -- after,+ # the dense one has already been pulled and built.+ pipe.update_components(transformer = transformer)+ transformer_quant_engaged = scheme+ transformer_quant_reason = (+ f"hosted pre-quantized {scheme} denoiser checkpoint ({source.location})"+ )+ logger.info(+ "video.transformer_quant: %s pre-quantized denoiser seeded for %s",+ scheme,+ fam.name,+ )+ # The token above only opens the modular index. Every component's own from_pretrained runs+ # here, against the repos that index names, so it has to be passed again or a gated/private+ # component load goes out anonymously (load_components only WARNS on a failed component).+ # Restrict component loading to what this workflow's blocks expect, WITHOUT pruning the+ # block graph itself (the blocks are what route each request between t2va and the+ # keyframe/reference paths). workflow= only narrows the name list load_components already+ # built, and that list skips every component whose attribute is set, so the seeding above+ # still keeps the dense 66.3 GB transformer from being fetched.+ pipe.load_components(+ workflow = workflow,+ dtype = dtype,+ **({"token": hf_token} if hf_token else {}),+ )+ # The video VAE loads at float32 and the decode runs under float16 autocast, so both+ # copies are resident for the whole decode. Pre-casting the decoder removes the pair+ # without changing a single output value. The encoder stays resident because the+ # keyframe and reference paths both encode their conditioning frames through it.++ from .video_minimax_h3 import trim_h3_video_vae++ try:+ trimmed = trim_h3_video_vae(getattr(pipe, "vae", None), workflow = workflow)+ except Exception as exc: # noqa: BLE001 -- a saving is not worth failing a load over+ logger.warning("video.h3_vae_trim failed, keeping the full VAE: %s", exc)+ else:+ if trimmed["encoder_freed"] or trimmed["decoder_freed"]:+ logger.info(+ "video.h3_vae_trim: freed %.2f GB (encoder %.2f, decoder pre-cast %.2f)",+ (trimmed["encoder_freed"] + trimmed["decoder_freed"]) / 1_000_000_000,+ trimmed["encoder_freed"] / 1_000_000_000,+ trimmed["decoder_freed"] / 1_000_000_000,+ )+ offload_policy = "none"+ denoiser_pinned = False+ if device != "cpu":+ manager.enable_auto_cpu_offload(+ # Measured H3 activations need substantially more than the+ # official 12 GB example at 10-15 seconds. Forty GB also keeps+ # very large GPUs from retaining both 66 GB components and OOMing+ # while smaller caps succeed by offloading one of them.+ device = device,+ memory_reserve_margin = "40GB",+ )+ offload_policy = "model"+ if transformer_quant_engaged:+ # enable_auto_cpu_offload just parked every component on the CPU and will move+ # each one back inside its own pre_forward. A torchao pre-quantized denoiser does+ # not survive that mid-block move (see pin_prequantized_module), so place it now+ # and take it out of the rotation. Nothing else changes: the encoder and the VAEs+ # keep their hooks and still offload around it.+ from .diffusion_prequant import pin_prequantized_module+ denoiser_pinned = pin_prequantized_module(+ manager, getattr(pipe, "transformer", None), device, logger = logger+ )++ resolved = build_resolved_record(+ {+ "memory_mode": (+ memory_mode,+ offload_policy,+ "MiniMax-H3 ComponentsManager auto CPU offload"+ + ("; the pre-quantized denoiser stays resident" if denoiser_pinned else ""),+ ),+ "speed_mode": (None, "off", "modular pipeline uses its native execution path"),+ "attention_backend": (None, "native", "Diffusers model default"),+ "transformer_cache": (None, "off", "not supported by this modular workflow"),+ "transformer_quant": (+ transformer_quant,+ transformer_quant_engaged or "off",+ transformer_quant_reason,+ ),+ "text_encoder_quant": (None, "off", "released bfloat16 components"),+ }+ )+ with self._lock:+ if _load_token is not None and _load_token != self._load_token:+ del pipe+ clear_gpu_cache()+ raise RuntimeError("Video load was cancelled or superseded.")+ self._state = _VideoLoadState(+ pipe = pipe,+ family = fam,+ repo_id = repo_id,+ base_repo = base,+ device = device,+ dtype = str(dtype).replace("torch.", ""),+ kind = kind,+ engine = "diffusers",+ h3_task = workflow,+ offload_policy = offload_policy,+ vae_tiling = True,+ memory_mode = normalize_memory_mode(memory_mode),+ speed_mode = SPEED_OFF,+ # The ENGAGED scheme, not the requested one, exactly as the conventional path+ # records it: status() reports this field, and a dense fallback must not claim a+ # quant the resident denoiser does not have.+ transformer_quant = transformer_quant_engaged,+ resolved = resolved,+ )+ logger.info(+ "video.loaded: %s (%s, modular diffusers, transformer_quant=%s)",+ repo_id,+ fam.name,+ transformer_quant_engaged or "off",+ )+ return self.status()+@staticmethoddef _resolve_checkpoint_path(repo_id: str, gguf_filename: Optional[str], hf_token: Optional[str]@@ -1989,6 +2819,14 @@ class VideoBackend:guidance: Optional[float] = None,guidance_2: Optional[float] = None,seed: Optional[int] = None,+ first_frame: Optional[str] = None,+ last_frame: Optional[str] = None,+ reference_images: Optional[list[str]] = None,+ reference_videos: Optional[list[dict]] = None,+ reference_audios: Optional[list[str]] = None,+ reference_image_size: Optional[str] = None,+ flow_shift: Optional[float] = None,+ audio_flow_shift: Optional[float] = None,) -> None:"""Validate cheaply, then run generate + gallery persist on a daemon thread.@@ -2002,6 +2840,31 @@ class VideoBackend:sentinels the route maps to 409."""cancel = threading.Event()+ # Snapshot load state before decoding outside the backend lock.+ with self._lock:+ if self._state is None:+ raise RuntimeError(VIDEO_NOT_LOADED_MSG)+ if self._generate_job_active:+ raise RuntimeError(VIDEO_GENERATION_BUSY_MSG)+ family = self._state.family+ task = self._state.h3_task+ engine = self._state.engine+ # Validate conditioning before creating the asynchronous job so request errors return 400.+ _, _, canvas_w, canvas_h, _ = self._resolve_keyframes(+ family, task, first_frame, last_frame, width, height+ )+ self._resolve_references(+ family,+ task,+ engine,+ reference_images,+ reference_videos,+ reference_audios,+ reference_image_size,+ canvas_w,+ canvas_h,+ )+ self._resolve_flow_shifts(family, engine, flow_shift, audio_flow_shift)with self._lock:if self._state is None:raise RuntimeError(VIDEO_NOT_LOADED_MSG)@@ -2038,6 +2901,14 @@ class VideoBackend:guidance = guidance,guidance_2 = guidance_2,seed = seed,+ first_frame = first_frame,+ last_frame = last_frame,+ reference_images = reference_images,+ reference_videos = reference_videos,+ reference_audios = reference_audios,+ reference_image_size = reference_image_size,+ flow_shift = flow_shift,+ audio_flow_shift = audio_flow_shift,cancel_event = cancel,),daemon = True,@@ -2087,6 +2958,9 @@ class VideoBackend:"guidance_2": gen_kwargs.get("guidance_2"),"seed": result["seed"],"has_audio": result["has_audio"],+ "conditioning": result["conditioning"],+ "flow_shift": result.get("flow_shift"),+ "audio_flow_shift": result.get("audio_flow_shift"),"model": result["repo_id"],# The load-time build, so a clip's recipe still names the precision it ran at# once the model is unloaded. All engaged values; absent keys read back as null@@ -2157,10 +3031,16 @@ class VideoBackend:guidance: Optional[float] = None,guidance_2: Optional[float] = None,seed: Optional[int] = None,+ first_frame: Optional[str] = None,+ last_frame: Optional[str] = None,+ reference_images: Optional[list[str]] = None,+ reference_videos: Optional[list[dict]] = None,+ reference_audios: Optional[list[str]] = None,+ reference_image_size: Optional[str] = None,+ flow_shift: Optional[float] = None,+ audio_flow_shift: Optional[float] = None,cancel_event: Optional[threading.Event] = None,) -> dict[str, Any]:- import torch-# begin_generate passes its already-registered event; a direct call makes its own.cancel = cancel_event if cancel_event is not None else threading.Event()with self._generate_lock:@@ -2177,13 +3057,26 @@ class VideoBackend:request_shape: Optional[dict[str, Any]] = Nonetry:fam = state.family- width, height = snap_video_size(+ first_pil, last_pil, width, height, conditioning = self._resolve_keyframes(+ fam, state.h3_task, first_frame, last_frame, width, height+ )+ references = self._resolve_references(fam,- width or fam.resolution_presets[0][0],- height or fam.resolution_presets[0][1],+ state.h3_task,+ state.engine,+ reference_images,+ reference_videos,+ reference_audios,+ reference_image_size,+ width,+ height,)+ if references:+ conditioning = h3_conditioning_mode(has_references = True)frames = snap_num_frames(fam, num_frames or fam.default_num_frames)- out_fps = int(fps or fam.default_fps)+ out_fps = (+ fam.default_fps if fam.name == "minimax-h3" else int(fps or fam.default_fps)+ )default_steps, default_guidance = default_video_generation_params(state.gguf_filename,state.repo_id,@@ -2192,8 +3085,71 @@ class VideoBackend:)steps = int(steps or default_steps)guidance = float(default_guidance if guidance is None else guidance)+ shift, audio_shift = self._resolve_flow_shifts(+ fam, state.engine, flow_shift, audio_flow_shift+ )++ if state.engine == "sd_cpp":+ return self._generate_h3_native(+ state = state,+ prompt = prompt,+ width = width,+ height = height,+ frames = frames,+ fps = out_fps,+ steps = steps,+ guidance = guidance,+ seed = seed,+ first_frame = first_pil,+ last_frame = last_pil,+ references = references,+ conditioning = conditioning,+ flow_shift = shift,+ cancel = cancel,+ )- generator = torch.Generator(device = state.device)+ import torch++ if state.engine == "diffusers" and fam.modular_workflow and state.device != "cpu":+ from .video_minimax_h3 import (+ estimate_h3_diffusers_host_ram_gb,+ estimate_h3_diffusers_vram_gb,+ )++ device_obj = torch.device(state.device)+ device_module = getattr(torch, device_obj.type, None)+ if device_module is not None and hasattr(device_module, "mem_get_info"):+ free_bytes, _ = device_module.mem_get_info(device_obj)+ reserved_bytes = (+ device_module.memory_reserved(device_obj)+ if hasattr(device_module, "memory_reserved")+ else 0+ )+ available_vram_gb = (free_bytes + reserved_bytes) / 1_000_000_000+ required_vram_gb = estimate_h3_diffusers_vram_gb(width, height, frames)+ if available_vram_gb + 0.25 < required_vram_gb:+ raise RuntimeError(+ f"MiniMax-H3 needs about {required_vram_gb:.1f} GB available "+ f"VRAM for {width}x{height} at {frames} frames; "+ f"{available_vram_gb:.1f} GB is available. Lower the resolution "+ "or duration, or load the GGUF artifact."+ )++ import psutil++ process_rss = psutil.Process().memory_info().rss+ host_capacity_gb = (+ psutil.virtual_memory().available + process_rss+ ) / 1_000_000_000+ required_host_gb = estimate_h3_diffusers_host_ram_gb(available_vram_gb)+ if host_capacity_gb + 0.5 < required_host_gb:+ raise RuntimeError(+ f"MiniMax-H3 needs about {required_host_gb:.0f} GB available "+ f"system RAM at this VRAM tier; {host_capacity_gb:.1f} GB is "+ "available. Load the GGUF artifact instead."+ )++ generator = torch.Generator(device = "cpu" if fam.modular_workflow else state.device)if seed is None:seed = int(generator.seed()) % (2**53)generator = generator.manual_seed(int(seed))@@ -2248,7 +3204,9 @@ class VideoBackend:):kwargs["sigmas"] = list(LTX23_DISTILLED_SIGMAS)sigma_ctx = ltx23_verbatim_sigmas(pipe)- if fam.guidance_via_guider:+ if not fam.supports_cfg:+ pass+ elif fam.guidance_via_guider:# HunyuanVideo-1.5: __call__ has no guidance kwarg; CFG scale is a guider attribute set per request.pipe.guider.guidance_scale = float(guidance)else:@@ -2261,6 +3219,24 @@ class VideoBackend:# Dual-DiT MoE: pass the low-noise expert guidance only when the family declares it AND the signature accepts it (WanPipeline raises with boundary_ratio=None).if fam.cfg2_kwarg and fam.cfg2_kwarg in call_params and guidance_2 is not None:kwargs[fam.cfg2_kwarg] = float(guidance_2)+ if fam.modular_workflow:+ kwargs["output"] = ["videos", "audio", "sampling_rate"]+ # Auto-blocks distinguish omitted conditioning from empty conditioning.+ if first_pil is not None:+ kwargs["image"] = first_pil+ if last_pil is not None:+ kwargs["last_image"] = last_pil+ if references:+ from .video_minimax_h3 import h3_diffusers_references+ kwargs["references"] = h3_diffusers_references(references)+ # Set scheduler shifts every run so prior requests cannot leak state.+ for component, value in (+ ("scheduler", shift),+ ("audio_scheduler", audio_shift),+ ):+ setter = getattr(getattr(pipe, component, None), "set_shift", None)+ if callable(setter) and value is not None:+ setter(float(value))started = time.monotonic()self._gen = {@@ -2298,6 +3274,9 @@ class VideoBackend:progress_ctx = contextlib.nullcontext()else:# HunyuanVideo-1.5 has no step callback, so wrap scheduler.step for progress + cancel and restore afterwards.+ # Same for H3's modular workflow: ModularPipeline takes no callback (an unknown input is only warned+ # about), but MiniMaxH3LoopSchedulerStep calls components.scheduler.step -- pipe.scheduler -- once per+ # denoise step, so the wrapper ticks and can unwind a multi-minute run on Cancel.progress_ctx = _scheduler_step_progress(pipe, _on_scheduler_step)# Re-check an AUTO cache decision against the ACTUAL step count; explicit choices never toggle.@@ -2340,12 +3319,28 @@ class VideoBackend:raise RuntimeError(VIDEO_CANCELLED_MSG)self._gen.update(phase = "export", eta_seconds = None)- video_frames = output.frames[0]- audio = getattr(output, "audio", None)- audio_track = audio[0] if fam.has_audio and audio is not None else None- mp4_bytes = self._encode_mp4(- video_frames, out_fps, audio_track, pipe if fam.has_audio else None- )+ if fam.modular_workflow:+ video_frames = output["videos"][0]+ audio = output.get("audio")+ audio_track = audio[0] if audio is not None else None+ audio_sample_rate = output.get("sampling_rate")+ else:+ video_frames = output.frames[0]+ audio = getattr(output, "audio", None)+ audio_track = audio[0] if fam.has_audio and audio is not None else None+ audio_sample_rate = None+ if audio_sample_rate is None:+ mp4_bytes = self._encode_mp4(+ video_frames, out_fps, audio_track, pipe if fam.has_audio else None+ )+ else:+ mp4_bytes = self._encode_mp4(+ video_frames,+ out_fps,+ audio_track,+ pipe if fam.has_audio else None,+ audio_sample_rate = int(audio_sample_rate),+ )# A cancel during the blocking export/mux must still discard the clip; re-check before it is persisted.if cancel.is_set():raise RuntimeError(VIDEO_CANCELLED_MSG)@@ -2361,8 +3356,11 @@ class VideoBackend:"fps": out_fps,"duration_s": duration_s,"has_audio": bool(audio_track is not None),+ "conditioning": conditioning,"steps": steps,"guidance": guidance,+ "flow_shift": shift,+ "audio_flow_shift": audio_shift,# The BUILD this clip came off, read from the ENGAGED state and never from the# request, so a saved MP4 can never be labelled with a precision that did not# run. Mirrors what the image gallery already records.@@ -2383,7 +3381,342 @@ class VideoBackend:self._active_generate_cancel = None@staticmethod- def _encode_mp4(video_frames, fps: int, audio, pipe) -> bytes:+ def _resolve_keyframes(+ fam: VideoFamily,+ h3_task: Optional[str],+ first_frame: Optional[str],+ last_frame: Optional[str],+ width: Optional[int],+ height: Optional[int],+ ) -> tuple[Any, Any, int, int, str]:+ """Decode keyframes and resolve their shared generation canvas.++ Unsupported keyframes are rejected. Omitting both dimensions matches the source aspect.+ """+ if first_frame or last_frame:+ if not fam.supports_keyframes:+ raise ValueError(+ f"{fam.name} generates from the prompt alone; it takes no first or last frame."+ )+ if h3_task == H3_TASK_REFERENCES:+ raise ValueError(+ "The loaded MiniMax-H3 checkpoint is the Ref2VA partition, which conditions "+ "on references rather than keyframes. Load a minimax_h3_fl2va checkpoint to "+ "generate from a first or last frame."+ )+ first = last = None+ if first_frame or last_frame:+ from .diffusion import decode_b64_image+ first = decode_b64_image(first_frame, mode = "RGB") if first_frame else None+ last = decode_b64_image(last_frame, mode = "RGB") if last_frame else None++ if (width is None or height is None) and (first is not None or last is not None):+ width, height = h3_canvas_for_aspect(*(first if first is not None else last).size)+ else:+ # begin_generate runs this for EVERY family, keyframes or not, so it cannot assume a+ # family declares presets: an unusual/custom one with an empty tuple used to die here+ # with an IndexError (a 500) before the request reached the worker. Fall back to the+ # generic 768x512 the rest of the video path already treats as the default canvas.+ default_w, default_h = (+ fam.resolution_presets[0] if fam.resolution_presets else (768, 512)+ )+ width, height = snap_video_size(+ fam,+ width or default_w,+ height or default_h,+ )+ # Fit once so both engines condition on identical pixels.+ if first is not None:+ first = fit_h3_keyframe(first, width, height, anchor = H3_ANCHOR_FIRST)+ if last is not None:+ last = fit_h3_keyframe(last, width, height, anchor = H3_ANCHOR_LAST)+ conditioning = h3_conditioning_mode(has_first = first is not None, has_last = last is not None)+ return first, last, width, height, conditioning++ @staticmethod+ def _resolve_flow_shifts(+ fam: VideoFamily,+ engine: str,+ flow_shift: Optional[float],+ audio_flow_shift: Optional[float],+ ) -> tuple[Optional[float], Optional[float]]:+ """Resolve requested or released sigma shifts.++ sd.cpp rejects non-default audio shifts because it cannot apply them.+ """+ if flow_shift is not None and fam.default_flow_shift is None:+ raise ValueError(f"{fam.name} does not expose a video flow_shift control.")+ if audio_flow_shift is not None and fam.default_audio_flow_shift is None:+ raise ValueError(f"{fam.name} does not expose an audio_flow_shift control.")+ shift = flow_shift if flow_shift is not None else fam.default_flow_shift+ audio_shift = (+ audio_flow_shift if audio_flow_shift is not None else fam.default_audio_flow_shift+ )+ if (+ audio_flow_shift is not None+ and engine == "sd_cpp"+ and audio_flow_shift != fam.default_audio_flow_shift+ ):+ raise ValueError(+ "stable-diffusion.cpp derives the audio schedule against a fixed "+ f"{fam.default_audio_flow_shift:g} shift, so audio_flow_shift needs the "+ "Diffusers engine."+ )+ return shift, audio_shift++ @staticmethod+ def _resolve_references(+ fam: VideoFamily,+ h3_task: Optional[str],+ engine: str,+ reference_images: Optional[list[str]],+ reference_videos: Optional[list[dict]],+ reference_audios: Optional[list[str]],+ reference_image_size: Optional[str],+ width: int,+ height: int,+ ) -> Any:+ """Decode the request's omni references into the one object both engines consume.++ Sizing is settled here for the same reason keyframes are: sd.cpp scales every reference+ to the generation's pixel area and the Diffusers blocks scale to their own 2048px short+ edge, and both are min(1, ...) scales, so pre-fitting to the requested policy makes each+ engine's own rule a no-op and the two agree. That is also why ``max`` is refused on the+ native engine rather than accepted and quietly undone.+ """+ from .video_minimax_h3 import (+ MiniMaxH3References,+ decode_h3_reference_audio,+ decode_h3_reference_video,+ )++ images = list(reference_images or [])+ videos = list(reference_videos or [])+ audios = list(reference_audios or [])+ if not (images or videos or audios):+ if h3_task == H3_TASK_REFERENCES:+ # Ref2VA has no text-only denoiser, so every request needs an image or video.+ raise ValueError(+ "The loaded MiniMax-H3 checkpoint is the Ref2VA partition, which generates "+ "from references. Add at least one reference image or video, or load a "+ "minimax_h3_fl2va checkpoint for text-to-video."+ )+ return MiniMaxH3References()+ if not fam.supports_references:+ raise ValueError(f"{fam.name} takes no reference images, videos or audio.")+ if h3_task != H3_TASK_REFERENCES:+ raise ValueError(+ "The loaded MiniMax-H3 checkpoint is the FL2VA partition, which conditions on "+ "keyframes rather than references. Load a minimax_h3_ref2va checkpoint to "+ "generate from references."+ )+ policy = (reference_image_size or H3_REF_SIZE_MATCH).strip().lower()+ if policy not in (H3_REF_SIZE_MATCH, H3_REF_SIZE_MAX):+ raise ValueError(+ f"reference_image_size must be '{H3_REF_SIZE_MATCH}' or '{H3_REF_SIZE_MAX}'."+ )+ if policy == H3_REF_SIZE_MAX and engine == "sd_cpp":+ raise ValueError(+ "stable-diffusion.cpp scales every reference to the generation's pixel area, so "+ f"'{H3_REF_SIZE_MAX}' reference sizing needs the Diffusers engine. Use "+ f"'{H3_REF_SIZE_MATCH}' with this checkpoint."+ )++ from .diffusion import decode_b64_image++ fitted_images = tuple(+ fit_h3_reference_image(+ decode_b64_image(item, mode = "RGB"),+ width = width,+ height = height,+ policy = policy,+ )+ for item in images+ )+ decoded_videos = []+ for item in videos:+ blob = _decode_b64_media(item.get("video") if isinstance(item, dict) else item)+ frames, waveform, sample_rate = decode_h3_reference_video(blob)+ override = item.get("audio") if isinstance(item, dict) else None+ if override:+ waveform, sample_rate = decode_h3_reference_audio(_decode_b64_media(override))+ decoded_videos.append((frames, waveform, sample_rate))+ if engine == "sd_cpp":+ soundtrack_gap = False+ for index, (_, waveform, _) in enumerate(decoded_videos, start = 1):+ if waveform is None:+ soundtrack_gap = True+ elif soundtrack_gap:+ # sd-cli pairs soundtrack flags by position, so gaps would misattach audio.+ raise ValueError(+ "stable-diffusion.cpp can pair reference-video soundtracks only from "+ f"Video 1 onward without gaps, but Video {index} has audio after a "+ "silent earlier video. Reorder the videos so ones with soundtracks "+ "come first, or add a replacement soundtrack to each earlier video."+ )+ decoded_audios = tuple(+ decode_h3_reference_audio(_decode_b64_media(item)) for item in audios+ )+ return MiniMaxH3References(+ images = fitted_images,+ videos = tuple(decoded_videos),+ audios = decoded_audios,+ )++ def _generate_h3_native(+ self,+ *,+ state: _VideoLoadState,+ prompt: str,+ width: int,+ height: int,+ frames: int,+ fps: int,+ steps: int,+ guidance: float,+ seed: Optional[int],+ # Canvas-fitted keyframes, and the task name they add up to (see _resolve_keyframes).+ first_frame: Any,+ last_frame: Any,+ references: Any,+ conditioning: str,+ flow_shift: Optional[float],+ cancel: threading.Event,+ ) -> dict[str, Any]:+ import random+ import re++ from .sd_cpp_args import SdCppVideoGenParams+ from .sd_cpp_engine import SdCppCancelled+ from .video_minimax_h3 import (+ inspect_video,+ stage_h3_references,+ transcode_video_to_mp4,+ )++ runtime = state.pipe+ if seed is None:+ seed = random.SystemRandom().randrange(0, 2**53)+ started = time.monotonic()+ self._gen = {+ "active": True,+ "phase": "denoise",+ "step": 0,+ "total": steps,+ "started": started,+ "eta_seconds": None,+ "error": None,+ }+ # sd.cpp reuses an unlabeled bar for loading, denoising, and VAE work. Count only+ # iteration-rated bars inside its denoise window.+ denoise_open = re.compile(r"generate_video\s+\d+x\d+x\d+")+ denoise_close = re.compile(r"sampling completed", re.IGNORECASE)+ step_bar = re.compile(r"\|\s*(\d+)\s*/\s*(\d+)\s*-\s*[\d.]+\s*(?:it/s|s/it)")+ denoising = False++ def on_log(line: str) -> None:+ nonlocal denoising+ if denoise_open.search(line):+ denoising = True+ return+ if denoise_close.search(line):+ denoising = False+ # sd.cpp still has to decode both latent streams and write its+ # intermediate video. Do not leave the UI at a completed denoise bar.+ self._gen.update(phase = "decode", eta_seconds = None)+ return+ match = step_bar.search(line) if denoising else None+ if match is None:+ return+ done, total = int(match.group(1)), int(match.group(2))+ elapsed = time.monotonic() - started+ self._gen.update(+ step = done,+ total = total,+ eta_seconds = (elapsed / max(1, done)) * max(0, total - done),+ )++ tmp = tempfile.NamedTemporaryFile(suffix = ".webm", delete = False)+ tmp.close()+ output_path = Path(tmp.name)+ # Stage in-memory conditioning in sd-cli's temporary disk format.+ with tempfile.TemporaryDirectory(prefix = "unsloth-h3-keyframes-") as scratch:++ def stage(image: Any, name: str) -> Optional[str]:+ if image is None:+ return None+ path = Path(scratch) / f"{name}.png"+ image.save(path, format = "PNG")+ return str(path)++ init_img = stage(first_frame, "first")+ end_img = stage(last_frame, "last")+ staged = stage_h3_references(references, Path(scratch))+ try:+ try:+ generated = runtime.engine.generate_video(+ runtime.files,+ SdCppVideoGenParams(+ prompt = prompt,+ width = width,+ height = height,+ num_frames = frames,+ fps = fps,+ steps = steps,+ cfg_scale = 1.0,+ seed = int(seed),+ init_img = init_img,+ end_img = end_img,+ ref_images = staged.images,+ ref_videos = staged.videos,+ ref_video_audios = staged.video_audios,+ ref_audios = staged.audios,+ flow_shift = flow_shift,+ ),+ output_path = str(output_path),+ offload = list(runtime.offload_flags),+ on_log = on_log,+ cancel_event = cancel,+ )+ except SdCppCancelled:+ raise RuntimeError(VIDEO_CANCELLED_MSG) from None+ if cancel.is_set():+ raise RuntimeError(VIDEO_CANCELLED_MSG)+ self._gen.update(phase = "export", eta_seconds = None)+ actual_width, actual_height, actual_frames, has_audio = inspect_video(generated)+ mp4_bytes = transcode_video_to_mp4(generated, fps = fps)+ if cancel.is_set():+ raise RuntimeError(VIDEO_CANCELLED_MSG)+ self._gen = {"active": False}+ return {+ "mp4_bytes": mp4_bytes,+ "seed": int(seed),+ "repo_id": state.repo_id,+ "width": actual_width,+ "height": actual_height,+ "num_frames": actual_frames,+ "fps": fps,+ "duration_s": actual_frames / float(fps),+ "has_audio": has_audio,+ "conditioning": conditioning,+ "steps": steps,+ "guidance": guidance,+ "flow_shift": flow_shift,+ # sd.cpp pins the audio schedule, so the recipe records what it actually ran.+ "audio_flow_shift": state.family.default_audio_flow_shift,+ }+ finally:+ output_path.unlink(missing_ok = True)++ @staticmethod+ def _encode_mp4(+ video_frames,+ fps: int,+ audio,+ pipe,+ *,+ audio_sample_rate: Optional[int] = None,+ ) -> bytes:"""Encode frames (+ optional audio) to H.264 MP4 bytes via diffusers' PyAVexporter. A temp file bridges the exporter's path-based API; the bytes arewhat the gallery persists."""@@ -2395,7 +3728,7 @@ class VideoBackend:encode_kwargs: dict[str, Any] = {}if audio is not None and pipe is not None:encode_kwargs["audio"] = audio- sample_rate = getattr(+ sample_rate = audio_sample_rate or getattr(getattr(getattr(pipe, "vocoder", None), "config", None),"output_sampling_rate",None,@@ -2502,6 +3835,7 @@ class VideoBackend:"device": None,"dtype": None,"model_kind": None,+ "engine": None,"gguf_variant": None,"offload_policy": None,"vae_tiling": False,@@ -2513,6 +3847,10 @@ class VideoBackend:"transformer_quant": None,"text_encoder_quant": None,"has_audio": False,+ "supports_cfg": True,+ "supports_keyframes": False,+ "supports_references": False,+ "h3_task": None,"defaults": None,"resolved": None,}@@ -2533,6 +3871,7 @@ class VideoBackend:"device": state.device,"dtype": state.dtype,"model_kind": state.kind,+ "engine": state.engine,# As on the image runtime: dtype is compute precision, which labelled a Q4_K_M BF16."gguf_variant": (extract_quant_token(state.gguf_filename)@@ -2549,14 +3888,29 @@ class VideoBackend:"transformer_quant": state.transformer_quant,"text_encoder_quant": state.text_encoder_quant,"has_audio": fam.has_audio,+ "supports_cfg": fam.supports_cfg,+ # Expose only conditioning supported by the resident partition.+ "supports_keyframes": fam.supports_keyframes and state.h3_task != H3_TASK_REFERENCES,+ "supports_references": fam.supports_references and state.h3_task == H3_TASK_REFERENCES,+ "h3_task": state.h3_task,"defaults": {"steps": default_steps,"guidance": default_guidance,"num_frames": fam.default_num_frames,"fps": fam.default_fps,"frame_step": fam.frame_step,+ "frame_offset": fam.frame_offset,+ "duration_presets": list(fam.duration_presets),"resolution_multiple": fam.resolution_multiple,"resolution_presets": [list(p) for p in fam.resolution_presets],+ # Let the frontend preview the backend-owned "match source" rule.+ "canvas_short_edge": H3_CANVAS_SHORT_EDGE if fam.supports_keyframes else None,+ "canvas_max_pixels": H3_CANVAS_MAX_PIXELS if fam.supports_keyframes else None,+ "flow_shift": fam.default_flow_shift,+ "audio_flow_shift": fam.default_audio_flow_shift,+ # sd.cpp has no flag for the audio shift, so the control is only real on Diffusers.+ "supports_audio_flow_shift": fam.default_audio_flow_shift is not None+ and state.engine != "sd_cpp",},"resolved": state.resolved,}diff --git a/studio/backend/core/inference/video_families.py b/studio/backend/core/inference/video_families.pyindex a6b709dc36b..46252edfd03 100644--- a/studio/backend/core/inference/video_families.py+++ b/studio/backend/core/inference/video_families.py@@ -52,16 +52,23 @@ class VideoFamily:cfg2_kwarg: Optional[str] = None# HunyuanVideo-1.5 guidance: __call__ takes NO guidance kwarg; CFG lives on a ``guider`` whose scale is set per request.guidance_via_guider: bool = False- # Generation defaults + shape. ``frame_step`` is the temporal compression: a valid frame count is k*frame_step + 1.+ # Generation defaults + shape. A valid frame count is k*frame_step + frame_offset.default_steps: int = 40default_guidance: float = 4.0default_num_frames: int = 121default_fps: int = 24frame_step: int = 8+ # Offset in the temporal lattice. Existing pipelines use k*step+1; MiniMax-H3 uses 17k+5.+ frame_offset: int = 1+ min_num_frames: int = 1+ max_num_frames: Optional[int] = None+ snap_frames_up: bool = False# Width/height must be divisible by this (LTX-2's pipeline rejects non-/32).resolution_multiple: int = 32# (width, height) UI presets, landscape first; the first is the default.resolution_presets: tuple[tuple[int, int], ...] = ((768, 512),)+ # Clip lengths offered by the UI. Most families use short previews; H3 is trained for 5-15 seconds.+ duration_presets: tuple[float, ...] = (1.0, 2.0, 3.0, 5.0)# Component bf16-RESIDENT sizes in decimal GB (denoiser(s), text encoder, VAE + audio): what sits on device after the cast.bf16_components_gb: Optional[tuple[float, float, float]] = None# True when the DiT compiles cleanly with regional torch.compile (declares _repeated_blocks).@@ -74,9 +81,81 @@ class VideoFamily:gguf_repo: Optional[str] = None# Hosted PRE-CAST text-encoder checkpoints as (scheme, component, repo_id); same semantics as DiffusionFamily.te_prequant_repos.te_prequant_repos: tuple[tuple[str, str, str], ...] = field(default_factory = tuple)+ # Hosted PRE-QUANTIZED DENOISER checkpoints as (scheme, repo_id). The DiT, NOT the text+ # encoder that te_prequant_repos above covers: the two are separate artifacts because a load+ # can take one without the other. Same semantics as DiffusionFamily.prequant_repos, so the+ # shared diffusion_prequant resolver reads this table through plain attribute access.+ prequant_repos: tuple[tuple[str, str], ...] = field(default_factory = tuple)+ # Per-variant overrides as (base_repo, scheme, repo_id), keyed on the LOWERCASED upstream base+ # id. A pre-quantized checkpoint is baked from ONE base's weights and the loader refuses it for+ # any other base, so a variant that ships its own denoiser needs its own entry; a variant+ # without one falls through to prequant_repos and, if that checkpoint was baked elsewhere, the+ # loader's base_model_id check sends the load back to the dense path.+ prequant_variant_repos: tuple[tuple[str, str, str], ...] = field(default_factory = tuple)+ # Modular Diffusers workflow to load instead of a conventional DiffusionPipeline. Its+ # components are loaded without pruning the workflow's routing blocks.+ modular_workflow: Optional[str] = None+ # Released video and audio sigma shifts, when configurable.+ default_flow_shift: Optional[float] = None+ default_audio_flow_shift: Optional[float] = None+ # First/last-frame conditioning: the request may carry keyframe images.+ supports_keyframes: bool = False+ # Omni-reference conditioning. MiniMax-H3 loads this in a separate denoiser partition.+ supports_references: bool = False+ # Guidance-distilled families expose neither CFG nor a negative prompt.+ supports_cfg: bool = True_FAMILIES: tuple[VideoFamily, ...] = (+ # FL2VA covers text-only and keyframe generation. Ref2VA is a separate partition.+ VideoFamily(+ name = "minimax-h3",+ pipeline_class = "ModularPipeline",+ transformer_class = "MiniMaxH3Transformer3DModel",+ base_repo = "MiniMaxAI/MiniMax-H3",+ aliases = ("minimax_h3", "minimaxh3", "h3"),+ has_audio = True,+ default_steps = 30,+ default_guidance = 1.0,+ default_num_frames = 124,+ default_fps = 24,+ frame_step = 17,+ frame_offset = 5,+ min_num_frames = 124,+ max_num_frames = 345,+ snap_frames_up = True,+ resolution_multiple = 32,+ # Model-card ratios use H3's canvas rule. Keep the legacy 1024 square and cheaper+ # 16:9 tiers for compatibility.+ resolution_presets = (+ (1344, 768), # 16:9+ (1536, 672), # 21:9+ (1024, 768), # 4:3+ (1024, 1024), # 1:1+ (768, 1024), # 3:4+ (768, 1344), # 9:16+ (960, 544), # 16:9, faster+ (544, 960), # 9:16, faster+ ),+ duration_presets = (5.0, 10.0, 14.4),+ # Decimal GB resident estimates: transformer, Qwen3-VL conditioner, video+audio VAEs.+ bf16_components_gb = (66.3, 66.8, 11.1),+ supports_torch_compile = False,+ gguf_repo = "unsloth/MiniMax-H3-GGUF",+ # Hosted pre-quantized FL2VA denoisers. The modular workflow builds each component through+ # its own from_pretrained, so there is no dense module to quantise in place: these are the+ # ONLY way to run the 66.3 GB transformer quantized, and seeding one also stops that+ # download. Both schemes live in ONE repo, at the root, named <Model>-<SCHEME>.pt, which is+ # the layout every image-side prequant repo already uses and the one prequant_repo_filename+ # builds without help.+ prequant_repos = (("int8", "unsloth/MiniMax-H3-FP8"), ("fp8", "unsloth/MiniMax-H3-FP8")),+ modular_workflow = "fl2va",+ default_flow_shift = 12.0,+ default_audio_flow_shift = 3.0,+ supports_keyframes = True,+ supports_references = True,+ supports_cfg = False,+ ),# LTX-2 (diffusers >= 0.39): ~19B single-stream video DiT generating synchronized audio + video in one pass. The Gemma3-12B# encoder is stored fp32 on the hub (~49 GB download, ~24 GB resident bf16). The base repo carries the dev config (40 steps, CFG 4).VideoFamily(@@ -252,15 +331,83 @@ def resolve_video_base_repo(fam: VideoFamily, base_repo: Optional[str]) -> str:return base or fam.base_repo+def _prequant_base_key(repo_id: Optional[str]) -> str:+ """The lookup key ``prequant_variant_repos`` is written against: trimmed and lowercased.++ Deliberately local rather than reusing ``diffusion_families.canonical_base``: this module+ header keeps the two registries apart so neither picker can reach the other's tables, and the+ image mirror map holds image repos only, so importing it would buy nothing but the coupling.+ """+ return (repo_id or "").strip().lower()+++def video_family_prequant_repo(+ fam: VideoFamily,+ scheme: str,+ base_repo: Optional[str] = None,+) -> Optional[str]:+ """The hosted pre-quantized DENOISER repo for ``scheme`` in this family, or None.++ Mirrors ``diffusion_families.family_prequant_repo``: ``base_repo`` (when known) selects a+ variant-specific checkpoint first, then the family default. Pure -- no IO, no torch -- so+ validation and download planning can both ask before anything is downloaded.++ Reads the tables through ``getattr`` and skips malformed rows instead of raising: this runs on+ the refusal path of a load request, and a table typo must not turn a legitimate pick into a+ 500. A family object that predates these fields simply has no hosted checkpoint.+ """+ base = _prequant_base_key(base_repo)+ if base:+ for entry in getattr(fam, "prequant_variant_repos", ()) or ():+ if not isinstance(entry, (tuple, list)) or len(entry) != 3:+ continue+ entry_base, entry_scheme, repo_id = entry+ if _prequant_base_key(entry_base) == base and entry_scheme == scheme and repo_id:+ return repo_id+ for entry in getattr(fam, "prequant_repos", ()) or ():+ if not isinstance(entry, (tuple, list)) or len(entry) != 2:+ continue+ entry_scheme, repo_id = entry+ if entry_scheme == scheme and repo_id:+ return repo_id+ return None+++def video_family_prequant_schemes(fam: VideoFamily) -> tuple[str, ...]:+ """Every scheme this family has a hosted denoiser checkpoint for, in table order.++ Used to name the workable schemes in a refusal message, so a rejected request tells the caller+ what to pick instead of only what failed. Malformed rows are skipped, as above."""+ schemes: list[str] = []+ for entry in getattr(fam, "prequant_repos", ()) or ():+ if isinstance(entry, (tuple, list)) and len(entry) == 2 and entry[0] not in schemes:+ schemes.append(entry[0])+ for entry in getattr(fam, "prequant_variant_repos", ()) or ():+ if isinstance(entry, (tuple, list)) and len(entry) == 3 and entry[1] not in schemes:+ schemes.append(entry[1])+ return tuple(schemes)++def snap_num_frames(fam: VideoFamily, num_frames: int) -> int:- """The nearest valid frame count at or below the request (k * frame_step + 1).+ """The nearest valid frame count at or below the request (k * step + offset).Video latents are allocated as (num_frames - 1) / temporal_compression + 1, soan off-lattice count wastes a partial latent frame at best and trips shapechecks at worst; snapping mirrors the image path's silent /16 size snap."""step = max(1, fam.frame_step)- return max(1, ((max(1, num_frames) - 1) // step) * step + 1)+ offset = max(1, fam.frame_offset)+ requested = max(offset, fam.min_num_frames, num_frames)+ if fam.max_num_frames is not None:+ requested = min(requested, fam.max_num_frames)+ delta = requested - offset+ if fam.snap_frames_up:+ snapped = ((delta + step - 1) // step) * step + offset+ else:+ snapped = (delta // step) * step + offset+ if fam.max_num_frames is not None:+ snapped = min(snapped, fam.max_num_frames)+ return max(offset, fam.min_num_frames, snapped)def snap_video_size(fam: VideoFamily, width: int, height: int) -> tuple[int, int]:@@ -324,23 +471,36 @@ def validate_video_request_shape(f"Supported resolutions: {format_video_resolution_presets(fam)}.")if num_frames is not None:+ # The lattice is k * frame_step + frame_offset, NOT a hardcoded k * step + 1: most families+ # do sit at offset 1, but MiniMax-H3 is 17k + 5, and judging it against 17k + 1 would refuse+ # every count its own duration select offers, starting with its default of 124. Read the two+ # fields snap_num_frames reads, so the gate and the snap can never disagree about what is valid.step = max(1, fam.frame_step)+ offset = max(1, fam.frame_offset)count = int(num_frames)- if count < 1 or (count - 1) % step != 0:- # The two lattice points straddling the request say more than a prefix of the lattice would, and stay short.- below = snap_num_frames(fam, count)+ if count < offset or (count - offset) % step != 0:+ # The two lattice points straddling the request say more than a prefix of the lattice would,+ # and stay short. Computed from the lattice rather than via snap_num_frames, which floors for+ # some families and CEILS for others (snap_frames_up) and so cannot be relied on for "below".+ below = offset + max(0, (count - offset) // step) * stepabove = below + step- # ...but only name the upper one if the request model would accept it. Near the ceiling- # (1018-1024 on an 8-step family) it lands past `le`, and advising a count that answers- # with a second, differently-shaped 422 is worse than naming one that works.- nearest = (- f"the nearest supported counts are {below} and {above}"- if above <= MAX_VIDEO_NUM_FRAMES- else f"the nearest supported count is {below}"- )+ # Only name a point the caller could actually load: past the request model's own `le`, or+ # outside this family's declared range, it answers with a second, differently-shaped 422.+ ceiling = MAX_VIDEO_NUM_FRAMES+ if fam.max_num_frames is not None:+ ceiling = min(ceiling, int(fam.max_num_frames))+ floor = max(offset, int(fam.min_num_frames))+ loadable = [n for n in (below, above) if floor <= n <= ceiling]+ if len(loadable) == 2:+ nearest = f"the nearest supported counts are {loadable[0]} and {loadable[1]}"+ elif len(loadable) == 1:+ nearest = f"the nearest supported count is {loadable[0]}"+ else:+ # The request is outside the family's whole range; point at the range instead.+ nearest = f"supported counts run from {floor} to {ceiling}"raise VideoShapeError(f"{count} is not a supported frame count for {fam.name}. Its VAE compresses time by "- f"{step}, so a frame count must be k * {step} + 1; {nearest} "+ f"{step}, so a frame count must be k * {step} + {offset}; {nearest} "f"(the default is {fam.default_num_frames}).")diff --git a/studio/backend/core/inference/video_minimax_h3.py b/studio/backend/core/inference/video_minimax_h3.pynew file mode 100644index 00000000000..f3160197873--- /dev/null+++ b/studio/backend/core/inference/video_minimax_h3.py@@ -0,0 +1,659 @@+# 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 helpers shared by the Diffusers and stable-diffusion.cpp paths."""++from __future__ import annotations++import math+import tempfile+from dataclasses import dataclass+from pathlib import Path+from typing import Any, Optional++# Must stay equal to the minimax-h3 family's `gguf_repo`. They are the same one-click pick, and+# main's test_curated_gguf_repos_are_unsloth_mirrors only checks the family field, so a divergence+# here would let that test pass while the actual download still came from a community repack.+# tests/test_video_backend.py::test_the_h3_native_repo_matches_the_family_gguf_repo pins the pair.+# The mirror carries the Qwen3-VL encoder quants as well as the denoisers, so this repo alone+# satisfies h3_native_hub_files' first two entries.+H3_GGUF_REPO = "unsloth/MiniMax-H3-GGUF"+H3_COMPONENT_REPO = "Comfy-Org/MiniMax-H3"+H3_VIDEO_VAE = "vae/minimax_h3_video_vae_fp16.safetensors"+H3_AUDIO_VAE = "vae/minimax_h3_audio_vae_fp32.safetensors"+H3_QWEN_Q2 = "qwen3vl_32b_minimax_h3-Q2_K_M.gguf"+H3_QWEN_Q4 = "qwen3vl_32b_minimax_h3-Q4_K_M.gguf"++# Measured with the merged Diffusers T2VA workflow and component-level CPU+# offload. The base is the largest component plus runtime overhead; activation+# memory scales with spatiotemporal volume across the tested 960x544 and+# 1344x768, 124-345 frame matrix. The guard covers allocator variation around+# the measured success and OOM boundaries.+H3_DIFFUSERS_VRAM_BASE_GB = 68.5+H3_DIFFUSERS_VRAM_GB_PER_MPIXEL_FRAME = 0.08+++def estimate_h3_diffusers_vram_gb(width: int, height: int, num_frames: int) -> float:+ """Measured available-VRAM floor for an H3 Diffusers generation."""+ volume_mpixel_frames = width * height * num_frames / 1_000_000+ return H3_DIFFUSERS_VRAM_BASE_GB + (+ H3_DIFFUSERS_VRAM_GB_PER_MPIXEL_FRAME * volume_mpixel_frames+ )+++def estimate_h3_diffusers_host_ram_gb(available_vram_gb: float) -> float:+ """Host-RAM floor for the offload tier selected at the available VRAM."""+ return 85.0 if available_vram_gb >= 132.0 else 150.0+++# torch.autocast casts the weight and bias of these module types to the autocast dtype on+# entry. Norms sit on autocast's float32 promote list and bare parameters are read directly,+# so both must keep their source precision.+_AUTOCAST_WEIGHT_MODULE_NAMES = ("Linear", "Conv1d", "Conv2d", "Conv3d")+++def _module_bytes(module: Any) -> int:+ seen: set[int] = set()+ total = 0+ for tensor in list(module.parameters()) + list(module.buffers()):+ if id(tensor) in seen:+ continue+ seen.add(id(tensor))+ total += tensor.numel() * tensor.element_size()+ return total+++def trim_h3_video_vae(vae: Any, *, workflow: str) -> dict[str, int]:+ """Drop what the H3 video VAE cannot use and pre-cast what autocast casts anyway.++ Two thirds of an H3 render's peak is not activations. Measured at 640x384 across 124+ frames, a 20.25 GB int8 denoiser peaks at 36.96 GB, and the gap is almost all weights:+ the video VAE alone is 10.42 GB because diffusers pins it to float32, and a further+ 4.91 GB is autocast's own float16 copy of those weights.++ ``MiniMaxH3VideoDecodeStep`` wraps ``vae.decode`` in ``torch.autocast(float16)``. Autocast+ casts every Linear and Conv weight it meets and caches the copy for the lifetime of the+ region, so the float32 original and its float16 twin are both resident through the whole+ decode. Storing those weights as float16 up front makes the cast a no-op and removes both:+ ``x.to(float16).to(float16)`` is ``x.to(float16)``, so the arithmetic is unchanged rather+ than merely close. The audio VAE decode is NOT under autocast, so it is left alone.++ The encoder half goes only for a workflow that never encodes. ``t2va`` starts from noise,+ so ``vae.encoder`` and ``vae.quant_conv`` are dead weight; a future image-conditioned+ workflow needs them, hence the explicit check rather than an unconditional drop.++ Returns a byte report for the caller to log. Never raises: a diffusers release that+ renames these attributes should cost the saving, not the render.+ """+ import torch++ # Every lookup below is a getattr with a default, so a None vae and a vae whose+ # attributes moved both fall through to a zero report without a separate guard.+ report = {"encoder_freed": 0, "decoder_freed": 0}++ if workflow == "t2va":+ for name in ("encoder", "quant_conv"):+ module = getattr(vae, name, None)+ if module is None:+ continue+ report["encoder_freed"] += _module_bytes(module)+ setattr(vae, name, None)++ for holder in ("decoder", "post_quant_conv"):+ module = getattr(vae, holder, None)+ if module is None:+ continue+ before = _module_bytes(module)+ for sub in module.modules():+ if type(sub).__name__ not in _AUTOCAST_WEIGHT_MODULE_NAMES:+ continue+ for name, param in list(sub.named_parameters(recurse = False)):+ if param.dtype is not torch.float32:+ continue+ setattr(+ sub,+ name,+ torch.nn.Parameter(param.data.to(torch.float16), requires_grad = False),+ )+ report["decoder_freed"] += before - _module_bytes(module)++ return report+++# ── canvas geometry ──────────────────────────────────────────────────────────+#+# MiniMax-H3's upstream canvas rule, shared by both engines.+H3_CANVAS_SHORT_EDGE = 768+H3_CANVAS_MAX_PIXELS = 768 * 1344+H3_CANVAS_MULTIPLE = 32+# Trained aspect-ratio range.+H3_MIN_ASPECT_RATIO = 1 / 4+H3_MAX_ASPECT_RATIO = 4++# Upstream stretches the first frame and center cover-crops the last.+H3_ANCHOR_FIRST = "first"+H3_ANCHOR_LAST = "last"+++def h3_canvas_for_aspect(aspect_width: float, aspect_height: float) -> tuple[int, int]:+ """Resolve MiniMax-H3's canvas for an aspect ratio.++ Raises ValueError outside the trained 1:4 to 4:1 range.+ """+ if aspect_width <= 0 or aspect_height <= 0:+ raise ValueError(+ f"The source image has no usable aspect ratio ({aspect_width}x{aspect_height})."+ )+ ratio = aspect_width / aspect_height+ if not H3_MIN_ASPECT_RATIO <= ratio <= H3_MAX_ASPECT_RATIO:+ raise ValueError(+ f"MiniMax-H3 supports aspect ratios from 1:4 to 4:1; this image is "+ f"{aspect_width:g}x{aspect_height:g} ({ratio:.2f}:1). Crop it first."+ )+ if ratio >= 1.0:+ width, height = H3_CANVAS_SHORT_EDGE * ratio, float(H3_CANVAS_SHORT_EDGE)+ else:+ width, height = float(H3_CANVAS_SHORT_EDGE), H3_CANVAS_SHORT_EDGE / ratio+ area = width * height+ if area > H3_CANVAS_MAX_PIXELS:+ scale = math.sqrt(H3_CANVAS_MAX_PIXELS / area)+ width, height = width * scale, height * scale+ snap = lambda v: max( # noqa: E731+ H3_CANVAS_MULTIPLE, round(v / H3_CANVAS_MULTIPLE) * H3_CANVAS_MULTIPLE+ )+ return snap(width), snap(height)+++def fit_h3_keyframe(image: Any, width: int, height: int, *, anchor: str) -> Any:+ """Fit a keyframe using MiniMax-H3's asymmetric first/last-frame rules."""+ from PIL import Image++ target = (max(1, int(width)), max(1, int(height)))+ if anchor == H3_ANCHOR_FIRST:+ return image.resize(target, Image.LANCZOS)+ if anchor != H3_ANCHOR_LAST:+ raise ValueError(f"Unknown keyframe anchor {anchor!r}.")+ source_w, source_h = image.size+ scale = max(target[0] / source_w, target[1] / source_h)+ crop_w = min(source_w, math.ceil(target[0] / scale))+ crop_h = min(source_h, math.ceil(target[1] / scale))+ left = (source_w - crop_w) // 2+ top = (source_h - crop_h) // 2+ return image.resize(target, Image.LANCZOS, box = (left, top, left + crop_w, top + crop_h))+++# ── omni references (Ref2VA) ─────────────────────────────────────────────────+#+# Ref2VA uses a separate transformer partition selected at load time.+H3_TASK_KEYFRAMES = "fl2va"+H3_TASK_REFERENCES = "ref2va"++# Upstream request limits.+H3_MAX_REF_IMAGES = 9+H3_MAX_REF_VIDEOS = 3+H3_MAX_REF_AUDIOS = 3+H3_MAX_REFERENCES = 12+# A reference video's trained window, in seconds.+H3_REF_VIDEO_MIN_SECONDS = 2.0+H3_REF_VIDEO_MAX_SECONDS = 15.0+H3_FPS = 24++# "match" uses the generation area. Diffusers-only "max" uses a 2048px short edge.+H3_REF_SIZE_MATCH = "match"+H3_REF_SIZE_MAX = "max"+H3_REF_IMAGE_SHORT_EDGE = 2048+++def h3_transformer_task(filename: str) -> str:+ """Which H3 task a picked GGUF denoiser serves, from its published name."""+ name = Path(filename).name.lower()+ return H3_TASK_REFERENCES if name.startswith("minimax_h3_ref2va") else H3_TASK_KEYFRAMES+++def fit_h3_reference_image(image: Any, *, width: int, height: int, policy: str) -> Any:+ """Scale a reference to its policy limit without changing its aspect ratio or upscaling."""+ from PIL import Image++ source_w, source_h = image.size+ if policy == H3_REF_SIZE_MAX:+ scale = min(1.0, H3_REF_IMAGE_SHORT_EDGE / max(1, min(source_w, source_h)))+ elif policy == H3_REF_SIZE_MATCH:+ scale = min(1.0, math.sqrt((width * height) / max(1, source_w * source_h)))+ else:+ raise ValueError(f"Unknown reference image size policy {policy!r}.")+ snap = lambda v: max( # noqa: E731+ H3_CANVAS_MULTIPLE, round(v * scale / H3_CANVAS_MULTIPLE) * H3_CANVAS_MULTIPLE+ )+ return image.resize((snap(source_w), snap(source_h)), Image.LANCZOS)+++def h3_reference_frame_size(source_w: int, source_h: int) -> tuple[int, int]:+ """Resolve a reference-video frame size without upscaling."""+ width, height = h3_canvas_for_aspect(source_w, source_h)+ if source_w * source_h < width * height:+ snap = lambda v: max( # noqa: E731+ H3_CANVAS_MULTIPLE, round(v / H3_CANVAS_MULTIPLE) * H3_CANVAS_MULTIPLE+ )+ width, height = snap(source_w), snap(source_h)+ return width, height+++def decode_h3_reference_video(blob: bytes) -> tuple[list, Optional[Any], Optional[int]]:+ """Decode one uploaded video to 24 fps frames plus its soundtrack, if it carries one.++ Returns ``(frames, waveform, sample_rate)``. The frames land on MiniMax-H3's own 24 fps by+ whole-frame drop and duplicate -- the selection ffmpeg's fps filter made in the reference+ implementation, and the one the Diffusers blocks make from a declared rate -- so both+ engines receive a stream that is already on the model's clock. The waveform is float32+ ``(samples, channels)`` at the container's own rate; both engines resample it themselves.+ """+ import io++ import av+ import numpy as np++ with av.open(io.BytesIO(blob)) as container:+ if not container.streams.video:+ raise ValueError("That reference file carries no video track.")+ stream = container.streams.video[0]+ source_fps = float(stream.average_rate or stream.guessed_rate or H3_FPS)+ if source_fps <= 0:+ source_fps = float(H3_FPS)+ # Select, resample, and resize incrementally to bound memory for 4K inputs.+ from PIL import Image++ frames = []+ decoded_count = 0+ next_target = 0+ fitted_size = None+ max_source_frames = math.floor(H3_REF_VIDEO_MAX_SECONDS * source_fps + 1e-6)+ for source_index, frame in enumerate(container.decode(video = 0)):+ decoded_count = source_index + 1+ if decoded_count > max_source_frames:+ raise ValueError(+ f"MiniMax-H3 reference videos run {H3_REF_VIDEO_MIN_SECONDS:g} to "+ f"{H3_REF_VIDEO_MAX_SECONDS:g} seconds; this one is longer than "+ f"{H3_REF_VIDEO_MAX_SECONDS:g}s. Trim it first."+ )+ target_source = int(next_target * source_fps / H3_FPS)+ if target_source > source_index:+ continue+ image = frame.to_image().convert("RGB")+ if fitted_size is None:+ fitted_size = h3_reference_frame_size(*image.size)+ if image.size != fitted_size:+ image = image.resize(fitted_size, Image.LANCZOS)+ while int(next_target * source_fps / H3_FPS) <= source_index:+ frames.append(image)+ next_target += 1++ if decoded_count == 0:+ raise ValueError("That reference video decoded to no frames.")+ duration = decoded_count / source_fps+ if duration + 1e-6 < H3_REF_VIDEO_MIN_SECONDS:+ raise ValueError(+ f"MiniMax-H3 reference videos run {H3_REF_VIDEO_MIN_SECONDS:g} to "+ f"{H3_REF_VIDEO_MAX_SECONDS:g} seconds; this one is {duration:.1f}s."+ )+ frames = frames[: int(round(duration * H3_FPS))]++ waveform, sample_rate = (None, None)+ with av.open(io.BytesIO(blob)) as container:+ if container.streams.audio:+ waveform, sample_rate = _decode_audio_stream(container, np)+ return frames, waveform, sample_rate+++def decode_h3_reference_audio(blob: bytes) -> tuple[Any, int]:+ """Decode one uploaded audio file to a float32 ``(samples, channels)`` waveform + its rate."""+ import io++ import av+ import numpy as np++ with av.open(io.BytesIO(blob)) as container:+ if not container.streams.audio:+ raise ValueError("That reference file carries no audio track.")+ waveform, sample_rate = _decode_audio_stream(container, np)+ if waveform is None:+ raise ValueError("That reference audio decoded to no samples.")+ return waveform, sample_rate+++def _decode_audio_stream(container: Any, np: Any) -> tuple[Optional[Any], Optional[int]]:+ """The container's first audio stream as float32 ``(samples, channels)`` at its own rate.++ Bounded while decoding, for the reason the video path above is: the encoded size says almost+ nothing about the decoded size. A 32 MiB request-limit MP3 is over half an hour of audio, which+ expands to ~1.9 GB of float32 here and doubles again in ``np.concatenate``, and three+ references are accepted per request. H3's reference window is+ ``H3_REF_VIDEO_MAX_SECONDS`` anyway, so anything past it is unusable rather than merely large:+ refuse it with the same message the video guard uses instead of decoding it first."""+ import av++ stream = container.streams.audio[0]+ sample_rate = int(stream.codec_context.sample_rate or 48_000)+ # One resampler pass gives interleaved float32 whatever the source layout/format was.+ resampler = av.AudioResampler(format = "flt", layout = stream.layout.name, rate = sample_rate)+ channels = len(stream.layout.channels)+ max_samples = math.floor(H3_REF_VIDEO_MAX_SECONDS * sample_rate + 1e-6)+ chunks = []+ total = 0++ def _take(resampled: Any) -> None:+ nonlocal total+ block = resampled.to_ndarray().reshape(-1, channels)+ total += block.shape[0]+ if total > max_samples:+ raise ValueError(+ f"MiniMax-H3 reference audio runs up to {H3_REF_VIDEO_MAX_SECONDS:g} seconds; "+ f"this one is longer. Trim it first."+ )+ chunks.append(block)++ for frame in container.decode(audio = 0):+ for resampled in resampler.resample(frame):+ _take(resampled)+ for resampled in resampler.resample(None):+ _take(resampled)+ if not chunks:+ return None, None+ return np.concatenate(chunks, axis = 0).astype("float32"), sample_rate+++def write_h3_reference_wav(path: Path, waveform: Any, sample_rate: int) -> None:+ """Write a reference waveform as the 16-bit PCM WAV sd-cli's --ref-audio loader reads."""+ import wave++ import numpy as np++ samples = np.clip(np.asarray(waveform, dtype = "float32"), -1.0, 1.0)+ if samples.ndim == 1:+ samples = samples[:, None]+ with wave.open(str(path), "wb") as handle:+ handle.setnchannels(int(samples.shape[1]))+ handle.setsampwidth(2)+ handle.setframerate(int(sample_rate))+ handle.writeframes((samples * 32767.0).astype("<i2").tobytes())+++@dataclass(frozen = True)+class MiniMaxH3References:+ """Decoded references in model order: images, videos, then standalone audio."""++ # Canvas-sized reference images, in <Picture i> order.+ images: tuple = ()+ # (frames, waveform, sample_rate) per <Video k>; waveform is None when silent.+ videos: tuple = ()+ # (waveform, sample_rate) per standalone reference, in <Audio j> order.+ audios: tuple = ()++ def __bool__(self) -> bool:+ return bool(self.images or self.videos or self.audios)++ def count(self) -> int:+ return len(self.images) + len(self.videos) + len(self.audios)+++@dataclass(frozen = True)+class MiniMaxH3StagedReferences:+ """``MiniMaxH3References`` written to disk the way sd-cli reads them back."""++ images: tuple[str, ...] = ()+ # Frame DIRECTORIES: sd-cli reads a reference video as images sorted lexicographically.+ videos: tuple[str, ...] = ()+ video_audios: tuple[str, ...] = ()+ audios: tuple[str, ...] = ()+++def stage_h3_references(+ references: MiniMaxH3References, scratch: Path+) -> MiniMaxH3StagedReferences:+ """Stage references in sd-cli's positional file layout.++ Video soundtracks must form a prefix because sd-cli pairs them by index.+ """+ images: list[str] = []+ for index, image in enumerate(references.images):+ path = scratch / f"ref-image-{index:02d}.png"+ image.save(path, format = "PNG")+ images.append(str(path))++ videos: list[str] = []+ video_audios: list[str] = []+ pairing_holds = True+ for index, (frames, waveform, sample_rate) in enumerate(references.videos):+ directory = scratch / f"ref-video-{index:02d}"+ directory.mkdir()+ for frame_index, frame in enumerate(frames):+ frame.save(directory / f"{frame_index:05d}.png", format = "PNG")+ videos.append(str(directory))+ if waveform is None:+ # Positional pairing cannot express "skip this one", so stop pairing here.+ pairing_holds = False+ continue+ if not pairing_holds:+ raise ValueError(+ "stable-diffusion.cpp reference-video soundtracks must form a leading "+ "sequence without silent gaps."+ )+ path = scratch / f"ref-video-audio-{index:02d}.wav"+ write_h3_reference_wav(path, waveform, sample_rate)+ video_audios.append(str(path))++ audios: list[str] = []+ for index, (waveform, sample_rate) in enumerate(references.audios):+ path = scratch / f"ref-audio-{index:02d}.wav"+ write_h3_reference_wav(path, waveform, sample_rate)+ audios.append(str(path))++ return MiniMaxH3StagedReferences(+ images = tuple(images),+ videos = tuple(videos),+ video_audios = tuple(video_audios),+ audios = tuple(audios),+ )+++def h3_diffusers_references(references: MiniMaxH3References) -> list:+ """``MiniMaxH3References`` as the Diffusers blocks' reference dataclasses, same order.++ Every rate travels with its media: the frames are already on the model's 24 fps and each+ waveform carries the rate it was decoded at, so nothing is re-guessed downstream.+ """+ import torch+ from diffusers.modular_pipelines.minimax_h3 import (+ MiniMaxH3AudioReference,+ MiniMaxH3ImageReference,+ MiniMaxH3VideoReference,+ )++ def waveform_tensor(waveform: Any) -> Any:+ # The blocks take a (channels, samples) tensor; the decoder produces (samples, channels).+ return torch.from_numpy(waveform).transpose(0, 1).contiguous()++ built: list = []+ for image in references.images:+ built.append(MiniMaxH3ImageReference(image = image))+ for frames, waveform, sample_rate in references.videos:+ built.append(+ MiniMaxH3VideoReference(+ frames = list(frames),+ fps = float(H3_FPS),+ audio = None if waveform is None else waveform_tensor(waveform),+ sample_rate = sample_rate,+ )+ )+ for waveform, sample_rate in references.audios:+ built.append(+ MiniMaxH3AudioReference(audio = waveform_tensor(waveform), sample_rate = sample_rate)+ )+ return built+++def h3_conditioning_mode(+ *,+ has_first: bool = False,+ has_last: bool = False,+ has_references: bool = False,+) -> str:+ """The task name for one request's conditioning, as MiniMax-H3 and sd.cpp name them.++ Recorded on the gallery clip so a restored recipe says which workflow produced it, and+ used in messages, so the five spellings live in one place.+ """+ if has_references:+ return H3_TASK_REFERENCES+ if has_first and has_last:+ return H3_TASK_KEYFRAMES+ if has_first:+ return "i2va"+ if has_last:+ return "l2va"+ return "t2va"+++def is_h3_native(family: Any, kind: str) -> bool:+ return getattr(family, "name", None) == "minimax-h3" and kind == "gguf"+++def h3_text_encoder_filename(transformer_filename: str) -> str:+ return H3_QWEN_Q2 if "-q2_" in transformer_filename.lower() else H3_QWEN_Q4+++def validate_h3_transformer_filename(filename: str) -> None:+ """Accept either released denoiser partition, and nothing else from the same repo.++ FL2VA serves text-to-video and first/last-frame video; Ref2VA serves omni-reference video.+ Which one is picked IS the task, so both are valid picks -- but the Qwen3-VL encoder and the+ VAEs share the repo and are companions, never denoisers."""+ name = Path(filename).name.lower()+ partitions = ("minimax_h3_fl2va", "minimax_h3_ref2va")+ if not name.startswith(partitions) or not name.endswith(".gguf"):+ raise ValueError(+ "MiniMax-H3 needs a minimax_h3_fl2va*.gguf transformer (text-to-video and "+ "first/last-frame video) or a minimax_h3_ref2va*.gguf one (reference video). The "+ "Qwen encoder and the VAEs are companion models, not picks for either."+ )+++def h3_download_error(repo_id: str, filename: str, exc: Exception) -> Exception:+ """Turn a Hub download failure on an H3 component into something a user can act on.++ The Hub says "Repository Not Found ... make sure you are authenticated" for a repo that is+ private or gated as well as for one that genuinely does not exist. For H3 that message is+ actively misleading in both directions: the mirror is real, and the user's own token is+ usually fine. Name the repo, say which of the four components it was, and say what to do.++ Returns the exception to raise (never raises), so the caller keeps ``raise ... from exc`` and+ the original traceback survives. Anything that is not a recognised access error is passed back+ unchanged rather than reworded, so a timeout or a disk-full still reads as itself.+ """+ from huggingface_hub.errors import GatedRepoError, RepositoryNotFoundError++ if not isinstance(exc, (RepositoryNotFoundError, GatedRepoError)):+ return exc++ role = {+ H3_VIDEO_VAE: "video VAE",+ H3_AUDIO_VAE: "audio VAE",+ H3_QWEN_Q2: "text encoder",+ H3_QWEN_Q4: "text encoder",+ }.get(filename, "denoiser")+ gated = isinstance(exc, GatedRepoError)+ detail = (+ "accept its licence on the Hub, then set a token in Settings"+ if gated+ else "it may be private or not published yet, or your token may not cover it"+ )+ return RuntimeError(+ f"MiniMax-H3 could not download its {role} ({filename}) from {repo_id}: {detail}. "+ f"The other H3 components are unaffected."+ )+++def h3_native_hub_files(transformer_filename: str) -> tuple[tuple[str, str], ...]:+ validate_h3_transformer_filename(transformer_filename)+ return (+ (H3_GGUF_REPO, transformer_filename),+ (H3_GGUF_REPO, h3_text_encoder_filename(transformer_filename)),+ (H3_COMPONENT_REPO, H3_VIDEO_VAE),+ (H3_COMPONENT_REPO, H3_AUDIO_VAE),+ )+++@dataclass(frozen = True)+class MiniMaxH3NativeRuntime:+ engine: Any+ files: Any+ offload_flags: tuple[str, ...]+++def transcode_video_to_mp4(source: Path, *, fps: int) -> bytes:+ """Convert an sd.cpp WebM into a gallery-compatible H.264/AAC MP4.++ The native backend is available in Studio's no-torch runtime, so keep this+ export entirely in PyAV rather than routing decoded frames through Diffusers.+ """+ import av++ tmp = tempfile.NamedTemporaryFile(suffix = ".mp4", delete = False)+ tmp.close()+ target = Path(tmp.name)+ try:+ with av.open(str(source)) as src, av.open(str(target), mode = "w", format = "mp4") as dst:+ source_video = src.streams.video[0]+ output_video = dst.add_stream("libx264", rate = fps)+ output_video.width = int(source_video.codec_context.width)+ output_video.height = int(source_video.codec_context.height)+ output_video.pix_fmt = "yuv420p"++ source_audio = src.streams.audio[0] if src.streams.audio else None+ output_audio = None+ audio_resampler = None+ if source_audio is not None:+ sample_rate = int(source_audio.codec_context.sample_rate or 32000)+ output_audio = dst.add_stream("aac", rate = sample_rate)+ output_audio.layout = "stereo"+ audio_resampler = av.AudioResampler(+ format = "fltp", layout = "stereo", rate = sample_rate+ )++ selected = (source_video,) if source_audio is None else (source_video, source_audio)+ for packet in src.demux(*selected):+ for frame in packet.decode():+ if packet.stream.type == "video":+ for encoded in output_video.encode(frame):+ dst.mux(encoded)+ elif output_audio is not None and audio_resampler is not None:+ for resampled in audio_resampler.resample(frame):+ for encoded in output_audio.encode(resampled):+ dst.mux(encoded)++ if output_audio is not None and audio_resampler is not None:+ for resampled in audio_resampler.resample(None):+ for encoded in output_audio.encode(resampled):+ dst.mux(encoded)+ for encoded in output_video.encode():+ dst.mux(encoded)+ if output_audio is not None:+ for encoded in output_audio.encode():+ dst.mux(encoded)+ return target.read_bytes()+ finally:+ target.unlink(missing_ok = True)+++def inspect_video(path: Path) -> tuple[int, int, int, bool]:+ """Return width, height, decoded frame count, and audio presence."""+ import av++ with av.open(str(path)) as container:+ stream = container.streams.video[0]+ width = int(stream.codec_context.width)+ height = int(stream.codec_context.height)+ frames = int(stream.frames or 0)+ has_audio = bool(container.streams.audio)+ if frames <= 0:+ frames = sum(1 for _ in container.decode(video = 0))+ return width, height, frames, has_audiodiff --git a/studio/backend/core/inference/video_minimax_h3_adaln.py b/studio/backend/core/inference/video_minimax_h3_adaln.pynew file mode 100644index 00000000000..1052defeff9--- /dev/null+++ b/studio/backend/core/inference/video_minimax_h3_adaln.py@@ -0,0 +1,264 @@+# 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's PRUNED (curve-form) adaptive layer norm, for hosted pre-quantized denoisers.++MiniMax-H3 spends roughly 40% of its parameters on modulation. Every block owns an+``adaln_proj.linear`` of shape ``(6 * hidden_size * 3, time_embed_dim)`` = ``(96768, 2688)``, and+with 50 blocks plus ``norm_out`` that is ~26 GB of the 66 GB denoiser, all of it recomputed from a+timestep embedding that only ever takes one of a few dozen distinct values in a sampling run.++The reference ComfyUI implementation removes that redundancy. ``silu(time_embedder(t))``, viewed as+a function of ``t`` over a fixed 1025-point grid on ``[0, 1]``, is a smooth curve living in a+rank-8 affine subspace, so it factors as ``u(t) ~= mean + B @ c(t)`` with ``B`` of shape+``(2688, 8)`` and the 8 coordinates ``c(t)`` tabulated per grid point. Folding ``B`` into the+projection collapses each block's modulation to ``(96768, 8)``:++ dense: y = W_dense @ silu(temb) + b_dense+ curve: y = W_curve @ c(t) + b_curve, W_curve = W_dense @ B, b_curve = b_dense + W_dense @ mean++The factorization is AFFINE, not a pure rank-8 product: the bias absorbs the curve's mean. A key+rename that inherits ``b_dense`` is wrong by an order of magnitude. Nothing here re-derives the+factorization; the hosted checkpoints ship ``W_curve`` / ``b_curve`` / the table already fitted, and+this module only rebuilds the module shapes and the forward that consume them.++``MiniMaxH3Transformer3DModel`` cannot load that form as shipped: against the dense config it is 4+keys missing (``time_embedder.linear_1/linear_2.{weight,bias}``), 1 unexpected+(``time_embedder.table``) and 51 shape mismatches (every ``adaln_proj.linear.weight`` plus+``norm_out.linear.weight``, ``(*, 8)`` against ``(*, 2688)``). So a hosted pre-quantized H3 denoiser+is unloadable by every route until the model is reshaped to match, which is what+``apply_h3_adaln_curve`` does, in place, between ``from_config`` and ``load_state_dict``.++Two behavioural differences from the dense path, both load-bearing:++* No SiLU. The tabulated curve is the activation's OWN output projected onto the basis, so applying+ SiLU again would square the nonlinearity.+* The table is indexed by the RAW timestep, not by the Fourier features. ``time_proj`` is therefore+ bypassed (it is parameter-free, so the state dict is unaffected).+"""++from __future__ import annotations++import types+from typing import Any, Optional++# Video, text and audio rows each get their own modulation row, so one projection emits three+# blocks of six chunks. Mirrors diffusers' MINIMAX_H3_MODALITY_NUM; hardcoded rather than imported+# so this module stays importable (and unit-testable) without diffusers.+MINIMAX_H3_MODALITY_NUM = 3++# Metadata keys the offline prequant builder bakes into a curve-form checkpoint.+ADALN_FORM_KEY = "adaln_form"+ADALN_CURVE_FORM = "curve"+CURVE_DIM_KEY = "curve_dim"+CURVE_GRID_KEY = "curve_grid"+# The dtype of the block stack the modulation feeds, recorded by the builder. See+# `_curve_modulation_forward` for why the chunks have to be cast to it.+ADALN_OUT_DTYPE_KEY = "adaln_out_dtype"+++def _resolve_torch_dtype(name: Any) -> Any:+ """``"bfloat16"`` -> ``torch.bfloat16``; None for anything unrecognised.++ A missing or unknown value must NOT fall back to a guess: the cast it drives changes the block+ stack's precision, and silently picking the wrong one would be a quality regression no test+ would catch. None simply leaves the chunks at the projection's own dtype, which is the+ pre-existing behaviour."""+ if not isinstance(name, str) or not name:+ return None+ import torch++ dtype = getattr(torch, name.replace("torch.", ""), None)+ return dtype if isinstance(dtype, torch.dtype) else None+++def is_curve_checkpoint(metadata: Any) -> bool:+ """True when ``metadata`` describes a pruned (curve-form) adaLN checkpoint.++ Keyed on the recorded form rather than on the presence of ``time_embedder.table``: a checkpoint+ that carries the table but does not declare the form is one this code has not been validated+ against, and silently reshaping the model for it would load mismatched weights under+ ``strict = True`` only to produce noise."""+ if not isinstance(metadata, dict):+ return False+ if metadata.get(ADALN_FORM_KEY) != ADALN_CURVE_FORM:+ return False+ # Both dimensions are required: without them the reshape would have to guess the basis rank.+ return bool(metadata.get(CURVE_DIM_KEY)) and bool(metadata.get(CURVE_GRID_KEY))+++def _curve_modulation_forward(self: Any, temb: Any) -> tuple:+ """``MiniMaxH3AdaLayerNormModulation.forward`` for the curve form: no SiLU, then cast down.++ ``temb`` already holds the interpolated curve coordinates, i.e. the projection of the dense+ path's post-activation embedding onto the fitted basis. The view/chunk tail is byte-identical to+ the dense module, so the row layout the block's ``adaln_indices`` addresses is unchanged.++ The pruned modulation is stored FLOAT32 (the rank-8 curve is a small, precision-sensitive+ signal), while the dense checkpoint's projections are bfloat16. The block's forward multiplies+ the normed hidden states by these chunks WITHOUT casting, so leaving them float32 promotes the+ whole block stack to float32 and the very first quantized matmul dies with+ "expected mat1 and mat2 to have the same dtype". The reference casts modulation to the hidden+ stream's dtype at the point of use for exactly this reason; ``adaln_out_dtype`` is the dtype the+ offline builder recorded for that stream, so honour it here where the chunks are produced."""+ temb = self.linear(temb.to(self.linear.weight.dtype))+ out_dtype = getattr(self, "_unsloth_adaln_out_dtype", None)+ if out_dtype is not None:+ temb = temb.to(out_dtype)+ temb = temb.view(-1, 6 * self.hidden_size)+ return temb.chunk(6, dim = -1)+++def _curve_norm_out_forward(self: Any, hidden_states: Any, temb: Any, timestep_indices: Any) -> Any:+ """``MiniMaxH3AdaLayerNormOut.forward`` for the curve form: no SiLU, same indexing.++ No cast down here, unlike the block modulation: the reference's final layer also consumes its+ shift/scale at their own precision, and the model's forward sends this result straight into the+ float32 output heads, so promoting is what the dense path effectively does too."""+ shift, scale = self.linear(temb.to(self.linear.weight.dtype)).chunk(2, dim = -1)+ hidden_states = self.norm(hidden_states)+ return hidden_states * (1.0 + scale.index_select(0, timestep_indices)) + shift.index_select(+ 0, timestep_indices+ )+++def _build_curve_time_embedder(curve_grid: int, curve_dim: int) -> Any:+ """The module replacing ``TimestepEmbedding`` on a curve-form model.++ Holds the fitted table under the checkpoint's own ``time_embedder.table`` key and turns a raw+ timestep into curve coordinates by linear interpolation between the two neighbouring grid rows,+ matching the reference exactly (clamp to ``[0, 1]``, then clamp the lower index to+ ``grid - 2`` so ``t == 1.0`` lands on the last interval instead of reading past the table)."""+ import torch+ from torch import nn++ class _MiniMaxH3CurveTimeEmbedder(nn.Module):+ def __init__(self) -> None:+ super().__init__()+ # Persistent: this IS the checkpoint's `time_embedder.table` entry, assigned by+ # load_state_dict. float32 like the reference; the curve is a smooth low-amplitude+ # signal whose differences drive every block's modulation.+ self.register_buffer("table", torch.empty(curve_grid, curve_dim, dtype = torch.float32))+ # The model's forward reads `self.time_embedder.linear_1.weight.dtype` to decide what to+ # cast the timestep to. The dense module has that Linear; this one does not, so expose a+ # NON-PERSISTENT stand-in carrying only the dtype. Non-persistent keeps it out of the+ # state dict, so `strict = True` still matches the checkpoint exactly.+ self.linear_1 = nn.Module()+ self.linear_1.register_buffer(+ "weight", torch.zeros(1, dtype = torch.float32), persistent = False+ )++ def forward(self, timestep: Any) -> Any:+ table = self.table+ grid = table.shape[0]+ # Out-of-range timesteps clamp to the curve's ends rather than extrapolating.+ pos = timestep.to(torch.float32).clamp(0.0, 1.0) * (grid - 1)+ i0 = pos.floor().long().clamp(max = grid - 2)+ return torch.lerp(table[i0], table[i0 + 1], (pos - i0).unsqueeze(1))++ return _MiniMaxH3CurveTimeEmbedder()+++def _passthrough_time_proj() -> Any:+ """Replaces ``Timesteps`` so the raw timestep reaches the curve embedder.++ The dense path feeds ``time_proj``'s Fourier features to the time embedder; the curve table is+ indexed by the timestep itself. ``Timesteps`` is parameter-free, so swapping it changes no+ state-dict key."""+ from torch import nn++ class _MiniMaxH3RawTimestep(nn.Module):+ def forward(self, timestep: Any) -> Any:+ return timestep++ return _MiniMaxH3RawTimestep()+++def apply_h3_adaln_curve(+ transformer: Any,+ metadata: Any,+ logger: Any = None,+) -> bool:+ """Reshape a freshly built ``MiniMaxH3Transformer3DModel`` to the pruned adaLN form, in place.++ Call between ``from_config`` and ``load_state_dict``: it swaps ``time_proj`` / ``time_embedder``+ and re-shapes every ``adaln_proj.linear`` plus ``norm_out.linear`` from ``time_embed_dim`` inputs+ to ``curve_dim``, so the hosted checkpoint then loads under ``strict = True``.++ Returns True when the model was converted, False when ``metadata`` does not describe a+ curve-form checkpoint (a dense checkpoint must be left exactly as it was). Raises on a+ structurally unexpected model, so the prequant loader's caller falls back to dense rather than+ generating from a half-converted model."""+ if not is_curve_checkpoint(metadata):+ return False++ from torch import nn++ curve_dim = int(metadata[CURVE_DIM_KEY])+ curve_grid = int(metadata[CURVE_GRID_KEY])++ blocks = getattr(transformer, "transformer_blocks", None)+ norm_out = getattr(transformer, "norm_out", None)+ if blocks is None or norm_out is None:+ raise ValueError(+ "MiniMax-H3 curve conversion needs `transformer_blocks` and `norm_out`; this is not a "+ "MiniMaxH3Transformer3DModel."+ )++ def _reshape(linear: Any, where: str) -> Any:+ # Rebuild rather than resize: the replacement is a plain float32 Linear (the hosted+ # checkpoints store the pruned adaLN in float32) whose weights load_state_dict then+ # overwrites via assign=True. Built on the real device, never meta, so the module is+ # well-formed even if the checkpoint were to omit it and strict=True caught that instead.+ if not isinstance(linear, nn.Linear):+ raise ValueError(f"MiniMax-H3 curve conversion expected a Linear at {where}.")+ import torch+ return nn.Linear(curve_dim, linear.out_features, bias = linear.bias is not None).to(+ torch.float32+ )++ out_dtype = _resolve_torch_dtype(metadata.get(ADALN_OUT_DTYPE_KEY))++ converted = 0+ for index, block in enumerate(blocks):+ proj = getattr(block, "adaln_proj", None)+ if proj is None:+ raise ValueError(f"MiniMax-H3 curve conversion: block {index} has no `adaln_proj`.")+ proj.linear = _reshape(proj.linear, f"transformer_blocks.{index}.adaln_proj.linear")+ # Plain attribute, not a buffer: it must not reach the state dict, and `.to(device)` on the+ # module must not try to move it.+ proj._unsloth_adaln_out_dtype = out_dtype+ # Bind the SiLU-free forward per instance: the dense class is shared with dense loads in the+ # same process, so patching the CLASS would corrupt them.+ proj.forward = types.MethodType(_curve_modulation_forward, proj)+ converted += 1++ norm_out.linear = _reshape(norm_out.linear, "norm_out.linear")+ norm_out.forward = types.MethodType(_curve_norm_out_forward, norm_out)++ transformer.time_embedder = _build_curve_time_embedder(curve_grid, curve_dim)+ transformer.time_proj = _passthrough_time_proj()++ if logger is not None:+ logger.info(+ "video.h3_adaln_curve: converted %d block projections + norm_out to rank-%d "+ "(grid %d) pruned modulation, emitting %s",+ converted,+ curve_dim,+ curve_grid,+ out_dtype or "the projection dtype",+ )+ return True+++def h3_prepare_prequant_model(logger: Any = None) -> Any:+ """A ``prepare_model`` callback for ``load_prequantized_transformer``.++ The loader builds the model from the base repo's DENSE transformer config, so a curve-form+ hosted checkpoint has to reshape it before ``load_state_dict``; this adapts+ ``apply_h3_adaln_curve`` to the callback's ``(transformer, metadata)`` shape."""++ def _prepare(transformer: Any, metadata: Optional[dict]) -> None:+ apply_h3_adaln_curve(transformer, metadata, logger = logger)++ return _preparediff --git a/studio/backend/hub/services/models/deletion.py b/studio/backend/hub/services/models/deletion.pyindex be775ecbd75..db31d25cd32 100644--- a/studio/backend/hub/services/models/deletion.py+++ b/studio/backend/hub/services/models/deletion.py@@ -656,6 +656,11 @@ def _video_blocks_delete(repo_id: str) -> Optional[str]:held = status.get(key)if held and _loaded_id_matches_repo(str(held), repo_id):return "Unload the model before deleting"+ # The native H3 runtime re-reads its Qwen encoder and both VAEs from companion repos that are+ # neither of the two ids above, so refuse those as well, exactly as the Images guard does.+ for lid in getattr(backend, "loaded_repo_ids", tuple)():+ if _loaded_id_matches_repo(str(lid), repo_id):+ return "Unload the model before deleting"for lid in getattr(backend, "loading_repo_ids", tuple)():if _loaded_id_matches_repo(str(lid), repo_id):return "A Video model load is using this repo; wait for it to finish"diff --git a/studio/backend/hub/services/models/local_inventory.py b/studio/backend/hub/services/models/local_inventory.pyindex 9a1b1b60855..627ac4cfdf9 100644--- a/studio/backend/hub/services/models/local_inventory.py+++ b/studio/backend/hub/services/models/local_inventory.py@@ -113,6 +113,24 @@ def _has_immediate_model_weight(return False+def _is_diffusers_pipeline_dir(path: Path) -> bool:+ """True for a diffusers PIPELINE root: a top-level ``model_index.json`` with the weights in+ component subdirs (``transformer/``, ``vae/``, ``text_encoder/`` ...).++ Every image and video model downloaded as a pipeline has this shape and NO root+ ``config.json``, so the root-config-plus-loose-weights test below rejects it. Without this the+ Images and Video pickers cannot see a pipeline the user already has on disk, and the LM Studio+ publisher walk descends into it and offers its components (``vae``, ``transformer``, ...) as+ separate models, none of which any loader can start.++ ``routes.models._local_pipeline_index`` is the same test; the two scanners are separate+ modules, and only that one had it."""+ try:+ return (path / "model_index.json").is_file()+ except OSError:+ return False++def _has_immediate_model_signal(path: Path, *, probe_limit: int = _MODEL_SIGNAL_PROBE_LIMIT) -> bool:@@ -121,10 +139,14 @@ def _has_immediate_model_signal(return Trueexcept OSError:return False+ if _is_diffusers_pipeline_dir(path):+ return Truereturn _has_immediate_model_weight(path, probe_limit = probe_limit)def _is_model_directory_for_scan(path: Path, *, entry_limit: int | None) -> bool:+ if _is_diffusers_pipeline_dir(path):+ return Trueif entry_limit is None:return _is_model_directory(path)try:@@ -416,9 +438,9 @@ def _scan_lmstudio_dir(lm_dir: Path, *, entry_limit: int | None = None) -> List[if not lm_dir.exists() or not lm_dir.is_dir():return []- # If the dir is itself a model dir (config + weights), it's not an LM Studio- # publisher structure -- return it as a single entry rather than descend.- if _is_model_directory(lm_dir):+ # If the dir is itself a model dir (config + weights, or a diffusers pipeline root), it's not+ # an LM Studio publisher structure -- return it as a single entry rather than descend.+ if _is_model_directory(lm_dir) or _is_diffusers_pipeline_dir(lm_dir):try:updated_at = lm_dir.stat().st_mtimeexcept OSError:@@ -461,8 +483,9 @@ def _scan_lmstudio_dir(lm_dir: Path, *, entry_limit: int | None = None) -> List[)continue- # Child is itself a model dir: surface it directly, not as a publisher.- if _is_model_directory(child):+ # Child is itself a model dir: surface it directly, not as a publisher. A diffusers+ # pipeline counts, or its component subdirs are walked as if they were models.+ if _is_model_directory(child) or _is_diffusers_pipeline_dir(child):try:updated_at = child.stat().st_mtimeexcept OSError:@@ -712,6 +735,15 @@ def _scan_custom_folder(from utils.models.model_config import detect_gguf_modelsupported_formats: set[ModelFormat] = {"gguf", "safetensors", "adapter"}++ def _is_supported(m: LocalModelInfo) -> bool:+ # A diffusers pipeline keeps its weights in component subdirs, so the root has no loose+ # weight file to classify and lands as "unknown". It is exactly what the Images and Video+ # loaders take, so judge it on its shape rather than on a format the layout cannot report.+ if m.model_format in supported_formats:+ return True+ return _is_diffusers_pipeline_dir(Path(m.path))+generic = [mfor m in (@@ -730,7 +762,7 @@ def _scan_custom_folder()+ _scan_lmstudio_dir(folder_path, entry_limit = _MAX_CUSTOM_FOLDER_ENTRIES))- if m.model_format in supported_formats+ if _is_supported(m)if not any(p in (".studio_links", "ollama_links") for p in Path(m.path).parts)]selectable = []diff --git a/studio/backend/hub/tests/test_model_services.py b/studio/backend/hub/tests/test_model_services.pyindex 3db699f4a70..135da11b0be 100644--- a/studio/backend/hub/tests/test_model_services.py+++ b/studio/backend/hub/tests/test_model_services.py@@ -112,6 +112,47 @@ class TestExtractQuantToken:assert labels == {"Q4_K_M", "Q8_0"}+ "repo", ["leejet/MiniMax-H3-GGUF", "unsloth/MiniMax-H3-GGUF", "UNSLOTH/minimax-h3-gguf"]+)+def test_minimax_h3_variant_filter_keeps_both_denoiser_partitions(repo):+ """Both H3 bundle repos need the filter, and the match is case-insensitive.++ The Unsloth mirror is the one the family and catalog now advertise, and it carries the+ Qwen3-VL encoder quants beside the denoisers, so leaving it off the list would aggregate a+ 12 GB text encoder as if it were a selectable transformer quant.++ Both denoiser partitions stay: which one is picked IS the task, the loader's+ ``validate_h3_transformer_filename`` accepts either, and the community bundle repo publishes+ Ref2VA quants today. Filtering them out hid the whole reference-video path from the picker."""+ selectable = gguf._is_selectable_repo_gguf+ assert selectable(repo, "minimax_h3_fl2va-Q4_K_M.gguf")+ assert selectable(repo, "minimax_h3_fl2va_pruned-Q4_K_M.gguf")+ assert selectable(repo, "minimax_h3_fl2va-Q2_K_M.gguf")+ assert selectable(repo, "minimax_h3_fl2va_pruned-UD-Q2_K_XL.gguf")+ assert selectable(repo, "minimax_h3_ref2va-Q4_K_M.gguf")+ assert selectable(repo, "minimax_h3_ref2va_pruned-Q2_K_M.gguf")+ # The companions are still never picks.+ assert not selectable(repo, "qwen3vl_32b_minimax_h3-Q4_K_M.gguf")+ assert not selectable(repo, "qwen3vl_32b_minimax_h3-Q2_K_M.gguf")+++def test_the_h3_native_repo_is_a_recognised_bundle_repo():+ """The repo the native loader downloads from must be one the filter knows about.++ These are set in different files, so a future repo move that updates only the loader would+ silently reintroduce the encoder-as-transformer aggregation this filter exists to prevent."""+ import sys+ from pathlib import Path++ backend = Path(__file__).resolve().parents[2]+ if str(backend) not in sys.path:+ sys.path.insert(0, str(backend))+ from core.inference.video_minimax_h3 import H3_GGUF_REPO++ assert gguf.is_h3_bundle_repo(H3_GGUF_REPO)++def test_big_endian_detection_ignores_model_name_be_token():assert gguf.is_big_endian_gguf_path("model-Q4_K_M-be.gguf", "Q4_K_M")assert gguf.is_big_endian_gguf_path("model-Q4_K_M_be_infill.gguf", "Q4_K_M")@@ -6314,6 +6355,132 @@ def test_custom_promotion_keeps_the_classifier_verdict(tmp_path, config, expecteassert promoted.capabilities.can_chat is expected+# ── local diffusers pipelines reach the Images / Video pickers ───────────────+++def _write_pipeline(root: Path, *, components = ("transformer", "vae", "text_encoder")) -> Path:+ """A diffusers PIPELINE directory: a root model_index.json, no root config.json, and the+ weights inside component subdirs. Every image and video model downloaded as a pipeline+ (MiniMax-H3, HunyuanVideo, Qwen-Image, HiDream) has exactly this shape."""+ root.mkdir(parents = True, exist_ok = True)+ (root / "model_index.json").write_text(+ json.dumps({"_class_name": "MiniMaxH3Pipeline", "_diffusers_version": "0.39.0"}),+ encoding = "utf-8",+ )+ for name in components:+ part = root / name+ part.mkdir(parents = True, exist_ok = True)+ (part / "config.json").write_text(json.dumps({"model_type": name}), encoding = "utf-8")+ (part / "diffusion_pytorch_model.safetensors").write_bytes(b"x" * 1024)+ return root+++def test_models_dir_scan_surfaces_a_local_diffusers_pipeline(tmp_path):+ """A pipeline the user already has on disk must be listed. It carries no root config.json+ and no loose weight file, which is the only shape the scan used to accept, so the Video and+ Images pickers showed nothing for a model that was sitting right there."""+ models = tmp_path / "models"+ _write_pipeline(models / "MiniMax-H3-local")++ rows = local_inventory._scan_models_dir(models)++ assert {Path(row.path).name for row in rows} == {"MiniMax-H3-local"}+++def test_a_scan_folder_pointed_straight_at_a_pipeline_is_that_model(tmp_path):+ pipeline = _write_pipeline(tmp_path / "MiniMax-H3-local")++ rows = local_inventory._scan_models_dir(pipeline, entry_limit = 64)++ assert [Path(row.path) for row in rows] == [pipeline]+++def test_the_lmstudio_walk_does_not_descend_into_a_pipeline(tmp_path):+ """LM Studio stores models as publisher/model, so an unrecognised directory is walked one+ level down. A pipeline root looked like a publisher, and its components (vae, transformer,+ text_encoder) were published as separate models -- none of which any loader can start."""+ root = tmp_path / "scan"+ _write_pipeline(root / "MiniMax-H3-local")++ names = {Path(row.path).name for row in local_inventory._scan_lmstudio_dir(root)}++ assert names == {"MiniMax-H3-local"}+ assert not names & {"vae", "transformer", "text_encoder"}+++def test_a_scan_folder_pointed_straight_at_a_pipeline_is_not_walked_as_a_publisher(tmp_path):+ """The same walk, entered AT the pipeline. A user adding the model folder itself as a scan+ folder is the obvious thing to do, and it published vae / transformer / text_encoder as three+ models instead of the one that is there."""+ pipeline = _write_pipeline(tmp_path / "MiniMax-H3-local")++ rows = local_inventory._scan_lmstudio_dir(pipeline)++ assert [Path(row.path) for row in rows] == [pipeline]+++def test_a_custom_folder_offers_the_pipeline_and_not_its_components(tmp_path):+ """End to end over the path the Custom Folders control uses. The format filter keeps only+ gguf / safetensors / adapter rows, and a pipeline root has no loose weight to classify, so+ it reports "unknown" by construction -- judged on its shape instead."""+ root = tmp_path / "scan"+ _write_pipeline(root / "MiniMax-H3-local")++ rows = local_inventory._scan_custom_folder(root)+ names = {Path(row.path).name for row in rows}++ assert names == {"MiniMax-H3-local"}+++def test_a_directory_that_is_not_a_pipeline_is_still_rejected(tmp_path):+ """The new signal is a ROOT model_index.json. A folder that only holds one in a subdir is+ not loadable from its root, and a bare folder is not a model at all."""+ root = tmp_path / "scan"+ (root / "not-a-model").mkdir(parents = True)+ (root / "not-a-model" / "notes.txt").write_text("hello", encoding = "utf-8")+ (root / "nested" / "inner").mkdir(parents = True)+ (root / "nested" / "inner" / "model_index.json").write_text("{}", encoding = "utf-8")++ assert local_inventory._scan_models_dir(root) == []+++def test_the_custom_folder_filter_still_drops_a_row_it_cannot_classify(tmp_path):+ """The pipeline exemption widens the custom-folder format filter, so pin what it must NOT let+ through. A folder holding a config.json and no weights (an aborted download) also reports+ "unknown", and nothing can load it: it has to stay filtered out while the pipeline beside it+ is offered."""+ root = tmp_path / "scan"+ _write_pipeline(root / "MiniMax-H3-local")+ aborted = root / "half-downloaded"+ aborted.mkdir(parents = True)+ (aborted / "config.json").write_text(json.dumps({"model_type": "llama"}), encoding = "utf-8")++ # The scan does see it, so the filter is what decides -- otherwise this proves nothing.+ assert "half-downloaded" in {+ Path(row.path).name for row in local_inventory._scan_models_dir(root)+ }+ assert {Path(row.path).name for row in local_inventory._scan_custom_folder(root)} == {+ "MiniMax-H3-local",+ }+++def test_the_pipeline_test_is_safe_on_a_path_that_is_not_a_readable_directory(tmp_path):+ """``_scan_custom_folder`` applies this to every row it did not already accept, and a row's+ path can be a GGUF FILE, not a directory. A missing path, a file, and a directory whose+ ``model_index.json`` is itself a directory must all answer False rather than raise: an+ exception here fails the whole scan and empties the picker."""+ assert local_inventory._is_diffusers_pipeline_dir(tmp_path / "does-not-exist") is False++ loose = tmp_path / "model.gguf"+ loose.write_bytes(b"GGUF")+ assert local_inventory._is_diffusers_pipeline_dir(loose) is False+ assert local_inventory._is_diffusers_pipeline_dir(loose / "model_index.json") is False++ odd = tmp_path / "odd"+ (odd / "model_index.json").mkdir(parents = True)+ assert local_inventory._is_diffusers_pipeline_dir(odd) is False++def test_gguf_progress_unknown_hashes_calls_a_sibling_only_dir_absent(monkeypatch, tmp_path):"""A repo dir kept alive by a sibling quant is not evidence that THIS one is here.diff --git a/studio/backend/hub/utils/gguf.py b/studio/backend/hub/utils/gguf.pyindex 5d8fe2585ed..f8daed55a7e 100644--- a/studio/backend/hub/utils/gguf.py+++ b/studio/backend/hub/utils/gguf.py@@ -140,6 +140,32 @@ def is_gguf_filename(filename: str) -> bool:return filename.lower().endswith(".gguf")+# Every repo that bundles H3's denoisers together with its companion models. The Unsloth mirror+# carries the Qwen3-VL text-encoder quants beside the denoisers, so it needs the same filtering as+# the community repack it replaced; listing only one of them would let the encoder GGUFs be+# aggregated as if they were selectable transformer quants.+_H3_BUNDLE_REPOS = frozenset({"leejet/minimax-h3-gguf", "unsloth/minimax-h3-gguf"})+++def is_h3_bundle_repo(repo_id: str) -> bool:+ return repo_id.strip().lower() in _H3_BUNDLE_REPOS+++# Both released denoiser partitions are valid picks -- which one is picked IS the task. Kept in+# step with validate_h3_transformer_filename in core/inference/video_minimax_h3.py, which the load+# enforces; listing only FL2VA hid every published Ref2VA quant from the picker even though the+# loader routes it and the reference UI depends on it.+_H3_DENOISER_PARTITIONS = ("minimax_h3_fl2va", "minimax_h3_ref2va")+++def _is_selectable_repo_gguf(repo_id: str, filename: str) -> bool:+ """Hide auxiliary GGUFs from repos that bundle several model roles."""+ if is_h3_bundle_repo(repo_id):+ name = Path(filename).name.lower()+ return name.startswith(_H3_DENOISER_PARTITIONS) and name.endswith(".gguf")+ return True++_BIG_ENDIAN_GGUF_FILENAME_RE = re.compile(r"(^|[-_])be(?:[._-]|$)", re.IGNORECASE)@@ -589,6 +615,8 @@ def list_gguf_variants(filename = getattr(sibling, "rfilename", None)if not isinstance(filename, str) or not is_gguf_filename(filename):continue+ if not _is_selectable_repo_gguf(repo_id, filename):+ continueif is_mtp_drafter_path(filename):continueif is_mmproj_filename(filename):@@ -652,8 +680,16 @@ def list_local_gguf_variants(quant_totals: dict[str, int] = {}quant_first_file: dict[str, str] = {}has_vision = False+ # Match the cache dir of ANY H3 bundle repo, not just one of them: the same aggregation runs+ # over whichever mirror the user actually downloaded.+ root_key = root.as_posix().lower()+ h3_bundle_repo = next(+ (r for r in _H3_BUNDLE_REPOS if f"models--{r.replace('/', '--')}" in root_key), None+ )for file in sorted(iter_gguf_files(root, recursive = True)):+ if h3_bundle_repo and not _is_selectable_repo_gguf(h3_bundle_repo, file.name):+ continueif is_mmproj_filename(file.name):# A projector llama.cpp cannot open is not vision support.try:diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.pyindex 75b4b278f79..cc575181473 100644--- a/studio/backend/models/inference.py+++ b/studio/backend/models/inference.py@@ -3230,6 +3230,14 @@ class VideoLoadRequest(BaseModel):"sm_100+). null keeps the encoder dense. Mirrors the image backend's field.",)+ h3_task: Optional[Literal["fl2va", "ref2va"]] = Field(+ None,+ description = "Which MiniMax-H3 denoiser partition to bring up: fl2va (text-to-video "+ "and first/last-frame video, the default) or ref2va (omni-reference video). They are "+ "separate ~62 GB partitions, so a load serves one of them. Ignored for a GGUF pick, "+ "whose filename already names the partition; rejected if it contradicts that filename.",+ )+@field_validator("attention_backend", mode = "before")@classmethoddef _normalize_attention_backend(cls, value):@@ -3237,6 +3245,23 @@ class VideoLoadRequest(BaseModel):return value.strip().lower() if isinstance(value, str) else value+class VideoReferenceVideo(BaseModel):+ """One reference video, with the soundtrack MiniMax-H3 conditions on alongside it."""++ video: str = Field(+ ...,+ max_length = 96 * 1024 * 1024,+ description = "Base64/data-URL video file, 2 to 15 seconds. Resampled onto the model's "+ "24 fps and onto the canvas its own aspect ratio resolves to.",+ )+ audio: Optional[str] = Field(+ None,+ max_length = 32 * 1024 * 1024,+ description = "Base64/data-URL soundtrack for THIS video. Omitted takes the track "+ "embedded in the file, if it has one; sent explicitly it replaces it.",+ )++class VideoGenerateRequest(BaseModel):"""Request to generate one clip from the loaded video model."""@@ -3246,7 +3271,7 @@ class VideoGenerateRequest(BaseModel):)# Width/height/num_frames/fps default per loaded family, so they are optional here. These bounds stay a COARSE outer# guard only -- they are family-agnostic, and a request that clears them can still be one no checkpoint can render. The- # enforced rule is the LOADED family's own (its resolution presets and k * frame_step + 1 lattice), which the generate+ # enforced rule is the LOADED family's own (its resolution presets and k * frame_step + frame_offset lattice), which the# route checks with validate_video_request_shape and rejects with a 422 naming the supported shapes. Nothing tighter# belongs here: with no model loaded there is no family to judge against, and that path must keep snapping as before.width: Optional[int] = Field(@@ -3265,7 +3290,7 @@ class VideoGenerateRequest(BaseModel):None,ge = 1,le = MAX_VIDEO_NUM_FRAMES,- description = "Number of frames; must lie on the family's temporal lattice (k * frame_step + 1)",+ description = "Number of frames; must lie on the family's temporal lattice (k * frame_step + frame_offset)",)fps: Optional[int] = Field(None, ge = 1, le = 120, description = "Playback frame rate (default per family)"@@ -3289,6 +3314,112 @@ class VideoGenerateRequest(BaseModel):seed: Optional[int] = Field(None, ge = 0, le = 2**53 - 1, description = "Seed for reproducibility (random if omitted)")+ # Keyframe conditioning (MiniMax-H3). Bounded like the image backend's init_image so one+ # request cannot buffer a multi-GB payload; ~32 MiB fits a full 4096px source.+ first_frame: Optional[str] = Field(+ None,+ max_length = 32 * 1024 * 1024,+ description = "Base64/data-URL image the clip starts from (image-to-video). It sets the "+ "geometry and is stretched onto the canvas. Omit for text-to-video. Rejected by a "+ "family that takes no keyframes.",+ )+ last_frame: Optional[str] = Field(+ None,+ max_length = 32 * 1024 * 1024,+ description = "Base64/data-URL image the clip ends on. Valid on its own (generate up "+ "TO a frame) or with first_frame (first-and-last-frame video), in which case it "+ "follows the first and is centre cover-cropped onto the canvas.",+ )++ # Separate lists preserve the model's image, video, then audio packing order.+ reference_images: Optional[list[str]] = Field(+ None,+ max_length = 9,+ description = "Subject / style / scene reference images (base64/data-URL), at most 9. "+ "The prompt refers to them as <Picture 1>, <Picture 2>, ... in this order.",+ )+ reference_videos: Optional[list[VideoReferenceVideo]] = Field(+ None,+ max_length = 3,+ description = "Motion / camera reference videos, at most 3. The prompt refers to them "+ "as <Video 1>, <Video 2>, ... in this order.",+ )+ reference_audios: Optional[list[str]] = Field(+ None,+ max_length = 3,+ description = "Standalone reference audio (base64/data-URL), at most 3, for voice or "+ "score. The prompt refers to them as <Audio 1>, <Audio 2>, ... in this order. Audio "+ "cannot be the only kind of reference a request carries.",+ )+ flow_shift: Optional[float] = Field(+ None,+ gt = 0.0,+ le = 100.0,+ description = "Sigma shift of the video schedule (MiniMax-H3 ships 12.0). Higher spends "+ "more of the schedule at high noise, which reads as more motion and less detail. null "+ "keeps the released value.",+ )+ audio_flow_shift: Optional[float] = Field(+ None,+ gt = 0.0,+ le = 100.0,+ description = "Sigma shift of the audio schedule (MiniMax-H3 ships 3.0). Needs the "+ "Diffusers engine: stable-diffusion.cpp derives the audio schedule against a hardcoded "+ "3.0, so it has no flag to map this onto. null keeps the released value.",+ )+ reference_image_size: Optional[Literal["match", "max"]] = Field(+ None,+ description = "How reference images are sized: match (default) scales each down to the "+ "generation's pixel area; max uses the reference pipeline's 2048px short edge for "+ "stronger identity fidelity, several times slower. max needs the Diffusers engine -- "+ "stable-diffusion.cpp rescales every reference to the generation area regardless.",+ )++ @field_validator("reference_images", "reference_audios")+ @classmethod+ def _bounded_reference_media(cls, value: Optional[list[str]]) -> Optional[list[str]]:+ # Bound each item like first_frame, so a list cannot buffer what one field may not.+ if value is not None:+ for item in value:+ if len(item) > 32 * 1024 * 1024:+ raise ValueError("each reference must be at most 32 MiB (base64)")+ return value++ @model_validator(mode = "after")+ def _references_fit_the_models_budget(self) -> "VideoGenerateRequest":+ images = self.reference_images or []+ videos = self.reference_videos or []+ audios = self.reference_audios or []+ total = len(images) + len(videos) + len(audios)+ if total > 12:+ raise ValueError(f"MiniMax-H3 takes at most 12 references in total, got {total}")+ # Standalone audio must accompany an image or video reference.+ if audios and not images and not videos:+ raise ValueError(+ "reference audio needs at least one reference image or video to go with"+ )+ if (images or videos or audios) and (self.first_frame or self.last_frame):+ raise ValueError(+ "keyframes and references cannot be combined: MiniMax-H3 runs them against "+ "different denoiser partitions"+ )+ return self++ @model_validator(mode = "after")+ def _keyframe_canvas_needs_both_axes(self) -> "VideoGenerateRequest":+ # Omit both axes for "match source", or provide both for an explicit canvas.+ # KEYFRAME requests only. There a half-specified canvas is silently discarded:+ # _resolve_keyframes matches the source aspect whenever either axis is missing, so the+ # axis that was sent never reaches the render and the API would accept one recipe and+ # draw another. Without a keyframe the backend deliberately resolves the missing axis+ # from the family's default preset -- validate_video_request_shape and generate() both+ # document and implement that -- so applying the rule to every request would reject+ # half-specified LTX, Wan, Hunyuan and prompt-only H3 calls that have always been valid.+ if not (self.first_frame or self.last_frame):+ return self+ if (self.width is None) != (self.height is None):+ raise ValueError("width and height must be sent together, or both omitted")+ return selfclass GalleryVideo(BaseModel):@@ -3308,8 +3439,20 @@ class GalleryVideo(BaseModel):guidance_2: Optional[float] = Field(None, description = "Second-expert guidance scale (dual-expert families), if sent")+ flow_shift: Optional[float] = Field(+ None, description = "Video-schedule sigma shift used, for families that expose it"+ )+ audio_flow_shift: Optional[float] = Field(+ None, description = "Audio-schedule sigma shift used, for families that expose it"+ )seed: int = Field(..., description = "Seed used")has_audio: bool = Field(False, description = "Whether the MP4 carries an audio track")+ conditioning: Optional[str] = Field(+ None,+ description = "How the clip was conditioned, in MiniMax-H3's own task names: t2va "+ "(prompt only), i2va (first frame), l2va (last frame) or fl2va (both). Absent on "+ "clips saved before keyframes existed.",+ )model: Optional[str] = Field(None, description = "Model repo id that produced it")# The load-time BUILD, mirroring GalleryImage: the repo id alone does not say which checkpoint# ran or at what precision, so a clip could not be told apart from one rendered at another. All@@ -3408,13 +3551,39 @@ class VideoGenerationDefaults(BaseModel):guidance: float = Field(..., description = "Default guidance scale")num_frames: int = Field(..., description = "Default frame count")fps: int = Field(..., description = "Default playback frame rate")- frame_step: int = Field(- ..., description = "Temporal lattice: valid counts are k * frame_step + 1"+ frame_step: int = Field(..., description = "Temporal lattice stride")+ frame_offset: int = Field(+ 1, description = "Temporal lattice offset: valid counts are k * frame_step + frame_offset"+ )+ duration_presets: list[float] = Field(+ default_factory = list, description = "Clip durations in seconds the UI offers")resolution_multiple: int = Field(..., description = "Width/height must be divisible by this")resolution_presets: list[list[int]] = Field(default_factory = list, description = "(width, height) presets the UI offers, default first")+ canvas_short_edge: Optional[int] = Field(+ None,+ description = "Short edge a source-derived canvas aims for, or null when the family "+ "has no keyframe canvas rule. With canvas_max_pixels and resolution_multiple this is "+ "the whole rule: short edge, then cap the area, then round both axes.",+ )+ canvas_max_pixels: Optional[int] = Field(+ None, description = "Area budget of a source-derived canvas, or null (see canvas_short_edge)"+ )+ flow_shift: Optional[float] = Field(+ None,+ description = "Released video-schedule sigma shift, or null when the family does not "+ "expose the control",+ )+ audio_flow_shift: Optional[float] = Field(+ None, description = "Released audio-schedule sigma shift, or null (see flow_shift)"+ )+ supports_audio_flow_shift: bool = Field(+ False,+ description = "Whether the ACTIVE engine can honour audio_flow_shift; false on "+ "stable-diffusion.cpp, which pins the audio schedule at its released value",+ )class VideoStatusResponse(BaseModel):@@ -3429,6 +3598,7 @@ class VideoStatusResponse(BaseModel):model_kind: Optional[str] = Field(None, description = "Resolved load kind: gguf | single_file | pipeline (gates GGUF-only UI)")+ engine: Optional[str] = Field(None, description = "Active video engine: diffusers | sd_cpp")gguf_variant: Optional[str] = Field(None, description = "Selected GGUF quantisation variant (for example Q8_0)")@@ -3462,6 +3632,25 @@ class VideoStatusResponse(BaseModel):has_audio: bool = Field(False, description = "Whether the loaded family produces a synchronized audio track")+ supports_keyframes: bool = Field(+ False,+ description = "Whether the LOADED checkpoint takes first/last-frame conditioning images "+ "(gates the image-to-video controls)",+ )+ supports_references: bool = Field(+ False,+ description = "Whether the LOADED checkpoint takes reference images / videos / audio "+ "(gates the reference-to-video controls). Never true at the same time as "+ "supports_keyframes: MiniMax-H3 serves the two from different denoiser partitions.",+ )+ h3_task: Optional[str] = Field(+ None,+ description = "The MiniMax-H3 denoiser partition that is up: fl2va | ref2va, or null "+ "for any other family",+ )+ supports_cfg: bool = Field(+ True, description = "Whether guidance and negative prompts apply to this family"+ )defaults: Optional[VideoGenerationDefaults] = Field(None, description = "Per-family generation defaults + shape constraints; null when unloaded")diff --git a/studio/backend/requirements/base.txt b/studio/backend/requirements/base.txtindex 407ae01b526..dd8474ceda0 100644--- a/studio/backend/requirements/base.txt+++ b/studio/backend/requirements/base.txt@@ -1,3 +1,6 @@# Core unsloth packagesunsloth-zoounsloth+# diffusers is deliberately NOT here: install.sh skips this file entirely+# (SKIP_STUDIO_BASE=1), so a pin here never reaches a fresh install. It lives in+# diffusers-pin.txt, installed by its own step in install_python_stack.py.diff --git a/studio/backend/requirements/diffusers-pin.txt b/studio/backend/requirements/diffusers-pin.txtnew file mode 100644index 00000000000..02c195f754e--- /dev/null+++ b/studio/backend/requirements/diffusers-pin.txt@@ -0,0 +1,22 @@+# The Diffusers revision Studio is built against. THE single source of truth for it:+# no other requirements file may name diffusers, and a test in+# tests/studio/install/test_diffusers_pin.py enforces that.+#+# Why a git archive and not a release: MiniMax-H3 needs the modular ModularPipeline /+# MiniMaxH3Transformer3DModel work that landed after 0.39.0 and is not in any published+# wheel yet, so a released version makes Studio refuse to load H3 at all. The archive+# reports itself as 0.40.0.dev0.+#+# Why it is installed from its own file, in its own step: install.sh installs unsloth+# itself and then hands off to install_python_stack.py with SKIP_STUDIO_BASE=1, which+# skips the base.txt step entirely. Anything pinned in base.txt is therefore applied on+# `unsloth studio update` but NOT on a fresh install.sh, where unsloth's own metadata had+# already pulled diffusers 0.39.0 from PyPI and nothing walked it forward. The step that+# installs this file runs on every path, and runs late, after every other requirements+# file, so nothing can re-resolve diffusers back to a release behind it.+#+# python < 3.10 has no candidate: diffusers dropped 3.9 in 0.38, so pinning the archive+# outright would leave the resolver nothing at all on a 3.9 host. Those hosts get the+# newest release they can take and the H3 guard refuses the model with a clear message.+diffusers @ https://github.com/huggingface/diffusers/archive/f53d552036a0d1bd5570782a39cd40cfabf112bc.zip ; python_version >= "3.10"+diffusers ; python_version < "3.10"diff --git a/studio/backend/requirements/extras-no-deps.txt b/studio/backend/requirements/extras-no-deps.txtindex 29d53ba2043..7500700bc7a 100644--- a/studio/backend/requirements/extras-no-deps.txt+++ b/studio/backend/requirements/extras-no-deps.txt@@ -14,7 +14,8 @@ trl==0.23.1# executorch>=1.0.1 # 41.5 MB - no imports in unsloth/zoo/studiotorch-c-dlpack-extsentence_transformers==5.2.0-transformers==4.57.6+transformers==5.5.0; python_version >= "3.10"+transformers==4.57.6; python_version < "3.10"# No macOS x86_64 wheel at any version, so uv falls back to an sdist that shells out to# cmake. Skipping it on Intel Macs keeps that install compiler-free.pytorch_tokenizers; sys_platform != "darwin" or platform_machine == "arm64"diff --git a/studio/backend/requirements/no-torch-runtime.txt b/studio/backend/requirements/no-torch-runtime.txtindex cc242e419dd..4e4d015ced9 100644--- a/studio/backend/requirements/no-torch-runtime.txt+++ b/studio/backend/requirements/no-torch-runtime.txt@@ -39,9 +39,11 @@ safetensors>=0.4.3datasets>=3.4.1,!=4.0.*,!=4.1.0,<4.4.0accelerate>=0.34.1peft>=0.18.0,!=0.11.0-huggingface_hub>=0.34.0+huggingface_hub>=1.23.0,<2.0; python_version >= "3.10"+huggingface_hub==0.36.2; python_version < "3.10"hf_transfer-diffusers+# diffusers: see diffusers-pin.txt, installed by its own step (this file is+# installed --no-deps, and the pin has to apply on the torch path too).# Transitive deps required because this file is installed with --no-deps.# Without these, `from transformers import AutoConfig` fails at import time.@@ -56,10 +58,10 @@ anyio>=3.0,<4.14.0 # 4.14 asyncio cancel-scope RuntimeError on Py3.13 streamingsniffioh11-# Unpinned resolves to 0.23.1+ which breaks `from transformers import-# AutoConfig`; transformers 4.56..5.3 declares tokenizers<=0.23.0.+# Transformers 5.5 supports tokenizers 0.22.x through 0.23.0.tokenizers<=0.23.0-transformers>=4.51.3,!=4.52.0,!=4.52.1,!=4.52.2,!=4.52.3,!=4.53.0,!=4.54.0,!=4.55.0,!=4.55.1,!=4.57.0,!=4.57.4,!=4.57.5,!=5.0.0,!=5.1.0,<=5.3.0+transformers==5.5.0; python_version >= "3.10"+transformers==4.57.6; python_version < "3.10"trl>=0.18.2,!=0.19.0,<=0.24.0sentence-transformerscut_cross_entropydiff --git a/studio/backend/requirements/single-env/constraints.txt b/studio/backend/requirements/single-env/constraints.txtindex 7d3b9a081f8..9d35f4b212e 100644--- a/studio/backend/requirements/single-env/constraints.txt+++ b/studio/backend/requirements/single-env/constraints.txt@@ -1,8 +1,10 @@# Single-env pins for unsloth + studio + data-designer-# Keep compatible with unsloth transformers bounds.-transformers==4.57.6+# MiniMax-H3's merged Diffusers workflow needs the current Hugging Face stack.+transformers==5.5.0; python_version >= "3.10"+transformers==4.57.6; python_version < "3.10"trl==0.23.1-huggingface-hub==0.36.2+huggingface-hub>=1.23.0,<2.0; python_version >= "3.10"+huggingface-hub==0.36.2; python_version < "3.10"# Unsloth stackdatasets==4.3.0diff --git a/studio/backend/requirements/single-env/overrides-darwin-arm64.txt b/studio/backend/requirements/single-env/overrides-darwin-arm64.txtindex bd2bdaee7ea..054cf21b7ae 100644--- a/studio/backend/requirements/single-env/overrides-darwin-arm64.txt+++ b/studio/backend/requirements/single-env/overrides-darwin-arm64.txt@@ -1,8 +1,7 @@-# mlx-vlm / mlx-lm declare transformers>=5.x which conflicts with the-# main venv's constraints.txt pin transformers==4.57.6 and forces uv to-# backtrack unsloth. Relax to match the pin -- per-model 5.x routing-# happens at runtime via the side-car venvs.-transformers>=4.57.6+# Keep mlx-vlm / mlx-lm on the same Transformers floor as the main Studio+# environment when uv applies their dependency metadata.+transformers>=5.5.0; python_version >= "3.10"+transformers>=4.57.6; python_version < "3.10"# mlx-vlm / mlx-lm pull anyio>=4.14, which fights the constraints.txt cap (needed# for the 4.14 Python-3.13 streaming cancel-scope RuntimeError, #6483). The -c@@ -11,9 +10,20 @@ transformers>=4.57.6# wins the fight, so force one consistent <4.14 here too.anyio<4.14.0-# mlx-audio (pulled by mlx-vlm>=0.5.0) declares huggingface_hub>=1.0, which-# conflicts with the transformers==4.57.6 stack (hub<1.0; constraints.txt pins-# hub==0.36.2). Without this override uv silently backtracks mlx-vlm to 0.4.4,-# dropping newer VLM/audio support. Keep <1.0 so the resolver can never pair-# hub 1.x with the pinned transformers.-huggingface_hub>=0.34.0,<1.0+# mlx-audio (pulled by mlx-vlm>=0.5.0) declares huggingface_hub>=1.0.+#+# On python < 3.10 we are still on the transformers==4.57.6 stack, which needs+# hub<1.0, and constraints.txt pins hub==0.36.2 there. Without the cap uv+# silently backtracks mlx-vlm to 0.4.4, dropping newer VLM/audio support, so the+# cap stays: the resolver must never pair hub 1.x with pinned transformers 4.x.+#+# On python >= 3.10 that premise is gone. diffusers (for MiniMax-H3) requires+# huggingface-hub>=1.23.0,<2.0, and constraints.txt, studio.txt, base.txt and+# no-torch-runtime.txt all moved to that window. A flat <1.0 here contradicts+# them and is unsatisfiable, which is macOS-arm only, so only the mac legs see+# it: uv reports "Because you require huggingface-hub>=0.34.0,<1.0 and+# huggingface-hub>=1.23.0,<2.0, your requirements are unsatisfiable", falls back+# to pip, and the clean-machine trace then fails on a rustc probe. mlx-audio's+# own >=1.0 floor is satisfied by the 1.x window anyway.+huggingface_hub>=1.23.0,<2.0; python_version >= "3.10"+huggingface_hub>=0.34.0,<1.0; python_version < "3.10"diff --git a/studio/backend/requirements/studio.txt b/studio/backend/requirements/studio.txtindex df04306b53b..e1e603e3486 100644--- a/studio/backend/requirements/studio.txt+++ b/studio/backend/requirements/studio.txt@@ -10,7 +10,8 @@ nest_asynciodatasets==4.3.0pyjwt# gradio>=4.0.0 # 148 MB - Unsloth uses React + FastAPI, not Gradio-huggingface-hub==0.36.2+huggingface-hub>=1.23.0,<2.0; python_version >= "3.10"+huggingface-hub==0.36.2; python_version < "3.10"# truststore is vendored at backend/vendor/, deliberately not a dependency.# Transitive via requests, pinned here for one reason: the GGUF header range-read# preflight bounds itself by half-closing the socket, and HTTPResponse.shutdown isdiff --git a/studio/backend/routes/models.py b/studio/backend/routes/models.pyindex 702c71b70ba..c253f98d05a 100644--- a/studio/backend/routes/models.py+++ b/studio/backend/routes/models.py@@ -3796,6 +3796,17 @@ _VIDEO_GEN_TASK = "text-to-video"_UNSUPPORTED_DIFFUSION_TASK = "image-diffusion-unsupported"+def _is_h3_bundle_gguf_hint(hint: Optional[str]) -> bool:+ """True when a name hint is one of the MiniMax-H3 GGUF bundle repos (video, never chat)."""+ if not hint:+ return False+ try:+ from hub.utils.gguf import is_h3_bundle_repo+ return is_h3_bundle_repo(hint)+ except Exception: # noqa: BLE001 -- never misclassify a model over a probe failure+ return False++def _gguf_architecture(path: str) -> Optional[str]:"""The GGUF ``general.architecture``, or None. Delegates to the shared,bounds-checked header reader (cached by path/mtime/size)."""@@ -3845,6 +3856,13 @@ def _video_family_buildable(fam) -> bool:def _arch_to_task(arch: Optional[str], name_hints: tuple[Optional[str], ...] = ()) -> Optional[str]:+ # MiniMax-H3's GGUFs carry NO metadata keys at all -- every file in the bundle, denoisers and+ # the Qwen conditioner alike, has kv_count 0, so general.architecture is absent where LTX-2 and+ # Wan GGUFs declare "ltxv"/"wan". The arch read therefore classifies the whole repo as unknown,+ # and an unknown task is dropped from the Video picker's On Device list while the chat picker+ # still offers the video DiT. Key the bundle repos by id instead, before the arch is consulted.+ if any(_is_h3_bundle_gguf_hint(hint) for hint in name_hints):+ return _VIDEO_GEN_TASKif arch is None:return Nonea = arch.lower()diff --git a/studio/backend/routes/training.py b/studio/backend/routes/training.pyindex bad23ca8fb7..3e3448038dc 100644--- a/studio/backend/routes/training.py+++ b/studio/backend/routes/training.py@@ -3403,7 +3403,7 @@ def _resolve_dataset_folder(name: str, *, must_exist: bool = True) -> Path:return folder-# Per-side dimension bound for uploaded training images, matching diffusion._decode_b64_image's 4096px guard, so a compressible PNG cannot smuggle huge pixels past the byte limit.+# Match diffusion's 4096px decoded-image limit._MAX_TRAINING_IMAGE_SIDE = 4096diff --git a/studio/backend/routes/video.py b/studio/backend/routes/video.pyindex d8f7196143b..006d653236e 100644--- a/studio/backend/routes/video.py+++ b/studio/backend/routes/video.py@@ -114,6 +114,10 @@ async def video_download_plan(family_override = request.family_override,model_kind = kind,base_repo = request.base_repo,+ # Validation is quant-keyed: a scheme this family can serve only from a hosted+ # pre-quantized checkpoint has to be refused HERE, on the route that stages the+ # download, or the panel fetches ~98.7 GB before /video/load can say no.+ transformer_quant = request.transformer_quant,)# BEFORE the plan is staged, as on the images side: /video/load refuses a precision this# host cannot honour, but the UI plans and downloads first, so an explicit FP8 on an@@ -141,6 +145,10 @@ async def video_download_plan(hf_token = request.hf_token,# The plan must see the encoder policy the load will use: an fp8 request takes a hosted pre-cast encoder, so staging the dense one wastes ~49 GB on LTX-2.text_encoder_quant = request.text_encoder_quant,+ # And the denoiser policy, for the same reason: a scheme with a hosted pre-quantized+ # checkpoint replaces the dense DiT, so without this the plan stages 66.3 GB of shards+ # the load never opens.+ transformer_quant = request.transformer_quant,)return DiffusionDownloadPlanResponse(**plan)except (ValueError, FileNotFoundError) as exc:@@ -185,6 +193,7 @@ async def load_video_model(model_kind = kind,transformer_quant = request.transformer_quant,text_encoder_quant = request.text_encoder_quant,+ h3_task = request.h3_task,)# Refuse while training is running (VRAM competition) BEFORE the precision check below:# that check runs an uncached quantise+matmul probe on the GPU, which would initialise a@@ -225,6 +234,7 @@ async def load_video_model(transformer_quant = request.transformer_quant,text_encoder_quant = request.text_encoder_quant,model_kind = kind,+ h3_task = request.h3_task,)if device != "cpu":@@ -289,6 +299,14 @@ async def generate_video(guidance = request.guidance,guidance_2 = request.guidance_2,seed = request.seed,+ first_frame = request.first_frame,+ last_frame = request.last_frame,+ reference_images = request.reference_images,+ reference_videos = [r.model_dump() for r in request.reference_videos or []] or None,+ reference_audios = request.reference_audios,+ reference_image_size = request.reference_image_size,+ flow_shift = request.flow_shift,+ audio_flow_shift = request.audio_flow_shift,)except VideoShapeError as exc:# 422 before the 400 below, and it must stay first: VideoShapeError IS a ValueError. The bodydiff --git a/studio/backend/tests/test_cached_gguf_routes.py b/studio/backend/tests/test_cached_gguf_routes.pyindex dcf64fba13b..c7e73de7e43 100644--- a/studio/backend/tests/test_cached_gguf_routes.py+++ b/studio/backend/tests/test_cached_gguf_routes.py@@ -2620,6 +2620,22 @@ def test_arch_to_task_hides_unsupported_diffusion_from_chat():assert not missing, f"diffusion archs would still show in chat: {missing}"+def test_arch_to_task_tags_the_h3_gguf_bundle_as_video():+ # The published MiniMax-H3 GGUFs carry kv_count 0, so general.architecture is absent and the+ # arch read alone leaves the downloaded repo without a task -- dropped from the Video picker's+ # On Device list and offered to chat instead. Both bundle repo ids must resolve to Video.+ from core.inference.video_minimax_h3 import H3_GGUF_REPO++ for repo in (H3_GGUF_REPO, "leejet/MiniMax-H3-GGUF"):+ assert (+ models_route._arch_to_task(None, (repo, "minimax_h3_fl2va-Q4_K_M.gguf"))+ == models_route._VIDEO_GEN_TASK+ )+ # No hint is still unknown, and an unrelated repo is untouched.+ assert models_route._arch_to_task(None) is None+ assert models_route._arch_to_task(None, ("unsloth/Qwen3-GGUF", "q.gguf")) is None++def test_arch_to_task_resolves_z_image_gguf_tagged_lumina2():# Z-Image's DiT is a Lumina2 derivative, so both Z-Image GGUF repos declare general.architecture = "lumina2". Reading# the arch alone tagged the whole line unsupported and hid it, even though validate_load_request loads it happily.diff --git a/studio/backend/tests/test_diffusion_prequant.py b/studio/backend/tests/test_diffusion_prequant.pyindex 71d01ca6da0..64beebbaa9a 100644--- a/studio/backend/tests/test_diffusion_prequant.py+++ b/studio/backend/tests/test_diffusion_prequant.py@@ -282,6 +282,10 @@ class _FakeTransformer:def buffers(self):return []+ def named_modules(self):+ # Real nn.Modules have this, and the small-M padding pass walks it.+ return []+def to(self, device):self.moved = devicereturn self@@ -1366,6 +1370,56 @@ def test_the_config_follows_the_checkpoint_into_the_other_cache_root(monkeypatchassert seen == [None] # read straight through the root that supplied the checkpoint+# ── small-M activation padding on the hosted path ────────────────────────────────+++def test_load_pads_the_small_m_linears_with_the_recorded_family(monkeypatch, tmp_path):+ """A checkpoint built under the current exclusion set QUANTISES its family's small-M linears,+ so the loader must wrap them exactly as the runtime dense-quantise path does. The family comes+ from the checkpoint's own metadata, not from the caller: it is the same field+ ``_validate_checkpoint`` derives the expected exclusion set from, so the two cannot disagree+ about which model this is."""+ from core.inference.diffusion_transformer_quant import exclude_tokens_for_scheme++ seen = {}++ def _spy(+ transformer,+ scheme,+ family = None,+ logger = None,+ ):+ seen["args"] = (scheme, family)+ return ("context_embedder",)++ monkeypatch.setattr("core.inference.diffusion_transformer_quant.apply_small_m_padding", _spy)+ ckpt = _good_ckpt(scheme = "int8")+ ckpt["metadata"]["family"] = "minimax-h3"+ ckpt["metadata"]["exclude_name_tokens"] = list(exclude_tokens_for_scheme("int8", "minimax-h3"))+ assert _load(monkeypatch, tmp_path, ckpt, scheme = "int8") is not None+ assert seen["args"] == ("int8", "minimax-h3")+++def test_load_is_dropped_when_the_padding_cannot_be_proven(monkeypatch, tmp_path):+ """Half-padded is the worst outcome: it compiles on the modules that were wrapped and crashes+ inside ``_int_mm`` on the ones that were not. A raise must drop the prequant so the caller+ falls back to dense-quantise, rather than returning a transformer that renders once and dies+ the moment the compiled scope reaches the text stream."""++ def _boom(+ transformer,+ scheme,+ family = None,+ logger = None,+ ):+ raise RuntimeError("cannot prove per-row granularity")++ monkeypatch.setattr("core.inference.diffusion_transformer_quant.apply_small_m_padding", _boom)+ ckpt = _good_ckpt(scheme = "int8")+ ckpt["metadata"]["family"] = "minimax-h3"+ assert _load(monkeypatch, tmp_path, ckpt, scheme = "int8") is None++# ── fp8 activation scale floor ──────────────────────────────────────────────────diff --git a/studio/backend/tests/test_diffusion_quant_pad.py b/studio/backend/tests/test_diffusion_quant_pad.pynew file mode 100644index 00000000000..72d3cd20b5d--- /dev/null+++ b/studio/backend/tests/test_diffusion_quant_pad.py@@ -0,0 +1,326 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Tests for the small-M activation padding (``diffusion_quant_pad.py``).++Real torch, CPU only: the padding is a shape transform plus a slice, so a dense Linear proves+every structural property (shape, pad-row content, state-dict transparency, attribute+passthrough). The granularity gate is exercised against FAKE torchao weight layouts, so the+tests pin the ATTRIBUTES the probe reads rather than needing torchao installed. One CUDA-gated+test closes the loop on a genuinely int8-quantized Linear.+"""++from __future__ import annotations++import types++import pytest++torch = pytest.importorskip("torch")+nn = torch.nn++from core.inference.diffusion_quant_pad import ( # noqa: E402+ DEFAULT_PAD_TO,+ INT_MM_MIN_M,+ PadToMinM,+ activation_granularity_is_per_row,+ is_quantized_linear,+ matching_linear_fqns,+ padding_is_bitwise_exact,+ wrap_small_m_linears,+)+++class _RecordingLinear(nn.Linear):+ """A Linear that remembers the activation it was handed, so the pad rows are inspectable."""++ def forward(self, x):+ self.seen = x.detach().clone()+ return super().forward(x)+++def _fake_quant_tensor_type(**class_attrs):+ """A stand-in for a torchao weight subclass.++ The marker the probe looks for is ``__tensor_flatten__``, which every torchao tensor subclass+ defines. The granularity attributes are set on the TYPE rather than on the instance because+ ``nn.Parameter(subclass_tensor)`` returns ``tensor.detach()`` -- a fresh Python object of the+ same type -- so an instance attribute would not survive the assignment the real quantiser+ makes either."""++ def __tensor_flatten__(self): # pragma: no cover - presence is the whole point+ return ["qdata"], None++ return type(+ "_FakeQuantTensor",+ (torch.Tensor,),+ {"__tensor_flatten__": __tensor_flatten__, **class_attrs},+ )+++def _fake_quantized_linear(+ in_f = 8,+ out_f = 6,+ *,+ per_row = True,+ unknown = False,+):+ """A Linear whose weight advertises a torchao layout with a chosen activation granularity."""+ if unknown:+ attrs = {}+ elif per_row:+ attrs = {+ "input_quant_func": types.SimpleNamespace(+ __name__ = "_int8_symm_per_token_reduced_range_quant"+ )+ }+ else:+ attrs = {"input_quant_func": types.SimpleNamespace(__name__ = "_int8_symm_per_tensor_quant")}+ lin = nn.Linear(in_f, out_f)+ lin.weight = nn.Parameter(+ lin.weight.data.as_subclass(_fake_quant_tensor_type(**attrs)), requires_grad = False+ )+ return lin+++# ── shape and value preservation ──────────────────────────────────────────────++[email protected]("m", [1, 5, 10, 16, 17, 19, 64])[email protected]("lead", [(), (2,), (2, 3)])+def test_padding_returns_the_unpadded_result(m, lead):+ """The rows the caller asked for come back unchanged, at the caller's leading dims.++ The reference is the same module without the wrapper, so any difference is the padding's+ fault and nothing else's. Note the tolerance: this is a DENSE float Linear, where a taller+ GEMM can pick a different BLAS path and reassociate the accumulation (torch routes a single+ row through addmv and 32 rows through addmm). The exactness claim belongs to the int8 path,+ where the accumulation is integer and therefore order-independent -- see+ ``test_int8_padding_is_bitwise_exact_on_a_real_quantized_linear``."""+ torch.manual_seed(0)+ inner = nn.Linear(8, 6)+ wrapped = PadToMinM(inner, min_m = INT_MM_MIN_M, pad_to = DEFAULT_PAD_TO)+ x = torch.randn(*lead, m, 8)+ with torch.no_grad():+ got, want = wrapped(x), inner(x)+ assert got.shape == (*lead, m, 6) == want.shape+ assert torch.allclose(got, want, rtol = 0, atol = 1e-6)+++def test_pad_rows_replicate_row_zero_rather_than_being_zeros():+ """An all-zero pad row has amax 0, so the activation quantizer divides by zero and the+ intermediate goes NaN. Replicating row 0 costs the same and keeps it finite -- and it is+ also what makes a per-tensor AMAX invariant, since it introduces no new element values."""+ inner = _RecordingLinear(8, 6)+ wrapped = PadToMinM(inner, min_m = 17, pad_to = 32)+ x = torch.randn(5, 8)+ wrapped(x)+ seen = inner.seen+ assert seen.shape == (32, 8), "activation must reach the GEMM at exactly pad_to rows"+ assert torch.equal(seen[:5], x), "the caller's rows must be untouched"+ for row in range(5, 32):+ assert torch.equal(seen[row], x[0]), f"pad row {row} is not a copy of row 0"+ assert not (seen[5:] == 0).all(), "pad rows must not be zeros"+++def test_every_small_activation_normalises_to_one_row_count():+ """Below ``pad_to`` every activation reaches the GEMM at exactly ``pad_to`` rows, so one+ inductor graph covers every prompt length in the range rather than one graph per length.+ H3's seven eval prompts run at M = 10, 13, 13, 13, 14, 17, 19 -- which straddles the floor,+ so padding only up to ``min_m`` would leave three distinct shapes behind."""+ inner = _RecordingLinear(8, 6)+ wrapped = PadToMinM(inner, min_m = 17, pad_to = 32)+ for m in (1, 10, 13, 14, 16, 17, 19, 31):+ wrapped(torch.randn(m, 8))+ assert inner.seen.shape == (32, 8), f"M = {m} did not normalise to 32 rows"+++def test_no_padding_at_or_above_pad_to():+ """A module that is small on one call and large on the next must pay nothing on the large+ one: at or above ``pad_to`` the activation reaches the GEMM at its own row count."""+ inner = _RecordingLinear(8, 6)+ wrapped = PadToMinM(inner, min_m = 17, pad_to = 32)+ wrapped(torch.randn(32, 8))+ assert inner.seen.shape == (32, 8)+ wrapped(torch.randn(4096, 8))+ assert inner.seen.shape == (4096, 8)+++def test_zero_rows_return_the_projected_width():+ """torchao hands a zero-row activation back UNPROJECTED, so a downstream width-sensitive add+ crashes. The wrapper has no row 0 to replicate either, so it synthesises the empty result."""+ inner = _RecordingLinear(8, 6)+ wrapped = PadToMinM(inner)+ out = wrapped(torch.randn(0, 8))+ assert out.shape == (0, 6), "an empty activation must still come back 6 wide, not 8"+ assert not hasattr(inner, "seen"), "the inner GEMM must not be called with zero rows"+++def test_pad_to_can_never_sit_below_min_m():+ """``pad_to`` exists to buy tiling and shape stability above the floor, never to undercut+ it: a 'padded' activation below ``min_m`` would still trip the assert it exists to clear."""+ inner = nn.Linear(8, 6)+ assert PadToMinM(inner, min_m = 17, pad_to = 8).pad_to == 17+ assert PadToMinM(inner, min_m = 17, pad_to = None).pad_to == 17+ assert PadToMinM(inner, min_m = 17, pad_to = 32).pad_to == 32+++def test_forward_holds_no_mutable_integer_state():+ """dynamo guards on an nn.Module's integer attributes, so a counter incremented in forward+ would recompile on every call until the recompile limit silently drops the module to eager.+ The wrapper's ints must be exactly the two configured constants, before and after use."""++ def int_attrs(module):+ return {+ k: v for k, v in vars(module).items() if isinstance(v, int) and not isinstance(v, bool)+ }++ wrapped = PadToMinM(nn.Linear(8, 6), min_m = 17, pad_to = 32)+ before = int_attrs(wrapped)+ for m in (3, 3, 40, 3):+ wrapped(torch.randn(m, 8))+ assert before == int_attrs(wrapped) == {"min_m": 17, "pad_to": 32}+++# ── drop-in transparency ──────────────────────────────────────────────────────+++def test_attributes_pass_through_to_the_inner_linear():+ """diffusers' attention processors read ``to_q.weight.dtype`` and H3's blocks read+ ``context_embedder.weight``; without the passthrough the wrapper is a drop-in only until the+ first such access, which fails at render time rather than at wrap time."""+ inner = nn.Linear(8, 6)+ wrapped = PadToMinM(inner)+ assert wrapped.in_features == 8+ assert wrapped.out_features == 6+ assert wrapped.weight is inner.weight+ assert wrapped.bias is inner.bias+ with pytest.raises(AttributeError):+ wrapped.definitely_not_a_linear_attribute+++class _Tiny(nn.Module):+ def __init__(self):+ super().__init__()+ self.context_embedder = nn.Linear(8, 6)+ self.other = nn.Linear(4, 4)+++def test_state_dict_hides_the_wrapper_in_both_directions():+ """The prequant builder saves a state dict and the loader loads one into a fresh tree, so a+ wrapper that renamed ``context_embedder.weight`` to ``context_embedder.inner.weight`` would+ split the two halves of the checkpoint contract. It must be invisible either way round."""+ plain, wrapped_model = _Tiny(), _Tiny()+ wrapped_model.context_embedder = PadToMinM(wrapped_model.context_embedder)++ assert sorted(wrapped_model.state_dict()) == sorted(plain.state_dict())+ assert "context_embedder.inner.weight" not in wrapped_model.state_dict()++ # A checkpoint written from a wrapped tree loads into an unwrapped one, and the reverse.+ assert plain.load_state_dict(dict(wrapped_model.state_dict()), strict = True)+ assert wrapped_model.load_state_dict(dict(plain.state_dict()), strict = True)+ assert torch.equal(wrapped_model.context_embedder.weight, plain.context_embedder.weight)+++# ── the granularity gate ──────────────────────────────────────────────────────+++def test_activation_granularity_probe_reads_both_torchao_layouts():+ """v1 tensors expose the activation quantizer as ``input_quant_func`` and v2 ones as+ ``act_quant_kwargs.granularity``. An unrecognised layout answers None, not True: the caller+ treats unproven as unsafe."""+ assert activation_granularity_is_per_row(_fake_quantized_linear(per_row = True)) is True+ assert activation_granularity_is_per_row(_fake_quantized_linear(per_row = False)) is False+ assert activation_granularity_is_per_row(_fake_quantized_linear(unknown = True)) is None++ def _v2(granularity_cls_name):+ lin = nn.Linear(8, 6)+ kwargs = types.SimpleNamespace(granularity = type(granularity_cls_name, (), {})())+ lin.weight = nn.Parameter(+ lin.weight.data.as_subclass(_fake_quant_tensor_type(act_quant_kwargs = kwargs)),+ requires_grad = False,+ )+ return lin++ assert activation_granularity_is_per_row(_v2("PerRow")) is True+ assert activation_granularity_is_per_row(_v2("PerToken")) is True+ assert activation_granularity_is_per_row(_v2("PerTensor")) is False+ assert activation_granularity_is_per_row(_v2("PerGroup")) is False++ # A dense Linear is not quantized at all, so there is no activation granularity to report.+ assert activation_granularity_is_per_row(nn.Linear(8, 6)) is None+++def test_wrap_raises_rather_than_skipping_an_unprovable_linear():+ """Silence is the worst outcome: a half-padded transformer compiles on the modules that were+ wrapped and crashes inside ``_int_mm`` on the ones that were not."""+ model = _Tiny()+ model.context_embedder = _fake_quantized_linear(per_row = False)+ with pytest.raises(RuntimeError, match = "provably per row"):+ wrap_small_m_linears(model, ["context_embedder"])+ assert isinstance(model.context_embedder, nn.Linear), "must not leave a partial wrap behind"++ model.context_embedder = _fake_quantized_linear(unknown = True)+ with pytest.raises(RuntimeError, match = "provably per row"):+ wrap_small_m_linears(model, ["context_embedder"])+++def test_wrap_skips_dense_and_already_wrapped_linears():+ """One gate covers both. A dense ``F.linear`` has no row floor, so there is nothing to pad+ and nothing to prove; and a ``PadToMinM`` is not an ``nn.Linear`` either, so a second pass+ cannot nest the padding and double the row count."""+ model = _Tiny()+ assert wrap_small_m_linears(model, ["context_embedder"]) == ()+ assert isinstance(model.context_embedder, nn.Linear)++ model.context_embedder = _fake_quantized_linear()+ assert wrap_small_m_linears(model, ["context_embedder"]) == ("context_embedder",)+ assert isinstance(model.context_embedder, PadToMinM)+ assert wrap_small_m_linears(model, ["context_embedder"]) == ()+ assert not isinstance(model.context_embedder.inner, PadToMinM)+ # The wrapper forwards `weight` to its inner Linear, so the gate cannot lean on that alone.+ assert model.context_embedder.weight is model.context_embedder.inner.weight+ assert is_quantized_linear(model.context_embedder) is False+++def test_wrap_ignores_names_absent_from_this_checkpoint_variant():+ """The pruned and dense H3 trees differ, so a family token list is a name list rather than a+ promise that every name exists."""+ assert wrap_small_m_linears(_Tiny(), ["token_refiner.refiner_blocks.0.attn.to_q"]) == ()+++def test_matching_fqns_selects_quantized_linears_by_substring():+ """Same substring rule ``make_filter_fn`` applies to exclusions, so the pad list and the+ exclude list are read the same way -- and a dense Linear never enters the pad list."""+ model = _Tiny()+ model.context_embedder = _fake_quantized_linear()+ assert matching_linear_fqns(model, ("context_embedder",)) == ("context_embedder",)+ assert matching_linear_fqns(model, ("CONTEXT_EMBEDDER",)) == ("context_embedder",)+ assert matching_linear_fqns(model, ("other",)) == (), "dense Linears are not pad candidates"+ assert matching_linear_fqns(model, ()) == ()+++def test_is_quantized_linear_only_accepts_a_torchao_weight():+ assert is_quantized_linear(_fake_quantized_linear()) is True+ assert is_quantized_linear(nn.Linear(8, 6)) is False+ assert is_quantized_linear(nn.LayerNorm(8)) is False+++# ── the real thing ────────────────────────────────────────────────────────────++[email protected](not torch.cuda.is_available(), reason = "int8 dynamic quant needs CUDA")+def test_int8_padding_is_bitwise_exact_on_a_real_quantized_linear():+ """Closes the loop the fakes leave open: a genuinely torchao-quantized Linear, at the row+ counts H3's seven eval prompts produce (M = 10..19, straddling ``_int_mm``'s floor of 16)."""+ pytest.importorskip("torchao")+ from torchao.quantization import quantize_++ from core.inference.diffusion_transformer_quant import _make_quant_config, make_filter_fn++ lin = nn.Linear(1024, 768, bias = False).cuda().bfloat16().eval()+ quantize_(lin, _make_quant_config("int8"), filter_fn = make_filter_fn(0))+ assert is_quantized_linear(lin)+ assert activation_granularity_is_per_row(lin) is True+ for m in (1, 10, 13, 16, 17, 19, 64):+ assert padding_is_bitwise_exact(lin, m), f"padding changed the kept rows at M = {m}"diff --git a/studio/backend/tests/test_diffusion_transformer_quant.py b/studio/backend/tests/test_diffusion_transformer_quant.pyindex 203e3c08621..f7999e5d7c2 100644--- a/studio/backend/tests/test_diffusion_transformer_quant.py+++ b/studio/backend/tests/test_diffusion_transformer_quant.py@@ -843,6 +843,166 @@ def test_the_attention_trim_families_exclude_their_small_m_text_streams():assert exclude_tokens_for_scheme(TQ_INT8, None) == _INT8_EXCLUDE_NAME_TOKENS+def test_minimax_h3_int8_excludes_its_adaln_projection():+ """H3's adaLN projection is named ``adaln_proj``, which the generic token list does not match.++ "norm" is the closest generic token and it does not appear in the name, so on the DENSE+ checkpoint Linear(2688 -> 96768) clears min_features = 512, gets quantized, then runs at M = 1+ and raises "self.size(0) needs to be greater than 16, but got 1" at the first denoise. Measured:+ the offline builder bakes it and torch.compile dies on that module.++ The pruned-modulation form hides this rather than fixing it, since there adaln_proj is+ Linear(8 -> 96768) and falls under min_features anyway (verified on the fl2va_pruned build:+ all 51 of them are rejected for min_features, in_features = 8). So this exclusion is what+ makes the DENSE path correct and is a no-op on the pruned one.+ """+ from core.inference.diffusion_transformer_quant import TQ_INT8, exclude_tokens_for_scheme++ assert "adaln_proj" in exclude_tokens_for_scheme(TQ_INT8, "minimax-h3")++ # The generic list genuinely does not cover adaln_proj, which is why the entry is needed at all.+ # If a future generic token starts matching it, this assertion fails and the family entry can+ # be reconsidered rather than left as dead weight.+ from core.inference.diffusion_transformer_quant import _INT8_EXCLUDE_NAME_TOKENS++ assert not any(t in "adaln_proj" for t in _INT8_EXCLUDE_NAME_TOKENS)+ # fp8 has no M floor, so it must not inherit any of this.+ assert exclude_tokens_for_scheme("fp8", "minimax-h3") == ()+++def test_minimax_h3_pads_its_text_stream_instead_of_excluding_it():+ """context_embedder and the two token_refiner blocks are QUANTIZED and padded, not skipped.++ They run at M = text tokens (10..19 across the seven eval prompts), which straddles+ ``_int_mm``'s floor of 16, so they used to be excluded. Padding the activation up to 32 rows+ is bitwise exact under per-row activation scaling and recovers 0.80 GB of weights, so the+ two names moved from the exclude list to the pad list. Both halves are asserted here: a+ change that dropped one without the other would either crash under compile or silently+ quantise nothing."""+ from core.inference.diffusion_transformer_quant import (+ TQ_INT8,+ exclude_tokens_for_scheme,+ pad_tokens_for_scheme,+ )++ pad = pad_tokens_for_scheme(TQ_INT8, "minimax-h3")+ exclude = exclude_tokens_for_scheme(TQ_INT8, "minimax-h3")+ for name in ("context_embedder", "token_refiner"):+ assert name in pad, f"minimax-h3 int8 must pad {name}"+ assert name not in exclude, f"{name} is padded, so excluding it would quantise nothing"+++def test_pad_and_exclude_sets_never_overlap():+ """An excluded Linear is never quantized, so there would be nothing to pad. A name in both+ lists means one of them is dead, and which one is dead is not visible at the call site."""+ from core.inference.diffusion_transformer_quant import (+ _INT8_FAMILY_PAD_NAME_TOKENS,+ TQ_INT8,+ exclude_tokens_for_scheme,+ pad_tokens_for_scheme,+ )+ for family in _INT8_FAMILY_PAD_NAME_TOKENS:+ exclude = exclude_tokens_for_scheme(TQ_INT8, family)+ for pad_token in pad_tokens_for_scheme(TQ_INT8, family):+ assert not any(+ e in pad_token or pad_token in e for e in exclude+ ), f"{family}: {pad_token!r} is both padded and excluded"+++def test_only_minimax_h3_pads_today():+ """Scoped deliberately. qwen-image, qwen-image-edit and hunyuanvideo-1.5 have the same+ small-M shape and could adopt this, but each has a PUBLISHED int8 prequant checkpoint whose+ metadata bakes the current exclusion set, and ``_validate_checkpoint`` compares that set+ against ``exclude_tokens_for_scheme``. Flipping one of them without rebuilding and+ republishing its artifact turns every hosted int8 load into a silent fallback."""+ from core.inference.diffusion_transformer_quant import TQ_INT8, pad_tokens_for_scheme++ for family in ("qwen-image", "qwen-image-edit", "hunyuanvideo-1.5", "hunyuanvideo-1.5-720p"):+ assert pad_tokens_for_scheme(TQ_INT8, family) == ()+ assert pad_tokens_for_scheme(TQ_INT8, "z-image") == ()+ assert pad_tokens_for_scheme(TQ_INT8, None) == ()+++def test_only_int8_pads():+ """``_int_mm``'s row floor is int8's alone: scaled_mm and the MX/FP4 kernels have no+ equivalent, so no other scheme should be paying for a pad-and-slice."""+ from core.inference.diffusion_transformer_quant import pad_tokens_for_scheme+ for scheme in ("fp8", "nvfp4", "mxfp8", "auto"):+ assert pad_tokens_for_scheme(scheme, "minimax-h3") == ()+++def test_quantize_transformer_pads_after_quantising(monkeypatch):+ """The padding runs on the RUNTIME dense-quantise path too, not only on the prequant one,+ and it runs AFTER quantize_ (it reparents Linears that must already hold quantized weights).+ """+ _stub_torch(monkeypatch, cc = (10, 0))+ _allow(monkeypatch, {TQ_INT8})+ order = []+ tqz = types.ModuleType("torchao.quantization")+ tqz.quantize_ = lambda module, config, filter_fn = None: order.append("quantize_")+ tqz.Int8DynamicActivationInt8WeightConfig = lambda: "int8-cfg"+ tqz.Float8DynamicActivationFloat8WeightConfig = lambda **kw: "fp8-cfg"+ tqz.PerRow = lambda: "per-row"+ monkeypatch.setitem(sys.modules, "torchao.quantization", tqz)+ monkeypatch.setattr(+ tq,+ "apply_small_m_padding",+ lambda transformer, scheme, family = None, logger = None: (+ order.append(("pad", scheme, family)) or ()+ ),+ )+ pipe = types.SimpleNamespace(transformer = types.SimpleNamespace())+ assert quantize_transformer(pipe, _target(), mode = "int8", family = "minimax-h3") == TQ_INT8+ assert order == ["quantize_", ("pad", TQ_INT8, "minimax-h3")]+++def test_quantize_transformer_refuses_when_padding_cannot_be_proven(monkeypatch):+ """A half-padded transformer compiles on the modules that were wrapped and crashes inside+ ``_int_mm`` on the ones that were not, so a raise from the padding must fail the whole+ quantise and send the caller to GGUF -- not be swallowed into a partially padded model."""+ _stub_torch(monkeypatch, cc = (10, 0))+ _allow(monkeypatch, {TQ_INT8})+ tqz = types.ModuleType("torchao.quantization")+ tqz.quantize_ = lambda module, config, filter_fn = None: None+ tqz.Int8DynamicActivationInt8WeightConfig = lambda: "int8-cfg"+ tqz.Float8DynamicActivationFloat8WeightConfig = lambda **kw: "fp8-cfg"+ tqz.PerRow = lambda: "per-row"+ monkeypatch.setitem(sys.modules, "torchao.quantization", tqz)++ def _boom(+ transformer,+ scheme,+ family = None,+ logger = None,+ ):+ raise RuntimeError("cannot prove per-row granularity")++ monkeypatch.setattr(tq, "apply_small_m_padding", _boom)+ pipe = types.SimpleNamespace(transformer = types.SimpleNamespace())+ assert quantize_transformer(pipe, _target(), mode = "int8", family = "minimax-h3") is None+ assert not hasattr(pipe.transformer, "_unsloth_runtime_quant")+++def test_apply_small_m_padding_is_inert_without_a_pad_list(monkeypatch):+ """No pad list means the padding module is never even IMPORTED.++ That matters beyond the wasted traversal: ``diffusion_transformer_quant`` deliberately keeps+ torch out of its own import path (every probe imports lazily), while ``diffusion_quant_pad``+ subclasses ``nn.Module`` and so must import torch at module scope. Shadowing the module with+ an empty stub makes the import observable: it raises for the family that pads, and must not+ be reached at all for anything else."""+ from core.inference.diffusion_transformer_quant import TQ_INT8, apply_small_m_padding++ stub = types.ModuleType("core.inference.diffusion_quant_pad") # no names to import+ monkeypatch.setitem(sys.modules, "core.inference.diffusion_quant_pad", stub)++ assert apply_small_m_padding(object(), TQ_INT8, "z-image") == ()+ assert apply_small_m_padding(object(), "fp8", "minimax-h3") == ()+ assert apply_small_m_padding(object(), TQ_INT8, None) == ()+ with pytest.raises(ImportError):+ apply_small_m_padding(object(), TQ_INT8, "minimax-h3")++def test_the_training_deny_is_a_superset_of_the_inference_deny():# The two tables are separate because rendering evidence is not training evidence, but the# relationship must only ever go one way: anything inference refuses, training refuses too.diff --git a/studio/backend/tests/test_mlx_repair.py b/studio/backend/tests/test_mlx_repair.pyindex 9bcc93d742d..09d4977720e 100644--- a/studio/backend/tests/test_mlx_repair.py+++ b/studio/backend/tests/test_mlx_repair.py@@ -113,7 +113,7 @@ def test_repair_install_pins_transformers_and_cleans_up(monkeypatch):assert pkg in cmdassert created_paths and not Path(created_paths[0]).exists()# The install mirrors the main installer by relaxing the transformers pin via- # UV_OVERRIDE so a current mlx-vlm can coexist with transformers==4.57.6.+ # UV_OVERRIDE so a current mlx-vlm can coexist with the Studio Transformers pin.env = captured["env"]assert env is not Noneassert env.get("UV_OVERRIDE", "").endswith("overrides-darwin-arm64.txt")diff --git a/studio/backend/tests/test_sd_cpp_args.py b/studio/backend/tests/test_sd_cpp_args.pyindex 0b2400f4e8a..763024f0be5 100644--- a/studio/backend/tests/test_sd_cpp_args.py+++ b/studio/backend/tests/test_sd_cpp_args.py@@ -22,10 +22,12 @@ from core.inference.sd_cpp_args import (SdCppGenParams,SdCppModelFiles,SdCppUpscaleParams,+ SdCppVideoGenParams,build_img_gen_request,build_sd_cpp_command,build_sd_cpp_server_command,build_sd_cpp_upscale_command,+ build_sd_cpp_video_command,is_ggml_unsupported_op_abort,metal_text_encoder_flags,native_speed_flags,@@ -81,8 +83,19 @@ def test_metal_text_encoder_flag_reaches_both_command_builders(monkeypatch):params = SdCppGenParams(prompt = "x"),output_path = "/o/x.png",)+ video = build_sd_cpp_video_command(+ binary = "sd-cli",+ files = SdCppModelFiles(+ diffusion_model = "/m/h3.gguf",+ vae = "/m/video.safetensors",+ llm = "/m/qwen.gguf",+ ),+ params = SdCppVideoGenParams(prompt = "x", width = 960, height = 544, num_frames = 124),+ output_path = "/o/x.webm",+ )assert server.count("--clip-on-cpu") == 1assert cli.count("--clip-on-cpu") == 1+ assert video.count("--clip-on-cpu") == 1# An offload policy that already pins the encoder must not emit it twice.dual = build_sd_cpp_server_command(binary = "sd-server",@@ -139,6 +152,30 @@ def test_offload_model_pushes_everything_to_cpu_and_tiles():assert offload_flags(OFFLOAD_SEQUENTIAL) == flags+def test_offload_can_keep_the_vae_off_the_cpu_path():+ """H3's audio VAE aborts on the CPU path, so `low_vram` has to drop just that flag.++ `ggml_conv_1d` hardcodes an F16 im2col destination and+ `ggml_compute_forward_im2col_f16` then asserts the kernel is F16, while sd.cpp's+ `audio_conv_weight_type` maps only BF16 to F16 and lets F32 through:+ `GGML_ASSERT(src0->type == GGML_TYPE_F16) failed`, SIGABRT, exit 134. Converting the+ checkpoint to fp16 does not help, since the type is imposed inside sd.cpp.++ Everything else the policy asks for still applies. The denoiser dominates, so+ `--offload-to-cpu` is where the saving is; dropping the mode entirely would cost far+ more than dropping this one flag.+ """+ for policy in (OFFLOAD_MODEL, OFFLOAD_SEQUENTIAL):+ flags = offload_flags(policy, vae_on_cpu = False)+ assert "--vae-on-cpu" not in flags+ for expected in ("--offload-to-cpu", "--clip-on-cpu", "--vae-tiling", "--diffusion-fa"):+ assert expected in flags, f"{policy}: {expected} should survive"+ # The default is unchanged for every other family.+ assert "--vae-on-cpu" in offload_flags(OFFLOAD_MODEL)+ # And it is a no-op where the policy never emitted it.+ assert offload_flags(OFFLOAD_GROUP, vae_on_cpu = False) == offload_flags(OFFLOAD_GROUP)++def test_offload_forced_flags_dedup():# vae_tiling/diffusion_fa forced on with a policy that already sets themflags = offload_flags(OFFLOAD_MODEL, vae_tiling = True, diffusion_fa = True)@@ -557,3 +594,117 @@ def test_server_command_appends_extra_args_last():)assert cmd[-2:] == ["--backend", "cpu"]assert cmd[0] == "/x/sd-server"+++def test_minimax_h3_video_command_has_all_joint_av_components():+ files = SdCppModelFiles(+ diffusion_model = "/m/minimax_h3_fl2va-Q4_K_M.gguf",+ vae = "/m/video.safetensors",+ audio_vae = "/m/audio.safetensors",+ llm = "/m/qwen.gguf",+ )+ cmd = build_sd_cpp_video_command(+ "/bin/sd-cli",+ files,+ SdCppVideoGenParams(+ prompt = "a fox runs through snow",+ width = 960,+ height = 544,+ num_frames = 124,+ fps = 24,+ steps = 30,+ seed = 42,+ ),+ output_path = "/out/result.webm",+ offload = ["--diffusion-fa", "--offload-to-cpu"],+ )+ assert _pair(cmd, "--mode") == "vid_gen"+ assert _pair(cmd, "--audio-vae") == "/m/audio.safetensors"+ assert _pair(cmd, "--llm") == "/m/qwen.gguf"+ assert _pair(cmd, "--video-frames") == "124"+ assert _pair(cmd, "--fps") == "24"+ assert _pair(cmd, "--cfg-scale") == "1"+ assert "--rng" in cmd and _pair(cmd, "--rng") == "cpu"+ assert cmd[-2:] == ["--diffusion-fa", "--offload-to-cpu"]+++def _h3_video_cmd(**params):+ return build_sd_cpp_video_command(+ "/bin/sd-cli",+ SdCppModelFiles(+ diffusion_model = "/m/minimax_h3_fl2va-Q4_K_M.gguf",+ vae = "/m/video.safetensors",+ audio_vae = "/m/audio.safetensors",+ llm = "/m/qwen.gguf",+ ),+ SdCppVideoGenParams(+ prompt = "a fox runs through snow",+ width = 960,+ height = 544,+ num_frames = 124,+ **params,+ ),+ output_path = "/out/result.webm",+ )+++def test_minimax_h3_video_command_omits_keyframe_flags_for_text_only():+ cmd = _h3_video_cmd()+ assert "--init-img" not in cmd+ assert "--end-img" not in cmd+++def test_minimax_h3_video_command_carries_each_keyframe():+ # Each keyframe combination maps to its sd.cpp flags.+ assert _pair(_h3_video_cmd(init_img = "/k/first.png"), "--init-img") == "/k/first.png"+ assert "--end-img" not in _h3_video_cmd(init_img = "/k/first.png")++ end_only = _h3_video_cmd(end_img = "/k/last.png")+ assert _pair(end_only, "--end-img") == "/k/last.png"+ assert "--init-img" not in end_only++ both = _h3_video_cmd(init_img = "/k/first.png", end_img = "/k/last.png")+ assert _pair(both, "--init-img") == "/k/first.png"+ assert _pair(both, "--end-img") == "/k/last.png"+++def test_minimax_h3_video_command_packs_references_in_reading_order():+ # Preserve the model's reference order.+ cmd = _h3_video_cmd(+ ref_images = ("/r/cat.png", "/r/style.png"),+ ref_videos = ("/r/motion", "/r/orbit"),+ ref_video_audios = ("/r/motion.wav",),+ ref_audios = ("/r/voice.wav",),+ )+ assert [c for c in cmd if c.startswith("--ref")] == [+ "--ref-image",+ "--ref-image",+ "--ref-video",+ "--ref-video",+ "--ref-video-audio",+ "--ref-audio",+ ]+ assert cmd[cmd.index("--ref-image") + 1] == "/r/cat.png"+ assert cmd[cmd.index("--ref-video") + 1] == "/r/motion"+ assert cmd[cmd.index("--ref-audio") + 1] == "/r/voice.wav"+++def test_minimax_h3_video_command_refuses_keyframes_with_references():+ # sd.cpp refuses the pair itself, but only once the model is resident.+ with pytest.raises(ValueError, match = "different denoiser partitions"):+ _h3_video_cmd(init_img = "/k/first.png", ref_images = ("/r/cat.png",))+ with pytest.raises(ValueError, match = "different denoiser partitions"):+ _h3_video_cmd(end_img = "/k/last.png", ref_audios = ("/r/voice.wav",))+++def test_minimax_h3_video_command_refuses_an_unpairable_soundtrack():+ # Reject soundtrack flags without a video at the same position.+ with pytest.raises(ValueError, match = "reference video to pair with"):+ _h3_video_cmd(ref_videos = ("/r/motion",), ref_video_audios = ("/r/a.wav", "/r/b.wav"))+++def test_minimax_h3_video_command_carries_the_video_flow_shift():+ # sd.cpp derives the audio schedule against a hardcoded 3.0, so only the video shift is a flag.+ assert "--flow-shift" not in _h3_video_cmd()+ assert _pair(_h3_video_cmd(flow_shift = 8.5), "--flow-shift") == "8.5"+ assert _pair(_h3_video_cmd(flow_shift = 12.0), "--flow-shift") == "12"diff --git a/studio/backend/tests/test_sd_cpp_backend.py b/studio/backend/tests/test_sd_cpp_backend.pyindex b977247ce75..37e86b375c4 100644--- a/studio/backend/tests/test_sd_cpp_backend.py+++ b/studio/backend/tests/test_sd_cpp_backend.py@@ -685,6 +685,83 @@ def test_ensure_binary_install_disabled_returns_none(monkeypatch):assert ensure_sd_cpp_binary(allow_install = False) is None+# A --help extract shaped like the real one: the mode list and --audio-vae are old enough to be in+# a pre-H3 build too (they came with LTX-2), so only the H3-only --ref-video separates the two.+_PRE_H3_HELP = (+ " -M, --mode run mode, one of [img_gen, vid_gen, upscale, convert]\n"+ " --audio-vae <string> path to standalone LTX audio vae model\n"+)+_H3_HELP = _PRE_H3_HELP + (+ " --ref-video MiniMax-H3 Ref2VA reference video frame directory at 24 fps\n"+)+++def test_h3_binary_gate_replaces_a_stale_managed_install(monkeypatch, tmp_path):+ # An upgraded Studio still carrying an older managed sd-cli got that binary handed straight+ # back: only runnability was probed, so the H3 load reported ready on a build with no H3+ # support and the first generation failed, after the whole bundle had already downloaded.+ stale = tmp_path / "stale" / "sd-cli"+ fresh = tmp_path / "fresh" / "sd-cli"+ for p in (stale, fresh):+ p.parent.mkdir()+ p.write_text("binary")+ found = [str(stale), str(fresh)]++ monkeypatch.setattr(bk, "ensure_sd_cpp_binary", lambda **_kwargs: found.pop(0))+ monkeypatch.setattr(bk, "is_managed_binary", lambda _b: True)+ monkeypatch.setattr(+ bk,+ "_sd_cpp_probe_output",+ lambda binary, *_args: _H3_HELP if binary == str(fresh) else _PRE_H3_HELP,+ )++ assert bk.ensure_h3_sd_cpp_binary() == str(fresh)+ # A copy we own is dropped, which is what lets the installer put the pinned prebuilt back.+ assert not stale.exists()+++def test_h3_binary_gate_refuses_but_keeps_a_user_supplied_build(monkeypatch, tmp_path):+ # Same ownership split as _usable_or_discard_managed: the user's own build is not ours to+ # delete (install() then refuses the still non-empty unmarked directory, leaving no binary at+ # all), so the load fails with a message naming the binary instead.+ own = tmp_path / "sd-cli"+ own.write_text("binary")+ monkeypatch.setattr(bk, "ensure_sd_cpp_binary", lambda **_kwargs: str(own))+ monkeypatch.setattr(bk, "is_managed_binary", lambda _b: False)+ monkeypatch.setattr(bk, "_sd_cpp_probe_output", lambda *_args: _PRE_H3_HELP)++ with pytest.raises(RuntimeError, match = "predates MiniMax-H3"):+ bk.ensure_h3_sd_cpp_binary()+ assert own.exists()+++def test_h3_binary_gate_keeps_a_binary_it_cannot_probe(monkeypatch):+ # An unreadable --help is "cannot tell", not "no H3": the load's own version() gate already+ # refuses a binary that will not run, and guessing here would strand a working build.+ monkeypatch.setattr(bk, "ensure_sd_cpp_binary", lambda **_kwargs: "/usr/bin/sd-cli")+ monkeypatch.setattr(bk, "_sd_cpp_probe_output", lambda *_args: None)+ assert bk.ensure_h3_sd_cpp_binary() == "/usr/bin/sd-cli"+++def test_lists_accelerator_device_reads_the_ggml_device_list(monkeypatch):+ # --list-devices is the only way to tell a reused CPU prebuilt from an accelerator build after+ # the fact: the finder returns whichever binary is installed, whatever accelerator was asked for.+ monkeypatch.setattr(bk, "_sd_cpp_probe_output", lambda *_a: "CPU\tIntel(R) Xeon(R) Platinum\n")+ assert bk.sd_cpp_lists_accelerator_device("/existing/sd-cli") is False++ monkeypatch.setattr(+ bk,+ "_sd_cpp_probe_output",+ lambda *_a: "CUDA0\tNVIDIA GeForce RTX 4090\nCPU\tIntel(R) Xeon(R) Platinum\n",+ )+ assert bk.sd_cpp_lists_accelerator_device("/existing/sd-cli") is True++ # An older build rejects the flag with a non-zero exit: "cannot tell", not "no accelerator".+ monkeypatch.setattr(bk, "_sd_cpp_probe_output", lambda *_a: None)+ assert bk.sd_cpp_lists_accelerator_device("/existing/sd-cli") is True+ assert bk.sd_cpp_lists_accelerator_device(None) is False++def test_unload_clears_state_and_signals_cancel():cancel = threading.Event()b = _loaded_backend()diff --git a/studio/backend/tests/test_sd_cpp_engine.py b/studio/backend/tests/test_sd_cpp_engine.pyindex 5501eec826e..4f7d338321d 100644--- a/studio/backend/tests/test_sd_cpp_engine.py+++ b/studio/backend/tests/test_sd_cpp_engine.py@@ -526,3 +526,125 @@ def test_native_generation_timeout_matches_the_ui_settle_window():), fn.__name__# The resident-server path shares the same ceiling, applied per request (see test_server_generate_splits_batches_above_server_limit).assert sd_cpp_backend.NATIVE_GENERATION_TIMEOUT_S == NATIVE_GENERATION_TIMEOUT_S+++# ── in-place progress redraws ───────────────────────────────────────────────+# sd-cli redraws its sampling bar with a LEADING carriage return and closes each redraw with an+# erase-to-end-of-line, emitting a newline only on the final step:+# printf("\r%s %i/%i - %s\033[K%s", bar, step, steps, speed, step == steps ? "\n" : "")+# so a reader that keys only on newlines reports nothing until sampling is already over.++_REDRAW = "\r |=========> | {}/{} - 21.50s/it\x1b[K"+++def test_split_progress_records_treats_erase_as_a_terminator():+ """The redraw is complete the moment sd-cli flushes it, even though its own newline never+ comes and the NEXT redraw's carriage return has not arrived yet."""+ records, rest = eng.split_progress_records(_REDRAW.format(7, 30))+ assert records == ["", " |=========> | 7/30 - 21.50s/it\x1b[K"]+ assert rest == ""+++def test_split_progress_records_keeps_unterminated_remainder():+ records, rest = eng.split_progress_records("done\nhalf a li")+ assert records == ["done"]+ assert rest == "half a li"+++def test_split_progress_records_counts_crlf_as_one_terminator():+ records, rest = eng.split_progress_records("a\r\nb\r\n")+ assert records == ["a", "b"]+ assert rest == ""+++def test_strip_ansi_removes_the_erase_sequence():+ assert eng.strip_ansi(" |==> | 7/30 - 21.50s/it\x1b[K") == " |==> | 7/30 - 21.50s/it"+++class _ChunkStream:+ """A text stream over a pipe: ``.buffer.read1`` returns whatever the child has flushed,+ exactly like a real subprocess pipe, and iteration would block until a newline. Counts reads+ so a test can prove WHEN a record was delivered, not merely that it arrived eventually."""++ class _Raw:+ def __init__(self, chunks, owner):+ self._chunks = list(chunks)+ self._owner = owner++ def read1(self, _n):+ if not self._chunks:+ return b""+ self._owner.reads += 1+ return self._chunks.pop(0)++ def __init__(self, chunks):+ self.reads = 0+ self.buffer = self._Raw(chunks, self)++ def __iter__(self):+ raise AssertionError("iteration would block on a redraw that carries no newline")+++def test_iter_records_delivers_every_redraw():+ chunks = [_REDRAW.format(i, 3).encode() for i in (1, 2)]+ chunks.append((_REDRAW.format(3, 3) + "\n").encode())+ got = [r for r in eng.iter_sd_cpp_records(_ChunkStream(chunks)) if r.strip()]+ assert got == [+ " |=========> | 1/3 - 21.50s/it",+ " |=========> | 2/3 - 21.50s/it",+ " |=========> | 3/3 - 21.50s/it",+ ]+++def test_iter_records_delivers_a_redraw_as_soon_as_it_is_flushed():+ """The actual regression: progress was not merely late-ish, it was one redraw behind, so a+ 30-step job showed 0/30 until step 2 and never showed the last step before completion.++ Delivering after ONE read is the whole claim. A redraw carries no newline, and its carriage+ return sits at the front of the NEXT redraw, so a reader terminating only on CR/LF cannot+ produce step 1 until step 2 has been flushed -- which is a second read.+ """+ stream = _ChunkStream([_REDRAW.format(i, 3).encode() for i in (1, 2, 3)])+ records = eng.iter_sd_cpp_records(stream)+ first = next(r for r in records if r.strip())+ assert first == " |=========> | 1/3 - 21.50s/it"+ assert stream.reads == 1+++def test_iter_records_decodes_utf8_split_across_reads():+ """A multi-byte character straddling two read1() boundaries must not become mojibake."""+ blob = "café\n".encode()+ stream = _ChunkStream([blob[:4], blob[4:]])+ assert list(eng.iter_sd_cpp_records(stream)) == ["café"]+++def test_iter_records_falls_back_to_line_iteration_without_a_raw_buffer():+ """Test doubles (and non-pipe streams) hand us a plain iterable with no ``.buffer``."""+ lines = ["loading\n", _REDRAW.format(4, 4) + "\n"]+ got = [r for r in eng.iter_sd_cpp_records(iter(lines)) if r.strip()]+ assert got == ["loading", " |=========> | 4/4 - 21.50s/it"]+++def test_run_forwards_clean_redraws_to_on_log(tmp_path, monkeypatch):+ """End of the engine's own chain: a redraw reaches on_log, with no escape left in it."""+ e = _engine(tmp_path)+ out = tmp_path / "img.png"+ _patch_popen(+ monkeypatch,+ lines = [_REDRAW.format(1, 2), _REDRAW.format(2, 2) + "\n"],+ returncode = 0,+ out_file = str(out),+ )+ seen: list[str] = []+ e.generate(+ SdCppModelFiles(diffusion_model = "/m/z.gguf"),+ SdCppGenParams(prompt = "p"),+ output_path = str(out),+ on_log = seen.append,+ )+ bars = [s for s in seen if "|" in s]+ assert bars == [+ " |=========> | 1/2 - 21.50s/it",+ " |=========> | 2/2 - 21.50s/it",+ ]+ assert not any("\x1b" in s for s in seen)diff --git a/studio/backend/tests/test_sd_cpp_install.py b/studio/backend/tests/test_sd_cpp_install.pyindex 2eea8b95063..fe2af041ef0 100644--- a/studio/backend/tests/test_sd_cpp_install.py+++ b/studio/backend/tests/test_sd_cpp_install.py@@ -616,6 +616,77 @@ def test_install_falls_back_to_upstream_when_mirror_missing(tmp_path, monkeypatcassert "source leejet/stable-diffusion.cpp" in captured.out+def test_the_shipped_pin_is_mirror_only(tmp_path, monkeypatch):+ """The default pin carries the H3 patch set, which only the mirror can build.++ If this ever goes back to a plain upstream tag (because upstream released the fixes and+ patches/ was emptied), the two tests below stop describing the shipped default, so fail here+ loudly rather than letting them quietly assert nothing."""+ assert sdmod.is_mirror_only_tag(DEFAULT_TAG)+ assert not sdmod.is_mirror_only_tag("master-813-bfbef5b")+ assert not sdmod.is_mirror_only_tag("")+ assert not sdmod.is_mirror_only_tag(None)+++def test_a_mirror_only_pin_is_never_requested_upstream(tmp_path, monkeypatch):+ """Upstream cannot have a -u<id> tag by construction, so asking for it is a guaranteed 404.++ The mirror-only pin is instead TRANSLATED back to the upstream release it was built from, so+ a host the mirror does not build keeps a pinned install rather than silently degrading to+ upstream latest. Asking upstream for the literal -u<id> string is still wrong, and that is+ what this pins.++ The mirror must NOT serve here: when it does, the very first attempt succeeds and the upstream+ attempts are never reached, so the assertion would hold no matter what the ordering says."""+ zb = _zip_with_sd_cli()+ _stub_two_repos(+ monkeypatch,+ mirror_serves = False,+ upstream_serves = True,+ zip_bytes = zb,+ digest = "sha256:" + hashlib.sha256(zb).hexdigest(),+ )+ asked = []+ real = sdmod._fetch_release+ monkeypatch.setattr(+ sdmod,+ "_fetch_release",+ lambda tag = None, **kw: (asked.append((kw.get("repo"), tag)), real(tag, **kw))[1],+ )+ install(install_dir = tmp_path)+ # Never the literal -u<id> string, which upstream cannot have.+ assert (sdmod.UPSTREAM_FALLBACK_REPO, DEFAULT_TAG) not in asked+ # It asks upstream for the release the mirror built on top of instead, so the pin survives+ # translation rather than being dropped.+ upstream_pin = sdmod.upstream_tag_for(DEFAULT_TAG)+ assert upstream_pin != DEFAULT_TAG+ assert (sdmod.UPSTREAM_FALLBACK_REPO, upstream_pin) in asked+ # And because that pinned attempt succeeds, it never has to settle for upstream latest --+ # which is the whole point of translating rather than skipping.+ assert (sdmod.UPSTREAM_FALLBACK_REPO, None) not in asked+++def test_falling_back_off_a_mirror_only_pin_warns_about_h3(tmp_path, monkeypatch, capsys):+ """The generic fallback line is not enough here.++ Every other model still works on an unpatched upstream build, so falling back beats having no+ native engine at all. H3 does not: it aborts on the default cfg-scale and on --vae-on-cpu, and+ a blanket --type silently renders a broken video rather than failing. A user who sees only+ "falling back to leejet" has no way to connect that to the H3 output they get."""+ zb = _zip_with_sd_cli()+ _stub_two_repos(+ monkeypatch,+ mirror_serves = False,+ upstream_serves = True,+ zip_bytes = zb,+ digest = "sha256:" + hashlib.sha256(zb).hexdigest(),+ )+ install(install_dir = tmp_path)+ err = capsys.readouterr().err+ assert "falling back to leejet/stable-diffusion.cpp" in err+ assert "lacks the MiniMax-H3 fixes" in err++def test_install_errors_when_neither_source_serves(tmp_path, monkeypatch):_stub_two_repos(monkeypatch, mirror_serves = False, upstream_serves = False, zip_bytes = b"", digest = ""diff --git a/studio/backend/tests/test_video_backend.py b/studio/backend/tests/test_video_backend.pyindex 488bb17e204..5fa35770d15 100644--- a/studio/backend/tests/test_video_backend.py+++ b/studio/backend/tests/test_video_backend.py@@ -6,12 +6,14 @@ Mirrors test_diffusion_backend's fake_runtime pattern: explicit fake signaturesthe signature-gated kwargs actually exercise, sys.modules stubs so no real MLstack loads."""+import builtinsimport contextlibimport sysimport threadingimport timeimport typesfrom dataclasses import replace+from pathlib import Pathimport pytest@@ -368,6 +370,102 @@ class _FakeHV15Pipeline:return _FakeHV15Pipeline.instance+# MiniMax-H3 BF16 fakes: the Modular Diffusers workflow. ModularPipeline takes no step callback+# (an unknown input is only warned about) and its denoise loop drives components.scheduler.step,+# i.e. pipe.scheduler, once per step -- exactly what the HV15 wrapper hooks.+++class _FakeH3Scheduler:+ def __init__(self) -> None:+ self.calls = 0+ # Fired from the ORIGINAL step, so a test can cancel mid-denoise as a user request would.+ self.on_step = None++ def step(self, *args, **kwargs):+ self.calls += 1+ if self.on_step is not None:+ self.on_step(self.calls)+ return object()+++class _FakeComponentsManager:+ def __init__(self) -> None:+ self.offload = None++ def enable_auto_cpu_offload(self, **kwargs):+ self.offload = kwargs+++class _FakeModularPipe:+ def __init__(self) -> None:+ self.scheduler = _FakeH3Scheduler()+ self.load_kwargs = None+ self.last_kwargs = None++ def load_components(self, **kwargs):+ self.load_kwargs = kwargs++ def __call__(+ self,+ *,+ prompt = None,+ num_inference_steps = None,+ width = None,+ height = None,+ num_frames = None,+ generator = None,+ output = None,+ **kwargs,+ ):+ self.last_kwargs = {+ "prompt": prompt,+ "num_inference_steps": num_inference_steps,+ "width": width,+ "height": height,+ "num_frames": num_frames,+ "output": output,+ **kwargs,+ }+ for _ in range(int(num_inference_steps or 1)):+ self.scheduler.step(object(), 0, object())+ return {"videos": [[object() for _ in range(int(num_frames or 1))]], "audio": None}+++class _FakeModularPipeline:+ last: dict = {}+ instance = None++ @classmethod+ def from_pretrained(cls, path, **kwargs):+ _FakeModularPipeline.last = {"path": path, **kwargs}+ _FakeModularPipeline.instance = _FakeModularPipe()+ return _FakeModularPipeline.instance+++def _load_h3_modular(backend, *, hf_token = None):+ """Commit the H3 BF16 state exactly as load_pipeline's Modular Diffusers branch does."""+ diffusers = sys.modules["diffusers"]+ diffusers.ComponentsManager = _FakeComponentsManager+ diffusers.ModularPipeline = _FakeModularPipeline+ fam = _detect_load_family("MiniMaxAI/MiniMax-H3", None, "minimax-h3")+ assert fam is not None+ backend._load_h3_modular_pipeline(+ diffusers = diffusers,+ torch = sys.modules["torch"],+ fam = fam,+ repo_id = "MiniMaxAI/MiniMax-H3",+ base = fam.base_repo,+ kind = "pipeline",+ dtype = sys.modules["torch"].bfloat16,+ device = "cpu",+ hf_token = hf_token,+ memory_mode = None,+ _load_token = None,+ _base_local_dir = None,+ )+ return _FakeModularPipeline.instance++@pytest.fixturedef fake_runtime(monkeypatch):torch = types.ModuleType("torch")@@ -2007,239 +2105,976 @@ def _plan_api(monkeypatch, repos):monkeypatch.setattr("huggingface_hub.HfApi", lambda *a, **k: _Api())-def test_download_plan_narrows_an_ltx23_pick_and_stages_its_extras(monkeypatch):- # A 2.3 checkpoint brings its own VAEs, vocoder and connectors, so staging the 2.0 base copies downloads gigabytes the- # pipeline never opens -- and the companions it DOES read were missing from the plan, so they were pulled inline.+def test_h3_native_download_plan_stages_the_complete_runtime(monkeypatch):+ # The mirror carries the Qwen3-VL encoder quants alongside the denoisers, so one repo covers+ # both halves of the runtime; the VAEs still come from the component repo._plan_api(monkeypatch,{- "unsloth/LTX-2.3-GGUF": _LTX23_REPO_SIBLINGS,- "Lightricks/LTX-2": _LTX_BASE_SIBLINGS,+ "unsloth/MiniMax-H3-GGUF": [+ _PlanSibling("minimax_h3_fl2va-Q4_K_M.gguf", 19),+ _PlanSibling("qwen3vl_32b_minimax_h3-Q4_K_M.gguf", 18),+ ],+ "Comfy-Org/MiniMax-H3": [+ _PlanSibling("vae/minimax_h3_video_vae_fp16.safetensors", 5),+ _PlanSibling("vae/minimax_h3_audio_vae_fp32.safetensors", 1),+ ],},)plan = VideoBackend().download_plan(- "unsloth/LTX-2.3-GGUF",- gguf_filename = "ltx-2.3-22b-distilled.gguf",- family_override = "ltx-2",- )-- by_repo = {e["repo_id"]: e for e in plan["entries"]}- # Checkpoint and extras share one repo, so they must be ONE entry: two jobs for the same repo would collide on the scoped job key.- assert set(by_repo) == {"unsloth/LTX-2.3-GGUF", "Lightricks/LTX-2"}- ckpt = by_repo["unsloth/LTX-2.3-GGUF"]- assert ckpt["gguf_filename"] == "ltx-2.3-22b-distilled.gguf"- assert "vae/ltx-2.3-22b-distilled_video_vae.safetensors" in ckpt["files"]- assert "vae/ltx-2.3-22b-distilled_audio_vae.safetensors" in ckpt["files"]- assert "text_encoders/ltx-2.3-22b-distilled_embeddings_connectors.safetensors" in ckpt["files"]- # The other variant's companions are not this checkpoint's.- assert "vae/ltx-2.3-22b-dev_video_vae.safetensors" not in ckpt["files"]-- base = by_repo["Lightricks/LTX-2"]- assert "scheduler/scheduler_config.json" in base["files"]- assert any(f.startswith("text_encoder/") for f in base["files"])- for dropped in ("vae/", "vocoder/", "connectors/", "transformer/"):- assert not any(f.startswith(dropped) for f in base["files"]), dropped- assert plan["total_bytes"] == ckpt["bytes"] + base["bytes"]---def _cuda_bf16_target(monkeypatch):- """Pretend the box can run layerwise fp8, so the pre-cast encoder resolves off-GPU."""- import torch- monkeypatch.setattr(- "core.inference.video.resolve_diffusion_device_target",- lambda: types.SimpleNamespace(device = "cuda", dtype = torch.bfloat16),+ "unsloth/MiniMax-H3-GGUF",+ gguf_filename = "minimax_h3_fl2va-Q4_K_M.gguf",+ family_override = "minimax-h3",+ model_kind = "gguf",)+ by_repo = {entry["repo_id"]: entry for entry in plan["entries"]}+ assert by_repo["unsloth/MiniMax-H3-GGUF"]["files"] == [+ "minimax_h3_fl2va-Q4_K_M.gguf",+ "qwen3vl_32b_minimax_h3-Q4_K_M.gguf",+ ]+ assert by_repo["Comfy-Org/MiniMax-H3"]["files"] == [+ "vae/minimax_h3_video_vae_fp16.safetensors",+ "vae/minimax_h3_audio_vae_fp32.safetensors",+ ]+ assert plan["total_bytes"] == 43-_LTX2_FP8_SIBLINGS = [_PlanSibling("LTX-2-text_encoder-FP8.pt", 13_000_000_000)]+_H3_BASE_SIBLINGS = [+ _PlanSibling("transformer/config.json", 1),+ _PlanSibling("transformer/diffusion_pytorch_model-00001-of-00002.safetensors", 40),+ _PlanSibling("transformer/diffusion_pytorch_model-00002-of-00002.safetensors", 26),+ _PlanSibling("scheduler/scheduler_config.json", 1),+ _PlanSibling("vae/diffusion_pytorch_model.safetensors", 11),+]-def test_base_download_files_skips_precast_text_encoder_weights():- # The pre-cast checkpoint supplies the encoder WEIGHTS only: the config and shard index stay, since the loader meta-inits from them.- siblings = _LTX2_SIBLINGS + [- _sibling("text_encoder/config.json", 1),- _sibling("text_encoder/model.safetensors.index.json", 1),- ]- info = types.SimpleNamespace(siblings = siblings)- names = [- n- for n, _ in VideoBackend._base_download_files(- info, "gguf", skip_te_components = ("text_encoder",)- )- ]- assert not any(n.endswith(".safetensors") and n.startswith("text_encoder/") for n in names)- assert "text_encoder/config.json" in names- assert "text_encoder/model.safetensors.index.json" in names- # A different component's weights are untouched.- assert "vae/diffusion_pytorch_model.safetensors" in names+_H3_PREQUANT_SIBLINGS = [+ _PlanSibling("MiniMax-H3-INT8.pt", 20),+ _PlanSibling("MiniMax-H3-FP8.pt", 20),+]-def test_download_plan_swaps_the_dense_encoder_for_the_precast_checkpoint(monkeypatch):- # An fp8 encoder request loads unsloth/LTX-2-FP8, so staging the dense Gemma3 downloads ~49 GB the pipeline never opens, and the checkpoint it DOES read was missing from the plan.+def test_download_plan_stages_the_prequant_denoiser_it_drops_the_dense_shards_for(monkeypatch):+ # The dense DiT shards leave the base entry as soon as a hosted pre-quantized checkpoint+ # covers them, so the checkpoint has to arrive in their place. Without it the plan skipped+ # 66 GB and added nothing: the byte total under-reported the stage by the size of the+ # artifact, the disk preflight cleared a volume that could not hold it, and an offline stage+ # finished without the one file the load opens._cuda_bf16_target(monkeypatch)_plan_api(monkeypatch,{- "unsloth/LTX-2.3-GGUF": _LTX23_REPO_SIBLINGS,- "Lightricks/LTX-2": _LTX_BASE_SIBLINGS,- "unsloth/LTX-2-FP8": _LTX2_FP8_SIBLINGS,+ "MiniMaxAI/MiniMax-H3": _H3_BASE_SIBLINGS,+ "unsloth/MiniMax-H3-FP8": _H3_PREQUANT_SIBLINGS,},)plan = VideoBackend().download_plan(- "unsloth/LTX-2.3-GGUF",- gguf_filename = "ltx-2.3-22b-distilled.gguf",- family_override = "ltx-2",- text_encoder_quant = "fp8",+ "MiniMaxAI/MiniMax-H3",+ family_override = "minimax-h3",+ model_kind = "pipeline",+ transformer_quant = "int8",)- by_repo = {e["repo_id"]: e for e in plan["entries"]}- assert by_repo["unsloth/LTX-2-FP8"]["files"] == ["LTX-2-text_encoder-FP8.pt"]- base = by_repo["Lightricks/LTX-2"]- assert not any(f.startswith("text_encoder/") for f in base["files"])- # The rest of the scoped base list is unchanged.- assert "scheduler/scheduler_config.json" in base["files"]- assert "tokenizer/tokenizer.json" in base["files"]+ by_repo = {entry["repo_id"]: entry for entry in plan["entries"]}+ # int8 and fp8 share one repo, so the SCHEME picks the file, not the repo.+ assert by_repo["unsloth/MiniMax-H3-FP8"]["files"] == ["MiniMax-H3-INT8.pt"]+ base = by_repo["MiniMaxAI/MiniMax-H3"]+ assert not any(f.startswith("transformer/diffusion_pytorch_model") for f in base["files"])+ # The config still goes, exactly as on the pre-cast encoder path: the class is read from it.+ assert "transformer/config.json" in base["files"]assert plan["total_bytes"] == sum(e["bytes"] for e in plan["entries"])-def test_download_plan_keeps_the_dense_encoder_without_an_fp8_request(monkeypatch):- # No fp8 request means the dense encoder IS the encoder: dropping it would break the load.+def test_download_plan_keeps_the_dense_denoiser_when_the_prequant_repo_is_missing(monkeypatch):+ # An unpublished / gated / renamed checkpoint must neither strand the load without a denoiser+ # nor sink the whole plan: the dense shards stay and no phantom entry is invented._cuda_bf16_target(monkeypatch)- _plan_api(- monkeypatch,- {- "unsloth/LTX-2.3-GGUF": _LTX23_REPO_SIBLINGS,- "Lightricks/LTX-2": _LTX_BASE_SIBLINGS,- },- )++ class _Api:+ def model_info(+ self,+ repo_id,+ files_metadata = False,+ token = None,+ ):+ if repo_id == "unsloth/MiniMax-H3-FP8":+ raise RuntimeError("404 gated")+ return _PlanInfo(_H3_BASE_SIBLINGS)++ monkeypatch.setattr("huggingface_hub.HfApi", lambda *a, **k: _Api())plan = VideoBackend().download_plan(- "unsloth/LTX-2.3-GGUF",- gguf_filename = "ltx-2.3-22b-distilled.gguf",- family_override = "ltx-2",+ "MiniMaxAI/MiniMax-H3",+ family_override = "minimax-h3",+ model_kind = "pipeline",+ transformer_quant = "int8",)- by_repo = {e["repo_id"]: e for e in plan["entries"]}- assert "unsloth/LTX-2-FP8" not in by_repo- assert any(f.startswith("text_encoder/") for f in by_repo["Lightricks/LTX-2"]["files"])+ by_repo = {entry["repo_id"]: entry for entry in plan["entries"]}+ assert "unsloth/MiniMax-H3-FP8" not in by_repo+ assert plan["total_bytes"] == sum(e["bytes"] for e in plan["entries"])-def test_download_plan_keeps_the_dense_encoder_when_the_precast_repo_is_missing(monkeypatch):- # The hosted artifact can be unpublished, gated or renamed. That must neither drop the dense encoder nor sink the whole plan, which is what an unguarded lookup did.+def test_download_plan_adds_no_prequant_entry_without_a_scheme(monkeypatch):+ # bf16 keeps the dense shards, so there is nothing to replace and no third repo to stage._cuda_bf16_target(monkeypatch)_plan_api(monkeypatch,{- "unsloth/LTX-2.3-GGUF": _LTX23_REPO_SIBLINGS,- "Lightricks/LTX-2": _LTX_BASE_SIBLINGS,+ "MiniMaxAI/MiniMax-H3": _H3_BASE_SIBLINGS,+ "unsloth/MiniMax-H3-FP8": _H3_PREQUANT_SIBLINGS,},)plan = VideoBackend().download_plan(- "unsloth/LTX-2.3-GGUF",- gguf_filename = "ltx-2.3-22b-distilled.gguf",- family_override = "ltx-2",- text_encoder_quant = "fp8",+ "MiniMaxAI/MiniMax-H3",+ family_override = "minimax-h3",+ model_kind = "pipeline",)- by_repo = {e["repo_id"]: e for e in plan["entries"]}- assert set(by_repo) == {"unsloth/LTX-2.3-GGUF", "Lightricks/LTX-2"}- assert any(f.startswith("text_encoder/") for f in by_repo["Lightricks/LTX-2"]["files"])- assert plan["total_bytes"] == sum(e["bytes"] for e in plan["entries"]) > 0+ by_repo = {entry["repo_id"]: entry for entry in plan["entries"]}+ assert "unsloth/MiniMax-H3-FP8" not in by_repo+ assert any(+ f.startswith("transformer/diffusion_pytorch_model")+ for f in by_repo["MiniMaxAI/MiniMax-H3"]["files"]+ )-def test_fetch_te_prequant_only_reports_what_it_downloaded(monkeypatch):- # The dense skip is earned by the pre-cast file being on disk; an unreachable checkpoint must report nothing.+def test_a_quantized_reference_load_is_refused_rather_than_run_on_the_wrong_partition():+ # The hosted checkpoints are FL2VA denoisers. Ref2VA shares their module shapes and base+ # model, so one installs cleanly, passes every metadata check, and makes load_components skip+ # the real Ref2VA transformer: the request generates from the keyframe partition instead of+ # failing. There is no in-place quantise seam to fall back on, so this has to be a refusal.backend = VideoBackend()- source = types.SimpleNamespace(- kind = "repo", location = "unsloth/LTX-2-FP8", filename = "LTX-2-text_encoder-FP8.pt"- )-- def _boom(- repo,- filename,- token,- cancel_event = None,- ):- raise OSError("404")+ with pytest.raises(ValueError, match = "reference video"):+ backend.validate_load_request(+ "MiniMaxAI/MiniMax-H3",+ family_override = "minimax-h3",+ model_kind = "pipeline",+ transformer_quant = "int8",+ h3_task = "ref2va",+ )- monkeypatch.setattr("utils.hf_xet_fallback.hf_hub_download_with_xet_fallback", _boom)- assert backend._fetch_te_prequant({"text_encoder": source}, None) == ()+def test_direct_h3_native_load_uses_sd_cpp_path(monkeypatch):+ backend = VideoBackend()+ calls = []+ monkeypatch.setattr("core.inference.video._ensure_mp4_encoder_available", lambda: None)monkeypatch.setattr(- "utils.hf_xet_fallback.hf_hub_download_with_xet_fallback",- lambda repo, filename, token, cancel_event = None: "/tmp/precast.pt",+ backend,+ "_run_load_h3_native",+ lambda **kwargs: calls.append(kwargs),)- assert backend._fetch_te_prequant({"text_encoder": source}, None) == ("text_encoder",)- # A local path override is the injection's business (allowlist), and nothing is fetched for it.- local = types.SimpleNamespace(kind = "path", location = "/tmp/x.pt", filename = None)- assert backend._fetch_te_prequant({"text_encoder": local}, None) == ()--def test_load_pipeline_tops_up_the_dense_encoder_when_injection_fails(fake_runtime, tmp_path):- # Injection is best-effort, but the pre-download already dropped the dense shards, so a failed injection must restore them rather than crash the load.- backend = VideoBackend()- calls: list[dict] = []- backend._predownload_base = lambda *a, **k: ( # type: ignore[method-assign]- calls.append({"args": a, "kwargs": k}) or str(tmp_path)- )- backend.load_pipeline(- "Lightricks/LTX-2",- model_kind = "pipeline",- _base_local_dir = str(tmp_path),- _te_prequant_skipped = ("text_encoder",),+ result = backend.load_pipeline(+ "leejet/MiniMax-H3-GGUF",+ gguf_filename = "minimax_h3_fl2va-Q4_K_M.gguf",+ family_override = "minimax-h3",+ model_kind = "gguf",)- assert len(calls) == 1 and calls[0]["kwargs"]["ltx23"] is False- backend.unload()- # Nothing was skipped -> no second pull.- calls.clear()- backend.load_pipeline("Lightricks/LTX-2", model_kind = "pipeline", _base_local_dir = str(tmp_path))- assert calls == []- backend.unload()+ assert result["loaded"] is False+ assert len(calls) == 1+ assert calls[0]["fam"].name == "minimax-h3"+ assert calls[0]["gguf_filename"] == "minimax_h3_fl2va-Q4_K_M.gguf"-def test_download_plan_keeps_the_wide_base_for_a_plain_ltx2_pick(monkeypatch):- # Only 2.3 checkpoints supply their own companions; a 2.0 pick still needs the base's.- _plan_api(- monkeypatch,- {- "someone/LTX-2-GGUF": [_PlanSibling("ltx-2-dev.gguf", 12_000_000_000)],- "Lightricks/LTX-2": _LTX_BASE_SIBLINGS,- },- )+def test_h3_native_load_honors_install_switch_and_maps_xpu_to_vulkan(monkeypatch, tmp_path):+ from core.inference import video as video_mod+ from core.inference import sd_cpp_backend, sd_cpp_engine- plan = VideoBackend().download_plan(- "someone/LTX-2-GGUF", gguf_filename = "ltx-2-dev.gguf", family_override = "ltx-2"+ class _Api:+ def __init__(self, **_kwargs):+ pass++ def model_info(self, *_args, **_kwargs):+ return _PlanInfo([])++ monkeypatch.setattr("huggingface_hub.HfApi", _Api)+ monkeypatch.setattr(+ video_mod,+ "resolve_diffusion_device_target",+ lambda: types.SimpleNamespace(backend = "xpu", device = "xpu", dtype = None),)+ monkeypatch.setattr(sd_cpp_backend, "_install_allowed", lambda: False)- base = next(e for e in plan["entries"] if e["repo_id"] == "Lightricks/LTX-2")- assert any(f.startswith("vae/") for f in base["files"])- assert any(f.startswith("connectors/") for f in base["files"])- # The GGUF still replaces the DiT, so the transformer shards stay out.- assert not any(f.startswith("transformer/") for f in base["files"])+ install_calls = []+ def _ensure(*, allow_install, accelerator):+ install_calls.append((allow_install, accelerator))+ return "/existing/sd-cli" if accelerator == "cpu" else None-def test_each_video_load_gets_its_own_cancel_event(monkeypatch):- """A cancelled load must STAY cancelled once the next one starts.+ monkeypatch.setattr(sd_cpp_backend, "ensure_sd_cpp_binary", _ensure)- unload() sets the event the running worker holds and drops _loading, so the next begin_load- could arrive before that worker had exited. Clearing a shared event there un-cancelled the old- worker, and its multi-gigabyte checkpoint pull resumed alongside the replacement load until the- token check at the very end.- """- import threading- from types import SimpleNamespace+ class _Engine:+ def __init__(self, binary):+ self.binary = binary- from core.inference.video import VideoBackend+ def version(self):+ # Only "not None" matters here: the load path treats that as "the engine started".+ # Deliberately not a real tag, so nobody reads this as a second pin competing with+ # install_sd_cpp_prebuilt.DEFAULT_TAG, which is what the previous literal looked like+ # once that pin moved on without it.+ return "stub-version"- backend = VideoBackend.__new__(VideoBackend)- backend._lock = threading.RLock()- backend._generate_lock = threading.RLock()- backend._cancel_event = threading.Event()- backend._load_token = 0+ monkeypatch.setattr(sd_cpp_engine, "SdCppEngine", _Engine)++ def _download(_repo, wanted, *_args, **_kwargs):+ path = tmp_path / Path(wanted).name+ path.write_bytes(b"x")+ return str(path)++ monkeypatch.setattr("utils.hf_xet_fallback.hf_hub_download_with_xet_fallback", _download)++ backend = VideoBackend()+ fam = _detect_load_family("leejet/MiniMax-H3-GGUF", None, "minimax-h3")+ assert fam is not None+ backend._run_load_h3_native(+ fam = fam,+ token = None,+ cancel_event = threading.Event(),+ repo_id = "leejet/MiniMax-H3-GGUF",+ gguf_filename = "minimax_h3_fl2va-Q4_K_M.gguf",+ )++ assert install_calls == [(False, "vulkan"), (False, "cpu")]+ assert backend._state is not None+ assert backend._state.device == "cpu"+++def test_h3_native_cpu_fallback_releases_the_video_gpu_claim(monkeypatch, tmp_path):+ """The accelerator binary is missing, so the runtime commits to the CPU build and holds no+ VRAM; /video/load's VIDEO claim (taken off the non-CPU device target) must not survive it,+ else the next chat/image acquire evicts a model that is not on the GPU."""+ from core.inference import gpu_arbiter+ from core.inference import video as video_mod+ from core.inference import sd_cpp_backend, sd_cpp_engine++ class _Api:+ def __init__(self, **_kwargs):+ pass++ def model_info(self, *_args, **_kwargs):+ return _PlanInfo([])++ monkeypatch.setattr("huggingface_hub.HfApi", _Api)+ monkeypatch.setattr(+ video_mod,+ "resolve_diffusion_device_target",+ lambda: types.SimpleNamespace(backend = "cuda", device = "cuda", dtype = None),+ )+ monkeypatch.setattr(sd_cpp_backend, "_install_allowed", lambda: True)+ monkeypatch.setattr(+ sd_cpp_backend,+ "ensure_sd_cpp_binary",+ lambda *, allow_install, accelerator: "/existing/sd-cli" if accelerator == "cpu" else None,+ )++ class _Engine:+ def __init__(self, binary):+ self.binary = binary++ def version(self):+ return "stub-version"++ monkeypatch.setattr(sd_cpp_engine, "SdCppEngine", _Engine)++ def _download(_repo, wanted, *_args, **_kwargs):+ path = tmp_path / Path(wanted).name+ path.write_bytes(b"x")+ return str(path)++ monkeypatch.setattr("utils.hf_xet_fallback.hf_hub_download_with_xet_fallback", _download)+ monkeypatch.setattr(gpu_arbiter, "_owner", gpu_arbiter.VIDEO)++ backend = VideoBackend()+ fam = _detect_load_family("leejet/MiniMax-H3-GGUF", None, "minimax-h3")+ assert fam is not None+ backend._run_load_h3_native(+ fam = fam,+ token = None,+ cancel_event = threading.Event(),+ repo_id = "leejet/MiniMax-H3-GGUF",+ gguf_filename = "minimax_h3_fl2va-Q4_K_M.gguf",+ )++ assert backend._state is not None+ assert backend._state.device == "cpu"+ assert gpu_arbiter.current_owner() is None+++def test_h3_native_accelerator_load_keeps_the_video_gpu_claim(monkeypatch, tmp_path):+ """The counterpart: when the accelerator binary IS there the runtime really uses the GPU,+ so the VIDEO claim has to stay."""+ from core.inference import gpu_arbiter+ from core.inference import video as video_mod+ from core.inference import sd_cpp_backend, sd_cpp_engine++ class _Api:+ def __init__(self, **_kwargs):+ pass++ def model_info(self, *_args, **_kwargs):+ return _PlanInfo([])++ monkeypatch.setattr("huggingface_hub.HfApi", _Api)+ monkeypatch.setattr(+ video_mod,+ "resolve_diffusion_device_target",+ lambda: types.SimpleNamespace(backend = "cuda", device = "cuda", dtype = None),+ )+ monkeypatch.setattr(sd_cpp_backend, "_install_allowed", lambda: True)+ monkeypatch.setattr(+ sd_cpp_backend,+ "ensure_sd_cpp_binary",+ lambda *, allow_install, accelerator: "/existing/sd-cli",+ )++ class _Engine:+ def __init__(self, binary):+ self.binary = binary++ def version(self):+ return "stub-version"++ monkeypatch.setattr(sd_cpp_engine, "SdCppEngine", _Engine)++ def _download(_repo, wanted, *_args, **_kwargs):+ path = tmp_path / Path(wanted).name+ path.write_bytes(b"x")+ return str(path)++ monkeypatch.setattr("utils.hf_xet_fallback.hf_hub_download_with_xet_fallback", _download)+ monkeypatch.setattr(gpu_arbiter, "_owner", gpu_arbiter.VIDEO)++ backend = VideoBackend()+ fam = _detect_load_family("leejet/MiniMax-H3-GGUF", None, "minimax-h3")+ assert fam is not None+ backend._run_load_h3_native(+ fam = fam,+ token = None,+ cancel_event = threading.Event(),+ repo_id = "leejet/MiniMax-H3-GGUF",+ gguf_filename = "minimax_h3_fl2va-Q4_K_M.gguf",+ )++ assert backend._state is not None+ assert backend._state.device == "cuda"+ assert gpu_arbiter.current_owner() == gpu_arbiter.VIDEO+++def test_h3_native_reused_cpu_binary_still_commits_to_cpu(monkeypatch, tmp_path):+ """The second load on a Linux CUDA host. The first one installed the CPU prebuilt (upstream+ publishes no Linux CUDA asset for the pinned tag), and from then on ensure_sd_cpp_binary finds+ that binary and returns it whatever accelerator it is asked for -- so the fallback below it was+ skipped, native_device stayed "cuda", and Studio kept the VIDEO claim and applied GPU offload+ policy while sd-cli ran wholly on the CPU. This is the common path, not an edge case."""+ from core.inference import gpu_arbiter+ from core.inference import video as video_mod+ from core.inference import sd_cpp_backend, sd_cpp_engine++ class _Api:+ def __init__(self, **_kwargs):+ pass++ def model_info(self, *_args, **_kwargs):+ return _PlanInfo([])++ monkeypatch.setattr("huggingface_hub.HfApi", _Api)+ monkeypatch.setattr(+ video_mod,+ "resolve_diffusion_device_target",+ lambda: types.SimpleNamespace(backend = "cuda", device = "cuda", dtype = None),+ )+ monkeypatch.setattr(sd_cpp_backend, "_install_allowed", lambda: True)+ # The reuse itself: the already-installed binary comes back for every accelerator.+ monkeypatch.setattr(+ sd_cpp_backend,+ "ensure_sd_cpp_binary",+ lambda *, allow_install, accelerator: "/existing/sd-cli",+ )++ def _probe(_binary, *args):+ if args == ("--list-devices",):+ # What the CPU prebuilt answers: the one ggml device it was built with.+ return "CPU\tIntel(R) Xeon(R) Platinum 8559C\n"+ return " --ref-video MiniMax-H3 Ref2VA reference video frame directory at 24 fps\n"++ monkeypatch.setattr(sd_cpp_backend, "_sd_cpp_probe_output", _probe)++ class _Engine:+ def __init__(self, binary):+ self.binary = binary++ def version(self):+ return "stub-version"++ monkeypatch.setattr(sd_cpp_engine, "SdCppEngine", _Engine)++ def _download(_repo, wanted, *_args, **_kwargs):+ path = tmp_path / Path(wanted).name+ path.write_bytes(b"x")+ return str(path)++ monkeypatch.setattr("utils.hf_xet_fallback.hf_hub_download_with_xet_fallback", _download)+ monkeypatch.setattr(gpu_arbiter, "_owner", gpu_arbiter.VIDEO)++ backend = VideoBackend()+ fam = _detect_load_family("leejet/MiniMax-H3-GGUF", None, "minimax-h3")+ assert fam is not None+ backend._run_load_h3_native(+ fam = fam,+ token = None,+ cancel_event = threading.Event(),+ repo_id = "leejet/MiniMax-H3-GGUF",+ gguf_filename = "minimax_h3_fl2va-Q4_K_M.gguf",+ )++ assert backend._state is not None+ assert backend._state.device == "cpu"+ assert backend._state.offload_policy == "none"+ # Reaching "cpu" is what lets the existing release_if drop the claim on this path too.+ assert gpu_arbiter.current_owner() is None+++def test_h3_native_load_publishes_the_companion_repos_while_downloading(monkeypatch, tmp_path):+ """The in-flight twin of loaded_repo_ids(). An H3 load downloads from the GGUF and component+ companion repos as well as repo_id, but loading_repo_ids() reported only repo_id and base_repo,+ so the cached-model delete guard allowed deleting Comfy-Org/MiniMax-H3 (and, when loading from+ another mirror as here, the GGUF companion) out from under the running download."""+ from core.inference import video as video_mod+ from core.inference import sd_cpp_backend, sd_cpp_engine+ from core.inference.video_minimax_h3 import H3_COMPONENT_REPO, H3_GGUF_REPO++ class _Api:+ def __init__(self, **_kwargs):+ pass++ def model_info(self, *_args, **_kwargs):+ return _PlanInfo([])++ monkeypatch.setattr("huggingface_hub.HfApi", _Api)+ monkeypatch.setattr(+ video_mod,+ "resolve_diffusion_device_target",+ lambda: types.SimpleNamespace(backend = "cpu", device = "cpu", dtype = None),+ )+ monkeypatch.setattr(sd_cpp_backend, "_install_allowed", lambda: True)+ monkeypatch.setattr(+ sd_cpp_backend,+ "ensure_sd_cpp_binary",+ lambda *, allow_install, accelerator: "/existing/sd-cli",+ )++ class _Engine:+ def __init__(self, binary):+ self.binary = binary++ def version(self):+ return "stub-version"++ monkeypatch.setattr(sd_cpp_engine, "SdCppEngine", _Engine)++ backend = VideoBackend()+ backend._load_token = 7+ backend._loading = video_mod._VideoLoadingState(repo_id = "leejet/MiniMax-H3-GGUF", base_repo = "")+ guarded: list[tuple[str, ...]] = []++ def _download(_repo, wanted, *_args, **_kwargs):+ # Sampled per file, so the guard has to be armed BEFORE any of the bytes land.+ guarded.append(tuple(backend.loading_repo_ids()))+ path = tmp_path / Path(wanted).name+ path.write_bytes(b"x")+ return str(path)++ monkeypatch.setattr("utils.hf_xet_fallback.hf_hub_download_with_xet_fallback", _download)++ fam = _detect_load_family("leejet/MiniMax-H3-GGUF", None, "minimax-h3")+ assert fam is not None+ backend._run_load_h3_native(+ fam = fam,+ token = 7,+ cancel_event = threading.Event(),+ repo_id = "leejet/MiniMax-H3-GGUF",+ gguf_filename = "minimax_h3_fl2va-Q4_K_M.gguf",+ )++ assert len(guarded) == 4+ for ids in guarded:+ assert "leejet/MiniMax-H3-GGUF" in ids+ assert fam.base_repo in ids+ assert H3_GGUF_REPO in ids+ assert H3_COMPONENT_REPO in ids+++def test_h3_native_load_refuses_a_binary_that_predates_h3(monkeypatch, tmp_path):+ """ensure_sd_cpp_binary probes runnability only, so an sd.cpp build older than H3 support is+ handed back and clears the version() gate: the load reported ready and the first generation+ failed, i.e. AFTER the multi-tens-of-GB bundle had downloaded. Gate on the capability."""+ from core.inference import video as video_mod+ from core.inference import sd_cpp_backend, sd_cpp_engine++ class _Api:+ def __init__(self, **_kwargs):+ pass++ def model_info(self, *_args, **_kwargs):+ return _PlanInfo([])++ monkeypatch.setattr("huggingface_hub.HfApi", _Api)+ monkeypatch.setattr(+ video_mod,+ "resolve_diffusion_device_target",+ lambda: types.SimpleNamespace(backend = "cpu", device = "cpu", dtype = None),+ )+ monkeypatch.setattr(sd_cpp_backend, "_install_allowed", lambda: True)+ monkeypatch.setattr(+ sd_cpp_backend,+ "ensure_sd_cpp_binary",+ lambda *, allow_install, accelerator: "/usr/local/bin/sd-cli",+ )+ # The user's own build: not ours to delete, so the load must fail rather than reinstall.+ monkeypatch.setattr(sd_cpp_backend, "is_managed_binary", lambda _b: False)+ # A pre-H3 --help. vid_gen and --audio-vae are both in it (they predate H3, they came with+ # LTX-2), which is why the H3-only options are what the gate looks for.+ monkeypatch.setattr(+ sd_cpp_backend,+ "_sd_cpp_probe_output",+ lambda *_args: (+ " -M, --mode run mode, one of [img_gen, vid_gen, upscale]\n"+ " --audio-vae <string> path to standalone LTX audio vae model\n"+ ),+ )++ class _Engine:+ def __init__(self, binary):+ self.binary = binary++ def version(self):+ # The old build runs perfectly well, which is exactly why this gate cannot catch it.+ return "stub-version"++ monkeypatch.setattr(sd_cpp_engine, "SdCppEngine", _Engine)++ def _download(_repo, wanted, *_args, **_kwargs):+ path = tmp_path / Path(wanted).name+ path.write_bytes(b"x")+ return str(path)++ monkeypatch.setattr("utils.hf_xet_fallback.hf_hub_download_with_xet_fallback", _download)++ backend = VideoBackend()+ fam = _detect_load_family("leejet/MiniMax-H3-GGUF", None, "minimax-h3")+ assert fam is not None+ with pytest.raises(RuntimeError, match = "predates MiniMax-H3"):+ backend._run_load_h3_native(+ fam = fam,+ token = None,+ cancel_event = threading.Event(),+ repo_id = "leejet/MiniMax-H3-GGUF",+ gguf_filename = "minimax_h3_fl2va-Q4_K_M.gguf",+ )++ assert backend._state is None+++def test_h3_native_generation_dispatch_does_not_import_torch(monkeypatch):+ from core.inference.video import _VideoLoadState++ backend = VideoBackend()+ fam = _detect_load_family("leejet/MiniMax-H3-GGUF", None, "minimax-h3")+ assert fam is not None+ backend._state = _VideoLoadState(+ pipe = object(),+ family = fam,+ repo_id = "leejet/MiniMax-H3-GGUF",+ base_repo = fam.base_repo,+ device = "cpu",+ dtype = "Q4_K_M",+ kind = "gguf",+ engine = "sd_cpp",+ gguf_filename = "minimax_h3_fl2va-Q4_K_M.gguf",+ )+ expected = {"mp4_bytes": b"native"}+ monkeypatch.setattr(backend, "_generate_h3_native", lambda **_kwargs: expected)++ original_import = builtins.__import__++ def _no_torch_import(name, *args, **kwargs):+ if name == "torch" or name.startswith("torch."):+ raise AssertionError("native generation imported torch")+ return original_import(name, *args, **kwargs)++ monkeypatch.setattr(builtins, "__import__", _no_torch_import)+ assert backend.generate(prompt = "a fox") is expected+++def test_h3_native_loaded_repo_ids_cover_the_companion_repos():+ # The delete guard reads repo_id + base_repo, but the native runtime keeps paths into the GGUF+ # mirror (Qwen encoder) and the component repo (both VAEs) and re-reads them every generation,+ # so deleting either On Device while H3 is loaded must be refused.+ from core.inference.video import _VideoLoadState+ from core.inference.video_minimax_h3 import H3_COMPONENT_REPO, H3_GGUF_REPO++ backend = VideoBackend()+ assert backend.loaded_repo_ids() == ()+ fam = _detect_load_family("leejet/MiniMax-H3-GGUF", None, "minimax-h3")+ assert fam is not None+ backend._state = _VideoLoadState(+ pipe = object(),+ family = fam,+ repo_id = "leejet/MiniMax-H3-GGUF",+ base_repo = fam.base_repo,+ device = "cpu",+ dtype = "Q4_K_M",+ kind = "gguf",+ engine = "sd_cpp",+ gguf_filename = "minimax_h3_fl2va-Q4_K_M.gguf",+ )+ assert backend.loaded_repo_ids() == (+ "leejet/MiniMax-H3-GGUF",+ H3_GGUF_REPO,+ H3_COMPONENT_REPO,+ )+ # A diffusers load holds its weights in memory, and base_repo already names its repo.+ object.__setattr__(backend._state, "engine", "diffusers")+ assert backend.loaded_repo_ids() == ()+++def test_h3_modular_load_forwards_the_hub_token_to_the_component_loads(fake_runtime):+ # The index load and the component from_pretrained calls are separate hub trips; the token has+ # to reach both, or gated/private components load anonymously (and only warn on failure).+ pipe = _load_h3_modular(VideoBackend(), hf_token = "hf_secret")+ assert _FakeModularPipeline.last["token"] == "hf_secret"+ assert pipe.load_kwargs["token"] == "hf_secret"+ # Without a configured token nothing extra is passed, so the hub's own resolution still applies.+ pipe = _load_h3_modular(VideoBackend())+ assert "token" not in pipe.load_kwargs+++def test_h3_modular_generation_ticks_and_cancels_through_the_scheduler(fake_runtime):+ backend = VideoBackend()+ pipe = _load_h3_modular(backend)+ steps_seen: list = []+ pipe.scheduler.on_step = lambda n: steps_seen.append(backend._gen.get("step"))+ result = backend.generate(prompt = "a fox", steps = 4)+ assert "callback_on_step_end" not in pipe.last_kwargs+ # One wrapped tick per denoise step, then the original method back in place.+ assert steps_seen == [1, 2, 3, 4]+ assert pipe.scheduler.step.__func__ is _FakeH3Scheduler.step+ assert result["num_frames"] == 124 and result["has_audio"] is False++ backend = VideoBackend()+ pipe = _load_h3_modular(backend)+ # The cancel lands during the FIRST step; the next wrapped call must unwind the modular denoise+ # instead of leaving Cancel to take effect only after the whole multi-minute run returns.+ pipe.scheduler.on_step = lambda n: backend.cancel_generate() if n == 1 else None+ with pytest.raises(RuntimeError, match = VIDEO_CANCELLED_MSG):+ backend.generate(prompt = "a fox", steps = 4)+ assert pipe.scheduler.calls == 1+ assert pipe.scheduler.step.__func__ is _FakeH3Scheduler.step+++def test_h3_native_transcode_is_torch_free_and_keeps_audio(monkeypatch, tmp_path):+ import io+ import math+ from fractions import Fraction++ av = pytest.importorskip("av")+ np = pytest.importorskip("numpy")+ from core.inference.video_minimax_h3 import transcode_video_to_mp4++ source = tmp_path / "native.webm"+ fps, sample_rate = 8, 48_000+ with av.open(str(source), mode = "w", format = "webm") as output:+ video = output.add_stream("libvpx-vp9", rate = fps)+ video.width = video.height = 32+ video.pix_fmt = "yuv420p"+ audio = output.add_stream("libopus", rate = sample_rate)+ audio.layout = "stereo"+ for value in (0, 128):+ frame = av.VideoFrame.from_ndarray(+ np.full((32, 32, 3), value, dtype = np.uint8), format = "rgb24"+ )+ for packet in video.encode(frame):+ output.mux(packet)+ written = 0+ while written < sample_rate // 4:+ count = min(960, sample_rate // 4 - written)+ tone = np.array(+ [+ int(12_000 * math.sin(2 * math.pi * 440 * (written + i) / sample_rate))+ for i in range(count)+ ],+ dtype = np.int16,+ )+ frame = av.AudioFrame.from_ndarray(+ np.repeat(tone, 2).reshape(1, count * 2),+ format = "s16",+ layout = "stereo",+ )+ frame.sample_rate = sample_rate+ frame.pts = written+ frame.time_base = Fraction(1, sample_rate)+ for packet in audio.encode(frame):+ output.mux(packet)+ written += count+ for packet in video.encode():+ output.mux(packet)+ for packet in audio.encode():+ output.mux(packet)++ original_import = builtins.__import__++ def _no_ml_stack_import(name, *args, **kwargs):+ if name == "torch" or name.startswith(("torch.", "diffusers")):+ raise AssertionError(f"native transcode imported {name}")+ return original_import(name, *args, **kwargs)++ monkeypatch.setattr(builtins, "__import__", _no_ml_stack_import)+ mp4 = transcode_video_to_mp4(source, fps = fps)++ with av.open(io.BytesIO(mp4)) as container:+ assert container.streams.video[0].codec_context.name == "h264"+ assert container.streams.audio[0].codec_context.name == "aac"+ assert sum(frame.samples for frame in container.decode(audio = 0)) > 0+++def test_download_plan_narrows_an_ltx23_pick_and_stages_its_extras(monkeypatch):+ # A 2.3 checkpoint brings its own VAEs, vocoder and connectors, so staging the 2.0 base copies downloads gigabytes the+ # pipeline never opens -- and the companions it DOES read were missing from the plan, so they were pulled inline.+ _plan_api(+ monkeypatch,+ {+ "unsloth/LTX-2.3-GGUF": _LTX23_REPO_SIBLINGS,+ "Lightricks/LTX-2": _LTX_BASE_SIBLINGS,+ },+ )++ plan = VideoBackend().download_plan(+ "unsloth/LTX-2.3-GGUF",+ gguf_filename = "ltx-2.3-22b-distilled.gguf",+ family_override = "ltx-2",+ )++ by_repo = {e["repo_id"]: e for e in plan["entries"]}+ # Checkpoint and extras share one repo, so they must be ONE entry: two jobs for the same repo would collide on the scoped job key.+ assert set(by_repo) == {"unsloth/LTX-2.3-GGUF", "Lightricks/LTX-2"}+ ckpt = by_repo["unsloth/LTX-2.3-GGUF"]+ assert ckpt["gguf_filename"] == "ltx-2.3-22b-distilled.gguf"+ assert "vae/ltx-2.3-22b-distilled_video_vae.safetensors" in ckpt["files"]+ assert "vae/ltx-2.3-22b-distilled_audio_vae.safetensors" in ckpt["files"]+ assert "text_encoders/ltx-2.3-22b-distilled_embeddings_connectors.safetensors" in ckpt["files"]+ # The other variant's companions are not this checkpoint's.+ assert "vae/ltx-2.3-22b-dev_video_vae.safetensors" not in ckpt["files"]++ base = by_repo["Lightricks/LTX-2"]+ assert "scheduler/scheduler_config.json" in base["files"]+ assert any(f.startswith("text_encoder/") for f in base["files"])+ for dropped in ("vae/", "vocoder/", "connectors/", "transformer/"):+ assert not any(f.startswith(dropped) for f in base["files"]), dropped+ assert plan["total_bytes"] == ckpt["bytes"] + base["bytes"]+++def _cuda_bf16_target(monkeypatch):+ """Pretend the box can run layerwise fp8, so the pre-cast encoder resolves off-GPU."""+ import torch+ monkeypatch.setattr(+ "core.inference.video.resolve_diffusion_device_target",+ lambda: types.SimpleNamespace(device = "cuda", dtype = torch.bfloat16),+ )+++_LTX2_FP8_SIBLINGS = [_PlanSibling("LTX-2-text_encoder-FP8.pt", 13_000_000_000)]+++def test_base_download_files_skips_precast_text_encoder_weights():+ # The pre-cast checkpoint supplies the encoder WEIGHTS only: the config and shard index stay, since the loader meta-inits from them.+ siblings = _LTX2_SIBLINGS + [+ _sibling("text_encoder/config.json", 1),+ _sibling("text_encoder/model.safetensors.index.json", 1),+ ]+ info = types.SimpleNamespace(siblings = siblings)+ names = [+ n+ for n, _ in VideoBackend._base_download_files(+ info, "gguf", skip_te_components = ("text_encoder",)+ )+ ]+ assert not any(n.endswith(".safetensors") and n.startswith("text_encoder/") for n in names)+ assert "text_encoder/config.json" in names+ assert "text_encoder/model.safetensors.index.json" in names+ # A different component's weights are untouched.+ assert "vae/diffusion_pytorch_model.safetensors" in names+++def test_download_plan_swaps_the_dense_encoder_for_the_precast_checkpoint(monkeypatch):+ # An fp8 encoder request loads unsloth/LTX-2-FP8, so staging the dense Gemma3 downloads ~49 GB the pipeline never opens, and the checkpoint it DOES read was missing from the plan.+ _cuda_bf16_target(monkeypatch)+ _plan_api(+ monkeypatch,+ {+ "unsloth/LTX-2.3-GGUF": _LTX23_REPO_SIBLINGS,+ "Lightricks/LTX-2": _LTX_BASE_SIBLINGS,+ "unsloth/LTX-2-FP8": _LTX2_FP8_SIBLINGS,+ },+ )++ plan = VideoBackend().download_plan(+ "unsloth/LTX-2.3-GGUF",+ gguf_filename = "ltx-2.3-22b-distilled.gguf",+ family_override = "ltx-2",+ text_encoder_quant = "fp8",+ )++ by_repo = {e["repo_id"]: e for e in plan["entries"]}+ assert by_repo["unsloth/LTX-2-FP8"]["files"] == ["LTX-2-text_encoder-FP8.pt"]+ base = by_repo["Lightricks/LTX-2"]+ assert not any(f.startswith("text_encoder/") for f in base["files"])+ # The rest of the scoped base list is unchanged.+ assert "scheduler/scheduler_config.json" in base["files"]+ assert "tokenizer/tokenizer.json" in base["files"]+ assert plan["total_bytes"] == sum(e["bytes"] for e in plan["entries"])+++def test_download_plan_keeps_the_dense_encoder_without_an_fp8_request(monkeypatch):+ # No fp8 request means the dense encoder IS the encoder: dropping it would break the load.+ _cuda_bf16_target(monkeypatch)+ _plan_api(+ monkeypatch,+ {+ "unsloth/LTX-2.3-GGUF": _LTX23_REPO_SIBLINGS,+ "Lightricks/LTX-2": _LTX_BASE_SIBLINGS,+ },+ )++ plan = VideoBackend().download_plan(+ "unsloth/LTX-2.3-GGUF",+ gguf_filename = "ltx-2.3-22b-distilled.gguf",+ family_override = "ltx-2",+ )++ by_repo = {e["repo_id"]: e for e in plan["entries"]}+ assert "unsloth/LTX-2-FP8" not in by_repo+ assert any(f.startswith("text_encoder/") for f in by_repo["Lightricks/LTX-2"]["files"])+++def test_download_plan_keeps_the_dense_encoder_when_the_precast_repo_is_missing(monkeypatch):+ # The hosted artifact can be unpublished, gated or renamed. That must neither drop the dense encoder nor sink the whole plan, which is what an unguarded lookup did.+ _cuda_bf16_target(monkeypatch)+ _plan_api(+ monkeypatch,+ {+ "unsloth/LTX-2.3-GGUF": _LTX23_REPO_SIBLINGS,+ "Lightricks/LTX-2": _LTX_BASE_SIBLINGS,+ },+ )++ plan = VideoBackend().download_plan(+ "unsloth/LTX-2.3-GGUF",+ gguf_filename = "ltx-2.3-22b-distilled.gguf",+ family_override = "ltx-2",+ text_encoder_quant = "fp8",+ )++ by_repo = {e["repo_id"]: e for e in plan["entries"]}+ assert set(by_repo) == {"unsloth/LTX-2.3-GGUF", "Lightricks/LTX-2"}+ assert any(f.startswith("text_encoder/") for f in by_repo["Lightricks/LTX-2"]["files"])+ assert plan["total_bytes"] == sum(e["bytes"] for e in plan["entries"]) > 0+++def test_fetch_te_prequant_only_reports_what_it_downloaded(monkeypatch):+ # The dense skip is earned by the pre-cast file being on disk; an unreachable checkpoint must report nothing.+ backend = VideoBackend()+ source = types.SimpleNamespace(+ kind = "repo", location = "unsloth/LTX-2-FP8", filename = "LTX-2-text_encoder-FP8.pt"+ )++ def _boom(+ repo,+ filename,+ token,+ cancel_event = None,+ ):+ raise OSError("404")++ monkeypatch.setattr("utils.hf_xet_fallback.hf_hub_download_with_xet_fallback", _boom)+ assert backend._fetch_te_prequant({"text_encoder": source}, None) == ()++ monkeypatch.setattr(+ "utils.hf_xet_fallback.hf_hub_download_with_xet_fallback",+ lambda repo, filename, token, cancel_event = None: "/tmp/precast.pt",+ )+ assert backend._fetch_te_prequant({"text_encoder": source}, None) == ("text_encoder",)+ # A local path override is the injection's business (allowlist), and nothing is fetched for it.+ local = types.SimpleNamespace(kind = "path", location = "/tmp/x.pt", filename = None)+ assert backend._fetch_te_prequant({"text_encoder": local}, None) == ()+++def test_load_pipeline_tops_up_the_dense_encoder_when_injection_fails(fake_runtime, tmp_path):+ # Injection is best-effort, but the pre-download already dropped the dense shards, so a failed injection must restore them rather than crash the load.+ backend = VideoBackend()+ calls: list[dict] = []+ backend._predownload_base = lambda *a, **k: ( # type: ignore[method-assign]+ calls.append({"args": a, "kwargs": k}) or str(tmp_path)+ )+ backend.load_pipeline(+ "Lightricks/LTX-2",+ model_kind = "pipeline",+ _base_local_dir = str(tmp_path),+ _te_prequant_skipped = ("text_encoder",),+ )+ assert len(calls) == 1 and calls[0]["kwargs"]["ltx23"] is False+ backend.unload()++ # Nothing was skipped -> no second pull.+ calls.clear()+ backend.load_pipeline("Lightricks/LTX-2", model_kind = "pipeline", _base_local_dir = str(tmp_path))+ assert calls == []+ backend.unload()+++def test_download_plan_keeps_the_wide_base_for_a_plain_ltx2_pick(monkeypatch):+ # Only 2.3 checkpoints supply their own companions; a 2.0 pick still needs the base's.+ _plan_api(+ monkeypatch,+ {+ "someone/LTX-2-GGUF": [_PlanSibling("ltx-2-dev.gguf", 12_000_000_000)],+ "Lightricks/LTX-2": _LTX_BASE_SIBLINGS,+ },+ )++ plan = VideoBackend().download_plan(+ "someone/LTX-2-GGUF", gguf_filename = "ltx-2-dev.gguf", family_override = "ltx-2"+ )++ base = next(e for e in plan["entries"] if e["repo_id"] == "Lightricks/LTX-2")+ assert any(f.startswith("vae/") for f in base["files"])+ assert any(f.startswith("connectors/") for f in base["files"])+ # The GGUF still replaces the DiT, so the transformer shards stay out.+ assert not any(f.startswith("transformer/") for f in base["files"])+++def test_each_video_load_gets_its_own_cancel_event(monkeypatch):+ """A cancelled load must STAY cancelled once the next one starts.++ unload() sets the event the running worker holds and drops _loading, so the next begin_load+ could arrive before that worker had exited. Clearing a shared event there un-cancelled the old+ worker, and its multi-gigabyte checkpoint pull resumed alongside the replacement load until the+ token check at the very end.+ """+ import threading+ from types import SimpleNamespace++ from core.inference.video import VideoBackend++ backend = VideoBackend.__new__(VideoBackend)+ backend._lock = threading.RLock()+ backend._generate_lock = threading.RLock()+ backend._cancel_event = threading.Event()+ backend._load_token = 0backend._loading = Nonebackend._active_generate_cancel = Nonebackend._state = None@@ -2368,34 +3203,250 @@ def test_generation_refuses_while_a_teardown_is_waiting(fake_runtime, tmp_path):_load_gguf(backend, tmp_path)assert backend.generate(prompt = "before", steps = 2)["mp4_bytes"] == b"MP4"- backend._teardown_waiters = 1- with pytest.raises(RuntimeError, match = "cancelled"):- backend.generate(prompt = "during", steps = 2)- # Still loaded: the refusal is about the pending teardown, not a missing model.- assert backend._state is not None+ backend._teardown_waiters = 1+ with pytest.raises(RuntimeError, match = "cancelled"):+ backend.generate(prompt = "during", steps = 2)+ # Still loaded: the refusal is about the pending teardown, not a missing model.+ assert backend._state is not None++ backend._teardown_waiters = 0+ assert backend.generate(prompt = "after", steps = 2)["mp4_bytes"] == b"MP4"+++def test_a_raising_teardown_still_drains_the_fence(fake_runtime, tmp_path, monkeypatch):+ # _teardown_state_locked ends in clear_gpu_cache(), which raises on a sticky CUDA fault. Without the finally the fence stayed up forever.+ from core.inference import video as video_mod++ backend = VideoBackend()+ _load_gguf(backend, tmp_path)++ def _sticky():+ raise RuntimeError("CUDA error: an illegal memory access was encountered")++ monkeypatch.setattr(video_mod, "clear_gpu_cache", _sticky)+ with pytest.raises(RuntimeError, match = "illegal memory access"):+ backend.unload()+ assert backend._teardown_waiters == 0, "a failed teardown must not leave the fence up"++ monkeypatch.setattr(video_mod, "clear_gpu_cache", lambda: None)+ _load_gguf(backend, tmp_path)+ assert backend.generate(prompt = "after", steps = 2)["mp4_bytes"] == b"MP4"+++# ── the H3 native path and the audio VAE ─────────────────────────────────────+def test_the_h3_native_load_never_puts_the_vae_on_the_cpu():+ """`low_vram` maps to the `model` policy, which emits `--vae-on-cpu` for everyone else.++ On H3 that aborts: the audio VAE's 1-D convolutions reach a CPU path that asserts the+ kernel is F16 while sd.cpp lets the F32 one through, so the process dies with+ `GGML_ASSERT(src0->type == GGML_TYPE_F16) failed`, SIGABRT, exit 134. Converting the+ checkpoint to fp16 does not avoid it, so the flag has to not be emitted.++ Source-level, because reproducing it needs a built sd-cli and the H3 weights. The point+ is that the H3 call site passes the opt-out, and that the flag is what is opted out of.+ """+ import ast+ from pathlib import Path++ source = (Path(__file__).resolve().parent.parent / "core" / "inference" / "video.py").read_text(+ encoding = "utf-8"+ )+ tree = ast.parse(source)+ calls = [+ node+ for node in ast.walk(tree)+ if isinstance(node, ast.Call)+ and isinstance(node.func, ast.Name)+ and node.func.id == "offload_flags"+ ]+ assert calls, "video.py no longer builds native offload flags"+ for call in calls:+ opt_out = [kw for kw in call.keywords if kw.arg == "vae_on_cpu"]+ assert opt_out, "the H3 native path must ask for the VAE to stay off the CPU"+ assert isinstance(opt_out[0].value, ast.Constant) and opt_out[0].value.value is False++ # And the flag the opt-out removes is still the one this is about.+ from core.inference.sd_cpp_args import OFFLOAD_MODEL, offload_flags++ assert "--vae-on-cpu" in offload_flags(OFFLOAD_MODEL)+ assert "--vae-on-cpu" not in offload_flags(OFFLOAD_MODEL, vae_on_cpu = False)+++def test_h3_rejects_companion_checkpoints_as_the_transformer():+ """Only a released DENOISER partition is a valid pick, and the mirror ships more than that.++ The Qwen3-VL encoder quants live in the same repo as the denoisers, so the picker lists both+ and a user can name either. Loading the encoder as the transformer would waste a ~12 GB+ download and fail deep inside sd-cli rather than at the boundary. Both fl2va and ref2va are+ valid picks -- which one is picked IS the task -- and each names its own task.++ The accept cases include the dynamic rung names specifically: the guard is a prefix/suffix+ check, and `-UD-Q2_K_XL` is a shape it had never seen when it was written.+ """+ from core.inference.video_minimax_h3 import (+ H3_TASK_KEYFRAMES,+ H3_TASK_REFERENCES,+ h3_transformer_task,+ validate_h3_transformer_filename,+ )++ for good, task in (+ ("minimax_h3_fl2va_pruned-UD-Q2_K_XL.gguf", H3_TASK_KEYFRAMES),+ ("minimax_h3_fl2va_pruned-UD-Q3_K_XL.gguf", H3_TASK_KEYFRAMES),+ ("minimax_h3_fl2va_pruned-Q4_K.gguf", H3_TASK_KEYFRAMES),+ ("minimax_h3_fl2va-Q4_K_M.gguf", H3_TASK_KEYFRAMES),+ ("minimax_h3_ref2va_pruned-Q2_K_M.gguf", H3_TASK_REFERENCES),+ ("minimax_h3_ref2va-Q4_K_M.gguf", H3_TASK_REFERENCES),+ ):+ validate_h3_transformer_filename(good)+ assert h3_transformer_task(good) == task++ for bad in (+ "qwen3vl_32b_minimax_h3-Q2_K_M.gguf",+ "qwen3vl_32b_minimax_h3-Q4_K_M.gguf",+ "minimax_h3_video_vae_fp16.safetensors",+ "minimax_h3_fl2va_pruned_bf16.safetensors",+ ):+ with pytest.raises(ValueError):+ validate_h3_transformer_filename(bad)+++def test_the_h3_native_repo_matches_the_family_gguf_repo():+ """The declared pick and the actual download must be the same repo.++ Main's `test_curated_gguf_repos_are_unsloth_mirrors` only inspects `VideoFamily.gguf_repo`,+ but H3's native path downloads from its own `H3_GGUF_REPO` constant and never reads the+ family field. So the two can drift apart and that test still passes while the one-click pick+ resolves to a community repack, which is exactly the failure it exists to prevent.++ Also asserts the transformer and the text encoder come from the same repo, since the mirror+ has to carry both for the pick to be self-contained.+ """+ from core.inference.video_families import detect_video_family+ from core.inference.video_minimax_h3 import (+ H3_GGUF_REPO,+ h3_native_hub_files,+ )++ family = detect_video_family("MiniMaxAI/MiniMax-H3")+ assert family is not None+ assert H3_GGUF_REPO == family.gguf_repo, (+ f"H3 native downloads from {H3_GGUF_REPO} but the family advertises "+ f"{family.gguf_repo}; the curated-mirror test would pass vacuously"+ )++ files = h3_native_hub_files("minimax_h3_fl2va_pruned-UD-Q2_K_XL.gguf")+ transformer_repo, transformer_name = files[0]+ encoder_repo, encoder_name = files[1]+ assert transformer_repo == encoder_repo == H3_GGUF_REPO+ assert transformer_name == "minimax_h3_fl2va_pruned-UD-Q2_K_XL.gguf"+ # The dynamic rung names must still route to the matching encoder tier.+ assert encoder_name == "qwen3vl_32b_minimax_h3-Q2_K_M.gguf"+ assert h3_native_hub_files("minimax_h3_fl2va_pruned-UD-Q3_K_XL.gguf")[1][1] == (+ "qwen3vl_32b_minimax_h3-Q4_K_M.gguf"+ )+++def test_h3_names_the_component_when_a_download_is_refused():+ """A 401 on one H3 component must not surface as the Hub's raw "Repository Not Found".++ H3 pulls four files from two repos, and the Hub returns the same message for "does not exist",+ "is private" and "your token does not cover it". A user reading it has no way to tell which of+ the four failed, and "Repository Not Found" actively points away from the real cause when the+ repo exists but is private. This matters most while the GGUF mirror is unpublished: without+ this, picking H3 fails with a message that suggests the wrong fix.+ """+ from unittest.mock import Mock++ from huggingface_hub.errors import GatedRepoError, RepositoryNotFoundError++ from core.inference.video_minimax_h3 import (+ H3_AUDIO_VAE,+ H3_QWEN_Q2,+ h3_download_error,+ )++ def _hub_error(cls):+ response = Mock()+ response.status_code = 401+ response.headers = {}+ return cls("Repository Not Found for url: ...", response = response)++ # Private / unpublished: name the repo and the component, and do not blame the token alone.+ denoiser = h3_download_error(+ "unsloth/MiniMax-H3-GGUF",+ "minimax_h3_fl2va_pruned-UD-Q2_K_XL.gguf",+ _hub_error(RepositoryNotFoundError),+ )+ assert isinstance(denoiser, RuntimeError)+ text = str(denoiser)+ assert "unsloth/MiniMax-H3-GGUF" in text+ assert "denoiser" in text+ assert "not published yet" in text++ # The same repo serves the encoder, so the component name has to come from the FILE.+ encoder = str(+ h3_download_error(+ "unsloth/MiniMax-H3-GGUF", H3_QWEN_Q2, _hub_error(RepositoryNotFoundError)+ )+ )+ assert "text encoder" in encoder and "denoiser" not in encoder++ # A gated repo has a different remedy, so it must not reuse the private wording.+ gated = str(h3_download_error("Comfy-Org/MiniMax-H3", H3_AUDIO_VAE, _hub_error(GatedRepoError)))+ assert "audio VAE" in gated+ assert "accept its licence" in gated+ assert "not published yet" not in gated- backend._teardown_waiters = 0- assert backend.generate(prompt = "after", steps = 2)["mp4_bytes"] == b"MP4"+ # Anything that is not an access error is passed straight back, so a timeout still reads as a+ # timeout rather than being reworded into a permissions problem.+ timeout = TimeoutError("read timed out")+ assert h3_download_error("unsloth/MiniMax-H3-GGUF", H3_QWEN_Q2, timeout) is timeout-def test_a_raising_teardown_still_drains_the_fence(fake_runtime, tmp_path, monkeypatch):- # _teardown_state_locked ends in clear_gpu_cache(), which raises on a sticky CUDA fault. Without the finally the fence stayed up forever.- from core.inference import video as video_mod+def test_the_h3_native_path_pins_cfg_scale_to_one():+ """H3 aborts at any cfg above 1.0, so the guidance slider must never reach sd-cli.- backend = VideoBackend()- _load_gguf(backend, tmp_path)+ H3 is distilled and CFG-free: the empty unconditional prompt encodes to zero tokens, and the+ resulting transposed tensor trips `GGML_ASSERT(!ggml_is_transposed(a))` in ggml.c. SIGABRT,+ exit 134. Measured: cfg 1.0 renders, cfg 1.5 and cfg 4.0 both abort. sd.cpp's own default is+ 7.0, so this is a crash a plausible refactor reintroduces by simply forwarding `guidance` the+ way every other family does.- def _sticky():- raise RuntimeError("CUDA error: an illegal memory access was encountered")+ The family already sets `supports_cfg = False`, but that only gates the diffusers path; the+ native path builds its own params object. Asserted at the source level because reproducing the+ abort needs a built sd-cli and the H3 weights.+ """+ import ast+ from pathlib import Path- monkeypatch.setattr(video_mod, "clear_gpu_cache", _sticky)- with pytest.raises(RuntimeError, match = "illegal memory access"):- backend.unload()- assert backend._teardown_waiters == 0, "a failed teardown must not leave the fence up"+ source = (Path(__file__).resolve().parent.parent / "core" / "inference" / "video.py").read_text(+ encoding = "utf-8"+ )+ calls = [+ node+ for node in ast.walk(ast.parse(source))+ if isinstance(node, ast.Call)+ and isinstance(node.func, ast.Name)+ and node.func.id == "SdCppVideoGenParams"+ ]+ assert calls, "video.py no longer builds native video params"+ for call in calls:+ pinned = [kw for kw in call.keywords if kw.arg == "cfg_scale"]+ assert (+ pinned+ ), "the H3 native path must pass cfg_scale explicitly, not fall back to a default"+ value = pinned[0].value+ assert isinstance(value, ast.Constant), (+ "cfg_scale must be a literal 1.0 on the H3 native path; forwarding the request's "+ "guidance reintroduces GGML_ASSERT(!ggml_is_transposed(a)), SIGABRT exit 134"+ )+ assert value.value == 1.0, value.value- monkeypatch.setattr(video_mod, "clear_gpu_cache", lambda: None)- _load_gguf(backend, tmp_path)- assert backend.generate(prompt = "after", steps = 2)["mp4_bytes"] == b"MP4"+ # And the family keeps declaring it has no CFG, so the UI does not offer the slider either.+ from core.inference.video_families import detect_video_family++ assert detect_video_family("MiniMaxAI/MiniMax-H3").supports_cfg is Falsedef _trim_spy(monkeypatch):@@ -2444,6 +3495,1028 @@ def test_attention_trim_skipped_for_static_shape_and_off_tiers(fake_runtime, monassert "hunyuan_attn_trim" not in status["speed_optims"], mode+def _fake_h3_vae():+ """A stand-in with the shapes that matter: an encoder half, a decoder with both+ autocast-eligible and float32-only parameters, and a post_quant_conv."""+ import torch++ class _VAE(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.encoder = torch.nn.Sequential(torch.nn.Conv3d(4, 8, 1))+ self.quant_conv = torch.nn.Conv3d(8, 8, 1)+ self.decoder = torch.nn.Module()+ self.decoder.proj = torch.nn.Linear(8, 16)+ self.decoder.conv = torch.nn.Conv3d(16, 4, 1)+ self.decoder.norm = torch.nn.LayerNorm(16)+ # Read directly rather than through an autocast-eligible op.+ self.decoder.register_parameter(+ "scale1", torch.nn.Parameter(torch.ones(16, dtype = torch.float32))+ )+ self.post_quant_conv = torch.nn.Conv3d(4, 4, 1)++ return _VAE().to(torch.float32)+++def test_h3_vae_trim_drops_the_encoder_only_for_a_workflow_that_never_encodes():+ import torch++ from core.inference.video_minimax_h3 import trim_h3_video_vae++ vae = _fake_h3_vae()+ report = trim_h3_video_vae(vae, workflow = "t2va")+ assert vae.encoder is None and vae.quant_conv is None+ assert report["encoder_freed"] > 0++ # An image-conditioned workflow encodes, so the same call must keep that half.+ other = _fake_h3_vae()+ other_report = trim_h3_video_vae(other, workflow = "ref2va")+ assert other.encoder is not None and other.quant_conv is not None+ assert other_report["encoder_freed"] == 0+ # The decoder pre-cast is workflow-independent and still happens.+ assert other_report["decoder_freed"] > 0+ assert other.decoder.proj.weight.dtype is torch.float16+++def test_h3_vae_trim_precasts_only_what_autocast_would_cast():+ import torch++ from core.inference.video_minimax_h3 import trim_h3_video_vae++ vae = _fake_h3_vae()+ trim_h3_video_vae(vae, workflow = "t2va")++ # Linear and Conv weights and biases are what torch.autocast casts on entry.+ assert vae.decoder.proj.weight.dtype is torch.float16+ assert vae.decoder.proj.bias.dtype is torch.float16+ assert vae.decoder.conv.weight.dtype is torch.float16+ assert vae.post_quant_conv.weight.dtype is torch.float16+ # A norm gain is on autocast's float32 promote list and a bare parameter is read+ # directly, so halving either would change the arithmetic rather than preserve it.+ assert vae.decoder.norm.weight.dtype is torch.float32+ assert vae.decoder.scale1.dtype is torch.float32+++def test_h3_vae_trim_leaves_the_decode_arithmetic_bit_identical():+ # The whole justification for pre-casting is that autocast performs exactly this cast+ # anyway, so x.to(f16).to(f16) == x.to(f16). Check the claim on a real matmul rather+ # than trusting the reasoning.+ import torch++ from core.inference.video_minimax_h3 import trim_h3_video_vae++ torch.manual_seed(0)+ reference = _fake_h3_vae()+ trimmed = _fake_h3_vae()+ trimmed.load_state_dict(reference.state_dict())+ trim_h3_video_vae(trimmed, workflow = "t2va")++ x = torch.randn(3, 8, dtype = torch.float16)+ # What autocast does with the float32 original, against the pre-cast weight.+ autocast_style = torch.nn.functional.linear(+ x,+ reference.decoder.proj.weight.to(torch.float16),+ reference.decoder.proj.bias.to(torch.float16),+ )+ precast = trimmed.decoder.proj(x)+ assert torch.equal(autocast_style, precast)+++def test_h3_vae_trim_survives_a_renamed_attribute():+ # A diffusers release that moves these attributes should cost the saving, not the render.+ import torch++ from core.inference.video_minimax_h3 import trim_h3_video_vae++ assert trim_h3_video_vae(None, workflow = "t2va") == {"encoder_freed": 0, "decoder_freed": 0}+ bare = torch.nn.Module()+ assert trim_h3_video_vae(bare, workflow = "t2va")["decoder_freed"] == 0+++# ── MiniMax-H3 keyframes (image-to-video) ────────────────────────────────────+++def test_h3_canvas_follows_the_released_checkpoint_rule():+ from core.inference.video_minimax_h3 import h3_canvas_for_aspect++ # The area cap brings 16:9 to the checkpoint's 1344x768 default.+ assert h3_canvas_for_aspect(1920, 1080) == (1344, 768)+ assert h3_canvas_for_aspect(1080, 1920) == (768, 1344)+ assert h3_canvas_for_aspect(1000, 1000) == (768, 768)+ # 4:3 stays under the cap, so the short edge is honoured exactly.+ assert h3_canvas_for_aspect(1024, 768) == (1024, 768)+ # Only the ratio matters, so a thumbnail and a 4K frame of the same shape agree.+ assert h3_canvas_for_aspect(160, 90) == h3_canvas_for_aspect(3840, 2160)+ # Outside the trained 1:4 - 4:1 band, refuse rather than generate off-distribution.+ with pytest.raises(ValueError, match = "aspect ratios"):+ h3_canvas_for_aspect(2000, 400)+ with pytest.raises(ValueError, match = "aspect ratio"):+ h3_canvas_for_aspect(0, 100)+++def test_h3_keyframe_fit_stretches_the_first_and_crops_the_last():+ Image = pytest.importorskip("PIL.Image")+ from core.inference.video_minimax_h3 import (+ H3_ANCHOR_FIRST,+ H3_ANCHOR_LAST,+ fit_h3_keyframe,+ )++ # A 2:1 source on a square canvas distinguishes stretch from center crop.+ source = Image.new("RGB", (200, 100), (0, 0, 0))+ for x in range(200):+ for y in range(100):+ source.putpixel((x, y), (255, 0, 0) if x < 20 or x >= 180 else (0, 0, 255))++ first = fit_h3_keyframe(source, 128, 128, anchor = H3_ANCHOR_FIRST)+ assert first.size == (128, 128)+ assert first.getpixel((2, 64))[0] > 200 # the red margin was squeezed in, not cut++ last = fit_h3_keyframe(source, 128, 128, anchor = H3_ANCHOR_LAST)+ assert last.size == (128, 128)+ assert last.getpixel((2, 64))[2] > 200 # the red margin fell outside the centre crop++ with pytest.raises(ValueError, match = "anchor"):+ fit_h3_keyframe(source, 64, 64, anchor = "middle")+++def _h3_native_backend(monkeypatch, calls):+ """A backend with an H3 sd.cpp state whose engine records the params it was handed."""+ from core.inference.video import _VideoLoadState+ from core.inference.video_minimax_h3 import MiniMaxH3NativeRuntime++ class _Engine:+ def generate_video(self, files, params, **kwargs):+ from PIL import Image++ # The staged PNGs live in a scratch dir the run deletes, so measure them here.+ def staged_size(path):+ if path is None:+ return None+ with Image.open(path) as image:+ return image.size++ calls.append(+ {+ "files": files,+ "params": params,+ "init_size": staged_size(params.init_img),+ "end_size": staged_size(params.end_img),+ **kwargs,+ }+ )+ return Path("/tmp/does-not-exist.webm")++ backend = VideoBackend()+ fam = _detect_load_family("unsloth/MiniMax-H3-GGUF", None, "minimax-h3")+ backend._state = _VideoLoadState(+ pipe = MiniMaxH3NativeRuntime(engine = _Engine(), files = object(), offload_flags = ()),+ family = fam,+ repo_id = "unsloth/MiniMax-H3-GGUF",+ base_repo = fam.base_repo,+ device = "cuda",+ dtype = "Q4_K_M",+ kind = "gguf",+ engine = "sd_cpp",+ h3_task = "fl2va",+ gguf_filename = "minimax_h3_fl2va-Q4_K_M.gguf",+ )+ # Imported inside _generate_h3_native, so patched at their own module.+ from core.inference import video_minimax_h3 as h3_mod++ monkeypatch.setattr(h3_mod, "inspect_video", lambda path: (1344, 768, 124, True))+ monkeypatch.setattr(h3_mod, "transcode_video_to_mp4", lambda path, fps: b"MP4")+ return backend+++def _data_url(width, height):+ import base64+ import io++ Image = pytest.importorskip("PIL.Image")+ buf = io.BytesIO()+ Image.new("RGB", (width, height), (10, 20, 30)).save(buf, format = "PNG")+ return "data:image/png;base64," + base64.b64encode(buf.getvalue()).decode()+++def test_h3_native_generate_stages_both_keyframes_on_the_canvas(monkeypatch):+ pytest.importorskip("PIL.Image")+ calls: list = []+ backend = _h3_native_backend(monkeypatch, calls)++ result = backend.generate(+ prompt = "a fox runs through snow",+ width = 960,+ height = 544,+ first_frame = _data_url(1920, 1080),+ last_frame = _data_url(400, 400),+ )++ assert calls[0]["params"].init_img and calls[0]["params"].end_img+ # Both staged images already use the requested canvas.+ assert calls[0]["init_size"] == (960, 544)+ assert calls[0]["end_size"] == (960, 544)+ assert result["conditioning"] == "fl2va"+++def test_h3_native_generate_names_each_keyframe_combination(monkeypatch):+ calls: list = []+ backend = _h3_native_backend(monkeypatch, calls)+ image = _data_url(640, 360)++ assert backend.generate(prompt = "p", width = 960, height = 544)["conditioning"] == "t2va"+ assert calls[-1]["params"].init_img is None and calls[-1]["params"].end_img is None++ assert (+ backend.generate(prompt = "p", width = 960, height = 544, first_frame = image)["conditioning"]+ == "i2va"+ )+ assert calls[-1]["params"].end_img is None++ assert (+ backend.generate(prompt = "p", width = 960, height = 544, last_frame = image)["conditioning"]+ == "l2va"+ )+ assert calls[-1]["params"].init_img is None+++def test_h3_omitted_size_takes_the_canvas_from_the_keyframe(monkeypatch):+ pytest.importorskip("PIL.Image")+ calls: list = []+ backend = _h3_native_backend(monkeypatch, calls)++ backend.generate(prompt = "p", first_frame = _data_url(1920, 1080))+ assert (calls[-1]["params"].width, calls[-1]["params"].height) == (1344, 768)++ # With no first frame the last one drives it, matching the Diffusers blocks.+ backend.generate(prompt = "p", last_frame = _data_url(1080, 1920))+ assert (calls[-1]["params"].width, calls[-1]["params"].height) == (768, 1344)+ assert calls[-1]["end_size"] == (768, 1344)++ # Without a keyframe there is nothing to match, so the family's first preset still wins.+ backend.generate(prompt = "p")+ assert (calls[-1]["params"].width, calls[-1]["params"].height) == (1344, 768)+++def test_keyframes_are_refused_by_a_family_that_has_none(fake_runtime, tmp_path):+ # Silently dropping the image would render a text-only clip with nothing to do with it.+ backend = VideoBackend()+ _load_gguf(backend, tmp_path)+ with pytest.raises(ValueError, match = "no first or last frame"):+ backend.begin_generate(prompt = "a sloth", first_frame = _data_url(64, 64))+ with pytest.raises(ValueError, match = "no first or last frame"):+ backend.generate(prompt = "a sloth", last_frame = _data_url(64, 64))+ # The refusal must not leave the busy flag set, or every later generation 409s.+ assert backend.generate_progress()["active"] is False+++def test_begin_generate_rejects_an_undecodable_keyframe(monkeypatch):+ # begin_generate returns before the job runs, so a bad image has to fail on the POST.+ backend = _h3_native_backend(monkeypatch, [])+ with pytest.raises(ValueError):+ backend.begin_generate(prompt = "p", first_frame = "data:image/png;base64,notanimage")+ assert backend.generate_progress()["active"] is False+++def test_h3_modular_load_restricts_the_components_not_the_blocks(monkeypatch, tmp_path):+ # Restrict components without pruning t2va/fl2va routing blocks.+ import types++ from core.inference.video import VideoBackend++ seen: dict = {}++ class _FakeModularPipeline:+ @classmethod+ def from_pretrained(cls, repo, **kwargs):+ seen["from_pretrained"] = {"repo": repo, **kwargs}+ return cls()++ def load_components(self, **kwargs):+ seen["load_components"] = kwargs++ def to(self, device):+ return self++ diffusers = types.SimpleNamespace(+ ComponentsManager = lambda: types.SimpleNamespace(+ enable_auto_cpu_offload = lambda **kwargs: seen.setdefault("offload", kwargs)+ ),+ ModularPipeline = _FakeModularPipeline,+ )+ torch = types.SimpleNamespace(bfloat16 = "bf16")+ fam = _detect_load_family("MiniMaxAI/MiniMax-H3", None, "minimax-h3")++ backend = VideoBackend()+ status = backend._load_h3_modular_pipeline(+ diffusers = diffusers,+ torch = torch,+ fam = fam,+ repo_id = "MiniMaxAI/MiniMax-H3",+ base = fam.base_repo,+ kind = "pipeline",+ dtype = torch.bfloat16,+ device = "cuda",+ hf_token = None,+ memory_mode = None,+ _load_token = None,+ _base_local_dir = None,+ )++ assert "workflow" not in seen["from_pretrained"]+ assert seen["load_components"]["workflow"] == "fl2va"+ assert status["supports_keyframes"] is True+ assert status["defaults"]["canvas_short_edge"] == 768+++def test_h3_modular_load_pins_a_hosted_prequant_denoiser_out_of_the_offload_rotation(monkeypatch):+ """A pre-quantized denoiser must be placed at LOAD time, not per forward.++ ComponentsManager moves each component onto the accelerator inside its own pre_forward, and a+ torchao-quantized module does not survive that mid-block move: the denoise loop died on step 1+ with "Attempted to set the storage of a tensor on device cuda:0 to a storage on different+ device cpu". So the loader has to pin it once the seeding actually engaged, and leave the+ released bfloat16 path exactly as it was.+ """+ import types++ from core.inference.video import VideoBackend++ calls: dict = {}++ class _FakeModularPipeline:+ @classmethod+ def from_pretrained(cls, repo, **kwargs):+ return cls()++ def load_components(self, **kwargs):+ pass++ def update_components(self, **kwargs):+ self.transformer = kwargs.get("transformer")++ def to(self, device):+ return self++ manager = types.SimpleNamespace(enable_auto_cpu_offload = lambda **kwargs: None)+ diffusers = types.SimpleNamespace(+ ComponentsManager = lambda: manager,+ ModularPipeline = _FakeModularPipeline,+ MiniMaxH3Transformer3DModel = object,+ )+ torch = types.SimpleNamespace(bfloat16 = "bf16")+ fam = _detect_load_family("MiniMaxAI/MiniMax-H3", None, "minimax-h3")++ seeded = object()+ import core.inference.diffusion_prequant as prequant_module++ monkeypatch.setattr(+ prequant_module,+ "load_prequantized_transformer",+ lambda *args, **kwargs: seeded,+ )+ monkeypatch.setattr(+ prequant_module,+ "pin_prequantized_module",+ lambda mgr, module, device, **kwargs: calls.setdefault(+ "pinned", {"manager": mgr, "module": module, "device": device}+ )+ is not None,+ )++ def load(scheme):+ calls.clear()+ return VideoBackend()._load_h3_modular_pipeline(+ diffusers = diffusers,+ torch = torch,+ fam = fam,+ repo_id = "MiniMaxAI/MiniMax-H3",+ base = fam.base_repo,+ kind = "pipeline",+ dtype = torch.bfloat16,+ device = "cuda",+ hf_token = None,+ memory_mode = None,+ transformer_quant = scheme,+ _load_token = None,+ _base_local_dir = None,+ )++ status = load("fp8")+ assert status["transformer_quant"] == "fp8"+ assert calls["pinned"]["module"] is seeded+ assert calls["pinned"]["manager"] is manager+ assert calls["pinned"]["device"] == "cuda"++ # No hosted checkpoint engaged -> released bfloat16 components, which the manager moves fine.+ status = load(None)+ assert status["transformer_quant"] is None+ assert "pinned" not in calls+++def test_h3_native_progress_reads_only_the_denoise_bar(monkeypatch):+ # Replay real log shapes to isolate the denoise progress bar.+ calls: list = []+ backend = _h3_native_backend(monkeypatch, calls)+ transcript = [+ "[INFO ] stable-diffusion.cpp:4365 - sampling using Euler method",+ "[INFO ] stable-diffusion.cpp:6107 - MiniMax-H3 I2VA",+ # keyframe VAE encode: same shape, its own loop+ " |==============> | 3/6 - 9.17it/s",+ "[INFO ] stable-diffusion.cpp:6899 - generate_video 640x384x124",+ # the denoiser's own weights streaming in, rated in GB/s+ " |======================| 532/532 - 3.81GB/s",+ " |=====> | 1/4 - 1.63it/s",+ " |==========> | 2/4 - 1.70it/s",+ "[INFO ] stable-diffusion.cpp:6997 - sampling completed, taking 13.20s",+ # VAE decode tiles, after the denoise window closed+ " |======================| 6/6 - 9.17it/s",+ ]++ class _ReplayEngine:+ def generate_video(self, files, params, *, on_log, **kwargs):+ seen = []+ for line in transcript:+ on_log(line)+ seen.append((backend._gen["step"], backend._gen["total"], backend._gen["phase"]))+ calls.append(seen)+ return Path("/tmp/does-not-exist.webm")++ from core.inference.video_minimax_h3 import MiniMaxH3NativeRuntime++ # Install the replay runtime into the frozen load state.+ object.__setattr__(+ backend._state,+ "pipe",+ MiniMaxH3NativeRuntime(engine = _ReplayEngine(), files = object(), offload_flags = ()),+ )+ backend.generate(prompt = "p", width = 640, height = 384, steps = 4)++ seen = calls[-1]+ # Only bars inside the denoise window update progress.+ assert seen[2] == (0, 4, "denoise")+ assert seen[4] == (0, 4, "denoise")+ assert seen[5] == (1, 4, "denoise")+ assert seen[6] == (2, 4, "denoise")+ assert seen[7] == (2, 4, "decode")+ assert seen[8] == (2, 4, "decode")+++def test_h3_native_progress_survives_the_real_in_place_redraws(monkeypatch):+ """The two halves of the frozen-bar defect have to be fixed together.++ ``sd_cpp_engine`` splits sd-cli's in-place redraws (leading ``\\r``, no newline until the last+ step, closed by ``\\033[K``) into records, and the backend's bar pattern reads them. Fix only+ the reader and the bar still never matches; fix only the pattern and the reader never hands a+ record over while sampling is running. This drives the REAL byte stream through both.+ """+ from core.inference.sd_cpp_engine import iter_sd_cpp_records++ redraw = "\r |=====> | {}/{} - 1.63it/s\x1b[K"+ # One flush per element, as the child actually writes them: the bar for step N is its own+ # write with no newline, and the carriage return that would terminate it does not arrive+ # until step N+1. Reading in one big chunk would hide exactly the lateness under test.+ flushes = [+ "[INFO ] stable-diffusion.cpp:6899 - generate_video 640x384x124\n",+ redraw.format(1, 4),+ redraw.format(2, 4),+ redraw.format(3, 4),+ redraw.format(4, 4) + "\n",+ "[INFO ] stable-diffusion.cpp:6997 - sampling completed, taking 13.20s\n",+ ]++ class _Raw:+ def __init__(self, owner) -> None:+ self._owner = owner++ def read1(self, _n: int) -> bytes:+ if not self._owner.pending:+ return b""+ self._owner.reads += 1+ return self._owner.pending.pop(0).encode()++ class _PipeStream:+ def __init__(self, payload: list[str]) -> None:+ self.pending = list(payload)+ self.reads = 0+ self.buffer = _Raw(self)++ def __iter__(self):+ raise AssertionError("a redraw carries no newline, so line iteration would block")++ calls: list = []+ backend = _h3_native_backend(monkeypatch, calls)++ class _ReplayEngine:+ def generate_video(self, files, params, *, on_log, **kwargs):+ seen = []+ stream = _PipeStream(flushes)+ for record in iter_sd_cpp_records(stream):+ on_log(record)+ seen.append((stream.reads, backend._gen["step"], backend._gen["phase"]))+ calls.append(seen)+ return Path("/tmp/does-not-exist.webm")++ from core.inference.video_minimax_h3 import MiniMaxH3NativeRuntime++ object.__setattr__(+ backend._state,+ "pipe",+ MiniMaxH3NativeRuntime(engine = _ReplayEngine(), files = object(), offload_flags = ()),+ )+ backend.generate(prompt = "p", width = 640, height = 384, steps = 4)++ seen = calls[-1]+ # Every sampling step is observed WHILE sampling, in order, not all at once at the end.+ # A redraw yields two records (the empty run before its leading CR, then the bar), so+ # collapse repeats: what matters is that 1, 2, 3 and 4 each arrive, and in that order.+ progression: list[int] = []+ for _reads, step, phase in seen:+ if phase == "denoise" and (not progression or progression[-1] != step):+ progression.append(step)+ assert progression == [0, 1, 2, 3, 4]+ # Step N must be visible after the flush that carried it (read N + 1, the opening log line+ # being read 1), not one redraw later. Being "eventually right" is the bug, not the fix.+ first_read_for = {}+ for reads, step, phase in seen:+ if phase == "denoise" and step:+ first_read_for.setdefault(step, reads)+ assert first_read_for == {1: 2, 2: 3, 3: 4, 4: 5}+ # And the run does not end parked on a full denoise bar.+ assert seen[-1][2] == "decode"+++# ── MiniMax-H3 references (Ref2VA) ───────────────────────────────────────────+++def _h3_ref_backend(monkeypatch, calls):+ """The native backend with the Ref2VA partition resident instead of FL2VA."""+ backend = _h3_native_backend(monkeypatch, calls)+ object.__setattr__(backend._state, "h3_task", "ref2va")+ object.__setattr__(backend._state, "gguf_filename", "minimax_h3_ref2va_pruned-Q4_K_M.gguf")+ return backend+++def _reference_video_data_url(+ seconds = 3.0,+ fps = 24,+ size = (160, 96),+ with_audio = True,+):+ """A real encoded MP4, so the decode path is exercised rather than stubbed."""+ import base64+ import io++ av = pytest.importorskip("av")+ np = pytest.importorskip("numpy")++ buf = io.BytesIO()+ with av.open(buf, mode = "w", format = "mp4") as out:+ video = out.add_stream("libx264", rate = fps)+ video.width, video.height = size+ video.pix_fmt = "yuv420p"+ audio = None+ if with_audio:+ audio = out.add_stream("aac", rate = 44_100)+ audio.layout = "stereo"+ for index in range(int(seconds * fps)):+ frame = av.VideoFrame.from_ndarray(+ np.full((size[1], size[0], 3), index % 255, dtype = np.uint8), format = "rgb24"+ )+ for packet in video.encode(frame):+ out.mux(packet)+ if audio is not None:+ written = 0+ total = int(seconds * 44_100)+ while written < total:+ count = min(1024, total - written)+ samples = np.zeros((1, count * 2), dtype = np.int16)+ frame = av.AudioFrame.from_ndarray(samples, format = "s16", layout = "stereo")+ frame.sample_rate = 44_100+ for packet in audio.encode(frame):+ out.mux(packet)+ written += count+ for packet in audio.encode():+ out.mux(packet)+ for packet in video.encode():+ out.mux(packet)+ return "data:video/mp4;base64," + base64.b64encode(buf.getvalue()).decode()+++def test_h3_reference_video_decodes_onto_the_models_own_clock():+ pytest.importorskip("av")+ from core.inference.video_minimax_h3 import decode_h3_reference_video++ import base64++ blob = base64.b64decode(_reference_video_data_url(seconds = 3.0, fps = 30).split(",", 1)[1])+ frames, waveform, sample_rate = decode_h3_reference_video(blob)+ # 3 seconds at 24 fps whatever the container's own rate was.+ assert len(frames) == 72+ assert waveform is not None and sample_rate == 44_100+ # And onto the canvas its own aspect ratio resolves to, never upscaled past the source.+ assert frames[0].size == (160, 96)+++def test_h3_reference_video_refuses_a_clip_below_the_trained_window():+ pytest.importorskip("av")+ import base64++ from core.inference.video_minimax_h3 import decode_h3_reference_video++ blob = base64.b64decode(_reference_video_data_url(seconds = 0.5).split(",", 1)[1])+ with pytest.raises(ValueError, match = "2 to 15 seconds"):+ decode_h3_reference_video(blob)+++def test_h3_reference_video_refuses_instead_of_silently_truncating_a_long_clip():+ pytest.importorskip("av")+ import base64++ from core.inference.video_minimax_h3 import decode_h3_reference_video++ blob = base64.b64decode(+ _reference_video_data_url(seconds = 15.1, fps = 24, with_audio = False).split(",", 1)[1]+ )+ with pytest.raises(ValueError, match = "longer than 15s"):+ decode_h3_reference_video(blob)+++def test_h3_native_refuses_a_later_video_soundtrack_after_a_silent_video(monkeypatch):+ pytest.importorskip("av")+ backend = _h3_ref_backend(monkeypatch, [])++ with pytest.raises(ValueError, match = "Video 2 has audio after a silent earlier video"):+ backend.begin_generate(+ prompt = "match <Video 1> and <Video 2>",+ reference_videos = [+ {"video": _reference_video_data_url(with_audio = False)},+ {"video": _reference_video_data_url(with_audio = True)},+ ],+ )+++def test_h3_reference_images_are_fitted_to_the_requested_policy():+ Image = pytest.importorskip("PIL.Image")+ from core.inference.video_minimax_h3 import fit_h3_reference_image++ source = Image.new("RGB", (6000, 3000), (0, 0, 0))+ # "match" brings the reference down to the generation's pixel area, aspect kept.+ matched = fit_h3_reference_image(source, width = 960, height = 544, policy = "match")+ assert matched.size[0] / matched.size[1] == pytest.approx(2.0, abs = 0.05)+ assert matched.size[0] * matched.size[1] <= 960 * 544 * 1.1+ # "max" targets the reference pipeline's own 2048px short edge instead.+ biggest = fit_h3_reference_image(source, width = 960, height = 544, policy = "max")+ assert min(biggest.size) == 2048 and max(biggest.size) == 4096+ # Neither ever upscales a source already under its target; it only snaps to 32.+ small = Image.new("RGB", (128, 128), (0, 0, 0))+ assert fit_h3_reference_image(small, width = 1344, height = 768, policy = "max").size == (128, 128)+ with pytest.raises(ValueError, match = "policy"):+ fit_h3_reference_image(source, width = 960, height = 544, policy = "huge")+++def test_h3_native_generate_stages_every_reference_kind(monkeypatch, tmp_path):+ pytest.importorskip("av")+ calls: list = []+ backend = _h3_ref_backend(monkeypatch, calls)++ staged: dict = {}++ class _Engine:+ def generate_video(self, files, params, **kwargs):+ # The scratch dir is deleted with the run, so read it here.+ staged["images"] = [Path(p).name for p in params.ref_images]+ staged["video_frames"] = sorted(Path(params.ref_videos[0]).iterdir())+ staged["video_audios"] = [Path(p).name for p in params.ref_video_audios]+ staged["audios"] = [Path(p).name for p in params.ref_audios]+ staged["wav_ok"] = all(+ Path(p).read_bytes()[:4] == b"RIFF"+ for p in params.ref_video_audios + params.ref_audios+ )+ staged["keyframes"] = (params.init_img, params.end_img)+ return Path("/tmp/does-not-exist.webm")++ from core.inference.video_minimax_h3 import MiniMaxH3NativeRuntime++ object.__setattr__(+ backend._state,+ "pipe",+ MiniMaxH3NativeRuntime(engine = _Engine(), files = object(), offload_flags = ()),+ )++ result = backend.generate(+ prompt = "the cat from <Picture 1> surfing, matching <Video 1>",+ width = 960,+ height = 544,+ reference_images = [_data_url(1200, 800), _data_url(640, 640)],+ reference_videos = [{"video": _reference_video_data_url()}],+ reference_audios = [_data_url_wav()],+ )++ assert staged["images"] == ["ref-image-00.png", "ref-image-01.png"]+ # A reference video is a DIRECTORY of frames sd-cli reads lexicographically, at 24 fps.+ assert len(staged["video_frames"]) == 72+ assert [p.name for p in staged["video_frames"][:2]] == ["00000.png", "00001.png"]+ assert staged["video_audios"] == ["ref-video-audio-00.wav"]+ assert staged["audios"] == ["ref-audio-00.wav"]+ assert staged["wav_ok"]+ assert staged["keyframes"] == (None, None)+ assert result["conditioning"] == "ref2va"+++def _data_url_wav(seconds = 1.0, rate = 32_000):+ import base64+ import io+ import math+ import wave++ buf = io.BytesIO()+ with wave.open(buf, "wb") as handle:+ handle.setnchannels(2)+ handle.setsampwidth(2)+ handle.setframerate(rate)+ frames = bytearray()+ for i in range(int(seconds * rate)):+ value = int(8000 * math.sin(2 * math.pi * 440 * i / rate))+ frames += int(value).to_bytes(2, "little", signed = True) * 2+ handle.writeframes(bytes(frames))+ return "data:audio/wav;base64," + base64.b64encode(buf.getvalue()).decode()+++def test_h3_reference_audio_decodes_inside_the_trained_window():+ pytest.importorskip("av")+ import base64++ from core.inference.video_minimax_h3 import decode_h3_reference_audio++ blob = base64.b64decode(_data_url_wav(seconds = 2.0).split(",", 1)[1])+ waveform, rate = decode_h3_reference_audio(blob)+ assert rate == 32_000+ assert waveform.shape == (64_000, 2)+++def test_h3_reference_audio_refuses_a_clip_past_the_window_while_decoding():+ # The encoded size does not bound the decoded size: the route's 32 MiB limit admits over half+ # an hour of compressed audio, which lands as ~1.9 GB of float32 and doubles again in the+ # concatenate, three times over per request. The refusal has to happen DURING the decode, not+ # after it, or the allocation the bound exists to prevent has already happened.+ pytest.importorskip("av")+ import base64++ from core.inference.video_minimax_h3 import decode_h3_reference_audio++ blob = base64.b64decode(_data_url_wav(seconds = 15.5).split(",", 1)[1])+ with pytest.raises(ValueError, match = "up to 15 seconds"):+ decode_h3_reference_audio(blob)+++def test_h3_partitions_refuse_each_others_conditioning(monkeypatch):+ # The resident partition decides which conditioning is valid.+ keyframe_backend = _h3_native_backend(monkeypatch, [])+ with pytest.raises(ValueError, match = "Load a minimax_h3_ref2va checkpoint"):+ keyframe_backend.generate(prompt = "p", reference_images = [_data_url(64, 64)])++ reference_backend = _h3_ref_backend(monkeypatch, [])+ with pytest.raises(ValueError, match = "Load a minimax_h3_fl2va checkpoint"):+ reference_backend.generate(prompt = "p", first_frame = _data_url(64, 64))+++def test_h3_native_refuses_the_max_reference_policy(monkeypatch):+ # sd.cpp cannot preserve the 2048px "max" policy.+ backend = _h3_ref_backend(monkeypatch, [])+ with pytest.raises(ValueError, match = "needs the Diffusers engine"):+ backend.generate(+ prompt = "p", reference_images = [_data_url(64, 64)], reference_image_size = "max"+ )+++def test_h3_status_reports_the_resident_partition(monkeypatch):+ keyframe_backend = _h3_native_backend(monkeypatch, [])+ status = keyframe_backend.status()+ assert status["h3_task"] == "fl2va"+ assert status["supports_keyframes"] is True and status["supports_references"] is False++ reference_backend = _h3_ref_backend(monkeypatch, [])+ status = reference_backend.status()+ assert status["h3_task"] == "ref2va"+ assert status["supports_keyframes"] is False and status["supports_references"] is True+++def test_h3_load_refuses_a_task_that_contradicts_the_picked_checkpoint():+ backend = VideoBackend()+ backend.validate_load_request(+ "unsloth/MiniMax-H3-GGUF",+ gguf_filename = "minimax_h3_ref2va_pruned-Q4_K_M.gguf",+ family_override = "minimax-h3",+ h3_task = "ref2va",+ )+ with pytest.raises(ValueError, match = "is the ref2va partition"):+ backend.validate_load_request(+ "unsloth/MiniMax-H3-GGUF",+ gguf_filename = "minimax_h3_ref2va_pruned-Q4_K_M.gguf",+ family_override = "minimax-h3",+ h3_task = "fl2va",+ )+++def test_h3_modular_load_brings_up_the_requested_partition(monkeypatch):+ import types++ seen: dict = {}++ class _FakeModularPipeline:+ @classmethod+ def from_pretrained(cls, repo, **kwargs):+ return cls()++ def load_components(self, **kwargs):+ seen["workflow"] = kwargs.get("workflow")++ def to(self, device):+ return self++ diffusers = types.SimpleNamespace(+ ComponentsManager = lambda: types.SimpleNamespace(+ enable_auto_cpu_offload = lambda **kwargs: None+ ),+ ModularPipeline = _FakeModularPipeline,+ )+ torch = types.SimpleNamespace(bfloat16 = "bf16")+ fam = _detect_load_family("MiniMaxAI/MiniMax-H3", None, "minimax-h3")++ backend = VideoBackend()+ status = backend._load_h3_modular_pipeline(+ diffusers = diffusers,+ torch = torch,+ fam = fam,+ repo_id = "MiniMaxAI/MiniMax-H3",+ base = fam.base_repo,+ kind = "pipeline",+ dtype = torch.bfloat16,+ device = "cuda",+ hf_token = None,+ memory_mode = None,+ h3_task = "ref2va",+ )+ assert seen["workflow"] == "ref2va"+ assert status["supports_references"] is True and status["supports_keyframes"] is False+++def test_h3_flow_shift_defaults_to_the_released_schedule(monkeypatch):+ calls: list = []+ backend = _h3_native_backend(monkeypatch, calls)++ result = backend.generate(prompt = "p", width = 640, height = 384)+ assert calls[-1]["params"].flow_shift == 12.0+ assert (result["flow_shift"], result["audio_flow_shift"]) == (12.0, 3.0)++ backend.generate(prompt = "p", width = 640, height = 384, flow_shift = 6.5)+ assert calls[-1]["params"].flow_shift == 6.5++ # sd.cpp accepts only the released audio shift it already applies.+ backend.generate(prompt = "p", width = 640, height = 384, audio_flow_shift = 3.0)+ with pytest.raises(ValueError, match = "Diffusers engine"):+ backend.generate(prompt = "p", width = 640, height = 384, audio_flow_shift = 5.0)++ status = backend.status()+ assert status["defaults"]["flow_shift"] == 12.0+ assert status["defaults"]["audio_flow_shift"] == 3.0+ assert status["defaults"]["supports_audio_flow_shift"] is False+++def test_schedule_shifts_are_refused_by_families_that_do_not_expose_them():+ fam = _detect_load_family("Lightricks/LTX-2", None, None)++ with pytest.raises(ValueError, match = "does not expose a video flow_shift"):+ VideoBackend._resolve_flow_shifts(fam, "diffusers", 5.0, None)+ with pytest.raises(ValueError, match = "does not expose an audio_flow_shift"):+ VideoBackend._resolve_flow_shifts(fam, "diffusers", None, 3.0)+++def test_h3_modular_generate_sets_both_schedule_shifts(fake_runtime, monkeypatch):+ # Scheduler components must receive both shifts on every run.+ import contextlib+ import types++ from core.inference.video import _VideoLoadState++ shifts: dict = {}++ class _Scheduler:+ def __init__(self, name):+ self._name = name++ def set_shift(self, value):+ shifts[self._name] = value++ def step(self, *args, **kwargs):+ return None++ class _ModularPipe:+ scheduler = _Scheduler("video")+ audio_scheduler = _Scheduler("audio")++ def __call__(self, **kwargs):+ shifts["called"] = True+ return {"videos": [[object()]], "audio": None, "sampling_rate": None}++ backend = VideoBackend()+ fam = _detect_load_family("MiniMaxAI/MiniMax-H3", None, "minimax-h3")+ backend._state = _VideoLoadState(+ pipe = _ModularPipe(),+ family = fam,+ repo_id = "MiniMaxAI/MiniMax-H3",+ base_repo = fam.base_repo,+ device = "cpu",+ dtype = "bfloat16",+ kind = "pipeline",+ engine = "diffusers",+ h3_task = "fl2va",+ )+ monkeypatch.setattr(VideoBackend, "_encode_mp4", staticmethod(lambda *a, **k: b"MP4"))+ monkeypatch.setattr("core.inference.video.contextlib", contextlib)++ result = backend.generate(prompt = "p", width = 960, height = 544, steps = 2)+ assert shifts["video"] == 12.0 and shifts["audio"] == 3.0++ backend.generate(+ prompt = "p",+ width = 960,+ height = 544,+ steps = 2,+ flow_shift = 7.0,+ audio_flow_shift = 4.0,+ )+ assert shifts["video"] == 7.0 and shifts["audio"] == 4.0+ assert result["flow_shift"] == 12.0+++def test_h3_begin_generate_refuses_an_unhonourable_audio_shift(monkeypatch):+ # Reject unsupported shifts before the asynchronous job starts.+ backend = _h3_native_backend(monkeypatch, [])+ with pytest.raises(ValueError, match = "Diffusers engine"):+ backend.begin_generate(prompt = "p", audio_flow_shift = 6.0)+ assert backend.generate_progress()["active"] is False+ # The released value is not a request to change anything, so it must still start.+ backend.begin_generate(prompt = "p", audio_flow_shift = 3.0)+++def test_h3_ref2va_partition_refuses_a_reference_less_request(monkeypatch):+ """A Ref2VA load fetched only `transformer_ref`, and only the reference branch reads it.++ A text-only request routes to the t2va branch, finds `transformer` unloaded and dies inside+ the Diffusers blocks with "'NoneType' object has no attribute 'forward'" -- caught running+ the real BF16 weights. Refused at the boundary instead, on both engines, so the rule does+ not depend on which one is active.+ """+ backend = _h3_ref_backend(monkeypatch, [])+ with pytest.raises(ValueError, match = "Add at least one reference"):+ backend.generate(prompt = "a fox in snow", width = 640, height = 384)+ with pytest.raises(ValueError, match = "Add at least one reference"):+ backend.begin_generate(prompt = "a fox in snow")+ assert backend.generate_progress()["active"] is False+ # The FL2VA partition is where text-only belongs, and it still takes it.+ keyframe_backend = _h3_native_backend(monkeypatch, [])+ assert (+ keyframe_backend.generate(prompt = "a fox in snow", width = 640, height = 384)["conditioning"]+ == "t2va"+ )+++def test_h3_vae_trim_keeps_the_encoder_for_the_workflows_that_encode():+ """The encoder drop is gated on t2va, and neither workflow Studio loads is text-only.++ fl2va encodes its keyframes and ref2va its references, both through this VAE, so dropping the+ encoder half would break image conditioning outright. The decoder pre-cast -- the larger of+ the two savings -- is unconditional and must still happen for either.+ """+ torch = pytest.importorskip("torch")+ from core.inference.video_minimax_h3 import trim_h3_video_vae++ def _vae():+ vae = types.SimpleNamespace()+ vae.encoder = torch.nn.Conv2d(3, 8, 3)+ vae.quant_conv = torch.nn.Conv2d(8, 8, 1)+ vae.decoder = torch.nn.Conv2d(8, 3, 3)+ vae.post_quant_conv = torch.nn.Conv2d(8, 8, 1)+ return vae++ for workflow in ("fl2va", "ref2va"):+ vae = _vae()+ report = trim_h3_video_vae(vae, workflow = workflow)+ assert vae.encoder is not None, workflow+ assert vae.quant_conv is not None, workflow+ assert report["encoder_freed"] == 0, workflow+ # The decoder is still pre-cast to float16, which is where the bulk of the saving is.+ assert report["decoder_freed"] > 0, workflow+ assert vae.decoder.weight.dtype is torch.float16, workflow++ # The gate itself still works for a text-only load, so the saving is not lost, only unused.+ vae = _vae()+ assert trim_h3_video_vae(vae, workflow = "t2va")["encoder_freed"] > 0+ assert vae.encoder is None++# ── a failed video must say what it was rendering (#8225) ────────────────────────@@ -2913,6 +4986,11 @@ def test_plan_is_unchanged_when_no_text_encoder_quant_is_requested(fake_runtime,for fam in _FAMILIES:if fam.bf16_components_gb is None or fam.name == "wan2.2-t2v-a14b":continue+ # A modular-workflow family has no dense plan to be unchanged: load_pipeline dispatches to+ # the workflow's own loader before plan_diffusion_memory is ever reached, because there is+ # no single dense pipeline to budget -- each component is built by its own from_pretrained.+ if fam.modular_workflow:+ continuecalls.clear()VideoBackend().load_pipeline(fam.base_repo, model_kind = "pipeline")assert calls[0]["model_dense_mib"] == int(diff --git a/studio/backend/tests/test_video_families.py b/studio/backend/tests/test_video_families.pyindex a1f07993f57..f968433d2fc 100644--- a/studio/backend/tests/test_video_families.py+++ b/studio/backend/tests/test_video_families.py@@ -16,6 +16,18 @@ from core.inference.video_families import (snap_video_size,supported_video_family_names,)+from core.inference.video_minimax_h3 import (+ estimate_h3_diffusers_host_ram_gb,+ estimate_h3_diffusers_vram_gb,+)+++def test_h3_measured_diffusers_memory_estimates():+ assert estimate_h3_diffusers_vram_gb(960, 544, 124) == pytest.approx(73.68, abs = 0.02)+ assert estimate_h3_diffusers_vram_gb(1344, 768, 124) == pytest.approx(78.74, abs = 0.02)+ assert estimate_h3_diffusers_vram_gb(1344, 768, 345) == pytest.approx(96.98, abs = 0.02)+ assert estimate_h3_diffusers_host_ram_gb(126) == 150+ assert estimate_h3_diffusers_host_ram_gb(132) == 85@pytest.mark.parametrize(@@ -145,6 +157,7 @@ def test_generation_defaults_distilled_vs_dev():def test_supported_names():assert supported_video_family_names() == (+ "minimax-h3","ltx-2","wan2.2-ti2v-5b","wan2.2-t2v-a14b",@@ -153,6 +166,22 @@ def test_supported_names():)+def test_minimax_h3_family_and_frame_lattice():+ fam = detect_video_family("MiniMaxAI/MiniMax-H3")+ assert fam is not None and fam.name == "minimax-h3"+ # fl2va loads the superset that also serves text-only requests.+ assert fam.modular_workflow == "fl2va"+ assert fam.has_audio is True+ assert fam.supports_keyframes is True+ assert fam.supports_cfg is False+ assert fam.frame_step == 17+ assert fam.frame_offset == 5+ assert snap_num_frames(fam, 124) == 124+ assert snap_num_frames(fam, 125) == 141+ assert snap_num_frames(fam, 1) == 124+ assert snap_num_frames(fam, 999) == 345++def test_wan_snap_num_frames_4k_plus_1():# Wan's temporal factor is 4, so valid counts are 4k+1 (not LTX-2's 8k+1).fam = detect_video_family("Wan-AI/Wan2.2-TI2V-5B-Diffusers")@@ -339,3 +368,26 @@ def test_curated_gguf_repos_are_unsloth_mirrors():curated = {fam.name: fam.gguf_repo for fam in _FAMILIES if fam.gguf_repo}assert curated["wan2.2-ti2v-5b"] == "unsloth/Wan2.2-TI2V-5B-GGUF"assert all(repo.startswith("unsloth/") for repo in curated.values()), curated+++def test_minimax_h3_offers_every_advertised_aspect_ratio():+ from core.inference.video_minimax_h3 import H3_CANVAS_MAX_PIXELS, h3_canvas_for_aspect++ fam = detect_video_family("MiniMaxAI/MiniMax-H3")+ presets = fam.resolution_presets+ ratios = {round(w / h, 3) for w, h in presets}+ # The six ratios advertised by the model card.+ for aspect in ((21, 9), (16, 9), (4, 3), (1, 1), (3, 4), (9, 16)):+ derived = h3_canvas_for_aspect(*aspect)+ assert round(derived[0] / derived[1], 3) in ratios, f"{aspect} has no preset"+ assert fam.resolution_presets[0] == (1344, 768), "16:9 stays the default"++ # Reduced tiers may be smaller than the resolved canvas. The legacy 1024 square is the+ # only entry above the area cap.+ for width, height in presets:+ assert width % 32 == 0 and height % 32 == 0, (width, height)+ if (width, height) == (1024, 1024):+ continue+ assert width * height <= H3_CANVAS_MAX_PIXELS, (width, height)+ rule_width, rule_height = h3_canvas_for_aspect(width, height)+ assert width <= rule_width and height <= rule_height, (width, height)diff --git a/studio/backend/tests/test_video_minimax_h3_adaln.py b/studio/backend/tests/test_video_minimax_h3_adaln.pynew file mode 100644index 00000000000..cb4c715451d--- /dev/null+++ b/studio/backend/tests/test_video_minimax_h3_adaln.py@@ -0,0 +1,321 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Hermetic CPU tests for MiniMax-H3's pruned (curve-form) adaLN conversion.++No diffusers, no CUDA, no checkpoint: a tiny stand-in with the same module layout as+``MiniMaxH3Transformer3DModel`` (``transformer_blocks[i].adaln_proj.linear``, ``norm_out.linear``,+``time_embedder``, ``time_proj``) exercises every branch of the conversion, and the numerics are+checked against the reference formula written out longhand rather than against the implementation.+"""++from __future__ import annotations++import pytest+import torch+from torch import nn++from core.inference.video_minimax_h3_adaln import (+ apply_h3_adaln_curve,+ is_curve_checkpoint,+)++HIDDEN = 4+CURVE_DIM = 3+CURVE_GRID = 5+MODALITIES = 3+++def _curve_meta(**overrides):+ meta = {+ "adaln_form": "curve",+ "curve_dim": CURVE_DIM,+ "curve_grid": CURVE_GRID,+ "scheme": "int8",+ "family": "minimax-h3",+ }+ meta.update(overrides)+ return meta+++class _Modulation(nn.Module):+ """Stands in for ``MiniMaxH3AdaLayerNormModulation`` (dense form: SiLU then project)."""++ def __init__(self, time_embed_dim: int, hidden_size: int):+ super().__init__()+ self.hidden_size = hidden_size+ self.linear = nn.Linear(time_embed_dim, 6 * hidden_size * MODALITIES)++ def forward(self, temb):+ temb = self.linear(nn.functional.silu(temb).to(self.linear.weight.dtype))+ return temb.view(-1, 6 * self.hidden_size).chunk(6, dim = -1)+++class _NormOut(nn.Module):+ """Stands in for ``MiniMaxH3AdaLayerNormOut``."""++ def __init__(self, time_embed_dim: int, hidden_size: int):+ super().__init__()+ self.norm = nn.RMSNorm(hidden_size, eps = 1e-5)+ self.linear = nn.Linear(time_embed_dim, 2 * hidden_size)++ def forward(self, hidden_states, temb, timestep_indices):+ shift, scale = self.linear(nn.functional.silu(temb).to(self.linear.weight.dtype)).chunk(+ 2, dim = -1+ )+ hidden_states = self.norm(hidden_states)+ return hidden_states * (1.0 + scale.index_select(0, timestep_indices)) + shift.index_select(+ 0, timestep_indices+ )+++class _Block(nn.Module):+ def __init__(self, time_embed_dim: int):+ super().__init__()+ self.adaln_proj = _Modulation(time_embed_dim, HIDDEN)+++class _FourierTimeProj(nn.Module):+ """Stands in for ``Timesteps``: expands a scalar timestep into features.++ Deliberately NOT an identity, so a test asserting `time_proj` became a passthrough actually+ fails when the conversion forgets to replace it."""++ def forward(self, timestep):+ return torch.stack([timestep.sin(), timestep.cos()], dim = -1)+++class _FakeH3(nn.Module):+ """The dense module layout the conversion rewrites."""++ def __init__(+ self,+ time_embed_dim: int = 7,+ num_layers: int = 2,+ ):+ super().__init__()+ self.time_proj = _FourierTimeProj()+ self.time_embedder = nn.Module()+ self.time_embedder.linear_1 = nn.Linear(2, time_embed_dim)+ self.time_embedder.linear_2 = nn.Linear(time_embed_dim, time_embed_dim)+ self.transformer_blocks = nn.ModuleList([_Block(time_embed_dim) for _ in range(num_layers)])+ self.norm_out = _NormOut(time_embed_dim, HIDDEN)+++# ── is_curve_checkpoint ──────────────────────────────────────────────────────────+def test_is_curve_checkpoint_accepts_a_fully_specified_curve_artifact():+ assert is_curve_checkpoint(_curve_meta()) is True+++ "overrides",+ [+ {"adaln_form": "dense"},+ {"adaln_form": None},+ {"curve_dim": 0},+ {"curve_grid": None},+ ],+)+def test_is_curve_checkpoint_rejects_incomplete_metadata(overrides):+ # A checkpoint that does not DECLARE the form, or omits either dimension, must not trigger a+ # reshape: the loader would then install differently-shaped weights and generate noise.+ assert is_curve_checkpoint(_curve_meta(**overrides)) is False+++def test_is_curve_checkpoint_rejects_a_non_mapping():+ assert is_curve_checkpoint(None) is False+ assert is_curve_checkpoint("curve") is False+++# ── apply_h3_adaln_curve ─────────────────────────────────────────────────────────+def test_dense_metadata_leaves_the_model_untouched():+ model = _FakeH3()+ before = model.transformer_blocks[0].adaln_proj.linear.in_features+ assert apply_h3_adaln_curve(model, {"adaln_form": "dense"}) is False+ assert model.transformer_blocks[0].adaln_proj.linear.in_features == before+ assert isinstance(model.time_proj, _FourierTimeProj)+ assert hasattr(model.time_embedder, "linear_1")+++def test_curve_conversion_reshapes_every_projection():+ model = _FakeH3(num_layers = 3)+ assert apply_h3_adaln_curve(model, _curve_meta()) is True+ for block in model.transformer_blocks:+ assert block.adaln_proj.linear.in_features == CURVE_DIM+ # Output width is the modulation fan-out and must NOT change.+ assert block.adaln_proj.linear.out_features == 6 * HIDDEN * MODALITIES+ assert model.norm_out.linear.in_features == CURVE_DIM+ assert model.norm_out.linear.out_features == 2 * HIDDEN+ assert model.time_embedder.table.shape == (CURVE_GRID, CURVE_DIM)+++def test_curve_conversion_rejects_a_model_without_the_h3_layout():+ with pytest.raises(ValueError, match = "MiniMaxH3Transformer3DModel"):+ apply_h3_adaln_curve(nn.Linear(2, 2), _curve_meta())+++def test_curve_conversion_rejects_a_block_whose_projection_is_not_a_linear():+ model = _FakeH3()+ model.transformer_blocks[0].adaln_proj.linear = nn.Identity()+ with pytest.raises(ValueError, match = "expected a Linear"):+ apply_h3_adaln_curve(model, _curve_meta())+++# ── the state dict must match the hosted checkpoint exactly ──────────────────────+def test_conversion_swaps_the_time_embedder_keys_for_the_table():+ model = _FakeH3()+ apply_h3_adaln_curve(model, _curve_meta())+ keys = set(model.state_dict())+ assert "time_embedder.table" in keys+ # The dense MLP keys must be GONE, or strict=True load of a curve checkpoint reports them missing.+ assert not any(k.startswith("time_embedder.linear_") for k in keys)+++def test_the_dtype_shim_stays_out_of_the_state_dict():+ # The model's forward reads time_embedder.linear_1.weight.dtype, so the shim must exist as an+ # attribute but must NOT be a persistent buffer: an extra key breaks the strict load it exists to allow.+ model = _FakeH3()+ apply_h3_adaln_curve(model, _curve_meta())+ assert model.time_embedder.linear_1.weight.dtype == torch.float32+ assert "time_embedder.linear_1.weight" not in set(model.state_dict())+++# ── numerics ─────────────────────────────────────────────────────────────────────+def _fill_table(model):+ with torch.no_grad():+ model.time_embedder.table.copy_(+ torch.arange(CURVE_GRID * CURVE_DIM, dtype = torch.float32).view(CURVE_GRID, CURVE_DIM)+ )+++def test_time_embedder_interpolates_between_the_two_neighbouring_grid_rows():+ model = _FakeH3()+ apply_h3_adaln_curve(model, _curve_meta())+ _fill_table(model)+ table = model.time_embedder.table+ # Half-way between grid rows 0 and 1 (grid of 5 spans [0,1], so t=0.125 is row 0.5).+ got = model.time_embedder(torch.tensor([0.125]))+ expected = 0.5 * table[0] + 0.5 * table[1]+ assert torch.allclose(got[0], expected, atol = 1e-6)+++def test_time_embedder_pins_the_grid_endpoints():+ model = _FakeH3()+ apply_h3_adaln_curve(model, _curve_meta())+ _fill_table(model)+ table = model.time_embedder.table+ got = model.time_embedder(torch.tensor([0.0, 1.0]))+ assert torch.equal(got[0], table[0])+ # t=1.0 must land exactly on the LAST row, not read past the table.+ assert torch.equal(got[1], table[-1])+++def test_time_embedder_clamps_out_of_range_timesteps_to_the_curve_ends():+ model = _FakeH3()+ apply_h3_adaln_curve(model, _curve_meta())+ _fill_table(model)+ table = model.time_embedder.table+ got = model.time_embedder(torch.tensor([-3.0, 7.5]))+ assert torch.equal(got[0], table[0])+ assert torch.equal(got[1], table[-1])+++def test_modulation_forward_drops_the_silu():+ # The tabulated curve is the dense path's POST-activation embedding projected onto the basis,+ # so re-applying SiLU would square the nonlinearity. This is the assertion that catches it.+ model = _FakeH3()+ apply_h3_adaln_curve(model, _curve_meta())+ proj = model.transformer_blocks[0].adaln_proj+ temb = torch.randn(2, CURVE_DIM)+ got = torch.cat(proj(temb), dim = -1)+ raw = proj.linear(temb).view(-1, 6 * HIDDEN)+ silu = proj.linear(nn.functional.silu(temb)).view(-1, 6 * HIDDEN)+ assert torch.allclose(got, raw, atol = 1e-6)+ assert not torch.allclose(got, silu, atol = 1e-4)+++def test_modulation_casts_the_chunks_to_the_recorded_stream_dtype():+ # The pruned modulation is stored float32 while the block stack runs bfloat16, and the block's+ # forward multiplies without casting. Leaving the chunks float32 promotes the stack and the+ # first quantized matmul fails on mismatched dtypes, so this cast is what makes the model run.+ model = _FakeH3()+ apply_h3_adaln_curve(model, _curve_meta(adaln_out_dtype = "bfloat16"))+ proj = model.transformer_blocks[0].adaln_proj+ assert proj.linear.weight.dtype == torch.float32+ chunks = proj(torch.randn(2, CURVE_DIM))+ assert all(chunk.dtype == torch.bfloat16 for chunk in chunks)+++def test_modulation_keeps_the_projection_dtype_when_none_was_recorded():+ # An unrecognised or absent value must not be guessed at: leave the chunks where they were.+ model = _FakeH3()+ apply_h3_adaln_curve(model, _curve_meta(adaln_out_dtype = "not_a_dtype"))+ chunks = model.transformer_blocks[0].adaln_proj(torch.randn(2, CURVE_DIM))+ assert all(chunk.dtype == torch.float32 for chunk in chunks)+++def test_norm_out_is_not_cast_down():+ # Unlike the block modulation, the final layer's shift/scale stay at their own precision: the+ # result goes straight into the float32 output heads.+ model = _FakeH3()+ apply_h3_adaln_curve(model, _curve_meta(adaln_out_dtype = "bfloat16"))+ out = model.norm_out(torch.randn(2, HIDDEN), torch.randn(1, CURVE_DIM), torch.tensor([0, 0]))+ assert out.dtype == torch.float32+++def test_the_out_dtype_marker_stays_out_of_the_state_dict():+ model = _FakeH3()+ apply_h3_adaln_curve(model, _curve_meta(adaln_out_dtype = "bfloat16"))+ assert not any("adaln_out_dtype" in k for k in model.state_dict())+++def test_modulation_forward_keeps_the_dense_row_layout():+ # Rows are [t0_mod0, t0_mod1, t0_mod2, t1_mod0, ...]: the block's adaln_indices address that+ # layout, so a reshape that changed it would silently modulate the wrong modality.+ model = _FakeH3()+ apply_h3_adaln_curve(model, _curve_meta())+ chunks = model.transformer_blocks[0].adaln_proj(torch.randn(2, CURVE_DIM))+ assert len(chunks) == 6+ for chunk in chunks:+ assert chunk.shape == (2 * MODALITIES, HIDDEN)+++def test_norm_out_forward_drops_the_silu_and_indexes_per_row():+ model = _FakeH3()+ apply_h3_adaln_curve(model, _curve_meta())+ norm_out = model.norm_out+ temb = torch.randn(2, CURVE_DIM)+ hidden = torch.randn(4, HIDDEN)+ indices = torch.tensor([0, 1, 1, 0])+ got = norm_out(hidden, temb, indices)+ shift, scale = norm_out.linear(temb).chunk(2, dim = -1)+ expected = norm_out.norm(hidden) * (1.0 + scale.index_select(0, indices)) + shift.index_select(+ 0, indices+ )+ assert torch.allclose(got, expected, atol = 1e-6)+ silu_shift, silu_scale = norm_out.linear(nn.functional.silu(temb)).chunk(2, dim = -1)+ silu_expected = norm_out.norm(hidden) * (+ 1.0 + silu_scale.index_select(0, indices)+ ) + silu_shift.index_select(0, indices)+ assert not torch.allclose(got, silu_expected, atol = 1e-4)+++def test_time_proj_becomes_a_passthrough():+ # The curve table is indexed by the RAW timestep, not by time_proj's Fourier features.+ model = _FakeH3()+ apply_h3_adaln_curve(model, _curve_meta())+ timestep = torch.tensor([0.25, 0.75])+ assert torch.equal(model.time_proj(timestep), timestep)+++def test_the_curve_forward_is_bound_per_instance_not_on_the_class():+ # A dense H3 load in the same process shares these classes; patching the class would corrupt it.+ converted = _FakeH3()+ dense = _FakeH3()+ apply_h3_adaln_curve(converted, _curve_meta())+ temb = torch.randn(2, dense.norm_out.linear.in_features)+ got = torch.cat(dense.transformer_blocks[0].adaln_proj(temb), dim = -1)+ expected = (+ dense.transformer_blocks[0].adaln_proj.linear(nn.functional.silu(temb)).view(-1, 6 * HIDDEN)+ )+ assert torch.allclose(got, expected, atol = 1e-6)diff --git a/studio/backend/tests/test_video_prequant.py b/studio/backend/tests/test_video_prequant.pynew file mode 100644index 00000000000..9865fb30a2b--- /dev/null+++ b/studio/backend/tests/test_video_prequant.py@@ -0,0 +1,321 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Hosted pre-quantized DENOISER route for video families.++Covers the family table + resolver, the repo-root checkpoint naming, and the+``validate_load_request`` refusals that must fire BEFORE anything downloads. All network-free and+torch-free: the refusals are deliberately placed ahead of the diffusers availability probe so they+still run (and still get tested) in an environment where diffusers cannot be imported at all.+"""++from __future__ import annotations++import pytest++from core.inference.diffusion_prequant import (+ cached_checkpoint_path,+ resolve_prequant_source,+)+from core.inference.video import VideoBackend+from core.inference.video_families import (+ VideoFamily,+ detect_video_family,+ video_family_prequant_repo,+ video_family_prequant_schemes,+)+++def _fam(**kwargs) -> VideoFamily:+ base = dict(+ name = "test-video",+ pipeline_class = "TestPipeline",+ transformer_class = "TestTransformer3DModel",+ base_repo = "org/test-video",+ )+ base.update(kwargs)+ return VideoFamily(**base)+++# ── the resolver ─────────────────────────────────────────────────────────────────+def test_resolves_the_hosted_repo_for_a_scheme():+ fam = _fam(prequant_repos = (("int8", "org/test-INT8"), ("fp8", "org/test-FP8")))+ assert video_family_prequant_repo(fam, "int8") == "org/test-INT8"+ assert video_family_prequant_repo(fam, "fp8") == "org/test-FP8"+ assert video_family_prequant_repo(fam, "nvfp4") is None+++def test_a_variant_checkpoint_wins_over_the_family_default():+ # A checkpoint is baked from ONE base's weights, so a variant base with its own artifact must+ # take it rather than the family default, which the base_model_id check would then reject.+ fam = _fam(+ prequant_repos = (("int8", "org/test-INT8"),),+ prequant_variant_repos = (("org/test-video-v2", "int8", "org/test-v2-INT8"),),+ )+ assert video_family_prequant_repo(fam, "int8", "org/test-video-v2") == "org/test-v2-INT8"+ # Case and surrounding whitespace must not change the answer.+ assert video_family_prequant_repo(fam, "int8", " ORG/Test-Video-V2 ") == "org/test-v2-INT8"+ # A base without its own entry falls back to the family default.+ assert video_family_prequant_repo(fam, "int8", "org/other") == "org/test-INT8"+++def test_a_malformed_table_row_is_skipped_rather_than_raised():+ # This runs on the refusal path of a load request: a table typo must not turn a legitimate+ # pick into a 500.+ fam = _fam(prequant_repos = (("int8",), ("int8", ""), ("int8", "org/good")))+ assert video_family_prequant_repo(fam, "int8") == "org/good"+++def test_a_family_without_the_fields_simply_has_no_checkpoint():+ import types+ assert video_family_prequant_repo(types.SimpleNamespace(), "int8") is None+ assert video_family_prequant_schemes(types.SimpleNamespace()) == ()+++def test_schemes_are_listed_in_table_order():+ # The refusal message names these, so the order is what the user is told to try first.+ fam = _fam(prequant_repos = (("int8", "org/a"), ("fp8", "org/b")))+ assert video_family_prequant_schemes(fam) == ("int8", "fp8")+++# ── the H3 table ─────────────────────────────────────────────────────────────────+def test_minimax_h3_declares_hosted_denoiser_checkpoints():+ fam = detect_video_family("MiniMaxAI/MiniMax-H3")+ assert fam is not None and fam.name == "minimax-h3"+ assert set(video_family_prequant_schemes(fam)) == {"int8", "fp8"}+ for scheme in ("int8", "fp8"):+ repo = video_family_prequant_repo(fam, scheme)+ # Curated hosted artifacts only: a third-party repo here would be unpickled by the loader.+ assert repo and repo.startswith("unsloth/")+++def test_both_h3_schemes_resolve_to_one_repo():+ # Both schemes live in the SAME hosted repo. Two repos meant one of them had to be named for a+ # scheme it did not carry, and it is the pair (repo, scheme) that names the file.+ fam = detect_video_family("MiniMaxAI/MiniMax-H3")+ repos = {s: video_family_prequant_repo(fam, s) for s in ("int8", "fp8")}+ assert repos["int8"] == repos["fp8"], repos+++# ── repo-root naming ─────────────────────────────────────────────────────────────+ "scheme, expected",+ [("int8", "MiniMax-H3-INT8.pt"), ("fp8", "MiniMax-H3-FP8.pt")],+)+def test_h3_resolves_the_primary_name_at_the_repo_root(scheme, expected):+ # The name the hosted repo actually publishes. It has to be the PRIMARY, not the fallback:+ # cached_checkpoint_path deliberately credits only the primary, so landing on the fallback+ # would report a cached checkpoint as "this would have to download" and hand the pick to GGUF.+ fam = detect_video_family("MiniMaxAI/MiniMax-H3")+ src = resolve_prequant_source(fam, scheme)+ assert src.filename == expected+ # Root-level: no directory component at all, on any platform.+ assert "/" not in src.filename and "\\" not in src.filename+++def test_the_h3_primary_name_is_what_memory_planning_credits():+ # The under-crediting bug in full: seed the cache under the primary name and+ # cached_checkpoint_path must find it. A nested (or otherwise non-primary) name would not.+ fam = detect_video_family("MiniMaxAI/MiniMax-H3")+ src = resolve_prequant_source(fam, "int8")+ seen = {}++ def _fake_try_to_load_from_cache(+ repo_id,+ filename,+ cache_dir = None,+ ):+ seen["filename"] = filename+ return "/cache/blobs/h3" if filename == "MiniMax-H3-INT8.pt" else None++ import huggingface_hub+ import os++ real_hub = huggingface_hub.try_to_load_from_cache+ real_isfile = os.path.isfile+ huggingface_hub.try_to_load_from_cache = _fake_try_to_load_from_cache+ os.path.isfile = lambda p: p == "/cache/blobs/h3" or real_isfile(p)+ try:+ assert cached_checkpoint_path(src) == "/cache/blobs/h3"+ finally:+ huggingface_hub.try_to_load_from_cache = real_hub+ os.path.isfile = real_isfile+ assert seen["filename"] == "MiniMax-H3-INT8.pt"+++def test_the_names_are_built_from_the_repo_and_the_scheme():+ # One repo serves both schemes, so the -FP8 suffix on the repo must be stripped and REPLACED by+ # the requested scheme rather than carried through.+ fam = _fam(prequant_repos = (("int8", "unsloth/Test-FP8"), ("fp8", "unsloth/Test-FP8")))+ assert resolve_prequant_source(fam, "int8").filename == "Test-INT8.pt"+ assert resolve_prequant_source(fam, "fp8").filename == "Test-FP8.pt"+ # The legacy per-scheme name stays available for repos that have not been renamed.+ assert resolve_prequant_source(fam, "int8").fallback_filename == "transformer_int8.pt"+++# ── validate_load_request: refuse BEFORE the download ────────────────────────────+def test_a_modular_family_refuses_a_single_file_load_before_anything_downloads():+ # Previously this reached the loader only after ~98.7 GB had downloaded AND after the resident+ # pipeline had been evicted to make room for it.+ backend = VideoBackend()+ with pytest.raises(ValueError) as excinfo:+ backend.validate_load_request(+ "MiniMaxAI/MiniMax-H3",+ gguf_filename = "minimax_h3_fl2va_pruned_int8_rowwise.safetensors",+ model_kind = "single_file",+ )+ message = str(excinfo.value)+ # The refusal is only useful if it says what to pick instead.+ assert "MiniMaxAI/MiniMax-H3" in message+ assert "unsloth/MiniMax-H3-GGUF" in message+++def test_an_unavailable_transformer_quant_is_refused_with_the_workable_schemes():+ backend = VideoBackend()+ with pytest.raises(ValueError) as excinfo:+ backend.validate_load_request("MiniMaxAI/MiniMax-H3", transformer_quant = "nvfp4")+ message = str(excinfo.value)+ assert "nvfp4" in message+ # Naming the schemes that DO work is the whole point: a bare refusal leaves the user guessing.+ assert "int8" in message and "fp8" in message++[email protected]("scheme", ["int8", "fp8"])+def test_a_scheme_with_a_hosted_checkpoint_is_not_refused(scheme):+ # The mirror image of the test above: the refusal must not swallow the picks it exists to enable.+ backend = VideoBackend()+ try:+ backend.validate_load_request("MiniMaxAI/MiniMax-H3", transformer_quant = scheme)+ except ValueError as exc: # pragma: no cover - only on a regression+ pytest.fail(f"{scheme} should be loadable but was refused: {exc}")+ except Exception:+ # Anything past the quant check (a diffusers import probe in a skewed env) is not this+ # test's business; reaching it already proves the refusal did not fire.+ pass+++def test_auto_is_never_refused():+ # "auto" asks the backend to choose, not for a specific scheme, so it stays on the released+ # components rather than being rejected as unavailable.+ backend = VideoBackend()+ try:+ backend.validate_load_request("MiniMaxAI/MiniMax-H3", transformer_quant = "auto")+ except ValueError as exc: # pragma: no cover - only on a regression+ pytest.fail(f"auto should never be refused: {exc}")+ except Exception:+ pass+++def test_the_refusals_run_before_the_diffusers_availability_probe():+ # Placement matters: the probe below imports diffusers, and on an environment where that raises+ # the user would get an unrelated error instead of the actionable refusal. Asserting the+ # message identifies the refusal proves it ran first.+ backend = VideoBackend()+ with pytest.raises(ValueError, match = "cannot load from a single .safetensors checkpoint"):+ backend.validate_load_request(+ "MiniMaxAI/MiniMax-H3",+ gguf_filename = "anything.safetensors",+ model_kind = "single_file",+ )+++def test_a_non_modular_video_family_is_unaffected():+ # LTX-2.3 legitimately loads a single-file DiT; the new refusal must be scoped to modular+ # workflows or it would break the artifact the picker routes to by default. Asserted on the+ # MESSAGE rather than on success: the diffusers availability probe further down is not+ # importable in every environment, and that unrelated failure must not mask a real regression+ # here (nor make this test pass for the wrong reason).+ backend = VideoBackend()+ try:+ fam = backend.validate_load_request(+ "Lightricks/LTX-2.3",+ gguf_filename = "ltx-2.3-22b-distilled.safetensors",+ model_kind = "single_file",+ )+ except ValueError as exc:+ pytest.fail(f"a single-file LTX-2.3 load must not be refused: {exc}")+ except RuntimeError:+ # Reaching the diffusers probe already proves the modular refusal did not fire.+ return+ # "ltx-2.3" is how the repo spells it; the family's canonical name is "ltx-2" and carries the+ # repo spelling as an alias. Pin the resolved family, not the alias that reached it.+ assert fam.name == "ltx-2" and "ltx-2.3" in fam.aliases+ assert fam.modular_workflow is None+++# ── keeping the pre-quantized denoiser out of the offload rotation ───────────────+#+# ComponentsManager.enable_auto_cpu_offload parks every component on the CPU and moves each one+# onto the accelerator inside its own pre_forward, i.e. from within the block already executing.+# A torchao pre-quantized denoiser does not survive that mid-block move: the device change reaches+# return_and_correct_aliasing, which tries to alias a CPU storage to an accelerator tensor and+# raises "Attempted to set the storage of a tensor on device cuda:0 to a storage on different+# device cpu", killing MiniMax-H3's denoise loop on its first step. Placing it once at load time+# and unhooking it is the fix, so both halves are asserted: hook removed AND module placed.+++class _FakeInnerHook:+ def __init__(self) -> None:+ self.other_hooks: list = []+++class _FakeUserHook:+ def __init__(self, model) -> None:+ self.model = model+ self.hook = _FakeInnerHook()+ self.removed = False++ def remove(self) -> None:+ self.removed = True+++class _FakeModule:+ def __init__(self) -> None:+ self.moved_to: list = []++ def to(self, device):+ self.moved_to.append(device)+ return self+++class _FakeOffloadManager:+ def __init__(self, models) -> None:+ self.model_hooks = [_FakeUserHook(model) for model in models]+ for hook in self.model_hooks:+ hook.hook.other_hooks = [other for other in self.model_hooks if other is not hook]+++def test_pinning_unhooks_the_denoiser_and_places_it():+ from core.inference.diffusion_prequant import pin_prequantized_module++ transformer, encoder, vae = _FakeModule(), _FakeModule(), _FakeModule()+ manager = _FakeOffloadManager([transformer, encoder, vae])+ denoiser_hook = manager.model_hooks[0]++ assert pin_prequantized_module(manager, transformer, "cuda") is True++ # The hook is gone, so nothing moves the denoiser per forward ...+ assert denoiser_hook.removed is True+ assert denoiser_hook not in manager.model_hooks+ assert [hook.model for hook in manager.model_hooks] == [encoder, vae]+ # ... and no surviving component can pick it as the thing to evict, which would strand it on+ # the CPU with no hook left to bring it back.+ for hook in manager.model_hooks:+ assert denoiser_hook not in hook.hook.other_hooks+ # It is placed exactly once, here, outside any executing block.+ assert transformer.moved_to == ["cuda"]+ # The components that CAN be moved safely keep their hooks and their rotation.+ assert encoder.moved_to == [] and vae.moved_to == []+++def test_pinning_still_places_the_module_when_the_manager_is_unrecognisable():+ """Best-effort on the hook surgery: an unmanaged module must still end up on the device."""+ from core.inference.diffusion_prequant import pin_prequantized_module++ transformer = _FakeModule()+ manager = _FakeOffloadManager([_FakeModule()])+ before = list(manager.model_hooks)++ assert pin_prequantized_module(manager, transformer, "cuda") is False+ assert transformer.moved_to == ["cuda"]+ assert manager.model_hooks == beforediff --git a/studio/backend/tests/test_video_routes.py b/studio/backend/tests/test_video_routes.pyindex c02c7157fa3..f3dbd086284 100644--- a/studio/backend/tests/test_video_routes.py+++ b/studio/backend/tests/test_video_routes.py@@ -86,7 +86,19 @@ class _FakeBackend(video_module.VideoBackend):@loaded.setterdef loaded(self, value: bool) -> None:- self._state = object() if value else None+ # Minimal committed state required by inherited generation validation.+ import types++ from core.inference.video_families import detect_video_family+ self._state = (+ types.SimpleNamespace(+ family = detect_video_family("Lightricks/LTX-2"),+ h3_task = None,+ engine = "diffusers",+ )+ if value+ else None+ )def loading_repo_ids(self) -> tuple:return tuple(self.loading)@@ -101,6 +113,7 @@ class _FakeBackend(video_module.VideoBackend):model_kind = None,transformer_quant = None,text_encoder_quant = None,+ h3_task = None,):# Mirror the real backend cheap validation so the route validate-before-evict ordering is exercised.from pathlib import Path@@ -170,6 +183,10 @@ class _FakeBackend(video_module.VideoBackend):"fps": kwargs.get("fps") or 24,"duration_s": 5.0,"has_audio": True,+ # Include every field persisted to the gallery sidecar.+ "conditioning": "t2va",+ "flow_shift": None,+ "audio_flow_shift": None,"steps": kwargs.get("steps") or 40,"guidance": 4.0 if kwargs.get("guidance") is None else kwargs.get("guidance"),}@@ -926,6 +943,58 @@ def test_delete_guard_protects_the_loaded_video_companion_base(monkeypatch):assert deletion._video_blocks_delete("unsloth/something-else") is None+def test_delete_guard_protects_the_native_video_companion_repos(monkeypatch):+ # The native H3 runtime re-reads its Qwen encoder and both VAEs from companion repos that are+ # neither repo_id nor the BF16 base_repo the status publishes, so the guard needs loaded_repo_ids().+ from hub.services.models import deletion++ class _Backend:+ def status(self):+ return {+ "loaded": True,+ "repo_id": "unsloth/MiniMax-H3-GGUF",+ "base_repo": "MiniMaxAI/MiniMax-H3",+ }++ def loaded_repo_ids(self):+ return ("unsloth/MiniMax-H3-GGUF", "Comfy-Org/MiniMax-H3")++ def loading_repo_ids(self):+ return ()++ monkeypatch.setattr(video_module, "get_video_backend", lambda: _Backend())+ assert deletion._video_blocks_delete("Comfy-Org/MiniMax-H3") is not None+ assert deletion._video_blocks_delete("unsloth/something-else") is None+++def test_delete_guard_protects_the_native_video_companion_repos_mid_load(monkeypatch):+ # The in-flight twin of the check above: during an H3 load status()["loaded"] is still False,+ # yet the download is pulling from the same companion repos, so deleting one would yank blobs+ # out from under it. loading_repo_ids() reported only repo_id and base_repo.+ from hub.services.models import deletion++ class _Backend:+ def status(self):+ return {"loaded": False, "repo_id": None, "base_repo": None}++ def loaded_repo_ids(self):+ return ()++ def loading_repo_ids(self):+ return (+ "leejet/MiniMax-H3-GGUF",+ "MiniMaxAI/MiniMax-H3",+ "unsloth/MiniMax-H3-GGUF",+ "Comfy-Org/MiniMax-H3",+ )++ monkeypatch.setattr(video_module, "get_video_backend", lambda: _Backend())+ assert deletion._video_blocks_delete("Comfy-Org/MiniMax-H3") is not None+ # Loading from the leejet mirror still pulls the Qwen encoder from the unsloth GGUF companion.+ assert deletion._video_blocks_delete("unsloth/MiniMax-H3-GGUF") is not None+ assert deletion._video_blocks_delete("unsloth/something-else") is None++def test_video_download_plan_forwards_the_encoder_policy(client, monkeypatch):# The plan drives the staged download, so it must use the encoder policy the load will run with: an fp8 request takes a hosted pre-cast encoder, and staging the dense one pulls ~49 GB of Gemma3.# Same host-independence as the load twin: the plan now makes the precision check too, so@@ -1101,6 +1170,104 @@ def test_signed_url_mint_is_bearer_gated_and_404s_for_an_unknown_clip(client):assert client.get("/api/inference/video/gallery/does-not-exist/signed-url").status_code == 404+def test_video_download_plan_forwards_the_denoiser_policy(client, monkeypatch):+ # Same rule as the encoder policy above, for the denoiser: with a hosted pre-quantized+ # checkpoint the plan must drop the dense transformer shards, and without this forwarding it+ # stages ~66 GB the load then never opens.+ backend = video_module.get_video_backend()+ seen: dict = {}++ def _plan(model_path, **kwargs):+ seen["model_path"] = model_path+ seen.update(kwargs)+ return {"entries": [], "total_bytes": 0}++ monkeypatch.setattr(backend, "download_plan", _plan, raising = False)+ # What is under test is the ROUTE forwarding the denoiser policy into download_plan, not the+ # precision gate that now runs ahead of it. That gate has its own tests and it refuses an+ # explicit scheme on a gguf pick before download_plan is ever reached, so stub it out here and+ # keep this test on the forwarding.+ monkeypatch.setattr(+ video_module, "assert_video_precision_available", lambda fam, **kw: None, raising = False+ )++ resp = client.post(+ "/api/inference/video/download-plan",+ json = {+ "model_path": "unsloth/LTX-2.3-GGUF",+ "gguf_filename": "distilled/ltx-2.3-22b-distilled-Q4_K_M.gguf",+ "model_kind": "gguf",+ "transformer_quant": "int8",+ },+ )++ assert resp.status_code == 200+ assert seen["transformer_quant"] == "int8"+++def test_video_download_plan_refuses_an_unsupported_combination_before_staging(client, monkeypatch):+ # The whole point of moving the refusal into validation: this pick used to return a 200 plan,+ # stage ~98.7 GB, and only then fail inside the loader. Runs the REAL validation rather than+ # the fake backend's mirror of it, since the rule under test lives in the real one.+ backend = video_module.get_video_backend()+ monkeypatch.setattr(+ backend,+ "validate_load_request",+ video_module.VideoBackend.validate_load_request.__get__(backend),+ raising = False,+ )++ def _plan(model_path, **kwargs): # pragma: no cover - reaching this IS the regression+ raise AssertionError("download_plan must not be reached for a refused pick")++ monkeypatch.setattr(backend, "download_plan", _plan, raising = False)++ resp = client.post(+ "/api/inference/video/download-plan",+ json = {+ "model_path": "MiniMaxAI/MiniMax-H3",+ "gguf_filename": "minimax_h3_fl2va_pruned_int8_rowwise.safetensors",+ "model_kind": "single_file",+ },+ )++ assert resp.status_code == 400+ detail = resp.json()["detail"]+ # A refusal that does not name the alternative just moves the dead end earlier.+ assert "MiniMaxAI/MiniMax-H3" in detail+ assert "unsloth/MiniMax-H3-GGUF" in detail+++def test_video_download_plan_refuses_an_unavailable_transformer_quant(client, monkeypatch):+ # And the quant-keyed refusal has to fire on THIS route too, which needs the route to forward+ # transformer_quant into validation: it is the route that stages the download.+ backend = video_module.get_video_backend()+ monkeypatch.setattr(+ backend,+ "validate_load_request",+ video_module.VideoBackend.validate_load_request.__get__(backend),+ raising = False,+ )+ monkeypatch.setattr(+ backend,+ "download_plan",+ lambda *a, **k: (_ for _ in ()).throw(AssertionError("must not be reached")),+ raising = False,+ )++ resp = client.post(+ "/api/inference/video/download-plan",+ json = {+ "model_path": "MiniMaxAI/MiniMax-H3",+ "model_kind": "pipeline",+ "transformer_quant": "nvfp4",+ },+ )++ assert resp.status_code == 400+ assert "nvfp4" in resp.json()["detail"]++def test_the_training_guard_runs_before_the_precision_probe(client, monkeypatch):# The precision gate's support check quantises a real Linear on the GPU and synchronises, so# running it first initialises a CUDA context and allocates next to the training subprocessdiff --git a/studio/backend/tests/test_video_shape_validation.py b/studio/backend/tests/test_video_shape_validation.pyindex 3af3bdc24e3..3e291b216d6 100644--- a/studio/backend/tests/test_video_shape_validation.py+++ b/studio/backend/tests/test_video_shape_validation.py@@ -40,6 +40,7 @@ from core.inference.video_families import (snap_video_size,validate_video_request_shape,)+from core.inference.video_minimax_h3 import h3_conditioning_modefrom routes.video import router as video_router# LTX-2 is the reference family for the single-family cases: 4 presets and frame_step 8.@@ -127,6 +128,39 @@ def test_wan_lattice_is_step_4_not_step_8():validate_video_request_shape(LTX2, num_frames = 85)+def test_the_lattice_reads_frame_offset_not_a_hardcoded_one():+ """MiniMax-H3's lattice is 17k + 5, not 17k + 1. A gate written against k*step+1+ refuses every count H3's own duration select offers, its default of 124 included,+ so the offset has to come from the family the way snap_num_frames reads it."""+ h3 = detect_video_family("MiniMaxAI/MiniMax-H3")+ assert (h3.frame_step, h3.frame_offset) == (17, 5)+ # The three durations the interface offers (5s / 10s / 14.4s at 24 fps, snapped up).+ for count in (124, 243, 345):+ assert (count - h3.frame_offset) % h3.frame_step == 0+ validate_video_request_shape(h3, num_frames = count)+ # A count on the WRONG offset (17k + 1) is what the old rule would have accepted.+ with pytest.raises(ValueError) as excinfo:+ validate_video_request_shape(h3, num_frames = 137)+ message = str(excinfo.value)+ assert "k * 17 + 5" in message+ assert "124" in message and "141" in message+++def test_a_suggested_count_never_falls_outside_the_family_range():+ """Naming a lattice point the family cannot load is the same dead end as naming one+ past the request ceiling. H3 starts at 124, so 90 (a real 17k+5 point) is not an answer."""+ h3 = detect_video_family("MiniMaxAI/MiniMax-H3")+ with pytest.raises(ValueError) as excinfo:+ validate_video_request_shape(h3, num_frames = 100)+ message = str(excinfo.value)+ assert "90" not in message+ assert "124" in message+ # Above the family ceiling of 345 there is nothing to suggest, so name the range.+ with pytest.raises(ValueError) as excinfo:+ validate_video_request_shape(h3, num_frames = 400)+ assert "supported counts run from 124 to 345" in str(excinfo.value)++def test_omitted_fields_are_always_valid():"""None means "use the family default", which is valid by construction."""validate_video_request_shape(LTX2)@@ -223,6 +257,14 @@ class _ShapeFakeBackend(video_module.VideoBackend):"has_audio": fam.has_audio,"steps": int(kwargs.get("steps") or fam.default_steps),"guidance": fam.default_guidance,+ # The real generate() records how the clip was conditioned and the job's persist step+ # reads it unconditionally, so the stub has to speak the same contract or every route+ # case here dies in persist with a KeyError instead of exercising the gate. Derived+ # from the shared helper rather than a literal, so a new conditioning mode cannot+ # leave this stub quietly returning a spelling the gallery no longer accepts.+ "conditioning": h3_conditioning_mode(),+ "flow_shift": kwargs.get("flow_shift"),+ "audio_flow_shift": kwargs.get("audio_flow_shift"),}@@ -394,3 +436,55 @@ def test_a_family_swap_cannot_slip_between_the_check_and_the_job(backend):with pytest.raises(ValueError):backend.begin_generate(prompt = "a cat", width = 704, height = 1216)assert not backend._generate_job_active, "a refused shape must not reserve the job slot"+++# ── the half-specified canvas, with and without a keyframe ────────────────────+++def _tiny_png_b64() -> str:+ """A 2x1 PNG, enough for the keyframe branch of the request model."""+ import base64+ import io++ from PIL import Image++ buf = io.BytesIO()+ Image.new("RGB", (2, 1), (255, 0, 0)).save(buf, format = "PNG")+ return base64.b64encode(buf.getvalue()).decode()++[email protected]("axes", [{"width": 768}, {"height": 512}])+def test_a_half_specified_canvas_stays_valid_without_a_keyframe(axes):+ """The regression this pins: the paired-axes rule was written for the keyframe canvas but+ ran as an unconditional request validator, so every existing LTX / Wan / Hunyuan /+ prompt-only H3 client that sends one axis started getting a 422. The backend deliberately+ resolves the missing axis from the family's default preset (validate_video_request_shape+ documents it, and _resolve_keyframes implements it), so these calls must still be accepted.+ """+ from models.inference import VideoGenerateRequest++ req = VideoGenerateRequest(prompt = "a cat", **axes)+ assert (req.width, req.height) == (axes.get("width"), axes.get("height"))++[email protected]("axes", [{"width": 768}, {"height": 512}])+def test_a_half_specified_canvas_is_refused_with_a_keyframe(axes):+ """The rule still has to hold where it means something: with a keyframe present+ _resolve_keyframes matches the SOURCE aspect whenever either axis is missing, so the axis+ the caller did send would be silently discarded. Refuse rather than draw another recipe."""+ import pydantic+ from models.inference import VideoGenerateRequest++ with pytest.raises(pydantic.ValidationError, match = "sent together"):+ VideoGenerateRequest(prompt = "a cat", first_frame = _tiny_png_b64(), **axes)+++def test_both_axes_and_neither_stay_valid_with_a_keyframe():+ """The two shapes the rule exists to allow: an explicit canvas, and "match source"."""+ from models.inference import VideoGenerateRequest++ frame = _tiny_png_b64()+ assert (+ VideoGenerateRequest(prompt = "a cat", first_frame = frame, width = 768, height = 512).width == 768+ )+ assert VideoGenerateRequest(prompt = "a cat", first_frame = frame).width is Nonediff --git a/studio/backend/utils/mlx_repair.py b/studio/backend/utils/mlx_repair.pyindex 78890bd308c..1716cfad59f 100644--- a/studio/backend/utils/mlx_repair.py+++ b/studio/backend/utils/mlx_repair.py@@ -286,8 +286,8 @@ def _mlx_install_env() -> dict[str, str]:Unsloth secrets or be steered to a hostile index.Mirror the main installer (install_python_stack.py) by pointing UV_OVERRIDE at- overrides-darwin-arm64.txt, which relaxes mlx-vlm/mlx-lm's transformers>=5- requirement to >=4.57.6. Without it, uv keeps the Unsloth transformers pin only+ overrides-darwin-arm64.txt, which keeps mlx-vlm/mlx-lm on the Studio+ Transformers floor. Without it, uv keeps the Unsloth transformers pin onlyby silently backtracking mlx-vlm to an old, unsupported version (uv honoursUV_OVERRIDE; plain pip ignores it, so the transformers constraint below is thepip-path safety net). We set UV_OVERRIDE ourselves, so a poisoned one in the@@ -325,7 +325,7 @@ def _transformers_constraint_args() -> tuple[list[str], str | None]:"""Pin transformers to the running version for the mlx install.The install must never upgrade transformers underneath a running Unsloth- (the single-env install pins transformers==4.57.6). With UV_OVERRIDE set this+ (the single-env install pins a compatible default). With UV_OVERRIDE set thisis belt-and-suspenders; on the plain-pip path (no UV_OVERRIDE support) it isthe actual guard -- the resolver either finds an mlx build compatible with thepin or fails, leaving us chat-only rather than breaking Unsloth. Returnsdiff --git a/studio/backend/utils/transformers_version.py b/studio/backend/utils/transformers_version.pyindex 5b413f7cbd4..fd108a61a54 100644--- a/studio/backend/utils/transformers_version.py+++ b/studio/backend/utils/transformers_version.py@@ -360,7 +360,7 @@ _probe_tier_cache: dict[str, str] = {}TRANSFORMERS_510_VERSION = "5.10.2"TRANSFORMERS_550_VERSION = "5.5.0"TRANSFORMERS_530_VERSION = "5.3.0"-TRANSFORMERS_DEFAULT_VERSION = "4.57.6"+TRANSFORMERS_DEFAULT_VERSION = "5.5.0" if sys.version_info >= (3, 10) else "4.57.6"# Backwards-compat alias for the highest 5.x tier; prefer TRANSFORMERS_510_VERSION /# TRANSFORMERS_550_VERSION / TRANSFORMERS_530_VERSION.TRANSFORMERS_5_VERSION = TRANSFORMERS_510_VERSIONdiff --git a/studio/frontend/src/components/image-dropzone.tsx b/studio/frontend/src/components/image-dropzone.tsxnew file mode 100644index 00000000000..f01507457d2--- /dev/null+++ b/studio/frontend/src/components/image-dropzone.tsx@@ -0,0 +1,109 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import { useCallback, useRef, useState } from "react";+import { Delete02Icon, ImageAdd02Icon } from "@hugeicons/core-free-icons";+import { HugeiconsIcon } from "@hugeicons/react";++import { Button } from "@/components/ui/button";+import {+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from "@/components/ui/tooltip";+import { cn } from "@/lib/utils";+import { toast } from "@/lib/toast";++/** Shared image picker that returns a data URL. */+export function ImageDropzone({+ value,+ onChange,+ label = "Click or drop an image",+ removeLabel = "Remove source image",+ className,+}: {+ value: string | null;+ onChange: (dataUrl: string | null) => void;+ /** Prompt shown in the empty state. */+ label?: string;+ /** Accessible remove-button name. */+ removeLabel?: string;+ className?: string;+}) {+ const inputRef = useRef<HTMLInputElement | null>(null);+ const [dragging, setDragging] = useState(false);++ const readFile = useCallback(+ (file: File | undefined | null) => {+ if (!file || !file.type.startsWith("image/")) {+ if (file) toast.error("Please choose an image file");+ return;+ }+ const reader = new FileReader();+ reader.onload = () => onChange(typeof reader.result === "string" ? reader.result : null);+ reader.onerror = () => toast.error("Could not read the image");+ reader.readAsDataURL(file);+ },+ [onChange],+ );++ if (value) {+ return (+ <div className={cn("relative overflow-hidden rounded-[10px] border border-border", className)}>+ <img src={value} alt="Source" className="max-h-44 w-full object-contain bg-muted/30" />+ <Tooltip>+ <TooltipTrigger asChild={true}>+ <Button+ type="button"+ variant="secondary"+ size="icon"+ aria-label={removeLabel}+ className="absolute right-1.5 top-1.5 size-7"+ onClick={() => {+ onChange(null);+ if (inputRef.current) inputRef.current.value = "";+ }}+ >+ <HugeiconsIcon icon={Delete02Icon} className="size-3.5" />+ </Button>+ </TooltipTrigger>+ <TooltipContent>Remove</TooltipContent>+ </Tooltip>+ </div>+ );+ }++ return (+ <button+ type="button"+ onClick={() => inputRef.current?.click()}+ onDragOver={(e) => {+ e.preventDefault();+ setDragging(true);+ }}+ onDragLeave={() => setDragging(false)}+ onDrop={(e) => {+ e.preventDefault();+ setDragging(false);+ readFile(e.dataTransfer.files?.[0]);+ }}+ className={cn(+ "flex h-28 w-full flex-col items-center justify-center gap-1 rounded-xl border border-dashed text-xs transition-colors",+ dragging+ ? "border-primary/60 bg-primary/5 text-foreground"+ : "border-border text-muted-foreground hover:border-foreground/30 hover:text-foreground",+ className,+ )}+ >+ <HugeiconsIcon icon={ImageAdd02Icon} className="size-5" />+ <span>{label}</span>+ <input+ ref={inputRef}+ type="file"+ accept="image/*"+ className="hidden"+ onChange={(e) => readFile(e.target.files?.[0])}+ />+ </button>+ );+}diff --git a/studio/frontend/src/features/images/images-page.tsx b/studio/frontend/src/features/images/images-page.tsxindex 675d8c73f60..94c53a9121b 100644--- a/studio/frontend/src/features/images/images-page.tsx+++ b/studio/frontend/src/features/images/images-page.tsx@@ -17,6 +17,7 @@ import {import { HugeiconsIcon, type IconSvgElement } from "@hugeicons/react";import { TestTubeOutlineIcon } from "@/lib/hugeicons-derived";+import { ImageDropzone } from "@/components/image-dropzone";import { Button } from "@/components/ui/button";import {DropdownMenu,@@ -652,91 +653,6 @@ function AdvancedSelect({);}-// Source-image picker for Transform (img2img): click or drag-drop an image, read it to a data URL sent as init_image.-function ImageDropzone({- value,- onChange,-}: {- value: string | null;- onChange: (dataUrl: string | null) => void;-}) {- const inputRef = useRef<HTMLInputElement | null>(null);- const [dragging, setDragging] = useState(false);-- const readFile = useCallback(- (file: File | undefined | null) => {- if (!file || !file.type.startsWith("image/")) {- if (file) toast.error("Please choose an image file");- return;- }- const reader = new FileReader();- reader.onload = () => onChange(typeof reader.result === "string" ? reader.result : null);- reader.onerror = () => toast.error("Could not read the image");- reader.readAsDataURL(file);- },- [onChange],- );-- if (value) {- return (- <div className="relative overflow-hidden rounded-[10px] border border-border">- <img src={value} alt="Source" className="max-h-44 w-full object-contain bg-muted/30" />- <Tooltip>- <TooltipTrigger asChild={true}>- <Button- type="button"- variant="secondary"- size="icon"- aria-label="Remove source image"- className="absolute right-1.5 top-1.5 size-7"- onClick={() => {- onChange(null);- if (inputRef.current) inputRef.current.value = "";- }}- >- <HugeiconsIcon icon={Delete02Icon} className="size-3.5" />- </Button>- </TooltipTrigger>- <TooltipContent>Remove</TooltipContent>- </Tooltip>- </div>- );- }-- return (- <button- type="button"- onClick={() => inputRef.current?.click()}- onDragOver={(e) => {- e.preventDefault();- setDragging(true);- }}- onDragLeave={() => setDragging(false)}- onDrop={(e) => {- e.preventDefault();- setDragging(false);- readFile(e.dataTransfer.files?.[0]);- }}- className={cn(- "flex h-28 w-full flex-col items-center justify-center gap-1 rounded-xl border border-dashed text-xs transition-colors",- dragging- ? "border-primary/60 bg-primary/5 text-foreground"- : "border-border text-muted-foreground hover:border-foreground/30 hover:text-foreground",- )}- >- <HugeiconsIcon icon={ImageAdd02Icon} className="size-5" />- <span>Click or drop an image</span>- <input- ref={inputRef}- type="file"- accept="image/*"- className="hidden"- onChange={(e) => readFile(e.target.files?.[0])}- />- </button>- );-}-// A brush-based mask editor for inpainting: the source image with a paintable overlay, exporting a grayscale PNG mask at// the image's NATIVE resolution (white = repaint). `brushPct` sizes the brush as a fraction of the shorter side.function MaskCanvas({diff --git a/studio/frontend/src/features/model-picker/components/model-selector/model-catalog.check.ts b/studio/frontend/src/features/model-picker/components/model-selector/model-catalog.check.tsindex 165b7be6980..9abaebc7a27 100644--- a/studio/frontend/src/features/model-picker/components/model-selector/model-catalog.check.ts+++ b/studio/frontend/src/features/model-picker/components/model-selector/model-catalog.check.ts@@ -425,6 +425,35 @@ assert.equal("BF16 - 480p",);+// MiniMax-H3 uses measured component-offload tiers instead of the resident 70% rule.+const h3 = groupForRepoId("MiniMaxAI/MiniMax-H3", VIDEO_CATALOG);+assert.ok(h3);+assert.equal(+ pickDefaultArtifact(h3, { gpuGb: 48, systemRamGb: 256, isDownloaded: notDownloaded })+ .format,+ "gguf",+);+assert.equal(+ pickDefaultArtifact(h3, { gpuGb: 80, systemRamGb: 128, isDownloaded: notDownloaded })+ .format,+ "gguf",+);+assert.equal(+ pickDefaultArtifact(h3, { gpuGb: 80, systemRamGb: 192, isDownloaded: notDownloaded })+ .format,+ "bf16",+);+assert.equal(+ pickDefaultArtifact(h3, { gpuGb: 122, systemRamGb: 96, isDownloaded: notDownloaded })+ .format,+ "gguf",+);+assert.equal(+ pickDefaultArtifact(h3, { gpuGb: 123, systemRamGb: 96, isDownloaded: notDownloaded })+ .format,+ "bf16",+);+// ── official BF16 artifacts (added so groups are not unsloth-quant-only) ────────// Qwen-Image-2512 BF16 (54 GB) misses a 24/48 GB budget (bnb-4bit/fp8 win there, asserted above) but on an 80 GB GPU (budget 56) it fits and wins.assert.equal(diff --git a/studio/frontend/src/features/model-picker/components/model-selector/model-catalog.ts b/studio/frontend/src/features/model-picker/components/model-selector/model-catalog.tsindex 9dd9946a660..e459a8fb3c9 100644--- a/studio/frontend/src/features/model-picker/components/model-selector/model-catalog.ts+++ b/studio/frontend/src/features/model-picker/components/model-selector/model-catalog.ts@@ -4,6 +4,7 @@// One canonical name per diffusion model, its published artifacts (GGUF quants, prequant FP8 / bnb-4bit repos, official BF16 pipelines), and a deterministic router picking the best artifact for the device.// Pure helpers, no React/DOM deps. See model-catalog.check.ts (`npm run catalog:check`).+import type { ModelCapabilities } from "./model-capabilities";import type { ModelOption } from "./types";export type ArtifactFormat = "gguf" | "fp8" | "bnb-4bit" | "bf16";@@ -20,8 +21,17 @@ export interface ModelArtifact {label: string;/** Curated resident-size estimate for routing. Omitted = unknown: never auto-picked unless downloaded. GGUF omits it too, since its quant ladder self-fits via pickDefaultQuant. */approxSizeGb?: number;+ /** Measured CPU-offload fit tiers. Any tier whose GPU and available-RAM floors+ * are both met can auto-route this artifact without applying the resident 70% rule. */+ offloadFitTiers?: readonly { gpuGb: number; systemRamGb: number }[];/** Extra search tokens beyond the id/label ("4bit", "nf4", ...). */keywords?: readonly string[];+ /** Parameter count of THIS artifact's checkpoint, for the row's size chip.+ * Only a fallback: the Hub listing's own `expand=gguf` total wins wherever it+ * reports one. Rows the listing never returns (a repo it does not index, a+ * non-unsloth owner, one this account cannot see) have no other source, and+ * ids like "MiniMax-H3-GGUF" carry no "<n>B" token to guess from. */+ totalParams?: number;/** Gated on the Hub (license + token). A bare group click skips it when not downloaded and falls through to an open artifact (e.g. the GGUF); an already-downloaded gated artifact is still returned. */gated?: boolean;}@@ -37,6 +47,11 @@ export interface CatalogGroup {artifacts: ModelArtifact[];/** Cross-owner ids that resolve to this group. Suffix stripping never merges two owners on its own. */aliases?: readonly string[];+ /** What the model can do, for the row's capability glyphs. Same fallback rule as+ * `ModelArtifact.totalParams`: the Hub listing's tags win where it returns the row.+ * `detectCapabilities` reads tags then repo-name keywords, and a name like+ * "MiniMax-H3-GGUF" says nothing about the audio track the model actually emits. */+ capabilities?: Partial<ModelCapabilities>;}// ── artifact constructors (keep the data tables terse) ─────────────────────────@@ -322,6 +337,27 @@ export const IMAGE_CATALOG: CatalogGroup[] = [];export const VIDEO_CATALOG: CatalogGroup[] = [+ {+ canonicalId: "MiniMaxAI/MiniMax-H3",+ displayName: "MiniMax H3",+ description: "Text, image and reference to video with synchronized audio",+ scope: "video",+ aliases: ["Comfy-Org/MiniMax-H3"],+ capabilities: { audio: true },+ artifacts: [+ bf16Pipeline("MiniMaxAI/MiniMax-H3", 145, {+ // Cluster measurements at the default 1344x768, 124-frame preset. The+ // lower-GPU tier holds one 66 GB component at a time and keeps the full+ // model in RAM; the higher tier retains more weights on-device.+ offloadFitTiers: [+ { gpuGb: 74, systemRamGb: 140 },+ { gpuGb: 123, systemRamGb: 80 },+ ],+ }),+ // The FL2VA denoiser this repo publishes, summed off its GGUF tensor shapes.+ gguf("unsloth/MiniMax-H3-GGUF", { totalParams: 20_111_438_744 }),+ ],+ },{// The distilled 2.3 release: Lightricks' own bf16/fp8 single-file DiT checkpoints (loaded against the already-trusted LTX-2// base for the VAE / Gemma3 encoder) plus the GGUF quants. The single-file ones keep the ~50 GB encoder in bf16, so consumer GPUs route to GGUF.@@ -335,6 +371,7 @@ export const VIDEO_CATALOG: CatalogGroup[] = [displayName: "LTX 2.3 distilled",description: "Text-to-video with audio",scope: "video",+ capabilities: { audio: true },artifacts: [bf16Single("Lightricks/LTX-2.3",@@ -342,7 +379,8 @@ export const VIDEO_CATALOG: CatalogGroup[] = [90,),// No FP8 artifact: the LTX-2.3 loader refuses the official scaled-FP8 single file (it carries .weight_scale/.input_scale), so a click would start a ~76 GB download that always fails.- gguf("unsloth/LTX-2.3-GGUF"),+ // 21.0B is what the Hub reports for this repo; carrying it keeps the row identical when the listing is unavailable (offline, rate-limited).+ gguf("unsloth/LTX-2.3-GGUF", { totalParams: 21_005_004_544 }),],},{@@ -350,6 +388,7 @@ export const VIDEO_CATALOG: CatalogGroup[] = [displayName: "LTX 2 (base)",description: "Text-to-video with audio",scope: "video",+ capabilities: { audio: true },artifacts: [bf16Pipeline("Lightricks/LTX-2", 90)],},{@@ -516,6 +555,34 @@ export function curatedSizeBytesFor(return gb && gb > 0 ? gb * BYTES_PER_GB : undefined;}+/** Curated parameter count for an exact artifact id, or undefined when the catalog+ * carries none. A FALLBACK for rows the Hub listing does not return: callers must+ * prefer the listing's own total wherever it reports one. */+export function curatedTotalParamsFor(+ repoId: string,+ catalog: CatalogGroup[],+): number | undefined {+ const params = artifactForRepoId(repoId, catalog)?.artifact.totalParams;+ return params && params > 0 ? params : undefined;+}++/** Curated capabilities for any id belonging to a group that declares them, or+ * undefined. Same fallback rule as `curatedTotalParamsFor`: the listing's tags win.+ * Group-level, not artifact-level: every artifact of a model can do what the model+ * can do. */+export function curatedCapabilitiesFor(+ repoId: string,+ catalog: CatalogGroup[],+): ModelCapabilities | undefined {+ const declared = groupForRepoId(repoId, catalog)?.capabilities;+ if (!declared) return undefined;+ return {+ vision: declared.vision ?? false,+ reasoning: declared.reasoning ?? false,+ audio: declared.audio ?? false,+ };+}+/** Back-compat: the flat ModelOption list the ModelSelector `models` prop expects, one option per ARTIFACT. */export function catalogToModelOptions(catalog: CatalogGroup[]): ModelOption[] {const options: ModelOption[] = [];@@ -656,12 +723,17 @@ const FORMAT_QUALITY: Record<ArtifactFormat, number> = {gguf: 3,};-function fitsResident(artifact: ModelArtifact, gpuGb: number): boolean {+function fitsArtifactBudget(artifact: ModelArtifact, budget: DeviceBudget): boolean {+ if (artifact.offloadFitTiers?.length) {+ return artifact.offloadFitTiers.some(+ (tier) => budget.gpuGb >= tier.gpuGb && budget.systemRamGb >= tier.systemRamGb,+ );+ }if (artifact.approxSizeGb === undefined) return false;- return artifact.approxSizeGb <= gpuGb * 0.7;+ return artifact.approxSizeGb <= budget.gpuGb * 0.7;}-/** The artifact a bare group click loads. Ladder: (1) highest-quality DOWNLOADED artifact within the 0.7 * GPU budget, else a downloaded GGUF, else the smallest downloaded; (2) no budget known -> the group GGUF, else the first artifact; (3) best sized artifact that fits, descending quality (BF16, FP8, bnb-4bit), unsized never auto-picked; (4) fallback GGUF, else the smallest. */+/** The artifact a bare group click loads. Sized artifacts normally use the 0.7 * GPU budget; measured offload tiers can override that fit check. */export function pickDefaultArtifact(group: CatalogGroup,input: RoutingInput,@@ -673,7 +745,7 @@ export function pickDefaultArtifact(const downloaded = artifacts.filter((a) => input.isDownloaded(a.repoId));if (downloaded.length > 0) {const fitting = downloaded.find(- (a) => a.format !== "gguf" && fitsResident(a, input.gpuGb),+ (a) => a.format !== "gguf" && fitsArtifactBudget(a, input),);if (fitting) return fitting;const downloadedGguf = downloaded.find((a) => a.format === "gguf");@@ -687,7 +759,7 @@ export function pickDefaultArtifact(}for (const artifact of artifacts) {// Skip a gated, NOT-downloaded artifact: auto-routing there fails the download without license/token access, so fall through to an open one. The downloaded branch above still returns gated artifacts.- if (artifact.format !== "gguf" && !artifact.gated && fitsResident(artifact, input.gpuGb)) {+ if (artifact.format !== "gguf" && !artifact.gated && fitsArtifactBudget(artifact, input)) {return artifact;}}@@ -697,7 +769,7 @@ export function pickDefaultArtifact()[0];}-/** Whether the "fit on device" toggle keeps a group: it stays when one artifact can run here (on disk, a GGUF, or sized within the 0.7*GPU + 0.7*RAM budget), so a bare click on a filtered list cannot start an OOM load. An unknown budget keeps everything. */+/** Whether the "fit on device" toggle keeps a group, including measured offload tiers when an artifact provides them. */export function catalogGroupFitsDevice(group: CatalogGroup,budget: DeviceBudget,@@ -711,6 +783,11 @@ export function catalogGroupFitsDevice(if (isDownloaded(a.repoId)) return true;// A GGUF quant ladder self-fits (llama-server offloads), so it is always a runnable fallback, matching pickDefaultArtifact.if (a.format === "gguf") return true;+ if (a.offloadFitTiers?.length) {+ return a.offloadFitTiers.some(+ (tier) => budget.gpuGb >= tier.gpuGb && budget.systemRamGb >= tier.systemRamGb,+ );+ }return a.approxSizeGb !== undefined && a.approxSizeGb <= budgetGb;});}diff --git a/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx b/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsxindex 857e25da011..b2ad1ac3123 100644--- a/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx+++ b/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx@@ -130,6 +130,7 @@ import {orderRecommendedRows,paramsFromId,searchRowFitsDevice,+ searchableRecommendedIds,} from "./recommended-fit";import {ggufVariantsMatchForPicker,@@ -161,7 +162,9 @@ import type {import {type CatalogGroup,artifactForRepoId,+ curatedCapabilitiesFor,curatedSizeBytesFor,+ curatedTotalParamsFor,} from "./model-catalog";import { describeVariantListingError } from "./variant-listing-error";import {@@ -2402,9 +2405,17 @@ export function HubModelPicker({// most curated ids and wrong for others (Wan2.2-TI2V-5B is 30 GB, not 2),// and non-unsloth ids never get a listing row to correct it.curatedSizeBytes: catalog ? curatedSizeBytesFor(id, catalog) : undefined,+ // Same reason the size is curated: a seed the listing does not return has no+ // other source for its param chip, and most curated ids carry no "<n>B" token.+ totalParams: catalog ? curatedTotalParamsFor(id, catalog) : undefined,}));}, [catalog, models, formatFilter, isKnownGgufRepo, isMac, task]);+ const catalogSeedIds = useMemo(+ () => catalogSeedRows.map((row) => row.id),+ [catalogSeedRows],+ );+// Recommended suggests GGUF anywhere; on Mac also MLX and safetensors. The// "recommended" sort also drops models too big for the device. Already-// downloaded models stay visible (badged), never hidden.@@ -2452,13 +2463,16 @@ export function HubModelPicker({catalog,]);- // Per-row meta + VRAM badge from the recommended listing's own metadata.+ // Per-row meta + VRAM badge from the recommended listing's own metadata, with the+ // curated seeds behind it: a listing row wins wherever there is one, and a curated+ // row the listing never returns still gets its size chip instead of rendering bare.const recommendedMeta = useMemo(() => {const map = new Map<string,{ meta: string | null; status: VramFitStatus | null; est: number }>();- for (const r of recommendedSearch.results) {+ for (const r of [...recommendedSearch.results, ...catalogSeedRows]) {+ if (map.has(r.id)) continue;const isG = isKnownGgufRepo(r.id);// GGUF param count comes from the repo name or the GGUF metadata, so even// repos with no "<n>B" token (Kimi, MiniMax) show a param chip.@@ -2516,10 +2530,18 @@ export function HubModelPicker({map.set(r.id, { meta, status, est });}return map;- }, [recommendedSearch.results, isKnownGgufRepo, gpu, inferenceGpu]);+ }, [+ recommendedSearch.results,+ catalogSeedRows,+ isKnownGgufRepo,+ gpu,+ inferenceGpu,+ ]);- // Tag-accurate capabilities keyed by repo id, pooled from both HF listings.- // Rows look it up by id and fall back to name detection when absent.+ // Tag-accurate capabilities keyed by repo id, pooled from both HF listings, then the+ // catalog for curated ids neither listing returned. Rows look it up by id and fall+ // back to repo-name detection when absent, which cannot see an audio track a name+ // does not mention. Listings first: real tags outrank curated data.const capsById = useMemo(() => {const map = new Map<string, ModelCapabilities>();for (const r of [...results, ...recommendedSearch.results]) {@@ -2533,8 +2555,15 @@ export function HubModelPicker({}),);}+ if (catalog) {+ for (const row of catalogSeedRows) {+ if (map.has(row.id)) continue;+ const curated = curatedCapabilitiesFor(row.id, catalog);+ if (curated) map.set(row.id, curated);+ }+ }return map;- }, [results, recommendedSearch.results]);+ }, [results, recommendedSearch.results, catalog, catalogSeedRows]);// Ordered by the On Device dropdown (recent/download date/size/name). The gate keeps diffusion GGUFs in the Images/Video picker and out of chat.const sortedCachedGguf = useMemo(@@ -2905,7 +2934,14 @@ export function HubModelPicker({searchRowFitsDevice({...row,- totalParams: row.totalParams ?? recommendedParamCountById.get(row.id),+ // Curated params last, same rule as the curated size below: a listing+ // total wins, but a repo no listing returns must still be sizable or+ // `requireKnown` hides it from search while the unfiltered Recommended+ // list, which reads the seed row's own metadata, keeps painting it.+ totalParams:+ row.totalParams ??+ recommendedParamCountById.get(row.id) ??+ (catalog ? curatedTotalParamsFor(row.id, catalog) : undefined),},{isGguf: isKnownGgufRepo(row.id),@@ -2932,7 +2968,10 @@ export function HubModelPicker({if (!showHfSection) return [];const q = normalizeForSearch(debouncedQuery.trim());return (- recommendedIds+ // Seeds included: recommendedIds hides downloaded models, which the unfiltered+ // Recommended list still paints, so without them a curated pick vanishes from+ // search the moment it is on disk unless a Hub listing row happens to carry it.+ searchableRecommendedIds(catalogSeedIds, recommendedIds).filter((id) => normalizeForSearch(id).includes(q)).filter((id) =>matchesFormatFilter(id, isKnownGgufRepo(id), formatFilter),@@ -2949,6 +2988,7 @@ export function HubModelPicker({}, [showHfSection,debouncedQuery,+ catalogSeedIds,recommendedIds,formatFilter,isKnownGgufRepo,@@ -4882,10 +4922,14 @@ export function HubModelPicker({hubUrl={hubRepoUrl(id)}alignMeta="hub"showSize={hubRowsShowSize}+ downloaded={downloadedSet.has(id.toLowerCase())}capabilities={capsById.get(id)}+ // Same meta the unfiltered Recommended row shows, so a+ // model does not lose its size chip just because it was+ // reached by typing its name.meta={isKnownGgufRepo(id)- ? "GGUF"+ ? (recommendedMeta.get(id)?.meta ?? "GGUF"): (vram?.detail ?? extractParamLabel(id))}selected={value === id}diff --git a/studio/frontend/src/features/model-picker/components/model-selector/recommended-fit.ts b/studio/frontend/src/features/model-picker/components/model-selector/recommended-fit.tsindex 177109567ce..7b6c78bc6e1 100644--- a/studio/frontend/src/features/model-picker/components/model-selector/recommended-fit.ts+++ b/studio/frontend/src/features/model-picker/components/model-selector/recommended-fit.ts@@ -222,6 +222,33 @@ export function searchRowFitsDevice<);}+/** The id pool the Recommended SEARCH matches a query against: the curated seeds the+ * unfiltered list paints, then the listing ids, each id once and seeds first (the+ * order `orderRecommendedRows` renders them in).+ *+ * The listing pool drops every id already on disk, because a downloaded model has its+ * own On Device row. The seed pool does not, and the unfiltered Recommended list keeps+ * painting a downloaded curated model (badged "downloaded"), so search has to keep it+ * too. Without this a curated pick disappears from Recommended search the moment it is+ * downloaded, and the only thing that can bring it back is a live Hub listing row --+ * which a repo the listing does not return (new, non-unsloth owner, invisible to this+ * account) never gets. The row then sits in the unfiltered list yet cannot be found by+ * typing its name. */+export function searchableRecommendedIds(+ seedIds: readonly string[],+ listingIds: readonly string[],+): string[] {+ const seen = new Set<string>();+ const out: string[] = [];+ for (const id of [...seedIds, ...listingIds]) {+ const key = id.toLowerCase();+ if (seen.has(key)) continue;+ seen.add(key);+ out.push(id);+ }+ return out;+}+/** Order Recommended: curated seeds first in catalog order, then the rest of the* listing, each id once. A seed hands off only to a row that survived `keep`, so* a painted curated row does not vanish when the listing reports it withdiff --git a/studio/frontend/src/features/video/api.ts b/studio/frontend/src/features/video/api.tsindex 75f11356fcc..2354bfa9d93 100644--- a/studio/frontend/src/features/video/api.ts+++ b/studio/frontend/src/features/video/api.ts@@ -27,12 +27,22 @@ export interface VideoGenerationDefaults {guidance: number;num_frames: number;fps: number;- // Temporal lattice: valid frame counts are k * frame_step + 1.+ // Temporal lattice: valid frame counts are k * frame_step + frame_offset.frame_step: number;+ frame_offset: number;+ duration_presets: number[];// Width/height must be divisible by this.resolution_multiple: number;// (width, height) presets the UI offers, default first.resolution_presets: Array<[number, number]>;+ // Backend-owned keyframe canvas rule, or null when unsupported.+ canvas_short_edge?: number | null;+ canvas_max_pixels?: number | null;+ // Released schedule shifts, or null when unsupported.+ flow_shift?: number | null;+ audio_flow_shift?: number | null;+ // Whether the active engine can apply audio_flow_shift.+ supports_audio_flow_shift?: boolean;}export interface VideoStatus {@@ -44,6 +54,7 @@ export interface VideoStatus {dtype: string | null;// Resolved load kind: "gguf" | "single_file" | "pipeline". Null when not loaded.model_kind?: string | null;+ engine?: "diffusers" | "sd_cpp" | null;// Selected GGUF quant. Newer backends report this separately from the compute dtype.gguf_variant?: string | null;// Resolved offload policy: none | group | model | sequential.@@ -61,6 +72,12 @@ export interface VideoStatus {text_encoder_quant?: string | null;// Whether the loaded family produces a synchronized audio track.has_audio: boolean;+ supports_cfg: boolean;+ // Conditioning supported by the loaded checkpoint.+ supports_keyframes?: boolean;+ supports_references?: boolean;+ // Resident MiniMax-H3 denoiser partition, if any.+ h3_task?: string | null;// Per-family generation defaults + shape constraints; null when unloaded.defaults?: VideoGenerationDefaults | null;// Per-control provenance keyed by control name (memory_mode, speed_mode, attention_backend, transformer_cache), read by@@ -70,7 +87,7 @@ export interface VideoStatus {export interface VideoGenerateProgress {active: boolean;- // "queued" | "denoise" | "export" | "completed" | "failed" | null; the terminal phases carry the background job's outcome.+ // "queued" | "denoise" | "decode" | "export" | "completed" | "failed" | null; the terminal phases carry the background job's outcome.phase?: string | null;step: number;total: number;@@ -118,10 +135,20 @@ export interface VideoLoadRequest {transformer_cache_threshold?: number;// Dense DiT precision on full-pipeline loads (omit for the hardware ladder; "none" pins bf16). GGUF / single-file checkpoints carry their own.transformer_quant?: "none" | "fp8" | "int8" | "nvfp4" | "mxfp8";+ // Pipeline denoiser partition. GGUF filenames already identify theirs.+ h3_task?: "fl2va" | "ref2va";// Text-encoder precision (omit to keep the dense bf16 encoder). Refused with a 409 when the host cannot run it.text_encoder_quant?: "fp8" | "fp8_dynamic" | "int8" | "nvfp4";}+/** One reference video, with the soundtrack MiniMax-H3 conditions on alongside it. */+export interface VideoReferenceVideo {+ // Base64/data-URL video file, 2 to 15 seconds.+ video: string;+ // Base64/data-URL soundtrack for THIS video; omitted takes the one embedded in the file.+ audio?: string;+}+export interface VideoGenerateRequest {prompt: string;negative_prompt?: string;@@ -135,6 +162,18 @@ export interface VideoGenerateRequest {steps?: number;guidance?: number;seed?: number;+ // MiniMax-H3 keyframes as data URLs. Omit both dimensions to match the source aspect.+ first_frame?: string;+ last_frame?: string;+ // Ref2VA references, grouped in the model's image, video, then audio order.+ reference_images?: string[];+ reference_videos?: VideoReferenceVideo[];+ reference_audios?: string[];+ // "max" uses Diffusers' 2048px short-edge policy; "match" uses the clip area.+ reference_image_size?: "match" | "max";+ // Sigma shift of the video schedule, and of the audio one (Diffusers engine only).+ flow_shift?: number;+ audio_flow_shift?: number;}// A persisted clip's full generation recipe (the JSON sidecar of the MP4).@@ -153,6 +192,10 @@ export interface GalleryVideo {guidance: number;seed: number;has_audio: boolean;+ // MiniMax-H3 task name, absent on older clips.+ conditioning?: string | null;+ flow_shift?: number | null;+ audio_flow_shift?: number | null;model?: string | null;// The load-time BUILD, all ENGAGED values, so a clip's recipe still names the precision it ran at// once the model is unloaded. Absent on sidecars written before this existed.diff --git a/studio/frontend/src/features/video/keyframe-canvas.ts b/studio/frontend/src/features/video/keyframe-canvas.tsnew file mode 100644index 00000000000..7d9493a7ade--- /dev/null+++ b/studio/frontend/src/features/video/keyframe-canvas.ts@@ -0,0 +1,35 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import type { VideoGenerationDefaults } from "./api";++/** Sentinel for deriving resolution from the keyframe aspect ratio. */+export const MATCH_SOURCE_RESOLUTION = -1;++/**+ * Preview the backend-owned canvas rule from status defaults.+ * Returns null when the family lacks a rule or the aspect ratio is unsupported.+ */+export function matchedCanvas(+ aspectWidth: number,+ aspectHeight: number,+ defaults: VideoGenerationDefaults | null | undefined,+): [number, number] | null {+ const shortEdge = defaults?.canvas_short_edge;+ const maxPixels = defaults?.canvas_max_pixels;+ const multiple = defaults?.resolution_multiple;+ if (!shortEdge || !maxPixels || !multiple) return null;+ if (aspectWidth <= 0 || aspectHeight <= 0) return null;+ const ratio = aspectWidth / aspectHeight;+ if (ratio < 1 / 4 || ratio > 4) return null;+ let width = ratio >= 1 ? shortEdge * ratio : shortEdge;+ let height = ratio >= 1 ? shortEdge : shortEdge / ratio;+ const area = width * height;+ if (area > maxPixels) {+ const scale = Math.sqrt(maxPixels / area);+ width *= scale;+ height *= scale;+ }+ const snap = (value: number) => Math.max(multiple, Math.round(value / multiple) * multiple);+ return [snap(width), snap(height)];+}diff --git a/studio/frontend/src/features/video/reference-budget.ts b/studio/frontend/src/features/video/reference-budget.tsnew file mode 100644index 00000000000..82319055f32--- /dev/null+++ b/studio/frontend/src/features/video/reference-budget.ts@@ -0,0 +1,13 @@+// 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's combined budget across picture, video and standalone-audio references. */+export const MAX_H3_REFERENCES = 12;++export function hasReferenceCapacity(+ images: number,+ videos: number,+ audios: number,+): boolean {+ return images + videos + audios < MAX_H3_REFERENCES;+}diff --git a/studio/frontend/src/features/video/reference-picker.tsx b/studio/frontend/src/features/video/reference-picker.tsxnew file mode 100644index 00000000000..a14c2a18932--- /dev/null+++ b/studio/frontend/src/features/video/reference-picker.tsx@@ -0,0 +1,126 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import { useCallback, useRef, useState } from "react";+import { Delete02Icon, FlimSlateIcon, MusicNote01Icon } from "@hugeicons/core-free-icons";+import { HugeiconsIcon } from "@hugeicons/react";++import { Button } from "@/components/ui/button";+import {+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from "@/components/ui/tooltip";+import { cn } from "@/lib/utils";+import { toast } from "@/lib/toast";++/** One staged reference file: the data URL the request carries, plus its name for the chip. */+export interface ReferenceMedia {+ name: string;+ dataUrl: string;+}++/** Reference video or audio picker that displays the selected filename. */+export function ReferenceMediaPicker({+ kind,+ value,+ onChange,+ label,+ compact = false,+}: {+ kind: "video" | "audio";+ value: ReferenceMedia | null;+ onChange: (media: ReferenceMedia | null) => void;+ /** Prompt shown in the empty state. */+ label: string;+ /** Half-height row, for the soundtrack slot that sits under its video. */+ compact?: boolean;+}) {+ const inputRef = useRef<HTMLInputElement | null>(null);+ const [dragging, setDragging] = useState(false);++ const readFile = useCallback(+ (file: File | undefined | null) => {+ if (!file || !file.type.startsWith(`${kind}/`)) {+ if (file) toast.error(`Please choose ${kind === "video" ? "a video" : "an audio"} file`);+ return;+ }+ const reader = new FileReader();+ reader.onload = () =>+ onChange(+ typeof reader.result === "string" ? { name: file.name, dataUrl: reader.result } : null,+ );+ reader.onerror = () => toast.error(`Could not read the ${kind} file`);+ reader.readAsDataURL(file);+ },+ [kind, onChange],+ );++ const icon = kind === "video" ? FlimSlateIcon : MusicNote01Icon;++ if (value) {+ return (+ <div+ className={cn(+ "flex items-center gap-2 rounded-[10px] border border-border bg-muted/30 px-2.5",+ compact ? "h-8" : "h-11",+ )}+ >+ <HugeiconsIcon icon={icon} className="size-3.5 shrink-0 text-muted-foreground" />+ <span className="min-w-0 flex-1 truncate text-ui-11 text-foreground">{value.name}</span>+ <Tooltip>+ <TooltipTrigger asChild={true}>+ <Button+ type="button"+ variant="ghost"+ size="icon"+ aria-label={`Remove ${label}`}+ className="size-6 shrink-0"+ onClick={() => {+ onChange(null);+ if (inputRef.current) inputRef.current.value = "";+ }}+ >+ <HugeiconsIcon icon={Delete02Icon} className="size-3.5" />+ </Button>+ </TooltipTrigger>+ <TooltipContent>Remove</TooltipContent>+ </Tooltip>+ </div>+ );+ }++ return (+ <button+ type="button"+ onClick={() => inputRef.current?.click()}+ onDragOver={(e) => {+ e.preventDefault();+ setDragging(true);+ }}+ onDragLeave={() => setDragging(false)}+ onDrop={(e) => {+ e.preventDefault();+ setDragging(false);+ readFile(e.dataTransfer.files?.[0]);+ }}+ className={cn(+ "flex w-full items-center justify-center gap-1.5 rounded-[10px] border border-dashed text-ui-11 transition-colors",+ compact ? "h-8" : "h-11",+ dragging+ ? "border-primary/60 bg-primary/5 text-foreground"+ : "border-border text-muted-foreground hover:border-foreground/30 hover:text-foreground",+ )}+ >+ <HugeiconsIcon icon={icon} className="size-3.5" />+ <span>{label}</span>+ <input+ ref={inputRef}+ type="file"+ accept={`${kind}/*`}+ className="hidden"+ onChange={(e) => readFile(e.target.files?.[0])}+ />+ </button>+ );+}diff --git a/studio/frontend/src/features/video/video-page.tsx b/studio/frontend/src/features/video/video-page.tsxindex b082c70ee73..542ea8bef86 100644--- a/studio/frontend/src/features/video/video-page.tsx+++ b/studio/frontend/src/features/video/video-page.tsx@@ -13,6 +13,7 @@ import {import { HugeiconsIcon } from "@hugeicons/react";import { AdvancedDisclosure } from "@/components/advanced-disclosure";+import { ImageDropzone } from "@/components/image-dropzone";import { MediaPageLink } from "@/components/media-page-link";import { usePlatformStore } from "@/config/env";import { useHardwareInfo } from "@/hooks/use-hardware-info";@@ -86,9 +87,13 @@ import { downloadUrlStreaming, isDownloadCancelled } from "@/lib/native-files";import { toast } from "@/lib/toast";import { subscribeModelEjected } from "@/lib/model-lifecycle-events";+import { MATCH_SOURCE_RESOLUTION, matchedCanvas } from "./keyframe-canvas";+import { hasReferenceCapacity } from "./reference-budget";+import { type ReferenceMedia, ReferenceMediaPicker } from "./reference-picker";import {type GalleryVideo,type VideoGenerateProgress,+ type VideoReferenceVideo,type VideoLoadProgress,type VideoStatus,cancelVideoGeneration,@@ -114,6 +119,8 @@ const VIDEO_MODELS: ModelOption[] = catalogToModelOptions(VIDEO_CATALOG);const DEFAULT_GEN = { steps: 8, guidance: 1 };const MODEL_DEFAULTS: Array<{ match: string; steps: number; guidance: number }> = [+ { match: "minimax-h3", steps: 30, guidance: 1 },+ { match: "minimax_h3", steps: 30, guidance: 1 },// "distilled" before the generic "ltx": the distilled model runs at 8 steps, guidance 1.{ match: "distilled", steps: 8, guidance: 1 },{ match: "ltx", steps: 40, guidance: 4 },@@ -137,7 +144,9 @@ const FALLBACK_RESOLUTION_PRESETS: Array<[number, number]> = [// Fallbacks for the duration presets before a model is loaded, so the select is populated and valid on first paint.const FALLBACK_FRAME_STEP = 8;+const FALLBACK_FRAME_OFFSET = 1;const FALLBACK_FPS = 24;+const FALLBACK_DURATION_TARGETS = [1, 2, 3, 5];// Module cache of the backend-persisted gallery, so a tab switch re-renders instantly. The srcById entries are short-lived// signed links, not object URLs: nothing is pinned in the webview, and the media element streams ranges as it plays.@@ -220,14 +229,23 @@ function formatTimestamp(iso: string): string {return Number.isNaN(d.getTime()) ? iso : d.toLocaleString();}-// A terse clip descriptor for the gallery card / player caption: duration + resolution.+// Labels for conditioned MiniMax-H3 tasks. Text-only and older clips need none.+const CONDITIONING_LABELS: Record<string, string> = {+ i2va: "From start frame",+ l2va: "To end frame",+ fl2va: "Start to end frame",+ ref2va: "From references",+};++// Keep the narrow gallery caption to duration and resolution.function clipMeta(video: GalleryVideo): string {const secs = video.duration_s > 0 ? `${video.duration_s.toFixed(1)}s` : `${video.num_frames}f`;return `${secs} · ${video.width}×${video.height}`;}-// Bar label for an in-flight generation: the phase ("Denoising step X/Y", "Encoding video...") plus an ETA once known.+// Bar label for an in-flight generation, plus an ETA while denoising.function genStepLabel(p: VideoGenerateProgress): string {+ if (p.phase === "decode") return "Decoding video and audio…";if (p.phase === "export") return "Encoding video…";// Text encoding and the first-step warmup run before the first scheduler tick, so step 0 means "working, not denoising yet" -- up to a minute at 720p.if (p.step === 0) return "Preparing (text encoding + warmup)…";@@ -552,6 +570,12 @@ function RecipePopover({<RecipeRow label="Negative" value={video.negative_prompt} wrap />) : null}{video.model ? <RecipeRow label="Model" value={video.model} /> : null}+ {CONDITIONING_LABELS[video.conditioning ?? ""] ? (+ <RecipeRow+ label="Source"+ value={CONDITIONING_LABELS[video.conditioning ?? ""]}+ />+ ) : null}{/* The load-time build, all ENGAGED values, so a saved clip can never be labelled with aprecision that did not run. Matches what the images Recipe already shows. */}{video.gguf_filename ? (@@ -578,6 +602,16 @@ function RecipePopover({<RecipeRow label="Duration" value={`${video.duration_s.toFixed(2)}s`} /><RecipeRow label="Steps" value={String(video.steps)} /><RecipeRow label="Guidance" value={String(video.guidance)} />+ {video.flow_shift != null ? (+ <RecipeRow+ label="Shift"+ value={+ video.audio_flow_shift != null+ ? `${video.flow_shift} video / ${video.audio_flow_shift} audio`+ : String(video.flow_shift)+ }+ />+ ) : null}<RecipeRow label="Seed" value={String(video.seed)} mono /></div><div className="border-t border-border/60 px-3 py-2.5">@@ -683,10 +717,27 @@ function VideoGenerator({ active = true }: { active?: boolean }) {const [steps, setSteps] = useState(DEFAULT_GEN.steps);const [guidance, setGuidance] = useState(DEFAULT_GEN.guidance);const [seed, setSeed] = useState("");- // The chosen resolution preset index into the current preset list.+ // Preset index, or MATCH_SOURCE_RESOLUTION for a keyframe-derived canvas.const [resolutionIdx, setResolutionIdx] = useState(0);- // The chosen frame count (must lie on the family's temporal lattice: k*frame_step+1).- const [numFrames, setNumFrames] = useState(FALLBACK_FRAME_STEP * 3 + 1);+ // MiniMax-H3 keyframes as data URLs: the frame the clip starts from, the frame it ends on, or both.+ const [firstFrame, setFirstFrame] = useState<string | null>(null);+ const [lastFrame, setLastFrame] = useState<string | null>(null);+ // Natural pixel size of whichever keyframe drives the canvas, for the "match source" preview.+ const [keyframeAspect, setKeyframeAspect] = useState<[number, number] | null>(null);+ // Separate lists preserve Ref2VA's image, video, then audio request order.+ const [referenceImages, setReferenceImages] = useState<string[]>([]);+ const [referenceVideos, setReferenceVideos] = useState<+ Array<{ video: ReferenceMedia; audio: ReferenceMedia | null }>+ >([]);+ const [referenceAudios, setReferenceAudios] = useState<ReferenceMedia[]>([]);+ const [referenceImageSize, setReferenceImageSize] = useState<"match" | "max">("match");+ // Null until the loaded family provides released schedule shifts.+ const [flowShift, setFlowShift] = useState<number | null>(null);+ const [audioFlowShift, setAudioFlowShift] = useState<number | null>(null);+ // The chosen frame count must lie on the family's temporal lattice.+ const [numFrames, setNumFrames] = useState(+ FALLBACK_FRAME_STEP * 3 + FALLBACK_FRAME_OFFSET,+ );// Advanced options live in a right-docked panel, closed by default; a single fixed top-bar toggle opens it.// Sits inline under Seed; the open state is remembered across visits.const [advancedOpen, setAdvancedOpen] = usePersistedToggle(@@ -808,28 +859,107 @@ function VideoGenerator({ active = true }: { active?: boolean }) {}, [status?.defaults?.resolution_presets]);const frameStep = status?.defaults?.frame_step ?? FALLBACK_FRAME_STEP;+ const frameOffset = status?.defaults?.frame_offset ?? FALLBACK_FRAME_OFFSET;const fps = status?.defaults?.fps ?? FALLBACK_FPS;+ const durationTargets =+ status?.defaults?.duration_presets ?? FALLBACK_DURATION_TARGETS;- // Duration presets: valid frame counts (k*frame_step+1) closest to ~1s/2s/3s/5s at the current fps, deduped.+ // Duration presets: valid frame counts closest to ~1s/2s/3s/5s at the current fps, deduped.const durationOptions = useMemo<Array<{ frames: number; seconds: number }>>(() => {- const targets = [1, 2, 3, 5];const seen = new Set<number>();const out: Array<{ frames: number; seconds: number }> = [];- for (const t of targets) {+ for (const t of durationTargets) {const desired = t * fps;- const k = Math.max(1, Math.round((desired - 1) / frameStep));- const frames = k * frameStep + 1;+ const k = Math.max(1, Math.round((desired - frameOffset) / frameStep));+ const frames = k * frameStep + frameOffset;if (seen.has(frames)) continue;seen.add(frames);out.push({ frames, seconds: frames / fps });}return out;- }, [frameStep, fps]);+ }, [frameStep, frameOffset, fps, durationTargets]);// Keep the resolution / frame-count selections valid when the loaded family changes.useEffect(() => {- setResolutionIdx((idx) => (idx < resolutionPresets.length ? idx : 0));+ setResolutionIdx((idx) =>+ idx === MATCH_SOURCE_RESOLUTION || idx < resolutionPresets.length ? idx : 0,+ );}, [resolutionPresets.length]);++ // ── keyframes ──────────────────────────────────────────────────────────────+ const supportsKeyframes = status?.supports_keyframes === true;+ // The keyframe the canvas follows: the first when there is one, else the last, matching the backend.+ const canvasKeyframe = firstFrame ?? lastFrame;++ const supportsReferences = status?.supports_references === true;+ const hasReferenceRoom = hasReferenceCapacity(+ referenceImages.length,+ referenceVideos.length,+ referenceAudios.length,+ );+ // Only Diffusers supports the 2048px reference policy.+ const canPickReferenceSize = supportsReferences && status?.engine !== "sd_cpp";++ // Drop conditioning that the newly loaded partition cannot accept.+ useEffect(() => {+ if (status?.loaded && !supportsKeyframes) {+ setFirstFrame(null);+ setLastFrame(null);+ }+ }, [status?.loaded, supportsKeyframes]);+ useEffect(() => {+ if (status?.loaded && !supportsReferences) {+ setReferenceImages([]);+ setReferenceVideos([]);+ setReferenceAudios([]);+ }+ }, [status?.loaded, supportsReferences]);+ useEffect(() => {+ if (!canPickReferenceSize) setReferenceImageSize("match");+ }, [canPickReferenceSize]);++ // Measure the keyframe that drives the canvas preview.+ useEffect(() => {+ if (!canvasKeyframe) {+ setKeyframeAspect(null);+ return;+ }+ let cancelled = false;+ const img = new Image();+ img.onload = () => {+ if (!cancelled) setKeyframeAspect([img.naturalWidth, img.naturalHeight]);+ };+ img.onerror = () => {+ if (!cancelled) setKeyframeAspect(null);+ };+ img.src = canvasKeyframe;+ return () => {+ cancelled = true;+ };+ }, [canvasKeyframe]);++ // Resolved "match source" canvas, when valid.+ const matchedResolution = useMemo(+ () =>+ keyframeAspect+ ? matchedCanvas(keyframeAspect[0], keyframeAspect[1], status?.defaults)+ : null,+ [keyframeAspect, status?.defaults],+ );++ // Select "match source" only after the staged keyframe passes the aspect-ratio check.+ const hadKeyframeRef = useRef(false);+ useEffect(() => {+ const has = canvasKeyframe != null;+ if (has === hadKeyframeRef.current) return;+ if (has && !matchedResolution) return;+ hadKeyframeRef.current = has;+ setResolutionIdx((idx) => {+ if (has) return MATCH_SOURCE_RESOLUTION;+ return idx === MATCH_SOURCE_RESOLUTION ? 0 : idx;+ });+ }, [canvasKeyframe, matchedResolution]);+const loadedFamily = status?.loaded ? status.family : null;const familyDefaultFrames = status?.defaults?.num_frames;const prevFamilyRef = useRef<string | null>(null);@@ -870,6 +1000,17 @@ function VideoGenerator({ active = true }: { active?: boolean }) {}}, [loadedModelKey, defaultSteps, defaultGuidance]);+ // Reset schedule shifts when the loaded model changes.+ const defaultFlowShift = status?.defaults?.flow_shift ?? null;+ const defaultAudioFlowShift = status?.defaults?.audio_flow_shift ?? null;+ const canPickAudioFlowShift = status?.defaults?.supports_audio_flow_shift === true;+ useEffect(() => {+ setFlowShift(defaultFlowShift);+ }, [defaultFlowShift, loadedModelKey]);+ useEffect(() => {+ setAudioFlowShift(defaultAudioFlowShift);+ }, [defaultAudioFlowShift, loadedModelKey]);+// Reseed the Advanced selects from the LOADED build, so they stop being pure local request state.// An honored request re-selects itself; a declined one snaps to what actually engaged, so the// Precision dropdown can never go on advertising a scheme the loaded DiT is not running. Keyed on@@ -1081,6 +1222,8 @@ function VideoGenerator({ active = true }: { active?: boolean }) {if (restoredNegative) setNegativeOpen(true);setSteps(video.steps);setGuidance(video.guidance);+ if (video.flow_shift != null) setFlowShift(video.flow_shift);+ if (video.audio_flow_shift != null) setAudioFlowShift(video.audio_flow_shift);setSeed(String(video.seed));// Snap the resolution to the matching preset when one exists; else leave as is.const presetIdx = resolutionPresets.findIndex(@@ -1774,6 +1917,10 @@ function VideoGenerator({ active = true }: { active?: boolean }) {toast.error("Prompt is empty");return;}+ if (supportsReferences && referenceImages.length === 0 && referenceVideos.length === 0) {+ toast.error("Add a reference picture or video for this checkpoint");+ return;+ }// Resolve a base seed up front: with a random one we still pick a concrete seed now so the recipe records it.let resolvedSeed: number | undefined;if (seed.trim()) {@@ -1787,8 +1934,9 @@ function VideoGenerator({ active = true }: { active?: boolean }) {resolvedSeed = Math.floor(Math.random() * 2 ** 32);}+ // Omitting both dimensions delegates "match source" to the backend.+ const matchSource = resolutionIdx === MATCH_SOURCE_RESOLUTION;const preset = resolutionPresets[resolutionIdx] ?? resolutionPresets[0];- const [w, h] = preset;setBusy("generating");setGenStep(null);@@ -1798,14 +1946,42 @@ function VideoGenerator({ active = true }: { active?: boolean }) {await generateVideo({prompt: prompt.trim(),// Only send a negative prompt when guidance uses it, so the recipe does not record one the model ignored.- negative_prompt: guidance > 0 ? negativePrompt.trim() || undefined : undefined,- width: w,- height: h,+ negative_prompt:+ status?.supports_cfg !== false && guidance > 0+ ? negativePrompt.trim() || undefined+ : undefined,+ width: matchSource ? undefined : preset[0],+ height: matchSource ? undefined : preset[1],num_frames: numFrames,fps,steps,- guidance,+ guidance: status?.supports_cfg !== false ? guidance : undefined,seed: resolvedSeed,+ first_frame: supportsKeyframes ? firstFrame ?? undefined : undefined,+ last_frame: supportsKeyframes ? lastFrame ?? undefined : undefined,+ reference_images:+ supportsReferences && referenceImages.length > 0 ? referenceImages : undefined,+ reference_videos:+ supportsReferences && referenceVideos.length > 0+ ? referenceVideos.map(+ (entry): VideoReferenceVideo => ({+ video: entry.video.dataUrl,+ audio: entry.audio?.dataUrl,+ }),+ )+ : undefined,+ reference_audios:+ supportsReferences && referenceAudios.length > 0+ ? referenceAudios.map((entry) => entry.dataUrl)+ : undefined,+ reference_image_size: canPickReferenceSize ? referenceImageSize : undefined,+ // Send only overrides of the released schedule.+ flow_shift:+ flowShift != null && flowShift !== defaultFlowShift ? flowShift : undefined,+ audio_flow_shift:+ canPickAudioFlowShift && audioFlowShift != null && audioFlowShift !== defaultAudioFlowShift+ ? audioFlowShift+ : undefined,});} catch (err) {if (!isMounted.current) return;@@ -1826,6 +2002,21 @@ function VideoGenerator({ active = true }: { active?: boolean }) {numFrames,fps,steps,+ status?.supports_cfg,+ supportsKeyframes,+ firstFrame,+ lastFrame,+ supportsReferences,+ referenceImages,+ referenceVideos,+ referenceAudios,+ canPickReferenceSize,+ referenceImageSize,+ flowShift,+ defaultFlowShift,+ audioFlowShift,+ defaultAudioFlowShift,+ canPickAudioFlowShift,startGenPoll,]);@@ -1955,6 +2146,7 @@ function VideoGenerator({ active = true }: { active?: boolean }) {{status?.loaded && (<div className="hidden min-w-0 items-center gap-3 text-ui-11 @min-[720px]:flex">{status.family && <StatusChip label="Family" value={status.family} />}+ {status.engine && <StatusChip label="Engine" value={status.engine} />}{status.model_kind && <StatusChip label="Kind" value={status.model_kind} />}{status.offload_policy && (<StatusChip label="Offload" value={status.offload_policy} />@@ -1998,7 +2190,11 @@ function VideoGenerator({ active = true }: { active?: boolean }) {Create videos</h2><p className="text-xs leading-snug text-muted-foreground">- Generate a video from a prompt+ {supportsReferences+ ? "Generate a video from a prompt and reference pictures, videos or audio"+ : supportsKeyframes+ ? "Generate a video from a prompt, or from a start and end frame"+ : "Generate a video from a prompt"}</p></div>@@ -2010,17 +2206,213 @@ function VideoGenerator({ active = true }: { active?: boolean }) {/></Field>- <NegativePromptField- value={negativePrompt}- onChange={setNegativePrompt}- open={negativeOpen}- onOpenChange={setNegativeOpen}- hint="What to steer the video away from. Only used when guidance is above 0."- />+ {supportsKeyframes && (+ <div className="grid gap-2">+ <span className="flex items-center gap-1 text-xs font-medium text-muted-foreground">+ Start and end frame+ <InfoHint>+ Optional. A start frame animates that picture; an end frame makes the clip land+ on one; both make it travel between them. Text-to-video is what you get with+ neither. The start frame is stretched onto the canvas and the end frame is+ centre-cropped, which is how the model was conditioned.+ </InfoHint>+ </span>+ <div className="grid grid-cols-2 gap-2">+ <div className="grid gap-1.5">+ <span className="text-ui-11 text-muted-foreground/70">Start frame</span>+ <ImageDropzone+ value={firstFrame}+ onChange={setFirstFrame}+ label="Click or drop"+ removeLabel="Remove start frame"+ />+ </div>+ <div className="grid gap-1.5">+ <span className="text-ui-11 text-muted-foreground/70">End frame</span>+ <ImageDropzone+ value={lastFrame}+ onChange={setLastFrame}+ label="Click or drop"+ removeLabel="Remove end frame"+ />+ </div>+ </div>+ {canvasKeyframe && !matchedResolution && (+ // Surface the same aspect-ratio rejection before Generate.+ <p className="text-ui-11 leading-snug text-destructive">+ This picture is too far from square for MiniMax-H3, which was trained between+ 1:4 and 4:1. Crop it, or pick a resolution preset to stretch it onto.+ </p>+ )}+ </div>+ )}++ {supportsReferences && (+ <div className="grid gap-2">+ <span className="flex items-center gap-1 text-xs font-medium text-muted-foreground">+ References+ <InfoHint>+ Lock the clip to a character, style, motion, camera move or voice. Name them in+ the prompt by the tags below -- "use the cat from <Picture 1>, match the+ shot rhythm of <Video 1>" -- since order is what the model reads them by.+ At most 9 pictures, 3 videos and 3 audio clips, 12 in all. Audio needs a picture+ or a video to go with it.+ </InfoHint>+ </span>++ <div className="grid grid-cols-3 gap-2">+ {referenceImages.map((image, index) => (+ // Index IS the identity here: the tag in the prompt is the position.+ // biome-ignore lint/suspicious/noArrayIndexKey: position is the reference's name+ <div key={`picture-${index}`} className="grid gap-1">+ <span className="text-ui-11 text-muted-foreground/70">+ Picture {index + 1}+ </span>+ <ImageDropzone+ value={image}+ onChange={(next) =>+ setReferenceImages((prev) =>+ next+ ? prev.map((item, i) => (i === index ? next : item))+ : prev.filter((_, i) => i !== index),+ )+ }+ removeLabel={`Remove picture ${index + 1}`}+ className="h-20"+ />+ </div>+ ))}+ {referenceImages.length < 9 && hasReferenceRoom && (+ <div className="grid gap-1">+ <span className="text-ui-11 text-muted-foreground/70">+ Picture {referenceImages.length + 1}+ </span>+ <ImageDropzone+ value={null}+ onChange={(next) => next && setReferenceImages((prev) => [...prev, next])}+ label="Add"+ className="h-20"+ />+ </div>+ )}+ </div>++ <div className="grid gap-1.5">+ {referenceVideos.map((entry, index) => (+ // biome-ignore lint/suspicious/noArrayIndexKey: position is the reference's name+ <div key={`video-${index}`} className="grid gap-1">+ <span className="text-ui-11 text-muted-foreground/70">Video {index + 1}</span>+ <ReferenceMediaPicker+ kind="video"+ value={entry.video}+ label={`Video ${index + 1}`}+ onChange={(next) =>+ setReferenceVideos((prev) =>+ next+ ? prev.map((item, i) => (i === index ? { ...item, video: next } : item))+ : prev.filter((_, i) => i !== index),+ )+ }+ />+ <ReferenceMediaPicker+ kind="audio"+ compact={true}+ value={entry.audio}+ label="Replace its soundtrack (optional)"+ onChange={(next) =>+ setReferenceVideos((prev) =>+ prev.map((item, i) => (i === index ? { ...item, audio: next } : item)),+ )+ }+ />+ </div>+ ))}+ {referenceVideos.length < 3 && hasReferenceRoom && (+ <ReferenceMediaPicker+ kind="video"+ value={null}+ label={`Add video ${referenceVideos.length + 1}`}+ onChange={(next) =>+ next && setReferenceVideos((prev) => [...prev, { video: next, audio: null }])+ }+ />+ )}+ </div>++ <div className="grid gap-1.5">+ {referenceAudios.map((audio, index) => (+ // biome-ignore lint/suspicious/noArrayIndexKey: position is the reference's name+ <div key={`audio-${index}`} className="grid gap-1">+ <span className="text-ui-11 text-muted-foreground/70">Audio {index + 1}</span>+ <ReferenceMediaPicker+ kind="audio"+ value={audio}+ label={`Audio ${index + 1}`}+ onChange={(next) =>+ setReferenceAudios((prev) =>+ next+ ? prev.map((item, i) => (i === index ? next : item))+ : prev.filter((_, i) => i !== index),+ )+ }+ />+ </div>+ ))}+ {referenceAudios.length < 3 &&+ hasReferenceRoom &&+ (referenceImages.length > 0 || referenceVideos.length > 0) && (+ <ReferenceMediaPicker+ kind="audio"+ value={null}+ label={`Add audio ${referenceAudios.length + 1}`}+ onChange={(next) => next && setReferenceAudios((prev) => [...prev, next])}+ />+ )}+ </div>++ {referenceImages.length === 0 && referenceVideos.length === 0 && (+ // Ref2VA cannot generate without an image or video reference.+ <p className="text-ui-11 leading-snug text-muted-foreground/70">+ This checkpoint generates from references. Add a picture or a video, or load a+ first/last-frame checkpoint for plain text-to-video.+ </p>+ )}++ {canPickReferenceSize && (+ <Field+ label="Reference detail"+ hint="How reference pictures are sized. Match keeps them at the clip's own pixel area. Max encodes them at 2048px for stronger identity fidelity, and rides every sampling step, so it can be several times slower."+ >+ <Select+ value={referenceImageSize}+ onValueChange={(v) => setReferenceImageSize(v as "match" | "max")}+ >+ <SelectTrigger>+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="match">Match the clip</SelectItem>+ <SelectItem value="max">Max (2048px, slower)</SelectItem>+ </SelectContent>+ </Select>+ </Field>+ )}+ </div>+ )}++ {status?.supports_cfg !== false && (+ <NegativePromptField+ value={negativePrompt}+ onChange={setNegativePrompt}+ open={negativeOpen}+ onOpenChange={setNegativeOpen}+ hint="What to steer the video away from. Only used when guidance is above 0."+ />+ )}<Fieldlabel="Resolution"- hint="The frame size. Presets come from the loaded model; portrait presets are marked."+ hint="The frame size. Presets come from the loaded model; portrait presets are marked. With a keyframe staged, Match source keeps the picture's own shape."><Selectvalue={String(resolutionIdx)}@@ -2030,6 +2422,14 @@ function VideoGenerator({ active = true }: { active?: boolean }) {<SelectValue /></SelectTrigger><SelectContent>+ {canvasKeyframe && (+ <SelectItem value={String(MATCH_SOURCE_RESOLUTION)}>+ Match source+ {matchedResolution+ ? ` · ${matchedResolution[0]} × ${matchedResolution[1]}`+ : ""}+ </SelectItem>+ )}{resolutionPresets.map(([w, h], i) => (<SelectItem key={`${w}x${h}`} value={String(i)}>{w} × {h}@@ -2078,15 +2478,39 @@ function VideoGenerator({ active = true }: { active?: boolean }) {step={1}onChange={setSteps}/>- <SliderField- label="Guidance"- hint="Classifier-free guidance scale. Keep low (1) for the distilled model; the base model uses real guidance (4)."- value={guidance}- min={0}- max={20}- step={0.5}- onChange={setGuidance}- />+ {status?.supports_cfg !== false && (+ <SliderField+ label="Guidance"+ hint="Classifier-free guidance scale. Keep low (1) for the distilled model; the base model uses real guidance (4)."+ value={guidance}+ min={0}+ max={20}+ step={0.5}+ onChange={setGuidance}+ />+ )}+ {flowShift != null && (+ <SliderField+ label="Motion shift"+ hint="Sigma shift of the video schedule. Higher spends more of the schedule at high noise, which reads as more motion and less fine detail. MiniMax-H3 ships 12."+ value={flowShift}+ min={1}+ max={30}+ step={0.5}+ onChange={setFlowShift}+ />+ )}+ {canPickAudioFlowShift && audioFlowShift != null && (+ <SliderField+ label="Audio shift"+ hint="Sigma shift of the audio schedule, which MiniMax-H3 runs alongside the video one. Ships at 3."+ value={audioFlowShift}+ min={1}+ max={30}+ step={0.5}+ onChange={setAudioFlowShift}+ />+ )}{/* A slider row ends flush with its track, so the label below needs room. */}<Fieldlabel="Seed"@@ -2237,7 +2661,9 @@ function VideoGenerator({ active = true }: { active?: boolean }) {title={null}message="Starting…"progressPercent={- genStep && genStep.total > 0 ? (genStep.step / genStep.total) * 100 : null+ genStep?.phase === "denoise" && genStep.total > 0+ ? (genStep.step / genStep.total) * 100+ : null}progressLabel={genStep ? genStepLabel(genStep) : null}/>@@ -2300,6 +2726,9 @@ function VideoGenerator({ active = true }: { active?: boolean }) {{video.prompt}<span className="mt-0.5 block opacity-70">seed {video.seed} - {clipMeta(video)}+ {CONDITIONING_LABELS[video.conditioning ?? ""]+ ? ` - ${CONDITIONING_LABELS[video.conditioning ?? ""]}`+ : ""}</span></TooltipContent></Tooltip>diff --git a/studio/frontend/tests/recommended-curated-row-metadata.test.ts b/studio/frontend/tests/recommended-curated-row-metadata.test.tsnew file mode 100644index 00000000000..26ae9d24451--- /dev/null+++ b/studio/frontend/tests/recommended-curated-row-metadata.test.ts@@ -0,0 +1,211 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// The Recommended list paints curated catalog seeds as well as live Hub listing rows.+// Everything a row shows beyond its id used to come from the listing alone, so a curated+// model the listing does not return (a repo it has not indexed, a non-unsloth owner, one+// this account cannot see) rendered bare and, once downloaded, stopped matching search+// entirely. These pin the catalog fallbacks that close both gaps.++import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import test from "node:test";+import { fileURLToPath } from "node:url";++import ts from "typescript";++import { detectCapabilities } from "../src/features/model-picker/components/model-selector/model-capabilities.ts";+import {+ VIDEO_CATALOG,+ curatedCapabilitiesFor,+ curatedTotalParamsFor,+} from "../src/features/model-picker/components/model-selector/model-catalog.ts";+import {+ paramsFromId,+ searchRowFitsDevice,+ searchableRecommendedIds,+} from "../src/features/model-picker/components/model-selector/recommended-fit.ts";++const H3_GGUF = "unsloth/MiniMax-H3-GGUF";+const H3_BF16 = "MiniMaxAI/MiniMax-H3";+const LTX_GGUF = "unsloth/LTX-2.3-GGUF";+const WAN_BF16 = "Wan-AI/Wan2.2-TI2V-5B-Diffusers";++// ── search: a downloaded curated row stays findable ───────────────────────────++test("a seed the listing pool dropped is still searchable", () => {+ // recommendedIds (the listing pool) filters out everything already on disk, because a+ // downloaded model has its own On Device row. The unfiltered Recommended list keeps+ // painting it from the seeds, so search has to as well.+ const seeds = [H3_GGUF, LTX_GGUF];+ const listing = [LTX_GGUF, "unsloth/Wan2.2-TI2V-5B-GGUF"]; // H3 downloaded -> dropped+ assert.deepEqual(searchableRecommendedIds(seeds, listing), [+ H3_GGUF,+ LTX_GGUF,+ "unsloth/Wan2.2-TI2V-5B-GGUF",+ ]);+});++test("seeds come first and no id is listed twice", () => {+ // Same order orderRecommendedRows renders: curated in catalog order, then the rest.+ const out = searchableRecommendedIds(+ [H3_GGUF, LTX_GGUF],+ ["unsloth/Other-GGUF", LTX_GGUF, H3_GGUF],+ );+ assert.deepEqual(out, [H3_GGUF, LTX_GGUF, "unsloth/Other-GGUF"]);+});++test("a listing row that only differs in case does not duplicate its seed", () => {+ // The HF cache lowercases repo ids, so the two pools can disagree on casing.+ const out = searchableRecommendedIds([H3_GGUF], ["unsloth/minimax-h3-gguf"]);+ assert.deepEqual(out, [H3_GGUF]);+});++test("with no seeds the listing pool is passed through unchanged", () => {+ // Chat (no catalog) must behave exactly as before.+ const listing = ["unsloth/a-GGUF", "unsloth/b-GGUF"];+ assert.deepEqual(searchableRecommendedIds([], listing), listing);+});++// ── row metadata: size chip + capability glyphs ───────────────────────────────++test("a curated GGUF carries the param count its id cannot spell", () => {+ // "MiniMax-H3-GGUF" has no "<n>B" token, and the listing does not return the repo, so+ // without the catalog the row has no size chip at all.+ assert.equal(paramsFromId(H3_GGUF), undefined);+ assert.equal(curatedTotalParamsFor(H3_GGUF, VIDEO_CATALOG), 20_111_438_744);+});++test("the curated param count is the artifact's own, not the group's", () => {+ // The BF16 pipeline row is a different checkpoint (it bundles the encoder and VAEs);+ // it declares no count rather than borrowing the denoiser's.+ assert.equal(curatedTotalParamsFor(H3_BF16, VIDEO_CATALOG), undefined);+ assert.equal(curatedTotalParamsFor(LTX_GGUF, VIDEO_CATALOG), 21_005_004_544);+});++test("a curated audio family reports audio the repo name never mentions", () => {+ assert.equal(detectCapabilities({ id: H3_GGUF }).audio, false);+ assert.equal(curatedCapabilitiesFor(H3_GGUF, VIDEO_CATALOG)?.audio, true);+ // Group-level, so every artifact of the model agrees.+ assert.equal(curatedCapabilitiesFor(H3_BF16, VIDEO_CATALOG)?.audio, true);+ assert.equal(curatedCapabilitiesFor(LTX_GGUF, VIDEO_CATALOG)?.audio, true);+});++test("curated capabilities claim nothing they were not given", () => {+ const caps = curatedCapabilitiesFor(H3_GGUF, VIDEO_CATALOG);+ assert.deepEqual(caps, { vision: false, reasoning: false, audio: true });+ // A group that declares none returns undefined, so the row falls back to name detection.+ assert.equal(curatedCapabilitiesFor(WAN_BF16, VIDEO_CATALOG), undefined);+});++test("every video group whose description says audio declares the capability", () => {+ // The catalog description is the human-facing claim; the flag is what draws the glyph.+ // A new audio family that sets one and forgets the other is the failure this catches.+ for (const group of VIDEO_CATALOG) {+ const saysAudio = /\baudio\b/i.test(group.description);+ assert.equal(+ group.capabilities?.audio === true,+ saysAudio,+ `${group.canonicalId}: description "${group.description}" and capabilities.audio disagree`,+ );+ }+});++test("the curated param count is what makes a curated row sizable in search", () => {+ // The search fit check hides anything it cannot size (`requireKnown`), while the+ // unfiltered Recommended list judges the seed row, which carries its own metadata.+ // Without the catalog fallback the same model is kept in one list and hidden in the+ // other the moment the "Fits on device" toggle is on.+ const gpu = {+ available: true,+ memoryTotalGb: 80,+ maxDeviceMemoryGb: 80,+ loadDeviceMemoryGb: 80,+ systemRamAvailableGb: 0,+ budgetKnown: true,+ };+ const opts = { isGguf: true, gpu, inferenceGpu: gpu, taskScoped: true };+ assert.equal(searchRowFitsDevice({ id: H3_GGUF }, opts), false);+ assert.equal(+ searchRowFitsDevice(+ {+ id: H3_GGUF,+ totalParams: curatedTotalParamsFor(H3_GGUF, VIDEO_CATALOG),+ },+ opts,+ ),+ true,+ );+});++// ── wiring: the picker actually reads the fallbacks ───────────────────────────++const PICKERS = fileURLToPath(+ new URL(+ "../src/features/model-picker/components/model-selector/pickers.tsx",+ import.meta.url,+ ),+);++/** Source text of the top-level `const <name> = ...` initializer in pickers.tsx. */+function declarationText(name: string): string {+ const source = ts.createSourceFile(+ PICKERS,+ readFileSync(PICKERS, "utf8"),+ ts.ScriptTarget.Latest,+ true,+ ts.ScriptKind.TSX,+ );+ let found: string | null = null;+ const walk = (node: ts.Node): void => {+ if (+ found === null &&+ ts.isVariableDeclaration(node) &&+ ts.isIdentifier(node.name) &&+ node.name.text === name &&+ node.initializer+ ) {+ found = node.initializer.getText(source);+ return;+ }+ ts.forEachChild(node, walk);+ };+ walk(source);+ assert.ok(found, `no const ${name} = ... in pickers.tsx`);+ return found as unknown as string;+}++test("the search list is built from the seeds as well as the listing pool", () => {+ assert.match(+ declarationText("filteredRecommendedIds"),+ /searchableRecommendedIds\(\s*catalogSeedIds\s*,\s*recommendedIds\s*\)/,+ );+});++test("row meta falls back to the curated seeds", () => {+ const text = declarationText("recommendedMeta");+ assert.match(text, /recommendedSearch\.results\s*,\s*\.\.\.catalogSeedRows/);+ // Listing first, and the first entry per id wins.+ assert.match(text, /if\s*\(map\.has\(r\.id\)\)\s*continue;/);+});++test("capabilities fall back to the curated catalog", () => {+ assert.match(+ declarationText("capsById"),+ /curatedCapabilitiesFor\(row\.id, catalog\)/,+ );+});++test("the search fit check falls back to the curated param count", () => {+ assert.match(+ declarationText("searchRowFits"),+ /curatedTotalParamsFor\(row\.id, catalog\)/,+ );+});++test("seed rows carry the curated param count", () => {+ assert.match(+ declarationText("catalogSeedRows"),+ /totalParams:\s*catalog\s*\?\s*curatedTotalParamsFor\(id, catalog\)/,+ );+});diff --git a/studio/frontend/tests/video-keyframe-canvas.test.ts b/studio/frontend/tests/video-keyframe-canvas.test.tsnew file mode 100644index 00000000000..820d8c7d6f1--- /dev/null+++ b/studio/frontend/tests/video-keyframe-canvas.test.ts@@ -0,0 +1,47 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import test from "node:test";+import type { VideoGenerationDefaults } from "../src/features/video/api.ts";+import { matchedCanvas } from "../src/features/video/keyframe-canvas.ts";++// What /video/status reports for MiniMax-H3: the released checkpoint's canvas rule.+const h3: VideoGenerationDefaults = {+ steps: 30,+ guidance: 1,+ num_frames: 124,+ fps: 24,+ frame_step: 17,+ frame_offset: 5,+ duration_presets: [5, 10, 14.4],+ resolution_multiple: 32,+ resolution_presets: [[1344, 768]],+ canvas_short_edge: 768,+ canvas_max_pixels: 768 * 1344,+};++test("previews the same canvas the backend derives from a keyframe", () => {+ // The pairs the backend's own test pins, so a divergence in either direction is caught.+ assert.deepEqual(matchedCanvas(1920, 1080, h3), [1344, 768]);+ assert.deepEqual(matchedCanvas(1080, 1920, h3), [768, 1344]);+ assert.deepEqual(matchedCanvas(1000, 1000, h3), [768, 768]);+ assert.deepEqual(matchedCanvas(1024, 768, h3), [1024, 768]);+});++test("reads the ratio only, so the source's own scale never matters", () => {+ assert.deepEqual(matchedCanvas(160, 90, h3), matchedCanvas(3840, 2160, h3));+});++test("previews nothing where the backend would refuse or has no rule", () => {+ // Outside the trained 1:4 - 4:1 band the backend raises, so offering a size would be a lie.+ assert.equal(matchedCanvas(2000, 400, h3), null);+ assert.equal(matchedCanvas(400, 2000, h3), null);+ assert.equal(matchedCanvas(0, 100, h3), null);+ // A family that declares no canvas rule takes no keyframes either.+ assert.equal(+ matchedCanvas(1920, 1080, { ...h3, canvas_short_edge: null, canvas_max_pixels: null }),+ null,+ );+ assert.equal(matchedCanvas(1920, 1080, null), null);+});diff --git a/studio/frontend/tests/video-reference-budget.test.ts b/studio/frontend/tests/video-reference-budget.test.tsnew file mode 100644index 00000000000..4f93952aae7--- /dev/null+++ b/studio/frontend/tests/video-reference-budget.test.ts@@ -0,0 +1,17 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import test from "node:test";++import {+ MAX_H3_REFERENCES,+ hasReferenceCapacity,+} from "../src/features/video/reference-budget.ts";++test("the combined reference budget closes every add slot at twelve items", () => {+ assert.equal(MAX_H3_REFERENCES, 12);+ assert.equal(hasReferenceCapacity(8, 2, 1), true);+ assert.equal(hasReferenceCapacity(9, 2, 1), false);+ assert.equal(hasReferenceCapacity(7, 3, 2), false);+});diff --git a/studio/install_python_stack.py b/studio/install_python_stack.pyindex 0cf11a258e5..8e0a44942b1 100644--- a/studio/install_python_stack.py+++ b/studio/install_python_stack.py@@ -3802,7 +3802,8 @@ def install_python_stack() -> int:package_name = os.environ.get("STUDIO_PACKAGE_NAME", "unsloth")# --local overlays a local repo checkout after updating deps.local_repo = os.environ.get("STUDIO_LOCAL_REPO", "")- base_total = 11 if IS_WINDOWS else 12 # +1 for the anyio repair check (step 8b)+ # +1 for the anyio repair check (step 8b), +1 for the diffusers pin (step 11b, every platform)+ base_total = 12 if IS_WINDOWS else 13if IS_MACOS:base_total -= 1 # triton step is skipped on macOSif not IS_MACOS and not NO_TORCH:@@ -4185,6 +4186,22 @@ def install_python_stack() -> int:constrain = False,)+ # 11b. The pinned Diffusers revision. Deliberately NOT in base.txt: install.sh installs+ # unsloth itself and then runs this script with SKIP_STUDIO_BASE=1, so the whole+ # base-packages step is skipped and anything pinned there reaches `unsloth studio+ # update` but never a fresh install -- where unsloth's own metadata has already+ # pulled a diffusers RELEASE from PyPI, and Studio then refuses to load MiniMax-H3.+ # This step is outside every skip_base / NO_TORCH branch, and it runs after every+ # other requirements file, so nothing left can re-resolve diffusers behind it.+ # constrain stays on: constraints.txt says nothing about diffusers, and a future+ # entry there should win rather than be silently bypassed here.+ _progress("diffusers pin")+ pip_install(+ "Installing the pinned Diffusers revision",+ "--no-cache-dir",+ req = REQ_ROOT / "diffusers-pin.txt",+ )+# 12. Patch metadata for single-env compatibility_progress("finalizing")run(diff --git a/studio/install_sd_cpp_prebuilt.py b/studio/install_sd_cpp_prebuilt.pyindex e1d8caa49df..56c6bd59cc0 100644--- a/studio/install_sd_cpp_prebuilt.py+++ b/studio/install_sd_cpp_prebuilt.py@@ -44,11 +44,24 @@ DEFAULT_REPO = "unslothai/stable-diffusion.cpp"# Fallback when the mirror cannot serve this host (release missing, or a host we do not build).UPSTREAM_FALLBACK_REPO = "leejet/stable-diffusion.cpp"# Pinned for reproducibility; UNSLOTH_SD_CPP_TAG overrides (empty tracks latest). A missing tag falls back to latest.+#+# The -u<id> suffix means the mirror built upstream master-813-bfbef5b plus the patch set in its+# patches/ directory, and the id is the hash of that set. MiniMax-H3 needs it: an unpatched build+# aborts on the default --cfg-scale, aborts again on --vae-on-cpu, and quantizes H3's 1-D norms+# into an output uncorrelated with its own bf16 reference. All three fixes are open upstream+# (leejet/stable-diffusion.cpp#1861, #1862, #1863) and the patches are deleted once they ship+# there, at which point this pin goes back to a plain upstream tag.+#+# leejet has no release under this name, so the upstream fallback cannot match the pin and drops+# to leejet's latest, which is the documented behaviour for a mirror-only tag.DEFAULT_TAG = "master-813-bfbef5b-u13b9d92"# Back-compat alias (some callers/tests import REPO).REPO = DEFAULT_REPO+# ``master-<n>-<sha>-u<id>``: the mirror's marker for "upstream tree plus our patches/".+_MIRROR_ONLY_TAG_RE = re.compile(r"^master-\d+-[0-9a-f]+-u[0-9a-f]+$")+# What the managed directory records about the install it holds, so a later ensure_* can tell a CPU# bundle from a CUDA one instead of reusing whatever binary happens to be on disk.INSTALL_RECORD = ".unsloth-sd-cpp-install.json"@@ -121,6 +134,14 @@ def _pinned_tag() -> Optional[str]:return val or None+def is_mirror_only_tag(tag: Optional[str]) -> bool:+ """True for a ``<upstream tag>-u<id>`` tag, which only the Unsloth mirror can serve.++ The mirror publishes such a tag when it builds the upstream tree plus the patch set in its+ ``patches/`` directory, so by construction upstream has no release under that name."""+ return bool(tag) and bool(_MIRROR_ONLY_TAG_RE.match(tag))++# A mirror release built on top of an upstream one carries a "-u<short sha>" suffix naming the# fork commit (master-813-bfbef5b-u13b9d92 is upstream master-813-bfbef5b plus fork commit 13b9d92)._MIRROR_TAG_SUFFIX = re.compile(r"-u[0-9a-f]{7,}$")@@ -448,6 +469,7 @@ def _resolve_with_fallback(allow_upstream = (not repo_pinned and primary == DEFAULT_REPO and DEFAULT_REPO != UPSTREAM_FALLBACK_REPO)+ mirror_only = is_mirror_only_tag(tag)# (repo, tag_to_fetch, allow_latest): with a pin, try the exact pin on every repo first, then each repo's latest.attempts: list[tuple[str, Optional[str], bool]] = []@@ -457,6 +479,8 @@ def _resolve_with_fallback(# The mirror's own tag does not exist upstream, so the pin has to be translated back# to the upstream release it was built from -- otherwise this attempt always 404s and# the pin degrades to upstream latest for every host the mirror does not build.+ # This supersedes simply skipping the attempt for a mirror-only tag: skipping kept the+ # round trip cheap but dropped the pin entirely on those hosts.attempts.append((UPSTREAM_FALLBACK_REPO, upstream_tag_for(tag), False))attempts.append((primary, None, True))if allow_upstream:@@ -478,6 +502,19 @@ def _resolve_with_fallback(file = sys.stderr,flush = True,)+ # A mirror-only pin means the shipped default carries fixes that upstream has+ # not released. Falling back is still better than no native engine at all for+ # every other model, but the H3 failures are SILENT (it renders, just wrongly),+ # so this has to be said out loud rather than left to the generic line above.+ if mirror_only:+ print(+ f"warning: {repo} has no {tag}; this build lacks the MiniMax-H3 fixes, "+ "so H3 will abort on the default cfg-scale and on --vae-on-cpu, and a "+ "blanket --type will quantize its 1-D norms into a broken render. Other "+ "models are unaffected.",+ file = sys.stderr,+ flush = True,+ )return repo, release, chosenreturn primary, None, Nonediff --git a/tests/studio/install/test_diffusers_pin.py b/tests/studio/install/test_diffusers_pin.pynew file mode 100644index 00000000000..a392f80cc56--- /dev/null+++ b/tests/studio/install/test_diffusers_pin.py@@ -0,0 +1,131 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""The pinned Diffusers revision has to survive a fresh install.sh, not just an update.++MiniMax-H3 needs a Diffusers revision newer than any published release, and Studio+refuses to load it otherwise. The pin originally lived in+studio/backend/requirements/base.txt, which looks like the obvious home and is+completely dead on the install path that matters: install.sh installs unsloth itself+(which drags a diffusers RELEASE in from PyPI as a transitive dependency) and then runs+install_python_stack.py with SKIP_STUDIO_BASE=1, where the base-packages step is a bare+`pass`. A clean install therefore ended up on the release, every time, with no error.++These tests pin the shape that fixes it: exactly one file names diffusers, and the step+that installs it sits outside every skip.+"""++from __future__ import annotations++import ast+import pathlib+import re++REPO_ROOT = pathlib.Path(__file__).resolve().parents[3]+REQ_ROOT = REPO_ROOT / "studio" / "backend" / "requirements"+PIN_FILE = REQ_ROOT / "diffusers-pin.txt"+STACK = REPO_ROOT / "studio" / "install_python_stack.py"+INSTALL_SH = REPO_ROOT / "install.sh"+++def _requirements(path: pathlib.Path) -> list[str]:+ """Requirement lines only: comments and flag lines dropped."""+ out = []+ for line in path.read_text(encoding = "utf-8").splitlines():+ text = line.split("#", 1)[0].strip()+ if text and not text.startswith("-"):+ out.append(text)+ return out+++def test_the_pin_file_exists_and_names_an_exact_revision():+ assert PIN_FILE.is_file(), f"{PIN_FILE} is missing"+ lines = _requirements(PIN_FILE)+ urls = [line for line in lines if "://" in line]+ assert len(urls) == 1, f"expected exactly one pinned URL, got {urls}"+ # A branch or tag would move under us; only a 40-char commit sha is reproducible.+ assert re.search(+ r"/archive/[0-9a-f]{40}\.zip", urls[0]+ ), f"the diffusers pin must name a full commit sha, not a moving ref: {urls[0]}"+ assert 'python_version >= "3.10"' in urls[0], (+ "diffusers dropped Python 3.9 in 0.38, so the archive needs a >= 3.10 marker or "+ "the resolver has no candidate at all on a 3.9 host"+ )+++def test_only_the_pin_file_names_diffusers():+ """One source of truth. A second entry anywhere is how a release creeps back in:+ whichever step runs last wins, and the step order is not obvious from any one file."""+ offenders = {}+ for path in sorted(REQ_ROOT.rglob("*.txt")):+ if path == PIN_FILE:+ continue+ named = [line for line in _requirements(path) if line.lower().startswith("diffusers")]+ if named:+ offenders[str(path.relative_to(REPO_ROOT))] = named+ assert not offenders, (+ f"diffusers is requirement-listed outside diffusers-pin.txt: {offenders}. "+ f"Move it into the pin file; base.txt in particular is skipped entirely by install.sh."+ )+++def test_the_pin_step_is_not_gated_by_skip_base_or_no_torch():+ """The whole bug in one assertion. base.txt's step lives under `if skip_base: pass`,+ so it never runs on install.sh; the pin's step has to sit at function top level,+ outside every conditional, or it inherits the same hole."""+ tree = ast.parse(STACK.read_text(encoding = "utf-8"))++ def _installs_pin(node: ast.AST) -> bool:+ for call in ast.walk(node):+ if not isinstance(call, ast.Call):+ continue+ if getattr(call.func, "id", None) != "pip_install":+ continue+ for kw in call.keywords:+ if kw.arg == "req" and "diffusers-pin.txt" in ast.dump(kw.value):+ return True+ return False++ found = False+ for func in ast.walk(tree):+ if not isinstance(func, ast.FunctionDef):+ continue+ for stmt in func.body: # top level of the function only, no if/else nesting+ if _installs_pin(stmt):+ found = True+ assert found, (+ "no unconditional pip_install of diffusers-pin.txt found at the top level of any "+ "function in install_python_stack.py. Nested under an `if`, the pin repeats the "+ "base.txt bug: applied on `unsloth studio update`, skipped on a fresh install.sh."+ )+++def test_the_pin_step_runs_after_every_other_requirements_install():+ """Ordering matters: a later `uv pip install -r ...` can re-resolve diffusers back to a+ release. Keeping the pin last means nothing is left that could walk it forward."""+ source = STACK.read_text(encoding = "utf-8")+ pin_at = source.index("diffusers-pin.txt")+ later = [+ name+ for name in (+ "extras.txt",+ "extras-no-deps.txt",+ "studio.txt",+ "base.txt",+ "no-torch-runtime.txt",+ "data-designer-deps.txt",+ "data-designer.txt",+ )+ if source.rfind(name) > pin_at+ ]+ assert not later, f"these requirements files are installed after the diffusers pin: {later}"+++def test_install_sh_still_skips_the_base_step():+ """Guards the premise. If install.sh ever stops setting SKIP_STUDIO_BASE=1 this test+ fails loudly and the comments above (and the pin's separate file) can be revisited,+ rather than quietly describing an installer that no longer behaves that way."""+ assert 'SKIP_STUDIO_BASE="$_SKIP_BASE"' in INSTALL_SH.read_text(encoding = "utf-8")+ assert "_SKIP_BASE=1" in INSTALL_SH.read_text(encoding = "utf-8")+ stack = STACK.read_text(encoding = "utf-8")+ assert "if skip_base:\n pass" in stackdiff --git a/tests/studio/install/test_studio_deps_cli.py b/tests/studio/install/test_studio_deps_cli.pyindex 85d1212b616..7a42aacd382 100644--- a/tests/studio/install/test_studio_deps_cli.py+++ b/tests/studio/install/test_studio_deps_cli.py@@ -47,7 +47,11 @@ _MANIFEST = _load(MANIFEST_PATH, "install_manifest_for_deps_test")def _studio_distributions() -> list:lines = (REQUIREMENTS / "studio.txt").read_text(encoding = "utf-8").splitlines()parsed = [_MANIFEST._parse_requirement_line(line) for line in lines]- return [name for name, _, _ in (p for p in parsed if p is not None)]+ return [+ name+ for name, marker, _ in (p for p in parsed if p is not None)+ if _MANIFEST._marker_applies(marker)+ ]def _studio_distribution_versions() -> dict:@@ -56,7 +60,9 @@ def _studio_distribution_versions() -> dict:for parsed in (_MANIFEST._parse_requirement_line(line) for line in lines):if parsed is None:continue- name, _marker, specifier = parsed+ name, marker, specifier = parsed+ if not _MANIFEST._marker_applies(marker):+ continueversion = "1.0.0"for part in specifier.split(","):if part.startswith("=="):diff --git a/tests/studio/install/test_studio_extra_matches_requirements.py b/tests/studio/install/test_studio_extra_matches_requirements.pyindex 83988ce64ec..e4c16e88907 100644--- a/tests/studio/install/test_studio_extra_matches_requirements.py+++ b/tests/studio/install/test_studio_extra_matches_requirements.py@@ -57,6 +57,18 @@ def test_studio_extra_exists():)+def test_huggingface_extra_contains_no_diffusers_vcs_reference():+ from packaging.requirements import Requirement++ entries = _load_pyproject()["project"]["optional-dependencies"]["huggingfacenotorch"]+ diffusers = [Requirement(entry) for entry in entries if Requirement(entry).name == "diffusers"]+ assert diffusers+ assert all(requirement.url is None for requirement in diffusers), (+ "PyPI rejects VCS direct references in uploaded Requires-Dist metadata; "+ "keep temporary Diffusers commit pins in Studio installer requirement files."+ )++def test_studio_extra_matches_requirements_file():extras = _load_pyproject()["project"]["optional-dependencies"]extra = sorted(_normalise(entry) for entry in extras["studio"])