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: avoid duplicate RAM reservation for shared weights (#10252)

Nianze Wu05c2838721b5
diff --git a/invokeai/backend/model_manager/load/load_default.py b/invokeai/backend/model_manager/load/load_default.py
index 28c70d8f07..46251aa098 100644
--- a/invokeai/backend/model_manager/load/load_default.py
+++ b/invokeai/backend/model_manager/load/load_default.py
@@ -23,6 +23,7 @@ from invokeai.backend.model_manager.load.model_cache.model_cache import (
ModelCache,
get_model_cache_key,
)
+from invokeai.backend.model_manager.load.model_cache.shared_cpu_weights import SharedCpuWeightsPin
from invokeai.backend.model_manager.load.model_util import calc_model_size_by_fs
from invokeai.backend.model_manager.load.optimizations import skip_torch_weight_init
from invokeai.backend.model_manager.taxonomy import (
@@ -432,11 +433,23 @@ class ModelLoader(ModelLoaderBase):
# clone of the built module. Adopt those weights instead of re-reading the model from
# disk — this avoids both the redundant disk read and the large transient second copy
# that would otherwise spike RAM (and, on a RAM-constrained box, drive the system into
- # swap). Any failure falls back to a normal load, so it can never change the result.
- loaded_model = self._try_adopt_shared_weights(cache_key)
+ # swap). If the shell cannot be materialized, fall back to the normal disk load.
+ execution_device = self._get_execution_device(config, submodel_type)
+ shared_store = self._ram_cache.shared_cpu_weights
+ selection = shared_store.pin_for_adoption(cache_key) if shared_store is not None else nullcontext(None)
+ with selection as adoption:
+ adopted_model = self._try_adopt_shared_weights(cache_key, adoption) if adoption is not None else None
+ if adopted_model is not None:
+ admission_claim = self._ram_cache.put(
+ cache_key,
+ model=adopted_model,
+ execution_device=execution_device,
+ claim_admission=True,
+ adoption=adoption,
+ )
shell_to_register: Optional[torch.nn.Module] = None
- if loaded_model is None:
+ if adopted_model is None:
# Optional RAM instrumentation for the cold disk-load path (the only place that runs
# `from_pretrained`, whose construction transient can briefly spike RAM past the
# cache's retained budget). Gated on `log_memory_usage`; captures process RAM before
@@ -460,19 +473,15 @@ class ModelLoader(ModelLoaderBase):
# Snapshot a meta-weight clone now — before put() applies custom layers or any VRAM
# move — so the next device to load this model can adopt these weights (see above).
# Skipped in single-device setups, where no other cache will ever adopt it.
- shared_store = self._ram_cache.shared_cpu_weights
if shared_store is not None and shared_store.enable_shell_capture:
shell_to_register = self._build_meta_shell(loaded_model)
- # Determine execution device from model config, considering submodel type
- execution_device = self._get_execution_device(config, submodel_type)
-
- admission_claim = self._ram_cache.put(
- cache_key,
- model=loaded_model,
- execution_device=execution_device,
- claim_admission=True,
- )
+ admission_claim = self._ram_cache.put(
+ cache_key,
+ model=loaded_model,
+ execution_device=execution_device,
+ claim_admission=True,
+ )
# Retrieve immediately, and hold the admission claim across the retrieval: the claim
# shields the new record until this frame's own claim takes over, so nothing — a peer's
# reconcile, another model's make-room, the cache's shutdown() — can evict the model
@@ -486,10 +495,8 @@ class ModelLoader(ModelLoaderBase):
# Register the shell only after put() has created the shared entry (via the wrapper's
# acquire); it is dropped automatically when that entry's last reference is released.
- if shell_to_register is not None:
- shared_store = self._ram_cache.shared_cpu_weights
- if shared_store is not None:
- shared_store.set_shell(cache_key, shell_to_register)
+ if shell_to_register is not None and shared_store is not None:
+ shared_store.set_shell(cache_key, shell_to_register)
return cache_record, first_use_claim
@@ -885,7 +892,7 @@ class ModelLoader(ModelLoaderBase):
module.register_forward_pre_hook(pre_hook)
module.register_forward_hook(post_hook, always_call=True)
- def _try_adopt_shared_weights(self, cache_key: str) -> Optional[AnyModel]:
+ def _try_adopt_shared_weights(self, cache_key: str, adoption: SharedCpuWeightsPin) -> torch.nn.Module | None:
"""Build this model by adopting another device's already-resident CPU weights, skipping the
disk read entirely.
@@ -895,23 +902,15 @@ class ModelLoader(ModelLoaderBase):
shared canonical weights into the copy — no per-loader architecture knowledge required, and
fp8 cast hooks carried by the shell are preserved automatically.
- Must be called while holding the MODEL_LOAD_LOCK write lock (as `_load_and_cache` does), so
- the peeked canonical weights and shell cannot be evicted between the peek and the adopt.
+ The pin protects shell and weights during the clone. Admission keeps the pin only when
+ the cache can use a zero reservation. Peer eviction may run under the model load lock.
"""
- shared_store = self._ram_cache.shared_cpu_weights
- if shared_store is None:
- return None
- canonical = shared_store.peek(cache_key)
- shell = shared_store.get_shell(cache_key)
- if canonical is None or shell is None:
- return None
-
try:
# Independent module per device (its params will be moved to its own GPU); deep-copying an
# all-meta shell is cheap (no weight data). assign=True then re-points the copy's
# parameters at the shared canonical tensors with no allocation.
- model = copy.deepcopy(shell)
- model.load_state_dict(canonical, assign=True)
+ model = copy.deepcopy(adoption.shell)
+ model.load_state_dict(adoption.state_dict, assign=True)
# Safety net: if anything is left on the meta device (e.g. a persistent buffer somehow
# missing from the canonical state dict) the model would silently produce wrong results.
for tensor in itertools.chain(model.parameters(), model.buffers()):
diff --git a/invokeai/backend/model_manager/load/model_cache/cached_model/cached_model_only_full_load.py b/invokeai/backend/model_manager/load/model_cache/cached_model/cached_model_only_full_load.py
index f41cfc09dc..9f835f7529 100644
--- a/invokeai/backend/model_manager/load/model_cache/cached_model/cached_model_only_full_load.py
+++ b/invokeai/backend/model_manager/load/model_cache/cached_model/cached_model_only_full_load.py
@@ -75,6 +75,7 @@ class CachedModelOnlyFullLoad:
# module at the shared tensors and drop our duplicate so the weights live once in RAM.
if shared_store is not None and cache_key is not None:
canonical = shared_store.acquire(cache_key, cpu_state_dict)
+ self._cpu_state_dict = canonical # Release this exact entry if construction fails.
self._shared_store = shared_store
self._shared_key = cache_key
try:
@@ -95,7 +96,7 @@ class CachedModelOnlyFullLoad:
self, shared_store.release_deferred, cache_key, canonical
)
self._shared_release_finalizer.atexit = False
- except Exception:
+ except BaseException:
# The re-point or finalizer registration failed after acquiring a reference;
# release it so the shared entry's refcount isn't leaked (this wrapper will
# never enter the cache).
diff --git a/invokeai/backend/model_manager/load/model_cache/cached_model/cached_model_with_partial_load.py b/invokeai/backend/model_manager/load/model_cache/cached_model/cached_model_with_partial_load.py
index 53ed67d1ae..3f2e26bedc 100644
--- a/invokeai/backend/model_manager/load/model_cache/cached_model/cached_model_with_partial_load.py
+++ b/invokeai/backend/model_manager/load/model_cache/cached_model/cached_model_with_partial_load.py
@@ -113,6 +113,7 @@ class CachedModelWithPartialLoad:
# drop our freshly-built duplicate so the weights live once in RAM.
if cpu_state_dict is not None and shared_store is not None and cache_key is not None:
canonical = shared_store.acquire(cache_key, cpu_state_dict)
+ self._cpu_state_dict = canonical # Release this exact entry if construction fails.
self._shared_store = shared_store
self._shared_key = cache_key
try:
@@ -132,7 +133,7 @@ class CachedModelWithPartialLoad:
self, shared_store.release_deferred, cache_key, canonical
)
self._shared_release_finalizer.atexit = False
- except Exception:
+ except BaseException:
# The re-point or finalizer registration failed after acquiring a reference;
# release it so the shared entry's refcount isn't leaked (this wrapper will never
# be inserted into the cache).
diff --git a/invokeai/backend/model_manager/load/model_cache/model_cache.py b/invokeai/backend/model_manager/load/model_cache/model_cache.py
index 4a18e780bd..090c0f7059 100644
--- a/invokeai/backend/model_manager/load/model_cache/model_cache.py
+++ b/invokeai/backend/model_manager/load/model_cache/model_cache.py
@@ -5,7 +5,7 @@ import sys
import threading
import time
import weakref
-from contextlib import contextmanager
+from contextlib import AbstractContextManager, contextmanager, nullcontext
from dataclasses import dataclass
from functools import wraps
from logging import Logger
@@ -27,6 +27,7 @@ from invokeai.backend.model_manager.load.model_cache.cached_model.cached_model_w
from invokeai.backend.model_manager.load.model_cache.ram_budget import RamBudget
from invokeai.backend.model_manager.load.model_cache.shared_cpu_weights import (
SHARED_CPU_WEIGHTS,
+ SharedCpuWeightsPin,
SharedCpuWeightsStore,
)
from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.torch_module_autocast import (
@@ -583,6 +584,9 @@ class ModelCache:
"""
self._shared_cpu_weights = shared_cpu_weights
self._ram_budget = ram_budget
+ self._budget_counts_store = (
+ ram_budget is not None and shared_cpu_weights is not None and ram_budget.counts_store(shared_cpu_weights)
+ )
self._enable_partial_loading = enable_partial_loading
self._keep_ram_copy_of_weights = keep_ram_copy_of_weights
# Notices already emitted, keyed by (topic, device), so each is logged once rather than
@@ -685,6 +689,9 @@ class ModelCache:
computed from their individual sizes (see ModelManagerService.build_model_manager).
"""
self._ram_budget = ram_budget
+ self._budget_counts_store = self._shared_cpu_weights is not None and ram_budget.counts_store(
+ self._shared_cpu_weights
+ )
ram_budget.register_cache(self)
@property
@@ -910,6 +917,8 @@ class ModelCache:
execution_device: Optional[torch.device] = None,
prefetch: bool = False,
claim_admission: bool = False,
+ *,
+ adoption: SharedCpuWeightsPin | None = None,
) -> Optional[FirstUseClaim]:
"""Add a model to the cache.
@@ -932,6 +941,7 @@ class ModelCache:
cannot outlive its load, so a load that is cancelled or errors before its
retrieval releases the admission by dying, instead of leaving a grace standing
that nothing can clear (see shutdown()).
+ adoption: Source pin passed by the loader so a full reservation can release it early.
"""
if key in self._cached_models:
self._logger.debug(
@@ -1032,11 +1042,6 @@ class ModelCache:
return None
size = calc_model_size_by_data(self._logger, model)
- self._make_room_internal(size)
-
- # Inject custom modules into the model.
- if isinstance(model, torch.nn.Module):
- apply_custom_layers_to_model(model)
# Use the provided execution device, or fall back to the cache's default
effective_execution_device = execution_device if execution_device is not None else self._execution_device
@@ -1050,7 +1055,8 @@ class ModelCache:
# ("no choice but to try and fit it all"), and on Linux that overshoot is an uncatchable OOM-kill rather than
# a degraded load. Combined with keep_ram_copy=False below, streaming moves weights rather than copying them.
running_with_dedicated_vram = device_has_dedicated_vram(effective_execution_device)
- supports_partial_loading = running_with_dedicated_vram or _is_integrated_xpu(effective_execution_device)
+ integrated_xpu = _is_integrated_xpu(effective_execution_device)
+ supports_partial_loading = running_with_dedicated_vram or integrated_xpu
# On an integrated GPU the "VRAM" copy and the RAM copy are the same DRAM, so keeping a RAM
# copy makes every resident model cost twice its size: full_load_to_vram() copies each
@@ -1060,11 +1066,11 @@ class ModelCache:
#
# Scoped to integrated XPU on purpose: CPU and MPS share memory too, but their behaviour
# here predates this and is left alone.
- keep_ram_copy = self._keep_ram_copy_of_weights and not _is_integrated_xpu(effective_execution_device)
+ keep_ram_copy = self._keep_ram_copy_of_weights and not integrated_xpu
# Overriding a setting the user turned on is worth saying once, rather than leaving someone
# to wonder why it made no difference.
- if self._keep_ram_copy_of_weights and _is_integrated_xpu(effective_execution_device):
+ if self._keep_ram_copy_of_weights and integrated_xpu:
self._warn_once(
"keep_ram_copy",
effective_execution_device,
@@ -1073,24 +1079,39 @@ class ModelCache:
"footprint against the same memory. Weights are moved rather than copied.",
)
- # Wrap model.
- if isinstance(model, torch.nn.Module) and supports_partial_loading and self._enable_partial_loading:
- wrapped_model = CachedModelWithPartialLoad(
- model,
- effective_execution_device,
- keep_ram_copy=keep_ram_copy,
- shared_store=self._shared_cpu_weights,
- cache_key=key,
- )
- else:
- wrapped_model = CachedModelOnlyFullLoad(
- model,
- effective_execution_device,
- size,
- keep_ram_copy=keep_ram_copy,
- shared_store=self._shared_cpu_weights,
- cache_key=key,
- )
+ store = self._shared_cpu_weights
+ if adoption is not None and (store is None or not isinstance(model, torch.nn.Module)):
+ raise RuntimeError("Adoption requires a module and a shared CPU weights store.")
+ reservation: AbstractContextManager[bool] = nullcontext(False)
+ if store is not None and isinstance(model, torch.nn.Module):
+ check_match = keep_ram_copy and self._budget_counts_store
+ if check_match or adoption is not None:
+ reservation = store.pin_for_admission(key, model if check_match else None, size, adoption)
+
+ with reservation as shares_reservation:
+ self._make_room_internal(0 if shares_reservation else size)
+
+ # Inject custom modules into the model.
+ if isinstance(model, torch.nn.Module):
+ apply_custom_layers_to_model(model)
+
+ if isinstance(model, torch.nn.Module) and supports_partial_loading and self._enable_partial_loading:
+ wrapped_model = CachedModelWithPartialLoad(
+ model,
+ effective_execution_device,
+ keep_ram_copy=keep_ram_copy,
+ shared_store=store,
+ cache_key=key,
+ )
+ else:
+ wrapped_model = CachedModelOnlyFullLoad(
+ model,
+ effective_execution_device,
+ size,
+ keep_ram_copy=keep_ram_copy,
+ shared_store=store,
+ cache_key=key,
+ )
# awaiting_first_use protects an unclaimed new entry from the asynchronous eviction paths
# (budget reconcile, peer-requested eviction) until the loader locks it - see CacheRecord.
@@ -3146,6 +3167,10 @@ class ModelCache:
a setting toggled during an in-flight generation would survive on the locked entry and quietly
get reused by the next generation.
+ Callers must serialize this operation against loads and admissions in every device cache,
+ using MODEL_LOAD_LOCK.write_lock() if they may run concurrently. The per-cache lock alone
+ cannot provide that fence.
+
Returns the number of entries immediately dropped (locked entries that are only marked
stale do not count).
"""
diff --git a/invokeai/backend/model_manager/load/model_cache/ram_budget.py b/invokeai/backend/model_manager/load/model_cache/ram_budget.py
index 55b3c3d260..48239b6166 100644
--- a/invokeai/backend/model_manager/load/model_cache/ram_budget.py
+++ b/invokeai/backend/model_manager/load/model_cache/ram_budget.py
@@ -74,6 +74,10 @@ class RamBudget:
"""The global cap on actual model-cache RAM, in bytes."""
return self._max_bytes
+ def counts_store(self, store: SharedCpuWeightsStore) -> bool:
+ """Whether this budget includes this store's canonical weights."""
+ return self._store is store
+
def add_non_shared(self, nbytes: int, cache: Optional["ModelCache"] = None) -> None:
"""Record `nbytes` of newly-resident non-deduplicated model RAM."""
with self._lock:
diff --git a/invokeai/backend/model_manager/load/model_cache/shared_cpu_weights.py b/invokeai/backend/model_manager/load/model_cache/shared_cpu_weights.py
index e0a8db38b4..4389a16da2 100644
--- a/invokeai/backend/model_manager/load/model_cache/shared_cpu_weights.py
+++ b/invokeai/backend/model_manager/load/model_cache/shared_cpu_weights.py
@@ -1,13 +1,16 @@
+import itertools
import queue
import threading
+from collections.abc import Iterator
+from contextlib import contextmanager
from dataclasses import dataclass, field
import torch
-from invokeai.backend.model_manager.load.model_cache.tensor_aliases import analyze_state_dict
+from invokeai.backend.model_manager.load.model_cache.tensor_aliases import analyze_state_dict, storage_key
-@dataclass
+@dataclass(eq=False)
class _SharedWeightsEntry:
"""A single canonical CPU state dict shared across per-device caches."""
@@ -23,6 +26,23 @@ class _SharedWeightsEntry:
_key_bytes: dict[str, int] = field(default_factory=dict)
+@dataclass(eq=False)
+class SharedCpuWeightsPin:
+ """Temporary custody of the entry while its shell is cloned and admitted."""
+
+ _entry: _SharedWeightsEntry | None
+
+ @property
+ def state_dict(self) -> dict[str, torch.Tensor]:
+ assert self._entry is not None
+ return self._entry.state_dict
+
+ @property
+ def shell(self) -> torch.nn.Module:
+ assert self._entry is not None and isinstance(self._entry.shell, torch.nn.Module)
+ return self._entry.shell
+
+
class SharedCpuWeightsStore:
"""Process-global store of canonical CPU weight tensors, shared across per-device model caches.
@@ -46,7 +66,9 @@ class SharedCpuWeightsStore:
Thread-safety: `acquire()`/`release()` are guarded by an internal lock. Note that model
construction (where `acquire()` is normally called) is already serialized process-globally by
`MODEL_LOAD_LOCK.write_lock()`; the internal lock here additionally protects `release()`, which
- runs under a per-cache lock off the global construction lock.
+ runs under a per-cache lock off the global construction lock. Callers must serialize an entire
+ load/admission against invalidation with that write lock; the store lock protects individual
+ operations, not the transaction across cloning, admission and invalidation.
"""
def __init__(self) -> None:
@@ -97,19 +119,89 @@ class SharedCpuWeightsStore:
entry.refcount += 1
return entry.state_dict
+ @contextmanager
+ def pin_for_adoption(self, key: str) -> Iterator[SharedCpuWeightsPin | None]:
+ """Select and pin the canonical and shell together for cloning and admission."""
+ adoption = None
+ with self._lock:
+ self._drain_deferred_locked()
+ entry = self._entries.get(key)
+ if entry is not None and isinstance(entry.shell, torch.nn.Module):
+ adoption = SharedCpuWeightsPin(entry)
+ entry.refcount += 1
+ del entry # The pin must not retain the shell after custody is dropped.
+ try:
+ yield adoption
+ finally:
+ if adoption is not None:
+ with self._lock:
+ self._release_adoption_pin_locked(key, adoption)
+
+ def _release_adoption_pin_locked(self, key: str, adoption: SharedCpuWeightsPin) -> None:
+ if (entry := adoption._entry) is not None:
+ adoption._entry = None
+ self._release_entry_locked(key, entry)
+
def peek(self, key: str) -> dict[str, torch.Tensor] | None:
"""Return the canonical state dict for `key` WITHOUT changing its refcount, or None if absent.
- Used by the loader to adopt already-resident weights at construction time (skipping the disk
- read) when another device has already loaded this model. The reference is taken later, in the
- cached-model wrapper's `acquire()`, exactly as for a normal load — so this peek must not
- itself increment the count.
+ For inspection. Use pin_for_adoption() to select the shell and weights together.
"""
with self._lock:
self._drain_deferred_locked()
entry = self._entries.get(key)
return entry.state_dict if entry is not None else None
+ @contextmanager
+ def pin_for_admission(
+ self,
+ key: str,
+ model: torch.nn.Module | None,
+ total_bytes: int,
+ adoption: SharedCpuWeightsPin | None,
+ ) -> Iterator[bool]:
+ """Keep custody only when the conservative matcher allows zero reservation.
+
+ The cache supplies a module only when it keeps a CPU copy and its budget counts this store.
+ An adoption that needs the full reservation releases its pin before eviction starts.
+ Zero reservation requires the complete module to alias the canonical state, with matching
+ keys and size. Packed tensors, tied weights, private or non-persistent buffers, and data
+ outside the module can prevent a match and therefore still require a full reservation.
+ """
+ state_dict = None
+ if model is not None:
+ candidate = model.state_dict()
+ model_tensors = {storage_key(t) for t in itertools.chain(model.parameters(), model.buffers())}
+ if model_tensors == {storage_key(t) for t in candidate.values()}:
+ state_dict = candidate
+
+ with self._lock:
+ self._drain_deferred_locked()
+ pinned = self._entries.get(key)
+ if (
+ pinned is None
+ or (adoption is not None and pinned is not adoption._entry)
+ or state_dict is None
+ or pinned.total_bytes != total_bytes
+ or pinned.state_dict.keys() != state_dict.keys()
+ or any(
+ tensor.device.type != "cpu" or storage_key(tensor) != storage_key(pinned.state_dict[name])
+ for name, tensor in state_dict.items()
+ )
+ ):
+ pinned = None
+ if adoption is not None:
+ self._release_adoption_pin_locked(key, adoption)
+ elif adoption is None:
+ pinned.refcount += 1
+
+ try:
+ yield pinned is not None
+ finally:
+ if pinned is not None and adoption is None:
+ with self._lock:
+ self._release_entry_locked(key, pinned)
+
def set_shell(self, key: str, shell: object) -> None:
"""Register the empty (meta-weight) structural clone for `key`, if an entry exists and none
is set yet. A no-op when the key has no canonical entry (e.g. keep_ram_copy disabled)."""
@@ -169,20 +261,24 @@ class SharedCpuWeightsStore:
"""The body of release(). Caller must hold self._lock."""
entry = self._entries.get(key)
if entry is not None and (state_dict is None or entry.state_dict is state_dict):
- entry.refcount -= 1
- if entry.refcount <= 0:
- del self._entries[key]
+ self._release_entry_locked(key, entry)
return
# Not the live canonical for `key` — it may be a retired (invalidated) entry whose
# tensors are still being counted against the RAM budget.
if state_dict is not None:
- for i, retired in enumerate(self._retired):
+ for retired in self._retired:
if retired.state_dict is state_dict:
- retired.refcount -= 1
- if retired.refcount <= 0:
- del self._retired[i]
+ self._release_entry_locked(key, retired)
return
+ def _release_entry_locked(self, key: str, entry: _SharedWeightsEntry) -> None:
+ entry.refcount -= 1
+ if entry.refcount == 0:
+ if self._entries.get(key) is entry:
+ del self._entries[key]
+ else:
+ self._retired.remove(entry)
+
def invalidate(self, model_key: str) -> int:
"""Forget the canonical entries (and shells) for `model_key` and all of its submodels, so no
future `acquire()`/`peek()` can adopt them. Returns the number of entries forgotten.
diff --git a/tests/app/services/model_load/test_stale_model_load_fence.py b/tests/app/services/model_load/test_stale_model_load_fence.py
index 0d3bfcaa03..1dd31c66b3 100644
--- a/tests/app/services/model_load/test_stale_model_load_fence.py
+++ b/tests/app/services/model_load/test_stale_model_load_fence.py
@@ -27,6 +27,7 @@ from invokeai.backend.model_manager.load import (
StaleModelConfigError,
)
from invokeai.backend.model_manager.load.model_cache.model_cache import MODEL_LOAD_LOCK
+from invokeai.backend.model_manager.load.model_cache.shared_cpu_weights import SharedCpuWeightsStore
from invokeai.backend.model_manager.taxonomy import AnyModel, ModelType, SubModelType
from invokeai.backend.util.logging import InvokeAILogger
from tests.fixtures.model_roles import text_llm_file
@@ -330,6 +331,90 @@ def _warm(service: ModelLoadService, store: ModelRecordServiceSQL) -> None:
assert _is_cached(service.ram_cache)
+def test_service_drop_waits_for_cross_cache_adoption(harness, monkeypatch):
+ service, records, source, _ = harness
+ weights = SharedCpuWeightsStore()
+ source._shared_cpu_weights = weights
+ _warm(service, records)
+ canonical = weights.peek(KEY)
+ assert canonical is not None and weights.get_shell(KEY) is not None
+
+ dest = ModelCache(
+ execution_device_working_mem_gb=1,
+ enable_partial_loading=False,
+ keep_ram_copy_of_weights=True,
+ execution_device="cpu",
+ logger=InvokeAILogger.get_logger(),
+ shared_cpu_weights=weights,
+ )
+ service._ram_caches = {"source": source, "cpu": dest}
+ # Unmatched host devices must also load into the destination, not the warmed source.
+ service._default_ram_cache = dest
+ cloning, resume, waiting = threading.Event(), threading.Event(), threading.Event()
+ original_adopt = _RecordingLoader._try_adopt_shared_weights
+ original_wait = MODEL_LOAD_LOCK._cond.wait
+
+ def paused_adopt(loader, key, pin):
+ assert pin.state_dict is canonical
+ cloning.set()
+ assert resume.wait(30), "adoption was not released"
+ return original_adopt(loader, key, pin)
+
+ def observe_wait(timeout=None):
+ if threading.current_thread().name == "drop-model":
+ waiting.set()
+ return original_wait(timeout)
+
+ monkeypatch.setattr(_RecordingLoader, "_try_adopt_shared_weights", paused_adopt)
+ monkeypatch.setattr(MODEL_LOAD_LOCK._cond, "wait", observe_wait)
+ outcomes: list[object] = []
+ drops: list[object] = []
+
+ def run(result, operation):
+ try:
+ result.append(operation())
+ except BaseException as exc:
+ result.append(exc)
+
+ loader = threading.Thread(
+ target=run, args=(outcomes, lambda: service.load_model(records.get_model(KEY))), daemon=True
+ )
+ drop = threading.Thread(
+ name="drop-model", target=run, args=(drops, lambda: service.drop_cached_models([KEY])), daemon=True
+ )
+ try:
+ loader.start()
+ assert cloning.wait(10), f"loader did not reach adoption: {outcomes}"
+ drop.start()
+ assert waiting.wait(10), "drop did not wait for the model load lock"
+ with MODEL_LOAD_LOCK._cond:
+ assert MODEL_LOAD_LOCK._writer_active and MODEL_LOAD_LOCK._writers_waiting > 0
+ assert not drops
+ resume.set()
+ loader.join(10)
+ drop.join(10)
+ assert not loader.is_alive() and not drop.is_alive()
+ assert len(outcomes) == 1 and isinstance(outcomes[0], LoadedModel), outcomes
+ assert len(drops) == 1 and isinstance(drops[0], int), drops
+ assert _RecordingLoader.built_from == [None]
+ assert weights.peek(KEY) is None
+ assert dest._cached_models[KEY].is_stale
+ assert dest._cached_models[KEY].cached_model.get_cpu_state_dict() is canonical
+ with outcomes[0]:
+ pass
+ with service.load_model(records.get_model(KEY)):
+ pass
+ assert _RecordingLoader.built_from == [None, None]
+ finally:
+ resume.set()
+ loader.join(10)
+ if drop.ident is not None:
+ drop.join(10)
+ if not loader.is_alive() and not drop.is_alive():
+ dest.shutdown()
+ source.shutdown()
+
+
def test_a_change_drops_the_model_before_it_ends(harness):
"""Loads of a model wait for its changes to end, so the cached instance must be gone by then: a load that starts
once the change has ended must find nothing to reuse."""
diff --git a/tests/backend/model_manager/load/model_cache/cached_model/test_cached_model_shared_weights.py b/tests/backend/model_manager/load/model_cache/cached_model/test_cached_model_shared_weights.py
index cfd9a8da50..a8e5ded6a0 100644
--- a/tests/backend/model_manager/load/model_cache/cached_model/test_cached_model_shared_weights.py
+++ b/tests/backend/model_manager/load/model_cache/cached_model/test_cached_model_shared_weights.py
@@ -126,3 +126,36 @@ def test_acquire_is_released_if_repoint_fails():
assert store.refcount("m") == 1 # back to just the first device, not leaked at 2
assert first.uses_shared_weights # keep the first wrapper alive through the assertions above
+
+
[email protected]("partial", [False, True], ids=["full", "partial"])
+def test_repoint_failure_releases_retired_entry_after_replacement(partial):
+ store = SharedCpuWeightsStore()
+ canonical = store.acquire("m", DummyModule().state_dict())
+ canonical_bytes = store.total_bytes_in_use()
+ replacement = DummyModule().state_dict()
+ incoming = DummyModule()
+
+ def replace_and_fail(*args):
+ assert store.peek("m") is canonical
+ assert store.refcount("m") == 2
+ assert store.invalidate("m") == 1
+ store.acquire("m", replacement)
+ raise RuntimeError("re-point failed after replacement")
+
+ incoming.register_load_state_dict_pre_hook(replace_and_fail)
+ kwargs = {"keep_ram_copy": True, "shared_store": store, "cache_key": "m"}
+ with pytest.raises(RuntimeError, match="re-point failed after replacement"):
+ if partial:
+ CachedModelWithPartialLoad(incoming, CPU, **kwargs)
+ else:
+ CachedModelOnlyFullLoad(incoming, CPU, total_bytes=canonical_bytes, **kwargs)
+
+ assert store.peek("m") is replacement
+ assert store.refcount("m") == 1
+ assert store.retired_bytes() == canonical_bytes
+ store.release("m", canonical)
+ assert store.retired_bytes() == 0
+ assert store.peek("m") is replacement
+ store.release("m", replacement)
+ assert store.total_bytes_in_use() == 0
diff --git a/tests/backend/model_manager/load/model_cache/test_model_cache_ram_budget.py b/tests/backend/model_manager/load/model_cache/test_model_cache_ram_budget.py
index b18338c52a..22e95a1d3a 100644
--- a/tests/backend/model_manager/load/model_cache/test_model_cache_ram_budget.py
+++ b/tests/backend/model_manager/load/model_cache/test_model_cache_ram_budget.py
@@ -18,6 +18,9 @@ import torch
from invokeai.backend.model_manager.load.load_base import LoadedModelWithoutConfig
from invokeai.backend.model_manager.load.model_cache import model_cache as model_cache_module
from invokeai.backend.model_manager.load.model_cache.cache_stats import CacheStats
+from invokeai.backend.model_manager.load.model_cache.cached_model.cached_model_with_partial_load import (
+ CachedModelWithPartialLoad,
+)
from invokeai.backend.model_manager.load.model_cache.model_cache import (
GB,
MIN_RAM_CACHE_BYTES,
@@ -51,10 +54,10 @@ def _collect_only_this_tests_objects():
gc.unfreeze()
-def _make_cache(store, budget, logger, keep_ram_copy=True) -> ModelCache:
+def _make_cache(store, budget, logger, keep_ram_copy=True, partial=False) -> ModelCache:
return ModelCache(
execution_device_working_mem_gb=1.0,
- enable_partial_loading=False,
+ enable_partial_loading=partial,
keep_ram_copy_of_weights=keep_ram_copy,
execution_device="cpu",
storage_device="cpu",
@@ -102,6 +105,90 @@ def test_shared_model_counts_once_in_global_budget(mock_logger):
cache_b.shutdown()
+def test_matching_put_releases_pin_if_injection_fails_after_peer_eviction(mock_logger, monkeypatch):
+ store = SharedCpuWeightsStore()
+ budget = RamBudget(max_bytes=8 * 8 * 4, shared_store=store)
+ source = _make_cache(store, budget, mock_logger)
+ dest = _make_cache(store, budget, mock_logger)
+ try:
+ source.put("m", torch.nn.Linear(8, 8, bias=False))
+ _use_and_release(source, "m")
+ canonical = store.peek("m")
+ assert canonical is not None
+ adopted = torch.nn.Linear(8, 8, bias=False)
+ adopted.load_state_dict(canonical, assign=True)
+
+ # Even a zero-byte reservation must attempt eviction when the budget is over its cap.
+ budget.add_non_shared(1)
+
+ def fail_injection(model):
+ with pytest.raises(IndexError):
+ source.get("m")
+ assert store.peek("m") is canonical
+ raise RuntimeError("custom-layer injection failed")
+
+ monkeypatch.setattr(model_cache_module, "apply_custom_layers_to_model", fail_injection)
+ with pytest.raises(RuntimeError, match="custom-layer injection failed"):
+ dest.put("m", adopted)
+
+ with pytest.raises(IndexError):
+ dest.get("m")
+ assert store.peek("m") is None
+ assert budget.total_in_use() == 1
+ finally:
+ source.shutdown()
+ dest.shutdown()
+
+
[email protected]("case", ["independent", "fresh_weights", "private_buffer"])
+def test_nonmatching_admission_reserves_full_size(mock_logger, case):
+ store = SharedCpuWeightsStore()
+ budget = RamBudget(max_bytes=356, shared_store=store)
+ source = _make_cache(store, budget, mock_logger)
+ dest = _make_cache(store, budget, mock_logger)
+ try:
+ source.put("m", torch.nn.Linear(8, 8, bias=False))
+ _use_and_release(source, "m")
+ canonical = store.peek("m")
+ assert canonical is not None
+ model = torch.nn.Linear(8, 8, bias=False)
+ if case == "private_buffer":
+ model.load_state_dict(canonical, assign=True)
+ model.register_buffer("private", torch.ones(8), persistent=False)
+ dest.put("other" if case == "independent" else "m", model)
+ with pytest.raises(IndexError):
+ source.get("m")
+ finally:
+ source.shutdown()
+ dest.shutdown()
+ assert store.total_bytes_in_use() == 0
+
+
+def test_partial_loading_matching_admission_keeps_peer(mock_logger, monkeypatch):
+ # Exercise the partial wrapper without selecting an accelerator.
+ monkeypatch.setattr(model_cache_module, "device_has_dedicated_vram", lambda _: True)
+ store = SharedCpuWeightsStore()
+ budget = RamBudget(max_bytes=356, shared_store=store)
+ source = _make_cache(store, budget, mock_logger, partial=True)
+ dest = _make_cache(store, budget, mock_logger, partial=True)
+ try:
+ source.put("m", torch.nn.Linear(8, 8, bias=False))
+ first = _use_and_release(source, "m")
+ canonical = store.peek("m")
+ assert canonical is not None
+ model = torch.nn.Linear(8, 8, bias=False)
+ model.load_state_dict(canonical, assign=True)
+ dest.put("m", model)
+ assert source.get("m") is first
+ assert isinstance(dest.get("m").cached_model, CachedModelWithPartialLoad)
+ assert store.refcount("m") == 2
+ assert budget.total_in_use() == 256
+ finally:
+ source.shutdown()
+ dest.shutdown()
+ assert budget.total_in_use() == 0
+
+
def _collect_until(predicate, attempts: int = 5) -> bool:
"""gc.collect() until predicate() holds - finalizer chains can need more than one pass."""
for _ in range(attempts):
diff --git a/tests/backend/model_manager/load/model_cache/test_shared_cpu_weights.py b/tests/backend/model_manager/load/model_cache/test_shared_cpu_weights.py
index e7d09d8c58..40337c0317 100644
--- a/tests/backend/model_manager/load/model_cache/test_shared_cpu_weights.py
+++ b/tests/backend/model_manager/load/model_cache/test_shared_cpu_weights.py
@@ -12,6 +12,29 @@ def _state_dict() -> dict[str, torch.Tensor]:
}
+def test_admission_pin_survives_peer_release_and_invalidation():
+ store = SharedCpuWeightsStore()
+ canonical = store.acquire("k", _state_dict())
+ adopted = torch.nn.Module()
+ for name, tensor in canonical.items():
+ adopted.register_parameter(name, torch.nn.Parameter(tensor))
+
+ with store.pin_for_admission("k", adopted, 420, None) as matched:
+ assert matched
+ peer = threading.Thread(target=store.release, args=("k", canonical))
+ peer.start()
+ peer.join(timeout=10)
+ assert not peer.is_alive()
+ assert store.refcount("k") == 1
+ assert store.total_bytes_in_use() == 420
+
+ assert store.invalidate("k") == 1
+ assert store.retired_bytes() == 420
+ assert store.total_bytes_in_use() == 0
+ with store.pin_for_admission("k", adopted, 420, None) as matched:
+ assert not matched
+
+
def test_first_acquire_registers_and_returns_same_object():
store = SharedCpuWeightsStore()
sd = _state_dict()
diff --git a/tests/backend/model_manager/load/test_shared_weight_adoption.py b/tests/backend/model_manager/load/test_shared_weight_adoption.py
index 72203b218c..75d12c014d 100644
--- a/tests/backend/model_manager/load/test_shared_weight_adoption.py
+++ b/tests/backend/model_manager/load/test_shared_weight_adoption.py
@@ -8,11 +8,17 @@ so it covers diffusers, single-file checkpoints, GGUF and transformers models al
any registered hooks (e.g. fp8 layerwise-cast hooks).
"""
+import logging
+from types import SimpleNamespace
from unittest.mock import MagicMock
+import pytest
import torch
from invokeai.backend.model_manager.load.load_default import ModelLoader
+from invokeai.backend.model_manager.load.model_cache import model_cache as cache_module
+from invokeai.backend.model_manager.load.model_cache.model_cache import ModelCache
+from invokeai.backend.model_manager.load.model_cache.ram_budget import RamBudget
from invokeai.backend.model_manager.load.model_cache.shared_cpu_weights import SharedCpuWeightsStore
@@ -27,12 +33,11 @@ class _TinyModel(torch.nn.Module):
return self.lin(x) * self.scale
-def _loader_with_store(store: SharedCpuWeightsStore | None) -> ModelLoader:
+def _adopt(store: SharedCpuWeightsStore, key: str):
loader = ModelLoader.__new__(ModelLoader) # bypass __init__ (needs app deps we don't use here)
loader._logger = MagicMock()
- loader._ram_cache = MagicMock()
- loader._ram_cache.shared_cpu_weights = store
- return loader
+ with store.pin_for_adoption(key) as pin:
+ return loader._try_adopt_shared_weights(key, pin) if pin is not None else None
def _populate(store: SharedCpuWeightsStore, key: str, model: torch.nn.Module) -> None:
@@ -92,7 +97,7 @@ def test_adopts_gguf_quantized_weights_and_shares_storage():
store.acquire("g", model.state_dict())
store.set_shell("g", shell)
- adopted = _loader_with_store(store)._try_adopt_shared_weights("g")
+ adopted = _adopt(store, "g")
assert adopted is not None
assert not any(t.is_meta for t in adopted.parameters())
@@ -112,7 +117,7 @@ def test_adopts_canonical_weights_without_copying():
canonical = store.peek("m")
refcount_before = store.refcount("m")
- model = _loader_with_store(store)._try_adopt_shared_weights("m")
+ model = _adopt(store, "m")
assert model is not None
# The adopted params ARE the canonical tensors (assign=True, no copy) -> no extra RAM.
@@ -120,7 +125,7 @@ def test_adopts_canonical_weights_without_copying():
assert model.lin.bias.data_ptr() == canonical["lin.bias"].data_ptr()
assert not any(t.is_meta for t in model.parameters())
assert not any(t.is_meta for t in model.buffers())
- # peek()/get_shell() must not have taken a reference -- the wrapper's acquire() does that later.
+ # The temporary pin is gone after leaving its scope.
assert store.refcount("m") == refcount_before
@@ -130,7 +135,7 @@ def test_adopted_model_produces_correct_output():
_populate(store, "m", source)
x = torch.randn(3, 4)
- model = _loader_with_store(store)._try_adopt_shared_weights("m")
+ model = _adopt(store, "m")
assert torch.allclose(model(x), source(x), atol=1e-6)
@@ -143,7 +148,7 @@ def test_adoption_preserves_forward_hooks():
source.lin.register_forward_pre_hook(lambda mod, args: fired.append("pre"))
_populate(store, "m", source)
- model = _loader_with_store(store)._try_adopt_shared_weights("m")
+ model = _adopt(store, "m")
model(torch.randn(1, 4))
assert fired == ["pre"] # the cloned module's hook fired
@@ -153,15 +158,11 @@ def test_no_shell_means_no_adoption():
# Canonical present but no shell registered (e.g. first device couldn't clone) -> fall back.
store = SharedCpuWeightsStore()
store.acquire("m", _TinyModel().state_dict())
- assert _loader_with_store(store)._try_adopt_shared_weights("m") is None
+ assert _adopt(store, "m") is None
def test_absent_key_means_no_adoption():
- assert _loader_with_store(SharedCpuWeightsStore())._try_adopt_shared_weights("missing") is None
-
-
-def test_no_shared_store_means_no_adoption():
- assert _loader_with_store(None)._try_adopt_shared_weights("m") is None
+ assert _adopt(SharedCpuWeightsStore(), "missing") is None
def test_mismatched_canonical_falls_back_safely():
@@ -174,9 +175,8 @@ def test_mismatched_canonical_falls_back_safely():
store.acquire("m", {"unexpected.key": torch.zeros(2)}) # wrong state dict
store.set_shell("m", shell)
- loader = _loader_with_store(store)
- assert loader._try_adopt_shared_weights("m") is None
- loader._logger.warning.assert_called_once()
+ assert _adopt(store, "m") is None
+ assert store.refcount("m") == 1
def test_shell_dropped_when_entry_released():
@@ -186,3 +186,189 @@ def test_shell_dropped_when_entry_released():
store.release("m") # last reference -> entry (and its shell) gone
assert store.get_shell("m") is None
assert "m" not in store
+
+
+class _AdmissionModel(torch.nn.Module):
+ def __init__(self, layout):
+ super().__init__()
+ self.proj = torch.nn.Linear(8, 8, bias=False)
+ if layout == "private":
+ self.register_buffer("private", torch.ones(8), persistent=False)
+ if layout == "tied":
+ self.head = torch.nn.Linear(8, 8, bias=False)
+ self.head.weight = self.proj.weight
+
+
+class _FileLoader(ModelLoader):
+ def __init__(self, cache, path, layout):
+ self._ram_cache = cache
+ self._logger = logging.getLogger(__name__)
+ self._app_config = SimpleNamespace(log_memory_usage=False, models_path=path.parent)
+ self.layout = layout
+ self.disk_loads = 0
+
+ def _load_model(self, config, submodel_type=None):
+ self.disk_loads += 1
+ model = _AdmissionModel(self.layout)
+ model.load_state_dict(torch.load(config.path, weights_only=True))
+ return model
+
+
+def adoption_pair(tmp_path):
+ caches = []
+
+ def create(*, layout="dense", keep_copy=True, cap=10**12):
+ path = tmp_path / "tiny.pt"
+ torch.save(_AdmissionModel(layout).state_dict(), path)
+ store = SharedCpuWeightsStore()
+ budget = RamBudget(max_bytes=cap, shared_store=store)
+ for keep in (True, keep_copy):
+ caches.append(
+ ModelCache(
+ execution_device_working_mem_gb=1,
+ enable_partial_loading=False,
+ keep_ram_copy_of_weights=keep,
+ execution_device="cpu",
+ storage_device="cpu",
+ logger=logging.getLogger(__name__),
+ shared_cpu_weights=store,
+ ram_budget=budget,
+ )
+ )
+ source, dest = (_FileLoader(cache, path, layout) for cache in caches)
+ config = SimpleNamespace(key="encoder", path=str(path), name="encoder", base="any", type="test")
+ first, claim = source._load_and_cache(config)
+ assert claim is not None
+ claim.release()
+ caches[0].lock(first, None)
+ caches[0].unlock(first)
+ return source, dest, config, store, budget
+
+ yield create
+ for cache in caches:
+ cache.shutdown()
+
+
+def test_adoption_keeps_peer_cached_and_avoids_reload(adoption_pair):
+ source, dest, config, store, budget = adoption_pair(cap=356)
+ first = source._ram_cache.get(config.key)
+ canonical = store.peek(config.key)
+ record, claim = dest._load_and_cache(config)
+ assert claim is not None
+ claim.release()
+ dest._ram_cache.lock(record, None)
+ dest._ram_cache.unlock(record)
+ first_again, claim = source._load_and_cache(config)
+ if claim is not None:
+ claim.release()
+ assert first_again is first
+ assert source.disk_loads == 1 and dest.disk_loads == 0
+ assert record.cached_model.get_cpu_state_dict() is canonical
+ assert store.refcount(config.key) == 2
+ assert budget.total_in_use() == 256
+
+
+def test_failed_clone_releases_pin_and_loads_from_disk(adoption_pair, monkeypatch):
+ source, dest, config, store, _ = adoption_pair()
+ canonical = store.peek(config.key)
+ assert canonical is not None
+
+ def fail_clone(self, memo):
+ raise RuntimeError("cannot copy shell")
+
+ monkeypatch.setattr(_AdmissionModel, "__deepcopy__", fail_clone, raising=False)
+ record, claim = dest._load_and_cache(config)
+ assert claim is not None
+ claim.release()
+ assert source.disk_loads == 1 and dest.disk_loads == 1
+ assert record.cached_model.get_cpu_state_dict() is canonical
+ assert store.refcount(config.key) == 2
+
+
+ ("layout", "policy", "reservation"),
+ [("private", "keep", 288), ("tied", "keep", 512), ("dense", "no_copy", 256), ("dense", "integrated_xpu", 256)],
+)
+def test_full_reservation_can_evict_source_without_evicting_warm_peer(
+ adoption_pair, monkeypatch, layout, policy, reservation
+):
+ warm_bytes = 256
+ source, dest, config, store, budget = adoption_pair(
+ layout=layout, keep_copy=policy != "no_copy", cap=reservation + warm_bytes
+ )
+ if policy == "integrated_xpu":
+ # Exercise the integrated-device RAM-copy override without selecting an accelerator.
+ dest_device = dest._ram_cache._execution_device
+ monkeypatch.setattr(cache_module, "_is_integrated_xpu", lambda device: device is dest_device)
+ warm_key = "warm"
+ source._ram_cache.put(warm_key, torch.nn.Linear(8, 8, bias=False))
+ warm = source._ram_cache.get(warm_key)
+ source._ram_cache.lock(warm, None)
+ source._ram_cache.unlock(warm)
+ canonical = store.peek(config.key)
+ assert canonical is not None
+ assert store.get_shell(config.key) is not None
+
+ record, claim = dest._load_and_cache(config)
+ assert claim is not None
+ claim.release()
+ assert dest.disk_loads == 0
+ assert source._ram_cache.get(warm_key) is warm
+ with pytest.raises(IndexError):
+ source._ram_cache.get(config.key)
+ assert torch.equal(record.cached_model.model.proj.weight, canonical["proj.weight"])
+ if policy == "keep":
+ # Full reservation can evict the original entry. The adopted model is then registered
+ # without a shell, as it was before the adoption pin was introduced.
+ current = store.peek(config.key)
+ assert current is not None and current is not canonical
+ assert record.cached_model.get_cpu_state_dict() is current
+ else:
+ assert record.cached_model.get_cpu_state_dict() is None
+ assert store.peek(config.key) is None
+ assert store.get_shell(config.key) is None
+ assert budget.total_in_use() <= budget.max_bytes
+
+
[email protected]("fail_make_room", [False, True])
+def test_matching_loader_pins_canonical_until_admission(adoption_pair, monkeypatch, fail_make_room):
+ source, dest, config, store, budget = adoption_pair()
+ key = config.key
+ canonical, shell = store.peek(key), store.get_shell(key)
+ assert canonical is not None and shell is not None
+
+ def evict_last_peer():
+ assert source._ram_cache.evict_unlocked_for_peer(lambda: False) == 1
+ assert store.peek(key) is canonical
+ assert store.get_shell(key) is shell
+
+ if fail_make_room:
+
+ def fail_reservation(size):
+ assert size == 0
+ evict_last_peer()
+ raise RuntimeError("cache reservation failed")
+
+ monkeypatch.setattr(dest._ram_cache, "_make_room_internal", fail_reservation)
+ with pytest.raises(RuntimeError, match="cache reservation failed"):
+ dest._load_and_cache(config)
+ with pytest.raises(IndexError):
+ dest._ram_cache.get(key)
+ assert store.peek(key) is None
+ assert budget.total_in_use() == 0
+ else:
+ original_put = dest._ram_cache.put
+
+ def evict_before_put(*args, **kwargs):
+ evict_last_peer()
+ return original_put(*args, **kwargs)
+
+ monkeypatch.setattr(dest._ram_cache, "put", evict_before_put)
+ record, claim = dest._load_and_cache(config)
+ assert claim is not None
+ claim.release()
+ assert dest.disk_loads == 0
+ assert record.cached_model.get_cpu_state_dict() is canonical
+ assert store.get_shell(key) is shell
+ assert store.refcount(key) == 1