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): close the three verified blockers in the int8 path
Alexander Eichhorn4375d715ec97
diff --git a/invokeai/app/invocations/krea2_denoise.py b/invokeai/app/invocations/krea2_denoise.pyindex 70e74d668d..64a9f354d0 100644--- a/invokeai/app/invocations/krea2_denoise.py+++ b/invokeai/app/invocations/krea2_denoise.py@@ -2,7 +2,7 @@ import jsonimport mathfrom contextlib import ExitStackfrom pathlib import Path-from typing import Any, Callable, Iterator, Optional+from typing import Callable, Iterator, Optionalimport torchimport torchvision.transforms as tv_transforms@@ -46,7 +46,7 @@ from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelFormatfrom invokeai.backend.patches.layer_patcher import LayerPatcher, PatchSpecfrom invokeai.backend.patches.lora_conversions.krea2_lora_constants import KREA2_LORA_TRANSFORMER_PREFIXfrom invokeai.backend.patches.model_patch_raw import ModelPatchRaw-from invokeai.backend.quantization.int8_convrot import Int8ConvrotLinear+from invokeai.backend.quantization.int8_convrot import requires_sidecar_patchingfrom invokeai.backend.rectified_flow.rectified_flow_inpaint_extension import RectifiedFlowInpaintExtensionfrom invokeai.backend.stable_diffusion.diffusers_pipeline import PipelineIntermediateStatefrom invokeai.backend.stable_diffusion.diffusion.conditioning_data import Krea2ConditioningInfo@@ -56,20 +56,6 @@ from invokeai.backend.util.devices import TorchDeviceKREA2_LATENT_CHANNELS = 16-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.-- The format alone does not answer this. A plain ``checkpoint`` Krea-2 may still be an- ``int8_tensorwise`` build, whose Linears the loader replaced with ``Int8ConvrotLinear`` --- those hold their weights as int8 buffers, which a direct patch cannot write into (and which- could not represent the patched values anyway, the rotation having mixed 256 of them). So the- loaded module tree is consulted, not just the config.- """- if model_format in (ModelFormat.GGUFQuantized,):- return True- return any(isinstance(module, Int8ConvrotLinear) for module in transformer.modules())--@invocation("krea2_denoise",title="Denoise - Krea-2",diff --git a/invokeai/app/invocations/z_image_denoise.py b/invokeai/app/invocations/z_image_denoise.pyindex 09af26bde9..edd3174b2e 100644--- a/invokeai/app/invocations/z_image_denoise.py+++ b/invokeai/app/invocations/z_image_denoise.py@@ -32,6 +32,7 @@ from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelFormatfrom invokeai.backend.patches.layer_patcher import LayerPatcher, PatchSpecfrom invokeai.backend.patches.lora_conversions.z_image_lora_constants import Z_IMAGE_LORA_TRANSFORMER_PREFIXfrom invokeai.backend.patches.model_patch_raw import ModelPatchRaw+from invokeai.backend.quantization.int8_convrot import requires_sidecar_patchingfrom invokeai.backend.rectified_flow.rectified_flow_inpaint_extension import RectifiedFlowInpaintExtensionfrom invokeai.backend.stable_diffusion.diffusers_pipeline import PipelineIntermediateStatefrom invokeai.backend.stable_diffusion.diffusion.conditioning_data import ZImageConditioningInfo@@ -434,19 +435,24 @@ class ZImageDenoiseInvocation(BaseInvocation):# Get transformer config to determine if it's quantizedtransformer_config = context.models.get_config(self.transformer.transformer)- # Determine if the model is quantized.- # If the model is quantized, then we need to apply the LoRA weights as sidecar layers. This results in- # slower inference than direct patching, but is agnostic to the quantization format.- if transformer_config.format in [ModelFormat.Diffusers, ModelFormat.Checkpoint]:- model_is_quantized = False- elif transformer_config.format in [ModelFormat.GGUFQuantized, ModelFormat.SDNQQuantized]:- model_is_quantized = True- else:+ if transformer_config.format not in (+ ModelFormat.Diffusers,+ ModelFormat.Checkpoint,+ ModelFormat.GGUFQuantized,+ ModelFormat.SDNQQuantized,+ ):raise ValueError(f"Unsupported Z-Image model format: {transformer_config.format}")# Load transformer - always use base transformer, control is handled via extension(cached_weights, transformer) = exit_stack.enter_context(transformer_info.model_on_device())+ # Whether LoRA has to go on as a sidecar. Asked of the loaded module tree, not the+ # format: a `checkpoint` Z-Image may be an int8_tensorwise build, whose Linears are+ # Int8ConvrotLinear. Those carry their weights as buffers rather than parameters, so+ # the fallbacks inside the patcher -- which iterate `module.parameters()` -- find+ # nothing and choose direct patching on a module that has no patchable weights.+ model_is_quantized = requires_sidecar_patching(transformer, transformer_config.format)+# Prepare control extension if control is providedcontrol_extension: ZImageControlNetExtension | None = Nonediff --git a/invokeai/backend/quantization/int8_convrot.py b/invokeai/backend/quantization/int8_convrot.pyindex f891ef4b1f..d288ca7303 100644--- a/invokeai/backend/quantization/int8_convrot.py+++ b/invokeai/backend/quantization/int8_convrot.py@@ -38,6 +38,8 @@ from typing import Anyimport torchimport torch.nn.functional as F+from invokeai.backend.model_manager.taxonomy import ModelFormat+CONVROT_GROUP_SIZE = 256_HADAMARD_SEED = ((1, 1, 1, -1), (1, 1, -1, 1), (1, -1, 1, 1), (-1, 1, 1, 1))@@ -57,8 +59,39 @@ def build_regular_hadamard(size: int, dtype: torch.dtype = torch.float32) -> tordef parse_comfy_quant_marker(blob: torch.Tensor) -> dict:- """Decode a ``<layer>.comfy_quant`` uint8 tensor into its JSON dict."""- return json.loads(bytes(blob.cpu().numpy().tobytes()).decode("utf-8"))+ """Decode a ``<layer>.comfy_quant`` uint8 tensor into its JSON dict, or ``{}``.++ Tolerant on purpose, and it has to be: this runs over *every* marker in the file before the+ loader knows which format it is dealing with, so a blob belonging to some other scheme decides+ whether an fp8 checkpoint loads at all. Comfy pads these to a fixed width with NUL bytes -- the+ fp8 reader documents that and strips it -- and a strict parse turns a padded marker into+ `JSONDecodeError: Extra data` out of the middle of a load, naming neither the file nor the key.++ A malformed marker is a lost hint, never a failed load: an int8 weight whose marker did not+ parse is then caught by the orphan check in the loaders, which says what is wrong.+ """+ try:+ text = bytes(blob.cpu().numpy().tobytes()).decode("utf-8", errors="replace").rstrip("\x00")+ parsed = json.loads(text)+ except Exception:+ return {}+ return parsed if isinstance(parsed, dict) else {}+++def as_column_scale(weight: torch.Tensor, scale: torch.Tensor) -> torch.Tensor:+ """A per-output-channel scale shaped `[out, 1]`, so it multiplies down the rows.++ `check_int8_scale_layout` accepts `[out]` as well as `[out, 1]`, but broadcasting aligns+ *trailing* dimensions: `weight[out, in] * scale[out]` scales along the input axis instead. For a+ square weight that is silent -- measured at 0.82 correlation against the intended result, so the+ model loads and generates subtly wrong images -- and for every other shape it raises with a size+ mismatch that names neither the layer nor the cause.++ A scalar, `[1]` or `[1, 1]` is per-tensor and broadcasts correctly as it is.+ """+ if scale.dim() == 1 and scale.shape[0] == weight.shape[0]:+ return scale.unsqueeze(1)+ return scaledef dequantize_convrot_weight(@@ -69,7 +102,7 @@ def dequantize_convrot_weight(group_size: int = CONVROT_GROUP_SIZE,) -> torch.Tensor:"""Recover the bf16/fp16 weight from int8 storage (and undo convrot if applied)."""- w = weight_q.to(torch.float32) * weight_scale.to(torch.float32)+ w = weight_q.to(torch.float32) * as_column_scale(weight_q, weight_scale).to(torch.float32)if convrot:out_features, in_features = w.shapeif in_features % group_size != 0:@@ -134,7 +167,8 @@ class Int8ConvrotLinear(torch.nn.Module):# per-call transient at ~two weight-sized tensors (~620 MB peak for the fused-SwiGLU# fc1 in bf16) instead of tripling through an fp32 intermediate (~1.5 GiB). An fp32# compute dtype still gets the exact fp32 path for free.- w = self.weight.to(device=device, dtype=dtype) * self.weight_scale.to(device=device, dtype=dtype)+ scale = as_column_scale(self.weight, self.weight_scale).to(device=device, dtype=dtype)+ w = self.weight.to(device=device, dtype=dtype) * scaleif self.convrot:assert self.hadamard is not Nonew = (@@ -193,6 +227,25 @@ def check_int8_scale_layout(path: str, weight: torch.Tensor, scale: torch.Tensor)+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.++ The format alone does not answer this. A plain ``checkpoint`` may still be an+ ``int8_tensorwise`` build, whose Linears the loader replaced with :class:`Int8ConvrotLinear` --+ those hold their weights as int8 *buffers*, which a direct patch cannot write into (and which+ could not represent the patched values anyway, the rotation having mixed 256 of them). Worse,+ the fallbacks that would otherwise catch this iterate ``module.parameters()``, and these modules+ have none, so they answer "not quantized" and direct patching is chosen. So the loaded module+ tree is consulted, not just the config.++ Lives here rather than beside one denoise node because every architecture this scheme reaches+ needs the same answer, and getting it from the config alone is wrong in the same way for each.+ """+ if model_format in (ModelFormat.GGUFQuantized, ModelFormat.SDNQQuantized):+ return True+ return any(isinstance(module, Int8ConvrotLinear) for module in transformer.modules())++def drop_unconsumed_quantization_sidecars(sd: dict[str, Any]) -> dict[str, Any]:"""Remove quantization metadata no loader here consumes.diff --git a/tests/backend/quantization/test_int8_convrot.py b/tests/backend/quantization/test_int8_convrot.pyindex e4b0b890e6..290d7e9c5c 100644--- a/tests/backend/quantization/test_int8_convrot.py+++ b/tests/backend/quantization/test_int8_convrot.py@@ -11,12 +11,15 @@ import sysimport pytestimport torch+from invokeai.backend.model_manager.taxonomy import ModelFormatfrom invokeai.backend.quantization.int8_convrot import (CONVROT_GROUP_SIZE,Int8ConvrotLinear,build_regular_hadamard,dequantize_convrot_weight,+ extract_int8_convrot_markers,parse_comfy_quant_marker,+ requires_sidecar_patching,)@@ -126,3 +129,106 @@ def test_int8_convrot_linear_bf16_path_tracks_fp32_reference() -> None:got = lin(x.to(torch.bfloat16)).to(torch.float32)rel_err = (got - ref).abs().max() / ref.abs().max()assert rel_err < 0.02, f"bf16 dequant path diverges from fp32 reference: rel_err={rel_err:.4f}"+++class TestThePerOutputChannelScaleLayout:+ """`check_int8_scale_layout` accepts `[out]` as well as `[out, 1]`, so both have to decode the+ same. Broadcasting aligns trailing dimensions, so `weight[out, in] * scale[out]` scales along+ the *input* axis: silently wrong for a square weight -- 0.82 correlation against the intended+ result, a model that loads and generates -- and a bare size mismatch for anything else."""++ @pytest.mark.parametrize(("out_features", "in_features"), [(16, 16), (32, 16), (16, 32)])+ def test_a_one_dimensional_scale_decodes_like_a_column_one(self, out_features, in_features):+ torch.manual_seed(0)+ weight = torch.randint(-127, 127, (out_features, in_features), dtype=torch.int8)+ flat = torch.rand(out_features) * 0.01 + 0.001++ from_flat = dequantize_convrot_weight(weight, flat, convrot=False, dtype=torch.float32)+ from_column = dequantize_convrot_weight(weight, flat.reshape(-1, 1), convrot=False, dtype=torch.float32)++ assert torch.equal(from_flat, from_column)++ def test_a_per_tensor_scale_is_left_alone(self):+ weight = torch.ones(8, 4, dtype=torch.int8)+ scalar = torch.tensor(0.5)++ decoded = dequantize_convrot_weight(weight, scalar, convrot=False, dtype=torch.float32)++ assert torch.allclose(decoded, torch.full((8, 4), 0.5))++ def test_the_module_decodes_a_one_dimensional_scale_the_same_way(self):+ torch.manual_seed(0)+ weight = torch.randint(-127, 127, (16, 16), dtype=torch.int8)+ flat = torch.rand(16) * 0.01 + 0.001++ flat_module = Int8ConvrotLinear(weight, flat, convrot=False)+ column_module = Int8ConvrotLinear(weight, flat.reshape(-1, 1), convrot=False)+ probe = torch.randn(3, 16)++ assert torch.allclose(flat_module(probe), column_module(probe))+++class TestAMalformedMarkerIsALostHintNotAFailedLoad:+ """This runs over every marker in the file before the loader knows which format it is reading,+ so a blob belonging to some other scheme decides whether an fp8 checkpoint loads at all. Comfy+ pads these to a fixed width with NUL bytes -- documented and stripped by the fp8 reader -- and a+ strict parse turned that into a JSONDecodeError out of the middle of a load."""++ @staticmethod+ def _blob(raw: bytes) -> torch.Tensor:+ # `frombuffer` rejects a zero-length buffer, and an empty marker is a case worth covering.+ if not raw:+ return torch.empty(0, dtype=torch.uint8)+ return torch.frombuffer(bytearray(raw), dtype=torch.uint8).clone()++ @pytest.mark.parametrize(+ ("label", "raw"),+ [+ ("nul padded", b'{"format":"float8_e4m3fn"}' + bytes([0]) * 8),+ ("invalid utf-8", b'{"format":"' + bytes([0xFF, 0xFE]) + b'"}'),+ ("not an object", b"[1, 2, 3]"),+ ("empty", b""),+ ],+ )+ def test_it_survives_a_blob_it_cannot_parse(self, label, raw):+ sd = {"lin.weight": torch.zeros(4, 4), "lin.comfy_quant": self._blob(raw)}++ markers = extract_int8_convrot_markers(sd)++ assert markers == {}+ # Left in place: it belongs to whichever path does understand it.+ assert "lin.comfy_quant" in sd++ def test_a_nul_padded_int8_marker_is_still_read(self):+ raw = b'{"format":"int8_tensorwise"}' + bytes([0]) * 16+ sd = {"lin.weight": torch.zeros(4, 4, dtype=torch.int8), "lin.comfy_quant": self._blob(raw)}++ markers = extract_int8_convrot_markers(sd)++ assert list(markers) == ["lin"]+ assert "lin.comfy_quant" not in sd+++class TestWhetherLoraNeedsASidecar:+ """Asked of the loaded module tree, not the config. An `Int8ConvrotLinear` holds its weight as a+ buffer, so the patcher's own fallbacks -- which iterate `module.parameters()` -- find nothing and+ choose direct patching on a module with no patchable weights."""++ @staticmethod+ def _model(int8: bool) -> torch.nn.Module:+ model = torch.nn.Module()+ if int8:+ model.blk = Int8ConvrotLinear(torch.zeros(8, 8, dtype=torch.int8), torch.ones(8, 1), convrot=False)+ else:+ model.blk = torch.nn.Linear(8, 8)+ return model++ def test_an_int8_resident_checkpoint_needs_one(self):+ assert requires_sidecar_patching(self._model(int8=True), ModelFormat.Checkpoint) is True++ def test_a_plain_checkpoint_does_not(self):+ assert requires_sidecar_patching(self._model(int8=False), ModelFormat.Checkpoint) is False++ @pytest.mark.parametrize("fmt", [ModelFormat.GGUFQuantized, ModelFormat.SDNQQuantized])+ def test_a_format_that_is_quantized_by_definition_needs_one(self, fmt):+ assert requires_sidecar_patching(self._model(int8=False), fmt) is True