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(fp8): handle both weight-scale spellings in every loader
Alexander Eichhorn0eca15fdcd46
diff --git a/invokeai/backend/model_manager/load/model_loaders/flux.py b/invokeai/backend/model_manager/load/model_loaders/flux.pyindex 0a9c0bc340..e3b95de590 100644--- a/invokeai/backend/model_manager/load/model_loaders/flux.py+++ b/invokeai/backend/model_manager/load/model_loaders/flux.py@@ -83,6 +83,8 @@ from invokeai.backend.model_manager.util.model_util import (from invokeai.backend.quantization.fp8_scaled import (can_stay_quantized,cast_state_dict,+ is_scale_metadata_key,+ iter_weight_scale_pairs,predict_cast_state_dict_size,should_keep_fp8_weights,)@@ -1116,44 +1118,37 @@ 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- weight_scale_keys = [k for k in sd.keys() if isinstance(k, str) and k.endswith(".weight_scale")]-- for scale_key in weight_scale_keys:- # Get the corresponding weight key- weight_key = scale_key.replace(".weight_scale", ".weight")- if weight_key in 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+ # 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.+ 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# Filter out scale metadata keys and other FP8 metadata- keys_to_remove = [- k- for k in sd.keys()- if isinstance(k, str)- and (k.endswith(".weight_scale") or k.endswith(".scale_weight") or "comfy_quant" in k or k == "scaled_fp8")- ]+ keys_to_remove = [k for k in sd.keys() if is_scale_metadata_key(k)]for k in keys_to_remove:del sd[k]diff --git a/invokeai/backend/model_manager/load/model_loaders/krea2.py b/invokeai/backend/model_manager/load/model_loaders/krea2.pyindex ecb1cb336a..c50e1301cf 100644--- a/invokeai/backend/model_manager/load/model_loaders/krea2.py+++ b/invokeai/backend/model_manager/load/model_loaders/krea2.py@@ -26,12 +26,14 @@ from invokeai.backend.model_manager.taxonomy import ()from invokeai.backend.quantization.fp8_scaled import (FP8_DTYPE,+ WEIGHT_SCALE_SUFFIXES,attach_fp8_scales,cast_state_dict,dequantize_fp8_scaled,extract_comfy_quant_hints,extract_fp8_scaled_layers,full_precision_hints_respected,+ iter_weight_scale_pairs,parse_quantization_metadata,predict_cast_state_dict_size,read_safetensors_metadata,@@ -128,18 +130,19 @@ def _dequantize_scaled_fp8(sd: dict[str, Any], dtype: "torch.dtype") -> dict[str"""import torch- scale_keys = [k for k in sd if isinstance(k, str) and k.endswith(".weight_scale")]+ scale_keys = [k for k in sd if isinstance(k, str) and k.endswith(WEIGHT_SCALE_SUFFIXES)]if not scale_keys:return sdout = dict(sd)+ for weight_key, scale_key in iter_weight_scale_pairs(sd):+ weight = torch.as_tensor(_to_plain_tensor(out[weight_key])).float()+ scale = torch.as_tensor(_to_plain_tensor(out[scale_key])).float()+ out[weight_key] = (weight * scale).to(dtype)+ del weight+ # Every scale key goes, including one whose `.weight` is missing: there is nothing to fold it+ # into, and leaving the orphan behind trips `load_state_dict(..., strict=True)`.for scale_key in scale_keys:- weight_key = scale_key.replace(".weight_scale", ".weight")- if weight_key in out:- weight = torch.as_tensor(_to_plain_tensor(out[weight_key])).float()- scale = torch.as_tensor(_to_plain_tensor(out[scale_key])).float()- out[weight_key] = (weight * scale).to(dtype)- del weight- del out[scale_key]+ out.pop(scale_key, None)return outdiff --git a/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.py b/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.pyindex 6aad71a71c..0707ae19bf 100644--- a/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.py+++ b/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.py@@ -37,6 +37,7 @@ from invokeai.backend.model_manager.taxonomy import (ModelType,SubModelType,)+from invokeai.backend.quantization.fp8_scaled import is_scale_metadata_key, iter_weight_scale_pairsfrom invokeai.backend.quantization.gguf.ggml_tensor import GGMLTensorfrom invokeai.backend.quantization.gguf.loaders import gguf_sd_loaderfrom invokeai.backend.util.devices import TorchDevice@@ -357,12 +358,8 @@ def _drop_quantization_metadata(sd: dict[str, Any], logger, target_dtype: torch.24B fp8 encoder that difference is tens of GB — enough to OOM machines that canotherwise load the model."""- weight_scale_keys = [k for k in sd.keys() if isinstance(k, str) and k.endswith(".weight_scale")]dequantized = 0- for scale_key in weight_scale_keys:- weight_key = scale_key[: -len(".weight_scale")] + ".weight"- if weight_key not in sd:- continue+ for weight_key, scale_key in list(iter_weight_scale_pairs(sd)):weight = sd[weight_key].float()scale = sd[scale_key].float()if scale.shape != weight.shape and scale.numel() > 1:@@ -377,11 +374,12 @@ def _drop_quantization_metadata(sd: dict[str, Any], logger, target_dtype: torch.if dequantized:logger.info(f"Dequantized {dequantized} Comfy-Org-style quantized weights")- drop_suffixes = (".weight_scale", ".input_scale", ".scale")+ # `is_scale_metadata_key` covers both spellings of the weight and input scales; `.scale` stays+ # here because it is this producer's own spelling and is not a scaled-fp8 key.drop_keys = [kfor k in sd.keys()- if isinstance(k, str) and (k.endswith(drop_suffixes) or "comfy_quant" in k or k.startswith("scaled_fp8"))+ if isinstance(k, str) and (is_scale_metadata_key(k) or k.endswith(".scale") or k.startswith("scaled_fp8"))]for k in drop_keys:del sd[k]diff --git a/invokeai/backend/model_manager/load/model_loaders/z_image.py b/invokeai/backend/model_manager/load/model_loaders/z_image.pyindex ddb4a49303..47e9015c4a 100644--- a/invokeai/backend/model_manager/load/model_loaders/z_image.py+++ b/invokeai/backend/model_manager/load/model_loaders/z_image.py@@ -41,6 +41,8 @@ from invokeai.backend.quantization.fp8_scaled import (extract_comfy_quant_hints,extract_fp8_scaled_layers,full_precision_hints_respected,+ is_scale_metadata_key,+ iter_weight_scale_pairs,parse_quantization_metadata,predict_cast_state_dict_size,read_safetensors_metadata,@@ -1079,46 +1081,43 @@ class Qwen3EncoderCheckpointLoader(ModelLoader):# Dequantization formula: dequantized = weight.to(dtype) * weight_scale# Reference: https://github.com/Comfy-Org/ComfyUI/blob/master/QUANTIZATION.mdoriginal_key_count = len(sd)- weight_scale_keys = [k for k in sd.keys() if k.endswith(".weight_scale")]dequantized_count = 0- for scale_key in weight_scale_keys:- # Get the corresponding weight key (remove "_scale" suffix)- weight_key = scale_key.replace(".weight_scale", ".weight")- if weight_key in sd:- weight = sd[weight_key]- scale = sd[scale_key]- # Dequantize: convert to float and multiply by scale- # Handle block-wise quantization (e.g., FP4 with block_size=8)- # where scale has shape [weight_dim / block_size, ...]- # Note: Float8 types (e.g., float8_e4m3fn) require .float() instead of .to(torch.float32)- # as PyTorch doesn't support direct type promotion for Float8 types- weight_float = weight.float()- scale = scale.float()- if scale.shape != weight_float.shape and scale.numel() > 1:- # Block-wise quantization: need to expand scale to match weight shape- # Find which dimension differs and repeat scale along that dimension- 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:- # Repeat scale along this dimension to match weight shape- scale = scale.repeat_interleave(block_size, dim=dim)- # Multiply in float32 for precision, but store the compute dtype immediately so the- # *whole model* is never materialized in float32. Keeping every dequantized weight as- # float32 until the caller's later cast quadruples the per-parameter cost (4 bytes vs- # 1 on disk) and dominates the cold-load RAM peak — enough to swap a 32 GB machine.- # Same fix as in the FLUX.2 and Krea-2 loaders.- sd[weight_key] = (weight_float * scale).to(model_dtype)- del weight_float- dequantized_count += 1+ # Both spellings, because the metadata strip below removes both.+ for weight_key, scale_key in list(iter_weight_scale_pairs(sd)):+ weight = sd[weight_key]+ scale = sd[scale_key]+ # Dequantize: convert to float and multiply by scale+ # Handle block-wise quantization (e.g., FP4 with block_size=8)+ # where scale has shape [weight_dim / block_size, ...]+ # Note: Float8 types (e.g., float8_e4m3fn) require .float() instead of .to(torch.float32)+ # as PyTorch doesn't support direct type promotion for Float8 types+ weight_float = weight.float()+ scale = scale.float()+ if scale.shape != weight_float.shape and scale.numel() > 1:+ # Block-wise quantization: need to expand scale to match weight shape+ # Find which dimension differs and repeat scale along that dimension+ 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:+ # Repeat scale along this dimension to match weight shape+ scale = scale.repeat_interleave(block_size, dim=dim)+ # Multiply in float32 for precision, but store the compute dtype immediately so the+ # *whole model* is never materialized in float32. Keeping every dequantized weight as+ # float32 until the caller's later cast quadruples the per-parameter cost (4 bytes vs+ # 1 on disk) and dominates the cold-load RAM peak — enough to swap a 32 GB machine.+ # Same fix as in the FLUX.2 and Krea-2 loaders.+ sd[weight_key] = (weight_float * scale).to(model_dtype)+ del weight_float+ dequantized_count += 1if dequantized_count > 0:logger.info(f"Dequantized {dequantized_count} ComfyUI quantized weights")# Filter out ComfyUI quantization metadata keys (comfy_quant, weight_scale)# These are no longer needed after dequantization- comfy_metadata_keys = [k for k in sd.keys() if "comfy_quant" in k or "weight_scale" in k]+ comfy_metadata_keys = [k for k in sd.keys() if is_scale_metadata_key(k)]for k in comfy_metadata_keys:del sd[k]if comfy_metadata_keys:diff --git a/invokeai/backend/quantization/fp8_scaled.py b/invokeai/backend/quantization/fp8_scaled.pyindex df245316b2..35e9062775 100644--- a/invokeai/backend/quantization/fp8_scaled.py+++ b/invokeai/backend/quantization/fp8_scaled.py@@ -141,6 +141,43 @@ def extract_comfy_quant_hints(sd: dict[str, Any]) -> dict[str, dict[str, Any]]:return hints+def iter_weight_scale_pairs(sd: Mapping[str, Any]) -> Iterable[tuple[str, str]]:+ """Yield ``(weight_key, scale_key)`` for every weight scale in ``sd``, in either spelling.++ For loaders that fold the scale into the weight themselves instead of going through+ :func:`extract_fp8_scaled_layers`. Matching only ``.weight_scale`` is the failure that keeps+ recurring: a ``.scale_weight`` checkpoint then either loses its scales silently (if the loader+ strips both spellings afterwards, leaving the weight off by ``1/weight_scale``) or trips+ ``load_state_dict(..., strict=True)`` on the leftover key. Pairs whose ``.weight`` is absent are+ skipped, so a stray scale cannot invent one.+ """+ for key in list(sd.keys()):+ if not isinstance(key, str):+ continue+ for suffix in WEIGHT_SCALE_SUFFIXES:+ if key.endswith(suffix):+ weight_key = f"{key[: -len(suffix)]}.weight"+ if weight_key in sd:+ yield weight_key, key+ break+++def is_scale_metadata_key(key: Any) -> bool:+ """Whether ``key`` is fp8 scale/quantization metadata rather than a model tensor.++ Covers both spellings of the weight and input scales plus the marker keys producers emit, so+ callers strip exactly what they were able to interpret.+ """+ if not isinstance(key, str):+ return False+ return (+ key.endswith(WEIGHT_SCALE_SUFFIXES)+ or key.endswith(INPUT_SCALE_SUFFIXES)+ or COMFY_QUANT_SUFFIX.strip(".") in key+ or key in STRAY_METADATA_KEYS+ )++def _strip_scale_suffix(key: str) -> tuple[str, bool] | None:"""Return ``(module path, is_input_scale)``, or None if ``key`` is not a scale key."""for suffix in WEIGHT_SCALE_SUFFIXES:diff --git a/tests/backend/model_manager/load/test_krea2_state_dict_utils.py b/tests/backend/model_manager/load/test_krea2_state_dict_utils.pyindex b5abded5d5..5a91084d6f 100644--- a/tests/backend/model_manager/load/test_krea2_state_dict_utils.py+++ b/tests/backend/model_manager/load/test_krea2_state_dict_utils.py@@ -125,6 +125,24 @@ class TestDequantizeScaledFp8:assert "layer.weight_scale" not in outassert "other.weight" in out+ def test_the_scale_weight_spelling_is_folded_too(self) -> None:+ # Producers use both spellings. Reading only `.weight_scale` left the weight unscaled and+ # dropped the key anyway, so the error was silent - off by exactly 1/weight_scale.+ sd = {"layer.weight": torch.tensor([2.0, 4.0]), "layer.scale_weight": torch.tensor(0.5)}++ out = _dequantize_scaled_fp8(sd, torch.bfloat16)++ assert torch.equal(out["layer.weight"], torch.tensor([1.0, 2.0], dtype=torch.bfloat16))+ assert "layer.scale_weight" not in out++ def test_an_orphan_scale_weight_is_dropped_too(self) -> None:+ sd = {"other.weight": torch.tensor([1.0]), "layer.scale_weight": torch.tensor(0.5)}++ out = _dequantize_scaled_fp8(sd, torch.bfloat16)++ assert "layer.scale_weight" not in out+ assert "other.weight" in out+class TestConvertKrea2NativeToDiffusers:def test_top_level_module_renames(self) -> None:diff --git a/tests/backend/quantization/test_fp8_scaled.py b/tests/backend/quantization/test_fp8_scaled.pyindex df2e109f29..af6c68565b 100644--- a/tests/backend/quantization/test_fp8_scaled.py+++ b/tests/backend/quantization/test_fp8_scaled.py@@ -15,6 +15,8 @@ from invokeai.backend.quantization.fp8_scaled import (device_supports_fp8_matmul,extract_comfy_quant_hints,extract_fp8_scaled_layers,+ is_scale_metadata_key,+ iter_weight_scale_pairs,parse_quantization_metadata,predict_cast_state_dict_size,reset_fp8_matmul_support_cache,@@ -725,3 +727,46 @@ class TestCustomLinearIntegration:rel = ((fp8.float() - baseline.float()).norm() / baseline.float().norm()).item()assert rel < 0.1, f"fp8 matmul diverges from the dequantized path by {rel:.4f}"+++class TestScaleSpellingHelpers:+ """Both spellings of the weight scale must be handled everywhere.++ Reading only `.weight_scale` is the mistake that keeps recurring in the per-loader dequant+ helpers. Depending on what the loader strips afterwards it either deletes a `.scale_weight`+ without applying it — leaving the weight off by `1/weight_scale`, silently — or leaves the key+ behind for `load_state_dict(..., strict=True)` to reject.+ """++ @pytest.mark.parametrize("spelling", [".weight_scale", ".scale_weight"])+ def test_pairs_are_found_in_either_spelling(self, spelling: str) -> None:+ sd = {"blk.weight": torch.ones(2, 2), f"blk{spelling}": torch.tensor(0.5)}++ assert list(iter_weight_scale_pairs(sd)) == [("blk.weight", f"blk{spelling}")]++ def test_a_scale_without_its_weight_is_not_paired(self) -> None:+ # Pairing it would invent a weight key the checkpoint never had.+ sd = {"other.weight": torch.ones(1), "blk.weight_scale": torch.tensor(0.5)}++ assert list(iter_weight_scale_pairs(sd)) == []++ def test_non_string_keys_are_ignored(self) -> None:+ # `.pt`/`.ckpt` sources can carry int keys; `endswith` would raise on them.+ assert list(iter_weight_scale_pairs({0: torch.ones(1)})) == []++ @pytest.mark.parametrize(+ "key",+ [".weight_scale", ".scale_weight", ".input_scale", ".scale_input"],+ )+ def test_metadata_keys_are_recognized_in_either_spelling(self, key: str) -> None:+ assert is_scale_metadata_key(f"blk{key}")++ @pytest.mark.parametrize("key", ["blk.comfy_quant", "scaled_fp8"])+ def test_marker_keys_are_recognized(self, key: str) -> None:+ assert is_scale_metadata_key(key)++ @pytest.mark.parametrize("key", ["blk.weight", "blk.bias", "norm.scale", 0])+ def test_model_tensors_are_not_mistaken_for_metadata(self, key: object) -> None:+ # `norm.scale` is a real learned parameter in several architectures - stripping it would+ # delete weights, and it is why this cannot just match "scale" anywhere in the key.+ assert not is_scale_metadata_key(key)