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(minimax-h3): adversarial-review findings for Turbo LoRA support
Lincoln Steina83c20f2598d
diff --git a/invokeai/backend/minimax_h3/pruned_adaln_lora.py b/invokeai/backend/minimax_h3/pruned_adaln_lora.pyindex 00cc0c758f..4a36e96849 100644--- a/invokeai/backend/minimax_h3/pruned_adaln_lora.py+++ b/invokeai/backend/minimax_h3/pruned_adaln_lora.py@@ -31,6 +31,7 @@ from typing import Iteratorimport torchfrom invokeai.backend.patches.layers.lora_layer import LoRALayer+from invokeai.backend.util import InvokeAILogger# The silu(t_emb) grid published with the Turbo LoRA's ComfyUI node (Apache 2.0),# pinned to a commit for reproducibility. ~5.5 MB; fetched once via@@ -157,24 +158,36 @@ def apply_minimax_h3_pruned_adaln_lora_patches(return linear_hook+ logger = InvokeAILogger.get_logger(__name__)handles: list[torch.utils.hooks.RemovableHandle] = []try:for layer_path, layer, patch_weight in adaln_patches:if layer.mid is not None or layer.bias is not None:raise ValueError(f"AdaLN LoRA layer {layer_path!r} has unsupported mid/bias tensors.")+ # Architecture mismatches (unresolvable path, wrong dims) warn and skip the layer —+ # the same policy the LayerPatcher applies to backbone layers, so a partially+ # incompatible LoRA degrades identically on both routes instead of hard-failing+ # only when the AdaLN half is the incompatible one.if layer.down.shape[1] != MINIMAX_H3_TIME_EMBED_DIM:- raise ValueError(- f"AdaLN LoRA layer {layer_path!r} expects a {layer.down.shape[1]}-dim input; the "- f"H3 silu(t_emb) space is {MINIMAX_H3_TIME_EMBED_DIM}-dim. This LoRA does not "- "target MiniMax H3's time conditioning."+ logger.warning(+ f"Skipping AdaLN LoRA layer '{layer_path}': it expects a {layer.down.shape[1]}-dim "+ f"input, but the H3 silu(t_emb) space is {MINIMAX_H3_TIME_EMBED_DIM}-dim. This LoRA "+ "may be incompatible with this model architecture.")- linear = transformer.get_submodule(layer_path)+ continue+ try:+ linear = transformer.get_submodule(layer_path)+ except AttributeError:+ logger.warning(f"Failed to find module for AdaLN LoRA layer: {layer_path}")+ continueout_features = getattr(linear, "out_features", None)if out_features is not None and layer.up.shape[0] != out_features:- raise ValueError(- f"AdaLN LoRA layer {layer_path!r} produces {layer.up.shape[0]} outputs but the "- f"target projection has {out_features}."+ logger.warning(+ f"Skipping AdaLN LoRA layer '{layer_path}' due to shape mismatch: the target "+ f"projection has {out_features} outputs, the LoRA produces {layer.up.shape[0]}. "+ "This LoRA may be incompatible with this model architecture.")+ continuehandles.append(linear.register_forward_hook(make_linear_hook(layer_path, _AdalnLoRADelta(layer, patch_weight))))diff --git a/invokeai/backend/model_manager/configs/lora.py b/invokeai/backend/model_manager/configs/lora.pyindex 3b665ce702..c455083f6b 100644--- a/invokeai/backend/model_manager/configs/lora.py+++ b/invokeai/backend/model_manager/configs/lora.py@@ -43,6 +43,7 @@ from invokeai.backend.patches.lora_conversions.flux_control_lora_utils import isfrom invokeai.backend.patches.lora_conversions.minimax_h3_lora_constants import (has_minimax_h3_lora_keys,has_non_minimax_h3_architecture_keys,+ has_unsupported_minimax_h3_lora_variant_keys,)from invokeai.backend.patches.lora_conversions.wan_lora_constants import (detect_wan_lora_variant,@@ -1262,6 +1263,14 @@ class LoRA_LyCORIS_MiniMaxH3_Config(LoRA_LyCORIS_Config_Base, Config_Base):str_keys = [k for k in state_dict.keys() if isinstance(k, str)]has_h3_keys = has_minimax_h3_lora_keys(str_keys)+ # LyCORIS variants (LoKR/LoHA/DoRA) cannot be applied across H3's fused qkv/SwiGLU+ # tensors; admitting them here would only defer the failure to generation time (or,+ # for DoRA's per-output-row magnitudes, silently mis-apply them). Reject at install.+ if has_h3_keys and has_unsupported_minimax_h3_lora_variant_keys(str_keys):+ raise NotAMatchError(+ "MiniMax H3 LoRAs must be plain low-rank (lora_A/lora_B); LoKR/LoHA/DoRA variants "+ "are not supported on H3's fused transformer layers"+ )has_lora_suffix = state_dict_has_any_keys_ending_with(state_dict,{@@ -1269,9 +1278,6 @@ class LoRA_LyCORIS_MiniMaxH3_Config(LoRA_LyCORIS_Config_Base, Config_Base):"lora_B.weight","lora_down.weight","lora_up.weight",- "dora_scale",- ".lokr_w1",- ".lokr_w2",},)@@ -1285,7 +1291,11 @@ class LoRA_LyCORIS_MiniMaxH3_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_minimax_h3_lora_keys(str_keys) and not has_non_minimax_h3_architecture_keys(str_keys):+ if (+ has_minimax_h3_lora_keys(str_keys)+ and not has_non_minimax_h3_architecture_keys(str_keys)+ and not has_unsupported_minimax_h3_lora_variant_keys(str_keys)+ ):return BaseModelType.MiniMaxH3raise NotAMatchError("model does not look like a MiniMax H3 LoRA")diff --git a/invokeai/backend/patches/lora_conversions/minimax_h3_lora_constants.py b/invokeai/backend/patches/lora_conversions/minimax_h3_lora_constants.pyindex 8455de78a7..25d6a52580 100644--- a/invokeai/backend/patches/lora_conversions/minimax_h3_lora_constants.py+++ b/invokeai/backend/patches/lora_conversions/minimax_h3_lora_constants.py@@ -27,8 +27,12 @@ import re# resolve patches against the loaded transformer's parameter paths.MINIMAX_H3_LORA_TRANSFORMER_PREFIX = "lora_transformer-"-# Optional prefixes seen on PEFT-style keys.-_PEFT_PREFIX_RE = r"(?:^|(?:diffusion_model|transformer|base_model\.model\.transformer)\.)"+# Optional prefixes seen on PEFT-style keys. Anchored to the key start so detection admits+# exactly what the converter's single prefix-strip can handle — an unanchored alternative+# would also match nested prefixes like ``diffusion_model.transformer.blocks...``, which the+# probe would then admit but the converter would map onto nonexistent module paths (the LoRA+# would silently apply zero layers).+_PEFT_PREFIX_RE = r"^(?:(?:diffusion_model|transformer|base_model\.model\.transformer)\.)?"# Submodules the H3 transformer exposes for LoRA, in the checkpoint's native naming.# ``attn.qkv_proj`` (a fused projection under a bare ``attn.``) and ``adaln_proj.linear``@@ -54,6 +58,26 @@ _NON_H3_ANTI_RES = (re.compile(r"mlp[\._]layer|adaln_modulation"), # Anima/Cosmos)+# LyCORIS variants the H3 pipeline does NOT support: LoKR/LoHA cannot be row-split across the+# fused qkv/SwiGLU tensors (a Kronecker/Hadamard factorization does not distribute over row+# slices), and DoRA's per-output-row magnitudes would need the same split/swap treatment plus+# original-weight access that the int8 sidecar path cannot provide. Rejecting these at probe+# time turns a would-be generation-time crash (or silent half-swap corruption) into a clear+# install-time "not supported".+_UNSUPPORTED_H3_VARIANT_SUFFIXES = (+ ".lokr_w1",+ ".lokr_w2",+ ".hada_w1_a",+ ".hada_w2_a",+ ".dora_scale",+)+++def has_unsupported_minimax_h3_lora_variant_keys(str_keys: list[str]) -> bool:+ """True if the state dict carries LyCORIS-variant tensors (LoKR/LoHA/DoRA) that the H3+ conversion pipeline cannot apply to the fused transformer layers."""+ return any(k.endswith(suffix) for k in str_keys for suffix in _UNSUPPORTED_H3_VARIANT_SUFFIXES)+def has_minimax_h3_lora_keys(str_keys: list[str]) -> bool:"""PEFT-style keys naming H3-exclusive submodules (fused ``attn.qkv_proj`` ordiff --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 05956d6965..672e37981f 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@@ -37,6 +37,7 @@ from invokeai.backend.patches.lora_conversions.minimax_h3_lora_constants importMINIMAX_H3_LORA_TRANSFORMER_PREFIX,has_minimax_h3_lora_keys,has_non_minimax_h3_architecture_keys,+ has_unsupported_minimax_h3_lora_variant_keys,)from invokeai.backend.patches.model_patch_raw import ModelPatchRaw@@ -90,6 +91,17 @@ def lora_model_from_minimax_h3_state_dict((``transformer_blocks.N.attn.to_q`` etc.) prefixed with``MINIMAX_H3_LORA_TRANSFORMER_PREFIX``."""+ # The probe rejects these at install time; this guard covers state dicts that reach the+ # converter through other paths. LoKR/LoHA factorizations cannot be row-split across the+ # fused qkv/SwiGLU tensors, and DoRA's per-output-row magnitudes would be silently+ # mis-applied by the half-swap below.+ str_keys = [k for k in state_dict.keys() if isinstance(k, str)]+ if has_unsupported_minimax_h3_lora_variant_keys(str_keys):+ raise ValueError(+ "MiniMax H3 LoRAs must be plain low-rank (lora_A/lora_B); LoKR/LoHA/DoRA variants are not "+ "supported on H3's fused transformer layers."+ )+layers: dict[str, BaseLayerPatch] = {}for raw_layer_path, layer_dict in _group_by_layer(state_dict).items():@@ -165,8 +177,6 @@ def _normalize_lora_param_names(layer_dict: dict[str, torch.Tensor], alpha: floavalues["alpha"] = torch.tensor(alpha)if "alpha" in layer_dict:values["alpha"] = layer_dict["alpha"]- if "dora_scale" in layer_dict:- values["dora_scale"] = layer_dict["dora_scale"]return valuesreturn layer_dictdiff --git a/tests/backend/minimax_h3/test_pruned_adaln_lora.py b/tests/backend/minimax_h3/test_pruned_adaln_lora.pyindex e0f0ba8100..4bd9146452 100644--- a/tests/backend/minimax_h3/test_pruned_adaln_lora.py+++ b/tests/backend/minimax_h3/test_pruned_adaln_lora.py@@ -141,28 +141,52 @@ def test_missing_timestep_fails_loudly():transformer(torch.randn(1, CURVE_DIM))-def test_rejects_wrong_input_dim():+def test_architecture_mismatches_warn_and_skip():+ """Wrong input dim, wrong output dim, and unresolvable paths degrade like the+ LayerPatcher's backbone policy (warn + skip), not a hard failure — while compatible+ layers in the same patch list still apply."""transformer = _StubPrunedTransformer()- bad_layer = LoRALayer(+ grid = _make_grid()+ good_layer = _make_lora(seed=40)+ wrong_input = LoRALayer(up=torch.randn(OUT_FEATURES, RANK), mid=None, down=torch.randn(RANK, 64), alpha=None, bias=None)- with pytest.raises(ValueError, match="does not target MiniMax H3"):- with apply_minimax_h3_pruned_adaln_lora_patches(- transformer, [("norm_out.linear", bad_layer, 1.0)], _make_grid()- ):- pass+ wrong_output = LoRALayer(+ up=torch.randn(OUT_FEATURES + 1, RANK),+ mid=None,+ down=torch.randn(RANK, MINIMAX_H3_TIME_EMBED_DIM),+ alpha=None,+ bias=None,+ )++ curve_temb = torch.randn(1, CURVE_DIM)+ timestep = torch.tensor([0.5])+ base_block, base_out = transformer(curve_temb, timestep=timestep)++ patches = [+ ("norm_out.linear", wrong_input, 1.0),+ ("norm_out.linear", wrong_output, 1.0),+ ("transformer_blocks.7.adaln_proj.linear", good_layer, 1.0), # out-of-range block+ ("transformer_blocks.0.adaln_proj.linear", good_layer, 1.0),+ ]+ with apply_minimax_h3_pruned_adaln_lora_patches(transformer, patches, grid):+ got_block, got_out = transformer(curve_temb, timestep=timestep)++ # Only the one compatible layer applied; every mismatch was skipped.+ assert torch.allclose(got_block, base_block + _expected_delta(grid, good_layer, 1.0, timestep), atol=1e-5)+ assert torch.equal(got_out, base_out)-def test_rejects_output_dim_mismatch():+def test_rejects_mid_or_bias_tensors():transformer = _StubPrunedTransformer()bad_layer = LoRALayer(- up=torch.randn(OUT_FEATURES + 1, RANK),+ up=torch.randn(OUT_FEATURES, RANK),mid=None,down=torch.randn(RANK, MINIMAX_H3_TIME_EMBED_DIM),alpha=None,- bias=None,+ bias=torch.randn(OUT_FEATURES),)- with pytest.raises(ValueError, match="produces .* outputs"):+ with pytest.raises(ValueError, match="mid/bias"):with apply_minimax_h3_pruned_adaln_lora_patches(transformer, [("norm_out.linear", bad_layer, 1.0)], _make_grid()):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 717c2ce7a6..c8481978f8 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@@ -142,6 +142,31 @@ def test_h3_probe_requires_lora_suffixes():assert not accepted, f"H3 probe wrongly accepted a non-LoRA state dict: {result}"+def test_h3_probe_rejects_lycoris_variants():+ # LoKR/LoHA/DoRA cannot be applied across H3's fused qkv/SwiGLU tensors — admitting them+ # would install a model that crashes (or silently corrupts) at generation time.+ lokr = {+ "blocks.0.attn.qkv_proj.lokr_w1": torch.zeros(64, 64),+ "blocks.0.attn.qkv_proj.lokr_w2": torch.zeros(252, 84),+ }+ accepted, result = _probe(LoRA_LyCORIS_MiniMaxH3_Config, lokr)+ assert not accepted, f"H3 probe wrongly accepted a LoKR file: {result}"++ dora = _h3_turbo_keys()+ dora["blocks.0.attn.qkv_proj.dora_scale"] = torch.zeros(3 * 5376, 1)+ accepted, result = _probe(LoRA_LyCORIS_MiniMaxH3_Config, dora)+ assert not accepted, f"H3 probe wrongly accepted a DoRA file: {result}"+++def test_h3_probe_rejects_nested_prefixes():+ # A nested prefix (diffusion_model.transformer.blocks...) survives the converter's single+ # prefix-strip as a nonexistent module path — the LoRA would apply zero layers. Detection+ # is anchored so such files are rejected instead of silently no-opping.+ sd = _h3_turbo_keys("diffusion_model.transformer.")+ accepted, result = _probe(LoRA_LyCORIS_MiniMaxH3_Config, sd)+ assert not accepted, f"H3 probe wrongly accepted nested-prefix keys: {result}"++def test_h3_probe_rejects_already_diffusers_keys():# v1 supports the published native layout only; diffusers-style transformer_blocks keys# are deliberately rejected rather than half-converted.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 7130c83f94..ea865f1ad4 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@@ -178,6 +178,22 @@ def test_format_detection():assert not is_state_dict_likely_in_minimax_h3_format(polluted)+def test_rejects_lycoris_variant_tensors():+ # The probe rejects these at install; the converter guard covers other entry paths. Without+ # it, DoRA's per-output-row magnitudes would be silently mis-applied by the SwiGLU half-swap.+ sd = _make_turbo_style_state_dict()+ sd["blocks.0.mlp.fc1.dora_scale"] = torch.zeros(2 * FFN, 1)+ with pytest.raises(ValueError, match="plain low-rank"):+ lora_model_from_minimax_h3_state_dict(sd)+++def test_nested_prefix_is_not_detected():+ # Anchored detection: a nested prefix would survive the single prefix-strip and convert to+ # nonexistent module paths, so it must not be detected as H3 in the first place.+ assert not is_state_dict_likely_in_minimax_h3_format(_make_turbo_style_state_dict("diffusion_model.transformer."))+ assert not is_state_dict_likely_in_minimax_h3_format(_make_turbo_style_state_dict("unet.diffusion_model."))++def test_rejects_malformed_fused_tensors():sd = {"blocks.0.attn.qkv_proj.lora_A.weight": torch.zeros(RANK, HIDDEN),