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.

refactor(model-manager): share the llama.cpp key converter and the embedding materialization

Alexander Eichhorna445cc17d644
diff --git a/invokeai/backend/model_manager/load/model_loaders/krea2.py b/invokeai/backend/model_manager/load/model_loaders/krea2.py
index 21e6e58226..f6a34af153 100644
--- a/invokeai/backend/model_manager/load/model_loaders/krea2.py
+++ b/invokeai/backend/model_manager/load/model_loaders/krea2.py
@@ -25,6 +25,7 @@ from invokeai.backend.model_manager.load.load_default import (
)
from invokeai.backend.model_manager.load.model_loader_registry import ModelLoaderRegistry
from invokeai.backend.model_manager.load.model_loaders.generic_diffusers import GenericDiffusersLoader
+from invokeai.backend.model_manager.load.quantized_embedding import materialize_quantized_embedding
from invokeai.backend.model_manager.taxonomy import (
AnyModel,
BaseModelType,
@@ -33,7 +34,7 @@ from invokeai.backend.model_manager.taxonomy import (
Qwen3VLVariantType,
SubModelType,
)
-from invokeai.backend.model_manager.util.qwen3_gguf import convert_qwen3_llamacpp_keys
+from invokeai.backend.model_manager.util.llamacpp_keys import convert_llamacpp_decoder_keys
from invokeai.backend.model_manager.util.qwen3_vl import normalize_qwen3vl_rope_config
from invokeai.backend.quantization.fp8_scaled import (
INPUT_SCALE_SUFFIXES,
@@ -1108,8 +1109,6 @@ class Qwen3VLEncoderGGUFLoader(_Qwen3VLEncoderSingleFileLoader[Qwen3VLEncoder_GG
import torch
from transformers import Qwen3VLModel
- from invokeai.backend.quantization.gguf.ggml_tensor import GGMLTensor
-
target_device = TorchDevice.choose_torch_device()
model_dtype = TorchDevice.choose_bfloat16_safe_dtype(target_device)
@@ -1121,7 +1120,7 @@ class Qwen3VLEncoderGGUFLoader(_Qwen3VLEncoderSingleFileLoader[Qwen3VLEncoder_GG
sd = gguf_sd_loader(Path(config.path), compute_dtype=model_dtype)
# Unconditional: identification requires the llama.cpp `token_embd.weight`, so this file is
# llama.cpp-named by construction. (The converter passes unrecognized keys through anyway.)
- sd = convert_qwen3_llamacpp_keys(sd)
+ sd = convert_llamacpp_decoder_keys(sd)
# Reuse the single-file remap so both containers land on identical module paths.
sd = _remap_qwen3vl_singlefile_keys(sd, what="Qwen3-VL encoder GGUF")
@@ -1136,20 +1135,7 @@ class Qwen3VLEncoderGGUFLoader(_Qwen3VLEncoderSingleFileLoader[Qwen3VLEncoder_GG
load_state_dict_ignoring_extras(model, sd, source="Qwen3-VL encoder GGUF", assign=True, allow_missing=True)
- # Embedding lookups index the weight directly, which a quantized GGMLTensor cannot serve, so
- # this one tensor is materialized. It is also the weight least worth quantizing: it is the
- # model's entire input representation.
- embed_tokens = model.language_model.embed_tokens
- if isinstance(embed_tokens.weight, GGMLTensor):
- # The framework reserved the GGUF's file size for this load, which does not cover
- # materializing a packed tensor on top of it: 0.78 GB for the 4B, 1.24 GB for the 8B, and
- # twice that at the peak because `get_dequantized_tensor` builds an intermediate before
- # casting to the compute dtype. Unreserved, that is what pushes a tight machine into swap.
- # `.shape` is the dequantized shape; `Tensor.numel()` is not overridden and would report
- # the packed element count.
- dequantized_bytes = embed_tokens.weight.shape.numel() * model_dtype.itemsize
- self._ram_cache.make_room(2 * dequantized_bytes)
- embed_tokens.weight = torch.nn.Parameter(embed_tokens.weight.get_dequantized_tensor(), requires_grad=False)
+ materialize_quantized_embedding(model.language_model.embed_tokens, ram_cache=self._ram_cache)
_reject_incomplete_load(model, what="Qwen3-VL encoder GGUF")
diff --git a/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.py b/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.py
index bdff17bae4..75be97bbf9 100644
--- a/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.py
+++ b/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.py
@@ -47,6 +47,7 @@ from invokeai.backend.model_manager.load.load_default import (
_model_declared_skip_patterns,
)
from invokeai.backend.model_manager.load.model_loader_registry import ModelLoaderRegistry
+from invokeai.backend.model_manager.load.quantized_embedding import materialize_quantized_embedding
from invokeai.backend.model_manager.taxonomy import (
AnyModel,
BaseModelType,
@@ -55,6 +56,10 @@ from invokeai.backend.model_manager.taxonomy import (
ModelType,
SubModelType,
)
+from invokeai.backend.model_manager.util.llamacpp_keys import (
+ convert_llamacpp_decoder_keys,
+ is_llamacpp_decoder_state_dict,
+)
from invokeai.backend.quantization.fp8_scaled import (
TRANSFORMER_KEY_PREFIXES,
attach_fp8_scales,
@@ -1398,11 +1403,11 @@ class MistralEncoderGGUFLoader(ModelLoader):
if rope_theta is not None:
logger.info(f"GGUF metadata: rope_theta={rope_theta}, max_position={max_pos}")
- # llama.cpp stores layers as `blk.N.*`. Normalize to transformers' `model.layers.N.*` if needed.
- is_llamacpp = any(isinstance(k, str) and k.startswith("blk.") for k in sd.keys())
- if is_llamacpp:
+ # llama.cpp stores layers as `blk.N.*`. Normalize to transformers' `model.layers.N.*` if needed;
+ # `_strip_known_prefixes` and `_convert_for_bare_mistral_model` below adapt that to MistralModel.
+ if is_llamacpp_decoder_state_dict(sd):
logger.info("Detected llama.cpp GGUF format, converting keys to transformers format")
- sd = _convert_llamacpp_mistral_to_pytorch(sd)
+ sd = convert_llamacpp_decoder_keys(sd)
sd = _strip_known_prefixes(sd)
@@ -1431,10 +1436,7 @@ class MistralEncoderGGUFLoader(ModelLoader):
f"Mistral encoder (GGUF): {len(missing)} keys missing from state dict (first 5: {missing[:5]})"
)
- # Embedding lookups require an indexable tensor — dequantize the GGMLTensor for embed_tokens.
- embed_weight = model.embed_tokens.weight
- if isinstance(embed_weight, GGMLTensor):
- model.embed_tokens.weight = torch.nn.Parameter(embed_weight.get_dequantized_tensor(), requires_grad=False)
+ materialize_quantized_embedding(model.embed_tokens, ram_cache=self._ram_cache)
_reinit_inv_freq(model, mistral_config, compute_dtype)
@@ -1443,42 +1445,3 @@ class MistralEncoderGGUFLoader(ModelLoader):
_warn_if_40_layer_mistral(config.variant, logger)
return model
-
-
-def _convert_llamacpp_mistral_to_pytorch(sd: dict[str, Any]) -> dict[str, Any]:
- """Rename llama.cpp Mistral keys to the transformers layout."""
- key_map = {
- "token_embd.weight": "model.embed_tokens.weight",
- "output_norm.weight": "model.norm.weight",
- "output.weight": "lm_head.weight",
- }
- out: dict[str, Any] = {}
- for key, value in sd.items():
- if not isinstance(key, str):
- out[key] = value
- continue
- if key in key_map:
- out[key_map[key]] = value
- continue
- # Per-layer keys: `blk.N.<thing>` -> `model.layers.N.<thing>`
- if key.startswith("blk."):
- parts = key.split(".", 2) # ["blk", "<N>", "<rest>"]
- if len(parts) == 3:
- rest = parts[2]
- # Order matters: q_norm/k_norm must be checked BEFORE attn_q/attn_k
- # so we don't rewrite "attn_q_norm" -> "self_attn.q_proj_norm".
- rest = rest.replace("attn_q_norm.", "self_attn.q_norm.")
- rest = rest.replace("attn_k_norm.", "self_attn.k_norm.")
- rest = rest.replace("attn_q.", "self_attn.q_proj.")
- rest = rest.replace("attn_k.", "self_attn.k_proj.")
- rest = rest.replace("attn_v.", "self_attn.v_proj.")
- rest = rest.replace("attn_output.", "self_attn.o_proj.")
- rest = rest.replace("attn_norm.", "input_layernorm.")
- rest = rest.replace("ffn_norm.", "post_attention_layernorm.")
- rest = rest.replace("ffn_gate.", "mlp.gate_proj.")
- rest = rest.replace("ffn_up.", "mlp.up_proj.")
- rest = rest.replace("ffn_down.", "mlp.down_proj.")
- out[f"model.layers.{parts[1]}.{rest}"] = value
- continue
- out[key] = value
- return out
diff --git a/invokeai/backend/model_manager/load/model_loaders/z_image.py b/invokeai/backend/model_manager/load/model_loaders/z_image.py
index bdf3d1c353..dc0a99e1fb 100644
--- a/invokeai/backend/model_manager/load/model_loaders/z_image.py
+++ b/invokeai/backend/model_manager/load/model_loaders/z_image.py
@@ -31,6 +31,7 @@ from invokeai.backend.model_manager.load.load_default import (
)
from invokeai.backend.model_manager.load.model_loader_registry import ModelLoaderRegistry
from invokeai.backend.model_manager.load.model_loaders.generic_diffusers import GenericDiffusersLoader
+from invokeai.backend.model_manager.load.quantized_embedding import materialize_quantized_embedding
from invokeai.backend.model_manager.taxonomy import (
AnyModel,
BaseModelType,
@@ -38,9 +39,9 @@ from invokeai.backend.model_manager.taxonomy import (
ModelType,
SubModelType,
)
-from invokeai.backend.model_manager.util.qwen3_gguf import (
- convert_qwen3_llamacpp_keys,
- is_llamacpp_qwen3_state_dict,
+from invokeai.backend.model_manager.util.llamacpp_keys import (
+ convert_llamacpp_decoder_keys,
+ is_llamacpp_decoder_state_dict,
)
from invokeai.backend.quantization.fp8_scaled import (
QKV_SPLIT_SIDECHANNEL_SUFFIXES,
@@ -283,7 +284,6 @@ class ZImageDiffusersModel(GenericDiffusersLoader):
from transformers import Qwen3Config, Qwen3ForCausalLM
from invokeai.backend.quantization.sdnq.loaders import sdnq_sd_loader
- from invokeai.backend.quantization.sdnq.sdnq_tensor import SDNQTensor
from invokeai.backend.util.logging import InvokeAILogger
logger = InvokeAILogger.get_logger(self.__class__.__name__)
@@ -365,11 +365,7 @@ class ZImageDiffusersModel(GenericDiffusersLoader):
"SDNQ Z-Image Qwen3 text encoder", missing, unexpected, allowed_missing={"lm_head.weight"}
)
- # Dequantize embed_tokens weight for embedding lookups
- embed_tokens_weight = model.model.embed_tokens.weight
- if isinstance(embed_tokens_weight, SDNQTensor):
- dequantized = embed_tokens_weight.get_dequantized_tensor()
- model.model.embed_tokens.weight = torch.nn.Parameter(dequantized, requires_grad=False)
+ if materialize_quantized_embedding(model.model.embed_tokens, ram_cache=self._ram_cache):
logger.info("Dequantized embed_tokens weight for embedding lookups")
# Handle tied weights
@@ -1542,9 +1538,9 @@ class Qwen3EncoderGGUFLoader(ModelLoader):
# via apply_custom_layers_to_model() and the partial loading cache
sd = gguf_sd_loader(model_path, compute_dtype=compute_dtype)
- if is_llamacpp_qwen3_state_dict(sd):
+ if is_llamacpp_decoder_state_dict(sd):
logger.info("Detected llama.cpp GGUF format, converting keys to PyTorch format")
- sd = convert_qwen3_llamacpp_keys(sd)
+ sd = convert_llamacpp_decoder_keys(sd)
# Determine Qwen model configuration from state dict
# Count the number of layers by looking at layer keys
@@ -1643,14 +1639,7 @@ class Qwen3EncoderGGUFLoader(ModelLoader):
# GGMLTensor wrappers will be dequantized on-the-fly during inference
load_state_dict_ignoring_extras(model, sd, source="Qwen3 GGUF text encoder", assign=True, allow_missing=True)
- # Dequantize embed_tokens weight - embedding lookups require indexed access
- # which quantized GGMLTensors can't efficiently provide (no __torch_dispatch__ for embedding)
- from invokeai.backend.quantization.gguf.ggml_tensor import GGMLTensor
-
- embed_tokens_weight = model.model.embed_tokens.weight
- if isinstance(embed_tokens_weight, GGMLTensor):
- dequantized = embed_tokens_weight.get_dequantized_tensor()
- model.model.embed_tokens.weight = torch.nn.Parameter(dequantized, requires_grad=False)
+ if materialize_quantized_embedding(model.model.embed_tokens, ram_cache=self._ram_cache):
logger.info("Dequantized embed_tokens weight for embedding lookups")
# Handle tied weights - llama.cpp GGUF doesn't include lm_head.weight when embeddings are tied
@@ -1741,7 +1730,6 @@ class Qwen3EncoderSDNQLoader(ModelLoader):
) -> AnyModel:
from transformers import Qwen3Config, Qwen3ForCausalLM
- from invokeai.backend.quantization.sdnq.sdnq_tensor import SDNQTensor
from invokeai.backend.util.logging import InvokeAILogger
logger = InvokeAILogger.get_logger(self.__class__.__name__)
@@ -1835,11 +1823,7 @@ class Qwen3EncoderSDNQLoader(ModelLoader):
missing, unexpected = model.load_state_dict(sd, strict=False, assign=True)
raise_on_incomplete_sdnq_load("SDNQ Qwen3 encoder", missing, unexpected, allowed_missing={"lm_head.weight"})
- # Dequantize embed_tokens weight - embedding lookups require indexed access
- embed_tokens_weight = model.model.embed_tokens.weight
- if isinstance(embed_tokens_weight, SDNQTensor):
- dequantized = embed_tokens_weight.get_dequantized_tensor()
- model.model.embed_tokens.weight = torch.nn.Parameter(dequantized, requires_grad=False)
+ if materialize_quantized_embedding(model.model.embed_tokens, ram_cache=self._ram_cache):
logger.info("Dequantized embed_tokens weight for embedding lookups")
# Handle tied weights
diff --git a/invokeai/backend/model_manager/load/quantized_embedding.py b/invokeai/backend/model_manager/load/quantized_embedding.py
new file mode 100644
index 0000000000..db87b7d980
--- /dev/null
+++ b/invokeai/backend/model_manager/load/quantized_embedding.py
@@ -0,0 +1,65 @@
+"""Materializing a quantized embedding weight, with the host RAM it needs reserved first.
+
+A quantized encoder has to undo the quantization of exactly one tensor: ``embed_tokens.weight``.
+``nn.Embedding`` indexes its weight directly, and neither ``GGMLTensor`` nor ``SDNQTensor`` can serve
+an indexed read from packed storage -- so the lookup would fail at the user's first prompt, long
+after the load that could have prevented it. It is also the weight least worth keeping packed: it is
+the model's entire input representation, and one dequantized copy is the price of every lookup being
+a plain gather.
+
+The framework reserves a model's *file size* before a load (``ModelLoader._load_and_cache``), which
+by construction does not cover unpacking a tensor on top of it. That gap is the reason this lives in
+one place: 0.78 GB for a Qwen3-VL 4B, 1.24 GB for the 8B, and several times that at the peak.
+
+Callers are the five single-file text-encoder loaders that reach a quantized embedding: Qwen3-VL
+GGUF, Qwen3 GGUF, Qwen3 SDNQ, Z-Image diffusers SDNQ and Mistral GGUF. Not an inventory of every
+such step in the tree -- ``gemma2_encoder.py`` dequantizes a 1.18 GB Gemma-2 embedding from a free
+function with no cache to reserve against, and ``flux.py`` does the same for T5 and CLIP. Those are
+other families, still unreserved, and folding them in means threading a cache through their call
+chains.
+"""
+
+from typing import Any
+
+import torch
+
+from invokeai.backend.model_manager.load.model_cache.model_cache import ModelCache
+
+# Measured, not derived: reading the dequantizers suggests 2 (an intermediate plus the result), and
+# for the 8-bit formats that is what happens -- but the k-quant, 5-bit and 4-bit kernels unpack
+# through full-size temporaries that coexist with both, and BF16 is not torch-compatible here
+# (`TORCH_COMPATIBLE_QTYPES` is F32/F16 only) so it shuffles rather than passing through. Peak host
+# RSS over one 256 MB bf16 dequantization, sampled during the call, one format per fresh process:
+#
+# Q8_0 2.01x Q4_0 3.04x Q4_K 3.14x Q2_K 3.32x BF16 4.01x Q5_K 4.01x
+# Q6_K 4.08x Q3_K 4.16x Q5_1 5.37x Q5_0 5.38x
+# SDNQ: int8 2.00x uint4 3.99x int5 4.64x
+#
+# Q5_0/Q5_1 are the outliers and the reason for the headroom: `dequantize_blocks_Q5_0` expands the
+# high bits through a full-size int32 shift table, which coexists with three uint8 temporaries, the
+# fp16 product and the cast. The numpy fallback branch, despite going through float32, stays at ~4x.
+#
+# 6 clears the worst of them. It over-reserves for the 8-bit formats, which costs at most an
+# eviction the cache can undo -- where under-reserving costs the swap this reservation exists to
+# prevent, so the error belongs on this side. A per-format table would be exact and would silently
+# rot the first time a new quant type lands, so the constant is deliberately blunt.
+_PEAK_COPIES = 6
+
+
+def materialize_quantized_embedding(embedding: torch.nn.Module, *, ram_cache: ModelCache) -> bool:
+ """Replace ``embedding.weight`` with a dequantized ``Parameter``, reserving the room first.
+
+ Does nothing and returns False when the weight is already a plain tensor, so a caller can run it
+ unconditionally over a model whose quantization it does not know.
+ """
+ weight: Any = embedding.weight
+ dequantize = getattr(weight, "get_dequantized_tensor", None)
+ if dequantize is None:
+ return False
+
+ # `.shape` is the dequantized shape on both wrapper types; `Tensor.numel()` is not overridden and
+ # would report the packed element count instead -- for a 4-bit quant, roughly half of what is
+ # about to be allocated.
+ ram_cache.make_room(_PEAK_COPIES * weight.shape.numel() * weight.compute_dtype.itemsize)
+ embedding.weight = torch.nn.Parameter(dequantize(), requires_grad=False)
+ return True
diff --git a/invokeai/backend/model_manager/util/qwen3_gguf.py b/invokeai/backend/model_manager/util/llamacpp_keys.py
similarity index 61%
rename from invokeai/backend/model_manager/util/qwen3_gguf.py
rename to invokeai/backend/model_manager/util/llamacpp_keys.py
index fd8281dc89..e30757b26b 100644
--- a/invokeai/backend/model_manager/util/qwen3_gguf.py
+++ b/invokeai/backend/model_manager/util/llamacpp_keys.py
@@ -1,14 +1,14 @@
-"""Shared key handling for llama.cpp-converted Qwen3 GGUF files.
+"""Shared key handling for llama.cpp-converted decoder GGUF files.
-Both Qwen3 encoder families InvokeAI loads from GGUF -- the text-only one (Z-Image / FLUX.2 Klein)
-and the Qwen3-VL one (Krea-2 / Ideogram 4) -- ship the same llama.cpp tensor naming, because a
-Qwen3-VL GGUF's language tower *is* a Qwen3 decoder. Keeping one converter means a naming quirk
-found on one path is fixed for both.
+Every text encoder InvokeAI loads from a llama.cpp GGUF is a decoder stack under the same tensor
+naming: the text-only Qwen3 (Z-Image / FLUX.2 Klein), the Qwen3-VL language tower (Krea-2 /
+Ideogram 4), and Mistral / Ministral 3 (FLUX.2 [dev]). llama.cpp names them by role -- ``attn_q``,
+``ffn_gate``, ``attn_norm`` -- not by architecture, so one converter serves all three and a naming
+quirk found on one path is fixed for the others.
-Scope is those two: ``mistral_encoder.py`` carries a near-identical converter for the same llama.cpp
-layout, which this does not (yet) replace -- folding it in would change a path this feature does not
-otherwise touch. ``gemma2_encoder.py``'s converter stays separate on purpose: different target
-prefix, different norm convention, and it raises on an unmapped key instead of passing it through.
+``gemma2_encoder.py``'s converter stays separate on purpose: different target prefix
+(``layers.N.*``, no ``model.``), Gemma's ``1 + weight`` norm convention folded in, and it raises on
+an unmapped key instead of passing it through.
"""
import re
@@ -16,13 +16,14 @@ from collections.abc import Mapping
from typing import Any
# llama.cpp block component -> transformers module path within a decoder layer.
-_QWEN3_BLOCK_COMPONENTS = {
+_BLOCK_COMPONENTS = {
"attn_q": "self_attn.q_proj",
"attn_k": "self_attn.k_proj",
"attn_v": "self_attn.v_proj",
"attn_output": "self_attn.o_proj",
- "attn_q_norm": "self_attn.q_norm", # Qwen3 QK normalization
- "attn_k_norm": "self_attn.k_norm", # Qwen3 QK normalization
+ # QK normalization: present on Qwen3 and Ministral 3, absent on architectures without it.
+ "attn_q_norm": "self_attn.q_norm",
+ "attn_k_norm": "self_attn.k_norm",
"ffn_gate": "mlp.gate_proj",
"ffn_up": "mlp.up_proj",
"ffn_down": "mlp.down_proj",
@@ -31,7 +32,7 @@ _QWEN3_BLOCK_COMPONENTS = {
}
# llama.cpp top-level tensor -> transformers key.
-_QWEN3_TOP_LEVEL_KEYS = {
+_TOP_LEVEL_KEYS = {
"token_embd.weight": "model.embed_tokens.weight",
"output_norm.weight": "model.norm.weight",
"output.weight": "lm_head.weight", # absent when embeddings are tied
@@ -40,19 +41,22 @@ _QWEN3_TOP_LEVEL_KEYS = {
_BLOCK_PATTERN = re.compile(r"^blk\.(\d+)\.(.+)$")
-def is_llamacpp_qwen3_state_dict(sd: Mapping[Any, Any]) -> bool:
+def is_llamacpp_decoder_state_dict(sd: Mapping[Any, Any]) -> bool:
"""True when the state dict uses llama.cpp's ``blk.N.*`` naming rather than the transformers one.
ComfyUI-converted GGUFs keep the transformers naming, llama.cpp-converted ones do not, and both
turn up in the wild for a text-only Qwen3 -- which is why that loader asks before converting. The
Qwen3-VL path has no such choice to make: its identification requires the llama.cpp
``token_embd.weight``, so a file that reaches its loader is llama.cpp-named by construction.
+
+ The caller's own layout comes after: a bare ``MistralModel`` has no ``model.`` prefix and strips
+ it again. This function's job is the role-to-module-path mapping, not the enclosing container.
"""
return any(isinstance(key, str) and key.startswith("blk.") for key in sd)
-def convert_qwen3_llamacpp_keys(sd: Mapping[Any, Any]) -> dict[Any, Any]:
- """Convert llama.cpp Qwen3 GGUF keys to the transformers causal-LM layout.
+def convert_llamacpp_decoder_keys(sd: Mapping[Any, Any]) -> dict[Any, Any]:
+ """Convert llama.cpp decoder GGUF keys to the transformers causal-LM layout.
``blk.N.attn_q.weight`` -> ``model.layers.N.self_attn.q_proj.weight``, ``token_embd.weight`` ->
``model.embed_tokens.weight``, and so on. Unrecognized block components keep their name under the
@@ -71,10 +75,10 @@ def convert_qwen3_llamacpp_keys(sd: Mapping[Any, Any]) -> dict[Any, Any]:
if match:
layer_index, rest = match.groups()
component, _, suffix = rest.partition(".")
- mapped = _QWEN3_BLOCK_COMPONENTS.get(component, component)
+ mapped = _BLOCK_COMPONENTS.get(component, component)
target = f"model.layers.{layer_index}.{mapped}"
out[f"{target}.{suffix}" if suffix else target] = value
continue
- out[_QWEN3_TOP_LEVEL_KEYS.get(key, key)] = value
+ out[_TOP_LEVEL_KEYS.get(key, key)] = value
return out
diff --git a/tests/backend/model_manager/load/test_mistral_encoder_gguf_loader.py b/tests/backend/model_manager/load/test_mistral_encoder_gguf_loader.py
new file mode 100644
index 0000000000..a758cf81b2
--- /dev/null
+++ b/tests/backend/model_manager/load/test_mistral_encoder_gguf_loader.py
@@ -0,0 +1,135 @@
+"""Loading a llama.cpp Mistral encoder GGUF (FLUX.2 [dev]).
+
+This loader had its own copy of the llama.cpp key converter until the three copies were folded into
+``util/llamacpp_keys``. A differential run over the two implementations says the fold is
+output-identical for any real GGUF, but nothing exercised this loader end to end — so a rename in
+the shared table, or a change to the prefix handling that follows it, would have surfaced at a
+FLUX.2 [dev] user's first prompt instead of here.
+
+The GGUF is real and its matrices are genuinely Q8_0, so the weights arrive as the ``GGMLTensor``
+wrappers the loader has to cope with.
+"""
+
+from pathlib import Path
+from unittest.mock import MagicMock, call, create_autospec
+
+import numpy as np
+import torch
+
+from invokeai.backend.model_manager.configs.mistral_encoder import MistralEncoder_GGUF_Config
+from invokeai.backend.model_manager.load.model_cache.model_cache import ModelCache
+from invokeai.backend.model_manager.load.model_loaders.mistral_encoder import MistralEncoderGGUFLoader
+from invokeai.backend.model_manager.load.quantized_embedding import _PEAK_COPIES as PEAK_COPIES
+from invokeai.backend.model_manager.taxonomy import MistralVariantType
+from invokeai.backend.quantization.gguf.ggml_tensor import GGMLTensor
+
+# `_build_mistral_config` derives the head counts by dividing the projection rows by a fixed head
+# dim of 128, so the attention shapes have to be multiples of it however small the rest is.
+_HEAD_DIM = 128
+_VOCAB, _HIDDEN, _FFN, _LAYERS = 64, _HEAD_DIM, 256, 2
+_FILL = 0.25
+
+
+def _write_mistral_gguf(path: Path) -> None:
+ """The llama.cpp tensor set for a tiny Mistral decoder.
+
+ No `attn_q_norm` / `attn_k_norm`: `MistralModel` has no QK norm, and a real Mistral GGUF carries
+ none either. Matrices are Q8_0, norms stay F32 — how llama.cpp quantizes a real encoder.
+ """
+ import gguf
+ from gguf.quants import quantize
+
+ tensors: dict[str, tuple[int, ...]] = {
+ "token_embd.weight": (_VOCAB, _HIDDEN),
+ "output_norm.weight": (_HIDDEN,),
+ }
+ for layer in range(_LAYERS):
+ tensors.update(
+ {
+ f"blk.{layer}.attn_q.weight": (_HEAD_DIM, _HIDDEN),
+ f"blk.{layer}.attn_k.weight": (_HEAD_DIM, _HIDDEN),
+ f"blk.{layer}.attn_v.weight": (_HEAD_DIM, _HIDDEN),
+ f"blk.{layer}.attn_output.weight": (_HIDDEN, _HEAD_DIM),
+ f"blk.{layer}.ffn_gate.weight": (_FFN, _HIDDEN),
+ f"blk.{layer}.ffn_up.weight": (_FFN, _HIDDEN),
+ f"blk.{layer}.ffn_down.weight": (_HIDDEN, _FFN),
+ f"blk.{layer}.attn_norm.weight": (_HIDDEN,),
+ f"blk.{layer}.ffn_norm.weight": (_HIDDEN,),
+ }
+ )
+
+ writer = gguf.GGUFWriter(str(path), "llama")
+ writer.add_uint32("llama.block_count", _LAYERS)
+ for name, shape in tensors.items():
+ data = np.full(shape, _FILL, dtype=np.float32)
+ if len(shape) == 2:
+ packed = quantize(data, gguf.GGMLQuantizationType.Q8_0)
+ writer.add_tensor(name, packed, raw_shape=packed.shape, raw_dtype=gguf.GGMLQuantizationType.Q8_0)
+ else:
+ writer.add_tensor(name, data)
+ writer.write_header_to_file()
+ writer.write_kv_data_to_file()
+ writer.write_tensors_to_file()
+ writer.close()
+
+
+def _load(tmp_path: Path, monkeypatch, ram_cache=None):
+ gguf_path = tmp_path / "mistral_tiny.gguf"
+ _write_mistral_gguf(gguf_path)
+ config = MistralEncoder_GGUF_Config.model_construct(
+ path=str(gguf_path), variant=MistralVariantType.Cow, name="tiny"
+ )
+ loader = object.__new__(MistralEncoderGGUFLoader)
+ loader._logger = MagicMock()
+ loader._ram_cache = ram_cache if ram_cache is not None else create_autospec(ModelCache, instance=True)
+ monkeypatch.setattr(
+ "invokeai.backend.model_manager.load.model_loaders.mistral_encoder.TorchDevice.choose_torch_device",
+ lambda: torch.device("cpu"),
+ )
+ monkeypatch.setattr(
+ "invokeai.backend.model_manager.load.model_loaders.mistral_encoder.TorchDevice.choose_bfloat16_safe_dtype",
+ lambda _device: torch.float32,
+ )
+ return loader._load_from_gguf(config)
+
+
+def test_the_shared_converter_lands_every_weight_in_the_mistral_module_tree(tmp_path, monkeypatch) -> None:
+ """The fold's actual risk: this loader builds a *bare* `MistralModel`, so the shared converter's
+ `model.`-prefixed output has to survive `_strip_known_prefixes` and
+ `_convert_for_bare_mistral_model` before it fits.
+
+ Asserting over *every* parameter is what makes this catch a mis-mapped key. A "no meta tensors"
+ check would not: `_materialize_remaining_meta_tensors` fills whatever the load missed with zeros
+ (ones for norms) and only logs, so a key mapped to a module that does not exist leaves a
+ plausible-looking, silently wrong model rather than a meta tensor. The fixture writes every
+ tensor as the same non-default value, so a defaulted parameter is exactly what fails here.
+
+ What this cannot catch is a transposition *within* a same-shaped pair -- `attn_q`/`attn_k`/
+ `attn_v`, `ffn_gate`/`ffn_up`, the two norms. `test_llamacpp_keys.py` owns that case, where each
+ component carries a distinct sentinel.
+ """
+ model = _load(tmp_path, monkeypatch)
+
+ assert len(model.layers) == _LAYERS
+ for name, parameter in model.named_parameters():
+ actual = parameter.get_dequantized_tensor() if isinstance(parameter, GGMLTensor) else parameter
+ assert torch.allclose(actual, torch.full(parameter.shape, _FILL), atol=1e-3), name
+
+ for layer in model.layers:
+ for projection in (layer.self_attn.q_proj, layer.mlp.gate_proj, layer.mlp.down_proj):
+ # Still packed: the reason to load a GGUF at all.
+ assert isinstance(projection.weight, GGMLTensor)
+ assert projection.weight.shape == (projection.out_features, projection.in_features)
+
+
+def test_the_embedding_is_materialized_and_its_copy_reserved(tmp_path, monkeypatch) -> None:
+ """The site this change added a reservation to. `nn.Embedding` indexes its weight directly, so
+ the dequantized copy is unavoidable — and the framework reserved only the file size.
+ """
+ ram_cache = create_autospec(ModelCache, instance=True)
+
+ model = _load(tmp_path, monkeypatch, ram_cache=ram_cache)
+
+ assert not isinstance(model.embed_tokens.weight, GGMLTensor)
+ assert model.embed_tokens(torch.tensor([[0, 1]])).shape == (1, 2, _HIDDEN)
+ assert ram_cache.make_room.call_args_list == [call(PEAK_COPIES * _VOCAB * _HIDDEN * torch.float32.itemsize)]
diff --git a/tests/backend/model_manager/load/test_quantized_embedding.py b/tests/backend/model_manager/load/test_quantized_embedding.py
new file mode 100644
index 0000000000..aa2ab85775
--- /dev/null
+++ b/tests/backend/model_manager/load/test_quantized_embedding.py
@@ -0,0 +1,99 @@
+"""Materializing a quantized embedding weight, and reserving the RAM it needs first.
+
+Five encoder loaders share this one step. The reservation is the part worth pinning: the framework
+reserves a model's file size before the load, which by construction does not cover unpacking a
+tensor on top of it, and getting the figure from the *packed* element count would under-reserve by
+whatever the quantization saved — roughly half for a 4-bit quant.
+"""
+
+from unittest.mock import call, create_autospec
+
+import torch
+
+from invokeai.backend.model_manager.load.model_cache.model_cache import ModelCache
+from invokeai.backend.model_manager.load.quantized_embedding import materialize_quantized_embedding
+from invokeai.backend.quantization.gguf.ggml_tensor import GGMLTensor
+from invokeai.backend.quantization.sdnq.sdnq_tensor import SDNQTensor
+from invokeai.backend.quantization.sdnq.utils import SDNQQuantizationType
+
+_VOCAB, _HIDDEN = 64, 32
+
+
+def _q8_0_embedding() -> torch.nn.Embedding:
+ """A real Q8_0 `GGMLTensor` on an `nn.Embedding`, as `gguf_sd_loader` hands one over."""
+ import gguf
+ import numpy as np
+ from gguf.quants import quantize
+
+ logical = torch.Size((_VOCAB, _HIDDEN))
+ packed = torch.from_numpy(quantize(np.full(tuple(logical), 0.25, dtype=np.float32), gguf.GGMLQuantizationType.Q8_0))
+ embedding = torch.nn.Embedding(_VOCAB, _HIDDEN)
+ embedding.weight = torch.nn.Parameter(
+ GGMLTensor(
+ packed,
+ ggml_quantization_type=gguf.GGMLQuantizationType.Q8_0,
+ tensor_shape=logical,
+ compute_dtype=torch.float32,
+ ),
+ requires_grad=False,
+ )
+ return embedding
+
+
+def test_a_packed_weight_is_materialized_and_reserved_by_its_dequantized_size() -> None:
+ ram_cache = create_autospec(ModelCache, instance=True)
+ embedding = _q8_0_embedding()
+ # The packed element count is a different number from the logical one in either direction — Q8_0
+ # spends 34 bytes per 32 values, a 4-bit quant roughly half — so a reservation taken from it is
+ # simply wrong, not conservative.
+ assert embedding.weight.quantized_data.numel() != _VOCAB * _HIDDEN
+
+ assert materialize_quantized_embedding(embedding, ram_cache=ram_cache) is True
+
+ assert ram_cache.make_room.call_args_list == [call(6 * _VOCAB * _HIDDEN * torch.float32.itemsize)]
+ assert not isinstance(embedding.weight, GGMLTensor)
+ assert embedding.weight.shape == (_VOCAB, _HIDDEN)
+ # An indexed read is the whole reason this step exists.
+ assert torch.allclose(embedding(torch.tensor([[1, 2]])), torch.full((1, 2, _HIDDEN), 0.25), atol=1e-3)
+
+
+def test_a_plain_weight_is_left_alone_and_reserves_nothing() -> None:
+ """Callers run this unconditionally over a model whose quantization they do not know — a
+ non-quantized build must not pay a reservation, which evicts other models from the cache.
+ """
+ ram_cache = create_autospec(ModelCache, instance=True)
+ embedding = torch.nn.Embedding(_VOCAB, _HIDDEN)
+ weight_before = embedding.weight
+
+ assert materialize_quantized_embedding(embedding, ram_cache=ram_cache) is False
+
+ assert ram_cache.make_room.call_args_list == []
+ assert embedding.weight is weight_before
+
+
+def test_an_sdnq_weight_is_handled_by_the_same_duck_typed_path() -> None:
+ """Three of the five call sites are SDNQ, not GGUF, and `SDNQTensor` shares no base class with
+ `GGMLTensor` — only `get_dequantized_tensor`, `.shape` as the dequantized shape, and
+ `.compute_dtype`. That contract is what the helper dispatches on, so it is asserted against the
+ real type: `compute_dtype` is a plain public attribute elsewhere reached via `hasattr`, so
+ renaming it would look free and would break every SDNQ encoder load.
+ """
+ ram_cache = create_autospec(ModelCache, instance=True)
+ embedding = torch.nn.Embedding(_VOCAB, _HIDDEN)
+ embedding.weight = torch.nn.Parameter(
+ SDNQTensor(
+ data=torch.full((_VOCAB, _HIDDEN), 10, dtype=torch.int8),
+ quantization_type=SDNQQuantizationType.INT8_SYM,
+ tensor_shape=torch.Size((_VOCAB, _HIDDEN)),
+ compute_dtype=torch.bfloat16,
+ scale=torch.full((_VOCAB, 1), 0.1),
+ ),
+ requires_grad=False,
+ )
+
+ assert materialize_quantized_embedding(embedding, ram_cache=ram_cache) is True
+
+ assert ram_cache.make_room.call_args_list == [call(6 * _VOCAB * _HIDDEN * torch.bfloat16.itemsize)]
+ assert not isinstance(embedding.weight, SDNQTensor)
+ assert embedding.weight.dtype is torch.bfloat16
+ assert embedding(torch.tensor([[0, 1]])).shape == (1, 2, _HIDDEN)
diff --git a/tests/backend/model_manager/load/test_qwen3_vl_gguf_loader.py b/tests/backend/model_manager/load/test_qwen3_vl_gguf_loader.py
index eb7b95ec57..34ee401c33 100644
--- a/tests/backend/model_manager/load/test_qwen3_vl_gguf_loader.py
+++ b/tests/backend/model_manager/load/test_qwen3_vl_gguf_loader.py
@@ -5,17 +5,19 @@ matrices and the production ``gguf_sd_loader`` reads it, so the tensors arrive a
wrappers the loader has to cope with. See ``qwen3vl_gguf_fixture`` for what is and is not simulated.
"""
-from unittest.mock import MagicMock, call
+from unittest.mock import call, create_autospec
import pytest
import torch
import invokeai.backend.model_manager.load.model_loaders.krea2 as krea2_loaders
from invokeai.backend.model_manager.configs.qwen3_vl_encoder import Qwen3VLEncoder_GGUF_Config
+from invokeai.backend.model_manager.load.model_cache.model_cache import ModelCache
from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.torch_module_autocast import (
apply_custom_layers_to_model,
)
from invokeai.backend.model_manager.load.model_loaders.krea2 import Qwen3VLEncoderGGUFLoader
+from invokeai.backend.model_manager.load.quantized_embedding import _PEAK_COPIES as PEAK_COPIES
from invokeai.backend.model_manager.taxonomy import Qwen3VLVariantType
from invokeai.backend.quantization.gguf.ggml_tensor import GGMLTensor
from tests.backend.model_manager.load.qwen3vl_gguf_fixture import (
@@ -121,19 +123,21 @@ def test_a_krea2_shaped_forward_produces_hidden_states(loaded_encoder) -> None:
def test_the_embedding_materialization_is_reserved(monkeypatch, tmp_path) -> None:
"""The framework reserves the GGUF's file size, which does not cover unpacking a tensor on top
- of it — 0.78 GB for the 4B, 1.24 GB for the 8B, twice that at the peak. Unreserved, that is what
- pushes a tight machine into swap.
+ of it — 0.78 GB for the 4B, 1.24 GB for the 8B, and several times that at the peak. Unreserved,
+ that is what pushes a tight machine into swap.
The expected figure is computed from the *dequantized* shape on purpose: `Tensor.numel()` is not
overridden on a GGMLTensor and reports the packed element count instead — a different number
- either way, and for a 4-bit quant roughly half of what is about to be allocated.
+ either way, and for a 4-bit quant roughly half of what is about to be allocated. The multiplier
+ is imported rather than restated: what this test owns is that the loader reserves against the
+ right *tensor*, while `test_quantized_embedding.py` owns the multiplier's value.
"""
- ram_cache = MagicMock()
+ ram_cache = create_autospec(ModelCache, instance=True)
encoder = load_tiny_gguf_encoder(monkeypatch, tmp_path, ram_cache=ram_cache)
embed_weight = encoder.language_model.embed_tokens.weight
- expected = 2 * embed_weight.shape.numel() * torch.float32.itemsize
+ expected = PEAK_COPIES * embed_weight.shape.numel() * torch.float32.itemsize
assert ram_cache.make_room.call_args_list == [call(expected)]
diff --git a/tests/backend/model_manager/util/test_qwen3_gguf.py b/tests/backend/model_manager/util/test_llamacpp_keys.py
similarity index 56%
rename from tests/backend/model_manager/util/test_qwen3_gguf.py
rename to tests/backend/model_manager/util/test_llamacpp_keys.py
index d3153e1bcb..7a02178691 100644
--- a/tests/backend/model_manager/util/test_qwen3_gguf.py
+++ b/tests/backend/model_manager/util/test_llamacpp_keys.py
@@ -1,18 +1,18 @@
-"""Tests for the shared llama.cpp Qwen3 GGUF key converter.
-
-Used by both Qwen3 encoder GGUF loaders (text-only for Z-Image / FLUX.2 Klein, Qwen3-VL for Krea-2
-and Ideogram 4). A key that maps to *nothing* fails loudly — both loaders sweep for leftover meta
-tensors afterwards and name the offending ones. What this table has to protect against is the
-silent case: a key mapped to a different but shape-compatible module. `attn_q`/`attn_k` and
-`ffn_gate`/`ffn_up` are same-shaped pairs, so transposing either pair would load cleanly and
-produce wrong conditioning with nothing logged.
+"""Tests for the shared llama.cpp decoder GGUF key converter.
+
+Used by three encoder GGUF loaders: text-only Qwen3 (Z-Image / FLUX.2 Klein), the Qwen3-VL language
+tower (Krea-2 / Ideogram 4) and Mistral / Ministral 3 (FLUX.2 [dev]). A key that maps to *nothing*
+fails loudly — the loaders sweep for leftover meta tensors afterwards and name the offending ones.
+What this table has to protect against is the silent case: a key mapped to a different but
+shape-compatible module. `attn_q`/`attn_k` and `ffn_gate`/`ffn_up` are same-shaped pairs, so
+transposing either pair would load cleanly and produce wrong conditioning with nothing logged.
"""
import pytest
-from invokeai.backend.model_manager.util.qwen3_gguf import (
- convert_qwen3_llamacpp_keys,
- is_llamacpp_qwen3_state_dict,
+from invokeai.backend.model_manager.util.llamacpp_keys import (
+ convert_llamacpp_decoder_keys,
+ is_llamacpp_decoder_state_dict,
)
@@ -32,7 +32,7 @@ def test_block_components_map_to_the_transformers_decoder_layout() -> None:
"blk.0.ffn_norm.weight": "post_ln",
}
- assert convert_qwen3_llamacpp_keys(sd) == {
+ assert convert_llamacpp_decoder_keys(sd) == {
"model.layers.0.self_attn.q_proj.weight": "q",
"model.layers.0.self_attn.k_proj.weight": "k",
"model.layers.0.self_attn.v_proj.weight": "v",
@@ -49,13 +49,13 @@ def test_block_components_map_to_the_transformers_decoder_layout() -> None:
def test_multi_digit_layer_indices_survive() -> None:
"""Qwen3-VL 4B/8B have 36 layers, so two-digit indices are the common case, not an edge one."""
- assert convert_qwen3_llamacpp_keys({"blk.35.attn_q.weight": "w"}) == {
+ assert convert_llamacpp_decoder_keys({"blk.35.attn_q.weight": "w"}) == {
"model.layers.35.self_attn.q_proj.weight": "w"
}
def test_top_level_tensors_map_to_their_transformers_names() -> None:
- assert convert_qwen3_llamacpp_keys(
+ assert convert_llamacpp_decoder_keys(
{
"token_embd.weight": "embed",
"output_norm.weight": "norm",
@@ -70,7 +70,7 @@ def test_top_level_tensors_map_to_their_transformers_names() -> None:
def test_unrecognized_keys_pass_through_instead_of_being_dropped() -> None:
"""An unknown tensor must stay visible so the load complains about it by its real name."""
- assert convert_qwen3_llamacpp_keys(
+ assert convert_llamacpp_decoder_keys(
{
"blk.2.some_future_thing.weight": "a",
"rope_freqs.weight": "b",
@@ -85,7 +85,7 @@ def test_unrecognized_keys_pass_through_instead_of_being_dropped() -> None:
def test_non_string_keys_are_preserved() -> None:
"""State dicts are typed `str | int` across the config layer; a non-string key must survive."""
- assert convert_qwen3_llamacpp_keys({0: "x"}) == {0: "x"}
+ assert convert_llamacpp_decoder_keys({0: "x"}) == {0: "x"}
@pytest.mark.parametrize(
@@ -99,4 +99,26 @@ def test_non_string_keys_are_preserved() -> None:
)
def test_llamacpp_layout_detection(sd: dict, expected: bool) -> None:
"""ComfyUI-converted GGUFs already use the transformers naming and must not be re-mapped."""
- assert is_llamacpp_qwen3_state_dict(sd) is expected
+ assert is_llamacpp_decoder_state_dict(sd) is expected
+
+
+def test_a_component_is_matched_by_position_not_by_containment() -> None:
+ """The replaced Mistral converter rewrote with unanchored `str.replace`, so a known component
+ name was rewritten wherever it appeared in the key -- not only as the component.
+
+ These two inputs are the ones that actually separate the implementations; I checked the deleted
+ one to be sure. `blk.0.cross_attn_q.weight` became `...cross_self_attn.q_proj.weight` under it,
+ and a nested `attn_v` was rewritten mid-path. Both land under a wrong but plausibly
+ shape-compatible module, which is the failure that loads cleanly and conditions wrongly.
+ (A name that merely *starts* with a known component, like `ffn_gate_exps`, was already safe
+ there -- every replacement carried a trailing dot -- so it would not discriminate.)
+ """
+ assert convert_llamacpp_decoder_keys(
+ {
+ "blk.0.cross_attn_q.weight": "cross_q",
+ "blk.0.some.attn_v.weight": "nested_v",
+ }
+ ) == {
+ "model.layers.0.cross_attn_q.weight": "cross_q",
+ "model.layers.0.some.attn_v.weight": "nested_v",
+ }