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.

Tighten the gated-base preflight comments (#8003)

Daniel Han012f709fa0aa
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.py
index 014926914df..fd3eb6e7f0a 100644
--- a/studio/backend/core/inference/diffusion.py
+++ b/studio/backend/core/inference/diffusion.py
@@ -434,8 +434,8 @@ 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."""
+ """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 (
@@ -458,29 +458,28 @@ def _assert_base_repo_accessible(
"""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."""
+ a plan built from it dies mid-download on a bare token error. Probes ``probe_file`` (fetched by
+ the load anyway) only when ``gated`` is set, so an open repo costs one metadata call; the native
+ plan passes its own asset name, as 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 living only under
+ huggingface_hub's import-time root, so the caller can load off disk: ``from_pretrained`` is
+ pinned to ``hub_cache_dir()`` and cannot see it, and the failure that earned the escape also
+ empties the size estimate. None otherwise."""
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.
+ # Blank to None, as load_pipeline does: build_hf_headers sends "" 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.
+ # OSError: invalid path characters -> a remote id. RuntimeError: pathlib raises it, not OSError,
+ # when expanduser() cannot resolve the home dir ('~other/models', or '~/models' with no HOME).
+ # Both carry one slash, so they reach here, and an escape would 500 this fail-open probe.
except (OSError, RuntimeError, ValueError):
pass
try:
@@ -493,23 +492,20 @@ def _assert_base_repo_accessible(
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.
+ # Set when only the import-time root holds the excusing copy, which the pinned from_pretrained
+ # would miss.
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.
+ # A base already on disk needs no Hub access: 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.
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."""
+ prefetch writes 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 still 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
@@ -517,9 +513,8 @@ def _assert_base_repo_accessible(
# 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.
+ # The live root is tried first, so root None means only the import-time one has
+ # it. Its parent is the snapshot dir only for a top-level probe.
if root is None and "/" not in probe_file:
other_root_snapshot = str(Path(hit).parent)
return True
@@ -528,12 +523,10 @@ def _assert_base_repo_accessible(
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."""
+ """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 the very case this probe exists to catch."""
status = getattr(getattr(exc, "response", None), "status_code", None)
return status in (401, 403)
@@ -545,10 +538,8 @@ def _assert_base_repo_accessible(
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.
+ # with a missing repo because "401 is misleading" (_http.py), so re-read the status. A
+ # 401/403 earns the cache escape; a genuine 404, or an error carrying no response, raises.
if _is_auth_error(exc) and _already_downloaded():
return other_root_snapshot
raise ValueError(_repo_access_message(repo, gated = False)) from None
@@ -561,7 +552,7 @@ def _assert_base_repo_accessible(
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.
+ # prefetch resolves each through whichever root holds it.
if not gated or _already_downloaded():
return None
try:
@@ -725,9 +716,9 @@ 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."""
+ /images/download-plan passes ``LoraSpec`` models, whose unpacking yields ``(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:
@@ -751,13 +742,12 @@ def _uncached_prequant_repo(
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).
+ """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."""
+ instead. 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)
@@ -838,20 +828,18 @@ class DiffusionBackend:
return str(resolve_local_gguf_child(local_root, gguf_filename))
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%.
+ # Pin the LIVE root, as the prefetch does: unpinned, a mid-session cache change misses the
+ # staged GGUF 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.
+ # Best-effort: an unreadable cache raises here, and letting that escape would abort a 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
+ # Same other-root reuse as the pre-quant checkpoint, 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():
@@ -902,8 +890,7 @@ class DiffusionBackend:
# 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.
+ # Active weights only: disagreeing with the load stages shards it never reads.
and not _has_active_lora(kwargs.get("loras"))
and _uncached_prequant_repo(
fam,
@@ -922,8 +909,7 @@ class DiffusionBackend:
requested = mode,
base_repo = kwargs.get("base_repo"),
prequant_path = kwargs.get("transformer_prequant_path"),
- # Same rule as the decline above: an all-zero list bakes nothing, so sizing it
- # dense stages transformer/ shards the load will not read.
+ # An all-zero list bakes nothing; sizing it dense stages shards the load never reads.
force_dense = _has_active_lora(kwargs.get("loras")),
logger = None,
)
@@ -975,10 +961,10 @@ 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.
+ # 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.
# 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(
@@ -991,9 +977,8 @@ class DiffusionBackend:
# 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.
+ # cache can serve the manifest from the old root while companions land in the live one, and
+ # returning that snapshot would point from_pretrained at a tree missing the rest.
roots: set[str] = set()
for rfilename in base_files:
if cancel.is_set():
@@ -1001,9 +986,8 @@ class DiffusionBackend:
local = hf_hub_download_with_xet_fallback(
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.
+ # 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 follows the symlink into blobs/.
try:
root = str(Path(local).parents[len(Path(rfilename).parts) - 1])
except (IndexError, ValueError, OSError):
@@ -1011,8 +995,8 @@ class DiffusionBackend:
roots.add(root)
if rfilename == "model_index.json":
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.
+ # Only hand back a snapshot the whole set lives in; otherwise the hub id resolves each file
+ # through its own root as before.
if snapshot_root is not None and roots != {snapshot_root}:
return None
return snapshot_root
@@ -1138,24 +1122,19 @@ class DiffusionBackend:
``_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."""
+ page falls back to /images/load on ANY plan failure. 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. 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.
+ # Probe the repo the load will FETCH from: refusing the upstream id would reject the gated
+ # picks the ungated mirror rescues, and the swap is pure, so it decides the same here as on
+ # the load thread. Only the raise matters; _run_load recomputes the excused snapshot.
_assert_base_repo_accessible(prefer_ungated_mirror(base, hf_token), hf_token)
# ── Background load + progress ─────────────────────────────────────────
@@ -1276,12 +1255,10 @@ class DiffusionBackend:
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.
+ # Runs on ``fetch_base``, once it is decided, so it probes the repo the pull will read:
+ # refusing the upstream id would reject the gated picks the ungated mirror rescues.
+ # Everything above is metadata, so no byte has moved yet. Returns a snapshot dir when it
+ # excused the base off a copy only the import-time root holds.
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).
@@ -1290,10 +1267,9 @@ 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.
- # 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.
+ # The carried snapshot is the fallback, never the override: it fires only when the
+ # estimate came back empty, since the metadata that fills it is the same call whose
+ # failure earned the escape. Without it the load 401s with every byte already on disk.
kwargs["_base_local_dir"] = (
self._prefetch_files(
kwargs["repo_id"],
@@ -1545,9 +1521,8 @@ class DiffusionBackend:
)
# 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.
+ # mid-download. Probing any id but 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]] = []
@@ -1599,12 +1574,11 @@ class DiffusionBackend:
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."""
+ cache-folder change the bytes the load reads are not in the live root at all and sizing that
+ root alone reads zero. 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.
+ # thread, so a second read could compare the new root against a `live` built from the old.
live_root = hub_cache_dir()
folder = f"models--{repo_id.replace('/', '--')}"
live = Path(live_root) / folder
@@ -1615,9 +1589,8 @@ class DiffusionBackend:
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.
+ # normcase/normpath before comparing: on Windows the two roots can differ by case alone and
+ # every caller below would walk the same tree twice. Best-effort; both readers are idempotent.
if os.path.normcase(os.path.normpath(other)) == os.path.normcase(
os.path.normpath(live_root)
):
@@ -1628,18 +1601,16 @@ class DiffusionBackend:
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_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.
+ 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 read 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.
+ # A ref file holds a bare commit hash; a separator would join out of the cache.
if not rev or rev in (".", "..") or "/" in rev or "\\" in rev:
return None
snapshot = repo_dir / "snapshots" / rev
@@ -1650,17 +1621,15 @@ class DiffusionBackend:
"""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."""
+ append-only: a republished repo keeps the superseded revision's blobs forever under
+ different etags, so summing the whole dir 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: those are this download's own bytes, and
+ dropping them 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 a
+ copy present in both roots counts once. Scanning only the live root reports 0 for a load a
+ moved cache serves entirely off disk, pinning the progress bar near 0%."""
sizes: dict[str, int] = {}
def _add(key: str, path: Path) -> None:
@@ -1690,10 +1659,9 @@ class DiffusionBackend:
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/.
+ # revision, so a republished file summed both copies and could report
+ # finalizing at 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
@@ -1745,24 +1713,22 @@ class DiffusionBackend:
``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."""
+ (the snapshot the prefetch/preflight handed back). Both roots, because the loader's per-file
+ root reuse makes them disjoint PARTS of one repo rather than copies: 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 -- under-counting leaves an auto plan resident and OOMing on
+ weights it never counted. Keying on the relative path keeps genuine copies safe too (a file
+ mirrored in two roots still counts once, at its largest) and makes the staged dir purely
+ additive, so a partial snapshot cannot erase what a root does hold."""
local = Path(base).expanduser()
if local.is_dir():
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.
+ # One revision per root, the one it serves: the merge is per FILE, so a superseded
+ # revision whose shards were repacked would count both namings and force offload on a
+ # base that fits. 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)
@@ -1987,8 +1953,7 @@ class DiffusionBackend:
# 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.
+ # behaviour, where the prequant IS the point. An all-zero-weight list is not a bake.
baking_loras = _has_active_lora(loras)
if kind == "gguf" and transformer_quant_auto and not baking_loras:
uncached_prequant = _uncached_prequant_repo(
@@ -2091,10 +2056,9 @@ class DiffusionBackend:
else None
)
# 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.
+ # was swapped in) and carries the staged snapshot: a base served wholly from
+ # the import-time root sizes as 0 on the hub id alone, and a 0 skips this
+ # fit check, landing the dense build under a GGUF-sized plan.
dense_mib = int(
self._dense_transformer_resident_bytes(fetch_base, _base_local_dir)
// (1024 * 1024)
@@ -2652,8 +2616,7 @@ class DiffusionBackend:
raise RuntimeError("transformer quant unsupported for this device/scheme")
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.
+ # prequant. Active weights only: an all-zero list bakes nothing.
source = resolve_prequant_source(
fam, scheme, path_override = prequant_path, base_repo = base
)
@@ -2698,11 +2661,10 @@ class DiffusionBackend:
"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.
+ # terminal (_get_model_file raises rather than falling back to the hub) and a sharded load
+ # raises per missing shard, so a partial snapshot 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",
@@ -2868,12 +2830,11 @@ 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.
+ ``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: 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
@@ -2885,14 +2846,12 @@ class DiffusionBackend:
# 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.
+ # The bytes land under the repo they were STAGED from, so scan the mirror when there is
+ # one: an upstream id whose cache is empty folds the whole pipeline to zero.
cache_repo = fetch_base or repo_id
- # 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.
+ # Largest of every source the load can read this repo from: a staged snapshot can sit
+ # under the OTHER root, and a prefetch that split the repo across roots hands back none
+ # at all, so 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()
@@ -2943,10 +2902,9 @@ 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:
- # 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).
+ # 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.
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
diff --git a/studio/backend/core/inference/diffusion_engine_router.py b/studio/backend/core/inference/diffusion_engine_router.py
index 6c7ce4d549d..4fe95c47968 100644
--- a/studio/backend/core/inference/diffusion_engine_router.py
+++ b/studio/backend/core/inference/diffusion_engine_router.py
@@ -74,10 +74,8 @@ def _engine_config() -> tuple[str, str, bool]:
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."""
+ """The engine object a name refers to, WITHOUT activating it: activating unloads the resident
+ model, so /images/load's gated-repo preflight needs the pending engine before the switch."""
if name == ENGINE_SD_CPP:
from core.inference.sd_cpp_backend import get_sd_cpp_backend
return get_sd_cpp_backend()
diff --git a/studio/backend/core/inference/diffusion_prequant.py b/studio/backend/core/inference/diffusion_prequant.py
index 27778d95835..6ede53b94c0 100644
--- a/studio/backend/core/inference/diffusion_prequant.py
+++ b/studio/backend/core/inference/diffusion_prequant.py
@@ -167,9 +167,8 @@ def cached_checkpoint_path(source: Any, *, cache_dir: Optional[str] = None) -> O
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.
+ not short-circuit it, or a stale name stays pinned once the repo ships the real one, 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."""
@@ -262,7 +261,7 @@ def load_prequantized_transformer(
``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.
+ into a root Studio no longer reads.
Returns the placed transformer, or None on any problem (missing / mismatched /
unreadable checkpoint, or unsupported meta-init) so the caller falls back to
@@ -297,10 +296,9 @@ def load_prequantized_transformer(
state_dict = ckpt["state_dict"]
_pin_kernel_preference(state_dict, logger)
- # 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.
+ # Read from the root that actually supplied the checkpoint: 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
@@ -339,10 +337,9 @@ def load_prequantized_transformer(
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."""
+ On 1.x the base splits into a remote 404 and ``LocalEntryNotFoundError`` (no copy in this root,
+ no network); on BOTH majors local subclasses the base, so catch it first where they differ.
+ Private markers on an unexpected layout are raised by nothing, keeping today's behaviour."""
try:
from huggingface_hub.errors import EntryNotFoundError
except Exception: # noqa: BLE001 — older/newer hub layouts
@@ -370,17 +367,13 @@ def _download_checkpoint_name(
) -> 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,
+ Pinned to ``cache_dir``, hf_hub_download would not look there and would re-fetch multiple GB, so
+ re-run it THROUGH that root rather than return the raw path: the blob is reused after 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."""
+ 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. 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."""
from huggingface_hub import hf_hub_download
EntryNotFoundError, LocalEntryNotFoundError = _entry_not_found_errors()
@@ -439,8 +432,7 @@ def _resolve_checkpoint_path(
except EntryNotFoundError:
if not has_fallback:
raise
- # The primary is genuinely absent, so the legacy name gets the same other-root
- # treatment, with nothing left to fall back to.
+ # Primary genuinely absent: same other-root treatment, with nothing left after it.
return _download_checkpoint_name(
source,
source.fallback_filename,
@@ -454,18 +446,17 @@ def _resolve_checkpoint_path(
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."""
+ ``_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."""
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.
+ # normcase before comparing: on Windows C:\Users vs c:\users would read as "not under the
+ # live root" and silently reverse 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)
diff --git a/studio/backend/core/inference/sd_cpp_backend.py b/studio/backend/core/inference/sd_cpp_backend.py
index b0c4400f0ff..7ec84d847e4 100644
--- a/studio/backend/core/inference/sd_cpp_backend.py
+++ b/studio/backend/core/inference/sd_cpp_backend.py
@@ -548,10 +548,9 @@ 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.
+ # Same preflight the plan runs, on POST-swap repos: catch a gated companion here, not
+ # 15 GiB into the prefetch, without refusing one an ungated mirror stands in for. The
+ # plan alone is not enough: the images page falls back to this load when it fails.
self._preflight_companion_repos(
self._assets_by_repo(assets), fetch_repo.get(repo_id, repo_id), hf_token
)
@@ -712,8 +711,8 @@ 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.
+ # AFTER the swap: preflighting the upstream id would refuse the very picks the ungated
+ # mirror exists to rescue.
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]] = []
@@ -759,16 +758,14 @@ class SdCppDiffusionBackend:
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."""
+ error this replaces. 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."""
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.
+ # Companions only: 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.
+ # Probe an asset THIS pick stages: a VAE-only repo 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(
@@ -783,15 +780,12 @@ class SdCppDiffusionBackend:
) -> 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."""
+ 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 checkpoint name."""
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.
+ # Post-swap, as the plan and the load are: the swap is pure, so all three decide alike.
specs = self._asset_specs(repo_id, gguf_filename, fam)
fetch_repo = _fetch_repo_map(specs, hf_token)
self._preflight_companion_repos(
@@ -884,10 +878,9 @@ class SdCppDiffusionBackend:
if kind == "diffusion_model" and local_root.exists():
path = str(resolve_local_gguf_child(local_root, fn))
else:
- # 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.
+ # Resolve an asset cached only under huggingface_hub's import-time root through
+ # that root, as the preflight does. Pinned to the live root, a cache-folder change
+ # re-downloads every moved asset and 401s on an already-downloaded gated base.
path = hf_hub_download_with_xet_fallback(
repo, fn, hf_token, cancel_event = cancel, reuse_other_cache_root = True
)
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 6328ae9a7d0..54b71267946 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -19022,13 +19022,13 @@ 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.
+ # Take the GPU from chat only on a non-CPU device: gate on the device, not the engine name.
+ # Pure resolve, so it can run 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).
+ # Gated/unreadable-companion refusal, asked of ONE engine (they check different repos).
return target.preflight_base_access(
request.model_path,
fam,
@@ -19039,12 +19039,11 @@ async def load_diffusion_model(
)
# 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.
+ # plan checks the same, but the images page falls back to THIS route when that call fails,
+ # and the loader's own copy runs after acquire_for already evicted chat. Must precede
+ # selection too: activating the other engine unloads the current one, so a pick refused
+ # afterwards destroys the model this preserves. 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
@@ -19058,13 +19057,11 @@ async def load_diffusion_model(
engine = await asyncio.to_thread(
select_and_activate_engine, fam, hf_token = request.hf_token, model_kind = kind
)
- # 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.
+ # predict_engine is selection's read-only twin: it never installs, so a host whose sd-cli
+ # install then fails lands on the OTHER engine. Re-ask the engine actually activated when
+ # the prediction missed, so neither the GPU handoff nor the load runs on an unread
+ # companion; a correct prediction already made this call, so it is never paid twice. Runs
+ # on the CPU path too when a preflight was owed there, since the switch is what is at stake.
if (needs_gpu or preflighted is not None) and engine is not preflighted:
await asyncio.to_thread(_preflight, engine)
diff --git a/studio/backend/tests/test_diffusion_backend.py b/studio/backend/tests/test_diffusion_backend.py
index 74ac703cf72..a90ddb50b16 100644
--- a/studio/backend/tests/test_diffusion_backend.py
+++ b/studio/backend/tests/test_diffusion_backend.py
@@ -2010,10 +2010,9 @@ def test_begin_load_rejects_concurrent(monkeypatch):
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.
+ # 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 and then runs the REAL load_pipeline
+ # inside whatever test is current, under that test's patches.
for thread in set(threading.enumerate()) - before:
thread.join(timeout = 5)
@@ -3153,9 +3152,8 @@ def test_dense_quant_prequant_proceeds_but_forbids_dense_fallback(
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. Counting every
- # instance lets that stray thread land in this assertion.
+ # Scoped to this backend: begin_load runs on a daemon thread and _plan_memory is patched
+ # on the CLASS, so counting every instance lets a stray load 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.
@@ -3619,9 +3617,8 @@ def test_dense_quant_unusable_prequant_path_runs_dense_refit(fake_runtime, tmp_p
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. Counting every
- # instance is what made this assert [True, True] on the slower CI runners.
+ # Scoped to this backend: begin_load runs on a daemon thread and _plan_memory is patched
+ # on the CLASS, so counting every instance asserted [True, True] on 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)
@@ -3964,9 +3961,8 @@ def test_a_baked_lora_load_is_unaffected_by_the_prequant_cache(fake_runtime, tmp
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.
+ # 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
@@ -4000,9 +3996,8 @@ def test_the_dense_builder_skips_the_prequant_only_for_a_real_bake(
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.
+ # The candidate sizing 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()
@@ -4024,9 +4019,9 @@ def test_the_plan_does_not_force_a_dense_bake_for_disabled_adapters(fake_runtime
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.
+ # /images/load sends (id, weight) tuples but /images/download-plan passes LoraSpec models,
+ # whose unpacking 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
@@ -4054,8 +4049,8 @@ def test_the_plan_reads_pydantic_lora_specs_as_the_load_reads_tuples(fake_runtim
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.
+ # stages transformer/ shards for a load that runs 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()
@@ -4174,12 +4169,10 @@ def _split_cache_roots(
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."""
+ left behind, both empty. ``register_root`` makes the second dir huggingface_hub's import-time
+ constant, the root ``cache_dir = None`` resolves to; without it the constant points at a third
+ empty dir, so ``other`` is reachable only as an explicit staged snapshot. 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
@@ -4251,9 +4244,8 @@ def _other_root_base_snapshot(
*,
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."""
+ """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, handed back as ``_base_local_dir``. Sparse."""
_live, other = _split_cache_roots(tmp_path, monkeypatch, register_root = register_root)
snapshot = other / "models--bfl--base" / "snapshots" / ("a" * 40)
for rel, mib in (
@@ -4285,9 +4277,9 @@ def _small_card(monkeypatch):
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.
+ # _companion_cache_bytes resolves a hub id under hub_cache_dir() ONLY, so a base served from
+ # the import-time root budgets as zero while from_pretrained loads it off that snapshot: the
+ # 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)
@@ -4324,8 +4316,8 @@ def test_plan_memory_budgets_companions_from_the_other_root_snapshot(monkeypatch
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.
+ # the live root's blobs, so a repo served from the other root sizes as unknown and a 4 GiB
+ # pipeline that does not fit stays resident.
from core.inference.diffusion_memory import OFFLOAD_MODEL, OFFLOAD_NONE
snapshot = _other_root_base_snapshot(tmp_path, monkeypatch)
@@ -4350,9 +4342,8 @@ def test_plan_memory_sizes_a_pipeline_load_from_the_other_root_snapshot(monkeypa
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.
+ # Same floor rule for the companion total: the preflight's snapshot can hold the manifest
+ # alone, so preferring it over the hub-id scan budgets 0 for the companions a root does hold.
from core.inference.diffusion_memory import OFFLOAD_GROUP
snapshot = _other_root_base_snapshot(tmp_path, monkeypatch, register_root = True)
@@ -4382,10 +4373,9 @@ def test_plan_memory_keeps_companions_a_partial_staged_snapshot_omits(monkeypatc
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
+ # After a cache-folder change the multi-GB checkpoint can be served 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".
+ # against a nonzero estimate, so the UI shows a healthy load stalled near 0% throughout.
from core.inference.diffusion import _LoadingState
live, other = _split_cache_roots(tmp_path, monkeypatch, register_root = True)
@@ -4407,11 +4397,9 @@ def test_load_progress_counts_a_checkpoint_the_other_cache_root_already_holds(
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.
+ # blobs/ is append-only: a republished repo keeps the superseded revision's blobs forever under
+ # different etags, so 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.
from core.inference.diffusion import _LoadingState
_live, other = _split_cache_roots(tmp_path, monkeypatch, register_root = True)
@@ -4442,10 +4430,9 @@ def test_load_progress_ignores_a_revision_the_moved_root_has_superseded(tmp_path
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.
+ # Each root serves its OWN refs/main, so after a republish the same logical shard has a
+ # different blob etag in each: an etag key never collides and both copies are summed, roughly
+ # doubling the count, though only one of them is ever loaded.
from core.inference.diffusion import _LoadingState
live, other = _split_cache_roots(tmp_path, monkeypatch, register_root = True)
@@ -4472,9 +4459,8 @@ def test_load_progress_counts_one_logical_file_across_roots_at_two_revisions(tmp
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.
+ # can leave the text encoder in the old snapshot while the VAE lands in the live one. Those
+ # snapshots are disjoint PARTS of one revision, so sizing off the larger one under-budgets.
from core.inference.diffusion_memory import OFFLOAD_GROUP, OFFLOAD_NONE
live, other = _split_cache_roots(tmp_path, monkeypatch, register_root = True)
@@ -4504,9 +4490,8 @@ def test_companion_bytes_union_a_base_the_prefetch_split_across_roots(tmp_path,
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.
+ # The merge is per FILE, so a repo that repacked its shards between revisions would count both
+ # namings and force offload on a base that fits. Only refs/main's revision is read.
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"):
@@ -4519,10 +4504,9 @@ def test_companion_bytes_skip_a_superseded_revision_in_the_same_root(tmp_path, m
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.
+ # A prefetch split across roots hands back NO snapshot (one missing the rest of the files 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 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)
@@ -4546,9 +4530,8 @@ def test_plan_memory_sizes_a_pipeline_split_across_both_cache_roots(monkeypatch,
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.
+ # The gated preflight excuses a base off ONE probe file, so its snapshot can hold the manifest
+ # alone: preferring a staged dir outright would size this 4.2 GiB pipeline at 0.
manifest_only = other / "models--bfl--base" / "snapshots" / ("c" * 40)
manifest_only.mkdir(parents = True)
(manifest_only / "model_index.json").write_bytes(b"{}")
@@ -4558,9 +4541,9 @@ def test_plan_memory_sizes_a_pipeline_split_across_both_cache_roots(monkeypatch,
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.
+ # The dense-quant preflight sizes the bf16 transformer to decide whether to re-check the fit. A
+ # base held only under the import-time root reads 0 on the live one, and a 0 skips the check, 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(
@@ -4572,9 +4555,8 @@ def test_dense_transformer_bytes_read_the_other_root_and_treat_the_snapshot_as_a
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.
+ # The staged snapshot is a floor, never a replacement: it can carry companions alone, and
+ # letting that 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
@@ -4592,10 +4574,10 @@ 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.
+ # bf16 transformer, so the fit re-check has to run, and it only runs when the size lookup finds
+ # the shards. For a moved cache they sit under the import-time root (staged=False) or in the
+ # already-resolved snapshot a second move strands outside both roots (staged=True), and the
+ # live root reads 0 for either.
from core.inference import diffusion as dmod
_live, other = _split_cache_roots(tmp_path, monkeypatch, register_root = True)
@@ -4647,11 +4629,10 @@ def test_the_dense_builder_reads_transformer_from_the_hub_id_not_the_staged_snap
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.
+ # directory as terminal (_get_model_file raises instead of falling back to the hub) and a
+ # sharded load raises per missing shard, so a partial snapshot -- 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
diff --git a/studio/backend/tests/test_diffusion_gated_base.py b/studio/backend/tests/test_diffusion_gated_base.py
index 6cdaac0c53a..b72d7e49b77 100644
--- a/studio/backend/tests/test_diffusion_gated_base.py
+++ b/studio/backend/tests/test_diffusion_gated_base.py
@@ -156,8 +156,8 @@ def test_unreadable_metadata_is_named_too(monkeypatch):
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."""
+ 401 HEAD and returns the cached pointer, so probing live access 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
@@ -208,9 +208,9 @@ def test_local_and_non_repo_bases_are_skipped(monkeypatch, tmp_path):
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.
+ # '~other/models' and '~/models' under an account with no home both carry one slash, so they
+ # reach the local-path probe, where pathlib raises RuntimeError -- NOT an OSError. It must fall
+ # through rather than 500 a load not yet started.
probed = _stub_hub(monkeypatch, info = _FakeInfo(False))
class _NoHomePath:
@@ -239,9 +239,7 @@ def test_an_unknown_user_home_base_fails_open_for_real(monkeypatch):
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.
+ # Mirror swap off so this pins the preflight itself; the #7952 mirror rescue is covered below.
monkeypatch.setenv("UNSLOTH_DIFFUSION_NO_MIRROR", "1")
_stub_hub(
monkeypatch,
@@ -259,11 +257,9 @@ def test_download_plan_refuses_a_gated_base_before_listing_files(monkeypatch):
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.
+ # The route calls this BEFORE acquire_for: _run_load's own check runs 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 this pins the preflight itself; the #7952 mirror rescue is covered below.
monkeypatch.setenv("UNSLOTH_DIFFUSION_NO_MIRROR", "1")
_stub_hub(
monkeypatch,
@@ -300,9 +296,7 @@ def test_the_pre_eviction_preflight_clears_an_open_base(monkeypatch):
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.
+ # Mirror swap off so this pins the preflight itself; the #7952 mirror rescue is covered below.
monkeypatch.setenv("UNSLOTH_DIFFUSION_NO_MIRROR", "1")
from core.inference.sd_cpp_backend import SdCppDiffusionBackend
@@ -329,9 +323,7 @@ def test_the_native_pre_eviction_preflight_refuses_a_gated_companion(monkeypatch
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.
+ # Mirror swap off so this pins the preflight itself; the #7952 mirror rescue is covered below.
monkeypatch.setenv("UNSLOTH_DIFFUSION_NO_MIRROR", "1")
backend = DiffusionBackend()
monkeypatch.setattr(
@@ -367,10 +359,9 @@ def test_run_load_stamps_the_gated_error_on_the_load(monkeypatch):
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."""
+ """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()
@@ -379,10 +370,9 @@ def _hub_http_error(cls, message, status):
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."""
+ """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)
@@ -437,11 +427,8 @@ def test_a_blank_token_is_not_sent_as_a_credential(token, monkeypatch):
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.
+ probe swallows the 401, so without the preflight that entry plans at 0 bytes."""
+ # Mirror swap off so this pins the preflight itself; the #7952 mirror rescue is covered below.
monkeypatch.setenv("UNSLOTH_DIFFUSION_NO_MIRROR", "1")
from core.inference.sd_cpp_backend import SdCppDiffusionBackend
@@ -491,9 +478,7 @@ def test_the_native_plan_preflights_its_companion_repos_too(monkeypatch):
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.
+ # Mirror swap off so this pins the preflight itself; the #7952 mirror rescue is covered below.
monkeypatch.setenv("UNSLOTH_DIFFUSION_NO_MIRROR", "1")
from core.inference.sd_cpp_backend import SdCppDiffusionBackend
@@ -601,9 +586,8 @@ def test_the_gguf_is_resolved_against_the_live_cache_root(monkeypatch, tmp_path)
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."""
+ so a PRIVATE base already on disk is indistinguishable from a deleted one. Refusing it would
+ block a load that works: hf_hub_download serves the cached pointer once the token expires."""
from huggingface_hub.errors import RepositoryNotFoundError
private = "unsloth/private-base"
@@ -645,12 +629,10 @@ def test_a_repo_not_found_with_no_response_still_raises(monkeypatch):
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.
+ # Built through __new__: on hub 1.x ``response`` is a REQUIRED keyword-only argument AND
+ # __init__ dereferences it unguarded, so omitting it raises TypeError and passing None raises
+ # AttributeError. Bypassing __init__ is the only portable way to model an error with no
+ # response; only args/response/server_message are read back, so setting those is enough.
err = RepositoryNotFoundError.__new__(RepositoryNotFoundError)
Exception.__init__(err, "no response attached")
err.response = None
@@ -699,9 +681,7 @@ 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.
+ # Mirror swap off so this pins the preflight itself; the #7952 mirror rescue is covered below.
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
@@ -744,9 +724,7 @@ def test_the_native_load_preflights_its_companion_repos_too(monkeypatch):
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.
+ # Mirror swap off so this pins the preflight itself; the #7952 mirror rescue is covered below.
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
@@ -843,8 +821,7 @@ def _stub_shared_download(
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."""
+ and, with no valid token for a gated base, 401s outright."""
seen = _stub_shared_download(monkeypatch, tmp_path, cached_elsewhere = {"ae.safetensors"})
DiffusionBackend()._prefetch_files(
"unsloth/FLUX.1-dev-GGUF",
@@ -879,10 +856,9 @@ def _stub_split_download(monkeypatch, per_file):
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."""
+ into the live one, so returning the manifest's snapshot would point from_pretrained at a tree
+ missing the VAE. 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(
@@ -954,11 +930,10 @@ def test_an_unreadable_gguf_cache_probe_still_downloads(tmp_path, monkeypatch):
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."""
+ """The prefetch reuse above only covers a base the size estimate could list, and that estimate
+ comes from the very ``model_info`` call whose 401 earned the cache escape: ``base_files`` is
+ left empty, so nothing is staged and ``from_pretrained``, pinned to the live root, re-raises the
+ bare auth error over a base wholly on disk. The preflight carries the snapshot it accepted."""
from huggingface_hub.errors import RepositoryNotFoundError
private = "unsloth/private-base"
@@ -1059,12 +1034,10 @@ def test_the_native_fetch_reuses_a_base_asset_cached_under_the_other_root(monkey
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."""
+ """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,
+ and a preflight still probing the upstream would turn those working loads into a 400 -- worse
+ than the bare token error this whole preflight replaced."""
mirror = "unsloth/FLUX.1-dev"
probed: list = []
diff --git a/studio/backend/tests/test_diffusion_prequant.py b/studio/backend/tests/test_diffusion_prequant.py
index 13abeb677c4..adc069c75ec 100644
--- a/studio/backend/tests/test_diffusion_prequant.py
+++ b/studio/backend/tests/test_diffusion_prequant.py
@@ -771,7 +771,7 @@ def test_prequant_checkpoint_cached_reads_only_the_cache(monkeypatch, tmp_path):
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.
+ # needs 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.
@@ -831,10 +831,9 @@ def _other_root_source():
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.
+ # hf_hub_download(cache_dir = live) would not look in huggingface_hub's import-time root and
+ # would re-fetch multiple GB, 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: one HEAD.
default_root = tmp_path / "default-hub"
default_root.mkdir()
ckpt = default_root / "Z-Image-Turbo-FP8.pt"
@@ -1033,9 +1032,8 @@ def test_the_legacy_name_is_still_used_once_the_canonical_one_is_absent(monkeypa
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."""
+ other-root treatment: revalidate through the root holding the copy rather than re-fetch multiple
+ GB into the live one, or pin a stale file by returning it raw."""
from huggingface_hub.errors import EntryNotFoundError
default_root = tmp_path / "default-hub"
@@ -1236,8 +1234,7 @@ def test_load_config_reads_the_same_cache_root_as_the_checkpoint(monkeypatch, tm
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."""
+ the checkpoint lookup just accepted -- silently, as the raise becomes a None return."""
import torch
from core.inference import diffusion_prequant as P
diff --git a/studio/backend/tests/test_diffusion_routes.py b/studio/backend/tests/test_diffusion_routes.py
index 0578568288e..1eb99fc8230 100644
--- a/studio/backend/tests/test_diffusion_routes.py
+++ b/studio/backend/tests/test_diffusion_routes.py
@@ -172,8 +172,8 @@ 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.
+ # The load route predicts the engine before selection; 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)
@@ -636,9 +636,9 @@ def test_load_validation_failure_does_not_evict_chat(client, monkeypatch):
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.
+ # The images page falls back to /images/load whenever the plan fails, so the plan's 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
@@ -674,8 +674,8 @@ def test_gated_base_load_returns_400_without_evicting_chat(client, monkeypatch):
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.
+ # No arbiter handoff on a CPU host means no eviction to protect, so the route skips the
+ # preflight's Hub round-trips: the loader's own copy still catches the gated base.
import types as _types
import core.inference.diffusion_device as devmod
@@ -703,11 +703,9 @@ def test_cpu_load_skips_the_gated_preflight(client, monkeypatch):
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."""
+ OTHER engine and the preflight ran against one never activated. The GPU path always re-asked the
+ engine it got; the CPU path did not, so a mispredict there 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
@@ -766,13 +764,10 @@ def test_a_cpu_mispredicted_engine_is_still_preflighted(monkeypatch):
[("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.
- """
+ """The refusal must precede the engine switch, not follow it: activating the other engine
+ unloads the deactivated one, so a preflight running after the selection destroyed the resident
+ image model and only then reported the gated repo. 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
diff --git a/studio/backend/utils/hf_xet_fallback.py b/studio/backend/utils/hf_xet_fallback.py
index 859b02904ba..0c9985ce4f2 100644
--- a/studio/backend/utils/hf_xet_fallback.py
+++ b/studio/backend/utils/hf_xet_fallback.py
@@ -567,15 +567,14 @@ def hf_hub_download_with_xet_fallback(
"""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).
- ``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."""
+ ``reuse_other_cache_root`` (opt-in) resolves a file cached ONLY under huggingface_hub's
+ import-time root through that root. Studio's cache folder is a setting, so after it changes every
+ cached asset is invisible to a call pinned to the new root: GBs re-download, and a gated base with
+ no valid token 401s even though the bytes are there and the preflight (which checks both roots)
+ already cleared it. Routed THROUGH the other root rather than returned raw, 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 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)