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): refuse SD 1.x, 2.x and SDXL GGUF files at install (#9965)
Alexander Eichhorn5524e8b65fab
diff --git a/docs/src/content/docs/Users Guide/03.Models/03.model-format-support.mdx b/docs/src/content/docs/Users Guide/03.Models/03.model-format-support.mdxindex 5b8574b185..97bc1dc0be 100644--- a/docs/src/content/docs/Users Guide/03.Models/03.model-format-support.mdx+++ b/docs/src/content/docs/Users Guide/03.Models/03.model-format-support.mdx@@ -1,7 +1,7 @@---title: Model Format Supportdescription: Which file formats and quantizations InvokeAI loads for every model family, text encoder, VAE and adapter.-lastUpdated: 2026-10-18+lastUpdated: 2026-10-21sidebar:order: 3---@@ -27,7 +27,7 @@ Ministral 3B encoder. Others are recognized by their layer names and fail, or mi| Family | Diffusers | Single file (bf16) | fp8 scaled | int8 | nvfp4 | MXFP8 | GGUF | SDNQ | NF4 ||---|---|---|---|---|---|---|---|---|---|-| [SD 1.x / 2.x](/users-guide/models/local-models/stable-diffusion-1-2/), [SDXL](/users-guide/models/local-models/sdxl/) | ✓ | ✓ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ |+| [SD 1.x / 2.x](/users-guide/models/local-models/stable-diffusion-1-2/), [SDXL](/users-guide/models/local-models/sdxl/) | ✓ | ✓ | ✗ | ✗ | ✗ | ✗ | R | ✗ | ✗ || [SD 3](/users-guide/models/local-models/sd-3/) | ✓ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ || [FLUX.1](/users-guide/models/local-models/flux-1/) | ✓ | ✓ | ✓ | ✓ | ✗ | ✓ | ✓ | ✓ | ✓ || [FLUX.2](/users-guide/models/local-models/flux-2/) | ✓ | ✓ | ✓ | ✓ | ✗ | ✓ | ✓ | ✓ | inside the Diffusers folder (FLUX.2 [dev]) |diff --git a/invokeai/backend/model_manager/configs/controlnet.py b/invokeai/backend/model_manager/configs/controlnet.pyindex 24faa05a88..51066c2a9e 100644--- a/invokeai/backend/model_manager/configs/controlnet.py+++ b/invokeai/backend/model_manager/configs/controlnet.py@@ -21,6 +21,7 @@ from invokeai.backend.model_manager.configs.identification_utils import (raise_if_not_file,state_dict_has_any_keys_starting_with,)+from invokeai.backend.model_manager.configs.main import _bare_sd_unet_base, _has_ggml_tensorsfrom invokeai.backend.model_manager.model_on_disk import ModelOnDiskfrom invokeai.backend.model_manager.taxonomy import (BaseModelType,@@ -171,8 +172,9 @@ class ControlNet_Checkpoint_Config_Base(Checkpoint_Config_Base):@classmethoddef _validate_looks_like_controlnet(cls, mod: ModelOnDisk) -> None:+ state_dict = mod.load_state_dict()if not state_dict_has_any_keys_starting_with(- mod.load_state_dict(),+ state_dict,{"controlnet","control_model",@@ -187,6 +189,11 @@ class ControlNet_Checkpoint_Config_Base(Checkpoint_Config_Base):):raise NotAMatchError("state dict does not look like a ControlNet checkpoint")+ # A bare SD UNet in GGUF has `input_blocks.*` keys too. The main-model configs refuse it with their reason;+ # claimed here, it would install as a ControlNet that fails to load.+ if _bare_sd_unet_base(state_dict) is not None and _has_ggml_tensors(state_dict):+ raise NotAMatchError("state dict is a GGUF Stable Diffusion UNet, not a ControlNet")+@classmethoddef _get_base_or_raise(cls, mod: ModelOnDisk) -> BaseModelType:state_dict = mod.load_state_dict()diff --git a/invokeai/backend/model_manager/configs/main.py b/invokeai/backend/model_manager/configs/main.pyindex bd29739671..925dc7f09b 100644--- a/invokeai/backend/model_manager/configs/main.py+++ b/invokeai/backend/model_manager/configs/main.py@@ -43,6 +43,7 @@ from invokeai.backend.model_manager.configs.identification_utils import (raise_if_not_dir,raise_if_not_file,state_dict_has_any_keys_exact,+ state_dict_has_any_keys_starting_with,)from invokeai.backend.model_manager.configs.qwen3_encoder import _SDNQ_LOADABLE_QWEN_ARCHITECTURESfrom invokeai.backend.model_manager.model_on_disk import ModelOnDisk@@ -251,6 +252,54 @@ def _has_krea2_keys(state_dict: dict[str | int, Any]) -> bool:return has_text_fusion and has_corroborator+_SD_GGUF_UNSUPPORTED = (+ "Stable Diffusion 1.x, 2.x and SDXL models are not supported in GGUF format. Install the model's .safetensors "+ "or .ckpt checkpoint, or its Diffusers folder, instead."+)++# A UNet's cross-attention takes its text encoder's width, which tells the bases apart: SD 1.x (768) and 2.x (1024)+# at the first resolution level, where SDXL has no attention, and SDXL (2048) and its refiner (1280) at the second.+# The keys are named as in the original checkpoint layout, and as in diffusers'.+_SD_BASES_BY_CONTEXT_WIDTH = (+ {768: BaseModelType.StableDiffusion1, 1024: BaseModelType.StableDiffusion2},+ {2048: BaseModelType.StableDiffusionXL, 1280: BaseModelType.StableDiffusionXLRefiner},+)+_SD_CHECKPOINT_CONTEXT_KEYS = (+ "input_blocks.2.1.transformer_blocks.0.attn2.to_k.weight",+ "input_blocks.4.1.transformer_blocks.0.attn2.to_k.weight",+)+_SD_DIFFUSERS_CONTEXT_KEYS = (+ "down_blocks.0.attentions.1.transformer_blocks.0.attn2.to_k.weight",+ "down_blocks.1.attentions.0.transformer_blocks.0.attn2.to_k.weight",+)+++def _sd_unet_base(state_dict: dict[str | int, Any], context_keys: tuple[str, ...]) -> BaseModelType | None:+ """The SD base whose context width the UNet's cross-attention at `context_keys` takes, or None."""+ for key, bases in zip(context_keys, _SD_BASES_BY_CONTEXT_WIDTH, strict=True):+ tensor = state_dict.get(key)+ if tensor is not None and (base := bases.get(tensor.shape[-1])) is not None:+ return base+ return None+++def _bare_sd_unet_base(state_dict: dict[str | int, Any]) -> BaseModelType | None:+ """The base of a whole SD UNet stored without the checkpoint's `model.diffusion_model.` prefix, or None.++ ComfyUI-GGUF's converter writes SD GGUFs this way: the UNet alone, under the checkpoint's key names or diffusers'.+ The decoder half (`output_blocks.` / `up_blocks.`) is required because a ControlNet copies the encoder half under+ the same names.+ """+ for context_keys, decoder_prefix in (+ (_SD_CHECKPOINT_CONTEXT_KEYS, "output_blocks."),+ (_SD_DIFFUSERS_CONTEXT_KEYS, "up_blocks."),+ ):+ base = _sd_unet_base(state_dict, context_keys)+ if base is not None:+ return base if state_dict_has_any_keys_starting_with(state_dict, decoder_prefix) else None+ return None++class Main_SD_Checkpoint_Config_Base(Checkpoint_Config_Base, Main_Config_Base):"""Model config for main checkpoint models."""@@ -269,6 +318,11 @@ class Main_SD_Checkpoint_Config_Base(Checkpoint_Config_Base, Main_Config_Base):cls._validate_base(mod)+ # No SD loader reads GGUF: a stable-diffusion.cpp conversion would install as a checkpoint and fail to load.+ # Checked after the base, so only a file that is this base is refused.+ if _has_ggml_tensors(mod.load_state_dict()):+ raise InvalidMatchError(_SD_GGUF_UNSUPPORTED)+prediction_type = override_fields.pop("prediction_type", None) or cls._get_scheduler_prediction_type_or_raise(mod)@@ -287,21 +341,11 @@ class Main_SD_Checkpoint_Config_Base(Checkpoint_Config_Base, Main_Config_Base):@classmethoddef _get_base_or_raise(cls, mod: ModelOnDisk) -> BaseModelType:- state_dict = mod.load_state_dict()-- key_name = "model.diffusion_model.input_blocks.2.1.transformer_blocks.0.attn2.to_k.weight"- if key_name in state_dict and state_dict[key_name].shape[-1] == 768:- return BaseModelType.StableDiffusion1- if key_name in state_dict and state_dict[key_name].shape[-1] == 1024:- return BaseModelType.StableDiffusion2-- key_name = "model.diffusion_model.input_blocks.4.1.transformer_blocks.0.attn2.to_k.weight"- if key_name in state_dict and state_dict[key_name].shape[-1] == 2048:- return BaseModelType.StableDiffusionXL- elif key_name in state_dict and state_dict[key_name].shape[-1] == 1280:- return BaseModelType.StableDiffusionXLRefiner-- raise NotAMatchError("unable to determine base type from state dict")+ context_keys = tuple(f"model.diffusion_model.{key}" for key in _SD_CHECKPOINT_CONTEXT_KEYS)+ base = _sd_unet_base(mod.load_state_dict(), context_keys)+ if base is None:+ raise NotAMatchError("unable to determine base type from state dict")+ return base@classmethoddef _get_scheduler_prediction_type_or_raise(cls, mod: ModelOnDisk) -> SchedulerPredictionType:@@ -346,9 +390,16 @@ class Main_SD_Checkpoint_Config_Base(Checkpoint_Config_Base, Main_Config_Base):@classmethoddef _validate_looks_like_main_model(cls, mod: ModelOnDisk) -> None:- has_main_model_keys = _has_main_keys(mod.load_state_dict())- if not has_main_model_keys:- raise NotAMatchError("state dict does not look like a main model")+ """Raise `NotAMatch` unless the state dict looks like a main model; refuse a bare GGUF UNet of this base.++ That UNet has none of the checkpoint's prefixes, so without the refusal it would register as Unknown.+ """+ state_dict = mod.load_state_dict()+ if _has_main_keys(state_dict):+ return+ if _bare_sd_unet_base(state_dict) is cls.model_fields["base"].default and _has_ggml_tensors(state_dict):+ raise InvalidMatchError(_SD_GGUF_UNSUPPORTED)+ raise NotAMatchError("state dict does not look like a main model")class Main_Checkpoint_SD1_Config(Main_SD_Checkpoint_Config_Base, Config_Base):diff --git a/tests/backend/model_manager/configs/test_sd_gguf_identification.py b/tests/backend/model_manager/configs/test_sd_gguf_identification.pynew file mode 100644index 0000000000..905ef6b197--- /dev/null+++ b/tests/backend/model_manager/configs/test_sd_gguf_identification.py@@ -0,0 +1,136 @@+"""Install-time refusal of SD 1.x / 2.x / SDXL GGUFs, made through ``ModelConfigFactory``.++No SD loader reads GGUF. These run at the default ``allow_unknown``, because that decides what the user sees: a+refusal with its reason, not a checkpoint or ControlNet record that fails at load, nor an Unknown model. Fixtures+are real GGUF files of a few kilobytes, read by the same GGUF loader identification uses.+"""++from collections.abc import Callable+from pathlib import Path+from typing import Any++import pytest+import torch++from invokeai.backend.model_manager.configs.controlnet import (+ ControlNet_Checkpoint_SD1_Config,+ ControlNet_Checkpoint_SDXL_Config,+)+from invokeai.backend.model_manager.configs.factory import ModelConfigFactory+from tests.fixtures.quantized_payloads import write_gguf++_OVERRIDE_FIELDS: dict[str, object] = {+ "hash": "blake3:fakehash",+ "path": "/fake/models/test-model",+ "file_size": 1000,+ "name": "test-model",+ "description": "test",+ "source": "test",+ "source_type": "path",+ "key": "test-key",+}++_SD1_CONTEXT_KEY = "input_blocks.2.1.transformer_blocks.0.attn2.to_k.weight"+_SDXL_CONTEXT_KEY = "input_blocks.4.1.transformer_blocks.0.attn2.to_k.weight"+++def _identify(path: Path) -> Any:+ return ModelConfigFactory.from_model_on_disk(path, dict(_OVERRIDE_FIELDS), allow_unknown=True)+++def _assert_refused_as_sd_gguf(result: Any) -> None:+ """Exactly one refusal: the installer shows the first, and the order of the candidate configs is not fixed."""+ assert result.config is None+ assert len(result.invalid_matches) == 1+ assert "not supported in GGUF format" in str(result.invalid_matches[0])+++ ("context_key", "context_width"),+ [(_SD1_CONTEXT_KEY, 768), (_SDXL_CONTEXT_KEY, 2048)],+ ids=["sd1", "sdxl"],+)+def test_a_stable_diffusion_cpp_pipeline_gguf_is_refused_with_its_reason(+ tmp_path: Path, context_key: str, context_width: int+) -> None:+ """stable-diffusion.cpp's layout: the whole pipeline under its original names, quantized, with no metadata."""+ path = tmp_path / "stable-diffusion-Q8_0.gguf"+ write_gguf(+ path,+ {+ "model.diffusion_model.input_blocks.0.0.weight": torch.ones(8, 4, 3, 3, dtype=torch.float16),+ "first_stage_model.encoder.conv_in.weight": torch.ones(8, 3, 3, 3, dtype=torch.float16),+ },+ q8_0={+ f"model.diffusion_model.{context_key}": torch.randn(8, context_width),+ "cond_stage_model.transformer.text_model.embeddings.token_embedding.weight": torch.randn(8, 768),+ },+ architecture="",+ )++ _assert_refused_as_sd_gguf(_identify(path))+++def test_a_bare_unet_gguf_is_refused_rather_than_installed_as_a_controlnet(tmp_path: Path) -> None:+ """ComfyUI-GGUF's layout: the UNet alone, its `model.diffusion_model.` prefix stripped. The SD 1.x UNet's+ `input_blocks.*` names are also a ControlNet's, which used to claim it."""+ path = tmp_path / "sd15-unet-Q8_0.gguf"+ write_gguf(+ path,+ {+ "input_blocks.0.0.weight": torch.ones(8, 4, 3, 3, dtype=torch.float16),+ "output_blocks.0.0.out_layers.3.weight": torch.ones(8, 8, 3, 3, dtype=torch.float16),+ },+ q8_0={_SD1_CONTEXT_KEY: torch.randn(8, 768)},+ architecture="sd1",+ )++ _assert_refused_as_sd_gguf(_identify(path))+++def _sd1_controlnet_in_checkpoint_names(path: Path) -> None:+ write_gguf(+ path,+ {+ "input_blocks.0.0.weight": torch.ones(8, 4, 3, 3, dtype=torch.float16),+ "input_hint_block.0.weight": torch.ones(8, 3, 3, 3, dtype=torch.float16),+ "zero_convs.0.0.weight": torch.ones(8, 8, 1, 1, dtype=torch.float16),+ },+ q8_0={_SD1_CONTEXT_KEY: torch.randn(8, 768)},+ architecture="",+ )+++def _sdxl_controlnet_in_diffusers_names(path: Path) -> None:+ write_gguf(+ path,+ {+ "controlnet_cond_embedding.conv_in.weight": torch.ones(16, 3, 3, 3, dtype=torch.float16),+ "controlnet_mid_block.bias": torch.ones(1280, dtype=torch.float16),+ "down_blocks.0.downsamplers.0.conv.weight": torch.ones(8, 8, 3, 3, dtype=torch.float16),+ },+ q8_0={"down_blocks.1.attentions.0.transformer_blocks.0.attn2.to_k.weight": torch.randn(8, 2048)},+ architecture="",+ )+++ ("write", "expected_config"),+ [+ (_sd1_controlnet_in_checkpoint_names, ControlNet_Checkpoint_SD1_Config),+ (_sdxl_controlnet_in_diffusers_names, ControlNet_Checkpoint_SDXL_Config),+ ],+ ids=["sd1-checkpoint-names", "sdxl-diffusers-names"],+)+def test_a_controlnet_gguf_still_identifies_as_a_controlnet(+ tmp_path: Path, write: Callable[[Path], None], expected_config: type+) -> None:+ """A ControlNet copies the UNet's encoder half under the same names; without the decoder half it is no UNet,+ so neither the main-model refusal nor the ControlNet config's GGUF guard applies to it."""+ path = tmp_path / "controlnet-Q8_0.gguf"+ write(path)++ result = _identify(path)++ assert isinstance(result.config, expected_config)+ assert not result.invalid_matchesdiff --git a/tests/model_identification/README.md b/tests/model_identification/README.mdindex bff7a23dd4..872c385a7b 100644--- a/tests/model_identification/README.md+++ b/tests/model_identification/README.md@@ -97,7 +97,7 @@ If the model is multi-file (e.g. diffusers-style), omit this key or set it to a#### `"expected_config_attrs"`-This field is a dict of expected configuration attributes for the model. It is required for all test cases.+This field is a dict of expected configuration attributes for the model. It is required for all test cases except those with an `"expected_refusal"`.It is used to verify that the model's configuration matches expectations. The keys and values in this dict depend on the specific model and its configuration.@@ -128,6 +128,16 @@ For example, for a SD1.5 main (pipeline) inpainting model in diffusers format, y}```+#### `"expected_refusal"`++For a model that identification recognizes and refuses, so the install fails with a reason (an `InvalidMatchError`), set this to a substring of that reason instead of giving `"expected_config_attrs"` (setting both fails the test). The test then expects no config and exactly one refusal, containing the substring.++```json+{+ "expected_refusal": "not supported in GGUF format"+}+```+#### `"notes"`This is an optional string field where you can add any notes or comments about the test case. It can be useful for providing context or explaining any special considerations.diff --git a/tests/model_identification/stripped_models/6978a3bd-a78e-4daf-a1c5-c892e73002e2/__test_metadata__.json b/tests/model_identification/stripped_models/6978a3bd-a78e-4daf-a1c5-c892e73002e2/__test_metadata__.jsonnew file mode 100644index 0000000000..1cf193c236--- /dev/null+++ b/tests/model_identification/stripped_models/6978a3bd-a78e-4daf-a1c5-c892e73002e2/__test_metadata__.json@@ -0,0 +1,3 @@+version https://git-lfs.github.com/spec/v1+oid sha256:68d62a95362846b551d192df21448d5567d0aeb7c965f6aa48f1e796527f0b75+size 512diff --git a/tests/model_identification/stripped_models/6978a3bd-a78e-4daf-a1c5-c892e73002e2/stable-diffusion-v1-5-pruned-emaonly-Q8_0.gguf b/tests/model_identification/stripped_models/6978a3bd-a78e-4daf-a1c5-c892e73002e2/stable-diffusion-v1-5-pruned-emaonly-Q8_0.ggufnew file mode 100644index 0000000000..a4a5047458--- /dev/null+++ b/tests/model_identification/stripped_models/6978a3bd-a78e-4daf-a1c5-c892e73002e2/stable-diffusion-v1-5-pruned-emaonly-Q8_0.gguf@@ -0,0 +1,3 @@+version https://git-lfs.github.com/spec/v1+oid sha256:121a9a639ce40c78f0984658969e57a940479b4777a7615b9675fd9ca2bcca2c+size 424107diff --git a/tests/model_identification/stripped_models/db9f8a27-8522-4167-a6d1-1bb661b67cc7/__test_metadata__.json b/tests/model_identification/stripped_models/db9f8a27-8522-4167-a6d1-1bb661b67cc7/__test_metadata__.jsonnew file mode 100644index 0000000000..864270b053--- /dev/null+++ b/tests/model_identification/stripped_models/db9f8a27-8522-4167-a6d1-1bb661b67cc7/__test_metadata__.json@@ -0,0 +1,3 @@+version https://git-lfs.github.com/spec/v1+oid sha256:df1b7c3b5451374233fde0e46f72c312354dc4226b916600bea43d3a4123e15c+size 428diff --git a/tests/model_identification/stripped_models/db9f8a27-8522-4167-a6d1-1bb661b67cc7/stable-diffusion-xl-base-1.0-Q4_0.gguf b/tests/model_identification/stripped_models/db9f8a27-8522-4167-a6d1-1bb661b67cc7/stable-diffusion-xl-base-1.0-Q4_0.ggufnew file mode 100644index 0000000000..10a50e1333--- /dev/null+++ b/tests/model_identification/stripped_models/db9f8a27-8522-4167-a6d1-1bb661b67cc7/stable-diffusion-xl-base-1.0-Q4_0.gguf@@ -0,0 +1,3 @@+version https://git-lfs.github.com/spec/v1+oid sha256:86e0624bea470e5793cc4098b29fe59ba44da2c0ba6591110a5f979ccac179f3+size 617516diff --git a/tests/model_identification/test_identification.py b/tests/model_identification/test_identification.pyindex 75038c95eb..df15282e7c 100644--- a/tests/model_identification/test_identification.py+++ b/tests/model_identification/test_identification.py@@ -80,6 +80,10 @@ def test_model_identification(model_path: Path):test_metadata_path = model_path / "__test_metadata__.json"test_metadata = json.loads(test_metadata_path.read_text())+ expected_refusal = test_metadata.get("expected_refusal")+ if expected_refusal and "expected_config_attrs" in test_metadata:+ pytest.fail(f"{id}: set either expected_refusal or expected_config_attrs, not both")+if file_name := test_metadata.get("file_name", ""):model_path = model_path / file_name@@ -93,6 +97,15 @@ def test_model_identification(model_path: Path):print(mod.path)pytest.fail(f"{id}: Exception during model probing: {e}")+ if expected_refusal:+ # Exactly one: the installer shows the first refusal, and the order of the candidate configs is not fixed.+ reasons = [str(e) for e in result.invalid_matches]+ if result.config is not None or len(reasons) != 1 or expected_refusal not in reasons[0]:+ pytest.fail(+ f"{id}: expected exactly one refusal containing {expected_refusal!r}, got {result.config!r}, {reasons}"+ )+ return+if result.config is None:pytest.fail(f"{id}: no match, detailed results:\n{pformat(result.details)}")