Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio diffusion: read a pipeline's .fp16 weight files on fp16 loads (SDXL reads 6.5 GB, not 12.9 GB) (#15195)
Daniel Han3042f52c05c1
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.pyindex 7d21dfeb8d4..2e6f34bac09 100644--- a/studio/backend/core/inference/diffusion.py+++ b/studio/backend/core/inference/diffusion.py@@ -371,7 +371,16 @@ from .diffusion_precision import (torchao_quantize_importable,)from .diffusion_te_prequant import supplied_component_pipe_kwargs, te_prequant_pipe_kwargs+from .diffusion_fast_load import _snapshot_dir as _load_snapshot_dirfrom .diffusion_fast_load import start_load_prefetch, stop_prefetch, te_precast_components+from .diffusion_fp16_variant import (+ fp16_variant_enabled,+ is_fp16_dtype,+ is_fp16_twin,+ local_fp16_variant,+ plan_fp16_twins,+ twin_of,+)from .diffusion_flow_shift import (SAMPLE_SIGMAS_KEY,apply_comfy_flow_shift,@@ -4487,6 +4496,15 @@ class DiffusionBackend:# request's card into the next one.return diffusion_device_target_from_torch_device(device, effective)+ def _fp16_load_target(self, fam: Optional[DiffusionFamily], ordinal: Optional[int]) -> bool:+ """True when this pick loads at fp16 (a pre-Ampere card), so the plan may stage ``.fp16`` twins. Never raises."""+ if not fp16_variant_enabled():+ return False+ try:+ return is_fp16_dtype(getattr(self._target_for_ordinal(fam, ordinal), "dtype", None))+ except Exception: # noqa: BLE001 - no target: the defaults always load+ return False+def _target_for_ordinal(self, fam: Optional[DiffusionFamily], ordinal: Optional[int]) -> DiffusionDeviceTarget:@@ -5716,6 +5734,8 @@ class DiffusionBackend:skip_transformer_weights = skip_transformer_weights,skipped_files_out = skipped_transformer_files,local_files_only = local_files_only,+ fp16_twins = kind == "pipeline"+ and self._fp16_load_target(fam, kwargs.get("gpu_ordinal")),resident_file_sizes_out = resident_sizes,fetch_repos_out = fetch_repos,file_sizes_out = planned_sizes,@@ -6644,6 +6664,7 @@ class DiffusionBackend:skipped_files_out: Optional[list[str]] = None,failures_out: Optional[list] = None,local_files_only: bool = False,+ fp16_twins: bool = False,) -> tuple[int, list[str]]:"""Total download size for the progress bar, plus the base-repo files to fetch (the prefetchreuses this list, so the base is listed only once).@@ -6671,6 +6692,10 @@ class DiffusionBackend:``local_files_only`` returns the metadata-unavailable answer ``(0, [])`` instead of asking:the bytes belong to a download that is not permitted, and the empty list stages nothing.++ ``fp16_twins`` (the load casts to fp16): a ``pipeline`` whose every listed component ships a single-file+ ``.fp16`` twin stages the twins instead of the defaults (``diffusion_fp16_variant``), unless the defaults are+ already cached and the twins are not. The load then reads them with ``variant="fp16"``."""if local_files_only:return 0, []@@ -6736,6 +6761,8 @@ class DiffusionBackend:picked = [s for s in picked if not _seeded_denoiser_shard(s.rfilename)]if skipped_files_out is not None:skipped_files_out[:] = [s.rfilename for s in seeded]+ if fp16_twins and not seeded and components is not None:+ picked = _swap_in_fp16_twins(metadata_repo, info, picked, hf_token)return info, components, picked# The family's own index: FLUX.3 ships only modular_model_index.json, so probing@@ -7106,6 +7133,9 @@ class DiffusionBackend:skip_te_components = tuple(te_files) + replaced,skip_transformer_weights = skip_transformer_weights,failures_out = plan_failures,+ fp16_twins = kind == "pipeline"+ and allow_device_probe+ and self._fp16_load_target(fam, load_kwargs.get("gpu_ordinal")),)# Decided once, from the staged file list, and both probed and reported: a gated base answers model_info# anonymously, so the plan would otherwise be confident and the 401 land mid-download. Probing any id but the@@ -7738,7 +7768,10 @@ class DiffusionBackend:# from_pretrained reads <component>/<file> only: a deeper tree (FLUX.3's variants/fp8r, variants/nvfp4# quantised packages) is never loaded and must not be priced.if load_itemsize is not None and (- len(rel.parts) != 2 or not _pipeline_default_variant_file(rel.as_posix())+ len(rel.parts) != 2+ or not (+ _pipeline_default_variant_file(rel.as_posix()) or is_fp16_twin(rel.as_posix())+ )):continuetry:@@ -7747,6 +7780,14 @@ class DiffusionBackend:continueif load_itemsize is None:return sizes+ # A twin beside a default would price the same tensors twice.+ default_dirs = {+ rel.rsplit("/", 1)[0]+ for rel in sizes+ if not is_fp16_twin(rel) and _pipeline_resident_weight(rel)+ }+ for rel in [r for r in sizes if is_fp16_twin(r) and r.rsplit("/", 1)[0] in default_dirs]:+ del sizes[rel]# A .bin only loses to a safetensors checkpoint the loader can select: unsharded, or shards with their index.st_dirs = {rel.rsplit("/", 1)[0]@@ -9434,6 +9475,28 @@ class DiffusionBackend:}if hf_token:pipe_kwargs["token"] = hf_token+ # fp16 load with a twin for every component reads the twins (bit-identical after cast).+ _te_replaced = te_precast_components(+ fam, fetch_base, text_encoder_quant, target+ )+ _variant_snapshot = _load_snapshot_dir(+ fetch_base, _base_local_dir, hub_cache_dir()+ )+ _fp16_variant_eligible = not (+ pipeline_seed_scheme is not None+ or _pipeline_prequant_skipped+ or is_flux3_family(fam)+ or fam.name in (MOSS_IMAGE_FAMILY_NAME, KREA2_FAMILY_NAME)+ )+ _fp16_variant = (+ local_fp16_variant(+ _variant_snapshot,+ load_dtype = dtype,+ supplied = _te_replaced,+ )+ if _fp16_variant_eligible+ else None+ )# Stopped once the pipeline is built.self._stop_load_prefetch()self._load_prefetch = start_load_prefetch(@@ -9442,11 +9505,10 @@ class DiffusionBackend:prequant_scheme = pipeline_seed_scheme,prequant_path_override = transformer_prequant_path,prequant_base_repo = base,- text_encoders_replaced = te_precast_components(- fam, fetch_base, text_encoder_quant, target- ),+ text_encoders_replaced = _te_replaced,cache_dir = hub_cache_dir(),logger = logger,+ variant = _fp16_variant,)if fam.name == HIDREAM_FAMILY_NAME:# The repo names a Llama text_encoder_4 it does not ship; supply it from the open@@ -9654,6 +9716,22 @@ class DiffusionBackend:pipe_kwargs["torch_dtype"] = small_host_torch_dtype_map(small_host, dtype)+ if _fp16_variant_eligible:+ # Final kwargs: a dtype map or a supplied component (a default-only cached+ # file it replaces blocked the first check) changes what twins must cover.+ _fp16_variant = local_fp16_variant(+ _variant_snapshot,+ load_dtype = dtype,+ torch_dtype = pipe_kwargs.get("torch_dtype"),+ supplied = tuple(pipe_kwargs),+ )+ if _fp16_variant is not None:+ pipe_kwargs["variant"] = _fp16_variant+ logger.info(+ "diffusion.fp16_variant: reading the .%s weight files (%s load)",+ _fp16_variant,+ str(dtype).replace("torch.", ""),+ )# The prefetched snapshot dir keeps from_pretrained off the hub (24 GB per FLUX.1# otherwise)try:@@ -15636,9 +15714,60 @@ def _pipeline_selected_file(def _pipeline_resident_weight(rfilename: str) -> bool:- """Whether a selected file becomes tensor storage in the loaded pipeline."""+ """Whether a selected file becomes tensor storage in the loaded pipeline (fp16 twins included)."""name = rfilename.rsplit("/", 1)[-1].lower()- return bool(_DEFAULT_PIPELINE_WEIGHT_RE.match(name))+ return bool(_DEFAULT_PIPELINE_WEIGHT_RE.match(name)) or is_fp16_twin(name)+++def _swap_in_fp16_twins(repo_id: str, info: Any, picked: list[Any], hf_token: Any) -> list[Any]:+ """``picked`` with defaults swapped for ``.fp16`` twins; unchanged when only the defaults are cached."""+ if not fp16_variant_enabled():+ return picked+ try:+ from huggingface_hub import hf_hub_download, try_to_load_from_cache++ siblings = {s.rfilename: s for s in (info.siblings or ())}+ picked_names = [s.rfilename for s in picked]+ folders = {+ name.split("/", 1)[0]+ for name in picked_names+ if "/" in name and _pipeline_resident_weight(name)+ }+ if not folders:+ return picked+ revision = getattr(info, "sha", None) or None+ index_path = hf_hub_download(+ repo_id,+ "model_index.json",+ revision = revision,+ cache_dir = hub_cache_dir(),+ token = hf_token or None,+ )+ index = json.loads(Path(index_path).read_text(encoding = "utf-8"))+ plan = plan_fp16_twins(siblings, index, components = folders)+ if plan is None or set(plan) != folders:+ return picked+ defaults = {+ n for n in picked_names if n.split("/", 1)[0] in plan and _pipeline_resident_weight(n)+ }+ if len(defaults) != len(plan) or any(+ twin_of(n) != plan[n.split("/", 1)[0]] for n in defaults+ ):+ return picked++ def _cached(name: str) -> bool:+ hit = try_to_load_from_cache(+ repo_id, name, cache_dir = hub_cache_dir(), revision = revision+ )+ return isinstance(hit, str)++ if all(_cached(n) for n in defaults) and not all(_cached(t) for t in plan.values()):+ return picked+ twins = [siblings[t] for t in plan.values()]+ return [s for s in picked if s.rfilename not in defaults] + twins+ except Exception as exc: # noqa: BLE001 - the defaults always load+ logger.debug("diffusion.fp16_variant: plan kept the default files (%r)", exc)+ return pickeddef _progress(diff --git a/studio/backend/core/inference/diffusion_auto_policy.py b/studio/backend/core/inference/diffusion_auto_policy.pyindex e2f9abcbb82..c6f6e49e49a 100644--- a/studio/backend/core/inference/diffusion_auto_policy.py+++ b/studio/backend/core/inference/diffusion_auto_policy.py@@ -25,6 +25,8 @@ import osfrom dataclasses import dataclassfrom typing import Any, Optional+from .diffusion_fp16_variant import is_fp16_twin, shadowed_twins+_MIB_PER_GB = 1000.0**3 / (1024.0 * 1024.0) # component sizes below are decimal GB# Steady size of a torchao-quantised transformer relative to bf16: int8/fp8 store one byte per param plus per-row@@ -125,9 +127,7 @@ _BASE_RESIDENT_FACTORS: dict = {"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.+ # SDXL defaults are fp32 (12.9 GB vs 6.5 GB loaded), unet/ is a companion: both factors halve. fp16 twins price 1:1."stabilityai/stable-diffusion-xl-base-1.0": (2.0, 2.0),"stabilityai/sdxl-turbo": (2.0, 2.0),}@@ -153,22 +153,34 @@ def resident_bytes_from_declared()denoiser = 0companions = 0- for path, size in declared_files or ():+ twins = 0 # already at load width: 1:1+ declared_files = list(declared_files or ())+ shadowed = shadowed_twins(path for path, _size in declared_files)+ for path, size in declared_files:size = int(size or 0)- if size <= 0:+ if size <= 0 or str(path) in shadowed:continue- if str(path).startswith(DENOISER_SUBFOLDERS):+ if is_fp16_twin(str(path)):+ twins += size+ elif str(path).startswith(DENOISER_SUBFOLDERS):denoiser += sizeelse:companions += sizeprequant_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:+ if (+ denoiser <= 0+ and companions <= 0+ and twins <= 0+ and prequant_bytes <= 0+ and extra_bf16_bytes <= 0+ ):return Nonedtype_resident = (int(denoiser / max(denoiser_factor, 0.01))+ int(companions / max(companion_factor, 0.01))+ + twins+ extra_bf16_bytes)return int(dtype_resident * dtype_scale) + prequant_bytes@@ -185,14 +197,21 @@ def companion_bytes_from_declared(_base_key(base_repo) if base_repo else "", (1.0, 1.0))# An SDXL-style UNet is a denoiser too.- companions = sum(- max(0, int(size or 0))- for path, size in (declared_files or ())- if not str(path).startswith(DENOISER_SUBFOLDERS + ("unet/",))- )- if companions <= 0:+ declared_files = list(declared_files or ())+ shadowed = shadowed_twins(path for path, _size in declared_files)+ kept = [+ (str(path), max(0, int(size or 0)))+ for path, size in declared_files+ if not str(path).startswith(DENOISER_SUBFOLDERS + ("unet/",)) and str(path) not in shadowed+ ]+ companions = sum(size for path, size in kept if not is_fp16_twin(path))+ twins = sum(size for path, size in kept if is_fp16_twin(path))+ if companions + twins <= 0:return None- return int(int(companions / max(companion_factor, 0.01)) * max(1.0, float(dtype_scale or 1.0)))+ return int(+ (int(companions / max(companion_factor, 0.01)) + twins)+ * max(1.0, float(dtype_scale or 1.0))+ )def _base_key(base_repo: Optional[str]) -> str:diff --git a/studio/backend/core/inference/diffusion_component_sizes.py b/studio/backend/core/inference/diffusion_component_sizes.pyindex 279b3f4916f..135c2b70b01 100644--- a/studio/backend/core/inference/diffusion_component_sizes.py+++ b/studio/backend/core/inference/diffusion_component_sizes.py@@ -240,7 +240,10 @@ def select_weight_files(return [f"{stem}.safetensors"]if any(_SHARD_RE.match(n) and n.startswith(stem + "-") for n in names):return []- # Only these stems load (Studio passes no variant, so .fp16 twins are not read either).+ # No default: an fp16 load reads the single-file .fp16 twin (sharded twins never read).+ for stem in _stem_order(folder):+ if f"{stem}.fp16.safetensors" in names:+ return [f"{stem}.fp16.safetensors"]return []diff --git a/studio/backend/core/inference/diffusion_families.py b/studio/backend/core/inference/diffusion_families.pyindex 8b0873b17fd..1823698834b 100644--- a/studio/backend/core/inference/diffusion_families.py+++ b/studio/backend/core/inference/diffusion_families.py@@ -2591,7 +2591,11 @@ def _safe_relative_parts(text: str) -> Optional[tuple[str, ...]]:return relative.parts-def _local_weights_are_complete(component: Path, library_name: str) -> bool:+def _local_weights_are_complete(+ component: Path,+ library_name: str,+ accept_twin: bool = True,+) -> bool:# The first format with any weights present decides: a leftover .bin index cannot veto safetensors.for stems, ext in _LOCAL_PIPELINE_WEIGHT_FORMATS:# Transformers never reads diffusion_pytorch_model* (LTX-2's text_encoder ships both shard sets).@@ -2617,11 +2621,20 @@ def _local_weights_are_complete(component: Path, library_name: str) -> bool:sizes = [w.stat().st_size for s in stems if (w := component / f"{s}.{ext}").is_file()]if sizes:return any(sizes)- return False+ # A lone single-file .fp16 twin: a snapshot an fp16 load staged, read with variant="fp16".+ return accept_twin and any(+ _nonempty_file(component / f"{s}.fp16.safetensors")+ for s in ("diffusion_pytorch_model", "model")+ if library_name != "transformers" or s != "diffusion_pytorch_model"+ )def _local_pipeline_component_is_complete(- component: Path, library_name: str, class_name: str, config_only_model_components: bool+ component: Path,+ library_name: str,+ class_name: str,+ config_only_model_components: bool,+ accept_twin: bool = True,) -> bool:if not component.is_dir():return False@@ -2644,7 +2657,8 @@ def _local_pipeline_component_is_complete(_nonempty_file(component / a) for a in ("vocab.json", "merges.txt"))return _json_dict(component / "config.json") is not None and (- config_only_model_components or _local_weights_are_complete(component, library_name)+ config_only_model_components+ or _local_weights_are_complete(component, library_name, accept_twin))@@ -2682,6 +2696,8 @@ def local_pipeline_components_are_complete(library,cls,config_only_model_components or name in excluded_components,+ # Fixed-folder assemblers (FLUX.3) open each component without a variant: no twins.+ accept_twin = False,)for name, (folder, library, cls) in fixed_component_folders.items())@@ -2689,6 +2705,7 @@ def local_pipeline_components_are_complete(return Falsecaller_supplied = _CALLER_SUPPLIED_COMPONENTS.get(class_name, frozenset())declared = False+ twin_only = Falsetry:for name, spec in payload.items():if (@@ -2731,11 +2748,29 @@ def local_pipeline_components_are_complete(component, spec[0], spec[1], config_only_model_components):return False+ if not config_only_model_components and _twin_only_component(component):+ twin_only = Trueexcept OSError:return False+ if declared and twin_only:+ # The loader reads .fp16 files pipeline-wide or not at all: a mix of twins and defaults would not open.+ from .diffusion_fp16_variant import local_fp16_variant+ return (+ local_fp16_variant(str(base), load_dtype = None, supplied = tuple(excluded_components))+ is not None+ )return declared+def _twin_only_component(component: Path) -> bool:+ from .diffusion_fp16_variant import is_default_weight, is_fp16_twin+ try:+ names = [entry.name for entry in component.iterdir() if entry.is_file()]+ except OSError:+ return False+ return any(is_fp16_twin(n) for n in names) and not any(is_default_weight(n) for n in names)++# Minimums that name a release which does not EXIST yet. ``pip install -U 'diffusers>=0.41.0'`` has# no candidate today, so quoting it as the remedy sends someone to a command that cannot succeed.# Studio installs the pinned main build for exactly these classes (studio/backend/requirements/diff --git a/studio/backend/core/inference/diffusion_fast_load.py b/studio/backend/core/inference/diffusion_fast_load.pyindex 2cd121f39ae..aa64399f6b9 100644--- a/studio/backend/core/inference/diffusion_fast_load.py+++ b/studio/backend/core/inference/diffusion_fast_load.py@@ -33,10 +33,11 @@ _UPLOAD_BUFFERS = 16_UPLOAD_MIN_TENSOR_BYTES = 1 << 20_UPLOAD_MIN_TOTAL_BYTES = 256 << 20-# variant=None: from_pretrained never opens *.fp16.safetensors-style twins.+# variant=None: from_pretrained never opens *.fp16.safetensors-style twins; variant="fp16" opens only those._DEFAULT_WEIGHT_RE = re.compile(r"^(?:diffusion_pytorch_model|model)(?:-\d{5}-of-\d{5})?\.safetensors$")+_FP16_WEIGHT_RE = re.compile(r"^(?:diffusion_pytorch_model|model)\.fp16\.safetensors$")_DENOISER_COMPONENTS = ("transformer", "unet")@@ -237,9 +238,11 @@ def pipeline_component_files(*,skip_denoiser: bool,skip_components: Iterable[str] = (),+ variant: Optional[str] = None,) -> list[str]:"""The weight files ``from_pretrained`` reads from a local diffusers snapshot: every component- ``model_index.json`` names, text encoders first, then the VAE, then the denoiser. Cache only."""+ ``model_index.json`` names, text encoders first, then the VAE, then the denoiser. Cache only.+ ``variant="fp16"`` names the ``.fp16`` twins instead."""if not snapshot:return []try:@@ -277,8 +280,9 @@ def pipeline_component_files(entries = sorted(os.listdir(folder))except OSError:continue+ pattern = _FP16_WEIGHT_RE if variant == "fp16" else _DEFAULT_WEIGHT_REfor entry in entries:- if _DEFAULT_WEIGHT_RE.match(entry):+ if pattern.match(entry):path = os.path.join(folder, entry)if os.path.isfile(path):files.append(path)@@ -307,6 +311,7 @@ def start_load_prefetch(text_encoders_replaced: Iterable[str] = (),cache_dir: Optional[str] = None,logger: Any = None,+ variant: Optional[str] = None,) -> Optional[LoadPrefetch]:"""Prefetch what a diffusers pipeline load of ``base`` will read. Never raises."""if not prefetch_enabled():@@ -339,6 +344,7 @@ def start_load_prefetch(_snapshot_dir(base, base_local_dir, cache_dir),skip_denoiser = seeded,skip_components = text_encoders_replaced,+ variant = variant,)return start_prefetch(paths, logger = logger)except Exception as exc: # noqa: BLE001 - a prefetch is only a hintdiff --git a/studio/backend/core/inference/diffusion_fp16_variant.py b/studio/backend/core/inference/diffusion_fp16_variant.pynew file mode 100644index 00000000000..0ad479f597f--- /dev/null+++ b/studio/backend/core/inference/diffusion_fp16_variant.py@@ -0,0 +1,219 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Read ``.fp16`` weight twins instead of fp32 defaults on fp16 loads (bit-identical after the cast).++fp16 targets only (fp16 -> bf16 rounds differently); needs a single-file twin for EVERY component and no class+pinning fp32 modules. Kill switch: ``UNSLOTH_DIFFUSION_FP16_VARIANT=0``.+"""++from __future__ import annotations++import json+import os+import re+from typing import Any, Iterable, Mapping, Optional++FP16_VARIANT = "fp16"+FP16_VARIANT_ENV = "UNSLOTH_DIFFUSION_FP16_VARIANT"++_STEMS = ("diffusion_pytorch_model", "model")+_DEFAULT_SINGLE_RE = re.compile(r"^(diffusion_pytorch_model|model)\.safetensors$")+_TWIN_SINGLE_RE = re.compile(r"^(diffusion_pytorch_model|model)\.fp16\.safetensors$")+_WEIGHT_RE = re.compile(+ r"^(?:diffusion_pytorch_model|pytorch_model|model)[.-].*(?:bin|safetensors)(?:\.index.*\.json)?$"+)+_WEIGHT_LIBRARIES = ("diffusers", "transformers")+++def fp16_variant_enabled() -> bool:+ return (os.environ.get(FP16_VARIANT_ENV) or "").strip().lower() not in (+ "0",+ "off",+ "false",+ "no",+ )+++def is_fp16_dtype(dtype: Any) -> bool:+ return str(dtype) in ("torch.float16", "float16")+++def is_fp16_twin(rfilename: str) -> bool:+ return bool(_TWIN_SINGLE_RE.match(str(rfilename).rsplit("/", 1)[-1]))+++_DEFAULT_ANY_RE = re.compile(+ r"^(?:diffusion_pytorch_model|pytorch_model|model)(?:-\d{5}-of-\d{5})?\.(?:bin|safetensors)$"+)+++def shadowed_twins(paths: Iterable[str]) -> set[str]:+ """Twins in ``paths`` whose folder also has a default weight file (the default load reads that one)."""+ paths = [str(p) for p in paths]+ default_dirs = {+ p.rpartition("/")[0] for p in paths if _DEFAULT_ANY_RE.match(p.rpartition("/")[2])+ }+ return {p for p in paths if is_fp16_twin(p) and p.rpartition("/")[0] in default_dirs}+++def twin_of(rfilename: str) -> Optional[str]:+ folder, _, name = str(rfilename).rpartition("/")+ match = _DEFAULT_SINGLE_RE.match(name)+ if not folder or match is None:+ return None+ return f"{folder}/{match.group(1)}.fp16.safetensors"+++def _class_pins_fp32(library: Any, class_name: Any) -> bool:+ """True when the component class keeps modules in fp32 at an fp16 load, or cannot be resolved (conservative)."""+ if library not in _WEIGHT_LIBRARIES or not isinstance(class_name, str) or not class_name:+ return True+ try:+ if library == "diffusers":+ import diffusers as module+ else:+ import transformers as module+ cls = getattr(module, class_name, None)+ except Exception: # noqa: BLE001 - an unimportable class decides nothing: keep the defaults+ return True+ if cls is None:+ return True+ return bool(+ getattr(cls, "_keep_in_fp32_modules", None)+ or getattr(cls, "_keep_in_fp32_modules_strict", None)+ )+++def plan_fp16_twins(+ names: Iterable[str],+ model_index: Optional[Mapping[str, Any]],+ *,+ components: Optional[Iterable[str]] = None,+) -> Optional[dict[str, str]]:+ """``{component: twin}`` when every weight-bearing component has a single-file twin in ``names``, else None."""+ if not isinstance(model_index, Mapping):+ return None+ specs: dict[str, tuple[Any, Any]] = {}+ for name, spec in model_index.items():+ if str(name).startswith("_") or not isinstance(spec, (list, tuple)) or len(spec) < 2:+ continue+ if spec[0] is None or spec[1] is None:+ continue+ specs[str(name)] = (spec[0], spec[1])+ wanted = set(specs) if components is None else {str(c) for c in components} & set(specs)+ by_folder: dict[str, set[str]] = {}+ for rel in names:+ folder, _, leaf = str(rel).rpartition("/")+ if folder in wanted and "/" not in folder:+ by_folder.setdefault(folder, set()).add(leaf)+ plan: dict[str, str] = {}+ for folder in sorted(wanted):+ leaves = by_folder.get(folder, set())+ if not any(_WEIGHT_RE.match(leaf) for leaf in leaves):+ continue+ twins = sorted(leaf for leaf in leaves if _TWIN_SINGLE_RE.match(leaf))+ if len(twins) != 1:+ return None # no twin, or an ambiguous pair (diffusion_pytorch_model + model)+ library, class_name = specs[folder]+ if _class_pins_fp32(library, class_name):+ return None+ plan[folder] = f"{folder}/{twins[0]}"+ return plan or None+++def read_model_index(snapshot: Optional[str]) -> Optional[dict]:+ if not snapshot:+ return None+ try:+ with open(os.path.join(snapshot, "model_index.json"), "r", encoding = "utf-8") as handle:+ payload = json.load(handle)+ except Exception: # noqa: BLE001 - no readable manifest: no variant+ return None+ return payload if isinstance(payload, dict) else None+++def _snapshot_names(snapshot: str, folders: Iterable[str]) -> list[str]:+ names: list[str] = []+ for folder in folders:+ path = os.path.join(snapshot, folder)+ try:+ entries = os.listdir(path)+ except OSError:+ continue+ for entry in entries:+ full = os.path.join(path, entry)+ try:+ if os.path.isfile(full) and os.path.getsize(full) > 0:+ names.append(f"{folder}/{entry}")+ except OSError:+ continue+ return names+++def is_default_weight(basename: str) -> bool:+ if _DEFAULT_ANY_RE.match(basename):+ return True+ return (+ basename.endswith(".index.json")+ and ".fp16." not in basename+ and bool(_WEIGHT_RE.match(basename))+ )+++def _defaults_present(names: Iterable[str], plan: Mapping[str, str]) -> bool:+ # Any default layout (single, sharded, .bin, an index) counts: only a folder with none reads the twins at bf16 / fp32.+ by_folder: dict[str, list[str]] = {}+ for name in names:+ folder, _, base = str(name).rpartition("/")+ by_folder.setdefault(folder, []).append(base)+ return all(any(is_default_weight(b) for b in by_folder.get(folder, ())) for folder in plan)+++def local_fp16_variant(+ snapshot: Optional[str],+ *,+ load_dtype: Any,+ torch_dtype: Any = None,+ supplied: Iterable[str] = (),+) -> Optional[str]:+ """``"fp16"`` when every non-supplied component has a twin on disk and the load is plain fp16 or twins-only."""+ if not fp16_variant_enabled() or not snapshot or not os.path.isdir(snapshot):+ return None+ index = read_model_index(snapshot)+ if index is None:+ return None+ skip = {str(s) for s in supplied}+ components = [+ name+ for name, spec in index.items()+ if not str(name).startswith("_")+ and name not in skip+ and isinstance(spec, (list, tuple))+ and len(spec) >= 2+ and spec[0] is not None+ and spec[1] is not None+ ]+ names = _snapshot_names(snapshot, components)+ plan = plan_fp16_twins(names, index, components = components)+ if plan is None:+ return None+ plain_fp16 = is_fp16_dtype(load_dtype) and (torch_dtype is None or is_fp16_dtype(torch_dtype))+ if plain_fp16 or not _defaults_present(names, plan):+ return FP16_VARIANT+ return None+++__all__ = [+ "FP16_VARIANT",+ "FP16_VARIANT_ENV",+ "fp16_variant_enabled",+ "is_default_weight",+ "is_fp16_dtype",+ "is_fp16_twin",+ "local_fp16_variant",+ "plan_fp16_twins",+ "read_model_index",+ "shadowed_twins",+ "twin_of",+]diff --git a/studio/backend/tests/test_diffusion_component_sizes.py b/studio/backend/tests/test_diffusion_component_sizes.pyindex 24aed11a5c7..17ce2d09ad6 100644--- a/studio/backend/tests/test_diffusion_component_sizes.py+++ b/studio/backend/tests/test_diffusion_component_sizes.py@@ -1255,12 +1255,14 @@ def test_loaded_role_with_unreadable_size_makes_its_term_unknown(tmp_path, monkedef test_no_index_fallback_takes_only_loader_names(tmp_path):- for name in (- "adapter_model.safetensors",- "weights.safetensors",- "diffusion_pytorch_model.fp16.safetensors",- ):+ for name in ("adapter_model.safetensors", "weights.safetensors"):assert dcs.select_weight_files([name], folder = "transformer") == []+ # A lone .fp16 twin is read; beside a default it is not.+ twin = "diffusion_pytorch_model.fp16.safetensors"+ assert dcs.select_weight_files([twin], folder = "transformer") == [twin]+ assert dcs.select_weight_files(+ [twin, "diffusion_pytorch_model.safetensors"], folder = "transformer"+ ) == ["diffusion_pytorch_model.safetensors"]_write_header(tmp_path / "transformer" / "adapter_model.safetensors", {"a": ("BF16", 10)})assert dcs.local_component_sizes(tmp_path) is Nonefor stem in ("diffusion_pytorch_model", "model", "pytorch_model"):diff --git a/studio/backend/tests/test_diffusion_fp16_variant.py b/studio/backend/tests/test_diffusion_fp16_variant.pynew file mode 100644index 00000000000..d273cf68ff0--- /dev/null+++ b/studio/backend/tests/test_diffusion_fp16_variant.py@@ -0,0 +1,437 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""An fp16 pipeline load reads the repo's ``.fp16`` twins (SDXL: 6.5 GB instead of the 12.9 GB fp32 defaults), and the+download plan, prefetch, size estimates and completeness checks agree with what it reads."""++from __future__ import annotations++import json+import types+from pathlib import Path++import pytest++from core.inference import diffusion as diffusion_mod+from core.inference import diffusion_fast_load as fl+from core.inference import diffusion_fp16_variant as fv+from core.inference.diffusion import DiffusionBackend+from core.inference.diffusion_auto_policy import (+ companion_bytes_from_declared,+ resident_bytes_from_declared,+)+from core.inference.diffusion_component_sizes import select_weight_files+from core.inference.diffusion_families import local_pipeline_components_are_complete++MIB = 1024 * 1024+SDXL = "stabilityai/stable-diffusion-xl-base-1.0"+SDXL_INDEX = {+ "_class_name": "StableDiffusionXLPipeline",+ "_diffusers_version": "0.19.0.dev0",+ "force_zeros_for_empty_prompt": True,+ "scheduler": ["diffusers", "EulerDiscreteScheduler"],+ "text_encoder": ["transformers", "CLIPTextModel"],+ "text_encoder_2": ["transformers", "CLIPTextModelWithProjection"],+ "tokenizer": ["transformers", "CLIPTokenizer"],+ "tokenizer_2": ["transformers", "CLIPTokenizer"],+ "unet": ["diffusers", "UNet2DConditionModel"],+ "vae": ["diffusers", "AutoencoderKL"],+}+# stabilityai/stable-diffusion-xl-base-1.0 @ 462165984030d822, sizes in bytes+SDXL_DEFAULTS = {+ "unet/diffusion_pytorch_model.safetensors": 10270077736,+ "vae/diffusion_pytorch_model.safetensors": 334643268,+ "text_encoder/model.safetensors": 492265168,+ "text_encoder_2/model.safetensors": 2778702264,+}+SDXL_TWINS = {+ "unet/diffusion_pytorch_model.fp16.safetensors": 5135149760,+ "vae/diffusion_pytorch_model.fp16.safetensors": 167335342,+ "text_encoder/model.fp16.safetensors": 246144152,+ "text_encoder_2/model.fp16.safetensors": 1389382176,+}+SDXL_CONFIGS = {+ "model_index.json": 609,+ "scheduler/scheduler_config.json": 479,+ "text_encoder/config.json": 565,+ "text_encoder_2/config.json": 575,+ "tokenizer/vocab.json": 1059962,+ "tokenizer/merges.txt": 524619,+ "tokenizer/tokenizer_config.json": 737,+ "tokenizer_2/vocab.json": 1059962,+ "tokenizer_2/merges.txt": 524619,+ "tokenizer_2/tokenizer_config.json": 725,+ "unet/config.json": 1680,+ "vae/config.json": 642,+ "unet/diffusion_pytorch_model.fp16.bin": 5135149760,+ "unet/openvino_model.bin": 5135149760,+ "text_encoder_2/flax_model.msgpack": 2778702264,+}++[email protected](autouse = True)+def _variant_on(monkeypatch):+ monkeypatch.delenv(fv.FP16_VARIANT_ENV, raising = False)+++def _snapshot(+ tmp_path: Path,+ files,+ index = SDXL_INDEX,+) -> Path:+ snap = tmp_path / "snap"+ snap.mkdir(parents = True, exist_ok = True)+ (snap / "model_index.json").write_text(json.dumps(index))+ for rel in files:+ if rel == "model_index.json":+ continue+ path = snap / rel+ path.parent.mkdir(parents = True, exist_ok = True)+ if rel.endswith("config.json"):+ path.write_text(json.dumps({"_class_name": "X"}))+ else:+ path.write_bytes(b"w")+ return snap+++# Backend CI has neither diffusers nor transformers, and an unresolvable class keeps the defaults (conservative):+# resolve the classes these tests name from a table, and check the real lookup separately where the libraries exist.+_PINS_FP32 = {+ "UNet2DConditionModel": False,+ "AutoencoderKL": False,+ "AutoencoderKLFlux2": False,+ "CLIPTextModel": False,+ "CLIPTextModelWithProjection": False,+ "UNet2DModel": False,+ "T5EncoderModel": True,+}++[email protected](autouse = True)+def _class_table(monkeypatch):+ monkeypatch.setattr(+ fv,+ "_class_pins_fp32",+ lambda library, class_name: library not in fv._WEIGHT_LIBRARIES+ or _PINS_FP32.get(class_name, True),+ )+++def test_the_real_class_lookup_reads_keep_in_fp32_modules(monkeypatch):+ pytest.importorskip("diffusers")+ pytest.importorskip("transformers")+ monkeypatch.undo()+ assert fv._class_pins_fp32("diffusers", "UNet2DConditionModel") is False+ assert fv._class_pins_fp32("transformers", "CLIPTextModel") is False+ assert fv._class_pins_fp32("transformers", "T5EncoderModel") is True+ assert fv._class_pins_fp32("diffusers", "NoSuchModel") is True+ assert fv._class_pins_fp32("not_a_library", "UNet2DConditionModel") is True+++def test_every_sdxl_component_maps_to_its_twin():+ names = [*SDXL_CONFIGS, *SDXL_DEFAULTS, *SDXL_TWINS]+ assert fv.plan_fp16_twins(names, SDXL_INDEX) == {+ "text_encoder": "text_encoder/model.fp16.safetensors",+ "text_encoder_2": "text_encoder_2/model.fp16.safetensors",+ "unet": "unet/diffusion_pytorch_model.fp16.safetensors",+ "vae": "vae/diffusion_pytorch_model.fp16.safetensors",+ }++[email protected]("missing", sorted(SDXL_TWINS))+def test_one_missing_twin_keeps_the_defaults(missing):+ names = [*SDXL_CONFIGS, *SDXL_DEFAULTS, *(t for t in SDXL_TWINS if t != missing)]+ assert fv.plan_fp16_twins(names, SDXL_INDEX) is None+++def test_a_sharded_twin_or_a_bin_twin_is_not_a_twin():+ names = [n for n in (*SDXL_CONFIGS, *SDXL_DEFAULTS, *SDXL_TWINS) if not n.startswith("unet/")]+ sharded = names + [+ "unet/diffusion_pytorch_model.fp16-00001-of-00002.safetensors",+ "unet/diffusion_pytorch_model.fp16-00002-of-00002.safetensors",+ "unet/diffusion_pytorch_model.safetensors.index.fp16.json",+ ]+ assert fv.plan_fp16_twins(sharded, SDXL_INDEX) is None+ assert fv.plan_fp16_twins(names + ["unet/diffusion_pytorch_model.fp16.bin"], SDXL_INDEX) is None+++def test_a_component_not_read_from_the_repo_needs_no_twin():+ names = [+ n+ for n in (*SDXL_CONFIGS, *SDXL_DEFAULTS, *SDXL_TWINS)+ if n != "text_encoder_2/model.fp16.safetensors"+ ]+ assert fv.plan_fp16_twins(names, SDXL_INDEX) is None+ plan = fv.plan_fp16_twins(names, SDXL_INDEX, components = ("unet", "vae", "text_encoder"))+ assert set(plan) == {"unet", "vae", "text_encoder"}+++def test_a_class_that_pins_fp32_modules_keeps_the_defaults():+ # T5EncoderModel keeps ``wo`` in fp32 at an fp16 load: a twin would upcast fp16-rounded weights.+ index = {**SDXL_INDEX, "text_encoder_2": ["transformers", "T5EncoderModel"]}+ assert fv.plan_fp16_twins([*SDXL_DEFAULTS, *SDXL_TWINS], index) is None+ unknown = {**SDXL_INDEX, "unet": ["diffusers", "NoSuchModel"]}+ assert fv.plan_fp16_twins([*SDXL_DEFAULTS, *SDXL_TWINS], unknown) is None+++def test_twin_names():+ assert fv.twin_of("unet/diffusion_pytorch_model.safetensors") == (+ "unet/diffusion_pytorch_model.fp16.safetensors"+ )+ assert fv.twin_of("text_encoder/model.safetensors") == "text_encoder/model.fp16.safetensors"+ assert fv.twin_of("text_encoder/model-00001-of-00002.safetensors") is None+ assert fv.twin_of("unet/diffusion_pytorch_model.fp16.safetensors") is None+ assert fv.is_fp16_twin("vae/diffusion_pytorch_model.fp16.safetensors")+ assert not fv.is_fp16_twin("vae/diffusion_pytorch_model.safetensors")+ assert not fv.is_fp16_twin("vae/diffusion_pytorch_model.fp16.bin")+++def test_an_fp16_load_reads_the_twins_and_a_bf16_load_the_defaults(tmp_path):+ snap = _snapshot(tmp_path, [*SDXL_CONFIGS, *SDXL_DEFAULTS, *SDXL_TWINS])+ assert fv.local_fp16_variant(str(snap), load_dtype = "torch.float16") == "fp16"+ import torch++ assert (+ fv.local_fp16_variant(str(snap), load_dtype = torch.float16, torch_dtype = torch.float16)+ == "fp16"+ )+ # fp16 -> bf16 rounds differently from fp32 -> bf16: a bf16 / fp32 load keeps the defaults.+ assert fv.local_fp16_variant(str(snap), load_dtype = torch.bfloat16) is None+ assert fv.local_fp16_variant(str(snap), load_dtype = torch.float32) is None+ mapped = {"default": torch.float16, "unet": torch.float32}+ assert fv.local_fp16_variant(str(snap), load_dtype = torch.float16, torch_dtype = mapped) is None+++def test_defaults_only_snapshot_never_asks_for_the_variant(tmp_path):+ snap = _snapshot(tmp_path, [*SDXL_CONFIGS, *SDXL_DEFAULTS])+ assert fv.local_fp16_variant(str(snap), load_dtype = "torch.float16") is None+++def test_twins_only_snapshot_loads_the_twins_at_any_dtype(tmp_path):+ # Twins-only snapshot: without the variant nothing loads.+ import torch+ snap = _snapshot(tmp_path, [*SDXL_CONFIGS, *SDXL_TWINS])+ assert fv.local_fp16_variant(str(snap), load_dtype = torch.bfloat16) == "fp16"+++ "unet_defaults",+ [+ (+ "unet/diffusion_pytorch_model-00001-of-00002.safetensors",+ "unet/diffusion_pytorch_model-00002-of-00002.safetensors",+ ),+ ("unet/diffusion_pytorch_model.safetensors.index.json",),+ ("unet/diffusion_pytorch_model.bin",),+ ],+)+def test_sharded_or_bin_defaults_beside_twins_keep_a_bf16_load_on_the_defaults(+ tmp_path, unet_defaults+):+ import torch++ defaults = [d for d in SDXL_DEFAULTS if not d.startswith("unet/")]+ snap = _snapshot(tmp_path, [*SDXL_CONFIGS, *defaults, *unet_defaults, *SDXL_TWINS])+ assert fv.local_fp16_variant(str(snap), load_dtype = torch.bfloat16) is None+ assert fv.local_fp16_variant(str(snap), load_dtype = torch.float16) == "fp16"+++def test_a_supplied_component_needs_no_twin_on_disk(tmp_path):+ files = [+ *SDXL_CONFIGS,+ *SDXL_DEFAULTS,+ *(t for t in SDXL_TWINS if not t.startswith("text_encoder_2/")),+ ]+ snap = _snapshot(tmp_path, files)+ assert fv.local_fp16_variant(str(snap), load_dtype = "torch.float16") is None+ assert (+ fv.local_fp16_variant(+ str(snap), load_dtype = "torch.float16", supplied = ("text_encoder_2", "torch_dtype")+ )+ == "fp16"+ )+++def test_kill_switch(tmp_path, monkeypatch):+ snap = _snapshot(tmp_path, [*SDXL_CONFIGS, *SDXL_DEFAULTS, *SDXL_TWINS])+ monkeypatch.setenv(fv.FP16_VARIANT_ENV, "0")+ assert fv.local_fp16_variant(str(snap), load_dtype = "torch.float16") is None+++def _stub_hub(+ monkeypatch,+ tmp_path,+ cached = (),+):+ manifest = tmp_path / "model_index.json"+ manifest.write_text(json.dumps(SDXL_INDEX))+ files = {**SDXL_CONFIGS, **SDXL_DEFAULTS, **SDXL_TWINS}++ class _Api:+ def model_info(self, repo_id, **_kwargs):+ siblings = [types.SimpleNamespace(rfilename = n, size = s) for n, s in files.items()]+ return types.SimpleNamespace(siblings = siblings, sha = "4" * 40)++ monkeypatch.setattr("huggingface_hub.HfApi", lambda *a, **k: _Api())+ monkeypatch.setattr("huggingface_hub.hf_hub_download", lambda *a, **k: str(manifest))+ monkeypatch.setattr(+ "huggingface_hub.try_to_load_from_cache",+ lambda repo_id, filename, **k: f"/cache/{filename}" if filename in cached else None,+ )+ monkeypatch.setattr(diffusion_mod, "prefer_ungated_mirror", lambda repo_id, *a, **k: repo_id)+++def _plan(fp16_twins):+ resident: list = []+ total, files = DiffusionBackend._estimate_download_bytes(+ SDXL,+ None,+ SDXL,+ None,+ kind = "pipeline",+ resident_file_sizes_out = resident,+ fp16_twins = fp16_twins,+ )+ return total, set(files), dict(resident)+++def test_an_fp16_plan_stages_the_twins_instead_of_the_defaults(monkeypatch, tmp_path):+ _stub_hub(monkeypatch, tmp_path)+ total, files, resident = _plan(True)+ assert set(SDXL_TWINS) <= files and not (set(SDXL_DEFAULTS) & files)+ assert resident == SDXL_TWINS+ configs = sum(s for n, s in SDXL_CONFIGS.items() if n.endswith((".json", ".txt")))+ assert total == sum(SDXL_TWINS.values()) + configs+ # Twins price 1:1.+ twins_resident = resident_bytes_from_declared(SDXL, resident.items())+ assert twins_resident == sum(SDXL_TWINS.values())+ assert (+ abs(twins_resident / resident_bytes_from_declared(SDXL, SDXL_DEFAULTS.items()) - 1) < 0.001+ )+++def test_a_bf16_plan_is_unchanged(monkeypatch, tmp_path):+ _stub_hub(monkeypatch, tmp_path)+ total, files, resident = _plan(False)+ assert set(SDXL_DEFAULTS) <= files and not (set(SDXL_TWINS) & files)+ assert resident == SDXL_DEFAULTS+++def test_cached_defaults_are_not_downloaded_again_as_twins(monkeypatch, tmp_path):+ _stub_hub(monkeypatch, tmp_path, cached = SDXL_DEFAULTS)+ _total, files, _resident = _plan(True)+ assert set(SDXL_DEFAULTS) <= files and not (set(SDXL_TWINS) & files)+ _stub_hub(monkeypatch, tmp_path, cached = (*SDXL_DEFAULTS, *SDXL_TWINS))+ assert set(SDXL_TWINS) <= _plan(True)[1]+++def test_kill_switch_keeps_the_default_plan(monkeypatch, tmp_path):+ _stub_hub(monkeypatch, tmp_path)+ monkeypatch.setenv(fv.FP16_VARIANT_ENV, "0")+ assert set(SDXL_DEFAULTS) <= _plan(True)[1]+++def test_resident_estimate_ignores_a_twin_beside_its_default():+ both = {**SDXL_DEFAULTS, **SDXL_TWINS}+ assert resident_bytes_from_declared(SDXL, both.items()) == resident_bytes_from_declared(+ SDXL, SDXL_DEFAULTS.items()+ )+ assert companion_bytes_from_declared(SDXL, both.items()) == companion_bytes_from_declared(+ SDXL, SDXL_DEFAULTS.items()+ )+ twins_te = {k: v for k, v in SDXL_TWINS.items() if not k.startswith("unet/")}+ assert companion_bytes_from_declared(SDXL, twins_te.items()) == sum(twins_te.values())+++def test_prefetch_reads_the_twins_the_load_reads(tmp_path):+ snap = _snapshot(tmp_path, [*SDXL_CONFIGS, *SDXL_DEFAULTS, *SDXL_TWINS])+ rel = lambda paths: sorted(p[len(str(snap)) + 1 :] for p in paths) # noqa: E731+ assert rel(fl.pipeline_component_files(str(snap), skip_denoiser = False)) == sorted(SDXL_DEFAULTS)+ assert rel(+ fl.pipeline_component_files(str(snap), skip_denoiser = False, variant = "fp16")+ ) == sorted(SDXL_TWINS)+++def test_header_sizes_fall_back_to_a_lone_twin():+ assert select_weight_files(["model.fp16.safetensors"], folder = "text_encoder") == [+ "model.fp16.safetensors"+ ]+ assert select_weight_files(+ ["diffusion_pytorch_model.safetensors", "diffusion_pytorch_model.fp16.safetensors"],+ folder = "unet",+ ) == ["diffusion_pytorch_model.safetensors"]+++def test_a_twins_only_snapshot_is_complete(tmp_path):+ snap = _snapshot(tmp_path, [*SDXL_CONFIGS, *SDXL_TWINS])+ assert local_pipeline_components_are_complete(snap, "model_index.json")+ (snap / "unet" / "diffusion_pytorch_model.fp16.safetensors").unlink()+ assert not local_pipeline_components_are_complete(snap, "model_index.json")+++def test_a_mix_of_twins_and_defaults_the_loader_cannot_open_is_incomplete(tmp_path, monkeypatch):+ # unet only as a twin, every other component only as a default: no pipeline-wide variant reads both.+ mixed = [t for t in SDXL_TWINS if t.startswith("unet/")]+ mixed += [d for d in SDXL_DEFAULTS if not d.startswith("unet/")]+ snap = _snapshot(tmp_path, [*SDXL_CONFIGS, *mixed])+ assert fv.local_fp16_variant(str(snap), load_dtype = "torch.float16") is None+ assert not local_pipeline_components_are_complete(snap, "model_index.json")+ monkeypatch.setenv(fv.FP16_VARIANT_ENV, "0")+ full = _snapshot(tmp_path / "full", [*SDXL_CONFIGS, *SDXL_TWINS])+ assert not local_pipeline_components_are_complete(full, "model_index.json")+++def test_local_pricing_reads_twins_only_where_no_default_sits(tmp_path, monkeypatch):+ import torch++ monkeypatch.setattr(+ DiffusionBackend, "_safetensors_cast_bytes", staticmethod(lambda path, itemsize, pinned: 7)+ )+ configs = [n for n in SDXL_CONFIGS if n.endswith((".json", ".txt"))]+ snap = _snapshot(tmp_path, [*configs, *SDXL_TWINS])+ priced = DiffusionBackend._local_dir_weight_sizes(+ snap, exclude_transformer = False, load_dtype = torch.float16+ )+ assert set(priced) == set(SDXL_TWINS)+ snap_both = _snapshot(tmp_path / "b", [*configs, *SDXL_DEFAULTS, *SDXL_TWINS])+ priced = DiffusionBackend._local_dir_weight_sizes(+ snap_both, exclude_transformer = False, load_dtype = torch.float16+ )+ assert set(priced) == set(SDXL_DEFAULTS)+++def test_a_supplied_component_unblocks_the_twins_its_cached_default_blocked(tmp_path):+ # vae cached only as its default file, every other component staged as a twin: the vae is supplied.+ files = [*SDXL_CONFIGS, "vae/diffusion_pytorch_model.safetensors"]+ files += [t for t in SDXL_TWINS if not t.startswith("vae/")]+ snap = _snapshot(tmp_path, files)+ assert fv.local_fp16_variant(str(snap), load_dtype = "torch.float16") is None+ assert fv.local_fp16_variant(str(snap), load_dtype = "torch.float16", supplied = ("vae",)) == "fp16"+++def test_the_load_recomputes_the_variant_with_the_final_kwargs_even_after_a_first_none():+ import inspect++ source = inspect.getsource(diffusion_mod)+ assert "if _fp16_variant_eligible:" in source+ assert (+ "if _fp16_variant is not None:\n # Final kwargs"+ not in source+ )+++def test_a_fixed_folder_assembler_never_accepts_a_lone_twin(tmp_path):+ # FLUX.3's assembler opens each folder without a variant: an fp16-only vae cannot load there.+ snap = _snapshot(tmp_path, [*SDXL_CONFIGS, *SDXL_DEFAULTS])+ folders = {+ "vae": ("vae", "diffusers", "AutoencoderKL"),+ "unet": ("unet", "diffusers", "UNet2DConditionModel"),+ }+ assert local_pipeline_components_are_complete(+ snap, "model_index.json", fixed_component_folders = folders+ )+ (snap / "vae" / "diffusion_pytorch_model.safetensors").unlink()+ (snap / "vae" / "diffusion_pytorch_model.fp16.safetensors").write_bytes(b"x" * 8)+ assert not local_pipeline_components_are_complete(+ snap, "model_index.json", fixed_component_folders = folders+ )