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): undo llama.cpp's Q/K reordering in Mistral GGUF encoders (#9968)
Alexander Eichhornc4314c9da2cd
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 6cccd5df98..2efa19c3e5 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-28+lastUpdated: 2026-10-31sidebar:order: 3---@@ -20,8 +20,9 @@ speeds are on each family's own page.- – no such build existsHow an unsupported file fails depends on the file. Some are not recognized at all and install as an unknown model,-with the reason only in the server log: the Diffusers layout of LTX-2 and the GGUF builds of MiniMax H3 and the-Ministral 3B encoder. Others are recognized by their layer names and fail, or misbehave, only when they load.+with the reason only in the server log: the Diffusers layout of LTX-2, the GGUF builds of MiniMax H3, and llama.cpp+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.## Main models@@ -69,7 +70,7 @@ Ministral 3B encoder. Others are recognized by their layer names and fail, or mi| Qwen3.5 9B | MOSS-Image | in the Diffusers folder | ✓ | L | L | L | ✗ | ✗ || Qwen2.5-VL | Qwen-Image | ✓ | ✓ | ✓ | L | ✓ | ✗ | ✗ || Mistral Small 3 | FLUX.2 dev | ✓ | ✓ | ✓ | L | ✓ | ✓ | ✗ |-| Ministral 3B | ERNIE-Image | ✓ | ✓ | ✓ | L | L | ✗ | ✗ |+| Ministral 3B | ERNIE-Image | ✓ | ✓ | ✓ | L | L | R | ✗ || Gemma-2 2B | PiD decoders | ✓ | ✗ | ✗ | ✗ | ✗ | ✓ | ✗ || Gemma-4 12B | LTX-2 | ✓ (bf16 or int8) | ✗ | L | in the folder | L | ✓ (LTX-2.5 conversions) | ✗ || UMT5 | Wan 2.2 | ✓ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ |diff --git a/docs/src/content/docs/Users Guide/03.Models/Local Models/ernie-image.mdx b/docs/src/content/docs/Users Guide/03.Models/Local Models/ernie-image.mdxindex 9cd7e058ff..2bd95a8b86 100644--- a/docs/src/content/docs/Users Guide/03.Models/Local Models/ernie-image.mdx+++ b/docs/src/content/docs/Users Guide/03.Models/Local Models/ernie-image.mdx@@ -1,7 +1,7 @@---title: ERNIE-Imagedescription: Generate images with Baidu's ERNIE-Image and ERNIE-Image Turbo, from the Diffusers pipelines, the single-file transformers or GGUF.-lastUpdated: 2026-10-09+lastUpdated: 2026-10-21sidebar:order: 3---@@ -66,8 +66,8 @@ ERNIE-Image Turbo (8 steps): the Q4_K_M transformer holds 4.8 GB instead of 15.3from 23.6 GB to 17.8 GB, and an image takes 11.0 s against 11.6 s for the Diffusers pipeline.Other GGUF conversions with the same layout(for example vantagewithai's) install as well. Quantized safetensors single files (fp8, int8) are not-supported, and neither is a GGUF build of the Ministral 3B encoder, so the encoder stays the 7.7 GB-safetensors file.+supported. A GGUF build of the Ministral 3B encoder is refused at install with a message naming the file to use+instead, so the encoder stays the 7.7 GB safetensors file.When a single-file ERNIE-Image model is selected, the **Components** section next to the model asks for:diff --git a/docs/src/content/docs/Users Guide/03.Models/Local Models/flux-2.mdx b/docs/src/content/docs/Users Guide/03.Models/Local Models/flux-2.mdxindex e57920c75f..742c3dabc7 100644--- a/docs/src/content/docs/Users Guide/03.Models/Local Models/flux-2.mdx+++ b/docs/src/content/docs/Users Guide/03.Models/Local Models/flux-2.mdx@@ -1,7 +1,7 @@---title: FLUX.2description: Generate and edit images with FLUX.2 Klein (4B and 9B, distilled and Base) and FLUX.2 [dev], including multi-reference image editing and the FLUX.2 [dev] Fun-ControlNet-Union.-lastUpdated: 2026-10-28+lastUpdated: 2026-10-31sidebar:order: 5---@@ -15,7 +15,7 @@ install:| **Klein 4B** | Qwen3 4B | Distilled for **4 steps** || **Klein 9B** | Qwen3 8B | Distilled for **4 steps** || **Klein 4B Base** / **Klein 9B Base** | Qwen3 4B / Qwen3 8B | Undistilled foundation models; **28 steps** |-| **FLUX.2 [dev]** | Mistral Small 3.1 | 32B guidance-distilled transformer; **28 steps**; non-commercial license |+| **FLUX.2 [dev]** | Mistral Small 3.2 | 32B guidance-distilled transformer; **28 steps**; non-commercial license |Every variant can take reference images for image editing (see [Reference images](#reference-images)).@@ -103,7 +103,11 @@ fp8 weights instead of expanding them.The GGUF transformers need a separate Mistral encoder. Q3_K_M and Q4_K_M install the GGUF Q4 encoder, thelarger quants the GGUF Q8 encoder. Other encoder starters are the Comfy-Org builds — *FP8* (~18 GB, bestquality for its size), *BF16* (~35.6 GB) and *FP4 mixed* (~12.3 GB download) — and a GGUF *IQ4_XS* build-(~11.1 GB).+(~11.1 GB). llama.cpp conversions of Mistral Small 3.2, such as unsloth's or bartowski's GGUFs, are the same+encoder; 3.0 and 3.1 GGUFs load too, but they are different weights. These files carry no Tekken tokenizer, so+their first load fetches it from the gated `black-forest-labs/FLUX.2-dev` repository (see below). A GGUF of the+same shape that declares scaled RoPE or an attention temperature, such as Devstral Small 2, is a different model+and installs as unknown.:::caution[License and access]FLUX.2 [dev] is released under a non-commercial license. Some Black Forest Labs repositories are gated ondiff --git a/invokeai/app/invocations/flux2/flux2_dev_model_loader.py b/invokeai/app/invocations/flux2/flux2_dev_model_loader.pyindex c772a18b41..1cb7db7b18 100644--- a/invokeai/app/invocations/flux2/flux2_dev_model_loader.py+++ b/invokeai/app/invocations/flux2/flux2_dev_model_loader.py@@ -1,6 +1,6 @@"""FLUX.2 [dev] model loader invocation.-Loads a FLUX.2 [dev] transformer with its Mistral Small 3.1 text encoder and the+Loads a FLUX.2 [dev] transformer with its Mistral Small 3.2 text encoder and theshared FLUX.2 32-channel VAE."""@@ -59,7 +59,7 @@ class Flux2DevModelLoaderInvocation(BaseInvocation):"""Load a FLUX.2 [dev] transformer plus its Mistral text encoder and VAE.FLUX.2 [dev] is a 32B guidance-distilled rectified flow transformer that uses- Mistral Small 3.1 (24B) as its sole text encoder, sharing the 32-channel+ Mistral Small 3.2 (24B) as its sole text encoder, sharing the 32-channelAutoencoderKLFlux2 VAE with FLUX.2 Klein.When the transformer is a Diffusers-format checkpoint, both VAE and Mistral@@ -159,7 +159,7 @@ class Flux2DevModelLoaderInvocation(BaseInvocation):raise ValueError("No Mistral encoder source provided. Single-file / GGUF transformers require a separate ""text encoder. Options:\n"- " 1. Set 'Mistral Encoder' to a standalone Mistral Small 3.1 text encoder model\n"+ " 1. Set 'Mistral Encoder' to a standalone Mistral Small 3.2 text encoder model\n"" 2. Set 'Mistral Source' to a Diffusers FLUX.2 [dev] model to extract the encoder from")diff --git a/invokeai/app/invocations/text_encoder/flux2_dev_text_encoder.py b/invokeai/app/invocations/text_encoder/flux2_dev_text_encoder.pyindex c7e32565cc..0a2aef8a06 100644--- a/invokeai/app/invocations/text_encoder/flux2_dev_text_encoder.py+++ b/invokeai/app/invocations/text_encoder/flux2_dev_text_encoder.py@@ -4,11 +4,11 @@ FLUX.2 [dev] uses a Mistral Small 3 (hidden_size=5120) text encoder. Two variantare supported (see ``MistralVariantType``), both read at the same hidden-stateindices (10, 20, 30):-- **Mistral24B** — the 40-layer encoder BFL ships in the canonical+- **Mistral24B** — the 40-layer encoder BFL ships in``black-forest-labs/FLUX.2-dev/text_encoder``. This is the default pipelineencoder; the loader keeps its final RMSNorm.-- **Cow** — the 30-layer "cow-mistral3-small" distillation, recommended for best- prompt adherence. On a 30-layer model the indices map to (1/3, 2/3, last), and+- **Cow** — the "cow-mistral3-small" build, the first 30 of those layers: all+ FLUX.2 [dev] reads. On a 30-layer model the indices map to (1/3, 2/3, last), andthe loader drops the final RMSNorm to match ComfyUI's reference (``final_norm=False``).Pipeline, per generation:@@ -64,7 +64,7 @@ FLUX2_DEV_PROMPT_TEMPLATE = "[SYSTEM_PROMPT]{system}[/SYSTEM_PROMPT][INST]{promp# Indices into hidden_states[] (hidden_states[0] is the embedding output) that# FLUX.2 [dev]'s joint attention was trained to consume. ComfyUI uses these-# same indices for both the 30-layer cow distillation and the 40-layer Mistral+# same indices for both the 30-layer cow build and the 40-layer Mistral# Small 3; for cow they hit (1/3, 2/3, last), and the loader strips the final# RMSNorm so the layer-30 readout is the raw post-layer-29 state.DEV_EXTRACTION_LAYERS = (10, 20, 30)@@ -83,7 +83,7 @@ DEV_MAX_SEQ_LEN = 512idle_gpu_offloadable=True,)class Flux2DevTextEncoderInvocation(BaseInvocation):- """Encode a prompt for FLUX.2 [dev] using its Mistral Small 3.1 text encoder."""+ """Encode a prompt for FLUX.2 [dev] using its Mistral Small 3.2 text encoder."""prompt: str = InputField(description="Text prompt to encode.", ui_component=UIComponent.Textarea)mistral_encoder: MistralEncoderField = InputField(diff --git a/invokeai/backend/anima/ip_adapter.py b/invokeai/backend/anima/ip_adapter.pyindex 815fb4f803..0c4e833647 100644--- a/invokeai/backend/anima/ip_adapter.py+++ b/invokeai/backend/anima/ip_adapter.py@@ -16,7 +16,7 @@ per adapter; with one image this is exactly its computation.import refrom functools import partial-from typing import TYPE_CHECKING, Iterable, Mapping, Optional, Sequence+from typing import TYPE_CHECKING, Any, Iterable, Mapping, Optional, Sequenceimport accelerateimport torch@@ -91,13 +91,13 @@ def encode_image_tokens(encoder: "SiglipVisionModel", pixel_values: torch.Tensorreturn outputs.last_hidden_state-def validate_anima_ip_adapter(keys: Iterable[str], metadata: Optional[Mapping[str, str]]) -> None:+def validate_anima_ip_adapter(keys: Iterable[str], metadata: Optional[Mapping[str, Any]]) -> None:"""Raise `ValueError` for a checkpoint of a reference variant `AnimaIPAdapter` does not compute.Shared by model identification and the loader, so such a file is refused at install rather than at generation."""for flag in _UNSUPPORTED_METADATA_FLAGS:- if (metadata or {}).get(flag, "False").lower() == "true":+ if str((metadata or {}).get(flag, "False")).lower() == "true":raise ValueError(f"Unsupported Anima IP-Adapter: it was trained with `{flag}`, which is not supported.")unsupported = [key for key in keys if not _IP_KEY_RE.match(key) and not key.startswith(_LORA_KEY_PREFIX)]if unsupported:diff --git a/invokeai/backend/ltx2/checkpoint_layout.py b/invokeai/backend/ltx2/checkpoint_layout.pyindex 4876acfb3d..17bb51661f 100644--- a/invokeai/backend/ltx2/checkpoint_layout.py+++ b/invokeai/backend/ltx2/checkpoint_layout.py@@ -65,7 +65,7 @@ def strip_transformer_prefix(key: str) -> str:return key[len(TRANSFORMER_PREFIX) :] if key.startswith(TRANSFORMER_PREFIX) else key-def header_config(metadata: Mapping[str, str] | None) -> dict[str, Any]:+def header_config(metadata: Mapping[str, Any] | None) -> dict[str, Any]:"""The ``config`` JSON the official files embed in their safetensors header, or ``{}``."""raw = (metadata or {}).get("config")if not isinstance(raw, str):@@ -77,7 +77,7 @@ def header_config(metadata: Mapping[str, str] | None) -> dict[str, Any]:return parsed if isinstance(parsed, dict) else {}-def header_model_version(metadata: Mapping[str, str] | None) -> str | None:+def header_model_version(metadata: Mapping[str, Any] | None) -> str | None:"""The ``model_version`` the official files embed (``"2.5.0"``), or None."""version = (metadata or {}).get("model_version")return version if isinstance(version, str) and version else None@@ -94,7 +94,7 @@ def generation_from_version(version: str | None) -> str | None:def classify_roles(- state_dict: Mapping[str, Any] | Iterable[str], metadata: Mapping[str, str] | None = None+ state_dict: Mapping[str, Any] | Iterable[str], metadata: Mapping[str, Any] | None = None) -> set[str]:"""Which components a file holds, from its key names.diff --git a/invokeai/backend/model_manager/configs/flux2_variant.py b/invokeai/backend/model_manager/configs/flux2_variant.pyindex a7bac8651e..c32a17adff 100644--- a/invokeai/backend/model_manager/configs/flux2_variant.py+++ b/invokeai/backend/model_manager/configs/flux2_variant.py@@ -22,7 +22,7 @@ from invokeai.backend.model_manager.taxonomy import Flux2VariantType_CONTEXT_IN_DIM: dict[Flux2VariantType, int] = {Flux2VariantType.Klein4B: 7680, # 3 × Qwen3-4B 2560Flux2VariantType.Klein9B: 12288, # 3 × Qwen3-8B 4096- Flux2VariantType.Dev: 15360, # 3 × Mistral Small 3.1 5120+ Flux2VariantType.Dev: 15360, # 3 × Mistral Small 3 5120}# vec_in_dim (text-encoder hidden_size) per distilled variant.diff --git a/invokeai/backend/model_manager/configs/gemma4_encoder.py b/invokeai/backend/model_manager/configs/gemma4_encoder.pyindex d567ced398..e2d7cb81a6 100644--- a/invokeai/backend/model_manager/configs/gemma4_encoder.py+++ b/invokeai/backend/model_manager/configs/gemma4_encoder.py@@ -173,12 +173,12 @@ class Gemma4Encoder_Gemma4Encoder_LTX2_Config(Config_Base):return cls(**override_fields, subfolder=subfolder, weight_file=weight_file)-def gguf_gemma4_text_config(metadata: Mapping[str, str]) -> dict[str, Any]:+def gguf_gemma4_text_config(metadata: Mapping[str, Any]) -> dict[str, Any]:"""The Gemma-4 text config a GGUF conversion embeds in its metadata, or ``NotAMatchError``."""for key in GGUF_CONFIG_KEYS:try:config = json.loads(metadata[key])- except (KeyError, ValueError):+ except (KeyError, TypeError, ValueError):continuetext_config = config.get("text_config", config) if isinstance(config, dict) else Noneif isinstance(text_config, dict) and {"hidden_size", "num_hidden_layers"} <= text_config.keys():diff --git a/invokeai/backend/model_manager/configs/lora.py b/invokeai/backend/model_manager/configs/lora.pyindex f81195acbf..331e4b5a15 100644--- a/invokeai/backend/model_manager/configs/lora.py+++ b/invokeai/backend/model_manager/configs/lora.py@@ -174,7 +174,7 @@ def _state_dict_looks_like_sdxl_unet_lora(state_dict: dict[str | int, Any]) -> b_FLUX2_CONTEXT_IN_DIMS = FLUX2_CONTEXT_IN_DIMS# FLUX.2 vec_in_dim values: text encoder hidden_size-# Klein 4B: 2560 (Qwen3-4B), Klein 9B: 4096 (Qwen3-8B), Dev: 5120 (Mistral Small 3.1)+# Klein 4B: 2560 (Qwen3-4B), Klein 9B: 4096 (Qwen3-8B), Dev: 5120 (Mistral Small 3)_FLUX2_VEC_IN_DIMS = {2560, 4096, 5120}# FLUX.1 hidden_size is 3072. Klein 9B uses 4096, FLUX.2 [dev] uses 6144 (48 heads × 128 head_dim).diff --git a/invokeai/backend/model_manager/configs/main.py b/invokeai/backend/model_manager/configs/main.pyindex 9b711d0b76..4ec3005c48 100644--- a/invokeai/backend/model_manager/configs/main.py+++ b/invokeai/backend/model_manager/configs/main.py@@ -517,7 +517,7 @@ def _get_flux2_variant(state_dict: dict[str | int, Any]) -> Flux2VariantType | NDistinguishes between variants based on context embedding dimension:- Klein 4B: context_in_dim = 7680 (3 × Qwen3-4B hidden_size 2560)- Klein 9B: context_in_dim = 12288 (3 × Qwen3-8B hidden_size 4096)- - Dev: context_in_dim = 15360 (3 × Mistral Small 3.1 hidden_size 5120)+ - Dev: context_in_dim = 15360 (3 × Mistral Small 3 hidden_size 5120)Note: Klein 9B (distilled) and Klein 9B Base (undistilled) have identical architecturesand cannot be distinguished from the state dict alone. This function defaults to Klein9B@@ -1076,7 +1076,7 @@ class Main_Diffusers_Flux2_Config(Diffusers_Config_Base, Main_Config_Base, ConfiFLUX.2 variants are distinguished by joint_attention_dim (= 3 × text encoder hidden_size):- Klein 4B/4B Base: 7680 (3 × Qwen3-4B 2560)- Klein 9B/9B Base: 12288 (3 × Qwen3-8B 4096)- - Dev: 15360 (3 × Mistral Small 3.1 5120)+ - Dev: 15360 (3 × Mistral Small 3 5120)Klein distilled and Base variants share identical architectures; the Base variantis detected by a filename heuristic.diff --git a/invokeai/backend/model_manager/configs/mistral_encoder.py b/invokeai/backend/model_manager/configs/mistral_encoder.pyindex bd37f25181..1fab13df30 100644--- a/invokeai/backend/model_manager/configs/mistral_encoder.py+++ b/invokeai/backend/model_manager/configs/mistral_encoder.py@@ -1,10 +1,12 @@import json+from collections.abc import Mappingfrom typing import Any, Literal, Selffrom pydantic import Fieldfrom invokeai.backend.model_manager.configs.base import Checkpoint_Config_Base, Config_Basefrom invokeai.backend.model_manager.configs.identification_utils import (+ InvalidMatchError,NotAMatchError,raise_for_class_name,raise_for_override_fields,@@ -13,21 +15,26 @@ from invokeai.backend.model_manager.configs.identification_utils import ()from invokeai.backend.model_manager.model_on_disk import ModelOnDiskfrom invokeai.backend.model_manager.taxonomy import BaseModelType, MistralVariantType, ModelFormat, ModelType+from invokeai.backend.model_manager.util.llamacpp_keys import is_llamacpp_decoder_state_dictfrom invokeai.backend.quantization.gguf.ggml_tensor import GGMLTensor-# Mistral Small 3 family hidden_size — both the BFL canonical 40-layer encoder-# (``black-forest-labs/FLUX.2-dev/text_encoder``) and the 30-layer "cow" community-# distillation share this. Anything else is rejected as not a FLUX.2 encoder.+# Mistral Small 3 family hidden_size — both the 40-layer encoder BFL ships+# (``black-forest-labs/FLUX.2-dev/text_encoder``) and the 30-layer "cow" build, its+# first 30 layers, share this. Anything else is rejected as not a FLUX.2 encoder._MISTRAL_3_HIDDEN_SIZE = 5120# Layer counts ComfyUI's reference implementation accepts:-# - 40 layers → BFL canonical (Mistral3_24B), keep final RMSNorm enabled.-# - 30 layers → BFL "cow" distillation, final RMSNorm dropped at load time.+# - 40 layers → Mistral Small 3 as BFL ships it (Mistral3_24B), keep final RMSNorm enabled.+# - 30 layers → the "cow" build, final RMSNorm dropped at load time.# Anything else is rejected._MISTRAL_24B_NUM_LAYERS = 40_COW_NUM_LAYERS = 30_ACCEPTED_NUM_LAYERS = (_COW_NUM_LAYERS, _MISTRAL_24B_NUM_LAYERS)+# Mistral Small 3's MLP width, shared by the cow build. Mistral NeMo 12B has the same width,+# depth and Tekken vocab but a 14336-wide MLP, so without this it installs as a FLUX.2 encoder.+_MISTRAL_3_INTERMEDIATE_SIZE = 32768+# ERNIE-Image's encoder is Ministral 3B — a different member of the Mistral family, not a# smaller Mistral Small 3. It is half as wide (3072) over 26 layers and uses YaRN RoPE, so the# loader builds it as ``Ministral3Model``; see ``MistralVariantType.Ministral3B``. Geometry is@@ -36,12 +43,57 @@ _MINISTRAL_3B_HIDDEN_SIZE = 3072_MINISTRAL_3B_NUM_LAYERS = 26_ACCEPTED_GEOMETRIES = (- f"hidden_size={_MISTRAL_3_HIDDEN_SIZE} with num_hidden_layers in {_ACCEPTED_NUM_LAYERS}, "+ f"hidden_size={_MISTRAL_3_HIDDEN_SIZE} and intermediate_size={_MISTRAL_3_INTERMEDIATE_SIZE} with "+ f"num_hidden_layers in {_ACCEPTED_NUM_LAYERS}, "f"or hidden_size={_MINISTRAL_3B_HIDDEN_SIZE} with num_hidden_layers={_MINISTRAL_3B_NUM_LAYERS}")+LLAMACPP_MISTRAL_ARCHITECTURES = ("llama", "mistral3")+"""The ``general.architecture`` values llama.cpp writes for Mistral Small 3. A llama.cpp-named GGUF of+any other architecture is a different model whatever its shapes -- Qwen3-14B shares Mistral Small 3's+width and depth and clears the vocabulary floor. The loader keys on the same set: these converters+reorder the query and key rows it puts back, and Qwen's do not."""++# What llama.cpp records about RoPE that Mistral Small 3 does not use: scaled RoPE (YaRN for Ministral 3 and+# Devstral Small 2) and the Llama 4-style position-dependent attention temperature, each under the file's+# architecture prefix. llama.cpp's `mistral3.py` writes the YaRN and temperature keys only for Ministral 3.+_UNSUPPORTED_ROPE_KEYS = (+ "rope.scaling.type",+ "rope.scaling.factor",+ "rope.scaling.original_context_length",+ "rope.scaling.yarn_beta_fast",+ "rope.scaling.yarn_beta_slow",+ "rope.scaling.yarn_log_multiplier",+ "attention.temperature_scale",+)+++def unsupported_rope_refusal(metadata: Mapping[str, Any]) -> str | None:+ """Why a GGUF's metadata (``ModelOnDisk.metadata()``) rules out Mistral Small 3's plain RoPE, or ``None``.++ Identification refuses such a file, and the loader refuses records installed before it did: the+ alternative is an encoder that loads cleanly at Mistral Small 3's geometry and encodes at the wrong+ frequencies. Any one key counts, a YaRN factor without a declared scaling type included.+ """+ architecture = metadata.get("general.architecture")+ if not isinstance(architecture, str):+ return None+ declared = [+ f"{architecture}.{key}={value!r}"+ for key in _UNSUPPORTED_ROPE_KEYS+ if (value := metadata.get(f"{architecture}.{key}")) is not None+ and not (key == "rope.scaling.type" and value == "none")+ ]+ if not declared:+ return None+ return (+ f"declares {', '.join(declared)}: scaled RoPE or attention temperature, which Mistral Small 3 does not "+ "use, so this is a different model"+ )++# Minimum vocab size to accept as a FLUX.2 Mistral encoder. Mistral Small 3's-# Tekken vocab is 131072 (shared by the 30-layer cow distillation). This gates out+# Tekken vocab is 131072 (shared by the 30-layer cow build). This gates out# unrelated causal LMs that happen to share the 5120-hidden / 40-layer geometry —# most notably Llama-2-13B (vocab 32000), which otherwise matches the llama.cpp key# names and geometry and would install as a Mistral encoder producing garbage. We@@ -129,17 +181,13 @@ def _count_mistral_layers(state_dict: dict[str | int, Any]) -> int:return (max(indices) + 1) if indices else 0-def _embed_shape(state_dict: dict[str | int, Any]) -> tuple[int, int] | None:- """Read the ``(vocab_size, hidden_size)`` of the embedding tensor, or ``None``.+def _weight_shape(state_dict: dict[str | int, Any], candidate_keys: set[str]) -> tuple[int, int] | None:+ """Read the 2-D shape of the first weight stored under one of ``candidate_keys``, or ``None``.Scans keys with the loader's prefix normalization so ``text_encoder.``- /- ``language_model.``-prefixed layouts are recognized too.+ ``language_model.``-prefixed layouts are recognized too. A GGML tensor reports its dequantized+ shape; an nvfp4 weight packs along the input dimension, so its rows still count outputs."""- candidate_keys = {- "model.embed_tokens.weight",- "language_model.model.embed_tokens.weight",- "token_embd.weight",- }for key, tensor in state_dict.items():if not isinstance(key, str) or _normalize_probe_key(key) not in candidate_keys:continue@@ -152,6 +200,26 @@ def _embed_shape(state_dict: dict[str | int, Any]) -> tuple[int, int] | None:return None+def _embed_shape(state_dict: dict[str | int, Any]) -> tuple[int, int] | None:+ """Read the ``(vocab_size, hidden_size)`` of the embedding tensor, or ``None``."""+ return _weight_shape(+ state_dict, {"model.embed_tokens.weight", "language_model.model.embed_tokens.weight", "token_embd.weight"}+ )+++def _mlp_width(state_dict: dict[str | int, Any]) -> int | None:+ """Read the MLP width -- the output rows of layer 0's gate projection -- or ``None``."""+ shape = _weight_shape(+ state_dict,+ {+ "model.layers.0.mlp.gate_proj.weight",+ "language_model.model.layers.0.mlp.gate_proj.weight",+ "blk.0.ffn_gate.weight",+ },+ )+ return shape[0] if shape is not None else None++def _embed_hidden_size(state_dict: dict[str | int, Any]) -> int | None:"""Read the embedding hidden size from a Mistral-like state dict, or ``None``."""shape = _embed_shape(state_dict)@@ -164,18 +232,25 @@ def _embed_vocab_size(state_dict: dict[str | int, Any]) -> int | None:return shape[0] if shape is not None else None-def _variant_for_geometry(hidden_size: int | None, num_layers: int | None) -> MistralVariantType | None:- """Map a ``(hidden_size, num_layers)`` pair onto a variant, or ``None`` if unrecognized.+def _variant_for_geometry(+ hidden_size: int | None, num_layers: int | None, intermediate_size: int | None+) -> MistralVariantType | None:+ """Map a ``(hidden_size, num_layers, intermediate_size)`` geometry onto a variant, or ``None`` if unrecognized.Recognized variants:- - 30-layer + hidden_size=5120 → ``MistralVariantType.Cow`` (BFL distillation)- - 40-layer + hidden_size=5120 → ``MistralVariantType.Mistral24B`` (BFL canonical / upstream Mistral Small 3.x)+ - 30-layer + hidden_size=5120 → ``MistralVariantType.Cow`` (Mistral Small 3's first 30 layers)+ - 40-layer + hidden_size=5120 → ``MistralVariantType.Mistral24B`` (BFL's release / upstream Mistral Small 3.x)- 26-layer + hidden_size=3072 → ``MistralVariantType.Ministral3B`` (ERNIE-Image)+ The 5120-wide variants also need Mistral Small 3's MLP width: Mistral NeMo 12B matches them+ otherwise. Ministral 3B's width is unique among the encoders accepted here, so it needs none.+Shared by the state-dict and ``config.json`` probes so the two can never recognizedifferent sets of encoders."""if hidden_size == _MISTRAL_3_HIDDEN_SIZE:+ if intermediate_size != _MISTRAL_3_INTERMEDIATE_SIZE:+ return Noneif num_layers == _COW_NUM_LAYERS:return MistralVariantType.Cowif num_layers == _MISTRAL_24B_NUM_LAYERS:@@ -215,12 +290,31 @@ misleading here: it would list Ministral's 3072/26 among the *expected* geometriexactly what this file has."""-def _is_ministral_language_model_only(state_dict: dict[str | int, Any]) -> bool:- """Ministral 3B geometry with no multimodal stack -- ERNIE-Image's prompt enhancer."""+MINISTRAL_GGUF_REFUSAL = (+ "Ministral 3B GGUFs are not supported: the GGUF loader lacks Ministral 3's YaRN RoPE and attention scaling. "+ "For ERNIE-Image's text encoder, install the 'ERNIE-Image Ministral Encoder' starter model (Comfy-Org's "+ "text_encoders/ministral-3-3b.safetensors) or the text_encoder/ folder of baidu/ERNIE-Image."+)+"""Named so the refusal can be asserted. Short, with the remedy by the second line: the install queue+shows about two lines of it. Neutral about intent: a Ministral 3B GGUF may be meant as ERNIE-Image's+encoder, its prompt enhancer or a plain LLM, so the remedy is scoped to the encoder.+Raised as ``InvalidMatchError``: the file is recognized and unusable, so it must not register as an+unknown model either."""+++def _geometry_variant(state_dict: dict[str | int, Any]) -> MistralVariantType | None:+ """The variant the state dict's geometry names, past the vocab floor, before any layout check."""vocab_size = _embed_vocab_size(state_dict)if vocab_size is None or vocab_size < _MISTRAL_3_MIN_VOCAB_SIZE:- return False- geometry = _variant_for_geometry(_embed_hidden_size(state_dict), _count_mistral_layers(state_dict))+ return None+ return _variant_for_geometry(+ _embed_hidden_size(state_dict), _count_mistral_layers(state_dict), _mlp_width(state_dict)+ )+++def _is_ministral_language_model_only(state_dict: dict[str | int, Any]) -> bool:+ """Ministral 3B geometry with no multimodal stack -- ERNIE-Image's prompt enhancer."""+ geometry = _geometry_variant(state_dict)return geometry is MistralVariantType.Ministral3B and not _has_mistral3_vision_stack(state_dict)@@ -232,16 +326,22 @@ def _get_mistral_variant_from_state_dict(state_dict: dict[str | int, Any]) -> MiSmall 3 encoders — without it they would install and emit garbage embeddings. Bothaccepted families share the 131072-entry Tekken vocab, so one floor covers them."""- vocab_size = _embed_vocab_size(state_dict)- if vocab_size is None or vocab_size < _MISTRAL_3_MIN_VOCAB_SIZE:- return None- variant = _variant_for_geometry(_embed_hidden_size(state_dict), _count_mistral_layers(state_dict))+ variant = _geometry_variant(state_dict)if variant is MistralVariantType.Ministral3B and not _has_mistral3_vision_stack(state_dict):# ERNIE-Image's prompt enhancer has this exact geometry; only the tower tells them apart.return Nonereturn variant+def _unrecognized_geometry(state_dict: dict[str | int, Any]) -> str:+ return (+ f"unrecognized Mistral geometry (got hidden_size={_embed_hidden_size(state_dict)}, "+ f"intermediate_size={_mlp_width(state_dict)}, vocab_size={_embed_vocab_size(state_dict)}, "+ f"layers={_count_mistral_layers(state_dict)}). "+ f"Expected vocab_size>={_MISTRAL_3_MIN_VOCAB_SIZE} and {_ACCEPTED_GEOMETRIES}."+ )++def _get_mistral_variant_from_config(config_path) -> MistralVariantType | None:"""Return the Mistral variant for a HF ``config.json``, or ``None`` if unrecognized."""try:@@ -251,16 +351,13 @@ def _get_mistral_variant_from_config(config_path) -> MistralVariantType | None:return None# Mistral3ForConditionalGeneration nests the LM config under text_config.- hidden_size = config.get("hidden_size")- num_layers = config.get("num_hidden_layers")- if hidden_size is None or num_layers is None:- text_config = config.get("text_config") or {}- if hidden_size is None:- hidden_size = text_config.get("hidden_size")- if num_layers is None:- num_layers = text_config.get("num_hidden_layers")+ text_config = config.get("text_config") or {}+ hidden_size, num_layers, intermediate_size = (+ config[name] if config.get(name) is not None else text_config.get(name)+ for name in ("hidden_size", "num_hidden_layers", "intermediate_size")+ )- return _variant_for_geometry(hidden_size, num_layers)+ return _variant_for_geometry(hidden_size, num_layers, intermediate_size)class MistralEncoder_Diffusers_Config(Config_Base):@@ -275,9 +372,8 @@ class MistralEncoder_Diffusers_Config(Config_Base):`Main_Diffusers_Flux2_Config` instead.Accepts both:- - 30-layer "cow" distillation (recommended, produces the cleanest output)- - 40-layer Mistral Small 3 (BFL canonical / upstream Mistral 3.x — also works,- slightly weaker prompt adherence than cow in our tests)+ - 40-layer Mistral Small 3 (BFL's ``text_encoder/`` or upstream Mistral Small 3.x)+ - the 30-layer "cow" build, its first 30 layersThe variant field records which one was probed so the loader can decidewhether to keep the final RMSNorm (40-layer) or strip it (30-layer cow).@@ -340,7 +436,7 @@ class MistralEncoder_Checkpoint_Config(Checkpoint_Config_Base, Config_Base):"""Configuration for a single-file Mistral text encoder (safetensors).Accepts both 30-layer cow (Comfy-Org bf16/fp8/fp4) and 40-layer Mistral Small 3- (BFL canonical / upstream Mistral 3.x single-files). The loader uses the+ (BFL's release / upstream Mistral 3.x single-files). The loader uses thedetected variant to decide whether to keep or strip the final RMSNorm."""@@ -368,11 +464,7 @@ class MistralEncoder_Checkpoint_Config(Checkpoint_Config_Base, Config_Base):if variant is None and _is_ministral_language_model_only(state_dict):raise NotAMatchError(PROMPT_ENHANCER_REFUSAL)if variant is None:- raise NotAMatchError(- f"unrecognized Mistral geometry (got hidden_size={_embed_hidden_size(state_dict)}, "- f"vocab_size={_embed_vocab_size(state_dict)}, layers={_count_mistral_layers(state_dict)}). "- f"Expected vocab_size>={_MISTRAL_3_MIN_VOCAB_SIZE} and {_ACCEPTED_GEOMETRIES}."- )+ raise NotAMatchError(_unrecognized_geometry(state_dict))return cls(variant=variant, **override_fields)@@ -404,17 +496,23 @@ class MistralEncoder_GGUF_Config(Checkpoint_Config_Base, Config_Base):if not _has_ggml_tensors(state_dict):raise NotAMatchError("state dict does not look like GGUF quantized")- variant = _get_mistral_variant_from_state_dict(state_dict)- if variant is MistralVariantType.Ministral3B:- # The GGUF loader builds a `MistralModel` with RoPE read from GGUF metadata. Ministral- # 3B needs `Ministral3Model` -- YaRN scaling plus a position-dependent attention scale --- # so accepting one here would install a model that loads cleanly and encodes garbage.- raise NotAMatchError("Ministral 3B GGUF encoders are not supported")- if variant is None:+ metadata = mod.metadata()+ architecture = metadata.get("general.architecture")+ if is_llamacpp_decoder_state_dict(state_dict) and architecture not in LLAMACPP_MISTRAL_ARCHITECTURES:raise NotAMatchError(- f"unrecognized Mistral geometry (got hidden_size={_embed_hidden_size(state_dict)}, "- f"vocab_size={_embed_vocab_size(state_dict)}, layers={_count_mistral_layers(state_dict)}). "- f"Expected vocab_size>={_MISTRAL_3_MIN_VOCAB_SIZE} and {_ACCEPTED_GEOMETRIES}."+ f"llama.cpp GGUF of architecture {architecture!r}; Mistral Small 3 converts to one of "+ f"{LLAMACPP_MISTRAL_ARCHITECTURES}")+ variant = _geometry_variant(state_dict)+ if variant is MistralVariantType.Ministral3B:+ raise InvalidMatchError(MINISTRAL_GGUF_REFUSAL)+ if variant is None:+ raise NotAMatchError(_unrecognized_geometry(state_dict))++ # Mistral Small 3 runs plain RoPE. A scaled one at the same geometry -- Devstral Small 2 declares+ # YaRN -- is another model.+ if refusal := unsupported_rope_refusal(metadata):+ raise NotAMatchError(refusal)+return cls(variant=variant, **override_fields)diff --git a/invokeai/backend/model_manager/configs/qwen3_encoder.py b/invokeai/backend/model_manager/configs/qwen3_encoder.pyindex 33de104f8b..496b5d640b 100644--- a/invokeai/backend/model_manager/configs/qwen3_encoder.py+++ b/invokeai/backend/model_manager/configs/qwen3_encoder.py@@ -522,7 +522,7 @@ class Qwen3Encoder_GGUF_Config(Checkpoint_Config_Base, Config_Base):@classmethoddef _reject_qwen3_vl_architecture(cls, mod: ModelOnDisk) -> None:- # `mod.metadata()` caches GGUF string fields across the whole identification sweep and+ # `mod.metadata()` caches a GGUF's scalar fields across the whole identification sweep and# yields {} for anything it cannot read, so a non-GGUF simply finds no architecture here and# is left to `_validate_looks_like_gguf_quantized`.architecture = mod.metadata().get("general.architecture")diff --git a/invokeai/backend/model_manager/configs/qwen3_vl_encoder.py b/invokeai/backend/model_manager/configs/qwen3_vl_encoder.pyindex 29787cd1d0..886ca3d219 100644--- a/invokeai/backend/model_manager/configs/qwen3_vl_encoder.py+++ b/invokeai/backend/model_manager/configs/qwen3_vl_encoder.py@@ -318,7 +318,7 @@ class Qwen3VLEncoder_GGUF_Config(Checkpoint_Config_Base, Config_Base):if mod.path.suffix.lower() != ".gguf":raise NotAMatchError(f"expected a .gguf file, got {mod.path.suffix or '(no suffix)'}")- # `mod.metadata()` reads and caches every GGUF string field, and identification probes many+ # `mod.metadata()` reads and caches every scalar GGUF field, and identification probes many# configs against the same ModelOnDisk -- so this costs one shared read rather than a second# mmap plus the full GC that closing a reader forces.architecture = mod.metadata().get("general.architecture")diff --git a/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.py b/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.pyindex 5e0cbbefba..21616976b3 100644--- a/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.py+++ b/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.py@@ -1,10 +1,12 @@"""Model loaders for the Mistral text encoder used by FLUX.2 [dev].-FLUX.2 [dev] uses BFL's 30-layer "cow-mistral3-small" distillation as its sole-text encoder. The diffusers release wraps it in the multimodal+FLUX.2 [dev] encodes prompts with Mistral Small 3 (24B, 40 layers) and reads its+hidden states 10, 20 and 30. The diffusers release wraps it in the multimodal``Mistral3ForConditionalGeneration``; standalone single-file safetensors-(Comfy-Org bf16/fp8/fp4) and GGUF redistributions (gguf-org cow variants) ship-only the text tower, which we load as an encoder-only ``MistralModel``.+(Comfy-Org bf16/fp8/fp4), gguf-org's GGUFs and llama.cpp conversions ship only the+text tower, which we load as an encoder-only ``MistralModel``. The Comfy-Org and+gguf-org files are "cow" builds: the first 30 layers, all FLUX.2 reads, with the+final norm dropped.ERNIE-Image encodes its prompts with a different member of the family: Ministral3B (26 layers, hidden_size 3072, YaRN RoPE), which loads as ``Ministral3Model``.@@ -36,9 +38,11 @@ from transformers import (from invokeai.backend.model_manager.configs.factory import AnyModelConfigfrom invokeai.backend.model_manager.configs.mistral_encoder import (+ LLAMACPP_MISTRAL_ARCHITECTURES,MistralEncoder_Checkpoint_Config,MistralEncoder_Diffusers_Config,MistralEncoder_GGUF_Config,+ unsupported_rope_refusal,)from invokeai.backend.model_manager.load.load_default import (ModelLoader,@@ -47,6 +51,7 @@ from invokeai.backend.model_manager.load.load_default import ()from invokeai.backend.model_manager.load.model_loader_registry import ModelLoaderRegistryfrom invokeai.backend.model_manager.load.quantized_embedding import materialize_quantized_embedding+from invokeai.backend.model_manager.model_on_disk import ModelOnDiskfrom invokeai.backend.model_manager.taxonomy import (AnyModel,BaseModelType,@@ -58,6 +63,7 @@ from invokeai.backend.model_manager.taxonomy import (from invokeai.backend.model_manager.util.llamacpp_keys import (convert_llamacpp_decoder_keys,is_llamacpp_decoder_state_dict,+ undo_llamacpp_qk_permutation,)from invokeai.backend.quantization.fp8_scaled import (TRANSFORMER_KEY_PREFIXES,@@ -92,11 +98,11 @@ from invokeai.backend.util.devices import TorchDevicefrom invokeai.backend.util.logging import InvokeAILoggerfrom invokeai.backend.util.state_dict_loading import log_unexpected_keys-# Architecture constants for the 30-layer cow-mistral3-small distillation.+# Architecture constants for the 30-layer cow-mistral3-small build.# Sourced from BFL's FLUX.2-dev ``text_encoder/config.json`` (text-model side of# the Mistral3 multimodal stack) with the layer count adjusted to the cow depth.# Hidden / head / KV / RoPE settings match upstream Mistral Small 3 because the-# cow distillation only changes depth (40 → 30), not width.+# cow build is its first 30 of 40 layers: only the depth differs._COW_HIDDEN_SIZE = 5120_COW_INTERMEDIATE_SIZE = 32768_COW_NUM_HIDDEN_LAYERS = 30@@ -332,60 +338,57 @@ def _build_ministral3_config()-def _decode_gguf_field(field: Any) -> Any | None:- """Decode a single GGUFReader field to a Python scalar, or ``None``."""- if field is None:- return None- try:- # GGUFReader exposes scalar fields under `.contents()` in recent gguf releases.- # Fall back to parts decoding for older versions.- if hasattr(field, "contents"):- return field.contents()- except Exception:- pass- import struct-- try:- if field.types[0].name in ("FLOAT32",):- return struct.unpack("<f", bytes(field.parts[-1]))[0]- if field.types[0].name in ("FLOAT64",):- return struct.unpack("<d", bytes(field.parts[-1]))[0]- if field.types[0].name in ("UINT32", "UINT64", "INT32", "INT64", "UINT16"):- return int.from_bytes(bytes(field.parts[-1]), "little")- except Exception:- return None- return None-+def _llamacpp_head_counts(+ sd: dict[str, Any], metadata: Mapping[str, Any], architecture: str, file_name: str+) -> tuple[int, int]:+ """The head counts llama.cpp regrouped the query and key rows by, checked against layer 0's projections.-def _read_gguf_metadata_values(path: Path, keys: tuple[str, ...]) -> dict[str, Any]:- """Read several named metadata fields from a GGUF header in a single reader pass.-- Returns an empty dict if the file/header can't be read — callers must treat the- result as best-effort and fall back to defaults. Reading multiple keys with one- ``GGUFReader`` avoids re-parsing the (potentially large) header once per key.+ Read from the metadata: the regrouping runs per head, and the row counts give a head count only+ through an assumed head width."""- try:- import gguf-- reader = gguf.GGUFReader(path)- except Exception:- return {}- return {key: _decode_gguf_field(reader.fields.get(key)) for key in keys}---def _read_gguf_metadata_value(path: Path, key: str) -> Any | None:- """Read a single named field from a GGUF file's metadata header, or ``None``."""- return _read_gguf_metadata_values(path, (key,)).get(key)-+ n_head = metadata.get(f"{architecture}.attention.head_count")+ n_head_kv = metadata.get(f"{architecture}.attention.head_count_kv")+ if not isinstance(n_head, int) or not isinstance(n_head_kv, int):+ missing = [+ f"{architecture}.attention.{name}"+ for name, value in (("head_count", n_head), ("head_count_kv", n_head_kv))+ if not isinstance(value, int)+ ]+ raise ValueError(+ f"{file_name} is a llama.cpp GGUF without {' or '.join(missing)}, so its attention rows cannot be "+ "put back in order."+ )+ key_length = metadata.get(f"{architecture}.attention.key_length")+ head_dim = key_length if isinstance(key_length, int) else _COW_HEAD_DIM+ q_proj = sd.get("model.layers.0.self_attn.q_proj.weight")+ k_proj = sd.get("model.layers.0.self_attn.k_proj.weight")+ rows = tuple(int(_shape_of(weight)[0]) if weight is not None else None for weight in (q_proj, k_proj))+ if head_dim != _COW_HEAD_DIM or rows != (n_head * head_dim, n_head_kv * head_dim):+ raise ValueError(+ f"{file_name}: the metadata declares {n_head} query and {n_head_kv} key/value heads of width "+ f"{head_dim}, but layer 0 has {rows[0]} query and {rows[1]} key rows. This loader builds "+ f"{_COW_HEAD_DIM}-wide heads."+ )+ return n_head, n_head_kv-def _read_gguf_metadata_float(path: Path, key: str) -> float | None:- value = _read_gguf_metadata_value(path, key)- return float(value) if isinstance(value, (int, float)) else None+def _refuse_unless_mistral_small_3_mlp(sd: dict[str, Any], file_name: str) -> None:+ """Refuse a 5120-wide encoder whose MLP is not Mistral Small 3's.-def _read_gguf_metadata_int(path: Path, key: str) -> int | None:- value = _read_gguf_metadata_value(path, key)- return int(value) if isinstance(value, (int, float)) else None+ Mistral NeMo 12B has Mistral Small 3's width, depth, heads and vocabulary, but a 14336-wide MLP.+ Identification refuses it at install; records made before it did would load it and condition+ FLUX.2 with the wrong model.+ """+ embed = sd.get("model.embed_tokens.weight")+ if embed is None or int(_shape_of(embed)[1]) != _COW_HIDDEN_SIZE:+ return+ gate = sd.get("model.layers.0.mlp.gate_proj.weight")+ mlp_width = int(_shape_of(gate)[0]) if gate is not None else None+ if mlp_width != _COW_INTERMEDIATE_SIZE:+ raise ValueError(+ f"{file_name} is {_COW_HIDDEN_SIZE} wide with an MLP of width {mlp_width}, not Mistral Small 3's "+ f"{_COW_INTERMEDIATE_SIZE}: a different model of the same width, such as Mistral NeMo 12B."+ )# Wrapper prefixes this loader strips from the state dict. Kept as a named constant because the@@ -501,7 +504,7 @@ def _materialize_remaining_meta_tensors(model: torch.nn.Module, dtype: torch.dtydef _strip_final_norm_for_cow(model: torch.nn.Module, variant: MistralVariantType, logger: Any) -> None:- """Replace ``model.norm`` with ``Identity`` for the 30-layer cow distillation.+ """Replace ``model.norm`` with ``Identity`` for the 30-layer cow build.ComfyUI's reference implementation (``Mistral3_24BModel`` with ``num_layers=30``)sets ``final_norm=False``, so the hidden state at extraction index 30 is the@@ -523,33 +526,6 @@ def _strip_final_norm_for_cow(model: torch.nn.Module, variant: MistralVariantTyplogger.info("Replaced model.norm with Identity for 30-layer cow Mistral (final_norm=False).")-def _warn_if_40_layer_mistral(variant: MistralVariantType, logger: Any) -> None:- """Warn when a 40-layer Mistral Small 3 is loaded as a FLUX.2 [dev] text encoder.-- Architecturally, BFL's canonical ``black-forest-labs/FLUX.2-dev/text_encoder``- (40-layer, fine-tuned by BFL) and upstream ``mistralai/Mistral-Small-3.x``- GGUFs / safetensors (40-layer, base weights) are indistinguishable. In- practice only the BFL bundle produces clean output — upstream Mistral 3.1/3.2- at any quantization level gives visibly degraded prompt adherence because- the joint attention was not trained against those weights.-- We accept both at probe time and emit this warning at load time so users who- install a non-BFL 40-layer Mistral see the issue called out in the log- instead of just getting weird images. Keys on ``config.variant`` (single source- of truth), consistent with ``_strip_final_norm_for_cow``.- """- if variant is not MistralVariantType.Mistral24B:- return- logger.warning(- "Loaded a 40-layer Mistral Small 3 text encoder. "- "If this is NOT BFL's canonical FLUX.2-dev/text_encoder, expect degraded "- "prompt adherence — upstream Mistral 3.1 / 3.2 weights (GGUFs from "- "unsloth, gguf-org, etc.) are not what FLUX.2's joint attention was "- "trained against. Recommended encoders: Comfy-Org bf16/fp8/fp4 or "- "gguf-org cow-mistral3-small quants (all 30-layer cow distillation)."- )--def _drop_quantization_metadata(sd: dict[str, Any], logger, target_dtype: torch.dtype | None = None) -> dict[str, Any]:"""Dequantize Comfy-Org-style scaled FP8 weights and drop their metadata keys.@@ -1118,15 +1094,14 @@ class MistralEncoderDiffusersLoader(ModelLoader):low_cpu_mem_usage=True,local_files_only=True,)- # `MistralModel.norm` is always built by transformers, but the- # 30-layer cow distillation was trained against the post-layer-29- # state *without* the final norm — swap it for Identity to match- # ComfyUI's reference implementation. ``Mistral3ForConditionalGeneration``+ # `MistralModel.norm` is always built by transformers, but FLUX.2 reads+ # hidden state 30 as layer 29's raw output, which on the 30-layer cow+ # build is the state the final norm would apply to — swap it for Identity+ # to match ComfyUI's reference implementation. ``Mistral3ForConditionalGeneration``# nests the LM under ``.language_model``; handle both layouts.inner = getattr(model, "language_model", None) or modellogger = InvokeAILogger.get_logger("MistralEncoderDiffusersLoader")_strip_final_norm_for_cow(inner, config.variant, logger)- _warn_if_40_layer_mistral(config.variant, logger)# The BFL `text_encoder` checkpoint maps to `Mistral3Model`, which ships a# `vision_tower` + `multi_modal_projector` (~0.8GB of real weights). The# invocation only ever runs `.language_model`, so drop the vision path to@@ -1341,7 +1316,6 @@ class MistralEncoderCheckpointLoader(ModelLoader):_materialize_remaining_meta_tensors(model, model_dtype, logger)_strip_final_norm_for_cow(model, config.variant, logger)- _warn_if_40_layer_mistral(config.variant, logger)if fp8_layers:attached = attach_fp8_scales(model, fp8_layers)@@ -1392,28 +1366,42 @@ class MistralEncoderGGUFLoader(ModelLoader):target_device = TorchDevice.choose_torch_device()compute_dtype = TorchDevice.choose_bfloat16_safe_dtype(target_device)- sd = gguf_sd_loader(Path(config.path), compute_dtype=compute_dtype)+ model_path = Path(config.path)- # Read RoPE / context hyperparameters from the GGUF metadata before key- # conversion strips them. Mistral GGUFs use the llama.* prefix because- # they share llama.cpp's architecture family. Falling back silently is OK:- # `_build_mistral_config` defaults to Mistral Small 3.1 values when the- # override is None.- gguf_meta = _read_gguf_metadata_values(Path(config.path), ("llama.rope.freq_base", "llama.context_length"))- rope_raw = gguf_meta.get("llama.rope.freq_base")+ # Hyperparameters live under the file's own architecture prefix. Falling back silently is OK for+ # RoPE and context: `_build_mistral_config` defaults to BFL's Mistral Small 3.2 values when they are None.+ # Read as identification reads it, with install's header-tolerant reader, and before the weights, so a+ # record this refuses fails without reading the whole file into RAM first.+ metadata = ModelOnDisk(model_path).metadata()+ architecture = metadata.get("general.architecture")+ if refusal := unsupported_rope_refusal(metadata):+ raise ValueError(f"{model_path.name} {refusal}.")+ rope_raw = metadata.get(f"{architecture}.rope.freq_base")rope_theta = float(rope_raw) if isinstance(rope_raw, (int, float)) else None- ctx_raw = gguf_meta.get("llama.context_length")+ ctx_raw = metadata.get(f"{architecture}.context_length")max_pos = int(ctx_raw) if isinstance(ctx_raw, (int, float)) else Noneif rope_theta is not None:logger.info(f"GGUF metadata: rope_theta={rope_theta}, max_position={max_pos}")+ sd = gguf_sd_loader(model_path, compute_dtype=compute_dtype)+# 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.+ # Its converter also reordered the query and key rows for its own RoPE, so they are put back+ # here; HF-named files (gguf-org's cow builds) are stored in transformers' order already.if is_llamacpp_decoder_state_dict(sd):+ if architecture not in LLAMACPP_MISTRAL_ARCHITECTURES:+ raise ValueError(+ f"{model_path.name} is a llama.cpp GGUF of architecture {architecture!r}, not Mistral Small 3 "+ f"(one of {LLAMACPP_MISTRAL_ARCHITECTURES})."+ )logger.info("Detected llama.cpp GGUF format, converting keys to transformers format")sd = convert_llamacpp_decoder_keys(sd)+ n_head, n_head_kv = _llamacpp_head_counts(sd, metadata, architecture, model_path.name)+ undo_llamacpp_qk_permutation(sd, n_head, n_head_kv)sd = _strip_known_prefixes(sd)+ _refuse_unless_mistral_small_3_mlp(sd, model_path.name)mistral_config = _build_mistral_config(sd,@@ -1446,6 +1434,5 @@ class MistralEncoderGGUFLoader(ModelLoader):_materialize_remaining_meta_tensors(model, compute_dtype, logger)_strip_final_norm_for_cow(model, config.variant, logger)- _warn_if_40_layer_mistral(config.variant, logger)return modeldiff --git a/invokeai/backend/model_manager/model_on_disk.py b/invokeai/backend/model_manager/model_on_disk.pyindex 34fd299906..b34d0912f7 100644--- a/invokeai/backend/model_manager/model_on_disk.py+++ b/invokeai/backend/model_manager/model_on_disk.py@@ -134,7 +134,13 @@ class ModelOnDisk:extensions = {".safetensors", ".pt", ".pth", ".ckpt", ".bin", ".gguf"}return {f for f in self.path.rglob("*") if f.suffix in extensions and f.is_file()}- def metadata(self, path: Optional[Path] = None) -> dict[str, str]:+ def metadata(self, path: Optional[Path] = None) -> dict[str, Any]:+ """The file's metadata: safetensors' string map, or a GGUF's scalar fields.++ GGUF values keep their type -- strings, numbers, booleans -- because llama.cpp records hyperparameters+ as numbers. Array fields (the tokenizer vocabulary, for one) are left out: nothing identifies by them,+ and they are most of a header's size.+ """path = path or self.pathif path in self._metadata_cache:return self._metadata_cache[path]@@ -142,11 +148,9 @@ class ModelOnDisk:if path.suffix == ".gguf":with WrappedGGUFReader(path) as reader:metadata = {- name: value+ name: field.contents()for name, field in reader.fields.items()- if field.types- and field.types[0] == GGUFValueType.STRING- and isinstance(value := field.contents(), str)+ if field.types and field.types[0] != GGUFValueType.ARRAY}else:with safe_open(path, framework="pt", device="cpu") as f:diff --git a/invokeai/backend/model_manager/starter_models/common.py b/invokeai/backend/model_manager/starter_models/common.pyindex 8af465567f..27c2cbdc65 100644--- a/invokeai/backend/model_manager/starter_models/common.py+++ b/invokeai/backend/model_manager/starter_models/common.py@@ -304,7 +304,7 @@ flux2_dev_comfy_mistral_fp8 = StarterModel(name="FLUX.2 [dev] Mistral Encoder (Comfy FP8)",base=BaseModelType.Any,source="https://huggingface.co/Comfy-Org/flux2-dev/resolve/main/split_files/text_encoders/mistral_3_small_flux2_fp8.safetensors",- description="Comfy-Org FP8 of BFL's 30-layer cow-mistral3-small. Best quality/size for prompt adherence; embeds Tekken tokenizer (no HF fetch needed). ~18GB",+ description="Comfy-Org FP8 of the 30-layer cow build of Mistral Small 3.2. Best quality/size for prompt adherence; embeds Tekken tokenizer (no HF fetch needed). ~18GB",type=ModelType.MistralEncoder,)@@ -312,7 +312,7 @@ flux2_dev_comfy_mistral_bf16 = StarterModel(name="FLUX.2 [dev] Mistral Encoder (Comfy BF16)",base=BaseModelType.Any,source="https://huggingface.co/Comfy-Org/flux2-dev/resolve/main/split_files/text_encoders/mistral_3_small_flux2_bf16.safetensors",- description="Comfy-Org BF16 of BFL's 30-layer cow-mistral3-small. Reference precision; embeds Tekken tokenizer. ~35.6GB",+ description="Comfy-Org BF16 of the 30-layer cow build of Mistral Small 3.2. Reference precision; embeds Tekken tokenizer. ~35.6GB",type=ModelType.MistralEncoder,)@@ -320,17 +320,18 @@ flux2_dev_comfy_mistral_fp4 = StarterModel(name="FLUX.2 [dev] Mistral Encoder (Comfy FP4 mixed)",base=BaseModelType.Any,source="https://huggingface.co/Comfy-Org/flux2-dev/resolve/main/split_files/text_encoders/mistral_3_small_flux2_fp4_mixed.safetensors",- description="Comfy-Org FP4-mixed of BFL's 30-layer cow-mistral3-small; embeds Tekken tokenizer. Its nvfp4 layers stay packed, up to about 14.7GB once loaded. ~12.3GB download",+ description="Comfy-Org FP4-mixed of the 30-layer cow build of Mistral Small 3.2; embeds Tekken tokenizer. Its nvfp4 layers stay packed, up to about 14.7GB once loaded. ~12.3GB download",type=ModelType.MistralEncoder,)-# gguf-org cow GGUF variants (30-layer cow, llama.cpp packaging, also embed Tekken).+# gguf-org cow GGUFs: the 30-layer cow build in a GGUF container, with transformers tensor names and+# order under architecture `cow` rather than llama.cpp's conversion; they embed Tekken too.# Lower memory footprint than the Comfy safetensors but slightly lower fidelity.flux2_dev_cow_mistral_q4 = StarterModel(name="FLUX.2 [dev] cow Mistral Encoder (GGUF Q4)",base=BaseModelType.Any,source="https://huggingface.co/gguf-org/flux2-dev-gguf/resolve/main/cow-mistral3-small-q4_0.gguf",- description="cow-mistral3-small Q4_0 — 30-layer cow distillation BFL trained against. ~11.6GB",+ description="cow-mistral3-small Q4_0 — the first 30 layers of Mistral Small 3, all FLUX.2 [dev] reads. ~11.6GB",type=ModelType.MistralEncoder,format=ModelFormat.GGUFQuantized,)diff --git a/invokeai/backend/model_manager/taxonomy.py b/invokeai/backend/model_manager/taxonomy.pyindex c51c6a179b..5481fad14b 100644--- a/invokeai/backend/model_manager/taxonomy.py+++ b/invokeai/backend/model_manager/taxonomy.py@@ -190,7 +190,7 @@ class Flux2VariantType(str, Enum):"""Flux2 Klein 9B Base variant - undistilled foundation model using Qwen3 8B text encoder."""Dev = "dev"- """FLUX.2 [dev] - 32B rectified flow transformer using Mistral Small 3.1 text encoder (guidance-distilled)."""+ """FLUX.2 [dev] - 32B rectified flow transformer using Mistral Small 3.2 text encoder (guidance-distilled)."""class Flux3VariantType(str, Enum):@@ -384,7 +384,7 @@ class MistralVariantType(str, Enum):"""Mistral text encoder variants used by FLUX.2 [dev] and ERNIE-Image."""Cow = "cow_mistral3_small"- """The 30-layer BFL "cow-mistral3-small" distillation (hidden_size=5120).+ """The "cow-mistral3-small" build: the first 30 of Mistral Small 3's 40 layers (hidden_size=5120).Hidden states are sampled at indices (10, 20, 30) which on a 30-layer modelhit 1/3, 2/3, and the final layer. ComfyUI's reference implementationdrops the final RMSNorm for this variant (``final_norm=False``), so the@@ -392,12 +392,11 @@ class MistralVariantType(str, Enum):Mistral24B = "mistral3_24b""""The 40-layer Mistral Small 3 (24B, hidden_size=5120) text encoder BFL- ships in the canonical ``black-forest-labs/FLUX.2-dev/text_encoder``. Same- extraction indices (10, 20, 30), final RMSNorm kept enabled. Architecturally- identical to upstream ``mistralai/Mistral-Small-3.1/3.2`` — installing one- of those instead of BFL's release will load fine but produces visibly- weaker prompt adherence than the cow distillation, so the cow variants- remain the recommended default."""+ ships in ``black-forest-labs/FLUX.2-dev/text_encoder``. Same extraction+ indices (10, 20, 30), final RMSNorm kept enabled. Its weights are bit-identical+ in BF16 to upstream ``mistralai/Mistral-Small-3.2-24B-Instruct-2506``, so+ upstream builds of that model, GGUFs included, are the same encoder. Mistral+ Small 3.0 and 3.1 have the same shape but different weights."""Ministral3B = "ministral3_3b""""The 26-layer Ministral 3B (hidden_size=3072) ERNIE-Image encodes itsdiff --git a/invokeai/backend/model_manager/util/llamacpp_keys.py b/invokeai/backend/model_manager/util/llamacpp_keys.pyindex e30757b26b..9e2c561c83 100644--- a/invokeai/backend/model_manager/util/llamacpp_keys.py+++ b/invokeai/backend/model_manager/util/llamacpp_keys.py@@ -2,10 +2,14 @@Every text encoder InvokeAI loads from a llama.cpp GGUF is a decoder stack under the same tensornaming: 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``,+Ideogram 4), and Mistral Small 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 namingquirk found on one path is fixed for the others.+The names are where the three stop being alike. llama.cpp's converter reorders the attention query+and key rows of Mistral, not of Qwen3, so the Mistral loader also runs+``undo_llamacpp_qk_permutation`` after renaming.+``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 onan unmapped key instead of passing it through.@@ -15,6 +19,10 @@ import refrom collections.abc import Mappingfrom typing import Any+import torch++from invokeai.backend.quantization.gguf.row_ops import take_rows+# llama.cpp block component -> transformers module path within a decoder layer._BLOCK_COMPONENTS = {"attn_q": "self_attn.q_proj",@@ -82,3 +90,45 @@ def convert_llamacpp_decoder_keys(sd: Mapping[Any, Any]) -> dict[Any, Any]:out[_TOP_LEVEL_KEYS.get(key, key)] = valuereturn out+++_QK_PROJECTION = re.compile(r"^model\.layers\.\d+\.self_attn\.([qk])_proj\.(?:weight|bias)$")+++def undo_llamacpp_qk_permutation(sd: dict[Any, Any], n_head: int, n_head_kv: int) -> None:+ """Put the query and key rows of a llama.cpp GGUF back into transformers' order, in place.++ Runs on the transformers-named dict ``convert_llamacpp_decoder_keys`` returns, over every layer's+ ``q_proj`` / ``k_proj`` weight and bias. Queries are regrouped by ``n_head``, keys by+ ``n_head_kv``. Other tensors are left alone; GGML tensors stay packed. In place so each original+ is released as its replacement lands: the gather copies, and a copy of every layer's rows at once+ would add about 0.6 GB to a Q4_K Mistral Small 3 load.++ transformers' RoPE rotates dimension ``i`` of a head with ``i + head_dim / 2``; llama.cpp's+ "normal" RoPE rotates consecutive pairs. ``LlamaModel.permute`` in llama.cpp's converter+ interleaves the two halves of each head to match, and this is its inverse. Applied wrongly,+ nothing fails: queries and keys carry the same reordering, so only RoPE pairs the wrong+ dimensions, and the first position is unaffected.++ Which converters permute (llama.cpp ``conversion/`` at 339f324,+ https://github.com/ggml-org/llama.cpp/blob/339f3242c761f16c27e5ffcde1d35dcc31933a55/conversion/llama.py):++ - ``LlamaModel`` (``undo_permute = True``), registered for ``MistralForCausalLM`` among others,+ writes architecture ``llama``. ``mistral3.py``'s Mistral Small 3 / Ministral 3 text model+ subclasses it and writes ``mistral3``. Mistral Small 3 GGUFs in the wild carry either name.+ - Mistral's consolidated checkpoints (``--mistral-format``, ``mistral.py``) skip the permute+ because they are stored in llama.cpp's order already, so their GGUFs end up the same.+ - The Qwen2 / Qwen3 / Qwen3-VL and Gemma converters never permute: llama.cpp runs those models+ with half-split RoPE (NeoX, multi-section for Qwen3-VL), the pairing transformers stores. T5+ has no RoPE. See ``llama_model_rope_type`` in ``src/llama-model.cpp``.+ """+ for key in list(sd):+ match = _QK_PROJECTION.match(key) if isinstance(key, str) else None+ if match is None:+ continue+ heads = n_head if match.group(1) == "q" else n_head_kv+ rows = int(sd[key].shape[0])+ if heads <= 0 or rows % (2 * heads):+ raise ValueError(f"{key} has {rows} rows, which do not split into {heads} heads of rotary pairs")+ index = torch.arange(rows).reshape(heads, rows // heads // 2, 2).transpose(1, 2).reshape(rows)+ sd[key] = take_rows(sd[key], index)diff --git a/invokeai/backend/quantization/gguf/loaders.py b/invokeai/backend/quantization/gguf/loaders.pyindex 5f145a98b9..fbebe250e2 100644--- a/invokeai/backend/quantization/gguf/loaders.py+++ b/invokeai/backend/quantization/gguf/loaders.py@@ -163,11 +163,11 @@ def parse_q8_cr_markers(fields: Mapping[str, Any], source: str) -> dict[str, dicGGML quantization -- ``gguf`` has no dequantizer for it -- so these layers cannot ride theGGMLTensor path at all.- ``fields`` maps metadata keys to their string values; other keys are ignored. Returns the int8- markers keyed by weight name, in the form :mod:`int8_convrot` reads. Raises ``ValueError`` for- anything else the converter writes (``int4_cr``, the retired ``int4_pytorch``): those tensors are- ``I8`` too, and nothing here decodes them. Model identification turns that into the installer's- refusal, so a file is refused for the same reason at install and at load.+ ``fields`` maps metadata keys to their values: the file's whole metadata at install, its prefixed fields+ at load. Keys without the prefix are ignored. Returns the int8 markers keyed by weight name, in the form+ :mod:`int8_convrot` reads. Raises ``ValueError`` for anything else the converter writes (``int4_cr``, the+ retired ``int4_pytorch``): those tensors are ``I8`` too, and nothing here decodes them. Model identification+ turns that into the installer's refusal, so a file is refused for the same reason at install and at load."""layers: dict[str, dict[str, Any]] = {}for key, value in fields.items():diff --git a/invokeai/backend/quantization/gguf/row_ops.py b/invokeai/backend/quantization/gguf/row_ops.pynew file mode 100644index 0000000000..fc1b9cd175--- /dev/null+++ b/invokeai/backend/quantization/gguf/row_ops.py@@ -0,0 +1,45 @@+"""Row operations on GGUF state-dict tensors that keep GGML weights packed."""++import torch++from invokeai.backend.quantization.gguf.ggml_tensor import GGMLTensor+++def _packed_rows(value: GGMLTensor) -> torch.Tensor:+ """The packed data of ``value``, refused unless it is stored one row per output.++ GGML blocks run along a row, never across rows, so such data can be cut by rows without+ dequantizing.+ """+ data = value.quantized_data+ if data.shape[0] != value.tensor_shape[0]:+ raise ValueError(f"GGML tensor of shape {tuple(value.tensor_shape)} is not stored one row per output")+ return data+++def _with_rows(value: GGMLTensor, data: torch.Tensor) -> GGMLTensor:+ shape = torch.Size((data.shape[0], *value.tensor_shape[1:]))+ return GGMLTensor(data, value._ggml_quantization_type, shape, value.compute_dtype)+++def take_rows(value: torch.Tensor, index: torch.Tensor) -> torch.Tensor:+ """Gather the rows -- the leading, output dimension -- of a weight or bias at ``index``.++ A ``GGMLTensor`` is gathered on its packed bytes and keeps its quantization type and compute+ dtype. Plain tensors index along dim 0.+ """+ if not isinstance(value, GGMLTensor):+ return value[index]+ return _with_rows(value, _packed_rows(value)[index])+++def split_rows(value: torch.Tensor, rows: int) -> tuple[torch.Tensor, torch.Tensor]:+ """Split a tensor's leading (output) dimension in two at ``rows``.++ Plain tensors split as views. GGML halves are sliced and cloned, so each owns its storage; a+ contiguous slice copies about twice as fast as an index gather of the same rows.+ """+ if not isinstance(value, GGMLTensor):+ return value[:rows], value[rows:]+ data = _packed_rows(value)+ return _with_rows(value, data[:rows].clone()), _with_rows(value, data[rows:].clone())diff --git a/invokeai/backend/qwen_image_2_1/checkpoint_layout.py b/invokeai/backend/qwen_image_2_1/checkpoint_layout.pyindex df26ffcf85..d3186340e7 100644--- a/invokeai/backend/qwen_image_2_1/checkpoint_layout.py+++ b/invokeai/backend/qwen_image_2_1/checkpoint_layout.py@@ -13,7 +13,7 @@ from typing import Anyimport torch-from invokeai.backend.quantization.gguf.ggml_tensor import GGMLTensor+from invokeai.backend.quantization.gguf.row_ops import split_rowsGATE_UP = ".img_mlp.gate_up.""""ComfyUI's fused gated-MLP projection; diffusers splits it into `gate_layer` (first half) and `proj`."""@@ -22,26 +22,6 @@ GATE_UP = ".img_mlp.gate_up."_SHARED_SIDECARS = ("input_scale", "scale_input", "comfy_quant")-def _split_rows(value: Any, rows: int) -> tuple[Any, Any]:- """Split a tensor's leading (output) dimension in two at `rows`.-- GGML blocks run along a row, never across rows, so a GGML tensor splits by its quantized rows- without dequantizing.- """- if isinstance(value, GGMLTensor):- total, cols = value.tensor_shape- data = value.quantized_data- if data.shape[0] != total:- raise ValueError(f"GGML tensor of shape {tuple(value.tensor_shape)} is not stored one row per output")- halves = (data[:rows].clone(), data[rows:].clone())- shapes = (torch.Size((rows, cols)), torch.Size((total - rows, cols)))- return tuple( # type: ignore[return-value]- GGMLTensor(part, value._ggml_quantization_type, shape, value.compute_dtype)- for part, shape in zip(halves, shapes, strict=True)- )- return value[:rows], value[rows:]--def split_fused_gate_up(sd: dict[str, Any]) -> dict[str, Any]:"""Split every `img_mlp.gate_up` weight, with its quantization sidecars, into `gate_layer` and `proj`.@@ -61,7 +41,7 @@ def split_fused_gate_up(sd: dict[str, Any]) -> dict[str, Any]:if rows % 2:raise ValueError(f"{key} has {rows} rows, which do not split into gate and up halves")halves_by_stem[stem] = rows // 2- gate, up = _split_rows(sd[key], rows // 2)+ gate, up = split_rows(sd[key], rows // 2)out[f"{stem.replace(GATE_UP[:-1], '.img_mlp.gate_layer')}.weight"] = gateout[f"{stem.replace(GATE_UP[:-1], '.img_mlp.proj')}.weight"] = upfor key in fused - weights:@@ -78,7 +58,7 @@ def split_fused_gate_up(sd: dict[str, Any]) -> dict[str, Any]:and value.shape[0] == 2 * halves_by_stem[stem])if per_row:- out[gate_key], out[proj_key] = _split_rows(value, halves_by_stem[stem])+ out[gate_key], out[proj_key] = split_rows(value, halves_by_stem[stem])else:out[gate_key], out[proj_key] = value, valuereturn outdiff --git a/invokeai/frontend/api/openapi.json b/invokeai/frontend/api/openapi.jsonindex 537a606fe5..0d524fb0df 100644--- a/invokeai/frontend/api/openapi.json+++ b/invokeai/frontend/api/openapi.json@@ -38969,7 +38969,7 @@"category": "model","class": "invocation","classification": "prototype",- "description": "Load a FLUX.2 [dev] transformer plus its Mistral text encoder and VAE.\n\nFLUX.2 [dev] is a 32B guidance-distilled rectified flow transformer that uses\nMistral Small 3.1 (24B) as its sole text encoder, sharing the 32-channel\nAutoencoderKLFlux2 VAE with FLUX.2 Klein.\n\nWhen the transformer is a Diffusers-format checkpoint, both VAE and Mistral\nencoder can be extracted directly from the main model. For single-file\nsafetensors or GGUF transformers, you must supply standalone VAE and\nMistral encoder models, or point at a Diffusers FLUX.2 [dev] checkout for\nsub-model extraction.",+ "description": "Load a FLUX.2 [dev] transformer plus its Mistral text encoder and VAE.\n\nFLUX.2 [dev] is a 32B guidance-distilled rectified flow transformer that uses\nMistral Small 3.2 (24B) as its sole text encoder, sharing the 32-channel\nAutoencoderKLFlux2 VAE with FLUX.2 Klein.\n\nWhen the transformer is a Diffusers-format checkpoint, both VAE and Mistral\nencoder can be extracted directly from the main model. For single-file\nsafetensors or GGUF transformers, you must supply standalone VAE and\nMistral encoder models, or point at a Diffusers FLUX.2 [dev] checkout for\nsub-model extraction.","node_pack": "invokeai","properties": {"id": {@@ -39140,7 +39140,7 @@"category": "prompt","class": "invocation","classification": "prototype",- "description": "Encode a prompt for FLUX.2 [dev] using its Mistral Small 3.1 text encoder.",+ "description": "Encode a prompt for FLUX.2 [dev] using its Mistral Small 3.2 text encoder.","node_pack": "invokeai","properties": {"id": {@@ -90546,7 +90546,7 @@"variant"],"title": "MistralEncoder_Checkpoint_Config",- "description": "Configuration for a single-file Mistral text encoder (safetensors).\n\nAccepts both 30-layer cow (Comfy-Org bf16/fp8/fp4) and 40-layer Mistral Small 3\n(BFL canonical / upstream Mistral 3.x single-files). The loader uses the\ndetected variant to decide whether to keep or strip the final RMSNorm."+ "description": "Configuration for a single-file Mistral text encoder (safetensors).\n\nAccepts both 30-layer cow (Comfy-Org bf16/fp8/fp4) and 40-layer Mistral Small 3\n(BFL's release / upstream Mistral 3.x single-files). The loader uses the\ndetected variant to decide whether to keep or strip the final RMSNorm."},"MistralEncoder_Diffusers_Config": {"properties": {@@ -90687,7 +90687,7 @@"variant"],"title": "MistralEncoder_Diffusers_Config",- "description": "Configuration for a Mistral text encoder in HuggingFace transformers/diffusers folder layout.\n\nMatches:\n- Full pipelines downloaded as just the `text_encoder/` subfolder\n (e.g. `black-forest-labs/FLUX.2-dev/text_encoder/`)\n- Quantized variants such as `diffusers/FLUX.2-dev-bnb-4bit/text_encoder/`\n\nDoes NOT match a full FLUX.2 pipeline directory \u2014 those are picked up by the\n`Main_Diffusers_Flux2_Config` instead.\n\nAccepts both:\n- 30-layer \"cow\" distillation (recommended, produces the cleanest output)\n- 40-layer Mistral Small 3 (BFL canonical / upstream Mistral 3.x \u2014 also works,\n slightly weaker prompt adherence than cow in our tests)\n\nThe variant field records which one was probed so the loader can decide\nwhether to keep the final RMSNorm (40-layer) or strip it (30-layer cow)."+ "description": "Configuration for a Mistral text encoder in HuggingFace transformers/diffusers folder layout.\n\nMatches:\n- Full pipelines downloaded as just the `text_encoder/` subfolder\n (e.g. `black-forest-labs/FLUX.2-dev/text_encoder/`)\n- Quantized variants such as `diffusers/FLUX.2-dev-bnb-4bit/text_encoder/`\n\nDoes NOT match a full FLUX.2 pipeline directory \u2014 those are picked up by the\n`Main_Diffusers_Flux2_Config` instead.\n\nAccepts both:\n- 40-layer Mistral Small 3 (BFL's ``text_encoder/`` or upstream Mistral Small 3.x)\n- the 30-layer \"cow\" build, its first 30 layers\n\nThe variant field records which one was probed so the loader can decide\nwhether to keep the final RMSNorm (40-layer) or strip it (30-layer cow)."},"MistralEncoder_GGUF_Config": {"properties": {diff --git a/invokeai/frontend/api/schema.ts b/invokeai/frontend/api/schema.tsindex d8fdaa0ee3..6ba0932345 100644--- a/invokeai/frontend/api/schema.ts+++ b/invokeai/frontend/api/schema.ts@@ -15039,7 +15039,7 @@ export type components = {* @description Load a FLUX.2 [dev] transformer plus its Mistral text encoder and VAE.** FLUX.2 [dev] is a 32B guidance-distilled rectified flow transformer that uses- * Mistral Small 3.1 (24B) as its sole text encoder, sharing the 32-channel+ * Mistral Small 3.2 (24B) as its sole text encoder, sharing the 32-channel* AutoencoderKLFlux2 VAE with FLUX.2 Klein.** When the transformer is a Diffusers-format checkpoint, both VAE and Mistral@@ -15138,7 +15138,7 @@ export type components = {};/*** Prompt - FLUX.2 [dev]- * @description Encode a prompt for FLUX.2 [dev] using its Mistral Small 3.1 text encoder.+ * @description Encode a prompt for FLUX.2 [dev] using its Mistral Small 3.2 text encoder.*/Flux2DevTextEncoderInvocation: {/**@@ -38982,7 +38982,7 @@ export type components = {* @description Configuration for a single-file Mistral text encoder (safetensors).** Accepts both 30-layer cow (Comfy-Org bf16/fp8/fp4) and 40-layer Mistral Small 3- * (BFL canonical / upstream Mistral 3.x single-files). The loader uses the+ * (BFL's release / upstream Mistral 3.x single-files). The loader uses the* detected variant to decide whether to keep or strip the final RMSNorm.*/MistralEncoder_Checkpoint_Config: {@@ -39082,9 +39082,8 @@ export type components = {* `Main_Diffusers_Flux2_Config` instead.** Accepts both:- * - 30-layer "cow" distillation (recommended, produces the cleanest output)- * - 40-layer Mistral Small 3 (BFL canonical / upstream Mistral 3.x — also works,- * slightly weaker prompt adherence than cow in our tests)+ * - 40-layer Mistral Small 3 (BFL's ``text_encoder/`` or upstream Mistral Small 3.x)+ * - the 30-layer "cow" build, its first 30 layers** The variant field records which one was probed so the loader can decide* whether to keep the final RMSNorm (40-layer) or strip it (30-layer cow).diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex 3a442b809d..c8bb200e64 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -1032,7 +1032,7 @@"mistralEncoder": {"heading": "Mistral Encoder","paragraphs": [- "FLUX.2 [dev] reads your prompt with the Mistral Small 3.1 text encoder. A single-file or GGUF checkpoint does not carry one, so it has to be selected here."+ "FLUX.2 [dev] reads your prompt with the Mistral Small 3.2 text encoder. A single-file or GGUF checkpoint does not carry one, so it has to be selected here."]},"model": {diff --git a/invokeai/frontend/webv2/src/features/upscale/core/settings.ts b/invokeai/frontend/webv2/src/features/upscale/core/settings.tsindex ed036c05fb..cc59716a3b 100644--- a/invokeai/frontend/webv2/src/features/upscale/core/settings.ts+++ b/invokeai/frontend/webv2/src/features/upscale/core/settings.ts@@ -207,7 +207,7 @@ const flux2KleinQwen3Slot = (model: MainModelConfig): UpscaleComponentSlot => ({field: 'qwen3EncoderModel',label: (typeof model.variant === 'string' && FLUX2_KLEIN_QWEN3_LABELS[model.variant]) || 'Qwen3 encoder',});-// FLUX.2 [dev] reads Mistral Small 3.1. ERNIE-Image's Ministral 3B is the same model type, and [dev] was not+// FLUX.2 [dev] reads Mistral Small 3.2. ERNIE-Image's Ministral 3B is the same model type, and [dev] was not// trained on it.const FLUX2_MISTRAL_SLOT: UpscaleComponentSlot = {accepts: isFlux2MistralEncoder,diff --git a/tests/backend/model_manager/configs/test_ministral3_encoder_config.py b/tests/backend/model_manager/configs/test_ministral3_encoder_config.pyindex d169733e0e..d617c9cbc9 100644--- a/tests/backend/model_manager/configs/test_ministral3_encoder_config.py+++ b/tests/backend/model_manager/configs/test_ministral3_encoder_config.py@@ -13,7 +13,6 @@ import pytestimport torchfrom safetensors.torch import save_file-from invokeai.backend.model_manager.configs import mistral_encoder as configs_mistral_encoderfrom invokeai.backend.model_manager.configs.factory import ModelConfigFactoryfrom invokeai.backend.model_manager.configs.identification_utils import NotAMatchErrorfrom invokeai.backend.model_manager.configs.mistral_encoder import (@@ -29,6 +28,8 @@ _TEKKEN_VOCAB = 131072_MINISTRAL_3B = (3072, 26)_COW = (5120, 30)_MISTRAL_24B = (5120, 40)+# Mistral Small 3's MLP width, which the FLUX.2 encoders also have to match.+_MISTRAL_3_MLP = 32768def _encoder_tensors(@@ -36,12 +37,14 @@ def _encoder_tensors(num_layers: int,vocab_size: int = _TEKKEN_VOCAB,*,+ mlp_width: int | None = None,with_vision_stack: bool = False,) -> dict[str, torch.Tensor]:"""A Mistral-family state dict at the given geometry, with one column per row kept tiny.- Only the embedding carries the real width -- that and the layer count are what the probe- reads. `torch.zeros` keeps the fixture a few MB rather than the size of a real encoder.+ Only the embedding carries the real width and the layer-0 gate projection the MLP width --+ those and the layer count are what the probe reads. `torch.zeros` keeps the fixture a few MB+ rather than the size of a real encoder.`with_vision_stack` reproduces the Mistral3 multimodal layout the released Ministral 3Bencoder ships. The FLUX.2 encoders are text-only, so it stays off for them.@@ -49,6 +52,8 @@ def _encoder_tensors(tensors = {"model.embed_tokens.weight": torch.zeros(vocab_size, hidden_size, dtype=torch.bfloat16)}for layer in range(num_layers):tensors[f"model.layers.{layer}.self_attn.q_proj.weight"] = torch.zeros(4, 4, dtype=torch.bfloat16)+ if mlp_width is not None:+ tensors["model.layers.0.mlp.gate_proj.weight"] = torch.zeros(mlp_width, 4, dtype=torch.bfloat16)if with_vision_stack:tensors["vision_tower.transformer.layers.0.attention.q_proj.weight"] = torch.zeros(4, 4, dtype=torch.bfloat16)tensors["multi_modal_projector.linear_1.weight"] = torch.zeros(4, 4, dtype=torch.bfloat16)@@ -79,7 +84,7 @@ def test_the_flux2_encoders_keep_their_variants(tmp_path: Path, geometry: tuple[int, int], expected: MistralVariantType) -> None:"""Widening the probe must not reclassify the encoders that already installed."""- config = _identify(tmp_path / "mistral.safetensors", _encoder_tensors(*geometry))+ config = _identify(tmp_path / "mistral.safetensors", _encoder_tensors(*geometry, mlp_width=_MISTRAL_3_MLP))assert isinstance(config, MistralEncoder_Checkpoint_Config)assert config.variant is expected@@ -95,8 +100,11 @@ def test_the_flux2_encoders_keep_their_variants()def test_a_geometry_between_the_families_is_refused(tmp_path: Path, hidden_size: int, num_layers: int) -> None:"""The pairs are matched as pairs. Accepting a loose combination would hand the loader a- variant whose model class does not fit the weights."""- config = _identify(tmp_path / "mixed.safetensors", _encoder_tensors(hidden_size, num_layers))+ variant whose model class does not fit the weights. The MLP is Mistral Small 3's, so the depth is+ what refuses the 5120-wide case."""+ config = _identify(+ tmp_path / "mixed.safetensors", _encoder_tensors(hidden_size, num_layers, mlp_width=_MISTRAL_3_MLP)+ )assert not isinstance(config, MistralEncoder_Checkpoint_Config)@@ -140,27 +148,6 @@ def test_the_released_encoder_folder_is_identified_too(tmp_path: Path) -> None:assert config.variant is MistralVariantType.Ministral3B-def test_a_ministral_gguf_is_refused_rather_than_loaded_as_a_mistral(- tmp_path: Path, monkeypatch: pytest.MonkeyPatch-) -> None:- """The GGUF loader builds a `MistralModel`, which has neither Ministral's YaRN scaling nor its- attention scale -- it would load cleanly and encode garbage. The refusal has to sit ahead of- the variant lookup, so this pins the ordering rather than the message.-- `_has_ggml_tensors` stands in for a real GGUF file: building one here would cost far more than- the ordering it protects.- """- monkeypatch.setattr(configs_mistral_encoder, "_has_ggml_tensors", lambda _state_dict: True)-- config = _identify(- tmp_path / "ministral-3-3b-q8.gguf.safetensors",- _encoder_tensors(*_MINISTRAL_3B, with_vision_stack=True),- )-- assert not isinstance(config, MistralEncoder_Checkpoint_Config)- assert getattr(config, "type", None) is not ModelType.MistralEncoder--def test_the_prompt_enhancer_is_not_claimed_as_an_encoder(tmp_path: Path) -> None:"""ERNIE-Image's prompt enhancer sits in the same released folder as the encoder and carriesthe identical geometry, vocabulary and embedded Tekken vocab -- it is a bare `Ministral3-diff --git a/tests/backend/model_manager/configs/test_mistral_small3_encoder_config.py b/tests/backend/model_manager/configs/test_mistral_small3_encoder_config.pynew file mode 100644index 0000000000..20be54a640--- /dev/null+++ b/tests/backend/model_manager/configs/test_mistral_small3_encoder_config.py@@ -0,0 +1,265 @@+"""Identification of FLUX.2 [dev]'s Mistral Small 3 encoder against the models that share its shape.++Width, depth and the Tekken vocabulary do not settle it alone. Mistral NeMo 12B has all three and a+narrower MLP; Qwen3-14B has the width and depth under another llama.cpp architecture; Ministral 3B is+a Mistral the GGUF loader cannot build. Each would install, load cleanly and condition FLUX.2 with+the wrong model.++GGUF fixtures are headers only -- shapes and metadata, in the identification suite's stripped form --+because the real tensors run to gigabytes and identification never reads them. Real stripped headers of+llama.cpp builds under both architecture names (unsloth's ``llama``, a newer ``mistral3``) and of gguf-org's+cow build live in ``tests/model_identification/stripped_models``. One real file, at a scaled-down geometry,+checks that the install's header read sees what those fixtures hold.+"""++import gc+import json+from pathlib import Path++import gguf+import numpy as np+import pytest+import torch++from invokeai.backend.model_manager.configs import mistral_encoder+from invokeai.backend.model_manager.configs.factory import ModelConfigFactory+from invokeai.backend.model_manager.configs.identification_utils import InvalidMatchError, NotAMatchError+from invokeai.backend.model_manager.configs.mistral_encoder import (+ MistralEncoder_Diffusers_Config,+ MistralEncoder_GGUF_Config,+)+from invokeai.backend.model_manager.model_on_disk import ModelOnDisk+from invokeai.backend.model_manager.taxonomy import MistralVariantType+from invokeai.backend.quantization.gguf.ggml_tensor import GGMLTensor+from tests.model_identification.strip_model import create_stripped_model+from tests.model_identification.stripped_model_on_disk import StrippedModelOnDisk++_TEKKEN_VOCAB = 131072+_MISTRAL_SMALL_3 = (5120, 40, 32768)+_MISTRAL_NEMO = (5120, 40, 14336)+_MINISTRAL_3B = (3072, 26, 9216)++[email protected](autouse=True)+def _collect_only_this_tests_objects():+ """Closing a GGUF reader runs gc.collect(), which walks the worker's whole heap -- over a second per test+ late in a session. Freezing what existed before the test leaves each collection to the test's own objects."""+ gc.freeze()+ yield+ gc.unfreeze()+++def _ggml(rows: int, cols: int) -> GGMLTensor:+ return GGMLTensor(+ torch.empty((rows, 1), dtype=torch.uint8, device="meta"),+ gguf.GGMLQuantizationType.Q4_K,+ torch.Size((rows, cols)),+ torch.float32,+ )+++def _llamacpp_tensors(hidden_size: int, num_layers: int, mlp_width: int) -> dict[str, GGMLTensor]:+ tensors = {+ "token_embd.weight": _ggml(_TEKKEN_VOCAB, hidden_size),+ "blk.0.ffn_gate.weight": _ggml(mlp_width, hidden_size),+ }+ tensors.update({f"blk.{layer}.attn_q.weight": _ggml(4096, hidden_size) for layer in range(num_layers)})+ return tensors+++def _hf_named_tensors(hidden_size: int, num_layers: int, mlp_width: int) -> dict[str, GGMLTensor]:+ tensors = {+ "model.embed_tokens.weight": _ggml(_TEKKEN_VOCAB, hidden_size),+ "model.layers.0.mlp.gate_proj.weight": _ggml(mlp_width, hidden_size),+ }+ tensors.update(+ {f"model.layers.{layer}.self_attn.q_proj.weight": _ggml(4096, hidden_size) for layer in range(num_layers)}+ )+ return tensors+++def _gguf_header(+ path: Path, tensors: dict[str, GGMLTensor], architecture: str | None, **strings: str+) -> StrippedModelOnDisk:+ """``strings`` are further string metadata, keyed under the architecture's prefix."""+ metadata = {} if architecture is None else {"general.architecture": architecture}+ metadata |= {f"{architecture}.{key}": value for key, value in strings.items()}+ path.write_text(json.dumps({**StrippedModelOnDisk.strip(tensors), StrippedModelOnDisk.METADATA_KEY: metadata}))+ return StrippedModelOnDisk(path)+++def test_a_declared_none_rope_scaling_is_plain_rope(tmp_path: Path) -> None:+ """``rope.scaling.type = "none"`` is how a converter spells unscaled RoPE, so it does not refuse the file."""+ mod = _gguf_header(+ tmp_path / "mistral-small-3.gguf",+ _llamacpp_tensors(*_MISTRAL_SMALL_3),+ "mistral3",+ **{"rope.scaling.type": "none"},+ )++ config = ModelConfigFactory.from_model_on_disk(mod, allow_unknown=False).config++ assert isinstance(config, MistralEncoder_GGUF_Config)+ assert config.variant is MistralVariantType.Mistral24B+++_TINY_VOCAB, _TINY_HIDDEN, _TINY_MLP = 64, 64, 128+++def _shrink_mistral_small_3(monkeypatch: pytest.MonkeyPatch) -> None:+ """Mistral Small 3's width, MLP and vocabulary floor scaled down, so a real file stays a few KB: its+ embedding alone is over 100 MB at the smallest quantization."""+ monkeypatch.setattr(mistral_encoder, "_MISTRAL_3_HIDDEN_SIZE", _TINY_HIDDEN)+ monkeypatch.setattr(mistral_encoder, "_MISTRAL_3_INTERMEDIATE_SIZE", _TINY_MLP)+ monkeypatch.setattr(mistral_encoder, "_MISTRAL_3_MIN_VOCAB_SIZE", _TINY_VOCAB)+++def _write_real_llamacpp_gguf(path: Path, architecture: str, **metadata: str | float) -> Path:+ """A real llama.cpp-named GGUF at the shrunk geometry and the cow build's 30 layers, matrices Q8_0.+ ``metadata`` are further string or float32 fields, keyed under the architecture's prefix."""+ writer = gguf.GGUFWriter(str(path), architecture)+ for key, value in metadata.items():+ if isinstance(value, str):+ writer.add_string(f"{architecture}.{key}", value)+ else:+ writer.add_float32(f"{architecture}.{key}", value)+ shapes = {"token_embd.weight": (_TINY_VOCAB, _TINY_HIDDEN), "blk.0.ffn_gate.weight": (_TINY_MLP, _TINY_HIDDEN)}+ shapes |= {f"blk.{layer}.attn_q.weight": (_TINY_HIDDEN, _TINY_HIDDEN) for layer in range(30)}+ rng = np.random.default_rng(0)+ for name, shape in shapes.items():+ packed = gguf.quantize(rng.standard_normal(shape).astype(np.float32), gguf.GGMLQuantizationType.Q8_0)+ writer.add_tensor(name, packed, raw_shape=packed.shape, raw_dtype=gguf.GGMLQuantizationType.Q8_0)+ writer.write_header_to_file()+ writer.write_kv_data_to_file()+ writer.write_tensors_to_file()+ writer.close()+ return path++[email protected]("_shrink_mistral_small_3")+def test_a_real_gguf_is_identified_from_its_header_as_its_stripped_fixture_is(tmp_path: Path) -> None:+ """Install reads a GGUF's header only: names, logical shapes, quantization types and metadata. The rules+ here have to hold on that read, and a fixture stripped from the file has to identify the same way."""+ path = _write_real_llamacpp_gguf(tmp_path / "cow.gguf", "llama")++ config = ModelConfigFactory.from_model_on_disk(ModelOnDisk(path), allow_unknown=False).config++ assert isinstance(config, MistralEncoder_GGUF_Config)+ assert config.variant is MistralVariantType.Cow+ stripped = create_stripped_model(path, tmp_path / "stripped")+ stripped_mod = StrippedModelOnDisk(stripped.path / path.name)+ stripped_config = ModelConfigFactory.from_model_on_disk(stripped_mod, allow_unknown=False).config+ assert isinstance(stripped_config, MistralEncoder_GGUF_Config)+ assert stripped_config.variant is MistralVariantType.Cow++[email protected]("_shrink_mistral_small_3")+ ("architecture", "metadata", "reason"),+ [+ ("qwen3", {}, "architecture"),+ ("mistral3", {"rope.scaling.type": "yarn"}, "mistral3.rope.scaling.type='yarn'"),+ # Numeric fields alone, no scaling type: what the loader refuses, identification refuses too.+ ("mistral3", {"attention.temperature_scale": 0.5}, "mistral3.attention.temperature_scale=0.5"),+ ("llama", {"rope.scaling.factor": 16.0}, "llama.rope.scaling.factor=16.0"),+ ],+ ids=["another-architecture", "yarn", "attention-temperature", "scaling-factor-without-type"],+)+def test_a_real_gguf_is_refused_by_the_metadata_its_header_carries(+ tmp_path: Path, architecture: str, metadata: dict[str, str | float], reason: str+) -> None:+ """The tensors of the file accepted above, so only the header's metadata can refuse it -- and a fixture+ stripped from the file keeps that metadata, numbers included, so it is refused the same way."""+ path = _write_real_llamacpp_gguf(tmp_path / "other.gguf", architecture, **metadata)+ stripped = create_stripped_model(path, tmp_path / "stripped")++ for mod in (ModelOnDisk(path), StrippedModelOnDisk(stripped.path / path.name)):+ with pytest.raises(NotAMatchError, match=reason):+ MistralEncoder_GGUF_Config.from_model_on_disk(mod, {})++[email protected]("architecture", ["qwen3", None])+def test_a_llamacpp_gguf_of_another_architecture_is_not_a_mistral_encoder(+ tmp_path: Path, architecture: str | None+) -> None:+ """Mistral Small 3's exact geometry, MLP width included, so only the architecture can refuse it.+ The loader would also un-permute its attention rows, which a Qwen3 converter never permuted."""+ mod = _gguf_header(tmp_path / "other.gguf", _llamacpp_tensors(*_MISTRAL_SMALL_3), architecture)++ with pytest.raises(NotAMatchError, match="architecture"):+ MistralEncoder_GGUF_Config.from_model_on_disk(mod, {})+++def test_mistral_nemo_gguf_is_not_a_flux2_encoder(tmp_path: Path) -> None:+ """Mistral NeMo 12B GGUFs -- and their many finetunes -- are llama.cpp ``llama`` builds of Mistral+ Small 3's width, depth and vocabulary. The MLP is what differs."""+ mod = _gguf_header(tmp_path / "mistral-nemo-12b.gguf", _llamacpp_tensors(*_MISTRAL_NEMO), "llama")++ with pytest.raises(NotAMatchError, match="intermediate_size=14336"):+ MistralEncoder_GGUF_Config.from_model_on_disk(mod, {})+++def _write_config(folder: Path, config: dict) -> Path:+ folder.mkdir()+ (folder / "config.json").write_text(json.dumps(config), encoding="utf-8")+ return folder+++def test_a_mistral_nemo_folder_is_not_a_flux2_encoder(tmp_path: Path) -> None:+ """The folder probe recognizes the same geometries as the state-dict probe, MLP width included."""+ folder = _write_config(+ tmp_path / "Mistral-Nemo-Instruct-2407",+ {+ "architectures": ["MistralForCausalLM"],+ "hidden_size": 5120,+ "intermediate_size": 14336,+ "num_hidden_layers": 40,+ },+ )++ with pytest.raises(NotAMatchError, match="recognized Mistral variant"):+ MistralEncoder_Diffusers_Config.from_model_on_disk(ModelOnDisk(folder), {})+++def test_the_bfl_text_encoder_folder_keeps_its_variant(tmp_path: Path) -> None:+ """BFL's ``text_encoder/config.json`` nests the language model's geometry under ``text_config``+ and carries a vision tower whose own ``intermediate_size`` must not be the one read."""+ folder = _write_config(+ tmp_path / "text_encoder",+ {+ "architectures": ["Mistral3ForConditionalGeneration"],+ "text_config": {"hidden_size": 5120, "intermediate_size": 32768, "num_hidden_layers": 40},+ "vision_config": {"hidden_size": 1024, "intermediate_size": 4096, "num_hidden_layers": 24},+ },+ )++ config = ModelConfigFactory.from_model_on_disk(folder, allow_unknown=False).config++ assert isinstance(config, MistralEncoder_Diffusers_Config)+ assert config.variant is MistralVariantType.Mistral24B++[email protected]("layout", ["llama.cpp", "hf_named_with_vision_tower"])+def test_a_ministral_gguf_is_refused_with_what_to_install_for_ernie_image(tmp_path: Path, layout: str) -> None:+ """Refused rather than left to fall back to an unknown model: the user tried to install a+ Ministral 3B, and the message says why and which file works as ERNIE-Image's encoder. Either+ layout, so a repackaging that keeps the vision tower cannot slip past the llama.cpp case. Both declare YaRN, as mistralai's own+ Ministral 3B GGUF does, so this refusal has to win over the plain-RoPE one."""+ if layout == "llama.cpp":+ tensors, architecture = _llamacpp_tensors(*_MINISTRAL_3B), "mistral3"+ else:+ tensors = {+ **_hf_named_tensors(*_MINISTRAL_3B),+ "vision_tower.transformer.layers.0.attention.q_proj.weight": _ggml(4, 4),+ }+ architecture = "ministral3"+ mod = _gguf_header(tmp_path / "ministral-3-3b.gguf", tensors, architecture, **{"rope.scaling.type": "yarn"})++ with pytest.raises(+ InvalidMatchError,+ match="^Ministral 3B GGUFs are not supported: .*'ERNIE-Image Ministral Encoder' starter model",+ ):+ MistralEncoder_GGUF_Config.from_model_on_disk(mod, {})++ assert ModelConfigFactory.from_model_on_disk(mod, allow_unknown=True).config is Nonediff --git a/tests/backend/model_manager/configs/test_sdnq_pipeline_submodel_discovery.py b/tests/backend/model_manager/configs/test_sdnq_pipeline_submodel_discovery.pyindex f80e6ac917..2e50dd2ec3 100644--- a/tests/backend/model_manager/configs/test_sdnq_pipeline_submodel_discovery.py+++ b/tests/backend/model_manager/configs/test_sdnq_pipeline_submodel_discovery.py@@ -547,7 +547,7 @@ def test_a_component_the_loader_always_reads_with_sdnq_needs_safetensors_even_wi# use — makes it identify as itself. Supporting [dev] SDNQ pipelines end to end is separate work._FLUX2_DEV_TRANSFORMER_CONFIG = {- # 3 x Mistral Small 3.1 5120, and 48 heads x 128 head_dim -> see configs/flux2_variant.py+ # 3 x Mistral Small 3 5120, and 48 heads x 128 head_dim -> see configs/flux2_variant.py"joint_attention_dim": 15360,"attention_head_dim": 128,"num_attention_heads": 48,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.pyindex e3ee69642d..acef309ad0 100644--- a/tests/backend/model_manager/load/test_mistral_encoder_gguf_loader.py+++ b/tests/backend/model_manager/load/test_mistral_encoder_gguf_loader.py@@ -6,45 +6,123 @@ output-identical for any real GGUF, but nothing exercised this loader end to endthe shared table, or a change to the prefix handling that follows it, would have surfaced at aFLUX.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``+llama.cpp's converter also regroups each head's query and key rows for its own RoPE, and the loader+has to put them back. Nothing fails when it does not: queries and keys carry the same reordering, so+only RoPE pairs the wrong dimensions, and the first position is unaffected. The fixture for that is+built so it cannot hide: several positions, grouped-query attention (keys regrouped by the query head+count land wrong), and a small RoPE base. Pair 0 turns a radian per position at any base; a small one+makes the other pairs rotate too, where a large one leaves them nearly still.++The GGUFs are real and their matrices genuinely Q8_0, so the weights arrive as the ``GGMLTensor``wrappers the loader has to cope with."""+import gcfrom pathlib import Pathfrom unittest.mock import MagicMock, call, create_autospec+import ggufimport numpy as np+import pytestimport torch+from gguf.quants import quantize+from transformers import MistralConfig, MistralModelfrom invokeai.backend.model_manager.configs.mistral_encoder import MistralEncoder_GGUF_Configfrom 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.mistral_encoder import MistralEncoderGGUFLoaderfrom invokeai.backend.model_manager.taxonomy import MistralVariantTypefrom invokeai.backend.quantization.gguf.ggml_tensor import HOST_DEQUANT_PEAK_COPIES as PEAK_COPIESfrom invokeai.backend.quantization.gguf.ggml_tensor import GGMLTensor+_Q8_0 = gguf.GGMLQuantizationType.Q8_0+# `_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+# The permutation fixture. Q8_0 blocks are 32 wide, so every input dimension is a multiple of 32.+_N_HEAD, _N_HEAD_KV = 2, 1+_P_VOCAB, _P_HIDDEN, _P_FFN, _P_LAYERS = 32, 64, 64, 2+_ROPE_THETA = 10000.0+_CONTEXT = 64+_TOKEN_IDS = torch.tensor([[3, 17, 5, 29, 11, 8]])-def _write_mistral_gguf(path: Path) -> None:- """The llama.cpp tensor set for a tiny Mistral decoder.+# llama.cpp component -> transformers module path within a layer, as `MistralModel` names it.+_LAYER_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",+ "ffn_gate": "mlp.gate_proj",+ "ffn_up": "mlp.up_proj",+ "ffn_down": "mlp.down_proj",+ "attn_norm": "input_layernorm",+ "ffn_norm": "post_attention_layernorm",+}- 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.+[email protected](autouse=True)+def _collect_only_this_tests_objects():+ """Closing a GGUF reader runs gc.collect(), which walks the worker's whole heap. Freezing what existed+ before the test leaves each collection to the test's own objects."""+ gc.freeze()+ yield+ gc.unfreeze()+++def _llamacpp_permute(weights: np.ndarray, n_head: int, n_head_kv: int | None) -> np.ndarray:+ """llama.cpp's ``LlamaModel.permute``, verbatim; its converter runs it on ``q_proj`` with+ ``(n_head, n_head)`` and on ``k_proj`` with ``(n_head, n_head_kv)``.++ https://github.com/ggml-org/llama.cpp/blob/339f3242c761f16c27e5ffcde1d35dcc31933a55/conversion/llama.py#L176-L182"""- import gguf- from gguf.quants import quantize+ if n_head_kv is not None and n_head != n_head_kv:+ n_head = n_head_kv+ return (+ weights.reshape(n_head, 2, weights.shape[0] // n_head // 2, *weights.shape[1:])+ .swapaxes(1, 2)+ .reshape(weights.shape)+ )- tensors: dict[str, tuple[int, ...]] = {- "token_embd.weight": (_VOCAB, _HIDDEN),- "output_norm.weight": (_HIDDEN,),- }++def _write_gguf(path: Path, architecture: str, tensors: dict[str, np.ndarray], metadata: dict[str, int | float | str]):+ """Matrices as Q8_0, vectors F32 — how llama.cpp quantizes a real encoder."""+ writer = gguf.GGUFWriter(str(path), architecture)+ for key, value in metadata.items():+ if isinstance(value, str):+ writer.add_string(key, value)+ elif isinstance(value, float):+ writer.add_float32(key, value)+ else:+ writer.add_uint32(key, value)+ for name, data in tensors.items():+ if data.ndim == 2:+ packed = quantize(data, _Q8_0)+ writer.add_tensor(name, packed, raw_shape=packed.shape, raw_dtype=_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()+ return path+++def _write_uniform_gguf(path: Path) -> Path:+ """The llama.cpp tensor set for a tiny Mistral decoder, every value `_FILL`.++ No `attn_q_norm` / `attn_k_norm`: `MistralModel` has no QK norm, and a real Mistral GGUF carries+ none either.+ """+ shapes: dict[str, tuple[int, ...]] = {"token_embd.weight": (_VOCAB, _HIDDEN), "output_norm.weight": (_HIDDEN,)}for layer in range(_LAYERS):- tensors.update(+ shapes.update({f"blk.{layer}.attn_q.weight": (_HEAD_DIM, _HIDDEN),f"blk.{layer}.attn_k.weight": (_HEAD_DIM, _HIDDEN),@@ -57,28 +135,92 @@ def _write_mistral_gguf(path: Path) -> None:f"blk.{layer}.ffn_norm.weight": (_HIDDEN,),})+ tensors = {name: np.full(shape, _FILL, dtype=np.float32) for name, shape in shapes.items()}+ metadata = {"llama.block_count": _LAYERS, "llama.attention.head_count": 1, "llama.attention.head_count_kv": 1}+ return _write_gguf(path, "llama", tensors, metadata)- 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 _raw_weights() -> dict[str, np.ndarray]:+ """Random weights keyed as bare ``MistralModel`` names them, every row distinct.-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"+ Matrices sit on a power-of-two grid with a full-scale value in every 32-wide block, which Q8_0+ stores exactly, so a load can be compared against them exactly, whatever precision the+ dequantization runs at.+ """+ rng = np.random.default_rng(0)+ q_rows, kv_rows = _N_HEAD * _HEAD_DIM, _N_HEAD_KV * _HEAD_DIM+ shapes: dict[str, tuple[int, ...]] = {"embed_tokens.weight": (_P_VOCAB, _P_HIDDEN), "norm.weight": (_P_HIDDEN,)}+ for layer in range(_P_LAYERS):+ prefix = f"layers.{layer}"+ shapes.update(+ {+ f"{prefix}.self_attn.q_proj.weight": (q_rows, _P_HIDDEN),+ f"{prefix}.self_attn.k_proj.weight": (kv_rows, _P_HIDDEN),+ f"{prefix}.self_attn.v_proj.weight": (kv_rows, _P_HIDDEN),+ f"{prefix}.self_attn.o_proj.weight": (_P_HIDDEN, q_rows),+ f"{prefix}.mlp.gate_proj.weight": (_P_FFN, _P_HIDDEN),+ f"{prefix}.mlp.up_proj.weight": (_P_FFN, _P_HIDDEN),+ f"{prefix}.mlp.down_proj.weight": (_P_HIDDEN, _P_FFN),+ f"{prefix}.input_layernorm.weight": (_P_HIDDEN,),+ f"{prefix}.post_attention_layernorm.weight": (_P_HIDDEN,),+ }+ )+ weights = {}+ for name, shape in shapes.items():+ if len(shape) == 1:+ weights[name] = (1.0 + 0.1 * rng.standard_normal(shape)).astype(np.float32)+ continue+ codes = rng.integers(-127, 128, size=shape)+ codes[:, ::32] = np.where(rng.random(codes[:, ::32].shape) < 0.5, -127, 127)+ weights[name] = (codes * 2.0**-9).astype(np.float32)+ return weights+++def _as_tensors(raw: dict[str, np.ndarray]) -> dict[str, torch.Tensor]:+ return {name: torch.from_numpy(value) for name, value in raw.items()}+++def _llamacpp_metadata(+ architecture: str = "llama", **overrides: int | float | str | None+) -> dict[str, int | float | str]:+ fields: dict[str, int | float | str | None] = {+ "block_count": _P_LAYERS,+ "context_length": _CONTEXT,+ "attention.head_count": _N_HEAD,+ "attention.head_count_kv": _N_HEAD_KV,+ "attention.key_length": _HEAD_DIM,+ "rope.freq_base": _ROPE_THETA,+ **overrides,+ }+ return {f"{architecture}.{key}": value for key, value in fields.items() if value is not None}+++def _write_llamacpp_gguf(+ path: Path,+ raw: dict[str, np.ndarray],+ architecture: str = "llama",+ unprefixed: dict[str, int] | None = None,+ **metadata,+) -> Path:+ """`raw` as llama.cpp's converter writes it: renamed by role, query and key rows permuted.++ `unprefixed` adds metadata keys as given, outside the architecture's prefix."""+ tensors = {"token_embd.weight": raw["embed_tokens.weight"], "output_norm.weight": raw["norm.weight"]}+ for layer in range(_P_LAYERS):+ for component, module in _LAYER_COMPONENTS.items():+ value = raw[f"layers.{layer}.{module}.weight"]+ if component == "attn_q":+ value = _llamacpp_permute(value, _N_HEAD, _N_HEAD)+ elif component == "attn_k":+ value = _llamacpp_permute(value, _N_HEAD, _N_HEAD_KV)+ tensors[f"blk.{layer}.{component}.weight"] = value+ return _write_gguf(+ path, architecture, tensors, {**_llamacpp_metadata(architecture, **metadata), **(unprefixed or {})})+++def _load(tmp_path: Path, monkeypatch, gguf_path: Path, variant=MistralVariantType.Cow, ram_cache=None):+ config = MistralEncoder_GGUF_Config.model_construct(path=str(gguf_path), variant=variant, 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)@@ -108,7 +250,7 @@ def test_the_shared_converter_lands_every_weight_in_the_mistral_module_tree(tmp_`attn_v`, `ffn_gate`/`ffn_up`, the two norms. `test_llamacpp_keys.py` owns that case, where eachcomponent carries a distinct sentinel."""- model = _load(tmp_path, monkeypatch)+ model = _load(tmp_path, monkeypatch, _write_uniform_gguf(tmp_path / "mistral_tiny.gguf"))assert len(model.layers) == _LAYERSfor name, parameter in model.named_parameters():@@ -128,8 +270,172 @@ def test_the_embedding_is_materialized_and_its_copy_reserved(tmp_path, monkeypat"""ram_cache = create_autospec(ModelCache, instance=True)- model = _load(tmp_path, monkeypatch, ram_cache=ram_cache)+ model = _load(tmp_path, monkeypatch, _write_uniform_gguf(tmp_path / "mistral_tiny.gguf"), 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)]+++ "architecture, metadata",+ # A declared "none" scaling is plain RoPE, not a reason to refuse.+ [("llama", {}), ("mistral3", {}), ("mistral3", {"rope.scaling.type": "none"})],+ ids=["llama", "mistral3", "mistral3-none-scaling"],+)+def test_llamacpp_query_and_key_rows_load_in_transformers_order(+ tmp_path, monkeypatch, architecture: str, metadata: dict+) -> None:+ """Both names llama.cpp writes Mistral Small 3 under, with the metadata under each one's prefix.++ Values rows too: llama.cpp leaves them in order, and regrouping them with the others would be+ the same silent corruption. Queries and keys stay packed -- the un-permute gathers quantized rows.+ """+ raw = _raw_weights()+ expected = _as_tensors(raw)+ gguf_path = _write_llamacpp_gguf(tmp_path / "mistral_llamacpp.gguf", raw, architecture, **metadata)++ model = _load(tmp_path, monkeypatch, gguf_path, variant=MistralVariantType.Mistral24B)++ for index, layer in enumerate(model.layers):+ for projection in ("q_proj", "k_proj", "v_proj"):+ weight = getattr(layer.self_attn, projection).weight+ assert isinstance(weight, GGMLTensor)+ assert weight._ggml_quantization_type is _Q8_0+ assert torch.equal(+ weight.get_dequantized_tensor(), expected[f"layers.{index}.self_attn.{projection}.weight"]+ )+++def test_a_llamacpp_gguf_repeating_the_header_as_metadata_loads(tmp_path, monkeypatch) -> None:+ """Install reads such a file with the header-tolerant reader; the loader's metadata read must too,+ or the architecture reads as None and a file install accepted is refused at load."""+ raw = _raw_weights()+ expected = _as_tensors(raw)+ gguf_path = _write_llamacpp_gguf(tmp_path / "mistral_llamacpp.gguf", raw, unprefixed={"GGUF.kv_count": 3})++ model = _load(tmp_path, monkeypatch, gguf_path, variant=MistralVariantType.Mistral24B)++ for index, layer in enumerate(model.layers):+ for projection in ("q_proj", "k_proj"):+ weight = getattr(layer.self_attn, projection).weight+ assert torch.equal(+ weight.get_dequantized_tensor(), expected[f"layers.{index}.self_attn.{projection}.weight"]+ )+++def test_a_llamacpp_encoder_computes_what_the_reference_model_computes(tmp_path, monkeypatch) -> None:+ """The loaded GGUF against a dense `MistralModel` holding the same weights in transformers order.++ The comparison that matters to a FLUX.2 [dev] user: hidden states over several positions, where+ RoPE is what a wrong row order changes. Run as the model cache runs it, through the custom layers+ that dequantize GGML weights.+ """+ raw = _raw_weights()+ model = _load(+ tmp_path,+ monkeypatch,+ _write_llamacpp_gguf(tmp_path / "mistral_llamacpp.gguf", raw),+ variant=MistralVariantType.Mistral24B,+ )+ apply_custom_layers_to_model(model)+ reference = MistralModel(+ MistralConfig(+ vocab_size=_P_VOCAB,+ hidden_size=_P_HIDDEN,+ intermediate_size=_P_FFN,+ num_hidden_layers=_P_LAYERS,+ num_attention_heads=_N_HEAD,+ num_key_value_heads=_N_HEAD_KV,+ head_dim=_HEAD_DIM,+ max_position_embeddings=_CONTEXT,+ rms_norm_eps=1e-5,+ rope_theta=_ROPE_THETA,+ tie_word_embeddings=False,+ )+ ).eval()+ reference.load_state_dict(_as_tensors(raw), strict=True)++ with torch.no_grad():+ actual = model(input_ids=_TOKEN_IDS).last_hidden_state+ expected = reference(input_ids=_TOKEN_IDS).last_hidden_state++ torch.testing.assert_close(actual, expected, rtol=1e-5, atol=1e-5)+++def test_an_hf_named_gguf_is_loaded_in_the_order_it_is_stored(tmp_path, monkeypatch) -> None:+ """gguf-org's cow builds -- every Mistral GGUF starter -- keep transformers' names and order and+ carry no head counts. Regrouping their rows would corrupt every starter install."""+ raw = _raw_weights()+ expected = _as_tensors(raw)+ hf_named = {f"model.{name}": value for name, value in raw.items()}+ gguf_path = _write_gguf(tmp_path / "cow.gguf", "cow", hf_named, {})++ model = _load(tmp_path, monkeypatch, gguf_path)++ for index, layer in enumerate(model.layers):+ for projection in ("q_proj", "k_proj"):+ weight = getattr(layer.self_attn, projection).weight+ assert torch.equal(+ weight.get_dequantized_tensor(), expected[f"layers.{index}.self_attn.{projection}.weight"]+ )+++ "architecture, metadata, match",+ [+ # A Qwen3 converter never permutes; un-permuting one would scramble it.+ ("qwen3", {}, "architecture 'qwen3'"),+ ("llama", {"attention.head_count_kv": None}, "without llama.attention.head_count_kv,"),+ # The rows are 2 x 128 query and 1 x 128 key; the metadata has to agree, or the regrouping is wrong.+ ("llama", {"attention.head_count": 4}, "4 query and 1 key/value heads"),+ # The rows agree with 4 x 64 and 2 x 64, but the model builds 128-wide heads, whose RoPE would+ # pair dimensions of different heads.+ ("llama", {"attention.head_count": 4, "attention.head_count_kv": 2, "attention.key_length": 64}, "of width 64"),+ # Devstral Small 2's shape: Mistral Small 3's geometry, but YaRN, which a plain MistralModel ignores.+ ("mistral3", {"rope.scaling.type": "yarn", "rope.scaling.factor": 16.0}, "rope.scaling.type='yarn'"),+ # A YaRN parameter without a declared scaling type is refused just the same.+ ("llama", {"rope.scaling.yarn_log_multiplier": 1.0}, "llama.rope.scaling.yarn_log_multiplier=1.0"),+ # Llama 4-style attention temperature, also numeric only.+ ("mistral3", {"attention.temperature_scale": 0.5}, "mistral3.attention.temperature_scale=0.5"),+ ],+)+def test_a_llamacpp_gguf_the_rows_cannot_be_trusted_for_is_refused(+ tmp_path, monkeypatch, architecture: str, metadata: dict, match: str+) -> None:+ """For records installed before identification refused such files: the alternative to refusing+ is an encoder that loads cleanly and conditions wrongly."""+ gguf_path = _write_llamacpp_gguf(tmp_path / "mistral_llamacpp.gguf", _raw_weights(), architecture, **metadata)++ with pytest.raises(ValueError, match=match):+ _load(tmp_path, monkeypatch, gguf_path, variant=MistralVariantType.Mistral24B)++[email protected]("layout", ["llama.cpp", "hf_named"])+def test_a_5120_wide_encoder_without_mistral_small_3s_mlp_is_refused(tmp_path, monkeypatch, layout: str) -> None:+ """Records of Mistral NeMo 12B -- Mistral Small 3's width, depth, heads and vocabulary, a 14336-wide+ MLP -- made before identification refused it, and HF-named files of other 5120-wide models.++ Only what the guard reads is written, at the real width; the MLP is narrower still, which the guard+ treats as it treats NeMo's.+ """+ hidden, mlp_width = 5120, 64+ shapes = {+ "embed": (_P_VOCAB, hidden),+ "q": (_N_HEAD * _HEAD_DIM, hidden),+ "k": (_N_HEAD_KV * _HEAD_DIM, hidden),+ "gate": (mlp_width, hidden),+ }+ if layout == "llama.cpp":+ names = {"embed": "token_embd.weight", "q": "blk.0.attn_q.weight", "k": "blk.0.attn_k.weight"}+ names["gate"] = "blk.0.ffn_gate.weight"+ architecture, metadata = "llama", _llamacpp_metadata()+ else:+ names = {"embed": "model.embed_tokens.weight", "q": "model.layers.0.self_attn.q_proj.weight"}+ names |= {"k": "model.layers.0.self_attn.k_proj.weight", "gate": "model.layers.0.mlp.gate_proj.weight"}+ architecture, metadata = "cow", {}+ tensors = {names[role]: np.full(shape, _FILL, dtype=np.float32) for role, shape in shapes.items()}+ gguf_path = _write_gguf(tmp_path / "nemo-like.gguf", architecture, tensors, metadata)++ with pytest.raises(ValueError, match="nemo-like.gguf is 5120 wide with an MLP of width 64"):+ _load(tmp_path, monkeypatch, gguf_path, variant=MistralVariantType.Mistral24B)diff --git a/tests/backend/model_manager/util/test_llamacpp_keys.py b/tests/backend/model_manager/util/test_llamacpp_keys.pyindex 7a02178691..1d79c9119a 100644--- a/tests/backend/model_manager/util/test_llamacpp_keys.py+++ b/tests/backend/model_manager/util/test_llamacpp_keys.py@@ -1,7 +1,7 @@"""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*+tower (Krea-2 / Ideogram 4) and Mistral Small 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 butshape-compatible module. `attn_q`/`attn_k` and `ffn_gate`/`ffn_up` are same-shaped pairs, so@@ -9,10 +9,12 @@ transposing either pair would load cleanly and produce wrong conditioning with n"""import pytest+import torchfrom invokeai.backend.model_manager.util.llamacpp_keys import (convert_llamacpp_decoder_keys,is_llamacpp_decoder_state_dict,+ undo_llamacpp_qk_permutation,)@@ -122,3 +124,51 @@ def test_a_component_is_matched_by_position_not_by_containment() -> None:"model.layers.0.cross_attn_q.weight": "cross_q","model.layers.0.some.attn_v.weight": "nested_v",}+++def _llamacpp_permute(weights: torch.Tensor, n_head: int, n_head_kv: int | None) -> torch.Tensor:+ """llama.cpp's ``LlamaModel.permute``, verbatim.++ https://github.com/ggml-org/llama.cpp/blob/339f3242c761f16c27e5ffcde1d35dcc31933a55/conversion/llama.py#L176-L182+ """+ if n_head_kv is not None and n_head != n_head_kv:+ n_head = n_head_kv+ return (+ weights.reshape(n_head, 2, weights.shape[0] // n_head // 2, *weights.shape[1:])+ .swapaxes(1, 2)+ .reshape(weights.shape)+ )+++def test_undoing_the_permutation_restores_query_and_key_rows_of_every_layer() -> None:+ """Weights and biases, queries regrouped by the query heads and keys by the key/value heads --+ the counts differ under grouped-query attention, which is what makes the second one checkable.+ Every row is its own index, so any misplaced row shows."""+ n_head, n_head_kv, head_dim = 4, 2, 8+ hf = {}+ for layer in (0, 11):+ prefix = f"model.layers.{layer}.self_attn"+ for projection, heads in (("q_proj", n_head), ("k_proj", n_head_kv)):+ rows = torch.arange(heads * head_dim, dtype=torch.float32) + 1000 * layer+ hf[f"{prefix}.{projection}.weight"] = rows[:, None].expand(-1, 3).clone()+ hf[f"{prefix}.{projection}.bias"] = rows.clone()+ gguf = {+ key: _llamacpp_permute(value, n_head, n_head if ".q_proj." in key else n_head_kv) for key, value in hf.items()+ }+ untouched = torch.arange(n_head_kv * head_dim, dtype=torch.float32)+ sd = {**gguf, "model.layers.0.self_attn.v_proj.weight": untouched}++ undo_llamacpp_qk_permutation(sd, n_head, n_head_kv)++ assert sd.keys() == {*hf, "model.layers.0.self_attn.v_proj.weight"}+ for key, value in hf.items():+ assert torch.equal(sd[key], value), key+ assert sd["model.layers.0.self_attn.v_proj.weight"] is untouched+++def test_rows_that_do_not_form_whole_heads_of_rotary_pairs_are_refused() -> None:+ """Head counts from a header that disagrees with the tensor would regroup across head boundaries."""+ sd = {"model.layers.0.self_attn.k_proj.weight": torch.zeros(12, 4)}++ with pytest.raises(ValueError, match="k_proj.weight has 12 rows"):+ undo_llamacpp_qk_permutation(sd, n_head=8, n_head_kv=4)diff --git a/tests/backend/quantization/gguf/test_row_ops.py b/tests/backend/quantization/gguf/test_row_ops.pynew file mode 100644index 0000000000..d135cecdae--- /dev/null+++ b/tests/backend/quantization/gguf/test_row_ops.py@@ -0,0 +1,39 @@+import gguf+import pytest+import torch++from invokeai.backend.quantization.gguf.ggml_tensor import GGMLTensor+from invokeai.backend.quantization.gguf.row_ops import take_rows++_Q8_0 = gguf.GGMLQuantizationType.Q8_0+++def _q8_0(rows: int, cols: int) -> tuple[GGMLTensor, torch.Tensor]:+ values = torch.randn(rows, cols, generator=torch.Generator().manual_seed(0))+ packed = torch.from_numpy(gguf.quantize(values.numpy(), _Q8_0))+ tensor = GGMLTensor(packed, _Q8_0, torch.Size((rows, cols)), torch.float32)+ return tensor, tensor.get_dequantized_tensor()+++def test_rows_of_a_packed_tensor_are_gathered_without_unpacking() -> None:+ """A subset in a new order, so the result's shape has to follow the index, not the source."""+ tensor, dequantized = _q8_0(6, 64)+ index = torch.tensor([4, 0, 5])++ rows = take_rows(tensor, index)++ assert isinstance(rows, GGMLTensor)+ assert rows._ggml_quantization_type is _Q8_0+ assert rows.compute_dtype is torch.float32+ assert rows.shape == (3, 64)+ assert torch.equal(rows.get_dequantized_tensor(), dequantized[index])+++def test_packed_data_not_stored_one_row_per_output_is_refused() -> None:+ """ComfyUI-GGUF reshapes tensors its quantizer rejects and records the native shape; such packed+ rows are not output rows, and gathering them would mix values across outputs."""+ tensor, _ = _q8_0(6, 64)+ reshaped = GGMLTensor(tensor.quantized_data.reshape(3, -1), _Q8_0, tensor.tensor_shape, torch.float32)++ with pytest.raises(ValueError, match="not stored one row per output"):+ take_rows(reshaped, torch.tensor([0, 1]))diff --git a/tests/model_identification/strip_model.py b/tests/model_identification/strip_model.pyindex 66e7c507bf..007a47aad5 100644--- a/tests/model_identification/strip_model.py+++ b/tests/model_identification/strip_model.py@@ -66,6 +66,7 @@ def create_stripped_model(model_path: Path, output_dir: Path):original_state_dict = stripped_mod.load_state_dict(component_path)stripped_state_dict = StrippedModelOnDisk.strip(original_state_dict)+ # Per file: `stripped_mod` is the clone's directory, whose own metadata is always empty.metadata = stripped_mod.metadata(component_path)contents = {**stripped_state_dict, StrippedModelOnDisk.METADATA_KEY: metadata}component_path.write_text(json.dumps(contents, indent=2))diff --git a/tests/model_identification/stripped_model_on_disk.py b/tests/model_identification/stripped_model_on_disk.pyindex 387e04839e..aabe7dd9c3 100644--- a/tests/model_identification/stripped_model_on_disk.py+++ b/tests/model_identification/stripped_model_on_disk.py@@ -17,7 +17,7 @@ class StrippedModelOnDisk(ModelOnDisk):path = self.resolve_weight_file(path)return self.load_stripped_model(path)- def metadata(self, path: Optional[Path] = None) -> dict[str, str]:+ def metadata(self, path: Optional[Path] = None) -> dict[str, Any]:path = self.resolve_weight_file(path)with open(path, "r") as f:contents = json.load(f)diff --git a/tests/model_identification/stripped_models/3a8c2042-2bc4-4af4-b0ce-a72e53ff95b4/Mistral-Small-3.2-24B-Instruct-2506-DASHQ-IQ2_XXS.gguf b/tests/model_identification/stripped_models/3a8c2042-2bc4-4af4-b0ce-a72e53ff95b4/Mistral-Small-3.2-24B-Instruct-2506-DASHQ-IQ2_XXS.ggufnew file mode 100644index 0000000000..54a2bf870e--- /dev/null+++ b/tests/model_identification/stripped_models/3a8c2042-2bc4-4af4-b0ce-a72e53ff95b4/Mistral-Small-3.2-24B-Instruct-2506-DASHQ-IQ2_XXS.gguf@@ -0,0 +1,3 @@+version https://git-lfs.github.com/spec/v1+oid sha256:2989df2d8fbce8f7acf73e27d1f999f69e6cd29dad4ea753ca541b907d7bec51+size 132517diff --git a/tests/model_identification/stripped_models/3a8c2042-2bc4-4af4-b0ce-a72e53ff95b4/__test_metadata__.json b/tests/model_identification/stripped_models/3a8c2042-2bc4-4af4-b0ce-a72e53ff95b4/__test_metadata__.jsonnew file mode 100644index 0000000000..37590958b3--- /dev/null+++ b/tests/model_identification/stripped_models/3a8c2042-2bc4-4af4-b0ce-a72e53ff95b4/__test_metadata__.json@@ -0,0 +1,3 @@+version https://git-lfs.github.com/spec/v1+oid sha256:22535a6f51ddbdc4b10b599498cde7201ce70cd37fd744e343acae74b4ed5306+size 698diff --git a/tests/model_identification/stripped_models/9d793671-2ead-42fa-b6ec-48f945671d68/__test_metadata__.json b/tests/model_identification/stripped_models/9d793671-2ead-42fa-b6ec-48f945671d68/__test_metadata__.jsonnew file mode 100644index 0000000000..1255ed1e17--- /dev/null+++ b/tests/model_identification/stripped_models/9d793671-2ead-42fa-b6ec-48f945671d68/__test_metadata__.json@@ -0,0 +1,3 @@+version https://git-lfs.github.com/spec/v1+oid sha256:0ca2b727b9298442c3f1cb767442fe362459b9607a6dd6df39ff9149644503e9+size 509diff --git a/tests/model_identification/stripped_models/9d793671-2ead-42fa-b6ec-48f945671d68/cow-mistral3-small-q2_k.gguf b/tests/model_identification/stripped_models/9d793671-2ead-42fa-b6ec-48f945671d68/cow-mistral3-small-q2_k.ggufnew file mode 100644index 0000000000..b86b9ffcb0--- /dev/null+++ b/tests/model_identification/stripped_models/9d793671-2ead-42fa-b6ec-48f945671d68/cow-mistral3-small-q2_k.gguf@@ -0,0 +1,3 @@+version https://git-lfs.github.com/spec/v1+oid sha256:0bbffd7c9ac374719e20a5a109ee23e023aeaa615915cbb23c6dd98e66056479+size 180852diff --git a/tests/model_identification/stripped_models/a64b18d7-d3e6-446c-b6c3-ce521d1eaa0d/Mistral-Small-3.2-24B-Instruct-2506-Q4_K_M.gguf b/tests/model_identification/stripped_models/a64b18d7-d3e6-446c-b6c3-ce521d1eaa0d/Mistral-Small-3.2-24B-Instruct-2506-Q4_K_M.ggufnew file mode 100644index 0000000000..0ee3c52559--- /dev/null+++ b/tests/model_identification/stripped_models/a64b18d7-d3e6-446c-b6c3-ce521d1eaa0d/Mistral-Small-3.2-24B-Instruct-2506-Q4_K_M.gguf@@ -0,0 +1,3 @@+version https://git-lfs.github.com/spec/v1+oid sha256:003abd16fa20ac94c628943ccf53f6db6a30537cff1c4fff26a92c2d6964c13a+size 139411diff --git a/tests/model_identification/stripped_models/a64b18d7-d3e6-446c-b6c3-ce521d1eaa0d/__test_metadata__.json b/tests/model_identification/stripped_models/a64b18d7-d3e6-446c-b6c3-ce521d1eaa0d/__test_metadata__.jsonnew file mode 100644index 0000000000..d62fb7842c--- /dev/null+++ b/tests/model_identification/stripped_models/a64b18d7-d3e6-446c-b6c3-ce521d1eaa0d/__test_metadata__.json@@ -0,0 +1,3 @@+version https://git-lfs.github.com/spec/v1+oid sha256:19df4edbe53cbfe401b4b6dc2e2c5379f86bb1861fdc14aa112c0288663ba523+size 530