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(app): guard model offloads during construction (#10218)

Nianze Wu6ff09b143292
diff --git a/docs/src/generated/invocation-context.json b/docs/src/generated/invocation-context.json
index 5178ac3c05..9132819aed 100644
--- a/docs/src/generated/invocation-context.json
+++ b/docs/src/generated/invocation-context.json
@@ -344,7 +344,7 @@
"signature": "(source: str | AnyHttpUrl, loader: Optional[Callable[[Path], AnyModel]] = None) -> LoadedModelWithoutConfig"
},
{
- "description": "Offload unlocked cached models from VRAM until `vram_bytes_needed` bytes are free on this thread's\nexecution device.\nUse this before placing a model on the GPU *outside* the model cache (e.g. a BitsAndBytes-quantized model\nthat cannot be moved between devices). Loads that go through `load()` never need this - the cache makes room\nfor them itself when they are locked - but an out-of-cache load competes with the cached models for VRAM\nand would otherwise only get whatever they happened to leave free. The configured working-memory reserve\nis kept free on top of the request.",
+ "description": "Offload unlocked cached models from VRAM until `vram_bytes_needed` bytes are free on this thread's\nexecution device.\nUse this before placing a model on the GPU *outside* the model cache (e.g. a BitsAndBytes-quantized model\nthat cannot be moved between devices). Loads that go through `load()` never need this - the cache makes room\nfor them itself when they are locked - but an out-of-cache load competes with the cached models for VRAM\nand would otherwise only get whatever they happened to leave free. The configured working-memory reserve\nis kept free on top of the request.\nThe caller must not hold `MODEL_LOAD_LOCK`; this method acquires its read lock.",
"name": "make_room_in_vram",
"parameters": [
{
@@ -359,7 +359,7 @@
"signature": "(vram_bytes_needed: int) -> int"
},
{
- "description": "Move a model (and all of its submodels) from VRAM to RAM, freeing its VRAM but keeping it cached.\nUse this when an invocation is done with a model for the rest of the run - e.g. a one-shot text encoder -\nso the next, larger load does not have to compete with it for VRAM. The model stays in the RAM cache, so\na subsequent load only re-streams it back to VRAM rather than rebuilding it from disk.",
+ "description": "Move a model (and all of its submodels) from VRAM to RAM, freeing its VRAM but keeping it cached.\nUse this when an invocation is done with a model for the rest of the run - e.g. a one-shot text encoder -\nso the next, larger load does not have to compete with it for VRAM. The model stays in the RAM cache, so\na subsequent load only re-streams it back to VRAM rather than rebuilding it from disk.\nThe caller must not hold `MODEL_LOAD_LOCK`; this method acquires its read lock.",
"name": "offload_from_vram",
"parameters": [
{
diff --git a/invokeai/app/invocations/text_encoder/qwen_image_text_encoder.py b/invokeai/app/invocations/text_encoder/qwen_image_text_encoder.py
index 9c20a8b2a5..0202c83e36 100644
--- a/invokeai/app/invocations/text_encoder/qwen_image_text_encoder.py
+++ b/invokeai/app/invocations/text_encoder/qwen_image_text_encoder.py
@@ -525,7 +525,7 @@ class QwenImageTextEncoderInvocation(BaseInvocation):
# lock is held no longer than necessary - while a writer holds it, or waits for it, every VRAM move on every
# worker stalls, and every reader delays every cold model construction:
# 1. the offload is a VRAM move like any other (`load_state_dict(assign=True)` -> `register_parameter`), so it
- # takes the read lock, acquired *before* the cache lock `make_room_in_vram` takes, per the lock-ordering
+ # takes the read lock inside `make_room_in_vram`, before its cache lock, per the lock-ordering
# contract;
# 2. the checkpoint read takes no lock: it creates no parameters and touches no global state, and it is the
# slow part on anything but NVMe. It runs after the offload so the offload's RAM cannot evict its pages;
@@ -544,8 +544,7 @@ class QwenImageTextEncoderInvocation(BaseInvocation):
try:
# A CPU execution device has no VRAM to make room in (recent bitsandbytes can quantize on the CPU).
if quantized_bytes > 0 and device.type != "cpu":
- with MODEL_LOAD_LOCK.read_lock():
- vram_available = context.models.make_room_in_vram(quantized_bytes)
+ vram_available = context.models.make_room_in_vram(quantized_bytes)
if vram_available < quantized_bytes:
context.logger.warning(
f"Only {max(vram_available, 0) / MB:.0f} MB of VRAM could be made available on {device} for "
diff --git a/invokeai/app/services/session_processor/architecture_switch.py b/invokeai/app/services/session_processor/architecture_switch.py
index eaae175849..9254846acf 100644
--- a/invokeai/app/services/session_processor/architecture_switch.py
+++ b/invokeai/app/services/session_processor/architecture_switch.py
@@ -19,7 +19,7 @@ from pydantic import BaseModel
from invokeai.app.invocations.model import ModelIdentifierField
from invokeai.app.services.shared.graph_validation import Graph
-from invokeai.backend.model_manager.load.model_cache.model_cache import ModelCache
+from invokeai.backend.model_manager.load.model_cache.model_cache import MODEL_LOAD_LOCK, ModelCache
from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelType
from invokeai.backend.util.logging import InvokeAILogger
@@ -64,7 +64,8 @@ class ArchitectureSwitchOffload:
previous, self._last_bases = self._last_bases, bases
if previous is None or bases == previous:
return 0
- freed = cache.offload_models_from_vram_except({model.key for model in models})
+ with MODEL_LOAD_LOCK.read_lock():
+ freed = cache.offload_models_from_vram_except({model.key for model in models})
if freed > 0:
InvokeAILogger.get_logger(__name__).info(
f"Switched from {_names(previous)} to {_names(bases)} models on {cache.execution_device}: moved "
diff --git a/invokeai/app/services/session_processor/session_processor_default.py b/invokeai/app/services/session_processor/session_processor_default.py
index ee56ff56cc..b3c7aead40 100644
--- a/invokeai/app/services/session_processor/session_processor_default.py
+++ b/invokeai/app/services/session_processor/session_processor_default.py
@@ -50,6 +50,7 @@ from invokeai.app.services.shared.invocation_context import InvocationContextDat
from invokeai.app.services.working_memory_calibration.working_memory_calibration_common import calibration_run_id
from invokeai.app.util.profiler import Profiler
from invokeai.app.util.startup_utils import log_attention_backends
+from invokeai.backend.model_manager.load.model_cache.model_cache import MODEL_LOAD_LOCK
from invokeai.backend.util.attention import attention_caller
from invokeai.backend.util.device_pool import (
GENERATION_DEVICE_POOL,
@@ -1248,7 +1249,8 @@ class DefaultSessionProcessor(SessionProcessorBase):
try:
services = self._invoker.services
if services.configuration.clear_vram_after_session and services.model_manager.load is not None:
- services.model_manager.load.ram_cache.offload_models_from_vram_except(())
+ with MODEL_LOAD_LOCK.read_lock():
+ services.model_manager.load.ram_cache.offload_models_from_vram_except(())
TorchDevice.empty_cache(force=True)
elif self._session_ended_early(worker, run_returned):
TorchDevice.empty_cache()
diff --git a/invokeai/app/services/shared/invocation_context.py b/invokeai/app/services/shared/invocation_context.py
index 89a5f230c8..f2aa070c99 100644
--- a/invokeai/app/services/shared/invocation_context.py
+++ b/invokeai/app/services/shared/invocation_context.py
@@ -38,6 +38,7 @@ from invokeai.backend.model_manager.configs.base import Config_Base
from invokeai.backend.model_manager.configs.factory import AnyModelConfig
from invokeai.backend.model_manager.configs.roles import serves_as, view_as
from invokeai.backend.model_manager.load.load_base import LoadedModel, LoadedModelWithoutConfig
+from invokeai.backend.model_manager.load.model_cache.model_cache import MODEL_LOAD_LOCK
from invokeai.backend.model_manager.taxonomy import AnyModel, BaseModelType, ModelFormat, ModelType, SubModelType
from invokeai.backend.stable_diffusion.diffusers_pipeline import PipelineIntermediateState
from invokeai.backend.stable_diffusion.diffusion.conditioning_data import ConditioningFieldData
@@ -725,6 +726,8 @@ class ModelsInterface(InvocationContextInterface):
so the next, larger load does not have to compete with it for VRAM. The model stays in the RAM cache, so
a subsequent load only re-streams it back to VRAM rather than rebuilding it from disk.
+ The caller must not hold `MODEL_LOAD_LOCK`; this method acquires its read lock.
+
Args:
identifier: The key or ModelField representing the model to offload.
@@ -732,7 +735,8 @@ class ModelsInterface(InvocationContextInterface):
The number of VRAM bytes freed.
"""
key = identifier if isinstance(identifier, str) else identifier.key
- return self._services.model_manager.load.ram_cache.offload_model_from_vram(key)
+ with MODEL_LOAD_LOCK.read_lock():
+ return self._services.model_manager.load.ram_cache.offload_model_from_vram(key)
def make_room_in_vram(self, vram_bytes_needed: int) -> int:
"""Offload unlocked cached models from VRAM until `vram_bytes_needed` bytes are free on this thread's
@@ -744,6 +748,8 @@ class ModelsInterface(InvocationContextInterface):
and would otherwise only get whatever they happened to leave free. The configured working-memory reserve
is kept free on top of the request.
+ The caller must not hold `MODEL_LOAD_LOCK`; this method acquires its read lock.
+
Args:
vram_bytes_needed: The VRAM footprint the caller is about to allocate.
@@ -752,7 +758,8 @@ class ModelsInterface(InvocationContextInterface):
(in-use) models are never offloaded, so the request is not guaranteed: compare the result with
`vram_bytes_needed` before allocating.
"""
- return self._services.model_manager.load.ram_cache.make_room_in_vram(vram_bytes_needed)
+ with MODEL_LOAD_LOCK.read_lock():
+ return self._services.model_manager.load.ram_cache.make_room_in_vram(vram_bytes_needed)
@staticmethod
def _raise_if_external(model: AnyModelConfig) -> None:
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 981261ada4..4a18e780bd 100644
--- a/invokeai/backend/model_manager/load/model_cache/model_cache.py
+++ b/invokeai/backend/model_manager/load/model_cache/model_cache.py
@@ -386,7 +386,8 @@ MODEL_LOAD_LOCK = _ModelLoadReadWriteLock()
# passes. Without this, a multi-GB stream (e.g. a partially-loaded video transformer) holds the
# read lock for its full duration, and because the lock is write-preferring, one construction
# queued behind it stalls every VRAM move on every GPU for that long. The cap bounds any queued
-# construction's wait to roughly one pass. 1 GiB keeps the per-pass overhead (lock churn plus a
+# construction's wait during these streams to roughly one pass; full offloads and the first lock
+# pass are not paced. 1 GiB keeps the per-pass overhead (lock churn plus a
# re-scan of the model's state dict) negligible against the transfer itself.
VRAM_MOVE_PASS_BYTES = 1 << 30
@@ -3189,6 +3190,8 @@ class ModelCache:
def make_room_in_vram(self, vram_bytes_needed: int, working_mem_bytes: Optional[int] = None) -> int:
"""Offload unlocked models from VRAM to RAM until `vram_bytes_needed` bytes are free on the execution device.
+ The caller must hold `MODEL_LOAD_LOCK`'s read lock before entering the cache lock.
+
This is the entry point for code that has to put a model on the GPU *outside* the cache - e.g. a
BitsAndBytes-quantized text encoder, which is pinned to the device it was quantized on and so cannot be
managed by the cache. Such a load competes with cached models for VRAM, but never passes through `lock()`,
@@ -3224,6 +3227,8 @@ class ModelCache:
def offload_model_from_vram(self, model_key: str) -> int:
"""Move a model (and its submodels) from VRAM to RAM without dropping it from the cache.
+ The caller must hold `MODEL_LOAD_LOCK`'s read lock before entering the cache lock.
+
Unlike `drop_model`, the cache entry is kept, so the model stays resident in RAM and the next load does
not have to rebuild it from disk - only re-stream its weights back to VRAM. This is useful for freeing
VRAM after a one-shot use (e.g. a text encoder that has already produced its embeddings) before a much
@@ -3238,6 +3243,8 @@ class ModelCache:
def offload_models_from_vram_except(self, keep_model_keys: Collection[str]) -> int:
"""Move every model whose key is not in `keep_model_keys` from VRAM to RAM, keeping it cached.
+ The caller must hold `MODEL_LOAD_LOCK`'s read lock before entering the cache lock.
+
`keep_model_keys` are plain model keys; a kept model keeps its submodels too. As with
`offload_model_from_vram`, the entries stay resident in RAM, so a later use re-streams weights instead of
rebuilding from disk, and locked (in-use) entries are skipped.
@@ -3254,6 +3261,8 @@ class ModelCache:
def offload_unlocked_models_from_vram(self, keep_cache_keys: Collection[str] = ()) -> int:
"""Move every unlocked entry but those in `keep_cache_keys` from VRAM to RAM whole, keeping it cached.
+ The caller must hold `MODEL_LOAD_LOCK`'s read lock before entering the cache lock.
+
`keep_cache_keys` are exact cache keys: keeping a submodel (`<model key>:vae`) keeps none of its siblings, unlike
`offload_models_from_vram_except`. Each entry leaves whole, where `lock()` moves out only the shortfall it
predicts and so splits the last model it reaches. A working-memory calibration calls this before its measured
diff --git a/tests/app/invocations/test_qwen_image_text_encoder.py b/tests/app/invocations/test_qwen_image_text_encoder.py
index d9bc359f41..b60f114748 100644
--- a/tests/app/invocations/test_qwen_image_text_encoder.py
+++ b/tests/app/invocations/test_qwen_image_text_encoder.py
@@ -323,8 +323,8 @@ class TestQuantizedEncoderLoad:
context.models.get_absolute_path.return_value = model_root
def make_room(vram_bytes_needed: int) -> int:
- # The offload is a VRAM move like any other, so it runs under the model-load *read* lock.
- events.append("make_room" if _read_lock_held() else "make_room(wrong lock)")
+ # The public interface takes the read lock itself; its caller must not already hold it.
+ events.append("make_room" if not (_read_lock_held() or _write_lock_held()) else "make_room(wrong lock)")
return vram_bytes_needed if vram_available is None else vram_available
context.models.make_room_in_vram.side_effect = make_room
diff --git a/tests/app/services/session_processor/test_architecture_switch.py b/tests/app/services/session_processor/test_architecture_switch.py
index 8d6707d785..c6c39f0ee8 100644
--- a/tests/app/services/session_processor/test_architecture_switch.py
+++ b/tests/app/services/session_processor/test_architecture_switch.py
@@ -76,6 +76,16 @@ def test_a_switch_keeps_what_the_new_session_names_and_moves_the_rest() -> None:
assert freed == 3 * 2**30
+def test_architecture_switch_retains_weights_during_concurrent_construction(offload_race) -> None:
+ def switch(cache):
+ offload = ArchitectureSwitchOffload()
+ assert offload.before_session(_graph(SD1), cache) == 0
+ return offload.before_session(_graph(SD2, SHARED_VAE), cache)
+
+ assert offload_race(switch, construction_first=True) == 16
+ assert offload_race(switch, construction_first=False) == 16
+
+
def test_the_same_architecture_moves_nothing() -> None:
offload, cache = ArchitectureSwitchOffload(), _Cache()
offload.before_session(_graph(SD1), cache) # type: ignore[arg-type]
diff --git a/tests/app/services/session_processor/test_release_vram_after_session.py b/tests/app/services/session_processor/test_release_vram_after_session.py
index fe80016ec7..4af9d80c5c 100644
--- a/tests/app/services/session_processor/test_release_vram_after_session.py
+++ b/tests/app/services/session_processor/test_release_vram_after_session.py
@@ -28,6 +28,7 @@ from invokeai.app.services.shared.database.database import Database
from invokeai.app.services.shared.graph import Graph, GraphExecutionState
from invokeai.app.services.shared.invocation_context import InvocationContext
from invokeai.backend.util.devices import EmptyCacheOutcome, TorchDevice
+from tests.fixtures.model_offload import assert_load_lock_idle
# Bounds a hang, not worker latency.
_TIMEOUT = 30
@@ -135,6 +136,7 @@ def test_clear_vram_after_session_moves_every_model_to_ram_and_forces_the_releas
leaves VRAM (staying cached in RAM) and the allocator hands its blocks back, whatever the session's outcome."""
cache = _Cache()
processor, logger = _processor(clear_vram_after_session=True, cache=cache)
+ device_requests.sample = assert_load_lock_idle
processor._release_vram_after_session(_worker(outcome), run_returned=True) # type: ignore[arg-type]
@@ -157,6 +159,34 @@ def test_clear_vram_after_session_logs_a_refused_forced_release_instead_of_faili
assert "cuda:0" in logger.warnings[0]
+def test_session_cleanup_retains_weights_during_concurrent_construction(offload_race) -> None:
+ def release(cache):
+ processor, logger = _processor(clear_vram_after_session=True, cache=cache)
+ result = processor._release_vram_after_session(_worker(), run_returned=True) # type: ignore[arg-type]
+ assert logger.warnings == []
+ return result
+
+ assert offload_race(release, construction_first=True) is None
+ assert offload_race(release, construction_first=False) is None
+
+
+def test_failed_session_offload_logs_without_emptying_allocator(monkeypatch) -> None:
+ class BrokenCache:
+ def offload_models_from_vram_except(self, keep_model_keys):
+ assert tuple(keep_model_keys) == ()
+ raise RuntimeError("offload failed")
+
+ emptied = []
+ monkeypatch.setattr(TorchDevice, "empty_cache", classmethod(lambda cls, **kwargs: emptied.append(True)))
+ processor, logger = _processor(clear_vram_after_session=True, cache=BrokenCache())
+
+ assert processor._release_vram_after_session(_worker(), run_returned=True) is None # type: ignore[arg-type]
+
+ assert len(logger.warnings) == 1
+ assert "cuda:0" in logger.warnings[0]
+ assert emptied == []
+
+
def test_clear_vram_after_session_leaves_other_gpus_caches_alone(monkeypatch) -> None:
"""Multi-GPU: a worker clears its own device's cache only -- a peer may be mid-session on its own."""
monkeypatch.setattr(TorchDevice, "empty_cache", classmethod(lambda cls, force=False: EmptyCacheOutcome.RAN))
diff --git a/tests/app/services/shared/test_invocation_context_make_room_in_vram.py b/tests/app/services/shared/test_invocation_context_make_room_in_vram.py
index 866cd211d0..688cf6174a 100644
--- a/tests/app/services/shared/test_invocation_context_make_room_in_vram.py
+++ b/tests/app/services/shared/test_invocation_context_make_room_in_vram.py
@@ -2,6 +2,7 @@
invocation context is the only route an invocation has to the cache, and the post-offload availability is what the
caller compares its request against."""
+from types import SimpleNamespace
from unittest.mock import MagicMock
from invokeai.app.services.shared.invocation_context import ModelsInterface
@@ -14,3 +15,13 @@ def test_make_room_in_vram_delegates_to_the_threads_ram_cache():
assert models.make_room_in_vram(10) == 123
services.model_manager.load.ram_cache.make_room_in_vram.assert_called_once_with(10)
+
+
+def test_make_room_retains_weights_during_concurrent_construction(offload_race, monkeypatch):
+ def offload(cache):
+ monkeypatch.setattr(cache, "_get_physical_vram_available", lambda *_: 0)
+ services = SimpleNamespace(model_manager=SimpleNamespace(load=SimpleNamespace(ram_cache=cache)))
+ return ModelsInterface(services=services, data=None, util=None).make_room_in_vram(16)
+
+ assert offload_race(offload, construction_first=True) == 0
+ assert offload_race(offload, construction_first=False) == 0
diff --git a/tests/app/services/shared/test_invocation_context_offload_from_vram.py b/tests/app/services/shared/test_invocation_context_offload_from_vram.py
new file mode 100644
index 0000000000..09ee8e411a
--- /dev/null
+++ b/tests/app/services/shared/test_invocation_context_offload_from_vram.py
@@ -0,0 +1,49 @@
+"""The invocation offload interface preserves model keys, freed bytes, failures and real weights."""
+
+from types import SimpleNamespace
+
+import pytest
+
+from invokeai.app.invocations.model import ModelIdentifierField
+from invokeai.app.services.shared.invocation_context import ModelsInterface
+from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelType
+
+
+def _models(cache):
+ services = SimpleNamespace(model_manager=SimpleNamespace(load=SimpleNamespace(ram_cache=cache)))
+ return ModelsInterface(services=services, data=None, util=None)
+
+
+def test_invocation_offload_retains_weights_during_concurrent_construction(offload_race) -> None:
+ def offload(cache):
+ return _models(cache).offload_from_vram("old")
+
+ assert offload_race(offload, construction_first=True) == 16
+ assert offload_race(offload, construction_first=False) == 16
+
+
+def test_offload_accepts_model_identifier_and_returns_cache_answer() -> None:
+ keys = []
+
+ def offload(key):
+ keys.append(key)
+ return 123
+
+ identifier = ModelIdentifierField(
+ key="encoder", hash="blake3:encoder", name="encoder", base=BaseModelType.StableDiffusion1, type=ModelType.Main
+ )
+ models = _models(SimpleNamespace(offload_model_from_vram=offload))
+ assert models.offload_from_vram(identifier) == 123
+ assert keys == ["encoder"]
+
+
+def test_failed_offload_preserves_exception() -> None:
+ error = RuntimeError("offload failed")
+
+ def fail(key):
+ raise error
+
+ models = _models(SimpleNamespace(offload_model_from_vram=fail))
+ with pytest.raises(RuntimeError) as raised:
+ models.offload_from_vram("encoder")
+ assert raised.value is error
diff --git a/tests/backend/model_manager/load/model_cache/test_model_load_rw_lock.py b/tests/backend/model_manager/load/model_cache/test_model_load_rw_lock.py
index c349ec9440..933ecb2d13 100644
--- a/tests/backend/model_manager/load/model_cache/test_model_load_rw_lock.py
+++ b/tests/backend/model_manager/load/model_cache/test_model_load_rw_lock.py
@@ -12,6 +12,23 @@ import pytest
from invokeai.backend.model_manager.load.model_cache.model_cache import _ModelLoadReadWriteLock
+def test_readers_can_overlap() -> None:
+ lock = _ModelLoadReadWriteLock()
+ acquired = threading.Event()
+
+ def reader() -> None:
+ with lock.read_lock():
+ acquired.set()
+
+ with lock.read_lock():
+ thread = threading.Thread(target=reader, daemon=True)
+ thread.start()
+ overlapped = acquired.wait(timeout=10)
+ thread.join(timeout=10)
+ assert not thread.is_alive()
+ assert overlapped, "readers were serialized"
+
+
def test_writer_does_not_leak_waiting_count_when_wait_raises() -> None:
"""An exception out of `_cond.wait()` must not wedge every future reader."""
lock = _ModelLoadReadWriteLock()
diff --git a/tests/conftest.py b/tests/conftest.py
index 6da4a4d5a6..f79a43329e 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -61,6 +61,7 @@ from tests.fixtures.database import ( # noqa: F401
empty_database,
external_test_db_url,
)
+from tests.fixtures.model_offload import offload_race # noqa: F401
from tests.fixtures.races import lost_races # noqa: F401
from tests.fixtures.sqlite_database import create_mock_sqlite_database # noqa: F401
from tests.test_nodes import TestEventService
diff --git a/tests/fixtures/model_offload.py b/tests/fixtures/model_offload.py
new file mode 100644
index 0000000000..199862e4b2
--- /dev/null
+++ b/tests/fixtures/model_offload.py
@@ -0,0 +1,125 @@
+"""Native offload/construction races shared by the three application entrypoints."""
+
+import gc
+import threading
+from time import monotonic
+
+import pytest
+import torch
+from accelerate import init_empty_weights
+
+from invokeai.backend.model_manager.load.model_cache.model_cache import MODEL_LOAD_LOCK, ModelCache
+from invokeai.backend.util.devices import TorchDevice
+
+WAIT_TIMEOUT = 20
+
+
+def assert_load_lock_idle() -> None:
+ with MODEL_LOAD_LOCK._cond:
+ assert MODEL_LOAD_LOCK._readers == MODEL_LOAD_LOCK._writers_waiting == 0
+ assert not MODEL_LOAD_LOCK._writer_active
+
+
+def offload_race(monkeypatch):
+ """Use real cache locks and CPU-backed full offloads; only device residency and allocator I/O are simulated.
+
+ The wait observer forwards to the real condition. It acknowledges contention without timing a negative event,
+ and bounds deadlocks so real context managers can unwind without resetting process-global lock state.
+ """
+
+ def run(offload, construction_first: bool):
+ assert_load_lock_idle()
+ with monkeypatch.context() as patch:
+ patch.setattr(gc, "collect", lambda: 0)
+ patch.setattr(TorchDevice, "empty_cache", classmethod(lambda cls, **kwargs: None))
+ cache = ModelCache(
+ execution_device_working_mem_gb=0,
+ execution_device="cpu",
+ storage_device="cpu",
+ enable_partial_loading=False,
+ keep_ram_copy_of_weights=True,
+ shared_cpu_weights=None,
+ )
+ model = torch.nn.Linear(2, 2, bias=False)
+ expected = torch.arange(4, dtype=torch.float32).reshape(2, 2)
+ model.load_state_dict({"weight": expected.clone()}, assign=True)
+ cache.put("old:encoder", model)
+ cached = cache._cached_models["old:encoder"].cached_model
+ cached.full_load_to_vram() # CPU copies, but the real wrapper records residency and retains its RAM copy.
+ patch.setattr(cache, "_execution_device", torch.device("cuda:0"))
+ ready, proceed, attempted, registered = (threading.Event() for _ in range(4))
+ errors, results, constructed = [], [], []
+ deadline = monotonic() + WAIT_TIMEOUT
+ real_wait, real_assign = MODEL_LOAD_LOCK._cond.wait, model.load_state_dict
+
+ def wait(timeout=None):
+ # Waiting for construction must happen before the calling thread owns the cache lock.
+ assert not cache._lock._is_owned(), "cache lock acquired before model load lock"
+ attempted.set()
+ remaining = deadline - monotonic()
+ assert remaining > 0, "model load lock did not make progress"
+ return real_wait(remaining if timeout is None else min(timeout, remaining))
+
+ def assign(*args, **kwargs):
+ try:
+ if not construction_first:
+ ready.set()
+ assert proceed.wait(WAIT_TIMEOUT), "offload was not released"
+ return real_assign(*args, **kwargs)
+ finally:
+ registered.set()
+ if construction_first:
+ attempted.set()
+
+ def move():
+ try:
+ results.append(offload(cache))
+ except BaseException as error:
+ errors.append(error)
+ attempted.set()
+
+ def construct():
+ try:
+ with MODEL_LOAD_LOCK.write_lock(), init_empty_weights():
+ constructed.append(torch.nn.Linear(2, 2).weight.device.type)
+ attempted.set()
+ assert registered.wait(WAIT_TIMEOUT), "offload never registered its weights"
+ except BaseException as error:
+ errors.append(error)
+
+ patch.setattr(MODEL_LOAD_LOCK._cond, "wait", wait)
+ patch.setattr(model, "load_state_dict", assign)
+ mover = threading.Thread(target=move, daemon=True)
+ builder = threading.Thread(target=construct, daemon=True)
+ try:
+ if construction_first:
+ with MODEL_LOAD_LOCK.write_lock(), init_empty_weights():
+ constructed.append(torch.nn.Linear(2, 2).weight.device.type)
+ mover.start()
+ assert attempted.wait(WAIT_TIMEOUT), "offload neither waited nor assigned"
+ else:
+ mover.start()
+ assert ready.wait(WAIT_TIMEOUT), f"offload never reached assignment: {errors!r}"
+ builder.start()
+ assert attempted.wait(WAIT_TIMEOUT), "construction neither waited nor started"
+ proceed.set()
+ finally:
+ proceed.set()
+ if mover.ident is not None:
+ mover.join(WAIT_TIMEOUT)
+ registered.set()
+ if builder.ident is not None:
+ builder.join(WAIT_TIMEOUT)
+ assert not mover.is_alive() and not builder.is_alive(), "offload/construction deadlocked"
+ cache.shutdown()
+ assert_load_lock_idle()
+
+ assert constructed == ["meta"] # The real accelerate patch was active, not a stand-in constructor.
+ assert model.weight.device.type == "cpu", f"offload stranded weights on meta: {errors!r}"
+ torch.testing.assert_close(model.weight, expected, rtol=0, atol=0)
+ assert not errors, f"offload/construction failed: {errors!r}"
+ assert cached.cur_vram_bytes() == 0
+ return results[0]
+
+ return run