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): keep wrapper sub-patches in place during sidecar forwards (#10243)

Alexander Eichhorn0ffa8631eeec
diff --git a/invokeai/backend/patches/layer_patcher.py b/invokeai/backend/patches/layer_patcher.py
index 7b52d60937..65c864b2d9 100644
--- a/invokeai/backend/patches/layer_patcher.py
+++ b/invokeai/backend/patches/layer_patcher.py
@@ -6,7 +6,7 @@ import torch
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
+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.model_patch_raw import ModelPatchRaw
from invokeai.backend.patches.pad_with_zeros import pad_with_zeros
@@ -318,14 +318,9 @@ 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.
"""
- 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)]
+ 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)]
diff --git a/invokeai/backend/patches/layers/base_layer_patch.py b/invokeai/backend/patches/layers/base_layer_patch.py
index f6f0289a90..e7c66fafc8 100644
--- a/invokeai/backend/patches/layers/base_layer_patch.py
+++ b/invokeai/backend/patches/layers/base_layer_patch.py
@@ -1,9 +1,20 @@
+import copy
from abc import ABC, abstractmethod
import torch
class BaseLayerPatch(ABC):
+ def __copy__(self):
+ """Shallow copy that also copies sub-patches, so the copy's `to()` cannot move the original's.
+
+ The sidecar forwards move `copy.copy(patch)` to the input device. Wrapper patches delegate `to()` to
+ their sub-patches, which a plain shallow copy would share with the cached patch.
+ """
+ clone = object.__new__(type(self))
+ clone.__dict__ = {name: _copy_sub_patches(value) for name, value in self.__dict__.items()}
+ return clone
+
@abstractmethod
def get_parameters(self, orig_parameters: dict[str, torch.Tensor], weight: float) -> dict[str, torch.Tensor]:
"""Get the parameter residual updates that should be applied to the original parameters. Parameters omitted
@@ -20,3 +31,27 @@ class BaseLayerPatch(ABC):
def calc_size(self) -> int:
"""Calculate the total size of all internal tensors in bytes."""
...
+
+
+def _held_patches(value: object) -> list[BaseLayerPatch]:
+ """The patches an attribute holds: the value itself if it is a patch, or the patch items of a list or tuple."""
+ if isinstance(value, BaseLayerPatch):
+ return [value]
+ if isinstance(value, (list, tuple)):
+ return [item for item in value if isinstance(item, BaseLayerPatch)]
+ return []
+
+
+def _copy_sub_patches(value: object) -> object:
+ """`value` with every held patch replaced by a copy; containers without patches and other values are shared."""
+ if isinstance(value, BaseLayerPatch):
+ return copy.copy(value)
+ if not _held_patches(value):
+ return value
+ items = [copy.copy(item) if isinstance(item, BaseLayerPatch) else item for item in value] # type: ignore[attr-defined]
+ return items if isinstance(value, list) else tuple(items)
+
+
+def sub_patches(patch: BaseLayerPatch) -> list[BaseLayerPatch]:
+ """The direct sub-patches of a wrapper patch: attributes that are patches, alone or in a list or tuple."""
+ return [item for value in vars(patch).values() for item in _held_patches(value)]
diff --git a/tests/backend/patches/layers/test_merged_layer_patch.py b/tests/backend/patches/layers/test_merged_layer_patch.py
new file mode 100644
index 0000000000..8e61b40a73
--- /dev/null
+++ b/tests/backend/patches/layers/test_merged_layer_patch.py
@@ -0,0 +1,37 @@
+import copy
+
+import torch
+
+from invokeai.backend.patches.layers.lora_layer import LoRALayer
+from invokeai.backend.patches.layers.merged_layer_patch import MergedLayerPatch, Range
+
+
+def _lora(out_features: int, dtype: torch.dtype) -> LoRALayer:
+ return LoRALayer(
+ up=torch.ones(out_features, 2, dtype=dtype),
+ mid=None,
+ down=torch.ones(2, 4, dtype=dtype),
+ alpha=None,
+ bias=None,
+ )
+
+
+def _placement(lora: LoRALayer) -> tuple[torch.device, torch.dtype, torch.device, torch.dtype]:
+ return lora.up.device, lora.up.dtype, lora.down.device, lora.down.dtype
+
+
+def test_moving_a_copy_leaves_the_original_sub_layers_in_place() -> None:
+ """The sidecar forwards move `copy.copy(patch)` to the input device; the cached patch must stay put."""
+ # Different dtypes only make the sub-layers' placements differ from each other.
+ layers = [_lora(3, torch.float16), _lora(5, torch.float32)]
+ merged = MergedLayerPatch(layers, [Range(0, 3), Range(3, 8)])
+ before = [_placement(layer) for layer in layers]
+
+ moved = copy.copy(merged)
+ # The copy is shallow: new sub-layer objects, same tensors.
+ assert all(new is not old for new, old in zip(moved.lora_layers, layers, strict=True))
+ assert moved.lora_layers[0].up is layers[0].up # type: ignore[attr-defined]
+ moved.to(torch.device("meta"))
+
+ assert [_placement(layer) for layer in merged.lora_layers] == before # type: ignore[arg-type]
+ assert all(layer.up.device.type == "meta" and layer.down.device.type == "meta" for layer in moved.lora_layers) # type: ignore[attr-defined]
diff --git a/tests/backend/patches/layers/test_swapped_halves_layer_patch.py b/tests/backend/patches/layers/test_swapped_halves_layer_patch.py
index e2ecbb7ac0..973cfa0a2d 100644
--- a/tests/backend/patches/layers/test_swapped_halves_layer_patch.py
+++ b/tests/backend/patches/layers/test_swapped_halves_layer_patch.py
@@ -1,7 +1,10 @@
+import copy
+
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.merged_layer_patch import MergedLayerPatch, Range
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.
@@ -94,3 +97,31 @@ def test_meta_original_parameters_give_the_same_lora_delta() -> None:
meta = patch.get_parameters({"weight": torch.empty(OUT_FEATURES, IN_FEATURES, device="meta")}, weight=1.0)
assert torch.equal(meta["weight"], real["weight"])
+
+
+def _lora(out_features: int, dtype: torch.dtype = torch.float32) -> LoRALayer:
+ 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 _tensors(*layers: LoRALayer) -> list[tuple[torch.device, torch.dtype]]:
+ return [(t.device, t.dtype) for layer in layers for t in (layer.up, layer.down)]
+
+
+def test_moving_a_copy_leaves_nested_sub_layers_in_place() -> None:
+ inner = [_lora(OUT_FEATURES // 2, torch.float16), _lora(OUT_FEATURES // 2, torch.float32)]
+ patch = SwappedHalvesLayerPatch(
+ MergedLayerPatch(inner, [Range(0, OUT_FEATURES // 2), Range(OUT_FEATURES // 2, OUT_FEATURES)])
+ )
+ before = _tensors(*inner)
+
+ moved = copy.copy(patch)
+ moved.to(torch.device("meta"))
+
+ assert _tensors(*inner) == before
+ assert all(layer.up.device.type == "meta" for layer in moved.layer.lora_layers) # type: ignore[attr-defined]
diff --git a/tests/backend/patches/test_layer_patcher.py b/tests/backend/patches/test_layer_patcher.py
index 7791e90a41..f01d6e3a92 100644
--- a/tests/backend/patches/test_layer_patcher.py
+++ b/tests/backend/patches/test_layer_patcher.py
@@ -783,6 +783,35 @@ def test_patching_leaves_the_cached_patch_where_it_found_it(
assert patch.calc_size() == before_bytes
+ "input_device",
+ ["meta", pytest.param("cuda", marks=pytest.mark.skipif(not torch.cuda.is_available(), reason="requires a GPU"))],
+)
+ "make_layer", [_lora_layer, _merged_layer, _swapped_halves_layer], ids=["lora", "merged", "swapped_halves"]
+)
+def test_sidecar_forward_leaves_the_cached_patch_in_place_during_the_scope(
+ make_layer: Callable[[int, int], BaseLayerPatch], input_device: str
+) -> None:
+ """The sidecar forward moves a copy of each patch to the input's device. For wrapper patches the copy used
+ to share its sub-patches with the cached patch, so the first forward moved those off the device the model
+ cache accounts them on, until the scope ended."""
+ model = DummyModuleWithOneLayer(in_features=8, out_features=16, device="cpu", dtype=torch.bfloat16)
+ apply_custom_layers_to_model(model)
+ model.linear_layer_1.set_device_autocasting_enabled(True)
+ patch = ModelPatchRaw(layers={"linear_layer_1": make_layer(8, 16)})
+
+ with LayerPatcher.apply_smart_model_patches(
+ model=model, patches=[(patch, 1.0)], prefix="", dtype=torch.bfloat16, force_sidecar_patching=True
+ ):
+ # Whatever placement patching itself chose for the scope; only the forward must not change it.
+ during_scope = _placements(patch)
+ model(torch.ones(1, 8, device=input_device, dtype=torch.bfloat16))
+ assert _placements(patch) == during_scope
+ assert all(placement_device.type == "cpu" for placement_device, _ in _placements(patch))
+
+
@pytest.mark.parametrize("make_layer", [_lora_layer, _swapped_halves_layer], ids=["lora", "swapped_halves"])
@pytest.mark.parametrize(
"device",