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(lora): identify and apply Qwen-Image LoRAs in ComfyUI and raw PEFT layouts (#10061)
Tanishq907695dd90ba
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 b9cdfe898d..aeeac68f03 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@@ -164,5 +164,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+[family page](/users-guide/models/local-models/qwen-image/#lora).+[PiD decoders](/users-guide/image-generation/advanced-topics/pid-decode/) load for FLUX.1, FLUX.2, SD 3, SDXL andQwen-Image (v1 and v1.5, bf16 and int8 builds). FLUX.3 and MOSS-Image use the FLUX.2 decoders.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 c43eff01ab..6310bc83fa 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@@ -145,6 +145,14 @@ Image**; connect an **Image to Latents - Qwen Image** node to the **Reference LaQwen Image LoRAs (diffusers PEFT, Kohya and LoKR formats) are supported and apply to the transformer.In the workflow editor use **Apply LoRA - Qwen Image** or **Apply LoRA Collection - Qwen Image**.+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+its `adapter_config.json`, which is not read, so an adapter trained with `lora_alpha` different from `r`, or+with rsLoRA, applies at a different strength.+## ControlNetTwo ControlNets are starter models, both a single model for several conditions (~3.5 GB each, Apache 2.0):diff --git a/invokeai/backend/model_manager/configs/lora.py b/invokeai/backend/model_manager/configs/lora.pyindex 331e4b5a15..dbff86ae5c 100644--- a/invokeai/backend/model_manager/configs/lora.py+++ b/invokeai/backend/model_manager/configs/lora.py@@ -866,6 +866,24 @@ class LoRA_LyCORIS_ZImage_Config(LoRA_LyCORIS_Config_Base, Config_Base):raise NotAMatchError("model does not look like a Z-Image LoRA")+# 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.+_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$"+)+++def _has_prefixed_qwen_image_lora_keys(state_dict: dict[str | int, Any]) -> bool:+ keys = [key for key in state_dict if isinstance(key, str)]+ # PEFT DoRA magnitudes are not mapped yet (#9558): the converter would fail on every generation.+ if any(key.endswith(".lora_magnitude_vector") for key in keys):+ return False+ return any(_PREFIXED_QWEN_IMAGE_BLOCK_KEY_RE.match(key) for key in keys)++class LoRA_LyCORIS_QwenImage_Config(LoRA_LyCORIS_Config_Base, Config_Base):"""Model config for Qwen Image Edit LoRA models in LyCORIS format."""@@ -883,7 +901,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)has_lora_suffix = state_dict_has_any_keys_ending_with(state_dict,{@@ -939,7 +957,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)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)]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 7fc01f7231..dc1b57fbb6 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@@ -3,7 +3,7 @@Qwen Image uses QwenImageTransformer2DModel architecture.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+- 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)"""@@ -85,6 +85,7 @@ def lora_model_from_qwen_image_state_dict(Handles three key 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"""is_kohya = is_state_dict_likely_kohya_qwen_image(state_dict)@@ -125,8 +126,8 @@ def _convert_diffusers_format(state_dict: Dict[str, torch.Tensor], alpha: float"""Convert Diffusers/PEFT format state dict."""layers: dict[str, BaseLayerPatch] = {}- # Some LoRAs use a "transformer." prefix on keys- strip_prefixes = ["transformer."]+ # The diffusers (`transformer.`), ComfyUI (`diffusion_model.`) and raw PEFT (`base_model.model.`) key prefixes+ strip_prefixes = ["transformer.", "diffusion_model.", "base_model.model."]grouped = _group_by_layer(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.pynew file mode 100644index 0000000000..03c5531c96--- /dev/null+++ b/tests/backend/model_manager/configs/test_qwen_image_lora_config.py@@ -0,0 +1,168 @@+"""Qwen-Image LoRA identification across the key layouts trainers save.++Most Qwen-Image LoRAs on Hugging Face prefix their keys with ComfyUI's `diffusion_model.`, and raw PEFT adapters+with `base_model.model.`. Other families' LoRAs carry the same prefixes, so a prefixed file is claimed only when+it has low-rank weights on a module that Qwen-Image's dual-stream blocks alone have.+"""++from pathlib import Path+from unittest.mock import MagicMock++import pytest+import torch++from invokeai.backend.model_manager.configs.base import Config_Base+from 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.taxonomy import ModelType++# Every Linear in a Qwen-Image transformer block, with its (in, out) features.+_QWEN_IMAGE_BLOCK_LINEARS = {+ "attn.to_q": (3072, 3072),+ "attn.to_k": (3072, 3072),+ "attn.to_v": (3072, 3072),+ "attn.to_out.0": (3072, 3072),+ "attn.add_q_proj": (3072, 3072),+ "attn.add_k_proj": (3072, 3072),+ "attn.add_v_proj": (3072, 3072),+ "attn.to_add_out": (3072, 3072),+ "img_mod.1": (3072, 18432),+ "img_mlp.net.0.proj": (3072, 12288),+ "img_mlp.net.2": (12288, 3072),+ "txt_mod.1": (3072, 18432),+ "txt_mlp.net.0.proj": (3072, 12288),+ "txt_mlp.net.2": (12288, 3072),+}+++def _z(*shape: int) -> torch.Tensor:+ """A zero tensor of the given shape with a single element of storage: the probes read names and shapes only."""+ return torch.zeros((), dtype=torch.float32).expand(shape)+++def _lora(layers: dict[str, tuple[int, int]]) -> dict[str, torch.Tensor]:+ sd: dict[str, torch.Tensor] = {}+ for layer, (in_features, out_features) in layers.items():+ sd[f"{layer}.lora_A.weight"] = _z(16, in_features)+ sd[f"{layer}.lora_B.weight"] = _z(out_features, 16)+ return sd+++def _qwen_image_lora(prefix: str) -> dict[str, torch.Tensor]:+ return _lora(+ {+ f"{prefix}transformer_blocks.{block}.{module}": features+ for block in range(2)+ for module, features in _QWEN_IMAGE_BLOCK_LINEARS.items()+ }+ )+++def _make_mod(path: Path, sd: dict[str, torch.Tensor]) -> MagicMock:+ path.touch()+ mod = MagicMock()+ mod.path = path+ mod.load_state_dict.return_value = sd+ mod.metadata.return_value = {}+ return mod+++def _overrides(path: Path) -> dict[str, str | int]:+ return {+ "hash": "test-hash",+ "path": str(path),+ "file_size": 0,+ "name": path.stem,+ "source": str(path),+ "source_type": "path",+ }++[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."""+ path = tmp_path / "lora.safetensors"+ mod = _make_mod(path, _qwen_image_lora(prefix))++ accepting = []+ for cls in Config_Base.CONFIG_CLASSES:+ if getattr(cls.model_fields.get("type"), "default", None) is not ModelType.LoRA:+ continue+ try:+ cls.from_model_on_disk(mod, _overrides(path))+ except Exception:+ # As in the model config factory, anything but a returned config is no match.+ continue+ accepting.append(cls.__name__)++ assert accepting == [LoRA_LyCORIS_QwenImage_Config.__name__]+++ "layers",+ [+ pytest.param(+ # FLUX's double blocks in diffusers naming share Qwen-Image's attention projections.+ {+ "base_model.model.transformer_blocks.0.attn.add_k_proj": (3072, 3072),+ "base_model.model.transformer_blocks.0.attn.to_add_out": (3072, 3072),+ "base_model.model.transformer_blocks.0.ff.net.0.proj": (3072, 12288),+ "base_model.model.transformer_blocks.0.norm1.linear": (3072, 18432),+ },+ id="flux-diffusers-naming",+ ),+ pytest.param(+ # FLUX's own naming has `img_mlp` and `img_mod` too, in `double_blocks`.+ {+ "base_model.model.double_blocks.0.img_attn.qkv": (3072, 9216),+ "base_model.model.double_blocks.0.img_mlp.0": (3072, 12288),+ "base_model.model.double_blocks.0.img_mod.lin": (3072, 18432),+ },+ id="flux-bfl-naming",+ ),+ pytest.param(+ # Attention alone names nothing only Qwen-Image has; Krea-2 installs this layout under an explicit base.+ {"diffusion_model.transformer_blocks.0.attn.to_q": (3072, 3072)},+ id="attention-only",+ ),+ pytest.param(+ # Qwen-Image-2.1's blocks name their MLP `img_mlp.proj` / `img_mlp.out`, not `img_mlp.net`.+ {+ "diffusion_model.transformer_blocks.0.img_mlp.proj": (4096, 16384),+ "diffusion_model.transformer_blocks.0.img_mlp.out": (16384, 4096),+ },+ id="qwen-image-2.1-mlp",+ ),+ ],+)+def test_a_prefixed_lora_without_a_qwen_image_only_module_is_not_claimed(+ layers: dict[str, tuple[int, int]], tmp_path: Path+) -> None:+ path = tmp_path / "lora.safetensors"++ with pytest.raises(NotAMatchError):+ LoRA_LyCORIS_QwenImage_Config.from_model_on_disk(_make_mod(path, _lora(layers)), _overrides(path))+++def test_a_prefixed_peft_dora_is_not_claimed(tmp_path: Path) -> None:+ """PEFT DoRA magnitudes are not mapped yet, so claiming the file would install a LoRA that fails to apply."""+ sd = _qwen_image_lora("base_model.model.")+ for key in [key for key in sd if key.endswith(".lora_B.weight")]:+ sd[key.removesuffix(".lora_B.weight") + ".lora_magnitude_vector"] = _z(sd[key].shape[0])+ path = tmp_path / "adapter_model.safetensors"++ with pytest.raises(NotAMatchError):+ 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."""+ 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"++ with pytest.raises(NotAMatchError):+ LoRA_LyCORIS_QwenImage_Config.from_model_on_disk(_make_mod(path, sd), _overrides(path))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 642a20b716..c14257c52f 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@@ -1,5 +1,6 @@"""Tests for Qwen Image LoRA conversion utilities."""+import pytestimport torchfrom invokeai.backend.patches.lora_conversions.qwen_image_lora_constants import (@@ -105,16 +106,17 @@ def test_diffusers_conversion_produces_correct_layer_keys():assert set(model.layers.keys()) == expected_keys-def test_diffusers_with_transformer_prefix_strips_it():- """Diffusers keys with 'transformer.' prefix get it stripped."""[email protected]("prefix", ["transformer.", "diffusion_model.", "base_model.model."])+def test_diffusers_key_prefix_is_stripped(prefix: str):+ """The diffusers (`transformer.`), ComfyUI (`diffusion_model.`) and raw PEFT (`base_model.model.`) prefixes+ are stripped, so the layer names a module of the transformer."""state_dict = {- "transformer.transformer_blocks.0.attn.to_k.lora_down.weight": torch.empty(64, 3072),- "transformer.transformer_blocks.0.attn.to_k.lora_up.weight": torch.empty(3072, 64),+ f"{prefix}transformer_blocks.0.attn.to_k.lora_down.weight": torch.empty(64, 3072),+ f"{prefix}transformer_blocks.0.attn.to_k.lora_up.weight": torch.empty(3072, 64),}model = lora_model_from_qwen_image_state_dict(state_dict, alpha=None)- expected_key = f"{QWEN_IMAGE_EDIT_LORA_TRANSFORMER_PREFIX}transformer_blocks.0.attn.to_k"- assert expected_key in model.layers+ assert set(model.layers) == {f"{QWEN_IMAGE_EDIT_LORA_TRANSFORMER_PREFIX}transformer_blocks.0.attn.to_k"}# ---- Unknown key handling tests ----