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): map Anima kohya non-block layers (#10059)
Guishi Wang596675da55ac
diff --git a/invokeai/backend/patches/lora_conversions/anima_lora_conversion_utils.py b/invokeai/backend/patches/lora_conversions/anima_lora_conversion_utils.pyindex 1707a2a212..eb57643520 100644--- a/invokeai/backend/patches/lora_conversions/anima_lora_conversion_utils.py+++ b/invokeai/backend/patches/lora_conversions/anima_lora_conversion_utils.py@@ -65,6 +65,18 @@ _KOHYA_UNET_KEY_REPLACEMENTS = [("mlp_layer2", "mlp.layer2"),]+# Anima's six trainable linear modules outside the DiT and LLM-adapter blocks. These need exact+# mappings because their leaf names contain underscores (for example ``linear_1``), so they cannot+# be recovered safely by splitting every underscore into a period.+_KOHYA_UNET_NON_BLOCK_KEY_MAP = {+ "final_layer_linear": "final_layer.linear",+ "final_layer_adaln_modulation_1": "final_layer.adaln_modulation.1",+ "final_layer_adaln_modulation_2": "final_layer.adaln_modulation.2",+ "t_embedder_1_linear_1": "t_embedder.1.linear_1",+ "t_embedder_1_linear_2": "t_embedder.1.linear_2",+ "x_embedder_proj_1": "x_embedder.proj.1",+}+# Mapping for Qwen3 text encoder Kohya keys._KOHYA_TE_KEY_REPLACEMENTS = [("self_attn_k_proj", "self_attn.k_proj"),@@ -82,11 +94,15 @@ def _convert_kohya_unet_key(kohya_layer_name: str) -> str:Example: lora_unet_blocks_0_cross_attn_k_proj -> blocks.0.cross_attn.k_projExample: lora_unet_llm_adapter_blocks_0_cross_attn_k_proj -> llm_adapter.blocks.0.cross_attn.k_proj+ Example: lora_unet_final_layer_linear -> final_layer.linear"""key = kohya_layer_nameif key.startswith("lora_unet_"):key = key[len("lora_unet_") :]+ if non_block_key := _KOHYA_UNET_NON_BLOCK_KEY_MAP.get(key):+ return non_block_key+# Handle llm_adapter prefix: strip it, run the standard block conversion, then re-add with dotllm_adapter_prefix = ""if key.startswith("llm_adapter_"):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 3bdfd6771d..a204dc076a 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@@ -1,6 +1,10 @@+import accelerateimport pytestimport torch+from invokeai.backend.anima.anima_transformer import AnimaTransformer+from invokeai.backend.anima.checkpoint_layout import ANIMA_TRANSFORMER_CONFIG+from invokeai.backend.patches.layers.lora_layer import LoRALayerfrom invokeai.backend.patches.lora_conversions.anima_lora_constants import (ANIMA_LORA_QWEN3_PREFIX,ANIMA_LORA_TRANSFORMER_PREFIX,@@ -105,6 +109,13 @@ def test_is_state_dict_likely_anima_lora_false_for_random():("lora_unet_blocks_0_adaln_modulation_cross_attn_1", "blocks.0.adaln_modulation_cross_attn.1"),("lora_unet_blocks_0_adaln_modulation_self_attn_1", "blocks.0.adaln_modulation_self_attn.1"),("lora_unet_blocks_0_adaln_modulation_mlp_1", "blocks.0.adaln_modulation_mlp.1"),+ # Non-block transformer modules+ ("lora_unet_final_layer_linear", "final_layer.linear"),+ ("lora_unet_final_layer_adaln_modulation_1", "final_layer.adaln_modulation.1"),+ ("lora_unet_final_layer_adaln_modulation_2", "final_layer.adaln_modulation.2"),+ ("lora_unet_t_embedder_1_linear_1", "t_embedder.1.linear_1"),+ ("lora_unet_t_embedder_1_linear_2", "t_embedder.1.linear_2"),+ ("lora_unet_x_embedder_proj_1", "x_embedder.proj.1"),# LLM Adapter keys("lora_unet_llm_adapter_blocks_0_cross_attn_k_proj", "llm_adapter.blocks.0.cross_attn.k_proj"),("lora_unet_llm_adapter_blocks_0_cross_attn_q_proj", "llm_adapter.blocks.0.cross_attn.q_proj"),@@ -120,6 +131,18 @@ def test_convert_kohya_unet_key(kohya_key: str, expected: str):assert _convert_kohya_unet_key(kohya_key) == expected+ "kohya_key",+ [+ "lora_unet_final_layer_linear_extra",+ "lora_unet_x_embedder_proj_10",+ ],+)+def test_convert_kohya_unet_key_does_not_guess_unknown_non_block_paths(kohya_key: str):+ """Near-matches stay unchanged instead of being mapped to a different real module."""+ assert _convert_kohya_unet_key(kohya_key) == kohya_key.removeprefix("lora_unet_")++@pytest.mark.parametrize(["kohya_key", "expected"],[@@ -157,6 +180,66 @@ def test_lora_model_from_anima_state_dict(sd_keys: dict[str, list[int]]):assert len(lora_model.layers) > 0+def test_kohya_non_block_layers_resolve_alongside_blocks_adapter_and_text_encoder():+ """Converted Kohya paths and weight shapes match the real Anima module graph."""+ non_block_source_to_module = {+ "lora_unet_final_layer_linear": "final_layer.linear",+ "lora_unet_final_layer_adaln_modulation_1": "final_layer.adaln_modulation.1",+ "lora_unet_final_layer_adaln_modulation_2": "final_layer.adaln_modulation.2",+ "lora_unet_t_embedder_1_linear_1": "t_embedder.1.linear_1",+ "lora_unet_t_embedder_1_linear_2": "t_embedder.1.linear_2",+ "lora_unet_x_embedder_proj_1": "x_embedder.proj.1",+ }+ # Keep block and LLM-adapter keys in the same conversion to catch precedence regressions, and retain a text-encoder+ # key to ensure the transformer-only mapping does not affect the separate Qwen route.+ coexisting_source_to_expected = {+ "lora_unet_blocks_0_self_attn_q_proj": f"{ANIMA_LORA_TRANSFORMER_PREFIX}blocks.0.self_attn.q_proj",+ "lora_unet_llm_adapter_blocks_0_cross_attn_k_proj": (+ f"{ANIMA_LORA_TRANSFORMER_PREFIX}llm_adapter.blocks.0.cross_attn.k_proj"+ ),+ "lora_te_layers_0_self_attn_q_proj": f"{ANIMA_LORA_QWEN3_PREFIX}model.layers.0.self_attn.q_proj",+ }++ with accelerate.init_empty_weights():+ transformer = AnimaTransformer(**{**ANIMA_TRANSFORMER_CONFIG, "num_blocks": 1})++ rank = 4+ state_dict: dict[str, torch.Tensor] = {}+ for source_key, module_name in non_block_source_to_module.items():+ module = transformer.get_submodule(module_name)+ assert isinstance(module, torch.nn.Linear), f"{module_name} is not a Linear"+ state_dict[f"{source_key}.lora_down.weight"] = torch.empty(rank, module.in_features)+ state_dict[f"{source_key}.lora_up.weight"] = torch.empty(module.out_features, rank)++ for source_key, patch_key in coexisting_source_to_expected.items():+ if patch_key.startswith(ANIMA_LORA_TRANSFORMER_PREFIX):+ module_name = patch_key.removeprefix(ANIMA_LORA_TRANSFORMER_PREFIX)+ module = transformer.get_submodule(module_name)+ assert isinstance(module, torch.nn.Linear), f"{module_name} is not a Linear"+ in_features, out_features = module.in_features, module.out_features+ else:+ # This test keeps the Qwen key only to pin routing coexistence; its module graph is owned by the encoder.+ in_features = out_features = 8+ state_dict[f"{source_key}.lora_down.weight"] = torch.empty(rank, in_features)+ state_dict[f"{source_key}.lora_up.weight"] = torch.empty(out_features, rank)++ patch = lora_model_from_anima_state_dict(state_dict)++ expected_non_block_keys = {+ f"{ANIMA_LORA_TRANSFORMER_PREFIX}{module_name}" for module_name in non_block_source_to_module.values()+ }+ assert set(patch.layers) == expected_non_block_keys | set(coexisting_source_to_expected.values())++ for patch_key in expected_non_block_keys:+ module_name = patch_key.removeprefix(ANIMA_LORA_TRANSFORMER_PREFIX)+ module = transformer.get_submodule(module_name)+ assert isinstance(module, torch.nn.Linear), f"{module_name} is not a Linear"+ layer = patch.layers[patch_key]+ assert isinstance(layer, LoRALayer)+ assert layer.down.shape == (rank, module.in_features)+ assert layer.up.shape == (module.out_features, rank)++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)