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(quantization): stop over-reserving RAM, and guard Krea-2's int8 paths
Alexander Eichhorn0a27307e2f77
diff --git a/invokeai/backend/model_manager/load/model_loaders/krea2.py b/invokeai/backend/model_manager/load/model_loaders/krea2.pyindex 0c619923da..7a54b366e5 100644--- a/invokeai/backend/model_manager/load/model_loaders/krea2.py+++ b/invokeai/backend/model_manager/load/model_loaders/krea2.py@@ -51,6 +51,7 @@ from invokeai.backend.quantization.int8_convrot import (cast_unquantized,drop_unconsumed_quantization_sidecars,extract_int8_convrot_markers,+ reject_unmarked_int8_weights,resolve_quantized_module_paths,swap_in_int8_linears,)@@ -357,9 +358,10 @@ class Krea2CheckpointModel(ModelLoader):and native/ComfyUI key naming. Apply the fp8-storage setting to keep the (large) transformerfp8-resident; otherwise it loads in full precision.- The int8 build is decoded to dense weights rather than kept int8-resident: on this model that- costs nothing, because fp8 storage and int8 storage measure the same 12.0 GiB, and the reason to- keep int8 resident is int8 *compute*, which needs a kernel InvokeAI does not have yet.+ The int8 build stays int8-resident: `swap_in_int8_linears` installs `Int8ConvrotLinear`, which+ holds the stored codes and dequantizes per forward, so a 12.0 GiB checkpoint stays 12.0 GiB.+ What it does not get is int8 *compute* -- that needs a kernel InvokeAI does not have yet -- so+ the saving here is resident memory, not speed."""def _load_model(@@ -404,6 +406,11 @@ class Krea2CheckpointModel(ModelLoader):# noise.int8_markers = extract_int8_convrot_markers(sd)+ # Outside the branch on purpose -- see the helper, which explains why. Z-Image has always+ # had this; Krea-2 did not, so an int8 weight whose marker was missing or unparseable was+ # cast to the compute dtype as raw codes and loaded silently.+ reject_unmarked_int8_weights(sd, int8_markers, "Krea-2")+if int8_markers:sd = drop_unconsumed_quantization_sidecars(sd)# Native/ComfyUI key naming → diffusers Krea2Transformer2DModel keys.@@ -458,7 +465,10 @@ class Krea2CheckpointModel(ModelLoader):if int8_markers:# int8 payloads are one byte, not two: reserving the compute dtype's width for them# would 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())+ # `max(element_size, itemsize)` would charge the compute dtype's width for the int8+ # payloads -- `max(1, 2)` is 2 -- which is the doubling this comment exists to avoid.+ # `predict_cast_state_dict_size` charges each tensor what it will actually occupy.+ new_sd_size = predict_cast_state_dict_size(sd, model_dtype, keep_fp8=False)self._ram_cache.make_room(new_sd_size)cast_unquantized(sd, model_dtype, quantized)swap_in_int8_linears(model, sd, quantized)@@ -779,6 +789,11 @@ class Qwen3VLEncoderCheckpointLoader(ModelLoader):# fp8.int8_markers = extract_int8_convrot_markers(sd)+ # Outside the branch on purpose -- see the helper, which explains why. Z-Image has always+ # had this; Krea-2 did not, so an int8 weight whose marker was missing or unparseable was+ # cast to the compute dtype as raw codes and loaded silently.+ reject_unmarked_int8_weights(sd, int8_markers, "Krea-2")+if int8_markers:sd = drop_unconsumed_quantization_sidecars(sd)key_map: dict[str, str] = {}@@ -826,7 +841,10 @@ class Qwen3VLEncoderCheckpointLoader(ModelLoader):if int8_markers:# int8 payloads are one byte, not two.- new_sd_size = sum(ten.nelement() * max(ten.element_size(), model_dtype.itemsize) for ten in sd.values())+ # `max(element_size, itemsize)` would charge the compute dtype's width for the int8+ # payloads -- `max(1, 2)` is 2 -- which is the doubling this comment exists to avoid.+ # `predict_cast_state_dict_size` charges each tensor what it will actually occupy.+ new_sd_size = predict_cast_state_dict_size(sd, model_dtype, keep_fp8=False)self._ram_cache.make_room(new_sd_size)cast_unquantized(sd, model_dtype, quantized)swap_in_int8_linears(model, sd, quantized)diff --git a/invokeai/backend/model_manager/load/model_loaders/z_image.py b/invokeai/backend/model_manager/load/model_loaders/z_image.pyindex 706f0abb98..9ee8ec6ede 100644--- a/invokeai/backend/model_manager/load/model_loaders/z_image.py+++ b/invokeai/backend/model_manager/load/model_loaders/z_image.py@@ -63,6 +63,7 @@ from invokeai.backend.quantization.int8_convrot import (cast_unquantized,drop_unconsumed_quantization_sidecars,extract_int8_convrot_markers,+ reject_unmarked_int8_weights,swap_in_int8_linears,)from invokeai.backend.quantization.sdnq.detection import is_sdnq_folder@@ -551,16 +552,8 @@ class ZImageCheckpointModel(ModelLoader):# other's tensors.int8_markers = extract_int8_convrot_markers(sd)- # Outside the branch on purpose: an int8 weight whose marker is missing leaves `int8_markers`- # empty, so a check living inside the int8 path would never see the very case it exists for.- # Such a weight would take the fp8 path, be treated as an ordinary tensor and load into a- # model that runs and generates noise.- 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."- )+ # Outside the branch on purpose -- see the helper, which explains why.+ reject_unmarked_int8_weights(sd, int8_markers, "Z-Image")if int8_markers:# Markers are read *after* the key conversion above, which carries them (and their@@ -578,7 +571,10 @@ class ZImageCheckpointModel(ModelLoader):# 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())+ # `max(element_size, itemsize)` would charge the compute dtype's width for the int8+ # payloads -- `max(1, 2)` is 2 -- which is the doubling this comment exists to avoid.+ # `predict_cast_state_dict_size` charges each tensor what it will actually occupy.+ new_sd_size = predict_cast_state_dict_size(sd, model_dtype, keep_fp8=False)self._ram_cache.make_room(new_sd_size)cast_unquantized(sd, model_dtype, int8_markers)diff --git a/invokeai/backend/quantization/int8_convrot.py b/invokeai/backend/quantization/int8_convrot.pyindex d288ca7303..cbbfc579f8 100644--- a/invokeai/backend/quantization/int8_convrot.py+++ b/invokeai/backend/quantization/int8_convrot.py@@ -33,6 +33,7 @@ largest layer) has to fit inside the calling node's working-memory reservation."""import json+from collections.abc import Mappingfrom typing import Anyimport torch@@ -227,6 +228,27 @@ def check_int8_scale_layout(path: str, weight: torch.Tensor, scale: torch.Tensor)+def reject_unmarked_int8_weights(sd: dict[str, Any], markers: Mapping[str, Any], architecture: str) -> None:+ """Refuse a checkpoint holding an int8 weight that no ``int8_tensorwise`` marker claims.++ Call this *outside* the "did we find markers" branch. An int8 weight whose marker is missing --+ or, since :func:`parse_comfy_quant_marker` is tolerant, one whose marker did not parse -- leaves+ `markers` without an entry for it, so a check living inside the int8 path would never see the+ very case it exists for. Such a weight then takes the unquantized path: cast to the compute+ dtype as raw int8 codes, unscaled and un-derotated, into a model that loads clean and generates+ noise.++ That tolerance is deliberate and this is its other half: a malformed marker is a lost hint, and+ this is what stops the loss from being silent.+ """+ orphans = sorted(k for k, v in sd.items() if v.dtype is torch.int8 and k[: -len(".weight")] not in markers)+ if orphans:+ raise ValueError(+ f"{architecture} 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."+ )++def requires_sidecar_patching(transformer: Any, model_format: ModelFormat) -> bool:"""Whether LoRA has to be applied as a sidecar rather than written into the weights.diff --git a/tests/backend/model_manager/load/test_krea2_loader_boundaries.py b/tests/backend/model_manager/load/test_krea2_loader_boundaries.pyindex fee0590d92..87326010ae 100644--- a/tests/backend/model_manager/load/test_krea2_loader_boundaries.py+++ b/tests/backend/model_manager/load/test_krea2_loader_boundaries.py@@ -1,6 +1,7 @@from types import SimpleNamespacefrom unittest.mock import MagicMock+import pytestimport torchfrom invokeai.backend.model_manager.configs.main import (@@ -20,6 +21,7 @@ from invokeai.backend.model_manager.load.model_loaders.krea2 import (Qwen3VLEncoderLoader,)from invokeai.backend.model_manager.taxonomy import Krea2VariantType, SubModelType+from invokeai.backend.quantization.fp8_scaled import predict_cast_state_dict_sizefrom invokeai.backend.quantization.int8_convrot import Int8ConvrotLinear@@ -121,6 +123,12 @@ def test_single_file_loader_decodes_an_int8_convrot_checkpoint(monkeypatch, tmp_model = loader._load_from_singlefile(config)+ # The reservation must be what the load actually occupies. `max(element_size, itemsize)` charged+ # the compute dtype's width for the int8 payloads -- `max(1, 2)` is 2 -- so every int8 load asked+ # the cache to free twice what it needed, evicting other models for room nobody used.+ (reserved,), _ = loader._ram_cache.make_room.call_args+ assert reserved == predict_cast_state_dict_size(state_dict, torch.float32, keep_fp8=False)+# This is also what pins the one-or-the-other split in the loader: the fixture's int8 weight# carries a `.weight_scale`, which is exactly what an fp8 scaled layer looks like from outside.# Route it down the fp8 path and it is scaled but never un-rotated -- `load_state_dict` then@@ -318,3 +326,56 @@ def test_directory_encoder_loader_estimates_standalone_root_weights(tmp_path) ->estimated_size = loader.get_size_fs(config, tmp_path, SubModelType.TextEncoder)assert estimated_size == weight_size+++def test_an_int8_weight_without_a_marker_is_refused(monkeypatch, tmp_path) -> None:+ """A weight the markers do not claim would be cast to the compute dtype as raw int8 codes.++ Unscaled and un-derotated, into a model that loads clean and generates noise. Z-Image has always+ refused this; Krea-2 accepted it silently, and `parse_comfy_quant_marker` being tolerant makes+ the case reachable through a marker that merely fails to parse.+ """+ import json++ import diffusers+ import safetensors.torch++ class _TinyInt8Krea2Transformer(torch.nn.Module):+ def __init__(self, **_kwargs) -> None:+ super().__init__()+ self.marked = torch.nn.Linear(8, 8, bias=False)+ self.unmarked = torch.nn.Linear(8, 8, bias=False)++ marker = json.dumps({"format": "int8_tensorwise", "convrot": False})+ state_dict = {+ "marked.weight": torch.zeros(8, 8, dtype=torch.int8),+ "marked.weight_scale": torch.ones(8, 1, dtype=torch.float32),+ "marked.comfy_quant": torch.frombuffer(bytearray(marker.encode("utf-8")), dtype=torch.uint8),+ # No marker at all: the orphan.+ "unmarked.weight": torch.zeros(8, 8, dtype=torch.int8),+ }++ checkpoint_path = tmp_path / "krea2_int8_convrot.safetensors"+ checkpoint_path.touch()+ config = Main_Checkpoint_Krea2_Config.model_construct(+ path=str(checkpoint_path), variant=Krea2VariantType.Turbo, fp8_storage=None+ )+ loader = object.__new__(Krea2CheckpointModel)+ loader._ram_cache = SimpleNamespace(make_room=MagicMock())+ loader._logger = MagicMock()++ monkeypatch.setattr(diffusers, "Krea2Transformer2DModel", _TinyInt8Krea2Transformer, raising=False)+ monkeypatch.setattr(safetensors.torch, "load_file", lambda _path: state_dict)+ monkeypatch.setattr(+ "invokeai.backend.model_manager.load.model_loaders.krea2.TorchDevice.choose_torch_device",+ lambda: torch.device("cpu"),+ )+ monkeypatch.setattr(+ "invokeai.backend.model_manager.load.model_loaders.krea2.TorchDevice.choose_bfloat16_safe_dtype",+ lambda _device: torch.float32,+ )++ with pytest.raises(ValueError) as excinfo:+ loader._load_from_singlefile(config)++ assert "unmarked.weight" in str(excinfo.value)