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 DoRA magnitudes on Z-Image, Qwen-Image and Anima and on quantized transformers (#10245)

Alexander Eichhorn5de896f2e8a0
diff --git a/docs/src/content/docs/Users Guide/03.Models/03.model-format-support.mdx b/docs/src/content/docs/Users Guide/03.Models/03.model-format-support.mdx
index bfc02e4c7e..ec09b16efa 100644
--- a/docs/src/content/docs/Users Guide/03.Models/03.model-format-support.mdx
+++ b/docs/src/content/docs/Users Guide/03.Models/03.model-format-support.mdx
@@ -238,5 +238,9 @@ Qwen-Image LoRAs, LoKR and LoHA files also load in ComfyUI's `diffusion_model.`
Qwen-Image LoRAs also patch the Qwen2.5-VL encoder when the file has text-encoder layers; see the same page.
+On Z-Image, Qwen-Image and Anima, DoRA in the `lora_A`/`lora_B` layout (`dora_scale`, PEFT
+`lora_magnitude_vector`, ai-toolkit `.magnitude`) applies with its magnitude. DoRA works wherever the transformer weight can be dequantized (GGUF, SDNQ, int8/int4-convrot, nvfp4, fp8), but not
+on bitsandbytes NF4/LLM.int8 bases.
+
[PiD decoders](/users-guide/image-generation/advanced-topics/pid-decode/) load for FLUX.1, FLUX.2, SD 3, SDXL and
Qwen-Image (v1 and v1.5, bf16 and int8 builds). FLUX.3 and MOSS-Image use the FLUX.2 decoders.
diff --git a/docs/src/content/docs/Users Guide/03.Models/Local Models/anima.mdx b/docs/src/content/docs/Users Guide/03.Models/Local Models/anima.mdx
index f965fd46c7..f1f41dcb8d 100644
--- a/docs/src/content/docs/Users Guide/03.Models/Local Models/anima.mdx
+++ b/docs/src/content/docs/Users Guide/03.Models/Local Models/anima.mdx
@@ -166,6 +166,9 @@ Anima LoRAs in Kohya / LyCORIS and Diffusers PEFT formats are supported. They ap
includes text-encoder layers, to the Qwen3 encoder. In the workflow editor use **Apply LoRA - Anima** or
**Apply LoRA Collection - Anima**.
+DoRA LoRAs apply with their magnitudes in the `lora_A`/`lora_B` layout (LyCORIS `dora_scale`, PEFT
+`lora_magnitude_vector`, ai-toolkit `.magnitude`) as well as in the kohya layout. DoRA runs on the GGUF, int8 and fp8 builds, but not on bitsandbytes NF4 or LLM.int8 weights.
+
## Character reference (IP-Adapter)
The **Anima IP-Adapter (Character Reference)** starter model, by LuciferTC (~500 MB), carries a character
diff --git a/docs/src/content/docs/Users Guide/03.Models/Local Models/qwen-image-2-1.mdx b/docs/src/content/docs/Users Guide/03.Models/Local Models/qwen-image-2-1.mdx
index 7fa1eddbd8..30b64925c7 100644
--- a/docs/src/content/docs/Users Guide/03.Models/Local Models/qwen-image-2-1.mdx
+++ b/docs/src/content/docs/Users Guide/03.Models/Local Models/qwen-image-2-1.mdx
@@ -82,7 +82,7 @@ Image-to-image, inpainting and outpainting read the colors of the input image an
Qwen-Image-2.1 LoRAs install like any other and appear under **Concepts** in the Generate panel. Files from ComfyUI (keys starting `diffusion_model.`), diffusers/PEFT trainers (`transformer.`) and Kohya-style trainers (`lora_unet_`) all load. ComfyUI's builds fuse each block's two MLP input projections into one `gate_up` layer; Invoke splits a LoRA on it to match the diffusers model.
- LoRAs for [Qwen Image](/users-guide/models/local-models/qwen-image/) (2512, Edit 2511) do not fit Qwen-Image-2.1 and are not offered for it, nor its LoRAs for them.
-- They work on every format, except that DoRA layers do not run on an int8 transformer: a generation with one there stops with a message before it starts. On GGUF, int8 and fp8 transformers the LoRA runs alongside the packed weights rather than being merged into them. Full weight differences on the attention and text norms, which ComfyUI's Turbo LoRA carries, are merged on every format.
+- They work on every format, DoRA layers included. On GGUF, int8 and fp8 transformers the LoRA runs alongside the packed weights rather than being merged into them. Full weight differences on the attention and text norms, which ComfyUI's Turbo LoRA carries, are merged on every format.
- A LoRA trained on the base model also applies to Turbo; how well it holds up at Turbo's 8 steps depends on the LoRA.
- Low-rank (`lora_A`/`lora_B` or `lora_down`/`lora_up`), DoRA, LoKR and LoHA LoRAs are recognized, and so are full weight differences (`diff`). On ComfyUI's fused `gate_up` only low-rank, PEFT DoRA and full layers work: a LoKR, LoHA or LyCORIS DoRA layer there mixes the two halves Invoke splits it into.
- A LoRA is recognized as a Qwen-Image-2.1 one only if all of it applies: every layer it targets exists in Qwen-Image-2.1, is complete, has the shape of the Qwen-Image-2.1 weight it changes and, on `gate_up`, can be split. A file with any part that does not apply installs as an unknown model and does not appear under **Concepts**.
diff --git a/docs/src/content/docs/Users Guide/03.Models/Local Models/qwen-image.mdx b/docs/src/content/docs/Users Guide/03.Models/Local Models/qwen-image.mdx
index 1f1a1fe001..aa7564aff1 100644
--- a/docs/src/content/docs/Users Guide/03.Models/Local Models/qwen-image.mdx
+++ b/docs/src/content/docs/Users Guide/03.Models/Local Models/qwen-image.mdx
@@ -50,8 +50,7 @@ ComfyUI's `int8_tensorwise` builds, rotated (`int8_convrot`) or not, load for th
encoder. Comfy-Org publishes `int8_convrot` transformers for Qwen Image Edit 2509 and 2511; the Qwen2.5-VL int8
encoders are community uploads. The int8 layers stay int8 in memory (about half the bf16 size) and are dequantized
layer by layer as they run, on every device. That is the default: on NVIDIA GPUs, [int8 Compute](/configuration/optimization/int8-compute/)
-can run them on the int8 tensor cores instead. The main benefit is memory; no speed-up is promised. DoRA LoRAs do not
-run on an int8 transformer. A file whose int8 layers carry only a `{"convrot": true}` marker, with no format, is
+can run them on the int8 tensor cores instead. The main benefit is memory; no speed-up is promised. A file whose int8 layers carry only a `{"convrot": true}` marker, with no format, is
refused at install for the transformer and when the encoder loads. Int4 builds are refused at install.
## Installing
@@ -163,19 +162,21 @@ Image**; connect an **Image to Latents - Qwen Image** node to the **Reference La
Qwen Image LoRAs (diffusers PEFT, Kohya, LoKR and LoHA formats) are supported and apply to the transformer and,
when the file has text-encoder layers, to the Qwen2.5-VL encoder too. This holds for every encoder build,
-including the **Encoder quantization** setting. DoRA layers on the encoder need unpacked weights: they fail
-with int8 or nf4 quantization and with packed nvfp4 encoders, so set **Encoder quantization** to **None** and
-use a bf16 or fp8 encoder. A LoRA that holds only text-encoder layers is not recognized on install.
+including the **Encoder quantization** setting. DoRA layers on the encoder work on bf16, fp8, int8-convrot and nvfp4 encoders, but fail
+with the bitsandbytes int8 or nf4 **Encoder quantization** setting; set it to **None** to use them. A LoRA that holds only text-encoder layers is not recognized on install.
In the workflow editor use **Apply LoRA - Qwen Image** or **Apply LoRA Collection - Qwen Image**. Route the
encoder through the LoRA node as well as the transformer: connect the node's **Qwen VL Encoder** output to
the prompt nodes, otherwise the LoRA's text-encoder layers stay unused. The LoRA node logs a warning when it sees this.
+DoRA LoRAs apply with their magnitudes in the `lora_A`/`lora_B` layout (LyCORIS `dora_scale`, PEFT
+`lora_magnitude_vector`, ai-toolkit `.magnitude`) as well as in the kohya layout. DoRA runs on the GGUF, fp8, int8 and nvfp4 transformers, but not on bitsandbytes NF4 or LLM.int8 weights.
+
Plain LoRAs, LoKR and LoHA files saved in ComfyUI's layout, whose keys start with `diffusion_model.`, and raw
PEFT adapters (`base_model.model.`) load as well, provided they train the blocks' modulation or MLP layers
(`img_mod`, `txt_mod`, `img_mlp`, `txt_mlp`), as files in these layouts usually do. Other model families use the
same key prefixes, so a file in these layouts that trains only attention layers is not recognized and installs as
-an unknown model, and so do PEFT DoRA files. LyCORIS and ai-toolkit files whose keys start with
+an unknown model. LyCORIS and ai-toolkit files whose keys start with
`lycoris_transformer_blocks_` or `lora_transformer_transformer_blocks_` are recognized only when they train those
modules. Without them, a `lycoris_` file installs as an unknown model, and a `lora_transformer_transformer_blocks_`
file installs as a FLUX LoRA, the spelling OneTrainer uses for FLUX. A learned `scalar` in a LoRA, LoKR or LoHA
diff --git a/docs/src/content/docs/Users Guide/03.Models/Local Models/z-image.mdx b/docs/src/content/docs/Users Guide/03.Models/Local Models/z-image.mdx
index 4095d0e10c..ff74fecc19 100644
--- a/docs/src/content/docs/Users Guide/03.Models/Local Models/z-image.mdx
+++ b/docs/src/content/docs/Users Guide/03.Models/Local Models/z-image.mdx
@@ -149,6 +149,9 @@ Z-Image LoRAs are supported in Kohya, PEFT/Diffusers and LyCORIS formats. They a
transformer and the Qwen3 encoder. In the workflow editor, use **Apply LoRA - Z-Image** or **Apply LoRA
Collection - Z-Image**.
+DoRA LoRAs apply with their magnitudes in the `lora_A`/`lora_B` layout (LyCORIS `dora_scale`, PEFT
+`lora_magnitude_vector`, ai-toolkit `.magnitude`) as well as in the kohya layout. DoRA runs on the GGUF, SDNQ, NVFP4, fp8 and int8 builds, but not on bitsandbytes NF4 or LLM.int8 weights.
+
## Seed Variance Enhancer
Z-Image Turbo tends to produce similar images across different seeds. **Seed variance**, next to the seed
diff --git a/docs/src/content/docs/Users Guide/05.Video Generation/wan-2.2.mdx b/docs/src/content/docs/Users Guide/05.Video Generation/wan-2.2.mdx
index d12389c4d8..16f607b35c 100644
--- a/docs/src/content/docs/Users Guide/05.Video Generation/wan-2.2.mdx
+++ b/docs/src/content/docs/Users Guide/05.Video Generation/wan-2.2.mdx
@@ -63,6 +63,6 @@ The UMT5-XXL encoder also comes as a GGUF file: **Wan T5 Encoder (UMT5-XXL, GGUF
#### ComfyUI int8 builds
-Single-file A14B and TI2V-5B transformers in ComfyUI's `int8_tensorwise` (convrot) format load like any other single file, with the same two-expert setup for A14B. The attention and feed-forward weights stay int8 in memory, which saves memory. By default they are dequantized per layer on each forward pass; [int8 Compute](/configuration/optimization/int8-compute/) can instead run them on NVIDIA int8 tensor cores. LoRAs, including Lightning, are applied alongside the int8 weights rather than merged into them, except that DoRA layers do not run on an int8 transformer, so a DoRA LoRA fails there when it is applied. Files marked only `{"convrot": true}`, without a `format` entry, and the int4 builds are refused when you install them.
+Single-file A14B and TI2V-5B transformers in ComfyUI's `int8_tensorwise` (convrot) format load like any other single file, with the same two-expert setup for A14B. The attention and feed-forward weights stay int8 in memory, which saves memory. By default they are dequantized per layer on each forward pass; [int8 Compute](/configuration/optimization/int8-compute/) can instead run them on NVIDIA int8 tensor cores. LoRAs, including Lightning, are applied alongside the int8 weights rather than merged into them. Files marked only `{"convrot": true}`, without a `format` entry, and the int4 builds are refused when you install them.
On one Windows machine with an RTX 4090 (T2V A14B, 832x480, 17 frames), an int8 expert file is about 14.5 GB against about 28.6 GB for a bf16 expert. With both experts and the UMT5 encoder kept in the RAM cache, the int8 build peaked at about 41 GB of RAM. With `max_cache_ram_gb: 16` it still runs but reloads the experts for each clip, and peaked at about 30 GB of RAM, because both experts are held in memory during the swap. Windows also counts VRAM toward a process's committed memory, so that figure reads higher than the RAM in use. int8 mainly saves memory; how much speed it changes depends on whether the model otherwise fits in VRAM. Other systems will differ.
diff --git a/docs/src/content/docs/configuration/Optimization/int8-compute.mdx b/docs/src/content/docs/configuration/Optimization/int8-compute.mdx
index a666624334..a7f6a05799 100644
--- a/docs/src/content/docs/configuration/Optimization/int8-compute.mdx
+++ b/docs/src/content/docs/configuration/Optimization/int8-compute.mdx
@@ -100,7 +100,7 @@ sizes in the same bucket don't pay it again.
| Running in FP32 | The kernels run in BF16 and FP16 only. |
LoRAs work as usual: they are applied beside the int8 layer in the compute precision, never quantized, and do not change
-which path the layer takes. DoRA patches don't load on int8 builds, with or without `int8_compute`.
+which path the layer takes. DoRA patches work too, with or without `int8_compute`: they get the dequantized weight. DoRA layers on a quantized transformer dequantize their weight again on every step, so they are slower than plain LoRA layers: with a 400-layer DoRA LoRA, Anima-2.9B int8 denoises 1024² in 30 steps in about 30 s, against 18 s with the same LoRA as plain LoRA.
<details>
<summary>Memory</summary>
diff --git a/docs/src/content/docs/configuration/Optimization/memory-options.mdx b/docs/src/content/docs/configuration/Optimization/memory-options.mdx
index 85334f88b7..dc0c2c8e8c 100644
--- a/docs/src/content/docs/configuration/Optimization/memory-options.mdx
+++ b/docs/src/content/docs/configuration/Optimization/memory-options.mdx
@@ -112,8 +112,8 @@ in RAM.
| [FP8 Storage](/configuration/optimization/fp8-storage/), on a full-precision model | 8 on the GPU | About half | Yes | Same or slightly slower | NVIDIA, AMD and Intel GPUs | Yes |
| fp8, scaled fp8 | 8 | About half, with FP8 Storage (on after install) | Yes | Unpacked per layer; faster with [FP8 Compute](/configuration/optimization/fp8-compute/) on RTX 40 and newer | Every device; unpacked to BF16 on the CPU and Apple silicon | Yes; with FP8 Compute only while fully in VRAM |
| MXFP8 | 8.25 | Full size: unpacked at load | Yes | Baseline | Every device | Yes |
-| int8 (`int8_convrot`) | 8 | About half | Yes, except DoRA | 0.75–0.97×; 1.3–2× with [int8 Compute](/configuration/optimization/int8-compute/) on RTX 30 and newer | Every device | Yes |
-| nvfp4 | 4.5 | About 28% | Yes, except DoRA | Unpacked per layer; no FP4 math | Every device | Yes |
+| int8 (`int8_convrot`) | 8 | About half | Yes | 0.75–0.97×; 1.3–2× with [int8 Compute](/configuration/optimization/int8-compute/) on RTX 30 and newer | Every device | Yes |
+| nvfp4 | 4.5 | About 28% | Yes | Unpacked per layer; no FP4 math | Every device | Yes |
| GGUF | 4.5 (Q4_K) to 8.5 (Q8_0) | About 28–53% | Yes | Unpacked per layer | Every device | Yes |
| [SDNQ](/configuration/optimization/sdnq-quantization/) | 4–5, plus the SVD correction | About a third | Yes | Unpacked per layer | Every device | Yes |
| NF4 (bitsandbytes) | 4, plus block scales | About 28% | Yes, except DoRA | Unpacked per layer | NVIDIA and AMD GPUs; not macOS; untested on Intel GPUs and the CPU | Yes |
@@ -123,5 +123,6 @@ in RAM.
- **Which models come in which format** is listed in [Model Format Support](/users-guide/models/model-format-support/).
Sizes, starter models and measured speeds are on each model family's page.
- **LoRAs** run beside the quantized layers rather than being merged into them, so a LoRA works on every format; DoRA
- patches fail on int8, nvfp4 and NF4.
+ patches work wherever the weight can be dequantized (GGUF, SDNQ, int8, nvfp4, fp8) and fail on bitsandbytes NF4 and
+ LLM.int8. DoRA layers on a quantized transformer dequantize their weight again on every step, so they are slower than plain LoRA layers: with a 400-layer DoRA LoRA, Anima-2.9B int8 denoises 1024² in 30 steps in about 30 s, against 18 s with the same LoRA as plain LoRA.
- On a GPU, every format works with Low-VRAM mode, which streams from RAM whatever doesn't fit in VRAM.
diff --git a/invokeai/app/invocations/flux3/flux3_denoise.py b/invokeai/app/invocations/flux3/flux3_denoise.py
index d68815b8fc..a325b048cc 100644
--- a/invokeai/app/invocations/flux3/flux3_denoise.py
+++ b/invokeai/app/invocations/flux3/flux3_denoise.py
@@ -34,11 +34,9 @@ from invokeai.backend.flux3.sampling import (
)
from invokeai.backend.model_manager.taxonomy import BaseModelType, Flux3VariantType, ModelType
from invokeai.backend.patches.layer_patcher import LayerPatcher, PatchSpec
-from invokeai.backend.patches.layers.dora_layer import DoRALayer
-from invokeai.backend.patches.layers.swapped_halves_layer_patch import SwappedHalvesLayerPatch
from invokeai.backend.patches.lora_conversions.flux3_lora_constants import FLUX3_LORA_TRANSFORMER_PREFIX
from invokeai.backend.patches.model_patch_raw import ModelPatchRaw
-from invokeai.backend.quantization.dequantizing_linear import DequantizingLinear, requires_sidecar_patching
+from invokeai.backend.quantization.dequantizing_linear import requires_sidecar_patching
from invokeai.backend.rectified_flow.rectified_flow_inpaint_extension import RectifiedFlowInpaintExtension
from invokeai.backend.stable_diffusion.diffusers_pipeline import PipelineIntermediateState
from invokeai.backend.stable_diffusion.diffusion.conditioning_data import Flux3ConditioningInfo
@@ -214,7 +212,6 @@ class Flux3DenoiseInvocation(BaseInvocation):
with ExitStack() as exit_stack:
transformer_info = context.models.load(self.transformer.transformer)
loras = self._active_loras(context)
- self._refuse_dora_on_quantized_layers(loras, transformer_info.model)
# Ask the model cache to keep free what one transformer forward needs. Reference images are the dominant
# term: their tokens join the attended sequence, so ten 1 MP references add ten times the tokens of a
# 1 MP image. Priced on the unlocked model, whose GGUF or fp8-stored layers add a transient per forward,
@@ -297,27 +294,6 @@ class Flux3DenoiseInvocation(BaseInvocation):
if lora.weight != 0
]
- @staticmethod
- def _refuse_dora_on_quantized_layers(loras: list[tuple[str, ModelPatchRaw]], transformer: torch.nn.Module) -> None:
- """Fail before loading the transformer onto the device, not at the first step: a DoRA layer normalizes the
- updated weight, which a Linear keeping its weight quantized in buffers never forms (`DoRALayer.get_parameters`
- raises on the shape it hands over instead)."""
- # Reached once quantized FLUX.3 builds, whose Linears are `DequantizingLinear`s, load.
- if not loras:
- return
- modules = dict(transformer.named_modules())
- for name, patch in loras:
- for key, layer in patch.layers.items():
- # A layer on BFL's output modulation comes wrapped, to swap its halves.
- if isinstance(layer, SwappedHalvesLayerPatch):
- layer = layer.layer
- module = modules.get(key.removeprefix(FLUX3_LORA_TRANSFORMER_PREFIX))
- if isinstance(layer, DoRALayer) and isinstance(module, DequantizingLinear):
- raise ValueError(
- f"LoRA '{name}' has DoRA layers, which do not run on this transformer's quantized layers. Use "
- "it with an unquantized or GGUF build of the transformer."
- )
-
def _lora_iterator(self, context: InvocationContext) -> Iterator[PatchSpec]:
for lora in self.transformer.loras:
lora_info = context.models.load(lora.lora)
diff --git a/invokeai/app/invocations/qwen_image_2_1/qwen_image_2_1_denoise.py b/invokeai/app/invocations/qwen_image_2_1/qwen_image_2_1_denoise.py
index 4c6a198e41..03525cfac9 100644
--- a/invokeai/app/invocations/qwen_image_2_1/qwen_image_2_1_denoise.py
+++ b/invokeai/app/invocations/qwen_image_2_1/qwen_image_2_1_denoise.py
@@ -28,7 +28,6 @@ from invokeai.app.services.shared.invocation_context import InvocationContext
from invokeai.backend.flux.sampling_utils import clip_timestep_schedule_fractional
from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelFormat, QwenImage21VariantType
from invokeai.backend.patches.layer_patcher import LayerPatcher, PatchSpec
-from invokeai.backend.patches.layers.dora_layer import DoRALayer
from invokeai.backend.patches.lora_conversions.qwen_image_2_1_lora_conversion_utils import (
QWEN_IMAGE_21_LORA_NORM_PREFIX,
QWEN_IMAGE_21_LORA_TRANSFORMER_PREFIX,
@@ -36,7 +35,6 @@ from invokeai.backend.patches.lora_conversions.qwen_image_2_1_lora_conversion_ut
from invokeai.backend.patches.model_patch_raw import ModelPatchRaw
from invokeai.backend.patches.sidecar_working_memory import lora_sidecar_bytes
from invokeai.backend.quantization.dequantizing_linear import (
- DequantizingLinear,
peak_dequant_transient_bytes,
requires_sidecar_patching,
)
@@ -445,7 +443,6 @@ class QwenImage21DenoiseInvocation(BaseInvocation, WithMetadata, WithBoard):
dtype,
)
working_memory += peak_dequant_transient_bytes(transformer_info.model, dtype)
- self._refuse_dora_on_int8(context, transformer_info.model)
working_memory += self._lora_working_memory(
context,
transformer_info.model,
@@ -625,21 +622,6 @@ class QwenImage21DenoiseInvocation(BaseInvocation, WithMetadata, WithBoard):
dtype=dtype,
)
- def _refuse_dora_on_int8(self, context: InvocationContext, transformer: torch.nn.Module) -> None:
- """Fail before loading the transformer onto the device, not at the first step: a DoRA layer normalizes the
- updated weight, and an int8 Linear's packed buffers never form one (`DoRALayer.get_parameters` raises)."""
- loras = [lora for lora in self.transformer.loras if lora.weight != 0]
- if not loras:
- return
- modules = dict(transformer.named_modules())
- for lora in loras:
- for key, layer in context.models.load(lora.lora).model.layers.items():
- if isinstance(layer, DoRALayer) and isinstance(modules.get(key.partition("-")[2]), DequantizingLinear):
- raise ValueError(
- f"LoRA '{lora.lora.name}' has DoRA layers, which do not run on an int8 transformer. Use it "
- "with a Qwen-Image-2.1 transformer in another format, such as bf16, fp8 or GGUF."
- )
-
def _lora_iterator(self, context: InvocationContext) -> Iterator[PatchSpec]:
for lora in self.transformer.loras:
lora_info = context.models.load(lora.lora)
diff --git a/invokeai/backend/model_manager/configs/lora.py b/invokeai/backend/model_manager/configs/lora.py
index 599a3ff123..11db340fb6 100644
--- a/invokeai/backend/model_manager/configs/lora.py
+++ b/invokeai/backend/model_manager/configs/lora.py
@@ -919,11 +919,7 @@ _PREFIXED_QWEN_IMAGE_BLOCK_KEY_RE = re.compile(
def _has_prefixed_qwen_image_lora_keys(state_dict: dict[str | int, Any]) -> bool:
- keys = [key for key in state_dict if isinstance(key, str)]
- # PEFT DoRA magnitudes are not mapped yet (#9558): the converter would fail on every generation.
- if any(key.endswith(".lora_magnitude_vector") for key in keys):
- return False
- return any(_PREFIXED_QWEN_IMAGE_BLOCK_KEY_RE.match(key) for key in keys)
+ return any(isinstance(key, str) and _PREFIXED_QWEN_IMAGE_BLOCK_KEY_RE.match(key) for key in state_dict)
# LyCORIS' own (`lycoris_`) and ai-toolkit's (`lora_transformer_`, also OneTrainer's FLUX spelling) flattened
diff --git a/invokeai/backend/model_manager/load/model_cache/torch_module_autocast/custom_modules/custom_dequantizing_linear.py b/invokeai/backend/model_manager/load/model_cache/torch_module_autocast/custom_modules/custom_dequantizing_linear.py
index cb4c2244af..d3c51abf2f 100644
--- a/invokeai/backend/model_manager/load/model_cache/torch_module_autocast/custom_modules/custom_dequantizing_linear.py
+++ b/invokeai/backend/model_manager/load/model_cache/torch_module_autocast/custom_modules/custom_dequantizing_linear.py
@@ -7,12 +7,25 @@ from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.custo
from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.custom_modules.custom_module_mixin import (
CustomModuleMixin,
)
+from invokeai.backend.patches.layers.base_layer_patch import BaseLayerPatch
+from invokeai.backend.patches.layers.dora_layer import DoRALayer
+from invokeai.backend.patches.layers.merged_layer_patch import MergedLayerPatch
+from invokeai.backend.patches.layers.swapped_halves_layer_patch import SwappedHalvesLayerPatch
from invokeai.backend.quantization.dequantizing_linear import DequantizingLinear
from invokeai.backend.quantization.fp8_rowwise import Fp8Linear
from invokeai.backend.quantization.int8_convrot import Int4ConvrotLinear, Int8ConvrotLinear
from invokeai.backend.quantization.nvfp4 import NVFP4Linear
+def _reads_weight_values(patch: BaseLayerPatch) -> bool:
+ if isinstance(patch, SwappedHalvesLayerPatch):
+ return _reads_weight_values(patch.layer)
+ if isinstance(patch, MergedLayerPatch):
+ return any(_reads_weight_values(layer) for layer in patch.lora_layers)
+ # Only DoRA reads the original weight's values; every other layer applied to a Linear reads its shape.
+ return isinstance(patch, DoRALayer)
+
+
class CustomDequantizingLinear(DequantizingLinear, CustomModuleMixin):
"""Sidecar patches (LoRA) and device autocast for a ``DequantizingLinear``, subclassed once per scheme below.
@@ -39,10 +52,14 @@ class CustomDequantizingLinear(DequantizingLinear, CustomModuleMixin):
return tensor
def _cast_weight_bias_for_input(self, input: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor | None]:
- # A meta tensor lets patch types without an optimized sidecar path read the weight's shape but never its
- # quantized values; LoRA layers take the residual path and never get here. Patches are reshaped to this
- # shape, so it has to be the unpacked one, which the weight buffer's is not for nvfp4 or int4.
- weight = torch.empty((self.out_features, self.in_features), device="meta")
+ # Most patch types only read the weight's shape, so they get a meta tensor and no dequantization is paid
+ # for them. Patches are reshaped to this shape, so it has to be the unpacked one, which the weight buffer's
+ # is not for nvfp4 or int4. A patch that reads values (DoRA) gets the dequantized weight instead, built
+ # for this call only: it is neither stored on the module nor cached.
+ if any(_reads_weight_values(patch) for patch, _ in self._patches_and_weights):
+ weight = self._dequantized_weight(input.device, input.dtype)
+ else:
+ weight = torch.empty((self.out_features, self.in_features), device="meta")
bias = self._cast_tensor_for_input(self.bias, input)
return weight, bias
diff --git a/invokeai/backend/model_manager/load/model_loaders/lora.py b/invokeai/backend/model_manager/load/model_loaders/lora.py
index 49fbc29900..1088493133 100644
--- a/invokeai/backend/model_manager/load/model_loaders/lora.py
+++ b/invokeai/backend/model_manager/load/model_loaders/lora.py
@@ -22,6 +22,7 @@ from invokeai.backend.model_manager.taxonomy import (
SubModelType,
)
from invokeai.backend.patches.lora_conversions.anima_lora_conversion_utils import lora_model_from_anima_state_dict
+from invokeai.backend.patches.lora_conversions.dora_magnitude_keys import DORA_MAGNITUDE_SUFFIX_TO_VALUE_KEY
from invokeai.backend.patches.lora_conversions.ernie_image_lora_conversion_utils import (
lora_model_from_ernie_image_state_dict,
)
@@ -85,7 +86,7 @@ from invokeai.backend.patches.lora_conversions.sdxl_lora_conversion_utils import
from invokeai.backend.patches.lora_conversions.wan_lora_conversion_utils import lora_model_from_wan_state_dict
from invokeai.backend.patches.lora_conversions.z_image_lora_conversion_utils import lora_model_from_z_image_state_dict
-_DORA_MAGNITUDE_SUFFIXES = (".dora_scale", ".dora_magnitude", ".lora_magnitude_vector.weight", ".magnitude")
+_DORA_MAGNITUDE_SUFFIXES = (*DORA_MAGNITUDE_SUFFIX_TO_VALUE_KEY, ".dora_magnitude")
_FACTORIZED_LAYER_SUFFIXES = (".hada_w1_a", ".lokr_w1", ".lokr_w1_a")
diff --git a/invokeai/backend/patches/lora_conversions/anima_lora_conversion_utils.py b/invokeai/backend/patches/lora_conversions/anima_lora_conversion_utils.py
index 541654b122..6a275005c2 100644
--- a/invokeai/backend/patches/lora_conversions/anima_lora_conversion_utils.py
+++ b/invokeai/backend/patches/lora_conversions/anima_lora_conversion_utils.py
@@ -23,6 +23,10 @@ from invokeai.backend.patches.lora_conversions.anima_lora_constants import (
has_cosmos_dit_kohya_keys,
has_cosmos_dit_peft_keys,
)
+from invokeai.backend.patches.lora_conversions.dora_magnitude_keys import (
+ DORA_MAGNITUDE_SUFFIX_TO_VALUE_KEY,
+ DORA_MAGNITUDE_VALUE_KEYS,
+)
from invokeai.backend.patches.model_patch_raw import ModelPatchRaw
@@ -149,25 +153,20 @@ def _make_layer_patch(layer_dict: dict[str, torch.Tensor]) -> BaseLayerPatch:
return any_lora_layer_from_state_dict(layer_dict)
-# Known suffixes for Kohya format
-_KOHYA_KNOWN_SUFFIXES = [
- ".lora_A.weight",
- ".lora_B.weight",
- ".lora_down.weight",
- ".lora_up.weight",
- ".dora_scale",
- ".alpha",
-]
+# Known suffixes for Kohya format, with the value key each is stored under
+_KOHYA_KNOWN_SUFFIXES = {
+ ".lora_A.weight": "lora_A.weight",
+ ".lora_B.weight": "lora_B.weight",
+ ".lora_down.weight": "lora_down.weight",
+ ".lora_up.weight": "lora_up.weight",
+ ".alpha": "alpha",
+ **DORA_MAGNITUDE_SUFFIX_TO_VALUE_KEY,
+}
# Additional suffixes for PEFT/LoKR format
-_PEFT_EXTRA_SUFFIXES = [
- ".lokr_w1",
- ".lokr_w2",
- ".lokr_w1_a",
- ".lokr_w1_b",
- ".lokr_w2_a",
- ".lokr_w2_b",
-]
+_PEFT_EXTRA_SUFFIXES = {
+ f".{key}": key for key in ("lokr_w1", "lokr_w2", "lokr_w1_a", "lokr_w1_b", "lokr_w2_a", "lokr_w2_b")
+}
_DIFFUSERS_NON_BLOCK_KEY_MAP = {
@@ -214,7 +213,7 @@ def _convert_diffusers_transformer_key(key: str) -> str:
def _group_keys_by_layer(
state_dict: Dict[str, torch.Tensor],
- extra_suffixes: list[str] | None = None,
+ extra_suffixes: dict[str, str] | None = None,
) -> dict[str, dict[str, torch.Tensor]]:
"""Group state dict keys by layer name based on known suffixes.
@@ -227,9 +226,7 @@ def _group_keys_by_layer(
"""
layer_dict: dict[str, dict[str, torch.Tensor]] = {}
- known_suffixes = list(_KOHYA_KNOWN_SUFFIXES)
- if extra_suffixes:
- known_suffixes.extend(extra_suffixes)
+ known_suffixes = {**_KOHYA_KNOWN_SUFFIXES, **(extra_suffixes or {})}
for key in state_dict:
if not isinstance(key, str):
@@ -237,10 +234,10 @@ def _group_keys_by_layer(
layer_name = None
key_name = None
- for suffix in known_suffixes:
+ for suffix, value_key in known_suffixes.items():
if key.endswith(suffix):
layer_name = key[: -len(suffix)]
- key_name = suffix[1:] # Remove leading dot
+ key_name = value_key
break
if layer_name is None:
@@ -266,6 +263,9 @@ def _get_lora_layer_values(layer_dict: dict[str, torch.Tensor], alpha: float | N
values["alpha"] = layer_dict["alpha"]
elif alpha is not None:
values["alpha"] = torch.tensor(alpha)
+ for magnitude_key in DORA_MAGNITUDE_VALUE_KEYS:
+ if magnitude_key in layer_dict:
+ values[magnitude_key] = layer_dict[magnitude_key]
return values
elif "lora_down.weight" in layer_dict:
return layer_dict
diff --git a/invokeai/backend/patches/lora_conversions/dora_magnitude_keys.py b/invokeai/backend/patches/lora_conversions/dora_magnitude_keys.py
new file mode 100644
index 0000000000..fe12e3cbb6
--- /dev/null
+++ b/invokeai/backend/patches/lora_conversions/dora_magnitude_keys.py
@@ -0,0 +1,16 @@
+"""DoRA magnitude key suffixes shared by the lora_A/lora_B converters, mapped to the value keys ``DoRALayer`` reads.
+
+The two orientations must not be mixed up (see ``DoRALayer``):
+- ``.dora_scale`` (LyCORIS) may index either axis; ``DoRALayer`` detects which from the shape.
+- ``.lora_magnitude_vector[.weight]`` (PEFT, with or without the ``.weight`` of the wrapped parameter) and
+ ``.magnitude`` (ai-toolkit) always index the output dim.
+"""
+
+DORA_MAGNITUDE_SUFFIX_TO_VALUE_KEY = {
+ ".dora_scale": "dora_scale",
+ ".lora_magnitude_vector.weight": "dora_magnitude",
+ ".lora_magnitude_vector": "dora_magnitude",
+ ".magnitude": "dora_magnitude",
+}
+
+DORA_MAGNITUDE_VALUE_KEYS = ("dora_scale", "dora_magnitude")
diff --git a/invokeai/backend/patches/lora_conversions/ideogram4_lora_constants.py b/invokeai/backend/patches/lora_conversions/ideogram4_lora_constants.py
index 466eb50d87..95eba076cb 100644
--- a/invokeai/backend/patches/lora_conversions/ideogram4_lora_constants.py
+++ b/invokeai/backend/patches/lora_conversions/ideogram4_lora_constants.py
@@ -70,8 +70,8 @@ _NON_IDEOGRAM4_ANTI_RES = (
)
# Low-rank and LoKR parameter names the conversion builds layers from. LoHA has not been seen for this family, and
-# DoRA is refused: the sidecar wrappers of the quantized builds (GGUF, int8, fp8, nf4) hand a patch only a
-# placeholder weight, and DoRA needs the real one.
+# DoRA is refused: the conversion fuses split q/k/v layers into one low-rank layer on `qkv`, which cannot carry a
+# magnitude per projection, and nf4 builds cannot run DoRA at all (bitsandbytes weights cannot be dequantized for it).
IDEOGRAM4_LORA_PARAM_NAMES = (
"lora_A.weight",
"lora_B.weight",
diff --git a/invokeai/backend/patches/lora_conversions/qwen_image_lora_conversion_utils.py b/invokeai/backend/patches/lora_conversions/qwen_image_lora_conversion_utils.py
index bfa46a40a3..344edaf287 100644
--- a/invokeai/backend/patches/lora_conversions/qwen_image_lora_conversion_utils.py
+++ b/invokeai/backend/patches/lora_conversions/qwen_image_lora_conversion_utils.py
@@ -20,6 +20,10 @@ import torch
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.dora_magnitude_keys import (
+ DORA_MAGNITUDE_SUFFIX_TO_VALUE_KEY,
+ DORA_MAGNITUDE_VALUE_KEYS,
+)
from invokeai.backend.patches.lora_conversions.kohya_key_utils import (
INDEX_PLACEHOLDER,
ParsingTree,
@@ -182,6 +186,7 @@ def _convert_kohya_format(state_dict: Dict[str, torch.Tensor], alpha: float | No
if not isinstance(key, str):
continue
layer_name, param_name = key.split(".", 1)
+ param_name = DORA_MAGNITUDE_SUFFIX_TO_VALUE_KEY.get(f".{param_name}", param_name)
if layer_name not in grouped:
grouped[layer_name] = {}
grouped[layer_name][param_name] = value
@@ -270,9 +275,10 @@ def _normalize_lora_keys(layer_dict: dict[str, torch.Tensor], alpha: float | Non
values["alpha"] = layer_dict["alpha"]
elif alpha is not None:
values["alpha"] = torch.tensor(alpha)
- # A PEFT DoRA magnitude indexes the output dim; dropping it would apply the adapter as a plain LoRA.
- if "lora_magnitude_vector.weight" in layer_dict:
- values["dora_magnitude"] = layer_dict["lora_magnitude_vector.weight"]
+ # Dropping a DoRA magnitude would apply the adapter as a plain LoRA.
+ for magnitude_key in DORA_MAGNITUDE_VALUE_KEYS:
+ if magnitude_key in layer_dict:
+ values[magnitude_key] = layer_dict[magnitude_key]
return values
elif "lora_down.weight" in layer_dict:
return layer_dict
@@ -284,30 +290,34 @@ def _group_by_layer(state_dict: Dict[str, torch.Tensor]) -> dict[str, dict[str,
"""Group state dict keys by layer path."""
layer_dict: dict[str, dict[str, torch.Tensor]] = {}
- known_suffixes = [
- ".lora_A.weight",
- ".lora_B.weight",
- ".lora_down.weight",
- ".lora_up.weight",
- ".lora_magnitude_vector.weight",
- ".dora_scale",
- ".alpha",
- ".scalar",
+ known_suffixes = {
+ ".lora_A.weight": "lora_A.weight",
+ ".lora_B.weight": "lora_B.weight",
+ ".lora_down.weight": "lora_down.weight",
+ ".lora_up.weight": "lora_up.weight",
+ ".alpha": "alpha",
+ ".scalar": "scalar",
+ **DORA_MAGNITUDE_SUFFIX_TO_VALUE_KEY,
# LoKr and LoHa parameters
- ".lokr_w1",
- ".lokr_w1_a",
- ".lokr_w1_b",
- ".lokr_w2",
- ".lokr_w2_a",
- ".lokr_w2_b",
- ".lokr_t2",
- ".hada_w1_a",
- ".hada_w1_b",
- ".hada_w2_a",
- ".hada_w2_b",
- ".hada_t1",
- ".hada_t2",
- ]
+ **{
+ suffix: suffix[1:]
+ for suffix in (
+ ".lokr_w1",
+ ".lokr_w1_a",
+ ".lokr_w1_b",
+ ".lokr_w2",
+ ".lokr_w2_a",
+ ".lokr_w2_b",
+ ".lokr_t2",
+ ".hada_w1_a",
+ ".hada_w1_b",
+ ".hada_w2_a",
+ ".hada_w2_b",
+ ".hada_t1",
+ ".hada_t2",
+ )
+ },
+ }
for key in state_dict:
if not isinstance(key, str):
@@ -315,10 +325,10 @@ def _group_by_layer(state_dict: Dict[str, torch.Tensor]) -> dict[str, dict[str,
layer_name = None
key_name = None
- for suffix in known_suffixes:
+ for suffix, value_key in known_suffixes.items():
if key.endswith(suffix):
layer_name = key[: -len(suffix)]
- key_name = suffix[1:]
+ key_name = value_key
break
if layer_name is None:
diff --git a/invokeai/backend/patches/lora_conversions/z_image_lora_conversion_utils.py b/invokeai/backend/patches/lora_conversions/z_image_lora_conversion_utils.py
index 2a051670a3..a874a7d28f 100644
--- a/invokeai/backend/patches/lora_conversions/z_image_lora_conversion_utils.py
+++ b/invokeai/backend/patches/lora_conversions/z_image_lora_conversion_utils.py
@@ -11,6 +11,10 @@ import torch
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.dora_magnitude_keys import (
+ DORA_MAGNITUDE_SUFFIX_TO_VALUE_KEY,
+ DORA_MAGNITUDE_VALUE_KEYS,
+)
from invokeai.backend.patches.lora_conversions.z_image_lora_constants import (
Z_IMAGE_LORA_QWEN3_PREFIX,
Z_IMAGE_LORA_TRANSFORMER_PREFIX,
@@ -203,6 +207,9 @@ def _get_lora_layer_values(layer_dict: dict[str, torch.Tensor], alpha: float | N
values["alpha"] = layer_dict["alpha"]
elif alpha is not None:
values["alpha"] = torch.tensor(alpha)
+ for magnitude_key in DORA_MAGNITUDE_VALUE_KEYS:
+ if magnitude_key in layer_dict:
+ values[magnitude_key] = layer_dict[magnitude_key]
return values
elif "lora_down.weight" in layer_dict:
# Already in internal format
@@ -217,7 +224,7 @@ def _group_by_layer(state_dict: Dict[str, torch.Tensor]) -> dict[str, dict[str,
Z-Image LoRAs have keys like:
- diffusion_model.layers.17.attention.to_k.alpha
- - diffusion_model.layers.17.attention.to_k.dora_scale
+ - diffusion_model.layers.17.attention.to_k.dora_scale (or PEFT lora_magnitude_vector, ai-toolkit magnitude)
- diffusion_model.layers.17.attention.to_k.lora_down.weight
- diffusion_model.layers.17.attention.to_k.lora_up.weight
@@ -226,15 +233,15 @@ def _group_by_layer(state_dict: Dict[str, torch.Tensor]) -> dict[str, dict[str,
"""
layer_dict: dict[str, dict[str, torch.Tensor]] = {}
- # Known suffixes that indicate the end of a layer name
- known_suffixes = [
- ".lora_A.weight",
- ".lora_B.weight",
- ".lora_down.weight",
- ".lora_up.weight",
- ".dora_scale",
- ".alpha",
- ]
+ # Known suffixes that indicate the end of a layer name, with the value key each is stored under
+ known_suffixes = {
+ ".lora_A.weight": "lora_A.weight",
+ ".lora_B.weight": "lora_B.weight",
+ ".lora_down.weight": "lora_down.weight",
+ ".lora_up.weight": "lora_up.weight",
+ ".alpha": "alpha",
+ **DORA_MAGNITUDE_SUFFIX_TO_VALUE_KEY,
+ }
for key in state_dict:
if not isinstance(key, str):
@@ -243,10 +250,10 @@ def _group_by_layer(state_dict: Dict[str, torch.Tensor]) -> dict[str, dict[str,
# Try to find a known suffix
layer_name = None
key_name = None
- for suffix in known_suffixes:
+ for suffix, value_key in known_suffixes.items():
if key.endswith(suffix):
layer_name = key[: -len(suffix)]
- key_name = suffix[1:] # Remove leading dot
+ key_name = value_key
break
if layer_name is None:
diff --git a/invokeai/backend/patches/sidecar_working_memory.py b/invokeai/backend/patches/sidecar_working_memory.py
index e81ce48f65..eccf0f901b 100644
--- a/invokeai/backend/patches/sidecar_working_memory.py
+++ b/invokeai/backend/patches/sidecar_working_memory.py
@@ -74,8 +74,8 @@ def lora_sidecar_bytes(
reads the timestep embedding), with a low-rank layer's `rank` columns beside it;
- for any layer but a low-rank one, the `out_features x in_features` tensors `_SIDECAR_WEIGHT_COPIES` counts for
its kind, one more from the second such layer on the module (the running sum) and two from the third (the
- previous layer's result as well). An int8 Linear hands over only its weight's shape, so there one copy is
- counted that is not made.
+ previous layer's result as well). A dequantizing Linear hands over only its weight's shape to any layer
+ but DoRA, which reads the weight and gets it dequantized, so for the others one copy is counted that is not made.
Modules run one after another, so only the largest such update counts. On GGUF, int8 and fp8 weights every layer
is a sidecar, kept on the device: all the sidecars' tensors are counted, plus that update. Other formats merge, but
diff --git a/tests/app/invocations/test_flux3_nodes.py b/tests/app/invocations/test_flux3_nodes.py
index 53beec9aee..a2173e432a 100644
--- a/tests/app/invocations/test_flux3_nodes.py
+++ b/tests/app/invocations/test_flux3_nodes.py
@@ -285,23 +285,14 @@ def test_the_reservation_prices_the_loras_the_sampling_applies() -> None:
assert applied.reserved[0].features["lora_sidecar_bytes"] == (24 + _TOKENS * (4 + 2)) * 4
-def test_a_dora_lora_on_quantized_layers_is_refused_before_the_transformer_is_loaded() -> None:
- """A DoRA layer normalizes the updated weight, which a Linear keeping its weight in buffers never forms. Here it is
- on BFL's output modulation, whose layer comes wrapped to swap its halves."""
- transformer = _Transformer()
- transformer.norm_out.linear = Int8ConvrotLinear(torch.ones(4, 8, dtype=torch.int8), torch.ones(4, 1), False)
- apply_custom_layers_to_model(transformer)
- native = "diffusion_model.final_layer.image.adaLN_modulation.1"
- low_rank = {f"{native}.lora_A.weight": torch.zeros(2, 8), f"{native}.lora_B.weight": torch.zeros(4, 2)}
- dora = lora_model_from_flux3_state_dict(
- low_rank | {f"{native}.lora_magnitude_vector.weight": torch.ones(4)}, name=_LORA_NAME
- )
- transformer_info = _TransformerInfo(transformer)
+def test_a_dora_lora_runs_on_a_quantized_layer(monkeypatch: pytest.MonkeyPatch) -> None:
+ """A DoRA layer normalizes the updated weight, so the int8 Linear hands the sidecar its dequantized weight."""
+ monkeypatch.setattr(LayerPatcher, "_is_any_part_of_layer_on_cpu", staticmethod(lambda _module: False))
+ magnitude = torch.arange(1, 5, dtype=torch.float32) / 4
+ dora = _lora(**{"lora_A.weight": _DOWN, "lora_B.weight": _UP, "lora_magnitude_vector.weight": magnitude})
- with pytest.raises(ValueError, match=f"LoRA '{_LORA_NAME}' has DoRA layers.*quantized layers"):
- _run(transformer_info, ModelFormat.Checkpoint, {"lora": (dora, 1.0)})
- assert transformer_info.reserved == []
- # A low-rank LoRA there runs as a sidecar.
- plain = lora_model_from_flux3_state_dict(low_rank, name=_LORA_NAME)
- _run(transformer_info, ModelFormat.Checkpoint, {"lora": (plain, 1.0)})
- assert len(transformer_info.reserved) == 1
+ seen = _run(_TransformerInfo(_int8_transformer()), ModelFormat.Checkpoint, {"lora": (dora, 1.0)})
+
+ updated = torch.full((4, 8), 0.125) + _UP @ _DOWN
+ expected = (magnitude[:, None] * updated / updated.norm(dim=1, keepdim=True)) @ torch.ones(8)
+ torch.testing.assert_close(seen["out"][0], expected)
diff --git a/tests/app/invocations/test_qwen_image_2_1_nodes.py b/tests/app/invocations/test_qwen_image_2_1_nodes.py
index c32bcc46a8..03d9fc3c67 100644
--- a/tests/app/invocations/test_qwen_image_2_1_nodes.py
+++ b/tests/app/invocations/test_qwen_image_2_1_nodes.py
@@ -1480,21 +1480,27 @@ def test_a_sidecar_reserves_what_its_forward_allocates(kinds: list[str], monkeyp
assert abs(reserved - beyond_cpu - mode.peak) < weight_copy / 2, (reserved / weight_copy, mode.peak / weight_copy)
-def test_a_dora_lora_on_an_int8_transformer_is_refused_before_the_transformer_is_loaded() -> None:
+def test_a_dora_lora_runs_on_an_int8_transformer(monkeypatch: pytest.MonkeyPatch) -> None:
from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.torch_module_autocast import (
apply_custom_layers_to_model,
)
+ from invokeai.backend.patches.layer_patcher import LayerPatcher
from invokeai.backend.quantization.int8_convrot import Int8ConvrotLinear
+ monkeypatch.setattr(LayerPatcher, "_is_any_part_of_layer_on_cpu", staticmethod(lambda _module: False))
transformer = _LinearTransformer()
- weight = torch.zeros(8, 8, dtype=torch.int8)
- transformer.transformer_blocks[0].attn.to_q = Int8ConvrotLinear(weight, torch.ones(8, 1), convrot=False)
+ transformer.transformer_blocks[0].attn.to_q = Int8ConvrotLinear(
+ torch.ones(8, 8, dtype=torch.int8), torch.full((8, 1), 0.125), convrot=False
+ )
apply_custom_layers_to_model(transformer)
- low_rank = {"lora_A.weight": torch.zeros(2, 8), "lora_B.weight": torch.zeros(8, 2)}
- dora = _patch(**low_rank, **{"lora_magnitude_vector.weight": torch.ones(8)})
+ magnitude = torch.arange(1, 9, dtype=torch.float32) / 4
+ dora = _patch(
+ "transformer_blocks.0.attn.to_q",
+ **{"lora_A.weight": _DOWN, "lora_B.weight": _UP, "lora_magnitude_vector.weight": magnitude},
+ )
transformer_info = _ReservingTransformerInfo(transformer)
context = _context(_Transformer(), QwenImage21VariantType.Base)
- loaded = {"lora": SimpleNamespace(model=dora)}
+ loaded = {"lora": SimpleNamespace(model=dora, model_in_ram=nullcontext)}
context.models = SimpleNamespace(
load=lambda identifier: loaded.get(identifier.key, transformer_info),
get_config=lambda _identifier: SimpleNamespace(
@@ -1504,13 +1510,13 @@ def test_a_dora_lora_on_an_int8_transformer_is_refused_before_the_transformer_is
node = _denoise(steps=1)
node.transformer.loras.append(_lora_field(1.0))
- with pytest.raises(ValueError) as refused:
- node._run_diffusion(context)
- assert _LORA_NAME in str(refused.value) and "int8" in str(refused.value)
- assert transformer_info.reserved == []
- # A low-rank LoRA runs there as a sidecar.
- loaded["lora"] = SimpleNamespace(model=_patch(**low_rank))
- node._refuse_dora_on_int8(context, transformer)
+ node._run_diffusion(context)
+
+ # DoRA of the dequantized weight (0.125 everywhere): the updated rows, rescaled to the magnitude.
+ updated = torch.full((8, 8), 0.125) + _UP @ _DOWN
+ expected = (magnitude[:, None] * updated / updated.norm(dim=1, keepdim=True)) @ torch.ones(8)
+ torch.testing.assert_close(transformer.seen[0][1][0], expected)
+ assert len(transformer_info.reserved) == 1
def test_a_lora_already_on_the_transformer_is_not_applied_again() -> None:
diff --git a/tests/backend/model_manager/configs/test_qwen_image_lora_config.py b/tests/backend/model_manager/configs/test_qwen_image_lora_config.py
index f8db061899..6b588643df 100644
--- a/tests/backend/model_manager/configs/test_qwen_image_lora_config.py
+++ b/tests/backend/model_manager/configs/test_qwen_image_lora_config.py
@@ -14,7 +14,11 @@ import torch
from invokeai.backend.model_manager.configs.base import Config_Base
from invokeai.backend.model_manager.configs.identification_utils import NotAMatchError
from invokeai.backend.model_manager.configs.lora import LoRA_LyCORIS_FLUX_Config, LoRA_LyCORIS_QwenImage_Config
-from invokeai.backend.model_manager.taxonomy import ModelType
+from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelType
+from invokeai.backend.patches.layers.dora_layer import DoRALayer
+from invokeai.backend.patches.lora_conversions.qwen_image_lora_conversion_utils import (
+ lora_model_from_qwen_image_state_dict,
+)
# Every Linear in a Qwen-Image transformer block, with its (in, out) features.
_QWEN_IMAGE_BLOCK_LINEARS = {
@@ -226,15 +230,18 @@ def test_a_prefixed_lora_without_a_qwen_image_only_module_is_not_claimed(
LoRA_LyCORIS_QwenImage_Config.from_model_on_disk(_make_mod(path, _lora(layers)), _overrides(path))
-def test_a_prefixed_peft_dora_is_not_claimed(tmp_path: Path) -> None:
- """PEFT DoRA magnitudes are not mapped yet, so claiming the file would install a LoRA that fails to apply."""
+def test_a_prefixed_peft_dora_is_claimed_and_loads_as_dora(tmp_path: Path) -> None:
sd = _qwen_image_lora("base_model.model.")
for key in [key for key in sd if key.endswith(".lora_B.weight")]:
sd[key.removesuffix(".lora_B.weight") + ".lora_magnitude_vector"] = _z(sd[key].shape[0])
path = tmp_path / "adapter_model.safetensors"
- with pytest.raises(NotAMatchError):
- LoRA_LyCORIS_QwenImage_Config.from_model_on_disk(_make_mod(path, sd), _overrides(path))
+ config = LoRA_LyCORIS_QwenImage_Config.from_model_on_disk(_make_mod(path, sd), _overrides(path))
+
+ assert config.base == BaseModelType.QwenImage
+ layers = lora_model_from_qwen_image_state_dict(sd).layers
+ assert len(layers) == len(_QWEN_IMAGE_BLOCK_LINEARS) * 2
+ assert all(isinstance(layer, DoRALayer) for layer in layers.values())
def _lokr_layers(prefix: str, *, factorized_w1: bool = False) -> dict[str, torch.Tensor]:
diff --git a/tests/backend/model_manager/load/model_cache/torch_module_autocast/custom_modules/test_custom_dequantizing_linear_patches.py b/tests/backend/model_manager/load/model_cache/torch_module_autocast/custom_modules/test_custom_dequantizing_linear_patches.py
new file mode 100644
index 0000000000..38f503818a
--- /dev/null
+++ b/tests/backend/model_manager/load/model_cache/torch_module_autocast/custom_modules/test_custom_dequantizing_linear_patches.py
@@ -0,0 +1,296 @@
+"""Sidecar patches that read the original weight values (DoRA) on dequantizing Linears.
+
+The weight lives in packed buffers, so a patch cannot be handed it for free: the module dequantizes it once per
+forward, and only when a patch in its list reads values. Patches that read only the weight shape must not pay
+for that.
+"""
+
+import gc
+import weakref
+from collections.abc import Callable
+
+import pytest
+import torch
+import torch.nn.functional as F
+
+from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.custom_modules.custom_dequantizing_linear import (
+ CustomDequantizingLinear,
+)
+from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.torch_module_autocast import (
+ apply_custom_layers_to_model,
+)
+from invokeai.backend.patches.layer_patcher import LayerPatcher
+from invokeai.backend.patches.layers.base_layer_patch import BaseLayerPatch
+from invokeai.backend.patches.layers.dora_layer import DoRALayer
+from invokeai.backend.patches.layers.full_layer import FullLayer
+from invokeai.backend.patches.layers.loha_layer import LoHALayer
+from invokeai.backend.patches.layers.lokr_layer import LoKRLayer
+from invokeai.backend.patches.layers.lora_layer import LoRALayer
+from invokeai.backend.patches.layers.merged_layer_patch import MergedLayerPatch, Range
+from invokeai.backend.patches.layers.swapped_halves_layer_patch import SwappedHalvesLayerPatch
+from invokeai.backend.patches.model_patch_raw import ModelPatchRaw
+from invokeai.backend.quantization.dequantizing_linear import DequantizingLinear
+from invokeai.backend.quantization.fp8_rowwise import FP8_ROWWISE_WEIGHT_DTYPE, Fp8Linear
+from invokeai.backend.quantization.int8_convrot import Int4ConvrotLinear, Int8ConvrotLinear
+from invokeai.backend.quantization.nvfp4 import NVFP4Linear
+from tests.fixtures.quantized_payloads import nvfp4_signed_tensors, quantize_convrot, quantize_convrot_int4
+
+RANK = 3
+
+
+def _int8(convrot: bool) -> Callable[[], tuple[DequantizingLinear, torch.Tensor]]:
+ def build():
+ weight = torch.randn(12, 16)
+ if convrot:
+ payload = quantize_convrot(weight, group_size=4)
+ module = Int8ConvrotLinear(payload.codes, payload.scale, convrot=True, group_size=4)
+ return module, payload.dequantized
+ scale = weight.abs().amax(dim=1, keepdim=True) / 127.0
+ codes = (weight / scale).round().to(torch.int8)
+ return Int8ConvrotLinear(codes, scale, convrot=False), codes.float() * scale
+
+ return build
+
+
+def _int4():
+ payload = quantize_convrot_int4(torch.randn(24, 256))
+ return Int4ConvrotLinear(payload.packed, payload.scale, convrot=True), payload.dequantized
+
+
+def _nvfp4():
+ tensors, dense = nvfp4_signed_tensors("p", torch.rand(128, 64) > 0.5)
+ return NVFP4Linear(tensors["p.weight"], tensors["p.weight_scale"], tensors["p.weight_scale_2"]), dense
+
+
+def _fp8():
+ weight = torch.randn(12, 16)
+ scale = weight.abs().amax(dim=1) / 448.0
+ module = Fp8Linear(16, 12, bias=False, compute_dtype=torch.float32)
+ module.weight = (weight / scale.unsqueeze(1)).to(FP8_ROWWISE_WEIGHT_DTYPE)
+ module.weight_scale = scale
+ return module, module.weight.float() * scale.unsqueeze(1)
+
+
+BUILDERS = {
+ "int8_convrot": _int8(True),
+ "int8_plain": _int8(False),
+ "int4_convrot": _int4,
+ "nvfp4": _nvfp4,
+ "fp8_rowwise": _fp8,
+}
+
+
+def _wrapped(name: str) -> tuple[torch.nn.Module, torch.Tensor]:
+ torch.manual_seed(0)
+ module, dense = BUILDERS[name]()
+ model = torch.nn.Module()
+ model.proj = module
+ apply_custom_layers_to_model(model)
+ assert isinstance(model.proj, CustomDequantizingLinear)
+ return model, dense
+
+
+def _dora(out_features: int, in_features: int, *, out_axis: bool) -> DoRALayer:
+ magnitude = torch.rand(out_features) + 0.5 if out_axis else torch.rand(1, in_features) + 0.5
+ return DoRALayer(
+ up=torch.randn(out_features, RANK) * 0.3,
+ down=torch.randn(RANK, in_features) * 0.3,
+ dora_scale=magnitude * 3,
+ alpha=None,
+ bias=None,
+ magnitude_is_out_dim=out_axis,
+ )
+
+
+def _dora_delta(w: torch.Tensor, layer: DoRALayer, out_axis: bool) -> torch.Tensor:
+ """DoRA update written from the paper, independently of DoRALayer: m * (W + dW) / ||W + dW|| - W."""
+ direction = w + layer.up @ layer.down
+ if out_axis:
+ norm = torch.sqrt((direction**2).sum(dim=1, keepdim=True))
+ return layer.dora_scale.reshape(-1, 1) * direction / norm - w
+ norm = torch.sqrt((direction**2).sum(dim=0, keepdim=True))
+ return layer.dora_scale * direction / norm - w
+
+
+def _lokr(out_features: int, in_features: int) -> LoKRLayer:
+ return LoKRLayer(
+ w1=torch.randn(2, 2) * 0.2,
+ w1_a=None,
+ w1_b=None,
+ w2=torch.randn(out_features // 2, in_features // 2) * 0.2,
+ w2_a=None,
+ w2_b=None,
+ t2=None,
+ alpha=None,
+ bias=None,
+ )
+
+
+def _loha(out_features: int, in_features: int) -> LoHALayer:
+ return LoHALayer(
+ w1_a=torch.randn(out_features, RANK) * 0.3,
+ w1_b=torch.randn(RANK, in_features) * 0.3,
+ w2_a=torch.randn(out_features, RANK) * 0.3,
+ w2_b=torch.randn(RANK, in_features) * 0.3,
+ t1=None,
+ t2=None,
+ alpha=None,
+ bias=None,
+ )
+
+
+def _lora(out_features: int, in_features: int) -> LoRALayer:
+ return LoRALayer(
+ up=torch.randn(out_features, RANK) * 0.3,
+ mid=None,
+ down=torch.randn(RANK, in_features) * 0.3,
+ alpha=None,
+ bias=None,
+ )
+
+
+def _apply(model: torch.nn.Module, layers_and_weights: list[tuple[BaseLayerPatch, float]]):
+ patches = [(ModelPatchRaw(layers={"p-proj": layer}), weight) for layer, weight in layers_and_weights]
+ return LayerPatcher.apply_smart_model_patches(
+ model=model, patches=patches, prefix="p-", dtype=torch.float32, force_sidecar_patching=True
+ )
+
+
[email protected]("out_axis", [True, False], ids=["out_axis", "in_axis"])
[email protected]("name", BUILDERS)
+def test_dora_on_a_quantized_linear_equals_dora_on_its_dequantized_weight(name: str, out_axis: bool) -> None:
+ model, dense = _wrapped(name)
+ out_features, in_features = dense.shape
+ layer = _dora(out_features, in_features, out_axis=out_axis)
+ x = torch.randn(5, in_features)
+
+ with _apply(model, [(layer, 0.8)]):
+ patched = model.proj(x)
+
+ expected = F.linear(x, dense + 0.8 * _dora_delta(dense, layer, out_axis))
+ assert torch.allclose(patched, expected, atol=1e-4, rtol=1e-4)
+ assert not torch.allclose(patched, F.linear(x, dense), atol=1e-2)
+
+
[email protected]("name", BUILDERS)
+def test_dora_beside_lora_and_lokr_patches_each_see_the_original_weight(name: str) -> None:
+ model, dense = _wrapped(name)
+ out_features, in_features = dense.shape
+ dora = _dora(out_features, in_features, out_axis=True)
+ lora, lokr = _lora(out_features, in_features), _lokr(out_features, in_features)
+ x = torch.randn(5, in_features)
+
+ with _apply(model, [(dora, 0.7), (lora, 0.5), (lokr, 0.6)]):
+ patched = model.proj(x)
+
+ assert lokr.w1 is not None and lokr.w2 is not None
+ expected_weight = (
+ dense + 0.7 * _dora_delta(dense, dora, True) + 0.5 * (lora.up @ lora.down) + 0.6 * torch.kron(lokr.w1, lokr.w2)
+ )
+ assert torch.allclose(patched, F.linear(x, expected_weight), atol=1e-4, rtol=1e-4)
+
+
+def test_dora_inside_swapped_and_merged_wrappers_gets_the_weight_too() -> None:
+ model, dense = _wrapped("int8_convrot")
+ out_features, in_features = dense.shape
+ half = out_features // 2
+ x = torch.randn(5, in_features)
+
+ inner = _dora(out_features, in_features, out_axis=True)
+ with _apply(model, [(SwappedHalvesLayerPatch(inner), 1.0)]):
+ swapped = model.proj(x)
+ swapped_delta = _dora_delta(dense.roll(half, dims=0), inner, True).roll(half, dims=0)
+ assert torch.allclose(swapped, F.linear(x, dense + swapped_delta), atol=1e-4, rtol=1e-4)
+
+ top, bottom = _dora(half, in_features, out_axis=True), _dora(half, in_features, out_axis=True)
+ merged = MergedLayerPatch([top, bottom], [Range(0, half), Range(half, out_features)])
+ with _apply(model, [(merged, 1.0)]):
+ patched = model.proj(x)
+ delta = torch.cat([_dora_delta(dense[:half], top, True), _dora_delta(dense[half:], bottom, True)])
+ assert torch.allclose(patched, F.linear(x, dense + delta), atol=1e-4, rtol=1e-4)
+
+
+class _DequantSpy:
+ """Counts a module's `_dequantized_weight` calls, calling through, and weakly tracks what it returns."""
+
+ def __init__(self, module: DequantizingLinear):
+ self.calls = 0
+ self.returned: list[weakref.ref] = []
+ self.requests: list[tuple[torch.device, torch.dtype]] = []
+ original = module._dequantized_weight
+
+ def spy(device: torch.device, dtype: torch.dtype) -> torch.Tensor:
+ self.calls += 1
+ self.requests.append((device, dtype))
+ weight = original(device, dtype)
+ self.returned.append(weakref.ref(weight))
+ return weight
+
+ module._dequantized_weight = spy # type: ignore[method-assign]
+
+
[email protected]("name", ["int8_convrot", "nvfp4"])
+def test_patches_that_only_need_the_weight_shape_do_not_dequantize_it(name: str) -> None:
+ model, dense = _wrapped(name)
+ out_features, in_features = dense.shape
+ x = torch.randn(5, in_features)
+ spy = _DequantSpy(model.proj)
+ model.proj(x)
+ forward_calls = spy.calls
+
+ shape_only: list[tuple[BaseLayerPatch, float]] = [
+ (_lora(out_features, in_features), 0.5),
+ (_loha(out_features, in_features), 0.5),
+ (_lokr(out_features, in_features), 0.5),
+ (FullLayer(weight=torch.randn(out_features, in_features), bias=None), 0.5),
+ ]
+ spy.calls = 0
+ with _apply(model, shape_only):
+ model.proj(x)
+ assert spy.calls == forward_calls
+
+ spy.calls = 0
+ with _apply(model, [*shape_only, (_dora(out_features, in_features, out_axis=True), 0.5)]):
+ model.proj(x)
+ assert spy.calls == forward_calls + 1
+
+
+def test_leaving_the_patch_scope_keeps_no_dequantized_weight_and_changes_nothing() -> None:
+ model, dense = _wrapped("nvfp4")
+ out_features, in_features = dense.shape
+ module = model.proj
+ layer = _dora(out_features, in_features, out_axis=False)
+ patch_tensors = {k: v.clone() for k, v in vars(layer).items() if isinstance(v, torch.Tensor)}
+ buffers = {k: v.clone() for k, v in module.named_buffers()}
+ x = torch.randn(5, in_features)
+ unpatched = module(x)
+ attributes = set(vars(module))
+ spy = _DequantSpy(module)
+
+ with _apply(model, [(layer, 1.0)]):
+ model.proj(x)
+ del module._dequantized_weight
+ gc.collect()
+
+ assert spy.calls == 2 # the module's own forward, and the one DoRA needs
+ assert all(ref() is None for ref in spy.returned)
+ assert set(vars(module)) == attributes
+ for key, value in module.named_buffers():
+ assert value.dtype == buffers[key].dtype and value.device == buffers[key].device
+ assert torch.equal(value, buffers[key])
+ for key, value in patch_tensors.items():
+ assert torch.equal(getattr(layer, key), value)
+ assert module.get_num_patches() == 0
+ assert torch.equal(module(x), unpatched)
+
+
+def test_a_value_reading_patch_gets_the_weight_in_the_inputs_dtype_and_device() -> None:
+ model, dense = _wrapped("int8_convrot")
+ out_features, in_features = dense.shape
+ x = torch.randn(5, in_features, dtype=torch.float64)
+ spy = _DequantSpy(model.proj)
+
+ with _apply(model, [(_dora(out_features, in_features, out_axis=True), 1.0)]):
+ model.proj(x)
+
+ assert spy.requests and all(request == (x.device, torch.float64) for request in spy.requests)
diff --git a/tests/backend/model_manager/load/test_lora_loader_dora_warning.py b/tests/backend/model_manager/load/test_lora_loader_dora_warning.py
index 89f42af027..ba0abf10dd 100644
--- a/tests/backend/model_manager/load/test_lora_loader_dora_warning.py
+++ b/tests/backend/model_manager/load/test_lora_loader_dora_warning.py
@@ -22,6 +22,9 @@ def test_factorized_dora_layers_warn_once_per_lora_with_name_and_count(tmp_path,
"loha.hada_w2_a": torch.randn(6, 2),
"loha.hada_w2_b": torch.randn(2, 6),
"loha.dora_magnitude": torch.ones(6, 1),
+ "peft_lokr.lokr_w1": torch.randn(2, 2),
+ "peft_lokr.lokr_w2": torch.randn(3, 3),
+ "peft_lokr.lora_magnitude_vector": torch.ones(6),
"dora.lora_down.weight": torch.randn(2, 6),
"dora.lora_up.weight": torch.randn(6, 2),
"dora.dora_scale": torch.ones(6, 1),
@@ -42,9 +45,10 @@ def test_factorized_dora_layers_warn_once_per_lora_with_name_and_count(tmp_path,
model = loader._load_model(config) # type: ignore[arg-type]
assert isinstance(model.layers["lokr"], LoKRLayer)
+ assert isinstance(model.layers["peft_lokr"], LoKRLayer)
assert isinstance(model.layers["loha"], LoHALayer)
assert isinstance(model.layers["dora"], DoRALayer)
logger.warning.assert_called_once_with(
- "LoRA 'factorized-dora' contains 2 LoKr/LoHa layers with unsupported DoRA magnitudes; "
+ "LoRA 'factorized-dora' contains 3 LoKr/LoHa layers with unsupported DoRA magnitudes; "
"applying those layers as plain LoKr/LoHa."
)
diff --git a/tests/backend/patches/lora_conversions/test_ab_dora_magnitudes.py b/tests/backend/patches/lora_conversions/test_ab_dora_magnitudes.py
new file mode 100644
index 0000000000..054b7c0dd6
--- /dev/null
+++ b/tests/backend/patches/lora_conversions/test_ab_dora_magnitudes.py
@@ -0,0 +1,148 @@
+"""DoRA magnitudes on lora_A/lora_B layers must reach the patch for Z-Image, Qwen-Image and Anima.
+
+Each family's converter used to recognize only some magnitude key spellings and drop the rest, which applied the
+adapter as a plain LoRA. The expected patch is computed here from the DoRA paper's formula, independently of
+``DoRALayer``.
+"""
+
+import pytest
+import torch
+
+from invokeai.backend.patches.layers.dora_layer import DoRALayer
+from invokeai.backend.patches.lora_conversions.anima_lora_conversion_utils import lora_model_from_anima_state_dict
+from invokeai.backend.patches.lora_conversions.qwen_image_lora_conversion_utils import (
+ lora_model_from_qwen_image_state_dict,
+)
+from invokeai.backend.patches.lora_conversions.z_image_lora_conversion_utils import lora_model_from_z_image_state_dict
+
+OUT_FEATURES = 6
+IN_FEATURES = 4
+RANK = 2
+FILE_ALPHA = 1.0
+
+# family -> (converter, module path inside the transformer, prefixes the family accepts on a transformer layer)
+FAMILIES = {
+ "z-image": (lora_model_from_z_image_state_dict, "layers.0.attention.to_q", ("diffusion_model.", "transformer.")),
+ "anima": (lora_model_from_anima_state_dict, "blocks.0.self_attn.q_proj", ("diffusion_model.", "transformer.")),
+ "qwen-image": (
+ lora_model_from_qwen_image_state_dict,
+ "transformer_blocks.0.attn.to_q",
+ ("", "transformer.", "diffusion_model.", "base_model.model."),
+ ),
+}
+
+# magnitude key suffix -> (shape of the stored magnitude, whether it indexes the output rows)
+MAGNITUDE_KEYS = {
+ "dora_scale-out": ("dora_scale", (OUT_FEATURES, 1), True),
+ "dora_scale-in": ("dora_scale", (1, IN_FEATURES), False),
+ "lora_magnitude_vector.weight": ("lora_magnitude_vector.weight", (OUT_FEATURES,), True),
+ "lora_magnitude_vector": ("lora_magnitude_vector", (OUT_FEATURES,), True),
+ "magnitude": ("magnitude", (OUT_FEATURES,), True),
+}
+
+CASES = [
+ pytest.param(family, prefixes[0], magnitude, id=f"{family}-{magnitude}")
+ for family, (_, _, prefixes) in FAMILIES.items()
+ for magnitude in MAGNITUDE_KEYS
+]
+
+
+def _layer_values(generator: torch.Generator) -> dict[str, torch.Tensor]:
+ return {
+ "lora_A.weight": torch.randn(RANK, IN_FEATURES, generator=generator, dtype=torch.float64),
+ "lora_B.weight": torch.randn(OUT_FEATURES, RANK, generator=generator, dtype=torch.float64),
+ "alpha": torch.tensor(FILE_ALPHA, dtype=torch.float64),
+ }
+
+
+def _expected_patch(
+ weight: torch.Tensor, a: torch.Tensor, b: torch.Tensor, magnitude: torch.Tensor, out_axis: bool
+) -> torch.Tensor:
+ """W' - W for W' = m * (W + s*B@A) / ||W + s*B@A||, the norm taken per output row or per input column."""
+ direction = weight + (FILE_ALPHA / RANK) * (b @ a)
+ if out_axis:
+ norm = torch.sqrt((direction**2).sum(dim=1, keepdim=True))
+ return magnitude.reshape(OUT_FEATURES, 1) * direction / norm - weight
+ norm = torch.sqrt((direction**2).sum(dim=0, keepdim=True))
+ return magnitude.reshape(1, IN_FEATURES) * direction / norm - weight
+
+
[email protected](("family", "prefix", "magnitude_case"), CASES)
+def test_ab_dora_magnitude_becomes_a_dora_layer_that_applies_it(family: str, prefix: str, magnitude_case: str):
+ convert, module, _ = FAMILIES[family]
+ suffix, shape, out_axis = MAGNITUDE_KEYS[magnitude_case]
+ generator = torch.Generator().manual_seed(0)
+ values = _layer_values(generator)
+ magnitude = torch.rand(shape, generator=generator, dtype=torch.float64) + 0.5
+ state_dict = {f"{prefix}{module}.{name}": tensor for name, tensor in values.items()}
+ state_dict[f"{prefix}{module}.{suffix}"] = magnitude
+
+ model = convert(state_dict, alpha=None)
+
+ assert len(model.layers) == 1
+ layer = next(iter(model.layers.values()))
+ assert isinstance(layer, DoRALayer)
+ assert layer.magnitude_is_out_dim == out_axis
+ assert layer.scale() == FILE_ALPHA / RANK
+ weight = torch.randn(OUT_FEATURES, IN_FEATURES, generator=generator, dtype=torch.float64)
+ patched = layer.get_parameters({"weight": weight}, weight=1.0)["weight"]
+ expected = _expected_patch(weight, values["lora_A.weight"], values["lora_B.weight"], magnitude, out_axis)
+ torch.testing.assert_close(patched, expected)
+
+
+ ("family", "prefix"),
+ [
+ pytest.param(family, prefix, id=f"{family}-{prefix or 'bare'}")
+ for family, (_, _, p) in FAMILIES.items()
+ for prefix in p
+ ],
+)
+def test_every_key_prefix_is_stripped_to_the_same_dora_layer_key(family: str, prefix: str):
+ convert, module, _ = FAMILIES[family]
+ generator = torch.Generator().manual_seed(2)
+ state_dict = {f"{prefix}{module}.{name}": tensor for name, tensor in _layer_values(generator).items()}
+ state_dict[f"{prefix}{module}.magnitude"] = torch.ones(OUT_FEATURES, dtype=torch.float64)
+ bare = {key.removeprefix(prefix): value for key, value in state_dict.items()}
+
+ layers = convert(state_dict, alpha=None).layers
+
+ assert isinstance(next(iter(layers.values())), DoRALayer)
+ assert layers.keys() == convert(bare, alpha=None).layers.keys()
+
+
[email protected]("family", FAMILIES)
+def test_caller_alpha_applies_to_a_dora_layer_without_a_file_alpha(family: str):
+ convert, module, (prefix, *_) = FAMILIES[family]
+ generator = torch.Generator().manual_seed(1)
+ values = _layer_values(generator)
+ del values["alpha"]
+ state_dict = {f"{prefix}{module}.{name}": tensor for name, tensor in values.items()}
+ state_dict[f"{prefix}{module}.magnitude"] = torch.ones(OUT_FEATURES, dtype=torch.float64)
+
+ layer = next(iter(convert(state_dict, alpha=4.0).layers.values()))
+
+ assert isinstance(layer, DoRALayer)
+ assert layer.scale() == 4.0 / RANK
+
+
+ ("convert", "layer_name"),
+ [
+ (lora_model_from_z_image_state_dict, "lora_unet__layers_0_attention_to_q"),
+ (lora_model_from_anima_state_dict, "lora_unet_blocks_0_self_attn_q_proj"),
+ (lora_model_from_qwen_image_state_dict, "lora_unet_transformer_blocks_0_attn_to_q"),
+ ],
+ ids=["z-image", "anima", "qwen-image"],
+)
+def test_kohya_dora_scale_stays_a_dora_layer(convert, layer_name: str):
+ state_dict = {
+ f"{layer_name}.lora_down.weight": torch.zeros(RANK, IN_FEATURES),
+ f"{layer_name}.lora_up.weight": torch.zeros(OUT_FEATURES, RANK),
+ f"{layer_name}.dora_scale": torch.ones(OUT_FEATURES, 1),
+ }
+
+ layers = convert(state_dict, alpha=None).layers
+
+ assert len(layers) == 1
+ assert isinstance(next(iter(layers.values())), DoRALayer)
diff --git a/tests/backend/patches/lora_conversions/test_qwen_image_lora_conversion_utils.py b/tests/backend/patches/lora_conversions/test_qwen_image_lora_conversion_utils.py
index 727c8314b2..44c4cf712a 100644
--- a/tests/backend/patches/lora_conversions/test_qwen_image_lora_conversion_utils.py
+++ b/tests/backend/patches/lora_conversions/test_qwen_image_lora_conversion_utils.py
@@ -169,24 +169,6 @@ def test_kohya_all_unknown_submodules_produces_empty_model():
assert len(model.layers) == 0
-def test_peft_dora_magnitude_is_kept_as_a_dora_layer():
- """A PEFT DoRA adapter must load as DoRA: dropping `lora_magnitude_vector` would silently apply a plain LoRA."""
- from invokeai.backend.patches.layers.dora_layer import DoRALayer
-
- magnitude = torch.rand(3072)
- state_dict = {
- "base_model.model.transformer_blocks.0.attn.to_k.lora_A.weight": torch.empty(64, 3072),
- "base_model.model.transformer_blocks.0.attn.to_k.lora_B.weight": torch.empty(3072, 64),
- "base_model.model.transformer_blocks.0.attn.to_k.lora_magnitude_vector.weight": magnitude,
- }
- model = lora_model_from_qwen_image_state_dict(state_dict, alpha=None)
-
- layer = model.layers[f"{QWEN_IMAGE_EDIT_LORA_TRANSFORMER_PREFIX}transformer_blocks.0.attn.to_k"]
- assert isinstance(layer, DoRALayer)
- assert layer.magnitude_is_out_dim
- assert torch.equal(layer.dora_scale, magnitude)
-
-
# ---- LyCORIS layouts: lycoris_ / ai-toolkit's lora_transformer_ prefixes, dotted LoKr/LoHa, scalar ----
_ATTENTION_MODULES = (