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(model-manager): stop float8 checkpoints pinning their file after load (#10194)

Alexander Eichhorn2c1905a6d417
diff --git a/invokeai/backend/model_manager/load/model_loaders/anima.py b/invokeai/backend/model_manager/load/model_loaders/anima.py
index f64d70a75a..d72f57c57c 100644
--- a/invokeai/backend/model_manager/load/model_loaders/anima.py
+++ b/invokeai/backend/model_manager/load/model_loaders/anima.py
@@ -40,6 +40,7 @@ from invokeai.backend.quantization.fp8_scaled import (
extract_comfy_quant_hints,
extract_fp8_scaled_layers,
full_precision_hints_respected,
+ load_safetensors_checkpoint,
parse_quantization_metadata,
read_safetensors_metadata,
reject_quantized_side_channel,
@@ -96,8 +97,6 @@ class AnimaCheckpointModel(ModelLoader):
self,
config: AnyModelConfig,
) -> AnyModel:
- from safetensors.torch import load_file
-
from invokeai.backend.anima.anima_transformer import AnimaTransformer
from invokeai.backend.anima.semantic_connector import AnimaSemanticConnectorConfig
@@ -115,15 +114,16 @@ class AnimaCheckpointModel(ModelLoader):
"Use 'Re-identify model' in the Model Manager to load it as a GGUF model."
)
- # Load the state dict from safetensors
- sd = load_file(model_path)
+ # Only the transformer's tensors are read: an all-in-one's bundled VAE and text encoder, and the runtime-derived
+ # buffers and exporter metadata that aren't model weights, are dropped by name before any payload is read.
+ sd = load_safetensors_checkpoint(
+ model_path,
+ select=lambda names: filter_non_model_keys(strip_anima_bundle_prefix(names)),
+ )
# Strip the transformer-key prefix (`net.` or bundled `model.diffusion_model.`).
sd = strip_anima_bundle_prefix(sd)
- # Drop runtime-derived buffers and exporter metadata that aren't model weights.
- sd = filter_non_model_keys(sd)
-
target_device = TorchDevice.choose_torch_device()
model_dtype = TorchDevice.choose_anima_inference_dtype(target_device)
diff --git a/invokeai/backend/model_manager/load/model_loaders/ernie_image.py b/invokeai/backend/model_manager/load/model_loaders/ernie_image.py
index f1265bd34e..5c8c2850a1 100644
--- a/invokeai/backend/model_manager/load/model_loaders/ernie_image.py
+++ b/invokeai/backend/model_manager/load/model_loaders/ernie_image.py
@@ -4,7 +4,6 @@ from pathlib import Path
from typing import Optional
import accelerate
-import safetensors.torch
from invokeai.backend.model_manager.configs.base import Diffusers_Config_Base
from invokeai.backend.model_manager.configs.factory import AnyModelConfig
@@ -19,7 +18,7 @@ from invokeai.backend.model_manager.taxonomy import (
ModelType,
SubModelType,
)
-from invokeai.backend.quantization.fp8_scaled import reject_quantized_side_channel
+from invokeai.backend.quantization.fp8_scaled import load_safetensors_checkpoint, reject_quantized_side_channel
from invokeai.backend.quantization.gguf.loaders import gguf_sd_loader, unpack_ggml_at_load
from invokeai.backend.util.devices import TorchDevice
@@ -113,7 +112,7 @@ class ErnieImageCheckpointModel(ModelLoader):
target_device = TorchDevice.choose_torch_device()
model_dtype = TorchDevice.choose_bfloat16_safe_dtype(target_device)
- sd = safetensors.torch.load_file(Path(config.path))
+ sd = load_safetensors_checkpoint(Path(config.path))
reject_quantized_side_channel(sd, f"ERNIE-Image checkpoint {Path(config.path).name}")
self._ram_cache.make_room(sum(t.nelement() * model_dtype.itemsize for t in sd.values()))
for key in sd:
diff --git a/invokeai/backend/model_manager/load/model_loaders/flux.py b/invokeai/backend/model_manager/load/model_loaders/flux.py
index 8874f16654..5dacf7a0a9 100644
--- a/invokeai/backend/model_manager/load/model_loaders/flux.py
+++ b/invokeai/backend/model_manager/load/model_loaders/flux.py
@@ -114,6 +114,7 @@ from invokeai.backend.quantization.fp8_scaled import (
full_precision_hints_respected,
is_scale_metadata_key,
iter_weight_scale_pairs,
+ load_safetensors_checkpoint,
parse_quantization_metadata,
read_safetensors_metadata,
reject_quantized_side_channel,
@@ -433,7 +434,7 @@ class CLIPSingleFileLoader(ModelLoader):
)
def _load_text_encoder(self, config: CLIPEmbed_Checkpoint_Config_Base) -> AnyModel:
- sd = load_file(Path(config.path))
+ sd = load_safetensors_checkpoint(Path(config.path))
text_config = clip_text_config(config.variant)
model: CLIPTextModel | CLIPTextModelWithProjection
with accelerate.init_empty_weights():
@@ -733,6 +734,13 @@ class T5EncoderGGUFModel(_T5DtypeByDevice):
return model
+def _without_duplicate_t5_embedding(names: dict[str, str]) -> dict[str, str]:
+ """What of a single-file T5 encoder is worth reading: not the `encoder.embed_tokens` copy of a `shared` embedding."""
+ if "shared.weight" not in names:
+ return names
+ return {key: value for key, value in names.items() if not key.startswith("encoder.embed_tokens.")}
+
+
@ModelLoaderRegistry.register(base=BaseModelType.Any, type=ModelType.T5Encoder, format=ModelFormat.Checkpoint)
class T5EncoderSingleFileLoader(ModelLoader):
"""Load a T5 encoder from one safetensors file with transformers key names (ComfyUI's ``t5xxl_*``).
@@ -803,15 +811,13 @@ class T5EncoderSingleFileLoader(ModelLoader):
model_path = Path(config.path)
keep_fp8, model_dtype = self._storage_format(config, submodel_type)
- sd = load_file(model_path)
+ # The duplicate embedding is never read when `shared` is there to keep.
+ sd = load_safetensors_checkpoint(model_path, select=_without_duplicate_t5_embedding)
# ComfyUI writes the token embedding twice, as `shared` and as the encoder's `embed_tokens`, which the
- # model ties to one parameter. Dropping the copy before anything is cast or reserved saves its size; a file
- # with only the encoder's copy has it renamed, with any scale beside it.
- has_shared = "shared.weight" in sd
- for key in [key for key in sd if key.startswith("encoder.embed_tokens.")]:
- value = sd.pop(key)
- if not has_shared:
- sd["shared." + key.removeprefix("encoder.embed_tokens.")] = value
+ # model ties to one parameter. A file with only the encoder's copy has it renamed, with any scale beside it.
+ if "shared.weight" not in sd:
+ for key in [key for key in sd if key.startswith("encoder.embed_tokens.")]:
+ sd["shared." + key.removeprefix("encoder.embed_tokens.")] = sd.pop(key)
layer_hints = {
**extract_comfy_quant_hints(sd),
@@ -867,6 +873,18 @@ class T5EncoderSingleFileLoader(ModelLoader):
return model
+#: Present in a FLUX.1 transformer's keys, under `model.diffusion_model.` when the file bundles other components.
+_FLUX_BUNDLE_MARKER_KEY = "model.diffusion_model.double_blocks.0.img_attn.norm.key_norm.scale"
+
+
+def _transformer_of_flux_bundle(names: dict[str, str]) -> dict[str, str]:
+ """What of a FLUX.1 checkpoint is worth reading: in an all-in-one bundle, only the transformer (as
+ `convert_bundle_to_flux_transformer_checkpoint` keeps it), not the VAE and text encoders beside it."""
+ if _FLUX_BUNDLE_MARKER_KEY not in names:
+ return names
+ return {key: value for key, value in names.items() if key.startswith("model.diffusion_model")}
+
+
@ModelLoaderRegistry.register(base=BaseModelType.Flux, type=ModelType.Main, format=ModelFormat.Checkpoint)
class FluxCheckpointModel(ModelLoader):
"""Class to load main models."""
@@ -915,8 +933,8 @@ class FluxCheckpointModel(ModelLoader):
with accelerate.init_empty_weights():
model = Flux(get_flux_transformers_params(config.variant))
- sd = load_file(model_path)
- if "model.diffusion_model.double_blocks.0.img_attn.norm.key_norm.scale" in sd:
+ sd = load_safetensors_checkpoint(model_path, select=_transformer_of_flux_bundle)
+ if _FLUX_BUNDLE_MARKER_KEY in sd:
sd = convert_bundle_to_flux_transformer_checkpoint(sd)
# ComfyUI 'scaled fp8' (fp8 weight + .weight_scale/.scale_weight, optionally an input
@@ -1312,7 +1330,7 @@ class Flux2CheckpointModel(ModelLoader):
model_path = Path(config.path)
# Load state dict
- sd = load_file(model_path)
+ sd = load_safetensors_checkpoint(model_path)
# The `match` above admits only the transformer, so that is the submodel the cast will be
# asked about too -- keep and cast therefore decide on the same input.
@@ -1343,6 +1361,8 @@ class Flux2CheckpointModel(ModelLoader):
# -- including the three a fused `qkv` becomes, which each inherit the fused layer's
# per-tensor scale and marker.
converted_sd = convert_flux2_bfl_to_diffusers(sd, module_map=flux2_modules)
+ # The conversion built a new dict; the source would keep every source tensor alive through the widening.
+ sd.clear()
int8_markers = extract_int8_convrot_markers(converted_sd)
# The header is the other place a repack declares its scheme, and for FLUX.2 that is
# not hypothetical: Comfy-Org's own fp8 build of this model carries *no* per-layer
@@ -1379,6 +1399,8 @@ class Flux2CheckpointModel(ModelLoader):
# asked by name cannot see that a fused qkv whose rows are not divisible by three is
# left unsplit, and would fan a hint onto three modules that do not exist.
converted_sd = convert_flux2_bfl_to_diffusers(sd, module_map=flux2_modules)
+ # The conversion built a new dict; the source would keep every source tensor alive through the widening.
+ sd.clear()
layer_hints = {
renamed: hints for name, hints in layer_hints.items() for renamed in (flux2_modules.get(name) or [name])
diff --git a/invokeai/backend/model_manager/load/model_loaders/flux3.py b/invokeai/backend/model_manager/load/model_loaders/flux3.py
index 655c65b1f0..b8b8b76971 100644
--- a/invokeai/backend/model_manager/load/model_loaders/flux3.py
+++ b/invokeai/backend/model_manager/load/model_loaders/flux3.py
@@ -49,11 +49,11 @@ from invokeai.backend.quantization.fp8_scaled import (
Fp8ScaledLayer,
attach_fp8_scales,
cast_state_dict,
- clone_unreplaced_tensors,
count_fp8_weights,
dequantize_fp8_scaled,
extract_comfy_quant_hints,
extract_fp8_scaled_layers,
+ load_safetensors_checkpoint,
read_safetensors_metadata,
split_fp8_scaled_layers,
translate_torchao_fp8_layers,
@@ -135,7 +135,11 @@ def flux3_transformer_from_single_file(
"""
log = logger or _logger
make_room = reserve or _reserve_nothing
- sd = CheckpointPrefix.detect(sd).strip(sd)
+ stripped = CheckpointPrefix.detect(sd).strip(sd)
+ if stripped is not sd:
+ # The caller still holds `sd`; emptied, it cannot keep the sources alive through the cast.
+ sd.clear()
+ sd = stripped
header_layers = flux3_header_layers(metadata, sd)
markers = {
key[: -len(COMFY_QUANT_SUFFIX)]: parse_comfy_quant_marker(value)
@@ -190,7 +194,6 @@ def flux3_transformer_from_single_file(
fp8_layers=fp8_layers,
nvfp4_payloads=nvfp4_payloads,
)
- mapped = dict(sd) if fp8_layers and not keep_fp8 else None
if fp8_layers and not keep_fp8:
# Kept, they would be dequantized on every forward to save memory nobody asked to save.
dequantize_fp8_scaled(sd, fp8_layers, dtype)
@@ -199,11 +202,6 @@ def flux3_transformer_from_single_file(
# layer whose scale `scaled_mm` cannot apply.
fp8_layers = split_fp8_scaled_layers(sd, fp8_layers, dtype, model=model, skip_patterns=skip_patterns)
cast_state_dict(sd, dtype, keep_fp8=keep_fp8, model=model, skip_patterns=skip_patterns)
- if mapped is not None:
- # Tensors the fold and cast left as they were are slices of the file mapping and would pin it, uncounted.
- # Only on this path: kept fp8 codes stay mapped, as copying them would defeat the keep.
- clone_unreplaced_tensors(sd, mapped)
- mapped.clear()
if nvfp4_payloads:
if modelopt:
# After the reservation: the copies it makes are what the reservation counts for the packed layers.
@@ -290,12 +288,10 @@ class Flux3CheckpointModel(ModelLoader):
if submodel_type is not SubModelType.Transformer:
raise ValueError("A single-file FLUX.3 model holds only the transformer.")
- from safetensors.torch import load_file
-
model_path = Path(config.path)
model_dtype = TorchDevice.choose_bfloat16_safe_dtype(TorchDevice.choose_torch_device())
model = flux3_transformer_from_single_file(
- load_file(model_path),
+ load_safetensors_checkpoint(model_path),
model_dtype,
self._ram_cache.make_room,
metadata=read_safetensors_metadata(model_path, self._logger),
diff --git a/invokeai/backend/model_manager/load/model_loaders/ideogram4.py b/invokeai/backend/model_manager/load/model_loaders/ideogram4.py
index acc9a4b693..f10cfb8527 100644
--- a/invokeai/backend/model_manager/load/model_loaders/ideogram4.py
+++ b/invokeai/backend/model_manager/load/model_loaders/ideogram4.py
@@ -51,6 +51,7 @@ from invokeai.backend.quantization.fp8_scaled import (
extract_comfy_quant_hints,
extract_fp8_scaled_layers,
full_precision_hints_respected,
+ load_safetensors_checkpoint,
parse_quantization_metadata,
read_safetensors_metadata,
reject_quantized_side_channel,
@@ -375,7 +376,7 @@ class Ideogram4CheckpointModel(ModelLoader):
target_device = TorchDevice.choose_torch_device()
model_dtype = TorchDevice.choose_bfloat16_safe_dtype(target_device)
- sd: dict[str, torch.Tensor] = load_file(model_path)
+ sd: dict[str, torch.Tensor] = load_safetensors_checkpoint(model_path)
# Which of the two ComfyUI side channels this file carries is decided once, and int8 first:
# an int8 layer ships a `.weight_scale` too, so probing for scales without ruling int8 out
diff --git a/invokeai/backend/model_manager/load/model_loaders/krea2.py b/invokeai/backend/model_manager/load/model_loaders/krea2.py
index 19961cd8c1..c9f3298890 100644
--- a/invokeai/backend/model_manager/load/model_loaders/krea2.py
+++ b/invokeai/backend/model_manager/load/model_loaders/krea2.py
@@ -58,6 +58,7 @@ from invokeai.backend.quantization.fp8_scaled import (
extract_comfy_quant_hints,
extract_fp8_scaled_layers,
full_precision_hints_respected,
+ load_safetensors_checkpoint,
parse_quantization_metadata,
read_safetensors_metadata,
reattach_layer_sidechannel,
@@ -541,7 +542,6 @@ class Krea2CheckpointModel(ModelLoader):
def _load_from_singlefile(self, config: AnyModelConfig) -> AnyModel:
from diffusers import Krea2Transformer2DModel
- from safetensors.torch import load_file
if not isinstance(config, Main_Checkpoint_Krea2_Config):
raise TypeError(f"Expected Main_Checkpoint_Krea2_Config, got {type(config).__name__}.")
@@ -550,13 +550,15 @@ class Krea2CheckpointModel(ModelLoader):
target_device = TorchDevice.choose_torch_device()
model_dtype = TorchDevice.choose_bfloat16_safe_dtype(target_device)
- sd = load_file(model_path)
- metadata = read_safetensors_metadata(model_path, self._logger)
- sd = CheckpointPrefix.detect(sd).strip(sd)
# Discard what the key conversion below would discard anyway, before anything is spent on
- # it. One repack quantizes `last.up` with a blockwise scale grid this decode does not
+ # it: not even read. One repack quantizes `last.up` with a blockwise scale grid this decode does not
# implement; refusing a tensor that is on its way to the bin would be an odd way to fail.
- sd = _drop_discarded_native_final_layers(sd)
+ sd = load_safetensors_checkpoint(
+ model_path,
+ select=lambda names: _drop_discarded_native_final_layers(CheckpointPrefix.detect(names).strip(names)),
+ )
+ metadata = read_safetensors_metadata(model_path, self._logger)
+ sd = CheckpointPrefix.detect(sd).strip(sd)
# Comfy's nvfp4 build names its layers in the header, natively. Take them out before either side-channel
# format below reads a scale: both pair every `weight_scale` with its weight, and the key conversion would
@@ -1082,19 +1084,17 @@ class Qwen3VLEncoderCheckpointLoader(_Qwen3VLEncoderSingleFileLoader[Qwen3VLEnco
def _load_text_encoder(self, config: Qwen3VLEncoder_Checkpoint_Config) -> AnyModel:
import torch
- from safetensors.torch import load_file
from transformers import Qwen3VLModel
model_path = Path(config.path)
target_device = TorchDevice.choose_torch_device()
model_dtype = TorchDevice.choose_bfloat16_safe_dtype(target_device)
- sd = load_file(str(model_path))
- # Ahead of every pass that reads tensors, so the tower is never dequantized, cast, copied or
- # reserved for. (The file *header* is still read below for quantization metadata, which can
- # therefore still name visual layers; those hints match no surviving key and are ignored.)
- # The LM head goes with it: this model has none, and a packed one would name no module.
- sd = drop_qwen3vl_unloaded_keys(sd)
+ # The tower is never read, so never dequantized, cast, copied or reserved for. (The file *header* is still
+ # read below for quantization metadata, which can therefore still name visual layers; those hints match no
+ # surviving key and are ignored.) The LM head goes with it: this model has none, and a packed one would
+ # name no module.
+ sd = load_safetensors_checkpoint(str(model_path), select=drop_qwen3vl_unloaded_keys)
metadata = read_safetensors_metadata(model_path, self._logger)
# Comfy's nvfp4 build packs every language-model projection and names the layers in `.comfy_quant`
diff --git a/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.py b/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.py
index 21616976b3..d30957ba80 100644
--- a/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.py
+++ b/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.py
@@ -75,6 +75,7 @@ from invokeai.backend.quantization.fp8_scaled import (
full_precision_hints_respected,
is_scale_metadata_key,
iter_weight_scale_pairs,
+ load_safetensors_checkpoint,
parse_quantization_metadata,
read_safetensors_metadata,
reject_undecoded_mx_scale,
@@ -1147,27 +1148,30 @@ class MistralEncoderCheckpointLoader(ModelLoader):
)
def _load_text_encoder(self, config: MistralEncoder_Checkpoint_Config) -> AnyModel:
- from safetensors.torch import load_file
-
logger = InvokeAILogger.get_logger(self.__class__.__name__)
target_device = TorchDevice.choose_torch_device()
model_dtype = TorchDevice.choose_bfloat16_safe_dtype(target_device)
model_path = Path(config.path)
- sd = load_file(model_path)
- sd = _strip_known_prefixes(sd)
# Comfy-Org's Ministral 3B file ships the full multimodal stack: a Pixtral vision tower and
# its projector, 222 tensors and ~0.9 GB. Only the language tower encodes prompts and the
- # encoder-only model has no slot for the rest, so drop them before the dequantize/cast pass
- # pays to convert weights that would then be reported as unexpected keys.
- vision_keys = [
- key for key in sd if isinstance(key, str) and key.startswith(("vision_tower.", "multi_modal_projector."))
- ]
- for key in vision_keys:
- del sd[key]
- if vision_keys:
- logger.info(f"Mistral encoder: dropped {len(vision_keys)} vision-tower tensor(s); prompts use the LM only")
+ # encoder-only model has no slot for the rest, so they are never read: not read, copied or converted
+ # by the dequantize/cast pass, only to be reported as unexpected keys.
+ def without_vision_tower(names: dict[str, str]) -> dict[str, str]:
+ kept = {
+ key: value
+ for key, value in _strip_known_prefixes(names).items()
+ if not key.startswith(("vision_tower.", "multi_modal_projector."))
+ }
+ if len(kept) < len(names):
+ logger.info(
+ f"Mistral encoder: skipped {len(names) - len(kept)} vision-tower tensor(s); prompts use the LM only"
+ )
+ return kept
+
+ sd = load_safetensors_checkpoint(model_path, select=without_vision_tower)
+ sd = _strip_known_prefixes(sd)
# The header names layers before this loader strips its own wrapper prefixes on top of the generic ones,
# so the names need both lists. With only the generic tuple, a `language_model.`-prefixed redistribution
diff --git a/invokeai/backend/model_manager/load/model_loaders/moss_image.py b/invokeai/backend/model_manager/load/model_loaders/moss_image.py
index f699e925e2..0bf6974da0 100644
--- a/invokeai/backend/model_manager/load/model_loaders/moss_image.py
+++ b/invokeai/backend/model_manager/load/model_loaders/moss_image.py
@@ -29,7 +29,6 @@ from typing import Any, Mapping, Optional
import accelerate
import torch
from safetensors import safe_open
-from safetensors.torch import load_file
from invokeai.app.util.path_safety import is_plain_filename
from invokeai.backend.model_manager.checkpoint_prefix import CheckpointPrefix
@@ -50,11 +49,12 @@ from invokeai.backend.quantization.fp8_scaled import (
TORCHAO_QDATA_SUFFIX,
attach_fp8_scales,
cast_state_dict,
- clone_unreplaced_tensors,
dequantize_fp8_scaled,
extract_fp8_scaled_layers,
is_scale_metadata_key,
+ load_safetensors_checkpoint,
reject_quantized_side_channel,
+ safetensors_backend,
split_fp8_scaled_layers,
translate_torchao_fp8_layers,
warn_on_unattached_scales,
@@ -166,9 +166,9 @@ def _read_component_state_dict(directory: Path) -> dict[str, torch.Tensor]:
sd: dict[str, torch.Tensor] = {}
for path, keys in moss_image_component_shards(directory).items():
if keys is None:
- sd.update(load_file(path))
+ sd.update(load_safetensors_checkpoint(path))
continue
- with safe_open(path, framework="pt", device="cpu") as f:
+ with safe_open(path, framework="pt", device="cpu", backend=safetensors_backend(path)) as f:
for key in keys:
sd[key] = f.get_tensor(key)
return sd
@@ -264,19 +264,12 @@ class _MossImageTransformerLoading(ModelLoader):
fp8_layers=fp8_layers,
nvfp4_payloads={},
)
- mapped = dict(sd) if fp8_layers and not keep_fp8 else None
if fp8_layers and not keep_fp8:
dequantize_fp8_scaled(sd, fp8_layers, dtype)
fp8_layers = {}
# Folds the layers a skip pattern holds dense (`.proj.q` among them) with their scale applied.
fp8_layers = split_fp8_scaled_layers(sd, fp8_layers, dtype, model=model, skip_patterns=skip_patterns)
cast_state_dict(sd, dtype, keep_fp8=keep_fp8, model=model, skip_patterns=skip_patterns)
- if mapped is not None:
- # Dense tensors the fold and cast left as they were are slices of the file mapping and would pin it,
- # uncounted. The kept path skips this step altogether: copying its fp8 codes costs ~4.4 GB at load, and
- # the mapping plus the copies are alive together for a moment.
- clone_unreplaced_tensors(sd, mapped)
- mapped.clear()
model.load_state_dict(sd, strict=True, assign=True)
# `assign=True` aliases every parameter to its state dict tensor; the dict would keep the whole model alive
# through the cast below.
@@ -292,11 +285,8 @@ class _MossImageTransformerLoading(ModelLoader):
# unscaled fp8 zeroes most of `time_embedding.2` and changed the image in a 4090 A/B. FP8 Storage on an
# fp8 file keeps the file's fp8 layers packed, nothing more (as Qwen-Image-2.1 and FLUX.3 do).
#
- # Memory: the clone step above is skipped on this path. The kept codes and their scales, and every dense
- # tensor already at the compute dtype, are views of the file mapping. On a bf16 device the folded `.proj.q`
- # codes (~396 MB) leave `sd` but stay mapped and uncounted, because those views pin the mapping; on fp16
- # the dense remainder is cast to new tensors and its bf16 bytes stay pinned and uncounted too. On Windows
- # that is committed memory while the model is cached.
+ # Memory: the file is read with pread (an fp8 file always is), so every tensor here owns its storage and
+ # nothing pins the file. The folded `.proj.q` codes (~396 MB) leave `sd` once folded and are freed.
return model.eval()
return self._apply_fp8_layerwise_casting(model.eval(), config, SubModelType.Transformer)
@@ -375,7 +365,7 @@ class MossImageCheckpointModel(_MossImageTransformerLoading):
"Select a standalone Qwen3.5 9B encoder and FLUX.2 VAE on the MOSS-Image model loader."
)
model_path = Path(config.path)
- sd = load_file(model_path)
+ sd = load_safetensors_checkpoint(model_path)
sd = CheckpointPrefix.detect(sd).strip(sd)
# unsloth's torchao fp8 build, renamed to the scaled-fp8 form. Before the split and the geometry read, which
# look for `.weight`.
diff --git a/invokeai/backend/model_manager/load/model_loaders/qwen3_5_encoder.py b/invokeai/backend/model_manager/load/model_loaders/qwen3_5_encoder.py
index 65be2e6322..3e9a42da87 100644
--- a/invokeai/backend/model_manager/load/model_loaders/qwen3_5_encoder.py
+++ b/invokeai/backend/model_manager/load/model_loaders/qwen3_5_encoder.py
@@ -22,7 +22,7 @@ from invokeai.backend.model_manager.configs.qwen3_5_encoder import (
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.taxonomy import AnyModel, BaseModelType, ModelFormat, ModelType, SubModelType
-from invokeai.backend.quantization.fp8_scaled import cast_state_dict, reject_quantized_side_channel
+from invokeai.backend.quantization.fp8_scaled import cast_state_dict, reject_quantized_side_channel, safetensors_backend
from invokeai.backend.quantization.int8_convrot import (
drop_unconsumed_quantization_sidecars,
extract_int8_convrot_markers,
@@ -105,7 +105,7 @@ def load_qwen3_5_text_encoder(
sd: dict[str, torch.Tensor] = {}
for path, keys in keys_by_file.items():
- with safe_open(path, framework="pt", device="cpu") as f:
+ with safe_open(path, framework="pt", device="cpu", backend=safetensors_backend(path)) as f:
for key in keys:
if key in names:
sd[names[key]] = f.get_tensor(key)
diff --git a/invokeai/backend/model_manager/load/model_loaders/qwen_image.py b/invokeai/backend/model_manager/load/model_loaders/qwen_image.py
index 9aebe71f48..647c967563 100644
--- a/invokeai/backend/model_manager/load/model_loaders/qwen_image.py
+++ b/invokeai/backend/model_manager/load/model_loaders/qwen_image.py
@@ -42,6 +42,7 @@ from invokeai.backend.quantization.fp8_scaled import (
dequantize_fp8_scaled,
extract_comfy_quant_hints,
extract_fp8_scaled_layers,
+ load_safetensors_checkpoint,
parse_quantization_metadata,
read_safetensors_metadata,
should_keep_fp8_weights,
@@ -284,7 +285,6 @@ class QwenImageCheckpointModel(ModelLoader):
def _load_from_singlefile(self, config: AnyModelConfig) -> AnyModel:
from diffusers import QwenImageTransformer2DModel
- from safetensors.torch import load_file
from invokeai.backend.util.logging import InvokeAILogger
@@ -297,7 +297,7 @@ class QwenImageCheckpointModel(ModelLoader):
target_device = TorchDevice.choose_torch_device()
model_dtype = TorchDevice.choose_bfloat16_safe_dtype(target_device)
- sd = load_file(str(model_path))
+ sd = load_safetensors_checkpoint(str(model_path))
sd = CheckpointPrefix.detect(sd).strip(sd)
# Earlier versions identified InstantX's Qwen-Image ControlNet, a trimmed copy of this transformer, as a main
# model. Such a record still exists; the file only needs identifying again.
@@ -516,7 +516,6 @@ class QwenVLEncoderCheckpointLoader(ModelLoader):
)
def _load_text_encoder_from_singlefile(self, config: QwenVLEncoder_Checkpoint_Config) -> AnyModel:
- from safetensors.torch import load_file
from transformers import Qwen2_5_VLConfig, Qwen2_5_VLForConditionalGeneration
from invokeai.backend.util.logging import InvokeAILogger
@@ -527,7 +526,7 @@ class QwenVLEncoderCheckpointLoader(ModelLoader):
device_keeps_fp8, model_dtype = self._storage_format(config)
- sd = load_file(str(model_path))
+ sd = load_safetensors_checkpoint(str(model_path))
# Comfy's nvfp4 build keeps the language model's projections in nvfp4, beside scaled fp8 embeddings. Take those
# layers out before the fp8 extraction: it pops every `.weight_scale`, nvfp4's block scales included.
diff --git a/invokeai/backend/model_manager/load/model_loaders/qwen_image_2_1.py b/invokeai/backend/model_manager/load/model_loaders/qwen_image_2_1.py
index 756e86bbc7..6b06bc0321 100644
--- a/invokeai/backend/model_manager/load/model_loaders/qwen_image_2_1.py
+++ b/invokeai/backend/model_manager/load/model_loaders/qwen_image_2_1.py
@@ -24,10 +24,10 @@ from invokeai.backend.model_manager.util.qwen3_vl import drop_qwen3vl_visual_tow
from invokeai.backend.quantization.fp8_scaled import (
attach_fp8_scales,
cast_state_dict,
- clone_unreplaced_tensors,
dequantize_fp8_scaled,
extract_comfy_quant_hints,
extract_fp8_scaled_layers,
+ load_safetensors_checkpoint,
parse_quantization_metadata,
read_safetensors_metadata,
split_fp8_scaled_layers,
@@ -177,7 +177,6 @@ def _vision_tower_tensors(folder: Path) -> list[tuple[Path, str, list[int]]]:
def _load_vision_tower(folder: Path, dtype: torch.dtype) -> torch.nn.Module:
"""The encoder's vision tower alone, as `Qwen3VLModel.visual` would hold it, without reading the language model."""
- from safetensors import safe_open
from transformers import AutoConfig
from transformers.models.qwen3_vl.modeling_qwen3_vl import Qwen3VLVisionModel
@@ -185,13 +184,21 @@ def _load_vision_tower(folder: Path, dtype: torch.dtype) -> torch.nn.Module:
with accelerate.init_empty_weights():
tower = Qwen3VLVisionModel._from_config(vision_config, torch_dtype=dtype)
+ keys_by_shard: dict[Path, dict[str, str]] = {}
+ for shard, key, _shape in _vision_tower_tensors(folder):
+ prefix = next(p for p in _VISION_TOWER_PREFIXES if key.startswith(p))
+ keys_by_shard.setdefault(shard, {})[key] = key[len(prefix) :]
state_dict: dict[str, torch.Tensor] = {}
- tensors = _vision_tower_tensors(folder)
- for shard in sorted({shard for shard, *_ in tensors}):
- with safe_open(shard, framework="pt", device="cpu") as f:
- for _shard, key, _shape in (t for t in tensors if t[0] == shard):
- prefix = next(p for p in _VISION_TOWER_PREFIXES if key.startswith(p))
- state_dict[key[len(prefix) :]] = f.get_tensor(key).to(dtype)
+ for shard, names in keys_by_shard.items():
+ # Owned storage whatever the shard holds: a bf16 tower's cast to bf16 returns the tensor itself, and a view of a
+ # text-encoder shard keeps all of it mapped for as long as the tower is cached.
+ tensors = load_safetensors_checkpoint(
+ shard, select=lambda keys, wanted=names: {k: k for k in keys if k in wanted}, owned=True
+ )
+ # Popped as it is cast, so a shard's raw tensors and their casts do not coexist.
+ for key in list(tensors):
+ state_dict[names[key]] = tensors.pop(key).to(dtype)
+ del tensors
load_state_dict_ignoring_extras(tower, state_dict, source=f"Qwen3-VL vision tower in {folder}", assign=True)
reject_incomplete_load(tower, what="Qwen3-VL vision tower")
return tower.eval()
@@ -212,12 +219,10 @@ class QwenImage21CheckpointModel(ModelLoader):
if submodel_type is not SubModelType.Transformer:
raise ValueError(f"Only the transformer is in a single file. Received: {submodel_type}")
- from safetensors.torch import load_file
-
model_path = Path(config.path)
model_dtype = TorchDevice.choose_bfloat16_safe_dtype(TorchDevice.choose_torch_device())
- sd = load_file(model_path)
+ sd = load_safetensors_checkpoint(model_path)
sd = CheckpointPrefix.detect(sd).strip(sd)
# unsloth's torchao FP8 build, renamed to the ComfyUI scaled-fp8 form everything below reads.
translate_torchao_fp8_layers(sd)
@@ -272,17 +277,11 @@ class QwenImage21CheckpointModel(ModelLoader):
fp8_layers=fp8_layers,
nvfp4_payloads={},
)
- mapped = dict(sd) if fp8_layers and not keep_fp8 else None
if fp8_layers and not keep_fp8:
dequantize_fp8_scaled(sd, fp8_layers, model_dtype)
fp8_layers = {}
fp8_layers = split_fp8_scaled_layers(sd, fp8_layers, model_dtype, model=model, skip_patterns=skip_patterns)
kept = cast_state_dict(sd, model_dtype, keep_fp8=keep_fp8, model=model, skip_patterns=skip_patterns)
- if mapped is not None:
- # Parameters the fold and cast left as they were are slices of the file mapping and would pin it,
- # uncounted. Only on this path: kept fp8 codes stay mapped, as copying them would defeat the keep.
- clone_unreplaced_tensors(sd, mapped)
- mapped.clear()
load_state_dict_ignoring_extras(
model, sd, source="Qwen-Image-2.1 single-file checkpoint", assign=True, allow_missing=True
diff --git a/invokeai/backend/model_manager/load/model_loaders/text_llm.py b/invokeai/backend/model_manager/load/model_loaders/text_llm.py
index 6b7c9014d4..6a8ebc6b00 100644
--- a/invokeai/backend/model_manager/load/model_loaders/text_llm.py
+++ b/invokeai/backend/model_manager/load/model_loaders/text_llm.py
@@ -11,7 +11,6 @@ from typing import TYPE_CHECKING, Optional
import accelerate
import torch
-from safetensors.torch import load_file
from transformers import (
AutoConfig,
AutoModelForCausalLM,
@@ -31,7 +30,11 @@ from invokeai.backend.model_manager.configs.text_llm import (
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.taxonomy import AnyModel, BaseModelType, ModelFormat, ModelType, SubModelType
-from invokeai.backend.quantization.fp8_scaled import cast_state_dict, reject_quantized_side_channel
+from invokeai.backend.quantization.fp8_scaled import (
+ cast_state_dict,
+ load_safetensors_checkpoint,
+ reject_quantized_side_channel,
+)
from invokeai.backend.quantization.int8_convrot import (
drop_unconsumed_quantization_sidecars,
extract_int8_convrot_markers,
@@ -76,6 +79,12 @@ class _TextLLMLoader(ModelLoader):
return 0
return super().get_size_fs(config, model_path, submodel_type)
+ def _without_mtp_head(self, names: dict[str, str], what: str) -> dict[str, str]:
+ """What of a single file is worth reading: not the multi-token-prediction head, which is never read at all."""
+ kept = {key: value for key, value in names.items() if not is_multi_token_prediction_key(key)}
+ _log_dropped_mtp(self._logger, what, len(names) - len(kept))
+ return kept
+
def _compute_dtype(self, cpu_only: bool | None, *, avoid_float16: bool) -> torch.dtype:
# float32 for CPU-only models: CPU float16 is emulated and slow.
if cpu_only is True:
@@ -142,7 +151,7 @@ class TextLLMCheckpointLoader(_TextLLMLoader):
path = Path(config.path)
what = f"Qwen3.5 checkpoint {path.name}"
model = qwen3_5_vl_from_state_dict(
- load_file(path),
+ load_safetensors_checkpoint(path, select=lambda names: self._without_mtp_head(names, what)),
self._compute_dtype(config.cpu_only, avoid_float16=True),
reserve=self._ram_cache.make_room,
what=what,
@@ -165,6 +174,16 @@ class TextLLMCheckpointLoader(_TextLLMLoader):
)
+def is_multi_token_prediction_key(key: str) -> bool:
+ """The `mtp.*` head the int8 build ships: generation never runs it."""
+ return key.startswith("mtp.")
+
+
+def _log_dropped_mtp(logger: Logger, what: str, count: int) -> None:
+ if count:
+ logger.info(f"{what}: dropped {count} multi-token-prediction tensor(s) (mtp.*), which generation never runs.")
+
+
def qwen3_5_vl_from_state_dict(
sd: dict[str, torch.Tensor],
dtype: torch.dtype,
@@ -189,13 +208,10 @@ def qwen3_5_vl_from_state_dict(
"""
from transformers import Qwen3_5ForConditionalGeneration
- mtp = [key for key in sd if key.startswith("mtp.")]
- for key in mtp:
+ dropped = [key for key in sd if is_multi_token_prediction_key(key)]
+ for key in dropped:
del sd[key]
- if mtp:
- logger.info(
- f"{what}: dropped {len(mtp)} multi-token-prediction tensor(s) (mtp.*), which generation never runs."
- )
+ _log_dropped_mtp(logger, what, len(dropped))
markers = extract_int8_convrot_markers(sd)
# Outside the int8 branch, so an int8 weight whose marker is missing or unreadable is refused, not cast as codes.
diff --git a/invokeai/backend/model_manager/load/model_loaders/z_image.py b/invokeai/backend/model_manager/load/model_loaders/z_image.py
index 7f71447988..c0ec4c5ed3 100644
--- a/invokeai/backend/model_manager/load/model_loaders/z_image.py
+++ b/invokeai/backend/model_manager/load/model_loaders/z_image.py
@@ -55,6 +55,7 @@ from invokeai.backend.quantization.fp8_scaled import (
extract_comfy_quant_hints,
extract_fp8_scaled_layers,
full_precision_hints_respected,
+ load_safetensors_checkpoint,
parse_quantization_metadata,
read_safetensors_metadata,
reject_quantized_side_channel,
@@ -484,7 +485,6 @@ class ZImageCheckpointModel(ModelLoader):
config: AnyModelConfig,
) -> AnyModel:
from diffusers import ZImageTransformer2DModel
- from safetensors.torch import load_file
if not isinstance(config, Main_Checkpoint_ZImage_Config):
raise TypeError(
@@ -494,7 +494,7 @@ class ZImageCheckpointModel(ModelLoader):
model_path = Path(config.path)
# Load the state dict from safetensors/checkpoint file
- sd = load_file(model_path)
+ sd = load_safetensors_checkpoint(model_path)
# Some Z-Image checkpoint files have keys prefixed with "diffusion_model." or
# "model.diffusion_model." (ComfyUI-style format). Check if we need to strip this prefix.
@@ -1115,7 +1115,6 @@ class Qwen3EncoderCheckpointLoader(ModelLoader):
self,
config: AnyModelConfig,
) -> AnyModel:
- from safetensors.torch import load_file
from transformers import Qwen3Config, Qwen3ForCausalLM
from invokeai.backend.util.logging import InvokeAILogger
@@ -1132,7 +1131,7 @@ class Qwen3EncoderCheckpointLoader(ModelLoader):
device_keeps_fp8, model_dtype = self._storage_format(config)
# Load the state dict from safetensors file
- sd = load_file(model_path)
+ sd = load_safetensors_checkpoint(model_path)
original_key_count = len(sd)
# Three ComfyUI side channels reach this loader and a file carries one of them. int8 is
diff --git a/invokeai/backend/model_manager/model_on_disk.py b/invokeai/backend/model_manager/model_on_disk.py
index 142ed931df..4474e1b53b 100644
--- a/invokeai/backend/model_manager/model_on_disk.py
+++ b/invokeai/backend/model_manager/model_on_disk.py
@@ -59,19 +59,33 @@ def read_safetensors_header(path: Path) -> dict[str, Any]:
Raises:
OSError: The file could not be read.
- ValueError: The header is not valid JSON (an empty or truncated file, or not safetensors at all).
+ ValueError: The file is not safetensors: its header length, JSON or tensor entries are not a safetensors
+ header's. The one error for every way a file can fail that, so callers need not guess which.
"""
+ not_safetensors = f"{path} is not a safetensors file"
with open(path, "rb") as f:
header_length = int.from_bytes(f.read(8), "little")
# Any 8 bytes decode to a length; for a file that is not safetensors that length is garbage, and reading it
# would try to allocate it.
if header_length > os.fstat(f.fileno()).st_size - 8:
- raise ValueError(f"{path} is not a safetensors file: its header length exceeds the file size")
- header = json.loads(f.read(header_length))
+ raise ValueError(f"{not_safetensors}: its header length exceeds the file size")
+ try:
+ header = json.loads(f.read(header_length))
+ except ValueError as e: # JSONDecodeError and UnicodeDecodeError
+ raise ValueError(f"{not_safetensors}: its header is not valid JSON ({e})") from e
if not isinstance(header, dict):
- raise ValueError(f"{path} is not a safetensors file: its header is not a JSON object")
+ raise ValueError(f"{not_safetensors}: its header is not a JSON object")
header.pop("__metadata__", None)
+ for key, entry in header.items():
+ if not (
+ isinstance(entry, dict)
+ and isinstance(entry.get("dtype"), str)
+ and isinstance(entry.get("shape"), list)
+ and isinstance(entry.get("data_offsets"), list)
+ and len(entry["data_offsets"]) == 2
+ ):
+ raise ValueError(f"{not_safetensors}: its header entry '{key}' is not a tensor's dtype, shape and offsets")
return header
diff --git a/invokeai/backend/model_manager/util/qwen3_vl.py b/invokeai/backend/model_manager/util/qwen3_vl.py
index 810d4ec1a9..860229c379 100644
--- a/invokeai/backend/model_manager/util/qwen3_vl.py
+++ b/invokeai/backend/model_manager/util/qwen3_vl.py
@@ -162,9 +162,11 @@ def read_qwen3vl_visual_tower_tensors(files: Iterable[Path]) -> dict[str, torch.
"""
from safetensors import safe_open
+ from invokeai.backend.quantization.fp8_scaled import safetensors_backend
+
tensors: dict[str, torch.Tensor] = {}
for path in files:
- with safe_open(str(path), framework="pt", device="cpu") as handle:
+ with safe_open(str(path), framework="pt", device="cpu", backend=safetensors_backend(path)) as handle:
for key in handle.keys():
if is_qwen3vl_visual_key(key):
tensors[key] = handle.get_tensor(key)
diff --git a/invokeai/backend/quantization/fp8_scaled.py b/invokeai/backend/quantization/fp8_scaled.py
index fb248ffbf3..ae454cc5d7 100644
--- a/invokeai/backend/quantization/fp8_scaled.py
+++ b/invokeai/backend/quantization/fp8_scaled.py
@@ -20,7 +20,7 @@ that :class:`CustomLinear` can decide per forward what to do with it.
from dataclasses import dataclass
from logging import Logger
from pathlib import Path
-from typing import Any, Iterable, Mapping
+from typing import Any, Callable, Iterable, Literal, Mapping
import torch
@@ -99,6 +99,69 @@ def read_safetensors_metadata(path: Path, logger: Logger | None = None) -> dict[
return None
+def _backend_for(header: Mapping[str, Any]) -> Literal["pread", "mmap"]:
+ weights = (".weight", TORCHAO_QDATA_SUFFIX)
+ return "pread" if any(k.endswith(weights) and v["dtype"].startswith("F8_") for k, v in header.items()) else "mmap"
+
+
+def safetensors_backend(path: Path | str) -> Literal["pread", "mmap"]:
+ """The ``backend`` to read ``path``'s tensors with, so that widening its float8 weights releases the file.
+
+ The default mmap backend maps the whole file and every tensor is a slice of that mapping. A loader that
+ widens float8 weights to bf16 replaces the float8 sources, but tensors already in the target dtype (norms,
+ biases) stay views because ``.to`` is a no-op for them, and those few views pin the entire file for the
+ model's lifetime, uncounted by the RAM cache. A float8 weight is the trigger because that is what gets
+ widened while its neighbours stay views: ``.weight``, or torchao's ``._weight_qdata``. A load that keeps its fp8
+ codes is read this way all the same: the codes and the dense layers the cast leaves alone would otherwise pin the
+ file just as well. With ``pread`` every tensor owns its storage.
+
+ Only those float8 weights trigger it. A file without one keeps the lazy mmap load, and so keeps pinning its file
+ through whatever dtype-matching tensors a loader leaves as views: that covers the empty ``scaled_fp8`` marker, a
+ file whose only float8 tensors are nvfp4 block scales (``.weight_scale``), and the modelopt nvfp4 FLUX.3 builds,
+ whose bf16 tensors (see ``relayout_modelopt_nvfp4_payloads``) stay views of the file.
+ """
+ from invokeai.backend.model_manager.model_on_disk import read_safetensors_header
+
+ header = read_safetensors_header(Path(path))
+ return _backend_for(header)
+
+
+def load_safetensors_checkpoint(
+ path: Path | str,
+ *,
+ select: Callable[[dict[str, str]], Mapping[str, str]] | None = None,
+ owned: bool = False,
+) -> dict[str, torch.Tensor]:
+ """Load a single-file checkpoint with the backend :func:`safetensors_backend` picks for it.
+
+ ``select`` names what is worth reading, from the header alone: it is called with ``{key: key}`` for every tensor
+ in the file and returns the part to read (a loader passes its own key rename and drop functions, which only look
+ at names; the values of what comes back name the file's keys). A tensor it leaves out is never read, which is what
+ a bundled VAE or vision tower costs under ``pread``: with mmap an unused tensor was never paged in. The result is
+ keyed by the file's own names, whatever ``select`` renamed.
+
+ ``owned`` reads with ``pread`` whatever the file stores, for a caller whose tensors stay views of the file even
+ though it holds no float8 weight: a bf16 tower, whose cast to bf16 returns the tensor itself.
+
+ The RAM cache's room for the read is not made here: the loader base class asks ``make_room`` for the file's size
+ (``get_size_fs``) before ``_load_model`` runs, and a read is never larger than the file.
+ """
+ from safetensors import safe_open
+
+ from invokeai.backend.model_manager.model_on_disk import read_safetensors_header
+
+ header = read_safetensors_header(Path(path))
+ names = {key: key for key in header}
+ if select is not None:
+ names = {key: key for key in select(names).values()}
+ absent = [key for key in names if key not in header]
+ if absent:
+ raise ValueError(f"{Path(path).name} has no tensor '{absent[0]}'.")
+ backend = "pread" if owned else _backend_for(header)
+ with safe_open(str(path), framework="pt", device="cpu", backend=backend) as f:
+ return {key: f.get_tensor(key) for key in names}
+
+
def parse_quantization_metadata(metadata: Mapping[str, Any] | None) -> dict[str, dict[str, Any]]:
"""Parse the safetensors ``_quantization_metadata`` header entry into a per-layer mapping.
@@ -596,23 +659,6 @@ def translate_torchao_fp8_layers(sd: dict[Any, Any]) -> int:
return len(layers)
-def clone_unreplaced_tensors(sd: dict[Any, Any], before: Mapping[Any, Any]) -> int:
- """Clone every tensor in ``sd`` that is still the very object ``before`` held; return how many.
-
- ``before`` is a shallow ``dict(sd)`` taken ahead of a fold and cast. Those leave a tensor in place when
- nothing needed changing (a bf16 weight cast to bf16 is the same object), and ``load_file`` tensors are slices of
- one file mapping, so each kept one pins the whole mapping for the model's cached life without the cache's size
- calculation seeing it. Tensors the fold or cast replaced are already fresh and are not copied again. Their
- storage cannot tell the two apart: every ``load_file`` tensor reports its own storage and size.
- """
- cloned = 0
- for key, tensor in sd.items():
- if before.get(key) is tensor and isinstance(tensor, torch.Tensor):
- sd[key] = tensor.clone()
- cloned += 1
- return cloned
-
-
def reject_undecoded_mx_scale(path: str, scale: Any) -> None:
"""Refuse an MX exponent grid to anything that is about to multiply it as a number.
diff --git a/tests/backend/flux3/test_loaders.py b/tests/backend/flux3/test_loaders.py
index ef30a20006..1ad5587466 100644
--- a/tests/backend/flux3/test_loaders.py
+++ b/tests/backend/flux3/test_loaders.py
@@ -36,15 +36,12 @@ def _variant(flow_map: bool) -> Flux3VariantType:
@FLOW_MAP
@pytest.mark.parametrize("prefix", ["", "model.diffusion_model."], ids=["bfl", "comfy-prefixed"])
def test_a_single_file_loads_as_the_model_it_was_written_from(monkeypatch, flow_map: bool, prefix: str) -> None:
- import safetensors.torch
-
reference = tiny_flux3_model(flow_map)
native = {prefix + name: value for name, value in to_native(reference).items()}
seam = Seam(
loader=Flux3CheckpointModel,
module=flux3_loaders,
entry="_load_model",
- load_file_host=safetensors.torch,
patches_device=True,
)
run = prepare(seam, monkeypatch, state_dict=native, metadata=None)
diff --git a/tests/backend/flux3/test_quantized_loaders.py b/tests/backend/flux3/test_quantized_loaders.py
index 2d83fcbde5..9c0bb301ba 100644
--- a/tests/backend/flux3/test_quantized_loaders.py
+++ b/tests/backend/flux3/test_quantized_loaders.py
@@ -38,6 +38,7 @@ from tests.backend.flux3.flux3_fixture import (
)
from tests.fixtures.loader_seams import Seam, SeamRun, prepare
from tests.fixtures.quantized_payloads import nvfp4_codes, nvfp4_tensors
+from tests.fixtures.safetensors_files import needs_mapping_that_shows_file_writes, tensors_reading_the_file
SEAM = Seam(
loader=Flux3CheckpointModel,
@@ -79,9 +80,9 @@ def _build(scheme: str, *, flow_map: bool = True, **options) -> QuantizedFlux3:
return quantize_flux3_native(to_native(tiny_flux3_model(flow_map=flow_map)), scheme, **options)
-def _config(flow_map: bool = True) -> Main_Checkpoint_Flux3_Config:
+def _config(flow_map: bool = True, path: str = "flux3.safetensors") -> Main_Checkpoint_Flux3_Config:
variant = Flux3VariantType.Klein if flow_map else Flux3VariantType.KleinBase
- return Main_Checkpoint_Flux3_Config.model_construct(path="flux3.safetensors", name="flux3", variant=variant)
+ return Main_Checkpoint_Flux3_Config.model_construct(path=path, name="flux3", variant=variant)
def _load(
@@ -397,23 +398,23 @@ def test_a_torchao_build_the_loader_cannot_decode_is_refused_before_room_is_rese
assert run.reserved == []
-def test_a_folded_torchao_load_does_not_leave_parameters_pinning_the_file_mapping(
- monkeypatch: pytest.MonkeyPatch,
+@needs_mapping_that_shows_file_writes
[email protected]("keep_fp8", [False, True], ids=["folded", "kept"])
+def test_no_parameter_of_a_torchao_load_reads_the_file_afterwards(
+ monkeypatch: pytest.MonkeyPatch, tmp_path, keep_fp8: bool
) -> None:
- """Dense tensors already in the compute dtype (the text blocks and the embedders) are left in place
- by the fold and the cast; as parameters they would be slices of the file's mapping, which the cache's size
- calculation cannot see."""
+ """Dense tensors already in the compute dtype (the text blocks and the embedders) are left in place by the fold and
+ the cast, and a kept load leaves the fp8 codes as read too. A parameter that is still a slice of the file's mapping
+ pins the whole file, which the cache's size calculation cannot see. Read from a real file: only one has a mapping."""
+ monkeypatch.setattr(load_default, "should_keep_fp8_weights", lambda _device: keep_fp8)
build = _torchao()
+ path = tmp_path / "flux3.safetensors"
+ safetensors.torch.save_file({key: value.clone() for key, value in build.state_dict.items()}, str(path))
- _, model = _load(monkeypatch, build)
+ run = prepare(SEAM, monkeypatch, metadata=build.metadata)
+ model = run.load(_config(path=str(path)), SubModelType.Transformer)
- for name in (
- "txt_mode_blocks.0.attn.to_q.weight",
- "x_embedders.image.weight",
- ):
- parameter = model.get_parameter(name)
- assert parameter.data_ptr() != build.state_dict[name].data_ptr(), name
- assert torch.equal(parameter, build.state_dict[name])
+ assert tensors_reading_the_file(model, path) == []
def test_a_kept_torchao_load_does_not_copy_the_fp8_codes(monkeypatch: pytest.MonkeyPatch) -> None:
diff --git a/tests/backend/model_manager/load/test_anima_fp8_wiring.py b/tests/backend/model_manager/load/test_anima_fp8_wiring.py
index fbaccdc188..62705ab3f9 100644
--- a/tests/backend/model_manager/load/test_anima_fp8_wiring.py
+++ b/tests/backend/model_manager/load/test_anima_fp8_wiring.py
@@ -15,6 +15,7 @@ from types import SimpleNamespace
from unittest.mock import MagicMock
import accelerate
+import safetensors.torch
import torch
from invokeai.backend.anima.anima_transformer import AnimaTransformer
@@ -26,6 +27,7 @@ from invokeai.backend.model_manager.load.load_default import (
)
from invokeai.backend.model_manager.load.model_loaders.anima import AnimaCheckpointModel
from invokeai.backend.model_manager.taxonomy import SubModelType
+from tests.fixtures.safetensors_files import record_reads, served_checkpoint
# Every cast-eligible module in the real Anima graph that the declared patterns protect. Pinned
# exhaustively rather than as a substring check, so both a rename (entries disappear) and an
@@ -104,7 +106,6 @@ def test_single_file_loader_applies_fp8_layerwise_casting(monkeypatch, tmp_path)
`tests/backend/model_manager` and `tests/backend/anima` suites green — nothing else observes
it — so the dead toggle can come straight back with CI passing.
"""
- import safetensors.torch
import invokeai.backend.anima.anima_transformer as anima_transformer_module
@@ -118,7 +119,10 @@ def test_single_file_loader_applies_fp8_layerwise_casting(monkeypatch, tmp_path)
)
monkeypatch.setattr(anima_transformer_module, "AnimaTransformer", _TinyAnimaTransformer)
- monkeypatch.setattr(safetensors.torch, "load_file", lambda _path: {"weight": torch.ones(2, 2)})
+ monkeypatch.setattr(
+ "invokeai.backend.model_manager.load.model_loaders.anima.load_safetensors_checkpoint",
+ served_checkpoint({"weight": torch.ones(2, 2)}),
+ )
# The stand-in state dict has no DiT blocks to read a depth from, and the tiny model takes no config.
monkeypatch.setattr(
"invokeai.backend.model_manager.load.model_loaders.anima.anima_transformer_config", lambda _sd: {}
@@ -151,3 +155,47 @@ def test_single_file_loader_applies_fp8_layerwise_casting(monkeypatch, tmp_path)
assert isinstance(model, _TinyAnimaTransformer)
assert torch.equal(model.weight, torch.ones(2, 2))
assert cast_calls == [(config, SubModelType.Transformer)]
+
+
+def test_an_all_in_ones_vae_text_encoder_and_exporter_metadata_are_never_read(monkeypatch, tmp_path) -> None:
+ """A ComfyUI bundle carries the VAE and text encoder under namespaces of their own, and exporters add sampling
+ schedules and derived buffers. Read through ``pread`` they would cost their size in process memory only to be
+ dropped."""
+ import invokeai.backend.anima.anima_transformer as anima_transformer_module
+
+ transformer = {"model.diffusion_model.weight": torch.ones(2, 2).to(torch.float8_e4m3fn)}
+ elsewhere = {
+ "first_stage_model.decoder.conv.weight": torch.ones(8, 8),
+ "cond_stage_model.layers.0.weight": torch.ones(8, 8),
+ "model.diffusion_model.pos_embedder.seq": torch.arange(4.0),
+ "model.diffusion_model.blocks.0.rope.inv_freq": torch.ones(4),
+ "model_sampling.sigmas": torch.ones(4),
+ }
+ checkpoint_path = tmp_path / "anima.safetensors"
+ safetensors.torch.save_file({**transformer, **elsewhere}, str(checkpoint_path))
+ monkeypatch.setattr(anima_transformer_module, "AnimaTransformer", _TinyAnimaTransformer)
+ monkeypatch.setattr(
+ "invokeai.backend.model_manager.load.model_loaders.anima.anima_transformer_config", lambda _sd: {}
+ )
+ monkeypatch.setattr(
+ "invokeai.backend.model_manager.load.model_loaders.anima.TorchDevice.choose_torch_device",
+ lambda: torch.device("cpu"),
+ )
+ monkeypatch.setattr(
+ "invokeai.backend.model_manager.load.model_loaders.anima.TorchDevice.choose_anima_inference_dtype",
+ lambda _device: torch.float32,
+ )
+ loader = object.__new__(AnimaCheckpointModel)
+ loader._ram_cache = SimpleNamespace(make_room=MagicMock())
+ loader._apply_fp8_layerwise_casting = lambda model, _config, _submodel: model
+ loader._torch_device = torch.device("cpu")
+ loader._logger = MagicMock()
+ log = record_reads(monkeypatch)
+
+ loader._load_from_singlefile(
+ Main_Checkpoint_Anima_Config.model_construct(
+ path=str(checkpoint_path), default_settings=MainModelDefaultSettings()
+ )
+ )
+
+ assert set(log.tensors) == set(transformer)
diff --git a/tests/backend/model_manager/load/test_flux1_int8_convrot_loader.py b/tests/backend/model_manager/load/test_flux1_int8_convrot_loader.py
index bdc23708d4..72864036bb 100644
--- a/tests/backend/model_manager/load/test_flux1_int8_convrot_loader.py
+++ b/tests/backend/model_manager/load/test_flux1_int8_convrot_loader.py
@@ -12,6 +12,7 @@ loader that ignored the rotation would produce a weight that loads cleanly and g
import json
import pytest
+import safetensors.torch
import torch
from invokeai.backend.flux.model import FluxParams
@@ -25,6 +26,7 @@ from invokeai.backend.quantization.int8_convrot import (
)
from tests.fixtures.loader_seams import Seam, prepare
from tests.fixtures.quantized_payloads import comfy_quant_marker, quantize_convrot, quantize_scaled_fp8
+from tests.fixtures.safetensors_files import record_reads
# As the file carries it: rotated along the input dim, per-output-channel scales.
MARKER = {"format": "int8_tensorwise", "per_row": True, "convrot": True, "convrot_groupsize": CONVROT_GROUP_SIZE}
@@ -106,9 +108,13 @@ SEAM = Seam(
)
-def _driver(monkeypatch, tmp_path, state_dict: dict, header: dict | None = None):
+def _driver(monkeypatch, tmp_path, state_dict: dict, header: dict | None = None, *, written: bool = False):
+ """The loader over ``state_dict`` served in place of the file read, or with ``written`` over a real file."""
checkpoint = tmp_path / "flux1-dev-int8-convrot.safetensors"
- checkpoint.touch()
+ if written:
+ safetensors.torch.save_file(state_dict, str(checkpoint))
+ else:
+ checkpoint.touch()
config = Main_Checkpoint_FLUX_Config.model_construct(
path=str(checkpoint), name="flux1-dev-int8", variant=FluxVariantType.Dev
)
@@ -120,14 +126,14 @@ def _driver(monkeypatch, tmp_path, state_dict: dict, header: dict | None = None)
# module symbol being gone.
patch.setattr(flux, "should_keep_fp8_weights", lambda _device: False, raising=False)
- run = prepare(SEAM, monkeypatch, state_dict=state_dict, metadata=header, geometry=geometry)
+ run = prepare(SEAM, monkeypatch, state_dict=None if written else state_dict, metadata=header, geometry=geometry)
# An instance attribute shadows the method, which is what keeps this working either way.
run.loader._keep_fp8_weights = lambda _config, _submodel=None: False
return run, config
-def _load(monkeypatch, tmp_path, state_dict, header: dict | None = None):
- run, config = _driver(monkeypatch, tmp_path, state_dict, header)
+def _load(monkeypatch, tmp_path, state_dict, header: dict | None = None, *, written: bool = False):
+ run, config = _driver(monkeypatch, tmp_path, state_dict, header, written=written)
return run.load(config), run
@@ -402,3 +408,20 @@ def test_a_prefixed_dense_checkpoint_is_refused_for_want_of_every_parameter(monk
with pytest.raises(RuntimeError, match=r"missing \d+ parameter\(s\) that the model requires"):
_load(monkeypatch, tmp_path, prefixed, header=header)
+
+
+def test_the_components_bundled_beside_the_transformer_are_never_read(monkeypatch, tmp_path) -> None:
+ """An all-in-one FLUX.1 file carries a VAE and text encoders under namespaces of their own. Read through ``pread``
+ they would cost their size in process memory only to be dropped by the bundle conversion."""
+ state_dict, _ = _checkpoint()
+ transformer = {f"model.diffusion_model.{key}": value for key, value in state_dict.items()}
+ bundled = {
+ "vae.decoder.conv_in.weight": torch.ones(8, 8, dtype=torch.bfloat16),
+ "text_encoders.clip_l.transformer.embeddings.weight": torch.ones(8, 8, dtype=torch.bfloat16),
+ }
+ log = record_reads(monkeypatch)
+
+ model, _ = _load(monkeypatch, tmp_path, {**transformer, **bundled}, written=True)
+
+ assert set(log.tensors) == set(transformer)
+ assert isinstance(model.double_blocks[0].img_attn.qkv, Int8ConvrotLinear)
diff --git a/tests/backend/model_manager/load/test_ideogram4_diffusers_loader.py b/tests/backend/model_manager/load/test_ideogram4_diffusers_loader.py
index 71e2f98322..0c0c8d2773 100644
--- a/tests/backend/model_manager/load/test_ideogram4_diffusers_loader.py
+++ b/tests/backend/model_manager/load/test_ideogram4_diffusers_loader.py
@@ -63,6 +63,8 @@ QUANTIZED = "layers.0.feed_forward.w1"
TRANSFORMER_SEAM = Seam(
loader=Ideogram4DiffusersModel,
module=ideogram4,
+ # The folder loader reads with a raw `load_file`; only the single-file loader goes through the helper.
+ load_file_host=ideogram4,
entry="_load_one_transformer",
patches_device=True,
sets_torch_dtype=False,
@@ -72,6 +74,8 @@ TRANSFORMER_SEAM = Seam(
ENCODER_SEAM = Seam(
loader=Ideogram4DiffusersModel,
module=ideogram4,
+ # The folder loader reads with a raw `load_file`; only the single-file loader goes through the helper.
+ load_file_host=ideogram4,
entry="_load_text_encoder",
patches_device=True,
sets_torch_dtype=False,
@@ -332,6 +336,8 @@ def test_an_nf4_text_encoder_gets_past_the_guards(monkeypatch: pytest.MonkeyPatc
VAE_SEAM = Seam(
loader=Ideogram4DiffusersModel,
module=ideogram4,
+ # The folder loader reads with a raw `load_file`; only the single-file loader goes through the helper.
+ load_file_host=ideogram4,
entry="_load_vae",
patches_device=True,
sets_torch_dtype=False,
diff --git a/tests/backend/model_manager/load/test_krea2_loader_boundaries.py b/tests/backend/model_manager/load/test_krea2_loader_boundaries.py
index 1c3592fa8c..20d8a2f8eb 100644
--- a/tests/backend/model_manager/load/test_krea2_loader_boundaries.py
+++ b/tests/backend/model_manager/load/test_krea2_loader_boundaries.py
@@ -22,6 +22,7 @@ from invokeai.backend.model_manager.load.model_loaders.krea2 import (
)
from invokeai.backend.model_manager.taxonomy import Krea2VariantType, Qwen3VLVariantType, SubModelType
from invokeai.backend.quantization.int8_convrot import Int4ConvrotLinear, Int8ConvrotLinear
+from tests.fixtures.safetensors_files import record_reads, served_checkpoint
class _TinyVisionTowerHost(torch.nn.Module):
@@ -48,7 +49,6 @@ class _TinyKrea2Transformer(torch.nn.Module):
def test_single_file_loader_constructs_and_materializes_model(monkeypatch, tmp_path) -> None:
import diffusers
- import safetensors.torch
checkpoint_path = tmp_path / "krea2.safetensors"
checkpoint_path.touch()
@@ -66,7 +66,10 @@ def test_single_file_loader_constructs_and_materializes_model(monkeypatch, tmp_p
loader._apply_fp8_layerwise_casting = lambda model, _config, _submodel: model
monkeypatch.setattr(diffusers, "Krea2Transformer2DModel", _TinyKrea2Transformer, raising=False)
- monkeypatch.setattr(safetensors.torch, "load_file", lambda _path: {"weight": torch.ones(2, 2)})
+ monkeypatch.setattr(
+ "invokeai.backend.model_manager.load.model_loaders.krea2.load_safetensors_checkpoint",
+ served_checkpoint({"weight": torch.ones(2, 2)}),
+ )
monkeypatch.setattr(
"invokeai.backend.model_manager.load.model_loaders.krea2.TorchDevice.choose_torch_device",
lambda: torch.device("cpu"),
@@ -95,7 +98,6 @@ def test_single_file_loader_decodes_an_int8_convrot_checkpoint(monkeypatch, tmp_
import json
import diffusers
- import safetensors.torch
from invokeai.backend.quantization.int8_convrot import CONVROT_GROUP_SIZE, build_regular_hadamard
@@ -135,7 +137,10 @@ def test_single_file_loader_decodes_an_int8_convrot_checkpoint(monkeypatch, tmp_
loader._apply_fp8_layerwise_casting = lambda model, _config, _submodel: model
monkeypatch.setattr(diffusers, "Krea2Transformer2DModel", _TinyInt8Krea2Transformer, raising=False)
- monkeypatch.setattr(safetensors.torch, "load_file", lambda _path: state_dict)
+ monkeypatch.setattr(
+ "invokeai.backend.model_manager.load.model_loaders.krea2.load_safetensors_checkpoint",
+ served_checkpoint(state_dict),
+ )
monkeypatch.setattr(
"invokeai.backend.model_manager.load.model_loaders.krea2.TorchDevice.choose_torch_device",
lambda: torch.device("cpu"),
@@ -180,7 +185,6 @@ def test_single_file_loader_keeps_a_mixed_int4_build_named_only_in_its_header_pa
import json
import diffusers
- import safetensors.torch
from invokeai.backend.quantization.int8_convrot import CONVROT_GROUP_SIZE
from tests.fixtures.quantized_payloads import (
@@ -224,7 +228,10 @@ def test_single_file_loader_keeps_a_mixed_int4_build_named_only_in_its_header_pa
loader._apply_fp8_layerwise_casting = lambda model, _config, _submodel: model
monkeypatch.setattr(diffusers, "Krea2Transformer2DModel", _TinyMixedKrea2Transformer, raising=False)
- monkeypatch.setattr(safetensors.torch, "load_file", lambda _path: state_dict)
+ monkeypatch.setattr(
+ "invokeai.backend.model_manager.load.model_loaders.krea2.load_safetensors_checkpoint",
+ served_checkpoint(state_dict),
+ )
monkeypatch.setattr(
"invokeai.backend.model_manager.load.model_loaders.krea2.read_safetensors_metadata", lambda *_args: header
)
@@ -562,7 +569,6 @@ def test_an_int8_weight_without_a_marker_is_refused(monkeypatch, tmp_path) -> No
import json
import diffusers
- import safetensors.torch
class _TinyInt8Krea2Transformer(torch.nn.Module):
def __init__(self, **_kwargs) -> None:
@@ -589,7 +595,10 @@ def test_an_int8_weight_without_a_marker_is_refused(monkeypatch, tmp_path) -> No
loader._logger = MagicMock()
monkeypatch.setattr(diffusers, "Krea2Transformer2DModel", _TinyInt8Krea2Transformer, raising=False)
- monkeypatch.setattr(safetensors.torch, "load_file", lambda _path: state_dict)
+ monkeypatch.setattr(
+ "invokeai.backend.model_manager.load.model_loaders.krea2.load_safetensors_checkpoint",
+ served_checkpoint(state_dict),
+ )
monkeypatch.setattr(
"invokeai.backend.model_manager.load.model_loaders.krea2.TorchDevice.choose_torch_device",
lambda: torch.device("cpu"),
@@ -627,9 +636,10 @@ def _int8_marker_blob(**overrides) -> torch.Tensor:
return torch.frombuffer(bytearray(json.dumps(marker).encode("utf-8")), dtype=torch.uint8).clone()
-def _int8_transformer_driver(monkeypatch, tmp_path, model_class, state_dict):
+def _int8_transformer_driver(monkeypatch, tmp_path, model_class, state_dict, *, written: bool = False):
+ """The loader over ``state_dict``, served in place of the file read, or with ``written`` over a real file."""
import diffusers
- import safetensors.torch
+ from safetensors import torch as safetensors_torch
checkpoint_path = tmp_path / "krea2_int8_convrot.safetensors"
checkpoint_path.touch()
@@ -639,10 +649,17 @@ def _int8_transformer_driver(monkeypatch, tmp_path, model_class, state_dict):
loader = object.__new__(Krea2CheckpointModel)
loader._ram_cache = SimpleNamespace(make_room=MagicMock())
loader._logger = MagicMock()
+ loader._torch_device = torch.device("cpu")
loader._apply_fp8_layerwise_casting = lambda model, _config, _submodel: model
monkeypatch.setattr(diffusers, "Krea2Transformer2DModel", model_class, raising=False)
- monkeypatch.setattr(safetensors.torch, "load_file", lambda _path: state_dict)
+ if written:
+ safetensors_torch.save_file(state_dict, str(checkpoint_path))
+ else:
+ monkeypatch.setattr(
+ "invokeai.backend.model_manager.load.model_loaders.krea2.load_safetensors_checkpoint",
+ served_checkpoint(state_dict),
+ )
monkeypatch.setattr(
"invokeai.backend.model_manager.load.model_loaders.krea2.TorchDevice.choose_torch_device",
lambda: torch.device("cpu"),
@@ -913,7 +930,6 @@ class _TinyNativeKrea2(torch.nn.Module):
def _native_fp8_driver(monkeypatch, tmp_path, state_dict, observe: tuple[str, ...] = ()):
import diffusers
- import safetensors.torch
from invokeai.backend.model_manager.load.model_loaders import krea2
from tests.fixtures.loader_seams import Seam, prepare
@@ -923,7 +939,7 @@ def _native_fp8_driver(monkeypatch, tmp_path, state_dict, observe: tuple[str, ..
config = Main_Checkpoint_Krea2_Config.model_construct(
path=str(checkpoint), variant=Krea2VariantType.Turbo, fp8_storage=None
)
- seam = Seam(loader=Krea2CheckpointModel, module=krea2, load_file_host=safetensors.torch, patches_device=True)
+ seam = Seam(loader=Krea2CheckpointModel, module=krea2, patches_device=True)
run = prepare(
seam,
monkeypatch,
@@ -1075,3 +1091,26 @@ def test_an_nvfp4_layer_missing_its_global_scale_is_refused_before_the_cache_is_
run.load(config)
assert run.reserved == []
+
+
[email protected]("prefix", ["", "model.diffusion_model."], ids=["bare", "comfyui-prefixed"])
+def test_the_final_layers_the_conversion_discards_are_never_read(monkeypatch, tmp_path, prefix: str) -> None:
+ """`last.up` and `last.down` of a native checkpoint have no module in the diffusers model. Read through ``pread``
+ they would cost their size in process memory only to be dropped."""
+ from invokeai.backend.model_manager.configs.main import KREA2_DISCARDED_NATIVE_FINAL_LAYERS
+
+ class _TinyKrea2(torch.nn.Module):
+ def __init__(self, **_kwargs) -> None:
+ super().__init__()
+ self.proj = torch.nn.Linear(4, 4, bias=False)
+
+ state_dict = {f"{prefix}proj.weight": torch.ones(4, 4)}
+ for layer in KREA2_DISCARDED_NATIVE_FINAL_LAYERS:
+ state_dict[f"{prefix}{layer}.weight"] = torch.ones(8, 8).to(torch.float8_e4m3fn)
+ state_dict[f"{prefix}{layer}.weight_scale"] = torch.tensor(1.0)
+ loader, config = _int8_transformer_driver(monkeypatch, tmp_path, _TinyKrea2, state_dict, written=True)
+ log = record_reads(monkeypatch)
+
+ loader._load_from_singlefile(config)
+
+ assert set(log.tensors) == {f"{prefix}proj.weight"}
diff --git a/tests/backend/model_manager/load/test_krea2_nvfp4_loader.py b/tests/backend/model_manager/load/test_krea2_nvfp4_loader.py
index 49298792c0..9cbd463b26 100644
--- a/tests/backend/model_manager/load/test_krea2_nvfp4_loader.py
+++ b/tests/backend/model_manager/load/test_krea2_nvfp4_loader.py
@@ -22,6 +22,7 @@ from invokeai.backend.model_manager.taxonomy import Krea2VariantType
from invokeai.backend.quantization.int8_convrot import CONVROT_GROUP_SIZE, Int8ConvrotLinear
from invokeai.backend.quantization.nvfp4 import NVFP4Linear
from tests.fixtures.quantized_payloads import comfy_quant_marker, nvfp4_signed_tensors
+from tests.fixtures.safetensors_files import served_checkpoint
COMPUTE_DTYPE = torch.bfloat16
@@ -77,7 +78,6 @@ def loaded(request, monkeypatch: pytest.MonkeyPatch, tmp_path) -> SimpleNamespac
"""The loader run over a native nvfp4 file whose `blocks.0.attn.wk` neighbour is dense or int8 -- the two
side-channel branches the nvfp4 layers have to pass through untouched."""
import diffusers
- import safetensors.torch
torch.manual_seed(0)
state_dict: dict[str, torch.Tensor] = {}
@@ -122,7 +122,10 @@ def loaded(request, monkeypatch: pytest.MonkeyPatch, tmp_path) -> SimpleNamespac
loader._apply_fp8_layerwise_casting = lambda model, _config, _submodel: model
monkeypatch.setattr(diffusers, "Krea2Transformer2DModel", _TinyKrea2, raising=False)
- monkeypatch.setattr(safetensors.torch, "load_file", lambda _path: state_dict)
+ monkeypatch.setattr(
+ "invokeai.backend.model_manager.load.model_loaders.krea2.load_safetensors_checkpoint",
+ served_checkpoint(state_dict),
+ )
monkeypatch.setattr(
krea2,
"read_safetensors_metadata",
diff --git a/tests/backend/model_manager/load/test_loader_makes_room_before_reading.py b/tests/backend/model_manager/load/test_loader_makes_room_before_reading.py
new file mode 100644
index 0000000000..50de8ff69e
--- /dev/null
+++ b/tests/backend/model_manager/load/test_loader_makes_room_before_reading.py
@@ -0,0 +1,92 @@
+"""The cache makes room for a single-file checkpoint before its payload is read into process memory.
+
+A float8 checkpoint is read with ``pread``, so its tensors are ordinary process memory the OS cannot reclaim, unlike
+the page cache an mmap load leaves them in. The room for that read is made by the loader base class, which asks the
+cache for the file's size before ``_load_model`` runs; the single-file loaders reserve again later for the state dict
+they build, which replaces that request rather than adding to it (``make_room`` holds nothing).
+"""
+
+from pathlib import Path
+from typing import Any
+
+import pytest
+import torch
+from safetensors.torch import save_file
+
+from invokeai.app.services.config.config_default import InvokeAIAppConfig
+from invokeai.backend.model_manager.configs.main import Main_Checkpoint_Krea2_Config
+from invokeai.backend.model_manager.load.load_default import ModelLoader
+from invokeai.backend.model_manager.load.model_cache.model_cache import ModelCache
+from invokeai.backend.quantization.fp8_scaled import load_safetensors_checkpoint
+from invokeai.backend.util.logging import InvokeAILogger
+from tests.fixtures.safetensors_files import record_reads
+
+
+def _is_cached(cache: ModelCache, key: str) -> bool:
+ try:
+ cache.get(key)
+ except IndexError:
+ return False
+ return True
+
+
+class _ReadsAnFp8File(ModelLoader):
+ """What every single-file loader does first: read the checkpoint through the shared helper."""
+
+ def _load_model(self, config: Any, submodel_type: Any = None) -> torch.nn.Module:
+ load_safetensors_checkpoint(Path(config.path))
+ return torch.nn.Linear(2, 2)
+
+
+def test_room_for_the_file_is_made_before_the_first_tensor_is_read(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ path = tmp_path / "model.safetensors"
+ save_file(
+ {
+ "a.weight": torch.ones(64, 64).to(torch.float8_e4m3fn),
+ "a.bias": torch.zeros(64, dtype=torch.bfloat16),
+ "norm.weight": torch.ones(64, dtype=torch.bfloat16),
+ },
+ str(path),
+ )
+ cache = ModelCache(
+ execution_device_working_mem_gb=1.0,
+ enable_partial_loading=False,
+ keep_ram_copy_of_weights=True,
+ # Room for about 10 kB: the cached model below leaves less than the file needs, so room has to be made.
+ max_ram_cache_size_gb=1e-5,
+ max_vram_cache_size_gb=0.0,
+ execution_device="cpu",
+ logger=InvokeAILogger.get_logger("test"),
+ shared_cpu_weights=None,
+ )
+ cache.put("evictable", torch.nn.Linear(40, 40, bias=False)) # 6.4 kB
+ log = record_reads(monkeypatch)
+ real_make_room = cache.make_room
+
+ def make_room(bytes_needed: int):
+ result = real_make_room(bytes_needed)
+ # One ordered list with the reads: what was asked for, and whether the cached model was evicted by then.
+ log.events.append(("make_room", f"{bytes_needed} evicted={not _is_cached(cache, 'evictable')}"))
+ return result
+
+ monkeypatch.setattr(cache, "make_room", make_room)
+ app_config = InvokeAIAppConfig(use_memory_db=True, models_dir=tmp_path)
+ loader = _ReadsAnFp8File(app_config, InvokeAILogger.get_logger("test"), cache)
+ config = Main_Checkpoint_Krea2_Config.model_construct(
+ key="k", name="model", path=str(path), cpu_only=None, repo_variant=None
+ )
+
+ loader.load_model(config)
+
+ assert log.backends == ["pread"], "the file holds a float8 weight, so it is read into owned memory"
+ kinds = [event[0] for event in log.events]
+ first_read = kinds.index("read")
+ asked = [event for event in log.events[:first_read] if event[0] == "make_room"]
+ assert asked, f"nothing made room before the first read: {log.events}"
+ # The room is for at least what the read puts into memory (the header is not payload) and no more than the file,
+ # and the cache has evicted what stood in the way by the time the first tensor is read.
+ size, evicted = asked[0][1].split(" evicted=")
+ assert path.stat().st_size - 1024 <= int(size) <= path.stat().st_size
+ assert evicted == "True"
diff --git a/tests/backend/model_manager/load/test_loader_seam_driver.py b/tests/backend/model_manager/load/test_loader_seam_driver.py
index 424a28fbfe..a7b2271ee7 100644
--- a/tests/backend/model_manager/load/test_loader_seam_driver.py
+++ b/tests/backend/model_manager/load/test_loader_seam_driver.py
@@ -135,3 +135,36 @@ def test_a_seam_installs_no_stub_it_did_not_ask_for(monkeypatch: pytest.MonkeyPa
# `read_safetensors_metadata` is left alone unless a test names it, so that a seam can be driven
# against a real header.
assert not hasattr(_stubbed, "read_safetensors_metadata")
+
+
+#: A loader module that reads through the shared helper and holds no ``load_file`` of its own.
+_helper_module = SimpleNamespace(load_safetensors_checkpoint=lambda _path, **_: {}, widen=_widen)
+
+
+class _ReadsThroughTheHelper:
+ def _load_from_singlefile(self, _config):
+ state_dict = _helper_module.load_safetensors_checkpoint("ignored")
+ self._ram_cache.make_room(1)
+ _helper_module.widen(state_dict)
+ return torch.nn.Module()
+
+
+def test_a_module_with_the_shared_helper_is_served_through_the_helper(monkeypatch: pytest.MonkeyPatch) -> None:
+ """The helper is patched when the module has it, and no `load_file` is invented for a module without one:
+ patching that name would fail loudly, which is what keeps a wrong host from passing quietly."""
+ run = prepare(Seam(loader=_ReadsThroughTheHelper, module=_helper_module), monkeypatch, state_dict=PACKED)
+
+ run.load(None)
+
+ assert SEEN == [{"lin.weight": torch.float8_e4m3fn}]
+ assert run.dtypes_at_make_room == {"lin.weight": torch.float8_e4m3fn}
+ assert not hasattr(_helper_module, "load_file")
+
+
+def test_a_seam_declaring_a_raw_read_patches_that_host_as_well(monkeypatch: pytest.MonkeyPatch) -> None:
+ raw_host = SimpleNamespace(load_file=lambda _path: {})
+ seam = Seam(loader=_ReadsThroughTheHelper, module=_helper_module, load_file_host=raw_host)
+
+ prepare(seam, monkeypatch, state_dict=PACKED)
+
+ assert raw_host.load_file("ignored") == PACKED
diff --git a/tests/backend/model_manager/load/test_loaders_read_float8_checkpoints_owned.py b/tests/backend/model_manager/load/test_loaders_read_float8_checkpoints_owned.py
new file mode 100644
index 0000000000..9a8eaff480
--- /dev/null
+++ b/tests/backend/model_manager/load/test_loaders_read_float8_checkpoints_owned.py
@@ -0,0 +1,110 @@
+"""A loader that folds or casts float8 weights must read its file through `load_safetensors_checkpoint`.
+
+`load_file` maps the whole file, so the bf16 tensors that stay views after the float8 ones are widened pin
+it for the model's lifetime (see `safetensors_backend`). Which loaders widen float8 is not declared anywhere;
+what they have in common is that they reach one of the fold or cast helpers, so this reads the loaders'
+source for a function that calls one of those and also a raw `load_file`, parsed rather than grepped so a
+comment mentioning either cannot flag or excuse anything.
+"""
+
+import ast
+import inspect
+from pathlib import Path
+
+import pytest
+
+import invokeai.backend.model_manager.load.model_loaders as model_loaders
+
+_FOLDS = {
+ "extract_fp8_scaled_layers",
+ "cast_state_dict",
+ "dequantize_fp8_scaled",
+ "_keep_fp8_weights",
+ "_dequantize_fp8_weights",
+ "_fold_comfy_scaled_weights",
+}
+
+#: (file, function) pairs that read with a raw `load_file` and reach a fold, each with the reason it is safe.
+_ALLOWED: dict[tuple[str, str], str] = {
+ ("ltx2.py", "_load_transformer_from_file"): "refuses float8 weights (reject_float8_weights) before any fold",
+ ("ltx2.py", "_load_text_encoder"): "refuses float8 weights (reject_float8_weights) before any cast",
+}
+
+
+def _called_names(function: ast.AST) -> set[str]:
+ names = set()
+ for node in ast.walk(function):
+ if isinstance(node, ast.Call):
+ names.add(node.func.id if isinstance(node.func, ast.Name) else getattr(node.func, "attr", ""))
+ return names
+
+
+def _raw_float8_readers() -> list[tuple[str, str]]:
+ found = []
+ for path in sorted(Path(inspect.getfile(model_loaders)).parent.glob("*.py")):
+ for node in ast.walk(ast.parse(path.read_text(encoding="utf-8"))):
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
+ called = _called_names(node)
+ if "load_file" in called and called & _FOLDS:
+ found.append((path.name, node.name))
+ return found
+
+
[email protected]_independent
+def test_no_loader_folds_float8_weights_it_read_with_a_raw_load_file() -> None:
+ offenders = [site for site in _raw_float8_readers() if site not in _ALLOWED]
+
+ assert offenders == [], (
+ "These functions fold or cast weights after a raw `load_file`; read through "
+ f"`load_safetensors_checkpoint` or allowlist them with a reason: {offenders}"
+ )
+
+
+#: (file, function) pairs that read tensors through a `safe_open` without choosing its backend, each with the reason it
+#: keeps nothing mapped.
+_ALLOWED_MAPPED_READS: dict[tuple[str, str], str] = {
+ ("mistral_encoder.py", "_extract_tekken_bytes"): "copies the tokenizer's bytes out and keeps no tensor",
+ (
+ "ltx2.py",
+ "_read_dense_component",
+ ): "a file it accepts has no float8 weight (reject_float8_weights refuses it after the read), so mmap is the backend `safetensors_backend` would pick",
+}
+
+
+def _mapped_tensor_readers() -> list[tuple[str, str]]:
+ """Functions that open a file with `safe_open` and take tensors from it without passing a ``backend``.
+
+ The default backend is mmap: each tensor it returns is a view of the file, and a cast to the dtype it already has
+ keeps the view. A loader reading tensors this way must say which backend it means (`pread` through
+ `load_safetensors_checkpoint`, or an explicit ``backend=``), so that the choice is made and visible. Opening a file
+ to list its keys is fine: only a ``with`` block that calls ``get_tensor`` counts.
+ """
+
+ def is_default_backend_open(item: ast.withitem) -> bool:
+ call = item.context_expr
+ return (
+ isinstance(call, ast.Call)
+ and getattr(call.func, "id", getattr(call.func, "attr", "")) == "safe_open"
+ and not any(keyword.arg == "backend" for keyword in call.keywords)
+ )
+
+ found = []
+ for path in sorted(Path(inspect.getfile(model_loaders)).parent.glob("*.py")):
+ for function in ast.walk(ast.parse(path.read_text(encoding="utf-8"))):
+ if not isinstance(function, (ast.FunctionDef, ast.AsyncFunctionDef)):
+ continue
+ for block in ast.walk(function):
+ if isinstance(block, ast.With) and "get_tensor" in _called_names(block):
+ if any(is_default_backend_open(item) for item in block.items):
+ found.append((path.name, function.name))
+ return found
+
+
[email protected]_independent
+def test_no_loader_takes_tensors_from_a_safe_open_it_left_on_the_default_backend() -> None:
+ offenders = [site for site in _mapped_tensor_readers() if site not in _ALLOWED_MAPPED_READS]
+
+ assert offenders == [], (
+ "These functions read tensors through a `safe_open` without a `backend`, so each tensor is a view of the file "
+ f"mapping. Read through `load_safetensors_checkpoint` or name the backend: {offenders}"
+ )
diff --git a/tests/backend/model_manager/load/test_mistral_encoder_checkpoint_loader.py b/tests/backend/model_manager/load/test_mistral_encoder_checkpoint_loader.py
index fe8dc505a7..c8752c1e54 100644
--- a/tests/backend/model_manager/load/test_mistral_encoder_checkpoint_loader.py
+++ b/tests/backend/model_manager/load/test_mistral_encoder_checkpoint_loader.py
@@ -20,6 +20,7 @@ from invokeai.backend.model_manager.taxonomy import MistralVariantType
from invokeai.backend.quantization.nvfp4 import NVFP4Linear, NVFP4Payload
from tests.fixtures.loader_seams import Seam, prepare
from tests.fixtures.quantized_payloads import comfy_quant_marker, quantize_convrot
+from tests.fixtures.safetensors_files import record_reads
# The loader derives head counts as projection rows // 128: two query heads over one key/value head, so a config
# that mixes up the two lookups, or falls back to the cow model's, cannot build this model. Dimensions are multiples
@@ -321,3 +322,24 @@ def test_an_nvfp4_layer_missing_its_global_scale_is_refused_before_the_cache_is_
run.load(_config(checkpoint))
assert run.reserved == []
+
+
+def test_the_vision_tower_and_projector_of_a_multimodal_file_are_never_read(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ """Comfy-Org's Ministral file bundles a Pixtral tower and projector the encoder has no slot for. Read through
+ ``pread`` they would cost their size in process memory before being dropped."""
+ checkpoint, _, _ = _write_checkpoint(tmp_path, evidence="none")
+ language_model = load_file(checkpoint)
+ vision = {
+ "vision_tower.transformer.layers.0.attention.q_proj.weight": torch.ones(8, 8),
+ "vision_tower.patch_conv.weight": torch.ones(8, 3, 2, 2),
+ "multi_modal_projector.linear_1.weight": torch.ones(8, 8),
+ }
+ save_file({**language_model, **vision}, checkpoint)
+ log = record_reads(monkeypatch)
+ run = prepare(SEAM, monkeypatch, geometry=_fp8_matmul(False))
+
+ run.load(_config(checkpoint))
+
+ assert set(log.tensors) == set(language_model)
diff --git a/tests/backend/model_manager/load/test_moss_image_loader.py b/tests/backend/model_manager/load/test_moss_image_loader.py
index 48b38c5184..2dbf1640cb 100644
--- a/tests/backend/model_manager/load/test_moss_image_loader.py
+++ b/tests/backend/model_manager/load/test_moss_image_loader.py
@@ -54,6 +54,11 @@ from tests.backend.model_manager.load.moss_image_fixtures import (
from tests.backend.model_manager.load.state_dicts.moss_image_dit_keys import state_dict_keys as moss_dit_keys
from tests.backend.model_manager.load.state_dicts.moss_image_vae_keys import state_dict_keys as moss_vae_keys
from tests.fixtures.quantized_payloads import comfy_quant_marker
+from tests.fixtures.safetensors_files import (
+ needs_mapping_that_shows_file_writes,
+ record_reads,
+ tensors_reading_the_file,
+)
# `OpenMOSS-Team/MOSS-Image-Base`'s `transformer/config.json` at 1ceede80badddd6a7812069619edaa5633587192, verbatim
# but for `rope_base`, which no tensor records. A literal, so this fails when the detection drifts rather than agreeing
@@ -578,19 +583,11 @@ class TestTorchaoFp8Checkpoint:
fp8_compute_only: bool = False,
dtype: torch.dtype = torch.float32,
) -> tuple[Any, Any, dict[str, torch.Tensor]]:
- """The model, its loader, and the tensors `load_file` returned for the real file.
+ """The model, its loader, and the tensors the loader read from the real file.
`keep_fp8` is FP8 Storage on. `fp8_compute_only` keeps the file's fp8 layers for the fp8 matmul with FP8
Storage off."""
- loaded: dict[str, torch.Tensor] = {}
- real_load_file = loader_module.load_file
-
- def recording_load_file(path: Any) -> dict[str, torch.Tensor]:
- tensors = real_load_file(path)
- loaded.update(tensors)
- return tensors
-
- monkeypatch.setattr(loader_module, "load_file", recording_load_file)
+ loaded = record_reads(monkeypatch).tensors
loader = _loader(MossImageCheckpointModel, monkeypatch)
monkeypatch.setattr(
loader_module.TorchDevice, "choose_bfloat16_safe_dtype", staticmethod(lambda _device: dtype)
@@ -693,19 +690,19 @@ class TestTorchaoFp8Checkpoint:
for layer, (codes, scale) in quantized.items():
assert torch.equal(model.get_submodule(layer).weight, codes.float() * scale), layer
- def test_a_folded_load_does_not_leave_parameters_pinning_the_file_mapping(
- self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+ @needs_mapping_that_shows_file_writes
+ @pytest.mark.parametrize("keep_fp8", [False, True], ids=["folded", "kept"])
+ def test_no_parameter_reads_the_file_after_the_load(
+ self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path, keep_fp8: bool
) -> None:
- """The dense tensors are stored in the compute dtype, so neither the fold nor the cast replaces them; assigned
- as parameters they would be slices of the file's mapping, which the cache's size calculation cannot see."""
- path, dense, _ = self._file(tmp_path)
+ """The dense tensors are stored in the compute dtype, so neither the fold nor the cast replaces them, and a kept
+ load leaves the fp8 codes as read. A parameter that is still a slice of the file's mapping pins the whole file,
+ which the cache's size calculation cannot see."""
+ path, _, _ = self._file(tmp_path)
- model, _, loaded = self._load(monkeypatch, path, keep_fp8=False)
+ model, _, _ = self._load(monkeypatch, path, keep_fp8=keep_fp8)
- for name in ("video_embedder.weight", "layers.0.norm1.weight"):
- parameter = model.get_parameter(name)
- assert parameter.data_ptr() != loaded[name].data_ptr(), name
- assert torch.equal(parameter, dense[name])
+ assert tensors_reading_the_file(model, path) == []
def test_a_kept_fp8_load_does_not_copy_the_codes(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
path, _, _ = self._file(tmp_path)
@@ -839,3 +836,60 @@ class TestGGUFLoader:
with pytest.raises(ValueError, match="holds only the transformer"):
loader._load_model(config, SubModelType.VAE)
+
+
+@needs_mapping_that_shows_file_writes
+def test_a_float8_shard_read_by_its_index_does_not_pin_the_file(tmp_path: Path) -> None:
+ """The sharded read picks keys per shard; the bf16 norms beside a float8 weight would otherwise stay views of
+ the whole shard."""
+ shard = tmp_path / "diffusion_pytorch_model-00001-of-00001.safetensors"
+ save_file(
+ {
+ "blocks.0.norm.weight": torch.arange(65, dtype=torch.float32).to(torch.bfloat16),
+ "blocks.0.proj.weight": torch.ones(256, 256).to(torch.float8_e4m3fn),
+ },
+ str(shard),
+ metadata={"format": "pt"},
+ )
+ _write_index(tmp_path / "diffusion_pytorch_model.safetensors.index.json", {shard.name: ["blocks.0.norm.weight"]})
+
+ sd = loader_module._read_component_state_dict(tmp_path)
+
+ assert list(sd) == ["blocks.0.norm.weight"]
+ assert tensors_reading_the_file(sd, shard) == []
+
+
+def _float8_file(path: Path) -> Path:
+ save_file(
+ {
+ "blocks.0.norm.weight": torch.arange(65, dtype=torch.float32).to(torch.bfloat16),
+ "blocks.0.proj.weight": torch.ones(256, 256).to(torch.float8_e4m3fn),
+ },
+ str(path),
+ metadata={"format": "pt"},
+ )
+ return path
+
+
+@needs_mapping_that_shows_file_writes
+def test_an_unsharded_float8_component_does_not_pin_the_file(tmp_path: Path) -> None:
+ path = _float8_file(tmp_path / "diffusion_pytorch_model.safetensors")
+
+ sd = loader_module._read_component_state_dict(tmp_path)
+
+ assert tensors_reading_the_file(sd, path) == []
+
+
+@needs_mapping_that_shows_file_writes
+def test_a_single_file_float8_checkpoint_does_not_pin_the_file(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ path = _float8_file(tmp_path / "moss-image-dit.safetensors")
+ loader = _loader(MossImageCheckpointModel, monkeypatch)
+ # The read is what is under test; the transformer build one call further is covered by the loads above.
+ read: dict[str, torch.Tensor] = {}
+ monkeypatch.setattr(loader_module, "moss_image_transformer_config", lambda _sd: {})
+ monkeypatch.setattr(loader, "_load_transformer", lambda _config, sd, _geometry, _what, **_: read.update(sd))
+ config = Main_Checkpoint_MossImage_Config.model_construct(path=str(path), name="moss")
+
+ loader._load_model(config, SubModelType.Transformer)
+
+ assert tensors_reading_the_file(read, path) == []
diff --git a/tests/backend/model_manager/load/test_qwen3_vl_encoder_nvfp4_loader.py b/tests/backend/model_manager/load/test_qwen3_vl_encoder_nvfp4_loader.py
index 187fa633e4..be51fa49ff 100644
--- a/tests/backend/model_manager/load/test_qwen3_vl_encoder_nvfp4_loader.py
+++ b/tests/backend/model_manager/load/test_qwen3_vl_encoder_nvfp4_loader.py
@@ -32,6 +32,7 @@ from tests.fixtures.quantized_payloads import (
nvfp4_signed_tensors,
quantize_scaled_fp8,
)
+from tests.fixtures.safetensors_files import record_reads
COMPUTE_DTYPE = torch.bfloat16
HIDDEN = 128
@@ -354,3 +355,19 @@ def test_a_layer_the_decode_would_misread_is_refused_before_the_loader_reserves_
run.load(config)
assert run.reserved == []
+
+
+def test_the_visual_tower_and_the_head_are_never_read_from_the_file(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ """The tower is a separate cache entry and the model has no head. Through ``pread`` a tensor that is read costs its
+ size in process memory whether or not the loader keeps it, so the file's own key names decide what is read."""
+ state_dict, metadata, _ = _checkpoint("marker")
+ run, config = _prepare(monkeypatch, tmp_path, state_dict, metadata)
+ log = record_reads(monkeypatch)
+
+ run.load(config)
+
+ unloaded = {key for key in state_dict if ".visual." in f".{key}" or key.startswith(("lm_head.", "model.lm_head."))}
+ assert any(key.startswith("lm_head.") for key in unloaded) and any("visual" in key for key in unloaded)
+ assert set(log.tensors) == set(state_dict) - unloaded
diff --git a/tests/backend/model_manager/load/test_qwen3_vl_vision_encoder.py b/tests/backend/model_manager/load/test_qwen3_vl_vision_encoder.py
index 5785f37bf8..d8c87014a5 100644
--- a/tests/backend/model_manager/load/test_qwen3_vl_vision_encoder.py
+++ b/tests/backend/model_manager/load/test_qwen3_vl_vision_encoder.py
@@ -38,6 +38,7 @@ from invokeai.backend.quantization.nvfp4 import NVFP4Linear
from invokeai.backend.qwen3_vl.qwen3_vl_assets import load_bundled_qwen3_vl_tokenizer
from tests.backend.model_manager.load.qwen3vl_gguf_fixture import tiny_qwen3vl_config
from tests.fixtures.quantized_payloads import comfy_quant_marker, nvfp4_signed_tensors
+from tests.fixtures.safetensors_files import needs_mapping_that_shows_file_writes, tensors_reading_the_file
_LOADERS = "invokeai.backend.model_manager.load.model_loaders.krea2"
@@ -422,3 +423,21 @@ def test_a_loaded_tower_lent_to_a_towerless_encoder_matches_the_intact_model(tmp
assert len(actual) == len(expected)
for index, (got, want) in enumerate(zip(actual, expected, strict=True)):
assert torch.equal(got, want), f"hidden state {index} differs"
+
+
+@needs_mapping_that_shows_file_writes
+def test_a_float8_files_visual_tower_does_not_pin_the_file(tmp_path):
+ """The tower of a scaled-fp8 build is bf16 beside fp8 language weights, and as views it would keep the whole
+ file mapped for as long as the tower lives."""
+ path = tmp_path / "qwen3vl_fp8.safetensors"
+ tower = {"model.visual.blocks.0.norm1.weight": torch.arange(65, dtype=torch.float32).to(torch.bfloat16)}
+ save_file(
+ {**tower, "model.language_model.layers.0.mlp.weight": torch.ones(256, 256).to(torch.float8_e4m3fn)},
+ str(path),
+ metadata={"format": "pt"},
+ )
+
+ tensors = read_qwen3vl_visual_tower_tensors([path])
+
+ assert list(tensors) == list(tower)
+ assert tensors_reading_the_file(tensors, path) == []
diff --git a/tests/backend/model_manager/load/test_qwen3_vl_visual_tower.py b/tests/backend/model_manager/load/test_qwen3_vl_visual_tower.py
index 81f24eae9f..0967380b73 100644
--- a/tests/backend/model_manager/load/test_qwen3_vl_visual_tower.py
+++ b/tests/backend/model_manager/load/test_qwen3_vl_visual_tower.py
@@ -36,6 +36,7 @@ from invokeai.backend.model_manager.util.qwen3_vl import (
)
from invokeai.backend.quantization.int8_convrot import CONVROT_GROUP_SIZE, build_regular_hadamard
from tests.backend.model_manager.load.qwen3vl_gguf_fixture import tiny_qwen3vl_config
+from tests.fixtures.safetensors_files import needs_mapping_that_shows_file_writes, tensors_reading_the_file
# --- the key filter -------------------------------------------------------------------------------
@@ -420,3 +421,18 @@ def test_the_tower_reserves_its_own_size_at_the_dtype_it_loads_in(monkeypatch, t
elements = sum(v.nelement() for v in saved.visual.state_dict().values())
assert loader.get_size_fs(config, tmp_path, SubModelType.VisionEncoder) == 4 * elements
+
+
+@needs_mapping_that_shows_file_writes
+def test_the_tower_does_not_keep_the_text_encoders_shards_mapped(monkeypatch, tmp_path: Path) -> None:
+ """Saved in the dtype it loads in, the tower's cast is a no-op, so each tensor read from a shard would stay a view
+ of it and keep the encoder's whole shard mapped for as long as the tower is cached."""
+ loader, config, _ = _qwen_image_2_1_pipeline(
+ monkeypatch, tmp_path, conditional_generation=True, max_shard_size="40KB"
+ )
+ tower = loader._load_model(config, SubModelType.VisionEncoder)
+
+ shards = sorted((tmp_path / "text_encoder").glob("*.safetensors"))
+
+ assert len(shards) > 1
+ assert [name for shard in shards for name in tensors_reading_the_file(tower, shard)] == []
diff --git a/tests/backend/model_manager/load/test_qwen_image_2_1_torchao_loader.py b/tests/backend/model_manager/load/test_qwen_image_2_1_torchao_loader.py
index c1b272fa07..c24947dd1b 100644
--- a/tests/backend/model_manager/load/test_qwen_image_2_1_torchao_loader.py
+++ b/tests/backend/model_manager/load/test_qwen_image_2_1_torchao_loader.py
@@ -16,6 +16,11 @@ from invokeai.backend.model_manager.load.model_loaders import qwen_image_2_1
from invokeai.backend.model_manager.load.model_loaders.qwen_image_2_1 import QwenImage21CheckpointModel
from invokeai.backend.model_manager.taxonomy import SubModelType
from tests.fixtures.loader_seams import Seam, prepare
+from tests.fixtures.safetensors_files import (
+ needs_mapping_that_shows_file_writes,
+ record_reads,
+ tensors_reading_the_file,
+)
FP8 = torch.float8_e4m3fn
@@ -45,11 +50,10 @@ SEAM = Seam(
module=qwen_image_2_1,
entry="_load_model",
compute_dtype=torch.bfloat16,
- # The loader imports `load_file` inside the method, so the name it resolves is the package's.
- load_file_host=safetensors.torch,
patches_device=True,
)
+CHECKPOINT = "Qwen-Image-2.1-FP8.safetensors"
QUANTIZED = ("transformer_blocks.0.attn.to_q", "norm_out.linear")
# ComfyUI-layout fused projection, gate rows first; the loader splits it into `gate_layer` and `proj`.
FUSED = "transformer_blocks.0.img_mlp.gate_up"
@@ -82,19 +86,11 @@ def _checkpoint() -> tuple[dict[str, torch.Tensor], dict[str, torch.Tensor], dic
def _load(
monkeypatch: pytest.MonkeyPatch, tmp_path, *, keep_fp8: bool
) -> tuple[torch.nn.Module, dict[str, torch.Tensor]]:
- """The model, and the tensors `load_file` returned for the real file the loader read."""
+ """The model, and the tensors the loader read from the real file."""
state_dict, _, _ = _checkpoint()
- checkpoint = tmp_path / "Qwen-Image-2.1-FP8.safetensors"
+ checkpoint = tmp_path / CHECKPOINT
safetensors.torch.save_file(state_dict, checkpoint)
- loaded: dict[str, torch.Tensor] = {}
- real_load_file = safetensors.torch.load_file
-
- def recording_load_file(path):
- tensors = real_load_file(path)
- loaded.update(tensors)
- return tensors
-
- monkeypatch.setattr(safetensors.torch, "load_file", recording_load_file)
+ loaded = record_reads(monkeypatch).tensors
config = Main_Checkpoint_QwenImage21_Config.model_construct(
path=str(checkpoint), name="qwen21", default_settings=MainModelDefaultSettings(fp8_storage=False)
)
@@ -142,15 +138,14 @@ def test_a_folded_layer_is_exactly_the_codes_times_the_scale(monkeypatch, tmp_pa
PREFIX = "model.diffusion_model."
-def test_a_folded_load_does_not_leave_parameters_pinning_the_file_mapping(monkeypatch, tmp_path) -> None:
- """`img_in` is stored in the compute dtype, so neither the fold nor the cast replaces it; assigned as a parameter it
- would be a slice of the file's mapping, which the cache's size calculation cannot see."""
- model, loaded = _load(monkeypatch, tmp_path, keep_fp8=False)
+@needs_mapping_that_shows_file_writes
[email protected]("keep_fp8", [False, True], ids=["folded", "kept"])
+def test_no_parameter_reads_the_file_after_the_load(monkeypatch, tmp_path, keep_fp8: bool) -> None:
+ """`img_in` is stored in the compute dtype, so neither the fold nor the cast replaces it, and a kept load leaves the
+ fp8 codes as read too. A parameter that is still a slice of the file's mapping pins the whole file."""
+ model, _ = _load(monkeypatch, tmp_path, keep_fp8=keep_fp8)
- for name in ("img_in.weight", "img_in.bias"):
- parameter = model.get_parameter(name)
- assert parameter.data_ptr() != loaded[PREFIX + name].data_ptr(), name
- assert torch.equal(parameter, loaded[PREFIX + name])
+ assert tensors_reading_the_file(model, tmp_path / CHECKPOINT) == []
def test_a_kept_fp8_load_does_not_copy_the_codes(monkeypatch, tmp_path) -> None:
diff --git a/tests/backend/model_manager/load/test_qwen_image_controlnet_loader.py b/tests/backend/model_manager/load/test_qwen_image_controlnet_loader.py
index 2de31f1c42..66bcfdac5d 100644
--- a/tests/backend/model_manager/load/test_qwen_image_controlnet_loader.py
+++ b/tests/backend/model_manager/load/test_qwen_image_controlnet_loader.py
@@ -9,7 +9,6 @@ published (alibaba-pai and Comfy-Org ship dense bf16 files), so refusing costs n
from pathlib import Path
import pytest
-import safetensors.torch
import torch
from diffusers.models.controlnets.controlnet_qwenimage import QwenImageControlNetModel
@@ -236,7 +235,6 @@ def test_an_instantx_file_an_earlier_version_recorded_as_a_main_model_is_refused
loader=QwenImageCheckpointModel,
module=qwen_image,
entry="_load_from_singlefile",
- load_file_host=safetensors.torch,
compute_dtype=torch.bfloat16,
patches_device=True,
sets_torch_dtype=False,
diff --git a/tests/backend/model_manager/load/test_qwen_image_nvfp4_loader.py b/tests/backend/model_manager/load/test_qwen_image_nvfp4_loader.py
index 3216eddffe..8fc052b596 100644
--- a/tests/backend/model_manager/load/test_qwen_image_nvfp4_loader.py
+++ b/tests/backend/model_manager/load/test_qwen_image_nvfp4_loader.py
@@ -15,7 +15,6 @@ from types import SimpleNamespace
from unittest.mock import MagicMock
import pytest
-import safetensors.torch
import torch
from invokeai.backend.model_manager.configs.main import Main_Checkpoint_QwenImage_Config
@@ -32,6 +31,7 @@ from invokeai.backend.quantization.int8_convrot import Int8ConvrotLinear
from invokeai.backend.quantization.nvfp4 import NVFP4Linear
from tests.fixtures.loader_seams import Seam, prepare
from tests.fixtures.quantized_payloads import comfy_quant_marker, nvfp4_signed_tensors, quantize_convrot
+from tests.fixtures.safetensors_files import served_checkpoint
COMPUTE_DTYPE = torch.bfloat16
@@ -57,8 +57,6 @@ ENCODER_SEAM = Seam(
loader=QwenVLEncoderCheckpointLoader,
module=qwen_image,
entry="_load_text_encoder_from_singlefile",
- # The loader imports `load_file` inside the method, so the name it resolves is the package's.
- load_file_host=safetensors.torch,
patches_device=True,
sets_torch_dtype=False,
casts_fp8_storage=False,
@@ -67,9 +65,11 @@ ENCODER_SEAM = Seam(
def _patch_common(monkeypatch: pytest.MonkeyPatch, state_dict: dict, metadata: dict) -> list[bool]:
"""Patch file access and devices; return a log for `_record_fold`."""
- import safetensors.torch
- monkeypatch.setattr(safetensors.torch, "load_file", lambda _path: state_dict)
+ monkeypatch.setattr(
+ "invokeai.backend.model_manager.load.model_loaders.qwen_image.load_safetensors_checkpoint",
+ served_checkpoint(state_dict),
+ )
monkeypatch.setattr(qwen_image, "read_safetensors_metadata", lambda _path, _logger: metadata)
monkeypatch.setattr(qwen_image.TorchDevice, "choose_torch_device", lambda: torch.device("cpu"))
monkeypatch.setattr(qwen_image.TorchDevice, "choose_bfloat16_safe_dtype", lambda _device: COMPUTE_DTYPE)
@@ -539,7 +539,6 @@ def test_the_transformer_refuses_an_nvfp4_layer_missing_its_global_scale_before_
loader=QwenImageCheckpointModel,
module=qwen_image,
entry="_load_from_singlefile",
- load_file_host=safetensors.torch,
compute_dtype=COMPUTE_DTYPE,
patches_device=True,
# This entry reads neither: `_torch_dtype` is read nowhere in `qwen_image`, and the fp8
diff --git a/tests/backend/model_manager/load/test_t5_single_file_loader.py b/tests/backend/model_manager/load/test_t5_single_file_loader.py
index 6143e731af..07ef962a60 100644
--- a/tests/backend/model_manager/load/test_t5_single_file_loader.py
+++ b/tests/backend/model_manager/load/test_t5_single_file_loader.py
@@ -26,6 +26,7 @@ from invokeai.backend.model_manager.load.model_loaders.flux import T5EncoderSing
from invokeai.backend.model_manager.taxonomy import SubModelType
from invokeai.backend.util.devices import TorchDevice
from invokeai.backend.util.logging import InvokeAILogger
+from tests.fixtures.safetensors_files import record_reads
FP8 = torch.float8_e4m3fn
LINEAR_SUFFIXES = (
@@ -350,3 +351,26 @@ def test_device_caches_do_not_share_folded_weights_of_different_dtypes(
dtypes[name] = weight_dtype(device)
assert dtypes == {"cpu": torch.float32, "cuda": torch.float16}
+
+
+def test_the_duplicate_embedding_of_a_comfyui_file_is_never_read(
+ loader: T5EncoderSingleFileLoader, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ """`shared` and `encoder.embed_tokens` are one tied parameter. Read through ``pread``, the second copy would cost
+ the embedding's size in process memory only to be dropped; a file with only the encoder's copy still reads it."""
+ _keep_fp8(monkeypatch, False)
+ reference = _tiny_reference()
+ both = tmp_path / "both.safetensors"
+ only_encoder = tmp_path / "only_encoder.safetensors"
+ _write_raw_fp8(reference, both)
+ _write_fp16_embed_tokens_only(reference, only_encoder)
+ log = record_reads(monkeypatch)
+
+ _load_encoder(loader, both)
+ read_from_both = set(log.tensors)
+ log.tensors.clear()
+ _load_encoder(loader, only_encoder)
+
+ assert "shared.weight" in read_from_both
+ assert not {key for key in read_from_both if key.startswith("encoder.embed_tokens.")}
+ assert "encoder.embed_tokens.weight" in log.tensors
diff --git a/tests/backend/model_manager/load/test_text_llm_loader.py b/tests/backend/model_manager/load/test_text_llm_loader.py
index 27008a1ace..67cef2fb08 100644
--- a/tests/backend/model_manager/load/test_text_llm_loader.py
+++ b/tests/backend/model_manager/load/test_text_llm_loader.py
@@ -13,6 +13,7 @@ from unittest.mock import MagicMock
import pytest
import torch
from PIL import Image
+from safetensors.torch import save_file
from transformers import (
Gemma4Config,
Gemma4ForConditionalGeneration,
@@ -41,6 +42,7 @@ from tests.backend.model_manager.load.state_dicts import flux3_pup_bf16_keys, fl
from tests.fixtures.loader_seams import Seam, prepare
from tests.fixtures.model_roles import encoder_file
from tests.fixtures.quantized_payloads import comfy_quant_marker, quantize_convrot
+from tests.fixtures.safetensors_files import record_reads
Keys = dict[str, tuple[list[int], str]]
@@ -261,6 +263,21 @@ class TestTheCheckpointLoader:
torch.testing.assert_close(_image_features(model), expected_features, rtol=1e-4, atol=1e-5)
assert run.reserved == [_nbytes(model.state_dict())]
+ def test_the_multi_token_prediction_head_is_never_read(
+ self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+ ) -> None:
+ """Generation never runs it; read through ``pread`` it would cost its size in process memory first."""
+ state_dict = _int8_checkpoint(_reference())
+ config = _config(tmp_path)
+ save_file({key: value.contiguous() for key, value in state_dict.items()}, config.path)
+ run = prepare(SEAM, monkeypatch, geometry=_tiny_geometry)
+ log = record_reads(monkeypatch)
+
+ run.load(config, None)
+
+ assert any(key.startswith("mtp.") for key in state_dict)
+ assert set(log.tensors) == {key for key in state_dict if not key.startswith("mtp.")}
+
def test_the_model_generates_with_the_releases_end_of_turn_tokens_and_real_rope_buffers(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
diff --git a/tests/backend/model_manager/load/test_z_image_fp8_wiring.py b/tests/backend/model_manager/load/test_z_image_fp8_wiring.py
index baf2594d93..ad42952216 100644
--- a/tests/backend/model_manager/load/test_z_image_fp8_wiring.py
+++ b/tests/backend/model_manager/load/test_z_image_fp8_wiring.py
@@ -10,12 +10,12 @@ from types import SimpleNamespace
from unittest.mock import MagicMock
import diffusers
-import safetensors.torch
import torch
from invokeai.backend.model_manager.configs.main import Main_Checkpoint_ZImage_Config
from invokeai.backend.model_manager.load.model_loaders.z_image import ZImageCheckpointModel
from invokeai.backend.model_manager.taxonomy import SubModelType, ZImageVariantType
+from tests.fixtures.safetensors_files import served_checkpoint
class _TinyZImageTransformer(torch.nn.Module):
@@ -33,7 +33,10 @@ def _prepare_loader(monkeypatch, tmp_path, state_dict: dict[str, torch.Tensor]):
)
monkeypatch.setattr(diffusers, "ZImageTransformer2DModel", _TinyZImageTransformer, raising=False)
- monkeypatch.setattr(safetensors.torch, "load_file", lambda _path: state_dict)
+ monkeypatch.setattr(
+ "invokeai.backend.model_manager.load.model_loaders.z_image.load_safetensors_checkpoint",
+ served_checkpoint(state_dict),
+ )
monkeypatch.setattr(
"invokeai.backend.model_manager.load.model_loaders.z_image.TorchDevice.choose_torch_device",
lambda: torch.device("cpu"),
diff --git a/tests/backend/model_manager/load/test_z_image_loader_boundaries.py b/tests/backend/model_manager/load/test_z_image_loader_boundaries.py
index 89285dd303..99032f1bae 100644
--- a/tests/backend/model_manager/load/test_z_image_loader_boundaries.py
+++ b/tests/backend/model_manager/load/test_z_image_loader_boundaries.py
@@ -11,7 +11,6 @@ import json
import diffusers
import pytest
import torch
-from safetensors import torch as safetensors_torch
from invokeai.backend.model_manager.configs.default_settings import MainModelDefaultSettings
from invokeai.backend.model_manager.configs.main import Main_Checkpoint_ZImage_Config
@@ -50,9 +49,6 @@ class _TinyZImage(torch.nn.Module):
SEAM = Seam(
loader=ZImageCheckpointModel,
module=z_image,
- # The loader calls `safetensors.torch.load_file` through the package, so patching the name on
- # its own module would patch nothing and let it read the empty file the config points at.
- load_file_host=safetensors_torch,
patches_device=True,
)
diff --git a/tests/backend/model_manager/test_model_on_disk.py b/tests/backend/model_manager/test_model_on_disk.py
index da9f829ca7..ef1cb226bc 100644
--- a/tests/backend/model_manager/test_model_on_disk.py
+++ b/tests/backend/model_manager/test_model_on_disk.py
@@ -78,3 +78,34 @@ def test_every_dtype_safetensors_writes_reads_back_from_the_header(tmp_path: Pat
meta = safetensors_meta_state_dict(path)["tensor"]
assert meta.dtype is dtype and meta.shape == (2, 3) and meta.is_meta
+
+
+ ("header", "reason"),
+ [
+ (b"not json", "not valid JSON"),
+ (b"\xff\xfe", "not valid JSON"),
+ (b"[1, 2]", "not a JSON object"),
+ (b'{"a": 1}', "header entry 'a'"),
+ (b'{"a": {"dtype": "F32", "shape": [1]}}', "header entry 'a'"),
+ (b'{"a": {"dtype": "F32", "shape": [1], "data_offsets": [0]}}', "header entry 'a'"),
+ ],
+ ids=["text", "bytes", "array", "bare number", "no offsets", "short offsets"],
+)
+def test_a_file_that_is_not_safetensors_is_refused_with_one_error_naming_it(
+ tmp_path: Path, header: bytes, reason: str
+) -> None:
+ """A header that parses as JSON but is not a tensor table used to fail later as a bare `TypeError`."""
+ path = tmp_path / "not_a_model.safetensors"
+ path.write_bytes(len(header).to_bytes(8, "little") + header)
+
+ with pytest.raises(ValueError, match=rf"not_a_model\.safetensors is not a safetensors file: .*{reason}"):
+ read_safetensors_header(path)
+
+
+def test_a_file_shorter_than_a_header_length_is_refused(tmp_path: Path) -> None:
+ path = tmp_path / "short.safetensors"
+ path.write_bytes(b"\x01\x02")
+
+ with pytest.raises(ValueError, match="is not a safetensors file"):
+ read_safetensors_header(path)
diff --git a/tests/backend/quantization/test_load_safetensors_checkpoint.py b/tests/backend/quantization/test_load_safetensors_checkpoint.py
new file mode 100644
index 0000000000..0942d9ac21
--- /dev/null
+++ b/tests/backend/quantization/test_load_safetensors_checkpoint.py
@@ -0,0 +1,196 @@
+from pathlib import Path
+
+import pytest
+import torch
+from safetensors.torch import load_file, save_file
+
+from invokeai.backend.model_manager.model_on_disk import read_safetensors_header
+from invokeai.backend.quantization.fp8_scaled import load_safetensors_checkpoint, safetensors_backend
+from tests.fixtures.safetensors_files import record_reads
+
+FLOAT8 = [torch.float8_e4m3fn, torch.float8_e5m2]
+_NORM = torch.arange(65, dtype=torch.float32).to(torch.bfloat16)
+_BIAS = torch.arange(64, dtype=torch.float32).to(torch.bfloat16) + 1
+
+
+def _write(path: Path, tensors: dict[str, torch.Tensor]) -> Path:
+ save_file(tensors, str(path), metadata={"format": "pt"})
+ return path
+
+
+def _fp8_checkpoint(path: Path, dtype: torch.dtype = torch.float8_e4m3fn) -> Path:
+ return _write(
+ path,
+ {
+ "block.norm.weight": _NORM,
+ "block.proj.bias": _BIAS,
+ "block.proj.weight": torch.linspace(-4, 4, 512 * 512).reshape(512, 512).to(dtype),
+ "block.proj.weight_scale": torch.tensor(0.5),
+ },
+ )
+
+
+def _tensors_share_one_mapping(sd: dict[str, torch.Tensor], header: dict, keys: list[str]) -> bool:
+ """With mmap each tensor sits at its header offset inside one mapping, so addresses differ exactly as offsets do."""
+ first, *rest = keys
+ return all(
+ sd[first].data_ptr() - sd[key].data_ptr() == header[first]["data_offsets"][0] - header[key]["data_offsets"][0]
+ for key in rest
+ )
+
+
[email protected]("dtype", FLOAT8, ids=["e4m3", "e5m2"])
+def test_a_float8_file_is_read_into_owned_storage_so_the_widened_weights_do_not_pin_it(
+ tmp_path: Path, dtype: torch.dtype
+) -> None:
+ path = _fp8_checkpoint(tmp_path / "fp8.safetensors", dtype)
+ header = read_safetensors_header(path)
+ survivors = ["block.norm.weight", "block.proj.bias"]
+
+ sd = load_safetensors_checkpoint(path)
+ # What a loader does: widen the float8 weight (the source is replaced), keep the dtype-matching tensors.
+ sd["block.proj.weight"] = sd["block.proj.weight"].to(torch.float32) * sd.pop("block.proj.weight_scale")
+
+ assert not _tensors_share_one_mapping(sd, header, survivors), "the bf16 survivors are views into the file mapping"
+ # The behavioural cost of the pin: a mapped file cannot be deleted on Windows while a view lives.
+ path.unlink()
+ assert sd["block.norm.weight"].tolist() == list(range(65))
+ assert sd["block.proj.bias"].tolist() == [float(i + 1) for i in range(64)]
+
+
+def test_the_mmap_path_pins_the_file_through_its_survivors(tmp_path: Path) -> None:
+ """The same probe on a plain `load_file`: it is the one the float8 path exists to avoid."""
+ path = _fp8_checkpoint(tmp_path / "fp8.safetensors")
+ header = read_safetensors_header(path)
+
+ sd = load_file(path)
+ del sd["block.proj.weight"]
+
+ assert _tensors_share_one_mapping(sd, header, ["block.norm.weight", "block.proj.bias"])
+
+
+ "tensors",
+ [
+ {"w": torch.ones(4, 4, dtype=torch.bfloat16), "b": torch.zeros(4, dtype=torch.bfloat16)},
+ {"w": torch.ones(4, 4, dtype=torch.float16), "b": torch.zeros(4, dtype=torch.float32)},
+ {"w": torch.ones(4, 4, dtype=torch.int8), "w_scale": torch.tensor(0.25)},
+ # nvfp4: packed codes under `.weight`, block scales in float8 under `.weight_scale`. Nothing is widened.
+ {
+ "layer.weight": torch.zeros(8, 8, dtype=torch.uint8),
+ "layer.weight_scale": torch.ones(8, 1).to(torch.float8_e4m3fn),
+ "layer.weight_scale_2": torch.tensor(1.0),
+ },
+ {"scaled_fp8": torch.empty(0, dtype=torch.float8_e4m3fn), "layer.weight": torch.ones(4, 4)},
+ ],
+ ids=["bf16", "fp16+fp32", "int8+fp32 scale", "nvfp4", "scaled_fp8 marker only"],
+)
+def test_a_file_without_a_float8_weight_keeps_the_mmap_load(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, tensors: dict[str, torch.Tensor]
+) -> None:
+ path = _write(tmp_path / "plain.safetensors", tensors)
+
+ log = record_reads(monkeypatch)
+ sd = load_safetensors_checkpoint(path)
+
+ assert log.backends == ["mmap"]
+ assert _tensors_share_one_mapping(sd, read_safetensors_header(path), [k for k, v in sd.items() if v.numel()])
+
+
+def test_a_mixed_nvfp4_build_with_real_float8_weights_is_read_into_owned_storage(tmp_path: Path) -> None:
+ path = _write(
+ tmp_path / "mixed.safetensors",
+ {
+ "packed.weight": torch.zeros(8, 8, dtype=torch.uint8),
+ "packed.weight_scale": torch.ones(8, 1).to(torch.float8_e4m3fn),
+ "dense.weight": torch.ones(8, 8).to(torch.float8_e4m3fn),
+ "dense.weight_scale": torch.tensor(1.0),
+ },
+ )
+
+ assert safetensors_backend(path) == "pread"
+
+
+def test_a_torchao_fp8_build_is_read_into_owned_storage(tmp_path: Path) -> None:
+ """torchao stores its codes under `._weight_qdata`, not `.weight`. Mapped, its dense tensors pin the file whether
+ the codes are then folded or kept."""
+ path = _write(
+ tmp_path / "torchao.safetensors",
+ {
+ "block.norm.weight": _NORM,
+ "block.proj.bias": _BIAS,
+ "block.proj._weight_qdata": torch.ones(64, 64).to(torch.float8_e4m3fn),
+ "block.proj._weight_scale": torch.ones(64, 1),
+ },
+ )
+
+ sd = load_safetensors_checkpoint(path)
+
+ assert not _tensors_share_one_mapping(sd, read_safetensors_header(path), ["block.norm.weight", "block.proj.bias"])
+
+
[email protected]("dtype", FLOAT8, ids=["e4m3", "e5m2"])
+def test_both_paths_return_the_same_tensors(tmp_path: Path, dtype: torch.dtype) -> None:
+ path = _fp8_checkpoint(tmp_path / "fp8.safetensors", dtype)
+
+ owned = load_safetensors_checkpoint(path)
+ mapped = load_file(path)
+
+ assert owned.keys() == mapped.keys()
+ for key, tensor in mapped.items():
+ assert owned[key].dtype == tensor.dtype
+ assert owned[key].shape == tensor.shape
+ # Compared as bytes: float8 has no equality on CPU.
+ assert owned[key].reshape(-1).view(torch.uint8).equal(tensor.reshape(-1).view(torch.uint8))
+
+
+def test_tensors_the_selection_leaves_out_are_never_read(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ """Through ``pread`` a tensor that is read costs its size in process memory whether or not the loader keeps it, so
+ a bundled component is dropped by name, from the header."""
+ transformer = load_file(_fp8_checkpoint(tmp_path / "fp8.safetensors"))
+ path = _write(tmp_path / "bundle.safetensors", {"vae.decoder.weight": torch.ones(512, 512), **transformer})
+ log = record_reads(monkeypatch)
+
+ sd = load_safetensors_checkpoint(
+ path, select=lambda names: {k: v for k, v in names.items() if k.startswith("block.")}
+ )
+
+ assert set(sd) == set(transformer)
+ assert set(log.tensors) == set(transformer)
+ assert log.backends == ["pread"], "the file's float8 weight decides the backend, whatever is selected"
+
+
+def test_the_selection_sees_every_key_and_what_it_returns_names_the_keys_to_read(tmp_path: Path) -> None:
+ """A loader hands its own key rename and drop functions over: they return renamed keys, whose values still name
+ the file's tensors, and the result is keyed by the file's own names."""
+ path = _fp8_checkpoint(tmp_path / "fp8.safetensors")
+ offered: list[dict[str, str]] = []
+
+ def select(names: dict[str, str]) -> dict[str, str]:
+ offered.append(dict(names))
+ return {f"model.{key}": value for key, value in names.items() if key != "block.proj.bias"}
+
+ sd = load_safetensors_checkpoint(path, select=select)
+
+ assert offered == [{key: key for key in load_file(path)}]
+ assert sorted(sd) == sorted(key for key in load_file(path) if key != "block.proj.bias")
+
+
+def test_a_selection_naming_a_tensor_the_file_lacks_is_refused_by_name(tmp_path: Path) -> None:
+ path = _fp8_checkpoint(tmp_path / "fp8.safetensors")
+
+ with pytest.raises(ValueError, match=r"fp8\.safetensors has no tensor 'block\.missing'"):
+ load_safetensors_checkpoint(path, select=lambda names: {"x": "block.missing"})
+
+
+def test_an_owned_read_gives_a_file_without_float8_weights_storage_of_its_own(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A bf16 tower's cast to bf16 returns the tensor itself, so whatever it reads would stay a view of the file."""
+ path = _write(tmp_path / "bf16.safetensors", {"w": torch.ones(4, 4, dtype=torch.bfloat16), "b": _BIAS})
+ log = record_reads(monkeypatch)
+
+ sd = load_safetensors_checkpoint(path, owned=True)
+
+ assert log.backends == ["pread"]
+ assert not _tensors_share_one_mapping(sd, read_safetensors_header(path), ["w", "b"])
diff --git a/tests/backend/qwen3_5/test_qwen3_5_loading.py b/tests/backend/qwen3_5/test_qwen3_5_loading.py
index f4e2d7cbdf..5e59912ac8 100644
--- a/tests/backend/qwen3_5/test_qwen3_5_loading.py
+++ b/tests/backend/qwen3_5/test_qwen3_5_loading.py
@@ -373,6 +373,40 @@ def test_a_scaled_fp8_layer_is_refused_before_room_is_reserved(tmp_path: Path, l
loader._ram_cache.make_room.assert_not_called()
+def test_a_shard_with_float8_weights_is_read_into_owned_storage_and_a_plain_shard_stays_mapped(
+ tmp_path: Path, loader, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Anima-3.8B's encoder ships raw fp8: a view kept through the widening would pin its whole shard."""
+ weights = _reference(final_norm=False).state_dict()
+ fp8_keys = {key for key in weights if key.startswith("layers.0.") and key.endswith("proj.weight")}
+ assert fp8_keys
+ keys = sorted(weights)
+ first, second = keys[: len(keys) // 2], keys[len(keys) // 2 :]
+ fp8_shard, plain_shard = (
+ tmp_path / "model-00001-of-00002.safetensors",
+ tmp_path / "model-00002-of-00002.safetensors",
+ )
+ save_file({k: weights[k].to(torch.float8_e4m3fn) if k in fp8_keys else weights[k] for k in first}, fp8_shard)
+ save_file({k: weights[k] for k in second if k not in fp8_keys}, plain_shard)
+ assert fp8_keys <= set(first)
+
+ backends: dict[Path, str] = {}
+ real_safe_open = loader_module.safe_open
+
+ def recording_safe_open(path, **kwargs):
+ if "backend" in kwargs:
+ backends[Path(path)] = kwargs["backend"]
+ return real_safe_open(path, **kwargs)
+
+ monkeypatch.setattr(loader_module, "safe_open", recording_safe_open)
+
+ load_qwen3_5_text_encoder(
+ loader, [fp8_shard, plain_shard], _config(), final_norm=False, keep_fp8=False, what="test"
+ )
+
+ assert backends == {fp8_shard: "pread", plain_shard: "mmap"}
+
+
def test_the_bundled_tokenizer_is_not_sized_as_the_whole_file(tmp_path: Path, loader) -> None:
path = tmp_path / "encoder.safetensors"
save_file(_random({"language_model.embed_tokens.weight": [64, 32]}), path)
diff --git a/tests/fixtures/loader_seams.py b/tests/fixtures/loader_seams.py
index adae6cbd73..e4f918c9f8 100644
--- a/tests/fixtures/loader_seams.py
+++ b/tests/fixtures/loader_seams.py
@@ -34,6 +34,7 @@ import pytest
import torch
from invokeai.backend.util.devices import TorchDevice
+from tests.fixtures.safetensors_files import served_checkpoint
#: Distinguishes "do not touch `read_safetensors_metadata`" from "make it return nothing". Both are
#: real cases: a loader can be tested against a file whose header it really reads, and against that
@@ -49,9 +50,11 @@ class Seam:
#: Where the loader's ``from x import y`` names live, and so where a patch has to land.
module: ModuleType
entry: str = "_load_from_singlefile"
- #: Only for a loader that calls ``safetensors.torch.load_file`` through the package rather than
- #: importing the name. Patching the wrong host patches a name nobody reads, and the loader then
- #: quietly reads whatever file the config points at.
+ #: Only for a seam whose entry point makes a raw ``load_file`` read, beside or instead of the shared
+ #: ``load_safetensors_checkpoint`` helper (which is patched whenever ``module`` has it). It names where
+ #: that read resolves ``load_file``: ``safetensors.torch`` for a loader that imports the name inside the
+ #: method, the module itself for one that imports it at module level. Patching the wrong host patches a
+ #: name nobody reads, and the loader then quietly reads whatever file the config points at.
load_file_host: ModuleType | None = None
compute_dtype: torch.dtype = torch.float32
#: ``TorchDevice`` is one class shared by every loader module, so this is a switch rather than a
@@ -120,8 +123,8 @@ def prepare(
run = SeamRun(seam=seam, loader=None)
served: list[dict[str, torch.Tensor]] = []
- def load_file(_path):
- served.append(dict(state_dict or {}))
+ def load_file(_path, *, select=None, owned: bool = False):
+ served.append(served_checkpoint(dict(state_dict or {}))(_path, select=select, owned=owned))
return served[-1]
def make_room(reserve: int) -> None:
@@ -144,7 +147,11 @@ def prepare(
run.loader = loader
if state_dict is not None:
- monkeypatch.setattr(seam.load_file_host or seam.module, "load_file", load_file)
+ has_helper = hasattr(seam.module, "load_safetensors_checkpoint")
+ if has_helper:
+ monkeypatch.setattr(seam.module, "load_safetensors_checkpoint", load_file)
+ if seam.load_file_host is not None or not has_helper:
+ monkeypatch.setattr(seam.load_file_host or seam.module, "load_file", load_file)
if metadata is not UNSET:
header = dict(metadata) if metadata is not None else None
monkeypatch.setattr(seam.module, "read_safetensors_metadata", lambda _path, _logger: header)
diff --git a/tests/fixtures/safetensors_files.py b/tests/fixtures/safetensors_files.py
index 10b98e6a24..5a522922af 100644
--- a/tests/fixtures/safetensors_files.py
+++ b/tests/fixtures/safetensors_files.py
@@ -1,8 +1,11 @@
"""Probes on a safetensors file a loader has already read."""
import functools
+import itertools
import os
+import sys
import tempfile
+from collections.abc import Callable, Mapping
from pathlib import Path
import pytest
@@ -41,7 +44,98 @@ def mapping_shows_file_writes() -> bool:
return changed
+#: Only the macOS runners keep the bytes a tensor was mapped with. Anywhere else a probe that cannot tell a view from
+#: a copy is a broken test environment, which `tensors_reading_the_file` reports instead of passing silently.
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",
+ sys.platform == "darwin",
+ reason="safetensors' mapping does not show in-place writes on macOS, so overwrite_payloads can't tell a view from a copy",
)
+
+
+def tensors_reading_the_file(source: torch.nn.Module | Mapping[str, torch.Tensor], path: Path) -> list[str]:
+ """The tensors of ``source`` that are still views of ``path``'s mapping, by `overwrite_payloads`.
+
+ ``source`` is a loaded state dict, or a module, whose parameters and buffers are checked: each one that is a view
+ pins the whole file for as long as the model is cached, outside the cache's size calculation. Bytes are
+ compared, so a float8 tensor, which `torch.equal` cannot compare on CPU, is checked like any other. Not
+ `state_dict()`: it leaves out non-persistent buffers, and the scales of kept fp8 layers are registered as those.
+ """
+ assert mapping_shows_file_writes(), "a mapped tensor does not show a write to its file here, so this finds nothing"
+
+ def as_bytes() -> dict[str, torch.Tensor]:
+ if isinstance(source, torch.nn.Module):
+ tensors = itertools.chain(
+ source.named_parameters(remove_duplicate=False), source.named_buffers(remove_duplicate=False)
+ )
+ else:
+ tensors = iter(source.items())
+ return {name: tensor.detach().contiguous().reshape(-1).view(torch.uint8).clone() for name, tensor in tensors}
+
+ before = as_bytes()
+ overwrite_payloads(path)
+ after = as_bytes()
+ return [name for name in before if not torch.equal(before[name], after[name])]
+
+
+def served_checkpoint(state_dict: Mapping[str, torch.Tensor]) -> Callable[..., dict[str, torch.Tensor]]:
+ """A stand-in for `load_safetensors_checkpoint` that serves ``state_dict`` without a file.
+
+ It applies ``select`` the way the real reader does, to the keys alone, so a loader's drops are exercised and
+ the tensors it never selects are never handed over.
+ """
+
+ def load(_path, *, select=None, owned: bool = False) -> dict[str, torch.Tensor]:
+ if select is None:
+ return state_dict # type: ignore[return-value] # the very dict, as a loader that clears it is tested on
+ return {key: state_dict[key] for key in select({key: key for key in state_dict}).values()}
+
+ return load
+
+
+class ReadLog:
+ """What `record_reads` saw: the tensors each ``get_tensor`` returned, and the ``backend`` each open asked for."""
+
+ def __init__(self) -> None:
+ self.tensors: dict[str, torch.Tensor] = {}
+ self.backends: list[str] = []
+ #: ``("open", backend)`` and ``("read", key)`` in the order they happened, for ordering assertions.
+ self.events: list[tuple[str, str]] = []
+
+
+def record_reads(monkeypatch: pytest.MonkeyPatch) -> ReadLog:
+ """Record every tensor read through ``safetensors.safe_open``, which is how the loaders read a checkpoint.
+
+ The handle is the real one, so the loader gets what it would have got; only its ``get_tensor`` is watched.
+ It patches the ``safetensors`` package attribute, so it sees only code that imports ``safe_open`` when it runs,
+ as `load_safetensors_checkpoint` does. A module that imports it at module level (`moss_image.py`,
+ `qwen3_5_encoder.py`) keeps the original and is not recorded.
+ """
+ log = ReadLog()
+
+ class _Handle:
+ def __init__(self, handle) -> None:
+ self._handle = handle
+
+ def get_tensor(self, key: str) -> torch.Tensor:
+ tensor = self._handle.get_tensor(key)
+ log.tensors[key] = tensor
+ log.events.append(("read", key))
+ return tensor
+
+ def __getattr__(self, name: str):
+ return getattr(self._handle, name)
+
+ class _Open:
+ def __init__(self, *args, **kwargs) -> None:
+ self._cm = safe_open(*args, **kwargs)
+ log.backends.append(kwargs.get("backend", "mmap"))
+ log.events.append(("open", log.backends[-1]))
+
+ def __enter__(self) -> _Handle:
+ return _Handle(self._cm.__enter__())
+
+ def __exit__(self, *exc) -> object:
+ return self._cm.__exit__(*exc)
+
+ monkeypatch.setattr("safetensors.safe_open", _Open)
+ return log