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.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
fix(lora): apply FLUX final-layer modulation LoRA layers with swapped scale/shift halves (#10052)
Alexander Eichhorn3570f1012620
diff --git a/invokeai/backend/patches/layer_patcher.py b/invokeai/backend/patches/layer_patcher.pyindex 2546db2304..7b52d60937 100644--- a/invokeai/backend/patches/layer_patcher.py+++ b/invokeai/backend/patches/layer_patcher.py@@ -41,10 +41,10 @@ class LayerPatcher:original_weights = OriginalWeightsStorage(cached_weights)# original_modules are stored for unpatching layers that are wrapped.original_modules: dict[str, torch.nn.Module] = {}- # Where each sidecar-applied patch's tensors lived before it was moved onto the device, so- # the `finally` can put them back. Keyed by identity: one patch object can be applied to many+ # Where each sidecar-applied leaf patch's tensors lived before they were moved onto the device,+ # so the `finally` can put them back. Keyed by identity: one patch object can be applied to many# modules, and only its first, pre-move placement is the one to restore.- patch_placements: dict[int, tuple[BaseLayerPatch, torch.device | None, torch.dtype | None]] = {}+ patch_placements: dict[int, tuple[BaseLayerPatch, torch.device, torch.dtype]] = {}cache_pins = ExitStack()try:# Materialize the patch iterable BEFORE acquiring the read lock. Callers pass a lazy@@ -103,8 +103,8 @@ class LayerPatcher:# Return every sidecar-applied patch to where it came from. `clear_patches()` only# drops the module's reference; without this the tensors stay on the device, inside# an object the model cache owns and believes is in RAM.- for patch, patch_device, patch_dtype in patch_placements.values():- patch.to(device=patch_device, dtype=patch_dtype)+ for leaf, leaf_device, leaf_dtype in patch_placements.values():+ leaf.to(device=leaf_device, dtype=leaf_dtype)finally:cache_pins.close()@@ -117,7 +117,7 @@ class LayerPatcher:patch_weight: float,original_weights: OriginalWeightsStorage,original_modules: dict[str, torch.nn.Module],- patch_placements: dict[int, tuple[BaseLayerPatch, torch.device | None, torch.dtype | None]],+ patch_placements: dict[int, tuple[BaseLayerPatch, torch.device, torch.dtype]],dtype: torch.dtype,force_direct_patching: bool,force_sidecar_patching: bool,@@ -240,80 +240,94 @@ class LayerPatcher:## `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.- original_device, original_dtype = LayerPatcher._patch_placement(patch)- patch.to(device=device)- patch.to(dtype=torch.float32)-- # TODO(ryand): Using torch.autocast(...) over explicit casting may offer a speed benefit on CUDA- # devices here. Experimentally, it was found to be very slow on CPU. More investigation needed.- params_dict = patch.get_parameters(dict(module_to_patch.named_parameters(recurse=False)), weight=patch_weight)- if not params_dict:- logger = InvokeAILogger.get_logger(LayerPatcher.__name__)- logger.warning(f"LoRA patch returned no parameters for module: {module_to_patch_key}")- return-- for param_name, param_weight in params_dict.items():- param_key = module_to_patch_key + "." + param_name- module_param = module_to_patch.get_parameter(param_name)-- # Save original weight- original_weights.save(param_key, module_param)-- # Handle layers that change the shape of the original layer.- # FLUX control LoRAs intentionally expand certain layers - we pad the original weight with zeros.- # For other LoRAs (e.g., Z-Image with architecture mismatch), skip incompatible layers with a warning.- if module_param.nelement() != param_weight.nelement():- if isinstance(patch, FluxControlLoRALayer):- # FLUX Control LoRAs intentionally expand layers - pad with zeros- expanded_weight = pad_with_zeros(module_param, param_weight.shape)- setattr(- module_to_patch,- param_name,- torch.nn.Parameter(expanded_weight, requires_grad=module_param.requires_grad),- )- # Point at the module's live (expanded) parameter so the out-of-place weight- # update below lands on the module. `expanded_weight` is a detached raw tensor;- # reassigning its `.data` would not propagate to the newly-set Parameter.- module_param = module_to_patch.get_parameter(param_name)- else:- # For other LoRAs, shape mismatch indicates architecture incompatibility - skip the layer- logger = InvokeAILogger.get_logger(LayerPatcher.__name__)- logger.warning(- f"Skipping LoRA layer '{module_to_patch_key}.{param_name}' due to shape mismatch: "- f"model has {module_param.nelement()} elements, LoRA expects {param_weight.nelement()}. "- "This LoRA may be incompatible with this model architecture."- )- continue-- # Convert param_weight to the correct device and dtype, then apply to model weights.- param_weight_converted = param_weight.to(device=device, dtype=dtype)- # Apply out-of-place (assign a new tensor) rather than an in-place `copy_`. The weight we- # are patching may be the model's canonical CPU copy, which is shared across the- # per-device model caches in multi-GPU mode (see SharedCpuWeightsStore) and is also the- # cache's keep_ram_copy used to restore the model after unpatching. An in-place mutation- # here would corrupt that shared/cached tensor — and every other device's view of it.- # Reassigning `.data` leaves the original tensor untouched while giving this module the- # patched weights, and is memory-equivalent (the in-place form already allocated the- # `module_param.data + param_weight_converted` temporary).- module_param.data = module_param.data + param_weight_converted-- # 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()`.- patch.to(device=original_device, dtype=original_dtype)+ # 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)+ try:+ patch.to(device=device)+ patch.to(dtype=torch.float32)++ # TODO(ryand): Using torch.autocast(...) over explicit casting may offer a speed benefit on CUDA+ # devices here. Experimentally, it was found to be very slow on CPU. More investigation needed.+ params_dict = patch.get_parameters(+ dict(module_to_patch.named_parameters(recurse=False)), weight=patch_weight+ )+ if not params_dict:+ logger = InvokeAILogger.get_logger(LayerPatcher.__name__)+ logger.warning(f"LoRA patch returned no parameters for module: {module_to_patch_key}")+ return++ for param_name, param_weight in params_dict.items():+ param_key = module_to_patch_key + "." + param_name+ module_param = module_to_patch.get_parameter(param_name)++ # Save original weight+ original_weights.save(param_key, module_param)++ # Handle layers that change the shape of the original layer.+ # FLUX control LoRAs intentionally expand certain layers - we pad the original weight with zeros.+ # For other LoRAs (e.g., Z-Image with architecture mismatch), skip incompatible layers with a warning.+ if module_param.nelement() != param_weight.nelement():+ if isinstance(patch, FluxControlLoRALayer):+ # FLUX Control LoRAs intentionally expand layers - pad with zeros+ expanded_weight = pad_with_zeros(module_param, param_weight.shape)+ setattr(+ module_to_patch,+ param_name,+ torch.nn.Parameter(expanded_weight, requires_grad=module_param.requires_grad),+ )+ # Point at the module's live (expanded) parameter so the out-of-place weight+ # update below lands on the module. `expanded_weight` is a detached raw tensor;+ # reassigning its `.data` would not propagate to the newly-set Parameter.+ module_param = module_to_patch.get_parameter(param_name)+ else:+ # For other LoRAs, shape mismatch indicates architecture incompatibility - skip the layer+ logger = InvokeAILogger.get_logger(LayerPatcher.__name__)+ logger.warning(+ f"Skipping LoRA layer '{module_to_patch_key}.{param_name}' due to shape mismatch: "+ f"model has {module_param.nelement()} elements, LoRA expects {param_weight.nelement()}. "+ "This LoRA may be incompatible with this model architecture."+ )+ continue++ # Convert param_weight to the correct device and dtype, then apply to model weights.+ param_weight_converted = param_weight.to(device=device, dtype=dtype)+ # Apply out-of-place (assign a new tensor) rather than an in-place `copy_`. The weight we+ # are patching may be the model's canonical CPU copy, which is shared across the+ # per-device model caches in multi-GPU mode (see SharedCpuWeightsStore) and is also the+ # cache's keep_ram_copy used to restore the model after unpatching. An in-place mutation+ # here would corrupt that shared/cached tensor — and every other device's view of it.+ # Reassigning `.data` leaves the original tensor untouched while giving this module the+ # patched weights, and is memory-equivalent (the in-place form already allocated the+ # `module_param.data + param_weight_converted` temporary).+ 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)@staticmethod- def _patch_placement(patch: BaseLayerPatch) -> tuple[torch.device | None, torch.dtype | None]:- """The device and dtype a patch's tensors currently sit on, so they can be put back.+ def _leaf_placements(patch: BaseLayerPatch) -> list[tuple[BaseLayerPatch, torch.device, torch.dtype]]:+ """The device and dtype each leaf patch's tensors currently sit on, so they can be put back.Patches carry their tensors in subclass-specific attributes rather than as registered- parameters, so this reads the first real tensor instead of relying on `nn.Module` state.+ parameters, so a leaf's placement is read from its first real tensor instead of from+ `nn.Module` state. Wrapper patches (`MergedLayerPatch`, `SwappedHalvesLayerPatch`) hold only+ 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."""- for value in vars(patch).values():- if isinstance(value, torch.Tensor):- return value.device, value.dtype- return None, None+ sub_patches = [+ item+ for value in vars(patch).values()+ for item in (value if isinstance(value, (list, tuple)) else (value,))+ if isinstance(item, BaseLayerPatch)+ ]+ if sub_patches:+ return [leaf for sub_patch in sub_patches 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)]@staticmethod@torch.no_grad()@@ -323,7 +337,7 @@ class LayerPatcher:patch: BaseLayerPatch,patch_weight: float,original_modules: dict[str, torch.nn.Module],- patch_placements: dict[int, tuple[BaseLayerPatch, torch.device | None, torch.dtype | None]],+ patch_placements: dict[int, tuple[BaseLayerPatch, torch.device, torch.dtype]],dtype: torch.dtype,):"""Apply a single LoRA wrapper patch to a module."""@@ -339,7 +353,8 @@ class LayerPatcher:# device. The record is RAM-pinned, so `cur_vram_bytes()` reports zero for it and# `full_unload_from_vram()` early-returns -- the cache cannot reclaim what it cannot see.# Recorded here and restored in the `finally`.- patch_placements.setdefault(id(patch), (patch, *LayerPatcher._patch_placement(patch)))+ for leaf_placement in LayerPatcher._leaf_placements(patch):+ patch_placements.setdefault(id(leaf_placement[0]), leaf_placement)patch.to(device=device, dtype=dtype)if module_to_patch_key not in original_modules:diff --git a/invokeai/backend/patches/layers/swapped_halves_layer_patch.py b/invokeai/backend/patches/layers/swapped_halves_layer_patch.pynew file mode 100644index 0000000000..acbffa79b4--- /dev/null+++ b/invokeai/backend/patches/layers/swapped_halves_layer_patch.py@@ -0,0 +1,37 @@+import torch++from invokeai.backend.patches.layers.base_layer_patch import BaseLayerPatch+++def _swap_halves(t: torch.Tensor) -> torch.Tensor:+ # index_select rather than chunk + cat: it also handles the sparse COO bias a LyCORIS layer can carry.+ n = t.shape[0]+ return t.index_select(0, torch.arange(n, device=t.device).roll(n // 2))+++class SwappedHalvesLayerPatch(BaseLayerPatch):+ """Applies a patch written for a layer whose output is split into two halves, to a module that stores those halves+ in the opposite order along the first (output) axis.++ The FLUX final-layer modulation is the case this exists for: diffusers' `AdaLayerNormContinuous` (`norm_out.linear`)+ orders its output as (scale, shift), BFL's `LastLayer` (`final_layer.adaLN_modulation.1`) as (shift, scale).+ Wrapping the built patch works for every layer type (LoRA, DoRA, LoHA, LoKR, full) without rearranging their+ factors.+ """++ def __init__(self, layer: BaseLayerPatch):+ super().__init__()+ self.layer = layer++ def get_parameters(self, orig_parameters: dict[str, torch.Tensor], weight: float) -> dict[str, torch.Tensor]:+ # The inner layer sees the original parameters in its own layout, so layers that read their values (DoRA)+ # stay exact. Swapping meta tensors keeps their shapes valid for shape-only layers.+ source_layout_parameters = {name: _swap_halves(param) for name, param in orig_parameters.items()}+ out_parameters = self.layer.get_parameters(source_layout_parameters, weight)+ return {name: _swap_halves(param) for name, param in out_parameters.items()}++ 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_bfl_peft_lora_conversion_utils.py b/invokeai/backend/patches/lora_conversions/flux_bfl_peft_lora_conversion_utils.pyindex 073704c6c7..faed919036 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@@ -29,6 +29,7 @@ from invokeai.backend.patches.layers.loha_layer import LoHALayerfrom invokeai.backend.patches.layers.lokr_layer import LoKRLayerfrom invokeai.backend.patches.layers.lora_layer import LoRALayerfrom invokeai.backend.patches.layers.merged_layer_patch import MergedLayerPatch, Range+from invokeai.backend.patches.layers.swapped_halves_layer_patch import SwappedHalvesLayerPatchfrom invokeai.backend.patches.layers.utils import any_lora_layer_from_state_dictfrom invokeai.backend.patches.lora_conversions.flux_lora_constants import FLUX_LORA_TRANSFORMER_PREFIXfrom invokeai.backend.patches.model_patch_raw import ModelPatchRaw@@ -119,6 +120,11 @@ _NON_BLOCK_RENAMES: dict[str, str] = {"time_in.out_layer": "time_guidance_embed.timestep_embedder.linear_2",}+# The final-layer modulation also orders its output halves differently: (shift, scale) in BFL's LastLayer,+# (scale, shift) in diffusers' AdaLayerNormContinuous. Its patches are wrapped in a SwappedHalvesLayerPatch.+_BFL_FINAL_MODULATION_KEY = "final_layer.adaLN_modulation.1"+_DIFFUSERS_FINAL_MODULATION_KEY = "norm_out.linear"+def is_state_dict_likely_in_flux_bfl_peft_format(state_dict: dict[str | int, torch.Tensor]) -> bool:"""Checks if the provided state dict is likely in the BFL PEFT FLUX LoRA/LyCORIS format.@@ -339,6 +345,8 @@ def _convert_bfl_layer_patch_to_diffusers(bfl_key: str, layer: BaseLayerPatch) -return [(f"{diff_prefix}.{rest}", layer)]# Non-block keys (embedders, modulations, output layers)+ if bfl_key == _BFL_FINAL_MODULATION_KEY:+ return [(_DIFFUSERS_FINAL_MODULATION_KEY, SwappedHalvesLayerPatch(layer))]if bfl_key in _NON_BLOCK_RENAMES:return [(_NON_BLOCK_RENAMES[bfl_key], layer)]diff --git a/invokeai/backend/patches/lora_conversions/flux_diffusers_lora_conversion_utils.py b/invokeai/backend/patches/lora_conversions/flux_diffusers_lora_conversion_utils.pyindex 578c20cce1..56b7237268 100644--- a/invokeai/backend/patches/lora_conversions/flux_diffusers_lora_conversion_utils.py+++ b/invokeai/backend/patches/lora_conversions/flux_diffusers_lora_conversion_utils.py@@ -4,6 +4,7 @@ import torchfrom invokeai.backend.patches.layers.base_layer_patch import BaseLayerPatchfrom invokeai.backend.patches.layers.merged_layer_patch import MergedLayerPatch, Range+from invokeai.backend.patches.layers.swapped_halves_layer_patch import SwappedHalvesLayerPatchfrom invokeai.backend.patches.layers.utils import any_lora_layer_from_state_dictfrom invokeai.backend.patches.lora_conversions.flux_lora_constants import (FLUX_LORA_CLIP_PREFIX,@@ -303,6 +304,10 @@ def lora_layers_from_flux_diffusers_grouped_state_dict(# Final layer.add_lora_layer_if_present("proj_out", "final_layer.linear")+ # The modulation output halves are (scale, shift) in diffusers and (shift, scale) in BFL.+ if "norm_out.linear" in grouped_state_dict:+ values = get_lora_layer_values(grouped_state_dict.pop("norm_out.linear"))+ layers["final_layer.adaLN_modulation.1"] = SwappedHalvesLayerPatch(any_lora_layer_from_state_dict(values))# Assert that all keys were processed.assert len(grouped_state_dict) == 0diff --git a/invokeai/backend/stable_diffusion/extensions/lora.py b/invokeai/backend/stable_diffusion/extensions/lora.pyindex 323a665f54..cedca7b2fb 100644--- a/invokeai/backend/stable_diffusion/extensions/lora.py+++ b/invokeai/backend/stable_diffusion/extensions/lora.py@@ -48,7 +48,7 @@ class LoRAExt(ExtensionBase):# believes is in RAM. That matters here despite `force_direct_patching`, for the fp8 reason# in the comment above.original_modules: dict[str, torch.nn.Module] = {}- patch_placements: dict[int, tuple[BaseLayerPatch, torch.device | None, torch.dtype | None]] = {}+ patch_placements: dict[int, tuple[BaseLayerPatch, torch.device, torch.dtype]] = {}with lora_info.model_in_ram() as lora_model:LayerPatcher.apply_smart_model_patch(@@ -70,5 +70,5 @@ class LoRAExt(ExtensionBase):finally:for module in original_modules.values():module.clear_patches()- for patch, patch_device, patch_dtype in patch_placements.values():- patch.to(device=patch_device, dtype=patch_dtype)+ for leaf, leaf_device, leaf_dtype in patch_placements.values():+ leaf.to(device=leaf_device, dtype=leaf_dtype)diff --git a/tests/backend/model_manager/load/model_cache/torch_module_autocast/custom_modules/test_all_custom_modules.py b/tests/backend/model_manager/load/model_cache/torch_module_autocast/custom_modules/test_all_custom_modules.pyindex 087f1474f6..c35bea1745 100644--- a/tests/backend/model_manager/load/model_cache/torch_module_autocast/custom_modules/test_all_custom_modules.py+++ b/tests/backend/model_manager/load/model_cache/torch_module_autocast/custom_modules/test_all_custom_modules.py@@ -19,6 +19,7 @@ from invokeai.backend.patches.layers.flux_control_lora_layer import FluxControlLfrom invokeai.backend.patches.layers.lokr_layer import LoKRLayerfrom invokeai.backend.patches.layers.lora_layer import LoRALayerfrom invokeai.backend.patches.layers.merged_layer_patch import MergedLayerPatch, Range+from invokeai.backend.patches.layers.swapped_halves_layer_patch import SwappedHalvesLayerPatchfrom invokeai.backend.quantization.sdnq.sdnq_tensor import SDNQTensorfrom invokeai.backend.quantization.sdnq.utils import SDNQQuantizationTypefrom invokeai.backend.util.original_weights_storage import OriginalWeightsStorage@@ -390,6 +391,7 @@ def _is_bnb_quantized_linear(layer: torch.nn.Module) -> bool:"single_lora","multiple_loras","concatenated_lora",+ "swapped_halves_lora","flux_control_lora","single_lokr","single_dora",@@ -452,6 +454,16 @@ def patch_under_test(request: pytest.FixtureRequest) -> PatchUnderTest:input = torch.randn(1, in_features)return ([(merged_layer_patch, 0.7)], input)+ elif layer_type == "swapped_halves_lora":+ lora_layer = LoRALayer(+ up=torch.randn(out_features, rank),+ mid=None,+ down=torch.randn(rank, in_features),+ alpha=1.0,+ bias=torch.randn(out_features),+ )+ input = torch.randn(1, in_features)+ return ([(SwappedHalvesLayerPatch(lora_layer), 0.7)], input)elif layer_type == "flux_control_lora":# Create a FluxControlLoRALayer.patched_in_features = 40diff --git a/tests/backend/patches/layers/test_swapped_halves_layer_patch.py b/tests/backend/patches/layers/test_swapped_halves_layer_patch.pynew file mode 100644index 0000000000..e2ecbb7ac0--- /dev/null+++ b/tests/backend/patches/layers/test_swapped_halves_layer_patch.py@@ -0,0 +1,96 @@+import torch++from invokeai.backend.patches.layers.dora_layer import DoRALayer+from invokeai.backend.patches.layers.lora_layer import LoRALayer+from invokeai.backend.patches.layers.swapped_halves_layer_patch import SwappedHalvesLayerPatch++OUT_FEATURES = 12 # Two halves of 6, like the (shift, scale) / (scale, shift) modulation output.+IN_FEATURES = 5+RANK = 3+++def _swap(t: torch.Tensor) -> torch.Tensor:+ half = t.shape[0] // 2+ return torch.cat([t[half:], t[:half]], dim=0)++[email protected]_grad()+def test_lora_weight_and_bias_land_in_the_target_halves() -> None:+ torch.manual_seed(0)+ up = torch.randn(OUT_FEATURES, RANK)+ down = torch.randn(RANK, IN_FEATURES)+ bias = torch.randn(OUT_FEATURES)+ alpha = 6.0+ patch_weight = 0.7+ target_weight = torch.randn(OUT_FEATURES, IN_FEATURES)+ target_bias = torch.randn(OUT_FEATURES)++ patch = SwappedHalvesLayerPatch(LoRALayer(up=up, mid=None, down=down, alpha=alpha, bias=bias))+ params = patch.get_parameters({"weight": target_weight, "bias": target_bias}, weight=patch_weight)++ # The deltas in the LoRA's own (source) layout, then moved to the target layout.+ source_weight_delta = up @ down * (alpha / RANK) * patch_weight+ source_bias_delta = bias * (alpha / RANK) * patch_weight+ assert torch.allclose(params["weight"], _swap(source_weight_delta), atol=1e-6)+ assert torch.allclose(params["bias"], _swap(source_bias_delta), atol=1e-6)++[email protected]_grad()+def test_dora_normalizes_against_the_original_weight_in_its_own_layout() -> None:+ torch.manual_seed(0)+ up = torch.randn(OUT_FEATURES, RANK) * 0.5+ down = torch.randn(RANK, IN_FEATURES) * 0.5+ magnitude = torch.rand(OUT_FEATURES) + 0.5+ source_weight = torch.randn(OUT_FEATURES, IN_FEATURES)++ patch = SwappedHalvesLayerPatch(+ DoRALayer.from_state_dict_values({"lora_up.weight": up, "lora_down.weight": down, "dora_magnitude": magnitude})+ )+ params = patch.get_parameters({"weight": _swap(source_weight)}, weight=1.0)++ # PEFT DoRA in the source layout: each output row of W + up @ down rescaled to its magnitude.+ direction = source_weight + up @ down+ source_patched = direction * (magnitude / direction.norm(dim=1))[:, None]+ assert torch.allclose(params["weight"], _swap(source_patched - source_weight), atol=1e-5)++[email protected]_grad()+def test_sparse_lycoris_bias_is_swapped() -> None:+ torch.manual_seed(0)+ up = torch.randn(OUT_FEATURES, RANK)+ down = torch.randn(RANK, IN_FEATURES)+ patch = SwappedHalvesLayerPatch(+ LoRALayer.from_state_dict_values(+ {+ "lora_up.weight": up,+ "lora_down.weight": down,+ "bias_indices": torch.tensor([[1, 8]]),+ "bias_values": torch.tensor([2.0, 3.0]),+ "bias_size": torch.tensor([OUT_FEATURES]),+ }+ )+ )+ params = patch.get_parameters(+ {"weight": torch.zeros(OUT_FEATURES, IN_FEATURES), "bias": torch.zeros(OUT_FEATURES)}, weight=1.0+ )++ source_bias_delta = torch.zeros(OUT_FEATURES)+ source_bias_delta[1] = 2.0+ source_bias_delta[8] = 3.0+ assert torch.equal(params["bias"].to_dense(), _swap(source_bias_delta))++[email protected]_grad()+def test_meta_original_parameters_give_the_same_lora_delta() -> None:+ """The sidecar hands shape-only meta tensors to patches when the base weights are quantized."""+ torch.manual_seed(0)+ patch = SwappedHalvesLayerPatch(+ LoRALayer(+ up=torch.randn(OUT_FEATURES, RANK), mid=None, down=torch.randn(RANK, IN_FEATURES), alpha=None, bias=None+ )+ )++ real = patch.get_parameters({"weight": torch.randn(OUT_FEATURES, IN_FEATURES)}, weight=1.0)+ meta = patch.get_parameters({"weight": torch.empty(OUT_FEATURES, IN_FEATURES, device="meta")}, weight=1.0)++ assert torch.equal(meta["weight"], real["weight"])diff --git a/tests/backend/patches/lora_conversions/test_flux_bfl_peft_lora_conversion_utils.py b/tests/backend/patches/lora_conversions/test_flux_bfl_peft_lora_conversion_utils.pynew file mode 100644index 0000000000..f52967f4a0--- /dev/null+++ b/tests/backend/patches/lora_conversions/test_flux_bfl_peft_lora_conversion_utils.py@@ -0,0 +1,96 @@+from typing import Callable++import pytest+import torch+from diffusers.models.normalization import AdaLayerNormContinuous++from invokeai.backend.flux.modules.layers import LastLayer+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,+ lora_model_from_flux2_bfl_peft_state_dict,+ lora_model_from_flux_bfl_peft_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++HIDDEN_SIZE = 8+OUT_CHANNELS = 4+RANK = 2+++class _Flux2FinalLayer(torch.nn.Module):+ """The tail of Flux2Transformer2DModel: AdaLayerNormContinuous, then the output projection."""++ def __init__(self):+ super().__init__()+ self.norm_out = AdaLayerNormContinuous(HIDDEN_SIZE, HIDDEN_SIZE, elementwise_affine=False, eps=1e-6)+ self.proj_out = torch.nn.Linear(HIDDEN_SIZE, OUT_CHANNELS)++ def forward(self, x: torch.Tensor, vec: torch.Tensor) -> torch.Tensor:+ return self.proj_out(self.norm_out(x, vec))+++def _flux2_state_dict_converter(state_dict: dict[str, torch.Tensor]) -> ModelPatchRaw:+ return lora_model_from_flux2_bfl_peft_state_dict(state_dict)+++def _flux1_converter_then_apply_time_conversion(state_dict: dict[str, torch.Tensor]) -> ModelPatchRaw:+ # What Flux2DenoiseInvocation does with a BFL LoRA that was loaded by the FLUX.1 converter.+ return convert_bfl_lora_patch_to_diffusers(lora_model_from_flux_bfl_peft_state_dict(state_dict))++[email protected]_grad()+ "convert",+ [_flux2_state_dict_converter, _flux1_converter_then_apply_time_conversion],+ ids=["state-dict", "built-patch"],+)+def test_final_layer_modulation_lora_patches_flux2_norm_out(+ convert: Callable[[dict[str, torch.Tensor]], ModelPatchRaw],+) -> None:+ """A LoRA on BFL's final_layer.adaLN_modulation.1, which orders its output (shift, scale), must patch the FLUX.2+ model's norm_out.linear, which orders it (scale, shift), so that the model computes what the LoRA does on the BFL+ model (#10022).+ """+ torch.manual_seed(0)+ bfl_final_layer = LastLayer(HIDDEN_SIZE, patch_size=1, out_channels=OUT_CHANNELS)+ flux2_model = _Flux2FinalLayer()+ # The base weights as the FLUX.2 loader converts them: BFL's halves swapped.+ flux2_model.proj_out.load_state_dict(bfl_final_layer.linear.state_dict())+ bfl_modulation = bfl_final_layer.adaLN_modulation[1]+ for name in ("weight", "bias"):+ bfl_param = getattr(bfl_modulation, name)+ getattr(flux2_model.norm_out.linear, name).copy_(torch.cat(bfl_param.chunk(2, dim=0)[::-1], dim=0))++ x = torch.randn(2, 3, HIDDEN_SIZE)+ vec = torch.randn(2, HIDDEN_SIZE)+ unpatched = flux2_model(x, vec)+ assert torch.allclose(unpatched, bfl_final_layer(x, vec), atol=1e-5)++ down = torch.randn(RANK, HIDDEN_SIZE)+ up = torch.randn(2 * HIDDEN_SIZE, RANK)+ state_dict = {+ "diffusion_model.final_layer.adaLN_modulation.1.lora_A.weight": down,+ "diffusion_model.final_layer.adaLN_modulation.1.lora_B.weight": up,+ # A block layer, which marks the LoRA as BFL-keyed for the apply-time conversion.+ "diffusion_model.double_blocks.0.img_attn.proj.lora_A.weight": torch.randn(RANK, HIDDEN_SIZE),+ "diffusion_model.double_blocks.0.img_attn.proj.lora_B.weight": torch.randn(HIDDEN_SIZE, RANK),+ }+ patch = convert(state_dict)+ final_layer_key = f"{FLUX_LORA_TRANSFORMER_PREFIX}norm_out.linear"+ assert set(patch.layers) == {final_layer_key, f"{FLUX_LORA_TRANSFORMER_PREFIX}transformer_blocks.0.attn.to_out.0"}++ with LayerPatcher.apply_smart_model_patches(+ model=flux2_model,+ patches=[(ModelPatchRaw(layers={final_layer_key: patch.layers[final_layer_key]}), 1.0)],+ prefix=FLUX_LORA_TRANSFORMER_PREFIX,+ dtype=torch.float32,+ force_direct_patching=True,+ ):+ patched = flux2_model(x, vec)++ bfl_modulation.weight += up @ down+ expected = bfl_final_layer(x, vec)+ assert not torch.allclose(expected, unpatched, atol=1e-2)+ assert torch.allclose(patched, expected, atol=1e-5)diff --git a/tests/backend/patches/lora_conversions/test_flux_diffusers_lora_conversion_utils.py b/tests/backend/patches/lora_conversions/test_flux_diffusers_lora_conversion_utils.pyindex 2c1a9750df..fa4e7bdb61 100644--- a/tests/backend/patches/lora_conversions/test_flux_diffusers_lora_conversion_utils.py+++ b/tests/backend/patches/lora_conversions/test_flux_diffusers_lora_conversion_utils.py@@ -1,6 +1,9 @@import pytestimport torch+from diffusers.models.normalization import AdaLayerNormContinuous+from invokeai.backend.flux.modules.layers import LastLayer+from invokeai.backend.patches.layer_patcher import LayerPatcherfrom invokeai.backend.patches.lora_conversions.flux_diffusers_lora_conversion_utils import (is_state_dict_likely_in_flux_diffusers_format,lora_model_from_flux_diffusers_state_dict,@@ -84,6 +87,57 @@ def test_lora_model_from_flux_diffusers_state_dict(sd_keys: dict[str, list[int]]assert all(k.startswith(FLUX_LORA_TRANSFORMER_PREFIX) for k in model.layers.keys())+class _BflFinalLayer(torch.nn.Module):+ """The part of the BFL FLUX model that the final-layer LoRA keys resolve against."""++ def __init__(self, hidden_size: int, out_channels: int):+ super().__init__()+ self.final_layer = LastLayer(hidden_size, patch_size=1, out_channels=out_channels)++[email protected]_grad()+def test_lora_model_from_flux_diffusers_state_dict_final_layer_modulation():+ """A LoRA on diffusers' norm_out.linear, which orders its output (scale, shift), must patch BFL's+ final_layer.adaLN_modulation.1, which orders it (shift, scale), so that the model computes what the LoRA does on+ the diffusers model (#10022).+ """+ torch.manual_seed(0)+ hidden_size, out_channels, rank = 8, 4, 2+ diffusers_norm_out = AdaLayerNormContinuous(hidden_size, hidden_size, elementwise_affine=False, eps=1e-6)+ bfl_model = _BflFinalLayer(hidden_size, out_channels)+ # The base weights as the FLUX loader converts them: diffusers' halves swapped.+ bfl_modulation = bfl_model.final_layer.adaLN_modulation[1]+ for name in ("weight", "bias"):+ diffusers_param = getattr(diffusers_norm_out.linear, name)+ getattr(bfl_modulation, name).copy_(torch.cat(diffusers_param.chunk(2, dim=0)[::-1], dim=0))++ def diffusers_forward(x: torch.Tensor, vec: torch.Tensor) -> torch.Tensor:+ return bfl_model.final_layer.linear(diffusers_norm_out(x, vec))++ x = torch.randn(2, 3, hidden_size)+ vec = torch.randn(2, hidden_size)+ unpatched = bfl_model.final_layer(x, vec)+ assert torch.allclose(unpatched, diffusers_forward(x, vec), atol=1e-5)++ down = torch.randn(rank, hidden_size)+ up = torch.randn(2 * hidden_size, rank)+ state_dict = {"transformer.norm_out.linear.lora_A.weight": down, "transformer.norm_out.linear.lora_B.weight": up}+ patch = lora_model_from_flux_diffusers_state_dict(state_dict, alpha=None)+ with LayerPatcher.apply_smart_model_patches(+ model=bfl_model,+ patches=[(patch, 1.0)],+ prefix=FLUX_LORA_TRANSFORMER_PREFIX,+ dtype=torch.float32,+ force_direct_patching=True,+ ):+ patched = bfl_model.final_layer(x, vec)++ diffusers_norm_out.linear.weight += up @ down+ expected = diffusers_forward(x, vec)+ assert not torch.allclose(expected, unpatched, atol=1e-2)+ assert torch.allclose(patched, expected, atol=1e-5)++def test_lora_model_from_flux_diffusers_state_dict_extra_keys_error():"""Test that lora_model_from_flux_diffusers_state_dict() raises an error if the input state_dict contains unexpectedkeys that we don't handle.diff --git a/tests/backend/patches/test_layer_patcher.py b/tests/backend/patches/test_layer_patcher.pyindex db5c820b22..7791e90a41 100644--- a/tests/backend/patches/test_layer_patcher.py+++ b/tests/backend/patches/test_layer_patcher.py@@ -1,5 +1,6 @@import gcimport weakref+from typing import Callableimport pytestimport torch@@ -11,7 +12,10 @@ from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.torchapply_custom_layers_to_model,)from invokeai.backend.patches.layer_patcher import LayerPatcher+from invokeai.backend.patches.layers.base_layer_patch import BaseLayerPatchfrom 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 SwappedHalvesLayerPatchfrom invokeai.backend.patches.model_patch_raw import ModelPatchRaw@@ -671,31 +675,75 @@ def test_lazy_patch_iterator_that_constructs_a_model_does_not_deadlock():assert result.get("done") is True-def _one_layer_patch(in_features: int, out_features: int, rank: int = 4) -> ModelPatchRaw:- return ModelPatchRaw(- layers={- "linear_layer_1": LoRALayer(- up=torch.ones(out_features, rank, dtype=torch.bfloat16),- mid=None,- down=torch.ones(rank, in_features, dtype=torch.bfloat16),- alpha=None,- bias=None,- )- }+def _lora_layer(in_features: int, out_features: int, rank: int = 4, dtype: torch.dtype = torch.float16) -> LoRALayer:+ # fp16 factors by default, under a bf16 compute dtype: the sidecar path then casts them even on CPU, so a+ # placement that is not put back is visible without a GPU.+ return LoRALayer(+ up=torch.ones(out_features, rank, dtype=dtype),+ mid=None,+ down=torch.ones(rank, in_features, dtype=dtype),+ alpha=None,+ bias=None,)-def _placement(patch: ModelPatchRaw) -> tuple[torch.device, torch.dtype]:- layer = patch.layers["linear_layer_1"]- return layer.up.device, layer.up.dtype+def _merged_layer(in_features: int, out_features: int) -> MergedLayerPatch:+ half = out_features // 2+ return MergedLayerPatch(+ lora_layers=[_lora_layer(in_features, half), _lora_layer(in_features, out_features - half)],+ ranges=[Range(0, half), Range(half, out_features)],+ )+++def _mixed_dtype_merged_layer(in_features: int, out_features: int) -> MergedLayerPatch:+ # Q/K/V factors converted separately need not share a dtype. Under the bf16 compute dtype only the+ # fp16 half is cast by the sidecar path, so restoring both to one dtype changes the other.+ half = out_features // 2+ return MergedLayerPatch(+ lora_layers=[+ _lora_layer(in_features, half),+ _lora_layer(in_features, out_features - half, dtype=torch.bfloat16),+ ],+ ranges=[Range(0, half), Range(half, out_features)],+ )+++def _swapped_halves_layer(in_features: int, out_features: int) -> SwappedHalvesLayerPatch:+ return SwappedHalvesLayerPatch(_lora_layer(in_features, out_features))+++def _innermost_loras(layer: BaseLayerPatch) -> list[LoRALayer]:+ if isinstance(layer, MergedLayerPatch):+ return [lora for sub_layer in layer.lora_layers for lora in _innermost_loras(sub_layer)]+ if isinstance(layer, SwappedHalvesLayerPatch):+ return _innermost_loras(layer.layer)+ assert isinstance(layer, LoRALayer)+ return [layer]++def _placements(patch: ModelPatchRaw) -> list[tuple[torch.device, torch.dtype]]:+ """The (device, dtype) of each innermost LoRA factor, in order, so each sub-layer is checked on its own."""+ return [+ (tensor.device, tensor.dtype)+ for layer in patch.layers.values()+ for lora in _innermost_loras(layer)+ for tensor in (lora.up, lora.down)+ ]++ "make_layer",+ [_lora_layer, _merged_layer, _mixed_dtype_merged_layer, _swapped_halves_layer],+ ids=["lora", "merged", "mixed_dtype_merged", "swapped_halves"],+)@pytest.mark.parametrize("force_sidecar", [False, True], ids=["direct", "sidecar"])@pytest.mark.parametrize("device",["cpu", pytest.param("cuda", marks=pytest.mark.skipif(not torch.cuda.is_available(), reason="requires a GPU"))],)-def test_patching_leaves_the_cached_patch_where_it_found_it(force_sidecar: bool, device: str) -> None:+def test_patching_leaves_the_cached_patch_where_it_found_it(+ make_layer: Callable[[int, int], BaseLayerPatch], force_sidecar: bool, device: str+) -> None:"""A patch is the model cache's own object, not a copy, and `BaseLayerPatch.to()` rebinds itstensors in place. So anything patching does to a patch's device or dtype outlives the patchedscope, inside a record the cache is still accounting for.@@ -707,11 +755,14 @@ def test_patching_leaves_the_cached_patch_where_it_found_it(force_sidecar: bool,a RAM-pinned record -- `cur_vram_bytes()` reports zero for it and `full_unload_from_vram()`early-returns, so the cache could not reclaim what it could not see. At a few tens of MB that wasinvisible; at LTX-2's 8.9 GB step-distillation LoRA it is a first-order VRAM consumer.++ Wrapper patches hold their tensors only in sub-patches, so their placement has to be read from+ there too, or the restore is a no-op that strands the inner layers."""model = DummyModuleWithOneLayer(in_features=8, out_features=16, device=device, dtype=torch.bfloat16)apply_custom_layers_to_model(model)- patch = _one_layer_patch(in_features=8, out_features=16)- before = _placement(patch)+ patch = ModelPatchRaw(layers={"linear_layer_1": make_layer(8, 16)})+ before = _placements(patch)before_bytes = patch.calc_size()with LayerPatcher.apply_smart_model_patches(@@ -719,16 +770,45 @@ def test_patching_leaves_the_cached_patch_where_it_found_it(force_sidecar: bool,patches=[(patch, 1.0)],prefix="",dtype=torch.bfloat16,+ force_direct_patching=not force_sidecar,force_sidecar_patching=force_sidecar,):- # The sidecar path has to keep it on the compute device while the forward needs it.- if force_sidecar and device != "cpu":- assert _placement(patch)[0].type == device+ # The sidecar path has to keep every sub-layer on the compute device and dtype while the forward needs+ # it. On CPU the cast is the only move, so this also keeps the restore check below from passing vacuously.+ if force_sidecar:+ assert {placement_device.type for placement_device, _ in _placements(patch)} == {device}+ assert {placement_dtype for _, placement_dtype in _placements(patch)} == {torch.bfloat16}- assert _placement(patch) == before+ assert _placements(patch) == beforeassert patch.calc_size() == before_bytes[email protected]("make_layer", [_lora_layer, _swapped_halves_layer], ids=["lora", "swapped_halves"])+ "device",+ ["cpu", pytest.param("cuda", marks=pytest.mark.skipif(not torch.cuda.is_available(), reason="requires a GPU"))],+)+def test_direct_patching_that_fails_still_returns_the_cached_patch(+ make_layer: Callable[[int, int], BaseLayerPatch], device: str+) -> None:+ """Direct-patched patches are not in the sidecar restore list, so the direct path has to put the+ patch back itself on every way out. A LoRA built for another shape raises from `get_parameters`+ after the patch has already been moved and promoted to float32."""+ model = DummyModuleWithOneLayer(in_features=8, out_features=16, device=device, dtype=torch.bfloat16)+ apply_custom_layers_to_model(model)+ # 12 output rows cannot be reshaped onto the module's 16.+ patch = ModelPatchRaw(layers={"linear_layer_1": make_layer(8, 12)})+ before = _placements(patch)++ with pytest.raises(RuntimeError, match="is invalid for input of size"):+ with LayerPatcher.apply_smart_model_patches(+ model=model, patches=[(patch, 1.0)], prefix="", dtype=torch.bfloat16, force_direct_patching=True+ ):+ pass++ assert _placements(patch) == before++@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires a GPU")def test_every_layer_of_a_multi_layer_patch_is_returned() -> None:"""A real LoRA is many layers -- the LTX-2 accelerator is 1660 of them -- and each is moved