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: load Wan2.2-A14B expert pairs and tell LTX-2.3 distilled from dev by its weights (#12872)

Daniel Han35f30b14d329
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index fc84f610040..810cf74458f 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -20336,9 +20336,9 @@ class LlamaCppBackend:
Same fixed order ``_arch_to_task`` asks in: the ARCHITECTURE first, since some map
straight to a family (``detect_video_family("", override = "ltxv")`` resolves LTX-2
with no name to go on), then the repo id, then the filename. Whatever resolves must
- not be an MoE (the GGUF loader cannot assemble those) and must be buildable by the
- video engine -- bare "wan" resolves nothing and QuantStack/Wan2.2-T2V-A14B-GGUF
- resolves an MoE, so neither is promised the page."""
+ be an MoE only when the file names one expert of a high/low noise pair (the loader
+ assembles the pair) and must be buildable by the video engine -- bare "wan" resolves
+ nothing, and an unpaired QuantStack/Wan2.2-T2V-A14B-GGUF file is not promised the page."""
try:
from core.inference.video_families import detect_video_family
@@ -20354,7 +20354,10 @@ class LlamaCppBackend:
break
if fam is None:
return False
- return not getattr(fam, "is_moe", False) and _video_family_buildable(fam)
+ from core.inference.video_moe_pair import moe_pick_pairs
+
+ # An MoE expert is offered when its name pairs the partner the loader assembles it with.
+ return moe_pick_pairs(fam, gguf_path) and _video_family_buildable(fam)
except Exception as e: # noqa: BLE001 -- never lose the page over a probe failure
logger.debug("Family probe failed for video arch: %s", e)
return True
diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.py
index 3463f16cf57..9b8ef1aef9d 100644
--- a/studio/backend/core/inference/video.py
+++ b/studio/backend/core/inference/video.py
@@ -64,6 +64,7 @@ from .diffusion_comfy_quant import (
refuse_comfy_quant,
)
from .diffusion_prequant import scoped_local_files_only
+from .video_moe_pair import moe_expert_of, moe_partner_filename, moe_pick_pairs
from .diffusion_cache import (
FBCACHE_MIN_STEPS,
TC_AUTO,
@@ -717,6 +718,27 @@ def _is_trusted_video_repo(repo_id: str) -> bool:
return rid.startswith("unsloth/") or rid in _TRUSTED_NON_GGUF_VIDEO_REPOS
+def _cached_checkpoint_file(repo_id: str, filename: str) -> Optional[Path]:
+ """``filename`` in a local ``repo_id`` dir, else its cached hub blob (no network; active, legacy and default cache
+ roots), else None."""
+ path = Path(repo_id).expanduser() / filename
+ if path.is_file():
+ return path
+ from huggingface_hub import try_to_load_from_cache
+
+ cached = try_to_load_from_cache(repo_id, filename)
+ if not isinstance(cached, str):
+ from hub.utils.paths import hf_default_cache_dir, legacy_hf_cache_dir
+ for root_fn in (legacy_hf_cache_dir, hf_default_cache_dir):
+ try:
+ cached = try_to_load_from_cache(repo_id, filename, cache_dir = str(root_fn()))
+ except Exception: # noqa: BLE001 -- a bad/absent root just falls through
+ cached = None
+ if isinstance(cached, str):
+ break
+ return Path(cached) if isinstance(cached, str) else None
+
+
def _picked_gguf_arch(repo_id: str, gguf_filename: str) -> Optional[str]:
"""``general.architecture`` of a picked GGUF, or None. The Video picker admits a GGUF by its
arch (not its name) -- for a LOCAL dir (``repo_id`` is a directory) AND for a cached HUB repo
@@ -725,29 +747,9 @@ def _picked_gguf_arch(repo_id: str, gguf_filename: str) -> Optional[str]:
family the picker offered. Reads the local file when present, else the cached hub blob
(network-free via try_to_load_from_cache). Header-only, bounds-checked."""
try:
- from pathlib import Path
-
- path = Path(repo_id).expanduser() / gguf_filename
- if not path.is_file():
- # Not a local dir: resolve a cached HUB blob (no network). Probe active, legacy AND default cache roots, or
- # a non-active-root GGUF 400s.
- from huggingface_hub import try_to_load_from_cache
-
- cached = try_to_load_from_cache(repo_id, gguf_filename)
- if not isinstance(cached, str):
- from hub.utils.paths import hf_default_cache_dir, legacy_hf_cache_dir
- for root_fn in (legacy_hf_cache_dir, hf_default_cache_dir):
- try:
- cached = try_to_load_from_cache(
- repo_id, gguf_filename, cache_dir = str(root_fn())
- )
- except Exception: # noqa: BLE001 -- a bad/absent root just falls through
- cached = None
- if isinstance(cached, str):
- break
- if not isinstance(cached, str):
- return None
- path = Path(cached)
+ path = _cached_checkpoint_file(repo_id, gguf_filename)
+ if path is None:
+ return None
from utils.models.gguf_metadata import read_gguf_architecture
return read_gguf_architecture(str(path))
@@ -1128,6 +1130,8 @@ class _VideoLoadState:
# resolves a bare device. Mirrors the image backend.
placed_ordinal: Optional[int] = None
gguf_filename: Optional[str] = None
+ # Content-detected checkpoint variant identifier (LTX-2.3 "ltx-2.3-22b-distilled" / "-dev"), read before the names.
+ variant_id: Optional[str] = None
# Resident MiniMax-H3 denoiser partition, if any.
h3_task: Optional[str] = None
offload_policy: str = "none"
@@ -1653,6 +1657,15 @@ def _h3_auto_denoiser_scheme(
return H3_AUTO_FALLBACK_SCHEME
+def _checkpoint_files(gguf_filename: Optional[str], kind: str) -> tuple[str, ...]:
+ """The checkpoint file(s) a gguf / single_file pick reads: the pick, plus its partner expert when the name
+ pairs one (only a dual-expert family gets past validation with such a name, and a single-DiT one never asks)."""
+ if not gguf_filename:
+ return ()
+ partner = moe_partner_filename(gguf_filename) if kind != "pipeline" else None
+ return (gguf_filename, partner) if partner else (gguf_filename,)
+
+
def _planned_denoiser_components(fam: Any, kind: str) -> tuple[str, ...]:
"""The denoiser component(s) a CONVENTIONAL seeded load covers, or ``()``."""
try:
@@ -2777,15 +2790,25 @@ class VideoBackend:
# the load.
from core.inference.diffusion import _assert_local_base_is_pipeline
- excluded = (fam.denoiser_attr,) if kind in ("gguf", "single_file") else ()
+ excluded = (
+ ((fam.denoiser_attr, "transformer_2") if fam.is_moe else (fam.denoiser_attr,))
+ if kind in ("gguf", "single_file")
+ else ()
+ )
_assert_local_base_is_pipeline(base_repo, excluded_components = excluded)
if kind in ("gguf", "single_file") and not gguf_filename:
raise ValueError("A gguf/single_file load needs the checkpoint filename.")
- if kind in ("gguf", "single_file") and fam.is_moe:
+ local_file = Path(repo_id).expanduser().is_file()
+ if (
+ kind in ("gguf", "single_file")
+ and fam.is_moe
+ and not moe_pick_pairs(fam, repo_id if local_file else gguf_filename)
+ ):
raise ValueError(
f"'{fam.name}' is a dual-expert model: a single {kind} file covers only "
- f"one of its two transformers. Load the diffusers pipeline repo "
- f"('{fam.base_repo}') instead."
+ f"one of its two transformers. Pick one expert of a high_noise / low_noise pair "
+ f"(Studio loads its partner from the same folder), or load the diffusers "
+ f"pipeline repo ('{fam.base_repo}')."
)
# A missing local checkpoint must fail HERE, before the route evicts a resident model.
if kind in ("gguf", "single_file"):
@@ -2810,9 +2833,18 @@ class VideoBackend:
from .diffusion_families import resolve_local_gguf_child
try:
resolve_local_gguf_child(root, gguf_filename or "")
+ if fam.is_moe:
+ resolve_local_gguf_child(root, moe_partner_filename(gguf_filename) or "")
except Exception as exc: # noqa: BLE001 -- surface as client input error
raise ValueError(str(exc)) from exc
elif root.is_file():
+ if fam.is_moe:
+ partner = root.with_name(moe_partner_filename(root.name) or root.name)
+ if not partner.is_file():
+ raise ValueError(
+ f"'{root.name}' is one expert of a dual-expert pair, but its partner "
+ f"'{partner.name}' is not in the same folder."
+ )
# The loader hands a local FILE straight through (ignoring gguf_filename), so the file's own suffix must
# match the kind.
suffix = root.suffix.lower()
@@ -3156,6 +3188,7 @@ class VideoBackend:
checkpoint_local: Optional[Path] = None
if kwargs.get("gguf_filename") and not Path(kwargs["repo_id"]).expanduser().exists():
from utils.hf_xet_fallback import hf_hub_download_with_xet_fallback
+
checkpoint_local = Path(
hf_hub_download_with_xet_fallback(
kwargs["repo_id"],
@@ -3171,6 +3204,16 @@ class VideoBackend:
gguf_header_delta = True,
)
)
+ partner = moe_partner_filename(kwargs["gguf_filename"])
+ if getattr(fam, "is_moe", False) and kind != "pipeline" and partner:
+ hf_hub_download_with_xet_fallback(
+ kwargs["repo_id"],
+ partner,
+ kwargs.get("hf_token"),
+ cancel_event = cancel_event,
+ reuse_other_cache_root = True,
+ local_files_only = local_files_only,
+ )
# An LTX-2.3 checkpoint supplies the VAEs/vocoder/connectors, so the base pull shrinks to scheduler + TE +
# tokenizer; recompute the estimate.
ltx23 = False
@@ -4765,7 +4808,7 @@ class VideoBackend:
if (
kind != "pipeline"
# An H3 single file (a ComfyUI denoiser) replaces the partition it serves, transformer_ref/ included.
- and name.startswith(("transformer/", h3_denoiser_prefix))
+ and name.startswith(("transformer/", "transformer_2/", h3_denoiser_prefix))
# transformer/config.json is the exception: from_single_file(config = <repo id>, subfolder =
# "transformer") reads it off the Hub, so a load that promised to download nothing needs it staged.
# Without it the locality gate cleared the pick and the fetch happened after eviction.
@@ -4828,8 +4871,9 @@ class VideoBackend:
skip_te_components = skip_te_components + ("text_encoder",)
if gguf_filename and not Path(repo_id).expanduser().exists():
info = api.model_info(repo_id, files_metadata = True)
+ wanted = _checkpoint_files(gguf_filename, kind)
for sibling in info.siblings or []:
- if sibling.rfilename == gguf_filename and sibling.size:
+ if sibling.rfilename in wanted and sibling.size:
total += int(sibling.size)
if base and not Path(base).expanduser().exists():
info = api.model_info(base, files_metadata = True)
@@ -4996,10 +5040,13 @@ class VideoBackend:
api = HfApi(token = hf_token or None)
if gguf_filename and not Path(repo_id).expanduser().exists():
info = api.model_info(repo_id, files_metadata = True)
+ wanted_checkpoints = (
+ _checkpoint_files(gguf_filename, kind) if fam.is_moe else (gguf_filename,)
+ )
sizes = [
(s.rfilename, int(s.size or 0))
for s in (info.siblings or [])
- if s.rfilename == gguf_filename
+ if s.rfilename in wanted_checkpoints
]
checkpoint_bytes = sum(size for _name, size in sizes)
total += add(
@@ -5014,7 +5061,12 @@ class VideoBackend:
# inline, outside the panel's disk preflight.
from .video_ltx2 import ltx23_extras_files, LTX23_EXTRAS_REPO
- wanted = set(ltx23_extras_files(gguf_filename))
+ # A cached checkpoint's weights name its variant, as at load; else its name decides.
+ try:
+ variant_source = _cached_checkpoint_file(repo_id, gguf_filename)
+ except Exception: # noqa: BLE001 -- the name decides
+ variant_source = None
+ wanted = set(ltx23_extras_files(variant_source or gguf_filename))
extras_info = (
info
if LTX23_EXTRAS_REPO == repo_id
@@ -5822,47 +5874,88 @@ class VideoBackend:
comfy_keep = (
transformer_quant is None or normalize_transformer_quant(transformer_quant) is not None
)
+ partner_path: Optional[Path] = None
+ partner_scan = None
+ # LTX-2.3 variant read from the weights; outranks the file name in recipe lookups (None: the name decides).
+ variant_id: Optional[str] = None
+ ltx_keys = None
if kind != "pipeline":
checkpoint_path = self._resolve_checkpoint_path(
repo_id, gguf_filename, hf_token, local_files_only = local_files_only
)
- size_mib = file_size_mib(str(checkpoint_path))
- if kind == "single_file":
- comfy_scan = refuse_comfy_quant(str(checkpoint_path))
- if comfy_scan is None and _video_comfy_key_map(fam) is not None:
- # No diffusers converter: an unquantized original-layout file goes through the key map too.
- from .diffusion_comfy_quant import ComfyQuantScan
- comfy_scan = ComfyQuantScan()
- if kind == "gguf":
- transformer_mib = estimate_gguf_resident_mib(size_mib)
- elif comfy_scan is not None:
- ltx_keys = None
- if fam.name == "ltx-2":
- # The file also bundles VAE / audio VAE / vocoder, priced as companions; connectors stay in.
- from .video_ltx2 import ltx23_is_dit_or_connector_key as ltx_keys
- transformer_mib = _video_comfy_resident_mib(
- fam,
- base,
- target,
- checkpoint_path,
- comfy_scan,
- keep = comfy_keep,
- keep_key = ltx_keys,
+ if fam.name == "ltx-2":
+ from .video_ltx2 import ltx23_variant_identifier
+ variant_id = ltx23_variant_identifier(checkpoint_path)
+ if variant_id is not None:
+ logger.info(
+ "video.ltx23_variant: %s (from the checkpoint's weights)", variant_id
+ )
+
+ if fam.name == "ltx-2":
+ # The file also bundles VAE / audio VAE / vocoder, priced as companions; connectors stay in.
+ from .video_ltx2 import ltx23_is_dit_or_connector_key as ltx_keys
+
+ def _price_checkpoint(path: Any) -> tuple[Optional[int], Any]:
+ """Resident MiB of one checkpoint file's DiT and its ComfyUI quant scan (None: a plain file)."""
+ scan = None
+ mib: Optional[int] = None
+ size_mib = file_size_mib(str(path))
+ if kind == "single_file":
+ scan = refuse_comfy_quant(str(path))
+ if scan is None and _video_comfy_key_map(fam) is not None:
+ # No diffusers converter: an unquantized original-layout file goes through the key map too.
+ from .diffusion_comfy_quant import ComfyQuantScan
+ scan = ComfyQuantScan()
+ if kind == "gguf":
+ mib = estimate_gguf_resident_mib(size_mib)
+ elif scan is not None:
+ mib = _video_comfy_resident_mib(
+ fam,
+ base,
+ target,
+ path,
+ scan,
+ keep = comfy_keep,
+ keep_key = ltx_keys,
+ )
+ if mib is None:
+ mib = estimate_safetensors_dense_mib(size_mib, fp8_upcast = True)
+ if mib is not None:
+ mib = int(mib * dtype_scale)
+ else:
+ mib = estimate_safetensors_dense_mib(size_mib)
+ if fam.name == "ltx-2" and mib is not None:
+ # The file also bundles VAE / audio VAE / vocoder, already priced as companions. The connectors
+ # under this prefix stay in: the table undercounts them (~2.9 of 6 GB), and dropping them plans
+ # below the peak.
+ dit_mib = safetensors_prefix_mib(str(path), "model.diffusion_model.")
+ if dit_mib is not None:
+ mib = min(mib, dit_mib)
+ if mib is not None:
+ mib = int(mib * dtype_scale)
+ return mib, scan
+
+ transformer_mib, comfy_scan = _price_checkpoint(checkpoint_path)
+ if getattr(fam, "is_moe", False):
+ # Both experts stay loaded, so price the pair; the planner splits the total per expert.
+ partner_path = self._resolve_moe_partner_path(
+ repo_id, gguf_filename, hf_token, local_files_only = local_files_only
)
- if transformer_mib is None:
- transformer_mib = estimate_safetensors_dense_mib(size_mib, fp8_upcast = True)
- if transformer_mib is not None:
- transformer_mib = int(transformer_mib * dtype_scale)
- else:
- transformer_mib = estimate_safetensors_dense_mib(size_mib)
- if fam.name == "ltx-2" and transformer_mib is not None:
- # The file also bundles VAE / audio VAE / vocoder, already priced as companions. The connectors under
- # this prefix stay in: the table undercounts them (~2.9 of 6 GB), and dropping them plans below the peak.
- dit_mib = safetensors_prefix_mib(str(checkpoint_path), "model.diffusion_model.")
- if dit_mib is not None:
- transformer_mib = min(transformer_mib, dit_mib)
- if transformer_mib is not None:
- transformer_mib = int(transformer_mib * dtype_scale)
+ partner_mib, partner_scan = _price_checkpoint(partner_path)
+ if (comfy_scan is None) != (partner_scan is None):
+ raise ValueError(
+ f"'{Path(str(checkpoint_path)).name}' and '{partner_path.name}' are not the same kind "
+ f"of checkpoint (one ComfyUI-quantized, one not); pick a matching pair."
+ )
+ transformer_mib = (
+ transformer_mib + partner_mib
+ if transformer_mib is not None and partner_mib is not None
+ else None
+ )
+ if moe_expert_of(Path(str(checkpoint_path)).name) == "low":
+ # The high-noise expert is transformer (the early steps), whichever of the two was picked.
+ checkpoint_path, partner_path = partner_path, checkpoint_path
+ comfy_scan, partner_scan = partner_scan, comfy_scan
# Price the plan at the hosted fp8 DiT: the bf16 file size would plan an offload and skip the seed.
ltx23_prequant_pick = (
transformer_mib is not None and comfy_scan is None
@@ -6079,6 +6172,21 @@ class VideoBackend:
keep_key = ltx_keys,
offload = True,
)
+ if offload_mib is not None and partner_path is not None and partner_scan is not None:
+ # transformer_mib prices the pair: reprice both experts.
+ partner_offload_mib = _video_comfy_resident_mib(
+ fam,
+ base,
+ target,
+ partner_path,
+ partner_scan,
+ keep = comfy_keep,
+ keep_key = ltx_keys,
+ offload = True,
+ )
+ offload_mib = (
+ offload_mib + partner_offload_mib if partner_offload_mib is not None else None
+ )
if offload_mib is not None and transformer_mib is not None:
offload_mib = int(offload_mib * dtype_scale)
if offload_mib > transformer_mib:
@@ -6330,26 +6438,40 @@ class VideoBackend:
text_encoder_device = ltx23_te_device,
)
else:
- if comfy_scan is not None:
- transformer = load_comfy_quant_transformer(
- transformer_cls,
- str(checkpoint_path),
- comfy_scan,
- sf_kwargs,
- **_video_comfy_backends(
- fam, base, target, plan, bf16_plan, keep = comfy_keep
- ),
- family = fam.name,
- target = target,
- logger = logger,
- key_map = _video_comfy_key_map(fam),
+
+ def _load_expert(path: Any, scan: Any, subfolder: str) -> Any:
+ kwargs = dict(sf_kwargs, subfolder = subfolder)
+ if scan is not None:
+ # int8 codes go to Studio's int8 runtime (torchao resident, the torchao-free twin under
+ # offload) and fp8 codes to its fp8 GEMM when resident, by the rules Studio's own quant follows.
+ return load_comfy_quant_transformer(
+ transformer_cls,
+ str(path),
+ scan,
+ kwargs,
+ **_video_comfy_backends(
+ fam, base, target, plan, bf16_plan, keep = comfy_keep
+ ),
+ family = fam.name,
+ target = target,
+ logger = logger,
+ key_map = _video_comfy_key_map(fam),
+ )
+ return transformer_cls.from_single_file(str(path), **kwargs)
+
+ transformer = _load_expert(checkpoint_path, comfy_scan, "transformer")
+ experts: dict[str, Any] = {"transformer": transformer}
+ if partner_path is not None:
+ experts["transformer_2"] = _load_expert(
+ partner_path, partner_scan, "transformer_2"
)
- else:
- transformer = transformer_cls.from_single_file(
- str(checkpoint_path), **sf_kwargs
+ logger.info(
+ "video.moe_pair: transformer=%s transformer_2=%s",
+ Path(str(checkpoint_path)).name,
+ Path(str(partner_path)).name,
)
pipe = pipeline_cls.from_pretrained(
- _base_local_dir or base, transformer = transformer, **pipe_kwargs
+ _base_local_dir or base, **{**pipe_kwargs, **experts}
)
# The dtype dict already loads the Wan VAE at float32; belt-and-suspenders for any path that bypassed it (e.g. a
@@ -6393,6 +6515,15 @@ class VideoBackend:
if comfy_scan is not None
else None
) or {}
+ partner_info = (
+ getattr(getattr(pipe, "transformer_2", None), "_unsloth_comfy_quant", None)
+ if partner_scan is not None
+ else None
+ )
+ if partner_info:
+ comfy_info = dict(comfy_info)
+ for key in ("int8", "fp8", "dequantized"):
+ comfy_info[key] = int(comfy_info.get(key) or 0) + int(partner_info.get(key) or 0)
comfy_scheme = (
TQ_INT8 if comfy_info.get("int8") else TQ_FP8 if comfy_info.get("fp8") else None
)
@@ -6460,7 +6591,8 @@ class VideoBackend:
if comfy_scheme is not None:
transformer_quant_engaged = comfy_scheme
transformer_quant_source = (
- f"ComfyUI-quantized checkpoint ({Path(str(checkpoint_path)).name}): "
+ f"ComfyUI-quantized checkpoint ({Path(str(checkpoint_path)).name}"
+ f"{' + ' + Path(str(partner_path)).name if partner_path is not None else ''}): "
f"{comfy_info.get('int8', 0)} int8 / {comfy_info.get('fp8', 0)} fp8 layers kept "
f"({comfy_info.get('backend') or comfy_info.get('fp8_backend')} runtime), "
f"{comfy_info.get('dequantized', 0)} dequantized"
@@ -6664,7 +6796,11 @@ class VideoBackend:
static_plan: Optional[dict] = None
if cache_auto:
default_cache_steps, _ = default_video_generation_params(
- gguf_filename, repo_id, base, fallback = (fam.default_steps, fam.default_guidance)
+ variant_id,
+ gguf_filename,
+ repo_id,
+ base,
+ fallback = (fam.default_steps, fam.default_guidance),
)
static_plan = auto_static_skip_plan(
(repo_id, base), skip_tier(speed_mode, effective_speed), default_cache_steps
@@ -7057,6 +7193,7 @@ class VideoBackend:
dtype = str(dtype).replace("torch.", ""),
kind = kind,
gguf_filename = gguf_filename,
+ variant_id = variant_id,
offload_policy = offload_policy,
vae_tiling = vae_tiling,
memory_mode = plan.requested_mode,
@@ -8293,6 +8430,30 @@ class VideoBackend:
)
)
+ @staticmethod
+ def _resolve_moe_partner_path(
+ repo_id: str,
+ gguf_filename: Optional[str],
+ hf_token: Optional[str],
+ local_files_only: bool = False,
+ ) -> Path:
+ """The OTHER expert's file of a dual-expert pick (same folder / repo, paired by name; downloads if hub)."""
+ root = Path(repo_id).expanduser()
+ if root.is_file():
+ partner = moe_partner_filename(root.name)
+ if partner is None:
+ raise ValueError(f"'{root.name}' does not name a high_noise / low_noise expert.")
+ path = root.with_name(partner)
+ if not path.is_file():
+ raise FileNotFoundError(f"The partner expert '{path}' does not exist.")
+ return path
+ partner = moe_partner_filename(gguf_filename)
+ if partner is None:
+ raise ValueError(f"'{gguf_filename}' does not name a high_noise / low_noise expert.")
+ return VideoBackend._resolve_checkpoint_path(
+ repo_id, partner, hf_token, local_files_only = local_files_only
+ )
+
# ── generation ───────────────────────────────────────────────────────────
def loaded_family(self) -> Optional[VideoFamily]:
@@ -8848,6 +9009,7 @@ class VideoBackend:
fam.default_fps if fam.name == "minimax-h3" else int(fps or fam.default_fps)
)
default_steps, default_guidance = default_video_generation_params(
+ state.variant_id,
state.gguf_filename,
state.repo_id,
state.base_repo,
@@ -9091,7 +9253,7 @@ class VideoBackend:
ltx23_verbatim_sigmas,
)
if steps == len(LTX23_DISTILLED_SIGMAS) and ltx2_distilled_ids(
- state.gguf_filename, state.repo_id, state.base_repo
+ state.variant_id, state.gguf_filename, state.repo_id, state.base_repo
):
kwargs["sigmas"] = list(LTX23_DISTILLED_SIGMAS)
sigma_ctx = ltx23_verbatim_sigmas(pipe)
@@ -9103,7 +9265,9 @@ class VideoBackend:
)
# Distilled DiT is sampled unguided; newer diffusers defaults would add STG + modality passes.
- if ltx2_distilled_ids(state.gguf_filename, state.repo_id, state.base_repo):
+ if ltx2_distilled_ids(
+ state.variant_id, state.gguf_filename, state.repo_id, state.base_repo
+ ):
kwargs.update(ltx2_distilled_guidance_kwargs(call_params, guidance))
# The render thread copies this thread's context, so raise the recompile limit here.
ensure_recompile_limit()
@@ -10250,6 +10414,7 @@ class VideoBackend:
)
fam = state.family
default_steps, default_guidance = default_video_generation_params(
+ state.variant_id,
state.gguf_filename,
state.display_repo_id,
state.repo_id,
diff --git a/studio/backend/core/inference/video_families.py b/studio/backend/core/inference/video_families.py
index 72f7baf535c..a3c6c28a24e 100644
--- a/studio/backend/core/inference/video_families.py
+++ b/studio/backend/core/inference/video_families.py
@@ -335,7 +335,8 @@ _FAMILIES: tuple[VideoFamily, ...] = (
),
# BOTH experts: the plan subtracts one denoiser term and this family builds two.
prequant_resident_gb_by_scheme = (("nvfp4", 16.2),),
- aliases = ("wan2.2-14b", "wan-t2v", "wan2.2-t2v", "wan-t2v-a14b", "wan-a14b"),
+ # "wan2.2_t2v": ComfyUI's expert files (wan2.2_t2v_high_noise_14B_*.safetensors), paired at load.
+ aliases = ("wan2.2-14b", "wan-t2v", "wan2.2-t2v", "wan2.2_t2v", "wan-t2v-a14b", "wan-a14b"),
has_audio = False,
# is_moe drives the dual-DiT optimisation layers; cfg2_kwarg names the pipeline kwarg for transformer_2's
# guidance.
@@ -357,7 +358,8 @@ _FAMILIES: tuple[VideoFamily, ...] = (
vae_force_fp32 = True,
# same VAE as TI2V-5B
cudnn_benchmark = False,
- # no gguf_repo: community GGUFs split the experts, and a single-file load covers only one
+ # no gguf_repo: community GGUFs split the experts; a gguf / single_file pick of either expert loads the pair
+ # (video_moe_pair)
),
# HunyuanVideo-1.5 (diffusers >= 0.39): 8.3B DiT, Qwen2.5-VL + ByT5 encoders. Three quirks: no guidance kwarg (CFG
# on the ``guider``), no callback_on_step_end (generate() wraps scheduler.step), and no upstream model_index.json,
diff --git a/studio/backend/core/inference/video_ltx2.py b/studio/backend/core/inference/video_ltx2.py
index dbe514fe479..d5c0ea21cbc 100644
--- a/studio/backend/core/inference/video_ltx2.py
+++ b/studio/backend/core/inference/video_ltx2.py
@@ -612,9 +612,115 @@ def _load_extras_file(
return load_file(path)
+# sha256[:16] of ``proj_out.bias`` as bf16 bits: headers match across 2.3 variants, but this bias is retrained per
+# release and never quantized, so fp8 / int8 / GGUF repacks carry the release's values.
+LTX23_PROJ_OUT_BIAS_SHA = {
+ "b6a06f88015c612b": "distilled", # ltx-2.3-22b-distilled (and -distilled-fp8)
+ "140a7d077a306ea9": "distilled", # ltx-2.3-22b-distilled-1.1
+ "3d334d94df5daf30": "dev", # ltx-2.3-22b-dev (and -dev-fp8)
+}
+_PROJ_OUT_BIAS_NAMES = (
+ "proj_out.bias",
+ "model.diffusion_model.proj_out.bias",
+ "diffusion_model.proj_out.bias",
+)
+_CONTENT_VARIANT_CACHE: dict[tuple[str, int, int], Optional[str]] = {}
+
+
+def _safetensors_tensor_bf16_bits(path: str, names: tuple[str, ...]) -> Optional[bytes]:
+ """One small tensor's values as bfloat16 bits, read through the header offsets (no other weight byte)."""
+ import json
+ import struct
+
+ import torch
+
+ with open(path, "rb") as fh:
+ (size,) = struct.unpack("<Q", fh.read(8))
+ if size <= 0 or size > 256 * 1024 * 1024:
+ return None
+ header = json.loads(fh.read(size))
+ entry = next((header[n] for n in names if isinstance(header.get(n), dict)), None)
+ if entry is None:
+ return None
+ dtype = {"F32": torch.float32, "F16": torch.float16, "BF16": torch.bfloat16}.get(
+ entry.get("dtype")
+ )
+ start, end = entry["data_offsets"]
+ if dtype is None or not 0 < end - start <= 1 << 20:
+ return None
+ fh.seek(8 + size + start)
+ raw = bytearray(fh.read(end - start))
+ values = torch.frombuffer(raw, dtype = dtype)
+ return values.to(torch.bfloat16).view(torch.int16).numpy().tobytes()
+
+
+def _gguf_tensor_bf16_bits(path: str, names: tuple[str, ...]) -> Optional[bytes]:
+ import numpy as np
+ import torch
+ from gguf import GGMLQuantizationType, GGUFReader
+
+ for tensor in GGUFReader(path).tensors:
+ if str(tensor.name) not in names:
+ continue
+ data = np.asarray(tensor.data)
+ if tensor.tensor_type == GGMLQuantizationType.F32:
+ values = torch.from_numpy(data.astype(np.float32).reshape(-1).copy())
+ elif tensor.tensor_type == GGMLQuantizationType.F16:
+ values = torch.from_numpy(data.astype(np.float16).reshape(-1).copy())
+ elif tensor.tensor_type == GGMLQuantizationType.BF16:
+ values = torch.from_numpy(data.reshape(-1).view(np.int16).copy()).view(torch.bfloat16)
+ else:
+ return None
+ return values.to(torch.bfloat16).view(torch.int16).numpy().tobytes()
+ return None
+
+
+def ltx23_checkpoint_variant(checkpoint_path: Path | str | None) -> Optional[str]:
+ """``"distilled"`` / ``"dev"`` from the checkpoint's CONTENT (a 128-value bias fingerprint), or None when the file
+ is not on disk, unreadable, or not a known LTX-2.3 release (a finetune): callers then fall back to the name. Reads
+ the header plus 256 bytes; cached on (path, size, mtime)."""
+ if not checkpoint_path:
+ return None
+ path = str(checkpoint_path)
+ try:
+ stat = Path(path).stat()
+ except OSError:
+ return None
+ key = (path, stat.st_size, stat.st_mtime_ns)
+ if key in _CONTENT_VARIANT_CACHE:
+ return _CONTENT_VARIANT_CACHE[key]
+ variant: Optional[str] = None
+ try:
+ import hashlib
+
+ reader = (
+ _gguf_tensor_bf16_bits
+ if path.lower().endswith(".gguf")
+ else _safetensors_tensor_bf16_bits
+ )
+ bits = reader(path, _PROJ_OUT_BIAS_NAMES)
+ if bits is not None:
+ variant = LTX23_PROJ_OUT_BIAS_SHA.get(hashlib.sha256(bits).hexdigest()[:16])
+ except Exception as exc: # noqa: BLE001 -- the name decides instead
+ logger.debug("video.ltx23_variant_probe_failed: %s", exc)
+ _CONTENT_VARIANT_CACHE[key] = variant
+ return variant
+
+
+def ltx23_variant_identifier(checkpoint_path: Path | str | None) -> Optional[str]:
+ """An identifier naming the content-detected variant, to put FIRST in the id lists the generation defaults and the
+ distilled recipe read (``default_video_generation_params`` / ``ltx2_distilled_ids``), so the file's weights outrank
+ its name. None when the content is inconclusive, leaving the name to decide as before."""
+ variant = ltx23_checkpoint_variant(checkpoint_path)
+ return f"ltx-2.3-22b-{variant}" if variant else None
+
+
def checkpoint_variant(checkpoint_path: Path | str) -> str:
- """Which companion-weight set a checkpoint pairs with ("dev"/"distilled"). The distilled-1.1
- refresh only retrained the DiT, so it shares the distilled companions."""
+ """Which companion-weight set a checkpoint pairs with ("dev"/"distilled"): the file's content when it is a known
+ release, else its name. The distilled-1.1 refresh only retrained the DiT, so it shares the distilled companions."""
+ by_content = ltx23_checkpoint_variant(checkpoint_path)
+ if by_content is not None:
+ return by_content
return "dev" if "dev" in Path(checkpoint_path).name.lower() else "distilled"
diff --git a/studio/backend/core/inference/video_moe_pair.py b/studio/backend/core/inference/video_moe_pair.py
new file mode 100644
index 00000000000..350fe50ed8a
--- /dev/null
+++ b/studio/backend/core/inference/video_moe_pair.py
@@ -0,0 +1,59 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Pair the two expert files of a dual-expert (Wan2.2-A14B) video DiT by their high/low noise token.
+
+The high-noise expert is the pipeline's ``transformer`` (early steps), the low-noise one ``transformer_2``.
+"""
+
+from __future__ import annotations
+
+import re
+from pathlib import Path
+from typing import Any, Optional
+
+# "high_noise", "high-noise", "high noise", "highnoise" / "HighNoise": the noise word follows directly.
+_EXPERT_RE = re.compile(r"(high|low)([_\- ]?noise)", re.IGNORECASE)
+
+
+def _swap_case(word: str, like: str) -> str:
+ if like.isupper():
+ return word.upper()
+ if like[:1].isupper():
+ return word[:1].upper() + word[1:]
+ return word
+
+
+def moe_expert_of(filename: Optional[str]) -> Optional[str]:
+ """``"high"`` or ``"low"`` for an expert file name, else None (no token, or both kinds)."""
+ if not filename:
+ return None
+ kinds = {m.group(1).lower() for m in _EXPERT_RE.finditer(str(filename))}
+ return kinds.pop() if len(kinds) == 1 else None
+
+
+def moe_partner_filename(filename: Optional[str]) -> Optional[str]:
+ """The other expert's path (folder components included), or None when the name pairs nothing."""
+ expert = moe_expert_of(filename)
+ if expert is None:
+ return None
+ other = "low" if expert == "high" else "high"
+ return _EXPERT_RE.sub(lambda m: _swap_case(other, m.group(1)) + m.group(2), str(filename))
+
+
+def moe_expert_pair(filename: Optional[str]) -> Optional[tuple[str, str]]:
+ """``(high, low)`` file names for either expert's name, or None."""
+ partner = moe_partner_filename(filename)
+ if partner is None:
+ return None
+ return (
+ (str(filename), partner) if moe_expert_of(filename) == "high" else (partner, str(filename))
+ )
+
+
+def moe_pick_pairs(fam: Any, *names: Optional[str]) -> bool:
+ """Whether a single-file / GGUF pick of ``fam`` is loadable: any single-DiT family, or a dual-expert
+ one whose name pairs its partner expert."""
+ if not getattr(fam, "is_moe", False):
+ return True
+ return any(moe_partner_filename(Path(str(n)).name if n else None) for n in names if n)
diff --git a/studio/backend/hub/services/models/catalog_classification.py b/studio/backend/hub/services/models/catalog_classification.py
index 9bdf3a482e0..17abda009d2 100644
--- a/studio/backend/hub/services/models/catalog_classification.py
+++ b/studio/backend/hub/services/models/catalog_classification.py
@@ -138,11 +138,12 @@ def _name_hint_media_task(
an unrecognised name means, hence *unmatched*.
"""
from core.inference.video_families import detect_video_family
+ from core.inference.video_moe_pair import moe_pick_pairs
for hint in name_hints:
family = detect_video_family(hint) if hint else None
if family is not None:
- if not getattr(family, "is_moe", False) and _video_family_buildable(family):
+ if moe_pick_pairs(family, *name_hints) and _video_family_buildable(family):
return _VIDEO_GEN_TASK
return _UNSUPPORTED_DIFFUSION_TASK
from core.inference.diffusion_families import detect_family_for_pick
@@ -281,6 +282,7 @@ def _arch_to_task(arch: Optional[str], name_hints: tuple[Optional[str], ...] = (
)
if normalized in _VIDEO_GGUF_ARCHS:
from core.inference.video_families import detect_video_family
+ from core.inference.video_moe_pair import moe_pick_pairs
family = detect_video_family("", override = normalized)
if family is None:
@@ -291,7 +293,7 @@ def _arch_to_task(arch: Optional[str], name_hints: tuple[Optional[str], ...] = (
break
if (
family is not None
- and not getattr(family, "is_moe", False)
+ and moe_pick_pairs(family, *name_hints)
and _video_family_buildable(family)
):
return _VIDEO_GEN_TASK
diff --git a/studio/backend/tests/test_llama_cpp_non_chat_gguf_preflight.py b/studio/backend/tests/test_llama_cpp_non_chat_gguf_preflight.py
index 15bc62ba008..57fbfe194bd 100644
--- a/studio/backend/tests/test_llama_cpp_non_chat_gguf_preflight.py
+++ b/studio/backend/tests/test_llama_cpp_non_chat_gguf_preflight.py
@@ -284,14 +284,16 @@ def test_a_placeholder_architecture_matches_the_picker_verdict(tmp_path):
def test_an_unassemblable_video_arch_promises_no_page(tmp_path):
- # Wan 2.2 A14B is a two-expert MoE the Video backend cannot assemble, and Wan 2.1's repo
- # ids resolve to no family, so _arch_to_task tags both image-diffusion-unsupported and
- # the Video picker never lists them. The header says "wan" for all three, so the refusal
- # has to consult the same family resolution rather than trusting the arch.
+ # Wan 2.2 A14B is a two-expert MoE the Video backend assembles only from a file naming one
+ # expert of a high/low noise pair, and Wan 2.1's repo ids resolve to no family, so
+ # _arch_to_task tags an unpaired A14B file and Wan 2.1 image-diffusion-unsupported and the
+ # Video picker never lists them. The header says "wan" for all of them, so the refusal has
+ # to consult the same family resolution rather than trusting the arch.
from routes.models import _arch_to_task
for identifier, name, page_named in (
("QuantStack/Wan2.2-TI2V-5B-GGUF", "Wan2.2-TI2V-5B-Q4_K_M.gguf", True),
- ("QuantStack/Wan2.2-T2V-A14B-GGUF", "Wan2.2-T2V-A14B-HighNoise-Q4_K_M.gguf", False),
+ ("QuantStack/Wan2.2-T2V-A14B-GGUF", "Wan2.2-T2V-A14B-HighNoise-Q4_K_M.gguf", True),
+ ("QuantStack/Wan2.2-T2V-A14B-GGUF", "Wan2.2-T2V-A14B-Q4_K_M.gguf", False),
("QuantStack/Wan2.1-T2V-14B-GGUF", "Wan2.1-T2V-14B-Q4_K_M.gguf", False),
):
_, message = _refusal(tmp_path, arch = "wan", name = name, identifier = identifier)
@@ -385,12 +387,13 @@ def test_a_split_placeholder_media_gguf_is_still_refused(tmp_path):
def test_the_metadata_less_branch_asks_what_the_pickers_ask(tmp_path):
# A family that resolves is not enough for the arch branches, nor here: routes.models
- # drops an MoE the loader cannot assemble, so the Video page would not list Wan 2.2 A14B
- # however its GGUF is packaged.
+ # drops an MoE the loader cannot assemble, so the Video page lists a Wan 2.2 A14B GGUF only
+ # when its name pairs the other expert.
from routes.models import _arch_to_task
for identifier, name, page_named in (
("QuantStack/Wan2.2-TI2V-5B-GGUF", "Wan2.2-TI2V-5B-Q4_K_M.gguf", True),
- ("QuantStack/Wan2.2-T2V-A14B-GGUF", "Wan2.2-T2V-A14B-HighNoise-Q4_K_M.gguf", False),
+ ("QuantStack/Wan2.2-T2V-A14B-GGUF", "Wan2.2-T2V-A14B-HighNoise-Q4_K_M.gguf", True),
+ ("QuantStack/Wan2.2-T2V-A14B-GGUF", "Wan2.2-T2V-A14B-Q4_K_M.gguf", False),
):
_, message = _refusal(tmp_path, arch = None, name = name, identifier = identifier)
assert message is not None
diff --git a/studio/backend/tests/test_video_backend.py b/studio/backend/tests/test_video_backend.py
index 28ace3b644c..c3a30ccab66 100644
--- a/studio/backend/tests/test_video_backend.py
+++ b/studio/backend/tests/test_video_backend.py
@@ -2528,14 +2528,20 @@ def test_wan_validate_trusted_repos(fake_runtime):
)
-def test_wan_a14b_refuses_single_file_loads(fake_runtime):
- # A single checkpoint carries only one of the A14B experts and the other would load dense outside the memory plan, so validate refuses it.
+def test_wan_a14b_refuses_unpaired_single_file_loads(fake_runtime):
+ # A checkpoint whose name pairs no partner expert covers one of the two A14B experts, so validate refuses it; a
+ # high/low noise expert name loads the pair (test_video_moe_pair.py).
backend = VideoBackend()
with pytest.raises(ValueError, match = "dual-expert"):
backend.validate_load_request(
"QuantStack/Wan2.2-T2V-A14B-GGUF",
- gguf_filename = "HighNoise/Wan2.2-T2V-A14B-HighNoise-Q4_K_M.gguf",
+ gguf_filename = "Wan2.2-T2V-A14B-Q4_K_M.gguf",
)
+ fam = backend.validate_load_request(
+ "QuantStack/Wan2.2-T2V-A14B-GGUF",
+ gguf_filename = "HighNoise/Wan2.2-T2V-A14B-HighNoise-Q4_K_M.gguf",
+ )
+ assert fam.name == "wan2.2-t2v-a14b"
# The single-DiT 5B family still accepts GGUF.
fam = backend.validate_load_request(
"unsloth/Wan2.2-TI2V-5B-GGUF",
@@ -2581,6 +2587,87 @@ _LTX2_SIBLINGS = [
]
[email protected]("picked", ["high", "low"])
+def test_wan_a14b_gguf_pair_loads_high_as_transformer_and_low_as_transformer_2(
+ fake_runtime, tmp_path, monkeypatch, picked
+):
+ # Either expert of a pair loads both, and the high-noise one always serves the early (transformer) steps.
+ high = tmp_path / "HighNoise" / "Wan2.2-T2V-A14B-HighNoise-Q4_K_M.gguf"
+ low = tmp_path / "LowNoise" / "Wan2.2-T2V-A14B-LowNoise-Q4_K_M.gguf"
+ for path in (high, low):
+ path.parent.mkdir(parents = True)
+ path.write_bytes(b"weights")
+ loaded = []
+
+ def _from_single_file(path, **kwargs):
+ loaded.append((Path(path).name, kwargs["subfolder"], kwargs.get("quantization_config")))
+ return f"dit:{Path(path).name}"
+
+ monkeypatch.setattr(_FakeTransformer, "from_single_file", staticmethod(_from_single_file))
+ pick = high if picked == "high" else low
+ VideoBackend().load_pipeline(
+ str(tmp_path),
+ gguf_filename = str(pick.relative_to(tmp_path)),
+ base_repo = "Wan-AI/Wan2.2-T2V-A14B-Diffusers",
+ family_override = "wan2.2-t2v-a14b",
+ )
+ assert [(name, sub) for name, sub, _ in loaded] == [
+ (high.name, "transformer"),
+ (low.name, "transformer_2"),
+ ]
+ assert all(q is not None for _, _, q in loaded)
+ last = _FakeWanPipelineSingle.last
+ assert last["transformer"] == f"dit:{high.name}"
+ assert last["transformer_2"] == f"dit:{low.name}"
+
+
+def test_wan_a14b_comfy_pair_offloaded_reprices_both_experts(fake_runtime, tmp_path, monkeypatch):
+ # An offloaded ComfyUI-quantized pair reprices both experts at their offload size before the build.
+ import core.inference.video as vid
+ from core.inference.diffusion_comfy_quant import ComfyQuantScan
+
+ names = [
+ "wan2.2_t2v_high_noise_14B_fp8_scaled.safetensors",
+ "wan2.2_t2v_low_noise_14B_fp8_scaled.safetensors",
+ ]
+ for name in names:
+ (tmp_path / name).write_bytes(b"weights")
+ priced = []
+
+ def _resident_mib(
+ fam,
+ base,
+ target,
+ path,
+ scan,
+ *,
+ keep = True,
+ keep_key = None,
+ offload = False,
+ ):
+ priced.append((Path(path).name, offload))
+ return 2 if offload else 1
+
+ class _Stop(Exception):
+ pass
+
+ def _stop(*args, **kwargs):
+ raise _Stop
+
+ monkeypatch.setattr(vid, "refuse_comfy_quant", lambda path: ComfyQuantScan())
+ monkeypatch.setattr(vid, "_video_comfy_resident", lambda *args: False)
+ monkeypatch.setattr(vid, "_video_comfy_resident_mib", _resident_mib)
+ monkeypatch.setattr(vid, "raise_on_unified_memory_shortfall", _stop)
+ with pytest.raises(_Stop):
+ VideoBackend().load_pipeline(
+ str(tmp_path),
+ gguf_filename = names[1],
+ base_repo = "Wan-AI/Wan2.2-T2V-A14B-Diffusers",
+ family_override = "wan2.2-t2v-a14b",
+ )
+ assert sorted(name for name, offload in priced if offload) == sorted(names)
+
+
def test_base_download_files_scopes_pipeline_pull():
# A pipeline load skips the packaged root checkpoint, duplicate encoder shards and non-weight assets.
info = types.SimpleNamespace(siblings = _LTX2_SIBLINGS)
@@ -5094,6 +5181,44 @@ def test_download_plan_narrows_an_ltx23_pick_and_stages_its_extras(monkeypatch):
assert plan["total_bytes"] == ckpt["bytes"] + base["bytes"]
+def test_download_plan_stages_the_companions_of_a_cached_checkpoints_content_variant(
+ monkeypatch, tmp_path
+):
+ # A cached checkpoint whose weights are dev under a distilled name stages the dev companions the load reads.
+ import core.inference.video as vid
+ import core.inference.video_ltx2 as ltx2
+
+ _plan_api_ltx23(monkeypatch)
+ cached = tmp_path / "ltx-2.3-22b-distilled.gguf"
+ monkeypatch.setattr(vid, "_cached_checkpoint_file", lambda repo_id, filename: cached)
+ monkeypatch.setattr(
+ ltx2, "ltx23_checkpoint_variant", lambda path: "dev" if Path(str(path)) == cached else None
+ )
+
+ plan = _ltx23_download_plan()
+
+ files = {e["repo_id"]: e for e in plan["entries"]}["unsloth/LTX-2.3-GGUF"]["files"]
+ assert "vae/ltx-2.3-22b-dev_video_vae.safetensors" in files
+ assert "vae/ltx-2.3-22b-distilled_video_vae.safetensors" not in files
+
+
+def test_wan_a14b_local_base_excludes_both_experts(fake_runtime, monkeypatch):
+ # A paired pick replaces transformer and transformer_2, so a local base needs neither expert's weights.
+ import core.inference.diffusion as diffusion
+
+ seen = []
+ monkeypatch.setattr(
+ diffusion,
+ "_assert_local_base_is_pipeline",
+ lambda base, *, excluded_components = (), **kw: seen.append(tuple(excluded_components)),
+ )
+ VideoBackend().validate_load_request(
+ "QuantStack/Wan2.2-T2V-A14B-GGUF",
+ gguf_filename = "HighNoise/Wan2.2-T2V-A14B-HighNoise-Q4_K_M.gguf",
+ )
+ assert seen and set(seen[-1]) == {"transformer", "transformer_2"}
+
+
def _cuda_bf16_target(monkeypatch):
"""Pretend the box can run layerwise fp8, so the pre-cast encoder resolves off-GPU."""
import torch
diff --git a/studio/backend/tests/test_video_ltx23_variant_content.py b/studio/backend/tests/test_video_ltx23_variant_content.py
new file mode 100644
index 00000000000..7ff9d4c1f0b
--- /dev/null
+++ b/studio/backend/tests/test_video_ltx23_variant_content.py
@@ -0,0 +1,133 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""LTX-2.3 distilled vs dev from the checkpoint's weights (a ``proj_out.bias`` fingerprint), the name only as the
+fallback, so a renamed distilled file keeps the distilled recipe and companions."""
+
+from __future__ import annotations
+
+import hashlib
+
+import pytest
+import torch
+from safetensors.torch import save_file
+
+from core.inference import video_ltx2
+from core.inference.video_families import default_video_generation_params
+from core.inference.video_ltx2 import (
+ checkpoint_variant,
+ ltx2_distilled_ids,
+ ltx23_checkpoint_variant,
+ ltx23_variant_identifier,
+)
+
+
+def _fingerprint(bias: torch.Tensor) -> str:
+ return hashlib.sha256(bias.to(torch.bfloat16).view(torch.int16).numpy().tobytes()).hexdigest()[
+ :16
+ ]
+
+
+def biases(monkeypatch):
+ """Two bf16-exact biases standing in for the distilled and dev releases."""
+ gen = torch.Generator().manual_seed(0)
+ distilled = torch.randn(128, generator = gen).to(torch.bfloat16)
+ dev = torch.randn(128, generator = gen).to(torch.bfloat16)
+ monkeypatch.setattr(
+ video_ltx2,
+ "LTX23_PROJ_OUT_BIAS_SHA",
+ {_fingerprint(distilled): "distilled", _fingerprint(dev): "dev"},
+ )
+ video_ltx2._CONTENT_VARIANT_CACHE.clear()
+ yield {"distilled": distilled, "dev": dev}
+ video_ltx2._CONTENT_VARIANT_CACHE.clear()
+
+
+def _ltx_file(
+ path,
+ bias,
+ *,
+ dtype = torch.bfloat16,
+ prefix = "model.diffusion_model.",
+):
+ tensors = {
+ f"{prefix}proj_out.bias": bias.to(dtype),
+ # A quantized weight beside it, as in an fp8 / int8 ComfyUI repack; never read.
+ f"{prefix}transformer_blocks.0.attn1.to_q.weight": torch.zeros(
+ 4, 4, dtype = torch.float8_e4m3fn
+ ),
+ f"{prefix}transformer_blocks.0.scale_shift_table": torch.zeros(9, 8),
+ f"{prefix}audio_proj_out.bias": torch.ones(16),
+ }
+ save_file(tensors, str(path), metadata = {"model_version": "2.3.0"})
+ return path
+
+
[email protected]("dtype", [torch.bfloat16, torch.float32, torch.float16])
[email protected]("prefix", ["model.diffusion_model.", ""])
+def test_a_renamed_distilled_file_reads_distilled_from_its_weights(tmp_path, biases, dtype, prefix):
+ path = _ltx_file(
+ tmp_path / "LTX-2.3-FP8-ComfyUI.safetensors",
+ biases["distilled"],
+ dtype = dtype,
+ prefix = prefix,
+ )
+ assert ltx23_checkpoint_variant(path) == "distilled"
+ assert ltx23_variant_identifier(path) == "ltx-2.3-22b-distilled"
+ assert checkpoint_variant(path) == "distilled"
+
+
+def test_content_outranks_the_name_both_ways(tmp_path, biases):
+ dev_named_distilled = _ltx_file(tmp_path / "my-distilled-copy.safetensors", biases["dev"])
+ assert checkpoint_variant(dev_named_distilled) == "dev"
+ distilled_named_dev = _ltx_file(tmp_path / "devbox_ltx.safetensors", biases["distilled"])
+ assert checkpoint_variant(distilled_named_dev) == "distilled"
+
+
+def test_an_unknown_fingerprint_or_missing_file_falls_back_to_the_name(tmp_path, biases):
+ finetune = _ltx_file(tmp_path / "ltx-2.3-22b-dev-finetune.safetensors", torch.zeros(128))
+ assert ltx23_checkpoint_variant(finetune) is None
+ assert ltx23_variant_identifier(finetune) is None
+ assert checkpoint_variant(finetune) == "dev"
+ assert ltx23_checkpoint_variant(tmp_path / "absent.safetensors") is None
+ assert ltx23_checkpoint_variant(None) is None
+ assert checkpoint_variant(tmp_path / "absent-distilled.safetensors") == "distilled"
+ garbage = tmp_path / "garbage.safetensors"
+ garbage.write_bytes(b"\x00" * 64)
+ assert ltx23_checkpoint_variant(garbage) is None
+
+
+def test_gguf_bias_is_fingerprinted(tmp_path, biases):
+ gguf = pytest.importorskip("gguf")
+ path = tmp_path / "LTX-2.3-Q4_K_M.gguf"
+ writer = gguf.GGUFWriter(str(path), "ltxv")
+ writer.add_tensor("proj_out.bias", biases["dev"].float().numpy())
+ writer.add_tensor("audio_proj_out.bias", torch.ones(16).numpy())
+ writer.write_header_to_file()
+ writer.write_kv_data_to_file()
+ writer.write_tensors_to_file()
+ writer.close()
+ assert ltx23_checkpoint_variant(path) == "dev"
+
+
+def test_the_identifier_drives_defaults_and_the_distilled_recipe(tmp_path, biases):
+ neutral = _ltx_file(tmp_path / "LTX-2.3-FP8-ComfyUI.safetensors", biases["distilled"])
+ variant_id = ltx23_variant_identifier(neutral)
+ ids = (variant_id, neutral.name, "local/LTX-2.3-FP8-ComfyUI", "Lightricks/LTX-2")
+ assert default_video_generation_params(*ids) == (8, 1.0)
+ assert ltx2_distilled_ids(*ids)
+ # Without content the neutral name gets the dev recipe: the regression this closes.
+ assert default_video_generation_params(*ids[1:]) == (40, 4.0)
+ assert not ltx2_distilled_ids(*ids[1:])
+ # A dev file under a "...distilled..." name stays dev.
+ dev = _ltx_file(tmp_path / "ltx-distilled-mirror.safetensors", biases["dev"])
+ dev_ids = (ltx23_variant_identifier(dev), dev.name, "Lightricks/LTX-2")
+ assert default_video_generation_params(*dev_ids) == (40, 4.0)
+ assert not ltx2_distilled_ids(*dev_ids)
+
+
+def test_the_real_release_fingerprints_are_registered():
+ table = video_ltx2.LTX23_PROJ_OUT_BIAS_SHA
+ assert sorted(table.values()) == ["dev", "distilled", "distilled"]
+ assert all(len(k) == 16 for k in table)
diff --git a/studio/backend/tests/test_video_moe_pair.py b/studio/backend/tests/test_video_moe_pair.py
new file mode 100644
index 00000000000..b0ac4263f85
--- /dev/null
+++ b/studio/backend/tests/test_video_moe_pair.py
@@ -0,0 +1,154 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Wan2.2-A14B single-file picks: either expert of a high/low noise pair names both, the high one
+loads as ``transformer``, and validation, the download plan and the base pull cover the pair."""
+
+from __future__ import annotations
+
+import types
+from pathlib import Path
+
+import pytest
+
+from core.inference.video import VideoBackend, _checkpoint_files
+from core.inference.video_families import detect_video_family
+from core.inference.video_moe_pair import (
+ moe_expert_of,
+ moe_expert_pair,
+ moe_partner_filename,
+ moe_pick_pairs,
+)
+
+COMFY_HIGH = "split_files/diffusion_models/wan2.2_t2v_high_noise_14B_fp8_scaled.safetensors"
+COMFY_LOW = "split_files/diffusion_models/wan2.2_t2v_low_noise_14B_fp8_scaled.safetensors"
+GGUF_HIGH = "HighNoise/Wan2.2-T2V-A14B-HighNoise-Q4_K_M.gguf"
+GGUF_LOW = "LowNoise/Wan2.2-T2V-A14B-LowNoise-Q4_K_M.gguf"
+
+
+ "name, partner",
+ [
+ (COMFY_HIGH, COMFY_LOW),
+ (COMFY_LOW, COMFY_HIGH),
+ # Folder and file tokens both swap, case kept.
+ (GGUF_HIGH, GGUF_LOW),
+ (GGUF_LOW, GGUF_HIGH),
+ ("WAN_HIGH_NOISE_Q8.gguf", "WAN_LOW_NOISE_Q8.gguf"),
+ ("wan2.2-t2v-a14b-high-noise.safetensors", "wan2.2-t2v-a14b-low-noise.safetensors"),
+ ("Wan2.2-T2V-A14B-Q4_K_M.gguf", None),
+ # Both tokens: ambiguous, never paired.
+ ("high_noise_to_low_noise.safetensors", None),
+ ("highlight_noisy.safetensors", None),
+ ("", None),
+ (None, None),
+ ],
+)
+def test_partner_swaps_every_noise_token(name, partner):
+ assert moe_partner_filename(name) == partner
+ if partner is not None:
+ assert moe_partner_filename(partner) == name
+
+
+def test_pair_orders_high_first_whichever_was_picked():
+ assert moe_expert_pair(COMFY_LOW) == (COMFY_HIGH, COMFY_LOW)
+ assert moe_expert_pair(GGUF_HIGH) == (GGUF_HIGH, GGUF_LOW)
+ assert moe_expert_of(GGUF_LOW) == "low"
+ assert moe_expert_pair("model.gguf") is None
+
+
+def test_comfy_expert_names_resolve_the_a14b_family_and_pair():
+ fam = detect_video_family(f"Comfy-Org/Wan_2.2_ComfyUI_Repackaged/{COMFY_HIGH}")
+ assert fam is not None and fam.name == "wan2.2-t2v-a14b"
+ assert moe_pick_pairs(fam, COMFY_HIGH)
+ assert not moe_pick_pairs(fam, "Wan2.2-T2V-A14B-Q4_K_M.gguf")
+ # The I2V experts are a different model (36-channel input) and must not resolve to T2V.
+ i2v = detect_video_family("wan2.2_i2v_high_noise_14B_fp8_scaled.safetensors")
+ assert i2v is None or i2v.name != "wan2.2-t2v-a14b"
+ # A single-DiT family never needs a pair.
+ assert moe_pick_pairs(detect_video_family("Wan-AI/Wan2.2-TI2V-5B-Diffusers"), "x.gguf")
+
+
+def test_checkpoint_files_name_both_experts():
+ assert _checkpoint_files(GGUF_HIGH, "gguf") == (GGUF_HIGH, GGUF_LOW)
+ assert _checkpoint_files("Wan2.2-TI2V-5B-Q4_K_M.gguf", "gguf") == (
+ "Wan2.2-TI2V-5B-Q4_K_M.gguf",
+ )
+ assert _checkpoint_files(None, "gguf") == ()
+
+
+def _sibling(name: str, size: int):
+ return types.SimpleNamespace(rfilename = name, size = size)
+
+
+def test_a_paired_pick_drops_both_dense_experts_from_the_base_pull():
+ info = types.SimpleNamespace(
+ siblings = [
+ _sibling("model_index.json", 1),
+ _sibling("transformer/config.json", 1),
+ _sibling("transformer/diffusion_pytorch_model-00001-of-00002.safetensors", 50),
+ _sibling("transformer_2/config.json", 1),
+ _sibling("transformer_2/diffusion_pytorch_model-00001-of-00002.safetensors", 50),
+ _sibling("text_encoder/model-00001-of-00002.safetensors", 5),
+ _sibling("vae/diffusion_pytorch_model.safetensors", 1),
+ ]
+ )
+ for kind in ("gguf", "single_file"):
+ names = {n for n, _ in VideoBackend._base_download_files(info, kind)}
+ # Both configs stay (from_single_file reads config = <base>, subfolder = transformer / transformer_2).
+ assert {"transformer/config.json", "transformer_2/config.json"} <= names
+ assert not any(n.endswith(".safetensors") and n.startswith("transformer") for n in names)
+ assert "text_encoder/model-00001-of-00002.safetensors" in names
+ pipeline = {n for n, _ in VideoBackend._base_download_files(info, "pipeline")}
+ assert "transformer_2/diffusion_pytorch_model-00001-of-00002.safetensors" in pipeline
+
+
+def _touch(path: Path) -> Path:
+ path.parent.mkdir(parents = True, exist_ok = True)
+ path.write_bytes(b"\0")
+ return path
+
+
+def test_partner_path_resolves_in_a_local_folder_and_next_to_a_local_file(tmp_path):
+ high = _touch(tmp_path / "HighNoise" / "Wan2.2-T2V-A14B-HighNoise-Q4_K_M.gguf")
+ low = _touch(tmp_path / "LowNoise" / "Wan2.2-T2V-A14B-LowNoise-Q4_K_M.gguf")
+ assert VideoBackend._resolve_moe_partner_path(str(tmp_path), GGUF_HIGH, None) == low.resolve()
+ assert VideoBackend._resolve_moe_partner_path(str(tmp_path), GGUF_LOW, None) == high.resolve()
+ flat_high = _touch(tmp_path / "flat" / "wan2.2_t2v_high_noise_14B_fp8_scaled.safetensors")
+ with pytest.raises(FileNotFoundError):
+ VideoBackend._resolve_moe_partner_path(str(flat_high), None, None)
+ flat_low = _touch(flat_high.with_name("wan2.2_t2v_low_noise_14B_fp8_scaled.safetensors"))
+ assert VideoBackend._resolve_moe_partner_path(str(flat_high), None, None) == flat_low
+ with pytest.raises(ValueError, match = "high_noise / low_noise"):
+ VideoBackend._resolve_moe_partner_path(str(tmp_path), "model.gguf", None)
+
+
+def test_validation_needs_the_partner_on_disk_for_a_local_pick(tmp_path, monkeypatch):
+ import core.inference.video as video_module
+
+ monkeypatch.setattr(video_module, "_ensure_mp4_encoder_available", lambda: None)
+ monkeypatch.setattr(
+ "core.inference.diffusion._assert_local_base_is_pipeline", lambda *a, **k: None
+ )
+ backend = VideoBackend()
+ high = _touch(tmp_path / "wan2.2_t2v_high_noise_14B_fp8_scaled.safetensors")
+ with pytest.raises(ValueError, match = "low_noise"):
+ backend.validate_load_request(
+ str(tmp_path), gguf_filename = high.name, family_override = "wan2.2-t2v-a14b"
+ )
+ with pytest.raises(ValueError, match = "partner"):
+ backend.validate_load_request(
+ str(high), gguf_filename = high.name, family_override = "wan2.2-t2v-a14b"
+ )
+ _touch(tmp_path / "wan2.2_t2v_low_noise_14B_fp8_scaled.safetensors")
+ for repo in (str(tmp_path), str(high)):
+ fam = backend.validate_load_request(
+ repo, gguf_filename = high.name, family_override = "wan2.2-t2v-a14b"
+ )
+ assert fam.name == "wan2.2-t2v-a14b"
+ # An unpaired name is still refused, with the way out.
+ lone = _touch(tmp_path / "solo" / "wan2.2_t2v_14B_fp8_scaled.safetensors")
+ with pytest.raises(ValueError, match = "dual-expert"):
+ backend.validate_load_request(
+ str(lone), gguf_filename = lone.name, family_override = "wan2.2-t2v-a14b"
+ )