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.

feat(model-manager): load nvfp4 Qwen3-VL text encoders (Krea-2, Ideogram 4) (#9804)

Alexander Eichhorn54c88a2d23ff
diff --git a/docs/src/content/docs/Users Guide/03.Models/02.model-families.mdx b/docs/src/content/docs/Users Guide/03.Models/02.model-families.mdx
index a99c137869..350891993a 100644
--- a/docs/src/content/docs/Users Guide/03.Models/02.model-families.mdx
+++ b/docs/src/content/docs/Users Guide/03.Models/02.model-families.mdx
@@ -49,7 +49,7 @@ InvokeAI recognizes the format from the file's contents, so you install them lik
- **SDNQ**: see [SDNQ Quantization](/configuration/optimization/sdnq-quantization/).
- **int8** (`int8_convrot`, from ComfyUI repackages): the weights stay int8 in memory on every device, including Apple Silicon, and need no setting to turn on. Supported for FLUX.1, FLUX.2 Klein, Z-Image, Anima, Krea-2, Qwen-Image-2.1, Ideogram 4, MiniMax H3, LTX-2 and the PiD decoders, and for the Qwen3 4B and 8B, Qwen3-VL and LTX-2 Gemma encoders.
- **int4** (`convrot_w4a4` or `int4_tensorwise`, ComfyUI repackages that usually keep some layers int8): the weights stay packed in memory at half a byte each and are unpacked per layer, on every device. This saves memory, not time: InvokeAI unpacks the weights for every step rather than running 4-bit matrix kernels, and 4-bit weights keep less detail than int8. Supported for the Krea-2 transformer.
-- **nvfp4** (4-bit, in ComfyUI's checkpoint format, such as Comfy-Org's builds; other nvfp4 exports such as AWQ are refused): the weights stay packed in memory and are unpacked per layer, so no special GPU is needed. Supported for the Z-Image, Krea-2, Qwen-Image and LTX-2 transformers and for the Qwen3, Qwen2.5-VL and FLUX.2 Mistral encoders; the Ideogram 4 and Qwen-Image-2.1 nvfp4 files are refused at install.
+- **nvfp4** (4-bit, in ComfyUI's checkpoint format, such as Comfy-Org's builds; other nvfp4 exports such as AWQ are refused): the weights stay packed in memory and are unpacked per layer, so no special GPU is needed. Supported for the Z-Image, Krea-2, Qwen-Image and LTX-2 transformers and for the Qwen3, Qwen3-VL 4B/8B, Qwen2.5-VL and FLUX.2 Mistral encoders; the Ideogram 4 and Qwen-Image-2.1 nvfp4 transformer files are refused at install.
- **fp8** (plain or `fp8_scaled`): InvokeAI keeps the weights in fp8 when [FP8 Storage](/configuration/optimization/fp8-storage/) is on, which installation does for you, or when `fp8_compute` is enabled.
- **MXFP8** (fp8 with one scale per block of 32 weights): loaded by unpacking to BF16. Turn FP8 Storage off for these; see the [FP8 Storage caution](/configuration/optimization/fp8-storage/).
diff --git a/docs/src/content/docs/Users Guide/03.Models/03.model-format-support.mdx b/docs/src/content/docs/Users Guide/03.Models/03.model-format-support.mdx
index 20a618ae1f..b9cdfe898d 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
@@ -67,7 +67,7 @@ Others are recognized by their layer names and fail, or misbehave, only when the
| T5-XXL | FLUX.1, SD 3 | ✓ | ✗ | ✗ | ✗ | ✗ | ✓ | ✓ (and bitsandbytes int8) |
| CLIP-L / CLIP-G | SD, SDXL, FLUX.1, SD 3 | ✓ | ✓ | R | R | – | ✗ | CLIP-L inside a FLUX.1 SDNQ pipeline |
| Qwen3 0.6B / 4B / 8B | Z-Image (4B), FLUX.2 Klein (4B, 8B), Anima (0.6B) | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
-| Qwen3-VL 4B / 8B | Krea-2, FLUX.3, Ideogram 4, Qwen-Image-2.1 (8B) | ✓ | ✓ | ✓ | ✓ | ✗ | ✓ | ✗ |
+| Qwen3-VL 4B / 8B | Krea-2, FLUX.3, Ideogram 4, Qwen-Image-2.1 (8B) | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✗ |
| Qwen3-VL 32B (truncated) | MiniMax H3 | in the Diffusers folder | ✓ | L | ✓ | L | ✗ | ✗ |
| Qwen3.5 4B | Anima 3.8B | ✗ | ✓ | L | L | L | ✗ | ✗ |
| Qwen3.5 9B | MOSS-Image | in the Diffusers folder | ✓ | L | L | L | ✗ | ✗ |
@@ -83,12 +83,18 @@ CLIP encoders from the main model only, so a separate CLIP file does not change
`text_projection` for SD 3 and is refused without it, as are extended-context CLIP-L variants such as Long-CLIP.
FLUX.1 takes CLIP-L only.
-The Qwen3-VL GGUF encoder is the language model only; a separate `mmproj` vision file is refused, and split
-multi-part GGUFs have to be joined before installing. The Gemma-4 encoder installs as a folder (its `config.json`
-and tokenizer files next to exactly one weight file, bf16 or int8) or as a GGUF conversion of the LTX-2.5 encoder
-that packs its tokenizer and config in, such as elix3r's or Rootport's. Google's stock Gemma-4-12B GGUF fails to
-install with a message, since LTX-2 needs the Lightricks-tuned weights; its `mmproj` file is not recognized. A
-standalone `.safetensors` file is not recognized.
+The Qwen3-VL GGUF encoder is the language model only; a separate `mmproj` vision file is refused, and split multi-part
+GGUFs have to be joined before installing. Qwen3-VL nvfp4 single files keep their layers packed: ComfyUI's
+`qwen3vl_8b_nvfp4`, and repacks that name their nvfp4 layers the same way, in `.comfy_quant` markers or the
+`_quantization_metadata` header. A repack that packs its vision tower the same way keeps it packed when Krea-2 edit
+loads it for reference images. A single file with nvfp4 layers named neither way, with AWQ layers, or with packed
+weights missing nvfp4's per-tensor `weight_scale_2` fails to install with a message; if only its vision tower has such
+layers, it installs and fails with a message when Krea-2 edit loads the tower for reference images. Quantized encoder
+folders (AWQ, ModelOpt, llm-compressor) are not covered by this. The Gemma-4 encoder installs as a folder (its
+`config.json` and tokenizer files next to exactly one weight file, bf16 or int8) or as a GGUF conversion of the
+LTX-2.5 encoder that packs its tokenizer and config in, such as elix3r's or Rootport's. Google's stock Gemma-4-12B
+GGUF fails to install with a message, since LTX-2 needs the Lightricks-tuned weights; its `mmproj` file is not
+recognized. A standalone `.safetensors` file is not recognized.
The Qwen3.5 4B and 9B install as the same encoder type but are not interchangeable: Anima-3.8B takes only
the 4B and MOSS-Image only the 9B, and each refuses the other. A 9B file must hold the whole language model:
diff --git a/docs/src/content/docs/Users Guide/03.Models/Local Models/ideogram4.mdx b/docs/src/content/docs/Users Guide/03.Models/Local Models/ideogram4.mdx
index 88e751fe59..27b2c1da4a 100644
--- a/docs/src/content/docs/Users Guide/03.Models/Local Models/ideogram4.mdx
+++ b/docs/src/content/docs/Users Guide/03.Models/Local Models/ideogram4.mdx
@@ -33,7 +33,7 @@ Comfy-Org's [`Comfy-Org/Ideogram-4`](https://huggingface.co/Comfy-Org/Ideogram-4
- `text_encoders/qwen3vl_8b_fp8_scaled.safetensors` — the Qwen3-VL **8B** encoder (not the 4B one Krea-2 uses). A llama.cpp GGUF of the 8B encoder works as well; see [Qwen3-VL GGUF encoders](/users-guide/models/local-models/krea-2/#qwen3-vl-gguf-encoders).
- `vae/flux2-vae.safetensors` — the 32-channel VAE, shared with FLUX.2, which is why it installs under the FLUX.2 base
-Pick the unconditional branch, the encoder and the VAE in the **Components** section next to the model — and pick the unconditional branch of the *same* build as the model. The `nvfp4` repackage in that repo is **not** supported yet and is refused at install.
+Pick the unconditional branch, the encoder and the VAE in the **Components** section next to the model — and pick the unconditional branch of the *same* build as the model. The `nvfp4` transformers in that repo are **not** supported yet and are refused at install; its nvfp4 encoder, `text_encoders/qwen3vl_8b_nvfp4.safetensors`, loads and keeps its layers packed.
Which branch a file holds is read from the file itself, and from the filename for a build that does not record it, so keep these names as published.
diff --git a/docs/src/content/docs/Users Guide/03.Models/Local Models/krea-2.mdx b/docs/src/content/docs/Users Guide/03.Models/Local Models/krea-2.mdx
index a6551dbcb9..5126d65060 100644
--- a/docs/src/content/docs/Users Guide/03.Models/Local Models/krea-2.mdx
+++ b/docs/src/content/docs/Users Guide/03.Models/Local Models/krea-2.mdx
@@ -81,7 +81,8 @@ the bundled components.
:::note[Qwen3-VL encoder]
Single-file Qwen3-VL encoders bundle only the weights. Their tokenizer and architecture config ship
with InvokeAI, so these encoders load without network access. A single-file fp8 encoder is kept
-resident in fp8 (roughly half the VRAM of the bf16 encoder).
+resident in fp8 (roughly half the VRAM of the bf16 encoder), and an nvfp4 encoder keeps its layers packed
+at 4 bits.
:::
### Qwen3-VL GGUF encoders
diff --git a/invokeai/backend/model_manager/configs/qwen3_vl_encoder.py b/invokeai/backend/model_manager/configs/qwen3_vl_encoder.py
index 886ca3d219..5fc42c9762 100644
--- a/invokeai/backend/model_manager/configs/qwen3_vl_encoder.py
+++ b/invokeai/backend/model_manager/configs/qwen3_vl_encoder.py
@@ -16,6 +16,10 @@ from invokeai.backend.model_manager.configs.identification_utils import (
from invokeai.backend.model_manager.configs.qwen3_5_encoder import has_qwen3_5_linear_attention
from invokeai.backend.model_manager.model_on_disk import ModelOnDisk
from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelFormat, ModelType, Qwen3VLVariantType
+from invokeai.backend.model_manager.util.qwen3_vl import drop_qwen3vl_unloaded_keys
+from invokeai.backend.quantization.fp8_scaled import COMFY_QUANT_SUFFIX, parse_quantization_metadata
+from invokeai.backend.quantization.int8_convrot import read_comfy_quant_markers
+from invokeai.backend.quantization.nvfp4 import find_nvfp4_layers
# The two Qwen3-VL encoders v7 can build, by language-model width. Both have 36 layers, so the
# width alone identifies the variant. Anything else -- including MiniMax H3's truncated
@@ -95,6 +99,27 @@ def _variant_from_checkpoint_shape(state_dict: dict[str | int, Any]) -> Qwen3VLV
return variant
+def _raise_for_undecodable_nvfp4_layers(mod: ModelOnDisk, state_dict: dict[str | int, Any]) -> None:
+ """Refuse at install time an nvfp4 layer the loader would refuse at the first generation.
+
+ The loader's own check, over the tensors the loader reads -- so a visual tower or LM head it drops cannot
+ get a file refused. It turns away AWQ builds, packed weights without nvfp4's per-tensor global scale,
+ malformed layers, and layers neither a ComfyUI ``.comfy_quant`` marker nor the safetensors header names as
+ nvfp4 (ModelOpt-style exports among them). Identification holds meta tensors, whose markers have no bytes to
+ parse, so those are read from the file -- whenever a kept key is a marker, which is when the check consults
+ them -- and passed beside the header rather than over it: as at load, either one naming a layer nvfp4 is
+ enough.
+ """
+ consumed = drop_qwen3vl_unloaded_keys(state_dict)
+ markers = None
+ if any(isinstance(key, str) and key.endswith(COMFY_QUANT_SUFFIX) for key in consumed):
+ markers = read_comfy_quant_markers(mod.path)
+ try:
+ find_nvfp4_layers(consumed, header_layers=parse_quantization_metadata(mod.metadata()), markers=markers)
+ except ValueError as e:
+ raise InvalidMatchError(f"this Qwen3-VL encoder cannot be loaded: {e}") from e
+
+
class Qwen3VLEncoder_Qwen3VLEncoder_Config(Config_Base):
"""Configuration for standalone Qwen3-VL text encoder models (diffusers-like directory format).
@@ -215,6 +240,9 @@ class Qwen3VLEncoder_Checkpoint_Config(Checkpoint_Config_Base, Config_Base):
state_dict = mod.load_state_dict()
if not _is_qwen3_vl_encoder_state_dict(state_dict):
raise NotAMatchError("state dict does not look like a single-file Qwen3-VL encoder")
+ # Ahead of the variant, whose width is read off the embedding: an undecodable repack that packs the
+ # embedding too would fail there instead, and register as an unknown model with the reason only in the log.
+ _raise_for_undecodable_nvfp4_layers(mod, state_dict)
variant = override_fields.pop("variant", None) or _variant_from_checkpoint_shape(state_dict)
return cls(**override_fields, variant=variant)
diff --git a/invokeai/backend/model_manager/load/model_loaders/krea2.py b/invokeai/backend/model_manager/load/model_loaders/krea2.py
index bd111f1032..aa47fa3d3f 100644
--- a/invokeai/backend/model_manager/load/model_loaders/krea2.py
+++ b/invokeai/backend/model_manager/load/model_loaders/krea2.py
@@ -39,8 +39,8 @@ from invokeai.backend.model_manager.taxonomy import (
)
from invokeai.backend.model_manager.util.llamacpp_keys import convert_llamacpp_decoder_keys
from invokeai.backend.model_manager.util.qwen3_vl import (
+ drop_qwen3vl_unloaded_keys,
drop_qwen3vl_visual_tower,
- drop_qwen3vl_visual_tower_keys,
normalize_qwen3vl_rope_config,
qwen3vl_target_key,
qwen3vl_visual_tower_files,
@@ -51,6 +51,7 @@ from invokeai.backend.quantization.fp8_scaled import (
INPUT_SCALE_SUFFIXES,
attach_fp8_scales,
cast_state_dict,
+ count_fp8_weights,
dequantize_fp8_scaled,
detach_layer_sidechannel,
extract_comfy_quant_hints,
@@ -304,6 +305,21 @@ def _qwen3vl_tower_key(key: str) -> str:
return qwen3vl_target_key(key)[len("visual.") :]
+def _remap_qwen3vl_tower_keys(entries: dict[str, Any], *, key_map: dict[str, str] | None = None) -> dict[str, Any]:
+ """Re-key tower tensors, or nvfp4 payloads by layer path, relative to the tower, refusing collisions.
+
+ `key_map` records old key -> new key when given, for `resolve_quantized_module_paths`.
+ """
+ out: dict[str, Any] = {}
+ source_of: dict[Any, Any] = {}
+ for key, value in entries.items():
+ new_key = _qwen3vl_tower_key(key)
+ _put_unique_key(out, new_key, value, source=key, source_of=source_of, what="Qwen3-VL vision tower")
+ if key_map is not None:
+ key_map[key] = new_key
+ return out
+
+
def _load_qwen3vl_visual_tower(
files: list[Path],
vision_config: Any,
@@ -316,10 +332,11 @@ def _load_qwen3vl_visual_tower(
Serves `SubModelType.VisionEncoder`: the encoders here drop their tower (see `drop_qwen3vl_visual_tower`),
and Krea-2's edit mode loads it as its own cache entry, only when a prompt has reference images.
- The tower ends up at the compute dtype whatever the container. Every single file seen so far stores it in
- BF16, the fp8_scaled ones included; a ComfyUI ``int8_tensorwise`` repack quantizes its Linears too, and
- those stay int8 as `Int8ConvrotLinear`, as on the encoder path. A scaled-fp8 tower would be folded to the
- compute dtype: at ~0.8 GiB it does not earn an fp8 matmul path of its own.
+ The tower ends up at the compute dtype whatever the container, except for its quantized Linears, which are
+ handled as on the encoder path: a ComfyUI ``int8_tensorwise`` repack's stay int8 as `Int8ConvrotLinear`, and
+ Comfy ``nvfp4`` layers stay packed as `NVFP4Linear`. The single files seen so far, fp8_scaled and both nvfp4
+ builds, store the tower in BF16, so the nvfp4 path is for repacks that pack the tower too. A scaled-fp8 tower
+ would be folded to the compute dtype: at ~0.8 GiB it does not earn an fp8 matmul path of its own.
"""
from transformers.models.qwen3_vl.modeling_qwen3_vl import Qwen3VLVisionModel
@@ -331,20 +348,27 @@ def _load_qwen3vl_visual_tower(
"cannot read Krea-2 edit reference images. Use the Krea-2 Diffusers model's own encoder, or a Qwen3-VL "
"single file or folder that includes the vision weights (e.g. qwen3vl_4b_bf16 or qwen3vl_4b_fp8_scaled)."
)
+ # The nvfp4 layers leave first, as on the encoder path: the sidecar drop below strips the markers that name
+ # them, and the fp8 extraction discards their block scales. Each header names its layers in the key space `sd`
+ # is still in. Identification ignores the tower, so this is where an undecodable tower layer is refused.
+ header_layers: dict[str, Any] = {}
+ for path in files:
+ header_layers.update(parse_quantization_metadata(read_safetensors_metadata(path)))
+ try:
+ nvfp4_payloads = pop_nvfp4_layers(sd, header_layers=header_layers)
+ except ValueError as e:
+ raise ValueError(f"The {what}, which Krea-2 edit needs for reference images, cannot be loaded: {e}") from e
# Markers are read in the checkpoint's key space, before the rename, as on the encoder path.
int8_markers = extract_int8_convrot_markers(sd)
reject_unmarked_int8_weights(sd, int8_markers, what)
sd = drop_unconsumed_quantization_sidecars(sd)
key_map: dict[str, str] = {}
- renamed: dict[str, Any] = {}
- source_of: dict[Any, Any] = {}
- for key, value in sd.items():
- key_map[key] = _qwen3vl_tower_key(key)
- _put_unique_key(renamed, key_map[key], value, source=key, source_of=source_of, what=what)
- sd = renamed
+ sd = _remap_qwen3vl_tower_keys(sd, key_map=key_map)
+ nvfp4_payloads = _remap_qwen3vl_tower_keys(nvfp4_payloads)
with accelerate.init_empty_weights():
tower = Qwen3VLVisionModel._from_config(vision_config)
+ skip_patterns = _model_declared_skip_patterns(tower)
if int8_markers:
install_int8_convrot_layers(
@@ -354,15 +378,27 @@ def _load_qwen3vl_visual_tower(
dtype,
architecture=what,
reserve=reserve,
- skip_patterns=_model_declared_skip_patterns(tower),
+ skip_patterns=skip_patterns,
+ # The branch's only reservation, and the nvfp4 layers are no longer in `sd`.
+ extra_reserved_bytes=predict_nvfp4_install_size(tower, nvfp4_payloads, dtype, skip_patterns),
)
else:
# Whole keys were renamed, so each `.weight_scale` still sits beside its `.weight`.
fp8_layers = extract_fp8_scaled_layers(sd)
- reserve_for_load(reserve, sd, dtype, keep_fp8=False, model=tower, fp8_layers=fp8_layers, nvfp4_payloads={})
+ reserve_for_load(
+ reserve,
+ sd,
+ dtype,
+ keep_fp8=False,
+ model=tower,
+ fp8_layers=fp8_layers,
+ nvfp4_payloads=nvfp4_payloads,
+ skip_patterns=skip_patterns,
+ )
dequantize_fp8_scaled(sd, fp8_layers, dtype)
cast_state_dict(sd, dtype, keep_fp8=False, model=tower)
+ install_nvfp4_layers(tower, sd, nvfp4_payloads, dtype, skip_patterns)
load_state_dict_ignoring_extras(tower, sd, source=what, assign=True, allow_missing=True)
_reject_incomplete_load(tower, what=what)
return tower
@@ -1023,9 +1059,10 @@ class _Qwen3VLEncoderSingleFileLoader(ModelLoader, Generic[_Qwen3VLSingleFileCon
class Qwen3VLEncoderCheckpointLoader(_Qwen3VLEncoderSingleFileLoader[Qwen3VLEncoder_Checkpoint_Config]):
"""Loads a single-file Qwen3-VL encoder checkpoint (e.g. ComfyUI ``qwen3vl_4b_bf16`` / ``_fp8_scaled``).
- The checkpoint bundles the language model + visual tower; the tower is dropped on the way in (see
- ``drop_qwen3vl_visual_tower_keys``). ComfyUI 'scaled fp8' weights are dequantized to the compute
- dtype on load.
+ The checkpoint bundles the language model + visual tower; the tower is dropped on the way in, with the
+ LM head (see ``drop_qwen3vl_unloaded_keys``). ComfyUI 'scaled fp8' weights are kept for the fp8 matmul or fp8
+ storage where the device has either, and folded into the compute dtype otherwise. ``int8_tensorwise``
+ layers stay int8 and Comfy's ``nvfp4`` layers stay packed, both dequantized per forward.
"""
CONFIG_CLASS = Qwen3VLEncoder_Checkpoint_Config
@@ -1055,7 +1092,19 @@ class Qwen3VLEncoderCheckpointLoader(_Qwen3VLEncoderSingleFileLoader[Qwen3VLEnco
# Ahead of every pass that reads tensors, so the tower is never dequantized, cast, copied or
# reserved for. (The file *header* is still read below for quantization metadata, which can
# therefore still name visual layers; those hints match no surviving key and are ignored.)
- sd = drop_qwen3vl_visual_tower_keys(sd)
+ # The LM head goes with it: this model has none, and a packed one would name no module.
+ sd = drop_qwen3vl_unloaded_keys(sd)
+ metadata = read_safetensors_metadata(model_path, self._logger)
+
+ # Comfy's nvfp4 build packs every language-model projection and names the layers in `.comfy_quant`
+ # markers (a header in some repacks). Take them out before either side-channel branch reads a scale:
+ # the int8 branch strips every remaining marker -- one of the two things that name an nvfp4 layer --
+ # and the fp8 extraction pops every `weight_scale` and discards those whose weight is not float8,
+ # nvfp4's block scales included. `install_nvfp4_layers` puts them back, packed, under the paths the
+ # remap gives their weights.
+ nvfp4_payloads = pop_nvfp4_layers(sd, header_layers=parse_quantization_metadata(metadata))
+ nvfp4_payloads = _remap_qwen3vl_singlefile_keys(nvfp4_payloads)
+
# Same one-or-the-other split as the transformer above, and here it also guards the fp8
# *detection*: an int8 layer ships a `.weight_scale` too, so probing for scales without
# ruling out int8 first would keep the encoder "fp8-resident" over weights that were never
@@ -1082,7 +1131,6 @@ class Qwen3VLEncoderCheckpointLoader(_Qwen3VLEncoderSingleFileLoader[Qwen3VLEnco
# only what this path already left dense -- work with no saving on the layers that matter.
use_fp8_storage = False
else:
- metadata = read_safetensors_metadata(model_path, self._logger)
# Per-layer markers must be read before extract_fp8_scaled_layers() drops them, and before
# the key remap, which would not carry a ".comfy_quant" suffix to a sensible destination.
layer_hints = {**extract_comfy_quant_hints(sd), **parse_quantization_metadata(metadata)}
@@ -1111,19 +1159,22 @@ class Qwen3VLEncoderCheckpointLoader(_Qwen3VLEncoderSingleFileLoader[Qwen3VLEnco
# for the byte count the file already had.
use_fp8_storage = source_is_fp8 and _device_supports_fp8_storage(self._torch_device, self._logger)
+ # Every layer that arrived scaled, before the split folds the ones the matmul cannot take. The storage
+ # pass below must leave those alone: cast again, they would be re-quantized *without* their scale.
+ scaled_paths = set(fp8_layers)
+
te_config = self._load_te_config(config)
with accelerate.init_empty_weights():
model = Qwen3VLModel._from_config(te_config)
# Its weights were dropped from the state dict above, so the module has to go too -- left in
# place it would stay on the meta device and `_reject_incomplete_load` would rightly refuse.
drop_qwen3vl_visual_tower(model)
+ # `Qwen3VLModel` declares no precision-sensitive modules, but read them rather than assume: in the
+ # int8 split they are also what keeps a marker on a non-Linear (a "quantize everything" repack's 1-D
+ # norms) out of `swap_in_int8_linears`, and the nvfp4 install decodes rather than packs under them.
+ skip_patterns = _model_declared_skip_patterns(model)
if int8_markers:
- # `Qwen3VLModel` declares no precision-sensitive modules, but read them rather than
- # assume: the split is also what keeps a marker on a non-Linear (a "quantize
- # everything" repack's 1-D norms) out of `swap_in_int8_linears`.
- skip_patterns = _model_declared_skip_patterns(model)
-
quantized = install_int8_convrot_layers(
model,
sd,
@@ -1132,6 +1183,9 @@ class Qwen3VLEncoderCheckpointLoader(_Qwen3VLEncoderSingleFileLoader[Qwen3VLEnco
architecture="Qwen3-VL encoder",
reserve=self._ram_cache.make_room,
skip_patterns=skip_patterns,
+ # The nvfp4 layers taken out above are held beside the int8 ones, and this is the
+ # branch's only reservation.
+ extra_reserved_bytes=predict_nvfp4_install_size(model, nvfp4_payloads, model_dtype, skip_patterns),
)
self._logger.info(
f"Qwen3-VL encoder: kept {len(quantized)} of {len(int8_markers)} layer(s) in int8 "
@@ -1168,21 +1222,27 @@ class Qwen3VLEncoderCheckpointLoader(_Qwen3VLEncoderSingleFileLoader[Qwen3VLEnco
keep_fp8=keep_fp8,
model=model,
fp8_layers=fp8_layers,
- nvfp4_payloads={},
+ nvfp4_payloads=nvfp4_payloads,
+ skip_patterns=skip_patterns,
)
if fp8_layers and not keep_fp8:
# Neither consumer wants them packed: fold the scales into the weights. Both consumers
# were resolved above, next to the matmul probe, because this fold is irreversible.
dequantize_fp8_scaled(sd, fp8_layers, model_dtype)
fp8_layers = {}
- fp8_layers = split_fp8_scaled_layers(sd, fp8_layers, model_dtype, model=model)
- # No `skip_patterns` here on purpose: this model declares none, and the storage pass below
- # applies `_FP8_DEFAULT_SKIP_PATTERNS` itself. Those two lists used to have to not intersect
- # on a layer class with no fp8-capable wrapper -- a `pos_embed` or a `patch_embed.proj`
- # would arrive fp8 from the state dict, be skipped by the cast pass, and then raise on the
- # first forward. `_apply_fp8_to_nn_module` now restores the compute dtype on the modules it
- # skips, so the two lists are independent again.
- cast_state_dict(sd, model_dtype, keep_fp8=keep_fp8, model=model)
+ # The model's own patterns (none, today) go to the reservation, the split, the cast and the nvfp4
+ # install alike, so the prediction answers for what each of them then does. They are independent
+ # of `_FP8_DEFAULT_SKIP_PATTERNS`, which the storage pass below applies itself: a `pos_embed` or
+ # `patch_embed.proj` arriving fp8 and skipped there used to raise on the first forward, and
+ # `_apply_fp8_to_nn_module` now restores the compute dtype on the modules it skips.
+ fp8_layers = split_fp8_scaled_layers(sd, fp8_layers, model_dtype, model=model, skip_patterns=skip_patterns)
+ cast_state_dict(sd, model_dtype, keep_fp8=keep_fp8, model=model, skip_patterns=skip_patterns)
+
+ if nvfp4_payloads:
+ packed = install_nvfp4_layers(model, sd, nvfp4_payloads, model_dtype, skip_patterns)
+ self._logger.info(
+ f"Qwen3-VL encoder '{config.name}': kept {packed} of {len(nvfp4_payloads)} nvfp4 layer(s) packed."
+ )
load_state_dict_ignoring_extras(
model, sd, source="Qwen3-VL encoder checkpoint", assign=True, allow_missing=True
@@ -1243,7 +1303,22 @@ class Qwen3VLEncoderCheckpointLoader(_Qwen3VLEncoderSingleFileLoader[Qwen3VLEnco
if use_fp8_storage:
# `model.dtype` now reports the float8 storage dtype; `_apply_fp8_to_nn_module` records
# the real compute dtype so callers can recover it via `get_model_compute_dtype`.
- self._apply_fp8_to_nn_module(model, storage_dtype=torch.float8_e4m3fn, compute_dtype=model_dtype)
+ #
+ # A scaled layer reaches this branch only when the split folded it -- every one it had, or the
+ # attach branch above would have run. The Linears among them go to fp8 storage like any other,
+ # which is what this pass is for: an MXFP8 build's block scales are folded, and its language model
+ # is held in fp8 rather than at twice the size. A folded embedding is not: Comfy's nvfp4 8B build
+ # scales its token table, and cast again it would lose that scale for the accuracy cost measured
+ # above for exactly this table -- the reason the attach branch leaves every embedding alone.
+ self._apply_fp8_to_nn_module(
+ model,
+ storage_dtype=torch.float8_e4m3fn,
+ compute_dtype=model_dtype,
+ skip=lambda name, module: name in scaled_paths and not isinstance(module, torch.nn.Linear),
+ )
+ # Counted rather than assumed: on that nvfp4 build every Linear is packed and the embedding skipped, so
+ # the pass leaves nothing in fp8, and saying it did would misdescribe the encoder.
+ if use_fp8_storage and count_fp8_weights(model):
self._logger.info(
f"FP8 layerwise casting enabled for Qwen3-VL encoder '{config.name}' "
f"(storage=float8_e4m3fn, compute={model_dtype})."
diff --git a/invokeai/backend/model_manager/util/qwen3_vl.py b/invokeai/backend/model_manager/util/qwen3_vl.py
index 318987e845..cbb4fd3104 100644
--- a/invokeai/backend/model_manager/util/qwen3_vl.py
+++ b/invokeai/backend/model_manager/util/qwen3_vl.py
@@ -204,3 +204,27 @@ def attach_qwen3vl_visual_tower(model: torch.nn.Module, tower: torch.nn.Module)
finally:
model.visual = existing
model.rope_deltas = prior_rope_deltas
+
+
+def drop_qwen3vl_unloaded_keys(sd: dict[str, Any]) -> dict[str, Any]:
+ """Keep only what the single-file encoder loader reads: drop the visual tower and the LM head.
+
+ ``Qwen3VLModel`` has no LM head, so a non-strict load would discard it anyway -- but only after the
+ side-channel handling had folded and reserved for it: on the 8B fp8 builds a 151936x4096 bf16 copy.
+ Identification judges a file's quantization by the same view, so it refuses nothing the loader would
+ never read.
+ """
+ return {k: v for k, v in sd.items() if not _is_qwen3vl_unloaded_key(k)}
+
+
+def _is_qwen3vl_unloaded_key(key: Any) -> bool:
+ """Whether a checkpoint key belongs to the visual tower or the LM head, sidecars included.
+
+ The head is matched where the remap sends it, like the tower: a top-level ``lm_head.*`` and a ``model.lm_head.*``
+ both land on ``language_model.lm_head``, which names no module. Left in, an nvfp4 head fails the install that
+ way, and a scaled fp8 one is folded and reserved for, then discarded.
+ """
+ if not isinstance(key, str):
+ return False
+ target = qwen3vl_target_key(key)
+ return target.startswith("visual.") or target.startswith("language_model.lm_head.")
diff --git a/invokeai/backend/quantization/fp8_scaled.py b/invokeai/backend/quantization/fp8_scaled.py
index 46e0d8d46e..d97fde5263 100644
--- a/invokeai/backend/quantization/fp8_scaled.py
+++ b/invokeai/backend/quantization/fp8_scaled.py
@@ -651,11 +651,53 @@ def dequantize_fp8_scaled(
weight = sd.get(key)
if weight is None:
continue
- weight = weight.float()
- sd[key] = (weight * expand_weight_scale(weight, layer.weight_scale, path)).to(dtype)
+ sd[key] = _fold_scale(weight, layer.weight_scale, dtype, path)
return sd
+# The most elements a fold widens to float32 at once. The multiply holds two float32 copies of what it works
+# on, so folding a tensor whole peaks at 10 bytes per element in RAM: 5.8 GiB for the 151936x4096 token
+# table of Comfy's nvfp4 Qwen3-VL 8B, against a 1.2 GiB result and a reservation sized for that result.
+_FOLD_SLAB_ELEMENTS = 1 << 24
+
+
+def _fold_scale(weight: torch.Tensor, scale: torch.Tensor, dtype: torch.dtype, path: str) -> torch.Tensor:
+ """``(weight.float() * expand_weight_scale(weight, scale)).to(dtype)``, element for element, a slab of rows
+ at a time.
+
+ ``scale`` is the compact one :func:`extract_fp8_scaled_layers` keeps, and it is expanded a slab at a time as
+ well: a block-wise or MXFP8 scale widened whole is itself a float32 copy of the weight, 2.3 GiB for that
+ token table, before the first slab is folded. So beyond the result, nothing the size of the weight is ever
+ held in float32, whatever the layout. Each slab rounds exactly as the whole would, since every element is
+ computed alone.
+ """
+ rows = weight.shape[0] if weight.dim() else 1
+ block_wise = scale.numel() > 1 and scale.dim() > 1
+ if block_wise and rows % scale.shape[0]:
+ # Expanded, such a scale never lines up with the rows; the multiply would refuse it without naming the layer.
+ raise ValueError(
+ f"{path}: a {tuple(scale.shape)} block-wise weight_scale does not tile the {rows} rows of its "
+ f"{tuple(weight.shape)} weight; the checkpoint's quantization metadata appears to be malformed."
+ )
+ if weight.numel() <= _FOLD_SLAB_ELEMENTS:
+ return (weight.float() * expand_weight_scale(weight, scale, path)).to(dtype)
+ step = max(1, _FOLD_SLAB_ELEMENTS // (weight.numel() // rows))
+ # A scalar or one entry per row: expanding it is a view, sliced per slab below.
+ expanded = None if block_wise else expand_weight_scale(weight, scale, path)
+ rows_per_scale_row = rows // scale.shape[0] if block_wise else 1
+ out = torch.empty(weight.shape, dtype=dtype, device=weight.device)
+ for start in range(0, rows, step):
+ slab = slice(start, start + step)
+ if expanded is None:
+ # The scale rows this slab's rows read, one per weight row, widened along the other axes.
+ index = torch.arange(start, min(start + step, rows), device=scale.device) // rows_per_scale_row
+ slab_scale = expand_weight_scale(weight[slab], scale.index_select(0, index), path)
+ else:
+ slab_scale = expanded[slab] if expanded.dim() else expanded
+ out[slab] = weight[slab].float() * slab_scale
+ return out
+
+
def attach_fp8_scales(
model: torch.nn.Module,
layers: Mapping[str, Fp8ScaledLayer],
diff --git a/invokeai/backend/quantization/nvfp4.py b/invokeai/backend/quantization/nvfp4.py
index 743bd76c94..cea81a00c5 100644
--- a/invokeai/backend/quantization/nvfp4.py
+++ b/invokeai/backend/quantization/nvfp4.py
@@ -193,7 +193,12 @@ class NVFP4Payload:
return sum(t.nelement() * t.element_size() for t in (self.weight, self.weight_scale, self.weight_scale_2))
-def _find_nvfp4_layers(sd: Mapping[str, Any], header_layers: Mapping[str, Any] | None) -> list[str]:
+def find_nvfp4_layers(
+ sd: Mapping[str, Any],
+ header_layers: Mapping[str, Any] | None,
+ *,
+ markers: Mapping[str, Mapping[str, Any]] | None = None,
+) -> list[str]:
"""Every nvfp4 layer in ``sd``, after refusing what this module would read wrong. Mutates nothing.
Detection is structural -- a ``weight_scale_2`` beside the weight -- and decided per layer, never per
@@ -201,6 +206,11 @@ def _find_nvfp4_layers(sd: Mapping[str, Any], header_layers: Mapping[str, Any] |
with a ``weight_scale`` but no ``weight_scale_2``; malformed layers; and layers that neither a
``.comfy_quant`` marker nor a ``_quantization_metadata`` entry (``header_layers``, in ``sd``'s key
space) names as nvfp4.
+
+ Reads dtypes and shapes only, so identification can run it over meta tensors and refuse at install time
+ what a load would refuse. A meta marker has no bytes to parse, so there pass the markers as ``markers``,
+ keyed by layer path as ``read_comfy_quant_markers`` reads them; each ``.comfy_quant`` key in ``sd`` then
+ takes its entry from there instead of from its tensor, and a marker of a layer not in ``sd`` is ignored.
"""
layers = sorted(
k[: -len(WEIGHT_SCALE_2_SUFFIX)] for k in sd if isinstance(k, str) and k.endswith(WEIGHT_SCALE_2_SUFFIX)
@@ -218,7 +228,8 @@ def _find_nvfp4_layers(sd: Mapping[str, Any], header_layers: Mapping[str, Any] |
marked: dict[str, Any] = {}
for key in [k for k in sd if isinstance(k, str) and k.endswith(COMFY_QUANT_SUFFIX)]:
path = key[: -len(COMFY_QUANT_SUFFIX)]
- marked[path] = parse_comfy_quant_marker(sd[key]).get("format")
+ marker = parse_comfy_quant_marker(sd[key]) if markers is None else markers.get(path, {})
+ marked[path] = marker.get("format")
if marked[path] == NVFP4_FORMAT and path not in claimed:
raise ValueError(f"nvfp4 layer '{path}' has no weight_scale_2, so it cannot be decoded.")
if path in claimed and marked[path] not in (None, NVFP4_FORMAT):
@@ -285,7 +296,7 @@ def reject_nvfp4_layers_a_plain_fold_cannot_decode(sd: Mapping[str, Any], what:
Detection is the union of two structural tests: a ``weight_scale_2`` beside the weight, which is
what the decode keys on, and a packed ``uint8`` weight carrying a block scale without one, which
- is the half-state :func:`_find_nvfp4_layers` refuses by name. Keying on the first alone would
+ is the half-state :func:`find_nvfp4_layers` refuses by name. Keying on the first alone would
miss the second, and the fold takes it just as readily.
Narrower than the decode in one way worth knowing: at the Wan seam a bundled nvfp4 text encoder
@@ -299,7 +310,7 @@ def reject_nvfp4_layers_a_plain_fold_cannot_decode(sd: Mapping[str, Any], what:
and key.endswith(WEIGHT_SCALE_2_SUFFIX)
and f"{key[: -len(WEIGHT_SCALE_2_SUFFIX)]}.weight" in sd
}
- # A packed weight with a block scale and no global one is the half-state `_find_nvfp4_layers`
+ # A packed weight with a block scale and no global one is the half-state `find_nvfp4_layers`
# refuses by name. Keying on `weight_scale_2` alone would miss it, and the fold takes it just as
# readily -- so the detection here is the union, not the narrower test.
half = {
@@ -326,7 +337,7 @@ def pop_nvfp4_layers(sd: dict[str, Any], header_layers: Mapping[str, Any] | None
is touched.
"""
payloads: dict[str, NVFP4Payload] = {}
- for path in _find_nvfp4_layers(sd, header_layers):
+ for path in find_nvfp4_layers(sd, header_layers):
payloads[path] = NVFP4Payload(
weight=sd.pop(f"{path}.weight"),
weight_scale=sd.pop(f"{path}.weight_scale"),
diff --git a/tests/backend/model_manager/configs/test_qwen3_vl_encoder_config.py b/tests/backend/model_manager/configs/test_qwen3_vl_encoder_config.py
index de905a95ee..a70fe20345 100644
--- a/tests/backend/model_manager/configs/test_qwen3_vl_encoder_config.py
+++ b/tests/backend/model_manager/configs/test_qwen3_vl_encoder_config.py
@@ -10,8 +10,10 @@ from pathlib import Path
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.identification_utils import InvalidMatchError, NotAMatchError
from invokeai.backend.model_manager.configs.qwen3_vl_encoder import (
Qwen3VLEncoder_Checkpoint_Config,
Qwen3VLEncoder_Qwen3VLEncoder_Config,
@@ -19,6 +21,7 @@ from invokeai.backend.model_manager.configs.qwen3_vl_encoder import (
)
from invokeai.backend.model_manager.model_on_disk import ModelOnDisk
from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelFormat, ModelType, Qwen3VLVariantType
+from tests.fixtures.quantized_payloads import comfy_quant_marker, nvfp4_signed_tensors, quantize_scaled_fp8
_REQUIRED_FIELDS = {
"hash": "blake3:fakehash",
@@ -175,6 +178,154 @@ class TestQwen3VLEncoderCheckpointConfig:
Qwen3VLEncoder_Checkpoint_Config.from_model_on_disk(mod, {**_REQUIRED_FIELDS})
+_PACKED = "model.layers.0.self_attn.q_proj"
+
+
+def _replace_packed_layer(state_dict: dict, **tensors: torch.Tensor) -> None:
+ for key in [key for key in state_dict if key.startswith(f"{_PACKED}.")]:
+ del state_dict[key]
+ state_dict.update({f"{_PACKED}.{suffix}": tensor for suffix, tensor in tensors.items()})
+
+
+class TestQwen3VLEncoderQuantizedCheckpoints:
+ """What the loader would refuse of a quantized single file is refused at install time; the rest installs.
+
+ Written as real files and read through `ModelOnDisk`, because identification sees tensors on the meta
+ device -- dtypes and shapes, no bytes -- so whatever names a layer nvfp4 has to be read from the file.
+ """
+
+ @classmethod
+ def _identify(
+ cls, tmp_path: Path, mutate=lambda _sd: None, *, naming: str = "marker"
+ ) -> Qwen3VLEncoder_Checkpoint_Config:
+ packed, _ = nvfp4_signed_tensors(_PACKED, torch.ones(128, 64, dtype=torch.bool))
+ state_dict = {
+ "model.embed_tokens.weight": torch.zeros(2, 2560, dtype=torch.bfloat16),
+ "model.layers.35.input_layernorm.weight": torch.ones(4, dtype=torch.bfloat16),
+ "model.visual.blocks.0.attn.qkv.weight": torch.zeros(4, 4, dtype=torch.bfloat16),
+ **packed,
+ }
+ metadata = None
+ if naming == "marker":
+ state_dict[f"{_PACKED}.comfy_quant"] = comfy_quant_marker({"format": "nvfp4"})
+ else:
+ metadata = {"_quantization_metadata": json.dumps({"layers": {_PACKED: {"format": "nvfp4"}}})}
+ mutate(state_dict)
+ path = tmp_path / "qwen3vl_4b.safetensors"
+ save_file(state_dict, str(path), metadata=metadata)
+ return Qwen3VLEncoder_Checkpoint_Config.from_model_on_disk(ModelOnDisk(path), {**_REQUIRED_FIELDS})
+
+ @pytest.mark.parametrize("naming", ["marker", "header"])
+ def test_a_comfy_nvfp4_build_installs(self, tmp_path: Path, naming: str) -> None:
+ assert self._identify(tmp_path, naming=naming).variant is Qwen3VLVariantType.Qwen3VL_4B
+
+ def test_scaled_fp8_and_int8_builds_still_install(self, tmp_path: Path) -> None:
+ # Both pair a weight with a `weight_scale` too, and neither is 4-bit.
+ fp8 = quantize_scaled_fp8(torch.randn(128, 64))
+ assert (
+ self._identify(
+ tmp_path, lambda sd: _replace_packed_layer(sd, weight=fp8.codes, weight_scale=fp8.scale)
+ ).variant
+ is Qwen3VLVariantType.Qwen3VL_4B
+ )
+ int8 = {
+ "weight": torch.randint(-127, 128, (128, 64), dtype=torch.int8),
+ "weight_scale": torch.ones(128, 1),
+ "comfy_quant": comfy_quant_marker({"format": "int8_tensorwise"}),
+ }
+ assert (
+ self._identify(tmp_path, lambda sd: _replace_packed_layer(sd, **int8)).variant
+ is Qwen3VLVariantType.Qwen3VL_4B
+ )
+
+ @pytest.mark.parametrize(
+ ("mutate", "message"),
+ [
+ # ModelOpt-style: the nvfp4 tensors, but nothing naming the layout ComfyUI's.
+ pytest.param(lambda sd: sd.pop(f"{_PACKED}.comfy_quant"), "no ComfyUI `comfy_quant` marker", id="unnamed"),
+ # A custom RTN repack published for this encoder: packed codes and a block scale only.
+ pytest.param(lambda sd: sd.pop(f"{_PACKED}.weight_scale_2"), "no weight_scale_2", id="no-global-scale"),
+ pytest.param(lambda sd: sd.update({f"{_PACKED}.pre_quant_scale": torch.ones(64)}), "AWQ", id="awq"),
+ # A marker that names no format names nothing; only the header could, and here it does not.
+ *(
+ pytest.param(
+ lambda sd, marker=marker: sd.update({f"{_PACKED}.comfy_quant": comfy_quant_marker(marker)}),
+ "no ComfyUI `comfy_quant` marker",
+ id=f"unnamed-{name}-marker",
+ )
+ for name, marker in (("empty", {}), ("format-less", {"full_precision_matrix_mult": False}))
+ ),
+ # Marked nvfp4 over a dense weight: no `weight_scale_2` anywhere in the file, and no packed half-state for
+ # the structural check to catch, so only the marker's own bytes say what the loader will refuse.
+ pytest.param(
+ lambda sd: _replace_packed_layer(
+ sd,
+ weight=torch.zeros(128, 128, dtype=torch.bfloat16),
+ comfy_quant=comfy_quant_marker({"format": "nvfp4"}),
+ ),
+ "has no weight_scale_2, so it cannot be decoded",
+ id="nvfp4-marker-on-a-dense-weight",
+ ),
+ ],
+ )
+ def test_a_layer_the_loader_would_refuse_is_refused_at_install(self, tmp_path: Path, mutate, message: str) -> None:
+ with pytest.raises(InvalidMatchError, match=message):
+ self._identify(tmp_path, mutate)
+ with pytest.raises(ValueError, match=message):
+ self._loader_finds_nvfp4_layers(tmp_path / "qwen3vl_4b.safetensors")
+
+ def test_a_repack_packing_its_embedding_too_is_refused_rather_than_unknown(self, tmp_path: Path) -> None:
+ # The variant is read off the embedding's width, which a packed table halves. Checked after that, such a
+ # file would fail there instead and register as an unknown model, its reason only in the log.
+ def packed_embedding_without_global_scale(state_dict: dict) -> None:
+ state_dict["model.embed_tokens.weight"] = torch.zeros(2, 1280, dtype=torch.uint8)
+ state_dict["model.embed_tokens.weight_scale"] = torch.zeros(2, 160).to(torch.float8_e4m3fn)
+
+ with pytest.raises(InvalidMatchError, match="no weight_scale_2"):
+ self._identify(tmp_path, packed_embedding_without_global_scale)
+
+ def test_a_layer_the_loader_never_reads_cannot_get_a_file_refused(self, tmp_path: Path) -> None:
+ # The loader drops the visual tower and the LM head before it reads a scale, so their layout is not this
+ # file's to answer for.
+ def unread_half_state_layers(state_dict: dict) -> None:
+ for path in ("model.visual.blocks.0.mlp.linear_fc1", "lm_head"):
+ state_dict[f"{path}.weight"] = torch.zeros(128, 32, dtype=torch.uint8)
+ state_dict[f"{path}.weight_scale"] = torch.zeros(128, 4).to(torch.float8_e4m3fn)
+
+ assert self._identify(tmp_path, unread_half_state_layers).variant is Qwen3VLVariantType.Qwen3VL_4B
+
+ @staticmethod
+ def _loader_finds_nvfp4_layers(path: Path) -> list[str]:
+ """The loader's own check, over the real tensors and header of the file `_identify` wrote."""
+ from safetensors.torch import load_file
+
+ from invokeai.backend.model_manager.util.qwen3_vl import drop_qwen3vl_unloaded_keys
+ from invokeai.backend.quantization.fp8_scaled import parse_quantization_metadata, read_safetensors_metadata
+ from invokeai.backend.quantization.nvfp4 import find_nvfp4_layers
+
+ state_dict = drop_qwen3vl_unloaded_keys(load_file(str(path)))
+ return find_nvfp4_layers(state_dict, parse_quantization_metadata(read_safetensors_metadata(path)))
+
+ @pytest.mark.parametrize("marker", [{}, {"full_precision_matrix_mult": False}], ids=["empty", "format_less"])
+ def test_a_header_named_layer_installs_beside_a_marker_naming_no_format(self, tmp_path: Path, marker) -> None:
+ # The loader names a layer nvfp4 when its marker or its header entry says so. Laid over the header, a marker
+ # without a format erased the header's entry, and a file the loader takes was refused at install.
+ def add_marker(state_dict: dict) -> None:
+ state_dict[f"{_PACKED}.comfy_quant"] = comfy_quant_marker(marker)
+
+ assert self._identify(tmp_path, add_marker, naming="header").variant is Qwen3VLVariantType.Qwen3VL_4B
+ assert self._loader_finds_nvfp4_layers(tmp_path / "qwen3vl_4b.safetensors") == [_PACKED]
+
+ def test_a_marker_contradicting_a_header_named_layer_is_refused_at_install_as_at_load(self, tmp_path: Path) -> None:
+ def add_marker(state_dict: dict) -> None:
+ state_dict[f"{_PACKED}.comfy_quant"] = comfy_quant_marker({"format": "float8_e4m3fn"})
+
+ with pytest.raises(InvalidMatchError, match="contradicts its tensors"):
+ self._identify(tmp_path, add_marker, naming="header")
+ with pytest.raises(ValueError, match="contradicts its tensors"):
+ self._loader_finds_nvfp4_layers(tmp_path / "qwen3vl_4b.safetensors")
+
+
class TestQwen3VLEncoderDirectoryConfig:
@staticmethod
def _write_config(path: Path, *, hidden_size: int = 2560, num_hidden_layers: int = 36) -> None:
diff --git a/tests/backend/model_manager/load/test_krea2_loader_boundaries.py b/tests/backend/model_manager/load/test_krea2_loader_boundaries.py
index adec4e24f4..ea58b80800 100644
--- a/tests/backend/model_manager/load/test_krea2_loader_boundaries.py
+++ b/tests/backend/model_manager/load/test_krea2_loader_boundaries.py
@@ -438,7 +438,7 @@ def test_checkpoint_encoder_loader_decodes_int8_and_does_not_call_it_fp8(monkeyp
return cls()
checkpoint_path = tmp_path / "qwen3vl_int8_convrot.safetensors"
- checkpoint_path.touch()
+ safetensors_torch.save_file(state_dict, str(checkpoint_path))
config = Qwen3VLEncoder_Checkpoint_Config.model_construct(path=str(checkpoint_path), name="encoder")
fp8_calls: list = []
@@ -450,7 +450,6 @@ def test_checkpoint_encoder_loader_decodes_int8_and_does_not_call_it_fp8(monkeyp
loader._apply_fp8_to_nn_module = lambda *a, **k: fp8_calls.append(a)
monkeypatch.setattr(transformers, "Qwen3VLModel", _TinyEncoder, raising=False)
- monkeypatch.setattr(safetensors_torch, "load_file", lambda _path: state_dict)
monkeypatch.setattr(
"invokeai.backend.model_manager.load.model_loaders.krea2.TorchDevice.choose_torch_device",
lambda: torch.device("cpu"),
@@ -714,7 +713,7 @@ def test_the_encoder_names_itself_when_refusing_an_unmarked_int8_weight(monkeypa
return cls()
checkpoint_path = tmp_path / "qwen3vl_int8_convrot.safetensors"
- checkpoint_path.touch()
+ safetensors_torch.save_file(state_dict, str(checkpoint_path))
config = Qwen3VLEncoder_Checkpoint_Config.model_construct(path=str(checkpoint_path), name="encoder")
loader = object.__new__(Qwen3VLEncoderCheckpointLoader)
@@ -724,7 +723,6 @@ def test_the_encoder_names_itself_when_refusing_an_unmarked_int8_weight(monkeypa
loader._load_te_config = lambda _config: SimpleNamespace()
monkeypatch.setattr(transformers, "Qwen3VLModel", _TinyEncoder, raising=False)
- monkeypatch.setattr(safetensors_torch, "load_file", lambda _path: state_dict)
monkeypatch.setattr(
"invokeai.backend.model_manager.load.model_loaders.krea2.TorchDevice.choose_torch_device",
lambda: torch.device("cpu"),
@@ -788,7 +786,7 @@ def test_a_merged_encoder_checkpoint_is_not_mistaken_for_a_mixed_format_one(
return cls()
checkpoint_path = tmp_path / "qwen3vl_int8_convrot.safetensors"
- checkpoint_path.touch()
+ safetensors_torch.save_file(state_dict, str(checkpoint_path))
config = Qwen3VLEncoder_Checkpoint_Config.model_construct(path=str(checkpoint_path), name="encoder")
loader = object.__new__(Qwen3VLEncoderCheckpointLoader)
@@ -799,7 +797,6 @@ def test_a_merged_encoder_checkpoint_is_not_mistaken_for_a_mixed_format_one(
loader._apply_fp8_to_nn_module = lambda *a, **k: None
monkeypatch.setattr(transformers, "Qwen3VLModel", _TinyEncoder, raising=False)
- monkeypatch.setattr(safetensors_torch, "load_file", lambda _path: state_dict)
monkeypatch.setattr(
"invokeai.backend.model_manager.load.model_loaders.krea2.TorchDevice.choose_torch_device",
lambda: torch.device("cpu"),
@@ -1029,7 +1026,7 @@ def test_an_nvfp4_layer_missing_its_global_scale_is_refused_before_the_cache_is_
A packed uint8 weight with a block-scale grid and no `weight_scale_2` is the state a guard keyed
on `weight_scale_2` -- the key the decode itself keys on -- lets straight through.
- `_find_nvfp4_layers` refuses it and `test_nvfp4.py` pins that; what only a seam can answer is
+ `find_nvfp4_layers` refuses it and `test_nvfp4.py` pins that; what only a seam can answer is
whether this loader reaches the detector before it asks the cache for room. Krea-2 pops on the
*native* keys, before the conversion that remaps the payload paths, so the refusal has to survive
being upstream of the rename as well as upstream of the reservation.
diff --git a/tests/backend/model_manager/load/test_ltx2_loader.py b/tests/backend/model_manager/load/test_ltx2_loader.py
index 2b7b83df7b..86641e5880 100644
--- a/tests/backend/model_manager/load/test_ltx2_loader.py
+++ b/tests/backend/model_manager/load/test_ltx2_loader.py
@@ -526,7 +526,7 @@ def test_an_nvfp4_layer_missing_its_global_scale_is_refused_before_the_cache_is_
"""The degraded half-state, at this seam rather than at the detector.
A packed uint8 weight with a block-scale grid and no `weight_scale_2` is what a guard keyed on
- `weight_scale_2` -- the key the decode keys on -- lets straight through. `_find_nvfp4_layers`
+ `weight_scale_2` -- the key the decode keys on -- lets straight through. `find_nvfp4_layers`
refuses it and `test_nvfp4.py` pins that; what only a seam can answer is whether this loader
reaches the detector before it asks the cache for room. Here a key conversion stands between the
pop and the reservation, and nothing but their order keeps them that way round.
diff --git a/tests/backend/model_manager/load/test_mistral_encoder_checkpoint_loader.py b/tests/backend/model_manager/load/test_mistral_encoder_checkpoint_loader.py
index 7cd8662fbd..fe8dc505a7 100644
--- a/tests/backend/model_manager/load/test_mistral_encoder_checkpoint_loader.py
+++ b/tests/backend/model_manager/load/test_mistral_encoder_checkpoint_loader.py
@@ -304,7 +304,7 @@ def test_an_nvfp4_layer_missing_its_global_scale_is_refused_before_the_cache_is_
"""The degraded half-state, at this seam rather than at the detector.
A packed uint8 weight with a block-scale grid and no `weight_scale_2` is what a guard keyed on
- `weight_scale_2` -- the key the decode itself keys on -- lets straight through. `_find_nvfp4_layers`
+ `weight_scale_2` -- the key the decode itself keys on -- lets straight through. `find_nvfp4_layers`
refuses it and `test_nvfp4.py` pins that; what only a seam can answer is whether this loader still
reaches the detector before it asks the cache for room, and on both fp8 branches. Nothing but the
order of two statements keeps `pop_nvfp4_layers` above the reservation here.
diff --git a/tests/backend/model_manager/load/test_qwen3_encoder_checkpoint_loader.py b/tests/backend/model_manager/load/test_qwen3_encoder_checkpoint_loader.py
index 9982f04079..64d30d43e2 100644
--- a/tests/backend/model_manager/load/test_qwen3_encoder_checkpoint_loader.py
+++ b/tests/backend/model_manager/load/test_qwen3_encoder_checkpoint_loader.py
@@ -259,7 +259,7 @@ def test_an_nvfp4_layer_missing_its_global_scale_is_refused_before_the_cache_is_
"""The degraded nvfp4 half-state, at this seam rather than at the detector.
A packed uint8 weight with a block-scale grid and no `weight_scale_2` is the state a guard keyed
- on `weight_scale_2` -- the key the decode keys on -- lets straight through. `_find_nvfp4_layers`
+ on `weight_scale_2` -- the key the decode keys on -- lets straight through. `find_nvfp4_layers`
refuses it and `test_nvfp4.py` pins that; what only a seam can answer is whether this loader
reaches the detector before it asks the cache for room. Asserted through the cache double this
file already uses, in the same idiom as the cells above, because this loader reads its header
diff --git a/tests/backend/model_manager/load/test_qwen3_vl_encoder_nvfp4_loader.py b/tests/backend/model_manager/load/test_qwen3_vl_encoder_nvfp4_loader.py
new file mode 100644
index 0000000000..187fa633e4
--- /dev/null
+++ b/tests/backend/model_manager/load/test_qwen3_vl_encoder_nvfp4_loader.py
@@ -0,0 +1,356 @@
+"""The single-file Qwen3-VL encoder loader keeps Comfy's nvfp4 builds packed.
+
+`qwen3vl_8b_nvfp4.safetensors` (Comfy-Org, Ideogram 4) packs all seven projections of every layer, names them only in
+`.comfy_quant` markers, and keeps the token embedding and the LM head in scaled fp8. Community 4B repacks name their
+layers in `.comfy_quant` markers too; the safetensors header is ComfyUI's other way to name nvfp4 layers, which the
+loader honours as well. Both reach the loader shared by Krea-2 and Ideogram 4. What these tests pin is the order: the
+packed layers leave the state dict before either side-channel branch reads a scale, come back packed under the
+transformers paths of a real `Qwen3VLModel`, are counted in the one reservation as they are held, and a folded scaled
+embedding is not re-quantized without its scale -- while the Linears an MXFP8 build folds still go to fp8 storage as
+before. The compute dtype is bf16, as in production: the packed global scale must not be cast with it.
+"""
+
+import json
+from pathlib import Path
+
+import pytest
+import safetensors.torch
+import torch
+from transformers import Qwen3VLConfig, Qwen3VLModel
+
+from invokeai.backend.model_manager.configs.qwen3_vl_encoder import Qwen3VLEncoder_Checkpoint_Config
+from invokeai.backend.model_manager.load.model_loaders import krea2
+from invokeai.backend.model_manager.load.model_loaders.krea2 import Qwen3VLEncoderCheckpointLoader
+from invokeai.backend.quantization.int8_convrot import Int8ConvrotLinear
+from invokeai.backend.quantization.nvfp4 import NVFP4Linear
+from tests.fixtures.loader_seams import Seam, prepare
+from tests.fixtures.quantized_payloads import (
+ MX_BLOCK_SIZE,
+ comfy_quant_marker,
+ mxfp8_marker,
+ mxfp8_tensors,
+ nvfp4_signed_tensors,
+ quantize_scaled_fp8,
+)
+
+COMPUTE_DTYPE = torch.bfloat16
+HIDDEN = 128
+INTERMEDIATE = 256
+VOCAB = 32
+HEAD_DIM = 32
+
+# Every projection, as the official build packs them: (layer path in the file, [out, in]). The widths are whole
+# 128-row scale tiles, the smallest an nvfp4 layer can be.
+PROJECTIONS = {
+ "model.layers.0.self_attn.q_proj": (HIDDEN, HIDDEN),
+ "model.layers.0.self_attn.k_proj": (HIDDEN, HIDDEN),
+ "model.layers.0.self_attn.v_proj": (HIDDEN, HIDDEN),
+ "model.layers.0.self_attn.o_proj": (HIDDEN, HIDDEN),
+ "model.layers.0.mlp.gate_proj": (INTERMEDIATE, HIDDEN),
+ "model.layers.0.mlp.up_proj": (INTERMEDIATE, HIDDEN),
+ "model.layers.0.mlp.down_proj": (HIDDEN, INTERMEDIATE),
+}
+# A packed visual layer, added in the header case. The tower is dropped before anything reads it, so the layer is
+# neither installed nor reserved for.
+VISUAL = "model.visual.blocks.0.mlp.linear_fc1"
+# The bf16 the folded embedding and the norms (two per layer, q/k norms, the final one) are held in.
+DENSE_ELEMENTS = VOCAB * HIDDEN + 2 * HIDDEN + 2 * HEAD_DIM + HIDDEN
+
+SEAM = Seam(
+ loader=Qwen3VLEncoderCheckpointLoader,
+ module=krea2,
+ entry="_load_text_encoder",
+ compute_dtype=COMPUTE_DTYPE,
+ patches_device=True,
+ sets_torch_dtype=False,
+ # This entry calls `_apply_fp8_to_nn_module` itself, and the storage pass is part of what is tested.
+ casts_fp8_storage=False,
+)
+
+
+def _te_config() -> Qwen3VLConfig:
+ """Qwen3-VL at toy width: one text layer whose projections all fit nvfp4's tiles, and a one-block tower."""
+ return Qwen3VLConfig(
+ text_config={
+ "hidden_size": HIDDEN,
+ "intermediate_size": INTERMEDIATE,
+ "num_hidden_layers": 1,
+ "num_attention_heads": 4,
+ "num_key_value_heads": 4,
+ "head_dim": HEAD_DIM,
+ "vocab_size": VOCAB,
+ "rope_scaling": {"rope_type": "default", "mrope_section": [8, 4, 4], "mrope_interleaved": True},
+ },
+ vision_config={
+ "depth": 1,
+ "hidden_size": 64,
+ "intermediate_size": 128,
+ "num_heads": 2,
+ "out_hidden_size": HIDDEN,
+ "deepstack_visual_indexes": [],
+ },
+ )
+
+
+def _transformers_path(path: str) -> str:
+ """Where `Qwen3VLModel` holds a language-model layer the file spells `model.X`."""
+ return path.replace("model.", "language_model.", 1)
+
+
+def _packed_bytes(rows: int, columns: int) -> int:
+ return rows * columns // 2 + rows * (columns // 16) + 4
+
+
+def _dense_checkpoint() -> dict[str, torch.Tensor]:
+ """The toy model's own state dict in bf16, spelled the way a Comfy export spells it.
+
+ Starting from the real model is what makes every key the loader has to fill be there, and the norms carry
+ real values.
+ """
+ torch.manual_seed(0)
+ reference = Qwen3VLModel(_te_config()).state_dict()
+ return {
+ f"model.{key.removeprefix('language_model.')}": value.to(torch.bfloat16) for key, value in reference.items()
+ }
+
+
+def _checkpoint(naming: str) -> tuple[dict[str, torch.Tensor], dict[str, str] | None, dict[str, torch.Tensor]]:
+ """The official build's layout at toy width: (state dict, header, expected weight per transformers path)."""
+ state_dict = _dense_checkpoint()
+ header: dict[str, dict[str, str]] = {}
+ expected: dict[str, torch.Tensor] = {}
+ for path, (rows, columns) in PROJECTIONS.items():
+ del state_dict[f"{path}.weight"]
+ tensors, weight = nvfp4_signed_tensors(path, torch.randint(0, 2, (rows, columns), dtype=torch.bool))
+ state_dict.update(tensors)
+ expected[_transformers_path(path)] = weight
+ if naming == "marker":
+ state_dict[f"{path}.comfy_quant"] = comfy_quant_marker({"format": "nvfp4"})
+ else:
+ header[path] = {"format": "nvfp4"}
+ if naming == "header":
+ del state_dict[f"{VISUAL}.weight"]
+ tensors, _ = nvfp4_signed_tensors(VISUAL, torch.ones(128, 64, dtype=torch.bool))
+ state_dict.update(tensors)
+ header[VISUAL] = {"format": "nvfp4"}
+
+ # The official build's scaled fp8 embedding and LM head.
+ for path, payload in (
+ ("model.embed_tokens", quantize_scaled_fp8(torch.randn(VOCAB, HIDDEN))),
+ ("lm_head", quantize_scaled_fp8(torch.randn(VOCAB, HIDDEN))),
+ ):
+ state_dict[f"{path}.weight"] = payload.codes
+ state_dict[f"{path}.weight_scale"] = payload.scale
+ state_dict[f"{path}.comfy_quant"] = comfy_quant_marker(
+ {"format": "float8_e4m3fn", "full_precision_matrix_mult": False}
+ )
+ expected[f"{path}.dequantized"] = payload.dequantized
+ metadata = {"_quantization_metadata": json.dumps({"layers": header})} if header else None
+ return state_dict, metadata, expected
+
+
+def _prepare(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+ state_dict,
+ metadata,
+ *,
+ matmul: bool = False,
+ storage: bool = False,
+):
+ """The loader over a real file holding `state_dict` and `metadata`, so the header it reads is the file's own."""
+ path = tmp_path / "qwen3vl_8b_nvfp4.safetensors"
+ safetensors.torch.save_file({key: value.contiguous() for key, value in state_dict.items()}, path, metadata)
+ run = prepare(SEAM, monkeypatch, observe=("dequantize_fp8_scaled", "split_fp8_scaled_layers"))
+ run.loader._load_te_config = lambda _config: _te_config()
+ monkeypatch.setattr(krea2, "should_keep_fp8_weights", lambda _device: matmul)
+ monkeypatch.setattr(krea2, "_device_supports_fp8_storage", lambda *_args: storage)
+ return run, Qwen3VLEncoder_Checkpoint_Config.model_construct(path=str(path), name="encoder")
+
+
+def _logged(run) -> list[str]:
+ return [str(call.args[0]) for call in run.loader._logger.info.call_args_list]
+
+
+def _assert_packed(model: torch.nn.Module, path: str, weight: torch.Tensor) -> None:
+ module = model.get_submodule(_transformers_path(path))
+ assert isinstance(module, NVFP4Linear), path
+ assert module.weight.dtype is torch.uint8, path
+ assert module.weight_scale_2.dtype is torch.float32, path
+ # A float32 activation, not the compute dtype: CPU bf16 GEMM faults on part of the windows runner fleet.
+ # Every decoded weight is +-0.5, exact in either width.
+ x = torch.randn(3, module.in_features, dtype=torch.float32)
+ torch.testing.assert_close(module(x), torch.nn.functional.linear(x, weight))
+
+
[email protected]("mode", ["fold", "fp8_compute", "fp8_storage"])
[email protected]("naming", ["marker", "header"])
+def test_named_nvfp4_layers_stay_packed_beside_a_folded_embedding(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, naming: str, mode: str
+) -> None:
+ state_dict, metadata, expected = _checkpoint(naming)
+ run, config = _prepare(
+ monkeypatch, tmp_path, state_dict, metadata, matmul=mode == "fp8_compute", storage=mode == "fp8_storage"
+ )
+
+ model = run.load(config)
+
+ for path in PROJECTIONS:
+ _assert_packed(model, path, expected[_transformers_path(path)])
+
+ # Comfy's embedding is scaled fp8, and no matmul takes an embedding: it is folded with its scale. Under fp8
+ # storage it must stay folded -- cast again it would be re-quantized without the scale. With every Linear
+ # packed nothing else is left to cast, and the log must not claim otherwise.
+ embedding = model.language_model.embed_tokens.weight
+ assert embedding.dtype is COMPUTE_DTYPE
+ assert torch.equal(embedding, expected["model.embed_tokens.dequantized"].to(COMPUTE_DTYPE))
+ assert not any("FP8 layerwise casting enabled" in message for message in _logged(run))
+
+ # One reservation, before the fold and the split widen anything. Counted by hand: the packed layers as held,
+ # the folded embedding and the norms at bf16, and the embedding's scalar scale. The LM head is in none of it:
+ # this model has none, and folding it first would only be paid for and thrown away.
+ packed = sum(_packed_bytes(rows, columns) for rows, columns in PROJECTIONS.values())
+ assert run.reserved == [packed + DENSE_ELEMENTS * COMPUTE_DTYPE.itemsize + 4]
+ assert run.order and all(reserved == 1 for _step, reserved in run.order), run.order
+
+
[email protected]("marker", [{}, {"full_precision_matrix_mult": False}], ids=["empty", "format_less"])
+def test_a_header_named_layer_stays_packed_beside_a_marker_naming_no_format(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, marker: dict
+) -> None:
+ """A marker without a format says nothing about the layer, so the header's entry still names it nvfp4."""
+ state_dict, metadata, expected = _checkpoint("header")
+ layer = "model.layers.0.self_attn.q_proj"
+ state_dict[f"{layer}.comfy_quant"] = comfy_quant_marker(marker)
+ run, config = _prepare(monkeypatch, tmp_path, state_dict, metadata)
+
+ model = run.load(config)
+
+ for path in PROJECTIONS:
+ _assert_packed(model, path, expected[_transformers_path(path)])
+
+
[email protected]("head", ["scaled_fp8", "nvfp4"])
+def test_a_head_spelled_under_the_model_prefix_is_never_read(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, head: str
+) -> None:
+ """`model.lm_head` is remapped to `language_model.lm_head` like a bare `lm_head`, a module this model lacks.
+
+ Read, an nvfp4 head failed the install for naming no module, and a scaled fp8 one was folded and reserved for,
+ then discarded. The head is 128 rows here, the smallest an nvfp4 layer can be: never read, its shape is moot.
+ """
+ state_dict, metadata, _ = _checkpoint("marker")
+ for key in [key for key in state_dict if key.startswith("lm_head.")]:
+ payload = state_dict.pop(key)
+ if head == "scaled_fp8":
+ state_dict[f"model.{key}"] = payload
+ if head == "nvfp4":
+ tensors, _ = nvfp4_signed_tensors("model.lm_head", torch.ones(128, HIDDEN, dtype=torch.bool))
+ state_dict.update(tensors)
+ state_dict["model.lm_head.comfy_quant"] = comfy_quant_marker({"format": "nvfp4"})
+ run, config = _prepare(monkeypatch, tmp_path, state_dict, metadata)
+
+ run.load(config)
+
+ packed = sum(_packed_bytes(rows, columns) for rows, columns in PROJECTIONS.values())
+ assert run.reserved == [packed + DENSE_ELEMENTS * COMPUTE_DTYPE.itemsize + 4]
+
+
[email protected]("naming", ["marker", "header"])
+def test_an_int8_neighbour_leaves_the_nvfp4_layers_packed_and_reserved(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, naming: str
+) -> None:
+ """The int8 branch strips every marker it leaves, nvfp4's included, so the packed layers must be out first; and
+ its reservation is the only one, so it has to count them."""
+ state_dict, metadata, expected = _checkpoint(naming)
+ int8 = "model.layers.0.mlp.down_proj"
+ # An int8 file carries no scaled fp8 beside it: that branch refuses foreign float8 scales.
+ for path in ("model.embed_tokens", "lm_head"):
+ state_dict[f"{path}.weight"] = expected[f"{path}.dequantized"].to(torch.bfloat16)
+ del state_dict[f"{path}.weight_scale"], state_dict[f"{path}.comfy_quant"]
+ for suffix in (".weight", ".weight_scale", ".weight_scale_2", ".comfy_quant"):
+ state_dict.pop(f"{int8}{suffix}", None)
+ if metadata is not None:
+ header = json.loads(metadata["_quantization_metadata"])
+ del header["layers"][int8]
+ metadata = {"_quantization_metadata": json.dumps(header)}
+ codes = torch.randint(-127, 128, (HIDDEN, INTERMEDIATE), dtype=torch.int8)
+ scale = torch.rand(HIDDEN, 1) + 0.5
+ state_dict[f"{int8}.weight"] = codes
+ state_dict[f"{int8}.weight_scale"] = scale
+ state_dict[f"{int8}.comfy_quant"] = comfy_quant_marker({"format": "int8_tensorwise", "convrot": False})
+ run, config = _prepare(monkeypatch, tmp_path, state_dict, metadata)
+
+ model = run.load(config)
+
+ for path in PROJECTIONS:
+ if path != int8:
+ _assert_packed(model, path, expected[_transformers_path(path)])
+ int8_module = model.get_submodule(_transformers_path(int8))
+ assert isinstance(int8_module, Int8ConvrotLinear)
+ torch.testing.assert_close(
+ int8_module._dequantized_weight(torch.device("cpu"), torch.float32), codes.float() * scale
+ )
+
+ packed = sum(_packed_bytes(rows, columns) for path, (rows, columns) in PROJECTIONS.items() if path != int8)
+ held_int8 = HIDDEN * INTERMEDIATE + HIDDEN * scale.element_size()
+ assert run.reserved == [packed + held_int8 + DENSE_ELEMENTS * COMPUTE_DTYPE.itemsize]
+
+
+def test_an_mxfp8_build_keeps_its_language_model_in_fp8_storage(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ """Every MXFP8 Linear is folded -- `_scaled_mm` cannot apply a block-wise scale -- so its scaled layers reach the
+ storage-only pass, which must still hold them in fp8: only a folded *embedding* stays wide there. Kept at the
+ compute dtype instead, the language model would be resident at twice the size it had before."""
+ state_dict = _dense_checkpoint()
+ expected: dict[str, torch.Tensor] = {}
+ torch.manual_seed(1)
+ for path, (rows, columns) in PROJECTIONS.items():
+ # Exponent bytes around the bias: block scales from 0.5 to 4, exact in e4m3 as in bf16.
+ tensors, block_scales = mxfp8_tensors(path, torch.randint(126, 130, (rows, columns // MX_BLOCK_SIZE)))
+ state_dict.update(tensors)
+ state_dict[f"{path}.comfy_quant"] = comfy_quant_marker(mxfp8_marker())
+ expected[_transformers_path(path)] = block_scales.repeat_interleave(MX_BLOCK_SIZE, dim=1)
+ run, config = _prepare(monkeypatch, tmp_path, state_dict, None, storage=True)
+
+ model = run.load(config)
+
+ for path, weight in expected.items():
+ stored = model.get_submodule(path).weight
+ assert stored.dtype is torch.float8_e4m3fn, path
+ assert torch.equal(stored.float(), weight), path
+ assert any("FP8 layerwise casting enabled" in message for message in _logged(run))
+
+
+ ("mutate", "message"),
+ [
+ pytest.param(
+ lambda sd: sd.pop("model.layers.0.self_attn.q_proj.comfy_quant"),
+ "no ComfyUI `comfy_quant` marker",
+ id="unnamed",
+ ),
+ pytest.param(
+ lambda sd: sd.pop("model.layers.0.self_attn.q_proj.weight_scale_2"),
+ "no weight_scale_2",
+ id="no-global-scale",
+ ),
+ pytest.param(
+ lambda sd: sd.update({"model.layers.0.self_attn.q_proj.pre_quant_scale": torch.ones(HIDDEN)}),
+ "AWQ",
+ id="awq",
+ ),
+ ],
+)
+def test_a_layer_the_decode_would_misread_is_refused_before_the_loader_reserves_room(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, mutate, message: str
+) -> None:
+ state_dict, metadata, _ = _checkpoint("marker")
+ mutate(state_dict)
+ run, config = _prepare(monkeypatch, tmp_path, state_dict, metadata)
+
+ with pytest.raises(ValueError, match=message):
+ run.load(config)
+
+ assert run.reserved == []
diff --git a/tests/backend/model_manager/load/test_qwen3_vl_vision_encoder.py b/tests/backend/model_manager/load/test_qwen3_vl_vision_encoder.py
index 661d4671fb..0011625c4d 100644
--- a/tests/backend/model_manager/load/test_qwen3_vl_vision_encoder.py
+++ b/tests/backend/model_manager/load/test_qwen3_vl_vision_encoder.py
@@ -34,8 +34,10 @@ from invokeai.backend.model_manager.util.qwen3_vl import (
read_qwen3vl_visual_tower_tensors,
)
from invokeai.backend.quantization.int8_convrot import CONVROT_GROUP_SIZE, Int8ConvrotLinear, build_regular_hadamard
+from invokeai.backend.quantization.nvfp4 import NVFP4Linear
from invokeai.backend.qwen3_vl.qwen3_vl_assets import load_bundled_qwen3_vl_tokenizer
from tests.backend.model_manager.load.qwen3vl_gguf_fixture import tiny_qwen3vl_config
+from tests.fixtures.quantized_payloads import comfy_quant_marker, nvfp4_signed_tensors
_LOADERS = "invokeai.backend.model_manager.load.model_loaders.krea2"
@@ -79,8 +81,10 @@ def _loader(cls):
return loader
-def _single_file(path: Path, state_dict: dict[str, torch.Tensor], te_config) -> Qwen3VLEncoderCheckpointLoader:
- save_file({k: v.contiguous() for k, v in state_dict.items()}, str(path))
+def _single_file(
+ path: Path, state_dict: dict[str, torch.Tensor], te_config, metadata: dict[str, str] | None = None
+) -> Qwen3VLEncoderCheckpointLoader:
+ save_file({k: v.contiguous() for k, v in state_dict.items()}, str(path), metadata=metadata)
loader = _loader(Qwen3VLEncoderCheckpointLoader)
loader._load_te_config = lambda _config: te_config
return loader
@@ -165,6 +169,132 @@ def test_an_int8_tower_stays_int8(tmp_path: Path) -> None:
assert torch.equal(tower.blocks[1].attn.proj.weight, reference.visual.blocks[1].attn.proj.weight)
+# Tower Linears of the tiny config that are whole nvfp4 scale tiles (128 rows by 64 columns): one in a block, one
+# in the merger.
+_NVFP4_TOWER_LAYERS = ("blocks.0.mlp.linear_fc1", "merger.linear_fc1")
+
+
+def _nvfp4_tower_checkpoint(naming: str):
+ """A ComfyUI-layout file whose tower packs `_NVFP4_TOWER_LAYERS`, named in `.comfy_quant` markers or the header;
+ and the reference encoder, its Linears there set to the +-0.5 weights the packed codes stand for."""
+ reference = _tiny_encoder()
+ state_dict = {f"model.{k}": v for k, v in reference.state_dict().items()}
+ header: dict[str, dict[str, str]] = {}
+ generator = torch.Generator().manual_seed(1)
+ for layer in _NVFP4_TOWER_LAYERS:
+ path = f"model.visual.{layer}"
+ linear = reference.visual.get_submodule(layer)
+ tensors, weight = nvfp4_signed_tensors(path, torch.rand(linear.weight.shape, generator=generator) > 0.5)
+ del state_dict[f"{path}.weight"]
+ state_dict.update(tensors)
+ if naming == "marker":
+ state_dict[f"{path}.comfy_quant"] = comfy_quant_marker({"format": "nvfp4"})
+ else:
+ header[path] = {"format": "nvfp4"}
+ with torch.no_grad():
+ linear.weight.copy_(weight)
+ metadata = {"_quantization_metadata": json.dumps({"layers": header})} if header else None
+ return state_dict, metadata, reference
+
+
+def _packed_bytes(linear: torch.nn.Linear) -> int:
+ """An nvfp4 layer as held: two codes per byte, an e4m3 scale per 16 weights, a float32 global scale."""
+ rows, columns = linear.weight.shape
+ return rows * columns // 2 + rows * (columns // 16) + 4
+
+
+def _dense_elements(reference, *replaced_layers: str) -> int:
+ replaced = {f"{layer}.weight" for layer in replaced_layers}
+ return sum(t.nelement() for key, t in reference.visual.state_dict().items() if key not in replaced)
+
+
+def _reserved(loader) -> list[int]:
+ return [call.args[0] for call in loader._ram_cache.make_room.call_args_list]
+
+
[email protected]("naming", ["marker", "header"])
+def test_an_nvfp4_tower_stays_packed_and_is_reserved_as_held(tmp_path: Path, naming: str) -> None:
+ """A repack that packs the tower too. Read as plain Linears, its packed weights would lose their scales to the
+ fp8 extraction and fail the load on their halved width."""
+ state_dict, metadata, reference = _nvfp4_tower_checkpoint(naming)
+ path = tmp_path / "qwen3vl_nvfp4.safetensors"
+ loader = _single_file(path, state_dict, tiny_qwen3vl_config(), metadata)
+
+ tower = loader._load_model(_checkpoint_config(path), SubModelType.VisionEncoder)
+
+ for layer in _NVFP4_TOWER_LAYERS:
+ assert isinstance(tower.get_submodule(layer), NVFP4Linear), layer
+ # One image of 4x4 patches, flattened as the processor hands them to the tower.
+ vision = reference.visual.config
+ patches = torch.randn(16, vision.in_channels * vision.temporal_patch_size * vision.patch_size**2)
+ grid = torch.tensor([[1, 4, 4]])
+ with torch.no_grad():
+ torch.testing.assert_close(
+ tower(patches, grid_thw=grid).pooler_output, reference.visual(patches, grid_thw=grid).pooler_output
+ )
+ # One reservation: the rest at the compute dtype, the packed layers as held.
+ packed = sum(_packed_bytes(reference.visual.get_submodule(layer)) for layer in _NVFP4_TOWER_LAYERS)
+ dense = _dense_elements(reference, *_NVFP4_TOWER_LAYERS) * torch.float32.itemsize
+ assert _reserved(loader) == [dense + packed]
+
+
+def test_an_int8_neighbour_leaves_the_nvfp4_tower_layers_packed_and_reserved(tmp_path: Path) -> None:
+ """An int8 layer sends the tower down the int8 branch, whose reservation is its only one, so it has to count the
+ packed layers that left the state dict."""
+ state_dict, metadata, reference = _nvfp4_tower_checkpoint("marker")
+ int8 = "blocks.1.attn.proj"
+ rows, columns = reference.visual.get_submodule(int8).weight.shape
+ codes = torch.randint(-127, 128, (rows, columns), dtype=torch.int8, generator=torch.Generator().manual_seed(2))
+ scale = torch.rand(rows, 1, generator=torch.Generator().manual_seed(3)) + 0.5
+ state_dict[f"model.visual.{int8}.weight"] = codes
+ state_dict[f"model.visual.{int8}.weight_scale"] = scale
+ state_dict[f"model.visual.{int8}.comfy_quant"] = comfy_quant_marker({"format": "int8_tensorwise", "convrot": False})
+ path = tmp_path / "qwen3vl_int8_nvfp4.safetensors"
+ loader = _single_file(path, state_dict, tiny_qwen3vl_config(), metadata)
+
+ tower = loader._load_model(_checkpoint_config(path), SubModelType.VisionEncoder)
+
+ for layer in _NVFP4_TOWER_LAYERS:
+ assert isinstance(tower.get_submodule(layer), NVFP4Linear), layer
+ int8_module = tower.get_submodule(int8)
+ assert isinstance(int8_module, Int8ConvrotLinear)
+ torch.testing.assert_close(
+ int8_module._dequantized_weight(torch.device("cpu"), torch.float32), codes.float() * scale
+ )
+ packed = sum(_packed_bytes(reference.visual.get_submodule(layer)) for layer in _NVFP4_TOWER_LAYERS)
+ held_int8 = codes.nelement() + scale.nelement() * scale.element_size()
+ dense = _dense_elements(reference, *_NVFP4_TOWER_LAYERS, int8) * torch.float32.itemsize
+ assert _reserved(loader) == [dense + held_int8 + packed]
+
+
+_FIRST_PACKED = f"model.visual.{_NVFP4_TOWER_LAYERS[0]}"
+
+
+ ("mutate", "reason"),
+ [
+ pytest.param(
+ lambda sd: sd.pop(f"{_FIRST_PACKED}.comfy_quant"), "no ComfyUI `comfy_quant` marker", id="unnamed"
+ ),
+ pytest.param(lambda sd: sd.pop(f"{_FIRST_PACKED}.weight_scale_2"), "no weight_scale_2", id="no-global-scale"),
+ pytest.param(lambda sd: sd.update({f"{_FIRST_PACKED}.pre_quant_scale": torch.ones(64)}), "AWQ", id="awq"),
+ ],
+)
+def test_an_undecodable_nvfp4_tower_layer_is_refused_as_the_vision_tower(tmp_path: Path, mutate, reason: str) -> None:
+ """Identification ignores the tower, so that it never blocks text-only use; the refusal comes at this load, and
+ has to say which part of the encoder failed and what it is needed for."""
+ state_dict, metadata, _ = _nvfp4_tower_checkpoint("marker")
+ mutate(state_dict)
+ path = tmp_path / "qwen3vl_nvfp4.safetensors"
+ loader = _single_file(path, state_dict, tiny_qwen3vl_config(), metadata)
+
+ with pytest.raises(ValueError, match="Qwen3-VL vision tower, which Krea-2 edit needs for reference images") as e:
+ loader._load_model(_checkpoint_config(path), SubModelType.VisionEncoder)
+
+ assert reason in str(e.value)
+ assert _reserved(loader) == []
+
+
def test_a_file_without_a_tower_is_refused(tmp_path: Path) -> None:
reference = _tiny_encoder()
language_only = {k: v for k, v in reference.state_dict().items() if not k.startswith("visual.")}
diff --git a/tests/backend/model_manager/load/test_qwen3_vl_visual_tower.py b/tests/backend/model_manager/load/test_qwen3_vl_visual_tower.py
index fa6c34213f..30214df6e9 100644
--- a/tests/backend/model_manager/load/test_qwen3_vl_visual_tower.py
+++ b/tests/backend/model_manager/load/test_qwen3_vl_visual_tower.py
@@ -30,6 +30,7 @@ from invokeai.backend.model_manager.load.model_loaders.krea2 import (
)
from invokeai.backend.model_manager.taxonomy import Qwen3VLVariantType, SubModelType
from invokeai.backend.model_manager.util.qwen3_vl import (
+ drop_qwen3vl_unloaded_keys,
drop_qwen3vl_visual_tower,
drop_qwen3vl_visual_tower_keys,
)
@@ -78,6 +79,29 @@ def test_non_string_keys_survive() -> None:
assert drop_qwen3vl_visual_tower_keys({0: "t"}) == {0: "t"}
+ "key",
+ [
+ "model.visual.blocks.0.attn.qkv.weight",
+ "lm_head.weight",
+ "lm_head.weight_scale",
+ # The remap routes these to `language_model.lm_head`, as it does a bare `lm_head`.
+ "model.lm_head.weight",
+ "model.lm_head.comfy_quant",
+ "model.language_model.lm_head.weight",
+ ],
+)
+def test_the_tower_and_every_lm_head_spelling_are_dropped(key: str) -> None:
+ assert drop_qwen3vl_unloaded_keys({key: "t", "model.embed_tokens.weight": "e"}) == {
+ "model.embed_tokens.weight": "e"
+ }
+
+
[email protected]("key", ["model.layers.0.self_attn.q_proj.weight", "model.norm.weight", "lm_head_bias", 0])
+def test_what_the_single_file_loader_reads_survives(key) -> None:
+ assert drop_qwen3vl_unloaded_keys({key: "t"}) == {key: "t"}
+
+
def test_a_model_without_a_tower_is_refused_rather_than_given_a_dead_attribute(tmp_path: Path) -> None:
"""`setattr` would happily invent `visual` on anything. On the `from_pretrained` paths nothing
else would notice a renamed tower: it would load, a dead stub would sit beside it, and the
diff --git a/tests/backend/model_manager/load/test_qwen_image_nvfp4_loader.py b/tests/backend/model_manager/load/test_qwen_image_nvfp4_loader.py
index fa461b027f..4dde6e2f88 100644
--- a/tests/backend/model_manager/load/test_qwen_image_nvfp4_loader.py
+++ b/tests/backend/model_manager/load/test_qwen_image_nvfp4_loader.py
@@ -325,7 +325,7 @@ def test_an_nvfp4_layer_missing_its_global_scale_is_refused_before_the_cache_is_
"""The degraded half-state, at the seam rather than at the detector.
A packed uint8 weight with a block-scale grid and no `weight_scale_2` is the shape a guard keyed
- on `weight_scale_2` -- what the decode keys on -- lets straight through. `_find_nvfp4_layers`
+ on `weight_scale_2` -- what the decode keys on -- lets straight through. `find_nvfp4_layers`
refuses it, and `test_nvfp4.py` pins that; what only a seam can answer is whether this loader
still reaches the detector *before* it asks the cache for room, which nothing but the order of
those two statements secures.
diff --git a/tests/backend/model_manager/load/test_scaled_fp8_fold_axis.py b/tests/backend/model_manager/load/test_scaled_fp8_fold_axis.py
index 20a997ac9d..e82b77d463 100644
--- a/tests/backend/model_manager/load/test_scaled_fp8_fold_axis.py
+++ b/tests/backend/model_manager/load/test_scaled_fp8_fold_axis.py
@@ -201,7 +201,7 @@ class TestSharedComfyFold:
def test_an_nvfp4_layer_missing_its_global_scale_is_refused_too(self) -> None:
"""The half-state: packed codes and a block-scale grid, no `weight_scale_2`. It is the shape
- `_find_nvfp4_layers` refuses by name, so a build that loses the global scale somewhere
+ `find_nvfp4_layers` refuses by name, so a build that loses the global scale somewhere
upstream arrives here looking like ordinary scaled fp8 -- and the fold takes it exactly as
readily as the whole layer, for the same reason and to the same end. Keying the guard on
`weight_scale_2` alone, which is what the decode keys on, would let this one through."""
diff --git a/tests/backend/model_manager/load/test_z_image_loader_boundaries.py b/tests/backend/model_manager/load/test_z_image_loader_boundaries.py
index 7f83938ad2..2de7454d84 100644
--- a/tests/backend/model_manager/load/test_z_image_loader_boundaries.py
+++ b/tests/backend/model_manager/load/test_z_image_loader_boundaries.py
@@ -422,7 +422,7 @@ def test_an_nvfp4_layer_missing_its_global_scale_is_refused_before_the_cache_is_
"""The degraded half-state, at this seam rather than at the detector.
A packed uint8 weight with a block-scale grid and no `weight_scale_2` is the shape a guard keyed
- on `weight_scale_2` -- the key the decode keys on -- lets straight through. `_find_nvfp4_layers`
+ on `weight_scale_2` -- the key the decode keys on -- lets straight through. `find_nvfp4_layers`
refuses it and `test_nvfp4.py` pins that; what only a seam can answer is whether this loader
reaches the detector before it asks the cache for room, which nothing but the order of those two
statements secures.
diff --git a/tests/backend/quantization/test_fp8_scaled.py b/tests/backend/quantization/test_fp8_scaled.py
index 606d81e18c..15ed5cad8d 100644
--- a/tests/backend/quantization/test_fp8_scaled.py
+++ b/tests/backend/quantization/test_fp8_scaled.py
@@ -6,6 +6,7 @@ from unittest import mock
import pytest
import torch
+from invokeai.backend.quantization import fp8_scaled
from invokeai.backend.quantization.block_scale_tiles import unblock_scale_grid
from invokeai.backend.quantization.fp8_scaled import (
FP8_DTYPE,
@@ -862,6 +863,107 @@ class TestE5m2ScaleRecovery:
assert torch.allclose(sd["lin.weight"].float(), torch.full((4, 4), 0.5))
+class TestFoldInSlabs:
+ """A tensor larger than a slab is folded a slab of rows at a time, and must come out as the whole fold would.
+
+ The expectations are the definition -- float32 product, one rounding to the target dtype -- with each weight
+ element's scale picked out by index rather than by the expansion the fold uses. The slab is shrunk so a 39-row
+ weight splits into slabs of two rows and an odd one at the end: the boundaries a row-indexing mistake would
+ show at, and, against three-row scale blocks, slabs that start inside a block.
+ """
+
+ @staticmethod
+ def _codes(shape: tuple[int, ...], contiguous: bool) -> torch.Tensor:
+ if contiguous:
+ return torch.randn(shape).to(FP8_DTYPE)
+ if len(shape) == 1:
+ return torch.randn(2 * shape[0]).to(FP8_DTYPE)[::2]
+ # A transposed buffer, so each slab is a strided row slice.
+ return torch.randn(shape[::-1]).to(FP8_DTYPE).permute(*reversed(range(len(shape))))
+
+ @staticmethod
+ def _per_element(scale: torch.Tensor, shape: torch.Size) -> torch.Tensor:
+ """Each weight element's scale: along every axis the scale has, element ``i`` reads block ``i // size``."""
+ for dim in range(scale.dim()):
+ scale = scale.index_select(dim, torch.arange(shape[dim]) // (shape[dim] // scale.shape[dim]))
+ return scale.reshape(*scale.shape, *[1] * (len(shape) - scale.dim()))
+
+ @pytest.mark.parametrize(
+ ("shape", "scale_shape"),
+ [
+ pytest.param((39, 48), (), id="per_tensor"),
+ pytest.param((39, 48), (39,), id="per_row"),
+ pytest.param((39, 48), (39, 3), id="column_blocks"),
+ pytest.param((39, 48), (13, 3), id="row_and_column_blocks"),
+ pytest.param((39, 48), (1, 3), id="one_scale_row"),
+ pytest.param((300,), (300,), id="1d"),
+ pytest.param((39, 4, 2, 3), (39,), id="4d_per_row"),
+ pytest.param((39, 4, 2, 3), (13, 2, 2, 3), id="4d_blocks"),
+ ],
+ )
+ @pytest.mark.parametrize("contiguous", [True, False], ids=["contiguous", "strided"])
+ def test_slabs_fold_exactly_as_the_whole(
+ self, monkeypatch: pytest.MonkeyPatch, shape: tuple[int, ...], scale_shape: tuple[int, ...], contiguous: bool
+ ) -> None:
+ monkeypatch.setattr(fp8_scaled, "_FOLD_SLAB_ELEMENTS", 100)
+ torch.manual_seed(0)
+ codes = self._codes(shape, contiguous)
+ scale = torch.rand(scale_shape) + 0.5
+ sd = {"lin.weight": codes}
+
+ dequantize_fp8_scaled(sd, {"lin": Fp8ScaledLayer(weight_scale=scale)}, torch.bfloat16)
+
+ expected = (codes.float() * self._per_element(scale, codes.shape)).to(torch.bfloat16)
+ assert torch.equal(sd["lin.weight"], expected)
+
+ def test_an_mxfp8_layer_folds_exactly_as_the_whole(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ """Through the real decode: slabs of seven rows run across the 32-row tiles the grid is stored in."""
+ monkeypatch.setattr(fp8_scaled, "_FOLD_SLAB_ELEMENTS", 7 * 128)
+ torch.manual_seed(0)
+ sd, decoded = mxfp8_tensors("lin", torch.randint(124, 131, (128, 4)))
+ sd["lin.weight"] = codes = torch.randn(128, 4 * MX_BLOCK_SIZE).to(FP8_DTYPE)
+
+ dequantize_fp8_scaled(sd, extract_fp8_scaled_layers(sd, layer_hints={"lin": mxfp8_marker()}), torch.bfloat16)
+
+ expected = (codes.float() * self._per_element(decoded, codes.shape)).to(torch.bfloat16)
+ assert torch.equal(sd["lin.weight"], expected)
+
+ @pytest.mark.parametrize(
+ "scale",
+ [
+ pytest.param(torch.tensor(0.37), id="per_tensor"),
+ pytest.param(torch.rand(256) + 0.5, id="per_row"),
+ pytest.param(torch.rand(16, 4) + 0.5, id="row_and_column_blocks"),
+ ],
+ )
+ def test_nothing_the_size_of_the_weight_is_held_in_float32(
+ self, monkeypatch: pytest.MonkeyPatch, scale: torch.Tensor
+ ) -> None:
+ """The point of the slabs: the largest allocation is the result itself.
+
+ Folded whole, the weight's float32 copy and product are each twice the size of the bf16 result; so is a
+ block-wise scale expanded whole before the slabs start, which bounded nothing for those layouts. Measured
+ with the profiler's per-op allocation record, which sees every one of them.
+ """
+ from torch.profiler import ProfilerActivity, profile
+
+ monkeypatch.setattr(fp8_scaled, "_FOLD_SLAB_ELEMENTS", 8 * 512)
+ sd = {"lin.weight": torch.randn(256, 512).to(FP8_DTYPE)}
+ result_bytes = 256 * 512 * torch.bfloat16.itemsize
+
+ with profile(activities=[ProfilerActivity.CPU], profile_memory=True) as profiler:
+ dequantize_fp8_scaled(sd, {"lin": Fp8ScaledLayer(weight_scale=scale)}, torch.bfloat16)
+
+ assert max(event.cpu_memory_usage for event in profiler.events()) == result_bytes
+
+ def test_a_block_scale_that_does_not_tile_the_rows_names_the_layer(self) -> None:
+ # Left to the multiply: "The size of tensor a (39) must match the size of tensor b (36)", naming nothing.
+ sd = {"blocks.0.lin.weight": torch.randn(39, 48).to(FP8_DTYPE)}
+
+ with pytest.raises(ValueError, match=r"blocks\.0\.lin: a \(12, 3\) block-wise weight_scale"):
+ dequantize_fp8_scaled(sd, {"blocks.0.lin": Fp8ScaledLayer(weight_scale=torch.ones(12, 3))})
+
+
class TestBlockWiseScale:
"""A 2-D ``weight_scale`` has one entry per *block* of weight elements, not per row."""
diff --git a/tests/backend/quantization/test_nvfp4.py b/tests/backend/quantization/test_nvfp4.py
index 863ab4aaa3..afe8fa2354 100644
--- a/tests/backend/quantization/test_nvfp4.py
+++ b/tests/backend/quantization/test_nvfp4.py
@@ -25,6 +25,7 @@ from invokeai.backend.quantization.dequantizing_linear import peak_dequant_trans
from invokeai.backend.quantization.nvfp4 import (
NVFP4Linear,
dequantize_nvfp4_weight,
+ find_nvfp4_layers,
install_nvfp4_layers,
pop_nvfp4_layers,
predict_nvfp4_install_size,
@@ -178,6 +179,31 @@ def test_a_layer_nothing_names_as_nvfp4_is_refused_rather_than_read_by_comfy_con
assert "layer.weight" in sd
[email protected]("marker", [{}, {"full_precision_matrix_mult": False}], ids=["empty", "format_less"])
[email protected]("source", ["tensor", "markers"])
+def test_a_marker_naming_no_format_does_not_name_a_packed_layer(marker: dict, source: str) -> None:
+ """Only a marker or header entry whose format is nvfp4 names a layer; a marker's presence alone says nothing.
+ Identification passes the file's markers as `markers`, its meta marker tensors having no bytes to parse."""
+ sd = _zero_layer("layer")
+ if source == "tensor":
+ sd["layer.comfy_quant"] = comfy_quant_marker(marker)
+ kwargs = {}
+ else:
+ sd["layer.comfy_quant"] = torch.empty(0, dtype=torch.uint8, device="meta")
+ kwargs = {"markers": {"layer": marker}}
+
+ with pytest.raises(ValueError, match="laid out like nvfp4 that no ComfyUI"):
+ find_nvfp4_layers(sd, None, **kwargs)
+ assert find_nvfp4_layers(sd, {"layer": {"format": "nvfp4"}}, **kwargs) == ["layer"]
+
+
+def test_markers_passed_in_stand_for_the_marker_tensors() -> None:
+ sd = _zero_layer("layer")
+ sd["layer.comfy_quant"] = torch.empty(0, dtype=torch.uint8, device="meta")
+
+ assert find_nvfp4_layers(sd, None, markers={"layer": {"format": "nvfp4"}}) == ["layer"]
+
+
def test_an_awq_checkpoint_is_refused_before_anything_is_taken_out() -> None:
sd = {**_zero_layer("layer"), "layer.pre_quant_scale": torch.ones(64)}