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
refactor(flux2): re-key header entries from the conversion's record
Alexander Eichhornd73cfe53c4b5
diff --git a/invokeai/backend/model_manager/load/model_loaders/flux.py b/invokeai/backend/model_manager/load/model_loaders/flux.pyindex 9dab609f85..86694c8707 100644--- a/invokeai/backend/model_manager/load/model_loaders/flux.py+++ b/invokeai/backend/model_manager/load/model_loaders/flux.py@@ -72,7 +72,6 @@ from invokeai.backend.model_manager.load.model_loader_registry import ModelLoadefrom 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 GenericDiffusersLoaderfrom invokeai.backend.model_manager.taxonomy import (@@ -1186,13 +1185,16 @@ class Flux2CheckpointModel(ModelLoader):int8_markers: dict[str, dict[str, Any]] = {}fp8_layers: dict[str, Fp8ScaledLayer] = {}+ # Where each BFL module's weight lands, recorded by the conversion itself. Both branches+ # re-key the header's per-layer entries with it; they differ only in when they convert.+ flux2_modules: dict[str, list[str]] = {}if has_int8_weights:# The converter carries `.comfy_quant` and `.weight_scale` to wherever their weight# landed, so the markers are read *after* the rename and already name diffusers modules# -- including the three a fused `qkv` becomes, which each inherit the fused layer's# per-tensor scale and marker.- converted_sd = convert_flux2_bfl_to_diffusers(sd)+ converted_sd = convert_flux2_bfl_to_diffusers(sd, module_map=flux2_modules)int8_markers = extract_int8_convrot_markers(converted_sd)# The header is the other place a repack declares its scheme, and for FLUX.2 that is# not hypothetical: Comfy-Org's own fp8 build of this model carries *no* per-layer@@ -1207,7 +1209,7 @@ class Flux2CheckpointModel(ModelLoader):parse_quantization_metadata(read_safetensors_metadata(model_path, self._logger))).items()if marker.get("format") == INT8_TENSORWISE_FORMAT- for renamed in (remap_flux2_layer_paths([name]).get(name) or [name])+ for renamed in (flux2_modules.get(name) or [name])}int8_markers = {**header_markers, **int8_markers}else:@@ -1222,14 +1224,17 @@ class Flux2CheckpointModel(ModelLoader):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)+ # wherever their weight landed, including across the fused-qkv split. The conversion+ # runs before the hints are re-keyed because it is what *knows* the mapping: a probe+ # asked by name cannot see that a fused qkv whose rows are not divisible by three is+ # left unsplit, and would fan a hint onto three modules that do not exist.+ converted_sd = convert_flux2_bfl_to_diffusers(sd, module_map=flux2_modules)++ layer_hints = {+ renamed: hints for name, hints in layer_hints.items() for renamed in (flux2_modules.get(name) or [name])+ }fp8_layers = extract_fp8_scaled_layers(converted_sd, layer_hints=layer_hints)if fp8_layers and not keep_fp8: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.pyindex 958aeeabb5..884d4b37ba 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@@ -377,34 +377,6 @@ def _flux2_sidechannel_parts(key: Any) -> tuple[str, str] | None:return None-# Divisible by both 3 (the fused QKV split) and 2 (the adaLN scale/shift swap), so a probe reaches-# every rename branch instead of tripping the converter's "malformed, leave alone" guards.-_PROBE_ROWS = 6---def _flux2_sidechannel_destinations(base: str) -> list[str]:- """Where a layer's weight *would* end 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.-- The answer is about the name alone, so it cannot see the branches that depend on the tensor: a- fused ``qkv`` whose rows are not divisible by three is left unsplit by the converter, and this- still reports three. The side-channel placement no longer asks it -- it reads what the conversion- recorded.-- Both remaining callers (`flux.py`, the int8 header markers and the fp8 layer hints) *do* have the- state dict in hand, so they could read that record too; the int8 branch already runs the- conversion before it asks. Until they do, a header hint or marker on a declined split is mapped- to three modules that do not exist. It is bounded -- such a file fails to load anyway, on the- three projections now missing -- but it is the same defect, and retiring this function by passing- the map to those two call sites is the next step, not a hypothetical one.- """- 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")]--# Converter transforms that reorder weight *rows*. A per-output-channel weight scale has one entry# per row, so it has to be reordered identically or every row ends up scaled by another row's# factor. The fused-QKV split is handled separately (`split_qkv_sidechannel`); this is the only@@ -427,13 +399,24 @@ def _mirror_row_permutation(base: str, suffix: str, value: Any) -> Any:return _flux2_swap_scale_shift(tensor)-def convert_flux2_bfl_to_diffusers(sd: dict) -> dict:+def convert_flux2_bfl_to_diffusers(sd: dict, *, module_map: dict[str, list[str]] | None = None) -> 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 notoptional for a scaled-fp8 checkpoint: a scale left on the fused ``qkv`` path is keyed on amodule the diffusers model does not have, so `attach_fp8_scales` finds nothing and the threesplit weights stay quantized but *unscaled* -- off by 1/weight_scale, with nothing logged.++ ``module_map``, when given, receives the record the placement uses: each source module to the+ module(s) its weight became. Callers with something else to re-key in the checkpoint's own scheme+ -- the header's per-layer hints and its int8 markers -- read it, rather than asking a probe what+ the rename *would* do, which cannot see the branches that depend on the tensor. It is updated,+ not adopted, so a caller that reuses a dict cannot end up with two records interleaved.++ A module named only in the header and absent from the file gets no entry, and the caller keeps+ the name as it stands. What happens then is the caller's business and differs: the fp8+ extraction ignores a hint that names no layer, while the int8 swap refuses the checkpoint by name+ ("is marked int8_tensorwise but is missing its weight"). Both predate this record."""weights = {k: v for k, v in sd.items() if _flux2_sidechannel_parts(k) is None}key_map: dict[str, list[str]] = {}@@ -448,19 +431,21 @@ def convert_flux2_bfl_to_diffusers(sd: dict) -> dict:# Only a destination ending `.weight` names a module a scale can sit beside. A `.bias` is not# renamed by this converter at all, so without the filter it contributes the module a second# time and the side channel is taken for a fused-qkv split.- module_map: dict[str, list[str]] = {}+ modules: dict[str, list[str]] = {}for source, moved_to in key_map.items():stem = source.rsplit(".", 1)[0] if "." in source else sourcelanded = [target[: -len(".weight")] for target in moved_to if target.endswith(".weight")]if landed:- module_map.setdefault(stem, []).extend(landed)+ modules.setdefault(stem, []).extend(landed)+ if module_map is not None:+ module_map.update(modules)for key, value in sd.items():parts = _flux2_sidechannel_parts(key)if parts is None:continuebase, suffix = parts- destinations = module_map.get(base, [])+ destinations = modules.get(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.@@ -472,14 +457,3 @@ def convert_flux2_bfl_to_diffusers(sd: dict) -> dict:converted[f"{destination}.{suffix}"] = partreturn 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.pyindex 5fe9e4b2aa..04d6cd0d33 100644--- a/invokeai/backend/model_manager/load/model_loaders/z_image.py+++ b/invokeai/backend/model_manager/load/model_loaders/z_image.py@@ -84,6 +84,12 @@ from invokeai.backend.util.state_dict_loading import load_state_dict_ignoring_exdef _remap_z_image_layer_paths(layer_names: Any) -> dict[str, list[str]]:"""Map native Z-Image layer paths to their diffusers equivalents.+ A probe, where FLUX.2's equivalent was replaced by the conversion's own record. The difference is+ that this converter *raises* on a fused ``qkv`` whose rows are not divisible by three rather than+ leaving the key alone, so a probe and the conversion cannot disagree about it -- and the second+ caller below works on payloads popped out *before* the conversion, which no record of that+ conversion could cover.+``_quantization_metadata`` names its layers in the checkpoint's own scheme, but the scales areextracted after the state dict has been renamed. Rather than restating the rename rules — whichwould drift — each name is pushed through the real converter as a lone ``<name>.weight`` entrydiff --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 8818414b99..a30ae8b94a 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@@ -18,7 +18,6 @@ import torchfrom invokeai.backend.model_manager.configs.main import Main_Checkpoint_Flux2_Configfrom invokeai.backend.model_manager.load.model_loaders import fluxfrom invokeai.backend.model_manager.load.model_loaders.flux import Flux2CheckpointModel-from invokeai.backend.model_manager.load.model_loaders.flux2_state_dict_utils import remap_flux2_layer_pathsfrom invokeai.backend.model_manager.taxonomy import Flux2VariantType, SubModelTypefrom invokeai.backend.quantization.fp8_scaled import iter_weight_scale_pairsfrom invokeai.backend.quantization.int8_convrot import Int8ConvrotLinear@@ -114,7 +113,10 @@ def _expected_reservation() -> int:file needs; charging none lets the split's transient land on an unreserved cache."""int8_bytes = sum(out * inp for out, inp in QUANTIZED.values())- destinations = sum(len(paths) for paths in remap_flux2_layer_paths(QUANTIZED).values())+ # How many modules the quantized layers become: one each, except the two fused qkv that become+ # three. Counted here rather than read off the conversion, so that a wrong mapping shifts the+ # measurement without shifting what it is measured against.+ destinations = len(QUANTIZED) + 2 * 2scale_bytes = destinations * torch.float32.itemsizedense_bytes = sum(torch.Size(shape).numel() for shape in DENSE.values()) * torch.bfloat16.itemsize# Klein has no guidance embedder, so the loader fills one with zeros shaped like the timestep@@ -460,3 +462,40 @@ def test_a_comfyui_prefixed_checkpoint_loads_the_same_as_a_bare_one(monkeypatch,assert set(from_prefixed) == set(from_bare)for key, value in from_bare.items():assert torch.equal(from_prefixed[key].to(torch.float32), value.to(torch.float32)), key+++def test_a_header_hint_reaches_every_projection_the_fused_qkv_became(monkeypatch, tmp_path) -> None:+ """`full_precision_matrix_mult` names a BFL layer; the modules it has to reach are the three a+ fused qkv becomes. Un-renamed it matches nothing and is ignored in silence -- the layer then runs+ on the fp8 tensor cores the producer measured as unsafe, with nothing logged.++ This is the fp8 half of the header re-key. Its int8 twin is covered two cells up; this one was+ the gap the mutation sweep found, and closing it costs one fixture that already existed.+ """+ from invokeai.backend.quantization import fp8_scaled++ state_dict, _ = _scaled_fp8_checkpoint()+ fused = next(path for path in QUANTIZED if path.endswith("img_attn.qkv"))+ header = {+ "_quantization_metadata": json.dumps(+ {+ "format_version": "1.0",+ "layers": {+ path: {"format": "float8_e4m3fn", "full_precision_matrix_mult": path == fused} for path in QUANTIZED+ },+ }+ )+ }+ # Process-wide, so set through monkeypatch rather than the setter: the flag must not leak to+ # whichever test this worker runs next.+ monkeypatch.setattr(fp8_scaled, "_full_precision_hints_override", True)++ run, config = _driver(monkeypatch, tmp_path, state_dict, header)+ # The scales only stay attached where something keeps the weights quantized.+ run.loader._keep_fp8_weights = lambda _config, _submodel=None: True+ model = run.load(config)++ for projection in ("to_q", "to_k", "to_v"):+ marked = model.get_submodule(f"transformer_blocks.0.attn.{projection}")+ assert marked._fp8_full_precision_matmul is True, projection+ assert model.get_submodule("transformer_blocks.0.attn.to_out.0")._fp8_full_precision_matmul is Falsediff --git a/tests/backend/model_manager/load/test_flux2_scaled_fp8_keys.py b/tests/backend/model_manager/load/test_flux2_scaled_fp8_keys.pyindex 3f8422d4c8..b79fdd3477 100644--- a/tests/backend/model_manager/load/test_flux2_scaled_fp8_keys.py+++ b/tests/backend/model_manager/load/test_flux2_scaled_fp8_keys.py@@ -9,7 +9,6 @@ import torchfrom 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_layersfrom tests.backend.model_manager.load.state_dicts.flux2_klein_4b_scaled_fp8_keys import (@@ -91,9 +90,19 @@ def test_every_quantized_linear_is_recognized_after_the_rename() -> None: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.+ Without remapping, `full_precision_matrix_mult` matches nothing and is silently ignored. The+ mapping comes from the conversion itself, so it describes what happened to *these* tensors --+ a probe answering by name reported three destinations even for a fused qkv the converter had+ declined to split."""- mapping = remap_flux2_layer_paths(["double_blocks.0.img_attn.qkv", "double_blocks.0.img_attn.proj"])+ mapping: dict[str, list[str]] = {}+ convert_flux2_bfl_to_diffusers(+ {+ "double_blocks.0.img_attn.qkv.weight": torch.zeros(6, 2),+ "double_blocks.0.img_attn.proj.weight": torch.zeros(2, 2),+ },+ module_map=mapping,+ )assert mapping["double_blocks.0.img_attn.qkv"] == ["transformer_blocks.0.attn.to_q",diff --git a/tests/backend/model_manager/load/test_flux2_state_dict_utils.py b/tests/backend/model_manager/load/test_flux2_state_dict_utils.pyindex 260495cc29..5d489e250c 100644--- a/tests/backend/model_manager/load/test_flux2_state_dict_utils.py+++ b/tests/backend/model_manager/load/test_flux2_state_dict_utils.py@@ -287,3 +287,25 @@ def test_a_bias_beside_a_quantized_weight_does_not_become_a_second_destination()converted = convert_flux2_bfl_to_diffusers(dict(sd))assert converted["transformer_blocks.0.attn.to_out.0.weight_scale"] == torch.tensor(2.0)+++def test_the_exported_module_map_reports_a_declined_split_as_one_module() -> None:+ """What the header's hints and int8 markers are re-keyed with.++ They name layers in the BFL scheme and have to follow the weights, and until now they followed a+ probe: for a fused qkv whose rows are not divisible by three it answered "three modules" while+ the converter left the weight where it was, so `full_precision_matrix_mult` and an int8 marker+ were fanned onto three modules that do not exist. The map reports what happened instead.+ """+ split: dict[str, list[str]] = {}+ convert_flux2_bfl_to_diffusers({"double_blocks.0.img_attn.qkv.weight": torch.zeros(6, 4)}, module_map=split)++ declined: dict[str, list[str]] = {}+ convert_flux2_bfl_to_diffusers({"double_blocks.0.img_attn.qkv.weight": torch.zeros(7, 4)}, module_map=declined)++ assert split["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 declined["double_blocks.0.img_attn.qkv"] == ["double_blocks.0.img_attn.qkv"]