Skip to content

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.

fix(krea2): decode MXFP8 and block-wise fp8 scales correctly

joshistoast9f2bb70f8856
diff --git a/invokeai/backend/model_manager/load/model_loaders/krea2.py b/invokeai/backend/model_manager/load/model_loaders/krea2.py
index 98cd4a2dec..a402518b93 100644
--- a/invokeai/backend/model_manager/load/model_loaders/krea2.py
+++ b/invokeai/backend/model_manager/load/model_loaders/krea2.py
@@ -5,6 +5,7 @@ from pathlib import Path
from typing import Any, Optional
import accelerate
+import torch
from transformers import AutoConfig, AutoTokenizer
from invokeai.backend.model_manager.configs.base import Checkpoint_Config_Base, Diffusers_Config_Base
@@ -25,6 +26,7 @@ from invokeai.backend.model_manager.taxonomy import (
SubModelType,
)
from invokeai.backend.quantization.gguf.loaders import gguf_sd_loader
+from invokeai.backend.quantization.scaled_fp8 import dequantize_scaled_fp8
from invokeai.backend.util.devices import TorchDevice
@@ -89,27 +91,16 @@ def _is_native_krea2_format(sd: dict[str, Any]) -> bool:
)
-def _dequantize_scaled_fp8(sd: dict[str, Any]) -> dict[str, Any]:
- """Dequantize ComfyUI 'scaled fp8' weights: ``dequant = weight.float() * weight_scale``.
+def _dequantize_scaled_fp8(sd: dict[str, Any], compute_dtype: torch.dtype) -> dict[str, Any]:
+ """Dequantize ComfyUI 'scaled fp8' weights to ``compute_dtype``, returning the same dict.
- Each quantized layer stores an fp8 ``<name>.weight`` plus a (usually scalar) ``<name>.weight_scale``.
- Returns a new dict with the weights dequantized to float and the ``.weight_scale`` keys removed.
- No-op if there are no scale keys.
+ Delegates to the shared implementation so this stays in step with the Qwen-Image loader; the
+ two previously had independent copies, and this one had drifted — it multiplied by the raw
+ scale (crashing on the block-wise scales real checkpoints ship) and dequantized via float32
+ (spiking peak RAM to ~4 bytes/param). No-op when there are no scale keys.
"""
- import torch
-
- scale_keys = [k for k in sd if isinstance(k, str) and k.endswith(".weight_scale")]
- if not scale_keys:
- return sd
- out = dict(sd)
- 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
- del out[scale_key]
- return out
+ dequantize_scaled_fp8(sd, compute_dtype)
+ return sd
def _convert_krea2_native_to_diffusers(sd: dict[str, Any]) -> dict[str, Any]:
@@ -331,17 +322,19 @@ class Krea2CheckpointModel(ModelLoader):
raise TypeError(f"Expected Main_Checkpoint_Krea2_Config, got {type(config).__name__}.")
model_path = Path(config.path)
+ target_device = TorchDevice.choose_torch_device()
+ model_dtype = TorchDevice.choose_bfloat16_safe_dtype(target_device)
+
sd = load_file(model_path)
sd = _strip_comfyui_prefix(sd)
- # ComfyUI 'scaled fp8' checkpoints: fold the per-tensor weight_scale into the weights (→ float).
- sd = _dequantize_scaled_fp8(sd)
+ # ComfyUI 'scaled fp8' checkpoints: fold the weight_scale into the weights. Dequantized
+ # straight to the model dtype — via float32 this needs ~4 bytes/param of host RAM, which
+ # for a 12.5 GB fp8 transformer is 50 GB and unloadable on a 32 GB machine.
+ sd = _dequantize_scaled_fp8(sd, model_dtype)
# Native/ComfyUI key naming → diffusers Krea2Transformer2DModel keys.
if _is_native_krea2_format(sd):
sd = _convert_krea2_native_to_diffusers(sd)
- target_device = TorchDevice.choose_torch_device()
- model_dtype = TorchDevice.choose_bfloat16_safe_dtype(target_device)
-
with accelerate.init_empty_weights():
model = Krea2Transformer2DModel(**KREA2_TRANSFORMER_CONFIG)
@@ -568,7 +561,9 @@ class Qwen3VLEncoderCheckpointLoader(ModelLoader):
getattr(t, "dtype", None) in (torch.float8_e4m3fn, torch.float8_e5m2) for t in sd.values()
)
# ComfyUI 'scaled fp8': fold weight_scale into the weights, then drop quantization metadata.
- sd = _dequantize_scaled_fp8(sd)
+ # Dequantized straight to the model dtype rather than via float32, which would double peak
+ # host RAM for an 8.9 GB encoder.
+ sd = _dequantize_scaled_fp8(sd, model_dtype)
for k in list(sd.keys()):
if isinstance(k, str) and (k.endswith(".comfy_quant") or "scale_input" in k):
del sd[k]
diff --git a/invokeai/backend/model_manager/load/model_loaders/qwen_image.py b/invokeai/backend/model_manager/load/model_loaders/qwen_image.py
index 9091979499..2e572dbdde 100644
--- a/invokeai/backend/model_manager/load/model_loaders/qwen_image.py
+++ b/invokeai/backend/model_manager/load/model_loaders/qwen_image.py
@@ -27,6 +27,7 @@ from invokeai.backend.model_manager.taxonomy import (
)
from invokeai.backend.quantization.gguf.ggml_tensor import GGMLTensor
from invokeai.backend.quantization.gguf.loaders import gguf_sd_loader
+from invokeai.backend.quantization.scaled_fp8 import dequantize_scaled_fp8
from invokeai.backend.util.devices import TorchDevice
@@ -51,40 +52,10 @@ def _strip_comfyui_prefix(sd: dict) -> dict:
def _dequantize_comfyui_fp8(sd: dict, compute_dtype: torch.dtype) -> int:
"""Dequantize ComfyUI-style fp8_scaled weights in-place. Returns count of dequantized tensors.
- Weights are dequantized directly to `compute_dtype` (typically bf16) instead of via a
- full-precision float32 intermediate. The previous float32 path materialised a complete
- 4-byte/param copy of the model before a separate downcast pass, spiking peak RAM to ~2x the
- final bf16 size (~80GB for the 20B Qwen-Image transformer). Multiplying in the target dtype
- keeps the dict at the bf16 model size plus a single transient tensor. fp8 has only 3 mantissa
- bits and bf16 shares float32's exponent range, so the bf16 multiply loses no meaningful
- precision here.
-
- Two key naming schemes are in the wild:
- - `<path>.weight` + `<path>.weight_scale` (FLUX, Z-Image style)
- - `<path>.weight` + `<path>.scale_weight` (Qwen2.5-VL fp8_scaled style, also
- emits `<path>.scale_input` for activation scaling that we discard).
+ Thin wrapper over the shared implementation, which this function's logic was extracted into so
+ the Krea-2 loader could stop carrying a divergent copy.
"""
- scale_suffixes = (".weight_scale", ".scale_weight")
- weight_scale_keys = [k for k in sd.keys() if isinstance(k, str) and k.endswith(scale_suffixes)]
- count = 0
- for scale_key in weight_scale_keys:
- for suffix in scale_suffixes:
- if scale_key.endswith(suffix):
- weight_key = scale_key[: -len(suffix)] + ".weight"
- break
- if weight_key not in sd:
- continue
- weight = 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
- count += 1
- return count
+ return dequantize_scaled_fp8(sd, compute_dtype)
def _remap_qwen_vl_checkpoint_keys(sd: dict) -> dict:
diff --git a/invokeai/backend/quantization/scaled_fp8.py b/invokeai/backend/quantization/scaled_fp8.py
new file mode 100644
index 0000000000..589fe5e3ec
--- /dev/null
+++ b/invokeai/backend/quantization/scaled_fp8.py
@@ -0,0 +1,107 @@
+"""Dequantization for scaled-fp8 single-file checkpoints (ComfyUI "scaled fp8" and MXFP8).
+
+A quantized layer stores an fp8 ``<name>.weight`` alongside a scale tensor. Dequantizing is
+``weight * scale``, but three details make a naive implementation wrong, each in a different way:
+
+**E8M0 (microscaling) scales are exponents, not multipliers.** MXFP8 checkpoints store the scale
+as a ``uint8`` biased power-of-two exponent, so the multiplier is ``2 ** (scale - 127)``. Treating
+the raw byte as the multiplier does not crash — it silently scales weights by ~10^6 (a real
+Krea-2 MXFP8 transformer goes from std 0.03 to std 14000), so the model loads and generates
+garbage. Distinguished here by dtype: an integer scale is an exponent, a float scale is a
+multiplier. A linear scale is never stored as an integer.
+
+**Block-wise scales.** The scale is often not a scalar. Microscaling uses one scale per block of
+32 values along the last dim, so a ``(6144, 6144)`` weight carries a ``(6144, 192)`` scale. Plain
+multiplication cannot broadcast that and raises "The size of tensor a (3072) must match the size
+of tensor b (384)". The scale has to be expanded with ``repeat_interleave`` first.
+
+**Dequantizing straight to the target dtype.** Going via ``.float()`` materialises a complete
+4-byte/param copy of the model before a separate downcast pass, spiking peak host RAM to ~2x the
+final bf16 size — 50 GB for a 12.5 GB fp8 Krea-2 transformer, which is unloadable on a 32 GB
+machine. Multiplying in the target dtype keeps the dict at the bf16 model size plus one transient
+tensor. fp8 has only 3 mantissa bits and bf16 shares float32's exponent range, so the bf16
+multiply loses no meaningful precision.
+
+This lives here rather than in a loader because the Krea-2 and Qwen-Image loaders both need it,
+and two independent copies had already drifted: the Krea-2 copy lacked every fix above.
+
+Two scale-key naming schemes are in the wild:
+ - ``<path>.weight`` + ``<path>.weight_scale`` (FLUX, Z-Image, Krea-2 style)
+ - ``<path>.weight`` + ``<path>.scale_weight`` (Qwen2.5-VL fp8_scaled style, which also emits
+ ``<path>.scale_input`` for activation scaling that we discard)
+"""
+
+from typing import Any
+
+import torch
+
+SCALE_SUFFIXES = (".weight_scale", ".scale_weight")
+
+#: Exponent bias for OCP Microscaling E8M0 scale bytes.
+E8M0_EXPONENT_BIAS = 127
+
+
+def _to_plain_tensor(value: Any) -> Any:
+ """Dequantize a GGMLTensor to a plain tensor; pass anything else through."""
+ if hasattr(value, "get_dequantized_tensor"):
+ return value.get_dequantized_tensor()
+ return value
+
+
+def to_scale_multiplier(scale: torch.Tensor, compute_dtype: torch.dtype) -> torch.Tensor:
+ """Resolve a stored scale tensor to the multiplier to apply to the weights.
+
+ An integer scale is an E8M0 biased exponent (microscaling), so it becomes ``2 ** (s - 127)``.
+ A float scale is already a linear multiplier and is only cast. ``exp2`` is evaluated in float32
+ before the cast so the intermediate cannot overflow a narrow dtype; every result is an exact
+ power of two and so is representable in bf16/fp16 without rounding.
+ """
+ if not scale.dtype.is_floating_point:
+ return torch.exp2(scale.float() - E8M0_EXPONENT_BIAS).to(compute_dtype)
+
+ return scale.to(compute_dtype)
+
+
+def expand_scale_to_weight(weight: torch.Tensor, scale: torch.Tensor) -> torch.Tensor:
+ """Broadcast a possibly block-wise ``scale`` up to ``weight``'s shape.
+
+ A scalar scale is returned untouched — it broadcasts natively. A block-wise scale is repeated
+ along each mismatched dimension by the block size implied by the shape ratio (32 for MXFP8).
+ """
+ if scale.shape == weight.shape or scale.numel() == 1:
+ return scale
+
+ 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)
+
+ return scale
+
+
+def dequantize_scaled_fp8(sd: dict[str, Any], compute_dtype: torch.dtype) -> int:
+ """Dequantize scaled-fp8 weights in ``sd`` in place; returns the number converted.
+
+ Weights are dequantized directly to ``compute_dtype`` (see the module docstring on why not via
+ float32). Scale keys are removed, including orphans with no matching weight — nothing can be
+ multiplied by those, and leaving them behind would inflate the caller's size accounting.
+ """
+ scale_keys = [k for k in sd if isinstance(k, str) and k.endswith(SCALE_SUFFIXES)]
+ count = 0
+
+ for scale_key in scale_keys:
+ for suffix in SCALE_SUFFIXES:
+ if scale_key.endswith(suffix):
+ weight_key = scale_key[: -len(suffix)] + ".weight"
+ break
+
+ if weight_key in sd:
+ weight = torch.as_tensor(_to_plain_tensor(sd[weight_key])).to(compute_dtype)
+ scale = to_scale_multiplier(torch.as_tensor(_to_plain_tensor(sd[scale_key])), compute_dtype)
+ sd[weight_key] = weight * expand_scale_to_weight(weight, scale)
+ count += 1
+
+ del sd[scale_key]
+
+ return count
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.py
index c75873a8fd..25f8c1896e 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
@@ -90,22 +90,101 @@ class TestDequantizeScaledFp8:
"layer.weight": torch.tensor([2.0, 4.0]),
"layer.weight_scale": torch.tensor(0.5),
}
- out = _dequantize_scaled_fp8(sd)
+ out = _dequantize_scaled_fp8(sd, torch.float32)
assert "layer.weight_scale" not in out
assert torch.allclose(out["layer.weight"], torch.tensor([1.0, 2.0]))
def test_noop_without_scale_keys(self) -> None:
sd = {"layer.weight": torch.tensor([2.0, 4.0])}
- out = _dequantize_scaled_fp8(sd)
+ out = _dequantize_scaled_fp8(sd, torch.float32)
assert out is sd
def test_orphan_scale_key_is_dropped(self) -> None:
# A scale key with no matching weight is simply removed (nothing to multiply).
sd = {"other.weight": torch.tensor([1.0]), "layer.weight_scale": torch.tensor(0.5)}
- out = _dequantize_scaled_fp8(sd)
+ out = _dequantize_scaled_fp8(sd, torch.float32)
assert "layer.weight_scale" not in out
assert "other.weight" in out
+ def test_expands_block_wise_scales(self) -> None:
+ """Regression: real Krea-2 fp8 checkpoints carry one scale per block of rows.
+
+ A (4, 2) weight with a (2, 1) scale used to raise "The size of tensor a (4) must match the
+ size of tensor b (2) at non-singleton dimension 0" because the raw scale was multiplied in
+ directly. Each scale must cover its block of rows.
+ """
+ sd = {
+ "layer.weight": torch.tensor([[2.0, 2.0], [4.0, 4.0], [6.0, 6.0], [8.0, 8.0]]),
+ "layer.weight_scale": torch.tensor([[0.5], [2.0]]),
+ }
+
+ out = _dequantize_scaled_fp8(sd, torch.float32)
+
+ expected = torch.tensor([[1.0, 1.0], [2.0, 2.0], [12.0, 12.0], [16.0, 16.0]])
+ assert torch.allclose(out["layer.weight"], expected)
+
+ def test_dequantizes_to_the_requested_dtype_without_a_float32_detour(self) -> None:
+ """The dtype is the whole point: a float32 intermediate doubles peak host RAM.
+
+ A 12.5 GB fp8 transformer needs ~50 GB via float32 versus ~25 GB straight to bf16, which is
+ the difference between loadable and OOM-killed on a 32 GB machine.
+ """
+ sd = {
+ "layer.weight": torch.tensor([2.0, 4.0], dtype=torch.float32),
+ "layer.weight_scale": torch.tensor(0.5, dtype=torch.float32),
+ }
+
+ out = _dequantize_scaled_fp8(sd, torch.bfloat16)
+
+ assert out["layer.weight"].dtype is torch.bfloat16
+
+ def test_decodes_e8m0_microscaling_exponents_rather_than_multiplying_the_byte(self) -> None:
+ """Regression: MXFP8 stores the scale as a uint8 biased power-of-two exponent.
+
+ Multiplying by the raw byte does not crash — it scales weights by ~10^6, so the model loads
+ and silently generates garbage. A real Krea-2 MXFP8 transformer goes from std ~0.03 to
+ ~14000 that way, which is exactly the failure this guards.
+ """
+ # Byte 127 is 2**0, so it must leave the weight untouched; 128 is 2**1 and 126 is 2**-1.
+ sd = {
+ "layer.weight": torch.tensor([[4.0], [4.0], [4.0]]),
+ "layer.weight_scale": torch.tensor([[127], [128], [126]], dtype=torch.uint8),
+ }
+
+ out = _dequantize_scaled_fp8(sd, torch.float32)
+
+ assert torch.allclose(out["layer.weight"], torch.tensor([[4.0], [8.0], [2.0]]))
+
+ def test_treats_a_float_scale_as_a_plain_multiplier(self) -> None:
+ # ComfyUI scaled-fp8 (FLUX / Z-Image / Qwen style) stores a linear float scale, which must
+ # not be reinterpreted as an exponent.
+ sd = {"layer.weight": torch.tensor([4.0]), "layer.weight_scale": torch.tensor(2.0)}
+
+ out = _dequantize_scaled_fp8(sd, torch.float32)
+
+ assert torch.allclose(out["layer.weight"], torch.tensor([8.0]))
+
+ def test_expands_a_block_wise_e8m0_scale_over_its_block(self) -> None:
+ # The combination that actually ships: block-wise scales that are also E8M0 exponents.
+ sd = {
+ "layer.weight": torch.tensor([[2.0, 2.0, 2.0, 2.0]]),
+ "layer.weight_scale": torch.tensor([[128, 126]], dtype=torch.uint8),
+ }
+
+ out = _dequantize_scaled_fp8(sd, torch.float32)
+
+ # First block doubles, second halves.
+ assert torch.allclose(out["layer.weight"], torch.tensor([[4.0, 4.0, 1.0, 1.0]]))
+
+ def test_supports_the_scale_weight_naming_variant(self) -> None:
+ # Qwen2.5-VL fp8_scaled exports use `.scale_weight` rather than `.weight_scale`.
+ sd = {"layer.weight": torch.tensor([2.0]), "layer.scale_weight": torch.tensor(3.0)}
+
+ out = _dequantize_scaled_fp8(sd, torch.float32)
+
+ assert "layer.scale_weight" not in out
+ assert torch.allclose(out["layer.weight"], torch.tensor([6.0]))
+
class TestConvertKrea2NativeToDiffusers:
def test_top_level_module_renames(self) -> None:
@@ -357,3 +436,38 @@ class TestConvertedShapesMatchRealKrea2Transformer:
for name in table_keys:
if name.startswith(("transformer_blocks.", "text_fusion.")):
assert expected[name][0] == 6, f"{name} expected 6 modulation rows, got {expected[name]}"
+
+
+class TestDequantCallSites:
+ """Guards the arity of every `_dequantize_scaled_fp8` call inside the Krea-2 loader.
+
+ The loader dequantizes in two places — the transformer single-file path and the Qwen3-VL
+ encoder single-file path — and only the first is covered by a functional test. When the
+ function gained its `compute_dtype` parameter, the encoder call site was missed and shipped a
+ TypeError that only surfaced at generation time.
+
+ mypy would catch this (`strict = true` flags a missing positional argument), but the module
+ already carries hundreds of pre-existing errors, so it cannot serve as a gate. This asserts the
+ property directly and cheaply instead.
+ """
+
+ def test_every_call_site_passes_a_compute_dtype(self) -> None:
+ import ast
+ import inspect
+
+ from invokeai.backend.model_manager.load.model_loaders import krea2
+
+ tree = ast.parse(inspect.getsource(krea2))
+ calls = [
+ node
+ for node in ast.walk(tree)
+ if isinstance(node, ast.Call)
+ and isinstance(node.func, ast.Name)
+ and node.func.id == "_dequantize_scaled_fp8"
+ ]
+
+ # Both single-file paths must be present; a dropped call site is as much a bug as a
+ # miscalled one.
+ assert len(calls) == 2, f"expected 2 call sites, found {len(calls)}"
+ for call in calls:
+ assert len(call.args) == 2, f"call at line {call.lineno} passes {len(call.args)} args, expected 2"