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.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
fix(models): keep scaled fp8 weights packed when FP8 Storage is on
Alexander Eichhorn2463383af810
diff --git a/invokeai/backend/model_manager/load/load_default.py b/invokeai/backend/model_manager/load/load_default.pyindex 276c67726d..d2e83df6b7 100644--- a/invokeai/backend/model_manager/load/load_default.py+++ b/invokeai/backend/model_manager/load/load_default.py@@ -485,6 +485,23 @@ class ModelLoader(ModelLoaderBase):return False+ def _keep_fp8_weights(self, config: AnyModelConfig, submodel_type: Optional[SubModelType] = None) -> bool:+ """Whether a checkpoint's fp8 weights should stay packed rather than be folded into bf16.++ Two consumers want them packed, and either is enough:++ - the fp8 matmul (`fp8_compute`), which runs on them directly;+ - FP8 Storage asked of this model, because the checkpoint's own per-tensor scale is exact+ while the layerwise cast of a *folded* weight has no scale at all and rounds to unscaled+ fp8 -- measured on FLUX.2 Klein 4B, that loses ~3% of the weights to underflow for the+ same one byte per weight.++ With neither, folding is right: staying packed would dequantize on every forward, spending+ speed to save memory nobody asked to save. `_should_use_fp8` already requires the device to+ support fp8 storage, so an unsupported device keeps the folding path.+ """+ return should_keep_fp8_weights(self._torch_device) or self._should_use_fp8(config, submodel_type)+def _apply_fp8_layerwise_casting(self, model: AnyModel, config: AnyModelConfig, submodel_type: Optional[SubModelType] = None) -> AnyModel:diff --git a/invokeai/backend/model_manager/load/model_loaders/anima.py b/invokeai/backend/model_manager/load/model_loaders/anima.pyindex 9af0d2c24c..71e91e7efd 100644--- a/invokeai/backend/model_manager/load/model_loaders/anima.py+++ b/invokeai/backend/model_manager/load/model_loaders/anima.py@@ -29,7 +29,6 @@ from invokeai.backend.quantization.fp8_scaled import (parse_quantization_metadata,predict_cast_state_dict_size,read_safetensors_metadata,- should_keep_fp8_weights,split_fp8_scaled_layers,strip_layer_path_prefix,warn_on_unattached_scales,@@ -182,7 +181,7 @@ class AnimaCheckpointModel(ModelLoader):## Anima keeps `q_proj`/`k_proj`/`v_proj` separate and the only key rewrite is a prefix strip,# so a sibling scale travels with its weight and nothing has to be split.- keep_fp8 = should_keep_fp8_weights(target_device)+ keep_fp8 = self._keep_fp8_weights(config, SubModelType.Transformer)header_hints = parse_quantization_metadata(read_safetensors_metadata(model_path, logger))# The header names layers in the checkpoint's own scheme -- `net.`-prefixed on every Anima# redistribution measured -- while the scales are read after `_strip_anima_bundle_prefix`diff --git a/invokeai/backend/model_manager/load/model_loaders/flux.py b/invokeai/backend/model_manager/load/model_loaders/flux.pyindex 7e1dfc9a8a..2708b0228e 100644--- a/invokeai/backend/model_manager/load/model_loaders/flux.py+++ b/invokeai/backend/model_manager/load/model_loaders/flux.py@@ -98,7 +98,6 @@ from invokeai.backend.quantization.fp8_scaled import (parse_quantization_metadata,predict_cast_state_dict_size,read_safetensors_metadata,- should_keep_fp8_weights,split_fp8_scaled_layers,strip_layer_path_prefix,warn_on_unattached_scales,@@ -760,14 +759,13 @@ class FluxCheckpointModel(ModelLoader):}fp8_layers = extract_fp8_scaled_layers(sd, layer_hints=layer_hints)- # A checkpoint that ships raw fp8 weights (fp8 tensors, no weight_scale) keeps them when the- # fp8 matmul is available; casting them to bf16 here would throw away both the VRAM saving- # and the tensor cores before the model is ever built.- keep_fp8 = should_keep_fp8_weights(self._torch_device)+ # 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.+ keep_fp8 = self._keep_fp8_weights(config, SubModelType.Transformer)if fp8_layers and not keep_fp8:- # Without the matmul, keeping them quantized would halve VRAM but dequantize on every- # forward. Fold the scale into the weight instead — the legacy result, except the scale- # is now actually applied rather than dropped.+ # Neither consumer asked for them, and dequantizing per forward would cost speed for+ # memory nobody wanted saved. Fold the scale into the weight instead — the legacy+ # result, except the scale is now actually applied rather than dropped.dequantize_fp8_scaled(sd, fp8_layers, torch.bfloat16)fp8_layers = {}@@ -1057,7 +1055,9 @@ class Flux2CheckpointModel(ModelLoader):# Load state dictsd = load_file(model_path)- keep_fp8 = should_keep_fp8_weights(self._torch_device)+ # 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.+ keep_fp8 = self._keep_fp8_weights(config, SubModelType.Transformer)# Check if keys have ComfyUI-style prefix and strip if needed. This runs before anything# reads the quantization side-channel: the scales carry the same prefix as their weights.diff --git a/invokeai/backend/model_manager/load/model_loaders/krea2.py b/invokeai/backend/model_manager/load/model_loaders/krea2.pyindex 96ea1a0c70..e252d00b70 100644--- a/invokeai/backend/model_manager/load/model_loaders/krea2.py+++ b/invokeai/backend/model_manager/load/model_loaders/krea2.py@@ -455,10 +455,10 @@ class Krea2CheckpointModel(ModelLoader):# ComfyUI 'scaled fp8' checkpoints (fp8 weight + .weight_scale, optionally .input_scale).fp8_layers = extract_fp8_scaled_layers(sd, layer_hints=layer_hints)- keep_fp8 = should_keep_fp8_weights(target_device)+ keep_fp8 = self._keep_fp8_weights(config, SubModelType.Transformer)if fp8_layers and not keep_fp8:- # Legacy behavior: fold the scales into the weights. Keeping them quantized without the- # fp8 matmul would halve VRAM but run slower, so both are tied to the same setting.+ # Neither consumer asked for them: keeping them quantized would halve VRAM but+ # dequantize on every forward, so fold the scales into the weights.dequantize_fp8_scaled(sd, fp8_layers, model_dtype)fp8_layers = {}diff --git a/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.py b/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.pyindex d751a209e6..7ffd212935 100644--- a/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.py+++ b/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.py@@ -27,7 +27,7 @@ from invokeai.backend.model_manager.configs.mistral_encoder import (MistralEncoder_Diffusers_Config,MistralEncoder_GGUF_Config,)-from invokeai.backend.model_manager.load.load_default import ModelLoader+from invokeai.backend.model_manager.load.load_default import ModelLoader, _device_supports_fp8_storagefrom invokeai.backend.model_manager.load.model_loader_registry import ModelLoaderRegistryfrom invokeai.backend.model_manager.taxonomy import (AnyModel,@@ -952,7 +952,11 @@ class MistralEncoderCheckpointLoader(ModelLoader):# 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.+ # This mirrors the Qwen3-VL encoder in the Krea-2 loader. Folding stays the fallback only+ # where fp8 cannot be held at all.+ 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 hintsdiff --git a/invokeai/backend/model_manager/load/model_loaders/z_image.py b/invokeai/backend/model_manager/load/model_loaders/z_image.pyindex d008478129..c45df80b3f 100644--- a/invokeai/backend/model_manager/load/model_loaders/z_image.py+++ b/invokeai/backend/model_manager/load/model_loaders/z_image.py@@ -52,7 +52,6 @@ from invokeai.backend.quantization.fp8_scaled import (parse_quantization_metadata,predict_cast_state_dict_size,read_safetensors_metadata,- should_keep_fp8_weights,split_fp8_scaled_layers,split_qkv_sidechannel,strip_layer_path_prefix,@@ -603,13 +602,12 @@ 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+ # both the VRAM saving and the tensor cores before the model is even built.+ keep_fp8 = self._keep_fp8_weights(config, SubModelType.Transformer)if fp8_layers and not keep_fp8:- # Legacy behavior, but now with the scale actually applied: fold it into the weight.+ # 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 = {}diff --git a/tests/backend/model_manager/load/test_anima_fp8_wiring.py b/tests/backend/model_manager/load/test_anima_fp8_wiring.pyindex 7bcdda873c..485e96dbb6 100644--- a/tests/backend/model_manager/load/test_anima_fp8_wiring.py+++ b/tests/backend/model_manager/load/test_anima_fp8_wiring.py@@ -139,6 +139,10 @@ def test_single_file_loader_applies_fp8_layerwise_casting(monkeypatch, tmp_path)loader = object.__new__(AnimaCheckpointModel)loader._ram_cache = SimpleNamespace(make_room=MagicMock())loader._apply_fp8_layerwise_casting = _record_cast+ # The real loader gets both from `ModelLoader.__init__`; `_keep_fp8_weights` reads them to ask+ # whether this device can hold fp8 at all.+ loader._torch_device = torch.device("cpu")+ loader._logger = MagicMock()model = loader._load_from_singlefile(config)diff --git a/tests/backend/model_manager/load/test_keep_fp8_weights.py b/tests/backend/model_manager/load/test_keep_fp8_weights.pynew file mode 100644index 0000000000..291501d6d2--- /dev/null+++ b/tests/backend/model_manager/load/test_keep_fp8_weights.py@@ -0,0 +1,77 @@+"""Whether a checkpoint's fp8 weights stay packed or get folded into bf16.++Two independent consumers want them packed: the fp8 matmul, and FP8 Storage. The decision used to+live in five loaders and asked only about the matmul, so a model with FP8 Storage on had its scales+folded in and the result re-quantized by the layerwise cast -- to *unscaled* fp8, which has no scale+to apply. Measured on FLUX.2 Klein 4B that loses ~3% of the weights to underflow, for exactly the+byte count the file already had.+"""++from unittest.mock import MagicMock++import pytest+import torch++from invokeai.backend.model_manager.configs.default_settings import MainModelDefaultSettings+from invokeai.backend.model_manager.configs.main import Main_Checkpoint_FLUX_Config+from invokeai.backend.model_manager.load import load_default+from invokeai.backend.model_manager.load.load_default import ModelLoader+from invokeai.backend.model_manager.taxonomy import SubModelType+++def _loader() -> ModelLoader:+ loader = object.__new__(ModelLoader)+ loader._torch_device = torch.device("cuda")+ loader._logger = MagicMock()+ return loader+++def _config(fp8_storage: bool | None) -> Main_Checkpoint_FLUX_Config:+ return Main_Checkpoint_FLUX_Config.model_construct(+ path="transformer.safetensors",+ default_settings=MainModelDefaultSettings(fp8_storage=fp8_storage),+ )+++ "matmul, fp8_storage, device_supports_storage, expected",+ [+ # The matmul runs on fp8 weights directly; it never needs the setting.+ (True, None, False, True),+ # The case this exists for: storage asked of the model, so the file's own exact scale is+ # kept rather than folded and re-rounded without one.+ (False, True, True, True),+ # Nobody asked: folding is right, because staying packed would dequantize per forward.+ (False, None, True, False),+ # Device capability decides first -- a device that cannot hold fp8 gets the folded path+ # however the model is configured.+ (False, True, False, False),+ ],+)+def test_fp8_weights_are_kept_for_either_consumer(+ monkeypatch: pytest.MonkeyPatch,+ matmul: bool,+ fp8_storage: bool | None,+ device_supports_storage: bool,+ expected: bool,+) -> None:+ monkeypatch.setattr(load_default, "should_keep_fp8_weights", lambda _device: matmul)+ monkeypatch.setattr(+ load_default, "_device_supports_fp8_storage", lambda _device, _logger=None: device_supports_storage+ )++ kept = _loader()._keep_fp8_weights(_config(fp8_storage), SubModelType.Transformer)++ assert kept is expected+++def test_a_text_encoder_submodel_never_keeps_them_for_storage(monkeypatch: pytest.MonkeyPatch) -> None:+ """FP8 Storage excludes text encoders by design -- fp8 rounding costs text quality -- so the+ per-model setting must not reach them through this helper either. The encoder loaders that do+ keep fp8 ask the device directly, which is a different question."""+ monkeypatch.setattr(load_default, "should_keep_fp8_weights", lambda _device: False)+ monkeypatch.setattr(load_default, "_device_supports_fp8_storage", lambda _device, _logger=None: True)++ kept = _loader()._keep_fp8_weights(_config(True), SubModelType.TextEncoder)++ assert kept is Falsediff --git a/tests/backend/model_manager/load/test_krea2_loader_boundaries.py b/tests/backend/model_manager/load/test_krea2_loader_boundaries.pyindex c247cf6402..1e0f57ef2b 100644--- a/tests/backend/model_manager/load/test_krea2_loader_boundaries.py+++ b/tests/backend/model_manager/load/test_krea2_loader_boundaries.py@@ -44,6 +44,9 @@ def test_single_file_loader_constructs_and_materializes_model(monkeypatch, tmp_ploader._ram_cache = ram_cache# ModelLoader.__init__ always sets a logger; this test bypasses __init__, so supply one.loader._logger = MagicMock()+ # `ModelLoader.__init__` sets this on the real object; `_keep_fp8_weights` reads it to ask+ # whether this device can hold fp8 at all.+ loader._torch_device = torch.device("cpu")loader._apply_fp8_layerwise_casting = lambda model, _config, _submodel: modelmonkeypatch.setattr(diffusers, "Krea2Transformer2DModel", _TinyKrea2Transformer, raising=False)@@ -112,6 +115,7 @@ def test_single_file_loader_decodes_an_int8_convrot_checkpoint(monkeypatch, tmp_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: modelmonkeypatch.setattr(diffusers, "Krea2Transformer2DModel", _TinyInt8Krea2Transformer, raising=False)