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(lora): identify and convert FLUX kohya and OneTrainer layers outside the blocks (#10206)

Alexander Eichhorn41df6abf9fce
diff --git a/docs/src/content/docs/Users Guide/03.Models/03.model-format-support.mdx b/docs/src/content/docs/Users Guide/03.Models/03.model-format-support.mdx
index 8bf0218f5c..086807bdc6 100644
--- a/docs/src/content/docs/Users Guide/03.Models/03.model-format-support.mdx
+++ b/docs/src/content/docs/Users Guide/03.Models/03.model-format-support.mdx
@@ -232,6 +232,14 @@ starter models do, needs no name. TAEF2, TAEQI2.1 and TAEW2.2 are recognized by
FLUX.1 and FLUX.2 also accept ComfyUI/OneTrainer PEFT LoRAs whose module names start with `diffusion_model.`.
Per-layer `.alpha` values in these `diffusion_model.` files set the LoRA scale.
+FLUX.1 and FLUX.2 kohya LoRAs (`lora_unet_…`) may also train the layers outside the transformer blocks: `img_in`,
+`txt_in`, the time, vector and guidance embedders (`time_in`, `vector_in`, `guidance_in`), the last layer
+(`final_layer_linear`, `final_layer_adaLN_modulation_1`) and FLUX.2's shared modulations. FLUX.1 OneTrainer LoRAs
+(`lora_transformer_…`, its LEGACY_LORA output format) may likewise train `x_embedder`, `context_embedder`, the
+timestep, text and guidance embedders, `norm_out` and the final `proj_out`; these files need single-block layers too.
+A kohya file holding only such layers, with no transformer block or text-encoder layer, is not recognized as FLUX,
+because Qwen-Image and SD 3 name some of them alike. On FLUX.2 the guidance embedder exists in FLUX.2 [dev] only.
+
For SD 1.x / 2.x and FLUX.2, LyCORIS LoKr files may store either Kronecker operand whole or as a
factorized `_a` / `_b` pair. FLUX.2 also accepts LoHA files in the same BFL and kohya layouts.
diff --git a/docs/src/content/docs/Users Guide/03.Models/Local Models/flux-1.mdx b/docs/src/content/docs/Users Guide/03.Models/Local Models/flux-1.mdx
index de6026dcf6..5a50f2629d 100644
--- a/docs/src/content/docs/Users Guide/03.Models/Local Models/flux-1.mdx
+++ b/docs/src/content/docs/Users Guide/03.Models/Local Models/flux-1.mdx
@@ -158,7 +158,9 @@ FLUX.1 LoRAs can be applied from the Generate tab or with the **Apply LoRA - FLU
Collection - FLUX** nodes. They patch the transformer and, where the LoRA includes text-encoder layers, the
CLIP and T5 encoders. Supported layouts include LyCORIS, Diffusers/PEFT, OMI and ComfyUI/OneTrainer PEFT files
whose module names start with `diffusion_model.`. Per-layer `.alpha` values in these `diffusion_model.` files set
-the LoRA scale.
+the LoRA scale. kohya and OneTrainer LoRAs that train layers outside the transformer blocks (`img_in`, `txt_in`,
+the time, vector and guidance embedders, the last layer) are supported too, as long as they also train at least one
+block (OneTrainer files: at least one single-block layer).
## PiD super-resolution decode
diff --git a/docs/src/content/docs/Users Guide/03.Models/Local Models/flux-2.mdx b/docs/src/content/docs/Users Guide/03.Models/Local Models/flux-2.mdx
index 82b4886a85..57bec93cb4 100644
--- a/docs/src/content/docs/Users Guide/03.Models/Local Models/flux-2.mdx
+++ b/docs/src/content/docs/Users Guide/03.Models/Local Models/flux-2.mdx
@@ -207,7 +207,9 @@ FLUX.2 [dev]** (and their *Collection* versions). Supported layouts include LyCO
ComfyUI/OneTrainer PEFT files whose module names start with `diffusion_model.`. Per-layer `.alpha` values in
these `diffusion_model.` files set the LoRA scale.
LyCORIS LoKr and LoHA files are supported in BFL and kohya layouts; each LoKr operand may be stored whole
-or as a factorized `_a` / `_b` pair.
+or as a factorized `_a` / `_b` pair. kohya LoRAs that also train layers outside the transformer blocks (`img_in`,
+`txt_in`, the time embedder, the guidance embedder of FLUX.2 [dev], the last layer and the shared modulations) are
+supported, as long as they train at least one block.
## PiD super-resolution decode
diff --git a/invokeai/backend/model_manager/configs/lora.py b/invokeai/backend/model_manager/configs/lora.py
index 11db340fb6..88de177648 100644
--- a/invokeai/backend/model_manager/configs/lora.py
+++ b/invokeai/backend/model_manager/configs/lora.py
@@ -1,6 +1,6 @@
import re
from abc import ABC
-from collections.abc import Callable
+from collections.abc import Callable, Iterator
from pathlib import Path
from typing import (
Any,
@@ -290,6 +290,103 @@ def _lycoris_out_dim(state_dict: dict[str | int, Any], key_prefix: str) -> int |
return lokr_dim if lokr_dim is not None else _loha_dim(state_dict, key_prefix, 0)
+# Kohya layers outside the blocks (the keys of `FLUX_KOHYA_NON_BLOCK_LAYERS`) whose shape tells FLUX.1 from FLUX.2.
+# Layers that are in no table, and those that are only in the hidden-axis table at 3072, have the same shape in FLUX.1
+# and Klein 4B and stay ambiguous: they apply to either without a shape error, so the FLUX.1 fallback stands for them.
+# The axis ("in" or "out") that is the transformer's hidden size: 3072 in FLUX.1 and Klein 4B, 4096 in Klein 9B.
+_KOHYA_NON_BLOCK_HIDDEN_AXIS = {
+ "img_in": "out",
+ "time_in_in_layer": "out",
+ "time_in_out_layer": "in",
+ "guidance_in_in_layer": "out",
+ "guidance_in_out_layer": "in",
+ "final_layer_linear": "in",
+ "final_layer_adaLN_modulation_1": "in",
+}
+# The axis that is the latent channels, 128 in both Klein variants. FLUX.1 differs (64, and 384 on `img_in` of FLUX.1
+# Fill, which adds the masked image), so only 128 is evidence of FLUX.2; any other width leaves the FLUX.1 fallback.
+# (FLUX.1 Canny/Depth-dev and BFL control LoRAs also take 128 on `img_in`; they are no supported FLUX.1 variant here,
+# and such a file fails on FLUX.1 either way.)
+_KOHYA_NON_BLOCK_LATENT_AXIS = {"img_in": "in", "final_layer_linear": "out"}
+_FLUX2_LATENT_CHANNELS = 128
+
+
+def _kohya_non_block_widths(state_dict: dict[str | int, Any]) -> Iterator[tuple[str, str, int]]:
+ """Yield (layer, axis, width) for each width a kohya layer outside the blocks reveals, as the block checks read it:
+ from `lora_down`/`lora_up`, or from the LyCORIS operands (a whole `lokr_w1` reveals both axes).
+
+ Only for a FLUX kohya file: `final_layer_linear`, `img_in` and the like are other families' module names too.
+ """
+ # Imported here: the conversion module reaches the model loaders, which import the configs.
+ from invokeai.backend.patches.lora_conversions.flux_kohya_lora_conversion_utils import (
+ is_state_dict_likely_in_flux_kohya_format,
+ )
+
+ if not is_state_dict_likely_in_flux_kohya_format(state_dict):
+ return
+ for key in state_dict:
+ if not isinstance(key, str) or not key.startswith("lora_unet_"):
+ continue
+ layer, _, param = key.removeprefix("lora_unet_").partition(".")
+ if layer not in _KOHYA_NON_BLOCK_HIDDEN_AXIS:
+ continue
+ prefix = key.rsplit(".", 1)[0]
+ if param == "lora_down.weight":
+ yield layer, "in", state_dict[key].shape[1]
+ elif param == "lora_up.weight":
+ yield layer, "out", state_dict[key].shape[0]
+ if key.endswith(_LYCORIS_IN_DIM_SUFFIXES) and (in_dim := _lycoris_in_dim(state_dict, prefix)) is not None:
+ yield layer, "in", in_dim
+ if key.endswith(_LYCORIS_OUT_DIM_SUFFIXES) and (out_dim := _lycoris_out_dim(state_dict, prefix)) is not None:
+ yield layer, "out", out_dim
+
+
+_KOHYA_FLUX1_BLOCK_MODULATION_REGEX = re.compile(
+ r"lora_unet_(double_blocks_\d+_(img|txt)_mod_lin|single_blocks_\d+_modulation_lin)\."
+)
+# The block layers whose shape depends on the MLP: the MLP input and output, a single block's fused linear1 (q, k, v and
+# the MLP input) and its linear2 (attention output and MLP). The whole (in, out) shape is compared, because one axis
+# alone can repeat in FLUX.2: Klein 9B's MLP output takes 4096 * 3 = 12288 inputs, as FLUX.1's does.
+_KOHYA_FLUX1_BLOCK_SHAPE_REGEX = re.compile(
+ r"(lora_unet_(?:double_blocks_\d+_(?:img|txt)_mlp_(?P<mlp>[02])|single_blocks_\d+_linear(?P<linear>[12])))\."
+)
+_FLUX1_MLP_WIDTH = _FLUX1_HIDDEN_SIZE * _FLUX1_MLP_RATIO
+_KOHYA_FLUX1_BLOCK_SHAPES = {
+ ("mlp", "0"): (_FLUX1_HIDDEN_SIZE, _FLUX1_MLP_WIDTH),
+ ("mlp", "2"): (_FLUX1_MLP_WIDTH, _FLUX1_HIDDEN_SIZE),
+ ("linear", "1"): (_FLUX1_HIDDEN_SIZE, 3 * _FLUX1_HIDDEN_SIZE + _FLUX1_MLP_WIDTH),
+ ("linear", "2"): (_FLUX1_HIDDEN_SIZE + _FLUX1_MLP_WIDTH, _FLUX1_HIDDEN_SIZE),
+}
+
+
+def _kohya_layer_shape(state_dict: dict[str | int, Any], prefix: str) -> tuple[int | None, int | None]:
+ """(in, out) of a kohya layer, from `lora_down`/`lora_up` or from its LyCORIS operands."""
+ down, up = state_dict.get(f"{prefix}.lora_down.weight"), state_dict.get(f"{prefix}.lora_up.weight")
+ if down is not None or up is not None:
+ return (down.shape[1] if down is not None else None, up.shape[0] if up is not None else None)
+ return _lycoris_in_dim(state_dict, prefix), _lycoris_out_dim(state_dict, prefix)
+
+
+def _has_kohya_flux1_only_blocks(state_dict: dict[str | int, Any]) -> bool:
+ """True if a kohya file holds a block layer that FLUX.2 does not have, or one shaped as FLUX.1's: per-block
+ modulations (FLUX.2 has the shared ones only), or FLUX.1's MLP and single-block shapes, which Klein's 3x MLP ratio
+ with a gated input changes."""
+ seen: set[str] = set()
+ for key in state_dict:
+ if not isinstance(key, str) or not key.startswith("lora_unet_"):
+ continue
+ if _KOHYA_FLUX1_BLOCK_MODULATION_REGEX.match(key):
+ return True
+ match = _KOHYA_FLUX1_BLOCK_SHAPE_REGEX.match(key)
+ if not match or match[1] in seen:
+ continue
+ seen.add(match[1])
+ kind = ("mlp", match["mlp"]) if match["mlp"] else ("linear", match["linear"])
+ if _kohya_layer_shape(state_dict, match[1]) == _KOHYA_FLUX1_BLOCK_SHAPES[kind]:
+ return True
+ return False
+
+
def _is_flux2_lora(mod: ModelOnDisk) -> bool:
"""Check if a FLUX-format LoRA is specifically for FLUX.2 (Klein) rather than FLUX.1.
@@ -424,6 +521,40 @@ def _is_flux2_lora_state_dict(state_dict: dict[str | int, Any]) -> bool:
if in_dim is not None:
return in_dim in _FLUX2_VEC_IN_DIMS
+ # Kohya format: the shared modulations exist only in FLUX.2 (FLUX.1 modulates per block), and a single block's
+ # `linear1` fuses q, k, v and the MLP input, so its width gives the hidden size and the MLP ratio (FLUX.1's is
+ # hidden_size * (3 + _FLUX1_MLP_RATIO)). This covers LoRAs that train no double block and no embedder.
+ for key in state_dict:
+ if not isinstance(key, str):
+ continue
+ if key.startswith(("lora_unet_double_stream_modulation_", "lora_unet_single_stream_modulation_")):
+ return True
+ if key.startswith("lora_unet_single_blocks_") and "_linear1." in key:
+ in_dim = out_dim = None
+ if key.endswith("lora_down.weight"):
+ in_dim = state_dict[key].shape[1]
+ elif key.endswith("lora_up.weight"):
+ out_dim = state_dict[key].shape[0]
+ # Not elif: a whole `lokr_w1` is in both suffix lists and gives both widths.
+ if key.endswith(_LYCORIS_IN_DIM_SUFFIXES):
+ in_dim = _lycoris_in_dim(state_dict, key.rsplit(".", 1)[0])
+ if key.endswith(_LYCORIS_OUT_DIM_SUFFIXES):
+ out_dim = _lycoris_out_dim(state_dict, key.rsplit(".", 1)[0])
+ if in_dim is not None and in_dim != _FLUX1_HIDDEN_SIZE:
+ return True
+ if out_dim is not None and out_dim != _FLUX1_HIDDEN_SIZE * (3 + _FLUX1_MLP_RATIO):
+ return True
+
+ # Kohya format: layers outside the blocks. FLUX.2's 128 latent channels on `img_in` or `final_layer_linear`, or a
+ # hidden-sized axis other than 3072 (Klein 9B), mark FLUX.2 for a LoRA that trains little else.
+ # FLUX.1-shaped blocks in the same file veto this: a block that exists only in FLUX.1 settles the base.
+ for layer, axis, width in _kohya_non_block_widths(state_dict):
+ flux2_width = (_KOHYA_NON_BLOCK_HIDDEN_AXIS[layer] == axis and width != _FLUX1_HIDDEN_SIZE) or (
+ _KOHYA_NON_BLOCK_LATENT_AXIS.get(layer) == axis and width == _FLUX2_LATENT_CHANNELS
+ )
+ if flux2_width and not _has_kohya_flux1_only_blocks(state_dict):
+ return True
+
# Kohya format: check transformer block dimensions (hidden_size and MLP ratio).
# This handles LoRAs that only target transformer blocks (no txt_in/vector_in/context_embedder).
# Klein 9B has hidden_size=4096 (vs 3072 for FLUX.1 and Klein 4B).
@@ -594,6 +725,27 @@ def _get_flux2_lora_variant(state_dict: dict[str | int, Any]) -> Flux2VariantTyp
if in_dim is not None:
return _variant_from_hidden_size(in_dim)
+ # No double block: the hidden size is also the input width of a single block's fused `linear1` and of the shared
+ # modulations.
+ for key in state_dict:
+ if not isinstance(key, str):
+ continue
+ if not key.startswith("lora_unet_") or not (
+ "_single_blocks_" in key and "_linear1." in key or "_stream_modulation_" in key
+ ):
+ continue
+ if key.endswith("lora_down.weight"):
+ return _variant_from_hidden_size(state_dict[key].shape[1])
+ elif key.endswith(_LYCORIS_IN_DIM_SUFFIXES):
+ in_dim = _lycoris_in_dim(state_dict, key.rsplit(".", 1)[0])
+ if in_dim is not None:
+ return _variant_from_hidden_size(in_dim)
+
+ # Layers outside the blocks: their hidden-sized axis.
+ for layer, axis, width in _kohya_non_block_widths(state_dict):
+ if _KOHYA_NON_BLOCK_HIDDEN_AXIS[layer] == axis:
+ return _variant_from_hidden_size(width)
+
return None
diff --git a/invokeai/backend/patches/lora_conversions/flux_bfl_peft_lora_conversion_utils.py b/invokeai/backend/patches/lora_conversions/flux_bfl_peft_lora_conversion_utils.py
index faed919036..f80a4754e5 100644
--- a/invokeai/backend/patches/lora_conversions/flux_bfl_peft_lora_conversion_utils.py
+++ b/invokeai/backend/patches/lora_conversions/flux_bfl_peft_lora_conversion_utils.py
@@ -118,6 +118,9 @@ _NON_BLOCK_RENAMES: dict[str, str] = {
"final_layer.linear": "proj_out",
"time_in.in_layer": "time_guidance_embed.timestep_embedder.linear_1",
"time_in.out_layer": "time_guidance_embed.timestep_embedder.linear_2",
+ # Only FLUX.2 [dev] has a guidance embedder.
+ "guidance_in.in_layer": "time_guidance_embed.guidance_embedder.linear_1",
+ "guidance_in.out_layer": "time_guidance_embed.guidance_embedder.linear_2",
}
# The final-layer modulation also orders its output halves differently: (shift, scale) in BFL's LastLayer,
diff --git a/invokeai/backend/patches/lora_conversions/flux_kohya_lora_conversion_utils.py b/invokeai/backend/patches/lora_conversions/flux_kohya_lora_conversion_utils.py
index 302bc32a63..6728089930 100644
--- a/invokeai/backend/patches/lora_conversions/flux_kohya_lora_conversion_utils.py
+++ b/invokeai/backend/patches/lora_conversions/flux_kohya_lora_conversion_utils.py
@@ -24,12 +24,36 @@ FLUX_KOHYA_TRANSFORMER_KEY_REGEX = (
r"(img_attn|img_mlp|img_mod|txt_attn|txt_mlp|txt_mod|linear1|linear2|modulation)_?(.*)"
)
-# A regex pattern that matches all of the last layer keys in the Kohya FLUX LoRA format.
+# The layers outside the transformer blocks that kohya-style FLUX trainers write, by their kohya name (the BFL module
+# path with periods turned into underscores) and mapped to the BFL module path. A table because underscores cannot be
+# turned back into periods by rule (`time_in_in_layer` is `time_in.in_layer`). The names are BFL's own, so they cover
+# FLUX.1 and FLUX.2 alike: FLUX.2 has no `vector_in` (and `guidance_in` only in [dev]) and adds the three shared
+# modulations, which FLUX.1 lacks.
+# `final_layer_adaLN_modulation_1` keeps BFL's (shift, scale) halves; FLUX.2 runs on diffusers modules, which
+# `convert_bfl_lora_patch_to_diffusers` swaps for it.
+FLUX_KOHYA_NON_BLOCK_LAYERS: dict[str, str] = {
+ "img_in": "img_in",
+ "txt_in": "txt_in",
+ "time_in_in_layer": "time_in.in_layer",
+ "time_in_out_layer": "time_in.out_layer",
+ "vector_in_in_layer": "vector_in.in_layer",
+ "vector_in_out_layer": "vector_in.out_layer",
+ "guidance_in_in_layer": "guidance_in.in_layer",
+ "guidance_in_out_layer": "guidance_in.out_layer",
+ "final_layer_linear": "final_layer.linear",
+ "final_layer_adaLN_modulation_1": "final_layer.adaLN_modulation.1",
+ "double_stream_modulation_img_lin": "double_stream_modulation_img.lin",
+ "double_stream_modulation_txt_lin": "double_stream_modulation_txt.lin",
+ "single_stream_modulation_lin": "single_stream_modulation.lin",
+}
+
+# A regex pattern that matches the keys of FLUX_KOHYA_NON_BLOCK_LAYERS: the layer name, then the LoRA parameter suffix.
# Example keys:
-# lora_unet_final_layer_linear.alpha
-# lora_unet_final_layer_linear.lora_down.weight
-# lora_unet_final_layer_linear.lora_up.weight
-FLUX_KOHYA_LAST_LAYER_KEY_REGEX = r"lora_unet_final_layer_(linear|linear1|linear2)_?(.*)"
+# lora_unet_img_in.alpha
+# lora_unet_final_layer_adaLN_modulation_1.lora_down.weight
+FLUX_KOHYA_NON_BLOCK_KEY_REGEX = (
+ r"lora_unet_(?P<layer>" + "|".join(re.escape(name) for name in FLUX_KOHYA_NON_BLOCK_LAYERS) + r")(?P<suffix>\..*)?"
+)
# A regex pattern that matches all of the CLIP keys in the Kohya FLUX LoRA format.
# Example keys:
@@ -52,15 +76,23 @@ def is_state_dict_likely_in_flux_kohya_format(state_dict: dict[str | int, Any])
This is intended to be a high-precision detector, but it is not guaranteed to have perfect precision. (A
perfect-precision detector would require checking all keys against a whitelist and verifying tensor shapes.)
+
+ Layers outside the blocks (`img_in`, `txt_in`, ...) are accepted, but do not identify FLUX on their own: Qwen-Image,
+ SD3 and others share some of those module names, so at least one block, CLIP or T5 key must be present.
"""
- return all(
- re.match(FLUX_KOHYA_TRANSFORMER_KEY_REGEX, k)
- or re.match(FLUX_KOHYA_LAST_LAYER_KEY_REGEX, k)
- or re.match(FLUX_KOHYA_CLIP_KEY_REGEX, k)
- or re.match(FLUX_KOHYA_T5_KEY_REGEX, k)
- for k in state_dict.keys()
- if isinstance(k, str)
- )
+ anchored = False
+ for k in state_dict.keys():
+ if not isinstance(k, str):
+ continue
+ if (
+ re.match(FLUX_KOHYA_TRANSFORMER_KEY_REGEX, k)
+ or re.match(FLUX_KOHYA_CLIP_KEY_REGEX, k)
+ or re.match(FLUX_KOHYA_T5_KEY_REGEX, k)
+ ):
+ anchored = True
+ elif not re.fullmatch(FLUX_KOHYA_NON_BLOCK_KEY_REGEX, k):
+ return False
+ return anchored
def lora_model_from_flux_kohya_state_dict(state_dict: Dict[str, torch.Tensor]) -> ModelPatchRaw:
@@ -78,9 +110,6 @@ def lora_model_from_flux_kohya_state_dict(state_dict: Dict[str, torch.Tensor]) -
t5_grouped_sd: dict[str, dict[str, torch.Tensor]] = {}
for layer_name, layer_state_dict in grouped_state_dict.items():
if layer_name.startswith("lora_unet"):
- # Skip the final layer. This is incompatible with current model definition.
- if layer_name.startswith("lora_unet_final_layer"):
- continue
transformer_grouped_sd[layer_name] = layer_state_dict
elif layer_name.startswith("lora_te1"):
clip_grouped_sd[layer_name] = layer_state_dict
@@ -139,6 +168,7 @@ def _convert_flux_transformer_kohya_state_dict_to_invoke_format(state_dict: Dict
Example key conversions:
"lora_unet_double_blocks_0_img_attn_proj" -> "double_blocks.0.img_attn.proj"
"lora_unet_double_blocks_0_img_attn_qkv" -> "double_blocks.0.img_attn.qkv"
+ "lora_unet_time_in_in_layer" -> "time_in.in_layer"
"""
def replace_func(match: re.Match[str]) -> str:
@@ -150,9 +180,13 @@ def _convert_flux_transformer_kohya_state_dict_to_invoke_format(state_dict: Dict
converted_dict: dict[str, T] = {}
for k, v in state_dict.items():
match = re.match(FLUX_KOHYA_TRANSFORMER_KEY_REGEX, k)
+ non_block_match = re.fullmatch(FLUX_KOHYA_NON_BLOCK_KEY_REGEX, k)
if match:
new_key = re.sub(FLUX_KOHYA_TRANSFORMER_KEY_REGEX, replace_func, k)
converted_dict[new_key] = v
+ elif non_block_match:
+ new_key = FLUX_KOHYA_NON_BLOCK_LAYERS[non_block_match["layer"]] + (non_block_match["suffix"] or "")
+ converted_dict[new_key] = v
else:
raise ValueError(f"Key '{k}' does not match the expected pattern for FLUX LoRA weights.")
diff --git a/invokeai/backend/patches/lora_conversions/flux_onetrainer_lora_conversion_utils.py b/invokeai/backend/patches/lora_conversions/flux_onetrainer_lora_conversion_utils.py
index 88aeee95e4..47b2475733 100644
--- a/invokeai/backend/patches/lora_conversions/flux_onetrainer_lora_conversion_utils.py
+++ b/invokeai/backend/patches/lora_conversions/flux_onetrainer_lora_conversion_utils.py
@@ -39,6 +39,31 @@ FLUX_ONETRAINER_TRANSFORMER_KEY_REGEX = (
r"lora_transformer_(single_transformer_blocks|transformer_blocks)_(\d+)_(\w+)\.(.*)"
)
+# A regex pattern that matches the layers outside the transformer blocks that OneTrainer trains with a full layer
+# filter. A fixed list: the single blocks have a `proj_out` of their own, and Qwen-Image, SD3 and others share some of
+# these module names. Only the top-level `proj_out` (the last layer) is meant here, which is why the names carry no
+# block index.
+# Example keys:
+# - "lora_transformer_x_embedder.lora_down.weight"
+# - "lora_transformer_time_text_embed_timestep_embedder_linear_1.alpha"
+FLUX_ONETRAINER_NON_BLOCK_KEY_REGEX = (
+ r"lora_transformer_(x_embedder|context_embedder|norm_out_linear|proj_out"
+ r"|time_text_embed_(timestep|text|guidance)_embedder_linear_[12])\..*"
+)
+
+
+def _is_convertible_onetrainer_block_key(key: str) -> bool:
+ """True for a block key whose module the converter's parsing tree can split. FLUX.2's block names
+ (`to_qkv_mlp_proj`, `ff_linear_in`, ...) and other families' do not split, and would fail at conversion."""
+ if not re.match(FLUX_ONETRAINER_TRANSFORMER_KEY_REGEX, key):
+ return False
+ module = key.split(".", 1)[0].removeprefix("lora_")
+ try:
+ insert_periods_into_kohya_key(module, flux_transformer_kohya_parsing_tree)
+ except ValueError:
+ return False
+ return True
+
def is_state_dict_likely_in_flux_onetrainer_format(state_dict: dict[str | int, Any]) -> bool:
"""Checks if the provided state dict is likely in the OneTrainer FLUX LoRA format.
@@ -47,14 +72,31 @@ def is_state_dict_likely_in_flux_onetrainer_format(state_dict: dict[str | int, A
perfect-precision detector would require checking all keys against a whitelist and verifying tensor shapes.)
Note that OneTrainer matches the Kohya format for the CLIP and T5 models.
+
+ The layers outside the blocks (`x_embedder`, `context_embedder`, ...) are accepted, but a state dict needs at least
+ one block, CLIP or T5 key as well, and a single-block key: Qwen-Image and SD3 share those module names and the
+ double-block names, but have no single blocks.
"""
- return all(
- re.match(FLUX_ONETRAINER_TRANSFORMER_KEY_REGEX, k)
- or re.match(FLUX_KOHYA_CLIP_KEY_REGEX, k)
- or re.match(FLUX_KOHYA_T5_KEY_REGEX, k)
- for k in state_dict.keys()
- if isinstance(k, str)
- )
+ anchored = False
+ has_non_block = False
+ has_single_block = False
+ for k in state_dict.keys():
+ if not isinstance(k, str):
+ continue
+ if (
+ _is_convertible_onetrainer_block_key(k)
+ or re.match(FLUX_KOHYA_CLIP_KEY_REGEX, k)
+ or re.match(FLUX_KOHYA_T5_KEY_REGEX, k)
+ ):
+ anchored = True
+ has_single_block = has_single_block or k.startswith("lora_transformer_single_transformer_blocks_")
+ elif re.fullmatch(FLUX_ONETRAINER_NON_BLOCK_KEY_REGEX, k):
+ has_non_block = True
+ else:
+ return False
+ # SD3 and Qwen-Image share FLUX's double-block names and the top-level names above, so those alone cannot tell them
+ # apart. Only FLUX has single blocks, and OneTrainer's full layer filter always trains them.
+ return anchored and (has_single_block or not has_non_block)
def lora_model_from_flux_onetrainer_state_dict(state_dict: Dict[str, torch.Tensor]) -> ModelPatchRaw: # type: ignore
@@ -103,9 +145,18 @@ def lora_model_from_flux_onetrainer_state_dict(state_dict: Dict[str, torch.Tenso
# This parsing tree was generated by calling `generate_kohya_parsing_tree_from_keys()` on the keys in
-# flux_lora_diffusers_format.py.
+# flux_lora_diffusers_format.py, plus the layers outside the blocks (FLUX_ONETRAINER_NON_BLOCK_KEY_REGEX).
flux_transformer_kohya_parsing_tree: ParsingTree = {
"transformer": {
+ "x_embedder": {},
+ "context_embedder": {},
+ "norm_out": {"linear": {}},
+ "proj_out": {},
+ "time_text_embed": {
+ "timestep_embedder": {"linear_1": {}, "linear_2": {}},
+ "text_embedder": {"linear_1": {}, "linear_2": {}},
+ "guidance_embedder": {"linear_1": {}, "linear_2": {}},
+ },
"single_transformer_blocks": {
INDEX_PLACEHOLDER: {
"attn": {"to_k": {}, "to_q": {}, "to_v": {}},
diff --git a/invokeai/backend/patches/lora_conversions/kohya_key_utils.py b/invokeai/backend/patches/lora_conversions/kohya_key_utils.py
index 2272a071fa..9aac7d5b07 100644
--- a/invokeai/backend/patches/lora_conversions/kohya_key_utils.py
+++ b/invokeai/backend/patches/lora_conversions/kohya_key_utils.py
@@ -28,36 +28,38 @@ def insert_periods_into_kohya_key(key: str, parsing_tree: ParsingTree) -> str:
> "module_a.module_b.0.attn.to_k"
```
"""
- # Split key into parts by underscore.
- parts = key.split("_")
-
- # Build up result by walking through parsing tree and parts.
- result_parts: list[str] = []
- current_part = ""
- current_tree = parsing_tree
-
- for part in parts:
- if len(current_part) > 0:
- current_part = current_part + "_"
- current_part += part
-
- if current_part in current_tree:
- # Match found.
- current_tree = current_tree[current_part]
- result_parts.append(current_part)
- current_part = ""
- elif current_part.isnumeric() and INDEX_PLACEHOLDER in current_tree:
- # Match found with index placeholder.
- current_tree = current_tree[INDEX_PLACEHOLDER]
- result_parts.append(current_part)
- current_part = ""
-
- if len(current_part) > 0:
+ result_parts = _split_kohya_key(key.split("_"), parsing_tree)
+ if result_parts is None:
raise ValueError(f"Key {key} does not match parsing tree {parsing_tree}.")
-
return ".".join(result_parts)
+def _split_kohya_key(parts: list[str], parsing_tree: ParsingTree) -> list[str] | None:
+ """Splits underscore-separated key parts into the module names of a parsing tree, or returns None if they do not
+ fit it.
+
+ The shortest module name that fits wins, and a longer one is tried when the rest of the key does not fit below
+ the shorter one: `ff_context_net_0_proj` is `ff_context`, though `ff` is a sibling in the tree too.
+ """
+ # A leading empty part (a double underscore in the key) belongs to no name.
+ while parts and not parts[0]:
+ parts = parts[1:]
+ if not parts:
+ return []
+ for end in range(1, len(parts) + 1):
+ name = "_".join(parts[:end])
+ if name in parsing_tree:
+ subtree = parsing_tree[name]
+ elif end == 1 and name.isnumeric() and INDEX_PLACEHOLDER in parsing_tree:
+ subtree = parsing_tree[INDEX_PLACEHOLDER]
+ else:
+ continue
+ rest = _split_kohya_key(parts[end:], subtree)
+ if rest is not None:
+ return [name, *rest]
+ return None
+
+
def kohya_module_path_is_leaf(module_path: str, parsing_tree: ParsingTree) -> bool:
"""True if a dotted module path walks the tree all the way to a leaf.
diff --git a/tests/backend/model_manager/configs/test_flux3_lora_probe_independence.py b/tests/backend/model_manager/configs/test_flux3_lora_probe_independence.py
index dab3a80235..e3cd8b3c51 100644
--- a/tests/backend/model_manager/configs/test_flux3_lora_probe_independence.py
+++ b/tests/backend/model_manager/configs/test_flux3_lora_probe_independence.py
@@ -19,13 +19,18 @@ import torch
from invokeai.backend.model_manager.configs.base import Config_Base
from invokeai.backend.model_manager.configs.identification_utils import InvalidMatchError, NotAMatchError
-from invokeai.backend.model_manager.configs.lora import LoRA_Diffusers_Flux3_Config, LoRA_LyCORIS_Flux3_Config
-from invokeai.backend.model_manager.taxonomy import BaseModelType
+from invokeai.backend.model_manager.configs.lora import (
+ LoRA_Diffusers_Flux3_Config,
+ LoRA_LyCORIS_Flux2_Config,
+ LoRA_LyCORIS_Flux3_Config,
+)
+from invokeai.backend.model_manager.taxonomy import BaseModelType, Flux2VariantType
from invokeai.backend.patches.lora_conversions import flux3_lora_constants as constants
from invokeai.backend.patches.lora_conversions.formats import flux_format_from_state_dict
from invokeai.backend.patches.lora_conversions.peft_adapter_utils import normalize_peft_adapter_names
from tests.backend.model_manager.load.state_dicts import flux3_klein_keys
from tests.backend.patches.lora_conversions.lora_state_dicts import (
+ flux2_lora_kohya_non_block_format,
flux3_lora_aitoolkit_format,
flux3_lora_comfy_alpha_format,
flux3_lora_diffusers_format,
@@ -36,7 +41,13 @@ from tests.backend.patches.lora_conversions.lora_state_dicts import (
flux_lora_aitoolkit_format,
flux_lora_diffusers_format,
flux_lora_kohya_format,
+ flux_lora_onetrainer_non_block_format,
flux_lora_xlabs_format,
+ qwen_image_lora_kohya_format,
+)
+from tests.backend.patches.lora_conversions.test_flux_onetrainer_lora_conversion_utils import (
+ _meta_sd3,
+ _onetrainer_legacy_state_dict,
)
_DTYPES = {"BF16": torch.bfloat16, "F32": torch.float32, "F8_E4M3": torch.float8_e4m3fn}
@@ -156,6 +167,9 @@ def _flux2_klein_native() -> dict[str, list[int]]:
(flux_lokr_bfl_format.state_dict_keys, "LoRA_LyCORIS_Flux2_Config"),
(_flux2_klein_diffusers(), "LoRA_LyCORIS_Flux2_Config"),
(_flux2_klein_native(), "LoRA_LyCORIS_Flux2_Config"),
+ (flux2_lora_kohya_non_block_format.state_dict_keys, "LoRA_LyCORIS_Flux2_Config"),
+ (flux_lora_onetrainer_non_block_format.state_dict_keys, "LoRA_LyCORIS_FLUX_Config"),
+ (qwen_image_lora_kohya_format.state_dict_keys, "LoRA_LyCORIS_QwenImage_Config"),
],
ids=[
"flux1-ai-toolkit",
@@ -166,12 +180,305 @@ def _flux2_klein_native() -> dict[str, list[int]]:
"flux2-bfl-lokr",
"flux2-klein-diffusers",
"flux2-klein-native",
+ "flux2-klein-kohya-with-non-block-layers",
+ "flux1-onetrainer-with-non-block-layers",
+ "qwen-image-kohya",
],
)
def test_a_flux1_or_flux2_lora_keeps_its_config(keys: dict[str, list[int]], claimed_by: str, tmp_path: Path) -> None:
assert _claimed_by(_state_dict(keys), tmp_path) == [claimed_by]
+def test_a_kohya_lora_with_non_block_layers_is_a_klein_4b_lora(tmp_path: Path) -> None:
+ """`txt_in` of the layers outside the blocks is what tells Klein 4B (7680 inputs) from FLUX.1 (#10030)."""
+ config = _probe(LoRA_LyCORIS_Flux2_Config, _state_dict(flux2_lora_kohya_non_block_format.state_dict_keys), tmp_path)
+
+ assert config.base is BaseModelType.Flux2
+ assert config.variant is Flux2VariantType.Klein4B
+
+
+def _layers(keys: dict[str, Any], *layer_names: str) -> dict[str, Any]:
+ """The fixture's keys of the named kohya layers only (a LoRA that trains just those)."""
+ return {k: v for k, v in keys.items() if k.split(".")[0] in {f"lora_unet_{name}" for name in layer_names}}
+
+
+_KLEIN_4B_KOHYA = flux2_lora_kohya_non_block_format.state_dict_keys
+_FLUX1_IMG_IN_128 = {
+ "lora_unet_img_in.alpha": [],
+ "lora_unet_img_in.lora_down.weight": [16, 128],
+ "lora_unet_img_in.lora_up.weight": [3072, 16],
+}
+
+
+ ("keys", "claimed_by", "variant"),
+ [
+ # The shared modulation exists in FLUX.2 only; the fused linear1 of a Klein 4B single block is 27648 wide where
+ # FLUX.1's is 21504 (a mismatch at apply time if it were read as FLUX.1).
+ (
+ _layers(
+ _KLEIN_4B_KOHYA, "single_blocks_0_linear1", "single_blocks_0_linear2", "single_stream_modulation_lin"
+ ),
+ "LoRA_LyCORIS_Flux2_Config",
+ Flux2VariantType.Klein4B,
+ ),
+ (
+ _layers(_KLEIN_4B_KOHYA, "single_blocks_0_linear1", "single_blocks_0_linear2"),
+ "LoRA_LyCORIS_Flux2_Config",
+ Flux2VariantType.Klein4B,
+ ),
+ (
+ _layers(_KLEIN_4B_KOHYA, "double_stream_modulation_img_lin", "double_blocks_0_txt_attn_qkv"),
+ "LoRA_LyCORIS_Flux2_Config",
+ Flux2VariantType.Klein4B,
+ ),
+ (
+ _layers(flux_lora_kohya_format.state_dict_keys, "single_blocks_0_linear1", "single_blocks_0_linear2"),
+ "LoRA_LyCORIS_FLUX_Config",
+ None,
+ ),
+ # LoKr with a whole `lokr_w1`, whose single key carries both widths: (4 x 6912) by (4 x 768) is Klein 4B's
+ # 27648 x 3072 linear1, (4 x 5376) by (4 x 768) FLUX.1's 21504 x 3072.
+ (
+ {
+ "lora_unet_single_blocks_0_linear1.lokr_w1": [4, 4],
+ "lora_unet_single_blocks_0_linear1.lokr_w2": [6912, 768],
+ "lora_unet_single_blocks_0_linear1.alpha": [],
+ },
+ "LoRA_LyCORIS_Flux2_Config",
+ Flux2VariantType.Klein4B,
+ ),
+ (
+ {
+ "lora_unet_single_blocks_0_linear1.lokr_w1": [4, 4],
+ "lora_unet_single_blocks_0_linear1.lokr_w2": [5376, 768],
+ "lora_unet_single_blocks_0_linear1.alpha": [],
+ },
+ "LoRA_LyCORIS_FLUX_Config",
+ None,
+ ),
+ # A 128-wide `img_in` is Klein's latent, but a block that exists only in FLUX.1 (its single block's 21504-wide
+ # linear1, its 12288-wide MLP, its per-block modulation) settles the file as FLUX.1 (FLUX.1 Fill/Control take
+ # 128 on `img_in` too).
+ *(
+ (
+ {**_layers(flux_lora_kohya_format.state_dict_keys, block), **_FLUX1_IMG_IN_128},
+ "LoRA_LyCORIS_FLUX_Config",
+ None,
+ )
+ for block in ("single_blocks_0_linear1", "double_blocks_0_img_mlp_0", "double_blocks_0_img_mod_lin")
+ ),
+ ],
+ ids=[
+ "klein-single-block-and-modulation",
+ "klein-single-block-only",
+ "klein-modulation-and-txt-attn",
+ "flux1-single-block-only",
+ "klein-lokr-whole-w1",
+ "flux1-lokr-whole-w1",
+ "flux1-single-block-with-img-in-128",
+ "flux1-mlp-with-img-in-128",
+ "flux1-block-modulation-with-img-in-128",
+ ],
+)
+def test_a_partial_kohya_lora_is_identified_by_the_layers_it_has(
+ keys: dict[str, Any], claimed_by: str, variant: Flux2VariantType | None, tmp_path: Path
+) -> None:
+ assert keys
+ state_dict = _state_dict(keys)
+
+ assert _claimed_by(state_dict, tmp_path) == [claimed_by]
+ if variant is not None:
+ assert _probe(LoRA_LyCORIS_Flux2_Config, state_dict, tmp_path).variant is variant
+
+
+def _kohya(layer: str, in_dim: int, out_dim: int, rank: int = 16) -> dict[str, Any]:
+ return {
+ f"lora_unet_{layer}.alpha": [],
+ f"lora_unet_{layer}.lora_down.weight": [rank, in_dim],
+ f"lora_unet_{layer}.lora_up.weight": [out_dim, rank],
+ }
+
+
+_ATTN_PROJ = "double_blocks_0_img_attn_proj" # 3072 x 3072 in FLUX.1 and Klein 4B: says nothing on its own
+# A block layer that names no hidden size outright: a Klein 9B MLP output, 3 x 4096 = 12288 in (as FLUX.1's MLP output
+# takes) and 4096 out.
+_MLP_OUT = "double_blocks_0_img_mlp_2"
+
+
+ ("keys", "claimed_by", "variant"),
+ [
+ # `img_in` takes 128 latent channels in FLUX.2 and 64 in FLUX.1 (reviewer's reproducer, #10206).
+ (
+ _layers(_KLEIN_4B_KOHYA, "img_in", _ATTN_PROJ),
+ "LoRA_LyCORIS_Flux2_Config",
+ Flux2VariantType.Klein4B,
+ ),
+ (
+ _layers(_KLEIN_4B_KOHYA, "final_layer_linear", _ATTN_PROJ),
+ "LoRA_LyCORIS_Flux2_Config",
+ Flux2VariantType.Klein4B,
+ ),
+ (
+ {**_kohya("img_in", 64, 3072), **_kohya(_ATTN_PROJ, 3072, 3072)},
+ "LoRA_LyCORIS_FLUX_Config",
+ None,
+ ),
+ (
+ {**_kohya("final_layer_linear", 3072, 64), **_kohya(_ATTN_PROJ, 3072, 3072)},
+ "LoRA_LyCORIS_FLUX_Config",
+ None,
+ ),
+ # FLUX.1 Fill's `img_in` takes 384 channels (latents, masked image and mask): not FLUX.2's 128.
+ (
+ {**_kohya("img_in", 384, 3072), **_kohya(_ATTN_PROJ, 3072, 3072)},
+ "LoRA_LyCORIS_FLUX_Config",
+ None,
+ ),
+ # Same shapes in FLUX.1 and Klein 4B: either model takes them, so FLUX.1 stays the answer.
+ (
+ _layers(
+ _KLEIN_4B_KOHYA,
+ "time_in_in_layer",
+ "time_in_out_layer",
+ "final_layer_adaLN_modulation_1",
+ _ATTN_PROJ,
+ ),
+ "LoRA_LyCORIS_FLUX_Config",
+ None,
+ ),
+ # Klein 9B (hidden size 4096) shows in the hidden-sized axis of any non-block layer, and `img_in`'s 128 channels.
+ (
+ {**_kohya("time_in_out_layer", 4096, 4096), **_kohya(_MLP_OUT, 12288, 4096)},
+ "LoRA_LyCORIS_Flux2_Config",
+ Flux2VariantType.Klein9B,
+ ),
+ (
+ {**_kohya("img_in", 128, 4096), **_kohya(_MLP_OUT, 12288, 4096)},
+ "LoRA_LyCORIS_Flux2_Config",
+ Flux2VariantType.Klein9B,
+ ),
+ (
+ {**_kohya("final_layer_adaLN_modulation_1", 4096, 8192), **_kohya(_MLP_OUT, 12288, 4096)},
+ "LoRA_LyCORIS_Flux2_Config",
+ Flux2VariantType.Klein9B,
+ ),
+ # The variant comes from the non-block layer alone (the block layer beside it has no hidden size to read).
+ (
+ {**_kohya("img_in", 128, 3072), **_kohya(_MLP_OUT, 9216, 3072)},
+ "LoRA_LyCORIS_Flux2_Config",
+ Flux2VariantType.Klein4B,
+ ),
+ # LoHa: (3072 x r) by (r x 128), twice.
+ (
+ {
+ "lora_unet_img_in.hada_w1_a": [3072, 4],
+ "lora_unet_img_in.hada_w1_b": [4, 128],
+ "lora_unet_img_in.hada_w2_a": [3072, 4],
+ "lora_unet_img_in.hada_w2_b": [4, 128],
+ **_kohya(_ATTN_PROJ, 3072, 3072),
+ },
+ "LoRA_LyCORIS_Flux2_Config",
+ Flux2VariantType.Klein4B,
+ ),
+ # LoKr: whole or factorized operands, the 128 inputs of `img_in` as 2 x 64 (FLUX.1's 64 as 2 x 32).
+ (
+ {
+ "lora_unet_img_in.lokr_w1": [3, 2],
+ "lora_unet_img_in.lokr_w2": [1024, 64],
+ **_kohya(_ATTN_PROJ, 3072, 3072),
+ },
+ "LoRA_LyCORIS_Flux2_Config",
+ Flux2VariantType.Klein4B,
+ ),
+ (
+ {
+ "lora_unet_img_in.lokr_w1_a": [3, 4],
+ "lora_unet_img_in.lokr_w1_b": [4, 2],
+ "lora_unet_img_in.lokr_w2_a": [1024, 4],
+ "lora_unet_img_in.lokr_w2_b": [4, 64],
+ **_kohya(_ATTN_PROJ, 3072, 3072),
+ },
+ "LoRA_LyCORIS_Flux2_Config",
+ Flux2VariantType.Klein4B,
+ ),
+ # Klein 9B: img_in is (4 x 1024) by (2 x 64) = 4096 x 128.
+ (
+ {
+ "lora_unet_img_in.lokr_w1": [4, 2],
+ "lora_unet_img_in.lokr_w2": [1024, 64],
+ **_kohya(_MLP_OUT, 12288, 4096),
+ },
+ "LoRA_LyCORIS_Flux2_Config",
+ Flux2VariantType.Klein9B,
+ ),
+ (
+ {
+ "lora_unet_img_in.lokr_w1": [3, 2],
+ "lora_unet_img_in.lokr_w2": [1024, 32],
+ **_kohya(_ATTN_PROJ, 3072, 3072),
+ },
+ "LoRA_LyCORIS_FLUX_Config",
+ None,
+ ),
+ (
+ {
+ "lora_unet_final_layer_linear.lokr_w1": [2, 3],
+ "lora_unet_final_layer_linear.lokr_w2": [64, 1024],
+ **_kohya(_ATTN_PROJ, 3072, 3072),
+ },
+ "LoRA_LyCORIS_Flux2_Config",
+ Flux2VariantType.Klein4B,
+ ),
+ ],
+ ids=[
+ "klein-img-in",
+ "klein-final-layer-linear",
+ "flux1-img-in",
+ "flux1-final-layer-linear",
+ "flux1-fill-img-in",
+ "shared-shapes-stay-flux1",
+ "klein9b-time-in",
+ "klein9b-img-in",
+ "klein9b-final-layer-adaln",
+ "klein-variant-from-img-in",
+ "klein-loha-img-in",
+ "klein-lokr-img-in-whole",
+ "klein-lokr-img-in-factorized",
+ "klein9b-lokr-img-in",
+ "flux1-lokr-img-in",
+ "klein-lokr-final-layer-linear",
+ ],
+)
+def test_a_kohya_lora_is_identified_by_the_shape_of_its_non_block_layers(
+ keys: dict[str, Any], claimed_by: str, variant: Flux2VariantType | None, tmp_path: Path
+) -> None:
+ """A layer outside the blocks that takes other widths in FLUX.2 than in FLUX.1 identifies the family, though the
+ block layers beside it fit both."""
+ state_dict = _state_dict(keys)
+
+ assert _claimed_by(state_dict, tmp_path) == [claimed_by]
+ if variant is not None:
+ assert _probe(LoRA_LyCORIS_Flux2_Config, state_dict, tmp_path).variant is variant
+
+
+def test_an_sd3_kohya_folder_with_a_final_layer_is_not_claimed_as_flux2(tmp_path: Path) -> None:
+ """SD3 names its last layer `final_layer_linear` too, 1536 wide: not a Klein hidden size. Only a FLUX kohya file is
+ read for its non-block layers."""
+ keys = {**_kohya("joint_blocks_0_x_block_attn_qkv", 1536, 4608), **_kohya("final_layer_linear", 1536, 64)}
+
+ assert _claimed_by(_state_dict(keys), tmp_path, folder=True) == ["LoRA_Diffusers_SD3_Config"]
+
+
+def test_an_sd3_onetrainer_lora_with_top_level_layers_is_not_claimed_as_flux(tmp_path: Path) -> None:
+ """SD3's top-level layers and double blocks are named like FLUX's, which OneTrainer's LEGACY_LORA keys keep; only
+ FLUX has single blocks."""
+ state_dict = _onetrainer_legacy_state_dict(_meta_sd3(), lambda name: True)
+
+ assert "LoRA_LyCORIS_FLUX_Config" not in _claimed_by(state_dict, tmp_path)
+
+
def test_a_distillation_extract_is_refused_with_its_reason(tmp_path: Path) -> None:
"""Its norm-scale deltas and flow-map embedder weights are no LoRA layers: the installer names them, and what to
install instead, rather than registering a file nothing applies in full as an unknown model."""
diff --git a/tests/backend/patches/lora_conversions/lora_state_dicts/flux2_lora_kohya_non_block_format.py b/tests/backend/patches/lora_conversions/lora_state_dicts/flux2_lora_kohya_non_block_format.py
new file mode 100644
index 0000000000..f23d3f01fb
--- /dev/null
+++ b/tests/backend/patches/lora_conversions/lora_state_dicts/flux2_lora_kohya_non_block_format.py
@@ -0,0 +1,75 @@
+"""A FLUX.2 Klein 4B LoRA in the kohya format with BFL module names, a distillation extract at rank 16
+(`flux2-klein-4b_kohya-bfl_pjmixers-distill-extract-rank16.safetensors`, issue #10030).
+
+Captured on 2026-11-08 with `scripts/capture_state_dict_fixture.py`,
+which reads the header only.
+
+Subsetting rule: block 0 of `double_blocks` and of `single_blocks`, plus every key outside a block stack. Values are
+`(shape, dtype)`.
+
+Besides the block layers the file trains every non-block layer of the model: the input projections (`img_in`,
+`txt_in` with 7680 inputs, which is what marks Klein 4B), the time embedder (`time_in_*`), the last layer
+(`final_layer_linear` and `final_layer_adaLN_modulation_1`) and the FLUX.2 shared modulations
+(`double_stream_modulation_{img,txt}_lin`, `single_stream_modulation_lin`). Klein has no `vector_in`. Names are
+BFL's module paths with every period turned into an underscore, so `time_in_in_layer` is `time_in.in_layer`.
+"""
+
+state_dict_keys: dict[str, tuple[list[int], str]] = {
+ "lora_unet_double_blocks_0_img_attn_proj.alpha": ([], "BF16"),
+ "lora_unet_double_blocks_0_img_attn_proj.lora_down.weight": ([16, 3072], "BF16"),
+ "lora_unet_double_blocks_0_img_attn_proj.lora_up.weight": ([3072, 16], "BF16"),
+ "lora_unet_double_blocks_0_img_attn_qkv.alpha": ([], "BF16"),
+ "lora_unet_double_blocks_0_img_attn_qkv.lora_down.weight": ([16, 3072], "BF16"),
+ "lora_unet_double_blocks_0_img_attn_qkv.lora_up.weight": ([9216, 16], "BF16"),
+ "lora_unet_double_blocks_0_img_mlp_0.alpha": ([], "BF16"),
+ "lora_unet_double_blocks_0_img_mlp_0.lora_down.weight": ([16, 3072], "BF16"),
+ "lora_unet_double_blocks_0_img_mlp_0.lora_up.weight": ([18432, 16], "BF16"),
+ "lora_unet_double_blocks_0_img_mlp_2.alpha": ([], "BF16"),
+ "lora_unet_double_blocks_0_img_mlp_2.lora_down.weight": ([16, 9216], "BF16"),
+ "lora_unet_double_blocks_0_img_mlp_2.lora_up.weight": ([3072, 16], "BF16"),
+ "lora_unet_double_blocks_0_txt_attn_proj.alpha": ([], "BF16"),
+ "lora_unet_double_blocks_0_txt_attn_proj.lora_down.weight": ([16, 3072], "BF16"),
+ "lora_unet_double_blocks_0_txt_attn_proj.lora_up.weight": ([3072, 16], "BF16"),
+ "lora_unet_double_blocks_0_txt_attn_qkv.alpha": ([], "BF16"),
+ "lora_unet_double_blocks_0_txt_attn_qkv.lora_down.weight": ([16, 3072], "BF16"),
+ "lora_unet_double_blocks_0_txt_attn_qkv.lora_up.weight": ([9216, 16], "BF16"),
+ "lora_unet_double_blocks_0_txt_mlp_0.alpha": ([], "BF16"),
+ "lora_unet_double_blocks_0_txt_mlp_0.lora_down.weight": ([16, 3072], "BF16"),
+ "lora_unet_double_blocks_0_txt_mlp_0.lora_up.weight": ([18432, 16], "BF16"),
+ "lora_unet_double_blocks_0_txt_mlp_2.alpha": ([], "BF16"),
+ "lora_unet_double_blocks_0_txt_mlp_2.lora_down.weight": ([16, 9216], "BF16"),
+ "lora_unet_double_blocks_0_txt_mlp_2.lora_up.weight": ([3072, 16], "BF16"),
+ "lora_unet_double_stream_modulation_img_lin.alpha": ([], "BF16"),
+ "lora_unet_double_stream_modulation_img_lin.lora_down.weight": ([16, 3072], "BF16"),
+ "lora_unet_double_stream_modulation_img_lin.lora_up.weight": ([18432, 16], "BF16"),
+ "lora_unet_double_stream_modulation_txt_lin.alpha": ([], "BF16"),
+ "lora_unet_double_stream_modulation_txt_lin.lora_down.weight": ([16, 3072], "BF16"),
+ "lora_unet_double_stream_modulation_txt_lin.lora_up.weight": ([18432, 16], "BF16"),
+ "lora_unet_final_layer_adaLN_modulation_1.alpha": ([], "BF16"),
+ "lora_unet_final_layer_adaLN_modulation_1.lora_down.weight": ([16, 3072], "BF16"),
+ "lora_unet_final_layer_adaLN_modulation_1.lora_up.weight": ([6144, 16], "BF16"),
+ "lora_unet_final_layer_linear.alpha": ([], "BF16"),
+ "lora_unet_final_layer_linear.lora_down.weight": ([16, 3072], "BF16"),
+ "lora_unet_final_layer_linear.lora_up.weight": ([128, 16], "BF16"),
+ "lora_unet_img_in.alpha": ([], "BF16"),
+ "lora_unet_img_in.lora_down.weight": ([16, 128], "BF16"),
+ "lora_unet_img_in.lora_up.weight": ([3072, 16], "BF16"),
+ "lora_unet_single_blocks_0_linear1.alpha": ([], "BF16"),
+ "lora_unet_single_blocks_0_linear1.lora_down.weight": ([16, 3072], "BF16"),
+ "lora_unet_single_blocks_0_linear1.lora_up.weight": ([27648, 16], "BF16"),
+ "lora_unet_single_blocks_0_linear2.alpha": ([], "BF16"),
+ "lora_unet_single_blocks_0_linear2.lora_down.weight": ([16, 12288], "BF16"),
+ "lora_unet_single_blocks_0_linear2.lora_up.weight": ([3072, 16], "BF16"),
+ "lora_unet_single_stream_modulation_lin.alpha": ([], "BF16"),
+ "lora_unet_single_stream_modulation_lin.lora_down.weight": ([16, 3072], "BF16"),
+ "lora_unet_single_stream_modulation_lin.lora_up.weight": ([9216, 16], "BF16"),
+ "lora_unet_time_in_in_layer.alpha": ([], "BF16"),
+ "lora_unet_time_in_in_layer.lora_down.weight": ([16, 256], "BF16"),
+ "lora_unet_time_in_in_layer.lora_up.weight": ([3072, 16], "BF16"),
+ "lora_unet_time_in_out_layer.alpha": ([], "BF16"),
+ "lora_unet_time_in_out_layer.lora_down.weight": ([16, 3072], "BF16"),
+ "lora_unet_time_in_out_layer.lora_up.weight": ([3072, 16], "BF16"),
+ "lora_unet_txt_in.alpha": ([], "BF16"),
+ "lora_unet_txt_in.lora_down.weight": ([16, 7680], "BF16"),
+ "lora_unet_txt_in.lora_up.weight": ([3072, 16], "BF16"),
+}
diff --git a/tests/backend/patches/lora_conversions/lora_state_dicts/flux_lora_onetrainer_non_block_format.py b/tests/backend/patches/lora_conversions/lora_state_dicts/flux_lora_onetrainer_non_block_format.py
new file mode 100644
index 0000000000..3480ab475c
--- /dev/null
+++ b/tests/backend/patches/lora_conversions/lora_state_dicts/flux_lora_onetrainer_non_block_format.py
@@ -0,0 +1,108 @@
+"""A FLUX.1 dev LoRA as OneTrainer writes it in its LEGACY_LORA format, with every layer of the transformer trained
+(rank 4, no text encoders, no DoRA).
+
+Generated on 2026-11-08 with OneTrainer (commit 4597d2f0) code: its `LoRAModuleWrapper` around a meta-device
+`FluxTransformer2DModel` (FLUX.1 dev config), saved by `FluxLoRASaver` in the LEGACY_LORA format, with the full layer
+filter and random values.
+
+Subsetting rule: block 0 of `transformer_blocks` and of `single_transformer_blocks`, plus every key outside a block
+stack. Values are `(shape, dtype)`.
+
+Keys are diffusers module paths with periods turned into underscores under `lora_transformer_`. Besides the
+block layers the file trains the layers a block filter leaves out: `x_embedder`, `context_embedder`,
+`time_text_embed_{timestep,text,guidance}_embedder_linear_{1,2}`, `norm_out_linear` and the top-level `proj_out`
+(not the single blocks' own `proj_out`).
+"""
+
+state_dict_keys: dict[str, tuple[list[int], str]] = {
+ "lora_transformer_context_embedder.alpha": ([], "BF16"),
+ "lora_transformer_context_embedder.lora_down.weight": ([4, 4096], "BF16"),
+ "lora_transformer_context_embedder.lora_up.weight": ([3072, 4], "BF16"),
+ "lora_transformer_norm_out_linear.alpha": ([], "BF16"),
+ "lora_transformer_norm_out_linear.lora_down.weight": ([4, 3072], "BF16"),
+ "lora_transformer_norm_out_linear.lora_up.weight": ([6144, 4], "BF16"),
+ "lora_transformer_proj_out.alpha": ([], "BF16"),
+ "lora_transformer_proj_out.lora_down.weight": ([4, 3072], "BF16"),
+ "lora_transformer_proj_out.lora_up.weight": ([64, 4], "BF16"),
+ "lora_transformer_single_transformer_blocks_0_attn_to_k.alpha": ([], "BF16"),
+ "lora_transformer_single_transformer_blocks_0_attn_to_k.lora_down.weight": ([4, 3072], "BF16"),
+ "lora_transformer_single_transformer_blocks_0_attn_to_k.lora_up.weight": ([3072, 4], "BF16"),
+ "lora_transformer_single_transformer_blocks_0_attn_to_q.alpha": ([], "BF16"),
+ "lora_transformer_single_transformer_blocks_0_attn_to_q.lora_down.weight": ([4, 3072], "BF16"),
+ "lora_transformer_single_transformer_blocks_0_attn_to_q.lora_up.weight": ([3072, 4], "BF16"),
+ "lora_transformer_single_transformer_blocks_0_attn_to_v.alpha": ([], "BF16"),
+ "lora_transformer_single_transformer_blocks_0_attn_to_v.lora_down.weight": ([4, 3072], "BF16"),
+ "lora_transformer_single_transformer_blocks_0_attn_to_v.lora_up.weight": ([3072, 4], "BF16"),
+ "lora_transformer_single_transformer_blocks_0_norm_linear.alpha": ([], "BF16"),
+ "lora_transformer_single_transformer_blocks_0_norm_linear.lora_down.weight": ([4, 3072], "BF16"),
+ "lora_transformer_single_transformer_blocks_0_norm_linear.lora_up.weight": ([9216, 4], "BF16"),
+ "lora_transformer_single_transformer_blocks_0_proj_mlp.alpha": ([], "BF16"),
+ "lora_transformer_single_transformer_blocks_0_proj_mlp.lora_down.weight": ([4, 3072], "BF16"),
+ "lora_transformer_single_transformer_blocks_0_proj_mlp.lora_up.weight": ([12288, 4], "BF16"),
+ "lora_transformer_single_transformer_blocks_0_proj_out.alpha": ([], "BF16"),
+ "lora_transformer_single_transformer_blocks_0_proj_out.lora_down.weight": ([4, 15360], "BF16"),
+ "lora_transformer_single_transformer_blocks_0_proj_out.lora_up.weight": ([3072, 4], "BF16"),
+ "lora_transformer_time_text_embed_guidance_embedder_linear_1.alpha": ([], "BF16"),
+ "lora_transformer_time_text_embed_guidance_embedder_linear_1.lora_down.weight": ([4, 256], "BF16"),
+ "lora_transformer_time_text_embed_guidance_embedder_linear_1.lora_up.weight": ([3072, 4], "BF16"),
+ "lora_transformer_time_text_embed_guidance_embedder_linear_2.alpha": ([], "BF16"),
+ "lora_transformer_time_text_embed_guidance_embedder_linear_2.lora_down.weight": ([4, 3072], "BF16"),
+ "lora_transformer_time_text_embed_guidance_embedder_linear_2.lora_up.weight": ([3072, 4], "BF16"),
+ "lora_transformer_time_text_embed_text_embedder_linear_1.alpha": ([], "BF16"),
+ "lora_transformer_time_text_embed_text_embedder_linear_1.lora_down.weight": ([4, 768], "BF16"),
+ "lora_transformer_time_text_embed_text_embedder_linear_1.lora_up.weight": ([3072, 4], "BF16"),
+ "lora_transformer_time_text_embed_text_embedder_linear_2.alpha": ([], "BF16"),
+ "lora_transformer_time_text_embed_text_embedder_linear_2.lora_down.weight": ([4, 3072], "BF16"),
+ "lora_transformer_time_text_embed_text_embedder_linear_2.lora_up.weight": ([3072, 4], "BF16"),
+ "lora_transformer_time_text_embed_timestep_embedder_linear_1.alpha": ([], "BF16"),
+ "lora_transformer_time_text_embed_timestep_embedder_linear_1.lora_down.weight": ([4, 256], "BF16"),
+ "lora_transformer_time_text_embed_timestep_embedder_linear_1.lora_up.weight": ([3072, 4], "BF16"),
+ "lora_transformer_time_text_embed_timestep_embedder_linear_2.alpha": ([], "BF16"),
+ "lora_transformer_time_text_embed_timestep_embedder_linear_2.lora_down.weight": ([4, 3072], "BF16"),
+ "lora_transformer_time_text_embed_timestep_embedder_linear_2.lora_up.weight": ([3072, 4], "BF16"),
+ "lora_transformer_transformer_blocks_0_attn_add_k_proj.alpha": ([], "BF16"),
+ "lora_transformer_transformer_blocks_0_attn_add_k_proj.lora_down.weight": ([4, 3072], "BF16"),
+ "lora_transformer_transformer_blocks_0_attn_add_k_proj.lora_up.weight": ([3072, 4], "BF16"),
+ "lora_transformer_transformer_blocks_0_attn_add_q_proj.alpha": ([], "BF16"),
+ "lora_transformer_transformer_blocks_0_attn_add_q_proj.lora_down.weight": ([4, 3072], "BF16"),
+ "lora_transformer_transformer_blocks_0_attn_add_q_proj.lora_up.weight": ([3072, 4], "BF16"),
+ "lora_transformer_transformer_blocks_0_attn_add_v_proj.alpha": ([], "BF16"),
+ "lora_transformer_transformer_blocks_0_attn_add_v_proj.lora_down.weight": ([4, 3072], "BF16"),
+ "lora_transformer_transformer_blocks_0_attn_add_v_proj.lora_up.weight": ([3072, 4], "BF16"),
+ "lora_transformer_transformer_blocks_0_attn_to_add_out.alpha": ([], "BF16"),
+ "lora_transformer_transformer_blocks_0_attn_to_add_out.lora_down.weight": ([4, 3072], "BF16"),
+ "lora_transformer_transformer_blocks_0_attn_to_add_out.lora_up.weight": ([3072, 4], "BF16"),
+ "lora_transformer_transformer_blocks_0_attn_to_k.alpha": ([], "BF16"),
+ "lora_transformer_transformer_blocks_0_attn_to_k.lora_down.weight": ([4, 3072], "BF16"),
+ "lora_transformer_transformer_blocks_0_attn_to_k.lora_up.weight": ([3072, 4], "BF16"),
+ "lora_transformer_transformer_blocks_0_attn_to_out_0.alpha": ([], "BF16"),
+ "lora_transformer_transformer_blocks_0_attn_to_out_0.lora_down.weight": ([4, 3072], "BF16"),
+ "lora_transformer_transformer_blocks_0_attn_to_out_0.lora_up.weight": ([3072, 4], "BF16"),
+ "lora_transformer_transformer_blocks_0_attn_to_q.alpha": ([], "BF16"),
+ "lora_transformer_transformer_blocks_0_attn_to_q.lora_down.weight": ([4, 3072], "BF16"),
+ "lora_transformer_transformer_blocks_0_attn_to_q.lora_up.weight": ([3072, 4], "BF16"),
+ "lora_transformer_transformer_blocks_0_attn_to_v.alpha": ([], "BF16"),
+ "lora_transformer_transformer_blocks_0_attn_to_v.lora_down.weight": ([4, 3072], "BF16"),
+ "lora_transformer_transformer_blocks_0_attn_to_v.lora_up.weight": ([3072, 4], "BF16"),
+ "lora_transformer_transformer_blocks_0_ff_context_net_0_proj.alpha": ([], "BF16"),
+ "lora_transformer_transformer_blocks_0_ff_context_net_0_proj.lora_down.weight": ([4, 3072], "BF16"),
+ "lora_transformer_transformer_blocks_0_ff_context_net_0_proj.lora_up.weight": ([12288, 4], "BF16"),
+ "lora_transformer_transformer_blocks_0_ff_context_net_2.alpha": ([], "BF16"),
+ "lora_transformer_transformer_blocks_0_ff_context_net_2.lora_down.weight": ([4, 12288], "BF16"),
+ "lora_transformer_transformer_blocks_0_ff_context_net_2.lora_up.weight": ([3072, 4], "BF16"),
+ "lora_transformer_transformer_blocks_0_ff_net_0_proj.alpha": ([], "BF16"),
+ "lora_transformer_transformer_blocks_0_ff_net_0_proj.lora_down.weight": ([4, 3072], "BF16"),
+ "lora_transformer_transformer_blocks_0_ff_net_0_proj.lora_up.weight": ([12288, 4], "BF16"),
+ "lora_transformer_transformer_blocks_0_ff_net_2.alpha": ([], "BF16"),
+ "lora_transformer_transformer_blocks_0_ff_net_2.lora_down.weight": ([4, 12288], "BF16"),
+ "lora_transformer_transformer_blocks_0_ff_net_2.lora_up.weight": ([3072, 4], "BF16"),
+ "lora_transformer_transformer_blocks_0_norm1_context_linear.alpha": ([], "BF16"),
+ "lora_transformer_transformer_blocks_0_norm1_context_linear.lora_down.weight": ([4, 3072], "BF16"),
+ "lora_transformer_transformer_blocks_0_norm1_context_linear.lora_up.weight": ([18432, 4], "BF16"),
+ "lora_transformer_transformer_blocks_0_norm1_linear.alpha": ([], "BF16"),
+ "lora_transformer_transformer_blocks_0_norm1_linear.lora_down.weight": ([4, 3072], "BF16"),
+ "lora_transformer_transformer_blocks_0_norm1_linear.lora_up.weight": ([18432, 4], "BF16"),
+ "lora_transformer_x_embedder.alpha": ([], "BF16"),
+ "lora_transformer_x_embedder.lora_down.weight": ([4, 64], "BF16"),
+ "lora_transformer_x_embedder.lora_up.weight": ([3072, 4], "BF16"),
+}
diff --git a/tests/backend/patches/lora_conversions/test_flux_kohya_lora_conversion_utils.py b/tests/backend/patches/lora_conversions/test_flux_kohya_lora_conversion_utils.py
index 35a5f5a909..5d14e0a874 100644
--- a/tests/backend/patches/lora_conversions/test_flux_kohya_lora_conversion_utils.py
+++ b/tests/backend/patches/lora_conversions/test_flux_kohya_lora_conversion_utils.py
@@ -1,10 +1,17 @@
import accelerate
import pytest
import torch
+from diffusers import Flux2Transformer2DModel
+from diffusers.models.normalization import AdaLayerNormContinuous
from invokeai.backend.flux.model import Flux
+from invokeai.backend.flux.modules.layers import LastLayer
from invokeai.backend.flux.util import get_flux_transformers_params
from invokeai.backend.model_manager.taxonomy import FluxVariantType
+from invokeai.backend.patches.layer_patcher import LayerPatcher
+from invokeai.backend.patches.lora_conversions.flux_bfl_peft_lora_conversion_utils import (
+ convert_bfl_lora_patch_to_diffusers,
+)
from invokeai.backend.patches.lora_conversions.flux_kohya_lora_conversion_utils import (
_convert_flux_transformer_kohya_state_dict_to_invoke_format,
is_state_dict_likely_in_flux_kohya_format,
@@ -14,6 +21,10 @@ from invokeai.backend.patches.lora_conversions.flux_lora_constants import (
FLUX_LORA_CLIP_PREFIX,
FLUX_LORA_TRANSFORMER_PREFIX,
)
+from invokeai.backend.patches.model_patch_raw import ModelPatchRaw
+from tests.backend.patches.lora_conversions.lora_state_dicts.flux2_lora_kohya_non_block_format import (
+ state_dict_keys as flux2_kohya_non_block_state_dict_keys,
+)
from tests.backend.patches.lora_conversions.lora_state_dicts.flux_dora_onetrainer_format import (
state_dict_keys as flux_onetrainer_state_dict_keys,
)
@@ -26,6 +37,9 @@ from tests.backend.patches.lora_conversions.lora_state_dicts.flux_lora_kohya_for
from tests.backend.patches.lora_conversions.lora_state_dicts.flux_lora_kohya_with_te1_format import (
state_dict_keys as flux_kohya_te1_state_dict_keys,
)
+from tests.backend.patches.lora_conversions.lora_state_dicts.qwen_image_lora_kohya_format import (
+ state_dict_keys as qwen_image_kohya_state_dict_keys,
+)
from tests.backend.patches.lora_conversions.lora_state_dicts.utils import keys_to_mock_state_dict
@@ -114,3 +128,216 @@ def test_lora_model_from_flux_kohya_state_dict(sd_keys: dict[str, list[int]]):
lora_model_keys = set(lora_model.layers.keys())
lora_model_keys = {k.replace(".", "_") for k in lora_model_keys}
assert lora_model_keys == expected_layer_keys
+
+
+def _fixture_state_dict(keys: dict[str, tuple[list[int], str]]) -> dict[str, torch.Tensor]:
+ # float32 whatever the file's dtype: CPU bf16 matmuls are not safe on every runner.
+ return keys_to_mock_state_dict({k: shape for k, (shape, _dtype) in keys.items()})
+
+
+def test_flux_kohya_format_with_layers_outside_the_blocks_is_detected():
+ """A FLUX.2 kohya LoRA that trains `img_in`, `txt_in`, the time embedder, the last layer and the modulations is
+ FLUX kohya, not unidentified (#10030)."""
+ state_dict = _fixture_state_dict(flux2_kohya_non_block_state_dict_keys)
+
+ assert is_state_dict_likely_in_flux_kohya_format(state_dict)
+
+
+def test_flux_kohya_format_needs_a_block_next_to_the_layers_outside_the_blocks():
+ """`img_in` and `txt_in` are also Qwen-Image and SD3 module names: alone they do not make a FLUX LoRA."""
+ only_non_block = {
+ k: v
+ for k, v in _fixture_state_dict(flux2_kohya_non_block_state_dict_keys).items()
+ if k.startswith(("lora_unet_img_in.", "lora_unet_txt_in."))
+ }
+ assert len(only_non_block) == 6
+
+ assert not is_state_dict_likely_in_flux_kohya_format(only_non_block)
+ assert not is_state_dict_likely_in_flux_kohya_format(keys_to_mock_state_dict(qwen_image_kohya_state_dict_keys))
+
+
+def test_flux_kohya_format_rejects_an_unknown_layer_next_to_flux_blocks():
+ state_dict = _fixture_state_dict(flux2_kohya_non_block_state_dict_keys)
+ state_dict["lora_unet_final_layer_something_else.lora_down.weight"] = torch.empty(4, 4)
+
+ assert not is_state_dict_likely_in_flux_kohya_format(state_dict)
+
+
+def test_flux1_kohya_layers_outside_the_blocks_land_on_every_bfl_non_block_linear():
+ """Every Linear of the FLUX.1 dev model outside its blocks, named as kohya names it (module path with the periods
+ turned into underscores), converts to that module's path."""
+ with accelerate.init_empty_weights():
+ model = Flux(get_flux_transformers_params(FluxVariantType.Dev))
+ non_block_linears = {
+ name: module
+ for name, module in model.named_modules()
+ if isinstance(module, torch.nn.Linear) and not name.startswith(("double_blocks", "single_blocks"))
+ }
+ assert {"img_in", "txt_in", "guidance_in.out_layer", "final_layer.adaLN_modulation.1"} <= set(non_block_linears)
+
+ state_dict: dict[str, torch.Tensor] = {
+ # One block layer, as the detector needs one.
+ "lora_unet_double_blocks_0_img_attn_proj.lora_down.weight": torch.empty(4, 3072),
+ "lora_unet_double_blocks_0_img_attn_proj.lora_up.weight": torch.empty(3072, 4),
+ }
+ for name, module in non_block_linears.items():
+ kohya_name = "lora_unet_" + name.replace(".", "_")
+ state_dict[f"{kohya_name}.lora_down.weight"] = torch.empty(4, module.in_features)
+ state_dict[f"{kohya_name}.lora_up.weight"] = torch.empty(module.out_features, 4)
+ assert is_state_dict_likely_in_flux_kohya_format(state_dict)
+
+ lora_model = lora_model_from_flux_kohya_state_dict(state_dict)
+
+ assert set(lora_model.layers) == {
+ FLUX_LORA_TRANSFORMER_PREFIX + name for name in [*non_block_linears, "double_blocks.0.img_attn.proj"]
+ }
+
+
+def test_flux2_kohya_lora_with_layers_outside_the_blocks_resolves_on_the_flux2_model():
+ """The converted BFL names reach diffusers' Flux2 modules through the conversion the FLUX.2 denoiser applies, and
+ every patch fits the module it lands on."""
+ state_dict = _fixture_state_dict(flux2_kohya_non_block_state_dict_keys)
+ with accelerate.init_empty_weights():
+ # Klein 4B's widths, one block of each kind (the fixture holds block 0 of each).
+ model = Flux2Transformer2DModel(
+ patch_size=1,
+ in_channels=128,
+ num_layers=1,
+ num_single_layers=1,
+ attention_head_dim=128,
+ num_attention_heads=24,
+ joint_attention_dim=7680,
+ )
+
+ patch = convert_bfl_lora_patch_to_diffusers(lora_model_from_flux_kohya_state_dict(state_dict))
+
+ for key, layer in patch.layers.items():
+ assert key.startswith(FLUX_LORA_TRANSFORMER_PREFIX)
+ module = model.get_submodule(key.removeprefix(FLUX_LORA_TRANSFORMER_PREFIX))
+ delta = layer.get_parameters({"weight": module.weight}, weight=1.0)["weight"]
+ assert delta.shape == module.weight.shape, key
+ non_block_targets = {k.removeprefix(FLUX_LORA_TRANSFORMER_PREFIX) for k in patch.layers if "blocks" not in k}
+ assert non_block_targets == {
+ "x_embedder",
+ "context_embedder",
+ "time_guidance_embed.timestep_embedder.linear_1",
+ "time_guidance_embed.timestep_embedder.linear_2",
+ "proj_out",
+ "norm_out.linear",
+ "double_stream_modulation_img.linear",
+ "double_stream_modulation_txt.linear",
+ "single_stream_modulation.linear",
+ }
+
+
+class _Flux2FinalLayer(torch.nn.Module):
+ """The tail of Flux2Transformer2DModel: AdaLayerNormContinuous, then the output projection."""
+
+ def __init__(self, hidden_size: int, out_channels: int):
+ super().__init__()
+ self.norm_out = AdaLayerNormContinuous(hidden_size, hidden_size, elementwise_affine=False, eps=1e-6)
+ self.proj_out = torch.nn.Linear(hidden_size, out_channels)
+
+ def forward(self, x: torch.Tensor, vec: torch.Tensor) -> torch.Tensor:
+ return self.proj_out(self.norm_out(x, vec))
+
+
[email protected]("flux_version", ["flux1", "flux2"])
+def test_kohya_final_layer_lora_changes_the_output_as_it_does_on_the_bfl_layer(flux_version: str):
+ """A kohya LoRA on the last layer applies with alpha / rank to BFL's (shift, scale) modulation halves. FLUX.2's
+ `norm_out` orders the halves the other way, and must still give the BFL layer's output."""
+ hidden, out_channels, rank, alpha = 8, 4, 2, 1.0
+ torch.manual_seed(0)
+ bfl_layer = LastLayer(hidden, patch_size=1, out_channels=out_channels)
+ down = torch.randn(rank, hidden)
+ up = torch.randn(2 * hidden, rank)
+ linear_down = torch.randn(rank, hidden)
+ linear_up = torch.randn(out_channels, rank)
+ state_dict = {
+ "lora_unet_final_layer_adaLN_modulation_1.lora_down.weight": down,
+ "lora_unet_final_layer_adaLN_modulation_1.lora_up.weight": up,
+ "lora_unet_final_layer_adaLN_modulation_1.alpha": torch.tensor(alpha),
+ "lora_unet_final_layer_linear.lora_down.weight": linear_down,
+ "lora_unet_final_layer_linear.lora_up.weight": linear_up,
+ "lora_unet_final_layer_linear.alpha": torch.tensor(alpha),
+ # A block layer, as the detector needs one.
+ "lora_unet_double_blocks_0_img_attn_proj.lora_down.weight": torch.randn(rank, hidden),
+ "lora_unet_double_blocks_0_img_attn_proj.lora_up.weight": torch.randn(hidden, rank),
+ }
+ assert is_state_dict_likely_in_flux_kohya_format(state_dict)
+ patch = lora_model_from_flux_kohya_state_dict(state_dict)
+ prefix = FLUX_LORA_TRANSFORMER_PREFIX
+
+ x = torch.randn(2, 3, hidden)
+ vec = torch.randn(2, hidden)
+ unpatched = bfl_layer(x, vec)
+ if flux_version == "flux1":
+ model: torch.nn.Module = bfl_layer
+ layers = {
+ f"{prefix}adaLN_modulation.1": patch.layers[f"{prefix}final_layer.adaLN_modulation.1"],
+ f"{prefix}linear": patch.layers[f"{prefix}final_layer.linear"],
+ }
+ else:
+ model = _Flux2FinalLayer(hidden, out_channels)
+ # The base weights as the FLUX.2 loader converts them: BFL's modulation halves swapped.
+ model.proj_out.load_state_dict(bfl_layer.linear.state_dict())
+ for name in ("weight", "bias"):
+ bfl_param = getattr(bfl_layer.adaLN_modulation[1], name)
+ getattr(model.norm_out.linear, name).copy_(torch.cat(bfl_param.chunk(2, dim=0)[::-1], dim=0))
+ assert torch.allclose(model(x, vec), unpatched, atol=1e-5)
+ converted = convert_bfl_lora_patch_to_diffusers(patch)
+ layers = {key: converted.layers[key] for key in (f"{prefix}norm_out.linear", f"{prefix}proj_out")}
+
+ with LayerPatcher.apply_smart_model_patches(
+ model=model,
+ patches=[(ModelPatchRaw(layers=layers), 1.0)],
+ prefix=prefix,
+ dtype=torch.float32,
+ force_direct_patching=True,
+ ):
+ patched = model(x, vec)
+
+ # The LoRA by hand, on the BFL layer: W += up @ down * alpha / rank.
+ bfl_layer.adaLN_modulation[1].weight += up @ down * (alpha / rank)
+ bfl_layer.linear.weight += linear_up @ linear_down * (alpha / rank)
+ expected = bfl_layer(x, vec)
+ assert not torch.allclose(expected, unpatched, atol=1e-2)
+ assert torch.allclose(patched, expected, atol=1e-4)
+
+
+def test_flux2_dev_kohya_guidance_embedder_resolves_on_the_flux2_model():
+ """FLUX.2 [dev] has a guidance embedder, which kohya names `guidance_in_*` (BFL's `guidance_in`)."""
+ with accelerate.init_empty_weights():
+ model = Flux2Transformer2DModel(
+ patch_size=1,
+ in_channels=8,
+ num_layers=1,
+ num_single_layers=1,
+ attention_head_dim=8,
+ num_attention_heads=2,
+ joint_attention_dim=16,
+ timestep_guidance_channels=16,
+ axes_dims_rope=(2, 2, 2, 2),
+ guidance_embeds=True,
+ )
+ embedder = model.time_guidance_embed.guidance_embedder
+ state_dict = {
+ # A block layer, as the detector needs one.
+ "lora_unet_double_blocks_0_img_attn_proj.lora_down.weight": torch.empty(4, 16),
+ "lora_unet_double_blocks_0_img_attn_proj.lora_up.weight": torch.empty(16, 4),
+ "lora_unet_guidance_in_in_layer.lora_down.weight": torch.empty(4, embedder.linear_1.in_features),
+ "lora_unet_guidance_in_in_layer.lora_up.weight": torch.empty(embedder.linear_1.out_features, 4),
+ "lora_unet_guidance_in_out_layer.lora_down.weight": torch.empty(4, embedder.linear_2.in_features),
+ "lora_unet_guidance_in_out_layer.lora_up.weight": torch.empty(embedder.linear_2.out_features, 4),
+ }
+ assert is_state_dict_likely_in_flux_kohya_format(state_dict)
+
+ patch = convert_bfl_lora_patch_to_diffusers(lora_model_from_flux_kohya_state_dict(state_dict))
+
+ for name, module in [
+ ("time_guidance_embed.guidance_embedder.linear_1", embedder.linear_1),
+ ("time_guidance_embed.guidance_embedder.linear_2", embedder.linear_2),
+ ]:
+ layer = patch.layers[FLUX_LORA_TRANSFORMER_PREFIX + name]
+ assert layer.get_parameters({"weight": module.weight}, weight=1.0)["weight"].shape == module.weight.shape
diff --git a/tests/backend/patches/lora_conversions/test_flux_onetrainer_lora_conversion_utils.py b/tests/backend/patches/lora_conversions/test_flux_onetrainer_lora_conversion_utils.py
index cf8a27d5ad..91d636d5da 100644
--- a/tests/backend/patches/lora_conversions/test_flux_onetrainer_lora_conversion_utils.py
+++ b/tests/backend/patches/lora_conversions/test_flux_onetrainer_lora_conversion_utils.py
@@ -1,5 +1,14 @@
+from typing import Callable
+
+import accelerate
import pytest
+import torch
+from diffusers import QwenImageTransformer2DModel, SD3Transformer2DModel
+from invokeai.backend.flux.model import Flux
+from invokeai.backend.flux.util import get_flux_transformers_params
+from invokeai.backend.model_manager.taxonomy import FluxLoRAFormat, FluxVariantType
+from invokeai.backend.patches.layers.swapped_halves_layer_patch import SwappedHalvesLayerPatch
from invokeai.backend.patches.lora_conversions.flux_lora_constants import (
FLUX_LORA_CLIP_PREFIX,
FLUX_LORA_T5_PREFIX,
@@ -9,6 +18,7 @@ from invokeai.backend.patches.lora_conversions.flux_onetrainer_lora_conversion_u
is_state_dict_likely_in_flux_onetrainer_format,
lora_model_from_flux_onetrainer_state_dict,
)
+from invokeai.backend.patches.lora_conversions.formats import flux_format_from_state_dict
from tests.backend.patches.lora_conversions.lora_state_dicts.flux_dora_onetrainer_format import (
state_dict_keys as flux_onetrainer_state_dict_keys,
)
@@ -21,6 +31,9 @@ from tests.backend.patches.lora_conversions.lora_state_dicts.flux_lora_kohya_for
from tests.backend.patches.lora_conversions.lora_state_dicts.flux_lora_kohya_with_te1_format import (
state_dict_keys as flux_kohya_te1_state_dict_keys,
)
+from tests.backend.patches.lora_conversions.lora_state_dicts.flux_lora_onetrainer_non_block_format import (
+ state_dict_keys as flux_onetrainer_non_block_state_dict_keys,
+)
from tests.backend.patches.lora_conversions.lora_state_dicts.utils import keys_to_mock_state_dict
@@ -75,3 +88,159 @@ def test_lora_model_from_flux_onetrainer_state_dict():
k.startswith((FLUX_LORA_TRANSFORMER_PREFIX, FLUX_LORA_CLIP_PREFIX, FLUX_LORA_T5_PREFIX))
for k in lora_model.layers.keys()
)
+
+
+def _non_block_fixture_state_dict() -> dict[str, torch.Tensor]:
+ return keys_to_mock_state_dict(
+ {k: shape for k, (shape, _dtype) in flux_onetrainer_non_block_state_dict_keys.items()}
+ )
+
+
+def test_flux_onetrainer_format_with_layers_outside_the_blocks_is_detected():
+ """A full-layer-filter OneTrainer FLUX LoRA, with `context_embedder` and the other non-block layers, is OneTrainer
+ FLUX and not rejected for them (#10030)."""
+ assert is_state_dict_likely_in_flux_onetrainer_format(_non_block_fixture_state_dict())
+
+
+def test_flux_onetrainer_format_needs_a_block_next_to_the_layers_outside_the_blocks():
+ """`x_embedder`, `context_embedder`, `proj_out` and `norm_out` are Qwen-Image, SD3 and Z-Image module names too:
+ alone they do not make a FLUX LoRA."""
+ state_dict = _non_block_fixture_state_dict()
+ only_non_block = {k: v for k, v in state_dict.items() if "_blocks_" not in k}
+ assert len(only_non_block) == 10 * 3 # ten layers, alpha and both factors each
+
+ assert not is_state_dict_likely_in_flux_onetrainer_format(only_non_block)
+ state_dict["lora_transformer_unknown_layer.lora_down.weight"] = torch.empty(4, 4)
+ assert not is_state_dict_likely_in_flux_onetrainer_format(state_dict)
+
+
+def test_flux_onetrainer_layers_outside_the_blocks_land_on_their_bfl_modules():
+ """Each layer of the real file reaches the BFL module of its role, the shapes fit the FLUX.1 model, and the last
+ layer's modulation, which BFL orders (shift, scale) against diffusers' (scale, shift), is swapped."""
+ lora_model = lora_model_from_flux_onetrainer_state_dict(_non_block_fixture_state_dict())
+
+ non_block = {
+ k.removeprefix(FLUX_LORA_TRANSFORMER_PREFIX): v for k, v in lora_model.layers.items() if "blocks" not in k
+ }
+ assert set(non_block) == {
+ "img_in",
+ "txt_in",
+ "time_in.in_layer",
+ "time_in.out_layer",
+ "vector_in.in_layer",
+ "vector_in.out_layer",
+ "guidance_in.in_layer",
+ "guidance_in.out_layer",
+ "final_layer.linear",
+ "final_layer.adaLN_modulation.1",
+ }
+ assert isinstance(non_block["final_layer.adaLN_modulation.1"], SwappedHalvesLayerPatch)
+ assert not any(
+ isinstance(v, SwappedHalvesLayerPatch) for k, v in non_block.items() if k != "final_layer.adaLN_modulation.1"
+ )
+
+ with accelerate.init_empty_weights():
+ model = Flux(get_flux_transformers_params(FluxVariantType.Dev))
+ for name, layer in non_block.items():
+ weight = model.get_submodule(name).weight
+ assert layer.get_parameters({"weight": weight}, weight=1.0)["weight"].shape == weight.shape, name
+
+
+def _onetrainer_legacy_state_dict(model: torch.nn.Module, keep: Callable[[str], bool]) -> dict[str, torch.Tensor]:
+ """The keys OneTrainer's LEGACY_LORA output writes for a diffusers transformer: each Linear's module path with the
+ periods turned into underscores under `lora_transformer_`."""
+ state_dict: dict[str, torch.Tensor] = {}
+ for name, module in model.named_modules():
+ if isinstance(module, torch.nn.Linear) and keep(name):
+ key = "lora_transformer_" + name.replace(".", "_")
+ state_dict[f"{key}.lora_down.weight"] = torch.empty(4, module.in_features)
+ state_dict[f"{key}.lora_up.weight"] = torch.empty(module.out_features, 4)
+ return state_dict
+
+
+def _meta_sd3() -> torch.nn.Module:
+ with accelerate.init_empty_weights():
+ return SD3Transformer2DModel(
+ sample_size=8,
+ patch_size=2,
+ in_channels=4,
+ num_layers=2,
+ attention_head_dim=8,
+ num_attention_heads=2,
+ joint_attention_dim=16,
+ caption_projection_dim=16,
+ pooled_projection_dim=16,
+ out_channels=4,
+ pos_embed_max_size=8,
+ dual_attention_layers=(0,),
+ )
+
+
+def _meta_qwen_image() -> torch.nn.Module:
+ with accelerate.init_empty_weights():
+ return QwenImageTransformer2DModel(
+ patch_size=2,
+ in_channels=16,
+ out_channels=4,
+ num_layers=2,
+ attention_head_dim=8,
+ num_attention_heads=2,
+ joint_attention_dim=16,
+ axes_dims_rope=(2, 2, 4),
+ )
+
+
+_TOP_LEVEL = tuple(f"lora_transformer_{name}" for name in ("norm_out", "proj_out", "time_text_embed"))
+
+
[email protected]("make_model", [_meta_sd3, _meta_qwen_image], ids=["sd3", "qwen-image"])
[email protected]("scope", ["full-filter", "blocks-and-top-level"])
+def test_sd3_and_qwen_image_onetrainer_files_with_top_level_layers_are_not_flux(make_model, scope: str):
+ """SD3 and Qwen-Image name their top-level layers and double blocks like FLUX; they have no single blocks, which
+ is what tells their OneTrainer files with those layers from FLUX's."""
+ model = make_model()
+ state_dict = _onetrainer_legacy_state_dict(model, lambda name: True)
+ if scope == "blocks-and-top-level":
+ state_dict = {k: v for k, v in state_dict.items() if "_blocks_" in k or k.startswith(_TOP_LEVEL)}
+ assert any(k.startswith("lora_transformer_transformer_blocks_") for k in state_dict)
+ assert any(k.startswith("lora_transformer_norm_out") for k in state_dict)
+
+ assert not is_state_dict_likely_in_flux_onetrainer_format(state_dict)
+ assert flux_format_from_state_dict(state_dict) is not FluxLoRAFormat.OneTrainer
+
+
+def test_flux_onetrainer_fixture_is_the_onetrainer_format():
+ assert flux_format_from_state_dict(_non_block_fixture_state_dict()) is FluxLoRAFormat.OneTrainer
+
+
+ "layer",
+ [
+ "single_transformer_blocks_0_attn_to_qkv_mlp_proj",
+ "transformer_blocks_0_ff_linear_in",
+ ],
+)
[email protected]("with_x_embedder", [False, True])
+def test_flux2_named_onetrainer_blocks_are_not_flux1_onetrainer(layer: str, with_x_embedder: bool):
+ """FLUX.2's block layers are not in FLUX.1's parsing tree: claimed as FLUX.1 they would fail at load."""
+ state_dict = {
+ f"lora_transformer_{layer}.lora_down.weight": torch.empty(4, 16),
+ f"lora_transformer_{layer}.lora_up.weight": torch.empty(16, 4),
+ }
+ if with_x_embedder:
+ state_dict["lora_transformer_x_embedder.lora_down.weight"] = torch.empty(4, 128)
+ state_dict["lora_transformer_x_embedder.lora_up.weight"] = torch.empty(16, 4)
+
+ assert not is_state_dict_likely_in_flux_onetrainer_format(state_dict)
+ assert flux_format_from_state_dict(state_dict) is None
+
+
+def test_qwen_image_onetrainer_blocks_are_not_flux1_onetrainer():
+ """Qwen-Image's block layers (`img_mlp`, `img_mod`, ...) are not FLUX.1's, whose parsing tree would reject them at
+ load."""
+ state_dict = {
+ k: v for k, v in _onetrainer_legacy_state_dict(_meta_qwen_image(), lambda name: True).items() if "_blocks_" in k
+ }
+ assert state_dict
+
+ assert flux_format_from_state_dict(state_dict) is None
diff --git a/tests/backend/patches/lora_conversions/test_kohya_key_utils.py b/tests/backend/patches/lora_conversions/test_kohya_key_utils.py
index 8e3c944695..5353ce46ef 100644
--- a/tests/backend/patches/lora_conversions/test_kohya_key_utils.py
+++ b/tests/backend/patches/lora_conversions/test_kohya_key_utils.py
@@ -94,3 +94,11 @@ def test_generate_kohya_parsing_tree_from_empty_keys():
keys: list[str] = []
tree = generate_kohya_parsing_tree_from_keys(keys)
assert tree == {}
+
+
+def test_insert_periods_into_kohya_key_prefers_a_longer_sibling_when_the_shorter_one_does_not_fit():
+ """`ff` and `ff_context` are siblings in FLUX's block: the key below `ff_context` must not stop at `ff`."""
+ parsing_tree: ParsingTree = {"blocks": {INDEX_PLACEHOLDER: {"ff": {"net": {}}, "ff_context": {"net": {}}}}}
+
+ assert insert_periods_into_kohya_key("blocks_0_ff_context_net", parsing_tree) == "blocks.0.ff_context.net"
+ assert insert_periods_into_kohya_key("blocks_0_ff_net", parsing_tree) == "blocks.0.ff.net"