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
feat(quantization): keep scaled fp8 layers in Qwen-Image checkpoints
Alexander Eichhornda7662bf37d5
diff --git a/docs/src/content/docs/configuration/fp8-storage.mdx b/docs/src/content/docs/configuration/fp8-storage.mdxindex 95a2bb00b0..689ce8329b 100644--- a/docs/src/content/docs/configuration/fp8-storage.mdx+++ b/docs/src/content/docs/configuration/fp8-storage.mdx@@ -11,7 +11,7 @@ FP8 Storage cuts a model's VRAM footprint roughly in half by keeping weights onIt pairs well with [Low-VRAM mode](/configuration/low-vram-mode/): low-VRAM mode streams layers between RAM and VRAM, while FP8 Storage shrinks the layers themselves.:::caution[For full precision models only]-FP8 Storage is meant for **full precision** checkpoints (FP16 / BF16 / FP32). It is **silently a no-op** for **GGUF**, **NF4** and [**SDNQ**](/configuration/sdnq-quantization/) checkpoints, which carry their own storage precision. **int8** and **nvfp4** single-file checkpoints keep their quantized layers as they are — the loader returns a module type the FP8 layer cast does not touch — so there the toggle only reaches the layers the build ships in full precision. If your model is already quantized, use its full-precision variant to get the full effect of FP8 Storage.+FP8 Storage is meant for **full precision** checkpoints (FP16 / BF16 / FP32). It is **silently a no-op** for **GGUF**, **NF4** and [**SDNQ**](/configuration/sdnq-quantization/) checkpoints, which carry their own storage precision. **int8** and **nvfp4** single-file checkpoints keep their quantized layers as they are — the loader returns a module type the FP8 layer cast does not touch — so there the toggle only reaches the layers the build ships in full precision. On **Qwen-Image** single-file checkpoints that ship scaled fp8 layers, the toggle keeps those layers in FP8 with their own scale instead of unpacking them, and casts the rest. If your model is already quantized, use its full-precision variant to get the full effect of FP8 Storage.:::## Requirementsdiff --git a/invokeai/backend/model_manager/configs/main.py b/invokeai/backend/model_manager/configs/main.pyindex 5e1b6c157f..c7ab129887 100644--- a/invokeai/backend/model_manager/configs/main.py+++ b/invokeai/backend/model_manager/configs/main.py@@ -1771,10 +1771,10 @@ def _infer_qwen_image_variant(sd: dict[str | int, Any], path: Path) -> QwenImageclass Main_Checkpoint_QwenImage_Config(Checkpoint_Config_Base, Main_Config_Base, Config_Base):"""Model config for Qwen Image single-file checkpoint models (safetensors, etc).- Covers both raw bf16/fp16 checkpoints and ComfyUI-style fp8_scaled checkpoints.- The loader dequantizes fp8 weights back to bf16 at load time; the- `default_settings.fp8_storage` toggle can then optionally re-cast to fp8 for- VRAM savings.+ Covers raw bf16/fp16 checkpoints and ComfyUI-style fp8_scaled and nvfp4 checkpoints.+ The loader keeps scaled fp8 weights when fp8 compute is available or the+ `default_settings.fp8_storage` toggle is on (which also re-casts the rest to fp8),+ and dequantizes them to bf16 at load time otherwise."""base: Literal[BaseModelType.QwenImage] = Field(default=BaseModelType.QwenImage)diff --git a/invokeai/backend/model_manager/load/load_default.py b/invokeai/backend/model_manager/load/load_default.pyindex 276c67726d..347a9fac74 100644--- a/invokeai/backend/model_manager/load/load_default.py+++ b/invokeai/backend/model_manager/load/load_default.py@@ -627,8 +627,12 @@ class ModelLoader(ModelLoaderBase):"""Cast a skipped module's float8 params back to the dtype it is expected to compute in.Only float8 params are touched, and only the storage dtypes — a quantized param (GGUF, NF4,- bitsandbytes) is left to its own kernels.+ bitsandbytes) is left to its own kernels. A scaled-fp8 layer (fp8 weight plus `weight_scale`)+ is not raw codes either: `CustomLinear` dequantizes it with its scale, while a plain upcast+ here would drop the scale."""+ if getattr(module, "weight_scale", None) is not None:+ returnfor param in module.parameters(recurse=False):if param.data.dtype in FP8_STORAGE_DTYPES and not _is_quantized_param(param):param.data = param.data.to(compute_dtype)diff --git a/invokeai/backend/model_manager/load/model_loaders/qwen_image.py b/invokeai/backend/model_manager/load/model_loaders/qwen_image.pyindex b24c8d6a15..f59af7278e 100644--- a/invokeai/backend/model_manager/load/model_loaders/qwen_image.py+++ b/invokeai/backend/model_manager/load/model_loaders/qwen_image.py@@ -31,10 +31,18 @@ from invokeai.backend.model_manager.taxonomy import (SubModelType,)from invokeai.backend.quantization.fp8_scaled import (+ attach_fp8_scales,+ cast_state_dict,+ dequantize_fp8_scaled,+ extract_comfy_quant_hints,+ extract_fp8_scaled_layers,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,)from invokeai.backend.quantization.gguf.ggml_tensor import GGMLTensorfrom invokeai.backend.quantization.gguf.loaders import gguf_sd_loader@@ -232,9 +240,10 @@ class QwenImageGGUFCheckpointModel(ModelLoader):@ModelLoaderRegistry.register(base=BaseModelType.QwenImage, type=ModelType.Main, format=ModelFormat.Checkpoint)class QwenImageCheckpointModel(ModelLoader):"""Loads Qwen Image transformer models from single-file safetensors checkpoints- (e.g. ComfyUI fp8_scaled, plain bf16/fp16). Dequantizes ComfyUI fp8 scaling to- bf16 at load time; the `default_settings.fp8_storage` toggle then optionally- re-casts to fp8 for VRAM savings."""+ (e.g. ComfyUI fp8_scaled or nvfp4, plain bf16/fp16). nvfp4 layers stay packed. Scaled+ fp8 layers keep their fp8 weight and scale when fp8 compute is available or the model's+ `default_settings.fp8_storage` is on (which then also casts the dense remainder to fp8);+ otherwise they are dequantized to bf16 at load time."""def _load_model(self,@@ -279,37 +288,69 @@ class QwenImageCheckpointModel(ModelLoader):)nvfp4_payloads = pop_nvfp4_layers(sd, header_layers=header_layers)+ # ComfyUI 'scaled fp8': an fp8 weight plus its `weight_scale`, named in the header or by a per-layer marker.+ fp8_layers = extract_fp8_scaled_layers(sd, layer_hints={**extract_comfy_quant_hints(sd), **header_layers})+ # Kept fp8 only when something uses them: the fp8 matmul, or fp8 storage the user asked of this model. For+ # storage the checkpoint's own scale is exact, where the layerwise cast of a folded weight has none. Without+ # either, a dequantize per forward would cost speed for memory nobody asked to save, so they are folded.+ use_fp8_storage = bool(fp8_layers) and self._should_use_fp8(config, SubModelType.Transformer)+ keep_fp8 = bool(fp8_layers) and (should_keep_fp8_weights(target_device) or use_fp8_storage)+is_edit = getattr(config, "variant", None) == QwenImageVariantType.Editmodel_config = _build_qwen_image_transformer_config(sd, is_edit=is_edit)- # Built before the reservation, which depends on its modules: they decide which nvfp4 layers stay packed.+ # Built before the reservation, which depends on its modules: they decide which nvfp4 and fp8 layers stay+ # quantized.with accelerate.init_empty_weights():model = QwenImageTransformer2DModel(**model_config)skip_patterns = _model_declared_skip_patterns(model)- # One reservation, before the fold widens a single weight: `make_room` makes that much room rather than adding- # to an earlier one. Every fp8 layer is folded to the compute dtype.+ # One reservation, before the fold or the split widens a single weight: `make_room` makes that much room+ # rather than adding to an earlier one.self._ram_cache.make_room(- predict_cast_state_dict_size(sd, model_dtype, keep_fp8=False)+ predict_cast_state_dict_size(+ sd, model_dtype, keep_fp8=keep_fp8, model=model, skip_patterns=skip_patterns, scaled_layers=fp8_layers+ )+ predict_nvfp4_install_size(model, nvfp4_payloads, model_dtype, skip_patterns))- dequantized = _dequantize_comfyui_fp8(sd, model_dtype)- if dequantized > 0:- logger.info(f"Dequantized {dequantized} ComfyUI-quantized weights")- _strip_quantization_metadata(sd)-- # Dequantized fp8 weights are already at model_dtype; this only casts any remaining- # non-quantized float weights (e.g. a plain fp16/fp32 checkpoint) to the compute dtype.- for k in list(sd.keys()):- if sd[k].is_floating_point():- sd[k] = sd[k].to(model_dtype)+ if fp8_layers and not keep_fp8:+ dequantize_fp8_scaled(sd, fp8_layers, model_dtype)+ logger.info(f"Qwen Image: folded {len(fp8_layers)} scaled fp8 layer(s) into {model_dtype}.")+ fp8_layers = {}+ # Layers the cast would widen anyway are folded here with their scale applied, so the cast never drops one.+ fp8_layers = split_fp8_scaled_layers(sd, fp8_layers, model_dtype, model=model, skip_patterns=skip_patterns)+ cast_state_dict(sd, model_dtype, keep_fp8=keep_fp8, model=model, skip_patterns=skip_patterns)if nvfp4_payloads:packed = install_nvfp4_layers(model, sd, nvfp4_payloads, model_dtype, skip_patterns)logger.info(f"Qwen Image: kept {packed} of {len(nvfp4_payloads)} nvfp4 layer(s) packed.")model.load_state_dict(sd, strict=False, assign=True)+ # `assign=True` aliases every param to its `sd` tensor: without this, the fp8 storage cast below would hold+ # each dense weight at bf16 and fp8 at once, past the reservation.+ sd.clear()++ if fp8_layers:+ attached = attach_fp8_scales(model, fp8_layers)+ warn_on_unattached_scales(logger, "Qwen Image", attached, fp8_layers)+ if not use_fp8_storage:+ logger.info(f"Qwen Image: kept {attached} scaled fp8 layer(s) fp8 for fp8 compute.")+ else:+ # The rest of the dense weights go to fp8 storage too. The scaled layers are left alone: the cast+ # hooks would upcast them without their scale. Marking the model cast keeps+ # `_apply_fp8_layerwise_casting` from doing exactly that afterwards.+ self._apply_fp8_to_nn_module(+ model,+ storage_dtype=torch.float8_e4m3fn,+ compute_dtype=model_dtype,+ extra_skip_patterns=skip_patterns,+ skip=lambda _name, module: getattr(module, "weight_scale", None) is not None,+ )+ logger.info(+ f"FP8 layerwise casting enabled for {config.name} (storage=float8_e4m3fn, compute={model_dtype}); "+ f"kept {attached} scaled fp8 layer(s) with their own scale."+ )return modeldiff --git a/tests/backend/model_manager/load/test_load_default_fp8.py b/tests/backend/model_manager/load/test_load_default_fp8.pyindex 9ed38273bf..f57bdaf896 100644--- a/tests/backend/model_manager/load/test_load_default_fp8.py+++ b/tests/backend/model_manager/load/test_load_default_fp8.py@@ -867,6 +867,24 @@ class TestSkippedModulesNeverKeepCheckpointFp8:assert model.proj_out.weight.dtype is torch.bfloat16, "skipped module left computing on fp8 codes"assert model.attn.weight.dtype is torch.float8_e4m3fn+ def test_a_pattern_skipped_scaled_layer_keeps_its_fp8_weight(self) -> None:+ """A scaled-fp8 `proj_out` is computed with its `weight_scale`; upcasting its codes without the+ scale would make the final projection wrong by that factor, silently."""+ model = self._model()+ codes = torch.full((32, 16), 3.0).to(torch.float8_e4m3fn)+ model.proj_out.weight = torch.nn.Parameter(codes, requires_grad=False)+ model.proj_out.weight_scale = torch.tensor(2.0)++ ModelLoader._apply_fp8_to_nn_module(+ model,+ storage_dtype=torch.float8_e4m3fn,+ compute_dtype=torch.bfloat16,+ skip=lambda _name, module: getattr(module, "weight_scale", None) is not None,+ )++ assert model.proj_out.weight.dtype is torch.float8_e4m3fn+ assert torch.equal(model.proj_out.weight.float(), codes.float())+def test_an_extra_skip_pattern_gets_the_same_treatment(self) -> None:model = self._model()model.attn.weight = torch.nn.Parameter(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.pyindex 9c574a579b..be662688ee 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@@ -1,10 +1,11 @@"""Qwen-Image's single-file loaders keep Comfy's nvfp4 builds packed.-Both Comfy files mix nvfp4 with scaled fp8, and both loaders fold ComfyUI fp8 with `_dequantize_comfyui_fp8`, which-multiplies every `.weight_scale` into its weight -- nvfp4's block scales included. So what these tests pin is the order:-the nvfp4 layers leave the state dict before the fold, come back packed under the paths the model uses (the encoder's-legacy `model.X` keys become `model.language_model.X`), the fp8 layers are still folded, and one reservation is made-before the fold widens anything. The compute dtype is bf16, as in production: the packed global scale must not be cast.+Both Comfy files mix nvfp4 with scaled fp8, and an fp8 fold multiplies every `.weight_scale` into its weight -- nvfp4's+block scales included. So what these tests pin is the order: the nvfp4 layers leave the state dict before any fp8+handling, come back packed under the paths the model uses (the encoder's legacy `model.X` keys become+`model.language_model.X`), and one reservation is made before anything is widened. The transformer's scaled fp8 layers+are folded unless fp8 compute or the model's fp8 storage setting keeps them; the encoder's are always folded. The compute+dtype is bf16, as in production: the packed global scale must not be cast."""import json@@ -16,6 +17,9 @@ import torchfrom invokeai.backend.model_manager.configs.main import Main_Checkpoint_QwenImage_Configfrom invokeai.backend.model_manager.configs.qwen_vl_encoder import QwenVLEncoder_Checkpoint_Config+from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.torch_module_autocast import (+ apply_custom_layers_to_model,+)from invokeai.backend.model_manager.load.model_loaders import qwen_imagefrom invokeai.backend.model_manager.load.model_loaders.qwen_image import (QwenImageCheckpointModel,@@ -49,7 +53,7 @@ def _marker(fmt: str) -> torch.Tensor:def _patch_common(monkeypatch: pytest.MonkeyPatch, state_dict: dict, metadata: dict) -> list[bool]:- """Patch file access and devices; return a log of whether room had been made when the fp8 fold ran."""+ """Patch file access and devices; return a log for `_record_fold`."""import safetensors.torchmonkeypatch.setattr(safetensors.torch, "load_file", lambda _path: state_dict)@@ -59,14 +63,16 @@ def _patch_common(monkeypatch: pytest.MonkeyPatch, state_dict: dict, metadata: dreturn []-def _record_fold(monkeypatch: pytest.MonkeyPatch, loader, log: list[bool]) -> None:- fold = qwen_image._dequantize_comfyui_fp8+def _record_fold(monkeypatch: pytest.MonkeyPatch, loader, log: list[bool], *names: str) -> None:+ """At every call of the named `qwen_image` functions, log whether room had been made yet."""+ for name in names or ("_dequantize_comfyui_fp8",):+ original = getattr(qwen_image, name)- def recording_fold(*args, **kwargs):- log.append(loader._ram_cache.make_room.called)- return fold(*args, **kwargs)+ def recording(*args, _original=original, **kwargs):+ log.append(loader._ram_cache.make_room.called)+ return _original(*args, **kwargs)- monkeypatch.setattr(qwen_image, "_dequantize_comfyui_fp8", recording_fold)+ monkeypatch.setattr(qwen_image, name, recording)class _TinyQwenImageTransformer(torch.nn.Module):@@ -88,11 +94,18 @@ class _TinyQwenImageTransformer(torch.nn.Module):self.img_in = torch.nn.Linear(64, 128)-def test_the_transformer_keeps_header_named_nvfp4_layers_packed_beside_folded_fp8(- monkeypatch: pytest.MonkeyPatch, tmp_path[email protected]("mode", ["fold", "fp8_compute", "fp8_storage"])+def test_the_transformer_keeps_nvfp4_packed_and_scaled_fp8_only_where_something_uses_it(+ monkeypatch: pytest.MonkeyPatch, tmp_path, mode: str) -> None:+ """Scaled fp8 layers stay fp8, with their own scale, for the fp8 matmul or for fp8 storage the model asks for; with+ neither they are folded. Under fp8 storage the dense remainder goes to fp8 too, but not the scaled layers, whose+ cast hooks would drop their scale."""import diffusers+ from invokeai.backend.model_manager.load import load_default+ from invokeai.backend.model_manager.taxonomy import SubModelType+torch.manual_seed(0)state_dict: dict[str, torch.Tensor] = {}expected: dict[str, torch.Tensor] = {}@@ -118,14 +131,29 @@ def test_the_transformer_keeps_header_named_nvfp4_layers_packed_beside_folded_fplog = _patch_common(monkeypatch, state_dict, {"_quantization_metadata": json.dumps({"layers": header})})monkeypatch.setattr(diffusers, "QwenImageTransformer2DModel", _TinyQwenImageTransformer, raising=False)+ monkeypatch.setattr(qwen_image, "should_keep_fp8_weights", lambda _device: mode == "fp8_compute")+ monkeypatch.setattr(load_default, "_device_supports_fp8_storage", lambda *_args: True)checkpoint = tmp_path / "qwen_image_nvfp4.safetensors"checkpoint.touch()loader = object.__new__(QwenImageCheckpointModel)loader._ram_cache = SimpleNamespace(make_room=MagicMock())- _record_fold(monkeypatch, loader, log)+ loader._torch_device = torch.device("cpu")+ loader._logger = MagicMock()+ _record_fold(monkeypatch, loader, log, "dequantize_fp8_scaled", "split_fp8_scaled_layers")+ # The storage cast allocates an fp8 copy per weight; the loaded state dict must no longer hold the originals.+ entries_at_storage_cast: list[int] = []+ loader._apply_fp8_to_nn_module = lambda *args, **kwargs: (+ entries_at_storage_cast.append(len(state_dict)),+ QwenImageCheckpointModel._apply_fp8_to_nn_module(*args, **kwargs),+ )biases = {path: state_dict[f"{path}.bias"] for path in expected}+ config = Main_Checkpoint_QwenImage_Config.model_construct(+ path=str(checkpoint),+ name="qwen_image_nvfp4",+ default_settings=SimpleNamespace(fp8_storage=mode == "fp8_storage"),+ )- model = loader._load_from_singlefile(Main_Checkpoint_QwenImage_Config.model_construct(path=str(checkpoint)))+ model = loader._load_model(config, SubModelType.Transformer)for path, weight in expected.items():module = model.get_submodule(path)@@ -135,16 +163,34 @@ def test_the_transformer_keeps_header_named_nvfp4_layers_packed_beside_folded_fpx = torch.randn(3, module.in_features, dtype=COMPUTE_DTYPE)expected_out = torch.nn.functional.linear(x, weight.to(COMPUTE_DTYPE), biases[path].to(COMPUTE_DTYPE))torch.testing.assert_close(module(x), expected_out)- folded = model.transformer_blocks[0].txt_mlp.net[2]- assert type(folded) is torch.nn.Linear- assert torch.equal(folded.weight, (fp8_values * 0.5).to(COMPUTE_DTYPE))- assert log == [True]-- # Counted by hand: the packed layers as stored; their biases, the folded fp8 weight and its bias, its two scale- # scalars, and the dense input projection at bf16. The packed layers' scales are part of their stored size.+ fp8_layer = model.transformer_blocks[0].txt_mlp.net[2]+ if mode == "fold":+ assert torch.equal(fp8_layer.weight, (fp8_values * 0.5).to(COMPUTE_DTYPE))+ assert getattr(fp8_layer, "weight_scale", None) is None+ else:+ assert fp8_layer.weight.dtype is torch.float8_e4m3fn+ assert torch.equal(fp8_layer.weight.float(), fp8_values)+ assert torch.equal(fp8_layer.weight_scale.float(), torch.tensor(0.5))+ assert model.img_in.weight.dtype is (torch.float8_e4m3fn if mode == "fp8_storage" else COMPUTE_DTYPE)+ assert getattr(model.img_in, "weight_scale", None) is None+ # Through the cache's custom layers, as denoising runs it: a cast hook on the kept layer would upcast its codes+ # without the scale before CustomLinear could apply it.+ fp8_bias = fp8_layer.bias.detach().to(COMPUTE_DTYPE)+ apply_custom_layers_to_model(model)+ x = torch.randn(3, 64, dtype=COMPUTE_DTYPE)+ expected_fp8_out = torch.nn.functional.linear(x, (fp8_values * 0.5).to(COMPUTE_DTYPE), fp8_bias)+ torch.testing.assert_close(model.transformer_blocks[0].txt_mlp.net[2](x), expected_fp8_out)+ # The reservation lands before the fold and before the split, whichever runs.+ assert log == ([True, True] if mode == "fold" else [True])+ assert entries_at_storage_cast == ([0] if mode == "fp8_storage" else [])++ # Counted by hand: the packed layers as stored; their biases, the fp8 layer's bias and the dense input projection at+ # bf16; the fp8 weight at bf16 when folded and one byte per element when kept. The side-channel scales, recovered+ # before the reservation, are not in the state dict it sizes.packed = _packed_bytes(128, 64) + _packed_bytes(256, 64)- widened = (128 + 256) + (128 * 64 + 128 + 2) + (128 * 64 + 128)- loader._ram_cache.make_room.assert_called_once_with(packed + widened * COMPUTE_DTYPE.itemsize)+ fp8_weight = 128 * 64 * (COMPUTE_DTYPE.itemsize if mode == "fold" else 1)+ dense = (128 + 256) + 128 + (128 * 64 + 128)+ loader._ram_cache.make_room.assert_called_once_with(packed + fp8_weight + dense * COMPUTE_DTYPE.itemsize)class _TinyQwenVL(torch.nn.Module):