Skip to content

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

Studio: refuse an oversized unified-memory image load before the download, not after (#9629)

oobabooga89f1e50c8eea
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.py
index 3e85d75c70b..ccf2201e40b 100644
--- a/studio/backend/core/inference/diffusion.py
+++ b/studio/backend/core/inference/diffusion.py
@@ -77,7 +77,12 @@ from .diffusion_device import (
resolve_selected_cuda_ordinal,
)
from .diffusion_ideogram4 import ideogram4_repo_is_fp8, load_ideogram4_pipeline
-from .diffusion_hidream import HIDREAM_FAMILY_NAME, hidream_te4_kwargs
+from .diffusion_hidream import (
+ HIDREAM_FAMILY_NAME,
+ HIDREAM_LLAMA_BF16_BYTES,
+ HIDREAM_LLAMA_REPO,
+ hidream_te4_kwargs,
+)
from .diffusion_krea2 import KREA2_FAMILY_NAME, load_krea2_pipeline
from .diffusion_memory import (
MEMORY_MODE_BALANCED,
@@ -97,6 +102,7 @@ from .diffusion_memory import (
reclaimable_snapshot_device_memory,
refine_memory_plan_for_components,
settled_snapshot_device_memory,
+ snapshot_device_memory,
unified_memory_shortfall_message,
)
from .diffusion_speed import (
@@ -138,6 +144,7 @@ from .diffusion_cache import (
normalize_transformer_cache,
)
from .diffusion_precision import (
+ TE_QUANT_FP8,
effective_te_quant,
normalize_te_quant,
quantize_text_encoders,
@@ -161,6 +168,7 @@ from .diffusion_auto_policy import (
family_bf16_components_gb,
precision_fallback_allowed,
precision_refusal_message,
+ resident_bytes_from_declared,
resolve_dense_quant_candidate,
)
from .diffusion_transformer_quant import (
@@ -472,6 +480,29 @@ def _fit_within(img: Any, max_w: int, max_h: int) -> Any:
return img.resize((nw, nh), Image.LANCZOS)
+def _prequant_plan_bytes(te_files: Any) -> int:
+ """Return the hosted pre-cast encoder bytes in a download plan."""
+ return sum(
+ int(size or 0) for entry in (te_files or {}).values() for _name, size in (entry[1] or ())
+ )
+
+
+def _predownload_encoder_bf16_bytes(
+ fam: Any,
+ te_files: Any,
+ *,
+ pipeline_declared: bool = True,
+) -> int:
+ """Return separately hosted dense bf16 encoder bytes absent from the pipeline repo."""
+ if (
+ getattr(fam, "name", None) == HIDREAM_FAMILY_NAME
+ and "text_encoder_4" not in (te_files or {})
+ and pipeline_declared
+ ):
+ return HIDREAM_LLAMA_BF16_BYTES
+ return 0
+
+
def _image_variant_hint(
family_name: Optional[str],
single_file_name: Optional[str],
@@ -2103,13 +2134,17 @@ class DiffusionBackend:
kwargs.get("hf_token"),
kwargs.get("gpu_ordinal"),
local_files_only = local_files_only,
+ base_repo = base,
)
+ resident_sizes: list[tuple[str, int]] = []
+ fetch_repos: dict[str, str] = {}
expected, base_files = self._estimate_download_bytes(
kwargs["repo_id"],
kwargs.get("gguf_filename"),
base,
kwargs.get("hf_token"),
kind = kind,
+ pipeline_components = _explicit_pipeline_components(fam),
single_file_is_pipeline = bool(fam and fam.single_file_is_pipeline),
# Pull the base shards here rather than inside the locked, unpreemptable finalize.
# Deferred: the widening turns on the base repo's own listing, which this call is
@@ -2129,6 +2164,8 @@ class DiffusionBackend:
),
skip_te_components = tuple(te_prequant_files),
local_files_only = local_files_only,
+ resident_file_sizes_out = resident_sizes,
+ fetch_repos_out = fetch_repos,
)
# Only shards this prefetch staged may be materialised by the dense fallback, so read it
# off the staged list: a failed size estimate drops every base file too. A LOCAL base
@@ -2139,7 +2176,9 @@ class DiffusionBackend:
) or _local_base_transformer_present(base)
# 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)
+ fetch_base = fetch_repos.get(base) or 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``, once it is decided, so it probes the repo the pull will read:
@@ -2163,6 +2202,27 @@ class DiffusionBackend:
kwargs.get("hf_token"),
allow_network = not local_files_only,
)
+ shortfall = self.declared_footprint_shortfall(
+ fam,
+ kwargs["repo_id"],
+ base,
+ kind = kind,
+ declared_files = resident_sizes,
+ prequant_bytes = _prequant_plan_bytes(te_prequant_files),
+ extra_bf16_bytes = _predownload_encoder_bf16_bytes(
+ fam, te_prequant_files, pipeline_declared = bool(resident_sizes)
+ ),
+ gguf_filename = kwargs.get("gguf_filename"),
+ gpu_ordinal = kwargs.get("gpu_ordinal"),
+ memory_mode = kwargs.get("memory_mode"),
+ cpu_offload = bool(kwargs.get("cpu_offload")),
+ )
+ if shortfall is not None:
+ logger.error(
+ "diffusion.memory: refusing oversized unified-memory load before download: %s",
+ shortfall,
+ )
+ raise RuntimeError(shortfall)
with self._lock:
# Stamp progress only if this load is still current (a superseder has its own token).
if self._load_token == token and self._loading is not None:
@@ -2267,6 +2327,7 @@ class DiffusionBackend:
hf_token: Optional[str],
gpu_ordinal: Optional[int] = None,
local_files_only: bool = False,
+ base_repo: Optional[str] = None,
) -> dict[str, tuple[str, list[tuple[str, int]]]]:
"""``{component: (repo_id, [(rfilename, size)])}`` for the text encoders this pick will
take PRE-CAST from a hosted checkpoint instead of the base repo's dense weights.
@@ -2281,19 +2342,34 @@ class DiffusionBackend:
if local_files_only:
return {}
try:
+ if normalize_te_quant(text_encoder_quant) != TE_QUANT_FP8:
+ return {}
from huggingface_hub import HfApi
- from .diffusion_te_prequant import te_prequant_hub_files, te_prequant_sources
+ from .diffusion_te_prequant import (
+ TE_PREQUANT_COMPONENTS,
+ te_prequant_hub_files,
+ te_prequant_sources_for_base,
+ )
- sources = te_prequant_sources(
- fam,
- te_quant_mode = text_encoder_quant,
+ source_kwargs = {
+ "te_quant_mode": text_encoder_quant,
# The selected card, for the same reason the dense-quant probe uses it.
- target = (
+ "target": (
resolve_diffusion_device_target()
if gpu_ordinal is None
else resolve_diffusion_device_target(ordinal = gpu_ordinal)
),
+ }
+ standalone_component_bases = None
+ if getattr(fam, "name", None) == HIDREAM_FAMILY_NAME:
+ source_kwargs["components"] = (*TE_PREQUANT_COMPONENTS, "text_encoder_4")
+ standalone_component_bases = {"text_encoder_4": HIDREAM_LLAMA_REPO}
+ sources = te_prequant_sources_for_base(
+ fam,
+ base_repo or str(getattr(fam, "base_repo", "") or ""),
+ standalone_component_bases = standalone_component_bases,
+ **source_kwargs,
)
if not sources:
return {}
@@ -2417,11 +2493,14 @@ class DiffusionBackend:
hf_token: Optional[str],
*,
kind: str = "gguf",
+ pipeline_components: Optional[Sequence[str]] = None,
single_file_is_pipeline: bool = False,
include_transformer: "bool | Callable[[Sequence[str], Sequence[str]], bool]" = False,
sizes_out: Optional[dict[str, int]] = None,
file_sizes_out: Optional[dict[str, dict[str, int]]] = None,
+ resident_file_sizes_out: Optional[list[tuple[str, int]]] = None,
revisions_out: Optional[dict[str, str]] = None,
+ fetch_repos_out: Optional[dict[str, str]] = None,
skip_te_components: tuple[str, ...] = (),
failures_out: Optional[list] = None,
local_files_only: bool = False,
@@ -2431,8 +2510,12 @@ class DiffusionBackend:
``sizes_out``, when given, is filled with per-repo byte totals so the download
plan can size one job per repo off this same single pair of Hub lookups.
+ ``resident_file_sizes_out`` receives only the selected pipeline components and default
+ weight variant, which is the set that ``from_pretrained`` materialises in memory.
``revisions_out`` records the commit each lookup described, so a cache probe can ask
about the SAME revision the sizes came from instead of whatever ``main`` is locally.
+ ``fetch_repos_out`` records the repo that supplied pipeline metadata, so staging reads
+ that same pinned file set instead of making a second mirror choice after the estimate.
For a ``pipeline`` load the whole repo IS the pipeline (``base_repo`` is the
repo itself), so the transformer/ subfolder is INCLUDED -- unlike the GGUF /
@@ -2478,35 +2561,63 @@ class DiffusionBackend:
try:
if kind == "pipeline":
- info = api.model_info(repo_id, files_metadata = True, token = hf_token)
- picked = [
- s
- for s in info.siblings
- if _pipeline_file_downloaded(s.rfilename) and not _dense_te_shard(s.rfilename)
- ]
- # diffusers prefers safetensors: drop a .bin whose dir also has a picked .safetensors.
- st_dirs = {
- s.rfilename.rsplit("/", 1)[0]
- for s in picked
- if s.rfilename.endswith(".safetensors")
- }
- for s in picked:
- if s.rfilename.endswith(".bin") and s.rfilename.rsplit("/", 1)[0] in st_dirs:
- continue
- base_files.append(s.rfilename)
- total += s.size or 0
- if sizes_out is not None:
- sizes_out[repo_id] = total
- if file_sizes_out is not None:
- file_sizes_out[repo_id] = {
- s.rfilename: int(s.size or 0)
- for s in picked
+
+ def _pipeline_listing(metadata_repo: str) -> tuple[Any, Any, list[Any]]:
+ info = api.model_info(metadata_repo, files_metadata = True, token = hf_token)
+ components = _pipeline_components_from_index(
+ metadata_repo,
+ info,
+ hf_token,
+ explicit_components = pipeline_components,
+ failures_out = failures_out,
+ )
+ candidates = [
+ s
+ for s in info.siblings
+ if _pipeline_file_downloaded(s.rfilename)
+ and not _dense_te_shard(s.rfilename)
+ and (components is None or _pipeline_selected_file(s.rfilename, components))
+ ]
+ # Prefer safetensors over sibling .bin weights.
+ st_dirs = {
+ s.rfilename.rsplit("/", 1)[0]
+ for s in candidates
+ if s.rfilename.endswith(".safetensors")
+ }
+ picked = [
+ s
+ for s in candidates
if not (
s.rfilename.endswith(".bin")
and s.rfilename.rsplit("/", 1)[0] in st_dirs
)
- }
- _record_revision(revisions_out, repo_id, info)
+ ]
+ return info, components, picked
+
+ metadata_repo = prefer_ungated_mirror(
+ repo_id, hf_token, files = ("model_index.json",)
+ )
+ info, components, picked = _pipeline_listing(metadata_repo)
+ base_files = [s.rfilename for s in picked]
+ fetch_repo = prefer_ungated_mirror(repo_id, hf_token, files = base_files)
+ if fetch_repo.lower() != metadata_repo.lower():
+ metadata_repo = fetch_repo
+ info, components, picked = _pipeline_listing(metadata_repo)
+ base_files = [s.rfilename for s in picked]
+ total = sum(s.size or 0 for s in picked)
+ if fetch_repos_out is not None:
+ fetch_repos_out[repo_id] = metadata_repo
+ if sizes_out is not None:
+ sizes_out[repo_id] = total
+ if file_sizes_out is not None:
+ file_sizes_out[repo_id] = {s.rfilename: int(s.size or 0) for s in picked}
+ if resident_file_sizes_out is not None and components is not None:
+ resident_file_sizes_out.extend(
+ (s.rfilename, int(s.size or 0))
+ for s in picked
+ if _pipeline_resident_weight(s.rfilename)
+ )
+ _record_revision(revisions_out, metadata_repo, info)
return total, base_files
# Skip the Hub size lookup for a LOCAL gguf path: model_info raises on a filesystem path.
if gguf_filename and not Path(repo_id).expanduser().exists():
@@ -2584,6 +2695,8 @@ class DiffusionBackend:
model_kind: Optional[str] = None,
hf_token: Optional[str] = None,
text_encoder_quant: Optional[str] = None,
+ allow_device_probe: bool = True,
+ memory_verdict: bool = True,
**load_kwargs: Any,
) -> dict[str, Any]:
"""The repos + exact files this pick needs, so the Hub download manager can fetch
@@ -2598,7 +2711,14 @@ class DiffusionBackend:
loads a hosted PRE-CAST encoder, so the base repo's dense encoder shards must not be
staged and the pre-cast checkpoint must be. Without it the manager stages the dense
encoder (tens of GB the load never opens) and the load then pulls the pre-cast file
- inline, outside the manager's progress and disk preflight."""
+ inline, outside the manager's progress and disk preflight.
+
+ ``allow_device_probe=False`` skips device-dependent precision planning and the memory
+ verdict while training owns the GPU. It is not free: the pre-cast encoder and the DiT
+ prequant need a target to resolve, so clearing it also changes WHICH FILES the plan
+ counts. ``memory_verdict=False`` suppresses only the oversized-unified-memory refusal,
+ so a caller that merely dislikes the verdict does not silently get a different file
+ list."""
fam = detect_family_for_pick(repo_id, gguf_filename, family_override)
kind = resolve_model_kind(gguf_filename, model_kind)
if kind == "pipeline":
@@ -2621,12 +2741,22 @@ class DiffusionBackend:
fam, repo_id, gguf_filename, base, hf_token
) or speech_pick_refusal(repo_id, gguf_filename, hf_token)
# Only a checkpoint that really resolves on the Hub earns the right to drop dense shards.
- te_files = self._te_prequant_plan_files(
- fam, text_encoder_quant, hf_token, load_kwargs.get("gpu_ordinal")
+ te_files = (
+ self._te_prequant_plan_files(
+ fam,
+ text_encoder_quant,
+ hf_token,
+ load_kwargs.get("gpu_ordinal"),
+ base_repo = base,
+ )
+ if allow_device_probe
+ else {}
)
sizes: dict[str, int] = {}
file_sizes: dict[str, dict[str, int]] = {}
+ resident_file_sizes: list[tuple[str, int]] = []
revisions: dict[str, str] = {}
+ fetch_repos: dict[str, str] = {}
plan_failures: list = []
required_total, base_files = self._estimate_download_bytes(
repo_id,
@@ -2634,6 +2764,7 @@ class DiffusionBackend:
base,
hf_token,
kind = kind,
+ pipeline_components = _explicit_pipeline_components(fam),
single_file_is_pipeline = bool(fam and fam.single_file_is_pipeline),
# The RESOLVED base, as the load passes it: a variant base picks its own pre-quant repo.
# Deferred exactly as _run_load defers it. Called eagerly this runs before the base
@@ -2649,12 +2780,14 @@ class DiffusionBackend:
transformer_files = transformer_files,
)
)
- if kind == "gguf"
+ if kind == "gguf" and allow_device_probe
else False
),
sizes_out = sizes,
file_sizes_out = file_sizes,
+ resident_file_sizes_out = resident_file_sizes,
revisions_out = revisions,
+ fetch_repos_out = fetch_repos,
skip_te_components = tuple(te_files),
failures_out = plan_failures,
)
@@ -2662,7 +2795,9 @@ class DiffusionBackend:
# answers model_info anonymously, so the plan would otherwise be confident and the 401 land
# 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)
+ fetch_base = fetch_repos.get(base) or prefer_ungated_mirror(
+ base, hf_token, files = base_files
+ )
_assert_base_repo_accessible(fetch_base, hf_token)
entries: list[dict[str, Any]] = []
checkpoint_bytes = 0
@@ -2670,12 +2805,15 @@ class DiffusionBackend:
checkpoint_bytes = int(
file_sizes.get(repo_id, {}).get(gguf_filename, sizes.get(repo_id, 0))
)
- required_total += sum(int(size) for files in te_files.values() for _name, size in files[1])
+ te_prequant_bytes = _prequant_plan_bytes(te_files)
+ required_total += te_prequant_bytes
# The dense transformer/ shards are excluded for a GGUF pick, so a hosted prequant that
# replaces them is real footprint the plan would otherwise never report. Sized against the
# RESOLVED base, as the load passes it: a variant base picks its own prequant repo.
- dit_prequant = self._dit_prequant_plan_source(
- fam, kind, hf_token, {**load_kwargs, "base_repo": base}
+ dit_prequant = (
+ self._dit_prequant_plan_source(fam, kind, hf_token, {**load_kwargs, "base_repo": base})
+ if allow_device_probe
+ else None
)
if dit_prequant is not None:
required_total += dit_prequant[2]
@@ -2821,6 +2959,22 @@ class DiffusionBackend:
# A companion of the checkpoint, never the selected model itself.
prequant_repo, prequant_file, prequant_size = dit_prequant
add_missing_entry(prequant_repo, [prequant_file], {prequant_file: prequant_size})
+ if incompatible is None and allow_device_probe and memory_verdict:
+ incompatible = self.declared_footprint_shortfall(
+ fam,
+ repo_id,
+ base,
+ kind = kind,
+ declared_files = resident_file_sizes,
+ prequant_bytes = te_prequant_bytes,
+ extra_bf16_bytes = _predownload_encoder_bf16_bytes(
+ fam, te_files, pipeline_declared = bool(resident_file_sizes)
+ ),
+ gguf_filename = gguf_filename,
+ gpu_ordinal = load_kwargs.get("gpu_ordinal"),
+ memory_mode = load_kwargs.get("memory_mode"),
+ cpu_offload = bool(load_kwargs.get("cpu_offload")),
+ )
return {
"entries": entries,
"total_bytes": sum(entry["bytes"] for entry in entries),
@@ -3867,7 +4021,11 @@ class DiffusionBackend:
# that fits is declined on bytes never materialised.
companion_override_mib = (
self._precast_scaled_companions_mib(
- prequant_candidate, fam, target, text_encoder_quant
+ prequant_candidate,
+ fam,
+ base,
+ target,
+ text_encoder_quant,
)
),
),
@@ -3939,7 +4097,11 @@ class DiffusionBackend:
),
# Same pre-cast encoder pricing as the fit check above.
companion_override_mib = self._precast_scaled_companions_mib(
- retry_candidate, fam, target, text_encoder_quant
+ retry_candidate,
+ fam,
+ base,
+ target,
+ text_encoder_quant,
),
)
if retry_candidate is not None
@@ -4087,6 +4249,7 @@ class DiffusionBackend:
dtype = dtype,
hf_token = hf_token,
logger = logger,
+ local_files_only = local_files_only,
).get("text_encoder"),
)
elif fam.name == IDEOGRAM4_FAMILY_NAME:
@@ -4122,6 +4285,7 @@ class DiffusionBackend:
dtype = dtype,
hf_token = hf_token,
logger = logger,
+ local_files_only = local_files_only,
)
)
# The prefetched snapshot dir keeps from_pretrained off the hub (24 GB per FLUX.1 otherwise).
@@ -4187,6 +4351,7 @@ class DiffusionBackend:
dtype = dtype,
hf_token = hf_token,
logger = logger,
+ local_files_only = local_files_only,
).get("text_encoder"),
)
else:
@@ -4220,6 +4385,7 @@ class DiffusionBackend:
dtype = dtype,
hf_token = hf_token,
logger = logger,
+ local_files_only = local_files_only,
)
)
pipe = pipeline_cls.from_pretrained(
@@ -4784,6 +4950,7 @@ class DiffusionBackend:
dtype = dtype,
hf_token = hf_token,
logger = logger,
+ local_files_only = local_files_only,
).get("text_encoder")
pipe = load_krea2_pipeline(
base_local_dir or base,
@@ -4828,6 +4995,7 @@ class DiffusionBackend:
dtype = dtype,
hf_token = hf_token,
logger = logger,
+ local_files_only = local_files_only,
)
)
pipe = pipeline_cls.from_pretrained(base_local_dir or base, **pipe_kwargs)
@@ -4836,7 +5004,11 @@ class DiffusionBackend:
@staticmethod
def _precast_scaled_companions_mib(
- candidate: Any, fam: DiffusionFamily, target: Any, text_encoder_quant: Optional[str]
+ candidate: Any,
+ fam: DiffusionFamily,
+ base: str,
+ target: Any,
+ text_encoder_quant: Optional[str],
) -> Optional[int]:
"""``candidate.companions_mib`` with the text-encoder share priced at the PRE-CAST size
when this pick takes its encoder from a hosted fp8 checkpoint.
@@ -4854,7 +5026,12 @@ class DiffusionBackend:
try:
from .diffusion_te_prequant import te_prequant_budget_scale
- scale = te_prequant_budget_scale(fam, te_quant_mode = text_encoder_quant, target = target)
+ scale = te_prequant_budget_scale(
+ fam,
+ te_quant_mode = text_encoder_quant,
+ target = target,
+ base = base,
+ )
encoders = int(getattr(candidate, "text_encoders_mib", 0) or 0)
if scale == 1.0 or encoders <= 0:
return int(companions)
@@ -4933,7 +5110,10 @@ class DiffusionBackend:
from .diffusion_te_prequant import te_prequant_budget_scale
te_scale = te_prequant_budget_scale(
- fam, te_quant_mode = text_encoder_quant, target = target
+ fam,
+ te_quant_mode = text_encoder_quant,
+ target = target,
+ base = base,
)
transformer_gb, text_encoders_gb, vae_gb = table
resident_gb = transformer_gb + text_encoders_gb * te_scale + vae_gb
@@ -4948,6 +5128,71 @@ class DiffusionBackend:
except Exception: # noqa: BLE001 — sizing aid only; refuse on the plan as built
return plan
+ def declared_footprint_shortfall(
+ self,
+ fam: Optional[DiffusionFamily],
+ repo_id: str,
+ base: str,
+ *,
+ kind: str,
+ declared_files: Any,
+ prequant_bytes: int = 0,
+ extra_bf16_bytes: int = 0,
+ gguf_filename: Optional[str] = None,
+ gpu_ordinal: Optional[int] = None,
+ memory_mode: Optional[str] = None,
+ cpu_offload: bool = False,
+ ) -> Optional[str]:
+ """Return a pre-download unified-memory refusal for a pipeline, if any.
+
+ The estimate comes from Hub metadata because a cold cache has no local size to inspect.
+ It uses total capacity so a currently loaded model does not make a valid swap look too
+ large. GGUF and single-file loads retain the existing in-load guard.
+ """
+ if fam is None or kind != "pipeline":
+ return None
+ declared_files = list(declared_files or ())
+ if (
+ max(0, int(prequant_bytes or 0)) <= 0
+ and max(0, int(extra_bf16_bytes or 0)) <= 0
+ and not any(int(size or 0) > 0 for _name, size in declared_files)
+ ):
+ return None
+ try:
+ target = self._target_for_ordinal(fam, gpu_ordinal)
+ with diffusion_device_scope(target.ordinal if target.is_cuda_torch_device else None):
+ device_memory = snapshot_device_memory(target)
+ if device_memory.memory_kind != "unified_memory" or device_memory.total_mib is None:
+ return None
+ dtype_scale = 2.0 if "float32" in str(getattr(target, "dtype", "")).lower() else 1.0
+ resident_bytes = resident_bytes_from_declared(
+ base,
+ declared_files,
+ prequant_bytes = prequant_bytes,
+ extra_bf16_bytes = extra_bf16_bytes,
+ dtype_scale = dtype_scale,
+ )
+ if not resident_bytes:
+ return None
+ capacity = replace(device_memory, free_mib = device_memory.total_mib)
+ resident_mib = int(resident_bytes) // (1024 * 1024)
+ variant_hint = _image_variant_hint(fam.name, gguf_filename, repo_id, base)
+ plan = plan_diffusion_memory(
+ target = target,
+ device_memory = capacity,
+ model_dense_mib = resident_mib,
+ runtime_headroom_mib = estimate_image_runtime_mib(
+ width = None, height = None, family = variant_hint
+ ),
+ requested_mode = memory_mode,
+ explicit_offload = bool(cpu_offload),
+ )
+ # The estimate uses capacity, not current free memory.
+ plan = replace(plan, device_memory = replace(capacity, free_mib = None))
+ except Exception: # noqa: BLE001 -- failed sizing must not refuse a load
+ return None
+ return unified_memory_shortfall_message(plan, family = fam.name)
+
def _plan_memory(
self,
target: DiffusionDeviceTarget,
@@ -6446,6 +6691,119 @@ def _pipeline_file_downloaded(rfilename: str) -> bool:
return True
+_DEFAULT_PIPELINE_WEIGHT_RE = re.compile(
+ r"^(?:diffusion_pytorch_model|pytorch_model|model)"
+ r"(?:-\d{5}-of-\d{5})?\.(?:bin|safetensors)$"
+)
+_DEFAULT_PIPELINE_WEIGHT_INDEX_RE = re.compile(
+ r"^(?:diffusion_pytorch_model|pytorch_model|model)\.(?:bin|safetensors)\.index\.json$"
+)
+_PIPELINE_WEIGHT_PREFIX_RE = re.compile(
+ r"^(?:diffusion_pytorch_model|pytorch_model|model)[.-].*"
+ r"(?:bin|safetensors)(?:\.index.*\.json)?$"
+)
+
+
+def _explicit_pipeline_components(fam: Any) -> Optional[tuple[str, ...]]:
+ """Component folders opened by image pipelines assembled outside generic Diffusers."""
+ name = getattr(fam, "name", None)
+ if name == KREA2_FAMILY_NAME:
+ return ("scheduler", "text_encoder", "tokenizer", "transformer", "vae")
+ if name == IDEOGRAM4_FAMILY_NAME:
+ return (
+ "scheduler",
+ "text_encoder",
+ "tokenizer",
+ "transformer",
+ "unconditional_transformer",
+ "vae",
+ )
+ return None
+
+
+def _pipeline_components_from_index(
+ repo_id: str,
+ info: Any,
+ hf_token: Optional[str],
+ *,
+ explicit_components: Optional[Sequence[str]] = None,
+ failures_out: Optional[list] = None,
+) -> Optional[tuple[frozenset[str], frozenset[str]]]:
+ """Return selected component folders and exact model-index ignores.
+
+ The manifest is small but authoritative. If it cannot be read, staging retains the prior
+ best-effort listing and resident sizing declines to issue a hard refusal.
+ """
+ try:
+ from huggingface_hub import hf_hub_download
+
+ if not any(s.rfilename == "model_index.json" for s in (info.siblings or ())):
+ raise FileNotFoundError(f"{repo_id} has no model_index.json")
+ path = hf_hub_download(
+ repo_id,
+ "model_index.json",
+ revision = getattr(info, "sha", None) or None,
+ cache_dir = hub_cache_dir(),
+ token = hf_token or None,
+ )
+ payload = json.loads(Path(path).read_text(encoding = "utf-8"))
+ if not isinstance(payload, dict):
+ raise ValueError(f"{repo_id}/model_index.json is not an object")
+ if explicit_components is None:
+ selected = {
+ str(name)
+ for name, spec in payload.items()
+ if not str(name).startswith("_")
+ and isinstance(spec, (list, tuple))
+ and len(spec) >= 2
+ and spec[0] is not None
+ and spec[1] is not None
+ }
+ else:
+ selected = {str(name) for name in explicit_components}
+ ignored = payload.get("_ignore_files", ())
+ if not isinstance(ignored, (list, tuple, set)):
+ ignored = ()
+ if not selected:
+ raise ValueError(f"{repo_id}/model_index.json names no loadable components")
+ return frozenset(selected), frozenset(str(name) for name in ignored)
+ except Exception as exc: # noqa: BLE001 -- no manifest means no hard memory verdict
+ logger.warning("diffusion.pipeline_manifest_failed: %s", exc)
+ if failures_out is not None:
+ failures_out.append(exc)
+ return None
+
+
+def _pipeline_default_variant_file(rfilename: str) -> bool:
+ """Whether a model-looking filename belongs to Diffusers' default variant."""
+ name = rfilename.rsplit("/", 1)[-1].lower()
+ if not _PIPELINE_WEIGHT_PREFIX_RE.match(name):
+ return True
+ return bool(
+ _DEFAULT_PIPELINE_WEIGHT_RE.match(name) or _DEFAULT_PIPELINE_WEIGHT_INDEX_RE.match(name)
+ )
+
+
+def _pipeline_selected_file(
+ rfilename: str, selection: tuple[frozenset[str], frozenset[str]]
+) -> bool:
+ """Match the files loaded by the selected components at ``variant=None``."""
+ components, ignored = selection
+ if rfilename in ignored:
+ return False
+ if rfilename == "model_index.json":
+ return True
+ if "/" not in rfilename or rfilename.split("/", 1)[0] not in components:
+ return False
+ return _pipeline_default_variant_file(rfilename)
+
+
+def _pipeline_resident_weight(rfilename: str) -> bool:
+ """Whether a selected file becomes tensor storage in the loaded pipeline."""
+ name = rfilename.rsplit("/", 1)[-1].lower()
+ return bool(_DEFAULT_PIPELINE_WEIGHT_RE.match(name))
+
+
def _progress(
phase: Optional[str],
bytes_downloaded: int = 0,
diff --git a/studio/backend/core/inference/diffusion_auto_policy.py b/studio/backend/core/inference/diffusion_auto_policy.py
index c2c190ba52f..e9e333ff2ea 100644
--- a/studio/backend/core/inference/diffusion_auto_policy.py
+++ b/studio/backend/core/inference/diffusion_auto_policy.py
@@ -78,14 +78,65 @@ _BASE_REPO_HUB_DOWNLOAD_FACTOR: dict[str, float] = {
}
-def _base_key(base_repo: Optional[str]) -> str:
- """The key both per-base tables below are written against: canonical upstream id, lowercased.
+DENOISER_SUBFOLDERS = ("transformer/", "unconditional_transformer/")
+
+# Download bytes per resident byte; unknown bases stay 1:1.
+_BASE_RESIDENT_FACTORS: dict = {
+ "tongyi-mai/z-image-turbo": (2.0, 1.0),
+ "tongyi-mai/z-image": (1.0, 1.0),
+ "alpha-vllm/lumina-image-2.0": (2.0, 2.0),
+ "ideogram-ai/ideogram-4-fp8": (0.5, 0.5),
+ # SDXL's default variant is fp32 throughout (headers read 2026-08-25); the loader skips the
+ # fp16 twins. At 1:1 its 12.9 GB prices against a 6.5 GB bf16 load and refuses on any 16 GB
+ # pool. Its denoiser is ``unet/``, so it lands in the companion bucket: both factors halve.
+ "stabilityai/stable-diffusion-xl-base-1.0": (2.0, 2.0),
+ "stabilityai/sdxl-turbo": (2.0, 2.0),
+}
+
- ``canonical_base`` maps a mirror back to its upstream but preserves the caller's casing for
- everything else, and a base repo reaches here however the user typed it: the trust gate and
- every other base-keyed table compare case-insensitively, so these must too or a lowercase
- custom base silently misses its override and gets sized as the family default.
+def resident_bytes_from_declared(
+ base_repo: Optional[str],
+ declared_files: Any,
+ *,
+ prequant_bytes: int = 0,
+ extra_bf16_bytes: int = 0,
+ dtype_scale: float = 1.0,
+) -> Optional[int]:
+ """Estimate resident bytes from Hub file sizes and component storage precision.
+
+ ``prequant_bytes`` is added unchanged because hosted pre-cast encoders are already stored at
+ their load precision. ``extra_bf16_bytes`` covers separately hosted dense components, and is
+ widened with the pipeline when the resolved target is float32. Unknown families are treated
+ as 1:1 with their download size.
"""
+ denoiser_factor, companion_factor = _BASE_RESIDENT_FACTORS.get(
+ _base_key(base_repo) if base_repo else "", (1.0, 1.0)
+ )
+ denoiser = 0
+ companions = 0
+ for path, size in declared_files or ():
+ size = int(size or 0)
+ if size <= 0:
+ continue
+ if str(path).startswith(DENOISER_SUBFOLDERS):
+ denoiser += size
+ else:
+ companions += size
+ prequant_bytes = max(0, int(prequant_bytes or 0))
+ extra_bf16_bytes = max(0, int(extra_bf16_bytes or 0))
+ dtype_scale = max(1.0, float(dtype_scale or 1.0))
+ if denoiser <= 0 and companions <= 0 and prequant_bytes <= 0 and extra_bf16_bytes <= 0:
+ return None
+ dtype_resident = (
+ int(denoiser / max(denoiser_factor, 0.01))
+ + int(companions / max(companion_factor, 0.01))
+ + extra_bf16_bytes
+ )
+ return int(dtype_resident * dtype_scale) + prequant_bytes
+
+
+def _base_key(base_repo: Optional[str]) -> str:
+ """Return the canonical, case-insensitive key used by per-base tables."""
from .diffusion_families import canonical_base
return canonical_base(base_repo).strip().lower()
diff --git a/studio/backend/core/inference/diffusion_hidream.py b/studio/backend/core/inference/diffusion_hidream.py
index c6c15e632b1..09905163390 100644
--- a/studio/backend/core/inference/diffusion_hidream.py
+++ b/studio/backend/core/inference/diffusion_hidream.py
@@ -25,6 +25,7 @@ HIDREAM_FAMILY_NAME = "hidream-i1"
# Open mirror of the gated meta-llama/Meta-Llama-3.1-8B-Instruct the pipeline expects.
HIDREAM_LLAMA_REPO = "unsloth/Meta-Llama-3.1-8B-Instruct"
+HIDREAM_LLAMA_BF16_BYTES = 16_060_556_376
def hidream_te4_kwargs(
@@ -90,9 +91,16 @@ def hidream_te4_kwargs(
if fp8_engages and fam is not None:
from .diffusion_te_prequant import (
load_prequant_text_encoder,
- resolve_te_prequant_source,
+ te_prequant_sources_for_base,
)
- source = resolve_te_prequant_source(fam, "text_encoder_4", "fp8")
+ source = te_prequant_sources_for_base(
+ fam,
+ HIDREAM_LLAMA_REPO,
+ te_quant_mode = te_quant_mode,
+ target = target,
+ components = ("text_encoder_4",),
+ standalone_component_bases = {"text_encoder_4": HIDREAM_LLAMA_REPO},
+ ).get("text_encoder_4")
if source is not None:
encoder = load_prequant_text_encoder(
HIDREAM_LLAMA_REPO,
@@ -108,6 +116,7 @@ def hidream_te4_kwargs(
"output_hidden_states": True,
"output_attentions": True,
},
+ local_files_only = local_files_only,
)
if encoder is not None:
return {"text_encoder_4": encoder, "tokenizer_4": tokenizer_4}
diff --git a/studio/backend/core/inference/diffusion_te_prequant.py b/studio/backend/core/inference/diffusion_te_prequant.py
index 8e0ec8a86f5..c7f5078bcbc 100644
--- a/studio/backend/core/inference/diffusion_te_prequant.py
+++ b/studio/backend/core/inference/diffusion_te_prequant.py
@@ -69,7 +69,9 @@ TE_PREQUANT_COMPONENTS = ("text_encoder", "text_encoder_2", "text_encoder_3")
TE_PREQUANT_BUDGET_SCALE = 0.65
-def te_prequant_budget_scale(fam: Any, *, te_quant_mode: Optional[str], target: Any) -> float:
+def te_prequant_budget_scale(
+ fam: Any, *, te_quant_mode: Optional[str], target: Any, base: str
+) -> float:
"""Scale to apply to a family's bf16 text-encoder size when budgeting memory for this pick:
``TE_PREQUANT_BUDGET_SCALE`` when the load takes its encoder PRE-CAST from a hosted fp8
checkpoint, else 1.0.
@@ -84,7 +86,12 @@ def te_prequant_budget_scale(fam: Any, *, te_quant_mode: Optional[str], target:
Best-effort like the rest of this module: anything unresolvable returns 1.0, i.e. today's
bf16 budget."""
try:
- sources = te_prequant_sources(fam, te_quant_mode = te_quant_mode, target = target)
+ sources = te_prequant_sources_for_base(
+ fam,
+ base,
+ te_quant_mode = te_quant_mode,
+ target = target,
+ )
except Exception: # noqa: BLE001 -- an unresolvable pre-cast just means the dense encoder
return 1.0
return TE_PREQUANT_BUDGET_SCALE if sources else 1.0
@@ -92,13 +99,24 @@ def te_prequant_budget_scale(fam: Any, *, te_quant_mode: Optional[str], target:
# Bases whose text-encoder weights are VERIFIED byte-identical (every shard LFS sha256 compared on 2026-07-18), so one hosted artifact serves them all. The validator accepts a base_model_id from the same group; anything else keeps the strict refusal.
_TE_EQUIVALENT_BASES: tuple[frozenset[str], ...] = (
- # Qwen2.5-VL-7B text encoder: 4 shards, 16,584,414,544 bytes, identical sha256 set.
+ # Qwen2.5-VL-7B text encoder: 4 shards, 16,584,414,544 bytes, identical sha256 set. Qwen-Image-2512
+ # republishes the same four shards (re-verified 2026-08-25); refusing it here would pull 16.6 GB
+ # of dense encoder the load never opens.
frozenset(
{
"qwen/qwen-image",
+ "qwen/qwen-image-2512",
"hunyuanvideo-community/hunyuanimage-2.1-diffusers",
}
),
+ # Qwen3-4B text encoder: 1 shard, 8,875,715,136 bytes, identical sha256 across the Krea-2 pair
+ # (compared 2026-08-25); only their transformers differ, as with Z-Image.
+ frozenset(
+ {
+ "krea/krea-2-turbo",
+ "krea/krea-2-raw",
+ }
+ ),
# T5-XXL (text_encoder_2): 2 shards, 9,524,648,584 bytes, identical sha256 across every FLUX.1 release; HiDream-I1 ships the same bytes as text_encoder_3 (cross-component mapping is not wired yet).
frozenset(
{
@@ -197,11 +215,18 @@ def resolve_te_prequant_source(
def te_prequant_sources(
- fam: Any, *, te_quant_mode: Optional[str], target: Any
+ fam: Any,
+ *,
+ te_quant_mode: Optional[str],
+ target: Any,
+ components: Iterable[str] = TE_PREQUANT_COMPONENTS,
) -> dict[str, TePrequantSource]:
"""``{component: source}`` for every text encoder this pick would load PRE-CAST rather
than dense; ``{}`` when none apply.
+ ``components`` defaults to the generic pipeline injection set; callers that assemble an
+ additional component separately may request it explicitly.
+
Pure (no IO, no ``torch.load``) and gated exactly like ``te_prequant_pipe_kwargs``
below, which calls it. Download planning uses the same resolver so a plan can never
disagree with the load about which dense encoders are still needed -- staging the dense
@@ -226,15 +251,49 @@ def te_prequant_sources(
if not te_quant_supported(target, mode):
return {}
sources: dict[str, TePrequantSource] = {}
- for component in TE_PREQUANT_COMPONENTS:
+ for component in components:
source = resolve_te_prequant_source(fam, component, mode)
if source is not None:
sources[component] = source
return sources
- except Exception: # noqa: BLE001 — an unresolvable pre-cast just means the dense encoder
+ except Exception: # noqa: BLE001 -- fall back to the dense encoder
return {}
+def te_prequant_sources_for_base(
+ fam: Any,
+ base: str,
+ *,
+ te_quant_mode: Optional[str],
+ target: Any,
+ components: Iterable[str] = TE_PREQUANT_COMPONENTS,
+ standalone_component_bases: Optional[dict[str, str]] = None,
+) -> dict[str, TePrequantSource]:
+ """Pre-cast sources whose registered encoder base matches the selected base.
+
+ A family match alone is insufficient for a custom pipeline. The hosted checkpoint was
+ built from the family's registered base, so selecting it for another base would download
+ the artifact before checkpoint metadata could reject it. Components loaded from their own
+ standalone repos may map both sides of this comparison through
+ ``standalone_component_bases``.
+ """
+ sources = te_prequant_sources(
+ fam,
+ te_quant_mode = te_quant_mode,
+ target = target,
+ components = components,
+ )
+ registered_base = str(getattr(fam, "base_repo", "") or "")
+ standalone = standalone_component_bases or {}
+ compatible: dict[str, TePrequantSource] = {}
+ for component, source in sources.items():
+ checkpoint_base = standalone.get(component) or registered_base
+ selected_base = standalone.get(component) or base
+ if checkpoint_base and selected_base and te_base_equivalent(checkpoint_base, selected_base):
+ compatible[component] = source
+ return compatible
+
+
# Weight files a dense encoder folder holds. Everything else (config.json, the shard index, tokenizer JSON) is kept when the pre-cast checkpoint replaces the weights: the pre-cast loader still meta-inits from the base repo component config.
_TE_WEIGHT_SUFFIXES = (".safetensors", ".bin", ".pth", ".pt", ".msgpack", ".h5")
@@ -259,6 +318,7 @@ def load_prequant_text_encoder(
logger: Any = None,
config_subfolder: Optional[str] = None,
config_overrides: Optional[dict] = None,
+ local_files_only: bool = False,
) -> Optional[Any]:
"""Load the pre-cast text encoder described by ``source`` (on CPU, for pipeline
assembly to place), with the layerwise upcast hooks already installed.
@@ -285,7 +345,15 @@ def load_prequant_text_encoder(
)
return None
- path = _resolve_checkpoint_path(source, hf_token)
+ from utils.hf_cache_settings import active_hf_hub_cache
+
+ cache_dir = active_hf_hub_cache()
+ path = _resolve_checkpoint_path(
+ source,
+ hf_token,
+ cache_dir = cache_dir,
+ local_files_only = local_files_only,
+ )
if path is None:
return None
@@ -309,7 +377,11 @@ def load_prequant_text_encoder(
)
return None
subfolder = component if config_subfolder is None else config_subfolder
- config_kwargs: dict[str, Any] = {"token": hf_token}
+ config_kwargs: dict[str, Any] = {
+ "token": hf_token,
+ "cache_dir": cache_dir,
+ "local_files_only": local_files_only,
+ }
if subfolder:
config_kwargs["subfolder"] = subfolder
config = transformers.AutoConfig.from_pretrained(base, **config_kwargs)
@@ -366,6 +438,7 @@ def te_prequant_pipe_kwargs(
dtype: Any,
hf_token: Optional[str] = None,
logger: Any = None,
+ local_files_only: bool = False,
) -> dict[str, Any]:
"""Component overrides for pipeline assembly: ``{<component>: <pre-cast encoder>}``
for every ``TE_PREQUANT_COMPONENTS`` attr the family hosts a pre-cast checkpoint for
@@ -379,7 +452,12 @@ def te_prequant_pipe_kwargs(
try:
from .diffusion_precision import TE_QUANT_FP8
- sources = te_prequant_sources(fam, te_quant_mode = te_quant_mode, target = target)
+ sources = te_prequant_sources_for_base(
+ fam,
+ base,
+ te_quant_mode = te_quant_mode,
+ target = target,
+ )
# Non-empty only for the one hosted scheme (see te_prequant_sources' gate).
mode = TE_QUANT_FP8
injected: dict[str, Any] = {}
@@ -392,6 +470,7 @@ def te_prequant_pipe_kwargs(
hf_token = hf_token,
scheme = mode,
logger = logger,
+ local_files_only = local_files_only,
)
if encoder is not None:
injected[component] = encoder
@@ -401,7 +480,13 @@ def te_prequant_pipe_kwargs(
return {}
-def _resolve_checkpoint_path(source: TePrequantSource, hf_token: Optional[str]) -> Optional[str]:
+def _resolve_checkpoint_path(
+ source: TePrequantSource,
+ hf_token: Optional[str],
+ *,
+ cache_dir: str,
+ local_files_only: bool = False,
+) -> Optional[str]:
"""The local file path for ``source``, downloading from the Hub if needed; None if absent."""
if source.kind == "path":
import os
@@ -409,7 +494,13 @@ def _resolve_checkpoint_path(source: TePrequantSource, hf_token: Optional[str])
return expanded if os.path.isfile(expanded) else None
if source.kind == "repo":
from huggingface_hub import hf_hub_download
- return hf_hub_download(repo_id = source.location, filename = source.filename, token = hf_token)
+ return hf_hub_download(
+ repo_id = source.location,
+ filename = source.filename,
+ token = hf_token,
+ cache_dir = cache_dir,
+ local_files_only = local_files_only,
+ )
return None
diff --git a/studio/backend/core/inference/media_locality.py b/studio/backend/core/inference/media_locality.py
index 567a6c355f4..b9dfe80904c 100644
--- a/studio/backend/core/inference/media_locality.py
+++ b/studio/backend/core/inference/media_locality.py
@@ -506,6 +506,11 @@ def missing_download_bytes(
model_kind = target.model_kind,
gpu_ordinal = ordinal,
hf_token = hf_token,
+ # Only the verdict, not the probe: this asks whether the pick is already on
+ # disk, so it must count the SAME files the load will fetch. Clearing the probe
+ # drops the pre-cast encoder and the GGUF dense-transformer widening, which is
+ # how a "fully downloaded" answer goes wrong.
+ memory_verdict = False,
)
or {}
for planner in planners_for(owner, target)
diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.py
index e18a13a2222..ad46d3f860a 100644
--- a/studio/backend/core/inference/video.py
+++ b/studio/backend/core/inference/video.py
@@ -1451,7 +1451,10 @@ class VideoBackend:
kwargs["base_repo"] = base
# An fp8 encoder request loads a hosted pre-cast checkpoint, so neither the estimate nor the pull includes those dense shards.
te_sources = self._te_prequant_sources(
- fam, kwargs.get("text_encoder_quant"), kwargs.get("gpu_ordinal")
+ fam,
+ kwargs.get("text_encoder_quant"),
+ kwargs.get("gpu_ordinal"),
+ base = base,
)
# The same deal for the denoiser: a hosted pre-quantized checkpoint replaces the dense
# DiT shards, so the estimate and the scoped pull below both drop them. VERIFIED, like
@@ -2042,12 +2045,14 @@ class VideoBackend:
fam: Any,
text_encoder_quant: Optional[str],
gpu_ordinal: Optional[int] = None,
+ base: Optional[str] = None,
) -> dict[str, Any]:
"""``{component: source}`` for the text encoders this load will take PRE-CAST from a
hosted checkpoint instead of the base repo's dense weights (``{}`` when none)."""
- from .diffusion_te_prequant import te_prequant_sources
- return te_prequant_sources(
+ from .diffusion_te_prequant import te_prequant_sources_for_base
+ return te_prequant_sources_for_base(
fam,
+ base or str(getattr(fam, "base_repo", "") or ""),
te_quant_mode = text_encoder_quant,
# The selected card: an fp8 encoder the default card cannot take is still hosted
# pre-cast for the one this load lands on, and vice versa.
@@ -2894,7 +2899,10 @@ class VideoBackend:
)
# Pre-cast encoders first: only a checkpoint that really resolves earns the right to drop the dense shards.
te_sources = self._te_prequant_sources(
- fam, text_encoder_quant, load_kwargs.get("gpu_ordinal")
+ fam,
+ text_encoder_quant,
+ load_kwargs.get("gpu_ordinal"),
+ base = base,
)
te_files = self._te_prequant_hub_files(te_sources, api)
for component, files in te_files.items():
@@ -3513,7 +3521,12 @@ class VideoBackend:
# families widen it), so only components[1] is scaled.
from .diffusion_te_prequant import te_prequant_budget_scale
- te_scale = te_prequant_budget_scale(fam, te_quant_mode = text_encoder_quant, target = target)
+ te_scale = te_prequant_budget_scale(
+ fam,
+ te_quant_mode = text_encoder_quant,
+ target = target,
+ base = repo_id if kind == "pipeline" else base,
+ )
transformer_mib: Optional[int] = None
if kind != "pipeline":
checkpoint_path = self._resolve_checkpoint_path(
@@ -3657,6 +3670,7 @@ class VideoBackend:
dtype = dtype,
hf_token = hf_token,
logger = logger,
+ local_files_only = local_files_only,
)
pipe_kwargs.update(te_injected)
# The fp8-sized budget is valid only once the pre-cast encoder is actually in hand. Injection is best-effort
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index bc1ddd84304..cf89d2c57ac 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -26352,6 +26352,12 @@ async def diffusion_download_plan(
cpu_offload = request.cpu_offload,
transformer_prequant_path = request.transformer_prequant_path,
loras = request.loras,
+ # Only the verdict, not the probe: the panel stages exactly what this reports.
+ # Clearing the probe drops the hosted DiT prequant, so a GGUF pick naming an explicit
+ # transformer_quant reports ~21 GB short, stages that, says done, and the load pulls
+ # the checkpoint inline. The probe kept here is the pre-existing one: a capability
+ # read plus total_mib, never free VRAM and never an allocation.
+ memory_verdict = not training,
)
return DiffusionDownloadPlanResponse(**plan)
except (ValueError, FileNotFoundError) as exc:
diff --git a/studio/backend/tests/test_diffusion_backend.py b/studio/backend/tests/test_diffusion_backend.py
index 7e97f675ca7..a234f67fc87 100644
--- a/studio/backend/tests/test_diffusion_backend.py
+++ b/studio/backend/tests/test_diffusion_backend.py
@@ -6895,14 +6895,15 @@ def test_download_plan_flags_a_mirrored_pipeline_as_the_checkpoint(monkeypatch):
# The page used to derive the label by comparing those two ids, which made every file of the
# selected model read as "Required assets". Only the planner knows about the swap.
gated = "black-forest-labs/FLUX.1-dev"
- _fake_hf_api(monkeypatch, {gated: _FLUX_BASE_SIBLINGS})
+ mirror = "unsloth/FLUX.1-dev"
+ _fake_hf_api(monkeypatch, {gated: _FLUX_BASE_SIBLINGS, mirror: _FLUX_BASE_SIBLINGS})
_no_cache(monkeypatch)
plan = DiffusionBackend().download_plan(gated, model_kind = "pipeline")
assert len(plan["entries"]) == 1
entry = plan["entries"][0]
- assert entry["repo_id"] == "unsloth/FLUX.1-dev" != gated
+ assert entry["repo_id"] == mirror != gated
assert entry["checkpoint"] is True
@@ -6945,7 +6946,7 @@ def test_download_plan_stages_the_precast_encoder_instead_of_the_dense_one(monke
# The pick resolves one hosted pre-cast encoder for text_encoder_2 (flux.1 hosts its T5-XXL).
monkeypatch.setattr(
"core.inference.diffusion_te_prequant.te_prequant_sources",
- lambda fam, *, te_quant_mode, target: (
+ lambda fam, *, te_quant_mode, target, **_kwargs: (
{
"text_encoder_2": types.SimpleNamespace(
kind = "repo",
@@ -10203,7 +10204,7 @@ def test_the_resident_size_table_prices_a_pre_cast_encoder_at_its_real_size(
monkeypatch.setattr(dmod, "family_bf16_components_gb", dmod.family_bf16_components_gb)
monkeypatch.setattr(
"core.inference.diffusion_te_prequant.te_prequant_sources",
- lambda fam, te_quant_mode = None, target = None: {"text_encoder": object()},
+ lambda fam, te_quant_mode = None, target = None, **_kwargs: {"text_encoder": object()},
)
precast = backend._resident_sized_plan(
plan, fam, base, target, "pipeline", text_encoder_quant = "fp8"
@@ -10302,7 +10303,6 @@ def test_the_prequant_fit_check_prices_a_pre_cast_text_encoder(fake_runtime, mon
already applies te_prequant_budget_scale; this is the same scale on the same estimate."""
from core.inference.diffusion import DiffusionBackend
from core.inference.diffusion_families import detect_family
- from core.inference.diffusion_te_prequant import TE_PREQUANT_BUDGET_SCALE
fam = detect_family("black-forest-labs/FLUX.2-dev")
assert fam is not None and fam.te_prequant_repos, "the fixture family lost its pre-cast repo"
@@ -10310,43 +10310,35 @@ def test_the_prequant_fit_check_prices_a_pre_cast_text_encoder(fake_runtime, mon
encoders = 48_000
candidate = types.SimpleNamespace(companions_mib = encoders + 400, text_encoders_mib = encoders)
- scaled = DiffusionBackend._precast_scaled_companions_mib(candidate, fam, object(), "fp8")
- # No pre-cast encoder resolves in this environment unless te_prequant_sources says so, so pin
- # the two outcomes on the resolver rather than assuming one.
- from core.inference.diffusion_te_prequant import te_prequant_sources
+ base = "black-forest-labs/FLUX.2-dev"
+ seen: dict = {}
+
+ def _scale(_fam, *, te_quant_mode, target, base):
+ seen.update(mode = te_quant_mode, target = target, base = base)
+ return 0.5 if te_quant_mode == "fp8" else 1.0
- if te_prequant_sources(fam, te_quant_mode = "fp8", target = object()):
- assert scaled == 400 + int(encoders * TE_PREQUANT_BUDGET_SCALE)
- assert scaled < candidate.companions_mib
- else:
- assert scaled == candidate.companions_mib
+ monkeypatch.setattr("core.inference.diffusion_te_prequant.te_prequant_budget_scale", _scale)
+ scaled = DiffusionBackend._precast_scaled_companions_mib(candidate, fam, base, object(), "fp8")
+ assert scaled == 24_400
+ assert seen["mode"] == "fp8"
+ assert seen["base"] == base
# No encoder quant requested: the estimate is passed through untouched, byte for byte.
assert (
- DiffusionBackend._precast_scaled_companions_mib(candidate, fam, object(), None)
+ DiffusionBackend._precast_scaled_companions_mib(candidate, fam, base, object(), None)
== candidate.companions_mib
)
# The VAE share is never scaled, and a candidate with no split degrades to the dense total.
no_split = types.SimpleNamespace(companions_mib = 1234, text_encoders_mib = 0)
- assert DiffusionBackend._precast_scaled_companions_mib(no_split, fam, object(), "fp8") == 1234
+ assert (
+ DiffusionBackend._precast_scaled_companions_mib(no_split, fam, base, object(), "fp8")
+ == 1234
+ )
# An estimate with no companions at all stays None, which _plan_memory reads as "no override".
empty = types.SimpleNamespace(companions_mib = None)
- assert DiffusionBackend._precast_scaled_companions_mib(empty, fam, object(), "fp8") is None
-
-
-def test_the_pre_cast_companion_scale_matches_the_load_level_plan(fake_runtime, monkeypatch):
- """Both sides must read the same scale from the same resolver, or the fit check and the plan
- it gates disagree about what the load builds."""
- from core.inference.diffusion import DiffusionBackend
- from core.inference.diffusion_families import detect_family
-
- fam = detect_family("black-forest-labs/FLUX.2-dev")
- monkeypatch.setattr(
- "core.inference.diffusion_te_prequant.te_prequant_budget_scale",
- lambda fam, *, te_quant_mode, target: 0.5 if te_quant_mode == "fp8" else 1.0,
+ assert (
+ DiffusionBackend._precast_scaled_companions_mib(empty, fam, base, object(), "fp8") is None
)
- candidate = types.SimpleNamespace(companions_mib = 10_400, text_encoders_mib = 10_000)
- assert DiffusionBackend._precast_scaled_companions_mib(candidate, fam, object(), "fp8") == 5_400
def test_an_offload_memory_request_is_not_reported_as_unstaged_shards(
diff --git a/studio/backend/tests/test_diffusion_predownload_guard_platforms.py b/studio/backend/tests/test_diffusion_predownload_guard_platforms.py
new file mode 100644
index 00000000000..c6ec0809f63
--- /dev/null
+++ b/studio/backend/tests/test_diffusion_predownload_guard_platforms.py
@@ -0,0 +1,440 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Where the pre-download guard from issue #9130 is allowed to speak, and what it does when
+the Hub answers badly.
+
+test_diffusion_predownload_memory_guard.py hand-builds a DeviceMemory, which proves the
+arithmetic but assumes the classification. These drive the REAL ``snapshot_device_memory``
+over a faked driver, once per platform and vendor, so "discrete VRAM and plain CPU are
+untouched" is tested rather than asserted.
+
+The second half covers the one new network read: however model_index.json comes back,
+staging must fall back to the old best-effort listing rather than refuse or raise.
+"""
+
+from __future__ import annotations
+
+import json
+import sys
+import types
+
+import pytest
+
+from core.inference import diffusion as diffusion_mod
+from core.inference import diffusion_memory as memory_mod
+from core.inference.diffusion import DiffusionBackend, _pipeline_components_from_index
+from core.inference.diffusion_device import DiffusionDeviceTarget
+from core.inference.diffusion_families import detect_family_for_pick
+from core.inference.diffusion_memory import DeviceMemory, snapshot_device_memory
+
+MIB = 1024 * 1024
+GIB_MIB = 1024
+
+# unsloth/FLUX.2-dev, 112.9 GB: too large for every pool below, so a machine that keeps
+# loading it is one the guard genuinely never reaches.
+FLUX2_DEV = [
+ (f"{name}/model.safetensors", mib * MIB)
+ for name, mib in (
+ ("transformer", 61461),
+ ("text_encoder", 45798),
+ ("vae", 321),
+ ("tokenizer", 16),
+ )
+]
+# unsloth/Lumina-Image-2.0, 20 GB stored fp32: the control that must still load.
+LUMINA_2 = [
+ (f"{name}/model.safetensors", mib * MIB)
+ for name, mib in (
+ ("transformer", 9956),
+ ("text_encoder", 9973),
+ ("vae", 320),
+ ("tokenizer", 21),
+ )
+]
+
+# Every OS Studio ships on. The classifier reads the device and the driver's `integrated`
+# flag and never sys.platform, so these are here to prove that rather than to vary it.
+PLATFORMS = ("linux", "wsl", "win32", "darwin")
+
+
+def _target(
+ device = "cuda",
+ *,
+ dtype = "bfloat16",
+ vendor = "amd",
+):
+ return DiffusionDeviceTarget(
+ device = device,
+ dtype = dtype,
+ backend = device,
+ vendor = vendor,
+ supports_model_cpu_offload = True,
+ supports_default_torch_compile = False,
+ supports_pinned_transfer = True,
+ ordinal = None,
+ )
+
+
+def _classify(monkeypatch, *, device, integrated, total_mib, platform):
+ """The real snapshot_device_memory over a faked driver, as ``platform`` would see it."""
+ monkeypatch.setattr(sys, "platform", "linux" if platform == "wsl" else platform)
+ if platform == "wsl":
+ monkeypatch.setenv("WSL_DISTRO_NAME", "Ubuntu")
+ else:
+ monkeypatch.delenv("WSL_DISTRO_NAME", raising = False)
+
+ props = types.SimpleNamespace(integrated = integrated)
+ monkeypatch.setitem(
+ sys.modules,
+ "torch",
+ types.SimpleNamespace(
+ cuda = types.SimpleNamespace(
+ current_device = lambda: 0,
+ get_device_properties = lambda _i: props,
+ ),
+ xpu = None,
+ ),
+ )
+ hardware = types.ModuleType("utils.hardware")
+ hardware.trusted_mem_get_info = lambda: (total_mib * MIB, total_mib * MIB)
+ monkeypatch.setitem(sys.modules, "utils.hardware", hardware)
+ monkeypatch.setattr(memory_mod, "_system_memory_mib", lambda: (total_mib, total_mib))
+ return snapshot_device_memory(_target(device))
+
+
+def _guard(
+ monkeypatch,
+ snapshot,
+ *,
+ device = "cuda",
+ dtype = "bfloat16",
+):
+ backend = DiffusionBackend()
+ monkeypatch.setattr(
+ backend, "_target_for_ordinal", lambda *_a, **_k: _target(device, dtype = dtype)
+ )
+ monkeypatch.setattr(diffusion_mod, "snapshot_device_memory", lambda _t: snapshot)
+
+ def verdict(files):
+ return backend.declared_footprint_shortfall(
+ types.SimpleNamespace(name = "flux.2-dev", base_repo = "black-forest-labs/FLUX.2-dev"),
+ "unsloth/FLUX.2-dev",
+ "black-forest-labs/FLUX.2-dev",
+ kind = "pipeline",
+ declared_files = files,
+ )
+
+ return verdict
+
+
[email protected]("platform", PLATFORMS)
[email protected]("total_mib", [8 * GIB_MIB, 24 * GIB_MIB, 96 * GIB_MIB])
+def test_a_discrete_card_keeps_loading_what_it_loads_today(monkeypatch, platform, total_mib):
+ """Discrete VRAM has somewhere to offload to, so an oversized pipeline still loads and
+ streams from host RAM. Asserted at three card sizes because the refusal must be keyed
+ on the memory KIND and never on the pipeline being larger than the card."""
+ snapshot = _classify(
+ monkeypatch,
+ device = "cuda",
+ integrated = False,
+ total_mib = total_mib,
+ platform = platform,
+ )
+ assert snapshot.memory_kind == "discrete_vram"
+ assert _guard(monkeypatch, snapshot)(FLUX2_DEV) is None
+
+
[email protected]("platform", ["linux", "wsl", "win32"])
+def test_an_integrated_gpu_is_the_one_machine_that_is_judged(monkeypatch, platform):
+ """gfx1151 and the other APUs: one pool, no offload target, so the OS kills an
+ oversized load outright. Refused before the download, and a model that fits is not."""
+ snapshot = _classify(
+ monkeypatch,
+ device = "cuda",
+ integrated = True,
+ total_mib = 64 * GIB_MIB,
+ platform = platform,
+ )
+ assert snapshot.memory_kind == "unified_memory"
+ verdict = _guard(monkeypatch, snapshot)
+ assert verdict(FLUX2_DEV) is not None
+ assert verdict(LUMINA_2) is None
+
+
+def test_apple_silicon_is_judged_the_same_way(monkeypatch):
+ snapshot = _classify(
+ monkeypatch,
+ device = "mps",
+ integrated = False,
+ total_mib = 36 * GIB_MIB,
+ platform = "darwin",
+ )
+ assert snapshot.memory_kind == "unified_memory"
+ verdict = _guard(monkeypatch, snapshot, device = "mps")
+ assert verdict(FLUX2_DEV) is not None
+ assert verdict(LUMINA_2) is None
+
+
[email protected]("platform", PLATFORMS)
+def test_a_cpu_only_host_is_left_alone(monkeypatch, platform):
+ """``system_memory`` is deliberately outside the refusal: it has swap, and it is not
+ what gets killed. The pre-download check has to honour the same carve-out the load-time
+ one already makes, or a CPU install starts refusing models it can page through."""
+ snapshot = _classify(
+ monkeypatch,
+ device = "cpu",
+ integrated = False,
+ total_mib = 16 * GIB_MIB,
+ platform = platform,
+ )
+ assert snapshot.memory_kind == "system_memory"
+ assert _guard(monkeypatch, snapshot, device = "cpu")(FLUX2_DEV) is None
+
+
+def test_an_intel_gpu_is_left_alone(monkeypatch):
+ snapshot = _classify(
+ monkeypatch,
+ device = "xpu",
+ integrated = False,
+ total_mib = 16 * GIB_MIB,
+ platform = "linux",
+ )
+ assert snapshot.memory_kind == "discrete_vram"
+ assert _guard(monkeypatch, snapshot, device = "xpu")(FLUX2_DEV) is None
+
+
+def test_a_driver_that_will_not_answer_is_left_alone(monkeypatch):
+ """An uninitialised or absent CUDA runtime yields no totals, which is not evidence
+ that anything is too large."""
+ monkeypatch.setattr(sys, "platform", "linux")
+ monkeypatch.setitem(
+ sys.modules,
+ "torch",
+ types.SimpleNamespace(
+ cuda = types.SimpleNamespace(
+ current_device = lambda: 0,
+ get_device_properties = lambda _i: (_ for _ in ()).throw(RuntimeError("no ctx")),
+ ),
+ ),
+ )
+ hardware = types.ModuleType("utils.hardware")
+ hardware.trusted_mem_get_info = lambda: (_ for _ in ()).throw(RuntimeError("driver"))
+ monkeypatch.setitem(sys.modules, "utils.hardware", hardware)
+ snapshot = snapshot_device_memory(_target("cuda"))
+ assert snapshot.memory_kind == "discrete_vram" and snapshot.total_mib is None
+ assert _guard(monkeypatch, snapshot)(FLUX2_DEV) is None
+
+
[email protected]("memory_mode", [None, "auto", "fast", "balanced", "low_vram"])
[email protected]("cpu_offload", [False, True])
+def test_no_offload_request_can_talk_a_shared_pool_into_it(monkeypatch, memory_mode, cpu_offload):
+ """Offloading inside one pool frees nothing, so no requested mode may turn the refusal
+ off -- and none of them may turn it ON for a model that fits either."""
+ backend = DiffusionBackend()
+ monkeypatch.setattr(backend, "_target_for_ordinal", lambda *_a, **_k: _target())
+ monkeypatch.setattr(
+ diffusion_mod,
+ "snapshot_device_memory",
+ lambda _t: DeviceMemory("cuda", "cuda", "unified_memory", 64 * GIB_MIB, 64 * GIB_MIB),
+ )
+
+ def verdict(files, base):
+ return backend.declared_footprint_shortfall(
+ types.SimpleNamespace(name = "flux.2-dev", base_repo = base),
+ "unsloth/FLUX.2-dev",
+ base,
+ kind = "pipeline",
+ declared_files = files,
+ memory_mode = memory_mode,
+ cpu_offload = cpu_offload,
+ )
+
+ assert verdict(FLUX2_DEV, "black-forest-labs/FLUX.2-dev") is not None
+ assert verdict(LUMINA_2, "Alpha-VLLM/Lumina-Image-2.0") is None
+
+
+# ── the manifest read ─────────────────────────────────────────────────────────
+
+_MANIFEST = {
+ "_class_name": "FluxPipeline",
+ "transformer": ["diffusers", "FluxTransformer2DModel"],
+ "text_encoder": ["transformers", "CLIPTextModel"],
+ "vae": ["diffusers", "AutoencoderKL"],
+ "safety_checker": [None, None],
+ "_ignore_files": ["transformer/diffusion_pytorch_model.fp16.safetensors"],
+}
+
+
+def _info(*, siblings = ("model_index.json",), sha = "deadbeef"):
+ return types.SimpleNamespace(
+ siblings = None
+ if siblings is None
+ else [types.SimpleNamespace(rfilename = name) for name in siblings],
+ sha = sha,
+ )
+
+
+def _stub_manifest(
+ monkeypatch,
+ tmp_path,
+ payload,
+ *,
+ raises = None,
+):
+ calls: list = []
+
+ def _download(repo_id, filename, **kwargs):
+ calls.append((repo_id, filename, kwargs.get("revision")))
+ if raises is not None:
+ raise raises
+ path = tmp_path / "model_index.json"
+ path.write_text(payload if isinstance(payload, str) else json.dumps(payload))
+ return str(path)
+
+ import huggingface_hub
+
+ monkeypatch.setattr(huggingface_hub, "hf_hub_download", _download)
+ return calls
+
+
+def test_the_manifest_names_the_components_and_the_revision_it_was_read_at(monkeypatch, tmp_path):
+ calls = _stub_manifest(monkeypatch, tmp_path, _MANIFEST)
+ selected, ignored = _pipeline_components_from_index("repo", _info(sha = "abc123"), None)
+ # A component declared [None, None] is not loaded, so its files are not priced.
+ assert selected == frozenset({"transformer", "text_encoder", "vae"})
+ assert ignored == frozenset({"transformer/diffusion_pytorch_model.fp16.safetensors"})
+ assert calls == [("repo", "model_index.json", "abc123")]
+
+
+ "payload, siblings, raises",
+ [
+ ("{not json", ("model_index.json",), None),
+ ("[1, 2, 3]", ("model_index.json",), None),
+ ('"a string"', ("model_index.json",), None),
+ ("null", ("model_index.json",), None),
+ ({}, ("model_index.json",), None),
+ ({"_class_name": "FluxPipeline"}, ("model_index.json",), None),
+ ({"safety_checker": [None, None]}, ("model_index.json",), None),
+ ({"transformer": "not-a-list"}, ("model_index.json",), None),
+ ({"transformer": ["diffusers"]}, ("model_index.json",), None),
+ (_MANIFEST, ("transformer/model.safetensors",), None),
+ (_MANIFEST, (), None),
+ (_MANIFEST, None, None),
+ (_MANIFEST, ("model_index.json",), OSError("hub unreachable")),
+ (_MANIFEST, ("model_index.json",), PermissionError("gated")),
+ ],
+ ids = [
+ "invalid-json",
+ "a-list",
+ "a-string",
+ "null",
+ "empty",
+ "only-private-keys",
+ "every-component-disabled",
+ "malformed-spec",
+ "short-spec",
+ "no-manifest-listed",
+ "empty-listing",
+ "null-listing",
+ "download-fails",
+ "download-401s",
+ ],
+)
+def test_a_manifest_that_cannot_be_read_declines_instead_of_raising(
+ monkeypatch, tmp_path, payload, siblings, raises
+):
+ """None here means staging keeps the previous best-effort listing and resident sizing
+ issues no hard verdict, which is the whole fail-open contract."""
+ _stub_manifest(monkeypatch, tmp_path, payload, raises = raises)
+ failures: list = []
+ assert (
+ _pipeline_components_from_index(
+ "repo", _info(siblings = siblings), None, failures_out = failures
+ )
+ is None
+ )
+ assert len(failures) == 1
+
+
+def test_an_ignore_list_of_the_wrong_shape_is_tolerated(monkeypatch, tmp_path):
+ _stub_manifest(monkeypatch, tmp_path, dict(_MANIFEST, _ignore_files = "not-a-list"))
+ selected, ignored = _pipeline_components_from_index("repo", _info(), None)
+ assert selected == frozenset({"transformer", "text_encoder", "vae"})
+ assert ignored == frozenset()
+
+
+# ── the two switches the plan exposes ─────────────────────────────────────────
+
+
+def _plan_probe(monkeypatch, calls):
+ """A download_plan whose device-dependent steps announce themselves."""
+ backend = DiffusionBackend()
+ # The real registry entry: download_plan reads more of it than a stub can carry.
+ fam = detect_family_for_pick("unsloth/FLUX.2-dev", None, None)
+ assert fam is not None
+ monkeypatch.setattr(diffusion_mod, "detect_family_for_pick", lambda *_a, **_k: fam)
+ monkeypatch.setattr(diffusion_mod, "prefer_ungated_mirror", lambda base, *_a, **_k: base)
+ monkeypatch.setattr(diffusion_mod, "_assert_base_repo_accessible", lambda *_a, **_k: None)
+ monkeypatch.setattr(diffusion_mod, "flux2_pick_mismatch", lambda *_a, **_k: None)
+ monkeypatch.setattr(diffusion_mod, "speech_pick_refusal", lambda *_a, **_k: None)
+ monkeypatch.setattr(backend, "_target_for_ordinal", lambda *_a, **_k: _target())
+ monkeypatch.setattr(
+ diffusion_mod,
+ "snapshot_device_memory",
+ lambda _t: DeviceMemory("cuda", "cuda", "unified_memory", 64 * GIB_MIB, 64 * GIB_MIB),
+ )
+
+ def _te(*_a, **_k):
+ calls.append("te_prequant")
+ return {}
+
+ def _dit(*_a, **_k):
+ calls.append("dit_prequant")
+ return None
+
+ def _estimate(*_a, **kwargs):
+ out = kwargs.get("file_sizes_out")
+ if out is not None:
+ out["unsloth/FLUX.2-dev"] = {name: size for name, size in FLUX2_DEV}
+ resident = kwargs.get("resident_file_sizes_out")
+ if resident is not None:
+ resident.extend(FLUX2_DEV)
+ return sum(size for _name, size in FLUX2_DEV), []
+
+ monkeypatch.setattr(DiffusionBackend, "_te_prequant_plan_files", _te)
+ monkeypatch.setattr(DiffusionBackend, "_dit_prequant_plan_source", _dit)
+ monkeypatch.setattr(DiffusionBackend, "_estimate_download_bytes", staticmethod(_estimate))
+ return backend
+
+
+def test_suppressing_the_verdict_leaves_the_file_scope_alone(monkeypatch):
+ """``memory_verdict=False`` is for callers that want today's plan and no refusal --
+ a byte count taken over a different file list than the load will fetch is how a
+ "fully downloaded" answer goes wrong."""
+ calls: list = []
+ backend = _plan_probe(monkeypatch, calls)
+ plan = backend.download_plan("unsloth/FLUX.2-dev", model_kind = "pipeline", memory_verdict = False)
+ assert plan["incompatible_reason"] is None
+ assert calls == ["te_prequant", "dit_prequant"]
+
+
+def test_clearing_the_probe_suppresses_the_verdict_too(monkeypatch):
+ """The training route wants both off: it must not open a second CUDA context, and
+ without a target it cannot resolve precision at all."""
+ calls: list = []
+ backend = _plan_probe(monkeypatch, calls)
+ plan = backend.download_plan(
+ "unsloth/FLUX.2-dev", model_kind = "pipeline", allow_device_probe = False
+ )
+ assert plan["incompatible_reason"] is None
+ assert calls == []
+
+
+def test_the_default_plan_still_refuses_an_oversized_pipeline(monkeypatch):
+ calls: list = []
+ backend = _plan_probe(monkeypatch, calls)
+ plan = backend.download_plan("unsloth/FLUX.2-dev", model_kind = "pipeline")
+ assert plan["incompatible_reason"] is not None
+ assert "unified memory" in plan["incompatible_reason"]
diff --git a/studio/backend/tests/test_diffusion_predownload_memory_guard.py b/studio/backend/tests/test_diffusion_predownload_memory_guard.py
new file mode 100644
index 00000000000..b5b407bb4e4
--- /dev/null
+++ b/studio/backend/tests/test_diffusion_predownload_memory_guard.py
@@ -0,0 +1,804 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Hermetic tests for the pre-download unified-memory guard from issue #9130.
+
+Hub sizes recorded on 2026-08-24 are aggregated by component directory.
+"""
+
+from __future__ import annotations
+
+import json
+import types
+
+import pytest
+
+from core.inference import diffusion as diffusion_mod
+from core.inference.diffusion import DiffusionBackend
+from core.inference.diffusion_device import DiffusionDeviceTarget
+from core.inference.diffusion_families import detect_family_for_pick
+from core.inference.diffusion_memory import DeviceMemory
+
+MIB = 1024 * 1024
+
+REPORTER_POOL_MIB = 104424
+STRIX_HALO_POOL_MIB = 64 * 1024
+
+
+def _files(**dirs: int) -> list:
+ return [(f"{name}/model.safetensors", mib * MIB) for name, mib in dirs.items()]
+
+
+# unsloth/Qwen-Image-2512 @ b96dde7f, 57.70 GB total.
+QWEN_IMAGE_2512 = _files(transformer = 38966, text_encoder = 15812, vae = 240, tokenizer = 10)
+
+FLUX2_DEV = _files(transformer = 61461, text_encoder = 45798, vae = 321, tokenizer = 16)
+
+Z_IMAGE_TURBO = _files(transformer = 23479, text_encoder = 7672, vae = 160, tokenizer = 15)
+
+LUMINA_2 = _files(transformer = 9956, text_encoder = 9973, vae = 320, tokenizer = 21)
+
+IDEOGRAM_4_FP8 = _files(
+ transformer = 8859,
+ unconditional_transformer = 8859,
+ text_encoder = 8373,
+ vae = 160,
+ tokenizer = 11,
+)
+
+IDEOGRAM_4_NF4 = _files(
+ transformer = 4980,
+ unconditional_transformer = 4980,
+ text_encoder = 5230,
+ vae = 160,
+ tokenizer = 11,
+)
+
+
+LUMINA_2_MINUS_DENSE_TE = _files(transformer = 9956, vae = 320, tokenizer = 21)
+LUMINA_HOSTED_TE_MIB = 3056
+LUMINA_HOSTED_TE = {
+ "text_encoder": (
+ "unsloth/Lumina-Image-2.0-fp8-te",
+ [("text_encoder_fp8.pt", LUMINA_HOSTED_TE_MIB * MIB)],
+ )
+}
+
+
+def _target(
+ *,
+ device = "cuda",
+ ordinal = None,
+ dtype = "bfloat16",
+) -> DiffusionDeviceTarget:
+ return DiffusionDeviceTarget(
+ device = device,
+ dtype = dtype,
+ backend = device,
+ vendor = "amd",
+ supports_model_cpu_offload = True,
+ supports_default_torch_compile = False,
+ supports_pinned_transfer = True,
+ ordinal = ordinal,
+ )
+
+
+def _family(name = "qwen-image", base_repo = "Qwen/Qwen-Image"):
+ return types.SimpleNamespace(name = name, base_repo = base_repo)
+
+
+def _flux2(name = "flux.2-dev", base_repo = "black-forest-labs/FLUX.2-dev"):
+ return _family(name = name, base_repo = base_repo)
+
+
+def _real_family(repo_id = "unsloth/FLUX.2-dev"):
+ fam = detect_family_for_pick(repo_id, None, None)
+ assert fam is not None
+ return fam
+
+
+def _backend(
+ monkeypatch,
+ *,
+ memory_kind = "unified_memory",
+ total_mib = REPORTER_POOL_MIB,
+ free_mib = None,
+ device = "cuda",
+ dtype = "bfloat16",
+):
+ backend = DiffusionBackend()
+ target = _target(device = device, dtype = dtype)
+ monkeypatch.setattr(backend, "_target_for_ordinal", lambda *_a, **_k: target)
+ snapshot = DeviceMemory(
+ device,
+ device,
+ memory_kind,
+ free_mib if free_mib is not None else total_mib,
+ total_mib,
+ )
+ monkeypatch.setattr(diffusion_mod, "snapshot_device_memory", lambda _t: snapshot)
+ return backend
+
+
+def _verdict(backend, fam, repo, base, files):
+ return backend.declared_footprint_shortfall(
+ fam, repo, base, kind = "pipeline", declared_files = files
+ )
+
+
+def _flux_verdict(backend):
+ return _verdict(
+ backend, _flux2(), "unsloth/FLUX.2-dev", "black-forest-labs/FLUX.2-dev", FLUX2_DEV
+ )
+
+
+def test_a_pipeline_that_cannot_fit_is_refused_from_metadata_alone(monkeypatch):
+ backend = _backend(monkeypatch, total_mib = STRIX_HALO_POOL_MIB)
+ message = _flux_verdict(backend)
+ assert message is not None
+ assert "flux.2-dev" in message
+ assert "about 107 GB of memory for its weights" in message
+ assert "about 51 GB is usable" in message
+ assert "currently free" not in message
+ assert "UNSLOTH_DIFFUSION_ALLOW_OVERSIZED_LOAD=1" in message
+
+
+ ("base", "files", "prequant_bytes", "dtype_scale", "expected"),
+ [
+ pytest.param(
+ "Tongyi-MAI/Z-Image-Turbo",
+ Z_IMAGE_TURBO,
+ 0,
+ 1.0,
+ 23_479 * MIB // 2 + (7_672 + 160 + 15) * MIB,
+ id = "fp32-denoiser",
+ ),
+ pytest.param(
+ "ideogram-ai/ideogram-4-fp8",
+ IDEOGRAM_4_FP8,
+ 0,
+ 1.0,
+ 2 * sum(size for _name, size in IDEOGRAM_4_FP8),
+ id = "raw-fp8-pipeline",
+ ),
+ pytest.param(
+ "Alpha-VLLM/Lumina-Image-2.0",
+ LUMINA_2,
+ 0,
+ 1.0,
+ sum(size for _name, size in LUMINA_2) // 2,
+ id = "fp32-pipeline",
+ ),
+ pytest.param(
+ "ideogram-ai/ideogram-4-nf4-diffusers",
+ IDEOGRAM_4_NF4,
+ 0,
+ 1.0,
+ sum(size for _name, size in IDEOGRAM_4_NF4),
+ id = "custom-precision-sibling",
+ ),
+ pytest.param(
+ "Alpha-VLLM/Lumina-Image-2.0",
+ LUMINA_2_MINUS_DENSE_TE,
+ LUMINA_HOSTED_TE_MIB * MIB,
+ 1.0,
+ sum(size for _name, size in LUMINA_2_MINUS_DENSE_TE) // 2 + LUMINA_HOSTED_TE_MIB * MIB,
+ id = "hosted-prequant",
+ ),
+ pytest.param(
+ "Alpha-VLLM/Lumina-Image-2.0",
+ LUMINA_2_MINUS_DENSE_TE,
+ LUMINA_HOSTED_TE_MIB * MIB,
+ 2.0,
+ sum(size for _name, size in LUMINA_2_MINUS_DENSE_TE) + LUMINA_HOSTED_TE_MIB * MIB,
+ id = "float32-with-hosted-prequant",
+ ),
+ ],
+)
+def test_declared_sizes_are_converted_to_their_resident_precision(
+ base, files, prequant_bytes, dtype_scale, expected
+):
+ from core.inference.diffusion_auto_policy import resident_bytes_from_declared
+ assert (
+ resident_bytes_from_declared(
+ base,
+ files,
+ prequant_bytes = prequant_bytes,
+ dtype_scale = dtype_scale,
+ )
+ == expected
+ )
+
+
+# stabilityai/stable-diffusion-xl-base-1.0, 12.9 GB: unet, both text encoders and the vae are
+# all stored F32 in the DEFAULT variant (headers read 2026-08-25), and the loader skips the fp16
+# twins, so the download is twice the bf16 residency.
+SDXL_BASE = [
+ ("unet/diffusion_pytorch_model.safetensors", 9794 * MIB),
+ ("text_encoder/model.safetensors", 469 * MIB),
+ ("text_encoder_2/model.safetensors", 2650 * MIB),
+ ("vae/diffusion_pytorch_model.safetensors", 319 * MIB),
+]
+
+
+def test_an_fp32_stored_pipeline_is_not_priced_at_its_download_size(monkeypatch):
+ """SDXL is the one U-Net family, so its denoiser sits in ``unet/`` and lands in the
+ companion bucket rather than the denoiser one. Both factors therefore have to halve, or
+ a 6.5 GB bf16 pipeline prices as 12.9 GB and is refused on every 16 GB pool."""
+ from core.inference.diffusion_auto_policy import resident_bytes_from_declared
+
+ declared = sum(size for _name, size in SDXL_BASE)
+ for base in ("stabilityai/stable-diffusion-xl-base-1.0", "stabilityai/sdxl-turbo"):
+ assert resident_bytes_from_declared(base, SDXL_BASE) == declared // 2, base
+
+ fam = _family(name = "sdxl", base_repo = "stabilityai/stable-diffusion-xl-base-1.0")
+ for pool_mib in (12 * 1024, 16 * 1024, 24 * 1024):
+ backend = _backend(monkeypatch, total_mib = pool_mib)
+ assert (
+ _verdict(
+ backend, fam, "stabilityai/stable-diffusion-xl-base-1.0", fam.base_repo, SDXL_BASE
+ )
+ is None
+ ), pool_mib
+
+
+def test_float32_target_rejects_lumina_that_bf16_accepts(monkeypatch):
+ fam = _family(name = "lumina-2", base_repo = "Alpha-VLLM/Lumina-Image-2.0")
+ bf16 = _backend(monkeypatch, total_mib = 16 * 1024)
+ assert _verdict(bf16, fam, "unsloth/Lumina-Image-2.0", fam.base_repo, LUMINA_2) is None
+
+ fp32 = _backend(monkeypatch, total_mib = 16 * 1024, device = "mps", dtype = "float32")
+ message = _verdict(fp32, fam, "unsloth/Lumina-Image-2.0", fam.base_repo, LUMINA_2)
+ assert message is not None
+ assert "about 22 GB of memory for its weights" in message
+
+
+def test_only_a_compatible_prequant_can_replace_dense_encoder_shards(monkeypatch):
+ from core.inference import diffusion_te_prequant as te_prequant
+
+ source = te_prequant.TePrequantSource(
+ kind = "repo", location = "unsloth/Qwen-Image-FP8", filename = "encoder.pt"
+ )
+ monkeypatch.setattr(
+ te_prequant,
+ "te_prequant_sources",
+ lambda *_a, **_k: {"text_encoder": source},
+ )
+ monkeypatch.setattr(
+ te_prequant,
+ "te_prequant_hub_files",
+ lambda sources, *_a, **_k: {component: [("encoder.pt", 8 * MIB)] for component in sources},
+ )
+ monkeypatch.setattr(
+ diffusion_mod, "resolve_diffusion_device_target", lambda *_a, **_k: _target()
+ )
+ fam = _family(name = "qwen-image", base_repo = "Qwen/Qwen-Image")
+
+ assert (
+ DiffusionBackend._te_prequant_plan_files(
+ fam, "fp8", None, base_repo = "unsloth/custom-qwen-image"
+ )
+ == {}
+ )
+ assert "text_encoder" in DiffusionBackend._te_prequant_plan_files(
+ fam, "fp8", None, base_repo = "Qwen/Qwen-Image"
+ )
+
+
+def test_hidream_te4_uses_its_standalone_base_for_prequant_compatibility(monkeypatch):
+ from core.inference import diffusion_te_prequant as te_prequant
+
+ seen: dict = {}
+ source = te_prequant.TePrequantSource(
+ kind = "repo", location = "unsloth/HiDream-I1-Full-FP8", filename = "te4.pt"
+ )
+
+ def _sources(*_a, **kwargs):
+ seen["components"] = tuple(kwargs["components"])
+ return {"text_encoder_4": source}
+
+ monkeypatch.setattr(te_prequant, "te_prequant_sources", _sources)
+ monkeypatch.setattr(
+ te_prequant,
+ "te_prequant_hub_files",
+ lambda sources, *_a, **_k: {component: [("te4.pt", 8 * MIB)] for component in sources},
+ )
+ monkeypatch.setattr(
+ diffusion_mod, "resolve_diffusion_device_target", lambda *_a, **_k: _target()
+ )
+ fam = _family(name = "hidream-i1", base_repo = "HiDream-ai/HiDream-I1-Full")
+
+ planned = DiffusionBackend._te_prequant_plan_files(
+ fam, "fp8", None, base_repo = "HiDream-ai/HiDream-I1-Dev"
+ )
+ assert "text_encoder_4" in seen["components"]
+ assert "text_encoder_4" in planned
+
+
+def test_hidream_dense_te4_is_counted_when_no_prequant_is_selected():
+ from core.inference.diffusion import (
+ _prequant_plan_bytes,
+ _predownload_encoder_bf16_bytes,
+ )
+ from core.inference.diffusion_hidream import HIDREAM_LLAMA_BF16_BYTES
+
+ fam = _family(name = "hidream-i1", base_repo = "HiDream-ai/HiDream-I1-Full")
+ assert _predownload_encoder_bf16_bytes(fam, {}) == HIDREAM_LLAMA_BF16_BYTES
+ assert _predownload_encoder_bf16_bytes(fam, {}, pipeline_declared = False) == 0
+ hosted = {"text_encoder_4": ("unsloth/HiDream-I1-Full-FP8", [("te4.pt", 8 * MIB)])}
+ assert _prequant_plan_bytes(hosted) == 8 * MIB
+ assert _predownload_encoder_bf16_bytes(fam, hosted) == 0
+
+
+def test_discrete_vram_is_never_refused(monkeypatch):
+ backend = _backend(monkeypatch, memory_kind = "discrete_vram", total_mib = 24 * 1024)
+ assert _flux_verdict(backend) is None
+
+
+def test_the_verdict_is_capacity_not_the_free_reading(monkeypatch):
+ backend = _backend(monkeypatch, free_mib = 4 * 1024)
+ assert (
+ _verdict(
+ backend,
+ _family(),
+ "unsloth/Qwen-Image-2512",
+ "unsloth/Qwen-Image-2512",
+ QWEN_IMAGE_2512,
+ )
+ is None
+ )
+
+
[email protected]("kind", ["gguf", "single_file"])
+def test_only_a_pipeline_pick_is_judged(monkeypatch, kind):
+ backend = _backend(monkeypatch, total_mib = STRIX_HALO_POOL_MIB)
+ assert (
+ backend.declared_footprint_shortfall(
+ _flux2(),
+ "unsloth/FLUX.2-dev",
+ "black-forest-labs/FLUX.2-dev",
+ kind = kind,
+ declared_files = FLUX2_DEV,
+ )
+ is None
+ )
+
+
[email protected]("files", [None, [], [("model_index.json", 0)]])
+def test_no_sizes_does_not_resolve_a_target(monkeypatch, files):
+ backend = DiffusionBackend()
+
+ def _resolve(*_a, **_k):
+ raise AssertionError("zero metadata must not resolve a device")
+
+ monkeypatch.setattr(backend, "_target_for_ordinal", _resolve)
+ assert (
+ backend.declared_footprint_shortfall(
+ _flux2(),
+ "unsloth/FLUX.2-dev",
+ "black-forest-labs/FLUX.2-dev",
+ kind = "pipeline",
+ declared_files = files,
+ )
+ is None
+ )
+
+
+def _stub_pipeline_hub(monkeypatch, tmp_path, repos):
+ manifests = {}
+ for index, (repo, (payload, _files, _sha)) in enumerate(repos.items()):
+ manifest = tmp_path / f"model-index-{index}.json"
+ manifest.write_text(json.dumps(payload), encoding = "utf-8")
+ manifests[repo] = manifest
+ info_calls: list = []
+ download_calls: list = []
+
+ class _Api:
+ def model_info(self, repo_id, **_kwargs):
+ info_calls.append(repo_id)
+ _payload, files, sha = repos[repo_id]
+ siblings = [types.SimpleNamespace(rfilename = name, size = size) for name, size in files]
+ return types.SimpleNamespace(siblings = siblings, sha = sha)
+
+ def fake_download(repo_id, filename, **kwargs):
+ download_calls.append((repo_id, filename, kwargs.get("revision")))
+ return str(manifests[repo_id])
+
+ monkeypatch.setattr("huggingface_hub.HfApi", lambda *a, **k: _Api())
+ monkeypatch.setattr("huggingface_hub.hf_hub_download", fake_download)
+ return info_calls, download_calls
+
+
+def test_pipeline_estimate_uses_selected_components_and_default_variant(monkeypatch, tmp_path):
+ repo = "unsloth/custom-pipeline"
+ payload = {
+ "_class_name": "FluxPipeline",
+ "_ignore_files": ["transformer/ignored.safetensors"],
+ "transformer": ["diffusers", "FluxTransformer2DModel"],
+ "unused": [None, None],
+ "scheduler": ["diffusers", "FlowMatchEulerDiscreteScheduler"],
+ }
+ files = [
+ ("model_index.json", 100),
+ ("transformer/config.json", 200),
+ ("transformer/diffusion_pytorch_model.safetensors", 20 * MIB),
+ ("transformer/diffusion_pytorch_model.fp8.safetensors", 10 * MIB),
+ ("transformer/diffusion_pytorch_model.fp8-00001-of-00002.safetensors", 10 * MIB),
+ ("transformer/ignored.safetensors", 9 * MIB),
+ ("unused/diffusion_pytorch_model.safetensors", 30 * MIB),
+ ("scheduler/scheduler_config.json", 300),
+ ]
+ _stub_pipeline_hub(monkeypatch, tmp_path, {repo: (payload, files, "a" * 40)})
+ staged: dict = {}
+ resident: list = []
+ total, files = DiffusionBackend._estimate_download_bytes(
+ repo,
+ None,
+ repo,
+ None,
+ kind = "pipeline",
+ file_sizes_out = staged,
+ resident_file_sizes_out = resident,
+ )
+
+ expected = {
+ "model_index.json",
+ "transformer/config.json",
+ "transformer/diffusion_pytorch_model.safetensors",
+ "scheduler/scheduler_config.json",
+ }
+ assert set(files) == expected
+ assert set(staged[repo]) == expected
+ assert resident == [("transformer/diffusion_pytorch_model.safetensors", 20 * MIB)]
+ assert total == 20 * MIB + 600
+
+
+def test_gated_pipeline_manifest_is_read_from_the_fetch_mirror(monkeypatch, tmp_path):
+ upstream = "black-forest-labs/FLUX.2-dev"
+ mirror = "unsloth/FLUX.2-dev"
+ payload = {"transformer": ["diffusers", "Flux2Transformer2DModel"]}
+ files = [
+ ("model_index.json", 100),
+ ("transformer/diffusion_pytorch_model.safetensors", 20 * MIB),
+ ]
+ info_calls, download_calls = _stub_pipeline_hub(
+ monkeypatch, tmp_path, {mirror: (payload, files, "b" * 40)}
+ )
+ monkeypatch.setattr(
+ diffusion_mod,
+ "prefer_ungated_mirror",
+ lambda repo_id, *_a, **_k: mirror if repo_id == upstream else repo_id,
+ )
+ resident: list = []
+ revisions: dict = {}
+ fetch_repos: dict = {}
+ _total, _files = DiffusionBackend._estimate_download_bytes(
+ upstream,
+ None,
+ upstream,
+ None,
+ kind = "pipeline",
+ resident_file_sizes_out = resident,
+ revisions_out = revisions,
+ fetch_repos_out = fetch_repos,
+ )
+
+ assert info_calls == [mirror]
+ assert download_calls == [(mirror, "model_index.json", "b" * 40)]
+ assert resident == [("transformer/diffusion_pytorch_model.safetensors", 20 * MIB)]
+ assert revisions == {mirror: "b" * 40}
+ assert fetch_repos == {upstream: mirror}
+
+
+def test_pipeline_listing_restarts_when_the_exact_scope_selects_the_mirror(monkeypatch, tmp_path):
+ upstream = "black-forest-labs/FLUX.2-dev"
+ mirror = "unsloth/FLUX.2-dev"
+ payload = {"transformer": ["diffusers", "Flux2Transformer2DModel"]}
+ listings = {
+ upstream: (
+ payload,
+ [
+ ("model_index.json", 100),
+ ("transformer/diffusion_pytorch_model.safetensors", 20 * MIB),
+ ],
+ "a" * 40,
+ ),
+ mirror: (
+ {**payload, "vae": ["diffusers", "AutoencoderKL"]},
+ [
+ ("model_index.json", 101),
+ ("transformer/diffusion_pytorch_model.safetensors", 21 * MIB),
+ ("vae/diffusion_pytorch_model.safetensors", 3 * MIB),
+ ],
+ "b" * 40,
+ ),
+ }
+ info_calls, download_calls = _stub_pipeline_hub(monkeypatch, tmp_path, listings)
+
+ def fake_prefer(
+ repo_id,
+ *_args,
+ files = None,
+ **_kwargs,
+ ):
+ assert repo_id == upstream
+ return upstream if tuple(files or ()) == ("model_index.json",) else mirror
+
+ monkeypatch.setattr(diffusion_mod, "prefer_ungated_mirror", fake_prefer)
+ resident: list = []
+ revisions: dict = {}
+ fetch_repos: dict = {}
+ total, files = DiffusionBackend._estimate_download_bytes(
+ upstream,
+ None,
+ upstream,
+ None,
+ kind = "pipeline",
+ resident_file_sizes_out = resident,
+ revisions_out = revisions,
+ fetch_repos_out = fetch_repos,
+ )
+
+ assert info_calls == [upstream, mirror]
+ assert download_calls == [
+ (upstream, "model_index.json", "a" * 40),
+ (mirror, "model_index.json", "b" * 40),
+ ]
+ assert set(files) == {
+ "model_index.json",
+ "transformer/diffusion_pytorch_model.safetensors",
+ "vae/diffusion_pytorch_model.safetensors",
+ }
+ assert total == 24 * MIB + 101
+ assert resident == [
+ ("transformer/diffusion_pytorch_model.safetensors", 21 * MIB),
+ ("vae/diffusion_pytorch_model.safetensors", 3 * MIB),
+ ]
+ assert revisions == {mirror: "b" * 40}
+ assert fetch_repos == {upstream: mirror}
+
+
+ ("family", "included"),
+ [
+ pytest.param("krea-2", "transformer", id = "krea"),
+ pytest.param("ideogram-4", "unconditional_transformer", id = "ideogram"),
+ ],
+)
+def test_explicit_pipeline_assemblers_use_their_fixed_component_sets(
+ monkeypatch, tmp_path, family, included
+):
+ from core.inference.diffusion import _explicit_pipeline_components
+
+ repo = f"unsloth/{family}"
+ files = [
+ ("model_index.json", 100),
+ (f"{included}/diffusion_pytorch_model.safetensors", 20 * MIB),
+ ("unused/diffusion_pytorch_model.safetensors", 30 * MIB),
+ ]
+ _stub_pipeline_hub(monkeypatch, tmp_path, {repo: ({"_class_name": "Pipeline"}, files, None)})
+ staged: dict = {}
+ resident: list = []
+ _total, files = DiffusionBackend._estimate_download_bytes(
+ repo,
+ None,
+ repo,
+ None,
+ kind = "pipeline",
+ pipeline_components = _explicit_pipeline_components(_family(name = family)),
+ file_sizes_out = staged,
+ resident_file_sizes_out = resident,
+ )
+ assert files == ["model_index.json", f"{included}/diffusion_pytorch_model.safetensors"]
+ assert resident == [(f"{included}/diffusion_pytorch_model.safetensors", 20 * MIB)]
+
+
+def test_an_unreadable_device_never_refuses(monkeypatch):
+ backend = _backend(monkeypatch, total_mib = None)
+ assert _flux_verdict(backend) is None
+
+
+def test_a_probe_that_raises_never_refuses(monkeypatch):
+ backend = _backend(monkeypatch, total_mib = STRIX_HALO_POOL_MIB)
+
+ def _boom(_target):
+ raise RuntimeError("no CUDA here")
+
+ monkeypatch.setattr(diffusion_mod, "snapshot_device_memory", _boom)
+ assert _flux_verdict(backend) is None
+
+
+def test_the_escape_hatch_still_opens_it(monkeypatch):
+ backend = _backend(monkeypatch, total_mib = STRIX_HALO_POOL_MIB)
+ monkeypatch.setenv("UNSLOTH_DIFFUSION_ALLOW_OVERSIZED_LOAD", "1")
+ assert _flux_verdict(backend) is None
+
+
+def _stub_estimate(monkeypatch, files):
+ def _estimate(*_a, **kwargs):
+ file_sizes = kwargs.get("file_sizes_out")
+ if file_sizes is not None:
+ file_sizes["unsloth/FLUX.2-dev"] = {name: size for name, size in files}
+ resident_sizes = kwargs.get("resident_file_sizes_out")
+ if resident_sizes is not None:
+ resident_sizes.extend(files)
+ return sum(size for _name, size in files), []
+
+ monkeypatch.setattr(DiffusionBackend, "_estimate_download_bytes", staticmethod(_estimate))
+
+
+def _stub_pick(
+ monkeypatch,
+ files,
+ *,
+ family = None,
+ te_prequant = None,
+):
+ fam = family if family is not None else _real_family()
+ monkeypatch.setattr(diffusion_mod, "detect_family_for_pick", lambda *_a, **_k: fam)
+ monkeypatch.setattr(
+ DiffusionBackend, "_te_prequant_plan_files", lambda *_a, **_k: te_prequant or {}
+ )
+ monkeypatch.setattr(diffusion_mod, "prefer_ungated_mirror", lambda base, *_a, **_k: base)
+ monkeypatch.setattr(diffusion_mod, "_assert_base_repo_accessible", lambda *_a, **_k: None)
+ _stub_estimate(monkeypatch, files)
+
+
+def _staged_backend(
+ monkeypatch,
+ *,
+ files,
+ calls,
+ total_mib = STRIX_HALO_POOL_MIB,
+ te_prequant = None,
+ family = None,
+):
+ backend = _backend(monkeypatch, total_mib = total_mib)
+ backend._load_token = 1
+ backend._loading = diffusion_mod._LoadingState(
+ repo_id = "unsloth/FLUX.2-dev", base_repo = "unsloth/FLUX.2-dev"
+ )
+ _stub_pick(monkeypatch, files, family = family, te_prequant = te_prequant)
+ monkeypatch.setattr(diffusion_mod, "assert_flux2_pick_compatible", lambda *_a, **_k: None)
+ monkeypatch.setattr(diffusion_mod, "assert_pick_is_not_speech", lambda *_a, **_k: None)
+ monkeypatch.setattr(diffusion_mod, "_local_base_transformer_present", lambda *_a, **_k: False)
+
+ def _prefetch(self, *_a, **_k):
+ calls.append("prefetch")
+ return None
+
+ monkeypatch.setattr(DiffusionBackend, "_prefetch_files", _prefetch)
+ monkeypatch.setattr(backend, "load_pipeline", lambda **_k: calls.append("load"))
+ return backend
+
+
+def test_an_offline_load_never_probes_the_device(monkeypatch):
+ calls: list = []
+ backend = _staged_backend(monkeypatch, files = [], calls = calls)
+
+ def _probe(_target):
+ raise AssertionError("the offline path opened a device probe")
+
+ monkeypatch.setattr(diffusion_mod, "snapshot_device_memory", _probe)
+
+ backend._run_load(
+ repo_id = "unsloth/FLUX.2-dev",
+ model_kind = "pipeline",
+ local_files_only = True,
+ _load_token = 1,
+ )
+
+ assert backend._loading is None, getattr(backend._loading, "error", None)
+ assert calls == ["prefetch", "load"]
+
+
+def _plan_backend(
+ monkeypatch,
+ *,
+ files,
+ mismatch = None,
+ total_mib = STRIX_HALO_POOL_MIB,
+ te_prequant = None,
+ family = None,
+):
+ backend = _backend(monkeypatch, total_mib = total_mib)
+ _stub_pick(monkeypatch, files, family = family, te_prequant = te_prequant)
+ monkeypatch.setattr(diffusion_mod, "flux2_pick_mismatch", lambda *_a, **_k: mismatch)
+ monkeypatch.setattr(diffusion_mod, "speech_pick_refusal", lambda *_a, **_k: None)
+ monkeypatch.setattr(DiffusionBackend, "_dit_prequant_plan_source", lambda *_a, **_k: None)
+ return backend
+
+
+def test_download_plan_keeps_an_earlier_refusal(monkeypatch):
+ backend = _plan_backend(monkeypatch, files = FLUX2_DEV, mismatch = "wrong base size")
+ plan = backend.download_plan("unsloth/FLUX.2-dev", model_kind = "pipeline")
+ assert plan["incompatible_reason"] == "wrong base size"
+
+
+def test_download_plan_skips_the_device_probe_when_asked(monkeypatch):
+ backend = _plan_backend(monkeypatch, files = FLUX2_DEV)
+
+ def _probe(*_args, **_kwargs):
+ raise AssertionError("the plan probed the device with allow_device_probe cleared")
+
+ monkeypatch.setattr(diffusion_mod, "snapshot_device_memory", _probe)
+ monkeypatch.setattr(DiffusionBackend, "_te_prequant_plan_files", _probe)
+ monkeypatch.setattr(DiffusionBackend, "_dit_prequant_plan_source", _probe)
+ plan = backend.download_plan(
+ "unsloth/FLUX.2-dev",
+ model_kind = "pipeline",
+ text_encoder_quant = "fp8",
+ allow_device_probe = False,
+ )
+ assert plan["incompatible_reason"] is None
+
+
+ ("repo", "files", "total_mib", "te_prequant", "expected_calls"),
+ [
+ pytest.param(
+ "unsloth/FLUX.2-dev",
+ FLUX2_DEV,
+ STRIX_HALO_POOL_MIB,
+ None,
+ [],
+ id = "refused",
+ ),
+ pytest.param(
+ "unsloth/FLUX.2-dev",
+ FLUX2_DEV,
+ 256 * 1024,
+ None,
+ ["prefetch", "load"],
+ id = "fits",
+ ),
+ pytest.param(
+ "unsloth/Lumina-Image-2.0",
+ LUMINA_2_MINUS_DENSE_TE,
+ 12 * 1024,
+ LUMINA_HOSTED_TE,
+ [],
+ id = "hosted-encoder",
+ ),
+ pytest.param(
+ "HiDream-ai/HiDream-I1-Full",
+ _files(transformer = 47_000),
+ STRIX_HALO_POOL_MIB,
+ None,
+ [],
+ id = "external-dense-encoder",
+ ),
+ ],
+)
+def test_load_and_plan_apply_the_same_memory_guard(
+ monkeypatch, repo, files, total_mib, te_prequant, expected_calls
+):
+ fam = _real_family(repo)
+ calls: list = []
+ staged = _staged_backend(
+ monkeypatch,
+ files = files,
+ calls = calls,
+ total_mib = total_mib,
+ te_prequant = te_prequant,
+ family = fam,
+ )
+ staged._run_load(repo_id = repo, model_kind = "pipeline", _load_token = 1)
+ assert calls == expected_calls
+
+ planner = _plan_backend(
+ monkeypatch,
+ files = files,
+ total_mib = total_mib,
+ te_prequant = te_prequant,
+ family = fam,
+ )
+ plan = planner.download_plan(repo, model_kind = "pipeline")
+ reason = plan["incompatible_reason"]
+ if expected_calls:
+ assert staged._loading is None
+ assert reason is None
+ else:
+ assert "usable on this device" in staged._loading.error
+ assert reason == staged._loading.error
diff --git a/studio/backend/tests/test_diffusion_routes.py b/studio/backend/tests/test_diffusion_routes.py
index fa867cd3b49..c9a6518aca3 100644
--- a/studio/backend/tests/test_diffusion_routes.py
+++ b/studio/backend/tests/test_diffusion_routes.py
@@ -1691,6 +1691,41 @@ def test_download_plan_forwards_the_load_time_controls(client, monkeypatch):
assert len(seen["loras"] or []) == 1
+def test_download_plan_suppresses_only_the_verdict_while_training_runs(client, monkeypatch):
+ # The panel stages exactly what this endpoint reports, so the plan has to keep counting the
+ # files the load will fetch even while a trainer holds the card. Only the oversized-memory
+ # refusal is suppressed: it needs a device reading nobody should take mid-training, and the
+ # load-time check still runs. Turning the whole probe off instead would silently drop the
+ # hosted DiT prequant and the pre-cast encoder from the plan.
+ from core.inference import diffusion_engine_router as router
+ from core.inference.sd_cpp_engine import ENGINE_DIFFUSERS
+ from routes import inference as routes_inference
+
+ monkeypatch.setattr(router, "predict_engine", lambda fam, **_: ENGINE_DIFFUSERS)
+ backend = diffusion_module.get_diffusion_backend()
+ seen: dict = {}
+
+ def _plan(model_path, **kwargs):
+ seen.clear()
+ seen.update(kwargs)
+ return {"entries": [], "total_bytes": 0}
+
+ monkeypatch.setattr(backend, "download_plan", _plan, raising = False)
+ body = {
+ "model_path": "unsloth/FLUX.1-dev-GGUF",
+ "gguf_filename": "flux1-dev-Q4_K_M.gguf",
+ "model_kind": "gguf",
+ "transformer_quant": "fp8",
+ }
+
+ for training, expected in ((True, False), (False, True)):
+ monkeypatch.setattr(routes_inference, "_training_is_active", lambda: training)
+ assert client.post("/api/inference/images/download-plan", json = body).status_code == 200
+ assert seen["memory_verdict"] is expected, training
+ # The file scope is never the thing that changes with training state.
+ assert "allow_device_probe" not in seen, training
+
+
def test_download_plan_response_keeps_the_planners_checkpoint_marker(client, monkeypatch):
# Through the ROUTE, not the planner: the response model is what the picker actually reads, and
# a field the planner sets but the model does not declare is dropped silently on serialization.
diff --git a/studio/backend/tests/test_diffusion_te_prequant.py b/studio/backend/tests/test_diffusion_te_prequant.py
index 2fabd4e10d7..d05c840d60d 100644
--- a/studio/backend/tests/test_diffusion_te_prequant.py
+++ b/studio/backend/tests/test_diffusion_te_prequant.py
@@ -25,8 +25,16 @@ from core.inference.diffusion_te_prequant import (
)
-def _fam(te_prequant_repos = (), name = "ltx-2"):
- return types.SimpleNamespace(name = name, te_prequant_repos = te_prequant_repos)
+def _fam(
+ te_prequant_repos = (),
+ name = "ltx-2",
+ base_repo = "Lightricks/LTX-2",
+):
+ return types.SimpleNamespace(
+ name = name,
+ base_repo = base_repo,
+ te_prequant_repos = te_prequant_repos,
+ )
# ── resolution ───────────────────────────────────────────────────────────────
@@ -152,11 +160,58 @@ def test_load_missing_file_returns_none(monkeypatch, tmp_path):
assert out is None
+def test_hosted_checkpoint_and_config_honor_cache_only_and_the_active_root(monkeypatch, tmp_path):
+ import huggingface_hub
+ import torch
+ import transformers
+ from utils import hf_cache_settings
+
+ seen: dict = {"download": {}, "config": {}}
+
+ def fake_download(**kwargs):
+ seen["download"].update(kwargs)
+ return "/cache/encoder.pt"
+
+ def fake_config(repo_id, **kwargs):
+ seen["config"] = {"repo_id": repo_id, **kwargs}
+ raise FileNotFoundError("stop after config lookup")
+
+ monkeypatch.setattr(huggingface_hub, "hf_hub_download", fake_download)
+ monkeypatch.setattr(torch, "load", lambda *_a, **_k: _good_ckpt())
+ monkeypatch.setattr(transformers.AutoConfig, "from_pretrained", fake_config)
+ monkeypatch.setattr(hf_cache_settings, "active_hf_hub_cache", lambda: str(tmp_path))
+ out = tpq.load_prequant_text_encoder(
+ "Lightricks/LTX-2",
+ "text_encoder",
+ TePrequantSource(kind = "repo", location = "org/hosted", filename = "encoder.pt"),
+ dtype = None,
+ local_files_only = True,
+ )
+ assert out is None
+ assert seen["download"]["local_files_only"] is True
+ assert seen["download"]["cache_dir"] == str(tmp_path)
+ assert seen["config"]["repo_id"] == "Lightricks/LTX-2"
+ assert seen["config"]["subfolder"] == "text_encoder"
+ assert seen["config"]["local_files_only"] is True
+ assert seen["config"]["cache_dir"] == str(tmp_path)
+
+
# ── pipeline-assembly injection gating ───────────────────────────────────────
def _target():
return types.SimpleNamespace(device = "cuda", dtype = None)
+def _budget_scale(
+ fam,
+ mode = "fp8",
+ *,
+ base = None,
+):
+ return tpq.te_prequant_budget_scale(
+ fam, te_quant_mode = mode, target = _target(), base = base or fam.base_repo
+ )
+
+
def test_pipe_kwargs_empty_when_mode_not_fp8(monkeypatch):
fam = _fam(te_prequant_repos = (("fp8", "text_encoder", "org/hosted"),))
for mode in (None, "", "off", "int8", "fp8_dynamic"):
@@ -230,6 +285,28 @@ def test_pipe_kwargs_injects_loaded_encoder(monkeypatch):
assert seen["source"].location == "org/hosted"
+def test_pipe_kwargs_does_not_download_a_checkpoint_for_a_custom_base(monkeypatch):
+ import core.inference.diffusion_precision as precision
+
+ fam = _fam(te_prequant_repos = (("fp8", "text_encoder", "org/hosted"),))
+ monkeypatch.setattr(precision, "te_quant_supported", lambda target, mode: True)
+
+ def unexpected_load(*_args, **_kwargs):
+ raise AssertionError("an incompatible hosted checkpoint must not be opened")
+
+ monkeypatch.setattr(tpq, "load_prequant_text_encoder", unexpected_load)
+ assert (
+ te_prequant_pipe_kwargs(
+ fam,
+ "someone/custom-ltx-2",
+ te_quant_mode = "fp8",
+ target = _target(),
+ dtype = None,
+ )
+ == {}
+ )
+
+
def test_pipe_kwargs_empty_when_load_fails(monkeypatch):
import core.inference.diffusion_precision as precision
@@ -263,7 +340,7 @@ def test_pipe_kwargs_injects_every_hosted_component(monkeypatch):
lambda base, component, source, **kw: markers[component],
)
out = te_prequant_pipe_kwargs(
- fam, "some/base", te_quant_mode = "fp8", target = _target(), dtype = None
+ fam, "Lightricks/LTX-2", te_quant_mode = "fp8", target = _target(), dtype = None
)
assert out == markers
@@ -441,6 +518,7 @@ def test_hidream_te4_prefers_precast_checkpoint(monkeypatch):
calls["component"] = component
calls["config_subfolder"] = kwargs.get("config_subfolder")
calls["config_overrides"] = kwargs.get("config_overrides")
+ calls["local_files_only"] = kwargs.get("local_files_only")
return precast
monkeypatch.setattr(tpq, "load_prequant_text_encoder", _fake_load)
@@ -448,13 +526,21 @@ def test_hidream_te4_prefers_precast_checkpoint(monkeypatch):
te_prequant_repos = (("fp8", "text_encoder_4", "unsloth/HiDream-I1-Full-FP8"),),
name = "hidream-i1",
)
- out = dh.hidream_te4_kwargs(None, None, fam = fam, te_quant_mode = "fp8", target = _target())
+ out = dh.hidream_te4_kwargs(
+ None,
+ None,
+ fam = fam,
+ te_quant_mode = "fp8",
+ target = _target(),
+ local_files_only = True,
+ )
assert out["text_encoder_4"] is precast
assert calls["base"] == "unsloth/Meta-Llama-3.1-8B-Instruct"
assert calls["component"] == "text_encoder_4"
# Standalone repo: config at the root, forward flags the pipeline needs applied.
assert calls["config_subfolder"] == ""
assert calls["config_overrides"] == {"output_hidden_states": True, "output_attentions": True}
+ assert calls["local_files_only"] is True
# The dense Llama download never ran.
assert ("llama_from_pretrained", "unsloth/Meta-Llama-3.1-8B-Instruct") not in recorder
@@ -640,16 +726,14 @@ def test_budget_scale_applies_only_when_a_pre_cast_checkpoint_resolves(monkeypat
monkeypatch.setattr(precision, "te_quant_supported", lambda target, mode: True)
hosted = _fam(te_prequant_repos = (("fp8", "text_encoder", "org/hosted"),))
- assert (
- tpq.te_prequant_budget_scale(hosted, te_quant_mode = "fp8", target = _target())
- == tpq.TE_PREQUANT_BUDGET_SCALE
- )
+ assert _budget_scale(hosted) == tpq.TE_PREQUANT_BUDGET_SCALE
+ assert _budget_scale(hosted, base = "someone/custom-ltx-2") == 1.0
# No hosted checkpoint: the encoder is downloaded dense and cast in place AFTER assembly, so
# its peak is bf16 and the budget must stay bf16.
- assert tpq.te_prequant_budget_scale(_fam(), te_quant_mode = "fp8", target = _target()) == 1.0
+ assert _budget_scale(_fam()) == 1.0
# Not requested, or a scheme with no hosted artifact.
for mode in (None, "", "off", "int8", "fp8_dynamic", "nvfp4"):
- assert tpq.te_prequant_budget_scale(hosted, te_quant_mode = mode, target = _target()) == 1.0
+ assert _budget_scale(hosted, mode) == 1.0
def test_budget_scale_is_bf16_when_the_device_cannot_quantise(monkeypatch):
@@ -657,7 +741,7 @@ def test_budget_scale_is_bf16_when_the_device_cannot_quantise(monkeypatch):
hosted = _fam(te_prequant_repos = (("fp8", "text_encoder", "org/hosted"),))
monkeypatch.setattr(precision, "te_quant_supported", lambda target, mode: False)
- assert tpq.te_prequant_budget_scale(hosted, te_quant_mode = "fp8", target = _target()) == 1.0
+ assert _budget_scale(hosted) == 1.0
def test_budget_scale_fails_open_to_bf16(monkeypatch):
@@ -666,7 +750,7 @@ def test_budget_scale_fails_open_to_bf16(monkeypatch):
raise RuntimeError("hub down")
monkeypatch.setattr(tpq, "te_prequant_sources", _boom)
- assert tpq.te_prequant_budget_scale(_fam(), te_quant_mode = "fp8", target = _target()) == 1.0
+ assert _budget_scale(_fam()) == 1.0
def test_shipped_video_and_image_families_resolve_the_scale(monkeypatch):
@@ -683,12 +767,45 @@ def test_shipped_video_and_image_families_resolve_the_scale(monkeypatch):
("Wan-AI/Wan2.2-T2V-A14B-Diffusers", 1.0),
):
fam = detect_video_family(repo)
- assert tpq.te_prequant_budget_scale(fam, te_quant_mode = "fp8", target = _target()) == (
- expected
- ), repo
- assert (
- tpq.te_prequant_budget_scale(
- detect_family("Qwen/Qwen-Image"), te_quant_mode = "fp8", target = _target()
- )
- == scale
- )
+ assert _budget_scale(fam, base = repo) == expected, repo
+ assert _budget_scale(detect_family("Qwen/Qwen-Image"), base = "Qwen/Qwen-Image") == scale
+
+
+def test_a_sibling_release_keeps_the_pre_cast_encoder(monkeypatch):
+ """The base gate must not refuse a release that republishes the SAME encoder.
+
+ Qwen-Image-2512 and Krea-2-Raw ship their sibling's text encoder byte for byte (shard
+ LFS sha256 compared 2026-08-25), so dropping the hosted pre-cast artifact for them
+ would stage 16.6 GB / 8.9 GB of dense encoder the load never opens -- and would widen
+ the memory budget that the pre-download unified-memory guard is sized against."""
+ import core.inference.diffusion_precision as precision
+ from core.inference.diffusion_families import detect_family_for_pick
+
+ monkeypatch.setattr(precision, "te_quant_supported", lambda target, mode: True)
+ for base in (
+ "Qwen/Qwen-Image",
+ "Qwen/Qwen-Image-2512",
+ "unsloth/Qwen-Image-2512",
+ "krea/Krea-2-Turbo",
+ "krea/Krea-2-Raw",
+ ):
+ fam = detect_family_for_pick(base, None, None)
+ assert fam is not None, base
+ sources = tpq.te_prequant_sources_for_base(fam, base, te_quant_mode = "fp8", target = _target())
+ assert "text_encoder" in sources, base
+ assert _budget_scale(fam, base = base) == tpq.TE_PREQUANT_BUDGET_SCALE, base
+
+
+def test_an_unrelated_custom_base_still_loses_it(monkeypatch):
+ """The other half of the same gate: a base nobody has compared keeps the strict
+ refusal, because the hosted artifact would otherwise download before its metadata
+ could reject it."""
+ import core.inference.diffusion_precision as precision
+ from core.inference.diffusion_families import detect_family_for_pick
+
+ monkeypatch.setattr(precision, "te_quant_supported", lambda target, mode: True)
+ fam = detect_family_for_pick("Qwen/Qwen-Image", None, None)
+ for base in ("someone/my-qwen-image-finetune", "randomuser/qwen-image-merged"):
+ assert (
+ tpq.te_prequant_sources_for_base(fam, base, te_quant_mode = "fp8", target = _target()) == {}
+ ), base
diff --git a/studio/backend/tests/test_media_auto_switch.py b/studio/backend/tests/test_media_auto_switch.py
index a5ec34fe871..8647c2e4d21 100644
--- a/studio/backend/tests/test_media_auto_switch.py
+++ b/studio/backend/tests/test_media_auto_switch.py
@@ -751,20 +751,22 @@ def test_a_replacement_load_is_not_reported_as_the_requested_model(
def test_the_download_plan_asks_the_engine_that_will_load_the_pick(cached_gguf, monkeypatch):
- # The resident engine can be native sd.cpp while the target loads through diffusers; its
- # planner refuses the pick, and that refusal would read as nothing missing.
pick = mas.resolve_local_media_model("city96/FLUX.1-dev-gguf", task = mas.IMAGE_TASK)
asked: list = []
class _Planner:
def download_plan(self, model_path, **kwargs):
- asked.append(model_path)
+ asked.append((model_path, kwargs))
return {"total_bytes": 7}
monkeypatch.setattr(locality, "planners_for", lambda owner, p: [_Planner()])
assert mas.missing_download_bytes(arb.DIFFUSION, pick) == 7
- assert asked == [pick.model_path]
+ assert [model_path for model_path, _kwargs in asked] == [pick.model_path]
+ # Only the oversized-memory verdict is suppressed. The probe stays on, because the
+ # byte count has to be taken over the same file list the load will fetch.
+ assert asked[0][1]["memory_verdict"] is False
+ assert "allow_device_probe" not in asked[0][1]
def test_two_bpw_builds_of_one_quant_are_not_confused(two_bpw, enabled, backend, loads):
diff --git a/studio/backend/tests/test_video_backend.py b/studio/backend/tests/test_video_backend.py
index f4f102a1fdc..60aca94e31d 100644
--- a/studio/backend/tests/test_video_backend.py
+++ b/studio/backend/tests/test_video_backend.py
@@ -4482,6 +4482,29 @@ def test_download_plan_swaps_the_dense_encoder_for_the_precast_checkpoint(monkey
assert plan["total_bytes"] == sum(e["bytes"] for e in plan["entries"])
+def test_download_plan_keeps_dense_encoder_for_a_custom_family_pipeline(monkeypatch):
+ _cuda_bf16_target(monkeypatch)
+ custom = "someone/custom-ltx-2"
+ _plan_api(
+ monkeypatch,
+ {
+ custom: _LTX_BASE_SIBLINGS,
+ "unsloth/LTX-2-FP8": _LTX2_FP8_SIBLINGS,
+ },
+ )
+
+ plan = VideoBackend().download_plan(
+ custom,
+ model_kind = "pipeline",
+ family_override = "ltx-2",
+ text_encoder_quant = "fp8",
+ )
+
+ by_repo = {entry["repo_id"]: entry for entry in plan["entries"]}
+ assert "unsloth/LTX-2-FP8" not in by_repo
+ assert any(name.startswith("text_encoder/") for name in by_repo[custom]["files"])
+
+
def test_download_plan_keeps_the_dense_encoder_without_an_fp8_request(monkeypatch):
# No fp8 request means the dense encoder IS the encoder: dropping it would break the load.
_cuda_bf16_target(monkeypatch)