Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Follow up #9435: restore the rest of the moved names, and read quant labels through the variant lister (#9701)
Daniel Han05d95c0b049d
diff --git a/studio/backend/routes/models.py b/studio/backend/routes/models.pyindex 98b477d24e5..0d8e786bbd1 100644--- a/studio/backend/routes/models.py+++ b/studio/backend/routes/models.py@@ -22,6 +22,7 @@ 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_namefrom hub.services.models import catalog_classification as _catalog_classification+from utils import gguf_archs as _gguf_archsfrom hub.services.models.catalog_classification import (_cached_repo_task,_is_sd_cpp_companion_repo,@@ -56,6 +57,19 @@ _task_classify_sort_key = _catalog_classification._task_classify_sort_key# 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+# The rest of what moved. Nothing in-repo reads these, which is why they went unnoticed --+# the one name that did have a caller surfaced as a wrong message, never an ImportError.+# All were importable from routes.models before and two are public, so a downstream fork or+# an older script may hold one, which this repo cannot see.+_H3_DENOISER_GGUF_PREFIXES = _catalog_classification._H3_DENOISER_GGUF_PREFIXES+_LOADABLE_MEDIA_GGUF_TASKS = _catalog_classification._LOADABLE_MEDIA_GGUF_TASKS+_MAX_TASK_CLASSIFY_GGUFS = _catalog_classification._MAX_TASK_CLASSIFY_GGUFS+_PLACEHOLDER_DIFFUSION_GGUF_ARCHS = _catalog_classification._PLACEHOLDER_DIFFUSION_GGUF_ARCHS+_TASK_CLASSIFY_READ_SECONDS = _catalog_classification._TASK_CLASSIFY_READ_SECONDS+_gguf_family_buildable = _catalog_classification._gguf_family_buildable+_is_h3_bundle_gguf_hint = _catalog_classification._is_h3_bundle_gguf_hint+SPEECH_GGUF_ARCHS = _gguf_archs.SPEECH_GGUF_ARCHS+is_speech_gguf_architecture = _gguf_archs.is_speech_gguf_architecturefrom utils.utils import canonical_model_repo_id, log_and_http_errorimport re as _re@@ -3839,6 +3853,16 @@ 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.++ _gguf_copy_is_usable asks the stronger question now, so this has no caller here. It stays+ because it was importable before, and a name read only from outside looks unused inside.+ """+ 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], active_root: Optional[Path]) -> bool:"""Whether this copy of the repo holds a quant a load can reach.diff --git a/studio/backend/tests/test_cached_gguf_routes.py b/studio/backend/tests/test_cached_gguf_routes.pyindex 0206b9913fc..f3f820ca2a5 100644--- a/studio/backend/tests/test_cached_gguf_routes.py+++ b/studio/backend/tests/test_cached_gguf_routes.py@@ -6824,3 +6824,37 @@ def test_a_speech_arch_is_the_same_answer_in_every_layer():assert models_route._SPEECH_GGUF_ARCHS is SPEECH_GGUF_ARCHSassert compat_archs is SPEECH_GGUF_ARCHSassert LlamaCppBackend._SPEECH_ARCHES is SPEECH_GGUF_ARCHS+++# Moved into catalog_classification, or no longer imported from utils.gguf_archs. Each was+# importable from routes.models before, so each may be held by something outside this repo.+MOVED_OUT_OF_ROUTES_MODELS = (+ "SPEECH_GGUF_ARCHS",+ "_H3_DENOISER_GGUF_PREFIXES",+ "_LOADABLE_MEDIA_GGUF_TASKS",+ "_MAX_TASK_CLASSIFY_GGUFS",+ "_PLACEHOLDER_DIFFUSION_GGUF_ARCHS",+ "_TASK_CLASSIFY_READ_SECONDS",+ "_default_ref_offers_no_whole_quant",+ "_gguf_family_buildable",+ "_is_h3_bundle_gguf_hint",+ "_video_family_buildable",+ "is_speech_gguf_architecture",+)++[email protected]("name", MOVED_OUT_OF_ROUTES_MODELS)+def test_a_name_that_moved_out_of_routes_models_still_resolves_there(name):+ """Extracting a helper must not retire the name it was reachable by.++ Not style. ``llama_cpp._video_arch_is_pickable`` imports ``_video_family_buildable`` from+ here inside a ``try`` returning True on any exception, so losing the name raised nothing:+ the probe just started saying yes, promising the Video page GGUFs it will not offer.+ """+ assert hasattr(models_route, name)+++def test_the_video_page_probe_resolves_the_helper_it_imports():+ """The exact import that broke, asserted at its own call site."""+ from routes.models import _video_family_buildable+ assert callable(_video_family_buildable)diff --git a/unsloth_cli/_model_catalog.py b/unsloth_cli/_model_catalog.pyindex b5e7f0f4661..205e5461766 100644--- a/unsloth_cli/_model_catalog.py+++ b/unsloth_cli/_model_catalog.py@@ -156,19 +156,114 @@ def exported_entries() -> List[ModelEntry]:return entries-def _quant_labels(repo_id: str, repo_path: str) -> str:- from utils.models.model_config import _is_mmproj+def _pinned_snapshot(repo_path: Path, load_id: Optional[str]) -> Optional[Path]:+ """The snapshot a pinned row will open, when ``load_id`` names one inside this repo.++ A pin beats ``refs/main``, because the inventory pins exactly when the ref would resolve+ somewhere worse, so the ref names a revision this row never loads.+ """+ if not load_id:+ return None+ try:+ candidate = Path(load_id)+ snapshots = (repo_path / "snapshots").resolve(strict = False)+ for path in (candidate, *candidate.parents):+ if path.parent.resolve(strict = False) == snapshots and path.is_dir():+ return path+ except (OSError, ValueError):+ return None+ return None+++def _reachable_snapshots(repo_path: Path, load_id: Optional[str] = None) -> List[Path]:+ """The snapshots a load through this row could actually open.++ The pinned one when the row carries a pin, else ``refs/main`` alone when it names one,+ since that is what a bare repo id resolves to and another revision's quants are files the+ selection cannot reach. A commit- or tag-pinned fetch leaves no ``refs/main``, and those+ rows are pinned rather than dropped, so they describe every snapshot instead.+ """+ snapshots = repo_path / "snapshots"+ try:+ available = sorted(path for path in snapshots.iterdir() if path.is_dir())+ except OSError:+ return []+ pinned = _pinned_snapshot(repo_path, load_id)+ if pinned is not None:+ # Returned as validated, not re-checked against `available`. inventory_scan resolves+ # the snapshot it pins while cache_path keeps the configured spelling, so under a+ # symlinked cache root the two name one directory and fail lexical equality, and the+ # membership test would drop a good pin back onto the ref it was pinned away from.+ return [pinned]+ try:+ # ValueError too: an undecodable ref raises UnicodeDecodeError, which is not an+ # OSError, and uncaught it leaves _safe hiding every Downloaded row over one repo.+ ref = (repo_path / "refs" / "main").read_text(encoding = "utf-8").strip()+ except (OSError, ValueError):+ ref = ""+ if ref:+ by_ref = snapshots / ref+ if by_ref in available:+ return [by_ref]+ return available+++def _complete_quants(snapshot: Path) -> Optional[set]:+ """The quant keys under *snapshot* a load can resolve, or None if unknown.++ ``_preferred_complete_gguf`` narrows to this same set, so a label outside it names a+ quant selecting the row can never reach.+ """+ try:+ from hub.utils.inventory_scan import complete_snapshot_variants+ complete = complete_snapshot_variants(str(snapshot))+ except Exception:+ return None+ # Empty here means the check could not tell, not that nothing loads: a genuinely+ # incomplete repo arrives partial and never reaches the picker. Describe what is on disk.+ return set(complete) or None+++def _quant_labels(+ repo_id: str,+ repo_path: str,+ load_id: Optional[str] = None,+) -> str:+ """The quants this cached GGUF repo offers, spelled the way Studio spells them.++ Through ``list_local_gguf_variants``, which is what ``_preferred_complete_gguf`` picks the+ load target with, so the label and the target cannot disagree. Globbing+ ``snapshots/*/*.gguf`` missed a per-quant subdirectory, gave a split quant one label per+ shard, and matched ``.GGUF`` only on Windows, where fnmatch normcases; the lister recurses,+ groups shard families, and tests the suffix case-insensitively.++ Scoped to the snapshot this row loads from and narrowed to the quants that snapshot can+ actually serve, so the detail never advertises a variant selecting the row cannot reach.++ Fails open to no detail, like every backend import here: a raise would leave ``_safe`` to+ swallow the whole cached source and every Downloaded row with it.+ """+ try:+ from hub.utils.gguf import list_local_gguf_variants+ except ImportError:+ return ""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-"):+ for snapshot in _reachable_snapshots(Path(repo_path), load_id):+ try:+ variants, _ = list_local_gguf_variants(str(snapshot))+ except Exception:continue- label = file.stem- if label.lower().startswith(stem + "-"):- label = label[len(stem) + 1 :]- if label not in quants:- quants.append(label)+ complete = _complete_quants(snapshot)+ for variant in variants:+ if complete is not None and variant.quant not in complete:+ continue+ label = variant.display_label or variant.quant+ if label.lower().startswith(stem + "-"):+ label = label[len(stem) + 1 :]+ if label and label not in quants:+ quants.append(label)return ", ".join(quants)@@ -320,7 +415,7 @@ def cached_entries() -> List[ModelEntry]:ModelEntry("Downloaded",row["repo_id"],- _quant_labels(row["repo_id"], row["cache_path"]),+ _quant_labels(row["repo_id"], row["cache_path"], row.get("load_id")),_cached_gguf_load_id(row),))diff --git a/unsloth_cli/tests/test_inference_chat.py b/unsloth_cli/tests/test_inference_chat.pyindex 2ffd45a2b70..c660e2fce6c 100644--- a/unsloth_cli/tests/test_inference_chat.py+++ b/unsloth_cli/tests/test_inference_chat.py@@ -449,9 +449,10 @@ def test_catalog_cached_entries_filter_non_chat_rows(monkeypatch, tmp_path):# 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)+ # The real variant lister, not a stub: it decides these labels and picks the load target,+ # so a stub tests the plumbing and none of the answer. Pulls neither torch nor fastapi, and+ # syspath_prepend is undone after the test, so the suite keeps its no-server-import property.+ monkeypatch.syspath_prepend(str(_REPO_ROOT / "studio" / "backend"))monkeypatch.setattr(cat, "_cached_catalog_rows", lambda: (gguf_rows, model_rows))entries = cat.cached_entries()@@ -2436,3 +2437,128 @@ def test_catalog_pins_an_active_cache_adapter_to_its_snapshot(tmp_path):"cache_path": str(repo),}assert cat._cached_model_load_id(plain) == "Org/Chat"+++QUANT_LAYOUTS = [+ ([("Tiny-Q4_K_M.gguf", 16)], "Q4_K_M"),+ ([("Tiny-Q4_K_M.gguf", 16), ("Tiny-Q8_0.gguf", 16)], "Q4_K_M, Q8_0"),+ # One directory per quant. snapshots/*/*.gguf is one level deep, so this rendered blank.+ ([("Q4_K_M/Tiny-Q4_K_M.gguf", 16), ("Q8_0/Tiny-Q8_0.gguf", 16)], "Q4_K_M, Q8_0"),+ # A split quant is ONE thing to pick. The glob listed every shard as its own label.+ ([(f"Tiny-Q4_K_M-0000{n}-of-00003.gguf", 16) for n in (1, 2, 3)], "Q4_K_M"),+ # The case the host decides: fnmatch normcases on Windows and not on Linux or macOS, so+ # "*.gguf" found this file on one platform only and the cache read differently per machine.+ ([("Tiny-Q8_0.GGUF", 16)], "Q8_0"),+ ([("Tiny-Q4_K_M.gguf", 16), ("mmproj-F16.gguf", 16)], "Q4_K_M"),+]++[email protected]("files,expected", QUANT_LAYOUTS)+def test_quant_labels_read_the_layouts_the_hub_actually_writes(+ monkeypatch, tmp_path, files, expected+):+ from unsloth_cli import _model_catalog as cat++ monkeypatch.syspath_prepend(str(_REPO_ROOT / "studio" / "backend"))+ repo = tmp_path / "models--org--Tiny-GGUF"+ for name, size in files:+ target = repo / "snapshots" / "abc" / name+ target.parent.mkdir(parents = True, exist_ok = True)+ target.write_bytes(b"\0" * size)++ assert cat._quant_labels("org/Tiny-GGUF", str(repo)) == expected+++def test_quant_labels_follow_the_pin_rather_than_the_ref(monkeypatch, tmp_path):+ """A pinned row loads its snapshot, not the one refs/main names.++ The inventory pins precisely when the ref resolves somewhere worse, so labelling by the+ ref advertised a quant the row will never open and hid the one it will.+ """+ from unsloth_cli import _model_catalog as cat++ monkeypatch.syspath_prepend(str(_REPO_ROOT / "studio" / "backend"))+ repo = tmp_path / "models--org--Two-GGUF"+ by_ref = repo / "snapshots" / ("a" * 40)+ pinned = repo / "snapshots" / ("b" * 40)+ by_ref.mkdir(parents = True)+ pinned.mkdir(parents = True)+ (by_ref / "Two-Q2_K.gguf").write_bytes(b"\0" * 16)+ (pinned / "Two-Q6_K.gguf").write_bytes(b"\0" * 16)+ (repo / "refs").mkdir(parents = True)+ (repo / "refs" / "main").write_text("a" * 40)++ assert cat._quant_labels("org/Two-GGUF", str(repo), str(pinned)) == "Q6_K"+ assert cat._quant_labels("org/Two-GGUF", str(repo)) == "Q2_K"+++def test_quant_labels_leave_out_a_quant_that_cannot_be_loaded(monkeypatch, tmp_path):+ """An interrupted second quant is not selectable, so it is not advertised.++ _preferred_complete_gguf narrows to complete_snapshot_variants before choosing the load+ target; the detail column reads the same set, or it names a quant nothing can open.+ """+ from unsloth_cli import _model_catalog as cat++ monkeypatch.syspath_prepend(str(_REPO_ROOT / "studio" / "backend"))+ repo = tmp_path / "models--org--Tiny-GGUF"+ snapshot = repo / "snapshots" / ("a" * 40)+ snapshot.mkdir(parents = True)+ (snapshot / "Tiny-Q4_K_M.gguf").write_bytes(b"\0" * 16)+ (snapshot / "Tiny-Q8_0-00001-of-00003.gguf").write_bytes(b"\0" * 16)+ (repo / "refs").mkdir(parents = True)+ (repo / "refs" / "main").write_text("a" * 40)++ assert cat._quant_labels("org/Tiny-GGUF", str(repo)) == "Q4_K_M"+++def test_one_undecodable_ref_does_not_empty_the_downloaded_group(monkeypatch, tmp_path):+ """read_text raises UnicodeDecodeError, which is a ValueError and not an OSError.++ Uncaught it leaves _quant_labels, aborts cached_entries, and _safe then hides every+ Downloaded row because one repo in the cache has a torn ref.+ """+ from unsloth_cli import _model_catalog as cat++ monkeypatch.syspath_prepend(str(_REPO_ROOT / "studio" / "backend"))+ repo = tmp_path / "models--org--Tiny-GGUF"+ snapshot = repo / "snapshots" / ("a" * 40)+ snapshot.mkdir(parents = True)+ (snapshot / "Tiny-Q4_K_M.gguf").write_bytes(b"\0" * 16)+ (repo / "refs").mkdir(parents = True)+ (repo / "refs" / "main").write_bytes(b"\xff\xfe\x00not utf-8")++ rows = [{"repo_id": "org/Tiny-GGUF", "cache_path": str(repo), "task": "text-generation"}]+ monkeypatch.setattr(cat, "_cached_catalog_rows", lambda: (rows, []))++ entries = cat.cached_entries()+ assert [(e.name, e.detail) for e in entries] == [("org/Tiny-GGUF", "Q4_K_M")]+++def test_a_pin_survives_a_symlinked_cache_root(monkeypatch, tmp_path):+ """inventory_scan resolves the snapshot it pins; cache_path keeps the configured spelling.++ Under a symlinked cache root (or a Windows junction) those two name one directory and+ are not lexically equal, so a membership test against the listed snapshots dropped a+ good pin back onto the ref it was pinned away from.+ """+ from unsloth_cli import _model_catalog as cat++ monkeypatch.syspath_prepend(str(_REPO_ROOT / "studio" / "backend"))+ physical = tmp_path / "physical_hub"+ physical.mkdir()+ repo = physical / "models--org--Two-GGUF"+ by_ref = repo / "snapshots" / ("a" * 40)+ pinned = repo / "snapshots" / ("b" * 40)+ by_ref.mkdir(parents = True)+ pinned.mkdir(parents = True)+ (by_ref / "Two-Q2_K.gguf").write_bytes(b"\0" * 16)+ (pinned / "Two-Q6_K.gguf").write_bytes(b"\0" * 16)+ (repo / "refs").mkdir(parents = True)+ (repo / "refs" / "main").write_text("a" * 40)++ configured = tmp_path / "configured_hub"+ configured.symlink_to(physical, target_is_directory = True)+ cache_path = configured / "models--org--Two-GGUF"++ assert cat._quant_labels("org/Two-GGUF", str(cache_path), str(pinned.resolve())) == "Q6_K"