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): apply output-axis DoRA scales per output row (#10039)

Saurav Gupta4376fd1589eb
diff --git a/invokeai/backend/patches/layers/dora_layer.py b/invokeai/backend/patches/layers/dora_layer.py
index e2b16a6e2c..8fa4ac22d5 100644
--- a/invokeai/backend/patches/layers/dora_layer.py
+++ b/invokeai/backend/patches/layers/dora_layer.py
@@ -13,15 +13,16 @@ class DoRALayer(LoRALayerBase):
Two mutually-incompatible magnitude conventions exist in the wild, and they differ in *which axis* of the
``(out_features, in_features)`` weight the magnitude vector indexes:
- - **LyCORIS / kohya / OneTrainer** (``.dora_scale``): one entry per **input** column, i.e. the direction
- norm is taken across the output dim. Shape ``(1, in_features)``.
- - **PEFT / Diffusers / ai-toolkit** (``.lora_magnitude_vector.weight`` / ``.magnitude``): one entry per
- **output** row, i.e. the direction norm is taken across the input dim (``torch.linalg.norm(w, dim=1)``).
- Shape ``(out_features,)``.
-
- Applying one convention's magnitude with the other's math silently produces wrong weights on square layers
- and raises a broadcast error on non-square ones, so the orientation is carried explicitly rather than
- guessed from the tensor shape.
+ - **Input axis**: one entry per **input** column, i.e. the direction norm is taken across the output dim.
+ Shape ``(1, in_features)``. This is LyCORIS' ``.dora_scale`` with ``wd_on_out=False``.
+ - **Output axis**: one entry per **output** row, i.e. the direction norm is taken across the input dim
+ (``torch.linalg.norm(w, dim=1)``). PEFT / Diffusers / ai-toolkit (``.lora_magnitude_vector.weight`` /
+ ``.magnitude``, shape ``(out_features,)``), and the ``.dora_scale`` that LyCORIS writes by default
+ (``wd_on_out=True``) and OneTrainer writes with "DoRA on output axis": shape ``(out_features, 1)``.
+
+ Applying one convention's magnitude with the other's math silently produces wrong weights, so the orientation
+ is carried explicitly. A ``.dora_scale`` can hold either, and its stored shape tells which (see
+ ``_dora_scale_is_out_dim``).
"""
def __init__(
@@ -48,12 +49,17 @@ class DoRALayer(LoRALayerBase):
values.get("bias_indices", None), values.get("bias_values", None), values.get("bias_size", None)
)
- # ``dora_magnitude`` is the PEFT/ai-toolkit out-dim magnitude; ``dora_scale`` is the LyCORIS in-dim one.
- magnitude_is_out_dim = "dora_magnitude" in values
- dora_scale = values["dora_magnitude"] if magnitude_is_out_dim else values["dora_scale"]
+ up = values["lora_up.weight"]
+ # ``dora_magnitude`` is the PEFT/ai-toolkit out-dim magnitude. ``dora_scale`` can index either axis.
+ if "dora_magnitude" in values:
+ dora_scale = values["dora_magnitude"]
+ magnitude_is_out_dim = True
+ else:
+ dora_scale = values["dora_scale"]
+ magnitude_is_out_dim = cls._dora_scale_is_out_dim(dora_scale, out_features=up.shape[0])
layer = cls(
- up=values["lora_up.weight"],
+ up=up,
down=values["lora_down.weight"],
dora_scale=dora_scale,
alpha=alpha,
@@ -79,6 +85,21 @@ class DoRALayer(LoRALayerBase):
return layer
+ @staticmethod
+ def _dora_scale_is_out_dim(dora_scale: torch.Tensor, out_features: int) -> bool:
+ """Whether a ``.dora_scale`` holds one entry per output row.
+
+ LyCORIS stores ``(out_features, 1)``, or ``(out_features, 1, 1, 1)`` for a conv layer, with
+ ``wd_on_out=True`` (its default) and ``(1, in_features[, 1, 1])`` with ``wd_on_out=False``. The two
+ shapes only coincide when ``out_features == in_features == 1``, where both conventions give the same
+ weight. A 1-D scale has no axis to tell from, so it keeps the input-axis reading.
+ """
+ return (
+ dora_scale.dim() >= 2
+ and dora_scale.shape[0] == out_features
+ and all(size == 1 for size in dora_scale.shape[1:])
+ )
+
def _rank(self) -> int:
return self.down.shape[0]
diff --git a/invokeai/backend/patches/layers/utils.py b/invokeai/backend/patches/layers/utils.py
index e6d36e2f7c..4c091d1854 100644
--- a/invokeai/backend/patches/layers/utils.py
+++ b/invokeai/backend/patches/layers/utils.py
@@ -16,7 +16,7 @@ def any_lora_layer_from_state_dict(state_dict: Dict[str, torch.Tensor]) -> BaseL
# Detect layers according to LyCORIS detection logic(`weight_list_det`)
# https://github.com/KohakuBlueleaf/LyCORIS/tree/8ad8000efb79e2b879054da8c9356e6143591bad/lycoris/modules
if "dora_scale" in state_dict or "dora_magnitude" in state_dict:
- # ``dora_scale`` is the LyCORIS in-dim magnitude, ``dora_magnitude`` the PEFT/ai-toolkit out-dim one.
+ # ``dora_scale`` is the LyCORIS magnitude, on either axis; ``dora_magnitude`` the PEFT/ai-toolkit out-dim one.
return DoRALayer.from_state_dict_values(state_dict)
elif "lora_up.weight" in state_dict:
# LoRA a.k.a LoCon
diff --git a/tests/backend/patches/layers/test_dora_layer.py b/tests/backend/patches/layers/test_dora_layer.py
index a56afacf59..c90b45c65e 100644
--- a/tests/backend/patches/layers/test_dora_layer.py
+++ b/tests/backend/patches/layers/test_dora_layer.py
@@ -1,6 +1,8 @@
+import pytest
import torch
from invokeai.backend.patches.layers.dora_layer import DoRALayer
+from invokeai.backend.patches.layers.utils import any_lora_layer_from_state_dict
def _reference_aitoolkit_forward(
@@ -63,3 +65,70 @@ def test_in_dim_magnitude_keeps_lycoris_math() -> None:
direction_norm = direction.transpose(0, 1).norm(dim=1, keepdim=True).transpose(0, 1)
expected = direction * (dora_scale / direction_norm)
assert torch.allclose(orig_weight + layer.get_weight(orig_weight), expected, atol=1e-6)
+
+
+ ["out_features", "in_features"],
+ [(12, 20), (16, 16), (1, 8)],
+ ids=["non-square", "square", "single-output-row"],
+)
+def test_out_dim_dora_scale_matches_lycoris_wd_on_out(out_features: int, in_features: int) -> None:
+ """A ``.dora_scale`` stored per output row, ``(out_features, 1)``, is LyCORIS' default ``wd_on_out=True`` layout
+ (and OneTrainer's "DoRA on output axis"). It must be applied per output row, as LyCORIS' ``weight_decompose``
+ does, not per input column (#10016)."""
+ torch.manual_seed(0)
+ rank, alpha = 2, 1.0
+ orig_weight = torch.randn(out_features, in_features)
+ up = torch.randn(out_features, rank) * 0.3
+ down = torch.randn(rank, in_features) * 0.3
+ dora_scale = orig_weight.norm(dim=1, keepdim=True)
+
+ layer = any_lora_layer_from_state_dict(
+ {"lora_up.weight": up, "lora_down.weight": down, "dora_scale": dora_scale, "alpha": torch.tensor(alpha)}
+ )
+ assert isinstance(layer, DoRALayer)
+ assert layer.magnitude_is_out_dim is True
+
+ direction = orig_weight + up @ down * (alpha / rank)
+ expected = dora_scale * direction / direction.norm(dim=1, keepdim=True)
+ torch.testing.assert_close(orig_weight + layer.get_weight(orig_weight.clone()), expected, rtol=1e-5, atol=1e-5)
+
+
+def test_out_dim_dora_scale_matches_lycoris_wd_on_out_for_conv() -> None:
+ """For a conv layer, LyCORIS' ``wd_on_out=True`` ``.dora_scale`` is ``(out_channels, 1, 1, 1)``."""
+ torch.manual_seed(0)
+ out_channels, in_channels, rank = 8, 4, 2
+ orig_weight = torch.randn(out_channels, in_channels, 3, 3)
+ up = torch.randn(out_channels, rank, 1, 1) * 0.3
+ down = torch.randn(rank, in_channels, 3, 3) * 0.3
+ dora_scale = orig_weight.flatten(1).norm(dim=1).reshape(out_channels, 1, 1, 1)
+
+ layer = DoRALayer.from_state_dict_values({"lora_up.weight": up, "lora_down.weight": down, "dora_scale": dora_scale})
+ assert layer.magnitude_is_out_dim is True
+
+ direction = orig_weight + (up.flatten(1) @ down.flatten(1)).reshape(orig_weight.shape)
+ direction_norm = direction.flatten(1).norm(dim=1).reshape(out_channels, 1, 1, 1)
+ expected = dora_scale * direction / direction_norm
+ torch.testing.assert_close(orig_weight + layer.get_weight(orig_weight.clone()), expected, rtol=1e-5, atol=1e-5)
+
+
+ ["dora_scale_shape", "expected_out_dim"],
+ [
+ ((1, 20), False), # LyCORIS wd_on_out=False, linear
+ ((12, 1), True), # LyCORIS wd_on_out=True, linear
+ ((1, 20, 1, 1), False), # LyCORIS wd_on_out=False, conv
+ ((12, 1, 1, 1), True), # LyCORIS wd_on_out=True, conv
+ ((20,), False), # 1-D: no axis to tell from, keeps the input-axis reading
+ ],
+)
+def test_dora_scale_orientation_follows_its_shape(dora_scale_shape: tuple[int, ...], expected_out_dim: bool) -> None:
+ out_features, in_features, rank = 12, 20, 4
+ up = torch.ones(out_features, rank, *([1] * (len(dora_scale_shape) - 2)))
+ down = torch.ones(rank, in_features, *([1] * (len(dora_scale_shape) - 2)))
+ layer = DoRALayer.from_state_dict_values(
+ {"lora_up.weight": up, "lora_down.weight": down, "dora_scale": torch.ones(dora_scale_shape)}
+ )
+ assert layer.magnitude_is_out_dim is expected_out_dim
diff --git a/tests/backend/patches/lora_conversions/test_krea2_lora_conversion_utils.py b/tests/backend/patches/lora_conversions/test_krea2_lora_conversion_utils.py
index b8ddbfdf7a..5bc132c56c 100644
--- a/tests/backend/patches/lora_conversions/test_krea2_lora_conversion_utils.py
+++ b/tests/backend/patches/lora_conversions/test_krea2_lora_conversion_utils.py
@@ -47,8 +47,8 @@ def test_peft_dora_layer_preserves_magnitude_and_alpha() -> None:
assert isinstance(layer, DoRALayer)
assert layer._alpha == 1.0
assert torch.equal(layer.dora_scale, dora_scale)
- # `.dora_scale` is the LyCORIS magnitude: it indexes the *input* dim.
- assert layer.magnitude_is_out_dim is False
+ # A `(out_features, 1)` `.dora_scale` is the LyCORIS `wd_on_out=True` magnitude: it indexes the *output* dim.
+ assert layer.magnitude_is_out_dim is True
def test_peft_layer_without_explicit_alpha_uses_rank_default() -> None: