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(quantization): fold per-output-channel scales down the rows, not across them
Alexander Eichhorn8c09fbbe6942
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 bc5d21837f..1eec64389d 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,6 +12,8 @@ need a second copy.import torch+from invokeai.backend.quantization.fp8_scaled import expand_weight_scale, is_scale_metadata_key+def _strip_comfyui_prefix(sd: dict) -> dict:"""Strip ComfyUI-style `model.diffusion_model.` / `diffusion_model.` prefixes from keys."""@@ -66,30 +68,26 @@ def _dequantize_comfyui_fp8(sd: dict, compute_dtype: torch.dtype) -> int:continueweight = sd[weight_key].to(compute_dtype)scale = sd[scale_key].to(compute_dtype)- if scale.shape != weight.shape and scale.numel() > 1:- for dim in range(len(weight.shape)):- if dim < len(scale.shape) and scale.shape[dim] != weight.shape[dim]:- block_size = weight.shape[dim] // scale.shape[dim]- if block_size > 1:- scale = scale.repeat_interleave(block_size, dim=dim)- sd[weight_key] = weight * scale+ # Through the shared expansion rather than a local copy of it. The copy that used to live+ # here compared `scale.shape[dim] != weight.shape[dim]`, so a per-output-channel scale --+ # whose length already equals the number of rows -- was expanded by nothing and left to+ # broadcasting, which aligns on the *last* axis. That scales columns instead of rows: a+ # shape error on a non-square weight, and on a square one (every attention out-projection)+ # a model that loads and generates noise.+ sd[weight_key] = weight * expand_weight_scale(weight, scale, weight_key)count += 1return countdef _strip_quantization_metadata(sd: dict) -> None:- """Strip ComfyUI fp8 quantization metadata keys in-place."""- keys_to_drop = [- k- for k in sd.keys()- if isinstance(k, str)- and (- k.endswith(".weight_scale")- or k.endswith(".scale_weight")- or k.endswith(".scale_input")- or "comfy_quant" in k- or k == "scaled_fp8"- )- ]- for k in keys_to_drop:- del sd[k]+ """Strip ComfyUI fp8 quantization metadata keys in-place.++ Through the shared predicate rather than a second list of suffixes. The list that used to stand+ here was a clause-for-clause copy of it that had fallen one spelling behind: it dropped+ ``.scale_input`` but not ``.input_scale``, which is the spelling Comfy actually writes, so on+ the Wan path an ordinary scaled-fp8 checkpoint was rejected outright by+ `_raise_for_incompatible_keys` as an unsupported variant. A copy that has to be kept in step by+ hand will fall behind again the next time a spelling is added.+ """+ for key in [k for k in sd if is_scale_metadata_key(k)]:+ del sd[key]diff --git a/invokeai/backend/model_manager/load/model_loaders/flux.py b/invokeai/backend/model_manager/load/model_loaders/flux.pyindex 534d279346..51032e0add 100644--- a/invokeai/backend/model_manager/load/model_loaders/flux.py+++ b/invokeai/backend/model_manager/load/model_loaders/flux.py@@ -91,6 +91,7 @@ from invokeai.backend.quantization.fp8_scaled import (can_stay_quantized,cast_state_dict,dequantize_fp8_scaled,+ expand_weight_scale,extract_comfy_quant_hints,extract_fp8_scaled_layers,full_precision_hints_respected,@@ -1245,9 +1246,12 @@ class Flux2CheckpointModel(ModelLoader):dequantize_fp8_scaled(converted_sd, fp8_layers, torch.bfloat16)fp8_layers = {}- # Safety net for scale layouts the shared extractor does not model (block-wise scales- # whose shape has to be expanded to the weight's). It is a no-op on every checkpoint- # measured so far, because extraction has already taken the scales it understood.+ # Reached only for the raw-fp8 conversion and the metadata strip. Its scale fold cannot+ # fire here: `extract_fp8_scaled_layers` above takes every scale key it is shown, by+ # suffix, whatever the layout — so no weight/scale pair survives this far. Moving this+ # call above that one would make the fold live again, which is what+ # `test_flux2_int8_convrot_loader.py::test_the_extraction_runs_before_the_fold_safety_net`+ # is there to catch.converted_sd = self._dequantize_fp8_weights(converted_sd, keep_fp8=keep_fp8)# Detect architecture from checkpoint keys@@ -1435,34 +1439,25 @@ class Flux2CheckpointModel(ModelLoader):superset: `cast_state_dict` re-applies the same predicate later *with* the model and castswhatever turns out not to be an ``nn.Linear`` weight."""- # Check for ComfyUI-style scale factors. Both spellings are folded here, because the- # metadata strip below removes both — reading only `.weight_scale` meant a `.scale_weight`- # checkpoint had its scales deleted without ever being applied, leaving every quantized- # weight off by 1/weight_scale with nothing logged.+ # Both spellings are folded here, because the metadata strip below removes both — reading+ # only `.weight_scale` meant a `.scale_weight` checkpoint had its scales deleted without ever+ # being applied, leaving every quantized weight off by 1/weight_scale with nothing logged.+ #+ # At the one call site this cannot fire: `extract_fp8_scaled_layers` runs first and takes+ # every scale it is shown, so nothing with a pair reaches here. It stays as the safety net+ # the call site calls it, but folds through the shared expansion now — the local copy that+ # used to stand here got a per-output-channel scale wrong in the same way the Wan and+ # Qwen-Image path did, and an unreachable branch carrying a live defect is the worst of both.for weight_key, scale_key in list(iter_weight_scale_pairs(sd)):- weight = sd[weight_key]- scale = sd[scale_key]-- # Dequantize: convert FP8 to float and multiply by scale- # Note: Float8 types require .float() instead of .to(torch.float32)- weight_float = weight.float()- scale = scale.float()-- # Handle block-wise quantization where scale may have different shape- if scale.dim() > 0 and scale.shape != weight_float.shape and scale.numel() > 1:- for dim in range(len(weight_float.shape)):- if dim < len(scale.shape) and scale.shape[dim] != weight_float.shape[dim]:- block_size = weight_float.shape[dim] // scale.shape[dim]- if block_size > 1:- scale = scale.repeat_interleave(block_size, dim=dim)-- # Do the multiply in float32 for precision, but store bf16 (FLUX.2's compute dtype)- # immediately so the *whole* model is never materialized in float32. Holding every- # dequantized weight as float32 here doubled RAM transiently (~36GB vs ~17GB for a 9B- # model) and was the dominant cold-load spike, especially with two GPUs. The result is- # identical to the previous code, which cast the same values to bf16 a few steps later.- sd[weight_key] = (weight_float * scale).to(torch.bfloat16)- del weight_float+ weight = sd[weight_key].float()+ scale = sd[scale_key].float()++ # Multiply in float32 for precision, but store bf16 (FLUX.2's compute dtype) immediately+ # so the *whole* model is never materialized in float32. Holding every dequantized weight+ # as float32 here doubled RAM transiently (~36GB vs ~17GB for a 9B model) and was the+ # dominant cold-load spike, especially with two GPUs.+ sd[weight_key] = (weight * expand_weight_scale(weight, scale, weight_key)).to(torch.bfloat16)+ del weight# Filter out scale metadata keys and other FP8 metadatakeys_to_remove = [k for k in sd.keys() if is_scale_metadata_key(k)]diff --git a/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.py b/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.pyindex a021f3b7b6..f1886b027a 100644--- a/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.py+++ b/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.py@@ -566,7 +566,7 @@ def _drop_quantization_metadata(sd: dict[str, Any], logger, target_dtype: torch.# `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 input# channels instead of output channels -- wrong on a square weight, a shape error otherwise.- scale = expand_weight_scale(weight, sd[scale_key].float())+ scale = expand_weight_scale(weight, sd[scale_key].float(), weight_key)result = weight * scalesd[weight_key] = result.to(target_dtype) if target_dtype is not None else resultdequantized += 1diff --git a/invokeai/backend/model_manager/load/model_loaders/z_image.py b/invokeai/backend/model_manager/load/model_loaders/z_image.pyindex 8869a08ff4..37fc2fd27e 100644--- a/invokeai/backend/model_manager/load/model_loaders/z_image.py+++ b/invokeai/backend/model_manager/load/model_loaders/z_image.py@@ -1164,7 +1164,7 @@ def _fold_comfy_scaled_weights(sd: dict[str, Any], dtype: torch.dtype) -> int:for weight_key, scale_key in list(iter_weight_scale_pairs(sd)):# 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())+ scale = expand_weight_scale(weight_float, sd[scale_key].float(), weight_key)sd[weight_key] = (weight_float * scale).to(dtype)del weight_floatfolded += 1diff --git a/invokeai/backend/quantization/fp8_scaled.py b/invokeai/backend/quantization/fp8_scaled.pyindex 868c0ebef2..6d38ba2242 100644--- a/invokeai/backend/quantization/fp8_scaled.py+++ b/invokeai/backend/quantization/fp8_scaled.py@@ -414,12 +414,12 @@ def _normalize_weight_scale(scale: torch.Tensor) -> torch.Tensor:return scale.flatten()-def expand_weight_scale(weight: torch.Tensor, scale: torch.Tensor) -> torch.Tensor:+def expand_weight_scale(weight: torch.Tensor, scale: torch.Tensor, path: str | None = None) -> torch.Tensor:"""Broadcast ``scale`` to line up with ``weight`` for an elementwise multiply.Handles the three layouts producers emit:- - per-tensor (0-d / single element) — returned unchanged, broadcasting handles it;+ - per-tensor (0-d / single element) — flattened to 0-d, broadcasting handles it;- per-output-channel (one entry per row) — reshaped to ``(rows, 1, ...)``;- block-wise (one entry per block along one or more dims) — each axis is``repeat_interleave``d by that axis' block size.@@ -428,20 +428,26 @@ def expand_weight_scale(weight: torch.Tensor, scale: torch.Tensor) -> torch.Tensa checkpoint using that layout fails to load outright. That is the layout ComfyUI's owndequantizer expands, and the FLUX.2 loader used to expand before this module centralized thelogic.++ ``path`` is the layer the scale belongs to, and only appears in the error. On a checkpoint with+ a thousand Linears, "which one" is the whole of the diagnosis."""if scale.numel() == 1:- return scale+ # Flattened rather than returned as-is: a `(1, 1, 1)` scale on an `(out, in)` weight would+ # otherwise broadcast back-aligned into a `(1, out, in)` product.+ return scale.reshape(())if scale.dim() <= 1:if scale.numel() != weight.shape[0]:# A 1-D scale is per-output-channel by definition, so any other length means the file# does not describe this weight — most likely a block-wise scale flattened by the# producer, whose block structure is not recoverable from the tensor alone. Say so:- # left to broadcast, torch raises "size of tensor a (32) must match tensor b (7)" from- # inside the multiply, which names neither the layer nor the file.+ # left to broadcast, torch raises "The size of tensor a (16) must match the size of+ # tensor b (7)" from inside the multiply — the weight's *last* axis against the scale,+ # naming neither the layer nor the axis the scale was supposed to describe.raise ValueError(- f"fp8 weight_scale has {scale.numel()} entries but the weight has {weight.shape[0]} output "- "channels; the scale is neither per-tensor nor per-output-channel and cannot be applied. "- "The checkpoint's quantization metadata appears to be malformed."+ f"{f'{path}: ' if path else ''}fp8 weight_scale has {scale.numel()} entries but the weight has "+ f"{weight.shape[0]} output channels; the scale is neither per-tensor nor per-output-channel and "+ "cannot be applied. The checkpoint's quantization metadata appears to be malformed.")return scale.reshape(-1, *([1] * (weight.dim() - 1)))for dim in range(weight.dim()):@@ -540,7 +546,7 @@ def dequantize_fp8_scaled(if weight is None:continueweight = weight.float()- sd[key] = (weight * expand_weight_scale(weight, layer.weight_scale)).to(dtype)+ sd[key] = (weight * expand_weight_scale(weight, layer.weight_scale, path)).to(dtype)return sddiff --git a/tests/backend/model_manager/load/test_flux2_int8_convrot_loader.py b/tests/backend/model_manager/load/test_flux2_int8_convrot_loader.pyindex 5e32218a11..f8d6f0aa36 100644--- a/tests/backend/model_manager/load/test_flux2_int8_convrot_loader.py+++ b/tests/backend/model_manager/load/test_flux2_int8_convrot_loader.py@@ -20,6 +20,7 @@ from invokeai.backend.model_manager.load.model_loaders import fluxfrom invokeai.backend.model_manager.load.model_loaders.flux import Flux2CheckpointModelfrom invokeai.backend.model_manager.load.model_loaders.flux2_state_dict_utils import remap_flux2_layer_pathsfrom invokeai.backend.model_manager.taxonomy import Flux2VariantType, SubModelType+from invokeai.backend.quantization.fp8_scaled import iter_weight_scale_pairsfrom invokeai.backend.quantization.int8_convrot import Int8ConvrotLinearfrom tests.fixtures.loader_seams import Seam, preparefrom tests.fixtures.quantized_payloads import comfy_quant_marker, quantize_scaled_fp8@@ -392,6 +393,32 @@ def _scaled_fp8_checkpoint() -> tuple[dict[str, torch.Tensor], dict[str, torch.Treturn state_dict, originals+def test_the_extraction_runs_before_the_fold_safety_net(monkeypatch, tmp_path) -> None:+ """`_dequantize_fp8_weights` still carries a scale fold, described as a safety net. It cannot+ fire, because `extract_fp8_scaled_layers` runs first and takes every scale key it is shown --+ and that ordering is the whole of the reason. Swap the two calls and the fold goes live over a+ state dict whose scales are already gone, which is a silent no-op on exactly the layers it was+ meant to rescue.++ The ordering is held today by the order the two lines happen to be written in, so it is asserted+ on what the method is actually handed rather than on the lines.+ """+ state_dict, _ = _scaled_fp8_checkpoint()+ assert list(iter_weight_scale_pairs(state_dict)), "the fixture carries no pair to observe"+ handed: list[list[tuple[str, str]]] = []+ original = Flux2CheckpointModel._dequantize_fp8_weights++ def recording(self, sd, keep_fp8=False):+ handed.append(list(iter_weight_scale_pairs(sd)))+ return original(self, sd, keep_fp8=keep_fp8)++ monkeypatch.setattr(Flux2CheckpointModel, "_dequantize_fp8_weights", recording)++ _load(monkeypatch, tmp_path, state_dict)++ assert handed == [[]], f"a weight/scale pair reached the safety net: {handed}"++def test_a_scaled_fp8_checkpoint_still_folds_its_scales(monkeypatch, tmp_path) -> None:"""The fp8 pipeline moved wholesale into the `else` branch, and nothing drove it end to end.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 2f08cb7a9e..480664b084 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@@ -3,11 +3,14 @@A per-output-channel `weight_scale` is 1-D of length `out_features`, and `(out, in) * (out,)`broadcasts on the *last* axis — so a bare multiply scales input channels instead of outputchannels. That is a shape error on a non-square weight (loud) and a silently wrong weight on a-square one (not loud at all). Both loaders below used to do the bare multiply; they now go through-`expand_weight_scale`.--`test_fp8_scaled.py` covers the helper itself. These pin the two call sites, so reverting either-one back to its local loop fails a test rather than passing CI.+square one (not loud at all). Every call site below used to do its own multiply; they now all go+through `expand_weight_scale`.++`test_fp8_scaled.py` covers the helper itself. These pin the call sites, so re-inlining a local+loop at any of them fails a test rather than passing CI — which is how three copies of the+expansion accumulated, two of them wrong. The expected weights are written out literally rather+than derived from `expand_weight_scale`, because an expectation computed by the code under test+cannot tell a correct fold from a fold that is wrong in the same way."""from unittest.mock import MagicMock@@ -15,8 +18,15 @@ from unittest.mock import MagicMockimport pytestimport torch+from invokeai.backend.model_manager.load.model_loaders.comfyui_state_dict_utils import (+ _dequantize_comfyui_fp8,+)+from invokeai.backend.model_manager.load.model_loaders.flux import Flux2CheckpointModelfrom invokeai.backend.model_manager.load.model_loaders.mistral_encoder import _drop_quantization_metadatafrom invokeai.backend.model_manager.load.model_loaders.z_image import _fold_comfy_scaled_weights+from invokeai.backend.quantization.fp8_scaled import (+ WEIGHT_SCALE_SUFFIXES,+)def _per_channel_case(out_features: int = 4, in_features: int = 2):@@ -90,3 +100,82 @@ class TestZImageQwen3EncoderFold:"layer.weight_scale": torch.full((3,), 2.0),})+++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] !=+ weight.shape[dim]`, so a per-output-channel scale -- whose length already equals the row count+ -- was expanded by nothing and left to broadcasting."""++ def _fold(self, weight: torch.Tensor, scale: torch.Tensor, spelling: str = ".weight_scale") -> torch.Tensor:+ sd = {"layer.weight": weight, f"layer{spelling}": scale}+ assert _dequantize_comfyui_fp8(sd, torch.float32) == 1, "the fold did not recognise the pair"+ return sd["layer.weight"]++ @pytest.mark.parametrize("spelling", WEIGHT_SCALE_SUFFIXES)+ def test_both_spellings_of_the_weight_scale_fold_the_same_way(self, spelling: str) -> None:+ """The Qwen2.5-VL producer writes `.scale_weight`; the weight key is derived from whichever+ suffix matched, and getting that derivation wrong for one spelling leaves those layers+ un-scaled with their orphaned scale then stripped, so nothing is logged."""+ folded = self._fold(torch.ones(4, 3), torch.tensor([1.0, 2.0, 3.0, 4.0]), spelling)++ assert torch.equal(folded, torch.tensor([1.0, 2.0, 3.0, 4.0]).reshape(4, 1).expand(4, 3))++ def test_a_square_weight_is_scaled_down_its_rows(self) -> None:+ """The silent case. Columns and rows both "work"; only one is right."""+ weight = torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]])++ folded = self._fold(weight, torch.tensor([2.0, 4.0, 8.0]))++ assert torch.equal(folded, torch.tensor([[2.0, 4.0, 6.0], [16.0, 20.0, 24.0], [56.0, 64.0, 72.0]]))++ def test_a_non_square_weight_folds_instead_of_raising(self) -> None:+ """The loud half of the same defect: broadcasting cannot align 4 against 3 at all."""+ folded = self._fold(torch.ones(4, 3), torch.tensor([1.0, 2.0, 3.0, 4.0]))++ assert torch.equal(folded, torch.tensor([1.0, 2.0, 3.0, 4.0]).reshape(4, 1).expand(4, 3))++ def test_a_block_wise_scale_is_still_expanded(self) -> None:+ """What the local loop existed for, and what the delegation must not lose."""+ folded = self._fold(torch.ones(4, 2), torch.tensor([[1.0], [2.0]]))++ assert torch.equal(folded, torch.tensor([[1.0, 1.0], [1.0, 1.0], [2.0, 2.0], [2.0, 2.0]]))++ def test_a_scale_matching_neither_layout_names_the_layer(self) -> None:+ """ "2 entries but 3 output channels" is not a diagnosis on a checkpoint with a thousand+ Linears; which layer is."""+ with pytest.raises(ValueError, match=r"layer\.weight: fp8 weight_scale has 2 entries"):+ self._fold(torch.ones(3, 3), torch.tensor([2.0, 4.0]))++ def test_a_single_entry_scale_of_any_rank_stays_per_tensor(self) -> None:+ """`(1, 1, 1)` is one number, so it is per-tensor whatever its rank -- but returned as-is it+ back-aligns and the product comes out `(1, out, in)`."""+ folded = self._fold(torch.ones(3, 2), torch.full((1, 1, 1), 2.0))++ assert torch.equal(folded, torch.full((3, 2), 2.0))+++class TestFlux2Fold:+ """FLUX.2's own copy (`flux.py`). It is unreachable at its one call site -- extraction takes+ every scale first -- but it is a method anyone can call, it carried the same defect, and the+ ordering that makes it dead is pinned in `test_flux2_int8_convrot_loader.py` rather than here."""++ def _fold(self, weight: torch.Tensor, scale: torch.Tensor) -> torch.Tensor:+ sd = {"layer.weight": weight, "layer.weight_scale": scale}+ return Flux2CheckpointModel._dequantize_fp8_weights(None, sd)["layer.weight"]++ def test_a_square_weight_is_scaled_down_its_rows(self) -> None:+ weight = torch.ones(3, 3).to(torch.float8_e4m3fn)++ folded = self._fold(weight, torch.tensor([1.0, 2.0, 4.0]))++ rows = torch.tensor([[1.0, 1.0, 1.0], [2.0, 2.0, 2.0], [4.0, 4.0, 4.0]], dtype=torch.bfloat16)+ assert torch.equal(folded, rows), "scale must vary down the rows, not across them"++ def test_the_result_is_bfloat16_rather_than_float32(self) -> None:+ """The multiply runs in float32 for precision but must not leave the whole model there --+ holding every dequantized weight as float32 was the dominant cold-load spike."""+ folded = self._fold(torch.ones(4, 2).to(torch.float8_e4m3fn), torch.tensor([1.0, 2.0, 3.0, 4.0]))++ assert folded.dtype is torch.bfloat16