Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: fetch the gated diffusion bases from ungated unsloth mirrors (#7952)
Daniel Han9568efd27e23
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.pyindex abf38b0a6b1..bba9ffac0b3 100644--- a/studio/backend/core/inference/diffusion.py+++ b/studio/backend/core/inference/diffusion.py@@ -37,9 +37,11 @@ from .diffusion_families import (DiffusionFamily,assert_flux2_gguf_matches_base,assert_pipeline_class_available,+ canonical_base,default_generation_params,detect_family_for_pick,excluded_model_reason,+ prefer_ungated_mirror,resolve_base_repo,resolve_local_gguf_child,supported_family_names,@@ -489,6 +491,10 @@ class _LoadingState:base_repo: strexpected_bytes: int = 0error: Optional[str] = None+ # Where the companion BYTES land: ``base_repo``, or its mirror when one was swapped in. Never+ # surfaced (``base_repo`` stays the id status() reports), but the cache scan and the delete+ # guard must look here.+ fetch_repo: Optional[str] = None@dataclass@@ -696,6 +702,7 @@ class DiffusionBackend:base_files: list[str],hf_token: Optional[str],cancel_event: Optional[threading.Event] = None,+ fetch_base: Optional[str] = None,) -> Optional[str]:"""Pre-download the GGUF + the given ``base_files`` into the HF cache,WITHOUT the lock and honoring ``cancel_event`` (this load's own event, so a@@ -710,6 +717,9 @@ class DiffusionBackend:(estimate failure, config-only base, local repo) -> hub id as before."""from utils.hf_xet_fallback import hf_hub_download_with_xet_fallback+ # Only the BYTES move; the caller keeps the upstream id. ``fetch_base`` is the load-wide+ # decision when one was taken, so every later fetch agrees with what was staged here.+ 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# GGUF transformer (hub repos only; a local path is already on disk).@@ -947,10 +957,15 @@ class DiffusionBackend:kwargs["_transformer_prefetched"] = any(f.startswith("transformer/") for f in base_files)+ # ONE mirror decision per load, taken with the staged file list in hand and carried into+ # load_pipeline: per-call-site, one repo could be staged and the other assembled from.+ fetch_base = prefer_ungated_mirror(base, kwargs.get("hf_token"), files = base_files)+ kwargs["_fetch_base"] = fetch_basewith self._lock:# Stamp progress only if this load is still current (a superseder has its own token).if self._load_token == token and self._loading is not None:self._loading.base_repo = base+ self._loading.fetch_repo = fetch_baseself._loading.expected_bytes = expected# Download outside the lock so unload/an eviction can preempt the pull.kwargs["_base_local_dir"] = self._prefetch_files(@@ -960,6 +975,7 @@ class DiffusionBackend:base_files,kwargs.get("hf_token"),cancel_event = cancel_event,+ fetch_base = fetch_base,)self.load_pipeline(**kwargs)with self._lock:@@ -991,10 +1007,18 @@ class DiffusionBackend:if loading is None:return _progress("ready" if self._state is not None else None)- # Sum checkpoint + companion cache; for a full-pipeline load base IS the repo, so count once.- downloaded = self._cache_bytes(loading.repo_id)- if loading.base_repo and loading.base_repo != loading.repo_id:- downloaded += self._cache_bytes(loading.base_repo)+ # Sum checkpoint + companion cache, scanning the repo the bytes LAND in (the mirror when one+ # was swapped in), else a mirrored companion download reads as zero and the bar sits still.+ companion = loading.fetch_repo or loading.base_repo+ if loading.base_repo and loading.base_repo == loading.repo_id:+ # Full pipeline: base IS the repo, so count it once. Summing would add the upstream's+ # stale partial blobs -- the very thing that selects the mirror -- to the mirror's live+ # bytes, pushing the bar to 100% / finalizing mid-download.+ downloaded = self._cache_bytes(companion or loading.repo_id)+ else:+ downloaded = self._cache_bytes(loading.repo_id)+ if companion and companion != loading.repo_id:+ downloaded += self._cache_bytes(companion)expected = loading.expected_bytes# Downloads done, still finalizing. The cache scan can exceed the estimate, so clamp to 100%.if expected > 0 and downloaded >= expected * 0.999:@@ -1009,12 +1033,15 @@ class DiffusionBackend:The delete-cached guard needs this: during a load ``status()["loaded"]`` isstill False, but deleting the target repo (or its companion base) would yank- blobs and snapshot files from under the download/assembly."""+ blobs and snapshot files from under the download/assembly. Includes the mirror+ when one was swapped in: that is where the companion bytes land, so guarding only+ the upstream id would leave the live download deletable."""with self._lock:loading = self._loadingif loading is None or loading.error is not None:return ()- return tuple(r for r in (loading.repo_id, loading.base_repo) if r)+ ids = (loading.repo_id, loading.base_repo, loading.fetch_repo)+ return tuple(dict.fromkeys(r for r in ids if r))@staticmethoddef _te_prequant_plan_files(@@ -1077,6 +1104,8 @@ class DiffusionBackend:meta-inits the encoder from the base repo's config."""from huggingface_hub import HfApi+ # No swap on purpose: the Hub gates only the BYTE endpoint, so model_info answers+ # anonymously and the mirror lists the same names. _prefetch_files swaps when it pulls.from .diffusion_te_prequant import is_prequant_covered_weightapi = HfApi()@@ -1205,9 +1234,12 @@ class DiffusionBackend:})if base_files and not Path(base).expanduser().exists():+ # STAGED before the loader runs, so it must name the MIRROR: a gated upstream here 401s+ # an anonymous user at staging and the swap downstream is never reached. status(), the+ # API base repo, saved configs and LoRA tags keep the vendor id; sizes key on it too.entries.append({- "repo_id": base,+ "repo_id": prefer_ungated_mirror(base, hf_token, files = base_files),"files": base_files,"bytes": int(sizes.get(base, 0)),"gguf_filename": None,@@ -1355,6 +1387,9 @@ class DiffusionBackend:# True when the prefetch staged the base repo's ``transformer/`` shards, the only condition under which the dense-quant# fallback may materialise them. Defaults True for a direct call, which has no prefetch phase._transformer_prefetched: bool = True,+ # The repo the background load staged the companions from; re-derived below for a direct+ # call, which has no prefetch phase.+ _fetch_base: Optional[str] = None,) -> dict[str, Any]:# A blank token must degrade to anonymous, not be passed as a credential. Normalize once.hf_token = hf_token.strip() if isinstance(hf_token, str) else hf_token@@ -1380,6 +1415,10 @@ class DiffusionBackend:base = (repo_id if kind == "pipeline" else _resolve_base_repo(repo_id, base_repo, fam, hf_token))+ # ``base`` stays the UPSTREAM id every report and table lookup keys on; ``fetch_base`` is+ # the only id handed to something that downloads. One decision per load (the background+ # path took it before staging), so nothing stages one repo and assembles from the other.+ fetch_base = _fetch_base or prefer_ungated_mirror(base, hf_token)target = self._resolve_device_target(fam)device, dtype = target.device, target.dtype@@ -1440,6 +1479,7 @@ class DiffusionBackend:cpu_offload,kind = kind,repo_id = repo_id,+ fetch_base = fetch_base,)# Dtype tri-state: unset/"auto" -> hardware ladder; "none"/"off" pins GGUF-as-is; an explicit scheme pins it.@@ -1493,6 +1533,7 @@ class DiffusionBackend:cpu_offload,kind = kind,repo_id = repo_id,+ fetch_base = fetch_base,transformer_resident_override_mib = (candidate.transient_transformer_mib),@@ -1546,8 +1587,9 @@ class DiffusionBackend:if scheme is not Noneelse None)+ # Reads the cache, so it has to look where the prefetch wrote.dense_mib = int(- self._dense_transformer_resident_bytes(base) // (1024 * 1024)+ self._dense_transformer_resident_bytes(fetch_base) // (1024 * 1024))if dense_mib > 0:dense_plan = self._plan_memory(@@ -1559,6 +1601,7 @@ class DiffusionBackend:cpu_offload,kind = kind,repo_id = repo_id,+ fetch_base = fetch_base,transformer_resident_override_mib = dense_mib,)if dense_plan.offload_policy != OFFLOAD_NONE:@@ -1590,6 +1633,7 @@ class DiffusionBackend:allow_dense_fallback = dense_fallback_allowed,lora_specs = loras,text_encoder_quant = text_encoder_quant,+ fetch_base = fetch_base,)except Exception as exc: # noqa: BLE001 — fall back to the GGUF buildlogger.warning(@@ -1628,13 +1672,14 @@ class DiffusionBackend:# Full diffusers repo: from_pretrained pulls every component and re-applies embedded quant config.if fam.name == KREA2_FAMILY_NAME:# krea ships transformers-5.x configs the 4.x line cannot parse, so assemble per-component; that path never sees pipe_kwargs, so pass the pre-cast TE.+ # Fetches EVERY component from the id given, so it must get the mirror.pipe = load_krea2_pipeline(- repo_id,+ fetch_base,dtype,hf_token = hf_token,text_encoder = te_prequant_pipe_kwargs(fam,- repo_id,+ fetch_base,te_quant_mode = text_encoder_quant,target = target,dtype = dtype,@@ -1643,8 +1688,8 @@ class DiffusionBackend:).get("text_encoder"),)elif fam.name == IDEOGRAM4_FAMILY_NAME:- # ideogram ships the same transformers-5.x Qwen stack as krea; assemble per-component too.- pipe = load_ideogram4_pipeline(repo_id, dtype, hf_token = hf_token)+ # ideogram ships the same transformers-5.x Qwen stack as krea; assemble per-component too, from the mirror for the same reason.+ pipe = load_ideogram4_pipeline(fetch_base, dtype, hf_token = hf_token)else:pipe_kwargs: dict[str, Any] = {"torch_dtype": dtype,@@ -1667,7 +1712,7 @@ class DiffusionBackend:pipe_kwargs.update(te_prequant_pipe_kwargs(fam,- repo_id,+ fetch_base,te_quant_mode = text_encoder_quant,target = target,dtype = dtype,@@ -1677,13 +1722,15 @@ class DiffusionBackend:)# The prefetched snapshot dir keeps from_pretrained off the hub (24 GB per FLUX.1 otherwise).pipe = pipeline_cls.from_pretrained(- _base_local_dir or repo_id, **pipe_kwargs+ _base_local_dir or fetch_base, **pipe_kwargs)elif kind == "single_file" and fam.single_file_is_pipeline:# A single-file SDXL-style checkpoint is the WHOLE pipeline: load it through the pipeline class with ``config`` on the base repo.sf_pipe_kwargs: dict[str, Any] = {"torch_dtype": dtype,- "config": base,+ # ``config`` is a REPO FETCH ahead of the mirrored load, so a gated id+ # would 401 here first.+ "config": fetch_base,"cache_dir": hub_cache_dir(),}if hf_token:@@ -1693,9 +1740,9 @@ class DiffusionBackend:# Transformer-only single file; VAE/text-encoder/scheduler come from the base repo.sf_kwargs: dict[str, Any] = {"torch_dtype": dtype,- "config": base,+ # Fetched before auth, same ordering as the whole-pipeline branch above.+ "config": fetch_base,"subfolder": "transformer",- # Config is fetched from the (possibly gated) base before auth."token": hf_token,"cache_dir": hub_cache_dir(),}@@ -1713,14 +1760,14 @@ class DiffusionBackend:if fam.name == KREA2_FAMILY_NAME:pipe = load_krea2_pipeline(- base,+ fetch_base,dtype,hf_token = hf_token,transformer = transformer,# Same pre-cast TE hand-in as the full-pipeline branch.text_encoder = te_prequant_pipe_kwargs(fam,- base,+ fetch_base,te_quant_mode = text_encoder_quant,target = target,dtype = dtype,@@ -1751,7 +1798,7 @@ class DiffusionBackend:pipe_kwargs.update(te_prequant_pipe_kwargs(fam,- base,+ fetch_base,te_quant_mode = text_encoder_quant,target = target,dtype = dtype,@@ -1760,7 +1807,7 @@ class DiffusionBackend:))pipe = pipeline_cls.from_pretrained(- _base_local_dir or base, **pipe_kwargs+ _base_local_dir or fetch_base, **pipe_kwargs)# Effective speed: GGUF defaults to `default` (~2.2x, below the quant noise floor); dense stays bit-identical `off`.@@ -2056,6 +2103,7 @@ class DiffusionBackend:allow_dense_fallback: bool = True,lora_specs: Optional[list[tuple[str, float]]] = None,text_encoder_quant: Optional[str] = None,+ fetch_base: Optional[str] = None,) -> tuple[Any, str]:"""Build the opt-in fast pipeline and return ``(pipe, engaged_scheme)``.@@ -2078,7 +2126,13 @@ class DiffusionBackend:Raises if the scheme is unsupported or quantisation fails, so ``load_pipeline``catches it and falls back to the GGUF build. Quantisation runs ON the device andBEFORE the loader compiles the repeated block, so the order stays quantize ->- compile -> placement."""+ compile -> placement.++ ``base`` keeps the UPSTREAM id for the prequant table and base_model_id checks; every+ download uses ``fetch_base``. A gated base 401s on both the prequant config read and the+ dense pull, and a nonzero baked LoRA refuses the GGUF fallback, so that 401 fails the load.+ """+ fetch_base = fetch_base or prefer_ungated_mirror(base, hf_token)# 1. Pre-quantized checkpoint, when one is configured for the resolved scheme.scheme = select_transformer_quant_scheme(target, mode, family = getattr(fam, "name", None))if scheme is None:@@ -2093,7 +2147,7 @@ class DiffusionBackend:if source is not None:transformer = load_prequantized_transformer(transformer_cls,- base,+ fetch_base,source,device = device,dtype = dtype,@@ -2117,6 +2171,7 @@ class DiffusionBackend:fam = fam,te_quant_mode = text_encoder_quant,target = target,+ fetch_base = fetch_base,)return pipe, scheme@@ -2127,7 +2182,7 @@ class DiffusionBackend:"prequant checkpoint unavailable and the dense transformer does not fit resident")transformer = transformer_cls.from_pretrained(- base,+ fetch_base,subfolder = "transformer",torch_dtype = dtype,token = hf_token,@@ -2144,6 +2199,7 @@ class DiffusionBackend:fam = fam,te_quant_mode = text_encoder_quant,target = target,+ fetch_base = fetch_base,)if lora_specs:# Bake the adapters BEFORE quantize_: peft wraps the dense Linears (post-quant torchao dispatch would TypeError),@@ -2190,9 +2246,15 @@ class DiffusionBackend:fam: Optional[DiffusionFamily] = None,te_quant_mode: Optional[str] = None,target: Any = None,+ fetch_base: Optional[str] = None,) -> Any:"""Assemble the diffusers pipeline around ``transformer`` and place it on ``device``- (a no-op for an already-placed pre-quantized transformer; it moves the companions)."""+ (a no-op for an already-placed pre-quantized transformer; it moves the companions).++ Everything below reads the base only to FETCH, so it uses ``fetch_base`` (the load-wide+ decision, re-derived for a direct call). Matters when ``base_local_dir`` is None: nothing+ was staged, so a gated upstream would 401 here."""+ base = fetch_base or prefer_ungated_mirror(base, hf_token)if getattr(fam, "name", None) == KREA2_FAMILY_NAME:# krea ships transformers-5.x configs and no top-level tokenizer files, so assemble per-component.krea_te = None@@ -2263,6 +2325,7 @@ class DiffusionBackend:repo_id: Optional[str] = None,transformer_resident_override_mib: Optional[int] = None,companion_override_mib: Optional[int] = None,+ fetch_base: Optional[str] = None,):"""Build the memory plan for this load: snapshot free device memory andestimate the model's resident footprint, then let the planner pick an@@ -2280,16 +2343,22 @@ class DiffusionBackend:``companion_override_mib`` likewise replaces the cached companion total on thatre-plan, so the base repo's PREFETCHED transformer/ shards -- which land in thesame blob cache _companion_cache_bytes sums -- are not counted as companions on- top of transformer_resident_override_mib (a double-count of the transformer)."""+ top of transformer_resident_override_mib (a double-count of the transformer).++ ``fetch_base`` is the repo the bytes were staged from, so every cache scan below reads it:+ sizing an upstream id whose cache is empty folds the VAE/text-encoder to zero and wrongly+ picks resident placement. ``base`` and ``repo_id`` keep the upstream identity for the+ family/variant checks."""# Settled (max-over-reads) on cuda: a transient foreign allocation would make an empty card look full.device_memory = settled_snapshot_device_memory(target)if kind == "pipeline":# The whole repo is one cached download, so cached bytes are the resident estimate; a LOCAL path is not cached, so sum its on-disk weights.local_repo = Path(repo_id).expanduser() if repo_id else None+ cache_repo = fetch_base or repo_idif local_repo is not None and local_repo.is_dir():cached = self._local_dir_weight_bytes(local_repo, exclude_transformer = False)else:- cached = self._cache_bytes(repo_id) if repo_id else 0+ cached = self._cache_bytes(cache_repo) if cache_repo else 0cached_mib = int(cached // (1024 * 1024)) if cached else Nonemodel_dense_mib = estimate_safetensors_dense_mib(cached_mib)# A repo can store weights NARROWER than the loaded dtype (ideogram-4 ships raw float8), so cached bytes@@ -2331,7 +2400,7 @@ 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_mibelse:- companion = self._companion_cache_bytes(base)+ companion = self._companion_cache_bytes(fetch_base or base)companion_mib = int(companion // (1024 * 1024)) if companion else Nonemodel_dense_mib = Noneif transformer_resident is not None:@@ -3369,7 +3438,11 @@ def _resolve_base_repo(if not base:tag = _hf_base_model(repo_id, hf_token)if tag and _is_trusted_diffusion_repo(tag):- base = tag+ # A card tag can now name a mirror (they are real unsloth/* repos) and clear the trust+ # bar. Map it back: this becomes status()["base_repo"] and a trained adapter's default+ # base_model, both of which must stay the vendor id. An EXPLICIT base_repo is verbatim.+ base = canonical_base(tag)+ # Returns the UPSTREAM id; the swap happens at the fetch sites only.return resolve_base_repo(fam, base)diff --git a/studio/backend/core/inference/diffusion_auto_policy.py b/studio/backend/core/inference/diffusion_auto_policy.pyindex b8e886d85e5..c03c69b96df 100644--- a/studio/backend/core/inference/diffusion_auto_policy.py+++ b/studio/backend/core/inference/diffusion_auto_policy.py@@ -81,7 +81,9 @@ def family_bf16_components_gb("""(transformer, text encoders, VAE) bf16-resident sizes in GB, or None when the family isn'tin the table (callers fall back to file-size estimates)."""if base_repo:- override = _BASE_REPO_BF16_GB.get(base_repo)+ # Keyed on UPSTREAM ids, and a miss falls through quietly to the coarser family table.+ from .diffusion_families import canonical_base+ override = _BASE_REPO_BF16_GB.get(canonical_base(base_repo))if override is not None:return overridename = getattr(fam, "name", None)diff --git a/studio/backend/core/inference/diffusion_families.py b/studio/backend/core/inference/diffusion_families.pyindex e68b4f966db..d28bb699c75 100644--- a/studio/backend/core/inference/diffusion_families.py+++ b/studio/backend/core/inference/diffusion_families.py@@ -14,10 +14,11 @@ diffusers classes and base repo needed to assemble the full pipeline.from __future__ import annotations+import osimport refrom dataclasses import dataclass, fieldfrom pathlib import Path, PurePosixPath-from typing import Optional+from typing import Optional, Sequence# Runtime->route contract: the /images/generate route matches these messages EXACTLY for a 409 (vs a 500), so both engines raise them verbatim.@@ -467,6 +468,133 @@ def resolve_base_repo(fam: DiffusionFamily, base_repo: Optional[str]) -> str:return base or fam.base_repo+# Byte-identical ungated unsloth mirrors of the gated vendor bases: a GGUF/FP8 pick ships only the+# denoiser, so a gated base still 401s on the companions. Swapped at the fetch sites only, never in+# ``resolve_base_repo``, whose result keys the UPSTREAM-id tables below (see ``canonical_base``).+_GATED_MIRROR_PAIRS: tuple[tuple[str, str], ...] = (+ ("black-forest-labs/FLUX.1-dev", "unsloth/FLUX.1-dev"),+ ("black-forest-labs/FLUX.1-schnell", "unsloth/FLUX.1-schnell"),+ ("black-forest-labs/FLUX.1-Kontext-dev", "unsloth/FLUX.1-Kontext-dev"),+ ("black-forest-labs/FLUX.1-Krea-dev", "unsloth/FLUX.1-Krea-dev"),+ ("black-forest-labs/FLUX.2-dev", "unsloth/FLUX.2-dev"),+ ("black-forest-labs/FLUX.2-klein-9B", "unsloth/FLUX.2-klein-9B"),+ ("black-forest-labs/FLUX.2-klein-base-9B", "unsloth/FLUX.2-klein-base-9B"),+ ("krea/Krea-2-Turbo", "unsloth/Krea-2-Turbo"),+ ("krea/Krea-2-Raw", "unsloth/Krea-2-Raw"),+ ("ideogram-ai/ideogram-4-fp8", "unsloth/ideogram-4-fp8"),+ ("ideogram-ai/ideogram-4-nf4", "unsloth/ideogram-4-nf4"),+ ("ideogram-ai/ideogram-4-nf4-diffusers", "unsloth/ideogram-4-nf4-diffusers"),+)+_GATED_MIRRORS: dict[str, str] = {u.lower(): m for u, m in _GATED_MIRROR_PAIRS}+_MIRROR_UPSTREAM: dict[str, str] = {m.lower(): u for u, m in _GATED_MIRROR_PAIRS}+++def mirror_repo(repo_id: Optional[str]) -> Optional[str]:+ """The ungated unsloth mirror of ``repo_id``, or None when it is not a gated vendor base."""+ return _GATED_MIRRORS.get((repo_id or "").strip().lower())+++def canonical_base(repo_id: Optional[str]) -> str:+ """A mirror id mapped back to the upstream it copies, else ``repo_id`` unchanged.++ Base-keyed tables hold UPSTREAM ids, so every lookup normalises here: a mirror reaching+ ``_FLUX2_BASE_INNER_DIM`` misses, and that shape guard fails OPEN, so it goes silent.+ """+ base = (repo_id or "").strip()+ return _MIRROR_UPSTREAM.get(base.lower(), base)+++# What counts as a real weight file, vs the stray config an interrupted pull leaves behind.+_WEIGHT_SUFFIXES = frozenset({".safetensors", ".bin", ".pt", ".ckpt", ".gguf"})+++def _upstream_is_cached(repo_id: str, files: Optional[Sequence[str]] = None) -> bool:+ """Whether the upstream load is SATISFIABLE from the local cache.++ Not "has any blob": one config left by an interrupted or previously-tokened pull would pin every+ later load to the gated upstream and re-raise the 401 the mirror exists to avoid. So the revision+ must hold ``files``, else a real weight file. ``.incomplete`` downloads have no snapshot symlink,+ so they count as absent.++ Only the revision ``refs/main`` names counts, the one a gated fetch falls back to: on a 401 the+ HEAD fails and ``hf_hub_download`` resolves the ref to ONE commit, so a complete but superseded+ revision would read as cached and hand the loader a repo it cannot fetch from. With no ref (a+ commit-pinned download) any revision counts, as before.++ Reads the LIVE cache root; huggingface_hub's import-time constant goes stale after a+ cache-folder change.+ """+ try:+ from utils.hf_cache_settings import active_hf_hub_cache++ root = Path(active_hf_hub_cache()) / f"models--{repo_id.replace('/', '--')}"+ wanted = tuple(files or ())+ ref = root / "refs" / "main"+ revs = (+ [root / "snapshots" / ref.read_text(encoding = "utf-8").strip()]+ if ref.is_file()+ else sorted((root / "snapshots").iterdir())+ )+ for rev in revs:+ if not rev.is_dir():+ continue+ if wanted:+ if all((rev / name).exists() for name in wanted):+ return True+ elif any(p.suffix.lower() in _WEIGHT_SUFFIXES and p.is_file() for p in rev.rglob("*")):+ return True+ return False+ except Exception: # noqa: BLE001 -- an unreadable/absent cache just means "not cached"+ return False+++def _is_local_path(base: str) -> bool:+ """Whether ``base`` exists on disk, i.e. a local dir rather than a Hub id.++ A user can clone a base into a relative dir named exactly like the vendor id+ (``black-forest-labs/FLUX.1-dev``), which the loaders deliberately treat as local. OSError from+ an id with invalid path characters just means "not a local path".+ """+ try:+ return Path(base or "").expanduser().exists()+ except OSError:+ return False+++def prefer_ungated_mirror(+ base: str,+ hf_token: Optional[str] = None,+ *,+ files: Optional[Sequence[str]] = None,+) -> str:+ """``base``, or its ungated unsloth mirror when that is the better repo to FETCH from.++ A GGUF/FP8 pick carries only the denoiser, so a gated base 401s on the companions; the mirrors+ are byte identical, so this drops the gate without changing a weight. Fetch only: the upstream+ id stays what the picker and status() show, what saved configs hold and what a trained LoRA's+ base_model tag records. The one visible swap is the download manager row, which must name the+ repo actually being pulled -- staging the gated id there is the 401 this exists to remove.++ Declines to today's behaviour under ``UNSLOTH_DIFFUSION_NO_MIRROR``, for a local path, or when+ the upstream already satisfies the load from cache and switching would re-pull tens of GiB.+ ``files`` sharpens that last test to the names about to be fetched; without it any weight counts.++ PURE: table lookup, env read, local stat, NO network. This runs inside pipeline assembly, where+ an earlier ``model_info`` probe of the mirror put a Hub round trip on the load path and broke+ four download-plan tests. A missing mirror surfaces as the ordinary download error.+ ``hf_token`` is unused, kept so callers need not care.+ """+ del hf_token # noqa: F841 -- signature stability only+ mirror = mirror_repo(base)+ if not mirror or os.environ.get("UNSLOTH_DIFFUSION_NO_MIRROR", "").strip():+ return base+ # A local path is never a Hub id: rewriting one sends loads the other sites resolve on disk+ # (``Path(base).exists()``) to the Hub, skipping the copy already downloaded.+ if _is_local_path(base):+ return base+ return base if _upstream_is_cached(base, files) else mirror++# Default (steps, guidance) per model for callers that cannot pass them. Matched by substring, most specific first; same values as the UI MODEL_DEFAULTS table, keep in sync._GENERATION_DEFAULTS: tuple[tuple[str, int, float], ...] = (("z-image-turbo", 9, 0.0),@@ -525,7 +653,8 @@ def family_prequant_repo(baked from ONE base's weights and the loader refuses it for any other base, so a variantwithout its own entry still returns the family default (harmless: the base_model_idvalidation then falls back to dense-quantise, exactly as before this table existed)."""- base = (base_repo or "").strip().lower()+ # prequant_variant_repos is keyed on upstream ids.+ base = canonical_base(base_repo).lower()if base:for entry_base, entry_scheme, repo_id in fam.prequant_variant_repos:if entry_base == base and entry_scheme == scheme:@@ -680,7 +809,8 @@ def assert_flux2_gguf_matches_base(fam, base_repo: str, gguf_path) -> None:unmapped base leaves the load exactly as it was."""if gguf_path is None or not str(getattr(fam, "name", "")).startswith("flux.2"):return- want = _FLUX2_BASE_INNER_DIM.get((base_repo or "").strip().lower())+ # Keyed on upstream ids, and this guard fails OPEN on a miss, so a mirror id would disable it.+ want = _FLUX2_BASE_INNER_DIM.get(canonical_base(base_repo).lower())got = gguf_flux2_inner_dim(gguf_path)if want is None or got is None or want == got:returndiff --git a/studio/backend/core/inference/diffusion_prequant.py b/studio/backend/core/inference/diffusion_prequant.pyindex aaaa17c79f2..5d8849c703d 100644--- a/studio/backend/core/inference/diffusion_prequant.py+++ b/studio/backend/core/inference/diffusion_prequant.py@@ -417,7 +417,16 @@ def _validate_checkpoint(def _same_base_model(a: str, b: str) -> bool:"""Tolerant base-model id compare: exact, or same final path/repo segment (e.g.- ``/models/Z-Image-Turbo`` vs ``Tongyi-MAI/Z-Image-Turbo``)."""+ ``/models/Z-Image-Turbo`` vs ``Tongyi-MAI/Z-Image-Turbo``).++ Both sides normalise through ``canonical_base`` first, so a mirror id in a baked+ ``base_model_id`` check cannot refuse the checkpoint and send the load down the multi-GB dense+ download. Today's mirrors keep the repo name, so the tail compare would cover them, but this+ must not depend on that.+ """+ from .diffusion_families import canonical_base++ a, b = canonical_base(a), canonical_base(b)def _tail(x: str) -> str:return x.replace("\\", "/").rstrip("/").split("/")[-1].lower()diff --git a/studio/backend/core/inference/diffusion_te_prequant.py b/studio/backend/core/inference/diffusion_te_prequant.pyindex a940f22c5c3..f755e5531a1 100644--- a/studio/backend/core/inference/diffusion_te_prequant.py+++ b/studio/backend/core/inference/diffusion_te_prequant.py@@ -71,7 +71,11 @@ def te_base_equivalent(ckpt_base: str, base: str) -> bool:equivalence group above."""if _same_base_model(ckpt_base, base):return True- a, b = str(ckpt_base).strip().lower(), str(base).strip().lower()+ # The groups hold UPSTREAM ids: an unnormalised mirror id is a different string, so it would be+ # refused and the pre-cast encoder dropped for a dense pull.+ from .diffusion_families import canonical_base++ a, b = canonical_base(ckpt_base).lower(), canonical_base(base).lower()return any(a in group and b in group for group in _TE_EQUIVALENT_BASES)diff --git a/studio/backend/core/inference/sd_cpp_backend.py b/studio/backend/core/inference/sd_cpp_backend.pyindex 838b126fbdd..c00ec348398 100644--- a/studio/backend/core/inference/sd_cpp_backend.py+++ b/studio/backend/core/inference/sd_cpp_backend.py@@ -40,6 +40,8 @@ from core.inference.diffusion_families import (DiffusionFamily,detect_family_for_pick,family_sd_cpp_supported,+ mirror_repo,+ prefer_ungated_mirror,resolve_base_repo,resolve_local_gguf_child,sd_cpp_text_encoders_for,@@ -320,6 +322,35 @@ def _map_guidance(return cfg, None+def _fetch_repo_map(assets: list[tuple[str, str, str]], hf_token: Optional[str]) -> dict[str, str]:+ """upstream asset repo -> the repo to actually fetch from (its ungated mirror, or itself).++ Decided per REPO over its whole file list, the same input ``download_plan`` uses, so staging+ and the load agree even when a repo carries several assets."""+ by_repo: dict[str, list[str]] = {}+ for repo, filename, _kind in assets:+ by_repo.setdefault(repo, []).append(filename)+ return {+ repo: prefer_ungated_mirror(repo, hf_token, files = names) for repo, names in by_repo.items()+ }+++def _with_mirrors(repo_ids) -> tuple[str, ...]:+ """``repo_ids`` plus the ungated mirror of each, de-duplicated, order preserved.++ The delete-cached guard must protect whichever of the pair the bytes landed in, and that+ decision is re-taken per load; naming both is cheap and cannot under-protect."""+ out: list[str] = []+ for rid in repo_ids:+ if not rid:+ continue+ out.append(rid)+ mirror = mirror_repo(rid)+ if mirror:+ out.append(mirror)+ return tuple(dict.fromkeys(out))++class SdCppDiffusionBackend:"""Native sd.cpp backend with the diffusers ``DiffusionBackend`` method surface."""@@ -511,7 +542,12 @@ class SdCppDiffusionBackend:if engine.version() is None:raise RuntimeError("sd-cli binary is present but not runnable.")- assets = self._asset_specs(repo_id, gguf_filename, fam)+ # Swap ONCE so the size probe and the download agree: sizes come from paths-info, which+ # -- unlike model_info -- 401s anonymously on a gated repo, so probing the upstream+ # drops the VAE from the progress total the mirror then pulls.+ 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]self._set_expected_bytes(assets, hf_token)paths = self._fetch_assets(assets, hf_token, cancel_event = cancel_event)@@ -670,6 +706,13 @@ class SdCppDiffusionBackend:if filename not in names:names.append(filename)+ # STAGED before the load runs, so each entry must name the repo _fetch_assets will pull+ # from: some asset repos are gated (the FLUX.1 VAE lives in black-forest-labs/FLUX.1-schnell)+ # and an anonymous user would 401 at staging, never reaching the swap. Same per-repo file+ # list on both sides, so both take the same decision.+ 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)sizes = self._plan_file_sizes(by_repo, hf_token)entries: list[dict[str, Any]] = []total = 0@@ -682,7 +725,7 @@ class SdCppDiffusionBackend:"files": names,"bytes": repo_bytes,# Only the transformer entry carries the GGUF filename; the VAE / encoder entries are plain single files.- "gguf_filename": gguf_filename if repo == repo_id else None,+ "gguf_filename": gguf_filename if repo == fetch_repo_id else None,})return {"entries": entries, "total_bytes": total}@@ -759,6 +802,11 @@ class SdCppDiffusionBackend:# 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_eventpaths: dict[str, str] = {}+ # This backend fetches the ASSET repos, never the base, and some are gated, so the swap goes+ # here. Decided per REPO over its whole file list, exactly as download_plan does, so the+ # load pulls from the repo the manager already staged.+ fetch_repo = _fetch_repo_map(assets, hf_token)+ assets = [(fetch_repo[repo], fn, kind) for repo, fn, kind in assets]for repo, fn, kind in assets:if cancel.is_set():raise SdCppCancelled("load cancelled")@@ -794,12 +842,14 @@ class SdCppDiffusionBackend:Mirrors the diffusers backend so the delete-cached guard can query whicheverengine is active without caring which one it got. Includes the companionVAE / text-encoder repos: deleting one of those mid-load would remove files- the committed SdCppModelFiles paths need."""+ the committed SdCppModelFiles paths need, and the mirror of each, where those bytes+ land once a gated asset repo is swapped out."""with self._lock:loading = self._loadingif loading is None or loading.error is not None:return ()- return tuple(r for r in (loading.repo_id, loading.base_repo, *loading.asset_repos) if r)+ ids = (loading.repo_id, loading.base_repo, *loading.asset_repos)+ return _with_mirrors(ids)def loaded_repo_ids(self) -> tuple[str, ...]:"""Repo ids the COMMITTED native model reads from disk (empty when unloaded).@@ -808,7 +858,8 @@ class SdCppDiffusionBackend:cache on every generation (server mode keeps them in the resident process, but theextra ids are harmless there), so the delete-cached guard must refuse thosecompanion repos while the model is loaded -- status().repo_id covers only the main- GGUF. Reconstructed from the committed family, mirroring loading_repo_ids()."""+ GGUF. Reconstructed from the committed family, mirroring loading_repo_ids(), and+ carrying the mirrors too: one-shot sd-cli re-reads whichever of the pair was fetched."""with self._lock:state = self._stateif state is None:@@ -824,7 +875,7 @@ class SdCppDiffusionBackend:fam, state.repo_id, state.gguf_filename))- return tuple(dict.fromkeys(r for r in repos if r))+ return _with_mirrors(repos)# ── Generate ───────────────────────────────────────────────────────────diff --git a/studio/backend/tests/test_diffusion_backend.py b/studio/backend/tests/test_diffusion_backend.pyindex 1784a5344a8..19c3ddf0701 100644--- a/studio/backend/tests/test_diffusion_backend.py+++ b/studio/backend/tests/test_diffusion_backend.py@@ -31,7 +31,13 @@ from core.inference.diffusion import (import core.inference.diffusion_eager_patches # noqa: E402,F401import core.inference.diffusion_arch_patches # noqa: E402,F401from core.inference.diffusion_families import (+ _GATED_MIRROR_PAIRS,+ assert_flux2_gguf_matches_base,+ canonical_base,detect_family,+ family_prequant_repo,+ mirror_repo,+ prefer_ungated_mirror,resolve_base_repo,resolve_local_gguf_child,supported_family_names,@@ -151,6 +157,220 @@ def test_resolve_base_repo():assert resolve_base_repo(fam, "custom/base") == "custom/base"+def _no_cache(monkeypatch):+ """Report every upstream as uncached, so local files cannot mask the mirror decision."""+ monkeypatch.setattr(+ "core.inference.diffusion_families._upstream_is_cached", lambda repo_id, files = None: False+ )+ monkeypatch.delenv("UNSLOTH_DIFFUSION_NO_MIRROR", raising = False)+++def _all_cached(monkeypatch):+ """The opposite: every upstream already satisfies the load, so nothing is swapped."""+ monkeypatch.setattr(+ "core.inference.diffusion_families._upstream_is_cached", lambda repo_id, files = None: True+ )+ monkeypatch.delenv("UNSLOTH_DIFFUSION_NO_MIRROR", raising = False)+++def test_gated_mirror_table_round_trips():+ """Both directions, exact case: canonical_base must hand back a real repo id."""+ assert len(_GATED_MIRROR_PAIRS) == 12+ for upstream, mirror in _GATED_MIRROR_PAIRS:+ assert mirror_repo(upstream) == mirror+ assert canonical_base(mirror) == upstream+ # Case-insensitive in, since a card tag may carry any casing.+ assert mirror_repo(upstream.upper()) == mirror+ # An ungated base is left alone.+ assert mirror_repo("Qwen/Qwen-Image") is None+ assert canonical_base("Qwen/Qwen-Image") == "Qwen/Qwen-Image"+++def test_prefer_ungated_mirror_swaps_gated_bases(monkeypatch):+ _no_cache(monkeypatch)+ for upstream, mirror in _GATED_MIRROR_PAIRS:+ assert prefer_ungated_mirror(upstream) == mirror+ # Ungated bases are untouched.+ assert prefer_ungated_mirror("Qwen/Qwen-Image") == "Qwen/Qwen-Image"+++def test_prefer_ungated_mirror_declines(monkeypatch):+ """Each decline path lands on the upstream id, i.e. exactly today's behaviour."""+ gated = "black-forest-labs/FLUX.1-dev"++ # 1. explicit opt-out+ _no_cache(monkeypatch)+ monkeypatch.setenv("UNSLOTH_DIFFUSION_NO_MIRROR", "1")+ assert prefer_ungated_mirror(gated) == gated++ # 2. already on disk: switching would re-pull tens of GiB+ _all_cached(monkeypatch)+ assert prefer_ungated_mirror(gated) == gated+++def test_a_local_base_directory_is_never_mirrored(monkeypatch, tmp_path):+ """A path that exists on disk is not a Hub id, so it must survive the swap untouched.++ A user can clone a base into a relative dir named exactly like the vendor id. The loaders+ resolve such a base locally (``Path(base).exists()``), but several take that branch after the+ swap, so rewriting it would send the load to the Hub and ignore the on-disk files.+ """+ gated = "black-forest-labs/FLUX.1-dev"+ _no_cache(monkeypatch)+ # The table still knows this id: only the local path stops the swap.+ assert mirror_repo(gated) == "unsloth/FLUX.1-dev"+ assert prefer_ungated_mirror(gated) == "unsloth/FLUX.1-dev"++ local = tmp_path / gated+ (local / "vae").mkdir(parents = True)+ (local / "model_index.json").write_text("{}")+ monkeypatch.chdir(tmp_path)+ assert prefer_ungated_mirror(gated) == gated+ assert prefer_ungated_mirror(gated, files = ["model_index.json"]) == gated+ # An absolute local path never matched the table, and still does not.+ assert prefer_ungated_mirror(str(local)) == str(local)+++def test_mirrored_base_still_trips_the_flux2_shape_guard():+ """The regression the two-helper split exists for.++ The guard fails OPEN on an unmapped base, so a mirror id reaching ``_FLUX2_BASE_INNER_DIM``+ would silence it. Assert the RAISE: a disabled guard passes any weaker check.+ """+ # "flux.2-klein", not "flux.2": no family has the bare name, and a None family returns early.+ fam = detect_family("x", override = "flux.2-klein")+ assert fam is not None and fam.name.startswith("flux.2")++ def _reader_for(inner_dim):+ class _Reader:+ def __init__(self, _path):+ self.tensors = [+ type(+ "T",+ (),+ {"name": "double_stream_modulation_img.lin.weight", "shape": (inner_dim,)},+ )()+ ]++ return _Reader++ import gguf++ original = gguf.GGUFReader+ try:+ # A 4B GGUF (inner_dim 3072) against the 9B base still raises through the mirror id.+ gguf.GGUFReader = _reader_for(3072)+ for base in ("black-forest-labs/FLUX.2-klein-9B", "unsloth/FLUX.2-klein-9B"):+ with pytest.raises(ValueError, match = "klein"):+ assert_flux2_gguf_matches_base(fam, base, "some-klein-4b.gguf")+ # A matching pair stays silent through the mirror id too.+ gguf.GGUFReader = _reader_for(4096)+ for base in ("black-forest-labs/FLUX.2-klein-9B", "unsloth/FLUX.2-klein-9B"):+ assert assert_flux2_gguf_matches_base(fam, base, "some-klein-9b.gguf") is None+ finally:+ gguf.GGUFReader = original+++def test_family_prequant_repo_accepts_either_id():+ """prequant_variant_repos is keyed on upstream ids, so a mirror must hit the same entry."""+ fam = detect_family("x", override = "flux.1")+ for scheme in ("int8", "fp8"):+ upstream = family_prequant_repo(fam, scheme, "black-forest-labs/FLUX.1-dev")+ mirrored = family_prequant_repo(fam, scheme, "unsloth/FLUX.1-dev")+ assert upstream == mirrored == "unsloth/FLUX.1-dev-FP8"+++def _fake_hub_cache(+ monkeypatch,+ tmp_path,+ repo_id,+ files,+ *,+ revision = "abc123",+ ref = None,+):+ """Lay out ``files`` as a cached snapshot revision of ``repo_id`` and point the live cache+ setting at it, so the mirror decision reads a tree the test controls. ``ref`` writes+ refs/main, as huggingface_hub does for a branch download."""+ root = tmp_path / f"models--{repo_id.replace('/', '--')}"+ rev = root / "snapshots" / revision+ for name in files:+ path = rev / name+ path.parent.mkdir(parents = True, exist_ok = True)+ path.write_bytes(b"x")+ rev.mkdir(parents = True, exist_ok = True)+ if ref is not None:+ (root / "refs").mkdir(parents = True, exist_ok = True)+ (root / "refs" / "main").write_text(ref, encoding = "utf-8")+ monkeypatch.setattr("utils.hf_cache_settings.active_hf_hub_cache", lambda: str(tmp_path))+ monkeypatch.delenv("UNSLOTH_DIFFUSION_NO_MIRROR", raising = False)+++def test_a_superseded_cached_revision_does_not_disable_the_mirror(monkeypatch, tmp_path):+ """Only the revision refs/main names can satisfy a gated fetch: on a 401 the HEAD call fails+ and hf_hub_download resolves refs/<revision> to ONE commit, returning its pointer or+ re-raising. A complete but superseded revision must therefore not read as cached."""+ from core.inference.diffusion_families import _upstream_is_cached++ gated = "black-forest-labs/FLUX.1-dev"+ wanted = ["model_index.json", "vae/diffusion_pytorch_model.safetensors"]+ # Old revision complete, refs/main moved on to a revision holding only the manifest.+ _fake_hub_cache(monkeypatch, tmp_path, gated, wanted, revision = "old")+ _fake_hub_cache(monkeypatch, tmp_path, gated, ["model_index.json"], revision = "new", ref = "new")+ assert _upstream_is_cached(gated, wanted) is False+ assert prefer_ungated_mirror(gated, files = wanted) == "unsloth/FLUX.1-dev"++ # refs/main pointing at the complete revision is the ordinary cached case.+ _fake_hub_cache(monkeypatch, tmp_path, gated, wanted, revision = "old", ref = "old")+ assert _upstream_is_cached(gated, wanted) is True+ assert prefer_ungated_mirror(gated, files = wanted) == gated+++def test_a_stray_upstream_file_does_not_disable_the_mirror(monkeypatch, tmp_path):+ """The decline is "the load is satisfiable from cache", not "some blob exists".++ An interrupted (or previously tokened) pull leaves a config behind. Treating that as cached+ pinned every later load to the gated upstream and re-raised the 401 the mirror removes.+ """+ from core.inference.diffusion_families import _upstream_is_cached++ gated = "black-forest-labs/FLUX.1-dev"+ # 1. debris only: not usable, so the mirror stands.+ _fake_hub_cache(monkeypatch, tmp_path, gated, ["model_index.json", "vae/config.json"])+ assert _upstream_is_cached(gated) is False+ assert prefer_ungated_mirror(gated) == "unsloth/FLUX.1-dev"++ # 2. a real weight file: the user's cache is worth keeping, so no swap.+ _fake_hub_cache(+ monkeypatch,+ tmp_path,+ gated,+ ["model_index.json", "vae/diffusion_pytorch_model.safetensors"],+ )+ assert _upstream_is_cached(gated) is True+ assert prefer_ungated_mirror(gated) == gated++ # 3. with the file list in hand the test is exact: a missing companion still swaps.+ wanted = ["vae/diffusion_pytorch_model.safetensors", "text_encoder/model.safetensors"]+ assert _upstream_is_cached(gated, wanted) is False+ assert prefer_ungated_mirror(gated, files = wanted) == "unsloth/FLUX.1-dev"+ assert prefer_ungated_mirror(gated, files = wanted[:1]) == gated+++def test_te_prequant_equivalence_group_accepts_a_mirrored_base():+ """The T5-XXL artifact is shared across the FLUX.1 releases through an equivalence group of+ UPSTREAM ids. A mirrored base is a different string, so without normalising it the pre-cast+ encoder is refused and the load falls back to the dense multi-GB download."""+ from core.inference.diffusion_te_prequant import te_base_equivalent++ ckpt = "black-forest-labs/FLUX.1-schnell"+ assert te_base_equivalent(ckpt, "black-forest-labs/FLUX.1-dev") is True+ assert te_base_equivalent(ckpt, "unsloth/FLUX.1-dev") is True+ assert te_base_equivalent("unsloth/FLUX.1-schnell", "unsloth/FLUX.1-dev") is True+ # A base outside the verified group is still refused, mirrored or not.+ assert te_base_equivalent(ckpt, "unsloth/FLUX.2-dev") is False++def test_resolve_local_gguf_child(tmp_path):(tmp_path / "model.gguf").write_bytes(b"x")assert resolve_local_gguf_child(tmp_path, "model.gguf") == (tmp_path / "model.gguf").resolve()@@ -1427,6 +1647,25 @@ def test_resolve_base_repo_drops_untrusted_card_tag(monkeypatch):)+def test_resolve_base_repo_maps_a_mirrored_card_tag_back_to_the_vendor_id(monkeypatch):+ """A card tag can now name a mirror and clear the trust bar. This value is+ status()["base_repo"] and a trained adapter's default base_model, so it must be the vendor+ id; only the fetch sites see the mirror."""+ import core.inference.diffusion as dmod++ fam = detect_family("unsloth/FLUX.1-dev-GGUF")+ monkeypatch.setattr(dmod, "_hf_base_model", lambda repo_id, hf_token: "unsloth/FLUX.1-dev")+ assert (+ _resolve_base_repo("unsloth/FLUX.1-dev-GGUF", None, fam, None)+ == "black-forest-labs/FLUX.1-dev"+ )+ # An EXPLICIT base_repo is the caller's own choice and is honoured verbatim.+ assert (+ _resolve_base_repo("unsloth/FLUX.1-dev-GGUF", "unsloth/FLUX.1-dev", fam, None)+ == "unsloth/FLUX.1-dev"+ )++def test_detect_family_rejects_layered():# Qwen-Image-Layered needs a dedicated pipeline (additional_t_cond), so reject at load, not at the first step.assert detect_family("unsloth/Qwen-Image-Layered-GGUF") is None@@ -1594,6 +1833,40 @@ def test_load_progress_downloading_then_finalizing(monkeypatch):assert backend.load_progress()["phase"] == "finalizing" # 1000/1000+def test_load_progress_counts_a_mirrored_pipeline_repo_once(monkeypatch):+ # base_repo == repo_id, so count once. Summing adds the upstream's stale partial blobs -- the+ # very thing that selects the mirror -- to the mirror's live bytes, pegging the bar at 100%.+ backend = DiffusionBackend()+ backend._loading = _LoadingState(+ repo_id = "black-forest-labs/FLUX.1-dev",+ base_repo = "black-forest-labs/FLUX.1-dev",+ expected_bytes = 1000,+ )+ backend._loading.fetch_repo = "unsloth/FLUX.1-dev"+ # 600 stale upstream bytes from the interrupted pull, 500 real ones into the mirror.+ monkeypatch.setattr(+ DiffusionBackend,+ "_cache_bytes",+ staticmethod(lambda repo: 600 if repo.startswith("black-forest-labs/") else 500),+ )+ p = backend.load_progress()+ assert p["bytes_downloaded"] == 500 # the mirror alone, not 1100+ assert p["phase"] == "downloading" # not "finalizing"+++def test_load_progress_still_sums_a_gguf_pick_and_its_separate_base(monkeypatch):+ # A base that is a DIFFERENT repo from the pick is a separate download, so still summed.+ backend = DiffusionBackend()+ backend._loading = _LoadingState(+ repo_id = "unsloth/FLUX.1-dev-GGUF",+ base_repo = "black-forest-labs/FLUX.1-dev",+ expected_bytes = 1000,+ )+ backend._loading.fetch_repo = "unsloth/FLUX.1-dev"+ monkeypatch.setattr(DiffusionBackend, "_cache_bytes", staticmethod(lambda repo: 150))+ assert backend.load_progress()["bytes_downloaded"] == 300++def test_base_file_downloaded_excludes_undownloaded():# Counted: the pipeline manifest + component subfolders from_pretrained fetches.assert _base_file_downloaded("model_index.json")@@ -1875,6 +2148,197 @@ def test_prefetch_downloads_gguf_and_base(monkeypatch, tmp_path):assert ("base/repo", "vae/x.safetensors") in calls+def test_prefetch_pulls_companions_from_the_ungated_mirror(monkeypatch, tmp_path):+ """The companions are why a gated base blocked a GGUF pick, so this is the call that has to+ move. The file names are identical either way, so the list passes through untouched."""+ backend = DiffusionBackend()+ calls: list = []+ monkeypatch.setattr(+ "utils.hf_xet_fallback.hf_hub_download_with_xet_fallback",+ lambda repo, fn, tok, **k: (calls.append((repo, fn)), f"/cache/{fn}")[1],+ )+ _no_cache(monkeypatch)+ backend._prefetch_files(+ "unsloth/FLUX.1-dev-GGUF",+ "flux1-dev-Q4_K_M.gguf",+ "black-forest-labs/FLUX.1-dev",+ ["vae/diffusion_pytorch_model.safetensors"],+ None,+ )+ assert ("unsloth/FLUX.1-dev", "vae/diffusion_pytorch_model.safetensors") in calls+ assert all(repo != "black-forest-labs/FLUX.1-dev" for repo, _ in calls)+ # The GGUF repo is never rewritten.+ assert ("unsloth/FLUX.1-dev-GGUF", "flux1-dev-Q4_K_M.gguf") in calls++ # An upstream already on disk keeps its cache.+ calls.clear()+ _all_cached(monkeypatch)+ backend._prefetch_files(+ "unsloth/FLUX.1-dev-GGUF",+ None,+ "black-forest-labs/FLUX.1-dev",+ ["vae/diffusion_pytorch_model.safetensors"],+ None,+ )+ assert ("black-forest-labs/FLUX.1-dev", "vae/diffusion_pytorch_model.safetensors") in calls+++def test_single_file_load_reads_config_and_companions_from_the_mirror(+ fake_runtime, tmp_path, monkeypatch+):+ """``config=`` is a REPO FETCH that runs BEFORE the mirrored pipeline load, so a gated id left+ there 401s an anonymous user first and the swap below is never reached."""+ diffusers = sys.modules["diffusers"]+ diffusers.FluxPipeline = _FakePipeline+ diffusers.FluxTransformer2DModel = _FakeTransformer+ _no_cache(monkeypatch)+ (tmp_path / "model.gguf").write_bytes(b"weights")++ status = DiffusionBackend().load_pipeline(+ str(tmp_path),+ gguf_filename = "model.gguf",+ base_repo = "black-forest-labs/FLUX.1-dev",+ family_override = "flux.1",+ )++ assert _FakeTransformer.last["config"] == "unsloth/FLUX.1-dev"+ assert _FakePipeline.last["base"] == "unsloth/FLUX.1-dev"+ # Invisible: only the bytes moved, so the API still reports the id the user picked.+ assert status["base_repo"] == "black-forest-labs/FLUX.1-dev"+++def test_pipeline_kind_assembles_krea_and_ideogram_from_the_mirror(fake_runtime, monkeypatch):+ """Both per-component loaders fetch EVERY component from the id handed to them, so a gated+ pipeline pick must arrive already swapped."""+ from core.inference import diffusion as dmod++ diffusers = sys.modules["diffusers"]+ diffusers.Krea2Pipeline = _FakePipeline+ diffusers.Krea2Transformer2DModel = _FakeTransformer+ _no_cache(monkeypatch)++ seen: dict[str, str] = {}++ def _krea(base, dtype, **kwargs):+ seen["krea"] = base+ return _FakePipe()++ def _ideogram(+ repo_id,+ dtype,+ hf_token = None,+ ):+ seen["ideogram"] = repo_id+ return _FakePipe()++ monkeypatch.setattr(dmod, "load_krea2_pipeline", _krea)+ monkeypatch.setattr(dmod, "load_ideogram4_pipeline", _ideogram)++ krea = DiffusionBackend().load_pipeline("krea/Krea-2-Turbo", model_kind = "pipeline")+ assert seen["krea"] == "unsloth/Krea-2-Turbo"+ assert krea["repo_id"] == "krea/Krea-2-Turbo"++ ideogram = DiffusionBackend().load_pipeline("ideogram-ai/ideogram-4-fp8", model_kind = "pipeline")+ assert seen["ideogram"] == "unsloth/ideogram-4-fp8"+ assert ideogram["repo_id"] == "ideogram-ai/ideogram-4-fp8"+++def test_dense_quant_pulls_the_transformer_from_the_mirror(monkeypatch):+ """The dense fallback downloads the base repo's transformer/ shards. With a nonzero baked LoRA+ the GGUF fallback is refused, so a 401 here fails the load outright."""+ _no_cache(monkeypatch)+ from core.inference import diffusion as dmod++ seen: dict = {}++ class _Transformer:+ @staticmethod+ def from_pretrained(base, **kwargs):+ seen["dense"] = base+ return object()++ monkeypatch.setattr(+ dmod, "select_transformer_quant_scheme", lambda target, mode, family = None: "fp8"+ )+ monkeypatch.setattr(dmod, "resolve_prequant_source", lambda fam, scheme, **kw: None)+ monkeypatch.setattr(dmod, "quantize_transformer", lambda pipe, target, **kw: "fp8")+ monkeypatch.setattr(+ DiffusionBackend,+ "_assemble_pipe",+ staticmethod(lambda *a, **k: seen.setdefault("assembled", _FakePipe())),+ )++ _pipe, scheme = DiffusionBackend()._load_dense_quant_pipeline(+ _Transformer,+ _FakePipeline,+ "black-forest-labs/FLUX.1-dev",+ "cuda:0",+ "bf16",+ None,+ types.SimpleNamespace(device = "cuda:0"),+ "fp8",+ fam = detect_family("x", override = "flux.1"),+ )+ assert scheme == "fp8"+ assert seen["dense"] == "unsloth/FLUX.1-dev"+++def test_load_progress_and_delete_guard_follow_the_mirrored_companion(monkeypatch):+ """Bytes land under the mirror, so scanning the upstream reports a companion download of zero+ and leaves the repo being written to deletable."""+ from core.inference import diffusion as dmod++ backend = DiffusionBackend()+ backend._loading = dmod._LoadingState(+ repo_id = "unsloth/FLUX.1-dev-GGUF",+ base_repo = "black-forest-labs/FLUX.1-dev",+ fetch_repo = "unsloth/FLUX.1-dev",+ expected_bytes = 10,+ )+ monkeypatch.setattr(+ DiffusionBackend,+ "_cache_bytes",+ staticmethod(lambda repo_id: 4 if repo_id == "unsloth/FLUX.1-dev" else 0),+ )++ assert backend.load_progress()["bytes_downloaded"] == 4+ # BOTH ids: the upstream is what status reports, the mirror is where the download writes.+ assert backend.loading_repo_ids() == (+ "unsloth/FLUX.1-dev-GGUF",+ "black-forest-labs/FLUX.1-dev",+ "unsloth/FLUX.1-dev",+ )+++def test_plan_memory_sizes_the_mirrored_companion_cache(monkeypatch, tmp_path):+ """A companion total of zero reads as "unknown", which picks resident placement and OOMs."""+ monkeypatch.setattr(+ DiffusionBackend,+ "_companion_cache_bytes",+ staticmethod(lambda base: 8 * 1024 * 1024 if base == "unsloth/FLUX.1-dev" else 0),+ )+ seen: dict = {}+ monkeypatch.setattr(+ "core.inference.diffusion.plan_diffusion_memory",+ lambda **kwargs: seen.update(kwargs) or types.SimpleNamespace(offload_policy = "none"),+ )+ from core.inference.diffusion_device import resolve_diffusion_device_target++ gguf = tmp_path / "m.gguf"+ gguf.write_bytes(b"x" * 1024)++ DiffusionBackend()._plan_memory(+ resolve_diffusion_device_target(),+ str(gguf),+ "black-forest-labs/FLUX.1-dev",+ detect_family("x", override = "flux.1"),+ None,+ False,+ fetch_base = "unsloth/FLUX.1-dev",+ )+ assert seen["companion_dense_mib"] == 8++# fp16-incompatible guard + dtype promotion@@ -3092,6 +3556,8 @@ def test_assemble_pipe_routes_krea2_per_component(monkeypatch):return Pipe()monkeypatch.setattr(dmod, "load_krea2_pipeline", fake_loader)+ # Pin the mirror decision, else the assertion below reads the developer's real HF cache.+ _no_cache(monkeypatch)class ExplodingPipeline:@staticmethod@@ -3109,7 +3575,8 @@ def test_assemble_pipe_routes_krea2_per_component(monkeypatch):fam = types.SimpleNamespace(name = "krea-2"),)assert isinstance(pipe, Pipe)- assert calls == {"base": "krea/Krea-2-Turbo", "transformer": marker, "device": "cuda:0"}+ # _assemble_pipe reads base only to FETCH, so the loader gets the ungated mirror.+ assert calls == {"base": "unsloth/Krea-2-Turbo", "transformer": marker, "device": "cuda:0"}def test_dense_quant_unusable_prequant_path_runs_dense_refit(fake_runtime, tmp_path, monkeypatch):@@ -3800,14 +4267,17 @@ def test_download_plan_scopes_the_base_repo_files(monkeypatch):monkeypatch.setattr(DiffusionBackend, "_dense_quant_prefetch_needed", lambda self, fam, kwargs: False)+ _no_cache(monkeypatch)plan = DiffusionBackend().download_plan("unsloth/FLUX.1-dev-GGUF", gguf_filename = "flux1-dev-Q4_K_M.gguf")+ # The base entry names the MIRROR: staged before the loader runs, so a gated id here 401s an+ # anonymous user at staging and the swap downstream is never reached.assert [e["repo_id"] for e in plan["entries"]] == ["unsloth/FLUX.1-dev-GGUF",- "black-forest-labs/FLUX.1-dev",+ "unsloth/FLUX.1-dev",]checkpoint, base = plan["entries"]assert checkpoint["files"] == ["flux1-dev-Q4_K_M.gguf"]@@ -3886,6 +4356,8 @@ def test_download_plan_stages_the_precast_encoder_instead_of_the_dense_one(monke),)+ _no_cache(monkeypatch)+plan = DiffusionBackend().download_plan("unsloth/FLUX.1-dev-GGUF",gguf_filename = "flux1-dev-Q4_K_M.gguf",@@ -3894,7 +4366,7 @@ def test_download_plan_stages_the_precast_encoder_instead_of_the_dense_one(monkeby_repo = {e["repo_id"]: e for e in plan["entries"]}assert "unsloth/FLUX.1-schnell-FP8" in by_repoassert by_repo["unsloth/FLUX.1-schnell-FP8"]["files"] == ["text_encoder_2-fp8.pt"]- base = by_repo["black-forest-labs/FLUX.1-dev"]+ base = by_repo["unsloth/FLUX.1-dev"]# text_encoder_2 dense weights are gone; text_encoder stays (no hosted artifact), as do the non-weight files the pre-cast loader meta-inits from.assert not any(f.startswith("text_encoder_2/") and f.endswith(".safetensors") for f in base["files"]@@ -3920,6 +4392,9 @@ def test_download_plan_keeps_the_dense_encoder_without_an_fp8_request(monkeypatcmonkeypatch.setattr(DiffusionBackend, "_dense_quant_prefetch_needed", lambda self, fam, kwargs: False)+ # An upstream that already satisfies the load keeps its id, so the plan stages the cache the+ # user already paid for.+ _all_cached(monkeypatch)plan = DiffusionBackend().download_plan("unsloth/FLUX.1-dev-GGUF", gguf_filename = "flux1-dev-Q4_K_M.gguf")@@ -3952,12 +4427,13 @@ def test_download_plan_keeps_the_dense_encoder_when_the_precast_repo_is_unavaila)},)+ _no_cache(monkeypatch)plan = DiffusionBackend().download_plan("unsloth/FLUX.1-dev-GGUF",gguf_filename = "flux1-dev-Q4_K_M.gguf",text_encoder_quant = "fp8",)- base = next(e for e in plan["entries"] if e["repo_id"] == "black-forest-labs/FLUX.1-dev")+ base = next(e for e in plan["entries"] if e["repo_id"] == "unsloth/FLUX.1-dev")assert "text_encoder/model.safetensors" in base["files"]assert not any(e["repo_id"] == "unsloth/does-not-exist" for e in plan["entries"])diff --git a/studio/backend/tests/test_sd_cpp_backend.py b/studio/backend/tests/test_sd_cpp_backend.pyindex d62d774e36c..d5b863b405b 100644--- a/studio/backend/tests/test_sd_cpp_backend.py+++ b/studio/backend/tests/test_sd_cpp_backend.py@@ -267,6 +267,78 @@ def test_download_plan_skips_a_local_transformer_but_still_stages_the_assets(monassert plan["total_bytes"] == 0+def _no_cache(monkeypatch):+ """Report every upstream as uncached, so a local cache cannot mask the mirror decision."""+ monkeypatch.setattr(+ "core.inference.diffusion_families._upstream_is_cached", lambda repo_id, files = None: False+ )+ monkeypatch.delenv("UNSLOTH_DIFFUSION_NO_MIRROR", raising = False)+++def test_download_plan_stages_the_mirrored_asset_repo(monkeypatch):+ """STAGED before the load runs, so a gated asset repo left here 401s an anonymous user and+ _fetch_assets' swap is never reached. FLUX.1's VAE lives in the gated FLUX.1-schnell."""+ _no_cache(monkeypatch)+ b = SdCppDiffusionBackend(engine = _FakeEngine())+ monkeypatch.setattr(+ SdCppDiffusionBackend, "_plan_file_sizes", staticmethod(lambda by_repo, token: {})+ )++ plan = b.download_plan(+ "unsloth/FLUX.1-dev-GGUF", gguf_filename = "flux1-dev-Q4_K_M.gguf", model_kind = "gguf"+ )++ staged = {e["repo_id"] for e in plan["entries"]}+ assert "unsloth/FLUX.1-schnell" in staged+ assert "black-forest-labs/FLUX.1-schnell" not in staged+ # The GGUF entry is untouched and still the only one carrying the filename.+ tr = [e for e in plan["entries"] if e["gguf_filename"]]+ assert len(tr) == 1 and tr[0]["repo_id"] == "unsloth/FLUX.1-dev-GGUF"+++def test_download_plan_and_fetch_assets_pick_the_same_repo(monkeypatch):+ """Staging one repo and then downloading from the other is the failure this feature removes,+ so both sides take the decision from the same per-repo file list."""+ _no_cache(monkeypatch)+ b = SdCppDiffusionBackend(engine = _FakeEngine())+ monkeypatch.setattr(+ SdCppDiffusionBackend, "_plan_file_sizes", staticmethod(lambda by_repo, token: {})+ )+ pulled: list = []+ monkeypatch.setattr(+ "utils.hf_xet_fallback.hf_hub_download_with_xet_fallback",+ lambda repo, fn, tok, **k: (pulled.append((repo, fn)), f"/cache/{fn}")[1],+ )++ fam = detect_family("flux.1")+ specs = b._asset_specs("unsloth/FLUX.1-dev-GGUF", "flux1-dev-Q4_K_M.gguf", fam)+ b._fetch_assets(specs, None)+ plan = b.download_plan(+ "unsloth/FLUX.1-dev-GGUF", gguf_filename = "flux1-dev-Q4_K_M.gguf", model_kind = "gguf"+ )++ assert {(e["repo_id"], f) for e in plan["entries"] for f in e["files"]} == set(pulled)+++def test_delete_guard_covers_the_mirrored_asset_repos(monkeypatch):+ """The bytes land under whichever of the pair was fetched, so guarding only the upstream leaves+ the mirror cache deletable under a one-shot sd-cli that re-reads it."""+ b = _loaded_backend("flux.1")+ ids = set(b.loaded_repo_ids())+ assert "black-forest-labs/FLUX.1-schnell" in ids+ assert "unsloth/FLUX.1-schnell" in ids++ b._state = None+ b._loading = bk._SdLoading(+ repo_id = "unsloth/FLUX.1-dev-GGUF",+ base_repo = "black-forest-labs/FLUX.1-dev",+ asset_repos = ("black-forest-labs/FLUX.1-schnell",),+ )+ loading = set(b.loading_repo_ids())+ assert {"black-forest-labs/FLUX.1-schnell", "unsloth/FLUX.1-schnell"} <= loading+ assert {"black-forest-labs/FLUX.1-dev", "unsloth/FLUX.1-dev"} <= loading++def test_download_plan_refuses_a_pick_native_cannot_serve():b = SdCppDiffusionBackend(engine = _FakeEngine())with pytest.raises(ValueError, match = "gguf_filename is required"):