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(int8): share the install sequence and load int8 Qwen3 encoders

Alexander Eichhorn386eaa651545
diff --git a/invokeai/backend/model_manager/load/model_loaders/flux.py b/invokeai/backend/model_manager/load/model_loaders/flux.py
index 108dfe9edf..534d279346 100644
--- a/invokeai/backend/model_manager/load/model_loaders/flux.py
+++ b/invokeai/backend/model_manager/load/model_loaders/flux.py
@@ -108,14 +108,10 @@ from invokeai.backend.quantization.gguf.utils import TORCH_COMPATIBLE_QTYPES
from invokeai.backend.quantization.int8_convrot import (
INT8_TENSORWISE_FORMAT,
Int8ConvrotLinear,
- cast_unquantized,
drop_unconsumed_quantization_sidecars,
extract_int8_convrot_markers,
- predict_int8_cast_size,
- reject_foreign_quantization_scales,
+ install_int8_convrot_layers,
reject_unmarked_int8_weights,
- split_int8_convrot_layers,
- swap_in_int8_linears,
)
from invokeai.backend.quantization.sdnq.detection import is_sdnq_folder
from invokeai.backend.quantization.sdnq.loaders import raise_on_incomplete_sdnq_load, sdnq_sd_loader
@@ -844,21 +840,15 @@ class FluxCheckpointModel(ModelLoader):
# which dequantizes the weight and computes in bf16.
sd = drop_unconsumed_quantization_sidecars(sd)
- quantized = int8_markers
- # A scale left over from another scheme means its weight is about to be cast without
- # one. After the model exists, so the check can tell a real module from a stray key.
- reject_foreign_quantization_scales(sd, quantized, "FLUX", model)
-
- # Reserve before the split, which dequantizes what it cannot keep, and charge the int8
- # payloads their actual one byte rather than bf16's two.
- self._ram_cache.make_room(
- predict_int8_cast_size(sd, torch.bfloat16, quantized, model=model, skip_patterns=skip_patterns)
- )
- quantized = split_int8_convrot_layers(
- sd, quantized, torch.bfloat16, model=model, skip_patterns=skip_patterns
+ quantized = install_int8_convrot_layers(
+ model,
+ sd,
+ int8_markers,
+ torch.bfloat16,
+ architecture="FLUX",
+ reserve=self._ram_cache.make_room,
+ skip_patterns=skip_patterns,
)
- cast_unquantized(sd, torch.bfloat16, quantized)
- swap_in_int8_linears(model, sd, quantized)
load_state_dict_ignoring_extras(model, sd, source="FLUX transformer checkpoint", assign=True)
# No setting behind this one and nothing to fall back to: `Int8ConvrotLinear` holds the
@@ -1352,23 +1342,15 @@ class Flux2CheckpointModel(ModelLoader):
# because they would otherwise be cast and counted against the reservation for nothing.
converted_sd = drop_unconsumed_quantization_sidecars(converted_sd)
- quantized = int8_markers
- # A scale left over from another scheme means its weight is about to be cast without
- # one. After the model exists, so the check can tell a real module from a stray key.
- reject_foreign_quantization_scales(converted_sd, quantized, "FLUX.2", model)
-
- # Reserve before the split, which dequantizes what it cannot keep, and charge the int8
- # payloads their actual one byte rather than bf16's two.
- self._ram_cache.make_room(
- predict_int8_cast_size(
- converted_sd, torch.bfloat16, quantized, model=model, skip_patterns=skip_patterns
- )
- )
- quantized = split_int8_convrot_layers(
- converted_sd, quantized, torch.bfloat16, model=model, skip_patterns=skip_patterns
+ quantized = install_int8_convrot_layers(
+ model,
+ converted_sd,
+ int8_markers,
+ torch.bfloat16,
+ architecture="FLUX.2",
+ reserve=self._ram_cache.make_room,
+ skip_patterns=skip_patterns,
)
- cast_unquantized(converted_sd, torch.bfloat16, quantized)
- swap_in_int8_linears(model, converted_sd, quantized)
else:
# The same reservation FLUX.1 makes above, and for the same reason: the split
# dequantizes its unusable subset through fp32, so reserving afterwards lets that
diff --git a/invokeai/backend/model_manager/load/model_loaders/ideogram4.py b/invokeai/backend/model_manager/load/model_loaders/ideogram4.py
index 0011fa5d53..5927a3dd80 100644
--- a/invokeai/backend/model_manager/load/model_loaders/ideogram4.py
+++ b/invokeai/backend/model_manager/load/model_loaders/ideogram4.py
@@ -50,14 +50,10 @@ from invokeai.backend.quantization.fp8_scaled import (
warn_on_unattached_scales,
)
from invokeai.backend.quantization.int8_convrot import (
- cast_unquantized,
drop_unconsumed_quantization_sidecars,
extract_int8_convrot_markers,
- predict_int8_cast_size,
- reject_foreign_quantization_scales,
+ install_int8_convrot_layers,
reject_unmarked_int8_weights,
- split_int8_convrot_layers,
- swap_in_int8_linears,
)
from invokeai.backend.util.devices import TorchDevice
from invokeai.backend.util.state_dict_loading import load_state_dict_ignoring_extras, log_unexpected_keys
@@ -354,19 +350,15 @@ class Ideogram4CheckpointModel(ModelLoader):
# same dict `load_state_dict(assign=True)` aliased its parameters from.
sd = drop_unconsumed_quantization_sidecars(sd)
- quantized = int8_markers
- # A scale left over from another scheme means its weight is about to be cast without
- # one. After the model exists, so the check can tell a real module from a stray key.
- reject_foreign_quantization_scales(sd, quantized, "Ideogram 4", model)
-
- # Reserve before the split for the same reason as below, and charge the int8 payloads
- # their actual one byte rather than the compute dtype's two.
- self._ram_cache.make_room(
- predict_int8_cast_size(sd, model_dtype, quantized, model=model, skip_patterns=skip_patterns)
+ quantized = install_int8_convrot_layers(
+ model,
+ sd,
+ int8_markers,
+ model_dtype,
+ architecture="Ideogram 4",
+ reserve=self._ram_cache.make_room,
+ skip_patterns=skip_patterns,
)
- quantized = split_int8_convrot_layers(sd, quantized, model_dtype, model=model, skip_patterns=skip_patterns)
- cast_unquantized(sd, model_dtype, quantized)
- swap_in_int8_linears(model, sd, quantized)
kept = 0
else:
# Reserve before the split: it dequantizes the layers it cannot keep through float32,
diff --git a/invokeai/backend/model_manager/load/model_loaders/krea2.py b/invokeai/backend/model_manager/load/model_loaders/krea2.py
index b87f89bf80..5f2911d0ba 100644
--- a/invokeai/backend/model_manager/load/model_loaders/krea2.py
+++ b/invokeai/backend/model_manager/load/model_loaders/krea2.py
@@ -50,15 +50,11 @@ from invokeai.backend.quantization.fp8_scaled import (
)
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,
- predict_int8_cast_size,
- reject_foreign_quantization_scales,
+ install_int8_convrot_layers,
reject_unmarked_int8_weights,
resolve_quantized_module_paths,
- split_int8_convrot_layers,
- swap_in_int8_linears,
)
from invokeai.backend.quantization.nvfp4 import (
WEIGHT_SCALE_2_SUFFIX,
@@ -499,24 +495,23 @@ class Krea2CheckpointModel(ModelLoader):
nvfp4_bytes = predict_nvfp4_install_size(model, nvfp4_payloads, model_dtype, skip_patterns)
if int8_markers:
- # Before anything is cast: a scale left over from another scheme means its weight is
- # about to be cast without it, and the orphan disappears into `strict=False` below.
- # After the model exists, so a merged file's bundled submodels -- which this loader does
- # not prefix-filter out and never loads -- cannot fail a checkpoint that works.
- reject_foreign_quantization_scales(sd, quantized, "Krea-2", model)
-
- # Reserve before the split, not after: the split dequantizes the layers it widens, so
- # reserving afterwards lets that transient land on an unreserved cache. The prediction
- # is given the same inputs, so it charges those layers the compute dtype's width and
- # the int8 payloads their actual one byte -- reserving two would ask the cache to free
- # ~12 GB that this load never uses.
- self._ram_cache.make_room(
- predict_int8_cast_size(sd, model_dtype, quantized, model=model, skip_patterns=skip_patterns)
- + nvfp4_bytes
+ # A merged file's bundled submodels are in `sd` too -- this loader does not
+ # prefix-filter them out and never loads them -- so the scale check inside is the one
+ # that asks the model, not the dict.
+ quantized = install_int8_convrot_layers(
+ model,
+ sd,
+ quantized,
+ model_dtype,
+ architecture="Krea-2",
+ reserve=self._ram_cache.make_room,
+ skip_patterns=skip_patterns,
+ extra_reserved_bytes=nvfp4_bytes,
+ )
+ self._logger.info(
+ f"Krea-2: kept {len(quantized)} of {len(int8_markers)} layer(s) in int8 "
+ "(int8_tensorwise checkpoint, dequantized per forward)"
)
- quantized = split_int8_convrot_layers(sd, quantized, model_dtype, model=model, skip_patterns=skip_patterns)
- cast_unquantized(sd, model_dtype, quantized)
- swap_in_int8_linears(model, sd, quantized)
# The fp8 reporting below is keyed on these; an int8 checkpoint keeps neither.
fp8_layers = {}
kept = 0
@@ -919,18 +914,19 @@ class Qwen3VLEncoderCheckpointLoader(ModelLoader):
# everything" repack's 1-D norms) out of `swap_in_int8_linears`.
skip_patterns = _model_declared_skip_patterns(model)
- # Before anything is cast: a scale left over from another scheme means its weight is
- # about to be cast without it, and the orphan disappears into `strict=False` below.
- reject_foreign_quantization_scales(sd, quantized, "Qwen3-VL encoder", model)
-
- # Reserve before the split -- it dequantizes the layers it widens -- and charge the int8
- # payloads their actual one byte rather than the compute dtype's two.
- self._ram_cache.make_room(
- predict_int8_cast_size(sd, model_dtype, quantized, model=model, skip_patterns=skip_patterns)
+ quantized = install_int8_convrot_layers(
+ model,
+ sd,
+ quantized,
+ model_dtype,
+ architecture="Qwen3-VL encoder",
+ reserve=self._ram_cache.make_room,
+ skip_patterns=skip_patterns,
+ )
+ self._logger.info(
+ f"Qwen3-VL encoder: kept {len(quantized)} of {len(int8_markers)} layer(s) in int8 "
+ "(int8_tensorwise checkpoint, dequantized per forward)"
)
- quantized = split_int8_convrot_layers(sd, quantized, model_dtype, model=model, skip_patterns=skip_patterns)
- cast_unquantized(sd, model_dtype, quantized)
- swap_in_int8_linears(model, sd, quantized)
else:
# Same ordering contract as every other loader in this series: split *before* the cast.
# A per-key `if dtype is not FP8_DTYPE` cast looks equivalent and is not — it keeps every
diff --git a/invokeai/backend/model_manager/load/model_loaders/z_image.py b/invokeai/backend/model_manager/load/model_loaders/z_image.py
index 786dbd4d54..8869a08ff4 100644
--- a/invokeai/backend/model_manager/load/model_loaders/z_image.py
+++ b/invokeai/backend/model_manager/load/model_loaders/z_image.py
@@ -59,13 +59,10 @@ from invokeai.backend.quantization.fp8_scaled import (
)
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,
- predict_int8_cast_size,
+ install_int8_convrot_layers,
reject_unmarked_int8_weights,
- split_int8_convrot_layers,
- swap_in_int8_linears,
)
from invokeai.backend.quantization.nvfp4 import (
NVFP4Payload,
@@ -610,21 +607,25 @@ class ZImageCheckpointModel(ModelLoader):
sd.update(kept_sd)
del kept_sd
- # Reserve before the split, not after: the split dequantizes the layers it widens, so
- # reserving afterwards lets that transient land on an unreserved cache. The prediction
- # is given the same inputs, so it charges those layers the compute dtype's width and
- # the int8 payloads their actual one byte -- reserving two would ask the cache to free
- # memory this load never uses.
- self._ram_cache.make_room(
- predict_int8_cast_size(sd, model_dtype, int8_markers, model=model, skip_patterns=skip_patterns)
- + nvfp4_bytes
+ # The nvfp4 layers taken out above are held beside the int8 ones, so the single
+ # reservation has to cover both.
+ quantized = install_int8_convrot_layers(
+ model,
+ sd,
+ int8_markers,
+ model_dtype,
+ architecture="Z-Image",
+ reserve=self._ram_cache.make_room,
+ skip_patterns=skip_patterns,
+ extra_reserved_bytes=nvfp4_bytes,
)
-
- quantized = split_int8_convrot_layers(
- sd, int8_markers, model_dtype, model=model, skip_patterns=skip_patterns
+ # What did not stay int8 was widened to the compute dtype, so a load that kept far fewer
+ # layers than the file marked is the explanation for a resident size twice what the file
+ # suggests. Every other int8 loader reports this; this one did not.
+ self._logger.info(
+ f"Z-Image: kept {len(quantized)} of {len(int8_markers)} layer(s) in int8 "
+ "(int8_tensorwise checkpoint, dequantized per forward)"
)
- cast_unquantized(sd, model_dtype, quantized)
- swap_in_int8_linears(model, sd, quantized)
# The fp8 reporting below is keyed on these; an int8 checkpoint keeps neither.
fp8_layers: dict[str, Any] = {}
kept = 0
@@ -1229,6 +1230,27 @@ class Qwen3EncoderCheckpointLoader(ModelLoader):
sd = load_file(model_path)
original_key_count = len(sd)
+ # Three ComfyUI side channels reach this loader and a file carries one of them. int8 is
+ # decided first because it is the one the others cannot be told apart from by structure: an
+ # int8 layer ships a `.weight_scale` too, so the scaled-fp8 fold further down would pair
+ # every int8 code tensor with its scale and widen it, and the blanket cast after that would
+ # turn what survived into bf16 integers. Neither raises.
+ int8_markers = extract_int8_convrot_markers(sd)
+
+ # Outside the branch on purpose -- see the helper. An int8 weight whose marker is missing or
+ # unparseable is the case that has no structural signature at all.
+ reject_unmarked_int8_weights(sd, int8_markers, "Qwen3 encoder")
+
+ if "lm_head" in int8_markers:
+ # Same reason the nvfp4 payloads drop it below, but the int8 codes are still in `sd` and
+ # so the whole layer has to go: `tie_weights` assigns the embedding Parameter straight
+ # over an installed `Int8ConvrotLinear`'s buffers, leaving a module that derotates a
+ # bf16 embedding table. Dropping only the marker would instead leave the codes for the
+ # cast to widen into bf16 integers. Either way nothing raises.
+ del int8_markers["lm_head"]
+ for suffix in ("weight", "weight_scale"):
+ sd.pop(f"lm_head.{suffix}", None)
+
# Comfy's fp4_mixed encoders keep most projections in nvfp4, beside scaled fp8. Take those out before
# anything below reads the side channel: the fold pairs every `weight_scale` with its weight and would
# stretch nvfp4's block scales over the packed codes, and the cast further down would widen them.
@@ -1238,6 +1260,15 @@ class Qwen3EncoderCheckpointLoader(ModelLoader):
# `lm_head` is tied to the embeddings below, which replaces the weight a packed module would hold.
nvfp4_payloads.pop("lm_head", None)
+ if int8_markers:
+ # After the nvfp4 pop, not before it: this strips every remaining `.comfy_quant`, and a
+ # marker is one of the two things `pop_nvfp4_layers` accepts as naming an nvfp4 layer.
+ # Stripped first, a mixed file whose nvfp4 layers are named only by markers is refused
+ # as an unnamed-layout foreign file. What is left to drop here is `.input_scale` (W8A8
+ # activation scales, which this path has nothing to apply), which would otherwise be
+ # cast and charged to the reservation.
+ sd = drop_unconsumed_quantization_sidecars(sd)
+
# Count the number of layers by looking at layer keys
layer_count = 0
for key in sd.keys():
@@ -1340,42 +1371,60 @@ class Qwen3EncoderCheckpointLoader(ModelLoader):
model = Qwen3ForCausalLM(qwen_config)
skip_patterns = _model_declared_skip_patterns(model)
- # Handle memory management before anything below widens a weight: the scaled-fp8 fold turns every quantized
- # layer into the compute dtype, and the base loader reserved only the file size. One reservation for what
- # the state dict ends up holding -- every tensor but the scale metadata at the compute dtype, plus the nvfp4
- # layers as they will be held -- since `make_room` makes that much room rather than adding to an earlier one.
- new_sd_size = sum(
- tensor.nelement() * model_dtype.itemsize for key, tensor in sd.items() if not is_scale_metadata_key(key)
- )
- self._ram_cache.make_room(
- new_sd_size + predict_nvfp4_install_size(model, nvfp4_payloads, model_dtype, skip_patterns)
- )
+ nvfp4_bytes = predict_nvfp4_install_size(model, nvfp4_payloads, model_dtype, skip_patterns)
- # Handle ComfyUI quantized checkpoints
- # ComfyUI stores quantized weights with accompanying scale factors:
- # - layer.weight: quantized data (FP8)
- # - layer.weight_scale: scale factor (FP32 scalar)
- # Dequantization formula: dequantized = weight.to(dtype) * weight_scale
- # Reference: https://github.com/Comfy-Org/ComfyUI/blob/master/QUANTIZATION.md
- dequantized_count = _fold_comfy_scaled_weights(sd, model_dtype)
-
- if dequantized_count > 0:
- logger.info(f"Dequantized {dequantized_count} ComfyUI quantized weights")
-
- # Filter out ComfyUI quantization metadata keys (comfy_quant, weight_scale)
- # These are no longer needed after dequantization
- comfy_metadata_keys = [k for k in sd.keys() if is_scale_metadata_key(k)]
- for k in comfy_metadata_keys:
- del sd[k]
- if comfy_metadata_keys:
- logger.info(f"Filtered out {len(comfy_metadata_keys)} ComfyUI quantization metadata keys")
+ if int8_markers:
+ # The projections stay int8-resident, which is the whole point of the build: 8.8 GiB on
+ # disk stays 8.8 GiB, against the 15.3 GiB the bf16 release occupies. The reservation,
+ # the split and the cast all have to agree on which layers those are, which is what the
+ # shared install is for.
+ kept = install_int8_convrot_layers(
+ model,
+ sd,
+ int8_markers,
+ model_dtype,
+ architecture="Qwen3 encoder",
+ reserve=self._ram_cache.make_room,
+ skip_patterns=skip_patterns,
+ extra_reserved_bytes=nvfp4_bytes,
+ )
+ logger.info(f"Kept {len(kept)} of {len(int8_markers)} layer(s) in int8 (dequantized per forward)")
+ else:
+ # Handle memory management before anything below widens a weight: the scaled-fp8 fold turns every
+ # quantized layer into the compute dtype, and the base loader reserved only the file size. One
+ # reservation for what the state dict ends up holding -- every tensor but the scale metadata at the
+ # compute dtype, plus the nvfp4 layers as they will be held -- since `make_room` makes that much room
+ # rather than adding to an earlier one.
+ new_sd_size = sum(
+ tensor.nelement() * model_dtype.itemsize for key, tensor in sd.items() if not is_scale_metadata_key(key)
+ )
+ self._ram_cache.make_room(new_sd_size + nvfp4_bytes)
+
+ # Handle ComfyUI quantized checkpoints
+ # ComfyUI stores quantized weights with accompanying scale factors:
+ # - layer.weight: quantized data (FP8)
+ # - layer.weight_scale: scale factor (FP32 scalar)
+ # Dequantization formula: dequantized = weight.to(dtype) * weight_scale
+ # Reference: https://github.com/Comfy-Org/ComfyUI/blob/master/QUANTIZATION.md
+ dequantized_count = _fold_comfy_scaled_weights(sd, model_dtype)
+
+ if dequantized_count > 0:
+ logger.info(f"Dequantized {dequantized_count} ComfyUI quantized weights")
+
+ # Filter out ComfyUI quantization metadata keys (comfy_quant, weight_scale)
+ # These are no longer needed after dequantization
+ comfy_metadata_keys = [k for k in sd.keys() if is_scale_metadata_key(k)]
+ for k in comfy_metadata_keys:
+ del sd[k]
+ if comfy_metadata_keys:
+ logger.info(f"Filtered out {len(comfy_metadata_keys)} ComfyUI quantization metadata keys")
+
+ # Convert to target dtype
+ for k in sd.keys():
+ sd[k] = sd[k].to(model_dtype)
logger.info(f"Loaded state dict with {len(sd)} keys (originally {original_key_count})")
- # Convert to target dtype
- for k in sd.keys():
- sd[k] = sd[k].to(model_dtype)
-
if nvfp4_payloads:
packed = install_nvfp4_layers(model, sd, nvfp4_payloads, model_dtype, skip_patterns)
logger.info(f"Kept {packed} of {len(nvfp4_payloads)} nvfp4 layer(s) packed.")
diff --git a/invokeai/backend/model_manager/starter_models/__init__.py b/invokeai/backend/model_manager/starter_models/__init__.py
index 7f6a3e2b87..693c5a6447 100644
--- a/invokeai/backend/model_manager/starter_models/__init__.py
+++ b/invokeai/backend/model_manager/starter_models/__init__.py
@@ -35,6 +35,7 @@ from invokeai.backend.model_manager.starter_models.common import (
flux2_klein_qwen3_4b_encoder_fp4,
flux2_klein_qwen3_8b_encoder,
flux2_klein_qwen3_8b_encoder_fp4,
+ flux2_klein_qwen3_8b_encoder_int8,
gemma2_2b_encoder,
llava_onevision,
llava_onevision_7b,
@@ -374,6 +375,7 @@ STARTER_MODELS: list[StarterModel] = [
flux2_klein_qwen3_8b_encoder,
flux2_klein_qwen3_4b_encoder_fp4,
flux2_klein_qwen3_8b_encoder_fp4,
+ flux2_klein_qwen3_8b_encoder_int8,
flux2_dev_comfy_mistral_bf16,
flux2_dev_comfy_mistral_fp4,
flux2_dev_comfy_mistral_fp8,
diff --git a/invokeai/backend/model_manager/starter_models/common.py b/invokeai/backend/model_manager/starter_models/common.py
index afdd9206e7..0a20b1e258 100644
--- a/invokeai/backend/model_manager/starter_models/common.py
+++ b/invokeai/backend/model_manager/starter_models/common.py
@@ -268,6 +268,19 @@ flux2_klein_qwen3_8b_encoder_fp4 = StarterModel(
type=ModelType.Qwen3Encoder,
)
+# A community repack -- Comfy-Org publishes no int8 build of this encoder. Pinned to a commit rather
+# than `main` for the same reason the FLUX.1 and Klein 9B int8 entries are: the decode follows the
+# file's own `comfy_quant` marker, which says `convrot: true` at group size 256. A reupload at the
+# same path that changed or dropped that flag would be derotated wrongly, and the result loads
+# cleanly, logs "Kept 252 of 252" and encodes noise.
+flux2_klein_qwen3_8b_encoder_int8 = StarterModel(
+ name="FLUX.2 Klein Qwen3 8B Encoder (int8)",
+ base=BaseModelType.Any,
+ source="https://huggingface.co/supermind/int8_convrot_models/resolve/eb6682675836a42aa91fd4effcd77d68fe60ff42/text_encoders/qwen_3_8b_int8_convrot.safetensors",
+ description="Community int8_convrot Qwen3 8B text encoder for FLUX.2 Klein 9B. Its 252 projections stay int8 and dequantize per forward, so it occupies roughly what it downloads rather than the ~16GB of the BF16 release. ~9.4GB download",
+ type=ModelType.Qwen3Encoder,
+)
+
# Comfy-Org safetensors (single-file, 30-layer cow, with embedded Tekken tokenizer).
# Higher precision than the cow GGUFs and avoids the Tekken-via-HF-Hub fetch.
flux2_dev_comfy_mistral_fp8 = StarterModel(
diff --git a/invokeai/backend/pid/decode.py b/invokeai/backend/pid/decode.py
index 19ec1649e0..b35e8cdf88 100644
--- a/invokeai/backend/pid/decode.py
+++ b/invokeai/backend/pid/decode.py
@@ -35,6 +35,7 @@ from invokeai.backend.pid.state_dict_utils import PID_VERSION_BY_LQ_HIDDEN_DIM,
from invokeai.backend.quantization.dequantizing_linear import peak_dequant_transient_bytes
from invokeai.backend.quantization.int8_convrot import (
extract_int8_convrot_markers,
+ reject_foreign_quantization_scales,
reject_unmarked_int8_weights,
split_int8_convrot_layers,
swap_in_int8_linears,
@@ -339,6 +340,12 @@ def load_pid_decoder(state_dict: dict[Any, Tensor], backbone: BaseModelType) ->
int8_markers = extract_int8_convrot_markers(state_dict)
reject_unmarked_int8_weights(state_dict, int8_markers, "PiD")
if int8_markers:
+ # The rest of `install_int8_convrot_layers` does not apply here -- this path has no model
+ # cache to reserve against, and `load_state_dict` copies into float32 parameters rather than
+ # casting the dict -- but this check does: an fp8 scale from a mixed repack would otherwise
+ # have its weight copied in unscaled, off by `1/weight_scale`, and the orphan would vanish
+ # into the `strict=False` load below.
+ reject_foreign_quantization_scales(state_dict, int8_markers, "PiD", net)
swap_in_int8_linears(
net, state_dict, split_int8_convrot_layers(state_dict, int8_markers, torch.float32, model=net)
)
diff --git a/invokeai/backend/quantization/int8_convrot.py b/invokeai/backend/quantization/int8_convrot.py
index 9ae2ec837f..4f9b010be0 100644
--- a/invokeai/backend/quantization/int8_convrot.py
+++ b/invokeai/backend/quantization/int8_convrot.py
@@ -36,7 +36,7 @@ its estimate for that, since the model's resident size does not account for it.
import json
import struct
-from collections.abc import Iterable, Mapping
+from collections.abc import Callable, Iterable, Mapping
from pathlib import Path
from typing import Any
@@ -664,6 +664,53 @@ def cast_unquantized(sd: dict[str, Any], dtype: torch.dtype, quantized: dict[str
sd[key] = sd[key].to(dtype)
+def install_int8_convrot_layers(
+ model: torch.nn.Module,
+ sd: dict[str, Any],
+ quantized: dict[str, dict[str, Any]],
+ dtype: torch.dtype,
+ *,
+ architecture: str,
+ reserve: Callable[[int], None],
+ skip_patterns: Iterable[str] = (),
+ extra_reserved_bytes: int = 0,
+) -> dict[str, dict[str, Any]]:
+ """Take a marked int8 checkpoint from state dict to installed ``Int8ConvrotLinear`` modules.
+
+ Five steps whose order is the point, and which every loader that keeps int8 weights needs in
+ full. Each step depends on the one before it:
+
+ 1. :func:`reject_foreign_quantization_scales` -- before anything is cast, because a scale from
+ another scheme means its weight is about to be cast without one, off by ``1/weight_scale``,
+ while the orphaned scale disappears into ``strict=False``. After the model exists, because
+ only a weight this model consumes can be corrupted that way.
+ 2. ``reserve`` -- before the split, which dequantizes the layers it cannot keep. A reservation
+ made afterwards lets that transient land on an unreserved cache, and a locked model cannot be
+ evicted to make room for it.
+ 3. :func:`split_int8_convrot_layers` -- widens what cannot stay int8 and returns what can.
+ 4. :func:`cast_unquantized` -- the dense tensors only; the surviving payloads reach
+ ``load_state_dict`` exactly as stored.
+ 5. :func:`swap_in_int8_linears` -- the surviving layers, never the full marker set: a marker on
+ a module the split widened would install an ``Int8ConvrotLinear`` where the model wants
+ something else.
+
+ Written down once because getting it partially right is silent: Z-Image and the PiD decoder each
+ skipped step 1 and loaded a mixed checkpoint's fp8 weights unscaled, with nothing in the log.
+
+ ``reserve`` is the cache's ``make_room``; ``extra_reserved_bytes`` is for a loader whose file
+ also holds layers of another scheme -- Krea-2 and Z-Image add what their nvfp4 layers will cost,
+ so the one reservation covers the whole load. Returns the layers that stayed int8.
+ """
+ reject_foreign_quantization_scales(sd, quantized, architecture, model)
+ reserve(
+ predict_int8_cast_size(sd, dtype, quantized, model=model, skip_patterns=skip_patterns) + extra_reserved_bytes
+ )
+ surviving = split_int8_convrot_layers(sd, quantized, dtype, model=model, skip_patterns=skip_patterns)
+ cast_unquantized(sd, dtype, surviving)
+ swap_in_int8_linears(model, sd, surviving)
+ return surviving
+
+
def reject_foreign_quantization_scales(
sd: Mapping[str, Any], quantized: Mapping[str, Any], architecture: str, model: torch.nn.Module
) -> None:
diff --git a/tests/backend/model_manager/load/test_qwen3_encoder_checkpoint_loader.py b/tests/backend/model_manager/load/test_qwen3_encoder_checkpoint_loader.py
index d9cbe80ede..beec2b518e 100644
--- a/tests/backend/model_manager/load/test_qwen3_encoder_checkpoint_loader.py
+++ b/tests/backend/model_manager/load/test_qwen3_encoder_checkpoint_loader.py
@@ -1,4 +1,4 @@
-"""Loader-level test for single-file Qwen3 encoders in Comfy's fp4_mixed layout.
+"""Loader-level tests for single-file Qwen3 encoders in the two quantized layouts that reach them.
Drives `Qwen3EncoderCheckpointLoader._load_from_singlefile` on a real, tiny safetensors file laid out like
`Comfy-Org/z_image`'s `qwen_3_4b_fp4_mixed`: nvfp4 projections named by `comfy_quant` markers -- or, as another
@@ -8,6 +8,11 @@ the nvfp4 layers leave the state dict before that fold, which would pair their b
and come back only after the blanket cast, which would widen them; and an nvfp4 `lm_head` is dropped rather than
packed, since the loader ties `lm_head` to the embeddings. And that the returned model encodes exactly like a dense
Qwen3 holding the same weights.
+
+The second is `int8_convrot`, which `supermind/int8_convrot_models` publishes for both encoder sizes and
+Comfy-Org publishes for neither. Everything the fp4 path does wrong to an int8 file is silent: the scaled-fp8
+fold pairs each `weight_scale` with its weight and widens it, and the blanket cast turns what is left into bf16
+integers. So what is pinned there is that the loader commits to the int8 branch before either runs.
"""
import json
@@ -24,6 +29,7 @@ from invokeai.backend.model_manager.configs.qwen3_encoder import Qwen3Encoder_Ch
from invokeai.backend.model_manager.load.model_loaders import z_image
from invokeai.backend.model_manager.load.model_loaders.z_image import Qwen3EncoderCheckpointLoader
from invokeai.backend.model_manager.taxonomy import Qwen3VariantType
+from invokeai.backend.quantization.int8_convrot import Int8ConvrotLinear, build_regular_hadamard
from invokeai.backend.quantization.nvfp4 import NVFP4Linear
# Not a known Qwen3 size, so the loader reads the head counts off the projections at its fixed head_dim of 128:
@@ -167,3 +173,108 @@ def test_an_fp4_mixed_encoder_loads_packed_and_encodes_like_its_dense_weights(
loader._ram_cache.make_room.assert_called_once()
(reserved,), _ = loader._ram_cache.make_room.call_args
assert rest + packed <= reserved < rest + packed + 1024
+
+
+# The real repacks rotate over 256-wide groups, which this 128-wide toy encoder cannot hold. The marker
+# carries the group size for exactly this reason -- a repack derotated with the wrong width runs and
+# generates noise -- and 64-wide repacks exist, so reading it is what the loader has to do.
+_INT8_GROUP = 64
+_INT8_MARKER = {"format": "int8_tensorwise", "convrot": True, "convrot_groupsize": _INT8_GROUP}
+
+
+def _quantize_convrot(weight: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
+ """Mirror of comfy-quants: rotate along the input dim, then per-output-channel int8.
+
+ Returns the codes, the scale, and the weight the loader has to reconstruct -- which is the
+ *dequantized* one, not the original: rounding to 127 levels is lossy, and comparing against the
+ original would be comparing against something no correct loader produces.
+ """
+ out_features, in_features = weight.shape
+ hadamard = build_regular_hadamard(_INT8_GROUP, dtype=weight.dtype)
+ rotated = (weight.view(out_features, in_features // _INT8_GROUP, _INT8_GROUP) @ hadamard.T).view(
+ out_features, in_features
+ )
+ scale = rotated.abs().amax(dim=1, keepdim=True) / 127.0
+ codes = torch.clamp(torch.round(rotated / scale), -128, 127).to(torch.int8)
+ restored = (codes.float() * scale).view(out_features, in_features // _INT8_GROUP, _INT8_GROUP) @ hadamard
+ return codes, scale.float(), restored.view(out_features, in_features)
+
+
+def _write_int8_checkpoint(tmp_path: Path) -> tuple[Path, dict[str, torch.Tensor]]:
+ """The int8 layout: codes, a per-output-row scale, a marker. Norms and embeddings stay dense,
+ exactly as the 8B repack ships them."""
+ torch.manual_seed(0)
+ tensors: dict[str, torch.Tensor] = {}
+ dense: dict[str, torch.Tensor] = {}
+ projections = {**NVFP4_PROJECTIONS, "self_attn.v_proj": (HIDDEN, HIDDEN)}
+ for name, shape in projections.items():
+ path = f"model.layers.0.{name}"
+ codes, scale, restored = _quantize_convrot(torch.randn(shape) * 0.05)
+ tensors[f"{path}.weight"] = codes
+ tensors[f"{path}.weight_scale"] = scale
+ tensors[f"{path}.comfy_quant"] = _marker_blob(_INT8_MARKER)
+ # W8A8 activation scales. This path dequantizes the weight and computes in the compute
+ # dtype, so there is nothing to apply them to; one Qwen3-VL repack ships 337 of them.
+ tensors[f"{path}.input_scale"] = torch.ones(shape[1])
+ dense[f"{path}.weight"] = restored
+
+ for key, tensor in {
+ "model.embed_tokens.weight": torch.randn(VOCAB, HIDDEN),
+ "model.layers.0.input_layernorm.weight": torch.rand(HIDDEN) + 0.5,
+ "model.layers.0.post_attention_layernorm.weight": torch.rand(HIDDEN) + 0.5,
+ "model.layers.0.self_attn.q_norm.weight": torch.rand(128) + 0.5,
+ "model.layers.0.self_attn.k_norm.weight": torch.rand(128) + 0.5,
+ "model.norm.weight": torch.rand(HIDDEN) + 0.5,
+ }.items():
+ tensors[key] = tensor
+ dense[key] = tensor
+
+ checkpoint = tmp_path / "qwen_3_8b_int8_convrot.safetensors"
+ save_file(tensors, checkpoint)
+ return checkpoint, dense
+
+
+def test_an_int8_convrot_encoder_stays_int8_resident_and_encodes_like_its_dense_weights(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ checkpoint, dense = _write_int8_checkpoint(tmp_path)
+ monkeypatch.setattr(z_image.TorchDevice, "choose_torch_device", lambda: torch.device("cpu"))
+ monkeypatch.setattr(z_image.TorchDevice, "choose_bfloat16_safe_dtype", lambda _device: torch.float32)
+ loader = object.__new__(Qwen3EncoderCheckpointLoader)
+ loader._ram_cache = SimpleNamespace(make_room=MagicMock())
+
+ def refuse(*_args, **_kwargs) -> int:
+ raise AssertionError("the scaled-fp8 fold must not see an int8 checkpoint")
+
+ monkeypatch.setattr(z_image, "_fold_comfy_scaled_weights", refuse)
+ config = Qwen3Encoder_Checkpoint_Config.model_construct(path=str(checkpoint), variant=Qwen3VariantType.Qwen3_8B)
+
+ model = loader._load_from_singlefile(config)
+
+ layer = model.model.layers[0]
+ for name in (*NVFP4_PROJECTIONS, "self_attn.v_proj"):
+ module = layer.get_submodule(name)
+ assert isinstance(module, Int8ConvrotLinear), name
+ # As stored. Cast to the compute dtype these would be bf16 integers, which loads and encodes noise.
+ assert module.weight.dtype is torch.int8, name
+ assert model.lm_head.weight is model.model.embed_tokens.weight
+
+ input_ids = torch.tensor([[1, 5, 7, 2, 30]])
+ with torch.no_grad():
+ encoded = model(input_ids=input_ids, output_hidden_states=True).hidden_states[-1]
+ expected = _dense_reference(dense)(input_ids=input_ids, output_hidden_states=True).hidden_states[-1]
+ assert torch.allclose(encoded, expected, atol=1e-4)
+
+ # One reservation, made before anything widened. Spelled out rather than bounded: the int8
+ # payloads charged one byte per code and their float32 scale column, the dense remainder charged
+ # float32, and the `.input_scale` activation scales charged nothing -- this path has nothing to
+ # apply them to, and left in the dict they would each cost `in_features` floats here. Reserving
+ # the decoded size instead would ask the cache to free four times what this load uses -- on the
+ # real 8B encoder, ~30GB for ~8.
+ shapes = [*NVFP4_PROJECTIONS.values(), (HIDDEN, HIDDEN)]
+ quantized_weights = {f"model.layers.0.{name}.weight" for name in (*NVFP4_PROJECTIONS, "self_attn.v_proj")}
+ codes_and_scales = sum(rows * columns + rows * 4 for rows, columns in shapes)
+ dense_bytes = sum(tensor.nelement() * 4 for key, tensor in dense.items() if key not in quantized_weights)
+ loader._ram_cache.make_room.assert_called_once()
+ (reserved,), _ = loader._ram_cache.make_room.call_args
+ assert reserved == codes_and_scales + dense_bytes
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.py
index aaad7f7dd4..1b5686e438 100644
--- a/tests/backend/model_manager/load/test_z_image_loader_boundaries.py
+++ b/tests/backend/model_manager/load/test_z_image_loader_boundaries.py
@@ -79,6 +79,41 @@ def _driver(monkeypatch, tmp_path, state_dict: dict) -> tuple[ZImageCheckpointMo
return loader, config
+class _TinyMixedZImage(torch.nn.Module):
+ """Two blocks, so a checkpoint can be int8 in one and scaled fp8 in the other."""
+
+ def __init__(self, **_kwargs) -> None:
+ super().__init__()
+ self.layers = torch.nn.ModuleList([_TinyBlock(), _TinyBlock()])
+
+
+def test_a_mixed_int8_and_scaled_fp8_checkpoint_is_refused(monkeypatch, tmp_path) -> None:
+ """This branch skips the fp8 pipeline entirely, so an fp8 weight that came along would be cast
+ without its scale -- off by `1/weight_scale` -- while the orphaned scale disappears into the
+ load. Z-Image made exactly that mistake: it ran every other step of the int8 install and not
+ this check, and the result was a model that loaded cleanly and generated noise.
+ """
+ import diffusers
+
+ torch.manual_seed(0)
+ quantized, scale = _quantize_convrot(torch.randn(4, CONVROT_GROUP_SIZE))
+ state_dict = {
+ "layers.0.proj.weight": quantized,
+ "layers.0.proj.weight_scale": scale,
+ "layers.0.proj.comfy_quant": _marker_blob(MARKER),
+ "layers.1.proj.weight": torch.zeros(4, CONVROT_GROUP_SIZE, dtype=torch.float8_e4m3fn),
+ "layers.1.proj.weight_scale": torch.ones(()),
+ }
+ loader, config = _driver(monkeypatch, tmp_path, state_dict)
+ monkeypatch.setattr(diffusers, "ZImageTransformer2DModel", _TinyMixedZImage, raising=False)
+
+ with pytest.raises(ValueError, match=r"layers\.1\.proj\.weight_scale"):
+ loader._load_from_singlefile(config)
+
+ # Refused before the cache was asked to evict anything for a load that cannot finish.
+ loader._ram_cache.make_room.assert_not_called()
+
+
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)
diff --git a/tests/backend/pid/test_pid_int8.py b/tests/backend/pid/test_pid_int8.py
index ba13cac307..b580ac8f69 100644
--- a/tests/backend/pid/test_pid_int8.py
+++ b/tests/backend/pid/test_pid_int8.py
@@ -8,6 +8,7 @@ the 4x4 seed), then symmetric per-row int8 — rather than with the code under t
"""
import json
+import re
import pytest
import torch
@@ -123,6 +124,26 @@ def test_an_int8_checkpoint_keeps_its_block_linears_int8_and_decodes_like_the_de
torch.testing.assert_close(_forward(net), _forward(reference))
+def test_a_scale_from_another_scheme_is_refused_rather_than_loaded_unscaled(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The int8 branch runs no fp8 pipeline, so a scaled-fp8 layer that came along in a mixed repack
+ would have its weight copied into a float32 parameter *without* its scale -- off by
+ `1/weight_scale` -- while the orphaned scale is swallowed by the `strict=False` load. This path
+ ran every other step of the int8 install and not this check."""
+ torch.manual_seed(0)
+ state_dict, _ = _int8_checkpoint(_tiny_net())
+ net = _tiny_net()
+ # A Linear the net really has, so the check can tell it from a bundled submodel's keys.
+ foreign = next(name for name in _quantized_layers(net) if f"{name}.comfy_quant" in state_dict)
+ del state_dict[f"{foreign}.comfy_quant"]
+ state_dict[f"{foreign}.weight"] = state_dict[f"{foreign}.weight"].float().to(torch.float8_e4m3fn)
+ monkeypatch.setattr(pid_decode_module, "build_pid_net", lambda backbone, version: net)
+
+ with pytest.raises(ValueError, match=rf"{re.escape(foreign)}\.weight_scale"):
+ load_pid_decoder(state_dict, BaseModelType.Flux)
+
+
def test_an_int8_weight_no_marker_claims_is_refused(monkeypatch: pytest.MonkeyPatch) -> None:
"""Loaded as the float parameter it replaces, the raw codes would decode noise without any error — including
when no marker at all is left to put the loader on its int8 path."""
diff --git a/tests/backend/quantization/test_int8_convrot_state_dict.py b/tests/backend/quantization/test_int8_convrot_state_dict.py
index ba7258d4be..e5512c5479 100644
--- a/tests/backend/quantization/test_int8_convrot_state_dict.py
+++ b/tests/backend/quantization/test_int8_convrot_state_dict.py
@@ -14,10 +14,12 @@ from safetensors.torch import save_file
from invokeai.backend.quantization.int8_convrot import (
CONVROT_GROUP_SIZE,
+ Int8ConvrotLinear,
cast_unquantized,
check_int8_scale_layout,
drop_unconsumed_quantization_sidecars,
extract_int8_convrot_markers,
+ install_int8_convrot_layers,
predict_int8_cast_size,
read_comfy_quant_markers,
reject_foreign_quantization_scales,
@@ -380,6 +382,111 @@ class TestTheForeignScaleCheck:
reject_foreign_quantization_scales(sd, {}, "Ideogram 4", self._model())
+class TestTheSharedInstall:
+ """`install_int8_convrot_layers` owns the order the five steps have to run in.
+
+ Each loader used to write the sequence out by hand, and two of them wrote it out incompletely:
+ Z-Image and the PiD decoder both skipped the foreign-scale check and would cast a mixed
+ checkpoint's fp8 weights without their scales. The order is what these pin -- every step is
+ individually covered above, and a partial sequence raises nothing at all.
+ """
+
+ @staticmethod
+ def _model() -> torch.nn.Module:
+ model = torch.nn.Module()
+ model.keeps = torch.nn.Linear(CONVROT_GROUP_SIZE, 4, bias=False)
+ model.widens = torch.nn.Linear(CONVROT_GROUP_SIZE, 4, bias=False)
+ return model
+
+ @staticmethod
+ def _int8_layer(path: str) -> dict[str, torch.Tensor]:
+ return {
+ f"{path}.weight": torch.ones(4, CONVROT_GROUP_SIZE, dtype=torch.int8),
+ f"{path}.weight_scale": torch.ones(4, 1),
+ }
+
+ def test_a_foreign_scale_is_refused_before_a_single_byte_is_reserved(self) -> None:
+ """The reservation is the expensive step -- it evicts other models to make room. A load that
+ is about to be refused must not first ask the cache to free memory for it."""
+ sd = {**self._int8_layer("keeps"), "widens.weight": torch.zeros(4, 4, dtype=torch.float8_e4m3fn)}
+ sd["widens.weight_scale"] = torch.ones(())
+ reserved: list[int] = []
+
+ with pytest.raises(ValueError, match=r"widens\.weight_scale"):
+ install_int8_convrot_layers(
+ self._model(),
+ sd,
+ {"keeps": MARKER},
+ torch.float32,
+ architecture="Z-Image",
+ reserve=reserved.append,
+ )
+
+ assert reserved == []
+
+ def test_the_reservation_is_made_before_the_split_widens_anything(self) -> None:
+ """A locked model cannot be evicted, so the first reservation has to already cover the peak.
+ Reserving after the split lets its dequantized tensors land on an unreserved cache."""
+ sd = {**self._int8_layer("keeps"), **self._int8_layer("widens")}
+ widths: list[torch.dtype] = []
+
+ install_int8_convrot_layers(
+ self._model(),
+ sd,
+ {"keeps": MARKER, "widens": MARKER},
+ torch.float32,
+ architecture="Z-Image",
+ reserve=lambda _bytes: widths.append(sd["widens.weight"].dtype),
+ skip_patterns=("widens",),
+ )
+
+ assert widths == [torch.int8]
+ # And the split did run afterwards, or the assertion above would pass vacuously.
+ assert sd["widens.weight"].dtype is torch.float32
+
+ def test_only_the_surviving_layers_are_installed_and_returned(self) -> None:
+ """A marker on a layer the split widened must not reach the swap: it would install an
+ `Int8ConvrotLinear` over a weight that is no longer int8."""
+ model = self._model()
+ sd = {**self._int8_layer("keeps"), **self._int8_layer("widens")}
+
+ surviving = install_int8_convrot_layers(
+ model,
+ sd,
+ {"keeps": MARKER, "widens": MARKER},
+ torch.float32,
+ architecture="Z-Image",
+ reserve=lambda _bytes: None,
+ skip_patterns=("widens",),
+ )
+
+ assert set(surviving) == {"keeps"}
+ assert isinstance(model.keeps, Int8ConvrotLinear)
+ assert not isinstance(model.widens, Int8ConvrotLinear)
+
+ def test_the_reservation_charges_int8_its_byte_and_adds_the_caller_s_own_bytes(self) -> None:
+ """Krea-2 and Z-Image hold nvfp4 layers beside the int8 ones, so one reservation covers the
+ whole load. Spelled out rather than recomputed with `predict_int8_cast_size`: an expectation
+ derived from the implementation cannot notice the implementation charging the wrong width."""
+ reserved: list[int] = []
+
+ install_int8_convrot_layers(
+ self._model(),
+ self._int8_layer("keeps"),
+ {"keeps": MARKER},
+ torch.float32,
+ architecture="Z-Image",
+ reserve=reserved.append,
+ extra_reserved_bytes=4096,
+ )
+
+ # The layer stays int8, so it is charged one byte per code -- not float32's four -- plus its
+ # float32 scale column, plus what the caller asked for on top.
+ codes = 4 * CONVROT_GROUP_SIZE
+ scale = 4 * 4
+ assert reserved == [codes + scale + 4096]
+
+
def test_read_comfy_quant_markers_reads_a_marker_off_a_file(tmp_path) -> None:
"""The scheme, from the file rather than from a state dict.