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
Studio: judge the cached-pipeline signals on the snapshot the row actually loads (#7851)
Daniel Hancfee82cd2c13
diff --git a/studio/backend/hub/services/models/cache_inventory.py b/studio/backend/hub/services/models/cache_inventory.pyindex d82a57d0e66..e3b60ad3feb 100644--- a/studio/backend/hub/services/models/cache_inventory.py+++ b/studio/backend/hub/services/models/cache_inventory.py@@ -645,6 +645,13 @@ def _repo_non_gguf_model_payload(repo_info) -> _CachedNonGgufPayload:if snapshot is not None:for config_name, key in (("config.json", "has_config"),+ # A diffusers pipeline's root manifest, which plays exactly the role config.json+ # plays for transformers: from_pretrained reads it at the snapshot root to learn+ # the component layout. Without it here no pure pipeline snapshot could classify+ # (real repos ship model_index.json and per-component configs, never a root+ # config.json), payload_snapshots came back empty, and every cached diffusion base+ # pipeline was force-flagged partial and dropped from the On Device lists.+ ("model_index.json", "has_config"),("adapter_config.json", "has_adapter_config"),):try:@@ -854,7 +861,9 @@ def _scan_cached_models() -> list[dict]:)# A companion-only prefetch (pipeline manifest + VAE / text-encoder but no transformer shards, left by a GGUF load) passes# the download check yet cannot from_pretrained, so mark it partial and the pickers stop advertising it as on-device.- companion_only = hf_cache_scan.repo_pipeline_missing_denoiser(repo_info)+ # Scoped to the row's own snapshot, like the download check above it: the repo-wide twin picks the newest revision for+ # itself, so a newer companion-only snapshot beside the complete one refs/main resolves to marked this row partial.+ companion_only = hf_cache_scan.snapshot_pipeline_missing_denoiser(load_snapshot)snapshot_partial = download_partial or companion_only# Flags are OR-ed over revisions, so no payload snapshot means no directory# serves the row and it would reach for the Hub.@@ -878,10 +887,11 @@ def _scan_cached_models() -> list[dict]:else None),# Diffusion repos with no pipeline index load only via from_single_file, so the task pickers must not offer them as- # pipeline loads. Without this the picker's single_file gate sees undefined on every hub-sourced row.+ # pipeline loads. Without this the picker's single_file gate sees undefined on every hub-sourced row. Read from the+ # row's snapshot: the manifest a sibling revision carries is not the one this row's load_id opens."single_file": bool(row_task is not None- and not hf_cache_scan.repo_has_pipeline_index(repo_info)+ and not hf_cache_scan.snapshot_has_pipeline_index(load_snapshot)),**local_metadata,}diff --git a/studio/backend/hub/tests/test_model_services.py b/studio/backend/hub/tests/test_model_services.pyindex f3b6446eb9c..d3aef8cc526 100644--- a/studio/backend/hub/tests/test_model_services.py+++ b/studio/backend/hub/tests/test_model_services.py@@ -949,20 +949,41 @@ def test_cached_models_scan_hides_non_gguf_embedder(monkeypatch, tmp_path):assert [row["repo_id"] for row in result["cached"]] == ["Org/Chat"]+_SNAPSHOT_SHA = "a" * 40++def _diffusion_scan(monkeypatch, tmp_path, repo_id: str, files: list, *, task: str):"""One cached diffusion repo through _scan_cached_models, with the download-partial signal- forced off so only the pipeline-shape checks can flag the row."""+ forced off so only the pipeline-shape checks can flag the row.++ The snapshot is materialised on disk, not just described: the pipeline-shape checks read the+ directory the row resolves to, so a revision without a real ``snapshot_path`` would report no+ manifest and no denoiser for every repo alike and the assertions below would all pass on+ nothing.+ """repo_path = tmp_path / f"hub/models--{repo_id.replace('/', '--')}"- repo_path.mkdir(parents = True)+ snapshot = repo_path / "snapshots" / _SNAPSHOT_SHA+ snapshot.mkdir(parents = True)+ for f in files:+ target = snapshot / f.file_name+ target.parent.mkdir(parents = True, exist_ok = True)+ target.write_bytes(b"\0" * min(int(f.size_on_disk), 4096))+ refs = repo_path / "refs"+ refs.mkdir(parents = True, exist_ok = True)+ (refs / "main").write_text(_SNAPSHOT_SHA)+ revision = SimpleNamespace(files = files, snapshot_path = snapshot, commit_hash = _SNAPSHOT_SHA)+ repo = SimpleNamespace(+ repo_id = repo_id, repo_type = "model", repo_path = repo_path, revisions = [revision]+ )monkeypatch.setattr(- cache_inventory,- "all_hf_cache_scans",- lambda: [SimpleNamespace(repos = [_repo(repo_id, files, repo_path)])],+ cache_inventory, "all_hf_cache_scans", lambda: [SimpleNamespace(repos = [repo])])+ # The real signature takes snapshot_dir; a double that omits it raises TypeError, which the+ # per-repo except swallows into an empty row list and every assertion below stops running.monkeypatch.setattr(cache_inventory.hf_cache_scan,"is_snapshot_partial",- lambda _kind, _repo_id, _path: False,+ lambda *_args, **_kwargs: False,)monkeypatch.setattr(cache_inventory, "_cached_row_task", lambda _repo, gguf: task)rows = cache_inventory._scan_cached_models()diff --git a/studio/backend/hub/utils/inventory_scan.py b/studio/backend/hub/utils/inventory_scan.pyindex 16076e973fd..798c6a39dbd 100644--- a/studio/backend/hub/utils/inventory_scan.py+++ b/studio/backend/hub/utils/inventory_scan.py@@ -1488,6 +1488,53 @@ def _current_revisions(repo_info):return revisions+# One definition of "the denoiser is on disk", shared by the repo-wide and the snapshot-scoped+# check so the two cannot drift into disagreeing about the same directory.+_DENOISER_DIRS = ("transformer", "unet")+_DENOISER_WEIGHT_SUFFIXES = (".safetensors", ".bin")+++def snapshot_has_pipeline_index(snapshot: Optional[Path]) -> bool:+ """Whether *snapshot* itself carries a ROOT ``model_index.json``.++ The snapshot-scoped twin of :func:`repo_has_pipeline_index`, for callers that already know the+ ONE directory their row loads from. ``from_pretrained`` reads the manifest at the root of the+ revision it resolves, so a sibling revision's manifest says nothing about this row.+ """+ if snapshot is None:+ return False+ try:+ return (Path(snapshot) / "model_index.json").is_file()+ except OSError:+ return False+++def snapshot_pipeline_missing_denoiser(snapshot: Optional[Path]) -> bool:+ """The companion-only-prefetch check scoped to ONE snapshot dir.++ Same signal as :func:`repo_pipeline_missing_denoiser` -- a root ``model_index.json`` with no+ weight under ``transformer/`` or ``unet/`` -- but judged on the directory the caller's row+ actually loads, not on whichever revision this module would have picked for itself. Two+ snapshot selectors disagree: a row pinned to (or resolving through ``refs/main`` to) a complete+ revision would otherwise be marked partial by a newer companion-only one sitting beside it.+ Best-effort in the same direction: a read error reports not-missing.+ """+ if not snapshot_has_pipeline_index(snapshot):+ return False+ try:+ for denoiser in _DENOISER_DIRS:+ component = Path(snapshot) / denoiser+ if not component.is_dir():+ continue+ for entry in component.rglob("*"):+ # is_file() follows the snapshot symlink, so a dangling blob is correctly absent.+ if entry.is_file() and entry.name.lower().endswith(_DENOISER_WEIGHT_SUFFIXES):+ return False+ return True+ except OSError:+ return False++def repo_has_pipeline_index(repo_info) -> bool:"""Whether the cached snapshot carries a ROOT model_index.json, i.e. is loadableas a full diffusers pipeline (from_pretrained reads only the repo root). A nested@@ -1522,8 +1569,6 @@ def repo_pipeline_missing_denoiser(repo_info) -> bool:genuinely complete pipeline."""if not repo_has_pipeline_index(repo_info):return False- _DENOISER_DIRS = ("transformer", "unet")- _WEIGHT_SUFFIXES = (".safetensors", ".bin")try:for rev in _current_revisions(repo_info):snapshot = getattr(rev, "snapshot_path", None)@@ -1542,7 +1587,7 @@ def repo_pipeline_missing_denoiser(repo_info) -> bool:if (len(parts) >= 2and parts[0].lower() in _DENOISER_DIRS- and parts[-1].lower().endswith(_WEIGHT_SUFFIXES)+ and parts[-1].lower().endswith(_DENOISER_WEIGHT_SUFFIXES)):return Falsereturn Truediff --git a/studio/backend/tests/test_hf_cache_dangling_refs.py b/studio/backend/tests/test_hf_cache_dangling_refs.pyindex d3957409f3f..b0fbfc3d8cc 100644--- a/studio/backend/tests/test_hf_cache_dangling_refs.py+++ b/studio/backend/tests/test_hf_cache_dangling_refs.py@@ -1499,6 +1499,14 @@ _BACKEND = Path(__file__).resolve().parents[1]_REPO_WIDE_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_task","_repo_gguf_last_modified","_repo_gguf_payload_snapshots","_repo_gguf_size_bytes",@@ -3096,6 +3104,61 @@ def test_a_self_contained_snapshot_is_not_made_partial_by_a_second_one(assert rows[0]["capabilities"]["can_chat"] is True+def test_a_newer_companion_only_snapshot_does_not_make_the_ref_snapshot_partial(+ tmp_path, monkeypatch+):+ """The pipeline signals must read the snapshot the row loads, not the newest one.++ A GGUF image load leaves a companion-only prefetch (root ``model_index.json`` + VAE /+ text-encoder, no ``transformer/``) in a NEW revision beside the complete pipeline that+ ``refs/main`` still resolves to. huggingface_hub reads ``refs/main`` to turn ``main`` into a+ commit, so ``from_pretrained(repo_id)`` opens the OLD, complete directory -- judging the row on+ the newest revision instead marks a fully downloaded model partial and unchattable."""+ from types import SimpleNamespace++ from hub.services.models import cache_inventory++ # No root config.json: real diffusers pipelines ship model_index.json and per-component+ # configs only, and a fixture that adds one would pin a layout that does not occur.+ pipeline = {+ "model_index.json": b'{"_class_name":"FluxPipeline"}',+ "transformer/config.json": b'{"_class_name":"FluxTransformer2DModel"}',+ "vae/config.json": b'{"_class_name":"AutoencoderKL"}',+ "text_encoder/model.safetensors": b"\0" * 256,+ "transformer/diffusion_pytorch_model.safetensors": b"\0" * 256,+ "vae/diffusion_pytorch_model.safetensors": b"\0" * 256,+ }+ companion_only = {name: blob for name, blob in pipeline.items() if "transformer/" not in name}+ repo_dir = _repo_with(+ tmp_path,+ # SNAPSHOT is the companion-only prefetch, OLDER the complete pipeline refs/main names.+ snapshots = {SNAPSHOT: companion_only, OLDER: pipeline},+ refs = {"main": OLDER},+ )+ # The companion-only revision is unambiguously the newest, the shape the repo-wide check picks.+ os.utime(repo_dir / "snapshots" / OLDER, (1_000_000, 1_000_000))+ os.utime(repo_dir / "snapshots" / SNAPSHOT, (2_000_000, 2_000_000))++ monkeypatch.setattr(inventory_scan, "hf_cache_roots", lambda: [tmp_path])+ monkeypatch.setattr(+ "utils.hf_cache_settings.get_hf_cache_paths",+ lambda: SimpleNamespace(hub_cache = tmp_path),+ )+ inventory_scan.invalidate_hf_cache_scans()+ try:+ rows = cache_inventory._scan_cached_models()+ finally:+ inventory_scan.invalidate_hf_cache_scans()++ assert [row["repo_id"] for row in rows] == ["Org/Model"]+ # The row loads by repo id, so refs/main decides: the complete pipeline.+ assert rows[0]["load_id"] == "Org/Model"+ assert rows[0]["partial"] is False+ assert rows[0]["capabilities"]["can_chat"] is True+ # ... and that same directory carries the manifest, so it is not a single-file checkpoint.+ assert rows[0]["single_file"] is False++def _snapshot_with(tmp_path, files: dict) -> Path:snapshot = tmp_path / "snap"snapshot.mkdir()