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
feat(quantization): read int8_convrot Z-Image checkpoints
Alexander Eichhorn8c9de55aa9a2
diff --git a/invokeai/backend/model_manager/load/model_loaders/krea2.py b/invokeai/backend/model_manager/load/model_loaders/krea2.pyindex 51156a7d60..0dd981874a 100644--- a/invokeai/backend/model_manager/load/model_loaders/krea2.py+++ b/invokeai/backend/model_manager/load/model_loaders/krea2.py@@ -27,10 +27,11 @@ from invokeai.backend.model_manager.taxonomy import (from invokeai.backend.model_manager.util.qwen3_vl import normalize_qwen3vl_rope_configfrom invokeai.backend.quantization.gguf.loaders import gguf_sd_loaderfrom invokeai.backend.quantization.int8_convrot import (- CONVROT_GROUP_SIZE,- Int8ConvrotLinear,- check_int8_scale_layout,+ cast_unquantized,+ drop_unconsumed_quantization_sidecars,extract_int8_convrot_markers,+ resolve_quantized_module_paths,+ swap_in_int8_linears,)from invokeai.backend.util.devices import TorchDevice@@ -402,12 +403,12 @@ class Krea2CheckpointModel(ModelLoader):# compute dtype is resolved first so the dequantized weights land there directly instead of# transiently materializing the whole model in float32.sd = _dequantize_scaled_fp8(sd, model_dtype)- sd = _drop_unconsumed_quantization_sidecars(sd)+ sd = drop_unconsumed_quantization_sidecars(sd)# Native/ComfyUI key naming → diffusers Krea2Transformer2DModel keys.key_map: dict[str, str] = {}if _is_native_krea2_format(sd):sd = _convert_krea2_native_to_diffusers(sd, key_map=key_map)- quantized = _resolve_quantized_module_paths(int8_markers, key_map)+ quantized = resolve_quantized_module_paths(int8_markers, key_map)with accelerate.init_empty_weights():model = Krea2Transformer2DModel(**KREA2_TRANSFORMER_CONFIG)@@ -416,8 +417,8 @@ class Krea2CheckpointModel(ModelLoader):# ask the cache to free ~12 GB that this load never uses.new_sd_size = sum(ten.nelement() * max(ten.element_size(), model_dtype.itemsize) for ten in sd.values())self._ram_cache.make_room(new_sd_size)- _cast_unquantized(sd, model_dtype, quantized)- _swap_in_int8_linears(model, sd, quantized)+ cast_unquantized(sd, model_dtype, quantized)+ swap_in_int8_linears(model, sd, quantized)model.load_state_dict(sd, assign=True, strict=False)_reject_incomplete_load(model, what="Krea-2 single-file checkpoint")@@ -553,86 +554,6 @@ def _remap_qwen3vl_singlefile_keys(sd: dict[str, Any], *, key_map: dict[str, strreturn out-def _drop_unconsumed_quantization_sidecars(sd: dict[str, Any]) -> dict[str, Any]:- """Remove quantization metadata no loader here consumes.-- - ``.comfy_quant`` markers whose format was handled elsewhere, or not at all.- - ``.input_scale`` / ``.scale_input``: activation scales for W8A8 inference. This code- dequantizes the weight and computes in bf16, so there is nothing to apply them to. (Both- spellings appear in the wild; one Qwen3-VL repack ships 337 of the former.)-- `load_state_dict(strict=False)` would ignore them, but they are still cast and still counted- against the RAM reservation - and a loader that later switches to strict would fail on them.- """- return {- k: v- for k, v in sd.items()- if not (isinstance(k, str) and (k.endswith(".comfy_quant") or "input_scale" in k or "scale_input" in k))- }---def _resolve_quantized_module_paths(- markers: dict[str, dict[str, Any]], key_map: dict[str, str]-) -> dict[str, dict[str, Any]]:- """Re-key markers from the checkpoint's names to the built model's names.-- The markers are read in the checkpoint's key space, because that is the only place where a- marker and its weight are reliably paired: the key conversions rename `.weight` (and, by- substring, `.weight_scale`) but leave `.comfy_quant` behind on the old name. Following the- weight's own rename is therefore the only mapping that cannot drift from the conversion.- """- resolved: dict[str, dict[str, Any]] = {}- for path, marker in markers.items():- weight_key = key_map.get(f"{path}.weight", f"{path}.weight")- resolved[weight_key[: -len(".weight")]] = marker- return resolved---def _swap_in_int8_linears(model: Any, sd: dict[str, Any], quantized: dict[str, dict[str, Any]]) -> None:- """Replace each quantized ``nn.Linear`` with an ``Int8ConvrotLinear`` sized from the state dict.-- The weights stay int8 and rotated as stored; the layer dequantizes and derotates per forward.- That keeps a 12 GB checkpoint at 12 GB resident instead of the ~24 GB a dense decode would- produce, on every platform and without the fp8-storage opt-in (which is off by default and- unavailable outside CUDA/XPU).-- Its persistent buffers are named ``weight``/``weight_scale`` -- the checkpoint's own spelling --- so the ``load_state_dict`` that follows assigns the quantized tensors straight into them.- """- for path, marker in quantized.items():- weight, scale = sd.get(f"{path}.weight"), sd.get(f"{path}.weight_scale")- if weight is None or scale is None:- raise ValueError(- f"'{path}' is marked int8_tensorwise but is missing its "- f"{'weight' if weight is None else 'weight_scale'}."- )- check_int8_scale_layout(path, weight, scale)- parent_path, _, attribute = path.rpartition(".")- setattr(- model.get_submodule(parent_path) if parent_path else model,- attribute,- Int8ConvrotLinear(- weight=weight,- weight_scale=scale,- convrot=bool(marker.get("convrot", False)),- bias=sd.get(f"{path}.bias"),- group_size=int(marker.get("convrot_groupsize", CONVROT_GROUP_SIZE)),- ),- )---def _cast_unquantized(sd: dict[str, Any], dtype: "torch.dtype", quantized: dict[str, dict[str, Any]]) -> None:- """Cast the dense tensors to the compute dtype, leaving the quantized payloads alone.-- An int8 weight cast to bf16 is no longer int8, and its float32 scale is what- ``Int8ConvrotLinear`` multiplies by -- both have to reach ``load_state_dict`` as stored.- """- pinned = {key for path in quantized for key in (f"{path}.weight", f"{path}.weight_scale")}- for key in sd:- if key not in pinned:- sd[key] = sd[key].to(dtype)--def _reject_incomplete_load(model: Any, *, what: str) -> None:"""Raise if a ``load_state_dict(strict=False)`` left required tensors on the meta device.@@ -729,10 +650,10 @@ class Qwen3VLEncoderCheckpointLoader(ModelLoader):) or any(getattr(t, "dtype", None) in (torch.float8_e4m3fn, torch.float8_e5m2) for t in sd.values())# ComfyUI 'scaled fp8': fold weight_scale into the weights, then drop quantization metadata.sd = _dequantize_scaled_fp8(sd, model_dtype)- sd = _drop_unconsumed_quantization_sidecars(sd)+ sd = drop_unconsumed_quantization_sidecars(sd)key_map: dict[str, str] = {}sd = _remap_qwen3vl_singlefile_keys(sd, key_map=key_map)- quantized = _resolve_quantized_module_paths(int8_markers, key_map)+ quantized = resolve_quantized_module_paths(int8_markers, key_map)te_config = self._load_hf_config()with accelerate.init_empty_weights():@@ -740,8 +661,8 @@ class Qwen3VLEncoderCheckpointLoader(ModelLoader):new_sd_size = sum(ten.nelement() * max(ten.element_size(), model_dtype.itemsize) for ten in sd.values())self._ram_cache.make_room(new_sd_size)- _cast_unquantized(sd, model_dtype, quantized)- _swap_in_int8_linears(model, sd, quantized)+ cast_unquantized(sd, model_dtype, quantized)+ swap_in_int8_linears(model, sd, quantized)model.load_state_dict(sd, assign=True, strict=False)_reject_incomplete_load(model, what="Qwen3-VL encoder checkpoint")diff --git a/invokeai/backend/model_manager/load/model_loaders/z_image.py b/invokeai/backend/model_manager/load/model_loaders/z_image.pyindex 0ca5dfb010..0164405e7e 100644--- a/invokeai/backend/model_manager/load/model_loaders/z_image.py+++ b/invokeai/backend/model_manager/load/model_loaders/z_image.py@@ -35,11 +35,39 @@ from invokeai.backend.model_manager.taxonomy import (SubModelType,)from invokeai.backend.quantization.gguf.loaders import gguf_sd_loader+from invokeai.backend.quantization.int8_convrot import (+ cast_unquantized,+ drop_unconsumed_quantization_sidecars,+ extract_int8_convrot_markers,+ swap_in_int8_linears,+)from invokeai.backend.quantization.sdnq.detection import is_sdnq_folderfrom invokeai.backend.quantization.sdnq.loaders import raise_on_incomplete_sdnq_load, sdnq_sd_loaderfrom invokeai.backend.qwen3.qwen3_tokenizer import load_bundled_qwen3_tokenizerfrom invokeai.backend.util.devices import TorchDevice+# Side-channel suffixes whose value is per output channel, and therefore splits with the weight.+# Everything else describes the layer as a whole -- a `comfy_quant` JSON blob most of all, whose+# byte length says nothing about how many outputs it covers.+_PER_ROW_SIDECHANNEL_SUFFIXES = ("weight_scale", "scale_weight")+++def _split_qkv_sidechannel(value: Any, suffix: str, target: str) -> Any:+ """One third of a fused-QKV side-channel tensor, or the whole thing when it is not per-row.++ A per-output-channel scale is ``[3 * dim, 1]`` and splits exactly like the weight it belongs+ to. A per-tensor scale, and any marker, is copied to all three unchanged. The decision is made+ from the suffix rather than the shape: a 72-byte JSON marker is also divisible by three.+ """+ if suffix not in _PER_ROW_SIDECHANNEL_SUFFIXES:+ return value+ shape = getattr(value, "shape", None)+ if shape is None or len(shape) == 0 or shape[0] <= 3 or shape[0] % 3 != 0:+ return value+ index = ("to_q", "to_k", "to_v").index(target)+ dim = shape[0] // 3+ return value[index * dim : (index + 1) * dim]+def _convert_z_image_gguf_to_diffusers(sd: dict[str, Any]) -> dict[str, Any]:"""Convert Z-Image GGUF state dict keys to diffusers format.@@ -97,10 +125,12 @@ def _convert_z_image_gguf_to_diffusers(sd: dict[str, Any]) -> dict[str, Any]:prefix = key.rsplit(".attention.qkv.", 1)[0]suffix = key.rsplit(".attention.qkv.", 1)[1] # "weight" or "bias"- # Skip non-weight/bias tensors (e.g., FP8 scale_weight tensors)- # These are quantization metadata and should not be split+ # Quantization side-channels have to follow their weight through the split, or they+ # are left behind under a module name that no longer exists -- and a loader then sees+ # a quantized weight with no scale, or a scale it cannot pair with anything.if suffix not in ("weight", "bias"):- new_sd[key] = value+ for target in ("to_q", "to_k", "to_v"):+ new_sd[f"{prefix}.attention.{target}.{suffix}"] = _split_qkv_sidechannel(value, suffix, target)continue# Split the fused QKV tensor into Q, K, V@@ -473,13 +503,25 @@ class ZImageCheckpointModel(ModelLoader):for k in keys_to_remove:del sd[k]- # Handle memory management and dtype conversion- new_sd_size = sum([ten.nelement() * model_dtype.itemsize for ten in sd.values()])+ # ComfyUI 'int8_tensorwise' checkpoints. The markers are read *after* the key conversion+ # above, which carries them (and their scales) through the fused-QKV split onto the module+ # names the model actually has -- so no re-keying is needed here.+ int8_markers = extract_int8_convrot_markers(sd)+ sd = drop_unconsumed_quantization_sidecars(sd)+ orphans = sorted(k for k, v in sd.items() if v.dtype is torch.int8 and k[: -len(".weight")] not in int8_markers)+ if orphans:+ raise ValueError(+ f"Z-Image checkpoint has {len(orphans)} int8 weight(s) with no `comfy_quant` marker, "+ f"e.g. {orphans[:3]}. Loading them would produce a model that runs and generates noise."+ )++ # int8 payloads are one byte, not two: reserving the compute dtype's width for them would+ # ask the cache to free memory this load never uses.+ new_sd_size = sum(ten.nelement() * max(ten.element_size(), model_dtype.itemsize) for ten in sd.values())self._ram_cache.make_room(new_sd_size)- # Convert to target dtype- for k in sd.keys():- sd[k] = sd[k].to(model_dtype)+ cast_unquantized(sd, model_dtype, int8_markers)+ swap_in_int8_linears(model, sd, int8_markers)model.load_state_dict(sd, assign=True)diff --git a/invokeai/backend/quantization/int8_convrot.py b/invokeai/backend/quantization/int8_convrot.pyindex 032e4c3f57..f891ef4b1f 100644--- a/invokeai/backend/quantization/int8_convrot.py+++ b/invokeai/backend/quantization/int8_convrot.py@@ -191,3 +191,83 @@ def check_int8_scale_layout(path: str, weight: torch.Tensor, scale: torch.Tensorf"'{path}' has a {tuple(scale.shape)} scale for a {tuple(weight.shape)} weight, which is ""neither per-output-channel nor per-tensor. Blockwise scale grids are not implemented.")+++def drop_unconsumed_quantization_sidecars(sd: dict[str, Any]) -> dict[str, Any]:+ """Remove quantization metadata no loader here consumes.++ - ``.comfy_quant`` markers whose format was handled elsewhere, or not at all.+ - ``.input_scale`` / ``.scale_input``: activation scales for W8A8 inference. This code+ dequantizes the weight and computes in bf16, so there is nothing to apply them to. (Both+ spellings appear in the wild; one Qwen3-VL repack ships 337 of the former.)++ `load_state_dict(strict=False)` would ignore them, but they are still cast and still counted+ against the RAM reservation - and a loader that later switches to strict would fail on them.+ """+ return {+ k: v+ for k, v in sd.items()+ if not (isinstance(k, str) and (k.endswith(".comfy_quant") or "input_scale" in k or "scale_input" in k))+ }+++def resolve_quantized_module_paths(+ markers: dict[str, dict[str, Any]], key_map: dict[str, str]+) -> dict[str, dict[str, Any]]:+ """Re-key markers from the checkpoint's names to the built model's names.++ The markers are read in the checkpoint's key space, because that is the only place where a+ marker and its weight are reliably paired: the key conversions rename `.weight` (and, by+ substring, `.weight_scale`) but leave `.comfy_quant` behind on the old name. Following the+ weight's own rename is therefore the only mapping that cannot drift from the conversion.+ """+ resolved: dict[str, dict[str, Any]] = {}+ for path, marker in markers.items():+ weight_key = key_map.get(f"{path}.weight", f"{path}.weight")+ resolved[weight_key[: -len(".weight")]] = marker+ return resolved+++def swap_in_int8_linears(model: torch.nn.Module, sd: dict[str, Any], quantized: dict[str, dict[str, Any]]) -> None:+ """Replace each quantized ``nn.Linear`` with an ``Int8ConvrotLinear`` sized from the state dict.++ The weights stay int8 and rotated as stored; the layer dequantizes and derotates per forward.+ That keeps a 12 GB checkpoint at 12 GB resident instead of the ~24 GB a dense decode would+ produce, on every platform and without the fp8-storage opt-in (which is off by default and+ unavailable outside CUDA/XPU).++ Its persistent buffers are named ``weight``/``weight_scale`` -- the checkpoint's own spelling --+ so the ``load_state_dict`` that follows assigns the quantized tensors straight into them.+ """+ for path, marker in quantized.items():+ weight, scale = sd.get(f"{path}.weight"), sd.get(f"{path}.weight_scale")+ if weight is None or scale is None:+ raise ValueError(+ f"'{path}' is marked int8_tensorwise but is missing its "+ f"{'weight' if weight is None else 'weight_scale'}."+ )+ check_int8_scale_layout(path, weight, scale)+ parent_path, _, attribute = path.rpartition(".")+ setattr(+ model.get_submodule(parent_path) if parent_path else model,+ attribute,+ Int8ConvrotLinear(+ weight=weight,+ weight_scale=scale,+ convrot=bool(marker.get("convrot", False)),+ bias=sd.get(f"{path}.bias"),+ group_size=int(marker.get("convrot_groupsize", CONVROT_GROUP_SIZE)),+ ),+ )+++def cast_unquantized(sd: dict[str, Any], dtype: torch.dtype, quantized: dict[str, dict[str, Any]]) -> None:+ """Cast the dense tensors to the compute dtype, leaving the quantized payloads alone.++ An int8 weight cast to bf16 is no longer int8, and its float32 scale is what+ ``Int8ConvrotLinear`` multiplies by -- both have to reach ``load_state_dict`` as stored.+ """+ pinned = {key for path in quantized for key in (f"{path}.weight", f"{path}.weight_scale")}+ for key in sd:+ if key not in pinned:+ sd[key] = sd[key].to(dtype)diff --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 8598d4e051..31cc6ff7bc 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@@ -19,18 +19,18 @@ from invokeai.backend.model_manager.load.model_loaders.krea2 import (_convert_krea2_native_to_diffusers,_dequantize_scaled_fp8,_drop_discarded_native_final_layers,- _drop_unconsumed_quantization_sidecars,_is_native_krea2_format,_normalize_qwen3vl_rope_config,_reject_incomplete_load,_remap_qwen3vl_singlefile_keys,- _resolve_quantized_module_paths,_strip_comfyui_prefix,)from invokeai.backend.quantization.int8_convrot import (CONVROT_GROUP_SIZE,build_regular_hadamard,+ drop_unconsumed_quantization_sidecars,extract_int8_convrot_markers,+ resolve_quantized_module_paths,)@@ -454,14 +454,14 @@ class TestInt8LayersSurviveTheLoaderPipeline:key_map: dict[str, str] = {}_convert_krea2_native_to_diffusers(sd, key_map=key_map)- assert _resolve_quantized_module_paths(markers, key_map) == {+ assert resolve_quantized_module_paths(markers, key_map) == {"transformer_blocks.0.attn.to_q": markers["blocks.0.attn.wq"]}def test_a_diffusers_named_checkpoint_needs_no_re_keying(self) -> None:"""No conversion runs, so the empty map has to resolve to the paths as they are."""markers = {"transformer_blocks.0.attn.to_q": {"format": "int8_tensorwise"}}- assert _resolve_quantized_module_paths(markers, {}) == markers+ assert resolve_quantized_module_paths(markers, {}) == markersclass TestUnconsumedQuantizationSidecars:@@ -475,11 +475,11 @@ class TestUnconsumedQuantizationSidecars:"layer.input_scale": torch.ones(1),"other.scale_input": torch.ones(1),}- assert set(_drop_unconsumed_quantization_sidecars(sd)) == {"layer.weight"}+ assert set(drop_unconsumed_quantization_sidecars(sd)) == {"layer.weight"}def test_a_clean_state_dict_is_unchanged(self) -> None:sd = {"layer.weight": torch.ones(2, 2), "layer.bias": torch.zeros(2)}- assert set(_drop_unconsumed_quantization_sidecars(sd)) == set(sd)+ assert set(drop_unconsumed_quantization_sidecars(sd)) == set(sd)class TestDiscardedFinalProjections: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.pynew file mode 100644index 0000000000..d111199bd1--- /dev/null+++ b/tests/backend/model_manager/load/test_z_image_loader_boundaries.py@@ -0,0 +1,125 @@+"""Loader-level tests for the Z-Image single-file path.++The state-dict helpers are covered elsewhere. What is pinned here is that the loader *calls*+them: deleting the swap would leave every unit test green while the loader produced a model that+loads cleanly and generates noise. These drive `_load_from_singlefile` itself and check what+reaches the module.+"""++import json+from types import SimpleNamespace+from unittest.mock import MagicMock++import pytest+import torch++from invokeai.backend.model_manager.configs.main import Main_Checkpoint_ZImage_Config+from invokeai.backend.model_manager.load.model_loaders.z_image import ZImageCheckpointModel+from invokeai.backend.quantization.int8_convrot import CONVROT_GROUP_SIZE, Int8ConvrotLinear, build_regular_hadamard++MARKER = {"format": "int8_tensorwise", "convrot": True, "convrot_groupsize": CONVROT_GROUP_SIZE}+++def _marker_blob(marker: dict) -> torch.Tensor:+ return torch.frombuffer(bytearray(json.dumps(marker).encode("utf-8")), dtype=torch.uint8)+++def _quantize_convrot(weight: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:+ """Mirror of comfy-quants: rotate along the input dim, then per-output-channel int8."""+ out_f, in_f = weight.shape+ h = build_regular_hadamard(CONVROT_GROUP_SIZE, dtype=weight.dtype)+ rotated = (weight.view(out_f, in_f // CONVROT_GROUP_SIZE, CONVROT_GROUP_SIZE) @ h.T).view(out_f, in_f)+ scale = rotated.abs().amax(dim=1, keepdim=True) / 127.0+ return torch.clamp(torch.round(rotated / scale), -128, 127).to(torch.int8), scale.to(torch.float32)+++class _TinyBlock(torch.nn.Module):+ def __init__(self) -> None:+ super().__init__()+ self.proj = torch.nn.Linear(CONVROT_GROUP_SIZE, 4, bias=False)+++class _TinyZImage(torch.nn.Module):+ """Stands in for ZImageTransformer2DModel. `layers.` is one of the loader's valid prefixes,+ so the state dict survives its filter."""++ def __init__(self, **_kwargs) -> None:+ super().__init__()+ self.layers = torch.nn.ModuleList([_TinyBlock()])+++def _driver(monkeypatch, tmp_path, state_dict: dict) -> tuple[ZImageCheckpointModel, Main_Checkpoint_ZImage_Config]:+ import diffusers+ from safetensors import torch as safetensors_torch++ checkpoint = tmp_path / "z_image_int8_convrot.safetensors"+ checkpoint.touch()+ config = Main_Checkpoint_ZImage_Config.model_construct(path=str(checkpoint), name="z-image")++ loader = object.__new__(ZImageCheckpointModel)+ loader._ram_cache = SimpleNamespace(make_room=MagicMock())+ loader._logger = MagicMock()+ loader._torch_device = torch.device("cpu")+ loader._torch_dtype = torch.float32+ loader._apply_fp8_layerwise_casting = lambda model, _config, _submodel: model++ monkeypatch.setattr(diffusers, "ZImageTransformer2DModel", _TinyZImage, raising=False)+ monkeypatch.setattr(safetensors_torch, "load_file", lambda _path: state_dict)+ monkeypatch.setattr(+ "invokeai.backend.model_manager.load.model_loaders.z_image.TorchDevice.choose_torch_device",+ lambda: torch.device("cpu"),+ )+ monkeypatch.setattr(+ "invokeai.backend.model_manager.load.model_loaders.z_image.TorchDevice.choose_bfloat16_safe_dtype",+ lambda _device: torch.float32,+ )+ return loader, config+++def test_an_int8_checkpoint_loads_int8_resident_and_un_rotated(monkeypatch, tmp_path) -> None:+ torch.manual_seed(0)+ original = torch.randn(4, CONVROT_GROUP_SIZE)+ quantized, scale = _quantize_convrot(original)+ state_dict = {+ "layers.0.proj.weight": quantized,+ "layers.0.proj.weight_scale": scale,+ "layers.0.proj.comfy_quant": _marker_blob(MARKER),+ }+ loader, config = _driver(monkeypatch, tmp_path, state_dict)++ model = loader._load_from_singlefile(config)++ # Resident, not decoded: that is what keeps a 5.8 GB checkpoint at 5.8 GB.+ assert isinstance(model.layers[0].proj, Int8ConvrotLinear)+ assert model.layers[0].proj.weight.dtype is torch.int8++ dequantized = model.layers[0].proj._dequantized_weight(torch.device("cpu"), torch.float32).flatten()+ assert torch.corrcoef(torch.stack([dequantized, original.flatten()]))[0, 1] > 0.999+ # And specifically not the scaled-but-still-rotated weight, which is what a loader that only+ # applied the scale would produce -- silently.+ rotated = (quantized.float() * scale).flatten()+ assert torch.corrcoef(torch.stack([rotated, original.flatten()]))[0, 1].abs() < 0.2+++def test_an_int8_weight_without_a_marker_is_refused(monkeypatch, tmp_path) -> None:+ """A quantized weight the loader does not recognise would be handed to a float Linear and only+ fail at forward time, if at all. Refuse at load, and say which layers."""+ torch.manual_seed(1)+ quantized, scale = _quantize_convrot(torch.randn(4, CONVROT_GROUP_SIZE))+ state_dict = {"layers.0.proj.weight": quantized, "layers.0.proj.weight_scale": scale}+ loader, config = _driver(monkeypatch, tmp_path, state_dict)++ with pytest.raises(ValueError, match=r"int8 weight\(s\) with no `comfy_quant` marker"):+ loader._load_from_singlefile(config)+++def test_an_unquantized_checkpoint_is_unaffected(monkeypatch, tmp_path) -> None:+ torch.manual_seed(2)+ weight = torch.randn(4, CONVROT_GROUP_SIZE)+ loader, config = _driver(monkeypatch, tmp_path, {"layers.0.proj.weight": weight})++ model = loader._load_from_singlefile(config)++ assert isinstance(model.layers[0].proj, torch.nn.Linear)+ assert not isinstance(model.layers[0].proj, Int8ConvrotLinear)+ assert torch.equal(model.layers[0].proj.weight, weight)diff --git a/tests/backend/model_manager/load/test_z_image_state_dict_utils.py b/tests/backend/model_manager/load/test_z_image_state_dict_utils.pyindex 37e113d857..242ba397b9 100644--- a/tests/backend/model_manager/load/test_z_image_state_dict_utils.py+++ b/tests/backend/model_manager/load/test_z_image_state_dict_utils.py@@ -1,8 +1,15 @@"""Unit tests for the Z-Image GGUF/ComfyUI -> diffusers state-dict converter."""+import json++import pytestimport torch-from invokeai.backend.model_manager.load.model_loaders.z_image import _convert_z_image_gguf_to_diffusers+from invokeai.backend.model_manager.load.model_loaders.z_image import (+ _convert_z_image_gguf_to_diffusers,+ _split_qkv_sidechannel,+)+from invokeai.backend.quantization.int8_convrot import extract_int8_convrot_markersfrom tests.backend.model_manager.load.state_dicts.utils import keys_to_mock_state_dictfrom tests.backend.model_manager.load.state_dicts.z_image_transformer_comfyui_keys import (state_dict_keys as z_image_keys,@@ -64,3 +71,72 @@ class TestConvertZImageGgufToDiffusers:assert torch.allclose(out["blk.attention.to_q.weight"], qkv[0:2])assert torch.allclose(out["blk.attention.to_k.weight"], qkv[2:4])assert torch.allclose(out["blk.attention.to_v.weight"], qkv[4:6])+++def _marker_blob(marker: dict) -> torch.Tensor:+ return torch.frombuffer(bytearray(json.dumps(marker).encode("utf-8")), dtype=torch.uint8)+++MARKER = {"format": "int8_tensorwise", "convrot": True, "convrot_groupsize": 256}+++class TestTheFusedQkvSplitCarriesQuantizationMetadata:+ """A quantized fused QKV travels as three keys, and all three have to reach the same three+ modules. The weight already split; the scale and the marker did not, and were left behind+ under a module name the model does not have."""++ def test_a_per_output_channel_scale_splits_with_its_weight(self) -> None:+ scale = torch.arange(3 * 4, dtype=torch.float32).reshape(3 * 4, 1)+ pieces = [_split_qkv_sidechannel(scale, "weight_scale", t) for t in ("to_q", "to_k", "to_v")]+ assert [tuple(p.shape) for p in pieces] == [(4, 1)] * 3+ assert torch.equal(torch.cat(pieces), scale)++ def test_a_marker_is_copied_whole_to_all_three(self) -> None:+ """The regression that motivated the suffix check: a 72-byte JSON blob is divisible by+ three, so a rule based on the tensor's shape cuts it into three fragments of broken JSON."""+ blob = _marker_blob(MARKER)+ assert len(blob) % 3 == 0, "the fixture has to reproduce the divisible-by-three trap"+ for target in ("to_q", "to_k", "to_v"):+ piece = _split_qkv_sidechannel(blob, "comfy_quant", target)+ assert torch.equal(piece, blob)+ assert json.loads(bytes(piece.numpy().tobytes()).decode()) == MARKER++ def test_a_per_tensor_scale_is_copied_rather_than_split(self) -> None:+ for scale in (torch.tensor(0.5), torch.tensor([0.5])):+ assert torch.equal(_split_qkv_sidechannel(scale, "weight_scale", "to_k"), scale)++ def test_weight_scale_and_marker_land_on_the_same_three_modules(self) -> None:+ prefix = "layers.0.attention"+ sd = {+ f"{prefix}.qkv.weight": torch.arange(3 * 4 * 8, dtype=torch.int8).reshape(3 * 4, 8),+ f"{prefix}.qkv.weight_scale": torch.arange(3 * 4, dtype=torch.float32).reshape(3 * 4, 1),+ f"{prefix}.qkv.comfy_quant": _marker_blob(MARKER),+ # `x_embedder.` is what makes the loader run this conversion at all.+ "x_embedder.weight": torch.zeros(2, 2),+ }+ out = _convert_z_image_gguf_to_diffusers(sd)++ for target in ("to_q", "to_k", "to_v"):+ assert f"{prefix}.{target}.weight" in out+ assert f"{prefix}.{target}.weight_scale" in out+ assert f"{prefix}.{target}.comfy_quant" in out+ assert not any(".qkv." in k for k in out), "the fused keys must not survive"++ def test_the_markers_are_readable_after_the_conversion(self) -> None:+ """Why Z-Image reads them after converting rather than before: unlike Krea-2's converter,+ this one carries `.comfy_quant` onto the final module names, so no re-keying is needed."""+ prefix = "layers.0.attention"+ sd = {+ f"{prefix}.qkv.weight": torch.zeros(3 * 4, 256, dtype=torch.int8),+ f"{prefix}.qkv.weight_scale": torch.ones(3 * 4, 1),+ f"{prefix}.qkv.comfy_quant": _marker_blob(MARKER),+ "x_embedder.weight": torch.zeros(2, 2),+ }+ markers = extract_int8_convrot_markers(_convert_z_image_gguf_to_diffusers(sd))+ assert set(markers) == {f"{prefix}.to_q", f"{prefix}.to_k", f"{prefix}.to_v"}+ assert all(m == MARKER for m in markers.values())++ def test_a_qkv_weight_that_does_not_divide_by_three_is_refused(self) -> None:+ sd = {"layers.0.attention.qkv.weight": torch.zeros(7, 8), "x_embedder.weight": torch.zeros(2, 2)}+ with pytest.raises(ValueError, match="not divisible by 3"):+ _convert_z_image_gguf_to_diffusers(sd)