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 map Diffusers Anima LoRAs (#10076)
Guishi Wang52e80304e121
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 2fdcda6b78..72972c8140 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@@ -142,7 +142,7 @@ themselves.| 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, 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 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) | ✗ | || LTX-2, MiniMax H3 | ✓ (plain low-rank; LoKR, LoHA and DoRA are refused) | ✗ | || SD 3, CogView4, Ideogram 4, ERNIE-Image, MOSS-Image | ✗ | ✗ | |diff --git a/docs/src/content/docs/Users Guide/03.Models/Local Models/anima.mdx b/docs/src/content/docs/Users Guide/03.Models/Local Models/anima.mdxindex 5c25fa3d36..d37cc77d49 100644--- a/docs/src/content/docs/Users Guide/03.Models/Local Models/anima.mdx+++ b/docs/src/content/docs/Users Guide/03.Models/Local Models/anima.mdx@@ -145,7 +145,7 @@ Anima** accepts a collection of conditionings for its positive and negative inpu## LoRA-Anima LoRAs (Kohya / LyCORIS format) are supported. They apply to the transformer and, where the LoRA+Anima LoRAs in Kohya / LyCORIS and Diffusers PEFT formats are supported. They apply to the transformer and, where the LoRAincludes text-encoder layers, to the Qwen3 encoder. In the workflow editor use **Apply LoRA - Anima** or**Apply LoRA Collection - Anima**.diff --git a/invokeai/backend/model_manager/configs/lora.py b/invokeai/backend/model_manager/configs/lora.pyindex 960826a8ac..f81195acbf 100644--- a/invokeai/backend/model_manager/configs/lora.py+++ b/invokeai/backend/model_manager/configs/lora.py@@ -904,6 +904,8 @@ class LoRA_LyCORIS_QwenImage_Config(LoRA_LyCORIS_Config_Base, Config_Base):# Krea-2 LoRAs also carry transformer.transformer_blocks. keys, but uniquely include the# text-fusion stage. Exclude them here so they route to LoRA_LyCORIS_Krea2_Config.has_krea2_keys = _has_krea2_lora_keys(state_dict)+ str_keys = [key for key in state_dict if isinstance(key, str)]+ has_anima_keys = has_cosmos_dit_peft_keys_strict(str_keys)has_flux_keys = state_dict_has_any_keys_starting_with(state_dict,{@@ -922,6 +924,7 @@ class LoRA_LyCORIS_QwenImage_Config(LoRA_LyCORIS_Config_Base, Config_Base):and has_lora_suffixand not has_z_image_keysand not has_krea2_keys+ and not has_anima_keysand not has_flux_keysand not _has_qwen_image21_lora_keys(state_dict)and not _has_ltx2_lora_keys(state_dict)@@ -939,6 +942,8 @@ class LoRA_LyCORIS_QwenImage_Config(LoRA_LyCORIS_Config_Base, Config_Base):)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)]+ has_anima_keys = has_cosmos_dit_peft_keys_strict(str_keys)has_flux_keys = state_dict_has_any_keys_starting_with(state_dict,{@@ -956,6 +961,7 @@ class LoRA_LyCORIS_QwenImage_Config(LoRA_LyCORIS_Config_Base, Config_Base):has_qwen_ie_keysand not has_z_image_keysand not has_krea2_keys+ and not has_anima_keysand not has_flux_keysand not _has_qwen_image21_lora_keys(state_dict)and not _has_ltx2_lora_keys(state_dict)@@ -1324,7 +1330,7 @@ class LoRA_LyCORIS_Anima_Config(LoRA_LyCORIS_Config_Base, Config_Base):},)- if has_cosmos_keys and has_lora_suffix:+ if has_cosmos_keys and has_lora_suffix and not has_ltx2_lora_keys(str_keys):returnraise NotAMatchError("model does not match Anima LoRA heuristics")@@ -1340,7 +1346,9 @@ class LoRA_LyCORIS_Anima_Config(LoRA_LyCORIS_Config_Base, Config_Base):state_dict = mod.load_state_dict()str_keys = [k for k in state_dict.keys() if isinstance(k, str)]- if has_cosmos_dit_kohya_keys_strict(str_keys) or has_cosmos_dit_peft_keys_strict(str_keys):+ if (+ has_cosmos_dit_kohya_keys_strict(str_keys) or has_cosmos_dit_peft_keys_strict(str_keys)+ ) and not has_ltx2_lora_keys(str_keys):return BaseModelType.Animaraise NotAMatchError("model does not look like an Anima LoRA")diff --git a/invokeai/backend/patches/lora_conversions/anima_lora_constants.py b/invokeai/backend/patches/lora_conversions/anima_lora_constants.pyindex c1c786181d..a22d125371 100644--- a/invokeai/backend/patches/lora_conversions/anima_lora_constants.py+++ b/invokeai/backend/patches/lora_conversions/anima_lora_constants.py@@ -31,6 +31,14 @@ _PEFT_ANIMA_RE = re.compile(r"(diffusion_model|transformer|base_model\.model\.transformer)\.blocks\.\d+\." + _COSMOS_DIT_SUBCOMPONENTS_RE)+# Diffusers' ``CosmosTransformer3DModel`` uses ``transformer_blocks.N.attn1`` / ``attn2`` where Anima's native+# module uses ``blocks.N.self_attn`` / ``cross_attn``. These names are distinct from Qwen-Image's+# ``transformer_blocks.N.attn`` and Wan's ``blocks.N.attn1`` layouts. ``ff.net`` is not a signature because FLUX+# uses the same path; it is converted only after another layer has identified the file as Anima.+_DIFFUSERS_ANIMA_RE = re.compile(+ r"^(?:transformer\.|base_model\.model\.(?:transformer\.)?)?transformer_blocks\.\d+\.(?:attn1|attn2)\."+)+# Subcomponents *uniquely* identifying Anima/Cosmos DiT: the DiT block MLP (``mlp.layer_0`` / ``mlp_layer1``)# and ``adaln_modulation`` (Wan calls those ``ffn`` and ``modulation`` respectively), plus the Cosmos@@ -70,7 +78,7 @@ def has_cosmos_dit_kohya_keys(str_keys: list[str]) -> bool:def has_cosmos_dit_peft_keys(str_keys: list[str]) -> bool:"""Loose PEFT-format detector — see ``has_cosmos_dit_kohya_keys`` docstring."""- return any(_PEFT_ANIMA_RE.search(k) is not None for k in str_keys)+ return any(_PEFT_ANIMA_RE.search(k) is not None or _DIFFUSERS_ANIMA_RE.search(k) is not None for k in str_keys)def has_cosmos_dit_kohya_keys_strict(str_keys: list[str]) -> bool:@@ -84,4 +92,6 @@ def has_cosmos_dit_kohya_keys_strict(str_keys: list[str]) -> bool:def has_cosmos_dit_peft_keys_strict(str_keys: list[str]) -> bool:"""Strict PEFT detector. See ``has_cosmos_dit_kohya_keys_strict`` docstring."""- return any(_PEFT_ANIMA_STRICT_RE.search(k) is not None for k in str_keys)+ return any(+ _PEFT_ANIMA_STRICT_RE.search(k) is not None or _DIFFUSERS_ANIMA_RE.search(k) is not None for k in str_keys+ )diff --git a/invokeai/backend/patches/lora_conversions/anima_lora_conversion_utils.py b/invokeai/backend/patches/lora_conversions/anima_lora_conversion_utils.pyindex eb57643520..e9abe5980b 100644--- a/invokeai/backend/patches/lora_conversions/anima_lora_conversion_utils.py+++ b/invokeai/backend/patches/lora_conversions/anima_lora_conversion_utils.py@@ -185,6 +185,48 @@ _PEFT_EXTRA_SUFFIXES = []+_DIFFUSERS_NON_BLOCK_KEY_MAP = {+ "patch_embed.proj": "x_embedder.proj.1",+ "time_embed.t_embedder.linear_1": "t_embedder.1.linear_1",+ "time_embed.t_embedder.linear_2": "t_embedder.1.linear_2",+ "norm_out.linear_1": "final_layer.adaln_modulation.1",+ "norm_out.linear_2": "final_layer.adaln_modulation.2",+ "proj_out": "final_layer.linear",+}++_DIFFUSERS_BLOCK_KEY_MAP = {+ "attn1.to_q": "self_attn.q_proj",+ "attn1.to_k": "self_attn.k_proj",+ "attn1.to_v": "self_attn.v_proj",+ "attn1.to_out.0": "self_attn.output_proj",+ "attn2.to_q": "cross_attn.q_proj",+ "attn2.to_k": "cross_attn.k_proj",+ "attn2.to_v": "cross_attn.v_proj",+ "attn2.to_out.0": "cross_attn.output_proj",+ "ff.net.0.proj": "mlp.layer1",+ "ff.net.2": "mlp.layer2",+ "norm1.linear_1": "adaln_modulation_self_attn.1",+ "norm1.linear_2": "adaln_modulation_self_attn.2",+ "norm2.linear_1": "adaln_modulation_cross_attn.1",+ "norm2.linear_2": "adaln_modulation_cross_attn.2",+ "norm3.linear_1": "adaln_modulation_mlp.1",+ "norm3.linear_2": "adaln_modulation_mlp.2",+}++_DIFFUSERS_BLOCK_KEY_RE = re.compile(r"^transformer_blocks\.(\d+)\.(.+)$")+++def _convert_diffusers_transformer_key(key: str) -> str:+ if mapped := _DIFFUSERS_NON_BLOCK_KEY_MAP.get(key):+ return mapped+ if match := _DIFFUSERS_BLOCK_KEY_RE.match(key):+ block, suffix = match.groups()+ if mapped := _DIFFUSERS_BLOCK_KEY_MAP.get(suffix):+ return f"blocks.{block}.{mapped}"+ raise ValueError(f"Unsupported diffusers Anima LoRA layer: {key}")+ return key++def _group_keys_by_layer(state_dict: Dict[str, torch.Tensor],extra_suffixes: list[str] | None = None,@@ -299,6 +341,7 @@ def lora_model_from_anima_state_dict(state_dict: Dict[str, torch.Tensor], alpha:if not is_text_encoder:for prefix in ["base_model.model.transformer.",+ "base_model.model.","transformer.","diffusion_model.",]:@@ -309,7 +352,7 @@ def lora_model_from_anima_state_dict(state_dict: Dict[str, torch.Tensor], alpha:if is_text_encoder:final_key = f"{ANIMA_LORA_QWEN3_PREFIX}{clean_key}"else:- final_key = f"{ANIMA_LORA_TRANSFORMER_PREFIX}{clean_key}"+ final_key = f"{ANIMA_LORA_TRANSFORMER_PREFIX}{_convert_diffusers_transformer_key(clean_key)}"layer = _make_layer_patch(values)layers[final_key] = layerdiff --git a/tests/backend/model_manager/configs/test_anima_diffusers_lora_config.py b/tests/backend/model_manager/configs/test_anima_diffusers_lora_config.pynew file mode 100644index 0000000000..8ff1fa369b--- /dev/null+++ b/tests/backend/model_manager/configs/test_anima_diffusers_lora_config.py@@ -0,0 +1,73 @@+import pytest+import torch+from safetensors.torch import save_file++import invokeai.backend.model_manager.load # noqa: F401+from invokeai.backend.model_manager.configs.factory import ModelConfigFactory+from invokeai.backend.model_manager.configs.identification_utils import NotAMatchError+from invokeai.backend.model_manager.configs.lora import LoRA_LyCORIS_Anima_Config+from invokeai.backend.model_manager.model_on_disk import ModelOnDisk+from invokeai.backend.model_manager.taxonomy import BaseModelType+++ "model_prefix",+ ["", "transformer.", "base_model.model.", "base_model.model.transformer."],+ ids=["bare", "diffusers", "peft", "peft-transformer"],+)+def test_diffusers_cosmos_lora_identifies_as_anima(tmp_path, model_prefix: str) -> None:+ state_dict: dict[str, torch.Tensor] = {}+ for name in ("attn1.to_q", "attn2.to_k", "ff.net.0.proj"):+ prefix = f"{model_prefix}transformer_blocks.0.{name}"+ state_dict[f"{prefix}.lora_A.weight"] = torch.randn(4, 2048)+ state_dict[f"{prefix}.lora_B.weight"] = torch.randn(2048, 4)++ path = tmp_path / "anima_diffusers_lora.safetensors"+ save_file(state_dict, path)++ config = ModelConfigFactory.from_model_on_disk(path, allow_unknown=False).config++ assert isinstance(config, LoRA_LyCORIS_Anima_Config)+ assert config.base == BaseModelType.Anima+++def test_sd_unet_transformer_block_is_not_identified_as_anima(tmp_path) -> None:+ prefix = "base_model.model.down_blocks.0.attentions.0.transformer_blocks.0.attn1.to_q"+ state_dict = {+ f"{prefix}.lora_A.weight": torch.randn(4, 320),+ f"{prefix}.lora_B.weight": torch.randn(320, 4),+ }++ path = tmp_path / "sd_unet_lora.safetensors"+ save_file(state_dict, path)++ with pytest.raises(NotAMatchError):+ LoRA_LyCORIS_Anima_Config._validate_looks_like_lora(ModelOnDisk(path))+++def test_diffusers_flux_ff_net_is_not_identified_as_anima(tmp_path) -> None:+ prefix = "transformer.transformer_blocks.0.ff.net.0.proj"+ state_dict = {+ f"{prefix}.lora_A.weight": torch.randn(4, 3072),+ f"{prefix}.lora_B.weight": torch.randn(12288, 4),+ }++ path = tmp_path / "flux_diffusers_lora.safetensors"+ save_file(state_dict, path)++ with pytest.raises(NotAMatchError):+ LoRA_LyCORIS_Anima_Config._validate_looks_like_lora(ModelOnDisk(path))+++def test_transformer_prefixed_ltx2_lora_is_not_identified_as_anima(tmp_path) -> None:+ state_dict = {+ "transformer.transformer_blocks.0.attn1.to_q.lora_A.weight": torch.randn(4, 2048),+ "transformer.transformer_blocks.0.attn1.to_q.lora_B.weight": torch.randn(2048, 4),+ "transformer.transformer_blocks.0.audio_attn1.to_q.lora_A.weight": torch.randn(4, 2048),+ "transformer.transformer_blocks.0.audio_attn1.to_q.lora_B.weight": torch.randn(2048, 4),+ }+ path = tmp_path / "ltx2_transformer_prefix.safetensors"+ save_file(state_dict, path)++ with pytest.raises(NotAMatchError):+ LoRA_LyCORIS_Anima_Config._validate_looks_like_lora(ModelOnDisk(path))diff --git a/tests/backend/patches/lora_conversions/test_anima_lora_conversion_utils.py b/tests/backend/patches/lora_conversions/test_anima_lora_conversion_utils.pyindex a204dc076a..7d4b7c1bde 100644--- a/tests/backend/patches/lora_conversions/test_anima_lora_conversion_utils.py+++ b/tests/backend/patches/lora_conversions/test_anima_lora_conversion_utils.py@@ -240,6 +240,59 @@ def test_kohya_non_block_layers_resolve_alongside_blocks_adapter_and_text_encodeassert layer.up.shape == (module.out_features, rank)+def test_diffusers_cosmos_layers_map_to_real_anima_modules():+ source_to_module = {+ "transformer.transformer_blocks.0.attn1.to_q": "blocks.0.self_attn.q_proj",+ "transformer.transformer_blocks.0.attn1.to_out.0": "blocks.0.self_attn.output_proj",+ "transformer.transformer_blocks.0.attn2.to_k": "blocks.0.cross_attn.k_proj",+ "transformer.transformer_blocks.0.attn2.to_out.0": "blocks.0.cross_attn.output_proj",+ "transformer.transformer_blocks.0.ff.net.0.proj": "blocks.0.mlp.layer1",+ "transformer.transformer_blocks.0.ff.net.2": "blocks.0.mlp.layer2",+ "transformer.transformer_blocks.0.norm1.linear_1": "blocks.0.adaln_modulation_self_attn.1",+ "transformer.transformer_blocks.0.norm2.linear_2": "blocks.0.adaln_modulation_cross_attn.2",+ "transformer.transformer_blocks.0.norm3.linear_1": "blocks.0.adaln_modulation_mlp.1",+ "transformer.patch_embed.proj": "x_embedder.proj.1",+ "transformer.time_embed.t_embedder.linear_1": "t_embedder.1.linear_1",+ "transformer.time_embed.t_embedder.linear_2": "t_embedder.1.linear_2",+ "transformer.norm_out.linear_1": "final_layer.adaln_modulation.1",+ "transformer.norm_out.linear_2": "final_layer.adaln_modulation.2",+ "transformer.proj_out": "final_layer.linear",+ }+ with accelerate.init_empty_weights():+ transformer = AnimaTransformer(**{**ANIMA_TRANSFORMER_CONFIG, "num_blocks": 1})++ rank = 4+ state_dict: dict[str, torch.Tensor] = {}+ for source, target in source_to_module.items():+ module = transformer.get_submodule(target)+ assert isinstance(module, torch.nn.Linear)+ state_dict[f"{source}.lora_A.weight"] = torch.empty(rank, module.in_features)+ state_dict[f"{source}.lora_B.weight"] = torch.empty(module.out_features, rank)++ patch = lora_model_from_anima_state_dict(state_dict)++ assert set(patch.layers) == {f"{ANIMA_LORA_TRANSFORMER_PREFIX}{target}" for target in source_to_module.values()}+ for patch_key, layer in patch.layers.items():+ module = transformer.get_submodule(patch_key.removeprefix(ANIMA_LORA_TRANSFORMER_PREFIX))+ assert isinstance(module, torch.nn.Linear)+ assert isinstance(layer, LoRALayer)+ assert layer.down.shape == (rank, module.in_features)+ assert layer.up.shape == (module.out_features, rank)++[email protected]("model_prefix", ["", "base_model.model."], ids=["bare", "peft"])+def test_diffusers_cosmos_prefix_variants_map_to_anima(model_prefix: str):+ source = f"{model_prefix}transformer_blocks.0.attn1.to_q"+ state_dict = {+ f"{source}.lora_A.weight": torch.empty(4, 2048),+ f"{source}.lora_B.weight": torch.empty(2048, 4),+ }++ patch = lora_model_from_anima_state_dict(state_dict)++ assert set(patch.layers) == {f"{ANIMA_LORA_TRANSFORMER_PREFIX}blocks.0.self_attn.q_proj"}++def test_kohya_unet_keys_get_transformer_prefix():"""Test that Kohya unet keys are prefixed with the transformer prefix."""state_dict = keys_to_mock_state_dict(anima_kohya_keys)