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
fix(loaders): refuse a rotated int8 layer where only the scale would be folded
Alexander Eichhorn82f1b12c103f
diff --git a/invokeai/backend/model_manager/load/model_loaders/comfyui_state_dict_utils.py b/invokeai/backend/model_manager/load/model_loaders/comfyui_state_dict_utils.pyindex 1eec64389d..8c4f86493d 100644--- a/invokeai/backend/model_manager/load/model_loaders/comfyui_state_dict_utils.py+++ b/invokeai/backend/model_manager/load/model_loaders/comfyui_state_dict_utils.py@@ -13,6 +13,7 @@ need a second copy.import torchfrom invokeai.backend.quantization.fp8_scaled import expand_weight_scale, is_scale_metadata_key+from invokeai.backend.quantization.int8_convrot import reject_int8_layers_a_plain_fold_cannot_decodedef _strip_comfyui_prefix(sd: dict) -> dict:@@ -33,7 +34,7 @@ def _strip_comfyui_prefix(sd: dict) -> dict:return stripped-def _dequantize_comfyui_fp8(sd: dict, compute_dtype: torch.dtype) -> int:+def _dequantize_comfyui_fp8(sd: dict, compute_dtype: torch.dtype, what: str = "This checkpoint") -> int:"""Dequantize ComfyUI-style fp8_scaled weights in-place. Returns count of dequantized tensors.Weights are dequantized directly to `compute_dtype` (typically bf16) instead of via a@@ -56,6 +57,7 @@ def _dequantize_comfyui_fp8(sd: dict, compute_dtype: torch.dtype) -> int:in the file is a scale that still needs applying — i.e. a checkpoint must not shipalready-dequantized weights alongside their scales."""+ reject_int8_layers_a_plain_fold_cannot_decode(sd, what)scale_suffixes = (".weight_scale", ".scale_weight")weight_scale_keys = [k for k in sd.keys() if isinstance(k, str) and k.endswith(scale_suffixes)]count = 0diff --git a/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.py b/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.pyindex f1886b027a..62889637c9 100644--- a/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.py+++ b/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.py@@ -75,6 +75,9 @@ from invokeai.backend.quantization.fp8_scaled import ()from invokeai.backend.quantization.gguf.ggml_tensor import GGMLTensorfrom invokeai.backend.quantization.gguf.loaders import gguf_sd_loader+from invokeai.backend.quantization.int8_convrot import (+ reject_int8_layers_a_plain_fold_cannot_decode,+)from invokeai.backend.quantization.nvfp4 import (NVFP4Payload,install_nvfp4_layers,@@ -1212,6 +1215,12 @@ class MistralEncoderCheckpointLoader(ModelLoader):# device check is always true, so the choice is unconditional and has no user setting behind# it. This loader never calls the layerwise cast (text encoders are excluded there), so the# kept weights reach `CustomLinear` with their scales intact.+ # Before either branch, because both consume what the check reads: `extract_fp8_scaled_layers`+ # pops every scale key -- discarding the ones whose weight is not float8, int8's included --+ # and deletes the markers with them. On CUDA that branch is always the one taken, so a check+ # placed after it would never run on the device almost everyone loads on.+ reject_int8_layers_a_plain_fold_cannot_decode(sd, "This Mistral encoder checkpoint")+keep_fp8 = should_keep_fp8_weights(target_device) or _device_supports_fp8_storage(target_device, logger)fp8_layers: dict[str, Any] = {}if keep_fp8:diff --git a/invokeai/backend/model_manager/load/model_loaders/qwen_image.py b/invokeai/backend/model_manager/load/model_loaders/qwen_image.pyindex 15582307d5..c72b40cf1b 100644--- a/invokeai/backend/model_manager/load/model_loaders/qwen_image.py+++ b/invokeai/backend/model_manager/load/model_loaders/qwen_image.py@@ -46,6 +46,7 @@ from invokeai.backend.quantization.fp8_scaled import ()from invokeai.backend.quantization.gguf.ggml_tensor import GGMLTensorfrom invokeai.backend.quantization.gguf.loaders import gguf_sd_loader+from invokeai.backend.quantization.int8_convrot import reject_int8_layers_a_plain_fold_cannot_decodefrom invokeai.backend.quantization.nvfp4 import install_nvfp4_layers, pop_nvfp4_layers, predict_nvfp4_install_sizefrom invokeai.backend.util.devices import TorchDevicefrom invokeai.backend.util.state_dict_loading import load_state_dict_ignoring_extras, log_unexpected_keys@@ -473,6 +474,11 @@ class QwenVLEncoderCheckpointLoader(ModelLoader):sd, header_layers=parse_quantization_metadata(read_safetensors_metadata(model_path, logger)))+ # Ahead of the config fetch and the reservation below, rather than where the fold reaches it:+ # a load that cannot finish should not go to the network first, nor evict the cache for room+ # it will never use.+ reject_int8_layers_a_plain_fold_cannot_decode(sd, "Qwen2.5-VL encoder checkpoint")+# Fetch the architecture config from HuggingFace (small, ~5KB).# Offline fallback: tries cache first, downloads only if missing.try:@@ -511,7 +517,7 @@ class QwenVLEncoderCheckpointLoader(ModelLoader):# Dequantize ComfyUI-style fp8 weights, then strip the now-unused quantization# metadata (`scale_input` is the activation scale ComfyUI's fp8 matmul kernels# use at runtime — we run the encoder in bf16 after dequantization).- dequantized_count = _dequantize_comfyui_fp8(sd, model_dtype)+ dequantized_count = _dequantize_comfyui_fp8(sd, model_dtype, "Qwen2.5-VL encoder checkpoint")if dequantized_count > 0:logger.info(f"Dequantized {dequantized_count} ComfyUI-quantized weights")_strip_quantization_metadata(sd)diff --git a/invokeai/backend/model_manager/load/model_loaders/wan.py b/invokeai/backend/model_manager/load/model_loaders/wan.pyindex bb9691d301..3d165e77fa 100644--- a/invokeai/backend/model_manager/load/model_loaders/wan.py+++ b/invokeai/backend/model_manager/load/model_loaders/wan.py@@ -508,7 +508,7 @@ class WanCheckpointModel(ModelLoader):sd = _strip_comfyui_prefix(sd)_drop_benign_extra_keys(sd, "Wan checkpoint", logger)- dequantized = _dequantize_comfyui_fp8(sd, model_dtype)+ dequantized = _dequantize_comfyui_fp8(sd, model_dtype, f"Wan checkpoint {model_path.name}")if dequantized > 0:logger.info(f"Dequantized {dequantized} ComfyUI-quantized weights")# Drop the scale tensors themselves — they've been folded into the weightsdiff --git a/invokeai/backend/quantization/int8_convrot.py b/invokeai/backend/quantization/int8_convrot.pyindex 4f9b010be0..5a2649e437 100644--- a/invokeai/backend/quantization/int8_convrot.py+++ b/invokeai/backend/quantization/int8_convrot.py@@ -49,6 +49,7 @@ from invokeai.backend.quantization.fp8_scaled import (INPUT_SCALE_SUFFIXES,WEIGHT_SCALE_SUFFIXES,is_castable_float,+ iter_weight_scale_pairs,)CONVROT_GROUP_SIZE = 256@@ -322,6 +323,66 @@ def extract_int8_convrot_markers(sd: dict[str, Any]) -> dict[str, dict[str, Any]return markers+def reject_int8_layers_a_plain_fold_cannot_decode(sd: Mapping[str, Any], what: str = "This checkpoint") -> None:+ """Refuse an ``int8_tensorwise`` layer to a fold that only multiplies the scale in.++ ``int8_tensorwise`` and ComfyUI's scaled fp8 share a key layout — a ``.weight`` beside a+ ``.weight_scale`` — so a loader with no int8 branch folds one as if it were the other. The scale+ even goes down the right axis, which is what makes this quiet: the result has the weight's+ shape, its dtype and roughly its magnitude. What is missing is the inverse Hadamard rotation+ ``convrot`` applies along the input dim. Measured on a 64x256 layer, the folded weight+ correlates with the one the checkpoint encodes at **0.07**, against 0.9999 for the real decode.++ Only the rotated case is refused. With ``convrot`` off, ``codes * scale`` *is* the whole decode+ — bit-identical to :class:`Int8ConvrotLinear` with ``convrot=False``, checked — so where a fold+ actually runs, such a build folds to the right weight and must keep doing so. (It does not+ follow that it loads: the Mistral encoder keeps fp8 rather than folding on any CUDA device, and+ there an unrotated int8 weight is left untouched and dies later in ``load_state_dict``. That is+ how it behaved before this check and is not what this check is about.) An int8 weight with no+ marker is refused too: nothing says whether it was rotated, and every published build marks+ every one of its int8 weights.++ Read from the *per-tensor* marker only. The safetensors header names formats as well, but it+ cannot carry ``convrot`` or the group size (see ``flux.py``, where the per-layer marker wins for+ that reason), so a header entry is not evidence that a layer is safe to fold — consulting one+ would let a header-named rotated build straight through. Every caller here still has the markers+ in ``sd``: the two folds run before anything pops them, and the Mistral seam checks ahead of+ ``extract_fp8_scaled_layers`` for the same reason.++ Narrower than :func:`reject_unmarked_int8_weights` in two ways, because it runs before a model+ exists: it sees only int8 weights that have a scale beside them, and it cannot skip weights the+ model will discard. A merged file bundling an int8 submodel a non-strict load would drop is+ therefore refused rather than ignored.+ """+ rotated: list[str] = []+ unmarked: list[str] = []+ for weight_key, _scale_key in iter_weight_scale_pairs(sd):+ weight = sd[weight_key]+ if getattr(weight, "dtype", None) is not torch.int8:+ continue+ path = weight_key[: -len(".weight")]+ blob = sd.get(f"{path}{COMFY_QUANT_SUFFIX}")+ marker = parse_comfy_quant_marker(blob) if blob is not None else None+ if not marker or marker.get("format") != INT8_TENSORWISE_FORMAT:+ unmarked.append(path)+ elif marker.get("convrot"):+ rotated.append(path)++ if rotated:+ raise ValueError(+ f"{what} carries {len(rotated)} int8_tensorwise layer(s) quantized with convrot (e.g. "+ f"{', '.join(sorted(rotated)[:3])}), and this loader has no int8 branch. Folding the scale in "+ "without the inverse rotation produces a weight of the right shape that bears no relation to the "+ "one stored. Use the fp8 or bf16 build of this checkpoint."+ )+ if unmarked:+ raise ValueError(+ f"{what} carries {len(unmarked)} int8 weight(s) with no int8_tensorwise marker (e.g. "+ f"{', '.join(sorted(unmarked)[:3])}), so nothing says whether they were rotated. Refusing rather "+ "than guessing: read unrotated, a rotated weight loads cleanly and generates noise."+ )++def check_int8_scale_layout(path: str, weight: torch.Tensor, scale: torch.Tensor) -> None:"""Refuse a scale granularity this decode does not implement.diff --git a/tests/backend/model_manager/load/test_int8_through_the_fp8_fold.py b/tests/backend/model_manager/load/test_int8_through_the_fp8_fold.pynew file mode 100644index 0000000000..b91f0ed133--- /dev/null+++ b/tests/backend/model_manager/load/test_int8_through_the_fp8_fold.py@@ -0,0 +1,124 @@+"""An int8_tensorwise layer reaching a fold that only applies the scale.++The two schemes share a key layout -- a `.weight` beside a per-output-channel `.weight_scale` -- so+a loader with no int8 branch folds one as if it were the other. The scale even goes down the right+axis, so the result has the weight's shape, its dtype and roughly its magnitude. What is missing is+the inverse Hadamard rotation `convrot` applies along the input dim, and without it the weight bears+no relation to the one the checkpoint encodes.++The distinction that decides the guard: with `convrot` *off*, `codes * scale` is the complete+decode, and the fold produces exactly what the int8 path would. Refusing on the int8 dtype alone+would break that build. So the marker is what is read, and the two cases are pinned apart here.+"""++import pytest+import torch++from invokeai.backend.model_manager.load.model_loaders.comfyui_state_dict_utils import _dequantize_comfyui_fp8+from invokeai.backend.quantization.int8_convrot import CONVROT_GROUP_SIZE, Int8ConvrotLinear+from tests.fixtures.quantized_payloads import comfy_quant_marker, quantize_convrot, quantize_scaled_fp8++CPU = torch.device("cpu")+ROTATED = {"format": "int8_tensorwise", "convrot": True, "convrot_groupsize": CONVROT_GROUP_SIZE}+UNROTATED = {"format": "int8_tensorwise", "convrot": False}+++def _int8_layer(marker: dict | None, *, rotate: bool) -> tuple[dict[str, torch.Tensor], torch.Tensor]:+ """One int8 layer, and the weight a correct loader recovers from it."""+ torch.manual_seed(0)+ original = torch.randn(64, CONVROT_GROUP_SIZE)+ if rotate:+ payload = quantize_convrot(original)+ codes, scale = payload.codes, payload.scale+ else:+ scale = original.abs().amax(dim=1, keepdim=True) / 127.0+ codes = torch.clamp(torch.round(original / scale), -128, 127).to(torch.int8)+ scale = scale.float()++ state_dict = {"lin.weight": codes, "lin.weight_scale": scale}+ if marker is not None:+ state_dict["lin.comfy_quant"] = comfy_quant_marker(marker)+ expected = Int8ConvrotLinear(codes, scale, convrot=rotate)._dequantized_weight(CPU, torch.float32)+ return state_dict, expected+++def test_a_rotated_layer_is_refused_rather_than_folded() -> None:+ """Measured on this layer: folded without the derotation it correlates with the stored weight at+ 0.07, against 0.9999 for the real decode -- at the same shape, dtype and magnitude."""+ state_dict, _ = _int8_layer(ROTATED, rotate=True)++ with pytest.raises(ValueError, match="quantized with convrot"):+ _dequantize_comfyui_fp8(state_dict, torch.float32)+++def test_what_the_fold_produces_on_a_rotated_layer_is_not_the_stored_weight() -> None:+ """The measurement the refusal rests on, taken through the fold itself rather than recomputed.++ The payload is rotated but its marker says `convrot: false`, which is the one way to get a+ rotated layer past the guard and see what the fold does with it. A checkpoint cannot lie like+ that by accident -- the point is to hold the number the guard exists for against the real code+ path, so that a fold which silently stopped applying the scale, or started skipping int8, is+ caught here too.+ """+ state_dict, correct = _int8_layer(UNROTATED, rotate=True)++ assert _dequantize_comfyui_fp8(state_dict, torch.float32) == 1+ folded = state_dict["lin.weight"]++ assert folded.shape == correct.shape and folded.dtype is correct.dtype+ similarity = torch.nn.functional.cosine_similarity(folded.flatten(), correct.flatten(), dim=0)+ assert similarity < 0.2, f"the rotation would have to matter for the guard to be worth having ({similarity})"+++def test_an_unrotated_layer_still_folds_bit_identically() -> None:+ """The half that must keep working. `convrot: false` makes `codes * scale` the whole decode, so+ a build like that loads correctly through this fold and a dtype-only guard would break it."""+ state_dict, expected = _int8_layer(UNROTATED, rotate=False)++ assert _dequantize_comfyui_fp8(state_dict, torch.float32) == 1+ assert torch.equal(state_dict["lin.weight"], expected)+++def test_an_int8_weight_with_no_marker_is_refused() -> None:+ """Nothing says whether it was rotated. Read unrotated, a rotated weight loads cleanly and+ generates noise -- and every published int8 build marks every one of its int8 weights, so an+ unmarked one is not a build this can reason about."""+ state_dict, _ = _int8_layer(None, rotate=True)++ with pytest.raises(ValueError, match="no int8_tensorwise marker"):+ _dequantize_comfyui_fp8(state_dict, torch.float32)+++def test_a_scaled_fp8_layer_is_untouched_by_the_check() -> None:+ """The population this fold exists for. The guard keys on the int8 dtype, so an fp8 layer never+ reaches it -- asserted, because a guard that fired here would break every Wan and Qwen-Image+ scaled-fp8 checkpoint."""+ payload = quantize_scaled_fp8(torch.randn(8, 16))+ state_dict = {"lin.weight": payload.codes, "lin.weight_scale": payload.scale}++ assert _dequantize_comfyui_fp8(state_dict, torch.float32) == 1+ assert torch.equal(state_dict["lin.weight"], payload.dequantized)+++def test_the_other_scale_spelling_is_refused_too() -> None:+ """Comfy's Qwen2.5-VL producer writes `.scale_weight`. The weight key is derived from whichever+ suffix matched, so a guard that only recovered the path for one spelling would let the other+ through -- into the fold, unrotated."""+ state_dict, _ = _int8_layer(ROTATED, rotate=True)+ state_dict["lin.scale_weight"] = state_dict.pop("lin.weight_scale")++ with pytest.raises(ValueError, match="quantized with convrot"):+ _dequantize_comfyui_fp8(state_dict, torch.float32)+++def test_a_header_entry_is_not_taken_as_evidence_that_a_layer_is_safe() -> None:+ """The safetensors header names formats too, but it cannot carry `convrot` or the group size --+ which is why `flux.py` gives the per-tensor marker precedence. An earlier version of this guard+ let a header hint override the marker, so a header-named rotated build walked straight through+ into the unrotated fold. The guard reads the marker and nothing else; the header is simulated+ here by the only thing that could stand in for it, a marker of the wrong format.+ """+ state_dict, _ = _int8_layer({"format": "float8_e4m3fn"}, rotate=True)++ with pytest.raises(ValueError, match="no int8_tensorwise marker"):+ _dequantize_comfyui_fp8(state_dict, torch.float32)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 5e673dc6f0..3c257cf1ab 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@@ -11,7 +11,7 @@ from pathlib import Pathimport pytestimport torch-from safetensors.torch import save_file+from safetensors.torch import load_file, save_filefrom invokeai.backend.model_manager.configs.mistral_encoder import MistralEncoder_Checkpoint_Configfrom invokeai.backend.model_manager.load.model_loaders import mistral_encoder@@ -19,7 +19,7 @@ from invokeai.backend.model_manager.load.model_loaders.mistral_encoder import Mifrom invokeai.backend.model_manager.taxonomy import MistralVariantTypefrom invokeai.backend.quantization.nvfp4 import NVFP4Linear, NVFP4Payloadfrom tests.fixtures.loader_seams import Seam, prepare-from tests.fixtures.quantized_payloads import comfy_quant_marker+from tests.fixtures.quantized_payloads import comfy_quant_marker, quantize_convrot# 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@@ -187,6 +187,39 @@ def test_an_nvfp4_mixed_checkpoint_keeps_its_nvfp4_layers_packed_under_either_fpassert abs(run.reserved[0] - expected_bytes) < 1024, (run.reserved, expected_bytes)[email protected]("keep_fp8", [False, True], ids=["fp8_folded", "fp8_kept"])+def test_an_int8_convrot_layer_is_refused_rather_than_folded_unrotated(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, keep_fp8: bool+) -> None:+ """This encoder has no int8 branch, and `int8_tensorwise` shares the fp8 key layout, so the fold+ applied the scale and skipped the inverse rotation -- a weight of the right shape and magnitude+ that bears no relation to the stored one.++ Both branches, because the first version of this guard only covered one. `keep_fp8` is+ unconditionally true on CUDA, and that branch's `extract_fp8_scaled_layers` pops every scale key+ -- discarding the ones whose weight is not float8 -- and deletes the markers with them. A check+ downstream of it is a no-op on the device almost everyone loads on.+ """+ checkpoint, _, _ = _write_checkpoint(tmp_path, evidence="none")+ tensors = load_file(checkpoint)+ target = f"model.layers.0.{FP8_PROJECTION}"+ payload = quantize_convrot(torch.randn(KV_ROWS, HIDDEN), group_size=64)+ tensors[f"{target}.weight"] = payload.codes+ tensors[f"{target}.weight_scale"] = payload.scale+ tensors[f"{target}.comfy_quant"] = comfy_quant_marker(+ {"format": "int8_tensorwise", "convrot": True, "convrot_groupsize": 64}+ )+ save_file(tensors, checkpoint)+ run = prepare(SEAM, monkeypatch, geometry=_fp8_matmul(keep_fp8))++ with pytest.raises(ValueError, match="quantized with convrot"):+ run.load(_config(checkpoint))++ # And before the cache was evicted for a load that cannot finish. The reservation sits fifty+ # lines below the check; a guard placed after it would cost a 16 GiB encoder's worth of room.+ assert run.reserved == []++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")run = prepare(SEAM, monkeypatch, geometry=_fp8_matmul(False), observe=WIDENING)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 1282c8f417..1a33a64bf5 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@@ -13,6 +13,7 @@ from types import SimpleNamespacefrom unittest.mock import MagicMockimport pytest+import safetensors.torchimport torchfrom invokeai.backend.model_manager.configs.main import Main_Checkpoint_QwenImage_Config@@ -26,7 +27,8 @@ 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_tensors+from tests.fixtures.loader_seams import Seam, prepare+from tests.fixtures.quantized_payloads import comfy_quant_marker, nvfp4_signed_tensors, quantize_convrotCOMPUTE_DTYPE = torch.bfloat16@@ -268,3 +270,41 @@ def test_the_encoder_keeps_marker_named_nvfp4_layers_packed_under_their_transforpacked = 2 * _packed_bytes(128, 64)widened = 128 + (32 * 64 + 2) + (4 * 8 + 4)loader._ram_cache.make_room.assert_called_once_with(packed + widened * COMPUTE_DTYPE.itemsize + fp8_marker.numel())+++def test_an_int8_convrot_checkpoint_is_refused_before_the_cache_is_evicted(monkeypatch, tmp_path) -> None:+ """This encoder has no int8 branch, and `int8_tensorwise` shares the fp8 key layout, so the fold+ applied the scale and skipped the inverse rotation.++ The refusal has to come before `make_room`, thirty lines further down, and before the config+ fetch between them: reserving room for a load that cannot finish evicts whatever else the user+ had resident, and the fetch reaches for the network to do it. That+ ordering is the half that went missing once already -- the guard was reported as moved ahead of+ the reservation while the call was not in the tree at all, and nothing here would have noticed.+ """+ payload = quantize_convrot(torch.randn(64, 256), group_size=64)+ state_dict = {+ "model.layers.0.self_attn.q_proj.weight": payload.codes,+ "model.layers.0.self_attn.q_proj.weight_scale": payload.scale,+ "model.layers.0.self_attn.q_proj.comfy_quant": comfy_quant_marker(+ {"format": "int8_tensorwise", "convrot": True, "convrot_groupsize": 64}+ ),+ }+ checkpoint = tmp_path / "qwen_2.5_vl_7b_int8_convrot.safetensors"+ checkpoint.touch()+ seam = Seam(+ loader=QwenVLEncoderCheckpointLoader,+ module=qwen_image,+ entry="_load_text_encoder_from_singlefile",+ # The loader imports `load_file` inside the method, so the name it resolves is the package's.+ load_file_host=safetensors.torch,+ patches_device=True,+ sets_torch_dtype=False,+ casts_fp8_storage=False,+ )+ run = prepare(seam, monkeypatch, state_dict=state_dict, metadata=None)++ with pytest.raises(ValueError, match="quantized with convrot"):+ run.load(QwenVLEncoder_Checkpoint_Config.model_construct(path=str(checkpoint)))++ assert run.reserved == []diff --git a/tests/backend/model_manager/load/test_wan_checkpoint_loader.py b/tests/backend/model_manager/load/test_wan_checkpoint_loader.pyindex 1d97c7d4eb..31211b9136 100644--- a/tests/backend/model_manager/load/test_wan_checkpoint_loader.py+++ b/tests/backend/model_manager/load/test_wan_checkpoint_loader.py@@ -20,6 +20,7 @@ from invokeai.backend.model_manager.load.model_loaders.wan import (_build_wan_transformer_config,)from invokeai.backend.model_manager.taxonomy import SubModelType, WanVariantType+from tests.fixtures.quantized_payloads import comfy_quant_marker, quantize_convrot# A structurally faithful but tiny Wan transformer. attention_head_dim must stay# at 128 — the loader derives num_attention_heads as inner_dim // 128, matching@@ -179,6 +180,30 @@ class TestEndToEnd:assert loaded[target].dtype == torch.bfloat16assert torch.allclose(loaded[target].float(), torch.full_like(loaded[target].float(), 2.0))+ def test_an_int8_convrot_checkpoint_is_refused_rather_than_folded_unrotated(self, tmp_path: Path) -> None:+ """Wan has no int8 branch, and `int8_tensorwise` shares the fp8 key layout, so the fold used+ to apply the scale and skip the inverse rotation. That produces a weight of the right shape,+ dtype and magnitude bearing no relation to the stored one -- a model that loads and+ generates noise. `test_int8_through_the_fp8_fold.py` measures how little relation; how+ little depends on the rotation width, so the number is kept where the geometry is fixed.+ Pinned at the loader as well, because Wan is one of the two that reach the shared fold.+ """+ reference = _tiny_model()+ sd = {k: v.clone() for k, v in reference.state_dict().items()}++ target = "blocks.0.attn1.to_q.weight"+ payload = quantize_convrot(sd[target].float(), group_size=64)+ sd[target] = payload.codes+ sd["blocks.0.attn1.to_q.weight_scale"] = payload.scale+ sd["blocks.0.attn1.to_q.comfy_quant"] = comfy_quant_marker(+ {"format": "int8_tensorwise", "convrot": True, "convrot_groupsize": 64}+ )+ path = tmp_path / "Wan2.2-A14B-HighNoise-int8_convrot.safetensors"+ save_file(sd, path)++ with pytest.raises(ValueError, match="quantized with convrot"):+ _load(path)+def test_scale_bookkeeping_never_reaches_the_model(self, tmp_path: Path) -> None:"""``load_state_dict(strict=False)`` silently ignores unexpected keys, soassert on what the loader actually hands over rather than on the result."""