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): state the MX reservation gap at its real size, and check the width against the file

Alexander Eichhorn3c8fa6401e54
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
index 4ee2196aed..0144db3c1b 100644
--- 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
@@ -15,8 +15,8 @@ entry per 32 weight elements, a whole number of cuBLAS tiles, and the layer is n
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.
+No weights can be checked in -- this build is `license: other` -- so what is recorded is the layout,
+and the block width the synthetic payloads are built from is checked against the width stored here.
"""
state_dict_keys: dict[str, tuple[list[int], str]] = {
diff --git a/tests/backend/model_manager/load/test_krea2_mxfp8_keys.py b/tests/backend/model_manager/load/test_krea2_mxfp8_keys.py
index 56ac9dd37b..1212ece107 100644
--- a/tests/backend/model_manager/load/test_krea2_mxfp8_keys.py
+++ b/tests/backend/model_manager/load/test_krea2_mxfp8_keys.py
@@ -5,14 +5,15 @@ entry per 32 weight elements, it is a whole number of cuBLAS tiles, and the laye
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.
+This is the one reachable MXFP8 file, and its weights cannot be checked in (`license: other`), so
+what is recorded is the layout. Four cells read it directly; a fifth takes the block width out of it
+and holds `MX_BLOCK_SIZE` -- the number every synthetic MXFP8 payload is built from -- 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 invokeai.backend.quantization.fp8_scaled import MXFP8_FORMAT
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
@@ -64,26 +65,27 @@ def test_no_hint_carries_a_block_size() -> None:
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.
+def test_the_block_width_the_builder_uses_is_the_one_the_released_build_stores() -> None:
+ """The one number the synthetic payload and the real file have to agree on.
- 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.
+ `MX_BLOCK_SIZE` is what every MXFP8 cell builds its grid from, and `decode_mx_block_scales` infers
+ the same width from the shapes it is given. Both sides being our own constant is how a scheme gets
+ tested against itself, so the width is read out of the capture here and our constant is checked
+ against it -- 40 real layers, five distinct geometries.
+
+ Deliberately not repeated here: that a distinct grid survives the de-swizzle. A constant grid is
+ invariant under every permutation, so it cannot see a tile error at all; that is
+ `TestMxfp8.test_the_exponents_are_decoded_and_unswizzled`, which uses varying exponents.
"""
- # 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"]
+ widths = set()
+ for path in QUANTIZED:
+ (_rows, columns), _dtype = KEYS[f"{path}.weight"]
+ (_scale_rows, blocks), _scale_dtype = KEYS[f"{path}.weight_scale"]
+ widths.add(columns // blocks)
- 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))
+ assert widths == {MX_BLOCK_SIZE}
- layers = extract_fp8_scaled_layers(dict(tensors), layer_hints={"lin": {"format": MXFP8_FORMAT}})
+ tensors, _expected = mxfp8_tensors("lin", torch.full((128, 4), 127))
+ weight, scale = tensors["lin.weight"], tensors["lin.weight_scale"]
- assert torch.equal(layers["lin"].weight_scale, expected)
+ assert weight.shape[1] // scale.shape[1] == widths.pop()
diff --git a/tests/backend/model_manager/load/test_qwen_image_nvfp4_loader.py b/tests/backend/model_manager/load/test_qwen_image_nvfp4_loader.py
index 1f82b299a6..436e4c64c9 100644
--- a/tests/backend/model_manager/load/test_qwen_image_nvfp4_loader.py
+++ b/tests/backend/model_manager/load/test_qwen_image_nvfp4_loader.py
@@ -323,8 +323,11 @@ def test_an_nvfp4_layer_missing_its_global_scale_is_refused_before_the_cache_is_
those two statements secures.
"""
state_dict = {
- "model.layers.0.self_attn.q_proj.weight": torch.zeros(64, 128, dtype=torch.uint8),
- "model.layers.0.self_attn.q_proj.weight_scale": torch.zeros(64, 16).to(torch.float8_e4m3fn),
+ # 128 rows and a 16-block grid: a whole number of cuBLAS tiles, i.e. a layer a real build
+ # could hold. The refusal reads only the key pairing and the uint8 dtype, so it fires either
+ # way -- but a shape no build can contain is the wrong thing to assert the state against.
+ "model.layers.0.self_attn.q_proj.weight": torch.zeros(128, 128, dtype=torch.uint8),
+ "model.layers.0.self_attn.q_proj.weight_scale": torch.zeros(128, 16).to(torch.float8_e4m3fn),
}
checkpoint = tmp_path / "qwen_2.5_vl_7b_nvfp4_half.safetensors"
checkpoint.touch()
@@ -342,16 +345,15 @@ def test_the_transformer_refuses_an_nvfp4_layer_missing_its_global_scale_before_
"""The same degraded half-state at the transformer seam, which had no `Seam` of its own.
The encoder cell above covers the other Qwen-Image seam; this one is the transformer. Declared
- through the shared driver rather than the
- hand-rolled loader the cells above use, because `run.reserved` is the assertion -- the recorded
- reservations are what say "before", and a `MagicMock` would only say "not called at all".
+ through the shared driver rather than the hand-rolled loader the cells above use, because
+ `run.reserved` is the assertion: the recorded reservations are what say "before", where a
+ `MagicMock` would only say "not called at all".
"""
import diffusers
state_dict = {
"img_in.weight": torch.randn(128, 64),
"img_in.bias": torch.randn(128),
- # 128 rows and 4 blocks: a whole number of cuBLAS tiles, i.e. a layer a real build could hold.
"transformer_blocks.0.attn.to_q.weight": torch.zeros(128, 32, dtype=torch.uint8),
"transformer_blocks.0.attn.to_q.weight_scale": torch.zeros(128, 4).to(torch.float8_e4m3fn),
}
diff --git a/tests/backend/quantization/test_fp8_scaled.py b/tests/backend/quantization/test_fp8_scaled.py
index 390fe75eae..25e4d3f9fc 100644
--- a/tests/backend/quantization/test_fp8_scaled.py
+++ b/tests/backend/quantization/test_fp8_scaled.py
@@ -1541,12 +1541,26 @@ class TestReservationCoversTheSideChannelItHolds:
`make_room`, so those bytes are resident while the cache decides what to evict -- and they are in
no reservation, because the predictor walks the state dict they are no longer in.
- Measured on a 512x512 toy layer: the prediction comes back at exactly the widened weight,
- 524288 bytes, while the decoded grid holds another 32768 -- 6.2% short, in the direction that
- makes the cache hand out room that is already spoken for. The grid is one entry per 32 weight
- elements, so on Comfy-Org's 12 GB MXFP8 build it is around 1.5 GB. Same class as the overshoots
- recorded at `z_image.py:697` and `krea2.py:588`; it reads as a rounding error only because one
- reachable build uses the scheme.
+ Measured on a 512x512 toy layer, per element of the weight:
+
+ predicted (the widened bf16 weight) 2.000 B/element 524288 B
+ decoded grids, held for every layer at once 0.125 B/element 32768 B
+ per-layer fold transients (below) 12.000 B/element
+
+ The grid is the *smallest* unreserved term, and the only one held for the whole quantized set at
+ once, which is why it is what this class pins: one entry per 32 weight elements, so around 1.5 GB
+ on Comfy-Org's 12 GB MXFP8 build.
+
+ The larger term is transient and bounded differently. `dequantize_fp8_scaled` folds one layer at a
+ time, and for a block-wise grid `expand_weight_scale` `repeat_interleave`s it to the weight's full
+ width in float32 -- 4 B/element -- beside `weight.float()` and the float32 product, so the peak is
+ ~14 B/element of the *largest* layer against 2 predicted. `int8_convrot.py:607` records the policy
+ that absorbs such a transient in the reservation's slack, on the grounds that "the widened set is
+ by construction the small one". That justification does not transfer here: a block-wise scale is
+ never matmul-usable (`is_matmul_usable_scale`), so for MXFP8 the widened set is every quantized
+ Linear in the file.
+
+ Same class as the overshoots recorded at `z_image.py:697` and `krea2.py:588`.
"""
@staticmethod
@@ -1569,8 +1583,11 @@ class TestReservationCoversTheSideChannelItHolds:
assert "lin.weight_scale" not in sd
assert grid.dtype is torch.float32 and stored_bytes * 4 == grid.nelement() * grid.element_size()
+ # `keep_fp8=True`, which is what the seams that can receive an MX build pass. The layer is
+ # charged 2 B/element either way -- a block-wise scale fails `is_matmul_usable_scale` -- but
+ # this is the branch where `scaled_layers` and `model` are consulted at all.
assert (
- predict_cast_state_dict_size(sd, torch.bfloat16, keep_fp8=False, model=model, scaled_layers=layers)
+ predict_cast_state_dict_size(sd, torch.bfloat16, keep_fp8=True, model=model, scaled_layers=layers)
== sd["lin.weight"].nelement() * 2
)
@@ -1592,7 +1609,7 @@ class TestReservationCoversTheSideChannelItHolds:
),
)
def test_the_decoded_mx_grid_is_inside_the_reservation(self) -> None:
- """What the reservation should cover. Strict, so PR D cannot land without removing it."""
+ """What the reservation should cover. Strict, so the fix cannot land without removing it."""
sd, hints, model = self._mx_layer()
layers = extract_fp8_scaled_layers(sd, layer_hints=hints)
grid = layers["lin"].weight_scale
diff --git a/tests/backend/quantization/test_quantized_payloads.py b/tests/backend/quantization/test_quantized_payloads.py
index 1c9ff2023a..f35ddf6e97 100644
--- a/tests/backend/quantization/test_quantized_payloads.py
+++ b/tests/backend/quantization/test_quantized_payloads.py
@@ -139,10 +139,10 @@ def test_an_mx_grid_that_is_not_whole_tiles_is_refused_rather_than_silently_zero
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):
+ with pytest.raises(ValueError, match="tile layout"):
mxfp8_tensors("lin", torch.full((64, 4), 127))
- with pytest.raises(ValueError):
+ with pytest.raises(ValueError, match="tile layout"):
mxfp8_tensors("lin", torch.full((128, 3), 127))
tensors, _expected = mxfp8_tensors("lin", torch.full((128, 4), 127))