Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
feat(quantization): decode MXFP8 block scales instead of refusing them
Alexander Eichhorn6b4032c47b1f
diff --git a/docs/src/content/docs/configuration/fp8-storage.mdx b/docs/src/content/docs/configuration/fp8-storage.mdxindex e124a387d4..880d99dbf1 100644--- a/docs/src/content/docs/configuration/fp8-storage.mdx+++ b/docs/src/content/docs/configuration/fp8-storage.mdx@@ -11,7 +11,7 @@ FP8 Storage cuts a model's VRAM footprint roughly in half by keeping weights onIt pairs well with [Low-VRAM mode](/configuration/low-vram-mode/): low-VRAM mode streams layers between RAM and VRAM, while FP8 Storage shrinks the layers themselves.:::caution[For full precision models only]-FP8 Storage is meant for **full precision** checkpoints (FP16 / BF16 / FP32). It is **silently a no-op** for **GGUF**, **NF4** and [**SDNQ**](/configuration/sdnq-quantization/) checkpoints, which carry their own storage precision. **int8** and **nvfp4** single-file checkpoints keep their quantized layers as they are — the loader returns a module type the FP8 layer cast does not touch — so there the toggle reaches only the layers the build ships in full precision, and on an **Ideogram 4** int8 file nothing at all. On single-file checkpoints that ship *scaled* fp8 layers, the toggle keeps those layers in FP8 with their own scale instead of unpacking them; that is what FLUX.1, FLUX.2, Z-Image, Anima, Krea-2, Qwen-Image and Ideogram 4 all do. If your model is already quantized, use its full-precision variant to get the full effect of FP8 Storage. Checkpoints that store FP8 weights are the exception: InvokeAI loads them at BF16 unless FP8 Storage is on, so they get it automatically when installed (see [When installing](#when-installing)).+FP8 Storage is meant for **full precision** checkpoints (FP16 / BF16 / FP32). It is **silently a no-op** for **GGUF**, **NF4** and [**SDNQ**](/configuration/sdnq-quantization/) checkpoints, which carry their own storage precision. **int8** and **nvfp4** single-file checkpoints keep their quantized layers as they are — the loader returns a module type the FP8 layer cast does not touch — so there the toggle reaches only the layers the build ships in full precision, and on an **Ideogram 4** int8 file nothing at all. On single-file checkpoints that ship *scaled* fp8 layers, the toggle keeps those layers in FP8 with their own scale instead of unpacking them; that is what FLUX.1, FLUX.2, Z-Image, Anima, Krea-2, Qwen-Image and Ideogram 4 all do. **MXFP8 is the exception, and there the toggle costs quality:** those files carry one exponent per 32-element block, which no GPU before Blackwell can apply, so the layers are unpacked at load and the toggle then re-encodes them as fp8 *without* any scale. Blocks whose scale sits far below 1 lose their weights to underflow. Leave it off for an MXFP8 checkpoint. If your model is already quantized, use its full-precision variant to get the full effect of FP8 Storage. Checkpoints that store FP8 weights are the exception: InvokeAI loads them at BF16 unless FP8 Storage is on, so they get it automatically when installed (see [When installing](#when-installing)).:::## Requirementsdiff --git a/invokeai/backend/model_manager/load/model_loaders/comfyui_state_dict_utils.py b/invokeai/backend/model_manager/load/model_loaders/comfyui_state_dict_utils.pyindex bc5d21837f..0b25c8146e 100644--- a/invokeai/backend/model_manager/load/model_loaders/comfyui_state_dict_utils.py+++ b/invokeai/backend/model_manager/load/model_loaders/comfyui_state_dict_utils.py@@ -12,6 +12,8 @@ need a second copy.import torch+from invokeai.backend.quantization.fp8_scaled import reject_undecoded_mx_scale+def _strip_comfyui_prefix(sd: dict) -> dict:"""Strip ComfyUI-style `model.diffusion_model.` / `diffusion_model.` prefixes from keys."""@@ -64,6 +66,7 @@ def _dequantize_comfyui_fp8(sd: dict, compute_dtype: torch.dtype) -> int:breakif weight_key not in sd:continue+ reject_undecoded_mx_scale(weight_key[: -len(".weight")], sd[scale_key])weight = sd[weight_key].to(compute_dtype)scale = sd[scale_key].to(compute_dtype)if scale.shape != weight.shape and scale.numel() > 1:diff --git a/invokeai/backend/quantization/block_scale_tiles.py b/invokeai/backend/quantization/block_scale_tiles.pynew file mode 100644index 0000000000..66d42f1a9d--- /dev/null+++ b/invokeai/backend/quantization/block_scale_tiles.py@@ -0,0 +1,50 @@+"""The cuBLAS block-scale tile layout, shared by every scheme whose scales arrive in it.++cuBLAS and TensorRT take a block-scale operand tiled rather than row-major, and producers write that+tiling into a tensor of the row-major *shape* -- so nothing about the shape gives it away, and a+grid read as stored decodes to noise that loads without complaint. NVIDIA documents it as "Block+Scaling Factors Layout"; ComfyUI writes it with `to_blocked` (`comfy/float.py`).++Two schemes in this tree arrive in it, with different block widths and different scale encodings:+nvfp4 (16-element blocks, ``float8_e4m3fn`` entries) and MXFP8 (32-element blocks, E8M0 exponent+bytes). The tiling is over the *grid*, so it is the same permutation for both and belongs to+neither scheme -- which is why it lives here rather than in one of them importing the other.+"""++import torch++# A tile spans 128 rows and 4 blocks, whatever a block is worth.+TILE_ROWS = 128+TILE_BLOCKS = 4+++def check_tile_layout(rows: int, blocks: int) -> None:+ """Refuse a grid the inverse below cannot address.++ ``to_blocked`` pads a grid that does not divide evenly and the padding is cropped on the way+ back. No published checkpoint measured so far needs it -- every grid in the nvfp4 and MXFP8+ builds checked is already aligned -- so the padded case is refused rather than implemented from+ the specification and shipped untested.+ """+ 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]``.++ 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. 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)``. Tile row+ ``r`` therefore occupies stored rows ``[128 r, 128 (r + 1))``.+ """+ 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)diff --git a/invokeai/backend/quantization/fp8_scaled.py b/invokeai/backend/quantization/fp8_scaled.pyindex 868c0ebef2..e1c67a35d9 100644--- a/invokeai/backend/quantization/fp8_scaled.py+++ b/invokeai/backend/quantization/fp8_scaled.py@@ -24,6 +24,8 @@ from typing import Any, Iterable, Mappingimport torch+from invokeai.backend.quantization.block_scale_tiles import unblock_scale_grid+FP8_DTYPE = torch.float8_e4m3fn# Every float8 dtype a checkpoint may store weights in. Scale *recovery* must cover all of them:@@ -46,6 +48,18 @@ COMFY_QUANT_SUFFIX = ".comfy_quant"# Standalone marker keys some producers emit alongside the tensors. They carry no per-layer data.STRAY_METADATA_KEYS = ("scaled_fp8",)+# OCP Microscaling. The weights are ordinary fp8; what differs is the scale, which is one E8M0+# exponent per block of 32 elements, laid out in cuBLAS tiles. Producers name it in the marker.+MXFP8_FORMAT = "mxfp8"+# MX is 32 by definition, and both published builds say so. The width is still read off the shapes+# and checked against this -- Krea-2's build declares no `block_size` at all, so for that file the+# inferred width is the only number there is, and a grid implying another width is a producer this+# decode has not seen rather than something to guess at.+MXFP8_BLOCK_SIZE = 32+# E8M0 is a bare biased exponent; 0xFF is reserved as NaN.+_E8M0_BIAS = 127+_E8M0_NAN = 0xFF+@dataclassclass Fp8ScaledLayer:@@ -353,21 +367,11 @@ def _usable_input_scale(scale: torch.Tensor | None) -> torch.Tensor | None:return scale-# OCP Microscaling (MXFP8) stores one E8M0 exponent per 32-element block. safetensors has no E8M0-# dtype, so producers write the exponents as `uint8`.-#-# We refuse such checkpoints rather than guessing at them. Decoding the byte as `2**(v-127)` and-# expanding it 32-wide is *not* sufficient, established against a real file: the MXFP8 and the-# scaled-fp8 build of `krea2TurboOfficialComfy` share all 174 bf16 tensors bit-for-bit, so the-# scaled build is an exact reference for the same weights -- and against it the decoded weights-# reach a correlation of only 0.60, producing pure noise end to end. The measured per-block scale-# has no monotonic relation to the byte (112 and 116 yield the same true scale), which points at a-# swizzled scale layout rather than a wrong exponent bias. Supporting it means implementing that-# de-swizzle, not adding a constant.-#-# Refusing is the point: with the block-wise expansion in place, such a file otherwise *loads* and-# generates a garbage image with nothing in the log.-_MX_SCALE_DTYPES = (torch.uint8,)+# safetensors has no E8M0 dtype, so producers write the exponents as `uint8`; torch grew+# `float8_e8m0fnu` later and another producer may use it, so both spellings are accepted. Neither+# says anything on its own -- a `uint8` tensor beside an fp8 weight could be any producer's idea --+# which is why `decode_mx_block_scales` requires the layer to be *named* mxfp8 as well.+_MX_SCALE_DTYPES = tuple(dtype for dtype in (torch.uint8, getattr(torch, "float8_e8m0fnu", None)) if dtype is not None)def _reject_unparsed_scales(sd: Mapping[str, Any]) -> None:@@ -390,12 +394,54 @@ def _reject_unparsed_scales(sd: Mapping[str, Any]) -> None:)-def _reject_mx_scale(path: str) -> None:- raise NotImplementedError(- f"'{path}' carries an MXFP8 (OCP Microscaling) block scale, which InvokeAI cannot decode "- "yet: the exponents are stored in a swizzled layout. Use the scaled-fp8 or bf16 build of "- "this checkpoint instead. Loading it anyway would produce a noise image, not a warning."- )+def decode_mx_block_scales(+ path: str, weight: torch.Tensor, scale: torch.Tensor, hints: Mapping[str, Any]+) -> torch.Tensor:+ """Turn an MXFP8 exponent grid into an ordinary block-wise float scale.++ Two things have to happen and both are silent when skipped. The grid is stored in cuBLAS tiles,+ so read row by row it pairs blocks with the wrong rows -- that is what made an earlier attempt+ at this decode reach a correlation of 0.60 against a reference build and generate noise. And the+ bytes are E8M0 exponents, so the value is ``2**(v - 127)``, not the byte.++ The layer must also *say* it is mxfp8, in a per-tensor ``comfy_quant`` marker or the+ ``_quantization_metadata`` header -- both published builds do, one each way. A ``uint8`` tensor+ beside an fp8 weight is otherwise just an unknown producer's convention, and guessing at it is+ how this class of defect happens. The block width comes from the shapes rather than from the+ marker, which only cross-checks it: Comfy-Org's Krea-2 build omits ``block_size`` entirely.++ Returns the row-major ``[rows, blocks]`` grid, which ``expand_weight_scale`` widens like any+ other block-wise scale. Block-wise scales never reach ``_scaled_mm`` (see+ :func:`is_matmul_usable_scale`), so an MXFP8 layer is always folded -- which is also what the+ hardware requires: block-scaled ``_scaled_mm`` needs Blackwell and torch >= 2.8.+ """+ if hints.get("format") != MXFP8_FORMAT:+ raise NotImplementedError(+ f"'{path}' has a {scale.dtype} weight_scale beside an fp8 weight, which looks like an MXFP8 "+ "(OCP Microscaling) exponent grid, but no `comfy_quant` marker or `_quantization_metadata` entry "+ f"names it '{MXFP8_FORMAT}'. Its layout is therefore unknown, and reading it as one would load "+ "cleanly and generate noise. Use the scaled-fp8 or bf16 build of this checkpoint."+ )+ if scale.dim() != 2 or scale.shape[0] != weight.shape[0] or weight.dim() != 2:+ raise ValueError(+ f"'{path}': an MXFP8 scale must be a 2-D [rows, blocks] grid matching the weight's rows; got "+ f"{tuple(scale.shape)} for a {tuple(weight.shape)} weight."+ )+ blocks = scale.shape[1]+ block_size, remainder = divmod(weight.shape[1], blocks)+ declared = hints.get("block_size", MXFP8_BLOCK_SIZE)+ if remainder or declared != block_size:+ raise ValueError(+ f"'{path}': a {tuple(scale.shape)} grid does not describe a {tuple(weight.shape)} weight in blocks of "+ f"{declared}."+ )++ exponents = unblock_scale_grid(scale.view(torch.uint8)).to(torch.int32)+ if bool((exponents == _E8M0_NAN).any()):+ # Reserved in OCP E8M0. Decoding it as an exponent would give 2**128; propagating NaN would+ # poison the layer just as quietly. Neither published build contains one.+ raise ValueError(f"'{path}': its MXFP8 scale grid contains the reserved E8M0 value 0x{_E8M0_NAN:02X} (NaN).")+ return torch.exp2((exponents - _E8M0_BIAS).to(torch.float32))def _normalize_weight_scale(scale: torch.Tensor) -> torch.Tensor:@@ -414,6 +460,23 @@ def _normalize_weight_scale(scale: torch.Tensor) -> torch.Tensor:return scale.flatten()+def reject_undecoded_mx_scale(path: str, scale: Any) -> None:+ """Refuse an MX exponent grid to anything that is about to multiply it as a number.++ Only ``extract_fp8_scaled_layers`` decodes these (see :func:`decode_mx_block_scales`); several+ loaders instead fold ``weight_scale`` into the weight directly, and there the bytes would be+ used as linear multipliers -- values around 120-135 rather than ``2**(v-127)``, and paired with+ the wrong rows besides. That loads cleanly and generates noise, which is the failure this whole+ decode exists to prevent, arriving through the door it does not cover.+ """+ if getattr(scale, "dtype", None) in _MX_SCALE_DTYPES:+ raise NotImplementedError(+ f"'{path}' carries an MXFP8 (OCP Microscaling) exponent grid, and this loader folds weight scales "+ "without decoding them. Its weights would be scaled by the raw exponent bytes and generate noise. "+ "Use the scaled-fp8 or bf16 build of this checkpoint."+ )++def expand_weight_scale(weight: torch.Tensor, scale: torch.Tensor) -> torch.Tensor:"""Broadcast ``scale`` to line up with ``weight`` for an elementwise multiply.@@ -429,6 +492,7 @@ def expand_weight_scale(weight: torch.Tensor, scale: torch.Tensor) -> torch.Tensdequantizer expands, and the FLUX.2 loader used to expand before this module centralized thelogic."""+ reject_undecoded_mx_scale("<weight_scale>", scale)if scale.numel() == 1:return scaleif scale.dim() <= 1:@@ -512,9 +576,9 @@ def extract_fp8_scaled_layers(# A scale without an fp8 weight means the weight was already dequantized (or the key# naming does not line up). Applying the scale later would corrupt it, so drop it.continue- if getattr(scale, "dtype", None) in _MX_SCALE_DTYPES:- _reject_mx_scale(path)hints = layer_meta.get(path, {})+ if getattr(scale, "dtype", None) in _MX_SCALE_DTYPES:+ scale = decode_mx_block_scales(path, weight, scale, hints)layers[path] = Fp8ScaledLayer(weight_scale=_normalize_weight_scale(scale),input_scale=_usable_input_scale(input_scales.get(path)),diff --git a/invokeai/backend/quantization/nvfp4.py b/invokeai/backend/quantization/nvfp4.pyindex 76aec234be..c3c33e4849 100644--- a/invokeai/backend/quantization/nvfp4.py+++ b/invokeai/backend/quantization/nvfp4.py@@ -40,6 +40,7 @@ from typing import Anyimport torchimport torch.nn.functional as F+from invokeai.backend.quantization.block_scale_tiles import TILE_ROWS, check_tile_layout, unblock_scale_gridfrom invokeai.backend.quantization.dequantizing_linear import DequantizingLinearfrom invokeai.backend.quantization.fp8_scaled import COMFY_QUANT_SUFFIX, INPUT_SCALE_SUFFIXES, iter_weight_scale_pairsfrom invokeai.backend.quantization.int8_convrot import parse_comfy_quant_marker@@ -53,10 +54,6 @@ PRE_QUANT_SCALE_SUFFIX = ".pre_quant_scale"# Everything a layer carries 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_PAIRS_BY_BYTE = torch.stack([_E2M1_VALUES[torch.arange(256) >> 4], _E2M1_VALUES[torch.arange(256) & 0x0F]], dim=1)@@ -78,36 +75,6 @@ def _e4m3_values_on(device: torch.device) -> torch.Tensor:return _E4M3_BY_BYTE.to(device)-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)``. Tile row ``r`` therefore occupies stored rows- ``[128 r, 128 (r + 1))``.-- 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 checkpoint tensors this decode would misread. Reads dtypes and shapes only."""if weight is None or weight_scale is None:@@ -127,7 +94,7 @@ def _check_layout(weight: torch.Tensor | None, weight_scale: torch.Tensor | Nonef"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)+ check_tile_layout(rows, blocks)def dequantize_nvfp4_weight(@@ -324,9 +291,9 @@ def split_nvfp4_rows(path: str, payload: NVFP4Payload, parts: int) -> list[NVFP4That is refused rather than guessed. The global scale belongs to every part."""rows = payload.out_features- if rows % parts or (rows // parts) % _TILE_ROWS:+ if rows % parts or (rows // parts) % TILE_ROWS:raise ValueError(- f"nvfp4 layer '{path}': its {rows} rows do not split into {parts} parts of whole {_TILE_ROWS}-row "+ f"nvfp4 layer '{path}': its {rows} rows do not split into {parts} parts of whole {TILE_ROWS}-row ""scale tiles.")step = rows // partsdiff --git a/tests/backend/quantization/test_block_scale_tiles.py b/tests/backend/quantization/test_block_scale_tiles.pynew file mode 100644index 0000000000..7ea0a04920--- /dev/null+++ b/tests/backend/quantization/test_block_scale_tiles.py@@ -0,0 +1,50 @@+"""The cuBLAS block-scale tiling, and its inverse.++Every scheme whose scales arrive tiled depends on this one permutation, and reading a tiled grid as+row-major is silent: it pairs blocks with the wrong rows, the checkpoint loads, and the model+generates noise. So the expectation here is built from the index formula measured against real+files, written out explicitly, rather than from the implementation's reshape.+"""++import pytest+import torch++from invokeai.backend.quantization.block_scale_tiles import unblock_scale_grid+++def stored_layout(grid: torch.Tensor) -> torch.Tensor:+ """Lay a row-major grid out the way checkpoints store it.++ By the measured index formula: element ``[m, k]`` lands at flat position ``position``. Shared+ with the nvfp4 and MXFP8 decode tests so both check against the same independent statement of+ the layout rather than against each other.+ """+ 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)++[email protected]("shape", [(128, 4), (128, 8), (256, 16), (384, 8)])+def test_a_stored_grid_is_restored_to_row_major(shape: tuple[int, int]) -> None:+ """(384, 8) is three tile rows by two tile columns, so swapping 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:+ """`to_blocked` pads such a grid and the padding is cropped on the way back. No published+ checkpoint needs it, so it is refused rather than implemented from the spec and shipped+ untested."""+ with pytest.raises(ValueError, match="tile layout"):+ unblock_scale_grid(torch.zeros(shape))+++def test_a_one_dimensional_grid_is_refused() -> None:+ with pytest.raises(ValueError, match="2-D"):+ unblock_scale_grid(torch.zeros(512))diff --git a/tests/backend/quantization/test_fp8_scaled.py b/tests/backend/quantization/test_fp8_scaled.pyindex 414d7ce180..6d8b28a49b 100644--- a/tests/backend/quantization/test_fp8_scaled.py+++ b/tests/backend/quantization/test_fp8_scaled.py@@ -1,16 +1,20 @@import contextlib+import jsonimport loggingfrom unittest import mockimport pytestimport torch+from invokeai.backend.quantization.block_scale_tiles import unblock_scale_gridfrom invokeai.backend.quantization.fp8_scaled import (FP8_DTYPE,+ QUANT_METADATA_KEY,Fp8ScaledLayer,attach_fp8_scales,cast_state_dict,count_fp8_weights,+ decode_mx_block_scales,dequantize_fp8_scaled,dequantize_weight,detach_layer_sidechannel,@@ -32,6 +36,7 @@ from invokeai.backend.quantization.fp8_scaled import (strip_layer_path_prefix,warn_on_unattached_scales,)+from tests.backend.quantization.test_block_scale_tiles import stored_layoutcuda_fp8 = pytest.mark.skipif(not (torch.cuda.is_available() and device_supports_fp8_matmul(torch.device("cuda"))),@@ -1015,26 +1020,40 @@ class TestProbeFailureCaching:reset_fp8_matmul_support_cache()-class TestMxfp8IsRefused:- """MXFP8 block scales are refused rather than guessed at.+class TestMxfp8:+ """MXFP8 block scales are decoded when the file names them, and refused when it does not.- Established against a real pair of checkpoints: the MXFP8 and the scaled-fp8 build of- `krea2TurboOfficialComfy` share all 174 bf16 tensors bit-for-bit, so the scaled build is an- exact reference. Decoding the uint8 exponents as `2**(v-127)` and expanding them 32-wide- reaches a correlation of only 0.60 against it and generates a pure-noise image; the measured- per-block scale has no monotonic relation to the byte (112 and 116 give the same true scale),- which points at a swizzled scale layout.-- Refusing matters because the block-wise expansion is what makes such a file *loadable*: without- a guard it produces garbage silently, which is strictly worse than the shape error it used to- raise.+ Both halves matter. The grid is stored in cuBLAS tiles, so reading it row by row pairs blocks+ with the wrong rows -- an earlier attempt at this decode reached a correlation of 0.60 against a+ reference build and generated a pure-noise image, with the block-wise expansion making such a+ file *loadable* rather than raising. And a `uint8` tensor beside an fp8 weight is not+ self-evidently MXFP8: it is whatever its producer meant, so the layer has to say so."""- def test_a_uint8_block_scale_is_rejected_with_an_actionable_message(self) -> None:+ @staticmethod+ def _mx_layer(exponents: torch.Tensor, marker: dict | None) -> tuple[dict, dict]:+ """One MXFP8 layer in checkpoint layout: fp8 codes, a tiled exponent grid, and the hints."""+ rows, blocks = exponents.shapesd = {- "lin.weight": torch.full((4, 64), 2.0).to(FP8_DTYPE),- "lin.weight_scale": torch.full((4, 2), 125, dtype=torch.uint8),+ "lin.weight": torch.ones(rows, blocks * 32).to(FP8_DTYPE),+ "lin.weight_scale": stored_layout(exponents.to(torch.float64)).to(torch.uint8),}+ return sd, ({"lin": marker} if marker else {})++ def test_the_exponents_are_decoded_and_unswizzled(self) -> None:+ """Distinct exponents across the grid, so a read in the stored order lands the wrong one on+ all but a few entries."""+ exponents = torch.arange(128 * 4, dtype=torch.int64).reshape(128, 4) % 8 + 124++ sd, hints = self._mx_layer(exponents, {"format": "mxfp8", "block_size": 32})+ layers = extract_fp8_scaled_layers(sd, layer_hints=hints)++ assert torch.equal(layers["lin"].weight_scale, torch.exp2(exponents.float() - 127))++ def test_a_grid_no_marker_or_header_names_is_refused(self) -> None:+ """The dtype alone is not evidence. Reading an unknown producer's uint8 grid as MXFP8 is+ exactly the guess that generates noise without a log line."""+ sd, _ = self._mx_layer(torch.full((128, 4), 125, dtype=torch.int64), None)with pytest.raises(NotImplementedError) as excinfo:extract_fp8_scaled_layers(sd)@@ -1044,8 +1063,149 @@ class TestMxfp8IsRefused:assert "MXFP8" in messageassert "noise" in message, "say what happens if it were loaded anyway"+ def test_the_header_names_it_too(self) -> None:+ """Comfy-Org's Krea-2 build ships no per-tensor markers at all: every layer is named only in+ `_quantization_metadata`, and without a `block_size`."""+ exponents = torch.full((128, 4), 129, dtype=torch.int64)++ sd, _ = self._mx_layer(exponents, None)+ layers = extract_fp8_scaled_layers(sd, layer_hints={"lin": {"format": "mxfp8"}})++ assert torch.equal(layers["lin"].weight_scale, torch.full((128, 4), 4.0))++ def test_a_declared_block_size_that_contradicts_the_shapes_is_refused(self) -> None:+ """The width is read off the shapes; the marker only cross-checks it. A producer that+ changed the block size would otherwise be decoded against the wrong blocks."""+ sd, hints = self._mx_layer(torch.full((128, 4), 127, dtype=torch.int64), {"format": "mxfp8", "block_size": 16})++ with pytest.raises(ValueError, match="blocks of 16"):+ extract_fp8_scaled_layers(sd, layer_hints=hints)++ def test_the_reserved_nan_exponent_is_refused(self) -> None:+ """0xFF is reserved in E8M0. Decoded as an exponent it is 2**128; propagated as NaN it+ poisons the layer just as quietly. Neither published build contains one."""+ exponents = torch.full((128, 4), 127, dtype=torch.int64)+ exponents[7, 2] = 0xFF++ sd, hints = self._mx_layer(exponents, {"format": "mxfp8", "block_size": 32})++ with pytest.raises(ValueError, match="reserved"):+ extract_fp8_scaled_layers(sd, layer_hints=hints)++ def test_an_mxfp8_layer_is_folded_rather_than_kept_for_the_matmul(self) -> None:+ """`_scaled_mm` cannot apply block scales before Blackwell and torch 2.8, so these layers+ have to be widened at load. Driven through the split that actually decides it, not through+ the predicate underneath: a decode that returned a per-tensor or per-row scale would satisfy+ the predicate test and still be wrong here."""+ exponents = torch.full((128, 4), 128, dtype=torch.int64)+ sd, hints = self._mx_layer(exponents, {"format": "mxfp8", "block_size": 32})+ layers = extract_fp8_scaled_layers(sd, layer_hints=hints)++ surviving = split_fp8_scaled_layers(sd, layers, torch.float32)++ assert surviving == {}+ assert sd["lin.weight"].dtype is torch.float32++ def test_the_decoded_scale_folds_into_the_weight(self) -> None:+ """End to end: the grid widens 32-fold across the row and multiplies the codes."""+ exponents = torch.tensor([[128, 129, 130, 131]] * 128, dtype=torch.int64)++ sd, hints = self._mx_layer(exponents, {"format": "mxfp8", "block_size": 32})+ layers = extract_fp8_scaled_layers(sd, layer_hints=hints)+ dequantize_fp8_scaled(sd, layers, torch.float32)++ expected = torch.cat([torch.full((128, 32), 2.0 ** (e - 127)) for e in (128, 129, 130, 131)], dim=1)+ assert torch.equal(sd["lin.weight"], expected)++ def test_every_exponent_byte_decodes_the_way_torch_reads_e8m0(self) -> None:+ """The bias is checked against the specification, not against a restatement of the code.++ `torch.float8_e8m0fnu` *is* the encoding: a byte is a biased exponent and nothing else. So+ every finite value is decoded here and compared with what torch makes of the same byte. An+ off-by-one bias, or reading the byte as a linear multiplier — the mistake that shipped once+ and inflated weights ~470,000x — cannot survive this.++ No checkpoint is needed for it, which matters: the two published MXFP8 builds are Krea-2's+ and NVIDIA's PiD, and neither is licensed for their weights to be carried in this repo. The+ de-swizzle is measured against them instead, and the numbers are in the class docstring.+ """+ finite = torch.arange(255, dtype=torch.uint8)++ sd, hints = self._mx_layer(finite.reshape(1, 255).expand(128, 255)[:, :4].contiguous().long(), None)+ decoded = decode_mx_block_scales("lin", sd["lin.weight"], sd["lin.weight_scale"], {"format": "mxfp8"})++ expected = unblock_scale_grid(sd["lin.weight_scale"]).view(torch.float8_e8m0fnu).float()+ assert torch.equal(decoded, expected)++ def test_a_scale_typed_as_e8m0_decodes_like_the_same_bytes_as_uint8(self) -> None:+ """safetensors has no E8M0 dtype so producers write `uint8`, but torch grew+ `float8_e8m0fnu` and another producer may use it. The two must decode identically: the code+ reinterprets the bytes rather than converting the values, and `scale.to(torch.int32)` on an+ e8m0 tensor silently yields zeros — every scale would become 2**-127."""+ exponents = torch.arange(128 * 4, dtype=torch.int64).reshape(128, 4) % 8 + 124++ as_bytes, hints = self._mx_layer(exponents, {"format": "mxfp8"})+ as_e8m0 = dict(as_bytes)+ as_e8m0["lin.weight_scale"] = as_bytes["lin.weight_scale"].view(torch.float8_e8m0fnu)++ assert torch.equal(+ extract_fp8_scaled_layers(as_bytes, layer_hints=hints)["lin"].weight_scale,+ extract_fp8_scaled_layers(as_e8m0, layer_hints=hints)["lin"].weight_scale,+ )++ def test_the_header_transport_names_it_too(self) -> None:+ """Comfy-Org's Krea-2 build — the one file this decode reaches today — ships no per-tensor+ markers at all: all 256 layers are named only in `_quantization_metadata`, and without a+ `block_size`. So the header is read here rather than hints being handed in ready-made."""+ exponents = torch.full((128, 4), 129, dtype=torch.int64)+ sd, _ = self._mx_layer(exponents, None)+ metadata = {QUANT_METADATA_KEY: json.dumps({"layers": {"lin": {"format": "mxfp8"}}})}++ layers = extract_fp8_scaled_layers(sd, metadata=metadata)++ assert torch.equal(layers["lin"].weight_scale, torch.full((128, 4), 4.0))++ def test_a_grid_whose_rows_do_not_match_the_weight_is_refused(self) -> None:+ """Left to `expand_weight_scale`, a short grid is repeat_interleaved along the row axis+ instead — every row scaled by another row's exponent, loading cleanly."""+ sd, hints = self._mx_layer(torch.full((128, 4), 127, dtype=torch.int64), {"format": "mxfp8"})+ sd["lin.weight"] = torch.ones(256, 128).to(FP8_DTYPE)++ with pytest.raises(ValueError, match="matching the weight"):+ extract_fp8_scaled_layers(sd, layer_hints=hints)++ def test_an_inferred_block_width_the_standard_does_not_use_is_refused(self) -> None:+ """Krea-2's build declares no `block_size`, so for the one reachable file the width is+ inferred outright. MX is 32 by definition; anything else is a producer this decode has not+ seen, and guessing at it is what this whole change exists to stop."""+ exponents = torch.full((128, 8), 127, dtype=torch.int64)+ sd, hints = self._mx_layer(exponents, {"format": "mxfp8"})+ sd["lin.weight"] = torch.ones(128, 128).to(FP8_DTYPE)++ # The message names the width MX is defined at, which is the one the file failed to meet.+ with pytest.raises(ValueError, match="blocks of 32"):+ extract_fp8_scaled_layers(sd, layer_hints=hints)++ def test_a_padded_block_axis_cannot_pass_as_a_wider_block(self) -> None:+ """`to_blocked` pads the *block* axis up to a multiple of 4, which is what makes the tile+ check pass -- so the tile check can never see that padding. An `in_features` of 192 gives 6+ real blocks padded to 8, and 192/8 divides evenly at 24, so nothing but the block width+ itself stands between a padded grid and every scale landing on the wrong 24 elements."""+ weight = torch.ones(128, 192).to(FP8_DTYPE)+ grid = torch.full((128, 8), 127, dtype=torch.uint8)++ with pytest.raises(ValueError, match="blocks of 32"):+ decode_mx_block_scales("lin", weight, grid, {"format": "mxfp8"})++ def test_a_loader_that_folds_without_decoding_refuses_rather_than_multiplying_bytes(self) -> None:+ """Several loaders fold `weight_scale` into the weight directly instead of going through+ the extraction. There the exponent bytes would be used as linear multipliers -- ~120-135+ instead of 2**(v-127) -- which loads cleanly and generates noise."""+ with pytest.raises(NotImplementedError, match="folds weight scales"):+ expand_weight_scale(torch.ones(128, 128), torch.full((128, 4), 127, dtype=torch.uint8))+def test_float_scales_are_unaffected(self) -> None:- """The guard keys off the dtype, so ordinary scaled-fp8 checkpoints must still load."""+ """The decode keys off the dtype, so ordinary scaled-fp8 checkpoints must still load."""sd = {"lin.weight": torch.full((4, 64), 2.0).to(FP8_DTYPE),"lin.weight_scale": torch.full((4, 2), 0.25),diff --git a/tests/backend/quantization/test_nvfp4.py b/tests/backend/quantization/test_nvfp4.pyindex e181b6a162..a11c525f25 100644--- a/tests/backend/quantization/test_nvfp4.py+++ b/tests/backend/quantization/test_nvfp4.py@@ -30,8 +30,8 @@ from invokeai.backend.quantization.nvfp4 import (pop_nvfp4_layers,predict_nvfp4_install_size,split_nvfp4_rows,- unblock_scale_grid,)+from tests.backend.quantization.test_block_scale_tiles import stored_layoutFIXTURE = Path(__file__).parent / "data" / "z_image_turbo_nvfp4_slices.safetensors"@@ -40,18 +40,6 @@ 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 marked layer in checkpoint layout. A uniform block scale keeps the expectation independent of thetile layout, which the tests above pin on their own."""@@ -92,20 +80,6 @@ def test_the_upper_nibble_is_the_first_element_and_both_scales_multiply() -> Nonassert 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))--@pytest.mark.parametrize("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@@ -127,7 +101,7 @@ def test_a_real_checkpoint_slice_decodes_to_its_bf16_build(layer: str) -> None: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)+ 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