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(patches): return a cached LoRA patch to where patching found it

Lincoln Steind6dc352bc311
diff --git a/invokeai/backend/patches/layer_patcher.py b/invokeai/backend/patches/layer_patcher.py
index 561e654d7f..6c3b83b715 100644
--- a/invokeai/backend/patches/layer_patcher.py
+++ b/invokeai/backend/patches/layer_patcher.py
@@ -10,7 +10,6 @@ from invokeai.backend.patches.layers.flux_control_lora_layer import FluxControlL
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
-from invokeai.backend.util.devices import TorchDevice
from invokeai.backend.util.fp8 import FP8_STORAGE_DTYPES
from invokeai.backend.util.original_weights_storage import OriginalWeightsStorage
@@ -41,6 +40,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
+ # 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]] = {}
cache_pins = ExitStack()
try:
# Materialize the patch iterable BEFORE acquiring the read lock. Callers pass a lazy
@@ -76,6 +79,7 @@ class LayerPatcher:
patch_weight=patch_weight,
original_weights=original_weights,
original_modules=original_modules,
+ patch_placements=patch_placements,
dtype=dtype,
force_direct_patching=force_direct_patching,
force_sidecar_patching=force_sidecar_patching,
@@ -94,6 +98,12 @@ class LayerPatcher:
# Note: This logic assumes no nested modules in original_modules.
for orig_module in original_modules.values():
orig_module.clear_patches()
+
+ # 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)
finally:
cache_pins.close()
@@ -106,6 +116,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]],
dtype: torch.dtype,
force_direct_patching: bool,
force_sidecar_patching: bool,
@@ -185,6 +196,7 @@ class LayerPatcher:
patch=layer,
patch_weight=patch_weight,
original_modules=original_modules,
+ patch_placements=patch_placements,
dtype=dtype,
)
else:
@@ -224,6 +236,11 @@ class LayerPatcher:
# We intentionally move to the target device first, then cast. Experimentally, this was found to
# 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.
+ original_device, original_dtype = LayerPatcher._patch_placement(patch)
patch.to(device=device)
patch.to(dtype=torch.float32)
@@ -280,7 +297,22 @@ class LayerPatcher:
# `module_param.data + param_weight_converted` temporary).
module_param.data = module_param.data + param_weight_converted
- patch.to(device=TorchDevice.CPU_DEVICE)
+ # 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)
+
+ @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.
+
+ 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.
+ """
+ for value in vars(patch).values():
+ if isinstance(value, torch.Tensor):
+ return value.device, value.dtype
+ return None, None
@staticmethod
@torch.no_grad()
@@ -290,6 +322,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]],
dtype: torch.dtype,
):
"""Apply a single LoRA wrapper patch to a module."""
@@ -300,6 +333,12 @@ class LayerPatcher:
if first_tensor is None:
first_tensor = next(module_to_patch.buffers())
device = first_tensor.device
+ # Same in-place mutation of the cache's own object as the direct path, but this one had no
+ # counterpart: `clear_patches()` drops the module's reference and leaves the tensors on the
+ # 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)))
patch.to(device=device, dtype=dtype)
if module_to_patch_key not in original_modules:
diff --git a/invokeai/backend/stable_diffusion/extensions/lora.py b/invokeai/backend/stable_diffusion/extensions/lora.py
index 8102b1dd8a..323a665f54 100644
--- a/invokeai/backend/stable_diffusion/extensions/lora.py
+++ b/invokeai/backend/stable_diffusion/extensions/lora.py
@@ -3,9 +3,11 @@ from __future__ import annotations
from contextlib import contextmanager
from typing import TYPE_CHECKING
+import torch
from diffusers import UNet2DConditionModel
from invokeai.backend.patches.layer_patcher import LayerPatcher
+from invokeai.backend.patches.layers.base_layer_patch import BaseLayerPatch
from invokeai.backend.patches.model_patch_raw import ModelPatchRaw
from invokeai.backend.stable_diffusion.extensions.base import ExtensionBase
from invokeai.backend.util.fp8 import get_model_compute_dtype
@@ -40,6 +42,14 @@ class LoRAExt(ExtensionBase):
# patching is impossible on float8 weights — see apply_smart_model_patch), which stores a
# live reference to this cached patch's layers inside the UNet's modules for the whole
# denoise.
+ # Both of these are restored below rather than discarded. `apply_smart_model_patch` mutates
+ # the cached patch in place -- it is the model cache's own object, not a copy -- so a patch
+ # left where the application put it is a cached record holding device memory the cache
+ # 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]] = {}
+
with lora_info.model_in_ram() as lora_model:
LayerPatcher.apply_smart_model_patch(
model=unet,
@@ -47,11 +57,18 @@ class LoRAExt(ExtensionBase):
patch=lora_model,
patch_weight=self._weight,
original_weights=original_weights,
- original_modules={},
+ original_modules=original_modules,
+ patch_placements=patch_placements,
dtype=get_model_compute_dtype(unet),
force_direct_patching=True,
force_sidecar_patching=False,
)
del lora_model
- yield
+ try:
+ yield
+ 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)
diff --git a/tests/backend/patches/test_layer_patcher.py b/tests/backend/patches/test_layer_patcher.py
index de1906bc35..db5c820b22 100644
--- a/tests/backend/patches/test_layer_patcher.py
+++ b/tests/backend/patches/test_layer_patcher.py
@@ -669,3 +669,91 @@ def test_lazy_patch_iterator_that_constructs_a_model_does_not_deadlock():
patcher.join(timeout=10)
assert not patcher.is_alive(), "patching a lazily-constructed LoRA must not deadlock on MODEL_LOAD_LOCK"
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 _placement(patch: ModelPatchRaw) -> tuple[torch.device, torch.dtype]:
+ layer = patch.layers["linear_layer_1"]
+ return layer.up.device, layer.up.dtype
+
+
[email protected]("force_sidecar", [False, True], ids=["direct", "sidecar"])
+ "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:
+ """A patch is the model cache's own object, not a copy, and `BaseLayerPatch.to()` rebinds its
+ tensors in place. So anything patching does to a patch's device or dtype outlives the patched
+ scope, inside a record the cache is still accounting for.
+
+ Both paths used to leave a mark. Direct patching promoted the patch to float32 for the maths and
+ returned only its device, permanently doubling the record while the cache went on billing the
+ size it measured at `put()`. Sidecar patching moved it onto the compute device and returned
+ nothing: `clear_patches()` drops the module's reference, so the tensors stayed on the GPU inside
+ 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 was
+ invisible; at LTX-2's 8.9 GB step-distillation LoRA it is a first-order VRAM consumer.
+ """
+ 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)
+ before_bytes = patch.calc_size()
+
+ with LayerPatcher.apply_smart_model_patches(
+ model=model,
+ patches=[(patch, 1.0)],
+ prefix="",
+ dtype=torch.bfloat16,
+ 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
+
+ assert _placement(patch) == before
+ assert patch.calc_size() == before_bytes
+
+
[email protected](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
+ onto the device separately. Restoring only the ones that happen to be reached first would
+ strand the remainder, which is the same leak in a form that a single-layer test cannot see."""
+ model = DummyModuleWithTwoLayers(in_features=8, out_features=8, device="cuda", dtype=torch.bfloat16)
+ apply_custom_layers_to_model(model)
+ patch = ModelPatchRaw(
+ layers={
+ name: LoRALayer(
+ up=torch.ones(8, 4, dtype=torch.bfloat16),
+ mid=None,
+ down=torch.ones(4, 8, dtype=torch.bfloat16),
+ alpha=None,
+ bias=None,
+ )
+ for name in ("linear_layer_1", "linear_layer_2")
+ }
+ )
+
+ with LayerPatcher.apply_smart_model_patches(
+ model=model, patches=[(patch, 1.0)], prefix="", dtype=torch.bfloat16, force_sidecar_patching=True
+ ):
+ pass
+
+ for layer in patch.layers.values():
+ assert layer.up.device.type == "cpu"
+ assert layer.up.dtype == torch.bfloat16