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): stop direct patching from fragmenting VRAM (#10272)

Alexander Eichhorn1bfe43a6cea2
diff --git a/invokeai/backend/minimax_h3/adaln_overlay.py b/invokeai/backend/minimax_h3/adaln_overlay.py
index 6f331b109e..74c7d776c7 100644
--- a/invokeai/backend/minimax_h3/adaln_overlay.py
+++ b/invokeai/backend/minimax_h3/adaln_overlay.py
@@ -227,7 +227,8 @@ def apply_minimax_h3_adaln_overlay(
"be AdaLN-pruned or both be full checkpoints."
)
original_weights.save(path, param, copy=param.device.type != "cpu")
- param.data = tensor.to(device=param.device, dtype=param.dtype)
+ # A device weight never aliases the (cached) overlay tensor, which `.to` returns itself when nothing changes.
+ param.data = tensor.to(device=param.device, dtype=param.dtype, copy=param.device.type != "cpu")
yield
finally:
for path, weight in original_weights.get_changed_weights():
diff --git a/invokeai/backend/patches/layer_patcher.py b/invokeai/backend/patches/layer_patcher.py
index 65c864b2d9..8e183b0728 100644
--- a/invokeai/backend/patches/layer_patcher.py
+++ b/invokeai/backend/patches/layer_patcher.py
@@ -1,5 +1,7 @@
import re
+from collections import Counter
from contextlib import AbstractContextManager, ExitStack, contextmanager
+from itertools import chain
from typing import Dict, Iterable, Optional, Tuple
import torch
@@ -46,6 +48,8 @@ class LayerPatcher:
# modules, and only its first, pre-move placement is the one to restore.
patch_placements: dict[int, tuple[BaseLayerPatch, torch.device, torch.dtype]] = {}
cache_pins = ExitStack()
+ # Storage shared with another parameter or buffer, as of before the first patch of this scope.
+ shared_storage: set[int] = set()
try:
# Materialize the patch iterable BEFORE acquiring the read lock. Callers pass a lazy
# generator (e.g. flux_text_encoder._t5_lora_iterator) that constructs each LoRA via
@@ -63,6 +67,8 @@ class LayerPatcher:
cache_pins.enter_context(patch_spec[2])
materialized_patches.append(patch_spec)
patches = materialized_patches
+ if patches and not force_sidecar_patching:
+ shared_storage = LayerPatcher._shared_storage_ptrs(model)
# Patching can register new parameters (FLUX Control LoRA shape expansion routes
# through nn.Module.register_parameter via setattr). Model construction on another
# worker thread monkey-patches register_parameter process-wide (accelerate's
@@ -85,6 +91,7 @@ class LayerPatcher:
force_direct_patching=force_direct_patching,
force_sidecar_patching=force_sidecar_patching,
suppress_warning_layers=suppress_warning_layers,
+ shared_storage=shared_storage,
)
yield
@@ -93,7 +100,13 @@ class LayerPatcher:
# Restore directly patched layers.
for param_key, weight in original_weights.get_changed_weights():
cur_param = model.get_parameter(param_key)
- cur_param.data = weight.to(dtype=cur_param.dtype, device=cur_param.device, copy=True)
+ # In place for the same reason as the patch step; a shape-expanded parameter is replaced.
+ if cur_param.shape == weight.shape and LayerPatcher._can_update_in_place(
+ cur_param, shared_storage, weight
+ ):
+ cur_param.data.copy_(weight)
+ else:
+ cur_param.data = weight.to(dtype=cur_param.dtype, device=cur_param.device, copy=True)
# Clear patches from all patched modules.
# Note: This logic assumes no nested modules in original_modules.
@@ -122,6 +135,7 @@ class LayerPatcher:
force_direct_patching: bool,
force_sidecar_patching: bool,
suppress_warning_layers: Optional[re.Pattern] = None,
+ shared_storage: Optional[set[int]] = None,
):
"""Apply a single LoRA patch to a model using the 'smart' patching strategy that chooses whether to use direct
patching or a sidecar wrapper for each module.
@@ -129,6 +143,11 @@ class LayerPatcher:
if patch_weight == 0:
return
+ # `shared_storage` is a snapshot taken before the first patch of the scope; it is computed here when the
+ # caller has none. Sidecar patching never writes into a weight.
+ if shared_storage is None:
+ shared_storage = set() if force_sidecar_patching else LayerPatcher._shared_storage_ptrs(model)
+
# If the layer keys contain a dot, then they are not flattened, and can be directly used to access model
# submodules. If the layer keys do not contain a dot, then they are flattened, meaning that all '.' have been
# replaced with '_'. Non-flattened keys are preferred, because they allow submodules to be accessed directly
@@ -207,8 +226,55 @@ class LayerPatcher:
patch=layer,
patch_weight=patch_weight,
original_weights=original_weights,
+ shared_storage=shared_storage,
)
+ @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)."""
+ if tensor.layout is not torch.strided:
+ return 0
+ try:
+ return tensor.untyped_storage().data_ptr()
+ except (NotImplementedError, RuntimeError, AttributeError):
+ return 0
+
+ @staticmethod
+ def _shared_storage_ptrs(model: torch.nn.Module) -> set[int]:
+ """Storage addresses that more than one parameter or buffer of the model points into.
+
+ `parameters()` and `buffers()` list a tensor registered in several modules once, so a weight tied by
+ sharing one `Parameter` is not reported: patching it in place has the same effect as patching it
+ out of place, because both reach every module that holds it. Distinct tensors or views over one
+ storage are reported. `tensor_aliases.storage_key` does not fit: it also keys on offset, dtype and
+ shape, so two different views of one storage get different keys, and those must count as shared.
+ """
+ counts = Counter(LayerPatcher._storage_ptr(t) for t in chain(model.parameters(), model.buffers()))
+ # Address 0 stands for "no storage to read", not for one shared allocation.
+ counts.pop(0, None)
+ return {ptr for ptr, count in counts.items() if count > 1}
+
+ @staticmethod
+ def _can_update_in_place(param: torch.nn.Parameter, shared_storage: set[int], original: torch.Tensor) -> bool:
+ """Whether a directly patched weight may be changed in place and restored in place from `original`.
+
+ A weight on a device is a private copy of the model: the model cache always copies to the device. A CPU
+ weight is the cache's canonical copy (shared across devices, and the keep_ram_copy used to restore the
+ model), so it is replaced instead. Aliases outside `model` are not visible to the scan.
+
+ Storage shared within the model is real: the cache binds tied weights with `load_state_dict(assign=True)`
+ as separate parameters over one tensor (`lm_head` and `embed_tokens` of the Qwen3 encoders, see
+ `tensor_aliases.move_shared`), and an in-place change would also reach the other. Tensor subclasses
+ (GGUF, SDNQ) have no readable memory and are sidecar-patched. A non-contiguous weight is replaced
+ because `add_` rejects overlapping views and `copy_` stages a non-contiguous host-to-device copy in a
+ temporary. `original` must not share memory with the weight, or the patch would change the original too.
+ """
+ data = param.data
+ if data.device.type == "cpu" or type(data) is not torch.Tensor or not data.is_contiguous():
+ return False
+ ptr = LayerPatcher._storage_ptr(data)
+ return ptr not in shared_storage and ptr != LayerPatcher._storage_ptr(original)
+
@staticmethod
def _is_any_part_of_layer_on_cpu(layer: torch.nn.Module) -> bool:
return any(p.device.type == "cpu" for p in layer.parameters())
@@ -227,6 +293,7 @@ class LayerPatcher:
patch: BaseLayerPatch,
patch_weight: float,
original_weights: OriginalWeightsStorage,
+ shared_storage: set[int],
):
# All of the LoRA weight calculations will be done on the same device as the module weight.
# (Performance will be best if this is a CUDA device.)
@@ -276,7 +343,7 @@ class LayerPatcher:
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
+ # Point at the module's live (expanded) parameter so the 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)
@@ -292,15 +359,15 @@ class LayerPatcher:
# 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
+ # In place on a device, out-of-place otherwise (see `_can_update_in_place`). Bit-identical when the
+ # weight has the compute dtype. A weight of another dtype in a mixed module (an fp32 weight next to
+ # a bf16 bias) is rounded to its own dtype in place, where the sum used to be promoted and stay so.
+ original = original_weights.get(param_key)
+ assert original is not None
+ if LayerPatcher._can_update_in_place(module_param, shared_storage, original):
+ module_param.data.add_(param_weight_converted)
+ 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
diff --git a/invokeai/backend/stable_diffusion/extensions_manager.py b/invokeai/backend/stable_diffusion/extensions_manager.py
index 3783bb422e..3d45d50e2a 100644
--- a/invokeai/backend/stable_diffusion/extensions_manager.py
+++ b/invokeai/backend/stable_diffusion/extensions_manager.py
@@ -79,4 +79,4 @@ class ExtensionsManager:
finally:
with torch.no_grad():
for param_key, weight in original_weights.get_changed_weights():
- unet.get_parameter(param_key).copy_(weight)
+ unet.get_parameter(param_key).data.copy_(weight)
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.py
index c35bea1745..3124634ae9 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
@@ -531,6 +531,7 @@ def test_linear_sidecar_patches(device: str, patch_under_test: PatchUnderTest):
patch=patch,
patch_weight=weight,
original_weights=OriginalWeightsStorage(),
+ shared_storage=set(),
)
# Wrap the original layer in a custom layer and add the patch to it as a sidecar.
diff --git a/tests/backend/patches/test_layer_patcher.py b/tests/backend/patches/test_layer_patcher.py
index f01d6e3a92..c7a9caa88f 100644
--- a/tests/backend/patches/test_layer_patcher.py
+++ b/tests/backend/patches/test_layer_patcher.py
@@ -1,6 +1,6 @@
import gc
import weakref
-from typing import Callable
+from typing import Callable, Iterable
import pytest
import torch
@@ -13,6 +13,7 @@ from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.torch
)
from invokeai.backend.patches.layer_patcher import LayerPatcher
from invokeai.backend.patches.layers.base_layer_patch import BaseLayerPatch
+from invokeai.backend.patches.layers.flux_control_lora_layer import FluxControlLoRALayer
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
@@ -866,3 +867,129 @@ def test_every_layer_of_a_multi_layer_patch_is_returned() -> None:
for layer in patch.layers.values():
assert layer.up.device.type == "cpu"
assert layer.up.dtype == torch.bfloat16
+
+
+def _integer_lora(names: Iterable[str], features: int, rank: int = 4) -> ModelPatchRaw:
+ """Small integer factors keep `up @ down` exact in fp32 on every device, so results compare bit for bit."""
+ generator = torch.Generator().manual_seed(0)
+ layers = {}
+ for name in names:
+ layer = _lora_layer(features, features, rank, dtype=torch.float32)
+ layer.up = torch.randint(-2, 3, (features, rank), generator=generator).float()
+ layer.down = torch.randint(-2, 3, (rank, features), generator=generator).float()
+ layers[name] = layer
+ return ModelPatchRaw(layers=layers)
+
+
+requires_cuda = pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA device")
+
+
+@requires_cuda
+def test_direct_patching_on_a_device_keeps_each_weights_memory_and_matches_out_of_place_math():
+ """Patching and restoring in place keeps every weight's allocation, so the allocator pool is not
+ left fragmented by a fresh tensor per patched weight."""
+ dtype = torch.bfloat16
+ model = DummyModuleWithTwoLayers(in_features=8, out_features=8, device="cuda", dtype=dtype)
+ apply_custom_layers_to_model(model)
+ names = ["linear_layer_1", "linear_layer_2"]
+ patch = _integer_lora(names, features=8)
+ patch_weight = 0.75
+
+ originals = {name: getattr(model, name).weight.detach().clone() for name in names}
+ pointers = {name: getattr(model, name).weight.data_ptr() for name in names}
+ expected = {
+ name: originals[name]
+ + (patch.layers[name].up @ patch.layers[name].down * patch_weight).to(device="cuda", dtype=dtype)
+ for name in names
+ }
+
+ with LayerPatcher.apply_smart_model_patches(
+ model=model, patches=[(patch, patch_weight)], prefix="", dtype=dtype, force_direct_patching=True
+ ):
+ for name in names:
+ weight = getattr(model, name).weight
+ assert weight.data_ptr() == pointers[name]
+ assert torch.equal(weight, expected[name])
+
+ for name in names:
+ weight = getattr(model, name).weight
+ assert weight.data_ptr() == pointers[name]
+ assert torch.equal(weight, originals[name])
+
+
+@requires_cuda
+def test_direct_patching_does_not_reach_a_parameter_over_the_same_storage():
+ """The model cache binds tied weights (a text encoder's `lm_head` and `embed_tokens`) as separate parameters
+ over one tensor. An in-place patch of one would change the other, so that weight is replaced instead."""
+ dtype = torch.bfloat16
+ model = DummyModuleWithTwoLayers(in_features=8, out_features=8, device="cuda", dtype=dtype)
+ apply_custom_layers_to_model(model)
+ model.linear_layer_2.weight = torch.nn.Parameter(model.linear_layer_1.weight.data)
+ original = model.linear_layer_1.weight.detach().clone()
+
+ with LayerPatcher.apply_smart_model_patches(
+ model=model,
+ patches=[(_integer_lora(["linear_layer_1"], features=8), 1.0)],
+ prefix="",
+ dtype=dtype,
+ force_direct_patching=True,
+ ):
+ assert not torch.equal(model.linear_layer_1.weight, original)
+ assert torch.equal(model.linear_layer_2.weight, original)
+
+ assert torch.equal(model.linear_layer_1.weight, original)
+ assert torch.equal(model.linear_layer_2.weight, original)
+
+
[email protected]("device", ["cpu", pytest.param("cuda", marks=requires_cuda)])
+def test_flux_control_lora_expands_the_weight_for_the_scope_and_restores_its_shape(device: str):
+ model = DummyModuleWithOneLayer(4, 16, device=device, dtype=torch.float32)
+ apply_custom_layers_to_model(model)
+ original = model.linear_layer_1.weight.detach().clone()
+ patch = ModelPatchRaw(
+ layers={
+ "linear_layer_1": FluxControlLoRALayer(
+ up=torch.ones(16, 4), mid=None, down=torch.ones(4, 8), alpha=torch.tensor(4.0), bias=None
+ )
+ }
+ )
+
+ with LayerPatcher.apply_smart_model_patches(
+ model=model, patches=[(patch, 1.0)], prefix="", dtype=torch.float32, force_direct_patching=True
+ ):
+ expanded = model.linear_layer_1.weight
+ assert expanded.shape == (16, 8)
+ # The original columns carry the patch and the new ones only the patch.
+ assert torch.equal(expanded[:, :4], original + 4.0)
+ assert torch.equal(expanded[:, 4:], torch.full((16, 4), 4.0, device=device))
+
+ assert model.linear_layer_1.weight.shape == original.shape
+ assert torch.equal(model.linear_layer_1.weight, original)
+
+
+@requires_cuda
+def test_restore_follows_the_current_parameter_when_the_model_left_the_device_during_the_scope():
+ """An offload with a RAM copy rebinds the weight to the canonical CPU tensor. The restore must replace it
+ rather than write the original into the canonical copy."""
+ dtype = torch.bfloat16
+ model = DummyModuleWithOneLayer(8, 8, device="cuda", dtype=dtype)
+ apply_custom_layers_to_model(model)
+ original = model.linear_layer_1.weight.detach().clone()
+ canonical = {k: v.detach().cpu().clone() for k, v in model.state_dict().items()}
+ canonical_before = {k: v.clone() for k, v in canonical.items()}
+
+ with LayerPatcher.apply_smart_model_patches(
+ model=model,
+ patches=[(_integer_lora(["linear_layer_1"], features=8), 1.0)],
+ prefix="",
+ dtype=dtype,
+ force_direct_patching=True,
+ ):
+ model.load_state_dict(canonical, assign=True)
+
+ assert all(torch.equal(canonical[k], canonical_before[k]) for k in canonical)
+ assert torch.equal(model.linear_layer_1.weight.cpu(), original.cpu())
diff --git a/tests/backend/patches/test_layer_patcher_shared_weights.py b/tests/backend/patches/test_layer_patcher_shared_weights.py
index 328f93b04c..142d8bf5fc 100644
--- a/tests/backend/patches/test_layer_patcher_shared_weights.py
+++ b/tests/backend/patches/test_layer_patcher_shared_weights.py
@@ -8,6 +8,7 @@ corrupt the weights seen by the other GPU (and taint the cached "clean" copy eve
These run on CPU and force direct patching, which is the path that touches CPU-resident weights.
"""
+import pytest
import torch
from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.torch_module_autocast import (
@@ -74,10 +75,14 @@ def test_force_direct_patch_does_not_mutate_canonical_cpu_weights():
assert torch.allclose(out_before, model(x))
[email protected]("pass_cached_weights", [True, False], ids=["cached_weights", "no_cached_weights"])
@torch.no_grad()
-def test_two_models_sharing_canonical_are_isolated_under_direct_patch():
+def test_two_models_sharing_canonical_are_isolated_under_direct_patch(pass_cached_weights: bool):
"""Patch one model built from the shared canonical weights; a second model built from the same
- canonical tensors must be unaffected (no cross-device bleed)."""
+ canonical tensors must be unaffected (no cross-device bleed).
+
+ Without `cached_weights`, `save()` copies the original, so nothing but the CPU rule in
+ `_can_update_in_place` keeps `add_` out of the tensor that model_b also holds."""
in_features, out_features, rank = 4, 8, 2
model_a = DummyModuleWithOneLayer(in_features, out_features, device="cpu", dtype=torch.float32)
apply_custom_layers_to_model(model_a)
@@ -97,7 +102,7 @@ def test_two_models_sharing_canonical_are_isolated_under_direct_patch():
patches=lora_models,
prefix="",
dtype=torch.float32,
- cached_weights=canonical,
+ cached_weights=canonical if pass_cached_weights else None,
force_direct_patching=True,
):
# model_a is patched; model_b (sharing the canonical weights) must be unchanged.