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.

test(quantization): one MXFP8 builder, checked against the released build

Alexander Eichhorna94cf06fe3a4
diff --git a/tests/backend/model_manager/load/state_dicts/krea2_turbo_mxfp8_keys.py b/tests/backend/model_manager/load/state_dicts/krea2_turbo_mxfp8_keys.py
new file mode 100644
index 0000000000..4ee2196aed
--- /dev/null
+++ b/tests/backend/model_manager/load/state_dicts/krea2_turbo_mxfp8_keys.py
@@ -0,0 +1,186 @@
+"""Representative key layout of Comfy-Org's MXFP8 Krea-2 Turbo build.
+
+Captured on 2026-09-26 with `scripts/capture_state_dict_fixture.py`,
+which reads the header only, from
+`Comfy-Org/Krea-2/diffusion_models/krea2_turbo_mxfp8.safetensors`.
+
+Subsetting rule: `blocks` index 0, plus every key outside a stack. Values are `(shape, dtype)`.
+
+The only reachable MXFP8 file, and the only checked-in evidence for what the scheme looks like on
+disk. Everything the decode assumes is visible here: the scale is `uint8` rather than a float, one
+entry per 32 weight elements, a whole number of cuBLAS tiles, and the layer is named `mxfp8` in the
+`_quantization_metadata` header with **no** per-tensor `.comfy_quant` marker beside it.
+
+`block_size` is absent from every hint. `decode_mx_block_scales` takes the block width from the
+shapes for exactly that reason and lets the marker only cross-check it; a decode that required the
+field would refuse this file, and a re-upload that added it must not change the answer.
+
+No weights can be checked in -- this build is `license: other` -- so this records the layout and the
+synthetic `mxfp8_tensors` payload is checked against it, rather than the other way round.
+"""
+
+state_dict_keys: dict[str, tuple[list[int], str]] = {
+ "blocks.0.attn.gate.weight": ([6144, 6144], "F8_E4M3"),
+ "blocks.0.attn.gate.weight_scale": ([6144, 192], "U8"),
+ "blocks.0.attn.qknorm.knorm.scale": ([128], "BF16"),
+ "blocks.0.attn.qknorm.qnorm.scale": ([128], "BF16"),
+ "blocks.0.attn.wk.weight": ([1536, 6144], "F8_E4M3"),
+ "blocks.0.attn.wk.weight_scale": ([1536, 192], "U8"),
+ "blocks.0.attn.wo.weight": ([6144, 6144], "F8_E4M3"),
+ "blocks.0.attn.wo.weight_scale": ([6144, 192], "U8"),
+ "blocks.0.attn.wq.weight": ([6144, 6144], "F8_E4M3"),
+ "blocks.0.attn.wq.weight_scale": ([6144, 192], "U8"),
+ "blocks.0.attn.wv.weight": ([1536, 6144], "F8_E4M3"),
+ "blocks.0.attn.wv.weight_scale": ([1536, 192], "U8"),
+ "blocks.0.mlp.down.weight": ([6144, 16384], "F8_E4M3"),
+ "blocks.0.mlp.down.weight_scale": ([6144, 512], "U8"),
+ "blocks.0.mlp.gate.weight": ([16384, 6144], "F8_E4M3"),
+ "blocks.0.mlp.gate.weight_scale": ([16384, 192], "U8"),
+ "blocks.0.mlp.up.weight": ([16384, 6144], "F8_E4M3"),
+ "blocks.0.mlp.up.weight_scale": ([16384, 192], "U8"),
+ "blocks.0.mod.lin": ([36864], "BF16"),
+ "blocks.0.postnorm.scale": ([6144], "BF16"),
+ "blocks.0.prenorm.scale": ([6144], "BF16"),
+ "first.bias": ([6144], "BF16"),
+ "first.weight": ([6144, 64], "BF16"),
+ "last.linear.bias": ([64], "BF16"),
+ "last.linear.weight": ([64, 6144], "BF16"),
+ "last.modulation.lin": ([2, 6144], "BF16"),
+ "last.norm.scale": ([6144], "BF16"),
+ "tmlp.0.bias": ([6144], "BF16"),
+ "tmlp.0.weight": ([6144, 256], "BF16"),
+ "tmlp.2.bias": ([6144], "BF16"),
+ "tmlp.2.weight": ([6144, 6144], "BF16"),
+ "tproj.1.bias": ([36864], "BF16"),
+ "tproj.1.weight": ([36864, 6144], "BF16"),
+ "txtfusion.layerwise_blocks.0.attn.gate.weight": ([2560, 2560], "F8_E4M3"),
+ "txtfusion.layerwise_blocks.0.attn.gate.weight_scale": ([2560, 80], "U8"),
+ "txtfusion.layerwise_blocks.0.attn.qknorm.knorm.scale": ([128], "BF16"),
+ "txtfusion.layerwise_blocks.0.attn.qknorm.qnorm.scale": ([128], "BF16"),
+ "txtfusion.layerwise_blocks.0.attn.wk.weight": ([2560, 2560], "F8_E4M3"),
+ "txtfusion.layerwise_blocks.0.attn.wk.weight_scale": ([2560, 80], "U8"),
+ "txtfusion.layerwise_blocks.0.attn.wo.weight": ([2560, 2560], "F8_E4M3"),
+ "txtfusion.layerwise_blocks.0.attn.wo.weight_scale": ([2560, 80], "U8"),
+ "txtfusion.layerwise_blocks.0.attn.wq.weight": ([2560, 2560], "F8_E4M3"),
+ "txtfusion.layerwise_blocks.0.attn.wq.weight_scale": ([2560, 80], "U8"),
+ "txtfusion.layerwise_blocks.0.attn.wv.weight": ([2560, 2560], "F8_E4M3"),
+ "txtfusion.layerwise_blocks.0.attn.wv.weight_scale": ([2560, 80], "U8"),
+ "txtfusion.layerwise_blocks.0.mlp.down.weight": ([2560, 6912], "F8_E4M3"),
+ "txtfusion.layerwise_blocks.0.mlp.down.weight_scale": ([2560, 216], "U8"),
+ "txtfusion.layerwise_blocks.0.mlp.gate.weight": ([6912, 2560], "F8_E4M3"),
+ "txtfusion.layerwise_blocks.0.mlp.gate.weight_scale": ([6912, 80], "U8"),
+ "txtfusion.layerwise_blocks.0.mlp.up.weight": ([6912, 2560], "F8_E4M3"),
+ "txtfusion.layerwise_blocks.0.mlp.up.weight_scale": ([6912, 80], "U8"),
+ "txtfusion.layerwise_blocks.0.postnorm.scale": ([2560], "BF16"),
+ "txtfusion.layerwise_blocks.0.prenorm.scale": ([2560], "BF16"),
+ "txtfusion.layerwise_blocks.1.attn.gate.weight": ([2560, 2560], "F8_E4M3"),
+ "txtfusion.layerwise_blocks.1.attn.gate.weight_scale": ([2560, 80], "U8"),
+ "txtfusion.layerwise_blocks.1.attn.qknorm.knorm.scale": ([128], "BF16"),
+ "txtfusion.layerwise_blocks.1.attn.qknorm.qnorm.scale": ([128], "BF16"),
+ "txtfusion.layerwise_blocks.1.attn.wk.weight": ([2560, 2560], "F8_E4M3"),
+ "txtfusion.layerwise_blocks.1.attn.wk.weight_scale": ([2560, 80], "U8"),
+ "txtfusion.layerwise_blocks.1.attn.wo.weight": ([2560, 2560], "F8_E4M3"),
+ "txtfusion.layerwise_blocks.1.attn.wo.weight_scale": ([2560, 80], "U8"),
+ "txtfusion.layerwise_blocks.1.attn.wq.weight": ([2560, 2560], "F8_E4M3"),
+ "txtfusion.layerwise_blocks.1.attn.wq.weight_scale": ([2560, 80], "U8"),
+ "txtfusion.layerwise_blocks.1.attn.wv.weight": ([2560, 2560], "F8_E4M3"),
+ "txtfusion.layerwise_blocks.1.attn.wv.weight_scale": ([2560, 80], "U8"),
+ "txtfusion.layerwise_blocks.1.mlp.down.weight": ([2560, 6912], "F8_E4M3"),
+ "txtfusion.layerwise_blocks.1.mlp.down.weight_scale": ([2560, 216], "U8"),
+ "txtfusion.layerwise_blocks.1.mlp.gate.weight": ([6912, 2560], "F8_E4M3"),
+ "txtfusion.layerwise_blocks.1.mlp.gate.weight_scale": ([6912, 80], "U8"),
+ "txtfusion.layerwise_blocks.1.mlp.up.weight": ([6912, 2560], "F8_E4M3"),
+ "txtfusion.layerwise_blocks.1.mlp.up.weight_scale": ([6912, 80], "U8"),
+ "txtfusion.layerwise_blocks.1.postnorm.scale": ([2560], "BF16"),
+ "txtfusion.layerwise_blocks.1.prenorm.scale": ([2560], "BF16"),
+ "txtfusion.projector.weight": ([1, 12], "BF16"),
+ "txtfusion.refiner_blocks.0.attn.gate.weight": ([2560, 2560], "F8_E4M3"),
+ "txtfusion.refiner_blocks.0.attn.gate.weight_scale": ([2560, 80], "U8"),
+ "txtfusion.refiner_blocks.0.attn.qknorm.knorm.scale": ([128], "BF16"),
+ "txtfusion.refiner_blocks.0.attn.qknorm.qnorm.scale": ([128], "BF16"),
+ "txtfusion.refiner_blocks.0.attn.wk.weight": ([2560, 2560], "F8_E4M3"),
+ "txtfusion.refiner_blocks.0.attn.wk.weight_scale": ([2560, 80], "U8"),
+ "txtfusion.refiner_blocks.0.attn.wo.weight": ([2560, 2560], "F8_E4M3"),
+ "txtfusion.refiner_blocks.0.attn.wo.weight_scale": ([2560, 80], "U8"),
+ "txtfusion.refiner_blocks.0.attn.wq.weight": ([2560, 2560], "F8_E4M3"),
+ "txtfusion.refiner_blocks.0.attn.wq.weight_scale": ([2560, 80], "U8"),
+ "txtfusion.refiner_blocks.0.attn.wv.weight": ([2560, 2560], "F8_E4M3"),
+ "txtfusion.refiner_blocks.0.attn.wv.weight_scale": ([2560, 80], "U8"),
+ "txtfusion.refiner_blocks.0.mlp.down.weight": ([2560, 6912], "F8_E4M3"),
+ "txtfusion.refiner_blocks.0.mlp.down.weight_scale": ([2560, 216], "U8"),
+ "txtfusion.refiner_blocks.0.mlp.gate.weight": ([6912, 2560], "F8_E4M3"),
+ "txtfusion.refiner_blocks.0.mlp.gate.weight_scale": ([6912, 80], "U8"),
+ "txtfusion.refiner_blocks.0.mlp.up.weight": ([6912, 2560], "F8_E4M3"),
+ "txtfusion.refiner_blocks.0.mlp.up.weight_scale": ([6912, 80], "U8"),
+ "txtfusion.refiner_blocks.0.postnorm.scale": ([2560], "BF16"),
+ "txtfusion.refiner_blocks.0.prenorm.scale": ([2560], "BF16"),
+ "txtfusion.refiner_blocks.1.attn.gate.weight": ([2560, 2560], "F8_E4M3"),
+ "txtfusion.refiner_blocks.1.attn.gate.weight_scale": ([2560, 80], "U8"),
+ "txtfusion.refiner_blocks.1.attn.qknorm.knorm.scale": ([128], "BF16"),
+ "txtfusion.refiner_blocks.1.attn.qknorm.qnorm.scale": ([128], "BF16"),
+ "txtfusion.refiner_blocks.1.attn.wk.weight": ([2560, 2560], "F8_E4M3"),
+ "txtfusion.refiner_blocks.1.attn.wk.weight_scale": ([2560, 80], "U8"),
+ "txtfusion.refiner_blocks.1.attn.wo.weight": ([2560, 2560], "F8_E4M3"),
+ "txtfusion.refiner_blocks.1.attn.wo.weight_scale": ([2560, 80], "U8"),
+ "txtfusion.refiner_blocks.1.attn.wq.weight": ([2560, 2560], "F8_E4M3"),
+ "txtfusion.refiner_blocks.1.attn.wq.weight_scale": ([2560, 80], "U8"),
+ "txtfusion.refiner_blocks.1.attn.wv.weight": ([2560, 2560], "F8_E4M3"),
+ "txtfusion.refiner_blocks.1.attn.wv.weight_scale": ([2560, 80], "U8"),
+ "txtfusion.refiner_blocks.1.mlp.down.weight": ([2560, 6912], "F8_E4M3"),
+ "txtfusion.refiner_blocks.1.mlp.down.weight_scale": ([2560, 216], "U8"),
+ "txtfusion.refiner_blocks.1.mlp.gate.weight": ([6912, 2560], "F8_E4M3"),
+ "txtfusion.refiner_blocks.1.mlp.gate.weight_scale": ([6912, 80], "U8"),
+ "txtfusion.refiner_blocks.1.mlp.up.weight": ([6912, 2560], "F8_E4M3"),
+ "txtfusion.refiner_blocks.1.mlp.up.weight_scale": ([6912, 80], "U8"),
+ "txtfusion.refiner_blocks.1.postnorm.scale": ([2560], "BF16"),
+ "txtfusion.refiner_blocks.1.prenorm.scale": ([2560], "BF16"),
+ "txtmlp.0.scale": ([2560], "BF16"),
+ "txtmlp.1.bias": ([6144], "BF16"),
+ "txtmlp.1.weight": ([6144, 2560], "BF16"),
+ "txtmlp.3.bias": ([6144], "BF16"),
+ "txtmlp.3.weight": ([6144, 6144], "BF16"),
+}
+
+# The `_quantization_metadata` header block, layer names exactly as the producer wrote them.
+layer_hints: dict[str, dict[str, object]] = {
+ "blocks.0.attn.gate": {"format": "mxfp8", "full_precision_matrix_mult": True},
+ "blocks.0.attn.wk": {"format": "mxfp8", "full_precision_matrix_mult": False},
+ "blocks.0.attn.wo": {"format": "mxfp8", "full_precision_matrix_mult": True},
+ "blocks.0.attn.wq": {"format": "mxfp8", "full_precision_matrix_mult": False},
+ "blocks.0.attn.wv": {"format": "mxfp8", "full_precision_matrix_mult": False},
+ "blocks.0.mlp.down": {"format": "mxfp8", "full_precision_matrix_mult": True},
+ "blocks.0.mlp.gate": {"format": "mxfp8", "full_precision_matrix_mult": False},
+ "blocks.0.mlp.up": {"format": "mxfp8", "full_precision_matrix_mult": False},
+ "txtfusion.layerwise_blocks.0.attn.gate": {"format": "mxfp8", "full_precision_matrix_mult": True},
+ "txtfusion.layerwise_blocks.0.attn.wk": {"format": "mxfp8", "full_precision_matrix_mult": False},
+ "txtfusion.layerwise_blocks.0.attn.wo": {"format": "mxfp8", "full_precision_matrix_mult": True},
+ "txtfusion.layerwise_blocks.0.attn.wq": {"format": "mxfp8", "full_precision_matrix_mult": False},
+ "txtfusion.layerwise_blocks.0.attn.wv": {"format": "mxfp8", "full_precision_matrix_mult": False},
+ "txtfusion.layerwise_blocks.0.mlp.down": {"format": "mxfp8", "full_precision_matrix_mult": True},
+ "txtfusion.layerwise_blocks.0.mlp.gate": {"format": "mxfp8", "full_precision_matrix_mult": False},
+ "txtfusion.layerwise_blocks.0.mlp.up": {"format": "mxfp8", "full_precision_matrix_mult": False},
+ "txtfusion.layerwise_blocks.1.attn.gate": {"format": "mxfp8", "full_precision_matrix_mult": True},
+ "txtfusion.layerwise_blocks.1.attn.wk": {"format": "mxfp8", "full_precision_matrix_mult": False},
+ "txtfusion.layerwise_blocks.1.attn.wo": {"format": "mxfp8", "full_precision_matrix_mult": True},
+ "txtfusion.layerwise_blocks.1.attn.wq": {"format": "mxfp8", "full_precision_matrix_mult": False},
+ "txtfusion.layerwise_blocks.1.attn.wv": {"format": "mxfp8", "full_precision_matrix_mult": False},
+ "txtfusion.layerwise_blocks.1.mlp.down": {"format": "mxfp8", "full_precision_matrix_mult": True},
+ "txtfusion.layerwise_blocks.1.mlp.gate": {"format": "mxfp8", "full_precision_matrix_mult": False},
+ "txtfusion.layerwise_blocks.1.mlp.up": {"format": "mxfp8", "full_precision_matrix_mult": False},
+ "txtfusion.refiner_blocks.0.attn.gate": {"format": "mxfp8", "full_precision_matrix_mult": True},
+ "txtfusion.refiner_blocks.0.attn.wk": {"format": "mxfp8", "full_precision_matrix_mult": False},
+ "txtfusion.refiner_blocks.0.attn.wo": {"format": "mxfp8", "full_precision_matrix_mult": True},
+ "txtfusion.refiner_blocks.0.attn.wq": {"format": "mxfp8", "full_precision_matrix_mult": False},
+ "txtfusion.refiner_blocks.0.attn.wv": {"format": "mxfp8", "full_precision_matrix_mult": False},
+ "txtfusion.refiner_blocks.0.mlp.down": {"format": "mxfp8", "full_precision_matrix_mult": True},
+ "txtfusion.refiner_blocks.0.mlp.gate": {"format": "mxfp8", "full_precision_matrix_mult": False},
+ "txtfusion.refiner_blocks.0.mlp.up": {"format": "mxfp8", "full_precision_matrix_mult": False},
+ "txtfusion.refiner_blocks.1.attn.gate": {"format": "mxfp8", "full_precision_matrix_mult": True},
+ "txtfusion.refiner_blocks.1.attn.wk": {"format": "mxfp8", "full_precision_matrix_mult": False},
+ "txtfusion.refiner_blocks.1.attn.wo": {"format": "mxfp8", "full_precision_matrix_mult": True},
+ "txtfusion.refiner_blocks.1.attn.wq": {"format": "mxfp8", "full_precision_matrix_mult": False},
+ "txtfusion.refiner_blocks.1.attn.wv": {"format": "mxfp8", "full_precision_matrix_mult": False},
+ "txtfusion.refiner_blocks.1.mlp.down": {"format": "mxfp8", "full_precision_matrix_mult": True},
+ "txtfusion.refiner_blocks.1.mlp.gate": {"format": "mxfp8", "full_precision_matrix_mult": False},
+ "txtfusion.refiner_blocks.1.mlp.up": {"format": "mxfp8", "full_precision_matrix_mult": False},
+}
diff --git a/tests/backend/model_manager/load/test_krea2_mxfp8_keys.py b/tests/backend/model_manager/load/test_krea2_mxfp8_keys.py
new file mode 100644
index 0000000000..56ac9dd37b
--- /dev/null
+++ b/tests/backend/model_manager/load/test_krea2_mxfp8_keys.py
@@ -0,0 +1,89 @@
+"""What the released MXFP8 Krea-2 build actually contains, and whether the synthetic payload matches.
+
+The MXFP8 decode is built on four assumptions about the file: the scale is `uint8`, it carries one
+entry per 32 weight elements, it is a whole number of cuBLAS tiles, and the layer says `mxfp8`
+somewhere. Until this capture all four rested on the same synthetic construction that the tests
+build, so the tests and the decode agreed without either being checked against a producer.
+
+This is the one reachable MXFP8 file, and its weights cannot be checked in (`license: other`), so the
+captured header is the reference and `mxfp8_tensors` is measured against it.
+"""
+
+import torch
+
+from invokeai.backend.quantization.block_scale_tiles import check_tile_layout
+from invokeai.backend.quantization.fp8_scaled import MXFP8_FORMAT, extract_fp8_scaled_layers
+from tests.backend.model_manager.load.state_dicts import krea2_turbo_mxfp8_keys as fixture
+from tests.fixtures.quantized_payloads import MX_BLOCK_SIZE, mxfp8_tensors
+
+KEYS = fixture.state_dict_keys
+QUANTIZED = sorted(
+ key[: -len(".weight")] for key, (_shape, dtype) in KEYS.items() if dtype == "F8_E4M3" and key.endswith(".weight")
+)
+
+
+def test_every_grid_is_one_uint8_entry_per_thirty_two_weight_elements() -> None:
+ """The block width the decode derives from the shapes. A build that changed it would be decoded
+ at the wrong granularity -- and `expand_weight_scale` would still widen the grid to the weight,
+ so it would load and generate noise rather than raise."""
+ assert QUANTIZED
+ for path in QUANTIZED:
+ (rows, columns), _dtype = KEYS[f"{path}.weight"]
+ (scale_rows, blocks), scale_dtype = KEYS[f"{path}.weight_scale"]
+
+ assert scale_dtype == "U8", path
+ assert scale_rows == rows, path
+ assert columns == blocks * MX_BLOCK_SIZE, path
+
+
+def test_every_grid_is_a_whole_number_of_cublas_tiles() -> None:
+ """`check_tile_layout` is what the de-swizzle requires, and off-tile it cannot be expressed --
+ so this is the property that decides whether the released file is decodable at all."""
+ for path in QUANTIZED:
+ (rows, _columns), _dtype = KEYS[f"{path}.weight"]
+ (_scale_rows, blocks), _scale_dtype = KEYS[f"{path}.weight_scale"]
+
+ check_tile_layout(rows, blocks)
+
+
+def test_the_header_names_every_quantized_layer_and_no_marker_does() -> None:
+ """One transport, not two: the header names them and there is no `.comfy_quant` in the file.
+
+ The decode refuses a `uint8` grid that nothing names, so for this build the header *is* the
+ evidence -- a re-upload that dropped `_quantization_metadata` would make the file unloadable
+ rather than mis-loaded, and this is the cell that would say why.
+ """
+ assert set(fixture.layer_hints) == set(QUANTIZED)
+ assert {hint["format"] for hint in fixture.layer_hints.values()} == {MXFP8_FORMAT}
+ assert not any(key.endswith(".comfy_quant") for key in KEYS)
+
+
+def test_no_hint_carries_a_block_size() -> None:
+ """Which is why the decode reads the width from the shapes and lets the marker only cross-check
+ it. A decode that required the field would refuse this build outright."""
+ assert not any("block_size" in hint for hint in fixture.layer_hints.values())
+
+
+def test_the_synthetic_payload_has_the_released_layouts_shape_relationship() -> None:
+ """The synthetic builder is what every MXFP8 cell drives; this is the one place it is held
+ against a producer.
+
+ Same relationship, not the same size: one real layer here is 6144x6144 with a 6144x192 grid, and
+ building that costs 36M elements to assert a ratio. So the ratio, the dtypes and the tile
+ condition are checked on a small layer, and the real numbers are read from the capture.
+ """
+ # One tile, all exponents 127. The released layers are 6144 wide with a 6144x192 grid; building
+ # that would cost 36M elements to assert a ratio the capture already records exactly.
+ tensors, expected = mxfp8_tensors("lin", torch.full((128, 4), 127))
+ weight, scale = tensors["lin.weight"], tensors["lin.weight_scale"]
+
+ assert weight.dtype is torch.float8_e4m3fn
+ assert scale.dtype is torch.uint8
+ assert weight.shape[1] == scale.shape[1] * MX_BLOCK_SIZE
+ assert weight.shape[0] == scale.shape[0]
+ # 127 is `2**0`: the value that makes a fold-as-multiplier off by ~127x instead of by nothing.
+ assert torch.equal(expected, torch.ones_like(expected))
+
+ layers = extract_fp8_scaled_layers(dict(tensors), layer_hints={"lin": {"format": MXFP8_FORMAT}})
+
+ assert torch.equal(layers["lin"].weight_scale, expected)
diff --git a/tests/backend/quantization/test_fp8_scaled.py b/tests/backend/quantization/test_fp8_scaled.py
index eb98231587..390fe75eae 100644
--- a/tests/backend/quantization/test_fp8_scaled.py
+++ b/tests/backend/quantization/test_fp8_scaled.py
@@ -42,7 +42,6 @@ from tests.fixtures.quantized_payloads import (
MX_BLOCK_SIZE,
mxfp8_marker,
mxfp8_tensors,
- stored_layout,
)
cuda_fp8 = pytest.mark.skipif(
@@ -1051,23 +1050,34 @@ class TestMxfp8:
@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.shape
- sd = {
- "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 {})
+ """One MXFP8 layer and its hints, the layout coming from the shared builder.
+
+ The hints stay a parameter here because half these cells are about a layer that says the
+ wrong thing about itself, or nothing at all.
+ """
+ tensors, _expected = mxfp8_tensors("lin", exponents)
+ return dict(tensors), ({"lin": marker} if marker else {})
+
+ @staticmethod
+ def _mx_layer_with_expectation(exponents: torch.Tensor) -> tuple[dict, dict, torch.Tensor]:
+ """The well-formed case, plus the decoded scale the builder says to expect."""
+ tensors, expected = mxfp8_tensors("lin", exponents)
+ return dict(tensors), {"lin": mxfp8_marker()}, expected
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."""
+ all but a few entries.
+
+ Against the expectation the shared builder returns, not a restatement of it here: that value
+ is derived from the hand-written tile formula and the spec's bias, so it is the one statement
+ of the decode that does not come from the decode.
+ """
exponents = torch.arange(128 * 4, dtype=torch.int64).reshape(128, 4) % 8 + 124
- sd, hints = self._mx_layer(exponents, {"format": "mxfp8", "block_size": 32})
+ sd, hints, expected = self._mx_layer_with_expectation(exponents)
layers = extract_fp8_scaled_layers(sd, layer_hints=hints)
- assert torch.equal(layers["lin"].weight_scale, torch.exp2(exponents.float() - 127))
+ assert torch.equal(layers["lin"].weight_scale, expected)
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
@@ -1542,10 +1552,10 @@ class TestReservationCoversTheSideChannelItHolds:
@staticmethod
def _mx_layer(rows: int = 512, blocks: int = 16) -> tuple[dict, dict, torch.nn.Module]:
exponents = (torch.arange(rows * blocks, dtype=torch.int64).reshape(rows, blocks) % 8) + 124
- tensors, _expected = mxfp8_tensors("lin", exponents)
+ sd, hints, _expected = TestMxfp8._mx_layer_with_expectation(exponents)
model = torch.nn.Module()
model.add_module("lin", torch.nn.Linear(blocks * MX_BLOCK_SIZE, rows, bias=False))
- return dict(tensors), {"lin": mxfp8_marker()}, model
+ return sd, hints, model
def test_the_decode_widens_the_grid_before_anything_reserves_for_it(self) -> None:
"""The half of the finding that is true today, so the numbers are recorded rather than
@@ -1567,16 +1577,18 @@ class TestReservationCoversTheSideChannelItHolds:
@pytest.mark.xfail(
strict=True,
reason=(
- "The clean fix presupposes PR D. Adding the mapping's bytes to this predictor cannot be "
- "unconditional: whether a scale is still resident after the split depends on whether its "
- "layer stayed fp8, which is the three-way agreement between `cast_state_dict`, this "
- "function and `split_fp8_scaled_layers` that §4.4 describes as held by call-order "
- "accident -- `TestPredictionIsSplitAware` pins `predicted == actual` against the state "
- "dict alone, and a flat term breaks it for the block-wise case the split folds. The "
- "alternative, an eighth hand-assembled term at each of the eight seams beside "
- "`predict_nvfp4_install_size`, is the per-loader assembly §0.1 already counts as a "
- "defect. §4.4's `decide(...) -> LoadPlan` with `predict_size(plan)` makes the dict and "
- "its side channel one argument, so the question cannot be asked of half of it."
+ "No fix for this belongs in this function as it stands. Adding the mapping's bytes "
+ "cannot be unconditional: whether a scale is still resident after the split depends on "
+ "whether its layer stayed fp8, so a flat term turns this function from 'bytes the state "
+ "dict will occupy' into 'peak bytes', and `TestPredictionIsSplitAware` pins the former "
+ "exactly -- measured: the flat term reddens all three `predicted == actual` "
+ "parametrizations and the under-count regression beside them. The alternative is a "
+ "second hand-assembled term at each of the nine call sites, beside the "
+ "`predict_nvfp4_install_size` each already adds by hand, which is the per-loader "
+ "assembly that keeps producing this class of gap. "
+ "Remove this marker when one object owns both the state dict and the scales recovered "
+ "from it and the reservation is computed from that object, so the size question cannot "
+ "be asked about half of the load."
),
)
def test_the_decoded_mx_grid_is_inside_the_reservation(self) -> None:
@@ -1585,6 +1597,6 @@ class TestReservationCoversTheSideChannelItHolds:
layers = extract_fp8_scaled_layers(sd, layer_hints=hints)
grid = layers["lin"].weight_scale
- predicted = predict_cast_state_dict_size(sd, torch.bfloat16, keep_fp8=False, model=model, scaled_layers=layers)
+ predicted = predict_cast_state_dict_size(sd, torch.bfloat16, keep_fp8=True, model=model, scaled_layers=layers)
assert predicted >= sd["lin.weight"].nelement() * 2 + grid.nelement() * grid.element_size()
diff --git a/tests/backend/quantization/test_quantized_payloads.py b/tests/backend/quantization/test_quantized_payloads.py
index ffeea5efba..1c9ff2023a 100644
--- a/tests/backend/quantization/test_quantized_payloads.py
+++ b/tests/backend/quantization/test_quantized_payloads.py
@@ -17,12 +17,13 @@ move in opposite directions and cancel. Those are pinned separately below, again
the dtype's range is rather than against the fixture's own numbers.
"""
+import pytest
import torch
from invokeai.backend.quantization.fp8_scaled import dequantize_fp8_scaled, extract_fp8_scaled_layers
from invokeai.backend.quantization.int8_convrot import CONVROT_GROUP_SIZE, Int8ConvrotLinear
from invokeai.backend.quantization.nvfp4 import NVFP4Linear
-from tests.fixtures.quantized_payloads import nvfp4_signed_tensors, quantize_convrot, quantize_scaled_fp8
+from tests.fixtures.quantized_payloads import mxfp8_tensors, nvfp4_signed_tensors, quantize_convrot, quantize_scaled_fp8
CPU = torch.device("cpu")
@@ -129,3 +130,20 @@ def test_the_nvfp4_payload_unpacks_to_the_exact_weights_it_claims() -> None:
assert linear.in_features == 64, "the packed weight's logical width was not doubled"
assert torch.equal(decoded, expected)
+
+
+def test_an_mx_grid_that_is_not_whole_tiles_is_refused_rather_than_silently_zeroed() -> None:
+ """`stored_layout`'s index formula is a bijection only over whole tiles.
+
+ Off-tile it leaves NaN in the positions it never writes, and `.to(torch.uint8)` turns those into
+ zeros -- an exponent byte of 0 is `2**-127`, so the payload would look built and decode to
+ nothing. The builder is shared now, so this would be wrong in every suite that used it.
+ """
+ with pytest.raises(ValueError):
+ mxfp8_tensors("lin", torch.full((64, 4), 127))
+
+ with pytest.raises(ValueError):
+ mxfp8_tensors("lin", torch.full((128, 3), 127))
+
+ tensors, _expected = mxfp8_tensors("lin", torch.full((128, 4), 127))
+ assert tensors["lin.weight_scale"].shape == (128, 4)
diff --git a/tests/fixtures/quantized_payloads.py b/tests/fixtures/quantized_payloads.py
index f7e394cb0c..2dba76f065 100644
--- a/tests/fixtures/quantized_payloads.py
+++ b/tests/fixtures/quantized_payloads.py
@@ -17,7 +17,7 @@ from typing import Any, NamedTuple
import torch
-from invokeai.backend.quantization.fp8_scaled import MXFP8_FORMAT
+from invokeai.backend.quantization.block_scale_tiles import check_tile_layout
from invokeai.backend.quantization.int8_convrot import CONVROT_GROUP_SIZE, build_regular_hadamard
# e4m3's largest finite magnitude. A per-tensor scaled-fp8 export divides by this, so that the
@@ -30,12 +30,12 @@ INT8_LEVELS = 127.0
# The two nvfp4 codes worth +1.0 and -1.0 in E2M1. Paired with a block scale and a global scale they
# give a weight whose exact value is known without depending on the rest of the E2M1 table.
-#: One MX block is 32 elements wide in every published build; the marker only cross-checks it.
-MX_BLOCK_SIZE = 32
-
NVFP4_CODE_PLUS_ONE = 2
NVFP4_CODE_MINUS_ONE = 10
+# One MX block is 32 elements wide in every published build; the marker only cross-checks it.
+MX_BLOCK_SIZE = 32
+
def comfy_quant_marker(marker: Mapping[str, Any], *, pad: int = 0) -> torch.Tensor:
"""The per-tensor ``.comfy_quant`` blob: UTF-8 JSON in a ``uint8`` tensor.
@@ -167,20 +167,25 @@ def mxfp8_tensors(
) -> tuple[dict[str, torch.Tensor], torch.Tensor]:
"""One MXFP8 layer in checkpoint layout, and the block-wise float scale it decodes to.
- MXFP8 is the scheme this repo only ever *refuses or folds* -- there is no kernel for it below
- Blackwell -- which is exactly why it was missing here: the payload builders were drawn from what
- `backend/quantization` decodes, and a layout nobody decodes for the matmul fell out of the set.
- It is also the worst payload to leave unbuilt. The grid is E8M0 exponent *bytes*, so 127 means
- `2**0`; folded as linear multipliers the weights come out around 127x too large, at the right
- shape and the right dtype, with nothing raised and nothing logged.
+ This builder existed already, private to `tests/backend/quantization/test_fp8_scaled.py`, which
+ now imports it from here instead. That is the whole of the change: MXFP8 was tested, it just was
+ not available to the other suites, so a seam-level cell had to hand-roll the layout -- and the
+ layout is the part worth getting from one place, because getting it wrong is silent.
- The grid is stored in cuBLAS tiles (:func:`stored_layout`), because that is how both published
- builds store it and reading it row-major pairs blocks with the wrong rows.
+ The grid is E8M0 exponent *bytes*, so 127 means `2**0`; folded as linear multipliers the weights
+ come out around 127x too large, at the right shape and the right dtype, with nothing raised and
+ nothing logged. And it is stored in cuBLAS tiles (:func:`stored_layout`), because that is how
+ both published builds store it; read row-major it pairs blocks with the wrong rows.
- The weight is all ones, so the decoded scale *is* the expected weight -- an assertion that moves
- by a factor of `2**(byte - 127)` per block if either half of the decode is skipped.
+ The weight is all ones, so the returned scale *is* the expected decoded weight -- an expectation
+ that moves by `2**(byte - 127)` per block if either half of the decode is skipped. It is
+ independent of the decode: the tile order comes from the hand-written index formula in
+ :func:`stored_layout`, and the bias is the spec's 127 rather than `_E8M0_BIAS`.
"""
rows, blocks = exponents.shape
+ # `stored_layout` is a bijection only over whole tiles. Off-tile, its `flat` keeps NaNs, and
+ # `.to(torch.uint8)` turns those into zeros -- every scale silently becomes `2**-127`.
+ check_tile_layout(rows, blocks)
tensors = {
f"{path}.weight": torch.ones(rows, blocks * block_size).to(torch.float8_e4m3fn),
f"{path}.weight_scale": stored_layout(exponents.to(torch.float64)).to(torch.uint8),
@@ -191,6 +196,8 @@ def mxfp8_tensors(
def mxfp8_marker(*, block_size: int = MX_BLOCK_SIZE) -> dict[str, object]:
"""What a layer has to say about itself before the decode will read its grid.
- A `uint8` tensor beside an fp8 weight is otherwise just an unknown producer's convention.
+ A `uint8` tensor beside an fp8 weight is otherwise just an unknown producer's convention. The
+ format string is spelled out rather than imported from `fp8_scaled`: it is what the *producer*
+ writes, so a rename on our side has to be caught by a test, not mirrored by one.
"""
- return {"format": MXFP8_FORMAT, "block_size": block_size}
+ return {"format": "mxfp8", "block_size": block_size}