Skip to content

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.

fix(lora): reject malformed MiniMax H3 LoRAs at install

Lincoln Steine8b8992c8d58
diff --git a/invokeai/backend/model_manager/configs/lora.py b/invokeai/backend/model_manager/configs/lora.py
index ac2dae6c98..503b3ea7ab 100644
--- a/invokeai/backend/model_manager/configs/lora.py
+++ b/invokeai/backend/model_manager/configs/lora.py
@@ -55,6 +55,7 @@ from invokeai.backend.patches.lora_conversions.ltx2_lora_constants import (
has_unsupported_ltx2_lora_variant_keys,
)
from invokeai.backend.patches.lora_conversions.minimax_h3_lora_constants import (
+ find_minimax_h3_lora_defect,
has_minimax_h3_lora_keys,
has_non_minimax_h3_architecture_keys,
has_unsupported_minimax_h3_lora_variant_keys,
@@ -1226,29 +1227,21 @@ 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)]
- has_h3_keys = has_minimax_h3_lora_keys(str_keys)
+ if not has_minimax_h3_lora_keys(str_keys) or has_non_minimax_h3_architecture_keys(str_keys):
+ raise NotAMatchError("model does not match MiniMax H3 LoRA heuristics")
# 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):
+ if 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,
- {
- "lora_A.weight",
- "lora_B.weight",
- "lora_down.weight",
- "lora_up.weight",
- },
- )
-
- if has_h3_keys and has_lora_suffix and not has_non_minimax_h3_architecture_keys(str_keys):
- return
-
- raise NotAMatchError("model does not match MiniMax H3 LoRA heuristics")
+ # The converter's own rule: every layer one complete low-rank pair, no stray tensors. This
+ # also rejects files without LoRA suffixes (e.g. base-model weights).
+ defect = find_minimax_h3_lora_defect(str_keys)
+ if defect is not None:
+ raise NotAMatchError(f"malformed MiniMax H3 LoRA: {defect}")
@classmethod
def _get_base_or_raise(cls, mod: ModelOnDisk) -> BaseModelType:
@@ -1259,6 +1252,7 @@ class LoRA_LyCORIS_MiniMaxH3_Config(LoRA_LyCORIS_Config_Base, Config_Base):
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)
+ and find_minimax_h3_lora_defect(str_keys) is None
):
return BaseModelType.MiniMaxH3
diff --git a/invokeai/backend/patches/lora_conversions/minimax_h3_lora_constants.py b/invokeai/backend/patches/lora_conversions/minimax_h3_lora_constants.py
index b2dc1e3efd..b8d18f34e7 100644
--- a/invokeai/backend/patches/lora_conversions/minimax_h3_lora_constants.py
+++ b/invokeai/backend/patches/lora_conversions/minimax_h3_lora_constants.py
@@ -26,6 +26,7 @@
# circular-import-free.
import re
+from collections.abc import Iterable
from invokeai.backend.patches.lora_conversions.kohya_key_utils import (
INDEX_PLACEHOLDER,
@@ -114,7 +115,10 @@ _NON_H3_ANTI_RES = (
# 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".
+# install-time "not supported". This list exists for that specific message; the well-formedness
+# rule below (``find_minimax_h3_lora_defect``) rejects them too, along with PEFT DoRA's
+# ``lora_magnitude_vector``: DoRA rescales by the norm of the *original* weight, which neither the
+# int8-convrot sidecar path nor the AdaLN-pruned re-injection (no full-width weight at all) has.
_UNSUPPORTED_H3_VARIANT_SUFFIXES = (
".lokr_w1",
".lokr_w2",
@@ -147,3 +151,56 @@ def has_non_minimax_h3_architecture_keys(str_keys: list[str]) -> bool:
if any(k.startswith(MINIMAX_H3_KOHYA_PREFIX) and _unflatten_kohya_minimax_h3_key(k) is None for k in str_keys):
return True
return any(anti.search(k) for k in str_keys for anti in _NON_H3_ANTI_RES)
+
+
+# The only per-layer tensors an H3 LoRA may carry: one complete low-rank pair in either spelling,
+# each optionally with a kohya ``alpha``.
+_LORA_PARAM_NAMES = ("lora_A.weight", "lora_B.weight", "lora_down.weight", "lora_up.weight", "alpha")
+_VALID_LAYER_PARAM_SETS = (
+ frozenset({"lora_A.weight", "lora_B.weight"}),
+ frozenset({"lora_A.weight", "lora_B.weight", "alpha"}),
+ frozenset({"lora_down.weight", "lora_up.weight"}),
+ frozenset({"lora_down.weight", "lora_up.weight", "alpha"}),
+)
+_PEFT_PREFIX_STRIP_RE = re.compile(_PEFT_PREFIX_RE)
+
+
+def group_minimax_h3_lora_keys(str_keys: Iterable[str]) -> dict[str, dict[str, str]]:
+ """Group raw H3 LoRA keys as ``{layer path: {param name: raw key}}``, or raise ``ValueError``.
+
+ Layer paths are kohya-un-flattened and stripped of the optional PEFT prefix, i.e. what the
+ converter maps onto runtime modules. Raises naming the first defect: a key whose tail is not a
+ LoRA parameter name (DoRA ``lora_magnitude_vector``, full weights, ...), two raw keys naming
+ the same tensor (e.g. a layer present both dotted and kohya-flattened), or a layer whose
+ tensors are not exactly one ``lora_A``/``lora_B`` or ``lora_down``/``lora_up`` pair plus an
+ optional ``alpha``. Converting any of these would crash, or silently drop or overwrite tensors.
+ """
+ grouped: dict[str, dict[str, str]] = {}
+ for raw_key in str_keys:
+ key = _PEFT_PREFIX_STRIP_RE.sub("", normalize_minimax_h3_lora_key(raw_key), count=1)
+ param = next((p for p in _LORA_PARAM_NAMES if key.endswith("." + p)), None)
+ if param is None:
+ raise ValueError(
+ f"unsupported tensor {raw_key!r}: only lora_A/lora_B or lora_down/lora_up pairs with an "
+ "optional alpha are supported (no DoRA, LyCORIS or full-weight tensors)"
+ )
+ layer_params = grouped.setdefault(key[: -len(param) - 1], {})
+ if param in layer_params:
+ raise ValueError(f"{layer_params[param]!r} and {raw_key!r} are the same tensor in two spellings")
+ layer_params[param] = raw_key
+ for layer, layer_params in grouped.items():
+ if frozenset(layer_params) not in _VALID_LAYER_PARAM_SETS:
+ raise ValueError(
+ f"layer {layer!r} carries {sorted(layer_params)}; expected exactly lora_A/lora_B or "
+ "lora_down/lora_up, optionally with alpha"
+ )
+ return grouped
+
+
+def find_minimax_h3_lora_defect(str_keys: Iterable[str]) -> str | None:
+ """Description of the first well-formedness defect (see ``group_minimax_h3_lora_keys``), or None."""
+ try:
+ group_minimax_h3_lora_keys(str_keys)
+ except ValueError as e:
+ return str(e)
+ return None
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.py
index 91e317c1d6..9e984afaa6 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
@@ -36,10 +36,11 @@ from invokeai.backend.patches.layers.base_layer_patch import BaseLayerPatch
from invokeai.backend.patches.layers.utils import any_lora_layer_from_state_dict
from invokeai.backend.patches.lora_conversions.minimax_h3_lora_constants import (
MINIMAX_H3_LORA_TRANSFORMER_PREFIX,
+ find_minimax_h3_lora_defect,
+ group_minimax_h3_lora_keys,
has_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
@@ -55,12 +56,6 @@ def is_minimax_h3_adaln_layer_path(layer_path: str) -> bool:
return layer_path.endswith(MINIMAX_H3_ADALN_LINEAR_SUFFIX) or layer_path == MINIMAX_H3_NORM_OUT_LINEAR_PATH
-_PEFT_PREFIXES_TO_STRIP: tuple[str, ...] = (
- "base_model.model.transformer.",
- "transformer.",
- "diffusion_model.",
-)
-
# Order matters: token_refiner.blocks. must be rewritten before the bare blocks. prefix.
_PREFIX_RENAMES: tuple[tuple[str, str], ...] = (
("token_refiner.blocks.", "token_refiner.refiner_blocks."),
@@ -79,9 +74,13 @@ _SWIGLU_SUFFIX = ".ff.net.0.proj"
def is_state_dict_likely_in_minimax_h3_format(state_dict: Dict[str, torch.Tensor]) -> bool:
- """Heuristic: does this state dict look like a MiniMax H3 LoRA in the native layout?"""
+ """Heuristic: does this state dict look like a well-formed MiniMax H3 LoRA in the native layout?"""
str_keys = [k for k in state_dict.keys() if isinstance(k, str)]
- return has_minimax_h3_lora_keys(str_keys) and not has_non_minimax_h3_architecture_keys(str_keys)
+ return (
+ has_minimax_h3_lora_keys(str_keys)
+ and not has_non_minimax_h3_architecture_keys(str_keys)
+ and find_minimax_h3_lora_defect(str_keys) is None
+ )
def lora_model_from_minimax_h3_state_dict(
@@ -104,15 +103,20 @@ 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()}
+ # Kohya-flattened keys (``lora_unet_blocks_0_attn_qkv_proj.lora_down.weight``) are grouped under
+ # their dotted native layer path, PEFT prefix stripped. A half pair, a layer present in two
+ # spellings, or a tensor that is not a LoRA parameter (e.g. PEFT DoRA's magnitude) raises here,
+ # before anything can be silently dropped or overwritten.
+ try:
+ grouped = group_minimax_h3_lora_keys(str_keys)
+ except ValueError as e:
+ raise ValueError(f"Malformed MiniMax H3 LoRA: {e}") from e
layers: dict[str, BaseLayerPatch] = {}
- for raw_layer_path, layer_dict in _group_by_layer(state_dict).items():
- layer_path = _rename_layer_path(_strip_peft_prefix(raw_layer_path))
- values = _normalize_lora_param_names(layer_dict, alpha)
+ for native_layer_path, param_keys in grouped.items():
+ layer_path = _rename_layer_path(native_layer_path)
+ values = _normalize_lora_param_names({param: state_dict[key] for param, key in param_keys.items()}, alpha)
if layer_path.endswith(_QKV_SUFFIX):
# Fused QKV: row-split lora_up into thirds; lora_down (which acts on the
@@ -120,7 +124,7 @@ def lora_model_from_minimax_h3_state_dict(
up = values["lora_up.weight"]
if up.shape[0] % 3 != 0:
raise ValueError(
- f"Fused-QKV LoRA layer {raw_layer_path!r} has {up.shape[0]} output rows, not divisible by 3"
+ f"Fused-QKV LoRA layer {native_layer_path!r} has {up.shape[0]} output rows, not divisible by 3"
)
rows = up.shape[0] // 3
stem = layer_path[: -len("qkv_proj")]
@@ -139,7 +143,9 @@ def lora_model_from_minimax_h3_state_dict(
# swaps the fused weight (see minimax_h3_state_dict_utils).
up = values["lora_up.weight"]
if up.shape[0] % 2 != 0:
- raise ValueError(f"Fused-SwiGLU LoRA layer {raw_layer_path!r} has odd output row count {up.shape[0]}")
+ raise ValueError(
+ f"Fused-SwiGLU LoRA layer {native_layer_path!r} has odd output row count {up.shape[0]}"
+ )
half = up.shape[0] // 2
values = dict(values)
values["lora_up.weight"] = torch.cat([up[half:], up[:half]], dim=0)
@@ -149,13 +155,6 @@ def lora_model_from_minimax_h3_state_dict(
return ModelPatchRaw(layers=layers)
-def _strip_peft_prefix(layer_path: str) -> str:
- for prefix in _PEFT_PREFIXES_TO_STRIP:
- if layer_path.startswith(prefix):
- return layer_path[len(prefix) :]
- return layer_path
-
-
def _rename_layer_path(layer_path: str) -> str:
for old, new in _PREFIX_RENAMES:
if layer_path.startswith(old):
@@ -169,7 +168,7 @@ def _rename_layer_path(layer_path: str) -> str:
def _normalize_lora_param_names(layer_dict: dict[str, torch.Tensor], alpha: float | None) -> dict[str, torch.Tensor]:
- """Map PEFT-style ``lora_A``/``lora_B`` to ``lora_down``/``lora_up``.
+ """Map PEFT-style ``lora_A``/``lora_B`` to ``lora_down``/``lora_up`` on a well-formed layer.
Kohya-style ``lora_down``/``lora_up`` pass through unchanged. A per-layer
``alpha`` tensor in the file wins over the caller-supplied default.
@@ -185,38 +184,3 @@ def _normalize_lora_param_names(layer_dict: dict[str, torch.Tensor], alpha: floa
values["alpha"] = layer_dict["alpha"]
return values
return layer_dict
-
-
-def _group_by_layer(state_dict: Dict[str, torch.Tensor]) -> dict[str, dict[str, torch.Tensor]]:
- """Group state-dict keys by their layer path (everything before the LoRA-suffix tail)."""
- grouped: dict[str, dict[str, torch.Tensor]] = {}
-
- known_suffixes = [
- ".lora_A.weight",
- ".lora_B.weight",
- ".lora_down.weight",
- ".lora_up.weight",
- ".dora_scale",
- ".alpha",
- ]
-
- for key in state_dict:
- if not isinstance(key, str):
- continue
-
- layer_name = None
- key_name = None
- for suffix in known_suffixes:
- if key.endswith(suffix):
- layer_name = key[: -len(suffix)]
- key_name = suffix[1:] # drop leading dot
- break
-
- if layer_name is None:
- parts = key.rsplit(".", maxsplit=2)
- layer_name = parts[0]
- key_name = ".".join(parts[1:])
-
- grouped.setdefault(layer_name, {})[key_name] = state_dict[key]
-
- return grouped
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.py
index f29064b7ed..42e1f2fa21 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
@@ -13,6 +13,7 @@ from pathlib import Path
from tempfile import TemporaryDirectory
from unittest.mock import MagicMock
+import pytest
import torch
from invokeai.backend.model_manager.configs.identification_utils import NotAMatchError
@@ -129,11 +130,17 @@ def _anima_kohya_keys() -> dict[str, torch.Tensor]:
return sd
-def test_h3_lora_identifies_as_h3():
- for prefix in ("", "diffusion_model."):
- accepted, result = _probe(LoRA_LyCORIS_MiniMaxH3_Config, _h3_turbo_keys(prefix))
- assert accepted, f"H3 probe rejected its own layout (prefix={prefix!r}): {result}"
- assert result.base is BaseModelType.MiniMaxH3
[email protected]("prefix", ["", "diffusion_model."])
[email protected]("with_alpha", [False, True], ids=["no-alpha", "per-layer-alpha"])
+def test_h3_lora_identifies_as_h3(prefix: str, with_alpha: bool):
+ sd = _h3_turbo_keys(prefix)
+ if with_alpha:
+ # ComfyUI-format H3 LoRAs: dotted lora_A/lora_B plus a per-layer alpha.
+ for key in [k for k in sd if k.endswith(".lora_A.weight")]:
+ sd[key.removesuffix("lora_A.weight") + "alpha"] = torch.tensor(8.0)
+ accepted, result = _probe(LoRA_LyCORIS_MiniMaxH3_Config, sd)
+ assert accepted, f"H3 probe rejected its own layout (prefix={prefix!r}): {result}"
+ assert result.base is BaseModelType.MiniMaxH3
def test_h3_kohya_lora_identifies_as_h3():
@@ -209,3 +216,53 @@ def test_h3_probe_rejects_already_diffusers_keys():
}
accepted, result = _probe(LoRA_LyCORIS_MiniMaxH3_Config, sd)
assert not accepted, f"H3 probe wrongly accepted diffusers-naming keys: {result}"
+
+
+def _malformed_h3_cases() -> list[tuple[str, dict[str, torch.Tensor]]]:
+ """Files with H3 keys whose layers the converter cannot apply as one complete low-rank pair."""
+ kohya_down_only = _h3_kohya_keys()
+ del kohya_down_only["lora_unet_blocks_0_attn_out_proj.lora_up.weight"]
+
+ dotted_a_only = _h3_turbo_keys()
+ del dotted_a_only["blocks.1.mlp.fc2.lora_B.weight"]
+
+ duplicate_spellings = _h3_turbo_keys()
+ duplicate_spellings["diffusion_model.blocks.0.attn.qkv_proj.lora_A.weight"] = _z(64, 5376)
+ duplicate_spellings["diffusion_model.blocks.0.attn.qkv_proj.lora_B.weight"] = _z(3 * 5376, 64)
+
+ dotted_and_kohya = _h3_kohya_keys()
+ dotted_and_kohya["blocks.0.attn.qkv_proj.lora_down.weight"] = _z(16, 5376)
+ dotted_and_kohya["blocks.0.attn.qkv_proj.lora_up.weight"] = _z(21504, 16)
+
+ mixed_spellings = _h3_turbo_keys()
+ mixed_spellings["lora_unet_blocks_0_attn_qkv_proj.lora_down.weight"] = _z(64, 5376)
+ mixed_spellings["lora_unet_blocks_0_attn_qkv_proj.lora_up.weight"] = _z(3 * 5376, 64)
+
+ peft_dora = _h3_turbo_keys()
+ peft_dora["blocks.0.attn.out_proj.lora_magnitude_vector.weight"] = _z(5376)
+
+ return [
+ ("kohya lora_down without lora_up", kohya_down_only),
+ ("dotted lora_A without lora_B", dotted_a_only),
+ ("layer with and without a PEFT prefix", duplicate_spellings),
+ ("layer both dotted and kohya-flattened", dotted_and_kohya),
+ ("layer with lora_A/lora_B and lora_down/lora_up", mixed_spellings),
+ ("PEFT DoRA magnitude", peft_dora),
+ ]
+
+
[email protected](("case", "sd"), _malformed_h3_cases(), ids=[c for c, _ in _malformed_h3_cases()])
+def test_h3_probe_rejects_malformed_lora(case: str, sd: dict[str, torch.Tensor]):
+ # Each of these used to install as H3 and then fail (or silently drop tensors) at conversion.
+ accepted, result = _probe(LoRA_LyCORIS_MiniMaxH3_Config, sd)
+ assert not accepted, f"H3 probe accepted a malformed file ({case}): {result}"
+ assert "malformed MiniMax H3 LoRA" in str(result)
+ with pytest.raises(NotAMatchError):
+ LoRA_LyCORIS_MiniMaxH3_Config._get_base_or_raise(_make_mod(Path(_TMP_DIR.name), sd))
+
+
+def test_h3_probe_accepts_kohya_pairs_with_and_without_alpha():
+ sd = _h3_kohya_keys()
+ del sd["lora_unet_blocks_0_attn_qkv_proj.alpha"]
+ accepted, result = _probe(LoRA_LyCORIS_MiniMaxH3_Config, sd)
+ assert accepted, f"H3 probe rejected a kohya file where only some layers carry alpha: {result}"
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.py
index 592ff55475..4e89994bb2 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
@@ -98,6 +98,22 @@ def test_alpha_defaults_to_rank_scale_one():
assert layer.scale() == 1.0
[email protected]("prefix", ["", "diffusion_model."])
+def test_file_alpha_on_peft_pairs_wins_over_caller_alpha(prefix: str):
+ # ComfyUI-format H3 LoRAs carry a per-layer alpha next to dotted lora_A/lora_B.
+ sd = _make_turbo_style_state_dict(prefix)
+ for key in [k for k in sd if k.endswith(".lora_A.weight")]:
+ sd[key.removesuffix("lora_A.weight") + "alpha"] = torch.tensor(1.0)
+ assert is_state_dict_likely_in_minimax_h3_format(sd)
+
+ patch = lora_model_from_minimax_h3_state_dict(sd, alpha=float(RANK))
+ assert patch.layers.keys() == {f"{MINIMAX_H3_LORA_TRANSFORMER_PREFIX}{p}" for p in EXPECTED_LAYER_PATHS}
+ for layer in patch.layers.values():
+ assert isinstance(layer, LoRALayer)
+ # alpha / rank with the file's alpha = 1 (the caller's would give 1.0 at rank 4, 2.0 at rank 2).
+ assert layer.scale() == pytest.approx(1.0 / layer.down.shape[0])
+
+
def test_qkv_fan_out_rows_and_shared_down():
sd = _make_turbo_style_state_dict()
key = "blocks.0.attn.qkv_proj"
@@ -255,3 +271,43 @@ def test_kohya_key_naming_no_h3_linear_is_not_detected():
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)
+
+
+def _malformed_cases() -> list[tuple[str, dict[str, torch.Tensor], str]]:
+ """(id, state dict, expected message fragment) for layers the converter must not half-apply."""
+ kohya_down_only = _to_kohya(_make_turbo_style_state_dict(), alpha=RANK)
+ del kohya_down_only["lora_unet_blocks_0_attn_qkv_proj.lora_up.weight"]
+
+ dotted_a_only = _make_turbo_style_state_dict()
+ del dotted_a_only["blocks.0.attn.out_proj.lora_B.weight"]
+
+ alpha_only = _make_turbo_style_state_dict()
+ alpha_only["blocks.0.attn.out_proj.alpha"] = torch.tensor(1.0)
+ del alpha_only["blocks.0.attn.out_proj.lora_A.weight"]
+ del alpha_only["blocks.0.attn.out_proj.lora_B.weight"]
+
+ # Same layer twice: whichever came last used to overwrite the other silently.
+ dotted_and_kohya = _to_kohya(_make_turbo_style_state_dict(), alpha=RANK)
+ dotted_and_kohya["blocks.0.attn.qkv_proj.lora_down.weight"] = torch.zeros(RANK, HIDDEN)
+ dotted_and_kohya["blocks.0.attn.qkv_proj.lora_up.weight"] = torch.zeros(3 * HIDDEN, RANK)
+ mixed_spellings = _to_kohya(_make_turbo_style_state_dict(), alpha=RANK)
+ mixed_spellings.update({k: v for k, v in _make_turbo_style_state_dict().items() if "blocks.0.mlp.fc1." in k})
+
+ peft_dora = _make_turbo_style_state_dict()
+ peft_dora["blocks.0.attn.out_proj.lora_magnitude_vector.weight"] = torch.ones(HIDDEN)
+
+ return [
+ ("kohya-down-only", kohya_down_only, r"\['alpha', 'lora_down.weight'\]"),
+ ("dotted-A-only", dotted_a_only, r"\['lora_A.weight'\]"),
+ ("alpha-only", alpha_only, r"\['alpha'\]"),
+ ("dotted-and-kohya", dotted_and_kohya, "two spellings"),
+ ("mixed-A/B-and-down/up", mixed_spellings, "'lora_A.weight', 'lora_B.weight', 'lora_down.weight'"),
+ ("peft-dora-magnitude", peft_dora, "lora_magnitude_vector"),
+ ]
+
+
[email protected](("sd", "message"), [c[1:] for c in _malformed_cases()], ids=[c[0] for c in _malformed_cases()])
+def test_rejects_malformed_layers(sd: dict[str, torch.Tensor], message: str):
+ assert not is_state_dict_likely_in_minimax_h3_format(sd)
+ with pytest.raises(ValueError, match=message):
+ lora_model_from_minimax_h3_state_dict(sd)