Skip to content

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

feat(quantization): share the int8_convrot scheme and teach Krea-2 to read it

Alexander Eichhorn8a9358e2fd15
diff --git a/invokeai/app/invocations/krea2_denoise.py b/invokeai/app/invocations/krea2_denoise.py
index 466568d505..70e74d668d 100644
--- a/invokeai/app/invocations/krea2_denoise.py
+++ b/invokeai/app/invocations/krea2_denoise.py
@@ -2,7 +2,7 @@ import json
import math
from contextlib import ExitStack
from pathlib import Path
-from typing import Callable, Iterator, Optional
+from typing import Any, Callable, Iterator, Optional
import torch
import torchvision.transforms as tv_transforms
@@ -46,6 +46,7 @@ from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelFormat
from invokeai.backend.patches.layer_patcher import LayerPatcher, PatchSpec
from invokeai.backend.patches.lora_conversions.krea2_lora_constants import KREA2_LORA_TRANSFORMER_PREFIX
from invokeai.backend.patches.model_patch_raw import ModelPatchRaw
+from invokeai.backend.quantization.int8_convrot import Int8ConvrotLinear
from invokeai.backend.rectified_flow.rectified_flow_inpaint_extension import RectifiedFlowInpaintExtension
from invokeai.backend.stable_diffusion.diffusers_pipeline import PipelineIntermediateState
from invokeai.backend.stable_diffusion.diffusion.conditioning_data import Krea2ConditioningInfo
@@ -55,6 +56,20 @@ from invokeai.backend.util.devices import TorchDevice
KREA2_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",
@@ -409,6 +424,7 @@ class Krea2DenoiseInvocation(BaseInvocation, WithMetadata, WithBoard):
)
transformer_config = context.models.get_config(self.transformer.transformer)
+ # Refined against the loaded module tree below, once the transformer is in hand.
model_is_quantized = transformer_config.format in (ModelFormat.GGUFQuantized,)
num_train_timesteps = scheduler.config.num_train_timesteps
@@ -439,6 +455,8 @@ class Krea2DenoiseInvocation(BaseInvocation, WithMetadata, WithBoard):
# SDPA for enable_gqa=True, which PyTorch only supports on the math backend — that materializes the
# full O(seq^2) score matrix (~5.7 GB per attention at 1280x720, ~40 GB at 2560x1440) and OOMs. Swap
# in a memory-efficient processor that expands the KV heads and uses the O(seq) SDPA kernel instead.
+ model_is_quantized = requires_sidecar_patching(transformer, transformer_config.format)
+
regional_prompting_state = Krea2RegionalPromptingState()
transformer.set_attn_processor(build_krea2_attention_processors(transformer, regional_prompting_state))
# The processors remain installed on the cached transformer after this invocation. Do not let them
diff --git a/invokeai/app/invocations/minimax_h3_denoise.py b/invokeai/app/invocations/minimax_h3_denoise.py
index 1f75bd6f64..29d2799333 100644
--- a/invokeai/app/invocations/minimax_h3_denoise.py
+++ b/invokeai/app/invocations/minimax_h3_denoise.py
@@ -33,7 +33,6 @@ from invokeai.app.invocations.model import MiniMaxH3TransformerField
from invokeai.app.services.session_processor.session_processor_common import CanceledException
from invokeai.app.services.shared.invocation_context import InvocationContext
from invokeai.backend.minimax_h3.denoise import denoise
-from invokeai.backend.minimax_h3.int8_convrot import Int8ConvrotLinear
from invokeai.backend.minimax_h3.packing import (
MINIMAX_H3_CANVAS_MULTIPLE,
MINIMAX_H3_FPS,
@@ -72,6 +71,7 @@ from invokeai.backend.patches.lora_conversions.minimax_h3_lora_conversion_utils
is_minimax_h3_adaln_layer_path,
)
from invokeai.backend.patches.model_patch_raw import ModelPatchRaw
+from invokeai.backend.quantization.int8_convrot import Int8ConvrotLinear
from invokeai.backend.stable_diffusion.diffusers_pipeline import PipelineIntermediateState
from invokeai.backend.stable_diffusion.diffusion.conditioning_data import MiniMaxH3ConditioningInfo
from invokeai.backend.util.devices import TorchDevice
diff --git a/invokeai/backend/model_manager/load/model_cache/torch_module_autocast/custom_modules/custom_int8_convrot_linear.py b/invokeai/backend/model_manager/load/model_cache/torch_module_autocast/custom_modules/custom_int8_convrot_linear.py
index bc8899a641..3cac78415b 100644
--- a/invokeai/backend/model_manager/load/model_cache/torch_module_autocast/custom_modules/custom_int8_convrot_linear.py
+++ b/invokeai/backend/model_manager/load/model_cache/torch_module_autocast/custom_modules/custom_int8_convrot_linear.py
@@ -1,6 +1,5 @@
import torch
-from invokeai.backend.minimax_h3.int8_convrot import Int8ConvrotLinear
from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.cast_to_device import cast_to_device
from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.custom_modules.custom_linear import (
autocast_linear_forward_sidecar_patches,
@@ -9,6 +8,7 @@ from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.custo
CustomModuleMixin,
)
from invokeai.backend.patches.layers.param_shape_utils import get_param_shape
+from invokeai.backend.quantization.int8_convrot import Int8ConvrotLinear
class CustomInt8ConvrotLinear(Int8ConvrotLinear, CustomModuleMixin):
diff --git a/invokeai/backend/model_manager/load/model_cache/torch_module_autocast/torch_module_autocast.py b/invokeai/backend/model_manager/load/model_cache/torch_module_autocast/torch_module_autocast.py
index 5b96ad86d1..c01d789310 100644
--- a/invokeai/backend/model_manager/load/model_cache/torch_module_autocast/torch_module_autocast.py
+++ b/invokeai/backend/model_manager/load/model_cache/torch_module_autocast/torch_module_autocast.py
@@ -4,7 +4,6 @@ import torch
from diffusers.models.normalization import RMSNorm as DiffusersRMSNorm
from invokeai.backend.flux.modules.layers import RMSNorm as FluxRMSNorm
-from invokeai.backend.minimax_h3.int8_convrot import Int8ConvrotLinear
from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.custom_modules.custom_conv1d import (
CustomConv1d,
)
@@ -35,6 +34,7 @@ from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.custo
from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.custom_modules.custom_module_mixin import (
CustomModuleMixin,
)
+from invokeai.backend.quantization.int8_convrot import Int8ConvrotLinear
AUTOCAST_MODULE_TYPE_MAPPING: dict[type[torch.nn.Module], type[torch.nn.Module]] = {
torch.nn.Linear: CustomLinear,
diff --git a/invokeai/backend/model_manager/load/model_loaders/krea2.py b/invokeai/backend/model_manager/load/model_loaders/krea2.py
index 774d3a9203..51156a7d60 100644
--- a/invokeai/backend/model_manager/load/model_loaders/krea2.py
+++ b/invokeai/backend/model_manager/load/model_loaders/krea2.py
@@ -26,6 +26,12 @@ from invokeai.backend.model_manager.taxonomy import (
)
from invokeai.backend.model_manager.util.qwen3_vl import normalize_qwen3vl_rope_config
from invokeai.backend.quantization.gguf.loaders import gguf_sd_loader
+from invokeai.backend.quantization.int8_convrot import (
+ CONVROT_GROUP_SIZE,
+ Int8ConvrotLinear,
+ check_int8_scale_layout,
+ extract_int8_convrot_markers,
+)
from invokeai.backend.util.devices import TorchDevice
if TYPE_CHECKING:
@@ -115,6 +121,11 @@ def _dequantize_scaled_fp8(sd: dict[str, Any], dtype: "torch.dtype") -> dict[str
out = dict(sd)
for scale_key in scale_keys:
weight_key = scale_key.replace(".weight_scale", ".weight")
+ if weight_key in out and not out[weight_key].is_floating_point():
+ # An int8_tensorwise layer. Scaling it here without un-rotating it produces a state dict
+ # that loads cleanly and generates noise, which is the failure the marker path exists to
+ # prevent -- so leave both the weight and its scale for that path to consume.
+ continue
if weight_key in out:
weight = torch.as_tensor(_to_plain_tensor(out[weight_key])).float()
scale = torch.as_tensor(_to_plain_tensor(out[scale_key])).float()
@@ -124,7 +135,26 @@ def _dequantize_scaled_fp8(sd: dict[str, Any], dtype: "torch.dtype") -> dict[str
return out
-def _convert_krea2_native_to_diffusers(sd: dict[str, Any]) -> dict[str, Any]:
+# The original final-block up/down projections have no counterpart in the diffusers
+# ``Krea2FinalLayer`` (a clean AdaLN + linear). Named once because two steps act on them: the
+# converter drops them, and the single-file loader drops them *before* dequantizing so it never
+# spends work - or trips over an exotic scale layout - on tensors that are about to be discarded.
+DISCARDED_NATIVE_FINAL_KEYS = ("last.down", "last.up")
+
+
+def _drop_discarded_native_final_layers(sd: dict[str, Any]) -> dict[str, Any]:
+ """Remove the dropped final-block projections together with their quantization metadata."""
+ doomed = {
+ f"{path}{suffix}"
+ for path in DISCARDED_NATIVE_FINAL_KEYS
+ for suffix in (".weight", ".weight_scale", ".comfy_quant")
+ }
+ if not doomed & set(sd):
+ return sd
+ return {k: v for k, v in sd.items() if k not in doomed}
+
+
+def _convert_krea2_native_to_diffusers(sd: dict[str, Any], *, key_map: dict[str, str] | None = None) -> dict[str, Any]:
"""Convert a native/ComfyUI-format Krea-2 state dict (e.g. GGUF) to diffusers Krea2Transformer2DModel keys.
Top-level module renames::
@@ -158,7 +188,7 @@ def _convert_krea2_native_to_diffusers(sd: dict[str, Any]) -> dict[str, Any]:
_put_unique_key(new_sd, key, value, source=key, source_of=source_of, what="Krea-2 checkpoint")
continue
# Drop original-only final-block projections (no diffusers equivalent).
- if key in ("last.down.weight", "last.up.weight"):
+ if key in tuple(f"{p}.weight" for p in DISCARDED_NATIVE_FINAL_KEYS):
continue
k = key
@@ -181,10 +211,11 @@ def _convert_krea2_native_to_diffusers(sd: dict[str, Any]) -> dict[str, Any]:
k = "txt_in.linear_1." + k[len("txtmlp.1.") :]
elif k.startswith("txtmlp.3."):
k = "txt_in.linear_2." + k[len("txtmlp.3.") :]
- elif k == "last.linear.weight":
- k = "final_layer.linear.weight"
- elif k == "last.linear.bias":
- k = "final_layer.linear.bias"
+ elif k.startswith("last.linear."):
+ # Prefix rather than an exact match per suffix: a quantized build carries
+ # `last.linear.weight_scale` too, and an exact rule leaves it behind under the old name
+ # -- which the loader only notices as a missing scale, well after the rename.
+ k = "final_layer.linear." + k[len("last.linear.") :]
elif k == "last.norm.scale":
k = "final_layer.norm.weight"
elif k == "last.modulation.lin":
@@ -215,6 +246,8 @@ def _convert_krea2_native_to_diffusers(sd: dict[str, Any]) -> dict[str, Any]:
value = torch.as_tensor(_to_plain_tensor(value)).reshape(6, -1)
_put_unique_key(new_sd, k, value, source=key, source_of=source_of, what="Krea-2 checkpoint")
+ if key_map is not None:
+ key_map[key] = k
return new_sd
@@ -316,9 +349,15 @@ class Krea2DiffusersModel(GenericDiffusersLoader):
class Krea2CheckpointModel(ModelLoader):
"""Class to load Krea-2 transformer models from single-file checkpoints (safetensors).
- Handles plain bf16/fp16 checkpoints as well as ComfyUI 'scaled fp8' checkpoints (fp8 weight +
- ``.weight_scale``), and both the diffusers and native/ComfyUI key naming. Apply the fp8-storage
- setting to keep the (large) transformer fp8-resident; otherwise it loads in full precision.
+ Handles plain bf16/fp16 checkpoints, ComfyUI 'scaled fp8' checkpoints (fp8 weight +
+ ``.weight_scale``) and ComfyUI 'int8_tensorwise' checkpoints (int8 weight + per-output-channel
+ ``.weight_scale`` + a ``.comfy_quant`` marker, optionally convrot-rotated), in both the diffusers
+ and native/ComfyUI key naming. Apply the fp8-storage setting to keep the (large) transformer
+ fp8-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.
"""
def _load_model(
@@ -348,21 +387,37 @@ class Krea2CheckpointModel(ModelLoader):
sd = load_file(model_path)
sd = _strip_comfyui_prefix(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.
+ sd = _drop_discarded_native_final_layers(sd)
+ # ComfyUI 'int8_tensorwise' checkpoints (Comfy-Org's *_int8_convrot.safetensors): dequantize
+ # and un-rotate the marked layers. This must run BEFORE the fp8 path, which keys off
+ # `.weight_scale` alone and would happily scale an int8 weight without ever un-rotating it --
+ # producing a state dict that loads cleanly and generates noise. It must also run BEFORE the
+ # key conversion below, which renames `.attn.wq.weight` by substring and so carries
+ # `.weight_scale` along but NOT `.comfy_quant`; decoding here keeps marker and weight paired.
+ int8_markers = extract_int8_convrot_markers(sd)
# ComfyUI 'scaled fp8' checkpoints: fold the per-tensor weight_scale into the weights. The
# 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)
# 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)
+ sd = _convert_krea2_native_to_diffusers(sd, key_map=key_map)
+ quantized = _resolve_quantized_module_paths(int8_markers, key_map)
with accelerate.init_empty_weights():
model = Krea2Transformer2DModel(**KREA2_TRANSFORMER_CONFIG)
- new_sd_size = sum(ten.nelement() * model_dtype.itemsize for ten in sd.values())
+ # 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())
self._ram_cache.make_room(new_sd_size)
- for k in sd.keys():
- sd[k] = sd[k].to(model_dtype)
+ _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")
@@ -471,7 +526,7 @@ class Qwen3VLEncoderLoader(ModelLoader):
)
-def _remap_qwen3vl_singlefile_keys(sd: dict[str, Any]) -> dict[str, Any]:
+def _remap_qwen3vl_singlefile_keys(sd: dict[str, Any], *, key_map: dict[str, str] | None = None) -> dict[str, Any]:
"""Remap ComfyUI single-file Qwen3-VL keys to the transformers ``Qwen3VLModel`` layout.
ComfyUI/native layout uses a single ``model.`` prefix for both towers; transformers splits them:
@@ -488,13 +543,96 @@ def _remap_qwen3vl_singlefile_keys(sd: dict[str, Any]) -> dict[str, Any]:
key = k[len("model.") :] if k.startswith("model.") else k
if key.startswith("visual.") or key.startswith("language_model."):
# Already the transformers layout (e.g. "model.language_model.*" / "model.visual.*").
- _put_unique_key(out, key, v, source=k, source_of=source_of, what=what)
+ new_key = key
else:
# Bare language-model keys (layers.* / embed_tokens / norm) belong under language_model.
- _put_unique_key(out, "language_model." + key, v, source=k, source_of=source_of, what=what)
+ new_key = "language_model." + key
+ _put_unique_key(out, new_key, v, source=k, source_of=source_of, what=what)
+ if key_map is not None:
+ key_map[k] = new_key
return 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.
@@ -575,27 +713,35 @@ class Qwen3VLEncoderCheckpointLoader(ModelLoader):
model_dtype = TorchDevice.choose_bfloat16_safe_dtype(target_device)
sd = load_file(str(model_path))
+ # ComfyUI 'int8_tensorwise' encoders, decoded first for the same two reasons as the
+ # transformer above -- and for a third one here: an int8 layer's `.weight_scale` would
+ # otherwise make the fp8 detection below answer yes, and the encoder would be kept
+ # "fp8-resident" over weights that were never fp8.
+ int8_markers = extract_int8_convrot_markers(sd)
# Detect an fp8 source (ComfyUI 'scaled fp8' weight_scale keys, or raw float8 weights) BEFORE
# dequantizing. An fp8-on-disk encoder is kept fp8-resident with layerwise upcasting below, so
# it occupies ~half the VRAM of the dequantized bf16 model (the whole point of shipping fp8).
- source_is_fp8 = any(isinstance(k, str) and k.endswith(".weight_scale") for k in sd) or any(
- getattr(t, "dtype", None) in (torch.float8_e4m3fn, torch.float8_e5m2) for t in sd.values()
- )
+ # An int8 layer's scale is not evidence of fp8, so those are excluded -- otherwise an int8
+ # encoder would be kept "fp8-resident" over weights that were never fp8.
+ source_is_fp8 = any(
+ isinstance(k, str) and k.endswith(".weight_scale") and k[: -len(".weight_scale")] not in int8_markers
+ for k in sd
+ ) 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)
- for k in list(sd.keys()):
- if isinstance(k, str) and (k.endswith(".comfy_quant") or "scale_input" in k):
- del sd[k]
- sd = _remap_qwen3vl_singlefile_keys(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)
te_config = self._load_hf_config()
with accelerate.init_empty_weights():
model = Qwen3VLModel._from_config(te_config)
- new_sd_size = sum(ten.nelement() * model_dtype.itemsize for ten in sd.values())
+ 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)
- for k in sd.keys():
- sd[k] = sd[k].to(model_dtype)
+ _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/minimax_h3.py b/invokeai/backend/model_manager/load/model_loaders/minimax_h3.py
index 3f5e8a7c34..8bf94492cc 100644
--- a/invokeai/backend/model_manager/load/model_loaders/minimax_h3.py
+++ b/invokeai/backend/model_manager/load/model_loaders/minimax_h3.py
@@ -173,7 +173,6 @@ class MiniMaxH3CheckpointModel(ModelLoader):
from invokeai.backend.minimax_h3.contiguous_attention import (
patch_minimax_h3_attention_contiguous_qkv,
)
- from invokeai.backend.minimax_h3.int8_convrot import Int8ConvrotLinear
from invokeai.backend.minimax_h3.transformer_minimax_h3_pruned import (
MiniMaxH3PrunedTransformer3DModel,
set_curve_modulation_dtype,
@@ -182,6 +181,7 @@ class MiniMaxH3CheckpointModel(ModelLoader):
convert_minimax_h3_checkpoint_to_diffusers,
read_comfy_quant_markers,
)
+ from invokeai.backend.quantization.int8_convrot import Int8ConvrotLinear
model_path = Path(config.path)
@@ -317,12 +317,12 @@ class MiniMaxH3TextEncoderCheckpointModel(ModelLoader):
from safetensors.torch import load_file
from transformers import Qwen3VLConfig, Qwen3VLForConditionalGeneration
- from invokeai.backend.minimax_h3.int8_convrot import Int8ConvrotLinear
from invokeai.backend.minimax_h3.text_conditioning import MINIMAX_H3_TEXT_ENCODER_LAYER
from invokeai.backend.model_manager.load.model_loaders.minimax_h3_state_dict_utils import (
convert_minimax_h3_text_encoder_checkpoint,
read_comfy_quant_markers,
)
+ from invokeai.backend.quantization.int8_convrot import Int8ConvrotLinear
model_path = Path(config.path)
diff --git a/invokeai/backend/model_manager/load/model_loaders/minimax_h3_state_dict_utils.py b/invokeai/backend/model_manager/load/model_loaders/minimax_h3_state_dict_utils.py
index e492064e5b..42069a7006 100644
--- a/invokeai/backend/model_manager/load/model_loaders/minimax_h3_state_dict_utils.py
+++ b/invokeai/backend/model_manager/load/model_loaders/minimax_h3_state_dict_utils.py
@@ -34,7 +34,7 @@ from typing import Any
import torch
-from invokeai.backend.minimax_h3.int8_convrot import parse_comfy_quant_marker
+from invokeai.backend.quantization.int8_convrot import parse_comfy_quant_marker
def read_comfy_quant_markers(path: Path) -> dict[str, dict[str, Any]]:
diff --git a/invokeai/backend/minimax_h3/int8_convrot.py b/invokeai/backend/quantization/int8_convrot.py
similarity index 69%
rename from invokeai/backend/minimax_h3/int8_convrot.py
rename to invokeai/backend/quantization/int8_convrot.py
index 378cbf4b99..032e4c3f57 100644
--- a/invokeai/backend/minimax_h3/int8_convrot.py
+++ b/invokeai/backend/quantization/int8_convrot.py
@@ -1,7 +1,12 @@
"""Runtime support for Comfy "int8_tensorwise + convrot" quantized linears.
-The Comfy-Org single-file H3 transformers store their four big per-block linears
-(qkv/out/fc1/fc2) as symmetric per-output-channel int8:
+``int8_tensorwise`` is a ComfyUI-wide scheme, not one architecture's format: the same
+spelling appears on MiniMax H3 (the first consumer here), Krea-2, and whatever Comfy-Org
+publishes next. It therefore lives beside the other schemes in ``backend/quantization``
+rather than in an architecture package, so a second architecture costs a call site and not
+a second copy of the mathematics.
+
+A quantized linear stores its weight as symmetric per-output-channel int8:
- ``<layer>.weight``: int8 ``[out, in]``
- ``<layer>.weight_scale``: float32 ``[out, 1]``
@@ -23,11 +28,12 @@ We target bf16 compute with int8 *storage*: ``Int8ConvrotLinear`` keeps the int8
weight and scale resident (4.6x smaller than bf16) and materializes the
dequantized, derotated bf16 weight per forward call. The derotation is a
``[out, in/256, 256] @ [256, 256]`` matmul — a rounding error next to the
-transformer forward itself — and the transient bf16 weight (<= ~310 MB for the
-largest layer) lives inside the denoise node's working-memory reservation.
+transformer forward itself — and the transient bf16 weight (<= ~310 MB for H3's
+largest layer) has to fit inside the calling node's working-memory reservation.
"""
import json
+from typing import Any
import torch
import torch.nn.functional as F
@@ -36,6 +42,8 @@ CONVROT_GROUP_SIZE = 256
_HADAMARD_SEED = ((1, 1, 1, -1), (1, 1, -1, 1), (1, -1, 1, 1), (-1, 1, 1, 1))
+INT8_TENSORWISE_FORMAT = "int8_tensorwise"
+
def build_regular_hadamard(size: int, dtype: torch.dtype = torch.float32) -> torch.Tensor:
"""Normalized regular Hadamard matrix of a power-of-4 size (CPU tensor)."""
@@ -83,9 +91,9 @@ class Int8ConvrotLinear(torch.nn.Module):
``AUTOCAST_MODULE_TYPE_MAPPING``), which enables sidecar LoRA patches and lets a partial
load leave some int8 buffers on the CPU — ``forward``'s per-call ``.to(device)`` then
streams them (at half the bf16 byte count) instead of failing outright. Fully-resident
- operation (~20 GiB free VRAM for the pruned transformer) remains the intended regime;
- streamed layers pay a per-forward PCIe cost, and the diffusers-folder bf16 model is still
- the better citizen on small cards.
+ operation remains the intended regime (~20 GiB free VRAM for H3's pruned transformer);
+ streamed layers pay a per-forward PCIe cost, and an unquantized model is still the better
+ citizen on small cards.
"""
def __init__(
@@ -142,3 +150,44 @@ class Int8ConvrotLinear(torch.nn.Module):
def extra_repr(self) -> str:
return f"in_features={self.in_features}, out_features={self.out_features}, convrot={self.convrot}"
+
+
+def extract_int8_convrot_markers(sd: dict[str, Any]) -> dict[str, dict[str, Any]]:
+ """Pop every ``int8_tensorwise`` marker out of ``sd``, keyed by the layer path it names.
+
+ Markers for other formats are left in place, together with their weights and scales: ComfyUI's
+ fp8_scaled repacks share this key layout and belong to the fp8 path. Deciding per marker rather
+ than per file is also what keeps mixed-precision checkpoints correct -- one Krea-2 build leaves
+ 40 weights in bf16 with no marker at all, and both Qwen3-VL encoders leave over 200.
+
+ Use this when the loader intends to keep the weights int8 and swap in
+ :class:`Int8ConvrotLinear`, which is what every loader here does.
+ """
+ markers = {}
+ for key in [k for k in sd if isinstance(k, str) and k.endswith(".comfy_quant")]:
+ marker = parse_comfy_quant_marker(sd[key])
+ if marker.get("format") != INT8_TENSORWISE_FORMAT:
+ continue
+ markers[key[: -len(".comfy_quant")]] = marker
+ del sd[key]
+ return markers
+
+
+def check_int8_scale_layout(path: str, weight: torch.Tensor, scale: torch.Tensor) -> None:
+ """Refuse a scale granularity this decode does not implement.
+
+ Two layouts are supported, because they are the two this dequantization is correct for:
+ per-output-channel (``[out, 1]`` or ``[out]``) and per-tensor (a scalar). Some repacks emit a
+ blockwise grid instead - a 6144x6144 weight with a ``[48, 48]`` scale is a 128x128 block grid -
+ which needs a different multiply. Left to broadcasting that either raises somewhere less
+ informative or, for an unlucky shape, silently scales the wrong axis.
+ """
+ rows = weight.shape[0] if weight.dim() else 1
+ if scale.dim() == 0 or tuple(scale.shape) in {(1,), (1, 1)}:
+ return
+ if tuple(scale.shape) in {(rows,), (rows, 1)}:
+ return
+ raise ValueError(
+ f"'{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."
+ )
diff --git a/tests/app/invocations/test_krea2_denoise.py b/tests/app/invocations/test_krea2_denoise.py
index 670bac2d67..4bbde4cffe 100644
--- a/tests/app/invocations/test_krea2_denoise.py
+++ b/tests/app/invocations/test_krea2_denoise.py
@@ -6,9 +6,14 @@ import pytest
import torch
from invokeai.app.invocations.fields import DenoiseMaskField, Krea2ConditioningField, LatentsField, TensorField
-from invokeai.app.invocations.krea2_denoise import KREA2_LATENT_CHANNELS, Krea2DenoiseInvocation
+from invokeai.app.invocations.krea2_denoise import (
+ KREA2_LATENT_CHANNELS,
+ Krea2DenoiseInvocation,
+ requires_sidecar_patching,
+)
from invokeai.app.invocations.model import ModelIdentifierField, TransformerField
from invokeai.backend.model_manager.taxonomy import BaseModelType, Krea2VariantType, ModelFormat, ModelType
+from invokeai.backend.quantization.int8_convrot import Int8ConvrotLinear
from invokeai.backend.stable_diffusion.diffusion.conditioning_data import ConditioningFieldData, Krea2ConditioningInfo
@@ -320,6 +325,12 @@ class _Transformer:
# The real Krea2Transformer2DModel exposes this; denoise swaps in a memory-efficient attention processor.
self.installed_processors = processor
+ def modules(self):
+ # Denoise walks the module tree to decide whether LoRA has to be applied as a sidecar: an
+ # int8_tensorwise build's Linears hold their weights as buffers, which a direct patch
+ # cannot write into. This double stands in for an unquantized model.
+ return iter(())
+
def __call__(self, *, hidden_states, encoder_hidden_states, **_kwargs):
self.conditioning_values.append(float(encoder_hidden_states.mean()))
# The real transformer concatenates [text, image] before attention, so this is the sequence length a
@@ -548,6 +559,9 @@ def test_run_diffusion_uses_per_prompt_position_ids_when_lengths_differ(monkeypa
def set_attn_processor(self, processor) -> None:
pass
+ def modules(self):
+ return iter(())
+
def __call__(self, *, hidden_states, encoder_hidden_states, position_ids, **_kwargs):
text_len = encoder_hidden_states.shape[1]
pos_len = position_ids.shape[0]
@@ -757,3 +771,28 @@ def test_regional_attention_memory_includes_masks_build_scratch_and_dtype_sized_
assert Krea2DenoiseInvocation._regional_attention_mask_bytes(positive, negative, torch.bfloat16) == 500
assert Krea2DenoiseInvocation._regional_attention_mask_bytes(positive, negative, torch.float32) == 740
assert Krea2DenoiseInvocation._regional_attention_mask_bytes(positive, None, torch.bfloat16) == 400
+
+
+class TestRequiresSidecarPatching:
+ """LoRA cannot be written into an int8 buffer, and the config format does not say when one
+ is present: an `int8_tensorwise` Krea-2 is a plain `checkpoint` as far as the config knows."""
+
+ class _Tree:
+ def __init__(self, *modules) -> None:
+ self._modules = modules
+
+ def modules(self):
+ return iter(self._modules)
+
+ def test_an_unquantized_checkpoint_is_patched_directly(self) -> None:
+ assert not requires_sidecar_patching(self._Tree(torch.nn.Linear(2, 2)), ModelFormat.Checkpoint)
+
+ def test_a_gguf_model_is_still_recognised_by_its_format(self) -> None:
+ assert requires_sidecar_patching(self._Tree(), ModelFormat.GGUFQuantized)
+
+ def test_an_int8_convrot_checkpoint_is_recognised_by_its_modules(self) -> None:
+ int8_linear = Int8ConvrotLinear(
+ weight=torch.zeros(4, 4, dtype=torch.int8), weight_scale=torch.ones(4, 1), convrot=False
+ )
+ tree = self._Tree(torch.nn.Linear(2, 2), int8_linear)
+ assert requires_sidecar_patching(tree, ModelFormat.Checkpoint)
diff --git a/tests/backend/minimax_h3/test_text_encoder_checkpoint.py b/tests/backend/minimax_h3/test_text_encoder_checkpoint.py
index e00fabfeb8..dc4de8de88 100644
--- a/tests/backend/minimax_h3/test_text_encoder_checkpoint.py
+++ b/tests/backend/minimax_h3/test_text_encoder_checkpoint.py
@@ -202,8 +202,8 @@ def test_te_converted_keys_match_real_model_exactly() -> None:
from transformers import Qwen3VLForConditionalGeneration
from transformers.models.qwen3_vl.configuration_qwen3_vl import Qwen3VLConfig
- from invokeai.backend.minimax_h3.int8_convrot import Int8ConvrotLinear
from invokeai.backend.model_manager.util.qwen3_vl import normalize_qwen3vl_rope_config
+ from invokeai.backend.quantization.int8_convrot import Int8ConvrotLinear
from tests.model_identification.stripped_model_on_disk import StrippedModelOnDisk
fixture_dir = (
diff --git a/tests/backend/model_manager/load/test_krea2_loader_boundaries.py b/tests/backend/model_manager/load/test_krea2_loader_boundaries.py
index ba618ab03b..2446039d2e 100644
--- a/tests/backend/model_manager/load/test_krea2_loader_boundaries.py
+++ b/tests/backend/model_manager/load/test_krea2_loader_boundaries.py
@@ -8,14 +8,19 @@ from invokeai.backend.model_manager.configs.main import (
Main_Diffusers_Krea2_Config,
Main_GGUF_Krea2_Config,
)
-from invokeai.backend.model_manager.configs.qwen3_vl_encoder import Qwen3VLEncoder_Qwen3VLEncoder_Config
+from invokeai.backend.model_manager.configs.qwen3_vl_encoder import (
+ Qwen3VLEncoder_Checkpoint_Config,
+ Qwen3VLEncoder_Qwen3VLEncoder_Config,
+)
from invokeai.backend.model_manager.load.model_loaders.krea2 import (
Krea2CheckpointModel,
Krea2DiffusersModel,
Krea2GGUFCheckpointModel,
+ Qwen3VLEncoderCheckpointLoader,
Qwen3VLEncoderLoader,
)
from invokeai.backend.model_manager.taxonomy import Krea2VariantType, SubModelType
+from invokeai.backend.quantization.int8_convrot import Int8ConvrotLinear
class _TinyKrea2Transformer(torch.nn.Module):
@@ -57,6 +62,73 @@ def test_single_file_loader_constructs_and_materializes_model(monkeypatch, tmp_p
ram_cache.make_room.assert_called_once()
+def test_single_file_loader_decodes_an_int8_convrot_checkpoint(monkeypatch, tmp_path) -> None:
+ """The decode has to be *wired in*, not merely available.
+
+ Every other test of this feature exercises the helpers directly, so deleting the call from
+ `_load_from_singlefile` would leave them all green while the loader silently produced a
+ scaled-but-still-rotated model. This one drives the loader itself and checks the weight that
+ actually reaches the module.
+ """
+ import json
+
+ import diffusers
+ import safetensors.torch
+
+ from invokeai.backend.quantization.int8_convrot import CONVROT_GROUP_SIZE, build_regular_hadamard
+
+ torch.manual_seed(0)
+ original = torch.randn(4, CONVROT_GROUP_SIZE)
+ hadamard = build_regular_hadamard(CONVROT_GROUP_SIZE)
+ rotated = (original.view(4, 1, CONVROT_GROUP_SIZE) @ hadamard.T).view(4, CONVROT_GROUP_SIZE)
+ scale = rotated.abs().amax(dim=1, keepdim=True) / 127.0
+ marker = json.dumps({"format": "int8_tensorwise", "convrot": True, "convrot_groupsize": CONVROT_GROUP_SIZE})
+ # A marker is always `<layer>.comfy_quant`; a quantized weight is a submodule's, never the
+ # model's own, so the fixture mirrors that.
+ state_dict = {
+ "proj.weight": torch.clamp(torch.round(rotated / scale), -128, 127).to(torch.int8),
+ "proj.weight_scale": scale.to(torch.float32),
+ "proj.comfy_quant": torch.frombuffer(bytearray(marker.encode("utf-8")), dtype=torch.uint8),
+ }
+
+ class _TinyInt8Krea2Transformer(torch.nn.Module):
+ def __init__(self, **_kwargs) -> None:
+ super().__init__()
+ self.proj = torch.nn.Linear(CONVROT_GROUP_SIZE, 4, bias=False)
+
+ 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._apply_fp8_layerwise_casting = lambda model, _config, _submodel: model
+
+ 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,
+ )
+
+ model = loader._load_from_singlefile(config)
+
+ # The weight stays quantized: that is the whole point of the swap, and it is what keeps a
+ # 12 GB checkpoint at 12 GB instead of the ~24 GB a dense decode would produce.
+ assert isinstance(model.proj, Int8ConvrotLinear)
+ assert model.proj.weight.dtype is torch.int8
+
+ # And it still computes the un-rotated weight, which the fp8 path alone would never produce.
+ dequantized = model.proj._dequantized_weight(torch.device("cpu"), torch.float32).flatten()
+ assert torch.corrcoef(torch.stack([dequantized, original.flatten()]))[0, 1] > 0.999
+ assert torch.corrcoef(torch.stack([dequantized, rotated.flatten()]))[0, 1].abs() < 0.2
+
+
def test_diffusers_loader_reaches_transformer_from_pretrained(monkeypatch, tmp_path) -> None:
config = Main_Diffusers_Krea2_Config.model_construct(path=str(tmp_path), repo_variant=None)
loader = object.__new__(Krea2DiffusersModel)
@@ -110,6 +182,85 @@ def test_gguf_loader_constructs_and_materializes_model(monkeypatch, tmp_path) ->
assert torch.equal(model.weight, torch.ones(2, 2))
+def test_checkpoint_encoder_loader_decodes_int8_and_does_not_call_it_fp8(monkeypatch, tmp_path) -> None:
+ """The encoder path carries the same hazard as the transformer, plus one of its own.
+
+ `source_is_fp8` answers yes to any `.weight_scale` key. Left to itself an int8 encoder would
+ be scaled, never un-rotated, and then kept "fp8-resident" over weights that were never fp8.
+ Decoding first removes the int8 scales, so the detection sees what it was written to see.
+ """
+ import json
+
+ import transformers
+ from safetensors import torch as safetensors_torch
+
+ from invokeai.backend.quantization.int8_convrot import CONVROT_GROUP_SIZE, build_regular_hadamard
+
+ torch.manual_seed(0)
+ original = torch.randn(4, CONVROT_GROUP_SIZE)
+ hadamard = build_regular_hadamard(CONVROT_GROUP_SIZE)
+ rotated = (original.view(4, 1, CONVROT_GROUP_SIZE) @ hadamard.T).view(4, CONVROT_GROUP_SIZE)
+ scale = rotated.abs().amax(dim=1, keepdim=True) / 127.0
+ marker = json.dumps({"format": "int8_tensorwise", "convrot": True, "convrot_groupsize": CONVROT_GROUP_SIZE})
+ state_dict = {
+ "proj.weight": torch.clamp(torch.round(rotated / scale), -128, 127).to(torch.int8),
+ "proj.weight_scale": scale.to(torch.float32),
+ "proj.comfy_quant": torch.frombuffer(bytearray(marker.encode("utf-8")), dtype=torch.uint8),
+ }
+
+ class _TinyLanguageModel(torch.nn.Module):
+ def __init__(self) -> None:
+ super().__init__()
+ self.proj = torch.nn.Linear(CONVROT_GROUP_SIZE, 4, bias=False)
+
+ class _TinyEncoder(torch.nn.Module):
+ """`_remap_qwen3vl_singlefile_keys` routes bare keys under `language_model.`, so the
+ fixture keeps the checkpoint's spelling and lets the remap do its job."""
+
+ def __init__(self) -> None:
+ super().__init__()
+ self.language_model = _TinyLanguageModel()
+
+ @classmethod
+ def _from_config(cls, _config):
+ return cls()
+
+ checkpoint_path = tmp_path / "qwen3vl_int8_convrot.safetensors"
+ checkpoint_path.touch()
+ config = Qwen3VLEncoder_Checkpoint_Config.model_construct(path=str(checkpoint_path), name="encoder")
+
+ fp8_calls: list = []
+ loader = object.__new__(Qwen3VLEncoderCheckpointLoader)
+ loader._ram_cache = SimpleNamespace(make_room=MagicMock())
+ loader._torch_device = torch.device("cpu")
+ loader._logger = MagicMock()
+ loader._load_hf_config = lambda: SimpleNamespace()
+ loader._apply_fp8_to_nn_module = lambda *a, **k: fp8_calls.append(a)
+
+ monkeypatch.setattr(transformers, "Qwen3VLModel", _TinyEncoder, 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,
+ )
+ monkeypatch.setattr(
+ "invokeai.backend.model_manager.load.model_loaders.krea2._device_supports_fp8_storage",
+ lambda _device, _logger: True,
+ )
+
+ model = loader._load_text_encoder(config)
+
+ assert isinstance(model.language_model.proj, Int8ConvrotLinear)
+ assert model.language_model.proj.weight.dtype is torch.int8
+ dequantized = model.language_model.proj._dequantized_weight(torch.device("cpu"), torch.float32).flatten()
+ assert torch.corrcoef(torch.stack([dequantized, original.flatten()]))[0, 1] > 0.999
+ assert fp8_calls == [], "an int8 encoder must not be treated as an fp8 one"
+
+
def test_directory_encoder_loader_reaches_transformers_from_pretrained(monkeypatch, tmp_path) -> None:
import transformers
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.py
index b5abded5d5..8598d4e051 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
@@ -18,12 +18,20 @@ from invokeai.backend.model_manager.load.model_loaders.krea2 import (
KREA2_TRANSFORMER_CONFIG,
_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,
+ extract_int8_convrot_markers,
+)
class TestNormalizeQwen3vlRopeConfig:
@@ -376,3 +384,153 @@ class TestConvertedShapesMatchRealKrea2Transformer:
for name in table_keys:
if name.startswith(("transformer_blocks.", "text_fusion.")):
assert expected[name][0] == 6, f"{name} expected 6 modulation rows, got {expected[name]}"
+
+
+def _quantized_int8_layer(path: str, weight: torch.Tensor) -> dict:
+ """A convrot-rotated int8 layer in the native key spelling, as Comfy-Org ships it."""
+ import json
+
+ 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
+ marker = json.dumps({"format": "int8_tensorwise", "convrot": True, "convrot_groupsize": CONVROT_GROUP_SIZE})
+ return {
+ f"{path}.weight": torch.clamp(torch.round(rotated / scale), -128, 127).to(torch.int8),
+ f"{path}.weight_scale": scale.to(torch.float32),
+ f"{path}.comfy_quant": torch.frombuffer(bytearray(marker.encode("utf-8")), dtype=torch.uint8),
+ }
+
+
+class TestInt8LayersSurviveTheLoaderPipeline:
+ """Two steps between the file and the model would quietly ruin an int8 layer.
+
+ Neither fails loudly if it is broken - both produce a state dict that loads cleanly and
+ generates noise - so each is pinned by a test that shows the damage.
+ """
+
+ def test_the_fp8_fold_leaves_an_int8_weight_and_its_scale_alone(self) -> None:
+ """The fp8 path keys off `.weight_scale` and never consults the marker. Folding the scale
+ into an int8 weight without un-rotating it is exactly the silent corruption the marker
+ exists to prevent, so it skips anything that is not floating point."""
+ torch.manual_seed(0)
+ sd = _quantized_int8_layer("blocks.0.mlp.down", torch.randn(64, 2 * CONVROT_GROUP_SIZE))
+ before = {k: v.clone() for k, v in sd.items()}
+
+ out = _dequantize_scaled_fp8(sd, torch.float32)
+
+ assert out["blocks.0.mlp.down.weight"].dtype is torch.int8
+ assert torch.equal(out["blocks.0.mlp.down.weight"], before["blocks.0.mlp.down.weight"])
+ assert "blocks.0.mlp.down.weight_scale" in out, "the scale the int8 layer still needs was consumed"
+
+ def test_an_fp8_layer_is_still_folded(self) -> None:
+ sd = {
+ "blocks.0.attn.wq.weight": torch.ones(4, 4, dtype=torch.float8_e4m3fn),
+ "blocks.0.attn.wq.weight_scale": torch.tensor(2.0),
+ }
+ out = _dequantize_scaled_fp8(sd, torch.float32)
+ assert "blocks.0.attn.wq.weight_scale" not in out
+ assert torch.allclose(out["blocks.0.attn.wq.weight"], torch.full((4, 4), 2.0))
+
+ def test_the_key_conversion_renames_the_scale_but_orphans_the_marker(self) -> None:
+ """Why the module paths are resolved by following the weight's own rename rather than the
+ marker's key: the within-block renames are substring replacements of `.attn.wq.weight`,
+ which `.weight_scale` contains and `.comfy_quant` does not."""
+ torch.manual_seed(1)
+ sd = _quantized_int8_layer("blocks.0.attn.wq", torch.randn(32, CONVROT_GROUP_SIZE))
+
+ converted = _convert_krea2_native_to_diffusers(sd)
+
+ assert "transformer_blocks.0.attn.to_q.weight" in converted
+ assert "transformer_blocks.0.attn.to_q.weight_scale" in converted
+ assert "transformer_blocks.0.attn.wq.comfy_quant" in converted
+ assert "transformer_blocks.0.attn.to_q.comfy_quant" not in converted
+
+ def test_the_marker_is_re_keyed_onto_the_module_the_weight_landed_on(self) -> None:
+ torch.manual_seed(2)
+ sd = _quantized_int8_layer("blocks.0.attn.wq", torch.randn(32, CONVROT_GROUP_SIZE))
+ markers = extract_int8_convrot_markers(sd)
+
+ key_map: dict[str, str] = {}
+ _convert_krea2_native_to_diffusers(sd, key_map=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
+
+
+class TestUnconsumedQuantizationSidecars:
+ def test_markers_and_activation_scales_are_dropped(self) -> None:
+ """`input_scale` is an activation scale for W8A8 inference; this code dequantizes the
+ weight and computes in bf16, so there is nothing to apply it to. One Qwen3-VL repack
+ ships 337 of them, under a spelling the previous filter did not match."""
+ sd = {
+ "layer.weight": torch.ones(2, 2),
+ "layer.comfy_quant": torch.zeros(4, dtype=torch.uint8),
+ "layer.input_scale": torch.ones(1),
+ "other.scale_input": torch.ones(1),
+ }
+ 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)
+
+
+class TestDiscardedFinalProjections:
+ def test_the_dropped_projections_take_their_quantization_metadata_with_them(self) -> None:
+ """`last.down`/`last.up` have no diffusers counterpart, and one real repack quantizes
+ `last.up` with a scale layout the decode refuses. Dropping them before the decode keeps a
+ tensor that is on its way to the bin from failing the load."""
+ sd = {
+ "last.up.weight": torch.zeros(4, 4, dtype=torch.int8),
+ "last.up.weight_scale": torch.ones(2, 2),
+ "last.up.comfy_quant": torch.zeros(8, dtype=torch.uint8),
+ "last.down.weight": torch.zeros(4, 4),
+ "last.linear.weight": torch.ones(4, 4),
+ }
+ out = _drop_discarded_native_final_layers(sd)
+ assert set(out) == {"last.linear.weight"}
+
+ def test_a_state_dict_without_them_is_returned_unchanged(self) -> None:
+ sd = {"last.linear.weight": torch.ones(2, 2)}
+ assert _drop_discarded_native_final_layers(sd) is sd
+
+
+class TestEverySuffixSurvivesTheKeyConversion:
+ """A quantized layer travels as three keys, and the converter has to move all of them.
+
+ The within-block renames are substring replacements of `.attn.wq.weight`, so `.weight_scale`
+ rides along by construction. The top-level renames are prefix slices, so they carry any
+ suffix. `last.linear` used to be neither -- an exact match per suffix, which silently left
+ `last.linear.weight_scale` under its old name.
+ """
+
+ @pytest.mark.parametrize(
+ ("native", "diffusers"),
+ [
+ ("blocks.0.attn.wq", "transformer_blocks.0.attn.to_q"),
+ ("blocks.3.mlp.down", "transformer_blocks.3.ff.down"),
+ ("txtfusion.refiner_blocks.1.attn.wv", "text_fusion.refiner_blocks.1.attn.to_v"),
+ ("first", "img_in"),
+ ("tmlp.0", "time_embed.linear_1"),
+ ("tmlp.2", "time_embed.linear_2"),
+ ("tproj.1", "time_mod_proj"),
+ ("txtmlp.1", "txt_in.linear_1"),
+ ("txtmlp.3", "txt_in.linear_2"),
+ ("last.linear", "final_layer.linear"),
+ ],
+ )
+ def test_the_weight_and_its_scale_land_on_the_same_module(self, native: str, diffusers: str) -> None:
+ sd = {f"{native}.weight": torch.zeros(4, 4, dtype=torch.int8), f"{native}.weight_scale": torch.ones(4, 1)}
+ key_map: dict[str, str] = {}
+ out = _convert_krea2_native_to_diffusers(sd, key_map=key_map)
+
+ assert f"{diffusers}.weight" in out
+ assert f"{diffusers}.weight_scale" in out, "the scale was left behind under its old name"
+ assert key_map[f"{native}.weight"] == f"{diffusers}.weight"
diff --git a/tests/backend/minimax_h3/test_int8_convrot.py b/tests/backend/quantization/test_int8_convrot.py
similarity index 99%
rename from tests/backend/minimax_h3/test_int8_convrot.py
rename to tests/backend/quantization/test_int8_convrot.py
index 0a2ef9db6f..e4b0b890e6 100644
--- a/tests/backend/minimax_h3/test_int8_convrot.py
+++ b/tests/backend/quantization/test_int8_convrot.py
@@ -11,7 +11,7 @@ import sys
import pytest
import torch
-from invokeai.backend.minimax_h3.int8_convrot import (
+from invokeai.backend.quantization.int8_convrot import (
CONVROT_GROUP_SIZE,
Int8ConvrotLinear,
build_regular_hadamard,
diff --git a/tests/backend/minimax_h3/test_int8_convrot_lora_sidecar.py b/tests/backend/quantization/test_int8_convrot_lora_sidecar.py
similarity index 98%
rename from tests/backend/minimax_h3/test_int8_convrot_lora_sidecar.py
rename to tests/backend/quantization/test_int8_convrot_lora_sidecar.py
index 47f75f08e6..efed3e89ba 100644
--- a/tests/backend/minimax_h3/test_int8_convrot_lora_sidecar.py
+++ b/tests/backend/quantization/test_int8_convrot_lora_sidecar.py
@@ -8,11 +8,6 @@ patching the dequantized weights directly.
import torch
-from invokeai.backend.minimax_h3.int8_convrot import (
- Int8ConvrotLinear,
- build_regular_hadamard,
- dequantize_convrot_weight,
-)
from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.torch_module_autocast import (
AUTOCAST_MODULE_TYPE_MAPPING,
apply_custom_layers_to_model,
@@ -20,6 +15,11 @@ from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.torch
from invokeai.backend.patches.layer_patcher import LayerPatcher
from invokeai.backend.patches.layers.lora_layer import LoRALayer
from invokeai.backend.patches.model_patch_raw import ModelPatchRaw
+from invokeai.backend.quantization.int8_convrot import (
+ Int8ConvrotLinear,
+ build_regular_hadamard,
+ dequantize_convrot_weight,
+)
IN_FEATURES = 16
OUT_FEATURES = 12
diff --git a/tests/backend/quantization/test_int8_convrot_state_dict.py b/tests/backend/quantization/test_int8_convrot_state_dict.py
new file mode 100644
index 0000000000..fea15c6818
--- /dev/null
+++ b/tests/backend/quantization/test_int8_convrot_state_dict.py
@@ -0,0 +1,97 @@
+"""Tests for the state-dict side of the int8_convrot scheme: which layers a loader picks up,
+and which scale layouts it will act on.
+
+The per-tensor mathematics is covered by ``test_int8_convrot.py``. What is pinned here is the
+part a loader can get wrong without anything raising — every failure below would otherwise
+surface as a model that loads cleanly and generates noise.
+"""
+
+import json
+
+import pytest
+import torch
+
+from invokeai.backend.quantization.int8_convrot import (
+ CONVROT_GROUP_SIZE,
+ check_int8_scale_layout,
+ extract_int8_convrot_markers,
+)
+
+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)
+
+
+class TestWhichLayersAreClaimed:
+ def test_an_int8_marker_is_claimed_and_removed(self) -> None:
+ sd = {
+ "blocks.0.attn.wq.weight": torch.zeros(4, CONVROT_GROUP_SIZE, dtype=torch.int8),
+ "blocks.0.attn.wq.weight_scale": torch.ones(4, 1),
+ "blocks.0.attn.wq.comfy_quant": _marker_blob(MARKER),
+ }
+ markers = extract_int8_convrot_markers(sd)
+
+ assert markers == {"blocks.0.attn.wq": MARKER}
+ # The marker is consumed; the weight and its scale stay for the loader to install.
+ assert set(sd) == {"blocks.0.attn.wq.weight", "blocks.0.attn.wq.weight_scale"}
+
+ def test_a_marker_for_another_format_is_left_untouched(self) -> None:
+ """ComfyUI's fp8_scaled repacks share this key layout and belong to the fp8 path."""
+ sd = {
+ "layer.weight": torch.zeros(4, 4, dtype=torch.float8_e4m3fn),
+ "layer.weight_scale": torch.ones(1),
+ "layer.comfy_quant": _marker_blob({"format": "float8_e4m3fn"}),
+ }
+ assert extract_int8_convrot_markers(sd) == {}
+ assert "layer.comfy_quant" in sd
+
+ def test_unmarked_weights_are_not_claimed(self) -> None:
+ """Mixed precision is the norm, not the exception: one Krea-2 build leaves 40 weights in
+ bf16 with no marker, and the two Qwen3-VL encoders leave over 200 each. A decision made
+ per file rather than per tensor would be wrong on all of them."""
+ sd = {
+ "txtfusion.0.weight": torch.zeros(8, 8, dtype=torch.bfloat16),
+ "blocks.0.attn.wq.weight": torch.zeros(4, CONVROT_GROUP_SIZE, dtype=torch.int8),
+ "blocks.0.attn.wq.weight_scale": torch.ones(4, 1),
+ "blocks.0.attn.wq.comfy_quant": _marker_blob(MARKER),
+ }
+ assert set(extract_int8_convrot_markers(sd)) == {"blocks.0.attn.wq"}
+
+ def test_a_state_dict_with_no_markers_is_unchanged(self) -> None:
+ sd = {"a.weight": torch.zeros(2, 2)}
+ assert extract_int8_convrot_markers(sd) == {}
+ assert set(sd) == {"a.weight"}
+
+ def test_the_group_size_travels_with_each_marker(self) -> None:
+ """Every marker in the Krea-2 build says 256, but the flag is per tensor and another
+ producer may vary it, so it is read rather than assumed."""
+ sd = {"layer.comfy_quant": _marker_blob({"format": "int8_tensorwise", "convrot_groupsize": 64})}
+ assert extract_int8_convrot_markers(sd)["layer"]["convrot_groupsize"] == 64
+
+
+class TestTheScaleLayoutsSeenInRealCheckpoints:
+ """Three appear across the checkpoints this was tested against, so none is hypothetical."""
+
+ def test_per_output_channel(self) -> None:
+ check_int8_scale_layout("layer", torch.zeros(64, 256, dtype=torch.int8), torch.ones(64, 1))
+
+ def test_per_output_channel_without_the_trailing_axis(self) -> None:
+ check_int8_scale_layout("layer", torch.zeros(64, 256, dtype=torch.int8), torch.ones(64))
+
+ def test_a_scalar_scale(self) -> None:
+ """One Qwen3-VL encoder stores every scale as a bare scalar, and Krea-2's
+ `txtfusion.projector` does the same."""
+ check_int8_scale_layout("layer", torch.zeros(1, 12, dtype=torch.int8), torch.tensor(0.01))
+
+ def test_a_blockwise_grid_is_refused_by_name(self) -> None:
+ """Also observed: a 6144x6144 weight with a [48, 48] scale, i.e. a 128x128 block grid.
+ Broadcasting would either raise somewhere uninformative or, for an unlucky shape,
+ silently scale the wrong axis."""
+ with pytest.raises(ValueError, match=r"Blockwise scale grids"):
+ check_int8_scale_layout("last.up", torch.zeros(512, 512, dtype=torch.int8), torch.ones(4, 4))
+
+ def test_the_message_names_the_layer_and_both_shapes(self) -> None:
+ with pytest.raises(ValueError, match=r"'last\.up' has a \(4, 4\) scale for a \(512, 512\) weight"):
+ check_int8_scale_layout("last.up", torch.zeros(512, 512, dtype=torch.int8), torch.ones(4, 4))