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 fused QKV DoRA on both magnitude axes (#10193)

Nianze Wu588d68757275
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 8fbf642c79..56ff8af3dd 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
@@ -270,6 +270,13 @@ because Qwen-Image and SD 3 name some of them alike. On FLUX.2 the guidance embe
For SD 1.x / 2.x and FLUX.2, LyCORIS LoKr files may store either Kronecker operand whole or as a
factorized `_a` / `_b` pair. FLUX.2 also accepts LoHA files in the same BFL and kohya layouts.
+FLUX.2 BFL and kohya DoRA adapters on fused image/text QKV projections support input-axis and output-axis
+magnitudes. Output-axis DoRA also works on supported FLUX.2 int8 checkpoints. Input-axis
+normalization uses all Q, K and V rows together and requires ordinary floating-point weights, including
+native FP8 storage; on packed modules and GGUF/SDNQ tensor subclasses, the fused group is skipped with a
+warning while the adapter's other supported layers apply. See the
+[FLUX.2 LoRA notes](/users-guide/models/local-models/flux-2/#lora).
+
Qwen-Image LoRAs, LoKR and LoHA files also load in ComfyUI's `diffusion_model.` key layout, as raw PEFT adapters
(`base_model.model.`), and in the LyCORIS `lycoris_transformer_blocks_…` and ai-toolkit
`lora_transformer_transformer_blocks_…` layouts, when they train the blocks' modulation or MLP layers; see the
diff --git a/docs/src/content/docs/Users Guide/03.Models/Local Models/flux-2.mdx b/docs/src/content/docs/Users Guide/03.Models/Local Models/flux-2.mdx
index 417893f9ae..53db812040 100644
--- a/docs/src/content/docs/Users Guide/03.Models/Local Models/flux-2.mdx
+++ b/docs/src/content/docs/Users Guide/03.Models/Local Models/flux-2.mdx
@@ -1,7 +1,7 @@
---
title: FLUX.2
description: Generate and edit images with FLUX.2 Klein (4B and 9B, distilled and Base) and FLUX.2 [dev], including multi-reference image editing and the FLUX.2 [dev] Fun-ControlNet-Union.
-lastUpdated: 2026-11-02
+lastUpdated: 2026-11-07
sidebar:
order: 5
---
@@ -215,6 +215,19 @@ or as a factorized `_a` / `_b` pair. kohya LoRAs that also train layers outside
`txt_in`, the time embedder, the guidance embedder of FLUX.2 [dev], the last layer and the shared modulations) are
supported, as long as they train at least one block.
+For BFL and kohya DoRA adapters, fused image/text QKV projections support both input-axis magnitudes
+(`dora_scale` shaped `(1, in_features)`, including one-dimensional vectors) and output-axis magnitudes
+(`(out_features, 1)`) with dense floating-point base weights, including native FP8 storage. Input-axis
+normalization uses all Q, K and V base rows together before applying strength. OneTrainer uses the input
+axis by default; its **Apply on output axis (DoRA Only)** setting is off by default. Both orientations
+preserve their normalization when Q, K and V are split, including when the fused weight is square.
+
+Output-axis DoRA also works on supported FLUX.2 int8 checkpoints. For fused QKV
+input-axis DoRA, the shared norm currently requires ordinary floating-point Q/K/V weights (including native
+FP8 storage). For packed modules and GGUF or SDNQ tensor subclasses, the fused QKV group is skipped with a
+warning and the adapter's other supported layers still apply. Use ordinary floating-point Q/K/V weights
+to apply the fused input-axis group.
+
## PiD super-resolution decode
FLUX.2 Klein latents can be decoded with a PiD decoder for a 4× super-resolved image. Install *PiD Decoder
diff --git a/invokeai/app/invocations/flux2/flux2_denoise.py b/invokeai/app/invocations/flux2/flux2_denoise.py
index d1dc25ae08..eed29b85fa 100644
--- a/invokeai/app/invocations/flux2/flux2_denoise.py
+++ b/invokeai/app/invocations/flux2/flux2_denoise.py
@@ -3,9 +3,10 @@
Run denoising process with a FLUX.2 transformer model: Klein (Qwen3 conditioning) or [dev] (Mistral conditioning).
"""
+import copy
from contextlib import ExitStack
from functools import partial
-from typing import Any, Callable, Iterator, Optional, Tuple
+from typing import Any, Callable, Optional, Tuple
import torch
import torch.nn.functional as F
@@ -39,7 +40,10 @@ from invokeai.app.services.shared.invocation_context import InvocationContext
from invokeai.backend.flux.sampling_utils import clip_timestep_schedule_fractional
from invokeai.backend.flux.schedulers import FLUX_SCHEDULER_LABELS, FLUX_SCHEDULER_MAP, FLUX_SCHEDULER_NAME_VALUES
from invokeai.backend.flux2.denoise import denoise
-from invokeai.backend.flux2.denoise_working_memory import estimate_flux2_denoise_working_memory
+from invokeai.backend.flux2.denoise_working_memory import (
+ estimate_flux2_denoise_working_memory,
+ flux2_dora_patch_bytes,
+)
from invokeai.backend.flux2.extensions.regional_prompting_extension import Flux2RegionalPromptingExtension
from invokeai.backend.flux2.latent_norm import bn_denormalize, bn_normalize, read_vae_bn_stats
from invokeai.backend.flux2.ref_image_extension import Flux2RefImageExtension
@@ -59,7 +63,7 @@ from invokeai.backend.fun_controlnet.hooks import FunControlHooks, install_fun_c
from invokeai.backend.model_manager.configs.flux2_variant import flux2_hidden_size
from invokeai.backend.model_manager.load.load_base import LoadedModel
from invokeai.backend.model_manager.taxonomy import BaseModelType, Flux2VariantType, ModelType
-from invokeai.backend.patches.layer_patcher import LayerPatcher, PatchSpec
+from invokeai.backend.patches.layer_patcher import LayerPatcher
from invokeai.backend.patches.lora_conversions.flux_bfl_peft_lora_conversion_utils import (
convert_bfl_lora_patch_to_diffusers,
)
@@ -482,6 +486,10 @@ class Flux2DenoiseInvocation(BaseInvocation, WithMetadata):
with ExitStack() as exit_stack:
transformer_info = context.models.load(self.transformer.transformer)
+ # Cold adapter loads can take the global model-load write lock. Finish them before
+ # moving the transformer and before the patcher takes the read lock.
+ lora_patches = self._materialize_lora_patches(context, exit_stack)
+ text_seq_len = max(txt.shape[1], neg_txt.shape[1] if neg_txt is not None else 0)
# Ask the model cache to keep free what the transformer forward needs. Without it the cache keeps only
# the default working memory and fills the rest of the card with the model, so anything beyond a plain
@@ -497,13 +505,19 @@ class Flux2DenoiseInvocation(BaseInvocation, WithMetadata):
hidden_size=flux2_hidden_size(getattr(transformer_config, "variant", None)) or FLUX2_MAX_HIDDEN_SIZE,
image_seq_len=packed_h * packed_w,
ref_image_seq_len=ref_image_seq_len,
- text_seq_len=max(txt.shape[1], neg_txt.shape[1] if neg_txt is not None else 0),
+ text_seq_len=text_seq_len,
# Taken from `x`, not from `b`. `b` is the *noise* tensor's batch, which this node builds at 1 from
# width/height/seed even when the init latents carry more; the img2img preblend above then
# broadcasts the two, so `x` is the only thing that knows how many samples actually go through the
# transformer. Reference latents are repeated to match it (`ensure_batch_size` below).
batch_size=x.shape[0],
- lora_count=len(self.transformer.loras),
+ lora_count=len(lora_patches),
+ dora_patch_bytes=flux2_dora_patch_bytes(
+ transformer_info.model,
+ lora_patches,
+ dtype=inference_dtype,
+ rows=(image_seq_len + ref_image_seq_len + text_seq_len) * x.shape[0],
+ ),
control_blocks=len(control_branch_info.model.control_blocks) if control_branch_info is not None else 0,
# The additive bias is skipped entirely when reference images are present (see below), so the mask
# only costs anything without them.
@@ -554,7 +568,7 @@ class Flux2DenoiseInvocation(BaseInvocation, WithMetadata):
exit_stack.enter_context(
LayerPatcher.apply_smart_model_patches(
model=transformer,
- patches=self._lora_iterator(context),
+ patches=lora_patches,
prefix=FLUX_LORA_TRANSFORMER_PREFIX,
dtype=inference_dtype,
cached_weights=cached_weights,
@@ -768,18 +782,25 @@ class Flux2DenoiseInvocation(BaseInvocation, WithMetadata):
out.append(Flux2TextConditioning(txt_embeddings=info.t5_embeds, mask=mask_processed))
return out
- def _lora_iterator(self, context: InvocationContext) -> Iterator[PatchSpec]:
- """Iterate over LoRA models to apply.
+ def _materialize_lora_patches(
+ self, context: InvocationContext, stack: ExitStack
+ ) -> list[tuple[ModelPatchRaw, float]]:
+ """Load and RAM-pin the LoRAs through patch restoration and transformer unlock.
Converts BFL-format LoRA keys to diffusers format if needed, since FLUX.2 Klein
uses Flux2Transformer2DModel (diffusers naming) but LoRAs may have been loaded
with BFL naming (e.g. when a Klein 4B LoRA is misidentified as FLUX.1).
"""
+ patches = []
for lora in self.transformer.loras:
- lora_info = context.models.load(lora.lora)
- assert isinstance(lora_info.model, ModelPatchRaw)
- converted = convert_bfl_lora_patch_to_diffusers(lora_info.model)
- yield (converted, lora.weight, lora_info.model_in_ram())
+ adapter = stack.enter_context(context.models.load(lora.lora).model_in_ram())
+ assert isinstance(adapter, ModelPatchRaw)
+ converted = convert_bfl_lora_patch_to_diffusers(adapter)
+ # Copy patch objects, including wrapper leaves, per application; their tensors remain shared
+ # until a patch's `to()` rebinds them. The cached objects must not be moved by patching.
+ local = ModelPatchRaw({key: copy.copy(layer) for key, layer in converted.layers.items()})
+ patches.append((local, lora.weight))
+ return patches
def _build_step_callback(self, context: InvocationContext) -> Callable[[PipelineIntermediateState], None]:
"""Build a callback for step progress updates."""
diff --git a/invokeai/backend/flux2/denoise_working_memory.py b/invokeai/backend/flux2/denoise_working_memory.py
index 10a7cfc2f5..268e61d048 100644
--- a/invokeai/backend/flux2/denoise_working_memory.py
+++ b/invokeai/backend/flux2/denoise_working_memory.py
@@ -89,19 +89,26 @@ The analytic terms:
text stream of their own, but `add_hint` touches only `hidden_states`. `n + 4` hint-sized tensors (batch x image
stream x width x element size) are charged for `n` blocks, the coefficient the Z-Image estimator measured for its
adapter over the plain forward. It is not measured for FLUX.2.
-- Half a GiB per LoRA and sample: a sidecar patch adds an activation branch per patched layer.
+- Half a GiB per LoRA and sample for the existing sidecar activation allowance. DoRA additionally prices
+ its factors and its largest projection or norm pass from the loaded adapter shapes.
- The dequantization copy an int8_tensorwise, nvfp4 or GGUF build materializes per quantized linear and forward,
alive alongside the activations and invisible to them (`peak_dequant_transient_bytes`); zero for every other build.
- The compute-dtype copies of a layer's float8-stored weights that FP8 Storage, or a kept fp8 checkpoint, widens per
forward (`peak_fp8_cast_transient_bytes`); zero for every other build.
"""
-from collections.abc import Mapping
+from collections.abc import Iterable, Mapping
from typing import Final, Optional, cast
import torch
-from invokeai.backend.quantization.dequantizing_linear import peak_dequant_transient_bytes
+from invokeai.backend.patches.layer_patcher import LayerPatcher
+from invokeai.backend.patches.layers.dora_layer import DoRALayer
+from invokeai.backend.patches.layers.fused_input_dora_layer import FusedInputDoRALayer
+from invokeai.backend.patches.layers.swapped_halves_layer_patch import SwappedHalvesLayerPatch
+from invokeai.backend.patches.lora_conversions.flux_lora_constants import FLUX_LORA_TRANSFORMER_PREFIX
+from invokeai.backend.patches.model_patch_raw import ModelPatchRaw
+from invokeai.backend.quantization.dequantizing_linear import DequantizingLinear, peak_dequant_transient_bytes
from invokeai.backend.util.attention import sdpa_score_matrix_bytes
from invokeai.backend.util.calc_tensor_size import largest_module_bytes
from invokeai.backend.util.fp8 import peak_fp8_cast_transient_bytes
@@ -177,6 +184,7 @@ def _terms(features: Mapping[str, FeatureValue], values: Mapping[str, float]) ->
# mask: zero is what such a point streams and pads, though a forward the node prices now always carries them.
streamed_layer_bytes = cast(int, features.get("streamed_layer_bytes", 0))
padded_bias_bytes = cast(int, features.get("padded_bias_bytes", 0))
+ dora_patch_bytes = cast(int, features.get("dora_patch_bytes", 0))
return (
WorkingMemoryTerm.fitted("activations", f"k_{suffix}", cast(int, features["tokens"]) * batch, values),
WorkingMemoryTerm.fitted("base", f"b_{suffix}", 1, values),
@@ -186,11 +194,130 @@ def _terms(features: Mapping[str, FeatureValue], values: Mapping[str, float]) ->
WorkingMemoryTerm("attention_scores", cast(int, features["score_matrix_bytes"]), True),
WorkingMemoryTerm("control_hints", hint_bytes, True),
WorkingMemoryTerm("lora_patches", cast(int, features["lora_count"]) * batch * _LORA_PATCH_BYTES, True),
+ *((WorkingMemoryTerm("dora_patches", dora_patch_bytes, True),) if dora_patch_bytes else ()),
WorkingMemoryTerm("dequant_transient", cast(int, features["dequant_transient_bytes"]), True),
WorkingMemoryTerm("fp8_cast_transient", cast(int, features["fp8_cast_transient_bytes"]), True),
)
+def flux2_dora_patch_bytes(
+ transformer: torch.nn.Module,
+ patches: Iterable[tuple[ModelPatchRaw, float]],
+ *,
+ dtype: torch.dtype,
+ rows: int,
+) -> int:
+ """Bound DoRA's explicit tensor allocations before transformer residency is decided.
+
+ A patch can be merged or run as a sidecar depending on placement. Allow all DoRA factors
+ (and the bound norms) to coexist on the device, including the per-projection copies of shared
+ factors. Only one projection is binding, applying, or running at a time. The legacy LoRA term
+ remains in place for other patch types. The bound counts tensors visible to PyTorch.
+ """
+ retained = 0
+ scratch = 0
+ for patch, strength in patches:
+ if strength == 0:
+ continue
+ flattened = not any("." in key for key in patch.layers)
+ for key, layer in patch.layers.items():
+ if not key.startswith(FLUX_LORA_TRANSFORMER_PREFIX):
+ continue
+ if isinstance(layer, FusedInputDoRALayer):
+ try:
+ modules = [transformer.get_submodule(name) for name in layer.keys]
+ except AttributeError:
+ continue # The patcher skips an incomplete group.
+ if not all(isinstance(module, torch.nn.Linear) for module in modules):
+ continue # The patcher warns and skips unsupported fused groups.
+
+ dora = layer.layer
+ vector_bytes = dora.down.shape[1] * torch.float32.itemsize
+ retained += (
+ _patch_tensor_bytes((dora.up,), dtype)
+ + (
+ dora.bias.numel() * max(dora.bias.element_size(), dtype.itemsize)
+ if dora.bias is not None
+ else 0
+ )
+ + len(modules) * (_patch_tensor_bytes((dora.down, dora.dora_scale), dtype) + vector_bytes)
+ )
+ for module in modules:
+ scratch = max(
+ scratch,
+ layer.binding_workspace_bytes(module, dtype),
+ _dora_projection_workspace_bytes(module, dora, dtype, rows, fused=True),
+ )
+ continue
+
+ wrapped = isinstance(layer, SwappedHalvesLayerPatch)
+ dora = layer.layer if wrapped else layer
+ if not isinstance(dora, DoRALayer):
+ continue
+ try:
+ _, module = LayerPatcher._get_submodule(
+ transformer, key.removeprefix(FLUX_LORA_TRANSFORMER_PREFIX), layer_key_is_flattened=flattened
+ )
+ except AttributeError:
+ continue
+ if not isinstance(module, (torch.nn.Linear, DequantizingLinear)):
+ continue
+ retained += _patch_tensor_bytes(
+ (dora.up, dora.down, dora.dora_scale, dora.bias, dora.direction_norm), dtype
+ )
+ scratch = max(scratch, _dora_projection_workspace_bytes(module, dora, dtype, rows, wrapped=wrapped))
+ return retained + scratch
+
+
+def _patch_tensor_bytes(tensors: Iterable[torch.Tensor | None], dtype: torch.dtype) -> int:
+ """The larger of a patch tensor's stored and streamed sizes."""
+ size = 0
+ for tensor in tensors:
+ if tensor is None:
+ continue
+ if tensor.is_sparse:
+ size += tensor._indices().nbytes
+ tensor = tensor._values()
+ size += tensor.numel() * max(tensor.element_size(), dtype.itemsize)
+ return size
+
+
+def _dora_projection_workspace_bytes(
+ module: torch.nn.Linear | DequantizingLinear,
+ layer: DoRALayer,
+ dtype: torch.dtype,
+ rows: int,
+ *,
+ wrapped: bool = False,
+ fused: bool = False,
+) -> int:
+ in_features, out_features = module.in_features, module.out_features
+ # Packed linears form the dense, inference-dtype base in the sidecar. Their backing payload
+ # can have a different shape and element width from the LoRA target.
+ base_bytes = module.weight.element_size() if isinstance(module, torch.nn.Linear) else dtype.itemsize
+ compute_dtype_bytes = max(torch.float32.itemsize, base_bytes, dtype.itemsize)
+ # In get_weight: widened base, scaled direction delta, direction, and residual. During a
+ # sidecar forward the base cast and running sum or prior update can also be live. The same
+ # space covers direct apply's dtype conversion and out-of-place replacement.
+ # Wrapper layouts can keep an extra weight from reordering or building the merged residual.
+ dense_bytes = (7 + 2 * wrapped) * in_features * out_features * compute_dtype_bytes
+ # Factor promotion is per projection. Fused input DoRA keeps its stored dtype and promotes
+ # only for the math; ordinary DoRA may move first and allocate the FP32 factors on-device.
+ if fused:
+ factor_bytes = (
+ _patch_tensor_bytes((layer.up,), torch.float32) // 3
+ + _patch_tensor_bytes((layer.down, layer.dora_scale), torch.float32)
+ + (layer.bias.numel() * torch.float32.itemsize // 3 if layer.bias is not None else 0)
+ )
+ else:
+ factor_bytes = _patch_tensor_bytes((layer.up, layer.down, layer.dora_scale, layer.bias), torch.float32)
+ # A streamed FP8 base can expand its scales with index tensors, and broadcasting a magnitude
+ # or applying a bias can hold extra input/output-width vectors.
+ vector_bytes = (in_features + out_features) * (2 * torch.int64.itemsize + 4 * compute_dtype_bytes)
+ output_bytes = rows * out_features * dtype.itemsize
+ return dense_bytes + factor_bytes + vector_bytes + output_bytes
+
+
def _padded_bias_bytes(mask: Optional[torch.Tensor], dtype: torch.dtype) -> int:
"""One sample's copy of the additive bias in `dtype`, its last dimension padded to `_BIAS_ALIGNMENT`; 0 without one."""
if mask is None:
@@ -221,6 +348,7 @@ def estimate_flux2_denoise_working_memory(
text_seq_len: int,
batch_size: int,
lora_count: int,
+ dora_patch_bytes: int = 0,
control_blocks: int = 0,
regional_attn_mask: Optional[torch.Tensor] = None,
weights_resident: bool = False,
@@ -272,4 +400,6 @@ def estimate_flux2_denoise_working_memory(
"dequant_transient_bytes": peak_dequant_transient_bytes(transformer, dtype),
"fp8_cast_transient_bytes": peak_fp8_cast_transient_bytes(transformer, dtype),
}
+ if dora_patch_bytes:
+ features["dora_patch_bytes"] = dora_patch_bytes
return FLUX2_DENOISE_SPEC.estimate(features, device)
diff --git a/invokeai/backend/patches/layer_patcher.py b/invokeai/backend/patches/layer_patcher.py
index 8e183b0728..6d6d0cb439 100644
--- a/invokeai/backend/patches/layer_patcher.py
+++ b/invokeai/backend/patches/layer_patcher.py
@@ -2,7 +2,7 @@ import re
from collections import Counter
from contextlib import AbstractContextManager, ExitStack, contextmanager
from itertools import chain
-from typing import Dict, Iterable, Optional, Tuple
+from typing import Dict, Iterable, Iterator, Optional, Tuple
import torch
from transformers import CLIPTextModel
@@ -10,6 +10,7 @@ from transformers import CLIPTextModel
from invokeai.backend.model_manager.load.model_cache.model_cache import MODEL_LOAD_LOCK
from invokeai.backend.patches.layers.base_layer_patch import BaseLayerPatch, sub_patches
from invokeai.backend.patches.layers.flux_control_lora_layer import FluxControlLoRALayer
+from invokeai.backend.patches.layers.fused_input_dora_layer import FusedInputDoRALayer, UnsupportedFusedInputDoRABase
from invokeai.backend.patches.model_patch_raw import ModelPatchRaw
from invokeai.backend.patches.pad_with_zeros import pad_with_zeros
from invokeai.backend.util import InvokeAILogger
@@ -162,7 +163,45 @@ class LayerPatcher:
prefix_len = len(prefix)
+ # Bind all projections before changing any of this adapter's weights. The temporary split
+ # patches own the norm; the CPU-cached adapter remains independent of model and generation.
+ layers: dict[str, BaseLayerPatch] = {}
for layer_key, layer in patch.layers.items():
+ if layer_key.startswith(prefix) and isinstance(layer, FusedInputDoRALayer):
+ # A fused input-axis norm cannot be calculated from a partial group. Check lookup separately
+ # from bind so an AttributeError in the numerical code is not mistaken for a missing target.
+ missing_key = None
+ for key in layer.keys:
+ try:
+ model.get_submodule(key)
+ except AttributeError:
+ missing_key = f"{prefix}{key}"
+ break
+ if missing_key is not None:
+ if not (suppress_warning_layers and suppress_warning_layers.search(missing_key)):
+ logger = InvokeAILogger.get_logger(LayerPatcher.__name__)
+ logger.warning("Failed to find module for LoRA layer key: %s", missing_key)
+ continue
+ base_dtypes = tuple(
+ dtype
+ if LayerPatcher._uses_sidecar(
+ model.get_submodule(key), force_direct_patching, force_sidecar_patching
+ )
+ else None
+ for key in layer.keys
+ )
+ try:
+ bound = layer.bind(model, base_dtypes)
+ except UnsupportedFusedInputDoRABase as error:
+ logger = InvokeAILogger.get_logger(LayerPatcher.__name__)
+ logger.warning("Skipping fused input-axis DoRA group '%s': %s", layer_key, error)
+ continue
+ for key, split_layer in bound:
+ layers[f"{prefix}{key}"] = split_layer
+ else:
+ layers[layer_key] = layer
+
+ for layer_key, layer in layers.items():
if not layer_key.startswith(prefix):
continue
@@ -189,25 +228,7 @@ class LayerPatcher:
# and that the caller will set force_sidecar_patching=True if the layer is quantized.
# TODO(ryand): Handle the case where we are running without a GPU. Should we set a config flag that allows
# forcing full patching even on the CPU?
- use_sidecar_patching = False
- if force_direct_patching and force_sidecar_patching:
- raise ValueError("Cannot force both direct and sidecar patching.")
- elif force_sidecar_patching:
- use_sidecar_patching = True
- elif LayerPatcher._is_any_part_of_layer_fp8(module):
- # FP8 weights (e.g. a model loaded with fp8_storage layerwise casting) cannot be
- # directly patched: _apply_model_layer_patch does an in-place add on the model weight,
- # and CUDA has no add kernel for float8 ("ufunc_add_CUDA not implemented for
- # Float8_e4m3fn"). Sidecar patching dequantizes to the compute dtype before any math,
- # so it works regardless of the storage dtype. This takes precedence over
- # force_direct_patching, since direct patching is simply not possible on fp8 weights.
- use_sidecar_patching = True
- elif force_direct_patching:
- use_sidecar_patching = False
- elif module.get_num_patches() > 0:
- use_sidecar_patching = True
- elif LayerPatcher._is_any_part_of_layer_on_cpu(module):
- use_sidecar_patching = True
+ use_sidecar_patching = LayerPatcher._uses_sidecar(module, force_direct_patching, force_sidecar_patching)
if use_sidecar_patching:
LayerPatcher._apply_model_layer_wrapper_patch(
@@ -229,6 +250,16 @@ class LayerPatcher:
shared_storage=shared_storage,
)
+ @staticmethod
+ def _uses_sidecar(module: torch.nn.Module, force_direct: bool, force_sidecar: bool) -> bool:
+ if force_direct and force_sidecar:
+ raise ValueError("Cannot force both direct and sidecar patching.")
+ if force_sidecar or LayerPatcher._is_any_part_of_layer_fp8(module):
+ return True
+ if force_direct:
+ return False
+ return module.get_num_patches() > 0 or LayerPatcher._is_any_part_of_layer_on_cpu(module)
+
@staticmethod
def _storage_ptr(tensor: torch.Tensor) -> int:
"""The address of the tensor's storage, or 0 when it has none to read (meta, sparse, quantized subclasses)."""
@@ -305,11 +336,12 @@ class LayerPatcher:
# be significantly faster for 16-bit CPU tensors being moved to a CUDA device than doing the
# same thing in a single call to '.to(...)'.
#
- # `patch` is the model cache's own object, not a copy, and `BaseLayerPatch.to()` rebinds its
- # tensors in place -- so whatever is done here outlives the patch and is what the cache is
- # left holding. Both moves are undone in the `finally` below, also on the early return and
- # when a move, `get_parameters` or the weight update raises.
- leaf_placements = LayerPatcher._leaf_placements(patch)
+ # to() rebinds a leaf's tensors. Keep the original references so that restoring a
+ # cache-owned patch or a shallow application copy needs no transfers or new buffers.
+ original_tensors = [
+ (leaf, {name: value for name, value in vars(leaf).items() if isinstance(value, torch.Tensor)})
+ for leaf in LayerPatcher._patch_leaves(patch)
+ ]
try:
patch.to(device=device)
patch.to(dtype=torch.float32)
@@ -369,11 +401,16 @@ class LayerPatcher:
else:
module_param.data = module_param.data + param_weight_converted
finally:
- # Back exactly as it came: returning the device but leaving the float32 promotion doubled the
- # cached record's size for the rest of the process, while the cache went on billing the size
- # it measured at `put()`.
- for leaf, leaf_device, leaf_dtype in leaf_placements:
- leaf.to(device=leaf_device, dtype=leaf_dtype)
+ for leaf, tensors in original_tensors:
+ vars(leaf).update(tensors)
+
+ @staticmethod
+ def _patch_leaves(patch: BaseLayerPatch) -> Iterator[BaseLayerPatch]:
+ children = sub_patches(patch)
+ if not children:
+ yield patch
+ for child in children:
+ yield from LayerPatcher._patch_leaves(child)
@staticmethod
def _leaf_placements(patch: BaseLayerPatch) -> list[tuple[BaseLayerPatch, torch.device, torch.dtype]]:
@@ -385,11 +422,12 @@ class LayerPatcher:
sub-patches, alone or in a list or tuple, and those need not share a dtype; so the leaves
under them are recorded and restored one by one. Leaves without tensors have nothing to restore.
"""
- wrapped = sub_patches(patch)
- if wrapped:
- return [leaf for sub_patch in wrapped for leaf in LayerPatcher._leaf_placements(sub_patch)]
- tensor = next((value for value in vars(patch).values() if isinstance(value, torch.Tensor)), None)
- return [] if tensor is None else [(patch, tensor.device, tensor.dtype)]
+ placements = []
+ for leaf in LayerPatcher._patch_leaves(patch):
+ tensor = next((value for value in vars(leaf).values() if isinstance(value, torch.Tensor)), None)
+ if tensor is not None:
+ placements.append((leaf, tensor.device, tensor.dtype))
+ return placements
@staticmethod
@torch.no_grad()
diff --git a/invokeai/backend/patches/layers/dora_layer.py b/invokeai/backend/patches/layers/dora_layer.py
index 8fa4ac22d5..cc6e95c39f 100644
--- a/invokeai/backend/patches/layers/dora_layer.py
+++ b/invokeai/backend/patches/layers/dora_layer.py
@@ -33,6 +33,7 @@ class DoRALayer(LoRALayerBase):
alpha: float | None,
bias: Optional[torch.Tensor],
magnitude_is_out_dim: bool = False,
+ direction_norm: torch.Tensor | None = None,
):
super().__init__(alpha, bias)
self.up = up
@@ -41,6 +42,8 @@ class DoRALayer(LoRALayerBase):
# False -> LyCORIS convention (magnitude indexes in_features). True -> PEFT/ai-toolkit convention
# (magnitude indexes out_features).
self.magnitude_is_out_dim = magnitude_is_out_dim
+ # Application-local shared norm for a split fused input-axis layer; never bound on a cached adapter.
+ self.direction_norm = direction_norm
@classmethod
def from_state_dict_values(cls, values: Dict[str, torch.Tensor]):
@@ -106,8 +109,14 @@ class DoRALayer(LoRALayerBase):
def get_weight(self, orig_weight: torch.Tensor) -> torch.Tensor:
orig_weight = cast_to_device(orig_weight, self.up.device)
+ # Form the direction and residual in float32 so low-precision rounding cannot erase a small update.
+ up, down = self.up, self.down
+ if orig_weight.dtype in (torch.float16, torch.bfloat16) or up.dtype in (torch.float16, torch.bfloat16):
+ orig_weight = orig_weight.float()
+ up, down = up.float(), down.float()
+
# Note: Variable names (e.g. delta_v) are based on the paper.
- delta_v = self.up.reshape(self.up.shape[0], -1) @ self.down.reshape(self.down.shape[0], -1)
+ delta_v = up.reshape(up.shape[0], -1) @ down.reshape(down.shape[0], -1)
delta_v = delta_v.reshape(orig_weight.shape)
delta_v = delta_v * self.scale()
@@ -115,7 +124,10 @@ class DoRALayer(LoRALayerBase):
# At this point, out_weight is the unnormalized direction matrix.
out_weight = orig_weight + delta_v
- if self.magnitude_is_out_dim:
+ if self.direction_norm is not None:
+ direction_norm = self.direction_norm
+ dora_scale = self.dora_scale
+ elif self.magnitude_is_out_dim:
# PEFT / ai-toolkit: norm over the input dim, one entry per output row.
trailing_dims = [1] * (out_weight.dim() - 1)
direction_norm = (
@@ -139,13 +151,19 @@ class DoRALayer(LoRALayerBase):
return out_weight - orig_weight
def to(self, device: torch.device | None = None, dtype: torch.dtype | None = None):
+ if self.direction_norm is not None:
+ # Keep the cached factors' precision; get_weight promotes them only while computing the residual.
+ dtype = None
super().to(device=device, dtype=dtype)
self.up = self.up.to(device=device, dtype=dtype)
self.down = self.down.to(device=device, dtype=dtype)
self.dora_scale = self.dora_scale.to(device=device, dtype=dtype)
+ if self.direction_norm is not None:
+ # Accumulated in float32 across all fused rows; keep that precision with low-precision factors.
+ self.direction_norm = self.direction_norm.to(device=device)
def calc_size(self) -> int:
- return super().calc_size() + calc_tensors_size([self.up, self.down, self.dora_scale])
+ return super().calc_size() + calc_tensors_size([self.up, self.down, self.dora_scale, self.direction_norm])
def get_parameters(self, orig_parameters: dict[str, torch.Tensor], weight: float) -> dict[str, torch.Tensor]:
if any(p.device.type == "meta" for p in orig_parameters.values()):
diff --git a/invokeai/backend/patches/layers/fused_input_dora_layer.py b/invokeai/backend/patches/layers/fused_input_dora_layer.py
new file mode 100644
index 0000000000..d488e769a8
--- /dev/null
+++ b/invokeai/backend/patches/layers/fused_input_dora_layer.py
@@ -0,0 +1,127 @@
+import torch
+
+from invokeai.backend.patches.layers.base_layer_patch import BaseLayerPatch
+from invokeai.backend.patches.layers.dora_layer import DoRALayer
+from invokeai.backend.quantization.fp8_scaled import dequantize_weight
+from invokeai.backend.util.fp8 import FP8_STORAGE_DTYPES
+
+# At most 4 MiB per float32 row slab (or one row for wider weights). The norm pass keeps only
+# a base slab, a direction slab, the low-rank factors and an input-width accumulator, never fused W.
+_NORM_BLOCK_ELEMENTS = 1 << 20
+
+
+class UnsupportedFusedInputDoRABase(Exception):
+ """The fused norm cannot be bound to one of this group's base weights."""
+
+
+class FusedInputDoRALayer(BaseLayerPatch):
+ """Unbound fused DoRA: loading knows the factors, but only application knows the Q/K/V bases.
+
+ Cached instances contain no base weights or computed norms. Binding happens once per adapter
+ application, before any of its projections change, and returns ordinary local DoRA patches.
+ """
+
+ def __init__(self, layer: DoRALayer, keys: tuple[str, str, str]):
+ self.layer = layer
+ self.keys = keys
+
+ @torch.no_grad()
+ def bind(
+ self, model: torch.nn.Module, base_dtypes: tuple[torch.dtype | None, ...] = (None, None, None)
+ ) -> list[tuple[str, DoRALayer]]:
+ modules = [model.get_submodule(key) for key in self.keys]
+ layer = self.layer
+ # Validate the adapter even when a quantized base will be skipped. These dimensions
+ # are available on both ordinary and buffer-backed quantized Linear modules.
+ if all(hasattr(module, "in_features") and hasattr(module, "out_features") for module in modules):
+ in_features = [module.in_features for module in modules]
+ out_features = [module.out_features for module in modules]
+ if (
+ layer.up.ndim != 2
+ or layer.down.ndim != 2
+ or len(set(in_features)) != 1
+ or len(set(out_features)) != 1
+ or layer.up.shape != (sum(out_features), layer.down.shape[0])
+ or layer.down.shape[1] != in_features[0]
+ or layer.dora_scale.numel() != in_features[0]
+ or (layer.bias is not None and layer.bias.numel() != sum(out_features))
+ ):
+ raise RuntimeError("Fused input-axis DoRA dimensions do not match its Q/K/V projections.")
+ for module in modules:
+ # Binding needs all three base weights before patching; packed modules and tensor subclasses
+ # do not provide the ordinary floating-point weight slabs used by this norm pass.
+ if (
+ not isinstance(module, torch.nn.Linear)
+ or module.weight.device.type == "meta"
+ or type(module.weight.data) is not torch.Tensor
+ or not module.weight.is_floating_point()
+ ):
+ raise UnsupportedFusedInputDoRABase(
+ "Fused input-axis DoRA requires ordinary floating-point Q/K/V weights; "
+ "this base model quantization format is not supported for that operation."
+ )
+
+ up_parts = layer.up.chunk(3, dim=0)
+ norm_sq = torch.zeros(layer.down.shape[1], device=modules[0].weight.device, dtype=torch.float32)
+ for module, up, base_dtype in zip(modules, up_parts, base_dtypes, strict=True):
+ weight = module.weight
+ down = layer.down.to(device=weight.device, dtype=torch.float32)
+ scale = getattr(module, "weight_scale", None) if weight.dtype in FP8_STORAGE_DTYPES else None
+ step = max(1, _NORM_BLOCK_ELEMENTS // weight.shape[1])
+ for start in range(0, weight.shape[0], step):
+ end = min(start + step, weight.shape[0])
+ slab_scale = scale
+ if scale is not None and scale.numel() > 1:
+ # Select compact scale rows before expanding, including block-wise scales.
+ rows_per_scale = weight.shape[0] // scale.shape[0]
+ indices = torch.arange(start, end, device=scale.device) // rows_per_scale
+ slab_scale = scale.index_select(0, indices)
+ base = dequantize_weight(weight[start:end], slab_scale, base_dtype or torch.float32).float()
+ direction = torch.addmm(
+ base, up[start:end].to(device=weight.device, dtype=torch.float32), down, alpha=layer.scale()
+ )
+ norm_sq.add_(direction.square_().sum(dim=0).to(norm_sq.device))
+ del base, direction
+ norm = norm_sq.sqrt_().reshape(1, -1)
+ bias = layer.bias.to_dense() if layer.bias is not None and layer.bias.is_sparse else layer.bias
+ bias_parts = (None, None, None) if bias is None else bias.chunk(3, dim=0)
+ return [
+ (
+ key,
+ DoRALayer(
+ up=up,
+ down=layer.down,
+ dora_scale=layer.dora_scale.reshape(1, -1),
+ alpha=layer._alpha,
+ bias=bias,
+ direction_norm=norm,
+ ),
+ )
+ for key, up, bias in zip(self.keys, up_parts, bias_parts, strict=True)
+ ]
+
+ def binding_workspace_bytes(self, module: torch.nn.Linear, dtype: torch.dtype) -> int:
+ """Bytes for one projection's FP32 norm pass, apart from the bound norm itself."""
+ rows, columns = module.out_features, module.in_features
+ slab_rows = min(rows, max(1, _NORM_BLOCK_ELEMENTS // columns))
+ fp32 = torch.float32.itemsize
+ scale = getattr(module, "weight_scale", None)
+ # A scaled FP8 slab can have a cast, indexed scales, expanded scales, and multiply output
+ # in flight. The FP32 addmm needs a base and a direction slab after dequantization.
+ slab_bytes = (
+ 4 * slab_rows * columns * max(fp32, dtype.itemsize, scale.element_size() if scale is not None else 0)
+ )
+ rank = self.layer.down.shape[0]
+ # One up slab and a down factor. Replacing down between projections can briefly hold two.
+ factor_bytes = (slab_rows * rank + 2 * self.layer.down.numel()) * fp32
+ vector_bytes = (slab_rows + columns) * (2 * torch.int64.itemsize + 2 * fp32)
+ return slab_bytes + factor_bytes + vector_bytes
+
+ def get_parameters(self, orig_parameters: dict[str, torch.Tensor], weight: float) -> dict[str, torch.Tensor]:
+ raise RuntimeError("Fused input-axis DoRA must be bound to its base model before application.")
+
+ def to(self, device: torch.device | None = None, dtype: torch.dtype | None = None):
+ self.layer.to(device=device, dtype=dtype)
+
+ def calc_size(self) -> int:
+ return self.layer.calc_size()
diff --git a/invokeai/backend/patches/lora_conversions/flux_aitoolkit_lora_conversion_utils.py b/invokeai/backend/patches/lora_conversions/flux_aitoolkit_lora_conversion_utils.py
index f359e7caa3..792622221b 100644
--- a/invokeai/backend/patches/lora_conversions/flux_aitoolkit_lora_conversion_utils.py
+++ b/invokeai/backend/patches/lora_conversions/flux_aitoolkit_lora_conversion_utils.py
@@ -47,8 +47,13 @@ def is_state_dict_likely_in_flux_aitoolkit_format(
"hada_w2_b",
"hada_t1",
"hada_t2",
+ "dora_scale",
)
- if any(k.endswith(_LYCORIS_SUFFIXES) for k in state_dict.keys() if isinstance(k, str)):
+ if any(
+ k.endswith((*_LYCORIS_SUFFIXES, "lora_magnitude_vector.weight", "lora_magnitude_vector", ".magnitude"))
+ for k in state_dict.keys()
+ if isinstance(k, str)
+ ):
return False
if metadata:
diff --git a/invokeai/backend/patches/lora_conversions/flux_bfl_peft_lora_conversion_utils.py b/invokeai/backend/patches/lora_conversions/flux_bfl_peft_lora_conversion_utils.py
index f80a4754e5..3391b87fba 100644
--- a/invokeai/backend/patches/lora_conversions/flux_bfl_peft_lora_conversion_utils.py
+++ b/invokeai/backend/patches/lora_conversions/flux_bfl_peft_lora_conversion_utils.py
@@ -25,12 +25,15 @@ from typing import Dict
import torch
from invokeai.backend.patches.layers.base_layer_patch import BaseLayerPatch
+from invokeai.backend.patches.layers.dora_layer import DoRALayer
+from invokeai.backend.patches.layers.fused_input_dora_layer import FusedInputDoRALayer
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.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
from invokeai.backend.patches.lora_conversions.flux_lora_constants import FLUX_LORA_TRANSFORMER_PREFIX
from invokeai.backend.patches.model_patch_raw import ModelPatchRaw
from invokeai.backend.util.logging import InvokeAILogger
@@ -57,7 +60,9 @@ _DOUBLE_BLOCK_RE = re.compile(r"^double_blocks\.(\d+)\.(.+)$")
_SINGLE_BLOCK_RE = re.compile(r"^single_blocks\.(\d+)\.(.+)$")
# Weight key suffixes used by PEFT LoRA in BFL format.
-_BFL_PEFT_LORA_SUFFIXES = ("lora_A.weight", "lora_B.weight")
+_BFL_PEFT_LORA_SUFFIXES = ("lora_A.weight", "lora_B.weight") + tuple(
+ suffix.removeprefix(".") for suffix in DORA_MAGNITUDE_SUFFIX_TO_VALUE_KEY if suffix != ".dora_scale"
+)
# Weight key suffixes used by LyCORIS algorithms (LoKR, LoHA, etc.) in BFL format.
# These are single-component suffixes (no dot), unlike the two-component PEFT suffixes.
@@ -208,6 +213,8 @@ def lora_model_from_flux_bfl_peft_state_dict(
grouped_state_dict[layer_name]["lora_down.weight"] = value
elif suffix == "lora_B.weight":
grouped_state_dict[layer_name]["lora_up.weight"] = value
+ elif f".{suffix}" in DORA_MAGNITUDE_SUFFIX_TO_VALUE_KEY:
+ grouped_state_dict[layer_name][DORA_MAGNITUDE_SUFFIX_TO_VALUE_KEY[f".{suffix}"]] = value
else:
grouped_state_dict[layer_name][suffix] = value
@@ -253,6 +260,8 @@ def lora_model_from_flux2_bfl_peft_state_dict(
grouped_state_dict[layer_name]["lora_down.weight"] = value
elif suffix == "lora_B.weight":
grouped_state_dict[layer_name]["lora_up.weight"] = value
+ elif f".{suffix}" in DORA_MAGNITUDE_SUFFIX_TO_VALUE_KEY:
+ grouped_state_dict[layer_name][DORA_MAGNITUDE_SUFFIX_TO_VALUE_KEY[f".{suffix}"]] = value
else:
grouped_state_dict[layer_name][suffix] = value
@@ -308,8 +317,8 @@ def convert_bfl_lora_patch_to_diffusers(patch: ModelPatchRaw) -> ModelPatchRaw:
def _convert_bfl_layer_patch_to_diffusers(bfl_key: str, layer: BaseLayerPatch) -> list[tuple[str, BaseLayerPatch]]:
"""Convert a single BFL-named LoRA layer patch to one or more diffusers-named patches.
- For simple renames, the layer object is reused. Fused QKV LoRA, LoHa, and LoKr patches keep
- their factorized representation after splitting.
+ For simple renames, the layer object is reused. Fused QKV patches remain factorized;
+ input-axis DoRA defers its split until the patcher has the base weights.
"""
# Double blocks
m = _DOUBLE_BLOCK_RE.match(bfl_key)
@@ -398,6 +407,35 @@ def _split_qkv_bias(
return dense_bias.chunk(3, dim=0)
+def _split_qkv_dora_layer(
+ layer: DoRALayer,
+ q_key: str,
+ k_key: str,
+ v_key: str,
+) -> list[tuple[str, BaseLayerPatch]]:
+ """Output norms are row-local; input norms require all Q/K/V base rows at application time."""
+ if not layer.magnitude_is_out_dim:
+ return [(q_key, FusedInputDoRALayer(layer, (q_key, k_key, v_key)))]
+
+ up_parts = layer.up.chunk(3, dim=0)
+ magnitude_parts = layer.dora_scale.reshape(-1).chunk(3)
+ bias_parts = _split_qkv_bias(layer.bias, layer.up.shape[0])
+ return [
+ (
+ key,
+ DoRALayer(
+ up=up,
+ down=layer.down,
+ dora_scale=magnitude,
+ alpha=layer._alpha,
+ bias=bias,
+ magnitude_is_out_dim=True,
+ ),
+ )
+ for key, up, magnitude, bias in zip((q_key, k_key, v_key), up_parts, magnitude_parts, bias_parts, strict=True)
+ ]
+
+
def _split_qkv_loha_layer(
layer: LoHALayer,
q_key: str,
@@ -591,6 +629,8 @@ def _split_qkv_layer_patch(
k_key: str,
v_key: str,
) -> list[tuple[str, BaseLayerPatch]]:
+ if isinstance(layer, DoRALayer):
+ return _split_qkv_dora_layer(layer, q_key=q_key, k_key=k_key, v_key=v_key)
if isinstance(layer, LoRALayer):
return _split_qkv_lora_layer(layer, q_key=q_key, k_key=k_key, v_key=v_key)
if isinstance(layer, LoHALayer):
diff --git a/invokeai/backend/patches/sidecar_working_memory.py b/invokeai/backend/patches/sidecar_working_memory.py
index 7836bcd84a..6ec301074c 100644
--- a/invokeai/backend/patches/sidecar_working_memory.py
+++ b/invokeai/backend/patches/sidecar_working_memory.py
@@ -22,7 +22,8 @@ from invokeai.backend.quantization.fp8_scaled import count_fp8_weights
# layer's own. A full layer scales its diff into a new tensor; LoKR builds kron(w1, w2), then scales it; LoHA holds
# its two products and theirs. DoRA holds its scaled delta, the updated weight and their difference, 4 in all; the
# input-dim (LyCORIS) magnitude's column norm, over a transposed view, measured another third of a copy on CUDA
-# (gate_layer, bf16), so DoRA is priced at 5. A low-rank layer forms none: it adds its output only.
+# (gate_layer, bf16), so DoRA is priced at 5 before accounting for FP32 promotion. A low-rank layer
+# forms none: it adds its output only.
_SIDECAR_WEIGHT_COPIES: dict[type[BaseLayerPatch], int] = {
FullLayer: 2,
LoKRLayer: 3,
@@ -64,6 +65,24 @@ def _weight_copies(layer: BaseLayerPatch) -> int:
return _SIDECAR_WEIGHT_COPIES[type(layer)]
+def _weight_workspace_bytes(layer: BaseLayerPatch, weight_elements: int, dtype: torch.dtype) -> tuple[int, int]:
+ """Dense update workspace in bytes and the residual's bytes per element."""
+ copies = _weight_copies(layer)
+ wrapped = isinstance(layer, SwappedHalvesLayerPatch)
+ leaf = layer.layer if wrapped else layer
+ if not isinstance(leaf, DoRALayer) or dtype not in (torch.bfloat16, torch.float16):
+ return copies * weight_elements * dtype.itemsize, dtype.itemsize
+
+ # The sidecar's original base and any swapped input are still in the inference dtype.
+ # DoRA widens the base, up and down, and computes the delta, direction, norm workspace
+ # and residual in FP32. A subsequent layer may run while an FP32 residual is still live.
+ base_copies = 1 + wrapped
+ fp32 = torch.float32.itemsize
+ matrix_bytes = weight_elements * (base_copies * dtype.itemsize + (copies - base_copies + 1) * fp32)
+ factor_bytes = (leaf.up.numel() + leaf.down.numel()) * fp32
+ return matrix_bytes + factor_bytes, fp32
+
+
def lora_sidecar_bytes(
patches: Iterable[ModelPatchRaw],
transformer: torch.nn.Module,
@@ -82,10 +101,9 @@ def lora_sidecar_bytes(
- an update of the module's output, `rows` rows (those `per_sample_rows` names: its own count, for a Linear that
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). 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.
+ - for any layer but a low-rank one, the largest dense update workspace in bytes. For DoRA this includes
+ the FP32 promotion of a half-precision base and factors. A running sum stays live from the second dense
+ patch on the module, and the previous layer's residual can also stay live from the third.
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
@@ -98,11 +116,10 @@ def lora_sidecar_bytes(
if not patches:
return 0
modules = dict(transformer.named_modules())
- # Per patched module: its layers' elements, the largest rank among its low-rank layers, and the weight copies of
- # each of its other layers.
+ # Per patched module: its resident patch elements, largest low rank, and dense workspaces.
elements: dict[str, int] = {}
ranks: dict[str, int] = {}
- copies: dict[str, list[int]] = {}
+ workspaces: dict[str, list[tuple[int, int]]] = {}
for patch in patches:
for key, layer in patch.layers.items():
if not key.startswith(prefix):
@@ -114,16 +131,22 @@ def lora_sidecar_bytes(
if isinstance(layer, LoRALayer):
ranks[path] = max(ranks.get(path, 0), layer.down.shape[0])
else:
- copies.setdefault(path, []).append(_weight_copies(layer))
+ module = modules[path]
+ weight_elements = module.out_features * module.in_features
+ workspaces.setdefault(path, []).append(_weight_workspace_bytes(layer, weight_elements, dtype))
updates: dict[str, int] = {}
for path in elements:
module = modules[path]
- summed = copies.get(path, [])
- weight_copies = max(summed) + min(len(summed) - 1, 2) if summed else 0
- updates[path] = (
- per_sample_rows.get(path, rows) * (module.out_features + ranks.get(path, 0))
- + weight_copies * module.out_features * module.in_features
- )
+ dense = workspaces.get(path, [])
+ output_elements = per_sample_rows.get(path, rows) * (module.out_features + ranks.get(path, 0))
+ update_bytes = output_elements * dtype.itemsize
+ if dense:
+ update_bytes += max(workspace for workspace, _ in dense)
+ residuals = min(len(dense) - 1, 2)
+ if residuals:
+ residual_size = max(itemsize for _, itemsize in dense)
+ update_bytes += residuals * module.out_features * module.in_features * residual_size
+ updates[path] = update_bytes
if requires_sidecar_patching(transformer, model_format) or count_fp8_weights(transformer):
- return (sum(elements.values()) + max(updates.values(), default=0)) * dtype.itemsize
- return max((elements[path] + updates[path] for path in elements), default=0) * dtype.itemsize
+ return sum(elements.values()) * dtype.itemsize + max(updates.values(), default=0)
+ return max((elements[path] * dtype.itemsize + updates[path] for path in elements), default=0)
diff --git a/tests/app/invocations/test_flux2_control.py b/tests/app/invocations/test_flux2_control.py
index 417af7f3dd..5cd3f6db4c 100644
--- a/tests/app/invocations/test_flux2_control.py
+++ b/tests/app/invocations/test_flux2_control.py
@@ -29,12 +29,17 @@ from invokeai.app.invocations.vae.flux2_vae_encode import Flux2VaeEncodeInvocati
from invokeai.backend.flux2.denoise_working_memory import estimate_flux2_denoise_working_memory
from invokeai.backend.fun_controlnet.flux2 import FLUX2_FUN_CONTROL_IN_DIM, Flux2FunControlBranch
from invokeai.backend.fun_controlnet.hooks import FunControlHooks
+from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.torch_module_autocast import (
+ apply_custom_layers_to_model,
+)
from invokeai.backend.model_manager.taxonomy import BaseModelType, Flux2VariantType, ModelFormat, ModelType
from invokeai.backend.patches.layer_patcher import LayerPatcher
+from invokeai.backend.quantization.int8_convrot import Int8ConvrotLinear
from invokeai.backend.stable_diffusion.diffusion.conditioning_data import ConditioningFieldData, FLUXConditioningInfo
from invokeai.backend.util import attention
from invokeai.backend.util.devices import TorchDevice
from invokeai.backend.working_memory import probe
+from tests.backend.patches.lora_conversions.test_flux2_dora_application import load_state
SIDE = 64 # an 8x8 latent: 16 image tokens
IMAGE_TOKENS = (SIDE // 16) ** 2
@@ -255,6 +260,121 @@ def _hook_count(transformer) -> int:
return sum(len(block._forward_hooks) + len(block._forward_pre_hooks) for block in transformer.transformer_blocks)
+def test_packed_output_axis_dora_adds_to_transformer_reservation(tmp_path, monkeypatch) -> None:
+ transformer = _tiny_transformer()
+ attention = transformer.transformer_blocks[0].attn
+ width = attention.to_q.in_features
+ for name in ("to_q", "to_k", "to_v"):
+ setattr(
+ attention,
+ name,
+ Int8ConvrotLinear(torch.ones(width, width, dtype=torch.int8), torch.full((width, 1), 0.125), convrot=False),
+ )
+ apply_custom_layers_to_model(transformer)
+ prefix = "lora_unet_double_blocks_0_img_attn_qkv"
+ strength = 0.5
+ adapter = load_state(
+ tmp_path,
+ {
+ f"{prefix}.lora_up.weight": torch.ones(3 * width, 2),
+ f"{prefix}.lora_down.weight": torch.ones(2, width),
+ f"{prefix}.dora_scale": torch.ones(3 * width, 1),
+ },
+ )
+ x = torch.ones(1, width)
+ baseline = attention.to_q(x)
+ changed = []
+
+ def check_forward(*args, **kwargs):
+ changed.append(attention.to_q(x))
+ raise _Stop
+
+ monkeypatch.setattr(flux2_denoise, "denoise", check_forward)
+ transformer_info = _loaded(transformer, _yielding(transformer))
+ context = _context(transformer_info=transformer_info)
+ adapter_identifier = _model(ModelType.LoRA)
+ adapter_info = SimpleNamespace(model=adapter, model_in_ram=lambda: nullcontext(adapter))
+ load = context.models.load.side_effect
+ context.models.load.side_effect = lambda identifier: (
+ adapter_info if identifier == adapter_identifier else load(identifier)
+ )
+ node = _denoise(
+ control=None,
+ transformer=SimpleNamespace(
+ transformer=_model(ModelType.Main), loras=[SimpleNamespace(lora=adapter_identifier, weight=strength)]
+ ),
+ )
+ with pytest.raises(_Stop):
+ node._run_diffusion(context)
+ torch.testing.assert_close(changed[0], (1 - strength) * baseline + strength * torch.full_like(baseline, width**0.5))
+ torch.testing.assert_close(attention.to_q(x), baseline, rtol=0, atol=0)
+
+ legacy = estimate_flux2_denoise_working_memory(
+ transformer,
+ hidden_size=DEV_HIDDEN,
+ image_seq_len=IMAGE_TOKENS,
+ ref_image_seq_len=0,
+ text_seq_len=TEXT_TOKENS,
+ batch_size=1,
+ lora_count=1,
+ device=torch.device("cpu"),
+ dtype=torch.bfloat16,
+ )
+ reserved = transformer_info.model_on_device.call_args.kwargs["working_memory"].reservation_bytes
+ # Widened base, scaled delta, direction and residual can be live at once.
+ assert reserved - legacy.reservation_bytes >= 4 * width**2 * torch.float32.itemsize
+
+
+def test_fused_dora_is_reserved_before_transformer_lock_and_unpinned_on_failure(tmp_path) -> None:
+ transformer = _tiny_transformer()
+ attention = transformer.transformer_blocks[0].attn
+ out_features, in_features = attention.to_q.weight.shape
+ prefix = "lora_unet_double_blocks_0_img_attn_qkv"
+ adapter = load_state(
+ tmp_path,
+ {
+ f"{prefix}.lora_up.weight": torch.ones(3 * out_features, 2),
+ f"{prefix}.lora_down.weight": torch.ones(2, in_features),
+ f"{prefix}.dora_scale": torch.ones(1, in_features),
+ },
+ )
+ pin_count = 0
+
+ @contextmanager
+ def pin():
+ nonlocal pin_count
+ pin_count += 1
+ try:
+ yield adapter
+ finally:
+ pin_count -= 1
+
+ def stop_at_lock(*, working_memory):
+ assert working_memory.features.get("dora_patch_bytes", 0) >= 4 * attention.to_q.weight.nbytes
+ assert pin_count == 1
+ raise _Stop
+
+ transformer_info = _loaded(transformer, stop_at_lock)
+ context = _context(transformer_info=transformer_info)
+ adapter_identifier = _model(ModelType.LoRA)
+ adapter_info = SimpleNamespace(model=adapter, model_in_ram=pin)
+ load = context.models.load.side_effect
+ context.models.load.side_effect = lambda identifier: (
+ adapter_info if identifier == adapter_identifier else load(identifier)
+ )
+ node = _denoise(
+ control=None,
+ transformer=SimpleNamespace(
+ transformer=_model(ModelType.Main), loras=[SimpleNamespace(lora=adapter_identifier, weight=0.5)]
+ ),
+ )
+
+ with pytest.raises(_Stop):
+ node._run_diffusion(context)
+
+ assert pin_count == 0
+
+
@pytest.mark.parametrize("variant", [Flux2VariantType.Klein9B, Flux2VariantType.Klein4BBase], ids=lambda v: v.value)
def test_control_is_refused_on_klein_before_the_controlnet_is_loaded(variant) -> None:
context = _context(transformer_info=_loaded(_tiny_transformer(), _stopping), variant=variant)
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 340296bd3c..2bbb2758d5 100644
--- a/tests/app/invocations/test_qwen_image_2_1_nodes.py
+++ b/tests/app/invocations/test_qwen_image_2_1_nodes.py
@@ -1615,6 +1615,28 @@ 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)
[email protected]("kind", ["peft-dora", "lycoris-dora"])
+def test_bfloat16_sidecar_reserves_promoted_dora_workspace(kind: str) -> None:
+ # The base cast lives alongside the FP32 DoRA calculation. Measure that calculation with
+ # actual BF16 factors and base, and include the already-materialized BF16 base in the bound.
+ transformer = torch.nn.Module()
+ block = torch.nn.Module()
+ block.attn = torch.nn.Module()
+ block.attn.to_q = torch.nn.Linear(_W, _W, bias=False, dtype=torch.bfloat16)
+ transformer.transformer_blocks = torch.nn.ModuleList([block])
+ patch = _sidecar_kind(kind)
+ patch.to(dtype=torch.bfloat16)
+ layer = next(iter(patch.layers.values()))
+ base = block.attn.to_q.weight
+ mode = _PeakAllocation()
+ with mode:
+ layer.get_parameters({"weight": base}, 1.0)
+
+ reserved = _reserve(patch, transformer, seq_len=2, dtype=torch.bfloat16)
+ assert reserved >= patch.calc_size() + base.nbytes + mode.peak
+
+
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,
diff --git a/tests/backend/patches/lora_conversions/test_flux2_dora_application.py b/tests/backend/patches/lora_conversions/test_flux2_dora_application.py
new file mode 100644
index 0000000000..95fa712161
--- /dev/null
+++ b/tests/backend/patches/lora_conversions/test_flux2_dora_application.py
@@ -0,0 +1,153 @@
+from contextlib import ExitStack, contextmanager
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import MagicMock
+
+import pytest
+import torch
+from safetensors.torch import save_file
+
+from invokeai.app.invocations.flux2.flux2_denoise import Flux2DenoiseInvocation
+from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.torch_module_autocast import (
+ apply_custom_layers_to_model,
+)
+from invokeai.backend.model_manager.load.model_loaders.lora import LoRALoader
+from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelFormat
+from invokeai.backend.patches.layer_patcher import LayerPatcher
+from invokeai.backend.patches.lora_conversions.flux_lora_constants import FLUX_LORA_TRANSFORMER_PREFIX
+
+
+class SplitAttention(torch.nn.Module):
+ def __init__(self, seed: int):
+ super().__init__()
+ generator = torch.Generator().manual_seed(seed)
+ self.names = ("to_q", "to_k", "to_v", "add_q_proj", "add_k_proj", "add_v_proj")
+ attention = torch.nn.ModuleDict({name: torch.nn.Linear(7, 4) for name in self.names})
+ self.transformer_blocks = torch.nn.ModuleList([torch.nn.ModuleDict({"attn": attention})])
+ with torch.no_grad():
+ for parameter in self.parameters():
+ parameter.copy_(torch.randn(parameter.shape, generator=generator))
+ apply_custom_layers_to_model(self)
+
+ def forward(self, x):
+ return torch.cat([self.transformer_blocks[0]["attn"][name](x) for name in self.names], dim=-1)
+
+
+def load_adapter(tmp_path, axis, layout, storage):
+ generator = torch.Generator().manual_seed(581026)
+ state, factors = {}, []
+ for stream in ("img", "txt"):
+ up = (torch.randn(12, 2, generator=generator) * 0.2).to(storage)
+ down = (torch.randn(2, 7, generator=generator) * 0.3).to(storage)
+ magnitude = torch.linspace(0.7, 1.7, 7 if axis == "input" else 12).to(storage)
+ magnitude = magnitude.reshape(1, 7) if axis == "input" else magnitude.reshape(12, 1)
+ factors.append((up.float(), down.float(), magnitude.float()))
+ if layout == "kohya":
+ key = f"lora_unet_double_blocks_0_{stream}_attn_qkv"
+ suffixes = ("lora_up.weight", "lora_down.weight")
+ else:
+ key = f"{layout}double_blocks.0.{stream}_attn.qkv"
+ suffixes = ("lora_B.weight", "lora_A.weight")
+ state.update(
+ {
+ f"{key}.{suffixes[0]}": up,
+ f"{key}.{suffixes[1]}": down,
+ f"{key}.dora_scale": magnitude,
+ f"{key}.alpha": torch.tensor(3.0).to(storage),
+ }
+ )
+ return load_state(tmp_path, state, storage), factors
+
+
+def load_state(tmp_path, state, storage=torch.float32):
+ path = tmp_path / "adapter.safetensors"
+ save_file(state, path)
+ config = SimpleNamespace(path=str(path), base=BaseModelType.Flux2, format=ModelFormat.LyCORIS, name="fixture")
+ loader = LoRALoader(MagicMock(models_path=tmp_path), MagicMock(), MagicMock())
+ loader._get_model_path(config)
+ loader._torch_dtype = storage
+ return loader._load_model(config)
+
+
+def fused_expected(model, factors, x, strength, axis):
+ outputs = []
+ attention = model.transformer_blocks[0]["attn"]
+ for names, (up, down, magnitude) in zip((model.names[:3], model.names[3:]), factors, strict=True):
+ base = torch.cat([attention[name].weight.float() for name in names])
+ bias = torch.cat([attention[name].bias.float() for name in names])
+ direction = base + (3.0 / 2) * (up @ down)
+ normalized = magnitude * direction / direction.norm(dim=0 if axis == "input" else 1, keepdim=True)
+ outputs.append(torch.nn.functional.linear(x, base + strength * (normalized - base), bias))
+ return torch.cat(outputs, dim=-1)
+
+
+ "axis,layout,storage,sidecar",
+ [
+ ("input", "kohya", torch.float32, False),
+ ("input", "diffusion_model.", torch.bfloat16, True),
+ ("input", "base_model.model.", torch.bfloat16, False),
+ ("output", "diffusion_model.", torch.float32, False),
+ ("output", "kohya", torch.bfloat16, True),
+ ],
+)
+def test_loader_iterator_and_patcher_match_fused_formula_across_bases(tmp_path: Path, axis, layout, storage, sidecar):
+ patch, factors = load_adapter(tmp_path, axis, layout, storage)
+ placements = [
+ (leaf, leaf.up.clone(), leaf.down.clone(), leaf.dora_scale.clone())
+ for layer in patch.layers.values()
+ for leaf, _, _ in LayerPatcher._leaf_placements(layer)
+ ]
+ pinned = []
+
+ @contextmanager
+ def model_in_ram():
+ pinned.append(True)
+ try:
+ yield patch
+ finally:
+ pinned.pop()
+
+ context = SimpleNamespace(
+ models=SimpleNamespace(load=lambda _: SimpleNamespace(model=patch, model_in_ram=model_in_ram))
+ )
+ lora = SimpleNamespace(lora="adapter", weight=0.0)
+ invocation = SimpleNamespace(transformer=SimpleNamespace(loras=[lora]))
+ x = torch.randn(2, 3, 7, generator=torch.Generator().manual_seed(23))
+ for seed in (71, 92):
+ model = SplitAttention(seed)
+ original = {name: value.clone() for name, value in model.state_dict().items()}
+ baseline = model(x)
+ for strength, fail in ((0.0, False), (-0.4, False), (0.65, True)):
+ lora.weight = strength
+ expected = fused_expected(model, factors, x, strength, axis)
+ try:
+ with ExitStack() as stack:
+ patches = Flux2DenoiseInvocation._materialize_lora_patches(invocation, context, stack)
+ stack.enter_context(
+ LayerPatcher.apply_smart_model_patches(
+ model=model,
+ patches=patches,
+ prefix=FLUX_LORA_TRANSFORMER_PREFIX,
+ dtype=torch.float32,
+ force_direct_patching=not sidecar,
+ force_sidecar_patching=sidecar,
+ )
+ )
+ assert pinned
+ torch.testing.assert_close(model(x), expected, atol=4e-6, rtol=4e-6)
+ if fail:
+ raise RuntimeError("cancelled")
+ except RuntimeError as error:
+ assert fail and str(error) == "cancelled"
+ assert not pinned
+ for name, value in model.state_dict().items():
+ torch.testing.assert_close(value, original[name], atol=0, rtol=0)
+ assert all(module.get_num_patches() == 0 for module in model.transformer_blocks[0]["attn"].values())
+ torch.testing.assert_close(model(x), baseline, atol=0, rtol=0)
+ for leaf, up, down, magnitude in placements:
+ assert leaf.up.dtype == storage and leaf.down.dtype == storage
+ torch.testing.assert_close(leaf.up, up, atol=0, rtol=0)
+ torch.testing.assert_close(leaf.down, down, atol=0, rtol=0)
+ torch.testing.assert_close(leaf.dora_scale, magnitude, atol=0, rtol=0)
diff --git a/tests/backend/patches/lora_conversions/test_flux2_dora_lifecycle.py b/tests/backend/patches/lora_conversions/test_flux2_dora_lifecycle.py
new file mode 100644
index 0000000000..0ab9496d46
--- /dev/null
+++ b/tests/backend/patches/lora_conversions/test_flux2_dora_lifecycle.py
@@ -0,0 +1,377 @@
+import re
+from contextlib import ExitStack, contextmanager
+from types import SimpleNamespace
+from unittest.mock import MagicMock
+
+import pytest
+import torch
+
+from invokeai.app.invocations.flux2.flux2_denoise import Flux2DenoiseInvocation
+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.dora_layer import DoRALayer
+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.lora_conversions.flux_bfl_peft_lora_conversion_utils import (
+ convert_bfl_lora_patch_to_diffusers,
+)
+from invokeai.backend.patches.lora_conversions.flux_lora_constants import FLUX_LORA_TRANSFORMER_PREFIX
+from invokeai.backend.patches.model_patch_raw import ModelPatchRaw
+from tests.backend.patches.lora_conversions.test_flux2_dora_application import (
+ SplitAttention,
+ fused_expected,
+ load_adapter,
+ load_state,
+)
+from tests.backend.patches.lora_conversions.test_flux2_dora_qkv_conversion import _SplitQKV
+
+
[email protected]("variant", ["aitoolkit", "peft-bfl", "kohya", "loha", "lokr"])
+def test_loader_keeps_other_flux_adapter_routes_numerically_unchanged(tmp_path, variant):
+ up = torch.arange(24, dtype=torch.float32).reshape(12, 2) / 24
+ down = torch.arange(14, dtype=torch.float32).reshape(2, 7) / 14
+ delta = up @ down
+ values = {"lora_A.weight": down, "lora_B.weight": up}
+ key = "diffusion_model.double_blocks.0.img_attn.qkv"
+ if variant == "peft-bfl":
+ key = "base_model.model.double_blocks.0.img_attn.qkv"
+ elif variant == "kohya":
+ key = "lora_unet_double_blocks_0_img_attn_qkv"
+ values = {"lora_down.weight": down, "lora_up.weight": up}
+ elif variant == "loha":
+ values = {"hada_w1_a": up, "hada_w1_b": down, "hada_w2_a": up + 0.2, "hada_w2_b": down - 0.1}
+ delta = delta * ((up + 0.2) @ (down - 0.1))
+ elif variant == "lokr":
+ w1 = torch.tensor([[0.3], [-0.4], [0.5]])
+ w2 = torch.arange(28, dtype=torch.float32).reshape(4, 7) / 28
+ values = {"lokr_w1": w1, "lokr_w2": w2}
+ delta = torch.kron(w1, w2)
+ patch = load_state(tmp_path, {f"{key}.{suffix}": value for suffix, value in values.items()})
+ model = _SplitQKV("img", 7)
+ attention = model.transformer_blocks[0]["attn"]
+ base = torch.cat([attention[name].weight for name in model.names])
+ bias = torch.cat([attention[name].bias for name in model.names])
+ x = torch.ones(2, 7)
+ expected = torch.nn.functional.linear(x, base + 0.6 * delta, bias)
+ with LayerPatcher.apply_smart_model_patches(
+ model=model,
+ patches=[(convert_bfl_lora_patch_to_diffusers(patch), 0.6)],
+ prefix=FLUX_LORA_TRANSFORMER_PREFIX,
+ dtype=torch.float32,
+ force_direct_patching=True,
+ ):
+ torch.testing.assert_close(model(x), expected, atol=4e-6, rtol=4e-6)
+
+
+def test_vector_input_magnitude_and_sparse_bias_on_square_fused_weight():
+ generator = torch.Generator().manual_seed(31)
+ model = _SplitQKV("txt", 12)
+ apply = model.transformer_blocks[0]["attn"]
+ base = torch.randn(12, 12, generator=generator)
+ for index, name in enumerate(model.names):
+ apply[name].weight.copy_(base[index * 4 : (index + 1) * 4])
+ bias = torch.cat([apply[name].bias for name in model.names])
+ up = torch.randn(12, 2, generator=generator)
+ down = torch.randn(2, 12, generator=generator)
+ magnitude = torch.linspace(0.3, 1.5, 12)
+ sparse_bias = torch.sparse_coo_tensor([[0, 5, 11]], [0.2, -0.4, 0.6], (12,))
+ layer = DoRALayer(up, down, magnitude, 3.0, sparse_bias)
+ patch = convert_bfl_lora_patch_to_diffusers(
+ ModelPatchRaw({f"{FLUX_LORA_TRANSFORMER_PREFIX}double_blocks.0.txt_attn.qkv": layer})
+ )
+ direction = base + 1.5 * (up @ down)
+ normalized = direction * magnitude / direction.norm(dim=0, keepdim=True)
+ x = torch.randn(2, 12, generator=generator)
+ expected = torch.nn.functional.linear(
+ x, base + 0.6 * (normalized - base), bias + 0.6 * 1.5 * sparse_bias.to_dense()
+ )
+ with LayerPatcher.apply_smart_model_patches(
+ model=model,
+ patches=[(patch, 0.6)],
+ prefix=FLUX_LORA_TRANSFORMER_PREFIX,
+ dtype=torch.float32,
+ force_direct_patching=True,
+ ):
+ torch.testing.assert_close(model(x), expected, atol=4e-6, rtol=4e-6)
+
+
[email protected]("sidecar", [False, True])
+def test_multiple_adapters_preserve_direct_order_and_sidecar_base_semantics(tmp_path, sidecar):
+ patches, all_factors = [], []
+ for axis in ("input", "output"):
+ directory = tmp_path / axis
+ directory.mkdir()
+ patch, factors = load_adapter(directory, axis, "diffusion_model.", torch.bfloat16)
+ patches.append(patch)
+ all_factors.append(factors)
+ model = SplitAttention(924)
+ attention = model.transformer_blocks[0]["attn"]
+ original = {key: value.clone() for key, value in model.state_dict().items()}
+ x = torch.randn(2, 7, generator=torch.Generator().manual_seed(10))
+ for order in ((0, 1), (1, 0)):
+ expected = []
+ for stream, names in enumerate((model.names[:3], model.names[3:])):
+ base = torch.cat([attention[name].weight for name in names])
+ bias = torch.cat([attention[name].bias for name in names])
+ updated = base.clone()
+ for index in order:
+ strength = (-0.25, 0.7)[index]
+ up, down, magnitude = all_factors[index][stream]
+ current = base if sidecar else updated
+ direction = current + 1.5 * (up @ down)
+ normalized = direction * magnitude / direction.norm(dim=index, keepdim=True)
+ updated = updated + strength * (normalized - current)
+ expected.append(torch.nn.functional.linear(x, updated, bias))
+ with LayerPatcher.apply_smart_model_patches(
+ model=model,
+ patches=[(convert_bfl_lora_patch_to_diffusers(patches[index]), (-0.25, 0.7)[index]) for index in order],
+ prefix=FLUX_LORA_TRANSFORMER_PREFIX,
+ dtype=torch.float32,
+ force_direct_patching=not sidecar,
+ force_sidecar_patching=sidecar,
+ ):
+ torch.testing.assert_close(model(x), torch.cat(expected, dim=-1), atol=4e-6, rtol=4e-6)
+ for key, value in model.state_dict().items():
+ torch.testing.assert_close(value, original[key], atol=0, rtol=0)
+
+
[email protected]("axis,scaled", [("input", False), ("input", True), ("output", False)])
+def test_native_fp8_base_uses_dense_values_and_keeps_storage(tmp_path, axis, scaled):
+ patch, factors = load_adapter(tmp_path, axis, "kohya", torch.bfloat16)
+ model = SplitAttention(63)
+ reference = SplitAttention(63)
+ for module, dense in zip(
+ model.transformer_blocks[0]["attn"].values(), reference.transformer_blocks[0]["attn"].values(), strict=True
+ ):
+ module.weight.data = module.weight.data.to(torch.float8_e4m3fn)
+ dense.weight.copy_(module.weight.float())
+ if scaled:
+ scale = torch.linspace(0.4, 0.8, 4)
+ module.register_buffer("weight_scale", scale)
+ dense.weight.mul_(scale.reshape(-1, 1))
+ x = torch.randn(2, 7, generator=torch.Generator().manual_seed(12))
+ expected = fused_expected(reference, factors, x, -0.3, axis)
+ with LayerPatcher.apply_smart_model_patches(
+ model=model,
+ patches=[(convert_bfl_lora_patch_to_diffusers(patch), -0.3)],
+ prefix=FLUX_LORA_TRANSFORMER_PREFIX,
+ dtype=torch.float32,
+ # Native FP8 must select sidecars even when direct patching is requested.
+ force_direct_patching=True,
+ ):
+ torch.testing.assert_close(model(x), expected, atol=4e-6, rtol=4e-6)
+ for module in model.transformer_blocks[0]["attn"].values():
+ assert module.weight.dtype == torch.float8_e4m3fn
+ assert module.get_num_patches() == 0
+
+
+def test_shared_norm_uses_bounded_row_blocks_without_modifying_cached_patch(tmp_path, monkeypatch):
+ import invokeai.backend.patches.layers.fused_input_dora_layer as fused
+
+ patch, factors = load_adapter(tmp_path, "input", "base_model.model.", torch.bfloat16)
+ model = SplitAttention(92)
+ block_shapes = []
+ addmm = torch.addmm
+
+ def record_addmm(base, up, down, **kwargs):
+ block_shapes.append(base.shape)
+ return addmm(base, up, down, **kwargs)
+
+ monkeypatch.setattr(fused, "_NORM_BLOCK_ELEMENTS", 14)
+ monkeypatch.setattr(torch, "addmm", record_addmm)
+ layer = next(iter(patch.layers.values()))
+ split = layer.bind(model)
+ up, down, _ = factors[0]
+ attention = model.transformer_blocks[0]["attn"]
+ direction = torch.cat([attention[name].weight for name in model.names[:3]]) + 1.5 * (up @ down)
+ assert len(block_shapes) == 6 and all(rows * columns <= 14 for rows, columns in block_shapes)
+ assert len(split) == 3
+ assert all(part.direction_norm is split[0][1].direction_norm for _, part in split)
+ torch.testing.assert_close(split[0][1].direction_norm, direction.norm(dim=0, keepdim=True))
+ assert layer.layer.up.dtype == torch.bfloat16
+ assert layer.layer.direction_norm is None
+
+
[email protected]("sidecar", [False, True])
+def test_binding_failure_restores_prior_adapter_and_releases_cache_pins(tmp_path, sidecar):
+ patch, _ = load_adapter(tmp_path, "input", "kohya", torch.bfloat16)
+ # The second adapter has an incompatible input width, after the first was already applied.
+ model = SplitAttention(35)
+ attention = model.transformer_blocks[0]["attn"]
+ original = {key: value.clone() for key, value in model.state_dict().items()}
+ x = torch.ones(1, 7)
+ baseline = model(x)
+ active = []
+
+ @contextmanager
+ def model_in_ram():
+ active.append(True)
+ try:
+ yield patch
+ finally:
+ active.pop()
+
+ invocation = SimpleNamespace(transformer=SimpleNamespace(loras=[SimpleNamespace(lora="adapter", weight=0.5)]))
+ context = SimpleNamespace(
+ models=SimpleNamespace(load=lambda _: SimpleNamespace(model=patch, model_in_ram=model_in_ram))
+ )
+ bad, _ = load_adapter(tmp_path, "input", "base_model.model.", torch.bfloat16)
+ next(iter(bad.layers.values())).layer.down = torch.ones(2, 8, dtype=torch.bfloat16)
+ with pytest.raises(RuntimeError), ExitStack() as stack:
+ good = Flux2DenoiseInvocation._materialize_lora_patches(invocation, context, stack)[0]
+ with LayerPatcher.apply_smart_model_patches(
+ model=model,
+ patches=[good, (bad, 0.7, model_in_ram())],
+ prefix=FLUX_LORA_TRANSFORMER_PREFIX,
+ dtype=torch.float32,
+ force_direct_patching=not sidecar,
+ force_sidecar_patching=sidecar,
+ ):
+ pytest.fail("incompatible base must fail during binding")
+ assert not active
+ for key, value in model.state_dict().items():
+ torch.testing.assert_close(value, original[key], atol=0, rtol=0)
+ assert all(module.get_num_patches() == 0 for module in attention.values())
+ torch.testing.assert_close(model(x), baseline, atol=0, rtol=0)
+
+
[email protected]("missing", ["to_q", "to_k", "to_v"])
[email protected]("suppress", [False, True])
+def test_missing_fused_projection_skips_group_and_applies_other_layers(tmp_path, monkeypatch, missing, suppress):
+ patch, _ = load_adapter(tmp_path, "input", "kohya", torch.float32)
+ patch = convert_bfl_lora_patch_to_diffusers(patch)
+ model = SplitAttention(35)
+ attention = model.transformer_blocks[0]["attn"]
+ del attention[missing]
+ logger = MagicMock()
+ monkeypatch.setattr("invokeai.backend.patches.layer_patcher.InvokeAILogger.get_logger", lambda _: logger)
+ original = {name: module.weight.clone() for name, module in attention.items()}
+ pattern = re.compile("transformer_blocks") if suppress else None
+
+ with LayerPatcher.apply_smart_model_patches(
+ model=model,
+ patches=[(patch, 0.7)],
+ prefix=FLUX_LORA_TRANSFORMER_PREFIX,
+ dtype=torch.float32,
+ force_direct_patching=True,
+ suppress_warning_layers=pattern,
+ ):
+ for name in set(model.names[:3]) - {missing}:
+ torch.testing.assert_close(attention[name].weight, original[name], rtol=0, atol=0)
+ assert not torch.equal(attention["add_q_proj"].weight, original["add_q_proj"])
+ assert logger.warning.call_count == (0 if suppress else 1)
+ for name, module in attention.items():
+ torch.testing.assert_close(module.weight, original[name], rtol=0, atol=0)
+
+
[email protected]("storage", [torch.bfloat16, torch.float32])
+def test_bfloat16_fused_input_sidecar_retains_small_direction_residual(storage):
+ # The low-precision forward is the behavior under test; the reference constructs the fused residual in float32.
+ model = _SplitQKV("img", 7).to(dtype=torch.bfloat16)
+ attention = model.transformer_blocks[0]["attn"]
+ for module in attention.values():
+ module.weight.fill_(1)
+ module.bias.zero_()
+ apply_custom_layers_to_model(model)
+ up = torch.full((12, 1), 0.001953125 if storage == torch.bfloat16 else 0.251, dtype=storage)
+ up[::2] *= -1
+ down = torch.zeros(1, 7, dtype=storage)
+ down[0, 0] = 1
+ magnitude = torch.full((1, 7), 3.46875 if storage == torch.bfloat16 else 3.47, dtype=storage)
+ patch = convert_bfl_lora_patch_to_diffusers(
+ ModelPatchRaw(
+ {f"{FLUX_LORA_TRANSFORMER_PREFIX}double_blocks.0.img_attn.qkv": DoRALayer(up, down, magnitude, None, None)}
+ )
+ )
+ base = torch.ones(12, 7)
+ direction = base + up.float() @ down.float()
+ residual = magnitude.float() * direction / direction.norm(dim=0, keepdim=True) - base
+ x = torch.tensor([[1, -1, 0, 0, 0, 0, 0]], dtype=torch.bfloat16)
+ expected = torch.nn.functional.linear(x, residual.to(torch.bfloat16))
+ assert expected.abs().min() > 0
+ with LayerPatcher.apply_smart_model_patches(
+ model=model,
+ patches=[(patch, 1.0)],
+ prefix=FLUX_LORA_TRANSFORMER_PREFIX,
+ dtype=torch.bfloat16,
+ force_sidecar_patching=True,
+ ):
+ torch.testing.assert_close(model(x), expected, rtol=0, atol=1e-5)
+
+
[email protected]("sidecar", [False, True])
[email protected]("wrapper", ["none", "swapped", "merged"])
+def test_flux2_overlapping_applications_do_not_mutate_cached_adapter(tmp_path, sidecar, wrapper):
+ patch, _ = load_adapter(tmp_path, "input", "kohya", torch.bfloat16)
+ # A diffusers-named layer passes through the converter unchanged, as do simple BFL renames.
+ shared = DoRALayer(
+ torch.ones(4, 2, dtype=torch.bfloat16),
+ torch.ones(2, 7, dtype=torch.bfloat16),
+ torch.ones(4, 1, dtype=torch.bfloat16),
+ None,
+ None,
+ magnitude_is_out_dim=True,
+ )
+ layer = shared
+ if wrapper == "swapped":
+ layer = SwappedHalvesLayerPatch(shared)
+ elif wrapper == "merged":
+ layer = MergedLayerPatch([shared], [Range(0, 4)])
+ key = f"{FLUX_LORA_TRANSFORMER_PREFIX}transformer_blocks.0.attn.to_q"
+ patch.layers[key] = layer
+ original_up = shared.up
+ original_size = patch.calc_size()
+ active = []
+
+ @contextmanager
+ def pin():
+ active.append(True)
+ try:
+ yield patch
+ finally:
+ active.pop()
+
+ context = SimpleNamespace(models=SimpleNamespace(load=lambda _: SimpleNamespace(model=patch, model_in_ram=pin)))
+ invocation = SimpleNamespace(transformer=SimpleNamespace(loras=[SimpleNamespace(lora="adapter", weight=0.5)]))
+ first, second = SplitAttention(1), SplitAttention(2)
+ args = {
+ "prefix": FLUX_LORA_TRANSFORMER_PREFIX,
+ "dtype": torch.float32,
+ "force_sidecar_patching": sidecar,
+ "force_direct_patching": not sidecar,
+ }
+ with ExitStack() as first_stack:
+ patches = Flux2DenoiseInvocation._materialize_lora_patches(invocation, context, first_stack)
+ [(leaf, _, _)] = LayerPatcher._leaf_placements(patches[0][0].layers[key])
+ assert leaf is not shared and leaf.up is original_up
+ first_stack.enter_context(LayerPatcher.apply_smart_model_patches(model=first, patches=patches, **args))
+ if not sidecar:
+ assert leaf.up is original_up and leaf.down is shared.down
+ assert shared.up is original_up and shared.up.dtype == torch.bfloat16
+ with pytest.raises(RuntimeError, match="cancelled"), ExitStack() as second_stack:
+ patches = Flux2DenoiseInvocation._materialize_lora_patches(invocation, context, second_stack)
+ second_stack.enter_context(LayerPatcher.apply_smart_model_patches(model=second, patches=patches, **args))
+ assert len(active) == 2
+ assert shared.up is original_up and shared.up.dtype == torch.bfloat16
+ assert patch.calc_size() == original_size
+ raise RuntimeError("cancelled")
+ assert len(active) == 1
+ assert shared.up is original_up
+ assert not active
+ assert shared.up is original_up
+ assert all(
+ module.get_num_patches() == 0
+ for model in (first, second)
+ for module in model.transformer_blocks[0]["attn"].values()
+ )
diff --git a/tests/backend/patches/lora_conversions/test_flux2_dora_qkv_conversion.py b/tests/backend/patches/lora_conversions/test_flux2_dora_qkv_conversion.py
new file mode 100644
index 0000000000..783c72d59b
--- /dev/null
+++ b/tests/backend/patches/lora_conversions/test_flux2_dora_qkv_conversion.py
@@ -0,0 +1,217 @@
+import pytest
+import torch
+from safetensors.torch import load, save
+
+from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.torch_module_autocast import (
+ apply_custom_layers_to_model,
+)
+from invokeai.backend.model_manager.taxonomy import ModelFormat
+from invokeai.backend.patches.layer_patcher import LayerPatcher
+from invokeai.backend.patches.layers.dora_layer import DoRALayer
+from invokeai.backend.patches.lora_conversions.flux_bfl_peft_lora_conversion_utils import (
+ convert_bfl_lora_patch_to_diffusers,
+ lora_model_from_flux2_bfl_peft_state_dict,
+ lora_model_from_flux_bfl_peft_state_dict,
+)
+from invokeai.backend.patches.lora_conversions.flux_kohya_lora_conversion_utils import (
+ lora_model_from_flux_kohya_state_dict,
+)
+from invokeai.backend.patches.lora_conversions.flux_lora_constants import FLUX_LORA_TRANSFORMER_PREFIX
+from invokeai.backend.patches.model_patch_raw import ModelPatchRaw
+from invokeai.backend.quantization.dequantizing_linear import requires_sidecar_patching
+from invokeai.backend.quantization.int8_convrot import Int8ConvrotLinear
+from invokeai.backend.quantization.nvfp4 import NVFP4Linear
+
+
+def _convert(source: str, stream: str, values: dict[str, torch.Tensor]) -> ModelPatchRaw:
+ if source == "kohya":
+ state = {f"lora_unet_double_blocks_0_{stream}_attn_qkv.{key}": value for key, value in values.items()}
+ return convert_bfl_lora_patch_to_diffusers(lora_model_from_flux_kohya_state_dict(load(save(state))))
+
+ suffixes = {"lora_up.weight": "lora_B.weight", "lora_down.weight": "lora_A.weight"}
+ state = {
+ f"diffusion_model.double_blocks.0.{stream}_attn.qkv.{suffixes.get(key, key)}": value
+ for key, value in values.items()
+ }
+ state = load(save(state))
+ if source == "bfl-built":
+ return convert_bfl_lora_patch_to_diffusers(lora_model_from_flux_bfl_peft_state_dict(state))
+ assert source == "bfl"
+ return lora_model_from_flux2_bfl_peft_state_dict(state)
+
+
+def dora_values() -> dict[str, torch.Tensor]:
+ generator = torch.Generator().manual_seed(10191)
+ return {
+ "lora_up.weight": torch.randn(12, 2, generator=generator),
+ "lora_down.weight": torch.randn(2, 7, generator=generator),
+ "dora_scale": torch.linspace(0.5, 2.0, 12).reshape(12, 1),
+ "alpha": torch.tensor(3.0),
+ "bias_indices": torch.tensor([[1, 4, 6, 11]]),
+ "bias_values": torch.tensor([0.2, -0.3, 0.7, -0.8]),
+ "bias_size": torch.tensor([12]),
+ }
+
+
+class _SplitQKV(torch.nn.Module):
+ def __init__(self, stream: str, in_features: int):
+ super().__init__()
+ self.names = ("to_q", "to_k", "to_v") if stream == "img" else ("add_q_proj", "add_k_proj", "add_v_proj")
+ attention = torch.nn.ModuleDict({name: torch.nn.Linear(in_features, 4) for name in self.names})
+ self.transformer_blocks = torch.nn.ModuleList([torch.nn.ModuleDict({"attn": attention})])
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ attention = self.transformer_blocks[0]["attn"]
+ return torch.cat([attention[name](x) for name in self.names], dim=-1)
+
+
+ "source,stream,sidecar,strength",
+ [("kohya", "img", False, -0.4), ("bfl", "txt", True, 0.65), ("bfl-built", "img", True, 1.0)],
+)
+def test_output_axis_dora_matches_full_fused_forward_and_restores(
+ source: str, stream: str, sidecar: bool, strength: float, dora_values: dict[str, torch.Tensor]
+) -> None:
+ """Compare real patch application to the unsplit formula, including sparse bias and alpha/rank scaling."""
+ patch = _convert(source, stream, dora_values)
+ model = _SplitQKV(stream, in_features=7)
+ if sidecar:
+ apply_custom_layers_to_model(model)
+ attention = model.transformer_blocks[0]["attn"]
+ generator = torch.Generator().manual_seed(200)
+ # Different Q/K/V base weights matter: DoRA's normalization depends on the base, not just the adapter.
+ base_weight = torch.randn(12, 7, generator=generator)
+ base_bias = torch.randn(12, generator=generator)
+ for index, name in enumerate(model.names):
+ attention[name].weight.copy_(base_weight[index * 4 : (index + 1) * 4])
+ attention[name].bias.copy_(base_bias[index * 4 : (index + 1) * 4])
+ original = {name: value.clone() for name, value in model.state_dict().items()}
+ x = torch.randn(2, 3, 7, generator=generator)
+ baseline = model(x)
+
+ # Independent full fused DoRA formula: no split patch/get_weight/get_parameters in the oracle.
+ scale = 3.0 / 2
+ direction = base_weight + scale * (dora_values["lora_up.weight"] @ dora_values["lora_down.weight"])
+ normalized = direction * dora_values["dora_scale"] / torch.linalg.vector_norm(direction, dim=1, keepdim=True)
+ expected_weight = base_weight + strength * (normalized - base_weight)
+ bias_delta = torch.zeros(12)
+ bias_delta[dora_values["bias_indices"][0]] = dora_values["bias_values"]
+ expected = torch.nn.functional.linear(x, expected_weight, base_bias + strength * scale * bias_delta)
+ assert not torch.allclose(expected, baseline, atol=1e-3)
+ assert set(patch.layers) == {f"{FLUX_LORA_TRANSFORMER_PREFIX}transformer_blocks.0.attn.{n}" for n in model.names}
+ assert all(isinstance(layer, DoRALayer) and layer.magnitude_is_out_dim for layer in patch.layers.values())
+
+ # Exercise normal cleanup and exceptional cleanup on the same real modules.
+ for fail in (False, True):
+ try:
+ with LayerPatcher.apply_smart_model_patches(
+ model=model,
+ patches=[(patch, strength)],
+ prefix=FLUX_LORA_TRANSFORMER_PREFIX,
+ dtype=torch.float32,
+ force_direct_patching=not sidecar,
+ force_sidecar_patching=sidecar,
+ ):
+ torch.testing.assert_close(model(x), expected, atol=3e-6, rtol=3e-6)
+ if fail:
+ raise RuntimeError("inference interrupted")
+ except RuntimeError as error:
+ assert fail and str(error) == "inference interrupted"
+ for name, value in model.state_dict().items():
+ torch.testing.assert_close(value, original[name], rtol=0, atol=0)
+ torch.testing.assert_close(model(x), baseline, rtol=0, atol=0)
+ if sidecar:
+ assert all(attention[name].get_num_patches() == 0 for name in model.names)
+
+
[email protected]("source", ["kohya", "bfl"])
[email protected]("in_features", [7, 12])
+def test_output_axis_orientation_survives_square_fused_weights_and_trailing_singletons(
+ source: str, in_features: int, dora_values: dict[str, torch.Tensor]
+) -> None:
+ dora_values["lora_down.weight"] = torch.ones(2, in_features)
+ dora_values["dora_scale"] = dora_values["dora_scale"].reshape(12, 1, 1, 1)
+ patch = _convert(source, "txt", dora_values)
+ assert len(patch.layers) == 3
+ for index, layer in enumerate(patch.layers.values()):
+ assert isinstance(layer, DoRALayer) and layer.magnitude_is_out_dim
+ torch.testing.assert_close(
+ layer.dora_scale.flatten(), torch.linspace(0.5, 2.0, 12)[index * 4 : (index + 1) * 4]
+ )
+
+
+def test_explicit_output_magnitude_vector_stays_output_axis(dora_values: dict[str, torch.Tensor]) -> None:
+ # The built-patch route also receives PEFT/ai-toolkit magnitudes, whose 1-D convention is output-axis.
+ dora_values["dora_magnitude"] = dora_values.pop("dora_scale").flatten()
+ layer = DoRALayer.from_state_dict_values(dora_values)
+ source = ModelPatchRaw({f"{FLUX_LORA_TRANSFORMER_PREFIX}double_blocks.0.img_attn.qkv": layer})
+ patch = convert_bfl_lora_patch_to_diffusers(source)
+ assert len(patch.layers) == 3
+ for index, split in enumerate(patch.layers.values()):
+ assert isinstance(split, DoRALayer) and split.magnitude_is_out_dim
+ assert split.down is layer.down
+ assert split.up.untyped_storage().data_ptr() == layer.up.untyped_storage().data_ptr()
+ torch.testing.assert_close(split.dora_scale, layer.dora_scale[index * 4 : (index + 1) * 4])
+
+
+ "packed,axis", [("int8", "output"), ("nvfp4", "output"), ("int8", "input"), ("nvfp4", "input")]
+)
+def test_converted_dora_on_packed_qkv_and_cleanup(packed: str, axis: str) -> None:
+ """Test packed QKV patching; NVFP4 is a synthetic base for this FLUX.2 test."""
+ values = {
+ "lora_up.weight": torch.ones(384, 2),
+ "lora_down.weight": torch.ones(2, 64),
+ "dora_scale": torch.ones(384, 1) if axis == "output" else torch.ones(1, 64),
+ }
+ patch = _convert("kohya", "img", values)
+ model = _SplitQKV("img", in_features=64)
+ attention = model.transformer_blocks[0]["attn"]
+ for name in model.names:
+ if packed == "int8":
+ attention[name] = Int8ConvrotLinear(
+ torch.ones(128, 64, dtype=torch.int8), torch.ones(128, 1), convrot=False
+ )
+ else:
+ attention[name] = NVFP4Linear(
+ torch.full((128, 32), 0x22, dtype=torch.uint8),
+ torch.ones(128, 4).to(torch.float8_e4m3fn),
+ torch.tensor(1.0),
+ )
+ apply_custom_layers_to_model(model)
+ original = {name: value.clone() for name, value in model.state_dict().items()}
+ x = torch.ones(1, 64, dtype=torch.float32)
+ baseline = model(x)
+ # This is the decision and patch setup used by FLUX2DenoiseInvocation.
+ force_sidecar = requires_sidecar_patching(model, ModelFormat.Checkpoint)
+ assert force_sidecar
+ if axis == "input":
+ with LayerPatcher.apply_smart_model_patches(
+ model=model,
+ patches=[(patch, 0.7)],
+ prefix=FLUX_LORA_TRANSFORMER_PREFIX,
+ dtype=torch.float32,
+ force_sidecar_patching=force_sidecar,
+ ):
+ torch.testing.assert_close(model(x), baseline, rtol=0, atol=0)
+ else:
+ # Both packed fixtures decode to ones. Build the full fused result independently of the split.
+ base = torch.ones(384, 64)
+ direction = base + values["lora_up.weight"] @ values["lora_down.weight"]
+ normalized = values["dora_scale"] * direction / direction.norm(dim=1, keepdim=True)
+ expected = torch.nn.functional.linear(x, base + 0.7 * (normalized - base))
+ with LayerPatcher.apply_smart_model_patches(
+ model=model,
+ patches=[(patch, 0.7)],
+ prefix=FLUX_LORA_TRANSFORMER_PREFIX,
+ dtype=torch.float32,
+ force_sidecar_patching=force_sidecar,
+ ):
+ torch.testing.assert_close(model(x), expected, rtol=1e-5, atol=1e-5)
+ assert all(attention[name].get_num_patches() == 0 for name in model.names)
+ for name, value in model.state_dict().items():
+ torch.testing.assert_close(value.float(), original[name].float(), rtol=0, atol=0)
+ torch.testing.assert_close(model(x), baseline, rtol=0, atol=0)
diff --git a/tests/backend/patches/lora_conversions/test_flux2_dora_quantized_skip.py b/tests/backend/patches/lora_conversions/test_flux2_dora_quantized_skip.py
new file mode 100644
index 0000000000..2c0df48f68
--- /dev/null
+++ b/tests/backend/patches/lora_conversions/test_flux2_dora_quantized_skip.py
@@ -0,0 +1,137 @@
+from contextlib import contextmanager
+from unittest.mock import MagicMock
+
+import gguf
+import pytest
+import torch
+
+from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.torch_module_autocast import (
+ apply_custom_layers_to_model,
+)
+from invokeai.backend.model_manager.taxonomy import ModelFormat
+from invokeai.backend.patches.layer_patcher import LayerPatcher
+from invokeai.backend.patches.lora_conversions import flux_bfl_peft_lora_conversion_utils as conversion
+from invokeai.backend.patches.lora_conversions.flux_lora_constants import FLUX_LORA_TRANSFORMER_PREFIX
+from invokeai.backend.quantization.dequantizing_linear import requires_sidecar_patching
+from invokeai.backend.quantization.int8_convrot import Int8ConvrotLinear
+from invokeai.backend.quantization.nvfp4 import NVFP4Linear
+from invokeai.backend.quantization.sdnq.sdnq_tensor import SDNQTensor
+from invokeai.backend.quantization.sdnq.utils import SDNQQuantizationType
+from tests.backend.quantization.gguf.test_ggml_tensor import quantize_tensor
+
+
+def quantized_linear(kind: str) -> torch.nn.Module:
+ if kind == "int8":
+ return Int8ConvrotLinear(torch.ones(128, 64, dtype=torch.int8), torch.ones(128, 1), convrot=False)
+ if kind == "nvfp4":
+ return NVFP4Linear(
+ torch.full((128, 32), 0x22, dtype=torch.uint8),
+ torch.ones(128, 4).to(torch.float8_e4m3fn),
+ torch.tensor(1.0),
+ )
+ linear = torch.nn.Linear(64, 128, bias=False)
+ if kind == "gguf":
+ weight = quantize_tensor(torch.ones(128, 64), gguf.GGMLQuantizationType.Q8_0)
+ else:
+ assert kind == "sdnq"
+ weight = SDNQTensor(
+ data=torch.ones(128, 64, dtype=torch.int8),
+ quantization_type=SDNQQuantizationType.INT8_SYM,
+ tensor_shape=torch.Size((128, 64)),
+ compute_dtype=torch.float32,
+ scale=torch.ones(1),
+ )
+ linear.weight = torch.nn.Parameter(weight, requires_grad=False)
+ return linear
+
+
+def model_and_state(kind: str, mixed: bool):
+ attention = torch.nn.ModuleDict({name: quantized_linear(kind) for name in ("to_q", "to_k", "to_v")})
+ if mixed:
+ attention["to_k"] = torch.nn.Linear(64, 128, bias=False)
+ model = torch.nn.Module()
+ model.transformer_blocks = torch.nn.ModuleList([torch.nn.ModuleDict({"attn": attention})])
+ model.proj = quantized_linear(kind)
+ apply_custom_layers_to_model(model)
+ state = {}
+ for key, outputs in (("double_blocks.0.img_attn.qkv", 384), ("proj", 128)):
+ state[f"diffusion_model.{key}.lora_A.weight"] = torch.ones(2, 64) * 0.1
+ state[f"diffusion_model.{key}.lora_B.weight"] = torch.ones(outputs, 2) * 0.2
+ state[f"diffusion_model.{key}.dora_scale"] = torch.ones(1, 64) * 3
+ return model, state
+
+
[email protected]("kind", ["gguf", "sdnq", "int8", "nvfp4"])
[email protected]("mixed", [False, True])
[email protected]("interrupt", [False, True])
+def test_quantized_fused_group_warns_and_skips_but_unfused_dora_applies(kind, mixed, interrupt, monkeypatch):
+ model, state = model_and_state(kind, mixed)
+ attention = model.transformer_blocks[0]["attn"]
+ logger = MagicMock()
+ monkeypatch.setattr(conversion, "logger", logger)
+ monkeypatch.setattr("invokeai.backend.patches.layer_patcher.InvokeAILogger.get_logger", lambda _: logger)
+ patch = conversion.lora_model_from_flux2_bfl_peft_state_dict(state)
+ x = torch.ones(1, 64)
+ baseline = [attention[name](x).clone() for name in ("to_q", "to_k", "to_v")]
+ baseline_proj = model.proj(x).clone()
+ active = []
+
+ @contextmanager
+ def pin():
+ active.append(True)
+ try:
+ yield
+ finally:
+ active.pop()
+
+ model_format = {"gguf": ModelFormat.GGUFQuantized, "sdnq": ModelFormat.SDNQQuantized}.get(
+ kind, ModelFormat.Checkpoint
+ )
+ assert requires_sidecar_patching(model, model_format)
+ with pytest.raises(RuntimeError, match="cancelled") if interrupt else _no_exception():
+ with LayerPatcher.apply_smart_model_patches(
+ model=model,
+ patches=[(patch, 0.7, pin())],
+ prefix=FLUX_LORA_TRANSFORMER_PREFIX,
+ dtype=torch.float32,
+ force_sidecar_patching=True,
+ ):
+ assert active
+ for index, name in enumerate(("to_q", "to_k", "to_v")):
+ assert attention[name].get_num_patches() == 0
+ torch.testing.assert_close(attention[name](x), baseline[index], rtol=0, atol=0)
+ assert model.proj.get_num_patches() == 1
+ assert not torch.allclose(model.proj(x), baseline_proj)
+ if interrupt:
+ raise RuntimeError("cancelled")
+ assert not active
+ assert logger.warning.call_count == 1
+ assert "skip" in str(logger.warning.call_args).lower()
+ assert all(attention[name].get_num_patches() == 0 for name in ("to_q", "to_k", "to_v"))
+ assert model.proj.get_num_patches() == 0
+ torch.testing.assert_close(model.proj(x), baseline_proj, rtol=0, atol=0)
+
+
+@contextmanager
+def _no_exception():
+ yield
+
+
[email protected]("kind", ["gguf", "sdnq", "int8", "nvfp4"])
+def test_quantized_fused_group_does_not_hide_malformed_dimensions(kind):
+ model, state = model_and_state(kind, False)
+ patch = conversion.lora_model_from_flux2_bfl_peft_state_dict(state)
+ fused = next(layer for key, layer in patch.layers.items() if "to_q" in key)
+ fused.layer.down = torch.ones(2, 63)
+ with (
+ pytest.raises(RuntimeError, match="dimensions"),
+ LayerPatcher.apply_smart_model_patches(
+ model=model,
+ patches=[(patch, 1)],
+ prefix=FLUX_LORA_TRANSFORMER_PREFIX,
+ dtype=torch.float32,
+ force_sidecar_patching=True,
+ ),
+ ):
+ pytest.fail("malformed adapter must fail")
diff --git a/tests/backend/patches/lora_conversions/test_flux2_dora_review_followup.py b/tests/backend/patches/lora_conversions/test_flux2_dora_review_followup.py
new file mode 100644
index 0000000000..89be6a56fd
--- /dev/null
+++ b/tests/backend/patches/lora_conversions/test_flux2_dora_review_followup.py
@@ -0,0 +1,207 @@
+import copy
+
+import pytest
+import torch
+
+from invokeai.backend.flux2.denoise_working_memory import flux2_dora_patch_bytes
+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.dora_layer import DoRALayer
+from invokeai.backend.patches.lora_conversions.flux_bfl_peft_lora_conversion_utils import (
+ convert_bfl_lora_patch_to_diffusers,
+)
+from invokeai.backend.patches.lora_conversions.flux_lora_constants import FLUX_LORA_TRANSFORMER_PREFIX
+from invokeai.backend.patches.model_patch_raw import ModelPatchRaw
+from invokeai.backend.quantization.int8_convrot import Int8ConvrotLinear
+from tests.backend.patches.lora_conversions.test_flux2_dora_application import SplitAttention, load_adapter, load_state
+from tests.backend.patches.lora_conversions.test_flux2_dora_qkv_conversion import _SplitQKV
+from tests.backend.patches.test_sidecar_working_memory import _PeakAllocation
+
+
[email protected]("fp8", [False, True])
+def test_patcher_binds_norm_to_sidecar_compute_dtype(fp8):
+ model = _SplitQKV("img", 7)
+ attention = model.transformer_blocks[0]["attn"]
+ for i, module in enumerate(attention.values()):
+ module.weight.fill_(1.003 + i * 0.0001 if not fp8 else 1)
+ if fp8:
+ module.weight = torch.nn.Parameter(module.weight.to(torch.float8_e4m3fn), requires_grad=False)
+ module.register_buffer("weight_scale", torch.tensor(1.003 + i * 0.0001))
+ apply_custom_layers_to_model(model)
+ layer = DoRALayer(torch.zeros(12, 1), torch.zeros(1, 7), torch.ones(1, 7), None, None)
+ patch = convert_bfl_lora_patch_to_diffusers(
+ ModelPatchRaw({f"{FLUX_LORA_TRANSFORMER_PREFIX}double_blocks.0.img_attn.qkv": layer})
+ )
+ bases = [
+ module._cast_weight_bias_for_input(torch.ones(1, 7, dtype=torch.bfloat16))[0] for module in attention.values()
+ ]
+ base = torch.cat(bases).float()
+ expected = base / base.norm(dim=0, keepdim=True) - base
+ with LayerPatcher.apply_smart_model_patches(
+ model=model,
+ patches=[(patch, 1.0)],
+ prefix=FLUX_LORA_TRANSFORMER_PREFIX,
+ dtype=torch.bfloat16,
+ force_sidecar_patching=True,
+ ):
+ actual = torch.cat(
+ [
+ module._patches_and_weights[0][0].get_weight(base)
+ for module, base in zip(attention.values(), bases, strict=True)
+ ]
+ )
+ torch.testing.assert_close(actual, expected, atol=1e-6, rtol=1e-6)
+
+
+def test_fused_input_norm_matches_actual_sidecar_base_dtype():
+ model = _SplitQKV("img", 7)
+ attention = model.transformer_blocks[0]["attn"]
+ for i, module in enumerate(attention.values()):
+ module.weight.fill_(1.003 + i * 0.0001)
+ layer = DoRALayer(torch.zeros(12, 1), torch.zeros(1, 7), torch.ones(1, 7), None, None)
+ patch = convert_bfl_lora_patch_to_diffusers(
+ ModelPatchRaw({f"{FLUX_LORA_TRANSFORMER_PREFIX}double_blocks.0.img_attn.qkv": layer})
+ )
+ bound = next(iter(patch.layers.values())).bind(model, (torch.bfloat16,) * 3)
+ base = torch.cat([module.weight for module in attention.values()]).to(torch.bfloat16).float()
+ expected = base / base.norm(dim=0, keepdim=True) - base
+ residual = torch.cat(
+ [
+ part.get_weight(module.weight.to(torch.bfloat16))
+ for (_, part), module in zip(bound, attention.values(), strict=True)
+ ]
+ )
+ torch.testing.assert_close(residual.float(), expected, atol=1e-6, rtol=1e-6)
+
+
+def test_output_axis_bfloat16_small_direction_residual_survives():
+ base = torch.ones(4, 7, dtype=torch.bfloat16)
+ up = torch.tensor([[0.001953125], [-0.001953125], [0.001953125], [-0.001953125]], dtype=torch.bfloat16)
+ down = torch.tensor([[1, 0, 0, 0, 0, 0, 0]], dtype=torch.bfloat16)
+ magnitude = torch.full((4,), 2.640625, dtype=torch.bfloat16)
+ layer = DoRALayer(up, down, magnitude, None, None, magnitude_is_out_dim=True)
+ direction = base.float() + up.float() @ down.float()
+ expected = magnitude.float().reshape(-1, 1) * direction / direction.norm(dim=1, keepdim=True) - base.float()
+ torch.testing.assert_close(layer.get_weight(base).float(), expected, atol=1e-6, rtol=1e-6)
+
+
+def test_split_factors_do_not_retain_duplicate_promotions():
+ model = _SplitQKV("img", 7)
+ layer = DoRALayer(
+ torch.ones(12, 2, dtype=torch.bfloat16),
+ torch.ones(2, 7, dtype=torch.bfloat16),
+ torch.ones(1, 7, dtype=torch.bfloat16),
+ None,
+ None,
+ )
+ patch = convert_bfl_lora_patch_to_diffusers(
+ ModelPatchRaw({f"{FLUX_LORA_TRANSFORMER_PREFIX}double_blocks.0.img_attn.qkv": layer})
+ )
+ parts = [part for _, part in next(iter(patch.layers.values())).bind(model)]
+ for part in parts:
+ part.to(device=torch.device("cpu"), dtype=torch.bfloat16)
+ assert all(part.down.dtype == torch.bfloat16 for part in parts)
+ assert len({part.down.untyped_storage().data_ptr() for part in parts}) == 1
+
+
[email protected]("suffix", ["lora_magnitude_vector.weight", "lora_magnitude_vector", "magnitude"])
+def test_bfl_magnitude_loads_from_safetensors(tmp_path, suffix):
+ prefix = "diffusion_model.double_blocks.0.img_attn.qkv"
+ state = {
+ f"{prefix}.lora_A.weight": torch.ones(2, 7),
+ f"{prefix}.lora_B.weight": torch.ones(12, 2),
+ f"{prefix}.{suffix}": torch.arange(1, 13, dtype=torch.float32),
+ }
+ patch = convert_bfl_lora_patch_to_diffusers(load_state(tmp_path, state))
+ layers = list(patch.layers.values())
+ assert len(layers) == 3
+ assert all(isinstance(layer, DoRALayer) and layer.magnitude_is_out_dim for layer in layers)
+ torch.testing.assert_close(torch.cat([layer.dora_scale for layer in layers]), state[f"{prefix}.{suffix}"])
+
+
[email protected]("sidecar", [False, True])
+def test_dora_budget_covers_live_cpu_tensor_allocations(tmp_path, sidecar):
+ adapter, _ = load_adapter(tmp_path, "input", "kohya", torch.bfloat16)
+ patch = convert_bfl_lora_patch_to_diffusers(adapter)
+ model = SplitAttention(14)
+ attention = model.transformer_blocks[0]["attn"]
+ for module in attention.values():
+ module.weight.data = module.weight.data.to(torch.float8_e4m3fn if sidecar else torch.bfloat16)
+ if sidecar:
+ module.register_buffer("weight_scale", torch.linspace(0.6, 1.0, 4))
+ patches = [
+ (ModelPatchRaw({key: copy.copy(layer) for key, layer in patch.layers.items()}), strength)
+ for strength in (0.5, -0.6)
+ ]
+ x = torch.randn(5, 7)
+ budget = flux2_dora_patch_bytes(model, patches, dtype=x.dtype, rows=x.shape[0])
+ allocation = _PeakAllocation()
+ with (
+ allocation,
+ LayerPatcher.apply_smart_model_patches(
+ model=model,
+ patches=patches,
+ prefix=FLUX_LORA_TRANSFORMER_PREFIX,
+ dtype=x.dtype,
+ force_direct_patching=not sidecar,
+ ),
+ ):
+ if sidecar:
+ attention["to_q"](x)
+ assert 0 < allocation.peak <= budget
+
+
+def test_dev_width_dora_reserves_more_than_one_flat_adapter_allowance(tmp_path):
+ width = 6144
+ model = SplitAttention(0)
+ attention = model.transformer_blocks[0]["attn"]
+ for name in model.names[:3]:
+ attention[name] = torch.nn.Linear(width, width, bias=False, device="meta", dtype=torch.bfloat16)
+ key = "lora_unet_double_blocks_0_img_attn_qkv"
+ adapter = load_state(
+ tmp_path,
+ {
+ f"{key}.lora_up.weight": torch.ones(3 * width, 2),
+ f"{key}.lora_down.weight": torch.ones(2, width),
+ f"{key}.dora_scale": torch.ones(1, width),
+ },
+ torch.bfloat16,
+ )
+ patch = convert_bfl_lora_patch_to_diffusers(adapter)
+ budget = flux2_dora_patch_bytes(model, [(patch, 0.5)], dtype=torch.bfloat16, rows=1)
+ # Four concurrently live FP32 matrices in the direction/residual calculation alone.
+ assert budget >= 4 * width * width * torch.float32.itemsize > 512 * 2**20
+ assert flux2_dora_patch_bytes(model, [(patch, 0.0)], dtype=torch.bfloat16, rows=1) == 0
+
+
+def test_klein_width_packed_dora_prices_the_unpacked_projection_shape(tmp_path):
+ in_features, out_features = 4096, 36864
+ model = torch.nn.Module()
+ block = torch.nn.Module()
+ block.attn = torch.nn.Module()
+ block.attn.to_qkv_mlp_proj = Int8ConvrotLinear(
+ torch.empty(out_features, in_features, device="meta", dtype=torch.int8),
+ torch.empty(out_features, 1, device="meta"),
+ convrot=True,
+ )
+ model.single_transformer_blocks = torch.nn.ModuleList([block])
+ key = "diffusion_model.single_blocks.0.linear1"
+ patch = load_state(
+ tmp_path,
+ {
+ f"{key}.lora_A.weight": torch.ones(2, in_features),
+ f"{key}.lora_B.weight": torch.ones(out_features, 2),
+ f"{key}.dora_scale": torch.ones(out_features, 1),
+ },
+ torch.bfloat16,
+ )
+ budget = flux2_dora_patch_bytes(
+ model, [(convert_bfl_lora_patch_to_diffusers(patch), 0.5)], dtype=torch.bfloat16, rows=1
+ )
+ assert budget >= 4 * in_features * out_features * torch.float32.itemsize
diff --git a/tests/backend/patches/test_layer_patcher.py b/tests/backend/patches/test_layer_patcher.py
index c7a9caa88f..4b8ab188d8 100644
--- a/tests/backend/patches/test_layer_patcher.py
+++ b/tests/backend/patches/test_layer_patcher.py
@@ -829,6 +829,8 @@ def test_direct_patching_that_fails_still_returns_the_cached_patch(
# 12 output rows cannot be reshaped onto the module's 16.
patch = ModelPatchRaw(layers={"linear_layer_1": make_layer(8, 12)})
before = _placements(patch)
+ [(leaf, _, _)] = LayerPatcher._leaf_placements(patch.layers["linear_layer_1"])
+ up, down = leaf.up, leaf.down
with pytest.raises(RuntimeError, match="is invalid for input of size"):
with LayerPatcher.apply_smart_model_patches(
@@ -837,6 +839,7 @@ def test_direct_patching_that_fails_still_returns_the_cached_patch(
pass
assert _placements(patch) == before
+ assert leaf.up is up and leaf.down is down
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires a GPU")