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): support factorized LyCORIS layouts (#10060)

Guishi Wang9fdb44f863df
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 7332e672a1..6a4d39ff81 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
@@ -1,7 +1,7 @@
---
title: Model Format Support
description: Which file formats and quantizations InvokeAI loads for every model family, text encoder, VAE and adapter.
-lastUpdated: 2026-10-26
+lastUpdated: 2026-10-28
sidebar:
order: 3
---
@@ -146,5 +146,8 @@ themselves.
| LTX-2, MiniMax H3 | ✓ (plain low-rank; LoKR, LoHA and DoRA are refused) | ✗ | |
| SD 3, CogView4, Ideogram 4, ERNIE-Image, Qwen-Image-2.1, MOSS-Image | ✗ | ✗ | |
+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.
+
[PiD decoders](/users-guide/image-generation/advanced-topics/pid-decode/) load for FLUX.1, FLUX.2, SD 3, SDXL and
Qwen-Image (v1 and v1.5, bf16 and int8 builds). MOSS-Image uses the FLUX.2 decoders.
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 453fbc6aba..636867af75 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
@@ -1,7 +1,7 @@
---
title: FLUX.2
description: Generate and edit images with FLUX.2 Klein (4B and 9B, distilled and Base) and FLUX.2 [dev], including multi-reference image editing and the FLUX.2 [dev] Fun-ControlNet-Union.
-lastUpdated: 2026-10-18
+lastUpdated: 2026-10-28
sidebar:
order: 5
---
@@ -187,6 +187,8 @@ FLUX.2 LoRAs are labelled with the variant they were trained for, and the Genera
that match the selected model's variant. LoRAs patch the transformer and, where they include text-encoder
layers, the Qwen3 or Mistral encoder. In workflows use **Apply LoRA - Flux2 Klein** or **Apply LoRA -
FLUX.2 [dev]** (and their *Collection* versions).
+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.
## PiD super-resolution decode
diff --git a/docs/src/content/docs/Users Guide/03.Models/Local Models/stable-diffusion-1-2.mdx b/docs/src/content/docs/Users Guide/03.Models/Local Models/stable-diffusion-1-2.mdx
index 7ad2698056..e785dfb061 100644
--- a/docs/src/content/docs/Users Guide/03.Models/Local Models/stable-diffusion-1-2.mdx
+++ b/docs/src/content/docs/Users Guide/03.Models/Local Models/stable-diffusion-1-2.mdx
@@ -1,7 +1,7 @@
---
title: Stable Diffusion 1.5 / 2.x
description: Generate images with Stable Diffusion 1.5 and legacy SD 2.x models, including inpainting models, ControlNet, T2I-Adapter, IP-Adapter reference images, LoRAs and embeddings.
-lastUpdated: 2026-09-30
+lastUpdated: 2026-10-28
sidebar:
order: 10
---
@@ -117,8 +117,9 @@ models.
## LoRAs and embeddings
-- **LoRAs** for SD 1.x (and SD 2.x), including LyCORIS variants, are supported. Add them in the LoRA
- section of the Generate panel. LoRAs made for a different model family are not applied.
+- **LoRAs** for SD 1.x (and SD 2.x), including LyCORIS variants, are supported. LoKr adapters may store
+ either Kronecker operand whole or as a factorized `_a` / `_b` pair. Add LoRAs in the LoRA section of the
+ Generate panel. LoRAs made for a different model family are not applied.
- **Textual-inversion embeddings** are supported in the positive and negative prompts. Type `<` in a
prompt box to pick from the compatible embeddings you have installed — for example, `EasyNegative`
in the negative prompt.
diff --git a/invokeai/backend/model_manager/configs/lora.py b/invokeai/backend/model_manager/configs/lora.py
index 081d276ceb..631d52c8ea 100644
--- a/invokeai/backend/model_manager/configs/lora.py
+++ b/invokeai/backend/model_manager/configs/lora.py
@@ -182,31 +182,80 @@ _FLUX1_HIDDEN_SIZE = 3072
# Klein 4B uses mlp_ratio=6 (ffn_dim=18432 for hidden_size=3072).
_FLUX1_MLP_RATIO = 4
+# Trigger once per LyCORIS layer from its w1 entry; the dimension helpers resolve w2 independently.
+_LYCORIS_IN_DIM_SUFFIXES = (
+ ".lokr_w1",
+ ".lokr_w1_b",
+ ".hada_w1_b",
+)
+_LYCORIS_OUT_DIM_SUFFIXES = (
+ ".lokr_w1",
+ ".lokr_w1_a",
+ ".hada_w1_a",
+)
+_BFL_LYCORIS_ATTN_IN_SUFFIXES = tuple(f".img_attn.proj{suffix}" for suffix in _LYCORIS_IN_DIM_SUFFIXES)
+_BFL_LYCORIS_MLP_OUT_SUFFIXES = tuple(f".img_mlp.0{suffix}" for suffix in _LYCORIS_OUT_DIM_SUFFIXES)
+
+
+def _lokr_operand_dim(
+ state_dict: dict[str | int, Any],
+ key_prefix: str,
+ operand: Literal["w1", "w2"],
+ axis: Literal[0, 1],
+) -> int | None:
+ full_key = f"{key_prefix}.lokr_{operand}"
+ if full_key in state_dict:
+ return state_dict[full_key].shape[axis]
+
+ factor_key = f"{full_key}_{'a' if axis == 0 else 'b'}"
+ if factor_key not in state_dict:
+ return None
+ return state_dict[factor_key].shape[axis]
+
def _lokr_in_dim(state_dict: dict[str | int, Any], key_prefix: str) -> int | None:
"""Compute the input dimension of a LOKR layer: w1.shape[1] * w2.shape[1].
- Supports both full LOKR (lokr_w1/lokr_w2) and factorized LOKR (lokr_w1_b/lokr_w2_b).
- Returns None if the required keys are not present.
+ Each Kronecker operand may independently be stored whole or as an ``_a``/``_b`` factor pair.
"""
- if f"{key_prefix}.lokr_w1" in state_dict and f"{key_prefix}.lokr_w2" in state_dict:
- return state_dict[f"{key_prefix}.lokr_w1"].shape[1] * state_dict[f"{key_prefix}.lokr_w2"].shape[1]
- elif f"{key_prefix}.lokr_w1_b" in state_dict and f"{key_prefix}.lokr_w2_b" in state_dict:
- return state_dict[f"{key_prefix}.lokr_w1_b"].shape[1] * state_dict[f"{key_prefix}.lokr_w2_b"].shape[1]
- return None
+ w1_dim = _lokr_operand_dim(state_dict, key_prefix, "w1", 1)
+ w2_dim = _lokr_operand_dim(state_dict, key_prefix, "w2", 1)
+ if w1_dim is None or w2_dim is None:
+ return None
+ return w1_dim * w2_dim
def _lokr_out_dim(state_dict: dict[str | int, Any], key_prefix: str) -> int | None:
"""Compute the output dimension of a LOKR layer: w1.shape[0] * w2.shape[0].
- Supports both full LOKR (lokr_w1/lokr_w2) and factorized LOKR (lokr_w1_a/lokr_w2_a).
- Returns None if the required keys are not present.
+ Each Kronecker operand may independently be stored whole or as an ``_a``/``_b`` factor pair.
"""
- if f"{key_prefix}.lokr_w1" in state_dict and f"{key_prefix}.lokr_w2" in state_dict:
- return state_dict[f"{key_prefix}.lokr_w1"].shape[0] * state_dict[f"{key_prefix}.lokr_w2"].shape[0]
- elif f"{key_prefix}.lokr_w1_a" in state_dict and f"{key_prefix}.lokr_w2_a" in state_dict:
- return state_dict[f"{key_prefix}.lokr_w1_a"].shape[0] * state_dict[f"{key_prefix}.lokr_w2_a"].shape[0]
- return None
+ w1_dim = _lokr_operand_dim(state_dict, key_prefix, "w1", 0)
+ w2_dim = _lokr_operand_dim(state_dict, key_prefix, "w2", 0)
+ if w1_dim is None or w2_dim is None:
+ return None
+ return w1_dim * w2_dim
+
+
+def _loha_dim(state_dict: dict[str | int, Any], key_prefix: str, axis: Literal[0, 1]) -> int | None:
+ factor = "a" if axis == 0 else "b"
+ w1_key = f"{key_prefix}.hada_w1_{factor}"
+ w2_key = f"{key_prefix}.hada_w2_{factor}"
+ if w1_key not in state_dict or w2_key not in state_dict:
+ return None
+ w1_dim = state_dict[w1_key].shape[axis]
+ w2_dim = state_dict[w2_key].shape[axis]
+ return w1_dim if w1_dim == w2_dim else None
+
+
+def _lycoris_in_dim(state_dict: dict[str | int, Any], key_prefix: str) -> int | None:
+ lokr_dim = _lokr_in_dim(state_dict, key_prefix)
+ return lokr_dim if lokr_dim is not None else _loha_dim(state_dict, key_prefix, 1)
+
+
+def _lycoris_out_dim(state_dict: dict[str | int, Any], key_prefix: str) -> int | None:
+ lokr_dim = _lokr_out_dim(state_dict, key_prefix)
+ return lokr_dim if lokr_dim is not None else _loha_dim(state_dict, key_prefix, 0)
def _is_flux2_lora(mod: ModelOnDisk) -> bool:
@@ -277,26 +326,26 @@ def _is_flux2_lora_state_dict(state_dict: dict[str | int, Any]) -> bool:
elif "vector_in" in key and key.endswith("lora_A.weight"):
return state_dict[key].shape[1] in _FLUX2_VEC_IN_DIMS
- # BFL LyCORIS (LoKR/LoHA): attention projection → check hidden_size via product of dims
- elif key.endswith((".img_attn.proj.lokr_w1", ".img_attn.proj.lokr_w1_b")):
+ # BFL LyCORIS: attention projection → check hidden_size from the reconstructed layer dimensions
+ elif key.endswith(_BFL_LYCORIS_ATTN_IN_SUFFIXES):
layer_prefix = key.rsplit(".", 1)[0]
- in_dim = _lokr_in_dim(state_dict, layer_prefix)
+ in_dim = _lycoris_in_dim(state_dict, layer_prefix)
if in_dim is not None:
if in_dim != _FLUX1_HIDDEN_SIZE:
return True
bfl_hidden_size = in_dim # ambiguous, keep checking
# BFL LyCORIS: context_embedder/txt_in
- elif "txt_in" in key and key.endswith((".lokr_w1", ".lokr_w1_b")):
+ elif "txt_in" in key and key.endswith(_LYCORIS_IN_DIM_SUFFIXES):
layer_prefix = key.rsplit(".", 1)[0]
- in_dim = _lokr_in_dim(state_dict, layer_prefix)
+ in_dim = _lycoris_in_dim(state_dict, layer_prefix)
if in_dim is not None:
return in_dim in _FLUX2_CONTEXT_IN_DIMS
# BFL LyCORIS: vector_in
- elif "vector_in" in key and key.endswith((".lokr_w1", ".lokr_w1_b")):
+ elif "vector_in" in key and key.endswith(_LYCORIS_IN_DIM_SUFFIXES):
layer_prefix = key.rsplit(".", 1)[0]
- in_dim = _lokr_in_dim(state_dict, layer_prefix)
+ in_dim = _lycoris_in_dim(state_dict, layer_prefix)
if in_dim is not None:
return in_dim in _FLUX2_VEC_IN_DIMS
@@ -311,10 +360,10 @@ def _is_flux2_lora_state_dict(state_dict: dict[str | int, Any]) -> bool:
if ffn_dim != bfl_hidden_size * _FLUX1_MLP_RATIO:
return True
break
- # BFL LyCORIS: check output dim of img_mlp.0 via product of dims
- if key.startswith(_bfl_prefixes) and key.endswith((".img_mlp.0.lokr_w1", ".img_mlp.0.lokr_w1_a")):
+ # BFL LyCORIS: check output dim of img_mlp.0
+ if key.startswith(_bfl_prefixes) and key.endswith(_BFL_LYCORIS_MLP_OUT_SUFFIXES):
layer_prefix = key.rsplit(".", 1)[0]
- out_dim = _lokr_out_dim(state_dict, layer_prefix)
+ out_dim = _lycoris_out_dim(state_dict, layer_prefix)
if out_dim is not None and out_dim != bfl_hidden_size * _FLUX1_MLP_RATIO:
return True
break
@@ -327,19 +376,19 @@ def _is_flux2_lora_state_dict(state_dict: dict[str | int, Any]) -> bool:
if key.startswith("lora_unet_txt_in.") or key.startswith("lora_unet_context_embedder."):
if key.endswith("lora_down.weight"):
return state_dict[key].shape[1] in _FLUX2_CONTEXT_IN_DIMS
- # Kohya LyCORIS (LoKR)
- elif key.endswith((".lokr_w1", ".lokr_w1_b")):
+ # Kohya LyCORIS
+ elif key.endswith(_LYCORIS_IN_DIM_SUFFIXES):
layer_prefix = key.rsplit(".", 1)[0]
- in_dim = _lokr_in_dim(state_dict, layer_prefix)
+ in_dim = _lycoris_in_dim(state_dict, layer_prefix)
if in_dim is not None:
return in_dim in _FLUX2_CONTEXT_IN_DIMS
if key.startswith("lora_unet_vector_in.") or key.startswith("lora_unet_time_text_embed_text_embedder_"):
if key.endswith("lora_down.weight"):
return state_dict[key].shape[1] in _FLUX2_VEC_IN_DIMS
- # Kohya LyCORIS (LoKR)
- elif key.endswith((".lokr_w1", ".lokr_w1_b")):
+ # Kohya LyCORIS
+ elif key.endswith(_LYCORIS_IN_DIM_SUFFIXES):
layer_prefix = key.rsplit(".", 1)[0]
- in_dim = _lokr_in_dim(state_dict, layer_prefix)
+ in_dim = _lycoris_in_dim(state_dict, layer_prefix)
if in_dim is not None:
return in_dim in _FLUX2_VEC_IN_DIMS
@@ -360,10 +409,10 @@ def _is_flux2_lora_state_dict(state_dict: dict[str | int, Any]) -> bool:
if kohya_hidden_size != _FLUX1_HIDDEN_SIZE:
return True
break
- # LoKR variant
- elif "_img_attn_proj." in key and key.endswith((".lokr_w1", ".lokr_w1_b")):
+ # LyCORIS variant
+ elif "_img_attn_proj." in key and key.endswith(_LYCORIS_IN_DIM_SUFFIXES):
layer_prefix = key.rsplit(".", 1)[0]
- in_dim = _lokr_in_dim(state_dict, layer_prefix)
+ in_dim = _lycoris_in_dim(state_dict, layer_prefix)
if in_dim is not None:
if in_dim != _FLUX1_HIDDEN_SIZE:
return True
@@ -381,10 +430,10 @@ def _is_flux2_lora_state_dict(state_dict: dict[str | int, Any]) -> bool:
if ffn_dim != kohya_hidden_size * _FLUX1_MLP_RATIO:
return True
break
- # LoKR variant
- if key.startswith("lora_unet_") and "_img_mlp_0." in key and key.endswith((".lokr_w1", ".lokr_w1_a")):
+ # LyCORIS variant
+ if key.startswith("lora_unet_") and "_img_mlp_0." in key and key.endswith(_LYCORIS_OUT_DIM_SUFFIXES):
layer_prefix = key.rsplit(".", 1)[0]
- out_dim = _lokr_out_dim(state_dict, layer_prefix)
+ out_dim = _lycoris_out_dim(state_dict, layer_prefix)
if out_dim is not None and out_dim != kohya_hidden_size * _FLUX1_MLP_RATIO:
return True
break
@@ -457,21 +506,21 @@ def _get_flux2_lora_variant(state_dict: dict[str | int, Any]) -> Flux2VariantTyp
if key.endswith(".img_attn.proj.lora_A.weight"):
return _variant_from_hidden_size(state_dict[key].shape[1])
- # BFL LyCORIS (LoKR): context embedder (txt_in)
- if "txt_in" in key and key.endswith((".lokr_w1", ".lokr_w1_b")):
- in_dim = _lokr_in_dim(state_dict, key.rsplit(".", 1)[0])
+ # BFL LyCORIS: context embedder (txt_in)
+ if "txt_in" in key and 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_context_dim(in_dim)
- # BFL LyCORIS (LoKR): vector embedder (vector_in)
- if "vector_in" in key and key.endswith((".lokr_w1", ".lokr_w1_b")):
- in_dim = _lokr_in_dim(state_dict, key.rsplit(".", 1)[0])
+ # BFL LyCORIS: vector embedder (vector_in)
+ if "vector_in" in key and 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_vec_dim(in_dim)
- # BFL LyCORIS (LoKR): attention projection
- if key.endswith((".img_attn.proj.lokr_w1", ".img_attn.proj.lokr_w1_b")):
- in_dim = _lokr_in_dim(state_dict, key.rsplit(".", 1)[0])
+ # BFL LyCORIS: attention projection
+ if key.endswith(_BFL_LYCORIS_ATTN_IN_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)
@@ -482,17 +531,17 @@ def _get_flux2_lora_variant(state_dict: dict[str | int, Any]) -> Flux2VariantTyp
if key.startswith("lora_unet_txt_in.") or key.startswith("lora_unet_context_embedder."):
if key.endswith("lora_down.weight"):
return _variant_from_context_dim(state_dict[key].shape[1])
- # Kohya LyCORIS (LoKR)
- elif key.endswith((".lokr_w1", ".lokr_w1_b")):
- in_dim = _lokr_in_dim(state_dict, key.rsplit(".", 1)[0])
+ # Kohya LyCORIS
+ 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_context_dim(in_dim)
if key.startswith("lora_unet_vector_in.") or key.startswith("lora_unet_time_text_embed_text_embedder_"):
if key.endswith("lora_down.weight"):
return _variant_from_vec_dim(state_dict[key].shape[1])
- # Kohya LyCORIS (LoKR)
- elif key.endswith((".lokr_w1", ".lokr_w1_b")):
- in_dim = _lokr_in_dim(state_dict, key.rsplit(".", 1)[0])
+ # Kohya LyCORIS
+ 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_vec_dim(in_dim)
@@ -507,9 +556,9 @@ def _get_flux2_lora_variant(state_dict: dict[str | int, Any]) -> Flux2VariantTyp
# Check img_attn_proj hidden_size
if "_img_attn_proj." in key and key.endswith("lora_down.weight"):
return _variant_from_hidden_size(state_dict[key].shape[1])
- # LoKR variant
- elif "_img_attn_proj." in key and key.endswith((".lokr_w1", ".lokr_w1_b")):
- in_dim = _lokr_in_dim(state_dict, key.rsplit(".", 1)[0])
+ # LyCORIS variant
+ elif "_img_attn_proj." in key and 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)
diff --git a/invokeai/backend/model_manager/util/model_util.py b/invokeai/backend/model_manager/util/model_util.py
index f85c1be490..540eba2701 100644
--- a/invokeai/backend/model_manager/util/model_util.py
+++ b/invokeai/backend/model_manager/util/model_util.py
@@ -110,14 +110,14 @@ def lora_token_vector_length(checkpoint: dict[str | int, torch.Tensor]) -> Optio
elif "lokr_" in lora_key:
if model_key + ".lokr_w1" in checkpoint:
_lokr_w1 = checkpoint[model_key + ".lokr_w1"]
- elif model_key + "lokr_w1_b" in checkpoint:
+ elif model_key + ".lokr_w1_b" in checkpoint:
_lokr_w1 = checkpoint[model_key + ".lokr_w1_b"]
else:
return lora_token_vector_length # unknown format
if model_key + ".lokr_w2" in checkpoint:
_lokr_w2 = checkpoint[model_key + ".lokr_w2"]
- elif model_key + "lokr_w2_b" in checkpoint:
+ elif model_key + ".lokr_w2_b" in checkpoint:
_lokr_w2 = checkpoint[model_key + ".lokr_w2_b"]
else:
return lora_token_vector_length # unknown format
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 fd89d673c8..073704c6c7 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
@@ -25,7 +25,10 @@ from typing import Dict
import torch
from invokeai.backend.patches.layers.base_layer_patch import BaseLayerPatch
+from invokeai.backend.patches.layers.loha_layer import LoHALayer
+from invokeai.backend.patches.layers.lokr_layer import LoKRLayer
from invokeai.backend.patches.layers.lora_layer import LoRALayer
+from invokeai.backend.patches.layers.merged_layer_patch import MergedLayerPatch, Range
from invokeai.backend.patches.layers.utils import any_lora_layer_from_state_dict
from invokeai.backend.patches.lora_conversions.flux_lora_constants import FLUX_LORA_TRANSFORMER_PREFIX
from invokeai.backend.patches.model_patch_raw import ModelPatchRaw
@@ -76,6 +79,9 @@ _BFL_LYCORIS_WEIGHT_SUFFIXES = (
# Common to all LyCORIS algorithms
"alpha",
"dora_scale",
+ "bias_indices",
+ "bias_values",
+ "bias_size",
# Full/Diff
"diff",
)
@@ -220,8 +226,8 @@ def lora_model_from_flux2_bfl_peft_state_dict(
- single_blocks.{i} → single_transformer_blocks.{i}
- Fused QKV (img_attn.qkv) → separate Q/K/V (attn.to_q, attn.to_k, attn.to_v)
- This function converts BFL PEFT/LyCORIS keys to diffusers naming and splits fused QKV LoRAs
- into separate Q/K/V LoRA layers.
+ This function converts BFL PEFT/LyCORIS keys to diffusers naming and splits fused QKV updates
+ into separate Q/K/V layers.
"""
# First, strip the prefix and group by BFL layer name with PEFT→InvokeAI naming.
grouped_state_dict: dict[str, dict[str, torch.Tensor]] = {}
@@ -246,188 +252,16 @@ def lora_model_from_flux2_bfl_peft_state_dict(
layer_state_dict["alpha"] = torch.tensor(alpha)
# Now convert BFL layer names to diffusers naming, splitting fused QKV as needed.
- layers: dict[str, any] = {}
+ layers: dict[str, BaseLayerPatch] = {}
for bfl_key, layer_sd in grouped_state_dict.items():
- diffusers_layers = _convert_bfl_layer_to_diffusers(bfl_key, layer_sd)
- for diff_key, diff_sd in diffusers_layers:
- layers[f"{FLUX_LORA_TRANSFORMER_PREFIX}{diff_key}"] = any_lora_layer_from_state_dict(diff_sd)
+ layer = any_lora_layer_from_state_dict(layer_sd)
+ diffusers_layers = _convert_bfl_layer_patch_to_diffusers(bfl_key, layer)
+ for diff_key, diff_layer in diffusers_layers:
+ layers[f"{FLUX_LORA_TRANSFORMER_PREFIX}{diff_key}"] = diff_layer
return ModelPatchRaw(layers=layers)
-def _convert_bfl_layer_to_diffusers(
- bfl_key: str, layer_sd: dict[str, torch.Tensor]
-) -> list[tuple[str, dict[str, torch.Tensor]]]:
- """Convert a single BFL-named LoRA/LyCORIS layer to one or more diffusers-named layers.
-
- Returns a list of (diffusers_key, layer_state_dict) tuples. Most layers produce one entry,
- but fused QKV layers are split into three separate Q/K/V entries.
- """
- # Double blocks
- m = _DOUBLE_BLOCK_RE.match(bfl_key)
- if m:
- idx, rest = m.group(1), m.group(2)
- prefix = f"transformer_blocks.{idx}"
-
- # Fused image QKV → split into separate Q, K, V
- if rest == "img_attn.qkv":
- if "lora_down.weight" in layer_sd:
- return _split_qkv_lora(
- layer_sd,
- q_key=f"{prefix}.attn.to_q",
- k_key=f"{prefix}.attn.to_k",
- v_key=f"{prefix}.attn.to_v",
- )
- elif "lokr_w1" in layer_sd or "lokr_w1_a" in layer_sd:
- return _split_qkv_lokr(
- layer_sd,
- q_key=f"{prefix}.attn.to_q",
- k_key=f"{prefix}.attn.to_k",
- v_key=f"{prefix}.attn.to_v",
- )
- else:
- logger.warning(f"Unsupported layer type for QKV split in {bfl_key}; layer will be skipped.")
- return []
- # Fused text QKV → split into separate Q, K, V
- if rest == "txt_attn.qkv":
- if "lora_down.weight" in layer_sd:
- return _split_qkv_lora(
- layer_sd,
- q_key=f"{prefix}.attn.add_q_proj",
- k_key=f"{prefix}.attn.add_k_proj",
- v_key=f"{prefix}.attn.add_v_proj",
- )
- elif "lokr_w1" in layer_sd or "lokr_w1_a" in layer_sd:
- return _split_qkv_lokr(
- layer_sd,
- q_key=f"{prefix}.attn.add_q_proj",
- k_key=f"{prefix}.attn.add_k_proj",
- v_key=f"{prefix}.attn.add_v_proj",
- )
- else:
- logger.warning(f"Unsupported layer type for QKV split in {bfl_key}; layer will be skipped.")
- return []
- # Simple renames
- if rest in _DOUBLE_BLOCK_RENAMES:
- return [(f"{prefix}.{_DOUBLE_BLOCK_RENAMES[rest]}", layer_sd)]
-
- # Fallback: keep as-is under the new prefix
- return [(f"{prefix}.{rest}", layer_sd)]
-
- # Single blocks
- m = _SINGLE_BLOCK_RE.match(bfl_key)
- if m:
- idx, rest = m.group(1), m.group(2)
- prefix = f"single_transformer_blocks.{idx}"
-
- if rest in _SINGLE_BLOCK_RENAMES:
- return [(f"{prefix}.{_SINGLE_BLOCK_RENAMES[rest]}", layer_sd)]
-
- return [(f"{prefix}.{rest}", layer_sd)]
-
- # Non-block keys (embedders, modulations, output layers)
- if bfl_key in _NON_BLOCK_RENAMES:
- return [(_NON_BLOCK_RENAMES[bfl_key], layer_sd)]
-
- # Fallback: pass through unchanged
- return [(bfl_key, layer_sd)]
-
-
-def _split_qkv_lora(
- layer_sd: dict[str, torch.Tensor],
- q_key: str,
- k_key: str,
- v_key: str,
-) -> list[tuple[str, dict[str, torch.Tensor]]]:
- """Split a fused QKV LoRA layer into separate Q, K, V LoRA layers.
-
- BFL uses fused QKV: lora_down [rank, hidden], lora_up [3*hidden, rank].
- Diffusers uses separate layers: each gets lora_down (shared/cloned) and a third of lora_up.
- """
- lora_down = layer_sd["lora_down.weight"] # [rank, hidden]
- lora_up = layer_sd["lora_up.weight"] # [3*hidden, rank]
- alpha = layer_sd.get("alpha")
-
- # Split lora_up into 3 equal parts along dim 0
- up_q, up_k, up_v = lora_up.chunk(3, dim=0)
-
- result = []
- for key, up_part in [(q_key, up_q), (k_key, up_k), (v_key, up_v)]:
- sd: dict[str, torch.Tensor] = {
- "lora_down.weight": lora_down.clone(),
- "lora_up.weight": up_part,
- }
- if alpha is not None:
- sd["alpha"] = alpha
- result.append((key, sd))
-
- return result
-
-
-def _split_qkv_lokr(
- layer_sd: dict[str, torch.Tensor],
- q_key: str,
- k_key: str,
- v_key: str,
-) -> list[tuple[str, dict[str, torch.Tensor]]]:
- """Split a fused QKV LoKR layer into separate Q, K, V full (diff) layers.
-
- LoKR uses a Kronecker product which cannot be split cleanly, so we compute the full weight
- matrix and store each third as a full weight update (diff).
-
- BFL uses fused QKV: full weight [3*hidden, hidden].
- Diffusers uses separate layers: each gets a [hidden, hidden] weight slice.
-
- For factorized LOKR (w1_a/w1_b), the alpha/rank scale is baked into the diff weights because
- FullLayer always uses scale=1.0.
- """
- w1 = layer_sd.get("lokr_w1")
- w1_a = layer_sd.get("lokr_w1_a")
- w1_b = layer_sd.get("lokr_w1_b")
- w2 = layer_sd.get("lokr_w2")
- w2_a = layer_sd.get("lokr_w2_a")
- w2_b = layer_sd.get("lokr_w2_b")
- t2 = layer_sd.get("lokr_t2")
- alpha = layer_sd.get("alpha")
-
- # Compute rank for scaling (only valid for factorized LOKR).
- if w1_b is not None:
- rank: int | None = w1_b.shape[0]
- elif w2_b is not None:
- rank = w2_b.shape[0]
- else:
- rank = None
-
- if w1 is None:
- assert w1_a is not None and w1_b is not None
- w1 = w1_a @ w1_b
- if w2 is None:
- assert w2_a is not None and w2_b is not None
- if t2 is not None:
- w2 = torch.einsum("i j k l, i p, j r -> p r k l", t2, w2_a, w2_b)
- else:
- w2 = w2_a @ w2_b
-
- if len(w2.shape) == 4:
- w1 = w1.unsqueeze(2).unsqueeze(2)
-
- full_weight = torch.kron(w1, w2) # [3*hidden, hidden]
-
- # For factorized LOKR, bake the alpha/rank scale into the weight because FullLayer.scale()
- # always returns 1.0 (it has no alpha). For non-factorized LOKR, rank is None and scale is 1.0.
- if rank is not None and alpha is not None:
- scale = alpha.item() / rank
- full_weight = full_weight * scale
-
- weight_q, weight_k, weight_v = full_weight.chunk(3, dim=0)
-
- result = []
- for key, weight_part in [(q_key, weight_q), (k_key, weight_k), (v_key, weight_v)]:
- result.append((key, {"diff": weight_part}))
-
- return result
-
-
def convert_bfl_lora_patch_to_diffusers(patch: ModelPatchRaw) -> ModelPatchRaw:
"""Convert a ModelPatchRaw with BFL-format layer keys to diffusers-format keys.
@@ -465,8 +299,8 @@ def convert_bfl_lora_patch_to_diffusers(patch: ModelPatchRaw) -> ModelPatchRaw:
def _convert_bfl_layer_patch_to_diffusers(bfl_key: str, layer: BaseLayerPatch) -> list[tuple[str, BaseLayerPatch]]:
"""Convert a single BFL-named LoRA layer patch to one or more diffusers-named patches.
- For simple renames, the layer object is reused. For QKV splits, new LoRALayer objects
- are created with split up-weights and cloned down-weights.
+ For simple renames, the layer object is reused. Fused QKV LoRA, LoHa, and LoKr patches keep
+ their factorized representation after splitting.
"""
# Double blocks
m = _DOUBLE_BLOCK_RE.match(bfl_key)
@@ -475,15 +309,15 @@ def _convert_bfl_layer_patch_to_diffusers(bfl_key: str, layer: BaseLayerPatch) -
diff_prefix = f"transformer_blocks.{idx}"
# Fused QKV → split into separate Q, K, V
- if rest == "img_attn.qkv" and isinstance(layer, LoRALayer):
- return _split_qkv_lora_layer(
+ if rest == "img_attn.qkv":
+ return _split_qkv_layer_patch(
layer,
q_key=f"{diff_prefix}.attn.to_q",
k_key=f"{diff_prefix}.attn.to_k",
v_key=f"{diff_prefix}.attn.to_v",
)
- if rest == "txt_attn.qkv" and isinstance(layer, LoRALayer):
- return _split_qkv_lora_layer(
+ if rest == "txt_attn.qkv":
+ return _split_qkv_layer_patch(
layer,
q_key=f"{diff_prefix}.attn.add_q_proj",
k_key=f"{diff_prefix}.attn.add_k_proj",
@@ -537,3 +371,221 @@ def _split_qkv_lora_layer(
result.append((key, split_layer))
return result
+
+
+def _split_qkv_bias(
+ bias: torch.Tensor | None, out_features: int
+) -> tuple[torch.Tensor | None, torch.Tensor | None, torch.Tensor | None]:
+ if bias is None:
+ return (None, None, None)
+
+ dense_bias = bias.to_dense() if bias.is_sparse else bias
+ if dense_bias.shape[0] != out_features or out_features % 3 != 0:
+ raise ValueError(
+ f"Expected a fused QKV bias with {out_features} output rows, got shape {tuple(dense_bias.shape)}."
+ )
+ return dense_bias.chunk(3, dim=0)
+
+
+def _split_qkv_loha_layer(
+ layer: LoHALayer,
+ q_key: str,
+ k_key: str,
+ v_key: str,
+) -> list[tuple[str, LoHALayer]]:
+ """Split a fused QKV LoHa by slicing its output factors without materializing its update."""
+ # Standard linear LoHa stores [out, rank]. CP-decomposed convolutional LoHa stores [rank, out].
+ out_axis = 0 if layer.t1 is None else 1
+ out_features = layer.w1_a.shape[out_axis]
+ if layer.w2_a.shape[out_axis] != out_features or out_features % 3 != 0:
+ raise ValueError(
+ "Expected matching fused QKV LoHa output factors with a dimension divisible by 3, "
+ f"got {tuple(layer.w1_a.shape)} and {tuple(layer.w2_a.shape)}."
+ )
+
+ w1_a_parts = layer.w1_a.chunk(3, dim=out_axis)
+ w2_a_parts = layer.w2_a.chunk(3, dim=out_axis)
+ bias_parts = _split_qkv_bias(layer.bias, out_features)
+ result: list[tuple[str, LoHALayer]] = []
+ for key, w1_a, w2_a, bias in zip((q_key, k_key, v_key), w1_a_parts, w2_a_parts, bias_parts, strict=True):
+ result.append(
+ (
+ key,
+ LoHALayer(
+ w1_a=w1_a,
+ w1_b=layer.w1_b,
+ w2_a=w2_a,
+ w2_b=layer.w2_b,
+ t1=layer.t1,
+ t2=layer.t2,
+ alpha=layer._alpha,
+ bias=bias,
+ ),
+ )
+ )
+ return result
+
+
+def _lokr_operand_out_features(layer: LoKRLayer) -> tuple[int, int]:
+ if layer.w1 is not None:
+ w1_out_features = layer.w1.shape[0]
+ else:
+ assert layer.w1_a is not None
+ w1_out_features = layer.w1_a.shape[0]
+
+ if layer.w2 is not None:
+ w2_out_features = layer.w2.shape[0]
+ else:
+ assert layer.w2_a is not None
+ if layer.t2 is None:
+ w2_out_features = layer.w2_a.shape[0]
+ else:
+ # With CP decomposition, einsum reconstructs w2 as [p, r, k, l] from w2_a [i, p].
+ w2_out_features = layer.w2_a.shape[1]
+ return w1_out_features, w2_out_features
+
+
+def _slice_lokr_layer(
+ layer: LoKRLayer,
+ w1_start: int,
+ w1_end: int,
+ w2_start: int,
+ w2_end: int,
+ bias: torch.Tensor | None,
+) -> LoKRLayer:
+ if layer.w1 is not None:
+ w1 = layer.w1[w1_start:w1_end]
+ w1_a = None
+ else:
+ w1 = None
+ assert layer.w1_a is not None
+ w1_a = layer.w1_a[w1_start:w1_end]
+
+ if layer.w2 is not None:
+ w2 = layer.w2[w2_start:w2_end]
+ w2_a = None
+ else:
+ w2 = None
+ assert layer.w2_a is not None
+ w2_a = layer.w2_a[w2_start:w2_end] if layer.t2 is None else layer.w2_a[:, w2_start:w2_end]
+
+ return LoKRLayer(
+ w1=w1,
+ w1_a=w1_a,
+ w1_b=layer.w1_b,
+ w2=w2,
+ w2_a=w2_a,
+ w2_b=layer.w2_b,
+ t2=layer.t2,
+ alpha=layer._alpha,
+ bias=bias,
+ )
+
+
+def _split_qkv_lokr_layer(
+ layer: LoKRLayer,
+ q_key: str,
+ k_key: str,
+ v_key: str,
+) -> list[tuple[str, BaseLayerPatch]]:
+ """Split a fused QKV LoKr while retaining its Kronecker factors.
+
+ Rows of ``kron(w1, w2)`` are grouped into ``w2``-sized blocks, one for each output row of
+ ``w1``. The common case has a w1 output dimension divisible by three, so each projection is
+ another LoKr obtained by slicing w1. For other layouts, each target row range is represented
+ by the exact intersecting LoKr segments in a MergedLayerPatch.
+ """
+ w1_out_features, w2_out_features = _lokr_operand_out_features(layer)
+ fused_out_features = w1_out_features * w2_out_features
+ if fused_out_features % 3 != 0:
+ raise ValueError(f"Expected fused QKV LoKr output rows divisible by 3, got {fused_out_features}.")
+
+ keys = (q_key, k_key, v_key)
+ target_out_features = fused_out_features // 3
+ dense_bias = layer.bias.to_dense() if layer.bias is not None and layer.bias.is_sparse else layer.bias
+ if dense_bias is not None and dense_bias.shape[0] != fused_out_features:
+ raise ValueError(
+ f"Expected a fused QKV LoKr bias with {fused_out_features} output rows, "
+ f"got shape {tuple(dense_bias.shape)}."
+ )
+
+ # Fast path: each Q/K/V range consists of whole w2 row blocks.
+ if w1_out_features % 3 == 0:
+ w1_rows_per_target = w1_out_features // 3
+ result: list[tuple[str, BaseLayerPatch]] = []
+ for target_idx, key in enumerate(keys):
+ w1_start = target_idx * w1_rows_per_target
+ w1_end = w1_start + w1_rows_per_target
+ bias = (
+ None
+ if dense_bias is None
+ else dense_bias[target_idx * target_out_features : (target_idx + 1) * target_out_features]
+ )
+ result.append(
+ (
+ key,
+ _slice_lokr_layer(
+ layer,
+ w1_start=w1_start,
+ w1_end=w1_end,
+ w2_start=0,
+ w2_end=w2_out_features,
+ bias=bias,
+ ),
+ )
+ )
+ return result
+
+ result = []
+ for target_idx, key in enumerate(keys):
+ target_start = target_idx * target_out_features
+ target_end = target_start + target_out_features
+ sub_layers: list[BaseLayerPatch] = []
+ sub_ranges: list[Range] = []
+
+ for w1_row in range(w1_out_features):
+ block_start = w1_row * w2_out_features
+ block_end = block_start + w2_out_features
+ overlap_start = max(target_start, block_start)
+ overlap_end = min(target_end, block_end)
+ if overlap_start >= overlap_end:
+ continue
+
+ w2_start = overlap_start - block_start
+ w2_end = overlap_end - block_start
+ bias = None if dense_bias is None else dense_bias[overlap_start:overlap_end]
+ sub_layers.append(
+ _slice_lokr_layer(
+ layer,
+ w1_start=w1_row,
+ w1_end=w1_row + 1,
+ w2_start=w2_start,
+ w2_end=w2_end,
+ bias=bias,
+ )
+ )
+ sub_ranges.append(Range(overlap_start - target_start, overlap_end - target_start))
+
+ if len(sub_layers) == 1 and sub_ranges[0] == Range(0, target_out_features):
+ result.append((key, sub_layers[0]))
+ else:
+ result.append((key, MergedLayerPatch(sub_layers, sub_ranges)))
+
+ return result
+
+
+def _split_qkv_layer_patch(
+ layer: BaseLayerPatch,
+ q_key: str,
+ k_key: str,
+ v_key: str,
+) -> list[tuple[str, BaseLayerPatch]]:
+ if isinstance(layer, LoRALayer):
+ return _split_qkv_lora_layer(layer, q_key=q_key, k_key=k_key, v_key=v_key)
+ if isinstance(layer, LoHALayer):
+ return _split_qkv_loha_layer(layer, q_key=q_key, k_key=k_key, v_key=v_key)
+ if isinstance(layer, LoKRLayer):
+ return _split_qkv_lokr_layer(layer, q_key=q_key, k_key=k_key, v_key=v_key)
+
+ logger.warning(f"Unsupported {type(layer).__name__} layer type for a fused QKV split; layer will be skipped.")
+ return []
diff --git a/tests/backend/model_manager/configs/test_lycoris_lora_identification.py b/tests/backend/model_manager/configs/test_lycoris_lora_identification.py
new file mode 100644
index 0000000000..d3d5c8779e
--- /dev/null
+++ b/tests/backend/model_manager/configs/test_lycoris_lora_identification.py
@@ -0,0 +1,215 @@
+from collections.abc import Callable
+from unittest.mock import MagicMock
+
+import pytest
+import torch
+
+import invokeai.backend.model_manager.configs.lora as lora_config
+from invokeai.backend.model_manager.configs.identification_utils import NotAMatchError
+from invokeai.backend.model_manager.configs.lora import (
+ LoRA_LyCORIS_Flux2_Config,
+ LoRA_LyCORIS_FLUX_Config,
+ LoRA_LyCORIS_SDXL_Config,
+ _lokr_in_dim,
+ _lokr_out_dim,
+)
+from invokeai.backend.model_manager.taxonomy import BaseModelType, Flux2VariantType
+from invokeai.backend.model_manager.util.model_util import lora_token_vector_length
+
+_REQUIRED_FIELDS = {
+ "hash": "blake3:fakehash",
+ "path": "/fake/models/lycoris.safetensors",
+ "file_size": 1000,
+ "name": "lycoris",
+ "description": "test",
+ "source": "test",
+ "source_type": "path",
+ "key": "test-key",
+}
+
+
+def _tensor(*shape: int) -> torch.Tensor:
+ return torch.empty(shape, device="meta")
+
+
+def _add_lokr_operand(
+ state_dict: dict[str, torch.Tensor],
+ prefix: str,
+ operand: str,
+ shape: tuple[int, int],
+ factorized: bool,
+) -> None:
+ out_dim, in_dim = shape
+ if factorized:
+ rank = 2
+ state_dict[f"{prefix}.lokr_{operand}_a"] = _tensor(out_dim, rank)
+ state_dict[f"{prefix}.lokr_{operand}_b"] = _tensor(rank, in_dim)
+ else:
+ state_dict[f"{prefix}.lokr_{operand}"] = _tensor(out_dim, in_dim)
+
+
+def _lokr_layer(
+ prefix: str,
+ out_dim: int,
+ in_dim: int,
+ *,
+ w1_factorized: bool,
+ w2_factorized: bool,
+) -> dict[str, torch.Tensor]:
+ assert out_dim % 4 == 0
+ assert in_dim % 8 == 0
+ state_dict: dict[str, torch.Tensor] = {}
+ _add_lokr_operand(state_dict, prefix, "w1", (4, 8), w1_factorized)
+ _add_lokr_operand(state_dict, prefix, "w2", (out_dim // 4, in_dim // 8), w2_factorized)
+ return state_dict
+
+
+def _loha_layer(prefix: str, out_dim: int, in_dim: int) -> dict[str, torch.Tensor]:
+ rank = 2
+ return {
+ f"{prefix}.hada_w1_a": _tensor(out_dim, rank),
+ f"{prefix}.hada_w1_b": _tensor(rank, in_dim),
+ f"{prefix}.hada_w2_a": _tensor(out_dim, rank),
+ f"{prefix}.hada_w2_b": _tensor(rank, in_dim),
+ }
+
+
+_LYCORIS_BUILDERS: dict[str, Callable[[str, int, int], dict[str, torch.Tensor]]] = {
+ "lokr": lambda prefix, out_dim, in_dim: _lokr_layer(
+ prefix,
+ out_dim,
+ in_dim,
+ w1_factorized=False,
+ w2_factorized=True,
+ ),
+ "loha": _loha_layer,
+}
+
+
+def _flux_state_dict(layout: str, algorithm: str, hidden_size: int, mlp_size: int) -> dict[str, torch.Tensor]:
+ builder = _LYCORIS_BUILDERS[algorithm]
+ prefixes = {
+ "bfl": (
+ "diffusion_model.double_blocks.0.img_attn.proj",
+ "diffusion_model.double_blocks.0.img_mlp.0",
+ ),
+ "kohya": (
+ "lora_unet_double_blocks_0_img_attn_proj",
+ "lora_unet_double_blocks_0_img_mlp_0",
+ ),
+ }
+ attn_prefix, mlp_prefix = prefixes[layout]
+ state_dict = builder(attn_prefix, hidden_size, hidden_size)
+ state_dict.update(builder(mlp_prefix, mlp_size, hidden_size))
+ return state_dict
+
+
+def _model_on_disk(state_dict: dict[str, torch.Tensor]) -> MagicMock:
+ mod = MagicMock()
+ mod.load_state_dict.return_value = state_dict
+ mod.metadata.return_value = {}
+ return mod
+
+
+ ("w1_factorized", "w2_factorized"),
+ [
+ pytest.param(False, False, id="both-full"),
+ pytest.param(False, True, id="w2-factorized"),
+ pytest.param(True, False, id="w1-factorized"),
+ pytest.param(True, True, id="both-factorized"),
+ ],
+)
+def test_lokr_dimensions_allow_each_operand_to_be_factorized_independently(
+ w1_factorized: bool, w2_factorized: bool
+) -> None:
+ prefix = "layer"
+ state_dict = _lokr_layer(
+ prefix,
+ out_dim=320,
+ in_dim=768,
+ w1_factorized=w1_factorized,
+ w2_factorized=w2_factorized,
+ )
+
+ assert _lokr_in_dim(state_dict, prefix) == 768
+ assert _lokr_out_dim(state_dict, prefix) == 320
+
+
+ ("w1_factorized", "w2_factorized"),
+ [
+ pytest.param(False, False, id="both-full"),
+ pytest.param(False, True, id="w2-factorized"),
+ pytest.param(True, False, id="w1-factorized"),
+ pytest.param(True, True, id="both-factorized"),
+ ],
+)
[email protected]("token_vector_length", [768, 1024], ids=["sd1", "sd2"])
+def test_sd_lokr_token_vector_length_supports_full_and_factorized_operands(
+ w1_factorized: bool, w2_factorized: bool, token_vector_length: int
+) -> None:
+ prefix = "lora_unet_down_blocks_0_attentions_0_transformer_blocks_0_attn2_to_k"
+ state_dict = _lokr_layer(
+ prefix,
+ out_dim=320,
+ in_dim=token_vector_length,
+ w1_factorized=w1_factorized,
+ w2_factorized=w2_factorized,
+ )
+
+ assert lora_token_vector_length(state_dict) == token_vector_length
+
+
[email protected]("algorithm", ["lokr", "loha"])
[email protected]("layout", ["bfl", "kohya"])
+ ("hidden_size", "mlp_size", "variant"),
+ [
+ pytest.param(3072, 18432, Flux2VariantType.Klein4B, id="klein-4b"),
+ pytest.param(4096, 16384, Flux2VariantType.Klein9B, id="klein-9b"),
+ ],
+)
+def test_flux2_config_identifies_lycoris_layouts(
+ monkeypatch: pytest.MonkeyPatch,
+ layout: str,
+ algorithm: str,
+ hidden_size: int,
+ mlp_size: int,
+ variant: Flux2VariantType,
+) -> None:
+ monkeypatch.setattr(lora_config, "raise_if_not_file", lambda _mod: None)
+ mod = _model_on_disk(_flux_state_dict(layout, algorithm, hidden_size, mlp_size))
+
+ config = LoRA_LyCORIS_Flux2_Config.from_model_on_disk(mod, dict(_REQUIRED_FIELDS))
+
+ assert config.base is BaseModelType.Flux2
+ assert config.variant is variant
+
+
[email protected]("algorithm", ["lokr", "loha"])
[email protected]("layout", ["bfl", "kohya"])
+def test_flux1_lycoris_layout_is_not_misidentified_as_flux2(
+ monkeypatch: pytest.MonkeyPatch, layout: str, algorithm: str
+) -> None:
+ monkeypatch.setattr(lora_config, "raise_if_not_file", lambda _mod: None)
+ mod = _model_on_disk(_flux_state_dict(layout, algorithm, hidden_size=3072, mlp_size=12288))
+
+ with pytest.raises(NotAMatchError):
+ LoRA_LyCORIS_Flux2_Config.from_model_on_disk(mod, dict(_REQUIRED_FIELDS))
+
+ config = LoRA_LyCORIS_FLUX_Config.from_model_on_disk(mod, dict(_REQUIRED_FIELDS))
+ assert config.base is BaseModelType.Flux
+
+
[email protected]("algorithm", ["lokr", "loha"])
+def test_sdxl_lycoris_layout_is_not_misidentified_as_flux2(monkeypatch: pytest.MonkeyPatch, algorithm: str) -> None:
+ monkeypatch.setattr(lora_config, "raise_if_not_file", lambda _mod: None)
+ prefix = "lora_unet_down_blocks_0_attentions_0_transformer_blocks_0_attn2_to_k"
+ mod = _model_on_disk(_LYCORIS_BUILDERS[algorithm](prefix, 320, 2048))
+
+ with pytest.raises(NotAMatchError):
+ LoRA_LyCORIS_Flux2_Config.from_model_on_disk(mod, dict(_REQUIRED_FIELDS))
+
+ config = LoRA_LyCORIS_SDXL_Config.from_model_on_disk(mod, dict(_REQUIRED_FIELDS))
+ assert config.base is BaseModelType.StableDiffusionXL
diff --git a/tests/backend/patches/lora_conversions/test_flux2_lycoris_qkv_conversion.py b/tests/backend/patches/lora_conversions/test_flux2_lycoris_qkv_conversion.py
new file mode 100644
index 0000000000..5f9cd3db7d
--- /dev/null
+++ b/tests/backend/patches/lora_conversions/test_flux2_lycoris_qkv_conversion.py
@@ -0,0 +1,285 @@
+import math
+
+import accelerate
+import pytest
+import torch
+from diffusers import Flux2Transformer2DModel
+
+from invokeai.backend.patches.layers.loha_layer import LoHALayer
+from invokeai.backend.patches.layers.lokr_layer import LoKRLayer
+from invokeai.backend.patches.layers.merged_layer_patch import MergedLayerPatch
+from invokeai.backend.patches.lora_conversions.flux_bfl_peft_lora_conversion_utils import (
+ convert_bfl_lora_patch_to_diffusers,
+ is_state_dict_likely_in_flux_bfl_peft_format,
+ lora_model_from_flux2_bfl_peft_state_dict,
+)
+from invokeai.backend.patches.lora_conversions.flux_kohya_lora_conversion_utils import (
+ lora_model_from_flux_kohya_state_dict,
+)
+from invokeai.backend.patches.lora_conversions.flux_lora_constants import FLUX_LORA_TRANSFORMER_PREFIX
+from invokeai.backend.patches.model_patch_raw import ModelPatchRaw
+
+_TINY_FLUX2_CONFIG = {
+ "patch_size": 1,
+ "in_channels": 128,
+ "num_layers": 1,
+ "num_single_layers": 1,
+ "attention_head_dim": 8,
+ "num_attention_heads": 2,
+ "joint_attention_dim": 8,
+ "timestep_guidance_channels": 16,
+ "axes_dims_rope": (2, 2, 2, 2),
+}
+
+
[email protected](scope="module")
+def flux2_transformer() -> Flux2Transformer2DModel:
+ with accelerate.init_empty_weights():
+ return Flux2Transformer2DModel(**_TINY_FLUX2_CONFIG)
+
+
+def _tensor(shape: tuple[int, ...], start: float) -> torch.Tensor:
+ values = torch.arange(math.prod(shape), dtype=torch.float32).reshape(shape)
+ return values / max(values.numel(), 1) + start
+
+
+def _lycoris_state_dict(
+ variant: str, fused_out_features: int, in_features: int
+) -> tuple[dict[str, torch.Tensor], torch.Tensor]:
+ rank = 2
+ alpha = torch.tensor(3.0)
+
+ if variant == "lokr_w1_full":
+ assert in_features % 4 == 0
+ w1 = _tensor((3, 4), 0.25)
+ w2_a = _tensor((fused_out_features // 3, rank), 0.5)
+ w2_b = _tensor((rank, in_features // 4), 0.75)
+ state_dict = {"lokr_w1": w1, "lokr_w2_a": w2_a, "lokr_w2_b": w2_b, "alpha": alpha}
+ expected = torch.kron(w1, w2_a @ w2_b) * (alpha.item() / rank)
+ elif variant == "lokr_w2_full":
+ assert in_features % 4 == 0
+ w1_a = _tensor((3, rank), 0.25)
+ w1_b = _tensor((rank, 4), 0.5)
+ w2 = _tensor((fused_out_features // 3, in_features // 4), 0.75)
+ state_dict = {"lokr_w1_a": w1_a, "lokr_w1_b": w1_b, "lokr_w2": w2, "alpha": alpha}
+ expected = torch.kron(w1_a @ w1_b, w2) * (alpha.item() / rank)
+ elif variant == "loha":
+ w1_a = _tensor((fused_out_features, rank), 0.25)
+ w1_b = _tensor((rank, in_features), 0.5)
+ w2_a = _tensor((fused_out_features, rank), 0.75)
+ w2_b = _tensor((rank, in_features), 1.0)
+ state_dict = {
+ "hada_w1_a": w1_a,
+ "hada_w1_b": w1_b,
+ "hada_w2_a": w2_a,
+ "hada_w2_b": w2_b,
+ "alpha": alpha,
+ }
+ expected = ((w1_a @ w1_b) * (w2_a @ w2_b)) * (alpha.item() / rank)
+ else:
+ raise AssertionError(f"Unhandled test variant: {variant}")
+
+ return state_dict, expected
+
+
+def _convert_patch(source_format: str, bfl_layer: str, layer_state_dict: dict[str, torch.Tensor]) -> ModelPatchRaw:
+ if source_format == "bfl":
+ state_dict = {
+ f"diffusion_model.double_blocks.0.{bfl_layer}.{suffix}": value for suffix, value in layer_state_dict.items()
+ }
+ assert is_state_dict_likely_in_flux_bfl_peft_format(state_dict)
+ return lora_model_from_flux2_bfl_peft_state_dict(state_dict)
+
+ if source_format == "kohya":
+ kohya_layer = f"lora_unet_double_blocks_0_{bfl_layer.replace('.', '_')}"
+ state_dict = {f"{kohya_layer}.{suffix}": value for suffix, value in layer_state_dict.items()}
+ return convert_bfl_lora_patch_to_diffusers(lora_model_from_flux_kohya_state_dict(state_dict))
+
+ raise AssertionError(f"Unhandled source format: {source_format}")
+
+
[email protected]("source_format", ["bfl", "kohya"])
[email protected]("variant", ["lokr_w1_full", "lokr_w2_full", "loha"])
+ ("bfl_layer", "target_modules"),
+ [
+ (
+ "img_attn.qkv",
+ (
+ "transformer_blocks.0.attn.to_q",
+ "transformer_blocks.0.attn.to_k",
+ "transformer_blocks.0.attn.to_v",
+ ),
+ ),
+ (
+ "txt_attn.qkv",
+ (
+ "transformer_blocks.0.attn.add_q_proj",
+ "transformer_blocks.0.attn.add_k_proj",
+ "transformer_blocks.0.attn.add_v_proj",
+ ),
+ ),
+ ],
+ ids=["image", "text"],
+)
+def test_flux2_lycoris_fused_qkv_resolves_and_preserves_update(
+ source_format: str,
+ variant: str,
+ bfl_layer: str,
+ target_modules: tuple[str, str, str],
+ flux2_transformer: Flux2Transformer2DModel,
+) -> None:
+ target = flux2_transformer.get_submodule(target_modules[0])
+ assert isinstance(target, torch.nn.Linear)
+ fused_out_features = target.out_features * 3
+ layer_state_dict, expected_weight = _lycoris_state_dict(variant, fused_out_features, target.in_features)
+
+ patch = _convert_patch(source_format, bfl_layer, layer_state_dict)
+
+ expected_keys = {f"{FLUX_LORA_TRANSFORMER_PREFIX}{module_name}" for module_name in target_modules}
+ assert set(patch.layers) == expected_keys
+ assert not any("qkv" in layer_key for layer_key in patch.layers)
+
+ split_weights: list[torch.Tensor] = []
+ input_vector = _tensor((target.in_features,), 0.125)
+ split_outputs: list[torch.Tensor] = []
+ for module_name in target_modules:
+ module = flux2_transformer.get_submodule(module_name)
+ layer = patch.layers[f"{FLUX_LORA_TRANSFORMER_PREFIX}{module_name}"]
+
+ assert isinstance(module, torch.nn.Linear)
+ expected_layer_type = LoHALayer if variant == "loha" else LoKRLayer
+ assert isinstance(layer, expected_layer_type)
+ assert layer.bias is None
+
+ applied_parameters = layer.get_parameters({"weight": torch.empty(module.weight.shape)}, weight=1.0)
+ assert set(applied_parameters) == {"weight"}
+ split_weight = applied_parameters["weight"].detach()
+ split_weights.append(split_weight)
+ split_outputs.append(split_weight @ input_vector)
+
+ actual_weight = torch.cat(split_weights, dim=0)
+ assert torch.allclose(actual_weight, expected_weight)
+ assert torch.allclose(torch.cat(split_outputs), expected_weight @ input_vector)
+ assert (
+ sum(layer.calc_size() for layer in patch.layers.values())
+ < expected_weight.numel() * expected_weight.element_size()
+ )
+
+
[email protected]("source_format", ["bfl", "kohya"])
[email protected]("variant", ["lokr", "loha"])
+def test_klein_9b_qkv_split_keeps_factorized_storage(source_format: str, variant: str) -> None:
+ hidden_size = 4096
+ fused_out_features = hidden_size * 3
+ rank = 4
+ if variant == "lokr":
+ # This is the mixed layout from the issue: w1 is full and w2 is factorized.
+ layer_state_dict = {
+ "lokr_w1": torch.empty((24, 8), device="meta"),
+ "lokr_w2_a": torch.empty((512, rank), device="meta"),
+ "lokr_w2_b": torch.empty((rank, 512), device="meta"),
+ "alpha": torch.tensor(float(rank)),
+ }
+ expected_type = LoKRLayer
+ else:
+ layer_state_dict = {
+ "hada_w1_a": torch.empty((fused_out_features, rank), device="meta"),
+ "hada_w1_b": torch.empty((rank, hidden_size), device="meta"),
+ "hada_w2_a": torch.empty((fused_out_features, rank), device="meta"),
+ "hada_w2_b": torch.empty((rank, hidden_size), device="meta"),
+ "alpha": torch.tensor(float(rank)),
+ }
+ expected_type = LoHALayer
+
+ patch = _convert_patch(source_format, "img_attn.qkv", layer_state_dict)
+
+ assert len(patch.layers) == 3
+ assert all(isinstance(layer, expected_type) for layer in patch.layers.values())
+ dense_update_bytes = fused_out_features * hidden_size * torch.empty((), dtype=torch.float32).element_size()
+ assert sum(layer.calc_size() for layer in patch.layers.values()) < dense_update_bytes // 100
+
+
[email protected]("source_format", ["bfl", "kohya"])
+def test_non_aligned_lokr_uses_ranges_and_preserves_alpha_and_bias(source_format: str) -> None:
+ w1 = _tensor((2, 2), 0.25)
+ w2_a = _tensor((9, 2), 0.5)
+ w2_b = _tensor((2, 3), 0.75)
+ alpha = torch.tensor(3.0)
+ fused_bias = _tensor((18,), 1.0)
+ state_dict = {
+ "lokr_w1": w1,
+ "lokr_w2_a": w2_a,
+ "lokr_w2_b": w2_b,
+ "alpha": alpha,
+ "bias_indices": torch.arange(18).unsqueeze(0),
+ "bias_values": fused_bias,
+ "bias_size": torch.tensor([18]),
+ }
+ expected_scale = alpha.item() / w2_b.shape[0]
+ expected_weight = torch.kron(w1, w2_a @ w2_b) * expected_scale
+ target_modules = (
+ "transformer_blocks.0.attn.to_q",
+ "transformer_blocks.0.attn.to_k",
+ "transformer_blocks.0.attn.to_v",
+ )
+
+ patch = _convert_patch(source_format, "img_attn.qkv", state_dict)
+
+ split_layers = [patch.layers[f"{FLUX_LORA_TRANSFORMER_PREFIX}{key}"] for key in target_modules]
+ assert isinstance(split_layers[0], LoKRLayer)
+ assert isinstance(split_layers[1], MergedLayerPatch)
+ assert isinstance(split_layers[2], LoKRLayer)
+
+ actual_weights: list[torch.Tensor] = []
+ actual_biases: list[torch.Tensor] = []
+ for layer in split_layers:
+ parameters = layer.get_parameters(
+ {"weight": torch.empty((6, 6)), "bias": torch.empty(6)},
+ weight=1.0,
+ )
+ actual_weights.append(parameters["weight"])
+ actual_biases.append(parameters["bias"])
+
+ assert torch.allclose(torch.cat(actual_weights), expected_weight)
+ assert torch.allclose(torch.cat(actual_biases), fused_bias * expected_scale)
+ assert sum(layer.calc_size() for layer in split_layers) < expected_weight.numel() * expected_weight.element_size()
+
+
[email protected]("source_format", ["bfl", "kohya"])
+def test_loha_split_preserves_alpha_and_bias(source_format: str) -> None:
+ rank = 2
+ alpha = torch.tensor(3.0)
+ w1_a = _tensor((18, rank), 0.25)
+ w1_b = _tensor((rank, 6), 0.5)
+ w2_a = _tensor((18, rank), 0.75)
+ w2_b = _tensor((rank, 6), 1.0)
+ fused_bias = _tensor((18,), 1.25)
+ state_dict = {
+ "hada_w1_a": w1_a,
+ "hada_w1_b": w1_b,
+ "hada_w2_a": w2_a,
+ "hada_w2_b": w2_b,
+ "alpha": alpha,
+ "bias_indices": torch.arange(18).unsqueeze(0),
+ "bias_values": fused_bias,
+ "bias_size": torch.tensor([18]),
+ }
+ expected_scale = alpha.item() / rank
+ expected_weight = ((w1_a @ w1_b) * (w2_a @ w2_b)) * expected_scale
+
+ patch = _convert_patch(source_format, "img_attn.qkv", state_dict)
+
+ assert all(isinstance(layer, LoHALayer) for layer in patch.layers.values())
+ actual_weights: list[torch.Tensor] = []
+ actual_biases: list[torch.Tensor] = []
+ for layer in patch.layers.values():
+ parameters = layer.get_parameters(
+ {"weight": torch.empty((6, 6)), "bias": torch.empty(6)},
+ weight=1.0,
+ )
+ actual_weights.append(parameters["weight"])
+ actual_biases.append(parameters["bias"])
+
+ assert torch.allclose(torch.cat(actual_weights), expected_weight)
+ assert torch.allclose(torch.cat(actual_biases), fused_bias * expected_scale)