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
feat(lora): support kohya-format MiniMax H3 LoRAs
Lincoln Stein608b80b8e371
diff --git a/invokeai/backend/model_manager/configs/lora.py b/invokeai/backend/model_manager/configs/lora.pyindex 3f7faf16e6..ac2dae6c98 100644--- a/invokeai/backend/model_manager/configs/lora.py+++ b/invokeai/backend/model_manager/configs/lora.py@@ -1207,10 +1207,11 @@ class LoRA_LyCORIS_Wan_Config(LoRA_LyCORIS_Config_Base, Config_Base):class LoRA_LyCORIS_MiniMaxH3_Config(LoRA_LyCORIS_Config_Base, Config_Base):- """Model config for MiniMax H3 LoRA models in LyCORIS (single-file PEFT) format.+ """Model config for MiniMax H3 LoRA models in LyCORIS (single-file PEFT or kohya) format.H3 LoRAs (e.g. the MiniMax-H3 Turbo step-distillation LoRA) target the- ``MiniMaxH3Transformer3DModel`` in the checkpoint's native single-file layout.+ ``MiniMaxH3Transformer3DModel`` in the checkpoint's native single-file layout,+ with dotted keys or kohya-flattened ``lora_unet_*`` keys.Detection keys on H3-exclusive submodule names (the fused ``attn.qkv_proj``under a bare ``attn.``, and ``adaln_proj.linear``) and rejects any state dictcarrying another architecture's signature — seediff --git a/invokeai/backend/model_manager/load/model_loaders/lora.py b/invokeai/backend/model_manager/load/model_loaders/lora.pyindex f60e96f147..6ab1a6a240 100644--- a/invokeai/backend/model_manager/load/model_loaders/lora.py+++ b/invokeai/backend/model_manager/load/model_loaders/lora.py@@ -191,9 +191,10 @@ class LoRALoader(ModelLoader):# WanTransformer3DModel attention (attn1/attn2) and FFN blocks.model = lora_model_from_wan_state_dict(state_dict=state_dict, alpha=None)elif self._model_base == BaseModelType.MiniMaxH3:- # MiniMax H3 LoRAs use PEFT lora_A/lora_B keys in the checkpoint's native- # single-file layout (fused qkv_proj / SwiGLU fc1, adaln_proj). alpha=None- # -> alpha=rank, matching the published Turbo LoRA's "no extra scaling".+ # MiniMax H3 LoRAs use PEFT lora_A/lora_B or kohya-flattened keys in the+ # checkpoint's native single-file layout (fused qkv_proj / SwiGLU fc1, adaln_proj).+ # alpha=None -> a file's own .alpha tensors, else alpha=rank, matching the+ # published Turbo LoRA's "no extra scaling".model = lora_model_from_minimax_h3_state_dict(state_dict=state_dict, alpha=None)elif self._model_base == BaseModelType.LTX2:# LTX-2 LoRAs use PEFT lora_A/lora_B keys in the official Lightricks single-filediff --git a/invokeai/backend/patches/lora_conversions/kohya_key_utils.py b/invokeai/backend/patches/lora_conversions/kohya_key_utils.pyindex 42e4c9854f..2272a071fa 100644--- a/invokeai/backend/patches/lora_conversions/kohya_key_utils.py+++ b/invokeai/backend/patches/lora_conversions/kohya_key_utils.py@@ -58,6 +58,26 @@ def insert_periods_into_kohya_key(key: str, parsing_tree: ParsingTree) -> str:return ".".join(result_parts)+def kohya_module_path_is_leaf(module_path: str, parsing_tree: ParsingTree) -> bool:+ """True if a dotted module path walks the tree all the way to a leaf.++ ``insert_periods_into_kohya_key`` only rejects *leftover* tokens, so a prefix of a real path (e.g.+ ``blocks.0.attn``) parses cleanly without naming a module. Requiring a leaf rejects those.+ """+ subtree = parsing_tree+ for component in module_path.split("."):+ # Mirror ``insert_periods_into_kohya_key``'s precedence: an exact match wins over the index+ # placeholder. Without that, a numeric component would always be looked up as INDEX_PLACEHOLDER and+ # a tree enumerating the specific indices it accepts (e.g. Krea-2's ``tmlp``) could never reach its leaves.+ if component in subtree:+ subtree = subtree[component]+ elif component.isnumeric() and INDEX_PLACEHOLDER in subtree:+ subtree = subtree[INDEX_PLACEHOLDER]+ else:+ return False+ return not subtree++def generate_kohya_parsing_tree_from_keys(keys: Iterable[str]) -> ParsingTree:"""Generate a parsing tree from a list of keys.diff --git a/invokeai/backend/patches/lora_conversions/krea2_lora_constants.py b/invokeai/backend/patches/lora_conversions/krea2_lora_constants.pyindex 433a4d1242..74473c49b4 100644--- a/invokeai/backend/patches/lora_conversions/krea2_lora_constants.py+++ b/invokeai/backend/patches/lora_conversions/krea2_lora_constants.py@@ -12,6 +12,7 @@ from invokeai.backend.patches.lora_conversions.kohya_key_utils import (INDEX_PLACEHOLDER,ParsingTree,insert_periods_into_kohya_key,+ kohya_module_path_is_leaf,)# Prefix for Krea-2 transformer (Krea2Transformer2DModel) LoRA layers.@@ -61,26 +62,6 @@ _KREA2_NATIVE_KOHYA_PARSING_TREE: ParsingTree = {}-def _kohya_module_path_is_leaf(module_path: str, parsing_tree: ParsingTree) -> bool:- """True if a dotted module path walks the tree all the way to a leaf.-- ``insert_periods_into_kohya_key`` only rejects *leftover* tokens, so a prefix of a real path (e.g.- ``blocks.0.attn``) parses cleanly without naming a module. Requiring a leaf rejects those.- """- subtree = parsing_tree- for component in module_path.split("."):- # Mirror ``insert_periods_into_kohya_key``'s precedence: an exact match wins over the index- # placeholder. Without that, a numeric component would always be looked up as INDEX_PLACEHOLDER and- # a tree enumerating the specific indices it accepts (``tmlp`` below) could never reach its leaves.- if component in subtree:- subtree = subtree[component]- elif component.isnumeric() and INDEX_PLACEHOLDER in subtree:- subtree = subtree[INDEX_PLACEHOLDER]- else:- return False- return not subtree--def unflatten_kohya_krea2_module_path(flat_path: str) -> str | None:"""Reconstruct a dotted native Krea-2 module path from its kohya-flattened form.@@ -92,7 +73,7 @@ def unflatten_kohya_krea2_module_path(flat_path: str) -> str | None:except ValueError:# Tokens left over: not a native Krea-2 module path.return None- return module_path if _kohya_module_path_is_leaf(module_path, _KREA2_NATIVE_KOHYA_PARSING_TREE) else None+ return module_path if kohya_module_path_is_leaf(module_path, _KREA2_NATIVE_KOHYA_PARSING_TREE) else Nonedef split_kohya_krea2_key(key: str | int) -> tuple[str, str, str] | None:diff --git a/invokeai/backend/patches/lora_conversions/minimax_h3_lora_constants.py b/invokeai/backend/patches/lora_conversions/minimax_h3_lora_constants.pyindex 25d6a52580..b2dc1e3efd 100644--- a/invokeai/backend/patches/lora_conversions/minimax_h3_lora_constants.py+++ b/invokeai/backend/patches/lora_conversions/minimax_h3_lora_constants.py@@ -16,12 +16,24 @@# ComfyUI users sometimes re-key these with a ``diffusion_model.`` prefix; a bare# ``transformer.`` / ``base_model.model.transformer.`` PEFT prefix is also accepted.#+# LoRAs trained with kohya sd-scripts / musubi-tuner flatten the same module paths and+# carry ``.alpha`` tensors (e.g. ``lora_unet_blocks_0_attn_qkv_proj.lora_down.weight``).+# ``normalize_minimax_h3_lora_key`` rewrites those to the dotted native layout so that+# detection and conversion only ever see one spelling.+## The detection helpers below are shared with ``configs/lora.py`` so the probe and# the conversion code agree on what counts as an H3 LoRA. They keep this file# circular-import-free.import re+from invokeai.backend.patches.lora_conversions.kohya_key_utils import (+ INDEX_PLACEHOLDER,+ ParsingTree,+ insert_periods_into_kohya_key,+ kohya_module_path_is_leaf,+)+# Prefix for H3 transformer LoRA layers in the ModelPatchRaw layer dict. Same# convention as Wan / Anima / QwenImage — the LayerPatcher uses this prefix to# resolve patches against the loaded transformer's parameter paths.@@ -48,6 +60,45 @@ _H3_EXCLUSIVE_RE = re.compile()_H3_FINAL_LAYER_RE = re.compile(_PEFT_PREFIX_RE + r"final_layer\.adaln_proj\.linear\.")+MINIMAX_H3_KOHYA_PREFIX = "lora_unet_"++# Native module vocabulary for un-flattening kohya keys. Only Linears with a LoRA conversion+# are leaves, so a flattened path that names anything else fails to reconstruct rather than+# being rewritten into a key that matches no module. Refiner blocks have no ``adaln_proj``.+_H3_KOHYA_BLOCK_SUBTREE: ParsingTree = {+ "attn": {"qkv_proj": {}, "out_proj": {}},+ "mlp": {"fc1": {}, "fc2": {}},+}+_H3_KOHYA_PARSING_TREE: ParsingTree = {+ "blocks": {INDEX_PLACEHOLDER: {**_H3_KOHYA_BLOCK_SUBTREE, "adaln_proj": {"linear": {}}}},+ "token_refiner": {"blocks": {INDEX_PLACEHOLDER: _H3_KOHYA_BLOCK_SUBTREE}},+ "final_layer": {"adaln_proj": {"linear": {}}},+}+++def _unflatten_kohya_minimax_h3_key(key: str) -> str | None:+ """Dotted native key for a kohya-flattened H3 key, or ``None`` if it names no H3 Linear."""+ flat_path, dot, weight_suffix = key[len(MINIMAX_H3_KOHYA_PREFIX) :].partition(".")+ try:+ module_path = insert_periods_into_kohya_key(flat_path, _H3_KOHYA_PARSING_TREE)+ except ValueError:+ return None+ if not kohya_module_path_is_leaf(module_path, _H3_KOHYA_PARSING_TREE):+ return None+ return module_path + dot + weight_suffix+++def normalize_minimax_h3_lora_key(key: str) -> str:+ """Rewrite a kohya-flattened H3 key to the dotted native layout; other keys pass through.++ A ``lora_unet_`` key that does not reconstruct to an H3 Linear is also returned unchanged,+ and ``has_non_minimax_h3_architecture_keys`` treats it as foreign.+ """+ if key.startswith(MINIMAX_H3_KOHYA_PREFIX):+ return _unflatten_kohya_minimax_h3_key(key) or key+ return key++# Any of these indicates a different architecture; an H3 LoRA never carries them._NON_H3_ANTI_RES = (re.compile(r"(self_attn|cross_attn)[\._]"), # Wan / Anima attention naming@@ -80,15 +131,19 @@ def has_unsupported_minimax_h3_lora_variant_keys(str_keys: list[str]) -> bool:def has_minimax_h3_lora_keys(str_keys: list[str]) -> bool:- """PEFT-style keys naming H3-exclusive submodules (fused ``attn.qkv_proj`` or+ """PEFT- or kohya-style keys naming H3-exclusive submodules (fused ``attn.qkv_proj`` or``adaln_proj.linear``) in the checkpoint's native layout."""- return any(_H3_EXCLUSIVE_RE.search(k) or _H3_FINAL_LAYER_RE.search(k) for k in str_keys)+ normalized = (normalize_minimax_h3_lora_key(k) for k in str_keys)+ return any(_H3_EXCLUSIVE_RE.search(k) or _H3_FINAL_LAYER_RE.search(k) for k in normalized)def has_non_minimax_h3_architecture_keys(str_keys: list[str]) -> bool:"""True if any key indicates a non-H3 architecture (Wan, Anima, FLUX, QwenImage, Z-Image).Used as an exclusion guard — an H3 LoRA never carries these patterns, so finding- them is grounds to reject the H3 probe.+ them is grounds to reject the H3 probe. A kohya ``lora_unet_`` key that does not+ reconstruct to an H3 Linear counts too: converting it would patch nothing."""+ if any(k.startswith(MINIMAX_H3_KOHYA_PREFIX) and _unflatten_kohya_minimax_h3_key(k) is None for k in str_keys):+ return Truereturn any(anti.search(k) for k in str_keys for anti in _NON_H3_ANTI_RES)diff --git a/invokeai/backend/patches/lora_conversions/minimax_h3_lora_conversion_utils.py b/invokeai/backend/patches/lora_conversions/minimax_h3_lora_conversion_utils.pyindex 672e37981f..91e317c1d6 100644--- a/invokeai/backend/patches/lora_conversions/minimax_h3_lora_conversion_utils.py+++ b/invokeai/backend/patches/lora_conversions/minimax_h3_lora_conversion_utils.py@@ -1,7 +1,8 @@"""MiniMax H3 LoRA conversion utilities.H3 LoRAs (e.g. larryvrh/MiniMax-H3-Turbo-Lora) target the original remote-code /-Comfy single-file transformer layout. We normalise them to the parameter paths the+Comfy single-file transformer layout, with dotted PEFT keys or kohya-flattened+``lora_unet_*`` keys (un-flattened first). We normalise them to the parameter paths thevendored ``MiniMaxH3Transformer3DModel`` uses at runtime, mirroring the base-modelstate-dict converter in``invokeai.backend.model_manager.load.model_loaders.minimax_h3_state_dict_utils``:@@ -38,6 +39,7 @@ from invokeai.backend.patches.lora_conversions.minimax_h3_lora_constants importhas_minimax_h3_lora_keys,has_non_minimax_h3_architecture_keys,has_unsupported_minimax_h3_lora_variant_keys,+ normalize_minimax_h3_lora_key,)from invokeai.backend.patches.model_patch_raw import ModelPatchRaw@@ -102,6 +104,10 @@ def lora_model_from_minimax_h3_state_dict("supported on H3's fused transformer layers.")+ # Kohya-flattened keys (``lora_unet_blocks_0_attn_qkv_proj.lora_down.weight``) become dotted+ # native keys; their ``lora_down``/``lora_up``/``alpha`` names already match the layer factory.+ state_dict = {normalize_minimax_h3_lora_key(k) if isinstance(k, str) else k: v for k, v in state_dict.items()}+layers: dict[str, BaseLayerPatch] = {}for raw_layer_path, layer_dict in _group_by_layer(state_dict).items():diff --git a/tests/backend/model_manager/configs/test_minimax_h3_lora_probe_independence.py b/tests/backend/model_manager/configs/test_minimax_h3_lora_probe_independence.pyindex d1cd35237d..f29064b7ed 100644--- a/tests/backend/model_manager/configs/test_minimax_h3_lora_probe_independence.py+++ b/tests/backend/model_manager/configs/test_minimax_h3_lora_probe_independence.py@@ -90,6 +90,24 @@ def _h3_turbo_keys(prefix: str = "") -> dict[str, torch.Tensor]:return sd+def _h3_kohya_keys() -> dict[str, torch.Tensor]:+ """Realistic key shape of a kohya / musubi-tuner H3 LoRA (flattened ``lora_unet_`` paths,+ ``lora_down``/``lora_up`` plus ``.alpha``; attention + MLP only)."""+ sd: dict[str, torch.Tensor] = {}+ for block in range(2):+ for module, out_features, in_features in (+ ("attn_qkv_proj", 21504, 5376),+ ("attn_out_proj", 5376, 7168),+ ("mlp_fc1", 28672, 5376),+ ("mlp_fc2", 5376, 14336),+ ):+ base = f"lora_unet_blocks_{block}_{module}"+ sd[f"{base}.lora_down.weight"] = _z(16, in_features)+ sd[f"{base}.lora_up.weight"] = _z(out_features, 16)+ sd[f"{base}.alpha"] = torch.tensor(16.0)+ return sd++def _wan_native_keys() -> dict[str, torch.Tensor]:sd: dict[str, torch.Tensor] = {}for block in range(2):@@ -118,11 +136,17 @@ def test_h3_lora_identifies_as_h3():assert result.base is BaseModelType.MiniMaxH3+def test_h3_kohya_lora_identifies_as_h3():+ accepted, result = _probe(LoRA_LyCORIS_MiniMaxH3_Config, _h3_kohya_keys())+ assert accepted, f"H3 probe rejected the kohya layout: {result}"+ assert result.base is BaseModelType.MiniMaxH3++def test_h3_lora_rejected_by_other_probes():- sd = _h3_turbo_keys()- for cls in (LoRA_LyCORIS_Wan_Config, LoRA_LyCORIS_Anima_Config, LoRA_LyCORIS_Krea2_Config):- accepted, result = _probe(cls, sd)- assert not accepted, f"{cls.__name__} wrongly accepted an H3 LoRA: {result}"+ for sd in (_h3_turbo_keys(), _h3_kohya_keys()):+ for cls in (LoRA_LyCORIS_Wan_Config, LoRA_LyCORIS_Anima_Config, LoRA_LyCORIS_Krea2_Config):+ accepted, result = _probe(cls, sd)+ assert not accepted, f"{cls.__name__} wrongly accepted an H3 LoRA: {result}"def test_wan_lora_rejected_by_h3_probe():diff --git a/tests/backend/patches/lora_conversions/test_minimax_h3_lora_conversion_utils.py b/tests/backend/patches/lora_conversions/test_minimax_h3_lora_conversion_utils.pyindex ea865f1ad4..592ff55475 100644--- a/tests/backend/patches/lora_conversions/test_minimax_h3_lora_conversion_utils.py+++ b/tests/backend/patches/lora_conversions/test_minimax_h3_lora_conversion_utils.py@@ -208,3 +208,50 @@ def test_rejects_malformed_fused_tensors():}with pytest.raises(ValueError, match="odd output row count"):lora_model_from_minimax_h3_state_dict(sd)+++def _to_kohya(sd: dict[str, torch.Tensor], alpha: float, separator: str = "_") -> dict[str, torch.Tensor]:+ """Re-key a dotted turbo-style dict the way kohya sd-scripts / musubi-tuner write it."""+ kohya: dict[str, torch.Tensor] = {}+ for key, value in sd.items():+ module, _, suffix = key.rpartition(".lora_")+ flat = f"lora_unet{separator}{module.replace('.', '_')}"+ kohya[f"{flat}.lora_{suffix.replace('A.', 'down.').replace('B.', 'up.')}"] = value+ kohya[f"{flat}.alpha"] = torch.tensor(alpha)+ return kohya++[email protected]("separator", ["_", "__"])+def test_kohya_keys_convert_like_dotted_keys(separator: str):+ dotted = _make_turbo_style_state_dict()+ kohya = _to_kohya(dotted, alpha=RANK / 2, separator=separator)+ assert is_state_dict_likely_in_minimax_h3_format(kohya)++ expected = lora_model_from_minimax_h3_state_dict(dotted)+ patch = lora_model_from_minimax_h3_state_dict(kohya)++ assert patch.layers.keys() == expected.layers.keys()+ for key, layer in patch.layers.items():+ reference = expected.layers[key]+ assert isinstance(layer, LoRALayer) and isinstance(reference, LoRALayer)+ assert torch.equal(layer.up, reference.up)+ assert torch.equal(layer.down, reference.down)+ assert layer.scale() == pytest.approx(0.5 if layer.down.shape[0] == RANK else RANK / 4)+++def test_kohya_key_naming_no_h3_linear_is_not_detected():+ # A flattened path outside the H3 Linear vocabulary would convert to a module that does not+ # exist (a silent no-op), so one such key disqualifies the whole file.+ kohya = _to_kohya(_make_turbo_style_state_dict(), alpha=RANK)+ kohya["lora_unet_x_embedder_proj.lora_down.weight"] = torch.zeros(RANK, HIDDEN)+ assert not is_state_dict_likely_in_minimax_h3_format(kohya)++ # A parent of real Linears is not itself a Linear.+ kohya = _to_kohya(_make_turbo_style_state_dict(), alpha=RANK)+ kohya["lora_unet_blocks_0_attn.lora_down.weight"] = torch.zeros(RANK, HIDDEN)+ assert not is_state_dict_likely_in_minimax_h3_format(kohya)++ # Refiner blocks have no AdaLN projection.+ kohya = _to_kohya(_make_turbo_style_state_dict(), alpha=RANK)+ kohya["lora_unet_token_refiner_blocks_0_adaln_proj_linear.lora_down.weight"] = torch.zeros(RANK, TIME_EMBED)+ assert not is_state_dict_likely_in_minimax_h3_format(kohya)