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(ideogram4): refuse foreign quantization at the diffusers-folder seams
Alexander Eichhorned4d5eb05163
diff --git a/invokeai/backend/ideogram4/quantized_loading.py b/invokeai/backend/ideogram4/quantized_loading.pyindex 326a44e04c..098c930d3c 100644--- a/invokeai/backend/ideogram4/quantized_loading.py+++ b/invokeai/backend/ideogram4/quantized_loading.py@@ -7,6 +7,7 @@ import torchimport torch.nn as nnimport torch.nn.functional as F+from invokeai.backend.quantization.fp8_scaled import WEIGHT_SCALE_SUFFIXESfrom invokeai.backend.util.state_dict_loading import log_unexpected_keysif TYPE_CHECKING:@@ -161,6 +162,34 @@ def quantize_weight_to_fp8(return q, scale.squeeze(1).to(torch.float32)+def reject_scale_spellings_this_path_drops(state_dict: dict[str, torch.Tensor], what: str) -> None:+ """Refuse a weight scale spelled in a way this path reads nothing from.++ Everything here keys on ``FP8_SCALE_SUFFIX`` and only that: :func:`swap_linears_to_fp8` decides+ a layer is quantized by it, and :func:`load_fp8_state_dict` keeps a float32 tensor by it. The+ other spelling ComfyUI writes, ``.scale_weight``, therefore selects nothing -- the layer stays+ an ordinary ``nn.Linear``, the fp8 codes are copied into it *as the weight*, and the scale is+ reported at DEBUG as an unexpected key. The load succeeds and every affected weight is off by+ ``1/weight_scale``, which for a per-row scale of ``amax/448`` is three to four orders of+ magnitude on a typical layer.++ Refusing rather than reading the second spelling, because a file that uses it is a ComfyUI+ scaled-fp8 build and not this path's private layout: supporting those is a different piece of+ work, with its own markers and its own per-layer flags, and this error is what would say it is+ needed. The suffixes come from the shared tuple rather than a literal, though with two spellings+ in it today no test can tell the two apart.+ """+ unread = tuple(suffix for suffix in WEIGHT_SCALE_SUFFIXES if suffix != FP8_SCALE_SUFFIX)+ carried = sorted(key for key in state_dict if key.endswith(unread))+ if carried:+ raise ValueError(+ f"{what} carries {len(carried)} weight scale(s) spelled `{unread[0]}` (e.g. "+ f"{', '.join(carried[:3])}), and this loader reads only `{FP8_SCALE_SUFFIX}`. They would be "+ "dropped and their layers left holding raw fp8 codes -- a model that loads and generates "+ "noise. Use the unquantized build, or an Ideogram 4 build quantized by InvokeAI."+ )++def is_fp8_state_dict(state_dict: dict[str, torch.Tensor]) -> bool:"""True if the checkpoint carries weight-only FP8 Linear weights."""return any(k.endswith(FP8_SCALE_SUFFIX) for k in state_dict) or any(diff --git a/invokeai/backend/model_manager/load/model_loaders/ideogram4.py b/invokeai/backend/model_manager/load/model_loaders/ideogram4.pyindex 2817463dab..2d665935fe 100644--- a/invokeai/backend/model_manager/load/model_loaders/ideogram4.py+++ b/invokeai/backend/model_manager/load/model_loaders/ideogram4.py@@ -45,6 +45,7 @@ from invokeai.backend.quantization.fp8_scaled import (parse_quantization_metadata,predict_cast_state_dict_size,read_safetensors_metadata,+ reject_quantized_side_channel,should_keep_fp8_weights,split_fp8_scaled_layers,warn_on_unattached_scales,@@ -53,6 +54,7 @@ from invokeai.backend.quantization.int8_convrot import (drop_unconsumed_quantization_sidecars,extract_int8_convrot_markers,install_int8_convrot_layers,+ reject_int8_layers_a_plain_fold_cannot_decode,reject_unmarked_int8_weights,)from invokeai.backend.util.devices import TorchDevice@@ -141,6 +143,7 @@ class Ideogram4DiffusersModel(ModelLoader):is_bnb4bit_state_dict,is_fp8_state_dict,load_fp8_state_dict,+ reject_scale_spellings_this_path_drops,swap_linears_to_fp8,)from invokeai.backend.quantization.bnb_nf4 import quantize_model_nf4@@ -149,6 +152,25 @@ class Ideogram4DiffusersModel(ModelLoader):compute_dtype = TorchDevice.choose_bfloat16_safe_dtype(target_device)sd = _load_local_state_dict(folder, "diffusion_pytorch_model")++ # Both refusals ahead of the reservation: `make_room` evicts to make space, so a refusal+ # below it would flush other resident models for a load that cannot finish. Neither can fire+ # on the nf4 build -- its sidecars are `.absmax` and `.quant_state.*`, and its weights are+ # uint8 rather than int8.+ #+ # int8 first, for the reason `Ideogram4CheckpointModel._load_model` gives at its own probe:+ # an int8 layer ships a `.weight_scale` too, and `is_fp8_state_dict` is satisfied by that+ # suffix alone. Taken for this path's private fp8, a rotated weight gets the scale and never+ # the inverse rotation -- `Fp8Linear.forward` is `weight * weight_scale.unsqueeze(1)`, a fold+ # deferred to forward.+ #+ # What the guard lets through is an *unrotated* marked int8 build, where the scale is the+ # whole decode. Not free even so: `Fp8Linear` stores in e4m3, so the codes are requantized on+ # the way in (1.9% mean weight error, measured). No such build is published for this layout;+ # if one appears, that requantization is the thing to fix, not this refusal.+ reject_int8_layers_a_plain_fold_cannot_decode(sd, f"Ideogram 4 transformer {folder.name}")+ reject_scale_spellings_this_path_drops(sd, f"Ideogram 4 transformer {folder.name}")+self._ram_cache.make_room(sum(t.nelement() * t.element_size() for t in sd.values()))if is_bnb4bit_state_dict(sd):@@ -183,6 +205,7 @@ class Ideogram4DiffusersModel(ModelLoader):from invokeai.backend.ideogram4.quantized_loading import (FP8_TEXT_ENCODER_CONFIG_FLAG,load_fp8_state_dict,+ reject_scale_spellings_this_path_drops,swap_linears_to_fp8,)from invokeai.backend.quantization.bnb_nf4 import quantize_model_nf4@@ -203,9 +226,24 @@ class Ideogram4DiffusersModel(ModelLoader):cfg.quantization_config = Nonesd = _load_local_state_dict(encoder_path, "model")++ # Ahead of the reservation, which evicts other resident models to make space: a refusal below+ # it would flush the cache for a load that cannot finish.+ keeps_fp8 = bool(raw_cfg.get(FP8_TEXT_ENCODER_CONFIG_FLAG, False))+ if keeps_fp8:+ # The fp8 branch reads one spelling of the scale and would drop the other silently.+ reject_scale_spellings_this_path_drops(sd, f"Ideogram 4 text encoder {encoder_path.name}")+ else:+ # Everything without the flag goes to `load_state_dict(assign=True, strict=False)` below,+ # which would make the fp8 codes the parameters themselves and report the orphaned scale+ # at DEBUG. InvokeAI is the only producer that writes the flag, so a third-party fp8+ # repack of this encoder arrives here rather than in the branch above. The nf4 build is+ # unaffected: its sidecars are `.absmax` and `.quant_state.*`, which name no scale.+ reject_quantized_side_channel(sd, f"Ideogram 4 text encoder {encoder_path.name}")+self._ram_cache.make_room(sum(t.nelement() * t.element_size() for t in sd.values()))- if raw_cfg.get(FP8_TEXT_ENCODER_CONFIG_FLAG, False):+ if keeps_fp8:# Weight-only fp8 (e4m3): build the empty architecture, swap the quantized Linears for# Fp8Linear (gated on a saved per-row scale), then load. Mirrors the transformer fp8 branch;# runs on any device. strict=False tolerates the tied embed weights transformers resolves@@ -248,6 +286,11 @@ class Ideogram4DiffusersModel(ModelLoader):model_dtype = TorchDevice.choose_bfloat16_safe_dtype(target_device)sd = load_file(model_path / "vae" / "diffusion_pytorch_model.safetensors")+ # No quantized layout reaches this decoder, and the load below drops what it does not+ # recognise: `load_state_dict_ignoring_extras` reports extras and copies on, so an fp8 conv+ # weight would be cast into a float32 parameter with its scale discarded. On the file's own+ # key names rather than the converted ones, so a rename cannot carry a scale out of sight.+ reject_quantized_side_channel(sd, f"Ideogram 4 VAE {model_path.name}")sd = convert_diffusers_state_dict(sd)ae = AutoEncoder(AutoEncoderParams())load_state_dict_ignoring_extras(ae, sd, source="Ideogram 4 VAE")diff --git a/tests/backend/model_manager/load/test_ideogram4_diffusers_loader.py b/tests/backend/model_manager/load/test_ideogram4_diffusers_loader.pynew file mode 100644index 0000000000..a7116d2ad2--- /dev/null+++ b/tests/backend/model_manager/load/test_ideogram4_diffusers_loader.py@@ -0,0 +1,334 @@+"""Loader-level tests for the diffusers-folder Ideogram 4 path.++Ideogram 4 has two loaders. The single-file one (`Ideogram4CheckpointModel._load_model`)+rules int8 out before it probes for scales, and says why in a comment there: an int8 layer ships a+`.weight_scale` too, so probing for scales without ruling int8 out "would take the whole checkpoint+down the fp8 path -- scaled, but never un-rotated, which loads cleanly and generates noise."++The folder loader had no such branch, and three of its seams took a foreign payload quietly.++**The transformer.** Its probe is `is_fp8_state_dict`, satisfied by any key ending `.weight_scale`+whatever the weight's dtype, and what it selects is Ideogram's own weight-only fp8: an `Fp8Linear`+whose forward is `weight.to(dtype) * weight_scale.unsqueeze(1)` -- a fold, deferred to forward.+Driven with a rotated `int8_tensorwise` payload, the layer it produced correlated with the weight+the file encodes at **0.067** on this file's geometry. The same seam also dropped the *other*+spelling of the scale: `swap_linears_to_fp8` gates on `.weight_scale` alone, so a `.scale_weight`+file installs no `Fp8Linear` at all and the raw fp8 codes are copied into an ordinary `nn.Linear`.++**The text encoder.** Its fp8 branch is gated on `ideogram_fp8_weight_only`, a flag InvokeAI writes+into `config.json` and no one else does, so any third-party fp8 repack falls through to+`load_state_dict(strict=False, assign=True)` -- where the codes *become* the parameters, off by+`1/weight_scale`, measured at 6803x for the payload below, with the scale reported at DEBUG. That+branch is one of nine call sites of `reject_quantized_side_channel`; the seven single-file ones live+in `test_side_channel_blind_loaders.py`, which owns that guard's story.++**The VAE.** `load_state_dict_ignoring_extras` reports what it does not recognise and copies on, so+an fp8 conv weight was cast into a float32 parameter with its scale discarded -- the same shape as+the encoder's, at the four sibling VAE seams that have refused it since the seven side-channel-blind+loaders were found.++Two schemes that share the same key layout are deliberately *not* guarded here, because at these+seams they cannot pass quietly -- measured, not assumed:++- **nvfp4** packs two codes per byte, so its weight is half the width `Fp8Linear` allocates.+- **MXFP8** carries a two-dimensional E8M0 grid against a one-dimensional `weight_scale` buffer.++Both are refused by the shape check inside `load_state_dict`. An `int8_tensorwise` scale is the one+that fits: `check_int8_scale_layout` allows `[out]` as well as `[out, 1]`, and `[out]` is exactly+what that buffer expects. The `[out, 1]` spelling trips the same shape check, which is why the cell+below uses the flat one -- the other spelling would pass for the wrong reason.+"""++import json+from pathlib import Path++import pytest+import torch+from safetensors.torch import save_file++from invokeai.backend.ideogram4.modeling_ideogram4 import Ideogram4Config, Ideogram4Transformer+from invokeai.backend.ideogram4.quantized_loading import (+ FP8_TEXT_ENCODER_CONFIG_FLAG,+ Fp8Linear,+ quantize_weight_to_fp8,+)+from invokeai.backend.model_manager.load.model_loaders import ideogram4+from invokeai.backend.model_manager.load.model_loaders.ideogram4 import Ideogram4DiffusersModel+from invokeai.backend.quantization.int8_convrot import CONVROT_GROUP_SIZE+from tests.fixtures.loader_seams import Seam, prepare+from tests.fixtures.quantized_payloads import comfy_quant_marker, quantize_convrot, quantize_scaled_fp8++QUANTIZED = "layers.0.feed_forward.w1"++TRANSFORMER_SEAM = Seam(+ loader=Ideogram4DiffusersModel,+ module=ideogram4,+ entry="_load_one_transformer",+ patches_device=True,+ sets_torch_dtype=False,+ casts_fp8_storage=False,+)++ENCODER_SEAM = Seam(+ loader=Ideogram4DiffusersModel,+ module=ideogram4,+ entry="_load_text_encoder",+ patches_device=True,+ sets_torch_dtype=False,+ casts_fp8_storage=False,+)+++def _tiny_config() -> Ideogram4Config:+ """convrot rotates in groups along the input dim, so every Linear has to be a whole number of+ groups wide. Same module tree as the released geometry, 29 tensors instead of 458. A fresh+ instance per call: the dataclass is not frozen and it is handed to a real model."""+ return Ideogram4Config(+ emb_dim=CONVROT_GROUP_SIZE,+ num_layers=1,+ num_heads=2,+ intermediate_size=CONVROT_GROUP_SIZE,+ adanln_dim=CONVROT_GROUP_SIZE,+ in_channels=8,+ llm_features_dim=32,+ mrope_section=(16, 8, 8),+ )+++def _shrink_the_geometry(monkeypatch: pytest.MonkeyPatch) -> None:+ """`_load_one_transformer` builds `Ideogram4Config()` with no way in; the released defaults are a+ 34-layer, 4608-wide model. Patched at the module the loader imports it from."""+ monkeypatch.setattr("invokeai.backend.ideogram4.modeling_ideogram4.Ideogram4Config", _tiny_config)+++def _tiny_transformer_state_dict() -> dict[str, torch.Tensor]:+ torch.manual_seed(0)+ reference = Ideogram4Transformer(_tiny_config())+ return {key: value.clone().to(torch.float32) for key, value in reference.state_dict().items()}+++def test_an_int8_checkpoint_is_refused_rather_than_taken_for_the_private_fp8_layout(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ """A rotated int8 weight with a flat per-output-channel scale fits `Fp8Linear` exactly: right+ weight shape, right scale shape, and a forward that applies the scale and stops there. It+ loaded, and the layer bore no relation to the stored one.+ """+ state_dict = _tiny_transformer_state_dict()+ payload = quantize_convrot(state_dict[f"{QUANTIZED}.weight"], group_size=CONVROT_GROUP_SIZE)+ state_dict[f"{QUANTIZED}.weight"] = payload.codes+ state_dict[f"{QUANTIZED}.weight_scale"] = payload.scale.squeeze(1)+ state_dict[f"{QUANTIZED}.comfy_quant"] = comfy_quant_marker(+ {"format": "int8_tensorwise", "convrot": True, "convrot_groupsize": CONVROT_GROUP_SIZE}+ )++ run = prepare(TRANSFORMER_SEAM, monkeypatch, state_dict=state_dict, geometry=_shrink_the_geometry)++ with pytest.raises(ValueError, match="quantized with convrot"):+ run.load(tmp_path)++ # `make_room` evicts other resident models to reserve space. Refusing below it would flush the+ # cache for a load that cannot finish.+ assert run.reserved == []+++def test_the_other_spelling_of_the_fp8_scale_is_refused_rather_than_dropped(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ """`.scale_weight` is the spelling ComfyUI writes, and `swap_linears_to_fp8` does not read it.+ The layer then stays an ordinary `nn.Linear`, the fp8 codes are copied in as the weight, and the+ scale is reported at DEBUG -- an effective weight off by `1/weight_scale`, measured at 7195x+ here. The int8 guard above cannot catch it, because the dtype really is fp8.+ """+ state_dict = _tiny_transformer_state_dict()+ codes, scale = quantize_weight_to_fp8(state_dict[f"{QUANTIZED}.weight"])+ state_dict[f"{QUANTIZED}.weight"] = codes+ state_dict[f"{QUANTIZED}.scale_weight"] = scale++ run = prepare(TRANSFORMER_SEAM, monkeypatch, state_dict=state_dict, geometry=_shrink_the_geometry)++ with pytest.raises(ValueError, match=r"Ideogram 4 transformer .*reads only `\.weight_scale`"):+ run.load(tmp_path)+ assert run.reserved == []+++def test_an_fp8_folder_build_still_loads(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:+ """The half that keeps the refusals honest: this loader's own weight-only fp8 layout goes+ through untouched, and the quantized layer arrives as an `Fp8Linear` holding its codes.+ """+ state_dict = _tiny_transformer_state_dict()+ codes, scale = quantize_weight_to_fp8(state_dict[f"{QUANTIZED}.weight"])+ state_dict[f"{QUANTIZED}.weight"] = codes+ state_dict[f"{QUANTIZED}.weight_scale"] = scale++ run = prepare(TRANSFORMER_SEAM, monkeypatch, state_dict=state_dict, geometry=_shrink_the_geometry)+ model = run.load(tmp_path)++ quantized = model.get_submodule(QUANTIZED)+ assert isinstance(quantized, Fp8Linear)+ # The codes themselves, not the dtype: `Fp8Linear.__init__` registers an empty float8 buffer, so+ # asserting the dtype alone passes on a loader that installs the layers and never fills them.+ assert torch.equal(quantized.weight.view(torch.int8), codes.view(torch.int8))+ assert torch.equal(quantized.weight_scale, scale)+++#: Small enough to build eagerly. `AutoModel` gives a bare Qwen3 encoder -- the architecture family+#: the released Ideogram 4 text encoder belongs to -- so the dense cell loads a real model rather+#: than asserting against a shape the loader never reaches.+TINY_ENCODER_CONFIG = {+ "model_type": "qwen3",+ "hidden_size": 32,+ "intermediate_size": 64,+ "num_hidden_layers": 1,+ "num_attention_heads": 2,+ "num_key_value_heads": 1,+ "head_dim": 16,+ "vocab_size": 64,+ "max_position_embeddings": 32,+ "tie_word_embeddings": False,+}++ENCODER_LAYER = "layers.0.mlp.gate_proj"+++def _encoder_folder(+ tmp_path: Path, state_dict: dict[str, torch.Tensor], *, fp8_flag: bool = False, nf4: bool = False+) -> Path:+ """An Ideogram 4 model root with a `text_encoder/` component, as the loader expects one."""+ encoder = tmp_path / "text_encoder"+ encoder.mkdir(parents=True, exist_ok=True)+ config = dict(TINY_ENCODER_CONFIG)+ if fp8_flag:+ config[FP8_TEXT_ENCODER_CONFIG_FLAG] = True+ if nf4:+ config["quantization_config"] = {"quant_method": "bitsandbytes_4bit", "load_in_4bit": True}+ (encoder / "config.json").write_text(json.dumps(config), encoding="utf-8")+ save_file(state_dict, encoder / "model.safetensors")+ return tmp_path+++def _tiny_encoder_state_dict() -> dict[str, torch.Tensor]:+ from transformers import AutoConfig, AutoModel++ torch.manual_seed(0)+ config = AutoConfig.for_model(**TINY_ENCODER_CONFIG)+ return {key: value.clone() for key, value in AutoModel.from_config(config).state_dict().items()}+++def test_a_quantized_text_encoder_without_the_flag_is_refused(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:+ """Without the private flag this branch assigns straight into the built model, so the fp8 codes+ *become* the parameters -- off by `1/weight_scale`, 6803x for this payload -- and the orphaned+ scale is reported at DEBUG. int8 happens to raise here instead, because an int8 tensor cannot be+ a `Parameter` at all; fp8 can, which is why this is the payload that matters.+ """+ state_dict = _tiny_encoder_state_dict()+ payload = quantize_scaled_fp8(state_dict[f"{ENCODER_LAYER}.weight"].float())+ state_dict[f"{ENCODER_LAYER}.weight"] = payload.codes+ state_dict[f"{ENCODER_LAYER}.weight_scale"] = payload.scale+ root = _encoder_folder(tmp_path, state_dict)++ run = prepare(ENCODER_SEAM, monkeypatch)++ with pytest.raises(ValueError, match="quantization side channel"):+ run.load(root)+ assert run.reserved == []+++def test_the_other_spelling_is_refused_in_the_flagged_branch_too(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ """With the flag set, the side-channel guard steps aside for the layout this branch does read --+ and `.scale_weight` is not it. Without this the flag would turn a quiet drop back on.+ """+ state_dict = _tiny_encoder_state_dict()+ codes, scale = quantize_weight_to_fp8(state_dict[f"{ENCODER_LAYER}.weight"].float())+ state_dict[f"{ENCODER_LAYER}.weight"] = codes+ state_dict[f"{ENCODER_LAYER}.scale_weight"] = scale+ root = _encoder_folder(tmp_path, state_dict, fp8_flag=True)++ run = prepare(ENCODER_SEAM, monkeypatch)++ with pytest.raises(ValueError, match=r"Ideogram 4 text encoder .*reads only `\.weight_scale`"):+ run.load(root)+ assert run.reserved == []+++def test_a_dense_text_encoder_still_loads(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:+ """The other half, and the only end-to-end coverage this branch has: an ordinary encoder is+ built, filled, and passes the meta-device check."""+ root = _encoder_folder(tmp_path, _tiny_encoder_state_dict())++ run = prepare(ENCODER_SEAM, monkeypatch)+ model = run.load(root)++ assert not model.training+ assert not any(tensor.is_meta for tensor in model.state_dict().values())+++def test_an_nf4_text_encoder_gets_past_the_guards(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:+ """bitsandbytes sidecars are `.absmax`, `.quant_map` and `.quant_state.bitsandbytes__*`, none of+ which names a scale -- so the published nf4 encoder must reach its own branch untouched. The+ `quantization_config` is what selects that branch, and with it the loader really does build+ `InvokeLinearNF4` layers before loading; the load then fails on this fixture's shapes, which is+ not the point. What must not happen is that it fails *here*: widening `is_scale_metadata_key` to+ any bnb spelling would refuse a build that ships today, and nothing else in the tree would+ notice.+ """+ state_dict = _tiny_encoder_state_dict()+ weight = state_dict.pop(f"{ENCODER_LAYER}.weight")+ state_dict[f"{ENCODER_LAYER}.weight"] = torch.zeros(weight.numel() // 2, 1, dtype=torch.uint8)+ state_dict[f"{ENCODER_LAYER}.weight.absmax"] = torch.zeros(4, dtype=torch.float32)+ state_dict[f"{ENCODER_LAYER}.weight.quant_map"] = torch.zeros(16, dtype=torch.float32)+ state_dict[f"{ENCODER_LAYER}.weight.quant_state.bitsandbytes__nf4"] = torch.zeros(1, dtype=torch.uint8)+ root = _encoder_folder(tmp_path, state_dict, nf4=True)++ run = prepare(ENCODER_SEAM, monkeypatch)++ try:+ run.load(root)+ except Exception as exc: # noqa: BLE001 - the point is *which* failure, not whether one happens+ assert "quantization side channel" not in str(exc), f"the guard fired on an nf4 encoder: {exc}"+ assert "reads only" not in str(exc), f"the spelling guard fired on an nf4 encoder: {exc}"+++VAE_SEAM = Seam(+ loader=Ideogram4DiffusersModel,+ module=ideogram4,+ entry="_load_vae",+ patches_device=True,+ sets_torch_dtype=False,+ casts_fp8_storage=False,+)+++def test_a_quantized_vae_is_refused(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:+ """No quantized layout reaches this decoder, and nothing here looked for one.++ The payload carries the standalone `scaled_fp8` marker as well as the per-layer scale, and that+ is what pins the guard's *placement*: `convert_diffusers_state_dict` refuses a key it cannot+ rewrite, so a guard below the conversion would be pre-empted by a `KeyError` naming the marker+ instead of the scheme. The per-layer scale alone would pass either way -- the rewriter leaves it+ untouched -- so it cannot tell the two placements apart.+ """+ payload = quantize_scaled_fp8(torch.randn(4, 4))+ state_dict = {+ "encoder.conv_out.weight": payload.codes,+ "encoder.conv_out.weight_scale": payload.scale,+ "scaled_fp8": torch.ones(1),+ }++ run = prepare(VAE_SEAM, monkeypatch, state_dict=state_dict)++ with pytest.raises(ValueError, match="quantization side channel"):+ run.load(tmp_path)+++def test_a_dense_vae_gets_past_the_guard(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:+ """The other half. This dict is far too small to fill a decoder, so the load fails either way --+ what must not happen is that it fails *here*."""+ run = prepare(VAE_SEAM, monkeypatch, state_dict={"encoder.conv_out.weight": torch.ones(4, 4)})++ try:+ run.load(tmp_path)+ except Exception as exc: # noqa: BLE001 - the point is *which* failure, not whether one happens+ assert "quantization side channel" not in str(exc), f"the guard fired on a dense VAE: {exc}"diff --git a/tests/backend/model_manager/load/test_side_channel_blind_loaders.py b/tests/backend/model_manager/load/test_side_channel_blind_loaders.pyindex b73f5b300e..272c7870ae 100644--- a/tests/backend/model_manager/load/test_side_channel_blind_loaders.py+++ b/tests/backend/model_manager/load/test_side_channel_blind_loaders.py@@ -1,7 +1,7 @@"""Loaders that handle no quantization side channel refuse one rather than dropping it.-Seven call sites across five loader classes read a state dict and hand it to a model without ever-looking for a `weight_scale`. At the five that load non-strictly a quantized checkpoint does not+Nine call sites across six loader classes read a state dict and hand it to a model without ever+looking for a `weight_scale`. At the seven that load non-strictly a quantized checkpoint does notfail -- it *loads*, with the scale dropped as an unexpected key. Most cast every tensor to thecompute dtype, turning the fp8 codes into ordinary floats off by `1/weight_scale`; the Z-ImageControlNet assigns them with no cast at all and reports the orphan only at DEBUG.@@ -17,6 +17,11 @@ The guard is key-only, so that draft still passed.Each cell is paired with a dense one. Two of these loaders have no other test in the tree, sowithout that half nothing would notice `is_scale_metadata_key` being widened until it startedrefusing ordinary checkpoints -- and it has been widened before, twice.++Two of the nine are not in the table below: Ideogram 4's text encoder and VAE read a diffusers+*folder* rather than a single file, and the encoder is the one seam here that does support a+quantized layout -- Ideogram's own weight-only fp8, behind a private flag in `config.json`. Both are+covered in `test_ideogram4_diffusers_loader.py`, which owns that loader."""from pathlib import Path