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
"""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)
@pytest.fixture(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
@pytest.fixture
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
@pytest.mark.usefixtures("_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
@pytest.mark.usefixtures("_shrink_mistral_small_3")
@pytest.mark.parametrize(
("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, {})
@pytest.mark.parametrize("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
@pytest.mark.parametrize("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 None