Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

fix(wan): keep system RAM within the model cache budget (#10192)

Alexander Eichhorn8143c638f40d
diff --git a/invokeai/app/invocations/wan/wan_denoise.py b/invokeai/app/invocations/wan/wan_denoise.py
index d6f57a0211..4a46247ad5 100644
--- a/invokeai/app/invocations/wan/wan_denoise.py
+++ b/invokeai/app/invocations/wan/wan_denoise.py
@@ -241,6 +241,9 @@ class _ExpertSwapper:
outgoing_info.unload_from_vram(outgoing_bytes)
except Exception:
pass
+ # The handle reaches the cache record and the model: while it is alive the outgoing expert's
+ # tensors cannot be freed, and both experts would be resident through the load below.
+ outgoing_info = None
# Hand the PyTorch allocator a clean slate before partial_load_to_vram measures
# free space — the freed blocks stay pinned in the caching allocator until
@@ -665,6 +668,8 @@ class WanDenoiseInvocation(BaseInvocation):
active_label = _ExpertSwapper.HIGH
active_cfg = self.guidance_scale
+ # The previous expert must be unreferenced by the time `get` loads the next one.
+ transformer = None
transformer = swapper.get(active_label)
# Cast latents to the transformer's dtype only for the forward
diff --git a/invokeai/app/invocations/wan/wan_video_denoise.py b/invokeai/app/invocations/wan/wan_video_denoise.py
index ea15ba2f70..2f031f1158 100644
--- a/invokeai/app/invocations/wan/wan_video_denoise.py
+++ b/invokeai/app/invocations/wan/wan_video_denoise.py
@@ -335,6 +335,8 @@ class WanVideoDenoiseInvocation(BaseInvocation):
active_label = _ExpertSwapper.HIGH
active_cfg = self.guidance_scale
+ # The previous expert must be unreferenced by the time `get` loads the next one.
+ transformer = None
transformer = swapper.get(active_label)
latent_model_input = latents.to(dtype=inference_dtype)
diff --git a/invokeai/backend/model_manager/load/model_loaders/comfyui_state_dict_utils.py b/invokeai/backend/model_manager/load/model_loaders/comfyui_state_dict_utils.py
index 0f1d5259ed..4f16025d3c 100644
--- a/invokeai/backend/model_manager/load/model_loaders/comfyui_state_dict_utils.py
+++ b/invokeai/backend/model_manager/load/model_loaders/comfyui_state_dict_utils.py
@@ -10,11 +10,14 @@ Originally written for the Qwen Image loader; shared so the Wan loader doesn't
need a second copy.
"""
+from typing import Any, Mapping
+
import torch
from invokeai.backend.quantization.fp8_scaled import (
expand_weight_scale,
is_scale_metadata_key,
+ iter_weight_scale_pairs,
reject_undecoded_mx_scale,
)
from invokeai.backend.quantization.int8_convrot import reject_int8_layers_a_plain_fold_cannot_decode
@@ -44,34 +47,42 @@ def _dequantize_comfyui_fp8(sd: dict, compute_dtype: torch.dtype, what: str = "T
in the file is a scale that still needs applying — i.e. a checkpoint must not ship
already-dequantized weights alongside their scales.
"""
- reject_nvfp4_layers_a_plain_fold_cannot_decode(sd, what)
- reject_int8_layers_a_plain_fold_cannot_decode(sd, what)
- scale_suffixes = (".weight_scale", ".scale_weight")
- weight_scale_keys = [k for k in sd.keys() if isinstance(k, str) and k.endswith(scale_suffixes)]
+ reject_layers_the_fold_cannot_decode(sd, what)
count = 0
- for scale_key in weight_scale_keys:
- for suffix in scale_suffixes:
- if scale_key.endswith(suffix):
- weight_key = scale_key[: -len(suffix)] + ".weight"
- break
- if weight_key not in sd:
- continue
- # Before the cast: `.to(compute_dtype)` on an E8M0 grid converts the exponent bytes to
- # floats and loses the only evidence of what they were.
- reject_undecoded_mx_scale(weight_key[: -len(".weight")], sd[scale_key])
- weight = sd[weight_key].to(compute_dtype)
- scale = sd[scale_key].to(compute_dtype)
- # Through the shared expansion rather than a local copy of it. The copy that used to live
- # here compared `scale.shape[dim] != weight.shape[dim]`, so a per-output-channel scale --
- # whose length already equals the number of rows -- was expanded by nothing and left to
- # broadcasting, which aligns on the *last* axis. That scales columns instead of rows: a
- # shape error on a non-square weight, and on a square one (every attention out-projection)
- # a model that loads and generates noise.
- sd[weight_key] = weight * expand_weight_scale(weight, scale, weight_key)
+ for weight_key, scale_key in iter_weight_scale_pairs(sd):
+ sd[weight_key] = fold_comfyui_fp8_scale(sd[weight_key], sd[scale_key], weight_key, compute_dtype)
count += 1
return count
+def reject_layers_the_fold_cannot_decode(sd: Mapping[str, Any], what: str = "This checkpoint") -> None:
+ """Refuse the quantized layers that share scaled fp8's key layout but that a plain fold would turn into noise.
+
+ Reads keys, dtypes and the ``.comfy_quant`` marker blobs only, so a loader that reads a file one tensor at a
+ time can run it over the header's ``meta`` tensors (with the markers read) before any weight is read.
+ """
+ reject_nvfp4_layers_a_plain_fold_cannot_decode(sd, what)
+ reject_int8_layers_a_plain_fold_cannot_decode(sd, what)
+
+
+def fold_comfyui_fp8_scale(
+ weight: torch.Tensor, scale: torch.Tensor, weight_key: str, compute_dtype: torch.dtype
+) -> torch.Tensor:
+ """``weight`` with its ComfyUI ``weight_scale`` multiplied in, at ``compute_dtype``."""
+ # Before the cast: `.to(compute_dtype)` on an E8M0 grid converts the exponent bytes to
+ # floats and loses the only evidence of what they were.
+ reject_undecoded_mx_scale(weight_key[: -len(".weight")], scale)
+ weight = weight.to(compute_dtype)
+ scale = scale.to(compute_dtype)
+ # Through the shared expansion rather than a local copy of it. The copy that used to live
+ # here compared `scale.shape[dim] != weight.shape[dim]`, so a per-output-channel scale --
+ # whose length already equals the number of rows -- was expanded by nothing and left to
+ # broadcasting, which aligns on the *last* axis. That scales columns instead of rows: a
+ # shape error on a non-square weight, and on a square one (every attention out-projection)
+ # a model that loads and generates noise.
+ return weight * expand_weight_scale(weight, scale, weight_key)
+
+
def _strip_quantization_metadata(sd: dict) -> None:
"""Strip ComfyUI fp8 quantization metadata keys in-place.
diff --git a/invokeai/backend/model_manager/load/model_loaders/wan.py b/invokeai/backend/model_manager/load/model_loaders/wan.py
index 1097daf393..a2cff77b73 100644
--- a/invokeai/backend/model_manager/load/model_loaders/wan.py
+++ b/invokeai/backend/model_manager/load/model_loaders/wan.py
@@ -12,8 +12,9 @@ Currently covers:
- VAE: handled in ``vae.py`` (registered for type=VAE generically).
"""
+from itertools import chain
from pathlib import Path
-from typing import Any, Optional
+from typing import Any, Callable, Optional
import torch
@@ -30,10 +31,12 @@ from invokeai.backend.model_manager.configs.wan_t5_encoder import WanT5Encoder_G
from invokeai.backend.model_manager.load.load_default import ModelLoader, _model_declared_skip_patterns
from invokeai.backend.model_manager.load.model_loader_registry import ModelLoaderRegistry
from invokeai.backend.model_manager.load.model_loaders.comfyui_state_dict_utils import (
- _dequantize_comfyui_fp8,
_strip_quantization_metadata,
+ fold_comfyui_fp8_scale,
+ reject_layers_the_fold_cannot_decode,
)
from invokeai.backend.model_manager.load.model_loaders.generic_diffusers import GenericDiffusersLoader
+from invokeai.backend.model_manager.model_on_disk import safetensors_meta_state_dict
from invokeai.backend.model_manager.taxonomy import (
AnyModel,
BaseModelType,
@@ -48,8 +51,11 @@ from invokeai.backend.model_manager.util.llamacpp_t5 import (
make_feed_forward_gguf_safe,
)
from invokeai.backend.quantization.fp8_scaled import (
+ COMFY_QUANT_SUFFIX,
is_scale_metadata_key,
+ iter_weight_scale_pairs,
parse_quantization_metadata,
+ predict_cast_state_dict_size,
read_safetensors_metadata,
strip_layer_path_prefix,
)
@@ -127,6 +133,7 @@ class WanDiffusersModel(GenericDiffusersLoader):
except TypeError:
# Older diffusers releases use torch_dtype instead of dtype.
result = _load_with_variant_fallback({"torch_dtype": torch.bfloat16})
+ _copy_tensors_left_on_the_mapping(result, torch.bfloat16)
# This override exists to force bfloat16, and in doing so it replaced the parent's whole
# `_load_model` -- including the cast at `GenericDiffusersLoader._load_model`, which every
@@ -136,6 +143,29 @@ class WanDiffusersModel(GenericDiffusersLoader):
return self._apply_fp8_layerwise_casting(result, config, submodel_type)
+def _copy_tensors_left_on_the_mapping(model: Any, dtype: torch.dtype) -> None:
+ """Give memory of their own to the tensors ``from_pretrained`` kept off ``dtype`` that still read the file's.
+
+ ``from_pretrained`` memory-maps each shard and casts tensor by tensor; a tensor whose cast is a no-op stays a
+ view of the mapping, and a view keeps its whole shard mapped. At ``dtype`` those views are the model's own
+ weights, and mapping them is how a bf16 folder loads without a copy, so they stay. Off ``dtype`` they are what
+ ``_keep_in_fp32_modules`` (norms, modulation tables, the time embedder) leaves in float32 when the file is
+ float32: a few MB per shard, each holding a multi-GB shard whose other tensors were all cast away. The A14B
+ experts ship float32, and one would hold 80 GB of working set against its 27 GB bf16 size. Copied, the mapping is
+ released with its last view, for a transient the size of the copies.
+
+ The test is ``resizable()``, which is False for a storage torch did not allocate itself -- here, the views of the
+ mapping; it does not mean "mapped" in general. It skips what the load already copied: a bf16 file whose
+ ``_keep_in_fp32_modules`` are stored in bf16 has them upcast by the load, and a second copy would buy nothing.
+ """
+ if not isinstance(model, torch.nn.Module):
+ return
+ with torch.no_grad():
+ for tensor in chain(model.parameters(), model.buffers()):
+ if tensor.device.type == "cpu" and tensor.dtype != dtype and not tensor.untyped_storage().resizable():
+ tensor.data = tensor.data.clone()
+
+
# Native (upstream) -> Diffusers key rename rules.
#
# Mirrors diffusers.loaders.single_file_utils.convert_wan_transformer_to_diffusers
@@ -226,11 +256,11 @@ def _drop_benign_extra_keys(sd: dict, source: str, logger: Any) -> None:
"""Remove packaging weights the transformer has no use for, in place.
Done up front rather than left to ``load_state_dict(strict=False)`` because
- everything between here and there costs real memory: the fp8 dequant pass, the
- blanket cast to the compute dtype, and the RAM-cache reservation all run over the
- whole dict. An all-in-one checkpoint bundles a full VAE and UMT5-XXL text encoder —
- several GB, upcast to bf16 and reserved in the cache — only for
- ``load_state_dict`` to discard them one line later.
+ everything between here and there costs real memory: the read, the fp8 dequant pass,
+ the cast to the compute dtype, and the RAM-cache reservation. An all-in-one checkpoint
+ bundles a full VAE and UMT5-XXL text encoder — several GB, upcast to bf16 and reserved
+ in the cache — only for ``load_state_dict`` to discard them. The single-file loader
+ runs this over the header, so what it drops is never read.
"""
dropped = [key for key in sd if isinstance(key, str) and _is_benign_extra_key(key)]
if not dropped:
@@ -427,6 +457,37 @@ class WanGGUFCheckpointModel(ModelLoader):
return model
+def _predict_folded_cast_size(sd: dict, dtype: torch.dtype) -> int:
+ """Bytes the state dict occupies once the scale fold and the cast to ``dtype`` have run.
+
+ The fold consumes and strips the scale tensors, and it widens every weight that has a sibling
+ scale to ``dtype`` whatever its stored dtype, so those are charged at ``dtype`` too.
+ """
+ kept = {k: v for k, v in sd.items() if not is_scale_metadata_key(k)}
+ folded = {weight_key for weight_key, _ in iter_weight_scale_pairs(sd)}
+ total = predict_cast_state_dict_size({k: v for k, v in kept.items() if k not in folded}, dtype, keep_fp8=False)
+ return total + sum(kept[k].nelement() * dtype.itemsize for k in folded)
+
+
+def _read_folded_and_cast(sd: dict[str, torch.Tensor], read: Callable[[str], torch.Tensor], dtype: torch.dtype) -> int:
+ """Fill ``sd``'s header entries from ``read`` one tensor at a time, each converted as it arrives.
+
+ A ComfyUI weight scale is folded into its weight and dropped with the rest of the quantization metadata;
+ every other float tensor is cast to ``dtype``. Converted on arrival, the peak is the finished state dict plus
+ the tensor in flight rather than the whole source. Returns the number of folds.
+ """
+ scales = dict(iter_weight_scale_pairs(sd))
+ _strip_quantization_metadata(sd)
+ for key in sd:
+ tensor = read(key)
+ if key in scales:
+ tensor = fold_comfyui_fp8_scale(tensor, read(scales[key]), key, dtype)
+ elif tensor.is_floating_point():
+ tensor = tensor.to(dtype)
+ sd[key] = tensor
+ return len(scales)
+
+
@ModelLoaderRegistry.register(base=BaseModelType.Wan, type=ModelType.Main, format=ModelFormat.Checkpoint)
class WanCheckpointModel(ModelLoader):
"""Loader for single-file Wan 2.2 transformer checkpoints (safetensors).
@@ -463,7 +524,7 @@ class WanCheckpointModel(ModelLoader):
def _load_from_singlefile(self, config: Main_Checkpoint_Wan_Config) -> AnyModel:
import accelerate
from diffusers import WanTransformer3DModel
- from safetensors.torch import load_file
+ from safetensors import safe_open
from invokeai.backend.util.logging import InvokeAILogger
@@ -473,78 +534,85 @@ class WanCheckpointModel(ModelLoader):
target_device = TorchDevice.choose_torch_device()
model_dtype = TorchDevice.choose_bfloat16_safe_dtype(target_device)
- sd = load_file(str(model_path))
- sd = CheckpointPrefix.detect(sd).strip(sd)
+ # Everything up to the read -- the prefix, what is dropped, how the file is quantized, the reservation -- is
+ # decided on the header's `meta` tensors, so a bundled VAE or text encoder is never read and the cache makes
+ # room before the first payload arrives.
+ sd = safetensors_meta_state_dict(model_path)
+ prefix = CheckpointPrefix.detect(sd)
+ file_keys = prefix.strip({key: key for key in sd})
+ sd = prefix.strip(sd)
_drop_benign_extra_keys(sd, "Wan checkpoint", logger)
- # Markers and header entries name their layers in the file's native key space, so they are read before
- # any rename. The refusal sits outside the "found markers" branch on purpose: an int8 weight no marker
- # claims must be refused, not cast to the compute dtype as raw codes.
- header_layers = strip_layer_path_prefix(
- parse_quantization_metadata(read_safetensors_metadata(model_path, logger))
- )
- int8_markers = extract_int8_convrot_markers(sd, header_layers=header_layers)
- reject_unmarked_int8_weights(sd, int8_markers, f"Wan 2.2 ({model_path.name})", header_layers=header_layers)
+ # pread gives every tensor memory of its own. Through the default mmap each one is a slice of one file-wide
+ # mapping, and a tensor whose cast is a no-op (bf16 on disk) would keep the whole file mapped.
+ with safe_open(str(model_path), framework="pt", device="cpu", backend="pread") as f:
- dequantized = 0
- if int8_markers:
- sd = drop_unconsumed_quantization_sidecars(sd)
- else:
- dequantized = _dequantize_comfyui_fp8(sd, model_dtype, f"Wan checkpoint {model_path.name}")
- if dequantized > 0:
- logger.info(f"Dequantized {dequantized} ComfyUI-quantized weights")
- # Drop the scale tensors themselves — they've been folded into the weights
- # above and are not parameters of WanTransformer3DModel. load_state_dict
- # runs with strict=False and would ignore them anyway, but dropping them
- # here keeps the dtype cast and the RAM-cache reservation below honest.
- _strip_quantization_metadata(sd)
-
- # Community releases ship the native upstream Wan key layout
- # (text_embedding.0, self_attn/cross_attn, ffn.0/2, head.head, ...);
- # diffusers' WanTransformer3DModel expects condition_embedder.*,
- # attn1/attn2, ffn.net.*, proj_out. Convert if needed.
- key_map: dict[str, str] = {}
- if _is_native_wan_layout(sd):
- key_map = {key: _rename_wan_native_key(key) for key in sd if isinstance(key, str)}
- sd = _convert_wan_native_to_diffusers(sd)
+ def read(key: str) -> torch.Tensor:
+ return f.get_tensor(file_keys[key])
- model_config = _build_wan_transformer_config(sd, source="checkpoint state dict")
+ # The markers are the one payload the decisions below look at.
+ for key in [k for k in sd if k.endswith(COMFY_QUANT_SUFFIX)]:
+ sd[key] = read(key)
- with accelerate.init_empty_weights():
- model = WanTransformer3DModel(**model_config)
-
- if int8_markers:
- # Casts only the dense tensors: the blanket cast below would also cast the fp32 scales. The skip
- # patterns match diffusers names, hence after the rename; `condition_embedder` reads its dtype from
- # a parameter, which an int8 layer does not have, so it is widened here.
- quantized = install_int8_convrot_layers(
- model,
- sd,
- resolve_quantized_module_paths(int8_markers, key_map),
- model_dtype,
- architecture="Wan 2.2",
- reserve=self._ram_cache.make_room,
- skip_patterns=_model_declared_skip_patterns(model),
- )
- # Metadata the fp8 branch strips: a stray `scaled_fp8` flag, or a weight scale beside a dense weight.
- # Left in, `_raise_for_incompatible_keys` would blame it on an Animate/S2V variant. Dropped after the
- # install, whose foreign-scale check has to see (and refuse) a scale that sits on an fp8 weight.
- for key in [k for k in sd if is_scale_metadata_key(k) and k.rsplit(".", 1)[0] not in quantized]:
- del sd[key]
- logger.info(
- f"Wan 2.2: kept {len(quantized)} of {len(int8_markers)} layer(s) in int8 "
- "(int8_tensorwise checkpoint, dequantized per forward)"
+ # Markers and header entries name their layers in the file's native key space, so they are read before
+ # any rename. The refusal sits outside the "found markers" branch on purpose: an int8 weight no marker
+ # claims must be refused, not cast to the compute dtype as raw codes.
+ header_layers = strip_layer_path_prefix(
+ parse_quantization_metadata(read_safetensors_metadata(model_path, logger))
)
- else:
- # Cast every float tensor to the compute dtype. Dequantized fp8_scaled
- # weights are already there; this catches plain fp16/fp32/fp8 checkpoints
- # and makes the cache reservation below reflect the post-cast sizes.
- for key in list(sd.keys()):
- if sd[key].is_floating_point():
- sd[key] = sd[key].to(model_dtype)
-
- new_sd_size = sum(t.nelement() * t.element_size() for t in sd.values())
- self._ram_cache.make_room(new_sd_size)
+ int8_markers = extract_int8_convrot_markers(sd, header_layers=header_layers)
+ reject_unmarked_int8_weights(sd, int8_markers, f"Wan 2.2 ({model_path.name})", header_layers=header_layers)
+
+ dequantized = 0
+ if int8_markers:
+ # Still the header's tensors: `install_int8_convrot_layers` reads them once it has reserved.
+ sd = drop_unconsumed_quantization_sidecars(sd)
+ else:
+ reject_layers_the_fold_cannot_decode(sd, f"Wan checkpoint {model_path.name}")
+ # Before the first read: the reservation is the state dict after the fold and the cast.
+ self._ram_cache.make_room(_predict_folded_cast_size(sd, model_dtype))
+ dequantized = _read_folded_and_cast(sd, read, model_dtype)
+ if dequantized > 0:
+ logger.info(f"Dequantized {dequantized} ComfyUI-quantized weights")
+
+ # Community releases ship the native upstream Wan key layout
+ # (text_embedding.0, self_attn/cross_attn, ffn.0/2, head.head, ...);
+ # diffusers' WanTransformer3DModel expects condition_embedder.*,
+ # attn1/attn2, ffn.net.*, proj_out. Convert if needed.
+ key_map: dict[str, str] = {}
+ if _is_native_wan_layout(sd):
+ key_map = {key: _rename_wan_native_key(key) for key in sd if isinstance(key, str)}
+ sd = _convert_wan_native_to_diffusers(sd)
+ file_keys = _convert_wan_native_to_diffusers(file_keys)
+
+ model_config = _build_wan_transformer_config(sd, source="checkpoint state dict")
+
+ with accelerate.init_empty_weights():
+ model = WanTransformer3DModel(**model_config)
+
+ if int8_markers:
+ # Casts only the dense tensors: the blanket cast below would also cast the fp32 scales. The skip
+ # patterns match diffusers names, hence after the rename; `condition_embedder` reads its dtype from
+ # a parameter, which an int8 layer does not have, so it is widened here.
+ quantized = install_int8_convrot_layers(
+ model,
+ sd,
+ resolve_quantized_module_paths(int8_markers, key_map),
+ model_dtype,
+ architecture="Wan 2.2",
+ reserve=self._ram_cache.make_room,
+ skip_patterns=_model_declared_skip_patterns(model),
+ read=read,
+ )
+ # Metadata the fp8 branch strips: a stray `scaled_fp8` flag, or a weight scale beside a dense weight.
+ # Left in, `_raise_for_incompatible_keys` would blame it on an Animate/S2V variant. Dropped after the
+ # install, whose foreign-scale check has to see (and refuse) a scale that sits on an fp8 weight.
+ for key in [k for k in sd if is_scale_metadata_key(k) and k.rsplit(".", 1)[0] not in quantized]:
+ del sd[key]
+ logger.info(
+ f"Wan 2.2: kept {len(quantized)} of {len(int8_markers)} layer(s) in int8 "
+ "(int8_tensorwise checkpoint, dequantized per forward)"
+ )
incompatible_keys = model.load_state_dict(sd, strict=False, assign=True)
_raise_for_incompatible_keys(incompatible_keys, source="Wan checkpoint")
diff --git a/invokeai/backend/model_manager/model_on_disk.py b/invokeai/backend/model_manager/model_on_disk.py
index cda2e9b95f..142ed931df 100644
--- a/invokeai/backend/model_manager/model_on_disk.py
+++ b/invokeai/backend/model_manager/model_on_disk.py
@@ -27,7 +27,9 @@ SAFETENSORS_DTYPES: dict[str, torch.dtype] = {
"U8": torch.uint8,
"I8": torch.int8,
"F8_E4M3": torch.float8_e4m3fn,
+ "F8_E4M3FNUZ": torch.float8_e4m3fnuz,
"F8_E5M2": torch.float8_e5m2,
+ "F8_E5M2FNUZ": torch.float8_e5m2fnuz,
"U16": torch.uint16,
"I16": torch.int16,
"BF16": torch.bfloat16,
@@ -38,8 +40,18 @@ SAFETENSORS_DTYPES: dict[str, torch.dtype] = {
"U64": torch.uint64,
"I64": torch.int64,
"F64": torch.float64,
+ "C64": torch.complex64,
}
-"""safetensors dtype names mapped to their torch equivalents."""
+"""safetensors dtype names mapped to their torch equivalents: every dtype `safetensors.torch` reads but F4, because the
+single-file loaders read through the header, and a missing name fails a file `load_file` loads -- at generation, since
+identification falls back to the full load and installs it. The sub-byte formats (F4, F6_E2M3, F6_E3M2) are absent:
+their header shapes count 4- and 6-bit elements, which no torch dtype stores one per element. `load_file` reads F4 as
+`float4_e2m1fn_x2` with the last dimension halved; no loader casts such a tensor, so it is refused here by name."""
+
+# MXFP8 exponent grids, which loaders refuse by name (`fp8_scaled.reject_undecoded_mx_scale`), so they have to get as
+# far as that check. Guarded like `fp8_scaled._MX_SCALE_DTYPES`: older torch builds lack the dtype.
+if hasattr(torch, "float8_e8m0fnu"):
+ SAFETENSORS_DTYPES["F8_E8M0"] = torch.float8_e8m0fnu
def read_safetensors_header(path: Path) -> dict[str, Any]:
@@ -63,22 +75,27 @@ def read_safetensors_header(path: Path) -> dict[str, Any]:
return header
-def _safetensors_meta_state_dict(path: Path) -> StateDict:
+def safetensors_meta_state_dict(path: Path) -> StateDict:
"""Build a state dict of `meta` tensors from a safetensors file's header.
Identification only ever reads keys, shapes and dtypes off a state dict - never tensor data - so loading
the tensors costs the model's full size in RAM for every probe and buys nothing. The header is a few KB at
- the front of the file, and `meta` tensors carry the shape and dtype without any storage behind them.
+ the front of the file, and `meta` tensors carry the shape and dtype without any storage behind them. A loader
+ uses it the same way, to decide which tensors to read and how much RAM they need before reading any.
Raises:
- Exception: The header could not be parsed, or names a dtype with no torch equivalent. Callers should
- fall back to loading the file for real.
+ OSError: The file could not be read.
+ ValueError: The header could not be parsed, or names a dtype with no entry in `SAFETENSORS_DTYPES`.
+ Identification falls back to loading the file for real.
"""
header = read_safetensors_header(path)
- return {
- key: torch.empty(info["shape"], dtype=SAFETENSORS_DTYPES[info["dtype"]], device="meta")
- for key, info in header.items()
- }
+ state_dict: StateDict = {}
+ for key, info in header.items():
+ dtype = SAFETENSORS_DTYPES.get(info["dtype"])
+ if dtype is None:
+ raise ValueError(f"{path.name} stores '{key}' as {info['dtype']}, a dtype this build cannot read.")
+ state_dict[key] = torch.empty(info["shape"], dtype=dtype, device="meta")
+ return state_dict
def unwrap_state_dict(checkpoint: dict[Any, Any]) -> StateDict:
@@ -236,7 +253,7 @@ class ModelOnDisk:
checkpoint = sdnq_sd_loader(path, compute_dtype=torch.float32)
else:
try:
- checkpoint = _safetensors_meta_state_dict(path)
+ checkpoint = safetensors_meta_state_dict(path)
except Exception:
logger.debug(f"Could not read the safetensors header of {path}, loading the whole file")
checkpoint = safetensors.torch.load_file(path)
diff --git a/invokeai/backend/quantization/int8_convrot.py b/invokeai/backend/quantization/int8_convrot.py
index 83dda6a81b..43666a0d2c 100644
--- a/invokeai/backend/quantization/int8_convrot.py
+++ b/invokeai/backend/quantization/int8_convrot.py
@@ -1165,6 +1165,7 @@ def install_int8_convrot_layers(
reserve: Callable[[int], None],
skip_patterns: Iterable[str] = (),
extra_reserved_bytes: int = 0,
+ read: Callable[[str], torch.Tensor] | None = None,
) -> dict[str, dict[str, Any]]:
"""Take a marked int8 or int4 checkpoint from state dict to installed ``Int8ConvrotLinear`` and
``Int4ConvrotLinear`` modules.
@@ -1191,12 +1192,24 @@ def install_int8_convrot_layers(
``reserve`` is the cache's ``make_room``; ``extra_reserved_bytes`` is for a loader whose file
also holds layers of another scheme -- Krea-2 and Z-Image add what their nvfp4 layers will cost,
- so the one reservation covers the whole load. Returns the layers that stayed int8.
+ so the one reservation covers the whole load. ``read`` is for a loader that hands over the file's header as
+ ``meta`` tensors: steps 1 and 2 need only keys, shapes and dtypes, so each ``meta`` entry is read through it after
+ the reservation, and no payload lands on an unreserved cache. Returns the layers that stayed int8.
"""
reject_foreign_quantization_scales(sd, quantized, architecture, model)
reserve(
predict_int8_cast_size(sd, dtype, quantized, model=model, skip_patterns=skip_patterns) + extra_reserved_bytes
)
+ if read is not None:
+ # The reservation is each tensor at its width after the cast, so a dense tensor is cast as it arrives: reading
+ # an fp32 file's dense tensors first and casting them afterwards holds twice what was reserved, in anonymous
+ # memory. The marked layers' payloads stay as stored for the split to keep or decode. No local holds the payload:
+ # it would keep the stored tensor alive through the next read.
+ marked = _pinned_quantized_keys(quantized)
+ for key in [key for key, tensor in sd.items() if tensor.is_meta]:
+ sd[key] = read(key)
+ if key not in marked and is_castable_float(sd[key]):
+ sd[key] = sd[key].to(dtype)
surviving = split_int8_convrot_layers(sd, quantized, dtype, model=model, skip_patterns=skip_patterns)
cast_unquantized(sd, dtype, surviving)
swap_in_int8_linears(model, sd, surviving)
diff --git a/pyproject.toml b/pyproject.toml
index b8e0f54271..9cd288e776 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -59,7 +59,7 @@ dependencies = [
"imageio>=2.37; sys_platform == 'win32' and platform_machine == 'ARM64'",
"imageio-ffmpeg>=0.6; sys_platform == 'win32' and platform_machine == 'ARM64'",
"psutil>=6", # video decode worker process-tree termination
- "safetensors",
+ "safetensors>=0.8.0",
"sentencepiece==0.2.2", # 0.2.0 has a heap overflow; 0.2.1 coredumped on windows loading the t5 tokenizer
"spandrel",
# Loosely pinned, will respect requirement of `diffusers[torch]`. Split by platform: linux/win allow
diff --git a/tests/app/invocations/test_wan_denoise.py b/tests/app/invocations/test_wan_denoise.py
index c4dc2bb80b..6ef348424e 100644
--- a/tests/app/invocations/test_wan_denoise.py
+++ b/tests/app/invocations/test_wan_denoise.py
@@ -9,7 +9,9 @@ runner. End-to-end tests against real Wan checkpoints are gated behind
from __future__ import annotations
+import gc
import os
+import weakref
from collections import Counter
from contextlib import contextmanager
from pathlib import Path
@@ -1582,3 +1584,53 @@ class TestWanVideoDenoiseMultiFrame:
num_latent_frames=t_lat,
)
assert torch.allclose(latents[:, :, 1:], expected_noise[:, :, 1:], atol=1e-5)
+
+
[email protected]("invocation_type", ["image", "video"])
+def test_outgoing_expert_is_collectable_when_the_denoise_loop_loads_the_next(
+ invocation_type: str, fake_model_root: Path
+) -> None:
+ """The loop's own `transformer` local would keep the high-noise expert alive through the low-noise
+ load, so both experts would be resident during every swap."""
+ ctx = _build_context(
+ nn.Identity(),
+ transformer_low=nn.Identity(),
+ variant=WanVariantType.T2V_A14B,
+ model_root=fake_model_root,
+ pos_cond=_make_conditioning(),
+ neg_cond=None,
+ )
+ high_ref: list[weakref.ref] = []
+ outgoing_collected: list[bool] = []
+
+ def load(model_id) -> MagicMock:
+ if str(getattr(model_id, "submodel_type", None)) == "SubModelType.Transformer2":
+ gc.collect()
+ outgoing_collected.append(high_ref[0]() is None)
+ expert = _ZeroTransformer(label="low")
+ else:
+ expert = _ZeroTransformer(label="high")
+ high_ref.append(weakref.ref(expert))
+ loaded = _make_loaded_model(expert)
+ # A plain int, as on the real LoadedModel: a mock attribute would point back at `loaded`.
+ loaded.weight_bytes = 0
+ return loaded
+
+ ctx.models.load.side_effect = load
+ field = _wan_transformer_field(dual=True, boundary_ratio=0.5)
+ if invocation_type == "image":
+ inv = _make_invocation(
+ field,
+ WanConditioningField(conditioning_name="pos"),
+ None,
+ width=64,
+ height=64,
+ steps=6,
+ guidance_scale=1.0,
+ )
+ else:
+ inv = _make_video_invocation(transformer_field=field, num_frames=5, steps=6)
+
+ inv._run_diffusion(ctx)
+
+ assert outgoing_collected == [True]
diff --git a/tests/app/invocations/test_wan_expert_swapper.py b/tests/app/invocations/test_wan_expert_swapper.py
index 360d230721..2ac9099dbd 100644
--- a/tests/app/invocations/test_wan_expert_swapper.py
+++ b/tests/app/invocations/test_wan_expert_swapper.py
@@ -14,6 +14,8 @@ so we can verify the swapper hands back the right model and routes the right
LoRA factory at each step.
"""
+import gc
+import weakref
from types import SimpleNamespace
from typing import Iterable, Tuple
from unittest.mock import patch
@@ -701,3 +703,35 @@ def test_slots_cleared_when_device_exit_raises():
assert log.count("lora-exit") == 1
assert log.count("device-exit:HIGH") == 1
+
+
+def test_outgoing_expert_is_collectable_when_the_next_expert_loads():
+ """While the swapper (or the caller) still references the outgoing expert, both experts are
+ resident through the incoming load. Handles are built per load and kept nowhere else, so any
+ surviving reference is the swapper's."""
+ log: list[str] = []
+ refs: dict[str, weakref.ref] = {}
+ outgoing_collected: list[bool] = []
+
+ class _Models:
+ def load(self, model_id):
+ if model_id == "low":
+ gc.collect()
+ outgoing_collected.append(refs["high"]() is None)
+ model = nn.Linear(1, 1)
+ refs[model_id] = weakref.ref(model)
+ return _FakeInfo(model_id.upper(), model, log)
+
+ swapper = _ExpertSwapper(
+ context=SimpleNamespace(models=_Models()),
+ high_model="high",
+ low_model="low",
+ inference_dtype=torch.bfloat16,
+ high_lora_factory=None,
+ low_lora_factory=None,
+ )
+ swapper.get(_ExpertSwapper.HIGH)
+ swapper.get(_ExpertSwapper.LOW)
+ swapper.close()
+
+ assert outgoing_collected == [True]
diff --git a/tests/backend/model_manager/load/test_wan_checkpoint_loader.py b/tests/backend/model_manager/load/test_wan_checkpoint_loader.py
index dc7a4c0093..6469cfe65e 100644
--- a/tests/backend/model_manager/load/test_wan_checkpoint_loader.py
+++ b/tests/backend/model_manager/load/test_wan_checkpoint_loader.py
@@ -7,11 +7,14 @@ expectation.
"""
import json
+import weakref
+from contextlib import contextmanager
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import MagicMock, patch
import pytest
+import safetensors.torch
import torch
from safetensors.torch import save_file
@@ -28,6 +31,7 @@ from tests.fixtures.quantized_payloads import (
quantize_convrot,
quantize_scaled_fp8,
)
+from tests.fixtures.safetensors_files import needs_mapping_that_shows_file_writes, overwrite_payloads
# A structurally faithful but tiny Wan transformer. attention_head_dim must stay
# at 128 — the loader derives num_attention_heads as inner_dim // 128, matching
@@ -380,6 +384,189 @@ class TestSubmodelGuard:
_make_loader()._load_model(MagicMock(), SubModelType.Transformer)
+class TestHeaderFirstRead:
+ """What the header settles before any payload is read, and what the loaded model still holds of the file."""
+
+ @staticmethod
+ def _load_recording(path: Path) -> tuple[torch.nn.Module, list[tuple], list[int]]:
+ """Load through the real reader, logging each payload it hands out and each reservation, in order.
+
+ Also returns, per read, how many earlier payloads that are not bf16 were still alive: source tensors that a
+ conversion on arrival has already replaced by then.
+ """
+ events: list[tuple] = []
+ alive_at_read: list[int] = []
+ sources: list[weakref.ref] = []
+ real_safe_open = safetensors.safe_open
+
+ def handed_out(key: str, tensor: torch.Tensor) -> torch.Tensor:
+ events.append(("read", key))
+ alive = [ref() for ref in sources]
+ alive_at_read.append(sum(1 for t in alive if t is not None and t.dtype != torch.bfloat16))
+ del alive
+ sources.append(weakref.ref(tensor))
+ return tensor
+
+ class Handle:
+ def __init__(self, handle) -> None:
+ self._handle = handle
+
+ def __getattr__(self, name: str):
+ return getattr(self._handle, name)
+
+ def get_tensor(self, key: str) -> torch.Tensor:
+ return handed_out(key, self._handle.get_tensor(key))
+
+ def get_tensors(self) -> dict[str, torch.Tensor]:
+ # What `load_file` reads through: the whole file.
+ return {key: handed_out(key, tensor) for key, tensor in self._handle.get_tensors().items()}
+
+ @contextmanager
+ def safe_open(*args, **kwargs):
+ with real_safe_open(*args, **kwargs) as handle:
+ yield Handle(handle)
+
+ loader = _make_loader()
+ loader._ram_cache.make_room.side_effect = lambda size: events.append(("reserve", size))
+ dtype = torch.float32 if "int8" in path.name else torch.bfloat16
+ with patch.object(safetensors, "safe_open", safe_open), patch.object(safetensors.torch, "safe_open", safe_open):
+ model = _load(path, loader=loader, dtype=dtype)
+ return model, events, alive_at_read
+
+ @staticmethod
+ def _load_mapped(path: Path, dtype: torch.dtype) -> torch.nn.Module:
+ """The same load with the reader on safetensors' default mmap backend: the control for the overwrite probe."""
+ real_safe_open = safetensors.safe_open
+
+ def mapped(*args, backend: str = "mmap", **kwargs):
+ return real_safe_open(*args, **kwargs)
+
+ with patch.object(safetensors, "safe_open", mapped):
+ return _load(path, dtype=dtype)
+
+ @staticmethod
+ def _all_in_one(tmp_path: Path) -> tuple[torch.nn.Module, Path]:
+ """An fp16 transformer under ComfyUI's prefix, bundled with a VAE and a text encoder."""
+ reference = _tiny_model()
+ sd = {f"model.diffusion_model.{k}": v.half() for k, v in reference.state_dict().items()}
+ sd["vae.decoder.conv_in.weight"] = torch.ones(64, 64, dtype=torch.float16)
+ sd["text_encoders.umt5xxl.transformer.shared.weight"] = torch.ones(64, 64, dtype=torch.float16)
+ path = tmp_path / "wan2.2_t2v_high_noise_14B_aio.safetensors"
+ save_file(sd, path)
+ return reference, path
+
+ def test_bundled_components_are_never_read(self, tmp_path: Path) -> None:
+ reference, path = self._all_in_one(tmp_path)
+
+ _, events, _ = self._load_recording(path)
+
+ read = [key for kind, key in events if kind == "read"]
+ assert sorted(read) == sorted(f"model.diffusion_model.{k}" for k in reference.state_dict())
+
+ def test_room_for_the_cast_size_is_made_before_the_first_read(self, tmp_path: Path) -> None:
+ reference, path = self._all_in_one(tmp_path)
+
+ model, events, _ = self._load_recording(path)
+
+ bf16_size = sum(v.numel() for v in reference.state_dict().values()) * 2
+ assert events[0] == ("reserve", bf16_size)
+ assert [event for event in events if event[0] == "reserve"] == [("reserve", bf16_size)]
+ assert all(t.dtype == torch.bfloat16 for t in model.state_dict().values())
+
+ def test_each_tensor_is_cast_before_the_next_is_read(self, tmp_path: Path) -> None:
+ """The peak stays the finished state dict plus the tensor in flight, never the whole fp16 source."""
+ _, path = self._all_in_one(tmp_path)
+
+ _, _, alive_at_read = self._load_recording(path)
+
+ assert len(alive_at_read) > 2
+ assert max(alive_at_read) == 0
+
+ def test_scaled_fp8_room_is_the_folded_size_and_its_metadata_is_never_read(self, tmp_path: Path) -> None:
+ reference = _tiny_model()
+ sd = {k: v.clone() for k, v in reference.state_dict().items()}
+ target = "blocks.0.attn1.to_q.weight"
+ sd[target] = torch.full_like(sd[target], 0.5).to(torch.float8_e4m3fn)
+ sd["blocks.0.attn1.to_q.scale_weight"] = torch.full((128,), 4.0)
+ sd["blocks.0.attn1.to_q.scale_input"] = torch.tensor([1.0])
+ sd["scaled_fp8"] = torch.zeros(1, dtype=torch.float8_e4m3fn)
+ path = tmp_path / "Wan2.2-A14B-HighNoise-fp8_scaled.safetensors"
+ save_file(sd, path)
+
+ model, events, alive_at_read = self._load_recording(path)
+
+ assert events[0] == ("reserve", sum(v.numel() for v in reference.state_dict().values()) * 2)
+ read = {key for kind, key in events if kind == "read"}
+ assert read == set(reference.state_dict()) | {"blocks.0.attn1.to_q.scale_weight"}
+ # Only the fp8 weight is still alive while its scale is read; it is folded right after.
+ assert max(alive_at_read) == 1
+ folded = model.state_dict()[target]
+ assert folded.dtype == torch.bfloat16
+ assert torch.equal(folded.float(), torch.full_like(folded.float(), 2.0))
+
+ def test_an_int8_checkpoint_reserves_before_any_weight_is_read(self, tmp_path: Path) -> None:
+ """Only the markers are read first. The reservation is every payload at its stored width: dense float32 at
+ the float32 compute dtype, the codes one byte each, the scales float32."""
+ _, sd = _int8_checkpoint(BLOCK_LAYERS)
+ path = _write(tmp_path, sd)
+
+ _, events, _ = self._load_recording(path)
+
+ reserves = [event for event in events if event[0] == "reserve"]
+ first_reserve = events.index(reserves[0])
+ assert all(key.endswith(".comfy_quant") for _, key in events[:first_reserve])
+ assert reserves == [("reserve", sum(v.nbytes for k, v in sd.items() if not k.endswith(".comfy_quant")))]
+ assert len(events[first_reserve + 1 :]) == len(sd) - len(BLOCK_LAYERS)
+
+ @needs_mapping_that_shows_file_writes
+ def test_a_bf16_checkpoint_leaves_nothing_reading_the_file(self, tmp_path: Path) -> None:
+ """bf16 on disk is the case where the cast is a no-op: a mapped tensor would come through it still mapped."""
+ reference = _tiny_model().to(torch.bfloat16)
+ path = tmp_path / "wan22-t2v-a14b-high_noise.safetensors"
+ save_file(reference.state_dict(), path)
+ mapped = self._load_mapped(path, torch.bfloat16)
+
+ model = _load(path)
+ overwrite_payloads(path)
+
+ assert any(not torch.equal(mapped.state_dict()[k], v) for k, v in reference.state_dict().items()), (
+ "the probe sees no change through mmap either, so it cannot tell a copy from a view"
+ )
+ for key, value in reference.state_dict().items():
+ assert torch.equal(model.state_dict()[key], value), key
+
+ @needs_mapping_that_shows_file_writes
+ def test_an_int8_checkpoint_leaves_nothing_reading_the_file(self, tmp_path: Path) -> None:
+ """The int8 codes are kept as stored, so they are never copied by a cast either."""
+ _, sd = _int8_checkpoint(BLOCK_LAYERS)
+ path = _write(tmp_path, sd)
+ mapped = self._load_mapped(path, torch.float32)
+ mapped_before = {key: value.clone() for key, value in mapped.state_dict().items()}
+
+ model = _load(path, dtype=torch.float32)
+ loaded = {key: value.clone() for key, value in model.state_dict().items()}
+ overwrite_payloads(path)
+
+ assert any(not torch.equal(v, mapped_before[k]) for k, v in mapped.state_dict().items()), (
+ "the probe sees no change through mmap either, so it cannot tell a copy from a view"
+ )
+ for key, value in model.state_dict().items():
+ assert torch.equal(value, loaded[key]), key
+
+ def test_an_mx_exponent_grid_is_refused_by_name(self, tmp_path: Path) -> None:
+ """An E8M0 grid has to reach the MXFP8 refusal; a header dtype the reader cannot map would stop it short."""
+ reference = _tiny_model()
+ sd = {k: v.clone() for k, v in reference.state_dict().items()}
+ target = "blocks.0.attn1.to_q"
+ sd[f"{target}.weight"] = sd[f"{target}.weight"].to(torch.float8_e4m3fn)
+ sd[f"{target}.weight_scale"] = torch.full((128, 4), 1.0).to(torch.float8_e8m0fnu)
+ path = tmp_path / "Wan2.2-A14B-HighNoise-mxfp8.safetensors"
+ save_file(sd, path)
+
+ with pytest.raises(NotImplementedError, match="MXFP8"):
+ _load(path)
+
+
# --- ComfyUI int8_tensorwise (convrot) -------------------------------------------------------------------------
GROUP = 16 # a power of 4 that divides every tiny input width, 32 (text_dim) up to 256 (freq_dim)
diff --git a/tests/backend/model_manager/load/test_wan_loader.py b/tests/backend/model_manager/load/test_wan_loader.py
index 6b2b488c3e..30cf264281 100644
--- a/tests/backend/model_manager/load/test_wan_loader.py
+++ b/tests/backend/model_manager/load/test_wan_loader.py
@@ -1,6 +1,7 @@
"""Tests for Wan loader helpers (native -> diffusers key conversion)."""
from contextlib import nullcontext
+from pathlib import Path
from types import SimpleNamespace
from unittest.mock import MagicMock, patch
@@ -8,13 +9,16 @@ import gguf
import pytest
import torch
+from invokeai.backend.model_manager.configs.base import Diffusers_Config_Base
from invokeai.backend.model_manager.load.model_loaders.wan import (
+ WanDiffusersModel,
WanGGUFCheckpointModel,
_convert_wan_native_to_diffusers,
_unwrap_unquantized_to_compute_dtype,
)
-from invokeai.backend.model_manager.taxonomy import WanVariantType
+from invokeai.backend.model_manager.taxonomy import ModelRepoVariant, SubModelType, WanVariantType
from invokeai.backend.quantization.gguf.ggml_tensor import GGMLTensor
+from tests.fixtures.safetensors_files import needs_mapping_that_shows_file_writes, overwrite_payloads
def test_converts_text_and_time_embedders():
@@ -337,3 +341,101 @@ def test_gguf_loader_rejects_missing_model_parameter() -> None:
pytest.raises(RuntimeError, match="missing"),
):
loader._load_from_singlefile(config)
+
+
+class TestDiffusersFolderLoad:
+ """`WanDiffusersModel` against real tiny transformer folders, read through diffusers' own memory mapping."""
+
+ @staticmethod
+ def _model():
+ from diffusers import WanTransformer3DModel
+
+ return WanTransformer3DModel(
+ patch_size=(1, 2, 2),
+ in_channels=16,
+ out_channels=16,
+ num_layers=1,
+ attention_head_dim=128,
+ num_attention_heads=1,
+ ffn_dim=64,
+ text_dim=32,
+ )
+
+ @staticmethod
+ def _config(root: Path, repo_variant: ModelRepoVariant | None = None) -> Diffusers_Config_Base:
+ config = MagicMock(spec=Diffusers_Config_Base)
+ config.path = str(root)
+ config.repo_variant = repo_variant
+ return config
+
+ @staticmethod
+ def _load(config: Diffusers_Config_Base) -> tuple[torch.nn.Module, dict[str, int]]:
+ """The loaded model, and where each of its tensors lived when `from_pretrained` handed it over."""
+ from diffusers import WanTransformer3DModel
+
+ as_loaded: dict[str, int] = {}
+
+ class Recorded(WanTransformer3DModel):
+ @classmethod
+ def from_pretrained(cls, *args, **kwargs):
+ model = WanTransformer3DModel.from_pretrained(*args, **kwargs)
+ as_loaded.update({name: value.data_ptr() for name, value in model.state_dict().items()})
+ return model
+
+ loader = object.__new__(WanDiffusersModel)
+ loader.get_hf_load_class = lambda *_args, **_kwargs: Recorded
+ loader._apply_fp8_layerwise_casting = lambda model, _config, _submodel: model
+ return loader._load_model(config, SubModelType.Transformer), as_loaded
+
+ @staticmethod
+ def _tensors_reading_the_file(root: Path, model: torch.nn.Module) -> set[str]:
+ """The state dict entries that change when the folder's weight files are rewritten underneath them."""
+ loaded = {name: value.clone() for name, value in model.state_dict().items()}
+ for file in (root / "transformer").glob("*.safetensors"):
+ overwrite_payloads(file)
+ return {name for name, value in model.state_dict().items() if not torch.equal(value, loaded[name])}
+
+ @needs_mapping_that_shows_file_writes
+ @pytest.mark.parametrize("repo_variant", [None, ModelRepoVariant.FP16], ids=["default", "fp16-variant-fallback"])
+ def test_an_fp32_folder_leaves_nothing_reading_the_file(
+ self, tmp_path: Path, repo_variant: ModelRepoVariant | None
+ ) -> None:
+ """Wan ships fp32. Everything is cast to bf16 except `_keep_in_fp32_modules`, whose cast is a no-op: left as
+ they come out of `from_pretrained`, those tensors are views of the mapping and hold every shard mapped.
+
+ The fp16 variant is absent, so with it requested the fallback does the loading."""
+ from diffusers import WanTransformer3DModel
+
+ self._model().save_pretrained(tmp_path / "transformer")
+
+ model, _ = self._load(self._config(tmp_path, repo_variant))
+
+ keep_fp32 = set(WanTransformer3DModel._keep_in_fp32_modules)
+ for name, value in model.state_dict().items():
+ expected = torch.float32 if keep_fp32 & set(name.split(".")) else torch.bfloat16
+ assert value.dtype == expected, name
+ assert self._tensors_reading_the_file(tmp_path, model) == set()
+
+ @needs_mapping_that_shows_file_writes
+ @pytest.mark.parametrize("norms_on_disk", ["bf16", "fp32"])
+ def test_a_bf16_folder_keeps_its_weights_on_the_mapping(self, tmp_path: Path, norms_on_disk: str) -> None:
+ """A bf16 file needs no cast: its weights stay on the file's pages, as upstream loads them, with no second copy.
+ Only what is kept in fp32 gets memory of its own -- cast from a bf16 norm, or copied off an fp32 one, the way
+ `save_pretrained` writes a model loaded in bf16."""
+ from diffusers import WanTransformer3DModel
+
+ if norms_on_disk == "bf16":
+ self._model().to(torch.bfloat16).save_pretrained(tmp_path / "transformer")
+ else:
+ self._model().save_pretrained(tmp_path / "fp32")
+ mixed = WanTransformer3DModel.from_pretrained(tmp_path / "fp32", torch_dtype=torch.bfloat16)
+ mixed.save_pretrained(tmp_path / "transformer")
+
+ model, as_loaded = self._load(self._config(tmp_path))
+
+ bf16 = {name for name, value in model.state_dict().items() if value.dtype == torch.bfloat16}
+ assert bf16 and len(bf16) < len(model.state_dict())
+ assert self._tensors_reading_the_file(tmp_path, model) == bf16
+ # Upcast from a bf16 norm, the fp32 tensors already have memory of their own and are not copied again.
+ copied = {name for name, value in model.state_dict().items() if value.data_ptr() != as_loaded[name]}
+ assert copied == (set() if norms_on_disk == "bf16" else set(model.state_dict()) - bf16)
diff --git a/tests/backend/model_manager/test_model_on_disk.py b/tests/backend/model_manager/test_model_on_disk.py
index 1d2ec00957..da9f829ca7 100644
--- a/tests/backend/model_manager/test_model_on_disk.py
+++ b/tests/backend/model_manager/test_model_on_disk.py
@@ -1,10 +1,19 @@
-"""``ModelOnDisk.metadata`` for GGUF files, which identification reads instead of reopening the file."""
+"""The header readers identification and loaders use instead of reading a model's tensors."""
+import json
from pathlib import Path
import gguf
+import pytest
+import torch
+from safetensors.torch import save_file
-from invokeai.backend.model_manager.model_on_disk import ModelOnDisk
+from invokeai.backend.model_manager.model_on_disk import (
+ SAFETENSORS_DTYPES,
+ ModelOnDisk,
+ read_safetensors_header,
+ safetensors_meta_state_dict,
+)
def test_gguf_metadata_keeps_scalar_fields_with_their_types_and_leaves_arrays_out(tmp_path: Path) -> None:
@@ -29,3 +38,43 @@ def test_gguf_metadata_keeps_scalar_fields_with_their_types_and_leaves_arrays_ou
assert metadata["t5encoder.block_count"] == 24 and type(metadata["t5encoder.block_count"]) is int
assert metadata["tokenizer.ggml.add_eos_token"] is True
assert "tokenizer.ggml.tokens" not in metadata
+
+
+def test_a_safetensors_dtype_without_a_torch_dtype_is_refused_by_name(tmp_path: Path) -> None:
+ """A sub-byte format's header counts 4-bit elements, so there is no meta tensor to build for it. The refusal has to
+ name the tensor and the dtype, not surface as a bare ``KeyError`` out of a loader."""
+ header = json.dumps({"layer.weight": {"dtype": "F4", "shape": [4], "data_offsets": [0, 2]}}).encode()
+ path = tmp_path / "packed.safetensors"
+ path.write_bytes(len(header).to_bytes(8, "little") + header + bytes(2))
+
+ with pytest.raises(ValueError, match=r"'layer\.weight' as F4"):
+ safetensors_meta_state_dict(path)
+
+
+def _torch_dtypes() -> list[torch.dtype]:
+ return sorted({value for value in vars(torch).values() if isinstance(value, torch.dtype)}, key=str)
+
+
[email protected]("dtype", _torch_dtypes(), ids=str)
+def test_every_dtype_safetensors_writes_reads_back_from_the_header(tmp_path: Path, dtype: torch.dtype) -> None:
+ """The single-file loaders read through the header, so a dtype `safetensors` writes but the header table lacks
+ fails a checkpoint the full `load_file` reads -- at generation, after identification has installed it through its
+ fallback. Asked of safetensors itself rather than a list, so a dtype it gains is covered too. The sub-byte formats
+ are the one exception, refused by name: their header shapes count elements no torch dtype stores one by one."""
+ path = tmp_path / "tensor.safetensors"
+ try:
+ save_file({"tensor": torch.zeros(2, 3, dtype=dtype)}, str(path))
+ except Exception:
+ # Never for a dtype the table maps: a platform that cannot write it must not turn its coverage into a skip.
+ if dtype in SAFETENSORS_DTYPES.values():
+ raise
+ pytest.skip(f"safetensors or torch cannot write {dtype}")
+
+ stored_as = read_safetensors_header(path)["tensor"]["dtype"]
+ if stored_as in ("F4", "F6_E2M3", "F6_E3M2"):
+ with pytest.raises(ValueError, match=f"as {stored_as}"):
+ safetensors_meta_state_dict(path)
+ return
+ meta = safetensors_meta_state_dict(path)["tensor"]
+
+ assert meta.dtype is dtype and meta.shape == (2, 3) and meta.is_meta
diff --git a/tests/backend/quantization/test_int8_convrot_state_dict.py b/tests/backend/quantization/test_int8_convrot_state_dict.py
index 084807f286..230bba75f6 100644
--- a/tests/backend/quantization/test_int8_convrot_state_dict.py
+++ b/tests/backend/quantization/test_int8_convrot_state_dict.py
@@ -6,6 +6,8 @@ part a loader can get wrong without anything raising — every failure below wou
surface as a model that loads cleanly and generates noise.
"""
+import weakref
+
import pytest
import torch
from safetensors.torch import save_file
@@ -544,6 +546,53 @@ class TestTheSharedInstall:
assert reserved == [4 * CONVROT_GROUP_SIZE * 4]
assert torch.allclose(sd["widens.weight"], int4.dequantized, atol=1e-5)
+ def test_a_header_read_never_holds_more_than_the_reservation(self) -> None:
+ """A loader that hands over the file's header has each payload read after the reservation, which charges a
+ dense tensor at the compute width. Reading an fp32 file's dense tensors first and casting them afterwards held
+ twice that, so each is cast as it arrives; the int8 payload and its scale still arrive as stored."""
+ width = CONVROT_GROUP_SIZE
+ model = self._model()
+ model.dense = torch.nn.Linear(width, width)
+ stored = {
+ **self._int8_layer("keeps"),
+ "dense.weight": torch.randn(width, width),
+ "dense.bias": torch.randn(width),
+ }
+ sd = {key: tensor.to("meta") for key, tensor in stored.items()}
+ reserved: list[int] = []
+ held: list[int] = []
+ # Every payload handed out, so one the install still references outside `sd` counts as held too.
+ handed_out: list[weakref.ref[torch.Tensor]] = []
+
+ def held_bytes() -> int:
+ alive = {id(t): t for t in sd.values() if not t.is_meta}
+ alive.update({id(t): t for t in (ref() for ref in handed_out) if t is not None})
+ return sum(tensor.nelement() * tensor.element_size() for tensor in alive.values())
+
+ def read(key: str) -> torch.Tensor:
+ held.append(held_bytes())
+ payload = stored[key].clone()
+ handed_out.append(weakref.ref(payload))
+ return payload
+
+ install_int8_convrot_layers(
+ model,
+ sd,
+ {"keeps": MARKER},
+ torch.bfloat16,
+ architecture="Wan 2.2",
+ reserve=reserved.append,
+ read=read,
+ )
+ held.append(held_bytes())
+
+ # Spelled out: int8 codes and their float32 scale as stored, the dense tensors at bf16's two bytes.
+ assert reserved == [4 * width + 4 * 4 + (width * width + width) * 2]
+ assert max(held) <= reserved[0]
+ assert sd["dense.weight"].dtype is torch.bfloat16 and sd["dense.bias"].dtype is torch.bfloat16
+ assert sd["keeps.weight"].dtype is torch.int8 and sd["keeps.weight_scale"].dtype is torch.float32
+ assert torch.equal(sd["dense.weight"], stored["dense.weight"].to(torch.bfloat16))
+
def test_read_comfy_quant_markers_reads_a_marker_off_a_file(tmp_path) -> None:
"""The scheme, from the file rather than from a state dict.
diff --git a/tests/fixtures/safetensors_files.py b/tests/fixtures/safetensors_files.py
new file mode 100644
index 0000000000..10b98e6a24
--- /dev/null
+++ b/tests/fixtures/safetensors_files.py
@@ -0,0 +1,47 @@
+"""Probes on a safetensors file a loader has already read."""
+
+import functools
+import os
+import tempfile
+from pathlib import Path
+
+import pytest
+import torch
+from safetensors import safe_open
+from safetensors.torch import save_file
+
+
+def overwrite_payloads(path: Path, byte: bytes = b"\x3f") -> None:
+ """Rewrite every tensor byte of ``path`` in place, leaving the header as it was.
+
+ Where safetensors' mapping shows writes made through a file handle (`mapping_shows_file_writes`), a loaded
+ tensor that still reads the file -- a view of the mapping -- shows the new bytes, and one that was copied does
+ not. Comparing storages cannot tell the two apart: every tensor ``safetensors`` maps from one file reports a
+ storage of its own, the size of the tensor.
+ """
+ with open(path, "r+b") as f:
+ start = 8 + int.from_bytes(f.read(8), "little")
+ size = f.seek(0, os.SEEK_END) - start
+ f.seek(start)
+ f.write(byte * size)
+
+
+def mapping_shows_file_writes() -> bool:
+ """Whether a tensor safetensors maps from a file sees `overwrite_payloads`. It does on Windows and Linux; on the
+ macOS CI runners it keeps the bytes it was mapped with, so there the probe cannot tell a view from a copy."""
+ with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as directory:
+ path = Path(directory) / "probe.safetensors"
+ save_file({"x": torch.zeros(1024)}, path)
+ with safe_open(path, framework="pt") as f:
+ tensor = f.get_tensor("x")
+ overwrite_payloads(path)
+ changed = bool(tensor.any())
+ del tensor
+ return changed
+
+
+needs_mapping_that_shows_file_writes = pytest.mark.skipif(
+ not mapping_shows_file_writes(),
+ reason="safetensors' mapping does not show in-place writes here, so overwrite_payloads can't tell a view from a copy",
+)
diff --git a/uv.lock b/uv.lock
index f23e733478..2cd869c0d3 100644
--- a/uv.lock
+++ b/uv.lock
@@ -2239,7 +2239,7 @@ requires-dist = [
{ name = "rocm-sdk-libraries", marker = "(platform_machine == 'x86_64' and sys_platform == 'linux' and extra == 'rocm') or (platform_machine != 'ARM64' and sys_platform == 'win32' and extra == 'rocm')", specifier = "==10.0.0", index = "https://stable.repo.amd.com/rocm/whl-next/" },
{ name = "ruff", marker = "extra == 'test'", specifier = "~=0.11.2" },
{ name = "ruff-lsp", marker = "extra == 'test'", specifier = "~=0.0.62" },
- { name = "safetensors" },
+ { name = "safetensors", specifier = ">=0.8.0" },
{ name = "scikit-learn", specifier = "~=1.5" },
{ name = "semver", specifier = "~=3.0.1" },
{ name = "sentencepiece", specifier = "==0.2.2" },