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(quantization): load Comfy nvfp4 checkpoints

Alexander Eichhorn90203522e106
diff --git a/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.py b/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.py
index d751a209e6..499014e0d8 100644
--- a/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.py
+++ b/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.py
@@ -56,6 +56,7 @@ from invokeai.backend.quantization.fp8_scaled import (
)
from invokeai.backend.quantization.gguf.ggml_tensor import GGMLTensor
from invokeai.backend.quantization.gguf.loaders import gguf_sd_loader
+from invokeai.backend.quantization.nvfp4 import dequantize_nvfp4_layers
from invokeai.backend.util.devices import TorchDevice
from invokeai.backend.util.logging import InvokeAILogger
@@ -369,7 +370,10 @@ def _warn_if_40_layer_mistral(variant: MistralVariantType, logger: Any) -> None:
def _drop_quantization_metadata(sd: dict[str, Any], logger, target_dtype: torch.dtype | None = None) -> dict[str, Any]:
- """Dequantize Comfy-Org-style FP8/FP4 weights and drop their metadata keys.
+ """Dequantize Comfy-Org-style scaled FP8 weights and drop their metadata keys.
+
+ nvfp4 layers must be decoded before this runs (see ``_load_text_encoder``): their block scales pair
+ with a ``.weight`` just like an fp8 scale, and the fold below would stretch them over the packed weight.
Comfy-Org's Mistral FLUX.2 redistributions store quantized weights alongside
``*.weight_scale`` (and occasionally ``*.input_scale``) tensors. We apply the
@@ -944,6 +948,17 @@ class MistralEncoderCheckpointLoader(ModelLoader):
sd = load_file(model_path)
sd = _strip_known_prefixes(sd)
+ # Comfy's fp4_mixed build keeps most projections in nvfp4 beside scaled fp8. Decode those first:
+ # the keep-fp8 branch below pops every `weight_scale` and discards the ones whose weight is not
+ # float8, nvfp4's block scales included, and the dequantizing branch would stretch them over the
+ # packed weight.
+ nvfp4_layers = dequantize_nvfp4_layers(sd, model_dtype, reserve=self._ram_cache.make_room)
+ if nvfp4_layers:
+ logger.info(
+ f"Mistral encoder: decoded {nvfp4_layers} nvfp4 layer(s) to {model_dtype}. They are not kept packed, "
+ "so the encoder needs as much memory as its bf16 build."
+ )
+
# These redistributions are ComfyUI 'scaled fp8': an fp8 weight plus a `weight_scale`.
# Folding the scale doubles the encoder -- 16.8 GiB on disk becomes 32.3 GiB in bf16, which
# does not fit on a 24 GB card even on its own. Keeping the weights quantized is therefore
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 d008478129..980e37dcc7 100644
--- a/invokeai/backend/model_manager/load/model_loaders/z_image.py
+++ b/invokeai/backend/model_manager/load/model_loaders/z_image.py
@@ -68,6 +68,7 @@ from invokeai.backend.quantization.int8_convrot import (
split_int8_convrot_layers,
swap_in_int8_linears,
)
+from invokeai.backend.quantization.nvfp4 import dequantize_nvfp4_layers
from invokeai.backend.quantization.sdnq.detection import is_sdnq_folder
from invokeai.backend.quantization.sdnq.loaders import raise_on_incomplete_sdnq_load, sdnq_sd_loader
from invokeai.backend.qwen3.qwen3_tokenizer import load_bundled_qwen3_tokenizer
@@ -481,6 +482,20 @@ class ZImageCheckpointModel(ModelLoader):
stripped_sd[key] = value
sd = stripped_sd
+ # Determine safe dtype based on target device capabilities
+ target_device = TorchDevice.choose_torch_device()
+ model_dtype = TorchDevice.choose_bfloat16_safe_dtype(target_device)
+
+ # Before anything below reads the quantization side channel: the scaled-fp8 extraction pops every
+ # `weight_scale` and drops the ones whose weight is not float8, nvfp4's block scales included, and
+ # the fused-QKV split has no destination for `weight_scale_2`.
+ nvfp4_layers = dequantize_nvfp4_layers(sd, model_dtype, reserve=self._ram_cache.make_room)
+ if nvfp4_layers:
+ self._logger.info(
+ f"Z-Image: decoded {nvfp4_layers} nvfp4 layer(s) to {model_dtype}. They are not kept packed, so the "
+ "model needs as much memory as its bf16 build."
+ )
+
# Per-layer `full_precision_matrix_mult` hints, from the safetensors header and/or the
# per-tensor `.comfy_quant` markers. The header names layers in the checkpoint's own scheme,
# so it is remapped below; the markers ride along through the key conversion instead.
@@ -522,10 +537,6 @@ class ZImageCheckpointModel(ModelLoader):
axes_lens=[1024, 512, 512],
)
- # Determine safe dtype based on target device capabilities
- target_device = TorchDevice.choose_torch_device()
- model_dtype = TorchDevice.choose_bfloat16_safe_dtype(target_device)
-
# Filter out keys that don't belong to the ZImageTransformer2DModel.
# Merged checkpoints (e.g. LoRA-baked models) may bundle text encoder weights
# (text_encoders.*) or other non-transformer keys alongside the transformer weights.
diff --git a/invokeai/backend/model_manager/starter_models/common.py b/invokeai/backend/model_manager/starter_models/common.py
index 161f6707ac..7c17e199d8 100644
--- a/invokeai/backend/model_manager/starter_models/common.py
+++ b/invokeai/backend/model_manager/starter_models/common.py
@@ -263,7 +263,7 @@ flux2_dev_comfy_mistral_fp4 = StarterModel(
name="FLUX.2 [dev] Mistral Encoder (Comfy FP4 mixed)",
base=BaseModelType.Any,
source="https://huggingface.co/Comfy-Org/flux2-dev/resolve/main/split_files/text_encoders/mistral_3_small_flux2_fp4_mixed.safetensors",
- description="Comfy-Org FP4-mixed of BFL's 30-layer cow-mistral3-small. Smallest safetensors variant; embeds Tekken tokenizer. ~12.3GB",
+ description="Comfy-Org FP4-mixed of BFL's 30-layer cow-mistral3-small; embeds Tekken tokenizer. Smallest download, but loads at BF16 size. ~12.3GB",
type=ModelType.MistralEncoder,
)
diff --git a/invokeai/backend/quantization/nvfp4.py b/invokeai/backend/quantization/nvfp4.py
new file mode 100644
index 0000000000..b7ab8f7381
--- /dev/null
+++ b/invokeai/backend/quantization/nvfp4.py
@@ -0,0 +1,206 @@
+"""Load-time support for Comfy "nvfp4" quantized linears.
+
+``nvfp4`` is a ComfyUI-wide scheme, not one architecture's format: Comfy-Org ships it for Z-Image,
+Krea-2, Qwen-Image, the FLUX.2 Mistral encoder and more, often beside scaled fp8 and plain bf16 in the
+same file. It therefore lives next to ``fp8_scaled`` and ``int8_convrot`` rather than in an
+architecture package.
+
+A quantized linear ``[out, in]`` is stored as:
+
+- ``<layer>.weight``: uint8 ``[out, in/2]``, two 4-bit E2M1 codes per byte. Element ``2j`` is the
+ *upper* nibble; reading the lower one first decodes to noise.
+- ``<layer>.weight_scale``: float8_e4m3fn ``[out, in/16]``, one scale per 16-element block, in NVIDIA's
+ cuBLAS block-scale layout rather than row by row (see :func:`unblock_scale_grid`).
+- ``<layer>.weight_scale_2``: a float32 scalar, multiplied in:
+ ``W = E2M1[codes] * block_scale * weight_scale_2``.
+- optionally ``<layer>.input_scale``, an activation scale for fp4 compute, and a ``.comfy_quant``
+ marker. Some producers name their layers in the ``_quantization_metadata`` header instead; detection
+ here is structural -- a ``weight_scale_2`` beside the weight -- so it needs neither.
+
+These facts were established against real checkpoints, not a specification: decoding every nvfp4
+tensor of the Mistral FLUX.2 encoder and Z-Image Turbo builds reaches cosine 0.995 against the bf16
+build in the same repository, the floor of 4-bit block quantization. Reading the scale grid row by row
+instead still loads without an error and reaches 0.68-0.95 -- a model that runs and follows its
+conditioning slightly worse. That silence is why tests pin the layout against the measured index
+formula and against a slice of a real checkpoint.
+
+The weights are dequantized to the compute dtype at load, so an nvfp4 checkpoint loads correctly but
+occupies as much memory as its bf16 build. AWQ builds (``pre_quant_scale``) are refused: their input
+channels were rescaled before quantization, so a plain decode would produce wrong weights.
+"""
+
+from collections.abc import Callable
+from typing import Any
+
+import torch
+import torch.nn.functional as F
+
+from invokeai.backend.quantization.fp8_scaled import COMFY_QUANT_SUFFIX, INPUT_SCALE_SUFFIXES, iter_weight_scale_pairs
+from invokeai.backend.quantization.int8_convrot import parse_comfy_quant_marker
+
+NVFP4_FORMAT = "nvfp4"
+NVFP4_BLOCK_SIZE = 16
+
+WEIGHT_SCALE_2_SUFFIX = ".weight_scale_2"
+PRE_QUANT_SCALE_SUFFIX = ".pre_quant_scale"
+
+# What a decoded layer no longer needs besides its weight.
+_SIDE_CHANNEL_SUFFIXES = (".weight_scale", WEIGHT_SCALE_2_SUFFIX, COMFY_QUANT_SUFFIX, *INPUT_SCALE_SUFFIXES)
+
+# cuBLAS block-scale tiles span 128 rows and 4 blocks.
+_TILE_ROWS = 128
+_TILE_BLOCKS = 4
+
+_E2M1_VALUES = torch.tensor([0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0, -0.0, -0.5, -1.0, -1.5, -2.0, -3.0, -4.0, -6.0])
+# Both decoded elements of every possible byte, upper nibble first: one lookup per byte.
+_E2M1_BYTE_PAIRS = torch.stack([_E2M1_VALUES[torch.arange(256) >> 4], _E2M1_VALUES[torch.arange(256) & 0x0F]], dim=1)
+
+
+def _check_tile_layout(rows: int, blocks: int) -> None:
+ if rows % _TILE_ROWS or blocks % _TILE_BLOCKS:
+ raise ValueError(
+ f"a {rows}x{blocks} block-scale grid is not in the cuBLAS tile layout: rows must be a multiple of "
+ f"{_TILE_ROWS} and blocks a multiple of {_TILE_BLOCKS}. Padded grids are not implemented."
+ )
+
+
+def unblock_scale_grid(scale: torch.Tensor) -> torch.Tensor:
+ """Reorder a block-scale grid from cuBLAS's tiled layout into row-major ``[rows, blocks]``.
+
+ cuBLAS and TensorRT take block-scale operands tiled: the grid is cut into tiles of 128 rows and 4
+ blocks, the tiles are stored in row-major order, and inside a tile the entries run over
+ ``row % 32``, then ``row // 32``, then the block. Producers write that layout into a tensor of the
+ row-major shape, so nothing about the shape gives it away. It is a permutation, and inverting it is
+ a reshape: stored ``(tile row, tile column, row % 32, row // 32, block)`` becomes
+ ``(tile row, row // 32, row % 32, tile column, block)``.
+
+ The MXFP8 scales ``fp8_scaled._reject_mx_scale`` refuses are stored reordered too; whether in these
+ tiles, with their 32-element blocks, has not been measured.
+ """
+ if scale.dim() != 2:
+ raise ValueError(f"expected a 2-D block-scale grid, got shape {tuple(scale.shape)}")
+ rows, blocks = scale.shape
+ _check_tile_layout(rows, blocks)
+ tiles = scale.reshape(rows // _TILE_ROWS, blocks // _TILE_BLOCKS, 32, 4, _TILE_BLOCKS)
+ return tiles.permute(0, 3, 2, 1, 4).reshape(rows, blocks)
+
+
+def _check_layout(weight: torch.Tensor | None, weight_scale: torch.Tensor | None, weight_scale_2: torch.Tensor) -> None:
+ """Refuse tensors this decode would misread. Reads dtypes and shapes only."""
+ if weight is None or weight_scale is None:
+ raise ValueError(f"has a weight_scale_2 but no {'weight' if weight is None else 'weight_scale'}")
+ if weight.dtype is not torch.uint8 or weight.dim() != 2:
+ raise ValueError(f"expected a packed uint8 [out, in/2] weight, got {weight.dtype} {tuple(weight.shape)}")
+ if weight_scale.dtype is not torch.float8_e4m3fn or weight_scale.dim() != 2:
+ raise ValueError(
+ f"expected a float8_e4m3fn [out, in/16] block scale, got {weight_scale.dtype} {tuple(weight_scale.shape)}"
+ )
+ if weight_scale_2.numel() != 1:
+ raise ValueError(f"expected a scalar weight_scale_2, got shape {tuple(weight_scale_2.shape)}")
+ out_features, packed_width = weight.shape
+ rows, blocks = weight_scale.shape
+ if rows != out_features or packed_width * 2 != blocks * NVFP4_BLOCK_SIZE:
+ raise ValueError(
+ f"a {tuple(weight_scale.shape)} block scale does not describe a {tuple(weight.shape)} packed weight "
+ f"({NVFP4_BLOCK_SIZE}-element blocks, two elements per byte)"
+ )
+ _check_tile_layout(rows, blocks)
+
+
+def dequantize_nvfp4_weight(
+ weight: torch.Tensor, weight_scale: torch.Tensor, weight_scale_2: torch.Tensor, dtype: torch.dtype
+) -> torch.Tensor:
+ """Decode one nvfp4 weight to ``[out, in]`` in ``dtype``, on the weight's device.
+
+ Decodes in ``dtype`` directly. The E2M1 values and the e4m3 block scales are exact in bf16, and the
+ rounding the float32 global scale introduces is far below the 4-bit quantization error. That keeps
+ the transient at the result plus an int32 byte index, two bytes per weight element each, instead of
+ adding a float32 copy on top.
+ """
+ _check_layout(weight, weight_scale, weight_scale_2)
+ out_features, blocks = weight_scale.shape
+ device = weight.device
+ global_scale = weight_scale_2.to(device=device, dtype=torch.float32).reshape(())
+ grid = unblock_scale_grid(weight_scale.to(device=device, dtype=torch.float32)) * global_scale
+ values = F.embedding(weight.to(torch.int32), _E2M1_BYTE_PAIRS.to(device=device, dtype=dtype))
+ values = values.view(out_features, blocks, NVFP4_BLOCK_SIZE).mul_(grid.to(dtype).unsqueeze(-1))
+ return values.view(out_features, blocks * NVFP4_BLOCK_SIZE)
+
+
+def dequantize_nvfp4_layers(
+ sd: dict[str, Any], dtype: torch.dtype, reserve: Callable[[int], object] | None = None
+) -> int:
+ """Decode every nvfp4 layer in ``sd`` to ``dtype`` in place, drop its side channel, return the count.
+
+ Call it before any fp8 handling. The scaled-fp8 extraction pops every ``weight_scale`` in the file
+ and discards those whose weight is not float8 -- nvfp4's block scales included -- and the folds that
+ multiply a scale in would stretch the ``[out, in/16]`` grid over the packed ``[out, in/2]`` weight.
+ Decided per layer, never per file: the same checkpoints mix nvfp4 with scaled fp8, whose weights,
+ scales and markers are left for that path.
+
+ Nothing is widened until everything has been checked: AWQ layers, packed weights with a
+ ``weight_scale`` but no ``weight_scale_2``, markers that contradict their tensors and malformed
+ layers are refused first, naming the layer. Then ``reserve`` -- a loader's ``make_room`` -- is called
+ once with the size ``sd`` will have after decoding. The model cache reserves only the file size
+ before a load and decoding more than triples it, so reserving afterwards would let the peak land on
+ memory other cached models still hold.
+ """
+ layers = sorted(
+ k[: -len(WEIGHT_SCALE_2_SUFFIX)] for k in sd if isinstance(k, str) and k.endswith(WEIGHT_SCALE_2_SUFFIX)
+ )
+ claimed = set(layers)
+
+ awq = [path for path in layers if f"{path}{PRE_QUANT_SCALE_SUFFIX}" in sd]
+ if awq:
+ raise ValueError(
+ f"Checkpoint has {len(awq)} nvfp4 layer(s) with an AWQ pre_quant_scale, e.g. {awq[:3]}. AWQ rescales "
+ "input channels before quantization and is not supported; decoding these as plain nvfp4 would load "
+ "wrong weights."
+ )
+
+ 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 = parse_comfy_quant_marker(sd[key]).get("format")
+ if marked == 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 not in (None, NVFP4_FORMAT):
+ raise ValueError(f"nvfp4 layer '{path}' is marked {marked!r}, which contradicts its tensors.")
+
+ half = sorted(
+ weight_key
+ for weight_key, _ in iter_weight_scale_pairs(sd)
+ if weight_key[: -len(".weight")] not in claimed and getattr(sd[weight_key], "dtype", None) is torch.uint8
+ )
+ if half:
+ raise ValueError(
+ f"Checkpoint has {len(half)} packed uint8 weight(s) with a weight_scale but no weight_scale_2, "
+ f"e.g. {half[:3]}. They look like nvfp4 missing its global scale; loading them would produce a "
+ "model that runs and generates noise."
+ )
+
+ for path in layers:
+ try:
+ _check_layout(
+ sd.get(f"{path}.weight"), sd.get(f"{path}.weight_scale"), sd[f"{path}{WEIGHT_SCALE_2_SUFFIX}"]
+ )
+ except ValueError as e:
+ raise ValueError(f"nvfp4 layer '{path}': {e}") from None
+
+ if not layers:
+ return 0
+ if reserve is not None:
+ reserve(_decoded_size(sd, layers, dtype))
+ for path in layers:
+ weight, scale = sd[f"{path}.weight"], sd[f"{path}.weight_scale"]
+ sd[f"{path}.weight"] = dequantize_nvfp4_weight(weight, scale, sd[f"{path}{WEIGHT_SCALE_2_SUFFIX}"], dtype)
+ for suffix in _SIDE_CHANNEL_SUFFIXES:
+ sd.pop(f"{path}{suffix}", None)
+ return len(layers)
+
+
+def _decoded_size(sd: dict[str, Any], layers: list[str], dtype: torch.dtype) -> int:
+ """Bytes ``sd`` occupies once ``layers`` are decoded to ``dtype`` and their side channels dropped."""
+ replaced = {f"{path}{suffix}" for path in layers for suffix in (".weight", *_SIDE_CHANNEL_SUFFIXES)}
+ kept = sum(tensor.nelement() * tensor.element_size() for key, tensor in sd.items() if key not in replaced)
+ decoded = sum(sd[f"{path}.weight"].shape[0] * sd[f"{path}.weight"].shape[1] * 2 for path in layers)
+ return kept + decoded * dtype.itemsize
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
new file mode 100644
index 0000000000..fc905fce2c
--- /dev/null
+++ b/tests/backend/model_manager/load/test_mistral_encoder_checkpoint_loader.py
@@ -0,0 +1,107 @@
+"""Loader-level tests for the Mistral encoder's single-file path.
+
+These drive `_load_text_encoder` on a real, tiny safetensors file, because what they pin is order
+inside the loader: nvfp4 layers have to be decoded before either scaled-fp8 branch reads the side
+channel, with room reserved for the result first. Without the decode both branches hand a packed
+weight to `load_state_dict`. With it only in the dequantizing branch, the branch that keeps fp8 pops the
+block scales first and loads the packed weight anyway -- which is why both branches are exercised.
+"""
+
+import json
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import MagicMock
+
+import pytest
+import torch
+from safetensors.torch import save_file
+
+from invokeai.backend.model_manager.configs.mistral_encoder import MistralEncoder_Checkpoint_Config
+from invokeai.backend.model_manager.load.model_loaders import mistral_encoder
+from invokeai.backend.model_manager.load.model_loaders.mistral_encoder import MistralEncoderCheckpointLoader
+from invokeai.backend.model_manager.taxonomy import MistralVariantType
+
+# The loader derives the head count as `q_proj` rows // 128, so this is a one-head model.
+HIDDEN = 128
+INTERMEDIATE = 256
+VOCAB = 32
+
+NVFP4_PROJECTIONS = {
+ "self_attn.q_proj": (HIDDEN, HIDDEN),
+ "self_attn.k_proj": (HIDDEN, HIDDEN),
+ "self_attn.o_proj": (HIDDEN, HIDDEN),
+ "mlp.gate_proj": (INTERMEDIATE, HIDDEN),
+ "mlp.up_proj": (INTERMEDIATE, HIDDEN),
+ "mlp.down_proj": (HIDDEN, INTERMEDIATE),
+}
+
+
+def _marker_blob(marker: dict) -> torch.Tensor:
+ return torch.frombuffer(bytearray(json.dumps(marker).encode("utf-8")), dtype=torch.uint8)
+
+
+def _write_checkpoint(tmp_path: Path) -> tuple[Path, dict[str, torch.Tensor], torch.Tensor]:
+ """A Comfy-style fp4_mixed Mistral: nvfp4 projections, one scaled-fp8 projection, bf16 for the rest.
+
+ Returns the file, the weights the nvfp4 projections must load as, and the fp8 projection's
+ dequantized weight. Codes 2 and 10 decode to +1.0 and -1.0, so no E2M1 table is needed here.
+ """
+ torch.manual_seed(0)
+ tensors: dict[str, torch.Tensor] = {}
+ expected: dict[str, torch.Tensor] = {}
+ for name, shape in NVFP4_PROJECTIONS.items():
+ positive = torch.randint(0, 2, shape, dtype=torch.bool)
+ codes = torch.where(positive, 2, 10).to(torch.uint8)
+ path = f"model.layers.0.{name}"
+ tensors[f"{path}.weight"] = (codes[:, 0::2] << 4) | codes[:, 1::2]
+ tensors[f"{path}.weight_scale"] = torch.full((shape[0], shape[1] // 16), 2.0).to(torch.float8_e4m3fn)
+ tensors[f"{path}.weight_scale_2"] = torch.tensor(0.25)
+ tensors[f"{path}.comfy_quant"] = _marker_blob({"format": "nvfp4"})
+ expected[f"layers.0.{name}.weight"] = torch.where(positive, 0.5, -0.5)
+
+ fp8_values = torch.randint(-8, 9, (HIDDEN, HIDDEN)).float()
+ tensors["model.layers.0.self_attn.v_proj.weight"] = fp8_values.to(torch.float8_e4m3fn)
+ tensors["model.layers.0.self_attn.v_proj.weight_scale"] = torch.tensor(0.5)
+ tensors["model.layers.0.self_attn.v_proj.comfy_quant"] = _marker_blob({"format": "float8_e4m3fn"})
+
+ tensors["model.embed_tokens.weight"] = torch.randn(VOCAB, HIDDEN)
+ for norm in ("model.layers.0.input_layernorm", "model.layers.0.post_attention_layernorm", "model.norm"):
+ tensors[f"{norm}.weight"] = torch.ones(HIDDEN)
+ tensors["tekken_model"] = torch.randint(0, 256, (64,), dtype=torch.uint8)
+
+ checkpoint = tmp_path / "mistral_3_small_flux2_fp4_mixed.safetensors"
+ save_file(tensors, checkpoint)
+ return checkpoint, expected, fp8_values * 0.5
+
+
+def _loader(monkeypatch: pytest.MonkeyPatch, keep_fp8: bool) -> MistralEncoderCheckpointLoader:
+ monkeypatch.setattr(mistral_encoder.TorchDevice, "choose_torch_device", lambda: torch.device("cpu"))
+ monkeypatch.setattr(mistral_encoder.TorchDevice, "choose_bfloat16_safe_dtype", lambda _device: torch.float32)
+ monkeypatch.setattr(mistral_encoder, "should_keep_fp8_weights", lambda _device: keep_fp8)
+ loader = object.__new__(MistralEncoderCheckpointLoader)
+ loader._ram_cache = SimpleNamespace(make_room=MagicMock())
+ return loader
+
+
[email protected]("keep_fp8", [False, True], ids=["fp8_dequantized", "fp8_kept"])
+def test_an_nvfp4_mixed_checkpoint_loads_under_either_fp8_branch(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, keep_fp8: bool
+) -> None:
+ checkpoint, expected, fp8_dequantized = _write_checkpoint(tmp_path)
+ loader = _loader(monkeypatch, keep_fp8)
+ config = MistralEncoder_Checkpoint_Config.model_construct(path=str(checkpoint), variant=MistralVariantType.Cow)
+
+ model = loader._load_text_encoder(config)
+
+ for name, weight in expected.items():
+ assert torch.equal(model.get_parameter(name), weight), name
+ v_proj = model.layers[0].self_attn.v_proj
+ if keep_fp8:
+ assert v_proj.weight.dtype is torch.float8_e4m3fn
+ assert torch.equal(v_proj.weight.float() * v_proj.weight_scale, fp8_dequantized)
+ else:
+ assert torch.equal(v_proj.weight, fp8_dequantized)
+ # The base loader reserved only the file size; the decode has to ask for its float32 result.
+ (reserved,), _ = loader._ram_cache.make_room.call_args
+ assert loader._ram_cache.make_room.call_count == 1
+ assert reserved >= sum(rows * columns * 4 for rows, columns in NVFP4_PROJECTIONS.values())
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 4270597076..53acb14bd3 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
@@ -183,3 +183,67 @@ def test_a_precision_sensitive_layer_is_not_left_int8(monkeypatch, tmp_path) ->
# And the reservation covers the widened layer at its post-split width, not at one byte.
(reserved,), _ = loader._ram_cache.make_room.call_args
assert reserved >= sensitive.nelement() * 4 + ordinary_q.nelement()
+
+
+class _TinyAttention(torch.nn.Module):
+ def __init__(self) -> None:
+ super().__init__()
+ self.to_q = torch.nn.Linear(64, 128, bias=False)
+ self.to_k = torch.nn.Linear(64, 128, bias=False)
+ self.to_v = torch.nn.Linear(64, 128, bias=False)
+
+
+class _TinyAttentionBlock(torch.nn.Module):
+ def __init__(self) -> None:
+ super().__init__()
+ self.attention = _TinyAttention()
+
+
+class _TinyNativeZImage(torch.nn.Module):
+ """What the native-to-diffusers conversion makes of a checkpoint with a fused `attention.qkv`."""
+
+ def __init__(self, **_kwargs) -> None:
+ super().__init__()
+ self.all_x_embedder = torch.nn.ModuleDict({"2-1": torch.nn.Linear(4, 4, bias=False)})
+ self.layers = torch.nn.ModuleList([_TinyAttentionBlock()])
+
+
+def test_an_nvfp4_checkpoint_is_decoded_before_the_qkv_split(monkeypatch, tmp_path) -> None:
+ """Comfy's nvfp4 Z-Image build quantizes the fused `attention.qkv` and names its layers only in the
+ safetensors header. The decode has to run before the key conversion and the scaled-fp8 extraction,
+ with room reserved for its result first. Without it the strict load meets a packed weight and an
+ orphaned `weight_scale_2`; placed after the conversion or the extraction, it finds its layers
+ incomplete and refuses them."""
+ torch.manual_seed(4)
+ # Codes 2 and 10 decode to +1.0 and -1.0, so the expected weight needs no E2M1 table.
+ positive = torch.randint(0, 2, (384, 64), dtype=torch.bool)
+ codes = torch.where(positive, 2, 10).to(torch.uint8)
+ embedder = torch.randn(4, 4)
+ state_dict = {
+ "x_embedder.weight": embedder,
+ "layers.0.attention.qkv.weight": (codes[:, 0::2] << 4) | codes[:, 1::2],
+ "layers.0.attention.qkv.weight_scale": torch.full((384, 4), 2.0).to(torch.float8_e4m3fn),
+ "layers.0.attention.qkv.weight_scale_2": torch.tensor(0.25),
+ "layers.0.attention.qkv.input_scale": torch.tensor(1.0),
+ }
+ loader, config = _driver(monkeypatch, tmp_path, state_dict)
+ import diffusers
+
+ monkeypatch.setattr(diffusers, "ZImageTransformer2DModel", _TinyNativeZImage, raising=False)
+ # The decode works on the very dict `load_file` returned, so the weight's dtype at each reservation
+ # tells whether that reservation came before the widening.
+ reservations = []
+ loader._ram_cache.make_room.side_effect = lambda size: reservations.append(
+ (size, state_dict["layers.0.attention.qkv.weight"].dtype)
+ )
+
+ model = loader._load_from_singlefile(config)
+
+ expected = torch.where(positive, 0.5, -0.5)
+ attention = model.layers[0].attention
+ assert torch.equal(attention.to_q.weight, expected[:128])
+ assert torch.equal(attention.to_k.weight, expected[128:256])
+ assert torch.equal(attention.to_v.weight, expected[256:])
+ assert torch.equal(model.all_x_embedder["2-1"].weight, embedder)
+ # First the decoded float32 qkv plus the embedder, asked for while the weight was still packed.
+ assert reservations[0] == (384 * 64 * 4 + 4 * 4 * 4, torch.uint8)
diff --git a/tests/backend/quantization/data/z_image_turbo_nvfp4_slices.safetensors b/tests/backend/quantization/data/z_image_turbo_nvfp4_slices.safetensors
new file mode 100644
index 0000000000..fd46455994
Binary files /dev/null and b/tests/backend/quantization/data/z_image_turbo_nvfp4_slices.safetensors differ
diff --git a/tests/backend/quantization/test_nvfp4.py b/tests/backend/quantization/test_nvfp4.py
new file mode 100644
index 0000000000..e711f9a483
--- /dev/null
+++ b/tests/backend/quantization/test_nvfp4.py
@@ -0,0 +1,217 @@
+"""nvfp4 decode: byte layout, block-scale layout, and the per-layer state-dict pass.
+
+No expected value here comes from `nvfp4.py` itself. Nibble order and the E2M1 table are checked
+against literal bytes; the block-scale layout against the index formula measured on real checkpoints,
+written out as arithmetic; and the whole decode against a slice of a real Comfy-Org checkpoint and its
+bf16 build. That slice is one tile row high: it pins the layout inside a row of tiles against real data,
+while the order of the tile rows rests on the formula test.
+"""
+
+import json
+from pathlib import Path
+
+import pytest
+import torch
+from safetensors.torch import load_file
+
+from invokeai.backend.quantization.nvfp4 import dequantize_nvfp4_layers, dequantize_nvfp4_weight, unblock_scale_grid
+
+FIXTURE = Path(__file__).parent / "data" / "z_image_turbo_nvfp4_slices.safetensors"
+
+E2M1 = torch.tensor([0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0, -0.0, -0.5, -1.0, -1.5, -2.0, -3.0, -4.0, -6.0])
+
+
+def _marker_blob(marker: dict) -> torch.Tensor:
+ return torch.frombuffer(bytearray(json.dumps(marker).encode("utf-8")), dtype=torch.uint8)
+
+
+def _stored_layout(grid: torch.Tensor) -> torch.Tensor:
+ """Lay a row-major grid out the way the checkpoints store it, by the index formula measured
+ against real files: element ``[m, k]`` lands at flat position ``position``."""
+ rows, blocks = grid.shape
+ flat = torch.full((rows * blocks,), float("nan"), dtype=grid.dtype)
+ for m in range(rows):
+ for k in range(blocks):
+ position = ((((m // 128) * (blocks // 4) + k // 4) * 32 + m % 32) * 4 + (m % 128) // 32) * 4 + k % 4
+ flat[position] = grid[m, k]
+ return flat.reshape(rows, blocks)
+
+
+def _nvfp4_tensors(path: str, codes: torch.Tensor, block_scale: float, global_scale: float) -> dict[str, torch.Tensor]:
+ """One layer in checkpoint layout. A uniform block scale keeps the expectation independent of the
+ tile layout, which the tests above pin on their own."""
+ rows, in_features = codes.shape
+ return {
+ f"{path}.weight": (codes[:, 0::2] << 4) | codes[:, 1::2],
+ f"{path}.weight_scale": torch.full((rows, in_features // 16), block_scale).to(torch.float8_e4m3fn),
+ f"{path}.weight_scale_2": torch.tensor(global_scale),
+ }
+
+
+def _zero_layer(path: str, rows: int = 128) -> dict[str, torch.Tensor]:
+ return _nvfp4_tensors(path, torch.zeros(rows, 64, dtype=torch.uint8), 1.0, 1.0)
+
+
+def test_the_upper_nibble_is_the_first_element_and_both_scales_multiply() -> None:
+ weight = torch.zeros(128, 32, dtype=torch.uint8)
+ # Every code once: 0x7F is 7 then 15, 0x19 is 1 then 9, and so on.
+ weight[0, :8] = torch.tensor([0x7F, 0x19, 0x2C, 0x35, 0x46, 0xAB, 0xDE, 0x08], dtype=torch.uint8)
+ scale = torch.full((128, 4), 4.0).to(torch.float8_e4m3fn)
+
+ decoded = dequantize_nvfp4_weight(weight, scale, torch.tensor(0.125), torch.float32)
+
+ codes = [6.0, -6.0, 0.5, -0.5, 1.0, -2.0, 1.5, 3.0, 2.0, 4.0, -1.0, -1.5, -3.0, -4.0, 0.0, -0.0]
+ assert torch.equal(decoded[0, :16], torch.tensor(codes) * 0.5)
+ assert decoded.shape == (128, 64)
+
+
[email protected]("shape", [(128, 4), (128, 8), (256, 16), (384, 8)])
+def test_the_block_scale_grid_is_unblocked_the_way_checkpoints_store_it(shape: tuple[int, int]) -> None:
+ """(384, 8) is three tile rows by two tile columns, so a swap of the tile axes cannot pass."""
+ grid = torch.arange(shape[0] * shape[1], dtype=torch.float64).reshape(shape)
+
+ assert torch.equal(unblock_scale_grid(_stored_layout(grid)), grid)
+
+
[email protected]("shape", [(100, 8), (128, 6)])
+def test_a_grid_outside_the_tile_layout_is_refused_rather_than_guessed(shape: tuple[int, int]) -> None:
+ with pytest.raises(ValueError, match="tile layout"):
+ unblock_scale_grid(torch.zeros(shape))
+
+
[email protected]("layer", ["layers.0.attention.out", "layers.5.feed_forward.w2"])
+def test_a_real_checkpoint_slice_decodes_to_its_bf16_build(layer: str) -> None:
+ """Comfy-Org/z_image_turbo at revision 08d04455279082882deaabc8d0d09fc914c071e1 (Apache-2.0): the
+ first 128 rows and input columns of `split_files/diffusion_models/z_image_turbo_nvfp4.safetensors`
+ and of `z_image_turbo_bf16.safetensors` beside it. The block scales are the first 8x128 entries of
+ the stored grid, which is exactly the tiled layout of that 128x8 sub-grid.
+
+ Measured when cut: cosine 0.9953 and 0.9955 decoded, 0.9102 and 0.8801 with the grid read row by
+ row. The latter loads without an error and quietly degrades the model -- the failure pinned here.
+ The norm check is what catches a global scale applied the wrong way, which leaves the cosine alone.
+ """
+ fixture = load_file(FIXTURE)
+ weight, scale = fixture[f"{layer}.weight"], fixture[f"{layer}.weight_scale"]
+ scale_2 = fixture[f"{layer}.weight_scale_2"]
+ reference = fixture[f"{layer}.bf16_reference"].float().flatten()
+
+ decoded = dequantize_nvfp4_weight(weight, scale, scale_2, torch.float32).flatten()
+ assert torch.cosine_similarity(decoded, reference, dim=0).item() > 0.99
+ assert (decoded.norm() / reference.norm()).item() == pytest.approx(1.0, abs=0.01)
+
+ # Laying the stored grid out once more makes the unblock hand back the raw grid: a row-major read.
+ row_major = _stored_layout(scale.float()).to(torch.float8_e4m3fn)
+ naive = dequantize_nvfp4_weight(weight, row_major, scale_2, torch.float32).flatten()
+ assert torch.cosine_similarity(naive, reference, dim=0).item() < 0.95
+
+
[email protected]("dtype", [torch.float32, torch.bfloat16])
+def test_only_nvfp4_layers_are_decoded_and_the_rest_is_left_for_the_fp8_path(dtype: torch.dtype) -> None:
+ torch.manual_seed(0)
+ codes = torch.randint(0, 16, (128, 64), dtype=torch.uint8)
+ fp8_weight = torch.randn(32, 32).to(torch.float8_e4m3fn)
+ fp8_scale = torch.tensor(0.5)
+ fp8_marker = _marker_blob({"format": "float8_e4m3fn"})
+ dense = torch.randn(8)
+ tekken = torch.randint(0, 256, (64,), dtype=torch.uint8)
+ sd = {
+ **_nvfp4_tensors("blocks.0.mlp", codes, block_scale=2.0, global_scale=0.25),
+ "blocks.0.mlp.input_scale": torch.tensor(1.0),
+ "blocks.0.mlp.comfy_quant": _marker_blob({"format": "nvfp4"}),
+ "blocks.0.attn.weight": fp8_weight,
+ "blocks.0.attn.weight_scale": fp8_scale,
+ "blocks.0.attn.comfy_quant": fp8_marker,
+ "blocks.0.norm.weight": dense,
+ "tekken_model": tekken,
+ }
+
+ assert dequantize_nvfp4_layers(sd, dtype) == 1
+
+ assert sd["blocks.0.mlp.weight"].dtype is dtype
+ assert torch.equal(sd["blocks.0.mlp.weight"], (E2M1[codes.long()] * 0.5).to(dtype))
+ assert [k for k in sd if k.startswith("blocks.0.mlp.")] == ["blocks.0.mlp.weight"]
+ # The scaled-fp8 layer, its scale and its marker belong to the fp8 path.
+ assert sd["blocks.0.attn.weight"] is fp8_weight
+ assert sd["blocks.0.attn.weight_scale"] is fp8_scale
+ assert sd["blocks.0.attn.comfy_quant"] is fp8_marker
+ assert sd["blocks.0.norm.weight"] is dense
+ assert sd["tekken_model"] is tekken
+
+
+def test_room_for_the_decoded_state_dict_is_reserved_before_any_layer_is_widened() -> None:
+ sd = {**_zero_layer("layer", rows=256), "layer.input_scale": torch.tensor(1.0), "norm.weight": torch.zeros(10)}
+ reservations: list[tuple[int, torch.dtype]] = []
+
+ dequantize_nvfp4_layers(
+ sd, torch.bfloat16, reserve=lambda size: reservations.append((size, sd["layer.weight"].dtype))
+ )
+
+ # The decoded [256, 64] weight at two bytes per element plus the untouched float32 norm; the packed
+ # payload and the side channel are gone by then. Still uint8 when asked: nothing was widened yet.
+ assert reservations == [(256 * 64 * 2 + 10 * 4, torch.uint8)]
+
+
+def test_nothing_is_reserved_for_a_checkpoint_without_nvfp4_layers() -> None:
+ reservations: list[int] = []
+
+ assert dequantize_nvfp4_layers({"norm.weight": torch.zeros(10)}, torch.bfloat16, reserve=reservations.append) == 0
+ assert reservations == []
+
+
+def test_an_awq_checkpoint_is_refused_before_anything_is_decoded() -> None:
+ sd = {**_zero_layer("layer"), "layer.pre_quant_scale": torch.ones(64)}
+
+ with pytest.raises(ValueError, match="AWQ"):
+ dequantize_nvfp4_layers(sd, torch.float32)
+ assert sd["layer.weight"].dtype is torch.uint8
+
+
+def test_a_packed_weight_without_its_global_scale_is_refused() -> None:
+ sd = _zero_layer("layer")
+ del sd["layer.weight_scale_2"]
+
+ with pytest.raises(ValueError, match="with a weight_scale but no weight_scale_2"):
+ dequantize_nvfp4_layers(sd, torch.float32)
+
+
[email protected]("missing", ["weight", "weight_scale"])
+def test_a_global_scale_without_its_layer_is_refused_naming_it(missing: str) -> None:
+ sd = _zero_layer("layer")
+ del sd[f"layer.{missing}"]
+
+ with pytest.raises(ValueError, match=f"nvfp4 layer 'layer': has a weight_scale_2 but no {missing}$"):
+ dequantize_nvfp4_layers(sd, torch.float32)
+
+
+def test_a_global_scale_on_a_dense_weight_is_refused() -> None:
+ sd = _zero_layer("layer")
+ sd["layer.weight"] = torch.zeros(128, 64)
+
+ with pytest.raises(ValueError, match="nvfp4 layer 'layer': expected a packed uint8"):
+ dequantize_nvfp4_layers(sd, torch.float32)
+
+
+def test_a_malformed_layer_is_refused_before_any_layer_is_decoded_or_reserved() -> None:
+ sd = {**_zero_layer("a"), **_zero_layer("b")}
+ sd["b.weight_scale"] = torch.ones(128, 8).to(torch.float8_e4m3fn)
+ reservations: list[int] = []
+
+ with pytest.raises(ValueError, match="nvfp4 layer 'b': .* does not describe"):
+ dequantize_nvfp4_layers(sd, torch.float32, reserve=reservations.append)
+ assert sd["a.weight"].dtype is torch.uint8
+ assert reservations == []
+
+
+ ("tensors", "marker", "message"),
+ [
+ ("dense", {"format": "nvfp4"}, "nvfp4 layer 'layer' has no weight_scale_2"),
+ ("nvfp4", {"format": "float8_e4m3fn"}, "marked 'float8_e4m3fn'"),
+ ],
+)
+def test_a_marker_that_contradicts_its_tensors_is_refused(tensors: str, marker: dict, message: str) -> None:
+ sd = {"layer.weight": torch.zeros(128, 64)} if tensors == "dense" else _zero_layer("layer")
+ sd["layer.comfy_quant"] = _marker_blob(marker)
+
+ with pytest.raises(ValueError, match=message):
+ dequantize_nvfp4_layers(sd, torch.float32)