Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

fix(mm): stop the SDNQ guards from aborting folder-encoder identification (#9561)

Alexander Eichhorn527098394319
diff --git a/invokeai/backend/model_manager/configs/qwen3_encoder.py b/invokeai/backend/model_manager/configs/qwen3_encoder.py
index 1cd98729b8..c39035fc49 100644
--- a/invokeai/backend/model_manager/configs/qwen3_encoder.py
+++ b/invokeai/backend/model_manager/configs/qwen3_encoder.py
@@ -1,4 +1,6 @@
import json
+from collections.abc import Iterable
+from pathlib import Path
from typing import Any, Literal, Optional, Self
from pydantic import Field
@@ -14,6 +16,11 @@ from invokeai.backend.model_manager.configs.identification_utils import (
from invokeai.backend.model_manager.model_on_disk import ModelOnDisk
from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelFormat, ModelType, Qwen3VariantType
from invokeai.backend.quantization.gguf.ggml_tensor import GGMLTensor
+from invokeai.backend.quantization.sdnq.detection import (
+ folder_has_sdnq_marker,
+ safetensors_have_sdnq_keys,
+ safetensors_tensor_names,
+)
from invokeai.backend.quantization.sdnq.sdnq_tensor import SDNQTensor
@@ -55,12 +62,65 @@ def _has_sdnq_tensors(state_dict: dict[str | int, Any]) -> bool:
def _has_sdnq_keys(state_dict: dict[str | int, Any]) -> bool:
"""Check if state dict has SDNQ-style keys (weight + scale pairs)."""
keys = {k for k in state_dict.keys() if isinstance(k, str)}
- for key in keys:
- if key.endswith(".weight"):
- base = key[:-7]
- if f"{base}.scale" in keys:
- return True
- return False
+ return any(key.endswith(".weight") and f"{key[: -len('.weight')]}.scale" in keys for key in keys)
+
+
+_TEXT_ENCODER_SUBDIR = "text_encoder"
+
+
+def resolve_qwen3_encoder_dir(model_path: Path) -> Path:
+ """The directory a Qwen3 encoder's weights and quantization marker actually live in.
+
+ Two layouts ship in the wild: a ``text_encoder+tokenizer`` download, where the weights sit under
+ ``text_encoder/`` next to a sibling ``tokenizer/``, and a standalone ``text_encoder`` download
+ whose files sit at the root. Identification and the loaders must resolve that the same way, or
+ identification accepts a folder the loader then cannot open - so this is the one implementation,
+ and `Qwen3EncoderSDNQLoader` calls it too.
+ """
+ nested = model_path / _TEXT_ENCODER_SUBDIR
+ return nested if nested.is_dir() else model_path
+
+
+def _encoder_dirs(mod: ModelOnDisk) -> tuple[Path, ...]:
+ """The directories a Qwen3 encoder folder probe is allowed to look at.
+
+ Deliberately not `mod.weight_files()`: that is an `rglob` over the whole tree, so for a full SDNQ
+ pipeline bundle it finds the transformer's and VAE's shards and reports the *bundle* as an SDNQ
+ encoder. The loaders only ever open the root or `text_encoder/`, so identification must judge the
+ folder on exactly that set.
+ """
+ nested = mod.path / _TEXT_ENCODER_SUBDIR
+ return (mod.path, nested) if nested.is_dir() else (mod.path,)
+
+
+def _folder_tensor_names(mod: ModelOnDisk) -> set[str]:
+ """Tensor names declared by the safetensors of the encoder folder at `mod.path`.
+
+ Folder probes must not go through ``ModelOnDisk.load_state_dict()``. It refuses to pick a file
+ when a folder holds more than one weight file and raises ``ValueError`` — not a
+ ``NotAMatchError`` — which aborts that config's probe rather than declining the model, so a
+ sharded encoder ends up stored as ``unknown``. Every folder-layout Qwen3 encoder we ship is
+ sharded: the FLUX.2 Klein 4B/9B and Z-Image ``text_encoder`` downloads are 2-4 shards each.
+ """
+ names: set[str] = set()
+ for folder in _encoder_dirs(mod):
+ names |= safetensors_tensor_names(folder.glob("*.safetensors"))
+ return names
+
+
+def _folder_is_sdnq_quantized(mod: ModelOnDisk) -> bool:
+ """True if the Qwen3 encoder folder at `mod.path` holds SDNQ-quantized weights.
+
+ `Qwen3Encoder_Qwen3Encoder_Config` and `Qwen3Encoder_SDNQ_Folder_Config` must be mutually
+ exclusive: one rejects what the other requires. That only holds if both ask the *same* question,
+ so both call this. They used to ask different ones — the unquantized config looked for the marker
+ in `text_encoder/` as well and for keys across every shard, while the SDNQ config looked only at
+ the root and only at safetensors sitting directly in it. A markerless SDNQ encoder in the nested
+ `text_encoder/` layout was therefore rejected by *both* and stored as `unknown`.
+ """
+ if any(folder_has_sdnq_marker(folder) for folder in _encoder_dirs(mod)):
+ return True
+ return safetensors_have_sdnq_keys(f for folder in _encoder_dirs(mod) for f in folder.glob("*.safetensors"))
def _has_t5_encoder_keys(state_dict: dict[str | int, Any]) -> bool:
@@ -92,8 +152,8 @@ def _has_gemma2_keys(state_dict: dict[str | int, Any]) -> bool:
return False
-def _has_qwen_vl_visual_tower(state_dict: dict[str | int, Any]) -> bool:
- """Check if state dict bundles a Qwen-VL vision tower (Qwen2-VL / Qwen2.5-VL / Qwen3-VL).
+def _has_qwen_vl_visual_tower(tensor_names: Iterable[str | int]) -> bool:
+ """Check if the tensor names bundle a Qwen-VL vision tower (Qwen2-VL / Qwen2.5-VL / Qwen3-VL).
VL encoders ship a visual tower alongside the language model, whereas a text-only Qwen3 encoder
never does. A VL file otherwise satisfies the Qwen3 key heuristic (it has ``model.layers.*`` /
@@ -105,14 +165,17 @@ def _has_qwen_vl_visual_tower(state_dict: dict[str | int, Any]) -> bool:
layout that ComfyUI single-file Qwen3-VL checkpoints use. Matching only bare ``visual.blocks.*``
missed that layout, letting a single-file Qwen3-VL 4B encoder match both configs and get misrouted to
the text-only Qwen3 type - silently breaking the single-file/GGUF Krea-2 encoder install path.
+
+ Takes any iterable of names so a folder probe can pass the union of its safetensors headers; a
+ state dict iterates over its keys, so existing call sites are unaffected.
"""
- for key in state_dict.keys():
+ for key in tensor_names:
if isinstance(key, str) and (key.startswith(("visual.", "model.visual.")) or ".visual." in key):
return True
return False
-def _has_qwen3_specific_keys(state_dict: dict[str | int, Any]) -> bool:
+def _has_qwen3_specific_keys(tensor_names: Iterable[str | int]) -> bool:
"""Check for Qwen3-only QK-normalization weights (``q_norm``/``k_norm`` per attention block).
Qwen3 adds an RMSNorm on the query and key projections that Qwen2 does not have. A Qwen2
@@ -120,8 +183,11 @@ def _has_qwen3_specific_keys(state_dict: dict[str | int, Any]) -> bool:
/ ``model.embed_tokens.weight`` layout), so this is the discriminator that keeps a Qwen2 file
from being accepted as a Qwen3 encoder the loader would fail to build. Covers both the
PyTorch/diffusers naming and the llama.cpp/GGUF naming.
+
+ Takes any iterable of names, so a folder probe can pass safetensors header keys instead of a
+ state dict it cannot load.
"""
- for key in state_dict.keys():
+ for key in tensor_names:
if not isinstance(key, str):
continue
if ".self_attn.q_norm." in key or ".self_attn.k_norm." in key:
@@ -342,23 +408,10 @@ class Qwen3Encoder_Qwen3Encoder_Config(Config_Base):
@classmethod
def _reject_if_sdnq_quantized(cls, mod: ModelOnDisk) -> None:
- # Primary signal: quantization_config.json with quant_method="sdnq" (at root or in
- # text_encoder/). Fallback: SDNQ-style weight+scale key pairs in the state dict. This mirrors
- # the detection in Qwen3Encoder_SDNQ_Folder_Config so the two stay mutually exclusive.
- for folder in (mod.path, mod.path / "text_encoder"):
- quant_config_path = folder / "quantization_config.json"
- if not quant_config_path.exists():
- continue
- try:
- with open(quant_config_path, "r", encoding="utf-8") as f:
- quant_config = json.load(f)
- except (json.JSONDecodeError, OSError):
- continue
- if quant_config.get("quant_method") == "sdnq":
- raise NotAMatchError("folder is SDNQ-quantized; use Qwen3Encoder_SDNQ_Folder_Config")
-
- if _has_sdnq_keys(mod.load_state_dict()):
- raise NotAMatchError("state dict looks SDNQ-quantized; use Qwen3Encoder_SDNQ_Folder_Config")
+ # Shared with Qwen3Encoder_SDNQ_Folder_Config so the two configs cannot both reject (or both
+ # accept) the same folder.
+ if _folder_is_sdnq_quantized(mod):
+ raise NotAMatchError("folder is SDNQ-quantized; use Qwen3Encoder_SDNQ_Folder_Config")
@classmethod
def _get_variant_from_config(cls, config_path) -> Qwen3VariantType:
@@ -527,25 +580,16 @@ class Qwen3Encoder_SDNQ_Folder_Config(Config_Base):
raise_for_override_fields(cls, override_fields)
- matched = False
-
- # Check for quantization_config.json with quant_method="sdnq"
- quant_config_path = mod.path / "quantization_config.json"
- if quant_config_path.exists():
- with open(quant_config_path, "r", encoding="utf-8") as f:
- quant_config = json.load(f)
- if quant_config.get("quant_method") == "sdnq":
- matched = True
-
- # Fallback: check if safetensors files have SDNQ-style keys
- if not matched:
- safetensors_files = list(mod.path.glob("*.safetensors"))
- if safetensors_files:
- state_dict = mod.load_state_dict()
- if _has_sdnq_keys(state_dict):
- matched = True
-
- if not matched:
+ # Exclude full pipeline models, mirroring Qwen3Encoder_Qwen3Encoder_Config. An SDNQ bundle's
+ # transformer and VAE are SDNQ-quantized too, so without this the bundle root answers "yes"
+ # to the SDNQ question and registers as a Qwen3 encoder whenever the Main config declines it
+ # (an interrupted download, a corrupt model_index.json) - at a path this loader cannot open.
+ cls._reject_if_pipeline(mod)
+
+ # Shared with the rejection guard in Qwen3Encoder_Qwen3Encoder_Config: exactly one of the two
+ # configs claims a given folder. A corrupt or foreign quantization_config.json falls through
+ # to the key check there instead of aborting this probe with a JSONDecodeError.
+ if not _folder_is_sdnq_quantized(mod):
raise NotAMatchError("directory does not look like an SDNQ-quantized Qwen3 encoder")
# A root config.json next to tokenizer files is a complete causal LM (TextLLM), not a Qwen3
@@ -563,6 +607,25 @@ class Qwen3Encoder_SDNQ_Folder_Config(Config_Base):
variant = cls._get_variant_from_dir(mod)
return cls(variant=variant, **override_fields)
+ @staticmethod
+ def resolve_text_encoder_dir(model_path: Path) -> Path:
+ """The directory `Qwen3EncoderSDNQLoader` opens for this config's weights and marker.
+
+ Exposed on the config so the loader resolves the layout exactly as identification did, the
+ way `T5Encoder_SDNQ_Config` already does for its own two layouts.
+ """
+ return resolve_qwen3_encoder_dir(model_path)
+
+ @classmethod
+ def _reject_if_pipeline(cls, mod: ModelOnDisk) -> None:
+ # Same signals as Qwen3Encoder_Qwen3Encoder_Config: model_index.json at the root (diffusers
+ # pipeline) or a transformer subfolder. A standalone encoder download has neither.
+ if (mod.path / "model_index.json").exists() or (mod.path / "transformer").exists():
+ raise NotAMatchError(
+ "directory looks like a full diffusers pipeline (has model_index.json or transformer folder), "
+ "not a standalone Qwen3 encoder"
+ )
+
@classmethod
def _reject_if_complete_causal_lm(cls, mod: ModelOnDisk) -> None:
# Only applies to the root-config layout: an encoder subfolder (text_encoder/config.json) is
@@ -608,25 +671,22 @@ class Qwen3Encoder_SDNQ_Folder_Config(Config_Base):
"(only Qwen3ForCausalLM is supported)"
)
- # Fallback for folders without a usable config.json architecture: check the state dict. The
+ # Fallback for folders without a usable config.json architecture: check the tensor names. The
# generic Qwen keys (model.layers. / model.embed_tokens.weight) are NOT enough — Qwen2 and
# Qwen2-VL folders carry exactly the same ones, and the loader reconstructs a text-only
# Qwen3ForCausalLM that fails on Qwen2's missing q/k-norm params and on Qwen-VL's visual
# tower. Mirror the single-file path: reject a bundled visual tower and require the
# Qwen3-only q/k-norm weights. An SDNQ transformer/VAE folder has transformer_blocks. /
- # decoder. keys instead and is rejected by both checks. Loading the state dict can raise for
- # sharded folders (multiple weight files), so treat that as "no usable signal" rather than
- # letting it abort identification.
- try:
- state_dict = mod.load_state_dict()
- except Exception:
- state_dict = {}
+ # decoder. keys instead and is rejected by both checks. Names come from the safetensors
+ # headers because a sharded folder has no single state dict to load — that path used to
+ # yield no signal at all and reject every sharded markerless SDNQ encoder.
+ tensor_names = _folder_tensor_names(mod)
- if _has_qwen_vl_visual_tower(state_dict):
+ if _has_qwen_vl_visual_tower(tensor_names):
raise NotAMatchError(
"state dict bundles a Qwen-VL visual tower; this is a Qwen-VL encoder, not a text-only Qwen3 encoder"
)
- if _has_qwen3_specific_keys(state_dict):
+ if _has_qwen3_specific_keys(tensor_names):
return
raise NotAMatchError(
diff --git a/invokeai/backend/model_manager/load/model_loaders/z_image.py b/invokeai/backend/model_manager/load/model_loaders/z_image.py
index a01c854ccf..a6c47e8dad 100644
--- a/invokeai/backend/model_manager/load/model_loaders/z_image.py
+++ b/invokeai/backend/model_manager/load/model_loaders/z_image.py
@@ -1515,6 +1515,15 @@ class Qwen3EncoderSDNQLoader(ModelLoader):
)
model_path = Path(config.path)
+ # A folder encoder ships in one of two layouts: weights at the root, or under `text_encoder/`
+ # next to a sibling `tokenizer/`. `sdnq_sd_loader` globs one directory and reads the
+ # `quantization_config.json` beside it, so pointing it at the root of a nested install finds
+ # no shards ("No safetensors files found") and would fall back to a default `group_size`.
+ # Resolve the layout with the same helper identification used, so the loader can open every
+ # folder identification accepts. Single-file configs carry a file path and are left alone.
+ if isinstance(config, Qwen3Encoder_SDNQ_Folder_Config):
+ model_path = Qwen3Encoder_SDNQ_Folder_Config.resolve_text_encoder_dir(model_path)
+
# Determine safe dtype based on target device capabilities
target_device = TorchDevice.choose_torch_device()
compute_dtype = TorchDevice.choose_bfloat16_safe_dtype(target_device)
diff --git a/invokeai/backend/quantization/sdnq/detection.py b/invokeai/backend/quantization/sdnq/detection.py
index c18cba4634..eadc5b4deb 100644
--- a/invokeai/backend/quantization/sdnq/detection.py
+++ b/invokeai/backend/quantization/sdnq/detection.py
@@ -10,6 +10,7 @@ misreads them.
"""
import json
+from collections.abc import Iterable
from pathlib import Path
from safetensors import safe_open
@@ -17,11 +18,44 @@ from safetensors import safe_open
_QUANTIZATION_CONFIG_FILENAME = "quantization_config.json"
-def folder_has_sdnq_keys(folder_path: Path) -> bool:
- """True if the safetensors in `folder_path` carry an SDNQ ``<name>.weight`` / ``<name>.scale`` pair.
+def safetensors_tensor_names(files: Iterable[Path]) -> set[str]:
+ """Union of the tensor names declared by `files`, read from their headers.
+
+ Identification only ever needs the *names* — "is there a `<name>.scale` next to this
+ `<name>.weight`", "is there a visual tower" — never the tensor data, and the header carries them
+ per file. That is what makes this shard-safe, which `ModelOnDisk.load_state_dict()` is not: it
+ refuses to pick a file when a folder holds more than one weight file and raises `ValueError` —
+ not a `NotAMatchError` — so it aborts that config's probe instead of declining the model. Every
+ sharded encoder folder (the FLUX.2 Klein and Z-Image `text_encoder` downloads are all 2-4 shards)
+ hit that and fell back to `unknown`.
+
+ Non-safetensors entries are skipped: they are the set `sdnq_sd_loader` reads, and a file whose
+ header cannot be read contributes nothing rather than failing the whole check.
+ """
+ names: set[str] = set()
+ for file in sorted(files):
+ if file.suffix != ".safetensors":
+ continue
+ try:
+ with safe_open(file, framework="pt", device="cpu") as f:
+ names.update(f.keys())
+ except Exception:
+ continue
+ return names
+
+
+def safetensors_have_sdnq_keys(files: Iterable[Path]) -> bool:
+ """True if `files` carry an SDNQ ``<name>.weight`` / ``<name>.scale`` pair.
The pair is resolved across the union of every shard, never within a single file: sharding splits
a checkpoint by tensor order, so a weight and its scale routinely land in different files.
+ """
+ names = safetensors_tensor_names(files)
+ return any(name.endswith(".weight") and f"{name[: -len('.weight')]}.scale" in names for name in names)
+
+
+def folder_has_sdnq_keys(folder_path: Path) -> bool:
+ """True if the safetensors directly in `folder_path` carry an SDNQ weight/scale pair.
Only safetensors are inspected, which is the same set `sdnq_sd_loader` reads — a `.bin` holding
SDNQ-shaped tensors is not something we could load anyway, so calling it SDNQ would only move the
@@ -30,15 +64,23 @@ def folder_has_sdnq_keys(folder_path: Path) -> bool:
if not folder_path.is_dir():
return False
- keys: set[str] = set()
- for shard in sorted(folder_path.glob("*.safetensors")):
- try:
- with safe_open(shard, framework="pt", device="cpu") as f:
- keys.update(f.keys())
- except Exception:
- continue
+ return safetensors_have_sdnq_keys(folder_path.glob("*.safetensors"))
+
+
+def folder_has_sdnq_marker(folder_path: Path) -> bool:
+ """True if `folder_path` holds a `quantization_config.json` naming SDNQ as the quant method.
- return any(key.endswith(".weight") and f"{key[: -len('.weight')]}.scale" in keys for key in keys)
+ A marker that is missing, unreadable or names another method is not evidence *against* SDNQ
+ weights — callers fall through to the key shape rather than treating False as "not SDNQ".
+ """
+ marker = folder_path / _QUANTIZATION_CONFIG_FILENAME
+ if not marker.is_file():
+ return False
+ try:
+ with open(marker, "r", encoding="utf-8") as f:
+ return json.load(f).get("quant_method") == "sdnq"
+ except (json.JSONDecodeError, OSError):
+ return False
def is_sdnq_folder(folder_path: Path) -> bool:
@@ -48,15 +90,4 @@ def is_sdnq_folder(folder_path: Path) -> bool:
back to the key shape. The fallback is what covers exports that ship no marker — without it such
a folder reads as plain diffusers to identification and as SDNQ to nothing at all.
"""
- marker = folder_path / _QUANTIZATION_CONFIG_FILENAME
- if marker.is_file():
- try:
- with open(marker, "r", encoding="utf-8") as f:
- if json.load(f).get("quant_method") == "sdnq":
- return True
- except (json.JSONDecodeError, OSError):
- pass
- # A marker that exists but names another method is not evidence *against* SDNQ keys, so fall
- # through rather than returning False here.
-
- return folder_has_sdnq_keys(folder_path)
+ return folder_has_sdnq_marker(folder_path) or folder_has_sdnq_keys(folder_path)
diff --git a/tests/backend/model_manager/configs/test_qwen3_encoder_config.py b/tests/backend/model_manager/configs/test_qwen3_encoder_config.py
index 36f0cb404c..63be3953a0 100644
--- a/tests/backend/model_manager/configs/test_qwen3_encoder_config.py
+++ b/tests/backend/model_manager/configs/test_qwen3_encoder_config.py
@@ -15,15 +15,20 @@ from tempfile import TemporaryDirectory
from unittest.mock import MagicMock, patch
import pytest
+import torch
+from safetensors.torch import save_file
from invokeai.backend.model_manager.configs.identification_utils import NotAMatchError
from invokeai.backend.model_manager.configs.qwen3_encoder import (
Qwen3Encoder_Checkpoint_Config,
Qwen3Encoder_GGUF_Config,
Qwen3Encoder_Qwen3Encoder_Config,
+ Qwen3Encoder_SDNQ_Folder_Config,
_has_gemma2_keys,
_has_qwen_vl_visual_tower,
)
+from invokeai.backend.model_manager.model_on_disk import ModelOnDisk
+from invokeai.backend.quantization.sdnq.loaders import _parse_quantization_config, sdnq_sd_loader
_OVERRIDE_FIELDS: dict[str, object] = {
"hash": "blake3:fakehash",
@@ -145,3 +150,273 @@ def test_gguf_config_rejects_gemma_state_dict() -> None:
}
with pytest.raises(NotAMatchError, match="Gemma-2"):
Qwen3Encoder_GGUF_Config._validate_looks_like_qwen3_model(mod)
+
+
+class TestShardedQwen3EncoderFolder:
+ """A sharded text_encoder folder must still identify as a Qwen3 encoder.
+
+ The starter-model download
+ `black-forest-labs/FLUX.2-klein-{4B,9B}::text_encoder+tokenizer` lands the encoder as several
+ `model-0000N-of-0000M.safetensors` shards. The SDNQ rejection guard used to call
+ `mod.load_state_dict()`, which raises ValueError ("Multiple weight files found") rather than a
+ NotAMatchError when a folder holds more than one weight file. That aborted this config's probe,
+ so the model was stored as `unknown`.
+ """
+
+ @staticmethod
+ def _make_sharded_encoder(root: Path, *, sdnq: bool = False) -> Path:
+ text_encoder = root / "text_encoder"
+ text_encoder.mkdir(parents=True)
+ _write_config(text_encoder / "config.json", hidden_size=4096, architecture="Qwen3ForCausalLM")
+
+ shards: list[dict[str, torch.Tensor]] = [
+ {"model.embed_tokens.weight": torch.zeros(8, 4096, dtype=torch.uint8 if sdnq else torch.float32)},
+ {"model.layers.0.self_attn.q_proj.weight": torch.zeros(8, 8, dtype=torch.uint8 if sdnq else torch.float32)},
+ ]
+ if sdnq:
+ shards[1]["model.layers.0.self_attn.q_proj.scale"] = torch.zeros(8, 1, dtype=torch.float32)
+
+ for i, shard in enumerate(shards, start=1):
+ save_file(shard, str(text_encoder / f"model-0000{i}-of-00002.safetensors"))
+
+ # Tokenizer files live in their own subfolder for the `text_encoder+tokenizer` download layout.
+ tokenizer = root / "tokenizer"
+ tokenizer.mkdir()
+ (tokenizer / "tokenizer_config.json").write_text("{}")
+ return root
+
+ def test_sharded_encoder_matches(self, tmp_path: Path) -> None:
+ root = self._make_sharded_encoder(tmp_path / "klein-9b-encoder")
+ config = Qwen3Encoder_Qwen3Encoder_Config.from_model_on_disk(ModelOnDisk(root), dict(_OVERRIDE_FIELDS))
+
+ assert config.type.value == "qwen3_encoder"
+ assert config.variant.value == "qwen3_8b"
+
+ def test_sharded_sdnq_encoder_is_still_rejected(self, tmp_path: Path) -> None:
+ """The shard-safe check must keep detecting SDNQ weight+scale pairs across shards."""
+ root = self._make_sharded_encoder(tmp_path / "klein-9b-encoder-sdnq", sdnq=True)
+ with pytest.raises(NotAMatchError, match="SDNQ"):
+ Qwen3Encoder_Qwen3Encoder_Config.from_model_on_disk(ModelOnDisk(root), dict(_OVERRIDE_FIELDS))
+
+ def test_folder_probe_never_loads_a_state_dict(self, tmp_path: Path) -> None:
+ """Identifying a folder encoder must not go through `load_state_dict()` at all.
+
+ A folder holding more than one weight file has no single state dict to load: the call raises
+ ValueError, which is not a NotAMatchError, and the probe is abandoned. Everything this config
+ needs is in `config.json` and the safetensors headers, so make the absence of that call a
+ property of the test suite rather than of today's implementation.
+ """
+ root = self._make_sharded_encoder(tmp_path / "klein-9b-encoder-nosd")
+
+ def _explode(*args: object, **kwargs: object) -> None:
+ raise AssertionError("identification must not load the state dict of a folder model")
+
+ with patch.object(ModelOnDisk, "load_state_dict", _explode):
+ config = Qwen3Encoder_Qwen3Encoder_Config.from_model_on_disk(ModelOnDisk(root), dict(_OVERRIDE_FIELDS))
+
+ assert config.variant.value == "qwen3_8b"
+
+
+class TestSdnqQwen3EncoderFolder:
+ """`Qwen3Encoder_Qwen3Encoder_Config` and `Qwen3Encoder_SDNQ_Folder_Config` must partition folders.
+
+ The two used to ask different questions about the same directory: the unquantized config looked
+ for the SDNQ marker in `text_encoder/` as well and for SDNQ keys across every shard, while the
+ SDNQ config looked only at the root and only at safetensors sitting directly in it. An SDNQ
+ encoder in the nested `text_encoder/` layout was therefore rejected by *both* - the exact shape
+ that lands a model in `unknown`.
+ """
+
+ @staticmethod
+ def _make_sdnq_encoder(root: Path, *, marker_in: str | None = None, architecture: str | None = None) -> Path:
+ text_encoder = root / "text_encoder"
+ text_encoder.mkdir(parents=True)
+
+ config: dict[str, object] = {"hidden_size": 4096}
+ if architecture is not None:
+ config["architectures"] = [architecture]
+ (text_encoder / "config.json").write_text(json.dumps(config))
+
+ # q_norm/k_norm are the Qwen3-only marker the config falls back to when config.json declares
+ # no architecture; they are split across shards on purpose.
+ save_file(
+ {"model.embed_tokens.weight": torch.zeros(8, 4096, dtype=torch.uint8)},
+ str(text_encoder / "model-00001-of-00002.safetensors"),
+ )
+ save_file(
+ {
+ "model.layers.0.self_attn.q_norm.weight": torch.zeros(8, 8, dtype=torch.uint8),
+ "model.layers.0.self_attn.q_norm.scale": torch.zeros(8, 1, dtype=torch.float32),
+ },
+ str(text_encoder / "model-00002-of-00002.safetensors"),
+ )
+
+ if marker_in is not None:
+ (root / marker_in / "quantization_config.json").write_text(json.dumps({"quant_method": "sdnq"}))
+ return root
+
+ def test_nested_markerless_sdnq_encoder_is_claimed(self, tmp_path: Path) -> None:
+ """Detected by key shape across the shards of `text_encoder/`, with no marker file at all."""
+ root = self._make_sdnq_encoder(tmp_path / "sdnq-nested", architecture="Qwen3ForCausalLM")
+
+ config = Qwen3Encoder_SDNQ_Folder_Config.from_model_on_disk(ModelOnDisk(root), dict(_OVERRIDE_FIELDS))
+
+ assert config.format.value == "sdnq_quantized"
+ assert config.variant.value == "qwen3_8b"
+ # ...and the unquantized config declines the same folder, so exactly one of them matches.
+ with pytest.raises(NotAMatchError, match="SDNQ"):
+ Qwen3Encoder_Qwen3Encoder_Config.from_model_on_disk(ModelOnDisk(root), dict(_OVERRIDE_FIELDS))
+
+ def test_marker_in_text_encoder_subfolder_is_honored(self, tmp_path: Path) -> None:
+ root = self._make_sdnq_encoder(
+ tmp_path / "sdnq-marker-nested", marker_in="text_encoder", architecture="Qwen3ForCausalLM"
+ )
+
+ config = Qwen3Encoder_SDNQ_Folder_Config.from_model_on_disk(ModelOnDisk(root), dict(_OVERRIDE_FIELDS))
+ assert config.format.value == "sdnq_quantized"
+
+ def test_unreadable_marker_falls_through_to_the_key_check(self, tmp_path: Path) -> None:
+ """A corrupt `quantization_config.json` used to abort this probe with a JSONDecodeError."""
+ root = self._make_sdnq_encoder(tmp_path / "sdnq-bad-marker", architecture="Qwen3ForCausalLM")
+ (root / "quantization_config.json").write_text("{not json")
+
+ config = Qwen3Encoder_SDNQ_Folder_Config.from_model_on_disk(ModelOnDisk(root), dict(_OVERRIDE_FIELDS))
+ assert config.format.value == "sdnq_quantized"
+
+ def test_sharded_folder_without_declared_architecture_is_claimed(self, tmp_path: Path) -> None:
+ """The Qwen3-only q_norm/k_norm fallback must read shard headers, not a single state dict.
+
+ With no `architectures` in config.json the config falls back to tensor names. Reading them
+ via `load_state_dict()` yielded nothing for a sharded folder, so this shape was rejected.
+ """
+ root = self._make_sdnq_encoder(tmp_path / "sdnq-no-arch")
+
+ config = Qwen3Encoder_SDNQ_Folder_Config.from_model_on_disk(ModelOnDisk(root), dict(_OVERRIDE_FIELDS))
+ assert config.format.value == "sdnq_quantized"
+
+
+class TestSdnqEncoderIdentificationMatchesTheLoader:
+ """Identification must not accept a folder `Qwen3EncoderSDNQLoader` cannot open.
+
+ Claiming the nested `text_encoder/` layout without teaching the loader about it would turn
+ "unknown at install" into "installed, then ValueError at generation time" - the worse of the two,
+ and the very failure `Main_SDNQ_Diffusers_ZImage_Config._validate_has_sdnq_transformer` exists to
+ prevent. `sdnq_sd_loader` globs one directory and reads the `quantization_config.json` beside it,
+ so the loader has to resolve the layout the same way the config did.
+ """
+
+ @staticmethod
+ def _make_nested_bundle(root: Path, *, group_size: int = 64) -> Path:
+ text_encoder = root / "text_encoder"
+ text_encoder.mkdir(parents=True)
+ (text_encoder / "config.json").write_text(
+ json.dumps({"architectures": ["Qwen3ForCausalLM"], "hidden_size": 2560})
+ )
+ (text_encoder / "quantization_config.json").write_text(
+ json.dumps({"quant_method": "sdnq", "group_size": group_size})
+ )
+ save_file(
+ {
+ "model.embed_tokens.weight": torch.randint(-128, 127, (64, 64), dtype=torch.int8),
+ "model.embed_tokens.scale": torch.tensor([0.01], dtype=torch.float32),
+ },
+ str(text_encoder / "model-00001-of-00002.safetensors"),
+ )
+ save_file(
+ {
+ "model.layers.0.self_attn.q_norm.weight": torch.randint(-128, 127, (64, 64), dtype=torch.int8),
+ "model.layers.0.self_attn.q_norm.scale": torch.tensor([0.02], dtype=torch.float32),
+ },
+ str(text_encoder / "model-00002-of-00002.safetensors"),
+ )
+ (root / "tokenizer").mkdir()
+ (root / "tokenizer" / "tokenizer_config.json").write_text("{}")
+ return root
+
+ def test_the_loader_can_open_what_identification_accepted(self, tmp_path: Path) -> None:
+ root = self._make_nested_bundle(tmp_path / "sdnq-nested-loadable")
+
+ config = Qwen3Encoder_SDNQ_Folder_Config.from_model_on_disk(ModelOnDisk(root), dict(_OVERRIDE_FIELDS))
+ assert config.format.value == "sdnq_quantized"
+
+ # The bug: handing the loader the registered path finds no weights at all.
+ with pytest.raises(ValueError, match="No safetensors files found"):
+ sdnq_sd_loader(root, compute_dtype=torch.float32)
+
+ # The fix: the same resolution identification used points at the shards *and* at the marker
+ # next to them, so a real group_size is honoured instead of silently defaulting.
+ resolved = Qwen3Encoder_SDNQ_Folder_Config.resolve_text_encoder_dir(root)
+ assert resolved == root / "text_encoder"
+ assert _parse_quantization_config(resolved / "quantization_config.json").get("group_size") == 64
+
+ sd = sdnq_sd_loader(resolved, compute_dtype=torch.float32)
+ assert "model.embed_tokens.weight" in sd
+ assert "model.layers.0.self_attn.q_norm.weight" in sd
+
+ def test_standalone_layout_still_resolves_to_the_root(self, tmp_path: Path) -> None:
+ root = tmp_path / "sdnq-standalone"
+ root.mkdir()
+ assert Qwen3Encoder_SDNQ_Folder_Config.resolve_text_encoder_dir(root) == root
+
+
+class TestSdnqPipelineBundleIsNotAQwen3Encoder:
+ """A full SDNQ pipeline bundle must not also match `Qwen3Encoder_SDNQ_Folder_Config`.
+
+ Its transformer and VAE are SDNQ-quantized too, so a recursive key scan answers "yes" at the
+ bundle root. While `Main_SDNQ_Diffusers_*` matches, the factory's type sort hides that; when it
+ declines - an interrupted download, a corrupt `model_index.json` - the whole bundle registers as
+ a Qwen3 encoder at a path the SDNQ encoder loader cannot open.
+ """
+
+ @staticmethod
+ def _make_bundle(root: Path, *, model_index: str | None = None, transformer_shards: bool = True) -> Path:
+ transformer = root / "transformer"
+ transformer.mkdir(parents=True)
+ (transformer / "config.json").write_text(json.dumps({"_class_name": "ZImageTransformer2DModel"}))
+ (transformer / "quantization_config.json").write_text(json.dumps({"quant_method": "sdnq"}))
+ if transformer_shards:
+ save_file(
+ {
+ "transformer_blocks.0.attn.to_q.weight": torch.randint(-128, 127, (64, 64), dtype=torch.int8),
+ "transformer_blocks.0.attn.to_q.scale": torch.tensor([0.01], dtype=torch.float32),
+ },
+ str(transformer / "diffusion_pytorch_model.safetensors"),
+ )
+ if model_index is not None:
+ (root / "model_index.json").write_text(model_index)
+ return root
+
+ def test_complete_bundle_is_rejected(self, tmp_path: Path) -> None:
+ root = self._make_bundle(tmp_path / "bundle", model_index=json.dumps({"_class_name": "ZImagePipeline"}))
+ with pytest.raises(NotAMatchError, match="full diffusers pipeline"):
+ Qwen3Encoder_SDNQ_Folder_Config.from_model_on_disk(ModelOnDisk(root), dict(_OVERRIDE_FIELDS))
+
+ def test_interrupted_download_is_rejected(self, tmp_path: Path) -> None:
+ """Transformer marker and config present, shards not downloaded yet: still not an encoder."""
+ root = self._make_bundle(tmp_path / "bundle-partial", transformer_shards=False)
+ with pytest.raises(NotAMatchError, match="full diffusers pipeline"):
+ Qwen3Encoder_SDNQ_Folder_Config.from_model_on_disk(ModelOnDisk(root), dict(_OVERRIDE_FIELDS))
+
+ def test_corrupt_model_index_is_rejected(self, tmp_path: Path) -> None:
+ root = self._make_bundle(tmp_path / "bundle-corrupt", model_index="{not json")
+ with pytest.raises(NotAMatchError, match="full diffusers pipeline"):
+ Qwen3Encoder_SDNQ_Folder_Config.from_model_on_disk(ModelOnDisk(root), dict(_OVERRIDE_FIELDS))
+
+ def test_sdnq_keys_outside_the_encoder_dirs_do_not_count(self, tmp_path: Path) -> None:
+ """The scan is scoped to the directories the loaders read, not an rglob over the tree.
+
+ No `transformer/` and no `model_index.json` here, so the pipeline guard does not fire - only
+ the scope keeps a folder whose sole SDNQ weights live in `vae/` from reading as an encoder.
+ """
+ root = tmp_path / "vae-only"
+ vae = root / "vae"
+ vae.mkdir(parents=True)
+ save_file(
+ {
+ "decoder.conv_in.weight": torch.randint(-128, 127, (64, 64), dtype=torch.int8),
+ "decoder.conv_in.scale": torch.tensor([0.01], dtype=torch.float32),
+ },
+ str(vae / "diffusion_pytorch_model.safetensors"),
+ )
+ with pytest.raises(NotAMatchError, match="does not look like an SDNQ-quantized Qwen3 encoder"):
+ Qwen3Encoder_SDNQ_Folder_Config.from_model_on_disk(ModelOnDisk(root), dict(_OVERRIDE_FIELDS))