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
test(quantization): build MXFP8 payloads, and record the grid the reservation misses
Alexander Eichhorne4439507b407
diff --git a/tests/backend/quantization/test_block_scale_tiles.py b/tests/backend/quantization/test_block_scale_tiles.pyindex 7ea0a04920..c596bf5a33 100644--- a/tests/backend/quantization/test_block_scale_tiles.py+++ b/tests/backend/quantization/test_block_scale_tiles.py@@ -10,22 +10,7 @@ import pytestimport torchfrom 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)+from tests.fixtures.quantized_payloads import stored_layout@pytest.mark.parametrize("shape", [(128, 4), (128, 8), (256, 16), (384, 8)])diff --git a/tests/backend/quantization/test_fp8_scaled.py b/tests/backend/quantization/test_fp8_scaled.pyindex 0caec17603..eb98231587 100644--- a/tests/backend/quantization/test_fp8_scaled.py+++ b/tests/backend/quantization/test_fp8_scaled.py@@ -38,7 +38,12 @@ 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_layout+from tests.fixtures.quantized_payloads import (+ MX_BLOCK_SIZE,+ mxfp8_marker,+ mxfp8_tensors,+ stored_layout,+)cuda_fp8 = pytest.mark.skipif(not (torch.cuda.is_available() and device_supports_fp8_matmul(torch.device("cuda"))),@@ -1515,3 +1520,71 @@ class TestMalformedWeightScale:tensor a (32) must match tensor b (7)" from inside the fold, naming neither layer nor file."""with pytest.raises(ValueError, match="neither per-tensor nor per-output-channel"):expand_weight_scale(torch.ones(32, 16), torch.full((7,), 2.0))+++class TestReservationCoversTheSideChannelItHolds:+ """The reservation is made *after* the side channel has been taken out of the state dict.++ `extract_fp8_scaled_layers` pops every scale key and hands back a mapping of tensors, and for an+ MXFP8 layer it does more than move them: `decode_mx_block_scales` replaces the stored `uint8`+ exponent grid with a float one, four times the size. That happens before the caller's+ `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.+ """++ @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)+ 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++ 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+ argued: the stored grid leaves the state dict and a four-times-larger one takes its place in+ a mapping the predictor is handed but does not weigh."""+ sd, hints, model = self._mx_layer()+ stored_bytes = sd["lin.weight_scale"].nelement() * sd["lin.weight_scale"].element_size()++ layers = extract_fp8_scaled_layers(sd, layer_hints=hints)+ grid = layers["lin"].weight_scale++ assert "lin.weight_scale" not in sd+ assert grid.dtype is torch.float32 and stored_bytes * 4 == grid.nelement() * grid.element_size()+ assert (+ predict_cast_state_dict_size(sd, torch.bfloat16, keep_fp8=False, model=model, scaled_layers=layers)+ == sd["lin.weight"].nelement() * 2+ )++ @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."+ ),+ )+ 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."""+ sd, hints, model = self._mx_layer()+ 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)++ assert predicted >= sd["lin.weight"].nelement() * 2 + grid.nelement() * grid.element_size()diff --git a/tests/backend/quantization/test_nvfp4.py b/tests/backend/quantization/test_nvfp4.pyindex 7f385b78c6..f71b3fa4a5 100644--- a/tests/backend/quantization/test_nvfp4.py+++ b/tests/backend/quantization/test_nvfp4.py@@ -30,8 +30,7 @@ from invokeai.backend.quantization.nvfp4 import (predict_nvfp4_install_size,split_nvfp4_rows,)-from tests.backend.quantization.test_block_scale_tiles import stored_layout-from tests.fixtures.quantized_payloads import comfy_quant_marker, nvfp4_tensors+from tests.fixtures.quantized_payloads import comfy_quant_marker, nvfp4_tensors, stored_layoutFIXTURE = Path(__file__).parent / "data" / "z_image_turbo_nvfp4_slices.safetensors"diff --git a/tests/fixtures/quantized_payloads.py b/tests/fixtures/quantized_payloads.pyindex e14e2e1afd..f7e394cb0c 100644--- a/tests/fixtures/quantized_payloads.py+++ b/tests/fixtures/quantized_payloads.py@@ -17,6 +17,7 @@ from typing import Any, NamedTupleimport torch+from invokeai.backend.quantization.fp8_scaled import MXFP8_FORMATfrom 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@@ -29,6 +30,9 @@ 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 = 2NVFP4_CODE_MINUS_ONE = 10@@ -140,3 +144,53 @@ def nvfp4_signed_tensors(path: str, positive: torch.Tensor) -> tuple[dict[str, tcodes = nvfp4_codes(positive)tensors = nvfp4_tensors(path, codes, block_scale=2.0, global_scale=0.25)return tensors, torch.where(positive, 0.5, -0.5)+++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)+++def mxfp8_tensors(+ path: str, exponents: torch.Tensor, *, block_size: int = MX_BLOCK_SIZE+) -> 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.++ 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 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.+ """+ rows, blocks = exponents.shape+ 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),+ }+ return tensors, torch.exp2(exponents.float() - 127)+++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.+ """+ return {"format": MXFP8_FORMAT, "block_size": block_size}