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
import re
from collections import Counter
from contextlib import AbstractContextManager, ExitStack, contextmanager
from itertools import chain
from typing import Dict, Iterable, Iterator, Optional, Tuple
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, 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
from invokeai.backend.util.fp8 import FP8_STORAGE_DTYPES
from invokeai.backend.util.original_weights_storage import OriginalWeightsStorage
# The optional third item pins the patch's model-cache record without moving the whole patch to VRAM.
# Two-item specs remain valid for patches that do not come from the model cache.
PatchSpec = Tuple[ModelPatchRaw, float] | Tuple[ModelPatchRaw, float, AbstractContextManager[object]]
class LayerPatcher:
@staticmethod
@torch.no_grad()
@contextmanager
def apply_smart_model_patches(
model: torch.nn.Module,
patches: Iterable[PatchSpec],
prefix: str,
dtype: torch.dtype,
cached_weights: Optional[Dict[str, torch.Tensor]] = None,
force_direct_patching: bool = False,
force_sidecar_patching: bool = False,
suppress_warning_layers: Optional[re.Pattern] = None,
):
"""Apply 'smart' model patching that chooses whether to use direct patching or a sidecar wrapper for each
module.
"""
# original_weights are stored for unpatching layers that are directly patched.
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 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, 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
# context.models.load() on demand, and a cold-cache construction takes
# MODEL_LOAD_LOCK.write_lock(). Because this lock is non-reentrant and write-preferring,
# constructing a LoRA while we already held the read lock below would deadlock: the
# write acquire waits for readers==0, but this very thread is that reader. Consuming the
# iterator here lets every LoRA load take (and release) the write lock first, then we
# take the read lock once for patch application only. This is also compatible with
# callers that hand us a fresh iterator per call (see wan_denoise.LoRAIteratorFactory).
# Enter optional model-cache pins before patching and retain them through restoration.
materialized_patches: list[PatchSpec] = []
for patch_spec in patches:
if len(patch_spec) == 3:
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
# init_empty_weights), which would strand our new parameter on the meta device — so
# patch application must exclude construction, like any VRAM load. Read semantics:
# patching on different devices may overlap; only construction is exclusive. The lock
# is released before the yield — patched inference must not block model loads.
with MODEL_LOAD_LOCK.read_lock():
for patch_spec in patches:
patch, patch_weight = patch_spec[:2]
LayerPatcher.apply_smart_model_patch(
model=model,
prefix=prefix,
patch=patch,
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,
suppress_warning_layers=suppress_warning_layers,
shared_storage=shared_storage,
)
yield
finally:
try:
# Restore directly patched layers.
for param_key, weight in original_weights.get_changed_weights():
cur_param = model.get_parameter(param_key)
# 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.
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 leaf, leaf_device, leaf_dtype in patch_placements.values():
leaf.to(device=leaf_device, dtype=leaf_dtype)
finally:
cache_pins.close()
@staticmethod
@torch.no_grad()
def apply_smart_model_patch(
model: torch.nn.Module,
prefix: str,
patch: ModelPatchRaw,
patch_weight: float,
original_weights: OriginalWeightsStorage,
original_modules: dict[str, torch.nn.Module],
patch_placements: dict[int, tuple[BaseLayerPatch, torch.device, torch.dtype]],
dtype: torch.dtype,
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.
"""
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
# without searching, but some legacy code still uses flattened keys.
#
# We inspect *all* keys rather than just the first one: a flattened key never contains a dot, so the patch is
# only flattened if no key contains a dot. Checking only the first key misclassifies non-flattened patches whose
# first layer happens to target a top-level module with a single-token name (e.g. a Flux2 diffusers LoRA whose
# first converted layer is `lora_transformer-context_embedder`), causing a spurious assertion failure on
# subsequent dotted keys.
layer_keys_are_flattened = not any("." in key for key in patch.layers.keys())
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
try:
module_key, module = LayerPatcher._get_submodule(
model, layer_key[prefix_len:], layer_key_is_flattened=layer_keys_are_flattened
)
except AttributeError:
if suppress_warning_layers and suppress_warning_layers.search(layer_key):
pass
else:
logger = InvokeAILogger.get_logger(LayerPatcher.__name__)
logger.warning("Failed to find module for LoRA layer key: %s", layer_key)
continue
# Decide whether to use direct patching or a sidecar patch.
# Direct patching is preferred, because it results in better runtime speed.
# Reasons to use sidecar patching:
# - The module is quantized, so the caller passed force_sidecar_patching=True.
# - The module already has sidecar patches.
# - The module is on the CPU (and we don't want to store a second full copy of the original weights on the
# CPU, since this would double the RAM usage)
# NOTE: For now, we don't check if the layer is quantized here. We assume that this is checked in the caller
# 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 = LayerPatcher._uses_sidecar(module, force_direct_patching, force_sidecar_patching)
if use_sidecar_patching:
LayerPatcher._apply_model_layer_wrapper_patch(
module_to_patch=module,
module_to_patch_key=module_key,
patch=layer,
patch_weight=patch_weight,
original_modules=original_modules,
patch_placements=patch_placements,
dtype=dtype,
)
else:
LayerPatcher._apply_model_layer_patch(
module_to_patch=module,
module_to_patch_key=module_key,
patch=layer,
patch_weight=patch_weight,
original_weights=original_weights,
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)."""
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())
# Direct patching does in-place arithmetic on the model weights, which has no CUDA kernel for the
# FP8 storage dtypes, so a layer with fp8 weights must be patched via the sidecar wrapper.
@staticmethod
def _is_any_part_of_layer_fp8(layer: torch.nn.Module) -> bool:
return any(p.dtype in FP8_STORAGE_DTYPES for p in layer.parameters())
@staticmethod
@torch.no_grad()
def _apply_model_layer_patch(
module_to_patch: torch.nn.Module,
module_to_patch_key: str,
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.)
first_param = next(module_to_patch.parameters())
device = first_param.device
dtype = first_param.dtype
# 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(...)'.
#
# 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)
# 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 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)
# 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:
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]]:
"""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 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.
"""
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()
def _apply_model_layer_wrapper_patch(
module_to_patch: torch.nn.Module,
module_to_patch_key: str,
patch: BaseLayerPatch,
patch_weight: float,
original_modules: dict[str, torch.nn.Module],
patch_placements: dict[int, tuple[BaseLayerPatch, torch.device, torch.dtype]],
dtype: torch.dtype,
):
"""Apply a single LoRA wrapper patch to a module."""
# Move the LoRA layer to the same device/dtype as the orig module. Quantized modules
# that register their weights as buffers (e.g. MiniMax H3's Int8ConvrotLinear) have no
# parameters at all — fall back to the first buffer for the device reference.
first_tensor = next(module_to_patch.parameters(), None)
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`.
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:
original_modules[module_to_patch_key] = module_to_patch
module_to_patch.add_patch(patch, patch_weight)
@staticmethod
def _split_parent_key(module_key: str) -> tuple[str, str]:
"""Split a module key into its parent key and module name.
Args:
module_key (str): The module key to split.
Returns:
tuple[str, str]: A tuple containing the parent key and module name.
"""
split_key = module_key.rsplit(".", 1)
if len(split_key) == 2:
return tuple(split_key)
elif len(split_key) == 1:
return "", split_key[0]
else:
raise ValueError(f"Invalid module key: {module_key}")
@staticmethod
def _set_submodule(parent_module: torch.nn.Module, module_name: str, submodule: torch.nn.Module):
try:
submodule_index = int(module_name)
# If the module name is an integer, then we use the __setitem__ method to set the submodule.
parent_module[submodule_index] = submodule # type: ignore
except ValueError:
# If the module name is not an integer, then we use the setattr method to set the submodule.
setattr(parent_module, module_name, submodule)
@staticmethod
def _get_submodule(
model: torch.nn.Module, layer_key: str, layer_key_is_flattened: bool
) -> tuple[str, torch.nn.Module]:
"""Get the submodule corresponding to the given layer key.
Args:
model (torch.nn.Module): The model to search.
layer_key (str): The layer key to search for.
layer_key_is_flattened (bool): Whether the layer key is flattened. If flattened, then all '.' have been
replaced with '_'. Non-flattened keys are preferred, because they allow submodules to be accessed
directly without searching, but some legacy code still uses flattened keys.
Returns:
tuple[str, torch.nn.Module]: A tuple containing the module key and the submodule.
"""
# LoRA formats address CLIP text encoder 1 under `text_model`, a wrapper transformers >=5.6 removed from
# CLIPTextModel (CLIPTextModelWithProjection keeps it), so drop the prefix for that class.
if isinstance(model, CLIPTextModel):
layer_key = layer_key.removeprefix("text_model_" if layer_key_is_flattened else "text_model.")
if not layer_key_is_flattened:
return layer_key, model.get_submodule(layer_key)
# Handle flattened keys.
assert "." not in layer_key
module = model
module_key = ""
key_parts = layer_key.split("_")
submodule_name = key_parts.pop(0)
while len(key_parts) > 0:
try:
module = module.get_submodule(submodule_name)
module_key += "." + submodule_name
submodule_name = key_parts.pop(0)
except Exception:
submodule_name += "_" + key_parts.pop(0)
module = module.get_submodule(submodule_name)
module_key = (module_key + "." + submodule_name).lstrip(".")
return module_key, module