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.

feat(fp8): run scaled fp8 FLUX.2 checkpoints on the tensor cores

Alexander Eichhorn587c0fa74a35
diff --git a/invokeai/backend/model_manager/load/model_loaders/flux.py b/invokeai/backend/model_manager/load/model_loaders/flux.py
index 727549af1b..9bcc99adc6 100644
--- a/invokeai/backend/model_manager/load/model_loaders/flux.py
+++ b/invokeai/backend/model_manager/load/model_loaders/flux.py
@@ -67,6 +67,7 @@ from invokeai.backend.model_manager.load.model_loader_registry import ModelLoade
from invokeai.backend.model_manager.load.model_loaders.flux2_state_dict_utils import (
convert_flux2_bfl_to_diffusers,
convert_flux2_vae_bfl_to_diffusers,
+ remap_flux2_layer_paths,
)
from invokeai.backend.model_manager.load.model_loaders.generic_diffusers import GenericDiffusersLoader
from invokeai.backend.model_manager.taxonomy import (
@@ -1036,12 +1037,10 @@ class Flux2CheckpointModel(ModelLoader):
# Load state dict
sd = load_file(model_path)
- # Handle FP8 quantized weights (ComfyUI-style or scaled FP8)
- # These store weights as: layer.weight (FP8) + layer.weight_scale (FP32 scalar)
keep_fp8 = should_keep_fp8_weights(self._torch_device)
- sd = self._dequantize_fp8_weights(sd, keep_fp8=keep_fp8)
- # Check if keys have ComfyUI-style prefix and strip if needed
+ # Check if keys have ComfyUI-style prefix and strip if needed. This runs before anything
+ # reads the quantization side-channel: the scales carry the same prefix as their weights.
prefix_to_strip = None
for prefix in ["model.diffusion_model.", "diffusion_model."]:
if any(k.startswith(prefix) for k in sd.keys() if isinstance(k, str)):
@@ -1054,9 +1053,37 @@ class Flux2CheckpointModel(ModelLoader):
for k, v in sd.items()
}
- # Convert BFL format state dict to diffusers format
+ # ComfyUI 'scaled fp8' (fp8 weight + .weight_scale, optionally an input scale). Until now
+ # these were folded into bf16 at load, so a FLUX.2 checkpoint that ships them ran as fp8
+ # *storage* at best and never reached the tensor cores.
+ #
+ # Hints ship in the safetensors header or as per-layer `.comfy_quant` markers, and both name
+ # layers in the checkpoint's BFL scheme. The scales are read after the rename, so the hints
+ # have to be renamed too -- a fused `qkv` becomes three diffusers layers.
+ header_hints = parse_quantization_metadata(read_safetensors_metadata(model_path, self._logger))
+ layer_hints = {**extract_comfy_quant_hints(sd), **header_hints}
+ path_map = remap_flux2_layer_paths(layer_hints.keys())
+ layer_hints = {
+ renamed: hints for name, hints in layer_hints.items() for renamed in (path_map.get(name) or [name])
+ }
+
+ # Convert BFL format state dict to diffusers format. Scales and markers are carried to
+ # wherever their weight landed, including across the fused-qkv split.
converted_sd = convert_flux2_bfl_to_diffusers(sd)
+ fp8_layers = extract_fp8_scaled_layers(converted_sd, layer_hints=layer_hints)
+ if fp8_layers and not keep_fp8:
+ # Without the matmul, keeping them quantized would halve VRAM but dequantize on every
+ # forward. Fold the scale into the weight instead -- the legacy result, except reached
+ # through the shared helper.
+ 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.
+ converted_sd = self._dequantize_fp8_weights(converted_sd, keep_fp8=keep_fp8)
+
# Detect architecture from checkpoint keys
double_block_indices = [
int(k.split(".")[1])
@@ -1135,19 +1162,38 @@ class Flux2CheckpointModel(ModelLoader):
# take them (the scaled-fp8 path above has already folded any weight_scale it found). The
# model's own precision-sensitive list is honored — see the Z-Image loader for why that is
# a correctness requirement and not just a quality nicety.
+ skip_patterns = tuple(getattr(model, "_skip_layerwise_casting_patterns", None) or ())
+ # Scaled layers the cast would dequantize anyway are folded here, scale applied, so
+ # `cast_state_dict` never strips a scale that can no longer be put back.
+ fp8_layers = split_fp8_scaled_layers(
+ converted_sd, fp8_layers, torch.bfloat16, model=model, skip_patterns=skip_patterns
+ )
+
kept = cast_state_dict(
converted_sd,
torch.bfloat16,
keep_fp8=keep_fp8,
model=model,
- skip_patterns=getattr(model, "_skip_layerwise_casting_patterns", None) or (),
+ skip_patterns=skip_patterns,
)
- if kept:
- self._logger.info(f"FLUX.2: kept {kept} raw fp8 weight(s) quantized for the fp8 tensor cores.")
# Load the state dict - guidance weights were already initialized above if missing
model.load_state_dict(converted_sd, assign=True)
+ if fp8_layers:
+ attached = attach_fp8_scales(model, fp8_layers)
+ self._logger.info(f"FLUX.2: kept {attached} layer(s) in fp8 (scaled fp8 checkpoint, fp8_compute enabled)")
+ warn_on_unattached_scales(self._logger, "FLUX.2", attached, fp8_layers)
+ marked = sum(1 for layer in fp8_layers.values() if layer.full_precision_matmul)
+ if marked and full_precision_hints_respected():
+ self._logger.info(
+ f"FLUX.2: {marked} of {len(fp8_layers)} layer(s) are marked full_precision_matrix_mult "
+ "and will dequantize per forward. Set fp8_compute_full_precision_hints=false to run "
+ "them on the fp8 tensor cores instead."
+ )
+ elif kept:
+ self._logger.info(f"FLUX.2: kept {kept} raw fp8 weight(s) quantized for the fp8 tensor cores.")
+
return model
def _dequantize_fp8_weights(self, sd: dict, keep_fp8: bool = False) -> dict:
diff --git a/invokeai/backend/model_manager/load/model_loaders/flux2_state_dict_utils.py b/invokeai/backend/model_manager/load/model_loaders/flux2_state_dict_utils.py
index 86fd847816..c705d9f024 100644
--- a/invokeai/backend/model_manager/load/model_loaders/flux2_state_dict_utils.py
+++ b/invokeai/backend/model_manager/load/model_loaders/flux2_state_dict_utils.py
@@ -14,9 +14,15 @@ Based on the diffusers `convert_flux2_to_diffusers.py` key mappings.
"""
import re
+from typing import Any
import torch
+from invokeai.backend.quantization.fp8_scaled import (
+ QKV_SPLIT_SIDECHANNEL_SUFFIXES,
+ split_qkv_sidechannel,
+)
+
def _flux2_chunk_tensor(tensor, chunks: int):
"""Chunk a tensor along dim 0, dequantizing GGUF tensors first.
@@ -134,8 +140,14 @@ def _convert_flux2_single_block_key(key: str, tensor, converted: dict) -> str |
return key
-def convert_flux2_bfl_to_diffusers(sd: dict) -> dict:
- """Convert a FLUX.2 transformer BFL-format state dict to diffusers format."""
+def _convert_flux2_weight_keys(sd: dict) -> dict:
+ """Convert the *weight* keys of a FLUX.2 BFL state dict to diffusers format.
+
+ Quantization side-channel keys must not be routed through here. The block renames below are
+ substring tests, so `img_attn.proj.weight_scale` satisfies `"img_attn.proj.weight" in rest`
+ and would be written to the weight's destination key -- overwriting the weight with its own
+ scale. `convert_flux2_bfl_to_diffusers` keeps them out and places them separately.
+ """
converted: dict = {}
# Basic key renames
@@ -324,3 +336,70 @@ def convert_flux2_vae_bfl_to_diffusers(sd: dict) -> dict:
converted[new_key] = tensor
return converted
+
+
+def _flux2_sidechannel_parts(key: Any) -> tuple[str, str] | None:
+ """Split ``<module path>.<suffix>`` for a quantization side-channel key, else None."""
+ if not isinstance(key, str):
+ return None
+ for suffix in QKV_SPLIT_SIDECHANNEL_SUFFIXES:
+ if key.endswith(f".{suffix}"):
+ return key[: -len(suffix) - 1], suffix
+ return None
+
+
+# Divisible by both 3 (the fused QKV split) and 2 (the adaLN scale/shift swap), so a probe runs
+# through every branch of the converter instead of tripping its "malformed, leave alone" guards.
+_PROBE_ROWS = 6
+
+
+def _flux2_sidechannel_destinations(base: str) -> list[str]:
+ """Where a layer's weight ends up after conversion, as module paths.
+
+ Rather than restating the rename rules -- which would drift from the converter the moment one
+ of them changes -- the layer is pushed through the real converter as a lone ``<base>.weight``
+ and the resulting keys are read back. A fused ``qkv`` maps to *three* destinations.
+ """
+ probe = {f"{base}.weight": torch.zeros(_PROBE_ROWS, 1)}
+ return [k[: -len(".weight")] for k in _convert_flux2_weight_keys(probe) if k.endswith(".weight")]
+
+
+def convert_flux2_bfl_to_diffusers(sd: dict) -> dict:
+ """Convert a FLUX.2 transformer BFL-format state dict to diffusers format.
+
+ Quantization scales and markers are carried to wherever their weight landed. Doing that is not
+ optional for a scaled-fp8 checkpoint: a scale left on the fused ``qkv`` path is keyed on a
+ module the diffusers model does not have, so `attach_fp8_scales` finds nothing and the three
+ split weights stay quantized but *unscaled* -- off by 1/weight_scale, with nothing logged.
+ """
+ weights = {k: v for k, v in sd.items() if _flux2_sidechannel_parts(k) is None}
+ converted = _convert_flux2_weight_keys(weights)
+
+ for key, value in sd.items():
+ parts = _flux2_sidechannel_parts(key)
+ if parts is None:
+ continue
+ base, suffix = parts
+ destinations = _flux2_sidechannel_destinations(base)
+ if not destinations:
+ # Unknown layer: keep the key as it is. `extract_fp8_scaled_layers` drops a scale with
+ # no matching fp8 weight, which is the safe outcome -- better than guessing a target.
+ converted[key] = value
+ elif len(destinations) == 1:
+ converted[f"{destinations[0]}.{suffix}"] = value
+ else:
+ for destination, part in zip(destinations, split_qkv_sidechannel(key, value), strict=True):
+ converted[f"{destination}.{suffix}"] = part
+
+ return converted
+
+
+def remap_flux2_layer_paths(layer_names: Any) -> dict[str, list[str]]:
+ """Map BFL layer paths to their diffusers equivalents, one-to-many for a fused ``qkv``.
+
+ ``_quantization_metadata`` names its layers in the checkpoint's own scheme, but the scales are
+ extracted *after* the state dict has been renamed. Without this the per-layer flags -- notably
+ ``full_precision_matrix_mult`` -- match nothing and are silently ignored, which is the exact
+ mistake that already cost a debugging round on Krea-2.
+ """
+ return {name: _flux2_sidechannel_destinations(name) for name in layer_names}
diff --git a/invokeai/backend/model_manager/load/model_loaders/z_image.py b/invokeai/backend/model_manager/load/model_loaders/z_image.py
index 868a1f2c69..5d973b6f2c 100644
--- a/invokeai/backend/model_manager/load/model_loaders/z_image.py
+++ b/invokeai/backend/model_manager/load/model_loaders/z_image.py
@@ -35,6 +35,7 @@ from invokeai.backend.model_manager.taxonomy import (
SubModelType,
)
from invokeai.backend.quantization.fp8_scaled import (
+ QKV_SPLIT_SIDECHANNEL_SUFFIXES,
attach_fp8_scales,
cast_state_dict,
dequantize_fp8_scaled,
@@ -48,6 +49,7 @@ from invokeai.backend.quantization.fp8_scaled import (
read_safetensors_metadata,
should_keep_fp8_weights,
split_fp8_scaled_layers,
+ split_qkv_sidechannel,
warn_on_unattached_scales,
)
from invokeai.backend.quantization.gguf.loaders import gguf_sd_loader
@@ -56,33 +58,6 @@ from invokeai.backend.quantization.sdnq.loaders import raise_on_incomplete_sdnq_
from invokeai.backend.qwen3.qwen3_tokenizer import load_bundled_qwen3_tokenizer
from invokeai.backend.util.devices import TorchDevice
-# Per-layer quantization side-channel entries that sit next to a fused `qkv.weight` and therefore
-# have to be split along with it. The scale spellings are the ones `fp8_scaled` accepts; the marker
-# is a JSON blob describing the layer, identical for all three halves of the split.
-_QKV_SPLIT_SIDECHANNEL_SUFFIXES = ("weight_scale", "scale_weight", "input_scale", "scale_input", "comfy_quant")
-
-
-def _split_qkv_sidechannel(key: str, value: Any) -> tuple[Any, Any, Any]:
- """Split a fused-QKV scale/marker into the parts belonging to Q, K and V.
-
- A per-tensor scale (and any marker blob) describes the whole fused tensor, so each third
- inherits it unchanged. A per-output-channel scale has one entry per row and is split exactly
- like the weight.
- """
- tensor = torch.as_tensor(value) if hasattr(value, "shape") else value
- if not hasattr(tensor, "shape") or tensor.dim() == 0 or tensor.shape[0] == 1:
- return (tensor, tensor, tensor)
- if tensor.numel() == 1 or key.endswith(("comfy_quant", "input_scale", "scale_input")):
- # A marker blob is a 1-D byte string, not a per-channel vector — never split it.
- return (tensor, tensor, tensor)
- if tensor.shape[0] % 3 != 0:
- raise ValueError(
- f"Cannot split fused QKV quantization data '{key}': first dimension ({tensor.shape[0]}) is "
- "neither 1 nor divisible by 3, so it matches neither a per-tensor nor a per-channel scale."
- )
- third = tensor.shape[0] // 3
- return (tensor[:third], tensor[third : 2 * third], tensor[2 * third :])
-
def _remap_z_image_layer_paths(layer_names: Any) -> dict[str, list[str]]:
"""Map native Z-Image layer paths to their diffusers equivalents.
@@ -169,8 +144,8 @@ def _convert_z_image_gguf_to_diffusers(sd: dict[str, Any]) -> dict[str, Any]:
# or the recovered scale is keyed on `...attention.qkv`, a module path that no
# longer exists — `attach_fp8_scales` then finds nothing and the three split
# weights stay quantized but *unscaled*, i.e. off by 1/weight_scale.
- if suffix in _QKV_SPLIT_SIDECHANNEL_SUFFIXES:
- for name, part in zip(("to_q", "to_k", "to_v"), _split_qkv_sidechannel(key, value), strict=True):
+ if suffix in QKV_SPLIT_SIDECHANNEL_SUFFIXES:
+ for name, part in zip(("to_q", "to_k", "to_v"), split_qkv_sidechannel(key, value), strict=True):
new_sd[f"{prefix}.attention.{name}.{suffix}"] = part
continue
new_sd[key] = value
diff --git a/invokeai/backend/quantization/fp8_scaled.py b/invokeai/backend/quantization/fp8_scaled.py
index 35e9062775..e2f77b0d87 100644
--- a/invokeai/backend/quantization/fp8_scaled.py
+++ b/invokeai/backend/quantization/fp8_scaled.py
@@ -162,6 +162,38 @@ def iter_weight_scale_pairs(sd: Mapping[str, Any]) -> Iterable[tuple[str, str]]:
break
+# Per-layer quantization side-channel entries that sit next to a fused `qkv.weight` and therefore
+# have to be carried through a split of it. The scale spellings are the ones this module accepts;
+# the marker is a JSON blob describing the layer, identical for all three parts of the split.
+QKV_SPLIT_SIDECHANNEL_SUFFIXES = ("weight_scale", "scale_weight", "input_scale", "scale_input", "comfy_quant")
+
+
+def split_qkv_sidechannel(key: str, value: Any) -> tuple[Any, Any, Any]:
+ """Split a fused-QKV scale/marker into the parts belonging to Q, K and V.
+
+ A per-tensor scale (and any marker blob) describes the whole fused tensor, so each third
+ inherits it unchanged. A per-output-channel scale has one entry per row and is split exactly
+ like the weight.
+
+ Getting this wrong is silent: a scale left on the fused path is keyed on a module the split
+ model does not have, so `attach_fp8_scales` finds nothing and the three weights stay quantized
+ but *unscaled* -- off by 1/weight_scale, with no error anywhere.
+ """
+ tensor = torch.as_tensor(value) if hasattr(value, "shape") else value
+ if not hasattr(tensor, "shape") or tensor.dim() == 0 or tensor.shape[0] == 1:
+ return (tensor, tensor, tensor)
+ if tensor.numel() == 1 or key.endswith(("comfy_quant", "input_scale", "scale_input")):
+ # A marker blob is a 1-D byte string, not a per-channel vector -- never split it.
+ return (tensor, tensor, tensor)
+ if tensor.shape[0] % 3 != 0:
+ raise ValueError(
+ f"Cannot split fused QKV quantization data '{key}': first dimension ({tensor.shape[0]}) is "
+ "neither 1 nor divisible by 3, so it matches neither a per-tensor nor a per-channel scale."
+ )
+ third = tensor.shape[0] // 3
+ return (tensor[:third], tensor[third : 2 * third], tensor[2 * third :])
+
+
def is_scale_metadata_key(key: Any) -> bool:
"""Whether ``key`` is fp8 scale/quantization metadata rather than a model tensor.
diff --git a/tests/backend/model_manager/load/state_dicts/flux2_klein_4b_scaled_fp8_keys.py b/tests/backend/model_manager/load/state_dicts/flux2_klein_4b_scaled_fp8_keys.py
new file mode 100644
index 0000000000..fd852f32a2
--- /dev/null
+++ b/tests/backend/model_manager/load/state_dicts/flux2_klein_4b_scaled_fp8_keys.py
@@ -0,0 +1,66 @@
+"""Representative key layout of the official scaled-fp8 FLUX.2 Klein 4B checkpoint.
+
+Captured from `black-forest-labs/FLUX.2-klein-4b-fp8`. Kept alongside
+`flux2_transformer_fp8mixed_keys` because that one comes from FLUX.2 **dev**, whose quantizer left
+the fused `qkv` alone -- so it cannot exercise the one case that makes FLUX.2 harder than FLUX.1.
+
+Here `double_blocks.0.img_attn.qkv.weight` is a fused `[9216, 3072]` fp8 tensor carrying a single
+**scalar** `weight_scale`. diffusers wants three separate projections, so the weight is chunked and
+the scalar has to be *copied* to all three -- splitting it would be wrong, and leaving it on the
+fused path is worse: `attach_fp8_scales` then matches nothing and the three weights stay quantized
+but unscaled, off by 1/weight_scale with nothing logged.
+
+The layer flags arrive through the safetensors header (`_quantization_metadata`), which names
+layers in the BFL scheme -- so they need the same one-to-many rename as the scales.
+
+Subsetting rule as for the sibling fixtures: block 0 of each stack plus every non-block key.
+Values are `(shape, dtype)`.
+"""
+
+state_dict_keys: dict[str, tuple[list[int], str]] = {
+ "double_blocks.0.img_attn.norm.key_norm.scale": ([128], "BF16"),
+ "double_blocks.0.img_attn.norm.query_norm.scale": ([128], "BF16"),
+ "double_blocks.0.img_attn.proj.input_scale": ([], "F32"),
+ "double_blocks.0.img_attn.proj.weight": ([3072, 3072], "F8_E4M3"),
+ "double_blocks.0.img_attn.proj.weight_scale": ([], "F32"),
+ "double_blocks.0.img_attn.qkv.input_scale": ([], "F32"),
+ "double_blocks.0.img_attn.qkv.weight": ([9216, 3072], "F8_E4M3"),
+ "double_blocks.0.img_attn.qkv.weight_scale": ([], "F32"),
+ "double_blocks.0.img_mlp.0.input_scale": ([], "F32"),
+ "double_blocks.0.img_mlp.0.weight": ([18432, 3072], "F8_E4M3"),
+ "double_blocks.0.img_mlp.0.weight_scale": ([], "F32"),
+ "double_blocks.0.img_mlp.2.input_scale": ([], "F32"),
+ "double_blocks.0.img_mlp.2.weight": ([3072, 9216], "F8_E4M3"),
+ "double_blocks.0.img_mlp.2.weight_scale": ([], "F32"),
+ "double_blocks.0.txt_attn.norm.key_norm.scale": ([128], "BF16"),
+ "double_blocks.0.txt_attn.norm.query_norm.scale": ([128], "BF16"),
+ "double_blocks.0.txt_attn.proj.input_scale": ([], "F32"),
+ "double_blocks.0.txt_attn.proj.weight": ([3072, 3072], "F8_E4M3"),
+ "double_blocks.0.txt_attn.proj.weight_scale": ([], "F32"),
+ "double_blocks.0.txt_attn.qkv.input_scale": ([], "F32"),
+ "double_blocks.0.txt_attn.qkv.weight": ([9216, 3072], "F8_E4M3"),
+ "double_blocks.0.txt_attn.qkv.weight_scale": ([], "F32"),
+ "double_blocks.0.txt_mlp.0.input_scale": ([], "F32"),
+ "double_blocks.0.txt_mlp.0.weight": ([18432, 3072], "F8_E4M3"),
+ "double_blocks.0.txt_mlp.0.weight_scale": ([], "F32"),
+ "double_blocks.0.txt_mlp.2.input_scale": ([], "F32"),
+ "double_blocks.0.txt_mlp.2.weight": ([3072, 9216], "F8_E4M3"),
+ "double_blocks.0.txt_mlp.2.weight_scale": ([], "F32"),
+ "double_stream_modulation_img.lin.weight": ([18432, 3072], "BF16"),
+ "double_stream_modulation_txt.lin.weight": ([18432, 3072], "BF16"),
+ "final_layer.adaLN_modulation.1.weight": ([6144, 3072], "BF16"),
+ "final_layer.linear.weight": ([128, 3072], "BF16"),
+ "img_in.weight": ([3072, 128], "BF16"),
+ "single_blocks.0.linear1.input_scale": ([], "F32"),
+ "single_blocks.0.linear1.weight": ([27648, 3072], "F8_E4M3"),
+ "single_blocks.0.linear1.weight_scale": ([], "F32"),
+ "single_blocks.0.linear2.input_scale": ([], "F32"),
+ "single_blocks.0.linear2.weight": ([3072, 12288], "F8_E4M3"),
+ "single_blocks.0.linear2.weight_scale": ([], "F32"),
+ "single_blocks.0.norm.key_norm.scale": ([128], "BF16"),
+ "single_blocks.0.norm.query_norm.scale": ([128], "BF16"),
+ "single_stream_modulation.lin.weight": ([9216, 3072], "BF16"),
+ "time_in.in_layer.weight": ([3072, 256], "BF16"),
+ "time_in.out_layer.weight": ([3072, 3072], "BF16"),
+ "txt_in.weight": ([3072, 7680], "BF16"),
+}
diff --git a/tests/backend/model_manager/load/test_flux2_scaled_fp8_keys.py b/tests/backend/model_manager/load/test_flux2_scaled_fp8_keys.py
new file mode 100644
index 0000000000..1acd3c7275
--- /dev/null
+++ b/tests/backend/model_manager/load/test_flux2_scaled_fp8_keys.py
@@ -0,0 +1,111 @@
+"""A scaled-fp8 FLUX.2 checkpoint must survive the BFL -> diffusers rename with its scales.
+
+FLUX.2 is the hard case of the scaled-fp8 loaders: unlike FLUX.1 the keys are renamed, and the
+fused `qkv` is split into three projections. Both steps can lose a scale silently -- the weights
+then stay quantized but unscaled, off by `1/weight_scale`, with nothing logged.
+"""
+
+import torch
+
+from invokeai.backend.model_manager.load.model_loaders.flux2_state_dict_utils import (
+ convert_flux2_bfl_to_diffusers,
+ remap_flux2_layer_paths,
+)
+from invokeai.backend.quantization.fp8_scaled import FP8_DTYPE, extract_fp8_scaled_layers
+from tests.backend.model_manager.load.state_dicts.flux2_klein_4b_scaled_fp8_keys import (
+ state_dict_keys as klein_keys,
+)
+
+_DTYPES = {"F8_E4M3": FP8_DTYPE, "F32": torch.float32, "BF16": torch.bfloat16}
+
+
+def _build_state_dict() -> dict[str, torch.Tensor]:
+ sd: dict[str, torch.Tensor] = {}
+ for key, (shape, dtype) in klein_keys.items():
+ torch_dtype = _DTYPES[dtype]
+ if torch_dtype is FP8_DTYPE:
+ sd[key] = torch.zeros(shape, dtype=torch.float32).to(FP8_DTYPE)
+ elif key.endswith((".weight_scale", ".input_scale")):
+ # 1.0 is the placeholder `_usable_input_scale` rejects, so it must not be used here.
+ sd[key] = torch.full(shape, 2.5, dtype=torch_dtype)
+ else:
+ sd[key] = torch.zeros(shape, dtype=torch_dtype)
+ return sd
+
+
+def test_no_scale_is_left_on_a_bfl_path() -> None:
+ """Every scale must land next to the weight it belongs to, under its diffusers name."""
+ converted = convert_flux2_bfl_to_diffusers(_build_state_dict())
+
+ scales = [k for k in converted if k.endswith((".weight_scale", ".input_scale"))]
+ assert scales, "fixture carries no scales"
+ orphans = [k for k in scales if k.rsplit(".", 1)[0] + ".weight" not in converted]
+ assert orphans == []
+ assert [k for k in converted if k.startswith(("double_blocks.", "single_blocks."))] == []
+
+
+def test_the_fused_qkv_scalar_is_copied_to_all_three_projections() -> None:
+ """A per-tensor scale describes the whole fused tensor, so each third inherits it unchanged."""
+ fused = [k for k in klein_keys if k.endswith(".qkv.weight")]
+ assert fused, "fixture carries no fused qkv weight"
+
+ converted = convert_flux2_bfl_to_diffusers(_build_state_dict())
+
+ for group in (("to_q", "to_k", "to_v"), ("add_q_proj", "add_k_proj", "add_v_proj")):
+ for name in group:
+ key = f"transformer_blocks.0.attn.{name}.weight_scale"
+ assert key in converted, f"missing {key}"
+ assert converted[key].shape == torch.Size([]), "a scalar scale must not be split"
+ assert torch.equal(converted[key], torch.tensor(2.5))
+
+
+def test_a_scale_never_overwrites_its_own_weight() -> None:
+ """The block renames are substring tests, so `...proj.weight_scale` matches `...proj.weight`.
+
+ Routed through the weight converter, the scale would be written to the weight's destination key
+ and replace it. The weight must still be the fp8 tensor afterwards, not an f32 scalar.
+ """
+ converted = convert_flux2_bfl_to_diffusers(_build_state_dict())
+
+ weight = converted["transformer_blocks.0.attn.to_out.0.weight"]
+ assert weight.dtype is FP8_DTYPE
+ assert weight.dim() == 2
+
+
+def test_every_quantized_linear_is_recognized_after_the_rename() -> None:
+ sd = convert_flux2_bfl_to_diffusers(_build_state_dict())
+ fp8_weights = {k for k, v in sd.items() if v.dtype is FP8_DTYPE and k.endswith(".weight")}
+
+ layers = extract_fp8_scaled_layers(sd)
+
+ assert {f"{path}.weight" for path in layers} == fp8_weights
+ assert all(layer.input_scale is not None for layer in layers.values())
+
+
+def test_layer_hints_are_renamed_one_to_many_for_the_fused_qkv() -> None:
+ """Hints name layers in the BFL scheme; the scales are read after the rename.
+
+ Without remapping, `full_precision_matrix_mult` matches nothing and is silently ignored.
+ """
+ mapping = remap_flux2_layer_paths(["double_blocks.0.img_attn.qkv", "double_blocks.0.img_attn.proj"])
+
+ assert mapping["double_blocks.0.img_attn.qkv"] == [
+ "transformer_blocks.0.attn.to_q",
+ "transformer_blocks.0.attn.to_k",
+ "transformer_blocks.0.attn.to_v",
+ ]
+ assert mapping["double_blocks.0.img_attn.proj"] == ["transformer_blocks.0.attn.to_out.0"]
+
+
+def test_a_per_channel_scale_is_split_like_the_weight() -> None:
+ """Not present in this checkpoint, but the split must not assume every scale is a scalar."""
+ sd = {
+ "double_blocks.0.img_attn.qkv.weight": torch.zeros(9, 2, dtype=torch.float32).to(FP8_DTYPE),
+ "double_blocks.0.img_attn.qkv.weight_scale": torch.arange(9, dtype=torch.float32),
+ }
+
+ converted = convert_flux2_bfl_to_diffusers(sd)
+
+ assert torch.equal(converted["transformer_blocks.0.attn.to_q.weight_scale"], torch.arange(0, 3.0))
+ assert torch.equal(converted["transformer_blocks.0.attn.to_k.weight_scale"], torch.arange(3, 6.0))
+ assert torch.equal(converted["transformer_blocks.0.attn.to_v.weight_scale"], torch.arange(6, 9.0))