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.

17.2 KB
Raw Blame
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, storage_key


@dataclass(eq=False)
class _SharedWeightsEntry:
    """A single canonical CPU state dict shared across per-device caches."""

    state_dict: dict[str, torch.Tensor]
    total_bytes: int
    # Number of per-device cached models currently aliasing this entry. The entry is freed
    # (its RAM released) when this drops to zero.
    refcount: int = 0
    # An empty (meta-weight) structural clone of the first-built module, used so a second device can
    # adopt the canonical weights without re-reading the model from disk. None until registered (and
    # for entries whose model isn't an nn.Module). Holds ~no real RAM: its weights are on `meta`.
    shell: object | None = None
    _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.

    In multi-GPU mode there is one `ModelCache` per generation device. Without coordination each
    cache keeps its own CPU copy of every model's weights, so a model loaded on N GPUs occupies N
    copies in RAM. The cached-model wrappers cannot simply share a single `torch.nn.Module`, because
    loading to VRAM mutates a module's parameters in place (`load_state_dict(assign=True)` / `.to`),
    and two GPUs running the same model concurrently need their params on two different devices at
    once. The CPU weight tensors, however, are read-only and device-agnostic, so they can be shared.

    This store keeps a single canonical CPU `state_dict` per cache key. The first device to load a
    key registers its freshly-built state dict as canonical; subsequent devices `acquire()` the
    canonical and re-point their own module's CPU parameters at the shared tensors (via
    `load_state_dict(assign=True)`), discarding their private duplicate. The result: model weights
    live once in RAM regardless of how many GPUs hold the model.

    Lifetime is reference-counted. Each per-device cached model that adopts an entry must call
    `release()` exactly once when it is evicted; the canonical tensors are dropped only when the
    last device releases them.

    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. 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:
        self._lock = threading.Lock()
        # Releases posted from GC context (a cached-model wrapper's weakref.finalize when its cache
        # was dropped without shutdown()/clear()). A finalizer must not take self._lock: it can run
        # at any allocation point on any thread — including inside acquire()'s critical section,
        # where taking this non-reentrant lock again would self-deadlock the process (see
        # ModelCache.release_first_use_grace for the same constraint). SimpleQueue.put is
        # lock-free/reentrant, so finalizers only enqueue; every public method drains the queue
        # under the lock before doing its own work.
        self._deferred_releases: queue.SimpleQueue[tuple[str, dict[str, torch.Tensor] | None]] = queue.SimpleQueue()
        self._entries: dict[str, _SharedWeightsEntry] = {}
        # Entries forgotten by `invalidate()` while still referenced by live cached models (e.g. a
        # locked, stale-marked cache entry mid-generation). They can no longer be acquired or peeked,
        # but their tensors are still resident, so `total_bytes_in_use()` keeps counting them until
        # every holder calls `release()`. Matched by state-dict identity, not key: a replacement
        # canonical may exist under the same key at the same time.
        self._retired: list[_SharedWeightsEntry] = []
        # Whether to capture per-model meta-weight shells for cross-device adoption. Only useful with
        # more than one device cache, so the model manager disables it in single-device setups to
        # avoid the (small) per-first-load clone cost. See ModelLoader._build_meta_shell.
        self.enable_shell_capture: bool = True

    def acquire(self, key: str, state_dict: dict[str, torch.Tensor]) -> dict[str, torch.Tensor]:
        """Adopt the canonical CPU state dict for `key`, registering `state_dict` as canonical if
        this is the first acquire.

        Increments the entry's refcount. The caller MUST pair every `acquire()` with exactly one
        `release()`.

        Returns:
            The canonical state dict. If this call registered the entry, the returned object is the
            same `state_dict` that was passed in (the caller keeps using its own tensors). Otherwise
            it is the previously-registered canonical dict, and the caller is responsible for
            re-pointing its module at these tensors and dropping the `state_dict` it passed in.
        """
        with self._lock:
            self._drain_deferred_locked()
            entry = self._entries.get(key)
            if entry is None:
                entry = _SharedWeightsEntry(
                    state_dict=state_dict,
                    # Tied weights appear under several keys; charging each name would count that memory twice.
                    total_bytes=sum(analyze_state_dict(state_dict).bytes_by_key.values()),
                )
                self._entries[key] = entry
            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.

        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)."""
        with self._lock:
            self._drain_deferred_locked()
            entry = self._entries.get(key)
            if entry is not None and entry.shell is None:
                entry.shell = shell

    def get_shell(self, key: str) -> object | None:
        """Return the registered meta-weight shell for `key`, or None if absent."""
        with self._lock:
            self._drain_deferred_locked()
            entry = self._entries.get(key)
            return entry.shell if entry is not None else None

    def release(self, key: str, state_dict: dict[str, torch.Tensor] | None = None) -> None:
        """Release one reference to `key`'s canonical state dict, freeing it when the count hits 0.

        A `release()` for a key that is not present is a no-op (e.g. a cached model that never
        acquired shared weights, or a double eviction guard).

        When `state_dict` is given, the release only applies if it is the *same object* as the
        current canonical. This protects against a holder of an `invalidate()`d entry releasing
        after a new canonical has been registered under the same key: without the identity check,
        that stale release would decrement the new entry's refcount and could free weights still
        aliased by live cached models. Such a release instead matches the retired entry (by
        state-dict identity), decrementing it so its bytes stop being counted once the last holder
        lets go.
        """
        with self._lock:
            self._drain_deferred_locked()
            self._release_locked(key, state_dict)

    def release_deferred(self, key: str, state_dict: dict[str, torch.Tensor] | None = None) -> None:
        """Post a release to be applied by the next store operation, WITHOUT taking the store lock.

        This is the only release entry point that is safe from GC context (weakref.finalize
        callbacks, __del__): it only enqueues. A finalizer can fire at any allocation point on any
        thread — including while that same thread holds self._lock inside acquire() — so taking the
        non-reentrant lock here could self-deadlock the process. Every public method drains the
        queue under the lock, so the released bytes disappear from the accounting no later than the
        next store operation (in particular, the next `total_bytes_in_use()` / budget query).
        """
        self._deferred_releases.put((key, state_dict))

    def _drain_deferred_locked(self) -> None:
        """Apply all pending deferred releases. Caller must hold self._lock."""
        while True:
            try:
                key, state_dict = self._deferred_releases.get_nowait()
            except queue.Empty:
                return
            self._release_locked(key, state_dict)

    def _release_locked(self, key: str, state_dict: dict[str, torch.Tensor] | None) -> None:
        """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):
            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 retired in self._retired:
                if retired.state_dict is state_dict:
                    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.

        Used when a load-affecting model setting changes: the canonical weights were built under the
        old settings and must not be re-adopted by any device's next load, even while a locked (in
        use, marked-stale) cache entry still aliases them. The forgotten tensors stay alive through
        the cached models that hold them and are garbage-collected as those are evicted. Entries
        that are still referenced are moved to a retired list so `total_bytes_in_use()` keeps
        counting them — if a replacement is registered before the stale holders unlock, both copies
        really are resident, and the RAM budget must see both. Each holder's later `release()`
        matches the retired entry by state-dict identity and frees its accounting (see `release()`).
        """
        prefix = f"{model_key}:"
        with self._lock:
            self._drain_deferred_locked()
            doomed = [key for key in self._entries if key == model_key or key.startswith(prefix)]
            for key in doomed:
                entry = self._entries.pop(key)
                if entry.refcount > 0:
                    self._retired.append(entry)
            return len(doomed)

    # -- Introspection / accounting (also used by tests) ----------------------------------------

    def __contains__(self, key: str) -> bool:
        with self._lock:
            self._drain_deferred_locked()
            return key in self._entries

    def refcount(self, key: str) -> int:
        """Return the current refcount for `key`, or 0 if not present."""
        with self._lock:
            self._drain_deferred_locked()
            entry = self._entries.get(key)
            return entry.refcount if entry is not None else 0

    def total_bytes_in_use(self) -> int:
        """Return the total size (in bytes) of all canonical state dicts currently held, including
        retired (invalidated but still referenced) entries whose tensors remain resident.

        This counts each shared model's weights exactly once, regardless of how many devices alias
        it — i.e. the true RAM footprint of cached weights, not the per-device double-count.
        """
        with self._lock:
            self._drain_deferred_locked()
            return sum(entry.total_bytes for entry in self._entries.values()) + sum(
                entry.total_bytes for entry in self._retired
            )

    def retired_bytes(self) -> int:
        """Return the total size (in bytes) of retired (invalidated but still referenced) entries."""
        with self._lock:
            self._drain_deferred_locked()
            return sum(entry.total_bytes for entry in self._retired)

    def keys(self) -> list[str]:
        with self._lock:
            self._drain_deferred_locked()
            return list(self._entries.keys())


# Process-global default store. Per-device caches share this instance so that the same model loaded
# on multiple GPUs keeps a single CPU copy. Tests may construct isolated `SharedCpuWeightsStore`
# instances instead.
SHARED_CPU_WEIGHTS = SharedCpuWeightsStore()