Skip to content

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

Studio: image-to-video for Wan2.2-TI2V-5B and LTX-2 / LTX-2.3 (#13378)

Daniel Han10dc580cc74d
diff --git a/studio/backend/core/inference/diffusion_bg_compile.py b/studio/backend/core/inference/diffusion_bg_compile.py
index f8cb9ef7d05..bf0f06097f9 100644
--- a/studio/backend/core/inference/diffusion_bg_compile.py
+++ b/studio/backend/core/inference/diffusion_bg_compile.py
@@ -32,6 +32,9 @@ _FORCE_EAGER: contextvars.ContextVar[bool] = contextvars.ContextVar(
_NO_CAPTURE: contextvars.ContextVar[bool] = contextvars.ContextVar(
"unsloth_diffusion_no_capture", default = False
)
+_NO_RECORD: contextvars.ContextVar[bool] = contextvars.ContextVar(
+ "unsloth_diffusion_no_record", default = False
+)
def enabled() -> bool:
@@ -55,6 +58,15 @@ def capture_suppressed() -> bool:
return _NO_CAPTURE.get()
+def no_record():
+ token = _NO_RECORD.set(True)
+ try:
+ yield
+ finally:
+ _NO_RECORD.reset(token)
+
+
@contextlib.contextmanager
def force_eager(on: bool = True):
token = _FORCE_EAGER.set(bool(on))
@@ -157,7 +169,12 @@ class BackgroundCompile:
pass
def _record(self, module: Any, args: tuple, kwargs: dict) -> None:
- if not eager_forced() or len(self.samples) >= self.max_samples or self.state != "recording":
+ if (
+ not eager_forced()
+ or _NO_RECORD.get()
+ or len(self.samples) >= self.max_samples
+ or self.state != "recording"
+ ):
return None
try:
import torch
@@ -245,6 +262,14 @@ class BackgroundCompile:
self._thread.start()
return True
+ def abandon(self, reason: str) -> bool:
+ """Give up while still recording, so the next render compiles inline. False once a compile started or ended."""
+ with self._lock:
+ if self.state != "recording":
+ return False
+ self._finish("failed", reason)
+ return True
+
def _finish(
self,
state: str,
diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.py
index 6c2b9135398..c10bd6a1282 100644
--- a/studio/backend/core/inference/video.py
+++ b/studio/backend/core/inference/video.py
@@ -218,6 +218,12 @@ from .video_families import (
video_family_prequant_repo,
video_family_prequant_resident_gb,
video_family_prequant_schemes,
+ first_frame_canvas,
+ video_checkpoint_refusal,
+ video_family_accepts_first_frame,
+ video_family_accepts_last_frame,
+ video_family_uses_i2v_pipeline,
+ video_i2v_call_kwargs,
)
from .video_frames import uint8_video_frames
from .video_minimax_h3 import (
@@ -1049,6 +1055,39 @@ def _refuse_non_dit_pick(repo_id: str, gguf_filename: Optional[str], page: str)
assert_local_pick_is_dit(repo_id, gguf_filename, page)
+def _i2v_pipeline_available(name: Optional[str]) -> bool:
+ from .video_i2v import i2v_pipeline_available
+ return i2v_pipeline_available(name)
+
+
+def _i2v_state_call_kwargs(fam: VideoFamily, state: Any) -> dict[str, Any]:
+ return video_i2v_call_kwargs(
+ fam,
+ state.variant_id,
+ state.gguf_filename,
+ state.display_repo_id,
+ state.repo_id,
+ state.base_repo,
+ )
+
+
+def _settle_bg_compile(bg: Any, *, i2v: bool) -> None:
+ if not i2v:
+ bg.note_eager_generation()
+ bg.kick()
+ elif not bg.kick():
+ # An image-to-video render records nothing; without this an i2v-only session never leaves eager.
+ bg.abandon("an image-to-video render records no compile sample")
+
+
+def assert_first_frame_pipeline_available(fam: VideoFamily) -> None:
+ if video_family_uses_i2v_pipeline(fam) and not _i2v_pipeline_available(fam.i2v_pipeline_class):
+ raise ValueError(
+ f"{fam.name} needs diffusers' {fam.i2v_pipeline_class} for a first frame, which this "
+ "install does not have. Update Unsloth to get a newer diffusers."
+ )
+
+
def _refuse_local_ltx25_pipeline(repo_id: str, gguf_filename: Optional[str]) -> None:
if not gguf_filename:
assert_local_pipeline_not_ltx25(repo_id)
@@ -2752,6 +2791,10 @@ 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."
)
+ # Network-free, so refused before any eviction.
+ refusal = video_checkpoint_refusal(fam, repo_id, display_repo_id, gguf_filename)
+ if refusal:
+ raise ValueError(refusal)
# ── 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
@@ -9162,6 +9205,8 @@ class VideoBackend:
bg = getattr(state, "bg_compile", None)
bg_eager = bg is not None and bg.pending()
bg_token = bg_compile._FORCE_EAGER.set(True) if bg_eager else None
+ # Closed in the finally so the pipeline is text-to-video again on return, cancel or failure.
+ i2v_swap = contextlib.ExitStack()
try:
# FIRST, before any device object exists. begin_generate runs this on a fresh daemon thread, so until it
# is pinned the un-indexed state.device below -- the H3 memory probe and every torch.Generator --
@@ -9435,6 +9480,23 @@ class VideoBackend:
self._last_request_shape = request_shape
pipe = state.pipe
+ i2v_extra: dict[str, Any] = {}
+ i2v_active = first_pil is not None and video_family_uses_i2v_pipeline(fam)
+ if i2v_active:
+ from .video_i2v import first_frame_pipeline
+
+ pipe = i2v_swap.enter_context(
+ first_frame_pipeline(
+ pipe,
+ fam.i2v_pipeline_class,
+ config_overrides = dict(getattr(fam, "i2v_pipeline_config", ()) or ()),
+ )
+ )
+ i2v_extra = _i2v_state_call_kwargs(fam, state)
+ request_shape["pipeline"] = type(pipe).__name__
+ if bg_eager:
+ # LTX-2 i2v passes a per-token timestep (t2v: per sample), so it must not seed the compile.
+ i2v_swap.enter_context(bg_compile.no_record())
call_params = inspect.signature(pipe.__call__).parameters
kwargs: dict[str, Any] = {
"prompt": prompt,
@@ -9494,6 +9556,9 @@ class VideoBackend:
# Auto-blocks distinguish omitted conditioning from empty conditioning.
if first_pil is not None:
kwargs["image"] = first_pil
+ for key, value in i2v_extra.items():
+ if key in call_params:
+ kwargs[key] = value
if last_pil is not None:
kwargs["last_image"] = last_pil
if references:
@@ -9801,8 +9866,7 @@ class VideoBackend:
if self._active_generate_cancel is cancel:
self._active_generate_cancel = None
if bg_eager:
- bg.note_eager_generation()
- bg.kick()
+ _settle_bg_compile(bg, i2v = i2v_active)
reclaim_offload_host_memory(state.offload_policy, logger = logger)
return {
"mp4_bytes": mp4_bytes,
@@ -9850,6 +9914,7 @@ class VideoBackend:
_log_failed_generation(request_shape, exc)
raise
finally:
+ i2v_swap.close()
if bg_token is not None:
bg_compile._FORCE_EAGER.reset(bg_token)
with self._lock:
@@ -9870,15 +9935,24 @@ class VideoBackend:
Unsupported keyframes are rejected. Omitting both dimensions matches the source aspect.
"""
validate_video_keyframe_conditioning(
- fam, h3_task, has_keyframes = bool(first_frame or last_frame)
+ fam,
+ h3_task,
+ has_keyframes = bool(first_frame or last_frame),
+ has_last_frame = bool(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
+ # i2v pipelines centre-crop onto the nearest-aspect preset, as the reference workflow does.
+ i2v_pipeline = video_family_uses_i2v_pipeline(fam)
+ if first is not None:
+ assert_first_frame_pipeline_available(fam)
- if (width is None or height is None) and (first is not None or last is not None):
+ if (width is None or height is None) and first is not None and i2v_pipeline:
+ width, height = first_frame_canvas(fam, *first.size)
+ elif (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
@@ -9894,7 +9968,9 @@ class VideoBackend:
height or default_h,
)
# Fit once so both engines condition on identical pixels.
- if first is not None:
+ if first is not None and i2v_pipeline:
+ first = fit_h3_keyframe(first, width, height, anchor = H3_ANCHOR_LAST)
+ elif 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)
@@ -10600,6 +10676,8 @@ class VideoBackend:
"has_audio": False,
"supports_cfg": True,
"supports_keyframes": False,
+ "supports_first_frame": False,
+ "supports_last_frame": False,
"supports_references": False,
"h3_task": None,
"defaults": None,
@@ -10664,6 +10742,15 @@ class VideoBackend:
"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_keyframes above stays MiniMax-H3's contract for older frontends.
+ "supports_first_frame": video_family_accepts_first_frame(fam)
+ and state.h3_task != H3_TASK_REFERENCES
+ and (
+ not video_family_uses_i2v_pipeline(fam)
+ or _i2v_pipeline_available(fam.i2v_pipeline_class)
+ ),
+ "supports_last_frame": video_family_accepts_last_frame(fam)
+ 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": {
@@ -10679,6 +10766,7 @@ class VideoBackend:
# 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,
+ "canvas_from_presets": video_family_uses_i2v_pipeline(fam),
"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.
diff --git a/studio/backend/core/inference/video_families.py b/studio/backend/core/inference/video_families.py
index 783186fbb01..9c1f7e01aa7 100644
--- a/studio/backend/core/inference/video_families.py
+++ b/studio/backend/core/inference/video_families.py
@@ -238,6 +238,15 @@ class VideoFamily:
default_audio_flow_shift: Optional[float] = None
# First/last-frame conditioning: the request may carry keyframe images.
supports_keyframes: bool = False
+ # Diffusers class serving a first-frame request over the loaded pipeline's components (video_i2v).
+ i2v_pipeline_class: Optional[str] = None
+ i2v_pipeline_config: tuple[tuple[str, object], ...] = field(default_factory = tuple)
+ # (identifier regex, ((kwarg, value), ...)); first matching row applies.
+ i2v_call_kwargs: tuple[tuple[str, tuple[tuple[str, object], ...]], ...] = field(
+ default_factory = tuple
+ )
+ # (identifier regex, refusal) for checkpoints the name tokens claim but this family cannot run.
+ unsupported_checkpoints: tuple[tuple[str, str], ...] = field(default_factory = tuple)
# 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.
@@ -255,6 +264,25 @@ def _h3_480p_presets() -> tuple[tuple[int, int], ...]:
return ((864, 480), (480, 864)) # fastest
+# LTX-Video 0.9.x matches ltx-2's "ltx-video"/"ltxv" tokens but is another architecture; names of LTX-2 itself pass.
+_LTX_VIDEO_09_RE = (
+ r"^(?!.*(?<![a-z0-9])ltx[-_ ]?2(?:$|[-_ /.]))"
+ r"(?=.*(?<![a-z0-9])ltx(?:[-_ ]?video|v)(?:$|[-_ /.](?!2(?:$|[-_ /.]|\.\d))))"
+)
+_LTX_VIDEO_09_REFUSAL = (
+ "This is an LTX-Video 0.9.x checkpoint, a different architecture from LTX-2 that Studio does not "
+ "run. Load LTX-2 or LTX-2.3 instead (for example unsloth/LTX-2.3-GGUF)."
+)
+# Last path segment of each identifier only: an owner or parent folder named i2v does not make a checkpoint I2V.
+_HV15_I2V_RE = r"(?<![a-z0-9])i2v(?![a-z0-9])(?=[^/\\|]*[/\\]*\s*(?:$|\|))"
+_HV15_I2V_REFUSAL = (
+ "This is a HunyuanVideo-1.5 image-to-video checkpoint. It needs its own image-conditioned "
+ "transformer and SigLIP image encoder, which Studio does not load yet. Load a HunyuanVideo-1.5 "
+ "text-to-video checkpoint (hunyuanvideo-community/HunyuanVideo-1.5-Diffusers-480p_t2v or "
+ "720p_t2v) instead."
+)
+
+
_FAMILIES: tuple[VideoFamily, ...] = (
VideoFamily(
name = "minimax-h3",
@@ -376,6 +404,10 @@ _FAMILIES: tuple[VideoFamily, ...] = (
cudnn_benchmark = False,
# Block RMSNorm (hidden 4096) R0_BLOCK 4096 vs 2048 tie on B200: 3 of 6 cold servers rendered another clip.
filter_reduction_configs = True,
+ i2v_pipeline_class = "LTX2ImageToVideoPipeline",
+ # LTX-2.3's reference workflow re-compresses the frame at CRF 18; LTX-2.0 keeps diffusers' 33.
+ i2v_call_kwargs = ((r"ltx[-_ ]?2[-_.]?3(?![0-9])", (("image_crf", 18),)),),
+ unsupported_checkpoints = ((_LTX_VIDEO_09_RE, _LTX_VIDEO_09_REFUSAL),),
),
# Wan2.2-TI2V-5B (diffusers >= 0.35, verified on 0.39): ~5B single-stream DiT (UMT5 encoder), no audio. Its VAE's
# temporal compression 4 gives valid frame counts 4k+1. Defaults 20 steps / CFG 5 (ComfyUI's template).
@@ -416,6 +448,8 @@ _FAMILIES: tuple[VideoFamily, ...] = (
fp16_guard = "native",
# Byte-identical mirror of QuantStack/Wan2.2-TI2V-5B-GGUF (13 quants + companion VAE).
gguf_repo = "unsloth/Wan2.2-TI2V-5B-GGUF",
+ # expand_timesteps on the loaded config keeps the first-frame latent clean.
+ i2v_pipeline_class = "WanImageToVideoPipeline",
),
# Wan2.2-T2V-A14B (diffusers >= 0.35, verified on 0.39): the dual-expert MoE. Both transformers are
# WanTransformer3DModel with boundary_ratio 0.875; high-noise steps route through transformer, low-noise through
@@ -515,6 +549,7 @@ _FAMILIES: tuple[VideoFamily, ...] = (
pipeline_class = "HunyuanVideo15Pipeline",
transformer_class = "HunyuanVideo15Transformer3DModel",
base_repo = "hunyuanvideo-community/HunyuanVideo-1.5-Diffusers-480p_t2v",
+ unsupported_checkpoints = ((_HV15_I2V_RE, _HV15_I2V_REFUSAL),),
prequant_repos = (("nvfp4", "unsloth/HunyuanVideo-1.5-NVFP4"),),
prequant_filenames = (("nvfp4", "HunyuanVideo-1.5-Diffusers-480p_t2v-NVFP4.pt"),),
prequant_resident_gb_by_scheme = (("nvfp4", 4.8),),
@@ -548,6 +583,7 @@ _FAMILIES: tuple[VideoFamily, ...] = (
pipeline_class = "HunyuanVideo15Pipeline",
transformer_class = "HunyuanVideo15Transformer3DModel",
base_repo = "hunyuanvideo-community/HunyuanVideo-1.5-Diffusers-720p_t2v",
+ unsupported_checkpoints = ((_HV15_I2V_RE, _HV15_I2V_REFUSAL),),
# RTN, not GPTQ: the 720p transformer is separately trained; 480p corrections do not apply.
prequant_repos = (("nvfp4", "unsloth/HunyuanVideo-1.5-NVFP4"),),
prequant_filenames = (("nvfp4", "HunyuanVideo-1.5-Diffusers-720p_t2v-NVFP4.pt"),),
@@ -958,8 +994,81 @@ def validate_video_request_shape(
)
+def video_family_accepts_first_frame(fam: VideoFamily) -> bool:
+ return bool(
+ getattr(fam, "supports_keyframes", False) or getattr(fam, "i2v_pipeline_class", None)
+ )
+
+
+def video_family_accepts_last_frame(fam: VideoFamily) -> bool:
+ return bool(getattr(fam, "supports_keyframes", False))
+
+
+def video_family_uses_i2v_pipeline(fam: VideoFamily) -> bool:
+ return bool(getattr(fam, "i2v_pipeline_class", None)) and not getattr(
+ fam, "supports_keyframes", False
+ )
+
+
+def _identifier_blob(identifiers: tuple[Optional[str], ...]) -> list[str]:
+ return [str(i).strip().lower() for i in identifiers if i and str(i).strip()]
+
+
+def video_checkpoint_refusal(fam: VideoFamily, *identifiers: Optional[str]) -> Optional[str]:
+ """Identifiers are joined into one line so an LTX-2.3 filename excuses an ``ltx-video`` folder; the last segment
+ of the most specific identifier is also judged alone, so an LTX-2 folder cannot excuse an LTX-Video 0.9 file."""
+ names = _identifier_blob(identifiers)
+ joined = " | ".join(names)
+ pick = os.path.basename(names[-1].replace("\\", "/").rstrip("/")) if names else ""
+ for entry in getattr(fam, "unsupported_checkpoints", ()) or ():
+ if not isinstance(entry, (tuple, list)) or len(entry) != 2:
+ continue
+ pattern, message = entry
+ try:
+ if any(text and re.search(pattern, text) for text in (pick, joined)):
+ return str(message)
+ except re.error:
+ continue
+ return None
+
+
+def video_i2v_call_kwargs(fam: VideoFamily, *identifiers: Optional[str]) -> dict[str, object]:
+ names = _identifier_blob(identifiers)
+ for entry in getattr(fam, "i2v_call_kwargs", ()) or ():
+ if not isinstance(entry, (tuple, list)) or len(entry) != 2:
+ continue
+ pattern, pairs = entry
+ try:
+ if any(re.search(pattern, name) for name in names):
+ return {str(k): v for k, v in pairs}
+ except (re.error, TypeError, ValueError):
+ continue
+ return {}
+
+
+def first_frame_canvas(
+ fam: VideoFamily, aspect_width: float, aspect_height: float
+) -> tuple[int, int]:
+ """Nearest-aspect preset in log space; ties keep table order so the family default wins."""
+ import math
+
+ if aspect_width <= 0 or aspect_height <= 0:
+ raise ValueError(
+ f"The first frame has no usable aspect ratio ({aspect_width}x{aspect_height})."
+ )
+ presets = tuple((int(w), int(h)) for w, h in fam.resolution_presets)
+ if not presets:
+ return snap_video_size(fam, int(aspect_width), int(aspect_height))
+ target = math.log(aspect_width / aspect_height)
+ return min(presets, key = lambda wh: abs(math.log(wh[0] / wh[1]) - target))
+
+
def validate_video_keyframe_conditioning(
- fam: VideoFamily, h3_task: Optional[str], *, has_keyframes: bool
+ fam: VideoFamily,
+ h3_task: Optional[str],
+ *,
+ has_keyframes: bool,
+ has_last_frame: bool = False,
) -> None:
"""Raise ``ValueError`` when a checkpoint cannot take the keyframes a request supplies.
@@ -968,14 +1077,16 @@ def validate_video_keyframe_conditioning(
one. Without that, an auto-switch evicts a working pipeline and spends minutes loading a
target for a request that was already known to be unservable.
"""
- if not has_keyframes:
+ if not (has_keyframes or has_last_frame):
return
from .video_minimax_h3 import H3_TASK_REFERENCES
- if not fam.supports_keyframes:
+ if not video_family_accepts_first_frame(fam):
raise ValueError(
f"{fam.name} generates from the prompt alone; it takes no first or last frame."
)
+ if has_last_frame and not video_family_accepts_last_frame(fam):
+ raise ValueError(f"{fam.name} animates from a first frame only; it takes no last frame.")
if h3_task == H3_TASK_REFERENCES:
raise ValueError(
"The MiniMax-H3 checkpoint is the Ref2VA partition, which conditions on references "
diff --git a/studio/backend/core/inference/video_i2v.py b/studio/backend/core/inference/video_i2v.py
new file mode 100644
index 00000000000..d9e9199f650
--- /dev/null
+++ b/studio/backend/core/inference/video_i2v.py
@@ -0,0 +1,195 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Run a first-frame render by swapping the loaded pipeline's class to its image-to-video class.
+
+Not ``from_pipe``: it casts every shared module to float32 (undoing fp32-VAE / bf16-DiT, GGUF,
+torchao, offload hooks) and builds a second object lacking what Studio set on the loaded one.
+"""
+
+from __future__ import annotations
+
+import contextlib
+import inspect
+import logging
+import threading
+from typing import Any, Iterator, Optional
+
+logger = logging.getLogger(__name__)
+
+_MISSING = object()
+# The per-backend generate lock does not cover a second backend holding the same pipeline.
+_SWAP_LOCK = threading.RLock()
+
+
+def resolve_i2v_pipeline_class(name: str) -> type:
+ import diffusers
+
+ from .ltx2_import_compat import ensure_ltx2_pipelines_importable, is_ltx2_pipeline_class
+
+ if is_ltx2_pipeline_class(name):
+ ensure_ltx2_pipelines_importable(logger)
+ cls = getattr(diffusers, name, None)
+ if cls is None:
+ raise ValueError(
+ f"This diffusers build has no {name}, which image-to-video for this model needs. "
+ "Update Unsloth to get a newer diffusers."
+ )
+ return cls
+
+
+def i2v_pipeline_available(name: Optional[str]) -> bool:
+ """Never raises: a missing class must read as "no first frame", not a 500."""
+ if not name:
+ return False
+ try:
+ import diffusers
+ except Exception: # noqa: BLE001
+ return False
+ key = (id(diffusers), name)
+ cached = _AVAILABLE.get(key)
+ if cached is None:
+ try:
+ resolve_i2v_pipeline_class(name)
+ cached = True
+ except Exception: # noqa: BLE001 -- an absent or unimportable class is simply unavailable
+ cached = False
+ _AVAILABLE[key] = cached
+ return cached
+
+
+_AVAILABLE: dict[tuple[int, str], bool] = {}
+
+
+def _init_kwargs(pipe: Any, cls: type, config_overrides: dict[str, Any]) -> dict[str, Any]:
+ params = inspect.signature(cls.__init__).parameters
+ components = dict(getattr(pipe, "components", {}) or {})
+ config = dict(getattr(pipe, "config", {}) or {})
+ kwargs: dict[str, Any] = {}
+ missing = []
+ for name, param in params.items():
+ if name == "self" or param.kind in (param.VAR_POSITIONAL, param.VAR_KEYWORD):
+ continue
+ if name in config_overrides:
+ kwargs[name] = config_overrides[name]
+ elif name in components:
+ kwargs[name] = components[name]
+ elif name in config and not name.startswith("_"):
+ kwargs[name] = config[name]
+ elif param.default is inspect.Parameter.empty:
+ missing.append(name)
+ if missing:
+ raise ValueError(
+ f"The loaded {type(pipe).__name__} has no {', '.join(sorted(missing))}, which "
+ f"{cls.__name__} needs, so this model cannot take a first frame."
+ )
+ return kwargs
+
+
+def i2v_instance_state(
+ pipe: Any,
+ cls: type,
+ config_overrides: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ template = cls(**_init_kwargs(pipe, cls, dict(config_overrides or {})))
+ own = pipe.__dict__
+ return {k: v for k, v in template.__dict__.items() if own.get(k, _MISSING) is not v}
+
+
+def first_frame_pipeline(
+ pipe: Any,
+ class_name: Optional[str],
+ *,
+ config_overrides: Optional[dict[str, Any]] = None,
+) -> Iterator[Any]:
+ if not class_name:
+ yield pipe
+ return
+ cls = resolve_i2v_pipeline_class(class_name)
+ if isinstance(pipe, cls):
+ yield pipe
+ return
+ original_cls = type(pipe)
+ with _SWAP_LOCK:
+ overlay = i2v_instance_state(pipe, cls, config_overrides)
+ saved = {k: pipe.__dict__.get(k, _MISSING) for k in overlay}
+ pipe.__dict__.update(overlay)
+ try:
+ pipe.__class__ = cls
+ except TypeError:
+ _restore(pipe, saved)
+ raise
+ try:
+ with _offload_vae_after_encode(pipe):
+ yield pipe
+ finally:
+ pipe.__class__ = original_cls
+ _carry_component_registrations(pipe, overlay, saved)
+ _restore(pipe, saved)
+
+
+def _offload_vae_after_encode(pipe: Any) -> Iterator[None]:
+ """Model offload chains vae after the transformer (the t2v order), so the first-frame encode would leave the VAE
+ resident through denoising; send it back once the encode returns."""
+ vae = getattr(pipe, "vae", None)
+ encode = getattr(vae, "encode", None)
+ if not getattr(pipe, "_all_hooks", None) or not callable(encode):
+ yield
+ return
+ try:
+ from accelerate.hooks import CpuOffload
+ except Exception: # noqa: BLE001 -- no accelerate, no offload hooks
+ yield
+ return
+ own = vae.__dict__.get("encode", _MISSING)
+
+ def _encode(*args: Any, **kwargs: Any) -> Any:
+ try:
+ return encode(*args, **kwargs)
+ finally:
+ hook = getattr(vae, "_hf_hook", None)
+ if isinstance(hook, CpuOffload):
+ hook.init_hook(vae)
+
+ vae.__dict__["encode"] = _encode
+ try:
+ yield
+ finally:
+ if vae.__dict__.get("encode") is _encode:
+ if own is _MISSING:
+ del vae.__dict__["encode"]
+ else:
+ vae.__dict__["encode"] = own
+
+
+def _carry_component_registrations(
+ pipe: Any, overlay: dict[str, Any], saved: dict[str, Any]
+) -> None:
+ """Components assigned mid-render register into the overlaid config; copy them to the restored one."""
+ live = pipe.__dict__.get("_internal_dict")
+ template = overlay.get("_internal_dict")
+ original = saved.get("_internal_dict", _MISSING)
+ if live is None or live is template or original is _MISSING or original is None:
+ return
+ try:
+ changed = {
+ k: v
+ for k, v in dict(live).items()
+ if k in original
+ and (template is None or template.get(k, _MISSING) != v)
+ and original[k] != v
+ }
+ if changed:
+ saved["_internal_dict"] = type(original)({**dict(original), **changed})
+ except Exception: # noqa: BLE001 -- bookkeeping only; never fail the render over it
+ logger.debug("video_i2v: could not carry component registrations back", exc_info = True)
+
+
+def _restore(pipe: Any, saved: dict[str, Any]) -> None:
+ for key, value in saved.items():
+ if value is _MISSING:
+ pipe.__dict__.pop(key, None)
+ else:
+ pipe.__dict__[key] = value
diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.py
index 9f78b49cab7..daf5fd3394e 100644
--- a/studio/backend/models/inference.py
+++ b/studio/backend/models/inference.py
@@ -6152,21 +6152,23 @@ 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.
+ # Bounded so one request cannot buffer a multi-GB payload; ~32 MiB fits a 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.",
+ description = "Base64/data-URL image the clip starts from (image-to-video). With width "
+ "and height omitted it picks the canvas: MiniMax-H3 matches its aspect and stretches it "
+ "on; Wan2.2-TI2V-5B and LTX-2 take the resolution preset nearest its aspect and "
+ "centre-crop it on. Omit for text-to-video. Rejected by a family that takes no first "
+ "frame (status supports_first_frame).",
)
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.",
+ description = "Base64/data-URL image the clip ends on (MiniMax-H3 only, status "
+ "supports_last_frame). 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.
@@ -6418,6 +6420,12 @@ class VideoGenerationDefaults(BaseModel):
canvas_max_pixels: Optional[int] = Field(
None, description = "Area budget of a source-derived canvas, or null (see canvas_short_edge)"
)
+ canvas_from_presets: bool = Field(
+ False,
+ description = "True when a first frame without width/height takes the resolution preset "
+ "nearest its aspect ratio (a declared image-to-video pipeline), instead of the "
+ "canvas_short_edge rule",
+ )
flow_shift: Optional[float] = Field(
None,
description = "Released video-schedule sigma shift, or null when the family does not "
@@ -6517,6 +6525,17 @@ class VideoStatusResponse(BaseModel):
description = "Whether the LOADED checkpoint takes first/last-frame conditioning images "
"(gates the image-to-video controls)",
)
+ supports_first_frame: bool = Field(
+ False,
+ description = "Whether the LOADED checkpoint takes a first_frame (image-to-video): "
+ "MiniMax-H3 keyframes, or a family's declared image-to-video pipeline (Wan2.2-TI2V-5B, "
+ "LTX-2 / LTX-2.3) built over the loaded components",
+ )
+ supports_last_frame: bool = Field(
+ False,
+ description = "Whether the LOADED checkpoint takes a last_frame. Only MiniMax-H3's "
+ "keyframe partition does; the image-to-video pipelines condition on a first frame alone",
+ )
supports_references: bool = Field(
False,
description = "Whether the LOADED checkpoint takes reference images / videos / audio "
diff --git a/studio/backend/routes/video.py b/studio/backend/routes/video.py
index b5d53a72219..14f7ac86d5e 100644
--- a/studio/backend/routes/video.py
+++ b/studio/backend/routes/video.py
@@ -626,7 +626,11 @@ async def generate_video(
resident pipeline and a multi-minute load. The same rules, applied to the target's family
and MiniMax-H3 partition, both of which the pick already determines."""
from core.inference.media_model_index import expected_partition
- from core.inference.video import _detect_load_family, resolve_video_model_kind
+ from core.inference.video import (
+ _detect_load_family,
+ assert_first_frame_pipeline_available,
+ resolve_video_model_kind,
+ )
from core.inference.video_minimax_h3 import is_h3_native
from core.inference.video_families import (
validate_video_flow_controls,
@@ -641,8 +645,13 @@ async def generate_video(
validate_video_request_shape(fam, request.width, request.height, request.num_frames)
h3_task = expected_partition(pick)
validate_video_keyframe_conditioning(
- fam, h3_task, has_keyframes = bool(request.first_frame or request.last_frame)
+ fam,
+ h3_task,
+ has_keyframes = bool(request.first_frame or request.last_frame),
+ has_last_frame = bool(request.last_frame),
)
+ if request.first_frame:
+ assert_first_frame_pipeline_available(fam)
# the engine is only knowable up front where the pick decides it, as an h3 gguf does
kind = resolve_video_model_kind(pick.gguf_filename, pick.model_kind)
engine = "sd_cpp" if is_h3_native(fam, kind) else None
@@ -1704,7 +1713,7 @@ async def _create_openai_video(
def _refuse_unservable_request(pick) -> None:
from core.inference.media_model_index import expected_partition
- from core.inference.video import _detect_load_family
+ from core.inference.video import _detect_load_family, assert_first_frame_pipeline_available
from core.inference.video_families import (
validate_video_keyframe_conditioning,
validate_video_reference_conditioning,
@@ -1736,6 +1745,8 @@ async def _create_openai_video(
validate_video_keyframe_conditioning(
fam, h3_task, has_keyframes = reference is not None and not ref2va
)
+ if reference is not None and not ref2va:
+ assert_first_frame_pipeline_available(fam)
validate_video_reference_conditioning(
fam,
h3_task,
diff --git a/studio/backend/tests/test_openai_videos_route.py b/studio/backend/tests/test_openai_videos_route.py
index fbd3b4aec74..030e6866e35 100644
--- a/studio/backend/tests/test_openai_videos_route.py
+++ b/studio/backend/tests/test_openai_videos_route.py
@@ -1323,3 +1323,44 @@ def test_requested_duration_is_recomputed_for_the_reserved_family(client, backen
job = _create(client, {"prompt": "five seconds", "seconds": "5"}).json()
assert backend.last_generate_kwargs["num_frames"] == 121
assert job["seconds"] == _format_seconds(121 / 24)
+
+
+def _wan_ti2v_switch(switched):
+ async def _fake_switch(model, *, before_switch = None, **_kwargs):
+ pick = types.SimpleNamespace(
+ model_path = "Wan-AI/Wan2.2-TI2V-5B-Diffusers", gguf_filename = None, model_kind = None
+ )
+ if before_switch is not None:
+ before_switch(pick)
+ switched["completed"] = True
+
+ return _fake_switch
+
+
+def test_a_first_frame_without_the_i2v_class_is_refused_before_the_model_switch(
+ client, backend, monkeypatch
+):
+ switched = {"completed": False}
+ monkeypatch.setattr(media_auto_switch, "maybe_auto_switch_media_model", _wan_ti2v_switch(switched))
+ monkeypatch.setattr(video_module, "_i2v_pipeline_available", lambda name: False)
+ png = _reference_image_bytes("PNG")
+ resp = _create(
+ client,
+ {"prompt": "animate", "model": "Wan2.2-TI2V-5B"},
+ {"input_reference": ("frame.png", png, "image/png")},
+ )
+ assert resp.status_code == 400, resp.json()
+ assert "WanImageToVideoPipeline" in resp.json()["error"]["message"]
+ assert switched["completed"] is False
+
+ resp = client.post(
+ "/api/inference/video/generate",
+ json = {
+ "prompt": "animate",
+ "model": "Wan2.2-TI2V-5B",
+ "first_frame": _reference_data_url("PNG", "image/png"),
+ },
+ )
+ assert resp.status_code == 400, resp.json()
+ assert "WanImageToVideoPipeline" in str(resp.json())
+ assert switched["completed"] is False
diff --git a/studio/backend/tests/test_video_backend.py b/studio/backend/tests/test_video_backend.py
index 449db3362e1..c9129e7da48 100644
--- a/studio/backend/tests/test_video_backend.py
+++ b/studio/backend/tests/test_video_backend.py
@@ -6645,13 +6645,203 @@ def test_a_cfg_free_family_records_the_guidance_it_actually_ran(monkeypatch):
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)
+ backend.load_pipeline(
+ "hunyuanvideo-community/HunyuanVideo-1.5-Diffusers-480p_t2v", model_kind = "pipeline"
+ )
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
+ status = backend.status()
+ assert status["supports_first_frame"] is False and status["supports_last_frame"] is False
+
+
+def test_a_first_frame_only_family_refuses_a_last_frame(fake_runtime, tmp_path):
+ backend = VideoBackend()
+ _load_gguf(backend, tmp_path)
+ with pytest.raises(ValueError, match = "first frame only"):
+ backend.begin_generate(prompt = "a sloth", last_frame = _data_url(64, 64))
+ with pytest.raises(ValueError, match = "first frame only"):
+ backend.generate(
+ prompt = "a sloth", first_frame = _data_url(64, 64), last_frame = _data_url(64, 64)
+ )
+ assert backend.generate_progress()["active"] is False
+
+
+# ── image-to-video through a declared i2v pipeline (video_i2v) ───────────────────────────────────
+
+
+class _FakeWanI2VPipe(_FakeWanPipeBase):
+ """WanImageToVideoPipeline fake. Constructed only as the template the swap reads its own
+ instance state from; the render then runs this __call__ on the LOADED pipe object."""
+
+ calls: list = []
+
+ def __init__(
+ self,
+ transformer = None,
+ vae = None,
+ image_encoder = None,
+ image_processor = None,
+ ):
+ self.transformer = transformer
+ self.vae = vae
+ self.image_encoder = image_encoder
+ self.image_processor = image_processor
+ self.video_processor = "i2v-video-processor"
+
+ def __call__(
+ self,
+ *,
+ image = None,
+ prompt = None,
+ negative_prompt = None,
+ num_inference_steps = None,
+ guidance_scale = None,
+ width = None,
+ height = None,
+ num_frames = None,
+ generator = None,
+ callback_on_step_end = None,
+ explode = False,
+ **kwargs,
+ ):
+ self.last_kwargs = {
+ "image": image,
+ "width": width,
+ "height": height,
+ "num_frames": num_frames,
+ "guidance_scale": guidance_scale,
+ **kwargs,
+ }
+ _FakeWanI2VPipe.calls.append(
+ {
+ "self": self,
+ "class": type(self).__name__,
+ "video_processor": getattr(self, "video_processor", None),
+ "image_size": getattr(image, "size", None),
+ }
+ )
+ if explode:
+ raise RuntimeError("i2v render failed")
+ return self._finish(num_inference_steps, num_frames, callback_on_step_end)
+
+
+class _FakeLTX2I2VPipe(_FakePipe):
+ def __init__(self, vae = None):
+ self.vae = vae
+ self.video_processor = "bilinear"
+
+ def __call__(
+ self,
+ *,
+ image = None,
+ image_crf = None,
+ prompt = None,
+ num_frames = None,
+ frame_rate = None,
+ callback_on_step_end = None,
+ **kwargs,
+ ):
+ self.last_kwargs = {"image": image, "image_crf": image_crf, "class": type(self).__name__}
+ frames = [[object() for _ in range(int(num_frames or 1))]]
+ return types.SimpleNamespace(frames = frames, audio = None)
+
+
+def fake_i2v(fake_runtime):
+ diffusers = sys.modules["diffusers"]
+ diffusers.WanImageToVideoPipeline = _FakeWanI2VPipe
+ diffusers.LTX2ImageToVideoPipeline = _FakeLTX2I2VPipe
+ _FakeWanI2VPipe.calls = []
+ yield
+
+
+def test_wan_first_frame_runs_the_i2v_pipeline_over_the_loaded_one(fake_i2v):
+ backend = VideoBackend()
+ status = backend.load_pipeline("Wan-AI/Wan2.2-TI2V-5B-Diffusers", model_kind = "pipeline")
+ assert status["supports_first_frame"] is True
+ assert status["supports_last_frame"] is False
+ assert status["supports_keyframes"] is False # the H3 contract older frontends read
+ pipe = backend._state.pipe
+ t2v_cls = type(pipe)
+ keys_before = set(pipe.__dict__)
+
+ result = backend.generate(prompt = "a car", steps = 2, first_frame = _data_url(1920, 1080))
+
+ call = _FakeWanI2VPipe.calls[-1]
+ # The loaded object ran the i2v __call__ with the i2v instance state, then got its own class back.
+ assert call["self"] is pipe and call["class"] == "_FakeWanI2VPipe"
+ assert call["video_processor"] == "i2v-video-processor"
+ assert type(pipe) is t2v_cls
+ assert "image_encoder" not in pipe.__dict__ and "video_processor" not in pipe.__dict__
+ assert set(pipe.__dict__) - keys_before <= {"last_kwargs"}
+ assert (result["width"], result["height"]) == (1280, 704)
+ assert call["image_size"] == (1280, 704)
+ assert result["conditioning"] == "i2va"
+
+ _FakeWanI2VPipe.calls.clear()
+ backend.generate(prompt = "a car", steps = 2)
+ assert _FakeWanI2VPipe.calls == []
+ assert "image" not in pipe.last_kwargs
+
+
+def test_wan_portrait_first_frame_takes_the_portrait_preset(fake_i2v):
+ backend = VideoBackend()
+ backend.load_pipeline("Wan-AI/Wan2.2-TI2V-5B-Diffusers", model_kind = "pipeline")
+ result = backend.generate(prompt = "p", steps = 2, first_frame = _data_url(832, 1104))
+ assert (result["width"], result["height"]) == (704, 1280)
+ result = backend.generate(
+ prompt = "p", steps = 2, width = 1280, height = 704, first_frame = _data_url(832, 1104)
+ )
+ assert (result["width"], result["height"]) == (1280, 704)
+ assert _FakeWanI2VPipe.calls[-1]["image_size"] == (1280, 704)
+
+
+def test_the_swap_is_undone_when_the_i2v_render_fails(fake_i2v, monkeypatch):
+ backend = VideoBackend()
+ backend.load_pipeline("Wan-AI/Wan2.2-TI2V-5B-Diffusers", model_kind = "pipeline")
+ pipe = backend._state.pipe
+ t2v_cls = type(pipe)
+ from core.inference import video as video_mod
+
+ monkeypatch.setattr(video_mod, "video_i2v_call_kwargs", lambda fam, *ids: {"explode": True})
+ with pytest.raises(RuntimeError, match = "i2v render failed"):
+ backend.generate(prompt = "p", steps = 2, first_frame = _data_url(64, 64))
+ assert type(pipe) is t2v_cls
+ assert "image_encoder" not in pipe.__dict__
+ assert backend.generate_progress()["active"] is False
+
+
+def test_ltx23_first_frame_carries_comfyui_image_crf(fake_i2v, tmp_path):
+ backend = VideoBackend()
+ (tmp_path / "ltx-2.3-22b-distilled-Q4_K_M.gguf").write_bytes(b"weights")
+ backend.load_pipeline(
+ str(tmp_path),
+ gguf_filename = "ltx-2.3-22b-distilled-Q4_K_M.gguf",
+ base_repo = "Lightricks/LTX-2",
+ family_override = "ltx-2",
+ )
+ pipe = backend._state.pipe
+ backend.generate(prompt = "p", steps = 2, first_frame = _data_url(1920, 1080))
+ assert pipe.last_kwargs["class"] == "_FakeLTX2I2VPipe"
+ assert pipe.last_kwargs["image_crf"] == 18
+ assert pipe.last_kwargs["image"].size == (1216, 704)
+ assert type(pipe) is _FakePipe
+
+
+def test_ltx2_first_frame_keeps_the_pipeline_crf_default(fake_i2v, tmp_path):
+ backend = VideoBackend()
+ _load_gguf(backend, tmp_path)
+ pipe = backend._state.pipe
+ backend.generate(prompt = "p", steps = 2, first_frame = _data_url(512, 768))
+ assert pipe.last_kwargs["class"] == "_FakeLTX2I2VPipe"
+ assert pipe.last_kwargs["image_crf"] is None
+ assert pipe.last_kwargs["image"].size == (512, 768)
+ backend.generate(prompt = "p", steps = 2)
+ assert "image" not in pipe.last_kwargs and "class" not in pipe.last_kwargs
def test_begin_generate_rejects_an_undecodable_keyframe(monkeypatch):
@@ -13101,3 +13291,14 @@ def test_untrusted_a14b_pair_checks_the_partner_files_header_too(
base_repo = "Wan-AI/Wan2.2-T2V-A14B-Diffusers",
family_override = "wan2.2-t2v-a14b",
)
+
+
+def test_a_diffusers_without_the_i2v_class_reports_no_first_frame(fake_runtime):
+ # The fake diffusers has WanPipeline but no WanImageToVideoPipeline: the picker must not offer
+ # a start frame, and a request carrying one is refused before it reserves the backend.
+ backend = VideoBackend()
+ status = backend.load_pipeline("Wan-AI/Wan2.2-TI2V-5B-Diffusers", model_kind = "pipeline")
+ assert status["supports_first_frame"] is False
+ with pytest.raises(ValueError, match = "WanImageToVideoPipeline"):
+ backend.begin_generate(prompt = "p", first_frame = _data_url(64, 64))
+ assert backend.generate_progress()["active"] is False
diff --git a/studio/backend/tests/test_video_i2v.py b/studio/backend/tests/test_video_i2v.py
new file mode 100644
index 00000000000..6877c820dc6
--- /dev/null
+++ b/studio/backend/tests/test_video_i2v.py
@@ -0,0 +1,527 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Image-to-video: the family table, the request rules, the detector refusals, and the class swap
+that serves a first frame through the loaded pipeline (video_i2v)."""
+
+from __future__ import annotations
+
+import pytest
+
+from core.inference.video_families import (
+ _FAMILIES,
+ detect_video_family,
+ first_frame_canvas,
+ validate_video_keyframe_conditioning,
+ video_checkpoint_refusal,
+ video_family_accepts_first_frame,
+ video_family_accepts_last_frame,
+ video_family_uses_i2v_pipeline,
+ video_i2v_call_kwargs,
+)
+
+
+def _fam(name):
+ fam = detect_video_family("", override = name)
+ assert fam is not None, name
+ return fam
+
+
+# ── family table ────────────────────────────────────────────────────────────────────────────────
+
+
+ "name,i2v_class",
+ [
+ ("wan2.2-ti2v-5b", "WanImageToVideoPipeline"),
+ ("ltx-2", "LTX2ImageToVideoPipeline"),
+ ],
+)
+def test_declared_families_take_a_first_frame_through_their_i2v_pipeline(name, i2v_class):
+ fam = _fam(name)
+ assert fam.i2v_pipeline_class == i2v_class
+ assert video_family_accepts_first_frame(fam)
+ assert video_family_uses_i2v_pipeline(fam)
+ assert not video_family_accepts_last_frame(fam)
+
+
+def test_h3_keeps_native_keyframes_and_needs_no_i2v_pipeline():
+ fam = _fam("minimax-h3")
+ assert video_family_accepts_first_frame(fam) and video_family_accepts_last_frame(fam)
+ assert not video_family_uses_i2v_pipeline(fam)
+
+
[email protected]("name", ["wan2.2-t2v-a14b", "hunyuanvideo-1.5", "hunyuanvideo-1.5-720p"])
+def test_text_only_families_take_no_frame(name):
+ fam = _fam(name)
+ assert fam.i2v_pipeline_class is None
+ assert not video_family_accepts_first_frame(fam)
+ assert not video_family_accepts_last_frame(fam)
+
+
+def test_i2v_class_is_never_the_t2v_class():
+ # A family naming its own t2v class as the i2v one would "swap" to the same class and pass the image to a
+ # __call__ that ignores it.
+ for fam in _FAMILIES:
+ if fam.i2v_pipeline_class:
+ assert fam.i2v_pipeline_class != fam.pipeline_class
+ assert fam.i2v_pipeline_class.endswith("Pipeline")
+
+
+# ── request validation ──────────────────────────────────────────────────────────────────────────
+
+
+def test_first_frame_accepted_only_where_declared():
+ validate_video_keyframe_conditioning(_fam("wan2.2-ti2v-5b"), None, has_keyframes = True)
+ validate_video_keyframe_conditioning(_fam("ltx-2"), None, has_keyframes = True)
+ for name in ("wan2.2-t2v-a14b", "hunyuanvideo-1.5"):
+ with pytest.raises(ValueError, match = "no first or last frame"):
+ validate_video_keyframe_conditioning(_fam(name), None, has_keyframes = True)
+
+
+def test_last_frame_refused_by_first_frame_only_families():
+ for name in ("wan2.2-ti2v-5b", "ltx-2"):
+ with pytest.raises(ValueError, match = "first frame only"):
+ validate_video_keyframe_conditioning(
+ _fam(name), None, has_keyframes = True, has_last_frame = True
+ )
+ validate_video_keyframe_conditioning(
+ _fam("minimax-h3"), "fl2va", has_keyframes = True, has_last_frame = True
+ )
+
+
+def test_text_to_video_requests_are_never_judged():
+ for fam in _FAMILIES:
+ validate_video_keyframe_conditioning(fam, None, has_keyframes = False)
+
+
+# ── i2v defaults ────────────────────────────────────────────────────────────────────────────────
+
+
+ "name,aspect,expected",
+ [
+ ("wan2.2-ti2v-5b", (1920, 1080), (1280, 704)),
+ ("wan2.2-ti2v-5b", (832, 1104), (704, 1280)),
+ # Square is equally far from both TI2V presets; the family default (first) wins the tie.
+ ("wan2.2-ti2v-5b", (512, 512), (1280, 704)),
+ ("ltx-2", (1920, 1080), (1216, 704)),
+ ("ltx-2", (3, 2), (768, 512)),
+ ("ltx-2", (2, 3), (512, 768)),
+ ("ltx-2", (9, 16), (704, 1216)),
+ ],
+)
+def test_first_frame_canvas_is_the_nearest_aspect_preset(name, aspect, expected):
+ assert first_frame_canvas(_fam(name), *aspect) == expected
+
+
+def test_first_frame_canvas_rejects_a_degenerate_image():
+ with pytest.raises(ValueError):
+ first_frame_canvas(_fam("ltx-2"), 0, 10)
+
+
+def test_ltx23_takes_comfyui_image_crf_and_ltx20_keeps_the_pipeline_default():
+ fam = _fam("ltx-2")
+ assert video_i2v_call_kwargs(fam, "ltx-2.3-22b-distilled", None) == {"image_crf": 18}
+ assert video_i2v_call_kwargs(fam, None, "distilled/ltx-2.3-22b-distilled-Q4_K_M.gguf") == {
+ "image_crf": 18
+ }
+ assert video_i2v_call_kwargs(fam, "Lightricks/LTX-2", "ltx-2-19b-dev.safetensors") == {}
+ assert video_i2v_call_kwargs(_fam("wan2.2-ti2v-5b"), "Wan-AI/Wan2.2-TI2V-5B-Diffusers") == {}
+
+
+# ── detector refusals ───────────────────────────────────────────────────────────────────────────
+
+
+ "ids",
+ [
+ ("Lightricks/LTX-Video",),
+ ("Lightricks/LTX-Video-0.9.7-dev",),
+ ("Lightricks/LTX-Video-0.9.8-13B-distilled",),
+ ("a-r-r-o-w/LTX-Video-0.9.1-diffusers",),
+ ("city96/LTX-Video-gguf", "ltx-video-2b-v0.9-Q4_K_M.gguf"),
+ ("/models", "ltxv-13b-0.9.7-dev-Q4_K_M.gguf"),
+ ],
+)
+def test_ltx_video_09_is_refused_not_built_as_ltx2(ids):
+ fam = detect_video_family("/".join(ids))
+ assert fam is not None and fam.name == "ltx-2" # what the detector claims it as
+ message = video_checkpoint_refusal(fam, *ids)
+ assert message and "LTX-Video 0.9" in message
+
+
+ "ids",
+ [
+ ("Lightricks/LTX-2",),
+ ("Lightricks/LTX-2.3",),
+ ("unsloth/LTX-2.3-GGUF", "distilled/ltx-2.3-22b-distilled-Q4_K_M.gguf"),
+ ("unsloth/LTX-2-FP8",),
+ ("Lightricks/LTX-Video-2",),
+ # A folder named after the old model holding an LTX-2.3 file: the filename names LTX-2.
+ ("/models/ltx-video", "ltx-2.3-22b-dev-Q4_K_M.gguf"),
+ ],
+)
+def test_ltx2_checkpoints_are_not_refused(ids):
+ assert video_checkpoint_refusal(_fam("ltx-2"), *ids) is None
+
+
+ "ids",
+ [
+ ("unsloth/LTX-2.3-GGUF", "ltx-video-2b-v0.9-Q4_K_M.gguf"),
+ ("/models/LTX-2.3", "ltxv-13b-0.9.7-dev-Q4_K_M.gguf"),
+ ("/models/LTX-2/ltxv-2b-0.9.6-distilled",),
+ ("Lightricks/LTX-2", "/models/LTX-2/LTX-Video-0.9.8-13B-distilled.safetensors"),
+ ],
+)
+def test_ltx_video_09_checkpoint_in_an_ltx2_folder_is_still_refused(ids):
+ message = video_checkpoint_refusal(_fam("ltx-2"), *ids)
+ assert message and "LTX-Video 0.9" in message
+
+
+ "repo,family",
+ [
+ ("hunyuanvideo-community/HunyuanVideo-1.5-Diffusers-480p_i2v", "hunyuanvideo-1.5"),
+ ("hunyuanvideo-community/HunyuanVideo-1.5-Diffusers-720p_i2v", "hunyuanvideo-1.5-720p"),
+ (
+ "hunyuanvideo-community/HunyuanVideo-1.5-Diffusers-480p_i2v_step_distilled",
+ "hunyuanvideo-1.5",
+ ),
+ ("someone/hunyuanvideo1.5_i2v_480p-GGUF", "hunyuanvideo-1.5"),
+ ],
+)
+def test_hv15_i2v_weights_are_refused_by_the_t2v_family(repo, family):
+ fam = detect_video_family(repo)
+ assert fam is not None and fam.name == family
+ message = video_checkpoint_refusal(fam, repo)
+ assert message and "image-to-video" in message
+
+
+ "repo",
+ [
+ "hunyuanvideo-community/HunyuanVideo-1.5-Diffusers-480p_t2v",
+ "hunyuanvideo-community/HunyuanVideo-1.5-Diffusers-720p_t2v",
+ "Wan-AI/Wan2.2-TI2V-5B-Diffusers",
+ "unsloth/Wan2.2-TI2V-5B-GGUF",
+ "MiniMaxAI/MiniMax-H3",
+ ],
+)
+def test_supported_checkpoints_are_not_refused(repo):
+ fam = detect_video_family(repo)
+ assert fam is not None
+ assert video_checkpoint_refusal(fam, repo) is None
+
+
+def test_load_validation_refuses_before_any_load():
+ from core.inference.video import VideoBackend
+
+ backend = VideoBackend()
+ with pytest.raises(ValueError, match = "LTX-Video 0.9"):
+ backend.validate_load_request("Lightricks/LTX-Video", model_kind = "pipeline")
+ with pytest.raises(ValueError, match = "image-to-video checkpoint"):
+ backend.validate_load_request(
+ "hunyuanvideo-community/HunyuanVideo-1.5-Diffusers-480p_i2v", model_kind = "pipeline"
+ )
+
+
+# ── the class swap over a real (tiny) diffusers Wan pipeline ────────────────────────────────────
+
+
+def _tiny_wan_pipe():
+ torch = pytest.importorskip("torch")
+ diffusers = pytest.importorskip("diffusers")
+ if not hasattr(diffusers, "WanImageToVideoPipeline"):
+ pytest.skip("diffusers without WanImageToVideoPipeline")
+ torch.manual_seed(0)
+ vae = diffusers.AutoencoderKLWan(
+ base_dim = 3,
+ z_dim = 16,
+ dim_mult = [1, 1, 1, 1],
+ num_res_blocks = 1,
+ temperal_downsample = [False, True, True],
+ )
+ torch.manual_seed(0)
+ transformer = diffusers.WanTransformer3DModel(
+ patch_size = (1, 2, 2),
+ num_attention_heads = 2,
+ attention_head_dim = 12,
+ in_channels = 16,
+ out_channels = 16,
+ text_dim = 32,
+ freq_dim = 256,
+ ffn_dim = 32,
+ num_layers = 2,
+ cross_attn_norm = True,
+ qk_norm = "rms_norm_across_heads",
+ rope_max_seq_len = 32,
+ )
+ scheduler = diffusers.FlowMatchEulerDiscreteScheduler(shift = 7.0)
+ pipe = diffusers.WanPipeline(
+ tokenizer = None,
+ text_encoder = None,
+ vae = vae,
+ scheduler = scheduler,
+ transformer = transformer,
+ expand_timesteps = True, # TI2V-5B's config
+ )
+ return torch, pipe
+
+
+def _render(torch, pipe, **extra):
+ gen = torch.Generator().manual_seed(7)
+ embeds = torch.Generator().manual_seed(3)
+ prompt_embeds = torch.randn(1, 8, 32, generator = embeds)
+ return pipe(
+ prompt_embeds = prompt_embeds,
+ height = 32,
+ width = 32,
+ num_frames = 5,
+ num_inference_steps = 2,
+ guidance_scale = 1.0,
+ generator = gen,
+ output_type = "np",
+ **extra,
+ ).frames[0]
+
+
+def test_class_swap_runs_i2v_over_the_same_modules_and_restores_t2v():
+ from PIL import Image
+
+ from core.inference.video_i2v import first_frame_pipeline
+
+ torch, pipe = _tiny_wan_pipe()
+ t2v_cls = type(pipe)
+ before_dict = dict(pipe.__dict__)
+ params_before = {
+ n: (p.data_ptr(), p.dtype, p.device) for n, p in pipe.transformer.named_parameters()
+ }
+ # Studio state set on the pipeline instance must be visible to the i2v call and survive it.
+ pipe._unsloth_marker = "kept"
+
+ t2v_a = _render(torch, pipe)
+
+ image = Image.new("RGB", (32, 32), (200, 40, 40))
+ with first_frame_pipeline(pipe, "WanImageToVideoPipeline") as i2v:
+ assert i2v is pipe # the same object: nothing was copied
+ assert type(pipe).__name__ == "WanImageToVideoPipeline"
+ assert pipe._unsloth_marker == "kept"
+ assert pipe.config.expand_timesteps is True
+ i2v_out = _render(torch, pipe, image = image)
+ pipe._unsloth_written_during_i2v = 1
+
+ assert type(pipe) is t2v_cls
+ # The overlay (config, processors, image-encoder slots) is gone; the render's own writes stay.
+ assert "image_encoder" not in pipe.__dict__ and "image_processor" not in pipe.__dict__
+ assert pipe.__dict__["_internal_dict"] is before_dict["_internal_dict"]
+ assert pipe.__dict__["video_processor"] is before_dict["video_processor"]
+ assert pipe._unsloth_written_during_i2v == 1
+ for key in ("transformer", "vae", "scheduler"):
+ assert pipe.__dict__[key] is before_dict[key]
+ assert {
+ n: (p.data_ptr(), p.dtype, p.device) for n, p in pipe.transformer.named_parameters()
+ } == params_before
+
+ # Text-to-video after an image-to-video render is bit-identical to before it.
+ t2v_b = _render(torch, pipe)
+ assert (t2v_a == t2v_b).all()
+ assert not (i2v_out == t2v_a).all()
+
+
+def test_class_swap_restores_on_failure():
+ from core.inference.video_i2v import first_frame_pipeline
+
+ _torch, pipe = _tiny_wan_pipe()
+ t2v_cls = type(pipe)
+ keys = set(pipe.__dict__)
+ with pytest.raises(RuntimeError, match = "boom"):
+ with first_frame_pipeline(pipe, "WanImageToVideoPipeline"):
+ raise RuntimeError("boom")
+ assert type(pipe) is t2v_cls
+ assert set(pipe.__dict__) == keys
+
+
+def test_class_swap_is_a_noop_without_a_class():
+ from core.inference.video_i2v import first_frame_pipeline
+ sentinel = object()
+ with first_frame_pipeline(sentinel, None) as got:
+ assert got is sentinel
+
+
+def test_from_pipe_would_upcast_which_is_why_it_is_not_used():
+ """Pins the reason video_i2v does not call DiffusionPipeline.from_pipe: without torch_dtype it
+ casts every shared module to float32, an extra copy of the weights and a different numeric
+ path. If diffusers changes that, the swap is still correct; this test only documents it."""
+ torch, pipe = _tiny_wan_pipe()
+ import diffusers
+
+ pipe.transformer.to(torch.bfloat16)
+ diffusers.WanImageToVideoPipeline.from_pipe(pipe)
+ if next(pipe.transformer.parameters()).dtype == torch.bfloat16:
+ pytest.skip("this diffusers from_pipe no longer upcasts")
+ assert next(pipe.transformer.parameters()).dtype == torch.float32
+
+
+def test_status_schema_carries_the_per_frame_support_and_the_canvas_rule():
+ from models.inference import VideoGenerationDefaults, VideoStatusResponse
+
+ fields = VideoStatusResponse.model_fields
+ assert "supports_first_frame" in fields and "supports_last_frame" in fields
+ assert VideoGenerationDefaults.model_fields["canvas_from_presets"].default is False
+
+
+def test_request_last_frame_route_check_names_first_frame_only():
+ fam = _fam("wan2.2-ti2v-5b")
+ with pytest.raises(ValueError, match = "first frame only"):
+ validate_video_keyframe_conditioning(fam, None, has_keyframes = True, has_last_frame = True)
+
+
+def test_an_unrecorded_render_never_seeds_the_background_compile():
+ from core.inference import diffusion_bg_compile as bgc
+
+ bg = bgc.BackgroundCompile(object())
+ with bgc.force_eager(), bgc.no_record():
+ assert bg._record(None, (), {}) is None
+ assert bg.samples == [] and bg.state == "recording"
+
+
+def test_a_component_assigned_mid_swap_stays_registered_after_it():
+ diffusers = pytest.importorskip("diffusers")
+
+ from core.inference.video_i2v import first_frame_pipeline
+
+ _torch, pipe = _tiny_wan_pipe()
+ with first_frame_pipeline(pipe, "WanImageToVideoPipeline"):
+ pipe.scheduler = diffusers.UniPCMultistepScheduler()
+ assert type(pipe).__name__ == "WanPipeline"
+ assert tuple(pipe.config["scheduler"])[1] == "UniPCMultistepScheduler"
+ assert isinstance(pipe.scheduler, diffusers.UniPCMultistepScheduler)
+ assert "image_encoder" not in pipe.config
+
+
+def test_availability_probe_never_raises():
+ from core.inference.video_i2v import i2v_pipeline_available
+ assert i2v_pipeline_available(None) is False
+ assert i2v_pipeline_available("NoSuchPipelineAnywhere") is False
+
+
+ "ids",
+ [
+ ("/models/i2v/HunyuanVideo-1.5-Diffusers-480p_t2v",),
+ ("i2v-lab/HunyuanVideo-1.5-Diffusers-480p_t2v",),
+ ("C:\\i2v\\HunyuanVideo-1.5-Diffusers-480p_t2v",),
+ ("/models/i2v/hv15", "hunyuanvideo1.5_t2v_480p-Q4_K_M.gguf"),
+ ],
+)
+def test_hv15_i2v_marker_in_an_owner_or_parent_folder_does_not_refuse(ids):
+ assert video_checkpoint_refusal(_fam("hunyuanvideo-1.5"), *ids) is None
+
+
+ "ids",
+ [
+ ("/models/t2v/HunyuanVideo-1.5-Diffusers-480p_i2v/",),
+ ("/models/t2v", "hunyuanvideo1.5_i2v_480p-Q4_K_M.gguf"),
+ ("someone/hunyuanvideo1.5_i2v_480p-GGUF", "hv15-480p-Q4_K_M.gguf"),
+ ],
+)
+def test_hv15_i2v_marker_in_the_checkpoint_name_still_refuses(ids):
+ assert "image-to-video" in (video_checkpoint_refusal(_fam("hunyuanvideo-1.5"), *ids) or "")
+
+
+def test_ltx23_crf_follows_the_declared_base_repo_of_a_neutrally_named_checkpoint():
+ import types
+
+ from core.inference.video import _i2v_state_call_kwargs
+
+ state = types.SimpleNamespace(
+ variant_id = None,
+ gguf_filename = "model.safetensors",
+ display_repo_id = None,
+ repo_id = "/models/finetune",
+ base_repo = "Lightricks/LTX-2.3",
+ )
+ assert _i2v_state_call_kwargs(_fam("ltx-2"), state) == {"image_crf": 18}
+ state.base_repo = "Lightricks/LTX-2"
+ assert _i2v_state_call_kwargs(_fam("ltx-2"), state) == {}
+
+
+def test_an_image_only_session_does_not_leave_the_background_compile_pending():
+ from core.inference import diffusion_bg_compile as bgc
+ from core.inference.video import _settle_bg_compile
+
+ bg = bgc.BackgroundCompile(object())
+ with bgc.force_eager(), bgc.no_record():
+ bg._record(None, (), {})
+ _settle_bg_compile(bg, i2v = True)
+ assert not bg.pending() and bg.state == "failed"
+ assert bg.abandon("again") is False
+
+
+def test_a_text_render_still_kicks_the_background_compile():
+ from core.inference import diffusion_bg_compile as bgc
+ from core.inference.video import _settle_bg_compile
+
+ bg = bgc.BackgroundCompile(object())
+ _settle_bg_compile(bg, i2v = False)
+ assert bg.state == "recording" and bg.eager_generations == 1
+
+
+def test_model_offload_sends_the_vae_back_before_the_first_frame_denoise():
+ from PIL import Image
+
+ from core.inference.video_i2v import first_frame_pipeline
+
+ torch, pipe = _tiny_wan_pipe()
+ pipe.enable_model_cpu_offload(device = "cpu")
+ hook = pipe.vae._hf_hook
+ resident = {"vae": False}
+ pre_forward, init_hook = hook.pre_forward, hook.init_hook
+
+ def _on(module, *args, **kwargs):
+ resident["vae"] = True
+ return pre_forward(module, *args, **kwargs)
+
+ def _off(module):
+ resident["vae"] = False
+ return init_hook(module)
+
+ hook.pre_forward, hook.init_hook = _on, _off
+ seen = []
+ handle = pipe.transformer.register_forward_pre_hook(lambda *_: seen.append(resident["vae"]))
+ try:
+ with first_frame_pipeline(pipe, "WanImageToVideoPipeline"):
+ _render(torch, pipe, image = Image.new("RGB", (32, 32), (200, 40, 40)))
+ assert seen and not any(seen)
+ assert "encode" not in pipe.vae.__dict__
+ finally:
+ handle.remove()
+
+
+def test_model_offload_sends_the_vae_back_when_the_first_frame_encode_raises():
+ from core.inference.video_i2v import first_frame_pipeline
+
+ torch, pipe = _tiny_wan_pipe()
+ pipe.enable_model_cpu_offload(device = "cpu")
+ hook = pipe.vae._hf_hook
+ offloaded = []
+ init_hook = hook.init_hook
+
+ def _off(module):
+ offloaded.append(module)
+ return init_hook(module)
+
+ def _boom(*args, **kwargs):
+ raise RuntimeError("CUDA out of memory")
+
+ hook.init_hook = _off
+ pipe.vae.__dict__["encode"] = _boom
+ with first_frame_pipeline(pipe, "WanImageToVideoPipeline"):
+ with pytest.raises(RuntimeError, match = "out of memory"):
+ pipe.vae.encode(torch.zeros(1))
+ assert offloaded == [pipe.vae]
+ assert pipe.vae.__dict__["encode"] is _boom
diff --git a/studio/backend/tests/test_video_static_skip.py b/studio/backend/tests/test_video_static_skip.py
index 7ad3013b5e9..259b8d511ec 100644
--- a/studio/backend/tests/test_video_static_skip.py
+++ b/studio/backend/tests/test_video_static_skip.py
@@ -247,6 +247,16 @@ def test_auto_skip_leaves_a_keyframe_clip_unskipped(loop_runtime, monkeypatch):
return object(), last, width, height, conditioning
monkeypatch.setattr(VideoBackend, "_resolve_keyframes", staticmethod(with_first_frame))
+
+ # A first frame on Wan2.2-TI2V-5B runs its image-to-video class over the loaded pipe (video_i2v);
+ # the fake runtime only knows the text-to-video one, so give it a class to swap to.
+ class _LoopWanI2V(_LoopWanPipe):
+ def __init__(self, **_components): # the template the swap reads; nothing to set
+ pass
+
+ monkeypatch.setattr(
+ sys.modules["diffusers"], "WanImageToVideoPipeline", _LoopWanI2V, raising = False
+ )
armed = []
import core.inference.video as video_mod
diff --git a/studio/frontend/src/features/video/api.ts b/studio/frontend/src/features/video/api.ts
index 31e6f2ba631..ff447c451b0 100644
--- a/studio/frontend/src/features/video/api.ts
+++ b/studio/frontend/src/features/video/api.ts
@@ -41,6 +41,8 @@ export interface VideoGenerationDefaults {
// Backend-owned keyframe canvas rule, or null when unsupported.
canvas_short_edge?: number | null;
canvas_max_pixels?: number | null;
+ // Image-to-video families without that rule take the preset nearest the first frame's aspect.
+ canvas_from_presets?: boolean;
// Released schedule shifts, or null when unsupported.
flow_shift?: number | null;
audio_flow_shift?: number | null;
@@ -91,6 +93,10 @@ export interface VideoStatus {
supports_cfg: boolean;
// Conditioning supported by the loaded checkpoint.
supports_keyframes?: boolean;
+ // Per keyframe: every image-to-video family takes a first frame; only MiniMax-H3 a last one.
+ // Absent on older backends, which read supports_keyframes for both.
+ supports_first_frame?: boolean;
+ supports_last_frame?: boolean;
supports_references?: boolean;
// Resident MiniMax-H3 denoiser partition, if any.
h3_task?: string | null;
diff --git a/studio/frontend/src/features/video/keyframe-canvas.ts b/studio/frontend/src/features/video/keyframe-canvas.ts
index f3139a83ee4..53ace3e3f9b 100644
--- a/studio/frontend/src/features/video/keyframe-canvas.ts
+++ b/studio/frontend/src/features/video/keyframe-canvas.ts
@@ -1,11 +1,34 @@
// 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";
+import type { VideoGenerationDefaults, VideoStatus } from "./api";
/** Sentinel for deriving resolution from the keyframe aspect ratio. */
export const MATCH_SOURCE_RESOLUTION = -1;
+/** The preset whose aspect ratio is nearest the picture's, compared in log space so 2:1 and 1:2 are
+ * equally far from square; ties keep the list order, so the family default wins. Mirrors the
+ * backend's first_frame_canvas. */
+export function nearestPresetCanvas(
+ aspectWidth: number,
+ aspectHeight: number,
+ presets: ReadonlyArray<readonly [number, number]>,
+): [number, number] | null {
+ if (aspectWidth <= 0 || aspectHeight <= 0 || presets.length === 0) return null;
+ const target = Math.log(aspectWidth / aspectHeight);
+ let best: readonly [number, number] | null = null;
+ let bestDistance = Number.POSITIVE_INFINITY;
+ for (const preset of presets) {
+ if (preset[0] <= 0 || preset[1] <= 0) continue;
+ const distance = Math.abs(Math.log(preset[0] / preset[1]) - target);
+ if (distance < bestDistance) {
+ best = preset;
+ bestDistance = distance;
+ }
+ }
+ return best ? [best[0], best[1]] : null;
+}
+
/** 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(
@@ -16,6 +39,9 @@ export function matchedCanvas(
const shortEdge = defaults?.canvas_short_edge;
const maxPixels = defaults?.canvas_max_pixels;
const multiple = defaults?.resolution_multiple;
+ if ((!shortEdge || !maxPixels) && defaults?.canvas_from_presets) {
+ return nearestPresetCanvas(aspectWidth, aspectHeight, defaults.resolution_presets ?? []);
+ }
if (!shortEdge || !maxPixels || !multiple) return null;
if (aspectWidth <= 0 || aspectHeight <= 0) return null;
const ratio = aspectWidth / aspectHeight;
@@ -31,3 +57,17 @@ export function matchedCanvas(
const snap = (value: number) => Math.max(multiple, Math.round(value / multiple) * multiple);
return [snap(width), snap(height)];
}
+
+/** Which keyframes the loaded checkpoint takes. Newer backends report each one; an older backend
+ * only has supports_keyframes, which meant MiniMax-H3's first-and/or-last pair. */
+export function keyframeSupport(
+ status: Pick<VideoStatus, "supports_keyframes" | "supports_first_frame" | "supports_last_frame">
+ | null
+ | undefined,
+): { first: boolean; last: boolean } {
+ const legacy = status?.supports_keyframes === true;
+ return {
+ first: typeof status?.supports_first_frame === "boolean" ? status.supports_first_frame : legacy,
+ last: typeof status?.supports_last_frame === "boolean" ? status.supports_last_frame : legacy,
+ };
+}
diff --git a/studio/frontend/src/features/video/video-page.tsx b/studio/frontend/src/features/video/video-page.tsx
index ea70dad9552..581dc7c57cb 100644
--- a/studio/frontend/src/features/video/video-page.tsx
+++ b/studio/frontend/src/features/video/video-page.tsx
@@ -183,7 +183,7 @@ import { loadGalleryUntil } from "@/lib/gallery-deep-link";
import { subscribeModelEjected } from "@/lib/model-lifecycle-events";
import { BlobUrlCache } from "@/lib/blob-url-cache";
-import { MATCH_SOURCE_RESOLUTION, matchedCanvas } from "./keyframe-canvas";
+import { MATCH_SOURCE_RESOLUTION, keyframeSupport, matchedCanvas } from "./keyframe-canvas";
import { hasReferenceCapacity } from "./reference-budget";
import {
applyReferenceImageCrop,
@@ -1312,9 +1312,13 @@ function VideoGenerator({
);
}, [resolutionPresets.length]);
- const supportsKeyframes = status?.supports_keyframes === true;
+ const { first: supportsFirstFrame, last: supportsLastFrame } = keyframeSupport(status);
+ const supportsKeyframes = supportsFirstFrame || supportsLastFrame;
// The keyframe the canvas follows: the first when there is one, else the last, matching the backend.
const canvasKeyframe = firstFrame ?? lastFrame;
+ // Only MiniMax-H3 derives its canvas from the aspect itself and refuses ratios past 1:4 / 4:1;
+ // the preset families always find a nearest preset.
+ const canvasRefusesAspect = !status?.defaults?.canvas_from_presets;
const supportsReferences = status?.supports_references === true;
const hasReferenceRoom = hasReferenceCapacity(
@@ -1327,11 +1331,9 @@ function VideoGenerator({
// Drop conditioning that the newly loaded partition cannot accept.
useEffect(() => {
- if (status?.loaded && !supportsKeyframes) {
- setFirstFrame(null);
- setLastFrame(null);
- }
- }, [status?.loaded, supportsKeyframes]);
+ if (status?.loaded && !supportsFirstFrame) setFirstFrame(null);
+ if (status?.loaded && !supportsLastFrame) setLastFrame(null);
+ }, [status?.loaded, supportsFirstFrame, supportsLastFrame]);
useEffect(() => {
if (status?.loaded && !supportsReferences) {
setReferenceImages([]);
@@ -3462,8 +3464,8 @@ function VideoGenerator({
steps,
guidance: status?.supports_cfg !== false ? guidance : undefined,
seed: resolvedSeed,
- first_frame: supportsKeyframes ? firstFrame ?? undefined : undefined,
- last_frame: supportsKeyframes ? lastFrame ?? undefined : undefined,
+ first_frame: supportsFirstFrame ? firstFrame ?? undefined : undefined,
+ last_frame: supportsLastFrame ? lastFrame ?? undefined : undefined,
reference_images:
supportsReferences && referenceImages.length > 0
? referenceImageDataUrls(referenceImages)
@@ -3519,7 +3521,8 @@ function VideoGenerator({
fps,
steps,
status?.supports_cfg,
- supportsKeyframes,
+ supportsFirstFrame,
+ supportsLastFrame,
firstFrame,
lastFrame,
supportsReferences,
@@ -3855,9 +3858,11 @@ function VideoGenerator({
<p className="text-xs leading-snug text-muted-foreground">
{supportsReferences
? "Generate a video from a prompt and reference pictures, videos or audio"
- : supportsKeyframes
+ : supportsLastFrame
? "Generate a video from a prompt, or from a start and end frame"
- : "Generate a video from a prompt"}
+ : supportsFirstFrame
+ ? "Generate a video from a prompt, or animate a start frame"
+ : "Generate a video from a prompt"}
</p>
</div>
@@ -3889,37 +3894,40 @@ function VideoGenerator({
</Field>
{supportsKeyframes && (
- <div className="grid gap-2">
+ <div className="grid gap-2" data-testid="video-keyframes">
<span className="flex items-center gap-1 text-xs font-medium text-muted-foreground">
- Start and end frame
+ {supportsLastFrame ? "Start and end frame" : "Start 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.
+ {supportsLastFrame
+ ? "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."
+ : "Optional. The clip starts on this picture and animates it (image-to-video); without one it is text-to-video. Match source picks the resolution preset closest to the picture's shape, and the picture is centre-cropped onto it."}
</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 className={supportsLastFrame ? "grid grid-cols-2 gap-2" : "grid gap-2"}>
+ {supportsFirstFrame && (
+ <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>
+ )}
+ {supportsLastFrame && (
+ <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 && (
+ {canvasKeyframe && !matchedResolution && canvasRefusesAspect && (
// 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
diff --git a/studio/frontend/tests/video-keyframe-canvas.test.ts b/studio/frontend/tests/video-keyframe-canvas.test.ts
index 820d8c7d6f1..d1db19bec02 100644
--- a/studio/frontend/tests/video-keyframe-canvas.test.ts
+++ b/studio/frontend/tests/video-keyframe-canvas.test.ts
@@ -4,7 +4,11 @@
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";
+import {
+ keyframeSupport,
+ matchedCanvas,
+ nearestPresetCanvas,
+} from "../src/features/video/keyframe-canvas.ts";
// What /video/status reports for MiniMax-H3: the released checkpoint's canvas rule.
const h3: VideoGenerationDefaults = {
@@ -45,3 +49,66 @@ test("previews nothing where the backend would refuse or has no rule", () => {
);
assert.equal(matchedCanvas(1920, 1080, null), null);
});
+
+// What /video/status reports for an image-to-video pipeline family (Wan2.2 TI2V 5B, LTX-2): no
+// aspect rule, the preset nearest the start frame instead.
+const ti2v: VideoGenerationDefaults = {
+ ...h3,
+ resolution_presets: [
+ [1280, 704],
+ [704, 1280],
+ ],
+ canvas_short_edge: null,
+ canvas_max_pixels: null,
+ canvas_from_presets: true,
+};
+const ltx2: VideoGenerationDefaults = {
+ ...ti2v,
+ resolution_presets: [
+ [768, 512],
+ [1216, 704],
+ [704, 1216],
+ [512, 768],
+ ],
+};
+
+test("an image-to-video family previews the preset nearest the start frame", () => {
+ assert.deepEqual(matchedCanvas(1920, 1080, ti2v), [1280, 704]);
+ assert.deepEqual(matchedCanvas(832, 1104, ti2v), [704, 1280]);
+ assert.deepEqual(matchedCanvas(512, 512, ti2v), [1280, 704]);
+ assert.deepEqual(matchedCanvas(1920, 1080, ltx2), [1216, 704]);
+ assert.deepEqual(matchedCanvas(3, 2, ltx2), [768, 512]);
+ assert.deepEqual(matchedCanvas(2, 3, ltx2), [512, 768]);
+ assert.deepEqual(matchedCanvas(9, 16, ltx2), [704, 1216]);
+ // Extreme ratios still land on a preset: the picture is cropped, never refused.
+ assert.deepEqual(matchedCanvas(2000, 400, ti2v), [1280, 704]);
+ assert.equal(matchedCanvas(0, 100, ti2v), null);
+});
+
+test("nearestPresetCanvas ignores an empty list", () => {
+ assert.equal(nearestPresetCanvas(16, 9, []), null);
+});
+
+test("keyframe support: per-frame fields win, the legacy flag covers old backends", () => {
+ // Wan2.2 TI2V 5B / LTX-2 on a new backend: the start frame only.
+ assert.deepEqual(
+ keyframeSupport({
+ supports_keyframes: false,
+ supports_first_frame: true,
+ supports_last_frame: false,
+ }),
+ { first: true, last: false },
+ );
+ assert.deepEqual(
+ keyframeSupport({ supports_keyframes: true, supports_first_frame: true, supports_last_frame: true }),
+ { first: true, last: true },
+ );
+ // An older backend only reports supports_keyframes (MiniMax-H3's pair).
+ assert.deepEqual(keyframeSupport({ supports_keyframes: true }), { first: true, last: true });
+ assert.deepEqual(keyframeSupport({ supports_keyframes: false }), { first: false, last: false });
+ assert.deepEqual(
+ keyframeSupport({ supports_keyframes: false, supports_first_frame: false, supports_last_frame: false }),
+ { first: false, last: false },
+ );
+ assert.deepEqual(keyframeSupport(null), { first: false, last: false });
+});
diff --git a/studio/frontend/tests/video-start-frame-upload.test.ts b/studio/frontend/tests/video-start-frame-upload.test.ts
new file mode 100644
index 00000000000..3cda70383c4
--- /dev/null
+++ b/studio/frontend/tests/video-start-frame-upload.test.ts
@@ -0,0 +1,97 @@
+// 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 { readFile } from "node:fs/promises";
+import test from "node:test";
+
+// A hidden frame must never be sent: the user cannot see what conditioned the clip.
+
+const page = await readFile(
+ new URL("../src/features/video/video-page.tsx", import.meta.url),
+ "utf8",
+);
+
+function block(after: string, until: string): string {
+ const start = page.indexOf(after);
+ assert.ok(start >= 0, `missing: ${after}`);
+ const end = page.indexOf(until, start);
+ assert.ok(end > start, `missing after ${after}: ${until}`);
+ return page.slice(start, end);
+}
+
+test("support is read per frame from the status, with the legacy flag as fallback", () => {
+ assert.match(
+ page,
+ /const \{ first: supportsFirstFrame, last: supportsLastFrame \} = keyframeSupport\(status\);/,
+ );
+});
+
+test("each dropzone renders only where its frame is supported", () => {
+ const controls = block(
+ 'data-testid="video-keyframes"',
+ "{supportsReferences && (",
+ );
+ const start = controls.indexOf('removeLabel="Remove start frame"');
+ const end = controls.indexOf('removeLabel="Remove end frame"');
+ assert.ok(start > 0 && end > 0);
+ const gateBefore = (index: number) => {
+ const head = controls.slice(0, index);
+ return head.slice(head.lastIndexOf("{supports")).split(" ")[0];
+ };
+ assert.equal(gateBefore(start), "{supportsFirstFrame");
+ assert.equal(gateBefore(end), "{supportsLastFrame");
+ assert.match(
+ controls,
+ /supportsLastFrame \? "grid grid-cols-2 gap-2" : "grid gap-2"/,
+ );
+});
+
+test("the section and its wording follow the loaded family", () => {
+ assert.match(
+ page,
+ /const supportsKeyframes = supportsFirstFrame \|\| supportsLastFrame;/,
+ );
+ assert.match(
+ page,
+ /\{supportsLastFrame \? "Start and end frame" : "Start frame"\}/,
+ );
+ assert.match(
+ page,
+ /"Generate a video from a prompt, or animate a start frame"/,
+ );
+});
+
+test("the request carries each frame only where it is supported", () => {
+ assert.match(
+ page,
+ /first_frame: supportsFirstFrame \? firstFrame \?\? undefined : undefined,/,
+ );
+ assert.match(
+ page,
+ /last_frame: supportsLastFrame \? lastFrame \?\? undefined : undefined,/,
+ );
+});
+
+test("a frame the newly loaded model cannot take is dropped, each on its own", () => {
+ assert.match(
+ page,
+ /if \(status\?\.loaded && !supportsFirstFrame\) setFirstFrame\(null\);/,
+ );
+ assert.match(
+ page,
+ /if \(status\?\.loaded && !supportsLastFrame\) setLastFrame\(null\);/,
+ );
+});
+
+test("the 1:4 to 4:1 warning is MiniMax-H3's alone", () => {
+ // A preset family centre-crops any picture onto its nearest preset, so it never refuses one.
+ assert.match(
+ page,
+ /const canvasRefusesAspect = !status\?\.defaults\?\.canvas_from_presets;/,
+ );
+ assert.match(
+ page,
+ /\{canvasKeyframe && !matchedResolution && canvasRefusesAspect && \(/,
+ );
+});