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.

Merge remote-tracking branch 'origin/main' into feat/fp8-storage-keeps-scaled

Alexander Eichhorna4c1739a29f9
diff --cc invokeai/backend/model_manager/load/model_loaders/anima.py
index da2575eeb6,faf8632df2..6831065643
--- a/invokeai/backend/model_manager/load/model_loaders/anima.py
+++ b/invokeai/backend/model_manager/load/model_loaders/anima.py
@@@ -225,29 -227,21 +226,25 @@@ class AnimaCheckpointModel(ModelLoader)
kept = cast_state_dict(sd, model_dtype, keep_fp8=keep_fp8, model=model, skip_patterns=skip_patterns)
load_result = model.load_state_dict(sd, assign=True, strict=False)
- if load_result.unexpected_keys:
- raise RuntimeError(
- f"Checkpoint contains {len(load_result.unexpected_keys)} unexpected keys. "
- f"This may indicate a corrupted or incompatible checkpoint. "
- f"First 5 unexpected keys: {load_result.unexpected_keys[:5]}"
- )
- if load_result.missing_keys:
- logger.warning(
- f"Checkpoint is missing {len(load_result.missing_keys)} keys "
- f"(expected for inv_freq buffers). First 5: {load_result.missing_keys[:5]}"
- )
+ log_unexpected_keys("Anima transformer checkpoint", load_result.unexpected_keys)
+ # `missing_keys` alone cannot police completeness here: AnimaTransformer's only three buffers
+ # are registered `persistent=False`, so they never appear in it (the old warning claiming
+ # otherwise was misleading). Sweep for tensors the checkpoint left on the meta device instead
+ # — that is the failure worth catching, and it is what the removed unexpected-key
+ # `RuntimeError` was really standing in for.
+ reject_incomplete_load(model, what="Anima transformer checkpoint")
- # Without this the `fp8_storage` toggle is shown for Anima models but does nothing. The
- # state dict was cast to a single `model_dtype` above, so the layerwise cast has one
- # unambiguous compute dtype to restore to. AnimaTransformer is a plain nn.Module, so this
- # takes the hook-based path in `_apply_fp8_to_nn_module`.
+ # Without this the `fp8_storage` toggle is shown for Anima models but does nothing. When
+ # nothing stayed packed, the state dict was cast to a single `model_dtype` above, so the
+ # layerwise cast has one unambiguous compute dtype to restore to; when something did stay
+ # packed, the cast bails out on its own rather than upcast a scaled weight without applying
+ # its scale. AnimaTransformer is a plain nn.Module, so this takes the hook-based path in
+ # `_apply_fp8_to_nn_module`.
if fp8_layers:
attached = attach_fp8_scales(model, fp8_layers)
- logger.info(f"Anima: kept {attached} layer(s) in fp8 (scaled fp8 checkpoint, fp8_compute enabled)")
+ logger.info(
+ f"Anima: kept {attached} layer(s) in fp8 (scaled fp8 checkpoint, kept for {self._fp8_kept_reason()})"
+ )
warn_on_unattached_scales(logger, "Anima", attached, fp8_layers)
marked = sum(1 for layer in fp8_layers.values() if layer.full_precision_matmul)
if marked and full_precision_hints_respected():
diff --cc invokeai/backend/model_manager/load/model_loaders/mistral_encoder.py
index 9cb9fc3fad,7096e54695..63352027d3
--- a/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.py
+++ b/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.py
@@@ -27,7 -28,7 +28,11 @@@ from invokeai.backend.model_manager.con
MistralEncoder_Diffusers_Config,
MistralEncoder_GGUF_Config,
)
- from invokeai.backend.model_manager.load.load_default import ModelLoader, _device_supports_fp8_storage
-from invokeai.backend.model_manager.load.load_default import ModelLoader, _model_declared_skip_patterns
++from invokeai.backend.model_manager.load.load_default import (
++ ModelLoader,
++ _device_supports_fp8_storage,
++ _model_declared_skip_patterns,
++)
from invokeai.backend.model_manager.load.model_loader_registry import ModelLoaderRegistry
from invokeai.backend.model_manager.taxonomy import (
AnyModel,
@@@ -952,38 -988,13 +992,20 @@@ class MistralEncoderCheckpointLoader(Mo
# Both key rewrites in this loader (`_strip_known_prefixes` above and
# `_convert_for_bare_mistral_model` below) are plain prefix operations, so a sibling
# `.weight_scale` travels with its weight automatically -- no fused projections to split.
- keep_fp8 = should_keep_fp8_weights(target_device)
+ # Storage keeps them too, gated on the device alone: `_should_use_fp8` excludes text encoders
+ # by design (fp8 rounding costs text quality), so there is no per-model setting to read here.
+ # Folding is the fallback only where fp8 cannot be held at all, and folding is what hurts
+ # here: 16.8 GiB on disk becomes 32.3 GiB resident. Note what that makes this -- on CUDA the
+ # device check is always true, so the choice is unconditional and has no user setting behind
+ # it. This loader never calls the layerwise cast (text encoders are excluded there), so the
+ # kept weights reach `CustomLinear` with their scales intact.
+ keep_fp8 = should_keep_fp8_weights(target_device) or _device_supports_fp8_storage(target_device, logger)
fp8_layers: dict[str, Any] = {}
if keep_fp8:
- # This loader strips its own wrapper prefixes on top of the generic ones, so the hints
- # need both lists. With only the generic tuple, a `language_model.`-prefixed
- # redistribution keeps its hint names while the sd keys lose the prefix, and every
- # `full_precision_matrix_mult` is silently ignored.
- header_hints = strip_layer_path_prefix(
- parse_quantization_metadata(read_safetensors_metadata(model_path, logger)),
- prefixes=(*MISTRAL_KEY_PREFIXES, *TRANSFORMER_KEY_PREFIXES),
- )
layer_hints = {**extract_comfy_quant_hints(sd), **header_hints}
fp8_layers = extract_fp8_scaled_layers(sd, layer_hints=layer_hints)
- if not fp8_layers:
- # Dequantize straight to the compute dtype (per-tensor peak, not whole-dict fp32).
- sd = _drop_quantization_metadata(sd, logger, target_dtype=model_dtype)
- else:
- # `extract_fp8_scaled_layers` removes the keys it interprets, but this producer also
- # emits `.scale` and `scaled_fp8*`, which it does not recognize. On the dequantizing
- # path `_drop_quantization_metadata` takes those; here nothing did, so they reached
- # `load_state_dict` and padded the "ignored N unexpected keys" line.
- for k in [k for k in sd if isinstance(k, str) and (k.endswith(".scale") or k.startswith("scaled_fp8"))]:
- del sd[k]
- mistral_config = _build_mistral_config(sd, torch_dtype=model_dtype)
+ mistral_config = _build_mistral_config(sd, torch_dtype=model_dtype, packed_layers=nvfp4_payloads)
logger.info(
f"Mistral encoder config (checkpoint): layers={mistral_config.num_hidden_layers}, "
f"hidden={mistral_config.hidden_size}, heads={mistral_config.num_attention_heads}, "
diff --cc invokeai/backend/model_manager/load/model_loaders/z_image.py
index 44fb8feb21,3ab7aefc8f..786dbd4d54
--- a/invokeai/backend/model_manager/load/model_loaders/z_image.py
+++ b/invokeai/backend/model_manager/load/model_loaders/z_image.py
@@@ -602,29 -636,19 +635,23 @@@ class ZImageCheckpointModel(ModelLoader
layer_hints = {**extract_comfy_quant_hints(sd), **header_hints}
fp8_layers = extract_fp8_scaled_layers(sd, layer_hints=layer_hints)
- # Handle memory management and dtype conversion. A checkpoint that ships raw fp8 weights
- # (fp8 tensors, no weight_scale) keeps them when the fp8 matmul is available — casting
- # them here would discard both the VRAM saving and the tensor cores before the model is
- # built.
- keep_fp8 = should_keep_fp8_weights(self._torch_device)
+ # Handle memory management and dtype conversion. Casting fp8 weights here would discard
+ # the VRAM saving before the model is even built -- and the tensor cores too, where the
- # fp8 matmul is what kept them.
++ # fp8 matmul is what kept them. FP8 Storage counts as a consumer alongside the matmul:
++ # the checkpoint's own scale is exact, where a layerwise cast of a folded weight has none.
++ #
++ # The fold itself stays below the reservation rather than moving up here: the prediction
++ # takes `scaled_layers=fp8_layers` and would see an empty mapping, charging the layers the
++ # split still widens 1 byte/element instead of 2.
+ keep_fp8 = self._keep_fp8_weights(config, SubModelType.Transformer)
- if fp8_layers and not keep_fp8:
- # Neither consumer asked for them, and dequantizing per forward would cost speed for
- # memory nobody wanted saved: fold the scale into the weight.
- dequantize_fp8_scaled(sd, fp8_layers, model_dtype)
- fp8_layers = {}
- # Honor the model's own precision-sensitive list. Z-Image declares
- # ["t_embedder", "cap_embedder"], and `TimestepEmbedder.forward` casts its activations to
- # `self.mlp[0].weight.dtype` — an fp8 weight there turns the activations fp8 and the
- # forward dies in `x.abs()`. Those layers must be dequantized even though the rest stays
- # quantized.
- skip_patterns = _model_declared_skip_patterns(model)
- # Scaled layers that the cast would dequantize anyway are folded here, scale applied, so
- # `cast_state_dict` never strips a scale it cannot put back.
- # Reserve before the split, not after: `split_fp8_scaled_layers` dequantizes its unusable
- # subset through fp32, so reserving afterwards lets that transient peak land on an
- # unreserved cache. `scaled_layers` is what keeps that honest: the split also widens
- # layers whose scale layout `scaled_mm` cannot apply, and without the mapping the
- # prediction would charge those 1 byte/element and arrive at 2.
+ # Reserve before anything below widens a weight, not after: without fp8 compute the fold right
+ # after this widens every scaled layer, and `split_fp8_scaled_layers` dequantizes its unusable
+ # subset through fp32 -- reserving afterwards lets either peak land on an unreserved cache.
+ # Without fp8 compute the prediction charges every float at `model_dtype`, folded yet or not.
+ # With it, `scaled_layers` is what keeps the prediction honest: the split also widens layers
+ # whose scale layout `scaled_mm` cannot apply, and without the mapping the prediction would
+ # charge those 1 byte/element and arrive at 2.
self._ram_cache.make_room(
predict_cast_state_dict_size(
sd,
diff --cc tests/backend/model_manager/load/test_z_image_loader_boundaries.py
index 6952a3f88b,a372e8a26e..aaad7f7dd4
--- a/tests/backend/model_manager/load/test_z_image_loader_boundaries.py
+++ b/tests/backend/model_manager/load/test_z_image_loader_boundaries.py
@@@ -13,11 -13,10 +13,12 @@@ from unittest.mock import MagicMoc
import pytest
import torch
+from invokeai.backend.model_manager.configs.default_settings import MainModelDefaultSettings
from invokeai.backend.model_manager.configs.main import Main_Checkpoint_ZImage_Config
+from invokeai.backend.model_manager.load import load_default
from invokeai.backend.model_manager.load.model_loaders.z_image import ZImageCheckpointModel
from invokeai.backend.quantization.int8_convrot import CONVROT_GROUP_SIZE, Int8ConvrotLinear, build_regular_hadamard
+ from invokeai.backend.quantization.nvfp4 import NVFP4Linear
MARKER = {"format": "int8_tensorwise", "convrot": True, "convrot_groupsize": CONVROT_GROUP_SIZE}
@@@ -187,34 -186,126 +188,159 @@@ def test_a_precision_sensitive_layer_is
assert reserved >= sensitive.nelement() * 4 + ordinary_q.nelement()
+ class _TinyAttention(torch.nn.Module):
+ def __init__(self) -> None:
+ super().__init__()
+ self.to_q = torch.nn.Linear(64, 128, bias=False)
+ self.to_k = torch.nn.Linear(64, 128, bias=False)
+ self.to_v = torch.nn.Linear(64, 128, bias=False)
+
+
+ class _TinyNativeBlock(torch.nn.Module):
+ def __init__(self) -> None:
+ super().__init__()
+ self.attention = _TinyAttention()
+ self.adaLN_modulation = torch.nn.Sequential(torch.nn.Linear(64, 128))
+
+
+ class _TinyNvfp4TimestepEmbedder(torch.nn.Module):
+ def __init__(self) -> None:
+ super().__init__()
+ self.mlp = torch.nn.ModuleList([torch.nn.Linear(64, 128, bias=False)])
+
+
+ class _TinyNativeZImage(torch.nn.Module):
+ """What the native-to-diffusers conversion makes of a checkpoint with a fused `attention.qkv`, beside the
+ timestep embedder Z-Image declares precision-sensitive."""
+
+ _skip_layerwise_casting_patterns = ["t_embedder", "cap_embedder"]
+
+ def __init__(self, **_kwargs) -> None:
+ super().__init__()
+ self.all_x_embedder = torch.nn.ModuleDict({"2-1": torch.nn.Linear(4, 4, bias=False)})
+ self.t_embedder = _TinyNvfp4TimestepEmbedder()
+ self.layers = torch.nn.ModuleList([_TinyNativeBlock()])
+
+
+ def _nvfp4_layer(
+ path: str, positive: torch.Tensor, tile_row_scales: list[float], global_scale: float
+ ) -> dict[str, torch.Tensor]:
+ """One layer as Comfy stores it. Codes 2 and 10 decode to +1.0 and -1.0, so the expected weight needs no
+ E2M1 table, and a block scale constant over each 128-row tile row reads the same tiled as row by row."""
+ codes = torch.where(positive, 2, 10).to(torch.uint8)
+ scales = torch.tensor(tile_row_scales).repeat_interleave(128).unsqueeze(1).repeat(1, positive.shape[1] // 16)
+ return {
+ f"{path}.weight": (codes[:, 0::2] << 4) | codes[:, 1::2],
+ f"{path}.weight_scale": scales.to(torch.float8_e4m3fn),
+ f"{path}.weight_scale_2": torch.tensor(global_scale),
+ }
+
+
+ def test_an_nvfp4_checkpoint_loads_packed_with_its_qkv_split_on_tile_rows(monkeypatch, tmp_path) -> None:
+ """Comfy's nvfp4 Z-Image build quantizes the fused `attention.qkv` and names its layers only in the
+ safetensors header. The packed tensors have to leave the state dict before the key conversion and the
+ scaled-fp8 extraction -- which drops block scales whose weight is not float8 -- follow the QKV split on
+ whole tile rows, and come back as `NVFP4Linear` modules for the strict load. The timestep embedder is
+ decoded to the compute dtype instead, since its forward picks its activation dtype off its weight, and a
+ bundled encoder's layers are dropped with everything else the transformer does not hold."""
+ torch.manual_seed(4)
+ qkv, modulation, timestep, bundled = (
+ torch.randint(0, 2, (rows, 64), dtype=torch.bool) for rows in (384, 128, 128, 128)
+ )
+ modulation_bias = torch.randn(128)
+ embedder = torch.randn(4, 4)
+ state_dict = {
+ "x_embedder.weight": embedder,
+ **_nvfp4_layer("layers.0.attention.qkv", qkv, [1.0, 2.0, 4.0], global_scale=0.5),
+ "layers.0.attention.qkv.input_scale": torch.tensor(1.0),
+ **_nvfp4_layer("layers.0.adaLN_modulation.0", modulation, [2.0], global_scale=0.25),
+ "layers.0.adaLN_modulation.0.bias": modulation_bias,
+ **_nvfp4_layer("t_embedder.mlp.0", timestep, [2.0], global_scale=0.25),
+ **_nvfp4_layer("text_encoders.qwen3.layers.0.mlp.up_proj", bundled, [2.0], global_scale=0.25),
+ }
+ header = {
+ path: {"format": "nvfp4"}
+ for path in (
+ "layers.0.attention.qkv",
+ "layers.0.adaLN_modulation.0",
+ "t_embedder.mlp.0",
+ "text_encoders.qwen3.layers.0.mlp.up_proj",
+ )
+ }
+ loader, config = _driver(monkeypatch, tmp_path, state_dict)
+ import diffusers
+
+ monkeypatch.setattr(diffusers, "ZImageTransformer2DModel", _TinyNativeZImage, raising=False)
+ monkeypatch.setattr(
+ "invokeai.backend.model_manager.load.model_loaders.z_image.read_safetensors_metadata",
+ lambda _path, _logger: {"_quantization_metadata": json.dumps({"layers": header})},
+ )
+ # bf16 rather than the driver's float32, so a layer decoded or charged at any other width shows.
+ monkeypatch.setattr(
+ "invokeai.backend.model_manager.load.model_loaders.z_image.TorchDevice.choose_bfloat16_safe_dtype",
+ lambda _device: torch.bfloat16,
+ )
+
+ model = loader._load_from_singlefile(config)
+
+ bf16 = torch.bfloat16
+ x = torch.randn(3, 64, dtype=bf16)
+ attention = model.layers[0].attention
+ for projection, signs, magnitude in (
+ (attention.to_q, qkv[:128], 0.5),
+ (attention.to_k, qkv[128:256], 1.0),
+ (attention.to_v, qkv[256:], 2.0),
+ ):
+ assert isinstance(projection, NVFP4Linear)
+ assert projection.weight.dtype is torch.uint8
+ expected = torch.where(signs, magnitude, -magnitude).to(bf16)
+ assert torch.equal(projection(x), torch.nn.functional.linear(x, expected))
+ adaln = model.layers[0].adaLN_modulation[0]
+ assert isinstance(adaln, NVFP4Linear)
+ expected = torch.nn.functional.linear(x, torch.where(modulation, 0.5, -0.5).to(bf16), modulation_bias.to(bf16))
+ assert torch.equal(adaln(x), expected)
+ assert type(model.t_embedder.mlp[0]) is torch.nn.Linear
+ assert torch.equal(model.t_embedder.mlp[0].weight, torch.where(timestep, 0.5, -0.5).to(bf16))
+ assert torch.equal(model.all_x_embedder["2-1"].weight, embedder.to(bf16))
+
+ # One reservation for what the model ends up holding: the packed tensors as stored, and the decoded embedder
+ # and the dense rest at two bytes. Not the bundled layer, and not the packed layers at their decoded size,
+ # which would ask for about 45 KB more.
+ packed = (384 + 128) * 32 + (384 + 128) * 4
+ dense = 128 * 64 * 2 + 128 * 2 + 4 * 4 * 2
+ loader._ram_cache.make_room.assert_called_once()
+ (reserved,), _ = loader._ram_cache.make_room.call_args
+ assert packed + dense <= reserved < packed + dense + 1024
++
++
+def test_a_scaled_fp8_checkpoint_stays_packed_when_storage_is_on(monkeypatch, tmp_path) -> None:
+ """The keep decision has to reach the loader, not only the helper it was extracted into.
+
+ With FP8 Storage on, the checkpoint's own scaled fp8 weights are kept rather than folded into
+ bf16 and re-quantized by the layerwise cast, which has no scale to apply. A loader that goes
+ back to asking only about the fp8 matmul folds them again -- silently, and precisely on the
+ hardware most users have, since `fp8_compute` is off by default.
+ """
+ torch.manual_seed(3)
+ original = torch.randn(4, CONVROT_GROUP_SIZE)
+ scale = (original.abs().max() / 448.0).to(torch.float32)
+ packed = (original / scale).to(torch.float8_e4m3fn)
+ state_dict = {"layers.0.proj.weight": packed, "layers.0.proj.weight_scale": scale}
+
+ loader, driver_config = _driver(monkeypatch, tmp_path, state_dict)
+ config = Main_Checkpoint_ZImage_Config.model_construct(
+ path=driver_config.path,
+ name="z-image",
+ default_settings=MainModelDefaultSettings(fp8_storage=True),
+ )
+ # The configuration this path exists for: no fp8 matmul, but a device that can hold fp8.
+ monkeypatch.setattr(load_default, "should_keep_fp8_weights", lambda _device: False)
+ monkeypatch.setattr(load_default, "_device_supports_fp8_storage", lambda _device, _logger=None: True)
+
+ model = loader._load_from_singlefile(config)
+
+ proj = model.layers[0].proj
+ assert proj.weight.dtype is torch.float8_e4m3fn, "folded back to a float dtype"
+ assert getattr(proj, "weight_scale", None) is not None, "kept packed but without its scale"
+ dequantized = (proj.weight.float() * proj.weight_scale).flatten()
+ assert torch.corrcoef(torch.stack([dequantized, original.flatten()]))[0, 1] > 0.999