Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

fix(loaders): refuse a quantized checkpoint where no loader handles its scales

Alexander Eichhorn96a1cd0ea4c1
diff --git a/invokeai/backend/model_manager/load/model_loaders/anima.py b/invokeai/backend/model_manager/load/model_loaders/anima.py
index 6831065643..c2a7ef65ce 100644
--- a/invokeai/backend/model_manager/load/model_loaders/anima.py
+++ b/invokeai/backend/model_manager/load/model_loaders/anima.py
@@ -29,6 +29,7 @@ from invokeai.backend.quantization.fp8_scaled import (
parse_quantization_metadata,
predict_cast_state_dict_size,
read_safetensors_metadata,
+ reject_quantized_side_channel,
split_fp8_scaled_layers,
strip_layer_path_prefix,
warn_on_unattached_scales,
@@ -286,6 +287,7 @@ class AnimaControlNetLLLiteModel(ModelLoader):
model_path = Path(config.path)
sd = load_file(model_path)
+ reject_quantized_side_channel(sd, f"Anima ControlNet checkpoint {model_path.name}")
with safe_open(model_path, framework="pt", device="cpu") as f:
metadata = f.metadata()
diff --git a/invokeai/backend/model_manager/load/model_loaders/ernie_image.py b/invokeai/backend/model_manager/load/model_loaders/ernie_image.py
index 91a9c55ae7..99920dccc7 100644
--- a/invokeai/backend/model_manager/load/model_loaders/ernie_image.py
+++ b/invokeai/backend/model_manager/load/model_loaders/ernie_image.py
@@ -20,6 +20,7 @@ from invokeai.backend.model_manager.taxonomy import (
ModelType,
SubModelType,
)
+from invokeai.backend.quantization.fp8_scaled import reject_quantized_side_channel
from invokeai.backend.util.devices import TorchDevice
# The geometry of the released ERNIE-Image transformer, from the pipeline's `transformer/config.json`.
@@ -113,6 +114,7 @@ class ErnieImageCheckpointModel(ModelLoader):
model_dtype = TorchDevice.choose_bfloat16_safe_dtype(target_device)
sd = safetensors.torch.load_file(Path(config.path))
+ reject_quantized_side_channel(sd, f"ERNIE-Image checkpoint {Path(config.path).name}")
self._ram_cache.make_room(sum(t.nelement() * model_dtype.itemsize for t in sd.values()))
for key in sd:
sd[key] = sd[key].to(model_dtype)
diff --git a/invokeai/backend/model_manager/load/model_loaders/flux.py b/invokeai/backend/model_manager/load/model_loaders/flux.py
index 51032e0add..5ecf42aa83 100644
--- a/invokeai/backend/model_manager/load/model_loaders/flux.py
+++ b/invokeai/backend/model_manager/load/model_loaders/flux.py
@@ -100,6 +100,7 @@ from invokeai.backend.quantization.fp8_scaled import (
parse_quantization_metadata,
predict_cast_state_dict_size,
read_safetensors_metadata,
+ reject_quantized_side_channel,
split_fp8_scaled_layers,
strip_layer_path_prefix,
warn_on_unattached_scales,
@@ -214,6 +215,7 @@ class Flux2VAELoader(ModelLoader):
# Load state dict manually since from_single_file may not support AutoencoderKLFlux2 yet
sd = load_file(model_path)
+ reject_quantized_side_channel(sd, f"FLUX.2 VAE checkpoint {model_path.name}")
# Convert BFL format to diffusers format if needed
# BFL format uses: encoder.down., decoder.up., decoder.mid.block_1, decoder.mid.attn_1, decoder.norm_out
diff --git a/invokeai/backend/model_manager/load/model_loaders/vae.py b/invokeai/backend/model_manager/load/model_loaders/vae.py
index 75a6546170..54d26d467e 100644
--- a/invokeai/backend/model_manager/load/model_loaders/vae.py
+++ b/invokeai/backend/model_manager/load/model_loaders/vae.py
@@ -25,6 +25,7 @@ from invokeai.backend.model_manager.taxonomy import (
ModelType,
SubModelType,
)
+from invokeai.backend.quantization.fp8_scaled import reject_quantized_side_channel
from invokeai.backend.quantization.sdnq.detection import is_sdnq_folder
from invokeai.backend.quantization.sdnq.loaders import raise_on_incomplete_sdnq_load, sdnq_sd_loader
from invokeai.backend.util.state_dict_loading import load_state_dict_ignoring_extras
@@ -288,6 +289,7 @@ class VAELoader(GenericDiffusersLoader):
patch_wan_causal_conv3d_for_rocm()
dtype = _wan_family_dtype(self._torch_dtype)
sd = _read_checkpoint(config.path)
+ reject_quantized_side_channel(sd, f"Wan VAE checkpoint {Path(config.path).name}")
for k in list(sd.keys()):
if sd[k].is_floating_point():
@@ -355,7 +357,9 @@ class VAELoader(GenericDiffusersLoader):
patch_wan_causal_conv3d_for_rocm()
dtype = _wan_family_dtype(self._torch_dtype)
- sd = convert_wan_vae_to_diffusers(_read_checkpoint(path))
+ sd = _read_checkpoint(path)
+ reject_quantized_side_channel(sd, f"Wan VAE checkpoint {Path(path).name}")
+ sd = convert_wan_vae_to_diffusers(sd)
for k in list(sd.keys()):
if sd[k].is_floating_point():
sd[k] = sd[k].to(dtype)
@@ -407,6 +411,7 @@ class VAELoader(GenericDiffusersLoader):
)
sd = _read_checkpoint(config.path)
+ reject_quantized_side_channel(sd, f"Qwen-Image VAE checkpoint {Path(config.path).name}")
# The same autoencoder as the Wan-family layout above, so the same precision policy.
dtype = _wan_family_dtype(self._torch_dtype)
diff --git a/invokeai/backend/model_manager/load/model_loaders/z_image.py b/invokeai/backend/model_manager/load/model_loaders/z_image.py
index 37fc2fd27e..5a93c37ef7 100644
--- a/invokeai/backend/model_manager/load/model_loaders/z_image.py
+++ b/invokeai/backend/model_manager/load/model_loaders/z_image.py
@@ -52,6 +52,7 @@ from invokeai.backend.quantization.fp8_scaled import (
parse_quantization_metadata,
predict_cast_state_dict_size,
read_safetensors_metadata,
+ reject_quantized_side_channel,
split_fp8_scaled_layers,
split_qkv_sidechannel,
strip_layer_path_prefix,
@@ -1068,6 +1069,8 @@ class ZImageControlCheckpointModel(ModelLoader):
# Load the safetensors state dict
sd = load_file(model_path)
+ # Before the geometry probe, because the shapes it reads are meaningless on a packed weight.
+ reject_quantized_side_channel(sd, f"Z-Image ControlNet checkpoint {model_path.name}")
# Determine number of control blocks from state dict
# Control blocks are named control_layers.0, control_layers.1, etc.
diff --git a/invokeai/backend/quantization/fp8_scaled.py b/invokeai/backend/quantization/fp8_scaled.py
index 6d38ba2242..6542ead5b6 100644
--- a/invokeai/backend/quantization/fp8_scaled.py
+++ b/invokeai/backend/quantization/fp8_scaled.py
@@ -313,6 +313,43 @@ def is_scale_metadata_key(key: Any) -> bool:
)
+def reject_quantized_side_channel(sd: Mapping[str, Any], what: str) -> None:
+ """Refuse a checkpoint carrying a quantization side channel to a loader that handles none.
+
+ Several loaders read a state dict and hand it straight to the model. Where they load
+ non-strictly — the VAEs and the Z-Image ControlNet — a quantized file does not fail: it *loads*,
+ with the ``weight_scale`` dropped as an unexpected key. The worst shape builds its module under
+ ``init_empty_weights`` and calls ``load_state_dict(assign=True, strict=False)``, so the fp8
+ codes become the parameters with no cast to widen them; every weight is then off by
+ ``1/weight_scale`` — orders of magnitude — and the only trace is a DEBUG line.
+
+ Two callers load strictly (ERNIE-Image, the Anima LLLite adapter) and so already raise on the
+ orphaned key. There this buys a message that names the cause instead of a list of unexpected
+ tensors, and for ERNIE it refuses before a multi-gigabyte state dict has been reserved for and
+ cast.
+
+ Refusing is the honest outcome while no such build exists: the alternative is not "it works
+ slightly worse", it is a model that generates noise with nothing to point at. Supporting a
+ scheme here is a separate piece of work, and this error is what would announce that it is needed.
+
+ Scoped to the *side channel*. A raw fp8 checkpoint with no scale is out of scope because it
+ cannot fail quietly: a loader that casts handles e4m3 exactly, and one that does not — the
+ Z-Image ControlNet casts nowhere — installs fp8 parameters that raise at the first ``F.linear``
+ on the dtype mismatch against the activations ("expected m1 and m2 to have the same dtype").
+ """
+ carried = sorted(key for key in sd if is_scale_metadata_key(key))
+ if carried:
+ # Keyed on the side channel rather than on the weights' dtype, so the wording says what was
+ # actually seen: a dense weight beside a stray scale key trips this too, and telling a user
+ # their checkpoint "is quantized" when it merely carries the key would send them looking for
+ # a build that does not exist.
+ raise ValueError(
+ f"{what} carries a quantization side channel ({len(carried)} key(s), e.g. "
+ f"{', '.join(carried[:3])}) and this loader does not support quantized checkpoints: its weights "
+ "would be loaded without their scales applied. Use an unquantized build of this model."
+ )
+
+
def _strip_scale_suffix(key: str) -> tuple[str, bool] | None:
"""Return ``(module path, is_input_scale)``, or None if ``key`` is not a scale key."""
for suffix in WEIGHT_SCALE_SUFFIXES:
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.py
new file mode 100644
index 0000000000..b73f5b300e
--- /dev/null
+++ b/tests/backend/model_manager/load/test_side_channel_blind_loaders.py
@@ -0,0 +1,163 @@
+"""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
+fail -- it *loads*, with the scale dropped as an unexpected key. Most cast every tensor to the
+compute dtype, turning the fp8 codes into ordinary floats off by `1/weight_scale`; the Z-Image
+ControlNet assigns them with no cast at all and reports the orphan only at DEBUG.
+
+The other two (ERNIE-Image and the Anima LLLite adapter) load strictly and already raise on the
+orphaned key, so there the guard buys a message that names the cause rather than a list of
+unexpected tensors -- and, for ERNIE, refuses before the cache has been asked for room.
+
+Each refusal cell writes a real checkpoint carrying a real fp8 layer -- asserted, because an earlier
+draft of this file overwrote its own codes with a dense tensor and tested nothing about fp8 at all.
+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, so
+without that half nothing would notice `is_scale_metadata_key` being widened until it started
+refusing ordinary checkpoints -- and it has been widened before, twice.
+"""
+
+from pathlib import Path
+
+import pytest
+import torch
+from safetensors.torch import save_file
+
+from invokeai.backend.model_manager.configs.controlnet import ControlNet_Checkpoint_Anima_Config
+from invokeai.backend.model_manager.configs.main import Main_Checkpoint_ErnieImage_Config
+from invokeai.backend.model_manager.configs.vae import (
+ VAE_Checkpoint_Flux2_Config,
+ VAE_Checkpoint_QwenImage_Config,
+ VAE_Checkpoint_Wan_Config,
+)
+from invokeai.backend.model_manager.load.model_loaders import anima, ernie_image, flux, vae
+from invokeai.backend.model_manager.load.model_loaders.anima import AnimaControlNetLLLiteModel
+from invokeai.backend.model_manager.load.model_loaders.ernie_image import ErnieImageCheckpointModel
+from invokeai.backend.model_manager.load.model_loaders.flux import Flux2VAELoader
+from invokeai.backend.model_manager.load.model_loaders.vae import VAELoader
+from tests.fixtures.loader_seams import Seam, prepare
+from tests.fixtures.quantized_payloads import quantize_scaled_fp8
+
+#: The layout marker `_load_qwen_image_vae` probes for *before* it reads the file. It is supplied in
+#: every checkpoint here so the probe is never what refuses -- the guard has to be.
+QWEN_IMAGE_LAYOUT_MARKER = "decoder.conv_in.weight"
+
+#: Deliberately not the layout marker: an earlier draft used one key for both and the marker
+#: silently replaced the fp8 codes.
+QUANTIZED_LAYER = "encoder.conv_out"
+
+
+def _dense() -> dict[str, torch.Tensor]:
+ return {QWEN_IMAGE_LAYOUT_MARKER: torch.ones(4, 4), f"{QUANTIZED_LAYER}.weight": torch.ones(4, 4)}
+
+
+def _quantized() -> dict[str, torch.Tensor]:
+ payload = quantize_scaled_fp8(torch.randn(4, 4))
+ state_dict = _dense()
+ state_dict[f"{QUANTIZED_LAYER}.weight"] = payload.codes
+ state_dict[f"{QUANTIZED_LAYER}.weight_scale"] = payload.scale
+ return state_dict
+
+
+def _written(tmp_path: Path, state_dict: dict[str, torch.Tensor], name: str) -> Path:
+ """A real file, because two of these loaders read through `_read_checkpoint` rather than a name
+ a test can patch."""
+ path = tmp_path / f"{name}.safetensors"
+ save_file(state_dict, path)
+ return path
+
+
+SITES = [
+ pytest.param(
+ ErnieImageCheckpointModel,
+ ernie_image,
+ "_load_model",
+ lambda path: Main_Checkpoint_ErnieImage_Config.model_construct(path=str(path), name="ernie"),
+ # The loader takes its dtype from the device, so it never reads `self._torch_dtype`.
+ False,
+ id="ernie_image",
+ ),
+ pytest.param(
+ VAELoader,
+ vae,
+ "_load_wan_vae",
+ lambda path: VAE_Checkpoint_Wan_Config.model_construct(path=str(path), name="wan-vae"),
+ True,
+ id="wan_vae",
+ ),
+ pytest.param(
+ VAELoader,
+ vae,
+ "_load_qwen_image_vae",
+ lambda path: VAE_Checkpoint_QwenImage_Config.model_construct(path=str(path), name="qwen-vae"),
+ True,
+ id="qwen_image_vae",
+ ),
+ pytest.param(
+ # Reached by the Anima VAE registration and by the community qwen-image redistribution of
+ # the same checkpoint, and it takes a bare path rather than a config.
+ VAELoader,
+ vae,
+ "_load_wan_family_vae",
+ str,
+ True,
+ id="wan_family_vae",
+ ),
+ pytest.param(
+ Flux2VAELoader,
+ flux,
+ "_load_model",
+ lambda path: VAE_Checkpoint_Flux2_Config.model_construct(path=str(path), name="flux2-vae"),
+ True,
+ id="flux2_vae",
+ ),
+ pytest.param(
+ AnimaControlNetLLLiteModel,
+ anima,
+ "_load_model",
+ lambda path: ControlNet_Checkpoint_Anima_Config.model_construct(path=str(path), name="anima-control"),
+ True,
+ id="anima_controlnet",
+ ),
+]
+
+
[email protected](("loader", "module", "entry", "argument_for", "sets_torch_dtype"), SITES)
+def test_a_quantized_checkpoint_is_refused(
+ monkeypatch, tmp_path, loader, module, entry, argument_for, sets_torch_dtype
+) -> None:
+ """The message has to say the checkpoint is quantized and that this loader cannot take it --
+ otherwise the user is left with a model that generates noise and no reason why."""
+ state_dict = _quantized()
+ assert any(tensor.dtype is torch.float8_e4m3fn for tensor in state_dict.values()), state_dict
+ checkpoint = _written(tmp_path, state_dict, "quantized")
+ seam = Seam(loader=loader, module=module, entry=entry, patches_device=True, sets_torch_dtype=sets_torch_dtype)
+ run = prepare(seam, monkeypatch)
+
+ with pytest.raises(ValueError, match="quantization side channel"):
+ run.load(argument_for(checkpoint))
+
+ # Before the cache is asked for room. ERNIE reserves on the line after the guard, so moving the
+ # guard below it would cost a multi-gigabyte reservation and cast for a load that cannot finish.
+ assert run.reserved == []
+
+
[email protected](("loader", "module", "entry", "argument_for", "sets_torch_dtype"), SITES)
+def test_a_dense_checkpoint_gets_past_the_guard(
+ monkeypatch, tmp_path, loader, module, entry, argument_for, sets_torch_dtype
+) -> None:
+ """The other half. These checkpoints are far too small to build a model from, so the load fails
+ either way -- what must not happen is that it fails *here*. Widening `is_scale_metadata_key` to
+ a spelling that also matches a dense tensor name would refuse every ordinary checkpoint, and for
+ two of these loaders there is no other test in the tree that would notice.
+ """
+ checkpoint = _written(tmp_path, _dense(), "dense")
+ seam = Seam(loader=loader, module=module, entry=entry, patches_device=True, sets_torch_dtype=sets_torch_dtype)
+ run = prepare(seam, monkeypatch)
+
+ try:
+ run.load(argument_for(checkpoint))
+ 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 checkpoint: {exc}"
diff --git a/tests/backend/model_manager/load/test_z_image_control_adapter_loader.py b/tests/backend/model_manager/load/test_z_image_control_adapter_loader.py
new file mode 100644
index 0000000000..80ee958e98
--- /dev/null
+++ b/tests/backend/model_manager/load/test_z_image_control_adapter_loader.py
@@ -0,0 +1,89 @@
+"""What the Z-Image ControlNet loader does with a quantized checkpoint.
+
+It handles no quantization side channel at all, and it is the worst-shaped of the loaders that do
+not: it builds the adapter under `init_empty_weights` and then calls
+`load_state_dict(sd, assign=True, strict=False)`. `assign=True` means the checkpoint's tensors
+*become* the parameters, so an fp8 weight stays fp8 -- there is no cast anywhere to widen it -- and
+`strict=False` sends the orphaned `weight_scale` to `unexpected_keys`, where `log_unexpected_keys`
+reports it at DEBUG and drops it. The result is an adapter whose every quantized weight is off by
+`1/weight_scale` -- orders of magnitude -- and nothing says so at the default log level.
+
+No quantized Z-Image ControlNet is published today (checked 2026-09-18: `alibaba-pai`'s ten builds
+are all dense, and `Comfy-Org/z_image_turbo` ships none), so refusing costs nothing that works.
+"""
+
+from pathlib import Path
+
+import pytest
+import safetensors.torch
+import torch
+
+from invokeai.backend.model_manager.configs.controlnet import ControlNet_Checkpoint_ZImage_Config
+from invokeai.backend.model_manager.load.model_loaders import z_image
+from invokeai.backend.model_manager.load.model_loaders.z_image import ZImageControlCheckpointModel
+from tests.fixtures.loader_seams import Seam, prepare
+from tests.fixtures.quantized_payloads import comfy_quant_marker, quantize_convrot, quantize_scaled_fp8
+
+SEAM = Seam(
+ loader=ZImageControlCheckpointModel,
+ module=z_image,
+ entry="_load_control_adapter",
+ # The loader imports `load_file` inside the method, so the name it resolves is the package's.
+ load_file_host=safetensors.torch,
+ casts_fp8_storage=False,
+)
+
+
+def _dense_adapter() -> dict[str, torch.Tensor]:
+ """The smallest state dict the loader's geometry probe accepts: one control block, two refiner
+ layers, and the embedder it reads `control_in_dim` off."""
+ return {
+ "control_layers.0.weight": torch.ones(8, 8),
+ "control_noise_refiner.0.weight": torch.ones(8, 8),
+ "control_noise_refiner.1.weight": torch.ones(8, 8),
+ "control_all_x_embedder.2-1.weight": torch.ones(3840, 64),
+ }
+
+
+def _driver(monkeypatch: pytest.MonkeyPatch, tmp_path: Path, state_dict: dict[str, torch.Tensor]):
+ checkpoint = tmp_path / "z_image_controlnet.safetensors"
+ checkpoint.touch()
+ config = ControlNet_Checkpoint_ZImage_Config.model_construct(path=str(checkpoint), name="z-image-control")
+ return prepare(SEAM, monkeypatch, state_dict=state_dict), config
+
+
+def test_a_scaled_fp8_checkpoint_is_refused_rather_than_loaded_unscaled(monkeypatch, tmp_path) -> None:
+ """`assign=True` would make the raw e4m3 codes the adapter's weights, and the scale that says
+ what they mean is dropped as an unexpected key."""
+ payload = quantize_scaled_fp8(torch.randn(8, 8))
+ state_dict = _dense_adapter()
+ state_dict["control_layers.0.weight"] = payload.codes
+ state_dict["control_layers.0.weight_scale"] = payload.scale
+ run, config = _driver(monkeypatch, tmp_path, state_dict)
+
+ with pytest.raises(ValueError, match="quantization side channel"):
+ run.load(config)
+
+
+def test_an_int8_checkpoint_is_refused_by_its_marker(monkeypatch, tmp_path) -> None:
+ """int8 is not even a dtype the adapter could run: `assign=True` would install an int8 tensor
+ where a float parameter belongs, and the un-rotation the scheme needs has no home here."""
+ codes, scale, _ = quantize_convrot(torch.randn(8, 256))
+ state_dict = _dense_adapter()
+ state_dict["control_layers.0.weight"] = codes
+ state_dict["control_layers.0.weight_scale"] = scale
+ state_dict["control_layers.0.comfy_quant"] = comfy_quant_marker({"format": "int8_tensorwise", "convrot": True})
+ run, config = _driver(monkeypatch, tmp_path, state_dict)
+
+ with pytest.raises(ValueError, match="quantization side channel"):
+ run.load(config)
+
+
+def test_a_dense_checkpoint_still_loads(monkeypatch, tmp_path) -> None:
+ """The other half: the guard must not cost the builds that exist. A refusal that fires on every
+ checkpoint is not a guard, it is an outage."""
+ run, config = _driver(monkeypatch, tmp_path, _dense_adapter())
+
+ model = run.load(config)
+
+ assert model.__class__.__name__ == "ZImageControlAdapter"