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(loaders): refuse quantization payloads a plain scale fold cannot decode
Alexander Eichhorn67a896af559c
diff --git a/invokeai/backend/model_manager/load/model_loaders/comfyui_state_dict_utils.py b/invokeai/backend/model_manager/load/model_loaders/comfyui_state_dict_utils.pyindex 8c4f86493d..f64b433e1f 100644--- a/invokeai/backend/model_manager/load/model_loaders/comfyui_state_dict_utils.py+++ b/invokeai/backend/model_manager/load/model_loaders/comfyui_state_dict_utils.py@@ -12,8 +12,13 @@ need a second copy.import torch-from invokeai.backend.quantization.fp8_scaled import expand_weight_scale, is_scale_metadata_key+from invokeai.backend.quantization.fp8_scaled import (+ expand_weight_scale,+ is_scale_metadata_key,+ reject_mx_block_scale,+)from invokeai.backend.quantization.int8_convrot import reject_int8_layers_a_plain_fold_cannot_decode+from invokeai.backend.quantization.nvfp4 import reject_nvfp4_layers_a_plain_fold_cannot_decodedef _strip_comfyui_prefix(sd: dict) -> dict:@@ -57,6 +62,7 @@ def _dequantize_comfyui_fp8(sd: dict, compute_dtype: torch.dtype, what: str = "Tin the file is a scale that still needs applying — i.e. a checkpoint must not shipalready-dequantized weights alongside their scales."""+ reject_nvfp4_layers_a_plain_fold_cannot_decode(sd, what)reject_int8_layers_a_plain_fold_cannot_decode(sd, what)scale_suffixes = (".weight_scale", ".scale_weight")weight_scale_keys = [k for k in sd.keys() if isinstance(k, str) and k.endswith(scale_suffixes)]@@ -68,6 +74,9 @@ def _dequantize_comfyui_fp8(sd: dict, compute_dtype: torch.dtype, what: str = "Tbreakif weight_key not in sd:continue+ # Before the cast: `.to(compute_dtype)` on an E8M0 grid converts the exponent bytes to+ # floats and loses the only evidence of what they were.+ reject_mx_block_scale(weight_key[: -len(".weight")], sd[scale_key])weight = sd[weight_key].to(compute_dtype)scale = sd[scale_key].to(compute_dtype)# Through the shared expansion rather than a local copy of it. The copy that used to livediff --git a/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.py b/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.pyindex 62889637c9..50598152be 100644--- a/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.py+++ b/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.py@@ -68,6 +68,7 @@ from invokeai.backend.quantization.fp8_scaled import (parse_quantization_metadata,predict_cast_state_dict_size,read_safetensors_metadata,+ reject_mx_block_scale,should_keep_fp8_weights,split_fp8_scaled_layers,strip_layer_path_prefix,@@ -565,6 +566,11 @@ def _drop_quantization_metadata(sd: dict[str, Any], logger, target_dtype: torch."""dequantized = 0for weight_key, scale_key in list(iter_weight_scale_pairs(sd)):+ # The one scheme no pass upstream of this fold catches. `extract_fp8_scaled_layers` refuses+ # an MX grid, but it only runs on the branch that *keeps* fp8; this is the other one, taken+ # wherever fp8 cannot be held at all. Without this the exponent bytes are folded as linear+ # multipliers -- around 120-135 -- at the right shape and dtype, with nothing logged.+ reject_mx_block_scale(weight_key[: -len(".weight")], sd[scale_key])weight = sd[weight_key].float()# `expand_weight_scale` rather than a local broadcast: a per-output-channel scale is 1-D of# length `out`, and `(out, in) * (out,)` aligns on the *last* axis, so it scales inputdiff --git a/invokeai/backend/model_manager/load/model_loaders/z_image.py b/invokeai/backend/model_manager/load/model_loaders/z_image.pyindex 5a93c37ef7..decfec4be5 100644--- a/invokeai/backend/model_manager/load/model_loaders/z_image.py+++ b/invokeai/backend/model_manager/load/model_loaders/z_image.py@@ -52,6 +52,7 @@ from invokeai.backend.quantization.fp8_scaled import (parse_quantization_metadata,predict_cast_state_dict_size,read_safetensors_metadata,+ reject_mx_block_scale,reject_quantized_side_channel,split_fp8_scaled_layers,split_qkv_sidechannel,@@ -1165,6 +1166,9 @@ def _fold_comfy_scaled_weights(sd: dict[str, Any], dtype: torch.dtype) -> int:"""folded = 0for weight_key, scale_key in list(iter_weight_scale_pairs(sd)):+ # Before the cast: `.float()` on an E8M0 grid turns the exponent bytes into ordinary numbers+ # and loses the only evidence of what they were.+ reject_mx_block_scale(weight_key[: -len(".weight")], sd[scale_key])# Float8 needs `.float()`; torch has no direct type promotion for it.weight_float = sd[weight_key].float()scale = expand_weight_scale(weight_float, sd[scale_key].float(), weight_key)diff --git a/invokeai/backend/pid/decode.py b/invokeai/backend/pid/decode.pyindex b35e8cdf88..826d31d3d8 100644--- a/invokeai/backend/pid/decode.py+++ b/invokeai/backend/pid/decode.py@@ -339,13 +339,16 @@ def load_pid_decoder(state_dict: dict[Any, Tensor], backbone: BaseModelType) -># through `load_state_dict`'s own copy.int8_markers = extract_int8_convrot_markers(state_dict)reject_unmarked_int8_weights(state_dict, int8_markers, "PiD")+ # Outside the branch, like the check above it and for the same reason. A scale from another+ # scheme would have its weight copied into a float32 parameter unscaled -- off by+ # `1/weight_scale` -- and the orphaned key would vanish into the `strict=False` load below,+ # reported at DEBUG. Inside the branch this only covered a *mixed* repack; a checkpoint that is+ # purely scaled fp8 has no int8 marker at all, so it never reached the check that exists for it.+ reject_foreign_quantization_scales(state_dict, int8_markers, "PiD", net)if int8_markers:# The rest of `install_int8_convrot_layers` does not apply here -- this path has no model# cache to reserve against, and `load_state_dict` copies into float32 parameters rather than- # casting the dict -- but this check does: an fp8 scale from a mixed repack would otherwise- # have its weight copied in unscaled, off by `1/weight_scale`, and the orphan would vanish- # into the `strict=False` load below.- reject_foreign_quantization_scales(state_dict, int8_markers, "PiD", net)+ # casting the dict.swap_in_int8_linears(net, state_dict, split_int8_convrot_layers(state_dict, int8_markers, torch.float32, model=net))diff --git a/invokeai/backend/quantization/fp8_scaled.py b/invokeai/backend/quantization/fp8_scaled.pyindex 6542ead5b6..61a5a0fecc 100644--- a/invokeai/backend/quantization/fp8_scaled.py+++ b/invokeai/backend/quantization/fp8_scaled.py@@ -435,6 +435,18 @@ def _reject_mx_scale(path: str) -> None:)+def reject_mx_block_scale(path: str, scale: Any) -> None:+ """Refuse an MX exponent grid to anything that would multiply it as a number.++ The same refusal :func:`extract_fp8_scaled_layers` applies, for the folds that do not go through+ it. An E8M0 byte is a biased exponent -- 127 means ``2**0`` -- so folding the grid as a linear+ scale multiplies every weight by something around 120-135. Right shape, right dtype, roughly two+ orders of magnitude out, and nothing raises.+ """+ if getattr(scale, "dtype", None) in _MX_SCALE_DTYPES:+ _reject_mx_scale(path)++def _normalize_weight_scale(scale: torch.Tensor) -> torch.Tensor:"""Canonical float32 form of a weight scale, preserving its layout.diff --git a/invokeai/backend/quantization/nvfp4.py b/invokeai/backend/quantization/nvfp4.pyindex 76aec234be..9de726c648 100644--- a/invokeai/backend/quantization/nvfp4.py+++ b/invokeai/backend/quantization/nvfp4.py@@ -295,6 +295,60 @@ def _find_nvfp4_layers(sd: Mapping[str, Any], header_layers: Mapping[str, Any] |return layers+def reject_nvfp4_layers_a_plain_fold_cannot_decode(sd: Mapping[str, Any], what: str = "This checkpoint") -> None:+ """Refuse an nvfp4 layer to a fold that only multiplies a scale into a weight.++ **Wan** (`wan.py:511`) is the seam this exists for: it reads scaled fp8 and never calls+ :func:`pop_nvfp4_layers`. The other caller of the shared fold, the Qwen2.5-VL encoder, *does*+ pop first (`qwen_image.py:473`, forty-odd lines before its fold) and ships the packed layers, so+ the guard is unreachable there — do not read it as evidence that encoder lacks nvfp4 support.++ The fold has no dtype gate, by design, so it takes the layer: the block-scale grid carries one+ entry per 16 logical elements and the weight packs two 4-bit codes per byte, so eight packed+ columns fall to each grid entry and the shapes line up by accident. What comes out is the packed+ bytes multiplied by the grid, at the compute dtype and half the logical width, reported in the+ log as a dequantized weight.++ Half the width is usually caught at ``load_state_dict`` — but not always, and that is the reason+ to refuse rather than rely on it. Wan infers ``text_dim`` from ``shape[1]`` of+ ``condition_embedder.text_embedder.linear_1`` (`wan.py:356`), which is the dimension the fold+ halves: with that layer packed, the *architecture* is built to match the mangled weight and+ nothing mismatches. The load then fails on the leftover ``weight_scale_2`` with a message about+ Wan variants with extra conditioning branches — a diagnosis pointing somewhere else entirely.++ Detection is the union of two structural tests: a ``weight_scale_2`` beside the weight, which is+ what the decode keys on, and a packed ``uint8`` weight carrying a block scale without one, which+ is the half-state :func:`_find_nvfp4_layers` refuses by name. Keying on the first alone would+ miss the second, and the fold takes it just as readily.++ Narrower than the decode in one way worth knowing: at the Wan seam a bundled nvfp4 text encoder+ in an all-in-one file is removed by ``_drop_benign_extra_keys`` before the fold, so it is dropped+ rather than refused.+ """+ named = {+ key[: -len(WEIGHT_SCALE_2_SUFFIX)]+ for key in sd+ if isinstance(key, str)+ and key.endswith(WEIGHT_SCALE_2_SUFFIX)+ and f"{key[: -len(WEIGHT_SCALE_2_SUFFIX)]}.weight" in sd+ }+ # A packed weight with a block scale and no global one is the half-state `_find_nvfp4_layers`+ # refuses by name. Keying on `weight_scale_2` alone would miss it, and the fold takes it just as+ # readily -- so the detection here is the union, not the narrower test.+ half = {+ weight_key[: -len(".weight")]+ for weight_key, _scale_key in iter_weight_scale_pairs(sd)+ if getattr(sd.get(weight_key), "dtype", None) is torch.uint8+ }+ packed = sorted(named | half)+ if packed:+ raise ValueError(+ f"{what} carries {len(packed)} nvfp4 layer(s) (e.g. {', '.join(packed[:3])}) and this loader does "+ "not support nvfp4. Their weights are two 4-bit codes per byte, so folding a scale into them "+ "produces a tensor of half the width the model needs. Use the fp8 or bf16 build of this checkpoint."+ )++def pop_nvfp4_layers(sd: dict[str, Any], header_layers: Mapping[str, Any] | None = None) -> dict[str, NVFP4Payload]:"""Take every nvfp4 layer's packed tensors out of ``sd`` and drop the rest of its side channel.diff --git a/tests/backend/model_manager/load/test_scaled_fp8_fold_axis.py b/tests/backend/model_manager/load/test_scaled_fp8_fold_axis.pyindex 480664b084..301e93cebf 100644--- a/tests/backend/model_manager/load/test_scaled_fp8_fold_axis.py+++ b/tests/backend/model_manager/load/test_scaled_fp8_fold_axis.py@@ -27,6 +27,8 @@ from invokeai.backend.model_manager.load.model_loaders.z_image import _fold_comffrom invokeai.backend.quantization.fp8_scaled import (WEIGHT_SCALE_SUFFIXES,)+from invokeai.backend.quantization.nvfp4 import pop_nvfp4_layers+from tests.fixtures.quantized_payloads import nvfp4_signed_tensorsdef _per_channel_case(out_features: int = 4, in_features: int = 2):@@ -59,6 +61,21 @@ class TestMistralEncoderFold:rows = torch.tensor([[1.0, 1.0, 1.0], [2.0, 2.0, 2.0], [3.0, 3.0, 3.0]], dtype=torch.bfloat16)assert torch.equal(sd["layer.weight"], rows), "scale must vary down the rows, not across them"+ def test_an_mx_block_scale_is_refused_rather_than_folded_as_a_multiplier(self) -> None:+ """An MXFP8 grid is E8M0 exponent *bytes*: 127 means 2**0, i.e. a scale of 1.0. Folded as a+ linear multiplier it makes every weight ~127x too large, at the right shape and the right+ dtype, with nothing raised and nothing logged. `extract_fp8_scaled_layers` has refused this+ since MXFP8 was recognised -- but these folds do not go through it, so the refusal never+ reached them.+ """+ sd = {+ "layer.weight": torch.ones(128, 128).to(torch.float8_e4m3fn),+ "layer.weight_scale": torch.full((128, 4), 127, dtype=torch.uint8),+ }++ with pytest.raises(NotImplementedError, match="MXFP8"):+ _drop_quantization_metadata(sd, MagicMock(), target_dtype=torch.bfloat16)+class TestZImageQwen3EncoderFold:"""The Z-Image Qwen3 encoder's single-file loader folds the same way."""@@ -101,10 +118,25 @@ class TestZImageQwen3EncoderFold:})+ def test_an_mx_block_scale_is_refused_rather_than_folded_as_a_multiplier(self) -> None:+ """An MXFP8 grid is E8M0 exponent *bytes*: 127 means 2**0, i.e. a scale of 1.0. Folded as a+ linear multiplier it makes every weight ~127x too large, at the right shape and the right+ dtype, with nothing raised and nothing logged. `extract_fp8_scaled_layers` has refused this+ since MXFP8 was recognised -- but these folds do not go through it, so the refusal never+ reached them.+ """+ sd = {+ "layer.weight": torch.ones(128, 128).to(torch.float8_e4m3fn),+ "layer.weight_scale": torch.full((128, 4), 127, dtype=torch.uint8),+ }++ with pytest.raises(NotImplementedError, match="MXFP8"):+ _fold_comfy_scaled_weights(sd, torch.bfloat16)+class TestSharedComfyFold:"""`_dequantize_comfyui_fp8`, the copy the Wan (`wan.py:511`) and Qwen-Image- (`qwen_image.py:514`) loaders reach. Its local loop compared `scale.shape[dim] !=+ (`qwen_image.py:520`) loaders reach. Its local loop compared `scale.shape[dim] !=weight.shape[dim]`, so a per-output-channel scale -- whose length already equals the row count-- was expanded by nothing and left to broadcasting."""@@ -155,6 +187,57 @@ class TestSharedComfyFold:assert torch.equal(folded, torch.full((3, 2), 2.0))+ def test_an_nvfp4_layer_is_refused_rather_than_folded_over_its_packed_codes(self) -> None:+ """nvfp4 packs two 4-bit codes per byte and carries a block-scale grid, one entry per 16+ logical elements. The shapes line up by accident -- eight packed columns per grid entry --+ so this fold, which has no dtype gate, multiplied the packed bytes and reported a+ dequantized weight. The result is half the width the model needs, so `load_state_dict`+ catches it; it just says "size mismatch" after a log line claiming success.+ """+ tensors, _ = nvfp4_signed_tensors("layer", torch.randint(0, 2, (128, 64), dtype=torch.bool))++ with pytest.raises(ValueError, match="does not support nvfp4"):+ _dequantize_comfyui_fp8(tensors, torch.float32)++ def test_an_nvfp4_layer_missing_its_global_scale_is_refused_too(self) -> None:+ """The half-state: packed codes and a block-scale grid, no `weight_scale_2`. It is the shape+ `_find_nvfp4_layers` refuses by name, so a build that loses the global scale somewhere+ upstream arrives here looking like ordinary scaled fp8 -- and the fold takes it exactly as+ readily as the whole layer, for the same reason and to the same end. Keying the guard on+ `weight_scale_2` alone, which is what the decode keys on, would let this one through."""+ tensors, _ = nvfp4_signed_tensors("layer", torch.randint(0, 2, (128, 64), dtype=torch.bool))+ del tensors["layer.weight_scale_2"]++ with pytest.raises(ValueError, match="does not support nvfp4"):+ _dequantize_comfyui_fp8(tensors, torch.float32)++ def test_a_layer_whose_packed_payload_was_taken_out_first_still_folds(self) -> None:+ """Two loaders reach this fold: Wan, which has no nvfp4 support at all, and the Qwen2.5-VL+ encoder, which calls `pop_nvfp4_layers` first (`qwen_image.py:473`) and ships the layers+ packed. That pop takes the weight and both scales out together, so by the time the fold runs+ there is nothing for the guard to see -- asserted, because a guard that fired here anyway+ would break the one supported nvfp4 build that passes through."""+ tensors, _ = nvfp4_signed_tensors("packed", torch.randint(0, 2, (128, 64), dtype=torch.bool))+ pop_nvfp4_layers(tensors, header_layers={"packed": {"format": "nvfp4"}})+ tensors.update({"layer.weight": torch.ones(4, 3), "layer.weight_scale": torch.tensor([1.0, 2.0, 3.0, 4.0])})++ assert _dequantize_comfyui_fp8(tensors, torch.float32) == 1++ def test_an_mx_block_scale_is_refused_rather_than_folded_as_a_multiplier(self) -> None:+ """An MXFP8 grid is E8M0 exponent *bytes*: 127 means 2**0, i.e. a scale of 1.0. Folded as a+ linear multiplier it makes every weight ~127x too large, at the right shape and the right+ dtype, with nothing raised and nothing logged. `extract_fp8_scaled_layers` has refused this+ since MXFP8 was recognised -- but these folds do not go through it, so the refusal never+ reached them.+ """+ sd = {+ "layer.weight": torch.ones(128, 128).to(torch.float8_e4m3fn),+ "layer.weight_scale": torch.full((128, 4), 127, dtype=torch.uint8),+ }++ with pytest.raises(NotImplementedError, match="MXFP8"):+ _dequantize_comfyui_fp8(sd, torch.bfloat16)+class TestFlux2Fold:"""FLUX.2's own copy (`flux.py`). It is unreachable at its one call site -- extraction takesdiff --git a/tests/backend/model_manager/load/test_wan_checkpoint_loader.py b/tests/backend/model_manager/load/test_wan_checkpoint_loader.pyindex 31211b9136..efda4c5625 100644--- a/tests/backend/model_manager/load/test_wan_checkpoint_loader.py+++ b/tests/backend/model_manager/load/test_wan_checkpoint_loader.py@@ -20,7 +20,7 @@ from invokeai.backend.model_manager.load.model_loaders.wan import (_build_wan_transformer_config,)from invokeai.backend.model_manager.taxonomy import SubModelType, WanVariantType-from tests.fixtures.quantized_payloads import comfy_quant_marker, quantize_convrot+from tests.fixtures.quantized_payloads import comfy_quant_marker, nvfp4_signed_tensors, quantize_convrot# A structurally faithful but tiny Wan transformer. attention_head_dim must stay# at 128 — the loader derives num_attention_heads as inner_dim // 128, matching@@ -201,7 +201,29 @@ class TestEndToEnd:path = tmp_path / "Wan2.2-A14B-HighNoise-int8_convrot.safetensors"save_file(sd, path)- with pytest.raises(ValueError, match="quantized with convrot"):+ message = r"Wan checkpoint Wan2\.2-A14B-HighNoise-int8_convrot\.safetensors.*quantized with convrot"+ with pytest.raises(ValueError, match=message):+ _load(path)++ def test_an_nvfp4_checkpoint_is_refused_rather_than_folded_over_its_packed_codes(self, tmp_path: Path) -> None:+ """Wan reads scaled fp8 but never calls `pop_nvfp4_layers`, and the shared fold has no dtype+ gate, so an nvfp4 layer was multiplied by its block-scale grid and logged as dequantized.+ The load then died on the width -- "size mismatch [128, 64] vs [128, 128]" -- which names+ neither the scheme nor the remedy, after a line claiming success. Pinned at the loader+ because that is where the misleading sequence was visible.+ """+ reference = _tiny_model()+ sd = {k: v.clone() for k, v in reference.state_dict().items()}++ target = "blocks.0.attn1.to_q"+ rows, columns = sd[f"{target}.weight"].shape+ packed, _ = nvfp4_signed_tensors(target, torch.randint(0, 2, (rows, columns), dtype=torch.bool))+ sd.update(packed)+ path = tmp_path / "Wan2.2-A14B-HighNoise-nvfp4.safetensors"+ save_file(sd, path)++ message = r"Wan checkpoint Wan2\.2-A14B-HighNoise-nvfp4\.safetensors.*does not support nvfp4"+ with pytest.raises(ValueError, match=message):_load(path)def test_scale_bookkeeping_never_reaches_the_model(self, tmp_path: Path) -> None:diff --git a/tests/backend/pid/test_pid_int8.py b/tests/backend/pid/test_pid_int8.pyindex b580ac8f69..badfbb60b6 100644--- a/tests/backend/pid/test_pid_int8.py+++ b/tests/backend/pid/test_pid_int8.py@@ -124,6 +124,27 @@ def test_an_int8_checkpoint_keeps_its_block_linears_int8_and_decodes_like_the_detorch.testing.assert_close(_forward(net), _forward(reference))+def test_a_purely_scaled_fp8_checkpoint_is_refused_too(monkeypatch: pytest.MonkeyPatch) -> None:+ """The same check, on a file with no int8 marker anywhere.++ It used to live inside `if int8_markers:`, so it only ever saw a *mixed* repack. A checkpoint+ that is scaled fp8 throughout produces no int8 markers at all -- `extract_int8_convrot_markers`+ takes only `int8_tensorwise`, and the unmarked-weight check filters on the int8 dtype -- so it+ walked past both gates and had its fp8 codes copied straight into the float32 parameters, off by+ `1/weight_scale`, with the orphaned scales reported only at DEBUG.+ """+ torch.manual_seed(0)+ state_dict, _ = _int8_checkpoint(_tiny_net())+ net = _tiny_net()+ for name in _quantized_layers(net):+ state_dict.pop(f"{name}.comfy_quant", None)+ state_dict[f"{name}.weight"] = state_dict[f"{name}.weight"].float().to(torch.float8_e4m3fn)+ monkeypatch.setattr(pid_decode_module, "build_pid_net", lambda backbone, version: net)++ with pytest.raises(ValueError, match=r"\.weight_scale"):+ load_pid_decoder(state_dict, BaseModelType.Flux)++def test_a_scale_from_another_scheme_is_refused_rather_than_loaded_unscaled(monkeypatch: pytest.MonkeyPatch,) -> None: