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.

Show all local models in the unsloth chat picker (#9435)

Nilay055bfd50aebf
diff --git a/pyproject.toml b/pyproject.toml
index c5fca524e14..87dc9975ea6 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -30,6 +30,7 @@ dependencies = [
"pydantic",
"pyyaml",
"nest-asyncio",
+ "huggingface-hub>=0.34.0",
# Every CLI command imports studio.backend.*, which reaches structlog at
# module level. The rest of the server stack lives in the studio extra.
"structlog>=24.1.0",
diff --git a/studio/backend/hub/schemas/inventory.py b/studio/backend/hub/schemas/inventory.py
index 8a2fe6abd36..d787d6149a7 100644
--- a/studio/backend/hub/schemas/inventory.py
+++ b/studio/backend/hub/schemas/inventory.py
@@ -269,6 +269,11 @@ class CachedModelRepo(CachedRepoBase):
# never a pick on ANY page. It still gets a row, because these run to tens of GB and the row
# is how they are seen and deleted; the pickers filter on this instead.
companion: bool = False
+ # True when the SELECTED revision is a diffusers pipeline. An unrecognised one carries no
+ # task and no root config for can_chat, so this flag is all that keeps it out of a chat
+ # picker. Declared because response_model drops undeclared keys, which left the CLI
+ # (reading the dict in-process) and the frontend disagreeing about the same row.
+ diffusers: bool = False
class CachedModelsResponse(BaseModel):
diff --git a/studio/backend/hub/services/__init__.py b/studio/backend/hub/services/__init__.py
index e86fcb6f462..8d32bfb9177 100644
--- a/studio/backend/hub/services/__init__.py
+++ b/studio/backend/hub/services/__init__.py
@@ -7,8 +7,6 @@ from __future__ import annotations
from typing import Iterable
-from fastapi import HTTPException
-
from hub.utils.hf_cache_state import resolve_destructive_case_matches
@@ -19,6 +17,7 @@ def resolve_destructive_repo_ids(repo_id: str, candidates: Iterable[str], *, nou
the wrong casing. *noun* is the plural shown to the user."""
resolved = resolve_destructive_case_matches(repo_id, candidates)
if resolved is None:
+ from fastapi import HTTPException
raise HTTPException(
status_code = 409,
detail = (
diff --git a/studio/backend/hub/services/models/cache_inventory.py b/studio/backend/hub/services/models/cache_inventory.py
index cde5f4817d5..1757754b3bf 100644
--- a/studio/backend/hub/services/models/cache_inventory.py
+++ b/studio/backend/hub/services/models/cache_inventory.py
@@ -13,7 +13,6 @@ from collections import OrderedDict
from pathlib import Path
from typing import NamedTuple, Optional
-from fastapi import HTTPException
from loggers import get_logger
from hub.schemas.inventory import ModelFormat
@@ -37,6 +36,7 @@ from hub.services.models.common import (
_is_mmproj_filename,
_is_transformers_safetensors_weight_name,
_local_inventory_id,
+ _local_path_can_chat,
_runtime_for_format,
)
@@ -396,18 +396,19 @@ def _cache_inventory_fields(
# The directory this row loads from: the non-GGUF scan passes only
# *identity*, so snapshot_path alone classified nothing.
classify_snapshot = identity.load_snapshot or snapshot_path
+ can_chat_override = None
+ if classify_snapshot is not None:
+ if model_format == "adapter":
+ can_chat_override = _local_path_can_chat(classify_snapshot)
+ elif model_format in {"safetensors", "checkpoint"}:
+ can_chat_override = _local_transformers_can_chat(classify_snapshot)
capabilities = _capabilities_for_format(
model_format,
"hf_cache",
partial = partial,
requires_variant = requires_variant,
- # Same classification the scan-folder rows get: a cached BERT or CLIP
- # repo is chat-capable on format alone, and small enough to be tried first.
- can_chat_override = (
- _local_transformers_can_chat(classify_snapshot)
- if model_format in {"safetensors", "checkpoint"} and classify_snapshot is not None
- else None
- ),
+ # cached encoders classify their config; adapters classify the selected snapshot's exact base.
+ can_chat_override = can_chat_override,
).model_dump()
# The loader's companion search never leaves the quants' snapshot.
if model_format == "gguf" and (
@@ -469,21 +470,38 @@ def _cached_row_companion(repo_id: str) -> bool:
return False
-def _cached_row_task(repo_info, *, gguf: bool) -> Optional[str]:
+def _cached_row_task(
+ repo_info,
+ *,
+ gguf: bool,
+ selected: Optional[Path] = None,
+) -> Optional[str]:
"""Pipeline task for a cached row, from the same classifiers the models API uses.
The Images/Video pickers filter On Device rows on this and the chat picker routes a diffusion
- pick by it, so a row that arrives without one is dropped from those lists entirely. Imported
- lazily (routes.models imports this package) and best-effort: an unreadable repo just has no
- task, exactly as before.
+ pick by it, so a row that arrives without one is dropped from those lists entirely.
"""
try:
- from routes.models import _cached_repo_task, _repo_gguf_task
- return _repo_gguf_task(repo_info) if gguf else _cached_repo_task(repo_info)
+ # Module-qualified: rebinding these names here re-points a load that resolved to
+ # routes.models before the move, which verify_import_hoist.py blocks.
+ from hub.services.models import catalog_classification
+ return (
+ catalog_classification._repo_gguf_task(repo_info, selected)
+ if gguf
+ else catalog_classification._cached_repo_task(repo_info, selected)
+ )
except Exception: # noqa: BLE001 -- a classification failure never hides a row
return None
+def _cached_row_is_diffusers(repo_info, selected: Optional[Path]) -> bool:
+ try:
+ from hub.services.models.catalog_classification import _repo_is_diffusers
+ return _repo_is_diffusers(repo_info, selected)
+ except Exception:
+ return False
+
+
def _variant_state_repositories(cache_scans):
for cache_scan in cache_scans:
for repo in cache_scan.repos:
@@ -560,6 +578,17 @@ def _scan_cached_gguf(
continue
# Must run after the skips above and before the partial walk it scopes.
gguf_snapshot, gguf_payload_snapshots = _repo_gguf_payload_snapshots(repo_info)
+ # Resolved before the row is classified, not inside _cache_inventory_fields
+ # below: a load_id left as the repo id resolves through refs/main, which can
+ # name an older revision than the newest payload snapshot. Classifying the
+ # newest then described a revision the load never reads.
+ gguf_identity = _resolve_load_identity(
+ repo_id,
+ repo_path = repo_path,
+ snapshot_path = gguf_snapshot or snapshot_path,
+ active_hub_cache = active_hub_cache,
+ payload_snapshots = gguf_payload_snapshots,
+ )
partial = hf_cache_scan.is_gguf_repo_partial(
repo_id,
repo_path,
@@ -575,7 +604,11 @@ def _scan_cached_gguf(
"repo_id": repo_id,
"size_bytes": max(total_size, variant_state_size),
"cache_path": str(repo_info.repo_path),
- "task": _cached_row_task(repo_info, gguf = True),
+ "task": _cached_row_task(
+ repo_info,
+ gguf = True,
+ selected = gguf_identity.load_snapshot or gguf_snapshot,
+ ),
"partial": partial,
# A marker-only sibling moves neither size nor mtime.
"has_variant_state": has_variant_state,
@@ -597,6 +630,8 @@ def _scan_cached_gguf(
partial = bool(row["partial"]),
requires_variant = True,
payload_snapshots = gguf_payload_snapshots,
+ # Same identity the task was classified on, so the two cannot disagree.
+ identity = gguf_identity,
# Scopes the row's vision flag to one directory.
gguf_snapshot = gguf_snapshot,
repo_info = repo_info,
@@ -667,6 +702,7 @@ async def list_cached_gguf_response(hf_token: Optional[str] = None):
cached = await _shared_cached_inventory_scan("gguf", _scan_cached_gguf)
return {"cached": cached}
except Exception as e:
+ from fastapi import HTTPException
logger.error(
"Error listing cached GGUF repos: %s",
download_registry.scrub_secrets(str(e), hf_token = hf_token),
@@ -1061,7 +1097,7 @@ def _scan_cached_models(
else (
"text-to-speech"
if local_metadata.get("pipeline_tag") == "text-to-speech"
- else _cached_row_task(repo_info, gguf = False)
+ else _cached_row_task(repo_info, gguf = False, selected = load_snapshot)
)
)
if is_whisper_stt:
@@ -1106,6 +1142,7 @@ def _scan_cached_models(
# Listed so tens of GB of companion weights stay visible and deletable, but
# flagged so no picker offers a denoiser-less repo as a load.
"companion": _cached_row_companion(repo_id),
+ "diffusers": _cached_row_is_diffusers(repo_info, load_snapshot),
**local_metadata,
}
last_modified = max(
@@ -1150,6 +1187,7 @@ async def list_cached_models_response(hf_token: Optional[str] = None):
cached = await _shared_cached_inventory_scan("models", _scan_cached_models)
return {"cached": cached}
except Exception as e:
+ from fastapi import HTTPException
logger.error(
"Error listing cached models: %s",
download_registry.scrub_secrets(str(e), hf_token = hf_token),
diff --git a/studio/backend/hub/services/models/catalog_classification.py b/studio/backend/hub/services/models/catalog_classification.py
new file mode 100644
index 00000000000..cc592577774
--- /dev/null
+++ b/studio/backend/hub/services/models/catalog_classification.py
@@ -0,0 +1,416 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Dependency-light task classification for model inventory rows."""
+
+from __future__ import annotations
+
+import re
+import time
+from pathlib import Path
+from typing import Optional
+
+from hub.services.models.common import (
+ _is_diffusers_pipeline_dir,
+ _is_mmproj_filename,
+ _iter_gguf_paths,
+ _local_path_can_chat,
+)
+from utils.gguf_archs import SPEECH_GGUF_ARCHS, is_speech_gguf_architecture
+
+
+_DIFFUSION_GGUF_ARCHS = frozenset({"flux", "flux2", "qwen_image", "qwenimage", "z_image", "zimage"})
+_UNSUPPORTED_DIFFUSION_GGUF_ARCHS = frozenset(
+ {"sd1", "sd3", "sdxl", "aura", "hidream", "cosmos", "hyvid"}
+)
+_AMBIGUOUS_DIFFUSION_GGUF_ARCHS = frozenset({"lumina2"})
+_PLACEHOLDER_DIFFUSION_GGUF_ARCHS = frozenset({"pig", "cow"})
+_VIDEO_GGUF_ARCHS = frozenset({"ltxv", "wan"})
+_VIDEO_GEN_TASK = "text-to-video"
+
+# TTS-only GGUF archs llama.cpp cannot load, tagged speech so the chat picker keeps them out of
+# llama-server. One shared definition rather than a copy per layer: the chat gate, this classifier
+# and the media preflight all have to agree.
+_SPEECH_GGUF_ARCHS = SPEECH_GGUF_ARCHS
+_SPEECH_TASK = "text-to-speech"
+_UNSUPPORTED_DIFFUSION_TASK = "image-diffusion-unsupported"
+_H3_DENOISER_GGUF_PREFIXES = ("minimax_h3_fl2va", "minimax_h3_ref2va")
+_LOADABLE_MEDIA_GGUF_TASKS = frozenset({"text-to-image", _VIDEO_GEN_TASK})
+_MAX_TASK_CLASSIFY_GGUFS = 64
+_TASK_CLASSIFY_WALK_SECONDS = 0.75
+_TASK_CLASSIFY_READ_SECONDS = 1.5
+_QWEN3_ASR_HINT = re.compile(
+ r"(?<![a-z0-9])qwen3[-_. ]*asr[-_. ]*(?:0[._]6|1[._]7)b(?![a-z0-9])",
+ re.IGNORECASE,
+)
+
+
+def _is_h3_bundle_gguf_hint(hint: Optional[str]) -> bool:
+ if not hint:
+ return False
+ name = str(hint).strip().lower().rsplit("/", 1)[-1].rsplit("\\", 1)[-1]
+ if name.endswith(".gguf") and name.startswith(_H3_DENOISER_GGUF_PREFIXES):
+ return True
+ try:
+ from hub.utils.gguf import is_h3_bundle_repo
+ return is_h3_bundle_repo(hint)
+ except Exception:
+ return False
+
+
+def _gguf_architecture(path: str) -> Optional[str]:
+ from utils.models.gguf_metadata import read_gguf_architecture
+ return read_gguf_architecture(path)
+
+
+def _gguf_family_buildable(name_hints: tuple[Optional[str], ...]) -> bool:
+ try:
+ from core.inference.diffusion_engine_router import family_buildable_here
+ from core.inference.diffusion_families import detect_family_for_pick
+ for hint in name_hints:
+ if not hint:
+ continue
+ family = detect_family_for_pick(hint)
+ if family is not None:
+ return family_buildable_here(family, model_kind = "gguf")
+ except Exception:
+ return True
+ return True
+
+
+def _video_family_buildable(family) -> bool:
+ try:
+ from core.inference.diffusion_families import family_pipeline_available
+ return family_pipeline_available(family)
+ except Exception:
+ return True
+
+
+def _arch_to_task(arch: Optional[str], name_hints: tuple[Optional[str], ...] = ()) -> Optional[str]:
+ if any(_is_h3_bundle_gguf_hint(hint) for hint in name_hints):
+ return _VIDEO_GEN_TASK
+ if arch is None:
+ return None
+ normalized = arch.lower()
+ if normalized == "qwen3" and any(
+ _QWEN3_ASR_HINT.search(str(hint)) for hint in name_hints if hint
+ ):
+ return "automatic-speech-recognition"
+ if normalized in _PLACEHOLDER_DIFFUSION_GGUF_ARCHS:
+ from core.inference.video_families import detect_video_family
+
+ for hint in name_hints:
+ family = detect_video_family(hint) if hint else None
+ if family is not None:
+ if not getattr(family, "is_moe", False) and _video_family_buildable(family):
+ return _VIDEO_GEN_TASK
+ return _UNSUPPORTED_DIFFUSION_TASK
+ from core.inference.diffusion_families import detect_family_for_pick
+
+ if any(detect_family_for_pick(hint) is not None for hint in name_hints if hint):
+ return (
+ "text-to-image"
+ if _gguf_family_buildable(name_hints)
+ else _UNSUPPORTED_DIFFUSION_TASK
+ )
+ return _UNSUPPORTED_DIFFUSION_TASK
+ if is_speech_gguf_architecture(normalized):
+ return _SPEECH_TASK
+ if normalized in _DIFFUSION_GGUF_ARCHS:
+ return (
+ "text-to-image" if _gguf_family_buildable(name_hints) else _UNSUPPORTED_DIFFUSION_TASK
+ )
+ if normalized in _VIDEO_GGUF_ARCHS:
+ from core.inference.video_families import detect_video_family
+
+ family = detect_video_family("", override = normalized)
+ if family is None:
+ for hint in name_hints:
+ if hint:
+ family = detect_video_family(hint)
+ if family is not None:
+ break
+ if (
+ family is not None
+ and not getattr(family, "is_moe", False)
+ and _video_family_buildable(family)
+ ):
+ return _VIDEO_GEN_TASK
+ return _UNSUPPORTED_DIFFUSION_TASK
+ if normalized in _AMBIGUOUS_DIFFUSION_GGUF_ARCHS:
+ from core.inference.diffusion_engine_router import family_buildable_here
+ from core.inference.diffusion_families import detect_family_for_pick, family_gguf_loadable
+
+ for hint in name_hints:
+ if not hint:
+ continue
+ family = detect_family_for_pick(hint)
+ if family is not None:
+ loadable = family_gguf_loadable(family) and family_buildable_here(
+ family, model_kind = "gguf"
+ )
+ return "text-to-image" if loadable else _UNSUPPORTED_DIFFUSION_TASK
+ return _UNSUPPORTED_DIFFUSION_TASK
+ if normalized in _UNSUPPORTED_DIFFUSION_GGUF_ARCHS:
+ return _UNSUPPORTED_DIFFUSION_TASK
+ return "text-generation"
+
+
+def _is_trailing_split_shard(name: str) -> bool:
+ try:
+ from utils.models.model_config import _GGUF_SPLIT_FILE_RE
+ except ImportError:
+ return False
+ match = _GGUF_SPLIT_FILE_RE.match(name)
+ return match is not None and match.group("index") != "00001"
+
+
+def _task_classify_sort_key(root: Path, path: Path) -> tuple[str, str]:
+ try:
+ relative = path.relative_to(root).as_posix()
+ except ValueError:
+ relative = path.name
+ return (relative.lower(), relative)
+
+
+def _gguf_folder_task(
+ root: Path,
+ id_hints: tuple[Optional[str], ...],
+ deadline: Optional[float] = None,
+) -> Optional[str]:
+ if deadline is None:
+ deadline = time.monotonic() + _TASK_CLASSIFY_WALK_SECONDS
+ fallback: Optional[str] = None
+ try:
+ scored: list[tuple[tuple[str, str], Path]] = []
+ # Recorded as the tail is dropped, never inferred from `scored` afterwards: trimming cuts
+ # back to the cap, so an overflowing folder is indistinguishable from one that fit.
+ overflowed = False
+ for path in _iter_gguf_paths(root, deadline):
+ name = path.name
+ if _is_mmproj_filename(name) or _is_trailing_split_shard(name):
+ continue
+ scored.append((_task_classify_sort_key(root, path), path))
+ if len(scored) > _MAX_TASK_CLASSIFY_GGUFS * 2:
+ scored.sort(key = lambda item: item[0])
+ del scored[_MAX_TASK_CLASSIFY_GGUFS:]
+ overflowed = True
+ scored.sort(key = lambda item: item[0])
+ paths = [path for _, path in scored[:_MAX_TASK_CLASSIFY_GGUFS]]
+ # Whether every candidate made it into `paths`: the walk gives up at its own deadline and
+ # the cap drops the tail, so either can leave a sibling unseen.
+ complete = (
+ not overflowed
+ and len(scored) <= _MAX_TASK_CLASSIFY_GGUFS
+ and time.monotonic() < deadline
+ )
+ except Exception:
+ return None
+ unsupported: Optional[str] = None
+ speech: Optional[str] = None
+ read_deadline = time.monotonic() + _TASK_CLASSIFY_READ_SECONDS
+ for index, path in enumerate(paths):
+ if index and time.monotonic() >= read_deadline:
+ complete = False
+ break
+ try:
+ task = _arch_to_task(_gguf_architecture(str(path)), name_hints = id_hints + (path.name,))
+ except Exception:
+ # Unread, so unranked: this file might have been the runnable sibling.
+ complete = False
+ continue
+ if task is None:
+ # A truncated header gives no architecture, and _arch_to_task answers None.
+ complete = False
+ continue
+ if task in _LOADABLE_MEDIA_GGUF_TASKS:
+ return task
+ # Speech is last resort: nothing here runs a llama-csm GGUF, so answering speech while a
+ # sibling is loadable hides that sibling. A speech-only folder still tags speech.
+ if task == _SPEECH_TASK:
+ if speech is None:
+ speech = task
+ elif task == _UNSUPPORTED_DIFFUSION_TASK:
+ unsupported = unsupported or task
+ elif task is not None and fallback is None:
+ fallback = task
+ # Speech only on a whole folder: it is the one answer that HIDES a row rather than filing it.
+ return unsupported or fallback or (speech if complete else None)
+
+
+def _repo_gguf_task(repo_info, selected: Optional[Path] = None) -> Optional[str]:
+ repo_id = getattr(repo_info, "repo_id", None)
+ try:
+ return _gguf_folder_task(selected or Path(repo_info.repo_path), (repo_id,))
+ except Exception:
+ return None
+
+
+def _gguf_path_task(path: str | Path, id_hints: tuple[Optional[str], ...] = ()) -> Optional[str]:
+ model_path = Path(path)
+ try:
+ if model_path.suffix.lower() == ".gguf" and model_path.is_file():
+ return _arch_to_task(
+ _gguf_architecture(str(model_path)),
+ name_hints = id_hints + (model_path.name,),
+ )
+ return _gguf_folder_task(model_path, id_hints)
+ except Exception:
+ return None
+
+
+def _hf_cache_snapshot_repo_id(path: Optional[str]) -> Optional[str]:
+ if not path:
+ return None
+ parts = str(path).replace("\\", "/").rstrip("/").split("/")
+ if len(parts) >= 3 and parts[-2] == "snapshots" and parts[-3].startswith("models--"):
+ from core.inference.model_ids import hf_cache_repo_id
+ return hf_cache_repo_id(path)
+ return None
+
+
+def _local_family_needles(model) -> tuple[str, ...]:
+ needles = [model.model_id, model.display_name, Path(model.id).name]
+ try:
+ needles.append(
+ _hf_cache_snapshot_repo_id(model.path) or _hf_cache_snapshot_repo_id(model.id)
+ )
+ except Exception:
+ pass
+ try:
+ from core.inference.diffusion import resolve_local_single_file
+ single = resolve_local_single_file(model.path)
+ if single:
+ needles.append(single)
+ except Exception:
+ pass
+ return tuple(needle for needle in needles if needle)
+
+
+def _local_model_can_chat(model) -> Optional[bool]:
+ return _local_path_can_chat(model.path, getattr(model, "base_model", None))
+
+
+def _local_model_task(model) -> Optional[str]:
+ path = model.path
+ id_hints = (model.model_id, model.display_name, model.id)
+ if model.model_format == "gguf" or Path(path).suffix.lower() == ".gguf":
+ return _gguf_path_task(path, id_hints)
+ if not _local_is_diffusers(model):
+ return None
+ try:
+ from core.inference.video import _is_trusted_video_repo
+ from core.inference.video_families import detect_video_family
+ for needle in _local_family_needles(model):
+ family = detect_video_family(needle)
+ if family is not None and _is_trusted_video_repo(path):
+ return _VIDEO_GEN_TASK if _video_family_buildable(family) else None
+ except Exception:
+ pass
+ try:
+ from core.inference.diffusion_engine_router import family_buildable_here
+ from core.inference.diffusion_families import detect_family, detect_family_by_pipeline_index
+
+ families = (
+ detect_family_by_pipeline_index(path),
+ *(detect_family(needle) for needle in _local_family_needles(model)),
+ )
+ for family in families:
+ if family is not None:
+ return (
+ "text-to-image"
+ if family_buildable_here(family, model_kind = "pipeline")
+ else None
+ )
+ return None
+ except Exception:
+ return "text-to-image"
+
+
+def _local_is_diffusers(model) -> bool:
+ try:
+ path = Path(model.path)
+ if path.is_dir() and _is_diffusers_pipeline_dir(path):
+ return True
+ except Exception:
+ pass
+ try:
+ from core.inference.diffusion_families import detect_family
+ if any(detect_family(needle) is not None for needle in _local_family_needles(model)):
+ return True
+ except Exception:
+ pass
+ try:
+ from core.inference.video_families import detect_video_family
+ return any(
+ detect_video_family(needle) is not None for needle in _local_family_needles(model)
+ )
+ except Exception:
+ return False
+
+
+def _repo_has_pipeline_index(repo_info, selected: Optional[Path] = None) -> bool:
+ if selected is not None:
+ return _is_diffusers_pipeline_dir(selected)
+ from hub.utils import inventory_scan
+ return inventory_scan.repo_has_pipeline_index(repo_info)
+
+
+def _repo_is_diffusers(repo_info, selected: Optional[Path] = None) -> bool:
+ if _repo_has_pipeline_index(repo_info, selected):
+ return True
+ repo_id = getattr(repo_info, "repo_id", "") or ""
+ try:
+ from core.inference.diffusion_families import detect_family
+ if detect_family(repo_id) is not None:
+ return True
+ except Exception:
+ pass
+ # Video too, as _local_is_diffusers already asks. _cached_repo_task returns None for an
+ # unbuildable video repo, so a single-file video checkpoint with no pipeline index carried
+ # no task and no diffusers flag, and an inconclusive config leaves can_chat set: every gate
+ # the chat picker has passes and the video weights reach the text loader.
+ try:
+ from core.inference.video_families import detect_video_family
+ return detect_video_family(repo_id) is not None
+ except Exception:
+ return False
+
+
+def _is_sd_cpp_companion_repo(repo_id: str) -> bool:
+ try:
+ from core.inference.diffusion_families import sd_cpp_companion_only_repo_ids
+ return (repo_id or "").strip().lower() in sd_cpp_companion_only_repo_ids()
+ except Exception:
+ return False
+
+
+def _cached_repo_task(repo_info, selected: Optional[Path] = None) -> Optional[str]:
+ repo_id = getattr(repo_info, "repo_id", "") or ""
+ try:
+ from core.inference.video import _is_trusted_video_repo
+ from core.inference.video_families import detect_video_family
+
+ family = detect_video_family(repo_id)
+ if family is not None:
+ if not _is_trusted_video_repo(repo_id) or not _video_family_buildable(family):
+ return None
+ return _VIDEO_GEN_TASK
+ except Exception:
+ pass
+ if not _repo_is_diffusers(repo_info, selected):
+ return None
+ try:
+ from core.inference.diffusion import _is_trusted_diffusion_repo
+ from core.inference.diffusion_families import detect_family, family_pipeline_available
+
+ if _is_sd_cpp_companion_repo(repo_id):
+ return None
+ family = detect_family(repo_id)
+ if not _is_trusted_diffusion_repo(repo_id) or family is None:
+ return None
+ if not family_pipeline_available(family):
+ return None
+ return "text-to-image"
+ except Exception:
+ return "text-to-image"
diff --git a/studio/backend/hub/services/models/common.py b/studio/backend/hub/services/models/common.py
index 404d052b5d1..194b8febcc1 100644
--- a/studio/backend/hub/services/models/common.py
+++ b/studio/backend/hub/services/models/common.py
@@ -7,6 +7,7 @@ from __future__ import annotations
import json
import os
+import time
from pathlib import Path
from typing import List, Literal, Optional
from urllib.parse import quote
@@ -100,6 +101,15 @@ def _is_model_directory(d: Path) -> bool:
return False
+def _is_diffusers_pipeline_dir(path: Path) -> bool:
+ try:
+ return (path / "model_index.json").is_file() or (
+ path / "modular_model_index.json"
+ ).is_file()
+ except OSError:
+ return False
+
+
def _local_inventory_id(
source: str,
model_format: ModelFormat,
@@ -349,6 +359,101 @@ def _local_transformers_can_chat(path: Path) -> Optional[bool]:
return None
+def _hub_cache_root_of(path: Optional[Path]) -> Optional[Path]:
+ """The hub cache root *path* sits in, i.e. the parent of its ``models--*`` repo dir."""
+ if path is None:
+ return None
+ try:
+ candidate = Path(path)
+ for part in (candidate, *candidate.parents):
+ if part.name.startswith("models--"):
+ return part.parent
+ except (OSError, RuntimeError, ValueError):
+ return None
+ return None
+
+
+def _base_transformers_can_chat(
+ base_model: str,
+ revision: Optional[str],
+ adapter_path: Optional[Path] = None,
+) -> Optional[bool]:
+ """Classify an exact local or cached base without a network lookup."""
+ try:
+ local_path = Path(base_model).expanduser()
+ if local_path.is_dir():
+ return _local_transformers_can_chat(local_path)
+ except (OSError, RuntimeError, ValueError):
+ return None
+
+ # The adapter's own root first, then the active root, then the configured ones. The scan
+ # covers legacy and previously configured roots, so an adapter can be listed from an
+ # inactive root with its base cached beside it; the active root alone answered None there,
+ # and None is inconclusive, which left a Whisper or encoder LoRA in the chat picker.
+ try:
+ from huggingface_hub import try_to_load_from_cache
+ except Exception:
+ return None
+
+ # Each source collected independently: under one try, a failure enumerating the OPTIONAL
+ # extra roots discarded the adapter's own root too and answered None, the same fail-open
+ # this function exists to close.
+ roots: list[Path] = []
+
+ def _add(root: Optional[Path]) -> None:
+ if root is not None and root not in roots:
+ roots.append(root)
+
+ _add(_hub_cache_root_of(adapter_path))
+ try:
+ from utils.hf_cache_settings import get_hf_cache_paths
+ _add(get_hf_cache_paths().hub_cache)
+ except Exception:
+ pass
+ try:
+ from utils.hf_cache_settings import known_hf_hub_caches
+ for configured in known_hf_hub_caches():
+ _add(configured)
+ except Exception:
+ pass
+ if not roots:
+ return None
+
+ config_path = None
+ for root in roots:
+ try:
+ found = try_to_load_from_cache(
+ base_model,
+ "config.json",
+ cache_dir = root,
+ revision = revision,
+ )
+ except Exception:
+ continue
+ # A non-str is _CACHED_NO_EXIST ("we know it is absent here") or None ("unknown"),
+ # and neither rules the base out of a different root.
+ if isinstance(found, str):
+ config_path = found
+ break
+ if not isinstance(config_path, str):
+ return None
+ return _local_transformers_can_chat(Path(config_path).parent)
+
+
+def _local_path_can_chat(path: str | Path, base_model: Optional[str] = None) -> Optional[bool]:
+ """Classify a local checkpoint or its exact adapter base without network access."""
+ model_path = Path(path)
+ verdict = _local_transformers_can_chat(model_path)
+ if verdict is not None:
+ return verdict
+ adapter_config = _read_adapter_config(model_path)
+ adapter_base = _clean_optional_string(adapter_config.get("base_model_name_or_path"))
+ revision = _clean_optional_string(adapter_config.get("revision"))
+ base = adapter_base or _clean_optional_string(base_model)
+ # model_path is the adapter's snapshot, which names the cache root its base shares.
+ return _base_transformers_can_chat(base, revision, model_path) if base else None
+
+
def _capabilities_for_format(
model_format: ModelFormat,
source: str,
@@ -562,15 +667,19 @@ def _is_main_gguf_filename(name: str) -> bool:
)
-def _iter_gguf_paths(root: Path):
+def _iter_gguf_paths(root: Path, deadline: Optional[float] = None):
stack = [root]
while stack:
+ if deadline is not None and time.monotonic() >= deadline:
+ return
current = stack.pop()
try:
entries = list(current.iterdir())
except OSError:
continue
for path in entries:
+ if deadline is not None and time.monotonic() >= deadline:
+ return
try:
if path.is_dir() and not path.is_symlink():
stack.append(path)
diff --git a/studio/backend/hub/services/models/local_inventory.py b/studio/backend/hub/services/models/local_inventory.py
index eb2ce5f0b14..9f30f0dbcde 100644
--- a/studio/backend/hub/services/models/local_inventory.py
+++ b/studio/backend/hub/services/models/local_inventory.py
@@ -14,7 +14,6 @@ import os
from pathlib import Path
from typing import List, NamedTuple, Optional
-from fastapi import HTTPException
from loggers import get_logger
from hub.schemas.inventory import LocalModelInfo, LocalModelListResponse, ModelFormat
@@ -90,6 +89,12 @@ _is_main_gguf_filename = model_common._is_main_gguf_filename
_is_transformers_bin_weight_file = model_common._is_transformers_bin_weight_file
_prefer_complete_larger = model_common._prefer_complete_larger
_gguf_variant_state_summary = model_common._gguf_variant_state_summary
+_is_diffusers_pipeline_dir = model_common._is_diffusers_pipeline_dir
+
+
+def _http_error(status_code: int, detail: str):
+ from fastapi import HTTPException
+ return HTTPException(status_code = status_code, detail = detail)
def _is_immediate_model_weight_file(path: Path) -> bool:
@@ -122,31 +127,6 @@ def _has_immediate_model_weight(
return False
-def _is_diffusers_pipeline_dir(path: Path) -> bool:
- """True for a diffusers PIPELINE root: a top-level ``model_index.json`` with the weights in
- component subdirs (``transformer/``, ``vae/``, ``text_encoder/`` ...).
-
- Every image and video model downloaded as a pipeline has this shape and NO root
- ``config.json``, so the root-config-plus-loose-weights test below rejects it. Without this the
- Images and Video pickers cannot see a pipeline the user already has on disk, and the LM Studio
- publisher walk descends into it and offers its components (``vae``, ``transformer``, ...) as
- separate models, none of which any loader can start.
-
- Either index counts. A Modular Diffusers pipeline carries ``modular_model_index.json`` and no
- ``model_index.json``, which is the pair the video loader accepts, so recognising only the
- conventional one hid a valid local root from the picker and left the publisher walk to offer
- its components separately.
-
- ``routes.models._local_pipeline_index`` is the same test; the two scanners are separate
- modules, and only that one had it."""
- try:
- return (path / "model_index.json").is_file() or (
- path / "modular_model_index.json"
- ).is_file()
- except OSError:
- return False
-
-
def _has_immediate_model_signal(
path: Path, *, probe_limit: int = _MODEL_SIGNAL_PROBE_LIMIT
) -> bool:
@@ -932,7 +912,7 @@ async def _scan_local_models_response(
try:
models_root = _resolve_allowed_models_dir(models_dir, allowed_roots)
except ValueError:
- raise HTTPException(status_code = 403, detail = "Directory not allowed")
+ raise _http_error(status_code = 403, detail = "Directory not allowed")
try:
local_models = await _collect_models_from_default_sources(
@@ -955,7 +935,7 @@ async def _scan_local_models_response(
)
except Exception as e:
logger.error(f"Error listing local models: {e}", exc_info = True)
- raise HTTPException(
+ raise _http_error(
status_code = 500,
detail = f"Failed to list local models: {str(e)}",
)
@@ -970,9 +950,11 @@ async def list_local_models_response(models_dir: str = "./models") -> LocalModel
# for a response that is actually about to be served.
# Classification reads GGUF headers, so keep it off the event loop too.
try:
- from routes.models import _local_model_task
+ # Module-qualified for the same reason as _cached_row_task: binding the bare
+ # name re-points a load that resolved to routes.models before the move.
+ from hub.services.models import catalog_classification
models = [
- model.model_copy(update = {"task": _local_model_task(model)})
+ model.model_copy(update = {"task": catalog_classification._local_model_task(model)})
for model in response.models
]
return response.model_copy(update = {"models": models})
@@ -1039,12 +1021,12 @@ def get_models_folder_response() -> dict:
try:
path.mkdir(parents = True, exist_ok = True)
except OSError as e:
- raise HTTPException(
+ raise _http_error(
status_code = 500,
detail = f"Failed to create models folder: {path}: {e}",
) from e
if not path.is_dir():
- raise HTTPException(
+ raise _http_error(
status_code = 500,
detail = f"Models folder path is not a directory: {path}",
)
@@ -1063,7 +1045,7 @@ def add_scan_folder_response(path: str) -> dict:
folder, inserted = add_scan_folder_with_status(_coerce_scan_folder_path(path))
except ValueError as e:
logger.warning("Scan folder rejected: %s (path=%s)", e, path)
- raise HTTPException(status_code = 400, detail = str(e))
+ raise _http_error(status_code = 400, detail = str(e))
logger.info("Scan folder added: %s", folder.get("path"))
if inserted:
from core.inference.local_model_resolver import invalidate_index, warm_index_soon
diff --git a/studio/backend/hub/tests/test_model_services.py b/studio/backend/hub/tests/test_model_services.py
index 363e6b85209..2770bf57ef9 100644
--- a/studio/backend/hub/tests/test_model_services.py
+++ b/studio/backend/hub/tests/test_model_services.py
@@ -22,6 +22,7 @@ from hub.services import snapshot_progress
from hub.services.datasets import downloads as dataset_downloads
from hub.services.models import (
cache_inventory,
+ catalog_classification,
common as model_common,
deletion,
downloads,
@@ -913,10 +914,10 @@ def test_local_inventory_requests_share_scan(monkeypatch, change_kind):
response.model_copy = lambda update: SimpleNamespace(models = update["models"])
sources = local_inventory._local_inventory_sources()
monkeypatch.setattr(local_inventory, "_local_inventory_sources", lambda: sources)
- monkeypatch.setitem(
- sys.modules,
- "routes.models",
- SimpleNamespace(_local_model_task = lambda row: task_calls.append(row.id) or "task"),
+ monkeypatch.setattr(
+ catalog_classification,
+ "_local_model_task",
+ lambda row: task_calls.append(row.id) or "task",
)
async def scan(*_args):
@@ -1813,9 +1814,21 @@ def _diffusion_scan(monkeypatch, tmp_path, repo_id: str, files: list, *, task: s
"is_snapshot_partial",
lambda *_args, **_kwargs: False,
)
- monkeypatch.setattr(cache_inventory, "_cached_row_task", lambda _repo, gguf: task)
+ selected_snapshots = []
+
+ def row_task(
+ _repo,
+ *,
+ gguf,
+ selected = None,
+ ):
+ selected_snapshots.append(selected)
+ return task
+
+ monkeypatch.setattr(cache_inventory, "_cached_row_task", row_task)
rows = cache_inventory._scan_cached_models()
assert len(rows) == 1
+ assert selected_snapshots == [snapshot]
return rows[0]
@@ -4139,6 +4152,19 @@ def test_local_inventory_filters_custom_embedder_hf_cache_row(monkeypatch, tmp_p
assert [row.model_id for row in rows] == ["org/chat-model"]
+def test_qwen3_asr_gguf_name_hint_is_not_classified_as_chat(monkeypatch, tmp_path):
+ from hub.services.models import catalog_classification
+
+ asr = tmp_path / "Qwen3-ASR-0.6B-Q8_0.gguf"
+ chat = tmp_path / "Qwen3-0.6B-Q8_0.gguf"
+ asr.write_bytes(b"gguf")
+ chat.write_bytes(b"gguf")
+ monkeypatch.setattr(catalog_classification, "_gguf_architecture", lambda _path: "qwen3")
+
+ assert catalog_classification._gguf_path_task(asr) == "automatic-speech-recognition"
+ assert catalog_classification._gguf_path_task(chat) == "text-generation"
+
+
def test_local_inventory_filters_embedder_configured_by_snapshot_path(monkeypatch, tmp_path):
from core.rag import config as rag_config
@@ -7185,9 +7211,7 @@ def test_local_inventory_classifies_off_the_event_loop(monkeypatch):
async def no_folders():
return []
- monkeypatch.setitem(
- sys.modules, "routes.models", SimpleNamespace(_local_model_task = classify_row)
- )
+ monkeypatch.setattr(catalog_classification, "_local_model_task", classify_row)
monkeypatch.setattr(local_inventory, "_scan_local_models_response", scan)
monkeypatch.setattr(local_inventory, "_load_custom_folders", no_folders)
monkeypatch.setattr(local_inventory, "_local_inventory_sources", lambda: ("roots",))
@@ -7226,12 +7250,10 @@ def test_local_inventory_classifies_a_superseded_result_off_the_event_loop(monke
async def no_folders():
return []
- monkeypatch.setitem(
- sys.modules,
- "routes.models",
- SimpleNamespace(
- _local_model_task = lambda row: idents.append(threading.get_ident()) or "task"
- ),
+ monkeypatch.setattr(
+ catalog_classification,
+ "_local_model_task",
+ lambda row: idents.append(threading.get_ident()) or "task",
)
monkeypatch.setattr(local_inventory, "_scan_local_models_response", always_superseded)
monkeypatch.setattr(local_inventory, "_load_custom_folders", no_folders)
@@ -7276,9 +7298,7 @@ def test_local_inventory_retries_when_the_cache_changes_during_classification(mo
async def no_folders():
return []
- monkeypatch.setitem(
- sys.modules, "routes.models", SimpleNamespace(_local_model_task = classify_row)
- )
+ monkeypatch.setattr(catalog_classification, "_local_model_task", classify_row)
monkeypatch.setattr(local_inventory, "_scan_local_models_response", scan)
monkeypatch.setattr(local_inventory, "_load_custom_folders", no_folders)
monkeypatch.setattr(local_inventory, "_local_inventory_sources", lambda: ("roots",))
@@ -7292,3 +7312,130 @@ def test_local_inventory_retries_when_the_cache_changes_during_classification(mo
listed = asyncio.run(run())
assert scans == [0, 1], scans
assert [row.id for row in listed.models] == ["scan2"]
+
+
+def _gguf_with_architecture(path: Path, architecture: str) -> None:
+ """A minimal valid GGUF carrying just ``general.architecture``."""
+ import struct
+
+ def string(value: str) -> bytes:
+ data = value.encode()
+ return struct.pack("<Q", len(data)) + data
+
+ path.parent.mkdir(parents = True, exist_ok = True)
+ metadata = string("general.architecture") + struct.pack("<I", 8) + string(architecture)
+ path.write_bytes(struct.pack("<IIQQ", 0x46554747, 3, 0, 1) + metadata)
+
+
+def test_cached_gguf_task_describes_the_revision_the_load_id_resolves_to(tmp_path):
+ """A bare repo id loads through ``refs/main``, which is not always the newest payload
+ snapshot: a revision-pinned fetch adds a newer one without moving the ref. Classifying the
+ newest then advertised a task for a revision the load never reads, and the pickers filter
+ On Device rows on exactly that field."""
+ hub_cache = tmp_path / "hub"
+ repo_path = hub_cache / "models--Org--Model-GGUF"
+ older = repo_path / "snapshots" / "aaaaold"
+ newer = repo_path / "snapshots" / "bbbbnew"
+ _gguf_with_architecture(older / "model-Q4_K_M.gguf", "llama")
+ _gguf_with_architecture(newer / "model-Q4_K_M.gguf", "flux")
+ (repo_path / "refs").mkdir(parents = True, exist_ok = True)
+ (repo_path / "refs" / "main").write_text("aaaaold")
+ os.utime(older, (1_000_000, 1_000_000))
+ os.utime(newer, (2_000_000, 2_000_000))
+
+ def revision(snapshot: Path) -> SimpleNamespace:
+ gguf = snapshot / "model-Q4_K_M.gguf"
+ return SimpleNamespace(
+ snapshot_path = snapshot,
+ files = [
+ SimpleNamespace(
+ file_name = "model-Q4_K_M.gguf",
+ size_on_disk = 64,
+ file_path = gguf,
+ blob_path = gguf,
+ )
+ ],
+ refs = set(),
+ commit_hash = snapshot.name,
+ last_modified = 1.0,
+ size_on_disk = 64,
+ )
+
+ repo_info = SimpleNamespace(
+ repo_id = "Org/Model-GGUF",
+ repo_type = "model",
+ repo_path = repo_path,
+ revisions = [revision(older), revision(newer)],
+ size_on_disk = 128,
+ last_accessed = 2.0,
+ last_modified = 2.0,
+ nb_files = 2,
+ )
+
+ rows = cache_inventory._scan_cached_gguf(
+ cache_scans = [SimpleNamespace(repos = [repo_info])], active_hub_cache = hub_cache
+ )
+ row = next(row for row in rows if row["repo_id"] == "Org/Model-GGUF")
+ # The id resolves through refs/main to the llama revision, so the row must say so.
+ assert row["load_id"] == "Org/Model-GGUF"
+ assert row["task"] == "text-generation"
+
+
+def test_every_row_key_the_scanner_emits_survives_the_response_schema():
+ """``response_model`` silently DROPS any key the schema does not declare.
+
+ ``_scan_cached_models`` grew a ``diffusers`` flag, which is the only gate keeping an
+ untrusted or unrecognised pipeline out of a chat picker: such a repo carries no task, and
+ its pipeline root has no config for can_chat to read. Undeclared, the flag reached the CLI
+ (which reads the dict in-process) but never the browser, so the two disagreed about the
+ same row.
+
+ The watched set is an explicit list, not every key the scanner emits: the AST harvest
+ over-approximates, picking up internal bookkeeping from nested dict literals that was never
+ meant to leave the process. So a NEW picker-visible flag is not covered the day it lands --
+ add it here when you add it to the scanner.
+ """
+ import ast
+ import pathlib
+
+ from hub.schemas.inventory import CachedGgufRepo, CachedModelRepo
+
+ source = pathlib.Path(cache_inventory.__file__).read_text(encoding = "utf-8")
+ tree = ast.parse(source)
+
+ def literal_keys(function_name: str) -> set:
+ for node in ast.walk(tree):
+ if (
+ isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))
+ and node.name == function_name
+ ):
+ return {
+ key.value
+ for inner in ast.walk(node)
+ if isinstance(inner, ast.Dict)
+ for key in inner.keys
+ if isinstance(key, ast.Constant) and isinstance(key.value, str)
+ }
+ return set()
+
+ # Each scanner against ITS OWN schema. A union would let a key emitted on a model row pass
+ # because the GGUF schema happens to declare it, which is not what response_model does.
+ emitted = literal_keys("_cache_inventory_fields") | literal_keys("_scan_cached_models")
+ watched = ("diffusers", "companion", "single_file", "partial", "load_id", "task")
+ for flag in watched:
+ if flag in emitted:
+ assert flag in CachedModelRepo.model_fields, (
+ f"_scan_cached_models emits {flag!r} but CachedModelRepo does not declare it, so "
+ f"FastAPI's response_model strips it before the frontend sees the row."
+ )
+
+ # And prove it end to end rather than by field name alone: a declared-but-mistyped field is
+ # dropped or 500s at serialization time, which a model_fields check cannot see.
+ row = {
+ "repo_id": "Org/Pipeline",
+ "size_on_disk": 4096,
+ "last_modified": 1.0,
+ "diffusers": True,
+ }
+ assert CachedModelRepo(**row).model_dump()["diffusers"] is True
+ assert set(CachedGgufRepo.model_fields), "GGUF schema import is load-bearing above"
diff --git a/studio/backend/routes/models.py b/studio/backend/routes/models.py
index 6d6cd4036a9..98b477d24e5 100644
--- a/studio/backend/routes/models.py
+++ b/studio/backend/routes/models.py
@@ -21,6 +21,41 @@ from loggers import get_logger
# Dependency-light leaf (PEP 562 package init): no llama.cpp / torch import chain.
from core.inference.model_ids import display_model_name
+from hub.services.models import catalog_classification as _catalog_classification
+from hub.services.models.catalog_classification import (
+ _cached_repo_task,
+ _is_sd_cpp_companion_repo,
+ _local_model_task,
+ _repo_gguf_task,
+ _repo_has_pipeline_index,
+ _repo_is_diffusers,
+)
+
+# 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 loads reads as a botched hoist to verify_import_hoist.py.
+_AMBIGUOUS_DIFFUSION_GGUF_ARCHS = _catalog_classification._AMBIGUOUS_DIFFUSION_GGUF_ARCHS
+_DIFFUSION_GGUF_ARCHS = _catalog_classification._DIFFUSION_GGUF_ARCHS
+_TASK_CLASSIFY_WALK_SECONDS = _catalog_classification._TASK_CLASSIFY_WALK_SECONDS
+_UNSUPPORTED_DIFFUSION_GGUF_ARCHS = _catalog_classification._UNSUPPORTED_DIFFUSION_GGUF_ARCHS
+_UNSUPPORTED_DIFFUSION_TASK = _catalog_classification._UNSUPPORTED_DIFFUSION_TASK
+_SPEECH_GGUF_ARCHS = _catalog_classification._SPEECH_GGUF_ARCHS
+_SPEECH_TASK = _catalog_classification._SPEECH_TASK
+_VIDEO_GEN_TASK = _catalog_classification._VIDEO_GEN_TASK
+_VIDEO_GGUF_ARCHS = _catalog_classification._VIDEO_GGUF_ARCHS
+_arch_to_task = _catalog_classification._arch_to_task
+_gguf_architecture = _catalog_classification._gguf_architecture
+_gguf_folder_task = _catalog_classification._gguf_folder_task
+_hf_cache_snapshot_repo_id = _catalog_classification._hf_cache_snapshot_repo_id
+_is_trailing_split_shard = _catalog_classification._is_trailing_split_shard
+_local_family_needles = _catalog_classification._local_family_needles
+_local_is_diffusers = _catalog_classification._local_is_diffusers
+_local_model_can_chat = _catalog_classification._local_model_can_chat
+_task_classify_sort_key = _catalog_classification._task_classify_sort_key
+# core.inference.llama_cpp imports this one. Without the alias that import raises, and the
+# probe's `except Exception: return True` reads the raise as "the page can build it",
+# promising an MoE or familyless GGUF a load that dies in llama-server.
+_video_family_buildable = _catalog_classification._video_family_buildable
from utils.utils import canonical_model_repo_id, log_and_http_error
import re as _re
@@ -41,6 +76,16 @@ class CachedModelRepo(BaseModel):
# True for an sd.cpp companion mirror (VAE / text encoders, no denoiser). Declared here or
# response_model drops it and the flag never reaches the picker that has to filter on it.
companion: Optional[bool] = None
+ # Snapshot path for a copy its bare repo id cannot reach (legacy/default cache while
+ # another is active); undeclared, response_model drops it and the picker uses the active cache.
+ 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
+ # 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 backend can load it as a pipeline; an untrusted or unrecognised one has none.
+ diffusers: Optional[bool] = None
class CachedModelsResponse(BaseModel):
@@ -220,10 +265,6 @@ from models.responses import (
EmbeddingCheckResponse,
)
from utils.paths.path_utils import is_appledouble_metadata
-from utils.gguf_archs import (
- SPEECH_GGUF_ARCHS,
- is_speech_gguf_architecture,
-)
router = APIRouter()
logger = get_logger(__name__)
@@ -311,17 +352,8 @@ def _has_non_gguf_weights(path: Path) -> bool:
def _local_pipeline_index(d: Path) -> bool:
- """True when *d* is a diffusers PIPELINE root (a top-level index, weights in component
- subdirs), which ``_is_model_directory`` (root config + loose weights) rejects.
-
- Either index counts. A Modular Diffusers pipeline carries ``modular_model_index.json`` and no
- ``model_index.json``, and the video loader accepts exactly that pair, so recognising only the
- conventional one hid a valid local root from the picker and let the publisher walk descend
- into it and offer its components as separate, unusable models."""
- try:
- return (d / "model_index.json").is_file() or (d / "modular_model_index.json").is_file()
- except OSError:
- return False
+ from hub.services.models.common import _is_diffusers_pipeline_dir
+ return _is_diffusers_pipeline_dir(d)
def _servable_gguf_names(directory: Path) -> list[str]:
@@ -3807,25 +3839,22 @@ def _repo_id_will_not_resolve(repo_cache_dir: Path) -> bool:
return impl(repo_cache_dir)
-def _default_ref_offers_no_whole_quant(repo_cache_dir: Path) -> bool:
- """See hub.utils.inventory_scan; True when refs/main resolves onto a torn quant."""
- from hub.utils.inventory_scan import default_ref_offers_no_whole_quant as impl
- return impl(repo_cache_dir)
-
-
-def _gguf_copy_is_usable(repo_info, load_id: Optional[str]) -> bool:
+def _gguf_copy_is_usable(repo_info, load_id: Optional[str], active_root: Optional[Path]) -> bool:
"""Whether this copy of the repo holds a quant a load can reach.
- A pinned copy names a complete snapshot. An unpinned one is usable when its id resolves onto a
- whole quant, which is exactly what withheld the pin.
+ A pinned copy names a complete snapshot. An unpinned copy must be in the active cache and have
+ an id that resolves onto a whole quant, which is exactly what withheld the pin.
"""
if load_id:
return True
+ if active_root is None:
+ return False
try:
repo_path = Path(repo_info.repo_path)
- return not _repo_id_will_not_resolve(repo_path) and not _default_ref_offers_no_whole_quant(
- repo_path
- )
+ if repo_path.parent.resolve(strict = False) != active_root:
+ return False
+ ref_snapshot = _default_ref_snapshot(repo_path)
+ return ref_snapshot is not None and snapshot_has_complete_variants(str(ref_snapshot))
except (OSError, RuntimeError, ValueError):
return False
@@ -3968,16 +3997,8 @@ def _cached_gguf_row_has_vision(repo_info, load_id: Optional[str]) -> bool:
def _iter_gguf_paths(root: Path, deadline: Optional[float] = None):
- """GGUF files under ``root``. With a ``deadline`` (time.monotonic), gives up mid-walk:
- only .gguf files are yielded, so a large tree can walk for a long time yielding nothing,
- and a caller checking its budget per yield would never get to check it."""
- for path in root.rglob("*"):
- if deadline is not None and time.monotonic() >= deadline:
- return
- if path.is_file() and _is_gguf_filename(path.name):
- if is_appledouble_metadata(path):
- continue
- yield path
+ from hub.services.models.common import _iter_gguf_paths as iter_paths
+ yield from iter_paths(root, deadline)
def _repo_gguf_size_bytes(repo_info) -> int:
@@ -4047,513 +4068,6 @@ def _repo_gguf_last_modified(repo_info) -> float:
return latest
-# GGUF general.architecture values denoting a diffusion (image) model; lets the Images picker show only image GGUFs.
-_DIFFUSION_GGUF_ARCHS = frozenset(
- {
- # ONLY the families the diffusion backend can assemble. Other diffusion archs would pass this filter then 400 in validate_load.
- "flux", # flux.1
- "flux2", # flux.2-klein
- "qwen_image", # qwen-image
- "qwenimage",
- "z_image", # z-image
- "zimage",
- }
-)
-
-# Diffusion / image-video GGUF archs the backend can NOT assemble yet (LlamaCppBackend._DIFFUSION_ARCHES minus the loadable set).
-_UNSUPPORTED_DIFFUSION_GGUF_ARCHS = frozenset(
- {
- "sd1",
- "sd3",
- "sdxl",
- "aura",
- "hidream",
- "cosmos",
- "hyvid",
- }
-)
-
-# Archs shared by a buildable family and a non-buildable one. Z-Image's DiT is a Lumina2
-# derivative, so its GGUFs declare "lumina2"; these resolve from the repo/file name.
-_AMBIGUOUS_DIFFUSION_GGUF_ARCHS = frozenset({"lumina2"})
-
-# Literal placeholders gguf-connector writes into general.architecture for its diffusion
-# GGUFs. Mirrors LlamaCppBackend._PLACEHOLDER_ARCHES, which does the same normalisation on
-# the load side; the two must agree or a row is offered to chat and then refused by it.
-_PLACEHOLDER_DIFFUSION_GGUF_ARCHS = frozenset({"pig", "cow"})
-
-# Video GGUF archs the video backend CAN load (LTX-2.x ships as "ltxv", the Wan community GGUFs as "wan").
-_VIDEO_GGUF_ARCHS = frozenset({"ltxv", "wan"})
-_VIDEO_GEN_TASK = "text-to-video"
-
-# Task tag for the archs above; mirrored by the frontend NON_CHAT_TASKS gate.
-_UNSUPPORTED_DIFFUSION_TASK = "image-diffusion-unsupported"
-
-# TTS-only GGUF archs llama.cpp cannot load, tagged speech so the chat picker keeps them out of
-# llama-server. One shared definition rather than a copy per layer: the chat gate, this classifier
-# and the media preflight all have to agree.
-_SPEECH_GGUF_ARCHS = SPEECH_GGUF_ARCHS
-_SPEECH_TASK = "text-to-speech"
-
-
-# The two denoiser partitions, by the filename prefix the loader itself validates against
-# (``video_minimax_h3``). These GGUFs carry no architecture metadata, so the NAME is the only
-# evidence there is, and it is the same evidence the load path acts on.
-_H3_DENOISER_GGUF_PREFIXES = ("minimax_h3_fl2va", "minimax_h3_ref2va")
-
-
-def _is_h3_bundle_gguf_hint(hint: Optional[str]) -> bool:
- """True when a name hint names MiniMax-H3 GGUF weights (video, never chat).
-
- Either a known bundle repo id, or a validated denoiser FILENAME. The filename half matters
- for a GGUF the user copied into a custom local directory rather than leaving under one of the
- bundle ids: with no architecture metadata to fall back on, ``_local_model_task`` returned null
- and an otherwise loadable checkpoint was dropped from the Video On Device picker."""
- if not hint:
- return False
- name = str(hint).strip().lower().rsplit("/", 1)[-1].rsplit("\\", 1)[-1]
- if name.endswith(".gguf") and name.startswith(_H3_DENOISER_GGUF_PREFIXES):
- return True
- try:
- from hub.utils.gguf import is_h3_bundle_repo
- return is_h3_bundle_repo(hint)
- except Exception: # noqa: BLE001 -- never misclassify a model over a probe failure
- return False
-
-
-def _gguf_architecture(path: str) -> Optional[str]:
- """The GGUF ``general.architecture``, or None. Delegates to the shared,
- bounds-checked header reader (cached by path/mtime/size)."""
- from utils.models.gguf_metadata import read_gguf_architecture
- return read_gguf_architecture(path)
-
-
-def _gguf_family_buildable(name_hints: tuple[Optional[str], ...]) -> bool:
- """Whether an engine on THIS host can build the diffusion family a GGUF belongs to.
-
- The listing twin of the loader's gate, and the same predicate: ``validate_load_request`` refuses
- a family whose diffusers pipeline class this environment lacks (the newer families ship only in a
- newer diffusers, and packaging still allows an older one on Python 3.9) UNLESS the native sd.cpp
- engine would serve the GGUF, which needs no pipeline class at all. Advertising a row neither
- engine can build is a pick that can only fail; hiding one the native engine loads is the opposite
- mistake, on exactly the CPU/MPS hosts that engine exists for.
-
- Fails OPEN when no family resolves from the hints or the probe raises: the load path reports a
- real problem properly, and a listing must not hide a usable model over a detection miss."""
- try:
- from core.inference.diffusion_engine_router import family_buildable_here
- from core.inference.diffusion_families import detect_family_for_pick
- for hint in name_hints:
- if not hint:
- continue
- fam = detect_family_for_pick(hint)
- if fam is not None:
- return family_buildable_here(fam, model_kind = "gguf")
- except Exception: # noqa: BLE001 -- never hide a model over a probe failure
- return True
- return True
-
-
-def _video_family_buildable(fam) -> bool:
- """Whether the installed diffusers can build this video family's pipeline class.
-
- The video backend has no native engine, so it is the plain class check its own
- ``validate_load_request`` runs (``video.py`` -> ``assert_pipeline_class_available``): LTX-2 and
- the other newer pipelines exist only in a newer diffusers. Fails OPEN on any probe error."""
- try:
- from core.inference.diffusion_families import family_pipeline_available
- return family_pipeline_available(fam)
- except Exception: # noqa: BLE001 -- never hide a model over a probe failure
- return True
-
-
-def _arch_to_task(arch: Optional[str], name_hints: tuple[Optional[str], ...] = ()) -> Optional[str]:
- # MiniMax-H3's GGUFs carry NO metadata keys at all -- every file in the bundle, denoisers and
- # the Qwen conditioner alike, has kv_count 0, so general.architecture is absent where LTX-2 and
- # Wan GGUFs declare "ltxv"/"wan". The arch read therefore classifies the whole repo as unknown,
- # and an unknown task is dropped from the Video picker's On Device list while the chat picker
- # still offers the video DiT. Key the bundle repos by id instead, before the arch is consulted.
- if any(_is_h3_bundle_gguf_hint(hint) for hint in name_hints):
- return _VIDEO_GEN_TASK
- if arch is None:
- return None
- a = arch.lower()
- if a in _PLACEHOLDER_DIFFUSION_GGUF_ARCHS:
- # Not an architecture at all: gguf-connector writes these literals in place of one
- # (gguf-org/flux2-dev-gguf and calcuis/cosmos-predict2-gguf both declare "pig").
- # Being non-null they used to fall past every media branch to "text-generation", so
- # a diffusion GGUF was offered to chat and only refused at load. Only gguf-connector
- # writes them and only for diffusion GGUFs, so the row is never a chat model:
- # resolve the page by name, and stay unsupported when neither answers.
- from core.inference.video_families import detect_video_family
-
- for hint in name_hints:
- fam = detect_video_family(hint) if hint else None
- if fam is not None:
- if not getattr(fam, "is_moe", False) and _video_family_buildable(fam):
- return _VIDEO_GEN_TASK
- return _UNSUPPORTED_DIFFUSION_TASK
- # An image family has to RESOLVE, not merely fail open: _gguf_family_buildable is
- # permissive by design for a branch whose arch already says "image GGUF", and a
- # placeholder says nothing, so it would advertise Images for anything.
- from core.inference.diffusion_families import detect_family_for_pick
-
- if any(detect_family_for_pick(hint) is not None for hint in name_hints if hint):
- return (
- "text-to-image"
- if _gguf_family_buildable(name_hints)
- else _UNSUPPORTED_DIFFUSION_TASK
- )
- return _UNSUPPORTED_DIFFUSION_TASK
- if is_speech_gguf_architecture(a):
- return _SPEECH_TASK
- if a in _DIFFUSION_GGUF_ARCHS:
- # Third gate, mirroring the cached-repo picker: a family no engine here can build can only fail.
- if not _gguf_family_buildable(name_hints):
- return _UNSUPPORTED_DIFFUSION_TASK
- return "text-to-image"
- if a in _VIDEO_GGUF_ARCHS:
- # Advertise as loadable video only when a VideoFamily resolves. Some archs map straight
- # from the arch (ltxv); bare "wan" is ambiguous, so fall back to repo/file names.
- from core.inference.video_families import detect_video_family
-
- fam = detect_video_family("", override = a)
- if fam is None:
- for hint in name_hints:
- if hint:
- fam = detect_video_family(hint)
- if fam is not None:
- break
- if fam is not None and not getattr(fam, "is_moe", False) and _video_family_buildable(fam):
- return _VIDEO_GEN_TASK
- return _UNSUPPORTED_DIFFUSION_TASK
- if a in _AMBIGUOUS_DIFFUSION_GGUF_ARCHS:
- # Same as the video branch: the arch is shared, so let the loader's family detection decide.
- from core.inference.diffusion_engine_router import family_buildable_here
- from core.inference.diffusion_families import detect_family_for_pick, family_gguf_loadable
-
- for hint in name_hints:
- if not hint:
- continue
- fam = detect_family_for_pick(hint)
- if fam is not None:
- # Both gates: a GGUF-assemblable family AND an engine here that can build it.
- loadable = family_gguf_loadable(fam) and family_buildable_here(
- fam, model_kind = "gguf"
- )
- return "text-to-image" if loadable else _UNSUPPORTED_DIFFUSION_TASK
- return _UNSUPPORTED_DIFFUSION_TASK
- # A diffusion arch the backend cannot assemble: hide from chat and from Images (would 400).
- if a in _UNSUPPORTED_DIFFUSION_GGUF_ARCHS:
- return _UNSUPPORTED_DIFFUSION_TASK
- return "text-generation"
-
-
-# A media checkpoint outranks a text one in the same GGUF folder (see _gguf_folder_task), and is
-# ranked within the media answers too: _UNSUPPORTED_DIFFUSION_TASK hides the row from the chat
-# picker AND from the Images and Video ones, so a folder holding both a buildable denoiser and an
-# arch this backend cannot assemble has exactly one loadable answer, and returning the other on the
-# strength of where it sorts hides a model that works.
-_LOADABLE_MEDIA_GGUF_TASKS = frozenset({"text-to-image", _VIDEO_GEN_TASK})
-# Enough to reach the denoiser past a bundle's encoders, VAE and LoRAs. The guarantee is "the first
-# 64 in order decide", the same 64 on every host. A folder deep enough to hit this is a dump.
-_MAX_TASK_CLASSIFY_GGUFS = 64
-# Ordering costs first-wins' early exit, so bound the walk as _dir_has_downloaded_model and
-# _read_native_context_length already do. A scan folder is arbitrary (a network mount, or weights
-# beside a huge unrelated subtree rglob counts every entry of) and this runs once per listed row.
-# Past the budget the answer comes from what was reached, still at least what first-wins saw.
-_TASK_CLASSIFY_WALK_SECONDS = 0.75
-# The header reads get their own budget, started after the walk, so a slow walk cannot cut them
-# short at the encoder and hand back the answer this function exists to avoid.
-_TASK_CLASSIFY_READ_SECONDS = 1.5
-
-
-def _is_trailing_split_shard(name: str) -> bool:
- """True for shard 2..N of a split GGUF.
-
- ``gguf-split`` writes the whole KV block into shard 1 only, so a trailing shard carries no
- ``general.architecture`` at all: reading one can only fail, and a 51-shard repo would cost 51
- header reads to answer one question.
-
- False if the shared pattern cannot be imported, so a rename there costs the optimisation and
- nothing else: this runs inside the caller's blanket except, where an ImportError would come
- back as no classification for any folder."""
- try:
- from utils.models.model_config import _GGUF_SPLIT_FILE_RE
- except ImportError:
- return False
-
- match = _GGUF_SPLIT_FILE_RE.match(name)
- return match is not None and match.group("index") != "00001"
-
-
-def _task_classify_sort_key(root: Path, path: Path) -> tuple[str, str]:
- """Order a candidate by its path RELATIVE to the folder, in posix form.
-
- Ordering exists so the answer stops depending on the filesystem, so the key carries neither the
- mount point (what moving a Models folder changes) nor the separator: ``\\`` sorts against ``-``
- and ``.`` differently than ``/``, so an absolute-path key can order the same two files one way
- on Windows and the other on Linux. Lowercased so a case-insensitive filesystem agrees, exact
- form as tie-break to keep the order total."""
- try:
- rel = path.relative_to(root).as_posix()
- except ValueError:
- rel = path.name
- return (rel.lower(), rel)
-
-
-def _gguf_folder_task(
- root: Path,
- id_hints: tuple[Optional[str], ...],
- deadline: Optional[float] = None,
-) -> Optional[str]:
- """The task a folder of GGUFs classifies as, ordered and decided by the media file.
-
- Two bugs, one fix (#8406, #8407). The walk is ``rglob``, i.e. raw directory order, and the
- answer used to be whichever file it yielded first, so a folder classified differently on two
- machines and differently before and after a copy, which is what moving the Models folder makes.
- Sorting makes the answer a property of the contents, not of the filesystem.
-
- Decisive rather than first-wins because a media checkpoint does not ship alone: community
- bundles put the text encoder (t5 / clip / a qwen3 conditioner) beside the denoiser. Answering
- with the encoder tags a real image or video repo ``text-generation``, dropping it out of the
- Images picker and offering a DiT in the chat one. A text repo has no diffusion GGUF in it, so
- nothing gains a media task that did not already have one.
-
- Bounded on both halves so neither scales with the folder: ``deadline`` (time.monotonic,
- defaulted here) stops the walk, and candidates are trimmed to the cap as they are found."""
- if deadline is None:
- deadline = time.monotonic() + _TASK_CLASSIFY_WALK_SECONDS
- fallback: Optional[str] = None
- try:
- # Trimmed back to the cap as it fills: a folder holding thousands of GGUFs should not cost
- # a list of thousands of paths to read 64 of them.
- scored: list[tuple[tuple[str, str], Path]] = []
- # Recorded as the tail is dropped, never inferred from `scored` afterwards: the trimming
- # branch cuts back to the cap, so a folder that overflows and then ends leaves exactly
- # `_MAX_TASK_CLASSIFY_GGUFS` entries behind, indistinguishable from a folder that fit.
- # Reading that as a complete scan is what would let 129 files answer speech off their
- # first 64 and hide the runnable sibling in the discarded tail.
- overflowed = False
- for path in _iter_gguf_paths(root, deadline):
- name = path.name
- if _is_mmproj_filename(name) or _is_trailing_split_shard(name):
- continue
- scored.append((_task_classify_sort_key(root, path), path))
- if len(scored) > _MAX_TASK_CLASSIFY_GGUFS * 2:
- scored.sort(key = lambda item: item[0])
- del scored[_MAX_TASK_CLASSIFY_GGUFS:]
- overflowed = True
- scored.sort(key = lambda item: item[0])
- paths = [path for _, path in scored[:_MAX_TASK_CLASSIFY_GGUFS]]
- # Whether every candidate in the folder made it into `paths`. The walk gives up at its own
- # deadline and the cap drops the tail, so either can leave a sibling unseen.
- complete = (
- not overflowed
- and len(scored) <= _MAX_TASK_CLASSIFY_GGUFS
- and time.monotonic() < deadline
- )
- except Exception:
- return None
- unsupported: Optional[str] = None
- speech: Optional[str] = None
- read_deadline = time.monotonic() + _TASK_CLASSIFY_READ_SECONDS
- for index, path in enumerate(paths):
- # The first read always happens, so a folder still classifies from its first ordered file
- # even where the budget was gone before this loop started.
- if index and time.monotonic() >= read_deadline:
- complete = False
- break
- try:
- task = _arch_to_task(_gguf_architecture(str(path)), name_hints = id_hints + (path.name,))
- except Exception:
- # Unread, so unranked: this file might have been the runnable sibling, and speech
- # cannot rest on a folder we only partly read.
- complete = False
- continue
- if task is None:
- # Same as the read that raised: a truncated header gives no architecture, and
- # `_arch_to_task` answers None rather than guessing.
- complete = False
- continue
- if task in _LOADABLE_MEDIA_GGUF_TASKS:
- return task
- # Speech ranks below everything else runnable, not just below the loadable media archs:
- # nothing here runs a llama-csm GGUF, so answering speech while a sibling is loadable
- # hides that sibling. Ranking it with the unsupported diffusion archs saved a runnable
- # image/video checkpoint but not a chat one -- a chat GGUF lands in `fallback`, which
- # `unsupported` outranked, so a csm + qwen3 folder answered speech and the arch-task gate
- # hid the qwen3. Last resort only, so a speech-only folder still tags speech.
- if task == _SPEECH_TASK:
- if speech is None:
- speech = task
- elif task == _UNSUPPORTED_DIFFUSION_TASK:
- if unsupported is None:
- unsupported = task
- elif task is not None and fallback is None:
- fallback = task
- # Speech only when the ranking above saw the whole folder. It is the one answer that HIDES a
- # row rather than filing it, so a walk that gave up at its deadline, a folder past the cap, or
- # a read budget spent after the csm quant sorted first would otherwise hide the runnable
- # sibling it never reached. Every other verdict is safe on a partial read: the worst case is a
- # row filed on the wrong page, not one the user cannot find at all.
- return unsupported or fallback or (speech if complete else None)
-
-
-def _repo_gguf_task(repo_info) -> Optional[str]:
- """HF pipeline task of a cached GGUF repo, from its architecture:
- 'text-to-image' for a loadable diffusion arch, the non-loadable diffusion tag
- for a recognized-but-unsupported image arch, else 'text-generation' (None if
- unreadable)."""
- repo_id = getattr(repo_info, "repo_id", None)
- try:
- return _gguf_folder_task(Path(repo_info.repo_path), (repo_id,))
- except Exception:
- return None
-
-
-def _hf_cache_snapshot_repo_id(path: Optional[str]) -> Optional[str]:
- """``org/name`` when *path* IS a ``models--org--name/snapshots/<sha>`` root, else None.
-
- ``hf_cache_repo_id`` also answers for anything UNDER that directory, which is right for its own
- job and wrong for a needle: a pipeline's ``transformer``, ``vae`` and ``text_encoder`` dirs
- carry a ``config.json`` and weights, so a scan folder registers each as a row, and handing them
- the parent's repo id makes every one detect the family, satisfy ``_local_is_diffusers`` and
- enter the Images picker as a checkpoint that cannot load. Hence the shape must end at the
- snapshot; the decode itself is still the strict shared one."""
- if not path:
- return None
- parts = str(path).replace("\\", "/").rstrip("/").split("/")
- if len(parts) >= 3 and parts[-2] == "snapshots" and parts[-3].startswith("models--"):
- from core.inference.model_ids import hf_cache_repo_id
- return hf_cache_repo_id(path)
- return None
-
-
-def _local_family_needles(model: "LocalModelInfo") -> tuple[str, ...]:
- """Family-detection hints for a local (non-GGUF) checkpoint: model id, display name, leaf dir
- name, and -- for a bare single-file dir -- the sole checkpoint's filename (a generic folder
- holding one ``qwen-image-*.safetensors`` identifies its family only there, and the load route
- resolves it via ``resolve_local_single_file``). Only basenames, so a parent-dir token can't
- match -- with one exception, the encoded repo id below.
-
- A checkpoint still in HF cache layout carries its repo id in the ``models--org--name``
- directory, while every other needle degrades to the snapshot basename, a commit hash. That is
- a moved Models folder registered as a scan folder (#8407): a GGUF still classifies from its
- architecture, but a diffusers pipeline, proven to be one by its ``model_index.json``, had no
- name left and dropped out of the Images picker as task=null. The decode answers only for a real
- ``models--*/snapshots/*`` path AND only for the row that IS the snapshot, so it recovers the id
- that row lost without letting arbitrary parent-dir tokens match or component dirs inherit it.
- Last of the name needles, so the basenames still win."""
- needles = [model.model_id, model.display_name, Path(model.id).name]
- try:
- needles.append(
- _hf_cache_snapshot_repo_id(model.path) or _hf_cache_snapshot_repo_id(model.id)
- )
- except Exception:
- pass
- try:
- from core.inference.diffusion import resolve_local_single_file
- single = resolve_local_single_file(model.path)
- if single:
- needles.append(single)
- except Exception:
- pass
- return tuple(n for n in needles if n)
-
-
-def _local_model_task(model: "LocalModelInfo") -> Optional[str]:
- """Classify a local model into an HF pipeline task so the Images picker can filter.
-
- For a GGUF, read its architecture (the path may be the .gguf file itself or a folder
- containing one). For a local non-GGUF image checkpoint (a diffusers pipeline dir or a
- single-file safetensors), fall through to the diffusers detection so on-device image
- models get the 'text-to-image' tag instead of being dropped as task=null; the load
- path accepts these as a local pipeline."""
- path = model.path
- _id_hints = (model.model_id, model.display_name, model.id)
- if model.model_format == "gguf":
- try:
- p = Path(path)
- if p.suffix.lower() == ".gguf" and p.is_file():
- return _arch_to_task(_gguf_architecture(str(p)), name_hints = _id_hints + (p.name,))
- return _gguf_folder_task(p, _id_hints)
- except Exception:
- pass
- return None
- if _local_is_diffusers(model):
- # A local diffusers pipeline can be a VIDEO family, not just image; tag it text-to-video so it surfaces in the Video picker.
- try:
- from core.inference.video import _is_trusted_video_repo
- from core.inference.video_families import detect_video_family
- for needle in _local_family_needles(model):
- vfam = detect_video_family(needle)
- # Third gate: the video load asserts the family's pipeline class, and newer ones need newer diffusers.
- if vfam is not None and _is_trusted_video_repo(path):
- return _VIDEO_GEN_TASK if _video_family_buildable(vfam) else None
- except Exception:
- pass
- # The Images load path 400s AFTER eviction when no image family is supported, so tag only when detection succeeds.
- try:
- from core.inference.diffusion_engine_router import family_buildable_here
- from core.inference.diffusion_families import (
- detect_family,
- detect_family_by_pipeline_index,
- )
-
- # The saved pipeline class first: evidence out of the checkpoint, where every needle
- # below is a name, and a moved model's name is what does not survive (#8407). The
- # loader reads the index through the same helper, so anything shown on this evidence is
- # something validate_load_request accepts on it.
- for fam in (
- detect_family_by_pipeline_index(path),
- *(detect_family(needle) for needle in _local_family_needles(model)),
- ):
- if fam is not None:
- # A local non-GGUF checkpoint always loads through diffusers, so the pipeline class has to exist here.
- return (
- "text-to-image"
- if family_buildable_here(fam, model_kind = "pipeline")
- else None
- )
- return None
- except Exception:
- # Detection unavailable: fall back to the prior permissive tag rather than hiding a possibly-loadable pipeline.
- return "text-to-image"
- return None
-
-
-def _local_is_diffusers(model: "LocalModelInfo") -> bool:
- """True for a local diffusers image checkpoint, mirroring the cached-repo
- ``_repo_is_diffusers`` heuristics: a full pipeline carries a top-level
- ``model_index.json``, while single-file / safetensors image checkpoints ship none, so
- fall back to the model id resolving to a known diffusion family (the same resolver the
- Images backend loads from). Family detection uses _local_family_needles (id / name / sole
- checkpoint filename, not the on-disk path), so a parent-dir keyword can't spuriously match."""
- try:
- p = Path(model.path)
- if p.is_dir() and (p / "model_index.json").is_file():
- return True
- except Exception:
- pass
- try:
- from core.inference.diffusion_families import detect_family
- for needle in _local_family_needles(model):
- if detect_family(needle) is not None:
- return True
- except Exception:
- pass
- # A single-file VIDEO checkpoint (no model_index.json) is missed above but loaded as single_file by the video route, so surface it.
- try:
- from core.inference.video_families import detect_video_family
- for needle in _local_family_needles(model):
- if detect_video_family(needle) is not None:
- return True
- except Exception:
- pass
- return False
-
-
def snapshot_variants_all_complete(snapshot: str) -> bool:
"""Re-export; the predicate lives beside the completed-variant walk it uses."""
from hub.utils import inventory_scan
@@ -4577,13 +4091,10 @@ def _repo_gguf_load_id(repo_info, active_root: Optional[Path]) -> Optional[str]:
if repo_path is None or active_root is None:
return None
try:
- # A recovered repo's refs/main names nothing, so its id resolves nowhere and needs a pin.
- if (
- repo_path.parent.resolve(strict = False) == active_root
- and not _repo_id_will_not_resolve(repo_path)
- and not _default_ref_offers_no_whole_quant(repo_path)
- ):
- return None
+ if repo_path.parent.resolve(strict = False) == active_root:
+ ref_snapshot = _default_ref_snapshot(repo_path)
+ if ref_snapshot is not None and snapshot_has_complete_variants(str(ref_snapshot)):
+ return None
except (OSError, RuntimeError, ValueError):
pass
# Shared selection key, so this route and the /gguf-variants lister name one snapshot.
@@ -4628,283 +4139,385 @@ def _preferred_gguf_copy(
async def list_cached_gguf(current_subject: str = Depends(get_current_subject)):
"""List GGUF repos downloaded to HF cache, legacy Unsloth cache, and HF default cache."""
try:
- cache_scans = _all_hf_cache_scans()
- try:
- active_root = _resolve_hf_cache_dir().resolve(strict = False)
- except Exception:
- active_root = None
-
- seen_lower: dict[str, dict] = {}
- # How each kept row's copy ranks, since the compatibility schema carries neither field.
- seen_rank: dict[str, tuple[bool, bool]] = {}
- for hf_cache in cache_scans:
- for repo_info in hf_cache.repos:
- try:
- if repo_info.repo_type != "model":
- continue
- repo_id = repo_info.repo_id
- # Pass the snapshot path too so the config check also hides custom Whisper checkpoints.
- if _is_hidden_model(repo_id, str(repo_info.repo_path)):
- continue
- total_size = _repo_gguf_size_bytes(repo_info)
- if total_size == 0:
- continue
- key = repo_id.lower()
- existing = seen_lower.get(key)
- last_modified = _repo_gguf_last_modified(repo_info)
- load_id = _repo_gguf_load_id(repo_info, active_root)
- rank = (
- _gguf_copy_is_usable(repo_info, load_id),
- active_root is not None
- and Path(repo_info.repo_path).parent.resolve(strict = False) == active_root,
- )
- if _preferred_gguf_copy(seen_lower, seen_rank, key, rank, total_size):
- row = {
- "repo_id": repo_id,
- "size_bytes": total_size,
- "cache_path": str(repo_info.repo_path),
- "has_vision": _cached_gguf_row_has_vision(repo_info, load_id),
- "task": _repo_gguf_task(repo_info),
- }
- if load_id:
- row["load_id"] = load_id
- # Keep the newest timestamp across duplicate caches; absent rows sort as oldest.
- lm = max(last_modified, (existing or {}).get("last_modified", 0.0))
- if lm > 0:
- row["last_modified"] = lm
- seen_lower[key] = row
- seen_rank[key] = rank
- elif last_modified > existing.get("last_modified", 0.0):
- existing["last_modified"] = last_modified
- except Exception as e:
- repo_label = getattr(repo_info, "repo_id", "<unknown>")
- logger.warning(f"Skipping cached GGUF repo {repo_label}: {e}")
- continue
- # Newest download first; stable repo_id tie-break for equal/missing mtimes.
- cached = sorted(
- seen_lower.values(),
- key = lambda c: (-(c.get("last_modified") or 0.0), c["repo_id"].lower()),
- )
- return {"cached": cached}
+ return {"cached": cached_gguf_rows()}
except Exception as e:
logger.error(f"Error listing cached GGUF repos: {e}", exc_info = True)
return {"cached": []}
-def _repo_has_pipeline_index(repo_info) -> bool:
- """Root-model_index.json check. Shared with the hub inventory scan, which classifies the
- same repos for the same pickers; see :func:`hub.utils.inventory_scan.repo_has_pipeline_index`."""
- from hub.utils import inventory_scan as hf_cache_scan
- return hf_cache_scan.repo_has_pipeline_index(repo_info)
-
-
-def _repo_is_diffusers(repo_info) -> bool:
- """True for an image-diffusion repo, so the chat picker hides it (it renders
- images, not chat) and the Images picker claims it — mirroring how cached
- diffusion GGUFs are classified by arch.
-
- Two signals: a full diffusers pipeline carries a top-level model_index.json,
- while single-file / ComfyUI / ControlNet image checkpoints (e.g. an FP8
- Qwen-Image or a z-image .safetensors) ship none. For those, fall back to the
- repo id resolving to a known diffusion family — the same resolver the Images
- backend loads from — so they don't surface as loadable chat models."""
- if _repo_has_pipeline_index(repo_info):
- return True
+def cached_gguf_rows(cache_scans = None) -> list[dict]:
+ if cache_scans is None:
+ cache_scans = _all_hf_cache_scans()
try:
- from core.inference.diffusion_families import detect_family
- if detect_family(getattr(repo_info, "repo_id", "") or "") is not None:
- return True
+ active_root = _resolve_hf_cache_dir().resolve(strict = False)
except Exception:
- pass
- return False
+ active_root = None
+
+ seen_lower: dict[str, dict] = {}
+ # keep active-cache rank beside rows; the compatibility schema only exposes partialness.
+ seen_rank: dict[str, tuple[bool, bool]] = {}
+ for hf_cache in cache_scans:
+ for repo_info in hf_cache.repos:
+ try:
+ if repo_info.repo_type != "model":
+ continue
+ repo_id = repo_info.repo_id
+ # Pass the snapshot path too so the config check also hides custom Whisper checkpoints.
+ if _is_hidden_model(repo_id, str(repo_info.repo_path)):
+ continue
+ total_size = _repo_gguf_size_bytes(repo_info)
+ if total_size == 0:
+ continue
+ key = repo_id.lower()
+ existing = seen_lower.get(key)
+ last_modified = _repo_gguf_last_modified(repo_info)
+ load_id = _repo_gguf_load_id(repo_info, active_root)
+ selected = (
+ Path(load_id) if load_id else _default_ref_snapshot(Path(repo_info.repo_path))
+ )
+ rank = (
+ _gguf_copy_is_usable(repo_info, load_id, active_root),
+ active_root is not None
+ and Path(repo_info.repo_path).parent.resolve(strict = False) == active_root,
+ )
+ if _preferred_gguf_copy(seen_lower, seen_rank, key, rank, total_size):
+ row = {
+ "repo_id": repo_id,
+ "size_bytes": total_size,
+ "cache_path": str(repo_info.repo_path),
+ "has_vision": _cached_gguf_row_has_vision(repo_info, load_id),
+ "task": _repo_gguf_task(repo_info, selected),
+ }
+ if load_id:
+ row["load_id"] = load_id
+ if not rank[0]:
+ row["partial"] = True
+ # Keep the newest timestamp across duplicate caches; absent rows sort as oldest.
+ lm = max(last_modified, (existing or {}).get("last_modified", 0.0))
+ if lm > 0:
+ row["last_modified"] = lm
+ seen_lower[key] = row
+ seen_rank[key] = rank
+ elif last_modified > existing.get("last_modified", 0.0):
+ existing["last_modified"] = last_modified
+ except Exception as e:
+ repo_label = getattr(repo_info, "repo_id", "<unknown>")
+ logger.warning(f"Skipping cached GGUF repo {repo_label}: {e}")
+ continue
+ # Newest download first; stable repo_id tie-break for equal/missing mtimes.
+ return sorted(
+ seen_lower.values(),
+ key = lambda c: (-(c.get("last_modified") or 0.0), c["repo_id"].lower()),
+ )
-def _repo_pipeline_missing_denoiser(repo_info) -> bool:
- """Companion-only-prefetch check (pipeline manifest present, denoiser weights absent). Shared
- with the hub inventory scan so both listings agree on which rows are really on-device; see
- :func:`hub.utils.inventory_scan.repo_pipeline_missing_denoiser`."""
+def _repo_pipeline_missing_denoiser(repo_info, selected: Optional[Path] = None) -> bool:
+ """Companion-only-prefetch check for the snapshot this row loads."""
from hub.utils import inventory_scan as hf_cache_scan
+
+ if selected is not None:
+ return hf_cache_scan.snapshot_pipeline_missing_denoiser(selected)
return hf_cache_scan.repo_pipeline_missing_denoiser(repo_info)
-def _cached_repo_partial(repo_id: str, repo_cache_dir: Optional[Path] = None) -> bool:
+def _cached_repo_partial(
+ repo_id: str,
+ repo_cache_dir: Optional[Path] = None,
+ snapshot_dir: Optional[Path] = None,
+) -> bool:
"""Whether the cached model snapshot is incomplete (cancelled/partial download).
Reuses the hub inventory scan's snapshot-partial detector (cancel marker, legacy
- .incomplete blob, manifest walk -- cheapest first). ``repo_cache_dir`` scopes all three
- signals to the specific snapshot being listed: without it the scan spans every HF cache
- root, so a stale .incomplete copy in one root would flag a complete copy in another as
- partial and hide it from the picker (the sibling inventory paths all scope the same way).
+ .incomplete blob, manifest walk -- cheapest first). ``repo_cache_dir`` scopes the cache copy;
+ ``snapshot_dir`` attributes repo-wide signals to the selected revision. Without both, an
+ interrupted newer revision can flag a complete pinned revision as partial and hide it from the
+ picker.
Best-effort: a detection error reports not-partial so a scan glitch never hides a
genuinely usable repo."""
try:
from hub.utils.inventory_scan import is_snapshot_partial
- return bool(is_snapshot_partial("model", repo_id, repo_cache_dir))
+ return bool(is_snapshot_partial("model", repo_id, repo_cache_dir, snapshot_dir))
except Exception: # noqa: BLE001 -- never fail the listing over a partial probe
return False
-def _is_sd_cpp_companion_repo(repo_id: str) -> bool:
- """True for a mirror that holds only sd.cpp companions (VAE / text encoders, no denoiser)."""
[email protected]("/cached-models", response_model = CachedModelsResponse)
+async def list_cached_models(
+ current_subject: str = Depends(get_current_subject),
+ hf_token: Optional[str] = Depends(get_hf_token),
+):
+ """List non-GGUF model repos downloaded to HF cache, legacy Unsloth cache, and HF default cache."""
try:
- from core.inference.diffusion_families import sd_cpp_companion_only_repo_ids
- return (repo_id or "").strip().lower() in sd_cpp_companion_only_repo_ids()
- except Exception: # noqa: BLE001 -- an import failure must not hide a usable repo
- return False
+ return {"cached": cached_model_rows()}
+ except Exception as e:
+ logger.error(f"Error listing cached models: {e}", exc_info = True)
+ return {"cached": []}
-def _cached_repo_task(repo_info) -> Optional[str]:
- """Pipeline task for a cached non-GGUF repo: 'text-to-video' for repos the
- video backend can load as full pipelines (its trust list / family detector),
- else 'text-to-image' for diffusers image repos, else None (chat). Without the
- video tag, cached Lightricks / Wan / Hunyuan pipelines never surfaced in the
- Video picker's On Device list -- everything diffusers was blanket-tagged
- text-to-image."""
- repo_id = getattr(repo_info, "repo_id", "") or ""
- try:
- from core.inference.video import _is_trusted_video_repo
- from core.inference.video_families import detect_video_family
-
- # Both gates: a detected video family (so image repos don't match) AND the load path's trust
- # rule. Third gate: the video load asserts the family's pipeline class (needs newer diffusers).
- video_fam = detect_video_family(repo_id)
- if video_fam is not None:
- if not _is_trusted_video_repo(repo_id) or not _video_family_buildable(video_fam):
- return None
- return _VIDEO_GEN_TASK
- except Exception:
- pass
- if not _repo_is_diffusers(repo_info):
- return None
- # BOTH gates, mirroring the video branch: trust rule AND a detected image family. A
- # model_index.json only proves it is a diffusers pipeline; newer families need diffusers 0.39.
- try:
- from core.inference.diffusion import _is_trusted_diffusion_repo
- from core.inference.diffusion_families import (
- detect_family,
- family_pipeline_available,
+# Row gate only. Broader than the pin's test below on purpose: a legacy diffusers pipeline
+# ships diffusion_pytorch_model.bin, which no weight-prefix rule accepts, but Images lists it.
+_NON_GGUF_WEIGHT_EXTENSIONS = (".safetensors", ".bin")
+
+
+def _snapshot_can_serve_a_load(snapshot: Path) -> bool:
+ """Whether this snapshot has metadata and a complete weight payload.
+
+ Transformers snapshots use the local scanners' config-plus-weight check. Diffusers
+ pipelines instead have a root ``model_index.json`` and component payloads in subdirs,
+ so use the same component-completeness check that guards local media loads.
+
+ huggingface_hub keeps one snapshot per commit, so a partial fetch leaves an unloadable
+ dir with a newer mtime than the complete one beside it. Both halves happen: metadata
+ only (AutoConfig/AutoTokenizer at a newer revision) and weights only (Unsloth's base
+ model pre-warm fetches the shards plus index, no config.json).
+ """
+ if _local_pipeline_index(snapshot):
+ from core.inference.media_locality import _pipeline_components_present
+ from hub.utils.inventory_scan import snapshot_pipeline_missing_denoiser
+ return _pipeline_components_present(snapshot) and not snapshot_pipeline_missing_denoiser(
+ snapshot
)
+ return _is_model_directory(snapshot) and not _snapshot_payload_is_torn(snapshot)
- # An sd.cpp companion repo holds no denoiser, so it is never a pick even though its
- # unsloth/* mirror clears the trust gate below (the third-party ids never did). No task
- # keeps it out of the IMAGE picker; the row's companion flag is what keeps it out of the
- # chat one, since a task of None is what every unclassified chat repo carries.
- if _is_sd_cpp_companion_repo(repo_id):
- return None
- fam = detect_family(repo_id)
- if not _is_trusted_diffusion_repo(repo_id) or fam is None:
- return None
- if not family_pipeline_available(fam):
- return None
- return "text-to-image"
- except Exception: # noqa: BLE001 -- an import failure must not hide a usable repo
- return "text-to-image"
+def _snapshot_payload_is_torn(snapshot: Optional[Path]) -> bool:
+ """See hub.utils.inventory_scan; True when the snapshot proves its payload incomplete."""
+ from hub.utils.inventory_scan import _snapshot_cannot_serve_its_payload
+ return _snapshot_cannot_serve_its_payload(snapshot)
+
+
+def _default_ref_snapshot(repo_cache_dir: Path) -> Optional[Path]:
+ """See hub.utils.inventory_scan; the snapshot dir ``refs/main`` names, or ``None``."""
+ from hub.utils.inventory_scan import default_ref_snapshot
+ return default_ref_snapshot(repo_cache_dir)
[email protected]("/cached-models", response_model = CachedModelsResponse)
-async def list_cached_models(
- current_subject: str = Depends(get_current_subject),
- hf_token: Optional[str] = Depends(get_hf_token),
-):
- """List non-GGUF model repos downloaded to HF cache, legacy Unsloth cache, and HF default cache."""
- _WEIGHT_EXTENSIONS = (".safetensors", ".bin")
- hf_token = _normalize_hf_token(hf_token)
+def _repo_model_snapshots(repo_info) -> list:
+ """Snapshot dirs of a cached non-GGUF repo, newest selection order first."""
+ from hub.utils.hf_cache_state import snapshot_selection_key
+
+ candidates = [
+ Path(snapshot)
+ for revision in getattr(repo_info, "revisions", ()) or ()
+ if (snapshot := getattr(revision, "snapshot_path", None)) is not None
+ ]
+ candidates.sort(key = snapshot_selection_key, reverse = True)
+ return candidates
+
+
+def _repo_is_reachable_by_id(repo_path: Path, active_root: Path, loadable: Optional[Path]) -> bool:
+ """Whether loading this repo by its bare id lands somewhere that can serve it.
+
+ Only the active cache makes the id a target, and there ``from_pretrained`` follows
+ ``refs/main``: ``repo_id_will_not_resolve`` catches a ref naming no directory, but a
+ ref naming an EXISTING half-fetched snapshot resolves fine and then fails. This is the
+ non-GGUF twin of ``default_ref_offers_no_whole_quant``. An unreadable ref, or a repo
+ with no better sibling, keeps the id it had.
+ """
try:
- cache_scans = _all_hf_cache_scans()
+ if repo_path.parent.resolve(strict = False) != active_root:
+ return False
+ if _repo_id_will_not_resolve(repo_path):
+ return False
+ except (OSError, RuntimeError, ValueError):
+ return False
+ if loadable is None:
+ return True
+ # No refs/main at all is not "fine", it is unresolvable: huggingface_hub writes
+ # refs/<revision> only when revision != commit_hash, so a commit-pinned fetch writes
+ # none and a tag-pinned one writes refs/<tag>. Offline the bare id then finds nothing.
+ ref_snapshot = _default_ref_snapshot(repo_path)
+ return ref_snapshot is not None and _snapshot_can_serve_a_load(ref_snapshot)
+
+
+def _repo_model_selection(
+ repo_info, active_root: Optional[Path]
+) -> tuple[Optional[Path], Optional[str]]:
+ """The snapshot a load of this repo will read, and the load id pinning it.
+
+ One choice of revision, so every field describing the pick answers for the SAME copy.
+ Scanning history instead lets an old revision speak for the row: a repo pushed first as
+ a LoRA and later merged into the same id (``push_to_hub_merged``) keeps its stale
+ ``adapter_config.json``, and a whole-model row read as an adapter is dropped from the
+ chat picker. ``load_id`` is ``None`` when the bare id already reaches a serving copy.
+ """
+ repo_path = getattr(repo_info, "repo_path", None)
+ if repo_path is None or active_root is None:
+ return None, None
+ usable = []
+ for snapshot in _repo_model_snapshots(repo_info):
try:
- active_root = _resolve_hf_cache_dir().resolve(strict = False)
- except Exception:
- active_root = None
+ if snapshot.is_dir():
+ usable.append(snapshot)
+ except OSError:
+ continue
+ # Newest snapshot a load can actually be served from: the row is listed because SOME
+ # revision carries weights, but the newest dir can be a half-fetched partial.
+ loadable = next((s for s in usable if _snapshot_can_serve_a_load(s)), None)
+ if _repo_is_reachable_by_id(Path(repo_path), active_root, loadable):
+ # The bare id follows refs/main, so that ref names the revision a load reads.
+ return _default_ref_snapshot(Path(repo_path)) or loadable, None
+ # no snapshot can prove it serves a load, so keep the previous newest-dir pin rather than
+ # drop it.
+ selected = loadable or (usable[0] if usable else None)
+ return selected, (str(selected) if selected else None)
+
+
+def _repo_model_load_id(repo_info, active_root: Optional[Path]) -> Optional[str]:
+ """Snapshot dir to load a non-GGUF repo by, or ``None`` when the bare id already works.
+
+ The non-GGUF twin of ``_repo_gguf_load_id``: a repo cached only in the legacy or
+ default cache otherwise reads as its bare id, which ``ModelConfig`` resolves through
+ the active cache instead, so offline the pick cannot load and online it re-downloads.
+ """
+ return _repo_model_selection(repo_info, active_root)[1]
- seen_lower: dict[str, dict] = {}
- # Repos whose active-cache copy cannot be loaded by id; this schema carries no path.
- unusable_active: set[str] = set()
- for hf_cache in cache_scans:
- for repo_info in hf_cache.repos:
- try:
- if repo_info.repo_type != "model":
- continue
- repo_id = repo_info.repo_id
- # Pass the snapshot path too so the config check also hides custom Whisper checkpoints.
- if _is_hidden_model(repo_id, str(repo_info.repo_path)):
- continue
- # No partial or load id here, so a snapshot-path-only repo would read as ready.
- if _recovered_repo_is_unusable_by_repo_id(repo_info):
- try:
- if (
- active_root is not None
- and Path(repo_info.repo_path).parent.resolve(strict = False)
- == active_root
- ):
- unusable_active.add(repo_id.lower())
- except (OSError, RuntimeError, ValueError):
- pass
- continue
- if _repo_has_gguf_files(repo_info):
- continue
- total_size = sum(
- (f.size_on_disk or 0) for rev in repo_info.revisions for f in rev.files
- )
- if total_size == 0:
- continue
- weight_files = [
- f
- for f in _cached_files(repo_info)
- if f.file_name.endswith(_WEIGHT_EXTENSIONS)
- ]
- if not weight_files:
- continue
- last_modified = max(
- (_blob_mtime(f) for f in weight_files),
- default = 0.0,
- )
- key = repo_id.lower()
- existing = seen_lower.get(key)
- # A companion-only prefetch (manifest + VAE/TE but no transformer shards) is not a loadable pipeline; treat it as partial.
- is_partial = _cached_repo_partial(
- repo_id, Path(repo_info.repo_path)
- ) or _repo_pipeline_missing_denoiser(repo_info)
- # Prefer the most COMPLETE snapshot, then largest: a partial copy in one cache root must not shadow a complete copy in another.
- if existing is None or (not is_partial, total_size) > (
- not bool(existing.get("partial")),
- existing["size_bytes"],
+
+def _repo_model_format(repo_info, selected: Optional[Path] = None) -> Optional[str]:
+ """``"adapter"`` for a cached LoRA/PEFT repo, else ``None``.
+
+ ``cached_model_rows`` set no format, so every consumer filtering out adapters compared
+ against a key that never existed. An adapter ships ``adapter_config.json``; a merge does not.
+ Judged on the selected revision; only when none is determinable does history stand in.
+ """
+ for snapshot in [selected] if selected is not None else _repo_model_snapshots(repo_info):
+ try:
+ if (snapshot / "adapter_config.json").is_file():
+ return "adapter"
+ except OSError:
+ continue
+ return None
+
+
+def _repo_model_can_chat(repo_info, selected: Optional[Path] = None) -> Optional[bool]:
+ """``False`` for a cached encoder-only repo (embedding, CLIP, ViT), else ``None``.
+
+ The classification the hub inventory already applies to its own rows. ``task`` is
+ ``None`` for everything not diffusion, so a cached BERT or CLIP otherwise read as an
+ ordinary chat model. ``None`` when nothing is conclusive, so unknowns are never hidden.
+
+ The selected revision answers first, so capability describes the copy the pin will
+ load rather than whichever snapshot sorts newest. Other snapshots stand in only when
+ the selection has no readable config, such as a weights-only snapshot.
+ """
+ from hub.services.models.common import _local_transformers_can_chat, _read_local_json_object
+
+ ordered = _repo_model_snapshots(repo_info)
+ if selected is not None:
+ verdict = _local_transformers_can_chat(selected)
+ if verdict is not None or _read_local_json_object(selected / "config.json"):
+ return verdict
+ ordered = [s for s in ordered if s != selected]
+ for snapshot in ordered:
+ verdict = _local_transformers_can_chat(snapshot)
+ if verdict is not None:
+ return verdict
+ return None
+
+
+def cached_model_rows(cache_scans = None) -> list[dict]:
+ _WEIGHT_EXTENSIONS = _NON_GGUF_WEIGHT_EXTENSIONS
+ if cache_scans is None:
+ cache_scans = _all_hf_cache_scans()
+ try:
+ active_root = _resolve_hf_cache_dir().resolve(strict = False)
+ except Exception:
+ active_root = None
+
+ seen_lower: dict[str, dict] = {}
+ for hf_cache in cache_scans:
+ for repo_info in hf_cache.repos:
+ try:
+ if repo_info.repo_type != "model":
+ continue
+ repo_id = repo_info.repo_id
+ # Pass the snapshot path too so the config check also hides custom Whisper checkpoints.
+ if _is_hidden_model(repo_id, str(repo_info.repo_path)):
+ continue
+ if _repo_has_gguf_files(repo_info):
+ continue
+ selected, model_load_id = _repo_model_selection(repo_info, active_root)
+ if _recovered_repo_is_unusable_by_repo_id(repo_info):
+ # That guard withheld these because this schema could describe neither a
+ # partial nor a path; it now carries load_id, so a recovery holding a
+ # snapshot that serves a load is listed pinned to it instead of dropped.
+ if not (
+ model_load_id is not None
+ and selected is not None
+ and _snapshot_can_serve_a_load(selected)
):
- row = {
- "repo_id": repo_id,
- "size_bytes": total_size,
- "task": _cached_repo_task(repo_info),
- }
- if is_partial:
- row["partial"] = True
- # Listed, so tens of GB of companion weights stay visible and deletable,
- # but flagged, so no picker offers a denoiser-less repo as a load.
- if _is_sd_cpp_companion_repo(repo_id):
- row["companion"] = True
- # Flag diffusion repos with no pipeline index: loadable only via from_single_file, so pickers must not offer a pipeline load.
- if row["task"] is not None and not _repo_has_pipeline_index(repo_info):
- row["single_file"] = True
- # Keep the newest timestamp across duplicate caches; absent rows sort as oldest.
- lm = max(last_modified, (existing or {}).get("last_modified", 0.0))
- if lm > 0:
- row["last_modified"] = lm
- seen_lower[key] = row
- elif last_modified > existing.get("last_modified", 0.0):
- existing["last_modified"] = last_modified
- except Exception as e:
- repo_label = getattr(repo_info, "repo_id", "<unknown>")
- logger.warning(f"Skipping cached model repo {repo_label}: {e}")
+ continue
+ total_size = sum(
+ (f.size_on_disk or 0) for rev in repo_info.revisions for f in rev.files
+ )
+ if total_size == 0:
+ continue
+ weight_files = [
+ f for f in _cached_files(repo_info) if f.file_name.endswith(_WEIGHT_EXTENSIONS)
+ ]
+ if not weight_files:
continue
+ last_modified = max(
+ (_blob_mtime(f) for f in weight_files),
+ default = 0.0,
+ )
+ key = repo_id.lower()
+ existing = seen_lower.get(key)
+ # A companion-only prefetch (manifest + VAE/TE but no transformer shards) is not a loadable pipeline; treat it as partial.
+ is_partial = _cached_repo_partial(
+ repo_id, Path(repo_info.repo_path), selected
+ ) or _repo_pipeline_missing_denoiser(repo_info, selected)
+ # Prefer the most COMPLETE snapshot, then largest: a partial copy in one cache root must not shadow a complete copy in another.
+ if existing is None or (not is_partial, total_size) > (
+ not bool(existing.get("partial")),
+ existing["size_bytes"],
+ ):
+ row_task = _cached_repo_task(repo_info, selected)
+ is_diffusers = _repo_is_diffusers(repo_info, selected)
+ has_pipeline_index = _repo_has_pipeline_index(repo_info, selected)
+ row = {
+ "repo_id": repo_id,
+ "size_bytes": total_size,
+ "task": row_task,
+ }
+ # Pin a copy its bare id cannot reach, so the pick loads the found snapshot.
+ if model_load_id:
+ row["load_id"] = model_load_id
+ model_format = _repo_model_format(repo_info, selected)
+ if model_format:
+ row["model_format"] = model_format
+ # Without this the picker offers an embedding or CLIP repo as a chat model.
+ if _repo_model_can_chat(repo_info, selected) is False:
+ row["can_chat"] = False
+ # task stays None for a diffusion repo this backend cannot load as a
+ # pipeline, and None is what every chat repo carries, so say it plainly.
+ if is_diffusers:
+ row["diffusers"] = True
+ if is_partial:
+ row["partial"] = True
+ # Listed, so tens of GB of companion weights stay visible and deletable,
+ # but flagged, so no picker offers a denoiser-less repo as a load.
+ if _is_sd_cpp_companion_repo(repo_id):
+ row["companion"] = True
+ # Flag diffusion repos with no pipeline index: loadable only via from_single_file, so pickers must not offer a pipeline load.
+ if row["task"] is not None and not has_pipeline_index:
+ row["single_file"] = True
+ # Keep the newest timestamp across duplicate caches; absent rows sort as oldest.
+ lm = max(last_modified, (existing or {}).get("last_modified", 0.0))
+ if lm > 0:
+ row["last_modified"] = lm
+ seen_lower[key] = row
+ elif last_modified > existing.get("last_modified", 0.0):
+ existing["last_modified"] = last_modified
+ except Exception as e:
+ repo_label = getattr(repo_info, "repo_id", "<unknown>")
+ logger.warning(f"Skipping cached model repo {repo_label}: {e}")
+ continue
- rows = [row for key, row in seen_lower.items() if key not in unusable_active]
- # Local-only list path: update checks are GGUF-only and happen lazily when variants are viewed.
- cached = sorted(
- rows,
- key = lambda c: (-(c.get("last_modified") or 0.0), c["repo_id"].lower()),
- )
- return {"cached": cached}
- except Exception as e:
- logger.error(f"Error listing cached models: {e}", exc_info = True)
- return {"cached": []}
+ # Local-only list path: update checks are GGUF-only and happen lazily when variants are viewed.
+ return sorted(
+ seen_lower.values(),
+ key = lambda c: (-(c.get("last_modified") or 0.0), c["repo_id"].lower()),
+ )
def _loaded_id_matches_repo(loaded_id: str, repo_id: str) -> bool:
diff --git a/studio/backend/tests/data/refactor_guard/patch_targets.json b/studio/backend/tests/data/refactor_guard/patch_targets.json
index a868726fb5a..12a4fd2e896 100644
--- a/studio/backend/tests/data/refactor_guard/patch_targets.json
+++ b/studio/backend/tests/data/refactor_guard/patch_targets.json
@@ -742,10 +742,6 @@
"tests/test_consent_gate.py"
],
"routes.models._cached_repo_task": [
- "tests/test_cached_gguf_routes.py",
- "tests/test_cached_gguf_routes.py"
- ],
- "routes.models._repo_gguf_task": [
"tests/test_cached_gguf_routes.py"
],
"routes.training_vram.summarize_resident_chat": [
@@ -1111,8 +1107,6 @@
"tests/test_hf_cache_dangling_refs.py",
"tests/test_hf_cache_dangling_refs.py",
"tests/test_hf_cache_dangling_refs.py",
- "tests/test_hf_cache_dangling_refs.py",
- "tests/test_hf_cache_dangling_refs.py",
"tests/test_model_update_robustness.py",
"tests/test_model_update_robustness.py",
"tests/test_offline_embedding_minimal.py",
diff --git a/studio/backend/tests/test_cached_gguf_routes.py b/studio/backend/tests/test_cached_gguf_routes.py
index 30ccdf7fffc..0206b9913fc 100644
--- a/studio/backend/tests/test_cached_gguf_routes.py
+++ b/studio/backend/tests/test_cached_gguf_routes.py
@@ -4,6 +4,7 @@
import asyncio
import json
import os
+import struct
import sys
import threading
import time
@@ -26,6 +27,7 @@ if "structlog" not in sys.modules:
)
import routes.models as models_route
+from hub.services.models import catalog_classification as _classification
from hub.services.models import gguf_variants as GV
@@ -597,8 +599,8 @@ def test_list_cached_gguf_load_id_skips_partial_split_snapshot(monkeypatch, tmp_
assert rows[0]["load_id"] == str(older)
-def test_list_cached_gguf_omits_load_id_when_no_snapshot_is_complete(monkeypatch, tmp_path):
- """With only a half-downloaded split quant, fall back to the repo id, not a path."""
+def test_list_cached_gguf_marks_partial_when_no_snapshot_is_complete(monkeypatch, tmp_path):
+ """With only a half-downloaded split quant, expose no loadable picker target."""
active = tmp_path / "active"
repo_dir = tmp_path / "legacy" / "models--Org--Torn"
snapshot = repo_dir / "snapshots" / "rev"
@@ -624,6 +626,13 @@ def test_list_cached_gguf_omits_load_id_when_no_snapshot_is_complete(monkeypatch
rows = asyncio.run(models_route.list_cached_gguf(current_subject = "test-user"))["cached"]
assert "load_id" not in rows[0]
+ assert rows[0]["partial"] is True
+
+ # a commit-pinned active-cache attempt has no refs/main, so the bare id is unusable there too.
+ monkeypatch.setattr(models_route, "_resolve_hf_cache_dir", lambda: repo_dir.parent)
+ rows = asyncio.run(models_route.list_cached_gguf(current_subject = "test-user"))["cached"]
+ assert "load_id" not in rows[0]
+ assert rows[0]["partial"] is True
def test_list_cached_gguf_load_id_takes_the_snapshot_holding_a_whole_quant(monkeypatch, tmp_path):
@@ -1021,8 +1030,8 @@ def test_a_copy_that_loads_beats_a_bigger_one_that_does_not(monkeypatch, tmp_pat
def test_list_cached_gguf_pins_a_snapshot_when_the_default_ref_quant_is_torn(monkeypatch, tmp_path):
"""The repo id resolving is not enough: refs/main can land on a revision holding half a split
- while an older one is whole. The compat schema carries no partial flag, so a client loading the
- id follows the torn ref and fails with a complete copy one directory away."""
+ while an older one is whole. A client loading the id follows the torn ref and fails with a
+ complete copy one directory away."""
import os
active = tmp_path / "active"
@@ -1436,6 +1445,7 @@ def test_list_cached_gguf_includes_non_suffix_repo_when_cache_contains_gguf(monk
"cache_path": str(repo.repo_path),
"has_vision": False,
"task": None,
+ "partial": True,
}
]
@@ -1459,6 +1469,7 @@ def test_list_cached_gguf_matches_extension_case_insensitively(monkeypatch, tmp_
"cache_path": str(repo.repo_path),
"has_vision": False,
"task": None,
+ "partial": True,
}
]
@@ -1757,6 +1768,7 @@ def test_list_cached_gguf_keeps_largest_duplicate_repo_across_scans(monkeypatch,
"cache_path": str(larger.repo_path),
"has_vision": False,
"task": None,
+ "partial": True,
}
]
@@ -1788,6 +1800,7 @@ def test_list_cached_gguf_dedupes_shared_blobs_across_revisions(monkeypatch, tmp
"cache_path": str(repo.repo_path),
"has_vision": False,
"task": None,
+ "partial": True,
}
]
@@ -1830,9 +1843,9 @@ def test_list_cached_models_prefers_complete_over_larger_partial(monkeypatch, tm
monkeypatch.setattr(
models_route,
"_cached_repo_partial",
- lambda repo_id, repo_cache_dir = None: "root_b" in str(repo_cache_dir),
+ lambda repo_id, repo_cache_dir = None, snapshot_dir = None: "root_b" in str(repo_cache_dir),
)
- monkeypatch.setattr(models_route, "_cached_repo_task", lambda repo_info: None)
+ monkeypatch.setattr(models_route, "_cached_repo_task", lambda repo_info, selected = None: None)
# List the partial (larger) FIRST, so the old size-only rule would have picked it.
monkeypatch.setattr(
models_route,
@@ -1876,6 +1889,7 @@ def test_list_cached_gguf_includes_mixed_repo_with_gguf_and_safetensors(monkeypa
"cache_path": str(mixed.repo_path),
"has_vision": False,
"task": None,
+ "partial": True,
}
]
@@ -1904,6 +1918,7 @@ def test_list_cached_gguf_handles_none_size_on_disk(monkeypatch, tmp_path):
"cache_path": str(partial.repo_path),
"has_vision": False,
"task": None,
+ "partial": True,
}
]
@@ -1941,6 +1956,7 @@ def test_list_cached_gguf_skips_malformed_repo_without_wiping_response(monkeypat
"cache_path": str(healthy.repo_path),
"has_vision": False,
"task": None,
+ "partial": True,
}
]
@@ -2085,6 +2101,7 @@ def test_list_cached_gguf_includes_vision_repo_with_main_gguf_and_mmproj(monkeyp
"cache_path": str(vision_repo.repo_path),
"has_vision": True,
"task": None,
+ "partial": True,
}
]
@@ -2121,6 +2138,7 @@ def test_all_hf_cache_scans_uses_shared_inventory(monkeypatch, tmp_path):
"cache_path": str(tmp_path / "active"),
"has_vision": False,
"task": None,
+ "partial": True,
}
]
@@ -2808,6 +2826,25 @@ def test_arch_to_task_hides_unsupported_diffusion_from_chat():
assert not missing, f"diffusion archs would still show in chat: {missing}"
+def test_local_model_task_classifies_suffix_only_gguf_from_architecture(tmp_path):
+ def gguf_string(value: str) -> bytes:
+ data = value.encode()
+ return struct.pack("<Q", len(data)) + data
+
+ model_path = tmp_path / "opaque.gguf"
+ metadata = gguf_string("general.architecture") + struct.pack("<I", 8) + gguf_string("flux")
+ model_path.write_bytes(struct.pack("<IIQQ", 0x46554747, 3, 0, 1) + metadata)
+ model = SimpleNamespace(
+ model_format = None,
+ path = str(model_path),
+ model_id = None,
+ display_name = "Opaque",
+ id = str(model_path),
+ )
+
+ assert models_route._local_model_task(model) == "text-to-image"
+
+
def test_arch_to_task_tags_speech_archs_as_speech():
# llama.cpp cannot load these at all, so chat must not claim them.
for arch in models_route._SPEECH_GGUF_ARCHS:
@@ -3108,24 +3145,26 @@ def test_cached_repo_partial_scopes_probe_to_snapshot_dir(monkeypatch):
repo_type,
repo_id,
repo_cache_dir = None,
+ snapshot_dir = None,
):
- calls.append((repo_type, repo_id, repo_cache_dir))
+ calls.append((repo_type, repo_id, repo_cache_dir, snapshot_dir))
return False
monkeypatch.setattr(scan, "is_snapshot_partial", _fake)
+ repo_dir = Path("/root_a/models--Org--Repo")
snapshot_dir = Path("/root_a/models--Org--Repo/snapshots/abc")
- assert models_route._cached_repo_partial("Org/Repo", snapshot_dir) is False
- assert calls == [("model", "Org/Repo", snapshot_dir)]
+ assert models_route._cached_repo_partial("Org/Repo", repo_dir, snapshot_dir) is False
+ assert calls == [("model", "Org/Repo", repo_dir, snapshot_dir)]
monkeypatch.setattr(scan, "is_snapshot_partial", lambda *a, **k: True)
- assert models_route._cached_repo_partial("Org/Repo", snapshot_dir) is True
+ assert models_route._cached_repo_partial("Org/Repo", repo_dir, snapshot_dir) is True
# A probe error is swallowed (never hides a usable repo over a scan glitch).
def _boom(*a, **k):
raise RuntimeError("scan glitch")
monkeypatch.setattr(scan, "is_snapshot_partial", _boom)
- assert models_route._cached_repo_partial("Org/Repo", snapshot_dir) is False
+ assert models_route._cached_repo_partial("Org/Repo", repo_dir, snapshot_dir) is False
def test_repo_has_pipeline_index_requires_root_model_index(tmp_path):
@@ -3295,7 +3334,9 @@ def test_list_cached_models_flags_single_file_diffusion_repos(monkeypatch, tmp_p
monkeypatch.setattr(
models_route,
"_cached_repo_task",
- lambda repo_info: "text-to-image" if "Qwen-Image" in repo_info.repo_id else None,
+ lambda repo_info, selected = None: (
+ "text-to-image" if "Qwen-Image" in repo_info.repo_id else None
+ ),
)
monkeypatch.setattr(
models_route,
@@ -3441,27 +3482,76 @@ def test_hub_cached_rows_carry_the_task_the_pickers_filter_on(monkeypatch, tmp_p
task on those rows the Images and Video pickers filtered every one of them out, and the chat
picker's diffusion routing (which reads the same field) never fired."""
from hub.schemas.inventory import CachedGgufRepo, CachedModelRepo
- from hub.services.models import cache_inventory
+ from hub.services.models import cache_inventory, catalog_classification
assert "task" in CachedGgufRepo.model_fields
assert "task" in CachedModelRepo.model_fields
repo = _pipeline_repo("unsloth/Qwen-Image", tmp_path)
monkeypatch.setattr(
- "routes.models._cached_repo_task", lambda repo_info: "text-to-image", raising = True
+ catalog_classification,
+ "_cached_repo_task",
+ lambda repo_info, selected = None: "text-to-image",
)
assert cache_inventory._cached_row_task(repo, gguf = False) == "text-to-image"
monkeypatch.setattr(
- "routes.models._repo_gguf_task", lambda repo_info: "text-generation", raising = True
+ catalog_classification,
+ "_repo_gguf_task",
+ lambda repo_info, selected = None: "text-generation",
)
assert cache_inventory._cached_row_task(repo, gguf = True) == "text-generation"
+def test_hub_cached_gguf_task_uses_the_selected_snapshot(monkeypatch, tmp_path):
+ from hub.services.models import cache_inventory, catalog_classification
+
+ selected = tmp_path / "models--org--model" / "snapshots" / "selected"
+ repo = SimpleNamespace(
+ repo_id = "org/model",
+ repo_type = "model",
+ repo_path = selected.parents[1],
+ revisions = [],
+ )
+ observed = []
+
+ monkeypatch.setattr(cache_inventory, "_repo_gguf_size_bytes", lambda _repo: 10)
+ monkeypatch.setattr(cache_inventory, "_repo_gguf_last_modified", lambda _repo: 1.0)
+ monkeypatch.setattr(cache_inventory, "_cached_model_snapshot_path", lambda _path: None)
+ monkeypatch.setattr(
+ cache_inventory,
+ "_repo_gguf_payload_snapshots",
+ lambda _repo: (selected, frozenset({str(selected)})),
+ )
+ monkeypatch.setattr(cache_inventory, "_gguf_variant_state_summary", lambda *a, **k: (False, 0))
+ monkeypatch.setattr(cache_inventory, "_is_hidden_infra_repo", lambda *values: False)
+ monkeypatch.setattr(
+ cache_inventory.hf_cache_scan, "is_gguf_repo_partial", lambda *a, **k: False
+ )
+ monkeypatch.setattr(
+ cache_inventory.download_manifest, "build_variant_state_index", lambda *a, **k: None
+ )
+ monkeypatch.setattr(cache_inventory, "_cache_inventory_fields", lambda *a, **k: {})
+
+ def classify(repo_info, snapshot = None):
+ observed.append((repo_info, snapshot))
+ return "text-generation"
+
+ monkeypatch.setattr(catalog_classification, "_repo_gguf_task", classify)
+
+ rows = cache_inventory._scan_cached_gguf(
+ cache_scans = [SimpleNamespace(repos = [repo])],
+ active_hub_cache = tmp_path,
+ )
+
+ assert rows[0]["task"] == "text-generation"
+ assert observed == [(repo, selected)]
+
+
def test_hub_cached_row_task_never_hides_a_row_when_classification_fails(monkeypatch, tmp_path):
# Best-effort, like the models API: a classifier that raises leaves the row untagged rather than dropping it.
from hub.services.models import cache_inventory
- def _boom(repo_info):
+ def _boom(repo_info, selected = None):
raise RuntimeError("unreadable")
monkeypatch.setattr("routes.models._cached_repo_task", _boom, raising = True)
@@ -3585,7 +3675,9 @@ def test_pipeline_class_guard_is_silent_when_a_lazy_submodule_cannot_import(monk
def test_cached_pipeline_needs_a_detectable_image_family(monkeypatch):
# A top-level model_index.json only proves the repo is a diffusers pipeline: an unsloth-hosted pipeline of a class this backend
# cannot assemble cleared the trust gate, was advertised, then failed validate_load_request. Both gates now, like the video branch.
- monkeypatch.setattr(models_route, "_repo_has_pipeline_index", lambda info: True)
+ monkeypatch.setattr(
+ _classification, "_repo_has_pipeline_index", lambda info, selected = None: True
+ )
def _task(repo_id):
return models_route._cached_repo_task(SimpleNamespace(repo_id = repo_id, repo_path = "/x"))
@@ -3603,7 +3695,9 @@ def test_cached_repo_task_agrees_with_the_image_loader(monkeypatch):
# Same invariant as the GGUF arch test: whatever the picker advertises as loadable, validate_load_request must accept.
from core.inference.diffusion import DiffusionBackend
- monkeypatch.setattr(models_route, "_repo_has_pipeline_index", lambda info: True)
+ monkeypatch.setattr(
+ _classification, "_repo_has_pipeline_index", lambda info, selected = None: True
+ )
backend = DiffusionBackend.__new__(DiffusionBackend)
for repo_id in (
"unsloth/Z-Image-Turbo",
@@ -3635,7 +3729,7 @@ def test_cached_picker_hides_a_family_this_diffusers_cannot_build(monkeypatch):
# Present in this environment's diffusers, so the row is offered.
assert family_pipeline_available(fam) is True
- monkeypatch.setattr(models_module, "_repo_is_diffusers", lambda info: True)
+ monkeypatch.setattr(models_module, "_repo_is_diffusers", lambda info, selected = None: True)
monkeypatch.setattr("core.inference.diffusion._is_trusted_diffusion_repo", lambda repo_id: True)
info = types.SimpleNamespace(repo_id = "unsloth/Z-Image-Turbo")
assert models_module._cached_repo_task(info) == "text-to-image"
@@ -3739,7 +3833,7 @@ def test_the_loader_demands_the_diffusers_class_only_when_diffusers_loads_it(mon
def test_the_video_picker_hides_a_family_this_diffusers_cannot_build(monkeypatch):
# Same gap on the video branches: LTX-2's pipeline class is 0.39-only too, and video has no native engine to fall back
# to, so the load asserts it unconditionally (video.py -> assert_pipeline_class_available).
- monkeypatch.setattr(models_route, "_repo_is_diffusers", lambda info: True)
+ monkeypatch.setattr(_classification, "_repo_is_diffusers", lambda info, selected = None: True)
info = SimpleNamespace(repo_id = "Lightricks/LTX-2", repo_path = "/x")
# Offered on this environment's diffusers ...
assert models_route._arch_to_task("ltxv") == models_route._VIDEO_GEN_TASK
@@ -4914,12 +5008,16 @@ def _both_walk_orders(root: Path, monkeypatch, classify):
"""*classify* under both possible ``_iter_gguf_paths`` orders.
The real walk is ``rglob``, raw directory order, which differs between filesystems and between
- a folder and a fresh copy of it. Order is the input being varied, so it is forced."""
+ a folder and a fresh copy of it. Order is the input being varied, so it is forced.
+
+ Patched on ``_classification``, not on ``models_route``: ``_gguf_folder_task`` lives in
+ catalog_classification and resolves ``_iter_gguf_paths`` in THAT namespace, so patching the
+ routes alias leaves the real walk running and the order is never varied at all."""
paths = sorted(root.rglob("*.gguf"))
answers = []
for order in (paths, list(reversed(paths))):
monkeypatch.setattr(
- models_route, "_iter_gguf_paths", lambda _root, deadline = None, _o = order: iter(_o)
+ _classification, "_iter_gguf_paths", lambda _root, deadline = None, _o = order: iter(_o)
)
answers.append(classify())
return answers
@@ -4941,6 +5039,48 @@ def test_a_mixed_gguf_repo_classifies_the_same_in_either_walk_order(tmp_path, mo
assert answers == ["text-to-image", "text-to-image"], answers
[email protected]("active_copy", [False, True], ids = ["pinned", "bare-repo-id"])
+def test_cached_gguf_task_comes_from_the_snapshot_the_row_loads(monkeypatch, tmp_path, active_copy):
+ """A historical diffusion GGUF must not hide the selected text snapshot from Chat."""
+ active = tmp_path / "active"
+ cache_root = active if active_copy else tmp_path / "legacy"
+ repo_dir = cache_root / "models--Org--Mixed-History-GGUF"
+ historical = repo_dir / "snapshots" / "historical"
+ selected = repo_dir / "snapshots" / "selected"
+ diffusion = _arch_gguf(historical / "flux1-dev-Q4_K_M.gguf", "flux")
+ text = _arch_gguf(selected / "model-Q4_K_M.gguf", "llama")
+ os.utime(historical, (1_000_000, 1_000_000))
+ os.utime(selected, (2_000_000, 2_000_000))
+ (repo_dir / "refs").mkdir(parents = True)
+ (repo_dir / "refs" / "main").write_text("selected")
+
+ repo_info = _repo(
+ "Org/Mixed-History-GGUF",
+ [],
+ repo_dir,
+ revisions = [
+ SimpleNamespace(
+ files = [_file(diffusion.name, diffusion.stat().st_size)],
+ snapshot_path = historical,
+ ),
+ SimpleNamespace(
+ files = [_file(text.name, text.stat().st_size)],
+ snapshot_path = selected,
+ ),
+ ],
+ )
+ monkeypatch.setattr(models_route, "_resolve_hf_cache_dir", lambda: active)
+
+ assert models_route._repo_gguf_task(repo_info) == "text-to-image"
+ [row] = models_route.cached_gguf_rows([SimpleNamespace(repos = [repo_info])])
+
+ assert row["task"] == "text-generation"
+ if active_copy:
+ assert "load_id" not in row
+ else:
+ assert row["load_id"] == str(selected)
+
+
def test_a_mixed_local_gguf_folder_classifies_the_same_in_either_walk_order(tmp_path, monkeypatch):
"""The local twin, and the half that made an image model unfindable: with the encoder answering
first the folder is tagged ``text-generation``, which drops it out of the Images picker
@@ -5122,16 +5262,18 @@ def test_only_the_first_shard_of_a_split_gguf_is_read_to_classify_a_repo(tmp_pat
(repo_dir / f"Big-Q4_K_M-{index}-of-00003.gguf").write_bytes(b"not a gguf header")
read: list[str] = []
- real = models_route._gguf_architecture
+ from hub.services.models import catalog_classification
+
+ real = catalog_classification._gguf_architecture
monkeypatch.setattr(
- models_route,
+ catalog_classification,
"_gguf_architecture",
lambda path: (read.append(Path(path).name), real(path))[1],
)
# Trailing shards first, an order the filesystem is free to hand back: without the skip they
# are opened and read as unclassifiable before shard 1 is reached.
monkeypatch.setattr(
- models_route,
+ catalog_classification,
"_iter_gguf_paths",
lambda _root, deadline = None: iter(sorted(repo_dir.rglob("*.gguf"), reverse = True)),
)
@@ -5176,7 +5318,10 @@ def test_a_slow_walk_cannot_hand_back_the_encoder_this_function_exists_to_avoid(
time.sleep(models_route._TASK_CLASSIFY_WALK_SECONDS + 0.05)
return iter(ordered)
- monkeypatch.setattr(models_route, "_iter_gguf_paths", _slow_walk)
+ # On _classification, where _gguf_folder_task resolves the name. Patching the routes
+ # alias instead leaves the real walk running, and the test passes on flux winning the
+ # ordinary sort rather than on the budget being honoured.
+ monkeypatch.setattr(_classification, "_iter_gguf_paths", _slow_walk)
assert models_route._gguf_folder_task(folder, ("someone/flux-bundle",)) == "text-to-image"
@@ -5253,7 +5398,7 @@ def test_a_truncated_classification_never_answers_speech(tmp_path, monkeypatch):
# The read budget gone before the second file: the first read always happens, so the csm quant
# is the only verdict in hand.
- monkeypatch.setattr(models_route, "_TASK_CLASSIFY_READ_SECONDS", -1.0)
+ monkeypatch.setattr(_classification, "_TASK_CLASSIFY_READ_SECONDS", -1.0)
assert models_route._gguf_folder_task(folder, ("someone/mixed-GGUF",)) is None
monkeypatch.undo()
@@ -5263,13 +5408,13 @@ def test_a_truncated_classification_never_answers_speech(tmp_path, monkeypatch):
while deadline is not None and time.monotonic() < deadline:
time.sleep(0.01)
- monkeypatch.setattr(models_route, "_iter_gguf_paths", truncating)
+ monkeypatch.setattr(_classification, "_iter_gguf_paths", truncating)
assert models_route._gguf_folder_task(folder, ("someone/mixed-GGUF",)) is None
monkeypatch.undo()
# The cap dropping the tail the runnable sibling sorts into.
capped = tmp_path / "capped"
- for index in range(models_route._MAX_TASK_CLASSIFY_GGUFS + 4):
+ for index in range(_classification._MAX_TASK_CLASSIFY_GGUFS + 4):
_arch_gguf(capped / f"aaa-{index:03d}-csm.gguf", "llama-csm")
_arch_gguf(capped / "zzz-qwen3-Q4_K_M.gguf", "llama")
assert models_route._gguf_folder_task(capped, ("someone/capped-GGUF",)) is None
@@ -5294,7 +5439,7 @@ def test_a_folder_trimmed_exactly_back_to_the_cap_never_answers_speech(tmp_path)
unreachable in every picker.
The boundary repeats: each later trim lands on the same length, hence the second size."""
- cap = models_route._MAX_TASK_CLASSIFY_GGUFS
+ cap = _classification._MAX_TASK_CLASSIFY_GGUFS
# 2 * cap + 1 is the count that trips the trim on its final candidate; + 1 more trim's worth
# is the next one that does, confirming this is a recurring boundary and not one bad number.
for total in (2 * cap + 1, 3 * cap + 2):
@@ -5815,6 +5960,816 @@ def test_the_listing_probe_hides_a_class_the_installed_diffusers_predates(monkey
assert "diffusers" not in sys.modules, "the listing probe imported diffusers"
+def test_cached_model_rows_pins_snapshot_load_id_for_inactive_cache(monkeypatch, tmp_path):
+ """A non-GGUF copy outside the active cache must carry its snapshot path.
+
+ Without the pin the row falls back to the bare repo id, which ModelConfig resolves
+ through the ACTIVE cache: offline the pick cannot load, online it re-downloads.
+ """
+ active = tmp_path / "active"
+ active.mkdir()
+ snapshot = tmp_path / "legacy" / "models--Org--Away" / "snapshots" / "rev"
+ snapshot.mkdir(parents = True)
+ away = _repo(
+ "Org/Away",
+ [],
+ tmp_path / "legacy" / "models--Org--Away",
+ revisions = [
+ SimpleNamespace(files = [_file("model.safetensors", 5_000)], snapshot_path = snapshot),
+ ],
+ )
+ here_snapshot = active / "models--Org--Here" / "snapshots" / "rev"
+ here_snapshot.mkdir(parents = True)
+ here = _repo(
+ "Org/Here",
+ [],
+ active / "models--Org--Here",
+ revisions = [
+ SimpleNamespace(files = [_file("model.safetensors", 6_000)], snapshot_path = here_snapshot),
+ ],
+ )
+
+ monkeypatch.setattr(models_route, "_cached_repo_task", lambda repo_info, selected = None: None)
+ monkeypatch.setattr(models_route, "_cached_repo_partial", lambda *args, **kwargs: False)
+ monkeypatch.setattr(
+ models_route, "_all_hf_cache_scans", lambda: [SimpleNamespace(repos = [away, here])]
+ )
+ monkeypatch.setattr(models_route, "_resolve_hf_cache_dir", lambda: active)
+
+ rows = {row["repo_id"]: row for row in models_route.cached_model_rows()}
+
+ assert rows["Org/Away"]["load_id"] == str(snapshot)
+ # The active-cache copy resolves by id, so pinning it would only freeze a revision.
+ assert "load_id" not in rows["Org/Here"]
+
+
+def test_cached_model_rows_flags_adapter_repos(monkeypatch, tmp_path):
+ """A cached LoRA must be labelled, or every 'no adapters' filter compares against
+ a key that is never set and offers the adapter as a whole model."""
+ active = tmp_path / "active"
+ adapter_snap = active / "models--Org--Lora" / "snapshots" / "rev"
+ adapter_snap.mkdir(parents = True)
+ (adapter_snap / "adapter_config.json").write_text("{}")
+ adapter = _repo(
+ "Org/Lora",
+ [],
+ active / "models--Org--Lora",
+ revisions = [
+ SimpleNamespace(
+ files = [_file("adapter_model.safetensors", 4_000)],
+ snapshot_path = adapter_snap,
+ ),
+ ],
+ )
+ merged_snap = active / "models--Org--Merged" / "snapshots" / "rev"
+ merged_snap.mkdir(parents = True)
+ (merged_snap / "config.json").write_text("{}")
+ merged = _repo(
+ "Org/Merged",
+ [],
+ active / "models--Org--Merged",
+ revisions = [
+ SimpleNamespace(files = [_file("model.safetensors", 9_000)], snapshot_path = merged_snap),
+ ],
+ )
+
+ monkeypatch.setattr(models_route, "_cached_repo_task", lambda repo_info, selected = None: None)
+ monkeypatch.setattr(models_route, "_cached_repo_partial", lambda *args, **kwargs: False)
+ monkeypatch.setattr(
+ models_route,
+ "_all_hf_cache_scans",
+ lambda: [SimpleNamespace(repos = [adapter, merged])],
+ )
+ monkeypatch.setattr(models_route, "_resolve_hf_cache_dir", lambda: active)
+
+ rows = {row["repo_id"]: row for row in models_route.cached_model_rows()}
+
+ assert rows["Org/Lora"]["model_format"] == "adapter"
+ assert "model_format" not in rows["Org/Merged"]
+
+
+def test_cached_model_rows_marks_encoder_only_repos_unchattable(monkeypatch, tmp_path):
+ """A cached embedding/CLIP repo has task None exactly like a chat repo, so without
+ the row's own classification every chat picker offers it as a model to talk to."""
+ active = tmp_path / "active"
+
+ def _cached(
+ repo_id,
+ config,
+ *,
+ modules_json = False,
+ ):
+ owner, name = repo_id.split("/")
+ snap = active / f"models--{owner}--{name}" / "snapshots" / "rev"
+ snap.mkdir(parents = True)
+ (snap / "config.json").write_text(json.dumps(config))
+ if modules_json:
+ (snap / "modules.json").write_text("[]")
+ return _repo(
+ repo_id,
+ [],
+ active / f"models--{owner}--{name}",
+ revisions = [
+ SimpleNamespace(
+ files = [_file("model.safetensors", 9_000)],
+ snapshot_path = snap,
+ ),
+ ],
+ )
+
+ # Configs as published on the Hub.
+ embedder = _cached(
+ "sentence-transformers/all-MiniLM-L6-v2",
+ {"model_type": "bert", "architectures": ["BertModel"]},
+ modules_json = True,
+ )
+ clip = _cached(
+ "openai/clip-vit-base-patch32",
+ {"model_type": "clip", "architectures": ["CLIPModel"]},
+ )
+ chat = _cached(
+ "unsloth/Qwen3-0.6B",
+ {"model_type": "qwen3", "architectures": ["Qwen3ForCausalLM"]},
+ )
+
+ monkeypatch.setattr(models_route, "_cached_repo_task", lambda repo_info, selected = None: None)
+ monkeypatch.setattr(models_route, "_cached_repo_partial", lambda *args, **kwargs: False)
+ monkeypatch.setattr(
+ models_route,
+ "_all_hf_cache_scans",
+ lambda: [SimpleNamespace(repos = [embedder, clip, chat])],
+ )
+ monkeypatch.setattr(models_route, "_resolve_hf_cache_dir", lambda: active)
+
+ rows = {row["repo_id"]: row for row in models_route.cached_model_rows()}
+
+ assert rows["sentence-transformers/all-MiniLM-L6-v2"]["can_chat"] is False
+ assert rows["openai/clip-vit-base-patch32"]["can_chat"] is False
+ # Fails open: a chat repo is never flagged, and neither is an unreadable snapshot.
+ assert "can_chat" not in rows["unsloth/Qwen3-0.6B"]
+
+
+def test_cached_model_rows_pins_the_snapshot_that_holds_the_weights(monkeypatch, tmp_path):
+ """A metadata-only commit must not win the pin just for being newest.
+
+ huggingface_hub stores one snapshot per commit, so reading a config or tokenizer at a
+ newer revision leaves a weightless dir beside the complete one. Pinning it advertises
+ a Downloaded model whose load raises "no file named model.safetensors" offline.
+ """
+ active = tmp_path / "active"
+ active.mkdir()
+ repo_dir = tmp_path / "legacy" / "models--Org--Chatty"
+
+ complete = repo_dir / "snapshots" / "complete"
+ complete.mkdir(parents = True)
+ (complete / "config.json").write_text("{}")
+ (complete / "model.safetensors").write_bytes(b"\0" * 64)
+
+ metadata_only = repo_dir / "snapshots" / "metadata"
+ metadata_only.mkdir(parents = True)
+ (metadata_only / "config.json").write_text("{}")
+ (metadata_only / "tokenizer.json").write_text("{}")
+
+ # The metadata fetch happened later, so it sorts first by mtime.
+ os.utime(complete, (1_000_000, 1_000_000))
+ os.utime(metadata_only, (2_000_000, 2_000_000))
+
+ repo = _repo(
+ "Org/Chatty",
+ [],
+ repo_dir,
+ revisions = [
+ SimpleNamespace(files = [_file("model.safetensors", 5_000)], snapshot_path = complete),
+ SimpleNamespace(files = [_file("config.json", 100)], snapshot_path = metadata_only),
+ ],
+ )
+
+ monkeypatch.setattr(models_route, "_cached_repo_task", lambda repo_info, selected = None: None)
+ monkeypatch.setattr(models_route, "_cached_repo_partial", lambda *args, **kwargs: False)
+ monkeypatch.setattr(
+ models_route, "_all_hf_cache_scans", lambda: [SimpleNamespace(repos = [repo])]
+ )
+ monkeypatch.setattr(models_route, "_resolve_hf_cache_dir", lambda: active)
+
+ rows = {row["repo_id"]: row for row in models_route.cached_model_rows()}
+
+ assert rows["Org/Chatty"]["load_id"] == str(complete)
+ assert rows["Org/Chatty"]["load_id"] != str(metadata_only)
+
+
+def test_repo_model_can_chat_still_reads_a_metadata_only_snapshot(tmp_path):
+ """The classification must read whichever snapshot holds the config even though the
+ load id skips it: the metadata-only commit is exactly where config.json lives."""
+ repo_dir = tmp_path / "models--Org--Embedder"
+
+ weights_only = repo_dir / "snapshots" / "weights"
+ weights_only.mkdir(parents = True)
+ (weights_only / "model.safetensors").write_bytes(b"\0" * 64)
+
+ metadata_only = repo_dir / "snapshots" / "metadata"
+ metadata_only.mkdir(parents = True)
+ (metadata_only / "config.json").write_text(
+ json.dumps({"model_type": "bert", "architectures": ["BertModel"]})
+ )
+
+ os.utime(weights_only, (2_000_000, 2_000_000))
+ os.utime(metadata_only, (1_000_000, 1_000_000))
+
+ repo = _repo(
+ "Org/Embedder",
+ [],
+ repo_dir,
+ revisions = [
+ SimpleNamespace(files = [], snapshot_path = weights_only),
+ SimpleNamespace(files = [], snapshot_path = metadata_only),
+ ],
+ )
+
+ assert models_route._repo_model_can_chat(repo) is False
+
+
+def test_cached_model_rows_skips_a_weights_only_snapshot(monkeypatch, tmp_path):
+ """Weights without metadata are as unloadable as metadata without weights.
+
+ Unsloth's base-model pre-warm fetches the shards plus index and no config.json, so a
+ weights-only commit lands beside the complete snapshot and sorts first. Pinning it
+ raises "Unrecognized model ... should have a model_type key".
+ """
+ active = tmp_path / "active"
+ active.mkdir()
+ repo_dir = tmp_path / "legacy" / "models--Org--Chatty"
+
+ complete = repo_dir / "snapshots" / "complete"
+ complete.mkdir(parents = True)
+ (complete / "config.json").write_text("{}")
+ (complete / "model.safetensors").write_bytes(b"\0" * 64)
+
+ weights_only = repo_dir / "snapshots" / "weights"
+ weights_only.mkdir(parents = True)
+ (weights_only / "model.safetensors").write_bytes(b"\0" * 64)
+ (weights_only / "model.safetensors.index.json").write_text("{}")
+
+ # The weight pre-warm happened later, so it sorts first by mtime.
+ os.utime(complete, (1_000_000, 1_000_000))
+ os.utime(weights_only, (2_000_000, 2_000_000))
+
+ repo = _repo(
+ "Org/Chatty",
+ [],
+ repo_dir,
+ revisions = [
+ SimpleNamespace(files = [_file("model.safetensors", 5_000)], snapshot_path = complete),
+ SimpleNamespace(files = [_file("model.safetensors", 5_000)], snapshot_path = weights_only),
+ ],
+ )
+
+ monkeypatch.setattr(models_route, "_cached_repo_task", lambda repo_info, selected = None: None)
+ monkeypatch.setattr(models_route, "_cached_repo_partial", lambda *args, **kwargs: False)
+ monkeypatch.setattr(
+ models_route, "_all_hf_cache_scans", lambda: [SimpleNamespace(repos = [repo])]
+ )
+ monkeypatch.setattr(models_route, "_resolve_hf_cache_dir", lambda: active)
+
+ rows = {row["repo_id"]: row for row in models_route.cached_model_rows()}
+
+ assert rows["Org/Chatty"]["load_id"] == str(complete)
+
+
+ "ref_files",
+ [
+ {"config.json": b"{}"},
+ {
+ "config.json": b"{}",
+ "model-00001-of-00002.safetensors": b"\0" * 64,
+ },
+ ],
+ ids = ["metadata-only", "torn-shards"],
+)
+def test_cached_model_rows_pins_when_the_active_ref_cannot_serve_a_load(
+ monkeypatch, tmp_path, ref_files
+):
+ """An active-cache row is only safe as a bare id while refs/main can serve the load.
+
+ repo_id_will_not_resolve only catches a ref naming no directory; a ref naming an
+ EXISTING half-fetched snapshot resolves fine and then fails, so the id must give way.
+ """
+ active = tmp_path / "active"
+ active.mkdir()
+ repo_dir = active / "models--Org--Chatty"
+
+ complete = repo_dir / "snapshots" / "complete"
+ complete.mkdir(parents = True)
+ (complete / "config.json").write_text("{}")
+ (complete / "model.safetensors").write_bytes(b"\0" * 64)
+
+ broken_ref = repo_dir / "snapshots" / "broken"
+ broken_ref.mkdir(parents = True)
+ for filename, payload in ref_files.items():
+ (broken_ref / filename).write_bytes(payload)
+
+ (repo_dir / "refs").mkdir(parents = True)
+ (repo_dir / "refs" / "main").write_text("broken")
+ (repo_dir / "blobs").mkdir(parents = True)
+ (repo_dir / "blobs" / "unfinished.incomplete").write_bytes(b"")
+
+ os.utime(complete, (1_000_000, 1_000_000))
+ os.utime(broken_ref, (2_000_000, 2_000_000))
+
+ repo = _repo(
+ "Org/Chatty",
+ [],
+ repo_dir,
+ revisions = [
+ SimpleNamespace(files = [_file("model.safetensors", 5_000)], snapshot_path = complete),
+ SimpleNamespace(
+ files = [_file(filename, len(payload)) for filename, payload in ref_files.items()],
+ snapshot_path = broken_ref,
+ ),
+ ],
+ )
+
+ monkeypatch.setattr(models_route, "_cached_repo_task", lambda repo_info, selected = None: None)
+ monkeypatch.setattr(
+ models_route, "_all_hf_cache_scans", lambda: [SimpleNamespace(repos = [repo])]
+ )
+ monkeypatch.setattr(models_route, "_resolve_hf_cache_dir", lambda: active.resolve())
+
+ rows = {row["repo_id"]: row for row in models_route.cached_model_rows()}
+
+ assert rows["Org/Chatty"]["load_id"] == str(complete)
+ assert "partial" not in rows["Org/Chatty"]
+
+
+def test_cached_model_rows_scope_pipeline_partialness_to_the_pinned_snapshot(monkeypatch, tmp_path):
+ """A newer companion-only pipeline must not mark an older complete pinned copy partial."""
+ active = tmp_path / "active"
+ active.mkdir()
+ repo_dir = active / "models--Org--Pipeline"
+ complete = repo_dir / "snapshots" / "complete"
+ broken = repo_dir / "snapshots" / "broken"
+
+ manifest = {
+ "_class_name": "FluxPipeline",
+ "scheduler": ["diffusers", "FlowMatchEulerDiscreteScheduler"],
+ "text_encoder": ["transformers", "CLIPTextModel"],
+ "tokenizer": ["transformers", "CLIPTokenizer"],
+ "transformer": ["diffusers", "FluxTransformer2DModel"],
+ "vae": ["diffusers", "AutoencoderKL"],
+ }
+
+ def write_pipeline(snapshot, *, with_transformer):
+ files = {
+ "model_index.json": json.dumps(manifest).encode(),
+ "scheduler/scheduler_config.json": b"{}",
+ "text_encoder/config.json": b"{}",
+ "text_encoder/model.safetensors": b"\0" * 64,
+ "tokenizer/tokenizer_config.json": b"{}",
+ "tokenizer/tokenizer.json": b"{}",
+ "vae/config.json": b"{}",
+ "vae/diffusion_pytorch_model.safetensors": b"\0" * 64,
+ }
+ if with_transformer:
+ files["transformer/config.json"] = b"{}"
+ files["transformer/diffusion_pytorch_model.safetensors"] = b"\0" * 64
+ for name, payload in files.items():
+ target = snapshot / name
+ target.parent.mkdir(parents = True, exist_ok = True)
+ target.write_bytes(payload)
+ return files
+
+ complete_files = write_pipeline(complete, with_transformer = True)
+ broken_files = write_pipeline(broken, with_transformer = False)
+ os.utime(complete, (1_000_000, 1_000_000))
+ os.utime(broken, (2_000_000, 2_000_000))
+ (repo_dir / "refs").mkdir(parents = True)
+ (repo_dir / "refs" / "main").write_text("broken")
+
+ repo = _repo(
+ "Org/Pipeline",
+ [],
+ repo_dir,
+ revisions = [
+ SimpleNamespace(
+ files = [_file(name, len(payload)) for name, payload in complete_files.items()],
+ snapshot_path = complete,
+ ),
+ SimpleNamespace(
+ files = [_file(name, len(payload)) for name, payload in broken_files.items()],
+ snapshot_path = broken,
+ ),
+ ],
+ )
+
+ monkeypatch.setattr(models_route, "_cached_repo_task", lambda repo_info, selected = None: None)
+ monkeypatch.setattr(models_route, "_cached_repo_partial", lambda *args, **kwargs: False)
+ monkeypatch.setattr(
+ models_route, "_all_hf_cache_scans", lambda: [SimpleNamespace(repos = [repo])]
+ )
+ monkeypatch.setattr(models_route, "_resolve_hf_cache_dir", lambda: active.resolve())
+
+ rows = {row["repo_id"]: row for row in models_route.cached_model_rows()}
+
+ assert rows["Org/Pipeline"]["load_id"] == str(complete)
+ assert "partial" not in rows["Org/Pipeline"]
+
+
+def test_active_cache_repo_with_a_serving_ref_keeps_its_bare_id(tmp_path):
+ """The pin is for refs that cannot serve: a healthy active-cache repo keeps its id,
+ and so does one with nothing better to offer."""
+ active = tmp_path / "active"
+ active.mkdir()
+
+ def _build(name, ref, snaps):
+ repo_dir = active / f"models--Org--{name}"
+ revisions = []
+ for commit, files in snaps.items():
+ snap = repo_dir / "snapshots" / commit
+ snap.mkdir(parents = True)
+ for fname in files:
+ (snap / fname).write_text("{}")
+ revisions.append(SimpleNamespace(snapshot_path = snap, files = []))
+ (repo_dir / "refs").mkdir(parents = True)
+ (repo_dir / "refs" / "main").write_text(ref)
+ return SimpleNamespace(repo_id = f"Org/{name}", repo_path = repo_dir, revisions = revisions)
+
+ healthy = _build("Healthy", "good", {"good": ["config.json", "model.safetensors"]})
+ assert models_route._repo_model_load_id(healthy, active.resolve()) is None
+
+ # Half-fetched ref, but no complete sibling exists: nothing better to pin.
+ nothing_better = _build("Bare", "meta", {"meta": ["config.json"]})
+ assert models_route._repo_model_load_id(nothing_better, active.resolve()) is None
+
+
+def test_cached_model_rows_ignores_a_training_args_bin_when_pinning(monkeypatch, tmp_path):
+ """A ``.bin`` is only weights when its name says so.
+
+ Trainer writes ``training_args.bin`` beside every fine-tune. Counting any ``.bin`` as
+ a payload let that decoy shadow the complete snapshot and pin a directory whose load
+ raises "no file named model.safetensors"; ``_WEIGHT_BIN_PREFIXES`` is the shared rule.
+ """
+ active = tmp_path / "active"
+ active.mkdir()
+ repo_dir = tmp_path / "legacy" / "models--Org--Tuned"
+
+ complete = repo_dir / "snapshots" / "complete"
+ complete.mkdir(parents = True)
+ (complete / "config.json").write_text("{}")
+ (complete / "model.safetensors").write_bytes(b"\0" * 64)
+
+ # config.json + the Trainer artefact landed; the shards are still coming.
+ decoy = repo_dir / "snapshots" / "decoy"
+ decoy.mkdir(parents = True)
+ (decoy / "config.json").write_text("{}")
+ (decoy / "training_args.bin").write_bytes(b"\0" * 64)
+
+ os.utime(complete, (1_000_000, 1_000_000))
+ os.utime(decoy, (2_000_000, 2_000_000))
+
+ repo = _repo(
+ "Org/Tuned",
+ [],
+ repo_dir,
+ revisions = [
+ SimpleNamespace(files = [_file("model.safetensors", 5_000)], snapshot_path = complete),
+ SimpleNamespace(files = [_file("training_args.bin", 64)], snapshot_path = decoy),
+ ],
+ )
+
+ monkeypatch.setattr(models_route, "_cached_repo_task", lambda repo_info, selected = None: None)
+ monkeypatch.setattr(models_route, "_cached_repo_partial", lambda *args, **kwargs: False)
+ monkeypatch.setattr(
+ models_route, "_all_hf_cache_scans", lambda: [SimpleNamespace(repos = [repo])]
+ )
+ monkeypatch.setattr(models_route, "_resolve_hf_cache_dir", lambda: active)
+
+ rows = {row["repo_id"]: row for row in models_route.cached_model_rows()}
+
+ assert rows["Org/Tuned"]["load_id"] == str(complete)
+ # A real weight .bin still counts, or every pre-safetensors checkpoint would be dropped.
+ assert models_route._snapshot_can_serve_a_load(decoy) is False
+ (decoy / "pytorch_model.bin").write_bytes(b"\0" * 64)
+ assert models_route._snapshot_can_serve_a_load(decoy) is True
+
+
+def test_cached_model_rows_classifies_the_selected_revision_not_the_history(monkeypatch, tmp_path):
+ """push_to_hub_merged reuses the repo id, so one repo holds a LoRA revision and later a
+ merge. Classifying every snapshot lets the stale adapter_config.json label the whole
+ repo an adapter, and cached_entries drops the merged checkpoint it should offer."""
+ active = tmp_path / "active"
+ repo_dir = active / "models--Org--Tuned"
+
+ adapter = repo_dir / "snapshots" / "lorarev"
+ adapter.mkdir(parents = True)
+ (adapter / "adapter_config.json").write_text("{}")
+ (adapter / "adapter_model.safetensors").write_bytes(b"\0" * 512)
+
+ merged = repo_dir / "snapshots" / "mergedrev"
+ merged.mkdir(parents = True)
+ (merged / "config.json").write_text("{}")
+ (merged / "model.safetensors").write_bytes(b"\0" * 9_000)
+
+ (repo_dir / "refs").mkdir(parents = True)
+ (repo_dir / "refs" / "main").write_text("mergedrev")
+ os.utime(adapter, (1_000_000, 1_000_000))
+ os.utime(merged, (2_000_000, 2_000_000))
+
+ repo = _repo(
+ "Org/Tuned",
+ [],
+ repo_dir,
+ revisions = [
+ SimpleNamespace(files = [_file("adapter_model.safetensors", 512)], snapshot_path = adapter),
+ SimpleNamespace(files = [_file("model.safetensors", 9_000)], snapshot_path = merged),
+ ],
+ )
+
+ monkeypatch.setattr(models_route, "_cached_repo_task", lambda repo_info, selected = None: None)
+ monkeypatch.setattr(models_route, "_cached_repo_partial", lambda *args, **kwargs: False)
+ monkeypatch.setattr(
+ models_route, "_all_hf_cache_scans", lambda: [SimpleNamespace(repos = [repo])]
+ )
+ monkeypatch.setattr(models_route, "_resolve_hf_cache_dir", lambda: active)
+
+ rows = {row["repo_id"]: row for row in models_route.cached_model_rows()}
+
+ assert "model_format" not in rows["Org/Tuned"]
+ # refs/main names the merge, so that is the revision the pick reads.
+ assert models_route._repo_model_selection(repo, active.resolve())[0] == merged
+
+
+def test_cached_model_rows_judge_chat_capability_on_the_selected_revision(monkeypatch, tmp_path):
+ """A stale encoder revision must not override an inconclusive selected config."""
+ active = tmp_path / "active"
+ repo_dir = active / "models--Org--Repurposed"
+ old = repo_dir / "snapshots" / "aaaold"
+ old.mkdir(parents = True)
+ (old / "config.json").write_text(json.dumps({"model_type": "qwen3"}))
+ (old / "model.safetensors").write_bytes(b"\0" * 32)
+ new = repo_dir / "snapshots" / "bbbnew"
+ new.mkdir(parents = True)
+ (new / "config.json").write_text(
+ json.dumps({"model_type": "bert", "architectures": ["BertModel"]})
+ )
+ os.utime(old, (1_000_000, 1_000_000))
+ os.utime(new, (2_000_000, 2_000_000))
+ repo = _repo(
+ "Org/Repurposed",
+ [],
+ repo_dir,
+ revisions = [
+ SimpleNamespace(files = [_file("model.safetensors", 9_000)], snapshot_path = old),
+ SimpleNamespace(files = [_file("config.json", 12)], snapshot_path = new),
+ ],
+ )
+
+ monkeypatch.setattr(models_route, "_cached_repo_task", lambda repo_info, selected = None: None)
+ monkeypatch.setattr(models_route, "_cached_repo_partial", lambda *args, **kwargs: False)
+ monkeypatch.setattr(
+ models_route, "_all_hf_cache_scans", lambda: [SimpleNamespace(repos = [repo])]
+ )
+ monkeypatch.setattr(models_route, "_resolve_hf_cache_dir", lambda: active)
+
+ rows = {row["repo_id"]: row for row in models_route.cached_model_rows()}
+
+ # The pin already reads the complete causal-LM, so the row must not read as unchattable.
+ assert models_route._repo_model_selection(repo, active.resolve())[0] == old
+ assert rows["Org/Repurposed"].get("can_chat") is not False
+
+
+def test_cached_model_rows_judge_diffusers_on_the_selected_revision(monkeypatch, tmp_path):
+ """A newer incomplete pipeline revision must not classify the older pinned LM as Diffusers."""
+ active = tmp_path / "active"
+ repo_dir = active / "models--Org--Repurposed"
+ causal = repo_dir / "snapshots" / "causal"
+ causal.mkdir(parents = True)
+ (causal / "config.json").write_text(
+ json.dumps({"model_type": "qwen3", "architectures": ["Qwen3ForCausalLM"]})
+ )
+ (causal / "model.safetensors").write_bytes(b"\0" * 64)
+ pipeline = repo_dir / "snapshots" / "pipeline"
+ (pipeline / "vae").mkdir(parents = True)
+ manifest = json.dumps(
+ {
+ "_class_name": "FluxPipeline",
+ "transformer": ["diffusers", "FluxTransformer2DModel"],
+ "vae": ["diffusers", "AutoencoderKL"],
+ }
+ )
+ (pipeline / "model_index.json").write_text(manifest)
+ (pipeline / "vae" / "diffusion_pytorch_model.safetensors").write_bytes(b"\0" * 64)
+ os.utime(causal, (1_000_000, 1_000_000))
+ os.utime(pipeline, (2_000_000, 2_000_000))
+ (repo_dir / "refs").mkdir(parents = True)
+ (repo_dir / "refs" / "main").write_text("pipeline")
+ repo = _repo(
+ "Org/Repurposed",
+ [],
+ repo_dir,
+ revisions = [
+ SimpleNamespace(
+ files = [_file("config.json", 64), _file("model.safetensors", 64)],
+ snapshot_path = causal,
+ ),
+ SimpleNamespace(
+ files = [
+ _file("model_index.json", len(manifest)),
+ _file("vae/diffusion_pytorch_model.safetensors", 64),
+ ],
+ snapshot_path = pipeline,
+ ),
+ ],
+ )
+
+ monkeypatch.setattr(models_route, "_cached_repo_partial", lambda *args, **kwargs: False)
+ monkeypatch.setattr(
+ models_route, "_all_hf_cache_scans", lambda: [SimpleNamespace(repos = [repo])]
+ )
+ monkeypatch.setattr(models_route, "_resolve_hf_cache_dir", lambda: active)
+
+ row = {item["repo_id"]: item for item in models_route.cached_model_rows()}["Org/Repurposed"]
+
+ assert row["load_id"] == str(causal)
+ assert row.get("task") is None
+ assert row.get("diffusers") is not True
+ assert "single_file" not in row
+
+
+def test_cached_model_rows_flag_a_selected_modular_pipeline_as_diffusers(monkeypatch, tmp_path):
+ active = tmp_path / "active"
+ repo_dir = active / "models--Org--Custom-Pipeline"
+ snapshot = repo_dir / "snapshots" / "rev"
+ (snapshot / "transformer").mkdir(parents = True)
+ manifest = json.dumps(
+ {
+ "_class_name": "ModularPipeline",
+ "transformer": ["diffusers", "FluxTransformer2DModel"],
+ }
+ )
+ (snapshot / "modular_model_index.json").write_text(manifest)
+ (snapshot / "transformer" / "config.json").write_text("{}")
+ (snapshot / "transformer" / "diffusion_pytorch_model.safetensors").write_bytes(b"\0" * 64)
+ (repo_dir / "refs").mkdir(parents = True)
+ (repo_dir / "refs" / "main").write_text("rev")
+ repo = _repo(
+ "Org/Custom-Pipeline",
+ [],
+ repo_dir,
+ revisions = [
+ SimpleNamespace(
+ files = [
+ _file("modular_model_index.json", len(manifest)),
+ _file("transformer/config.json", 2),
+ _file("transformer/diffusion_pytorch_model.safetensors", 64),
+ ],
+ snapshot_path = snapshot,
+ )
+ ],
+ )
+
+ monkeypatch.setattr(models_route, "_cached_repo_partial", lambda *args, **kwargs: False)
+ monkeypatch.setattr(
+ models_route, "_all_hf_cache_scans", lambda: [SimpleNamespace(repos = [repo])]
+ )
+ monkeypatch.setattr(models_route, "_resolve_hf_cache_dir", lambda: active)
+
+ row = {item["repo_id"]: item for item in models_route.cached_model_rows()}[
+ "Org/Custom-Pipeline"
+ ]
+
+ assert row.get("task") is None
+ assert row["diffusers"] is True
+
+
+def test_cached_model_rows_flag_a_diffusion_repo_this_backend_cannot_load(monkeypatch, tmp_path):
+ """An untrusted or unrecognised diffusion repo carries no task, exactly like a chat
+ repo, and its pipeline root has no config for can_chat to read. Without a flag of its
+ own the chat picker offered an ordinary community SDXL checkpoint as a chat model."""
+ active = tmp_path / "active"
+ repo_dir = active / "models--someuser--my-sdxl-finetune"
+ snap = repo_dir / "snapshots" / "rev"
+ (snap / "unet").mkdir(parents = True)
+ (snap / "model_index.json").write_text(json.dumps({"_class_name": "StableDiffusionXLPipeline"}))
+ (snap / "unet" / "diffusion_pytorch_model.safetensors").write_bytes(b"\0" * 32)
+ repo = _repo(
+ "someuser/my-sdxl-finetune",
+ [],
+ repo_dir,
+ revisions = [
+ SimpleNamespace(
+ files = [_file("unet/diffusion_pytorch_model.safetensors", 9_000)],
+ snapshot_path = snap,
+ ),
+ ],
+ )
+
+ monkeypatch.setattr(models_route, "_cached_repo_partial", lambda *args, **kwargs: False)
+ monkeypatch.setattr(
+ models_route, "_all_hf_cache_scans", lambda: [SimpleNamespace(repos = [repo])]
+ )
+ monkeypatch.setattr(models_route, "_resolve_hf_cache_dir", lambda: active)
+
+ rows = {row["repo_id"]: row for row in models_route.cached_model_rows()}
+ row = rows["someuser/my-sdxl-finetune"]
+
+ # Still listed, since Studio's Images picker consumes these rows; only chat excludes it.
+ assert row["diffusers"] is True
+ # The trust rule leaves task None on purpose, which is why the flag is needed.
+ assert row.get("task") is None
+
+
+def test_cached_model_rows_pins_a_commit_pinned_repo_with_no_default_ref(monkeypatch, tmp_path):
+ """A commit-pinned fetch writes no refs/main, so the bare id resolves nowhere.
+
+ huggingface_hub writes refs/<revision> only when revision != commit_hash, so pinning a
+ revision leaves the repo with snapshots and no ref at all. repo_id_will_not_resolve
+ reads that as fine (it only catches a ref naming a missing dir), so the row has to be
+ pinned on the absence of the ref rather than on its contents.
+ """
+ active = tmp_path / "active"
+ active.mkdir()
+ repo_dir = active / "models--Org--Pinned"
+
+ commit = "a" * 40
+ complete = repo_dir / "snapshots" / commit
+ complete.mkdir(parents = True)
+ (complete / "config.json").write_text("{}")
+ (complete / "model.safetensors").write_bytes(b"\0" * 64)
+ # No refs/ directory at all: the shape a revision=<sha> fetch leaves behind.
+
+ repo = _repo(
+ "Org/Pinned",
+ [],
+ repo_dir,
+ revisions = [
+ SimpleNamespace(files = [_file("model.safetensors", 5_000)], snapshot_path = complete),
+ ],
+ )
+
+ monkeypatch.setattr(models_route, "_cached_repo_task", lambda repo_info, selected = None: None)
+ monkeypatch.setattr(models_route, "_cached_repo_partial", lambda *args, **kwargs: False)
+ monkeypatch.setattr(
+ models_route, "_all_hf_cache_scans", lambda: [SimpleNamespace(repos = [repo])]
+ )
+ monkeypatch.setattr(models_route, "_resolve_hf_cache_dir", lambda: active)
+
+ rows = {row["repo_id"]: row for row in models_route.cached_model_rows()}
+
+ assert rows["Org/Pinned"].get("load_id") == str(complete)
+
+
+def test_cached_model_rows_keeps_a_recovered_repo_that_can_serve_a_load(monkeypatch, tmp_path):
+ """A recovery holding a self-contained snapshot is listed, pinned to it.
+
+ recovered_repo_is_unusable_by_repo_id withheld these because this schema could describe
+ neither a partial nor a path. It carries load_id now, so the row can say honestly which
+ copy to load. A recovery whose only snapshot is metadata-only stays dropped: there is
+ nothing to pin it to.
+ """
+ active = tmp_path / "active"
+ active.mkdir()
+
+ def _recovered(name, files):
+ repo_dir = active / f"models--Org--{name}"
+ snapshot = repo_dir / "snapshots" / ("b" * 40)
+ snapshot.mkdir(parents = True)
+ for filename, blob in files.items():
+ (snapshot / filename).write_bytes(blob)
+ (repo_dir / "refs").mkdir(parents = True)
+ # Dangling: names a commit with no directory, which is what recovery fires on.
+ (repo_dir / "refs" / "main").write_text("d" * 40)
+ return snapshot, _repo(
+ f"Org/{name}",
+ [],
+ repo_dir,
+ revisions = [
+ SimpleNamespace(files = [_file("model.safetensors", 5_000)], snapshot_path = snapshot),
+ ],
+ )
+
+ complete_snapshot, complete = _recovered(
+ "Whole", {"config.json": b"{}", "model.safetensors": b"\0" * 64}
+ )
+ _, metadata_only = _recovered("Half", {"config.json": b"{}"})
+
+ monkeypatch.setattr(models_route, "_cached_repo_task", lambda repo_info, selected = None: None)
+ monkeypatch.setattr(models_route, "_cached_repo_partial", lambda *args, **kwargs: False)
+ monkeypatch.setattr(
+ models_route, "_recovered_repo_is_unusable_by_repo_id", lambda repo_info: True
+ )
+ monkeypatch.setattr(
+ models_route,
+ "_all_hf_cache_scans",
+ lambda: [SimpleNamespace(repos = [complete, metadata_only])],
+ )
+ monkeypatch.setattr(models_route, "_resolve_hf_cache_dir", lambda: active)
+
+ rows = {row["repo_id"]: row for row in models_route.cached_model_rows()}
+
+ assert rows["Org/Whole"]["load_id"] == str(complete_snapshot)
+ assert "Org/Half" not in rows
+
+
# ── the architectures published CSM bundles actually declare ────────────────────
# ggml-org/sesame-csm-1b-GGUF ships its Mimi vocoder with a SENTENCE where the architecture
diff --git a/studio/backend/tests/test_hf_cache_dangling_refs.py b/studio/backend/tests/test_hf_cache_dangling_refs.py
index cf39d5aa9eb..975f46db51a 100644
--- a/studio/backend/tests/test_hf_cache_dangling_refs.py
+++ b/studio/backend/tests/test_hf_cache_dangling_refs.py
@@ -1548,18 +1548,11 @@ def test_vision_does_not_travel_between_two_cache_roots(tmp_path, monkeypatch):
# --- the chokepoints, so a new signal cannot pick its own snapshot ------------
_BACKEND = Path(__file__).resolve().parents[1]
-# Every helper the per-repo scan may hand the whole repo to. Each aggregates across revisions on
-# purpose, so a new name here is a new repo-wide signal on a one-directory row.
-_REPO_WIDE_HELPERS = frozenset(
+# helpers passed repo_info; snapshot signals also receive selected.
+_REPO_INFO_HELPERS = frozenset(
{
"_cache_inventory_fields",
- # The row's pipeline task. Repo-wide on purpose and NOT a snapshot signal: it answers "which
- # model is this", which every revision of a repo agrees on. The non-GGUF classifier returns
- # non-None only when detect_family(repo_id) does, and _repo_is_diffusers is True whenever
- # that holds, so its newest-revision _repo_has_pipeline_index branch cannot change the
- # answer; the GGUF one reads general.architecture, identical in every cached quant. Scoping
- # it would only lose rows -- an unreadable header in the one pinned snapshot would drop the
- # repo from the Images/Video pickers entirely.
+ "_cached_row_is_diffusers",
"_cached_row_task",
"_repo_gguf_last_modified",
"_repo_gguf_payload_snapshots",
@@ -1640,8 +1633,8 @@ def test_the_scan_loop_cannot_advertise_a_signal_it_did_not_scope(scan):
}
)
assert (
- set(handed_off) <= _REPO_WIDE_HELPERS
- ), f"{scan} hands the whole repo to {sorted(set(handed_off) - _REPO_WIDE_HELPERS)}"
+ set(handed_off) <= _REPO_INFO_HELPERS
+ ), f"{scan} hands repo_info to {sorted(set(handed_off) - _REPO_INFO_HELPERS)}"
@pytest.mark.parametrize("module, allowed", sorted(_MTIME_READERS.items()))
@@ -2550,10 +2543,8 @@ def test_a_nested_adapter_config_does_not_serve_the_snapshot_root(tmp_path, monk
assert rows == [] or rows[0]["partial"] is True
-def test_a_broken_active_copy_withholds_the_compatibility_row(tmp_path, monkeypatch):
- """The compatibility model list carries no path, so a client loads by id out of the active
- cache. With a broken copy there, publishing another cache's copy under the same id offers a
- load that follows the broken one. The Hub inventory still lists it, with a path."""
+def test_a_broken_active_copy_does_not_hide_a_complete_legacy_copy(tmp_path, monkeypatch):
+ """A broken active copy must not hide a complete copy the row can pin by path."""
import asyncio
import routes.models as models_route
@@ -2569,13 +2560,9 @@ def test_a_broken_active_copy_withholds_the_compatibility_row(tmp_path, monkeypa
del torn["model-00002-of-00002.safetensors"]
# Active: half a set behind a dangling ref. Legacy: the same repo, whole.
_repo_with(active, snapshots = {OLDER: torn}, refs = {"main": UPSTREAM_HEAD})
- _repo_with(legacy, snapshots = {NEWER: whole}, refs = {"main": NEWER})
+ legacy_repo = _repo_with(legacy, snapshots = {NEWER: whole}, refs = {"main": NEWER})
monkeypatch.setattr(inventory_scan, "hf_cache_roots", lambda **kw: [active, legacy])
- monkeypatch.setattr(
- "utils.hf_cache_settings.get_hf_cache_paths",
- lambda: SimpleNamespace(hub_cache = active),
- )
monkeypatch.setattr(models_route, "_resolve_hf_cache_dir", lambda: active)
inventory_scan.invalidate_hf_cache_scans()
@@ -2583,14 +2570,11 @@ def test_a_broken_active_copy_withholds_the_compatibility_row(tmp_path, monkeypa
models_route.list_cached_models(current_subject = "test-user", hf_token = None)
)
cached = response["cached"] if isinstance(response, dict) else response.cached
- assert cached == []
+ assert len(cached) == 1
+ assert cached[0]["load_id"] == str(legacy_repo / "snapshots" / NEWER)
# Control: the broken copy in the other cache leaves the active one publishable.
monkeypatch.setattr(inventory_scan, "hf_cache_roots", lambda **kw: [legacy, active])
- monkeypatch.setattr(
- "utils.hf_cache_settings.get_hf_cache_paths",
- lambda: SimpleNamespace(hub_cache = legacy),
- )
monkeypatch.setattr(models_route, "_resolve_hf_cache_dir", lambda: legacy)
inventory_scan.invalidate_hf_cache_scans()
@@ -3980,6 +3964,58 @@ def test_a_stray_base_shard_does_not_veto_a_complete_adapter(
assert rows[0]["capabilities"]["can_chat"] is True
+ ("base_config", "expected"),
+ [
+ ({"model_type": "qwen3", "architectures": ["Qwen3ForCausalLM"]}, True),
+ (
+ {
+ "model_type": "whisper",
+ "architectures": ["WhisperForConditionalGeneration"],
+ },
+ False,
+ ),
+ ],
+ ids = ["chat-base", "non-chat-base"],
+)
+def test_cached_adapter_chat_capability_uses_its_exact_cached_base(
+ base_config, expected, tmp_path, monkeypatch
+):
+ _repo_with(
+ tmp_path,
+ snapshots = {
+ SNAPSHOT: {
+ "adapter_config.json": json.dumps(
+ {
+ "base_model_name_or_path": "Org/Base",
+ "revision": SNAPSHOT,
+ "peft_type": "LORA",
+ }
+ ).encode(),
+ "adapter_model.safetensors": b"\0" * 128,
+ }
+ },
+ refs = {"main": SNAPSHOT},
+ name = "models--Org--Adapter",
+ )
+ _repo_with(
+ tmp_path,
+ snapshots = {
+ SNAPSHOT: {
+ "config.json": json.dumps(base_config).encode(),
+ "model.safetensors": b"\0" * 256,
+ }
+ },
+ refs = {"main": SNAPSHOT},
+ name = "models--Org--Base",
+ )
+
+ rows = {row["repo_id"]: row for row in _autoload_rows(tmp_path, monkeypatch)}
+
+ assert rows["Org/Adapter"]["model_format"] == "adapter"
+ assert rows["Org/Adapter"]["capabilities"]["can_chat"] is expected
+
+
@pytest.mark.parametrize(
"files, cannot_serve",
[
@@ -4037,8 +4073,13 @@ def test_the_judged_weight_family_follows_the_row_format(files, cannot_serve, tm
def _compat_cached_models(cache_root: Path, monkeypatch) -> list[str]:
- """GET /api/models/cached-models. Its schema has no partial and no load_id, so it can only
- describe a repo that loads by id."""
+ """Repo ids from GET /api/models/cached-models."""
+ return [row["repo_id"] for row in _compat_cached_rows(cache_root, monkeypatch)]
+
+
+def _compat_cached_rows(cache_root: Path, monkeypatch) -> list[dict]:
+ """GET /api/models/cached-models. Its schema carries partial and load_id, so it can describe
+ a repo pinned to a snapshot as well as one that loads by id."""
import asyncio
from types import SimpleNamespace
@@ -4056,25 +4097,33 @@ def _compat_cached_models(cache_root: Path, monkeypatch) -> list[str]:
)
finally:
inventory_scan.invalidate_hf_cache_scans()
- return [row["repo_id"] for row in response["cached"]]
+ return list(response["cached"])
@pytest.mark.parametrize(
- "snapshot_files",
+ "snapshot_files, listed",
[
- {"config.json": b"{}", "model-00001-of-00002.safetensors": b"\0" * 256},
- {"config.json": b"{}", "model.safetensors": b"\0" * 256},
+ ({"config.json": b"{}", "model-00001-of-00002.safetensors": b"\0" * 256}, False),
+ ({"config.json": b"{}", "model.safetensors": b"\0" * 256}, True),
],
ids = ["short-a-shard", "whole-but-only-loadable-by-path"],
)
def test_the_compatibility_route_withholds_a_recovery_it_cannot_describe(
- snapshot_files, tmp_path, monkeypatch
+ snapshot_files, listed, tmp_path, monkeypatch
):
- """Un-hiding a repo must not smuggle it into a response that cannot say what is wrong with it:
- with neither partial nor a load id, a torn recovery reads as a plain cached model and a whole
- one is offered under a repo id that does not resolve."""
+ """Un-hiding a repo must not smuggle it into a response that cannot say what is wrong with it.
+
+ A torn recovery stays withheld: nothing in the schema says "short a shard", so it would read
+ as a plain cached model. The whole one is no longer withheld, because the premise changed --
+ this schema now carries ``load_id``, so the row can name the snapshot to load instead of an
+ id that does not resolve. Withholding it hid a model whose weights are on disk and loadable.
+ """
_repo_with(tmp_path, snapshots = {SNAPSHOT: snapshot_files}, refs = {"main": UPSTREAM_HEAD})
- assert _compat_cached_models(tmp_path, monkeypatch) == []
+ rows = _compat_cached_rows(tmp_path, monkeypatch)
+ assert [row["repo_id"] for row in rows] == (["Org/Model"] if listed else [])
+ if listed:
+ # Pinned, since the dangling ref is exactly what the bare id cannot follow.
+ assert rows[0]["load_id"].endswith(SNAPSHOT)
# The Hub inventory still lists it, with the fields to describe it.
assert [row["repo_id"] for row in _autoload_rows(tmp_path, monkeypatch)] == ["Org/Model"]
diff --git a/studio/backend/tests/test_llama_cpp_non_chat_gguf_preflight.py b/studio/backend/tests/test_llama_cpp_non_chat_gguf_preflight.py
index 09725b8f413..4c9359f3a49 100644
--- a/studio/backend/tests/test_llama_cpp_non_chat_gguf_preflight.py
+++ b/studio/backend/tests/test_llama_cpp_non_chat_gguf_preflight.py
@@ -402,3 +402,31 @@ def test_speech_arch_names_the_audio_page(tmp_path):
assert message is not None
assert "Audio page" in message
assert "Images page" not in message
+
+
+def test_every_name_the_video_preflight_imports_from_routes_still_resolves():
+ """The preflight reaches into routes.models for the Video page's own buildability rule.
+
+ That import sits inside ``except Exception: return True``, so when a helper moves out of
+ routes.models without a compatibility alias the ImportError is swallowed and the probe
+ answers "yes, the page can build it" for a GGUF the loader cannot assemble. Nothing else
+ fails, which is why this is asserted rather than left to the arch tests: the names are
+ read out of the source so a newly added import is covered the day it lands.
+ """
+ import ast
+ import pathlib
+
+ import routes.models as models_route
+
+ source = pathlib.Path(__file__).resolve().parents[1] / "core" / "inference" / "llama_cpp.py"
+ wanted: set[str] = set()
+ for node in ast.walk(ast.parse(source.read_text(encoding = "utf-8"))):
+ if isinstance(node, ast.ImportFrom) and node.module == "routes.models":
+ wanted.update(alias.name for alias in node.names)
+
+ assert wanted, "llama_cpp.py no longer imports from routes.models; drop this test"
+ missing = sorted(name for name in wanted if not hasattr(models_route, name))
+ assert not missing, (
+ f"core/inference/llama_cpp.py imports {missing} from routes.models, but routes.models "
+ f"does not bind them. The probe's broad except turns that into a silent fail-open."
+ )
diff --git a/studio/backend/tests/test_local_model_format.py b/studio/backend/tests/test_local_model_format.py
index c88b32a8e5e..7363043390d 100644
--- a/studio/backend/tests/test_local_model_format.py
+++ b/studio/backend/tests/test_local_model_format.py
@@ -15,6 +15,7 @@ No GPU/network: only file names and sizes are inspected.
from __future__ import annotations
+import json
import sys
import types
from pathlib import Path
@@ -40,6 +41,25 @@ def _touch(path: Path) -> Path:
return path
+def test_local_adapter_chat_capability_uses_its_local_base(tmp_path):
+ from hub.services.models.common import _classify_local_path
+
+ base = tmp_path / "whisper-base"
+ _touch(base / "model.safetensors")
+ (base / "config.json").write_text(
+ '{"model_type":"whisper","architectures":["WhisperForConditionalGeneration"]}'
+ )
+ adapter = tmp_path / "whisper-adapter"
+ _touch(adapter / "adapter_model.safetensors")
+ (adapter / "adapter_config.json").write_text(json.dumps({"base_model_name_or_path": str(base)}))
+
+ rows = _classify_local_path(adapter, "custom")
+
+ assert len(rows) == 1
+ assert rows[0].base_model == str(base)
+ assert models_route._local_model_can_chat(rows[0]) is False
+
+
def test_dir_model_format_gguf_only(tmp_path):
d = tmp_path / "model"
_touch(d / "model-Q4_K_M.gguf")
@@ -356,6 +376,10 @@ def test_a_modular_pipeline_root_counts_as_a_pipeline_index(tmp_path):
(modular / "transformer").mkdir(parents = True)
(modular / "modular_model_index.json").write_text("{}")
assert _local_pipeline_index(modular) is True
+ assert (
+ models_route._local_is_diffusers(_local(modular, display_name = "opaque", id = str(modular)))
+ is True
+ )
conventional = tmp_path / "conventional"
conventional.mkdir()
@@ -365,3 +389,57 @@ def test_a_modular_pipeline_root_counts_as_a_pipeline_index(tmp_path):
neither = tmp_path / "neither"
neither.mkdir()
assert _local_pipeline_index(neither) is False
+
+
+def test_a_single_file_video_repo_is_flagged_diffusers(monkeypatch):
+ """_local_is_diffusers asks detect_video_family; _repo_is_diffusers must ask it too.
+
+ A cached single-file video checkpoint with no pipeline index gets no task from
+ _cached_repo_task (it returns None for an untrusted or unbuildable video family), so if
+ the diffusers flag is also missing, an inconclusive transformer config leaves can_chat
+ set -- and that is every gate the chat picker has. The video weights would be offered to
+ the text loader.
+ """
+ from types import SimpleNamespace
+
+ from core.inference.video_families import detect_video_family
+ from hub.services.models import catalog_classification as classification
+
+ repo_id = "Lightricks/LTX-Video"
+ assert detect_video_family(repo_id) is not None, "fixture assumes a known video family"
+
+ info = SimpleNamespace(repo_id = repo_id, repo_path = "/nonexistent")
+ assert classification._repo_is_diffusers(info) is True
+ # A plain chat repo must not be swept up by the same rule.
+ chat = SimpleNamespace(repo_id = "unsloth/Qwen3-0.6B", repo_path = "/nonexistent")
+ assert classification._repo_is_diffusers(chat) is False
+
+
+def test_adapter_base_is_found_in_the_cache_root_holding_the_adapter(tmp_path):
+ """An adapter listed from a legacy or previously configured root has its base cached in
+ that SAME root. Probing only the active root answered None, and None is inconclusive,
+ which leaves the adapter chat-capable -- so a Whisper LoRA reached the chat picker.
+ """
+ import json
+
+ from hub.services.models.common import _base_transformers_can_chat, _hub_cache_root_of
+
+ root = tmp_path / "legacy_hub"
+ base_snapshot = root / "models--Org--WhisperBase" / "snapshots" / ("b" * 40)
+ base_snapshot.mkdir(parents = True)
+ (base_snapshot / "config.json").write_text(
+ json.dumps(
+ {
+ "model_type": "whisper",
+ "architectures": ["WhisperForConditionalGeneration"],
+ }
+ )
+ )
+ (root / "models--Org--WhisperBase" / "refs").mkdir(parents = True)
+ (root / "models--Org--WhisperBase" / "refs" / "main").write_text("b" * 40)
+
+ adapter_snapshot = root / "models--Org--SpeechLora" / "snapshots" / ("a" * 40)
+ adapter_snapshot.mkdir(parents = True)
+
+ assert _hub_cache_root_of(adapter_snapshot) == root
+ assert _base_transformers_can_chat("Org/WhisperBase", None, adapter_snapshot) is False
diff --git a/tests/studio/test_model_picker_contracts.py b/tests/studio/test_model_picker_contracts.py
index 1c79b9c2be3..59381544c35 100644
--- a/tests/studio/test_model_picker_contracts.py
+++ b/tests/studio/test_model_picker_contracts.py
@@ -3547,14 +3547,16 @@ def test_variant_scans_take_the_run_signal():
def test_cached_rows_classify_chat_capability_too():
"""The same encoder gate the scan-folder rows get; cached rows built their
- capabilities from file format alone."""
+ capabilities from file format alone. Both halves are pinned separately, since
+ the gate is now nested rather than one `and`, and the call must read the
+ snapshot the load resolves to rather than any other revision."""
src = _read_backend("hub/services/models/cache_inventory.py")
assert "_local_transformers_can_chat" in src
fields = src.split("def _cache_inventory_fields", 1)[1].split("\ndef ", 1)[0]
assert "can_chat_override" in fields
- assert (
- 'model_format in {"safetensors", "checkpoint"} and classify_snapshot is not None' in fields
- )
+ assert 'model_format in {"safetensors", "checkpoint"}' in fields
+ assert "classify_snapshot is not None" in fields
+ assert "_local_transformers_can_chat(classify_snapshot)" in fields
def test_every_load_target_comparison_uses_the_same_case_rules():
diff --git a/unsloth_cli/_model_catalog.py b/unsloth_cli/_model_catalog.py
new file mode 100644
index 00000000000..b5e7f0f4661
--- /dev/null
+++ b/unsloth_cli/_model_catalog.py
@@ -0,0 +1,586 @@
+# 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 asyncio
+import os
+from dataclasses import dataclass
+from datetime import datetime
+from pathlib import Path
+from typing import List, Optional
+
+NON_CHAT_TASKS = frozenset(
+ {
+ "automatic-speech-recognition",
+ "text-to-image",
+ "text-to-video",
+ "text-to-speech",
+ "image-diffusion-unsupported",
+ }
+)
+LOCAL_SOURCES = frozenset({"models_dir", "lmstudio", "custom"})
+
+
+@dataclass
+class ModelEntry:
+ group: str
+ name: str
+ detail: str
+ model: str
+
+
+def _run_title(run: dict) -> str:
+ for key in ("display_name", "project_name", "model_name"):
+ value = (run.get(key) or "").strip()
+ if value:
+ return value.split("/")[-1]
+ return ""
+
+
+def _folder_title(folder: str) -> str:
+ name = folder.removeprefix("unsloth_")
+ stem, _, suffix = name.rpartition("_")
+ return stem if stem and suffix.isdigit() else name
+
+
+def _short_date(value) -> str:
+ try:
+ if isinstance(value, (int, float)):
+ dt = datetime.fromtimestamp(value)
+ else:
+ dt = datetime.fromisoformat(str(value)).astimezone()
+ return dt.strftime("%b %d").replace(" 0", " ")
+ except Exception:
+ return ""
+
+
+def _dataset_title(dataset: Optional[str]) -> str:
+ if not dataset:
+ return ""
+ base = os.path.basename(dataset.rstrip("/"))
+ head, sep, tail = base.partition("_")
+ if sep and len(head) == 32 and all(c in "0123456789abcdef" for c in head):
+ base = tail
+ return base.removesuffix(".jsonl").removesuffix(".json").removesuffix(".csv")
+
+
+def _run_detail(model_type: str, path: str, run: Optional[dict]) -> str:
+ parts = [] if model_type == "lora" else [model_type]
+ if run:
+ parts.append(_dataset_title(run.get("dataset_name")))
+ if run.get("final_step"):
+ parts.append(f"{run['final_step']} steps")
+ parts.append(_short_date(run.get("started_at")))
+ else:
+ try:
+ parts.append(_short_date(Path(path).stat().st_mtime))
+ except OSError:
+ pass
+ return " · ".join(p for p in parts if p)
+
+
+def _runs_by_output_dir() -> dict:
+ try:
+ from storage.studio_db import list_runs
+ runs = list_runs(limit = 1000)["runs"]
+ except Exception:
+ return {}
+ by_dir = {}
+ for run in sorted(runs, key = lambda r: r.get("started_at") or ""):
+ if run.get("output_dir"):
+ by_dir[os.path.normpath(run["output_dir"])] = run
+ return by_dir
+
+
+def _path_can_chat(path: str, base_model: Optional[str] = None) -> Optional[bool]:
+ """``False`` only for a locally identifiable non-chat checkpoint, else ``None``."""
+ try:
+ from hub.services.models.common import _local_path_can_chat
+ except ImportError:
+ return None
+ return _local_path_can_chat(path, base_model)
+
+
+def _gguf_export_task(
+ path: str,
+ name: str,
+ base_model: Optional[str] = None,
+) -> Optional[str]:
+ try:
+ from hub.services.models.catalog_classification import _gguf_path_task
+ except ImportError:
+ return None
+ return _gguf_path_task(path, (name, base_model))
+
+
+def trained_entries() -> List[ModelEntry]:
+ from utils.models import scan_trained_models
+
+ runs = _runs_by_output_dir()
+ entries = []
+ for folder, path, model_type in scan_trained_models():
+ run = runs.get(os.path.normpath(path))
+ base = run.get("model_name") if run and model_type == "lora" else None
+ if _path_can_chat(path, base) is False:
+ continue
+ name = (_run_title(run) if run else "") or _folder_title(folder)
+ entries.append(ModelEntry("Fine-tunes", name, _run_detail(model_type, path, run), path))
+ return entries
+
+
+def exported_entries() -> List[ModelEntry]:
+ from utils.models import scan_exported_models
+
+ entries = []
+ for name, path, export_type, base in scan_exported_models():
+ if _path_can_chat(path, base if export_type == "lora" else None) is False:
+ continue
+ if export_type == "gguf" and _gguf_export_task(path, name, base) in NON_CHAT_TASKS:
+ continue
+ if export_type == "gguf":
+ # No complete quant means every candidate is zero-byte or short a shard, which
+ # survives resolve_model_config() and fails only at load time. Drop it only when
+ # positively unloadable: a falsy result also means "could not tell", and hiding a
+ # real export on a transient read is worse than listing it.
+ load_id = _preferred_complete_gguf(path)
+ if not load_id and not _local_dir_holds_a_payload(Path(path)):
+ continue
+ else:
+ load_id = None
+ # Positively loadable, not merely "not torn". scan_exported_models types a
+ # checkpoint as "lora" on adapter_config.json alone, so an interrupted export
+ # leaves a config and no weights: nothing torn because there is no payload, and
+ # the picker offered a directory load_peft_weights raises ValueError on.
+ if not _local_dir_holds_a_payload(Path(path)):
+ continue
+ entries.append(ModelEntry("Fine-tunes", name, export_type, load_id or path))
+ return entries
+
+
+def _quant_labels(repo_id: str, repo_path: str) -> str:
+ from utils.models.model_config import _is_mmproj
+
+ stem = repo_id.split("/")[-1].removesuffix("-GGUF").lower()
+ quants = []
+ for file in sorted(Path(repo_path).glob("snapshots/*/*.gguf")):
+ if _is_mmproj(file.name) or file.name.lower().startswith("mtp-"):
+ continue
+ label = file.stem
+ if label.lower().startswith(stem + "-"):
+ label = label[len(stem) + 1 :]
+ if label not in quants:
+ quants.append(label)
+ return ", ".join(quants)
+
+
+def _local_payload_is_torn(path: Path) -> bool:
+ """Whether *path*'s own contents prove it cannot serve a load.
+
+ Named apart from ``routes.models._snapshot_payload_is_torn``, which shares the rule but
+ not the error policy: this one fails open, because ``_safe`` turns a raise here into an
+ empty source rather than one dropped row.
+
+ The shared rule the cache rows already use: a zero-byte weight, or a shard set naming a
+ total it does not have, is not a payload. Fails open so an unreadable dir is not hidden.
+ """
+ try:
+ from hub.utils.inventory_scan import _snapshot_cannot_serve_its_payload
+ except ImportError:
+ return False
+ try:
+ return bool(_snapshot_cannot_serve_its_payload(path))
+ except (OSError, RuntimeError, ValueError):
+ return False
+
+
+def _gguf_file_is_loadable(path: Path) -> bool:
+ """Whether a single-file GGUF can be read: non-empty, and whole if it names a shard total.
+
+ ``_snapshot_cannot_serve_its_payload`` judges a directory; a scan row can name the ``.gguf``
+ itself, and its folder may hold unrelated quants, so the file is judged on its own family.
+ """
+ try:
+ if path.stat().st_size <= 0:
+ return False
+ except OSError:
+ return True
+ try:
+ from hub.utils.inventory_scan import _GGUF_SPLIT_RE
+ except ImportError:
+ return True
+ split = _GGUF_SPLIT_RE.search(path.name)
+ if split is None:
+ return True
+ total = int(split.group(2))
+ prefix = path.name[: split.start()]
+ if int(split.group(1)) <= 0 or total <= 0 or int(split.group(1)) > total:
+ return False
+ present = set()
+ try:
+ for sibling in path.parent.iterdir():
+ match = _GGUF_SPLIT_RE.search(sibling.name)
+ if (
+ match is None
+ or sibling.name[: match.start()] != prefix
+ or int(match.group(2)) != total
+ or not sibling.is_file()
+ or sibling.stat().st_size <= 0
+ ):
+ continue
+ present.add(int(match.group(1)))
+ except OSError:
+ return True
+ return present >= set(range(1, total + 1))
+
+
+def _preferred_complete_gguf(path: str) -> Optional[str]:
+ model_path = Path(path)
+ try:
+ root = model_path.parent if model_path.is_file() else model_path
+ if not root.is_dir():
+ return None
+ from hub.utils.gguf import list_local_gguf_variants, pick_best_gguf
+ from hub.utils.inventory_scan import complete_snapshot_variants
+
+ variants, _ = list_local_gguf_variants(str(root))
+ complete = complete_snapshot_variants(str(root))
+ ready = [variant for variant in variants if variant.quant in complete]
+ root_variants = [variant for variant in ready if "/" not in variant.quant]
+ best = pick_best_gguf([variant.filename for variant in root_variants or ready])
+ candidate = root / best if best else None
+ return str(candidate) if candidate is not None and candidate.is_file() else None
+ except Exception:
+ return None
+
+
+def _cached_gguf_load_id(row: dict) -> str:
+ """A concrete local GGUF for a cached row, falling back to the identifier it came with.
+
+ An inactive-cache row already carries a snapshot path, so this resolves the quant inside it.
+ An ACTIVE-cache row carries the bare repo id, which is right for the inventory and wrong
+ for a picker: from_identifier() sends a non-path through detect_gguf_model_remote(), whose
+ GatedRepoError branch is permanent and returns None without the offline local-cache
+ fallback, so a fully downloaded gated GGUF reads as non-GGUF and hits the Transformers
+ loader. Resolving the on-disk file keeps the pick on the weights the row was listed for.
+ """
+ load_id = row.get("load_id") or row["repo_id"]
+ resolved = _preferred_complete_gguf(load_id)
+ if resolved:
+ return resolved
+ # The bare repo id is not a path, so resolve through the snapshot the row was built from.
+ cache_path = row.get("cache_path")
+ if cache_path:
+ try:
+ from hub.utils.inventory_scan import default_ref_snapshot
+ snapshot = default_ref_snapshot(Path(cache_path))
+ except Exception:
+ snapshot = None
+ if snapshot is None:
+ snapshots = sorted(Path(cache_path).glob("snapshots/*"))
+ snapshot = snapshots[-1] if snapshots else None
+ if snapshot is not None:
+ resolved = _preferred_complete_gguf(str(snapshot))
+ if resolved:
+ return resolved
+ return load_id
+
+
+def _cached_catalog_rows() -> tuple[list[dict], list[dict]]:
+ from hub.services.models.cache_inventory import (
+ _scan_cached_gguf,
+ _scan_cached_models,
+ all_hf_cache_scans,
+ )
+ from utils.hf_cache_settings import get_hf_cache_paths
+
+ scans = all_hf_cache_scans()
+ active_hub_cache = get_hf_cache_paths().hub_cache
+
+ def newest_first(rows):
+ return sorted(
+ rows,
+ key = lambda row: (-(row.get("last_modified") or 0.0), row["repo_id"].lower()),
+ )
+
+ gguf_rows = _scan_cached_gguf(cache_scans = scans, active_hub_cache = active_hub_cache)
+ model_rows = _scan_cached_models(cache_scans = scans, active_hub_cache = active_hub_cache)
+ return newest_first(gguf_rows), newest_first(model_rows)
+
+
+def cached_entries() -> List[ModelEntry]:
+ gguf_rows, model_rows = _cached_catalog_rows()
+ entries = []
+ for row in gguf_rows:
+ if (
+ row.get("partial")
+ or row.get("task") in NON_CHAT_TASKS
+ or row.get("capabilities", {}).get("can_chat") is False
+ ):
+ continue
+ entries.append(
+ ModelEntry(
+ "Downloaded",
+ row["repo_id"],
+ _quant_labels(row["repo_id"], row["cache_path"]),
+ _cached_gguf_load_id(row),
+ )
+ )
+ for row in model_rows:
+ if row.get("partial") or row.get("companion") or row.get("task") in NON_CHAT_TASKS:
+ continue
+ # A cached embedding/CLIP repo has task None like any chat repo; can_chat is the gate.
+ if row.get("capabilities", {}).get("can_chat") is False:
+ continue
+ # A diffusion repo also carries no task, and its pipeline root has no config for
+ # can_chat to read, so neither gate above catches it.
+ if row.get("diffusers"):
+ continue
+ entries.append(ModelEntry("Downloaded", row["repo_id"], "", _cached_model_load_id(row)))
+ return entries
+
+
+def _cached_model_load_id(row: dict) -> str:
+ """Load target for a cached non-GGUF row; a local snapshot for adapters.
+
+ An ACTIVE-cache adapter carries the bare repo id, and a LoRA resolved by id takes the
+ remote branch of get_base_model_from_lora_identifier, which downloads adapter_config.json
+ with no local_files_only. For a cached gated adapter with no token that fails and the base
+ is never read, so a row advertised as local yields no model configuration. A snapshot path
+ makes is_local_path true and takes the local reader instead.
+
+ Only adapters, deliberately: pinning an ordinary cached repo would freeze a live repo the
+ inventory chose not to pin.
+ """
+ load_id = row.get("load_id") or row["repo_id"]
+ if row.get("model_format") != "adapter" or os.path.isabs(str(load_id)):
+ return load_id
+ cache_path = row.get("cache_path")
+ if not cache_path:
+ return load_id
+ try:
+ from hub.utils.inventory_scan import default_ref_snapshot
+ snapshot = default_ref_snapshot(Path(cache_path))
+ except Exception:
+ snapshot = None
+ if snapshot is None:
+ snapshots = sorted(Path(cache_path).glob("snapshots/*"))
+ snapshot = snapshots[-1] if snapshots else None
+ return str(snapshot) if snapshot is not None else load_id
+
+
+def _local_dir_holds_a_payload(path: Path) -> bool:
+ """Whether a scanned local directory holds something a load can actually read.
+
+ ``_scan_models_dir`` lists a child on a config alone, so a weights-less config dir
+ arrives with ``partial`` False and the picker would offer a folder that fails on
+ selection. Anything that is not a readable directory fails open: a single-file GGUF
+ is a file, not a dir.
+ """
+ try:
+ is_dir = path.is_dir()
+ except OSError:
+ return True
+ if not is_dir:
+ # A scan row can name the .gguf file itself; anything else still fails open.
+ return _gguf_file_is_loadable(path) if path.suffix.lower() == ".gguf" else True
+ from hub.services.models.common import (
+ _is_diffusers_pipeline_dir,
+ _is_main_gguf_filename,
+ _is_model_directory,
+ )
+ from utils.paths.path_utils import is_appledouble_metadata
+
+ # A pipeline keeps its weights in component subdirs, so the torn test below reads an
+ # empty root and would call every pipeline unserviceable.
+ if _is_diffusers_pipeline_dir(path):
+ return True
+ if _local_payload_is_torn(path):
+ return False
+ # iterdir, not glob("*.gguf"): the glob is case-sensitive on Linux and macOS while
+ # _is_main_gguf_filename lowercases first, so a folder holding Model.GGUF was classified
+ # as a GGUF model and then dropped by this gate, which decides whether it is listed.
+ try:
+ children = list(path.iterdir())
+ except OSError:
+ return True
+ return any(
+ _is_main_gguf_filename(file.name) and not is_appledouble_metadata(file) for file in children
+ ) or _is_model_directory(path)
+
+
+def _local_is_a_diffusers_pipeline(model) -> bool:
+ """Whether a local row is a diffusers pipeline, which never answers a chat turn.
+
+ An unrecognised pipeline gets no task and no root config for can_chat to read, so both
+ gates pass it while the payload check accepts its pipeline index. The cached path says
+ this with the row's ``diffusers`` flag; this is the local twin.
+ """
+ from hub.services.models.catalog_classification import _local_is_diffusers
+ return bool(_local_is_diffusers(model))
+
+
+def _local_model_task(model) -> Optional[str]:
+ from hub.services.models.catalog_classification import _local_model_task as classify
+ return classify(model)
+
+
+def _local_model_can_chat(model) -> Optional[bool]:
+ from hub.services.models.catalog_classification import _local_model_can_chat as classify
+ return classify(model)
+
+
+def _local_catalog_rows():
+ from hub.services.models.local_inventory import list_local_models_response
+ response = asyncio.run(list_local_models_response(str(Path("./models").resolve())))
+ return response.models
+
+
+def _registered_custom_hf_cache(model) -> bool:
+ if model.source != "hf_cache":
+ return False
+ try:
+ from hub.storage.scan_folders import list_scan_folders
+ from hub.utils.hf_cache_state import hf_cache_roots
+ from hub.utils.paths import path_is_same_or_child
+
+ model_path = Path(model.path)
+ repo_dir = next(
+ (
+ path
+ for path in (model_path, *model_path.parents)
+ if path.name.startswith("models--")
+ ),
+ None,
+ )
+ if repo_dir is None:
+ return False
+ cache_root = repo_dir.parent
+
+ def same_path(left: Path, right: Path) -> bool:
+ return path_is_same_or_child(left, right) and path_is_same_or_child(right, left)
+
+ if any(same_path(cache_root, root) for root in hf_cache_roots()):
+ return False
+ return any(
+ same_path(cache_root, Path(folder["path"]).expanduser())
+ for folder in list_scan_folders()
+ if folder.get("path")
+ )
+ except Exception:
+ return False
+
+
+def local_folder_entries() -> List[ModelEntry]:
+ entries = []
+ for model in _local_catalog_rows():
+ if (
+ model.source not in LOCAL_SOURCES and not _registered_custom_hf_cache(model)
+ ) or model.partial:
+ continue
+ is_gguf = model.model_format == "gguf" or model.path.lower().endswith(".gguf")
+ # No format gate: _dir_model_format reports only "gguf" or None, so a safetensors
+ # checkpoint arrives as None and a "safetensors" literal dropped every non-GGUF model.
+ if _local_model_task(model) in NON_CHAT_TASKS:
+ continue
+ # No format gate, so embedding and CLIP exports get through; only this stops them.
+ if _local_model_can_chat(model) is False:
+ continue
+ if not _local_dir_holds_a_payload(Path(model.path)):
+ continue
+ if _local_is_a_diffusers_pipeline(model):
+ continue
+ target = model.load_id or model.id
+ # A GGUF DIRECTORY goes through detect_gguf_model, which sorts by size and takes the
+ # largest complete file, commonly the F16, while cached and exported rows resolve a
+ # Q4-class quant. Same folder, dramatically bigger load by source alone, so an OOM
+ # rather than a preference. Resolve it the same way here.
+ if is_gguf:
+ target = _preferred_complete_gguf(target) or target
+ entries.append(
+ ModelEntry(
+ "Downloaded",
+ model.display_name,
+ "gguf" if is_gguf else "",
+ target,
+ )
+ )
+ return entries
+
+
+def _safe(fn) -> List[ModelEntry]:
+ """Run one source, and never let it take the other three down with it.
+
+ Fails open, since a picker missing one group beats a traceback where a model list should
+ be, but not SILENTLY: a source is every downloaded model or every fine-tune, so swallowing
+ the reason turns "my HF cache is unreadable" into an empty list. UNSLOTH_DEBUG re-raises.
+ """
+ try:
+ return fn()
+ except Exception as error:
+ # Same truthy set the rest of the tree uses (utils.utils, utils.transformers_version).
+ if os.environ.get("UNSLOTH_DEBUG", "").strip().lower() in ("1", "true", "yes", "on"):
+ raise
+ # Not at module scope: this module must pull in nothing beyond the inventory layer
+ # (test_catalog_inventory_works_without_fastapi_or_routes).
+ import typer
+
+ typer.echo(
+ f"Could not read one model source ({fn.__name__}): {type(error).__name__}: {error}. "
+ f"Set UNSLOTH_DEBUG=1 for the traceback.",
+ err = True,
+ )
+ return []
+
+
+def _shorten_names(entries: List[ModelEntry]) -> None:
+ # Counted over EVERY visible label, not just the prefixed ones: a fine-tune already named
+ # Qwen3-0.6B is what an unsloth/Qwen3-0.6B row would collide with once shortened.
+ counts = {}
+ for entry in entries:
+ short = entry.name.split("/")[-1].lower()
+ counts[short] = counts.get(short, 0) + 1
+ for entry in entries:
+ if "/" not in entry.name:
+ continue
+ short = entry.name.split("/")[-1]
+ if counts[short.lower()] == 1:
+ entry.name = short
+
+
+def _dedup_key(model: str):
+ """Identity of a load target, for collapsing the same model reached by two sources.
+
+ For anything that exists on disk the filesystem is ASKED rather than guessed: two paths
+ are the same model when they are the same inode. That is the only rule that holds across
+ the three cases that actually differ, and no platform test gets all three right --
+ ``/models/Foo`` and ``/models/foo`` are two models on ext4, one model on NTFS, and one
+ model on a stock case-insensitive APFS volume, where ``os.path.normcase`` is identity and
+ would wrongly have shown the user the same model twice. It also collapses a path reached
+ once directly and once through a symlink, which the old key could not see at all.
+
+ Falling back on a string is only for what cannot be stat'd: a bare repo id, or a path that
+ has gone away since the scan. A repo id keeps the case-insensitive treatment, since the Hub
+ resolves ``Unsloth/Qwen3`` and ``unsloth/qwen3`` to one repo and the cache folds them into
+ one directory; a vanished path uses ``normcase``, which at worst leaves two rows for a model
+ that is not loadable from either of them.
+ """
+ try:
+ stat = os.stat(model)
+ return (stat.st_dev, stat.st_ino)
+ except (OSError, ValueError):
+ return os.path.normcase(model) if os.path.isabs(model) else model.lower()
+
+
+def list_chat_models() -> List[ModelEntry]:
+ entries = []
+ for fn in (trained_entries, exported_entries, cached_entries, local_folder_entries):
+ entries.extend(_safe(fn))
+ seen = set()
+ unique = []
+ for entry in entries:
+ key = _dedup_key(entry.model)
+ if key in seen:
+ continue
+ seen.add(key)
+ unique.append(entry)
+ _shorten_names(unique)
+ return unique
diff --git a/unsloth_cli/commands/chat.py b/unsloth_cli/commands/chat.py
index 423ce23e173..f9da50c2d36 100644
--- a/unsloth_cli/commands/chat.py
+++ b/unsloth_cli/commands/chat.py
@@ -127,38 +127,44 @@ def _drain_available_stdin() -> None:
return
-def _pick_trained_model(console) -> str:
+def _pick_model(console) -> str:
ensure_studio_backend_path()
- from utils.models import scan_trained_models
+ from unsloth_cli._model_catalog import list_chat_models
- trained = scan_trained_models()
- if not trained:
+ entries = list_chat_models()
+ if not entries:
typer.echo(
- "No trained models found in your outputs folder. "
- "Pass a model id or path: `unsloth chat <model>`.",
+ "No local models found. Pass a model id or path: `unsloth chat <model>`.",
err = True,
)
raise typer.Exit(code = 1)
- console.print("Your trained models (newest first):", style = "bold")
- for i, (display_name, _, model_type) in enumerate(trained, 1):
- console.print(f" {i}. {display_name} ({model_type})", markup = False)
+ console.print("Your models", style = "bold")
+ width = max(len(e.name) for e in entries)
+ group = None
+ for i, entry in enumerate(entries, 1):
+ if entry.group != group:
+ group = entry.group
+ console.print(f"\n {group}", style = "bright_black")
+ line = f" {i:>2}. {entry.name:<{width}} {entry.detail}".rstrip()
+ console.print(line, markup = False, highlight = False, soft_wrap = True)
+ console.print()
while True:
try:
- raw = input(f"Chat with [1-{len(trained)}, Enter = 1]: ").strip()
+ raw = input(f"Chat with [1-{len(entries)}, Enter = 1]: ").strip()
except (EOFError, KeyboardInterrupt):
raise typer.Exit(code = 1)
if not raw:
- return trained[0][1]
- if raw.isdigit() and 1 <= int(raw) <= len(trained):
- return trained[int(raw) - 1][1]
- console.print(f"Pick a number between 1 and {len(trained)}.", style = "yellow")
+ return entries[0].model
+ if raw.isdigit() and 1 <= int(raw) <= len(entries):
+ return entries[int(raw) - 1].model
+ console.print(f"Pick a number between 1 and {len(entries)}.", style = "yellow")
def chat(
model: Optional[str] = typer.Argument(
- None, help = "HF model id or local path. Omit to pick one of your trained models."
+ None, help = "HF model id or local path. Omit to pick one of your local models."
),
hf_token: Optional[str] = typer.Option(
None, "--hf-token", envvar = "HF_TOKEN", help = "Hugging Face token if needed."
@@ -251,7 +257,7 @@ def chat(
markup = False,
)
raise typer.Exit(code = 1)
- model = _pick_trained_model(console)
+ model = _pick_model(console)
# Resolve first so --compare can be rejected before the slow load.
with quiet_if_nonzero_mlx_rank():
diff --git a/unsloth_cli/tests/conftest.py b/unsloth_cli/tests/conftest.py
index 92c3a2f2c15..eae86dc2065 100644
--- a/unsloth_cli/tests/conftest.py
+++ b/unsloth_cli/tests/conftest.py
@@ -24,6 +24,10 @@ def _plain_cli_output(monkeypatch):
monkeypatch.delenv(var, raising = False)
monkeypatch.setenv("NO_COLOR", "1")
monkeypatch.setenv("TERM", "dumb")
+ # UNSLOTH_DEBUG makes the catalog re-raise a failing source instead of reporting it, so a
+ # developer who exports it fails every test that drives a source into a raise. The one
+ # test that wants it sets it itself.
+ monkeypatch.delenv("UNSLOTH_DEBUG", raising = False)
@pytest.fixture
diff --git a/unsloth_cli/tests/test_inference_chat.py b/unsloth_cli/tests/test_inference_chat.py
index 648ade6af88..2ffd45a2b70 100644
--- a/unsloth_cli/tests/test_inference_chat.py
+++ b/unsloth_cli/tests/test_inference_chat.py
@@ -7,6 +7,7 @@ from __future__ import annotations
import inspect
import json
+import subprocess
import sys
import types
from pathlib import Path
@@ -331,19 +332,494 @@ def test_chat_exits_cleanly_on_slash_exit(monkeypatch):
assert "You: You:" not in result.output
-def test_pick_trained_model_lists_and_selects(monkeypatch):
+def test_pick_model_lists_groups_and_selects(monkeypatch):
+ from unsloth_cli import _model_catalog as cat
+
+ entries = [
+ cat.ModelEntry("Fine-tunes", "run-new", "lora · Aug 1", "outputs/run-new"),
+ cat.ModelEntry("Fine-tunes", "run-old", "merged", "outputs/run-old"),
+ cat.ModelEntry("GGUF", "org/Tiny-GGUF", "Q4_K_M", "org/Tiny-GGUF"),
+ ]
+ monkeypatch.setattr(cat, "list_chat_models", lambda: entries)
+ monkeypatch.setattr(chatmod, "ensure_studio_backend_path", lambda: None)
+
+ console = Console(record = True, width = 100)
+ monkeypatch.setattr("builtins.input", lambda prompt = "": "3")
+ assert chatmod._pick_model(console) == "org/Tiny-GGUF"
+ out = console.export_text()
+ assert "Fine-tunes" in out and "GGUF" in out
+ assert "1. run-new" in out and "lora · Aug 1" in out
+ assert "3. org/Tiny-GGUF" in out
+
+ monkeypatch.setattr("builtins.input", lambda prompt = "": "")
+ assert chatmod._pick_model(Console()) == "outputs/run-new"
+
+
+def test_pick_model_exits_when_nothing_found(monkeypatch):
+ from unsloth_cli import _model_catalog as cat
+
+ monkeypatch.setattr(cat, "list_chat_models", lambda: [])
+ monkeypatch.setattr(chatmod, "ensure_studio_backend_path", lambda: None)
+ with pytest.raises(typer.Exit):
+ chatmod._pick_model(Console())
+
+
+def test_catalog_trained_entries_use_run_metadata(monkeypatch, tmp_path):
+ from unsloth_cli import _model_catalog as cat
+
+ named = tmp_path / "unsloth_Llama-3.2-1B-Instruct_1785529397"
+ bare = tmp_path / "unsloth_Qwen3-0.6B_1785529000"
+ named.mkdir()
+ bare.mkdir()
fake_models = types.ModuleType("utils.models")
fake_models.scan_trained_models = lambda: [
- ("run-new", "outputs/run-new", "lora"),
- ("run-old", "outputs/run-old", "merged"),
+ (named.name, str(named), "lora"),
+ (bare.name, str(bare), "merged"),
]
monkeypatch.setitem(sys.modules, "utils.models", fake_models)
+ monkeypatch.setattr(
+ cat,
+ "_runs_by_output_dir",
+ lambda: {
+ str(named): {
+ "display_name": "support-bot",
+ "model_name": "unsloth/Llama-3.2-1B-Instruct",
+ "dataset_name": "/x/uploads/0123456789abcdef0123456789abcdef_tickets.jsonl",
+ "started_at": "2026-07-31T20:23:09+00:00",
+ "final_step": 30,
+ "final_loss": 2.4368,
+ }
+ },
+ )
- monkeypatch.setattr("builtins.input", lambda prompt = "": "2")
- assert chatmod._pick_trained_model(Console()) == "outputs/run-old"
+ first, second = cat.trained_entries()
+ assert (first.group, first.name, first.model) == ("Fine-tunes", "support-bot", str(named))
+ assert first.detail.startswith("tickets · 30 steps · ")
+ assert second.name == "Qwen3-0.6B"
+ assert second.detail.startswith("merged · ")
- monkeypatch.setattr("builtins.input", lambda prompt = "": "")
- assert chatmod._pick_trained_model(Console()) == "outputs/run-new"
+
+def test_catalog_cached_entries_filter_non_chat_rows(monkeypatch, tmp_path):
+ from unsloth_cli import _model_catalog as cat
+
+ repo = tmp_path / "models--org--Tiny-GGUF"
+ snap = repo / "snapshots" / "abc"
+ snap.mkdir(parents = True)
+ for name in ("Tiny-Q4_K_M.gguf", "Tiny-Q2_K.gguf", "mmproj-F16.gguf"):
+ (snap / name).write_bytes(b"")
+
+ gguf_rows = [
+ {"repo_id": "org/Tiny-GGUF", "cache_path": str(repo), "task": "text-generation"},
+ {
+ "repo_id": "org/Half-GGUF",
+ "cache_path": str(repo),
+ "task": "text-generation",
+ "partial": True,
+ },
+ {"repo_id": "org/Flux-GGUF", "cache_path": str(repo), "task": "text-to-image"},
+ {
+ "repo_id": "unsloth/Qwen3-ASR-GGUF",
+ "cache_path": str(repo),
+ "task": "text-generation",
+ "capabilities": {"can_chat": False},
+ },
+ ]
+ model_rows = [
+ {"repo_id": "org/Chat", "task": None},
+ {"repo_id": "org/Half", "task": None, "partial": True},
+ {"repo_id": "org/Image", "task": "text-to-image"},
+ {"repo_id": "org/TTS", "task": "text-to-speech"},
+ {"repo_id": "org/Pinned", "task": None, "load_id": "/snap/path"},
+ {
+ "repo_id": "org/ChatAdapter",
+ "task": None,
+ "model_format": "adapter",
+ "load_id": "/snap/chat-adapter",
+ "capabilities": {"can_chat": True},
+ },
+ {
+ "repo_id": "org/SpeechAdapter",
+ "task": None,
+ "model_format": "adapter",
+ "capabilities": {"can_chat": False},
+ },
+ # An embedding/CLIP repo carries task None like any chat repo; can_chat separates them.
+ {"repo_id": "org/Embedder", "task": None, "capabilities": {"can_chat": False}},
+ # An untrusted diffusion repo carries no task either, and its pipeline root has no
+ # config for can_chat to read, so only its own flag keeps it out of chat.
+ {"repo_id": "org/Sdxl", "task": None, "diffusers": True},
+ ]
+ fake_cfg = types.ModuleType("utils.models.model_config")
+ fake_cfg._is_mmproj = lambda name: "mmproj" in name.lower()
+ monkeypatch.setitem(sys.modules, "utils.models.model_config", fake_cfg)
+ monkeypatch.setattr(cat, "_cached_catalog_rows", lambda: (gguf_rows, model_rows))
+
+ entries = cat.cached_entries()
+ assert [(e.group, e.name, e.detail, e.model) for e in entries] == [
+ ("Downloaded", "org/Tiny-GGUF", "Q2_K, Q4_K_M", "org/Tiny-GGUF"),
+ ("Downloaded", "org/Chat", "", "org/Chat"),
+ ("Downloaded", "org/Pinned", "", "/snap/path"),
+ ("Downloaded", "org/ChatAdapter", "", "/snap/chat-adapter"),
+ ]
+
+
+def test_catalog_pinned_cached_gguf_uses_the_preferred_complete_quant(monkeypatch, tmp_path):
+ from unsloth_cli._inference import ensure_studio_backend_path
+ from unsloth_cli import _model_catalog as cat
+
+ ensure_studio_backend_path()
+ from utils.models.model_config import detect_gguf_model
+
+ repo = tmp_path / "legacy" / "models--org--Multi-GGUF"
+ snapshot = repo / "snapshots" / "revision"
+ snapshot.mkdir(parents = True)
+ (snapshot / "Model-F16.gguf").write_bytes(b"f" * 1024)
+ first = snapshot / "Model-Q4_K_M-00001-of-00002.gguf"
+ first.write_bytes(b"q" * 256)
+ (snapshot / "Model-Q4_K_M-00002-of-00002.gguf").write_bytes(b"q" * 256)
+ (snapshot / "mmproj-F16.gguf").write_bytes(b"m" * 2048)
+
+ monkeypatch.setattr(
+ cat,
+ "_cached_catalog_rows",
+ lambda: (
+ [
+ {
+ "repo_id": "org/Multi-GGUF",
+ "cache_path": str(repo),
+ "load_id": str(snapshot),
+ "task": "text-generation",
+ }
+ ],
+ [],
+ ),
+ )
+
+ assert Path(detect_gguf_model(str(snapshot))).name == "Model-F16.gguf"
+ assert cat.cached_entries()[0].model == str(first)
+
+
+def test_catalog_exported_gguf_uses_the_preferred_complete_quant(monkeypatch, tmp_path):
+ from unsloth_cli._inference import ensure_studio_backend_path
+ from unsloth_cli import _model_catalog as cat
+
+ ensure_studio_backend_path()
+ export = tmp_path / "exports" / "multi-quant"
+ export.mkdir(parents = True)
+ f16 = export / "Model-F16.gguf"
+ f16.write_bytes(b"f" * 1024)
+ first = export / "Model-Q4_K_M-00001-of-00002.gguf"
+ first.write_bytes(b"q" * 256)
+ (export / "Model-Q4_K_M-00002-of-00002.gguf").write_bytes(b"q" * 256)
+
+ fake_models = types.ModuleType("utils.models")
+ fake_models.scan_exported_models = lambda: [
+ ("multi-quant", str(f16), "gguf", None),
+ ]
+ monkeypatch.setitem(sys.modules, "utils.models", fake_models)
+ monkeypatch.setattr(cat, "_path_can_chat", lambda *_args: None)
+ monkeypatch.setattr(cat, "_gguf_export_task", lambda *_args: "text-generation")
+
+ assert cat.exported_entries()[0].model == str(first)
+
+
+def test_catalog_keeps_only_custom_unconfigured_hf_cache_rows(monkeypatch, tmp_path):
+ from unsloth_cli._inference import ensure_studio_backend_path
+ from unsloth_cli import _model_catalog as cat
+
+ ensure_studio_backend_path()
+ from hub.storage import scan_folders
+ from hub.utils import hf_cache_state
+
+ class _LocalModelInfo:
+ def __init__(self, path):
+ self.id = path
+ self.load_id = path
+ self.display_name = Path(path).parents[1].name.rsplit("--", 1)[-1]
+ self.path = path
+ self.source = "hf_cache"
+ self.model_format = "safetensors"
+ self.partial = False
+
+ custom_root = tmp_path / "custom-cache"
+ custom_snapshot = custom_root / "models--org--Custom" / "snapshots" / "revision"
+ custom_snapshot.mkdir(parents = True)
+ (custom_snapshot / "config.json").write_text(json.dumps({"model_type": "qwen3"}))
+ (custom_snapshot / "model.safetensors").write_bytes(b"weights")
+ configured_root = tmp_path / "configured-cache"
+ configured_snapshot = configured_root / "models--org--Configured" / "snapshots" / "revision"
+ configured_snapshot.mkdir(parents = True)
+ (configured_snapshot / "config.json").write_text(json.dumps({"model_type": "qwen3"}))
+ (configured_snapshot / "model.safetensors").write_bytes(b"weights")
+
+ monkeypatch.setattr(
+ cat,
+ "_local_catalog_rows",
+ lambda: [_LocalModelInfo(str(custom_snapshot)), _LocalModelInfo(str(configured_snapshot))],
+ )
+ monkeypatch.setattr(scan_folders, "list_scan_folders", lambda: [{"path": str(custom_root)}])
+ monkeypatch.setattr(hf_cache_state, "hf_cache_roots", lambda: [configured_root])
+ monkeypatch.setattr(cat, "_local_model_task", lambda _model: None)
+ monkeypatch.setattr(cat, "_local_model_can_chat", lambda _model: None)
+ monkeypatch.setattr(cat, "_local_is_a_diffusers_pipeline", lambda _model: False)
+
+ entries = cat.local_folder_entries()
+
+ assert [(entry.name, entry.model) for entry in entries] == [("Custom", str(custom_snapshot))]
+
+
+def test_catalog_inventory_works_without_fastapi_or_routes():
+ script = """
+import builtins
+from unsloth_cli._inference import ensure_studio_backend_path
+
+ensure_studio_backend_path()
+real_import = builtins.__import__
+
+def import_without_server(name, *args, **kwargs):
+ if name == "fastapi" or name.startswith("fastapi.") or name == "routes" or name.startswith("routes."):
+ raise AssertionError(f"server import: {name}")
+ return real_import(name, *args, **kwargs)
+
+builtins.__import__ = import_without_server
+from hub.services.models import cache_inventory, catalog_classification, local_inventory
+from unsloth_cli import _model_catalog
+assert cache_inventory and catalog_classification and local_inventory and _model_catalog
+cache_inventory.all_hf_cache_scans = lambda: []
+cache_inventory._scan_cached_gguf = lambda **kwargs: []
+cache_inventory._scan_cached_models = lambda **kwargs: []
+assert _model_catalog.cached_entries() == []
+
+async def empty_local_models(_models_dir):
+ return type("Response", (), {"models": []})()
+
+local_inventory.list_local_models_response = empty_local_models
+assert _model_catalog.local_folder_entries() == []
+"""
+ result = subprocess.run(
+ [sys.executable, "-c", script],
+ cwd = _REPO_ROOT,
+ capture_output = True,
+ text = True,
+ check = False,
+ )
+ assert result.returncode == 0, result.stderr
+
+
+def test_catalog_local_folder_entries_keep_safetensors_and_use_id(monkeypatch):
+ from unsloth_cli._inference import ensure_studio_backend_path
+ from unsloth_cli import _model_catalog as cat
+
+ ensure_studio_backend_path()
+
+ class _LocalModelInfo:
+ """Mirrors the catalog fields used from LocalModelInfo."""
+
+ def __init__(
+ self,
+ id,
+ display_name,
+ path,
+ source,
+ model_format = None,
+ partial = False,
+ load_id = None,
+ ):
+ self.id = id
+ self.display_name = display_name
+ self.path = path
+ self.source = source
+ self.model_format = model_format
+ self.partial = partial
+ self.load_id = load_id
+
+ rows = [
+ # _dir_model_format reports None for a safetensors folder, never "safetensors".
+ _LocalModelInfo("/models/Qwen3-0.6B", "Qwen3-0.6B", "/models/Qwen3-0.6B", "models_dir"),
+ _LocalModelInfo("/m/Tiny.gguf", "Tiny", "/m/Tiny.gguf", "lmstudio", model_format = "gguf"),
+ _LocalModelInfo("/models/Half", "Half", "/models/Half", "models_dir", partial = True),
+ _LocalModelInfo("/models/MiniLM", "MiniLM", "/models/MiniLM", "models_dir"),
+ # the cli has no studio load-route materializer for this opaque identifier.
+ _LocalModelInfo(
+ "ollama-manifest:%2Fmodels%2Fmanifests%2Fqwen",
+ "Ollama Qwen",
+ "/models/blobs/sha256-deadbeef",
+ "ollama",
+ model_format = "gguf",
+ load_id = "ollama-manifest:%2Fmodels%2Fmanifests%2Fqwen",
+ ),
+ ]
+
+ monkeypatch.setattr(cat, "_local_catalog_rows", lambda: rows)
+ monkeypatch.setattr(cat, "_local_model_task", lambda model: None)
+ monkeypatch.setattr(
+ cat,
+ "_local_model_can_chat",
+ lambda model: (False if model.display_name == "MiniLM" else None),
+ )
+
+ entries = cat.local_folder_entries()
+ assert [(e.group, e.name, e.detail, e.model) for e in entries] == [
+ ("Downloaded", "Qwen3-0.6B", "", "/models/Qwen3-0.6B"),
+ ("Downloaded", "Tiny", "gguf", "/m/Tiny.gguf"),
+ ]
+
+
+def test_catalog_dedupes_and_survives_failing_sources(monkeypatch):
+ from unsloth_cli import _model_catalog as cat
+
+ def boom():
+ raise RuntimeError("no studio db")
+
+ monkeypatch.setattr(cat, "trained_entries", boom)
+ # The SAME load target reached by two sources is one model, and the first source wins.
+ monkeypatch.setattr(cat, "exported_entries", lambda: [cat.ModelEntry("Exports", "a", "", "/A")])
+ monkeypatch.setattr(cat, "cached_entries", lambda: [cat.ModelEntry("GGUF", "b", "", "/A")])
+ monkeypatch.setattr(cat, "local_folder_entries", lambda: [])
+ assert [e.name for e in cat.list_chat_models()] == ["a"]
+
+
+def test_catalog_keeps_case_distinct_local_paths_where_the_filesystem_does(monkeypatch, tmp_path):
+ """``Foo`` and ``foo`` are two models on ext4 and one model on NTFS or a stock APFS volume.
+
+ Built on the real filesystem and asked of it, rather than decided from ``sys.platform`` or
+ from ``os.path.normcase`` -- normcase is identity on macOS, where the DEFAULT volume is
+ case-insensitive, so a platform test gets that case exactly backwards. Whatever this
+ filesystem does, the picker must agree with it: one directory, one row.
+ """
+ from unsloth_cli import _model_catalog as cat
+
+ upper = tmp_path / "Foo"
+ upper.mkdir()
+ (upper / "config.json").write_text("{}")
+ lower = tmp_path / "foo"
+ case_sensitive_fs = not lower.exists()
+ if case_sensitive_fs:
+ lower.mkdir()
+ (lower / "config.json").write_text("{}")
+
+ for name in ("trained_entries", "exported_entries", "cached_entries"):
+ monkeypatch.setattr(cat, name, lambda: [])
+ monkeypatch.setattr(
+ cat,
+ "local_folder_entries",
+ lambda: [
+ cat.ModelEntry("Downloaded", "Foo", "", str(upper)),
+ cat.ModelEntry("Downloaded", "foo", "", str(lower)),
+ ],
+ )
+ names = [e.name for e in cat.list_chat_models()]
+ assert names == (["Foo", "foo"] if case_sensitive_fs else ["Foo"])
+
+
+def test_catalog_collapses_a_model_reached_twice_through_a_symlink(monkeypatch, tmp_path):
+ """Two sources naming one model by different paths is one row.
+
+ The scan folder and the models dir can both cover the same directory through a link, which
+ a string key cannot see through however it is cased.
+ """
+ import pytest
+
+ from unsloth_cli import _model_catalog as cat
+
+ real = tmp_path / "real"
+ real.mkdir()
+ (real / "config.json").write_text("{}")
+ link = tmp_path / "link"
+ try:
+ link.symlink_to(real, target_is_directory = True)
+ except (OSError, NotImplementedError):
+ pytest.skip("this filesystem does not support symlinks")
+
+ for name in ("trained_entries", "exported_entries"):
+ monkeypatch.setattr(cat, name, lambda: [])
+ monkeypatch.setattr(
+ cat,
+ "cached_entries",
+ lambda: [
+ cat.ModelEntry("Downloaded", "real", "", str(real)),
+ ],
+ )
+ monkeypatch.setattr(
+ cat,
+ "local_folder_entries",
+ lambda: [
+ cat.ModelEntry("Downloaded", "link", "", str(link)),
+ ],
+ )
+ assert [e.name for e in cat.list_chat_models()] == ["real"]
+
+
+def test_catalog_still_folds_case_on_bare_repo_ids(monkeypatch):
+ """A repo id is not a path. The Hub resolves ``Unsloth/Qwen3`` and ``unsloth/qwen3`` to one
+ repo and the cache folds them into one directory, so these stay a single row everywhere."""
+ from unsloth_cli import _model_catalog as cat
+
+ for name in ("trained_entries", "exported_entries", "local_folder_entries"):
+ monkeypatch.setattr(cat, name, lambda: [])
+ monkeypatch.setattr(
+ cat,
+ "cached_entries",
+ lambda: [
+ cat.ModelEntry("Downloaded", "Unsloth/Qwen3-0.6B", "", "Unsloth/Qwen3-0.6B"),
+ cat.ModelEntry("Downloaded", "unsloth/qwen3-0.6b", "", "unsloth/qwen3-0.6b"),
+ ],
+ )
+ assert len(cat.list_chat_models()) == 1
+
+
+def test_a_failing_source_says_so_instead_of_vanishing(monkeypatch, capsys):
+ """A source is ALL of your downloaded models or ALL of your fine-tunes. Returning [] with
+ no word for it turns an unreadable HF cache into a picker that is simply missing half its
+ content, with nothing for the user to act on."""
+ from unsloth_cli import _model_catalog as cat
+
+ monkeypatch.delenv("UNSLOTH_DEBUG", raising = False)
+ for name in ("trained_entries", "exported_entries", "local_folder_entries"):
+ monkeypatch.setattr(cat, name, lambda: [])
+
+ def boom():
+ raise OSError("cache is on a dead mount")
+
+ monkeypatch.setattr(cat, "cached_entries", boom)
+ assert cat.list_chat_models() == []
+ assert "cache is on a dead mount" in capsys.readouterr().err
+
+
+def test_unsloth_debug_re_raises_a_failing_source(monkeypatch):
+ """When the empty group IS the bug, the traceback is the thing you need."""
+ import pytest
+
+ from unsloth_cli import _model_catalog as cat
+
+ monkeypatch.setenv("UNSLOTH_DEBUG", "1")
+ for name in ("trained_entries", "exported_entries", "local_folder_entries"):
+ monkeypatch.setattr(cat, name, lambda: [])
+
+ def boom():
+ raise OSError("cache is on a dead mount")
+
+ monkeypatch.setattr(cat, "cached_entries", boom)
+ with pytest.raises(OSError, match = "dead mount"):
+ cat.list_chat_models()
+
+
+def test_catalog_drops_org_prefix_unless_ambiguous(monkeypatch):
+ from unsloth_cli import _model_catalog as cat
+
+ rows = [
+ cat.ModelEntry("Downloaded", "unsloth/Qwen3-1.7B", "", "unsloth/Qwen3-1.7B"),
+ cat.ModelEntry("Downloaded", "Qwen/Qwen3-0.6B", "", "Qwen/Qwen3-0.6B"),
+ cat.ModelEntry("Downloaded", "unsloth/qwen3-0.6b", "", "unsloth/qwen3-0.6b"),
+ ]
+ for name in ("trained_entries", "exported_entries", "local_folder_entries"):
+ monkeypatch.setattr(cat, name, lambda: [])
+ monkeypatch.setattr(cat, "cached_entries", lambda: rows)
+ assert [e.name for e in cat.list_chat_models()] == [
+ "Qwen3-1.7B",
+ "Qwen/Qwen3-0.6B",
+ "unsloth/qwen3-0.6b",
+ ]
def test_chat_no_arg_chats_with_picked_trained_model(monkeypatch):
@@ -355,7 +831,7 @@ def test_chat_no_arg_chats_with_picked_trained_model(monkeypatch):
pass
resolved = []
- monkeypatch.setattr(chatmod, "_pick_trained_model", lambda console: "outputs/run-42")
+ monkeypatch.setattr(chatmod, "_pick_model", lambda console: "outputs/run-42")
monkeypatch.setattr(
chatmod,
"resolve_model_config",
@@ -1461,3 +1937,502 @@ def test_load_chat_backend_forwards_mlx_distributed_options(monkeypatch):
assert calls[0]["tensor_parallel"] is True
assert calls[0]["mlx_distributed"] is True
+
+
+def test_catalog_local_folder_entries_require_loadable_payloads(monkeypatch, tmp_path):
+ """Config-only and GGUF-companion directories are not selectable model payloads."""
+ from unsloth_cli._inference import ensure_studio_backend_path
+ from unsloth_cli import _model_catalog as cat
+
+ ensure_studio_backend_path()
+
+ class _LocalModelInfo:
+ def __init__(
+ self,
+ id,
+ display_name,
+ path,
+ source,
+ model_format = None,
+ partial = False,
+ ):
+ self.id = id
+ self.display_name = display_name
+ self.path = path
+ self.source = source
+ self.model_format = model_format
+ self.partial = partial
+ self.load_id = None
+
+ def _dir(name, files):
+ d = tmp_path / name
+ d.mkdir()
+ for file in files:
+ # A config has to parse: an unreadable one is its own reason not to load.
+ if file.endswith("config.json"):
+ (d / file).write_text(json.dumps({"model_type": "qwen3"}))
+ else:
+ (d / file).write_bytes(b"\0" * 8)
+ return d
+
+ config_only = _dir("ConfigOnly", ["config.json"])
+ real = _dir("Real", ["config.json", "model.safetensors"])
+ gguf_folder = _dir("GgufFolder", ["Qwen3-0.6B-Q4_K_M.gguf"])
+ companions = _dir("Companions", ["mmproj-F16.gguf", "mtp-drafter-Q8_0.gguf"])
+ pipeline = _dir("Pipeline", ["model_index.json"])
+ (pipeline / "unet").mkdir()
+ modular = _dir("OpaqueModular", ["modular_model_index.json"])
+ (modular / "transformer").mkdir()
+ single_file = tmp_path / "Tiny.gguf"
+ single_file.write_bytes(b"\0" * 8)
+
+ rows = [
+ _LocalModelInfo(str(real), "Real", str(real), "models_dir"),
+ _LocalModelInfo(str(config_only), "ConfigOnly", str(config_only), "models_dir"),
+ _LocalModelInfo(
+ str(gguf_folder), "GgufFolder", str(gguf_folder), "models_dir", model_format = "gguf"
+ ),
+ _LocalModelInfo(str(companions), "Companions", str(companions), "models_dir"),
+ _LocalModelInfo(str(pipeline), "Pipeline", str(pipeline), "custom"),
+ _LocalModelInfo(str(modular), "OpaqueModular", str(modular), "custom"),
+ _LocalModelInfo(
+ str(single_file), "Tiny", str(single_file), "lmstudio", model_format = "gguf"
+ ),
+ ]
+
+ monkeypatch.setattr(cat, "_local_catalog_rows", lambda: rows)
+ monkeypatch.setattr(cat, "_local_model_task", lambda model: None)
+ monkeypatch.setattr(cat, "_local_model_can_chat", lambda model: None)
+ monkeypatch.setattr(
+ cat,
+ "_local_is_a_diffusers_pipeline",
+ lambda model: (
+ (Path(model.path) / "model_index.json").is_file()
+ or (Path(model.path) / "modular_model_index.json").is_file()
+ ),
+ )
+
+ # The pipeline still HOLDS a payload; it is excluded from the chat picker for the
+ # separate reason that a diffusers pipeline cannot answer a text turn.
+ assert cat._local_dir_holds_a_payload(pipeline) is True
+ assert cat._local_dir_holds_a_payload(modular) is True
+ assert cat._local_dir_holds_a_payload(companions) is False
+
+ assert [e.name for e in cat.local_folder_entries()] == ["Real", "GgufFolder", "Tiny"]
+
+
+def test_catalog_trained_and_exported_entries_drop_non_chat_checkpoints(monkeypatch, tmp_path):
+ """Studio trains Whisper and other audio models, so an outputs or exports folder
+ legitimately holds a checkpoint that cannot answer a text turn. Neither builder
+ classified anything, so both offered it for chat."""
+ from unsloth_cli._inference import ensure_studio_backend_path
+ from unsloth_cli import _model_catalog as cat
+
+ ensure_studio_backend_path()
+ from hub.services.models import catalog_classification
+
+ def _ckpt(parent, name, config):
+ d = parent / name
+ d.mkdir(parents = True)
+ (d / "config.json").write_text(json.dumps(config))
+ (d / "model.safetensors").write_bytes(b"\0" * 8)
+ return d
+
+ def _adapter(parent, name, base):
+ d = parent / name
+ d.mkdir(parents = True)
+ config = {"base_model_name_or_path": str(base)} if base else {}
+ (d / "adapter_config.json").write_text(json.dumps(config))
+ (d / "adapter_model.safetensors").write_bytes(b"\0" * 8)
+ return d
+
+ whisper = {"model_type": "whisper", "architectures": ["WhisperForConditionalGeneration"]}
+ causal = {"model_type": "qwen3", "architectures": ["Qwen3ForCausalLM"]}
+ trained_whisper = _ckpt(tmp_path / "outputs", "whisper-finetune", whisper)
+ trained_chat = _ckpt(tmp_path / "outputs", "qwen-finetune", causal)
+ trained_whisper_adapter = _adapter(tmp_path / "outputs", "whisper-adapter", trained_whisper)
+ trained_chat_adapter = _adapter(tmp_path / "outputs", "qwen-adapter", trained_chat)
+ trained_run_adapter = _adapter(tmp_path / "outputs", "run-whisper-adapter", None)
+ exported_whisper = _ckpt(tmp_path / "exports", "checkpoint-whisper", whisper)
+ exported_chat = _ckpt(tmp_path / "exports", "checkpoint-qwen", causal)
+ exported_whisper_adapter = _adapter(
+ tmp_path / "exports", "checkpoint-whisper-adapter", trained_whisper
+ )
+ exported_gguf = tmp_path / "exports" / "run-gguf" / "model-Q4_K_M.gguf"
+ exported_gguf.parent.mkdir(parents = True)
+ exported_gguf.write_bytes(b"\0" * 8)
+ exported_image_gguf = tmp_path / "exports" / "run-image-gguf" / "model-Q4_K_M.gguf"
+ exported_image_gguf.parent.mkdir(parents = True)
+ exported_image_gguf.write_bytes(b"\0" * 8)
+ exported_asr_gguf = tmp_path / "exports" / "dictation" / "model-Q8_0.gguf"
+ exported_asr_gguf.parent.mkdir(parents = True)
+ exported_asr_gguf.write_bytes(b"\0" * 8)
+
+ fake_models = types.ModuleType("utils.models")
+ fake_models.scan_trained_models = lambda: [
+ (trained_whisper.name, str(trained_whisper), "merged"),
+ (trained_chat.name, str(trained_chat), "merged"),
+ (trained_whisper_adapter.name, str(trained_whisper_adapter), "lora"),
+ (trained_chat_adapter.name, str(trained_chat_adapter), "lora"),
+ (trained_run_adapter.name, str(trained_run_adapter), "lora"),
+ ]
+ fake_models.scan_exported_models = lambda: [
+ ("whisper-export", str(exported_whisper), "merged", None),
+ ("qwen-export", str(exported_chat), "merged", None),
+ ("whisper-adapter", str(exported_whisper_adapter), "lora", str(trained_whisper)),
+ ("gguf-export", str(exported_gguf), "gguf", None),
+ ("image-gguf-export", str(exported_image_gguf), "gguf", None),
+ (
+ "dictation",
+ str(exported_asr_gguf),
+ "gguf",
+ "Qwen/Qwen3-ASR-0.6B",
+ ),
+ ]
+ monkeypatch.setitem(sys.modules, "utils.models", fake_models)
+ monkeypatch.setattr(
+ cat,
+ "_runs_by_output_dir",
+ lambda: {str(trained_run_adapter): {"model_name": str(trained_whisper)}},
+ )
+
+ monkeypatch.setattr(
+ catalog_classification,
+ "_gguf_architecture",
+ lambda path: (
+ "flux"
+ if Path(path) == exported_image_gguf
+ else "qwen3"
+ if Path(path) == exported_asr_gguf
+ else "llama"
+ ),
+ )
+
+ assert [e.name for e in cat.trained_entries()] == ["qwen-finetune", "qwen-adapter"]
+ assert [e.name for e in cat.exported_entries()] == ["qwen-export", "gguf-export"]
+
+
+def test_catalog_adapter_classifies_the_exact_cached_base_revision(monkeypatch, tmp_path):
+ from unsloth_cli import _model_catalog as cat
+
+ monkeypatch.syspath_prepend(str(_REPO_ROOT / "studio" / "backend"))
+ import huggingface_hub
+ from utils import hf_cache_settings
+
+ adapter = tmp_path / "adapter"
+ adapter.mkdir()
+ (adapter / "adapter_config.json").write_text(
+ json.dumps(
+ {
+ "base_model_name_or_path": "openai/whisper-large-v3",
+ "revision": "base-commit",
+ }
+ )
+ )
+ (adapter / "adapter_model.safetensors").write_bytes(b"\0" * 8)
+ base = tmp_path / "cache" / "models--openai--whisper-large-v3" / "snapshots" / "base-commit"
+ base.mkdir(parents = True)
+ (base / "config.json").write_text(json.dumps({"model_type": "whisper"}))
+
+ calls = []
+
+ def _cached(repo_id, filename, *, cache_dir, revision):
+ calls.append((repo_id, filename, cache_dir, revision))
+ return str(base / filename)
+
+ monkeypatch.setattr(huggingface_hub, "try_to_load_from_cache", _cached)
+ monkeypatch.setattr(
+ hf_cache_settings,
+ "get_hf_cache_paths",
+ lambda: types.SimpleNamespace(hub_cache = tmp_path / "cache"),
+ )
+
+ assert cat._path_can_chat(str(adapter)) is False
+ assert calls == [
+ (
+ "openai/whisper-large-v3",
+ "config.json",
+ tmp_path / "cache",
+ "base-commit",
+ )
+ ]
+
+
+def _catalog_local_row(
+ path,
+ name = None,
+ source = "models_dir",
+ model_format = None,
+):
+ return types.SimpleNamespace(
+ id = str(path),
+ display_name = name or Path(path).name,
+ path = str(path),
+ source = source,
+ model_format = model_format,
+ partial = False,
+ load_id = None,
+ )
+
+
+def test_catalog_rejects_incomplete_local_and_exported_payloads(monkeypatch, tmp_path):
+ """A zero-byte weight and a shard set short of its own total are not payloads.
+
+ Both survive resolve_model_config() and fail only once the loader opens the file, so the
+ picker has to reject them here rather than offer a model that cannot load.
+ """
+ from unsloth_cli._inference import ensure_studio_backend_path
+ from unsloth_cli import _model_catalog as cat
+
+ ensure_studio_backend_path()
+ config = json.dumps({"model_type": "qwen3", "architectures": ["Qwen3ForCausalLM"]})
+
+ def _dir(name, files):
+ d = tmp_path / name
+ d.mkdir(parents = True)
+ for filename, payload in files.items():
+ (d / filename).write_bytes(payload)
+ return d
+
+ zero_gguf = _dir("zero_gguf", {"m-Q4_K_M.gguf": b""})
+ lone_shard = _dir("lone_shard", {"s-Q4_K_M-00001-of-00003.gguf": b"\0" * 64})
+ zero_export = _dir("zero_export", {"config.json": config.encode(), "model.safetensors": b""})
+ good_gguf = _dir("good_gguf", {"m-Q4_K_M.gguf": b"\0" * 64})
+ good_export = _dir(
+ "good_export", {"config.json": config.encode(), "model.safetensors": b"\0" * 64}
+ )
+ whole_shards = _dir(
+ "whole_shards",
+ {
+ "s-Q4_K_M-00001-of-00002.gguf": b"\0" * 64,
+ "s-Q4_K_M-00002-of-00002.gguf": b"\0" * 64,
+ },
+ )
+
+ # Directories: torn payloads out, every loadable shape kept.
+ assert cat._local_dir_holds_a_payload(zero_gguf) is False
+ assert cat._local_dir_holds_a_payload(lone_shard) is False
+ assert cat._local_dir_holds_a_payload(zero_export) is False
+ assert cat._local_dir_holds_a_payload(good_gguf) is True
+ assert cat._local_dir_holds_a_payload(good_export) is True
+ assert cat._local_dir_holds_a_payload(whole_shards) is True
+
+ # A scan row can name the .gguf file itself, which is judged on its own shard family.
+ assert cat._local_dir_holds_a_payload(zero_gguf / "m-Q4_K_M.gguf") is False
+ assert cat._local_dir_holds_a_payload(lone_shard / "s-Q4_K_M-00001-of-00003.gguf") is False
+ assert cat._local_dir_holds_a_payload(good_gguf / "m-Q4_K_M.gguf") is True
+ assert cat._local_dir_holds_a_payload(whole_shards / "s-Q4_K_M-00001-of-00002.gguf") is True
+
+ exports = [
+ ("zero-gguf", str(zero_gguf / "m-Q4_K_M.gguf"), "gguf", None),
+ ("lone-shard", str(lone_shard / "s-Q4_K_M-00001-of-00003.gguf"), "gguf", None),
+ ("zero-export", str(zero_export), "merged", None),
+ ("good-gguf", str(good_gguf / "m-Q4_K_M.gguf"), "gguf", None),
+ ("good-export", str(good_export), "merged", None),
+ ]
+ fake_models = types.ModuleType("utils.models")
+ fake_models.scan_exported_models = lambda: exports
+ monkeypatch.setitem(sys.modules, "utils.models", fake_models)
+
+ assert [e.name for e in cat.exported_entries()] == ["good-gguf", "good-export"]
+
+
+def test_catalog_uses_only_the_two_specified_groups(monkeypatch, tmp_path):
+ """The picker is specified as Fine-tunes and Downloaded; exports and scanned local
+ folders belong inside those, not in two extra headings of their own."""
+ from unsloth_cli._inference import ensure_studio_backend_path
+ from unsloth_cli import _model_catalog as cat
+
+ ensure_studio_backend_path()
+ config = json.dumps({"model_type": "qwen3", "architectures": ["Qwen3ForCausalLM"]})
+ export = tmp_path / "export"
+ export.mkdir()
+ (export / "config.json").write_text(config)
+ (export / "model.safetensors").write_bytes(b"\0" * 64)
+ local = tmp_path / "local"
+ local.mkdir()
+ (local / "config.json").write_text(config)
+ (local / "model.safetensors").write_bytes(b"\0" * 64)
+
+ fake_models = types.ModuleType("utils.models")
+ fake_models.scan_exported_models = lambda: [("an-export", str(export), "merged", None)]
+ fake_models.scan_trained_models = lambda: []
+ monkeypatch.setitem(sys.modules, "utils.models", fake_models)
+ monkeypatch.setattr(cat, "_local_catalog_rows", lambda: [_catalog_local_row(local)])
+ monkeypatch.setattr(cat, "_local_model_task", lambda model: None)
+ monkeypatch.setattr(cat, "_local_model_can_chat", lambda model: None)
+ monkeypatch.setattr(cat, "_local_is_a_diffusers_pipeline", lambda model: False)
+
+ assert {e.group for e in cat.exported_entries()} == {"Fine-tunes"}
+ assert {e.group for e in cat.local_folder_entries()} == {"Downloaded"}
+
+ monkeypatch.setattr(cat, "cached_entries", lambda: [])
+ monkeypatch.setattr(cat, "trained_entries", lambda: [])
+ headings = []
+ for entry in cat.list_chat_models():
+ if not headings or headings[-1] != entry.group:
+ headings.append(entry.group)
+ assert headings == ["Fine-tunes", "Downloaded"]
+
+
+def test_catalog_keeps_the_org_prefix_when_a_plain_name_collides(monkeypatch):
+ """A fine-tune is already a bare name, so shortening a repo down to the same string
+ produces two identical rows; the collision count has to see both."""
+ from unsloth_cli import _model_catalog as cat
+
+ trained = [cat.ModelEntry("Fine-tunes", "Qwen3-0.6B", "", "/outputs/run-1")]
+ cached = [
+ cat.ModelEntry("Downloaded", "unsloth/Qwen3-0.6B", "", "unsloth/Qwen3-0.6B"),
+ cat.ModelEntry("Downloaded", "unsloth/Llama-3.2-1B", "", "unsloth/Llama-3.2-1B"),
+ ]
+ monkeypatch.setattr(cat, "trained_entries", lambda: trained)
+ monkeypatch.setattr(cat, "cached_entries", lambda: cached)
+ for name in ("exported_entries", "local_folder_entries"):
+ monkeypatch.setattr(cat, name, lambda: [])
+
+ names = [e.name for e in cat.list_chat_models()]
+ assert names == ["Qwen3-0.6B", "unsloth/Qwen3-0.6B", "Llama-3.2-1B"]
+ assert len(names) == len(set(names))
+
+
+def test_catalog_drops_an_export_with_no_loadable_payload(monkeypatch, tmp_path):
+ """scan_exported_models types a checkpoint "lora" on adapter_config.json ALONE.
+
+ The merged branch checks has_weights; the LoRA one does not. So an interrupted export
+ leaves a config with no adapter_model.safetensors or .bin, and nothing is "torn" there
+ because there is no payload at all -- which a negative-only check reads as fine. PEFT's
+ load_peft_weights finds neither weight name locally and raises, so the row was a path
+ the picker could offer and nothing could load.
+ """
+ from unsloth_cli._inference import ensure_studio_backend_path
+ from unsloth_cli import _model_catalog as cat
+
+ ensure_studio_backend_path()
+
+ broken = tmp_path / "broken"
+ broken.mkdir()
+ (broken / "adapter_config.json").write_text('{"peft_type": "LORA"}')
+ whole = tmp_path / "whole"
+ whole.mkdir()
+ (whole / "adapter_config.json").write_text('{"peft_type": "LORA"}')
+ (whole / "adapter_model.safetensors").write_bytes(b"\0" * 2048)
+
+ monkeypatch.setattr(cat, "_path_can_chat", lambda *a, **k: None)
+ # Warm the real hub.* chain BEFORE shadowing utils.models: _local_dir_holds_a_payload
+ # imports through it, and a stub package would break that import rather than the test.
+ assert cat._local_dir_holds_a_payload(whole) is True
+ assert cat._local_dir_holds_a_payload(broken) is False
+
+ fake_models = types.ModuleType("utils.models")
+ fake_models.scan_exported_models = lambda: [
+ ("broken / ckpt", str(broken), "lora", None),
+ ("whole / ckpt", str(whole), "lora", None),
+ ]
+ monkeypatch.setitem(sys.modules, "utils.models", fake_models)
+
+ assert [e.name for e in cat.exported_entries()] == ["whole / ckpt"]
+
+
+def test_catalog_hands_a_cached_gguf_pick_a_local_file(monkeypatch, tmp_path):
+ """An ACTIVE-cache row carries the bare repo id, which is right for the inventory and
+ wrong for a pick: from_identifier sends a non-path through detect_gguf_model_remote,
+ whose GatedRepoError branch returns None WITHOUT the local-cache fallback it uses when
+ offline. A cached gated GGUF then reads as non-GGUF and falls to the Transformers loader.
+ """
+ from unsloth_cli import _model_catalog as cat
+
+ repo = tmp_path / "models--Org--Gated-GGUF"
+ snapshot = repo / "snapshots" / ("a" * 40)
+ snapshot.mkdir(parents = True)
+ (snapshot / "gated-Q4_K_M.gguf").write_bytes(b"\0" * 4096)
+ (repo / "refs").mkdir()
+ (repo / "refs" / "main").write_text("a" * 40)
+
+ monkeypatch.setattr(
+ cat,
+ "_preferred_complete_gguf",
+ lambda p: str(snapshot / "gated-Q4_K_M.gguf") if str(snapshot) in str(p) else None,
+ )
+ resolved = cat._cached_gguf_load_id(
+ {"repo_id": "Org/Gated-GGUF", "load_id": "Org/Gated-GGUF", "cache_path": str(repo)}
+ )
+ assert resolved.endswith("gated-Q4_K_M.gguf"), resolved
+
+
+def test_catalog_payload_gate_accepts_an_uppercase_gguf_suffix(tmp_path):
+ """``glob("*.gguf")`` is case-sensitive on Linux and on a case-sensitive macOS volume
+ while ``_is_main_gguf_filename`` lowercases first, so a folder holding ``Model.GGUF``
+ was classified as a GGUF model and then dropped by this gate, which decides whether the
+ row is listed at all."""
+ from unsloth_cli._inference import ensure_studio_backend_path
+ from unsloth_cli import _model_catalog as cat
+
+ ensure_studio_backend_path()
+ upper = tmp_path / "upper"
+ upper.mkdir()
+ (upper / "Model.GGUF").write_bytes(b"GGUF" + b"\0" * 4096)
+ assert cat._local_dir_holds_a_payload(upper) is True
+
+
+def test_catalog_local_gguf_folder_picks_the_preferred_quant(monkeypatch, tmp_path):
+ """A GGUF DIRECTORY goes through detect_gguf_model, which sorts by size and takes the
+ largest complete file, commonly the F16, while cached and exported rows resolve a
+ Q4-class quant: the same folder loaded a far bigger model by source alone."""
+ from unsloth_cli import _model_catalog as cat
+
+ folder = tmp_path / "multi"
+ folder.mkdir()
+ (folder / "mymodel-Q4_K_M.gguf").write_bytes(b"GGUF" + b"\0" * 4096)
+ (folder / "mymodel-F16.gguf").write_bytes(b"GGUF" + b"\0" * 4096 * 40)
+
+ row = SimpleNamespace(
+ source = "models_dir",
+ partial = False,
+ model_format = "gguf",
+ path = str(folder),
+ display_name = "multi",
+ load_id = str(folder),
+ id = str(folder),
+ )
+ monkeypatch.setattr(cat, "_local_catalog_rows", lambda: [row])
+ monkeypatch.setattr(cat, "_local_model_task", lambda m: None)
+ monkeypatch.setattr(cat, "_local_model_can_chat", lambda m: None)
+ monkeypatch.setattr(cat, "_local_is_a_diffusers_pipeline", lambda m: False)
+ monkeypatch.setattr(cat, "_local_dir_holds_a_payload", lambda p: True)
+ monkeypatch.setattr(
+ cat, "_preferred_complete_gguf", lambda p: str(folder / "mymodel-Q4_K_M.gguf")
+ )
+
+ entries = cat.local_folder_entries()
+ assert entries and entries[0].model.endswith("mymodel-Q4_K_M.gguf"), entries[0].model
+
+
+def test_catalog_pins_an_active_cache_adapter_to_its_snapshot(tmp_path):
+ """A LoRA resolved by bare repo id takes the REMOTE branch of
+ get_base_model_from_lora_identifier, which downloads adapter_config.json with no
+ local_files_only; for a cached gated adapter with no token that fails and the base is
+ never read. A snapshot path takes the local reader. An ordinary cached repo is
+ deliberately left on its id."""
+ from unsloth_cli import _model_catalog as cat
+
+ repo = tmp_path / "models--Org--GatedLora"
+ snapshot = repo / "snapshots" / ("a" * 40)
+ snapshot.mkdir(parents = True)
+ (repo / "refs").mkdir()
+ (repo / "refs" / "main").write_text("a" * 40)
+
+ adapter = {
+ "repo_id": "Org/GatedLora",
+ "load_id": "Org/GatedLora",
+ "model_format": "adapter",
+ "cache_path": str(repo),
+ }
+ assert cat._cached_model_load_id(adapter) == str(snapshot)
+
+ plain = {
+ "repo_id": "Org/Chat",
+ "load_id": "Org/Chat",
+ "model_format": "safetensors",
+ "cache_path": str(repo),
+ }
+ assert cat._cached_model_load_id(plain) == "Org/Chat"
diff --git a/unsloth_cli/tests/test_start.py b/unsloth_cli/tests/test_start.py
index b761498e91b..c0c8d99035c 100644
--- a/unsloth_cli/tests/test_start.py
+++ b/unsloth_cli/tests/test_start.py
@@ -804,9 +804,10 @@ def _parse_toml(text: str) -> dict:
return tomllib.loads(text)
-def test_project_declares_direct_click_dependency():
+def test_project_declares_direct_cli_dependencies():
project = _parse_toml((_REPO_ROOT / "pyproject.toml").read_text(encoding = "utf-8"))
assert "click>=8.0" in project["project"]["dependencies"]
+ assert "huggingface-hub>=0.34.0" in project["project"]["dependencies"]
def test_agent_paths_use_cli_studio_home_without_backend_imports(monkeypatch, tmp_path):