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): identify LTX-2 LoRAs that train diffusers-named modulation heads (#10377)

Бат-Орших6313ac205c8c
diff --git a/invokeai/backend/patches/lora_conversions/ltx2_lora_constants.py b/invokeai/backend/patches/lora_conversions/ltx2_lora_constants.py
index 856331b686..302d74f351 100644
--- a/invokeai/backend/patches/lora_conversions/ltx2_lora_constants.py
+++ b/invokeai/backend/patches/lora_conversions/ltx2_lora_constants.py
@@ -54,20 +54,44 @@ _LTX2_CROSS_MODAL_RE = re.compile(
_PEFT_PREFIX_RE + r"(?:av_ca_(?:a2v_gate|v2a_gate|audio_scale_shift|video_scale_shift)_adaln_single|"
r"audio_adaln_single|audio_prompt_adaln_single|audio_patchify_proj|audio_proj_out)\."
)
+# The same heads under the diffusers ``LTX2VideoTransformer3DModel`` names, as a PEFT ``PeftModel``
+# around that class saves them. The runtime transformer uses these names, so the converter must carry
+# them through untouched. ``time_embed`` / ``proj_in`` / ``prompt_adaln`` are accepted the same way
+# but are not markers: LTX-Video's diffusers transformer has ``time_embed`` and ``proj_in`` too.
+_LTX2_DIFFUSERS_TOP_LEVEL_MARKER_RE = re.compile(
+ _PEFT_PREFIX_RE + r"(?:av_cross_attn_(?:video_scale_shift|video_a2v_gate|audio_scale_shift|audio_v2a_gate)|"
+ r"audio_time_embed|audio_prompt_adaln|audio_proj_in)\."
+)
+# Every top-level module the converter must leave alone, matched against prefix-stripped layer paths
+# (``proj_in`` itself is a layer, so this compares the first path component rather than a ``name.`` prefix).
+_LTX2_DIFFUSERS_TOP_LEVEL_MODULES = frozenset(
+ {
+ "time_embed",
+ "audio_time_embed",
+ "prompt_adaln",
+ "audio_prompt_adaln",
+ "proj_in",
+ "audio_proj_in",
+ "av_cross_attn_video_scale_shift",
+ "av_cross_attn_video_a2v_gate",
+ "av_cross_attn_audio_scale_shift",
+ "av_cross_attn_audio_v2a_gate",
+ }
+)
# Any of these indicates a different architecture; an LTX-2 LoRA never carries them.
#
# Note what is absent: ``transformer_blocks\.\d+`` cannot be an anti-pattern here because
# LTX-2 uses it natively. QwenImage is excluded by its own modulation/MLP naming instead.
_NON_LTX2_ANTI_RES = (
- re.compile(r"(self_attn|cross_attn)[\._]"), # Wan / Anima attention naming
+ # Wan / Anima attention naming; LTX-2's diffusers ``av_cross_attn_*`` heads are not it.
+ re.compile(r"(self_attn|(?<!av_)cross_attn)[\._]"),
re.compile(r"blocks\.\d+\.(?:attn\.qkv_proj|adaln_proj\.linear)"), # MiniMax H3 fused attention
re.compile(r"final_layer\.adaln_proj\.linear"), # MiniMax H3 final layer
re.compile(r"(^|\.|_)(double_blocks|single_blocks|single_transformer_blocks)[\._]\d+"), # FLUX
re.compile(r"(img_mod|txt_mod|img_mlp|txt_mlp|img_attn|txt_attn)[\._]"), # QwenImage / FLUX-style
re.compile(r"diffusion_model\.layers\.\d+\."), # Z-Image
re.compile(r"mlp[\._]layer|adaln_modulation"), # Anima / Cosmos
- re.compile(r"(^|\.)(time_embed|audio_time_embed|av_cross_attn_)"), # already-converted diffusers keys
)
# LyCORIS variants the LTX-2 pipeline does NOT support. The conversion maps official layer
@@ -101,18 +125,26 @@ def has_unsupported_ltx2_lora_variant_keys(str_keys: list[str]) -> bool:
def has_ltx2_lora_keys(str_keys: list[str]) -> bool:
- """PEFT-style keys naming LTX-2-exclusive submodules in the checkpoint's native layout.
+ """PEFT-style keys naming LTX-2-exclusive submodules in the checkpoint's native or diffusers layout.
Either an audio-side / cross-modal tower inside a block, or one of the top-level
- cross-modal modulation heads. Both exist only on a dual-stream video+audio transformer.
+ cross-modal modulation heads under either naming. Both exist only on a dual-stream video+audio transformer.
"""
- return any(_LTX2_BLOCK_RE.search(k) or _LTX2_CROSS_MODAL_RE.search(k) for k in str_keys)
+ return any(
+ _LTX2_BLOCK_RE.search(k) or _LTX2_CROSS_MODAL_RE.search(k) or _LTX2_DIFFUSERS_TOP_LEVEL_MARKER_RE.search(k)
+ for k in str_keys
+ )
+
+
+def is_ltx2_diffusers_top_level_path(layer_path: str) -> bool:
+ """True if a prefix-stripped layer path already names a top-level module in diffusers form."""
+ return layer_path.split(".", 1)[0] in _LTX2_DIFFUSERS_TOP_LEVEL_MODULES
def has_non_ltx2_architecture_keys(str_keys: list[str]) -> bool:
"""True if any key indicates a non-LTX-2 architecture (Wan, H3, FLUX, QwenImage, Z-Image,
- Anima) or an already-converted diffusers layout.
+ Anima).
- Used as an exclusion guard — an LTX-2 LoRA in its published layout never carries these.
+ Used as an exclusion guard — an LTX-2 LoRA never carries these.
"""
return any(anti.search(k) for k in str_keys for anti in _NON_LTX2_ANTI_RES)
diff --git a/invokeai/backend/patches/lora_conversions/ltx2_lora_conversion_utils.py b/invokeai/backend/patches/lora_conversions/ltx2_lora_conversion_utils.py
index f81b24c97e..cd191a5050 100644
--- a/invokeai/backend/patches/lora_conversions/ltx2_lora_conversion_utils.py
+++ b/invokeai/backend/patches/lora_conversions/ltx2_lora_conversion_utils.py
@@ -34,6 +34,7 @@ from invokeai.backend.patches.lora_conversions.ltx2_lora_constants import (
has_ltx2_lora_keys,
has_non_ltx2_architecture_keys,
has_unsupported_ltx2_lora_variant_keys,
+ is_ltx2_diffusers_top_level_path,
)
from invokeai.backend.patches.model_patch_raw import ModelPatchRaw
@@ -100,7 +101,11 @@ def _official_to_diffusers_paths(layer_paths: Iterable[str]) -> dict[str, str]:
from invokeai.backend.ltx2 import component_configs as cc
- sentinels = {f"{path}.weight": f"{path}.weight" for path in layer_paths}
+ # A layer already in diffusers form is the runtime name; keep it out of the map so no rename can
+ # be applied to it a second time.
+ sentinels = {
+ f"{path}.weight": f"{path}.weight" for path in layer_paths if not is_ltx2_diffusers_top_level_path(path)
+ }
renamed = convert_ltx2_transformer_to_diffusers(dict(sentinels))
renamed, _ = cc.finish_transformer_keys(renamed)
diff --git a/tests/backend/model_manager/configs/test_ltx2_lora_probe_independence.py b/tests/backend/model_manager/configs/test_ltx2_lora_probe_independence.py
index 5e78830043..9fa22b9b10 100644
--- a/tests/backend/model_manager/configs/test_ltx2_lora_probe_independence.py
+++ b/tests/backend/model_manager/configs/test_ltx2_lora_probe_independence.py
@@ -250,12 +250,35 @@ def test_the_ltx2_probe_rejects_nested_prefixes() -> None:
assert not matched
-def test_the_ltx2_probe_rejects_already_converted_keys() -> None:
- """A state dict already in diffusers naming has been through the conversion once; running it
- through again would rename nothing and resolve nothing."""
- sd = _ltx2_distilled_keys()
- sd["diffusion_model.time_embed.linear.lora_A.weight"] = _z(450, 4096)
- sd["diffusion_model.time_embed.linear.lora_B.weight"] = _z(36864, 450)
+def _ltx2_diffusers_top_level_keys(prefix: str) -> dict[str, torch.Tensor]:
+ """The modulation heads under the diffusers names a PEFT ``PeftModel`` around
+ ``LTX2VideoTransformer3DModel`` saves, with no block-level marker to lean on."""
+ sd: dict[str, torch.Tensor] = {}
+ for name, (in_f, out_f) in {
+ "time_embed.linear": (4096, 36864),
+ "audio_time_embed.linear": (2048, 18432),
+ "av_cross_attn_video_a2v_gate.linear": (4096, 4096),
+ }.items():
+ sd[f"{prefix}{name}.lora_A.weight"] = _z(8, in_f)
+ sd[f"{prefix}{name}.lora_B.weight"] = _z(out_f, 8)
+ return sd
+
+
[email protected]("prefix", ALL_PREFIXES)
+def test_diffusers_named_modulation_heads_identify_as_ltx2(prefix: str) -> None:
+ """The runtime transformer uses these names, so the converter carries them through as-is."""
+ for sd in (
+ _ltx2_distilled_keys(prefix) | _ltx2_diffusers_top_level_keys(prefix),
+ _ltx2_diffusers_top_level_keys(prefix),
+ ):
+ probes = [cls for cls in Config_Base.CONFIG_CLASSES if cls.__name__.startswith("LoRA_")]
+ assert [cls.__name__ for cls in probes if _probe(cls, sd)[0]] == [LoRA_LyCORIS_LTX2_Config.__name__]
+
+
+def test_a_diffusers_time_embed_alone_is_not_an_ltx2_marker() -> None:
+ """LTX-Video's diffusers transformer has ``time_embed`` too."""
+ sd = _ltx2_diffusers_top_level_keys("transformer.")
+ sd = {k: v for k, v in sd.items() if ".time_embed." in f".{k}"}
matched, _ = _probe(LoRA_LyCORIS_LTX2_Config, sd)
diff --git a/tests/backend/patches/lora_conversions/test_ltx2_lora_conversion.py b/tests/backend/patches/lora_conversions/test_ltx2_lora_conversion.py
index dc6111632a..dbd1aeabc1 100644
--- a/tests/backend/patches/lora_conversions/test_ltx2_lora_conversion.py
+++ b/tests/backend/patches/lora_conversions/test_ltx2_lora_conversion.py
@@ -206,3 +206,57 @@ def test_lycoris_variants_are_refused_by_name() -> None:
def test_the_published_layout_is_recognized_as_ltx2() -> None:
assert is_state_dict_likely_in_ltx2_format(_published_state_dict())
+
+
+# (diffusers path, in_features, out_features) as a PEFT `PeftModel` around `LTX2VideoTransformer3DModel` names them.
+DIFFUSERS_TOP_LEVEL_LAYERS = (
+ ("time_embed.linear", 4096, 36864),
+ ("audio_time_embed.linear", 2048, 18432),
+ ("av_cross_attn_video_a2v_gate.linear", 4096, 4096),
+ ("av_cross_attn_audio_v2a_gate.linear", 2048, 2048),
+ ("av_cross_attn_video_scale_shift.linear", 4096, 16384),
+ ("av_cross_attn_audio_scale_shift.linear", 2048, 8192),
+ ("prompt_adaln.linear", 4096, 8192),
+ ("audio_prompt_adaln.linear", 2048, 4096),
+ ("proj_in", 128, 4096),
+ ("audio_proj_in", 128, 2048),
+)
+
+
[email protected]("prefix", ["", "transformer.", "base_model.model.", "base_model.model.transformer."])
+def test_diffusers_named_layers_keep_their_names_and_resolve(prefix: str) -> None:
+ """Already the runtime names: the official -> diffusers rename must not touch them a second time."""
+ modules = _transformer_modules()
+ state_dict: dict[str, torch.Tensor] = {}
+ for path, in_features, out_features in DIFFUSERS_TOP_LEVEL_LAYERS:
+ state_dict[f"{prefix}{path}.lora_A.weight"] = _z(8, in_features)
+ state_dict[f"{prefix}{path}.lora_B.weight"] = _z(out_features, 8)
+
+ assert is_state_dict_likely_in_ltx2_format(state_dict)
+ patch = lora_model_from_ltx2_state_dict(state_dict)
+
+ paths = [name[len(LTX2_LORA_TRANSFORMER_PREFIX) :] for name in patch.layers]
+ assert paths == [path for path, _in, _out in DIFFUSERS_TOP_LEVEL_LAYERS]
+ for path, layer in zip(paths, patch.layers.values(), strict=True):
+ module = modules.get(path)
+ assert isinstance(module, torch.nn.Linear), f"{path!r} is not a Linear on the transformer"
+ assert layer.up.shape[0] == module.out_features, path
+ assert layer.down.shape[1] == module.in_features, path
+
+
+def test_diffusers_named_layers_are_kept_out_of_the_rename(monkeypatch: pytest.MonkeyPatch) -> None:
+ """The current rename tables happen to leave these names alone; the guard must not rely on that."""
+ import diffusers.loaders.single_file_utils as single_file_utils
+
+ def rename_everything(sd: dict[str, str]) -> dict[str, str]:
+ return {f"renamed.{key}": value for key, value in sd.items()}
+
+ monkeypatch.setattr(single_file_utils, "convert_ltx2_transformer_to_diffusers", rename_everything)
+ official = "transformer_blocks.0.audio_attn1.to_q"
+ state_dict: dict[str, torch.Tensor] = {}
+ for path in (official, *(path for path, _in, _out in DIFFUSERS_TOP_LEVEL_LAYERS)):
+ state_dict[f"base_model.model.{path}.lora_A.weight"] = _z(8, 16)
+ state_dict[f"base_model.model.{path}.lora_B.weight"] = _z(16, 8)
+
+ paths = [name[len(LTX2_LORA_TRANSFORMER_PREFIX) :] for name in lora_model_from_ltx2_state_dict(state_dict).layers]
+ assert paths == [f"renamed.{official}", *(path for path, _in, _out in DIFFUSERS_TOP_LEVEL_LAYERS)]