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 multi-part and unreadable GGUF files at install (#10199)

Alexander Eichhorna79b1b1b7f3e
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.mdx
index e15ca2ff17..f3306886bc 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
@@ -24,6 +24,11 @@ with the reason only in the server log: the Diffusers layout of LTX-2, the GGUF
GGUFs of Mistral Small 3's shape that declare scaled RoPE or an attention temperature, such as Devstral Small 2.
Others are recognized by their layer names and fail, or misbehave, only when they load.
+Any GGUF, of any model, is refused at install with a message in two cases. A multi-part GGUF (llama.cpp's
+`...-00001-of-00003.gguf` files) has to be joined into one file first with llama.cpp's
+`llama-gguf-split --merge`, since no part loads alone. A GGUF whose header cannot be read is refused with the
+reader's error; if the file is incomplete or corrupt, download it again.
+
## Main models
| Family | Diffusers | Single file (bf16) | fp8 scaled | int8 | int4 | nvfp4 | MXFP8 | GGUF | SDNQ | NF4 |
@@ -91,18 +96,17 @@ CLIP encoders from the main model only, so a separate CLIP file does not change
`text_projection` for SD 3 and is refused without it, as are extended-context CLIP-L variants such as Long-CLIP.
FLUX.1 takes CLIP-L only.
-The Qwen3-VL GGUF encoder is the language model only; a separate `mmproj` vision file is refused, and split multi-part
-GGUFs have to be joined before installing. Qwen3-VL nvfp4 single files keep their layers packed: ComfyUI's
-`qwen3vl_8b_nvfp4`, and repacks that name their nvfp4 layers the same way, in `.comfy_quant` markers or the
-`_quantization_metadata` header. A repack that packs its vision tower the same way keeps it packed when Krea-2 edit
-loads it for reference images. A single file with nvfp4 layers named neither way, with AWQ layers, or with packed
-weights missing nvfp4's per-tensor `weight_scale_2` fails to install with a message; if only its vision tower has such
-layers, it installs and fails with a message when Krea-2 edit loads the tower for reference images. Quantized encoder
-folders (AWQ, ModelOpt, llm-compressor) are not covered by this. The Gemma-4 encoder installs as a folder (its
-`config.json` and tokenizer files next to exactly one weight file, bf16 or int8) or as a GGUF conversion of the
-LTX-2.5 encoder that packs its tokenizer and config in, such as elix3r's or Rootport's. Google's stock Gemma-4-12B
-GGUF fails to install with a message, since LTX-2 needs the Lightricks-tuned weights; its `mmproj` file is not
-recognized. A standalone `.safetensors` file is not recognized.
+The Qwen3-VL GGUF encoder is the language model only; a separate `mmproj` vision file is refused. Qwen3-VL nvfp4 single
+files keep their layers packed: ComfyUI's `qwen3vl_8b_nvfp4`, and repacks that name their nvfp4 layers the same way, in
+`.comfy_quant` markers or the `_quantization_metadata` header. A repack that packs its vision tower the same way keeps
+it packed when Krea-2 edit loads it for reference images. A single file with nvfp4 layers named neither way, with AWQ
+layers, or with packed weights missing nvfp4's per-tensor `weight_scale_2` fails to install with a message; if only its
+vision tower has such layers, it installs and fails with a message when Krea-2 edit loads the tower for reference
+images. Quantized encoder folders (AWQ, ModelOpt, llm-compressor) are not covered by this. The Gemma-4 encoder installs
+as a folder (its `config.json` and tokenizer files next to exactly one weight file, bf16 or int8) or as a GGUF
+conversion of the LTX-2.5 encoder that packs its tokenizer and config in, such as elix3r's or Rootport's. Google's stock
+Gemma-4-12B GGUF fails to install with a message, since LTX-2 needs the Lightricks-tuned weights; its `mmproj` file is
+not recognized. A standalone `.safetensors` file is not recognized.
The Qwen3.5 4B and 9B install as the same encoder type but are not interchangeable: Anima-3.8B takes only
the 4B and MOSS-Image only the 9B, and each refuses the other. A 9B file must hold the whole language model:
diff --git a/invokeai/backend/model_manager/configs/factory.py b/invokeai/backend/model_manager/configs/factory.py
index f749f74768..3ee5c0abc2 100644
--- a/invokeai/backend/model_manager/configs/factory.py
+++ b/invokeai/backend/model_manager/configs/factory.py
@@ -774,6 +774,33 @@ class ModelConfigFactory:
"yet. Use a GGML-quantized (Q8_0, Q4_K, ...) or safetensors build instead."
)
+ @staticmethod
+ def _gguf_file_refusal(mod: ModelOnDisk) -> InvalidMatchError | None:
+ """The reason a `.gguf` file cannot be installed whatever model it holds, or None.
+
+ Two files no loader reads: a part of a llama.cpp multi-part GGUF (gguf-py writes every key,
+ `general.architecture` included, into part 1 only and gives every part `split.*` keys), and a file whose
+ header cannot be parsed. Neither has an architecture key to match on, so without this they would
+ register as Unknown models, and part 1 would pass any family check that looks at metadata alone.
+ """
+ if mod.path.suffix != ".gguf" or not mod.path.is_file():
+ return None
+ if (error := mod.metadata_read_error()) is not None:
+ return InvalidMatchError(
+ f"{mod.path.name} could not be read as a GGUF file ({error}). If the file is incomplete or corrupt, "
+ "download it again."
+ )
+ metadata = mod.metadata()
+ count = metadata.get("split.count")
+ if isinstance(count, int) and count > 1:
+ part = metadata.get("split.no")
+ which = f"part {part + 1} of {count}" if isinstance(part, int) else f"one of {count} parts"
+ return InvalidMatchError(
+ f"{mod.path.name} is {which} of a multi-part GGUF, which cannot be loaded. Join the parts into "
+ "one file with llama.cpp's `llama-gguf-split --merge`, then install the joined file."
+ )
+ return None
+
@staticmethod
def from_dict(fields: dict[str, Any]) -> AnyModelConfig:
"""Return the appropriate config object from raw dict values."""
@@ -966,6 +993,10 @@ class ModelConfigFactory:
# This rejects obviously non-model paths early, saving time
ModelConfigFactory._validate_path_looks_like_model(mod.path)
+ # A property of the file, not of any model family: no candidate runs on a file nothing can load.
+ if refusal := ModelConfigFactory._gguf_file_refusal(mod):
+ return ModelClassificationResult(config=None, details={"gguf_file": refusal})
+
# We will always need these fields to build any model config.
fields = ModelConfigFactory.build_common_fields(mod, override_fields)
diff --git a/invokeai/backend/model_manager/configs/qwen3_vl_encoder.py b/invokeai/backend/model_manager/configs/qwen3_vl_encoder.py
index 5fc42c9762..05d2784b25 100644
--- a/invokeai/backend/model_manager/configs/qwen3_vl_encoder.py
+++ b/invokeai/backend/model_manager/configs/qwen3_vl_encoder.py
@@ -277,11 +277,9 @@ def _raise_if_qwen3_vl_mmproj(mod: ModelOnDisk) -> None:
def _variant_from_gguf_state_dict(state_dict: dict[str | int, Any]) -> Qwen3VLVariantType:
"""Derive the variant from the tensors, and reject a file whose tensors are incomplete.
- Deliberately not taken from the ``embedding_length``/``block_count`` metadata, though both are
- present. A llama.cpp multi-part quant (``...-00002-of-00003.gguf``, routine for the larger 8B
- quants) and an interrupted download both carry a complete KV block and only some of the tensors.
- Matching on metadata alone would install such a file, offer it in the encoder picker, and fail
- at the user's first generation rather than at install time.
+ Deliberately not taken from the ``embedding_length``/``block_count`` metadata: a file can carry a
+ complete KV block and only some of the tensors. Matching on metadata alone would install such a file,
+ offer it in the encoder picker, and fail at the user's first generation rather than at install time.
Raises ``InvalidMatchError``, not ``NotAMatchError``: the caller runs this only after the
architecture metadata identified the file as a Qwen3-VL encoder, so "recognised and unusable" is
@@ -305,9 +303,7 @@ def _variant_from_gguf_state_dict(state_dict: dict[str | int, Any]) -> Qwen3VLVa
if not any(isinstance(key, str) and key.startswith(f"blk.{last_layer}.") for key in state_dict):
raise InvalidMatchError(
f"this Qwen3-VL encoder GGUF is incomplete: it carries no 'blk.{last_layer}.*' tensors, but a "
- f"Qwen3-VL encoder has {_QWEN3_VL_NUM_HIDDEN_LAYERS} layers. Multi-part quants "
- "('...-00002-of-00003.gguf') must be joined before installing, and an interrupted download "
- "must be re-fetched."
+ f"Qwen3-VL encoder has {_QWEN3_VL_NUM_HIDDEN_LAYERS} layers. Re-fetch the file."
)
return variant
diff --git a/invokeai/backend/model_manager/model_on_disk.py b/invokeai/backend/model_manager/model_on_disk.py
index ecef29087c..cda2e9b95f 100644
--- a/invokeai/backend/model_manager/model_on_disk.py
+++ b/invokeai/backend/model_manager/model_on_disk.py
@@ -119,6 +119,7 @@ class ModelOnDisk:
# This prevents redundant computations during matching and parsing
self._state_dict_cache: dict[Path, Any] = {}
self._metadata_cache: dict[Path, Any] = {}
+ self._metadata_errors: dict[Path, str] = {}
def hash(self) -> str:
return ModelHash(algorithm=self.hash_algo).hash(self.path)
@@ -156,12 +157,24 @@ class ModelOnDisk:
with safe_open(path, framework="pt", device="cpu") as f:
metadata = f.metadata()
assert isinstance(metadata, dict)
- except Exception:
+ except Exception as e:
metadata = {}
+ # The message only: a stored exception would pin the traceback frames.
+ self._metadata_errors[path] = f"{type(e).__name__}: {e}"
self._metadata_cache[path] = metadata
return metadata
+ def metadata_read_error(self, path: Optional[Path] = None) -> Optional[str]:
+ """Why `metadata()` could not read the file, or None if it could.
+
+ `metadata()` returns `{}` for an unreadable file, which is indistinguishable from a readable one
+ without metadata; this tells the two apart without a second parse.
+ """
+ path = path or self.path
+ self.metadata(path)
+ return self._metadata_errors.get(path)
+
def repo_variant(self) -> Optional[ModelRepoVariant]:
if self.path.is_file():
return None
diff --git a/tests/backend/model_manager/configs/test_gguf_file_refusal.py b/tests/backend/model_manager/configs/test_gguf_file_refusal.py
new file mode 100644
index 0000000000..20f1f54732
--- /dev/null
+++ b/tests/backend/model_manager/configs/test_gguf_file_refusal.py
@@ -0,0 +1,78 @@
+"""GGUF files no loader reads are refused for every model family, made through ``ModelConfigFactory``.
+
+Run at the default ``allow_unknown``, because that is what decides what the user sees: a refusal with its reason
+rather than an Unknown model. The parts are written by gguf-py's own splitting, so they are what llama.cpp's
+tooling produces.
+"""
+
+from collections.abc import Callable
+from pathlib import Path
+
+import gguf
+import numpy as np
+import pytest
+
+from invokeai.backend.model_manager.configs.factory import ModelClassificationResult, ModelConfigFactory
+from invokeai.backend.model_manager.configs.unknown import Unknown_Config
+
+
+def _identify(path: Path) -> ModelClassificationResult:
+ return ModelConfigFactory.from_model_on_disk(path, allow_unknown=True)
+
+
+def _write_gguf(path: Path, *, split_max_tensors: int = 0) -> None:
+ writer = gguf.GGUFWriter(str(path), "llama", split_max_tensors=split_max_tensors)
+ writer.add_uint32("llama.block_count", 2)
+ for name in ("token_embd.weight", "blk.0.attn_q.weight", "blk.1.attn_q.weight"):
+ writer.add_tensor(name, np.zeros((4, 4), dtype=np.float32))
+ writer.write_header_to_file()
+ writer.write_kv_data_to_file()
+ writer.write_tensors_to_file()
+ writer.close()
+
+
[email protected]("part_index", [0, 1, 2])
+def test_every_part_of_a_multi_part_gguf_is_refused(tmp_path: Path, part_index: int) -> None:
+ _write_gguf(tmp_path / "model.gguf", split_max_tensors=1)
+ parts = sorted(tmp_path.glob("model-*-of-*.gguf"))
+ assert len(parts) == 3
+
+ result = _identify(parts[part_index])
+
+ assert result.config is None
+ assert len(result.invalid_matches) == 1
+ reason = str(result.invalid_matches[0])
+ assert f"part {part_index + 1} of 3" in reason
+ assert "llama-gguf-split --merge" in reason
+
+
+def _cut_in_half(path: Path) -> None:
+ data = path.read_bytes()
+ path.write_bytes(data[: len(data) // 2])
+
+
+ "damage",
+ [_cut_in_half, lambda path: path.write_bytes(b"hello, not a gguf"), lambda path: path.write_bytes(b"")],
+ ids=["cut-short", "not-gguf", "empty"],
+)
+def test_an_unreadable_gguf_is_refused_with_the_read_error(tmp_path: Path, damage: Callable[[Path], object]) -> None:
+ path = tmp_path / "model.gguf"
+ _write_gguf(path)
+ damage(path)
+
+ result = _identify(path)
+
+ assert result.config is None
+ assert len(result.invalid_matches) == 1
+ assert "could not be read as a GGUF file" in str(result.invalid_matches[0])
+
+
+def test_a_readable_single_file_gguf_that_no_family_claims_is_not_refused(tmp_path: Path) -> None:
+ path = tmp_path / "model.gguf"
+ _write_gguf(path)
+
+ result = _identify(path)
+
+ assert isinstance(result.config, Unknown_Config)
+ assert result.invalid_matches == []
diff --git a/tests/backend/model_manager/configs/test_qwen3_vl_gguf_config.py b/tests/backend/model_manager/configs/test_qwen3_vl_gguf_config.py
index 2e77d074a9..72b3a1c15f 100644
--- a/tests/backend/model_manager/configs/test_qwen3_vl_gguf_config.py
+++ b/tests/backend/model_manager/configs/test_qwen3_vl_gguf_config.py
@@ -57,7 +57,7 @@ def _write_gguf(
"""Write a minimal but structurally honest GGUF.
`hidden_size=None` omits the embedding entirely; `last_layer=None` omits the final block, which
- is what a multi-part quant's later shard or an interrupted download looks like.
+ is a file that carries all the metadata but not all of its tensors.
"""
import gguf
@@ -148,13 +148,13 @@ def test_variant_comes_from_the_embedding_tensor(
def test_a_partial_quant_is_rejected_at_install_time(tmp_path: Path) -> None:
- """A multi-part quant's later shard carries a complete KV block and only some tensors. Matching
- on metadata alone would install it, offer it in the picker, and fail at the first generation.
+ """A file with a complete KV block and only some tensors. Matching on metadata alone would install
+ it, offer it in the picker, and fail at the first generation.
Asserted through the factory at the default `allow_unknown`: once the architecture metadata has
identified the file, the rejection has to be final (`InvalidMatchError`), or the file still
installs -- as an Unknown model, with the reason nowhere the user looks."""
- path = _write_gguf(tmp_path / "Qwen3VL-8B-Instruct-Q8_0-00002-of-00003.gguf", last_layer=None)
+ path = _write_gguf(tmp_path / "Qwen3VL-8B-Instruct-Q8_0.gguf", last_layer=None)
result = _identify(path, allow_unknown=True)
@@ -165,7 +165,7 @@ def test_a_partial_quant_is_rejected_at_install_time(tmp_path: Path) -> None:
def test_a_variant_override_does_not_skip_the_completeness_check(tmp_path: Path) -> None:
"""`variant` is an install-API override. It says which Qwen3-VL the file is, not that all of its
tensors are present, so it must not buy the file past the one check that looks."""
- path = _write_gguf(tmp_path / "Qwen3VL-8B-Instruct-Q8_0-00002-of-00003.gguf", last_layer=None)
+ path = _write_gguf(tmp_path / "Qwen3VL-8B-Instruct-Q8_0.gguf", last_layer=None)
with pytest.raises(InvalidMatchError, match="incomplete"):
Qwen3VLEncoder_GGUF_Config.from_model_on_disk(