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): validate loader and IP-Adapter metadata
JPPhotoc6fc65c6e41a
diff --git a/invokeai/backend/model_manager/configs/factory.py b/invokeai/backend/model_manager/configs/factory.pyindex 6aa10f0bd9..27d1cc4d6d 100644--- a/invokeai/backend/model_manager/configs/factory.py+++ b/invokeai/backend/model_manager/configs/factory.py@@ -862,9 +862,17 @@ class ModelConfigFactory:for candidate_class in filter(lambda x: x is not Unknown_Config, Config_Base.CONFIG_CLASSES):candidate_name = candidate_class.__name__try:+ candidate_fields = fields+ # This config value comes from metadata, but its explicit override must reach its own probe.+ if (+ override_fields is not None+ and "image_encoder_model_id" in override_fields+ and "image_encoder_model_id" in candidate_class.model_fields+ ):+ candidate_fields = {**fields, "image_encoder_model_id": override_fields["image_encoder_model_id"]}# Technically, from_model_on_disk returns a Config_Base, but in practice it will always be a member of# the AnyModelConfig union.- details[candidate_name] = candidate_class.from_model_on_disk(mod, fields) # type: ignore+ details[candidate_name] = candidate_class.from_model_on_disk(mod, candidate_fields) # type: ignoreexcept NotAMatchError as e:# This means the model didn't match this config class. It's not an error, just no match.details[candidate_name] = ModelConfigFactory._detach_traceback(e)diff --git a/invokeai/backend/model_manager/configs/ip_adapter.py b/invokeai/backend/model_manager/configs/ip_adapter.pyindex ba27f17620..d0ca67fa60 100644--- a/invokeai/backend/model_manager/configs/ip_adapter.py+++ b/invokeai/backend/model_manager/configs/ip_adapter.py@@ -45,11 +45,11 @@ class IPAdapter_InvokeAI_Config_Base(IPAdapter_Config_Base):cls._validate_has_weights_file(mod)- cls._validate_has_image_encoder_metadata_file(mod)+ image_encoder_model_id = cls._get_image_encoder_model_id(mod, override_fields)cls._validate_base(mod)- return cls(**override_fields)+ return cls(**{**override_fields, "image_encoder_model_id": image_encoder_model_id})@classmethoddef _validate_base(cls, mod: ModelOnDisk) -> None:@@ -66,10 +66,16 @@ class IPAdapter_InvokeAI_Config_Base(IPAdapter_Config_Base):raise NotAMatchError("missing ip_adapter.bin weights file")@classmethod- def _validate_has_image_encoder_metadata_file(cls, mod: ModelOnDisk) -> None:+ def _get_image_encoder_model_id(cls, mod: ModelOnDisk, override_fields: dict[str, Any]) -> str:image_encoder_metadata_file = mod.path / "image_encoder.txt"if not image_encoder_metadata_file.exists():raise NotAMatchError("missing image_encoder.txt metadata file")+ if "image_encoder_model_id" in override_fields:+ return override_fields["image_encoder_model_id"]+ image_encoder_model_id = image_encoder_metadata_file.read_text(encoding="utf-8").strip()+ if not image_encoder_model_id:+ raise NotAMatchError("empty image_encoder.txt metadata")+ return image_encoder_model_id@classmethoddef _get_base_or_raise(cls, mod: ModelOnDisk) -> BaseModelType:diff --git a/invokeai/backend/model_manager/load/model_loaders/generic_diffusers.py b/invokeai/backend/model_manager/load/model_loaders/generic_diffusers.pyindex eaba4be434..9cfe0c391c 100644--- a/invokeai/backend/model_manager/load/model_loaders/generic_diffusers.py+++ b/invokeai/backend/model_manager/load/model_loaders/generic_diffusers.py@@ -1,11 +1,11 @@"""Class for simple diffusers model loading in InvokeAI."""-import sys+import importlib+import inspectfrom pathlib import Pathfrom typing import Any, Optionalfrom diffusers.configuration_utils import ConfigMixin-from diffusers.models.modeling_utils import ModelMixinfrom invokeai.backend.model_manager.configs.base import Diffusers_Config_Basefrom invokeai.backend.model_manager.configs.factory import AnyModelConfig@@ -49,43 +49,65 @@ class GenericDiffusersLoader(ModelLoader):result = self._apply_fp8_layerwise_casting(result, config, submodel_type)return result- # TO DO: Add exception handling- def get_hf_load_class(self, model_path: Path, submodel_type: Optional[SubModelType] = None) -> ModelMixin:- """Given the model path and submodel, returns the diffusers ModelMixin subclass needed to load."""- result = None+ def get_hf_load_class(self, model_path: Path, submodel_type: Optional[SubModelType] = None) -> type:+ """Return the class declared by a Diffusers or Transformers config."""if submodel_type:- try:- config = self._load_diffusers_config(model_path, config_name="model_index.json")- module, class_name = config[submodel_type.value]- result = self._hf_definition_to_type(module=module, class_name=class_name)- except KeyError as e:- raise ValueError(f'The "{submodel_type}" submodel is not available for this model.') from e+ config = self._load_diffusers_config(model_path, config_name="model_index.json")+ if not isinstance(config, dict):+ raise ValueError("model_index.json must contain a JSON object")+ definition = config.get(submodel_type.value)+ if not isinstance(definition, (list, tuple)) or len(definition) != 2:+ raise ValueError(f'The "{submodel_type}" submodel class metadata is missing or malformed.')+ module, class_name = definition+ if not isinstance(class_name, str) or not class_name.strip():+ raise ValueError(f'The "{submodel_type}" submodel class name must be a nonempty string.')+ if not isinstance(module, str) or not module:+ raise ValueError(f'The "{submodel_type}" submodel module must be a nonempty string.')+ return self._hf_definition_to_type(module=module, class_name=class_name)else:- try:- config = self._load_diffusers_config(model_path, config_name="config.json")- if class_name := config.get("_class_name"):- result = self._hf_definition_to_type(module="diffusers", class_name=class_name)- elif class_name := config.get("architectures"):- result = self._hf_definition_to_type(module="transformers", class_name=class_name[0])- else:- raise RuntimeError("Unable to decipher Load Class based on given config.json")- except KeyError as e:- raise ValueError("An expected config.json file is missing from this model.") from e- assert result is not None- return result+ config = self._load_diffusers_config(model_path, config_name="config.json")+ if not isinstance(config, dict):+ raise ValueError("config.json must contain a JSON object")++ if "_class_name" in config:+ class_name = config["_class_name"]+ if not isinstance(class_name, str) or not class_name.strip():+ raise ValueError("config.json _class_name must be a nonempty string")+ return self._hf_definition_to_type(module="diffusers", class_name=class_name)++ architectures = config.get("architectures")+ if (+ not isinstance(architectures, list)+ or not architectures+ or any(not isinstance(name, str) or not name.strip() for name in architectures)+ ):+ raise ValueError("config.json architectures must be a nonempty list of class names")+ return self._hf_definition_to_type(module="transformers", class_name=architectures[0])- # TO DO: Add exception handling- def _hf_definition_to_type(self, module: str, class_name: str) -> ModelMixin: # fix with correct type- if module in [+ def _hf_definition_to_type(self, module: str, class_name: str) -> type:+ """Resolve only known model namespaces and reject symbols that cannot load local weights."""+ known_modules = {"diffusers","transformers","invokeai.backend.quantization.fast_quantized_transformers_model","invokeai.backend.quantization.fast_quantized_diffusion_model",- ]:- res_type = sys.modules[module]- else:- res_type = sys.modules["diffusers"].pipelines- result: ModelMixin = getattr(res_type, class_name)+ }+ try:+ if module in known_modules:+ namespace = importlib.import_module(module)+ elif module == "stable_diffusion":+ namespace = importlib.import_module("diffusers.pipelines.stable_diffusion")+ elif module == "diffusers.pipelines" or module.startswith("diffusers.pipelines."):+ # Diffusers indexes use both `diffusers` and pipeline module paths. The old resolver exposed+ # pipeline classes through the top-level pipelines namespace for either path.+ namespace = importlib.import_module("diffusers.pipelines")+ else:+ raise ValueError(f"Unsupported model class module {module!r}")+ result = getattr(namespace, class_name)+ if not inspect.isclass(result) or not callable(getattr(result, "from_pretrained", None)):+ raise TypeError(f"{class_name!r} is not a loadable class")+ except Exception as e:+ raise ValueError(f"Unable to resolve loadable model class {class_name!r} from {module!r}") from ereturn resultdef _load_diffusers_config(self, model_path: Path, config_name: str = "config.json") -> dict[str, Any]:diff --git a/tests/backend/model_manager/configs/test_ip_adapter_config.py b/tests/backend/model_manager/configs/test_ip_adapter_config.pyindex 5c5989b1df..68314b3249 100644--- a/tests/backend/model_manager/configs/test_ip_adapter_config.py+++ b/tests/backend/model_manager/configs/test_ip_adapter_config.py@@ -21,3 +21,34 @@ def test_invokeai_ip_adapter_probe_normalizes_image_encoder_metadata(tmp_path: Passert isinstance(result.config, IPAdapter_InvokeAI_SD1_Config)assert result.config.image_encoder_model_id == "InvokeAI/ip_adapter_sd_image_encoder"+++def test_invokeai_ip_adapter_probe_rejects_empty_image_encoder_metadata(tmp_path: Path) -> None:+ torch.save({"ip_adapter": {"1.to_k_ip.weight": torch.empty(1, 768)}}, tmp_path / "ip_adapter.bin")+ (tmp_path / "image_encoder.txt").write_text(" \r\n\t", encoding="utf-8")++ result = ModelConfigFactory.from_model_on_disk(tmp_path, allow_unknown=False)++ assert result.config is None+ assert any("empty image_encoder.txt metadata" in str(error) for error in result.details.values())+++def test_invokeai_ip_adapter_probe_uses_encoder_override_without_mutating_it(tmp_path: Path) -> None:+ torch.save({"ip_adapter": {"1.to_k_ip.weight": torch.empty(1, 768)}}, tmp_path / "ip_adapter.bin")+ (tmp_path / "image_encoder.txt").write_text(" \n", encoding="utf-8")+ overrides = {"image_encoder_model_id": "custom/image-encoder"}++ result = ModelConfigFactory.from_model_on_disk(tmp_path, override_fields=overrides, allow_unknown=False)++ assert isinstance(result.config, IPAdapter_InvokeAI_SD1_Config)+ assert result.config.image_encoder_model_id == "custom/image-encoder"+ assert overrides == {"image_encoder_model_id": "custom/image-encoder"}+++def test_invokeai_ip_adapter_probe_rejects_missing_image_encoder_metadata(tmp_path: Path) -> None:+ torch.save({"ip_adapter": {"1.to_k_ip.weight": torch.empty(1, 768)}}, tmp_path / "ip_adapter.bin")++ result = ModelConfigFactory.from_model_on_disk(tmp_path, allow_unknown=False)++ assert result.config is None+ assert any("missing image_encoder.txt metadata file" in str(error) for error in result.details.values())diff --git a/tests/backend/model_manager/load/test_generic_diffusers_loader_boundaries.py b/tests/backend/model_manager/load/test_generic_diffusers_loader_boundaries.pyindex 7c632d8f69..e1e948eb67 100644--- a/tests/backend/model_manager/load/test_generic_diffusers_loader_boundaries.py+++ b/tests/backend/model_manager/load/test_generic_diffusers_loader_boundaries.py@@ -6,6 +6,7 @@ from pathlib import Pathimport pytestfrom invokeai.backend.model_manager.load.model_loaders.generic_diffusers import GenericDiffusersLoader+from invokeai.backend.model_manager.taxonomy import SubModelType@pytest.mark.parametrize(@@ -48,6 +49,77 @@ def test_generic_diffusers_loader_accepts_a_real_loadable_class(tmp_path: Path)assert loader.get_hf_load_class(tmp_path) is AutoencoderKL+def test_generic_diffusers_loader_accepts_a_real_transformers_class(tmp_path: Path) -> None:+ from transformers import T5EncoderModel++ (tmp_path / "config.json").write_text(json.dumps({"architectures": ["T5EncoderModel"]}), encoding="utf-8")+ loader = object.__new__(GenericDiffusersLoader)++ assert loader.get_hf_load_class(tmp_path) is T5EncoderModel+++def test_generic_diffusers_loader_accepts_a_diffusers_submodel_class(tmp_path: Path) -> None:+ from diffusers import EulerDiscreteScheduler++ (tmp_path / "model_index.json").write_text(+ json.dumps({"scheduler": ["diffusers", "EulerDiscreteScheduler"]}), encoding="utf-8"+ )+ loader = object.__new__(GenericDiffusersLoader)++ assert loader.get_hf_load_class(tmp_path, SubModelType.Scheduler) is EulerDiscreteScheduler+++def test_generic_diffusers_loader_accepts_a_pipeline_namespace_class(tmp_path: Path) -> None:+ from diffusers import StableDiffusionPipeline++ loader = object.__new__(GenericDiffusersLoader)++ # Some model indexes name pipeline submodules instead of the top-level Diffusers namespace.+ assert loader._hf_definition_to_type("diffusers.pipelines.stable_diffusion", "StableDiffusionPipeline") is (+ StableDiffusionPipeline+ )+++def test_generic_diffusers_loader_accepts_short_pipeline_namespace_in_model_index(tmp_path: Path) -> None:+ from diffusers.pipelines.stable_diffusion import StableDiffusionSafetyChecker++ (tmp_path / "model_index.json").write_text(+ json.dumps({"safety_checker": ["stable_diffusion", "StableDiffusionSafetyChecker"]}), encoding="utf-8"+ )+ loader = object.__new__(GenericDiffusersLoader)++ assert loader.get_hf_load_class(tmp_path, SubModelType.SafetyChecker) is StableDiffusionSafetyChecker+++ "model_index",+ [+ [],+ {},+ {"scheduler": []},+ {"scheduler": ["diffusers"]},+ {"scheduler": [123, "EulerDiscreteScheduler"]},+ {"scheduler": ["diffusers", 123]},+ {"scheduler": ["untrusted.module", "EulerDiscreteScheduler"]},+ {"scheduler": ["diffusers", "NotARealScheduler"]},+ {"scheduler": ["diffusers", "ConfigMixin"]},+ ],+)+def test_generic_diffusers_loader_rejects_invalid_submodel_metadata(tmp_path: Path, model_index: object) -> None:+ (tmp_path / "model_index.json").write_text(json.dumps(model_index), encoding="utf-8")+ loader = object.__new__(GenericDiffusersLoader)++ with pytest.raises(ValueError):+ loader.get_hf_load_class(tmp_path, SubModelType.Scheduler)+++def test_generic_diffusers_loader_preserves_missing_config_oserror(tmp_path: Path) -> None:+ loader = object.__new__(GenericDiffusersLoader)++ with pytest.raises(OSError):+ loader.get_hf_load_class(tmp_path)++def test_generic_diffusers_loader_rejects_non_object_config(tmp_path: Path) -> None:(tmp_path / "config.json").write_text('["AutoencoderKL"]', encoding="utf-8")loader = object.__new__(GenericDiffusersLoader)