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.

refactor(model-manager): expose a loaded model's size and residency

Alexander Eichhornc08dd8e65ce2
diff --git a/invokeai/app/invocations/wan/wan_denoise.py b/invokeai/app/invocations/wan/wan_denoise.py
index a7336ede9e..85e7e0c2fe 100644
--- a/invokeai/app/invocations/wan/wan_denoise.py
+++ b/invokeai/app/invocations/wan/wan_denoise.py
@@ -44,7 +44,6 @@ from invokeai.app.invocations.fields import (
from invokeai.app.invocations.model import LoRAField, WanTransformerField
from invokeai.app.invocations.primitives import LatentsOutput
from invokeai.app.services.shared.invocation_context import InvocationContext
-from invokeai.backend.model_manager.load.model_cache.model_cache import MODEL_LOAD_LOCK
from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelFormat, WanVariantType
from invokeai.backend.patches.layer_patcher import LayerPatcher, PatchSpec
from invokeai.backend.patches.lora_conversions.wan_lora_constants import WAN_LORA_TRANSFORMER_PREFIX
@@ -219,16 +218,10 @@ class _ExpertSwapper:
assert self._active_model is not None
return self._active_model
- # Capture the outgoing expert's cache record before _release() drops our handle.
- # We need it to force-unload below.
- outgoing_cached_model = None
+ # Capture the outgoing expert's size before _release() drops our handle; it is what the
+ # force-unload below asks for.
outgoing_info = self._active_info
- if self._active_info is not None:
- # ``LoadedModel`` keeps the cache record private, but exposes
- # ``unload_from_vram`` so cache error handling stays in one place.
- outgoing_cached_model = getattr(self._active_info, "_cache_record", None)
- if outgoing_cached_model is not None:
- outgoing_cached_model = getattr(outgoing_cached_model, "cached_model", None)
+ outgoing_bytes = 0 if outgoing_info is None else outgoing_info.weight_bytes
# Release current GPU residency before bringing the other expert on device.
self._release()
@@ -245,16 +238,9 @@ class _ExpertSwapper:
# Sidestep the heuristic by explicitly unloading every weight of the outgoing
# expert to RAM. This is safe even if the cache evicted the entry between unlock
# and now — the cached_model object still owns the tensors.
- if outgoing_cached_model is not None:
+ if outgoing_info is not None:
try:
- unload_from_vram = getattr(outgoing_info, "unload_from_vram", None)
- if callable(unload_from_vram):
- unload_from_vram(outgoing_cached_model.total_bytes())
- else:
- # Keep compatibility with old LoadedModel handles while preserving
- # the process-global register_parameter guard.
- with MODEL_LOAD_LOCK.read_lock():
- outgoing_cached_model.full_unload_from_vram()
+ outgoing_info.unload_from_vram(outgoing_bytes)
except Exception:
pass
@@ -294,15 +280,10 @@ class _ExpertSwapper:
)
self._warned_partial_loading_unavailable = True
else:
- cache_record = getattr(info, "_cache_record", None)
- cached_model = getattr(cache_record, "cached_model", None)
- cur_vram_bytes = getattr(cached_model, "cur_vram_bytes", None)
- unload_from_vram = getattr(info, "unload_from_vram", None)
- if callable(cur_vram_bytes) and callable(unload_from_vram):
- vram_bytes_to_free = max(0, cur_vram_bytes() - self._max_resident_model_bytes)
- if vram_bytes_to_free > 0:
- unload_from_vram(vram_bytes_to_free, keep_required_weights_in_vram=True)
- TorchDevice.empty_cache()
+ vram_bytes_to_free = max(0, info.resident_weight_bytes - self._max_resident_model_bytes)
+ if vram_bytes_to_free > 0:
+ info.unload_from_vram(vram_bytes_to_free, keep_required_weights_in_vram=True)
+ TorchDevice.empty_cache()
# Apply LoRA patches for this expert. GGUF transformers need sidecar
# patching since direct patching of GGMLTensors isn't supported.
diff --git a/invokeai/backend/model_manager/load/load_base.py b/invokeai/backend/model_manager/load/load_base.py
index cc2d9bbd41..cd5623c0f5 100644
--- a/invokeai/backend/model_manager/load/load_base.py
+++ b/invokeai/backend/model_manager/load/load_base.py
@@ -241,6 +241,22 @@ class LoadedModelWithoutConfig:
"""Whether this model can stream individual weights between RAM and the compute device."""
return isinstance(self._cache_record.cached_model, CachedModelWithPartialLoad)
+ @property
+ def weight_bytes(self) -> int:
+ """Total size of this model's weights, resident or not."""
+ return self._cache_record.cached_model.total_bytes()
+
+ @property
+ def resident_weight_bytes(self) -> int:
+ """How many of this model's weight bytes currently sit on the compute device.
+
+ A caller that has to bound its own residency — because it holds a second model of the same
+ size at the same time — needs this to size its `unload_from_vram` request. Exposed here so
+ such a caller does not have to reach through `_cache_record.cached_model`, whose lifetime
+ the cache owns.
+ """
+ return self._cache_record.cached_model.cur_vram_bytes()
+
def repair_required_tensors_on_device(self) -> int:
"""Repair required tensors that should be resident on the cached model's execution device."""
cached_model = self._cache_record.cached_model
diff --git a/tests/app/invocations/test_wan_denoise.py b/tests/app/invocations/test_wan_denoise.py
index f189e8900a..9dbaef7f79 100644
--- a/tests/app/invocations/test_wan_denoise.py
+++ b/tests/app/invocations/test_wan_denoise.py
@@ -284,9 +284,10 @@ class TestWanDenoiseShapes:
transformer = _ZeroTransformer()
loaded = MagicMock()
loaded.supports_partial_loading = True
- cached_model = MagicMock()
- cached_model.cur_vram_bytes.return_value = 5 * 2**30
- loaded._cache_record.cached_model = cached_model
+ # `LoadedModel` exposes residency as a property, so a MagicMock must be given a real int
+ # here or the swapper's arithmetic compares against a mock.
+ loaded.resident_weight_bytes = 5 * 2**30
+ loaded.weight_bytes = 14 * 2**30
device_context = MagicMock()
device_context.__enter__.return_value = (None, transformer)
loaded.model_on_device.return_value = device_context
@@ -314,7 +315,7 @@ class TestWanDenoiseShapes:
transformer = _ZeroTransformer()
loaded = MagicMock()
loaded.supports_partial_loading = True
- loaded._cache_record.cached_model.cur_vram_bytes.return_value = 2 * 2**30
+ loaded.resident_weight_bytes = 2 * 2**30
device_context = MagicMock()
device_context.__enter__.return_value = (None, transformer)
loaded.model_on_device.return_value = device_context
@@ -342,7 +343,7 @@ class TestWanDenoiseShapes:
transformer = _ZeroTransformer()
loaded = MagicMock()
loaded.supports_partial_loading = False
- loaded._cache_record.cached_model.cur_vram_bytes.return_value = 5 * 2**30
+ loaded.resident_weight_bytes = 5 * 2**30
device_context = MagicMock()
device_context.__enter__.return_value = (None, transformer)
loaded.model_on_device.return_value = device_context
diff --git a/tests/app/invocations/test_wan_expert_swapper.py b/tests/app/invocations/test_wan_expert_swapper.py
index 9c8ed67ee7..140fbff79b 100644
--- a/tests/app/invocations/test_wan_expert_swapper.py
+++ b/tests/app/invocations/test_wan_expert_swapper.py
@@ -68,14 +68,17 @@ class _FakeCacheRecord:
class _FakeInfo:
- """Mirrors the runtime ``LoadedModel`` enough for the swapper to reach
- ``info._cache_record.cached_model.full_unload_from_vram()`` on swap."""
+ """Mirrors the runtime ``LoadedModel`` enough for the swapper to force the outgoing expert off
+ the device on swap. ``weight_bytes`` and ``resident_weight_bytes`` are the public properties the
+ swapper sizes its unload request from."""
def __init__(self, label: str, model: nn.Module, log: list[str]) -> None:
self._label = label
self._model = model
self._log = log
self._cache_record = _FakeCacheRecord(_FakeCachedModel(label, log))
+ self.weight_bytes = 0
+ self.resident_weight_bytes = 0
def model_on_device(self):
return _FakeModelOnDevice(self._label, self._model, self._log)
diff --git a/tests/backend/model_manager/load/model_cache/test_loaded_model_size_accessors.py b/tests/backend/model_manager/load/model_cache/test_loaded_model_size_accessors.py
new file mode 100644
index 0000000000..e5277c8aaf
--- /dev/null
+++ b/tests/backend/model_manager/load/model_cache/test_loaded_model_size_accessors.py
@@ -0,0 +1,99 @@
+"""`LoadedModel.weight_bytes` and `.resident_weight_bytes` against a real cache.
+
+A caller that holds two large models at once has to bound its own residency, and to size that
+request it needs both numbers: how big the model is, and how much of it is currently on the compute
+device. `Ideogram4DenoiseInvocation` is the first such caller; `wan_denoise.py` does the same thing
+by reaching through `_cache_record.cached_model` to `total_bytes()` / `cur_vram_bytes()`.
+
+These cells exist because that reach-through is what the properties wrap. Their node-level tests
+use a hand-written `LoadedModel` fake with its own attributes, so renaming either cache method
+would leave those green and fail at runtime — after both multi-GiB branches are already locked. The
+two cached-model kinds answer differently and are covered separately: a CPU execution device yields
+`CachedModelOnlyFullLoad`, which is all-or-nothing, while a CUDA one yields
+`CachedModelWithPartialLoad`, where residency is the point.
+"""
+
+import logging
+from unittest.mock import MagicMock
+
+import pytest
+import torch
+
+from invokeai.backend.model_manager.load.load_base import LoadedModelWithoutConfig
+from invokeai.backend.model_manager.load.model_cache.model_cache import ModelCache
+
+MB = 1024**2
+
+requires_cuda = pytest.mark.skipif(not torch.cuda.is_available(), reason="Requires CUDA.")
+
+
+def _module_bytes(module: torch.nn.Module) -> int:
+ return sum(t.numel() * t.element_size() for t in list(module.parameters()) + list(module.buffers()))
+
+
+def _cache(execution_device: str) -> ModelCache:
+ logger = MagicMock()
+ logger.getEffectiveLevel.return_value = logging.INFO
+ return ModelCache(
+ execution_device_working_mem_gb=0.1,
+ enable_partial_loading=True,
+ keep_ram_copy_of_weights=True,
+ execution_device=execution_device,
+ storage_device="cpu",
+ logger=logger,
+ )
+
+
+def _wrap(cache: ModelCache, module: torch.nn.Module) -> LoadedModelWithoutConfig:
+ cache.put("model", module)
+ return LoadedModelWithoutConfig(cache.get("model"), cache)
+
+
+def test_weight_bytes_reports_the_models_own_size() -> None:
+ """The size is what the caller compares against the device's capacity, so it must be the
+ model's bytes and not the cache's or the record's."""
+ cache = _cache("cpu")
+ try:
+ module = torch.nn.Linear(256, 256)
+ assert _wrap(cache, module).weight_bytes == _module_bytes(module)
+ finally:
+ cache.shutdown()
+
+
+def test_an_unloaded_model_reports_no_residency() -> None:
+ """A model the cache holds only in RAM has nothing on the compute device. A caller sizing an
+ unload from this would otherwise ask the cache to free bytes that are not there."""
+ cache = _cache("cpu")
+ try:
+ loaded = _wrap(cache, torch.nn.Linear(256, 256))
+ assert loaded.resident_weight_bytes == 0
+ assert loaded.weight_bytes > 0
+ finally:
+ cache.shutdown()
+
+
+@requires_cuda
+def test_residency_follows_an_unload_while_the_size_does_not() -> None:
+ """The two numbers move independently, which is the whole reason both exist.
+
+ A caller reading size where it means residency would keep asking for an unload that already
+ happened; reading residency where it means size would under-read a model that is only partly
+ loaded and conclude the device has room it does not have.
+ """
+ cache = _cache("cuda:0")
+ try:
+ module = torch.nn.Linear(2048, 2048)
+ loaded = _wrap(cache, module)
+ size = loaded.weight_bytes
+ assert size == _module_bytes(module)
+
+ with loaded.model_on_device():
+ assert loaded.resident_weight_bytes > 0
+ resident_before = loaded.resident_weight_bytes
+
+ loaded.unload_from_vram(resident_before // 2)
+
+ assert loaded.resident_weight_bytes < resident_before
+ assert loaded.weight_bytes == size
+ finally:
+ cache.shutdown()