Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio Anima LoRA: rule out kohya splits that name no registered module before probing (#17247)

Daniel Han0036e84ad79b
diff --git a/studio/backend/core/inference/diffusion_lora_files.py b/studio/backend/core/inference/diffusion_lora_files.py
index b100c59df8c..16a7a03592e 100644
--- a/studio/backend/core/inference/diffusion_lora_files.py
+++ b/studio/backend/core/inference/diffusion_lora_files.py
@@ -419,16 +419,60 @@ def _attach_lokr(pipe: Any, name: str, lokr: dict, family: Optional[str]) -> int
return len(adapters)
-def _resolve_kohya_stem(pipe: Any, stem: str, family: Optional[str]) -> str:
+def _anima_unreachable(pipe: Any, paths: list, names: dict) -> set:
+ """Splits whose Anima rename names no registered submodule: ``_lokr_targets`` would raise for each.
+ One batched rename; an output collision returns nothing ruled out (every split is then tried)."""
+ import torch
+
+ try:
+ from diffusers.loaders.lora_conversion_utils import (
+ _convert_non_diffusers_anima_lora_to_diffusers,
+ )
+ except ImportError:
+ return set()
+
+ keys = ["diffusion_model." + _strip(path) + ".x" for path in paths]
+ renamed = list(_convert_non_diffusers_anima_lora_to_diffusers(dict.fromkeys(keys)))
+ if len(renamed) != len(keys):
+ return set()
+ out = set()
+ for path, name in zip(paths, renamed):
+ component, _, sub = name[: -len(".x")].partition(".")
+ if component not in names:
+ root = getattr(pipe, component, None)
+ names[component] = (
+ {n for n, _ in root.named_modules(remove_duplicate = False)}
+ if isinstance(root, torch.nn.Module)
+ else None
+ )
+ known = names[component]
+ if known is not None and sub not in known:
+ out.add(path)
+ return out
+
+
+def _resolve_kohya_stem(
+ pipe: Any,
+ stem: str,
+ family: Optional[str],
+ names: Optional[dict] = None,
+) -> str:
"""The one dotted path, of every way to re-split ``stem``'s underscores, that names a layer of this model."""
tokens = stem.split("_")
if len(tokens) > 16:
raise ValueError(f"LoRA key {stem} names no layer of this model")
+ paths = [
+ tokens[0]
+ + "".join(("." if mask >> i & 1 else "_") + token for i, token in enumerate(tokens[1:]))
+ for mask in range(1 << (len(tokens) - 1))
+ ]
+ skip = (
+ _anima_unreachable(pipe, paths, {} if names is None else names) if family == "anima" else ()
+ )
found = []
- for mask in range(1 << (len(tokens) - 1)):
- path = tokens[0] + "".join(
- ("." if mask >> i & 1 else "_") + token for i, token in enumerate(tokens[1:])
- )
+ for path in paths:
+ if path in skip:
+ continue
try:
_lokr_targets(pipe, path, family)
except Exception: # noqa: BLE001 -- this split names no layer
@@ -442,6 +486,7 @@ def _resolve_kohya_stem(pipe: Any, stem: str, family: Optional[str]) -> str:
def _dotted_kohya_keys(pipe: Any, state: dict, family: Optional[str]) -> dict:
out: dict = {}
paths: dict = {}
+ names: dict = {}
for key, value in state.items():
prefix = next((p for p in _KOHYA_PREFIXES if key.startswith(p)), None)
if prefix is None:
@@ -449,7 +494,7 @@ def _dotted_kohya_keys(pipe: Any, state: dict, family: Optional[str]) -> dict:
continue
stem, _, suffix = key[len(prefix) :].partition(".")
if stem not in paths:
- paths[stem] = _resolve_kohya_stem(pipe, stem, family)
+ paths[stem] = _resolve_kohya_stem(pipe, stem, family, names)
out[f"diffusion_model.{paths[stem]}.{suffix}"] = value
return out
diff --git a/studio/backend/tests/test_anima_kohya_split_pruning.py b/studio/backend/tests/test_anima_kohya_split_pruning.py
new file mode 100644
index 00000000000..3d36232e831
--- /dev/null
+++ b/studio/backend/tests/test_anima_kohya_split_pruning.py
@@ -0,0 +1,65 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Anima kohya stems: splits whose rename names no registered module are ruled out before the per-split probe,
+and the resolved path is the same."""
+
+import sys
+import types
+
+from torch import nn
+
+from core.inference import diffusion_lora_files as lf
+
+
+def _install_converter(monkeypatch):
+ def convert(state):
+ return {
+ "transformer." + key[len("diffusion_model.") :]: value for key, value in state.items()
+ }
+
+ module = types.ModuleType("diffusers.loaders.lora_conversion_utils")
+ module._convert_non_diffusers_anima_lora_to_diffusers = convert
+ for name in ("diffusers", "diffusers.loaders"):
+ monkeypatch.setitem(sys.modules, name, sys.modules.get(name) or types.ModuleType(name))
+ monkeypatch.setitem(sys.modules, "diffusers.loaders.lora_conversion_utils", module)
+
+
+def _pipe():
+ block = nn.Module()
+ block.self_attn = nn.Module()
+ block.self_attn.q_proj = nn.Linear(2, 2)
+ block.mlp = nn.Module()
+ block.mlp.layer1 = nn.Linear(2, 2)
+ root = nn.Module()
+ root.blocks = nn.ModuleList([block])
+ return types.SimpleNamespace(transformer = root)
+
+
+def test_only_reachable_splits_are_probed(monkeypatch):
+ _install_converter(monkeypatch)
+ probed = []
+ original = lf._lokr_targets
+
+ def spy(pipe, path, family):
+ probed.append(path)
+ return original(pipe, path, family)
+
+ monkeypatch.setattr(lf, "_lokr_targets", spy)
+ pipe = _pipe()
+ assert (
+ lf._resolve_kohya_stem(pipe, "blocks_0_self_attn_q_proj", "anima")
+ == "blocks.0.self_attn.q_proj"
+ )
+ assert lf._resolve_kohya_stem(pipe, "blocks_0_mlp_layer1", "anima") == "blocks.0.mlp.layer1"
+ assert probed == ["blocks.0.self_attn.q_proj", "blocks.0.mlp.layer1"]
+
+
+def test_a_stem_naming_no_layer_still_raises(monkeypatch):
+ _install_converter(monkeypatch)
+ try:
+ lf._resolve_kohya_stem(_pipe(), "blocks_0_cross_attn_q_proj", "anima")
+ except ValueError as err:
+ assert "names no single layer" in str(err)
+ else:
+ raise AssertionError("expected ValueError")