Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
fix(qwen-image): identify LyCORIS LoRA layouts and group dotted LoKr and LoHa keys (#10189)
Alexander Eichhorn2674a4015140
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.mdxindex 98fb6b2067..d50a86dbb8 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@@ -211,7 +211,7 @@ starter models do, needs no name. TAEF2, TAEQI2.1 and TAEW2.2 are recognized by| SDXL | ✓ (LyCORIS, Diffusers, OMI) | ✓ | IP-Adapter, T2I-Adapter, textual inversion || FLUX.1 | ✓ (LyCORIS, Diffusers, OMI) | ✓ | Control LoRA, IP-Adapter, Redux || FLUX.2, Z-Image | ✓ (LyCORIS, Diffusers) | FLUX.2 [dev] (single-file checkpoint), Z-Image | |-| Qwen-Image, Krea-2, Wan 2.2, Anima | ✓ (LyCORIS/kohya and Diffusers PEFT, including LoKR where noted on the family page) | Qwen-Image (single-file checkpoint: Fun and InstantX ControlNet Unions; InstantX Inpainting is refused), Anima (ControlNet-LLLite) | |+| Qwen-Image, Krea-2, Wan 2.2, Anima | ✓ (LyCORIS/kohya and Diffusers PEFT, including LoKR, and for Qwen-Image LoHA, where noted on the family page) | Qwen-Image (single-file checkpoint: Fun and InstantX ControlNet Unions; InstantX Inpainting is refused), Anima (ControlNet-LLLite) | || Qwen-Image-2.1 | ✓ (ComfyUI, diffusers/PEFT and kohya, including LoKR, LoHA and DoRA as noted on the family page) | ✗ | || FLUX.3 | ✓ (diffusers/PEFT, ComfyUI and ai-toolkit files and Diffusers folders, including DoRA, and LoKR and LoHA under diffusers or BFL module names; LyCORIS's flattened `lycoris_…` names are not recognized, and PEFT LoKr/LoHa adapters with a diffusers header and distillation extracts are refused, as noted on the family page) | ✗ | || LTX-2, MiniMax H3 | ✓ (plain low-rank; LoKR, LoHA and DoRA are refused) | ✗ | |@@ -226,8 +226,9 @@ Per-layer `.alpha` values in these `diffusion_model.` files set the LoRA scale.For SD 1.x / 2.x and FLUX.2, LyCORIS LoKr files may store either Kronecker operand whole or as afactorized `_a` / `_b` pair. FLUX.2 also accepts LoHA files in the same BFL and kohya layouts.-Plain Qwen-Image LoRAs also load in ComfyUI's `diffusion_model.` key layout and as raw PEFT adapters-(`base_model.model.`) when they train the blocks' modulation or MLP layers; see the+Qwen-Image LoRAs, LoKR and LoHA files also load in ComfyUI's `diffusion_model.` key layout, as raw PEFT adapters+(`base_model.model.`), and in the LyCORIS `lycoris_transformer_blocks_…` and ai-toolkit+`lora_transformer_transformer_blocks_…` layouts, when they train the blocks' modulation or MLP layers; see the[family page](/users-guide/models/local-models/qwen-image/#lora).Qwen-Image LoRAs also patch the Qwen2.5-VL encoder when the file has text-encoder layers; see the same page.diff --git a/docs/src/content/docs/Users Guide/03.Models/Local Models/qwen-image.mdx b/docs/src/content/docs/Users Guide/03.Models/Local Models/qwen-image.mdxindex 9d7ab0a5e6..1f1a1fe001 100644--- a/docs/src/content/docs/Users Guide/03.Models/Local Models/qwen-image.mdx+++ b/docs/src/content/docs/Users Guide/03.Models/Local Models/qwen-image.mdx@@ -1,7 +1,7 @@---title: Qwen Imagedescription: Generate and edit images with the Qwen Image 2512 text-to-image model and the Qwen Image Edit 2511 reference-image editing model, including GGUF and fp8 installs, the Lightning LoRAs and the Fun and InstantX ControlNet Unions.-lastUpdated: 2026-11-02+lastUpdated: 2026-11-10sidebar:order: 9---@@ -161,7 +161,7 @@ Image**; connect an **Image to Latents - Qwen Image** node to the **Reference La## LoRA-Qwen Image LoRAs (diffusers PEFT, Kohya and LoKR formats) are supported and apply to the transformer and,+Qwen Image LoRAs (diffusers PEFT, Kohya, LoKR and LoHA formats) are supported and apply to the transformer and,when the file has text-encoder layers, to the Qwen2.5-VL encoder too. This holds for every encoder build,including the **Encoder quantization** setting. DoRA layers on the encoder need unpacked weights: they failwith int8 or nf4 quantization and with packed nvfp4 encoders, so set **Encoder quantization** to **None** and@@ -171,11 +171,20 @@ In the workflow editor use **Apply LoRA - Qwen Image** or **Apply LoRA Collectioencoder through the LoRA node as well as the transformer: connect the node's **Qwen VL Encoder** output tothe prompt nodes, otherwise the LoRA's text-encoder layers stay unused. The LoRA node logs a warning when it sees this.-Plain LoRAs saved in ComfyUI's layout, whose keys start with `diffusion_model.`, and raw PEFT adapters-(`base_model.model.`) load as well, provided they train the blocks' modulation or MLP layers (`img_mod`,-`txt_mod`, `img_mlp`, `txt_mlp`), as LoRAs in these layouts usually do. Other model families use the same key-prefixes, so a LoRA in these layouts that trains only attention layers is not recognized and installs as an-unknown model, and so do LoKR, LoHA and DoRA files in these layouts. A raw PEFT adapter's strength is set in+Plain LoRAs, LoKR and LoHA files saved in ComfyUI's layout, whose keys start with `diffusion_model.`, and raw+PEFT adapters (`base_model.model.`) load as well, provided they train the blocks' modulation or MLP layers+(`img_mod`, `txt_mod`, `img_mlp`, `txt_mlp`), as files in these layouts usually do. Other model families use the+same key prefixes, so a file in these layouts that trains only attention layers is not recognized and installs as+an unknown model, and so do PEFT DoRA files. LyCORIS and ai-toolkit files whose keys start with+`lycoris_transformer_blocks_` or `lora_transformer_transformer_blocks_` are recognized only when they train those+modules. Without them, a `lycoris_` file installs as an unknown model, and a `lora_transformer_transformer_blocks_`+file installs as a FLUX LoRA, the spelling OneTrainer uses for FLUX. A learned `scalar` in a LoRA, LoKR or LoHA+layer is applied. In the plain dotted layout (`transformer_blocks.` or `transformer.transformer_blocks.`) and+in the Kohya layout (`lora_unet_transformer_blocks_`), LoHA files and LoKR files with factorized matrices+(`lokr_w1_a`, `lokr_w2_a`) are recognized under that condition too, while LoRAs and LoKR files with whole matrices+(`lokr_w1`, `lokr_w2`) are recognized as before. A LoHA or LoKR that also carries DoRA magnitudes+(`dora_scale`) applies without them, as a plain LoHA or LoKR, so it can look different from the trainer's samples.+A raw PEFT adapter's strength is set inits `adapter_config.json`, which is not read, so an adapter trained with `lora_alpha` different from `r`, orwith rsLoRA, applies at a different strength.diff --git a/invokeai/backend/model_manager/configs/lora.py b/invokeai/backend/model_manager/configs/lora.pyindex 62d2031f1d..599a3ff123 100644--- a/invokeai/backend/model_manager/configs/lora.py+++ b/invokeai/backend/model_manager/configs/lora.py@@ -83,6 +83,7 @@ from invokeai.backend.patches.lora_conversions.minimax_h3_lora_constants importfrom invokeai.backend.patches.lora_conversions.qwen_image_2_1_lora_constants import (unsupported_keys as qwen_image_21_unsupported_lora_keys,)+from invokeai.backend.patches.lora_conversions.qwen_image_lora_constants import QWEN_IMAGE_ONLY_MODULE_REfrom invokeai.backend.patches.lora_conversions.sd3_lora_constants import (group_sd3_lora_layers,is_sd3_lora,@@ -909,11 +910,11 @@ class LoRA_LyCORIS_ZImage_Config(LoRA_LyCORIS_Config_Base, Config_Base):# ComfyUI's `diffusion_model.` and raw PEFT's `base_model.model.` also prefix other families' LoRAs, some of them on# `transformer_blocks.N` (LTX-2) or on Qwen-Image's attention names (FLUX in diffusers naming). Under these prefixes,-# only low-rank weights on modules that Qwen-Image's dual-stream blocks alone have identify a Qwen-Image LoRA:-# Qwen-Image-2.1 names its MLP `img_mlp.proj`, and the converter cannot group dotted LoKr keys.+# only weights on modules that Qwen-Image's dual-stream blocks alone have identify a Qwen-Image LoRA:+# Qwen-Image-2.1 names its MLP `img_mlp.proj`._PREFIXED_QWEN_IMAGE_BLOCK_KEY_RE = re.compile(r"^(?:diffusion_model|base_model\.model)\.transformer_blocks\.\d+\.(?:img_mod|txt_mod|img_mlp\.net|txt_mlp)\."- r".*\.(?:lora_A|lora_B|lora_down|lora_up)\.weight$"+ r".*\.(?:(?:lora_A|lora_B|lora_down|lora_up)\.weight|lokr_w[12](?:_[ab])?|hada_w[12]_[ab])$")@@ -925,6 +926,35 @@ def _has_prefixed_qwen_image_lora_keys(state_dict: dict[str | int, Any]) -> boolreturn any(_PREFIXED_QWEN_IMAGE_BLOCK_KEY_RE.match(key) for key in keys)+# LyCORIS' own (`lycoris_`) and ai-toolkit's (`lora_transformer_`, also OneTrainer's FLUX spelling) flattened+# spellings of the transformer, also used by FLUX (`lora_transformer_transformer_blocks_`, diffusers naming) and+# others. Only a module of Qwen-Image's dual-stream blocks identifies a Qwen-Image LoRA under them.+_FLATTENED_QWEN_IMAGE_BLOCK_KEY_RE = re.compile(+ r"^(?:lycoris|lora_transformer)_transformer_blocks_\d+_(?:img_mod|txt_mod|img_mlp_net|txt_mlp)_"+)+++def _has_flattened_qwen_image_lora_keys(state_dict: dict[str | int, Any]) -> bool:+ return any(isinstance(key, str) and _FLATTENED_QWEN_IMAGE_BLOCK_KEY_RE.match(key) for key in state_dict)+++# LoKr and LoHa parameters `any_lora_layer_from_state_dict` reads that were not identification suffixes before. Other+# families' LoRAs share the generic `transformer_blocks.` prefixes, so these count only beside a Qwen-Image-only module.+_QWEN_IMAGE_LYCORIS_ONLY_SUFFIXES = {+ "lokr_w1_a",+ "lokr_w1_b",+ "lokr_w2_a",+ "lokr_w2_b",+ "lokr_t2",+ "hada_w1_a",+ "hada_w1_b",+ "hada_w2_a",+ "hada_w2_b",+ "hada_t1",+ "hada_t2",+}++# Qwen-Image's transformer width (24 heads of 128)._QWEN_IMAGE_HIDDEN_SIZE = 3072# Module names diffusers' SD 3 has and Qwen-Image does not (it names its MLPs `img_mlp`/`txt_mlp` and its modulation@@ -973,7 +1003,7 @@ class LoRA_LyCORIS_QwenImage_Config(LoRA_LyCORIS_Config_Base, Config_Base):"transformer.transformer_blocks.","lora_unet_transformer_blocks_", # Kohya format},- ) or _has_prefixed_qwen_image_lora_keys(state_dict)+ ) or (_has_prefixed_qwen_image_lora_keys(state_dict) or _has_flattened_qwen_image_lora_keys(state_dict))has_lora_suffix = state_dict_has_any_keys_ending_with(state_dict,{@@ -983,8 +1013,11 @@ class LoRA_LyCORIS_QwenImage_Config(LoRA_LyCORIS_Config_Base, Config_Base):"lora_up.weight","dora_scale","lokr_w1",- "lokr_w2", # LoKR format+ "lokr_w2",},+ ) or (+ state_dict_has_any_keys_ending_with(state_dict, _QWEN_IMAGE_LYCORIS_ONLY_SUFFIXES)+ and any(isinstance(key, str) and QWEN_IMAGE_ONLY_MODULE_RE.search(key) for key in state_dict))# Must NOT have diffusion_model.layers (Z-Image) or Flux-style keys.# Flux LoRAs can have transformer.single_transformer_blocks or transformer.transformer_blocks@@ -1035,7 +1068,7 @@ class LoRA_LyCORIS_QwenImage_Config(LoRA_LyCORIS_Config_Base, Config_Base):has_qwen_ie_keys = state_dict_has_any_keys_starting_with(state_dict,{"transformer_blocks.", "transformer.transformer_blocks.", "lora_unet_transformer_blocks_"},- ) or _has_prefixed_qwen_image_lora_keys(state_dict)+ ) or (_has_prefixed_qwen_image_lora_keys(state_dict) or _has_flattened_qwen_image_lora_keys(state_dict))has_z_image_keys = state_dict_has_any_keys_starting_with(state_dict, {"diffusion_model.layers."})has_krea2_keys = _has_krea2_lora_keys(state_dict)str_keys = [key for key in state_dict if isinstance(key, str)]@@ -1098,9 +1131,6 @@ _QWEN_IMAGE21_MLP_MARKERS = (# `audio_to_video_attn.to_q` is as wide and would match the bare `attn.to_q`._BLOCK_ATTENTION_PROJECTION = re.compile(r"transformer_blocks[._]\d+[._]attn[._]to_(?:[qkv]|out[._]0)[._]")_LOKR_FACTOR = re.compile(r"\.(lokr_w[12])(?:_b)?$")-# Modules of Qwen Image's dual-stream blocks that no other family naming `transformer_blocks.N` has: its per-stream-# modulation and MLPs, dotted or Kohya-flattened.-_QWEN_IMAGE_ONLY_MODULE = re.compile(r"transformer_blocks[._]\d+[._](?:img_mod|txt_mod|img_mlp[._]net|txt_mlp)[._]")# The parameters that carry a layer's input width as their second dimension: the input-side matrix of a low-rank@@ -1152,7 +1182,7 @@ def _has_qwen_image21_lora_keys(state_dict: dict[str | int, Any]) -> bool:if _QWEN_IMAGE21_HIDDEN_SIZE in direct:return Truereturn _QWEN_IMAGE21_HIDDEN_SIZE in factored and not any(- isinstance(key, str) and _QWEN_IMAGE_ONLY_MODULE.search(key) for key in state_dict+ isinstance(key, str) and QWEN_IMAGE_ONLY_MODULE_RE.search(key) for key in state_dict)diff --git a/invokeai/backend/patches/lora_conversions/formats.py b/invokeai/backend/patches/lora_conversions/formats.pyindex d10ca4d4a7..4c9853f62d 100644--- a/invokeai/backend/patches/lora_conversions/formats.py+++ b/invokeai/backend/patches/lora_conversions/formats.py@@ -24,6 +24,7 @@ from invokeai.backend.patches.lora_conversions.flux_onetrainer_lora_conversion_ufrom invokeai.backend.patches.lora_conversions.flux_xlabs_lora_conversion_utils import (is_state_dict_likely_in_flux_xlabs_format,)+from invokeai.backend.patches.lora_conversions.qwen_image_lora_constants import QWEN_IMAGE_ONLY_MODULE_REdef flux_format_from_state_dict(@@ -34,6 +35,10 @@ def flux_format_from_state_dict(# ai-toolkit and BFL-PEFT probes below look no further than that, so a FLUX.3 LoRA would identify as theirs too.if has_flux3_lora_keys(state_dict):return None+ # Qwen-Image's OneTrainer LoRAs spell `transformer_blocks_N_<module>` as FLUX's do, and the OneTrainer probe accepts+ # any module name; FLUX has none of Qwen-Image's per-stream modulation and MLP modules.+ if any(isinstance(key, str) and QWEN_IMAGE_ONLY_MODULE_RE.search(key) for key in state_dict):+ return Noneif is_state_dict_likely_in_flux_kohya_format(state_dict):return FluxLoRAFormat.Kohyaelif is_state_dict_likely_in_flux_onetrainer_bfl_format(state_dict, metadata):diff --git a/invokeai/backend/patches/lora_conversions/qwen_image_lora_constants.py b/invokeai/backend/patches/lora_conversions/qwen_image_lora_constants.pyindex e1b1d5bcbd..d0d0cfd711 100644--- a/invokeai/backend/patches/lora_conversions/qwen_image_lora_constants.py+++ b/invokeai/backend/patches/lora_conversions/qwen_image_lora_constants.py@@ -1,8 +1,14 @@+import re+# Qwen Image Edit LoRA prefix constants# These prefixes are used for key mapping when applying LoRA patches to Qwen Image Edit models# Prefix for Qwen Image Edit transformer LoRA layersQWEN_IMAGE_EDIT_LORA_TRANSFORMER_PREFIX = "lora_transformer-"+# Modules of Qwen Image's dual-stream blocks that no other family naming `transformer_blocks.N` has: its per-stream+# modulation and MLPs, dotted or Kohya-flattened. A LoRA naming one of them is Qwen Image's alone.+QWEN_IMAGE_ONLY_MODULE_RE = re.compile(r"transformer_blocks[._]\d+[._](?:img_mod|txt_mod|img_mlp[._]net|txt_mlp)[._]")+# Prefix for Qwen2.5-VL text encoder LoRA layersQWEN_IMAGE_LORA_QWEN_VL_PREFIX = "lora_qwen_vl-"diff --git a/invokeai/backend/patches/lora_conversions/qwen_image_lora_conversion_utils.py b/invokeai/backend/patches/lora_conversions/qwen_image_lora_conversion_utils.pyindex 5736d30c60..bfa46a40a3 100644--- a/invokeai/backend/patches/lora_conversions/qwen_image_lora_conversion_utils.py+++ b/invokeai/backend/patches/lora_conversions/qwen_image_lora_conversion_utils.py@@ -5,6 +5,7 @@ Supports multiple LoRA formats:- Diffusers/PEFT: transformer_blocks.0.attn.to_k.lora_down.weight- With prefix: transformer.transformer_blocks.0.attn.to_k.lora_down.weight (also diffusion_model./base_model.model.)- Kohya: lora_unet_transformer_blocks_0_attn_to_k.lora_down.weight (underscores instead of dots)+- LyCORIS: lycoris_transformer_blocks_0_attn_to_k.lokr_w1 (also ai-toolkit's lora_transformer_transformer_blocks_0_...)Text-encoder layers are routed to the Qwen2.5-VL encoder under their own prefix:- Diffusers/PEFT: text_encoder.model.language_model.layers.0.mlp.down_proj.lora_A.weight (also base_model.model.,@@ -63,10 +64,17 @@ _KOHYA_TEXT_ENCODER_TREE: ParsingTree = {"lm_head": {},}+# Prefixes of the flattened (Kohya-style) spellings: Kohya's, LyCORIS' own, and ai-toolkit's.+_KOHYA_PREFIXES = (+ "lora_unet_transformer_blocks_",+ "lycoris_transformer_blocks_",+ "lora_transformer_transformer_blocks_",+)+# Regex for Kohya-format Qwen Image LoRA keys.# Example: lora_unet_transformer_blocks_0_attn_to_k# Groups: (block_idx, sub_module_with_underscores)-_KOHYA_KEY_REGEX = re.compile(r"lora_unet_transformer_blocks_(\d+)_(.*)")+_KOHYA_KEY_REGEX = re.compile(r"(?:lora_unet_|lycoris_|lora_transformer_)transformer_blocks_(\d+)_(.*)")# Mapping from Kohya underscore-separated sub-module names to dot-separated model paths.# The Kohya format uses underscores everywhere, but some underscores are part of the@@ -98,7 +106,7 @@ def is_state_dict_likely_kohya_qwen_image(state_dict: dict[str | int, torch.Tensif not str_keys:return False# Check if any key matches the Kohya pattern- return any(k.startswith("lora_unet_transformer_blocks_") for k in str_keys)+ return any(k.startswith(_KOHYA_PREFIXES) for k in str_keys)def _convert_kohya_key(kohya_layer: str) -> str | None:@@ -154,6 +162,7 @@ def lora_model_from_qwen_image_state_dict(- With prefix: transformer.transformer_blocks.0.attn.to_k.lora_down.weight(also diffusion_model., base_model.model.)- Kohya: lora_unet_transformer_blocks_0_attn_to_k.lora_down.weight+ (also LyCORIS' lycoris_transformer_blocks_ and ai-toolkit's lora_transformer_transformer_blocks_)"""is_kohya = is_state_dict_likely_kohya_qwen_image(state_dict)@@ -189,7 +198,7 @@ def _convert_kohya_format(state_dict: Dict[str, torch.Tensor], alpha: float | Nounmapped += 1continue- layers[f"{prefix}{model_path}"] = any_lora_layer_from_state_dict(layer_dict)+ layers[f"{prefix}{model_path}"] = any_lora_layer_from_state_dict(_fold_lycoris_scalar(layer_dict))_warn_unmapped_layers(unmapped)return ModelPatchRaw(layers=layers)@@ -206,6 +215,7 @@ def _convert_diffusers_format(state_dict: Dict[str, torch.Tensor], alpha: floatunmapped = 0for layer_key, layer_dict in grouped.items():+ values = _normalize_lora_keys(_fold_lycoris_scalar(layer_dict), alpha)# Text-encoder layers first: `base_model.model.` is also in the transformer strip list.text_encoder_prefix = next((p for p in _DIFFUSERS_TEXT_ENCODER_PREFIXES if layer_key.startswith(p)), None)if text_encoder_prefix is not None:@@ -215,10 +225,9 @@ def _convert_diffusers_format(state_dict: Dict[str, torch.Tensor], alpha: floatif not kohya_module_path_is_leaf(module_path, _KOHYA_TEXT_ENCODER_TREE):unmapped += 1continue- layer = any_lora_layer_from_state_dict(_normalize_lora_keys(layer_dict, alpha))- layers[f"{QWEN_IMAGE_LORA_QWEN_VL_PREFIX}{module_path}"] = layer+ layers[f"{QWEN_IMAGE_LORA_QWEN_VL_PREFIX}{module_path}"] = any_lora_layer_from_state_dict(values)continue- layer = any_lora_layer_from_state_dict(_normalize_lora_keys(layer_dict, alpha))+ layer = any_lora_layer_from_state_dict(values)clean_key = layer_keyfor prefix in strip_prefixes:if clean_key.startswith(prefix):@@ -231,6 +240,25 @@ def _convert_diffusers_format(state_dict: Dict[str, torch.Tensor], alpha: floatreturn ModelPatchRaw(layers=layers)+def _fold_lycoris_scalar(layer_dict: dict[str, torch.Tensor]) -> dict[str, torch.Tensor]:+ """Fold LyCORIS' learned `scalar` into the layer's weights.++ LyCORIS multiplies a LoKr, LoHa or LoRA/LoCon layer's whole update by `scalar` (trained from zero, so it is+ usually far from 1), and the patch layers ignore it. The update is linear in the LoKr's `w1`, the LoHa's `w1_a`+ and the LoRA's up matrix, so scaling that factor gives the same update. Runs before key normalization, which+ drops keys it does not know.+ """+ if "scalar" not in layer_dict:+ return layer_dict+ folded = dict(layer_dict)+ scalar = folded.pop("scalar")+ for key in ("lokr_w1", "lokr_w1_a", "hada_w1_a", "lora_up.weight", "lora_B.weight"):+ if key in folded:+ folded[key] = folded[key] * scalar.to(folded[key].dtype)+ break+ return folded++def _normalize_lora_keys(layer_dict: dict[str, torch.Tensor], alpha: float | None) -> dict[str, torch.Tensor]:"""Normalize LoRA key names to internal format."""if "lora_A.weight" in layer_dict:@@ -264,6 +292,21 @@ def _group_by_layer(state_dict: Dict[str, torch.Tensor]) -> dict[str, dict[str,".lora_magnitude_vector.weight",".dora_scale",".alpha",+ ".scalar",+ # LoKr and LoHa parameters+ ".lokr_w1",+ ".lokr_w1_a",+ ".lokr_w1_b",+ ".lokr_w2",+ ".lokr_w2_a",+ ".lokr_w2_b",+ ".lokr_t2",+ ".hada_w1_a",+ ".hada_w1_b",+ ".hada_w2_a",+ ".hada_w2_b",+ ".hada_t1",+ ".hada_t2",]for key in state_dict:diff --git a/tests/backend/model_manager/configs/test_qwen_image_lora_config.py b/tests/backend/model_manager/configs/test_qwen_image_lora_config.pyindex b6be9567b3..f8db061899 100644--- a/tests/backend/model_manager/configs/test_qwen_image_lora_config.py+++ b/tests/backend/model_manager/configs/test_qwen_image_lora_config.py@@ -13,7 +13,7 @@ import torchfrom invokeai.backend.model_manager.configs.base import Config_Basefrom invokeai.backend.model_manager.configs.identification_utils import NotAMatchError-from invokeai.backend.model_manager.configs.lora import LoRA_LyCORIS_QwenImage_Config+from invokeai.backend.model_manager.configs.lora import LoRA_LyCORIS_FLUX_Config, LoRA_LyCORIS_QwenImage_Configfrom invokeai.backend.model_manager.taxonomy import ModelType# Every Linear in a Qwen-Image transformer block, with its (in, out) features.@@ -78,12 +78,9 @@ def _overrides(path: Path) -> dict[str, str | int]:}[email protected]("prefix", ["", "transformer.", "diffusion_model.", "base_model.model."])-def test_only_the_qwen_image_probe_claims_a_qwen_image_lora(prefix: str, tmp_path: Path) -> None:- """`Config_Base.CONFIG_CLASSES` is a set: a second LoRA probe accepting the file would make the result depend- on iteration order."""+def _accepting_probes(sd: dict[str, torch.Tensor], tmp_path: Path) -> list[str]:path = tmp_path / "lora.safetensors"- mod = _make_mod(path, _qwen_image_lora(prefix))+ mod = _make_mod(path, sd)accepting = []for cls in Config_Base.CONFIG_CLASSES:@@ -95,8 +92,14 @@ def test_only_the_qwen_image_probe_claims_a_qwen_image_lora(prefix: str, tmp_pat# As in the model config factory, anything but a returned config is no match.continueaccepting.append(cls.__name__)+ return accepting- assert accepting == [LoRA_LyCORIS_QwenImage_Config.__name__]+[email protected]("prefix", ["", "transformer.", "diffusion_model.", "base_model.model."])+def test_only_the_qwen_image_probe_claims_a_qwen_image_lora(prefix: str, tmp_path: Path) -> None:+ """`Config_Base.CONFIG_CLASSES` is a set: a second LoRA probe accepting the file would make the result depend+ on iteration order."""+ assert _accepting_probes(_qwen_image_lora(prefix), tmp_path) == [LoRA_LyCORIS_QwenImage_Config.__name__]@pytest.mark.parametrize(@@ -234,13 +237,181 @@ def test_a_prefixed_peft_dora_is_not_claimed(tmp_path: Path) -> None:LoRA_LyCORIS_QwenImage_Config.from_model_on_disk(_make_mod(path, sd), _overrides(path))-def test_a_prefixed_lokr_is_not_claimed(tmp_path: Path) -> None:- """The converter cannot group dotted LoKr keys, so claiming one would install a LoRA that fails to apply."""+def _lokr_layers(prefix: str, *, factorized_w1: bool = False) -> dict[str, torch.Tensor]:sd: dict[str, torch.Tensor] = {}for module, (in_features, out_features) in _QWEN_IMAGE_BLOCK_LINEARS.items():- sd[f"diffusion_model.transformer_blocks.0.{module}.lokr_w1"] = _z(16, 16)- sd[f"diffusion_model.transformer_blocks.0.{module}.lokr_w2"] = _z(out_features // 16, in_features // 16)- path = tmp_path / "lokr.safetensors"+ key = f"{prefix}{module}"+ if factorized_w1:+ sd[f"{key}.lokr_w1_a"] = _z(16, 4)+ sd[f"{key}.lokr_w1_b"] = _z(4, 16)+ else:+ sd[f"{key}.lokr_w1"] = _z(16, 16)+ sd[f"{key}.lokr_w2"] = _z(out_features // 16, in_features // 16)+ return sd- with pytest.raises(NotAMatchError):- LoRA_LyCORIS_QwenImage_Config.from_model_on_disk(_make_mod(path, sd), _overrides(path))+[email protected]("factorized_w1", [False, True])[email protected]("prefix", ["transformer.", "diffusion_model.", "base_model.model."])+def test_a_dotted_lokr_with_qwen_image_only_modules_is_claimed(+ prefix: str, factorized_w1: bool, tmp_path: Path+) -> None:+ sd = _lokr_layers(f"{prefix}transformer_blocks.0.", factorized_w1=factorized_w1)++ assert _accepting_probes(sd, tmp_path) == [LoRA_LyCORIS_QwenImage_Config.__name__]+++def _loha_layers(prefix: str) -> dict[str, torch.Tensor]:+ sd: dict[str, torch.Tensor] = {}+ for module, (in_features, out_features) in _QWEN_IMAGE_BLOCK_LINEARS.items():+ key = f"{prefix}{module}"+ sd[f"{key}.hada_w1_a"] = _z(out_features, 8)+ sd[f"{key}.hada_w1_b"] = _z(8, in_features)+ sd[f"{key}.hada_w2_a"] = _z(out_features, 8)+ sd[f"{key}.hada_w2_b"] = _z(8, in_features)+ return sd++[email protected]("prefix", ["transformer.transformer_blocks.0.", "transformer_blocks.0."])+def test_a_dotted_loha_with_qwen_image_only_modules_is_claimed(prefix: str, tmp_path: Path) -> None:+ assert _accepting_probes(_loha_layers(prefix), tmp_path) == [LoRA_LyCORIS_QwenImage_Config.__name__]++[email protected]("prefix", ["transformer.transformer_blocks.0.", "transformer_blocks.0."])+ "modules",+ [+ pytest.param(+ {+ "attn.to_q": (3072, 3072),+ "attn.add_q_proj": (3072, 3072),+ "ff.net.0.proj": (3072, 12288),+ "ff_context.net.2": (12288, 3072),+ "norm1.linear": (3072, 18432),+ },+ id="flux-diffusers-naming",+ ),+ pytest.param({"attn.to_q": (3072, 3072), "attn.to_k": (3072, 3072)}, id="attention-only"),+ ],+)+def test_a_dotted_loha_without_a_qwen_image_only_module_is_not_claimed(+ prefix: str, modules: dict[str, tuple[int, int]], tmp_path: Path+) -> None:+ """The LoHA suffixes are new to this probe, so an ambiguous LoHA stays unrecognized rather than landing in+ Qwen-Image."""+ sd: dict[str, torch.Tensor] = {}+ for module, (in_features, out_features) in modules.items():+ for param, shape in (("w1_a", (out_features, 8)), ("w1_b", (8, in_features))) + (+ ("w2_a", (out_features, 8)),+ ("w2_b", (8, in_features)),+ ):+ sd[f"{prefix}{module}.hada_{param}"] = _z(*shape)++ assert LoRA_LyCORIS_QwenImage_Config.__name__ not in _accepting_probes(sd, tmp_path)+++# Flattened LyCORIS and ai-toolkit spellings: `lycoris_transformer_blocks_N_<module>` and+# `lora_transformer_transformer_blocks_N_<module>`.+++def _flattened(prefix: str, sd: dict[str, torch.Tensor]) -> dict[str, torch.Tensor]:+ """Rename `<module.with.dots>.<param>` keys to `<prefix><module_with_underscores>.<param>`."""+ flat: dict[str, torch.Tensor] = {}+ for key, value in sd.items():+ module, param = key.rsplit(".", 1)+ flat[f"{prefix}{module.replace('.', '_')}.{param}"] = value+ return flat++[email protected]("scalar", [False, True])[email protected]("factorized_w1", [False, True])+def test_a_lycoris_prefixed_lokr_is_claimed(factorized_w1: bool, scalar: bool, tmp_path: Path) -> None:+ """Trained LyCORIS LoKr files save `lycoris_transformer_blocks_N_<module>` keys, some with a learned scalar."""+ sd = _flattened("lycoris_transformer_blocks_0_", _lokr_layers("", factorized_w1=factorized_w1))+ for module in {key.split(".", 1)[0] for key in sd}:+ sd[f"{module}.alpha"] = _z()+ if scalar:+ sd[f"{module}.scalar"] = _z()++ assert _accepting_probes(sd, tmp_path) == [LoRA_LyCORIS_QwenImage_Config.__name__]+++def test_a_lora_transformer_prefixed_loha_with_dora_is_qwen_image_not_flux(tmp_path: Path) -> None:+ """The `lora_transformer_transformer_blocks_` spelling (ai-toolkit LoHa) is also OneTrainer's for FLUX, and the+ FLUX probe accepts any module name, so only Qwen-Image's own modules tell them apart."""+ sd = _flattened("lora_transformer_transformer_blocks_0_", _loha_layers(""))+ for module in {key.split(".", 1)[0] for key in sd}:+ sd[f"{module}.dora_scale"] = _z(8, 1)+ sd[f"{module}.alpha"] = _z()+ sd[f"{module}.scalar"] = _z()++ assert _accepting_probes(sd, tmp_path) == [LoRA_LyCORIS_QwenImage_Config.__name__]+++def test_a_flux_onetrainer_lora_is_still_flux(tmp_path: Path) -> None:+ """The same spelling with FLUX's own modules (diffusers naming) stays with the FLUX probe."""+ sd: dict[str, torch.Tensor] = {}+ flux_modules = {+ "lora_transformer_transformer_blocks_0_": {+ "attn_to_q": (3072, 3072),+ "attn_add_k_proj": (3072, 3072),+ "attn_to_add_out": (3072, 3072),+ "ff_net_0_proj": (3072, 12288),+ "ff_context_net_2": (12288, 3072),+ "norm1_linear": (3072, 18432),+ },+ "lora_transformer_single_transformer_blocks_0_": {+ "attn_to_q": (3072, 3072),+ "proj_mlp": (3072, 12288),+ "proj_out": (15360, 3072),+ },+ }+ for prefix, modules in flux_modules.items():+ for module, (in_features, out_features) in modules.items():+ sd[f"{prefix}{module}.lora_down.weight"] = _z(16, in_features)+ sd[f"{prefix}{module}.lora_up.weight"] = _z(out_features, 16)+ sd[f"{prefix}{module}.alpha"] = _z()++ assert _accepting_probes(sd, tmp_path) == [LoRA_LyCORIS_FLUX_Config.__name__]+++ "layers",+ [+ pytest.param(+ # FLUX in diffusers naming, without single blocks: attention and feed-forward modules only.+ {+ "lycoris_transformer_blocks_0_attn_to_q": (3072, 3072),+ "lycoris_transformer_blocks_0_attn_add_k_proj": (3072, 3072),+ "lycoris_transformer_blocks_0_ff_net_0_proj": (3072, 12288),+ },+ id="flux-diffusers-naming",+ ),+ pytest.param(+ # LTX-2: video attention plus the audio and cross-modal towers.+ {+ "lycoris_transformer_blocks_0_attn1_to_q": (4096, 4096),+ "lycoris_transformer_blocks_0_audio_attn1_to_q": (2048, 2048),+ "lycoris_transformer_blocks_0_audio_to_video_attn_to_q": (2048, 2048),+ },+ id="ltx2",+ ),+ pytest.param(+ # Qwen-Image-2.1: a gated MLP instead of `img_mlp.net`.+ {+ "lycoris_transformer_blocks_0_attn_to_q": (4096, 4096),+ "lycoris_transformer_blocks_0_img_mlp_proj": (4096, 16384),+ "lycoris_transformer_blocks_0_img_mlp_out": (16384, 4096),+ },+ id="qwen-image-2.1",+ ),+ ],+)+def test_a_lycoris_prefixed_lokr_of_another_family_is_not_claimed(+ layers: dict[str, tuple[int, int]], tmp_path: Path+) -> None:+ sd: dict[str, torch.Tensor] = {}+ for key, (in_features, out_features) in layers.items():+ sd[f"{key}.lokr_w1"] = _z(16, 16)+ sd[f"{key}.lokr_w2"] = _z(out_features // 16, in_features // 16)++ assert LoRA_LyCORIS_QwenImage_Config.__name__ not in _accepting_probes(sd, tmp_path)diff --git a/tests/backend/patches/lora_conversions/lora_state_dicts/qwen_image_lora_aitoolkit_loha_format.py b/tests/backend/patches/lora_conversions/lora_state_dicts/qwen_image_lora_aitoolkit_loha_format.pynew file mode 100644index 0000000000..de9f027664--- /dev/null+++ b/tests/backend/patches/lora_conversions/lora_state_dicts/qwen_image_lora_aitoolkit_loha_format.py@@ -0,0 +1,103 @@+# ai-toolkit LoHa (with DoRA and scalar) Qwen Image LoRA state dict keys, block 0 of a trained file (3072 hidden size).+# Keys: lora_transformer_transformer_blocks_{N}_{sub_module}.{param}, the spelling OneTrainer also uses for FLUX.++state_dict_keys: dict[str, list[int]] = {+ "lora_transformer_transformer_blocks_0_attn_add_k_proj.alpha": [],+ "lora_transformer_transformer_blocks_0_attn_add_k_proj.dora_scale": [3072, 1],+ "lora_transformer_transformer_blocks_0_attn_add_k_proj.hada_w1_a": [3072, 64],+ "lora_transformer_transformer_blocks_0_attn_add_k_proj.hada_w1_b": [64, 3072],+ "lora_transformer_transformer_blocks_0_attn_add_k_proj.hada_w2_a": [3072, 64],+ "lora_transformer_transformer_blocks_0_attn_add_k_proj.hada_w2_b": [64, 3072],+ "lora_transformer_transformer_blocks_0_attn_add_k_proj.scalar": [],+ "lora_transformer_transformer_blocks_0_attn_add_q_proj.alpha": [],+ "lora_transformer_transformer_blocks_0_attn_add_q_proj.dora_scale": [3072, 1],+ "lora_transformer_transformer_blocks_0_attn_add_q_proj.hada_w1_a": [3072, 64],+ "lora_transformer_transformer_blocks_0_attn_add_q_proj.hada_w1_b": [64, 3072],+ "lora_transformer_transformer_blocks_0_attn_add_q_proj.hada_w2_a": [3072, 64],+ "lora_transformer_transformer_blocks_0_attn_add_q_proj.hada_w2_b": [64, 3072],+ "lora_transformer_transformer_blocks_0_attn_add_q_proj.scalar": [],+ "lora_transformer_transformer_blocks_0_attn_add_v_proj.alpha": [],+ "lora_transformer_transformer_blocks_0_attn_add_v_proj.dora_scale": [3072, 1],+ "lora_transformer_transformer_blocks_0_attn_add_v_proj.hada_w1_a": [3072, 64],+ "lora_transformer_transformer_blocks_0_attn_add_v_proj.hada_w1_b": [64, 3072],+ "lora_transformer_transformer_blocks_0_attn_add_v_proj.hada_w2_a": [3072, 64],+ "lora_transformer_transformer_blocks_0_attn_add_v_proj.hada_w2_b": [64, 3072],+ "lora_transformer_transformer_blocks_0_attn_add_v_proj.scalar": [],+ "lora_transformer_transformer_blocks_0_attn_to_add_out.alpha": [],+ "lora_transformer_transformer_blocks_0_attn_to_add_out.dora_scale": [3072, 1],+ "lora_transformer_transformer_blocks_0_attn_to_add_out.hada_w1_a": [3072, 64],+ "lora_transformer_transformer_blocks_0_attn_to_add_out.hada_w1_b": [64, 3072],+ "lora_transformer_transformer_blocks_0_attn_to_add_out.hada_w2_a": [3072, 64],+ "lora_transformer_transformer_blocks_0_attn_to_add_out.hada_w2_b": [64, 3072],+ "lora_transformer_transformer_blocks_0_attn_to_add_out.scalar": [],+ "lora_transformer_transformer_blocks_0_attn_to_k.alpha": [],+ "lora_transformer_transformer_blocks_0_attn_to_k.dora_scale": [3072, 1],+ "lora_transformer_transformer_blocks_0_attn_to_k.hada_w1_a": [3072, 64],+ "lora_transformer_transformer_blocks_0_attn_to_k.hada_w1_b": [64, 3072],+ "lora_transformer_transformer_blocks_0_attn_to_k.hada_w2_a": [3072, 64],+ "lora_transformer_transformer_blocks_0_attn_to_k.hada_w2_b": [64, 3072],+ "lora_transformer_transformer_blocks_0_attn_to_k.scalar": [],+ "lora_transformer_transformer_blocks_0_attn_to_out_0.alpha": [],+ "lora_transformer_transformer_blocks_0_attn_to_out_0.dora_scale": [3072, 1],+ "lora_transformer_transformer_blocks_0_attn_to_out_0.hada_w1_a": [3072, 64],+ "lora_transformer_transformer_blocks_0_attn_to_out_0.hada_w1_b": [64, 3072],+ "lora_transformer_transformer_blocks_0_attn_to_out_0.hada_w2_a": [3072, 64],+ "lora_transformer_transformer_blocks_0_attn_to_out_0.hada_w2_b": [64, 3072],+ "lora_transformer_transformer_blocks_0_attn_to_out_0.scalar": [],+ "lora_transformer_transformer_blocks_0_attn_to_q.alpha": [],+ "lora_transformer_transformer_blocks_0_attn_to_q.dora_scale": [3072, 1],+ "lora_transformer_transformer_blocks_0_attn_to_q.hada_w1_a": [3072, 64],+ "lora_transformer_transformer_blocks_0_attn_to_q.hada_w1_b": [64, 3072],+ "lora_transformer_transformer_blocks_0_attn_to_q.hada_w2_a": [3072, 64],+ "lora_transformer_transformer_blocks_0_attn_to_q.hada_w2_b": [64, 3072],+ "lora_transformer_transformer_blocks_0_attn_to_q.scalar": [],+ "lora_transformer_transformer_blocks_0_attn_to_v.alpha": [],+ "lora_transformer_transformer_blocks_0_attn_to_v.dora_scale": [3072, 1],+ "lora_transformer_transformer_blocks_0_attn_to_v.hada_w1_a": [3072, 64],+ "lora_transformer_transformer_blocks_0_attn_to_v.hada_w1_b": [64, 3072],+ "lora_transformer_transformer_blocks_0_attn_to_v.hada_w2_a": [3072, 64],+ "lora_transformer_transformer_blocks_0_attn_to_v.hada_w2_b": [64, 3072],+ "lora_transformer_transformer_blocks_0_attn_to_v.scalar": [],+ "lora_transformer_transformer_blocks_0_img_mlp_net_0_proj.alpha": [],+ "lora_transformer_transformer_blocks_0_img_mlp_net_0_proj.dora_scale": [12288, 1],+ "lora_transformer_transformer_blocks_0_img_mlp_net_0_proj.hada_w1_a": [12288, 64],+ "lora_transformer_transformer_blocks_0_img_mlp_net_0_proj.hada_w1_b": [64, 3072],+ "lora_transformer_transformer_blocks_0_img_mlp_net_0_proj.hada_w2_a": [12288, 64],+ "lora_transformer_transformer_blocks_0_img_mlp_net_0_proj.hada_w2_b": [64, 3072],+ "lora_transformer_transformer_blocks_0_img_mlp_net_0_proj.scalar": [],+ "lora_transformer_transformer_blocks_0_img_mlp_net_2.alpha": [],+ "lora_transformer_transformer_blocks_0_img_mlp_net_2.dora_scale": [3072, 1],+ "lora_transformer_transformer_blocks_0_img_mlp_net_2.hada_w1_a": [3072, 64],+ "lora_transformer_transformer_blocks_0_img_mlp_net_2.hada_w1_b": [64, 12288],+ "lora_transformer_transformer_blocks_0_img_mlp_net_2.hada_w2_a": [3072, 64],+ "lora_transformer_transformer_blocks_0_img_mlp_net_2.hada_w2_b": [64, 12288],+ "lora_transformer_transformer_blocks_0_img_mlp_net_2.scalar": [],+ "lora_transformer_transformer_blocks_0_img_mod_1.alpha": [],+ "lora_transformer_transformer_blocks_0_img_mod_1.dora_scale": [18432, 1],+ "lora_transformer_transformer_blocks_0_img_mod_1.hada_w1_a": [18432, 64],+ "lora_transformer_transformer_blocks_0_img_mod_1.hada_w1_b": [64, 3072],+ "lora_transformer_transformer_blocks_0_img_mod_1.hada_w2_a": [18432, 64],+ "lora_transformer_transformer_blocks_0_img_mod_1.hada_w2_b": [64, 3072],+ "lora_transformer_transformer_blocks_0_img_mod_1.scalar": [],+ "lora_transformer_transformer_blocks_0_txt_mlp_net_0_proj.alpha": [],+ "lora_transformer_transformer_blocks_0_txt_mlp_net_0_proj.dora_scale": [12288, 1],+ "lora_transformer_transformer_blocks_0_txt_mlp_net_0_proj.hada_w1_a": [12288, 64],+ "lora_transformer_transformer_blocks_0_txt_mlp_net_0_proj.hada_w1_b": [64, 3072],+ "lora_transformer_transformer_blocks_0_txt_mlp_net_0_proj.hada_w2_a": [12288, 64],+ "lora_transformer_transformer_blocks_0_txt_mlp_net_0_proj.hada_w2_b": [64, 3072],+ "lora_transformer_transformer_blocks_0_txt_mlp_net_0_proj.scalar": [],+ "lora_transformer_transformer_blocks_0_txt_mlp_net_2.alpha": [],+ "lora_transformer_transformer_blocks_0_txt_mlp_net_2.dora_scale": [3072, 1],+ "lora_transformer_transformer_blocks_0_txt_mlp_net_2.hada_w1_a": [3072, 64],+ "lora_transformer_transformer_blocks_0_txt_mlp_net_2.hada_w1_b": [64, 12288],+ "lora_transformer_transformer_blocks_0_txt_mlp_net_2.hada_w2_a": [3072, 64],+ "lora_transformer_transformer_blocks_0_txt_mlp_net_2.hada_w2_b": [64, 12288],+ "lora_transformer_transformer_blocks_0_txt_mlp_net_2.scalar": [],+ "lora_transformer_transformer_blocks_0_txt_mod_1.alpha": [],+ "lora_transformer_transformer_blocks_0_txt_mod_1.dora_scale": [18432, 1],+ "lora_transformer_transformer_blocks_0_txt_mod_1.hada_w1_a": [18432, 64],+ "lora_transformer_transformer_blocks_0_txt_mod_1.hada_w1_b": [64, 3072],+ "lora_transformer_transformer_blocks_0_txt_mod_1.hada_w2_a": [18432, 64],+ "lora_transformer_transformer_blocks_0_txt_mod_1.hada_w2_b": [64, 3072],+ "lora_transformer_transformer_blocks_0_txt_mod_1.scalar": [],+}diff --git a/tests/backend/patches/lora_conversions/lora_state_dicts/qwen_image_lora_lycoris_lokr_format.py b/tests/backend/patches/lora_conversions/lora_state_dicts/qwen_image_lora_lycoris_lokr_format.pynew file mode 100644index 0000000000..77022e53b8--- /dev/null+++ b/tests/backend/patches/lora_conversions/lora_state_dicts/qwen_image_lora_lycoris_lokr_format.py@@ -0,0 +1,42 @@+# LyCORIS LoKr Qwen Image LoRA state dict keys, block 0 of a trained file (shapes as stored, 3072 hidden size).+# Keys: lycoris_transformer_blocks_{N}_{sub_module}.{param}. The attention projections and MLPs are trained; the+# modulation (img_mod/txt_mod) is not.++state_dict_keys: dict[str, list[int]] = {+ "lycoris_transformer_blocks_0_attn_add_k_proj.alpha": [],+ "lycoris_transformer_blocks_0_attn_add_k_proj.lokr_w1": [16, 16],+ "lycoris_transformer_blocks_0_attn_add_k_proj.lokr_w2": [192, 192],+ "lycoris_transformer_blocks_0_attn_add_q_proj.alpha": [],+ "lycoris_transformer_blocks_0_attn_add_q_proj.lokr_w1": [16, 16],+ "lycoris_transformer_blocks_0_attn_add_q_proj.lokr_w2": [192, 192],+ "lycoris_transformer_blocks_0_attn_add_v_proj.alpha": [],+ "lycoris_transformer_blocks_0_attn_add_v_proj.lokr_w1": [16, 16],+ "lycoris_transformer_blocks_0_attn_add_v_proj.lokr_w2": [192, 192],+ "lycoris_transformer_blocks_0_attn_to_add_out.alpha": [],+ "lycoris_transformer_blocks_0_attn_to_add_out.lokr_w1": [16, 16],+ "lycoris_transformer_blocks_0_attn_to_add_out.lokr_w2": [192, 192],+ "lycoris_transformer_blocks_0_attn_to_k.alpha": [],+ "lycoris_transformer_blocks_0_attn_to_k.lokr_w1": [16, 16],+ "lycoris_transformer_blocks_0_attn_to_k.lokr_w2": [192, 192],+ "lycoris_transformer_blocks_0_attn_to_out_0.alpha": [],+ "lycoris_transformer_blocks_0_attn_to_out_0.lokr_w1": [16, 16],+ "lycoris_transformer_blocks_0_attn_to_out_0.lokr_w2": [192, 192],+ "lycoris_transformer_blocks_0_attn_to_q.alpha": [],+ "lycoris_transformer_blocks_0_attn_to_q.lokr_w1": [16, 16],+ "lycoris_transformer_blocks_0_attn_to_q.lokr_w2": [192, 192],+ "lycoris_transformer_blocks_0_attn_to_v.alpha": [],+ "lycoris_transformer_blocks_0_attn_to_v.lokr_w1": [16, 16],+ "lycoris_transformer_blocks_0_attn_to_v.lokr_w2": [192, 192],+ "lycoris_transformer_blocks_0_img_mlp_net_0_proj.alpha": [],+ "lycoris_transformer_blocks_0_img_mlp_net_0_proj.lokr_w1": [16, 16],+ "lycoris_transformer_blocks_0_img_mlp_net_0_proj.lokr_w2": [768, 192],+ "lycoris_transformer_blocks_0_img_mlp_net_2.alpha": [],+ "lycoris_transformer_blocks_0_img_mlp_net_2.lokr_w1": [16, 16],+ "lycoris_transformer_blocks_0_img_mlp_net_2.lokr_w2": [192, 768],+ "lycoris_transformer_blocks_0_txt_mlp_net_0_proj.alpha": [],+ "lycoris_transformer_blocks_0_txt_mlp_net_0_proj.lokr_w1": [16, 16],+ "lycoris_transformer_blocks_0_txt_mlp_net_0_proj.lokr_w2": [768, 192],+ "lycoris_transformer_blocks_0_txt_mlp_net_2.alpha": [],+ "lycoris_transformer_blocks_0_txt_mlp_net_2.lokr_w1": [16, 16],+ "lycoris_transformer_blocks_0_txt_mlp_net_2.lokr_w2": [192, 768],+}diff --git a/tests/backend/patches/lora_conversions/test_qwen_image_lora_conversion_utils.py b/tests/backend/patches/lora_conversions/test_qwen_image_lora_conversion_utils.pyindex 13a729ace1..727c8314b2 100644--- a/tests/backend/patches/lora_conversions/test_qwen_image_lora_conversion_utils.py+++ b/tests/backend/patches/lora_conversions/test_qwen_image_lora_conversion_utils.py@@ -2,11 +2,15 @@import logging+import accelerateimport pytestimport torch+from diffusers.models.transformers.transformer_qwenimage import QwenImageTransformer2DModelfrom transformers import Qwen2_5_VLConfig, Qwen2_5_VLForConditionalGenerationfrom invokeai.backend.patches.layer_patcher import LayerPatcher+from invokeai.backend.patches.layers.loha_layer import LoHALayer+from invokeai.backend.patches.layers.lokr_layer import LoKRLayerfrom invokeai.backend.patches.lora_conversions.qwen_image_lora_constants import (QWEN_IMAGE_EDIT_LORA_TRANSFORMER_PREFIX,QWEN_IMAGE_LORA_QWEN_VL_PREFIX,@@ -16,6 +20,9 @@ from invokeai.backend.patches.lora_conversions.qwen_image_lora_conversion_utilsis_state_dict_likely_kohya_qwen_image,lora_model_from_qwen_image_state_dict,)+from tests.backend.patches.lora_conversions.lora_state_dicts.qwen_image_lora_aitoolkit_loha_format import (+ state_dict_keys as aitoolkit_loha_state_dict_keys,+)from tests.backend.patches.lora_conversions.lora_state_dicts.qwen_image_lora_diffusers_format import (state_dict_keys as diffusers_state_dict_keys,)@@ -25,6 +32,9 @@ from tests.backend.patches.lora_conversions.lora_state_dicts.qwen_image_lora_kohfrom tests.backend.patches.lora_conversions.lora_state_dicts.qwen_image_lora_kohya_with_te_format import (state_dict_keys as kohya_with_te_state_dict_keys,)+from tests.backend.patches.lora_conversions.lora_state_dicts.qwen_image_lora_lycoris_lokr_format import (+ state_dict_keys as lycoris_lokr_state_dict_keys,+)from tests.backend.patches.lora_conversions.lora_state_dicts.utils import keys_to_mock_state_dict# ---- Format detection tests ----@@ -177,6 +187,204 @@ def test_peft_dora_magnitude_is_kept_as_a_dora_layer():assert torch.equal(layer.dora_scale, magnitude)+# ---- LyCORIS layouts: lycoris_ / ai-toolkit's lora_transformer_ prefixes, dotted LoKr/LoHa, scalar ----++_ATTENTION_MODULES = (+ "attn.add_k_proj",+ "attn.add_q_proj",+ "attn.add_v_proj",+ "attn.to_add_out",+ "attn.to_k",+ "attn.to_out.0",+ "attn.to_q",+ "attn.to_v",+)+_MLP_MODULES = ("img_mlp.net.0.proj", "img_mlp.net.2", "txt_mlp.net.0.proj", "txt_mlp.net.2")++[email protected](scope="module")+def tiny_transformer() -> QwenImageTransformer2DModel:+ with accelerate.init_empty_weights():+ return QwenImageTransformer2DModel(+ patch_size=2,+ in_channels=64,+ out_channels=16,+ num_layers=1,+ attention_head_dim=8,+ num_attention_heads=2,+ joint_attention_dim=8,+ axes_dims_rope=(2, 4, 2),+ )+++def _layer_keys(*modules: str) -> set[str]:+ return {f"{QWEN_IMAGE_EDIT_LORA_TRANSFORMER_PREFIX}transformer_blocks.0.{m}" for m in modules}+++def _assert_layers_address_the_transformer(model, transformer: QwenImageTransformer2DModel) -> None:+ for key in model.layers:+ module = transformer.get_submodule(key.removeprefix(QWEN_IMAGE_EDIT_LORA_TRANSFORMER_PREFIX))+ assert isinstance(module, torch.nn.Linear)+++def test_lycoris_prefixed_lokr_converts_to_transformer_modules(tiny_transformer):+ """A trained `lycoris_transformer_blocks_` LoKr has no modulation layers; every other module maps."""+ model = lora_model_from_qwen_image_state_dict(keys_to_mock_state_dict(lycoris_lokr_state_dict_keys))++ assert set(model.layers) == _layer_keys(*_ATTENTION_MODULES, *_MLP_MODULES)+ _assert_layers_address_the_transformer(model, tiny_transformer)+++def test_lora_transformer_prefixed_loha_converts_to_transformer_modules(tiny_transformer):+ """ai-toolkit's `lora_transformer_transformer_blocks_` spelling, with its modulation layers, maps too. The file+ carries DoRA magnitudes (`dora_scale`) beside every LoHa factor, so this also covers that they don't turn a+ layer into a DoRA layer that has no `lora_up.weight` to read."""+ model = lora_model_from_qwen_image_state_dict(keys_to_mock_state_dict(aitoolkit_loha_state_dict_keys))++ assert set(model.layers) == _layer_keys(*_ATTENTION_MODULES, *_MLP_MODULES, "img_mod.1", "txt_mod.1")+ assert all(isinstance(layer, LoHALayer) for layer in model.layers.values())+ _assert_layers_address_the_transformer(model, tiny_transformer)++[email protected]("prefix", ["transformer.", "diffusion_model.", "base_model.model."])+def test_dotted_lokr_groups_by_full_module_path(prefix: str):+ """Dotted LoKr keys group per module: cutting at the last two dots merged every projection of a block."""+ state_dict = {}+ for module in ("attn.to_q", "attn.to_k"):+ state_dict[f"{prefix}transformer_blocks.0.{module}.lokr_w1"] = torch.zeros(4, 4)+ state_dict[f"{prefix}transformer_blocks.0.{module}.lokr_w2_a"] = torch.zeros(8, 2)+ state_dict[f"{prefix}transformer_blocks.0.{module}.lokr_w2_b"] = torch.zeros(2, 8)++ model = lora_model_from_qwen_image_state_dict(state_dict)++ assert set(model.layers) == _layer_keys("attn.to_q", "attn.to_k")+++def test_dotted_loha_groups_by_full_module_path():+ state_dict = {}+ for module in ("attn.to_q", "attn.to_out.0"):+ for param in ("hada_w1_a", "hada_w2_a"):+ state_dict[f"transformer.transformer_blocks.0.{module}.{param}"] = torch.zeros(32, 4)+ for param in ("hada_w1_b", "hada_w2_b"):+ state_dict[f"transformer.transformer_blocks.0.{module}.{param}"] = torch.zeros(4, 32)++ model = lora_model_from_qwen_image_state_dict(state_dict)++ assert set(model.layers) == _layer_keys("attn.to_q", "attn.to_out.0")++[email protected]("factors", ["loha", "lokr"])+def test_dotted_lycoris_dora_magnitude_is_skipped(factors: str):+ """A dotted LoHa or LoKr with `dora_scale` applies as the plain LoHa or LoKr: the magnitude is not supported on+ these layers, and dispatching it as DoRA failed at generation with `KeyError('lora_up.weight')`."""+ generator = torch.Generator().manual_seed(3)+ prefix = "transformer.transformer_blocks.0.attn.to_q"+ if factors == "loha":+ layer_class = LoHALayer+ state_dict = {+ f"{prefix}.hada_w1_a": torch.randn(16, 4, generator=generator),+ f"{prefix}.hada_w1_b": torch.randn(4, 16, generator=generator),+ f"{prefix}.hada_w2_a": torch.randn(16, 4, generator=generator),+ f"{prefix}.hada_w2_b": torch.randn(4, 16, generator=generator),+ }+ expected = (state_dict[f"{prefix}.hada_w1_a"] @ state_dict[f"{prefix}.hada_w1_b"]) * (+ state_dict[f"{prefix}.hada_w2_a"] @ state_dict[f"{prefix}.hada_w2_b"]+ )+ else:+ layer_class = LoKRLayer+ state_dict = {+ f"{prefix}.lokr_w1": torch.randn(4, 4, generator=generator),+ f"{prefix}.lokr_w2": torch.randn(4, 4, generator=generator),+ }+ expected = torch.kron(state_dict[f"{prefix}.lokr_w1"], state_dict[f"{prefix}.lokr_w2"])+ state_dict[f"{prefix}.dora_scale"] = torch.full((1, 16), 3.0)++ model = lora_model_from_qwen_image_state_dict(state_dict)++ (layer,) = model.layers.values()+ assert isinstance(layer, layer_class)+ delta = layer.get_parameters({"weight": torch.zeros(16, 16)}, weight=1.0)["weight"]+ assert torch.allclose(delta, expected, atol=1e-4)+++ "prefix", ["lycoris_transformer_blocks_0_attn_to_q", "transformer.transformer_blocks.0.attn.to_q"]+)[email protected]("factorized", [False, True])+def test_lokr_scalar_scales_the_update(prefix: str, factorized: bool):+ """LyCORIS multiplies a LoKr's whole update by its learned `scalar`; the layer must apply the same delta."""+ generator = torch.Generator().manual_seed(0)+ w1 = torch.randn(4, 4, generator=generator)+ w2 = torch.randn(4, 4, generator=generator)+ scalar = torch.tensor(0.25)+ state_dict = {f"{prefix}.scalar": scalar, f"{prefix}.alpha": torch.tensor(8.0)}+ if factorized:+ w1_a, w1_b = torch.randn(4, 2, generator=generator), torch.randn(2, 4, generator=generator)+ w1 = w1_a @ w1_b+ state_dict[f"{prefix}.lokr_w1_a"] = w1_a+ state_dict[f"{prefix}.lokr_w1_b"] = w1_b+ else:+ state_dict[f"{prefix}.lokr_w1"] = w1+ state_dict[f"{prefix}.lokr_w2"] = w2++ model = lora_model_from_qwen_image_state_dict(state_dict)++ (layer,) = model.layers.values()+ delta = layer.get_parameters({"weight": torch.zeros(16, 16)}, weight=1.0)["weight"]+ # LyCORIS scales by alpha / rank, and a LoKr with whole factors has no rank (scale 1); w1_b's rows are the rank.+ lycoris_scale = 8.0 / 2 if factorized else 1.0+ assert torch.allclose(delta, torch.kron(w1, w2) * lycoris_scale * 0.25, atol=1e-5)+++def test_loha_scalar_scales_the_update():+ generator = torch.Generator().manual_seed(1)+ w1_a, w2_a = torch.randn(16, 4, generator=generator), torch.randn(16, 4, generator=generator)+ w1_b, w2_b = torch.randn(4, 16, generator=generator), torch.randn(4, 16, generator=generator)+ prefix = "lora_transformer_transformer_blocks_0_attn_to_q"+ state_dict = {+ f"{prefix}.hada_w1_a": w1_a,+ f"{prefix}.hada_w1_b": w1_b,+ f"{prefix}.hada_w2_a": w2_a,+ f"{prefix}.hada_w2_b": w2_b,+ f"{prefix}.alpha": torch.tensor(2.0),+ f"{prefix}.scalar": torch.tensor(-0.5),+ }++ model = lora_model_from_qwen_image_state_dict(state_dict)++ (layer,) = model.layers.values()+ delta = layer.get_parameters({"weight": torch.zeros(16, 16)}, weight=1.0)["weight"]+ # LyCORIS: ((w1_a @ w1_b) * (w2_a @ w2_b)) * (alpha / rank) * scalar+ assert torch.allclose(delta, (w1_a @ w1_b) * (w2_a @ w2_b) * (2.0 / 4) * -0.5, atol=1e-4)+++ ("prefix", "form"),+ [+ ("lycoris_transformer_blocks_0_attn_to_q", "lora_down_up"),+ ("transformer.transformer_blocks.0.attn.to_q", "lora_down_up"),+ ("transformer.transformer_blocks.0.attn.to_q", "lora_A_B"),+ ],+)+def test_lora_scalar_scales_the_update(prefix: str, form: str):+ """LyCORIS folds `scalar` into its weights on save, but raw writers such as ai-toolkit keep the key; the update+ is multiplied by it."""+ generator = torch.Generator().manual_seed(2)+ down, up = torch.randn(4, 16, generator=generator), torch.randn(16, 4, generator=generator)+ names = ("lora_down.weight", "lora_up.weight") if form == "lora_down_up" else ("lora_A.weight", "lora_B.weight")+ state_dict = {+ f"{prefix}.{names[0]}": down,+ f"{prefix}.{names[1]}": up,+ f"{prefix}.scalar": torch.tensor(0.01),+ }++ model = lora_model_from_qwen_image_state_dict(state_dict)++ (layer,) = model.layers.values()+ delta = layer.get_parameters({"weight": torch.zeros(16, 16)}, weight=1.0)["weight"]+ assert torch.allclose(delta, (up @ down) * 0.01, atol=1e-6)++# ---- Text encoder layers ----