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: share the quantized payload builders and the loader seam driver
Alexander Eichhorn82f09f03e46b
diff --git a/tests/backend/model_manager/load/test_flux1_int8_convrot_loader.py b/tests/backend/model_manager/load/test_flux1_int8_convrot_loader.pyindex 8103815cc8..129af35f09 100644--- a/tests/backend/model_manager/load/test_flux1_int8_convrot_loader.py+++ b/tests/backend/model_manager/load/test_flux1_int8_convrot_loader.py@@ -10,21 +10,21 @@ loader that ignored the rotation would produce a weight that loads cleanly and g"""import json-from types import SimpleNamespace-from unittest.mock import MagicMockimport pytestimport torchfrom invokeai.backend.flux.model import FluxParamsfrom invokeai.backend.model_manager.configs.main import Main_Checkpoint_FLUX_Config+from invokeai.backend.model_manager.load.model_loaders import fluxfrom invokeai.backend.model_manager.load.model_loaders.flux import FluxCheckpointModelfrom invokeai.backend.model_manager.taxonomy import FluxVariantTypefrom invokeai.backend.quantization.int8_convrot import (CONVROT_GROUP_SIZE,Int8ConvrotLinear,- build_regular_hadamard,)+from tests.fixtures.loader_seams import Seam, prepare+from tests.fixtures.quantized_payloads import comfy_quant_marker, quantize_convrot, quantize_scaled_fp8# As the file carries it: rotated along the input dim, per-output-channel scales.MARKER = {"format": "int8_tensorwise", "per_row": True, "convrot": True, "convrot_groupsize": CONVROT_GROUP_SIZE}@@ -61,21 +61,6 @@ QUANTIZED = ()-def _marker_blob(marker: dict) -> torch.Tensor:- return torch.frombuffer(bytearray(json.dumps(marker).encode("utf-8")), dtype=torch.uint8).clone()---def _quantize_convrot(weight: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:- """Mirror of comfy-quants: rotate along the input dim, then per-output-channel int8."""- out_features, in_features = weight.shape- hadamard = build_regular_hadamard(CONVROT_GROUP_SIZE, dtype=weight.dtype)- rotated = (weight.view(out_features, in_features // CONVROT_GROUP_SIZE, CONVROT_GROUP_SIZE) @ hadamard.T).view(- out_features, in_features- )- scale = rotated.abs().amax(dim=1, keepdim=True) / 127.0- return torch.clamp(torch.round(rotated / scale), -128, 127).to(torch.int8), scale.to(torch.float32)--# Stored fp32 rather than bf16, because a repack that mixes precisions in its dense remainder is# what makes `cast_unquantized` observable at all: `load_state_dict(assign=True)` assigns storage# dtypes straight through, so without the cast this layer lands as fp32 inside a bf16 model -- and@@ -103,46 +88,47 @@ def _checkpoint(marker: dict | None = MARKER) -> tuple[dict[str, torch.Tensor],key = f"{path}.weight"weight = state_dict[key].float()originals[path] = weight- state_dict[key], state_dict[f"{path}.weight_scale"] = _quantize_convrot(weight)+ payload = quantize_convrot(weight)+ state_dict[key], state_dict[f"{path}.weight_scale"] = payload.codes, payload.scaleif marker is not None:- state_dict[f"{path}.comfy_quant"] = _marker_blob(marker)+ state_dict[f"{path}.comfy_quant"] = comfy_quant_marker(marker)return state_dict, originals-def _driver(monkeypatch, tmp_path, state_dict: dict, trace: dict | None = None, header: dict | None = None):- """Drive the loader with the cache recorded rather than stubbed out."""- import invokeai.backend.model_manager.load.model_loaders.flux as module+SEAM = Seam(+ loader=FluxCheckpointModel,+ module=flux,+ compute_dtype=torch.bfloat16,+ # `_load_from_singlefile` never reaches the FP8 Storage pass, and the tests that do reach it+ # through `_load_model` install their own counter. Nothing here would read this stub, and a+ # stub nothing reads is one more thing to keep true.+ casts_fp8_storage=False,+)- recorded = trace if trace is not None else {}- recorded.setdefault("reserved", None)+def _driver(monkeypatch, tmp_path, state_dict: dict, header: dict | None = None):checkpoint = tmp_path / "flux1-dev-int8-convrot.safetensors"checkpoint.touch()config = Main_Checkpoint_FLUX_Config.model_construct(path=str(checkpoint), name="flux1-dev-int8", variant=FluxVariantType.Dev)- loader = object.__new__(FluxCheckpointModel)- loader._ram_cache = SimpleNamespace(make_room=lambda reserved: recorded.__setitem__("reserved", reserved))- loader._logger = MagicMock()- loader._torch_device = torch.device("cpu")- loader._torch_dtype = torch.bfloat16+ def geometry(patch):+ patch.setattr(flux, "get_flux_transformers_params", lambda _variant: TINY)+ # Both spellings of the same decision: the module-level helper, and the loader method that+ # supersedes it once FP8 Storage counts as a consumer too. `raising=False` tolerates the+ # module symbol being gone.+ patch.setattr(flux, "should_keep_fp8_weights", lambda _device: False, raising=False)- monkeypatch.setattr(module, "load_file", lambda _path: state_dict)- # Both spellings of the same decision: the module-level helper, and the loader method that- # supersedes it once FP8 Storage counts as a consumer too. Setting both keeps this fixture- # working either way -- an instance attribute shadows the method when it exists, and- # `raising=False` tolerates the module symbol being gone.- monkeypatch.setattr(module, "should_keep_fp8_weights", lambda _device: False, raising=False)- loader._keep_fp8_weights = lambda _config, _submodel=None: False- monkeypatch.setattr(module, "read_safetensors_metadata", lambda _path, _logger: header)- monkeypatch.setattr(module, "get_flux_transformers_params", lambda _variant: TINY)- return loader, config+ run = prepare(SEAM, monkeypatch, state_dict=state_dict, metadata=header, geometry=geometry)+ # An instance attribute shadows the method, which is what keeps this working either way.+ run.loader._keep_fp8_weights = lambda _config, _submodel=None: False+ return run, config-def _load(monkeypatch, tmp_path, state_dict, trace: dict | None = None, header: dict | None = None):- loader, config = _driver(monkeypatch, tmp_path, state_dict, trace, header)- return loader._load_from_singlefile(config)+def _load(monkeypatch, tmp_path, state_dict, header: dict | None = None):+ run, config = _driver(monkeypatch, tmp_path, state_dict, header)+ return run.load(config), rundef test_an_int8_checkpoint_stays_int8_and_un_rotates(monkeypatch, tmp_path) -> None:@@ -155,7 +141,7 @@ def test_an_int8_checkpoint_stays_int8_and_un_rotates(monkeypatch, tmp_path) ->"""state_dict, originals = _checkpoint()- model = _load(monkeypatch, tmp_path, state_dict)+ model, _ = _load(monkeypatch, tmp_path, state_dict)for path in QUANTIZED:layer = model.get_submodule(path)@@ -179,7 +165,7 @@ def test_the_biases_of_the_quantized_layers_survive(monkeypatch, tmp_path) -> Noexpected = {path: state_dict[f"{path}.bias"].clone() for path in QUANTIZED if f"{path}.bias" in state_dict}assert expected, "fixture carries no biases on the quantized layers"- model = _load(monkeypatch, tmp_path, state_dict)+ model, _ = _load(monkeypatch, tmp_path, state_dict)for path, bias in expected.items():assert torch.equal(model.get_submodule(path).bias.to(bias.dtype), bias), path@@ -192,9 +178,8 @@ def test_the_reservation_charges_each_payload_its_stored_width(monkeypatch, tmp_"""state_dict, _ = _checkpoint()before_load = {key: value.clone() for key, value in state_dict.items()}- trace: dict = {}- _load(monkeypatch, tmp_path, state_dict, trace)+ _, run = _load(monkeypatch, tmp_path, state_dict)# One byte per code; its per-output-channel scale stays at the fp32 it is pinned at; the marker# and the activation scale are dropped before the load and charged nothing; everything else@@ -207,7 +192,7 @@ def test_the_reservation_charges_each_payload_its_stored_width(monkeypatch, tmp_continueexpected += tensor.nelement() * (tensor.element_size() if key in pinned else torch.bfloat16.itemsize)- assert trace["reserved"] == expected+ assert run.reserved[-1] == expecteddef test_an_int8_weight_without_a_marker_is_refused(monkeypatch, tmp_path) -> None:@@ -227,7 +212,7 @@ def test_a_checkpoint_that_declares_int8_only_in_its_header_still_loads(monkeypastate_dict, originals = _checkpoint(marker=None)header = {"_quantization_metadata": json.dumps({"layers": dict.fromkeys(QUANTIZED, MARKER)})}- model = _load(monkeypatch, tmp_path, state_dict, header=header)+ model, _ = _load(monkeypatch, tmp_path, state_dict, header=header)for path in QUANTIZED:layer = model.get_submodule(path)@@ -252,7 +237,7 @@ def test_a_per_layer_marker_wins_over_the_header(monkeypatch, tmp_path) -> None:state_dict[f"{path}.weight_scale"] = scale.to(torch.float32)header = {"_quantization_metadata": json.dumps({"layers": dict.fromkeys(QUANTIZED, MARKER)})}- model = _load(monkeypatch, tmp_path, state_dict, header=header)+ model, _ = _load(monkeypatch, tmp_path, state_dict, header=header)assert model.get_submodule(QUANTIZED[0]).convrot is False@@ -270,7 +255,7 @@ def test_a_header_that_names_a_layer_this_file_does_not_quantize_is_ignored(monkstate_dict[f"{path}.weight"] = originals[path].to(torch.bfloat16)header = {"_quantization_metadata": json.dumps({"layers": dict.fromkeys(QUANTIZED, MARKER)})}- model = _load(monkeypatch, tmp_path, state_dict, header=header)+ model, _ = _load(monkeypatch, tmp_path, state_dict, header=header)assert not any(isinstance(module, Int8ConvrotLinear) for module in model.modules())@@ -285,7 +270,7 @@ def test_an_int8_weight_the_transformer_does_not_consume_is_tolerated(monkeypatcstate_dict, _ = _checkpoint()state_dict["text_encoders.t5xxl.block.0.attn.q.weight"] = torch.zeros(8, 8, dtype=torch.int8)- model = _load(monkeypatch, tmp_path, state_dict)+ model, _ = _load(monkeypatch, tmp_path, state_dict)assert isinstance(model.get_submodule(QUANTIZED[0]), Int8ConvrotLinear)@@ -294,10 +279,9 @@ def test_a_file_mixing_int8_with_scaled_fp8_is_refused(monkeypatch, tmp_path) ->"""Inside the int8 branch the fp8 pipeline is skipped entirely, so an fp8 layer that came alongwould be cast to bf16 without its scale -- off by `1/weight_scale`, with nothing logged."""state_dict, _ = _checkpoint()- weight = state_dict["double_blocks.0.img_attn.proj.weight"].float()- scale = weight.abs().max() / 448.0- state_dict["double_blocks.0.img_attn.proj.weight"] = (weight / scale).to(torch.float8_e4m3fn)- state_dict["double_blocks.0.img_attn.proj.weight_scale"] = scale.to(torch.float32)+ fp8 = quantize_scaled_fp8(state_dict["double_blocks.0.img_attn.proj.weight"].float())+ state_dict["double_blocks.0.img_attn.proj.weight"] = fp8.codes+ state_dict["double_blocks.0.img_attn.proj.weight_scale"] = fp8.scalewith pytest.raises(ValueError, match="mixing int8_tensorwise with scaled fp8"):_load(monkeypatch, tmp_path, state_dict)@@ -311,7 +295,7 @@ def test_a_plain_checkpoint_still_takes_the_fp8_path(monkeypatch, tmp_path) -> Ndel state_dict[f"{path}.weight_scale"]state_dict[f"{path}.weight"] = originals[path].to(torch.bfloat16)- model = _load(monkeypatch, tmp_path, state_dict)+ model, _ = _load(monkeypatch, tmp_path, state_dict)assert not any(isinstance(module, Int8ConvrotLinear) for module in model.modules())for path in QUANTIZED:@@ -327,7 +311,7 @@ def test_the_dense_remainder_is_cast_to_the_compute_dtype(monkeypatch, tmp_path)state_dict, _ = _checkpoint()assert state_dict[STORED_FP32].dtype is torch.float32, "fixture no longer exercises the cast"- model = _load(monkeypatch, tmp_path, state_dict)+ model, _ = _load(monkeypatch, tmp_path, state_dict)assert model.img_in.weight.dtype is torch.bfloat16@@ -343,10 +327,11 @@ def test_the_fp8_storage_pass_is_not_offered_an_int8_model(monkeypatch, tmp_pathstate_dict, _ = _checkpoint()calls: list[str] = []- loader, config = _driver(monkeypatch, tmp_path, state_dict)- loader._apply_fp8_layerwise_casting = lambda model, *_args: calls.append("cast") or model+ run, config = _driver(monkeypatch, tmp_path, state_dict)+ run.loader._apply_fp8_layerwise_casting = lambda model, *_args: calls.append("cast") or model- model = loader._load_model(config, SubModelType.Transformer)+ # `_load_model`, not the seam's `_load_from_singlefile`: the FP8 Storage pass sits one level up.+ model = run.loader._load_model(config, SubModelType.Transformer)assert calls == []assert any(isinstance(module, Int8ConvrotLinear) for module in model.modules())@@ -363,10 +348,11 @@ def test_a_dense_checkpoint_still_reaches_the_fp8_storage_pass(monkeypatch, tmp_del state_dict[f"{path}.weight_scale"]state_dict[f"{path}.weight"] = originals[path].to(torch.bfloat16)calls: list[str] = []- loader, config = _driver(monkeypatch, tmp_path, state_dict)- loader._apply_fp8_layerwise_casting = lambda model, *_args: calls.append("cast") or model+ run, config = _driver(monkeypatch, tmp_path, state_dict)+ run.loader._apply_fp8_layerwise_casting = lambda model, *_args: calls.append("cast") or model- model = loader._load_model(config, SubModelType.Transformer)+ # `_load_model`, not the seam's `_load_from_singlefile`: the FP8 Storage pass sits one level up.+ model = run.loader._load_model(config, SubModelType.Transformer)assert calls == ["cast"]assert not any(isinstance(module, Int8ConvrotLinear) for module in model.modules())diff --git a/tests/backend/model_manager/load/test_flux2_int8_convrot_loader.py b/tests/backend/model_manager/load/test_flux2_int8_convrot_loader.pyindex b8c7323ef8..5e32218a11 100644--- a/tests/backend/model_manager/load/test_flux2_int8_convrot_loader.py+++ b/tests/backend/model_manager/load/test_flux2_int8_convrot_loader.py@@ -11,17 +11,18 @@ There the codes are scaled but never dequantized to a dtype torch computes in."""import json-from types import SimpleNamespace-from unittest.mock import MagicMockimport pytestimport torchfrom invokeai.backend.model_manager.configs.main import Main_Checkpoint_Flux2_Config+from invokeai.backend.model_manager.load.model_loaders import fluxfrom invokeai.backend.model_manager.load.model_loaders.flux import Flux2CheckpointModelfrom invokeai.backend.model_manager.load.model_loaders.flux2_state_dict_utils import remap_flux2_layer_pathsfrom invokeai.backend.model_manager.taxonomy import Flux2VariantType, SubModelTypefrom invokeai.backend.quantization.int8_convrot import Int8ConvrotLinear+from tests.fixtures.loader_seams import Seam, prepare+from tests.fixtures.quantized_payloads import comfy_quant_marker, quantize_scaled_fp8MARKER = {"format": "int8_tensorwise"}@@ -63,10 +64,6 @@ DENSE: dict[str, tuple[int, ...]] = {}-def _marker_blob(marker: dict) -> torch.Tensor:- return torch.frombuffer(bytearray(json.dumps(marker).encode("utf-8")), dtype=torch.uint8).clone()--def _quantize_tensorwise(weight: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:"""As the repack stores it: one scalar scale for the whole tensor, no rotation."""scale = weight.abs().max() / 127.0@@ -99,7 +96,7 @@ def _checkpoint(marker: dict | None = MARKER) -> tuple[dict[str, torch.Tensor],originals[path] = weightsd[f"{path}.weight"], sd[f"{path}.weight_scale"] = _quantize_tensorwise(weight)if marker is not None:- sd[f"{path}.comfy_quant"] = _marker_blob(marker)+ sd[f"{path}.comfy_quant"] = comfy_quant_marker(marker)return sd, originals@@ -125,42 +122,39 @@ def _expected_reservation() -> int:return int8_bytes + scale_bytes + dense_bytes + guidance_bytes-def _driver(monkeypatch, tmp_path, state_dict: dict, trace: dict | None = None, header: dict | None = None):- """Drive the loader with the cache recorded rather than stubbed out."""- import invokeai.backend.model_manager.load.model_loaders.flux as module+SEAM = Seam(+ loader=Flux2CheckpointModel,+ module=flux,+ compute_dtype=torch.bfloat16,+ # `_load_from_singlefile` never reaches the FP8 Storage pass, and the tests that do reach it+ # through `_load_model` install their own counter. Nothing here would read this stub, and a+ # stub nothing reads is one more thing to keep true.+ casts_fp8_storage=False,+)- recorded = trace if trace is not None else {}- recorded.setdefault("reserved", None)+def _driver(monkeypatch, tmp_path, state_dict: dict, header: dict | None = None):checkpoint = tmp_path / "flux-2-klein-9b-int8-convrot.safetensors"checkpoint.touch()config = Main_Checkpoint_Flux2_Config.model_construct(path=str(checkpoint), name="klein-9b-int8", variant=Flux2VariantType.Klein9B)- def make_room(reserved: int) -> None:- recorded["reserved"] = reserved-- loader = object.__new__(Flux2CheckpointModel)- loader._ram_cache = SimpleNamespace(make_room=make_room)- loader._logger = MagicMock()- loader._torch_device = torch.device("cpu")- loader._torch_dtype = torch.bfloat16+ def geometry(patch):+ # Both spellings of the same decision: the module-level helper, and the loader method that+ # supersedes it once FP8 Storage counts as a consumer too. `raising=False` tolerates the+ # module symbol being gone.+ patch.setattr(flux, "should_keep_fp8_weights", lambda _device: False, raising=False)- monkeypatch.setattr(module, "load_file", lambda _path: state_dict)- # Both spellings of the same decision: the module-level helper, and the loader method that- # supersedes it once FP8 Storage counts as a consumer too. Setting both keeps this fixture- # working either way -- an instance attribute shadows the method when it exists, and- # `raising=False` tolerates the module symbol being gone.- monkeypatch.setattr(module, "should_keep_fp8_weights", lambda _device: False, raising=False)- loader._keep_fp8_weights = lambda _config, _submodel=None: False- monkeypatch.setattr(module, "read_safetensors_metadata", lambda _path, _logger: header)- return loader, config+ run = prepare(SEAM, monkeypatch, state_dict=state_dict, metadata=header, geometry=geometry)+ # An instance attribute shadows the method, which is what keeps this working either way.+ run.loader._keep_fp8_weights = lambda _config, _submodel=None: False+ return run, config-def _load(monkeypatch, tmp_path, state_dict, trace: dict | None = None, header: dict | None = None):- loader, config = _driver(monkeypatch, tmp_path, state_dict, trace, header)- return loader._load_from_singlefile(config)+def _load(monkeypatch, tmp_path, state_dict, header: dict | None = None):+ run, config = _driver(monkeypatch, tmp_path, state_dict, header)+ return run.load(config), rundef test_an_int8_checkpoint_stays_int8_resident(monkeypatch, tmp_path) -> None:@@ -171,7 +165,7 @@ def test_an_int8_checkpoint_stays_int8_resident(monkeypatch, tmp_path) -> None:"""state_dict, _ = _checkpoint()- model = _load(monkeypatch, tmp_path, state_dict)+ model, _ = _load(monkeypatch, tmp_path, state_dict)swapped = [name for name, module in model.named_modules() if isinstance(module, Int8ConvrotLinear)]assert swapped, "no layer kept its int8 storage"@@ -189,7 +183,7 @@ def test_both_fusions_are_swapped_and_reconstruct_their_source(monkeypatch, tmp_"""state_dict, originals = _checkpoint()- model = _load(monkeypatch, tmp_path, state_dict)+ model, _ = _load(monkeypatch, tmp_path, state_dict)for fused, parts in (("double_blocks.0.img_attn.qkv", ("transformer_blocks.0.attn.to_q", "transformer_blocks.0.attn.to_k")),@@ -215,7 +209,7 @@ def test_the_dense_remainder_is_cast_to_the_compute_dtype(monkeypatch, tmp_path)state_dict, _ = _checkpoint()assert state_dict[STORED_FP32].dtype is torch.float32, "fixture no longer exercises the cast"- model = _load(monkeypatch, tmp_path, state_dict)+ model, _ = _load(monkeypatch, tmp_path, state_dict)for path in ("x_embedder", "context_embedder", "proj_out"):layer = model.get_submodule(path)@@ -231,16 +225,15 @@ def test_an_unusable_activation_scale_is_dropped(monkeypatch, tmp_path) -> None:"""with_scale, without_scale = _checkpoint()[0], _checkpoint()[0]del without_scale[ACTIVATION_SCALE]- traces: list[dict] = [{}, {}]- model = _load(monkeypatch, tmp_path, with_scale, traces[0])- _load(monkeypatch, tmp_path, without_scale, traces[1])+ model, with_run = _load(monkeypatch, tmp_path, with_scale)+ _, without_run = _load(monkeypatch, tmp_path, without_scale)assert isinstance(model.get_submodule("transformer_blocks.0.attn.to_out.0"), Int8ConvrotLinear)# Compared against the same file without the sidecar rather than against a computed total: what# has to hold is that carrying one costs nothing, and a dropped `drop_unconsumed_...` shows up# as the two branches disagreeing.- assert traces[0]["reserved"] == traces[1]["reserved"] == _expected_reservation()+ assert with_run.reserved[-1] == without_run.reserved[-1] == _expected_reservation()def test_the_reservation_charges_the_int8_payloads_one_byte(monkeypatch, tmp_path) -> None:@@ -251,11 +244,10 @@ def test_the_reservation_charges_the_int8_payloads_one_byte(monkeypatch, tmp_patunreserved cache."""state_dict, _ = _checkpoint()- trace: dict = {}- _load(monkeypatch, tmp_path, state_dict, trace)+ _, run = _load(monkeypatch, tmp_path, state_dict)- assert trace["reserved"] == _expected_reservation()+ assert run.reserved[-1] == _expected_reservation()def test_an_int8_weight_without_a_marker_is_refused(monkeypatch, tmp_path) -> None:@@ -276,13 +268,13 @@ def test_the_fp8_storage_pass_is_not_offered_an_int8_model(monkeypatch, tmp_pathSo it would spend the walk for no saving on the 144 layers that matter, and it is skipped."""state_dict, _ = _checkpoint()- trace: dict = {}calls: list[str] = []- loader, config = _driver(monkeypatch, tmp_path, state_dict, trace)- loader._apply_fp8_layerwise_casting = lambda model, *_args: calls.append("cast") or model+ run, config = _driver(monkeypatch, tmp_path, state_dict)+ run.loader._apply_fp8_layerwise_casting = lambda model, *_args: calls.append("cast") or model- model = loader._load_model(config, SubModelType.Transformer)+ # `_load_model`, not the seam's `_load_from_singlefile`: the FP8 Storage pass sits one level up.+ model = run.loader._load_model(config, SubModelType.Transformer)assert calls == []assert any(isinstance(module, Int8ConvrotLinear) for module in model.modules())@@ -298,10 +290,11 @@ def test_a_dense_checkpoint_still_reaches_the_fp8_storage_pass(monkeypatch, tmp_state_dict[f"{path}.weight"] = originals[path].to(torch.bfloat16)calls: list[str] = []- loader, config = _driver(monkeypatch, tmp_path, state_dict)- loader._apply_fp8_layerwise_casting = lambda model, *_args: calls.append("cast") or model+ run, config = _driver(monkeypatch, tmp_path, state_dict)+ run.loader._apply_fp8_layerwise_casting = lambda model, *_args: calls.append("cast") or model- model = loader._load_model(config, SubModelType.Transformer)+ # `_load_model`, not the seam's `_load_from_singlefile`: the FP8 Storage pass sits one level up.+ model = run.loader._load_model(config, SubModelType.Transformer)assert calls == ["cast"]assert not any(isinstance(module, Int8ConvrotLinear) for module in model.modules())@@ -315,10 +308,9 @@ def test_a_file_mixing_int8_with_scaled_fp8_is_refused(monkeypatch, tmp_path) ->detection is file-wide, so a merged export is exactly the shape that reaches this."""state_dict, _ = _checkpoint()- weight = state_dict["final_layer.linear.weight"].float()- scale = weight.abs().max() / 448.0- state_dict["final_layer.linear.weight"] = (weight / scale).to(torch.float8_e4m3fn)- state_dict["final_layer.linear.weight_scale"] = scale.to(torch.float32)+ fp8 = quantize_scaled_fp8(state_dict["final_layer.linear.weight"].float())+ state_dict["final_layer.linear.weight"] = fp8.codes+ state_dict["final_layer.linear.weight_scale"] = fp8.scalewith pytest.raises(ValueError, match="mixing int8_tensorwise with scaled fp8"):_load(monkeypatch, tmp_path, state_dict)@@ -336,9 +328,9 @@ def test_a_repack_that_quantizes_a_skip_patterned_layer_is_dequantized(monkeypatweight = state_dict[f"{path}.weight"].float()originals[path] = weightstate_dict[f"{path}.weight"], state_dict[f"{path}.weight_scale"] = _quantize_tensorwise(weight)- state_dict[f"{path}.comfy_quant"] = _marker_blob(MARKER)+ state_dict[f"{path}.comfy_quant"] = comfy_quant_marker(MARKER)- model = _load(monkeypatch, tmp_path, state_dict)+ model, _ = _load(monkeypatch, tmp_path, state_dict)skipped = model.get_submodule("norm_out.linear")assert not isinstance(skipped, Int8ConvrotLinear)@@ -365,7 +357,7 @@ def test_a_checkpoint_that_declares_int8_only_in_its_header_still_loads(monkeypa)}- model = _load(monkeypatch, tmp_path, state_dict, header=header)+ model, _ = _load(monkeypatch, tmp_path, state_dict, header=header)for path in ("transformer_blocks.0.attn.to_q",@@ -385,7 +377,7 @@ def test_a_per_layer_marker_wins_over_the_header(monkeypatch, tmp_path) -> None:)}- model = _load(monkeypatch, tmp_path, state_dict, header=header)+ model, _ = _load(monkeypatch, tmp_path, state_dict, header=header)assert model.get_submodule("transformer_blocks.0.attn.to_q").convrot is False@@ -394,10 +386,9 @@ def _scaled_fp8_checkpoint() -> tuple[dict[str, torch.Tensor], dict[str, torch.T"""The other build this loader takes: ComfyUI scaled fp8, one scale per tensor."""state_dict, originals = _checkpoint(marker=None)for path in QUANTIZED:- weight = originals[path]- scale = weight.abs().max() / 448.0- state_dict[f"{path}.weight"] = (weight / scale).to(torch.float8_e4m3fn)- state_dict[f"{path}.weight_scale"] = scale.to(torch.float32)+ fp8 = quantize_scaled_fp8(originals[path])+ state_dict[f"{path}.weight"] = fp8.codes+ state_dict[f"{path}.weight_scale"] = fp8.scalereturn state_dict, originals@@ -410,7 +401,7 @@ def test_a_scaled_fp8_checkpoint_still_folds_its_scales(monkeypatch, tmp_path) -"""state_dict, originals = _scaled_fp8_checkpoint()- model = _load(monkeypatch, tmp_path, state_dict)+ model, _ = _load(monkeypatch, tmp_path, state_dict)assert not any(isinstance(module, Int8ConvrotLinear) for module in model.modules())for path, source in (diff --git a/tests/backend/model_manager/load/test_ideogram4_checkpoint_loader.py b/tests/backend/model_manager/load/test_ideogram4_checkpoint_loader.pyindex 8fee3b3677..0fff557e58 100644--- a/tests/backend/model_manager/load/test_ideogram4_checkpoint_loader.py+++ b/tests/backend/model_manager/load/test_ideogram4_checkpoint_loader.py@@ -10,10 +10,6 @@ A tiny `Ideogram4Config` stands in for the released geometry: same module tree,of 458."""-import json-from types import SimpleNamespace-from unittest.mock import MagicMock-import pytestimport torch@@ -21,13 +17,15 @@ from invokeai.backend.ideogram4.modeling_ideogram4 import Ideogram4Config, Ideogfrom invokeai.backend.model_manager.configs.default_settings import MainModelDefaultSettingsfrom invokeai.backend.model_manager.configs.main import Main_Checkpoint_Ideogram4_Configfrom invokeai.backend.model_manager.load import load_default+from invokeai.backend.model_manager.load.model_loaders import ideogram4from invokeai.backend.model_manager.load.model_loaders.ideogram4 import Ideogram4CheckpointModelfrom invokeai.backend.model_manager.taxonomy import SubModelTypefrom invokeai.backend.quantization.int8_convrot import (CONVROT_GROUP_SIZE,Int8ConvrotLinear,- build_regular_hadamard,)+from tests.fixtures.loader_seams import Seam, SeamRun, prepare+from tests.fixtures.quantized_payloads import comfy_quant_marker, quantize_convrot, quantize_scaled_fp8FP8 = torch.float8_e4m3fn@@ -60,12 +58,6 @@ KEPT = "layers.0.feed_forward.w1"SKIPPED = ("input_proj", "t_embedding.mlp_in")-def _quantize_scaled_fp8(weight: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:- """ComfyUI 'scaled fp8': one scale per tensor, folded back in by `dequantize_fp8_scaled`."""- scale = weight.abs().max() / 448.0- return (weight / scale).to(FP8), scale.to(torch.float32)--def _checkpoint(paths: tuple[str, ...]) -> tuple[dict[str, torch.Tensor], dict[str, torch.Tensor]]:"""A full state dict for the tiny geometry, with `paths` stored as scaled fp8.@@ -80,11 +72,20 @@ def _checkpoint(paths: tuple[str, ...]) -> tuple[dict[str, torch.Tensor], dict[sfor path in paths:key = f"{path}.weight"originals[key] = state_dict[key].clone()- state_dict[key], state_dict[f"{path}.weight_scale"] = _quantize_scaled_fp8(state_dict[key])+ payload = quantize_scaled_fp8(state_dict[key])+ state_dict[key], state_dict[f"{path}.weight_scale"] = payload.codes, payload.scalereturn state_dict, originals+SEAM = Seam(+ loader=Ideogram4CheckpointModel,+ module=ideogram4,+ entry="_load_model",+ patches_device=True,+)++def _driver(monkeypatch,tmp_path,@@ -92,23 +93,8 @@ def _driver(*,keep_fp8: bool,fp8_storage: bool = False,- trace: dict | None = None,geometry: Ideogram4Config = TINY_CONFIG,):- """Drive the loader with the cache and the fp8 storage pass recorded rather than stubbed out.-- `trace` collects what the loader *did*: `casting_calls` counts entries into- `_apply_fp8_layerwise_casting`, and `weights_at_make_room` snapshots the state dict's dtypes at- the moment room is reserved. Both are invariants the module documents in prose and both are- invisible to an end-state assertion.- """- import invokeai.backend.model_manager.load.model_loaders.ideogram4 as module-- recorded = trace if trace is not None else {}- recorded.setdefault("casting_calls", 0)- recorded.setdefault("fp8_weights_at_make_room", None)- recorded.setdefault("reserved", None)-checkpoint = tmp_path / "ideogram4_fp8_scaled.safetensors"checkpoint.touch()config = Main_Checkpoint_Ideogram4_Config.model_construct(@@ -118,32 +104,15 @@ def _driver(default_settings=MainModelDefaultSettings(fp8_storage=fp8_storage),)- def make_room(reserved: int) -> None:- recorded["reserved"] = reserved- recorded["fp8_weights_at_make_room"] = sum(1 for v in state_dict.values() if v.dtype is FP8)-- def apply_casting(model, _config, _submodel):- recorded["casting_calls"] += 1- return model-- loader = object.__new__(Ideogram4CheckpointModel)- loader._ram_cache = SimpleNamespace(make_room=make_room)- loader._logger = MagicMock()- loader._torch_device = torch.device("cpu")- loader._torch_dtype = torch.float32- loader._apply_fp8_layerwise_casting = apply_casting-- monkeypatch.setattr(module, "load_file", lambda _path: state_dict)- # The two inputs of the loader's decision, not the decision itself: `_keep_fp8_weights` asks the- # fp8 matmul and this model's FP8 Storage setting, and either alone is enough. Stubbing the- # answer would let a loader that consults only one of them stay green.- monkeypatch.setattr(load_default, "should_keep_fp8_weights", lambda _device: keep_fp8)- monkeypatch.setattr(load_default, "_device_supports_fp8_storage", lambda _device, _logger=None: True)- monkeypatch.setattr(module, "read_safetensors_metadata", lambda _path, _logger: None)- monkeypatch.setattr(module.TorchDevice, "choose_torch_device", staticmethod(lambda: torch.device("cpu")))- monkeypatch.setattr(module.TorchDevice, "choose_bfloat16_safe_dtype", staticmethod(lambda _device: torch.float32))- monkeypatch.setattr("invokeai.backend.ideogram4.modeling_ideogram4.Ideogram4Config", lambda: geometry, raising=True)- return loader, config+ def install(patch):+ # The two inputs of the loader's decision, not the decision itself: `_keep_fp8_weights` asks+ # the fp8 matmul and this model's FP8 Storage setting, and either alone is enough. Stubbing+ # the answer would let a loader that consults only one of them stay green.+ patch.setattr(load_default, "should_keep_fp8_weights", lambda _device: keep_fp8)+ patch.setattr(load_default, "_device_supports_fp8_storage", lambda _device, _logger=None: True)+ patch.setattr("invokeai.backend.ideogram4.modeling_ideogram4.Ideogram4Config", lambda: geometry)++ return prepare(SEAM, monkeypatch, state_dict=state_dict, metadata=None, geometry=install), configdef _load(@@ -153,19 +122,14 @@ def _load(*,keep_fp8: bool,fp8_storage: bool = False,- trace: dict | None = None,geometry: Ideogram4Config = TINY_CONFIG,-) -> torch.nn.Module:- loader, model_config = _driver(- monkeypatch,- tmp_path,- state_dict,- keep_fp8=keep_fp8,- fp8_storage=fp8_storage,- trace=trace,- geometry=geometry,+) -> tuple[torch.nn.Module, SeamRun]:+ """The model, and the record of how the loader got there -- the second is why several of these+ tests exist at all, so it is returned rather than collected through an out-parameter."""+ run, model_config = _driver(+ monkeypatch, tmp_path, state_dict, keep_fp8=keep_fp8, fp8_storage=fp8_storage, geometry=geometry)- return loader._load_model(model_config, SubModelType.Transformer)+ return run.load(model_config, SubModelType.Transformer), rundef test_with_neither_consumer_the_scales_are_folded_into_full_precision_weights(monkeypatch, tmp_path) -> None:@@ -173,7 +137,7 @@ def test_with_neither_consumer_the_scales_are_folded_into_full_precision_weightswould dequantize on every forward to save memory nobody asked to save."""state_dict, originals = _checkpoint((KEPT, *SKIPPED))- model = _load(monkeypatch, tmp_path, state_dict, keep_fp8=False)+ model, _ = _load(monkeypatch, tmp_path, state_dict, keep_fp8=False)for key, original in originals.items():weight = model.get_parameter(key)@@ -194,14 +158,13 @@ def test_fp8_storage_alone_keeps_the_checkpoint_in_its_own_scaled_form(monkeypat"""state_dict, _ = _checkpoint((KEPT,))before = {key: value.clone() for key, value in state_dict.items()}- trace: dict = {}- model = _load(monkeypatch, tmp_path, state_dict, keep_fp8=False, fp8_storage=True, trace=trace)+ model, run = _load(monkeypatch, tmp_path, state_dict, keep_fp8=False, fp8_storage=True)kept = model.get_submodule(KEPT)assert kept.weight.dtype is FP8assert kept.weight_scale.shape == ()- assert trace["casting_calls"] == 0+ assert run.casting_calls == 0# Byte for byte what the file holds -- that is the whole argument for keeping them. A fold# followed by the storage cast re-encodes without the scale, which on a checkpoint whose scales# are not powers of two silently flushes the smallest weights to zero.@@ -219,14 +182,13 @@ def test_fp8_storage_alone_keeps_the_checkpoint_in_its_own_scaled_form(monkeypatfor key, tensor in before.items()if key != f"{KEPT}.weight" and not key.endswith(".weight_scale"))- assert trace["reserved"] == kept_codes + dense+ assert run.reserved[-1] == kept_codes + densedef test_with_the_fp8_matmul_the_codes_stay_and_the_scales_are_attached(monkeypatch, tmp_path) -> None:state_dict, _ = _checkpoint((KEPT,))- trace: dict = {}- model = _load(monkeypatch, tmp_path, state_dict, keep_fp8=True, trace=trace)+ model, run = _load(monkeypatch, tmp_path, state_dict, keep_fp8=True)kept = model.get_submodule(KEPT)assert kept.weight.dtype is FP8@@ -235,7 +197,7 @@ def test_with_the_fp8_matmul_the_codes_stay_and_the_scales_are_attached(monkeypaassert "weight_scale" not in kept.state_dict()# And the layerwise storage pass must not have run: its hooks restore the compute dtype without# applying `weight_scale` (a silently wrong weight) and disable the matmul this path exists for.- assert trace["casting_calls"] == 0+ assert run.casting_calls == 0def test_room_is_reserved_before_the_scales_are_folded(monkeypatch, tmp_path) -> None:@@ -243,11 +205,11 @@ def test_room_is_reserved_before_the_scales_are_folded(monkeypatch, tmp_path) -># made afterwards lets that transient peak land on an unreserved cache. Reserving first is# invisible in the loaded model, so it is asserted where it happens.state_dict, _ = _checkpoint((KEPT, *SKIPPED))- trace: dict = {}- _load(monkeypatch, tmp_path, state_dict, keep_fp8=True, trace=trace)+ _, run = _load(monkeypatch, tmp_path, state_dict, keep_fp8=True)- assert trace["fp8_weights_at_make_room"] == 3, "the fold ran before the cache was asked for room"+ fp8_at_reservation = sum(1 for dtype in run.dtypes_at_make_room.values() if dtype is FP8)+ assert fp8_at_reservation == 3, "the fold ran before the cache was asked for room"@pytest.mark.parametrize("path", SKIPPED)@@ -263,7 +225,7 @@ def test_the_two_dtype_deriving_layers_never_stay_quantized(# computes in a dtype the model never intended.state_dict, originals = _checkpoint((KEPT, path))- model = _load(monkeypatch, tmp_path, state_dict, keep_fp8=keep_fp8, fp8_storage=fp8_storage)+ model, run = _load(monkeypatch, tmp_path, state_dict, keep_fp8=keep_fp8, fp8_storage=fp8_storage)skipped = model.get_submodule(path)assert skipped.weight.dtype is torch.float32@@ -276,9 +238,8 @@ def test_the_two_dtype_deriving_layers_never_stay_quantized(def test_a_plain_checkpoint_loads_verbatim_and_is_offered_to_the_storage_pass(monkeypatch, tmp_path) -> None:state_dict, _ = _checkpoint(())expected = {key: value.clone() for key, value in state_dict.items()}- trace: dict = {}- model = _load(monkeypatch, tmp_path, state_dict, keep_fp8=False, fp8_storage=True, trace=trace)+ model, run = _load(monkeypatch, tmp_path, state_dict, keep_fp8=False, fp8_storage=True)for key, value in expected.items():assert torch.equal(model.get_parameter(key), value), key@@ -286,16 +247,16 @@ def test_a_plain_checkpoint_loads_verbatim_and_is_offered_to_the_storage_pass(mo# it so -- this is the one path that must reach `_apply_fp8_layerwise_casting`. The setting is on# for realism rather than because the assertion needs it: the casting pass is stubbed out by a# counter here, so what is pinned is that the loader offers the model to it at all.- assert trace["casting_calls"] == 1+ assert run.casting_calls == 1def test_only_the_transformer_submodel_is_served(monkeypatch, tmp_path) -> None:# A single file has no encoder, tokenizer or VAE in it; those are selected on the loader node.state_dict, _ = _checkpoint(())- loader, config = _driver(monkeypatch, tmp_path, state_dict, keep_fp8=False)+ run, config = _driver(monkeypatch, tmp_path, state_dict, keep_fp8=False)with pytest.raises(ValueError, match="holds only a transformer"):- loader._load_model(config, SubModelType.VAE)+ run.load(config, SubModelType.VAE)MARKER = {"format": "int8_tensorwise", "convrot": True, "convrot_groupsize": CONVROT_GROUP_SIZE}@@ -305,27 +266,12 @@ MARKER = {"format": "int8_tensorwise", "convrot": True, "convrot_groupsize": CONINT8_LAYERS = ("layers.0.attention.o", "layers.0.adaln_modulation")-def _marker_blob(marker: dict) -> torch.Tensor:- return torch.frombuffer(bytearray(json.dumps(marker).encode("utf-8")), dtype=torch.uint8).clone()--def _quantize_tensorwise(weight: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:"""Per-output-channel int8 with no rotation."""scale = weight.abs().amax(dim=1, keepdim=True) / 127.0return torch.clamp(torch.round(weight / scale), -128, 127).to(torch.int8), scale.to(torch.float32)-def _quantize_convrot(weight: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:- """Mirror of comfy-quants: rotate along the input dim, then per-output-channel int8."""- out_features, in_features = weight.shape- hadamard = build_regular_hadamard(CONVROT_GROUP_SIZE, dtype=weight.dtype)- rotated = (weight.view(out_features, in_features // CONVROT_GROUP_SIZE, CONVROT_GROUP_SIZE) @ hadamard.T).view(- out_features, in_features- )- scale = rotated.abs().amax(dim=1, keepdim=True) / 127.0- return torch.clamp(torch.round(rotated / scale), -128, 127).to(torch.int8), scale.to(torch.float32)--def _int8_checkpoint(paths: tuple[str, ...] = INT8_LAYERS, *, convrot: bool = True) -> tuple[dict[str, torch.Tensor], dict[str, torch.Tensor]]:@@ -344,10 +290,11 @@ def _int8_checkpoint(key = f"{path}.weight"originals[key] = state_dict[key].clone()if convrot:- state_dict[key], state_dict[f"{path}.weight_scale"] = _quantize_convrot(state_dict[key])+ payload = quantize_convrot(state_dict[key])+ state_dict[key], state_dict[f"{path}.weight_scale"] = payload.codes, payload.scaleelse:state_dict[key], state_dict[f"{path}.weight_scale"] = _quantize_tensorwise(state_dict[key])- state_dict[f"{path}.comfy_quant"] = _marker_blob({**MARKER, "convrot": convrot})+ state_dict[f"{path}.comfy_quant"] = comfy_quant_marker({**MARKER, "convrot": convrot})return state_dict, originals@@ -387,9 +334,8 @@ def test_an_int8_checkpoint_stays_int8_resident_and_un_rotates(monkeypatch, tmp_"""state_dict, originals = _int8_checkpoint()biases = {key: value.clone() for key, value in state_dict.items() if key.endswith(".bias")}- trace: dict = {}- model = _load(monkeypatch, tmp_path, state_dict, keep_fp8=False, trace=trace, geometry=INT8_CONFIG)+ model, run = _load(monkeypatch, tmp_path, state_dict, keep_fp8=False, geometry=INT8_CONFIG)for path in INT8_LAYERS:layer = model.get_submodule(path)@@ -406,7 +352,7 @@ def test_an_int8_checkpoint_stays_int8_resident_and_un_rotates(monkeypatch, tmp_# as a buffer rather than a parameter -- so the strict load below cannot see it go missing.assert torch.equal(model.get_submodule("layers.0.adaln_modulation").bias, biases["layers.0.adaln_modulation.bias"])# The fp8 storage pass must not run over int8 codes either.- assert trace["casting_calls"] == 0+ assert run.casting_calls == 0def test_an_unusable_activation_scale_does_not_break_the_strict_load(monkeypatch, tmp_path) -> None:@@ -418,7 +364,7 @@ def test_an_unusable_activation_scale_does_not_break_the_strict_load(monkeypatchstate_dict, _ = _int8_checkpoint()state_dict[f"{INT8_LAYERS[0]}.input_scale"] = torch.ones((), dtype=torch.float32)- model = _load(monkeypatch, tmp_path, state_dict, keep_fp8=False, geometry=INT8_CONFIG)+ model, _ = _load(monkeypatch, tmp_path, state_dict, keep_fp8=False, geometry=INT8_CONFIG)assert isinstance(model.get_submodule(INT8_LAYERS[0]), Int8ConvrotLinear)@@ -437,9 +383,8 @@ def test_a_repack_that_quantizes_a_dtype_deriving_layer_is_dequantized(monkeypatif key.startswith(f"{INT8_LAYERS[0]}."):state_dict[key] = valuebefore_load = {key: value.clone() for key, value in state_dict.items()}- trace: dict = {}- model = _load(monkeypatch, tmp_path, state_dict, keep_fp8=False, trace=trace, geometry=INT8_CONFIG)+ model, run = _load(monkeypatch, tmp_path, state_dict, keep_fp8=False, geometry=INT8_CONFIG)skipped = model.get_submodule(path)assert not isinstance(skipped, Int8ConvrotLinear)@@ -450,7 +395,7 @@ def test_a_repack_that_quantizes_a_dtype_deriving_layer_is_dequantized(monkeypatassert isinstance(model.get_submodule(INT8_LAYERS[0]), Int8ConvrotLinear)# And the widened layer was reserved for at its widened width: charging it one byte because a# marker claims it leaves the reservation short by exactly the layers the split grew.- assert trace["reserved"] == _reservation_for(before_load, (INT8_LAYERS[0],))+ assert run.reserved[-1] == _reservation_for(before_load, (INT8_LAYERS[0],))def test_the_int8_reservation_charges_each_payload_its_stored_width(monkeypatch, tmp_path) -> None:@@ -458,11 +403,10 @@ def test_the_int8_reservation_charges_each_payload_its_stored_width(monkeypatch,# two bytes per int8 payload evicts roughly twice what an 8.9 GiB file needs.state_dict, _ = _int8_checkpoint()before_load = {key: value.clone() for key, value in state_dict.items()}- trace: dict = {}- _load(monkeypatch, tmp_path, state_dict, keep_fp8=False, trace=trace, geometry=INT8_CONFIG)+ _, run = _load(monkeypatch, tmp_path, state_dict, keep_fp8=False, geometry=INT8_CONFIG)- assert trace["reserved"] == _reservation_for(before_load, INT8_LAYERS)+ assert run.reserved[-1] == _reservation_for(before_load, INT8_LAYERS)def test_a_missing_bias_on_a_quantized_layer_is_refused(monkeypatch, tmp_path) -> None:@@ -488,9 +432,9 @@ def test_a_file_mixing_int8_with_scaled_fp8_is_refused(monkeypatch, tmp_path) ->setting under which this file is loadable, so it is refused rather than half-loaded."""state_dict, _ = _int8_checkpoint()- state_dict["final_layer.linear.weight"], state_dict["final_layer.linear.weight_scale"] = _quantize_scaled_fp8(- state_dict["final_layer.linear.weight"]- )+ fp8 = quantize_scaled_fp8(state_dict["final_layer.linear.weight"])+ state_dict["final_layer.linear.weight"] = fp8.codes+ state_dict["final_layer.linear.weight_scale"] = fp8.scalewith pytest.raises(ValueError, match="mixing int8_tensorwise with scaled fp8"):_load(monkeypatch, tmp_path, state_dict, keep_fp8=False, geometry=INT8_CONFIG)diff --git a/tests/backend/model_manager/load/test_krea2_nvfp4_loader.py b/tests/backend/model_manager/load/test_krea2_nvfp4_loader.pyindex bb622ac258..302846702d 100644--- a/tests/backend/model_manager/load/test_krea2_nvfp4_loader.py+++ b/tests/backend/model_manager/load/test_krea2_nvfp4_loader.py@@ -21,6 +21,7 @@ from invokeai.backend.model_manager.load.model_loaders.krea2 import Krea2Checkpofrom invokeai.backend.model_manager.taxonomy import Krea2VariantTypefrom invokeai.backend.quantization.int8_convrot import CONVROT_GROUP_SIZE, Int8ConvrotLinearfrom invokeai.backend.quantization.nvfp4 import NVFP4Linear+from tests.fixtures.quantized_payloads import comfy_quant_marker, nvfp4_signed_tensorsCOMPUTE_DTYPE = torch.bfloat16@@ -64,15 +65,7 @@ class _TinyKrea2(torch.nn.Module):def _nvfp4_tensors(path: str, shape: tuple[int, int]) -> tuple[dict[str, torch.Tensor], torch.Tensor]:- """Codes 2 and 10 are +1.0 and -1.0; with a block scale of 2 and a global scale of 0.25 the weight is +-0.5."""- positive = torch.randint(0, 2, shape, dtype=torch.bool)- codes = torch.where(positive, 2, 10).to(torch.uint8)- tensors = {- f"{path}.weight": (codes[:, 0::2] << 4) | codes[:, 1::2],- f"{path}.weight_scale": torch.full((shape[0], shape[1] // 16), 2.0).to(torch.float8_e4m3fn),- f"{path}.weight_scale_2": torch.tensor(0.25),- }- return tensors, torch.where(positive, 0.5, -0.5)+ return nvfp4_signed_tensors(path, torch.randint(0, 2, shape, dtype=torch.bool))def _packed_bytes(rows: int, columns: int) -> int:@@ -108,12 +101,9 @@ def loaded(request, monkeypatch: pytest.MonkeyPatch, tmp_path) -> SimpleNamespacif request.param == "dense":state_dict["blocks.0.attn.wk.weight"] = torch.randn(128, CONVROT_GROUP_SIZE)else:- marker = json.dumps({"format": "int8_tensorwise", "convrot": False})state_dict["blocks.0.attn.wk.weight"] = torch.randint(-127, 128, (128, CONVROT_GROUP_SIZE), dtype=torch.int8)state_dict["blocks.0.attn.wk.weight_scale"] = torch.ones(128, 1)- state_dict["blocks.0.attn.wk.comfy_quant"] = torch.frombuffer(- bytearray(marker.encode("utf-8")), dtype=torch.uint8- ).clone()+ state_dict["blocks.0.attn.wk.comfy_quant"] = comfy_quant_marker({"format": "int8_tensorwise", "convrot": False})dense = {name: state_dict[name] for name in ("tmlp.0.bias", "first.weight", "first.bias", "blocks.0.attn.wk.weight")}diff --git a/tests/backend/model_manager/load/test_loader_seam_driver.py b/tests/backend/model_manager/load/test_loader_seam_driver.pynew file mode 100644index 0000000000..424a28fbfe--- /dev/null+++ b/tests/backend/model_manager/load/test_loader_seam_driver.py@@ -0,0 +1,137 @@+"""The seam driver's own records, against a loader small enough to be wrong on purpose.++`tests/fixtures/loader_seams.py` is fixture code, and fixture code that lies is worse than no+fixture: every seam driven through it inherits the lie, and the tests keep passing. That happened+once already -- `dtypes_at_make_room` watched the caller's dict while the loader worked on a copy,+so it reported the test's own input whatever the loader did, and the one ordering test relying on it+became unfalsifiable. Three reviewers found it; nothing in the suite did.++So the records are pinned here against toy loaders that deliberately get the order wrong. These are+not tests of a loader. They are the reason a loader's test can be believed.+"""++from types import SimpleNamespace++import pytest+import torch++from tests.fixtures.loader_seams import Seam, prepare+++class _WidensBeforeReserving:+ """The regression every seam's ordering assertion exists to catch: the checkpoint is widened to+ the compute dtype, and only then is the cache asked to make room for it."""++ def _load_from_singlefile(self, _config):+ _stubbed.widen(_stubbed.load_file("ignored"))+ self._ram_cache.make_room(1)+ return torch.nn.Module()+++class _ReservesFirst:+ def _load_from_singlefile(self, _config):+ state_dict = _stubbed.load_file("ignored")+ self._ram_cache.make_room(1)+ _stubbed.widen(state_dict)+ return torch.nn.Module()+++#: What each `widen` call was handed, so a test can say what the loader actually received rather+#: than inferring it from a dict the loader never touched.+SEEN: list[dict[str, torch.dtype]] = []+++def _widen(state_dict: dict[str, torch.Tensor]) -> dict[str, torch.Tensor]:+ """The step `observe` watches: a stand-in for the fold or the cast that widens a checkpoint."""+ SEEN.append({key: value.dtype for key, value in state_dict.items()})+ for key in list(state_dict):+ state_dict[key] = state_dict[key].float()+ return state_dict++[email protected](autouse=True)+def _forget_what_was_seen():+ SEEN.clear()+ yield+ SEEN.clear()+++#: Stands in for a loader module: `prepare` patches these names here, and the toy loaders read them+#: back the way a real loader reads its own module-level imports.+_stubbed = SimpleNamespace(load_file=lambda _path: {}, widen=_widen)++PACKED = {"lin.weight": torch.zeros(4, 4, dtype=torch.float8_e4m3fn)}+++ ("loader", "expected"),+ [(_WidensBeforeReserving, torch.float32), (_ReservesFirst, torch.float8_e4m3fn)],+ ids=["widened_before_reserving", "reserved_first"],+)+def test_the_dtype_record_sees_what_the_loader_had_when_it_asked_for_room(+ monkeypatch: pytest.MonkeyPatch, loader: type, expected: torch.dtype+) -> None:+ """The two cases have to come out differently, or the record is not an observation.++ A driver that hands the loader a copy and then reads its own dict reports `float8_e4m3fn` for+ both -- which is what shipped in the first draft of this fixture, and what made the ideogram4+ ordering test pass no matter where `make_room` was called.+ """+ run = prepare(Seam(loader=loader, module=_stubbed), monkeypatch, state_dict=PACKED)++ run.load(None)++ assert run.dtypes_at_make_room == {"lin.weight": expected}+++def test_each_load_gets_its_own_copy_of_the_checkpoint(monkeypatch: pytest.MonkeyPatch) -> None:+ """Loaders rebind and clear the dict they are handed, so a second load must not be reading the+ first one's leavings.++ Asserted on what the loader was actually handed, not on the caller's dict: the caller's dict+ survives either way, so a driver that made one copy up front and served it to both loads would+ satisfy that half while the second load started from the first load's float32 weights.+ """+ run = prepare(Seam(loader=_ReservesFirst, module=_stubbed), monkeypatch, state_dict=PACKED)++ run.load(None)+ run.load(None)++ assert SEEN == [{"lin.weight": torch.float8_e4m3fn}] * 2, SEEN+ assert PACKED["lin.weight"].dtype is torch.float8_e4m3fn, "the loader mutated the test's own dict"+++ ("loader", "expected"),+ [(_WidensBeforeReserving, [("widen", 0)]), (_ReservesFirst, [("widen", 1)])],+ ids=["widened_before_reserving", "reserved_first"],+)+def test_the_step_record_says_how_much_room_had_been_reserved(+ monkeypatch: pytest.MonkeyPatch, loader: type, expected: list[tuple[str, int]]+) -> None:+ """`observe` is the other half of the ordering claim, and the half that works on a seam reading+ a real file, where there is no served dict to watch. It has to separate the same two loaders."""+ run = prepare(Seam(loader=loader, module=_stubbed), monkeypatch, state_dict=PACKED, observe=("widen",))++ run.load(None)++ assert run.order == expected+++def test_a_seam_installs_no_stub_it_did_not_ask_for(monkeypatch: pytest.MonkeyPatch) -> None:+ """The failure this fixture exists to stop: a driver that stubs one thing too many lets a test+ pass without the loader having done the work. Only the plumbing every `object.__new__` loader+ needs -- cache, logger, device -- is unconditional."""+ declined = Seam(loader=_ReservesFirst, module=_stubbed, sets_torch_dtype=False, casts_fp8_storage=False)+ asked = Seam(loader=_ReservesFirst, module=_stubbed)++ without = prepare(declined, monkeypatch, state_dict=PACKED)+ with_stubs = prepare(asked, monkeypatch, state_dict=PACKED)++ assert not hasattr(without.loader, "_torch_dtype")+ assert not hasattr(without.loader, "_apply_fp8_layerwise_casting")+ assert with_stubs.loader._torch_dtype is torch.float32+ assert callable(with_stubs.loader._apply_fp8_layerwise_casting)+ # `read_safetensors_metadata` is left alone unless a test names it, so that a seam can be driven+ # against a real header.+ assert not hasattr(_stubbed, "read_safetensors_metadata")diff --git a/tests/backend/model_manager/load/test_minimax_h3_int8_loading.py b/tests/backend/model_manager/load/test_minimax_h3_int8_loading.pyindex f2ec2544bc..6788acc339 100644--- a/tests/backend/model_manager/load/test_minimax_h3_int8_loading.py+++ b/tests/backend/model_manager/load/test_minimax_h3_int8_loading.py@@ -10,7 +10,6 @@ routes -- once from the header before committing to the tensor read, once from tthe header route is only exercised by an actual file."""-import jsonfrom pathlib import Pathfrom types import SimpleNamespacefrom unittest.mock import MagicMock@@ -25,9 +24,9 @@ from invokeai.backend.model_manager.load.model_loaders.minimax_h3 import MiniMaxfrom invokeai.backend.model_manager.taxonomy import MiniMaxH3VariantTypefrom invokeai.backend.quantization.int8_convrot import (Int8ConvrotLinear,- build_regular_hadamard,read_comfy_quant_markers,)+from tests.fixtures.quantized_payloads import comfy_quant_marker, quantize_convrot@pytest.fixture(autouse=True)@@ -93,23 +92,6 @@ def _tiny_remote_code_state_dict() -> dict[str, torch.Tensor]:return sd-def _quantize_convrot(weight: torch.Tensor, group_size: int) -> tuple[torch.Tensor, torch.Tensor]:- """Mirror of comfy-quants: rotate along the input dim in groups, then per-output-channel int8."""- out_features, in_features = weight.shape- hadamard = build_regular_hadamard(group_size, dtype=weight.dtype)- rotated = (weight.view(out_features, in_features // group_size, group_size) @ hadamard.T).view(- out_features, in_features- )- scale = rotated.abs().amax(dim=1, keepdim=True) / 127.0- return torch.clamp(torch.round(rotated / scale), -128, 127).to(torch.int8), scale.to(torch.float32)---def _marker_blob(marker: dict, *, pad: int = 0) -> torch.Tensor:- """Comfy pads these to a fixed width with NUL bytes; `pad` reproduces that."""- raw = json.dumps(marker).encode("utf-8") + b"\x00" * pad- return torch.frombuffer(bytearray(raw), dtype=torch.uint8).clone()--def _write_checkpoint(tmp_path: Path, *, scale: torch.Tensor | None = None, marker: dict | None = None, pad: int = 16) -> tuple[Path, torch.Tensor]:@@ -117,10 +99,10 @@ def _write_checkpoint(torch.manual_seed(0)sd = _tiny_remote_code_state_dict()original = sd[QUANTIZED_SOURCE_KEY]- quantized, derived_scale = _quantize_convrot(original, GROUP_SIZE)+ quantized, derived_scale, _restored = quantize_convrot(original, group_size=GROUP_SIZE)sd[QUANTIZED_SOURCE_KEY] = quantizedsd["blocks.0.attn.out_proj.weight_scale"] = derived_scale if scale is None else scale- sd["blocks.0.attn.out_proj.comfy_quant"] = _marker_blob(+ sd["blocks.0.attn.out_proj.comfy_quant"] = comfy_quant_marker(marker or {"format": "int8_tensorwise", "convrot": True, "convrot_groupsize": GROUP_SIZE}, pad=pad)path = tmp_path / "minimax_h3_int8_convrot.safetensors"diff --git a/tests/backend/model_manager/load/test_mistral_encoder_checkpoint_loader.py b/tests/backend/model_manager/load/test_mistral_encoder_checkpoint_loader.pyindex df379d7e19..5e673dc6f0 100644--- a/tests/backend/model_manager/load/test_mistral_encoder_checkpoint_loader.py+++ b/tests/backend/model_manager/load/test_mistral_encoder_checkpoint_loader.py@@ -8,8 +8,6 @@ branches are exercised: the one that keeps fp8 pops every block scale, the one timport jsonfrom pathlib import Path-from types import SimpleNamespace-from unittest.mock import MagicMockimport pytestimport torch@@ -20,6 +18,8 @@ from invokeai.backend.model_manager.load.model_loaders import mistral_encoderfrom invokeai.backend.model_manager.load.model_loaders.mistral_encoder import MistralEncoderCheckpointLoaderfrom invokeai.backend.model_manager.taxonomy import MistralVariantTypefrom invokeai.backend.quantization.nvfp4 import NVFP4Linear, NVFP4Payload+from tests.fixtures.loader_seams import Seam, prepare+from tests.fixtures.quantized_payloads import comfy_quant_marker# The loader derives head counts as projection rows // 128: two query heads over one key/value head, so a config# that mixes up the two lookups, or falls back to the cow model's, cannot build this model. Dimensions are multiples@@ -43,10 +43,6 @@ NVFP4_PROJECTIONS = {FP8_PROJECTION = "self_attn.v_proj"-def _marker_blob(marker: dict) -> torch.Tensor:- return torch.frombuffer(bytearray(json.dumps(marker).encode("utf-8")), dtype=torch.uint8)--def _packed_bytes(rows: int, columns: int) -> int:"""A layer as stored: two codes per byte, one e4m3 scale per 16 elements, a float32 global scale."""return rows * columns // 2 + rows * (columns // 16) + 4@@ -83,7 +79,7 @@ def _write_checkpoint(tmp_path: Path, evidence: str) -> tuple[Path, dict[str, toif evidence == "header":header[path] = {"format": "nvfp4"}else:- tensors[f"{path}.comfy_quant"] = _marker_blob({"format": "nvfp4"})+ tensors[f"{path}.comfy_quant"] = comfy_quant_marker({"format": "nvfp4"})return torch.where(positive, 0.5, -0.5)for layer in range(LAYERS):@@ -94,7 +90,7 @@ def _write_checkpoint(tmp_path: Path, evidence: str) -> tuple[Path, dict[str, tov_proj = f"{prefix}model.layers.{layer}.{FP8_PROJECTION}"tensors[f"{v_proj}.weight"] = fp8_values.to(torch.float8_e4m3fn)tensors[f"{v_proj}.weight_scale"] = torch.tensor(0.5)- tensors[f"{v_proj}.comfy_quant"] = _marker_blob({"format": "float8_e4m3fn"})+ tensors[f"{v_proj}.comfy_quant"] = comfy_quant_marker({"format": "float8_e4m3fn"})fp8_dequantized[layer] = fp8_values * 0.5for norm in ("input_layernorm", "post_attention_layernorm"):@@ -112,27 +108,31 @@ def _write_checkpoint(tmp_path: Path, evidence: str) -> tuple[Path, dict[str, toreturn checkpoint, expected, fp8_dequantized-def _loader(monkeypatch: pytest.MonkeyPatch, keep_fp8: bool) -> tuple[MistralEncoderCheckpointLoader, list[str]]:- """The loader, and a log of the steps that widen weights, each recorded with whether room was made first."""- monkeypatch.setattr(mistral_encoder.TorchDevice, "choose_torch_device", lambda: torch.device("cpu"))- monkeypatch.setattr(mistral_encoder.TorchDevice, "choose_bfloat16_safe_dtype", lambda _device: COMPUTE_DTYPE)- monkeypatch.setattr(mistral_encoder, "should_keep_fp8_weights", lambda _device: keep_fp8)- loader = object.__new__(MistralEncoderCheckpointLoader)- loader._ram_cache = SimpleNamespace(make_room=MagicMock())- # Supplied because the loader reads it when it decides whether to keep fp8 weights packed:- # a fixture built with `object.__new__` has to provide every attribute that path touches.- loader._torch_device = torch.device("cpu")+SEAM = Seam(+ loader=MistralEncoderCheckpointLoader,+ module=mistral_encoder,+ entry="_load_text_encoder",+ patches_device=True,+ compute_dtype=COMPUTE_DTYPE,+ # The loader takes its dtype from the device and has no FP8 Storage pass, so neither is supplied:+ # an attribute a loader does not read is one a test must not make it look like it reads.+ sets_torch_dtype=False,+ casts_fp8_storage=False,+)++#: The two steps that widen weights. Room has to have been reserved before either runs.+WIDENING = ("_drop_quantization_metadata", "split_fp8_scaled_layers")+- widening: list[str] = []- for name in ("_drop_quantization_metadata", "split_fp8_scaled_layers"):- original = getattr(mistral_encoder, name)+def _fp8_matmul(available: bool):+ """The encoder asks the device, not the model config, so this is the only input to the+ keep-or-fold decision -- stubbing the decision itself would let a loader that stopped+ asking stay green."""- def recording(*args, _name=name, _original=original, **kwargs):- widening.append(f"{_name}, reserved={loader._ram_cache.make_room.called}")- return _original(*args, **kwargs)+ def geometry(patch):+ patch.setattr(mistral_encoder, "should_keep_fp8_weights", lambda _device: available)- monkeypatch.setattr(mistral_encoder, name, recording)- return loader, widening+ return geometrydef _config(checkpoint: Path) -> MistralEncoder_Checkpoint_Config:@@ -148,9 +148,9 @@ def test_an_nvfp4_mixed_checkpoint_keeps_its_nvfp4_layers_packed_under_either_fpmonkeypatch: pytest.MonkeyPatch, tmp_path: Path, keep_fp8: bool, evidence: str) -> None:checkpoint, expected, fp8_dequantized = _write_checkpoint(tmp_path, evidence)- loader, widening = _loader(monkeypatch, keep_fp8)+ run = prepare(SEAM, monkeypatch, geometry=_fp8_matmul(keep_fp8), observe=WIDENING)- model = loader._load_text_encoder(_config(checkpoint))+ model = run.load(_config(checkpoint))assert len(model.layers) == LAYERSassert (model.config.num_attention_heads, model.config.num_key_value_heads) == (2, 1)@@ -169,7 +169,7 @@ def test_an_nvfp4_mixed_checkpoint_keeps_its_nvfp4_layers_packed_under_either_fpassert torch.equal(v_proj.weight.float() * v_proj.weight_scale, weight)else:assert torch.equal(v_proj.weight, weight.to(COMPUTE_DTYPE))- assert all(step.endswith("reserved=True") for step in widening), widening+ assert run.order and all(reserved for _step, reserved in run.order), run.order# One reservation for what the state dict ends up holding: the nvfp4 layers packed (the LM head not at all), the# fp8 weights at one byte where the keep branch holds them and at the compute dtype where they are dequantized,@@ -183,23 +183,22 @@ def test_an_nvfp4_mixed_checkpoint_keeps_its_nvfp4_layers_packed_under_either_fp+ full_precision_elements * COMPUTE_DTYPE.itemsize+ 64 # tekken_model)- (reserved,), _ = loader._ram_cache.make_room.call_args- assert loader._ram_cache.make_room.call_count == 1- assert abs(reserved - expected_bytes) < 1024, (reserved, expected_bytes)+ assert len(run.reserved) == 1+ assert abs(run.reserved[0] - expected_bytes) < 1024, (run.reserved, expected_bytes)def test_a_checkpoint_without_nvfp4_layers_loads_as_before(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:checkpoint, expected, _ = _write_checkpoint(tmp_path, evidence="none")- loader, widening = _loader(monkeypatch, keep_fp8=False)+ run = prepare(SEAM, monkeypatch, geometry=_fp8_matmul(False), observe=WIDENING)- model = loader._load_text_encoder(_config(checkpoint))+ model = run.load(_config(checkpoint))for path, weight in expected.items():module = model.get_submodule(path)assert type(module) is torch.nn.Linear, pathassert torch.equal(module.weight, weight.to(COMPUTE_DTYPE)), path- assert loader._ram_cache.make_room.call_count == 1- assert all(step.endswith("reserved=True") for step in widening), widening+ assert len(run.reserved) == 1+ assert run.order and all(reserved for _step, reserved in run.order), run.orderdef test_the_config_reads_layer_and_head_counts_through_packed_projections() -> None:diff --git a/tests/backend/model_manager/load/test_qwen3_encoder_checkpoint_loader.py b/tests/backend/model_manager/load/test_qwen3_encoder_checkpoint_loader.pyindex beec2b518e..cb79e847f6 100644--- a/tests/backend/model_manager/load/test_qwen3_encoder_checkpoint_loader.py+++ b/tests/backend/model_manager/load/test_qwen3_encoder_checkpoint_loader.py@@ -29,8 +29,9 @@ from invokeai.backend.model_manager.configs.qwen3_encoder import Qwen3Encoder_Chfrom invokeai.backend.model_manager.load.model_loaders import z_imagefrom invokeai.backend.model_manager.load.model_loaders.z_image import Qwen3EncoderCheckpointLoaderfrom invokeai.backend.model_manager.taxonomy import Qwen3VariantType-from invokeai.backend.quantization.int8_convrot import Int8ConvrotLinear, build_regular_hadamard+from invokeai.backend.quantization.int8_convrot import Int8ConvrotLinearfrom invokeai.backend.quantization.nvfp4 import NVFP4Linear+from tests.fixtures.quantized_payloads import comfy_quant_marker, nvfp4_signed_tensors, quantize_convrot# Not a known Qwen3 size, so the loader reads the head counts off the projections at its fixed head_dim of 128:# a one-head model.@@ -49,21 +50,11 @@ NVFP4_PROJECTIONS = {}-def _marker_blob(marker: dict) -> torch.Tensor:- return torch.frombuffer(bytearray(json.dumps(marker).encode("utf-8")), dtype=torch.uint8)--def _nvfp4_layer(path: str, positive: torch.Tensor, evidence: str) -> dict[str, torch.Tensor]:- """Codes 2 and 10 are +1.0 and -1.0; with a block scale of 2 and a global scale of 0.25 the weight is +-0.5."""- rows, columns = positive.shape- codes = torch.where(positive, 2, 10).to(torch.uint8)- layer = {- f"{path}.weight": (codes[:, 0::2] << 4) | codes[:, 1::2],- f"{path}.weight_scale": torch.full((rows, columns // 16), 2.0).to(torch.float8_e4m3fn),- f"{path}.weight_scale_2": torch.tensor(0.25),- }+ """`evidence` picks the transport: the per-tensor marker, or the header entry the caller writes."""+ layer, _ = nvfp4_signed_tensors(path, positive)if evidence == "marker":- layer[f"{path}.comfy_quant"] = _marker_blob({"format": "nvfp4"})+ layer[f"{path}.comfy_quant"] = comfy_quant_marker({"format": "nvfp4"})return layer@@ -82,7 +73,7 @@ def _write_checkpoint(tmp_path: Path, evidence: str) -> tuple[Path, dict[str, tofp8_values = torch.randint(-8, 9, (HIDDEN, HIDDEN)).float()tensors["model.layers.0.self_attn.v_proj.weight"] = fp8_values.to(torch.float8_e4m3fn)tensors["model.layers.0.self_attn.v_proj.weight_scale"] = torch.tensor(0.5)- tensors["model.layers.0.self_attn.v_proj.comfy_quant"] = _marker_blob({"format": "float8_e4m3fn"})+ tensors["model.layers.0.self_attn.v_proj.comfy_quant"] = comfy_quant_marker({"format": "float8_e4m3fn"})dense["model.layers.0.self_attn.v_proj.weight"] = fp8_values * 0.5for key, tensor in {@@ -182,24 +173,6 @@ _INT8_GROUP = 64_INT8_MARKER = {"format": "int8_tensorwise", "convrot": True, "convrot_groupsize": _INT8_GROUP}-def _quantize_convrot(weight: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:- """Mirror of comfy-quants: rotate along the input dim, then per-output-channel int8.-- Returns the codes, the scale, and the weight the loader has to reconstruct -- which is the- *dequantized* one, not the original: rounding to 127 levels is lossy, and comparing against the- original would be comparing against something no correct loader produces.- """- out_features, in_features = weight.shape- hadamard = build_regular_hadamard(_INT8_GROUP, dtype=weight.dtype)- rotated = (weight.view(out_features, in_features // _INT8_GROUP, _INT8_GROUP) @ hadamard.T).view(- out_features, in_features- )- scale = rotated.abs().amax(dim=1, keepdim=True) / 127.0- codes = torch.clamp(torch.round(rotated / scale), -128, 127).to(torch.int8)- restored = (codes.float() * scale).view(out_features, in_features // _INT8_GROUP, _INT8_GROUP) @ hadamard- return codes, scale.float(), restored.view(out_features, in_features)--def _write_int8_checkpoint(tmp_path: Path) -> tuple[Path, dict[str, torch.Tensor]]:"""The int8 layout: codes, a per-output-row scale, a marker. Norms and embeddings stay dense,exactly as the 8B repack ships them."""@@ -209,10 +182,10 @@ def _write_int8_checkpoint(tmp_path: Path) -> tuple[Path, dict[str, torch.Tensorprojections = {**NVFP4_PROJECTIONS, "self_attn.v_proj": (HIDDEN, HIDDEN)}for name, shape in projections.items():path = f"model.layers.0.{name}"- codes, scale, restored = _quantize_convrot(torch.randn(shape) * 0.05)+ codes, scale, restored = quantize_convrot(torch.randn(shape) * 0.05, group_size=_INT8_GROUP)tensors[f"{path}.weight"] = codestensors[f"{path}.weight_scale"] = scale- tensors[f"{path}.comfy_quant"] = _marker_blob(_INT8_MARKER)+ tensors[f"{path}.comfy_quant"] = comfy_quant_marker(_INT8_MARKER)# W8A8 activation scales. This path dequantizes the weight and computes in the compute# dtype, so there is nothing to apply them to; one Qwen3-VL repack ships 337 of them.tensors[f"{path}.input_scale"] = torch.ones(shape[1])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.pyindex be662688ee..1282c8f417 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@@ -26,22 +26,17 @@ from invokeai.backend.model_manager.load.model_loaders.qwen_image import (QwenVLEncoderCheckpointLoader,)from invokeai.backend.quantization.nvfp4 import NVFP4Linear+from tests.fixtures.quantized_payloads import comfy_quant_marker, nvfp4_signed_tensorsCOMPUTE_DTYPE = torch.bfloat16def _nvfp4_tensors(path: str, shape: tuple[int, int]) -> tuple[dict[str, torch.Tensor], torch.Tensor]:- """Codes 2 and 10 are +1.0 and -1.0; with a block scale of 2 and a global scale of 0.25 the weight is +-0.5. Comfy- ships an activation scale beside each layer, which the loader has no use for."""- positive = torch.randint(0, 2, shape, dtype=torch.bool)- codes = torch.where(positive, 2, 10).to(torch.uint8)- tensors = {- f"{path}.weight": (codes[:, 0::2] << 4) | codes[:, 1::2],- f"{path}.weight_scale": torch.full((shape[0], shape[1] // 16), 2.0).to(torch.float8_e4m3fn),- f"{path}.weight_scale_2": torch.tensor(0.25),- f"{path}.input_scale": torch.tensor(1.0),- }- return tensors, torch.where(positive, 0.5, -0.5)+ """Comfy ships an activation scale beside each layer, which the loader has no use for -- so it has+ to be dropped rather than reach `load_state_dict`, and it is here for that reason alone."""+ tensors, expected = nvfp4_signed_tensors(path, torch.randint(0, 2, shape, dtype=torch.bool))+ tensors[f"{path}.input_scale"] = torch.tensor(1.0)+ return tensors, expecteddef _packed_bytes(rows: int, columns: int) -> int:@@ -49,7 +44,7 @@ def _packed_bytes(rows: int, columns: int) -> int:def _marker(fmt: str) -> torch.Tensor:- return torch.frombuffer(bytearray(json.dumps({"format": fmt}).encode("utf-8")), dtype=torch.uint8).clone()+ return comfy_quant_marker({"format": fmt})def _patch_common(monkeypatch: pytest.MonkeyPatch, state_dict: dict, metadata: dict) -> list[bool]:diff --git a/tests/backend/model_manager/load/test_z_image_loader_boundaries.py b/tests/backend/model_manager/load/test_z_image_loader_boundaries.pyindex 1b5686e438..cf71b63adb 100644--- a/tests/backend/model_manager/load/test_z_image_loader_boundaries.py+++ b/tests/backend/model_manager/load/test_z_image_loader_boundaries.py@@ -7,35 +7,31 @@ reaches the module."""import json-from types import SimpleNamespace-from unittest.mock import MagicMock+import diffusersimport pytestimport torch+from safetensors import torch as safetensors_torchfrom invokeai.backend.model_manager.configs.default_settings import MainModelDefaultSettingsfrom invokeai.backend.model_manager.configs.main import Main_Checkpoint_ZImage_Configfrom invokeai.backend.model_manager.load import load_default+from invokeai.backend.model_manager.load.model_loaders import z_imagefrom invokeai.backend.model_manager.load.model_loaders.z_image import ZImageCheckpointModel-from invokeai.backend.quantization.int8_convrot import CONVROT_GROUP_SIZE, Int8ConvrotLinear, build_regular_hadamard+from invokeai.backend.quantization.int8_convrot import CONVROT_GROUP_SIZE, Int8ConvrotLinearfrom invokeai.backend.quantization.nvfp4 import NVFP4Linear+from tests.fixtures.loader_seams import Seam, prepare+from tests.fixtures.quantized_payloads import (+ comfy_quant_marker,+ nvfp4_codes,+ nvfp4_tensors,+ quantize_convrot,+ quantize_scaled_fp8,+)MARKER = {"format": "int8_tensorwise", "convrot": True, "convrot_groupsize": CONVROT_GROUP_SIZE}-def _marker_blob(marker: dict) -> torch.Tensor:- return torch.frombuffer(bytearray(json.dumps(marker).encode("utf-8")), dtype=torch.uint8)---def _quantize_convrot(weight: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:- """Mirror of comfy-quants: rotate along the input dim, then per-output-channel int8."""- out_f, in_f = weight.shape- h = build_regular_hadamard(CONVROT_GROUP_SIZE, dtype=weight.dtype)- rotated = (weight.view(out_f, in_f // CONVROT_GROUP_SIZE, CONVROT_GROUP_SIZE) @ h.T).view(out_f, in_f)- scale = rotated.abs().amax(dim=1, keepdim=True) / 127.0- return torch.clamp(torch.round(rotated / scale), -128, 127).to(torch.int8), scale.to(torch.float32)--class _TinyBlock(torch.nn.Module):def __init__(self) -> None:super().__init__()@@ -51,32 +47,25 @@ class _TinyZImage(torch.nn.Module):self.layers = torch.nn.ModuleList([_TinyBlock()])-def _driver(monkeypatch, tmp_path, state_dict: dict) -> tuple[ZImageCheckpointModel, Main_Checkpoint_ZImage_Config]:- import diffusers- from safetensors import torch as safetensors_torch+SEAM = Seam(+ loader=ZImageCheckpointModel,+ module=z_image,+ # The loader calls `safetensors.torch.load_file` through the package, so patching the name on+ # its own module would patch nothing and let it read the empty file the config points at.+ load_file_host=safetensors_torch,+ patches_device=True,+)++def _driver(monkeypatch, tmp_path, state_dict: dict, model_class=None):checkpoint = tmp_path / "z_image_int8_convrot.safetensors"checkpoint.touch()config = Main_Checkpoint_ZImage_Config.model_construct(path=str(checkpoint), name="z-image")- loader = object.__new__(ZImageCheckpointModel)- loader._ram_cache = SimpleNamespace(make_room=MagicMock())- loader._logger = MagicMock()- loader._torch_device = torch.device("cpu")- loader._torch_dtype = torch.float32- loader._apply_fp8_layerwise_casting = lambda model, _config, _submodel: model+ def geometry(patch):+ patch.setattr(diffusers, "ZImageTransformer2DModel", model_class or _TinyZImage, raising=False)- monkeypatch.setattr(diffusers, "ZImageTransformer2DModel", _TinyZImage, raising=False)- monkeypatch.setattr(safetensors_torch, "load_file", lambda _path: state_dict)- monkeypatch.setattr(- "invokeai.backend.model_manager.load.model_loaders.z_image.TorchDevice.choose_torch_device",- lambda: torch.device("cpu"),- )- monkeypatch.setattr(- "invokeai.backend.model_manager.load.model_loaders.z_image.TorchDevice.choose_bfloat16_safe_dtype",- lambda _device: torch.float32,- )- return loader, config+ return prepare(SEAM, monkeypatch, state_dict=state_dict, geometry=geometry), configclass _TinyMixedZImage(torch.nn.Module):@@ -93,39 +82,37 @@ def test_a_mixed_int8_and_scaled_fp8_checkpoint_is_refused(monkeypatch, tmp_pathload. Z-Image made exactly that mistake: it ran every other step of the int8 install and notthis check, and the result was a model that loaded cleanly and generated noise."""- import diffuserstorch.manual_seed(0)- quantized, scale = _quantize_convrot(torch.randn(4, CONVROT_GROUP_SIZE))+ quantized, scale, _restored = quantize_convrot(torch.randn(4, CONVROT_GROUP_SIZE))state_dict = {"layers.0.proj.weight": quantized,"layers.0.proj.weight_scale": scale,- "layers.0.proj.comfy_quant": _marker_blob(MARKER),+ "layers.0.proj.comfy_quant": comfy_quant_marker(MARKER),"layers.1.proj.weight": torch.zeros(4, CONVROT_GROUP_SIZE, dtype=torch.float8_e4m3fn),"layers.1.proj.weight_scale": torch.ones(()),}- loader, config = _driver(monkeypatch, tmp_path, state_dict)- monkeypatch.setattr(diffusers, "ZImageTransformer2DModel", _TinyMixedZImage, raising=False)+ run, config = _driver(monkeypatch, tmp_path, state_dict, model_class=_TinyMixedZImage)with pytest.raises(ValueError, match=r"layers\.1\.proj\.weight_scale"):- loader._load_from_singlefile(config)+ run.load(config)# Refused before the cache was asked to evict anything for a load that cannot finish.- loader._ram_cache.make_room.assert_not_called()+ assert not run.reserveddef test_an_int8_checkpoint_loads_int8_resident_and_un_rotated(monkeypatch, tmp_path) -> None:torch.manual_seed(0)original = torch.randn(4, CONVROT_GROUP_SIZE)- quantized, scale = _quantize_convrot(original)+ quantized, scale, _restored = quantize_convrot(original)state_dict = {"layers.0.proj.weight": quantized,"layers.0.proj.weight_scale": scale,- "layers.0.proj.comfy_quant": _marker_blob(MARKER),+ "layers.0.proj.comfy_quant": comfy_quant_marker(MARKER),}- loader, config = _driver(monkeypatch, tmp_path, state_dict)+ run, config = _driver(monkeypatch, tmp_path, state_dict)- model = loader._load_from_singlefile(config)+ model = run.load(config)# Resident, not decoded: that is what keeps a 5.8 GB checkpoint at 5.8 GB.assert isinstance(model.layers[0].proj, Int8ConvrotLinear)@@ -143,20 +130,20 @@ def test_an_int8_weight_without_a_marker_is_refused(monkeypatch, tmp_path) -> No"""A quantized weight the loader does not recognise would be handed to a float Linear and onlyfail at forward time, if at all. Refuse at load, and say which layers."""torch.manual_seed(1)- quantized, scale = _quantize_convrot(torch.randn(4, CONVROT_GROUP_SIZE))+ quantized, scale, _restored = quantize_convrot(torch.randn(4, CONVROT_GROUP_SIZE))state_dict = {"layers.0.proj.weight": quantized, "layers.0.proj.weight_scale": scale}- loader, config = _driver(monkeypatch, tmp_path, state_dict)+ run, config = _driver(monkeypatch, tmp_path, state_dict)with pytest.raises(ValueError, match=r"int8 weight\(s\) with no `comfy_quant` marker"):- loader._load_from_singlefile(config)+ run.load(config)def test_an_unquantized_checkpoint_is_unaffected(monkeypatch, tmp_path) -> None:torch.manual_seed(2)weight = torch.randn(4, CONVROT_GROUP_SIZE)- loader, config = _driver(monkeypatch, tmp_path, {"layers.0.proj.weight": weight})+ run, config = _driver(monkeypatch, tmp_path, {"layers.0.proj.weight": weight})- model = loader._load_from_singlefile(config)+ model = run.load(config)assert isinstance(model.layers[0].proj, torch.nn.Linear)assert not isinstance(model.layers[0].proj, Int8ConvrotLinear)@@ -190,22 +177,19 @@ def test_a_precision_sensitive_layer_is_not_left_int8(monkeypatch, tmp_path) ->torch.manual_seed(3)sensitive = torch.randn(4, CONVROT_GROUP_SIZE)ordinary = torch.randn(4, CONVROT_GROUP_SIZE)- sensitive_q, sensitive_scale = _quantize_convrot(sensitive)- ordinary_q, ordinary_scale = _quantize_convrot(ordinary)+ sensitive_q, sensitive_scale, _ = quantize_convrot(sensitive)+ ordinary_q, ordinary_scale, _ = quantize_convrot(ordinary)state_dict = {"t_embedder.mlp.0.weight": sensitive_q,"t_embedder.mlp.0.weight_scale": sensitive_scale,- "t_embedder.mlp.0.comfy_quant": _marker_blob(MARKER),+ "t_embedder.mlp.0.comfy_quant": comfy_quant_marker(MARKER),"layers.0.proj.weight": ordinary_q,"layers.0.proj.weight_scale": ordinary_scale,- "layers.0.proj.comfy_quant": _marker_blob(MARKER),+ "layers.0.proj.comfy_quant": comfy_quant_marker(MARKER),}- loader, config = _driver(monkeypatch, tmp_path, state_dict)- import diffusers+ run, config = _driver(monkeypatch, tmp_path, state_dict, model_class=_TinyZImageWithTimestepEmbedder)- monkeypatch.setattr(diffusers, "ZImageTransformer2DModel", _TinyZImageWithTimestepEmbedder, raising=False)-- model = loader._load_from_singlefile(config)+ model = run.load(config)embedder_linear = model.t_embedder.mlp[0]assert not isinstance(embedder_linear, Int8ConvrotLinear)@@ -219,7 +203,7 @@ def test_a_precision_sensitive_layer_is_not_left_int8(monkeypatch, tmp_path) ->assert model.layers[0].proj.weight.dtype is torch.int8# And the reservation covers the widened layer at its post-split width, not at one byte.- (reserved,), _ = loader._ram_cache.make_room.call_args+ reserved = run.reserved[-1]assert reserved >= sensitive.nelement() * 4 + ordinary_q.nelement()@@ -260,15 +244,10 @@ class _TinyNativeZImage(torch.nn.Module):def _nvfp4_layer(path: str, positive: torch.Tensor, tile_row_scales: list[float], global_scale: float) -> dict[str, torch.Tensor]:- """One layer as Comfy stores it. Codes 2 and 10 decode to +1.0 and -1.0, so the expected weight needs no- E2M1 table, and a block scale constant over each 128-row tile row reads the same tiled as row by row."""- codes = torch.where(positive, 2, 10).to(torch.uint8)- scales = torch.tensor(tile_row_scales).repeat_interleave(128).unsqueeze(1).repeat(1, positive.shape[1] // 16)- return {- f"{path}.weight": (codes[:, 0::2] << 4) | codes[:, 1::2],- f"{path}.weight_scale": scales.to(torch.float8_e4m3fn),- f"{path}.weight_scale_2": torch.tensor(global_scale),- }+ """A block scale constant over each 128-row tile row, which reads the same tiled as row by row --+ so the split under test can be checked without the de-swizzle being part of the expectation."""+ grid = torch.tensor(tile_row_scales).repeat_interleave(128).unsqueeze(1).repeat(1, positive.shape[1] // 16)+ return nvfp4_tensors(path, nvfp4_codes(positive), block_scale=grid, global_scale=global_scale)def test_an_nvfp4_checkpoint_loads_packed_with_its_qkv_split_on_tile_rows(monkeypatch, tmp_path) -> None:@@ -302,10 +281,7 @@ def test_an_nvfp4_checkpoint_loads_packed_with_its_qkv_split_on_tile_rows(monkey"text_encoders.qwen3.layers.0.mlp.up_proj",)}- loader, config = _driver(monkeypatch, tmp_path, state_dict)- import diffusers-- monkeypatch.setattr(diffusers, "ZImageTransformer2DModel", _TinyNativeZImage, raising=False)+ run, config = _driver(monkeypatch, tmp_path, state_dict, model_class=_TinyNativeZImage)monkeypatch.setattr("invokeai.backend.model_manager.load.model_loaders.z_image.read_safetensors_metadata",lambda _path, _logger: {"_quantization_metadata": json.dumps({"layers": header})},@@ -316,7 +292,7 @@ def test_an_nvfp4_checkpoint_loads_packed_with_its_qkv_split_on_tile_rows(monkeylambda _device: torch.bfloat16,)- model = loader._load_from_singlefile(config)+ model = run.load(config)bf16 = torch.bfloat16x = torch.randn(3, 64, dtype=bf16)@@ -343,8 +319,8 @@ def test_an_nvfp4_checkpoint_loads_packed_with_its_qkv_split_on_tile_rows(monkey# which would ask for about 45 KB more.packed = (384 + 128) * 32 + (384 + 128) * 4dense = 128 * 64 * 2 + 128 * 2 + 4 * 4 * 2- loader._ram_cache.make_room.assert_called_once()- (reserved,), _ = loader._ram_cache.make_room.call_args+ assert len(run.reserved) == 1+ reserved = run.reserved[0]assert packed + dense <= reserved < packed + dense + 1024@@ -358,11 +334,10 @@ def test_a_scaled_fp8_checkpoint_stays_packed_when_storage_is_on(monkeypatch, tm"""torch.manual_seed(3)original = torch.randn(4, CONVROT_GROUP_SIZE)- scale = (original.abs().max() / 448.0).to(torch.float32)- packed = (original / scale).to(torch.float8_e4m3fn)- state_dict = {"layers.0.proj.weight": packed, "layers.0.proj.weight_scale": scale}+ fp8 = quantize_scaled_fp8(original)+ state_dict = {"layers.0.proj.weight": fp8.codes, "layers.0.proj.weight_scale": fp8.scale}- loader, driver_config = _driver(monkeypatch, tmp_path, state_dict)+ run, driver_config = _driver(monkeypatch, tmp_path, state_dict)config = Main_Checkpoint_ZImage_Config.model_construct(path=driver_config.path,name="z-image",@@ -372,7 +347,7 @@ def test_a_scaled_fp8_checkpoint_stays_packed_when_storage_is_on(monkeypatch, tmmonkeypatch.setattr(load_default, "should_keep_fp8_weights", lambda _device: False)monkeypatch.setattr(load_default, "_device_supports_fp8_storage", lambda _device, _logger=None: True)- model = loader._load_from_singlefile(config)+ model = run.load(config)proj = model.layers[0].projassert proj.weight.dtype is torch.float8_e4m3fn, "folded back to a float dtype"diff --git a/tests/backend/model_manager/load/test_z_image_state_dict_utils.py b/tests/backend/model_manager/load/test_z_image_state_dict_utils.pyindex 3b3f00daa6..a6af361a78 100644--- a/tests/backend/model_manager/load/test_z_image_state_dict_utils.py+++ b/tests/backend/model_manager/load/test_z_image_state_dict_utils.py@@ -1,7 +1,5 @@"""Unit tests for the Z-Image GGUF/ComfyUI -> diffusers state-dict converter."""-import json-import pytestimport torch@@ -14,6 +12,7 @@ from tests.backend.model_manager.load.state_dicts.utils import keys_to_mock_statfrom tests.backend.model_manager.load.state_dicts.z_image_transformer_comfyui_keys import (state_dict_keys as z_image_keys,)+from tests.fixtures.quantized_payloads import comfy_quant_markerclass TestConvertZImageGgufToDiffusers:@@ -73,10 +72,6 @@ class TestConvertZImageGgufToDiffusers:assert torch.allclose(out["blk.attention.to_v.weight"], qkv[4:6])-def _marker_blob(marker: dict) -> torch.Tensor:- return torch.frombuffer(bytearray(json.dumps(marker).encode("utf-8")), dtype=torch.uint8)--MARKER = {"format": "int8_tensorwise", "convrot": True, "convrot_groupsize": 256}@@ -112,7 +107,7 @@ class TestQkvQuantizationSideChannel:def test_marker_blob_is_copied_not_split(self):# `.comfy_quant` is a 1-D JSON byte string describing the layer, not a per-channel vector.- blob = torch.frombuffer(b'{"format":"float8_e4m3fn"}', dtype=torch.uint8).clone()+ blob = comfy_quant_marker({"format": "float8_e4m3fn"})out = _convert_z_image_gguf_to_diffusers({"blk.attention.qkv.weight": torch.arange(12, dtype=torch.float32).reshape(6, 2),@@ -147,7 +142,7 @@ class TestQkvQuantizationSideChannel:sd = {f"{prefix}.qkv.weight": torch.zeros(3 * 4, 256, dtype=torch.int8),f"{prefix}.qkv.weight_scale": torch.ones(3 * 4, 1),- f"{prefix}.qkv.comfy_quant": _marker_blob(MARKER),+ f"{prefix}.qkv.comfy_quant": comfy_quant_marker(MARKER),"x_embedder.weight": torch.zeros(2, 2),}markers = extract_int8_convrot_markers(_convert_z_image_gguf_to_diffusers(sd))diff --git a/tests/backend/quantization/test_int8_convrot_state_dict.py b/tests/backend/quantization/test_int8_convrot_state_dict.pyindex e5512c5479..2e86f0aa47 100644--- a/tests/backend/quantization/test_int8_convrot_state_dict.py+++ b/tests/backend/quantization/test_int8_convrot_state_dict.py@@ -6,8 +6,6 @@ part a loader can get wrong without anything raising — every failure below wousurface as a model that loads cleanly and generates noise."""-import json-import pytestimport torchfrom safetensors.torch import save_file@@ -27,20 +25,17 @@ from invokeai.backend.quantization.int8_convrot import (split_int8_convrot_layers,swap_in_int8_linears,)+from tests.fixtures.quantized_payloads import comfy_quant_markerMARKER = {"format": "int8_tensorwise", "convrot": True, "convrot_groupsize": CONVROT_GROUP_SIZE}-def _marker_blob(marker: dict) -> torch.Tensor:- return torch.frombuffer(bytearray(json.dumps(marker).encode("utf-8")), dtype=torch.uint8)--class TestWhichLayersAreClaimed:def test_an_int8_marker_is_claimed_and_removed(self) -> None:sd = {"blocks.0.attn.wq.weight": torch.zeros(4, CONVROT_GROUP_SIZE, dtype=torch.int8),"blocks.0.attn.wq.weight_scale": torch.ones(4, 1),- "blocks.0.attn.wq.comfy_quant": _marker_blob(MARKER),+ "blocks.0.attn.wq.comfy_quant": comfy_quant_marker(MARKER),}markers = extract_int8_convrot_markers(sd)@@ -53,7 +48,7 @@ class TestWhichLayersAreClaimed:sd = {"layer.weight": torch.zeros(4, 4, dtype=torch.float8_e4m3fn),"layer.weight_scale": torch.ones(1),- "layer.comfy_quant": _marker_blob({"format": "float8_e4m3fn"}),+ "layer.comfy_quant": comfy_quant_marker({"format": "float8_e4m3fn"}),}assert extract_int8_convrot_markers(sd) == {}assert "layer.comfy_quant" in sd@@ -66,7 +61,7 @@ class TestWhichLayersAreClaimed:"txtfusion.0.weight": torch.zeros(8, 8, dtype=torch.bfloat16),"blocks.0.attn.wq.weight": torch.zeros(4, CONVROT_GROUP_SIZE, dtype=torch.int8),"blocks.0.attn.wq.weight_scale": torch.ones(4, 1),- "blocks.0.attn.wq.comfy_quant": _marker_blob(MARKER),+ "blocks.0.attn.wq.comfy_quant": comfy_quant_marker(MARKER),}assert set(extract_int8_convrot_markers(sd)) == {"blocks.0.attn.wq"}@@ -78,7 +73,7 @@ class TestWhichLayersAreClaimed:def test_the_group_size_travels_with_each_marker(self) -> None:"""Every marker in the Krea-2 build says 256, but the flag is per tensor and anotherproducer may vary it, so it is read rather than assumed."""- sd = {"layer.comfy_quant": _marker_blob({"format": "int8_tensorwise", "convrot_groupsize": 64})}+ sd = {"layer.comfy_quant": comfy_quant_marker({"format": "int8_tensorwise", "convrot_groupsize": 64})}assert extract_int8_convrot_markers(sd)["layer"]["convrot_groupsize"] == 64@@ -331,7 +326,7 @@ class TestTheKeysTheOrphanCheckAndTheSidecarDropActOn:sd = {"blocks.0.input_scaler.weight": torch.ones(4, 4),"blocks.0.attn.input_scale": torch.ones(1),- "blocks.0.attn.comfy_quant": _marker_blob({"format": "float8_e4m3fn"}),+ "blocks.0.attn.comfy_quant": comfy_quant_marker({"format": "float8_e4m3fn"}),}assert set(drop_unconsumed_quantization_sidecars(sd)) == {"blocks.0.input_scaler.weight"}diff --git a/tests/backend/quantization/test_nvfp4.py b/tests/backend/quantization/test_nvfp4.pyindex e181b6a162..444058f4e9 100644--- a/tests/backend/quantization/test_nvfp4.py+++ b/tests/backend/quantization/test_nvfp4.py@@ -7,7 +7,6 @@ bf16 build. That slice is one tile row high: it pins the layout inside a row ofwhile the order of the tile rows rests on the formula test."""-import jsonfrom pathlib import Pathimport pytest@@ -32,14 +31,11 @@ from invokeai.backend.quantization.nvfp4 import (split_nvfp4_rows,unblock_scale_grid,)+from tests.fixtures.quantized_payloads import comfy_quant_marker, nvfp4_tensorsFIXTURE = Path(__file__).parent / "data" / "z_image_turbo_nvfp4_slices.safetensors"-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 measuredagainst real files: element ``[m, k]`` lands at flat position ``position``."""@@ -53,15 +49,10 @@ def _stored_layout(grid: torch.Tensor) -> torch.Tensor: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 the- tile layout, which the tests above pin on their own."""- rows, in_features = codes.shape- return {- f"{path}.weight": (codes[:, 0::2] << 4) | codes[:, 1::2],- f"{path}.weight_scale": torch.full((rows, in_features // 16), block_scale).to(torch.float8_e4m3fn),- f"{path}.weight_scale_2": torch.tensor(global_scale),- f"{path}.comfy_quant": _marker_blob({"format": "nvfp4"}),- }+ """One layer in checkpoint layout, carrying the per-tensor marker this module's subject reads."""+ layer = nvfp4_tensors(path, codes, block_scale=block_scale, global_scale=global_scale)+ layer[f"{path}.comfy_quant"] = comfy_quant_marker({"format": "nvfp4"})+ return layerdef _zero_layer(path: str, rows: int = 128) -> dict[str, torch.Tensor]:@@ -140,7 +131,7 @@ def test_a_real_checkpoint_slice_decodes_to_its_bf16_build(layer: str) -> None:def test_popped_layers_keep_their_tensors_as_stored_and_leave_the_rest_for_the_fp8_path() -> None:fp8_weight = torch.randn(32, 32).to(torch.float8_e4m3fn)fp8_scale = torch.tensor(0.5)- fp8_marker = _marker_blob({"format": "float8_e4m3fn"})+ fp8_marker = comfy_quant_marker({"format": "float8_e4m3fn"})tekken = torch.randint(0, 256, (64,), dtype=torch.uint8)sd = {**_zero_layer("blocks.0.mlp"),@@ -243,7 +234,7 @@ def test_a_malformed_layer_is_refused_before_any_layer_is_taken_out() -> None:)def test_a_marker_that_contradicts_its_tensors_is_refused(tensors: str, marker: dict, message: str) -> None:sd = {"layer.weight": torch.zeros(128, 64)} if tensors == "dense" else _zero_layer("layer")- sd["layer.comfy_quant"] = _marker_blob(marker)+ sd["layer.comfy_quant"] = comfy_quant_marker(marker)with pytest.raises(ValueError, match=message):pop_nvfp4_layers(sd)diff --git a/tests/backend/quantization/test_quantized_payloads.py b/tests/backend/quantization/test_quantized_payloads.pynew file mode 100644index 0000000000..ffeea5efba--- /dev/null+++ b/tests/backend/quantization/test_quantized_payloads.py@@ -0,0 +1,131 @@+"""Do the shared checkpoint payloads say what the production decoders hear?++`tests/fixtures/quantized_payloads.py` is now the source of the quantized layers in a dozen test+files. That makes it a load-bearing statement about what ComfyUI writes, and a statement that is+wrong in a self-consistent way is the worst case: every test that builds a layer with it and asserts+against its own arithmetic stays green while agreeing about the wrong encoding.++So each payload is handed to the code that reads real checkpoints, and the weight that comes back is+compared with the one the payload says it stored. What that catches is the half the builders cannot+check themselves -- nibble order, which tensor the scale multiplies, the axis it is broadcast along,+the key spellings -- because that half is decided by the decoder, which was written from the format+rather than from these fixtures.++A round trip cannot see everything, though. It is invariant to the two constants the builders make+the most noise about, `INT8_LEVELS` and `FP8_E4M3_MAX`: halve either and the codes and the scale+move in opposite directions and cancel. Those are pinned separately below, against what torch says+the dtype's range is rather than against the fixture's own numbers.+"""++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++CPU = torch.device("cpu")+++def test_the_convrot_payload_dequantizes_to_the_weight_it_claims() -> None:+ """Driven through `Int8ConvrotLinear`, which owns the un-rotation.++ The rotation is the part a builder cannot verify alone: codes and scale of the right shape and+ magnitude come out either way, and a payload that rotated in the wrong direction -- or not at+ all -- would still look like a plausible int8 layer to every shape check in the suite.+ """+ torch.manual_seed(0)+ original = torch.randn(8, CONVROT_GROUP_SIZE)+ payload = quantize_convrot(original)++ linear = Int8ConvrotLinear(payload.codes, payload.scale, convrot=True)+ decoded = linear._dequantized_weight(CPU, torch.float32)++ assert torch.allclose(decoded, payload.dequantized, atol=1e-4)+ # And close to the weight that went in, which is what makes the payload a useful stand-in at all.+ assert torch.corrcoef(torch.stack([decoded.flatten(), original.flatten()]))[0, 1] > 0.999+++def test_the_convrot_codes_fill_the_int8_range_without_saturating_it() -> None:+ """What the round trip cannot see: the number of levels the scale is derived from.++ Halve `INT8_LEVELS` and every code halves while the scale doubles, so the decoded weight is+ unchanged and every other test here still passes -- the checkpoint would simply be throwing+ away a bit of precision per weight, silently. The statement that does pin it is about the range:+ the extreme weight lands on int8's largest magnitude, and nothing saturates against it.+ """+ torch.manual_seed(1)+ payload = quantize_convrot(torch.randn(8, CONVROT_GROUP_SIZE))+ codes = payload.codes.to(torch.int32)++ top = torch.iinfo(torch.int8).max+ # Per row, because the scale is per output channel: each row's own extreme lands on the top code.+ assert torch.equal(codes.abs().amax(dim=1), torch.full((codes.shape[0],), top)), codes.abs().amax(dim=1)+ # `-128` exists in int8 but the exporters leave it unused to keep the range symmetric. Too few+ # levels would pile many weights onto the extremes instead of only each row's largest.+ assert codes.min().item() > -128+ assert (codes.abs() == top).sum().item() <= 2 * codes.shape[0]+++def test_the_convrot_scale_is_one_per_output_channel_and_reaches_its_own_row() -> None:+ """A `[out, 1]` scale is what `as_column_scale` broadcasts down the output axis. Built here with+ rows of deliberately different magnitudes and a non-square weight, so a scale taken over the+ wrong axis has the wrong shape, and one applied to the wrong axis puts each row's magnitude on+ another row. Driven through the decoder rather than asserted against the fixture's own arithmetic.+ """+ original = torch.zeros(4, CONVROT_GROUP_SIZE)+ for row in range(4):+ original[row] = torch.full((CONVROT_GROUP_SIZE,), 10.0**row)+ payload = quantize_convrot(original)++ assert payload.scale.shape == (4, 1)+ decoded = Int8ConvrotLinear(payload.codes, payload.scale, convrot=True)._dequantized_weight(CPU, torch.float32)++ magnitudes = decoded.abs().amax(dim=1)+ assert torch.all(magnitudes[:-1] < magnitudes[1:]), f"rows did not keep their own scale: {magnitudes}"+++def test_the_scaled_fp8_payload_dequantizes_through_the_real_extraction() -> None:+ """Through `extract_fp8_scaled_layers` + `dequantize_fp8_scaled`, so the key spellings are part+ of the assertion: a payload whose scale is stored under a name the extraction does not look for+ would leave the weight un-scaled and the orphaned scale behind."""+ torch.manual_seed(2)+ original = torch.randn(4, 16)+ payload = quantize_scaled_fp8(original)+ state_dict = {"lin.weight": payload.codes, "lin.weight_scale": payload.scale}++ layers = extract_fp8_scaled_layers(state_dict)+ dequantize_fp8_scaled(state_dict, layers, torch.float32)++ assert set(state_dict) == {"lin.weight"}, "the scale was not consumed under the name it was stored as"+ assert torch.equal(state_dict["lin.weight"], payload.dequantized)+ assert torch.corrcoef(torch.stack([state_dict["lin.weight"].flatten(), original.flatten()]))[0, 1] > 0.999+++def test_the_scaled_fp8_codes_reach_the_top_of_e4m3() -> None:+ """The other constant a round trip is blind to. `FP8_E4M3_MAX` set too low wastes range; set too+ high it overflows to infinity. Pinned against `torch.finfo`, which is the dtype's own answer+ rather than a restatement of the fixture's number."""+ torch.manual_seed(3)+ payload = quantize_scaled_fp8(torch.randn(4, 16))++ assert payload.codes.float().abs().max().item() == torch.finfo(torch.float8_e4m3fn).max+ assert payload.codes.float().isfinite().all(), "the scale let a weight overflow e4m3"+++def test_the_nvfp4_payload_unpacks_to_the_exact_weights_it_claims() -> None:+ """Exact, not approximate: the signed payload is built from the two codes worth +-1.0 and scales+ that are powers of two, so every product is representable. A swapped nibble order transposes the+ sign pattern within each pair and a dropped `weight_scale_2` moves everything by 4x -- both+ exactly visible here, and both invisible to a magnitude check."""+ torch.manual_seed(4)+ # 128 rows by 64 columns is the smallest layer nvfp4 accepts: the scale grid has to be one whole+ # cuBLAS tile, 128 rows by 4 blocks of 16.+ positive = torch.randint(0, 2, (128, 64), dtype=torch.bool)+ tensors, expected = nvfp4_signed_tensors("lin", positive)++ linear = NVFP4Linear(tensors["lin.weight"], tensors["lin.weight_scale"], tensors["lin.weight_scale_2"])+ decoded = linear._dequantized_weight(CPU, torch.float32)++ assert linear.in_features == 64, "the packed weight's logical width was not doubled"+ assert torch.equal(decoded, expected)diff --git a/tests/fixtures/loader_seams.py b/tests/fixtures/loader_seams.pynew file mode 100644index 0000000000..adae6cbd73--- /dev/null+++ b/tests/fixtures/loader_seams.py@@ -0,0 +1,168 @@+"""Drive a real loader over a toy checkpoint, and record what it did on the way.++Sixteen places in this tree take a checkpoint apart before a model exists to put it into: strip+prefixes, read markers, read the header, pick a quantization branch, convert key names, reserve+cache room, swap modules in. Each has grown its own test driver -- twenty files build a loader with+``object.__new__`` and most define a helper to do it -- and each driver stubs a slightly different+set of the loader's surroundings. The cost is not the duplication. It is that a driver which stubs+one thing too many turns its tests green without the loader having done the work, and nothing+points that out.++So the *surroundings* are described here, once, as data: a :class:`Seam` says which of them a given+loader reaches for, and :func:`prepare` installs those and no others.++The loader's own attributes -- cache handle, logger, device -- are a separate matter and are always+supplied: ``object.__new__`` leaves an instance with none of them, so putting them back is+reconstituting the object rather than standing in for something outside it. Not every loader reads+all three (the Mistral encoder builds its own logger), but a switch per attribute would cost more+than the attribute.++What a run records is as much the point as what it returns. ``reserved``, ``dtypes_at_make_room``+and ``order`` make the ordering constraint visible -- room has to be reserved *before* the weights+widen, or the reservation is for a smaller model than the one about to exist -- and that constraint+is held at every seam today by the order the calls happen to be written in. An end-state assertion+cannot see it. These can.+"""++from collections.abc import Callable, Mapping+from dataclasses import dataclass, field+from types import ModuleType+from typing import Any+from unittest.mock import MagicMock++import pytest+import torch++from invokeai.backend.util.devices import TorchDevice++#: Distinguishes "do not touch `read_safetensors_metadata`" from "make it return nothing". Both are+#: real cases: a loader can be tested against a file whose header it really reads, and against that+#: read yielding nothing, and those are different paths through it.+UNSET = object()+++@dataclass(frozen=True)+class Seam:+ """Which of a loader's surroundings a test has to stand in for."""++ loader: type+ #: Where the loader's ``from x import y`` names live, and so where a patch has to land.+ module: ModuleType+ entry: str = "_load_from_singlefile"+ #: Only for a loader that calls ``safetensors.torch.load_file`` through the package rather than+ #: importing the name. Patching the wrong host patches a name nobody reads, and the loader then+ #: quietly reads whatever file the config points at.+ load_file_host: ModuleType | None = None+ compute_dtype: torch.dtype = torch.float32+ #: ``TorchDevice`` is one class shared by every loader module, so this is a switch rather than a+ #: host: patching it is process-wide for the test's duration, not scoped to ``module``.+ patches_device: bool = False+ #: Loaders that never read ``self._torch_dtype``. Setting it anyway would hide one that started.+ sets_torch_dtype: bool = True+ #: False for loaders with no FP8 Storage pass, and for those whose tests want the real one:+ #: stubbing ``_apply_fp8_layerwise_casting`` by default would take real code out of their path.+ casts_fp8_storage: bool = True+++@dataclass+class SeamRun:+ """A loader standing ready over a checkpoint, plus the record of what it does when run.++ Kept separate from the call so that a refusal can be asserted with the record still in hand:+ "it raised" and "it raised *before* reserving cache room for a load that cannot finish" are+ different claims, and only the second one is worth making.+ """++ seam: Seam+ loader: Any+ #: Every ``make_room`` argument, in call order. A loader that reserves twice is reserving+ #: absolutely rather than additively, so the last call has to cover the peak on its own.+ reserved: list[int] = field(default_factory=list)+ #: The dtypes of the dict *the loader is working on* when room was first reserved. A weight+ #: already widened here was widened before it was paid for. Empty when the loader reads a real+ #: file, because then there is no served dict to watch.+ dtypes_at_make_room: dict[str, torch.dtype] = field(default_factory=dict)+ #: ``(name, rooms_reserved)`` for each observed step, in call order -- how many times+ #: ``make_room`` had been called by the time that step ran.+ order: list[tuple[str, int]] = field(default_factory=list)+ casting_calls: int = 0++ def load(self, *args: Any) -> Any:+ """Call the seam's entry point. Most take the config alone; ``_load_model`` also takes the+ submodel, which is the argument deciding which part of a checkpoint is being asked for."""+ return getattr(self.loader, self.seam.entry)(*args)+++def prepare(+ seam: Seam,+ monkeypatch: pytest.MonkeyPatch,+ *,+ state_dict: Mapping[str, torch.Tensor] | None = None,+ metadata: Mapping[str, str] | None | object = UNSET,+ geometry: Callable[[pytest.MonkeyPatch], None] = lambda _monkeypatch: None,+ observe: tuple[str, ...] = (),+) -> SeamRun:+ """Stand ``seam``'s loader up over ``state_dict``, or over whatever file the config points at.++ Each read gets its own copy of ``state_dict``, because loaders rebind and clear the dict they+ are handed and a test that loads twice must not be reading the first load's leavings. The copy+ the loader is working on is the one ``dtypes_at_make_room`` watches: watching the caller's dict+ instead would make that record a restatement of the test's own input, which is a probe that+ cannot fail.++ Leaving ``state_dict`` out lets the loader read an actual checkpoint, which is the only way to+ exercise ``read_safetensors_metadata`` for real. Seven loaders call it and almost every test+ stubs it out; of the seams driven here today only the Mistral encoder writes a real file.++ ``observe`` names module-level steps of the loader to wrap, so that :attr:`SeamRun.order` says+ how much room had been reserved by the time each one ran.+ """+ run = SeamRun(seam=seam, loader=None)+ served: list[dict[str, torch.Tensor]] = []++ def load_file(_path):+ served.append(dict(state_dict or {}))+ return served[-1]++ def make_room(reserve: int) -> None:+ if not run.reserved and served:+ run.dtypes_at_make_room = {key: value.dtype for key, value in served[-1].items()}+ run.reserved.append(reserve)++ def apply_casting(model: torch.nn.Module, _config: Any, _submodel: Any) -> torch.nn.Module:+ run.casting_calls += 1+ return model++ loader = object.__new__(seam.loader)+ loader._ram_cache = MagicMock(make_room=make_room)+ loader._logger = MagicMock()+ loader._torch_device = torch.device("cpu")+ if seam.sets_torch_dtype:+ loader._torch_dtype = seam.compute_dtype+ if seam.casts_fp8_storage:+ loader._apply_fp8_layerwise_casting = apply_casting+ run.loader = loader++ if state_dict is not None:+ monkeypatch.setattr(seam.load_file_host or seam.module, "load_file", load_file)+ if metadata is not UNSET:+ header = dict(metadata) if metadata is not None else None+ monkeypatch.setattr(seam.module, "read_safetensors_metadata", lambda _path, _logger: header)+ if seam.patches_device:+ monkeypatch.setattr(TorchDevice, "choose_torch_device", staticmethod(lambda: torch.device("cpu")))+ monkeypatch.setattr(TorchDevice, "choose_bfloat16_safe_dtype", staticmethod(lambda _d: seam.compute_dtype))++ # Before the wrappers, so a geometry that replaces an observed name cannot silently discard the+ # observation: this way each wrapper closes over whatever geometry left in place.+ geometry(monkeypatch)++ for name in observe:+ original = getattr(seam.module, name)++ def step(*args, _name=name, _original=original, **kwargs):+ run.order.append((_name, len(run.reserved)))+ return _original(*args, **kwargs)++ monkeypatch.setattr(seam.module, name, step)++ return rundiff --git a/tests/fixtures/quantized_payloads.py b/tests/fixtures/quantized_payloads.pynew file mode 100644index 0000000000..e14e2e1afd--- /dev/null+++ b/tests/fixtures/quantized_payloads.py@@ -0,0 +1,142 @@+"""Checkpoint payloads in the shapes the producers actually write.++Every loader test that wants a quantized layer has so far built one itself: five copies of the+convrot quantizer, five nvfp4 packers, six spellings of the fp8 scale, thirteen marker blobs. They+agree today, which is the problem -- they agree by having been copied, so a producer detail that is+wrong is wrong in all of them at once, and a test asserting against its own copy of the encoding+asserts nothing about the encoding.++These are mirrors of what ComfyUI's exporters emit, and each docstring says which part of the+producer it is mirroring. Nothing here imports a loader: a payload is what arrives on disk, and the+question of what a loader does with it belongs to the caller.+"""++import json+from collections.abc import Mapping+from typing import Any, NamedTuple++import torch++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+# largest weight lands on the top code rather than at infinity.+FP8_E4M3_MAX = 448.0++# int8 is quantized against 127, not 128: the exporters keep the range symmetric and leave -128+# unused, so a scale derived from 128 is off by one level on every weight.+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.+NVFP4_CODE_PLUS_ONE = 2+NVFP4_CODE_MINUS_ONE = 10+++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.++ ``pad`` appends NUL bytes, which is what Comfy does when it writes these at a fixed width. The+ clone gives the tensor its own storage instead of a view onto the buffer built here, which is+ what keeps a payload independent of the builder that made it.+ """+ raw = json.dumps(dict(marker)).encode("utf-8") + b"\x00" * pad+ return torch.frombuffer(bytearray(raw), dtype=torch.uint8).clone()+++class Int8ConvrotPayload(NamedTuple):+ """What an ``int8_tensorwise`` + ``convrot`` layer stores, and what it must come back as.++ ``dequantized`` is the *round trip*, not the weight that went in: rounding to 127 levels is+ lossy, so the original is something no correct loader can produce and comparing against it+ measures the quantizer's error rather than the loader's.+ """++ codes: torch.Tensor+ scale: torch.Tensor+ dequantized: torch.Tensor+++def quantize_convrot(weight: torch.Tensor, *, group_size: int = CONVROT_GROUP_SIZE) -> Int8ConvrotPayload:+ """Mirror of comfy-quants: rotate along the input dim in groups, then per-output-channel int8.++ The rotation is what makes this scheme different from plain int8, and it is also what a loader+ can silently skip: applying the scale without un-rotating gives a weight of the right shape and+ magnitude that correlates with the original at roughly nothing.+ """+ out_features, in_features = weight.shape+ hadamard = build_regular_hadamard(group_size, dtype=weight.dtype)+ grouped = weight.view(out_features, in_features // group_size, group_size)+ rotated = (grouped @ hadamard.T).view(out_features, in_features)++ scale = rotated.abs().amax(dim=1, keepdim=True) / INT8_LEVELS+ codes = torch.clamp(torch.round(rotated / scale), -128, 127).to(torch.int8)++ restored = (codes.float() * scale).view(out_features, in_features // group_size, group_size) @ hadamard+ return Int8ConvrotPayload(codes, scale.to(torch.float32), restored.view(out_features, in_features))+++class ScaledFp8Payload(NamedTuple):+ """What a per-tensor scaled-fp8 layer stores, and the weight it decodes back to.++ ``dequantized`` is the round trip rather than the input, for the same reason as+ :class:`Int8ConvrotPayload`: e4m3 has three mantissa bits, so the original is not something a+ correct loader can return.+ """++ codes: torch.Tensor+ scale: torch.Tensor+ dequantized: torch.Tensor+++def quantize_scaled_fp8(weight: torch.Tensor) -> ScaledFp8Payload:+ """Mirror of ComfyUI's per-tensor "scaled fp8": one float32 scalar beside an e4m3 weight.++ The scale is stored as the multiplier the loader applies, so the codes are the weight *divided*+ by it. Getting that direction wrong survives every shape check and every dtype check.+ """+ scale = (weight.abs().max() / FP8_E4M3_MAX).to(torch.float32)+ codes = (weight / scale).to(torch.float8_e4m3fn)+ return ScaledFp8Payload(codes, scale, codes.float() * scale)+++def nvfp4_codes(positive: torch.Tensor) -> torch.Tensor:+ """Codes for a layer of exactly +1.0 and -1.0 in E2M1, one per element of ``positive``."""+ return torch.where(positive, NVFP4_CODE_PLUS_ONE, NVFP4_CODE_MINUS_ONE).to(torch.uint8)+++def nvfp4_tensors(+ path: str, codes: torch.Tensor, *, block_scale: float | torch.Tensor, global_scale: float+) -> dict[str, torch.Tensor]:+ """One nvfp4 layer in checkpoint layout: packed nibbles, a block-scale grid, a global scalar.++ Two 4-bit codes share a byte, high nibble first, so the stored weight is half as wide as the+ logical one. A number fills the grid uniformly; pass a grid to vary it. Either way the grid has+ to *be* a whole number of cuBLAS tiles, so the smallest layer this can build is 128 rows by 64+ columns -- `NVFP4Linear` refuses anything else rather than padding it.++ No expected weight comes back, because stating one means restating the tile permutation the+ decode applies (`unblock_scale_grid`), and an expectation derived from the implementation is no+ expectation. Use :func:`nvfp4_signed_tensors` for a layer whose decoded weight is known outright.+ """+ rows, in_features = codes.shape+ grid = block_scale if isinstance(block_scale, torch.Tensor) else torch.full((rows, in_features // 16), block_scale)+ return {+ f"{path}.weight": (codes[:, 0::2] << 4) | codes[:, 1::2],+ f"{path}.weight_scale": grid.to(torch.float8_e4m3fn),+ f"{path}.weight_scale_2": torch.tensor(global_scale),+ }+++def nvfp4_signed_tensors(path: str, positive: torch.Tensor) -> tuple[dict[str, torch.Tensor], torch.Tensor]:+ """An nvfp4 layer whose every weight is exactly +0.5 or -0.5, and that expected weight.++ A block scale of 2 and a global scale of 0.25 put the product at +-0.5, exact in every dtype+ involved, so the assertion can be equality rather than a tolerance and a dropped+ ``weight_scale_2`` moves the result by a factor of four. The block scale is uniform, which is+ what makes the expectation independent of the cuBLAS tile order -- that order is pinned on its+ own in ``tests/backend/quantization/test_nvfp4.py`` rather than restated here.+ """+ codes = 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)