Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
feat: pace partial-load VRAM moves so queued model loads aren't starved
Lincoln Steind5e8cc580c90
diff --git a/invokeai/backend/model_manager/load/load_base.py b/invokeai/backend/model_manager/load/load_base.pyindex 9df213f90a..98d7681f8c 100644--- a/invokeai/backend/model_manager/load/load_base.py+++ b/invokeai/backend/model_manager/load/load_base.py@@ -3,6 +3,7 @@Base class for model loading in InvokeAI."""+import timefrom abc import ABC, abstractmethodfrom contextlib import contextmanagerfrom logging import Logger@@ -18,7 +19,11 @@ from invokeai.backend.model_manager.load.model_cache.cache_record import CacheRefrom 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 MODEL_LOAD_LOCK, ModelCache+from invokeai.backend.model_manager.load.model_cache.model_cache import (+ MODEL_LOAD_LOCK,+ VRAM_MOVE_PASS_BYTES,+ ModelCache,+)from invokeai.backend.model_manager.taxonomy import AnyModel, SubModelType@@ -65,13 +70,49 @@ class LoadedModelWithoutConfig:if self._first_use_finalizer is not None:self._first_use_finalizer.atexit = False- def __enter__(self) -> AnyModel:- # Hold the MODEL_LOAD_LOCK read lock across the VRAM load (lock() runs- # load_state_dict(assign=True), which calls register_parameter) so it can't overlap a- # concurrent model construction that has the global register_parameter -> meta patch active.- # Acquired before the cache's own lock to keep a consistent lock order (see MODEL_LOAD_LOCK).+ def _lock_paced(self, working_mem_bytes: Optional[int]) -> None:+ """Move the model into VRAM in bounded passes, yielding the global load lock between them.++ Each pass holds the MODEL_LOAD_LOCK read lock across its slice of the VRAM load (the move+ runs load_state_dict(assign=True), which calls register_parameter, so it must not overlap+ a concurrent model construction that has the global register_parameter -> meta patch+ active), acquired before the cache's own lock to keep the documented lock order. Nothing+ is held between passes, so a construction (write lock) queued on any worker runs in the+ gap instead of waiting out the entire multi-GB stream — the write-preferring lock+ guarantees the queued construction wins that gap. A failed pass behaves exactly like a+ failed lock(): the cache has already unpinned the entry, so no unlock is owed here.++ Known trade-off of yielding mid-stream: another load on the SAME device cache can slip+ into a gap and pin VRAM this stream's budget had counted on. The stream then settles at+ correspondingly lower residency (after trimming its own bytes if needed to preserve the+ working-memory reservation) — exactly what a fresh lock() would compute at that instant.+ Pre-pacing behavior made the interleaver wait instead. Residency recovers at the next+ invocation's re-lock, once the interleaver unlocks.+ """+ stream_started_at = time.time()with MODEL_LOAD_LOCK.read_lock():- self._cache.lock(self._cache_record, None)+ settled = self._cache.lock(self._cache_record, working_mem_bytes, max_move_bytes=VRAM_MOVE_PASS_BYTES)+ # Termination backstop: pathological interleavings (another thread's budget disagreeing+ # with ours can unload what a pass just loaded) could in principle re-truncate forever.+ # After comfortably more passes than the model's size can honestly require, run one final+ # uncapped pass — with no cap, a pass can never report itself truncated, so it settles.+ remaining_capped_passes = self._cache_record.cached_model.total_bytes() // VRAM_MOVE_PASS_BYTES + 8+ while not settled:+ remaining_capped_passes -= 1+ with MODEL_LOAD_LOCK.read_lock():+ settled = self._cache.continue_lock(+ self._cache_record,+ working_mem_bytes,+ max_move_bytes=VRAM_MOVE_PASS_BYTES if remaining_capped_passes > 0 else None,+ stream_started_at=stream_started_at,+ )+ if remaining_capped_passes <= 0:+ # The uncapped pass settles by construction; guard against a regression in that+ # invariant turning this loop into a spin.+ assert settled, "uncapped continue_lock pass did not settle"++ def __enter__(self) -> AnyModel:+ self._lock_paced(None)if self._first_use_finalizer is not None:self._first_use_finalizer.detach()try:@@ -93,9 +134,7 @@ class LoadedModelWithoutConfig::param working_mem_bytes: The amount of working memory to keep available on the compute device when loading themodel."""- # See __enter__ for why the VRAM load is wrapped in the read lock.- with MODEL_LOAD_LOCK.read_lock():- self._cache.lock(self._cache_record, working_mem_bytes)+ self._lock_paced(working_mem_bytes)if self._first_use_finalizer is not None:self._first_use_finalizer.detach()try: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.pyindex 00be7d3d95..d19de2b1cd 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@@ -334,17 +334,42 @@ class CachedModelWithPartialLoad:Returns:The number of bytes loaded into VRAM."""+ vram_bytes_loaded, _truncated = self.partial_load_to_vram_chunk(vram_bytes_to_load, max_bytes=None)+ return vram_bytes_loaded++ @torch.no_grad()+ def partial_load_to_vram_chunk(self, vram_bytes_to_load: int, max_bytes: int | None) -> tuple[int, bool]:+ """Load more weights into VRAM without exceeding vram_bytes_to_load, optionally stopping after max_bytes.++ `vram_bytes_to_load` is the capacity budget (how much VRAM the weights may occupy);+ `max_bytes` is a per-call pacing cap that lets a caller split one long RAM->VRAM stream+ into bounded passes (so a lock held around each pass is released between passes).+ Successive calls resume from the current residency, so calling until `truncated` is False+ reaches exactly the state a single uncapped call would have reached.++ Returns:+ (vram_bytes_loaded, truncated): `truncated` is True iff the scan stopped because+ `max_bytes` was reached while more weights would otherwise have been selected — i.e.+ another call can make further progress toward the same `vram_bytes_to_load` budget.+ """# TODO(ryand): Handle the case where an exception is thrown while loading or unloading weights. At the very# least, we should reset self._cur_vram_bytes to None.+ if max_bytes is not None and max_bytes <= 0:+ # A non-positive cap would return (0, truncated=True) forever and spin any caller that+ # loops until settled.+ raise ValueError(f"max_bytes must be positive when set; got {max_bytes}.")+vram_bytes_loaded = 0+ truncated = Falsecur_state_dict = self._model.state_dict()# Identify the keys that will be loaded into VRAM.keys_to_load: set[str] = set()- # First, process the keys that *must* be loaded into VRAM.+ # First, process the keys that *must* be loaded into VRAM. The pacing cap does not apply to+ # these: a pass must never end with the model in a state that cannot run.for key in self._keys_in_modules_that_do_not_support_autocast:param = cur_state_dict[key]if param.device.type == self._compute_device.type:@@ -371,6 +396,13 @@ class CachedModelWithPartialLoad:if param.device.type == self._compute_device.type:continue+ if max_bytes is not None and vram_bytes_loaded >= max_bytes:+ # The pacing cap is reached and at least one more off-device key exists. Whether+ # that key would have fit the capacity budget is deliberately not checked here —+ # the next pass re-derives it with a fresh budget.+ truncated = True+ break+param_size = self._state_dict_bytes[key]if vram_bytes_loaded + param_size > vram_bytes_to_load:# TODO(ryand): Should we just break here? If we couldn't fit this parameter into VRAM, is it really@@ -390,16 +422,18 @@ class CachedModelWithPartialLoad:if self._cur_vram_bytes is not None:self._cur_vram_bytes += vram_bytes_loaded- if fully_loaded:+ if fully_loaded and not truncated:self._set_autocast_enabled_in_all_modules(False)else:+ # Not fully resident (or a truncated pass whose remaining keys are unknown): the+ # autocast wrappers must stay enabled so the model stays runnable either way.self._set_autocast_enabled_in_all_modules(True)# Move all non-persistent buffers to the compute device. These are a weird edge case and do not participate in# the vram_bytes_loaded tracking.self._move_non_persistent_buffers_to_device(self._compute_device)- return vram_bytes_loaded+ return vram_bytes_loaded, truncated@torch.no_grad()def partial_unload_from_vram(self, vram_bytes_to_free: int, keep_required_weights_in_vram: bool = False) -> int:diff --git a/invokeai/backend/model_manager/load/model_cache/model_cache.py b/invokeai/backend/model_manager/load/model_cache/model_cache.pyindex 364f23dd0c..c7fd502a20 100644--- a/invokeai/backend/model_manager/load/model_cache/model_cache.py+++ b/invokeai/backend/model_manager/load/model_cache/model_cache.py@@ -180,6 +180,15 @@ class _ModelLoadReadWriteLock:# Process-global lock guarding the non-thread-safe model load machinery. See _ModelLoadReadWriteLock.MODEL_LOAD_LOCK = _ModelLoadReadWriteLock()+# Pacing cap for partial-load VRAM moves: `LoadedModelWithoutConfig` splits a long RAM->VRAM+# stream into passes of at most this many bytes, dropping MODEL_LOAD_LOCK's read lock between+# 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+# re-scan of the model's state dict) negligible against the transfer itself.+VRAM_MOVE_PASS_BYTES = 1 << 30+# TODO(ryand): Where should this go? The ModelCache shouldn't be concerned with submodels.def get_model_cache_key(model_key: str, submodel_type: Optional[SubModelType] = None) -> str:@@ -987,8 +996,21 @@ class ModelCache:@synchronized@record_activity- def lock(self, cache_entry: CacheRecord, working_mem_bytes: Optional[int]) -> None:- """Lock a model for use and move it into VRAM."""+ def lock(+ self,+ cache_entry: CacheRecord,+ working_mem_bytes: Optional[int],+ max_move_bytes: Optional[int] = None,+ ) -> bool:+ """Lock a model for use and move it into VRAM.++ `max_move_bytes` optionally paces the RAM->VRAM stream: at most that many bytes are moved+ in this call. Returns True when the move is settled (the model is as resident as the VRAM+ budget allows); False when the pacing cap ended the pass early — the caller must then call+ `continue_lock()` (re-taking its outer locks in between) until it returns True. The entry+ is pinned by this call either way; a False return leaves it runnable (autocast wrappers+ stay enabled for the still-offloaded weights).+ """if cache_entry.key not in self._cached_models:self._logger.info(f"Locking model cache entry {cache_entry.key} "@@ -1024,10 +1046,10 @@ class ModelCache:f"Loaded model '{cache_entry.key}' ({cache_entry.cached_model.model.__class__.__name__}) onto "f"cpu device; skipping VRAM load")- return+ return Truetry:- self._load_locked_model(cache_entry, working_mem_bytes)+ settled = self._load_locked_model(cache_entry, working_mem_bytes, max_move_bytes=max_move_bytes)self._logger.debug(f"Finished locking model {cache_entry.key} (Type: {cache_entry.cached_model.model.__class__.__name__})")@@ -1040,6 +1062,55 @@ class ModelCache:raiseself._log_cache_state()+ return settled++ @synchronized+ @record_activity+ def continue_lock(+ self,+ cache_entry: CacheRecord,+ working_mem_bytes: Optional[int],+ max_move_bytes: Optional[int] = None,+ stream_started_at: Optional[float] = None,+ ) -> bool:+ """Continue a paced VRAM move begun by `lock(..., max_move_bytes=...)` that returned False.++ Moves at most `max_move_bytes` more bytes toward the same budget and returns True once the+ move is settled. The entry is already pinned by the initial `lock()` call, so this does NOT+ pin it again; on failure it releases that original pin (mirroring `lock()`), so the caller+ must treat an exception here exactly like a failed `lock()` and not unlock again.++ `stream_started_at` (a `time.time()` value from before the initial `lock()`) makes the+ final pass's "Loaded model ..." line report the whole stream's elapsed time rather than+ the last pass's.+ """+ if cache_entry.key not in self._cached_models:+ # Same diagnostic as lock()/unlock() (issue 7513): a detached record's continuation+ # passes should not run silently.+ self._logger.info(+ f"Continuing paced lock of model cache entry {cache_entry.key} "+ f"(Type: {cache_entry.cached_model.model.__class__.__name__}), but it has already been dropped from "+ "the RAM cache. This is a sign that the model loading order is non-optimal in the invocation code "+ "(See https://github.com/invoke-ai/InvokeAI/issues/7513)."+ )+ try:+ settled = self._load_locked_model(+ cache_entry,+ working_mem_bytes,+ max_move_bytes=max_move_bytes,+ stream_started_at=stream_started_at,+ )+ except torch.OutOfMemoryError:+ self._logger.warning("Insufficient GPU memory to load model. Aborting")+ cache_entry.unlock()+ raise+ except Exception:+ cache_entry.unlock()+ raise++ if settled:+ self._log_cache_state()+ return settled@synchronized@record_activity@@ -1088,9 +1159,19 @@ class ModelCache:if self._ram_budget is not None and self._ram_budget.available() < 0:self._budget_reconcile_pending.set()- def _load_locked_model(self, cache_entry: CacheRecord, working_mem_bytes: Optional[int] = None) -> None:- """Helper function for self.lock(). Loads a locked model into VRAM."""- start_time = time.time()+ def _load_locked_model(+ self,+ cache_entry: CacheRecord,+ working_mem_bytes: Optional[int] = None,+ max_move_bytes: Optional[int] = None,+ stream_started_at: Optional[float] = None,+ ) -> bool:+ """Helper function for self.lock(). Loads a locked model into VRAM.++ Returns True when the move is settled (fully resident, or as resident as the VRAM budget+ allows); False when `max_move_bytes` truncated the pass and another pass is needed.+ """+ start_time = stream_started_at if stream_started_at is not None else time.time()# Calculate model_vram_needed, the amount of additional VRAM that will be used if we fully load the model into# VRAM.@@ -1130,7 +1211,17 @@ class ModelCache:# vram_available = int(model_vram_needed * 0.1)# We add 1 MB to the available VRAM to account for small errors in memory tracking (e.g. off-by-one). A fully# loaded model is much faster than a 95% loaded model.- model_bytes_loaded = self._move_model_to_vram(cache_entry, vram_available + MB)+ model_bytes_loaded, truncated = self._move_model_to_vram(cache_entry, vram_available + MB, max_move_bytes)++ if truncated:+ # A paced pass that stopped at max_move_bytes with more weights still to move. Keep the+ # per-pass logging at DEBUG — the settled pass below emits the one INFO summary line.+ self._logger.debug(+ f"Paced VRAM move for {cache_entry.key}: moved {model_bytes_loaded / MB:.2f}MB this pass, "+ f"{(cache_entry.cached_model.total_bytes() - cache_entry.cached_model.cur_vram_bytes()) / MB:.2f}MB "+ "still to move."+ )+ return Falsemodel_cur_vram_bytes = cache_entry.cached_model.cur_vram_bytes()vram_available = self._get_vram_available(working_mem_bytes)@@ -1161,11 +1252,17 @@ class ModelCache:self._logger.debug(f"After loading: {self._get_vram_state_str(model_cur_vram_bytes, model_total_bytes, vram_available)}")+ return True- def _move_model_to_vram(self, cache_entry: CacheRecord, vram_available: int) -> int:+ def _move_model_to_vram(+ self, cache_entry: CacheRecord, vram_available: int, max_move_bytes: Optional[int] = None+ ) -> tuple[int, bool]:+ """Move up to `vram_available` bytes of the model into VRAM (at most `max_move_bytes` of it+ in this call, when set). Returns (bytes_moved, truncated); truncated is only ever True for+ partial-load models — full-load models move in one indivisible pass."""try:if isinstance(cache_entry.cached_model, CachedModelWithPartialLoad):- return cache_entry.cached_model.partial_load_to_vram(vram_available)+ return cache_entry.cached_model.partial_load_to_vram_chunk(vram_available, max_bytes=max_move_bytes)elif isinstance(cache_entry.cached_model, CachedModelOnlyFullLoad): # type: ignore# Partial load is not supported, so we have not choice but to try and fit it all into VRAM.#@@ -1195,7 +1292,7 @@ class ModelCache:"so proceeding would exhaust system memory. Free up RAM, use a smaller or more ""heavily quantized model, or lower `device_working_mem_gb`.")- return cache_entry.cached_model.full_load_to_vram()+ return cache_entry.cached_model.full_load_to_vram(), Falseelse:raise ValueError(f"Unsupported cached model type: {type(cache_entry.cached_model)}")except Exception as e:@@ -1472,7 +1569,12 @@ class ModelCache:)vram_bytes_freed += cache_entry_bytes_freed- TorchDevice.empty_cache()+ # Only pay for empty_cache() when something was actually offloaded. Paced VRAM moves run+ # this method once per pass, and on most passes there is nothing left to offload —+ # an unconditional empty_cache() would return the allocator's blocks to the driver+ # (and synchronize the device on ROCm) dozens of times per stream for no benefit.+ if vram_bytes_freed > 0:+ TorchDevice.empty_cache()return vram_bytes_freeddef _log_cache_state(self, title: str = "Model cache state:", include_entry_details: bool = True):diff --git a/tests/backend/model_manager/load/model_cache/cached_model/test_cached_model_with_partial_load.py b/tests/backend/model_manager/load/model_cache/cached_model/test_cached_model_with_partial_load.pyindex 7ae45ff2f5..342f5f6492 100644--- a/tests/backend/model_manager/load/model_cache/cached_model/test_cached_model_with_partial_load.py+++ b/tests/backend/model_manager/load/model_cache/cached_model/test_cached_model_with_partial_load.py@@ -339,3 +339,76 @@ def test_cached_model_partial_load_and_inference(device: str, model: DummyModule# The output should be the same as the output from the CPU.assert torch.allclose(output1, output2.to("cpu"))+++@parameterize_mps_and_cuda+@parameterize_keep_ram_copy+def test_cached_model_partial_load_chunked_full_residency(device: str, model: DummyModule, keep_ram_copy: bool):+ """Paced passes (max_bytes) must converge to exactly the state one uncapped call reaches."""+ cached_model = CachedModelWithPartialLoad(+ model=model, compute_device=torch.device(device), keep_ram_copy=keep_ram_copy+ )+ model_total_bytes = cached_model.total_bytes()+ assert cached_model.cur_vram_bytes() == 0++ # A cap far below the total forces several passes.+ max_bytes = model_total_bytes // 4+ passes = 0+ truncated = True+ while truncated:+ remaining_budget = model_total_bytes - cached_model.cur_vram_bytes()+ _, truncated = cached_model.partial_load_to_vram_chunk(remaining_budget, max_bytes=max_bytes)+ passes += 1+ assert passes < 100, "paced load did not converge"++ assert passes > 1, "cap did not actually split the load into multiple passes"+ assert cached_model.cur_vram_bytes() == model_total_bytes+ assert all(p.device.type == device for p in model.parameters())+ # Fully resident: the settled pass must have disabled device autocasting.+ assert not model.linear1.is_device_autocasting_enabled()+ assert not model.linear2.is_device_autocasting_enabled()++ # Inference still works after the paced load.+ x = torch.randn(1, 10).to(device)+ assert model(x).device.type == device+++@parameterize_mps_and_cuda+@parameterize_keep_ram_copy+def test_cached_model_partial_load_chunked_matches_uncapped_budget(+ device: str, model: DummyModule, keep_ram_copy: bool+):+ """With a capacity budget below the total, paced passes settle at the same residency as one+ uncapped call with the same budget, and autocasting stays enabled while truncated."""+ cached_model = CachedModelWithPartialLoad(+ model=model, compute_device=torch.device(device), keep_ram_copy=keep_ram_copy+ )+ model_total_bytes = cached_model.total_bytes()+ target_vram_bytes = int(model_total_bytes * 0.6)++ # Reference: an identical (by architecture) model loaded with one uncapped call.+ reference_model = DummyModule()+ apply_custom_layers_to_model(reference_model)+ reference_cached = CachedModelWithPartialLoad(+ model=reference_model, compute_device=torch.device(device), keep_ram_copy=keep_ram_copy+ )+ reference_loaded = reference_cached.partial_load_to_vram(target_vram_bytes)++ passes = 0+ truncated = True+ while truncated:+ remaining_budget = target_vram_bytes - cached_model.cur_vram_bytes()+ _, truncated = cached_model.partial_load_to_vram_chunk(remaining_budget, max_bytes=1024)+ passes += 1+ if truncated:+ # Mid-stream the model must stay runnable: autocasting stays enabled.+ assert model.linear1.is_device_autocasting_enabled()+ assert model.linear2.is_device_autocasting_enabled()+ assert passes < 100, "paced load did not converge"++ assert passes > 1, "cap did not actually split the load into multiple passes"+ assert cached_model.cur_vram_bytes() == reference_loaded+ assert cached_model.cur_vram_bytes() < model_total_bytes+ # Still partially loaded, so autocasting remains enabled after settling too.+ assert model.linear1.is_device_autocasting_enabled()+ assert model.linear2.is_device_autocasting_enabled()diff --git a/tests/backend/model_manager/load/model_cache/test_model_cache_integrated_gpu.py b/tests/backend/model_manager/load/model_cache/test_model_cache_integrated_gpu.pyindex 4aab7f3f1e..2621aa0ca4 100644--- a/tests/backend/model_manager/load/model_cache/test_model_cache_integrated_gpu.py+++ b/tests/backend/model_manager/load/model_cache/test_model_cache_integrated_gpu.py@@ -190,7 +190,7 @@ def test_relocking_a_resident_model_on_an_integrated_gpu_is_not_refused(mock_logentry.cached_model._is_in_vram = Trueassert entry.cached_model.cur_vram_bytes() == entry.cached_model.total_bytes()# Free memory is now smaller than the model (it is the model); the re-lock must pass.- assert cache._move_model_to_vram(entry, vram_available=0) == 0+ assert cache._move_model_to_vram(entry, vram_available=0) == (0, False)assert "m" in cache._cached_modelsfinally:cache.shutdown()@@ -205,7 +205,7 @@ def test_oversized_model_on_a_discrete_card_still_tries(mock_logger: MagicMock):cache.put("m", DummyModule())entry = _entry(cache, "m")entry.cached_model.full_load_to_vram = MagicMock(return_value=123)- assert cache._move_model_to_vram(entry, vram_available=0) == 123+ assert cache._move_model_to_vram(entry, vram_available=0) == (123, False)finally:cache.shutdown()@@ -217,7 +217,7 @@ def test_cpu_execution_device_is_not_guarded(mock_logger: MagicMock):cache.put("m", DummyModule())entry = _entry(cache, "m")entry.cached_model.full_load_to_vram = MagicMock(return_value=7)- assert cache._move_model_to_vram(entry, vram_available=0) == 7+ assert cache._move_model_to_vram(entry, vram_available=0) == (7, False)finally:cache.shutdown()@@ -236,7 +236,7 @@ def test_mps_is_left_alone(mock_logger: MagicMock):# Present the cached model as MPS-resident without needing a Mac.entry.cached_model._compute_device = torch.device("mps")entry.cached_model.full_load_to_vram = MagicMock(return_value=42)- assert cache._move_model_to_vram(entry, vram_available=0) == 42+ assert cache._move_model_to_vram(entry, vram_available=0) == (42, False)finally:cache.shutdown()diff --git a/tests/backend/model_manager/load/model_cache/test_model_cache_paced_lock.py b/tests/backend/model_manager/load/model_cache/test_model_cache_paced_lock.pynew file mode 100644index 0000000000..4e91cce8bb--- /dev/null+++ b/tests/backend/model_manager/load/model_cache/test_model_cache_paced_lock.py@@ -0,0 +1,162 @@+"""Tests for paced (chunked) VRAM moves.++`ModelCache.lock(..., max_move_bytes=...)` / `continue_lock()` split one long RAM->VRAM stream+into bounded passes, and `LoadedModelWithoutConfig._lock_paced()` drops MODEL_LOAD_LOCK's read+lock between passes so a queued model construction (write lock) on any worker runs in the gap+instead of waiting out the entire stream.+"""++import logging+import threading+import time+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.cached_model.cached_model_with_partial_load import (+ CachedModelWithPartialLoad,+)+from invokeai.backend.model_manager.load.model_cache.model_cache import MODEL_LOAD_LOCK, ModelCache+from tests.backend.model_manager.load.model_cache.cached_model.utils import DummyModule++requires_cuda = pytest.mark.skipif(not torch.cuda.is_available(), reason="Requires CUDA.")+++def _mock_logger() -> MagicMock:+ logger = MagicMock()+ logger.getEffectiveLevel.return_value = logging.INFO+ return logger+++def _make_cache() -> ModelCache:+ return ModelCache(+ execution_device_working_mem_gb=1.0,+ enable_partial_loading=True,+ keep_ram_copy_of_weights=True,+ execution_device="cuda:0",+ storage_device="cpu",+ logger=_mock_logger(),+ shared_cpu_weights=None,+ )+++@requires_cuda+def test_paced_lock_converges_and_pins_once():+ """A capped lock() returning False plus continue_lock() passes must end fully resident with+ the entry pinned exactly once."""+ cache = _make_cache()+ cache.put("m", DummyModule())+ record = cache.get("m")++ settled = cache.lock(record, None, max_move_bytes=1024)+ passes = 1+ while not settled:+ settled = cache.continue_lock(record, None, max_move_bytes=1024)+ passes += 1+ assert passes < 100, "paced lock did not converge"++ assert passes > 1, "cap did not actually split the move into multiple passes"+ cached_model = record.cached_model+ assert isinstance(cached_model, CachedModelWithPartialLoad)+ assert cached_model.cur_vram_bytes() == cached_model.total_bytes()++ # Exactly one pin across all passes: a single unlock releases it.+ assert record.is_locked+ cache.unlock(record)+ assert not record.is_locked+++@requires_cuda+def test_paced_lock_without_cap_settles_in_one_call():+ """The legacy shape — no cap — must settle in the first lock() call."""+ cache = _make_cache()+ cache.put("m", DummyModule())+ record = cache.get("m")++ assert cache.lock(record, None) is True+ cached_model = record.cached_model+ assert isinstance(cached_model, CachedModelWithPartialLoad)+ assert cached_model.cur_vram_bytes() == cached_model.total_bytes()+ cache.unlock(record)+++@requires_cuda+def test_paced_lock_failure_mid_stream_releases_pin():+ """continue_lock() failing must release the pin taken by the initial lock(), mirroring a+ failed lock() — the caller must not be left owing (or double-issuing) an unlock."""+ cache = _make_cache()+ cache.put("m", DummyModule())+ record = cache.get("m")++ settled = cache.lock(record, None, max_move_bytes=256)+ assert settled is False, "expected the tiny cap to truncate the first pass"++ def boom(*args, **kwargs):+ raise RuntimeError("stream failed mid-pass")++ record.cached_model.partial_load_to_vram_chunk = boom # type: ignore[method-assign]+ with pytest.raises(RuntimeError, match="stream failed mid-pass"):+ cache.continue_lock(record, None, max_move_bytes=256)++ assert not record.is_locked, "failed continue_lock left the entry pinned"+++def test_lock_paced_yields_global_lock_to_waiting_writer():+ """A writer queued while a paced stream is mid-flight must acquire between passes.++ With the pre-pacing behavior (one read lock held across the whole stream) the writer could+ only acquire after the stream settled — which in this test never happens until the writer+ runs, so a regression shows up as the timeouts below expiring.+ """+ record = MagicMock()+ record.awaiting_first_use = False+ # Real bytes so _lock_paced's termination-backstop arithmetic works on the mock. Large enough+ # that the backstop's uncapped pass cannot be reached within this test's runtime — the loop+ # must exit via the writer, not the backstop.+ record.cached_model.total_bytes.return_value = 1 << 40+ cache = MagicMock()+ cache.release_first_use_grace = None++ in_stream = threading.Event()+ writer_ran = threading.Event()+ stream_done = threading.Event()++ cache.lock.return_value = False++ def continue_side_effect(*args, **kwargs):+ in_stream.set()+ # Honor the pacing contract: an uncapped pass always settles.+ if kwargs.get("max_move_bytes") is None:+ return True+ # Emulate a pass doing real work so the loop doesn't spin unrealistically fast.+ time.sleep(0.001)+ return writer_ran.is_set()++ cache.continue_lock.side_effect = continue_side_effect++ loaded = LoadedModelWithoutConfig(cache_record=record, cache=cache)++ def run_stream() -> None:+ loaded._lock_paced(None)+ stream_done.set()++ stream_thread = threading.Thread(target=run_stream, daemon=True)+ stream_thread.start()+ assert in_stream.wait(timeout=10), "stream never started"++ writer_done = threading.Event()++ def writer() -> None:+ with MODEL_LOAD_LOCK.write_lock():+ writer_ran.set()+ writer_done.set()++ writer_thread = threading.Thread(target=writer, daemon=True)+ writer_thread.start()++ assert writer_done.wait(timeout=10), "writer never acquired between paced passes"+ assert stream_done.wait(timeout=10), "paced stream did not settle after the writer finished"+ stream_thread.join(timeout=10)+ writer_thread.join(timeout=10)diff --git a/tests/backend/model_manager/load/test_loaded_model.py b/tests/backend/model_manager/load/test_loaded_model.pyindex a8dcfa8667..04368325bd 100644--- a/tests/backend/model_manager/load/test_loaded_model.py+++ b/tests/backend/model_manager/load/test_loaded_model.py@@ -26,9 +26,10 @@ class FakeCache:self.lock_calls = 0self.unlock_calls = 0- def lock(self, cache_record: CacheRecord, working_mem_bytes: int | None) -> None:- del cache_record, working_mem_bytes+ def lock(self, cache_record: CacheRecord, working_mem_bytes: int | None, max_move_bytes: int | None = None) -> bool:+ del cache_record, working_mem_bytes, max_move_bytesself.lock_calls += 1+ return Truedef unlock(self, cache_record: CacheRecord) -> None:del cache_record