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
fix(model-manager): retry superseded loads in the load service
Lincoln Steine3ae73a04262
diff --git a/docs/src/content/docs/development/Architecture/model-manager.mdx b/docs/src/content/docs/development/Architecture/model-manager.mdxindex 94cde57a8d..e22edfb46f 100644--- a/docs/src/content/docs/development/Architecture/model-manager.mdx+++ b/docs/src/content/docs/development/Architecture/model-manager.mdx@@ -969,7 +969,7 @@ The optional second argument, `subtype` is a `SubModelType` string enum, such asThe optional third argument, `context` can be provided by an invocation to trigger model load event reporting. See below for details.-If the model has to be built (it is not in the calling device's cache) and its record was edited in a way that changes how it loads (for example its `cpu_only` or `fp8_storage` setting) after the caller read `model_config`, `load_model()` raises `StaleModelConfigError` rather than caching a model built from the superseded record. Read the record again and retry; an invocation's `context.models.load()` does this once itself.+If the model has to be built (it is not in the calling device's cache) and its record was edited in a way that changes how it loads (for example its `cpu_only` or `fp8_storage` setting) after the caller read `model_config`, `load_model()` does not cache a model built from the superseded record: it reads the record again and loads that instead. If the record changes again during that retry, it raises `StaleModelConfigError`.The returned `LoadedModel` object contains a copy of the configuration record returned by the model record`get_model()` method, as well as the in-memory loaded model:diff --git a/invokeai/app/services/model_load/model_load_default.py b/invokeai/app/services/model_load/model_load_default.pyindex 4274f0fab5..8470f2dee6 100644--- a/invokeai/app/services/model_load/model_load_default.py+++ b/invokeai/app/services/model_load/model_load_default.py@@ -19,6 +19,7 @@ from invokeai.backend.model_manager.load import (ModelLoader,ModelLoaderRegistry,ModelLoaderRegistryBase,+ StaleModelConfigError,)from invokeai.backend.model_manager.load.model_cache.model_cache import MODEL_LOAD_LOCK, ModelCachefrom invokeai.backend.model_manager.load.model_loaders.generic_diffusers import GenericDiffusersLoader@@ -94,6 +95,22 @@ class ModelLoadService(ModelLoadServiceBase):if hasattr(self, "_invoker"):self._invoker.services.events.emit_model_load_started(model_config, submodel_type, user_id or "system")+ try:+ loaded_model = self._load(model_config, submodel_type)+ except StaleModelConfigError:+ # The edit has already invalidated the cache, so loading what the record says now is what this+ # call would have done had it been made a moment later. Retried here rather than by callers so+ # every caller gets it and the load events stay paired.+ loaded_model = self._load(+ self._invoker.services.model_manager.store.get_model(model_config.key), submodel_type+ )++ if hasattr(self, "_invoker"):+ self._invoker.services.events.emit_model_load_complete(model_config, submodel_type, user_id or "system")++ return loaded_model++ def _load(self, model_config: AnyModelConfig, submodel_type: Optional[SubModelType]) -> LoadedModel:implementation, model_config, submodel_type = self._registry.get_implementation(model_config, submodel_type) # type: ignoreloader = implementation(app_config=self._app_config,@@ -102,12 +119,7 @@ class ModelLoadService(ModelLoadServiceBase):)if hasattr(self, "_invoker") and isinstance(loader, ModelLoader):loader.config_is_current = self._config_is_current- loaded_model: LoadedModel = loader.load_model(model_config, submodel_type)-- if hasattr(self, "_invoker"):- self._invoker.services.events.emit_model_load_complete(model_config, submodel_type, user_id or "system")-- return loaded_model+ return loader.load_model(model_config, submodel_type)def _config_is_current(self, config: AnyModelConfig) -> bool:"""Whether `config` still loads the same model as the stored record for its key.diff --git a/invokeai/app/services/shared/invocation_context.py b/invokeai/app/services/shared/invocation_context.pyindex 8d36b035f0..2be9fc0103 100644--- a/invokeai/app/services/shared/invocation_context.py+++ b/invokeai/app/services/shared/invocation_context.py@@ -25,7 +25,7 @@ from invokeai.app.services.wildcard_records.wildcard_records_common import buildfrom invokeai.app.util.step_callback import diffusion_step_callbackfrom invokeai.backend.model_manager.configs.base import Config_Basefrom invokeai.backend.model_manager.configs.factory import AnyModelConfig-from invokeai.backend.model_manager.load.load_base import LoadedModel, LoadedModelWithoutConfig, StaleModelConfigError+from invokeai.backend.model_manager.load.load_base import LoadedModel, LoadedModelWithoutConfigfrom invokeai.backend.model_manager.taxonomy import AnyModel, BaseModelType, ModelFormat, ModelType, SubModelTypefrom invokeai.backend.stable_diffusion.diffusers_pipeline import PipelineIntermediateStatefrom invokeai.backend.stable_diffusion.diffusion.conditioning_data import ConditioningFieldData@@ -601,7 +601,7 @@ class ModelsInterface(InvocationContextInterface):if submodel_type:message += f" ({submodel_type.value})"self._util.signal_progress(message)- return self._load_current(model, submodel_type)+ return self._services.model_manager.load.load_model(model, submodel_type, user_id=self._data.queue_item.user_id)def load_by_attrs(self, name: str, base: BaseModelType, type: ModelType, submodel_type: Optional[SubModelType] = None@@ -631,20 +631,9 @@ class ModelsInterface(InvocationContextInterface):if submodel_type:message += f" ({submodel_type.value})"self._util.signal_progress(message)- return self._load_current(configs[0], submodel_type)-- def _load_current(self, model: AnyModelConfig, submodel_type: Optional[SubModelType]) -> LoadedModel:- """Load `model`, re-reading its record once if a load-affecting edit superseded it mid-load."""- load = self._services.model_manager.load- user_id = self._data.queue_item.user_id- try:- return load.load_model(model, submodel_type, user_id=user_id)- except StaleModelConfigError:- # The edit has already invalidated the cache; loading what the record says now is what- # this call would have done had it been made a moment later.- model = self._services.model_manager.store.get_model(model.key)- self._raise_if_external(model)- return load.load_model(model, submodel_type, user_id=user_id)+ return self._services.model_manager.load.load_model(+ configs[0], submodel_type, user_id=self._data.queue_item.user_id+ )def offload_from_vram(self, identifier: Union[str, "ModelIdentifierField"]) -> int:"""Move a model (and all of its submodels) from VRAM to RAM, freeing its VRAM but keeping it cached.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.pyindex 2b1afb1692..7b3f00afe7 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@@ -6,7 +6,6 @@ import timefrom pathlib import Pathfrom types import SimpleNamespacefrom typing import Callable, Optional-from unittest.mock import MagicMockimport pytestimport torch@@ -14,7 +13,6 @@ import torchfrom invokeai.app.services.config import InvokeAIAppConfigfrom invokeai.app.services.model_load.model_load_default import ModelLoadServicefrom invokeai.app.services.model_records import ModelRecordChanges, ModelRecordServiceSQL-from invokeai.app.services.shared.invocation_context import ModelsInterfacefrom invokeai.backend.model_manager.configs.factory import AnyModelConfigfrom invokeai.backend.model_manager.configs.siglip import SigLIP_Diffusers_Configfrom invokeai.backend.model_manager.load import LoadedModel, ModelCache, ModelLoader, StaleModelConfigError@@ -42,8 +40,17 @@ class _Registry:return _RecordingLoader, config, submodel_type-def _noop(*args, **kwargs) -> None:- return None+class _LoadEvents:+ """Records the model load events in order, as (event, model name)."""++ def __init__(self) -> None:+ self.log: list[tuple[str, str]] = []++ def emit_model_load_started(self, config: AnyModelConfig, submodel_type, user_id: str) -> None:+ self.log.append(("started", config.name))++ def emit_model_load_complete(self, config: AnyModelConfig, submodel_type, user_id: str) -> None:+ self.log.append(("complete", config.name))@pytest.fixture@@ -71,9 +78,9 @@ def harness(tmp_path: Path):shared_cpu_weights=None,)service = ModelLoadService(app_config=app_config, ram_cache=cache, registry=_Registry) # type: ignore[arg-type]- events = SimpleNamespace(emit_model_load_started=_noop, emit_model_load_complete=_noop)+ events = _LoadEvents()service.start(SimpleNamespace(services=SimpleNamespace(events=events, model_manager=SimpleNamespace(store=store)))) # type: ignore[arg-type]- return service, store, cache+ return service, store, cache, eventsdef _edit_and_invalidate(store: ModelRecordServiceSQL, cache: ModelCache, changes: ModelRecordChanges) -> None:@@ -91,25 +98,22 @@ def _is_cached(cache: ModelCache) -> bool:return True-def test_load_from_record_read_before_invalidating_edit_is_rejected_and_not_cached(harness):- service, store, cache = harness+def test_load_from_record_read_before_invalidating_edit_loads_the_updated_record(harness):+ service, store, cache, events = harnessstale = store.get_model(KEY)_edit_and_invalidate(store, cache, ModelRecordChanges(cpu_only=True))- with pytest.raises(StaleModelConfigError):- service.load_model(stale)- assert not _is_cached(cache)- assert _RecordingLoader.built_from == []-- loaded = service.load_model(store.get_model(KEY))+ loaded = service.load_model(stale)assert loaded.config.cpu_only is Trueassert _RecordingLoader.built_from == [True]assert _is_cached(cache)+ # One load as far as the UI can tell: a retry that re-announced itself would leave a load showing.+ assert events.log == [("started", "siglip"), ("complete", "siglip")]def test_load_from_record_read_before_metadata_only_edit_still_loads(harness):- service, store, cache = harness+ service, store, cache, _ = harnessprevious = store.get_model(KEY)# A rename does not invalidate the cache, so nothing fences a load that read the old name.@@ -147,34 +151,25 @@ def _run_with_edit_while_queued_on_construction_lock(return outcome[0]-def test_load_waiting_on_construction_lock_during_invalidating_edit_is_rejected(harness):- service, store, cache = harness+def test_load_waiting_on_construction_lock_during_invalidating_edit_loads_the_updated_record(harness):+ service, store, cache, events = harnessoutcome = _run_with_edit_while_queued_on_construction_lock(store, cache, lambda: service.load_model(store.get_model(KEY)))- assert isinstance(outcome, StaleModelConfigError)- assert _RecordingLoader.built_from == []- assert not _is_cached(cache)---def test_invocation_load_superseded_mid_load_loads_the_updated_record(harness):- service, store, cache = harness- services = SimpleNamespace(model_manager=SimpleNamespace(store=store, load=service))- models = ModelsInterface(services=services, data=MagicMock(), util=MagicMock()) # type: ignore[arg-type]-- outcome = _run_with_edit_while_queued_on_construction_lock(store, cache, lambda: models.load(KEY))-assert isinstance(outcome, LoadedModel)assert outcome.config.cpu_only is True+ # Built once, from the updated record: the stale construction never ran.assert _RecordingLoader.built_from == [True]+ # One load as far as the UI can tell: a retry that re-announced itself would leave a load showing.+ assert events.log == [("started", "siglip"), ("complete", "siglip")]def test_config_object_reused_after_eviction_still_loads(harness):"""The loader rewrites `config.path` to an absolute path in place; a service that keeps its configobject across loads must not see that as a load-affecting edit."""- service, store, cache = harness+ service, store, cache, _ = harnessconfig = store.get_model(KEY)# Use it once so its first-use hold is released and the drop below evicts it outright.with service.load_model(config):@@ -184,3 +179,19 @@ def test_config_object_reused_after_eviction_still_loads(harness):service.load_model(config)assert _RecordingLoader.built_from == [None, None]+++def test_record_superseded_again_during_retry_raises(harness, monkeypatch):+ service, store, _, _ = harness+ fence_checks: list[str] = []++ def never_current(config: AnyModelConfig) -> bool:+ fence_checks.append(config.key)+ return False++ monkeypatch.setattr(service, "_config_is_current", never_current)++ with pytest.raises(StaleModelConfigError):+ service.load_model(store.get_model(KEY))+ assert fence_checks == [KEY, KEY]+ assert _RecordingLoader.built_from == []