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(flux2): place the side channel where the weight went, not where a probe guesses
Alexander Eichhornfd6a980f2838
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 43db644ebd..958aeeabb5 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@@ -58,11 +58,16 @@ def _flux2_swap_scale_shift(weight):return torch.cat([scale, shift], dim=0)-def _convert_flux2_double_block_key(key: str, tensor, converted: dict) -> str | None:+def _convert_flux2_double_block_key(+ key: str, tensor, converted: dict, *, destinations: list[str] | None = None+) -> str | None:"""Convert a `double_blocks.X.*` key to `transformer_blocks.X.*` format.Returns the new key, or None if the key was consumed by writing directly into- `converted` (fused QKV split into separate projections).+ `converted` (fused QKV split into separate projections). ``destinations``, when given, collects+ the keys written that way, and only those: a split this function *declines* to perform -- a+ fused qkv whose rows are not divisible by three -- leaves it empty and reports the unchanged key+ through the return value instead, which is what the caller records."""parts = key.split(".")block_idx = parts[1]@@ -74,18 +79,28 @@ def _convert_flux2_double_block_key(key: str, tensor, converted: dict) -> str |if "img_attn.qkv.weight" in rest:if _flux2_malformed_for_chunk(tensor, 3):return key- q, k, v = _flux2_chunk_tensor(tensor, 3)- converted[f"{prefix}.attn.to_q.weight"] = q- converted[f"{prefix}.attn.to_k.weight"] = k- converted[f"{prefix}.attn.to_v.weight"] = v+ targets = [+ f"{prefix}.attn.to_q.weight",+ f"{prefix}.attn.to_k.weight",+ f"{prefix}.attn.to_v.weight",+ ]+ for target, part in zip(targets, _flux2_chunk_tensor(tensor, 3), strict=True):+ converted[target] = part+ if destinations is not None:+ destinations.extend(targets)return Noneelif "txt_attn.qkv.weight" in rest:if _flux2_malformed_for_chunk(tensor, 3):return key- q, k, v = _flux2_chunk_tensor(tensor, 3)- converted[f"{prefix}.attn.add_q_proj.weight"] = q- converted[f"{prefix}.attn.add_k_proj.weight"] = k- converted[f"{prefix}.attn.add_v_proj.weight"] = v+ targets = [+ f"{prefix}.attn.add_q_proj.weight",+ f"{prefix}.attn.add_k_proj.weight",+ f"{prefix}.attn.add_v_proj.weight",+ ]+ for target, part in zip(targets, _flux2_chunk_tensor(tensor, 3), strict=True):+ converted[target] = part+ if destinations is not None:+ destinations.extend(targets)return None# Attention output projection@@ -140,13 +155,20 @@ def _convert_flux2_single_block_key(key: str, tensor, converted: dict) -> str |return key-def _convert_flux2_weight_keys(sd: dict) -> dict:+def _convert_flux2_weight_keys(sd: dict, *, key_map: dict[str, list[str]] | None = None) -> 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 aresubstring 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 ownscale. `convert_flux2_bfl_to_diffusers` keeps them out and places them separately.++ ``key_map``, when given, records where each source key went: one destination for a rename, three+ for a fused ``qkv`` that was split, and the source key itself for one that was *not*. That record+ is what places the side channel. Asking a probe where a layer would go cannot see the+ shape-dependent branches: it answered "three destinations" for a fused weight the converter had+ left alone, so the scale was split three ways onto modules that did not exist while the weight+ kept none."""converted: dict = {}@@ -167,6 +189,7 @@ def _convert_flux2_weight_keys(sd: dict) -> dict:for old_key, tensor in sd.items():new_key = old_key+ split_destinations: list[str] = []# Apply basic renamesif old_key in key_renames:@@ -176,21 +199,27 @@ def _convert_flux2_weight_keys(sd: dict) -> dict:if old_key == "final_layer.adaLN_modulation.1.weight":tensor = _flux2_swap_scale_shift(tensor)converted[new_key] = tensor+ if key_map is not None:+ key_map[old_key] = [new_key]continue# Convert double_blocks.X.* to transformer_blocks.X.*if old_key.startswith("double_blocks."):- new_key = _convert_flux2_double_block_key(old_key, tensor, converted)- if new_key is None:- continue # Key was handled specially+ new_key = _convert_flux2_double_block_key(old_key, tensor, converted, destinations=split_destinations)# Convert single_blocks.X.* to single_transformer_blocks.X.*elif old_key.startswith("single_blocks."):new_key = _convert_flux2_single_block_key(old_key, tensor, converted)- if new_key is None:- continue # Key was handled specially++ if new_key is None:+ # The helper wrote into `converted` itself, and recorded where.+ if key_map is not None:+ key_map[old_key] = split_destinations+ continueif new_key != old_key or new_key not in converted:converted[new_key] = tensor+ if key_map is not None:+ key_map[old_key] = [new_key]return converted@@ -348,17 +377,29 @@ 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 runs-# through every branch of the converter instead of tripping its "malformed, leave alone" guards.+# 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 = 6def _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.+ """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")]@@ -395,14 +436,31 @@ def convert_flux2_bfl_to_diffusers(sd: dict) -> dict: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)+ key_map: dict[str, list[str]] = {}+ converted = _convert_flux2_weight_keys(weights, key_map=key_map)++ # The conversion records where each *key* went; a side channel is keyed on the *module*. Read the+ # module off whatever the source key was rather than assuming it was `<module>.weight`: BFL+ # stores a norm's parameter as `.scale`, and this converter accepts both spellings. (The probe+ # this replaces got that right; a first draft of this map looked the destination up under+ # `<base>.weight` and would have left every such scale behind. Caught in review, not shipped.)+ #+ # 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]] = {}+ for source, moved_to in key_map.items():+ stem = source.rsplit(".", 1)[0] if "." in source else source+ landed = [target[: -len(".weight")] for target in moved_to if target.endswith(".weight")]+ if landed:+ module_map.setdefault(stem, []).extend(landed)for key, value in sd.items():parts = _flux2_sidechannel_parts(key)if parts is None:continuebase, suffix = parts- destinations = _flux2_sidechannel_destinations(base)+ destinations = module_map.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.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 a5c3c5972d..260495cc29 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@@ -205,3 +205,85 @@ class TestAdaLnSwapIsMirroredOntoTheScale:scale = next(v for k, v in converted.items() if k.endswith(".weight_scale"))assert scale.tolist() == [1, 2, 3, 4, 5, 6]+++def test_a_fused_qkv_the_converter_declines_to_split_keeps_its_scale() -> None:+ """The side channel follows where the weight *went*, not where a probe says it would go.++ `_flux2_malformed_for_chunk` leaves a fused qkv alone when its rows are not divisible by three,+ so the weight stays on its BFL key. The probe that used to place the side channel always ran on+ a 6-row tensor, so it answered "three destinations" regardless -- and a per-tensor scale was+ duplicated onto three modules that do not exist while the fp8 weight kept none. Measured before+ the fix: 3 scales pointing at nothing, 1 weight left unscaled.++ Such a file is malformed and its load still fails, on the three projections now missing. What+ this pins is that the conversion reports what it did rather than what it would have done.+ """+ base = "double_blocks.0.img_attn.qkv"+ sd = {+ f"{base}.weight": torch.zeros(7, 4).to(torch.float8_e4m3fn),+ f"{base}.weight_scale": torch.tensor(2.0),+ }++ converted = convert_flux2_bfl_to_diffusers(dict(sd))++ assert set(converted) == {f"{base}.weight", f"{base}.weight_scale"}+++def test_a_fused_qkv_that_is_split_still_carries_its_scale_to_all_three() -> None:+ """The other half: the split case must keep working, or this fix trades one loss for another."""+ base = "double_blocks.0.img_attn.qkv"+ sd = {+ f"{base}.weight": torch.zeros(6, 4).to(torch.float8_e4m3fn),+ f"{base}.weight_scale": torch.tensor(2.0),+ }++ converted = convert_flux2_bfl_to_diffusers(dict(sd))++ for projection in ("to_q", "to_k", "to_v"):+ assert f"transformer_blocks.0.attn.{projection}.weight" in converted+ assert converted[f"transformer_blocks.0.attn.{projection}.weight_scale"] == torch.tensor(2.0)+++def test_a_norm_stored_as_scale_keeps_its_side_channel() -> None:+ """BFL stores a norm's parameter as `.scale`, and this converter accepts both spellings -- so the+ module a side channel belongs to has to be read off whatever the source key was, not assumed to+ be `<module>.weight`.++ Nothing shipped with that assumption: the probe this placement replaces answered by name and+ handled norms correctly. It is pinned because the first draft of the replacement did key the+ lookup on `.weight`, which left the scale on the BFL path while the weight moved, for+ `extract_fp8_scaled_layers` to drop without a word. The same assumption was the Krea-2 defect+ fixed one round earlier, where the parameter is `scale` for a norm and `lin` for a table.+ """+ base = "double_blocks.0.img_attn.norm.query_norm"+ sd = {f"{base}.scale": torch.zeros(4).to(torch.float8_e4m3fn), f"{base}.weight_scale": torch.tensor(2.0)}++ converted = convert_flux2_bfl_to_diffusers(dict(sd))++ assert set(converted) == {+ "transformer_blocks.0.attn.norm_q.weight",+ "transformer_blocks.0.attn.norm_q.weight_scale",+ }+++def test_a_bias_beside_a_quantized_weight_does_not_become_a_second_destination() -> None:+ """A module's side channel belongs to its *weight*. Read every destination as a module and a+ `.bias` contributes one too -- and since this converter's block renames match on `.weight` (its+ other rules rename `.scale` norms and five whole top-level keys), a bias falls through unchanged,+ so the module appears to have gone two places at once. The side channel is+ then taken for a split and `split_qkv_sidechannel` is handed two destinations for three chunks.++ Today's FLUX.2 releases carry no biases, so this guards the rule rather than a shipped file --+ the same rule, and the same near-miss, as the biased Linear in the Krea-2 slice.+ """+ base = "double_blocks.0.img_attn.proj"+ sd = {+ f"{base}.weight": torch.zeros(4, 4).to(torch.float8_e4m3fn),+ f"{base}.bias": torch.zeros(4),+ f"{base}.weight_scale": torch.tensor(2.0),+ }++ converted = convert_flux2_bfl_to_diffusers(dict(sd))++ assert converted["transformer_blocks.0.attn.to_out.0.weight_scale"] == torch.tensor(2.0)