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(pid): keep Comfy int8_convrot PiD decoders int8

Alexander Eichhornf28f4aa49534
diff --git a/docs/src/content/docs/features/pid-decode.mdx b/docs/src/content/docs/features/pid-decode.mdx
index 26c6b003b3..cc41cff505 100644
--- a/docs/src/content/docs/features/pid-decode.mdx
+++ b/docs/src/content/docs/features/pid-decode.mdx
@@ -41,12 +41,12 @@ PiD needs two extra models, both available in **Model Manager → Starter Models
2. The **Gemma 2 2B (PiD caption encoder)** — PiD uses it to condition the decode on your prompt. It installs automatically as a dependency of any PiD decoder, and is shared across all of them.
</Steps>
-A first-generation PiD decoder download is roughly 5 GB, a PiD 1.5 decoder download roughly 2.8 GB, and the shared Gemma-2 encoder is roughly 5 GB. Once loaded, both generations take about the same memory: the decoder runs in full precision.
+A first-generation PiD decoder download is roughly 5 GB, a PiD 1.5 decoder download roughly 2.8 GB (1.6 GB for its int8 build), and the shared Gemma-2 encoder is roughly 5 GB. Once loaded, a decoder runs in full precision and takes about 5.6 GB in either generation; the PiD 1.5 int8 build keeps its transformer layers in int8 and takes about 2 GB.
<Aside type="note">
Most Starter Models install NVIDIA's first-generation PiD checkpoints, which are spread over both the `checkpoints/` and the `checkpoints_deprecated/` folder of the `nvidia/PiD` repository depending on the backbone and preset. NVIDIA's second generation, **PiD 1.5**, exists for FLUX.1, FLUX.2 and Qwen-Image in the *2K-to-4K* preset. *PiD 1.5 Decoder Qwen-Image* is a Starter Model; the FLUX.1 and FLUX.2 decoders install from Comfy-Org's single files by URL, e.g. `https://huggingface.co/Comfy-Org/PixelDiT/resolve/main/diffusion_models/pid_1.5_flux2_1024_to_4096_4step_bf16.safetensors`. Both generations decode through the same nodes.
-Only the `_4step` builds work: the files without it are NVIDIA's undistilled teacher decoders, which need a different sampler, and are rejected during model identification — as are the `int8_convrot` builds, which are not supported yet.
+Only the `_4step` builds work: the files without it are NVIDIA's undistilled teacher decoders, which need a different sampler, and are rejected during model identification. The `_4step_int8_convrot` builds (*PiD 1.5 Decoder Qwen-Image (2K to 4K, int8)* is a Starter Model) keep the decoder's transformer layers in int8: about 2 GB once loaded instead of 5.6 GB, with output practically identical to the full-precision build.
</Aside>
The Gemma-2 caption encoder can also be a single-file **GGUF** (e.g. `gemma-2-2b-it-Q4_K_M.gguf`) that you install manually: InvokeAI loads it natively, keeping the large projection weights quantized instead of expanding them in memory, which cuts the encoder's footprint noticeably. Only Gemma-2-**2b** GGUFs are accepted — PiD's caption projection is fixed to their 2304-dim hidden state.
diff --git a/invokeai/app/invocations/pid/flux2_pid_decode.py b/invokeai/app/invocations/pid/flux2_pid_decode.py
index 1216a145df..449eaaeb46 100644
--- a/invokeai/app/invocations/pid/flux2_pid_decode.py
+++ b/invokeai/app/invocations/pid/flux2_pid_decode.py
@@ -210,6 +210,7 @@ class Flux2PiDDecodeInvocation(BaseInvocation, WithMetadata, WithBoard):
packed,
BaseModelType.Flux2,
pid_memory_optimization,
+ pid_net=pid_info.model,
)
with pid_info.model_on_device(working_mem_bytes=estimated_working_memory) as (_, pid_net):
if not isinstance(pid_net, PidNet):
diff --git a/invokeai/app/invocations/pid/flux_pid_decode.py b/invokeai/app/invocations/pid/flux_pid_decode.py
index a39b05cb9f..a084caecea 100644
--- a/invokeai/app/invocations/pid/flux_pid_decode.py
+++ b/invokeai/app/invocations/pid/flux_pid_decode.py
@@ -136,6 +136,7 @@ class FluxPiDDecodeInvocation(BaseInvocation, WithMetadata, WithBoard):
latents,
BaseModelType.Flux,
pid_memory_optimization,
+ pid_net=pid_info.model,
)
with pid_info.model_on_device(working_mem_bytes=estimated_working_memory) as (_, pid_net):
if not isinstance(pid_net, PidNet):
diff --git a/invokeai/app/invocations/pid/pid_upscale.py b/invokeai/app/invocations/pid/pid_upscale.py
index b44d83afd9..4ca46a8180 100644
--- a/invokeai/app/invocations/pid/pid_upscale.py
+++ b/invokeai/app/invocations/pid/pid_upscale.py
@@ -180,6 +180,7 @@ class PiDUpscaleInvocation(BaseInvocation, WithMetadata, WithBoard):
raw_latent,
BaseModelType.Flux,
pid_memory_optimization,
+ pid_net=pid_info.model,
)
with pid_info.model_on_device(working_mem_bytes=estimated_working_memory) as (_, pid_net):
if not isinstance(pid_net, PidNet):
diff --git a/invokeai/app/invocations/pid/qwen_image_pid_decode.py b/invokeai/app/invocations/pid/qwen_image_pid_decode.py
index 8af466b92b..83f5375ac0 100644
--- a/invokeai/app/invocations/pid/qwen_image_pid_decode.py
+++ b/invokeai/app/invocations/pid/qwen_image_pid_decode.py
@@ -202,6 +202,7 @@ class QwenImagePiDDecodeInvocation(BaseInvocation, WithMetadata, WithBoard):
latents,
BaseModelType.QwenImage,
pid_memory_optimization,
+ pid_net=pid_info.model,
)
with pid_info.model_on_device(working_mem_bytes=estimated_working_memory) as (_, pid_net):
if not isinstance(pid_net, PidNet):
diff --git a/invokeai/app/invocations/pid/sd3_pid_decode.py b/invokeai/app/invocations/pid/sd3_pid_decode.py
index ab7ee66c2c..03b2fe5d84 100644
--- a/invokeai/app/invocations/pid/sd3_pid_decode.py
+++ b/invokeai/app/invocations/pid/sd3_pid_decode.py
@@ -133,6 +133,7 @@ class SD3PiDDecodeInvocation(BaseInvocation, WithMetadata, WithBoard):
latents,
BaseModelType.StableDiffusion3,
pid_memory_optimization,
+ pid_net=pid_info.model,
)
with pid_info.model_on_device(working_mem_bytes=estimated_working_memory) as (_, pid_net):
if not isinstance(pid_net, PidNet):
diff --git a/invokeai/app/invocations/pid/sdxl_pid_decode.py b/invokeai/app/invocations/pid/sdxl_pid_decode.py
index 57e78725e0..fa34744f05 100644
--- a/invokeai/app/invocations/pid/sdxl_pid_decode.py
+++ b/invokeai/app/invocations/pid/sdxl_pid_decode.py
@@ -178,6 +178,7 @@ class SDXLPiDDecodeInvocation(BaseInvocation, WithMetadata, WithBoard):
latents,
BaseModelType.StableDiffusionXL,
pid_memory_optimization,
+ pid_net=pid_info.model,
)
with pid_info.model_on_device(working_mem_bytes=estimated_working_memory) as (_, pid_net):
if not isinstance(pid_net, PidNet):
diff --git a/invokeai/app/invocations/pid/z_image_pid_decode.py b/invokeai/app/invocations/pid/z_image_pid_decode.py
index 76c1a14f63..7d835ce4b1 100644
--- a/invokeai/app/invocations/pid/z_image_pid_decode.py
+++ b/invokeai/app/invocations/pid/z_image_pid_decode.py
@@ -179,6 +179,7 @@ class ZImagePiDDecodeInvocation(BaseInvocation, WithMetadata, WithBoard):
latents,
BaseModelType.Flux,
pid_memory_optimization,
+ pid_net=pid_info.model,
)
with pid_info.model_on_device(working_mem_bytes=estimated_working_memory) as (_, pid_net):
if not isinstance(pid_net, PidNet):
diff --git a/invokeai/backend/model_manager/configs/pid_decoder.py b/invokeai/backend/model_manager/configs/pid_decoder.py
index 078a8ee320..d8bc6408cb 100644
--- a/invokeai/backend/model_manager/configs/pid_decoder.py
+++ b/invokeai/backend/model_manager/configs/pid_decoder.py
@@ -12,6 +12,7 @@ preset; Comfy-Org repackages both generations as single safetensors files. See
import re
from collections.abc import Mapping
+from pathlib import Path
from typing import Any, Literal, Self
from pydantic import Field
@@ -31,7 +32,12 @@ from invokeai.backend.model_manager.taxonomy import (
ModelType,
PiDDecoderVariantType,
)
-from invokeai.backend.pid.state_dict_utils import PID_VERSION_BY_LQ_HIDDEN_DIM, PiDVersion, pid_net_shapes
+from invokeai.backend.pid.state_dict_utils import (
+ PID_VERSION_BY_LQ_HIDDEN_DIM,
+ PiDVersion,
+ pid_net_shapes,
+ strip_net_prefix,
+)
# Marker substring produced by `PidNet.lq_proj` (see
# invokeai/backend/pid/_src/networks/pid_net.py). The pretrained PixDiT_T2I
@@ -300,6 +306,80 @@ def _raise_if_named_undistilled(components: tuple[str, ...], folder_name: str) -
)
+def _int8_sidecar_keys(state_dict: dict[Any, Any], path: Path) -> set[str]:
+ """The keys of Comfy-Org's `int8_tensorwise` side channel, which the contract does not list; reject a quantization
+ `load_pid_decoder` would refuse.
+
+ Held to what the loader accepts, so an int8 build that registers also loads: every marked layer needs an int8
+ weight, a per-row or per-tensor `weight_scale`, and a marker declaring `int8_tensorwise` with a rotation group the
+ decode has a Hadamard for and that divides the layer's inputs; every int8 weight needs a marker. Anything else
+ decodes garbage or fails at every decode, and every config class would turn the file away for the same reason.
+
+ Dtypes and shapes come from the header identification reads. The markers' JSON does not — a header has no tensor
+ data — so it is read from the safetensors file itself, once the dtypes have shown the file is worth reading.
+ """
+ import torch
+
+ from invokeai.backend.quantization.fp8_scaled import COMFY_QUANT_SUFFIX
+ from invokeai.backend.quantization.int8_convrot import (
+ CONVROT_GROUP_SIZE,
+ INT8_TENSORWISE_FORMAT,
+ check_hadamard_size,
+ check_int8_scale_layout,
+ read_comfy_quant_markers,
+ )
+
+ stripped = strip_net_prefix(state_dict)
+ marked = {k[: -len(COMFY_QUANT_SUFFIX)] for k in stripped if isinstance(k, str) and k.endswith(COMFY_QUANT_SUFFIX)}
+ if not_int8 := sorted(
+ layer for layer in marked if getattr(stripped.get(f"{layer}.weight"), "dtype", None) is not torch.int8
+ ):
+ raise InvalidMatchError(
+ f"PiD checkpoint quantizes {len(not_int8)} layer(s) other than as int8, e.g. '{not_int8[0]}'; only "
+ "int8_tensorwise builds are supported."
+ )
+ if unmarked := sorted(
+ k
+ for k, v in stripped.items()
+ if getattr(v, "dtype", None) is torch.int8
+ and not (isinstance(k, str) and k.endswith(".weight") and k[: -len(".weight")] in marked)
+ ):
+ raise InvalidMatchError(
+ f"PiD checkpoint has {len(unmarked)} int8 weight(s) with no int8_tensorwise marker, e.g. {unmarked[:3]}."
+ )
+ if not marked:
+ return set()
+
+ try:
+ markers = strip_net_prefix(read_comfy_quant_markers(path))
+ except Exception as e:
+ raise InvalidMatchError(
+ f"PiD checkpoint marks {len(marked)} layer(s) int8, but its markers cannot be read from {path.name}: {e}"
+ ) from e
+ for layer in sorted(marked):
+ weight, scale, marker = (
+ stripped[f"{layer}.weight"],
+ stripped.get(f"{layer}.weight_scale"),
+ markers.get(layer, {}),
+ )
+ try:
+ if marker.get("format") != INT8_TENSORWISE_FORMAT:
+ raise ValueError(f"'{layer}' is marked {marker.get('format') or 'with an unreadable marker'}")
+ if scale is None:
+ raise ValueError(f"'{layer}' is missing its weight_scale")
+ check_int8_scale_layout(layer, weight, scale)
+ if marker.get("convrot", False):
+ group = int(marker.get("convrot_groupsize", CONVROT_GROUP_SIZE))
+ check_hadamard_size(group)
+ if weight.shape[-1] % group:
+ raise ValueError(
+ f"'{layer}' rotates groups of {group}, which do not divide its {weight.shape[-1]} inputs"
+ )
+ except ValueError as e:
+ raise InvalidMatchError(f"PiD int8 checkpoint cannot be loaded: {e}") from e
+ return {f"{layer}{suffix}" for layer in marked for suffix in (COMFY_QUANT_SUFFIX, ".weight_scale")}
+
+
class PiDDecoder_Checkpoint_Config_Base(Checkpoint_Config_Base):
"""Shared logic for PiD decoder checkpoint configs.
@@ -328,7 +408,8 @@ class PiDDecoder_Checkpoint_Config_Base(Checkpoint_Config_Base):
# no reason to load for the overwhelming majority of files.
from invokeai.backend.pid.decode import required_pid_net_shapes
- shapes = pid_net_shapes(state_dict)
+ sidecars = _int8_sidecar_keys(state_dict, mod.path)
+ shapes = {k: v for k, v in pid_net_shapes(state_dict).items() if k not in sidecars}
# Everything from here to `_validate_base` is backbone-independent: each of these rejects a file
# *every* PiD config class would reject for the same reason, which is exactly the case the plain
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 8483e5590d..135dfa8dcf 100644
--- a/invokeai/backend/model_manager/load/model_loaders/minimax_h3.py
+++ b/invokeai/backend/model_manager/load/model_loaders/minimax_h3.py
@@ -187,10 +187,10 @@ class MiniMaxH3CheckpointModel(ModelLoader):
)
from invokeai.backend.model_manager.load.model_loaders.minimax_h3_state_dict_utils import (
convert_minimax_h3_checkpoint_to_diffusers,
- read_comfy_quant_markers,
)
from invokeai.backend.quantization.int8_convrot import (
INT8_TENSORWISE_FORMAT,
+ read_comfy_quant_markers,
swap_in_int8_linears,
)
@@ -333,10 +333,10 @@ class MiniMaxH3TextEncoderCheckpointModel(ModelLoader):
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 (
INT8_TENSORWISE_FORMAT,
+ read_comfy_quant_markers,
swap_in_int8_linears,
)
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 e5eed5ead4..71a30e59a4 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
@@ -27,41 +27,11 @@ module renames it to the vendored diffusers-style
out to all three of ``to_q``/``to_k``/``to_v``).
"""
-import json
-import struct
-from pathlib import Path
from typing import Any
import torch
-from invokeai.backend.quantization.int8_convrot import parse_comfy_quant_bytes, parse_comfy_quant_marker
-
-
-def read_comfy_quant_markers(path: Path) -> dict[str, dict[str, Any]]:
- """Read every ``<layer>.comfy_quant`` marker from a safetensors file WITHOUT loading tensor
- data - header parse plus a seek per marker blob. Keys are the raw (un-renamed) layer names.
-
- Lets the loader reject unsupported quantization formats (e.g. the fp8_scaled repacks, which
- share this key layout) before committing to a ~20 GiB read.
-
- Marker bytes go through the same tolerant parser the state-dict readers use. This reader runs
- FIRST, so a strict parse here is what a NUL-padded marker -- which Comfy writes, and which that
- parser exists to absorb -- would actually hit: a `JSONDecodeError` out of the middle of a load,
- naming neither the file nor the key.
- """
- markers: dict[str, dict[str, Any]] = {}
- with open(path, "rb") as f:
- header_len = struct.unpack("<Q", f.read(8))[0]
- header = json.loads(f.read(header_len))
- header.pop("__metadata__", None)
- for key, entry in header.items():
- if not key.endswith(".comfy_quant"):
- continue
- start, end = entry["data_offsets"]
- f.seek(8 + header_len + start)
- markers[key[: -len(".comfy_quant")]] = parse_comfy_quant_bytes(f.read(end - start))
- return markers
-
+from invokeai.backend.quantization.int8_convrot import parse_comfy_quant_marker
_QKV_SUFFIXES = (".weight", ".weight_scale")
diff --git a/invokeai/backend/model_manager/starter_models/__init__.py b/invokeai/backend/model_manager/starter_models/__init__.py
index 83191a313e..2a0056c362 100644
--- a/invokeai/backend/model_manager/starter_models/__init__.py
+++ b/invokeai/backend/model_manager/starter_models/__init__.py
@@ -140,6 +140,7 @@ from invokeai.backend.model_manager.starter_models.minimax_h3 import (
)
from invokeai.backend.model_manager.starter_models.qwen_image import (
pid_1_5_decoder_qwenimage_2kto4k,
+ pid_1_5_decoder_qwenimage_2kto4k_int8,
pid_decoder_qwenimage_2kto4k,
qwen_image,
qwen_image_edit,
@@ -459,6 +460,7 @@ STARTER_MODELS: list[StarterModel] = [
pid_decoder_sdxl_2kto4k,
pid_decoder_qwenimage_2kto4k,
pid_1_5_decoder_qwenimage_2kto4k,
+ pid_1_5_decoder_qwenimage_2kto4k_int8,
]
sd1_bundle: list[StarterModel] = [
diff --git a/invokeai/backend/model_manager/starter_models/qwen_image.py b/invokeai/backend/model_manager/starter_models/qwen_image.py
index ac2f5b7f17..5b980d1b97 100644
--- a/invokeai/backend/model_manager/starter_models/qwen_image.py
+++ b/invokeai/backend/model_manager/starter_models/qwen_image.py
@@ -36,6 +36,17 @@ pid_1_5_decoder_qwenimage_2kto4k = StarterModel(
dependencies=[gemma2_2b_encoder],
)
+pid_1_5_decoder_qwenimage_2kto4k_int8 = StarterModel(
+ name="PiD 1.5 Decoder Qwen-Image (2K to 4K, int8)",
+ base=BaseModelType.QwenImage,
+ source="https://huggingface.co/Comfy-Org/PixelDiT/resolve/main/diffusion_models/pid_1.5_qwenimage_1024_to_4096_4step_int8_convrot.safetensors",
+ description="PiD 1.5 Qwen-Image decoder in Comfy-Org's int8_convrot build: its transformer layers stay int8, about 2GB once loaded instead of 5.6GB, with output practically identical to the full-precision build. ~1.6GB",
+ type=ModelType.PiDDecoder,
+ format=ModelFormat.Checkpoint,
+ variant=PiDDecoderVariantType.Res2kTo4k_Sr4x,
+ dependencies=[gemma2_2b_encoder],
+)
+
# region Qwen Image components (shared between Edit and txt2img variants)
qwen_image_vae = StarterModel(
name="Qwen Image VAE",
diff --git a/invokeai/backend/pid/decode.py b/invokeai/backend/pid/decode.py
index e493d05e3b..21bc315530 100644
--- a/invokeai/backend/pid/decode.py
+++ b/invokeai/backend/pid/decode.py
@@ -32,6 +32,13 @@ from torch import Tensor
from invokeai.backend.model_manager.taxonomy import BaseModelType
from invokeai.backend.pid._src.networks.pid_net import PidNet
from invokeai.backend.pid.state_dict_utils import PID_VERSION_BY_LQ_HIDDEN_DIM, PiDVersion
+from invokeai.backend.quantization.int8_convrot import (
+ extract_int8_convrot_markers,
+ peak_int8_dequant_transient_bytes,
+ reject_unmarked_int8_weights,
+ split_int8_convrot_layers,
+ swap_in_int8_linears,
+)
from invokeai.backend.util.logging import InvokeAILogger
_PID_ACTIVATION_CHUNK_SIZE = 1024
@@ -179,8 +186,26 @@ def estimate_pid_decode_working_memory(
latent: Tensor,
backbone: BaseModelType,
pid_memory_optimization: bool = False,
+ pid_net: torch.nn.Module | None = None,
) -> int:
- """Estimate the working memory in bytes for a PiD decode of *latent*.
+ """Estimate the working memory in bytes for a PiD decode of *latent* by *pid_net*.
+
+ The activations, plus — for an `int8_tensorwise` decoder — the weight its largest int8 Linear dequantizes per
+ forward, which the model's resident size does not cover. That weight materializes in the input's dtype, float32
+ at most. Returns 0 for unsupported backbones so callers fall back to the cache's default reservation.
+ """
+ activations = _estimate_pid_activation_memory(latent, backbone, pid_memory_optimization)
+ if activations == 0 or pid_net is None:
+ return activations
+ return activations + peak_int8_dequant_transient_bytes(pid_net, torch.float32)
+
+
+def _estimate_pid_activation_memory(
+ latent: Tensor,
+ backbone: BaseModelType,
+ pid_memory_optimization: bool = False,
+) -> int:
+ """Estimate the activation working memory in bytes for a PiD decode of *latent*.
Each decoded image is ``latent_spatial * sr_scale * latent_spatial_down_factor`` pixels per side. PidNet
runs in float32 (see ``model_loaders/pid_decoder.py``), so the element size is 4 bytes. The per-pixel term
@@ -306,6 +331,17 @@ def load_pid_decoder(state_dict: dict[Any, Tensor], backbone: BaseModelType) ->
+ (f" (+ {len(not_strings) - 5} more)" if len(not_strings) > 5 else "")
)
+ # Comfy-Org's `int8_tensorwise` builds keep their marked Linears int8. Each becomes an `Int8ConvrotLinear`
+ # whose `weight`/`weight_scale` buffers the load below fills with the stored tensors, so the contract's keys
+ # still match; the markers are taken out of *state_dict*. The dense tensors reach the float32 parameters
+ # through `load_state_dict`'s own copy.
+ int8_markers = extract_int8_convrot_markers(state_dict)
+ reject_unmarked_int8_weights(state_dict, int8_markers, "PiD")
+ if int8_markers:
+ swap_in_int8_linears(
+ net, state_dict, split_int8_convrot_layers(state_dict, int8_markers, torch.float32, model=net)
+ )
+
# strict=False so we can report missing and unexpected keys separately; both are fatal. The model
# cache builds loaders under `skip_torch_weight_init()`, which no-ops every `reset_parameters()`,
# so a key the checkpoint does not supply is left as uninitialised memory rather than a sane
diff --git a/invokeai/backend/quantization/int8_convrot.py b/invokeai/backend/quantization/int8_convrot.py
index a505661ebc..629bfeb037 100644
--- a/invokeai/backend/quantization/int8_convrot.py
+++ b/invokeai/backend/quantization/int8_convrot.py
@@ -35,7 +35,9 @@ for that, since the model's resident size does not account for it.
"""
import json
+import struct
from collections.abc import Iterable, Mapping
+from pathlib import Path
from typing import Any
import torch
@@ -152,6 +154,33 @@ def parse_comfy_quant_marker(blob: torch.Tensor) -> dict:
return parse_comfy_quant_bytes(raw)
+def read_comfy_quant_markers(path: Path) -> dict[str, dict[str, Any]]:
+ """Read every ``<layer>.comfy_quant`` marker from a safetensors file WITHOUT loading tensor
+ data - header parse plus a seek per marker blob. Keys are the raw (un-renamed) layer names.
+
+ Lets a loader reject unsupported quantization formats (e.g. the fp8_scaled repacks, which
+ share this key layout) before committing to a ~20 GiB read, and model identification -- which
+ sees only a header's dtypes and shapes -- check what a marker declares.
+
+ Marker bytes go through the same tolerant parser the state-dict readers use. This reader runs
+ FIRST, so a strict parse here is what a NUL-padded marker -- which Comfy writes, and which that
+ parser exists to absorb -- would actually hit: a `JSONDecodeError` out of the middle of a load,
+ naming neither the file nor the key.
+ """
+ markers: dict[str, dict[str, Any]] = {}
+ with open(path, "rb") as f:
+ header_len = struct.unpack("<Q", f.read(8))[0]
+ header = json.loads(f.read(header_len))
+ header.pop("__metadata__", None)
+ for key, entry in header.items():
+ if not key.endswith(COMFY_QUANT_SUFFIX):
+ continue
+ start, end = entry["data_offsets"]
+ f.seek(8 + header_len + start)
+ markers[key[: -len(COMFY_QUANT_SUFFIX)]] = parse_comfy_quant_bytes(f.read(end - start))
+ return markers
+
+
def as_column_scale(weight: torch.Tensor, scale: torch.Tensor) -> torch.Tensor:
"""A per-output-channel scale shaped `[out, 1]`, so it multiplies down the rows.
diff --git a/tests/app/invocations/test_pid_memory_optimization_wiring.py b/tests/app/invocations/test_pid_memory_optimization_wiring.py
index 4a6e45d50f..61f2bd178c 100644
--- a/tests/app/invocations/test_pid_memory_optimization_wiring.py
+++ b/tests/app/invocations/test_pid_memory_optimization_wiring.py
@@ -73,6 +73,18 @@ def test_pid_node_estimates_working_memory_for_the_same_mode_it_decodes_in(modul
)
[email protected]("module_path", _modules_constructing_a_decode_config(), ids=lambda p: p.stem)
+def test_pid_node_estimates_working_memory_for_the_decoder_it_loaded(module_path: Path) -> None:
+ """An int8_tensorwise decoder dequantizes a weight per forward that its resident size does not cover; the
+ estimate can only add it when it is handed the decoder."""
+ tree = ast.parse(module_path.read_text(encoding="utf-8"))
+ for call in _calls(tree, _ESTIMATE):
+ assert any(kw.arg == "pid_net" for kw in call.keywords), (
+ f"{module_path.name}:{call.lineno} estimates working memory without pid_net=; an int8 decoder's "
+ "dequant transient would not be reserved."
+ )
+
+
@pytest.mark.parametrize("module_path", _modules_constructing_a_decode_config(), ids=lambda p: p.stem)
def test_pid_node_reads_the_setting_exactly_once(module_path: Path) -> None:
"""The estimate and the decode must be fed from one read, so they cannot disagree."""
diff --git a/tests/backend/minimax_h3/test_pruned_transformer_and_converter.py b/tests/backend/minimax_h3/test_pruned_transformer_and_converter.py
index 33cdc97b00..65a86f2cc0 100644
--- a/tests/backend/minimax_h3/test_pruned_transformer_and_converter.py
+++ b/tests/backend/minimax_h3/test_pruned_transformer_and_converter.py
@@ -217,9 +217,7 @@ def test_converted_keys_match_full_model_exactly() -> None:
def test_read_comfy_quant_markers_from_header_only(tmp_path) -> None:
from safetensors.torch import save_file
- from invokeai.backend.model_manager.load.model_loaders.minimax_h3_state_dict_utils import (
- read_comfy_quant_markers,
- )
+ from invokeai.backend.quantization.int8_convrot import read_comfy_quant_markers
marker_json = b'{"format": "fp8_scaled", "convrot": false}'
path = tmp_path / "tiny.safetensors"
diff --git a/tests/backend/model_manager/configs/test_pid_decoder_config.py b/tests/backend/model_manager/configs/test_pid_decoder_config.py
index e01587c4f4..f5d6b3f847 100644
--- a/tests/backend/model_manager/configs/test_pid_decoder_config.py
+++ b/tests/backend/model_manager/configs/test_pid_decoder_config.py
@@ -203,6 +203,92 @@ def test_a_v1_5_file_whose_name_names_no_preset_is_2k_to_4k() -> None:
assert config.variant is PiDDecoderVariantType.Res2kTo4k_Sr4x
+_INT8_LAYER = "patch_blocks.0.attn.qkv_x"
+
+
+def _int8_v1_5_state_dict(
+ weight_dtype: torch.dtype = torch.int8, scale_shape: tuple[int, ...] | None = (4608, 1)
+) -> dict[str, object]:
+ """A v1.5 contract with one Linear in Comfy-Org's `int8_tensorwise` layout, as identification reads it off a
+ safetensors header: meta tensors with shapes and dtypes, and no data — the marker's bytes are not in it."""
+ sd = _pid_state_dict(version=PiDVersion.V1_5)
+ layer = f"{_NET_PREFIX}{_INT8_LAYER}"
+ sd[f"{layer}.weight"] = torch.empty(4608, 1536, dtype=weight_dtype, device="meta")
+ if scale_shape is not None:
+ sd[f"{layer}.weight_scale"] = torch.empty(*scale_shape, device="meta")
+ sd[f"{layer}.comfy_quant"] = torch.empty(72, dtype=torch.uint8, device="meta")
+ return sd
+
+
+def _int8_mod(root: Path, state_dict: dict[str, object], marker_format: str = "int8_tensorwise", group: int = 256):
+ """`_mock_mod` over a safetensors file holding the marker's bytes, which is where identification reads them."""
+ from safetensors.torch import save_file
+
+ mod = _mock_mod(root, state_dict, file_name="pid_1.5_qwenimage_1024_to_4096_4step_int8_convrot.safetensors")
+ marker = f'{{"format": "{marker_format}", "convrot": true, "convrot_groupsize": {group}}}'.encode()
+ save_file(
+ {f"{_NET_PREFIX}{_INT8_LAYER}.comfy_quant": torch.frombuffer(bytearray(marker), dtype=torch.uint8)}, mod.path
+ )
+ return mod
+
+
+def test_an_int8_tensorwise_v1_5_checkpoint_identifies() -> None:
+ """Its scales and markers are not PidNet parameters, but `load_pid_decoder` consumes them."""
+ with TemporaryDirectory() as tmpdir:
+ mod = _int8_mod(Path(tmpdir), _int8_v1_5_state_dict())
+ config = PiDDecoder_Checkpoint_QwenImage_Config.from_model_on_disk(
+ mod, dict(_OVERRIDE_FIELDS, base="qwen-image")
+ )
+ assert config.base is BaseModelType.QwenImage
+
+
+def test_a_checkpoint_quantized_in_another_format_is_rejected() -> None:
+ """The decode applies no fp8 scale, so such a layer would load off by its scale."""
+ with TemporaryDirectory() as tmpdir:
+ mod = _int8_mod(Path(tmpdir), _int8_v1_5_state_dict(weight_dtype=torch.float8_e4m3fn))
+ with pytest.raises(InvalidMatchError, match=f"1 layer\\(s\\) other than as int8, e.g. '{_INT8_LAYER}'"):
+ PiDDecoder_Checkpoint_FLUX_Config.from_model_on_disk(mod, dict(_OVERRIDE_FIELDS))
+
+
+ ("marker_format", "group", "scale_shape", "reason"),
+ [
+ ("float8_e4m3fn", 256, (4608, 1), "is marked float8_e4m3fn"),
+ ("int8_tensorwise", 256, None, "is missing its weight_scale"),
+ ("int8_tensorwise", 256, (48, 48), "Blockwise scale grids are not implemented"),
+ ("int8_tensorwise", 512, (4608, 1), "power of 4"),
+ ("int8_tensorwise", 1024, (4608, 1), "groups of 1024, which do not divide its 1536 inputs"),
+ ],
+ ids=["foreign_marker", "missing_scale", "blockwise_scale", "no_hadamard", "group_does_not_divide"],
+)
+def test_an_int8_build_the_loader_would_refuse_does_not_register(
+ marker_format: str, group: int, scale_shape: tuple[int, ...] | None, reason: str
+) -> None:
+ """Identification accepts exactly what `load_pid_decoder` accepts: a file registered here fails at every decode.
+ Each case is one the loader refuses, read off the header and the marker the file carries."""
+ with TemporaryDirectory() as tmpdir:
+ mod = _int8_mod(Path(tmpdir), _int8_v1_5_state_dict(scale_shape=scale_shape), marker_format, group)
+ with pytest.raises(InvalidMatchError, match=reason):
+ PiDDecoder_Checkpoint_FLUX_Config.from_model_on_disk(mod, dict(_OVERRIDE_FIELDS))
+
+
+def test_an_int8_build_whose_markers_cannot_be_read_does_not_register() -> None:
+ with TemporaryDirectory() as tmpdir:
+ mod = _mock_mod(Path(tmpdir), _int8_v1_5_state_dict())
+ with pytest.raises(InvalidMatchError, match="markers cannot be read"):
+ PiDDecoder_Checkpoint_FLUX_Config.from_model_on_disk(mod, dict(_OVERRIDE_FIELDS))
+
+
+def test_an_int8_weight_no_marker_claims_is_rejected() -> None:
+ """Loaded as the float parameter it replaces, the raw codes would decode noise without any error."""
+ sd = _int8_v1_5_state_dict()
+ del sd[f"{_NET_PREFIX}patch_blocks.0.attn.qkv_x.comfy_quant"]
+ with TemporaryDirectory() as tmpdir:
+ mod = _mock_mod(Path(tmpdir), sd)
+ with pytest.raises(InvalidMatchError, match="1 int8 weight\\(s\\) with no int8_tensorwise marker"):
+ PiDDecoder_Checkpoint_FLUX_Config.from_model_on_disk(mod, dict(_OVERRIDE_FIELDS))
+
+
def test_an_lq_width_no_generation_has_is_rejected_as_an_architecture() -> None:
with TemporaryDirectory() as tmpdir:
mod = _mock_mod(Path(tmpdir), _pid_state_dict(lq_hidden_dim=768))
@@ -390,9 +476,8 @@ class TestUnusableCheckpointIsNeverRegistered:
"""Intact but for an LQ width no generation has: every config class would reject it for that reason."""
return _real_pid_state_dict(lq_hidden_dim=768)
- def _int8_convrot_v1_5(self) -> dict[str, object]:
- """Comfy-Org's `pid_1.5_*_int8_convrot` builds carry a scale and a marker beside each int8 weight. Loading
- such a weight as the float parameter it replaces decodes garbage, so the file must not register."""
+ def _marker_beside_a_float_weight(self) -> dict[str, object]:
+ """A quantization marker on a layer whose weight is not int8 names a scale the decode would never apply."""
sd = _real_pid_state_dict(version=PiDVersion.V1_5)
sd[f"{_NET_PREFIX}patch_blocks.0.attn.qkv_x.weight_scale"] = torch.ones(())
sd[f"{_NET_PREFIX}patch_blocks.0.attn.qkv_x.comfy_quant"] = torch.zeros(28, dtype=torch.uint8)
@@ -428,7 +513,7 @@ class TestUnusableCheckpointIsNeverRegistered:
("_missing_backbone_weight", "missing 1 of the weights required by PidNet"),
("_truncated_v1_5", "missing 1 of the weights required by PidNet"),
("_unknown_architecture", "lq_proj hidden dim 768"),
- ("_int8_convrot_v1_5", "2 keys PidNet does not expect"),
+ ("_marker_beside_a_float_weight", "quantizes 1 layer(s) other than as int8"),
("_unsupported_latent_channels", "32 latent channels"),
("_malformed_discriminator", "malformed lq_proj.latent_proj.0.weight"),
("_bare_with_a_non_string_key", "2 keys PidNet does not expect"),
diff --git a/tests/backend/model_manager/load/test_minimax_h3_int8_loading.py b/tests/backend/model_manager/load/test_minimax_h3_int8_loading.py
index 05536e605c..f2ec2544bc 100644
--- a/tests/backend/model_manager/load/test_minimax_h3_int8_loading.py
+++ b/tests/backend/model_manager/load/test_minimax_h3_int8_loading.py
@@ -22,9 +22,12 @@ from safetensors.torch import save_file
from invokeai.backend.minimax_h3.transformer_minimax_h3 import MiniMaxH3AttnProcessor
from invokeai.backend.model_manager.configs.main import Main_Checkpoint_MiniMaxH3_Config
from invokeai.backend.model_manager.load.model_loaders.minimax_h3 import MiniMaxH3CheckpointModel
-from invokeai.backend.model_manager.load.model_loaders.minimax_h3_state_dict_utils import read_comfy_quant_markers
from invokeai.backend.model_manager.taxonomy import MiniMaxH3VariantType
-from invokeai.backend.quantization.int8_convrot import Int8ConvrotLinear, build_regular_hadamard
+from invokeai.backend.quantization.int8_convrot import (
+ Int8ConvrotLinear,
+ build_regular_hadamard,
+ read_comfy_quant_markers,
+)
@pytest.fixture(autouse=True)
diff --git a/tests/backend/pid/test_pid_int8.py b/tests/backend/pid/test_pid_int8.py
new file mode 100644
index 0000000000..ba13cac307
--- /dev/null
+++ b/tests/backend/pid/test_pid_int8.py
@@ -0,0 +1,148 @@
+"""Comfy-Org's `int8_tensorwise` PiD builds: the marked Linears stay int8 and decode like the dense ones.
+
+`pid_1.5_*_int8_convrot` stores each patch- and pixel-block Linear as int8 codes rotated along the input dimension,
+with a per-row float32 scale and a `comfy_quant` marker. The rotation group differs per layer — 256 for the 1536-wide
+patch blocks, 64 for the 1152-wide pixel attention — so the tiny net below mixes two groups the same way. The
+reference quantizes it the way the scheme is defined — a grouped matmul with the regular Hadamard (Kronecker powers of
+the 4x4 seed), then symmetric per-row int8 — rather than with the code under test.
+"""
+
+import json
+
+import pytest
+import torch
+
+from invokeai.backend.model_manager.taxonomy import BaseModelType
+from invokeai.backend.pid import decode as pid_decode_module
+from invokeai.backend.pid._src.networks.pid_net import PidNet
+from invokeai.backend.pid.decode import estimate_pid_decode_working_memory, load_pid_decoder
+from invokeai.backend.quantization.int8_convrot import Int8ConvrotLinear
+
+_SEED = torch.tensor([[1, 1, 1, -1], [1, 1, -1, 1], [1, -1, 1, 1], [-1, 1, 1, 1]], dtype=torch.float32) / 2
+# Normalized regular Hadamards: symmetric and orthonormal, so each is its own inverse.
+_HADAMARDS = {4: _SEED, 16: torch.kron(_SEED, _SEED)}
+
+
+def _tiny_net() -> PidNet:
+ net = PidNet(
+ in_channels=3,
+ num_groups=2,
+ hidden_size=16,
+ pixel_hidden_size=4,
+ pixel_attn_hidden_size=8,
+ pixel_num_groups=2,
+ patch_depth=2,
+ pixel_depth=1,
+ num_text_blocks=1,
+ patch_size=2,
+ txt_embed_dim=6,
+ txt_max_length=4,
+ rope_mode="original",
+ rope_ref_h=4,
+ rope_ref_w=4,
+ lq_in_channels=0,
+ lq_latent_channels=2,
+ lq_hidden_dim=4,
+ lq_num_res_blocks=1,
+ lq_interval=1,
+ sr_scale=1,
+ latent_spatial_down_factor=2,
+ ).eval()
+ with torch.no_grad():
+ # The backbone zero-inits its final layer, which would make every output zero.
+ torch.nn.init.normal_(net.final_layer.linear.weight)
+ return net
+
+
+def _group_size(in_features: int) -> int | None:
+ """The widest rotation group that divides the layer, as Comfy-Org picks it per layer."""
+ return next((group for group in sorted(_HADAMARDS, reverse=True) if in_features % group == 0), None)
+
+
+def _quantized_layers(net: PidNet) -> dict[str, int]:
+ return {
+ name: group
+ for name, module in net.named_modules()
+ if isinstance(module, torch.nn.Linear)
+ and name.startswith(("patch_blocks.", "pixel_blocks."))
+ and (group := _group_size(module.in_features)) is not None
+ }
+
+
+def _int8_checkpoint(net: PidNet) -> tuple[dict[str, torch.Tensor], dict[str, torch.Tensor]]:
+ """The net's state dict with its block Linears quantized, and the weights those codes decode to."""
+ state_dict = {k: v.clone() for k, v in net.state_dict().items()}
+ decoded = {}
+ for layer, group in _quantized_layers(net).items():
+ weight = state_dict[f"{layer}.weight"]
+ out_features, in_features = weight.shape
+ hadamard = _HADAMARDS[group]
+ rotated = (weight.view(out_features, in_features // group, group) @ hadamard).view(weight.shape)
+ scale = rotated.abs().amax(dim=1, keepdim=True).clamp_min(1e-8) / 127
+ codes = torch.round(rotated / scale).clamp(-127, 127).to(torch.int8)
+ marker = {"format": "int8_tensorwise", "convrot": True, "convrot_groupsize": group}
+ state_dict[f"{layer}.weight"] = codes
+ state_dict[f"{layer}.weight_scale"] = scale
+ state_dict[f"{layer}.comfy_quant"] = torch.frombuffer(bytearray(json.dumps(marker).encode()), dtype=torch.uint8)
+ grouped = (codes.float() * scale).view(out_features, in_features // group, group)
+ decoded[f"{layer}.weight"] = (grouped @ hadamard).view(weight.shape)
+ return state_dict, decoded
+
+
+def _forward(net: PidNet) -> torch.Tensor:
+ torch.manual_seed(3)
+ with torch.no_grad():
+ return net(
+ torch.randn(1, 3, 4, 4),
+ torch.tensor([500.0]),
+ torch.randn(1, 4, 6),
+ lq_latent=torch.randn(1, 2, 2, 2),
+ degrade_sigma=torch.tensor([0.3]),
+ )
+
+
+def test_an_int8_checkpoint_keeps_its_block_linears_int8_and_decodes_like_the_dense_net(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ torch.manual_seed(0)
+ source = _tiny_net()
+ state_dict, decoded = _int8_checkpoint(source)
+ reference = _tiny_net()
+ reference.load_state_dict(source.state_dict() | decoded)
+ monkeypatch.setattr(pid_decode_module, "build_pid_net", lambda backbone, version: _tiny_net())
+
+ net = load_pid_decoder(dict(state_dict), BaseModelType.Flux)
+
+ layers = _quantized_layers(source)
+ assert set(layers.values()) == {4, 16}, "the fixture must mix rotation groups, as the released files do"
+ for layer, group in layers.items():
+ module = net.get_submodule(layer)
+ assert isinstance(module, Int8ConvrotLinear), layer
+ assert module.weight.dtype is torch.int8, layer
+ assert module.group_size == group, layer
+ torch.testing.assert_close(_forward(net), _forward(reference))
+
+
+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."""
+ torch.manual_seed(0)
+ state_dict, _ = _int8_checkpoint(_tiny_net())
+ state_dict = {k: v for k, v in state_dict.items() if not k.endswith((".comfy_quant", ".weight_scale"))}
+ monkeypatch.setattr(pid_decode_module, "build_pid_net", lambda backbone, version: _tiny_net())
+
+ with pytest.raises(ValueError, match="no `comfy_quant` marker"):
+ load_pid_decoder(state_dict, BaseModelType.Flux)
+
+
+def test_the_working_memory_estimate_reserves_the_int8_dequant_transient_on_top() -> None:
+ """The largest int8 Linear dequantizes at float32 — the dtype PidNet runs in — on top of the activations."""
+ decoder = torch.nn.Module()
+ decoder.small = Int8ConvrotLinear(torch.zeros(8, 4, dtype=torch.int8), torch.ones(8, 1), convrot=False)
+ decoder.large = Int8ConvrotLinear(torch.zeros(16, 8, dtype=torch.int8), torch.ones(16, 1), convrot=False)
+ latent = torch.zeros(1, 16, 64, 64)
+
+ dense = estimate_pid_decode_working_memory(latent, BaseModelType.Flux)
+
+ assert estimate_pid_decode_working_memory(latent, BaseModelType.Flux, pid_net=decoder) > dense
+ assert estimate_pid_decode_working_memory(latent, BaseModelType.Flux, pid_net=torch.nn.Linear(4, 4)) == dense