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: size the image memory plan at the dtype the pipeline loads in (SDXL resident on 24 GB) (#11922)

Daniel Han9cf9a34968c4
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.py
index 018917bf99a..41204cd2676 100644
--- a/studio/backend/core/inference/diffusion.py
+++ b/studio/backend/core/inference/diffusion.py
@@ -1137,6 +1137,48 @@ def _resolve_diffusion_compute_dtype(fam: Optional[DiffusionFamily], dtype: Any)
return torch.float32 if dtype == torch.float16 else dtype
+def _float_load_itemsize(dtype: Any) -> Optional[int]:
+ try:
+ import torch
+ if isinstance(dtype, torch.dtype) and dtype.is_floating_point:
+ return int(dtype.itemsize)
+ except Exception: # noqa: BLE001 - no torch: keep on-disk sizing
+ pass
+ return None
+
+
+def _class_pins_fp32(class_name: str, load_dtype: Any) -> tuple[str, ...]:
+ """Diffusers pins at both halves; Transformers pins ``_keep_in_fp32_modules`` only at fp16."""
+ for lib in ("diffusers", "transformers"):
+ module = sys.modules.get(lib)
+ try:
+ cls = getattr(module, class_name, None) if module is not None else None
+ except Exception: # noqa: BLE001 - an unimportable class tells us nothing
+ cls = None
+ if cls is None:
+ continue
+ pinned = list(getattr(cls, "_keep_in_fp32_modules_strict", None) or ())
+ if lib == "diffusers" or str(load_dtype) == "torch.float16":
+ pinned += list(getattr(cls, "_keep_in_fp32_modules", None) or ())
+ # Diffusers tests each pin against single name segments, so a dotted pin never matches there.
+ return tuple(str(name) for name in pinned if lib != "diffusers" or "." not in str(name))
+ return ()
+
+
+def _component_pins_fp32(folder: Path, load_dtype: Any) -> tuple[str, ...]:
+ try:
+ config = json.loads((folder / "config.json").read_text(encoding = "utf-8"))
+ names = [config.get("_class_name"), *(config.get("architectures") or ())]
+ except Exception: # noqa: BLE001 - no readable config: nothing is pinned by name
+ return ()
+ return tuple(
+ pin
+ for name in names
+ if isinstance(name, str) and name
+ for pin in _class_pins_fp32(name, load_dtype)
+ )
+
+
def _install_gguf_prefix_strip(transformer_cls: Any, logger: Any) -> None:
"""Wrap the class's diffusers single-file converter to strip the ``model.diffusion_model.``
container prefix that sd.cpp-converted GGUFs carry on every tensor.
@@ -4477,10 +4519,17 @@ class DiffusionBackend:
return sum(sizes.values())
@staticmethod
- def _local_dir_weight_sizes(path: Path, *, exclude_transformer: bool) -> dict[str, int]:
+ def _local_dir_weight_sizes(
+ path: Path,
+ *,
+ exclude_transformer: bool,
+ load_dtype: Any = None,
+ ) -> dict[str, int]:
"""``{relative path: on-disk bytes}`` for the weight files under a diffusers directory. Per
file, not a total, so callers merging several trees can dedupe by path. See
- ``_local_dir_weight_bytes`` for what the filter is for."""
+ ``_local_dir_weight_bytes`` for what the filter is for. ``load_dtype`` prices what
+ ``from_pretrained`` holds instead (default variant, safetensors over ``.bin``, cast floats)."""
+ load_itemsize = _float_load_itemsize(load_dtype)
sizes: dict[str, int] = {}
for f in path.rglob("*"):
if f.suffix.lower() not in (".safetensors", ".bin", ".pt", ".ckpt"):
@@ -4491,14 +4540,147 @@ class DiffusionBackend:
continue
if exclude_transformer and rel.parts and rel.parts[0] == "transformer":
continue
+ if load_itemsize is not None and (
+ len(rel.parts) < 2 or not _pipeline_default_variant_file(rel.as_posix())
+ ):
+ continue
try:
sizes[rel.as_posix()] = f.stat().st_size
except OSError:
continue
+ if load_itemsize is None:
+ return sizes
+ # A .bin only loses to a safetensors checkpoint the loader can select: unsharded, or shards with their index.
+ st_dirs = {
+ rel.rsplit("/", 1)[0]
+ for rel in sizes
+ if _SELECTABLE_SAFETENSORS_RE.match(rel.rsplit("/", 1)[-1])
+ } | {
+ index.parent.relative_to(path).as_posix()
+ for index in path.glob("*/*.safetensors.index.json")
+ if _DEFAULT_PIPELINE_WEIGHT_INDEX_RE.match(index.name)
+ }
+ for rel in list(sizes):
+ if rel.endswith(".bin") and rel.rsplit("/", 1)[0] in st_dirs:
+ del sizes[rel]
+ elif rel.endswith((".safetensors", ".bin")):
+ pinned = (
+ _component_pins_fp32((path / rel).parent, load_dtype)
+ if load_itemsize < 4
+ else ()
+ )
+ reader = (
+ DiffusionBackend._safetensors_cast_bytes
+ if rel.endswith(".safetensors")
+ else DiffusionBackend._bin_cast_bytes
+ )
+ cast = reader(path / rel, load_itemsize, pinned)
+ if cast is not None:
+ sizes[rel] = cast
return sizes
@staticmethod
- def _local_dir_weight_bytes(path: Path, *, exclude_transformer: bool) -> int:
+ def _safetensors_cast_bytes(
+ path: Path,
+ itemsize: int,
+ pinned: tuple[str, ...] = (),
+ ) -> Optional[int]:
+ """A half load narrows only a file stored wider throughout (a mixed file pins its fp32 norms)."""
+ try:
+ with open(path, "rb") as fh:
+ length = int.from_bytes(fh.read(8), "little")
+ if length > 100_000_000:
+ return None
+ header = json.loads(fh.read(length))
+ tensors = []
+ for name, meta in header.items():
+ if name == "__metadata__" or not isinstance(meta, dict):
+ continue
+ dtype = str(meta.get("dtype", ""))
+ if dtype not in _SAFETENSORS_FLOAT_WIDTH and dtype not in ("I64", "I32", "BOOL"):
+ return None
+ begin, end = meta["data_offsets"]
+ numel = 1
+ for dim in meta.get("shape", []):
+ numel *= int(dim)
+ tensors.append(
+ (name, _SAFETENSORS_FLOAT_WIDTH.get(dtype), numel, int(end) - int(begin))
+ )
+ return DiffusionBackend._cast_tensor_bytes(tensors, itemsize, pinned)
+ except Exception: # noqa: BLE001 - corrupt/crafted header keeps the on-disk size
+ return None
+
+ @staticmethod
+ def _bin_cast_bytes(
+ path: Path,
+ itemsize: int,
+ pinned: tuple[str, ...] = (),
+ ) -> Optional[int]:
+ try:
+ import torch
+
+ state = torch.load(path, map_location = "cpu", mmap = True, weights_only = True)
+ if not isinstance(state, dict):
+ return None
+ tensors = []
+ seen: set = set()
+ for name, tensor in state.items():
+ if not isinstance(tensor, torch.Tensor):
+ return None
+ # Tied weights are saved once and load as one tensor: count an exact alias once.
+ alias = (
+ tensor.untyped_storage().data_ptr(),
+ tensor.storage_offset(),
+ tuple(tensor.shape),
+ tuple(tensor.stride()),
+ tensor.dtype,
+ )
+ if alias in seen:
+ continue
+ seen.add(alias)
+ width = int(tensor.element_size()) if tensor.is_floating_point() else None
+ numel = int(tensor.numel())
+ tensors.append((str(name), width, numel, numel * int(tensor.element_size())))
+ del state
+ return DiffusionBackend._cast_tensor_bytes(tensors, itemsize, pinned)
+ except Exception: # noqa: BLE001 - unreadable pickle keeps the on-disk size
+ return None
+
+ @staticmethod
+ def _cast_tensor_bytes(
+ tensors: list[tuple[str, Optional[int], int, int]],
+ itemsize: int,
+ pinned: tuple[str, ...] = (),
+ ) -> Optional[int]:
+ widths = [width for _, width, _, _ in tensors if width is not None]
+ if not widths:
+ return None
+ narrows = min(widths) > itemsize
+ # The loaders' own match: a pin names whole dot-separated segments, dotted pins included.
+ pin_match = (
+ re.compile("|".join(rf"(^|\.){re.escape(pin)}($|\.)" for pin in pinned)).search
+ if pinned
+ else None
+ )
+ total = 0
+ for name, width, numel, stored in tensors:
+ if width is None:
+ total += stored
+ elif itemsize >= 4 or (pin_match is not None and pin_match(name)):
+ total += numel * 4
+ elif narrows:
+ total += numel * itemsize
+ else:
+ total += stored
+ return total
+
+ @staticmethod
+ def _local_dir_weight_bytes(
+ path: Path,
+ *,
+ exclude_transformer: bool,
+ load_dtype: Any = None,
+ ) -> int:
"""Sum the on-disk weight files under a local diffusers directory. The HF blob cache is
empty for a local path, so this is the only size signal for auto memory planning; without
it a large local model folds to zero and the planner skips offload and OOMs.
@@ -4506,7 +4688,7 @@ class DiffusionBackend:
a full pipeline load keeps it."""
return sum(
DiffusionBackend._local_dir_weight_sizes(
- path, exclude_transformer = exclude_transformer
+ path, exclude_transformer = exclude_transformer, load_dtype = load_dtype
).values()
)
@@ -4552,7 +4734,11 @@ class DiffusionBackend:
return sum(merged.values())
@staticmethod
- def _companion_cache_bytes(base: str, staged_dir: Optional[str] = None) -> int:
+ def _companion_cache_bytes(
+ base: str,
+ staged_dir: Optional[str] = None,
+ load_dtype: Any = None,
+ ) -> int:
"""Resident companion (VAE + text-encoder) size for the memory plan. Excludes
``transformer/`` (supplied by the GGUF/single file, not resident here), otherwise the
dense-quant prefetch's cached transformer shards would inflate this and wrongly force
@@ -4560,12 +4746,14 @@ class DiffusionBackend:
preserves the subfolder split needed to exclude it."""
return DiffusionBackend._union_over_cached_revs(
base,
- lambda d: DiffusionBackend._local_dir_weight_sizes(d, exclude_transformer = True),
+ lambda d: DiffusionBackend._local_dir_weight_sizes(
+ d, exclude_transformer = True, load_dtype = load_dtype
+ ),
staged_dir,
)
@staticmethod
- def _local_dir_text_encoder_sizes(path: Path) -> dict[str, int]:
+ def _local_dir_text_encoder_sizes(path: Path, load_dtype: Any = None) -> dict[str, int]:
"""``{relative path: on-disk bytes}`` for the TEXT-ENCODER weight files under a diffusers
directory: the ``text_encoder*`` subfolders of what ``_local_dir_weight_sizes`` returns.
Derived from that same walk rather than a second one, so the text-encoder term is a
@@ -4573,21 +4761,25 @@ class DiffusionBackend:
return {
rel: size
for rel, size in DiffusionBackend._local_dir_weight_sizes(
- path, exclude_transformer = True
+ path, exclude_transformer = True, load_dtype = load_dtype
).items()
# Prefix, not equality: families ship text_encoder, text_encoder_2, text_encoder_3.
if rel.split("/", 1)[0].startswith("text_encoder")
}
@staticmethod
- def _text_encoder_cache_bytes(base: str, staged_dir: Optional[str] = None) -> int:
+ def _text_encoder_cache_bytes(
+ base: str,
+ staged_dir: Optional[str] = None,
+ load_dtype: Any = None,
+ ) -> int:
"""Text-encoder size for the memory plan: the share of ``_companion_cache_bytes`` the
planner can move off the resident floor by streaming the encoders. Same
union-over-cache-roots merge as the companion total, keyed on the same relative paths, so
a repo split across two roots is counted once in BOTH terms."""
return DiffusionBackend._union_over_cached_revs(
base,
- DiffusionBackend._local_dir_text_encoder_sizes,
+ lambda d: DiffusionBackend._local_dir_text_encoder_sizes(d, load_dtype),
staged_dir,
)
@@ -7441,6 +7633,9 @@ class DiffusionBackend:
if device_memory_override is not None
else settled_snapshot_device_memory(target)
)
+ load_dtype = getattr(target, "dtype", None)
+ if _float_load_itemsize(load_dtype) is None:
+ load_dtype = None
companions_from_cache = False
if kind == "pipeline" and transformer_resident_override_mib is not None:
# Re-planning an assembled pipeline against its dense-quant candidate. The family estimate already
@@ -7469,6 +7664,30 @@ class DiffusionBackend:
else 0,
self._cache_bytes(cache_repo) if cache_repo else 0,
)
+ if load_dtype is not None:
+ # Cached bytes are what the repo STORES, not what the load holds at this dtype.
+ loaded = max(
+ self._local_dir_weight_bytes(
+ local_repo, exclude_transformer = False, load_dtype = load_dtype
+ )
+ if local_repo is not None and local_repo.is_dir()
+ else 0,
+ self._local_dir_weight_bytes(
+ staged_repo, exclude_transformer = False, load_dtype = load_dtype
+ )
+ if staged_repo is not None and staged_repo.is_dir()
+ else 0,
+ self._union_over_cached_revs(
+ cache_repo,
+ lambda d: self._local_dir_weight_sizes(
+ d, exclude_transformer = False, load_dtype = load_dtype
+ ),
+ )
+ if cache_repo
+ else 0,
+ )
+ if loaded:
+ cached = loaded
cached_mib = int(cached // (1024 * 1024)) if cached else None
model_dense_mib = estimate_safetensors_dense_mib(cached_mib)
# A repo can store weights NARROWER than the loaded dtype (ideogram-4 ships raw float8), so cached bytes
@@ -7496,9 +7715,11 @@ class DiffusionBackend:
# The whole repo is the model, but its companions still sit in their own subfolders, so the same walk the
# GGUF/single-file branch uses splits them out here too. Without the split both group tiers fail on None
# and a pipeline that does not fit resident can only ever reach whole-module offload.
- companion = self._companion_cache_bytes(fetch_base or base, base_local_dir)
+ companion = self._companion_cache_bytes(fetch_base or base, base_local_dir, load_dtype)
companion_mib = int(companion // (1024 * 1024)) if companion else None
- text_encoder = self._text_encoder_cache_bytes(fetch_base or base, base_local_dir)
+ text_encoder = self._text_encoder_cache_bytes(
+ fetch_base or base, base_local_dir, load_dtype
+ )
text_encoder_mib = int(text_encoder // (1024 * 1024)) if text_encoder else None
companions_from_cache = True
if is_narrow_base and table is not None:
@@ -7542,12 +7763,16 @@ class DiffusionBackend:
# Scan the repo the bytes were staged from, and hand over the staged snapshot too: a base served from
# the import-time root is invisible to a hub-id scan of the live one, so the VAE + text encoders would
# load unbudgeted.
- companion = self._companion_cache_bytes(fetch_base or base, base_local_dir)
+ companion = self._companion_cache_bytes(
+ fetch_base or base, base_local_dir, load_dtype
+ )
companion_mib = int(companion // (1024 * 1024)) if companion else None
# The text-encoder share of that companion total, from the SAME walk over the same trees, so the
# subtraction the planner does is exact rather than two estimates meeting in the middle. 0 bytes reads
# as nothing cached, i.e. no split.
- text_encoder = self._text_encoder_cache_bytes(fetch_base or base, base_local_dir)
+ text_encoder = self._text_encoder_cache_bytes(
+ fetch_base or base, base_local_dir, load_dtype
+ )
text_encoder_mib = int(text_encoder // (1024 * 1024)) if text_encoder else None
companions_from_cache = True
model_dense_mib = None
@@ -7565,7 +7790,9 @@ class DiffusionBackend:
fetch_base or base,
lambda d: {
rel: size
- for rel, size in self._local_dir_text_encoder_sizes(d).items()
+ for rel, size in self._local_dir_text_encoder_sizes(
+ d, load_dtype
+ ).items()
if rel.split("/", 1)[0] in covered
},
base_local_dir,
@@ -9244,6 +9471,10 @@ _DEFAULT_PIPELINE_WEIGHT_RE = re.compile(
_DEFAULT_PIPELINE_WEIGHT_INDEX_RE = re.compile(
r"^(?:diffusion_pytorch_model|pytorch_model|model)\.(?:bin|safetensors)\.index\.json$"
)
+_SELECTABLE_SAFETENSORS_RE = re.compile(
+ r"^(?:diffusion_pytorch_model|pytorch_model|model)\.safetensors$"
+)
+_SAFETENSORS_FLOAT_WIDTH = {"F64": 8, "F32": 4, "F16": 2, "BF16": 2}
_PIPELINE_WEIGHT_PREFIX_RE = re.compile(
r"^(?:diffusion_pytorch_model|pytorch_model|model)[.-].*"
r"(?:bin|safetensors)(?:\.index.*\.json)?$"
diff --git a/studio/backend/tests/test_diffusion_backend.py b/studio/backend/tests/test_diffusion_backend.py
index 4e1e0645e1d..7dedc5b76eb 100644
--- a/studio/backend/tests/test_diffusion_backend.py
+++ b/studio/backend/tests/test_diffusion_backend.py
@@ -3671,10 +3671,10 @@ def test_plan_memory_sizes_the_mirrored_companion_cache(monkeypatch, tmp_path):
monkeypatch.setattr(
DiffusionBackend,
"_companion_cache_bytes",
- # Second arg is the staged snapshot dir, unused here: what this pins is that the
- # MIRROR id is the one sized.
staticmethod(
- lambda base, staged = None: 8 * 1024 * 1024 if base == "unsloth/FLUX.1-dev" else 0
+ lambda base, staged = None, load_dtype = None: (
+ 8 * 1024 * 1024 if base == "unsloth/FLUX.1-dev" else 0
+ )
),
)
seen: dict = {}
diff --git a/studio/backend/tests/test_diffusion_plan_load_dtype.py b/studio/backend/tests/test_diffusion_plan_load_dtype.py
new file mode 100644
index 00000000000..d0d2b6224aa
--- /dev/null
+++ b/studio/backend/tests/test_diffusion_plan_load_dtype.py
@@ -0,0 +1,453 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""SDXL-Turbo's fp32 shards, sized as stored, sent it to whole-model offload on 24 GB cards."""
+
+import json
+import sys
+import types
+
+import pytest
+
+torch = pytest.importorskip("torch")
+
+from core.inference import diffusion as dmod
+from core.inference.diffusion import DiffusionBackend
+from core.inference.diffusion_memory import (
+ OFFLOAD_NONE,
+ DeviceMemory,
+ unified_memory_shortfall_message,
+)
+
+MIB = 1024 * 1024
+REPO = "org/sdxl-like"
+REV = "a" * 40
+
+
+def _safetensors(path, tensors):
+ width = {"F64": 8, "F32": 4, "F16": 2, "BF16": 2, "U8": 1, "I64": 8}
+ header, offset = {}, 0
+ for name, (dtype, numel) in tensors.items():
+ header[name] = {
+ "dtype": dtype,
+ "shape": [numel],
+ "data_offsets": [offset, offset + numel * width[dtype]],
+ }
+ offset += numel * width[dtype]
+ raw = json.dumps(header).encode()
+ path.parent.mkdir(parents = True, exist_ok = True)
+ with open(path, "wb") as fh:
+ fh.write(len(raw).to_bytes(8, "little"))
+ fh.write(raw)
+ fh.truncate(8 + len(raw) + offset)
+ return path
+
+
+def _f32(mib):
+ return {"w": ("F32", mib * MIB // 4)}
+
+
+def _bf16(mib):
+ return {"w": ("BF16", mib * MIB // 2)}
+
+
+def _t5(dtype, wo_mib, rest_mib):
+ width = 4 if dtype == "F32" else 2
+ return {
+ "encoder.block.0.layer.1.DenseReluDense.wo.weight": (dtype, wo_mib * MIB // width),
+ "encoder.block.0.layer.1.DenseReluDense.wi.weight": (dtype, rest_mib * MIB // width),
+ }
+
+
+def _snapshot(
+ tmp_path,
+ monkeypatch,
+ files,
+ repo = REPO,
+):
+ from huggingface_hub import constants as hf_constants
+
+ live = tmp_path / "hub"
+ unused = tmp_path / "import-time-hub"
+ unused.mkdir(parents = True, exist_ok = True)
+ monkeypatch.setattr(dmod, "hub_cache_dir", lambda: str(live))
+ monkeypatch.setattr(hf_constants, "HF_HUB_CACHE", str(unused))
+ repo_dir = live / f"models--{repo.replace('/', '--')}"
+ snapshot = repo_dir / "snapshots" / REV
+ for rel, tensors in files.items():
+ if isinstance(tensors, dict):
+ _safetensors(snapshot / rel, tensors)
+ else:
+ (snapshot / rel).parent.mkdir(parents = True, exist_ok = True)
+ (snapshot / rel).write_text(tensors)
+ (repo_dir / "refs").mkdir(parents = True, exist_ok = True)
+ (repo_dir / "refs" / "main").write_text(REV)
+ return snapshot
+
+
+def _card(
+ monkeypatch,
+ free = 9000,
+ total = 9216,
+ kind = "discrete_vram",
+):
+ """budget = free - 2048 reserve; resident margin 0.85 x budget. Runtime headroom fixed at 100."""
+ monkeypatch.setattr(
+ dmod,
+ "settled_snapshot_device_memory",
+ lambda t: DeviceMemory("cuda", "cuda", kind, free, total),
+ )
+ monkeypatch.setattr(dmod, "estimate_image_runtime_mib", lambda **kw: 100)
+
+
+def _target(dtype):
+ return types.SimpleNamespace(
+ device = "cuda", backend = "cuda", supports_model_cpu_offload = True, dtype = dtype
+ )
+
+
+FAM = types.SimpleNamespace(name = "sdxl", base_repo = "unrelated/base")
+
+SDXL_LIKE = {
+ "model_index.json": "{}",
+ "unet/diffusion_pytorch_model.safetensors": _f32(3600),
+ "text_encoder/model.safetensors": _f32(300),
+ "vae/diffusion_pytorch_model.safetensors": _f32(100),
+}
+
+
+def _plan(
+ dtype,
+ kind = "pipeline",
+ single_file = None,
+ repo = REPO,
+):
+ return DiffusionBackend()._plan_memory(
+ _target(dtype), single_file, repo, FAM, None, False, kind = kind, repo_id = repo
+ )
+
+
[email protected]("dtype", ["bfloat16", "float16"])
+def test_an_fp32_pipeline_is_planned_at_the_half_precision_it_loads_in(
+ tmp_path, monkeypatch, dtype
+):
+ _snapshot(tmp_path, monkeypatch, SDXL_LIKE)
+ _card(monkeypatch)
+ plan = _plan(getattr(torch, dtype))
+ assert plan.estimates["model_dense_mib"] == 2000
+ assert plan.estimates["companion_dense_mib"] == 2000
+ assert plan.estimates["text_encoder_dense_mib"] == 150
+ assert plan.offload_policy == OFFLOAD_NONE
+
+
+def test_an_fp32_load_keeps_the_stored_size(tmp_path, monkeypatch):
+ _snapshot(tmp_path, monkeypatch, SDXL_LIKE)
+ _card(monkeypatch)
+ plan = _plan(torch.float32)
+ assert plan.estimates["model_dense_mib"] == 4000
+ assert plan.offload_policy != OFFLOAD_NONE
+
+
+def test_a_target_without_a_dtype_sizes_from_cached_bytes(tmp_path, monkeypatch):
+ _snapshot(tmp_path, monkeypatch, SDXL_LIKE)
+ _card(monkeypatch)
+ plan = _plan(None)
+ assert plan.estimates["model_dense_mib"] == 4000
+
+
+def test_variant_twins_bin_twins_and_single_files_are_not_counted(tmp_path, monkeypatch):
+ _snapshot(
+ tmp_path,
+ monkeypatch,
+ {
+ "model_index.json": "{}",
+ "unet/diffusion_pytorch_model.safetensors": _bf16(1000),
+ "unet/diffusion_pytorch_model.fp16.safetensors": _bf16(1000),
+ "text_encoder/model.safetensors": _bf16(300),
+ "text_encoder/pytorch_model.bin": _bf16(300),
+ "sd_xl_like_fp16.safetensors": _bf16(2500),
+ },
+ )
+ _card(monkeypatch)
+ plan = _plan(torch.bfloat16)
+ assert plan.estimates["model_dense_mib"] == 1300
+ assert plan.estimates["companion_dense_mib"] == 1300
+ assert plan.estimates["text_encoder_dense_mib"] == 300
+ assert plan.offload_policy == OFFLOAD_NONE
+
+
+def test_a_folder_holding_only_a_bin_keeps_it(tmp_path, monkeypatch):
+ _snapshot(
+ tmp_path,
+ monkeypatch,
+ {
+ "unet/diffusion_pytorch_model.safetensors": _bf16(1000),
+ "text_encoder/pytorch_model.bin": _bf16(300),
+ },
+ )
+ _card(monkeypatch)
+ assert _plan(torch.bfloat16).estimates["model_dense_mib"] == 1300
+
+
+def test_a_mixed_precision_or_quantised_file_keeps_its_stored_size(tmp_path, monkeypatch):
+ _snapshot(
+ tmp_path,
+ monkeypatch,
+ {
+ "transformer/diffusion_pytorch_model.safetensors": {
+ "w": ("BF16", 900 * MIB // 2),
+ "norm": ("F32", 100 * MIB // 4),
+ },
+ # A 4-bit checkpoint: packed bytes plus fp32 quant state.
+ "text_encoder/model.safetensors": {
+ "w": ("U8", 200 * MIB),
+ "absmax": ("F32", 20 * MIB // 4),
+ },
+ },
+ )
+ _card(monkeypatch)
+ assert _plan(torch.bfloat16).estimates["model_dense_mib"] == 1220
+
+
+def test_a_component_class_pinning_fp32_modules_keeps_those_modules_wide(tmp_path, monkeypatch):
+ _snapshot(
+ tmp_path,
+ monkeypatch,
+ {
+ "transformer/diffusion_pytorch_model.safetensors": _f32(2000),
+ "text_encoder/config.json": json.dumps({"architectures": ["T5EncoderModel"]}),
+ "text_encoder/model.safetensors": _t5("F32", 100, 300),
+ },
+ )
+ _card(monkeypatch)
+ pinned = types.SimpleNamespace(T5EncoderModel = type("T5", (), {"_keep_in_fp32_modules": ["wo"]}))
+ monkeypatch.setitem(sys.modules, "transformers", pinned)
+ assert _plan(torch.float16).estimates["model_dense_mib"] == 1000 + 100 + 150
+ free = types.SimpleNamespace(T5EncoderModel = type("T5", (), {"_keep_in_fp32_modules": None}))
+ monkeypatch.setitem(sys.modules, "transformers", free)
+ assert _plan(torch.float16).estimates["model_dense_mib"] == 1000 + 200
+
+
+def test_pinned_modules_of_a_half_checkpoint_are_widened(tmp_path, monkeypatch):
+ _snapshot(
+ tmp_path,
+ monkeypatch,
+ {
+ "text_encoder/config.json": json.dumps({"architectures": ["T5EncoderModel"]}),
+ "text_encoder/model.safetensors": _t5("BF16", 100, 300),
+ },
+ )
+ _card(monkeypatch)
+ pinned = types.SimpleNamespace(T5EncoderModel = type("T5", (), {"_keep_in_fp32_modules": ["wo"]}))
+ monkeypatch.setitem(sys.modules, "transformers", pinned)
+ # bf16 on disk, loaded in fp16: wo is upcast to fp32 (200), the rest stays two bytes (300).
+ assert _plan(torch.float16).estimates["model_dense_mib"] == 500
+ assert _plan(torch.bfloat16).estimates["model_dense_mib"] == 400
+
+
+def test_gguf_companions_are_priced_at_the_load_dtype(tmp_path, monkeypatch):
+ # Lumina-2 publishes its Gemma encoder in fp32: a GGUF pick loads it in bf16 beside the GGUF.
+ _snapshot(
+ tmp_path,
+ monkeypatch,
+ {
+ "text_encoder/model.safetensors": _f32(2000),
+ "vae/diffusion_pytorch_model.safetensors": _f32(200),
+ "transformer/diffusion_pytorch_model.safetensors": _f32(4000),
+ },
+ )
+ gguf = tmp_path / "t-Q8_0.gguf"
+ with open(gguf, "wb") as fh:
+ fh.truncate(1000 * MIB)
+ _card(monkeypatch)
+ plan = _plan(torch.bfloat16, kind = "gguf", single_file = str(gguf))
+ assert plan.estimates["companion_dense_mib"] == 1100
+ assert plan.estimates["text_encoder_dense_mib"] == 1000
+ assert plan.estimates["model_dense_mib"] == int(1000 * 1.05) + 1100
+
+
+def test_a_unified_pool_no_longer_refuses_an_fp32_repo_that_fits_in_bf16(tmp_path, monkeypatch):
+ _snapshot(tmp_path, monkeypatch, SDXL_LIKE)
+ _card(monkeypatch, free = 7000, total = 7000, kind = "unified_memory")
+ fp32 = _plan(torch.float32)
+ bf16 = _plan(torch.bfloat16)
+ assert unified_memory_shortfall_message(fp32, family = "sdxl") is not None
+ assert unified_memory_shortfall_message(bf16, family = "sdxl") is None
+
+
+ "tensors, itemsize, expected",
+ [
+ ({"a": ("F32", 10), "b": ("I64", 2)}, 2, 10 * 2 + 16),
+ ({"a": ("F64", 10)}, 4, 40),
+ ({"a": ("F32", 10)}, 4, 40),
+ ({"a": ("BF16", 10), "b": ("F32", 5)}, 4, 60),
+ ({"a": ("I64", 10)}, 2, None),
+ ({"a": ("F32", 10), "b": ("F16", 10)}, 2, 60),
+ ({"a": ("U8", 10), "b": ("F32", 1)}, 4, None),
+ ],
+)
+def test_safetensors_cast_bytes(tmp_path, tensors, itemsize, expected):
+ path = _safetensors(tmp_path / "x.safetensors", tensors)
+ assert DiffusionBackend._safetensors_cast_bytes(path, itemsize) == expected
+
+
+def test_a_dotted_pin_matches_the_parameter_path_the_way_the_loader_does(tmp_path):
+ path = _safetensors(
+ tmp_path / "x.safetensors",
+ {
+ "model.layers.0.mlp.gate.weight": ("F32", 10),
+ "model.layers.0.mlp.gate_proj.weight": ("F32", 10),
+ "model.layers.0.gate": ("F32", 10),
+ },
+ )
+ assert DiffusionBackend._safetensors_cast_bytes(path, 2, ("gate.weight",)) == 40 + 20 + 20
+ assert DiffusionBackend._safetensors_cast_bytes(path, 2, ("gate",)) == 40 + 20 + 40
+
+
+def test_a_bin_checkpoint_is_priced_at_the_load_dtype(tmp_path):
+ path = tmp_path / "pytorch_model.bin"
+ torch.save(
+ {"a": torch.zeros(10, dtype = torch.bfloat16), "b": torch.zeros(5, dtype = torch.float32)},
+ path,
+ )
+ assert DiffusionBackend._bin_cast_bytes(path, 4) == 10 * 4 + 5 * 4
+ assert DiffusionBackend._bin_cast_bytes(path, 2) == 10 * 2 + 5 * 4
+
+
+def test_a_bin_only_component_is_repriced_in_the_directory_scan(tmp_path):
+ encoder = tmp_path / "text_encoder"
+ encoder.mkdir()
+ torch.save({"w": torch.zeros(1000, dtype = torch.bfloat16)}, encoder / "pytorch_model.bin")
+ sizes = DiffusionBackend._local_dir_weight_sizes(
+ tmp_path, exclude_transformer = False, load_dtype = torch.float32
+ )
+ assert sizes == {"text_encoder/pytorch_model.bin": 4000}
+
+
+def test_a_tied_bin_weight_is_counted_once(tmp_path):
+ path = tmp_path / "pytorch_model.bin"
+ shared = torch.zeros(100, 8, dtype = torch.bfloat16)
+ torch.save(
+ {"shared.weight": shared, "encoder.embed_tokens.weight": shared, "head": shared[:10]},
+ path,
+ )
+ # The alias costs nothing; a distinct view of the same storage is still its own parameter.
+ assert DiffusionBackend._bin_cast_bytes(path, 4) == (800 + 80) * 4
+
+
+def test_a_legacy_bin_keeps_the_stored_size(tmp_path):
+ path = tmp_path / "pytorch_model.bin"
+ torch.save({"w": torch.zeros(10)}, path, _use_new_zipfile_serialization = False)
+ assert DiffusionBackend._bin_cast_bytes(path, 2) is None
+
+
+def test_an_unreadable_header_keeps_the_stored_size(tmp_path):
+ path = tmp_path / "x.safetensors"
+ with open(path, "wb") as fh:
+ fh.truncate(4096)
+ assert DiffusionBackend._safetensors_cast_bytes(path, 2) is None
+
+
+def test_an_oversized_header_length_is_not_read(tmp_path):
+ path = tmp_path / "x.safetensors"
+ with open(path, "wb") as fh:
+ fh.write((2**62).to_bytes(8, "little"))
+ assert DiffusionBackend._safetensors_cast_bytes(path, 2) is None
+
+
+def test_a_half_precision_repo_loaded_in_fp32_is_priced_at_fp32(tmp_path, monkeypatch):
+ _snapshot(
+ tmp_path,
+ monkeypatch,
+ {
+ "transformer/diffusion_pytorch_model.safetensors": _bf16(1800),
+ "text_encoder/model.safetensors": _bf16(200),
+ },
+ )
+ _card(monkeypatch)
+ assert _plan(torch.bfloat16).estimates["model_dense_mib"] == 2000
+ fp32 = _plan(torch.float32)
+ assert fp32.estimates["model_dense_mib"] == 4000
+ assert fp32.estimates["text_encoder_dense_mib"] == 400
+ assert fp32.offload_policy != OFFLOAD_NONE
+
+
+def test_a_pinned_component_is_widened_on_an_fp32_load(tmp_path, monkeypatch):
+ _snapshot(
+ tmp_path,
+ monkeypatch,
+ {
+ "text_encoder/config.json": json.dumps({"architectures": ["T5EncoderModel"]}),
+ "text_encoder/model.safetensors": _bf16(400),
+ },
+ )
+ _card(monkeypatch)
+ pinned = types.SimpleNamespace(T5EncoderModel = type("T5", (), {"_keep_in_fp32_modules": ["wo"]}))
+ monkeypatch.setitem(sys.modules, "transformers", pinned)
+ assert _plan(torch.float32).estimates["model_dense_mib"] == 800
+
+
+def test_a_bin_is_kept_beside_safetensors_shards_the_loader_cannot_select(tmp_path, monkeypatch):
+ snapshot = _snapshot(
+ tmp_path,
+ monkeypatch,
+ {
+ # Numbered shards with no index: the loader falls back to the .bin.
+ "text_encoder/model-00001-of-00002.safetensors": _bf16(100),
+ "text_encoder/pytorch_model.bin": _bf16(300),
+ # Indexed shards: selectable, so the .bin twin is never opened.
+ "text_encoder_2/model-00001-of-00002.safetensors": _bf16(100),
+ "text_encoder_2/model-00002-of-00002.safetensors": _bf16(100),
+ "text_encoder_2/model.safetensors.index.json": "{}",
+ "text_encoder_2/pytorch_model.bin": _bf16(200),
+ },
+ )
+ assert snapshot.is_dir()
+ _card(monkeypatch)
+ assert _plan(torch.bfloat16).estimates["model_dense_mib"] == 100 + 300 + 200
+
+
+ "attrs, dtype, expected",
+ [
+ # Transformers upcasts the non-strict set only for fp16; the strict set for both halves.
+ ({"_keep_in_fp32_modules": ["wo"]}, "float16", 250),
+ ({"_keep_in_fp32_modules": ["wo"]}, "bfloat16", 200),
+ ({"_keep_in_fp32_modules_strict": ["wo"]}, "bfloat16", 250),
+ ],
+)
+def test_transformers_pins_follow_the_half_dtype(tmp_path, monkeypatch, attrs, dtype, expected):
+ _snapshot(
+ tmp_path,
+ monkeypatch,
+ {
+ "text_encoder/config.json": json.dumps({"architectures": ["T5EncoderModel"]}),
+ "text_encoder/model.safetensors": _t5("F32", 100, 300),
+ },
+ )
+ _card(monkeypatch)
+ lib = types.SimpleNamespace(T5EncoderModel = type("T5", (), attrs))
+ monkeypatch.setitem(sys.modules, "transformers", lib)
+ monkeypatch.delitem(sys.modules, "diffusers", raising = False)
+ assert _plan(getattr(torch, dtype)).estimates["model_dense_mib"] == expected
+
+
+def test_a_diffusers_pin_holds_at_bf16(tmp_path, monkeypatch):
+ _snapshot(
+ tmp_path,
+ monkeypatch,
+ {
+ "transformer/config.json": json.dumps({"_class_name": "PinnedTransformer"}),
+ "transformer/diffusion_pytorch_model.safetensors": {
+ "blocks.0.norm.weight": ("F32", 100 * MIB // 4),
+ "blocks.0.proj.weight": ("F32", 300 * MIB // 4),
+ },
+ },
+ )
+ _card(monkeypatch)
+ lib = types.SimpleNamespace(
+ PinnedTransformer = type("P", (), {"_keep_in_fp32_modules": ["norm"]})
+ )
+ monkeypatch.setitem(sys.modules, "diffusers", lib)
+ assert _plan(torch.bfloat16).estimates["model_dense_mib"] == 100 + 150