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
Do not stage diffusion files that are already in the cache (#8154)
Michael Han43c9efcff946
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.pyindex a66f982cff2..c7c59274a88 100644--- a/studio/backend/core/inference/diffusion.py+++ b/studio/backend/core/inference/diffusion.py@@ -146,6 +146,17 @@ install_torchao_windows_rocm_stub()_MODEL_KINDS = frozenset({"gguf", "single_file", "pipeline"})+def _record_sha(shas_out: Optional[dict[str, str]], repo_id: str, info: Any) -> None:+ """Note the commit ``info`` describes so a cache probe can pin to it.++ No ``sha`` just means the plan cannot pin, and stages as before."""+ if shas_out is None:+ return+ sha = getattr(info, "sha", None)+ if isinstance(sha, str) and sha:+ shas_out[repo_id] = sha++def hub_cache_dir() -> str:"""The cache root every loader call must be pinned to.@@ -1461,6 +1472,8 @@ class DiffusionBackend:single_file_is_pipeline: bool = False,include_transformer: bool = False,sizes_out: Optional[dict[str, int]] = None,+ file_sizes_out: Optional[dict[tuple[str, str], int]] = None,+ shas_out: Optional[dict[str, str]] = None,skip_te_components: tuple[str, ...] = (),) -> tuple[int, list[str]]:"""Total download size for the progress bar, plus the base-repo files to@@ -1468,6 +1481,9 @@ class DiffusionBackend:``sizes_out``, when given, is filled with per-repo byte totals so the downloadplan can size one job per repo off this same single pair of Hub lookups.+ ``file_sizes_out`` is the per (repo, filename) breakdown, so the plan can drop cached+ files and size the rest. ``shas_out`` is each repo's CURRENT commit, so a cache hit+ counts only in that revision.For a ``pipeline`` load the whole repo IS the pipeline (``base_repo`` is therepo itself), so the transformer/ subfolder is INCLUDED -- unlike the GGUF /@@ -1500,6 +1516,7 @@ class DiffusionBackend:try:if kind == "pipeline":info = api.model_info(repo_id, files_metadata = True, token = hf_token)+ _record_sha(shas_out, repo_id, info)picked = [sfor s in info.siblings@@ -1516,16 +1533,21 @@ class DiffusionBackend:continuebase_files.append(s.rfilename)total += s.size or 0+ if file_sizes_out is not None:+ file_sizes_out[(repo_id, s.rfilename)] = s.size or 0if sizes_out is not None:sizes_out[repo_id] = totalreturn total, base_files# Skip the Hub size lookup for a LOCAL gguf path: model_info raises on a filesystem path.if gguf_filename and not Path(repo_id).expanduser().exists():info = api.model_info(repo_id, files_metadata = True, token = hf_token)+ _record_sha(shas_out, repo_id, info)gguf_bytes = sum(s.size or 0 for s in info.siblings if s.rfilename == gguf_filename)total += gguf_bytesif sizes_out is not None:sizes_out[repo_id] = gguf_bytes+ if file_sizes_out is not None:+ file_sizes_out[(repo_id, gguf_filename)] = gguf_bytes# A whole-pipeline single file (SDXL) needs only the base's config/tokenizer, not its weights.if kind == "single_file" and single_file_is_pipeline:base_filter = _base_config_file_downloaded@@ -1535,11 +1557,14 @@ class DiffusionBackend:return _base_file_downloaded(rfilename, include_transformer = include_transformer)base_info = api.model_info(base_repo, files_metadata = True, token = hf_token)+ _record_sha(shas_out, base_repo, base_info)base_bytes = 0for s in base_info.siblings:if base_filter(s.rfilename) and not _dense_te_shard(s.rfilename):base_files.append(s.rfilename)base_bytes += s.size or 0+ if file_sizes_out is not None:+ file_sizes_out[(base_repo, s.rfilename)] = s.size or 0total += base_bytesif sizes_out is not None:sizes_out[base_repo] = base_bytes@@ -1547,6 +1572,72 @@ class DiffusionBackend:logger.warning("diffusion.size_estimate_failed: %s", exc)return total, base_files+ @staticmethod+ def _files_already_cached(+ repo_id: str,+ files: list[str],+ revision: Optional[str] = None,+ ) -> set[str]:+ """Of ``files``, the names ONE root serves whole at ``revision``: all of them, or none.++ Both roots are searched -- Studio's live setting, and ``cache_dir = None`` for+ huggingface_hub's constant -- but hits are never UNIONED. A set split between the roots is+ complete in neither: ``_prefetch_files`` hands back a snapshot only when every file came+ from the SAME root, else None, and ``from_pretrained`` is then pinned to ``hub_cache_dir()``+ and cannot see the other root, so dropping the repo moves its refetch inline, outside the+ panel's progress and disk preflight. One root holding all of it still drops.++ ``revision`` is REQUIRED to drop anything: defaulted, ``try_to_load_from_cache`` reads the+ cache's OWN ``refs/main``, which a republished repo leaves on the superseded commit, so the+ stale blob would leave the plan and the loader would pull the new one inline.++ Only a str is a cached path. Never raises: an unreadable cache means "stage it"."""+ if not revision or not files:+ return set()+ try:+ from huggingface_hub import try_to_load_from_cache++ # Once, inside the try: hub_cache_dir is a SQLite read plus Path.home(), which raises+ # with no home -- per file and outside, it was the one way this could 500.+ roots = (hub_cache_dir(), None)+ except Exception: # noqa: BLE001 — no hub package / unreadable settings: stage everything+ return set()+ wanted = set(files)+ live_root, fallback_root = roots++ def _hits(root: Optional[str]) -> set[str]:+ found: set[str] = set()+ for name in wanted:+ try:+ hit = try_to_load_from_cache(repo_id, name, cache_dir = root, revision = revision)+ except Exception: # noqa: BLE001 — a cache we cannot read is not a verdict+ continue+ # is_file() is belt and braces: hub already ends on os.path.isfile today.+ if isinstance(hit, str) and Path(hit).is_file():+ found.add(name)+ return found++ live = _hits(live_root)+ if live == wanted:+ return wanted+ # A partial live hit IS the split: no single-root snapshot, so the pinned load refetches+ # the fallback's share.+ if live:+ return set()+ return wanted if _hits(fallback_root) == wanted else set()++ @staticmethod+ def _current_sha(repo_id: str, hf_token: Optional[str]) -> Optional[str]:+ """``repo_id``'s current commit, or None when the Hub does not say.++ Only for the MIRROR: it is a separate repo with its own history, so the vendor sha+ ``_estimate_download_bytes`` recorded would never hit."""+ try:+ from huggingface_hub import HfApi+ return getattr(HfApi().model_info(repo_id, token = hf_token), "sha", None) or None+ except Exception: # noqa: BLE001 — no sha means no skip, never a failed plan+ return None+def download_plan(self,repo_id: str,@@ -1581,7 +1672,10 @@ class DiffusionBackend:# Only a checkpoint that really resolves on the Hub earns the right to drop dense shards.te_files = self._te_prequant_plan_files(fam, text_encoder_quant, hf_token)sizes: dict[str, int] = {}- total, base_files = self._estimate_download_bytes(+ file_sizes: dict[tuple[str, str], int] = {}+ shas: dict[str, str] = {}+ # Total discarded: it counts every file the pick needs, not what is left to fetch.+ _estimate_total, base_files = self._estimate_download_bytes(repo_id,gguf_filename,base,@@ -1592,6 +1686,8 @@ class DiffusionBackend:include_transformer = kind == "gguf"and self._dense_quant_prefetch_needed(fam, {**load_kwargs, "base_repo": base}),sizes_out = sizes,+ file_sizes_out = file_sizes,+ shas_out = shas,skip_te_components = tuple(te_files),)# Decided once, from the staged file list, and both probed and reported: a gated base@@ -1601,38 +1697,74 @@ class DiffusionBackend:fetch_base = prefer_ungated_mirror(base, hf_token, files = base_files)_assert_base_repo_accessible(fetch_base, hf_token)entries: list[dict[str, Any]] = []- for repo, files in te_files.values():++ def _stage(+ repo: str,+ files: list[str],+ sized: dict[str, int],+ gguf: Optional[str],+ revision: Optional[str] = None,+ ) -> None:+ """Queue the files the cache is missing at ``revision``.++ Entries are what the Downloads panel lists, so an all-cached pick yields none rather+ than reading as a re-download of a model the user already has. No revision drops+ nothing, so an unpinnable repo stages in full as it always did.++ All or nothing per repo, never a subset: every diffusion entry for a repo rides the one+ "@diffusion" scope slot, and download_registry refuses a claim whose scoped_files differ+ from the live job's, so a shrinking list would 409 a second pick sharing this base where+ it used to adopt the running job. Staging a cached file costs nothing anyway, since+ hf_hub_download returns the pointer without a transfer.++ "Cached" is per ROOT, never a union across the two; see ``_files_already_cached``."""+ cached = self._files_already_cached(repo, files, revision)+ if files and cached.issuperset(files):+ returnentries.append({"repo_id": repo,- "files": [name for name, _size in files],- "bytes": int(sum(size for _name, size in files)),- "gguf_filename": None,+ "files": files,+ "bytes": int(sum(sized.get(name, 0) for name in files)),+ "gguf_filename": gguf,})- total += int(sum(size for _name, size in files))++ for repo, files in te_files.values():+ # No revision: te_prequant_hub_files reports names and sizes only, so a pre-cast+ # checkpoint stages whole, not off a stale refs/main. Worth surfacing its info.sha:+ # these replace tens of GB.+ _stage(repo, [n for n, _s in files], dict(files), None)if gguf_filename and not Path(repo_id).expanduser().exists():- entries.append(- {- "repo_id": repo_id,- "files": [gguf_filename],- "bytes": int(sizes.get(repo_id, 0)),- "gguf_filename": gguf_filename,- }+ _stage(+ repo_id,+ [gguf_filename],+ # file_sizes, not sizes: a base repo equal to this one overwrote sizes[repo_id]+ # with the base total, mis-sizing this row.+ {gguf_filename: int(file_sizes.get((repo_id, gguf_filename), 0))},+ gguf_filename,+ shas.get(repo_id),)if base_files and not Path(base).expanduser().exists():# STAGED before the loader runs, so it must name the MIRROR: a gated upstream here 401s# an anonymous user at staging and the swap downstream is never reached. status(), the# API base repo, saved configs and LoRA tags keep the vendor id; sizes key on it too.- entries.append(- {- "repo_id": fetch_base,- "files": base_files,- "bytes": int(sizes.get(base, 0)),- "gguf_filename": None,- }+ # The commit follows the id: the sizes came from the vendor, the probe must not.+ base_rev = (+ shas.get(base) if fetch_base == base else self._current_sha(fetch_base, hf_token))- return {"entries": entries, "total_bytes": int(total)}+ _stage(+ fetch_base,+ base_files,+ {name: file_sizes.get((base, name), 0) for name in base_files},+ None,+ base_rev,+ )+ # Derived, never decremented: a carried total can only drift from the rows the panel shows.+ return {+ "entries": entries,+ "total_bytes": int(sum(e["bytes"] for e in entries)),+ }@staticmethoddef _hub_cache_repo_dir(repo_id: str) -> Path:diff --git a/studio/backend/tests/conftest.py b/studio/backend/tests/conftest.pyindex b21e810991f..9c359dfb8ec 100644--- a/studio/backend/tests/conftest.py+++ b/studio/backend/tests/conftest.py@@ -161,6 +161,32 @@ def _no_background_model_scan(monkeypatch):monkeypatch.setattr(local_model_resolver, "_scan", (time.monotonic(), {}))[email protected](scope = "session")+def _empty_hf_hub_cache(tmp_path_factory):+ """One empty hub-cache root for the whole session; per-test mktemp is quadratic."""+ return str(tmp_path_factory.mktemp("hf_hub_cache_empty"))++[email protected](autouse = True)+def _hf_cache_is_empty(_empty_hf_hub_cache, monkeypatch):+ """Point BOTH hub-cache roots at an empty dir, so the suite is host independent.++ Studio pins its live setting out of this env snapshot; huggingface_hub falls back to+ ``constants.HF_HUB_CACHE``. A dev holding FLUX.1-dev otherwise watches its files leave a+ download plan AND the mirror swap decline. Pinned at the ROOT, not by stubbing a probe: that+ reaches only one of the four cache reads, and ``_upstream_is_cached`` walks the tree itself.+ Tests that own the cache setting replace the whole dict, so they still win."""+ from utils import hf_cache_settings++ monkeypatch.setitem(hf_cache_settings._EXPLICIT_CACHE_ENV, "HF_HUB_CACHE", _empty_hf_hub_cache)+ monkeypatch.setenv("HF_HUB_CACHE", _empty_hf_hub_cache)+ try:+ from huggingface_hub import constants+ except Exception: # optional deps absent on some CI legs+ return+ monkeypatch.setattr(constants, "HF_HUB_CACHE", _empty_hf_hub_cache)++@pytest.fixture(autouse = True)def _assume_bare_metal(monkeypatch):"""Pin the virtualised-Metal detector off so the suite is host independent.diff --git a/studio/backend/tests/test_diffusion_backend.py b/studio/backend/tests/test_diffusion_backend.pyindex a90ddb50b16..bc94fa6576d 100644--- a/studio/backend/tests/test_diffusion_backend.py+++ b/studio/backend/tests/test_diffusion_backend.py@@ -5054,6 +5054,7 @@ _FLUX_BASE_SIBLINGS = [_FakeSibling("assets/gallery.pdf", 5000),_FakeSibling("README.md", 200),]+_FLUX_BASE_SIBLINGS_BY_NAME = {s.rfilename: s.size for s in _FLUX_BASE_SIBLINGS}def _fake_hf_api(monkeypatch, repos):@@ -5421,3 +5422,495 @@ def test_a_superseding_load_fences_queued_generations_too(fake_runtime, tmp_pathassert seen == [1]assert backend._teardown_waiters == 0+++def test_download_plan_skips_files_already_in_the_cache(monkeypatch):+ # Entries are what the Downloads panel lists, so a model fully on disk must plan nothing.+ _fake_hf_api(+ monkeypatch,+ {+ "unsloth/FLUX.1-dev-GGUF": [_FakeSibling("flux1-dev-Q4_K_M.gguf", 7 * GB)],+ "black-forest-labs/FLUX.1-dev": _FLUX_BASE_SIBLINGS,+ },+ )+ monkeypatch.setattr(+ "core.inference.diffusion._resolve_base_repo",+ lambda *a, **k: "black-forest-labs/FLUX.1-dev",+ )+ monkeypatch.setattr(+ DiffusionBackend, "_dense_quant_prefetch_needed", lambda self, fam, kwargs: False+ )+ _no_cache(monkeypatch)+ monkeypatch.setattr(+ DiffusionBackend,+ "_files_already_cached",+ staticmethod(lambda repo_id, files, revision = None: set(files)),+ )++ plan = DiffusionBackend().download_plan(+ "unsloth/FLUX.1-dev-GGUF", gguf_filename = "flux1-dev-Q4_K_M.gguf"+ )++ assert plan["entries"] == []+ assert plan["total_bytes"] == 0+++def test_download_plan_stages_only_what_the_cache_is_missing(monkeypatch):+ # The common case after a base repo is shared: the companion is on disk, a new quant is not.+ _fake_hf_api(+ monkeypatch,+ {+ "unsloth/FLUX.1-dev-GGUF": [_FakeSibling("flux1-dev-Q4_K_M.gguf", 7 * GB)],+ "black-forest-labs/FLUX.1-dev": _FLUX_BASE_SIBLINGS,+ },+ )+ monkeypatch.setattr(+ "core.inference.diffusion._resolve_base_repo",+ lambda *a, **k: "black-forest-labs/FLUX.1-dev",+ )+ monkeypatch.setattr(+ DiffusionBackend, "_dense_quant_prefetch_needed", lambda self, fam, kwargs: False+ )+ _no_cache(monkeypatch)+ # Everything but the checkpoint repo is cached.+ monkeypatch.setattr(+ DiffusionBackend,+ "_files_already_cached",+ staticmethod(+ lambda repo_id, files, revision = None: (+ set() if repo_id.endswith("-GGUF") else set(files)+ )+ ),+ )++ plan = DiffusionBackend().download_plan(+ "unsloth/FLUX.1-dev-GGUF", gguf_filename = "flux1-dev-Q4_K_M.gguf"+ )++ assert [e["repo_id"] for e in plan["entries"]] == ["unsloth/FLUX.1-dev-GGUF"]+ assert plan["entries"][0]["files"] == ["flux1-dev-Q4_K_M.gguf"]+ # The cached base is gone from the total too, or the progress bar waits on bytes nobody fetches.+ assert plan["total_bytes"] == 7 * GB+++def _seed_cache_file(+ root,+ repo_id,+ filename,+ sha,+ *,+ dangling = False,+):+ """Write ``filename`` into a real HF cache layout at ``sha``, refs/main pointing there."""+ import os as _os++ repo = root / f"models--{repo_id.replace('/', '--')}"+ (repo / "refs").mkdir(parents = True, exist_ok = True)+ (repo / "refs" / "main").write_text(sha)+ target = repo / "snapshots" / sha / filename+ target.parent.mkdir(parents = True, exist_ok = True)+ if dangling:+ # A snapshot entry is a symlink into blobs/; a pruned blob leaves the link but no bytes.+ try:+ _os.symlink(repo / "blobs" / "gone", target)+ except (OSError, NotImplementedError):+ pytest.skip("symlinks unavailable on this host")+ else:+ target.write_bytes(b"x")+ return target+++def _two_cache_roots(monkeypatch, tmp_path):+ """(live, other) roots wired up the way a mid-session cache-folder change leaves them."""+ from huggingface_hub import constants as hf_constants++ live = tmp_path / "live"+ other = tmp_path / "other"+ live.mkdir()+ other.mkdir()+ monkeypatch.setattr("core.inference.diffusion.hub_cache_dir", lambda: str(live))+ monkeypatch.setattr(hf_constants, "HF_HUB_CACHE", str(other))+ return live, other+++def test_files_already_cached_needs_a_revision_to_drop_anything(monkeypatch, tmp_path):+ """No commit, no verdict: try_to_load_from_cache would otherwise resolve the cache's OWN+ refs/main, stale on a republished repo, and the loader would pull the new blob outside the+ panel."""+ live, _other = _two_cache_roots(monkeypatch, tmp_path)+ sha = "a" * 40+ _seed_cache_file(live, "unsloth/FLUX.1-dev-GGUF", "flux1-dev-Q4_K_M.gguf", sha)++ probe = DiffusionBackend._files_already_cached+ assert probe("unsloth/FLUX.1-dev-GGUF", ["flux1-dev-Q4_K_M.gguf"]) == set()+ assert probe("unsloth/FLUX.1-dev-GGUF", ["flux1-dev-Q4_K_M.gguf"], sha) == {+ "flux1-dev-Q4_K_M.gguf"+ }+++def test_files_already_cached_ignores_a_superseded_revision(monkeypatch, tmp_path):+ """The blob is on disk under the old commit and refs/main still names it, but the plan asked+ about the commit the Hub just reported, so the file stays staged."""+ live, _other = _two_cache_roots(monkeypatch, tmp_path)+ _seed_cache_file(live, "unsloth/FLUX.1-dev-GGUF", "flux1-dev-Q4_K_M.gguf", "a" * 40)++ assert (+ DiffusionBackend._files_already_cached(+ "unsloth/FLUX.1-dev-GGUF", ["flux1-dev-Q4_K_M.gguf"], "b" * 40+ )+ == set()+ )+++def test_files_already_cached_skips_unusable_hits(monkeypatch, tmp_path):+ """A dangling symlink is a path but not usable bytes, and an absent file is simply missing, so+ neither can complete the live root's set."""+ live, _other = _two_cache_roots(monkeypatch, tmp_path)+ sha = "c" * 40+ repo = "black-forest-labs/FLUX.1-dev"+ _seed_cache_file(live, repo, "model_index.json", sha)+ _seed_cache_file(live, repo, "vae/diffusion_pytorch_model.safetensors", sha)+ _seed_cache_file(live, repo, "text_encoder/model.safetensors", sha, dangling = True)++ probe = DiffusionBackend._files_already_cached+ files = ["model_index.json", "vae/diffusion_pytorch_model.safetensors"]+ assert probe(repo, files, sha) == set(files)+ # The dangling link and the file that was never fetched both leave the set incomplete.+ assert probe(repo, [*files, "text_encoder/model.safetensors"], sha) == set()+ assert probe(repo, [*files, "scheduler/scheduler_config.json"], sha) == set()+++def test_files_already_cached_takes_the_whole_set_from_the_fallback_root(monkeypatch, tmp_path):+ """The other root still counts, as a WHOLE: every diffusion fetch passes reuse_other_cache_root,+ so _prefetch_files resolves every file there and hands from_pretrained that snapshot."""+ _live, other = _two_cache_roots(monkeypatch, tmp_path)+ sha = "c" * 40+ repo = "black-forest-labs/FLUX.1-dev"+ files = ["model_index.json", "vae/diffusion_pytorch_model.safetensors"]+ for name in files:+ _seed_cache_file(other, repo, name, sha)++ assert DiffusionBackend._files_already_cached(repo, files, sha) == set(files)+++def test_files_already_cached_refuses_a_set_split_over_two_roots(monkeypatch, tmp_path):+ """Never a per-file union. Neither root holds a complete snapshot, so _prefetch_files returns+ None instead of a snapshot dir and from_pretrained falls back to the hub id pinned to+ hub_cache_dir(), which cannot see the fallback root: calling this repo cached would refetch+ that root's share inline, outside the Downloads panel's progress and its disk preflight."""+ live, other = _two_cache_roots(monkeypatch, tmp_path)+ sha = "c" * 40+ repo = "black-forest-labs/FLUX.1-dev"+ _seed_cache_file(live, repo, "model_index.json", sha)+ _seed_cache_file(other, repo, "vae/diffusion_pytorch_model.safetensors", sha)+ files = ["model_index.json", "vae/diffusion_pytorch_model.safetensors"]++ # Every file is on disk somewhere, at the right commit, and nothing is missing.+ assert DiffusionBackend._files_already_cached(repo, files, sha) == set()+ # One root holding the whole set is the only thing that changes the verdict.+ _seed_cache_file(live, repo, "vae/diffusion_pytorch_model.safetensors", sha)+ assert DiffusionBackend._files_already_cached(repo, files, sha) == set(files)+++def test_download_plan_stages_a_repo_split_across_two_cache_roots(monkeypatch, tmp_path):+ """End to end: a base repo half in the live root and half in the import-time one keeps its row.+ Dropping it tells the panel there is nothing to fetch and the load pulls the rest itself."""+ live, other = _two_cache_roots(monkeypatch, tmp_path)+ base_sha = "9" * 40+ base = "black-forest-labs/FLUX.1-dev"+ _fake_hf_api_with_shas(+ monkeypatch,+ {+ "unsloth/FLUX.1-dev-GGUF": ([_FakeSibling("flux1-dev-Q4_K_M.gguf", 7 * GB)], "8" * 40),+ base: (_FLUX_BASE_SIBLINGS, base_sha),+ },+ )+ monkeypatch.setattr("core.inference.diffusion._resolve_base_repo", lambda *a, **k: base)+ monkeypatch.setattr(+ DiffusionBackend, "_dense_quant_prefetch_needed", lambda self, fam, kwargs: False+ )+ # No mirror swap, so the staged id and the probed commit are the vendor's own.+ _all_cached(monkeypatch)+ staged = [+ name+ for name in _FLUX_BASE_SIBLINGS_BY_NAME+ if _base_file_downloaded(name, include_transformer = False)+ ]+ assert len(staged) > 1+ _seed_cache_file(live, base, staged[0], base_sha)+ for name in staged[1:]:+ _seed_cache_file(other, base, name, base_sha)++ plan = DiffusionBackend().download_plan(+ "unsloth/FLUX.1-dev-GGUF", gguf_filename = "flux1-dev-Q4_K_M.gguf"+ )++ by_repo = {e["repo_id"]: e for e in plan["entries"]}+ assert base in by_repo, "a split base repo must keep its row"+ assert by_repo[base]["files"] == staged+ assert by_repo[base]["bytes"] == sum(_FLUX_BASE_SIBLINGS_BY_NAME[n] for n in staged)+ assert plan["total_bytes"] == sum(e["bytes"] for e in plan["entries"])+++def test_download_plan_drops_a_repo_the_fallback_root_holds_whole(monkeypatch, tmp_path):+ """The other half of the rule, so the split guard cannot become "always stage": a repo left+ complete in the import-time root after a cache-folder change still leaves the plan."""+ _live, other = _two_cache_roots(monkeypatch, tmp_path)+ base_sha, gguf_sha = "9" * 40, "8" * 40+ base = "black-forest-labs/FLUX.1-dev"+ _fake_hf_api_with_shas(+ monkeypatch,+ {+ "unsloth/FLUX.1-dev-GGUF": ([_FakeSibling("flux1-dev-Q4_K_M.gguf", 7 * GB)], gguf_sha),+ base: (_FLUX_BASE_SIBLINGS, base_sha),+ },+ )+ monkeypatch.setattr("core.inference.diffusion._resolve_base_repo", lambda *a, **k: base)+ monkeypatch.setattr(+ DiffusionBackend, "_dense_quant_prefetch_needed", lambda self, fam, kwargs: False+ )+ _all_cached(monkeypatch)+ for name in _FLUX_BASE_SIBLINGS_BY_NAME:+ if _base_file_downloaded(name, include_transformer = False):+ _seed_cache_file(other, base, name, base_sha)+ _seed_cache_file(other, "unsloth/FLUX.1-dev-GGUF", "flux1-dev-Q4_K_M.gguf", gguf_sha)++ plan = DiffusionBackend().download_plan(+ "unsloth/FLUX.1-dev-GGUF", gguf_filename = "flux1-dev-Q4_K_M.gguf"+ )++ assert plan == {"entries": [], "total_bytes": 0}+++def test_files_already_cached_survives_an_unreadable_root(monkeypatch, tmp_path):+ """A cache we cannot read is not a verdict: the first root raising must not lose the second+ root's hit, nor abort the files after it."""+ live, other = _two_cache_roots(monkeypatch, tmp_path)+ sha = "d" * 40+ _seed_cache_file(other, "unsloth/FLUX.1-dev-GGUF", "flux1-dev-Q4_K_M.gguf", sha)+ import huggingface_hub++ real = huggingface_hub.try_to_load_from_cache++ def _boom(+ repo_id,+ filename,+ cache_dir = None,+ **kwargs,+ ):+ if str(cache_dir) == str(live):+ raise OSError("unreadable")+ return real(repo_id, filename, cache_dir = cache_dir, **kwargs)++ monkeypatch.setattr(huggingface_hub, "try_to_load_from_cache", _boom)++ assert DiffusionBackend._files_already_cached(+ "unsloth/FLUX.1-dev-GGUF", ["flux1-dev-Q4_K_M.gguf"], sha+ ) == {"flux1-dev-Q4_K_M.gguf"}+++def test_download_plan_stages_a_half_cached_repo_whole(monkeypatch):+ """Dropped only when ALL of it is cached: a shrinking file list would 409 a second pick sharing+ this base, since every diffusion entry rides the one "@diffusion" scope slot and+ download_registry refuses a claim whose scoped_files differ from the live job's."""+ _fake_hf_api(+ monkeypatch,+ {+ "unsloth/FLUX.1-dev-GGUF": [_FakeSibling("flux1-dev-Q4_K_M.gguf", 7 * GB)],+ "black-forest-labs/FLUX.1-dev": _FLUX_BASE_SIBLINGS,+ },+ )+ monkeypatch.setattr(+ "core.inference.diffusion._resolve_base_repo",+ lambda *a, **k: "black-forest-labs/FLUX.1-dev",+ )+ monkeypatch.setattr(+ DiffusionBackend, "_dense_quant_prefetch_needed", lambda self, fam, kwargs: False+ )+ _no_cache(monkeypatch)+ # The manifest is on disk, the VAE is not; the checkpoint repo is untouched.+ monkeypatch.setattr(+ DiffusionBackend,+ "_files_already_cached",+ staticmethod(+ lambda repo_id, files, revision = None: (+ set()+ if repo_id.endswith("-GGUF")+ else {n for n in files if n != "vae/diffusion_pytorch_model.safetensors"}+ )+ ),+ )++ plan = DiffusionBackend().download_plan(+ "unsloth/FLUX.1-dev-GGUF", gguf_filename = "flux1-dev-Q4_K_M.gguf"+ )++ by_repo = {e["repo_id"]: e for e in plan["entries"]}+ # Nothing is cached, so prefer_ungated_mirror swaps the gated vendor id for the mirror.+ assert set(by_repo) == {"unsloth/FLUX.1-dev-GGUF", "unsloth/FLUX.1-dev"}+ base = by_repo["unsloth/FLUX.1-dev"]+ # The whole scoped list, not just the missing VAE: the cached file is still staged.+ assert "vae/diffusion_pytorch_model.safetensors" in base["files"]+ assert "model_index.json" in base["files"]+ assert base["bytes"] == sum(+ size for name, size in _FLUX_BASE_SIBLINGS_BY_NAME.items() if name in base["files"]+ )+ # Derived, so the panel's rows and the bar it drives can never disagree.+ assert plan["total_bytes"] == sum(e["bytes"] for e in plan["entries"])+ assert all(e["files"] for e in plan["entries"])+++def test_download_plan_files_do_not_shrink_as_a_repo_warms(monkeypatch):+ """The scope-slot invariant, stated directly: for one pick, a repo's staged file list is the+ same whether none or some of it is on disk. Only all-cached removes the entry."""++ def _plan(cached_for_base):+ mp = pytest.MonkeyPatch()+ try:+ _fake_hf_api(+ mp,+ {+ "unsloth/FLUX.1-dev-GGUF": [_FakeSibling("flux1-dev-Q4_K_M.gguf", 7 * GB)],+ "black-forest-labs/FLUX.1-dev": _FLUX_BASE_SIBLINGS,+ },+ )+ mp.setattr(+ "core.inference.diffusion._resolve_base_repo",+ lambda *a, **k: "black-forest-labs/FLUX.1-dev",+ )+ mp.setattr(+ DiffusionBackend, "_dense_quant_prefetch_needed", lambda self, fam, kwargs: False+ )+ _no_cache(mp)+ mp.setattr(+ DiffusionBackend,+ "_files_already_cached",+ staticmethod(+ lambda repo_id, files, revision = None: (+ set() if repo_id.endswith("-GGUF") else set(cached_for_base(files))+ )+ ),+ )+ return DiffusionBackend().download_plan(+ "unsloth/FLUX.1-dev-GGUF", gguf_filename = "flux1-dev-Q4_K_M.gguf"+ )+ finally:+ mp.undo()++ cold = _plan(lambda files: [])+ half = _plan(lambda files: files[:1])+ most = _plan(lambda files: files[:-1])+ warm = _plan(lambda files: files)++ base_files = {e["repo_id"]: e["files"] for e in cold["entries"]}["unsloth/FLUX.1-dev"]+ for plan in (half, most):+ staged = {e["repo_id"]: e["files"] for e in plan["entries"]}+ assert staged["unsloth/FLUX.1-dev"] == base_files+ # Fully cached is the one state that removes the row.+ assert "unsloth/FLUX.1-dev" not in {e["repo_id"] for e in warm["entries"]}+++class _ShaInfo(_FakeInfo):+ """A model_info that carries a commit, as the real one does."""++ def __init__(self, siblings, sha):+ super().__init__(siblings)+ self.sha = sha+++def _fake_hf_api_with_shas(monkeypatch, repos):+ """_fake_hf_api, but each repo also reports the commit its listing describes."""++ class _Api:+ def model_info(+ self,+ repo_id,+ files_metadata = False,+ token = None,+ ):+ siblings, sha = repos[repo_id]+ return _ShaInfo(siblings, sha)++ monkeypatch.setattr("huggingface_hub.HfApi", lambda *a, **k: _Api())+++def test_download_plan_pins_each_probe_to_the_commit_it_just_read(monkeypatch):+ """Each probe gets the sha its own model_info reported, the MIRROR at ITS commit: a mirror is a+ separate repo with its own history, so the vendor's sha would never hit and a cached mirror+ would re-stage in full."""+ gguf_sha, vendor_sha, mirror_sha = "f" * 40, "d" * 40, "e" * 40+ _fake_hf_api_with_shas(+ monkeypatch,+ {+ "unsloth/FLUX.1-dev-GGUF": ([_FakeSibling("flux1-dev-Q4_K_M.gguf", 7 * GB)], gguf_sha),+ "black-forest-labs/FLUX.1-dev": (_FLUX_BASE_SIBLINGS, vendor_sha),+ "unsloth/FLUX.1-dev": (_FLUX_BASE_SIBLINGS, mirror_sha),+ },+ )+ monkeypatch.setattr(+ "core.inference.diffusion._resolve_base_repo",+ lambda *a, **k: "black-forest-labs/FLUX.1-dev",+ )+ monkeypatch.setattr(+ DiffusionBackend, "_dense_quant_prefetch_needed", lambda self, fam, kwargs: False+ )+ _no_cache(monkeypatch)+ seen: list = []+ monkeypatch.setattr(+ DiffusionBackend,+ "_files_already_cached",+ staticmethod(+ lambda repo_id, files, revision = None: seen.append((repo_id, revision)) or set()+ ),+ )++ DiffusionBackend().download_plan(+ "unsloth/FLUX.1-dev-GGUF", gguf_filename = "flux1-dev-Q4_K_M.gguf"+ )++ assert ("unsloth/FLUX.1-dev-GGUF", gguf_sha) in seen+ # Nothing is cached, so the swap fired and the base is staged from the mirror.+ assert ("unsloth/FLUX.1-dev", mirror_sha) in seen+ assert vendor_sha not in [rev for _repo, rev in seen]+++def test_download_plan_skips_nothing_when_the_hub_reports_no_commit(monkeypatch):+ """An old huggingface_hub, or a listing without a sha, must not fall back to the cache's own+ refs/main: no commit is no verdict, so the pick stages exactly as it did before #8154."""+ _fake_hf_api(+ monkeypatch,+ {+ "unsloth/FLUX.1-dev-GGUF": [_FakeSibling("flux1-dev-Q4_K_M.gguf", 7 * GB)],+ "black-forest-labs/FLUX.1-dev": _FLUX_BASE_SIBLINGS,+ },+ )+ monkeypatch.setattr(+ "core.inference.diffusion._resolve_base_repo",+ lambda *a, **k: "black-forest-labs/FLUX.1-dev",+ )+ monkeypatch.setattr(+ DiffusionBackend, "_dense_quant_prefetch_needed", lambda self, fam, kwargs: False+ )+ _no_cache(monkeypatch)+ revisions: list = []+ real = DiffusionBackend._files_already_cached++ def _spy(+ repo_id,+ files,+ revision = None,+ ):+ revisions.append(revision)+ return real(repo_id, files, revision)++ monkeypatch.setattr(DiffusionBackend, "_files_already_cached", staticmethod(_spy))++ plan = DiffusionBackend().download_plan(+ "unsloth/FLUX.1-dev-GGUF", gguf_filename = "flux1-dev-Q4_K_M.gguf"+ )++ assert revisions and all(rev is None for rev in revisions)+ assert {e["repo_id"] for e in plan["entries"]} == {+ "unsloth/FLUX.1-dev-GGUF",+ "unsloth/FLUX.1-dev",+ }