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(model-manager): refuse model loaders that bypass the stale-config check

Lincoln Steinf58893881e0d
diff --git a/docs/src/content/docs/development/Architecture/model-manager.mdx b/docs/src/content/docs/development/Architecture/model-manager.mdx
index 6f9012b9e7..846883395b 100644
--- a/docs/src/content/docs/development/Architecture/model-manager.mdx
+++ b/docs/src/content/docs/development/Architecture/model-manager.mdx
@@ -1005,7 +1005,7 @@ def _load_model(
`_load_model()` will be passed the path to the model on disk, an optional repository variant (used by the diffusers loaders to select, e.g. the `fp16` variant, and an optional submodel_type for main and onnx models.
-To install a new loader, place it in `invokeai/backend/model_manager/load/model_loaders`. Inherit from `ModelLoader` and use the `@ModelLoaderRegistry.register()` decorator to indicate what type of models the loader can handle.
+To install a new loader, place it in `invokeai/backend/model_manager/load/model_loaders`. Inherit from `ModelLoader`, which checks a cold load against edits of its record (the registry refuses any other class), and use the `@ModelLoaderRegistry.register()` decorator to indicate what type of models the loader can handle.
Here is a complete example from `generic_diffusers.py`, which is able to load several different diffusers types:
diff --git a/invokeai/app/services/model_load/model_load_default.py b/invokeai/app/services/model_load/model_load_default.py
index 4012ca53c0..704b4b1d83 100644
--- a/invokeai/app/services/model_load/model_load_default.py
+++ b/invokeai/app/services/model_load/model_load_default.py
@@ -193,7 +193,10 @@ class ModelLoadService(ModelLoadServiceBase):
logger=self._logger,
ram_cache=self.ram_cache,
)
- if hasattr(self, "_invoker") and isinstance(loader, ModelLoader):
+ if not isinstance(loader, ModelLoader):
+ # Only `ModelLoader` applies the stale-config check before admitting a model to the cache.
+ raise TypeError(f"{implementation!r} is not a ModelLoader, so it cannot be loaded safely")
+ if hasattr(self, "_invoker"):
loader.config_check = self._check_config
return loader.load_model(model_config, submodel_type)
diff --git a/invokeai/backend/model_manager/load/model_loader_registry.py b/invokeai/backend/model_manager/load/model_loader_registry.py
index db1a462f93..3e2c2b7ab0 100644
--- a/invokeai/backend/model_manager/load/model_loader_registry.py
+++ b/invokeai/backend/model_manager/load/model_loader_registry.py
@@ -14,13 +14,14 @@ Use like this:
"""
+import inspect
from abc import ABC, abstractmethod
from typing import Callable, Dict, Optional, Tuple, Type, TypeVar
from invokeai.backend.model_manager.configs.base import Config_Base
from invokeai.backend.model_manager.configs.factory import AnyModelConfig
-from invokeai.backend.model_manager.load import ModelLoaderBase
from invokeai.backend.model_manager.load.fp8_capability import Fp8StorageDeclaration, declare_fp8_storage
+from invokeai.backend.model_manager.load.load_default import ModelLoader
from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelFormat, ModelType, SubModelType
@@ -35,16 +36,16 @@ class ModelLoaderRegistryBase(ABC):
format: ModelFormat,
base: BaseModelType = BaseModelType.Any,
fp8_storage: Fp8StorageDeclaration = None,
- ) -> Callable[[Type[ModelLoaderBase]], Type[ModelLoaderBase]]:
+ ) -> Callable[[Type[ModelLoader]], Type[ModelLoader]]:
"""Define a decorator which registers the subclass of loader."""
@classmethod
@abstractmethod
def get_implementation(
cls, config: AnyModelConfig, submodel_type: Optional[SubModelType]
- ) -> Tuple[Type[ModelLoaderBase], Config_Base, Optional[SubModelType]]:
+ ) -> Tuple[Type[ModelLoader], Config_Base, Optional[SubModelType]]:
"""
- Get subclass of ModelLoaderBase registered to handle base and type.
+ Get subclass of ModelLoader registered to handle base and type.
Parameters:
:param config: Model configuration record, as returned by ModelRecordService
@@ -56,7 +57,7 @@ class ModelLoaderRegistryBase(ABC):
"""
-TModelLoader = TypeVar("TModelLoader", bound=ModelLoaderBase)
+TModelLoader = TypeVar("TModelLoader", bound=ModelLoader)
class ModelLoaderRegistry(ModelLoaderRegistryBase):
@@ -64,7 +65,7 @@ class ModelLoaderRegistry(ModelLoaderRegistryBase):
This class allows model loaders to register their type, base and format.
"""
- _registry: Dict[str, Type[ModelLoaderBase]] = {}
+ _registry: Dict[str, Type[ModelLoader]] = {}
@classmethod
def register(
@@ -83,6 +84,10 @@ class ModelLoaderRegistry(ModelLoaderRegistryBase):
"""
def decorator(subclass: Type[TModelLoader]) -> Type[TModelLoader]:
+ # `ModelLoader` is where a cold load is checked against edits of its record, so a loader built
+ # directly on `ModelLoaderBase` could cache a model built from a superseded record.
+ if not (inspect.isclass(subclass) and issubclass(subclass, ModelLoader)):
+ raise TypeError(f"{subclass!r} must subclass ModelLoader to be registered as a model loader")
key = cls._to_registry_key(base, type, format)
if key in cls._registry:
raise Exception(
@@ -97,8 +102,8 @@ class ModelLoaderRegistry(ModelLoaderRegistryBase):
@classmethod
def get_implementation(
cls, config: AnyModelConfig, submodel_type: Optional[SubModelType]
- ) -> Tuple[Type[ModelLoaderBase], Config_Base, Optional[SubModelType]]:
- """Get subclass of ModelLoaderBase registered to handle base and type."""
+ ) -> Tuple[Type[ModelLoader], Config_Base, Optional[SubModelType]]:
+ """Get subclass of ModelLoader registered to handle base and type."""
key1 = cls._to_registry_key(config.base, config.type, config.format) # for a specific base type
key2 = cls._to_registry_key(BaseModelType.Any, config.type, config.format) # with wildcard Any
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.py
index 26a3d29e9f..becd772141 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
@@ -16,7 +16,13 @@ from invokeai.app.services.model_load.model_load_default import ModelLoadService
from invokeai.app.services.model_records import ModelRecordChanges, ModelRecordServiceSQL
from invokeai.backend.model_manager.configs.factory import AnyModelConfig
from invokeai.backend.model_manager.configs.siglip import SigLIP_Diffusers_Config
-from invokeai.backend.model_manager.load import LoadedModel, ModelCache, ModelLoader, StaleModelConfigError
+from invokeai.backend.model_manager.load import (
+ LoadedModel,
+ ModelCache,
+ ModelLoader,
+ ModelLoaderBase,
+ StaleModelConfigError,
+)
from invokeai.backend.model_manager.load.model_cache.model_cache import MODEL_LOAD_LOCK
from invokeai.backend.model_manager.taxonomy import AnyModel, SubModelType
from invokeai.backend.util.logging import InvokeAILogger
@@ -484,3 +490,40 @@ def test_rename_then_load_affecting_edit_while_a_load_waits_rejects_it(harness,
assert len(outcome) == 1 and outcome[0].config.cpu_only is True
assert _RecordingLoader.built_from == [True]
+
+
+class _UnfencedLoader(ModelLoaderBase):
+ """Built directly on the base, so nothing checks its config against record edits before it caches."""
+
+ def __init__(self, app_config, logger, ram_cache: ModelCache) -> None:
+ self._ram_cache = ram_cache
+
+ @property
+ def ram_cache(self) -> ModelCache:
+ return self._ram_cache
+
+ def get_size_fs(self, config, model_path, submodel_type=None) -> int:
+ return 0
+
+ def load_model(self, model_config: AnyModelConfig, submodel_type: Optional[SubModelType] = None) -> LoadedModel:
+ self._ram_cache.put(model_config.key, torch.nn.Linear(2, 2))
+ return LoadedModel(
+ config=model_config, cache_record=self._ram_cache.get(model_config.key), cache=self._ram_cache
+ )
+
+
+def test_loader_built_directly_on_the_base_is_refused_before_it_can_cache(harness, monkeypatch):
+ """A registry is free to hand the service any class, so the service refuses one that skips the check."""
+ service, store, cache, events = harness
+
+ class _UnfencedRegistry:
+ @classmethod
+ def get_implementation(cls, config: AnyModelConfig, submodel_type: Optional[SubModelType]):
+ return _UnfencedLoader, config, submodel_type
+
+ monkeypatch.setattr(service, "_registry", _UnfencedRegistry)
+
+ with pytest.raises(TypeError, match="not a ModelLoader"):
+ service.load_model(store.get_model(KEY))
+ assert not _is_cached(cache)
+ assert events.log == [("started", "siglip"), ("complete", "siglip")]
diff --git a/tests/backend/model_manager/load/test_model_loader_registry_entries.py b/tests/backend/model_manager/load/test_model_loader_registry_entries.py
index 84fc6cb59c..6e3590e7dc 100644
--- a/tests/backend/model_manager/load/test_model_loader_registry_entries.py
+++ b/tests/backend/model_manager/load/test_model_loader_registry_entries.py
@@ -1,49 +1,51 @@
-"""Every registry entry must be an instantiable loader class.
-
-`ModelLoaderRegistry.register` does no runtime type check and returns its argument unchanged, so it
-happily decorates whatever follows it. Insert a helper function between the decorator and the class
-it was meant to decorate — a plausible outcome of extracting a loop into a named function — and the
-registry silently binds the helper instead. The helper keeps working everywhere it is called
-directly, the module imports, ruff is clean and the whole suite passes; the only symptom is that
-`ModelLoadService.load_model` calls `implementation(app_config=..., logger=..., ram_cache=...)` and
-gets `TypeError: <helper>() got an unexpected keyword argument 'app_config'` — i.e. that model type
-can no longer be loaded at all.
-
-This happened to `Qwen3EncoderCheckpointLoader`. One assertion over the whole registry closes the
-class, so it cannot happen again to a loader nobody has an end-to-end test for.
+"""`ModelLoaderRegistry.register` refuses anything but a `ModelLoader` subclass.
+
+Insert a helper function between the decorator and the class it was meant to decorate — a plausible
+outcome of extracting a loop into a named function — and a decorator without a type check binds the
+helper instead. The module imports and the helper keeps working where it is called directly; the only
+symptom is that `ModelLoadService.load_model` calls `implementation(app_config=..., ...)` and gets a
+`TypeError`, i.e. that model type can no longer be loaded at all. This happened to
+`Qwen3EncoderCheckpointLoader`.
+
+A class built directly on `ModelLoaderBase` is refused too: `ModelLoader` is where a cold load is checked
+against edits of its record, so such a loader could cache a model built from a superseded record.
"""
-import importlib
-import inspect
-import pkgutil
+from typing import Optional
+
+import pytest
-import invokeai.backend.model_manager.load.model_loaders as model_loaders_pkg
-from invokeai.backend.model_manager.load.load_base import ModelLoaderBase
+from invokeai.backend.model_manager.load.load_base import LoadedModel, ModelLoaderBase
from invokeai.backend.model_manager.load.model_loader_registry import ModelLoaderRegistry
+from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelFormat, ModelType, SubModelType
+
+
+class _DirectLoader(ModelLoaderBase):
+ def __init__(self, app_config, logger, ram_cache) -> None:
+ pass
+
+ @property
+ def ram_cache(self):
+ raise NotImplementedError
+ def get_size_fs(self, config, model_path, submodel_type: Optional[SubModelType] = None) -> int:
+ return 0
-def _import_every_loader_module() -> None:
- """Registration is an import side effect, so nothing is in the registry until this runs."""
- for module in pkgutil.iter_modules(model_loaders_pkg.__path__):
- importlib.import_module(f"{model_loaders_pkg.__name__}.{module.name}")
+ def load_model(self, model_config, submodel_type: Optional[SubModelType] = None) -> LoadedModel:
+ raise NotImplementedError
-def test_every_registered_implementation_is_a_loader_class() -> None:
- _import_every_loader_module()
- assert ModelLoaderRegistry._registry, "no loaders registered — the import sweep above is broken"
+def _helper() -> None:
+ pass
- not_classes = {key: impl for key, impl in ModelLoaderRegistry._registry.items() if not inspect.isclass(impl)}
- assert not not_classes, (
- "these registry keys are bound to something that is not a class, so instantiating them at "
- f"load time raises TypeError: {not_classes}"
- )
[email protected]("implementation", [_helper, _DirectLoader], ids=["function", "direct-base-subclass"])
+def test_register_refuses_anything_but_a_model_loader(implementation) -> None:
+ before = dict(ModelLoaderRegistry._registry)
-def test_every_registered_implementation_subclasses_the_loader_base() -> None:
- """A class is not enough on its own — `load_model` also needs the base's constructor signature."""
- _import_every_loader_module()
+ with pytest.raises(TypeError, match="must subclass ModelLoader"):
+ ModelLoaderRegistry.register(base=BaseModelType.Any, type=ModelType.Main, format=ModelFormat.Diffusers)(
+ implementation
+ )
- wrong_base = {
- key: impl for key, impl in ModelLoaderRegistry._registry.items() if not issubclass(impl, ModelLoaderBase)
- }
- assert not wrong_base, f"registered implementations that are not ModelLoaderBase subclasses: {wrong_base}"
+ assert ModelLoaderRegistry._registry == before