Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: stop a GGUF pick from pulling the wrong companion bytes (#7870)

Daniel Han82d3925b741a
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.py
index bba9ffac0b3..014926914df 100644
--- a/studio/backend/core/inference/diffusion.py
+++ b/studio/backend/core/inference/diffusion.py
@@ -20,6 +20,7 @@ from __future__ import annotations
import inspect
import json
+import os
import threading
import time
from dataclasses import dataclass
@@ -110,6 +111,7 @@ from .diffusion_precision import normalize_te_quant, quantize_text_encoders
from .diffusion_te_prequant import te_prequant_pipe_kwargs
from .diffusion_prequant import (
load_prequantized_transformer,
+ prequant_checkpoint_cached,
resolve_prequant_source,
usable_prequant_source,
)
@@ -431,6 +433,152 @@ def _assert_local_base_is_pipeline(base_repo: str) -> None:
)
+def _repo_access_message(repo: str, *, gated: bool) -> str:
+ """The repo id AND its licence page: the worker's 401/403 names neither, and the base comes
+ from a card tag, so the user never saw which repo it is."""
+ url = f"https://huggingface.co/{repo}"
+ if gated:
+ return (
+ f"'{repo}' is gated on Hugging Face and this model cannot be downloaded without it. "
+ f"Accept its licence at {url}, then add a Hugging Face token that has access in "
+ "Studio settings and try again."
+ )
+ return (
+ f"'{repo}' could not be read from Hugging Face (private, renamed or removed) and this "
+ f"model cannot be downloaded without it. Check {url}, then add a Hugging Face token that "
+ "has access in Studio settings and try again."
+ )
+
+
+def _assert_base_repo_accessible(
+ base_repo: str,
+ hf_token: Optional[str],
+ probe_file: str = "model_index.json",
+) -> Optional[str]:
+ """Fail up front, with the licence URL, when a companion base cannot be read.
+
+ The Hub gates the BYTE endpoint only, so ``model_info`` answers anonymously for gated repos and
+ a plan built from it dies mid-download on a bare token error. Probes ``probe_file`` (a file the
+ load fetches anyway) and only when ``gated`` is set, so an open repo costs one metadata call;
+ the native plan passes its own asset name, since a repo it reads only for a VAE has no manifest
+ cached. Fails open on any non-access error: offline/transient must not block a load.
+
+ Returns the base's snapshot dir when an ACCESS verdict was excused by a copy that lives only
+ under huggingface_hub's import-time cache root, so the caller can load off disk; None
+ otherwise. That escape is needed because ``from_pretrained`` is pinned to ``hub_cache_dir()``
+ and cannot see the other root, and the metadata failure that earned it also empties the size
+ estimate, so the prefetch stages nothing to reuse."""
+ repo = (base_repo or "").strip()
+ # Only a remote 'org/name' can be gated; a local base is already on disk.
+ if not repo or repo.count("/") != 1:
+ return None
+ # Blank to None, as load_pipeline does: build_hf_headers sends "" verbatim as a literal
+ # "Bearer " that 401s, which the handling below would read as an open base being unreadable.
+ hf_token = (hf_token.strip() if isinstance(hf_token, str) else hf_token) or None
+ try:
+ if Path(repo).expanduser().exists():
+ return None
+ # OSError: invalid path characters -> a remote id. RuntimeError: pathlib, not OSError, when
+ # expanduser() cannot resolve the home dir ('~other/models', or '~/models' with no HOME). Both
+ # have exactly one slash so they reach here, and an escape would 500 this fail-open probe.
+ except (OSError, RuntimeError, ValueError):
+ pass
+ try:
+ from huggingface_hub import HfApi, get_hf_file_metadata, hf_hub_url
+ from huggingface_hub.errors import (
+ GatedRepoError,
+ HfHubHTTPError,
+ RepositoryNotFoundError,
+ )
+ except Exception: # noqa: BLE001 — an unexpected hub layout leaves today's behaviour
+ return None
+
+ # Set when only huggingface_hub's import-time root holds the excusing copy, so the caller can
+ # load off disk: a from_pretrained pinned to hub_cache_dir() looks in the live root and misses.
+ other_root_snapshot: Optional[str] = None
+
+ # A base already on disk needs no Hub access, so refusing one would block a load that works
+ # today: hf_hub_download catches the gated/401 HEAD and serves the cached pointer
+ # (file_download._get_metadata_or_catch_error), which is how a downloaded gated base still
+ # loads once the token is cleared or expires. Excuses an ACCESS verdict only, never a 404: a
+ # renamed or removed repo cannot be un-renamed by a stale copy, and the size estimate swallows
+ # that 404 into a zero-byte plan.
+ def _already_downloaded() -> bool:
+ """True when ``probe_file`` is on disk under EITHER root (Studio pins its live setting, the
+ prefetch downloads under huggingface_hub's import-time constant). Never raises.
+
+ Exact for the native plan, which probes an asset it stages; a proxy for the diffusers plan,
+ which probes the manifest, so a manifest-cached base with missing shards passes and dies
+ mid-download on the bare token error -- the pre-preflight behaviour, never a blocked load."""
+ nonlocal other_root_snapshot
+ try:
+ from huggingface_hub import try_to_load_from_cache
+ for root in (hub_cache_dir(), None):
+ # Only a str is a cached path; a miss is None and an absent file is a sentinel.
+ hit = try_to_load_from_cache(repo, probe_file, cache_dir = root)
+ if isinstance(hit, str):
+ # The live root is tried first, so root None here means only the import-time
+ # one has it. Its parent is the snapshot dir only for a top-level probe, so a
+ # subfolder name yields nothing rather than a wrong root.
+ if root is None and "/" not in probe_file:
+ other_root_snapshot = str(Path(hit).parent)
+ return True
+ except Exception: # noqa: BLE001 — a cache we cannot read is not an access verdict
+ pass
+ return False
+
+ def _is_auth_error(exc: Any) -> bool:
+ """A 401/403 that hf_raise_for_status did not classify.
+
+ An expired token 401s "Invalid credentials in Authorization header", which _http.py
+ excludes from its RepoNotFound branch by name, and a token missing a permission 403s. Both
+ arrive as plain HfHubHTTPError, so catching only the classified errors fails open on
+ exactly the case this probe exists to catch."""
+ status = getattr(getattr(exc, "response", None), "status_code", None)
+ return status in (401, 403)
+
+ try:
+ gated = getattr(HfApi().model_info(repo, token = hf_token), "gated", None)
+ except GatedRepoError: # a gated repo can also withhold its metadata
+ if _already_downloaded():
+ return other_root_snapshot
+ raise ValueError(_repo_access_message(repo, gated = True)) from None
+ except RepositoryNotFoundError as exc:
+ # 401 and 404 both land here: hf_raise_for_status folds unauthenticated private/gated in
+ # with a missing repo, because "401 is misleading" (_http.py), so the status is re-read to
+ # tell them apart. A 401/403 is an ACCESS verdict and earns the same cache escape as the
+ # other access branches; a genuine 404 never does, and an error carrying no response reads
+ # as neither, so it raises: fail safe.
+ if _is_auth_error(exc) and _already_downloaded():
+ return other_root_snapshot
+ raise ValueError(_repo_access_message(repo, gated = False)) from None
+ except HfHubHTTPError as exc:
+ if not _is_auth_error(exc):
+ return None # a 5xx or rate limit is not an access verdict
+ if _already_downloaded():
+ return other_root_snapshot
+ raise ValueError(_repo_access_message(repo, gated = False)) from None
+ except Exception: # noqa: BLE001 — offline / transient: the download surfaces any real error
+ return None
+ # Nothing to carry: model_info answered, so the size estimate lists the base files and the
+ # prefetch already resolves each one through whichever root holds it.
+ if not gated or _already_downloaded():
+ return None
+ try:
+ # A metadata HEAD, never hf_hub_download: a cached manifest makes the download return the
+ # cached pointer, so a stale token would pass the probe and 401 again mid-prefetch.
+ get_hf_file_metadata(hf_hub_url(repo, probe_file), token = hf_token)
+ except GatedRepoError:
+ raise ValueError(_repo_access_message(repo, gated = True)) from None
+ except HfHubHTTPError as exc:
+ if not _is_auth_error(exc):
+ return None
+ raise ValueError(_repo_access_message(repo, gated = True)) from None
+ except Exception: # noqa: BLE001 — no manifest / offline / transient is not an access verdict
+ return None
+ return None
+
+
@dataclass(frozen = True)
class _LoadState:
"""Everything about the currently-loaded pipeline, swapped as one unit."""
@@ -570,6 +718,65 @@ def _install_gguf_prefix_strip(transformer_cls: Any, logger: Any) -> None:
logger.warning("diffusion.gguf: prefix-strip shim not installed: %s", exc)
+_NO_WEIGHT = object()
+
+
+def _has_active_lora(loras: Any) -> bool:
+ """True when any adapter would actually be baked, for either shape the callers pass.
+
+ Weight 0 means disabled, but /images/load passes ``(id, weight)`` tuples while
+ /images/download-plan passes ``LoraSpec`` models. Unpacking a pydantic model yields its
+ ``(field, value)`` pairs, so ``(_lid, w)`` would bind ``w`` to ``("weight", 0.0)`` and read a
+ disabled adapter as active; reading the attribute first covers both."""
+ for entry in loras or ():
+ weight = getattr(entry, "weight", _NO_WEIGHT)
+ if weight is _NO_WEIGHT:
+ try:
+ _lid, weight = entry
+ except (TypeError, ValueError): # an unrecognised shape is not a disabled adapter
+ return True
+ try:
+ if float(weight) != 0:
+ return True
+ except (TypeError, ValueError): # likewise: an unreadable weight must not skip the bake
+ return True
+ return False
+
+
+def _uncached_prequant_repo(
+ fam: Optional[DiffusionFamily],
+ target: Any,
+ requested: Optional[str],
+ *,
+ base_repo: Optional[str],
+ prequant_path: Optional[str],
+) -> Optional[str]:
+ """The hosted pre-quant repo an AUTO-derived quant would have to DOWNLOAD for this pick, or
+ None when it costs no extra bytes (no hosted source, a local override, or already cached).
+
+ Otherwise an auto GGUF pick fetches the GGUF and then a second multi-GB denoiser it uses
+ instead, which is not what "auto" may spend on the user's behalf. Shared by ``load_pipeline``
+ and ``_dense_quant_prefetch_needed`` so the load and the download plan decline together. Cheap
+ (a refs read + stat) and never raises."""
+ try:
+ scheme = select_transformer_quant_scheme(
+ target, requested, family = getattr(fam, "name", None)
+ )
+ if scheme is None:
+ return None
+ source = usable_prequant_source(
+ fam, scheme, path_override = prequant_path, base_repo = base_repo
+ )
+ # A local override is the operator's own file, so it never downloads.
+ if source is None or source.kind != "repo":
+ return None
+ if prequant_checkpoint_cached(source, cache_dir = hub_cache_dir()):
+ return None
+ return source.location
+ except Exception: # noqa: BLE001 — a probe that cannot answer keeps the prequant shortcut
+ return None
+
+
class DiffusionBackend:
"""Holds at most one loaded diffusers pipeline. All mutations are serialised."""
@@ -629,9 +836,34 @@ class DiffusionBackend:
local_root = Path(repo_id).expanduser()
if local_root.exists():
return str(resolve_local_gguf_child(local_root, gguf_filename))
- from huggingface_hub import hf_hub_download
-
- return hf_hub_download(repo_id, gguf_filename, token = hf_token)
+ from huggingface_hub import hf_hub_download, try_to_load_from_cache
+
+ # Pin the LIVE root, as the prefetch does. Unpinned, a mid-session cache change misses the
+ # GGUF the prefetch just staged and re-pulls the whole multi-GB file inside the load lock,
+ # after eviction, where unload cannot preempt it and progress already reported 100%.
+ cache_dir = hub_cache_dir()
+ # Both probes are best-effort: a malformed or unreadable cache raises here, and letting
+ # that escape would abort a remote load that only had to download. Any failure falls
+ # through to the pinned download below.
+ try:
+ if not isinstance(
+ try_to_load_from_cache(repo_id, gguf_filename, cache_dir = cache_dir), str
+ ):
+ # Same other-root reuse as the pre-quant checkpoint: re-fetching a copy that root
+ # already holds is the download this pins the root to avoid. Reached THROUGH that
+ # root rather than returned raw, so the ref still resolves and a republished GGUF is
+ # picked up; the blob is reused, and offline the cached pointer comes back anyway.
+ elsewhere = try_to_load_from_cache(repo_id, gguf_filename, cache_dir = None)
+ if isinstance(elsewhere, str) and Path(elsewhere).is_file():
+ try:
+ return hf_hub_download(
+ repo_id, gguf_filename, token = hf_token, cache_dir = None
+ )
+ except Exception: # noqa: BLE001 — revalidation is a bonus, never a new failure
+ return elsewhere
+ except Exception: # noqa: BLE001 — an unreadable cache is not a verdict, just download
+ pass
+ return hf_hub_download(repo_id, gguf_filename, token = hf_token, cache_dir = cache_dir)
def _dense_quant_prefetch_needed(self, fam: DiffusionFamily, kwargs: dict) -> bool:
"""True when ``load_pipeline`` may take the dense transformer-quant path, so
@@ -643,10 +875,12 @@ class DiffusionBackend:
"finalizing", after the previous pipeline was already evicted, where
unload/cancellation cannot preempt the download. Mirrors the dense-path
gates in ``load_pipeline``: quant requested and supported for this device,
- and no pre-quantized checkpoint that would shortcut the dense build."""
+ and no pre-quantized checkpoint that would shortcut the dense build. Callers only ask for
+ a ``kind == "gguf"`` pick, so the auto-quant decline below applies as written."""
raw = kwargs.get("transformer_quant")
# Unset defaults to the hardware ladder (mirrors load_pipeline's tri-state).
- if raw is None or str(raw).strip().lower() in ("", "auto"):
+ auto = raw is None or str(raw).strip().lower() in ("", "auto")
+ if auto:
mode = TQ_AUTO
else:
mode = normalize_transformer_quant(raw)
@@ -664,6 +898,23 @@ class DiffusionBackend:
if mm is None and kwargs.get("cpu_offload"):
return False
target = self._resolve_device_target(fam)
+ # Same decline as load_pipeline: an uncached hosted pre-quant keeps the GGUF, so the
+ # plan must not stage the base transformer/ shards either.
+ if (
+ auto
+ # Active weights only: an all-zero list is not a bake, and disagreeing here stages
+ # base transformer/ shards for a load that runs the GGUF.
+ and not _has_active_lora(kwargs.get("loras"))
+ and _uncached_prequant_repo(
+ fam,
+ target,
+ mode,
+ base_repo = kwargs.get("base_repo"),
+ prequant_path = kwargs.get("transformer_prequant_path"),
+ )
+ is not None
+ ):
+ return False
# Only widen when the loader would take the dense path; same candidate load_pipeline re-plans against.
candidate = resolve_dense_quant_candidate(
fam = fam,
@@ -671,7 +922,9 @@ class DiffusionBackend:
requested = mode,
base_repo = kwargs.get("base_repo"),
prequant_path = kwargs.get("transformer_prequant_path"),
- force_dense = bool(kwargs.get("loras")),
+ # Same rule as the decline above: an all-zero list bakes nothing, so sizing it
+ # dense stages transformer/ shards the load will not read.
+ force_dense = _has_active_lora(kwargs.get("loras")),
logger = None,
)
# A prequant loads a small checkpoint, so widening defeats the savings and can disk-full.
@@ -722,19 +975,46 @@ class DiffusionBackend:
base = fetch_base or prefer_ungated_mirror(base, hf_token, files = base_files)
# Callers without a per-load event (tests, direct use) fall back to the current one.
cancel = cancel_event if cancel_event is not None else self._cancel_event
+ # A file cached only under huggingface_hub's import-time root resolves through that root.
+ # The preflight clears a base found under EITHER root, so without this a cache-folder
+ # change turns an already-downloaded gated base into a mid-prefetch Hub token error (and
+ # every other moved asset into a needless re-download) on a load the preflight accepted.
# GGUF transformer (hub repos only; a local path is already on disk).
if gguf_filename and not Path(repo_id).expanduser().exists():
- hf_hub_download_with_xet_fallback(repo_id, gguf_filename, hf_token, cancel_event = cancel)
+ hf_hub_download_with_xet_fallback(
+ repo_id,
+ gguf_filename,
+ hf_token,
+ cancel_event = cancel,
+ reuse_other_cache_root = True,
+ )
# Base repo (VAE / text-encoder / scheduler); list comes from the estimate.
snapshot_root: Optional[str] = None
+ # reuse_other_cache_root resolves EACH file through whichever root holds it, so a moved
+ # cache can serve the manifest from the old root while the companions download into the
+ # live one. Returning the manifest's snapshot then points from_pretrained at a directory
+ # the rest of the files are not in, failing a load that would have worked off the hub id.
+ roots: set[str] = set()
for rfilename in base_files:
if cancel.is_set():
raise RuntimeError("Cancelled")
local = hf_hub_download_with_xet_fallback(
- base, rfilename, hf_token, cancel_event = cancel
+ base, rfilename, hf_token, cancel_event = cancel, reuse_other_cache_root = True
)
+ # The snapshot dir is the resolved path minus the file's own relative path, so a
+ # subfolder entry yields the same root as a top-level one. Not resolve()d: that would
+ # follow the symlink into blobs/ and leave the snapshot tree entirely.
+ try:
+ root = str(Path(local).parents[len(Path(rfilename).parts) - 1])
+ except (IndexError, ValueError, OSError):
+ root = ""
+ roots.add(root)
if rfilename == "model_index.json":
- snapshot_root = str(Path(local).parent)
+ snapshot_root = root or None
+ # Only hand back a snapshot the whole prefetched set actually lives in; otherwise fall
+ # back to the hub id, which resolves each file through its own root as before.
+ if snapshot_root is not None and roots != {snapshot_root}:
+ return None
return snapshot_root
def validate_load_request(
@@ -844,6 +1124,40 @@ class DiffusionBackend:
)
return fam
+ def preflight_base_access(
+ self,
+ repo_id: str,
+ fam: Optional[DiffusionFamily],
+ *,
+ gguf_filename: Optional[str] = None,
+ model_kind: Optional[str] = None,
+ base_repo: Optional[str] = None,
+ hf_token: Optional[str] = None,
+ ) -> None:
+ """The gated/unreadable-base refusal, run by the route BEFORE it takes the GPU.
+
+ ``_run_load`` and ``download_plan`` already make it, but ``_run_load`` runs on the load
+ thread, after the route evicted chat, and the plan's 400 does not stop the load: the images
+ page falls back to /images/load on ANY plan failure. Without this, a pick refused only at
+ plan time still unloads the resident chat/video model and only then reports the message.
+ Resolves the base exactly as those two do, so all three agree.
+
+ The one deliberate network step on the pre-eviction path (``validate_load_request`` stays
+ network-free): two metadata calls for a remote pick, none for a local one, both already
+ made by ``_run_load`` moments later. It fails open on offline/transient, so it can refuse
+ a load but never block one that would have worked."""
+ kind = resolve_model_kind(gguf_filename, model_kind)
+ if kind == "pipeline":
+ base = repo_id # the full pipeline IS the repo
+ else:
+ base = _resolve_base_repo(repo_id, base_repo, fam, hf_token)
+ # Probe the repo the load will FETCH from. Refusing the upstream id would reject exactly
+ # the gated picks the ungated mirror exists to rescue, and the swap is pure, so it takes
+ # the same decision here as on the load thread.
+ # The excused-snapshot return is for the loader's pinned from_pretrained; only the raise
+ # matters here, and _run_load recomputes it.
+ _assert_base_repo_accessible(prefer_ungated_mirror(base, hf_token), hf_token)
+
# ── Background load + progress ─────────────────────────────────────────
def begin_load(
@@ -961,6 +1275,14 @@ class DiffusionBackend:
# load_pipeline: per-call-site, one repo could be staged and the other assembled from.
fetch_base = prefer_ungated_mirror(base, kwargs.get("hf_token"), files = base_files)
kwargs["_fetch_base"] = fetch_base
+ # Same preflight the plan runs: catch a gated base here, not 15 GiB into the prefetch.
+ # Runs on ``fetch_base``, and only once it is decided, so it probes the repo the pull
+ # will actually read: refusing the upstream id would reject exactly the gated picks the
+ # ungated mirror rescues. Everything above is metadata (model_info answers anonymously
+ # for a gated repo), so no byte has moved yet.
+ # Returns a snapshot dir when it excused the base off a copy only the import-time root
+ # holds, which the pinned from_pretrained below could not reach.
+ base_snapshot = _assert_base_repo_accessible(fetch_base, kwargs.get("hf_token"))
with self._lock:
# Stamp progress only if this load is still current (a superseder has its own token).
if self._load_token == token and self._loading is not None:
@@ -968,14 +1290,21 @@ class DiffusionBackend:
self._loading.fetch_repo = fetch_base
self._loading.expected_bytes = expected
# Download outside the lock so unload/an eviction can preempt the pull.
- kwargs["_base_local_dir"] = self._prefetch_files(
- kwargs["repo_id"],
- kwargs.get("gguf_filename"),
- base,
- base_files,
- kwargs.get("hf_token"),
- cancel_event = cancel_event,
- fetch_base = fetch_base,
+ # The carried snapshot is the fallback, never the override: it only fires when the
+ # estimate came back empty, since the base metadata that fills it is the same call
+ # whose failure earned the escape. Without it the load ends on the bare Hub auth error
+ # with every byte already on disk.
+ kwargs["_base_local_dir"] = (
+ self._prefetch_files(
+ kwargs["repo_id"],
+ kwargs.get("gguf_filename"),
+ base,
+ base_files,
+ kwargs.get("hf_token"),
+ cancel_event = cancel_event,
+ fetch_base = fetch_base,
+ )
+ or base_snapshot
)
self.load_pipeline(**kwargs)
with self._lock:
@@ -1208,11 +1537,19 @@ class DiffusionBackend:
hf_token,
kind = kind,
single_file_is_pipeline = bool(fam and fam.single_file_is_pipeline),
+ # The RESOLVED base, as the load passes it: a variant base picks its own pre-quant repo.
include_transformer = kind == "gguf"
- and self._dense_quant_prefetch_needed(fam, load_kwargs),
+ and self._dense_quant_prefetch_needed(fam, {**load_kwargs, "base_repo": base}),
sizes_out = sizes,
skip_te_components = tuple(te_files),
)
+ # Decided once, from the staged file list, and both probed and reported: a gated base
+ # answers model_info anonymously, so the plan would otherwise be confident and the 401 land
+ # mid-download. Probing the UPSTREAM would instead refuse the gated picks the mirror
+ # rescues, and probing a different id from the one staged would refuse a load that works.
+ # The route maps ValueError -> 400. Nothing above downloads, so the reorder costs nothing.
+ 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():
entries.append(
@@ -1239,7 +1576,7 @@ class DiffusionBackend:
# API base repo, saved configs and LoRA tags keep the vendor id; sizes key on it too.
entries.append(
{
- "repo_id": prefer_ungated_mirror(base, hf_token, files = base_files),
+ "repo_id": fetch_base,
"files": base_files,
"bytes": int(sizes.get(base, 0)),
"gguf_filename": None,
@@ -1257,28 +1594,117 @@ class DiffusionBackend:
return Path(hub_cache_dir()) / f"models--{repo_id.replace('/', '--')}"
@staticmethod
- def _cache_bytes(repo_id: str) -> int:
- blobs = DiffusionBackend._hub_cache_repo_dir(repo_id) / "blobs"
- total = 0
+ def _hub_cache_repo_dirs(repo_id: str) -> list[Path]:
+ """``repo_id``'s cache dir under EVERY root a load can resolve it through, live root first.
+
+ The loader reuses a file cached only under huggingface_hub's import-time root
+ (``reuse_other_cache_root``, and the gated preflight excuses a base off it), so after a
+ mid-session cache-folder change the bytes the load reads are not in the live root at all.
+ Sizing that root alone reads zero for them. The constant is read HERE, never bound at
+ import: it is what ``cache_dir = None`` resolves to, and tests move it."""
+ # One read of the live root: it is a setting, and load_progress polls this from another
+ # thread, so a second read could land the other side of a cache-folder change and compare
+ # the new root against a `live` built from the old one.
+ live_root = hub_cache_dir()
+ folder = f"models--{repo_id.replace('/', '--')}"
+ live = Path(live_root) / folder
try:
- for entry in blobs.iterdir():
- try:
- total += entry.stat().st_size
- except OSError:
- continue # broken symlink / unreadable
- except OSError:
- return 0 # repo not in cache yet
- return total
+ from huggingface_hub import constants
+ other = str(constants.HF_HUB_CACHE or "").strip()
+ except Exception: # noqa: BLE001 — no hub package: the live root still stands
+ return [live]
+ if not other:
+ return [live]
+ # normcase/normpath before comparing: on Windows the two roots can differ by case alone,
+ # and every caller below would then walk the same tree twice. Best-effort -- an aliased
+ # spelling just costs a second walk, since both readers below are idempotent.
+ if os.path.normcase(os.path.normpath(other)) == os.path.normcase(
+ os.path.normpath(live_root)
+ ):
+ return [live]
+ return [live, Path(other) / folder]
@staticmethod
- def _local_dir_weight_bytes(path: Path, *, exclude_transformer: bool) -> int:
- """Sum the on-disk weight files under a local diffusers directory. The HF blob
- cache is empty for a local path, so this is the only size signal for auto memory
- planning; without it a large local model folds to zero and the planner skips
- offload and OOMs. ``exclude_transformer`` drops the ``transformer/`` subfolder
- for GGUF/single-file loads (their transformer is the single file, not resident
- here); a full pipeline load keeps it (the whole repo is resident)."""
- total = 0
+ def _live_snapshot_dir(repo_dir: Path) -> Optional[Path]:
+ """The snapshot ``refs/main`` names: the ONE revision a load reads out of this root.
+
+ ``try_to_load_from_cache`` (what the per-file root reuse probes with) defaults to
+ ``main`` and resolves it through ``refs/main``, so this is exactly the tree the loader
+ will read here. None when the cache does not say -- no ref file (a revision pinned to a
+ commit hash never writes one), unreadable, or the snapshot it names is gone. Callers then
+ fall back to reading the whole root: a cache we cannot scope must still report its bytes,
+ never zero."""
+ try:
+ rev = (repo_dir / "refs" / "main").read_text(encoding = "utf-8").strip()
+ except (OSError, ValueError):
+ return None
+ # A ref file holds a bare commit hash; anything with a separator is not one, and joining
+ # it would walk out of the cache.
+ if not rev or rev in (".", "..") or "/" in rev or "\\" in rev:
+ return None
+ snapshot = repo_dir / "snapshots" / rev
+ return snapshot if snapshot.is_dir() else None
+
+ @staticmethod
+ def _cache_bytes(repo_id: str) -> int:
+ """Bytes of ``repo_id`` on disk across every cache root, for progress and the pipeline plan.
+
+ Scoped per root to the revision that root serves (``refs/main``), because ``blobs/`` is
+ append-only: a republished repo leaves the superseded revision's blobs there forever, and
+ they carry different etags from the ones now downloading, so nothing dedupes them. Summing
+ the whole dir then counts a stale full copy on top of the live partial one and
+ ``load_progress`` reports "finalizing" through the rest of a multi-GB pull. The in-flight
+ ``blobs/*.incomplete`` still counts: it is this download's own bytes, and dropping it would
+ freeze the bar for the length of each shard.
+
+ Keyed by blob filename, not summed per root: a blob is named after the file's etag, so the
+ same file carries the same name in either root and a copy present in both must count once.
+ Scanning only the live root reports 0 for a load a moved cache serves entirely off disk,
+ which pins the progress bar near 0% for the whole construction."""
+ sizes: dict[str, int] = {}
+
+ def _add(key: str, path: Path) -> None:
+ try:
+ size = path.stat().st_size
+ except OSError:
+ return # broken symlink / unreadable
+ sizes[key] = max(sizes.get(key, 0), size)
+
+ for repo_dir in DiffusionBackend._hub_cache_repo_dirs(repo_id):
+ snapshot = DiffusionBackend._live_snapshot_dir(repo_dir)
+ try:
+ blobs = list((repo_dir / "blobs").iterdir())
+ except OSError:
+ blobs = [] # repo not in this root yet / unreadable / no-symlink cache mode
+ if snapshot is None:
+ # Unscopeable root: read every blob, as before.
+ for entry in blobs:
+ _add(entry.name, entry)
+ continue
+ for entry in blobs:
+ if entry.name.endswith(".incomplete"):
+ _add(entry.name, entry)
+ try:
+ for f in snapshot.rglob("*"):
+ if not f.is_file():
+ continue
+ # Dedupe on the path INSIDE the snapshot, so one logical file counts once
+ # however many roots hold it. The etag would not: each root serves its own
+ # revision, and a republished file has a different blob hash in each, so
+ # keying on that summed both copies and could report finalizing at roughly
+ # half the real progress. Works for a no-symlink cache too, which stores the
+ # file in the snapshot rather than linking to blobs/.
+ _add(f"path:{f.relative_to(snapshot).as_posix()}", f)
+ except OSError:
+ pass # the download is writing this tree under the walk; report what we counted
+ return sum(sizes.values())
+
+ @staticmethod
+ def _local_dir_weight_sizes(path: Path, *, exclude_transformer: bool) -> dict[str, int]:
+ """``{relative path: on-disk bytes}`` for the weight files under a diffusers directory.
+ Per file, not a total, so callers merging several trees can dedupe by path. See
+ ``_local_dir_weight_bytes`` for what the filter is for."""
+ sizes: dict[str, int] = {}
for f in path.rglob("*"):
if f.suffix.lower() not in (".safetensors", ".bin", ".pt", ".ckpt"):
continue
@@ -1289,34 +1715,82 @@ class DiffusionBackend:
if exclude_transformer and rel.parts and rel.parts[0] == "transformer":
continue
try:
- total += f.stat().st_size
+ sizes[rel.as_posix()] = f.stat().st_size
except OSError:
continue
- return total
+ return sizes
+
+ @staticmethod
+ def _local_dir_weight_bytes(path: Path, *, exclude_transformer: bool) -> int:
+ """Sum the on-disk weight files under a local diffusers directory. The HF blob
+ cache is empty for a local path, so this is the only size signal for auto memory
+ planning; without it a large local model folds to zero and the planner skips
+ offload and OOMs. ``exclude_transformer`` drops the ``transformer/`` subfolder
+ for GGUF/single-file loads (their transformer is the single file, not resident
+ here); a full pipeline load keeps it (the whole repo is resident)."""
+ return sum(
+ DiffusionBackend._local_dir_weight_sizes(
+ path, exclude_transformer = exclude_transformer
+ ).values()
+ )
@staticmethod
- def _max_over_cached_revs(base: str, fn: Callable[[Path], int]) -> int:
- """Apply ``fn`` to a LOCAL diffusers dir, or to the fullest cached hub snapshot
- revision (the active one is the fullest), returning that count. 0 when nothing is
- cached. Multiple revisions may be cached, so take the max."""
+ def _union_over_cached_revs(
+ base: str,
+ fn: Callable[[Path], dict[str, int]],
+ staged_dir: Optional[str] = None,
+ ) -> int:
+ """Total ``fn`` over a LOCAL diffusers dir, or over the UNION of every tree this load could
+ read ``base`` from. 0 when nothing is cached.
+
+ ``fn`` maps a directory to ``{relative path: count}`` so the merge happens per FILE. The
+ candidates are every cached snapshot revision under EVERY cache root, plus ``staged_dir``
+ (the snapshot the prefetch/preflight handed back). Both roots because the loader's per-file
+ root reuse resolves EACH file through whichever root holds it, so after a cache-folder
+ change the candidates are disjoint PARTS of one repo, not copies of it: a text encoder left
+ in the old snapshot and a VAE prefetched into the live one both load, and taking the larger
+ total would budget only one of them -- under-counting leaves an auto plan resident and
+ OOMing on weights it never counted. Keying on the relative path is what keeps that safe for
+ genuine copies too: a file mirrored in two roots, or shared by two revisions, still counts
+ once, at its largest copy. It also makes the staged dir purely additive, so a snapshot
+ carrying only part of the repo cannot erase what a root does hold."""
local = Path(base).expanduser()
if local.is_dir():
- return fn(local)
- snapshots = DiffusionBackend._hub_cache_repo_dir(base) / "snapshots"
- if not snapshots.is_dir():
- return 0
- return max((fn(rev) for rev in snapshots.iterdir() if rev.is_dir()), default = 0)
+ return sum(fn(local).values())
+ candidates: list[Path] = [Path(staged_dir).expanduser()] if staged_dir else []
+ for repo_dir in DiffusionBackend._hub_cache_repo_dirs(base):
+ # One revision per root, the one that root serves: the merge is per FILE, so pulling in
+ # a superseded revision whose shards were repacked would count both namings and force
+ # offload on a base that fits. Only a root naming no revision falls back to all of
+ # them, where over-counting still beats reading zero.
+ live_rev = DiffusionBackend._live_snapshot_dir(repo_dir)
+ if live_rev is not None:
+ candidates.append(live_rev)
+ continue
+ try:
+ candidates.extend(rev for rev in (repo_dir / "snapshots").iterdir() if rev.is_dir())
+ except OSError:
+ continue # a root with no copy of this repo contributes nothing
+ merged: dict[str, int] = {}
+ for candidate in candidates:
+ if not candidate.is_dir():
+ continue
+ for rel, count in fn(candidate).items():
+ merged[rel] = max(merged.get(rel, 0), count)
+ return sum(merged.values())
@staticmethod
- def _companion_cache_bytes(base: str) -> int:
+ def _companion_cache_bytes(base: str, staged_dir: Optional[str] = None) -> int:
"""Resident companion (VAE + text-encoder) size for the memory plan.
Excludes ``transformer/`` (supplied by the GGUF/single file, not resident here) --
otherwise the dense-quant prefetch's cached transformer shards would inflate this
and wrongly force offload. Walks the snapshot dir, not the flat ``blobs/`` cache,
since only the snapshot preserves the subfolder split needed to exclude it."""
- return DiffusionBackend._max_over_cached_revs(
- base, lambda d: DiffusionBackend._local_dir_weight_bytes(d, exclude_transformer = True)
+ return DiffusionBackend._union_over_cached_revs(
+ base,
+ lambda d: DiffusionBackend._local_dir_weight_sizes(d, exclude_transformer = True),
+ staged_dir,
)
@staticmethod
@@ -1340,24 +1814,27 @@ class DiffusionBackend:
return 0
@staticmethod
- def _dense_transformer_resident_bytes(base: str) -> int:
+ def _dense_transformer_resident_bytes(base: str, staged_dir: Optional[str] = None) -> int:
"""Resident bf16 size of the base repo's dense ``transformer/`` for the dense-quant
preflight. That fast path loads the transformer at the compute dtype (bf16, 2
bytes/param) before quantizing, so budget num_params * 2 -- NOT the on-disk bytes,
which for an F32 base (e.g. Z-Image) are ~2x the resident size. Read from the
safetensors shard headers. Returns 0 when no ``transformer/*.safetensors`` shards
are present (an uncached base, or a .bin-only transformer); the caller then gates
- the fast path on the plain plan."""
+ the fast path on the plain plan -- so a base whose shards this misses skips the fit
+ check entirely and lets the dense build OOM under a plan sized for the GGUF."""
- def _params(d: Path) -> int:
+ def _params(d: Path) -> dict[str, int]:
tdir = d / "transformer"
if not tdir.is_dir():
- return 0
- return sum(
- DiffusionBackend._safetensors_param_count(s) for s in tdir.glob("*.safetensors")
- )
+ return {}
+ return {
+ f"transformer/{s.name}": DiffusionBackend._safetensors_param_count(s)
+ for s in tdir.glob("*.safetensors")
+ }
- return DiffusionBackend._max_over_cached_revs(base, _params) * 2 # bf16: 2 bytes/param
+ # bf16: 2 bytes/param
+ return DiffusionBackend._union_over_cached_revs(base, _params, staged_dir) * 2
# ── Synchronous load / generate / unload ───────────────────────────────
@@ -1479,14 +1956,17 @@ class DiffusionBackend:
cpu_offload,
kind = kind,
repo_id = repo_id,
+ # The base may be resolved off the OTHER cache root, which the plan's live-root
+ # scans read as zero companions.
+ base_local_dir = _base_local_dir,
fetch_base = fetch_base,
)
# Dtype tri-state: unset/"auto" -> hardware ladder; "none"/"off" pins GGUF-as-is; an explicit scheme pins it.
- if transformer_quant is None or str(transformer_quant).strip().lower() in (
- "",
- "auto",
- ):
+ transformer_quant_auto = transformer_quant is None or str(
+ transformer_quant
+ ).strip().lower() in ("", "auto")
+ if transformer_quant_auto:
# An explicit Speed="off" stays GGUF-as-is: auto-quant would break the bit-exact request.
speed_off = (
speed_mode is not None and str(speed_mode).strip().lower() == SPEED_OFF
@@ -1497,17 +1977,40 @@ class DiffusionBackend:
pipe = None
transformer_quant_engaged = None
quant_plan = None
- # The GGUF-size plan can mis-budget the fast path, so preflight the real footprint pre-eviction.
+ # The GGUF-size plan can mis-budget the fast path, so preflight the real footprint pre-eviction. Also set below when an auto quant declines a hosted pre-quant.
dense_declined = False
# False when the plan only holds a PREQUANT-sized build: a failed prequant load must raise, not materialise the
# unbudgeted dense bf16 transformer. Also false when the prefetch skipped the base repo's transformer/ shards, since
# the fallback would pull them HERE, inside the load lock, after eviction, where unload cannot preempt it and
# progress already reported 100%.
dense_fallback_allowed = bool(_transformer_prefetched)
+ # A GGUF pick with the scheme left to us: the hosted pre-quant is free only while
+ # already cached, since fetching it means a SECOND multi-GB denoiser and the GGUF
+ # never runs. An explicit scheme, a LoRA bake and every non-GGUF kind keep today's
+ # behaviour, where the prequant IS the point. An all-zero-weight list is not a
+ # bake, so plain truthiness would fetch the dense companion for no adapter at all.
+ baking_loras = _has_active_lora(loras)
+ if kind == "gguf" and transformer_quant_auto and not baking_loras:
+ uncached_prequant = _uncached_prequant_repo(
+ fam,
+ target,
+ transformer_quant,
+ base_repo = base,
+ prequant_path = transformer_prequant_path,
+ )
+ if uncached_prequant is not None:
+ logger.info(
+ "diffusion.transformer_quant_declined: pre-quant checkpoint in %s is "
+ "not cached (an auto quant never downloads a second transformer for a "
+ "GGUF pick); loading the GGUF",
+ uncached_prequant,
+ )
+ dense_declined = True
if (
kind == "gguf"
and normalize_transformer_quant(transformer_quant) is not None
and dense_transformer_supported(target)
+ and not dense_declined
):
if plan.offload_policy != OFFLOAD_NONE:
# The GGUF plan picked offload but the quantised artifact is smaller, so re-plan: a resident quant build wins.
@@ -1518,7 +2021,7 @@ class DiffusionBackend:
base_repo = base,
prequant_path = transformer_prequant_path,
# A LoRA bake skips the prequant shortcut, so size for the dense build it will run.
- force_dense = bool(loras),
+ force_dense = _has_active_lora(loras),
logger = logger,
)
if candidate is not None:
@@ -1577,7 +2080,7 @@ class DiffusionBackend:
prequant = (
# A LoRA bake skips the prequant shortcut, so gate the fast path as if no prequant existed.
None
- if loras
+ if _has_active_lora(loras)
else usable_prequant_source(
fam,
scheme,
@@ -1587,9 +2090,14 @@ class DiffusionBackend:
if scheme is not None
else None
)
- # Reads the cache, so it has to look where the prefetch wrote.
+ # Reads the cache, so it looks where the prefetch WROTE (the mirror when one
+ # was swapped in), and carries the staged snapshot as the plan below does: a
+ # base served wholly from the import-time root sizes as 0 on the hub id
+ # alone, and a 0 skips this whole fit check, so the dense build would land
+ # under a GGUF-sized plan.
dense_mib = int(
- self._dense_transformer_resident_bytes(fetch_base) // (1024 * 1024)
+ self._dense_transformer_resident_bytes(fetch_base, _base_local_dir)
+ // (1024 * 1024)
)
if dense_mib > 0:
dense_plan = self._plan_memory(
@@ -1603,6 +2111,9 @@ class DiffusionBackend:
repo_id = repo_id,
fetch_base = fetch_base,
transformer_resident_override_mib = dense_mib,
+ # No companion_override here, so this one reads the cache: point it
+ # at the snapshot the load will read, not the live root alone.
+ base_local_dir = _base_local_dir,
)
if dense_plan.offload_policy != OFFLOAD_NONE:
dense_fallback_allowed = False
@@ -1656,7 +2167,7 @@ class DiffusionBackend:
pipe is None
and kind == "gguf"
and normalize_transformer_quant(transformer_quant) is not None
- and any(w != 0 for (_lid, w) in (loras or ()))
+ and _has_active_lora(loras)
):
# Adapters were requested BAKED but that build failed, and the GGUF fallback cannot carry them; fail loudly.
raise RuntimeError(
@@ -2139,8 +2650,10 @@ class DiffusionBackend:
# Bail BEFORE the multi-GB dense download: an unsupported scheme (fp8 on Ampere, nvfp4 off Blackwell) would
# materialise the transformer only to fail at quantize, after eviction. load_pipeline falls back to GGUF.
raise RuntimeError("transformer quant unsupported for this device/scheme")
- if fam is not None and not lora_specs:
- # A LoRA bake needs the DENSE transformer (adapters attach before quantize_), so skip prequant.
+ if fam is not None and not _has_active_lora(lora_specs):
+ # A LoRA bake needs the DENSE transformer (adapters attach before quantize_), so skip
+ # prequant. Active weights only: an all-zero list bakes nothing and must not cost the
+ # caller the dense build the decline above already declined to pay for.
source = resolve_prequant_source(
fam, scheme, path_override = prequant_path, base_repo = base
)
@@ -2157,6 +2670,9 @@ class DiffusionBackend:
min_features = DEFAULT_MIN_LINEAR_FEATURES,
# Only enforced when the caller forces fp8 fast-accum; a checkpoint that baked the other choice falls to the dense path.
fast_accum = fast_accum,
+ # The root _uncached_prequant_repo cleared this load against, so its hit is
+ # reused rather than re-downloaded under the import-time constant.
+ cache_dir = hub_cache_dir(),
logger = logger,
)
if transformer is not None:
@@ -2181,6 +2697,12 @@ class DiffusionBackend:
raise RuntimeError(
"prequant checkpoint unavailable and the dense transformer does not fit resident"
)
+ # Deliberately the hub id, not base_local_dir: diffusers treats a local directory as
+ # terminal (_get_model_file raises "Error no file named ..." rather than falling back to
+ # the hub), and a sharded load raises per missing shard, so a snapshot holding
+ # transformer/config.json, or 2 of 3 shards, would drop a build the hub id completes. Off
+ # the hub id a base only the other root holds costs a re-download, or 401s into the GGUF
+ # fallback, which is what main does today.
transformer = transformer_cls.from_pretrained(
fetch_base,
subfolder = "transformer",
@@ -2201,7 +2723,7 @@ class DiffusionBackend:
target = target,
fetch_base = fetch_base,
)
- if lora_specs:
+ if _has_active_lora(lora_specs):
# Bake the adapters BEFORE quantize_: peft wraps the dense Linears (post-quant torchao dispatch would TypeError),
# then quantize_ converts only each wrapper's frozen base_layer while the "lora_" side path stays high precision.
baked = self._resolve_lora_set(
@@ -2325,6 +2847,7 @@ class DiffusionBackend:
repo_id: Optional[str] = None,
transformer_resident_override_mib: Optional[int] = None,
companion_override_mib: Optional[int] = None,
+ base_local_dir: Optional[str] = None,
fetch_base: Optional[str] = None,
):
"""Build the memory plan for this load: snapshot free device memory and
@@ -2345,6 +2868,13 @@ class DiffusionBackend:
same blob cache _companion_cache_bytes sums -- are not counted as companions on
top of transformer_resident_override_mib (a double-count of the transformer).
+ ``base_local_dir`` is the snapshot the load will actually read, carried into the size
+ lookups as an extra source alongside the cache roots. A prefetch split across roots hands
+ back no snapshot at all, and a preflight-excused one can hold less than the repo, so it is
+ additive and never a replacement: the companion lookup unions the sources file by file and
+ the pipeline branch takes the fullest, since under-counting here leaves an auto plan
+ resident and OOMing on weights it never budgeted.
+
``fetch_base`` is the repo the bytes were staged from, so every cache scan below reads it:
sizing an upstream id whose cache is empty folds the VAE/text-encoder to zero and wrongly
picks resident placement. ``base`` and ``repo_id`` keep the upstream identity for the
@@ -2354,11 +2884,24 @@ class DiffusionBackend:
if kind == "pipeline":
# The whole repo is one cached download, so cached bytes are the resident estimate; a LOCAL path is not cached, so sum its on-disk weights.
local_repo = Path(repo_id).expanduser() if repo_id else None
+ staged_repo = Path(base_local_dir).expanduser() if base_local_dir else None
+ # The bytes land under the repo they were STAGED from, so scan the mirror when there
+ # is one: scanning an upstream id whose cache is empty folds the whole pipeline to
+ # zero and wrongly picks resident placement.
cache_repo = fetch_base or repo_id
- if local_repo is not None and local_repo.is_dir():
- cached = self._local_dir_weight_bytes(local_repo, exclude_transformer = False)
- else:
- cached = self._cache_bytes(cache_repo) if cache_repo else 0
+ # Largest of every source the load can read this repo from. A staged snapshot can sit
+ # under the OTHER cache root, and a prefetch that landed half the repo in each root
+ # hands back none at all -- so neither the snapshot nor the cache scan alone sees the
+ # whole thing, and the smaller answer would plan a multi-GB pipeline as unknown.
+ cached = max(
+ self._local_dir_weight_bytes(local_repo, exclude_transformer = False)
+ if local_repo is not None and local_repo.is_dir()
+ else 0,
+ self._local_dir_weight_bytes(staged_repo, exclude_transformer = False)
+ if staged_repo is not None and staged_repo.is_dir()
+ else 0,
+ self._cache_bytes(cache_repo) if cache_repo else 0,
+ )
cached_mib = int(cached // (1024 * 1024)) if cached else None
model_dense_mib = estimate_safetensors_dense_mib(cached_mib)
# A repo can store weights NARROWER than the loaded dtype (ideogram-4 ships raw float8), so cached bytes
@@ -2400,7 +2943,11 @@ class DiffusionBackend:
# Re-planning the dense candidate: the prefetched transformer/ shards land in the same cache, so use the estimate instead of double-counting.
companion_mib = companion_override_mib
else:
- companion = self._companion_cache_bytes(fetch_base or base)
+ # Scan the repo the bytes were staged from, and hand over the staged snapshot too:
+ # a base served from the import-time root is invisible to a hub-id scan of the
+ # live one, so the VAE + text encoders would load unbudgeted (transformer/ stays
+ # excluded either way).
+ companion = self._companion_cache_bytes(fetch_base or base, base_local_dir)
companion_mib = int(companion // (1024 * 1024)) if companion else None
model_dense_mib = None
if transformer_resident is not None:
@@ -2891,7 +3438,7 @@ class DiffusionBackend:
# Deferred speed auto: engage the compile profile on the 3rd image. Best-effort; a failure stays eager and never retries.
# NOT when a LoRA is requested: a compiled transformer rejects LoRA, breaking every LoRA generation on this load.
- lora_requested = any(w != 0 for (_id, w) in (loras or []))
+ lora_requested = _has_active_lora(loras)
# Also stay eager while a PRIOR generation's adapters are attached: compiling would bake them in permanently.
loras_attached = bool(getattr(state.pipe, "_unsloth_loras", ()))
if (
diff --git a/studio/backend/core/inference/diffusion_engine_router.py b/studio/backend/core/inference/diffusion_engine_router.py
index 6cc6f1c94e0..6c7ce4d549d 100644
--- a/studio/backend/core/inference/diffusion_engine_router.py
+++ b/studio/backend/core/inference/diffusion_engine_router.py
@@ -73,9 +73,12 @@ def _engine_config() -> tuple[str, str, bool]:
return forced, sd_cpp, mps
-def get_active_diffusion_engine() -> Any:
- """The engine object the active selection points at (defaults to diffusers)."""
- if _active_engine_name == ENGINE_SD_CPP:
+def engine_for(name: str) -> Any:
+ """The engine object a name refers to, WITHOUT activating it (nothing is unloaded).
+
+ Lets a caller reach the engine a load is ABOUT to switch to -- the pre-activation gated-repo
+ preflight in /images/load -- since activating it first is what unloads the resident model."""
+ if name == ENGINE_SD_CPP:
from core.inference.sd_cpp_backend import get_sd_cpp_backend
return get_sd_cpp_backend()
from core.inference.diffusion import get_diffusion_backend
@@ -83,6 +86,11 @@ def get_active_diffusion_engine() -> Any:
return get_diffusion_backend()
+def get_active_diffusion_engine() -> Any:
+ """The engine object the active selection points at (defaults to diffusers)."""
+ return engine_for(_active_engine_name)
+
+
def active_engine_name() -> str:
return _active_engine_name
diff --git a/studio/backend/core/inference/diffusion_prequant.py b/studio/backend/core/inference/diffusion_prequant.py
index 5d8849c703d..27778d95835 100644
--- a/studio/backend/core/inference/diffusion_prequant.py
+++ b/studio/backend/core/inference/diffusion_prequant.py
@@ -162,6 +162,55 @@ def usable_prequant_source(
return src
+def cached_checkpoint_path(source: Any, *, cache_dir: Optional[str] = None) -> Optional[str]:
+ """The path of a hosted (``kind == "repo"``) checkpoint ALREADY in the local Hub cache.
+
+ A pure lookup (a refs read plus a stat, no network), so memory planning can ask on every pick.
+ Only the PRIMARY ``filename`` counts: a cached ``fallback_filename`` (the legacy artifact) must
+ not short-circuit it, or a stale name stays pinned forever once the repo ships the real one.
+ The primary's remote existence cannot be known without a network call, so a fallback-only cache
+ reads as "this would have to download" and the GGUF simply runs.
+
+ Both cache roots are searched: Studio pins the LIVE cache setting while an unpinned
+ ``hf_hub_download`` falls back to huggingface_hub's import-time constant. Never raises."""
+ for root in (cache_dir, None) if cache_dir else (None,):
+ hit = _cached_in_root(source, root)
+ if hit is not None:
+ return hit
+ return None
+
+
+def _cached_in_root(
+ source: Any,
+ root: Optional[str],
+ name: Optional[str] = None,
+) -> Optional[str]:
+ """One checkpoint name's path inside ONE cache root, or None. Defaults to the primary name; the
+ resolver passes ``fallback_filename`` once the primary turns out to be absent. Never raises."""
+ if source is None or getattr(source, "kind", None) != "repo":
+ return None
+ name = name or getattr(source, "filename", None)
+ if not name:
+ return None
+ try:
+ import os
+
+ from huggingface_hub import try_to_load_from_cache
+ except Exception: # noqa: BLE001 — no cache API to ask: treat as not cached
+ return None
+ try:
+ hit = try_to_load_from_cache(source.location, name, cache_dir = root)
+ except Exception: # noqa: BLE001 — a malformed cache entry is not a hit
+ return None
+ # A str is the cached path; a miss is None and a known-absent file is a sentinel object.
+ return hit if isinstance(hit, str) and os.path.isfile(hit) else None
+
+
+def prequant_checkpoint_cached(source: Any, *, cache_dir: Optional[str] = None) -> bool:
+ """True when ``source`` resolves from the cache, i.e. enabling prequant costs no download."""
+ return cached_checkpoint_path(source, cache_dir = cache_dir) is not None
+
+
def _pin_kernel_preference(state_dict: Any, logger: Any = None) -> int:
"""Force every loaded fp8 weight onto the plain-torch kernel, matching the local path.
@@ -206,10 +255,15 @@ def load_prequantized_transformer(
scheme: str,
min_features: Optional[int] = None,
fast_accum: Optional[bool] = None,
+ cache_dir: Optional[str] = None,
logger: Any = None,
) -> Optional[Any]:
"""Load the pre-quantized transformer described by ``source`` onto ``device``.
+ ``cache_dir`` is the live Hub cache root, as every other loader call pins it: unset, a fetch
+ lands under huggingface_hub's import-time constant, so a mid-session cache change re-downloads
+ the checkpoint into a root Studio is no longer reading.
+
Returns the placed transformer, or None on any problem (missing / mismatched /
unreadable checkpoint, or unsupported meta-init) so the caller falls back to
dense-quantise. Best-effort: never raises for an unavailable artifact.
@@ -228,7 +282,7 @@ def load_prequantized_transformer(
)
return None
- path = _resolve_checkpoint_path(source, hf_token)
+ path = _resolve_checkpoint_path(source, hf_token, cache_dir)
if path is None:
return None
@@ -243,7 +297,11 @@ def load_prequantized_transformer(
state_dict = ckpt["state_dict"]
_pin_kernel_preference(state_dict, logger)
- config = transformer_cls.load_config(base, subfolder = "transformer", token = hf_token)
+ # The root that actually supplied the checkpoint above, which is the import-time one
+ # whenever the resolver answered from there. After a mid-session cache change the pinned
+ # root may be gone or read-only, and load_config's raise is swallowed below into a None
+ # return -- silently dropping a prequant whose checkpoint is cached and already loaded.
+ config = _load_transformer_config(transformer_cls, base, hf_token, cache_dir, path)
from accelerate import init_empty_weights
with init_empty_weights():
@@ -278,7 +336,86 @@ def load_prequantized_transformer(
return None
-def _resolve_checkpoint_path(source: PrequantSource, hf_token: Optional[str]) -> Optional[str]:
+def _entry_not_found_errors() -> tuple:
+ """``(EntryNotFoundError, LocalEntryNotFoundError)`` for both huggingface_hub majors.
+
+ On 1.x the base splits into a remote 404 and ``LocalEntryNotFoundError`` (no copy in this root
+ and no network). On BOTH majors local subclasses the base, so it must be caught first wherever
+ the two mean different things. Private markers on an unexpected layout: nothing raises them, so
+ the caller keeps today's behaviour."""
+ try:
+ from huggingface_hub.errors import EntryNotFoundError
+ except Exception: # noqa: BLE001 — older/newer hub layouts
+
+ class EntryNotFoundError(Exception): # type: ignore[no-redef]
+ pass
+
+ try:
+ from huggingface_hub.errors import LocalEntryNotFoundError
+ except Exception: # noqa: BLE001
+
+ class LocalEntryNotFoundError(EntryNotFoundError): # type: ignore[no-redef]
+ pass
+
+ return EntryNotFoundError, LocalEntryNotFoundError
+
+
+def _download_checkpoint_name(
+ source: PrequantSource,
+ name: str,
+ hf_token: Optional[str],
+ cache_dir: Optional[str],
+ *,
+ propagate_missing: bool,
+) -> str:
+ """Download ONE checkpoint filename, reusing a copy that sits under the other cache root.
+
+ Only the OTHER root needs handling: pinned to ``cache_dir``, hf_hub_download would not look
+ there and would re-fetch multiple GB, the download the caller declined on. So re-run it THROUGH
+ that root instead of returning the raw path: an unchanged repo reuses the blob for one HEAD,
+ a republished checkpoint is picked up rather than pinned stale, and offline still resolves off
+ the cached pointer.
+
+ ``propagate_missing`` says another filename is still to be tried, so a remote 404 for THIS one
+ must reach the caller's fallback branch; swallowing it would return the stale other-root copy
+ of a name the repo no longer publishes and never reach the fallback that IS valid. A local
+ cache miss is not that verdict, and with no name left to try neither is a 404: both keep the
+ copy already found, so revalidation stays a bonus and never a new failure."""
+ from huggingface_hub import hf_hub_download
+
+ EntryNotFoundError, LocalEntryNotFoundError = _entry_not_found_errors()
+
+ if cache_dir is not None and _cached_in_root(source, cache_dir, name) is None:
+ elsewhere = _cached_in_root(source, None, name)
+ if elsewhere is not None:
+ try:
+ return hf_hub_download(
+ repo_id = source.location,
+ filename = name,
+ token = hf_token,
+ cache_dir = None,
+ )
+ except LocalEntryNotFoundError: # offline with the copy right there: use it
+ return elsewhere
+ except EntryNotFoundError:
+ if not propagate_missing:
+ return elsewhere
+ raise
+ except Exception: # noqa: BLE001 — revalidation is a bonus, never a new failure
+ return elsewhere
+ return hf_hub_download(
+ repo_id = source.location,
+ filename = name,
+ token = hf_token,
+ cache_dir = cache_dir,
+ )
+
+
+def _resolve_checkpoint_path(
+ source: PrequantSource,
+ hf_token: Optional[str],
+ cache_dir: Optional[str] = None,
+) -> Optional[str]:
"""The local file path for ``source``, downloading from the Hub if needed; None if absent."""
if source.kind == "path":
import os
@@ -287,27 +424,75 @@ def _resolve_checkpoint_path(source: PrequantSource, hf_token: Optional[str]) ->
expanded = os.path.expanduser(source.location)
return expanded if os.path.isfile(expanded) else None
if source.kind == "repo":
- from huggingface_hub import hf_hub_download
- try:
- from huggingface_hub.errors import EntryNotFoundError
- except Exception: # noqa: BLE001 — older hub layouts; fall back to a private marker
-
- class EntryNotFoundError(Exception): # type: ignore[no-redef]
- pass
-
+ EntryNotFoundError, _ = _entry_not_found_errors()
+ has_fallback = (
+ bool(source.fallback_filename) and source.fallback_filename != source.filename
+ )
try:
- return hf_hub_download(
- repo_id = source.location, filename = source.filename, token = hf_token
+ return _download_checkpoint_name(
+ source,
+ source.filename,
+ hf_token,
+ cache_dir,
+ propagate_missing = has_fallback,
)
except EntryNotFoundError:
- if not source.fallback_filename or source.fallback_filename == source.filename:
+ if not has_fallback:
raise
- return hf_hub_download(
- repo_id = source.location, filename = source.fallback_filename, token = hf_token
+ # The primary is genuinely absent, so the legacy name gets the same other-root
+ # treatment, with nothing left to fall back to.
+ return _download_checkpoint_name(
+ source,
+ source.fallback_filename,
+ hf_token,
+ cache_dir,
+ propagate_missing = False,
)
return None
+def _config_cache_roots(checkpoint_path: str, cache_dir: Optional[str]) -> tuple:
+ """Cache roots to read the transformer config from, the checkpoint's OWN root first.
+
+ ``_resolve_checkpoint_path`` may answer from huggingface_hub's import-time root even when
+ Studio pins its live one, so pinning the config to the live root alone misses in exactly the
+ cache-moved/offline case the checkpoint lookup just accepted -- and load_config's raise is
+ swallowed into a None return. The other root is still tried second, so nothing that resolves
+ today stops resolving."""
+ if cache_dir is None:
+ return (None,)
+ import os
+
+ try:
+ # normcase before comparing: on Windows a plain startswith says "not under the live root"
+ # on nothing more than C:\Users vs c:\users and silently reverses the order below.
+ root = os.path.normcase(os.path.realpath(cache_dir))
+ real = os.path.normcase(os.path.realpath(checkpoint_path))
+ under_live = real == root or real.startswith(root + os.sep)
+ except Exception: # noqa: BLE001 — an unresolvable path keeps today's order
+ under_live = True
+ return (cache_dir, None) if under_live else (None, cache_dir)
+
+
+def _load_transformer_config(
+ transformer_cls: Any,
+ base: str,
+ hf_token: Optional[str],
+ cache_dir: Optional[str],
+ checkpoint_path: str,
+) -> Any:
+ """``transformer_cls.load_config`` against the checkpoint's cache root, then the other one."""
+ last: Optional[BaseException] = None
+ for root in _config_cache_roots(checkpoint_path, cache_dir):
+ try:
+ return transformer_cls.load_config(
+ base, subfolder = "transformer", token = hf_token, cache_dir = root
+ )
+ except Exception as exc: # noqa: BLE001 — try the other root before giving up
+ last = exc
+ raise last # type: ignore[misc]
+
+
def _validate_checkpoint(
ckpt: Any,
scheme: str,
diff --git a/studio/backend/core/inference/sd_cpp_backend.py b/studio/backend/core/inference/sd_cpp_backend.py
index c00ec348398..b0c4400f0ff 100644
--- a/studio/backend/core/inference/sd_cpp_backend.py
+++ b/studio/backend/core/inference/sd_cpp_backend.py
@@ -548,6 +548,13 @@ class SdCppDiffusionBackend:
specs = self._asset_specs(repo_id, gguf_filename, fam)
fetch_repo = _fetch_repo_map(specs, hf_token)
assets = [(fetch_repo[repo], fn, kind) for repo, fn, kind in specs]
+ # Same preflight the plan runs, and on the POST-swap repos: catch a gated companion
+ # here, not 15 GiB into the prefetch, but do not refuse one whose ungated mirror is
+ # standing in for it. The plan alone is not enough -- the images page falls back to
+ # calling this load directly when the plan call fails, skipping the check entirely.
+ self._preflight_companion_repos(
+ self._assets_by_repo(assets), fetch_repo.get(repo_id, repo_id), hf_token
+ )
self._set_expected_bytes(assets, hf_token)
paths = self._fetch_assets(assets, hf_token, cancel_event = cancel_event)
@@ -696,15 +703,7 @@ class SdCppDiffusionBackend:
raise ValueError(f"'{repo_id}' has no native sd.cpp asset mapping.")
specs = self._asset_specs(repo_id, gguf_filename, fam)
- # Group by repo so a family whose VAE and encoder share a repo yields one entry, keeping first-seen order (transformer first).
- by_repo: dict[str, list[str]] = {}
- for repo, filename, kind in specs:
- # A local GGUF directory is already on disk; nothing to stage for it.
- if kind == "diffusion_model" and Path(repo).expanduser().exists():
- continue
- names = by_repo.setdefault(repo, [])
- if filename not in names:
- names.append(filename)
+ by_repo = self._assets_by_repo(specs)
# STAGED before the load runs, so each entry must name the repo _fetch_assets will pull
# from: some asset repos are gated (the FLUX.1 VAE lives in black-forest-labs/FLUX.1-schnell)
@@ -713,6 +712,9 @@ class SdCppDiffusionBackend:
fetch_repo = _fetch_repo_map(specs, hf_token)
by_repo = {fetch_repo[repo]: names for repo, names in by_repo.items()}
fetch_repo_id = fetch_repo.get(repo_id, repo_id)
+ # AFTER the swap: the point of the mirror is that a gated companion no longer blocks the
+ # load, so preflighting the upstream id would refuse the very picks the mirror rescues.
+ self._preflight_companion_repos(by_repo, fetch_repo_id, hf_token)
sizes = self._plan_file_sizes(by_repo, hf_token)
entries: list[dict[str, Any]] = []
total = 0
@@ -730,6 +732,74 @@ class SdCppDiffusionBackend:
)
return {"entries": entries, "total_bytes": total}
+ @staticmethod
+ def _assets_by_repo(specs: list[tuple[str, str, str]]) -> dict[str, list[str]]:
+ """repo -> the files this pick needs from it, first-seen order (transformer first), so a
+ family whose VAE and text encoder share a repo yields one entry."""
+ by_repo: dict[str, list[str]] = {}
+ for repo, filename, kind in specs:
+ # A local GGUF directory is already on disk; nothing to stage or preflight for it.
+ if kind == "diffusion_model":
+ try:
+ if Path(repo).expanduser().exists():
+ continue
+ except (OSError, RuntimeError, ValueError):
+ pass # unresolvable home / invalid path characters -> a remote id
+ names = by_repo.setdefault(repo, [])
+ if filename not in names:
+ names.append(filename)
+ return by_repo
+
+ @staticmethod
+ def _preflight_companion_repos(
+ by_repo: dict[str, list[str]], repo_id: str, hf_token: Optional[str]
+ ) -> None:
+ """Refuse a companion repo this pick cannot read, before any byte is fetched.
+
+ The native asset list carries its own companion repos (flux.1's VAE is the gated
+ black-forest-labs/FLUX.1-schnell), and neither ``_plan_file_sizes`` nor the size probe
+ surfaces the 401: the entry is planned at 0 bytes and the fetch dies on the bare Hub token
+ error this preflight exists to replace. Run from BOTH the plan and ``_run_load``, as the
+ diffusers backend does, because the UI falls back to /images/load when the plan call
+ fails, so a 400 raised only at plan time is swallowed."""
+ from core.inference.diffusion import _assert_base_repo_accessible
+ for repo, names in by_repo.items():
+ # Companions only, mirroring the diffusers plan: the picker only lists repos it could
+ # already read.
+ if repo != repo_id and names:
+ # Probe an asset THIS pick stages: a repo read only for its VAE has no pipeline
+ # manifest, so the default name would neither verify access nor see the cache.
+ _assert_base_repo_accessible(repo, hf_token, names[0])
+
+ def preflight_base_access(
+ self,
+ repo_id: str,
+ fam: Optional[DiffusionFamily],
+ *,
+ gguf_filename: Optional[str] = None,
+ model_kind: Optional[str] = None,
+ base_repo: Optional[str] = None,
+ hf_token: Optional[str] = None,
+ ) -> None:
+ """The companion refusal ``_run_load`` makes, run by the route BEFORE it takes the GPU.
+
+ Same signature and reason as the diffusers backend's: ``_run_load`` runs on the load
+ thread, after a forced-native load on a GPU host already evicted chat, so a pick refused
+ only there unloads the resident model first. Nothing to check without a family or a
+ checkpoint name -- the asset list needs both, and the route already rejected those picks."""
+ if fam is None or not gguf_filename:
+ return
+ # Post-swap, as the plan and the load both are: probing the upstream id would refuse
+ # exactly the gated companions the ungated mirror stands in for. The swap is pure, so all
+ # three take the same decision.
+ specs = self._asset_specs(repo_id, gguf_filename, fam)
+ fetch_repo = _fetch_repo_map(specs, hf_token)
+ self._preflight_companion_repos(
+ self._assets_by_repo([(fetch_repo[r], fn, kind) for r, fn, kind in specs]),
+ fetch_repo.get(repo_id, repo_id),
+ hf_token,
+ )
+
@staticmethod
def _plan_file_sizes(
by_repo: dict[str, list[str]], hf_token: Optional[str]
@@ -814,7 +884,13 @@ class SdCppDiffusionBackend:
if kind == "diffusion_model" and local_root.exists():
path = str(resolve_local_gguf_child(local_root, fn))
else:
- path = hf_hub_download_with_xet_fallback(repo, fn, hf_token, cancel_event = cancel)
+ # An asset cached only under huggingface_hub's import-time root resolves through
+ # that root, matching the preflight, which clears a base found under EITHER root.
+ # Pinned to the live one, a cache-folder change re-downloads every moved asset and
+ # turns an already-downloaded gated base into the bare Hub token error.
+ path = hf_hub_download_with_xet_fallback(
+ repo, fn, hf_token, cancel_event = cancel, reuse_other_cache_root = True
+ )
paths[kind] = path
with self._lock:
if self._loading is not None:
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 31d2d380a95..6328ae9a7d0 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -18991,8 +18991,11 @@ async def load_diffusion_model(
)
from core.inference.diffusion_device import resolve_diffusion_device_target
from core.inference.diffusion_engine_router import (
+ active_engine_name,
annotate_status,
begin_load_on,
+ engine_for,
+ predict_engine,
select_and_activate_engine,
)
from core.inference.gpu_arbiter import acquire_for, release, DIFFUSION
@@ -19019,13 +19022,51 @@ async def load_diffusion_model(
)
# Refuse while training is running: a multi-GB pipeline would compete with the training subprocess for VRAM.
_guard_diffusion_load_against_training()
+ # Take the GPU from chat only when the resolved device is non-CPU: gate on the device, not the engine name.
+ # A pure resolve, so it is read before selection, which the refusal below has to precede.
+ device = await asyncio.to_thread(lambda: resolve_diffusion_device_target().device)
+ needs_gpu = device != "cpu"
+
+ def _preflight(target):
+ # The gated/unreadable-companion refusal, asked of ONE engine (they check different repos).
+ return target.preflight_base_access(
+ request.model_path,
+ fam,
+ gguf_filename = request.gguf_filename,
+ model_kind = kind,
+ base_repo = request.base_repo,
+ hf_token = request.hf_token,
+ )
+
+ # Last refusal before anything is torn down: a gated/unreadable companion repo. The download
+ # plan makes the same check, but the images page falls back to THIS route whenever the plan
+ # call fails, and the loader's own copy runs on the load thread, after acquire_for already
+ # evicted chat. It also has to precede selection: activating the other engine unloads the
+ # current one, so a pick refused afterwards destroys the very model this preserves. Costs two
+ # metadata calls the load makes anyway, fails open on offline/transient, and runs only where
+ # something is at stake -- a GPU handoff, or an engine switch.
+ try:
+ pending_name = predict_engine(fam, model_kind = kind) if fam is not None else None
+ except Exception: # noqa: BLE001 -- a probe failure must not refuse a loadable pick
+ pending_name = None
+ preflighted = None
+ if pending_name is not None and (needs_gpu or pending_name != active_engine_name()):
+ preflighted = engine_for(pending_name)
+ await asyncio.to_thread(_preflight, preflighted)
+
# Pick the engine for this host (diffusers on GPU, native sd.cpp otherwise), installing sd-cli if needed, BEFORE evicting chat.
engine = await asyncio.to_thread(
select_and_activate_engine, fam, hf_token = request.hf_token, model_kind = kind
)
- # Take the GPU from chat only when the resolved device is non-CPU: gate on the device, not the engine name.
- device = await asyncio.to_thread(lambda: resolve_diffusion_device_target().device)
- needs_gpu = device != "cpu"
+ # predict_engine is the selection's read-only twin, not the selection: it never installs,
+ # so a host where the sd-cli install then fails lands on the OTHER engine. Ask the engine
+ # actually activated whenever the prediction missed, so neither the GPU handoff nor the
+ # load is made on an unread companion. Same call the (correct) prediction already made, so
+ # never paid twice. Runs on the CPU path too when a preflight was already owed there: the
+ # switch is what is at stake, and it happens whether or not a GPU is involved. Where none
+ # was owed, CPU still pays nothing.
+ if (needs_gpu or preflighted is not None) and engine is not preflighted:
+ await asyncio.to_thread(_preflight, engine)
def _start_engine_load():
# Kicks the slow load onto a background thread and returns at once (the client polls images/load-progress).
diff --git a/studio/backend/tests/test_diffusion_backend.py b/studio/backend/tests/test_diffusion_backend.py
index 19c3ddf0701..74ac703cf72 100644
--- a/studio/backend/tests/test_diffusion_backend.py
+++ b/studio/backend/tests/test_diffusion_backend.py
@@ -2006,9 +2006,16 @@ def test_begin_load_rejects_concurrent(monkeypatch):
monkeypatch.setattr(
DiffusionBackend, "load_pipeline", lambda self, **k: __import__("time").sleep(0.2)
)
+ before = set(threading.enumerate())
backend.begin_load("unsloth/Z-Image-Turbo-GGUF", gguf_filename = "z-image-turbo-Q4_K_S.gguf")
with pytest.raises(RuntimeError):
backend.begin_load("unsloth/Z-Image-Turbo-GGUF", gguf_filename = "z-image-turbo-Q4_K_S.gguf")
+ # Drain the worker while the stubs above still make it exit in 0.2s. begin_load's thread is
+ # fire-and-forget, so left running it outlives this test, monkeypatch reverts load_pipeline
+ # under it, and it then runs the REAL one inside whatever test is current -- inheriting that
+ # test's class-level patches and landing in its assertions.
+ for thread in set(threading.enumerate()) - before:
+ thread.join(timeout = 5)
def test_unload_cancels_in_flight_load(fake_runtime):
@@ -2315,7 +2322,11 @@ def test_plan_memory_sizes_the_mirrored_companion_cache(monkeypatch, tmp_path):
monkeypatch.setattr(
DiffusionBackend,
"_companion_cache_bytes",
- staticmethod(lambda base: 8 * 1024 * 1024 if base == "unsloth/FLUX.1-dev" else 0),
+ # Second arg is the staged snapshot dir, unused here: what this pins is that the
+ # MIRROR id is the one sized.
+ staticmethod(
+ lambda base, staged = None: 8 * 1024 * 1024 if base == "unsloth/FLUX.1-dev" else 0
+ ),
)
seen: dict = {}
monkeypatch.setattr(
@@ -3079,7 +3090,7 @@ def test_dense_quant_skipped_when_dense_transformer_does_not_fit(
monkeypatch.setattr(
DiffusionBackend,
"_dense_transformer_resident_bytes",
- staticmethod(lambda base: 40 * 1024**3),
+ staticmethod(lambda base, staged_dir = None: 40 * 1024**3),
)
orig_plan = DiffusionBackend._plan_memory
@@ -3131,7 +3142,7 @@ def test_dense_quant_prequant_proceeds_but_forbids_dense_fallback(
monkeypatch.setattr(
DiffusionBackend,
"_dense_transformer_resident_bytes",
- staticmethod(lambda base: 999 * 1024**3),
+ staticmethod(lambda base, staged_dir = None: 999 * 1024**3),
)
dense_refit_ran = []
orig_plan = DiffusionBackend._plan_memory
@@ -3142,7 +3153,10 @@ def test_dense_quant_prequant_proceeds_but_forbids_dense_fallback(
transformer_resident_override_mib = None,
**k,
):
- if transformer_resident_override_mib is not None:
+ # Scoped to this backend: begin_load runs on a daemon thread, so an earlier test's load
+ # can still be in flight here, and _plan_memory is patched on the CLASS. Counting every
+ # instance lets that stray thread land in this assertion.
+ if transformer_resident_override_mib is not None and self is backend:
dense_refit_ran.append(True)
# GGUF budget fits (real plan -> none); the dense-transformer preflight does not.
return types.SimpleNamespace(offload_policy = "model")
@@ -3594,7 +3608,7 @@ def test_dense_quant_unusable_prequant_path_runs_dense_refit(fake_runtime, tmp_p
monkeypatch.setattr(
DiffusionBackend,
"_dense_transformer_resident_bytes",
- staticmethod(lambda base: 999 * 1024**3),
+ staticmethod(lambda base, staged_dir = None: 999 * 1024**3),
)
dense_refit_ran = []
orig_plan = DiffusionBackend._plan_memory
@@ -3605,7 +3619,10 @@ def test_dense_quant_unusable_prequant_path_runs_dense_refit(fake_runtime, tmp_p
transformer_resident_override_mib = None,
**k,
):
- if transformer_resident_override_mib is not None:
+ # Scoped to this backend: begin_load runs on a daemon thread, so an earlier test's load
+ # can still be in flight here, and _plan_memory is patched on the CLASS. Counting every
+ # instance is what made this assert [True, True] on the slower CI runners.
+ if transformer_resident_override_mib is not None and self is backend:
dense_refit_ran.append(True)
return orig_plan(self, *a, **k)
@@ -3790,6 +3807,305 @@ def test_dense_quant_prefetch_needed_gates(fake_runtime, monkeypatch):
assert backend._dense_quant_prefetch_needed(fam, {"transformer_quant": "fp8"}) is False
+# ── an auto quant never buys a second denoiser for a GGUF pick ────────────────
+
+
+_HOSTED_PREQUANT = types.SimpleNamespace(
+ kind = "repo",
+ location = "unsloth/Z-Image-Turbo-FP8",
+ filename = "Z-Image-Turbo-FP8.pt",
+ fallback_filename = "transformer_fp8.pt",
+)
+
+
+def _stub_hosted_prequant(monkeypatch, *, cached: bool):
+ """Resolve the family's hosted fp8 checkpoint, present or absent from the cache."""
+ from core.inference import diffusion as dmod
+
+ monkeypatch.setattr(dmod, "dense_transformer_supported", lambda target: True)
+ monkeypatch.setattr(
+ dmod, "select_transformer_quant_scheme", lambda target, mode, family = None: "fp8"
+ )
+ monkeypatch.setattr(dmod, "usable_prequant_source", lambda fam, scheme, **kw: _HOSTED_PREQUANT)
+ monkeypatch.setattr(dmod, "prequant_checkpoint_cached", lambda source, **kw: cached)
+
+
+def _spy_dense_quant(monkeypatch):
+ """Record every dense/prequant fast-path build and keep it from running.
+
+ Keyed by backend INSTANCE: the patch is class-level and an earlier test's begin_load can leave
+ a daemon thread still loading, so a bare count is not this test's. Read via ``_dense_calls``."""
+ calls: list = []
+
+ def _record(self, *a, **k):
+ calls.append((self, k.get("prequant_path")))
+ return None, None
+
+ monkeypatch.setattr(DiffusionBackend, "_load_dense_quant_pipeline", _record)
+ return calls
+
+
+def _dense_calls(calls, backend):
+ """The recorded fast-path builds belonging to ``backend`` alone."""
+ return [prequant_path for (owner, prequant_path) in calls if owner is backend]
+
+
+def test_auto_quant_declines_an_uncached_hosted_prequant(fake_runtime, tmp_path, monkeypatch):
+ # The reported bug: picking unsloth/Z-Image-GGUF fetched the GGUF and THEN a 6.29 GB hosted fp8
+ # checkpoint that became the denoiser, so the GGUF was never used.
+ _stub_hosted_prequant(monkeypatch, cached = False)
+ calls = _spy_dense_quant(monkeypatch)
+ backend = DiffusionBackend()
+ _force_cuda_target(backend, monkeypatch)
+ (tmp_path / "m.gguf").write_bytes(b"x")
+
+ status = backend.load_pipeline(str(tmp_path), gguf_filename = "m.gguf", family_override = "z-image")
+
+ # The fast path never ran, so nothing fetched a second transformer.
+ assert _dense_calls(calls, backend) == []
+ assert status["loaded"] is True
+ assert status["transformer_quant"] is None
+ assert _FakeTransformer.last["path"] # the GGUF the user picked
+
+
+def test_auto_quant_takes_a_hosted_prequant_that_is_already_cached(
+ fake_runtime, tmp_path, monkeypatch
+):
+ # Free shortcuts are still taken: dense+torchao beats per-matmul dequant and costs no bytes.
+ _stub_hosted_prequant(monkeypatch, cached = True)
+ calls = _spy_dense_quant(monkeypatch)
+ backend = DiffusionBackend()
+ _force_cuda_target(backend, monkeypatch)
+ (tmp_path / "m.gguf").write_bytes(b"x")
+
+ backend.load_pipeline(str(tmp_path), gguf_filename = "m.gguf", family_override = "z-image")
+
+ assert len(_dense_calls(calls, backend)) == 1
+
+
[email protected]("loras", [[("adapter", 0.0)], [("a", 0.0), ("b", 0.0)]])
+def test_all_zero_weight_loras_do_not_look_like_a_bake(loras, fake_runtime, tmp_path, monkeypatch):
+ # Weight 0 is disabled everywhere else, so plain truthiness on the list would call this a bake,
+ # skip the decline and fetch the dense companion for a request that applies no adapter.
+ _stub_hosted_prequant(monkeypatch, cached = False)
+ calls = _spy_dense_quant(monkeypatch)
+ backend = DiffusionBackend()
+ _force_cuda_target(backend, monkeypatch)
+ (tmp_path / "m.gguf").write_bytes(b"x")
+
+ backend.load_pipeline(
+ str(tmp_path), gguf_filename = "m.gguf", family_override = "z-image", loras = loras
+ )
+
+ assert _dense_calls(calls, backend) == []
+
+
+def test_a_weighted_lora_is_still_treated_as_a_bake(fake_runtime, tmp_path, monkeypatch):
+ # The other direction, so the zero-weight fix does not turn every bake into a GGUF load: a real
+ # adapter still takes the dense route, which this runtime reports rather than silently drops.
+ _stub_hosted_prequant(monkeypatch, cached = False)
+ _spy_dense_quant(monkeypatch)
+ backend = DiffusionBackend()
+ _force_cuda_target(backend, monkeypatch)
+ (tmp_path / "m.gguf").write_bytes(b"x")
+
+ with pytest.raises(RuntimeError, match = "LoRA adapters could not be applied"):
+ backend.load_pipeline(
+ str(tmp_path),
+ gguf_filename = "m.gguf",
+ family_override = "z-image",
+ loras = [("adapter", 0.8)],
+ )
+
+
+def test_an_explicit_quant_request_still_downloads_the_hosted_prequant(
+ fake_runtime, tmp_path, monkeypatch
+):
+ # Only the AUTO-derived case is restricted: asking for fp8 asks for the artifact serving it.
+ _stub_hosted_prequant(monkeypatch, cached = False)
+ calls = _spy_dense_quant(monkeypatch)
+ backend = DiffusionBackend()
+ _force_cuda_target(backend, monkeypatch)
+ (tmp_path / "m.gguf").write_bytes(b"x")
+
+ backend.load_pipeline(
+ str(tmp_path),
+ gguf_filename = "m.gguf",
+ family_override = "z-image",
+ transformer_quant = "fp8",
+ )
+
+ assert len(_dense_calls(calls, backend)) == 1
+
+
+def test_a_baked_lora_load_is_unaffected_by_the_prequant_cache(fake_runtime, tmp_path, monkeypatch):
+ # A LoRA bake needs the DENSE transformer and the GGUF fallback cannot carry the adapters.
+ _stub_hosted_prequant(monkeypatch, cached = False)
+ calls = _spy_dense_quant(monkeypatch)
+ backend = DiffusionBackend()
+ _force_cuda_target(backend, monkeypatch)
+ (tmp_path / "m.gguf").write_bytes(b"x")
+
+ with pytest.raises(RuntimeError, match = "LoRA"):
+ backend.load_pipeline(
+ str(tmp_path),
+ gguf_filename = "m.gguf",
+ family_override = "z-image",
+ loras = [("adapter", 1.0)],
+ )
+
+ assert len(_dense_calls(calls, backend)) == 1
+
+
+ "lora_specs, consults_prequant",
+ [([("adapter", 0.0)], True), ([("adapter", 0.8)], False), (None, True)],
+)
+def test_the_dense_builder_skips_the_prequant_only_for_a_real_bake(
+ lora_specs, consults_prequant, fake_runtime, monkeypatch
+):
+ # The decline let the auto path continue, but this builder's own gate read the raw list as
+ # truthy and built the dense transformer for adapters that apply nothing. The rule holds here
+ # too, not just at the decline.
+ import contextlib
+
+ from core.inference import diffusion as dmod
+
+ consulted: list = []
+ monkeypatch.setattr(
+ dmod, "select_transformer_quant_scheme", lambda target, mode, family = None: "fp8"
+ )
+ monkeypatch.setattr(
+ dmod, "resolve_prequant_source", lambda *a, **k: consulted.append(1) or None
+ )
+ backend = DiffusionBackend()
+ target = _force_cuda_target(backend, monkeypatch)
+
+ with contextlib.suppress(Exception): # the build cannot complete here; the gate is the subject
+ backend._load_dense_quant_pipeline(
+ object(),
+ object(),
+ "Tongyi-MAI/Z-Image-Turbo",
+ "cuda",
+ None,
+ None,
+ target,
+ "fp8",
+ None,
+ fam = detect_family("unsloth/Z-Image-GGUF"),
+ lora_specs = lora_specs,
+ )
+
+ assert bool(consulted) is consults_prequant
+
+
+def test_the_plan_does_not_force_a_dense_bake_for_disabled_adapters(fake_runtime, monkeypatch):
+ # The gate above stopped calling it a bake, but the candidate sizing below still passed
+ # force_dense on the raw list, staging base transformer/ shards while the load ran the cached
+ # prequant. Both must read the same rule.
+ from core.inference import diffusion as dmod
+
+ backend = DiffusionBackend()
+ _force_cuda_target(backend, monkeypatch)
+ fam = detect_family("unsloth/Z-Image-GGUF")
+ forced: list = []
+ monkeypatch.setattr(
+ dmod,
+ "resolve_dense_quant_candidate",
+ lambda **kw: forced.append(kw.get("force_dense")) or types.SimpleNamespace(prequant = True),
+ )
+ # Cached, so the decline does not fire and sizing is actually reached.
+ _stub_hosted_prequant(monkeypatch, cached = True)
+
+ backend._dense_quant_prefetch_needed(fam, {"loras": [("adapter", 0.0)]})
+ backend._dense_quant_prefetch_needed(fam, {"loras": [("adapter", 0.8)]})
+
+ assert forced == [False, True]
+
+
+def test_the_plan_reads_pydantic_lora_specs_as_the_load_reads_tuples(fake_runtime, monkeypatch):
+ # /images/load sends (id, weight) tuples but /images/download-plan passes LoraSpec models, and
+ # unpacking a pydantic model yields (field, value) pairs, so a plain (_lid, w) unpack binds w
+ # to ("weight", 0.0) and reads a disabled adapter as an active bake.
+ from core.inference import diffusion as dmod
+ from models.inference import LoraSpec
+
+ backend = DiffusionBackend()
+ _force_cuda_target(backend, monkeypatch)
+ fam = detect_family("unsloth/Z-Image-GGUF")
+ consulted: list = []
+ monkeypatch.setattr(
+ dmod,
+ "resolve_dense_quant_candidate",
+ lambda **kw: consulted.append(kw) or types.SimpleNamespace(prequant = True),
+ )
+ _stub_hosted_prequant(monkeypatch, cached = False)
+
+ assert (
+ backend._dense_quant_prefetch_needed(fam, {"loras": [LoraSpec(id = "adapter", weight = 0)]})
+ is False
+ )
+ assert consulted == [] # declined on the cache verdict, never sized as a bake
+
+ # A weighted spec is still a bake, so the normalisation did not disable the candidate path.
+ backend._dense_quant_prefetch_needed(fam, {"loras": [LoraSpec(id = "adapter", weight = 0.8)]})
+ assert consulted != []
+
+
+def test_the_plan_reads_zero_weight_loras_exactly_as_the_load_does(fake_runtime, monkeypatch):
+ # The plan and the load must agree on what a bake is: gating the prefetch on the raw list
+ # stages base transformer/ shards for a load that will run the GGUF. The return value alone
+ # does not show it, so this asserts the decline happened on the cache verdict, BEFORE sizing.
+ from core.inference import diffusion as dmod
+
+ backend = DiffusionBackend()
+ _force_cuda_target(backend, monkeypatch)
+ fam = detect_family("unsloth/Z-Image-GGUF")
+ consulted: list = []
+ monkeypatch.setattr(
+ dmod,
+ "resolve_dense_quant_candidate",
+ lambda **kw: consulted.append(kw) or types.SimpleNamespace(prequant = True),
+ )
+ _stub_hosted_prequant(monkeypatch, cached = False)
+
+ for loras in ([("adapter", 0.0)], [("a", 0.0), ("b", 0.0)]):
+ consulted.clear()
+ assert backend._dense_quant_prefetch_needed(fam, {"loras": loras}) is False
+ assert consulted == []
+
+ # A real bake still sizes the dense build, so the fix did not disable the candidate path.
+ consulted.clear()
+ backend._dense_quant_prefetch_needed(fam, {"loras": [("adapter", 0.8)]})
+ assert consulted != []
+
+
+def test_dense_quant_prefetch_declines_with_the_load(fake_runtime, monkeypatch):
+ # The plan must call it as the loader does: a declined prequant means the GGUF runs, so the
+ # prefetch must not widen to the base transformer/ shards.
+ from core.inference import diffusion as dmod
+
+ backend = DiffusionBackend()
+ _force_cuda_target(backend, monkeypatch)
+ fam = detect_family("unsloth/Z-Image-GGUF")
+ consulted: list = []
+ monkeypatch.setattr(
+ dmod,
+ "resolve_dense_quant_candidate",
+ lambda **kw: consulted.append(kw) or types.SimpleNamespace(prequant = True),
+ )
+
+ _stub_hosted_prequant(monkeypatch, cached = False)
+ assert backend._dense_quant_prefetch_needed(fam, {}) is False
+ # Declined on the cache verdict alone, BEFORE any candidate sizing.
+ assert consulted == []
+ # Cached, or an explicit request: the candidate decides as before.
+ assert backend._dense_quant_prefetch_needed(fam, {"transformer_quant": "fp8"}) is False
+ _stub_hosted_prequant(monkeypatch, cached = True)
+ assert backend._dense_quant_prefetch_needed(fam, {}) is False
+ assert len(consulted) == 2
+
+
def test_diffusion_status_response_carries_resolved():
# The backend records per-control auto-policy provenance on state.resolved, so the response model must declare the field or Pydantic drops it.
from models.inference import DiffusionStatusResponse
@@ -3851,6 +4167,529 @@ def test_plan_memory_dense_replan_does_not_double_count_prefetched_transformer(m
assert plan.offload_policy == OFFLOAD_NONE
+def _split_cache_roots(
+ tmp_path,
+ monkeypatch,
+ *,
+ register_root = False,
+):
+ """Studio's live cache root and a second one holding what a mid-session cache-folder change
+ left behind. Returns ``(live, other)``, both empty.
+
+ ``register_root`` makes the second dir huggingface_hub's import-time constant, i.e. the root
+ ``cache_dir = None`` resolves to and the one the loader's per-file reuse reads from. Without it
+ the constant is pointed at a third empty dir, so ``other`` is reachable only as an explicit
+ staged snapshot -- and either way the test never sees the developer's real cache."""
+ from huggingface_hub import constants as hf_constants
+
+ from core.inference import diffusion as dmod
+
+ live = tmp_path / "live-hub"
+ other = tmp_path / "other-hub"
+ unused = tmp_path / "import-time-hub"
+ for path in (live, other, unused):
+ path.mkdir(exist_ok = True)
+ monkeypatch.setattr(dmod, "hub_cache_dir", lambda: str(live))
+ monkeypatch.setattr(hf_constants, "HF_HUB_CACHE", str(other if register_root else unused))
+ return live, other
+
+
+def _hub_blob(root, repo_id, name, mib):
+ """A completed download's blob under ``root``. Named after the file's etag, so the same file
+ carries the same name in every root it was ever downloaded into. Sparse: costs no disk."""
+ blob = root / f"models--{repo_id.replace('/', '--')}" / "blobs" / name
+ blob.parent.mkdir(parents = True, exist_ok = True)
+ with open(blob, "wb") as fh:
+ fh.truncate(mib * 1024 * 1024)
+ return blob
+
+
+def _hub_snapshot_file(root, repo_id, rev, rel, blob_name):
+ """The pointer a finished download leaves at ``snapshots/<rev>/<rel>``: a symlink at the blob
+ named after the file's etag, exactly as hf_hub_download creates it once the blob is complete."""
+ repo = root / f"models--{repo_id.replace('/', '--')}"
+ pointer = repo / "snapshots" / rev / rel
+ pointer.parent.mkdir(parents = True, exist_ok = True)
+ pointer.symlink_to(repo / "blobs" / blob_name)
+ return pointer
+
+
+def _hub_ref(root, repo_id, rev):
+ """``refs/main`` -> the commit this root currently serves. hf_hub_download writes it as soon as
+ it resolves the revision, i.e. BEFORE the first byte of that revision lands."""
+ ref = root / f"models--{repo_id.replace('/', '--')}" / "refs" / "main"
+ ref.parent.mkdir(parents = True, exist_ok = True)
+ ref.write_text(rev)
+ return ref
+
+
+def _sparse_snapshot_file(root, repo_id, rev, rel, mib):
+ """One file of ``rev`` present in ``root``'s snapshot. Sparse, so the size costs no disk."""
+ path = root / f"models--{repo_id.replace('/', '--')}" / "snapshots" / rev / rel
+ path.parent.mkdir(parents = True, exist_ok = True)
+ with open(path, "wb") as fh:
+ fh.truncate(mib * 1024 * 1024)
+ return path
+
+
+def _safetensors_with_params(path, numel):
+ """A safetensors shard whose JSON header declares ``numel`` elements. Only the header is read
+ (_safetensors_param_count never touches tensor data), so no payload is written."""
+ import json
+
+ header = json.dumps({"w": {"dtype": "F32", "shape": [numel], "data_offsets": [0, 4]}}).encode()
+ path.parent.mkdir(parents = True, exist_ok = True)
+ with open(path, "wb") as fh:
+ fh.write(len(header).to_bytes(8, "little"))
+ fh.write(header)
+ return path
+
+
+def _other_root_base_snapshot(
+ tmp_path,
+ monkeypatch,
+ *,
+ register_root = False,
+):
+ """A base repo cached ONLY under the other cache root, with Studio's live root empty: what a
+ mid-session cache-folder change leaves behind, and what the per-file root reuse hands the
+ loader back as ``_base_local_dir``. Sparse files, so the sizes cost no disk."""
+ _live, other = _split_cache_roots(tmp_path, monkeypatch, register_root = register_root)
+ snapshot = other / "models--bfl--base" / "snapshots" / ("a" * 40)
+ for rel, mib in (
+ ("text_encoder/model.safetensors", 150),
+ ("vae/diffusion_pytorch_model.safetensors", 50),
+ # Excluded from the companion total: on a GGUF load the single file supplies the transformer.
+ ("transformer/diffusion_pytorch_model.safetensors", 4096),
+ ):
+ path = snapshot / rel
+ path.parent.mkdir(parents = True, exist_ok = True)
+ with open(path, "wb") as fh:
+ fh.truncate(mib * 1024 * 1024)
+ return snapshot
+
+
+def _small_card(monkeypatch):
+ """A 5 GiB-free card + a fixed runtime headroom, so the plan's arithmetic is exact:
+ budget = 5000 - max(2048, 5120*0.10) = 2952 MiB, resident margin 0.85 * 2952 = 2509 MiB."""
+ from core.inference import diffusion as dmod
+ from core.inference.diffusion_memory import DeviceMemory
+
+ monkeypatch.setattr(
+ dmod,
+ "settled_snapshot_device_memory",
+ lambda t: DeviceMemory("cuda", "cuda", "discrete_vram", 5000, 5120),
+ )
+ monkeypatch.setattr(dmod, "estimate_image_runtime_mib", lambda **kw: 100)
+ return types.SimpleNamespace(device = "cuda", backend = "cuda", supports_model_cpu_offload = True)
+
+
+def test_plan_memory_budgets_companions_from_the_other_root_snapshot(monkeypatch, tmp_path):
+ # _companion_cache_bytes resolves a hub id under hub_cache_dir() ONLY, so a base the prefetch
+ # served from huggingface_hub's import-time root budgets as zero while from_pretrained loads it
+ # off that snapshot: an auto plan stays resident and OOMs on companions it never counted.
+ from core.inference.diffusion_memory import OFFLOAD_GROUP, OFFLOAD_NONE
+
+ snapshot = _other_root_base_snapshot(tmp_path, monkeypatch)
+ target = _small_card(monkeypatch)
+ backend = DiffusionBackend()
+ fam = types.SimpleNamespace(name = "flux.1")
+
+ def _plan(**kw):
+ return backend._plan_memory(
+ target,
+ None,
+ "bfl/base",
+ fam,
+ None,
+ False,
+ kind = "gguf",
+ transformer_resident_override_mib = 300,
+ **kw,
+ )
+
+ # The live root holds none of it, so the hub-id scan is blind to 200 MiB of real companions.
+ assert DiffusionBackend._companion_cache_bytes("bfl/base") == 0
+ blind = _plan()
+ assert blind.estimates["companion_dense_mib"] is None
+ # 300 + 0 + 100 + 2048 = 2448 <= 2509: resident, and the 200 MiB of companions arrive unbudgeted.
+ assert blind.offload_policy == OFFLOAD_NONE
+
+ plan = _plan(base_local_dir = str(snapshot))
+ # transformer/ stays excluded; only the VAE + text encoder count.
+ assert plan.estimates["companion_dense_mib"] == 200
+ # 300 + 200 + 100 + 2048 = 2648 > 2509, and the 2348 MiB group floor fits: stream the transformer.
+ assert plan.offload_policy == OFFLOAD_GROUP
+
+
+def test_plan_memory_sizes_a_pipeline_load_from_the_other_root_snapshot(monkeypatch, tmp_path):
+ # Same hole on the full-pipeline branch, where the whole repo IS the base: _cache_bytes walks
+ # the live root's blobs, so a repo served from the other root sizes as unknown -> "staying
+ # resident" for a 4 GiB pipeline that does not fit.
+ from core.inference.diffusion_memory import OFFLOAD_MODEL, OFFLOAD_NONE
+
+ snapshot = _other_root_base_snapshot(tmp_path, monkeypatch)
+ target = _small_card(monkeypatch)
+ backend = DiffusionBackend()
+ # base_repo deliberately unequal to repo_id: the narrow-base size table is a different path.
+ fam = types.SimpleNamespace(name = "flux.1", base_repo = "unrelated/repo")
+
+ def _plan(**kw):
+ return backend._plan_memory(
+ target, None, "bfl/base", fam, None, False, kind = "pipeline", repo_id = "bfl/base", **kw
+ )
+
+ blind = _plan()
+ assert blind.estimates["model_dense_mib"] is None
+ assert blind.offload_policy == OFFLOAD_NONE
+
+ plan = _plan(base_local_dir = str(snapshot))
+ # A pipeline load keeps transformer/: 4096 + 150 + 50 = 4296 MiB, well past the 2509 MiB margin.
+ assert plan.estimates["model_dense_mib"] == 4296
+ assert plan.offload_policy == OFFLOAD_MODEL
+
+
+def test_plan_memory_keeps_companions_a_partial_staged_snapshot_omits(monkeypatch, tmp_path):
+ # Same floor rule for the companion total. The snapshot the preflight carries can hold the
+ # manifest alone, so preferring it over the hub-id scan budgets 0 for the VAE + text encoders
+ # the cache root does hold, and the auto plan stays resident and OOMs on them.
+ from core.inference.diffusion_memory import OFFLOAD_GROUP
+
+ snapshot = _other_root_base_snapshot(tmp_path, monkeypatch, register_root = True)
+ target = _small_card(monkeypatch)
+ backend = DiffusionBackend()
+ manifest_only = snapshot.parent / ("c" * 40)
+ manifest_only.mkdir(parents = True)
+ (manifest_only / "model_index.json").write_bytes(b"{}")
+
+ plan = backend._plan_memory(
+ target,
+ None,
+ "bfl/base",
+ types.SimpleNamespace(name = "flux.1"),
+ None,
+ False,
+ kind = "gguf",
+ transformer_resident_override_mib = 300,
+ base_local_dir = str(manifest_only),
+ )
+ # The registered root still holds 150 + 50 MiB of companions, so 300 + 200 + 100 + 2048 = 2648
+ # clears the 2509 MiB resident margin and the 2348 MiB group floor fits.
+ assert plan.estimates["companion_dense_mib"] == 200
+ assert plan.offload_policy == OFFLOAD_GROUP
+
+
+def test_load_progress_counts_a_checkpoint_the_other_cache_root_already_holds(
+ tmp_path, monkeypatch
+):
+ # After a cache-folder change the multi-GB checkpoint can be satisfied entirely from
+ # huggingface_hub's import-time root. Counting only the live root leaves `downloaded` at 0
+ # against a nonzero estimate, so the UI reports a healthy multi-minute load as stalled near
+ # 0% for the whole of pipeline construction and never reaches "finalizing".
+ from core.inference.diffusion import _LoadingState
+
+ live, other = _split_cache_roots(tmp_path, monkeypatch, register_root = True)
+ _hub_blob(other, "org/gguf", "a" * 64, 400)
+ # The base is mirrored in both roots: one etag, one file, so it must not count twice.
+ _hub_blob(other, "org/base", "b" * 64, 100)
+ _hub_blob(live, "org/base", "b" * 64, 100)
+
+ assert DiffusionBackend._cache_bytes("org/gguf") == 400 * 1024 * 1024
+ assert DiffusionBackend._cache_bytes("org/base") == 100 * 1024 * 1024
+
+ backend = DiffusionBackend()
+ backend._loading = _LoadingState(
+ repo_id = "org/gguf", base_repo = "org/base", expected_bytes = 500 * 1024 * 1024
+ )
+ progress = backend.load_progress()
+ assert progress["phase"] == "finalizing"
+ assert progress["fraction"] == 1.0
+
+
+def test_load_progress_ignores_a_revision_the_moved_root_has_superseded(tmp_path, monkeypatch):
+ # blobs/ is append-only: a republished repo leaves the superseded revision's blobs there
+ # forever, under different etags from the ones now downloading, so nothing dedupes them.
+ # Summing the whole dir counts that stale full copy on top of the live partial one, and
+ # load_progress reports "finalizing" for the rest of a multi-GB pull -- the UI calls a download
+ # finished while it is barely half through.
+ from core.inference.diffusion import _LoadingState
+
+ _live, other = _split_cache_roots(tmp_path, monkeypatch, register_root = True)
+ old_rev, new_rev = "a" * 40, "b" * 40
+ # Revision A, complete: what this root downloaded before the cache folder changed.
+ _hub_blob(other, "org/pipe", "a1", 2000)
+ _hub_blob(other, "org/pipe", "a2", 2000)
+ _hub_snapshot_file(other, "org/pipe", old_rev, "transformer/shard-1.safetensors", "a1")
+ _hub_snapshot_file(other, "org/pipe", old_rev, "vae/diffusion_pytorch_model.safetensors", "a2")
+ # The repo was republished and the per-file root reuse serves this load through the same root:
+ # refs/main moves to B first, then B's shards land one at a time.
+ _hub_ref(other, "org/pipe", new_rev)
+ _hub_blob(other, "org/pipe", "b1", 2000)
+ _hub_snapshot_file(other, "org/pipe", new_rev, "transformer/shard-1.safetensors", "b1")
+ _hub_blob(other, "org/pipe", "b2.incomplete", 200) # 200 of the second 2000 MiB shard
+
+ # 2000 done + 200 in flight out of a 4000 MiB revision. A's bytes are not this load's; the
+ # .incomplete one is, so the bar still moves inside a shard instead of freezing per shard.
+ assert DiffusionBackend._cache_bytes("org/pipe") == 2200 * 1024 * 1024
+
+ backend = DiffusionBackend()
+ backend._loading = _LoadingState(
+ repo_id = "org/pipe", base_repo = None, expected_bytes = 4000 * 1024 * 1024
+ )
+ progress = backend.load_progress()
+ assert progress["phase"] == "downloading"
+ assert progress["fraction"] == 0.55
+
+
+def test_load_progress_counts_one_logical_file_across_roots_at_two_revisions(tmp_path, monkeypatch):
+ # Each root serves its OWN refs/main, so after a republish the two roots can be scoped to
+ # different revisions. The same logical shard then has a different blob etag in each, so an
+ # etag key never collides and both copies are summed -- roughly doubling the count and
+ # reporting finalizing at about half the real progress. Only one of them is ever loaded.
+ from core.inference.diffusion import _LoadingState
+
+ live, other = _split_cache_roots(tmp_path, monkeypatch, register_root = True)
+ old_rev, new_rev = "a" * 40, "b" * 40
+ # The stale root still names revision A; the live root has moved to B.
+ _hub_blob(other, "org/pipe", "a1", 1000)
+ _hub_snapshot_file(other, "org/pipe", old_rev, "transformer/shard-1.safetensors", "a1")
+ _hub_ref(other, "org/pipe", old_rev)
+ _hub_blob(live, "org/pipe", "b1", 1000)
+ _hub_snapshot_file(live, "org/pipe", new_rev, "transformer/shard-1.safetensors", "b1")
+ _hub_ref(live, "org/pipe", new_rev)
+
+ # One shard at one logical path, so one count -- not 2000.
+ assert DiffusionBackend._cache_bytes("org/pipe") == 1000 * 1024 * 1024
+
+ backend = DiffusionBackend()
+ backend._loading = _LoadingState(
+ repo_id = "org/pipe", base_repo = None, expected_bytes = 2000 * 1024 * 1024
+ )
+ progress = backend.load_progress()
+ assert progress["phase"] == "downloading" # not "finalizing" off a phantom second copy
+ assert progress["fraction"] == 0.5
+
+
+def test_companion_bytes_union_a_base_the_prefetch_split_across_roots(tmp_path, monkeypatch):
+ # reuse_other_cache_root resolves EACH file through whichever root holds it, so a moved cache
+ # can leave the text encoder in the old snapshot while the VAE downloads into the live one.
+ # Those two snapshots are disjoint PARTS of one revision, not copies of it, so sizing off the
+ # larger one budgets a fraction of the companions the load goes on to make resident.
+ from core.inference.diffusion_memory import OFFLOAD_GROUP, OFFLOAD_NONE
+
+ live, other = _split_cache_roots(tmp_path, monkeypatch, register_root = True)
+ rev = "a" * 40
+ _sparse_snapshot_file(other, "bfl/base", rev, "text_encoder/model.safetensors", 200)
+ _sparse_snapshot_file(live, "bfl/base", rev, "vae/diffusion_pytorch_model.safetensors", 150)
+
+ assert DiffusionBackend._companion_cache_bytes("bfl/base") == 350 * 1024 * 1024
+
+ target = _small_card(monkeypatch)
+ plan = DiffusionBackend()._plan_memory(
+ target,
+ None,
+ "bfl/base",
+ types.SimpleNamespace(name = "flux.1"),
+ None,
+ False,
+ kind = "gguf",
+ transformer_resident_override_mib = 100,
+ )
+ assert plan.estimates["companion_dense_mib"] == 350
+ # 100 + 350 + 100 + 2048 = 2598 > the 2509 MiB resident margin, so stream the transformer.
+ # Off the larger half alone (200) it reads 2448 and stays resident, and the 150 MiB the other
+ # root holds arrives unbudgeted on a card with nothing left for it.
+ assert plan.offload_policy != OFFLOAD_NONE
+ assert plan.offload_policy == OFFLOAD_GROUP
+
+
+def test_companion_bytes_skip_a_superseded_revision_in_the_same_root(tmp_path, monkeypatch):
+ # The merge is per FILE, so a repo that repacked its shards between revisions would have both
+ # namings counted and budget roughly twice the companions it loads -- enough to force offload
+ # on a base that fits resident. Only the revision refs/main names is the one this load reads.
+ live, _other = _split_cache_roots(tmp_path, monkeypatch, register_root = True)
+ old_rev, new_rev = "a" * 40, "b" * 40
+ for shard in ("model-00001-of-00002.safetensors", "model-00002-of-00002.safetensors"):
+ _sparse_snapshot_file(live, "bfl/base", old_rev, f"text_encoder/{shard}", 100)
+ _sparse_snapshot_file(live, "bfl/base", new_rev, "text_encoder/model.safetensors", 200)
+ _hub_ref(live, "bfl/base", new_rev)
+
+ # 200, not the 400 that merging both revisions' disjoint file names would report.
+ assert DiffusionBackend._companion_cache_bytes("bfl/base") == 200 * 1024 * 1024
+
+
+def test_plan_memory_sizes_a_pipeline_split_across_both_cache_roots(monkeypatch, tmp_path):
+ # A prefetch that landed part of the repo in each root hands back NO snapshot (a snapshot dir
+ # the rest of the files are not in would fail the load), so the plan falls back to the cache
+ # scan. Scoped to the live root that reads a fraction of the repo, and the pinned
+ # from_pretrained then loads shards the plan never budgeted.
+ from core.inference.diffusion_memory import OFFLOAD_MODEL
+
+ live, other = _split_cache_roots(tmp_path, monkeypatch, register_root = True)
+ target = _small_card(monkeypatch)
+ backend = DiffusionBackend()
+ # base_repo deliberately unequal to repo_id: the narrow-base size table is a different path.
+ fam = types.SimpleNamespace(name = "flux.1", base_repo = "unrelated/repo")
+ # Downloaded into the live root, and again mirrored in both: same etag, so one file.
+ _hub_blob(live, "bfl/base", "a" * 64, 300)
+ _hub_blob(other, "bfl/base", "a" * 64, 300)
+ _hub_blob(other, "bfl/base", "b" * 64, 4000)
+
+ def _plan(**kw):
+ return backend._plan_memory(
+ target, None, "bfl/base", fam, None, False, kind = "pipeline", repo_id = "bfl/base", **kw
+ )
+
+ plan = _plan()
+ # 300 + 4000, each counted once: a per-root sum would read 4600, the live root alone 300 (and
+ # 300 + 100 + 2048 fits the 2509 MiB margin, so the 4.2 GiB repo would have stayed resident).
+ assert plan.estimates["model_dense_mib"] == 4300
+ assert plan.offload_policy == OFFLOAD_MODEL
+
+ # The gated preflight excuses a base off ONE probe file, so the snapshot it carries can hold
+ # the manifest and nothing else. Preferring a staged dir outright would size this 4.2 GiB
+ # pipeline at 0; it is a floor here too, and the cache scan still wins.
+ manifest_only = other / "models--bfl--base" / "snapshots" / ("c" * 40)
+ manifest_only.mkdir(parents = True)
+ (manifest_only / "model_index.json").write_bytes(b"{}")
+ assert _plan(base_local_dir = str(manifest_only)).estimates["model_dense_mib"] == 4300
+
+
+def test_dense_transformer_bytes_read_the_other_root_and_treat_the_snapshot_as_a_floor(
+ tmp_path, monkeypatch
+):
+ # The dense-quant preflight sizes the bf16 transformer to decide whether to re-check the fit.
+ # A base a moved cache holds only under the import-time root reads 0 on the live root, and a 0
+ # skips the check entirely, so the dense build lands under a plan sized for the GGUF.
+ _live, other = _split_cache_roots(tmp_path, monkeypatch, register_root = True)
+ snapshot = other / "models--bfl--base" / "snapshots" / ("a" * 40)
+ _safetensors_with_params(
+ snapshot / "transformer" / "diffusion_pytorch_model.safetensors", 1_000_000
+ )
+
+ # bf16 on load: 2 bytes/param, reached through the hub id or the staged snapshot alike.
+ assert DiffusionBackend._dense_transformer_resident_bytes("bfl/base") == 2_000_000
+ assert (
+ DiffusionBackend._dense_transformer_resident_bytes("bfl/base", str(snapshot)) == 2_000_000
+ )
+ # The staged snapshot is a floor, never a replacement: the prefetch only stages transformer/
+ # when the dense path is in play, and a preflight-excused snapshot can carry companions alone.
+ # Letting one of those erase the shards a root does hold would skip the fit check again.
+ bare = tmp_path / "companions-only-snapshot"
+ bare.mkdir()
+ assert DiffusionBackend._dense_transformer_resident_bytes("bfl/base", str(bare)) == 2_000_000
+ # A staged dir under NEITHER current root: the cache folder can change again while a multi-GB
+ # prefetch runs, and the snapshot it already resolved is still where the load reads the shards.
+ stale = tmp_path / "stale-root" / "models--bfl--base" / "snapshots" / ("b" * 40)
+ _safetensors_with_params(
+ stale / "transformer" / "diffusion_pytorch_model.safetensors", 3_000_000
+ )
+ assert DiffusionBackend._dense_transformer_resident_bytes("bfl/base", str(stale)) == 6_000_000
+
+
[email protected]("staged", [False, True])
+def test_dense_fit_check_runs_for_a_base_the_live_cache_root_does_not_hold(
+ fake_runtime, tmp_path, monkeypatch, staged
+):
+ # End of the same hole, at the load: with no usable prequant the loader materialises the dense
+ # bf16 transformer, so the fit re-check has to run. It only runs when the size lookup finds the
+ # shards, and for a moved cache they are either under the import-time root (staged=False) or
+ # only in the snapshot the prefetch already resolved, which a second move strands outside both
+ # roots (staged=True). The live root reads 0 for either, and a 0 skips the check.
+ from core.inference import diffusion as dmod
+
+ _live, other = _split_cache_roots(tmp_path, monkeypatch, register_root = True)
+ root = tmp_path / "stale-root" if staged else other
+ shards = root / "models--Tongyi-MAI--Z-Image-Turbo" / "snapshots" / ("a" * 40)
+ _safetensors_with_params(
+ shards / "transformer" / "diffusion_pytorch_model.safetensors",
+ 6 * 1024**3, # 6G params -> 12 GiB resident at bf16
+ )
+ backend = DiffusionBackend()
+ _force_cuda_target(backend, monkeypatch)
+ monkeypatch.setattr(dmod, "dense_transformer_supported", lambda target: True)
+ monkeypatch.setattr(
+ dmod, "select_transformer_quant_scheme", lambda target, mode, family = None: "fp8"
+ )
+ monkeypatch.setattr(dmod, "usable_prequant_source", lambda fam, scheme, **kw: None)
+ dense_refit_ran = []
+ orig_plan = DiffusionBackend._plan_memory
+
+ def spy_plan(
+ self,
+ *a,
+ transformer_resident_override_mib = None,
+ **k,
+ ):
+ # Scoped to this backend: begin_load runs on a daemon thread, so an earlier test's load can
+ # still be in flight here and _plan_memory is patched on the CLASS.
+ if transformer_resident_override_mib is not None and self is backend:
+ dense_refit_ran.append(transformer_resident_override_mib)
+ return orig_plan(self, *a, **k)
+
+ monkeypatch.setattr(DiffusionBackend, "_plan_memory", spy_plan)
+ monkeypatch.setattr(
+ DiffusionBackend, "_load_dense_quant_pipeline", lambda self, *a, **k: (None, None)
+ )
+ (tmp_path / "m.gguf").write_bytes(b"x")
+ backend.load_pipeline(
+ str(tmp_path),
+ gguf_filename = "m.gguf",
+ family_override = "z-image",
+ transformer_quant = "fp8",
+ _base_local_dir = str(shards) if staged else None,
+ )
+ assert dense_refit_ran == [12288]
+ assert backend.status()["loaded"] is True
+
+
+def test_the_dense_builder_reads_transformer_from_the_hub_id_not_the_staged_snapshot(
+ fake_runtime, tmp_path, monkeypatch
+):
+ # Sizing reads the staged snapshot; the LOAD deliberately does not. diffusers treats a local
+ # directory as terminal -- _get_model_file raises "Error no file named ..." instead of falling
+ # back to the hub (utils/hub_utils.py), and a sharded load raises FileNotFoundError per missing
+ # shard -- so a snapshot holding transformer/config.json, or 2 of 3 shards (what a cancelled
+ # prefetch leaves), would turn a working load into a hard failure. The hub id costs a
+ # re-download instead, or 401s into the GGUF fallback, which is what main does today.
+ import contextlib
+
+ from core.inference import diffusion as dmod
+
+ monkeypatch.setattr(
+ dmod, "select_transformer_quant_scheme", lambda target, mode, family = None: "fp8"
+ )
+ monkeypatch.setattr(dmod, "resolve_prequant_source", lambda *a, **k: None)
+ snapshot = tmp_path / "other-hub" / "models--Tongyi-MAI--Z-Image-Turbo" / "snapshots" / "abc"
+ # transformer/ present but shardless: the shape an is_dir() guard would wave through.
+ (snapshot / "transformer").mkdir(parents = True)
+ seen: list = []
+
+ class _Transformer:
+ @classmethod
+ def from_pretrained(cls, source, **kw):
+ seen.append(source)
+ raise RuntimeError("the source is the subject; the build cannot complete here")
+
+ backend = DiffusionBackend()
+ target = _force_cuda_target(backend, monkeypatch)
+ with contextlib.suppress(Exception):
+ backend._load_dense_quant_pipeline(
+ _Transformer,
+ object(),
+ "Tongyi-MAI/Z-Image-Turbo",
+ "cuda",
+ None,
+ None,
+ target,
+ "fp8",
+ None,
+ fam = detect_family("unsloth/Z-Image-GGUF"),
+ base_local_dir = str(snapshot),
+ )
+ assert seen == ["Tongyi-MAI/Z-Image-Turbo"]
+
+
def test_reset_step_cache_helper_is_best_effort():
# Prefer the real CacheMixin hook (_reset_stateful_cache): reset_stateful_hooks lives only on the HookRegistry, so the old lookup was a silent no-op.
calls = []
@@ -4438,6 +5277,56 @@ def test_download_plan_keeps_the_dense_encoder_when_the_precast_repo_is_unavaila
assert not any(e["repo_id"] == "unsloth/does-not-exist" for e in plan["entries"])
+_ZIMAGE_BASE_SIBLINGS = [
+ _FakeSibling("model_index.json", 1000),
+ _FakeSibling("transformer/diffusion_pytorch_model-00001-of-00002.safetensors", 12 * GB),
+ _FakeSibling("text_encoder/model.safetensors", 8 * GB),
+ _FakeSibling("vae/diffusion_pytorch_model.safetensors", 300),
+]
+
+
+def test_download_plan_stages_no_second_denoiser_for_an_uncached_prequant(monkeypatch):
+ # The plan drives the download manager, so it must agree with the load: a declined prequant
+ # stages neither its .pt nor the base transformer/ shards the dense build wanted.
+ _fake_hf_api(
+ monkeypatch,
+ {
+ "unsloth/Z-Image-GGUF": [_FakeSibling("Z-Image-Turbo-Q4_K_M.gguf", 4 * GB)],
+ "Tongyi-MAI/Z-Image-Turbo": _ZIMAGE_BASE_SIBLINGS,
+ },
+ )
+ monkeypatch.setattr(
+ "core.inference.diffusion._resolve_base_repo", lambda *a, **k: "Tongyi-MAI/Z-Image-Turbo"
+ )
+ _stub_hosted_prequant(monkeypatch, cached = False)
+
+ plan = DiffusionBackend().download_plan(
+ "unsloth/Z-Image-GGUF", gguf_filename = "Z-Image-Turbo-Q4_K_M.gguf"
+ )
+
+ assert [e["repo_id"] for e in plan["entries"]] == [
+ "unsloth/Z-Image-GGUF",
+ "Tongyi-MAI/Z-Image-Turbo",
+ ]
+ checkpoint, base = plan["entries"]
+ assert checkpoint["files"] == ["Z-Image-Turbo-Q4_K_M.gguf"]
+ # No hosted checkpoint and no dense shards: the companions are all the base repo owes.
+ assert not any(f.endswith(".pt") for e in plan["entries"] for f in e["files"])
+ assert not any(f.startswith("transformer/") for f in base["files"])
+ assert "text_encoder/model.safetensors" in base["files"]
+ assert plan["total_bytes"] == 4 * GB + base["bytes"] < 17 * GB
+
+
+def test_download_plan_for_a_pipeline_kind_ignores_the_prequant_cache(monkeypatch):
+ # Only a GGUF pick is restricted: a full pipeline's transformer IS the repo's.
+ _fake_hf_api(monkeypatch, {"unsloth/some-pipeline": _ZIMAGE_BASE_SIBLINGS})
+ _stub_hosted_prequant(monkeypatch, cached = False)
+
+ plan = DiffusionBackend().download_plan("unsloth/some-pipeline", model_kind = "pipeline")
+
+ assert any(f.startswith("transformer/") for f in plan["entries"][0]["files"])
+
+
# ── teardown fence ────────────────────────────────────────────────────────────
diff --git a/studio/backend/tests/test_diffusion_gated_base.py b/studio/backend/tests/test_diffusion_gated_base.py
new file mode 100644
index 00000000000..6cdaac0c53a
--- /dev/null
+++ b/studio/backend/tests/test_diffusion_gated_base.py
@@ -0,0 +1,1150 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Hermetic tests for the gated companion-base preflight.
+
+Hugging Face gates the BYTE endpoint only, so ``model_info`` answers anonymously and the download
+plan is built from a full file list before anything 401s. Stubbing ``HfApi`` /
+``get_hf_file_metadata`` pins both halves: the plan fails up front naming the repo and its licence
+page, and every non-access failure falls through so an offline host can still load.
+"""
+
+from __future__ import annotations
+
+import os
+import types
+
+import pytest
+
+from core.inference.diffusion import (
+ DiffusionBackend,
+ _assert_base_repo_accessible,
+ _LoadingState,
+)
+
+GATED_REPO = "black-forest-labs/FLUX.1-dev"
+
+
+class _FakeInfo:
+ def __init__(
+ self,
+ gated,
+ siblings = (),
+ ):
+ # The Hub reports "auto" / "manual" (a truthy STRING) or False, never True.
+ self.gated = gated
+ self.siblings = list(siblings)
+
+
+class _FakeSibling:
+ def __init__(self, rfilename, size):
+ self.rfilename = rfilename
+ self.size = size
+
+
+def _stub_hub(
+ monkeypatch,
+ *,
+ info = None,
+ model_info_error = None,
+ download_error = None,
+):
+ """Point model_info / the byte-URL HEAD at canned outcomes; returns the probe log."""
+ probed: list = []
+
+ class _Api:
+ def model_info(
+ self,
+ repo_id,
+ files_metadata = False,
+ token = None,
+ ):
+ if model_info_error is not None:
+ raise model_info_error
+ return info
+
+ def _metadata(
+ url,
+ token = None,
+ **kwargs,
+ ):
+ probed.append(url)
+ if download_error is not None:
+ raise download_error
+ return types.SimpleNamespace(etag = "abc", size = 1000)
+
+ monkeypatch.setattr("huggingface_hub.HfApi", lambda *a, **k: _Api())
+ monkeypatch.setattr("huggingface_hub.get_hf_file_metadata", _metadata)
+ # No ambient cache: whether THIS box happens to hold the repo must not decide the test.
+ monkeypatch.setattr("huggingface_hub.try_to_load_from_cache", lambda *a, **k: None)
+ # The probe must never route through the download API: a cached manifest answers that from disk.
+ monkeypatch.setattr(
+ "huggingface_hub.hf_hub_download",
+ lambda *a, **k: pytest.fail("the access probe must not be satisfiable from the cache"),
+ )
+ return probed
+
+
+def _gated_error():
+ from huggingface_hub.errors import GatedRepoError
+ return _hub_http_error(
+ GatedRepoError, "401 Client Error. Cannot access gated repo for url ...", 401
+ )
+
+
+def test_a_gated_base_fails_at_plan_time_naming_the_repo_and_its_licence(monkeypatch):
+ # The whole point: metadata says 18 files / 15.4 GiB, the first byte says 401.
+ probed = _stub_hub(monkeypatch, info = _FakeInfo("auto"), download_error = _gated_error())
+
+ with pytest.raises(ValueError) as excinfo:
+ _assert_base_repo_accessible(GATED_REPO, None)
+
+ detail = str(excinfo.value)
+ assert GATED_REPO in detail
+ assert f"https://huggingface.co/{GATED_REPO}" in detail
+ assert "licence" in detail.lower() and "token" in detail.lower()
+ # Probed the manifest the load fetches anyway, not a multi-GB shard.
+ assert probed == [f"https://huggingface.co/{GATED_REPO}/resolve/main/model_index.json"]
+
+
+def test_an_open_base_is_never_probed(monkeypatch):
+ # gated is False for almost every repo, so the preflight costs one metadata call.
+ probed = _stub_hub(monkeypatch, info = _FakeInfo(False), download_error = _gated_error())
+
+ _assert_base_repo_accessible("Tongyi-MAI/Z-Image-Turbo", None)
+
+ assert probed == []
+
+
+def test_a_network_error_fails_open(monkeypatch):
+ # Offline / transient must never refuse a load: the download surfaces any real error.
+ _stub_hub(monkeypatch, model_info_error = OSError("Connection reset by peer"))
+ _assert_base_repo_accessible(GATED_REPO, None)
+
+ # Same on the byte probe: only an access verdict counts.
+ from huggingface_hub.errors import EntryNotFoundError
+
+ _stub_hub(monkeypatch, info = _FakeInfo("auto"), download_error = EntryNotFoundError("404"))
+ _assert_base_repo_accessible(GATED_REPO, None)
+
+ _stub_hub(monkeypatch, info = _FakeInfo("manual"), download_error = TimeoutError("read timed out"))
+ _assert_base_repo_accessible(GATED_REPO, None)
+
+
+def test_unreadable_metadata_is_named_too(monkeypatch):
+ # A private / renamed / deleted base 401s on model_info, which the size estimate swallows into
+ # a zero-byte plan, so the load fails with no explanation.
+ from huggingface_hub.errors import RepositoryNotFoundError
+
+ _stub_hub(
+ monkeypatch,
+ model_info_error = _hub_http_error(RepositoryNotFoundError, "401 Client Error.", 401),
+ )
+
+ with pytest.raises(ValueError) as excinfo:
+ _assert_base_repo_accessible("unsloth/not-published-yet", None)
+
+ assert "unsloth/not-published-yet" in str(excinfo.value)
+ assert "https://huggingface.co/unsloth/not-published-yet" in str(excinfo.value)
+
+ # A gated repo that also withholds its metadata keeps the licence wording.
+ _stub_hub(monkeypatch, model_info_error = _gated_error())
+ with pytest.raises(ValueError) as gated:
+ _assert_base_repo_accessible(GATED_REPO, None)
+ assert "licence" in str(gated.value).lower()
+
+
+def test_an_already_downloaded_base_is_never_refused(monkeypatch, tmp_path):
+ """A base whose bytes are on disk loads today with no token: hf_hub_download catches the gated
+ 401 HEAD and returns the cached pointer. Probing live access there could only refuse a load
+ that already works. The never-downloaded pick this preflight exists for still probes."""
+ root = tmp_path / "hub"
+ folder = root / f"models--{GATED_REPO.replace('/', '--')}"
+ commit = "c" * 40
+ (folder / "refs").mkdir(parents = True)
+ (folder / "refs" / "main").write_text(commit)
+ (folder / "snapshots" / commit).mkdir(parents = True)
+ (folder / "snapshots" / commit / "model_index.json").write_text("{}")
+
+ # Cached under the LIVE root, and separately under huggingface_hub's import-time constant: the
+ # prefetch downloads under the latter, so checking only one root would still refuse the load.
+ for live, imported in ((str(root), tmp_path / "other"), (str(tmp_path / "other"), root)):
+ monkeypatch.setattr("core.inference.diffusion.hub_cache_dir", lambda live = live: live)
+ monkeypatch.setenv("HF_HUB_CACHE", str(imported))
+ probed = _stub_hub(monkeypatch, info = _FakeInfo("auto"), download_error = _gated_error())
+ monkeypatch.setattr(
+ "huggingface_hub.try_to_load_from_cache",
+ lambda repo_id, filename, cache_dir = None, **k: (
+ str(
+ root / f"models--{repo_id.replace('/', '--')}" / "snapshots" / commit / filename
+ )
+ if cache_dir in (str(root), None) and str(root) in (live, str(imported))
+ else None
+ ),
+ )
+ _assert_base_repo_accessible(GATED_REPO, "stale-token")
+ assert probed == [] # served from disk, so not one Hub call was made
+
+ # Nothing cached: the reported case still fails up front, naming the repo and its licence.
+ monkeypatch.setattr("core.inference.diffusion.hub_cache_dir", lambda: str(tmp_path / "empty"))
+ _stub_hub(monkeypatch, info = _FakeInfo("auto"), download_error = _gated_error())
+ with pytest.raises(ValueError, match = "gated"):
+ _assert_base_repo_accessible(GATED_REPO, "stale-token")
+
+
+def test_local_and_non_repo_bases_are_skipped(monkeypatch, tmp_path):
+ # Only a remote 'org/name' can be gated; a local pipeline dir is already on disk.
+ def _explode(*a, **k):
+ pytest.fail("a local / non-repo base must never be probed")
+
+ monkeypatch.setattr("huggingface_hub.HfApi", _explode)
+ monkeypatch.setattr("huggingface_hub.hf_hub_download", _explode)
+
+ local = tmp_path / "my-base"
+ local.mkdir()
+ _assert_base_repo_accessible(str(local), None)
+ _assert_base_repo_accessible("", None)
+ _assert_base_repo_accessible("bare-name", None)
+
+
+def test_a_base_whose_home_cannot_be_resolved_fails_open(monkeypatch):
+ # '~other/models' and '~/models' under an account with no home both carry exactly one slash,
+ # so they reach the local-path probe, where pathlib raises RuntimeError -- NOT an OSError.
+ # This probe fails open, so that must fall through rather than 500 a load that has not started.
+ probed = _stub_hub(monkeypatch, info = _FakeInfo(False))
+
+ class _NoHomePath:
+ def __init__(self, *a, **k):
+ pass
+
+ def expanduser(self):
+ raise RuntimeError("Could not determine home directory.")
+
+ monkeypatch.setattr("core.inference.diffusion.Path", _NoHomePath)
+
+ _assert_base_repo_accessible("~ghost/my-base", None)
+ # Fell through to the remote probe instead of raising: an open repo costs one metadata call.
+ assert probed == []
+
+
+def test_an_unknown_user_home_base_fails_open_for_real(monkeypatch):
+ # The same failure unstubbed: no such user, so expanduser() raises. POSIX only -- Windows
+ # rewrites '~ghost' against USERPROFILE's parent and never reaches the RuntimeError branch.
+ if os.name == "nt":
+ pytest.skip("POSIX-only: Windows expanduser() never fails for an unknown user")
+ _stub_hub(monkeypatch, info = _FakeInfo(False))
+
+ _assert_base_repo_accessible("~unsloth-no-such-user-4b1f/my-base", None)
+
+
+def test_download_plan_refuses_a_gated_base_before_listing_files(monkeypatch):
+ # End to end: the ValueError the route maps to a 400 replaces a confident 18-file plan.
+ # Mirror swap off, so what this pins is the preflight itself. #7952 sends a gated base to
+ # its ungated unsloth mirror, which the preflight now probes in its place; that rescue is
+ # exercised on its own below rather than folded into every refusal case.
+ monkeypatch.setenv("UNSLOTH_DIFFUSION_NO_MIRROR", "1")
+ _stub_hub(
+ monkeypatch,
+ info = _FakeInfo("auto", [_FakeSibling("model_index.json", 1000)]),
+ download_error = _gated_error(),
+ )
+ monkeypatch.setattr("core.inference.diffusion._resolve_base_repo", lambda *a, **k: GATED_REPO)
+
+ with pytest.raises(ValueError) as excinfo:
+ DiffusionBackend().download_plan(
+ "unsloth/FLUX.1-dev-GGUF", gguf_filename = "flux1-dev-Q4_K_M.gguf"
+ )
+
+ assert GATED_REPO in str(excinfo.value)
+
+
+def test_the_pre_eviction_preflight_refuses_the_same_gated_base(monkeypatch):
+ # The route calls this BEFORE acquire_for. _run_load makes the same check, but only after the
+ # GPU was taken from chat, and the images page falls back to /images/load on any plan failure.
+ # Mirror swap off, so what this pins is the preflight itself. #7952 sends a gated base to
+ # its ungated unsloth mirror, which the preflight now probes in its place; that rescue is
+ # exercised on its own below rather than folded into every refusal case.
+ monkeypatch.setenv("UNSLOTH_DIFFUSION_NO_MIRROR", "1")
+ _stub_hub(
+ monkeypatch,
+ info = _FakeInfo("auto", [_FakeSibling("model_index.json", 1000)]),
+ download_error = _gated_error(),
+ )
+ monkeypatch.setattr("core.inference.diffusion._resolve_base_repo", lambda *a, **k: GATED_REPO)
+
+ with pytest.raises(ValueError) as excinfo:
+ DiffusionBackend().preflight_base_access(
+ "unsloth/FLUX.1-dev-GGUF",
+ types.SimpleNamespace(name = "flux.1", single_file_is_pipeline = False),
+ gguf_filename = "flux1-dev-Q4_K_M.gguf",
+ model_kind = "gguf",
+ )
+
+ assert GATED_REPO in str(excinfo.value)
+
+
+def test_the_pre_eviction_preflight_clears_an_open_base(monkeypatch):
+ # It must refuse a load, never block one: an open base costs one metadata call and no byte probe.
+ probed = _stub_hub(monkeypatch, info = _FakeInfo(False))
+ monkeypatch.setattr("core.inference.diffusion._resolve_base_repo", lambda *a, **k: "unsloth/x")
+
+ DiffusionBackend().preflight_base_access(
+ "unsloth/Z-Image-Turbo-GGUF",
+ types.SimpleNamespace(name = "z-image", single_file_is_pipeline = False),
+ gguf_filename = "z.gguf",
+ model_kind = "gguf",
+ )
+
+ assert probed == []
+
+
+def test_the_native_pre_eviction_preflight_refuses_a_gated_companion(monkeypatch):
+ # A forced-native load on a GPU box takes the arbiter too, so sd.cpp needs the same entry point.
+ # Mirror swap off, so what this pins is the preflight itself: #7952 sends a gated companion
+ # to its ungated unsloth mirror, which the preflight now probes in its place. That rescue
+ # is exercised on its own below rather than folded into every refusal case.
+ monkeypatch.setenv("UNSLOTH_DIFFUSION_NO_MIRROR", "1")
+ from core.inference.sd_cpp_backend import SdCppDiffusionBackend
+
+ _stub_hub(
+ monkeypatch,
+ info = _FakeInfo("auto", [_FakeSibling("ae.safetensors", 1000)]),
+ download_error = _gated_error(),
+ )
+ fam = types.SimpleNamespace(
+ name = "flux.1",
+ sd_cpp_vae = (GATED_REPO, "ae.safetensors"),
+ )
+ monkeypatch.setattr(
+ "core.inference.sd_cpp_backend.sd_cpp_text_encoders_for", lambda *a, **k: ()
+ )
+
+ with pytest.raises(ValueError) as excinfo:
+ SdCppDiffusionBackend().preflight_base_access(
+ "unsloth/FLUX.1-dev-GGUF", fam, gguf_filename = "flux1-dev-Q4_K_M.gguf"
+ )
+
+ assert GATED_REPO in str(excinfo.value)
+
+
+def test_run_load_stamps_the_gated_error_on_the_load(monkeypatch):
+ # The load path takes the same preflight, so the failure reaches the UI as a load error.
+ # Mirror swap off, so what this pins is the preflight itself. #7952 sends a gated base to
+ # its ungated unsloth mirror, which the preflight now probes in its place; that rescue is
+ # exercised on its own below rather than folded into every refusal case.
+ monkeypatch.setenv("UNSLOTH_DIFFUSION_NO_MIRROR", "1")
+ backend = DiffusionBackend()
+ monkeypatch.setattr(
+ backend, "validate_load_request", lambda *a, **k: types.SimpleNamespace(name = "flux.1")
+ )
+ monkeypatch.setattr(
+ "core.inference.diffusion.detect_family_for_pick",
+ lambda *a, **k: types.SimpleNamespace(name = "flux.1", single_file_is_pipeline = False),
+ )
+ monkeypatch.setattr("core.inference.diffusion._resolve_base_repo", lambda *a, **k: GATED_REPO)
+ _stub_hub(monkeypatch, info = _FakeInfo("auto"), download_error = _gated_error())
+
+ def _no_prefetch(*a, **k):
+ pytest.fail("the prefetch must not start once the base is known to be unreadable")
+
+ monkeypatch.setattr(DiffusionBackend, "_prefetch_files", _no_prefetch)
+ monkeypatch.setattr(
+ DiffusionBackend, "_estimate_download_bytes", staticmethod(lambda *a, **k: (0, []))
+ )
+ # What begin_load() stamps before handing off to the worker thread.
+ backend._loading = _LoadingState(
+ repo_id = "unsloth/FLUX.1-dev-GGUF", base_repo = "black-forest-labs/FLUX.1-schnell"
+ )
+
+ backend._run_load(
+ repo_id = "unsloth/FLUX.1-dev-GGUF",
+ gguf_filename = "flux1-dev-Q4_K_M.gguf",
+ hf_token = None,
+ _load_token = backend._load_token,
+ )
+
+ assert GATED_REPO in (backend.load_progress().get("error") or "")
+
+
+def _hub_http_error(cls, message, status):
+ """Build an HfHubHTTPError subclass portably.
+
+ huggingface_hub 1.x made ``response`` a REQUIRED keyword-only argument, and CI resolves 1.x
+ (transformers pins huggingface-hub>=1.5 over studio.txt's 0.36.2). Passing it works on both."""
+ import requests
+
+ response = requests.Response()
+ response.status_code = status
+ return cls(message, response = response)
+
+
+def _auth_error(status):
+ """The bare HfHubHTTPError hf_raise_for_status leaves for an unclassified 401/403.
+
+ Its RepoNotFound branch excludes 401 "Invalid credentials in Authorization header" by name, and
+ a permission-scoped 403 has no branch at all, so neither becomes GatedRepoError."""
+ from huggingface_hub.errors import HfHubHTTPError
+ return _hub_http_error(HfHubHTTPError, f"{status} Client Error.", status)
+
+
[email protected]("status", [401, 403])
+def test_an_invalid_token_is_an_access_error_not_a_transient_one(status, monkeypatch):
+ """An expired token must not fail open: that is the case the probe exists for."""
+ _stub_hub(monkeypatch, model_info_error = _auth_error(status))
+ with pytest.raises(ValueError) as excinfo:
+ _assert_base_repo_accessible(GATED_REPO, "stale-token")
+ assert GATED_REPO in str(excinfo.value)
+
+
[email protected]("status", [401, 403])
+def test_an_invalid_token_on_the_byte_probe_is_an_access_error(status, monkeypatch):
+ """Same on the second half, where metadata succeeded and only the HEAD carries the verdict."""
+ _stub_hub(monkeypatch, info = _FakeInfo("auto"), download_error = _auth_error(status))
+ with pytest.raises(ValueError) as excinfo:
+ _assert_base_repo_accessible(GATED_REPO, "stale-token")
+ assert GATED_REPO in str(excinfo.value)
+
+
[email protected]("status", [500, 429])
+def test_a_server_error_still_fails_open(status, monkeypatch):
+ """A 5xx or a rate limit is not an access verdict, so an offline-ish host still loads."""
+ _stub_hub(monkeypatch, info = _FakeInfo("auto"), download_error = _auth_error(status))
+ _assert_base_repo_accessible(GATED_REPO, "token")
+
+
[email protected]("token", ["", " ", None])
+def test_a_blank_token_is_not_sent_as_a_credential(token, monkeypatch):
+ """build_hf_headers sends any str verbatim, so "" becomes a literal "Bearer " the Hub answers
+ 401 to. Left unnormalized, the 401 handling would turn an open base into a hard access error."""
+ seen: list = []
+
+ class _Api:
+ def model_info(
+ self,
+ repo_id,
+ files_metadata = False,
+ token = None,
+ ):
+ seen.append(token)
+ return _FakeInfo(False)
+
+ monkeypatch.setattr("huggingface_hub.HfApi", lambda *a, **k: _Api())
+ _assert_base_repo_accessible("some-org/open-model", token)
+
+ assert seen == [None] # blank normalized away, so the cached login still applies
+
+
+def test_the_native_plan_preflights_its_companion_repos_too(monkeypatch):
+ """A GPU-less host routes /images/download-plan to the sd.cpp planner, whose asset list carries
+ its own companion repos: flux.1's VAE is the gated black-forest-labs/FLUX.1-schnell. The size
+ probe swallows the 401, so without the preflight that entry plans at 0 bytes and the fetch dies
+ on the bare token error."""
+ # Mirror swap off, so what this pins is the preflight itself: #7952 sends a gated companion
+ # to its ungated unsloth mirror, which the preflight now probes in its place. That rescue
+ # is exercised on its own below rather than folded into every refusal case.
+ monkeypatch.setenv("UNSLOTH_DIFFUSION_NO_MIRROR", "1")
+ from core.inference.sd_cpp_backend import SdCppDiffusionBackend
+
+ gated = "black-forest-labs/FLUX.1-schnell"
+ b = SdCppDiffusionBackend(engine = None)
+ monkeypatch.setattr(
+ SdCppDiffusionBackend, "_plan_file_sizes", staticmethod(lambda by_repo, token: {})
+ )
+
+ # Only the VAE repo is gated, as on the Hub: the pick and the encoder repo answer normally.
+ class _Api:
+ def model_info(
+ self,
+ repo_id,
+ files_metadata = False,
+ token = None,
+ ):
+ return _FakeInfo("auto" if repo_id == gated else False)
+
+ monkeypatch.setattr("huggingface_hub.HfApi", lambda *a, **k: _Api())
+ monkeypatch.setattr(
+ "huggingface_hub.get_hf_file_metadata",
+ lambda url, token = None, **k: (_ for _ in ()).throw(_gated_error()),
+ )
+
+ with pytest.raises(ValueError) as excinfo:
+ b.download_plan(
+ "unsloth/FLUX.1-dev-GGUF",
+ gguf_filename = "flux1-dev-Q4_K_M.gguf",
+ model_kind = "gguf",
+ )
+ detail = str(excinfo.value)
+ assert gated in detail and f"https://huggingface.co/{gated}" in detail
+
+ # An open family is untouched: every companion answers, so the plan is built exactly as before.
+ plan = b.download_plan(
+ "unsloth/Z-Image-Turbo-GGUF",
+ gguf_filename = "z-image-turbo-Q4_K_M.gguf",
+ model_kind = "gguf",
+ )
+ assert {e["repo_id"] for e in plan["entries"]} == {
+ "unsloth/Z-Image-Turbo-GGUF",
+ "Comfy-Org/z_image_turbo",
+ }
+
+
+def test_the_native_plan_probes_the_asset_it_stages(monkeypatch):
+ """flux.1's native VAE repo is read for ae.safetensors only, so probing the pipeline manifest
+ there would neither verify access to that file nor see it in the cache."""
+ # Mirror swap off, so what this pins is the preflight itself: #7952 sends a gated companion
+ # to its ungated unsloth mirror, which the preflight now probes in its place. That rescue
+ # is exercised on its own below rather than folded into every refusal case.
+ monkeypatch.setenv("UNSLOTH_DIFFUSION_NO_MIRROR", "1")
+ from core.inference.sd_cpp_backend import SdCppDiffusionBackend
+
+ gated = "black-forest-labs/FLUX.1-schnell"
+ b = SdCppDiffusionBackend(engine = None)
+ monkeypatch.setattr(
+ SdCppDiffusionBackend, "_plan_file_sizes", staticmethod(lambda by_repo, token: {})
+ )
+
+ class _Api:
+ def model_info(
+ self,
+ repo_id,
+ files_metadata = False,
+ token = None,
+ ):
+ return _FakeInfo("auto" if repo_id == gated else False)
+
+ monkeypatch.setattr("huggingface_hub.HfApi", lambda *a, **k: _Api())
+ probed: list = []
+
+ def _metadata(
+ url,
+ token = None,
+ **k,
+ ):
+ probed.append(url)
+ raise _gated_error()
+
+ monkeypatch.setattr("huggingface_hub.get_hf_file_metadata", _metadata)
+
+ # Nothing cached: the probe is the VAE file the plan stages, not the manifest.
+ monkeypatch.setattr("huggingface_hub.try_to_load_from_cache", lambda *a, **k: None)
+ with pytest.raises(ValueError, match = "gated"):
+ b.download_plan(
+ "unsloth/FLUX.1-dev-GGUF",
+ gguf_filename = "flux1-dev-Q4_K_M.gguf",
+ model_kind = "gguf",
+ )
+ assert probed == [f"https://huggingface.co/{gated}/resolve/main/ae.safetensors"]
+
+ # That same VAE already on disk clears the plan without a single Hub call.
+ probed.clear()
+ monkeypatch.setattr(
+ "huggingface_hub.try_to_load_from_cache",
+ lambda repo_id, filename, cache_dir = None, **k: (
+ "/cache/ae.safetensors" if filename == "ae.safetensors" else None
+ ),
+ )
+ plan = b.download_plan(
+ "unsloth/FLUX.1-dev-GGUF", gguf_filename = "flux1-dev-Q4_K_M.gguf", model_kind = "gguf"
+ )
+ assert probed == []
+ assert gated in {e["repo_id"] for e in plan["entries"]}
+
+
+def test_the_gguf_is_resolved_against_the_live_cache_root(monkeypatch, tmp_path):
+ """The prefetch stages the GGUF under the LIVE root, so an unpinned resolve reads
+ huggingface_hub's import-time constant and, after a mid-session cache change, pulls the whole
+ multi-GB file again inside the load lock."""
+ live = tmp_path / "live"
+ calls: list = []
+
+ def _download(
+ repo_id,
+ filename,
+ token = None,
+ cache_dir = None,
+ **k,
+ ):
+ calls.append(cache_dir)
+ return str(live / filename)
+
+ monkeypatch.setattr("huggingface_hub.hf_hub_download", _download)
+ monkeypatch.setattr("core.inference.diffusion.hub_cache_dir", lambda: str(live))
+
+ b = DiffusionBackend()
+
+ # Nothing cached anywhere: the download is pinned to the live root, not the import-time one.
+ monkeypatch.setattr("huggingface_hub.try_to_load_from_cache", lambda *a, **k: None)
+ b._resolve_gguf_path("unsloth/Z-Image-Turbo-GGUF", "z.gguf", None)
+ assert calls == [str(live)]
+
+ # A copy under the OTHER root is reached THROUGH that root, not returned raw: the blob is
+ # reused, but the ref still resolves, so a republished GGUF is picked up instead of pinned.
+ other = tmp_path / "other" / "z.gguf"
+ other.parent.mkdir(parents = True)
+ other.write_bytes(b"gguf")
+ calls.clear()
+ monkeypatch.setattr(
+ "huggingface_hub.try_to_load_from_cache",
+ lambda repo_id, filename, cache_dir = None, **k: None if cache_dir else str(other),
+ )
+ b._resolve_gguf_path("unsloth/Z-Image-Turbo-GGUF", "z.gguf", None)
+ assert calls == [None] # revalidated through the root holding the copy, never the live one
+
+ # Revalidation is a bonus, never a new failure: offline, the path already found is returned.
+ calls.clear()
+ monkeypatch.setattr(
+ "huggingface_hub.hf_hub_download",
+ lambda *a, **k: (_ for _ in ()).throw(OSError("offline")),
+ )
+ assert b._resolve_gguf_path("unsloth/Z-Image-Turbo-GGUF", "z.gguf", None) == str(other)
+
+
+def test_a_private_but_already_downloaded_base_is_not_refused(monkeypatch):
+ """huggingface_hub folds 401 into RepositoryNotFoundError ("401 is misleading", utils/_http.py),
+ so a PRIVATE companion base already on disk arrives indistinguishable from a deleted one.
+ Refusing it would block a load that works today: hf_hub_download serves the cached pointer once
+ the token is cleared or expires, exactly as it does for a gated base."""
+ from huggingface_hub.errors import RepositoryNotFoundError
+
+ private = "unsloth/private-base"
+ for status in (401, 403):
+ probed = _stub_hub(
+ monkeypatch,
+ model_info_error = _hub_http_error(
+ RepositoryNotFoundError, f"{status} Client Error.", status
+ ),
+ )
+ monkeypatch.setattr(
+ "huggingface_hub.try_to_load_from_cache",
+ lambda repo_id, filename, cache_dir = None, **k: "/cache/model_index.json",
+ )
+ _assert_base_repo_accessible(private, "expired-token")
+ assert probed == [] # served from disk, so not one byte probe was made
+
+
+def test_a_deleted_or_renamed_base_still_raises_even_when_cached(monkeypatch):
+ """The other side of the split: a 404 is not an access verdict a stale copy can excuse. The
+ repo is gone, and the size estimate swallows the 404 into a zero-byte plan."""
+ from huggingface_hub.errors import RepositoryNotFoundError
+
+ _stub_hub(
+ monkeypatch,
+ model_info_error = _hub_http_error(RepositoryNotFoundError, "404 Client Error.", 404),
+ )
+ monkeypatch.setattr(
+ "huggingface_hub.try_to_load_from_cache",
+ lambda repo_id, filename, cache_dir = None, **k: "/cache/model_index.json",
+ )
+ with pytest.raises(ValueError) as excinfo:
+ _assert_base_repo_accessible("unsloth/renamed-away", None)
+ assert "unsloth/renamed-away" in str(excinfo.value)
+
+
+def test_a_repo_not_found_with_no_response_still_raises(monkeypatch):
+ """A hub version that attaches no response leaves the status unreadable: neither 401 nor 404
+ can be proven, so the cache escape is not granted. Fail safe."""
+ from huggingface_hub.errors import RepositoryNotFoundError
+
+ # Built through __new__, because no constructor call can produce this on both hub majors: on
+ # 1.x ``response`` is a REQUIRED keyword-only argument AND its __init__ dereferences it
+ # unguarded, so omitting it raises TypeError and passing None raises AttributeError on
+ # response.headers. Bypassing __init__ is the only version-independent way to model the thing
+ # under test, an error carrying no response. Only args/response/server_message are read back
+ # (there is no __str__ override on either major), so setting those is enough.
+ err = RepositoryNotFoundError.__new__(RepositoryNotFoundError)
+ Exception.__init__(err, "no response attached")
+ err.response = None
+ err.request = None
+ err.request_id = None
+ err.server_message = None
+ _stub_hub(monkeypatch, model_info_error = err)
+ monkeypatch.setattr(
+ "huggingface_hub.try_to_load_from_cache",
+ lambda repo_id, filename, cache_dir = None, **k: "/cache/model_index.json",
+ )
+ with pytest.raises(ValueError):
+ _assert_base_repo_accessible("unsloth/mystery", None)
+
+
+def _native_backend_ready(monkeypatch):
+ """An SdCppDiffusionBackend whose binary resolution and asset fetch are stubbed out, so
+ ``_run_load`` reaches (or fails to reach) the preflight without touching a real engine."""
+ from core.inference.sd_cpp_backend import SdCppDiffusionBackend
+
+ b = SdCppDiffusionBackend(engine = None)
+ monkeypatch.setattr(
+ SdCppDiffusionBackend,
+ "_resolve_backend",
+ lambda self: ("oneshot", None, types.SimpleNamespace(version = lambda: "master")),
+ )
+ monkeypatch.setattr(
+ SdCppDiffusionBackend, "_set_expected_bytes", lambda self, assets, token: None
+ )
+ fetched: list = []
+
+ def _fetch(
+ self,
+ assets,
+ token,
+ cancel_event = None,
+ ):
+ fetched.append(assets)
+ raise AssertionError("the gated companion must be caught before any byte is fetched")
+
+ monkeypatch.setattr(SdCppDiffusionBackend, "_fetch_assets", _fetch)
+ return b, fetched
+
+
+def test_the_native_load_preflights_its_companion_repos_too(monkeypatch):
+ """The plan alone is not enough: images-page.tsx wraps getDiffusionDownloadPlan in a try/catch
+ and calls /images/load regardless, so the plan's 400 is swallowed and the load would run with
+ no preflight. The diffusers backend checks in both places; the native one must too."""
+ # Mirror swap off, so what this pins is the preflight itself: #7952 sends a gated companion
+ # to its ungated unsloth mirror, which the preflight now probes in its place. That rescue
+ # is exercised on its own below rather than folded into every refusal case.
+ monkeypatch.setenv("UNSLOTH_DIFFUSION_NO_MIRROR", "1")
+ from core.inference.diffusion_families import detect_family_for_pick
+ from core.inference.sd_cpp_backend import _SdLoading
+
+ gated = "black-forest-labs/FLUX.1-schnell"
+ b, fetched = _native_backend_ready(monkeypatch)
+ b._loading = _SdLoading(repo_id = "unsloth/FLUX.1-dev-GGUF", base_repo = "")
+
+ class _Api:
+ def model_info(
+ self,
+ repo_id,
+ files_metadata = False,
+ token = None,
+ ):
+ return _FakeInfo("auto" if repo_id == gated else False)
+
+ monkeypatch.setattr("huggingface_hub.HfApi", lambda *a, **k: _Api())
+ monkeypatch.setattr(
+ "huggingface_hub.get_hf_file_metadata",
+ lambda url, token = None, **k: (_ for _ in ()).throw(_gated_error()),
+ )
+ monkeypatch.setattr("huggingface_hub.try_to_load_from_cache", lambda *a, **k: None)
+
+ fam = detect_family_for_pick("unsloth/FLUX.1-dev-GGUF", "flux1-dev-Q4_K_M.gguf", None)
+ b._run_load(
+ repo_id = "unsloth/FLUX.1-dev-GGUF",
+ gguf_filename = "flux1-dev-Q4_K_M.gguf",
+ base = "",
+ fam = fam,
+ hf_token = "no-access",
+ _load_token = b._load_token,
+ )
+
+ assert fetched == [] # refused before the multi-GB pull, not 15 GiB into it
+ detail = b._loading.error or ""
+ assert gated in detail and "licence" in detail.lower()
+
+
+def test_the_native_load_probes_the_asset_it_stages_and_honours_the_cache(monkeypatch):
+ """Same two properties as the plan half, so the load half cannot drift: the probe is the file
+ THIS pick stages (a VAE-only repo has no manifest), and a cached companion is never refused."""
+ # Mirror swap off, so what this pins is the preflight itself: #7952 sends a gated companion
+ # to its ungated unsloth mirror, which the preflight now probes in its place. That rescue
+ # is exercised on its own below rather than folded into every refusal case.
+ monkeypatch.setenv("UNSLOTH_DIFFUSION_NO_MIRROR", "1")
+ from core.inference.diffusion_families import detect_family_for_pick
+ from core.inference.sd_cpp_backend import _SdLoading
+
+ gated = "black-forest-labs/FLUX.1-schnell"
+ b, fetched = _native_backend_ready(monkeypatch)
+ b._loading = _SdLoading(repo_id = "unsloth/FLUX.1-dev-GGUF", base_repo = "")
+
+ class _Api:
+ def model_info(
+ self,
+ repo_id,
+ files_metadata = False,
+ token = None,
+ ):
+ return _FakeInfo("auto" if repo_id == gated else False)
+
+ monkeypatch.setattr("huggingface_hub.HfApi", lambda *a, **k: _Api())
+ probed: list = []
+
+ def _metadata(
+ url,
+ token = None,
+ **k,
+ ):
+ probed.append(url)
+ raise _gated_error()
+
+ monkeypatch.setattr("huggingface_hub.get_hf_file_metadata", _metadata)
+ monkeypatch.setattr("huggingface_hub.try_to_load_from_cache", lambda *a, **k: None)
+
+ fam = detect_family_for_pick("unsloth/FLUX.1-dev-GGUF", "flux1-dev-Q4_K_M.gguf", None)
+ kwargs = dict(
+ repo_id = "unsloth/FLUX.1-dev-GGUF",
+ gguf_filename = "flux1-dev-Q4_K_M.gguf",
+ base = "",
+ fam = fam,
+ hf_token = "no-access",
+ _load_token = b._load_token,
+ )
+ b._run_load(**kwargs)
+ # The VAE file the load actually opens, not model_index.json, which that repo would not serve.
+ assert probed == [f"https://huggingface.co/{gated}/resolve/main/ae.safetensors"]
+ assert fetched == []
+
+ # That same VAE already on disk clears the preflight and the load proceeds to the fetch.
+ probed.clear()
+ b._loading = _SdLoading(repo_id = "unsloth/FLUX.1-dev-GGUF", base_repo = "")
+ monkeypatch.setattr(
+ "huggingface_hub.try_to_load_from_cache",
+ lambda repo_id, filename, cache_dir = None, **k: (
+ "/cache/ae.safetensors" if filename == "ae.safetensors" else None
+ ),
+ )
+ b._run_load(**kwargs)
+ assert probed == []
+ assert len(fetched) == 1 # got past the preflight, exactly as before this check existed
+
+
+def _stub_shared_download(
+ monkeypatch,
+ tmp_path,
+ cached_elsewhere = (),
+):
+ """Record the cache root each companion download resolves against.
+
+ ``cached_elsewhere`` names the files that exist ONLY under huggingface_hub's import-time root
+ (Studio's cache folder was changed mid-session), so the live root is a miss for them."""
+ import utils.hf_xet_fallback as X
+
+ seen: list = []
+
+ def _shared(repo_id, filename, token, **k):
+ seen.append((filename, k.get("cache_dir")))
+ return f"/somewhere/{filename}"
+
+ monkeypatch.setattr(X, "_shared_hf_hub_download_with_xet_fallback", _shared)
+ monkeypatch.setattr(
+ "utils.hf_cache_settings.get_hf_cache_paths",
+ lambda: types.SimpleNamespace(hub_cache = "/live-hub"),
+ )
+ other = tmp_path / "other-hub" / "blob"
+ other.parent.mkdir(parents = True, exist_ok = True)
+ other.write_bytes(b"cached under the import-time root")
+ monkeypatch.setattr(
+ "huggingface_hub.try_to_load_from_cache",
+ lambda repo_id, filename, cache_dir = None, **k: (
+ str(other) if cache_dir is None and filename in cached_elsewhere else None
+ ),
+ )
+ return seen
+
+
+def test_the_prefetch_reuses_a_base_asset_cached_under_the_other_root(monkeypatch, tmp_path):
+ """The preflight clears a base found under EITHER cache root, but the companion downloads are
+ pinned to the live one, so after a cache-folder change the load re-fetches every cached asset
+ and, with no valid token for a gated base, 401s outright. The download has to resolve through
+ the root that actually holds the file, as the GGUF and pre-quant resolvers do."""
+ seen = _stub_shared_download(monkeypatch, tmp_path, cached_elsewhere = {"ae.safetensors"})
+ DiffusionBackend()._prefetch_files(
+ "unsloth/FLUX.1-dev-GGUF",
+ None,
+ "black-forest-labs/FLUX.1-dev",
+ ["ae.safetensors", "text_encoder/model.safetensors"],
+ "no-access",
+ )
+ assert seen == [
+ # cached only under the import-time root: reached through it, not re-pulled into the live one
+ ("ae.safetensors", None),
+ # nowhere on disk: a real download, still pinned to the root Studio is reading
+ ("text_encoder/model.safetensors", "/live-hub"),
+ ]
+
+
+def _stub_split_download(monkeypatch, per_file):
+ """Resolve each companion to the exact path ``per_file`` names, so a test can put the manifest
+ and the rest of the base under DIFFERENT cache roots the way a mid-session cache move does."""
+ import utils.hf_xet_fallback as X
+
+ monkeypatch.setattr(
+ X,
+ "_shared_hf_hub_download_with_xet_fallback",
+ lambda repo_id, filename, token, **k: per_file[filename],
+ )
+ monkeypatch.setattr(
+ "utils.hf_cache_settings.get_hf_cache_paths",
+ lambda: types.SimpleNamespace(hub_cache = "/live-hub"),
+ )
+
+
+def test_a_prefetch_split_across_roots_hands_back_no_snapshot(monkeypatch):
+ """Per-file root reuse can serve the manifest from the old root while the companions download
+ into the live one. The manifest's snapshot dir then does not contain them, so returning it
+ would point from_pretrained at a tree missing the VAE and fail a load that the plain hub id
+ completes. Falling back to the hub id costs nothing: it resolves each file through its own
+ root, which is how the files got here."""
+ old = "/old-hub/models--bfl--base/snapshots/" + "a" * 40
+ live = "/live-hub/models--bfl--base/snapshots/" + "a" * 40
+ _stub_split_download(
+ monkeypatch,
+ {
+ "model_index.json": f"{old}/model_index.json",
+ "vae/diffusion_pytorch_model.safetensors": (
+ f"{live}/vae/diffusion_pytorch_model.safetensors"
+ ),
+ },
+ )
+ assert (
+ DiffusionBackend()._prefetch_files(
+ "unsloth/FLUX.1-dev-GGUF",
+ None,
+ "bfl/base",
+ ["model_index.json", "vae/diffusion_pytorch_model.safetensors"],
+ None,
+ )
+ is None
+ )
+
+
+def test_a_prefetch_wholly_in_one_root_still_hands_back_that_snapshot(monkeypatch):
+ """The other side, so the guard above cannot be satisfied by never returning a snapshot: when
+ every prefetched file does live in the manifest's snapshot, the loader is still handed it. A
+ subfolder entry resolves to the same root as a top-level one."""
+ root = "/old-hub/models--bfl--base/snapshots/" + "a" * 40
+ _stub_split_download(
+ monkeypatch,
+ {
+ "model_index.json": f"{root}/model_index.json",
+ "vae/diffusion_pytorch_model.safetensors": (
+ f"{root}/vae/diffusion_pytorch_model.safetensors"
+ ),
+ },
+ )
+ assert (
+ DiffusionBackend()._prefetch_files(
+ "unsloth/FLUX.1-dev-GGUF",
+ None,
+ "bfl/base",
+ ["model_index.json", "vae/diffusion_pytorch_model.safetensors"],
+ None,
+ )
+ == root
+ )
+
+
+def test_an_unreadable_gguf_cache_probe_still_downloads(tmp_path, monkeypatch):
+ """A malformed cache makes try_to_load_from_cache raise. That is not a verdict about the repo,
+ so it must not abort a remote GGUF load that only had to download."""
+ import huggingface_hub
+
+ def _boom(*a, **k):
+ raise OSError("unreadable cache")
+
+ monkeypatch.setattr(huggingface_hub, "try_to_load_from_cache", _boom)
+ monkeypatch.setattr(
+ huggingface_hub,
+ "hf_hub_download",
+ lambda repo_id, filename, **k: f"/downloaded/{filename}",
+ )
+ monkeypatch.setattr(
+ "core.inference.diffusion.hub_cache_dir", lambda: str(tmp_path / "live-hub")
+ )
+ path = DiffusionBackend()._resolve_gguf_path("unsloth/FLUX.1-dev-GGUF", "m.gguf", None)
+ assert path == "/downloaded/m.gguf"
+
+
+def test_a_base_excused_by_the_other_root_is_loaded_from_that_snapshot(monkeypatch, tmp_path):
+ """The prefetch reuse above only covers a base the size estimate could list, and the estimate
+ comes from the very ``model_info`` call whose 401 earned the cache escape: a private base, or a
+ stale token on any base, leaves ``base_files`` empty, so nothing is staged and
+ ``from_pretrained``, pinned to the live root, re-raises the bare Hub auth error over a base
+ completely on disk. The preflight carries the snapshot it accepted so the load reads it."""
+ from huggingface_hub.errors import RepositoryNotFoundError
+
+ private = "unsloth/private-base"
+ snapshot = tmp_path / "other-hub" / "models--unsloth--private-base" / "snapshots" / ("c" * 40)
+ snapshot.mkdir(parents = True)
+ (snapshot / "model_index.json").write_text("{}")
+
+ backend = DiffusionBackend()
+ monkeypatch.setattr(
+ "core.inference.diffusion.detect_family_for_pick",
+ lambda *a, **k: types.SimpleNamespace(name = "flux.1", single_file_is_pipeline = False),
+ )
+ monkeypatch.setattr("core.inference.diffusion._resolve_base_repo", lambda *a, **k: private)
+ # Studio's cache folder was changed: the live root holds none of it.
+ monkeypatch.setattr(
+ "core.inference.diffusion.hub_cache_dir", lambda: str(tmp_path / "live-hub")
+ )
+ _stub_hub(
+ monkeypatch,
+ model_info_error = _hub_http_error(RepositoryNotFoundError, "401 Client Error.", 401),
+ )
+ monkeypatch.setattr(
+ "huggingface_hub.try_to_load_from_cache",
+ lambda repo_id, filename, cache_dir = None, **k: (
+ str(snapshot / filename) if cache_dir is None and repo_id == private else None
+ ),
+ )
+ staged: list = []
+
+ def _prefetch(
+ self,
+ repo_id,
+ gguf_filename,
+ base,
+ base_files,
+ hf_token,
+ cancel_event = None,
+ fetch_base = None,
+ ):
+ staged.append(base_files)
+ return None
+
+ monkeypatch.setattr(DiffusionBackend, "_prefetch_files", _prefetch)
+ loaded: dict = {}
+ monkeypatch.setattr(DiffusionBackend, "load_pipeline", lambda self, **k: loaded.update(k))
+ backend._loading = _LoadingState(repo_id = "unsloth/FLUX.1-dev-GGUF", base_repo = private)
+
+ backend._run_load(
+ repo_id = "unsloth/FLUX.1-dev-GGUF",
+ gguf_filename = "flux1-dev-Q4_K_M.gguf",
+ hf_token = "expired-token",
+ _load_token = backend._load_token,
+ )
+
+ # The 401 the escape forgave is the same call the estimate needs, so it stages nothing.
+ assert staged == [[]]
+ # ...and the load still reaches the base, through the root that actually holds it.
+ assert loaded["_base_local_dir"] == str(snapshot)
+ assert backend._loading is None
+
+
+def test_a_base_excused_by_the_live_root_carries_no_snapshot(monkeypatch, tmp_path):
+ """The other side: a copy under the root the loader already reads needs no escort. Returning
+ one would pin ``from_pretrained`` to a local dir, so a partially cached base could no longer
+ finish its own download."""
+ from huggingface_hub.errors import RepositoryNotFoundError
+
+ private = "unsloth/private-base"
+ monkeypatch.setattr("core.inference.diffusion.hub_cache_dir", lambda: str(tmp_path / "live"))
+ _stub_hub(
+ monkeypatch,
+ model_info_error = _hub_http_error(RepositoryNotFoundError, "401 Client Error.", 401),
+ )
+ monkeypatch.setattr(
+ "huggingface_hub.try_to_load_from_cache",
+ lambda repo_id, filename, cache_dir = None, **k: (
+ f"{tmp_path}/live/snap/{filename}" if cache_dir is not None else None
+ ),
+ )
+
+ assert _assert_base_repo_accessible(private, "expired-token") is None
+
+
+def test_the_native_fetch_reuses_a_base_asset_cached_under_the_other_root(monkeypatch, tmp_path):
+ """Same for the native sd.cpp loader, whose preflight grants the same two-root escape."""
+ from core.inference.sd_cpp_backend import SdCppDiffusionBackend
+
+ seen = _stub_shared_download(monkeypatch, tmp_path, cached_elsewhere = {"ae.safetensors"})
+ b = SdCppDiffusionBackend(engine = None)
+ b._fetch_assets(
+ [
+ ("black-forest-labs/FLUX.1-dev", "ae.safetensors", "vae"),
+ ("unsloth/FLUX.1-dev-GGUF", "flux1-dev-Q4_K_M.gguf", "diffusion_model"),
+ ],
+ "no-access",
+ )
+ assert seen == [("ae.safetensors", None), ("flux1-dev-Q4_K_M.gguf", "/live-hub")]
+
+
+def test_a_gated_base_with_a_live_mirror_is_not_refused(monkeypatch):
+ """The other side of every refusal above, and the reason the probe moved onto the fetch repo.
+
+ #7952 sends a gated base to its ungated unsloth mirror, so the bytes never touch the vendor
+ id. A preflight that kept probing the upstream would refuse exactly the picks that swap
+ rescues, turning a working load into a 400 -- worse than the bare token error this whole
+ preflight replaced."""
+ mirror = "unsloth/FLUX.1-dev"
+ probed: list = []
+
+ class _Api:
+ def model_info(
+ self,
+ repo_id,
+ files_metadata = False,
+ token = None,
+ ):
+ # Gated upstream, open mirror: the Hub state this rescue exists for.
+ return _FakeInfo(
+ "auto" if repo_id == GATED_REPO else False,
+ [
+ _FakeSibling("model_index.json", 1000),
+ _FakeSibling("vae/diffusion_pytorch_model.safetensors", 2000),
+ ],
+ )
+
+ def _metadata(
+ url,
+ token = None,
+ **k,
+ ):
+ probed.append(url)
+ raise _gated_error()
+
+ monkeypatch.setattr("huggingface_hub.HfApi", lambda *a, **k: _Api())
+ monkeypatch.setattr("huggingface_hub.get_hf_file_metadata", _metadata)
+ monkeypatch.setattr("huggingface_hub.try_to_load_from_cache", lambda *a, **k: None)
+ monkeypatch.setattr("core.inference.diffusion._resolve_base_repo", lambda *a, **k: GATED_REPO)
+
+ plan = DiffusionBackend().download_plan(
+ "unsloth/FLUX.1-dev-GGUF", gguf_filename = "flux1-dev-Q4_K_M.gguf"
+ )
+
+ repos = {e["repo_id"] for e in plan["entries"]}
+ # Staged from the mirror, and probed there too: an open repo costs one metadata call and no
+ # byte probe, so the 401 the upstream would have raised never happens.
+ assert mirror in repos and GATED_REPO not in repos
+ assert probed == []
+
+
+def test_the_native_load_lets_the_mirror_stand_in_for_a_gated_companion(monkeypatch):
+ """Same rescue on the sd.cpp path, which has its own preflight and its own swap: both have to
+ take the same decision or the load refuses a companion it was about to fetch from elsewhere."""
+ from core.inference.diffusion_families import detect_family_for_pick
+ from core.inference.sd_cpp_backend import _SdLoading
+
+ gated = "black-forest-labs/FLUX.1-schnell"
+ b, fetched = _native_backend_ready(monkeypatch)
+ b._loading = _SdLoading(repo_id = "unsloth/FLUX.1-dev-GGUF", base_repo = "")
+
+ class _Api:
+ def model_info(
+ self,
+ repo_id,
+ files_metadata = False,
+ token = None,
+ ):
+ return _FakeInfo("auto" if repo_id == gated else False)
+
+ monkeypatch.setattr("huggingface_hub.HfApi", lambda *a, **k: _Api())
+ monkeypatch.setattr(
+ "huggingface_hub.get_hf_file_metadata",
+ lambda url, token = None, **k: (_ for _ in ()).throw(_gated_error()),
+ )
+ monkeypatch.setattr("huggingface_hub.try_to_load_from_cache", lambda *a, **k: None)
+
+ fam = detect_family_for_pick("unsloth/FLUX.1-dev-GGUF", "flux1-dev-Q4_K_M.gguf", None)
+ b._run_load(
+ repo_id = "unsloth/FLUX.1-dev-GGUF",
+ gguf_filename = "flux1-dev-Q4_K_M.gguf",
+ base = "",
+ fam = fam,
+ hf_token = "no-access",
+ _load_token = b._load_token,
+ )
+
+ # Reached the fetch instead of being refused, and the VAE it asks for is the mirror's.
+ assert len(fetched) == 1
+ vae_repos = {repo for repo, _f, kind in fetched[0] if kind == "vae"}
+ assert vae_repos == {"unsloth/FLUX.1-schnell"}
diff --git a/studio/backend/tests/test_diffusion_prequant.py b/studio/backend/tests/test_diffusion_prequant.py
index 71cda8d8ece..13abeb677c4 100644
--- a/studio/backend/tests/test_diffusion_prequant.py
+++ b/studio/backend/tests/test_diffusion_prequant.py
@@ -15,6 +15,8 @@ import contextlib
import sys
import types
+import pytest
+
import core.inference.diffusion_prequant as pq
from core.inference.diffusion_families import DiffusionFamily
from core.inference.diffusion_prequant import (
@@ -498,8 +500,19 @@ def test_load_repo_source_allowed_without_optin(monkeypatch, tmp_path):
downloaded = tmp_path / "transformer_fp8.pt"
downloaded.write_bytes(b"x")
+ roots: list = []
+
+ def _dl(
+ repo_id,
+ filename,
+ token = None,
+ cache_dir = None,
+ ):
+ roots.append(cache_dir)
+ return str(downloaded)
+
hub = types.ModuleType("huggingface_hub")
- hub.hf_hub_download = lambda repo_id, filename, token = None: str(downloaded)
+ hub.hf_hub_download = _dl
monkeypatch.setitem(sys.modules, "huggingface_hub", hub)
source = PrequantSource(kind = "repo", location = "org/hosted-fp8", filename = "transformer_fp8.pt")
@@ -511,9 +524,12 @@ def test_load_repo_source_allowed_without_optin(monkeypatch, tmp_path):
dtype = "bfloat16",
hf_token = None,
scheme = "fp8",
+ cache_dir = "/live-hub",
logger = None,
)
assert result is not None
+ # The loader pins the caller's live root, so the fetch cannot split across two.
+ assert roots == ["/live-hub"]
def test_load_repo_source_falls_back_to_legacy_filename(monkeypatch, tmp_path):
@@ -536,6 +552,7 @@ def test_load_repo_source_falls_back_to_legacy_filename(monkeypatch, tmp_path):
repo_id,
filename,
token = None,
+ cache_dir = None,
):
requested.append(filename)
if filename != "transformer_fp8.pt":
@@ -716,3 +733,568 @@ def test_pin_kernel_preference_no_torchao(monkeypatch):
sd = {"a.weight": _FakeFp8Weight(_FakeKernelPreference.AUTO)}
assert pq._pin_kernel_preference(sd, logger = None) == 0
assert sd["a.weight"].kernel_preference == _FakeKernelPreference.AUTO
+
+
+# ── local cache lookup (no network) ──────────────────────────────────────────────
+def test_prequant_checkpoint_cached_reads_only_the_cache(monkeypatch, tmp_path):
+ # Memory planning asks this, so it must be a pure lookup: no Hub call, no raise.
+ from core.inference.diffusion_prequant import prequant_checkpoint_cached
+
+ ckpt = tmp_path / "Z-Image-Turbo-FP8.pt"
+ ckpt.write_bytes(b"weights")
+ legacy = tmp_path / "transformer_fp8.pt"
+ legacy.write_bytes(b"weights")
+ source = PrequantSource(
+ kind = "repo",
+ location = "unsloth/Z-Image-Turbo-FP8",
+ filename = "Z-Image-Turbo-FP8.pt",
+ fallback_filename = "transformer_fp8.pt",
+ )
+ asked: list = []
+
+ def _cache(
+ repo_id,
+ filename,
+ cache_dir = None,
+ ):
+ asked.append((repo_id, filename, cache_dir))
+ return str(tmp_path / filename) if (tmp_path / filename).is_file() else None
+
+ monkeypatch.setattr("huggingface_hub.try_to_load_from_cache", _cache)
+ monkeypatch.setattr(
+ "huggingface_hub.hf_hub_download",
+ lambda *a, **k: pytest.fail("the cache probe must never download"),
+ )
+
+ assert prequant_checkpoint_cached(source, cache_dir = "/models/hub") is True
+ # The live root is asked first, and the model-name file resolves, so no legacy lookup.
+ assert asked == [("unsloth/Z-Image-Turbo-FP8", "Z-Image-Turbo-FP8.pt", "/models/hub")]
+
+ # Only the legacy name on disk does NOT count: whether the repo publishes the canonical one
+ # cannot be known without a network call, so this reads as "would download" and the GGUF runs.
+ ckpt.unlink()
+ assert prequant_checkpoint_cached(source) is False
+ # Neither name cached -> same answer, for the ordinary reason.
+ legacy.unlink()
+ assert prequant_checkpoint_cached(source) is False
+
+
+def test_a_live_root_hit_still_goes_through_the_hub_so_it_revalidates(monkeypatch, tmp_path):
+ # hf_hub_download(cache_dir = live) reuses that root's blob AND revalidates, so a hit there
+ # must not be short-circuited: returning it raw would pin a stale checkpoint past a republish.
+ live = tmp_path / "live-hub"
+ live.mkdir()
+ ckpt = live / "Z-Image-Turbo-FP8.pt"
+ ckpt.write_bytes(b"weights")
+ source = PrequantSource(
+ kind = "repo",
+ location = "unsloth/Z-Image-Turbo-FP8",
+ filename = "Z-Image-Turbo-FP8.pt",
+ fallback_filename = "transformer_fp8.pt",
+ )
+
+ def _cache(
+ repo_id,
+ filename,
+ cache_dir = None,
+ ):
+ path = live / filename
+ return str(path) if cache_dir == str(live) and path.is_file() else None
+
+ monkeypatch.setattr("huggingface_hub.try_to_load_from_cache", _cache)
+ asked: list = []
+
+ def _download(
+ repo_id,
+ filename,
+ token = None,
+ cache_dir = None,
+ ):
+ asked.append((filename, cache_dir))
+ return str(ckpt) # the same blob, revalidated
+
+ monkeypatch.setattr("huggingface_hub.hf_hub_download", _download)
+
+ # Still "cached" for the decline gate: this costs a HEAD, not a multi-GB fetch.
+ assert pq.prequant_checkpoint_cached(source, cache_dir = str(live)) is True
+ assert pq._resolve_checkpoint_path(source, None, str(live)) == str(ckpt)
+ assert asked == [("Z-Image-Turbo-FP8.pt", str(live))] # pinned to the root holding the blob
+
+
+def _other_root_source():
+ return PrequantSource(
+ kind = "repo",
+ location = "unsloth/Z-Image-Turbo-FP8",
+ filename = "Z-Image-Turbo-FP8.pt",
+ fallback_filename = "transformer_fp8.pt",
+ )
+
+
+def test_a_hit_only_in_the_other_root_is_revalidated_through_that_root(monkeypatch, tmp_path):
+ # The case this branch exists for: hf_hub_download(cache_dir = live) would not look in
+ # huggingface_hub's import-time root and would re-fetch multiple GB already here, while
+ # returning the cached path raw would pin it past a republish. So the download is re-run
+ # THROUGH the root that holds the copy, which reuses the blob and costs one HEAD.
+ default_root = tmp_path / "default-hub"
+ default_root.mkdir()
+ ckpt = default_root / "Z-Image-Turbo-FP8.pt"
+ ckpt.write_bytes(b"weights")
+ source = _other_root_source()
+
+ def _cache(
+ repo_id,
+ filename,
+ cache_dir = None,
+ ):
+ # Only the import-time default (cache_dir None) holds it; the live root is a miss.
+ path = default_root / filename
+ return str(path) if cache_dir is None and path.is_file() else None
+
+ monkeypatch.setattr("huggingface_hub.try_to_load_from_cache", _cache)
+ asked: list = []
+
+ def _download(
+ repo_id,
+ filename,
+ token = None,
+ cache_dir = None,
+ ):
+ asked.append((filename, cache_dir))
+ return str(ckpt) # unchanged upstream: the same blob, revalidated
+
+ monkeypatch.setattr("huggingface_hub.hf_hub_download", _download)
+
+ assert pq.prequant_checkpoint_cached(source, cache_dir = "/models/live") is True
+ assert pq._resolve_checkpoint_path(source, None, "/models/live") == str(ckpt)
+ # cache_dir None, never the live root: the live root is empty, so pinning it there would be
+ # the multi-GB re-fetch the caller declined on.
+ assert asked == [("Z-Image-Turbo-FP8.pt", None)]
+
+
+def test_a_republished_checkpoint_in_the_other_root_is_picked_up(monkeypatch, tmp_path):
+ # Revalidation earns its HEAD here: the repo replaced the file under the same name, so the
+ # cached pointer is stale and the loader must follow the new snapshot instead.
+ default_root = tmp_path / "default-hub"
+ default_root.mkdir()
+ stale = default_root / "Z-Image-Turbo-FP8.pt"
+ stale.write_bytes(b"old weights")
+ fresh = default_root / "snapshots-new" / "Z-Image-Turbo-FP8.pt"
+ fresh.parent.mkdir()
+ fresh.write_bytes(b"corrected weights")
+
+ monkeypatch.setattr(
+ "huggingface_hub.try_to_load_from_cache",
+ lambda repo_id, filename, cache_dir = None, **k: (
+ str(stale) if cache_dir is None and filename == "Z-Image-Turbo-FP8.pt" else None
+ ),
+ )
+ monkeypatch.setattr("huggingface_hub.hf_hub_download", lambda **kwargs: str(fresh))
+
+ assert pq._resolve_checkpoint_path(_other_root_source(), None, "/models/live") == str(fresh)
+
+
+def test_other_root_revalidation_never_breaks_a_load_that_works(monkeypatch, tmp_path):
+ # Offline hf_hub_download already serves the cached pointer, but anything else it raises (a hub
+ # layout change, a read-only root) must fall back to the copy already located.
+ default_root = tmp_path / "default-hub"
+ default_root.mkdir()
+ ckpt = default_root / "Z-Image-Turbo-FP8.pt"
+ ckpt.write_bytes(b"weights")
+
+ monkeypatch.setattr(
+ "huggingface_hub.try_to_load_from_cache",
+ lambda repo_id, filename, cache_dir = None, **k: (
+ str(default_root / filename)
+ if cache_dir is None and (default_root / filename).is_file()
+ else None
+ ),
+ )
+ asked: list = []
+
+ def _download(**kwargs):
+ asked.append(kwargs["cache_dir"])
+ raise RuntimeError("hub is unhappy")
+
+ monkeypatch.setattr("huggingface_hub.hf_hub_download", _download)
+
+ assert pq._resolve_checkpoint_path(_other_root_source(), None, "/models/live") == str(ckpt)
+ assert asked == [None] # it was tried, through the root holding the copy, and forgiven
+
+
+def test_an_uncached_checkpoint_downloads_into_the_live_root(monkeypatch):
+ # The other half: a real fetch must land where Studio is reading, not under the stale constant.
+ asked: list = []
+ source = PrequantSource(
+ kind = "repo", location = "unsloth/Z-Image-Turbo-FP8", filename = "Z-Image-Turbo-FP8.pt"
+ )
+
+ def _dl(**kwargs):
+ asked.append(kwargs)
+ return "/live-hub/blobs/abc"
+
+ monkeypatch.setattr("huggingface_hub.try_to_load_from_cache", lambda *a, **k: None)
+ monkeypatch.setattr("huggingface_hub.hf_hub_download", _dl)
+
+ assert pq._resolve_checkpoint_path(source, "tok", "/live-hub") == "/live-hub/blobs/abc"
+ assert asked == [
+ {
+ "repo_id": "unsloth/Z-Image-Turbo-FP8",
+ "filename": "Z-Image-Turbo-FP8.pt",
+ "token": "tok",
+ "cache_dir": "/live-hub",
+ }
+ ]
+
+
+def test_prequant_checkpoint_cached_never_raises(monkeypatch):
+ # An unanswerable probe is "not cached", never an exception into the memory planner.
+ from core.inference.diffusion_prequant import prequant_checkpoint_cached
+
+ monkeypatch.setattr(
+ "huggingface_hub.try_to_load_from_cache",
+ lambda *a, **k: (_ for _ in ()).throw(OSError("unreadable cache")),
+ )
+ source = PrequantSource(kind = "repo", location = "org/hosted-fp8", filename = "hosted-FP8.pt")
+ assert prequant_checkpoint_cached(source) is False
+ # A local override is the operator's own file, so it is not a cache question.
+ assert prequant_checkpoint_cached(PrequantSource(kind = "path", location = "/tmp/x.pt")) is False
+ assert prequant_checkpoint_cached(None) is False
+
+
+def test_a_cached_legacy_file_does_not_pre_empt_the_canonical_one(monkeypatch, tmp_path):
+ """fallback_filename is primary-first by contract, reached only once the canonical name is
+ absent remotely. Short-circuiting on a cached legacy artifact would pin a stale
+ transformer_<scheme>.pt forever, even after the repo publishes the real name."""
+ from core.inference.diffusion_prequant import _resolve_checkpoint_path
+
+ legacy = tmp_path / "transformer_fp8.pt"
+ legacy.write_bytes(b"stale")
+ source = PrequantSource(
+ kind = "repo",
+ location = "unsloth/Z-Image-Turbo-FP8",
+ filename = "Z-Image-Turbo-FP8.pt",
+ fallback_filename = "transformer_fp8.pt",
+ )
+ monkeypatch.setattr(
+ "huggingface_hub.try_to_load_from_cache",
+ lambda repo_id, filename, cache_dir = None: (
+ str(tmp_path / filename) if (tmp_path / filename).is_file() else None
+ ),
+ )
+ asked: list = []
+
+ def _download(
+ repo_id,
+ filename,
+ token = None,
+ cache_dir = None,
+ ):
+ asked.append(filename)
+ return str(tmp_path / "downloaded-canonical.pt")
+
+ monkeypatch.setattr("huggingface_hub.hf_hub_download", _download)
+
+ assert _resolve_checkpoint_path(source, None) == str(tmp_path / "downloaded-canonical.pt")
+ assert asked == ["Z-Image-Turbo-FP8.pt"] # the canonical name, not the cached legacy one
+
+
+def test_the_legacy_name_is_still_used_once_the_canonical_one_is_absent(monkeypatch, tmp_path):
+ """The other direction, which is what fallback_filename exists for: a repo that only ever
+ shipped the legacy artifact must still load."""
+ from huggingface_hub.errors import EntryNotFoundError
+
+ from core.inference.diffusion_prequant import _resolve_checkpoint_path
+
+ source = PrequantSource(
+ kind = "repo",
+ location = "unsloth/Z-Image-Turbo-FP8",
+ filename = "Z-Image-Turbo-FP8.pt",
+ fallback_filename = "transformer_fp8.pt",
+ )
+ monkeypatch.setattr("huggingface_hub.try_to_load_from_cache", lambda *a, **k: None)
+ asked: list = []
+
+ def _download(
+ repo_id,
+ filename,
+ token = None,
+ cache_dir = None,
+ ):
+ asked.append(filename)
+ if filename == "Z-Image-Turbo-FP8.pt":
+ raise EntryNotFoundError("404")
+ return str(tmp_path / filename)
+
+ monkeypatch.setattr("huggingface_hub.hf_hub_download", _download)
+
+ assert _resolve_checkpoint_path(source, None) == str(tmp_path / "transformer_fp8.pt")
+ assert asked == ["Z-Image-Turbo-FP8.pt", "transformer_fp8.pt"] # primary first, then legacy
+
+
+def test_a_legacy_copy_in_the_other_root_is_reused_after_the_primary_404s(monkeypatch, tmp_path):
+ """Once the primary is absent remotely the legacy name IS the artifact, so it needs the same
+ other-root treatment: hf_hub_download(cache_dir = live) cannot see a copy in huggingface_hub's
+ import-time root and would re-fetch multiple GB, while returning that copy raw would pin it
+ past a republish. Revalidate through the root holding it instead."""
+ from huggingface_hub.errors import EntryNotFoundError
+
+ default_root = tmp_path / "default-hub"
+ default_root.mkdir()
+ legacy = default_root / "transformer_fp8.pt"
+ legacy.write_bytes(b"weights")
+ source = PrequantSource(
+ kind = "repo",
+ location = "unsloth/Z-Image-Turbo-FP8",
+ filename = "Z-Image-Turbo-FP8.pt",
+ fallback_filename = "transformer_fp8.pt",
+ )
+
+ def _cache(
+ repo_id,
+ filename,
+ cache_dir = None,
+ ):
+ # Only the import-time default holds the legacy file; the live root holds nothing.
+ path = default_root / filename
+ return str(path) if cache_dir is None and path.is_file() else None
+
+ monkeypatch.setattr("huggingface_hub.try_to_load_from_cache", _cache)
+ asked: list = []
+
+ def _download(
+ repo_id,
+ filename,
+ token = None,
+ cache_dir = None,
+ ):
+ asked.append((filename, cache_dir))
+ if filename == "Z-Image-Turbo-FP8.pt":
+ raise EntryNotFoundError("404")
+ return str(legacy) # unchanged upstream: the same blob, revalidated
+
+ monkeypatch.setattr("huggingface_hub.hf_hub_download", _download)
+
+ assert pq._resolve_checkpoint_path(source, None, "/models/live") == str(legacy)
+ # The primary was tried in the live root and 404'd; the legacy was revalidated through the
+ # root that actually holds it, never re-fetched into the live one.
+ assert asked == [("Z-Image-Turbo-FP8.pt", "/models/live"), ("transformer_fp8.pt", None)]
+
+
+def test_a_primary_404_during_revalidation_still_reaches_the_legacy_fallback(monkeypatch, tmp_path):
+ """The other-root revalidation must not swallow the primary's 404: when the live root misses
+ but the import-time root still holds an OLD canonical checkpoint, a blanket catch returns that
+ stale file and the fallback-name branch is never reached."""
+ from huggingface_hub.errors import EntryNotFoundError
+
+ default_root = tmp_path / "default-hub"
+ default_root.mkdir()
+ stale = default_root / "Z-Image-Turbo-FP8.pt"
+ stale.write_bytes(b"obsolete")
+ live = str(tmp_path / "live")
+
+ monkeypatch.setattr(
+ "huggingface_hub.try_to_load_from_cache",
+ lambda repo_id, filename, cache_dir = None, **k: (
+ str(default_root / filename)
+ if cache_dir is None and (default_root / filename).is_file()
+ else None
+ ),
+ )
+ asked: list = []
+
+ def _download(
+ repo_id,
+ filename,
+ token = None,
+ cache_dir = None,
+ ):
+ asked.append((filename, cache_dir))
+ if filename == "Z-Image-Turbo-FP8.pt":
+ raise EntryNotFoundError("404: the repo no longer publishes this name")
+ return str(tmp_path / "fresh-legacy.pt")
+
+ monkeypatch.setattr("huggingface_hub.hf_hub_download", _download)
+
+ assert pq._resolve_checkpoint_path(_other_root_source(), None, live) == str(
+ tmp_path / "fresh-legacy.pt"
+ )
+ # The 404 reached the fallback branch instead of pinning the stale canonical copy.
+ assert asked == [("Z-Image-Turbo-FP8.pt", None), ("transformer_fp8.pt", live)]
+
+
+def test_offline_revalidation_still_returns_the_other_root_copy(monkeypatch, tmp_path):
+ """A LOCAL cache miss is not "absent remotely": huggingface_hub raises LocalEntryNotFoundError
+ (a subclass of EntryNotFoundError on both majors) when it cannot reach the Hub, so telling it
+ apart from a real 404 is what keeps an offline load from dropping the prequant."""
+ from huggingface_hub.errors import LocalEntryNotFoundError
+
+ default_root = tmp_path / "default-hub"
+ default_root.mkdir()
+ ckpt = default_root / "Z-Image-Turbo-FP8.pt"
+ ckpt.write_bytes(b"weights")
+
+ monkeypatch.setattr(
+ "huggingface_hub.try_to_load_from_cache",
+ lambda repo_id, filename, cache_dir = None, **k: (
+ str(default_root / filename)
+ if cache_dir is None and (default_root / filename).is_file()
+ else None
+ ),
+ )
+ asked: list = []
+
+ def _download(
+ repo_id,
+ filename,
+ token = None,
+ cache_dir = None,
+ ):
+ asked.append((filename, cache_dir))
+ raise LocalEntryNotFoundError("offline and not in this root")
+
+ monkeypatch.setattr("huggingface_hub.hf_hub_download", _download)
+
+ assert pq._resolve_checkpoint_path(_other_root_source(), None, "/models/live") == str(ckpt)
+ assert asked == [("Z-Image-Turbo-FP8.pt", None)] # no doomed fallback fetch
+
+
+def test_with_no_fallback_name_a_404_keeps_the_other_root_copy(monkeypatch, tmp_path):
+ """Propagating the 404 only makes sense while another filename is left to try. With none, the
+ copy already located is still the best answer, so revalidation stays a bonus."""
+ from huggingface_hub.errors import EntryNotFoundError
+
+ default_root = tmp_path / "default-hub"
+ default_root.mkdir()
+ ckpt = default_root / "X-FP8.pt"
+ ckpt.write_bytes(b"weights")
+ source = PrequantSource(kind = "repo", location = "unsloth/X-FP8", filename = "X-FP8.pt")
+
+ monkeypatch.setattr(
+ "huggingface_hub.try_to_load_from_cache",
+ lambda repo_id, filename, cache_dir = None, **k: (
+ str(default_root / filename)
+ if cache_dir is None and (default_root / filename).is_file()
+ else None
+ ),
+ )
+ monkeypatch.setattr(
+ "huggingface_hub.hf_hub_download",
+ lambda **k: (_ for _ in ()).throw(EntryNotFoundError("404")),
+ )
+
+ assert pq._resolve_checkpoint_path(source, None, "/models/live") == str(ckpt)
+
+
+def test_load_config_reads_the_same_cache_root_as_the_checkpoint(monkeypatch, tmp_path):
+ """load_config forwards cache_dir to hf_hub_download, so unpinned it reads huggingface_hub's
+ import-time constant. After a mid-session cache change that root may be gone or read-only, and
+ the raise is swallowed into a None return: the prequant is silently dropped."""
+ import torch
+
+ from core.inference import diffusion_prequant as P
+
+ seen: list = []
+ live_root = tmp_path / "live"
+ live_root.mkdir()
+ live = str(live_root)
+ ckpt = live_root / "ck.pt" # the checkpoint came from the LIVE root
+ ckpt.write_bytes(b"x")
+
+ monkeypatch.setattr(P, "_resolve_checkpoint_path", lambda s, t, c = None: str(ckpt))
+ monkeypatch.setattr(P, "_validate_checkpoint", lambda *a, **k: True)
+ monkeypatch.setattr(P, "_pin_kernel_preference", lambda *a, **k: 0)
+ monkeypatch.setattr(torch, "load", lambda *a, **k: {"state_dict": {}, "scheme": "int8"})
+
+ class _Cls:
+ @staticmethod
+ def load_config(
+ base,
+ subfolder = None,
+ token = None,
+ cache_dir = None,
+ ):
+ seen.append(cache_dir)
+ raise RuntimeError("stop right after the config fetch")
+
+ src = P.PrequantSource(kind = "repo", location = "unsloth/X-FP8", filename = "X-FP8.pt")
+ assert (
+ P.load_prequantized_transformer(
+ _Cls,
+ "org/base",
+ src,
+ device = "cpu",
+ dtype = torch.bfloat16,
+ scheme = "int8",
+ cache_dir = live,
+ )
+ is None
+ )
+
+ assert seen[0] == live # the checkpoint's own root is read first
+
+
+def test_the_config_follows_the_checkpoint_into_the_other_cache_root(monkeypatch, tmp_path):
+ """``_resolve_checkpoint_path`` can answer from huggingface_hub's import-time root while Studio
+ pins its live one, so a config pinned to the live root misses in exactly the cache-moved case
+ the checkpoint lookup just accepted -- silently, since the raise becomes a None return and the
+ symptom is a dropped prequant. The config must follow the checkpoint's root, then the other."""
+ import torch
+
+ from core.inference import diffusion_prequant as P
+
+ seen: list = []
+ live = str(tmp_path / "live") # the moved-to root: nothing is cached under it yet
+ other_root = tmp_path / "default-hub"
+ other_root.mkdir()
+ ckpt = other_root / "ck.pt"
+ ckpt.write_bytes(b"x")
+
+ monkeypatch.setattr(P, "_resolve_checkpoint_path", lambda s, t, c = None: str(ckpt))
+ monkeypatch.setattr(P, "_validate_checkpoint", lambda *a, **k: True)
+ monkeypatch.setattr(P, "_pin_kernel_preference", lambda *a, **k: 0)
+ monkeypatch.setattr(torch, "load", lambda *a, **k: {"state_dict": {}, "scheme": "int8"})
+ monkeypatch.setattr(P, "_has_meta_tensors", lambda *a, **k: False)
+ accelerate = types.ModuleType("accelerate")
+ accelerate.init_empty_weights = lambda: contextlib.nullcontext()
+ monkeypatch.setitem(sys.modules, "accelerate", accelerate)
+
+ class _Transformer:
+ def load_state_dict(self, *a, **k):
+ return None
+
+ def to(self, device):
+ return self
+
+ def eval(self):
+ return self
+
+ class _Cls:
+ @staticmethod
+ def load_config(
+ base,
+ subfolder = None,
+ token = None,
+ cache_dir = None,
+ ):
+ seen.append(cache_dir)
+ if cache_dir is not None:
+ raise OSError("the live root has no cached config for this base")
+ return {"ok": True}
+
+ @staticmethod
+ def from_config(config):
+ return _Transformer()
+
+ src = P.PrequantSource(kind = "repo", location = "unsloth/X-FP8", filename = "X-FP8.pt")
+ out = P.load_prequantized_transformer(
+ _Cls,
+ "org/base",
+ src,
+ device = "cpu",
+ dtype = torch.bfloat16,
+ scheme = "int8",
+ cache_dir = live,
+ )
+
+ assert isinstance(out, _Transformer) # the prequant loaded instead of being dropped
+ assert seen == [None] # read straight through the root that supplied the checkpoint
diff --git a/studio/backend/tests/test_diffusion_routes.py b/studio/backend/tests/test_diffusion_routes.py
index 87cded610e6..0578568288e 100644
--- a/studio/backend/tests/test_diffusion_routes.py
+++ b/studio/backend/tests/test_diffusion_routes.py
@@ -65,6 +65,10 @@ class _FakeBackend:
raise ValueError(f"Could not infer a diffusion family for '{model_path}'.")
return fam
+ def preflight_base_access(self, model_path, fam, **kwargs):
+ # The real backends probe the Hub for a gated companion here; the fake clears every pick.
+ return None
+
def begin_load(self, model_path, **kwargs):
# The real backend loads on a thread; the fake completes instantly.
self.loaded = True
@@ -168,6 +172,9 @@ def client(monkeypatch, tmp_path):
"get_active_diffusion_engine",
lambda: diffusion_module.get_diffusion_backend(),
)
+ # The load route predicts the engine before selection (to preflight it before any unload); left
+ # real it reaches the host's binaries and, on a GPU-less runner, the live sd.cpp backend.
+ monkeypatch.setattr(engine_router, "predict_engine", lambda fam, **kw: "diffusers")
monkeypatch.setattr(engine_router, "_active_engine_name", "diffusers")
monkeypatch.setattr(engine_router, "_fallback_reason", None)
# Isolate from the real GPU arbiter: reset ownership and stub the evictors so acquire_for() never touches live singletons.
@@ -628,6 +635,212 @@ def test_load_validation_failure_does_not_evict_chat(client, monkeypatch):
assert gpu_arbiter.current_owner() == gpu_arbiter.CHAT
+def test_gated_base_load_returns_400_without_evicting_chat(client, monkeypatch):
+ # The images page falls back to /images/load whenever the download plan fails, so the plan's
+ # gated-base refusal alone is not enough: run here BEFORE acquire_for, or the pick the plan
+ # already rejected tears down the loaded chat model and only then reports the same message.
+ import types as _types
+
+ import core.inference.diffusion_device as devmod
+
+ monkeypatch.setattr(gpu_arbiter, "_owner", gpu_arbiter.CHAT)
+ evicted = []
+ monkeypatch.setitem(gpu_arbiter._EVICTORS, gpu_arbiter.CHAT, lambda: evicted.append(True))
+ # The arbiter is only taken for a non-CPU load, which is exactly where an eviction is at stake.
+ monkeypatch.setattr(
+ devmod, "resolve_diffusion_device_target", lambda: _types.SimpleNamespace(device = "cuda")
+ )
+ backend = diffusion_module.get_diffusion_backend()
+ detail = (
+ "'black-forest-labs/FLUX.1-dev' is gated on Hugging Face and this model cannot be "
+ "downloaded without it."
+ )
+
+ def _refuse(model_path, fam, **kwargs):
+ raise ValueError(detail)
+
+ monkeypatch.setattr(backend, "preflight_base_access", _refuse, raising = False)
+
+ resp = client.post(
+ "/api/inference/images/load",
+ json = {"model_path": "unsloth/Z-Image-Turbo-GGUF", "gguf_filename": "q.gguf"},
+ )
+
+ assert resp.status_code == 400
+ assert resp.json()["detail"] == detail
+ assert evicted == [] # chat backend was never evicted
+ assert gpu_arbiter.current_owner() == gpu_arbiter.CHAT
+ assert backend.is_loaded is False # and the refused load never started
+
+
+def test_cpu_load_skips_the_gated_preflight(client, monkeypatch):
+ # No arbiter handoff on a CPU host means no eviction to protect, so the route must not pay the
+ # preflight's Hub round-trips there: the loader's own copy still catches the gated base.
+ import types as _types
+
+ import core.inference.diffusion_device as devmod
+
+ monkeypatch.setattr(
+ devmod, "resolve_diffusion_device_target", lambda: _types.SimpleNamespace(device = "cpu")
+ )
+ backend = diffusion_module.get_diffusion_backend()
+ calls: list = []
+ monkeypatch.setattr(
+ backend,
+ "preflight_base_access",
+ lambda *a, **k: calls.append(a),
+ raising = False,
+ )
+
+ resp = client.post(
+ "/api/inference/images/load",
+ json = {"model_path": "unsloth/Z-Image-Turbo-GGUF", "gguf_filename": "q.gguf"},
+ )
+
+ assert resp.status_code == 200
+ assert calls == []
+
+
+def test_a_cpu_mispredicted_engine_is_still_preflighted(monkeypatch):
+ """predict_engine never installs, so a host where the sd-cli install then fails lands on the
+ OTHER engine, and the preflight ran against the one that was never activated.
+
+ The GPU path always re-asked the engine it actually got. The CPU path did not, so a mispredict
+ there switched engines and started the load with the diffusers companions unread -- the bare
+ mid-download token error this preflight exists to replace."""
+ from types import SimpleNamespace
+
+ import core.inference.diffusion_device as devmod
+ import core.inference.diffusion_engine_router as engine_router
+ import core.inference.sd_cpp_backend as sd_backend
+ from core.inference.sd_cpp_engine import ENGINE_DIFFUSERS, ENGINE_SD_CPP
+
+ # Native is unavailable, so the selection lands on diffusers however the prediction went.
+ monkeypatch.setenv("UNSLOTH_DIFFUSION_SD_CPP", "0")
+ monkeypatch.delenv("UNSLOTH_DIFFUSION_ENGINE", raising = False)
+ monkeypatch.setattr(engine_router, "_active_engine_name", ENGINE_DIFFUSERS)
+ monkeypatch.setattr(engine_router, "_fallback_reason", None)
+ # ...but the prediction says native, so a preflight is owed and it is owed on the wrong engine.
+ monkeypatch.setattr(engine_router, "predict_engine", lambda fam, **_: ENGINE_SD_CPP)
+
+ native = _FakeBackend()
+ monkeypatch.setattr(sd_backend, "get_sd_cpp_backend", lambda: native)
+
+ detail = (
+ "'black-forest-labs/FLUX.1-dev' is gated on Hugging Face and this model cannot be "
+ "downloaded without it."
+ )
+
+ def _refuse(model_path, fam, **kwargs):
+ raise ValueError(detail)
+
+ diffusers = _FakeBackend()
+ diffusers.preflight_base_access = _refuse
+ monkeypatch.setattr(diffusion_module, "get_diffusion_backend", lambda: diffusers)
+ monkeypatch.setattr(
+ engine_router,
+ "resolve_diffusion_device_target",
+ lambda: SimpleNamespace(backend = "cpu", device = "cpu"),
+ )
+ monkeypatch.setattr(
+ devmod, "resolve_diffusion_device_target", lambda: SimpleNamespace(device = "cpu")
+ )
+
+ app = FastAPI()
+ app.include_router(studio_router, prefix = "/api/inference")
+ app.dependency_overrides[get_current_subject] = lambda: "test-user"
+ local = TestClient(app)
+
+ resp = local.post(
+ "/api/inference/images/load",
+ json = {"model_path": "unsloth/Z-Image-Turbo-GGUF", "gguf_filename": "q.gguf"},
+ )
+
+ assert resp.status_code == 400
+ assert resp.json()["detail"] == detail
+ assert diffusers.loaded is False # the refused load never started
+
+
+ "device, env",
+ [("cuda", {}), ("cpu", {"UNSLOTH_DIFFUSION_SD_CPP": "0"})],
+)
+def test_gated_pick_on_an_engine_switch_keeps_the_previous_model(monkeypatch, device, env):
+ """The refusal must precede the engine switch, not follow it.
+
+ Activating the other engine unloads the deactivated one, so a preflight that ran after the
+ selection destroyed the resident image model and only then reported the gated repo -- exactly
+ the eviction this check exists to prevent. The CPU case has no GPU handoff at all, so there the
+ switch is the only thing at stake.
+ """
+ from types import SimpleNamespace
+
+ import core.inference.diffusion_device as devmod
+ import core.inference.diffusion_engine_router as engine_router
+ import core.inference.sd_cpp_backend as sd_backend
+ from core.inference.sd_cpp_engine import ENGINE_SD_CPP
+
+ for e in (
+ "UNSLOTH_DIFFUSION_ENGINE",
+ "UNSLOTH_DIFFUSION_SD_CPP",
+ "UNSLOTH_DIFFUSION_SD_CPP_MPS",
+ "UNSLOTH_DIFFUSION_SD_CPP_INSTALL",
+ ):
+ monkeypatch.delenv(e, raising = False)
+ for name, value in env.items():
+ monkeypatch.setenv(name, value)
+
+ # A native model is resident; this pick routes to diffusers, so the REAL router switches engines.
+ resident = _FakeBackend()
+ resident.loaded = True
+ monkeypatch.setattr(sd_backend, "get_sd_cpp_backend", lambda: resident)
+ monkeypatch.setattr(engine_router, "_active_engine_name", ENGINE_SD_CPP)
+ monkeypatch.setattr(engine_router, "_fallback_reason", None)
+
+ detail = (
+ "'black-forest-labs/FLUX.1-dev' is gated on Hugging Face and this model cannot be "
+ "downloaded without it."
+ )
+
+ def _refuse(model_path, fam, **kwargs):
+ raise ValueError(detail)
+
+ diffusers = _FakeBackend()
+ diffusers.preflight_base_access = _refuse
+ monkeypatch.setattr(diffusion_module, "get_diffusion_backend", lambda: diffusers)
+ monkeypatch.setattr(
+ engine_router,
+ "resolve_diffusion_device_target",
+ lambda: SimpleNamespace(backend = device, device = device),
+ )
+ monkeypatch.setattr(
+ devmod, "resolve_diffusion_device_target", lambda: SimpleNamespace(device = device)
+ )
+ monkeypatch.setattr(gpu_arbiter, "_owner", gpu_arbiter.CHAT)
+ evicted: list = []
+ monkeypatch.setitem(gpu_arbiter._EVICTORS, gpu_arbiter.CHAT, lambda: evicted.append(True))
+ monkeypatch.setitem(gpu_arbiter._EVICTORS, gpu_arbiter.DIFFUSION, lambda: None)
+
+ app = FastAPI()
+ app.include_router(studio_router, prefix = "/api/inference")
+ app.dependency_overrides[get_current_subject] = lambda: "test-user"
+ local = TestClient(app)
+
+ resp = local.post(
+ "/api/inference/images/load",
+ json = {"model_path": "unsloth/Z-Image-Turbo-GGUF", "gguf_filename": "q.gguf"},
+ )
+
+ assert resp.status_code == 400
+ assert resp.json()["detail"] == detail
+ # Refused before the switch: the native engine still holds its model and is still the active one.
+ assert resident.loaded is True
+ assert engine_router.active_engine_name() == ENGINE_SD_CPP
+ assert diffusers.loaded is False # and the refused load never started
+ assert evicted == []
+ assert gpu_arbiter.current_owner() == gpu_arbiter.CHAT
+
+
def test_load_refused_during_training_does_not_evict_chat(client, monkeypatch):
# An image load while training is active is refused (409) before the GPU is taken.
import core.training as core_training
@@ -1062,6 +1275,38 @@ def test_download_plan_forwards_the_load_time_controls(client, monkeypatch):
assert len(seen["loras"] or []) == 1
+def test_download_plan_surfaces_a_gated_base_as_a_400(client, monkeypatch):
+ # The planner's ValueError has to reach the UI intact: the repo id and licence URL are the fix.
+ from core.inference import diffusion_engine_router as router
+ from core.inference.sd_cpp_engine import ENGINE_DIFFUSERS
+
+ monkeypatch.setattr(router, "predict_engine", lambda fam, **_: ENGINE_DIFFUSERS)
+ backend = diffusion_module.get_diffusion_backend()
+ detail = (
+ "'black-forest-labs/FLUX.1-dev' is gated on Hugging Face and this model cannot be "
+ "downloaded without it. Accept its licence at "
+ "https://huggingface.co/black-forest-labs/FLUX.1-dev, then add a Hugging Face token "
+ "that has access in Studio settings and try again."
+ )
+
+ def _plan(model_path, **kwargs):
+ raise ValueError(detail)
+
+ monkeypatch.setattr(backend, "download_plan", _plan, raising = False)
+
+ resp = client.post(
+ "/api/inference/images/download-plan",
+ json = {
+ "model_path": "unsloth/FLUX.1-dev-GGUF",
+ "gguf_filename": "flux1-dev-Q4_K_M.gguf",
+ "model_kind": "gguf",
+ },
+ )
+
+ assert resp.status_code == 400
+ assert resp.json()["detail"] == detail
+
+
def test_download_plan_uses_the_engine_the_load_will_pick(client, monkeypatch):
# On a host with no usable GPU a GGUF pick routes to native sd.cpp, which reads single-file assets and never opens the base
# repo's sharded components. Planning with diffusers there staged GB the load discards and pulled the rest inline.
diff --git a/studio/backend/utils/hf_xet_fallback.py b/studio/backend/utils/hf_xet_fallback.py
index 9b7c4b82a21..859b02904ba 100644
--- a/studio/backend/utils/hf_xet_fallback.py
+++ b/studio/backend/utils/hf_xet_fallback.py
@@ -562,12 +562,39 @@ def hf_hub_download_with_xet_fallback(
on_status: Optional[Callable[[str], None]] = None,
force_download: bool = False,
cache_dir: Optional[str] = None,
+ reuse_other_cache_root: bool = False,
) -> str:
"""Single-file download via the shared fallback with Unsloth's marker-aware HTTP-retry prep.
- ``force_download`` re-fetches a newer blob over a cached one (Unsloth's model-update path)."""
+ ``force_download`` re-fetches a newer blob over a cached one (Unsloth's model-update path).
+
+ ``reuse_other_cache_root`` (opt-in) lets a file cached ONLY under huggingface_hub's import-time
+ root resolve through that root instead of being re-fetched into the live one. Studio's cache
+ folder is a setting, so after it changes every asset already on disk is invisible to a call
+ pinned to the new root: multiple GB re-download, and for a gated base with no valid token the
+ pull 401s even though the bytes are right there, on a load the preflight (which looks in BOTH
+ roots) already cleared. Reached THROUGH the other root rather than by returning the raw path,
+ so the ref still resolves and a republished file is picked up; the blob is reused, and
+ offline/401 hf_hub_download keeps the failed HEAD and serves the cached pointer. Off for
+ ``force_download``, whose whole point is to re-fetch."""
if cache_dir is None:
from utils.hf_cache_settings import get_hf_cache_paths
cache_dir = str(get_hf_cache_paths().hub_cache)
+ if reuse_other_cache_root and not force_download and cache_dir is not None:
+ try:
+ from huggingface_hub import try_to_load_from_cache
+
+ # Only a str is a cached path; a miss is None and a known-absent file is a sentinel.
+ here = try_to_load_from_cache(
+ repo_id, filename, repo_type = repo_type, revision = revision, cache_dir = cache_dir
+ )
+ if not isinstance(here, str):
+ elsewhere = try_to_load_from_cache(
+ repo_id, filename, repo_type = repo_type, revision = revision, cache_dir = None
+ )
+ if isinstance(elsewhere, str) and Path(elsewhere).is_file():
+ cache_dir = None
+ except Exception: # noqa: BLE001 — a cache we cannot read just keeps the live root
+ pass
# Omit rather than forward None: an older unsloth_zoo hands `interval` straight to Event.wait(),
# where None blocks forever and a hung Xet download never falls back. Omitting also lets the
# shared layer pick its per-transport defaults.