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: make media family overrides structural (#10150)

Lee Jacksonac6ddf3b9a44
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.py
index 3faf0475f48..ac5e74dbc0b 100644
--- a/studio/backend/core/inference/diffusion.py
+++ b/studio/backend/core/inference/diffusion.py
@@ -51,6 +51,8 @@ from .diffusion_families import (
DiffusionModelReplacedError, # re-exported: callers import it from either module
LoadIdentity,
load_identity,
+ local_pipeline_components_are_complete,
+ _family_override_resolved,
assert_flux2_gguf_matches_base,
assert_pipeline_class_available,
_is_local_path,
@@ -99,6 +101,7 @@ from .diffusion_hidream import (
hidream_te4_kwargs,
)
from .diffusion_krea2 import KREA2_FAMILY_NAME, load_krea2_pipeline
+from .model_ids import hf_cache_repo_id
from .diffusion_memory import (
MEMORY_MODE_BALANCED,
MEMORY_MODE_LOW_VRAM,
@@ -755,7 +758,13 @@ def _is_trusted_diffusion_repo(repo_id: str) -> bool:
return rid.startswith("unsloth/") or rid in _TRUSTED_NON_GGUF_REPOS
-def _assert_local_base_is_pipeline(base_repo: str, *, allow_modular: bool = False) -> None:
+def _assert_local_base_is_pipeline(
+ base_repo: str,
+ *,
+ allow_modular: bool = False,
+ excluded_components: Sequence[str] = (),
+ config_only_model_components: bool = False,
+) -> None:
"""A companion ``base_repo`` fed to ``from_pretrained(base)`` (or ``config=base``) must be a
diffusers PIPELINE directory (has ``model_index.json``). ``_is_trusted_diffusion_repo`` accepts
ANY existing local path, so without this a local base that is not a pipeline dir would pass the
@@ -768,7 +777,9 @@ def _assert_local_base_is_pipeline(base_repo: str, *, allow_modular: bool = Fals
``ModularPipeline.from_pretrained``: that IS the valid on-disk layout for a Modular Diffusers
pipeline (MiniMax-H3 ships no ``model_index.json`` at all). Off by default: a conventional
``DiffusionPipeline`` load still needs the conventional index.
- """
+
+ ``excluded_components`` are supplied by the caller (the checkpoint's denoiser), not the base;
+ ``config_only_model_components`` means the base only supplies component configs."""
base = (base_repo or "").strip()
if not base:
return
@@ -782,10 +793,18 @@ def _assert_local_base_is_pipeline(base_repo: str, *, allow_modular: bool = Fals
indexes = ["model_index.json"]
if allow_modular:
indexes.append("modular_model_index.json")
- if not root.is_dir() or not any((root / name).is_file() for name in indexes):
+ if not root.is_dir() or not any(
+ local_pipeline_components_are_complete(
+ root,
+ name,
+ excluded_components = excluded_components,
+ config_only_model_components = config_only_model_components,
+ )
+ for name in indexes
+ ):
raise ValueError(
f"Local base_repo is not a diffusers pipeline directory "
- f"(no {' or '.join(indexes)}): {base}"
+ f"(no valid {' or '.join(indexes)}): {base}"
)
@@ -973,6 +992,7 @@ class _LoadState:
device: str
dtype: str
cpu_offload: bool
+ display_repo_id: Optional[str] = None
# Defaulted so older positional constructions keep working.
offload_policy: str = OFFLOAD_NONE
vae_tiling: bool = False
@@ -2747,7 +2767,13 @@ class DiffusionBackend:
f"base_repo is restricted to unsloth/* repos (or a local path); got '{base_repo}'."
)
# A local base_repo loads as a full pipeline; reject a non-pipeline one before eviction
- _assert_local_base_is_pipeline(base_repo)
+ whole_file = kind == "single_file" and fam.single_file_is_pipeline
+ excluded = (
+ (fam.denoiser_attr,) if kind in ("gguf", "single_file") and not whole_file else ()
+ )
+ _assert_local_base_is_pipeline(
+ base_repo, excluded_components = excluded, config_only_model_components = whole_file
+ )
local_root = Path(repo_id).expanduser()
# Path-shaped: "."/".." prefix, a backslash (never in "org/name"), or an absolute path.
path_shaped = (
@@ -2778,9 +2804,9 @@ class DiffusionBackend:
"a 'pipeline' load takes a full diffusers repo, not a single-file name."
)
if local_root.exists():
- if not (local_root / "model_index.json").exists():
+ if not local_pipeline_components_are_complete(local_root, "model_index.json"):
raise FileNotFoundError(
- f"Local pipeline directory has no model_index.json: {repo_id}"
+ f"Local pipeline directory has no complete valid model_index.json: {repo_id}"
)
elif path_shaped:
raise FileNotFoundError(f"Local model path does not exist: {repo_id}")
@@ -2836,6 +2862,7 @@ class DiffusionBackend:
self,
repo_id: str,
*,
+ display_repo_id: Optional[str] = None,
local_files_only: bool = False,
gguf_filename: Optional[str] = None,
base_repo: Optional[str] = None,
@@ -2920,6 +2947,7 @@ class DiffusionBackend:
target = self._run_load,
kwargs = dict(
repo_id = repo_id,
+ display_repo_id = display_repo_id,
local_files_only = local_files_only,
gguf_filename = gguf_filename,
base_repo = base_repo,
@@ -5003,6 +5031,7 @@ class DiffusionBackend:
self,
repo_id: str,
*,
+ display_repo_id: Optional[str] = None,
local_files_only: bool = False,
gguf_filename: Optional[str] = None,
base_repo: Optional[str] = None,
@@ -6831,6 +6860,7 @@ class DiffusionBackend:
# explicit.
resolved = build_resolved_record(
{
+ "family_override": _family_override_resolved(family_override, fam),
"speed_mode": (
speed_mode,
"deferred" if speed_deferred else effective_speed,
@@ -6948,6 +6978,7 @@ class DiffusionBackend:
pipe = pipe,
family = fam,
repo_id = repo_id,
+ display_repo_id = display_repo_id,
base_repo = base,
device = device,
gpu_ordinal = target.ordinal,
@@ -7585,7 +7616,7 @@ class DiffusionBackend:
on any target not sized in bf16, and for a LOCAL directory: the table is keyed on upstream
repo ids, so a local checkpoint can only reach the coarse family entry, and a family
covering more than one size would be lowered to a number less than half what it loads.
- """
+ A snapshot inside a configured HF cache is sized by the repo id it came from."""
try:
# A whole-pipeline single file (SDXL) carries the U-Net, VAE and text encoders itself, and the base repo
# is read for config only, but the plan still adds the base's cached companion weights, so a user who once
@@ -7603,8 +7634,19 @@ class DiffusionBackend:
},
)
return plan
- if kind != "pipeline" or _is_local_path(base):
+ if kind != "pipeline":
return plan
+ table_base = base
+ if _is_local_path(base):
+ from utils.hf_cache_settings import known_hf_hub_caches
+
+ table_base = hf_cache_repo_id(base)
+ snapshot = Path(base).expanduser().resolve()
+ if table_base is None or not any(
+ snapshot.is_relative_to(Path(root).expanduser().resolve())
+ for root in known_hf_hub_caches()
+ ):
+ return plan
import torch
if getattr(target, "dtype", None) not in (torch.bfloat16, torch.float16):
@@ -7614,13 +7656,13 @@ class DiffusionBackend:
# carrying two sizes that entry is the smaller one, so a 9B derivative would be lowered to the 4B number
# and walk past the refusal. Accept the family's own default base and anything with an explicit override;
# anything else keeps its measured size.
- canonical = canonical_base(base)
+ canonical = canonical_base(table_base)
if (
- base_repo_bf16_components_gb(base) is None
+ base_repo_bf16_components_gb(table_base) is None
and canonical.lower() != str(getattr(fam, "base_repo", "") or "").lower()
):
return plan
- table = family_bf16_components_gb(fam, base)
+ table = family_bf16_components_gb(fam, table_base)
if table is None:
return plan
# The table's encoder term is the DENSE one. When this pick takes its encoder pre-cast from a hosted fp8
@@ -7633,7 +7675,7 @@ class DiffusionBackend:
fam,
te_quant_mode = text_encoder_quant,
target = target,
- base = base,
+ base = table_base,
)
transformer_gb, text_encoders_gb, vae_gb = table
resident_gb = transformer_gb + text_encoders_gb * te_scale + vae_gb
@@ -9136,7 +9178,7 @@ class DiffusionBackend:
"images": list(images),
"seed": int(seed),
"seeds": [int(s) for s in per_image_seeds],
- "repo_id": state.repo_id,
+ "repo_id": state.display_repo_id or state.repo_id,
# The BUILD this ran on, not just the repo id: a GGUF quant and a torchao scheme each change the
# pixels.
"model_kind": state.kind,
@@ -9375,6 +9417,7 @@ class DiffusionBackend:
return {
"loaded": False,
"repo_id": None,
+ "display_repo_id": None,
"family": None,
"base_repo": None,
"device": None,
@@ -9409,6 +9452,7 @@ class DiffusionBackend:
return {
"loaded": True,
"repo_id": state.repo_id,
+ "display_repo_id": state.display_repo_id,
"family": state.family.name,
"base_repo": state.base_repo,
"device": state.device,
diff --git a/studio/backend/core/inference/diffusion_engine_router.py b/studio/backend/core/inference/diffusion_engine_router.py
index abf0f9f7ed8..46fdfea80d2 100644
--- a/studio/backend/core/inference/diffusion_engine_router.py
+++ b/studio/backend/core/inference/diffusion_engine_router.py
@@ -21,6 +21,7 @@ Env knobs:
from __future__ import annotations
+import functools
import os
import sys
import threading
@@ -32,6 +33,7 @@ from core.inference.diffusion_families import (
DiffusionFamily,
family_pipeline_available,
family_sd_cpp_supported,
+ pipeline_available_family_names,
)
from core.inference.sd_cpp_backend import (
_card_lookup_inventory,
@@ -573,11 +575,17 @@ def family_buildable_here(fam: Optional[DiffusionFamily], *, model_kind: Optiona
return False
+def _supported_family_capabilities() -> tuple[str, ...]:
+ return tuple(pipeline_available_family_names())
+
+
def annotate_status(status: dict[str, Any]) -> dict[str, Any]:
"""Tag a backend status dict with the active engine + any fallback reason."""
out = dict(status)
out["engine"] = _active_engine_name
out["fallback_reason"] = _fallback_reason
+ out["supported_families"] = list(_supported_family_capabilities())
return out
diff --git a/studio/backend/core/inference/diffusion_families.py b/studio/backend/core/inference/diffusion_families.py
index e1c6c61dcdb..3edc8202c12 100644
--- a/studio/backend/core/inference/diffusion_families.py
+++ b/studio/backend/core/inference/diffusion_families.py
@@ -10,6 +10,7 @@ the full pipeline."""
from __future__ import annotations
+import importlib.util
import json
import os
import re
@@ -1257,6 +1258,7 @@ def family_prequant_filename(
# the release where diffusers' own requires-python went ">= 3.10.0", making 0.36.0 the newest a supported Python 3.9
# host can resolve
_DIFFUSERS_DROPPED_PY39 = "0.37.0"
+_MAX_PIPELINE_MANIFEST_BYTES = 1 << 20
# First diffusers release exporting each pipeline class, read off ``src/diffusers/__init__.py`` at the upstream tags
# and cross-checked against each release's requires-python on PyPI. An unlisted class gets a version-free "a newer
@@ -1326,6 +1328,172 @@ def pipeline_class_requirement(pipeline_class: str) -> tuple[Optional[str], bool
return minimum, _version_tuple(minimum) >= _version_tuple(_DIFFUSERS_DROPPED_PY39)
+def _json_dict(path: Path, max_bytes: int = _MAX_PIPELINE_MANIFEST_BYTES) -> Optional[dict]:
+ try:
+ if not path.is_file() or path.stat().st_size > max_bytes:
+ return None
+ # PowerShell writes JSON with a UTF-8 BOM; match pipeline_class_from_index.
+ payload = json.loads(path.read_text(encoding = "utf-8-sig"))
+ except (OSError, ValueError, RecursionError):
+ return None
+ return payload if isinstance(payload, dict) else None
+
+
+_CALLER_SUPPLIED_COMPONENTS = {"HiDreamImagePipeline": frozenset({"text_encoder_4", "tokenizer_4"})}
+# safetensors first, default variant only: the load uses variant=None, which cannot open *.fp16.safetensors.
+_LOCAL_PIPELINE_WEIGHT_FORMATS = (
+ (("diffusion_pytorch_model", "model"), "safetensors"),
+ (("diffusion_pytorch_model", "pytorch_model"), "bin"),
+)
+_MAX_PIPELINE_WEIGHT_INDEX_BYTES = 64 * 1024 * 1024
+_LOCAL_PIPELINE_METADATA_CONFIGS = (
+ (("tokenizer",), ("tokenizer_config.json",)),
+ (("scheduler",), ("scheduler_config.json",)),
+ (("guider", "guidance"), ("guider_config.json",)),
+ (("featureextractor", "imageprocessor"), ("preprocessor_config.json",)),
+ (("processor",), ("processor_config.json", "preprocessor_config.json")),
+)
+_SELF_CONTAINED_TOKENIZER_ASSETS = (
+ "tokenizer.json",
+ "vocab.txt",
+ "spiece.model",
+ "tokenizer.model",
+ "sentencepiece.bpe.model",
+)
+
+
+def _nonempty_file(path: Path) -> bool:
+ return path.is_file() and path.stat().st_size > 0
+
+
+def _safe_relative_parts(text: str) -> Optional[tuple[str, ...]]:
+ # Manifest paths are POSIX-relative: reject other separators and drive prefixes, or ..\\ / C: escape on Windows.
+ relative = PurePosixPath(text)
+ if "\\" in text or ":" in text or relative.is_absolute() or ".." in relative.parts:
+ return None
+ return relative.parts
+
+
+def _local_weights_are_complete(component: Path, library_name: str) -> bool:
+ # The first format with any weights present decides: a leftover .bin index cannot veto safetensors.
+ for stems, ext in _LOCAL_PIPELINE_WEIGHT_FORMATS:
+ # Transformers never reads diffusion_pytorch_model* (LTX-2's text_encoder ships both shard sets).
+ if library_name == "transformers":
+ stems = tuple(s for s in stems if s != "diffusion_pytorch_model")
+ # Transformers opens a single checkpoint before a shard index (_get_resolved_checkpoint_files).
+ if any(_nonempty_file(component / f"{s}.{ext}") for s in stems):
+ return True
+ index = next(
+ (p for s in stems if (p := component / f"{s}.{ext}.index.json").exists()), None
+ )
+ if index is not None:
+ weight_map = (_json_dict(index, _MAX_PIPELINE_WEIGHT_INDEX_BYTES) or {}).get(
+ "weight_map"
+ )
+ shards = (
+ {str(v) for v in weight_map.values() if v} if isinstance(weight_map, dict) else ()
+ )
+ parts = [_safe_relative_parts(shard) for shard in shards]
+ return bool(parts) and all(
+ p is not None and _nonempty_file(component.joinpath(*p)) for p in parts
+ )
+ sizes = [w.stat().st_size for s in stems if (w := component / f"{s}.{ext}").is_file()]
+ if sizes:
+ return any(sizes)
+ return False
+
+
+def _local_pipeline_component_is_complete(
+ component: Path, library_name: str, class_name: str, config_only_model_components: bool
+) -> bool:
+ if not component.is_dir():
+ return False
+ if library_name not in {"diffusers", "transformers"}:
+ return any(_nonempty_file(child) for child in component.iterdir())
+ identity = class_name.replace("_", "").lower()
+ for tokens, config_names in _LOCAL_PIPELINE_METADATA_CONFIGS:
+ if not any(token in identity for token in tokens):
+ continue
+ # Configs can exceed the manifest cap: LTX-2's Gemma3 tokenizer_config.json is 1.1 MB.
+ if not any(
+ _json_dict(component / name, _MAX_PIPELINE_WEIGHT_INDEX_BYTES) is not None
+ for name in config_names
+ ):
+ return False
+ if tokens[0] not in ("tokenizer", "processor") or "byt5tokenizer" in identity:
+ return True
+ return any(_nonempty_file(component / a) for a in _SELF_CONTAINED_TOKENIZER_ASSETS) or all(
+ _nonempty_file(component / a) for a in ("vocab.json", "merges.txt")
+ )
+ return _json_dict(component / "config.json") is not None and (
+ config_only_model_components or _local_weights_are_complete(component, library_name)
+ )
+
+
+def local_pipeline_components_are_complete(
+ root: Path | str,
+ filename: str,
+ *,
+ excluded_components: Sequence[str] = (),
+ config_only_model_components: bool = False,
+) -> bool:
+ """Check local component presence and known Diffusers/Transformers serialization layouts."""
+ if filename not in {"model_index.json", "modular_model_index.json"}:
+ return False
+ base = Path(root).expanduser()
+ payload = _json_dict(base / filename) or {}
+ class_name = payload.get("_class_name")
+ if not isinstance(class_name, str) or not class_name.strip():
+ return False
+ caller_supplied = _CALLER_SUPPLIED_COMPONENTS.get(class_name, frozenset())
+ declared = False
+ try:
+ for name, spec in payload.items():
+ if (
+ name.startswith("_")
+ or not isinstance(spec, (list, tuple))
+ or len(spec) < 2
+ or not (isinstance(spec[0], str) and isinstance(spec[1], str))
+ ):
+ continue
+ if name in {"", ".."} or "\\" in name or Path(name).name != name:
+ return False
+ if name in excluded_components or (
+ name in caller_supplied and not (base / name).exists()
+ ):
+ continue
+ declared = True
+ component = base / name
+ source = spec[2] if filename == "modular_model_index.json" and len(spec) >= 3 else None
+ source = source if isinstance(source, dict) else {}
+ repo = source.get("pretrained_model_name_or_path") or source.get("repo")
+ if isinstance(repo, str) and repo.strip():
+ # A modular spec may load the component from another repo or folder instead.
+ repo = repo.strip()
+ subfolder = source.get("subfolder")
+ parts = (
+ _safe_relative_parts((subfolder or "").strip())
+ if subfolder is None or isinstance(subfolder, str)
+ else None
+ )
+ if parts is None:
+ return False
+ rooted = Path(repo).expanduser()
+ rooted = rooted if rooted.is_absolute() else base / rooted
+ if not rooted.exists():
+ if repo.startswith(("/", "\\", "~", ".")) or "\\" in repo or ":" in repo:
+ return False
+ continue
+ component = rooted.joinpath(*parts)
+ if not _local_pipeline_component_is_complete(
+ component, spec[0], spec[1], config_only_model_components
+ ):
+ return False
+ except OSError:
+ return False
+ return declared
+
+
# Minimums that name a release which does not EXIST yet. ``pip install -U 'diffusers>=0.41.0'`` has
# no candidate today, so quoting it as the remedy sends someone to a command that cannot succeed.
# Studio installs the pinned main build for exactly these classes (studio/backend/requirements/
@@ -1640,6 +1808,29 @@ def family_pipeline_available(fam: Optional[DiffusionFamily]) -> bool:
return _installed_at_least(installed, minimum)
+def _family_override_resolved(family_override: Optional[str], fam) -> tuple:
+ reason = "detected from the model" if family_override is None else "requested"
+ return (family_override, fam.name, reason)
+
+
+def family_selectable(fam) -> bool:
+ """Whether a Family selector may offer ``fam``: diffusers installed and new enough.
+
+ Import-free: a pipeline-class probe from a status poll raced the loader's own diffusers import;
+ the load path keeps the strict class gate."""
+ module = sys.modules.get("diffusers", False)
+ if module is False:
+ try:
+ module = importlib.util.find_spec("diffusers")
+ except (ImportError, ValueError):
+ module = None
+ return module is not None and family_pipeline_available(fam)
+
+
+def pipeline_available_family_names() -> tuple[str, ...]:
+ return tuple(fam.name for fam in _FAMILIES if family_selectable(fam))
+
+
def family_gguf_loadable(fam: DiffusionFamily) -> bool:
"""True when a GGUF transformer can be assembled for this family. The two exclusions mirror the
ones ``DiffusionBackend.validate_load_request`` raises on (which keep their own specific
diff --git a/studio/backend/core/inference/media_auto_switch.py b/studio/backend/core/inference/media_auto_switch.py
index faa6ced2fc0..c0647a7c7fa 100644
--- a/studio/backend/core/inference/media_auto_switch.py
+++ b/studio/backend/core/inference/media_auto_switch.py
@@ -236,6 +236,7 @@ async def _start_load(
await load_diffusion_model_gated(
DiffusionLoadRequest(
model_path = pick.model_path,
+ display_repo_id = pick.model_id,
gguf_filename = pick.gguf_filename,
model_kind = pick.model_kind,
hf_token = hf_token,
@@ -249,6 +250,7 @@ async def _start_load(
await load_video_model_gated(
VideoLoadRequest(
model_path = pick.model_path,
+ display_repo_id = pick.model_id,
gguf_filename = pick.gguf_filename,
model_kind = pick.model_kind,
h3_task = partition,
diff --git a/studio/backend/core/inference/sd_cpp_backend.py b/studio/backend/core/inference/sd_cpp_backend.py
index 530d68db8dc..35d27b7ced4 100644
--- a/studio/backend/core/inference/sd_cpp_backend.py
+++ b/studio/backend/core/inference/sd_cpp_backend.py
@@ -30,7 +30,7 @@ from dataclasses import dataclass, field, replace
from pathlib import Path
from typing import Any, Optional
-from core.inference.diffusion_auto_policy import format_generation_for_log
+from core.inference.diffusion_auto_policy import build_resolved_record, format_generation_for_log
from core.inference.diffusion_compat import flux2_inner_dim_for_pick
from core.inference.diffusion_device import (
resolve_diffusion_device_target,
@@ -53,6 +53,7 @@ from core.inference.diffusion_families import (
resolve_local_gguf_child,
sd_cpp_text_encoders_for,
supported_family_names,
+ _family_override_resolved,
)
from core.inference.diffusion_memory import (
OFFLOAD_GROUP,
@@ -1943,6 +1944,7 @@ class _SdState:
family: DiffusionFamily
device: str
files: SdCppModelFiles
+ display_repo_id: Optional[str] = None
vae_format: Optional[str] = None
native_speed: str = "off"
offload_flags: tuple[str, ...] = ()
@@ -1953,6 +1955,7 @@ class _SdState:
mode: str = "server"
# Token kept so LoRA adapters selected at generate time can be fetched from the Hub.
hf_token: Optional[str] = None
+ resolved: Optional[dict] = None
# The GGUF basename this load committed: some variants pick their encoder by filename, and a local *klein-9B*.gguf
# carries that keyword only in the basename.
gguf_filename: Optional[str] = None
@@ -2445,6 +2448,7 @@ class SdCppDiffusionBackend:
# BINARY, which is a separate managed tree with its own install policy; a background load may still install
# one, exactly as it does today.
local_files_only: bool = False,
+ display_repo_id: Optional[str] = None,
gguf_filename: Optional[str] = None,
base_repo: Optional[str] = None,
family_override: Optional[str] = None,
@@ -2556,10 +2560,12 @@ class SdCppDiffusionBackend:
target = self._run_load,
kwargs = dict(
repo_id = repo_id,
+ display_repo_id = display_repo_id,
local_files_only = local_files_only,
gguf_filename = gguf_filename,
base = base,
fam = fam,
+ family_override = family_override,
hf_token = hf_token,
cpu_offload = cpu_offload,
memory_mode = memory_mode,
@@ -2578,9 +2584,11 @@ class SdCppDiffusionBackend:
self,
*,
repo_id: str,
+ display_repo_id: Optional[str] = None,
gguf_filename: str,
base: str,
fam: DiffusionFamily,
+ family_override: Optional[str] = None,
hf_token: Optional[str],
# Cache-only when set: every Hub call below is either skipped or told to resolve from disk, so a load nobody
# asked for cannot pull bytes. See begin_load for what it does not cover.
@@ -2919,6 +2927,7 @@ class SdCppDiffusionBackend:
)
state = _SdState(
repo_id = repo_id,
+ display_repo_id = display_repo_id,
base_repo = base,
family = fam,
device = device,
@@ -2934,6 +2943,9 @@ class SdCppDiffusionBackend:
server = server,
mode = mode,
hf_token = hf_token,
+ resolved = build_resolved_record(
+ {"family_override": _family_override_resolved(family_override, fam)}
+ ),
gguf_filename = gguf_filename,
flux2_inner_dim = inner_dim,
# Only the one-shot path needs to carry it: it re-resolves sd-cli per image, long after this
@@ -3666,7 +3678,7 @@ class SdCppDiffusionBackend:
"images": images,
"seed": int(seed),
"seeds": seeds,
- "repo_id": state.repo_id,
+ "repo_id": state.display_repo_id or state.repo_id,
# The BUILD, for the recipe: the repo id alone does not say WHICH GGUF quant ran, and two quants
# make different pixels.
"model_kind": "gguf",
@@ -4129,6 +4141,7 @@ class SdCppDiffusionBackend:
return {
"loaded": False,
"repo_id": None,
+ "display_repo_id": None,
"family": None,
"base_repo": None,
"device": None,
@@ -4144,6 +4157,7 @@ class SdCppDiffusionBackend:
"transformer_quant": None,
"attention_backend": None,
"transformer_cache": None,
+ "resolved": None,
"engine": "sd_cpp",
"native_mode": None,
"supports_lora": False,
@@ -4183,6 +4197,7 @@ class SdCppDiffusionBackend:
return {
"loaded": True,
"repo_id": state.repo_id,
+ "display_repo_id": state.display_repo_id,
"family": state.family.name,
"base_repo": state.base_repo,
"device": state.device,
@@ -4206,6 +4221,7 @@ class SdCppDiffusionBackend:
"transformer_quant": None,
"attention_backend": None,
"transformer_cache": None,
+ "resolved": state.resolved,
"engine": "sd_cpp",
"supports_lora": diffusion_lora.supports_lora(
engine = "sd_cpp",
diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.py
index 0bd4e6d9367..e5f690ef4aa 100644
--- a/studio/backend/core/inference/video.py
+++ b/studio/backend/core/inference/video.py
@@ -161,7 +161,7 @@ from .diffusion_transformer_quant import (
stored_denoiser_precision,
transformer_is_quantised,
)
-from .diffusion import _memory_request_forces_offload
+from .diffusion import _family_override_resolved, _memory_request_forces_offload
from .diffusion_native_quant import native_quant_reason
from .diffusion_batched import is_oom_error
from .diffusion_precision import (
@@ -178,6 +178,7 @@ from .video_families import (
VIDEO_GENERATION_BUSY_MSG,
VIDEO_MODEL_CHANGED_MSG,
VIDEO_NOT_LOADED_MSG,
+ pipeline_available_video_families,
VideoFamily,
default_video_generation_params,
detect_video_family,
@@ -923,18 +924,24 @@ def _assert_pick_is_not_speech(
def _detect_load_family(
- repo_id: str, gguf_filename: Optional[str], family_override: Optional[str]
+ repo_id: str,
+ gguf_filename: Optional[str],
+ family_override: Optional[str],
+ display_repo_id: Optional[str] = None,
) -> Optional[VideoFamily]:
"""Family detection shared by validate_load_request and the load worker: the
repo id first, then the picked filename -- a local directory or generically
named repo often carries the family token only in the checkpoint filename,
and the worker must resolve the same family the validator accepted."""
- fam = detect_video_family(repo_id, family_override) or (
- detect_video_family(f"{repo_id}/{gguf_filename}")
- if gguf_filename and not family_override
- else None
+ if family_override:
+ return detect_video_family(repo_id, family_override)
+ fam = (
+ (display_repo_id and detect_video_family(display_repo_id))
+ or detect_video_family(repo_id)
+ or (gguf_filename and detect_video_family(f"{repo_id}/{gguf_filename}"))
+ or None
)
- if fam is None and gguf_filename and not family_override:
+ if fam is None and gguf_filename:
# A renamed GGUF carries no family token, so resolve via general.architecture. No-backend archs still yield None
# (a 400)
arch = _picked_gguf_arch(repo_id, gguf_filename)
@@ -968,6 +975,7 @@ class _VideoLoadState:
device: str
dtype: str
kind: str
+ display_repo_id: Optional[str] = None
engine: str = "diffusers"
# The torch ordinal this pipeline's weights were placed on, or None for an automatic pick. Committed WITH the
# pipeline, so a load in flight never moves the resident model's card.
@@ -2246,6 +2254,16 @@ def _probe_target(request_shape: dict[str, Any]) -> Any:
return types.SimpleNamespace(device = request_shape.get("device"), dtype = dtype)
+def _video_family_capabilities() -> tuple[tuple[str, ...], tuple[str, ...]]:
+ # Once per process: on Metal the device probe allocates and syncs, which a status poll must not repeat.
+ available = pipeline_available_video_families(device = resolve_diffusion_device_target().device)
+ return (
+ tuple(fam.name for fam in available),
+ tuple(fam.name for fam in available if fam.modular_workflow),
+ )
+
+
class VideoBackend:
"""One loaded video pipeline; loads swap it atomically (same model as images)."""
@@ -2308,6 +2326,7 @@ class VideoBackend:
gguf_filename: Optional[str] = None,
base_repo: Optional[str] = None,
family_override: Optional[str] = None,
+ display_repo_id: Optional[str] = None,
model_kind: Optional[str] = None,
transformer_quant: Optional[str] = None,
text_encoder_quant: Optional[str] = None,
@@ -2322,7 +2341,7 @@ class VideoBackend:
f"'{repo_id}' is a GGUF repo: pick one of its .gguf files "
"(gguf_filename) instead of loading it as a diffusers pipeline."
)
- fam = _detect_load_family(repo_id, gguf_filename, family_override)
+ fam = _detect_load_family(repo_id, gguf_filename, family_override, display_repo_id)
if fam is None:
raise ValueError(
f"'{repo_id}' is not a supported text-to-video model. Supported families: "
@@ -2404,6 +2423,17 @@ class VideoBackend:
f"can be applied and the dense weights cannot be quantized in place. "
f"{hint}"
)
+ if kind == "pipeline":
+ from .diffusion_families import local_pipeline_components_are_complete
+
+ root = Path(repo_id).expanduser()
+ index = "modular_model_index.json" if fam.modular_workflow else "model_index.json"
+ if root.exists() and not (
+ root.is_dir() and local_pipeline_components_are_complete(root, index)
+ ):
+ raise ValueError(
+ f"Local pipeline path is not a diffusers directory (no valid {index}): {repo_id}"
+ )
from .video_minimax_h3 import is_h3_native, validate_h3_transformer_filename
if is_h3_native(fam, kind):
@@ -2444,7 +2474,8 @@ class VideoBackend:
# the load.
from core.inference.diffusion import _assert_local_base_is_pipeline
- _assert_local_base_is_pipeline(base_repo)
+ excluded = (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:
@@ -2494,22 +2525,6 @@ class VideoBackend:
)
elif path_shaped:
raise ValueError(f"Local model path '{repo_id}' does not exist.")
- # A local pipeline pick must be a diffusers directory (model_index.json), else it would only fail after eviction
- if kind == "pipeline":
- root = Path(repo_id).expanduser()
- # Gate on .exists() (not .is_dir()) so a local FILE picked as a pipeline is rejected too
- indexes = (
- ("model_index.json", "modular_model_index.json")
- if fam.modular_workflow
- else ("model_index.json",)
- )
- if root.exists() and not (
- root.is_dir() and any((root / name).is_file() for name in indexes)
- ):
- raise ValueError(
- f"Local pipeline path is not a diffusers directory "
- f"(no {' or '.join(indexes)}): {repo_id}"
- )
# Reject a malformed transformer_quant cheaply, before the handoff (pipeline-kind only, matching the image
# backend)
normalize_transformer_quant(transformer_quant)
@@ -2525,6 +2540,7 @@ class VideoBackend:
self,
repo_id: str,
*,
+ display_repo_id: Optional[str] = None,
local_files_only: bool = False,
gguf_filename: Optional[str] = None,
base_repo: Optional[str] = None,
@@ -2561,6 +2577,7 @@ class VideoBackend:
gguf_filename = gguf_filename,
base_repo = base_repo,
family_override = family_override,
+ display_repo_id = display_repo_id,
model_kind = model_kind,
transformer_quant = transformer_quant,
text_encoder_quant = text_encoder_quant,
@@ -2633,6 +2650,7 @@ class VideoBackend:
target = self._run_load,
kwargs = dict(
repo_id = repo_id,
+ display_repo_id = display_repo_id,
local_files_only = local_files_only,
gguf_filename = gguf_filename,
base_repo = base_repo,
@@ -2666,7 +2684,10 @@ class VideoBackend:
local_files_only = bool(kwargs.get("local_files_only"))
try:
fam = _detect_load_family(
- kwargs["repo_id"], kwargs.get("gguf_filename"), kwargs.get("family_override")
+ kwargs["repo_id"],
+ kwargs.get("gguf_filename"),
+ kwargs.get("family_override"),
+ kwargs.get("display_repo_id"),
)
# Also on the worker, which a direct begin_load reaches without a plan. Here rather than in
# validate_load_request, which is network-free by contract.
@@ -2989,9 +3010,11 @@ class VideoBackend:
token: Optional[int],
cancel_event: threading.Event,
repo_id: str,
+ display_repo_id: Optional[str] = None,
gguf_filename: Optional[str] = None,
hf_token: Optional[str] = None,
memory_mode: Optional[str] = None,
+ family_override: Optional[str] = None,
gpu_ordinal: Optional[int] = None,
# NAMED so a static step-skip ask can be recorded as declined: sd.cpp runs every step itself.
transformer_cache: Optional[str] = None,
@@ -3395,6 +3418,7 @@ class VideoBackend:
pipe = runtime,
family = fam,
repo_id = repo_id,
+ display_repo_id = display_repo_id,
base_repo = fam.base_repo,
device = native_device,
gpu_ordinal = native_ordinal,
@@ -3412,6 +3436,7 @@ class VideoBackend:
attention_backend = "flash",
resolved = build_resolved_record(
{
+ "family_override": _family_override_resolved(family_override, fam),
"memory_mode": (memory_mode, policy, "native model offload"),
"attention_backend": (
None,
@@ -4360,6 +4385,7 @@ class VideoBackend:
gguf_filename: Optional[str] = None,
base_repo: Optional[str] = None,
family_override: Optional[str] = None,
+ display_repo_id: Optional[str] = None,
model_kind: Optional[str] = None,
hf_token: Optional[str] = None,
transformer_quant: Optional[str] = None,
@@ -4388,7 +4414,7 @@ class VideoBackend:
download manager."""
from huggingface_hub import HfApi
- fam = _detect_load_family(repo_id, gguf_filename, family_override)
+ fam = _detect_load_family(repo_id, gguf_filename, family_override, display_repo_id)
# _detect_load_family resolves from the REPO id first, so a mixed repo answers its media family for every file
# in it, a csm quant included. Refuse before the plan stages a byte.
_assert_pick_is_not_speech(repo_id, gguf_filename, hf_token)
@@ -5081,6 +5107,7 @@ class VideoBackend:
self,
repo_id: str,
*,
+ display_repo_id: Optional[str] = None,
local_files_only: bool = False,
gguf_filename: Optional[str] = None,
base_repo: Optional[str] = None,
@@ -5108,6 +5135,7 @@ class VideoBackend:
gguf_filename = gguf_filename,
base_repo = base_repo,
family_override = family_override,
+ display_repo_id = display_repo_id,
model_kind = model_kind,
transformer_quant = transformer_quant,
text_encoder_quant = text_encoder_quant,
@@ -5122,9 +5150,11 @@ class VideoBackend:
token = _load_token,
cancel_event = threading.Event(),
repo_id = repo_id,
+ display_repo_id = display_repo_id,
gguf_filename = gguf_filename,
hf_token = hf_token,
memory_mode = memory_mode,
+ family_override = family_override,
# Carried, not defaulted: load_pipeline is also reached directly (no _run_load), and dropping it here
# would let an offline load fetch the four-file bundle.
local_files_only = local_files_only,
@@ -5224,12 +5254,14 @@ class VideoBackend:
fam = fam,
target = target,
repo_id = repo_id,
+ display_repo_id = display_repo_id,
base = base,
kind = kind,
dtype = dtype,
device = device,
hf_token = hf_token,
memory_mode = memory_mode,
+ family_override = family_override,
transformer_quant = transformer_quant,
text_encoder_quant = text_encoder_quant,
# The speed layer lives BELOW this dispatch, which the modular branch never reached: no channels_last
@@ -6193,6 +6225,7 @@ class VideoBackend:
resolved = build_resolved_record(
{
+ "family_override": _family_override_resolved(family_override, fam),
"memory_mode": _memory_mode_resolved(memory_mode, plan, offload_policy),
"speed_mode": (
speed_mode,
@@ -6282,6 +6315,7 @@ class VideoBackend:
pipe = pipe,
family = fam,
repo_id = repo_id,
+ display_repo_id = display_repo_id,
base_repo = base,
device = device,
gpu_ordinal = target.ordinal,
@@ -6396,12 +6430,14 @@ class VideoBackend:
torch: Any,
fam: VideoFamily,
repo_id: str,
+ display_repo_id: Optional[str] = None,
base: str,
kind: str,
dtype: Any,
device: str,
hf_token: Optional[str],
memory_mode: Optional[str],
+ family_override: Optional[str] = None,
transformer_quant: Optional[str] = None,
text_encoder_quant: Optional[str] = None,
speed_mode: Optional[str] = None,
@@ -7056,6 +7092,7 @@ class VideoBackend:
resolved = build_resolved_record(
{
+ "family_override": _family_override_resolved(family_override, fam),
"memory_mode": (
memory_mode,
offload_policy,
@@ -7143,6 +7180,7 @@ class VideoBackend:
pipe = pipe,
family = fam,
repo_id = repo_id,
+ display_repo_id = display_repo_id,
base_repo = base,
device = device,
gpu_ordinal = umem_target.ordinal,
@@ -7915,7 +7953,7 @@ class VideoBackend:
# and the log is not the place for user content.
request_shape = {
"family": fam.name,
- "repo_id": state.repo_id,
+ "repo_id": state.display_repo_id or state.repo_id,
"gguf": state.gguf_filename,
"width": width,
"height": height,
@@ -8253,7 +8291,7 @@ class VideoBackend:
return {
"mp4_bytes": mp4_bytes,
"seed": int(seed),
- "repo_id": state.repo_id,
+ "repo_id": state.display_repo_id or state.repo_id,
"width": width,
"height": height,
"num_frames": len(video_frames),
@@ -8630,7 +8668,7 @@ class VideoBackend:
return {
"mp4_bytes": mp4_bytes,
"seed": int(seed),
- "repo_id": state.repo_id,
+ "repo_id": state.display_repo_id or state.repo_id,
"width": actual_width,
"height": actual_height,
"num_frames": actual_frames,
@@ -8839,11 +8877,15 @@ class VideoBackend:
def status(self) -> dict[str, Any]:
state = self._state
+ supported, modular = _video_family_capabilities()
if state is None:
return {
"loaded": False,
"repo_id": None,
+ "display_repo_id": None,
"family": None,
+ "supported_families": list(supported),
+ "modular_families": list(modular),
"base_repo": None,
"device": None,
"dtype": None,
@@ -8882,6 +8924,7 @@ class VideoBackend:
fam = state.family
default_steps, default_guidance = default_video_generation_params(
state.gguf_filename,
+ state.display_repo_id,
state.repo_id,
state.base_repo,
fallback = (fam.default_steps, fam.default_guidance),
@@ -8889,7 +8932,10 @@ class VideoBackend:
return {
"loaded": True,
"repo_id": state.repo_id,
+ "display_repo_id": state.display_repo_id,
"family": fam.name,
+ "supported_families": list(supported),
+ "modular_families": list(modular),
"base_repo": state.base_repo,
"device": state.device,
"dtype": state.dtype,
diff --git a/studio/backend/core/inference/video_families.py b/studio/backend/core/inference/video_families.py
index be9a59423ac..db45efafccf 100644
--- a/studio/backend/core/inference/video_families.py
+++ b/studio/backend/core/inference/video_families.py
@@ -413,6 +413,15 @@ def supported_video_family_names() -> tuple[str, ...]:
return tuple(fam.name for fam in _FAMILIES)
+def pipeline_available_video_families(*, device: Optional[str] = None) -> tuple[VideoFamily, ...]:
+ from .diffusion_families import family_selectable
+ return tuple(
+ fam
+ for fam in _FAMILIES
+ if family_selectable(fam) and not (device == "mps" and fam.modular_workflow)
+ )
+
+
def resolve_video_base_repo(fam: VideoFamily, base_repo: Optional[str]) -> str:
"""The companion diffusers repo: caller-supplied if given, else the family fallback."""
base = (base_repo or "").strip()
diff --git a/studio/backend/hub/schemas/inventory.py b/studio/backend/hub/schemas/inventory.py
index c7db2572437..808ac0edcd2 100644
--- a/studio/backend/hub/schemas/inventory.py
+++ b/studio/backend/hub/schemas/inventory.py
@@ -12,6 +12,16 @@ from typing import List, Literal, Optional
ModelFormat = Literal["gguf", "safetensors", "adapter", "checkpoint", "unknown"]
ModelRuntime = Literal["llama_cpp", "transformers", "adapter", "unknown"]
+LocalArtifactKind = Literal[
+ "diffusers_pipeline",
+ "diffusers_modular_pipeline",
+ "diffusers_dual_pipeline",
+ "transformers_model",
+ "single_file_checkpoint",
+ "gguf",
+ "adapter",
+ "unknown",
+]
class GgufVariantDetail(BaseModel):
@@ -157,6 +167,10 @@ class LocalModelInfo(BaseModel):
path: str = Field(..., description = "Local path where model data was discovered")
size_bytes: int = Field(0, description = "Observed model artifact size in bytes")
model_format: ModelFormat = Field("unknown", description = "Model file format")
+ artifact_kind: LocalArtifactKind = Field(
+ "unknown",
+ description = "Structural contract, e.g. a Diffusers pipeline root vs a Transformers dir",
+ )
runtime: ModelRuntime = Field("unknown", description = "Expected runtime backend")
format_variant: Optional[str] = Field(
None, description = "Format variant label, for example a GGUF quant"
@@ -275,6 +289,7 @@ class CachedRepoBase(BaseModel):
inventory_id: Optional[str] = None
load_id: Optional[str] = None
model_format: ModelFormat = "unknown"
+ artifact_kind: LocalArtifactKind = "unknown"
runtime: ModelRuntime = "unknown"
format_variant: Optional[str] = None
capabilities: LocalModelCapabilities = Field(default_factory = LocalModelCapabilities)
diff --git a/studio/backend/hub/services/models/cache_inventory.py b/studio/backend/hub/services/models/cache_inventory.py
index 6879e4e936f..9debba84117 100644
--- a/studio/backend/hub/services/models/cache_inventory.py
+++ b/studio/backend/hub/services/models/cache_inventory.py
@@ -28,6 +28,7 @@ from hub.utils.snapshot_filters import (
from hub.services.models.common import (
_capabilities_for_format,
_classify_non_gguf_model_format,
+ _diffusers_pipeline_artifact_kind,
_gguf_variant_state_summary,
_is_adapter_weight_name,
_is_checkpoint_weight_name,
@@ -1171,10 +1172,12 @@ def _scan_cached_models(
if not any(tag.lower() == "whisper" for tag in tags):
tags.append("whisper")
local_metadata["tags"] = tags
+ pipeline_artifact_kind = _diffusers_pipeline_artifact_kind(load_snapshot)
row = {
"repo_id": repo_id,
"size_bytes": payload.size_bytes,
"cache_path": str(repo_info.repo_path),
+ "artifact_kind": pipeline_artifact_kind or "unknown",
"task": row_task,
"audio_type": audio_type,
"partial": snapshot_partial,
@@ -1227,6 +1230,9 @@ def _scan_cached_models(
tts_only = is_output_audio,
)
)
+ # Pin the immutable snapshot, not the bare id: refs/main can move after this structural scan.
+ if row_task is None and pipeline_artifact_kind is not None:
+ row["load_id"] = str(load_snapshot)
# Native backend selection reads the load identity itself, so a custom native fork addressed only by repo id is indistinguishable from an ordinary LLM.
if native_audio_type and load_snapshot is not None:
row["load_id"] = str(load_snapshot)
diff --git a/studio/backend/hub/services/models/common.py b/studio/backend/hub/services/models/common.py
index a52273cc60e..a1a5ee27dda 100644
--- a/studio/backend/hub/services/models/common.py
+++ b/studio/backend/hub/services/models/common.py
@@ -13,6 +13,7 @@ from typing import List, Literal, Optional
from urllib.parse import quote
from hub.schemas.inventory import (
+ LocalArtifactKind,
LocalModelCapabilities,
LocalModelInfo,
ModelFormat,
@@ -101,7 +102,22 @@ def _is_model_directory(d: Path) -> bool:
return False
+def _diffusers_pipeline_artifact_kind(path: Optional[Path]) -> Optional[LocalArtifactKind]:
+ if path is None:
+ return None
+ from core.inference.diffusion_families import local_pipeline_components_are_complete
+
+ index, modular = (
+ local_pipeline_components_are_complete(path, name)
+ for name in ("model_index.json", "modular_model_index.json")
+ )
+ if index:
+ return "diffusers_dual_pipeline" if modular else "diffusers_pipeline"
+ return "diffusers_modular_pipeline" if modular else None
+
+
def _is_diffusers_pipeline_dir(path: Path) -> bool:
+ # An interrupted copy is still one pipeline; completeness gates only artifact_kind.
try:
return (path / "model_index.json").is_file() or (
path / "modular_model_index.json"
@@ -793,6 +809,7 @@ def _local_model_info(
load_path: Path,
source: LocalModelSource,
model_format: ModelFormat,
+ artifact_kind: Optional[LocalArtifactKind] = None,
display_name: Optional[str] = None,
model_id: Optional[str] = None,
updated_at: Optional[float] = None,
@@ -813,6 +830,10 @@ def _local_model_info(
else str(load_path)
)
semantic_id = model_id or str(load_path)
+ if artifact_kind is None and model_format in {"safetensors", "checkpoint"}:
+ artifact_kind = "single_file_checkpoint" if scan_path.is_file() else "transformers_model"
+ elif artifact_kind is None:
+ artifact_kind = model_format if model_format in {"gguf", "adapter"} else "unknown"
return LocalModelInfo(
id = load_id,
inventory_id = _local_inventory_id(
@@ -835,6 +856,7 @@ def _local_model_info(
updated_at = updated_at,
partial = partial,
model_format = model_format,
+ artifact_kind = artifact_kind,
runtime = _runtime_for_format(model_format),
format_variant = format_variant,
capabilities = _capabilities_for_format(
@@ -976,6 +998,9 @@ def _classify_local_path(
load_path = load_path,
source = source,
model_format = fallback_format,
+ artifact_kind = (
+ _diffusers_pipeline_artifact_kind(scan_path) if scan_path.is_dir() else None
+ ),
display_name = display_name,
model_id = model_id,
updated_at = updated_at,
diff --git a/studio/backend/hub/tests/test_model_services.py b/studio/backend/hub/tests/test_model_services.py
index 9704d0246de..53e52090433 100644
--- a/studio/backend/hub/tests/test_model_services.py
+++ b/studio/backend/hub/tests/test_model_services.py
@@ -2257,7 +2257,7 @@ def test_cached_models_scan_emits_curated_and_custom_whisper_as_stt(monkeypatch,
lambda repo_path, _snapshot = None: {"_hidden_stt": "custom-whisper" in str(repo_path)},
)
- rows = cache_inventory._scan_cached_models()
+ rows = cache_inventory._scan_cached_models(active_hub_cache = curated_path.parent)
rows_by_repo = {row["repo_id"]: row for row in rows}
assert set(rows_by_repo) == {"unsloth/whisper-tiny", "Org/custom-whisper"}
@@ -2329,7 +2329,7 @@ def _diffusion_scan(
return task
monkeypatch.setattr(cache_inventory, "_cached_row_task", row_task)
- rows = cache_inventory._scan_cached_models()
+ rows = cache_inventory._scan_cached_models(active_hub_cache = tmp_path / "hub")
assert len(rows) == 1
assert selected_snapshots == ([snapshot] if expect_task_classification else [])
return rows[0]
@@ -2378,6 +2378,7 @@ def test_cached_models_scan_keeps_a_complete_pipeline_loadable(monkeypatch, tmp_
assert row["partial"] is False
assert row["companion_prefetch"] is False
assert row["single_file"] is False
+ assert row["load_id"] == "Org/Pipeline-Complete"
def test_cached_models_scan_exposes_minimax_music3_modular_pipeline(monkeypatch, tmp_path):
@@ -2393,6 +2394,8 @@ def test_cached_models_scan_exposes_minimax_music3_modular_pipeline(monkeypatch,
modular_manifest = {
"_class_name": "MiniMaxMusic3ModularPipeline",
"_blocks_class_name": "MiniMaxMusic3Blocks",
+ # A component sourced from its Hub repo, not the snapshot.
+ "transformer": ["diffusers", "Model", {"pretrained_model_name_or_path": "Org/Music"}],
},
expect_task_classification = False,
)
@@ -2400,6 +2403,10 @@ def test_cached_models_scan_exposes_minimax_music3_modular_pipeline(monkeypatch,
assert row["task"] == "text-to-speech"
assert row["audio_type"] == "minimax_music3"
assert row["capabilities"]["can_chat"] is False
+ assert row["artifact_kind"] == "diffusers_modular_pipeline"
+ assert row["load_id"] == str(
+ tmp_path / "hub/models--MiniMaxAI--MiniMax-Music3/snapshots" / _SNAPSHOT_SHA
+ )
assert row["partial"] is False
assert row["single_file"] is False
@@ -6932,7 +6939,7 @@ def _write_pipeline(root: Path, *, components = ("transformer", "vae", "text_enc
(MiniMax-H3, HunyuanVideo, Qwen-Image, HiDream) has exactly this shape."""
root.mkdir(parents = True, exist_ok = True)
(root / "model_index.json").write_text(
- json.dumps({"_class_name": "MiniMaxH3Pipeline", "_diffusers_version": "0.39.0"}),
+ json.dumps({"_class_name": "MiniMaxH3Pipeline", "transformer": ["diffusers", "Model"]}),
encoding = "utf-8",
)
for name in components:
@@ -6976,6 +6983,16 @@ def test_the_lmstudio_walk_does_not_descend_into_a_pipeline(tmp_path):
assert not names & {"vae", "transformer", "text_encoder"}
+def test_the_walk_does_not_descend_into_an_interrupted_pipeline_copy(tmp_path):
+ root = tmp_path / "scan"
+ pipeline = _write_pipeline(root / "MiniMax-H3-local")
+ (pipeline / "transformer" / "diffusion_pytorch_model.safetensors").unlink()
+
+ names = {Path(row.path).name for row in local_inventory._scan_lmstudio_dir(root)}
+
+ assert names == {"MiniMax-H3-local"}
+
+
def test_a_scan_folder_pointed_straight_at_a_pipeline_is_not_walked_as_a_publisher(tmp_path):
"""The same walk, entered AT the pipeline. A user adding the model folder itself as a scan
folder is the obvious thing to do, and it published vae / transformer / text_encoder as three
diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.py
index b3ad0ed963f..5fec97e9831 100644
--- a/studio/backend/models/inference.py
+++ b/studio/backend/models/inference.py
@@ -3957,6 +3957,8 @@ class DiffusionLoadRequest(BaseModel):
"""Request to load a local diffusion (text-to-image) checkpoint."""
model_path: str = Field(..., description = "Diffusion repo id or local path")
+ display_repo_id: Optional[str] = Field(None, description = "Logical Hub id of a local snapshot")
+ _blank_display_id = field_validator("display_repo_id")(lambda v: (v or "").strip() or None)
# The same inventory handle the picker was shown; see `resolve_inventory_handle`.
_resolve_the_handle = field_validator("model_path")(resolve_inventory_handle)
gguf_filename: Optional[str] = Field(
@@ -4684,7 +4686,9 @@ class DiffusionStatusResponse(BaseModel):
loaded: bool = Field(False, description = "Whether a diffusion model is loaded")
repo_id: Optional[str] = Field(None, description = "Loaded repo id or local path")
+ display_repo_id: Optional[str] = Field(None, description = "Logical Hub id of a local snapshot")
family: Optional[str] = Field(None, description = "Detected diffusion family")
+ supported_families: List[str] = Field(default_factory = list, description = "Loadable families")
base_repo: Optional[str] = Field(None, description = "Companion diffusers base repo")
device: Optional[str] = Field(None, description = "Device the pipeline is on")
dtype: Optional[str] = Field(None, description = "Compute dtype")
@@ -5025,6 +5029,8 @@ class VideoLoadRequest(BaseModel):
"""Request to load a local text-to-video checkpoint."""
model_path: str = Field(..., description = "Video repo id or local path")
+ display_repo_id: Optional[str] = Field(None, description = "Logical Hub id of a local snapshot")
+ _blank_display_id = field_validator("display_repo_id")(lambda v: (v or "").strip() or None)
# The same inventory handle the picker was shown; see `resolve_inventory_handle`.
_resolve_the_handle = field_validator("model_path")(resolve_inventory_handle)
gguf_filename: Optional[str] = Field(
@@ -5527,7 +5533,10 @@ class VideoStatusResponse(BaseModel):
loaded: bool = Field(False, description = "Whether a video model is loaded")
repo_id: Optional[str] = Field(None, description = "Loaded repo id or local path")
+ display_repo_id: Optional[str] = Field(None, description = "Logical Hub id of a local snapshot")
family: Optional[str] = Field(None, description = "Detected video family")
+ supported_families: List[str] = Field(default_factory = list, description = "Loadable families")
+ modular_families: List[str] = Field(default_factory = list, description = "Modular families")
base_repo: Optional[str] = Field(None, description = "Companion diffusers base repo")
device: Optional[str] = Field(None, description = "Device the pipeline is on")
dtype: Optional[str] = Field(None, description = "Compute dtype")
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 0b025394620..db04ee9e43e 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -42052,6 +42052,7 @@ async def load_diffusion_model_gated(
# Kicks the slow load onto a background thread and returns at once (the client polls images/load-progress).
return engine.begin_load(
request.model_path,
+ display_repo_id = request.display_repo_id,
# a load nobody asked for may not reach the hub: the switch verified locality
# from the outside, and this is what makes that promise the loader's own rule
local_files_only = not user_initiated,
@@ -42113,7 +42114,7 @@ async def load_diffusion_model_gated(
*account_access.media_adapter_references(request),
)
reset_media_load_progress("image")
- return DiffusionStatusResponse(**annotate_status(status_dict))
+ return DiffusionStatusResponse(**(await asyncio.to_thread(annotate_status, status_dict)))
except (ValueError, FileNotFoundError) as exc:
raise HTTPException(status_code = 400, detail = redact_native_paths(str(exc)))
except account_access.GpuBusyForAnotherAccountError as exc:
@@ -42823,7 +42824,9 @@ async def unload_diffusion_model(
from hub.utils.host_paths import redact_host_paths, restore_inventory_handles
return redact_host_paths(
- restore_inventory_handles(DiffusionStatusResponse(**annotate_status(status_dict))),
+ restore_inventory_handles(
+ DiffusionStatusResponse(**(await asyncio.to_thread(annotate_status, status_dict)))
+ ),
via_api_key = via_api_key,
)
@@ -42838,7 +42841,7 @@ async def diffusion_status(
from core.inference.diffusion_engine_router import active_status
from hub.utils.host_paths import redact_host_paths
- status_dict = active_status()
+ status_dict = await asyncio.to_thread(active_status)
if account_access.resident_hidden("diffusion", status_dict.get("repo_id")):
return account_access.hidden_resident_response()
# Step-skip counters trace a render as it runs, which generate-progress hides from other accounts:
diff --git a/studio/backend/routes/models.py b/studio/backend/routes/models.py
index fb4fd26e27a..51eed6ad180 100644
--- a/studio/backend/routes/models.py
+++ b/studio/backend/routes/models.py
@@ -21,6 +21,7 @@ from core.inference.memory_contract import (
project_kv_cache_estimate,
)
from core.inference.model_ids import display_model_name
+from hub.schemas.inventory import LocalArtifactKind
from hub.services.models import account_access
from hub.services.models import catalog_classification as _catalog_classification
from utils import gguf_archs as _gguf_archs
@@ -32,6 +33,7 @@ from hub.services.models.catalog_classification import (
_repo_has_pipeline_index,
_repo_is_diffusers,
)
+from hub.services.models.common import _diffusers_pipeline_artifact_kind
# Compatibility aliases: these moved to catalog_classification, but callers and tests still resolve them
# from routes.models. Assigned through the module rather than re-imported, since an import this module never
@@ -96,6 +98,7 @@ class CachedModelRepo(BaseModel):
load_id: Optional[str] = None
# "adapter" for a cached LoRA/PEFT repo; pickers that offer whole models filter on it.
model_format: Optional[str] = None
+ artifact_kind: Optional[LocalArtifactKind] = None
# False for an encoder-only repo (embedding/CLIP/ViT); undeclared, response_model drops it.
can_chat: Optional[bool] = None
# True for an image/video diffusion repo. Not the same question as task, which says only whether this
@@ -5354,8 +5357,13 @@ def cached_model_rows(cache_scans = None) -> list[dict]:
"size_bytes": total_size,
"task": row_task,
}
+ pipeline_artifact_kind = _diffusers_pipeline_artifact_kind(selected)
+ if pipeline_artifact_kind is not None:
+ row["artifact_kind"] = pipeline_artifact_kind
# Pin a copy its bare id cannot reach, so the pick loads the found snapshot.
- if model_load_id:
+ if row_task is None and pipeline_artifact_kind is not None:
+ row["load_id"] = str(selected)
+ elif model_load_id:
row["load_id"] = model_load_id
model_format = _repo_model_format(repo_info, selected)
if model_format:
diff --git a/studio/backend/routes/video.py b/studio/backend/routes/video.py
index 018fb3c4664..3f86c04ce54 100644
--- a/studio/backend/routes/video.py
+++ b/studio/backend/routes/video.py
@@ -183,6 +183,7 @@ async def video_download_plan(
request.model_path,
gguf_filename = request.gguf_filename,
family_override = request.family_override,
+ display_repo_id = request.display_repo_id,
model_kind = kind,
base_repo = request.base_repo,
transformer_quant = request.transformer_quant,
@@ -225,6 +226,7 @@ async def video_download_plan(
gguf_filename = request.gguf_filename,
base_repo = request.base_repo,
family_override = request.family_override,
+ display_repo_id = request.display_repo_id,
model_kind = kind,
hf_token = request.hf_token,
# The plan must see the encoder policy the load will use: an fp8 request takes a hosted pre-cast encoder, so
@@ -358,6 +360,7 @@ async def load_video_model_gated(
gguf_filename = request.gguf_filename,
base_repo = request.base_repo,
family_override = request.family_override,
+ display_repo_id = request.display_repo_id,
model_kind = kind,
transformer_quant = request.transformer_quant,
text_encoder_quant = request.text_encoder_quant,
@@ -411,6 +414,7 @@ async def load_video_model_gated(
# network-free.
return backend.begin_load(
request.model_path,
+ display_repo_id = request.display_repo_id,
# a load nobody asked for may not reach the hub: the switch verified locality
# from the outside, and this makes that promise the loader's own rule
local_files_only = not user_initiated,
@@ -770,7 +774,7 @@ async def video_status(
from hub.utils.host_paths import redact_host_paths
backend = get_video_backend()
- status_dict = backend.status()
+ status_dict = await asyncio.to_thread(backend.status)
if account_access.resident_hidden("video", status_dict.get("repo_id")):
return account_access.hidden_resident_response()
# Step-skip counters trace a clip as it runs, which generate-progress hides from other accounts:
diff --git a/studio/backend/tests/multi_account/test_media_unload_handoff.py b/studio/backend/tests/multi_account/test_media_unload_handoff.py
index dbbe21ce205..255e89535fb 100644
--- a/studio/backend/tests/multi_account/test_media_unload_handoff.py
+++ b/studio/backend/tests/multi_account/test_media_unload_handoff.py
@@ -3,6 +3,7 @@
"""CPU reproduction: an authorized image unload cancels a later foreign generation."""
+import json
import sys
import secrets
import threading
@@ -52,6 +53,14 @@ def client_for(account):
return TestClient(app)
+def _write_local_pipeline(root: Path) -> None:
+ scheduler = ["diffusers", "FlowMatchEulerDiscreteScheduler"]
+ manifest = {"_class_name": "ZImagePipeline", "scheduler": scheduler}
+ (root / "model_index.json").write_text(json.dumps(manifest))
+ (root / "scheduler").mkdir()
+ (root / "scheduler" / "scheduler_config.json").write_text("{}")
+
+
@pytest.mark.parametrize("unloader", ["alice", "bob", "unsloth"])
@pytest.mark.parametrize(
"load_method,phase",
@@ -71,7 +80,7 @@ def test_cpu_load_cancellation_requires_its_owner(
backend = DiffusionBackend()
entered, release, response_ready = (threading.Event() for _ in range(3))
threads, errors, responses = [], [], []
- (tmp_path / "model_index.json").write_text("{}", encoding = "utf-8")
+ _write_local_pipeline(tmp_path)
monkeypatch.setattr(gpu_arbiter, "_owner", None)
monkeypatch.setattr(gpu_arbiter, "_owner_account", None)
for name in ("_resident_accounts", "_prior_resident_accounts", "_resident_sharers"):
@@ -166,7 +175,7 @@ def test_pending_caller_cannot_block_load_owner_eject(
backend = DiffusionBackend()
entered, pending, release, response_ready = (threading.Event() for _ in range(4))
threads, errors, responses = [], [], {}
- (tmp_path / "model_index.json").write_text("{}", encoding = "utf-8")
+ _write_local_pipeline(tmp_path)
monkeypatch.setattr(gpu_arbiter, "_owner", None)
monkeypatch.setattr(gpu_arbiter, "_owner_account", None)
for name in ("_resident_accounts", "_prior_resident_accounts", "_resident_sharers"):
diff --git a/studio/backend/tests/test_cached_gguf_routes.py b/studio/backend/tests/test_cached_gguf_routes.py
index 76d3c426adf..f2a96e9ed6d 100644
--- a/studio/backend/tests/test_cached_gguf_routes.py
+++ b/studio/backend/tests/test_cached_gguf_routes.py
@@ -1948,8 +1948,14 @@ def test_list_cached_models_tags_diffusers_pipeline_as_text_to_image(monkeypatch
[_file("config.json", 1_000), _file("model.safetensors", 9_000)],
tmp_path / "models--unsloth--Llama-3.2-1B-Instruct",
)
+ snapshot = diffusion.repo_path / "snapshots" / "revision"
+ _saved_pipeline(snapshot, "ZImagePipeline")
+ (diffusion.repo_path / "refs").mkdir()
+ (diffusion.repo_path / "refs" / "main").write_text("revision")
+ diffusion.revisions[0].snapshot_path = snapshot
_scanned_repos(monkeypatch, diffusion, checkpoint)
+ monkeypatch.setattr(models_route, "_resolve_hf_cache_dir", lambda: tmp_path)
result = asyncio.run(models_route.list_cached_models(current_subject = "test-user"))
by_repo = {c["repo_id"]: c["task"] for c in result["cached"]}
@@ -1957,6 +1963,11 @@ def test_list_cached_models_tags_diffusers_pipeline_as_text_to_image(monkeypatch
"Tongyi-MAI/Z-Image-Turbo": "text-to-image",
"unsloth/Llama-3.2-1B-Instruct": None,
}
+ rows = {c["repo_id"]: c for c in result["cached"]}
+ assert rows["Tongyi-MAI/Z-Image-Turbo"]["artifact_kind"] == "diffusers_pipeline"
+ # A snapshot on refs/main loads by its Hub id, not a pinned path.
+ assert "load_id" not in rows["Tongyi-MAI/Z-Image-Turbo"]
+ assert rows["unsloth/Llama-3.2-1B-Instruct"].get("artifact_kind", "unknown") == "unknown"
def test_list_cached_models_marks_companion_only_pipeline_partial(monkeypatch, tmp_path):
@@ -4968,7 +4979,8 @@ def test_a_pure_text_gguf_folder_is_never_promoted_to_a_media_task(tmp_path, mon
def _saved_pipeline(root: Path, class_name: str) -> Path:
root.mkdir(parents = True, exist_ok = True)
- (root / "model_index.json").write_text(json.dumps({"_class_name": class_name}))
+ manifest = {"_class_name": class_name, "transformer": ["diffusers", "Transformer2DModel"]}
+ (root / "model_index.json").write_text(json.dumps(manifest))
for component in ("transformer", "vae", "text_encoder"):
(root / component).mkdir(parents = True, exist_ok = True)
(root / component / "config.json").write_text("{}")
@@ -6432,6 +6444,10 @@ def test_cached_model_rows_flag_a_selected_modular_pipeline_as_diffusers(monkeyp
assert row.get("task") is None
assert row["diffusers"] is True
+ assert row["artifact_kind"] == "diffusers_modular_pipeline"
+ assert row["load_id"] == str(snapshot)
+ response = models_route.CachedModelsResponse(cached = [row])
+ assert response.cached[0].artifact_kind == "diffusers_modular_pipeline"
def test_cached_model_rows_flag_a_diffusion_repo_this_backend_cannot_load(monkeypatch, tmp_path):
diff --git a/studio/backend/tests/test_diffusion_backend.py b/studio/backend/tests/test_diffusion_backend.py
index 9f3b88dc171..d9b8854e180 100644
--- a/studio/backend/tests/test_diffusion_backend.py
+++ b/studio/backend/tests/test_diffusion_backend.py
@@ -12,6 +12,7 @@ from __future__ import annotations
import contextlib
import dataclasses
+import json
import re
import sys
import threading
@@ -45,6 +46,7 @@ from core.inference.diffusion_families import (
family_prequant_repo,
load_identity,
mirror_repo,
+ pipeline_available_family_names,
prefer_ungated_mirror,
resolve_base_repo,
resolve_local_gguf_child,
@@ -170,6 +172,34 @@ def test_supported_family_names():
assert detect_family("some/unknown-repo", override = name) is not None
+def test_pipeline_available_names_filter_the_selector_without_importing(monkeypatch):
+ # Status polls call this; importing pipeline classes there raced the loader's own import.
+ import importlib.util
+
+ import core.inference.diffusion_families as families
+
+ blocked = {"krea-2", "flux.2-klein"}
+ monkeypatch.setattr(families, "family_selectable", lambda fam: fam.name not in blocked)
+ assert set(supported_family_names()) - set(pipeline_available_family_names()) == blocked
+
+ def _strict(*_a, **_k):
+ raise AssertionError("the selector must stay import-free")
+
+ monkeypatch.undo()
+ monkeypatch.setattr(families, "assert_pipeline_class_available", _strict)
+ real_find_spec = importlib.util.find_spec
+ monkeypatch.delitem(sys.modules, "diffusers", raising = False)
+ monkeypatch.setattr(
+ importlib.util,
+ "find_spec",
+ lambda name, *a, **k: object() if name == "diffusers" else real_find_spec(name, *a, **k),
+ )
+ assert "flux.1" in pipeline_available_family_names()
+
+ monkeypatch.setitem(sys.modules, "diffusers", None)
+ assert pipeline_available_family_names() == ()
+
+
def test_resolve_base_repo():
fam = detect_family("x", override = "z-image")
assert resolve_base_repo(fam, None) == fam.base_repo
@@ -914,6 +944,19 @@ def fake_runtime(monkeypatch):
_LOAD_DEFAULTS = dict(gguf_filename = "model.gguf", base_repo = "base/repo", family_override = "z-image")
+def _write_pipeline(
+ root,
+ class_name = "TestPipeline",
+ **components,
+):
+ weight = components.pop("weight", "diffusion_pytorch_model.safetensors")
+ (root / "transformer").mkdir(parents = True, exist_ok = True)
+ manifest = {"_class_name": class_name, "transformer": ["diffusers", "Transformer2DModel"]}
+ (root / "model_index.json").write_text(json.dumps({**manifest, **components}))
+ (root / "transformer" / "config.json").write_text("{}")
+ (root / "transformer" / weight).write_bytes(b"x")
+
+
def _load_into(backend, tmp_path, **overrides):
"""``load_pipeline`` on ``tmp_path`` over the z-image defaults; writes no checkpoint file."""
return backend.load_pipeline(str(tmp_path), **{**_LOAD_DEFAULTS, **overrides})
@@ -1038,7 +1081,9 @@ def test_load_generate_unload_gguf(fake_runtime, tmp_path):
(tmp_path / "model.gguf").write_bytes(b"weights")
backend = DiffusionBackend()
- status = _load_into(backend, tmp_path, hf_token = "hf_secret")
+ status = _load_into(
+ backend, tmp_path, hf_token = "hf_secret", display_repo_id = "Org/pinned-z-image"
+ )
assert status["loaded"] is True
assert status["family"] == "z-image"
assert status["base_repo"] == "base/repo"
@@ -1057,7 +1102,7 @@ def test_load_generate_unload_gguf(fake_runtime, tmp_path):
prompt = "a sloth", negative_prompt = "blurry", width = 512, height = 512, steps = 4, guidance = 3.0
)
assert gen["seed"] == 4242 # random seed reported back
- assert gen["repo_id"] == str(tmp_path) # echoed so the route can record the model
+ assert gen["repo_id"] == "Org/pinned-z-image" # stable picker identity for the recipe
assert len(gen["images"]) == 1 # PIL images handed to the route for persistence
# z-image guides via guidance_scale; the signature-gated negative_prompt and the step callback both land.
call = backend._state.pipe.last_kwargs
@@ -2165,8 +2210,19 @@ def test_validate_gates_untrusted_base_repo(fake_runtime, tmp_path):
model_kind = "gguf",
base_repo = str(bad_base),
)
- # A local base_repo that IS a real pipeline dir passes the gate.
- (tmp_path / "model_index.json").write_text("{}")
+ (tmp_path / "model_index.json").write_text("{")
+ with pytest.raises(ValueError, match = "valid model_index.json"):
+ backend.validate_load_request(
+ "unsloth/Qwen-Image-2512-GGUF",
+ gguf_filename = "x.gguf",
+ model_kind = "gguf",
+ base_repo = str(tmp_path),
+ )
+ # A base whose declared transformer is absent still serves companions for a GGUF load.
+ _write_pipeline(tmp_path, scheduler = ["diffusers", "FlowMatchEulerDiscreteScheduler"])
+ (tmp_path / "transformer" / "diffusion_pytorch_model.safetensors").unlink()
+ (tmp_path / "scheduler").mkdir()
+ (tmp_path / "scheduler" / "scheduler_config.json").write_text("{}")
fam = backend.validate_load_request(
"unsloth/Qwen-Image-2512-GGUF",
gguf_filename = "x.gguf",
@@ -2174,6 +2230,55 @@ def test_validate_gates_untrusted_base_repo(fake_runtime, tmp_path):
base_repo = str(tmp_path),
)
assert fam is not None
+ with pytest.raises(FileNotFoundError, match = "valid model_index.json"):
+ backend.validate_load_request(str(tmp_path), family_override = "qwen-image")
+
+
+def test_validate_accepts_config_only_local_base_for_whole_pipeline_single_file(
+ fake_runtime, tmp_path
+):
+ backend = DiffusionBackend()
+ (tmp_path / "model.safetensors").write_bytes(b"checkpoint")
+ base = tmp_path / "sdxl-config"
+ (base / "unet").mkdir(parents = True)
+ (base / "unet" / "config.json").write_text("{}")
+ manifest = {
+ "_class_name": "StableDiffusionXLPipeline",
+ "unet": ["diffusers", "UNet2DConditionModel"],
+ }
+ (base / "model_index.json").write_text(json.dumps(manifest))
+
+ fam = backend.validate_load_request(
+ str(tmp_path),
+ gguf_filename = "model.safetensors",
+ model_kind = "single_file",
+ base_repo = str(base),
+ family_override = "sdxl",
+ )
+ assert fam.single_file_is_pipeline is True
+ with pytest.raises(FileNotFoundError, match = "valid model_index.json"):
+ backend.validate_load_request(str(base), family_override = "sdxl")
+
+
+def test_validate_accepts_custom_local_components(fake_runtime, tmp_path):
+ manifest = {
+ "_class_name": "StableDiffusionXLPipeline",
+ "unet": ["local_extensions", "CustomModel"],
+ "scheduler": ["local_extensions", "CustomScheduler"],
+ }
+ (tmp_path / "model_index.json").write_text(json.dumps(manifest))
+ for name, asset in (
+ ("unet", "custom_weights.safetensors"),
+ ("scheduler", "custom_schedule.json"),
+ ):
+ (tmp_path / name).mkdir()
+ (tmp_path / name / asset).write_text("{}")
+
+ backend = DiffusionBackend()
+ assert backend.validate_load_request(str(tmp_path), family_override = "sdxl").name == "sdxl"
+ status = backend.load_pipeline(str(tmp_path), family_override = "sdxl", speed_mode = "off")
+ assert status["loaded"] is True
+ assert _FakePipeline.last["base"] == str(tmp_path)
def test_resolve_local_single_file(tmp_path):
@@ -2545,7 +2650,7 @@ def test_generate_qwen_uses_true_cfg_scale(fake_runtime, tmp_path):
def _load_ideogram(backend, tmp_path):
# Ideogram 4 loads only as a full pipeline (the loader is stubbed), so a local dir is enough.
- (tmp_path / "model_index.json").write_text("{}")
+ _write_pipeline(tmp_path, "Ideogram4Pipeline", weight = "pytorch_model.bin")
backend.load_pipeline(str(tmp_path), family_override = "ideogram-4")
@@ -2589,7 +2694,7 @@ def test_generate_ideogram_custom_guidance_nulls_schedule(fake_runtime, tmp_path
def _load_lumina(backend, tmp_path):
# Lumina 2 loads through the GENERIC pipeline path, so a local pipeline dir is enough here.
- (tmp_path / "model_index.json").write_text("{}")
+ _write_pipeline(tmp_path, "Lumina2Pipeline")
backend.load_pipeline(str(tmp_path), family_override = "lumina-2")
@@ -3075,7 +3180,7 @@ def test_krea_component_load_honors_eject(fake_runtime, tmp_path, monkeypatch, p
backend = DiffusionBackend()
calls, ejectors, reclaimed = [], [], []
live = weakref.WeakSet()
- (tmp_path / "model_index.json").write_text("{}", encoding = "utf-8")
+ _write_pipeline(tmp_path)
def record(name, value):
calls.append(name)
@@ -3173,7 +3278,7 @@ def test_eager_encoder_cancellation_stops_pipeline_build(
backend = DiffusionBackend()
calls, ejectors, reclaimed = [], [], []
live = weakref.WeakSet()
- (tmp_path / "model_index.json").write_text("{}", encoding = "utf-8")
+ _write_pipeline(tmp_path)
filename = "model.gguf" if kind == "gguf" else "model.safetensors"
(tmp_path / filename).write_bytes(b"weights")
sys.modules["diffusers"].HiDreamImagePipeline = _FakePipeline
@@ -3249,7 +3354,7 @@ def test_ideogram_component_load_honors_eject(fake_runtime, tmp_path, monkeypatc
backend = DiffusionBackend()
calls, ejectors, reclaimed = [], [], []
live = weakref.WeakSet()
- (tmp_path / "model_index.json").write_text("{}", encoding = "utf-8")
+ _write_pipeline(tmp_path, weight = "pytorch_model.bin")
def component(name):
calls.append(name)
@@ -10811,6 +10916,28 @@ def test_the_resident_size_table_never_shrinks_a_local_checkpoint(fake_runtime,
assert lowered.estimates["model_dense_mib"] < measured
[email protected]("configured", [True, False])
+def test_the_resident_size_table_trusts_only_a_configured_cache_snapshot(
+ fake_runtime, tmp_path, monkeypatch, configured
+):
+ # A configured-cache snapshot keeps its Hub provenance; a lookalike path elsewhere does not.
+ import torch
+
+ cache_root = tmp_path / "hub"
+ snapshot = cache_root / "models--Tongyi-MAI--Z-Image-Turbo" / "snapshots" / ("a" * 40)
+ snapshot.mkdir(parents = True)
+ known = [cache_root] if configured else [tmp_path / "other-hub"]
+ monkeypatch.setattr("utils.hf_cache_settings.known_hf_hub_caches", lambda: known)
+ sized = DiffusionBackend()._resident_sized_plan(
+ _plan_with_weights(40_000),
+ detect_family("Tongyi-MAI/Z-Image-Turbo"),
+ str(snapshot),
+ _mps_target(torch),
+ "pipeline",
+ )
+ assert (sized.estimates["model_dense_mib"] < 40_000) is configured
+
+
def test_speed_off_is_not_reported_as_a_staging_failure(fake_runtime, tmp_path, monkeypatch):
"""An explicit Speed=off rewrites an auto request to "off" and the plan stages no
transformer/ on purpose. Reading that expected absence as a decline told the caller their
diff --git a/studio/backend/tests/test_diffusion_base_precision.py b/studio/backend/tests/test_diffusion_base_precision.py
index 5be5f76421e..d544ac470bb 100644
--- a/studio/backend/tests/test_diffusion_base_precision.py
+++ b/studio/backend/tests/test_diffusion_base_precision.py
@@ -742,7 +742,13 @@ def test_assert_trusted_base_model_rejects_local_non_pipeline(tmp_path):
with pytest.raises(ValueError, match = "model_index.json"):
common._assert_trusted_base_model(str(bad))
# A real local pipeline dir (model_index.json) is accepted.
- (bad / "model_index.json").write_text("{}")
+ manifest = (
+ '{"_class_name":"DiffusionPipeline","transformer":["diffusers","Transformer2DModel"]}'
+ )
+ (bad / "model_index.json").write_text(manifest)
+ (bad / "transformer").mkdir()
+ (bad / "transformer" / "config.json").write_text("{}")
+ (bad / "transformer" / "diffusion_pytorch_model.safetensors").write_bytes(b"x")
common._assert_trusted_base_model(str(bad)) # no raise
# An untrusted remote base is still rejected by the trust gate.
with pytest.raises(ValueError, match = "untrusted"):
diff --git a/studio/backend/tests/test_diffusion_engine_router.py b/studio/backend/tests/test_diffusion_engine_router.py
index 4fe743bfbf3..67e6c6fdba6 100644
--- a/studio/backend/tests/test_diffusion_engine_router.py
+++ b/studio/backend/tests/test_diffusion_engine_router.py
@@ -23,6 +23,7 @@ _ENVS = (
@pytest.fixture(autouse = True)
def _clean_env_and_state(monkeypatch):
+ r._supported_family_capabilities.cache_clear()
for e in _ENVS:
monkeypatch.delenv(e, raising = False)
# A light status-capable stub so selection / active_status() never import the heavy diffusers or sd.cpp
@@ -46,6 +47,7 @@ def _clean_env_and_state(monkeypatch):
finally:
r._active_engine_name = saved_engine
r._fallback_reason = saved_reason
+ r._supported_family_capabilities.cache_clear()
def _set_device(monkeypatch, backend):
@@ -202,6 +204,19 @@ def test_active_status_injects_engine_and_reason(monkeypatch):
assert st["fallback_reason"] and "binary unavailable" in st["fallback_reason"]
+def test_status_family_capabilities_are_probed_once(monkeypatch):
+ calls = []
+ monkeypatch.setattr(
+ r,
+ "pipeline_available_family_names",
+ lambda: calls.append("probe") or ("z-image", "flux.1"),
+ )
+
+ assert r.active_status()["supported_families"] == ["z-image", "flux.1"]
+ assert r.active_status()["supported_families"] == ["z-image", "flux.1"]
+ assert calls == ["probe"]
+
+
# ── engine-switch eviction ordering ───────────────────────────────────────────
diff --git a/studio/backend/tests/test_diffusion_h3_trainer.py b/studio/backend/tests/test_diffusion_h3_trainer.py
index 56c0a6ab167..db6382990ef 100644
--- a/studio/backend/tests/test_diffusion_h3_trainer.py
+++ b/studio/backend/tests/test_diffusion_h3_trainer.py
@@ -1389,7 +1389,16 @@ def test_a_local_modular_h3_pipeline_is_an_acceptable_training_base(tmp_path):
modular = tmp_path / "MiniMax-H3"
modular.mkdir()
- (modular / "modular_model_index.json").write_text("{}")
+ transformer = ["diffusers", "MiniMaxH3Transformer3DModel"]
+ manifest = {
+ "_class_name": "ModularPipeline",
+ "_blocks_class_name": "Blocks",
+ "transformer": transformer,
+ }
+ (modular / "modular_model_index.json").write_text(json.dumps(manifest))
+ (modular / "transformer").mkdir()
+ (modular / "transformer" / "config.json").write_text("{}")
+ (modular / "transformer" / "diffusion_pytorch_model.safetensors").write_bytes(b"x")
_assert_trusted_base_model(str(modular), allow_modular = True)
# Off by default: a conventional DiffusionPipeline load still needs the conventional index.
diff --git a/studio/backend/tests/test_local_model_format.py b/studio/backend/tests/test_local_model_format.py
index 7bdf9b5fd2b..152192071ce 100644
--- a/studio/backend/tests/test_local_model_format.py
+++ b/studio/backend/tests/test_local_model_format.py
@@ -44,6 +44,46 @@ def _touch(path: Path) -> Path:
return path
+_TRANSFORMER = {"transformer": ["diffusers", "Transformer2DModel"]}
+
+
+def _write(path: Path, text: str = "{}") -> None:
+ path.parent.mkdir(parents = True, exist_ok = True)
+ path.write_text(text)
+
+
+def _index(
+ root: Path,
+ name: str = "model_index.json",
+ **payload,
+) -> Path:
+ payload.setdefault("_class_name", "DiffusionPipeline")
+ _write(root / name, json.dumps(payload))
+ return root / name
+
+
+def _pipeline_manifest(
+ root: Path,
+ name: str = "model_index.json",
+ **payload,
+) -> Path:
+ if name.startswith("modular_"):
+ payload.setdefault("_blocks_class_name", "TestPipelineBlocks")
+ path = _index(root, name, **{**_TRANSFORMER, **payload})
+ _write(root / "transformer" / "config.json")
+ _touch(root / "transformer" / "diffusion_pytorch_model.safetensors")
+ return path
+
+
+def _weight_map(path: Path, shard: str) -> None:
+ _write(path, json.dumps({"weight_map": {"layer": shard}}))
+
+
+def _complete(root: Path, *name: str, **kwargs) -> bool:
+ from core.inference.diffusion_families import local_pipeline_components_are_complete
+ return local_pipeline_components_are_complete(root, *(name or ("model_index.json",)), **kwargs)
+
+
def _empty_compat_sources(tmp_path: Path):
empty = tmp_path / "empty"
return models_route._CompatLocalInventorySources(
@@ -505,9 +545,7 @@ def test_scan_models_dir_surfaces_diffusers_pipeline_folder(tmp_path):
# must surface it or it never reaches the On Device picker. Not a GGUF, so model_format stays None.
root = tmp_path / "models"
pipe = root / "my-pipeline"
- _touch(pipe / "model_index.json")
- _touch(pipe / "transformer" / "config.json")
- _touch(pipe / "transformer" / "diffusion_pytorch_model.safetensors")
+ _pipeline_manifest(pipe)
_touch(pipe / "vae" / "diffusion_pytorch_model.safetensors")
rows = {Path(m.path).name: m for m in models_route._scan_models_dir(root)}
@@ -519,9 +557,7 @@ def test_scan_models_dir_surfaces_diffusers_pipeline_folder(tmp_path):
def test_scan_models_dir_surfaces_root_diffusers_pipeline(tmp_path):
# A scan folder can point DIRECTLY at a diffusers pipeline, which _is_model_directory rejects; without admitting it the scan surfaces component subdirs and hides the pipeline.
root = tmp_path / "my-local-pipeline"
- _touch(root / "model_index.json")
- _touch(root / "transformer" / "config.json")
- _touch(root / "transformer" / "diffusion_pytorch_model.safetensors")
+ _pipeline_manifest(root)
_touch(root / "vae" / "diffusion_pytorch_model.safetensors")
rows = models_route._scan_models_dir(root)
@@ -530,6 +566,236 @@ def test_scan_models_dir_surfaces_root_diffusers_pipeline(tmp_path):
assert rows[0].model_format is None
+def _bom(pipeline):
+ manifest = pipeline / "model_index.json"
+ manifest.write_bytes(b"\xef\xbb\xbf" + manifest.read_bytes())
+
+
+def _write_manifest(text):
+ return lambda p: (p / "model_index.json").write_text(text)
+
+
+ "manifests, mutate, expected",
+ [
+ (("model_index.json",), None, "diffusers_pipeline"),
+ (("model_index.json",), _bom, "diffusers_pipeline"),
+ (("modular_model_index.json",), None, "diffusers_modular_pipeline"),
+ (("model_index.json", "modular_model_index.json"), None, "diffusers_dual_pipeline"),
+ (
+ ("model_index.json",),
+ lambda p: (p / "transformer" / "diffusion_pytorch_model.safetensors").unlink(),
+ "unknown",
+ ),
+ ]
+ + [
+ (("model_index.json",), _write_manifest(text), "unknown")
+ for text in ["", "{", "[]", "{}", '{"_class_name":" "}', '{"_class_name":"P"}']
+ ],
+)
+def test_hub_inventory_types_pipeline_roots_structurally(tmp_path, manifests, mutate, expected):
+ from hub.services.models.common import _classify_local_path
+
+ pipeline = tmp_path / "opaque-model"
+ for name in manifests:
+ _pipeline_manifest(pipeline, name)
+ if mutate:
+ mutate(pipeline)
+ [row] = _classify_local_path(pipeline, "custom")
+ assert (row.model_format, row.artifact_kind) == ("unknown", expected)
+
+
+def test_hub_inventory_does_not_confuse_transformers_or_adapter_with_pipeline(tmp_path):
+ from hub.services.models.common import _classify_local_path
+ from hub.services.models.local_inventory import _scan_models_dir as scan_hub_models_dir
+
+ transformer, adapter, loose = tmp_path / "transformer", tmp_path / "adapter", tmp_path / "loose"
+ _pipeline_manifest(transformer)
+ _touch(transformer / "model.safetensors")
+ (transformer / "config.json").write_text('{"architectures":["Qwen3ForCausalLM"]}')
+ _pipeline_manifest(adapter)
+ _touch(adapter / "adapter_model.safetensors")
+ (adapter / "adapter_config.json").write_text("{}")
+ _touch(loose / "qwen_3_4b.safetensors")
+ _touch(loose / "diffusion_pytorch_model-00001-of-00002.bf16.safetensors")
+
+ assert _classify_local_path(transformer, "custom")[0].artifact_kind == "transformers_model"
+ assert _classify_local_path(adapter, "custom")[0].artifact_kind == "adapter"
+ assert scan_hub_models_dir(loose) == []
+
+
+def test_local_pipeline_completeness_checks_configs_and_every_indexed_shard(tmp_path):
+ _pipeline_manifest(tmp_path)
+ component = tmp_path / "transformer"
+ (component / "diffusion_pytorch_model.safetensors").unlink()
+ (component / "config.json").write_text("{")
+ index = component / "diffusion_pytorch_model.safetensors.index.json"
+ _weight_map(index, "weights-00001-of-00001.safetensors")
+ assert _complete(tmp_path) is False
+ (component / "config.json").write_text("{}")
+ assert _complete(tmp_path) is False
+ _touch(component / "weights-00001-of-00001.safetensors")
+ assert _complete(tmp_path) is True
+ _weight_map(index, "..\\outside.safetensors")
+ assert _complete(tmp_path) is False
+ index.unlink()
+ (component / "weights-00001-of-00001.safetensors").unlink()
+ _touch(component / "diffusion_pytorch_model.safetensors")
+ _weight_map(component / "diffusion_pytorch_model.bin.index.json", "model-00001-of-00001.bin")
+ assert _complete(tmp_path) is True
+ (component / "diffusion_pytorch_model.safetensors").unlink()
+ assert _complete(tmp_path) is False
+
+
+def test_local_pipeline_completeness_rejects_variant_only_weights(tmp_path):
+ # The pipeline loads at variant=None, where diffusers / transformers raise on fp16-only folders.
+ _pipeline_manifest(tmp_path)
+ component = tmp_path / "transformer"
+ (component / "diffusion_pytorch_model.safetensors").unlink()
+ shard = "diffusion_pytorch_model.fp16-00001-of-00001.safetensors"
+ _touch(component / shard)
+ _weight_map(component / "diffusion_pytorch_model.safetensors.index.fp16.json", shard)
+ assert _complete(tmp_path) is False
+ _touch(component / "diffusion_pytorch_model.safetensors")
+ assert _complete(tmp_path) is True
+
+
+def test_local_pipeline_completeness_accepts_a_tokenizer_config_over_the_manifest_cap(tmp_path):
+ # LTX-2's Gemma3 tokenizer_config.json is 1,155,387 bytes.
+ _pipeline_manifest(tmp_path, tokenizer = ["transformers", "GemmaTokenizerFast"])
+ _write(
+ tmp_path / "tokenizer" / "tokenizer_config.json",
+ json.dumps({"added_tokens_decoder": "x" * (2 << 20)}),
+ )
+ _touch(tmp_path / "tokenizer" / "tokenizer.json")
+ assert _complete(tmp_path) is True
+
+
+def test_local_pipeline_completeness_ignores_a_diffusers_index_on_a_transformers_encoder(tmp_path):
+ # LTX-2's text_encoder ships both shard sets; transformers reads only model*.
+ _pipeline_manifest(tmp_path, text_encoder = ["transformers", "Gemma3ForConditionalGeneration"])
+ encoder = tmp_path / "text_encoder"
+ _write(encoder / "config.json")
+ _touch(encoder / "model-00001-of-00001.safetensors")
+ for prefix in ("model", "diffusion_pytorch_model"):
+ _weight_map(
+ encoder / f"{prefix}.safetensors.index.json", f"{prefix}-00001-of-00001.safetensors"
+ )
+ assert _complete(tmp_path) is True
+ (encoder / "model-00001-of-00001.safetensors").unlink()
+ assert _complete(tmp_path) is False
+ # Transformers opens a single checkpoint before the (now stale) index.
+ _touch(encoder / "model.safetensors")
+ assert _complete(tmp_path) is True
+
+
+ "extra, expected",
+ [
+ ({}, True),
+ ({"text_encoder": [None, None]}, True),
+ ({"text_encoder_select_layers": [2, 5, 8, 11]}, True),
+ ({"text_encoder": ["transformers", "CLIPTextModel"]}, False),
+ ],
+)
+def test_local_pipeline_optional_component_presence(tmp_path, extra, expected):
+ _pipeline_manifest(tmp_path, **extra)
+ assert _complete(tmp_path) is expected
+
+
+def test_local_pipeline_completeness_allows_hidream_caller_supplied_encoder(tmp_path):
+ encoders = {
+ "text_encoder_4": ["transformers", "LlamaForCausalLM"],
+ "tokenizer_4": ["transformers", "PreTrainedTokenizerFast"],
+ }
+ _pipeline_manifest(tmp_path, _class_name = "HiDreamImagePipeline", **encoders)
+ assert _complete(tmp_path) is True
+ (tmp_path / "text_encoder_4").mkdir()
+ assert _complete(tmp_path) is False
+ (tmp_path / "text_encoder_4").rmdir()
+ _pipeline_manifest(tmp_path, **encoders)
+ assert _complete(tmp_path) is False
+
+
+def test_local_pipeline_completeness_honors_exclusions_and_config_only_models(tmp_path):
+ _index(tmp_path, scheduler = ["diffusers", "FlowMatchEulerDiscreteScheduler"], **_TRANSFORMER)
+ _write(tmp_path / "scheduler" / "scheduler_config.json")
+ assert _complete(tmp_path) is False
+ assert _complete(tmp_path, excluded_components = ("transformer",)) is True
+ _index(tmp_path, **_TRANSFORMER)
+ assert _complete(tmp_path, excluded_components = ("transformer",)) is False
+
+ _index(tmp_path, unet = ["diffusers", "UNet2DConditionModel"])
+ _write(tmp_path / "unet" / "config.json")
+ assert _complete(tmp_path) is False
+ assert _complete(tmp_path, config_only_model_components = True) is True
+
+
+ "name, class_name, files, expected",
+ [
+ ("scheduler", "FlowMatchEulerDiscreteScheduler", "README.md", False),
+ ("scheduler", "FlowMatchEulerDiscreteScheduler", "scheduler_config.json", True),
+ ("tokenizer", "Qwen2Tokenizer", "tokenizer_config.json", False),
+ ("tokenizer", "Qwen2Tokenizer", "tokenizer_config.json tokenizer.json", True),
+ ("tokenizer_2", "ByT5Tokenizer", "tokenizer_config.json", True),
+ ("guider", "ClassifierFreeGuidance", "guider_config.json", True),
+ ("processor", "Qwen3VLProcessor", "preprocessor_config.json", False),
+ ("processor", "Qwen3VLProcessor", "preprocessor_config.json tokenizer.json", True),
+ ],
+)
+def test_local_pipeline_completeness_validates_metadata_component_contracts(
+ tmp_path, name, class_name, files, expected
+):
+ library = "diffusers" if name in ("scheduler", "guider") else "transformers"
+ _index(tmp_path, **{name: [library, class_name]})
+ for file in files.split():
+ _write(tmp_path / name / file)
+ assert _complete(tmp_path) is expected
+
+
[email protected]("filename", ["model_index.json", "modular_model_index.json"])
+ "class_name, asset",
+ [("CustomModel", "custom_weights.safetensors"), ("CustomScheduler", "custom_schedule.json")],
+)
+def test_local_pipeline_preserves_custom_component_contracts(tmp_path, filename, class_name, asset):
+ from hub.services.models.common import _diffusers_pipeline_artifact_kind
+
+ spec = {"component": ["local_extensions", class_name], "optional_component": [None, None]}
+ _index(tmp_path, filename, **spec)
+ component = tmp_path / "component"
+ assert not _complete(tmp_path, filename)
+ component.mkdir()
+ assert not _complete(tmp_path, filename)
+ (component / asset).write_bytes(b"")
+ assert not _complete(tmp_path, filename)
+ (component / asset).write_text("{}")
+ assert _complete(tmp_path, filename)
+ assert _diffusers_pipeline_artifact_kind(tmp_path) == (
+ "diffusers_pipeline" if filename == "model_index.json" else "diffusers_modular_pipeline"
+ )
+
+
+def test_local_pipeline_completeness_honors_modular_external_component_sources(tmp_path):
+ pipeline, modular = tmp_path / "external-modular", "modular_model_index.json"
+
+ def manifest(source, component = ("transformers", "Qwen2Tokenizer", "tokenizer")):
+ spec = {"pretrained_model_name_or_path": source, "subfolder": component[2]}
+ _index(pipeline, modular, tokenizer = [*component[:2], spec])
+ return _complete(pipeline, modular)
+
+ assert manifest("Org/components") is True
+ assert manifest("./missing") is False
+ source = tmp_path / "component-source"
+ _write(source / "tokenizer" / "tokenizer_config.json")
+ _write(source / "tokenizer" / "tokenizer.json")
+ assert manifest(str(source)) is True
+ assert manifest(str(source), ("transformers", "Qwen2Tokenizer", "../outside")) is False
+ (source / "custom_weights.safetensors").write_bytes(b"weights")
+ assert manifest(str(source), ("local_extensions", "CustomModel", None)) is True
+
+
def test_scan_models_dir_surfaces_root_single_file_checkpoint(tmp_path):
# A scan folder can also point DIRECTLY at a bare single-file checkpoint dir (one loose .safetensors). The child loop
# admits that shape and the images route reinterprets it via resolve_local_single_file, so the root must be surfaced too.
@@ -777,7 +1043,7 @@ def test_an_ancestor_directory_does_not_name_an_unhydrated_gguf(tmp_path, monkey
def test_local_task_tags_family_named_pipeline_dir(tmp_path):
# A local diffusers pipeline whose id resolves to a supported image family loads fine, so tag it and the Images picker keeps it.
d = tmp_path / "flux-pipeline"
- _touch(d / "model_index.json")
+ _pipeline_manifest(d)
_touch(d / "unet" / "diffusion_pytorch_model.safetensors")
assert (
models_route._local_model_task(_local(d, model_id = "black-forest-labs/FLUX.1-dev"))
@@ -788,7 +1054,7 @@ def test_local_task_tags_family_named_pipeline_dir(tmp_path):
def test_local_task_none_for_familyless_pipeline_dir(tmp_path):
# A generically named on-device pipeline (model_index.json, no family token) is UNLOADABLE: the Images load resolves no family and 400s after eviction, so it stays untagged.
d = tmp_path / "my-local-pipeline"
- _touch(d / "model_index.json")
+ _pipeline_manifest(d)
_touch(d / "unet" / "diffusion_pytorch_model.safetensors")
assert models_route._local_is_diffusers(_local(d)) is True
assert models_route._local_model_task(_local(d)) is None
@@ -815,14 +1081,11 @@ def test_local_task_none_for_plain_llm(tmp_path):
def test_local_task_tags_minimax_music3_modular_pipeline(tmp_path):
d = tmp_path / "music3"
d.mkdir()
- (d / "modular_model_index.json").write_text(
- json.dumps(
- {
- "_class_name": "MiniMaxMusic3ModularPipeline",
- "_blocks_class_name": "MiniMaxMusic3Blocks",
- }
- ),
- encoding = "utf-8",
+ _pipeline_manifest(
+ d,
+ "modular_model_index.json",
+ _class_name = "MiniMaxMusic3ModularPipeline",
+ _blocks_class_name = "MiniMaxMusic3Blocks",
)
assert models_route._local_model_task(_local(d, model_format = "safetensors")) == (
@@ -834,14 +1097,11 @@ def test_compat_local_inventory_preserves_minimax_music3_audio_type(monkeypatch,
models_dir = tmp_path / "models"
d = models_dir / "music3"
d.mkdir(parents = True)
- (d / "modular_model_index.json").write_text(
- json.dumps(
- {
- "_class_name": "MiniMaxMusic3ModularPipeline",
- "_blocks_class_name": "MiniMaxMusic3Blocks",
- }
- ),
- encoding = "utf-8",
+ _pipeline_manifest(
+ d,
+ "modular_model_index.json",
+ _class_name = "MiniMaxMusic3ModularPipeline",
+ _blocks_class_name = "MiniMaxMusic3Blocks",
)
sources = models_route._CompatLocalInventorySources(
hf_cache_dir = models_dir,
@@ -929,7 +1189,7 @@ def test_a_modular_pipeline_root_counts_as_a_pipeline_index(tmp_path):
modular = tmp_path / "modular"
(modular / "transformer").mkdir(parents = True)
- (modular / "modular_model_index.json").write_text("{}")
+ _pipeline_manifest(modular, "modular_model_index.json")
assert _local_pipeline_index(modular) is True
assert (
models_route._local_is_diffusers(_local(modular, display_name = "opaque", id = str(modular)))
@@ -938,7 +1198,7 @@ def test_a_modular_pipeline_root_counts_as_a_pipeline_index(tmp_path):
conventional = tmp_path / "conventional"
conventional.mkdir()
- (conventional / "model_index.json").write_text("{}")
+ _pipeline_manifest(conventional)
assert _local_pipeline_index(conventional) is True
neither = tmp_path / "neither"
diff --git a/studio/backend/tests/test_media_display_identity.py b/studio/backend/tests/test_media_display_identity.py
new file mode 100644
index 00000000000..25119a295f7
--- /dev/null
+++ b/studio/backend/tests/test_media_display_identity.py
@@ -0,0 +1,19 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+from models.inference import (
+ DiffusionLoadRequest,
+ DiffusionStatusResponse,
+ VideoLoadRequest,
+ VideoStatusResponse,
+)
+
+
+def test_media_requests_and_statuses_keep_load_and_display_identities_separate():
+ snapshot, logical = "/cache/models--Org--Opaque/snapshots/abc", "Org/Opaque"
+ for request_type in (DiffusionLoadRequest, VideoLoadRequest):
+ request = request_type(model_path = snapshot, display_repo_id = logical)
+ assert (request.model_path, request.display_repo_id) == (snapshot, logical)
+ for status_type in (DiffusionStatusResponse, VideoStatusResponse):
+ status = status_type(loaded = True, repo_id = snapshot, display_repo_id = logical)
+ assert (status.repo_id, status.display_repo_id) == (snapshot, logical)
diff --git a/studio/backend/tests/test_openai_auto_switch.py b/studio/backend/tests/test_openai_auto_switch.py
index 8dcec43edba..116de71a9ac 100644
--- a/studio/backend/tests/test_openai_auto_switch.py
+++ b/studio/backend/tests/test_openai_auto_switch.py
@@ -10097,7 +10097,16 @@ def test_a_diffusers_pipeline_is_not_a_servable_chat_model(tmp_path):
# The Images and Video backends own these; /v1/chat/completions cannot serve them.
pipeline = _local_checkpoint(tmp_path, "SomeDiffusionPipeline")
- (pipeline / "model_index.json").write_text("{}")
+ manifest = {
+ "_class_name": "DiffusionPipeline",
+ "transformer": ["diffusers", "Transformer2DModel"],
+ }
+ (pipeline / "model_index.json").write_text(json.dumps(manifest))
+ (pipeline / "transformer").mkdir()
+ (pipeline / "transformer" / "config.json").write_text("{}")
+ (pipeline / "transformer" / "diffusion_pytorch_model.safetensors").write_bytes(
+ _safetensors_bytes()
+ )
info = SimpleNamespace(id = str(pipeline), path = str(pipeline))
assert resolver.local_servable_model(info) is None
diff --git a/studio/backend/tests/test_sd_cpp_backend.py b/studio/backend/tests/test_sd_cpp_backend.py
index 439edf60696..d6e1b0d1615 100644
--- a/studio/backend/tests/test_sd_cpp_backend.py
+++ b/studio/backend/tests/test_sd_cpp_backend.py
@@ -143,6 +143,22 @@ def test_loaded_repo_ids_includes_native_companions():
assert b.loaded_repo_ids() == ()
+def test_native_status_preserves_the_logical_picker_identity():
+ import dataclasses
+
+ b = _loaded_backend()
+ b._state = dataclasses.replace(
+ b._state,
+ repo_id = "/cache/models--unsloth--Z-Image-Turbo-GGUF/snapshots/abc",
+ display_repo_id = "unsloth/Z-Image-Turbo-GGUF",
+ )
+ status = b.status()
+ assert status["repo_id"].endswith("/snapshots/abc")
+ assert status["display_repo_id"] == "unsloth/Z-Image-Turbo-GGUF"
+ result = b.generate(prompt = "logical identity", steps = 1, seed = 1)
+ assert result["repo_id"] == "unsloth/Z-Image-Turbo-GGUF"
+
+
def test_loaded_repo_ids_tracks_variant_encoder_by_gguf_filename():
# A local *klein-9B*.gguf carries the variant keyword only in the basename, so loaded_repo_ids() must include the filename or the guard protects the wrong repo.
b = SdCppDiffusionBackend(engine = _FakeEngine())
@@ -1423,6 +1439,7 @@ def _run_server_load(
fam_name = "z-image",
device = "cpu",
gguf_filename = "z.gguf",
+ family_override = None,
):
fam = detect_family(fam_name)
monkeypatch.setattr(bk, "find_sd_server_binary", lambda: "/x/sd-server")
@@ -1451,6 +1468,7 @@ def _run_server_load(
gguf_filename = gguf_filename,
base = fam.base_repo,
fam = fam,
+ family_override = family_override,
hf_token = None,
_load_token = 1,
)
@@ -1466,6 +1484,18 @@ def test_server_load_spawns_once_and_status_reports_mode(monkeypatch):
assert b.status()["native_mode"] == "server"
+def test_server_status_preserves_explicit_family_provenance(monkeypatch):
+ b = SdCppDiffusionBackend()
+ servers: list = []
+ _run_server_load(monkeypatch, b, servers, family_override = "z-image")
+
+ family = b.status()["resolved"]["family_override"]
+ assert (family["value"], family["requested"], family["source"]) == ("z-image",) * 2 + (
+ "explicit",
+ )
+ assert (family["status"], family["reason"]) == ("applied", "requested")
+
+
def test_server_status_reports_selected_gguf_quant(monkeypatch):
b = SdCppDiffusionBackend()
servers: list = []
diff --git a/studio/backend/tests/test_video_backend.py b/studio/backend/tests/test_video_backend.py
index 8d25d7380c1..75319e82518 100644
--- a/studio/backend/tests/test_video_backend.py
+++ b/studio/backend/tests/test_video_backend.py
@@ -8,6 +8,7 @@ stack loads."""
import builtins
import contextlib
+import json
import dataclasses
import functools
import inspect
@@ -20,6 +21,7 @@ from pathlib import Path
import pytest
+import core.inference.video as video_module
from core.inference.diffusion_device import DiffusionDeviceTarget
from core.inference.video import (
VideoBackend,
@@ -143,9 +145,13 @@ def _assume_the_restricted_load_is_available(monkeypatch):
tests are about the load/plan decisions; the capability is covered in
test_diffusion_prequant.py."""
import core.inference.diffusion_prequant as _pq
+
monkeypatch.setattr(
_pq, "restricted_prequant_load_supported", lambda scheme = None, filename = None: True
)
+ video_module._video_family_capabilities.cache_clear()
+ yield
+ video_module._video_family_capabilities.cache_clear()
class _FakeDtype:
@@ -859,6 +865,15 @@ def test_validate_rejects_windows_shaped_missing_checkpoint(tmp_path):
assert fam.name == "ltx-2"
+def _write_pipeline(root, class_name, cls, **extra):
+ index = extra.pop("index", "model_index.json")
+ (root / "transformer").mkdir(parents = True, exist_ok = True)
+ manifest = {"_class_name": class_name, "transformer": ["diffusers", cls], **extra}
+ (root / index).write_text(json.dumps(manifest))
+ (root / "transformer" / "config.json").write_text("{}")
+ (root / "transformer" / "diffusion_pytorch_model.safetensors").write_bytes(b"x")
+
+
def test_validate_rejects_local_pipeline_without_model_index(tmp_path):
backend = VideoBackend()
d = tmp_path / "ltx-local"
@@ -867,12 +882,49 @@ def test_validate_rejects_local_pipeline_without_model_index(tmp_path):
# A local dir missing model_index.json is not a loadable pipeline; it must fail preflight BEFORE eviction.
with pytest.raises(ValueError, match = "model_index.json"):
backend.validate_load_request(str(d), family_override = "ltx-2")
- # With a model_index.json it is a valid local pipeline pick and passes preflight.
(d / "model_index.json").write_text("{}")
+ with pytest.raises(ValueError, match = "valid model_index.json"):
+ backend.validate_load_request(str(d), family_override = "ltx-2")
+ _write_pipeline(d, "LTX2Pipeline", "LTX2VideoTransformer3DModel")
fam = backend.validate_load_request(str(d), family_override = "ltx-2")
assert fam.name == "ltx-2"
+def test_validate_modular_family_requires_modular_manifest(tmp_path, fake_runtime, monkeypatch):
+ backend = VideoBackend()
+ root = tmp_path / "opaque-h3"
+ _write_pipeline(root, "LTX2Pipeline", "LTX2Transformer")
+ original_import = builtins.__import__
+
+ def _no_diffusers_import(name, *args, **kwargs):
+ if name == "diffusers" or name.startswith("diffusers."):
+ raise ModuleNotFoundError(f"No module named '{name}'", name = name)
+ return original_import(name, *args, **kwargs)
+
+ # The manifest is checked before diffusers is imported.
+ with monkeypatch.context() as no_diffusers:
+ no_diffusers.delitem(sys.modules, "diffusers")
+ no_diffusers.setattr(builtins, "__import__", _no_diffusers_import)
+ with pytest.raises(ValueError, match = "modular_model_index.json"):
+ backend.validate_load_request(str(root), family_override = "minimax-h3")
+
+ diffusers = sys.modules["diffusers"]
+ diffusers.ModularPipeline = _FakeModularPipeline
+ diffusers.MiniMaxH3Transformer3DModel = _FakeTransformer
+ (root / "modular_model_index.json").write_text("{}")
+ with pytest.raises(ValueError, match = "valid modular_model_index.json"):
+ backend.validate_load_request(str(root), family_override = "minimax-h3")
+ _write_pipeline(
+ root,
+ "ModularPipeline",
+ "MiniMaxH3Transformer3DModel",
+ index = "modular_model_index.json",
+ _blocks_class_name = "HunyuanVideo15PipelineBlocks",
+ )
+ fam = backend.validate_load_request(str(root), family_override = "minimax-h3")
+ assert fam.name == "minimax-h3"
+
+
def test_validate_rejects_local_file_picked_as_pipeline(tmp_path):
backend = VideoBackend()
# A local FILE sent as a pipeline is not a diffusers directory, so gate on .exists() (not .is_dir()) to catch files too.
@@ -894,8 +946,15 @@ def test_validate_rejects_local_base_repo_without_model_index(tmp_path):
model_kind = "gguf",
base_repo = str(bad_base),
)
- # A local base_repo that IS a real pipeline dir passes the gate.
- (bad_base / "model_index.json").write_text("{}")
+ _write_pipeline(
+ bad_base,
+ "LTX2Pipeline",
+ "LTX2VideoTransformer3DModel",
+ scheduler = ["diffusers", "FlowMatchEulerDiscreteScheduler"],
+ )
+ (bad_base / "transformer" / "diffusion_pytorch_model.safetensors").unlink()
+ (bad_base / "scheduler").mkdir()
+ (bad_base / "scheduler" / "scheduler_config.json").write_text("{}")
fam = backend.validate_load_request(
"unsloth/LTX-2.3-GGUF",
gguf_filename = "x.gguf",
@@ -904,6 +963,9 @@ def test_validate_rejects_local_base_repo_without_model_index(tmp_path):
)
assert fam.name == "ltx-2"
+ with pytest.raises(ValueError, match = "valid model_index.json"):
+ backend.validate_load_request(str(bad_base), model_kind = "pipeline", family_override = "ltx-2")
+
def test_validate_rejects_gguf_repo_as_pipeline():
backend = VideoBackend()
@@ -929,6 +991,14 @@ def test_detect_load_family_filename_fallback():
assert _detect_load_family("someorg/quants", "ltx-2-19b-Q4_K_M.gguf", "bogus") is None
+def test_detect_load_family_uses_logical_id_for_an_opaque_pinned_snapshot():
+ fam = _detect_load_family("/cache/snapshots/deadbeef", None, None, "MiniMaxAI/MiniMax-H3")
+ assert fam is not None and fam.name == "minimax-h3"
+ # The logical id outranks a family token in the physical path.
+ fam = _detect_load_family("/cache/wan2.2/snapshots/deadbeef", None, None, "Lightricks/LTX-2")
+ assert fam is not None and fam.name == "ltx-2"
+
+
def test_detect_load_family_cached_hub_arch_fallback(monkeypatch):
# A cached HUB GGUF is admitted to the picker by its architecture, but an opaque repo id + renamed file carry no family token, so the cache fallback keeps a supported pick loadable.
import huggingface_hub
@@ -1652,6 +1722,7 @@ def test_hv15_guider_and_scheduler_progress(fake_runtime):
backend = VideoBackend()
status = backend.load_pipeline(
"hunyuanvideo-community/HunyuanVideo-1.5-Diffusers-480p_t2v",
+ display_repo_id = "Org/pinned-hv15",
model_kind = "pipeline",
)
assert status["family"] == "hunyuanvideo-1.5"
@@ -1669,6 +1740,23 @@ def test_hv15_guider_and_scheduler_progress(fake_runtime):
assert pipe.scheduler.calls == 4
assert pipe.scheduler.step.__func__ is _FakeHV15Scheduler.step
assert result["num_frames"] == 9 and result["has_audio"] is False
+ assert result["repo_id"] == "Org/pinned-hv15"
+
+
+def test_pipeline_load_uses_logical_identity_for_a_commit_named_snapshot(fake_runtime, tmp_path):
+ snapshot = tmp_path / "deadbeef"
+ _write_pipeline(snapshot, "LTXPipeline", "LTXVideoTransformer3DModel")
+ status = VideoBackend().load_pipeline(
+ str(snapshot),
+ display_repo_id = "Lightricks/LTX-2-Distilled",
+ model_kind = "pipeline",
+ )
+
+ assert status["family"] == "ltx-2"
+ assert status["repo_id"] == str(snapshot)
+ assert status["display_repo_id"] == "Lightricks/LTX-2-Distilled"
+ assert status["defaults"]["steps"] == 8
+ assert status["defaults"]["guidance"] == 1.0
def test_hv15_cancel_unwinds_scheduler_loop(fake_runtime):
@@ -2048,6 +2136,31 @@ def test_video_gguf_status_reports_selected_quant_instead_of_only_compute_dtype(
backend.unload()
+def test_video_status_family_capabilities_are_probed_once(monkeypatch):
+ calls = []
+ available = (
+ types.SimpleNamespace(name = "ltx-2", modular_workflow = False),
+ types.SimpleNamespace(name = "minimax-h3", modular_workflow = True),
+ )
+ monkeypatch.setattr(
+ video_module,
+ "pipeline_available_video_families",
+ lambda *, device: calls.append(device) or available,
+ )
+ resolves = []
+ monkeypatch.setattr(
+ video_module,
+ "resolve_diffusion_device_target",
+ lambda: resolves.append(1) or types.SimpleNamespace(device = "cpu"),
+ )
+ backend = VideoBackend()
+
+ assert backend.status()["supported_families"] == ["ltx-2", "minimax-h3"]
+ assert backend.status()["modular_families"] == ["minimax-h3"]
+ assert calls == ["cpu"]
+ assert resolves == [1]
+
+
def test_video_status_response_carries_gguf_variant():
from models.inference import VideoStatusResponse
assert VideoStatusResponse(loaded = True, gguf_variant = "Q4_K_M").gguf_variant == "Q4_K_M"
@@ -6029,10 +6142,12 @@ def test_h3_native_generate_records_the_build_it_ran_on(monkeypatch):
pytest.importorskip("PIL.Image")
calls: list = []
backend = _h3_native_backend(monkeypatch, calls)
+ object.__setattr__(backend._state, "display_repo_id", "Org/pinned-h3")
result = backend.generate(prompt = "a fox runs through snow", width = 960, height = 544)
state = backend._state
+ assert result["repo_id"] == "Org/pinned-h3"
assert result["model_kind"] == state.kind == "gguf"
assert result["gguf_filename"] == state.gguf_filename
assert result["memory_mode"] == state.memory_mode
@@ -6182,6 +6297,7 @@ def test_h3_modular_load_restricts_the_components_not_the_blocks(monkeypatch, tm
torch = torch,
fam = fam,
repo_id = "MiniMaxAI/MiniMax-H3",
+ display_repo_id = "MiniMaxAI/MiniMax-H3",
base = fam.base_repo,
kind = "pipeline",
dtype = torch.bfloat16,
@@ -6195,6 +6311,7 @@ def test_h3_modular_load_restricts_the_components_not_the_blocks(monkeypatch, tm
assert "workflow" not in seen["from_pretrained"]
assert seen["load_components"]["workflow"] == "fl2va"
assert status["supports_keyframes"] is True
+ assert status["display_repo_id"] == "MiniMaxAI/MiniMax-H3"
assert status["defaults"]["canvas_short_edge"] == 768
diff --git a/studio/backend/tests/test_video_families.py b/studio/backend/tests/test_video_families.py
index ee236dd95a6..26400463eaa 100644
--- a/studio/backend/tests/test_video_families.py
+++ b/studio/backend/tests/test_video_families.py
@@ -11,6 +11,7 @@ from core.inference.video_families import (
VIDEO_NOT_LOADED_MSG,
default_video_generation_params,
detect_video_family,
+ pipeline_available_video_families,
resolve_video_base_repo,
snap_num_frames,
snap_video_size,
@@ -187,6 +188,20 @@ def test_supported_names():
)
+ "device, blocked, hidden",
+ [(None, {"minimax-h3", "ltx-2"}, {"minimax-h3", "ltx-2"}), ("mps", set(), {"minimax-h3"})],
+)
+def test_pipeline_available_families_filter_the_override_selector(
+ monkeypatch, device, blocked, hidden
+):
+ monkeypatch.setattr(
+ "core.inference.diffusion_families.family_selectable", lambda fam: fam.name not in blocked
+ )
+ available = {fam.name for fam in pipeline_available_video_families(device = device)}
+ assert set(supported_video_family_names()) - available == hidden
+
+
def test_minimax_h3_family_and_frame_lattice():
fam = detect_video_family("MiniMaxAI/MiniMax-H3")
assert fam is not None and fam.name == "minimax-h3"
diff --git a/studio/backend/tests/test_video_routes.py b/studio/backend/tests/test_video_routes.py
index dffe55069f7..fe9fc83eb4e 100644
--- a/studio/backend/tests/test_video_routes.py
+++ b/studio/backend/tests/test_video_routes.py
@@ -156,6 +156,7 @@ class _FakeBackend(video_module.VideoBackend):
gguf_filename = None,
base_repo = None,
family_override = None,
+ display_repo_id = None,
model_kind = None,
transformer_quant = None,
text_encoder_quant = None,
diff --git a/studio/frontend/src/features/chat/api/chat-api.ts b/studio/frontend/src/features/chat/api/chat-api.ts
index 2ffbf12e57a..ec4d23f1212 100644
--- a/studio/frontend/src/features/chat/api/chat-api.ts
+++ b/studio/frontend/src/features/chat/api/chat-api.ts
@@ -627,6 +627,7 @@ export interface LocalModelInfo {
model_id?: string | null;
// Backend-detected weights format ("gguf" when known), for folders whose name lacks -GGUF.
model_format?: string | null;
+ opaque?: boolean;
// Set when a cached snapshot holds an incomplete download, so consumers skip unloadable weights.
partial?: boolean;
updated_at?: number | null;
@@ -664,6 +665,7 @@ export interface CachedModelRepo {
size_bytes: number;
/** Weights format; "adapter" is a LoRA with no base weights of its own. Optional for older-backend compatibility. */
model_format?: string | null;
+ opaque?: boolean;
/** epoch seconds of the newest downloaded weight; optional for older backends. */
last_modified?: number;
/** HF pipeline task: "text-to-image" for a cached diffusers pipeline repo, so the chat picker can
diff --git a/studio/frontend/src/features/hub/inventory/api.ts b/studio/frontend/src/features/hub/inventory/api.ts
index 178a779d953..df615a7218d 100644
--- a/studio/frontend/src/features/hub/inventory/api.ts
+++ b/studio/frontend/src/features/hub/inventory/api.ts
@@ -71,6 +71,7 @@ export interface CachedModelRepo {
inventory_id?: string | null;
load_id?: string | null;
model_format?: ModelInventoryFormat | null;
+ artifact_kind?: LocalArtifactKind | null;
runtime?: ModelInventoryRuntime | null;
format_variant?: string | null;
capabilities?: BackendModelCapabilities | null;
@@ -103,6 +104,7 @@ export interface LocalModelInfo {
path: string;
size_bytes?: number;
model_format?: ModelInventoryFormat | null;
+ artifact_kind?: LocalArtifactKind | null;
runtime?: ModelInventoryRuntime | null;
format_variant?: string | null;
capabilities?: BackendModelCapabilities | null;
@@ -128,6 +130,16 @@ export interface LocalModelInfo {
quant_method?: string | null;
}
+export type LocalArtifactKind =
+ | "diffusers_pipeline"
+ | "diffusers_modular_pipeline"
+ | "diffusers_dual_pipeline"
+ | "transformers_model"
+ | "single_file_checkpoint"
+ | "gguf"
+ | "adapter"
+ | "unknown";
+
export interface LocalModelListResponse {
models_dir: string;
hf_cache_dir?: string | null;
diff --git a/studio/frontend/src/features/hub/inventory/types.ts b/studio/frontend/src/features/hub/inventory/types.ts
index efc9cd7ead0..fbd05146109 100644
--- a/studio/frontend/src/features/hub/inventory/types.ts
+++ b/studio/frontend/src/features/hub/inventory/types.ts
@@ -1,7 +1,7 @@
// 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 { BaseModelSource } from "./api";
+import type { BaseModelSource, LocalArtifactKind } from "./api";
import type { InventoryHintKind, LocalSource } from "./constants";
export type ModelInventoryFormat =
@@ -37,6 +37,7 @@ export interface CachedInventoryRow {
repo: string;
isGguf: boolean;
modelFormat: ModelInventoryFormat;
+ artifact: LocalArtifactKind;
formatVariant?: string | null;
capabilities: ModelInventoryCapabilities;
bytes: number;
@@ -84,6 +85,7 @@ export interface LocalInventoryRow {
path: string;
isGguf: boolean;
modelFormat: ModelInventoryFormat;
+ artifact: LocalArtifactKind;
formatVariant?: string | null;
capabilities: ModelInventoryCapabilities;
baseModel?: string | null;
diff --git a/studio/frontend/src/features/hub/inventory/use-hub-inventory.ts b/studio/frontend/src/features/hub/inventory/use-hub-inventory.ts
index 34f59ee4914..8b5f254f6c3 100644
--- a/studio/frontend/src/features/hub/inventory/use-hub-inventory.ts
+++ b/studio/frontend/src/features/hub/inventory/use-hub-inventory.ts
@@ -544,6 +544,7 @@ export function useHubInventory(
isGguf: false,
loadId: ds.id,
modelFormat: "unknown" as const,
+ artifact: "unknown" as const,
formatVariant: null,
capabilities: defaultCapabilities("unknown"),
updatedAt: normalizeTimestamp(ds.updated_at),
diff --git a/studio/frontend/src/features/hub/inventory/view-models.ts b/studio/frontend/src/features/hub/inventory/view-models.ts
index dfdbd707224..a3eef280a0d 100644
--- a/studio/frontend/src/features/hub/inventory/view-models.ts
+++ b/studio/frontend/src/features/hub/inventory/view-models.ts
@@ -170,6 +170,7 @@ export function buildCachedInventoryRow(
inventory_id?: string | null;
load_id?: string | null;
model_format?: ModelInventoryFormat | null;
+ artifact_kind?: import("./api").LocalArtifactKind | null;
format_variant?: string | null;
capabilities?: BackendModelCapabilities | null;
last_modified?: number | null;
@@ -206,6 +207,7 @@ export function buildCachedInventoryRow(
repo: row.repo_id.includes("/") ? repoOf(row.repo_id) : row.repo_id,
isGguf: modelFormat === "gguf",
modelFormat,
+ artifact: row.artifact_kind ?? "unknown",
formatVariant: row.format_variant ?? null,
capabilities,
bytes: row.size_bytes,
@@ -289,6 +291,7 @@ export function buildLocalInventoryRows(
path: model.path,
isGguf: modelFormat === "gguf",
modelFormat,
+ artifact: model.artifact_kind ?? "unknown",
formatVariant: model.format_variant ?? null,
capabilities,
baseModel,
diff --git a/studio/frontend/src/features/images/api.ts b/studio/frontend/src/features/images/api.ts
index f27fe0a054a..3da79cdad37 100644
--- a/studio/frontend/src/features/images/api.ts
+++ b/studio/frontend/src/features/images/api.ts
@@ -28,7 +28,10 @@ export interface DiffusionResolvedControl {
export interface DiffusionStatus {
loaded: boolean;
repo_id: string | null;
+ /** Logical Hub identity when repo_id is an exact local snapshot. */
+ display_repo_id?: string | null;
family: string | null;
+ supported_families?: string[];
base_repo: string | null;
device: string | null;
dtype: string | null;
@@ -107,6 +110,8 @@ export interface DiffusionLoadProgress {
export interface DiffusionLoadRequest {
model_path: string;
+ /** Logical Hub identity to publish while model_path remains the physical load target. */
+ display_repo_id?: string;
// Optional now: required for the gguf / single_file kinds, omitted for a full pipeline loaded via from_pretrained.
gguf_filename?: string;
// How to load the model (omit to auto-detect from gguf_filename). Non-GGUF kinds are restricted to unsloth/* repos.
diff --git a/studio/frontend/src/features/images/image-generation-defaults.ts b/studio/frontend/src/features/images/image-generation-defaults.ts
index dd018dc6a30..f12de0f6655 100644
--- a/studio/frontend/src/features/images/image-generation-defaults.ts
+++ b/studio/frontend/src/features/images/image-generation-defaults.ts
@@ -1,6 +1,8 @@
// 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 { explicitFamily } from "../model-picker/components/model-selector/family-override.ts";
+
// Generation defaults when the model is unrecognised. Also seeds the Create sliders.
export const DEFAULT_GEN = { steps: 9, guidance: 0 };
@@ -51,6 +53,19 @@ export function defaultsFor(repoId: string): {
: DEFAULT_GEN;
}
+/** A recognizable variant (Schnell vs Dev) keeps its own key; an explicit family keys only an opaque path. */
+export function defaultsKeyFor(repoId: string, familyOverride: unknown): string {
+ return defaultsFor(repoId) !== DEFAULT_GEN ? repoId : (explicitFamily(familyOverride) ?? repoId);
+}
+
+export function residentDefaultsKey(
+ repoId: string,
+ baseRepo: string | null | undefined,
+ resolvedFamily: { value?: unknown; source?: "auto" | "explicit" } | null | undefined,
+): string {
+ return defaultsKeyFor(baseRepo ?? repoId, resolvedFamily?.source === "explicit" ? resolvedFamily.value : null);
+}
+
// The canvas every family is tuned for, and what an unrecognised model gets.
export const DEFAULT_RESOLUTION = { width: 1024, height: 1024 } as const;
diff --git a/studio/frontend/src/features/images/image-model-recall.ts b/studio/frontend/src/features/images/image-model-recall.ts
index 9d8ac97ce99..d2fa3d8753b 100644
--- a/studio/frontend/src/features/images/image-model-recall.ts
+++ b/studio/frontend/src/features/images/image-model-recall.ts
@@ -1,10 +1,14 @@
// 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 { explicitFamily } from "../model-picker/components/model-selector/family-override.ts";
+
export interface RememberedImageModel {
repoId: string;
kind: "gguf" | "single_file" | "pipeline";
filename?: string;
+ // An opaque pipeline reloads only under the family it was loaded with.
+ familyOverride?: string;
}
const KEY = "unsloth:images:last-model";
@@ -20,12 +24,14 @@ export function readImageModel(): RememberedImageModel | null {
(typeof value.filename !== "string" || !value.filename)
)
return null;
+ const family = explicitFamily(value.familyOverride);
return {
repoId: value.repoId,
kind: value.kind,
...(typeof value.filename === "string"
? { filename: value.filename }
: {}),
+ ...(family ? { familyOverride: family } : {}),
};
} catch {
return null;
diff --git a/studio/frontend/src/features/images/images-page.tsx b/studio/frontend/src/features/images/images-page.tsx
index 6c8bc757d33..1ab78afbd08 100644
--- a/studio/frontend/src/features/images/images-page.tsx
+++ b/studio/frontend/src/features/images/images-page.tsx
@@ -67,6 +67,11 @@ import { useDiffusionGpuChoices } from "@/hooks/use-gpu-info";
import { usePersistedChoice } from "@/hooks/use-persisted-choice";
import { useScrollFades } from "@/hooks/use-scroll-fades";
import { ModelSelector } from "@/features/model-picker/components/model-selector";
+import {
+ explicitFamily,
+ resolvedFamilyOverrideSelection,
+ useFamilyOverride,
+} from "@/features/model-picker/components/model-selector/family-override";
import { IMAGE_GEN_TASKS } from "@/features/model-picker/components/model-selector/pickers";
import { PillTabs } from "@/features/model-picker/components/model-selector/pill-tabs";
import {
@@ -167,6 +172,7 @@ import {
resolvedSeedKey,
resolvedSelectValue,
} from "@/lib/resolved-precision";
+import { diffusionPipelineLoadTarget, diffusionStagingEntries } from "@/lib/diffusion-pipeline-load-target";
import {
routedGgufFilename,
routedGgufLabel,
@@ -174,7 +180,7 @@ import {
import { toast } from "@/lib/toast";
import { loadGalleryUntil } from "@/lib/gallery-deep-link";
import { subscribeModelEjected } from "@/lib/model-lifecycle-events";
-import { DEFAULT_GEN, defaultsFor, resolutionFor } from "./image-generation-defaults";
+import { DEFAULT_GEN, defaultsFor, defaultsKeyFor, residentDefaultsKey, resolutionFor } from "./image-generation-defaults";
import {
MIN_DIM,
type SizeLimits,
@@ -256,6 +262,14 @@ import {
type TrainFamilyOption,
} from "./train/train-base-selector";
+function withEngagedFamily(
+ { repoId, kind, filename }: RememberedImageModel,
+ status: Pick<DiffusionStatus, "resolved">,
+): RememberedImageModel {
+ const family = explicitFamily(resolvedFamilyOverrideSelection(status.resolved?.family_override));
+ return { repoId, kind, ...(filename ? { filename } : {}), ...(family ? { familyOverride: family } : {}) };
+}
+
/** Whether this pick may receive a transformer precision request. Unknown repos defer to the backend. */
function sendsTransformerQuant(kind: string | null | undefined, repoId: string): boolean {
return (
@@ -1245,6 +1259,7 @@ function reportLoadFailure(message: string | null | undefined, fallback: string)
}
type Busy = "loading" | "unloading" | "generating" | null;
+type ImageLoadOptions = { kind: "gguf" | "single_file" | "pipeline"; filename?: string; displayRepoId?: string };
// What a pick optimistically replaced, so a load that never takes can put it all back. The
// quant label and the recipe move together at pick time, so they roll back together.
@@ -1270,6 +1285,7 @@ type LoadAdvanced = Pick<
| "attention_backend"
| "memory_mode"
| "transformer_cache"
+ | "family_override"
| "loras"
| "gpu_ids"
>;
@@ -1471,9 +1487,7 @@ export function ImagesPage({
const [transformerCache, setTransformerCache] = useState<"auto" | "off" | "fbcache" | "static">("auto");
const [cpuOffload, setCpuOffload] = useState(false);
// The last load descriptor, so "Reapply" can reload the same model with new advanced options without re-picking it.
- const lastLoad = useRef<{ repoId: string; kind: "gguf" | "single_file" | "pipeline"; filename?: string } | null>(
- null,
- );
+ const lastLoad = useRef<({ repoId: string } & ImageLoadOptions) | null>(null);
// Render-safe mirror of whether a page-initiated load supplied a complete Reapply target.
const [canReapply, setCanReapply] = useState(false);
// Repo id whose defaults were already seeded from a discovered resident model, so we seed
@@ -1489,6 +1503,7 @@ export function ImagesPage({
// setInterval, so returning fires one immediate poll.
const genVisibilityListener = useRef<(() => void) | null>(null);
const [status, setStatus] = useState<DiffusionStatus | null>(null);
+ const { familyOverride, setFamilyOverride, familySelect, opaqueKind, selectorModelId } = useFamilyOverride(status, status?.supported_families);
const conditioning = status?.loaded ? (status.conditioning ?? null) : null;
const sizeLimits = useMemo(() => sizeLimitsFrom(conditioning), [conditioning]);
const unifiedEdit = Boolean(conditioning?.unified_edit);
@@ -1566,10 +1581,11 @@ export function ImagesPage({
}),
[batchSize, count, guidance, height, negativePrompt, steps, width],
);
+ const residentDefaults = residentDefaultsKey(status?.repo_id ?? "", status?.base_repo, status?.resolved?.family_override);
const imageDefaultRecipe = useMemo<ImageGenerationPresetParams>(() => {
const recommended =
pendingModelDefaults ??
- defaultsFor(status?.base_repo ?? status?.repo_id ?? "");
+ defaultsFor(residentDefaults);
// Reset restores the resident build's canvas, the same one the seed above applied. A constant
// here would quietly undo it and put a 24 GB card back over its budget.
const size = resolutionFor(status?.base_repo ?? status?.repo_id ?? "", {
@@ -1587,6 +1603,7 @@ export function ImagesPage({
};
}, [
pendingModelDefaults,
+ residentDefaults,
status?.base_repo,
status?.repo_id,
status?.model_kind,
@@ -1617,7 +1634,7 @@ export function ImagesPage({
const claimImageRecipe = imagePresets.claimRecipe;
const imageFormClaimId = imagePresets.formClaimId;
const applyImageModelDefaults = useCallback(
- (repoId: string, forceLoad = false) => {
+ (repoId: string, effectiveFamilyOverride = familyOverride, forceLoad = false) => {
if (modelSelectionAction === "download" && !forceLoad) return;
const revert = quantRevert.current;
if (revert && !revert.releaseRecipeClaim) {
@@ -1629,7 +1646,7 @@ export function ImagesPage({
// whether the user takes the form after THIS pick.
const claimedAt = imageFormClaimId();
pickRecipeSuperseded.current = () => imageFormClaimId() !== claimedAt;
- const recommended = defaultsFor(repoId);
+ const recommended = defaultsFor(defaultsKeyFor(repoId, effectiveFamilyOverride));
setPendingModelDefaults(recommended);
setSteps(recommended.steps);
setGuidance(recommended.guidance);
@@ -1638,7 +1655,7 @@ export function ImagesPage({
revert.appliedGuidance = recommended.guidance;
}
},
- [claimImageRecipe, imageFormClaimId, modelSelectionAction],
+ [claimImageRecipe, familyOverride, imageFormClaimId, modelSelectionAction],
);
const dismissLoadToast = useCallback(() => {
@@ -2473,8 +2490,9 @@ export function ImagesPage({
setStatusIfNewest(ticket, loaded);
toast.success("Model loaded");
if (lastLoad.current && matchesRememberedModel(lastLoad.current, loaded)) {
- rememberImageModel(lastLoad.current);
- setRememberedModel(lastLoad.current);
+ const remembered = withEngagedFamily(lastLoad.current, loaded);
+ rememberImageModel(remembered);
+ setRememberedModel(remembered);
}
setBusy(null);
// Load succeeded: the optimistic quant is now the real one, so drop the pending revert.
@@ -2642,22 +2660,21 @@ export function ImagesPage({
const repoId = status?.loaded ? status.repo_id : null;
if (!repoId) return;
if (lastLoad.current) return;
- if (seededResident.current === repoId) return;
- seededResident.current = repoId;
+ const seedKey = `${repoId}\0${residentDefaults}`;
+ if (seededResident.current === seedKey) return;
+ seededResident.current = seedKey;
// Wire Reapply to the resident model too. Only a full pipeline is reloadable by repo id
// alone; a resident GGUF carries no checkpoint filename, so the target stays null and the
// button hidden. Set before the recipe decision below, which is a separate question.
if (status?.model_kind === "pipeline") {
- lastLoad.current = { repoId, kind: "pipeline" };
+ lastLoad.current = { repoId, kind: "pipeline", displayRepoId: status.display_repo_id ?? undefined };
}
// A stored recipe is the user's own choice, so it outranks the resident model's defaults on the first seed.
if (!residentSeeded.current) {
residentSeeded.current = true;
if (imagePresets.storedRecipe) return;
}
- // Seed from base_repo (the resolved diffusers base, holding the family), not repo_id: a GGUF
- // resident has no family substring. Status is the authority for a resident model.
- const d = defaultsFor(status?.base_repo ?? repoId);
+ const d = defaultsFor(residentDefaults);
setPendingModelDefaults(null);
setSteps(d.steps);
setGuidance(d.guidance);
@@ -2675,6 +2692,8 @@ export function ImagesPage({
setPortrait(matched.portrait);
}, [
imagePresets.storedRecipe,
+ residentDefaults,
+ status?.display_repo_id,
status?.loaded,
status?.repo_id,
status?.base_repo,
@@ -2690,6 +2709,8 @@ export function ImagesPage({
useEffect(() => {
const record = status?.loaded ? status.resolved : null;
if (!record) return;
+ const family = resolvedFamilyOverrideSelection(record.family_override);
+ if (family) setFamilyOverride(family);
const quant = resolvedSelectValue(record.transformer_quant, (v) =>
// The engaged value spells "no quant" as "off"; the select's option for it is "none".
(["auto", "none", "int8", "fp8", "nvfp4", "mxfp8"] as const).find(
@@ -2735,7 +2756,7 @@ export function ImagesPage({
// One snapshot of every Advanced control a load sends, so a staged pick can pin the values it planned against.
const currentLoadAdvanced = useCallback(
- (repoId: string, preserveSelection = false): LoadAdvanced => {
+ (repoId: string, familyOverrideRequired = true, preserveSelection = false): LoadAdvanced => {
const baked = bakedLorasFor(repoId, preserveSelection);
return {
cpu_offload: cpuOffload,
@@ -2745,6 +2766,7 @@ export function ImagesPage({
attention_backend: attentionBackend === "auto" ? undefined : attentionBackend,
memory_mode: memoryMode === "auto" ? undefined : memoryMode,
transformer_cache: transformerCache === "auto" ? undefined : transformerCache,
+ family_override: familyOverrideRequired ? explicitFamily(familyOverride) : undefined,
loras: baked.length > 0 ? baked : undefined,
// Dropped when the chosen card is gone, so a stale pick loads automatically instead of 400ing.
gpu_ids:
@@ -2763,6 +2785,7 @@ export function ImagesPage({
attentionBackend,
memoryMode,
transformerCache,
+ familyOverride,
selectedGpu,
gpuChoices,
],
@@ -2772,10 +2795,7 @@ export function ImagesPage({
// Resolves true when the background load STARTED (callers may revert optimistic picker state on false).
async (
repoId: string,
- opts: {
- kind: "gguf" | "single_file" | "pipeline";
- filename?: string;
- },
+ opts: ImageLoadOptions,
// The Advanced values this load must use when pinned earlier: a staged download plans its file
// set at pick time and loads minutes later, so live state could outrun the staged files.
pinned?: LoadAdvanced,
@@ -2815,7 +2835,7 @@ export function ImagesPage({
const bakeLoras = advanced.loras ?? [];
// Whether THIS load carries the selection into the build, so a quantized load that did not can drop it.
bakedLorasOnLoad.current = bakeLoras.length > 0;
- lastLoad.current = { repoId, kind: opts.kind, filename: opts.filename };
+ lastLoad.current = { repoId, kind: opts.kind, filename: opts.filename, displayRepoId: opts.displayRepoId };
setCanReapply(true);
// Carry the prior target so the async poll can restore it if the background load fails after starting.
lastLoadRevert.current = { prev: prevLastLoad };
@@ -2824,6 +2844,7 @@ export function ImagesPage({
// family and base repo from the id, and the saved HF token covers gated bases.
const startRequest = loadDiffusionModel({
model_path: repoId,
+ display_repo_id: opts.displayRepoId,
model_kind: opts.kind,
gguf_filename: opts.filename,
hf_token: hfApiToken(getHfToken()),
@@ -2837,6 +2858,7 @@ export function ImagesPage({
attention_backend: advanced.attention_backend,
memory_mode: advanced.memory_mode,
transformer_cache: advanced.transformer_cache,
+ family_override: advanced.family_override,
loras: bakeLoras.length > 0 ? bakeLoras : undefined,
gpu_ids: advanced.gpu_ids,
});
@@ -2886,7 +2908,7 @@ export function ImagesPage({
// warm cache. In a ref, so the callback is not a render dep.
const pendingStagedLoad = useRef<{
repoId: string;
- opts: { kind: "gguf" | "single_file" | "pipeline"; filename?: string };
+ opts: ImageLoadOptions;
// The Advanced values the plan was built from: staging does not set `busy`, so the user can
// change precision or LoRAs while the download runs.
advanced: LoadAdvanced;
@@ -3035,7 +3057,7 @@ export function ImagesPage({
const requestDownloadPlan = useCallback(
(
repoId: string,
- opts: { kind: "gguf" | "single_file" | "pipeline"; filename?: string },
+ opts: ImageLoadOptions,
advanced: LoadAdvanced,
) =>
getDiffusionDownloadPlan({
@@ -3054,6 +3076,7 @@ export function ImagesPage({
: undefined,
text_encoder_quant: advanced.text_encoder_quant,
memory_mode: advanced.memory_mode,
+ family_override: advanced.family_override,
// The backend prefetch decision reads the adapter selection too: a baked LoRA always runs the
// dense build path, and omitting it staged too little.
loras: advanced.loras,
@@ -3067,9 +3090,10 @@ export function ImagesPage({
const loadOrStage = useCallback(
async (
repoId: string,
- opts: { kind: "gguf" | "single_file" | "pipeline"; filename?: string },
+ opts: ImageLoadOptions,
source: ModelSelectorChangeMeta["source"] = "hub",
token?: number,
+ familyOverrideRequired = false,
downloadSnapshot?: LoadAdvanced,
): Promise<boolean> => {
const downloadOnly = downloadSnapshot !== undefined || modelSelectionAction === "download";
@@ -3094,11 +3118,11 @@ export function ImagesPage({
pickToast.dismissAll();
if (!owns()) return true;
}
- if (source !== "hub" && !downloadOnly) return handleLoadRef.current(repoId, opts);
+ // ONE snapshot for the plan and the load it fires: the download runs for minutes without setting `busy`.
+ const advanced = downloadSnapshot ?? currentLoadAdvanced(repoId, familyOverrideRequired);
+ if (source !== "hub" && !downloadOnly) return handleLoadRef.current(repoId, opts, advanced);
// Show feedback before the potentially slow Hub metadata request.
const pickToastId = downloadOnly ? undefined : pickToast.show();
- // ONE snapshot for the plan and the load it fires: the download runs for minutes without setting `busy`.
- const advanced = downloadSnapshot ?? currentLoadAdvanced(repoId);
// Read before the await: a pick made while the plan resolves replaces quantRevert, and this
// job must not revert it. A download-only pick claims no slot at all: it never relabels the
// selector, so there is nothing here it could own, and reverting what it found would restore
@@ -3109,7 +3133,7 @@ export function ImagesPage({
// load if the refusal itself threw.
let incompatible: string | null = null;
try {
- const plan = await requestDownloadPlan(repoId, opts, advanced);
+ const plan = await requestDownloadPlan(opts.displayRepoId ?? repoId, opts, advanced);
// Only load intents are superseded; accepted downloads keep their own plans.
if (!downloadOnly && (pick !== pickSeq.current || !owns())) {
pickToast.dismiss(pickToastId);
@@ -3130,18 +3154,13 @@ export function ImagesPage({
};
stagedQuantRevert.current = ownRevert;
}
- const entries = plan.entries.map((e) => ({
- repoId: e.repo_id,
- files: e.files,
- bytes: e.bytes,
- ggufFilename: e.gguf_filename,
- // Keep the planner's checkpoint marker, including explicit false for companions.
- checkpoint:
- e.checkpoint ??
- (opts.filename
- ? e.files.includes(opts.filename)
- : e.repo_id === repoId),
- }));
+ const entries = diffusionStagingEntries(plan.entries, repoId, opts);
+ if (entries.length === 0) {
+ pickToast.dismiss(pickToastId);
+ if (downloadOnly) return true;
+ pendingStagedLoad.current = null;
+ return handleLoadRef.current(repoId, opts, advanced);
+ }
if (downloadOnly) {
// Picking the same model twice plans the same files twice. Queueing both downloaded
// every byte twice, and the second start could come back "busy" against the first.
@@ -3198,7 +3217,7 @@ export function ImagesPage({
const plan = await requestDownloadPlan(
repoId,
{ kind: "gguf", filename: meta.ggufFilename },
- currentLoadAdvanced(repoId),
+ currentLoadAdvanced(repoId, false),
);
const requiredBytes = plan.required_bytes ?? 0;
if (requiredBytes <= 0) return null;
@@ -3229,12 +3248,13 @@ export function ImagesPage({
quantHint: string | null,
source: ModelSelectorChangeMeta["source"] = "hub",
localPath?: string | null,
+ effectiveFamilyOverride = familyOverride,
): Promise<boolean> => {
// Normal loads belong to the latest selection. A download-only pick claims nothing and
// retires nothing: it fetches files, and a staged load already in flight still owns the page.
const downloadOnly = modelSelectionAction === "download";
const token = downloadOnly ? 0 : pickGuard.claim();
- const downloadSnapshot = downloadOnly ? currentLoadAdvanced(repoId) : undefined;
+ const downloadSnapshot = downloadOnly ? currentLoadAdvanced(repoId, false) : undefined;
const isCurrent = () => isMounted.current &&
(downloadOnly || pickGuard.holds(token));
// onResolved skips the label for a download-only pick, so this snapshot is never installed
@@ -3258,7 +3278,7 @@ export function ImagesPage({
if (downloadOnly) return;
quantRevert.current = revert;
setQuant(quantHint ?? filename);
- applyImageModelDefaults(repoId);
+ applyImageModelDefaults(repoId, effectiveFamilyOverride);
},
onNotStarted: () => {
// Nothing was applied for a download-only pick, so there is nothing to hand back, and
@@ -3269,7 +3289,7 @@ export function ImagesPage({
}
},
load: (filename) =>
- loadOrStage(repoId, { kind: "gguf", filename }, source, token, downloadSnapshot),
+ loadOrStage(repoId, { kind: "gguf", filename }, source, token, false, downloadSnapshot),
});
},
[applyImageModelDefaults, currentLoadAdvanced, loadOrStage, modelSelectionAction, pickGuard, quant, revertPick],
@@ -3310,13 +3330,14 @@ export function ImagesPage({
// already staging with its claim, or resumePendingLoad drops that load once its files arrive.
const downloadOnlyPick = modelSelectionAction === "download";
const token = downloadOnlyPick ? undefined : pickGuard.claim();
+ if (!downloadOnlyPick) setFamilyOverride("auto");
void navigateSelf({ to: "/images", search: {}, replace: true });
// A label means a GGUF repo whatever the catalog says, and is not loadable, so resolve it
// rather than routing it as a filename.
if (routedLabel) {
// Deferred, not inline: resolution is a request, and the load it fires owns the state a direct pick sets.
void Promise.resolve().then(() =>
- loadGgufRepoPick(wanted, routedLabel, "hub"),
+ loadGgufRepoPick(wanted, routedLabel, "hub", null, "auto"),
);
return;
}
@@ -3328,7 +3349,7 @@ export function ImagesPage({
);
// A curated GGUF artifact resolves to kind "gguf" with no filename: the catalog lists the repo, not its files.
if (pick.opts.kind === "gguf" && !pick.opts.filename) {
- void Promise.resolve().then(() => loadGgufRepoPick(pick.repoId, null, "hub"));
+ void Promise.resolve().then(() => loadGgufRepoPick(pick.repoId, null, "hub", null, "auto"));
return;
}
// Match every direct picker branch: the routed intent owns both the visible build label and
@@ -3340,7 +3361,7 @@ export function ImagesPage({
if (revert) {
quantRevert.current = revert;
setQuant(pick.opts.kind === "pipeline" ? null : (pick.opts.filename ?? null));
- applyImageModelDefaults(wanted);
+ applyImageModelDefaults(wanted, "auto");
}
void loadOrStage(pick.repoId, pick.opts, "hub", token).then((started) => {
if (!started && revert && token !== undefined && pickGuard.holds(token) && quantRevert.current === revert) {
@@ -3398,7 +3419,7 @@ export function ImagesPage({
// Reload the current model with the current advanced options.
const handleReapply = useCallback(() => {
const l = lastLoad.current;
- if (l) void handleLoad(l.repoId, { kind: l.kind, filename: l.filename });
+ if (l) void handleLoad(l.repoId, { kind: l.kind, filename: l.filename, displayRepoId: l.displayRepoId });
}, [handleLoad]);
// Every pick supersedes the one before it, whichever route it takes: a staged download
@@ -3429,6 +3450,11 @@ export function ImagesPage({
const token = downloadOnlyPick ? undefined : pickGuard.claim();
// A download-only pick holds no token, and an absent token owns nothing to hand back.
const stillOwnsPick = (): boolean => token !== undefined && pickGuard.holds(token);
+ const pipelineTarget = diffusionPipelineLoadTarget(id, meta);
+ const { displayRepoId } = pipelineTarget;
+ const familyOverrideRequired = meta.familyOverrideRequired === true;
+ const nextFamilyOverride = familyOverrideRequired ? familyOverride : "auto";
+ if (!downloadOnlyPick && !familyOverrideRequired) setFamilyOverride("auto");
// Curated non-GGUF model: load as a full pipeline or single-file safetensors.
const spec = loadSpecFor(id, IMAGE_CATALOG);
if (spec && spec.kind !== "gguf") {
@@ -3444,12 +3470,12 @@ export function ImagesPage({
if (revert) {
quantRevert.current = revert;
setQuant(null);
- applyImageModelDefaults(id);
+ applyImageModelDefaults(id, nextFamilyOverride);
}
void loadOrStage(
- id,
- { kind: spec.kind, filename: spec.filename },
- meta.source,
+ pipelineTarget.repoId,
+ { kind: spec.kind, filename: spec.filename, displayRepoId },
+ pipelineTarget.source,
token,
).then((started) => {
if (!started && revert && stillOwnsPick()) {
@@ -3471,7 +3497,7 @@ export function ImagesPage({
if (revert) {
quantRevert.current = revert;
setQuant(meta.ggufVariant);
- applyImageModelDefaults(id);
+ applyImageModelDefaults(id, nextFamilyOverride);
}
void loadOrStage(
id,
@@ -3501,6 +3527,7 @@ export function ImagesPage({
meta.ggufVariant ?? null,
meta.source,
meta.source === "local" ? id : null,
+ nextFamilyOverride,
);
return;
}
@@ -3515,7 +3542,7 @@ export function ImagesPage({
if (revert) {
quantRevert.current = revert;
setQuant(filename);
- applyImageModelDefaults(id);
+ applyImageModelDefaults(id, nextFamilyOverride);
}
void loadOrStage(dir, { kind: "gguf", filename }, meta.source, token).then((started) => {
// Guarded like every sibling branch: quantRevert is one slot, so a pick that no longer
@@ -3543,7 +3570,7 @@ export function ImagesPage({
if (revert) {
quantRevert.current = revert;
setQuant(filename);
- applyImageModelDefaults(id);
+ applyImageModelDefaults(id, nextFamilyOverride);
}
void loadOrStage(dir, { kind: "single_file", filename }, meta.source, token).then((started) => {
if (!started && revert && stillOwnsPick()) {
@@ -3562,11 +3589,12 @@ export function ImagesPage({
spec?.filename ?? meta.ggufVariant ?? null,
meta.source,
meta.source === "local" ? id : null,
+ nextFamilyOverride,
);
return;
}
// Otherwise treat it as a full diffusers repo. The backend gates loads to unsloth/* repos or on-device paths.
- if (meta.source !== "local" && !id.toLowerCase().startsWith("unsloth/")) {
+ if (!pipelineTarget.onDevice && !id.toLowerCase().startsWith("unsloth/")) {
// A refused Download only pick retires nothing: it never claimed the page, and the rollback
// slot it would clear belongs to whatever load is still staging.
toast.error("Only unsloth or on-device image models can be loaded here");
@@ -3583,9 +3611,9 @@ export function ImagesPage({
if (revert) {
quantRevert.current = revert;
setQuant(null);
- applyImageModelDefaults(id);
+ applyImageModelDefaults(id, nextFamilyOverride);
}
- void loadOrStage(id, { kind: "pipeline" }, meta.source, token).then((started) => {
+ void loadOrStage(pipelineTarget.repoId, { kind: "pipeline", displayRepoId }, pipelineTarget.source, token, familyOverrideRequired).then((started) => {
if (!started && revert && stillOwnsPick()) {
revertPick(revert);
quantRevert.current = null;
@@ -3597,6 +3625,8 @@ export function ImagesPage({
applyImageModelDefaults,
beginPick,
busy,
+ currentLoadAdvanced,
+ familyOverride,
handleLoad,
loadGgufRepoPick,
loadOrStage,
@@ -3630,7 +3660,7 @@ export function ImagesPage({
const revert: PickRevert = quantRevert.current ?? { prev: quant, steps, guidance };
quantRevert.current = revert;
setQuant(null);
- applyImageModelDefaults(args.baseRepo, true);
+ applyImageModelDefaults(args.baseRepo, "auto", true);
void handleLoad(args.baseRepo, { kind: "pipeline" }).then((started) => {
if (!started) {
pendingDeploy.current = null;
@@ -4329,11 +4359,7 @@ export function ImagesPage({
(kind === "pipeline" ||
((kind === "gguf" || kind === "single_file") && status.gguf_filename))
) {
- const model: RememberedImageModel = {
- repoId: status.repo_id,
- kind,
- filename: status.gguf_filename ?? undefined,
- };
+ const model = withEngagedFamily({ repoId: status.repo_id, kind, filename: status.gguf_filename ?? undefined }, status);
rememberImageModel(model);
setRememberedModel(model);
}
@@ -4358,7 +4384,8 @@ export function ImagesPage({
const started = await handleLoad(
rememberedModel.repoId,
{ kind: rememberedModel.kind, filename: rememberedModel.filename },
- currentLoadAdvanced(rememberedModel.repoId, true),
+ // Only the family the remembered load engaged; the live selection belongs to whatever is picked next.
+ { ...currentLoadAdvanced(rememberedModel.repoId, false, true), family_override: rememberedModel.familyOverride },
);
if (!started) pendingRecalledGeneration.current = null;
}, [
@@ -4439,6 +4466,7 @@ export function ImagesPage({
const advancedControls = (
<>
+ <AdvancedSelect {...familySelect} badge={<ResolvedBadge status={status} controlKey="family_override" />} />
<AdvancedSelect
label="On model selection"
hint="Choose Download only to prepare the selected model and its required assets without loading it. Applies to the next model you select; progress and cancellation appear in Downloads."
@@ -4642,7 +4670,8 @@ export function ImagesPage({
<ModelSelector
triggerDataTour="images-model"
models={imageModels}
- value={status?.loaded ? status.repo_id ?? undefined : undefined}
+ value={selectorModelId}
+ loadedModelIdOverride={selectorModelId}
activeGgufVariant={quant}
onValueChange={handleModelSelect}
resolveDownloadFootprint={resolveDownloadFootprint}
@@ -4652,6 +4681,7 @@ export function ImagesPage({
triggerLabelClassName="text-ui-14 @[68rem]:text-ui-16"
task={IMAGE_GEN_TASKS}
catalog={IMAGE_CATALOG}
+ opaqueKind={opaqueKind}
hubCapability="diffusion"
placeholder="Select image model"
open={active && selectorOpen}
diff --git a/studio/frontend/src/features/model-picker/components/model-selector.tsx b/studio/frontend/src/features/model-picker/components/model-selector.tsx
index 907a4a1450f..9011932e2d5 100644
--- a/studio/frontend/src/features/model-picker/components/model-selector.tsx
+++ b/studio/frontend/src/features/model-picker/components/model-selector.tsx
@@ -135,6 +135,8 @@ interface ModelSelectorProps {
/** Also list community (non-unsloth) models for `task`. Opt-in: only pages whose runtime loads
* arbitrary publishers. */
communityModelPolicy?: CommunityModelPolicy;
+ /** The one opaque on-device artifact kind this task runtime may load. */
+ opaqueKind?: "diffusers_pipeline" | "diffusers_modular_pipeline";
/** Hub filter the Search Hub button opens with. Also shows Search Hub on curated task pickers. */
hubCapability?: CapabilityKey;
/** Trigger text when nothing is loaded. Defaults to "Select model"; task pages name what they
@@ -356,6 +358,7 @@ function ModelSelectorContent({
task,
catalog,
communityModelPolicy,
+ opaqueKind,
}: {
open: boolean;
models: ModelOption[];
@@ -385,6 +388,7 @@ function ModelSelectorContent({
task?: HfTaskFilter;
catalog?: CatalogGroup[];
communityModelPolicy?: CommunityModelPolicy;
+ opaqueKind?: "diffusers_pipeline" | "diffusers_modular_pipeline";
}) {
const t = useT();
const hasSelection = Boolean(value);
@@ -655,6 +659,7 @@ function ModelSelectorContent({
task={task}
catalog={catalog}
communityModelPolicy={communityModelPolicy}
+ opaqueKind={opaqueKind}
npu={npu}
section={effectiveHubSection}
sectionToggle={
@@ -716,6 +721,7 @@ export function ModelSelector({
task,
catalog,
communityModelPolicy = "none",
+ opaqueKind,
hubCapability,
placeholder,
loaded,
@@ -907,6 +913,7 @@ export function ModelSelector({
task={task}
catalog={catalog}
communityModelPolicy={communityModelPolicy}
+ opaqueKind={opaqueKind}
/>
</Popover>
);
diff --git a/studio/frontend/src/features/model-picker/components/model-selector/family-override.ts b/studio/frontend/src/features/model-picker/components/model-selector/family-override.ts
new file mode 100644
index 00000000000..fb08d0e3411
--- /dev/null
+++ b/studio/frontend/src/features/model-picker/components/model-selector/family-override.ts
@@ -0,0 +1,99 @@
+// 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 { useState } from "react";
+
+export type FamilyOverrideArtifactKind = "diffusers_pipeline" | "diffusers_modular_pipeline";
+
+const LABELS: Readonly<Record<string, string>> = {
+ "flux.1": "FLUX.1",
+ "flux.2-klein": "FLUX.2 Klein",
+ "flux.2-dev": "FLUX.2 Dev",
+ "flux.1-kontext": "FLUX.1 Kontext",
+ "qwen-image": "Qwen Image",
+ "qwen-image-2.1": "Qwen Image 2.1",
+ "qwen-image-edit": "Qwen Image Edit",
+ "z-image": "Z-Image",
+ "krea-2": "Krea 2",
+ "lumina-2": "Lumina 2",
+ "hunyuanimage-2.1": "HunyuanImage 2.1",
+ "hidream-i1": "HiDream-I1",
+ "ideogram-4": "Ideogram 4",
+ sdxl: "SDXL",
+ "minimax-h3": "MiniMax-H3",
+ "ltx-2": "LTX-2",
+ "wan2.2-ti2v-5b": "Wan2.2 TI2V 5B",
+ "wan2.2-t2v-a14b": "Wan2.2 T2V A14B",
+ "hunyuanvideo-1.5": "HunyuanVideo 1.5 (480p)",
+ "hunyuanvideo-1.5-720p": "HunyuanVideo 1.5 (720p)",
+};
+
+export const FAMILY_OVERRIDE_HINT =
+ "Architecture family. Auto detects it from the repository or pipeline metadata. Choose one only for a custom Diffusers pipeline whose metadata does not identify a supported family.";
+
+/** Options come from the backend registry, so a new family cannot leave the UI stale. */
+export function familyOverrideOptions(supported: readonly string[] | null | undefined): [string, string][] {
+ const names = [...new Set(supported ?? [])].filter(Boolean);
+ return [["auto", "Auto (detect)"], ...names.map((n): [string, string] => [n, LABELS[n] ?? n])];
+}
+
+export function explicitFamily(value: unknown): string | undefined {
+ const family = typeof value === "string" ? value.trim() : "";
+ return family && family.toLowerCase() !== "auto" ? family : undefined;
+}
+
+/** A family choice admits only a structurally valid row whose task is unknown; dual roots satisfy either loader. */
+export function taskOpaqueArtifactSupportsFamilyOverride(
+ task: string | null | undefined,
+ artifactKind: string | null | undefined,
+ requiredKind: FamilyOverrideArtifactKind | null | undefined,
+): boolean {
+ return (
+ !task?.trim() &&
+ Boolean(requiredKind) &&
+ (artifactKind === requiredKind || artifactKind === "diffusers_dual_pipeline")
+ );
+}
+
+/** Restore the selector from the canonical family that engaged, not a request alias. */
+export function resolvedFamilyOverrideSelection(
+ control: { source?: "auto" | "explicit"; value?: unknown; requested?: unknown } | null | undefined,
+): string | undefined {
+ if (control?.source === "auto") return "auto";
+ for (const v of [control?.value, control?.requested]) {
+ if (typeof v === "string" && v.trim()) return v;
+ }
+ return undefined;
+}
+
+export function familyOverrideArtifactKind(
+ familyOverride: string | null | undefined,
+ modularFamilies?: readonly string[] | null,
+): FamilyOverrideArtifactKind | undefined {
+ const family = explicitFamily(familyOverride)?.toLowerCase();
+ if (!family) return undefined;
+ return modularFamilies?.some((f) => f.trim().toLowerCase() === family)
+ ? "diffusers_modular_pipeline"
+ : "diffusers_pipeline";
+}
+
+/** A pinned snapshot is labelled by its logical id in the selector. */
+export function useFamilyOverride(
+ status: { loaded: boolean; repo_id: string | null; display_repo_id?: string | null; modular_families?: string[] } | null,
+ supportedFamilies?: readonly string[],
+) {
+ const [familyOverride, setFamilyOverride] = useState("auto");
+ return {
+ familyOverride,
+ setFamilyOverride,
+ familySelect: {
+ label: "Family",
+ hint: FAMILY_OVERRIDE_HINT,
+ value: familyOverride,
+ onValueChange: setFamilyOverride,
+ options: familyOverrideOptions(supportedFamilies),
+ },
+ opaqueKind: familyOverrideArtifactKind(familyOverride, status?.modular_families),
+ selectorModelId: status?.loaded && status.repo_id ? (status.display_repo_id ?? status.repo_id) : undefined,
+ };
+}
diff --git a/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx b/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx
index bcee222dae2..179b7bb2a67 100644
--- a/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx
+++ b/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx
@@ -2626,6 +2626,7 @@ function passesTaskGate(
filter: HfTaskFilter,
catalog?: CatalogGroup[],
activeCatalogArtifactIds?: ReadonlySet<string>,
+ localModel?: { opaque?: boolean },
): boolean {
if (filter) {
const exactArtifact =
@@ -2642,7 +2643,7 @@ function passesTaskGate(
pickerTask: filter,
})) &&
!isImageEditModel(repoId)
- );
+ ) || localModel?.opaque === true;
}
// Unfiltered (chat) picker: an on-device diffusion model stays listed and routes to its page
// on click; only the never-loadable tag is hidden.
@@ -2846,6 +2847,7 @@ function localModelMeta(
isGguf = false,
pipelineTag?: string | null,
audioType?: string | null,
+ familyOverrideRequired = false,
): ModelSelectorChangeMeta {
return {
source: "local",
@@ -2854,6 +2856,7 @@ function localModelMeta(
...(isGguf ? { isGguf: true } : {}),
pipelineTag: pipelineTag ?? null,
audioType: audioType ?? null,
+ familyOverrideRequired,
};
}
@@ -2909,6 +2912,7 @@ export function HubModelPicker({
task,
catalog,
communityModelPolicy = "none",
+ opaqueKind,
npu,
}: {
models: ModelOption[];
@@ -2942,6 +2946,7 @@ export function HubModelPicker({
/** Also surface community models carrying `task`'s pipeline tags, below the unsloth rows.
* Opt-in, since the runtime has to load an arbitrary publisher's checkpoint: true of audio. */
communityModelPolicy?: CommunityModelPolicy;
+ opaqueKind?: "diffusers_pipeline" | "diffusers_modular_pipeline";
npu?: NpuPickerSource;
}) {
const gpu = useGpuInfo();
@@ -3212,6 +3217,7 @@ export function HubModelPicker({
const pickerInventory = useChatPickerInventory({
enabled: true,
allowedHiddenModelIds: activeCatalogArtifactIds,
+ opaqueKind,
});
const {
cachedGguf,
@@ -4142,6 +4148,7 @@ export function HubModelPicker({
task,
catalog,
activeCatalogArtifactIds,
+ c,
) &&
// Diffusion pickers: unsloth repos plus any repo the backend can LOAD. Gate on a curated
// ARTIFACT, not a group-key match: a base sibling matches by key but dead-ends at the trust
@@ -4174,7 +4181,9 @@ export function HubModelPicker({
})) ||
(catalog
? artifactForRepoId(c.repo_id, catalog) !== null
- : false)),
+ : false) ||
+ // A pinned snapshot admitted only by an explicit family.
+ (c.opaque === true && Boolean(c.load_id?.trim()) && c.load_id?.trim() !== c.repo_id.trim())),
),
downloadedSort,
loadTimes,
@@ -4240,6 +4249,7 @@ export function HubModelPicker({
task,
catalog,
activeCatalogArtifactIds,
+ m,
) &&
localModelMatchesFormat(m, formatFilter) &&
matchesLocalQuery(m),
@@ -4286,6 +4296,7 @@ export function HubModelPicker({
task,
catalog,
activeCatalogArtifactIds,
+ m,
) &&
(!chatOnly ||
Boolean(task) ||
@@ -4335,6 +4346,7 @@ export function HubModelPicker({
task,
catalog,
activeCatalogArtifactIds,
+ m,
) &&
localModelMatchesFormat(m, formatFilter) &&
matchesLocalQuery(m),
@@ -6362,6 +6374,7 @@ export function HubModelPicker({
isDownloaded: !isPartial,
pipelineTag: c.task ?? null,
audioType: c.audio_type ?? null,
+ familyOverrideRequired: c.opaque === true,
})
}
vramStatus={null}
@@ -6386,6 +6399,7 @@ export function HubModelPicker({
isGguf: false,
pipelineTag: c.task ?? null,
audioType: c.audio_type ?? null,
+ familyOverrideRequired: c.opaque === true,
})
}
/>
@@ -7318,7 +7332,7 @@ export function HubModelPicker({
} else {
onSelect(
m.id,
- localModelMeta(false, m.task, m.audio_type),
+ localModelMeta(false, m.task, m.audio_type, m.opaque === true),
);
}
}}
@@ -7359,7 +7373,7 @@ export function HubModelPicker({
onConfigure={() =>
onConfigure(
m.id,
- localModelMeta(false, m.task, m.audio_type),
+ localModelMeta(false, m.task, m.audio_type, m.opaque === true),
)
}
/>
@@ -7458,7 +7472,7 @@ export function HubModelPicker({
} else {
onSelect(
m.id,
- localModelMeta(false, m.task, m.audio_type),
+ localModelMeta(false, m.task, m.audio_type, m.opaque === true),
);
}
}}
@@ -7499,7 +7513,7 @@ export function HubModelPicker({
onConfigure={() =>
onConfigure(
m.id,
- localModelMeta(false, m.task, m.audio_type),
+ localModelMeta(false, m.task, m.audio_type, m.opaque === true),
)
}
/>
@@ -7589,7 +7603,7 @@ export function HubModelPicker({
} else {
onSelect(
m.id,
- localModelMeta(false, m.task, m.audio_type),
+ localModelMeta(false, m.task, m.audio_type, m.opaque === true),
);
}
}}
@@ -7626,7 +7640,7 @@ export function HubModelPicker({
onConfigure={() =>
onConfigure(
m.id,
- localModelMeta(false, m.task, m.audio_type),
+ localModelMeta(false, m.task, m.audio_type, m.opaque === true),
)
}
/>
diff --git a/studio/frontend/src/features/model-picker/components/model-selector/types.ts b/studio/frontend/src/features/model-picker/components/model-selector/types.ts
index e5e4ad33013..96c1b39ad24 100644
--- a/studio/frontend/src/features/model-picker/components/model-selector/types.ts
+++ b/studio/frontend/src/features/model-picker/components/model-selector/types.ts
@@ -78,6 +78,8 @@ export interface ModelSelectorChangeMeta {
/** Hub pipeline tag for an uncurated pick, so a task page can tell which task the repo does when
* it is not in the page's catalog. */
pipelineTag?: string | null;
+ /** Admitted only via an explicit family; detected picks must not inherit it. */
+ familyOverrideRequired?: boolean;
/** Detected local audio architecture, used when a filesystem path has no Hub id. */
audioType?: string | null;
nativePathExpiresAtMs?: number | null;
diff --git a/studio/frontend/src/features/model-picker/inventory/use-chat-picker-inventory.ts b/studio/frontend/src/features/model-picker/inventory/use-chat-picker-inventory.ts
index a4145e65e8e..724dd628946 100644
--- a/studio/frontend/src/features/model-picker/inventory/use-chat-picker-inventory.ts
+++ b/studio/frontend/src/features/model-picker/inventory/use-chat-picker-inventory.ts
@@ -17,6 +17,10 @@ import {
} from "@/features/hub";
import { useMemo } from "react";
import { allowedHiddenModelIdMatches } from "../components/model-selector/audio-picker-policy";
+import {
+ type FamilyOverrideArtifactKind,
+ taskOpaqueArtifactSupportsFamilyOverride,
+} from "../components/model-selector/family-override";
const PICKER_LOCAL_SOURCES: ReadonlySet<LocalSource> = new Set([
"lmstudio",
@@ -53,13 +57,14 @@ function toCachedGgufRepo(row: CachedInventoryRow): CachedGgufRepo {
};
}
-function toCachedModelRepo(row: CachedInventoryRow): CachedModelRepo {
+function toCachedModelRepo(row: CachedInventoryRow, opaqueKind?: FamilyOverrideArtifactKind): CachedModelRepo {
return {
repo_id: row.repoId,
load_id: row.loadId,
// Delete targets the copy the row describes; without it the request hits the active cache.
cache_path: row.cachePath,
size_bytes: row.bytes,
+ opaque: taskOpaqueArtifactSupportsFamilyOverride(row.task, row.artifact, opaqueKind),
last_modified: epochMillisecondsToSeconds(row.lastModified),
// Listed but not loadable: the row renders a partial mark and its click opens the download.
partial: row.partial,
@@ -75,7 +80,7 @@ function toCachedModelRepo(row: CachedInventoryRow): CachedModelRepo {
};
}
-function toLocalModelInfo(row: LocalInventoryRow): LocalModelInfo {
+function toLocalModelInfo(row: LocalInventoryRow, opaqueKind?: FamilyOverrideArtifactKind): LocalModelInfo {
return {
id: row.loadId,
display_name: row.displayName ?? row.title,
@@ -83,6 +88,7 @@ function toLocalModelInfo(row: LocalInventoryRow): LocalModelInfo {
source: row.source as LocalModelInfo["source"],
model_id: row.modelId ?? row.repoId,
model_format: row.modelFormat,
+ opaque: taskOpaqueArtifactSupportsFamilyOverride(row.task, row.artifact, opaqueKind),
updated_at: epochMillisecondsToSeconds(row.updatedAt),
task: row.task ?? null,
audio_type: row.audioType ?? null,
@@ -103,6 +109,8 @@ export function useChatPickerInventory(
enabled?: boolean;
/** Exact task-page artifacts that may bypass chat's hidden-model list. */
allowedHiddenModelIds?: ReadonlySet<string>;
+ /** Include task-opaque pipeline roots; the picker still applies the family gate. */
+ opaqueKind?: FamilyOverrideArtifactKind;
} = {},
): ChatPickerInventory {
const inventory = useHubInventory({
@@ -144,8 +152,8 @@ export function useChatPickerInventory(
row.repoId,
)),
)
- .map(toCachedModelRepo),
- [inventory.cachedRows, options.allowedHiddenModelIds],
+ .map((row) => toCachedModelRepo(row, options.opaqueKind)),
+ [inventory.cachedRows, options.allowedHiddenModelIds, options.opaqueKind],
);
const localModels = useMemo(
() =>
@@ -159,7 +167,8 @@ export function useChatPickerInventory(
// the chat loader, and dropping it here hid every on-device diffusion model from the pickers
// that CAN load it.
(row.capabilities.canChat ||
- studioPageForTask(row.task) !== undefined) &&
+ studioPageForTask(row.task) !== undefined ||
+ taskOpaqueArtifactSupportsFamilyOverride(row.task, row.artifact, options.opaqueKind)) &&
(!isHiddenModelId(row.modelId, row.repoId, row.path) ||
allowedHiddenModelIdMatches(
options.allowedHiddenModelIds,
@@ -167,8 +176,8 @@ export function useChatPickerInventory(
row.repoId,
)),
)
- .map(toLocalModelInfo),
- [inventory.localRows, options.allowedHiddenModelIds],
+ .map((row) => toLocalModelInfo(row, options.opaqueKind)),
+ [inventory.localRows, options.allowedHiddenModelIds, options.opaqueKind],
);
return {
diff --git a/studio/frontend/src/features/video/api.ts b/studio/frontend/src/features/video/api.ts
index 3fec394faf0..e56338b3cd6 100644
--- a/studio/frontend/src/features/video/api.ts
+++ b/studio/frontend/src/features/video/api.ts
@@ -51,7 +51,12 @@ export interface VideoGenerationDefaults {
export interface VideoStatus {
loaded: boolean;
repo_id: string | null;
+ /** Logical Hub identity when repo_id is an exact local snapshot. */
+ display_repo_id?: string | null;
family: string | null;
+ supported_families?: string[];
+ /** Pipeline-capable families whose loader accepts a Modular Diffusers manifest on this host. */
+ modular_families?: string[];
base_repo: string | null;
device: string | null;
dtype: string | null;
@@ -121,6 +126,8 @@ export interface VideoLoadProgress {
export interface VideoLoadRequest {
model_path: string;
+ /** Logical Hub identity to publish while model_path remains the physical load target. */
+ display_repo_id?: string;
// Required for the gguf / single_file kinds, omitted for a full pipeline loaded via
// from_pretrained.
gguf_filename?: string;
diff --git a/studio/frontend/src/features/video/video-page.tsx b/studio/frontend/src/features/video/video-page.tsx
index 891eb553572..ea22585783c 100644
--- a/studio/frontend/src/features/video/video-page.tsx
+++ b/studio/frontend/src/features/video/video-page.tsx
@@ -109,6 +109,11 @@ import { NegativePromptField } from "@/components/negative-prompt-field";
import { usePersistedChoice } from "@/hooks/use-persisted-choice";
import { useScrollFades } from "@/hooks/use-scroll-fades";
import { ModelSelector } from "@/features/model-picker/components/model-selector";
+import {
+ explicitFamily,
+ resolvedFamilyOverrideSelection,
+ useFamilyOverride,
+} from "@/features/model-picker/components/model-selector/family-override";
import { VIDEO_GEN_TASKS } from "@/features/model-picker/components/model-selector/pickers";
import {
type HostClass,
@@ -161,6 +166,7 @@ import {
resolvedSeedKey,
resolvedSelectValue,
} from "@/lib/resolved-precision";
+import { diffusionPipelineLoadTarget, diffusionStagingEntries } from "@/lib/diffusion-pipeline-load-target";
import {
routedGgufFilename,
routedGgufLabel,
@@ -257,6 +263,10 @@ function defaultsFor(repoId: string): { steps: number; guidance: number } {
return MODEL_DEFAULTS.find((d) => id.includes(d.match)) ?? DEFAULT_GEN;
}
+function defaultsKeyFor(repoId: string, familyOverride: string): string {
+ return defaultsFor(repoId) !== DEFAULT_GEN ? repoId : (explicitFamily(familyOverride) ?? repoId);
+}
+
// Resolution presets offered before a model is loaded; status.defaults.resolution_presets replaces these once loaded.
const FALLBACK_RESOLUTION_PRESETS: Array<[number, number]> = [
[768, 512],
@@ -819,6 +829,7 @@ type VideoLoadOptions = {
kind: "gguf" | "single_file" | "pipeline";
filename?: string;
h3Task?: H3Task;
+ displayRepoId?: string;
};
/** A pick held back while the user chooses the H3 partition. It carries what the deferred
* loadOrStage call would have been given inline, so the choice only adds `h3Task`; `source`
@@ -828,6 +839,7 @@ type PendingH3Load = {
opts: VideoLoadOptions;
source: ModelSelectorChangeMeta["source"];
token: number;
+ familyOverrideRequired: boolean;
};
const H3_BF16_REPO = "MiniMaxAI/MiniMax-H3";
@@ -835,9 +847,10 @@ const H3_BF16_REPO = "MiniMaxAI/MiniMax-H3";
/** Whether a pick is the H3 base pipeline, whose denoiser partition the user must choose. Shared
* by both entry points, since a chat-picker pick reaches loadOrStage without passing through
* handleModelSelect. An on-device copy counts and a Hub-id equality test never recognises one, so
- * it is matched on the final path segment. */
-function isH3PipelinePick(repoId: string, kind: VideoLoadOptions["kind"]): boolean {
+ * it is matched on the final path segment, or on an explicit family. */
+function isH3PipelinePick(repoId: string, kind: VideoLoadOptions["kind"], familyOverride?: string): boolean {
if (kind !== "pipeline") return false;
+ if (familyOverride?.trim().toLowerCase() === "minimax-h3") return true;
const id = repoId.toLowerCase();
if (id === H3_BF16_REPO.toLowerCase()) return true;
const leaf = id.replace(/\\/g, "/").replace(/\/+$/, "").split("/").at(-1) ?? "";
@@ -866,6 +879,7 @@ type VideoLoadAdvanced = Pick<
| "attention_backend"
| "transformer_cache"
| "transformer_quant"
+ | "family_override"
| "gpu_ids"
>;
@@ -1056,6 +1070,7 @@ function VideoGenerator({
// setInterval, so returning fires one immediate poll.
const genVisibilityListener = useRef<(() => void) | null>(null);
const [status, setStatus] = useState<VideoStatus | null>(null);
+ const { familyOverride, setFamilyOverride, familySelect, opaqueKind, selectorModelId } = useFamilyOverride(status, status?.supported_families);
// Controlled so the body-portaled model selector force-closes when this page is mounted but off-tab.
const [selectorOpen, setSelectorOpen] = useState(false);
const [pendingH3Load, setPendingH3Load] = useState<PendingH3Load | null>(null);
@@ -1436,7 +1451,7 @@ function VideoGenerator({
const claimVideoRecipe = videoPresets.claimRecipe;
const videoFormClaimId = videoPresets.formClaimId;
const applyVideoModelDefaults = useCallback(
- (repoId: string) => {
+ (repoId: string, effectiveFamilyOverride = familyOverride) => {
const revert = quantRevert.current;
if (revert && !revert.releaseRecipeClaim) {
const claim = claimVideoRecipe();
@@ -1447,7 +1462,7 @@ function VideoGenerator({
// whether the user takes the form after THIS pick.
const claimedAt = videoFormClaimId();
pickRecipeSuperseded.current = () => videoFormClaimId() !== claimedAt;
- const recommended = defaultsFor(repoId);
+ const recommended = defaultsFor(defaultsKeyFor(repoId, effectiveFamilyOverride));
setPendingModelDefaults(recommended);
setSteps(recommended.steps);
setGuidance(recommended.guidance);
@@ -1462,7 +1477,7 @@ function VideoGenerator({
modelSeeded.current = true;
familySeeded.current = true;
},
- [claimVideoRecipe, videoFormClaimId],
+ [claimVideoRecipe, familyOverride, videoFormClaimId],
);
useEffect(() => {
@@ -1585,6 +1600,8 @@ function VideoGenerator({
useEffect(() => {
const record = status?.loaded ? status.resolved : null;
if (!record) return;
+ const family = resolvedFamilyOverrideSelection(record.family_override);
+ if (family) setFamilyOverride(family);
const quant = resolvedSelectValue(record.transformer_quant, (v) =>
// The engaged value spells "no quant" as "off"; the select's option for it is "none".
(["auto", "none", "int8", "fp8", "nvfp4", "mxfp8"] as const).find(
@@ -2281,6 +2298,14 @@ function VideoGenerator({
};
}, [active, ensureSrc, ensureThumbnail, loadGallery, onInitialReady, refreshStatus]);
+ useEffect(() => {
+ const repoId = status?.loaded ? status.repo_id : null;
+ if (!repoId || lastLoad.current || status?.model_kind !== "pipeline") return;
+ const h3Task = status.h3_task === "fl2va" || status.h3_task === "ref2va" ? status.h3_task : undefined;
+ lastLoad.current = { repoId, kind: "pipeline", displayRepoId: status.display_repo_id ?? undefined, h3Task };
+ setCanReapply(true);
+ }, [status?.display_repo_id, status?.h3_task, status?.loaded, status?.model_kind, status?.repo_id]);
+
// Ejected from the loaded models indicator, which does not run handleUnload: without this the
// controls keep offering to generate on a freed runtime. So: handleUnload minus the unload.
useEffect(
@@ -2528,6 +2553,7 @@ function VideoGenerator({
attentionBackend,
transformerCache,
transformerQuant,
+ familyOverride,
selectedGpu,
gpuChoices,
});
@@ -2537,11 +2563,12 @@ function VideoGenerator({
attentionBackend,
transformerCache,
transformerQuant,
+ familyOverride,
selectedGpu,
gpuChoices,
};
const currentLoadAdvanced = useCallback(
- (kind: "gguf" | "single_file" | "pipeline"): VideoLoadAdvanced => {
+ (kind: "gguf" | "single_file" | "pipeline", familyOverrideRequired = true): VideoLoadAdvanced => {
const controls = loadControlsRef.current;
return {
memory_mode: controls.memoryMode === "auto" ? undefined : controls.memoryMode,
@@ -2554,6 +2581,7 @@ function VideoGenerator({
kind === "pipeline" && controls.transformerQuant !== "auto"
? controls.transformerQuant
: undefined,
+ family_override: familyOverrideRequired ? explicitFamily(controls.familyOverride) : undefined,
// Dropped when the chosen card is gone, so a stale pick loads automatically instead of 400ing.
gpu_ids:
controls.selectedGpu !== "auto" &&
@@ -2567,7 +2595,7 @@ function VideoGenerator({
const resolveDownloadFootprint = useCallback(
async (repoId: string, meta: ModelSelectorChangeMeta) => {
if (!meta.ggufFilename) return null;
- const advanced = currentLoadAdvanced("gguf");
+ const advanced = currentLoadAdvanced("gguf", false);
const plan = await getVideoDownloadPlan({
model_path: repoId,
gguf_filename: meta.ggufFilename,
@@ -2575,6 +2603,7 @@ function VideoGenerator({
hf_token: hfApiToken(getHfToken()),
transformer_quant: advanced.transformer_quant,
memory_mode: advanced.memory_mode,
+ family_override: advanced.family_override,
// The plan sizes its file set against the card the load will use, so it needs the pick.
gpu_ids: advanced.gpu_ids,
});
@@ -2633,6 +2662,7 @@ function VideoGenerator({
// Returns immediately; the load runs in the background and we poll.
const startRequest = loadVideoModel({
model_path: repoId,
+ display_repo_id: opts.displayRepoId,
model_kind: opts.kind,
gguf_filename: opts.filename,
hf_token: hfApiToken(getHfToken()),
@@ -2641,6 +2671,7 @@ function VideoGenerator({
attention_backend: advanced.attention_backend,
transformer_cache: advanced.transformer_cache,
transformer_quant: advanced.transformer_quant,
+ family_override: advanced.family_override,
// Not an Advanced control: the partition is chosen per pick, so it stays on opts rather than
// joining the pinned set.
h3_task: opts.h3Task,
@@ -2769,6 +2800,7 @@ function VideoGenerator({
opts: VideoLoadOptions,
source: ModelSelectorChangeMeta["source"] = "hub",
token?: number,
+ familyOverrideRequired = false,
): Promise<boolean> => {
// Every Hub pick needs the plan, not just an undownloaded one: a cached checkpoint can still be
// missing its base repo's text encoder or VAE. Staging never sets `busy`, so plans resolve in
@@ -2782,11 +2814,10 @@ function VideoGenerator({
pickToast.dismissAll();
const owns = () => token === undefined || pickGuard.holds(token);
if (!owns()) return true;
- if (source !== "hub") return handleLoadRef.current(repoId, opts);
+ const advanced = currentLoadAdvanced(opts.kind, familyOverrideRequired);
+ if (source !== "hub") return handleLoadRef.current(repoId, opts, advanced);
// Show feedback before the potentially slow Hub metadata request.
const pickToastId = pickToast.show();
-
- const advanced = currentLoadAdvanced(opts.kind);
// Read before the await: a pick made while the plan resolves replaces quantRevert, and this
// job must not revert it.
const ownRevert = quantRevert.current;
@@ -2794,7 +2825,7 @@ function VideoGenerator({
let incompatible: string | null = null;
try {
const plan = await getVideoDownloadPlan({
- model_path: repoId,
+ model_path: opts.displayRepoId ?? repoId,
gguf_filename: opts.filename,
model_kind: opts.kind,
// Same token handleLoad sends: without it the metadata lookup fails on a gated base and the
@@ -2803,6 +2834,7 @@ function VideoGenerator({
// The route preflights the same values used by the eventual load.
transformer_quant: advanced.transformer_quant,
memory_mode: advanced.memory_mode,
+ family_override: advanced.family_override,
// And the partition, for the same reason: the two H3 denoisers are separate downloads, so a
// plan asked without it stages the default fl2va weights.
h3_task: opts.h3Task,
@@ -2820,6 +2852,8 @@ function VideoGenerator({
// the shared envelope's half of the contract rather than a live path.
incompatible = plan.incompatible_reason ?? null;
if (!incompatible && plan.entries.length > 0) {
+ const entries = diffusionStagingEntries(plan.entries, repoId, opts);
+ if (entries.length === 0) return handleLoadRef.current(repoId, opts, advanced);
pendingStagedLoad.current = {
repoId,
opts,
@@ -2828,23 +2862,7 @@ function VideoGenerator({
toastId: pickToastId,
};
stagedQuantRevert.current = ownRevert;
- const staged = stage(
- plan.entries.map((e) => ({
- repoId: e.repo_id,
- files: e.files,
- bytes: e.bytes,
- ggufFilename: e.gguf_filename,
- // The entry carrying the picked checkpoint file, so the panel can label it without guessing:
- // filenames cannot tell the two apart, and repo identity is not enough when a checkpoint shares its
- // repo with cached companions. The backend's answer wins, since a gated pipeline is staged from an
- // ungated MIRROR; nullish coalescing, since false is still an answer.
- checkpoint:
- e.checkpoint ??
- (opts.filename
- ? e.files.includes(opts.filename)
- : e.repo_id === repoId),
- })),
- );
+ const staged = stage(entries);
pickToast.setPhase(pickToastId, "downloading", staged);
return true;
}
@@ -2874,6 +2892,7 @@ function VideoGenerator({
quantHint: string | null,
source: ModelSelectorChangeMeta["source"] = "hub",
localPath?: string | null,
+ effectiveFamilyOverride = familyOverride,
): Promise<boolean> => {
// Claimed here so every entry point is covered; the next pick's claim makes this one inert.
const token = pickGuard.claim();
@@ -2895,7 +2914,7 @@ function VideoGenerator({
quantRevert.current = revert;
setQuant(quantHint ?? filename);
// Filename-qualified like the expander branch: the LTX variant lives in the checkpoint name, not the repo id.
- applyVideoModelDefaults(`${repoId}/${filename}`);
+ applyVideoModelDefaults(`${repoId}/${filename}`, effectiveFamilyOverride);
},
onNotStarted: () => {
if (quantRevert.current === revert) {
@@ -2957,6 +2976,7 @@ function VideoGenerator({
const key = `${wanted}|${routeSearch?.quant ?? ""}|${routeSearch?.ggufQuant ?? ""}`;
if (handledRouteModel.current === key) return;
handledRouteModel.current = key;
+ setFamilyOverride("auto");
// This arrival owns the page like a direct pick, so a download staged by an earlier one cannot land on top.
const token = pickGuard.claim();
void navigateSelf({ to: "/video", search: {}, replace: true });
@@ -2965,7 +2985,7 @@ function VideoGenerator({
if (routedLabel) {
// Deferred, not inline: resolution is a request, and the load it fires owns the state a direct pick sets.
void Promise.resolve().then(() =>
- loadGgufRepoPick(wanted, routedLabel, "hub"),
+ loadGgufRepoPick(wanted, routedLabel, "hub", null, "auto"),
);
return;
}
@@ -2978,7 +2998,7 @@ function VideoGenerator({
);
// A curated GGUF artifact resolves to kind "gguf" with no filename: the catalog lists the repo, not its files.
if (pick.opts.kind === "gguf" && !pick.opts.filename) {
- void Promise.resolve().then(() => loadGgufRepoPick(pick.repoId, null, "hub"));
+ void Promise.resolve().then(() => loadGgufRepoPick(pick.repoId, null, "hub", null, "auto"));
return;
}
// Match every direct picker branch: the routed intent owns both the visible build label and
@@ -2988,6 +3008,7 @@ function VideoGenerator({
setQuant(pick.opts.kind === "pipeline" ? null : (pick.opts.filename ?? null));
applyVideoModelDefaults(
pick.opts.filename ? `${pick.repoId}/${pick.opts.filename}` : pick.repoId,
+ "auto",
);
// A routed pick owns the page exactly like a direct one, so it has to offer the same choice.
if (isH3PipelinePick(pick.repoId, pick.opts.kind)) {
@@ -2996,6 +3017,7 @@ function VideoGenerator({
opts: pick.opts,
source: "hub",
token,
+ familyOverrideRequired: false,
});
return;
}
@@ -3066,6 +3088,7 @@ function VideoGenerator({
{ ...pending.opts, h3Task: task },
pending.source,
pending.token,
+ pending.familyOverrideRequired,
).then((started) => {
// One slot, so only the pick that set the label may take it back.
if (!started && revert && quantRevert.current === revert && pickGuard.holds(pending.token)) {
@@ -3093,6 +3116,7 @@ function VideoGenerator({
kind: l.kind,
filename: l.filename,
h3Task: l.h3Task,
+ displayRepoId: l.displayRepoId,
});
}
}, [handleLoad]);
@@ -3117,6 +3141,11 @@ function VideoGenerator({
// This pick owns the page now, so one still awaiting a listing or a plan drops out. Before any
// branch, since staging never sets `busy`.
const token = pickGuard.claim();
+ const pipelineTarget = diffusionPipelineLoadTarget(id, meta);
+ const { displayRepoId } = pipelineTarget;
+ const familyOverrideRequired = meta.familyOverrideRequired === true;
+ const nextFamilyOverride = familyOverrideRequired ? familyOverride : "auto";
+ if (!familyOverrideRequired) setFamilyOverride("auto");
// Curated non-GGUF model: load as a full pipeline.
const spec = loadSpecFor(id, VIDEO_CATALOG);
if (spec && spec.kind !== "gguf") {
@@ -3128,20 +3157,21 @@ function VideoGenerator({
setQuant(null);
// The distilled variant lives in the checkpoint name, not the repo id, so include the filename
// when seeding defaults, or these fall through to the generic LTX 40-step/CFG-4 values.
- applyVideoModelDefaults(spec.filename ? `${id}/${spec.filename}` : id);
- if (isH3PipelinePick(id, spec.kind)) {
+ applyVideoModelDefaults(spec.filename ? `${id}/${spec.filename}` : id, nextFamilyOverride);
+ if (isH3PipelinePick(id, spec.kind, nextFamilyOverride)) {
setPendingH3Load({
- repoId: id,
- opts: { kind: spec.kind, filename: spec.filename },
- source: meta.source,
+ repoId: pipelineTarget.repoId,
+ opts: { kind: spec.kind, filename: spec.filename, displayRepoId },
+ source: pipelineTarget.source,
token,
+ familyOverrideRequired,
});
return;
}
void loadOrStage(
- id,
- { kind: spec.kind, filename: spec.filename },
- meta.source,
+ pipelineTarget.repoId,
+ { kind: spec.kind, filename: spec.filename, displayRepoId },
+ pipelineTarget.source,
token,
).then((started) => {
if (!started && pickGuard.holds(token)) {
@@ -3158,7 +3188,7 @@ function VideoGenerator({
quantRevert.current = revert;
setQuant(meta.ggufVariant);
// Include the picked filename: the variant (distilled vs dev) lives there, not in the repo id.
- applyVideoModelDefaults(`${id}/${meta.ggufFilename}`);
+ applyVideoModelDefaults(`${id}/${meta.ggufFilename}`, nextFamilyOverride);
void loadOrStage(
id,
{ kind: "gguf", filename: meta.ggufFilename },
@@ -3187,14 +3217,15 @@ function VideoGenerator({
meta.ggufVariant ?? null,
meta.source,
meta.source === "local" ? id : null,
+ nextFamilyOverride,
);
return;
}
const revert: PickRevert = quantRevert.current ?? { prev: quant, steps, guidance };
quantRevert.current = revert;
setQuant(filename);
- applyVideoModelDefaults(id);
- void handleLoad(dir, { kind: "gguf", filename }).then((started) => {
+ applyVideoModelDefaults(id, nextFamilyOverride);
+ void handleLoad(dir, { kind: "gguf", filename }, currentLoadAdvanced("gguf", false)).then((started) => {
if (!started) {
revertPick(revert);
quantRevert.current = null;
@@ -3212,8 +3243,8 @@ function VideoGenerator({
const revert: PickRevert = quantRevert.current ?? { prev: quant, steps, guidance };
quantRevert.current = revert;
setQuant(filename);
- applyVideoModelDefaults(id);
- void handleLoad(dir, { kind: "single_file", filename }).then((started) => {
+ applyVideoModelDefaults(id, nextFamilyOverride);
+ void handleLoad(dir, { kind: "single_file", filename }, currentLoadAdvanced("single_file", false)).then((started) => {
if (!started) {
revertPick(revert);
quantRevert.current = null;
@@ -3230,12 +3261,13 @@ function VideoGenerator({
spec?.filename ?? meta.ggufVariant ?? null,
meta.source,
meta.source === "local" ? id : null,
+ nextFamilyOverride,
);
return;
}
// Otherwise treat it as a full diffusers repo. The backend gates loads to unsloth/* repos, the
// family bases, or on-device paths.
- if (meta.source !== "local" && !id.toLowerCase().startsWith("unsloth/")) {
+ if (!pipelineTarget.onDevice && !id.toLowerCase().startsWith("unsloth/")) {
toast.error("Only unsloth or on-device video models can be loaded here");
abandonPick();
return;
@@ -3245,19 +3277,20 @@ function VideoGenerator({
const revert: PickRevert = quantRevert.current ?? { prev: quant, steps, guidance };
quantRevert.current = revert;
setQuant(null);
- applyVideoModelDefaults(id);
+ applyVideoModelDefaults(id, nextFamilyOverride);
// The on-device copy of the H3 pipeline lands here rather than in the curated branch, and
// needs the same partition question: without it the load silently takes fl2va.
- if (isH3PipelinePick(id, "pipeline")) {
+ if (isH3PipelinePick(id, "pipeline", nextFamilyOverride)) {
setPendingH3Load({
- repoId: id,
- opts: { kind: "pipeline" },
- source: meta.source,
+ repoId: pipelineTarget.repoId,
+ opts: { kind: "pipeline", displayRepoId },
+ source: pipelineTarget.source,
token,
+ familyOverrideRequired,
});
return;
}
- void loadOrStage(id, { kind: "pipeline" }, meta.source, token).then((started) => {
+ void loadOrStage(pipelineTarget.repoId, { kind: "pipeline", displayRepoId }, pipelineTarget.source, token, familyOverrideRequired).then((started) => {
if (!started && pickGuard.holds(token)) {
revertPick(revert);
quantRevert.current = null;
@@ -3269,7 +3302,9 @@ function VideoGenerator({
applyVideoModelDefaults,
beginPick,
busy,
+ currentLoadAdvanced,
handleLoad,
+ familyOverride,
loadGgufRepoPick,
loadOrStage,
pickGuard,
@@ -3484,6 +3519,7 @@ function VideoGenerator({
const advancedControls = (
<>
+ <AdvancedSelect {...familySelect} badge={<ResolvedBadge status={status} controlKey="family_override" />} />
<AdvancedSelect
label="Memory"
hint="auto measures free VRAM. fast keeps everything resident. balanced streams the transformer. low_vram offloads every component (lowest VRAM, slower)."
@@ -3699,7 +3735,8 @@ function VideoGenerator({
<ModelSelector
triggerDataTour="video-model"
models={videoModels}
- value={status?.loaded ? status.repo_id ?? undefined : undefined}
+ value={selectorModelId}
+ loadedModelIdOverride={selectorModelId}
activeGgufVariant={quant}
onValueChange={handleModelSelect}
resolveDownloadFootprint={resolveDownloadFootprint}
@@ -3708,6 +3745,7 @@ function VideoGenerator({
className="!h-[calc(34px*var(--ui-space-scale,1))]"
task={VIDEO_GEN_TASKS}
catalog={VIDEO_CATALOG}
+ opaqueKind={opaqueKind}
hubCapability="diffusion"
placeholder="Select video model"
open={active && selectorOpen}
diff --git a/studio/frontend/src/lib/diffusion-pipeline-load-target.ts b/studio/frontend/src/lib/diffusion-pipeline-load-target.ts
new file mode 100644
index 00000000000..8c12c9935d1
--- /dev/null
+++ b/studio/frontend/src/lib/diffusion-pipeline-load-target.ts
@@ -0,0 +1,41 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+type DiffusionPickSource = "hub" | "lora" | "exported" | "local" | "external";
+
+/** A cached row pinned to its validated snapshot loads by path; `displayRepoId` keeps the logical id for planning. */
+export function diffusionPipelineLoadTarget(
+ model: string,
+ meta: { loadId?: string | null; source: DiffusionPickSource },
+): { repoId: string; displayRepoId?: string; source: DiffusionPickSource; onDevice: boolean } {
+ const loadId = meta.loadId?.trim();
+ return loadId && loadId !== model.trim()
+ ? { repoId: loadId, displayRepoId: model, source: meta.source, onDevice: true }
+ : { repoId: model, source: meta.source, onDevice: meta.source === "local" };
+}
+
+/** Plan entries to stage. A pinned snapshot is already on disk (and its Hub revision may move), so only companions download. */
+export function diffusionStagingEntries(
+ entries: readonly {
+ repo_id: string;
+ files: string[];
+ bytes: number;
+ gguf_filename: string | null;
+ checkpoint?: boolean;
+ }[],
+ repoId: string,
+ opts: { filename?: string; displayRepoId?: string },
+) {
+ const planRepoId = opts.displayRepoId ?? repoId;
+ return entries
+ .map((e) => ({
+ repoId: e.repo_id,
+ files: e.files,
+ bytes: e.bytes,
+ ggufFilename: e.gguf_filename,
+ // `??`, not `||`: a planner answering false is an answer; the fallback is only for older backends.
+ checkpoint:
+ e.checkpoint ?? (opts.filename ? e.files.includes(opts.filename) : e.repo_id === planRepoId),
+ }))
+ .filter((e) => planRepoId === repoId || !e.checkpoint);
+}
diff --git a/studio/frontend/src/lib/resolved-precision.ts b/studio/frontend/src/lib/resolved-precision.ts
index 1e6342c5911..9bf3fbb3aba 100644
--- a/studio/frontend/src/lib/resolved-precision.ts
+++ b/studio/frontend/src/lib/resolved-precision.ts
@@ -184,6 +184,7 @@ export function resolvedSeedKey(
part(resolved.text_encoder_quant, true),
part(resolved.memory_mode, true),
part(resolved.attention_backend, false),
+ part(resolved.family_override, true),
].join("|");
}
diff --git a/studio/frontend/tests/family-override.test.ts b/studio/frontend/tests/family-override.test.ts
new file mode 100644
index 00000000000..c6370ba746d
--- /dev/null
+++ b/studio/frontend/tests/family-override.test.ts
@@ -0,0 +1,114 @@
+// 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 { readFileSync } from "node:fs";
+import test from "node:test";
+
+import {
+ explicitFamily,
+ familyOverrideArtifactKind,
+ familyOverrideOptions,
+ resolvedFamilyOverrideSelection,
+ taskOpaqueArtifactSupportsFamilyOverride,
+} from "../src/features/model-picker/components/model-selector/family-override.ts";
+import { diffusionPipelineLoadTarget, diffusionStagingEntries } from "../src/lib/diffusion-pipeline-load-target.ts";
+import { readSrc } from "./helpers/kit.ts";
+
+test("an explicit family selects exactly one structurally loadable artifact kind", () => {
+ for (const [family, modular, want] of [
+ ["auto", undefined, undefined],
+ [undefined, undefined, undefined],
+ ["z-image", undefined, "diffusers_pipeline"],
+ ["ltx-2", ["minimax-h3"], "diffusers_pipeline"],
+ [" MINIMAX-H3 ", ["minimax-h3"], "diffusers_modular_pipeline"],
+ ] as const) {
+ assert.equal(familyOverrideArtifactKind(family, modular), want, String(family));
+ }
+ for (const [value, want] of [[" z-image ", "z-image"], ["AUTO", undefined], ["", undefined], [3, undefined]] as const) {
+ assert.equal(explicitFamily(value), want);
+ }
+});
+
+test("a family admits only a task-less row of a matching (or dual) manifest", () => {
+ for (const [task, artifact, required, want] of [
+ [null, "diffusers_pipeline", "diffusers_pipeline", true],
+ [" ", "diffusers_dual_pipeline", "diffusers_pipeline", true],
+ [null, "diffusers_dual_pipeline", "diffusers_modular_pipeline", true],
+ [null, "diffusers_pipeline", "diffusers_modular_pipeline", false],
+ [null, "diffusers_pipeline", undefined, false],
+ ["text-to-image", "diffusers_pipeline", "diffusers_pipeline", false],
+ ["text-to-video", "diffusers_dual_pipeline", "diffusers_modular_pipeline", false],
+ ] as const) {
+ assert.equal(taskOpaqueArtifactSupportsFamilyOverride(task, artifact, required), want, `${task} ${artifact} ${required}`);
+ }
+});
+
+test("selector restoration prefers the canonical engaged family over an alias", () => {
+ assert.equal(resolvedFamilyOverrideSelection({ source: "explicit", requested: "h3", value: "minimax-h3" }), "minimax-h3");
+ assert.equal(resolvedFamilyOverrideSelection({ source: "explicit", requested: "h3", value: "" }), "h3");
+ assert.equal(resolvedFamilyOverrideSelection({ source: "auto", requested: null, value: "minimax-h3" }), "auto");
+ assert.equal(resolvedFamilyOverrideSelection(null), undefined);
+});
+
+test("family options follow the backend registry, deduplicated, and every backend family has a label", () => {
+ assert.deepEqual(familyOverrideOptions(["z-image", "z-image", "flux.1"]), [
+ ["auto", "Auto (detect)"],
+ ["z-image", "Z-Image"],
+ ["flux.1", "FLUX.1"],
+ ]);
+ const root = new URL("../../backend/core/inference/", import.meta.url);
+ const names = ["diffusion_families.py", "video_families.py"].flatMap((f) =>
+ [...readFileSync(new URL(f, root), "utf8").matchAll(/^\s+name = "([^"]+)"/gm)].map((m) => m[1]),
+ );
+ assert.ok(names.includes("flux.1") && names.includes("ltx-2"));
+ const unlabeled = familyOverrideOptions(names).slice(1).filter(([value, label]) => value === label);
+ assert.deepEqual(unlabeled, []);
+});
+
+test("a pinned cache snapshot loads by path, plans by its Hub id, and stages only companions", () => {
+ const pinned = diffusionPipelineLoadTarget("MiniMaxAI/MiniMax-H3", { source: "hub", loadId: " /cache/snapshots/abc " });
+ assert.deepEqual(pinned, {
+ repoId: "/cache/snapshots/abc",
+ displayRepoId: "MiniMaxAI/MiniMax-H3",
+ source: "hub",
+ onDevice: true,
+ });
+ for (const loadId of [undefined, "Org/Opaque", " "]) {
+ assert.deepEqual(diffusionPipelineLoadTarget("Org/Opaque", { source: "hub", loadId }), {
+ repoId: "Org/Opaque",
+ source: "hub",
+ onDevice: false,
+ });
+ }
+ assert.equal(diffusionPipelineLoadTarget("/models/x", { source: "local" }).onDevice, true);
+
+ const entry = (repo_id: string, checkpoint?: boolean) => ({ repo_id, files: ["a"], bytes: 1, gguf_filename: null, checkpoint });
+ const plan = [entry("MiniMaxAI/MiniMax-H3"), entry("external/quant", false)];
+ assert.deepEqual(
+ diffusionStagingEntries(plan, pinned.repoId, { displayRepoId: pinned.displayRepoId }).map((e) => e.repoId),
+ ["external/quant"],
+ );
+ assert.deepEqual(
+ diffusionStagingEntries(plan, "MiniMaxAI/MiniMax-H3", {}).map((e) => [e.repoId, e.checkpoint]),
+ [["MiniMaxAI/MiniMax-H3", true], ["external/quant", false]],
+ );
+});
+
+for (const page of ["features/images/images-page.tsx", "features/video/video-page.tsx"]) {
+ test(`${page} pins the family and logical id through plan, load and selector`, () => {
+ const text = readSrc(page);
+ for (const needle of [
+ "family_override: advanced.family_override",
+ "display_repo_id: opts.displayRepoId",
+ "displayRepoId: l.displayRepoId",
+ "opaqueKind={opaqueKind}",
+ "loadedModelIdOverride={selectorModelId}",
+ "diffusionStagingEntries(plan.entries, repoId, opts)",
+ "!pipelineTarget.onDevice",
+ ]) {
+ assert.ok(text.includes(needle), needle);
+ }
+ if (page.includes("images")) assert.ok(text.includes("downloadOnly ? currentLoadAdvanced(repoId, false)"));
+ });
+}
diff --git a/studio/frontend/tests/image-generation-defaults.test.ts b/studio/frontend/tests/image-generation-defaults.test.ts
index 7517542398a..952331ab391 100644
--- a/studio/frontend/tests/image-generation-defaults.test.ts
+++ b/studio/frontend/tests/image-generation-defaults.test.ts
@@ -5,7 +5,11 @@ import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import test from "node:test";
-import { defaultsFor } from "../src/features/images/image-generation-defaults.ts";
+import {
+ defaultsFor,
+ defaultsKeyFor,
+ residentDefaultsKey,
+} from "../src/features/images/image-generation-defaults.ts";
import { readSrc } from "./helpers/kit.ts";
@@ -37,6 +41,25 @@ test("keeps the existing family defaults and fallback", () => {
});
});
+test("an explicit family keys defaults only for an opaque path, never flattening a named variant", () => {
+ const opaque = "/models/my-private-finetune";
+ const schnell = "black-forest-labs/FLUX.1-schnell";
+ const explicit = (value: string) => ({ value, source: "explicit" as const });
+ for (const [key, want] of [
+ [defaultsKeyFor(opaque, "qwen-image"), "qwen-image"],
+ [defaultsKeyFor(opaque, "auto"), opaque],
+ [defaultsKeyFor(schnell, "flux.1"), schnell],
+ [defaultsKeyFor("Tongyi-MAI/Z-Image-Turbo", "z-image"), "Tongyi-MAI/Z-Image-Turbo"],
+ [residentDefaultsKey(opaque, opaque, explicit("qwen-image")), "qwen-image"],
+ [residentDefaultsKey(opaque, null, { value: "qwen-image", source: "auto" }), opaque],
+ [residentDefaultsKey(schnell, schnell, explicit("flux.1")), schnell],
+ ]) {
+ assert.equal(key, want);
+ }
+ assert.deepEqual(defaultsFor("qwen-image"), { steps: 20, guidance: 4 });
+ assert.deepEqual(defaultsFor(schnell), { steps: 4, guidance: 0 });
+});
+
test("routed image picks apply and transactionally roll back model defaults", () => {
const source = readSrc("features/images/images-page.tsx");
const routeStart = source.indexOf(
@@ -51,7 +74,7 @@ test("routed image picks apply and transactionally roll back model defaults", ()
const routeBlock = source.slice(routeStart, routeEnd);
assert.match(routeBlock, /imagePresets\.hydrated/);
assert.match(routeBlock, /quantRevert\.current = revert/);
- assert.match(routeBlock, /applyImageModelDefaults\(wanted\)/);
+ assert.match(routeBlock, /applyImageModelDefaults\(wanted, "auto"\)/);
assert.match(routeBlock, /!started[\s\S]*revertPick\(revert\)/);
});
diff --git a/studio/frontend/tests/image-model-recall.test.ts b/studio/frontend/tests/image-model-recall.test.ts
index c171a0e0f7d..54a604a8be2 100644
--- a/studio/frontend/tests/image-model-recall.test.ts
+++ b/studio/frontend/tests/image-model-recall.test.ts
@@ -4,6 +4,7 @@
import assert from "node:assert/strict";
import test from "node:test";
import ts from "typescript";
+import { explicitFamily } from "../src/features/model-picker/components/model-selector/family-override.ts";
import {
matchesRememberedModel,
readImageModel,
@@ -40,26 +41,19 @@ test("recalling a quantized model carries the selected adapters into its load",
"\nreturn { handleGenerateWithRecall, currentLoadAdvanced };",
{ compilerOptions: { target: ts.ScriptTarget.ES2022 } },
);
- for (const quant of ["int8", "fp8"]) {
- const model = {
- repoId: "unsloth/model-GGUF",
- kind: "gguf",
- filename: "model-Q8_0.gguf",
- };
+ const recall = (overrides: Record<string, unknown>) => {
const loads: unknown[][] = [];
const scope = {
useCallback: (fn: unknown) => fn,
lastLoad: { current: null },
status: { loaded: false, repo_id: null },
- loras: [
- { id: " org/style ", weight: 0.7 },
- { id: "", weight: 1 },
- { id: "org/off", weight: 0 },
- ],
+ loras: [],
+ familyOverride: "auto",
+ explicitFamily,
cpuOffload: false,
speedMode: "auto",
- transformerQuant: quant,
- textEncoderQuant: "int8",
+ transformerQuant: "auto",
+ textEncoderQuant: "auto",
attentionBackend: "auto",
memoryMode: "auto",
transformerCache: "auto",
@@ -68,7 +62,6 @@ test("recalling a quantized model carries the selected adapters into its load",
busy: null,
imagePresets: { hydrated: true },
prompt: "a teapot",
- rememberedModel: model,
pendingRecalledGeneration: { current: null },
oversizedOnce: { current: false },
loadSeq: { current: 3 },
@@ -80,10 +73,31 @@ test("recalling a quantized model carries the selected adapters into its load",
loads.push(args);
return true;
},
+ ...overrides,
};
const callbacks = new Function(...Object.keys(scope), outputText)(
...Object.values(scope),
);
+ return { scope, loads, callbacks };
+ };
+ for (const quant of ["int8", "fp8"]) {
+ const model = {
+ repoId: "unsloth/model-GGUF",
+ kind: "gguf",
+ filename: "model-Q8_0.gguf",
+ };
+ // The live selection (qwen-image) must not leak into a recalled load.
+ const { scope, loads, callbacks } = recall({
+ loras: [
+ { id: " org/style ", weight: 0.7 },
+ { id: "", weight: 1 },
+ { id: "org/off", weight: 0 },
+ ],
+ familyOverride: "qwen-image",
+ transformerQuant: quant,
+ textEncoderQuant: "int8",
+ rememberedModel: model,
+ });
await callbacks.handleGenerateWithRecall();
const pending = scope.pendingRecalledGeneration.current as { allowOversized?: boolean } | null;
assert.equal(pending?.allowOversized, false);
@@ -98,16 +112,37 @@ test("recalling a quantized model carries the selected adapters into its load",
loras?: unknown;
transformer_quant?: string;
text_encoder_quant?: string;
+ family_override?: string;
}
| undefined;
assert.deepEqual(advanced?.loras, [{ id: "org/style", weight: 0.7 }]);
assert.equal(advanced?.transformer_quant, quant);
assert.equal(advanced?.text_encoder_quant, "int8");
+ assert.equal(advanced?.family_override, undefined);
assert.equal(
callbacks.currentLoadAdvanced("org/different-model").loras,
undefined,
);
}
+
+ // An opaque pipeline loaded under an explicit family recalls with it after a restart (UI at Auto).
+ const { loads, callbacks } = recall({
+ rememberedModel: { repoId: "/cache/models--org--custom/snapshots/abc", kind: "pipeline", familyOverride: "flux.1" },
+ });
+ await callbacks.handleGenerateWithRecall();
+ assert.equal((loads[0][2] as { family_override?: string }).family_override, "flux.1");
+});
+
+test("recall keeps an explicit family and drops Auto", () => {
+ const model = {
+ repoId: "/cache/models--org--custom/snapshots/abc",
+ kind: "pipeline" as const,
+ familyOverride: "flux.1",
+ };
+ rememberImageModel(model);
+ assert.deepEqual(readImageModel(), model);
+ rememberImageModel({ ...model, familyOverride: "auto" });
+ assert.equal(readImageModel()?.familyOverride, undefined);
});
test("recall keeps the exact GGUF artifact", () => {
diff --git a/studio/frontend/tests/model-picker-partial-downloads.test.ts b/studio/frontend/tests/model-picker-partial-downloads.test.ts
index c1e7f63c1d1..6af7abb702b 100644
--- a/studio/frontend/tests/model-picker-partial-downloads.test.ts
+++ b/studio/frontend/tests/model-picker-partial-downloads.test.ts
@@ -198,6 +198,7 @@ test("Hub selections preserve download completeness and continuation state", ()
repo: "Model",
isGguf: false,
modelFormat: "safetensors",
+ artifact: "unknown",
capabilities,
bytes: 128,
partial: true,
@@ -216,6 +217,7 @@ test("Hub selections preserve download completeness and continuation state", ()
path: "/cache/models--Org--Model",
isGguf: false,
modelFormat: "safetensors",
+ artifact: "unknown",
capabilities,
updatedAt: 1,
partial: true,
diff --git a/studio/frontend/tests/resolved-precision.test.ts b/studio/frontend/tests/resolved-precision.test.ts
index 2ea6de1cd47..397822c8db0 100644
--- a/studio/frontend/tests/resolved-precision.test.ts
+++ b/studio/frontend/tests/resolved-precision.test.ts
@@ -238,6 +238,7 @@ test("the reseed key ignores the entries the backend rewrites mid-session", () =
transformer_quant: { value: "off", requested: null, source: "auto", status: "applied", reason: "" },
memory_mode: { value: "none", requested: null, source: "auto", status: "applied", reason: "" },
attention_backend: { value: "native", requested: null, source: "auto", status: "applied", reason: "" },
+ family_override: { value: "auto", requested: null, source: "auto", status: "applied", reason: "" },
speed_mode: { value: "deferred", requested: null, source: "auto", status: "applied", reason: "" },
transformer_cache: { value: "off", requested: null, source: "auto", status: "applied", reason: "" },
};
@@ -291,6 +292,14 @@ test("the reseed key ignores the entries the backend rewrites mid-session", () =
}),
key,
);
+ assert.notEqual(
+ resolvedSeedKey({
+ ...atLoad,
+ family_override: { value: "z-image", requested: "z-image", source: "explicit", status: "applied", reason: "" },
+ }),
+ key,
+ "a replacement load with a different family must re-seed",
+ );
});
test("the reseed key tolerates an empty or absent record", () => {
diff --git a/studio/frontend/tests/video-download-plan-payload.test.ts b/studio/frontend/tests/video-download-plan-payload.test.ts
index 50da505b13b..44a4941d387 100644
--- a/studio/frontend/tests/video-download-plan-payload.test.ts
+++ b/studio/frontend/tests/video-download-plan-payload.test.ts
@@ -40,7 +40,7 @@ test("the staged plan pins its controls through the eventual load", () => {
source.indexOf("const loadOrStage = useCallback("),
source.indexOf("// A GGUF pick can arrive"),
);
- const advancedAt = flow.indexOf("const advanced = currentLoadAdvanced(opts.kind);");
+ const advancedAt = flow.indexOf("const advanced = currentLoadAdvanced(opts.kind, familyOverrideRequired);");
const planAt = flow.indexOf("await getVideoDownloadPlan({");
assert.ok(advancedAt >= 0, "the staged flow must compute the advanced snapshot");
assert.ok(planAt >= 0, "the staged flow must request the download plan");
@@ -104,7 +104,7 @@ test("a routed H3 pipeline pick asks for the task instead of loading a default",
assert.ok(routeEffect.includes("setPendingH3Load({"));
// One predicate, so the two entry points cannot drift apart again.
assert.ok(source.includes("function isH3PipelinePick("));
- assert.ok(source.includes("isH3PipelinePick(id, spec.kind)"));
+ assert.ok(source.includes("isH3PipelinePick(id, spec.kind, nextFamilyOverride)"));
});
test("reapply preserves the loaded H3 task", () => {
diff --git a/studio/frontend/tests/video-h3-task-dialog.test.ts b/studio/frontend/tests/video-h3-task-dialog.test.ts
index d50bc6d0393..5afc7e606fc 100644
--- a/studio/frontend/tests/video-h3-task-dialog.test.ts
+++ b/studio/frontend/tests/video-h3-task-dialog.test.ts
@@ -24,7 +24,7 @@ test("only a non-hub pick skips the plan, so a cached hub pick still gets one",
// The bypass is keyed on the pick's SOURCE. A curated artifact already on disk is still
// source "hub" (localModelMeta is the only thing that emits "local"), so it keeps the plan:
// "downloaded" is a property of the repo, and an H3 repo can be half downloaded.
- assert.match(source, /if \(source !== "hub"\) return handleLoadRef\.current\(repoId, opts\);/);
+ assert.match(source, /if \(source !== "hub"\) return handleLoadRef\.current\(repoId, opts, advanced\);/);
assert.doesNotMatch(source, /if \(isDownloaded !== false\) return handleLoadRef\.current/);
// And the deferred choice re-enters loadOrStage rather than loading directly, so the plan
// decision is made again with the chosen partition in hand.
@@ -44,10 +44,11 @@ test("an on-device copy of the pipeline reaches the same dialog", () => {
);
// Not a Hub-id equality test any more: the local directory never matches one.
assert.match(predicate, /split\("\/"\)\.at\(-1\)/);
+ assert.match(predicate, /familyOverride\?\.trim\(\)\.toLowerCase\(\) === "minimax-h3"/);
assert.match(predicate, /H3_BF16_REPO\.split\("\/"\)\[1\]\.toLowerCase\(\)/);
// And the generic local-pipeline branch consults it, not only the curated branch.
assert.equal(
- source.split('isH3PipelinePick(id, "pipeline")').length - 1,
+ source.split('isH3PipelinePick(id, "pipeline", nextFamilyOverride)').length - 1,
1,
"the local-pipeline branch must intercept an H3 pick exactly once",
);
diff --git a/tests/studio/test_model_picker_contracts.py b/tests/studio/test_model_picker_contracts.py
index 8e78bdd90d5..90c60427489 100644
--- a/tests/studio/test_model_picker_contracts.py
+++ b/tests/studio/test_model_picker_contracts.py
@@ -704,7 +704,7 @@ def test_gguf_vision_capability_is_threaded_through_deferred_chat_load():
def test_local_picker_rows_require_chat_capability():
"""Local inventory rows can be classified non-chat (canChat false, e.g."""
src = _read("features/model-picker/inventory/use-chat-picker-inventory.ts")
- memo = re.search(r"const localModels = useMemo\(.*?\[inventory\.localRows", src, re.S)
+ memo = re.search(r"const localModels = useMemo\(.*?\[\s*inventory\.localRows", src, re.S)
assert memo, "localModels memo not found"
assert "row.capabilities.canChat" in memo.group(0)
@@ -1648,6 +1648,16 @@ def test_a_routed_local_single_file_pick_keeps_its_load_kind():
assert re.search(r"loadOrStage\(\s*pick\.repoId,\s*pick\.opts", src), rel
+def test_video_reapply_recovers_a_resident_pipeline_target_after_remount():
+ """Reapply after refresh rebuilds target, logical identity and H3 partition from status."""
+ src = _read("features/video/video-page.tsx")
+ assert 'status?.model_kind !== "pipeline"' in src
+ assert "displayRepoId: status.display_repo_id ?? undefined," in src
+ assert 'status.h3_task === "fl2va" || status.h3_task === "ref2va"' in src
+ assert "lastLoad.current = {" in src
+ assert "setCanReapply(true);" in src
+
+
def test_a_routed_curated_pick_uses_the_same_load_spec_as_a_direct_one():
"""The chat picker can only forward a GGUF filename (ggufFilename is GGUF-specific), so a
curated single-file artifact -- an LTX-2.3 checkpoint, an FP8 transformer -- arrives with no
@@ -2121,19 +2131,19 @@ def test_staged_plans_label_the_checkpoint_without_guessing_from_the_extension()
alone is not enough -- a checkpoint sharing its repo with the companions, and already
cached, leaves an entry of companion files that would still claim to be the model."""
for page in ("images/images-page.tsx", "video/video-page.tsx"):
- src = _read(f"features/{page}")
- entries = re.search(r"plan\.entries\.map\(\(e\) => \(\{.*?\}\)\)", src, re.S)
- assert entries, f"{page} does not map the plan entries into staged downloads"
- assert "e.files.includes(opts.filename)" in entries.group(
- 0
- ), f"{page} does not mark the picked repo's entry as the checkpoint"
- # The plan's own answer wins over both local guesses. A gated pipeline is staged from an
- # ungated MIRROR, so its entry no longer carries the id we picked and the repo-id test
- # reads the whole selected model as "Required assets". Only the planner knows about the
- # swap. `??`, not `||`: a planner that answers false must not fall through to a guess.
- assert "e.checkpoint ??" in entries.group(
- 0
- ), f"{page} ignores the checkpoint flag the plan carried"
+ assert "diffusionStagingEntries(plan.entries" in _read(
+ f"features/{page}"
+ ), f"{page} does not map the plan entries into staged downloads"
+ page = "lib/diffusion-pipeline-load-target.ts"
+ entries = re.search(r"entries\s*\.map\(\(e\) => \(\{.*?\}\)\)", _read(page), re.S)
+ assert entries, f"{page} does not map the plan entries into staged downloads"
+ assert "e.files.includes(opts.filename)" in entries.group(
+ 0
+ ), f"{page} does not mark the picked repo's entry as the checkpoint"
+ # The plan's answer wins (only it knows a gated pipeline is staged from an ungated mirror); false is final.
+ assert "e.checkpoint ??" in entries.group(
+ 0
+ ), f"{page} ignores the checkpoint flag the plan carried"
staged = _read("features/hub/download-manager/use-staged-download.ts")
assert "checkpoint?: boolean;" in staged