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
refactor(loaders): one object for the checkpoint wrapper prefix
Alexander Eichhorn9184f15d019f
diff --git a/invokeai/backend/model_manager/checkpoint_prefix.py b/invokeai/backend/model_manager/checkpoint_prefix.pynew file mode 100644index 0000000000..0ed5211e11--- /dev/null+++ b/invokeai/backend/model_manager/checkpoint_prefix.py@@ -0,0 +1,95 @@+"""The wrapper prefix a single-file checkpoint's keys carry, as one object.++Redistributors wrap a model's keys in a namespace of their own — ``model.diffusion_model.`` for the+ComfyUI bundle layout, ``diffusion_model.`` for the bare one, ``net.`` for Anima — and every loader+that accepts such a file has to undo that before anything reads a key. Nine near-identical copies of+that step had grown across six modules, six of them inline in a loader method, differing only in+which prefixes they listed and (for Anima alone) in whether keys outside the prefix are kept.++A loader whose list is short by one entry does not fail quietly, but it fails confusingly: every key+keeps its wrapper, so nothing matches, and the load dies on the *missing* keys rather than on the+prefix — ``load_state_dict_ignoring_extras`` logs the unexpected ones and raises for the absent ones+(``backend/util/state_dict_loading.py``). It is a defect per loader rather than one to fix once.++Identification reads the same prefixes to decide *which* loader a file goes to+(``configs/main.py``), so this module deliberately imports nothing: a cycle or a torch import here+would put the whole loading stack into identification-time code. ``backend/pid/state_dict_utils.py``+is kept dependency-free for the same reason.++Two rules this deliberately does *not* unify:++- **Per-key stripping.** The Mistral encoder strips ``text_encoder.``/``language_model.`` from each+ key independently rather than detecting one prefix for the whole file, because its redistributions+ mix wrapped and unwrapped keys. Identification strips per key too, for the same reason: it is+ looking for evidence in individual names, not normalising a file. Both share the list below;+ neither can share :meth:`CheckpointPrefix.detect`.+- **The header hints.** ``strip_layer_path_prefix`` strips any known prefix from a layer name named+ in ``_quantization_metadata``, whatever the state dict carried. Binding it to the prefix detected+ here would be stricter and would close a drift — but it would also lose the hint on a file whose+ header names a namespace its tensors do not use, which works today. Neither shape is observed on+ any checkpoint measured (0 of the 7 local files carrying header metadata name a layer their+ tensors do not), so the forgiving rule is kept: it cannot lose a hint that currently matches.+"""++from collections.abc import Iterable, Mapping+from dataclasses import dataclass+from typing import Any, TypeVar++#: What the ComfyUI single-file conventions wrap a transformer in. ``net.`` is deliberately *not*+#: here: Anima passes it in its own list, while for a PiD checkpoint ``net.`` is the model's real+#: root module rather than a wrapper (``backend/pid/state_dict_utils.py`` strips it with a deny-list+#: of its own). A shared default carrying it would teach every loader to cut into a namespace that+#: is load-bearing elsewhere.+#:+#: These two are mutually exclusive as prefixes — ``model.diffusion_model.x`` does *not* start with+#: ``diffusion_model.`` — so their order here is not load-bearing. It would become load-bearing the+#: moment an entry is added that is a prefix of another, which is why :meth:`CheckpointPrefix.detect`+#: takes the first match in *list* order rather than the longest.+COMFYUI_KEY_PREFIXES = ("model.diffusion_model.", "diffusion_model.")++T = TypeVar("T")+++@dataclass(frozen=True)+class CheckpointPrefix:+ """The one prefix a checkpoint's keys carry, or the empty string for a bare checkpoint.++ Built from the dict, then applied to it. It reports nothing beyond :attr:`prefix` because there+ is nothing else to report: for a prefix strip the whole source-to-destination mapping follows+ from that one string. A transform that renames per key does have to return its mapping, so that+ a layer's side channel can be moved to wherever its weight went.+ """++ prefix: str++ @classmethod+ def detect(cls, sd: Mapping[Any, Any], prefixes: Iterable[str] = COMFYUI_KEY_PREFIXES) -> "CheckpointPrefix":+ """The first of ``prefixes`` that any key starts with, in the order given."""+ for prefix in prefixes:+ if any(isinstance(key, str) and key.startswith(prefix) for key in sd):+ return cls(prefix)+ return cls("")++ def strip(self, sd: dict[Any, T], *, drop_foreign: bool = False) -> dict[Any, T]:+ """``sd`` re-keyed into the model's own namespace.++ A bare checkpoint is returned as it came, not copied: loaders drop their reference to the+ dict to let the weights go before a cast, and an extra copy here would keep them alive.++ ``drop_foreign`` discards what was *not* under the prefix, which is what a loader reading an+ all-in-one export wants: the bundled VAE and text encoder sit beside the transformer under+ namespaces of their own, and they are not this model's. It applies only once a prefix has+ been detected — a bare checkpoint has nothing to tell foreign keys apart by, and dropping+ them there would hide a stray key from the unexpected-key checks that exist to report it.+ """+ if not self.prefix:+ return sd+ cut = len(self.prefix)+ if drop_foreign:+ return {+ key[cut:]: value for key, value in sd.items() if isinstance(key, str) and key.startswith(self.prefix)+ }+ return {+ (key[cut:] if isinstance(key, str) and key.startswith(self.prefix) else key): value+ for key, value in sd.items()+ }diff --git a/invokeai/backend/model_manager/configs/main.py b/invokeai/backend/model_manager/configs/main.pyindex 34ad1b758b..3d345a56e0 100644--- a/invokeai/backend/model_manager/configs/main.py+++ b/invokeai/backend/model_manager/configs/main.py@@ -6,6 +6,7 @@ from typing import Any, Literal, Selfimport torchfrom pydantic import BaseModel, Field+from invokeai.backend.model_manager.checkpoint_prefix import COMFYUI_KEY_PREFIXESfrom invokeai.backend.model_manager.configs.base import (Checkpoint_Config_Base,Config_Base,@@ -1910,15 +1911,16 @@ class Main_Diffusers_QwenImage_Config(Diffusers_Config_Base, Main_Config_Base, Creturn QwenImageVariantType.Generate-# ComfyUI single-file checkpoints prefix every transformer key with one of these.-# The loaders strip them before instantiating the model (see `_strip_comfyui_prefix`-# in the qwen_image loader); detection must strip them too so the two paths agree.-_COMFYUI_KEY_PREFIXES = ("model.diffusion_model.", "diffusion_model.")+# ComfyUI single-file checkpoints prefix every transformer key with one of these. The loaders strip+# them before instantiating the model (`CheckpointPrefix`), and detection has to strip them too or+# the two disagree: a file identification accepts, the loader then refuses with every key unexpected.+# Shared rather than restated, which is what made them drift; the *operation* still differs, because+# detection looks for evidence in individual names instead of normalising a whole file.def _strip_comfyui_key_prefix(key: str) -> str:"""Strip a leading ComfyUI `model.diffusion_model.` / `diffusion_model.` prefix from a key."""- for prefix in _COMFYUI_KEY_PREFIXES:+ for prefix in COMFYUI_KEY_PREFIXES:if key.startswith(prefix):return key[len(prefix) :]return keydiff --git a/invokeai/backend/model_manager/load/model_loaders/anima.py b/invokeai/backend/model_manager/load/model_loaders/anima.pyindex c2a7ef65ce..e6f2cb0dd1 100644--- a/invokeai/backend/model_manager/load/model_loaders/anima.py+++ b/invokeai/backend/model_manager/load/model_loaders/anima.py@@ -6,6 +6,7 @@ from typing import Optionalimport accelerate+from invokeai.backend.model_manager.checkpoint_prefix import CheckpointPrefixfrom invokeai.backend.model_manager.configs.base import Checkpoint_Config_Basefrom invokeai.backend.model_manager.configs.controlnet import ControlNet_Checkpoint_Anima_Configfrom invokeai.backend.model_manager.configs.factory import AnyModelConfig@@ -41,6 +42,13 @@ from invokeai.backend.util.state_dict_loading import log_unexpected_keys, rejectlogger = InvokeAILogger.get_logger(__name__)+#: Anima's own wrapper namespaces. `net.` is the official packaging; the ComfyUI bundle uses the+#: usual `model.diffusion_model.`. `diffusion_model.` is deliberately absent -- no Anima+#: redistribution measured uses it, and `net.` is not stripped anywhere else because it is also the+#: root module name of a PiD checkpoint.+ANIMA_KEY_PREFIXES = ("model.diffusion_model.", "net.")++def _strip_anima_bundle_prefix(sd: dict) -> dict:"""Strip the transformer-key prefix from an Anima single-file checkpoint.@@ -53,21 +61,7 @@ def _strip_anima_bundle_prefix(sd: dict) -> dict:checkpoints (VAE, text encoder) are dropped. If no known prefix is present, thestate dict is returned unchanged."""- prefix_to_strip = None- for prefix in ["model.diffusion_model.", "net."]:- if any(k.startswith(prefix) for k in sd.keys() if isinstance(k, str)):- prefix_to_strip = prefix- break-- if prefix_to_strip is None:- return sd-- stripped_sd: dict = {}- for key, value in sd.items():- if isinstance(key, str) and key.startswith(prefix_to_strip):- stripped_sd[key[len(prefix_to_strip) :]] = value- # Skip non-transformer keys from bundled checkpoints (VAE, text encoder)- return stripped_sd+ return CheckpointPrefix.detect(sd, ANIMA_KEY_PREFIXES).strip(sd, drop_foreign=True)# Checkpoint tensors that are not part of the transformer's in-memory state. Suffixes matchdiff --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 1795f89c66..0f1d5259ed 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@@ -21,24 +21,6 @@ from invokeai.backend.quantization.int8_convrot import reject_int8_layers_a_plaifrom invokeai.backend.quantization.nvfp4 import reject_nvfp4_layers_a_plain_fold_cannot_decode-def _strip_comfyui_prefix(sd: dict) -> dict:- """Strip ComfyUI-style `model.diffusion_model.` / `diffusion_model.` prefixes from keys."""- prefix_to_strip = None- for prefix in ["model.diffusion_model.", "diffusion_model."]:- if any(k.startswith(prefix) for k in sd.keys() if isinstance(k, str)):- prefix_to_strip = prefix- break- if prefix_to_strip is None:- return sd- stripped: dict = {}- for key, value in sd.items():- if isinstance(key, str) and key.startswith(prefix_to_strip):- stripped[key[len(prefix_to_strip) :]] = value- else:- stripped[key] = value- return stripped--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.diff --git a/invokeai/backend/model_manager/load/model_loaders/flux.py b/invokeai/backend/model_manager/load/model_loaders/flux.pyindex 5ecf42aa83..9dab609f85 100644--- a/invokeai/backend/model_manager/load/model_loaders/flux.py+++ b/invokeai/backend/model_manager/load/model_loaders/flux.py@@ -35,6 +35,7 @@ from invokeai.backend.flux.model import Fluxfrom invokeai.backend.flux.modules.autoencoder import AutoEncoderfrom invokeai.backend.flux.redux.flux_redux_model import FluxReduxModelfrom invokeai.backend.flux.util import get_flux_ae_params, get_flux_transformers_params+from invokeai.backend.model_manager.checkpoint_prefix import CheckpointPrefixfrom invokeai.backend.model_manager.configs.base import Checkpoint_Config_Base, Diffusers_Config_Basefrom invokeai.backend.model_manager.configs.clip_embed import CLIPEmbed_Diffusers_Config_Basefrom invokeai.backend.model_manager.configs.controlnet import (@@ -1172,17 +1173,7 @@ class Flux2CheckpointModel(ModelLoader):# Check if keys have ComfyUI-style prefix and strip if needed. This runs before anything# reads the quantization side-channel: the scales carry the same prefix as their weights.- prefix_to_strip = None- for prefix in ["model.diffusion_model.", "diffusion_model."]:- if any(k.startswith(prefix) for k in sd.keys() if isinstance(k, str)):- prefix_to_strip = prefix- break-- if prefix_to_strip:- sd = {- (k[len(prefix_to_strip) :] if isinstance(k, str) and k.startswith(prefix_to_strip) else k): v- for k, v in sd.items()- }+ sd = CheckpointPrefix.detect(sd).strip(sd)# Which of the two ComfyUI side channels this file carries is decided once, and int8 first:# an int8 layer ships a `.weight_scale` too, so probing for scales without ruling int8 out@@ -1694,17 +1685,7 @@ class Flux2GGUFCheckpointModel(ModelLoader):sd = gguf_sd_loader(model_path, compute_dtype=torch.bfloat16)# Check if keys have ComfyUI-style prefix and strip if needed- prefix_to_strip = None- for prefix in ["model.diffusion_model.", "diffusion_model."]:- if any(k.startswith(prefix) for k in sd.keys() if isinstance(k, str)):- prefix_to_strip = prefix- break-- if prefix_to_strip:- sd = {- (k[len(prefix_to_strip) :] if isinstance(k, str) and k.startswith(prefix_to_strip) else k): v- for k, v in sd.items()- }+ sd = CheckpointPrefix.detect(sd).strip(sd)# Convert BFL format state dict to diffusers formatconverted_sd = convert_flux2_bfl_to_diffusers(sd)diff --git a/invokeai/backend/model_manager/load/model_loaders/krea2.py b/invokeai/backend/model_manager/load/model_loaders/krea2.pyindex 286570f4c1..f5c4f1ca93 100644--- a/invokeai/backend/model_manager/load/model_loaders/krea2.py+++ b/invokeai/backend/model_manager/load/model_loaders/krea2.py@@ -7,6 +7,7 @@ from typing import Any, Optionalimport acceleratefrom transformers import AutoConfig, AutoTokenizer+from invokeai.backend.model_manager.checkpoint_prefix import CheckpointPrefixfrom invokeai.backend.model_manager.configs.base import Checkpoint_Config_Base, Diffusers_Config_Basefrom invokeai.backend.model_manager.configs.factory import AnyModelConfigfrom invokeai.backend.model_manager.configs.main import Main_Checkpoint_Krea2_Config, Main_GGUF_Krea2_Config@@ -70,21 +71,6 @@ from invokeai.backend.util.state_dict_loading import load_state_dict_ignoring_ex_normalize_qwen3vl_rope_config = normalize_qwen3vl_rope_config-def _strip_comfyui_prefix(sd: dict[str, Any]) -> dict[str, Any]:- """Strip ComfyUI-style ``model.diffusion_model.`` / ``diffusion_model.`` key prefixes if present."""- prefix_to_strip = None- for prefix in ("model.diffusion_model.", "diffusion_model."):- if any(isinstance(k, str) and k.startswith(prefix) for k in sd.keys()):- prefix_to_strip = prefix- break- if not prefix_to_strip:- return sd- return {- (k[len(prefix_to_strip) :] if isinstance(k, str) and k.startswith(prefix_to_strip) else k): v- for k, v in sd.items()- }--def _to_plain_tensor(value: Any) -> Any:"""Dequantize a GGMLTensor to a plain tensor (needed before reshape); pass others through."""if hasattr(value, "get_dequantized_tensor"):@@ -409,7 +395,7 @@ class Krea2CheckpointModel(ModelLoader):sd = load_file(model_path)metadata = read_safetensors_metadata(model_path, self._logger)- sd = _strip_comfyui_prefix(sd)+ sd = CheckpointPrefix.detect(sd).strip(sd)# Discard what the key conversion below would discard anyway, before anything is spent on# it. One repack quantizes `last.up` with a blockwise scale grid this decode does not# implement; refusing a tensor that is on its way to the bin would be an odd way to fail.@@ -666,7 +652,7 @@ class Krea2GGUFCheckpointModel(ModelLoader):# GGMLTensor wrappers (kept on CPU; dequantized on-the-fly by the cache during inference).sd = gguf_sd_loader(model_path, compute_dtype=compute_dtype)- sd = _strip_comfyui_prefix(sd)+ sd = CheckpointPrefix.detect(sd).strip(sd)# GGUF conversions use the native/ComfyUI compact key naming; remap to diffusers keys.if _is_native_krea2_format(sd):sd = _convert_krea2_native_to_diffusers(sd)diff --git a/invokeai/backend/model_manager/load/model_loaders/qwen_image.py b/invokeai/backend/model_manager/load/model_loaders/qwen_image.pyindex c72b40cf1b..28710a272a 100644--- a/invokeai/backend/model_manager/load/model_loaders/qwen_image.py+++ b/invokeai/backend/model_manager/load/model_loaders/qwen_image.py@@ -4,6 +4,7 @@ from typing import Optionalimport accelerateimport torch+from invokeai.backend.model_manager.checkpoint_prefix import CheckpointPrefixfrom invokeai.backend.model_manager.configs.base import Checkpoint_Config_Base, Diffusers_Config_Basefrom invokeai.backend.model_manager.configs.factory import AnyModelConfigfrom invokeai.backend.model_manager.configs.main import (@@ -18,7 +19,6 @@ from invokeai.backend.model_manager.load.load_default import ModelLoader, _modelfrom invokeai.backend.model_manager.load.model_loader_registry import ModelLoaderRegistryfrom invokeai.backend.model_manager.load.model_loaders.comfyui_state_dict_utils import (_dequantize_comfyui_fp8,- _strip_comfyui_prefix,_strip_quantization_metadata,)from invokeai.backend.model_manager.load.model_loaders.generic_diffusers import GenericDiffusersLoader@@ -227,7 +227,7 @@ class QwenImageGGUFCheckpointModel(ModelLoader):compute_dtype = TorchDevice.choose_bfloat16_safe_dtype(target_device)sd = gguf_sd_loader(model_path, compute_dtype=compute_dtype)- sd = _strip_comfyui_prefix(sd)+ sd = CheckpointPrefix.detect(sd).strip(sd)is_edit = getattr(config, "variant", None) == QwenImageVariantType.Editmodel_config = _build_qwen_image_transformer_config(sd, is_edit=is_edit)@@ -282,7 +282,7 @@ class QwenImageCheckpointModel(ModelLoader):model_dtype = TorchDevice.choose_bfloat16_safe_dtype(target_device)sd = load_file(str(model_path))- sd = _strip_comfyui_prefix(sd)+ sd = CheckpointPrefix.detect(sd).strip(sd)# Comfy's nvfp4 build keeps the image stream's attention and MLP in nvfp4, beside scaled fp8. Take those layers# out before the fold: `_dequantize_comfyui_fp8` multiplies every `.weight_scale` into its weight, nvfp4'sdiff --git a/invokeai/backend/model_manager/load/model_loaders/wan.py b/invokeai/backend/model_manager/load/model_loaders/wan.pyindex 3d165e77fa..b8440971c9 100644--- a/invokeai/backend/model_manager/load/model_loaders/wan.py+++ b/invokeai/backend/model_manager/load/model_loaders/wan.py@@ -16,6 +16,7 @@ from typing import Any, Optionalimport torch+from invokeai.backend.model_manager.checkpoint_prefix import CheckpointPrefixfrom invokeai.backend.model_manager.configs.base import Checkpoint_Config_Base, Diffusers_Config_Basefrom invokeai.backend.model_manager.configs.factory import AnyModelConfigfrom invokeai.backend.model_manager.configs.main import (@@ -27,7 +28,6 @@ from invokeai.backend.model_manager.load.load_default import ModelLoaderfrom invokeai.backend.model_manager.load.model_loader_registry import ModelLoaderRegistryfrom invokeai.backend.model_manager.load.model_loaders.comfyui_state_dict_utils import (_dequantize_comfyui_fp8,- _strip_comfyui_prefix,_strip_quantization_metadata,)from invokeai.backend.model_manager.load.model_loaders.generic_diffusers import GenericDiffusersLoader@@ -427,12 +427,7 @@ class WanGGUFCheckpointModel(ModelLoader):sd = gguf_sd_loader(model_path, compute_dtype=compute_dtype)# Strip ComfyUI-style prefixes if present.- for prefix in ("model.diffusion_model.", "diffusion_model."):- if any(isinstance(k, str) and k.startswith(prefix) for k in sd.keys()):- sd = {- (k[len(prefix) :] if isinstance(k, str) and k.startswith(prefix) else k): v for k, v in sd.items()- }- break+ sd = CheckpointPrefix.detect(sd).strip(sd)_drop_benign_extra_keys(sd, "GGUF state dict", InvokeAILogger.get_logger(self.__class__.__name__))@@ -505,7 +500,7 @@ class WanCheckpointModel(ModelLoader):model_dtype = TorchDevice.choose_bfloat16_safe_dtype(target_device)sd = load_file(str(model_path))- sd = _strip_comfyui_prefix(sd)+ sd = CheckpointPrefix.detect(sd).strip(sd)_drop_benign_extra_keys(sd, "Wan checkpoint", logger)dequantized = _dequantize_comfyui_fp8(sd, model_dtype, f"Wan checkpoint {model_path.name}")diff --git a/invokeai/backend/model_manager/load/model_loaders/z_image.py b/invokeai/backend/model_manager/load/model_loaders/z_image.pyindex 273c6dd4f9..5fe9e4b2aa 100644--- a/invokeai/backend/model_manager/load/model_loaders/z_image.py+++ b/invokeai/backend/model_manager/load/model_loaders/z_image.py@@ -8,6 +8,7 @@ import accelerateimport torchfrom transformers import AutoTokenizer, Qwen3ForCausalLM+from invokeai.backend.model_manager.checkpoint_prefix import CheckpointPrefixfrom invokeai.backend.model_manager.configs.base import Checkpoint_Config_Base, Diffusers_Config_Basefrom invokeai.backend.model_manager.configs.controlnet import ControlNet_Checkpoint_ZImage_Configfrom invokeai.backend.model_manager.configs.factory import AnyModelConfig@@ -483,20 +484,7 @@ class ZImageCheckpointModel(ModelLoader):# Some Z-Image checkpoint files have keys prefixed with "diffusion_model." or# "model.diffusion_model." (ComfyUI-style format). Check if we need to strip this prefix.- prefix_to_strip = None- for prefix in ["model.diffusion_model.", "diffusion_model."]:- if any(k.startswith(prefix) for k in sd.keys() if isinstance(k, str)):- prefix_to_strip = prefix- break-- if prefix_to_strip:- stripped_sd = {}- for key, value in sd.items():- if isinstance(key, str) and key.startswith(prefix_to_strip):- stripped_sd[key[len(prefix_to_strip) :]] = value- else:- stripped_sd[key] = value- sd = stripped_sd+ sd = CheckpointPrefix.detect(sd).strip(sd)# Determine safe dtype based on target device capabilitiestarget_device = TorchDevice.choose_torch_device()@@ -774,20 +762,7 @@ class ZImageGGUFCheckpointModel(ModelLoader):# Some Z-Image GGUF models have keys prefixed with "diffusion_model." or# "model.diffusion_model." (ComfyUI-style format). Check if we need to strip this prefix.- prefix_to_strip = None- for prefix in ["model.diffusion_model.", "diffusion_model."]:- if any(k.startswith(prefix) for k in sd.keys() if isinstance(k, str)):- prefix_to_strip = prefix- break-- if prefix_to_strip:- stripped_sd = {}- for key, value in sd.items():- if isinstance(key, str) and key.startswith(prefix_to_strip):- stripped_sd[key[len(prefix_to_strip) :]] = value- else:- stripped_sd[key] = value- sd = stripped_sd+ sd = CheckpointPrefix.detect(sd).strip(sd)# Convert GGUF format keys to diffusers formatsd = _convert_z_image_gguf_to_diffusers(sd)@@ -908,20 +883,7 @@ class ZImageSDNQCheckpointModel(ModelLoader):# Some Z-Image SDNQ models may have keys prefixed with "diffusion_model." or# "model.diffusion_model." (ComfyUI-style format). Check if we need to strip this prefix.- prefix_to_strip = None- for prefix in ["model.diffusion_model.", "diffusion_model."]:- if any(k.startswith(prefix) for k in sd.keys() if isinstance(k, str)):- prefix_to_strip = prefix- break-- if prefix_to_strip:- stripped_sd = {}- for key, value in sd.items():- if isinstance(key, str) and key.startswith(prefix_to_strip):- stripped_sd[key[len(prefix_to_strip) :]] = value- else:- stripped_sd[key] = value- sd = stripped_sd+ sd = CheckpointPrefix.detect(sd).strip(sd)# Check if conversion is needed (original format vs diffusers format)needs_conversion = any(k.startswith("x_embedder.") for k in sd.keys() if isinstance(k, str))diff --git a/invokeai/backend/quantization/fp8_scaled.py b/invokeai/backend/quantization/fp8_scaled.pyindex ad52626782..95433742fd 100644--- a/invokeai/backend/quantization/fp8_scaled.py+++ b/invokeai/backend/quantization/fp8_scaled.py@@ -167,6 +167,11 @@ def extract_comfy_quant_hints(sd: dict[str, Any]) -> dict[str, dict[str, Any]]:# Key prefixes redistributors wrap a transformer in. Loaders strip these off the state dict before# anything else, so `_quantization_metadata` — which is read from the file and still carries them —# has to be stripped the same way.+#+# Deliberately a superset of what any single loader strips, and deliberately not bound to the prefix+# a loader detected: see `model_manager/checkpoint_prefix.py`, which records why the forgiving rule+# is the one kept. Binding the two is the obvious-looking change, and it loses a hint that matches+# today.TRANSFORMER_KEY_PREFIXES = ("model.diffusion_model.", "diffusion_model.", "net.")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 f8d6f0aa36..8818414b99 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@@ -440,3 +440,23 @@ def test_a_scaled_fp8_checkpoint_still_folds_its_scales(monkeypatch, tmp_path) -assert not hasattr(layer, "weight_scale"), path# fp8 keeps ~2 decimal digits, so this is a "the scale was applied" check, not a bit compare.assert torch.allclose(layer.weight.float(), source, rtol=0.1, atol=0.1 * source.abs().max())+++def test_a_comfyui_prefixed_checkpoint_loads_the_same_as_a_bare_one(monkeypatch, tmp_path) -> None:+ """Not about int8 -- about the prefix strip this loader performs before it reads any side+ channel, which was eight lines inline here and which no test noticed. A redistribution wrapping+ every key in `model.diffusion_model.` passes the config probes and reaches this method; with the+ strip gone, the markers and scales are read from keys the model does not have. Asserted against+ the bare load, so the two cannot drift apart.+ """+ state_dict, _ = _checkpoint()+ prefixed = {f"model.diffusion_model.{key}": value for key, value in state_dict.items()}++ run, config = _driver(monkeypatch, tmp_path, prefixed)+ from_prefixed = run.loader._load_model(config, SubModelType.Transformer).state_dict()+ run, config = _driver(monkeypatch, tmp_path, state_dict)+ from_bare = run.loader._load_model(config, SubModelType.Transformer).state_dict()++ assert set(from_prefixed) == set(from_bare)+ for key, value in from_bare.items():+ assert torch.equal(from_prefixed[key].to(torch.float32), value.to(torch.float32)), keydiff --git a/tests/backend/model_manager/load/test_fp8_hint_prefixes.py b/tests/backend/model_manager/load/test_fp8_hint_prefixes.pyindex 3c93e7349a..0c1a6cb7cb 100644--- a/tests/backend/model_manager/load/test_fp8_hint_prefixes.py+++ b/tests/backend/model_manager/load/test_fp8_hint_prefixes.py@@ -90,3 +90,21 @@ class TestFluxHintPrefixes:layers = extract_fp8_scaled_layers(sd, layer_hints=strip_layer_path_prefix(header))assert layers["double_blocks.0.img_attn.qkv"].full_precision_matmul is True+++def test_a_prefixed_hint_still_reaches_a_checkpoint_whose_tensors_are_bare() -> None:+ """The decision `checkpoint_prefix.py` records, made falsifiable.++ The hint re-keyer strips any known prefix, whatever the state dict carried. Binding it instead+ to the prefix the loader *detected* is the obvious-looking way to stop the two lists drifting --+ and on this shape, a header naming `model.diffusion_model.X` over bare tensors, the detected+ prefix is the empty string, the hint keeps its wrapper, matches nothing, and+ `full_precision_matrix_mult` is lost in silence. Neither this shape nor its mirror is observed on+ any local checkpoint, so the rule that cannot lose a hint is the one kept.+ """+ sd = _quantized("double_blocks.0.img_attn.qkv")+ header = {"model.diffusion_model.double_blocks.0.img_attn.qkv": {"full_precision_matrix_mult": True}}++ layers = extract_fp8_scaled_layers(sd, layer_hints=strip_layer_path_prefix(header))++ assert layers["double_blocks.0.img_attn.qkv"].full_precision_matmul is Truediff --git a/tests/backend/model_manager/load/test_krea2_state_dict_utils.py b/tests/backend/model_manager/load/test_krea2_state_dict_utils.pyindex 0b65b4430c..f6d9984629 100644--- a/tests/backend/model_manager/load/test_krea2_state_dict_utils.py+++ b/tests/backend/model_manager/load/test_krea2_state_dict_utils.py@@ -23,7 +23,6 @@ from invokeai.backend.model_manager.load.model_loaders.krea2 import (_reject_incomplete_load,_remap_native_layer_paths,_remap_qwen3vl_singlefile_keys,- _strip_comfyui_prefix,)from invokeai.backend.quantization.fp8_scaled import (FP8_DTYPE,@@ -63,25 +62,6 @@ class TestNormalizeQwen3vlRopeConfig:assert _normalize_qwen3vl_rope_config(config) is config-class TestStripComfyuiPrefix:- @pytest.mark.parametrize("prefix", ["model.diffusion_model.", "diffusion_model."])- def test_strips_known_prefixes(self, prefix: str) -> None:- sd = {f"{prefix}blocks.0.weight": torch.zeros(1), f"{prefix}first.weight": torch.zeros(1)}- out = _strip_comfyui_prefix(sd)- assert set(out.keys()) == {"blocks.0.weight", "first.weight"}-- def test_noop_when_no_prefix(self) -> None:- sd = {"blocks.0.weight": torch.zeros(1), "img_in.weight": torch.zeros(1)}- out = _strip_comfyui_prefix(sd)- assert set(out.keys()) == set(sd.keys())-- def test_only_the_first_matching_prefix_is_used(self) -> None:- # "model.diffusion_model." is checked before "diffusion_model.", so both strip to the same tail.- sd = {"model.diffusion_model.blocks.0.weight": torch.zeros(1)}- out = _strip_comfyui_prefix(sd)- assert list(out.keys()) == ["blocks.0.weight"]--class TestIsNativeKrea2Format:@pytest.mark.parametrize("key",diff --git a/tests/backend/model_manager/load/test_qwen_image_state_dict_utils.py b/tests/backend/model_manager/load/test_qwen_image_state_dict_utils.pyindex 425e9b6cc6..1577f0c841 100644--- a/tests/backend/model_manager/load/test_qwen_image_state_dict_utils.py+++ b/tests/backend/model_manager/load/test_qwen_image_state_dict_utils.py@@ -12,7 +12,6 @@ from invokeai.backend.model_manager.load.model_loaders.qwen_image import (_build_qwen_image_transformer_config,_dequantize_comfyui_fp8,_remap_qwen_vl_checkpoint_keys,- _strip_comfyui_prefix,_strip_quantization_metadata,)from tests.backend.model_manager.load.state_dicts.qwen_vl_encoder_comfyui_keys import (@@ -132,20 +131,6 @@ class TestDequantizeComfyuiFp8:assert torch.allclose(sd["l.weight"], expected)-class TestStripComfyuiPrefix:- def test_strips_diffusion_model_prefix(self):- sd = {- "model.diffusion_model.transformer_blocks.0.img_mod.1.weight": torch.empty(1),- "model.diffusion_model.img_in.weight": torch.empty(1),- }- out = _strip_comfyui_prefix(sd)- assert set(out.keys()) == {"transformer_blocks.0.img_mod.1.weight", "img_in.weight"}-- def test_no_prefix_is_a_noop(self):- sd = {"transformer_blocks.0.x": torch.empty(1)}- assert _strip_comfyui_prefix(sd) is sd--class TestBuildQwenImageTransformerConfig:def test_infers_layer_count_and_dims_from_shapes(self):# torch-order (logical) shapes, as the GGMLTensor.tensor_shape / safetensors path exposes.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 40b2920644..2548d04e6c 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@@ -390,3 +390,23 @@ def test_a_scaled_fp8_checkpoint_stays_packed_when_storage_is_on(monkeypatch, tmassert getattr(proj, "weight_scale", None) is not None, "kept packed but without its scale"dequantized = (proj.weight.float() * proj.weight_scale).flatten()assert torch.corrcoef(torch.stack([dequantized, original.flatten()]))[0, 1] > 0.999+++def test_a_comfyui_prefixed_checkpoint_loads_the_same_as_a_bare_one(monkeypatch, tmp_path) -> None:+ """The prefix strip used to be eight lines inline in this method, and nothing here noticed if it+ went away: a redistribution wrapping every key in `model.diffusion_model.` is accepted by the+ config probes, so it reaches this loader, and unstripped it hands the model a state dict in which+ every key is unexpected. Asserted against the bare load rather than a key list, so the two cannot+ drift apart."""+ torch.manual_seed(0)+ bare = {key: value.clone() for key, value in _TinyZImage().state_dict().items()}+ prefixed = {f"model.diffusion_model.{key}": value for key, value in bare.items()}++ run, config = _driver(monkeypatch, tmp_path, prefixed)+ from_prefixed = run.load(config).state_dict()+ run, config = _driver(monkeypatch, tmp_path, bare)+ from_bare = run.load(config).state_dict()++ assert set(from_prefixed) == set(from_bare)+ for key, value in from_bare.items():+ assert torch.equal(from_prefixed[key], value), keydiff --git a/tests/backend/model_manager/test_checkpoint_prefix.py b/tests/backend/model_manager/test_checkpoint_prefix.pynew file mode 100644index 0000000000..8263d7a8b8--- /dev/null+++ b/tests/backend/model_manager/test_checkpoint_prefix.py@@ -0,0 +1,87 @@+"""The shared wrapper-prefix strip, which nine places across six modules had a copy of.++What is worth pinning here is not that a prefix comes off -- it is the three decisions the copies+made silently and differently: which prefix wins when two match, what happens to keys that were not+under it, and whether a bare checkpoint may have keys dropped at all.+"""++import pytest+import torch++from invokeai.backend.model_manager.checkpoint_prefix import COMFYUI_KEY_PREFIXES, CheckpointPrefix++#: Spelled out rather than taken from `COMFYUI_KEY_PREFIXES`: a cell parametrized over the constant+#: it is meant to pin loses the case along with the entry, and passes.+BOTH_COMFYUI_SPELLINGS = ("model.diffusion_model.", "diffusion_model.")++[email protected]("prefix", BOTH_COMFYUI_SPELLINGS)+def test_every_spelling_the_config_probes_accept_is_actually_stripped(prefix: str) -> None:+ """Both reach real files: the config probes accept either, so a file carrying the bare+ `diffusion_model.` form installs and is routed to a loader. Were it missing from the constant,+ that loader would hand the model a state dict with every key still wrapped."""+ sd = {f"{prefix}blocks.0.attn.weight": torch.zeros(1)}++ detected = CheckpointPrefix.detect(sd, COMFYUI_KEY_PREFIXES)++ assert detected.prefix == prefix+ assert list(detected.strip(sd)) == ["blocks.0.attn.weight"]+++def test_detection_takes_the_first_prefix_in_list_order() -> None:+ """The two ComfyUI spellings are mutually exclusive as prefixes -- `model.diffusion_model.x` does+ not start with `diffusion_model.` -- so their order in the constant cannot be observed, and a+ cell using them would pin nothing. What *is* worth pinning is the rule for a list where one entry+ is a prefix of another, because that is the day the order starts to matter: the first match in+ list order wins, not the longest.+ """+ sd = {"a.x": torch.zeros(1), "a.b.y": torch.zeros(1)}++ assert CheckpointPrefix.detect(sd, ("a.b.", "a.")).prefix == "a.b."+ assert CheckpointPrefix.detect(sd, ("a.", "a.b.")).prefix == "a."+++def test_a_bare_checkpoint_is_returned_as_it_came() -> None:+ sd = {"blocks.0.attn.weight": torch.zeros(1)}++ assert CheckpointPrefix.detect(sd, COMFYUI_KEY_PREFIXES).strip(sd) is sd+++def test_keys_outside_the_prefix_are_kept_by_default() -> None:+ """Eleven of the twelve call sites keep them, and filter later by rules of their own if at+ all. Only Anima asks for them to be dropped."""+ sd = {"net.blocks.0.weight": torch.zeros(1), "first_stage_model.encoder.weight": torch.zeros(1)}++ stripped = CheckpointPrefix.detect(sd, ("net.",)).strip(sd)++ assert sorted(stripped) == ["blocks.0.weight", "first_stage_model.encoder.weight"]+++def test_an_all_in_one_export_can_drop_what_is_not_its_model() -> None:+ """The one caller that asks for it (Anima) reads bundles where the VAE and text encoder sit+ beside the transformer under namespaces of their own. Those are not its model's weights."""+ sd = {"net.blocks.0.weight": torch.zeros(1), "first_stage_model.encoder.weight": torch.zeros(1)}++ stripped = CheckpointPrefix.detect(sd, ("net.",)).strip(sd, drop_foreign=True)++ assert sorted(stripped) == ["blocks.0.weight"]+++def test_a_bare_checkpoint_keeps_its_stray_keys_even_when_foreign_ones_may_be_dropped() -> None:+ """With no prefix there is nothing to tell a foreign key from an own one, so dropping would be+ guessing -- and it would hide the stray key from the unexpected-key checks that report it."""+ sd = {"blocks.0.weight": torch.zeros(1), "discriminator.weight": torch.zeros(1)}++ stripped = CheckpointPrefix.detect(sd, ("net.",)).strip(sd, drop_foreign=True)++ assert sorted(stripped) == ["blocks.0.weight", "discriminator.weight"]+++def test_a_non_string_key_survives_detection_and_the_strip() -> None:+ """Checkpoints have arrived with non-string keys; every copy of this code guarded for it, so the+ guard is load-bearing rather than defensive."""+ sd = {7: torch.zeros(1), "model.diffusion_model.blocks.0.weight": torch.zeros(1)}++ stripped = CheckpointPrefix.detect(sd, COMFYUI_KEY_PREFIXES).strip(sd)++ assert sorted(map(str, stripped)) == ["7", "blocks.0.weight"]