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(krea2): load ComfyUI int4 convrot transformer builds (#9817)

Alexander Eichhorn8f5e113f1107
diff --git a/docs/src/content/docs/Users Guide/03.Models/02.model-families.mdx b/docs/src/content/docs/Users Guide/03.Models/02.model-families.mdx
index a8cea058fb..a99c137869 100644
--- a/docs/src/content/docs/Users Guide/03.Models/02.model-families.mdx
+++ b/docs/src/content/docs/Users Guide/03.Models/02.model-families.mdx
@@ -34,7 +34,7 @@ Newer models are often distributed in **quantized** forms, which
store the weights at reduced precision to save disk space and
VRAM. InvokeAI recognizes several of these, including **GGUF** files
(named for their quantization level, such as `Q4_K_M` or `Q8_0`),
-**fp8**, **int8** and **nf4** builds. Like other single-file
+**fp8**, **int8**, **int4** and **nf4** builds. Like other single-file
checkpoints, a quantized file usually carries only the transformer
and needs separately installed companions. Lower precision trades a
little image quality for a large saving in memory; each model family's
@@ -44,10 +44,11 @@ page lists the builds it supports.
InvokeAI recognizes the format from the file's contents, so you install them like any other model. Which format loads for which model is listed in [Model Format Support](/users-guide/models/model-format-support/).
-- **GGUF** (`.gguf`, llama.cpp quantization such as Q4_K or Q8_0): weights stay packed in memory and are unpacked layer by layer during generation. Supported for the FLUX.1, FLUX.2, FLUX.3, Z-Image, Krea-2, Qwen-Image, Qwen-Image-2.1, Ideogram 4, ERNIE-Image and Wan transformers, and for the T5, Qwen3, Qwen3-VL, Mistral and Gemma 2 text encoders. ComfyUI-GGUF's `Q8_CR` files, which store int8 (`int8_convrot`) layers inside a `.gguf`, load for the Krea-2 transformer; for other models, and for ComfyUI-GGUF's `Q4_CR`, installation is refused with a message saying so.
+- **GGUF** (`.gguf`, llama.cpp quantization such as Q4_K or Q8_0): weights stay packed in memory and are unpacked layer by layer during generation. Supported for the FLUX.1, FLUX.2, FLUX.3, Z-Image, Krea-2, Qwen-Image, Qwen-Image-2.1, Ideogram 4, ERNIE-Image and Wan transformers, and for the T5, Qwen3, Qwen3-VL, Mistral and Gemma 2 text encoders. ComfyUI-GGUF's `Q8_CR` and `Q4_CR` files, which store int8 or int4 convrot layers inside a `.gguf`, load for the Krea-2 transformer; for other models installation is refused with a message saying so.
- **NF4** (bitsandbytes): 4-bit, CUDA only.
- **SDNQ**: see [SDNQ Quantization](/configuration/optimization/sdnq-quantization/).
- **int8** (`int8_convrot`, from ComfyUI repackages): the weights stay int8 in memory on every device, including Apple Silicon, and need no setting to turn on. Supported for FLUX.1, FLUX.2 Klein, Z-Image, Anima, Krea-2, Qwen-Image-2.1, Ideogram 4, MiniMax H3, LTX-2 and the PiD decoders, and for the Qwen3 4B and 8B, Qwen3-VL and LTX-2 Gemma encoders.
+- **int4** (`convrot_w4a4` or `int4_tensorwise`, ComfyUI repackages that usually keep some layers int8): the weights stay packed in memory at half a byte each and are unpacked per layer, on every device. This saves memory, not time: InvokeAI unpacks the weights for every step rather than running 4-bit matrix kernels, and 4-bit weights keep less detail than int8. Supported for the Krea-2 transformer.
- **nvfp4** (4-bit, in ComfyUI's checkpoint format, such as Comfy-Org's builds; other nvfp4 exports such as AWQ are refused): the weights stay packed in memory and are unpacked per layer, so no special GPU is needed. Supported for the Z-Image, Krea-2, Qwen-Image and LTX-2 transformers and for the Qwen3, Qwen2.5-VL and FLUX.2 Mistral encoders; the Ideogram 4 and Qwen-Image-2.1 nvfp4 files are refused at install.
- **fp8** (plain or `fp8_scaled`): InvokeAI keeps the weights in fp8 when [FP8 Storage](/configuration/optimization/fp8-storage/) is on, which installation does for you, or when `fp8_compute` is enabled.
- **MXFP8** (fp8 with one scale per block of 32 weights): loaded by unpacking to BF16. Turn FP8 Storage off for these; see the [FP8 Storage caution](/configuration/optimization/fp8-storage/).
diff --git a/docs/src/content/docs/Users Guide/03.Models/03.model-format-support.mdx b/docs/src/content/docs/Users Guide/03.Models/03.model-format-support.mdx
index 2efa19c3e5..20a618ae1f 100644
--- a/docs/src/content/docs/Users Guide/03.Models/03.model-format-support.mdx
+++ b/docs/src/content/docs/Users Guide/03.Models/03.model-format-support.mdx
@@ -26,33 +26,36 @@ Others are recognized by their layer names and fail, or misbehave, only when the
## Main models
-| Family | Diffusers | Single file (bf16) | fp8 scaled | int8 | nvfp4 | MXFP8 | GGUF | SDNQ | NF4 |
-|---|---|---|---|---|---|---|---|---|---|
-| [SD 1.x / 2.x](/users-guide/models/local-models/stable-diffusion-1-2/), [SDXL](/users-guide/models/local-models/sdxl/) | ✓ | ✓ | ✗ | ✗ | ✗ | ✗ | R | ✗ | ✗ |
-| [SD 3](/users-guide/models/local-models/sd-3/) | ✓ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ |
-| [FLUX.1](/users-guide/models/local-models/flux-1/) | ✓ | ✓ | ✓ | ✓ | ✗ | ✓ | ✓ | ✓ | ✓ |
-| [FLUX.2](/users-guide/models/local-models/flux-2/) | ✓ | ✓ | ✓ | ✓ | ✗ | ✓ | ✓ | ✓ | inside the Diffusers folder (FLUX.2 [dev]) |
-| [FLUX.3](/users-guide/models/local-models/flux-3/) | ✓ | ✓ | R | R | R | – | ✓ | – | – |
-| [CogView4](/users-guide/models/local-models/cogview4/) | ✓ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ |
-| [Z-Image](/users-guide/models/local-models/z-image/) | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✗ |
-| [Qwen-Image](/users-guide/models/local-models/qwen-image/) | ✓ | ✓ | ✓ | ✗ | ✓ | ✓ | ✓ | ✗ | ✗ |
-| [Qwen-Image-2.1](/users-guide/models/local-models/qwen-image-2-1/) | ✓ | ✓ | ✓ | ✓ | R | – | ✓ | ✗ | ✗ |
-| [Anima](/users-guide/models/local-models/anima/) | – | ✓ | ✓ | ✓ | ✗ | ✓ | ✓ | ✗ | ✗ |
-| [Krea-2](/users-guide/models/local-models/krea-2/) | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✗ | ✗ |
-| [Ideogram 4](/users-guide/models/local-models/ideogram4/) | ✓ | ✓ | ✓ | ✓ | R | ✓ | ✓ | ✗ | inside the Diffusers folder |
-| [ERNIE-Image](/users-guide/models/local-models/ernie-image/) | ✓ | ✓ | L | L | L | ✗ | ✓ | ✗ | ✗ |
-| [MOSS-Image](/users-guide/models/local-models/moss-image/) | ✓ | ✓ | R | R | R | R | R | ✗ | ✗ |
-| [Wan 2.2](/users-guide/video-generation/wan-22/) | ✓ | ✓ | ✓ | L | L | L | ✓ | ✗ | ✗ |
-| [LTX-2](/users-guide/video-generation/ltx-2/) (2.5 only) | official layout ✓, Diffusers layout ✗ | ✓ | L | ✓ | ✓ | ✗ | ✓ | ✗ | ✗ |
-| [MiniMax H3](/users-guide/video-generation/minimax-h3/) | ✓ | ✓ | L | ✓ | L | ✗ | ✗ | ✗ | ✗ |
+| Family | Diffusers | Single file (bf16) | fp8 scaled | int8 | int4 | nvfp4 | MXFP8 | GGUF | SDNQ | NF4 |
+|---|---|---|---|---|---|---|---|---|---|---|
+| [SD 1.x / 2.x](/users-guide/models/local-models/stable-diffusion-1-2/), [SDXL](/users-guide/models/local-models/sdxl/) | ✓ | ✓ | ✗ | ✗ | ✗ | ✗ | ✗ | R | ✗ | ✗ |
+| [SD 3](/users-guide/models/local-models/sd-3/) | ✓ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ |
+| [FLUX.1](/users-guide/models/local-models/flux-1/) | ✓ | ✓ | ✓ | ✓ | L | ✗ | ✓ | ✓ | ✓ | ✓ |
+| [FLUX.2](/users-guide/models/local-models/flux-2/) | ✓ | ✓ | ✓ | ✓ | L | ✗ | ✓ | ✓ | ✓ | inside the Diffusers folder (FLUX.2 [dev]) |
+| [FLUX.3](/users-guide/models/local-models/flux-3/) | ✓ | ✓ | R | R | R | R | – | ✓ | – | – |
+| [CogView4](/users-guide/models/local-models/cogview4/) | ✓ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ |
+| [Z-Image](/users-guide/models/local-models/z-image/) | ✓ | ✓ | ✓ | ✓ | L | ✓ | ✓ | ✓ | ✓ | ✗ |
+| [Qwen-Image](/users-guide/models/local-models/qwen-image/) | ✓ | ✓ | ✓ | ✗ | ✗ | ✓ | ✓ | ✓ | ✗ | ✗ |
+| [Qwen-Image-2.1](/users-guide/models/local-models/qwen-image-2-1/) | ✓ | ✓ | ✓ | ✓ | R | R | – | ✓ | ✗ | ✗ |
+| [Anima](/users-guide/models/local-models/anima/) | – | ✓ | ✓ | ✓ | L | ✗ | ✓ | ✓ | ✗ | ✗ |
+| [Krea-2](/users-guide/models/local-models/krea-2/) | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✗ | ✗ |
+| [Ideogram 4](/users-guide/models/local-models/ideogram4/) | ✓ | ✓ | ✓ | ✓ | R | R | ✓ | ✓ | ✗ | inside the Diffusers folder |
+| [ERNIE-Image](/users-guide/models/local-models/ernie-image/) | ✓ | ✓ | L | L | L | L | ✗ | ✓ | ✗ | ✗ |
+| [MOSS-Image](/users-guide/models/local-models/moss-image/) | ✓ | ✓ | R | R | R | R | R | R | ✗ | ✗ |
+| [Wan 2.2](/users-guide/video-generation/wan-22/) | ✓ | ✓ | ✓ | L | L | L | L | ✓ | ✗ | ✗ |
+| [LTX-2](/users-guide/video-generation/ltx-2/) (2.5 only) | official layout ✓, Diffusers layout ✗ | ✓ | L | ✓ | L | ✓ | ✗ | ✓ | ✗ | ✗ |
+| [MiniMax H3](/users-guide/video-generation/minimax-h3/) | ✓ | ✓ | L | ✓ | L | L | ✗ | ✗ | ✗ | ✗ |
- **int8** means ComfyUI's `int8_convrot` (`int8_tensorwise`) builds; on NVIDIA GPUs, [int8 Compute](/configuration/optimization/int8-compute/)
- runs them on the int8 tensor cores. **nvfp4** and **fp8 scaled** mean ComfyUI's
- checkpoint layouts; other exports of the same schemes (AWQ, ModelOpt) fail when the model loads. For Qwen-Image-2.1,
- torchao exports such as unsloth's FP8 build are refused at install. MOSS-Image refuses every quantized
- transformer at install, unscaled fp8 included.
-- **GGUF** covers the llama.cpp types (Q4_0 through Q8_0, the K-quants, BF16). ComfyUI-GGUF's `Q8_CR` files load
- for Krea-2 only; for every other model with GGUF support the install fails.
+ runs them on the int8 tensor cores. **int4** means their packed 4-bit counterparts, `convrot_w4a4` and
+ `int4_tensorwise`, which most builds mix with int8 layers. **nvfp4** and **fp8 scaled** mean ComfyUI's checkpoint
+ layouts; other exports of the same schemes (AWQ, ModelOpt) fail when the model loads. For Qwen-Image-2.1, torchao
+ exports such as unsloth's FP8 build are refused at install. MOSS-Image refuses every quantized transformer at
+ install, unscaled fp8 included. ComfyUI's other low-bit layouts (`w4a8`, `w6a8`, SVDQuant) are not supported;
+ Krea-2 refuses them at install.
+- **GGUF** covers the llama.cpp types (Q4_0 through Q8_0, the K-quants, BF16). ComfyUI-GGUF's `Q8_CR` (int8) and
+ `Q4_CR` (int4) files load for Krea-2 only; for every other model with GGUF support the install fails, as it does
+ for `Q4_CR` files of ComfyUI-GGUF's retired W4A16 kind.
- LTX-2.0/2.3 files, GGUF builds included, fail to install with a message. Wan 2.1, Wan Animate, S2V, Fun-Control
and VACE single files and GGUFs are not recognized as Wan 2.2 and install as unknown models; a Wan 2.1 Diffusers
folder is not detected and is not supported either.
diff --git a/docs/src/content/docs/Users Guide/03.Models/Local Models/krea-2.mdx b/docs/src/content/docs/Users Guide/03.Models/Local Models/krea-2.mdx
index aa51e7e3d3..a6551dbcb9 100644
--- a/docs/src/content/docs/Users Guide/03.Models/Local Models/krea-2.mdx
+++ b/docs/src/content/docs/Users Guide/03.Models/Local Models/krea-2.mdx
@@ -37,15 +37,17 @@ Krea-2 is a large model. See the [System Requirements](/start-here/system-requir
details. In short, on a 24 GB card enable **FP8** in the model's Default Settings to fit 1024² (with a
LoRA). For lower VRAM, use a smaller transformer build:
-| Transformer build | Transformer size | Notes |
-| ------------------------------------ | ---------------- | ------------------------------------------------------------- |
-| NVFP4 (starter model) | ≈ 7.2 GiB | stays packed, unpacked per layer on any GPU |
-| GGUF Q4_K_M (starter model) | ≈ 7 GB | stays packed, unpacked per layer |
-| GGUF Q8_0 (starter model) | ≈ 13 GB | near-full quality |
-| int8 (`int8_convrot`, starter model) | ≈ 12.6 GiB | stays int8 on every device, no FP8 setting needed |
-| GGUF Q8_CR (ComfyUI-GGUF) | ≈ 12.8 GiB | the same int8 inside a `.gguf`, stays int8 on every device |
-| fp8 / `fp8_scaled` (starter model) | ≈ 12.2 GiB | with FP8 Storage (switched on at install) or `fp8_compute` |
-| MXFP8 | ≈ 24 GB | unpacked to BF16 at load; prefer the fp8, NVFP4 or GGUF build |
+| Transformer build | Transformer size | Notes |
+| ---------------------------------------- | ---------------- | ------------------------------------------------------------------------------------ |
+| NVFP4 (starter model) | ≈ 7.2 GiB | stays packed, unpacked per layer on any GPU |
+| GGUF Q4_K_M (starter model) | ≈ 7 GB | stays packed, unpacked per layer |
+| GGUF Q8_0 (starter model) | ≈ 13 GB | near-full quality |
+| int8 (`int8_convrot`, starter model) | ≈ 12.6 GiB | stays int8 on every device, no FP8 setting needed |
+| int4 (`convrot_w4a4`, `int4_tensorwise`) | ≈ 6.4–9.6 GiB | stays packed on every device; most builds keep some layers int8, which sets the size |
+| GGUF Q8_CR (ComfyUI-GGUF) | ≈ 12.8 GiB | the same int8 inside a `.gguf`, stays int8 on every device |
+| GGUF Q4_CR (ComfyUI-GGUF) | ≈ 7.0 GiB | the same int4 inside a `.gguf` |
+| fp8 / `fp8_scaled` (starter model) | ≈ 12.2 GiB | with FP8 Storage (switched on at install) or `fp8_compute` |
+| MXFP8 | ≈ 24 GB | unpacked to BF16 at load; prefer the fp8, NVFP4 or GGUF build |
The Qwen3-VL encoder and the small VAE come on top of these sizes. The encoder takes about 8.5 GB as bf16
(the starter bundle's encoder), about half that as fp8, and about 2.8 GB as a Q4_K_M
@@ -60,7 +62,7 @@ Krea-2 needs three components:
| Component | Diffusers install | GGUF / single-file install |
| ----------------------- | ----------------------- | ------------------------------------ |
-| Transformer | bundled in the pipeline | the `.gguf` / single-file checkpoint (GGUF, fp8, int8, NVFP4, MXFP8) |
+| Transformer | bundled in the pipeline | the `.gguf` / single-file checkpoint (GGUF, fp8, int8, int4, NVFP4, MXFP8) |
| VAE (Qwen-Image) | bundled | installed separately |
| Text encoder (Qwen3-VL) | bundled | installed separately |
@@ -95,7 +97,7 @@ encoder closely; the remaining difference is the quantization of the encoder.
- The `mmproj-*.gguf` file next to it holds the vision part and is not needed for text-to-image. Installing
it is refused with a message saying so. Without the vision part, a GGUF encoder cannot encode the
reference images of [edit LoRAs](#edit-loras-and-reference-images).
-- ComfyUI-GGUF's `Q8_CR` encoder files are refused at install; only the transformer loads from `Q8_CR`.
+- ComfyUI-GGUF's `Q8_CR` and `Q4_CR` encoder files are refused at install; only the transformer loads from them.
- LoRAs with text-encoder layers still apply to a quantized encoder.
## Conditioning enhancers
@@ -169,7 +171,7 @@ feeding the **Style Reference** input of **Denoise - Krea-2**.
## LoRA
Krea-2 LoRAs (diffusers PEFT format) are supported and apply to both the transformer and — where the
-LoRA includes text-encoder layers — the Qwen3-VL encoder. On quantized builds (GGUF, int8, NVFP4) the LoRA
+LoRA includes text-encoder layers — the Qwen3-VL encoder. On quantized builds (GGUF, int8, int4, NVFP4) the LoRA
is applied alongside the packed weights rather than merged into them. LoRAs trained to edit an input image
need reference images; see [Edit LoRAs](#edit-loras-and-reference-images).
diff --git a/docs/src/content/docs/contributing/new-model-integration.mdx b/docs/src/content/docs/contributing/new-model-integration.mdx
index c398394b89..32ded7daf6 100644
--- a/docs/src/content/docs/contributing/new-model-integration.mdx
+++ b/docs/src/content/docs/contributing/new-model-integration.mdx
@@ -419,6 +419,10 @@ Loaders turn a config into an in-memory model. Every module in this folder is im
- stripping the ComfyUI prefix with `CheckpointPrefix.detect(sd).strip(sd)` (`invokeai/backend/model_manager/checkpoint_prefix.py`) rather than a hand-written loop
- reserving RAM before materializing, exactly once: build the empty model first, take the fp8 and nvfp4 side channels out of the state dict, then reserve, and only then fold or widen anything. A fold before the reservation lands on a cache that was never asked for the room. For fp8, nvfp4 and dense files the reservation is `reserve_for_load` (`invokeai/backend/quantization/load_plan.py`).
- quantized formats: ComfyUI `fp8_scaled`, `int8_convrot` and `nvfp4` (helpers in `invokeai/backend/quantization/`), and GGUF through `gguf_sd_loader`. For int8, call `install_int8_convrot_layers` instead of its individual steps. It makes the reservation itself through its `reserve` argument, so do not also call `reserve_for_load`; the steps' order matters, and skipping the first one loads a mixed checkpoint's fp8 weights without their scale.
+ - ComfyUI's packed int4 layers (`convrot_w4a4`, `int4_tensorwise`) install through the same call. Opt in only once a real int4 build of the model has been checked, and opt in everywhere the format is decided, as the Krea-2 loader and config do, or install and load disagree about the same file:
+ - pass `accept_int4=True` to `extract_int8_convrot_markers`, and pass the safetensors header (`header_layers=`) to it and to `reject_unmarked_int8_weights`: some converters name their layers only there;
+ - refuse at install what the loader cannot decode with `_raise_for_undecodable_int8_weights` in `configs/main.py`, given the same formats (`accepted_convrot_formats(accept_int4=True)`) and `read_header=True`;
+ - for GGUF, set the config's `DECODES_GGUF_CONVROT` to the same formats and load with `gguf_sd_loader(..., convrot="decode")`.
- a loader that handles no quantization side channel (a VAE, an adapter, a non-strict `load_state_dict`) calls `reject_quantized_side_channel` so a quantized file is refused rather than loaded wrongly
- opting into FP8 storage with `_apply_fp8_layerwise_casting`
diff --git a/invokeai/backend/model_manager/configs/base.py b/invokeai/backend/model_manager/configs/base.py
index 72b56bb884..a72b67b94c 100644
--- a/invokeai/backend/model_manager/configs/base.py
+++ b/invokeai/backend/model_manager/configs/base.py
@@ -102,9 +102,11 @@ class Config_Base(ABC, BaseModel):
"""Set of all non-abstract subclasses of Config_Base, for use during model probing. In other words, this is the set
of all known model config types."""
- DECODES_GGUF_Q8_CR: ClassVar[bool] = False
- """Whether this config's loader decodes ComfyUI-GGUF ``Q8_CR`` (int8 convrot) layers. Off by default, so a GGUF
- config refuses those files at install until its loader asks ``gguf_sd_loader`` to decode them."""
+ DECODES_GGUF_CONVROT: ClassVar[frozenset[str]] = frozenset()
+ """The marker formats this config's loader decodes from ComfyUI-GGUF's convrot layers, as
+ ``accepted_convrot_formats`` names them: ``Q8_CR`` arrives as ``int8_tensorwise`` and ``Q4_CR`` as
+ ``int4_tensorwise``. Empty by default, so a GGUF config refuses those files at install until its loader asks
+ ``gguf_sd_loader`` to decode them -- and the int4 ones until it also opts into int4."""
model_config = ConfigDict(
validate_assignment=True,
diff --git a/invokeai/backend/model_manager/configs/factory.py b/invokeai/backend/model_manager/configs/factory.py
index 9b770fbbde..c73fe3afe6 100644
--- a/invokeai/backend/model_manager/configs/factory.py
+++ b/invokeai/backend/model_manager/configs/factory.py
@@ -232,7 +232,7 @@ from invokeai.backend.model_manager.taxonomy import (
ModelType,
variant_type_adapter,
)
-from invokeai.backend.quantization.gguf.loaders import COMFY_QUANT_KEY_PREFIX, parse_q8_cr_markers
+from invokeai.backend.quantization.gguf.loaders import COMFY_QUANT_KEY_PREFIX, parse_gguf_convrot_markers
logger = logging.getLogger(__name__)
@@ -738,20 +738,29 @@ class ModelConfigFactory:
if getattr(config, "format", None) is not ModelFormat.GGUFQuantized:
return
metadata = mod.metadata()
- if not type(config).DECODES_GGUF_Q8_CR:
+ decodes = type(config).DECODES_GGUF_CONVROT
+ if not decodes:
# Nothing this config's loader runs decodes any of the converter's schemes, so whatever its
# JSON says is beside the point -- parsing it first would report a detail of the scheme (a
# marker on a tensor that is not a weight, say) in place of the reason the file is refused.
if any(key.startswith(COMFY_QUANT_KEY_PREFIX) for key in metadata):
raise InvalidMatchError(
- f"{mod.path.name} uses ComfyUI-GGUF's own quantization (Q8_CR or similar), which this model "
- "type cannot load yet. Use a GGML-quantized (Q8_0, Q4_K, ...) or safetensors build instead."
+ f"{mod.path.name} uses ComfyUI-GGUF's own quantization (Q8_CR, Q4_CR or similar), which this "
+ "model type cannot load yet. Use a GGML-quantized (Q8_0, Q4_K, ...) or safetensors build instead."
)
return
try:
- parse_q8_cr_markers(metadata, mod.path.name)
+ markers = parse_gguf_convrot_markers(metadata, mod.path.name)
except ValueError as e:
raise InvalidMatchError(str(e)) from None
+ undecodable = sorted({m["format"] for m in markers.values()} - decodes)
+ if undecodable:
+ names = {"int8_tensorwise": "Q8_CR", "int4_tensorwise": "Q4_CR"}
+ kinds = " and ".join(names.get(fmt, fmt) for fmt in undecodable)
+ raise InvalidMatchError(
+ f"{mod.path.name} is a ComfyUI-GGUF convrot ({kinds}) file, which this model type cannot load "
+ "yet. Use a GGML-quantized (Q8_0, Q4_K, ...) or safetensors build instead."
+ )
@staticmethod
def from_dict(fields: dict[str, Any]) -> AnyModelConfig:
diff --git a/invokeai/backend/model_manager/configs/main.py b/invokeai/backend/model_manager/configs/main.py
index 4ec3005c48..38bc32af06 100644
--- a/invokeai/backend/model_manager/configs/main.py
+++ b/invokeai/backend/model_manager/configs/main.py
@@ -73,9 +73,17 @@ from invokeai.backend.model_manager.taxonomy import (
WanVariantType,
ZImageVariantType,
)
-from invokeai.backend.quantization.fp8_scaled import FP8_WEIGHT_DTYPES, is_scale_metadata_key
+from invokeai.backend.quantization.fp8_scaled import (
+ FP8_WEIGHT_DTYPES,
+ is_scale_metadata_key,
+ parse_quantization_metadata,
+)
from invokeai.backend.quantization.gguf.ggml_tensor import GGMLTensor
-from invokeai.backend.quantization.int8_convrot import INT8_TENSORWISE_FORMAT, read_comfy_quant_markers
+from invokeai.backend.quantization.int8_convrot import (
+ accepted_convrot_formats,
+ int8_weights_without_a_decodable_marker,
+ read_comfy_quant_markers,
+)
from invokeai.backend.quantization.sdnq.detection import is_sdnq_folder
from invokeai.backend.quantization.sdnq.sdnq_tensor import SDNQTensor
@@ -1616,6 +1624,59 @@ def _ideogram4_branch_or_raise(mod: ModelOnDisk) -> Ideogram4Branch:
return branch
+def _raise_for_undecodable_int8_weights(
+ mod: ModelOnDisk,
+ state_dict: dict[str | int, Any],
+ formats: frozenset[str],
+ *,
+ read_header: bool,
+ what: str,
+ supported: str,
+ discarded: tuple[str, ...] = (),
+) -> None:
+ """Refuse at install the int8 weights a checkpoint loader decoding ``formats`` would refuse at load.
+
+ `InvalidMatchError`, not `NotAMatchError`: the file *is* this model, so the installer shows the reason
+ instead of registering an unknown model -- or a model that installs, pulls in its starter dependencies and
+ fails at the first render. Identification has every dtype but no tensor bytes, so the markers are read from
+ the file: one header parse plus a seek per marker, and only for a file with int8 weights to explain.
+ ``read_header`` mirrors whether the loader also reads ``_quantization_metadata``, and ``discarded`` the
+ layers it drops before reading any marker.
+ """
+ if not any(
+ isinstance(key, str) and key.endswith(".weight") and getattr(value, "dtype", None) is torch.int8
+ for key, value in state_dict.items()
+ ):
+ return
+ try:
+ markers = read_comfy_quant_markers(mod.path)
+ except Exception:
+ # Not readable safetensors, so there are no markers to find and nothing explains the int8 weights. The
+ # refusal below is the right answer for that file too.
+ markers = {}
+ header_layers = parse_quantization_metadata(mod.metadata()) if read_header else {}
+ try:
+ undecodable = int8_weights_without_a_decodable_marker(
+ state_dict, markers, header_layers, formats, discarded=discarded
+ )
+ except ValueError as e:
+ raise InvalidMatchError(str(e)) from None
+ if not undecodable:
+ return
+ example = sorted(undecodable)[0]
+ declared = sorted({fmt for fmt in undecodable.values() if fmt is not None})
+ if declared:
+ raise InvalidMatchError(
+ f"{len(undecodable)} int8 weight(s) in this {what} are marked {', '.join(map(repr, declared))} (e.g. "
+ f"'{example}'), which InvokeAI cannot load for this model. {supported}"
+ )
+ raise InvalidMatchError(
+ f"{len(undecodable)} int8 weight(s) in this {what} carry no readable marker of a format it loads "
+ f"({', '.join(map(repr, sorted(formats)))}; e.g. '{example}'), so the quantization scheme cannot be "
+ f"identified. {supported}"
+ )
+
+
def _raise_for_unsupported_comfy_quantization(mod: ModelOnDisk, state_dict: dict[str | int, Any], family: str) -> None:
"""Refuse the ComfyUI quantization schemes the Ideogram 4 and Qwen-Image-2.1 single-file loaders cannot build.
@@ -1654,29 +1715,16 @@ def _raise_for_unsupported_comfy_quantization(mod: ModelOnDisk, state_dict: dict
"Install the fp8_scaled or int8_convrot build instead."
)
- int8_weights = sorted(
- key
- for key, value in state_dict.items()
- if isinstance(key, str) and key.endswith(".weight") and getattr(value, "dtype", None) is torch.int8
+ # Per-tensor `.comfy_quant` markers only: neither the Ideogram 4 nor the Qwen-Image-2.1 loader reads the
+ # `_quantization_metadata` header.
+ _raise_for_undecodable_int8_weights(
+ mod,
+ state_dict,
+ accepted_convrot_formats(accept_int4=False),
+ read_header=False,
+ what=f"{family} transformer",
+ supported="Only Comfy-Org's int8_convrot build is supported.",
)
- if not int8_weights:
- return
-
- try:
- markers = read_comfy_quant_markers(mod.path)
- except Exception:
- # Not readable safetensors, so there are no markers to find and nothing explains the
- # int8 weights. The refusal below is the right answer for that file too.
- markers = {}
- unmarked = [
- key for key in int8_weights if markers.get(key[: -len(".weight")], {}).get("format") != INT8_TENSORWISE_FORMAT
- ]
- if unmarked:
- raise InvalidMatchError(
- f"{len(unmarked)} int8 weight(s) in this {family} transformer carry no readable "
- f"'{INT8_TENSORWISE_FORMAT}' marker (e.g. '{unmarked[0]}'), so the quantization scheme "
- "cannot be identified. Only Comfy-Org's int8_convrot build is supported."
- )
class Main_Checkpoint_Ideogram4_Config(Checkpoint_Config_Base, Main_Config_Base, Config_Base):
@@ -2183,6 +2231,12 @@ def _ltx2_transformer_identity(
return generation, LTX2VariantType(variant)
+# The original final-block up/down projections have no counterpart in the diffusers ``Krea2FinalLayer`` (a
+# clean AdaLN + linear). The Krea-2 loaders drop them before reading any quantization marker, so identification
+# leaves them out of its quantization check too.
+KREA2_DISCARDED_NATIVE_FINAL_LAYERS = ("last.down", "last.up")
+
+
class Main_Checkpoint_Krea2_Config(Checkpoint_Config_Base, Main_Config_Base, Config_Base):
"""Model config for Krea-2 single-file checkpoint models (safetensors, etc)."""
@@ -2203,6 +2257,20 @@ class Main_Checkpoint_Krea2_Config(Checkpoint_Config_Base, Main_Config_Base, Con
cls._validate_does_not_look_like_gguf_quantized(mod)
+ # What `Krea2CheckpointModel` would refuse at load, refused here: an int8 layer the file does not mark as
+ # int8 or int4 convrot -- Starnodes' w4a8, w6a8, SVDQuant or AWQ builds, a torchao repack -- or marks
+ # only ambiguously in its header. The loader reads both the per-tensor markers and the header, and drops
+ # the final-block projections before it reads either.
+ _raise_for_undecodable_int8_weights(
+ mod,
+ mod.load_state_dict(),
+ accepted_convrot_formats(accept_int4=True),
+ read_header=True,
+ discarded=KREA2_DISCARDED_NATIVE_FINAL_LAYERS,
+ what="Krea-2 transformer",
+ supported="The int8 and int4 convrot builds (int8_tensorwise, convrot_w4a4, int4_tensorwise) are supported.",
+ )
+
variant = override_fields.pop("variant", None) or _get_krea2_variant_from_name(mod.path.name)
return cls(**override_fields, variant=variant)
@@ -2221,7 +2289,7 @@ class Main_Checkpoint_Krea2_Config(Checkpoint_Config_Base, Main_Config_Base, Con
class Main_GGUF_Krea2_Config(Checkpoint_Config_Base, Main_Config_Base, Config_Base):
"""Model config for GGUF-quantized Krea-2 transformer models (single-file)."""
- DECODES_GGUF_Q8_CR: ClassVar[bool] = True
+ DECODES_GGUF_CONVROT: ClassVar[frozenset[str]] = accepted_convrot_formats(accept_int4=True)
base: Literal[BaseModelType.Krea2] = Field(default=BaseModelType.Krea2)
format: Literal[ModelFormat.GGUFQuantized] = Field(default=ModelFormat.GGUFQuantized)
diff --git a/invokeai/backend/model_manager/load/model_cache/torch_module_autocast/custom_modules/custom_dequantizing_linear.py b/invokeai/backend/model_manager/load/model_cache/torch_module_autocast/custom_modules/custom_dequantizing_linear.py
index 8c5f15fd76..1a6245d0f7 100644
--- a/invokeai/backend/model_manager/load/model_cache/torch_module_autocast/custom_modules/custom_dequantizing_linear.py
+++ b/invokeai/backend/model_manager/load/model_cache/torch_module_autocast/custom_modules/custom_dequantizing_linear.py
@@ -8,7 +8,7 @@ from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.custo
CustomModuleMixin,
)
from invokeai.backend.quantization.dequantizing_linear import DequantizingLinear
-from invokeai.backend.quantization.int8_convrot import Int8ConvrotLinear
+from invokeai.backend.quantization.int8_convrot import Int4ConvrotLinear, Int8ConvrotLinear
from invokeai.backend.quantization.nvfp4 import NVFP4Linear
@@ -40,7 +40,7 @@ class CustomDequantizingLinear(DequantizingLinear, CustomModuleMixin):
def _cast_weight_bias_for_input(self, input: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor | None]:
# A meta tensor lets patch types without an optimized sidecar path read the weight's shape but never its
# quantized values; LoRA layers take the residual path and never get here. Patches are reshaped to this
- # shape, so it has to be the unpacked one, which the weight buffer's is not for nvfp4.
+ # shape, so it has to be the unpacked one, which the weight buffer's is not for nvfp4 or int4.
weight = torch.empty((self.out_features, self.in_features), device="meta")
bias = self._cast_tensor_for_input(self.bias, input)
return weight, bias
@@ -64,5 +64,9 @@ class CustomInt8ConvrotLinear(CustomDequantizingLinear, Int8ConvrotLinear):
pass
+class CustomInt4ConvrotLinear(CustomDequantizingLinear, Int4ConvrotLinear):
+ pass
+
+
class CustomNVFP4Linear(CustomDequantizingLinear, NVFP4Linear):
pass
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 684b87f708..cbd60e1b37 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
@@ -11,6 +11,7 @@ from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.custo
CustomConv2d,
)
from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.custom_modules.custom_dequantizing_linear import (
+ CustomInt4ConvrotLinear,
CustomInt8ConvrotLinear,
CustomNVFP4Linear,
)
@@ -36,7 +37,7 @@ from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.custo
CustomModuleMixin,
)
from invokeai.backend.quantization.bnb_import import record_bnb_import_failure
-from invokeai.backend.quantization.int8_convrot import Int8ConvrotLinear
+from invokeai.backend.quantization.int8_convrot import Int4ConvrotLinear, Int8ConvrotLinear
from invokeai.backend.quantization.nvfp4 import NVFP4Linear
AUTOCAST_MODULE_TYPE_MAPPING: dict[type[torch.nn.Module], type[torch.nn.Module]] = {
@@ -49,6 +50,7 @@ AUTOCAST_MODULE_TYPE_MAPPING: dict[type[torch.nn.Module], type[torch.nn.Module]]
FluxRMSNorm: CustomFluxRMSNorm,
DiffusersRMSNorm: CustomDiffusersRMSNorm,
Int8ConvrotLinear: CustomInt8ConvrotLinear,
+ Int4ConvrotLinear: CustomInt4ConvrotLinear,
NVFP4Linear: CustomNVFP4Linear,
}
diff --git a/invokeai/backend/model_manager/load/model_loaders/krea2.py b/invokeai/backend/model_manager/load/model_loaders/krea2.py
index 37d5d35156..bd111f1032 100644
--- a/invokeai/backend/model_manager/load/model_loaders/krea2.py
+++ b/invokeai/backend/model_manager/load/model_loaders/krea2.py
@@ -12,7 +12,11 @@ from transformers import AutoConfig, AutoTokenizer
from invokeai.backend.model_manager.checkpoint_prefix import CheckpointPrefix
from invokeai.backend.model_manager.configs.base import Checkpoint_Config_Base, Diffusers_Config_Base
from invokeai.backend.model_manager.configs.factory import AnyModelConfig
-from invokeai.backend.model_manager.configs.main import Main_Checkpoint_Krea2_Config, Main_GGUF_Krea2_Config
+from invokeai.backend.model_manager.configs.main import (
+ KREA2_DISCARDED_NATIVE_FINAL_LAYERS,
+ Main_Checkpoint_Krea2_Config,
+ Main_GGUF_Krea2_Config,
+)
from invokeai.backend.model_manager.configs.qwen3_vl_encoder import (
Qwen3VLEncoder_Checkpoint_Config,
Qwen3VLEncoder_GGUF_Config,
@@ -65,6 +69,7 @@ from invokeai.backend.quantization.int8_convrot import (
drop_unconsumed_quantization_sidecars,
extract_int8_convrot_markers,
install_int8_convrot_layers,
+ marker_layout,
reject_unmarked_int8_weights,
resolve_quantized_module_paths,
split_int8_convrot_layers,
@@ -119,6 +124,12 @@ def _put_unique_key(
source_of[key] = source
+def _int4_int8_split(markers: dict[str, dict[str, Any]]) -> str:
+ """How the kept quantized layers divide into packed int4 and int8, for the load log."""
+ int4 = sum(marker_layout(marker).packed_int4 for marker in markers.values())
+ return f"{int4} int4, {len(markers) - int4} int8"
+
+
def _is_native_krea2_format(sd: dict[str, Any]) -> bool:
"""Detect the native/ComfyUI Krea-2 key naming (e.g. GGUF) vs. the diffusers naming."""
return any(
@@ -154,13 +165,6 @@ def _remap_native_layer_paths(layer_names: Any) -> dict[str, str]:
return mapping
-# 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.
@@ -169,7 +173,7 @@ def _drop_discarded_native_final_layers(sd: dict[str, Any]) -> dict[str, Any]:
"""
doomed = {
f"{path}{suffix}"
- for path in DISCARDED_NATIVE_FINAL_KEYS
+ for path in KREA2_DISCARDED_NATIVE_FINAL_LAYERS
for suffix in (".weight", ".weight_scale", WEIGHT_SCALE_2_SUFFIX, ".comfy_quant", *INPUT_SCALE_SUFFIXES)
}
if not doomed & set(sd):
@@ -209,7 +213,7 @@ def _convert_krea2_native_to_diffusers(sd: dict[str, Any], *, key_map: dict[str,
_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 tuple(f"{p}.weight" for p in DISCARDED_NATIVE_FINAL_KEYS):
+ if key in tuple(f"{p}.weight" for p in KREA2_DISCARDED_NATIVE_FINAL_LAYERS):
continue
k = key
@@ -478,8 +482,10 @@ class Krea2CheckpointModel(ModelLoader):
The int8 build stays int8-resident: `swap_in_int8_linears` installs `Int8ConvrotLinear`, which
holds the stored codes and dequantizes per forward, so a 12.0 GiB checkpoint stays 12.0 GiB.
What it does not get is int8 *compute* -- that needs a kernel InvokeAI does not have yet -- so
- the saving here is resident memory, not speed. ComfyUI's 'nvfp4' build, whose layers the
- safetensors header names, stays packed the same way as `NVFP4Linear`.
+ the saving here is resident memory, not speed. The packed int4 builds (`convrot_w4a4`,
+ `int4_tensorwise`), usually mixed with int8 layers, stay packed the same way as
+ `Int4ConvrotLinear`; some name their layers only in the safetensors header. ComfyUI's 'nvfp4'
+ build, whose layers the header names too, stays packed as `NVFP4Linear`.
"""
def _load_model(
@@ -534,12 +540,14 @@ class Krea2CheckpointModel(ModelLoader):
# from the marker that says it is rotated. Taken down the fp8 path instead, such a weight
# would be scaled but never un-rotated -- a state dict that loads cleanly and generates
# noise.
- int8_markers = extract_int8_convrot_markers(sd)
+ # The packed int4 layouts are recognised here too, and from the header as well as per tensor: the
+ # Starnodes converter writes its int4 and int8 builds with the header entries alone.
+ int8_markers = extract_int8_convrot_markers(sd, accept_int4=True, header_layers=header_layers)
# Outside the branch on purpose -- see the helper, which explains why. Z-Image has always
# had this; Krea-2 did not, so an int8 weight whose marker was missing or unparseable was
# cast to the compute dtype as raw codes and loaded silently.
- reject_unmarked_int8_weights(sd, int8_markers, "Krea-2")
+ reject_unmarked_int8_weights(sd, int8_markers, "Krea-2", header_layers=header_layers)
if int8_markers:
sd = drop_unconsumed_quantization_sidecars(sd)
@@ -623,8 +631,8 @@ class Krea2CheckpointModel(ModelLoader):
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)"
+ f"Krea-2: kept {len(quantized)} of {len(int8_markers)} layer(s) quantized "
+ f"({_int4_int8_split(quantized)}; dequantized per forward)"
)
# The fp8 reporting below is keyed on these; an int8 checkpoint keeps neither.
fp8_layers = {}
@@ -742,8 +750,9 @@ class Krea2GGUFCheckpointModel(ModelLoader):
GGUF ships only the transformer; the VAE (Qwen-Image), Qwen3-VL encoder, tokenizer and scheduler
are sourced separately by the Krea-2 model-loader invocation (mix-and-match, like Z-Image/FLUX).
The GGML tensors stay quantized and are dequantized on-the-fly during inference. ComfyUI-GGUF's
- ``Q8_CR`` layers arrive from `gguf_sd_loader` as an ``int8_tensorwise`` export and stay int8 as
- `Int8ConvrotLinear`, beside whatever GGML-quantized layers the same file mixes in.
+ ``Q8_CR`` and ``Q4_CR`` layers arrive from `gguf_sd_loader` as an ``int8_tensorwise`` or
+ ``int4_tensorwise`` export and stay quantized as `Int8ConvrotLinear` or `Int4ConvrotLinear`, beside
+ whatever GGML-quantized layers the same file mixes in.
"""
def _load_model(
@@ -770,16 +779,17 @@ class Krea2GGUFCheckpointModel(ModelLoader):
compute_dtype = TorchDevice.choose_bfloat16_safe_dtype(target_device)
# GGMLTensor wrappers (kept on CPU; dequantized on-the-fly by the cache during inference).
- sd = gguf_sd_loader(model_path, compute_dtype=compute_dtype, q8_cr="decode")
+ sd = gguf_sd_loader(model_path, compute_dtype=compute_dtype, convrot="decode")
sd = CheckpointPrefix.detect(sd).strip(sd)
# As in the single-file loader: the key conversion drops these weights but not their markers.
sd = _drop_discarded_native_final_layers(sd)
# Before the key conversion, which carries `.weight_scale` along with its weight but not
# `.comfy_quant` -- see the single-file loader above.
- int8_markers = extract_int8_convrot_markers(sd)
+ int8_markers = extract_int8_convrot_markers(sd, accept_int4=True)
# An `I8` tensor the metadata does not claim is still a GGMLTensor of dtype int8, and `gguf` has
# no dequantizer for it: without this it fails on the first denoise step instead of here.
- reject_unmarked_int8_weights(sd, int8_markers, "Krea-2 GGUF")
+ # GGUF has no safetensors header: its quantization metadata already arrived as per-tensor markers.
+ reject_unmarked_int8_weights(sd, int8_markers, "Krea-2 GGUF", header_layers={})
# GGUF conversions use the native/ComfyUI compact key naming; remap to diffusers keys.
key_map: dict[str, str] = {}
if _is_native_krea2_format(sd):
@@ -801,8 +811,8 @@ class Krea2GGUFCheckpointModel(ModelLoader):
)
swap_in_int8_linears(model, sd, quantized)
self._logger.info(
- f"Krea-2: kept {len(quantized)} of {len(int8_markers)} layer(s) in int8 "
- "(ComfyUI-GGUF Q8_CR, dequantized per forward)"
+ f"Krea-2: kept {len(quantized)} of {len(int8_markers)} layer(s) quantized "
+ f"(ComfyUI-GGUF Q8_CR/Q4_CR, {_int4_int8_split(quantized)}; dequantized per forward)"
)
load_state_dict_ignoring_extras(model, sd, source="Krea-2 GGUF checkpoint", assign=True, allow_missing=True)
diff --git a/invokeai/backend/model_manager/model_on_disk.py b/invokeai/backend/model_manager/model_on_disk.py
index b34d0912f7..ecef29087c 100644
--- a/invokeai/backend/model_manager/model_on_disk.py
+++ b/invokeai/backend/model_manager/model_on_disk.py
@@ -215,8 +215,8 @@ class ModelOnDisk:
assert isinstance(checkpoint, dict)
elif path.suffix.endswith(".gguf"):
# Shapes and quantization types from the header, like the safetensors branch: the tensor data
- # is never read. Whether a Q8_CR file's quantization is supported is decided from its metadata
- # by `ModelConfigFactory`, once, not per candidate.
+ # is never read. Whether a Q8_CR or Q4_CR file's quantization is supported is decided from its
+ # metadata by `ModelConfigFactory`, once, not per candidate.
checkpoint = gguf_header_state_dict(path, compute_dtype=torch.float32)
elif path.suffix.endswith(".safetensors"):
if _is_sdnq_safetensors(path):
diff --git a/invokeai/backend/quantization/gguf/loaders.py b/invokeai/backend/quantization/gguf/loaders.py
index fbebe250e2..8478216941 100644
--- a/invokeai/backend/quantization/gguf/loaders.py
+++ b/invokeai/backend/quantization/gguf/loaders.py
@@ -13,7 +13,12 @@ import torch
from invokeai.backend.quantization.fp8_scaled import COMFY_QUANT_SUFFIX
from invokeai.backend.quantization.gguf.ggml_tensor import HOST_DEQUANT_PEAK_COPIES, GGMLTensor
from invokeai.backend.quantization.gguf.utils import TORCH_COMPATIBLE_QTYPES
-from invokeai.backend.quantization.int8_convrot import INT8_TENSORWISE_FORMAT
+from invokeai.backend.quantization.int8_convrot import (
+ CONVROT_GROUP_SIZE,
+ INT4_TENSORWISE_FORMAT,
+ INT8_TENSORWISE_FORMAT,
+ marker_layout,
+)
from invokeai.backend.util.logging import InvokeAILogger
logger = InvokeAILogger.get_logger()
@@ -150,24 +155,33 @@ def _read_comfy_orig_shapes(reader: gguf.GGUFReader) -> dict[str, torch.Size]:
COMFY_QUANT_KEY_PREFIX = "comfy.gguf.quant."
-Q8CRMode = Literal["refuse", "decode"]
+GGUFConvrotMode = Literal["refuse", "decode"]
+
+# ComfyUI-GGUF's name for its packed int4 convrot layers (`Q4_CR`), and the one backing InvokeAI decodes.
+INT4_CR_FORMAT = "int4_cr"
+INT4_CR_BACKING = "w4a4"
-def parse_q8_cr_markers(fields: Mapping[str, Any], source: str) -> dict[str, dict[str, Any]]:
- """Parse ComfyUI-GGUF's ``Q8_CR`` layers from a GGUF's ``comfy.gguf.quant.<weight name>`` metadata.
+def parse_gguf_convrot_markers(fields: Mapping[str, Any], source: str) -> dict[str, dict[str, Any]]:
+ """Parse ComfyUI-GGUF's convrot layers from a GGUF's ``comfy.gguf.quant.<weight name>`` metadata.
- ``Q8_CR`` (github.com/molbal/ComfyUI-GGUF) is ComfyUI's ``int8_tensorwise`` + convrot scheme in a
- GGUF container: the int8 codes are stored under GGML type ``I8`` (GGUF has no other int8 type), a
- per-output-row F32 scale beside them as ``<weight name>_scale``, and the JSON that a safetensors
- export keeps in ``<layer>.comfy_quant`` here lives in the metadata, as a string. ``I8`` is not a
- GGML quantization -- ``gguf`` has no dequantizer for it -- so these layers cannot ride the
- GGMLTensor path at all.
+ ComfyUI-GGUF (github.com/molbal/ComfyUI-GGUF) stores ComfyUI's integer convrot schemes in a GGUF
+ container, under GGML type ``I8`` -- GGUF has no other integer type -- with a per-output-row scale beside
+ them as ``<weight name>_scale``. The JSON a safetensors export keeps in ``<layer>.comfy_quant`` here lives
+ in the metadata, as a string. ``I8`` is not a GGML quantization -- ``gguf`` has no dequantizer for it --
+ so these layers cannot ride the GGMLTensor path at all. Two formats are read:
- ``fields`` maps metadata keys to their values: the file's whole metadata at install, its prefixed fields
- at load. Keys without the prefix are ignored. Returns the int8 markers keyed by weight name, in the form
- :mod:`int8_convrot` reads. Raises ``ValueError`` for anything else the converter writes (``int4_cr``, the
- retired ``int4_pytorch``): those tensors are ``I8`` too, and nothing here decodes them. Model identification
- turns that into the installer's refusal, so a file is refused for the same reason at install and at load.
+ - ``Q8_CR``, ``int8_tensorwise``: int8 codes ``[out, in]`` and an F32 scale.
+ - ``Q4_CR``, ``int4_cr`` with ``"backing": "w4a4"``: comfy-kitchen's packed int4 layout, codes ``[out, in/2]``
+ two per byte and an F16 scale, always rotated. The JSON's ``orig_shape`` gives the unpacked shape. It
+ comes back as an ``int4_tensorwise`` marker, which is what :mod:`int8_convrot` decodes it as.
+
+ ``fields`` maps metadata keys to their values: the file's whole metadata at install, its prefixed fields at
+ load. Keys without the prefix are ignored. Returns the markers keyed by weight name, in the form
+ :mod:`int8_convrot` reads. Raises ``ValueError`` for anything else the converter writes: ``int4_cr`` without
+ the w4a4 backing (its retired W4A16 form, with group-wise scales) and the retired ``int4_pytorch``. Those
+ tensors are ``I8`` too, and nothing here decodes them. Model identification turns that into the installer's
+ refusal, so a file is refused for the same reason at install and at load.
"""
layers: dict[str, dict[str, Any]] = {}
for key, value in fields.items():
@@ -178,21 +192,57 @@ def parse_q8_cr_markers(fields: Mapping[str, Any], source: str) -> dict[str, dic
config = json.loads(value)
except Exception as e:
raise ValueError(f"{source}: GGUF metadata {key!r} is not valid quantization JSON: {e}") from None
- if not isinstance(config, dict) or config.get("format") != INT8_TENSORWISE_FORMAT:
- fmt = config.get("format") if isinstance(config, dict) else config
+ if not isinstance(config, dict):
+ raise ValueError(f"{source}: GGUF metadata {key!r} is not a quantization object: {config!r}")
+ fmt = config.get("format")
+ if fmt == INT8_TENSORWISE_FORMAT:
+ marker = dict(config)
+ # The converter's own loader treats `convrot` without `weight_rotated` as a file from an older
+ # converter that stored the codes unrotated, and runs it without the rotation. Un-rotating
+ # weights that were never rotated would scramble them, so follow it.
+ if marker.get("convrot") and not marker.get("weight_rotated", False):
+ marker["convrot"] = False
+ marker.pop("convrot_groupsize", None)
+ elif fmt == INT4_CR_FORMAT and config.get("backing") == INT4_CR_BACKING:
+ orig_shape = config.get("orig_shape")
+ if not (
+ isinstance(orig_shape, list)
+ and len(orig_shape) == 2
+ and all(isinstance(d, int) and not isinstance(d, bool) and d > 0 for d in orig_shape)
+ and orig_shape[1] % 2 == 0
+ ):
+ raise ValueError(f"{source}: Q4_CR tensor {weight_name!r} has no usable orig_shape ({orig_shape!r}).")
+ group_size = config.get("convrot_groupsize", CONVROT_GROUP_SIZE)
+ if not isinstance(group_size, int) or isinstance(group_size, bool) or group_size <= 0:
+ raise ValueError(
+ f"{source}: Q4_CR tensor {weight_name!r} has no usable convrot_groupsize ({group_size!r})."
+ )
+ # The w4a4 backing is symmetric and pre-rotated by definition -- its kernel rotates the activations to
+ # match -- so the decode assumes both. A file that says otherwise would decode to a weight of the right
+ # shape and the wrong values (without the rotation a real Q4_CR layer correlates with its weights at
+ # 0.06), so it is refused instead.
+ if config.get("sym", True) is not True or config.get("weight_rotated", True) is not True:
+ raise ValueError(
+ f"{source}: Q4_CR tensor {weight_name!r} declares sym={config.get('sym')!r}, "
+ f"weight_rotated={config.get('weight_rotated')!r}; only symmetric, pre-rotated codes are decoded."
+ )
+ marker = {
+ "format": INT4_TENSORWISE_FORMAT,
+ "convrot": True,
+ "convrot_groupsize": group_size,
+ "orig_shape": list(orig_shape),
+ }
+ else:
+ backing = ""
+ if fmt == INT4_CR_FORMAT:
+ backing = f" with backing {config['backing']!r}" if "backing" in config else " without a backing"
raise ValueError(
- f"{source}: tensor {weight_name!r} uses ComfyUI-GGUF quantization {fmt!r}, which is not "
- f"supported. Only {INT8_TENSORWISE_FORMAT!r} (Q8_CR) layers can be loaded from GGUF."
+ f"{source}: tensor {weight_name!r} uses ComfyUI-GGUF quantization {fmt!r}{backing}, which is not "
+ f"supported. Only {INT8_TENSORWISE_FORMAT!r} (Q8_CR) and {INT4_CR_FORMAT!r} with the "
+ f"{INT4_CR_BACKING!r} backing (Q4_CR) layers can be loaded from GGUF."
)
if not weight_name.endswith(".weight"):
- raise ValueError(f"{source}: {INT8_TENSORWISE_FORMAT} metadata names {weight_name!r}, not a weight.")
- marker = dict(config)
- # The converter's own loader treats `convrot` without `weight_rotated` as a file from an older
- # converter that stored the codes unrotated, and runs it without the rotation. Un-rotating
- # weights that were never rotated would scramble them, so follow it.
- if marker.get("convrot") and not marker.get("weight_rotated", False):
- marker["convrot"] = False
- marker.pop("convrot_groupsize", None)
+ raise ValueError(f"{source}: {fmt} metadata names {weight_name!r}, not a weight.")
layers[weight_name] = marker
return layers
@@ -217,9 +267,9 @@ def gguf_header_state_dict(path: Path, compute_dtype: torch.dtype) -> dict[str,
Model identification needs names, shapes and quantization types, never values, and the header holds them
all. `gguf_sd_loader` copies every tensor out of the file -- for a 23.6 GB transformer, 22 GiB of RAM per
probe -- to answer questions the first few MB answer. Each tensor comes back as the `GGMLTensor` the full
- read gives, with the same packed and logical shapes; a ComfyUI-GGUF ``Q8_CR`` layer comes back as its raw
- ``I8`` codes, without the markers a decoding read adds, since whether it is supported is decided from the
- metadata. The reader maps the file but touches only the header.
+ read gives, with the same packed and logical shapes; a ComfyUI-GGUF ``Q8_CR`` or ``Q4_CR`` layer comes back
+ as its raw ``I8`` codes, without the markers a decoding read adds, since whether it is supported is decided
+ from the metadata. The reader maps the file but touches only the header.
"""
with WrappedGGUFReader(path) as reader:
orig_shapes = _read_comfy_orig_shapes(reader)
@@ -241,7 +291,7 @@ def gguf_sd_loader(
path: Path,
compute_dtype: torch.dtype,
*,
- q8_cr: Q8CRMode = "refuse",
+ convrot: GGUFConvrotMode = "refuse",
keep: Callable[[str], bool] | None = None,
) -> dict[str, torch.Tensor]:
"""Read a GGUF file into a state dict of ``GGMLTensor``s, dequantized on the fly at use.
@@ -249,16 +299,17 @@ def gguf_sd_loader(
``keep`` selects the tensors to read by name. The rest are skipped before their data is copied, so a
loader that uses only part of a file -- a transformer with its text connectors bundled beside it, an
encoder with its tokenizer packed in -- does not pay RAM for the part it drops. It selects tensors
- only: ``Q8_CR`` markers are read for the whole file, so ``"refuse"`` refuses a file even if ``keep``
+ only: convrot markers are read for the whole file, so ``"refuse"`` refuses a file even if ``keep``
would skip every marked layer.
- ``q8_cr`` says what to do with ComfyUI-GGUF ``Q8_CR`` layers (see :func:`parse_q8_cr_markers`):
+ ``convrot`` says what to do with ComfyUI-GGUF's ``Q8_CR``/``Q4_CR`` layers (see
+ :func:`parse_gguf_convrot_markers`):
- ``"decode"``: their weight, scale and bias come back as plain tensors with a ``<layer>.comfy_quant``
- marker beside them -- exactly a safetensors ``int8_tensorwise`` export, so the loader decodes both
- containers with the same :mod:`int8_convrot` code. Only a loader that does so may ask for this.
- - ``"refuse"``: any other loader. Raises before the tensors are read; without it the int8 codes reach
- a plain ``nn.Linear`` and the load fails on a dtype error that names neither the file nor the format.
+ marker beside them -- exactly a safetensors ``int8_tensorwise``/``int4_tensorwise`` export, so the loader
+ decodes both containers with the same :mod:`int8_convrot` code. Only a loader that does so may ask for this.
+ - ``"refuse"``: any other loader. Raises before the tensors are read; without it the codes reach a plain
+ ``nn.Linear`` and the load fails on a dtype error that names neither the file nor the format.
Identification refuses such files at install already, so this guards records made before it did.
Model identification does not come here: it reads the header (`gguf_header_state_dict`).
@@ -267,18 +318,19 @@ def gguf_sd_loader(
sd: dict[str, torch.Tensor] = {}
orig_shapes = _read_comfy_orig_shapes(reader)
quant_fields = {k: f.contents() for k, f in reader.fields.items() if k.startswith(COMFY_QUANT_KEY_PREFIX)}
- int8_layers = parse_q8_cr_markers(quant_fields, path.name)
- if int8_layers and q8_cr == "refuse":
+ layers = parse_gguf_convrot_markers(quant_fields, path.name)
+ if layers and convrot == "refuse":
raise ValueError(
- f"{path.name} holds {len(int8_layers)} ComfyUI-GGUF Q8_CR (int8 convrot) layer(s), e.g. "
- f"{next(iter(int8_layers))!r}. Loading Q8_CR from GGUF is not supported for this model type; "
+ f"{path.name} holds {len(layers)} ComfyUI-GGUF convrot (Q8_CR or Q4_CR) layer(s), e.g. "
+ f"{next(iter(layers))!r}. Loading those from GGUF is not supported for this model type; "
"use a GGML-quantized (Q8_0, Q4_K, ...) or safetensors build instead."
)
- int8_scales = {f"{name}_scale" for name in int8_layers}
- int8_biases = {f"{name[: -len('.weight')]}.bias" for name in int8_layers}
- missing = sorted((int8_layers.keys() | int8_scales) - {tensor.name for tensor in reader.tensors})
+ packed = {name for name, marker in layers.items() if marker_layout(marker).packed_int4}
+ scales = {f"{name}_scale": name for name in layers}
+ biases = {f"{name[: -len('.weight')]}.bias" for name in layers}
+ missing = sorted((layers.keys() | scales.keys()) - {tensor.name for tensor in reader.tensors})
if missing:
- raise ValueError(f"{path.name}: Q8_CR metadata names layers the file does not hold, e.g. {missing[0]!r}.")
+ raise ValueError(f"{path.name}: convrot metadata names layers the file does not hold, e.g. {missing[0]!r}.")
for tensor in reader.tensors:
if keep is not None and not keep(tensor.name):
@@ -288,18 +340,39 @@ def gguf_sd_loader(
# while tensors still hold references to the mapped memory.
torch_tensor = torch.from_numpy(tensor.data.copy())
- shape = _logical_shape(tensor, orig_shapes)
-
- if tensor.name in int8_layers or tensor.name in int8_scales:
- expected = gguf.GGMLQuantizationType.I8 if tensor.name in int8_layers else gguf.GGMLQuantizationType.F32
+ if tensor.name in layers or tensor.name in scales:
+ # Stored as written: a packed int4 weight holds half its elements, so it is checked against the
+ # quant JSON's own unpacked shape below, never reshaped to a `comfy.gguf.orig_shape` entry.
+ shape = torch.Size(tuple(int(v) for v in reversed(tensor.shape)))
+ name = scales.get(tensor.name, tensor.name)
+ is_scale = tensor.name in scales
+ expected = (
+ gguf.GGMLQuantizationType.I8
+ if not is_scale
+ else gguf.GGMLQuantizationType.F16
+ if name in packed
+ else gguf.GGMLQuantizationType.F32
+ )
if tensor.tensor_type != expected:
raise ValueError(
- f"{path.name}: Q8_CR tensor {tensor.name!r} is stored as {tensor.tensor_type.name}, "
+ f"{path.name}: convrot tensor {tensor.name!r} is stored as {tensor.tensor_type.name}, "
f"expected {expected.name}."
)
- sd[tensor.name] = torch_tensor.reshape(shape)
+ if name in packed and not is_scale:
+ rows, cols = layers[name]["orig_shape"]
+ if tuple(shape) != (rows, cols // 2):
+ raise ValueError(
+ f"{path.name}: Q4_CR tensor {tensor.name!r} is stored as {tuple(shape)}, which does not hold "
+ f"the packed codes of its declared ({rows}, {cols}) weight."
+ )
+ # The int4 scale widens to fp32, the dtype `Int4ConvrotLinear` holds it in.
+ sd[tensor.name] = (
+ torch_tensor.reshape(shape).to(torch.float32) if is_scale else torch_tensor.reshape(shape)
+ )
continue
+ shape = _logical_shape(tensor, orig_shapes)
+
if tensor.tensor_type in TORCH_COMPATIBLE_QTYPES:
torch_tensor = torch_tensor.view(*shape)
ggml_tensor = GGMLTensor(
@@ -308,11 +381,11 @@ def gguf_sd_loader(
tensor_shape=shape,
compute_dtype=compute_dtype,
)
- # An int8 layer's bias becomes a buffer of `Int8ConvrotLinear`, whose forward casts it to the
+ # A convrot layer's bias becomes a buffer of its quantized module, whose forward casts it to the
# activation dtype -- a dtype change a GGMLTensor refuses.
- sd[tensor.name] = ggml_tensor.get_dequantized_tensor() if tensor.name in int8_biases else ggml_tensor
+ sd[tensor.name] = ggml_tensor.get_dequantized_tensor() if tensor.name in biases else ggml_tensor
- for weight_name, marker in int8_layers.items():
+ for weight_name, marker in layers.items():
raw = json.dumps(marker).encode("utf-8")
marker_key = f"{weight_name[: -len('.weight')]}{COMFY_QUANT_SUFFIX}"
sd[marker_key] = torch.frombuffer(bytearray(raw), dtype=torch.uint8)
diff --git a/invokeai/backend/quantization/int8_convrot.py b/invokeai/backend/quantization/int8_convrot.py
index ba3e5ba690..0161471a28 100644
--- a/invokeai/backend/quantization/int8_convrot.py
+++ b/invokeai/backend/quantization/int8_convrot.py
@@ -33,12 +33,25 @@ transformer forward itself — and the transient bf16 weight (<= ~310 MB for H3'
largest layer) has to fit inside the calling node's working-memory reservation:
``dequantizing_linear.peak_dequant_transient_bytes`` is what a denoise node adds to
its estimate for that, since the model's resident size does not account for it.
+
+The same scheme also exists at 4 bits, written under two names: ``convrot_w4a4``
+(comfy-kitchen's released layout, always rotated) and ``int4_tensorwise`` (with a
+``convrot`` flag, from comfy-kitchen's unreleased int4 PR). Both store
+``<layer>.weight`` as int8 ``[out, in/2]`` holding two signed 4-bit codes per byte,
+the LOW nibble first -- the opposite of nvfp4's order -- and a per-output-row scale.
+Every other step is the int8 decode. ComfyUI-GGUF's ``Q4_CR`` is the same layout in a
+GGUF container (see ``gguf.loaders``). Established against real Krea-2 Turbo builds of
+all three: decoding them this way reaches cosine 0.984-0.987 against the bf16 weights,
+the 4-bit floor, where the high nibble first lands at 0.00 and skipping the derotation
+at 0.06. A loader opts into the 4-bit layouts (``accept_int4``): without a checkpoint
+to check a model family against, it keeps refusing them.
"""
import functools
import json
import struct
from collections.abc import Callable, Iterable, Mapping
+from dataclasses import dataclass
from pathlib import Path
from typing import Any
@@ -52,6 +65,7 @@ from invokeai.backend.quantization.fp8_scaled import (
WEIGHT_SCALE_SUFFIXES,
is_castable_float,
iter_weight_scale_pairs,
+ strip_layer_path_prefix,
)
from invokeai.backend.quantization.int8_matmul import (
KERNEL_ROTATION_GROUP_SIZE,
@@ -68,6 +82,44 @@ 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"
+CONVROT_W4A4_FORMAT = "convrot_w4a4"
+INT4_TENSORWISE_FORMAT = "int4_tensorwise"
+INT4_CONVROT_FORMATS = frozenset({CONVROT_W4A4_FORMAT, INT4_TENSORWISE_FORMAT})
+# Formats whose layout is rotated by definition, so their markers carry no `convrot` flag.
+_ALWAYS_ROTATED_FORMATS = frozenset({CONVROT_W4A4_FORMAT})
+
+
+@dataclass(frozen=True)
+class ConvrotLayout:
+ """How a marked layer is stored, as far as decoding it is concerned."""
+
+ packed_int4: bool
+ convrot: bool
+ group_size: int
+
+
+def marker_layout(marker: Mapping[str, Any]) -> ConvrotLayout:
+ """The storage a marker declares. The one place a marker's format is interpreted.
+
+ Every step that touches a marked layer -- the size prediction, the split, the swap -- asks this, so they
+ cannot disagree about whether a layer is packed or rotated. ``convrot_w4a4`` carries no ``convrot`` flag
+ because the layout is always rotated; ``quant_group_size`` and ``linear_dtype`` beside it only steer
+ Comfy's kernels and change nothing about the stored weight.
+ """
+ fmt = marker.get("format")
+ if fmt not in INT4_CONVROT_FORMATS and fmt != INT8_TENSORWISE_FORMAT:
+ raise ValueError(f"{marker!r} is not an int8 or int4 convrot marker.")
+ convrot = fmt in _ALWAYS_ROTATED_FORMATS or bool(marker.get("convrot", False))
+ group_size = marker.get("convrot_groupsize", CONVROT_GROUP_SIZE)
+ if not isinstance(group_size, int) or isinstance(group_size, bool) or group_size <= 0:
+ raise ValueError(f"{marker!r} declares no usable convrot_groupsize.")
+ return ConvrotLayout(packed_int4=fmt in INT4_CONVROT_FORMATS, convrot=convrot, group_size=group_size)
+
+
+def accepted_convrot_formats(accept_int4: bool) -> frozenset[str]:
+ """The marker formats a loader decodes: always int8, and the 4-bit layouts where it opted in."""
+ return INT4_CONVROT_FORMATS | {INT8_TENSORWISE_FORMAT} if accept_int4 else frozenset({INT8_TENSORWISE_FORMAT})
+
# Per-layer side-channel entries the int8 path reads elsewhere or cannot use at all; see
# `drop_unconsumed_quantization_sidecars`.
@@ -213,14 +265,32 @@ def as_column_scale(weight: torch.Tensor, scale: torch.Tensor) -> torch.Tensor:
return scale
+def unpack_int4_codes(packed: torch.Tensor, dtype: torch.dtype = torch.int8) -> torch.Tensor:
+ """The signed 4-bit codes ``[out, in]`` held two per byte in an int8 ``[out, in/2]`` tensor, as ``dtype``.
+
+ Element ``2j`` is the LOW nibble, ``2j + 1`` the high one; reading them the other way round decodes to
+ noise. Shifting left by four and back sign-extends the low nibble, the arithmetic right shift the high one,
+ and each half is written straight into its interleaved slot of the result: no int8 copy of the codes and no
+ separate cast, which measured 1.2-1.3x faster than unpacking to int8 first (RX 9060 XT, Krea-2 shapes).
+ """
+ codes = torch.empty(packed.shape[0], packed.shape[1], 2, dtype=dtype, device=packed.device)
+ codes[..., 0] = (packed << 4) >> 4
+ codes[..., 1] = packed >> 4
+ return codes.view(packed.shape[0], packed.shape[1] * 2)
+
+
def dequantize_convrot_weight(
weight_q: torch.Tensor,
weight_scale: torch.Tensor,
convrot: bool,
dtype: torch.dtype,
group_size: int = CONVROT_GROUP_SIZE,
+ *,
+ packed_int4: bool = False,
) -> torch.Tensor:
- """Recover the bf16/fp16 weight from int8 storage (and undo convrot if applied)."""
+ """Recover the bf16/fp16 weight from int8 or packed int4 storage (and undo convrot if applied)."""
+ if packed_int4:
+ weight_q = unpack_int4_codes(weight_q, torch.float32)
w = weight_q.to(torch.float32) * as_column_scale(weight_q, weight_scale).to(torch.float32)
if convrot:
out_features, in_features = w.shape
@@ -244,7 +314,7 @@ class Int8ConvrotLinear(DequantizingLinear):
The model cache wraps this module as ``CustomInt8ConvrotLinear`` (see
``AUTOCAST_MODULE_TYPE_MAPPING``), which enables sidecar LoRA patches and lets a partial
load leave some int8 buffers on the CPU — the per-call ``.to(device)`` then streams them
- (at half the bf16 byte count) instead of failing outright. Fully-resident operation remains
+ (at half the bf16 byte count, being moved before they are widened) instead of failing outright. Fully-resident 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.
@@ -295,14 +365,9 @@ class Int8ConvrotLinear(DequantizingLinear):
# per-call transient at ~two weight-sized tensors (~620 MB peak for the fused-SwiGLU
# fc1 in bf16) instead of tripling through an fp32 intermediate (~1.5 GiB). An fp32
# compute dtype still gets the exact fp32 path for free.
- scale = as_column_scale(self.weight, self.weight_scale).to(device=device, dtype=dtype)
- w = self.weight.to(device=device).to(dtype=dtype) * scale
- if self.convrot:
- w = (
- w.view(self.out_features, self.in_features // self.group_size, self.group_size)
- @ shared_regular_hadamard(self.group_size, device, dtype)
- ).view(self.out_features, self.in_features)
- return w
+ return _scale_and_derotate(
+ self.weight.to(device).to(dtype=dtype), self.weight_scale, self.convrot, self.group_size
+ )
@property
def int8_matmul_eligible(self) -> bool:
@@ -328,19 +393,18 @@ class Int8ConvrotLinear(DequantizingLinear):
def dequant_transient_bytes(self, compute_dtype: torch.dtype) -> int:
"""Two weight-sized tensors in the compute dtype.
- Both halves of ``_dequantized_weight`` peak at two: the dtype cast of the int8 weight is alive
- alongside the product it is multiplied into, and that product is then alive alongside the
- derotation matmul's output. Each pair is freed before the next allocates.
-
- Under partial load the int8 weight is additionally streamed to the device per call. That copy is at
- most half a weight and is freed by the cast, before the product allocates, so the peak stays at two. Verified
- against the real `z_image_turbo_int8_convrot` checkpoint: exact for most shapes, and 2 MiB under on
- the two that make cuBLAS take a workspace (10240x3840 and 3840x10240), against a 3 GiB reservation
- floor.
-
- This also bounds the int8 compute path: it quantizes at most ``2 * out_features`` rows at a
- time, so its int8 activation copy plus a streamed int8 weight stay below these two weights
- (see ``int8_matmul``).
+ The widened weight is scaled in place, so with convrot the peak is the derotation's: its input alive
+ alongside the matmul's output. The int8 codes partial loading leaves in RAM are streamed per call, and that
+ copy is freed once widened, before the derotation allocates. Without convrot the peak is the widened weight
+ beside the streamed codes, ``itemsize + 1`` bytes per element against this estimate's ``2 * itemsize``:
+ half a weight less in bf16 or fp16, three quarters in fp32. The margin is kept rather than tracking a
+ layout the published builds do not use. Verified against the real `z_image_turbo_int8_convrot` checkpoint: exact
+ for most shapes, and 2 MiB under on the two that make cuBLAS take a workspace (10240x3840 and 3840x10240),
+ against a 3 GiB reservation floor.
+
+ This also bounds the int8 compute path, which only rotated layers take: it quantizes at most
+ ``2 * out_features`` rows at a time, so its int8 activation copy plus a streamed int8 weight stay below
+ these two weights (see ``int8_matmul``).
"""
return 2 * self.out_features * self.in_features * compute_dtype.itemsize
@@ -348,27 +412,197 @@ class Int8ConvrotLinear(DequantizingLinear):
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.
+def _scale_and_derotate(weight: torch.Tensor, scale: torch.Tensor, convrot: bool, group_size: int) -> torch.Tensor:
+ """Apply the per-row scale and undo convrot on a weight already widened to the compute dtype and device.
+
+ ``weight`` must be a fresh tensor the caller does not keep -- a widening cast always is -- because it is
+ scaled in place: that keeps the peak at the derotation's two weight-sized tensors instead of adding a third.
+ """
+ weight.mul_(as_column_scale(weight, scale).to(device=weight.device, dtype=weight.dtype))
+ if not convrot:
+ return weight
+ out_features, in_features = weight.shape
+ hadamard = shared_regular_hadamard(group_size, weight.device, weight.dtype)
+ return (weight.view(out_features, in_features // group_size, group_size) @ hadamard).view(out_features, in_features)
+
+
+class Int4ConvrotLinear(DequantizingLinear):
+ """A linear layer storing Comfy's packed int4 (+convrot) weights, dequantized per forward.
+
+ ``weight`` is the checkpoint's int8 ``[out, in/2]`` payload, two codes per byte, and ``weight_scale`` its
+ per-row scale, registered as persistent buffers under those names as in :class:`Int8ConvrotLinear`, whose
+ decode this shares after unpacking. ``in_features`` is the unpacked width: LoRA sidecars and the model
+ cache's patch shapes are built from it. Resident, a layer costs half a byte per weight element plus its
+ scale, against int8's one byte.
+
+ The model cache wraps it as ``CustomInt4ConvrotLinear`` (see ``AUTOCAST_MODULE_TYPE_MAPPING``) for
+ sidecar LoRA patches and streaming under partial load, exactly like the int8 module.
+ """
+
+ def __init__(
+ self,
+ weight: torch.Tensor,
+ weight_scale: torch.Tensor,
+ convrot: bool,
+ bias: torch.Tensor | None = None,
+ group_size: int = CONVROT_GROUP_SIZE,
+ ) -> None:
+ super().__init__()
+ if weight.dtype != torch.int8 or weight.dim() != 2:
+ raise ValueError(
+ f"expected a 2-D int8 tensor of packed int4 codes, got {weight.dtype} {tuple(weight.shape)}"
+ )
+ self.out_features = weight.shape[0]
+ self.in_features = weight.shape[1] * 2
+ self.convrot = convrot
+ self.group_size = group_size
+ self.register_buffer("weight", weight)
+ self.register_buffer("weight_scale", weight_scale.to(torch.float32))
+ if convrot:
+ check_hadamard_size(group_size)
+ if self.in_features % group_size != 0:
+ raise ValueError(f"convrot weight in_features {self.in_features} not divisible by {group_size}")
+ if bias is not None:
+ self.register_buffer("bias", bias)
+ else:
+ self.bias = None
+
+ def _dequantized_weight(self, device: torch.device, dtype: torch.dtype) -> torch.Tensor:
+ # Unpacked on the compute device: under partial load only the packed half byte per element crosses the bus.
+ return _scale_and_derotate(
+ unpack_int4_codes(self.weight.to(device), dtype), self.weight_scale, self.convrot, self.group_size
+ )
+
+ def dequant_transient_bytes(self, compute_dtype: torch.dtype) -> int:
+ """The decode's peak, counting the packed payload as streamed.
+
+ With convrot that is the derotation's two weight-sized tensors in the compute dtype. Without it, the unpack
+ is the peak: the widened weight beside the two half-width shift results it is filled from and the payload
+ copy, half a byte per element, that partial loading streams to the device per call. The working memory is
+ reserved before the model cache decides which layers stay in RAM, so any layer may stream; a resident one
+ peaks half a byte per element lower.
+ """
+ elements = self.out_features * self.in_features
+ if self.convrot:
+ return 2 * elements * compute_dtype.itemsize
+ return elements * compute_dtype.itemsize + elements + elements // 2
+
+ def extra_repr(self) -> str:
+ return f"in_features={self.in_features}, out_features={self.out_features}, convrot={self.convrot}, int4"
+
+
+def extract_int8_convrot_markers(
+ sd: dict[str, Any], *, accept_int4: bool = False, header_layers: Mapping[str, Any] | None = None
+) -> dict[str, dict[str, Any]]:
+ """Pop every ``int8_tensorwise`` marker -- and with ``accept_int4`` every packed int4 one -- 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.
+ ``accept_int4`` also claims the packed 4-bit layouts (see :func:`marker_layout`), for a loader that
+ decodes them. ``header_layers`` -- the safetensors ``_quantization_metadata`` entries, in ``sd``'s key
+ space -- adds layers a file names only in its header, as the Starnodes converter writes every one of
+ them (see :func:`marker_from_header_entry`). A per-tensor marker wins over a header entry for the same
+ layer, and a header entry only counts where the layer's weight actually is int8: a stale or bundled
+ header entry naming a dense weight is not a marker.
+
+ Use this when the loader intends to keep the weights quantized and swap in :class:`Int8ConvrotLinear`
+ or :class:`Int4ConvrotLinear`, which is what every loader here does.
"""
+ formats = accepted_convrot_formats(accept_int4)
markers = {}
- for key in [k for k in sd if isinstance(k, str) and k.endswith(COMFY_QUANT_SUFFIX)]:
+ marker_keys = [k for k in sd if isinstance(k, str) and k.endswith(COMFY_QUANT_SUFFIX)]
+ # Every layer with a per-tensor marker, claimed or not: a header entry never overrides one.
+ marked = {key[: -len(COMFY_QUANT_SUFFIX)] for key in marker_keys}
+ for key in marker_keys:
marker = parse_comfy_quant_marker(sd[key])
- if marker.get("format") != INT8_TENSORWISE_FORMAT:
+ if marker.get("format") not in formats:
continue
markers[key[: -len(COMFY_QUANT_SUFFIX)]] = marker
del sd[key]
+ for path, entry in (header_layers or {}).items():
+ if path in marked or getattr(sd.get(f"{path}.weight"), "dtype", None) is not torch.int8:
+ continue
+ marker = marker_from_header_entry(path, entry, formats)
+ if marker is not None:
+ markers[path] = marker
return markers
+def marker_from_header_entry(path: str, entry: Any, formats: Iterable[str]) -> dict[str, Any] | None:
+ """A layer's marker from its safetensors-header entry, or None where the entry declares no format in ``formats``.
+
+ Refuses an ``int8_tensorwise`` or ``int4_tensorwise`` entry that does not say whether the layer was
+ rotated. In a per-tensor marker an absent ``convrot`` means unrotated, and producers that write only the
+ header state it either way. Comfy-Org's own exports, though, write header entries without the flag beside
+ per-tensor markers that set it, so a header-only file of that origin would read as unrotated: a weight
+ of the right shape that bears no relation to the one stored. ``convrot_w4a4`` needs no flag, being
+ rotated by definition.
+ """
+ if not isinstance(entry, Mapping) or entry.get("format") not in set(formats):
+ return None
+ fmt = entry["format"]
+ if fmt not in _ALWAYS_ROTATED_FORMATS and "convrot" not in entry:
+ raise ValueError(
+ f"'{path}' is quantized as {fmt!r} according to the safetensors header alone, and the header does not "
+ "say whether the weight was rotated (no 'convrot' entry). Read the wrong way it loads cleanly and "
+ "generates noise, so it is refused rather than guessed. Use another build of this model."
+ )
+ return dict(entry)
+
+
+def int8_weights_without_a_decodable_marker(
+ state_dict: Mapping[str, Any],
+ markers: Mapping[str, Mapping[str, Any]],
+ header_layers: Mapping[str, Any],
+ formats: Iterable[str],
+ *,
+ discarded: Iterable[str] = (),
+) -> dict[str, str | None]:
+ """The int8 ``.weight`` keys a loader decoding ``formats`` would refuse, each with the format it is declared as.
+
+ Model identification's reading of what :func:`extract_int8_convrot_markers` and
+ :func:`reject_unmarked_int8_weights` decide at load, so a file is refused at install for the reason it
+ would fail on later. Identification has every dtype but no tensor bytes, hence ``markers`` -- the per-tensor
+ markers as :func:`read_comfy_quant_markers` reads them from the file -- and ``header_layers``, the
+ ``_quantization_metadata`` entries. Pass an empty ``header_layers`` for a loader that does not read the
+ header. The value is the declared format, or None where nothing declares one. Raises ``ValueError`` where
+ :func:`marker_from_header_entry` would.
+
+ All three are compared without the checkpoint prefix, as the loaders compare them after stripping it: a
+ header can name its layers with or without the prefix the tensors carry. ``discarded`` names the layers the
+ loader drops before it reads any marker, so their quantization is never its business either.
+ """
+ formats = set(formats)
+ markers = strip_layer_path_prefix(markers)
+ header_layers = strip_layer_path_prefix(header_layers)
+ int8_weights = strip_layer_path_prefix(
+ {
+ key[: -len(".weight")]: key
+ for key, value in state_dict.items()
+ if isinstance(key, str) and key.endswith(".weight") and getattr(value, "dtype", None) is torch.int8
+ }
+ )
+ undecodable: dict[str, str | None] = {}
+ discarded = set(discarded)
+ for path, key in int8_weights.items():
+ if path in discarded:
+ continue
+ entry = markers.get(path)
+ if entry is None:
+ entry = header_layers.get(path)
+ if marker_from_header_entry(path, entry, formats) is not None:
+ continue
+ elif entry.get("format") in formats:
+ continue
+ fmt = entry.get("format") if isinstance(entry, Mapping) else None
+ undecodable[key] = fmt if isinstance(fmt, str) else None
+ return undecodable
+
+
def reject_int8_layers_a_plain_fold_cannot_decode(sd: Mapping[str, Any], what: str = "This checkpoint") -> None:
"""Refuse an ``int8_tensorwise`` layer to a fold that only multiplies the scale in.
@@ -388,11 +622,11 @@ def reject_int8_layers_a_plain_fold_cannot_decode(sd: Mapping[str, Any], what: s
marker is refused too: nothing says whether it was rotated, and every published build marks
every one of its int8 weights.
- Read from the *per-tensor* marker only. The safetensors header names formats as well, but no
- observed header entry carries ``convrot`` or the group size (see ``flux.py``, where the
- per-layer marker wins for that reason), so a header entry is not evidence that a layer is safe
- to fold — consulting one
- would let a header-named rotated build straight through. Every caller here still has the markers
+ Read from the *per-tensor* marker only. The safetensors header names formats as well, but
+ Comfy-Org's header entries carry neither ``convrot`` nor the group size beside per-tensor markers
+ that do (see ``flux.py``, where the per-layer marker wins for that reason), so a header entry is
+ not evidence that a layer is safe to fold — consulting one would let a header-named rotated build
+ straight through. Every caller here still has the markers
in ``sd``: the two folds run before anything pops them, and the Mistral seam checks ahead of
``extract_fp8_scaled_layers`` for the same reason.
@@ -403,6 +637,7 @@ def reject_int8_layers_a_plain_fold_cannot_decode(sd: Mapping[str, Any], what: s
"""
rotated: list[str] = []
unmarked: list[str] = []
+ foreign: dict[str, str] = {}
for weight_key, _scale_key in iter_weight_scale_pairs(sd):
weight = sd[weight_key]
if getattr(weight, "dtype", None) is not torch.int8:
@@ -410,7 +645,9 @@ def reject_int8_layers_a_plain_fold_cannot_decode(sd: Mapping[str, Any], what: s
path = weight_key[: -len(".weight")]
blob = sd.get(f"{path}{COMFY_QUANT_SUFFIX}")
marker = parse_comfy_quant_marker(blob) if blob is not None else None
- if not marker or marker.get("format") != INT8_TENSORWISE_FORMAT:
+ if marker and isinstance(marker.get("format"), str) and marker["format"] != INT8_TENSORWISE_FORMAT:
+ foreign[path] = marker["format"]
+ elif not marker or marker.get("format") != INT8_TENSORWISE_FORMAT:
unmarked.append(path)
elif marker.get("convrot"):
rotated.append(path)
@@ -422,6 +659,12 @@ def reject_int8_layers_a_plain_fold_cannot_decode(sd: Mapping[str, Any], what: s
"without the inverse rotation produces a weight of the right shape that bears no relation to the "
"one stored. Use the fp8 or bf16 build of this checkpoint."
)
+ if foreign:
+ raise ValueError(
+ f"{what} carries {len(foreign)} int8 weight(s) marked {_formats_named(foreign)} (e.g. "
+ f"{', '.join(sorted(foreign)[:3])}), which this loader cannot decode. Use the fp8 or bf16 build of "
+ "this checkpoint."
+ )
if unmarked:
raise ValueError(
f"{what} carries {len(unmarked)} int8 weight(s) with no int8_tensorwise marker (e.g. "
@@ -458,7 +701,12 @@ def check_int8_scale_layout(path: str, weight: torch.Tensor, scale: torch.Tensor
def reject_unmarked_int8_weights(
- sd: dict[str, Any], markers: Mapping[str, Any], architecture: str, model: torch.nn.Module | None = None
+ sd: dict[str, Any],
+ markers: Mapping[str, Any],
+ architecture: str,
+ model: torch.nn.Module | None = None,
+ *,
+ header_layers: Mapping[str, Any] | None = None,
) -> None:
"""Refuse a checkpoint holding an int8 weight that no ``int8_tensorwise`` marker claims.
@@ -484,6 +732,11 @@ def reject_unmarked_int8_weights(
transformer; a non-strict load discards those keys rather than casting them, so they cannot
become noise and are not this loader's business. Without ``model`` every int8 key in ``sd`` is
in scope, which is right for a caller that has not built the module tree yet.
+
+ ``header_layers`` changes the message only: an orphan that an unclaimed marker or a header entry
+ declares a format for is refused as that format -- a packed int4 layer on a loader that has not
+ opted into int4 -- rather than as a weight with no marker. Pass it (empty where the container has no
+ header) whenever the loader reads the header, so the refusal does not blame a header it has read.
"""
consumed = None if model is None else {name for name, _ in model.named_modules()}
orphans = sorted(
@@ -493,11 +746,40 @@ def reject_unmarked_int8_weights(
and not (isinstance(k, str) and k.endswith(".weight") and k[: -len(".weight")] in markers)
and (consumed is None or (isinstance(k, str) and k.rsplit(".", 1)[0] in consumed))
)
- if orphans:
+ if not orphans:
+ return
+ # A marker this loader did not claim is still in `sd`, and a header entry is passed in: an orphan that one of
+ # them names is a format this architecture does not load -- int4, say -- not a file missing its markers.
+ declared: dict[str, str] = {}
+ for key in orphans:
+ path = key[: -len(".weight")] if isinstance(key, str) and key.endswith(".weight") else None
+ if path is None:
+ continue
+ blob = sd.get(f"{path}{COMFY_QUANT_SUFFIX}")
+ entry = parse_comfy_quant_marker(blob) if blob is not None else (header_layers or {}).get(path)
+ if isinstance(entry, Mapping) and isinstance(entry.get("format"), str):
+ declared[key] = entry["format"]
+ if declared:
raise ValueError(
- f"{architecture} checkpoint has {len(orphans)} int8 weight(s) with no `comfy_quant` marker, "
- f"e.g. {orphans[:3]}. Loading them would produce a model that runs and generates noise."
+ f"{architecture} checkpoint has {len(declared)} int8 weight(s) marked {_formats_named(declared)}, e.g. "
+ f"{sorted(declared)[:3]}, which {architecture} does not load. Use another build of this model."
)
+ # A loader that read the header has already looked there; one that did not may be refusing a build that names
+ # its formats nowhere else, as int4 builds often do.
+ unread_header = (
+ ""
+ if header_layers is not None
+ else f" A build that names its quantization only in the safetensors header is not supported for {architecture}."
+ )
+ raise ValueError(
+ f"{architecture} checkpoint has {len(orphans)} int8 weight(s) with no `comfy_quant` marker, "
+ f"e.g. {orphans[:3]}. Loading them would produce a model that runs and generates noise.{unread_header}"
+ )
+
+
+def _formats_named(formats_by_layer: Mapping[str, str]) -> str:
+ """The distinct formats in ``formats_by_layer``, quoted, for a refusal message."""
+ return ", ".join(repr(fmt) for fmt in sorted(set(formats_by_layer.values())))
def drop_unconsumed_quantization_sidecars(sd: dict[str, Any]) -> dict[str, Any]:
@@ -548,13 +830,13 @@ def _resolve_int8_target(model: torch.nn.Module, path: str) -> tuple[torch.nn.Mo
target = getattr(parent, attribute)
except AttributeError:
raise ValueError(
- f"'{path}' is marked int8_tensorwise but the built model has no such module. The "
+ f"'{path}' is marked quantized but the built model has no such module. The "
"checkpoint is misidentified, or its keys need a conversion this loader did not apply."
) from None
if not isinstance(target, torch.nn.Linear):
raise ValueError(
- f"'{path}' is marked int8_tensorwise but is a {type(target).__name__}, not an nn.Linear. "
- "Only a Linear weight can be kept in int8 storage."
+ f"'{path}' is marked quantized but is a {type(target).__name__}, not an nn.Linear. "
+ "Only a Linear weight can be kept in quantized storage."
)
return parent, attribute, target
@@ -625,14 +907,15 @@ def split_int8_convrot_layers(
continue
weight, scale = sd[f"{path}.weight"], sd[f"{path}.weight_scale"]
check_int8_scale_layout(path, weight, scale)
- convrot = bool(marker.get("convrot", False))
- if convrot and weight.dim() != 2:
+ layout = marker_layout(marker)
+ if (layout.convrot or layout.packed_int4) and weight.dim() != 2:
raise ValueError(
- f"'{path}' is marked convrot but its weight is {tuple(weight.shape)}. The rotation is "
- "defined over a weight's input dimension, so there is nothing to un-rotate here."
+ f"'{path}' is marked {'convrot' if layout.convrot else 'packed int4'} but its weight is "
+ f"{tuple(weight.shape)}. Both are defined over a weight's input dimension, so there is nothing to "
+ "undo here."
)
sd[f"{path}.weight"] = dequantize_convrot_weight(
- weight, scale, convrot, dtype, int(marker.get("convrot_groupsize", CONVROT_GROUP_SIZE))
+ weight, scale, layout.convrot, dtype, layout.group_size, packed_int4=layout.packed_int4
)
del sd[f"{path}.weight_scale"]
return surviving
@@ -659,12 +942,16 @@ def predict_int8_cast_size(
A pinned ``weight_scale`` stays fp32, and charging it two under-counts it by half. A payload the
split is about to dequantize arrives at ``dtype.itemsize`` while its scale disappears into it,
and charging that one byte is the direction that actually hurts: the reservation comes up short
- by exactly the layers the split widened.
+ by exactly the layers the split widened. A packed int4 payload the split widens comes out with
+ twice the elements it is stored with, so it is charged for those.
"""
surviving = _surviving_int8_layers(sd, quantized, model, skip_patterns)
pinned = _pinned_quantized_keys(surviving)
widening = {path: marker for path, marker in quantized.items() if path not in surviving}
- dequantized_weights = {f"{path}.weight" for path in widening}
+ # Elements per stored element once widened: two codes per byte for a packed int4 payload.
+ dequantized_weights = {
+ f"{path}.weight": 2 if marker_layout(marker).packed_int4 else 1 for path, marker in widening.items()
+ }
consumed_scales = {f"{path}.weight_scale" for path in widening}
total = 0
@@ -675,7 +962,7 @@ def predict_int8_cast_size(
if key in pinned or (key not in dequantized_weights and not is_castable_float(tensor)):
total += tensor.nelement() * tensor.element_size()
else:
- total += tensor.nelement() * dtype.itemsize
+ total += tensor.nelement() * dequantized_weights.get(key, 1) * dtype.itemsize
return total
@@ -703,15 +990,20 @@ def _pinned_quantized_keys(quantized: Mapping[str, Any]) -> set[str]:
def swap_in_int8_linears(model: torch.nn.Module, sd: dict[str, Any], quantized: dict[str, dict[str, Any]]) -> None:
- """Replace each quantized ``nn.Linear`` with an ``Int8ConvrotLinear`` sized from the state dict.
+ """Replace each quantized ``nn.Linear`` with an ``Int8ConvrotLinear`` or, for a packed int4 marker, an
+ ``Int4ConvrotLinear``, sized from the state dict.
- The weights stay int8 and rotated as stored; the layer dequantizes and derotates per forward.
+ The weights stay quantized 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.
+ so the ``load_state_dict`` that follows assigns the quantized tensors straight into them. That
+ assignment takes the buffers' shapes from the file, not from the model, so the weight's decoded
+ shape is checked against the Linear it replaces here: a payload of the wrong width -- an int4
+ layer whose marker says int8, or a checkpoint of a different model size -- would otherwise load
+ without a complaint and fail inside the first forward.
Pass only what :func:`split_int8_convrot_layers` returned: every layer refused below is one that
split would have dequantized instead.
@@ -721,19 +1013,27 @@ def swap_in_int8_linears(model: torch.nn.Module, sd: dict[str, Any], quantized:
"""
installed: list[Int8ConvrotLinear] = []
for path, marker in quantized.items():
+ fmt = marker.get("format")
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'}."
+ f"'{path}' is marked {fmt} but is missing its {'weight' if weight is None else 'weight_scale'}."
)
if weight.dim() != 2:
raise ValueError(
- f"'{path}' is marked int8_tensorwise but its weight is {tuple(weight.shape)}, not 2-D. "
- "Only a Linear weight can be kept in int8 storage; dequantize this one instead."
+ f"'{path}' is marked {fmt} but its weight is {tuple(weight.shape)}, not 2-D. "
+ "Only a Linear weight can be kept quantized; dequantize this one instead."
)
check_int8_scale_layout(path, weight, scale)
+ layout = marker_layout(marker)
parent, attribute, target = _resolve_int8_target(model, path)
+ decoded = (weight.shape[0], weight.shape[1] * (2 if layout.packed_int4 else 1))
+ if decoded != (target.out_features, target.in_features):
+ raise ValueError(
+ f"'{path}' is marked {fmt} with a stored {tuple(weight.shape)} weight, which decodes to "
+ f"{decoded}, but the model's Linear there is ({target.out_features}, {target.in_features}). The "
+ "checkpoint does not match this architecture."
+ )
bias = sd.get(f"{path}.bias")
if (bias is None) is not (target.bias is None):
# The replacement's buffers are whatever the checkpoint supplied, so from here on the
@@ -743,19 +1043,25 @@ def swap_in_int8_linears(model: torch.nn.Module, sd: dict[str, Any], quantized:
# quantized layer silently missing its offset.
missing, extra = ("checkpoint", "model") if bias is None else ("model", "checkpoint")
raise ValueError(
- f"'{path}' is marked int8_tensorwise and the {extra}'s Linear has a bias, but the "
+ f"'{path}' is marked {fmt} and the {extra}'s Linear has a bias, but the "
f"{missing} has none. The checkpoint does not match this architecture."
)
- layer = Int8ConvrotLinear(
- weight=weight,
- weight_scale=scale,
- convrot=bool(marker.get("convrot", False)),
- bias=bias,
- group_size=int(marker.get("convrot_groupsize", CONVROT_GROUP_SIZE)),
- full_precision_matmul=bool(marker.get("full_precision_matrix_mult", False)),
- )
+ layer: Int4ConvrotLinear | Int8ConvrotLinear
+ if layout.packed_int4:
+ layer = Int4ConvrotLinear(
+ weight=weight, weight_scale=scale, convrot=layout.convrot, bias=bias, group_size=layout.group_size
+ )
+ else:
+ layer = Int8ConvrotLinear(
+ weight=weight,
+ weight_scale=scale,
+ convrot=layout.convrot,
+ bias=bias,
+ group_size=layout.group_size,
+ full_precision_matmul=bool(marker.get("full_precision_matrix_mult", False)),
+ )
+ installed.append(layer)
setattr(parent, attribute, layer)
- installed.append(layer)
uncovered = [layer for layer in installed if not layer.int8_matmul_eligible]
if uncovered and is_int8_compute_enabled():
marked = sum(layer.full_precision_matmul for layer in uncovered)
@@ -794,7 +1100,8 @@ def install_int8_convrot_layers(
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.
+ """Take a marked int8 or int4 checkpoint from state dict to installed ``Int8ConvrotLinear`` and
+ ``Int4ConvrotLinear`` 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:
@@ -873,7 +1180,7 @@ def reject_foreign_quantization_scales(
)
if orphans:
raise ValueError(
- f"{architecture} checkpoint has {len(orphans)} float8 weight scale(s) that no "
- f"`int8_tensorwise` marker claims, e.g. {orphans[:3]}. A file mixing int8_tensorwise "
- "with scaled fp8 is not supported: the fp8 weights would load unscaled."
+ f"{architecture} checkpoint has {len(orphans)} float8 weight scale(s) that no int8 or int4 "
+ f"convrot marker claims, e.g. {orphans[:3]}. A file mixing convrot layers with scaled fp8 is not "
+ "supported: the fp8 weights would load unscaled."
)
diff --git a/tests/backend/model_manager/configs/test_gguf_convrot_identification.py b/tests/backend/model_manager/configs/test_gguf_convrot_identification.py
new file mode 100644
index 0000000000..ee70b2234f
--- /dev/null
+++ b/tests/backend/model_manager/configs/test_gguf_convrot_identification.py
@@ -0,0 +1,111 @@
+"""Install-time decisions for ComfyUI-GGUF ``Q8_CR`` and ``Q4_CR`` files, made through ``ModelConfigFactory``.
+
+These run at the *default* ``allow_unknown``, because that is what decides what the user sees: a file a
+config recognises but cannot load must come back as a refusal with its reason, not register as an Unknown
+model whose explanation is only in the server log. Fixtures are real GGUF files of a few kilobytes.
+"""
+
+from pathlib import Path
+from typing import Any
+
+import pytest
+import torch
+
+from invokeai.backend.model_manager.configs.factory import ModelConfigFactory
+from invokeai.backend.model_manager.configs.main import Main_GGUF_Krea2_Config
+from tests.fixtures.quantized_payloads import (
+ q4_cr_marker,
+ q8_cr_marker,
+ quantize_convrot,
+ quantize_convrot_int4,
+ write_gguf,
+)
+
+_OVERRIDE_FIELDS: dict[str, object] = {
+ "hash": "blake3:fakehash",
+ "path": "/fake/models/test-model",
+ "file_size": 1000,
+ "name": "test-model",
+ "description": "test",
+ "source": "test",
+ "source_type": "path",
+ "key": "test-key",
+}
+
+
+def _krea2_convrot(path: Path, marker: dict[str, Any], *, packed_int4: bool = False) -> Path:
+ """A native-named Krea-2 GGUF with one quantized layer, as ComfyUI-GGUF's converter writes one: int8 codes and
+ an F32 scale for Q8_CR, packed codes and an F16 scale for Q4_CR."""
+ if packed_int4:
+ payload = quantize_convrot_int4(torch.randn(4, 256))
+ layer = {"blocks.0.attn.wq.weight": payload.packed, "blocks.0.attn.wq.weight_scale": payload.scale.half()}
+ else:
+ int8 = quantize_convrot(torch.randn(4, 256))
+ layer = {"blocks.0.attn.wq.weight": int8.codes, "blocks.0.attn.wq.weight_scale": int8.scale}
+ write_gguf(
+ path,
+ {
+ "txtfusion.projector.weight": torch.ones(12, 1),
+ "first.weight": torch.ones(8, 4),
+ "tproj.0.weight": torch.ones(8, 4),
+ **layer,
+ },
+ quant={"blocks.0.attn.wq.weight": marker},
+ )
+ return path
+
+
+def _identify(path: Path) -> Any:
+ return ModelConfigFactory.from_model_on_disk(path, dict(_OVERRIDE_FIELDS), allow_unknown=True)
+
+
+def test_a_q8_cr_krea2_gguf_installs_as_a_krea2_gguf(tmp_path: Path) -> None:
+ result = _identify(_krea2_convrot(tmp_path / "krea2_turbo-Q8_CR.gguf", q8_cr_marker()))
+
+ assert isinstance(result.config, Main_GGUF_Krea2_Config)
+ assert not result.invalid_matches
+
+
+def test_a_q8_cr_gguf_is_refused_with_its_reason_where_the_loader_cannot_decode_it(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The gate every other GGUF config sits behind. Driven through the Krea-2 config with its
+ capability switched off, so the fixture is one that is otherwise known to install."""
+ monkeypatch.setattr(Main_GGUF_Krea2_Config, "DECODES_GGUF_CONVROT", frozenset())
+
+ result = _identify(_krea2_convrot(tmp_path / "krea2_turbo-Q8_CR.gguf", q8_cr_marker()))
+
+ assert result.config is None
+ assert any("Q8_CR" in str(reason) for reason in result.invalid_matches)
+
+
+def test_a_loader_that_decodes_q8_cr_but_not_int4_refuses_a_q4_cr_file(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Q8_CR and Q4_CR are opted into separately, as the safetensors loaders opt into int4 separately: a loader wired
+ for int8 alone would otherwise install a Q4_CR file and refuse it at its first load."""
+ monkeypatch.setattr(Main_GGUF_Krea2_Config, "DECODES_GGUF_CONVROT", frozenset({"int8_tensorwise"}))
+
+ result = _identify(_krea2_convrot(tmp_path / "krea2_turbo-Q4_CR.gguf", q4_cr_marker(4, 256), packed_int4=True))
+
+ assert result.config is None
+ assert any("(Q4_CR)" in str(reason) for reason in result.invalid_matches)
+
+
+def test_a_q4_cr_krea2_gguf_installs_as_a_krea2_gguf(tmp_path: Path) -> None:
+ result = _identify(_krea2_convrot(tmp_path / "krea2_turbo-Q4_CR.gguf", q4_cr_marker(4, 256), packed_int4=True))
+
+ assert isinstance(result.config, Main_GGUF_Krea2_Config)
+ assert not result.invalid_matches
+
+
+def test_the_retired_q4_cr_backing_is_refused_with_its_reason(tmp_path: Path) -> None:
+ """ComfyUI-GGUF's first Q4_CR was W4A16 with group-wise scales and no `backing` entry. Its own loader no longer
+ reads it either, and it stores its codes as I8 just the same."""
+ marker = q4_cr_marker(4, 256)
+ del marker["backing"]
+
+ result = _identify(_krea2_convrot(tmp_path / "krea2_turbo-Q4_CR.gguf", marker, packed_int4=True))
+
+ assert result.config is None
+ assert any("'int4_cr' without a backing" in str(reason) for reason in result.invalid_matches)
diff --git a/tests/backend/model_manager/configs/test_gguf_q8_cr_identification.py b/tests/backend/model_manager/configs/test_gguf_q8_cr_identification.py
deleted file mode 100644
index 668e9d5b9a..0000000000
--- a/tests/backend/model_manager/configs/test_gguf_q8_cr_identification.py
+++ /dev/null
@@ -1,76 +0,0 @@
-"""Install-time decisions for ComfyUI-GGUF ``Q8_CR`` files, made through ``ModelConfigFactory``.
-
-These run at the *default* ``allow_unknown``, because that is what decides what the user sees: a file a
-config recognises but cannot load must come back as a refusal with its reason, not register as an Unknown
-model whose explanation is only in the server log. Fixtures are real GGUF files of a few kilobytes.
-"""
-
-from pathlib import Path
-from typing import Any
-
-import pytest
-import torch
-
-from invokeai.backend.model_manager.configs.factory import ModelConfigFactory
-from invokeai.backend.model_manager.configs.main import Main_GGUF_Krea2_Config
-from tests.fixtures.quantized_payloads import q8_cr_marker, quantize_convrot, write_gguf
-
-_OVERRIDE_FIELDS: dict[str, object] = {
- "hash": "blake3:fakehash",
- "path": "/fake/models/test-model",
- "file_size": 1000,
- "name": "test-model",
- "description": "test",
- "source": "test",
- "source_type": "path",
- "key": "test-key",
-}
-
-
-def _krea2_q8_cr(path: Path, marker: dict[str, Any]) -> Path:
- """A native-named Krea-2 GGUF with one quantized layer, as ComfyUI-GGUF's converter writes one."""
- payload = quantize_convrot(torch.randn(4, 256))
- write_gguf(
- path,
- {
- "txtfusion.projector.weight": torch.ones(12, 1),
- "first.weight": torch.ones(8, 4),
- "tproj.0.weight": torch.ones(8, 4),
- "blocks.0.attn.wq.weight": payload.codes,
- "blocks.0.attn.wq.weight_scale": payload.scale,
- },
- quant={"blocks.0.attn.wq.weight": marker},
- )
- return path
-
-
-def _identify(path: Path) -> Any:
- return ModelConfigFactory.from_model_on_disk(path, dict(_OVERRIDE_FIELDS), allow_unknown=True)
-
-
-def test_a_q8_cr_krea2_gguf_installs_as_a_krea2_gguf(tmp_path: Path) -> None:
- result = _identify(_krea2_q8_cr(tmp_path / "krea2_turbo-Q8_CR.gguf", q8_cr_marker()))
-
- assert isinstance(result.config, Main_GGUF_Krea2_Config)
- assert not result.invalid_matches
-
-
-def test_a_q8_cr_gguf_is_refused_with_its_reason_where_the_loader_cannot_decode_it(
- tmp_path: Path, monkeypatch: pytest.MonkeyPatch
-) -> None:
- """The gate every other GGUF config sits behind. Driven through the Krea-2 config with its
- capability switched off, so the fixture is one that is otherwise known to install."""
- monkeypatch.setattr(Main_GGUF_Krea2_Config, "DECODES_GGUF_Q8_CR", False)
-
- result = _identify(_krea2_q8_cr(tmp_path / "krea2_turbo-Q8_CR.gguf", q8_cr_marker()))
-
- assert result.config is None
- assert any("Q8_CR" in str(reason) for reason in result.invalid_matches)
-
-
-def test_a_q4_cr_gguf_is_refused_with_its_reason(tmp_path: Path) -> None:
- """ComfyUI-GGUF's Q4_CR is advertised beside Q8_CR and stores its codes as I8 as well."""
- result = _identify(_krea2_q8_cr(tmp_path / "krea2_turbo-Q4_CR.gguf", {"format": "int4_cr", "backing": "w4a4"}))
-
- assert result.config is None
- assert any("int4_cr" in str(reason) for reason in result.invalid_matches)
diff --git a/tests/backend/model_manager/configs/test_ideogram4_checkpoint_config.py b/tests/backend/model_manager/configs/test_ideogram4_checkpoint_config.py
index a819f32272..6093280855 100644
--- a/tests/backend/model_manager/configs/test_ideogram4_checkpoint_config.py
+++ b/tests/backend/model_manager/configs/test_ideogram4_checkpoint_config.py
@@ -195,13 +195,15 @@ class TestRefusals:
assert config.branch == "unconditional"
@pytest.mark.parametrize(
- ("marker", "case"),
+ ("marker", "refusal"),
[
- (None, "no marker at all"),
- ({"format": "int8_dynamic"}, "a scheme this loader cannot build"),
+ pytest.param(None, "no readable marker of a format it loads", id="no marker at all"),
+ pytest.param({"format": "int8_dynamic"}, "marked 'int8_dynamic'", id="a scheme this loader cannot build"),
],
)
- def test_rejects_int8_weights_with_no_readable_marker(self, tmp_path: Path, marker: dict | None, case: str) -> None:
+ def test_rejects_int8_weights_with_no_readable_marker(
+ self, tmp_path: Path, marker: dict | None, refusal: str
+ ) -> None:
"""The loader refuses these, so identification has to as well.
A rotated weight loaded as if it were not one generates noise, which is why
@@ -210,7 +212,7 @@ class TestRefusals:
"""
sd = _state_dict(**_int8_layer("layers.0.attention.qkv", marker=marker))
- with pytest.raises(InvalidMatchError, match="no readable 'int8_tensorwise' marker"):
+ with pytest.raises(InvalidMatchError, match=refusal):
_identify(_mod_on_disk(sd, tmp_path, name="ideogram4_int8.safetensors"))
def test_accepts_the_scaled_fp8_release(self) -> None:
diff --git a/tests/backend/model_manager/configs/test_krea2_main_config.py b/tests/backend/model_manager/configs/test_krea2_main_config.py
index e8eee77b97..dde31b272d 100644
--- a/tests/backend/model_manager/configs/test_krea2_main_config.py
+++ b/tests/backend/model_manager/configs/test_krea2_main_config.py
@@ -15,13 +15,16 @@ from tempfile import TemporaryDirectory
from unittest.mock import MagicMock, patch
import pytest
+import torch
+from safetensors.torch import save_file
from invokeai.backend.architectures import resolve_default_settings
-from invokeai.backend.model_manager.configs.identification_utils import NotAMatchError
+from invokeai.backend.model_manager.configs.identification_utils import InvalidMatchError, NotAMatchError
from invokeai.backend.model_manager.configs.main import (
_get_krea2_variant_from_name,
_has_krea2_keys,
)
+from invokeai.backend.model_manager.model_on_disk import ModelOnDisk
from invokeai.backend.model_manager.taxonomy import BaseModelType, Krea2VariantType
# Required fields for the Pydantic config models (mirrors the other config-probe tests).
@@ -197,6 +200,88 @@ class TestKrea2CheckpointVariantDetection:
Main_Checkpoint_Krea2_Config.from_model_on_disk(mod, {**_REQUIRED_FIELDS})
+class TestKrea2CheckpointQuantizationAtInstall:
+ """What the loader would refuse is refused at install, with the format named: an int8 layer the file marks as
+ something Krea-2 does not decode, or marks only ambiguously in its header. The int4 builds install. Driven
+ through a real `ModelOnDisk` over a real file: identification reads the markers from the file, because its
+ state dict is on the meta device."""
+
+ @staticmethod
+ def _mod(tmp_path: Path, layers: dict[str, dict | None], header: dict[str, dict] | None = None) -> ModelOnDisk:
+ """One int8 layer per entry of `layers`, with that per-tensor marker (None: none), and `header` as the
+ `_quantization_metadata` layers."""
+ state_dict: dict[str, torch.Tensor] = {}
+ for path, marker in layers.items():
+ state_dict[f"{path}.weight"] = torch.zeros(4, 128, dtype=torch.int8)
+ state_dict[f"{path}.weight_scale"] = torch.ones(4)
+ if marker is not None:
+ raw = json.dumps(marker).encode("utf-8")
+ state_dict[f"{path}.comfy_quant"] = torch.frombuffer(bytearray(raw), dtype=torch.uint8).clone()
+ metadata = {"_quantization_metadata": json.dumps({"layers": header})} if header else None
+ path = tmp_path / "krea2_turbo_int4.safetensors"
+ save_file(state_dict, path, metadata=metadata)
+ return ModelOnDisk(path, "random")
+
+ @staticmethod
+ def _identify(mod: ModelOnDisk):
+ from invokeai.backend.model_manager.configs.main import Main_Checkpoint_Krea2_Config
+
+ with (
+ patch("invokeai.backend.model_manager.configs.main._has_krea2_keys", return_value=True),
+ patch("invokeai.backend.model_manager.configs.main.raise_for_override_fields"),
+ ):
+ return Main_Checkpoint_Krea2_Config.from_model_on_disk(mod, {**_REQUIRED_FIELDS})
+
+ @pytest.mark.parametrize(
+ ("marker", "header"),
+ [
+ pytest.param(None, {"blocks.0.attn.wq": {"format": "convrot_w4a4"}}, id="header only, Starnodes"),
+ pytest.param({"format": "int4_tensorwise", "convrot": True}, None, id="per-tensor, comfy-quants"),
+ ],
+ )
+ def test_an_int4_build_installs(self, tmp_path: Path, marker: dict | None, header: dict | None) -> None:
+ mod = self._mod(tmp_path, {"blocks.0.attn.wq": marker}, header)
+
+ assert self._identify(mod).variant == Krea2VariantType.Turbo
+
+ def test_a_header_naming_its_layers_without_the_checkpoint_prefix_still_names_them(self, tmp_path: Path) -> None:
+ """The loader compares both after stripping the prefix, so identification has to as well."""
+ mod = self._mod(
+ tmp_path, {"model.diffusion_model.blocks.0.attn.wq": None}, {"blocks.0.attn.wq": {"format": "convrot_w4a4"}}
+ )
+
+ assert self._identify(mod).variant == Krea2VariantType.Turbo
+
+ def test_a_format_krea2_does_not_decode_is_refused_by_name(self, tmp_path: Path) -> None:
+ mod = self._mod(tmp_path, {"blocks.0.attn.wq": None}, {"blocks.0.attn.wq": {"format": "asym_w4a8_int8"}})
+
+ with pytest.raises(InvalidMatchError, match="marked 'asym_w4a8_int8'"):
+ self._identify(mod)
+
+ def test_a_per_tensor_marker_wins_over_the_header_as_it_does_at_load(self, tmp_path: Path) -> None:
+ mod = self._mod(
+ tmp_path,
+ {"blocks.0.attn.wq": {"format": "asym_w4a8_int8"}},
+ {"blocks.0.attn.wq": {"format": "convrot_w4a4"}},
+ )
+
+ with pytest.raises(InvalidMatchError, match="marked 'asym_w4a8_int8'"):
+ self._identify(mod)
+
+ def test_a_header_entry_that_does_not_say_whether_the_layer_was_rotated_is_refused(self, tmp_path: Path) -> None:
+ mod = self._mod(tmp_path, {"blocks.0.attn.wq": None}, {"blocks.0.attn.wq": {"format": "int8_tensorwise"}})
+
+ with pytest.raises(InvalidMatchError, match="does not say whether the weight was rotated"):
+ self._identify(mod)
+
+ def test_the_final_block_projections_the_loader_drops_are_not_checked(self, tmp_path: Path) -> None:
+ """One repack quantizes `last.up` in a scheme of its own; the loader discards that layer before it reads any
+ marker, so it loads, and refusing it here would refuse a file that works."""
+ mod = self._mod(tmp_path, {"blocks.0.attn.wq": {"format": "int4_tensorwise", "convrot": True}, "last.up": None})
+
+ assert self._identify(mod).variant == Krea2VariantType.Turbo
+
+
class TestKrea2DiffusersVariantDetection:
"""Main_Diffusers_Krea2_Config._get_variant reads is_distilled from model_index.json."""
diff --git a/tests/backend/model_manager/load/test_flux1_int8_convrot_loader.py b/tests/backend/model_manager/load/test_flux1_int8_convrot_loader.py
index bf57a59741..bdc23708d4 100644
--- a/tests/backend/model_manager/load/test_flux1_int8_convrot_loader.py
+++ b/tests/backend/model_manager/load/test_flux1_int8_convrot_loader.py
@@ -283,7 +283,7 @@ def test_a_file_mixing_int8_with_scaled_fp8_is_refused(monkeypatch, tmp_path) ->
state_dict["double_blocks.0.img_attn.proj.weight"] = fp8.codes
state_dict["double_blocks.0.img_attn.proj.weight_scale"] = fp8.scale
- with pytest.raises(ValueError, match="mixing int8_tensorwise with scaled fp8"):
+ with pytest.raises(ValueError, match="mixing convrot layers with scaled fp8"):
_load(monkeypatch, tmp_path, state_dict)
diff --git a/tests/backend/model_manager/load/test_flux2_int8_convrot_loader.py b/tests/backend/model_manager/load/test_flux2_int8_convrot_loader.py
index 32a50df156..cb42cd4a15 100644
--- a/tests/backend/model_manager/load/test_flux2_int8_convrot_loader.py
+++ b/tests/backend/model_manager/load/test_flux2_int8_convrot_loader.py
@@ -315,7 +315,7 @@ def test_a_file_mixing_int8_with_scaled_fp8_is_refused(monkeypatch, tmp_path) ->
state_dict["final_layer.linear.weight"] = fp8.codes
state_dict["final_layer.linear.weight_scale"] = fp8.scale
- with pytest.raises(ValueError, match="mixing int8_tensorwise with scaled fp8"):
+ with pytest.raises(ValueError, match="mixing convrot layers with scaled fp8"):
_load(monkeypatch, tmp_path, state_dict)
diff --git a/tests/backend/model_manager/load/test_ideogram4_checkpoint_loader.py b/tests/backend/model_manager/load/test_ideogram4_checkpoint_loader.py
index c22fc2363d..35ed70d13b 100644
--- a/tests/backend/model_manager/load/test_ideogram4_checkpoint_loader.py
+++ b/tests/backend/model_manager/load/test_ideogram4_checkpoint_loader.py
@@ -449,5 +449,5 @@ def test_a_file_mixing_int8_with_scaled_fp8_is_refused(monkeypatch, tmp_path) ->
state_dict["final_layer.linear.weight"] = fp8.codes
state_dict["final_layer.linear.weight_scale"] = fp8.scale
- with pytest.raises(ValueError, match="mixing int8_tensorwise with scaled fp8"):
+ with pytest.raises(ValueError, match="mixing convrot layers with scaled fp8"):
_load(monkeypatch, tmp_path, state_dict, keep_fp8=False, geometry=INT8_CONFIG)
diff --git a/tests/backend/model_manager/load/test_int8_through_the_fp8_fold.py b/tests/backend/model_manager/load/test_int8_through_the_fp8_fold.py
index b91f0ed133..3b50a8910a 100644
--- a/tests/backend/model_manager/load/test_int8_through_the_fp8_fold.py
+++ b/tests/backend/model_manager/load/test_int8_through_the_fp8_fold.py
@@ -112,13 +112,13 @@ def test_the_other_scale_spelling_is_refused_too() -> None:
def test_a_header_entry_is_not_taken_as_evidence_that_a_layer_is_safe() -> None:
- """The safetensors header names formats too, but it cannot carry `convrot` or the group size --
- which is why `flux.py` gives the per-tensor marker precedence. An earlier version of this guard
+ """The safetensors header names formats too, but Comfy-Org's header entries carry neither `convrot` nor
+ the group size -- which is why `flux.py` gives the per-tensor marker precedence. An earlier version of this guard
let a header hint override the marker, so a header-named rotated build walked straight through
into the unrotated fold. The guard reads the marker and nothing else; the header is simulated
here by the only thing that could stand in for it, a marker of the wrong format.
"""
state_dict, _ = _int8_layer({"format": "float8_e4m3fn"}, rotate=True)
- with pytest.raises(ValueError, match="no int8_tensorwise marker"):
+ with pytest.raises(ValueError, match="marked 'float8_e4m3fn'"):
_dequantize_comfyui_fp8(state_dict, torch.float32)
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 29082594df..adec4e24f4 100644
--- a/tests/backend/model_manager/load/test_krea2_loader_boundaries.py
+++ b/tests/backend/model_manager/load/test_krea2_loader_boundaries.py
@@ -21,7 +21,7 @@ from invokeai.backend.model_manager.load.model_loaders.krea2 import (
Qwen3VLEncoderLoader,
)
from invokeai.backend.model_manager.taxonomy import Krea2VariantType, Qwen3VLVariantType, SubModelType
-from invokeai.backend.quantization.int8_convrot import Int8ConvrotLinear
+from invokeai.backend.quantization.int8_convrot import Int4ConvrotLinear, Int8ConvrotLinear
class _TinyVisionTowerHost(torch.nn.Module):
@@ -173,6 +173,80 @@ def test_single_file_loader_decodes_an_int8_convrot_checkpoint(monkeypatch, tmp_
assert torch.corrcoef(torch.stack([dequantized, rotated.flatten()]))[0, 1].abs() < 0.2
+def test_single_file_loader_keeps_a_mixed_int4_build_named_only_in_its_header_packed(monkeypatch, tmp_path) -> None:
+ """The Starnodes converter deletes every per-tensor marker and names its layers in `_quantization_metadata`
+ alone, and most published int4 builds mix int8 layers in. Both have to be read, each layer installed as it is
+ stored, and the reservation has to charge the packed layer the half byte per weight it actually occupies."""
+ import json
+
+ import diffusers
+ import safetensors.torch
+
+ from invokeai.backend.quantization.int8_convrot import CONVROT_GROUP_SIZE
+ from tests.fixtures.quantized_payloads import (
+ comfy_quant_marker,
+ convrot_w4a4_marker,
+ quantize_convrot,
+ quantize_convrot_int4,
+ )
+
+ torch.manual_seed(0)
+ original = torch.randn(4, CONVROT_GROUP_SIZE)
+ int4 = quantize_convrot_int4(original)
+ int8 = quantize_convrot(torch.randn(4, CONVROT_GROUP_SIZE))
+ int8_marker = {"format": "int8_tensorwise", "convrot": True, "convrot_groupsize": CONVROT_GROUP_SIZE}
+ state_dict = {
+ "packed.weight": int4.packed,
+ "packed.weight_scale": int4.scale.view(-1),
+ "wide.weight": int8.codes,
+ "wide.weight_scale": int8.scale,
+ "wide.comfy_quant": comfy_quant_marker(int8_marker),
+ }
+ header = {
+ "_quantization_metadata": json.dumps({"format_version": "1.0", "layers": {"packed": convrot_w4a4_marker()}})
+ }
+
+ class _TinyMixedKrea2Transformer(torch.nn.Module):
+ def __init__(self, **_kwargs) -> None:
+ super().__init__()
+ self.packed = torch.nn.Linear(CONVROT_GROUP_SIZE, 4, bias=False)
+ self.wide = torch.nn.Linear(CONVROT_GROUP_SIZE, 4, bias=False)
+
+ checkpoint_path = tmp_path / "krea2Int4Convrot_v10Turbo.safetensors"
+ checkpoint_path.touch()
+ config = Main_Checkpoint_Krea2_Config.model_construct(
+ path=str(checkpoint_path), variant=Krea2VariantType.Turbo, fp8_storage=None
+ )
+ loader = object.__new__(Krea2CheckpointModel)
+ loader._ram_cache = SimpleNamespace(make_room=MagicMock())
+ loader._logger = MagicMock()
+ loader._torch_device = torch.device("cpu")
+ loader._apply_fp8_layerwise_casting = lambda model, _config, _submodel: model
+
+ monkeypatch.setattr(diffusers, "Krea2Transformer2DModel", _TinyMixedKrea2Transformer, raising=False)
+ monkeypatch.setattr(safetensors.torch, "load_file", lambda _path: state_dict)
+ monkeypatch.setattr(
+ "invokeai.backend.model_manager.load.model_loaders.krea2.read_safetensors_metadata", lambda *_args: header
+ )
+ 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)
+
+ (reserved,), _ = loader._ram_cache.make_room.call_args
+ assert reserved == (4 * CONVROT_GROUP_SIZE // 2 + 4 * 4) + (4 * CONVROT_GROUP_SIZE + 4 * 4)
+ assert type(model.packed) is Int4ConvrotLinear and type(model.wide) is Int8ConvrotLinear
+ decoded = model.packed._dequantized_weight(torch.device("cpu"), torch.float32)
+ assert torch.allclose(decoded, int4.dequantized, atol=1e-5)
+ assert torch.corrcoef(torch.stack([decoded.flatten(), original.flatten()]))[0, 1] > 0.98
+
+
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)
@@ -275,6 +349,35 @@ def test_gguf_loader_keeps_a_q8_cr_layer_int8_through_the_native_rename(monkeypa
assert isinstance(model.img_in.weight, GGMLTensor)
+def test_gguf_loader_keeps_a_q4_cr_layer_packed_through_the_native_rename(monkeypatch, tmp_path) -> None:
+ """Q4_CR's codes are stored packed and its scale in fp16; both have to reach an `Int4ConvrotLinear` under the
+ weight's diffusers name, decoding to the round trip with the scale ComfyUI-GGUF actually stored."""
+ from tests.fixtures.quantized_payloads import q4_cr_marker, quantize_convrot_int4, write_gguf
+
+ width = _TinyNativeKrea2.WIDTH
+ group_size = 4
+ torch.manual_seed(8)
+ payload = quantize_convrot_int4(torch.randn(width, width), group_size=group_size)
+ stored_scale = payload.scale.view(-1).half()
+ tensors = {
+ **_native_block(width),
+ "blocks.0.attn.wq.weight": payload.packed,
+ "blocks.0.attn.wq.weight_scale": stored_scale,
+ }
+ path = tmp_path / "krea2TurboINT4GGUF.gguf"
+ write_gguf(path, tensors, quant={"blocks.0.attn.wq.weight": q4_cr_marker(width, width, group_size=group_size)})
+ loader, config = _gguf_driver(monkeypatch, path, _TinyNativeKrea2)
+
+ model = loader._load_from_gguf(config)
+
+ to_q = model.transformer_blocks[0].attn.to_q
+ assert isinstance(to_q, Int4ConvrotLinear)
+ assert to_q.weight.shape == (width, width // 2)
+ # Each row of the round trip is proportional to its scale, so the fp16 rounding of the stored scale is exact.
+ expected = payload.dequantized * (stored_scale.float() / payload.scale.view(-1)).unsqueeze(1)
+ assert torch.allclose(to_q._dequantized_weight(torch.device("cpu"), torch.float32), expected, atol=1e-5)
+
+
def test_gguf_loader_refuses_an_i8_tensor_no_metadata_claims(monkeypatch, tmp_path) -> None:
"""`gguf` has no dequantizer for `I8`, so an unclaimed int8 tensor used to load and then fail on the
first denoise step with `Dequantization for I8 is not yet implemented`."""
@@ -587,7 +690,7 @@ def test_a_checkpoint_mixing_int8_and_fp8_is_refused(monkeypatch, tmp_path) -> N
}
loader, config = _int8_transformer_driver(monkeypatch, tmp_path, _TinyMixedKrea2, state_dict)
- with pytest.raises(ValueError, match=r"weight scale\(s\) that no `int8_tensorwise` marker claims"):
+ with pytest.raises(ValueError, match=r"weight scale\(s\) that no int8 or int4 convrot marker claims"):
loader._load_from_singlefile(config)
diff --git a/tests/backend/quantization/data/z_image_turbo_convrot_w4a4_slices.safetensors b/tests/backend/quantization/data/z_image_turbo_convrot_w4a4_slices.safetensors
new file mode 100644
index 0000000000..8867244947
Binary files /dev/null and b/tests/backend/quantization/data/z_image_turbo_convrot_w4a4_slices.safetensors differ
diff --git a/tests/backend/quantization/gguf/test_loaders.py b/tests/backend/quantization/gguf/test_loaders.py
index 29dd7bcf2f..38ba5c4847 100644
--- a/tests/backend/quantization/gguf/test_loaders.py
+++ b/tests/backend/quantization/gguf/test_loaders.py
@@ -15,7 +15,13 @@ from invokeai.backend.quantization.gguf.loaders import (
gguf_tensor_bytes,
unpack_ggml_at_load,
)
-from tests.fixtures.quantized_payloads import q8_cr_marker, quantize_convrot, write_gguf
+from tests.fixtures.quantized_payloads import (
+ q4_cr_marker,
+ q8_cr_marker,
+ quantize_convrot,
+ quantize_convrot_int4,
+ write_gguf,
+)
def _write_gguf(path, *, orig_shape: Sequence[float] | None) -> None:
@@ -101,7 +107,7 @@ def test_a_q8_cr_layer_loads_as_an_int8_tensorwise_export(tmp_path):
q8_0={"blocks.0.mlp.up.weight": torch.randn(4, 64)},
)
- sd = gguf_sd_loader(path, compute_dtype=torch.float32, q8_cr="decode")
+ sd = gguf_sd_loader(path, compute_dtype=torch.float32, convrot="decode")
weight, scale = sd["blocks.0.attn.wq.weight"], sd["blocks.0.attn.wq.weight_scale"]
assert not isinstance(weight, GGMLTensor) and torch.equal(weight, tensors["blocks.0.attn.wq.weight"])
@@ -118,7 +124,7 @@ def test_a_q8_cr_file_is_refused_unless_the_caller_decodes_int8(tmp_path):
path = tmp_path / "model.gguf"
write_gguf(path, _q8_cr_layer("blocks.0.attn.wq"), quant={"blocks.0.attn.wq.weight": q8_cr_marker()})
- with pytest.raises(ValueError, match=r"model\.gguf holds 1 ComfyUI-GGUF Q8_CR"):
+ with pytest.raises(ValueError, match=r"model\.gguf holds 1 ComfyUI-GGUF convrot \(Q8_CR or Q4_CR\)"):
gguf_sd_loader(path, compute_dtype=torch.float32)
@@ -148,7 +154,7 @@ def test_a_convrot_layer_not_marked_weight_rotated_is_read_unrotated(tmp_path, w
del marker["weight_rotated"]
write_gguf(path, _q8_cr_layer("proj"), quant={"proj.weight": marker})
- markers = extract_int8_convrot_markers(gguf_sd_loader(path, compute_dtype=torch.float32, q8_cr="decode"))
+ markers = extract_int8_convrot_markers(gguf_sd_loader(path, compute_dtype=torch.float32, convrot="decode"))
assert markers["proj"]["convrot"] is False
assert "convrot_groupsize" not in markers["proj"]
@@ -161,7 +167,7 @@ def test_an_int8_layers_bias_is_read_as_a_plain_tensor(tmp_path):
bias = torch.arange(4, dtype=torch.float32)
write_gguf(path, {**_q8_cr_layer("proj"), "proj.bias": bias}, quant={"proj.weight": q8_cr_marker()})
- sd = gguf_sd_loader(path, compute_dtype=torch.float32, q8_cr="decode")
+ sd = gguf_sd_loader(path, compute_dtype=torch.float32, convrot="decode")
assert not isinstance(sd["proj.bias"], GGMLTensor)
assert torch.equal(sd["proj.bias"], bias)
@@ -171,10 +177,10 @@ def test_an_int8_layers_bias_is_read_as_a_plain_tensor(tmp_path):
("quant", "tensors", "message"),
[
pytest.param(
- {"proj.weight": {"format": "int4_cr", "backing": "w4a4"}},
+ {"proj.weight": {"format": "int4_pytorch"}},
{},
- "quantization 'int4_cr', which is not supported",
- id="int4",
+ "quantization 'int4_pytorch', which is not supported",
+ id="retired-int4",
),
pytest.param({"proj.weight": "{not json"}, {}, "is not valid quantization JSON", id="malformed-json"),
pytest.param({"proj": q8_cr_marker()}, {}, "names 'proj', not a weight", id="not-a-weight"),
@@ -198,7 +204,70 @@ def test_a_q8_cr_file_the_decode_cannot_read_is_refused(tmp_path, quant, tensors
write_gguf(path, {k: v for k, v in layer.items() if v is not None}, quant=quant)
with pytest.raises(ValueError, match=message):
- gguf_sd_loader(path, compute_dtype=torch.float32, q8_cr="decode")
+ gguf_sd_loader(path, compute_dtype=torch.float32, convrot="decode")
+
+
+def _q4_cr_layer(name: str, out_features: int = 4, in_features: int = 256, seed: int = 0) -> dict[str, torch.Tensor]:
+ """One Q4_CR layer's tensors as ComfyUI-GGUF writes them: packed codes and an F16 scale per row."""
+ torch.manual_seed(seed)
+ payload = quantize_convrot_int4(torch.randn(out_features, in_features))
+ return {f"{name}.weight": payload.packed, f"{name}.weight_scale": payload.scale.view(-1).half()}
+
+
+def test_a_q4_cr_layer_loads_as_an_int4_tensorwise_export(tmp_path):
+ """Packed codes as stored, the scale widened to the fp32 the int4 module holds, and a marker the int4 decode
+ reads as rotated: the w4a4 backing has no `weight_rotated` flag and is rotated by definition."""
+ from invokeai.backend.quantization.int8_convrot import extract_int8_convrot_markers, marker_layout
+
+ path = tmp_path / "model.gguf"
+ tensors = _q4_cr_layer("blocks.0.attn.wq")
+ write_gguf(path, tensors, quant={"blocks.0.attn.wq.weight": q4_cr_marker(4, 256)})
+
+ sd = gguf_sd_loader(path, compute_dtype=torch.float32, convrot="decode")
+
+ assert torch.equal(sd["blocks.0.attn.wq.weight"], tensors["blocks.0.attn.wq.weight"])
+ scale = sd["blocks.0.attn.wq.weight_scale"]
+ assert scale.dtype is torch.float32 and torch.equal(scale, tensors["blocks.0.attn.wq.weight_scale"].float())
+ (marker,) = extract_int8_convrot_markers(sd, accept_int4=True).values()
+ assert marker_layout(marker).packed_int4 and marker_layout(marker).convrot
+
+
+ ("marker", "tensors", "message"),
+ [
+ pytest.param(
+ q4_cr_marker(4, 512),
+ {},
+ r"stored as \(4, 128\), which does not hold the packed codes of its declared \(4, 512\)",
+ id="orig-shape-mismatch",
+ ),
+ pytest.param(q4_cr_marker(4, 256, orig_shape=None), {}, "no usable orig_shape", id="no-orig-shape"),
+ pytest.param(
+ q4_cr_marker(4, 256),
+ {"proj.weight_scale": torch.ones(4)},
+ "'proj.weight_scale' is stored as F32, expected F16",
+ id="scale-not-f16",
+ ),
+ pytest.param(
+ q4_cr_marker(4, 256, backing="w4a16"),
+ {},
+ "'int4_cr' with backing 'w4a16', which is not supported",
+ id="retired-backing",
+ ),
+ pytest.param(q4_cr_marker(4, 256, sym=False), {}, "sym=False.*only symmetric", id="asymmetric"),
+ pytest.param(
+ q4_cr_marker(4, 256, weight_rotated=False), {}, "weight_rotated=False.*pre-rotated", id="unrotated"
+ ),
+ pytest.param(q4_cr_marker(4, 256, convrot_groupsize=None), {}, "no usable convrot_groupsize", id="no-group"),
+ pytest.param('"int4_cr"', {}, "is not a quantization object", id="not-an-object"),
+ ],
+)
+def test_a_q4_cr_file_the_decode_cannot_read_is_refused(tmp_path, marker, tensors, message):
+ path = tmp_path / "model.gguf"
+ write_gguf(path, {**_q4_cr_layer("proj"), **tensors}, quant={"proj.weight": marker})
+
+ with pytest.raises(ValueError, match=message):
+ gguf_sd_loader(path, compute_dtype=torch.float32, convrot="decode")
def test_keep_reads_only_the_tensors_it_selects(tmp_path):
diff --git a/tests/backend/quantization/test_int4_convrot.py b/tests/backend/quantization/test_int4_convrot.py
new file mode 100644
index 0000000000..59094288b2
--- /dev/null
+++ b/tests/backend/quantization/test_int4_convrot.py
@@ -0,0 +1,309 @@
+"""The packed int4 convrot layouts: ``convrot_w4a4``, ``int4_tensorwise`` and, via GGUF, ``Q4_CR``.
+
+They share the int8 scheme's scale and rotation and differ in one thing a decoder can get wrong without any
+shape or dtype check noticing: two signed codes per byte, the LOW nibble first. Read in nvfp4's order, or
+without the rotation, a layer still has the right shape and roughly the right magnitude.
+"""
+
+from pathlib import Path
+
+import pytest
+import torch
+from safetensors.torch import load_file
+
+from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.torch_module_autocast import (
+ apply_custom_layers_to_model,
+)
+from invokeai.backend.model_manager.taxonomy import ModelFormat
+from invokeai.backend.patches.layer_patcher import LayerPatcher
+from invokeai.backend.patches.layers.full_layer import FullLayer
+from invokeai.backend.patches.layers.lora_layer import LoRALayer
+from invokeai.backend.patches.model_patch_raw import ModelPatchRaw
+from invokeai.backend.quantization.dequantizing_linear import peak_dequant_transient_bytes, requires_sidecar_patching
+from invokeai.backend.quantization.int8_convrot import (
+ CONVROT_GROUP_SIZE,
+ ConvrotLayout,
+ Int4ConvrotLinear,
+ extract_int8_convrot_markers,
+ marker_layout,
+ unpack_int4_codes,
+)
+from tests.fixtures.device_allocations import PeakDeviceBytes
+from tests.fixtures.quantized_payloads import (
+ comfy_quant_marker,
+ convrot_w4a4_marker,
+ int4_tensorwise_marker,
+ quantize_convrot_int4,
+)
+
+FIXTURE = Path(__file__).parent / "data" / "z_image_turbo_convrot_w4a4_slices.safetensors"
+
+
+def _swap_nibbles(packed: torch.Tensor) -> torch.Tensor:
+ """The same bytes read in nvfp4's order, high nibble first."""
+ u = packed.view(torch.uint8)
+ return ((u >> 4) | (u << 4)).view(torch.int8)
+
+
+def test_every_byte_unpacks_to_its_two_signed_nibbles_low_first() -> None:
+ packed = torch.arange(256, dtype=torch.int32).to(torch.uint8).view(torch.int8).view(1, 256)
+
+ codes = unpack_int4_codes(packed)
+
+ def signed(nibble: int) -> int:
+ return nibble - 16 if nibble >= 8 else nibble
+
+ expected = [value for byte in range(256) for value in (signed(byte & 0x0F), signed(byte >> 4))]
+ assert codes.dtype is torch.int8
+ assert codes.tolist() == [expected]
+
+
+def test_the_module_decodes_a_comfy_kitchen_payload_to_its_round_trip() -> None:
+ torch.manual_seed(0)
+ payload = quantize_convrot_int4(torch.randn(48, 2 * CONVROT_GROUP_SIZE))
+ module = Int4ConvrotLinear(payload.packed, payload.scale, convrot=True)
+
+ decoded = module._dequantized_weight(torch.device("cpu"), torch.float32)
+
+ assert (module.out_features, module.in_features) == (48, 2 * CONVROT_GROUP_SIZE)
+ assert torch.allclose(decoded, payload.dequantized, atol=1e-5)
+ x = torch.randn(5, 2 * CONVROT_GROUP_SIZE)
+ assert torch.allclose(module(x), torch.nn.functional.linear(x, payload.dequantized), atol=1e-4)
+
+
[email protected]("layer", ["layers.0.attention.out", "layers.0.feed_forward.w2"])
+def test_a_real_checkpoint_slice_decodes_to_its_bf16_source(layer: str) -> None:
+ """JoaoZaokk/Z-Image-Turbo-W4A4-ConvRot at revision 71a4af3c75208746513ed4bca0e067b3fbf7d080 (Apache-2.0):
+ the first rows of two `convrot_w4a4` layers of `zimage_turbo_w4a4.safetensors`, beside the same rows of
+ Tongyi-MAI/Z-Image-Turbo's transformer (Apache-2.0) in bf16. A row slice decodes exactly as it does in the
+ full matrix, because the rotation acts within each row.
+
+ Measured when cut: cosine 0.984 for both, the 4-bit floor -- and 0.98-0.99 on Krea-2 Turbo builds of all
+ three spellings, which are not redistributable. The two misreadings this pins land near zero: the nibbles
+ in nvfp4's order, and the scale applied without undoing the rotation.
+ """
+ fixture = load_file(FIXTURE)
+ packed, scale = fixture[f"{layer}.weight"], fixture[f"{layer}.weight_scale"]
+ reference = fixture[f"{layer}.bf16_reference"].float().flatten()
+
+ def cosine(weight: torch.Tensor) -> float:
+ return torch.cosine_similarity(weight.flatten(), reference, dim=0).item()
+
+ decoded = Int4ConvrotLinear(packed, scale, convrot=True)._dequantized_weight(torch.device("cpu"), torch.float32)
+ assert cosine(decoded) > 0.98
+ assert (decoded.norm() / reference.norm()).item() == pytest.approx(1.0, abs=0.05)
+
+ swapped = Int4ConvrotLinear(_swap_nibbles(packed), scale, convrot=True)
+ assert abs(cosine(swapped._dequantized_weight(torch.device("cpu"), torch.float32))) < 0.1
+ unrotated = Int4ConvrotLinear(packed, scale, convrot=False)
+ assert abs(cosine(unrotated._dequantized_weight(torch.device("cpu"), torch.float32))) < 0.2
+
+
+def test_the_module_registers_the_checkpoints_own_keys_and_reports_its_unpacked_width() -> None:
+ """`load_state_dict` assigns the file's tensors straight into these buffers, and LoRA sidecars and the model
+ cache's patch shapes are built from `in_features`, which has to be the width the layer computes with."""
+ torch.manual_seed(1)
+ payload = quantize_convrot_int4(torch.randn(16, CONVROT_GROUP_SIZE))
+
+ module = Int4ConvrotLinear(payload.packed, payload.scale, convrot=True, bias=torch.randn(16))
+
+ assert set(module.state_dict()) == {"weight", "weight_scale", "bias"}
+ assert module.state_dict()["weight"].shape == (16, CONVROT_GROUP_SIZE // 2)
+ assert module.in_features == CONVROT_GROUP_SIZE
+
+
+def test_a_lora_and_a_full_layer_patch_ride_as_sidecars_over_the_packed_weight() -> None:
+ """Patches cannot be written into packed buffers, so the model has to be recognised as needing sidecars once the
+ model cache has wrapped the module, and patches that are not LoRAs have to be handed the unpacked weight shape
+ to be reshaped to -- half the stored width would not reshape at all."""
+ torch.manual_seed(2)
+ payload = quantize_convrot_int4(torch.randn(12, CONVROT_GROUP_SIZE))
+ bias = torch.randn(12)
+ model = torch.nn.Module()
+ model.proj = Int4ConvrotLinear(payload.packed, payload.scale, convrot=True, bias=bias)
+ apply_custom_layers_to_model(model)
+ up, down, full = torch.randn(12, 3), torch.randn(3, CONVROT_GROUP_SIZE), torch.randn(12, CONVROT_GROUP_SIZE)
+ lora = ModelPatchRaw(layers={"lora-proj": LoRALayer(up=up, mid=None, down=down, alpha=None, bias=None)})
+ full_diff = ModelPatchRaw(layers={"lora-proj": FullLayer(weight=full, bias=None)})
+ x = torch.randn(3, CONVROT_GROUP_SIZE)
+ dense = torch.nn.functional.linear(x, payload.dequantized, bias)
+
+ with LayerPatcher.apply_smart_model_patches(
+ model=model,
+ patches=[(lora, 0.75), (full_diff, 0.5)],
+ prefix="lora-",
+ dtype=torch.float32,
+ force_sidecar_patching=requires_sidecar_patching(model, ModelFormat.Checkpoint),
+ ):
+ patched = model.proj(x)
+
+ expected = torch.nn.functional.linear(x, payload.dequantized + 0.75 * (up @ down) + 0.5 * full, bias)
+ assert torch.allclose(patched, expected, atol=1e-4)
+ assert model.proj.get_num_patches() == 0
+ assert torch.allclose(model.proj(x), dense, atol=1e-5)
+
+
+ ("marker", "layout"),
+ [
+ pytest.param(convrot_w4a4_marker(), ConvrotLayout(True, True, 256), id="convrot_w4a4 is rotated by definition"),
+ pytest.param(int4_tensorwise_marker(), ConvrotLayout(True, True, 256), id="int4_tensorwise"),
+ pytest.param(
+ int4_tensorwise_marker(convrot=False, group_size=64), ConvrotLayout(True, False, 64), id="int4 unrotated"
+ ),
+ pytest.param({"format": "int8_tensorwise"}, ConvrotLayout(False, False, 256), id="int8 without convrot"),
+ ],
+)
+def test_a_marker_declares_its_layout(marker: dict, layout: ConvrotLayout) -> None:
+ assert marker_layout(marker) == layout
+
+
+class TestMarkerExtraction:
+ @staticmethod
+ def _sd(weight_dtype: torch.dtype = torch.int8, marker: dict | None = None) -> dict:
+ sd = {"proj.weight": torch.zeros(4, 128, dtype=weight_dtype), "proj.weight_scale": torch.ones(4)}
+ if marker is not None:
+ sd["proj.comfy_quant"] = comfy_quant_marker(marker)
+ return sd
+
+ def test_int4_markers_are_left_alone_unless_the_loader_opts_in(self) -> None:
+ sd = self._sd(marker=convrot_w4a4_marker())
+
+ assert extract_int8_convrot_markers(sd) == {}
+ assert "proj.comfy_quant" in sd
+ assert extract_int8_convrot_markers(sd, accept_int4=True) == {"proj": convrot_w4a4_marker()}
+ assert "proj.comfy_quant" not in sd
+
+ def test_a_layer_the_header_alone_names_is_claimed(self) -> None:
+ """The Starnodes converter deletes every per-tensor marker and writes the header only."""
+ sd = self._sd()
+
+ markers = extract_int8_convrot_markers(sd, accept_int4=True, header_layers={"proj": convrot_w4a4_marker()})
+
+ assert markers == {"proj": convrot_w4a4_marker()}
+
+ def test_a_per_tensor_marker_wins_over_the_header_even_one_the_loader_does_not_claim(self) -> None:
+ sd = self._sd(marker={"format": "asym_w4a8_int8"})
+
+ markers = extract_int8_convrot_markers(sd, accept_int4=True, header_layers={"proj": convrot_w4a4_marker()})
+
+ assert markers == {}
+
+ def test_a_header_entry_for_a_weight_that_is_not_int8_is_stale_and_ignored(self) -> None:
+ sd = self._sd(weight_dtype=torch.bfloat16)
+
+ assert extract_int8_convrot_markers(sd, accept_int4=True, header_layers={"proj": convrot_w4a4_marker()}) == {}
+
+ @pytest.mark.parametrize("fmt", ["int8_tensorwise", "int4_tensorwise"])
+ def test_a_header_entry_that_does_not_say_whether_the_layer_was_rotated_is_refused(self, fmt: str) -> None:
+ """Comfy-Org's own exports write header entries without `convrot` beside per-tensor markers that set it,
+ so a header-only file of that origin would decode as unrotated noise."""
+ with pytest.raises(ValueError, match="does not say whether the weight was rotated"):
+ extract_int8_convrot_markers(self._sd(), accept_int4=True, header_layers={"proj": {"format": fmt}})
+
+
+def test_an_int8_marker_on_a_packed_payload_is_refused_at_the_swap() -> None:
+ """A strict load assigns the quantized buffers whatever shape the file has, so nothing after the swap would
+ notice an int4 payload declared as int8 until its forward multiplies half a weight."""
+ from invokeai.backend.quantization.int8_convrot import swap_in_int8_linears
+
+ model = torch.nn.Module()
+ model.proj = torch.nn.Linear(CONVROT_GROUP_SIZE, 8, bias=False)
+ payload = quantize_convrot_int4(torch.randn(8, CONVROT_GROUP_SIZE))
+ sd = {"proj.weight": payload.packed, "proj.weight_scale": payload.scale}
+
+ with pytest.raises(ValueError, match=r"decodes to \(8, 128\).*\(8, 256\)"):
+ swap_in_int8_linears(model, sd, {"proj": {"format": "int8_tensorwise", "convrot": True}})
+
+ swap_in_int8_linears(model, sd, {"proj": int4_tensorwise_marker()})
+ assert isinstance(model.proj, Int4ConvrotLinear)
+
+
[email protected]("streamed", [True, False], ids=["streamed", "resident"])
[email protected]("convrot", [True, False])
[email protected]("dtype", [torch.bfloat16, torch.float32])
+def test_the_transient_estimate_is_the_decode_peak_with_the_payload_streamed(
+ streamed: bool, convrot: bool, dtype: torch.dtype
+) -> None:
+ """The node reserves working memory before partial loading decides which layers stay in RAM, so the estimate
+ has to hold for a layer whose packed payload is copied to the compute device per call: unrotated, that copy is
+ still alive while the unpack peaks. A resident layer peaks at or below it. The meta device stands in for the
+ accelerator."""
+ device = torch.device("meta")
+ torch.manual_seed(3)
+ payload = quantize_convrot_int4(torch.randn(64, 2 * CONVROT_GROUP_SIZE))
+ model = torch.nn.Module()
+ model.proj = Int4ConvrotLinear(
+ payload.packed if streamed else payload.packed.to(device),
+ payload.scale if streamed else payload.scale.to(device),
+ convrot=convrot,
+ )
+ model.proj._dequantized_weight(device, dtype) # Mints the shared Hadamard matrix.
+
+ with PeakDeviceBytes(device) as allocations:
+ model.proj._dequantized_weight(device, dtype)
+
+ estimate = peak_dequant_transient_bytes(model, dtype)
+ if streamed:
+ assert allocations.peak == estimate
+ else:
+ assert allocations.peak <= estimate
+
+
[email protected](not torch.cuda.is_available(), reason="measures GPU allocations")
[email protected]("streamed", [True, False], ids=["streamed", "resident"])
[email protected]("convrot", [True, False])
[email protected]("dtype", [torch.bfloat16, torch.float32])
+def test_the_transient_estimate_covers_what_the_per_forward_decode_allocates(
+ streamed: bool, convrot: bool, dtype: torch.dtype
+) -> None:
+ """The node reserves this much working memory for the decode, and the model's resident size does not include
+ it, so an estimate that falls short lets the first forward compete with weights the cache just placed. Runs on
+ ROCm too, where `torch.cuda` is the HIP device.
+
+ Measured in requested bytes: peak *allocated* bytes count whole cached blocks, which blocks left over by
+ earlier tests in the same process can inflate. The estimate counts the payload as streamed, so a resident
+ unrotated layer comes in at (itemsize + 1) / (itemsize + 1.5) of it."""
+ device = torch.device("cuda")
+ torch.manual_seed(3)
+ payload = quantize_convrot_int4(torch.randn(1024, 4096))
+ model = torch.nn.Module()
+ model.proj = Int4ConvrotLinear(
+ payload.packed if streamed else payload.packed.to(device),
+ payload.scale if streamed else payload.scale.to(device),
+ convrot=convrot,
+ )
+ model.proj._dequantized_weight(device, dtype) # Mints the shared Hadamard matrix.
+ torch.cuda.synchronize()
+ torch.cuda.reset_peak_memory_stats()
+ baseline = torch.cuda.memory_stats()["requested_bytes.all.current"]
+
+ weight = model.proj._dequantized_weight(device, dtype)
+ torch.cuda.synchronize()
+
+ measured = torch.cuda.memory_stats()["requested_bytes.all.peak"] - baseline
+ estimate = peak_dequant_transient_bytes(model, dtype)
+ assert weight.dtype is dtype
+ assert (0.9 * estimate if streamed or convrot else 0.8 * estimate) <= measured <= estimate
+
+
[email protected](not torch.cuda.is_available(), reason="needs a GPU device")
+def test_buffers_left_in_ram_stream_per_call_and_decode_like_resident_ones() -> None:
+ """Partial loading leaves some packed layers in RAM, and their forward has to move them to the input's device
+ -- packed, before unpacking -- and compute exactly what the resident layer computes."""
+ device = torch.device("cuda")
+ torch.manual_seed(4)
+ payload = quantize_convrot_int4(torch.randn(64, CONVROT_GROUP_SIZE))
+ model = torch.nn.Module()
+ model.proj = Int4ConvrotLinear(payload.packed, payload.scale, convrot=True, bias=torch.randn(64))
+ apply_custom_layers_to_model(model, device_autocasting_enabled=True)
+ x = torch.randn(3, CONVROT_GROUP_SIZE, device=device, dtype=torch.bfloat16)
+
+ streamed = model.proj(x)
+ model.to(device)
+ resident = model.proj(x)
+
+ assert streamed.device == x.device
+ assert torch.equal(streamed, resident)
diff --git a/tests/backend/quantization/test_int8_convrot.py b/tests/backend/quantization/test_int8_convrot.py
index 0f23d630a0..91bfdf3a09 100644
--- a/tests/backend/quantization/test_int8_convrot.py
+++ b/tests/backend/quantization/test_int8_convrot.py
@@ -24,6 +24,7 @@ from invokeai.backend.quantization.int8_convrot import (
parse_comfy_quant_marker,
shared_regular_hadamard,
)
+from tests.fixtures.device_allocations import PeakDeviceBytes
def _quantize_reference(w: torch.Tensor, convrot: bool) -> tuple[torch.Tensor, torch.Tensor]:
@@ -378,7 +379,7 @@ class TestThePerForwardDequantTransient:
not part of the model's resident size and the calling node has to reserve for it."""
@staticmethod
- def _model(*shapes: tuple[int, int]) -> torch.nn.Module:
+ def _model(*shapes: tuple[int, int], convrot: bool) -> torch.nn.Module:
model = torch.nn.Module()
for index, (out_features, in_features) in enumerate(shapes):
model.add_module(
@@ -386,20 +387,73 @@ class TestThePerForwardDequantTransient:
Int8ConvrotLinear(
torch.zeros(out_features, in_features, dtype=torch.int8),
torch.ones(out_features, 1),
- convrot=False,
+ convrot=convrot,
),
)
return model
def test_it_is_two_weights_of_the_largest_layer_in_the_compute_dtype(self) -> None:
- """Two, not one: the dtype cast of the int8 weight is alive alongside the product it is
- multiplied into, and that product is alive alongside the derotation matmul's output."""
- model = self._model((4, CONVROT_GROUP_SIZE), (16, CONVROT_GROUP_SIZE))
+ """The widened weight is scaled in place, so the peak is the derotation's input beside its output."""
+ model = self._model((4, CONVROT_GROUP_SIZE), (16, CONVROT_GROUP_SIZE), convrot=True)
assert peak_dequant_transient_bytes(model, torch.bfloat16) == 2 * 16 * CONVROT_GROUP_SIZE * 2
+ @pytest.mark.parametrize("streamed", [True, False], ids=["streamed", "resident"])
+ @pytest.mark.parametrize("convrot", [True, False])
+ @pytest.mark.parametrize("dtype", [torch.bfloat16, torch.float32])
+ def test_it_covers_the_decode_peak_with_the_codes_streamed_or_resident(
+ self, streamed: bool, convrot: bool, dtype: torch.dtype
+ ) -> None:
+ """Working memory is reserved before partial loading decides which layers stay in RAM, so the estimate has
+ to hold for a layer whose codes are copied to the compute device per call as well as for a resident one.
+ With convrot both peak at exactly the estimate. The meta device stands in for the accelerator (see the int4
+ counterpart)."""
+ device = torch.device("meta")
+ q, scale = _quantize_reference(torch.randn(64, 2 * CONVROT_GROUP_SIZE), convrot=convrot)
+ model = torch.nn.Module()
+ model.proj = Int8ConvrotLinear(
+ q if streamed else q.to(device), scale if streamed else scale.to(device), convrot=convrot
+ )
+ model.proj._dequantized_weight(device, dtype) # Mints the shared Hadamard matrix.
+
+ with PeakDeviceBytes(device) as allocations:
+ model.proj._dequantized_weight(device, dtype)
+
+ estimate = peak_dequant_transient_bytes(model, dtype)
+ if convrot:
+ assert allocations.peak == estimate
+ else:
+ assert allocations.peak <= estimate
+
def test_a_model_with_no_quantized_layers_needs_nothing(self) -> None:
model = torch.nn.Module()
model.dense = torch.nn.Linear(8, 8)
assert peak_dequant_transient_bytes(model, torch.bfloat16) == 0
+
+
[email protected](not torch.cuda.is_available(), reason="measures GPU allocations")
[email protected]("convrot", [True, False])
[email protected]("dtype", [torch.bfloat16, torch.float32])
+def test_the_transient_estimate_covers_what_the_per_forward_decode_allocates(convrot: bool, dtype: torch.dtype) -> None:
+ """What the node reserves for the per-forward decode against what it allocates, in requested bytes (see the
+ int4 counterpart). Runs on ROCm too, where `torch.cuda` is the HIP device."""
+ device = torch.device("cuda")
+ torch.manual_seed(3)
+ q, scale = _quantize_reference(torch.randn(1024, 4096), convrot=convrot)
+ model = torch.nn.Module()
+ model.proj = Int8ConvrotLinear(q.to(device), scale.to(device), convrot=convrot)
+ model.proj._dequantized_weight(device, dtype) # Mints the shared Hadamard matrix.
+ torch.cuda.synchronize()
+ torch.cuda.reset_peak_memory_stats()
+ baseline = torch.cuda.memory_stats()["requested_bytes.all.current"]
+
+ weight = model.proj._dequantized_weight(device, dtype)
+ torch.cuda.synchronize()
+
+ measured = torch.cuda.memory_stats()["requested_bytes.all.peak"] - baseline
+ estimate = peak_dequant_transient_bytes(model, dtype)
+ assert weight.dtype is dtype
+ # Without convrot one weight is the peak and the estimate keeps a second as margin.
+ assert (0.9 * estimate if convrot else 0.45 * estimate) <= measured <= estimate
diff --git a/tests/backend/quantization/test_int8_convrot_state_dict.py b/tests/backend/quantization/test_int8_convrot_state_dict.py
index 2e86f0aa47..084807f286 100644
--- a/tests/backend/quantization/test_int8_convrot_state_dict.py
+++ b/tests/backend/quantization/test_int8_convrot_state_dict.py
@@ -12,6 +12,7 @@ from safetensors.torch import save_file
from invokeai.backend.quantization.int8_convrot import (
CONVROT_GROUP_SIZE,
+ Int4ConvrotLinear,
Int8ConvrotLinear,
cast_unquantized,
check_int8_scale_layout,
@@ -25,7 +26,12 @@ from invokeai.backend.quantization.int8_convrot import (
split_int8_convrot_layers,
swap_in_int8_linears,
)
-from tests.fixtures.quantized_payloads import comfy_quant_marker
+from tests.fixtures.quantized_payloads import (
+ comfy_quant_marker,
+ convrot_w4a4_marker,
+ int4_tensorwise_marker,
+ quantize_convrot_int4,
+)
MARKER = {"format": "int8_tensorwise", "convrot": True, "convrot_groupsize": CONVROT_GROUP_SIZE}
@@ -317,6 +323,19 @@ class TestTheKeysTheOrphanCheckAndTheSidecarDropActOn:
with pytest.raises(ValueError, match=r"'w'"):
reject_unmarked_int8_weights(sd, {"": MARKER}, "Krea-2")
+ @pytest.mark.parametrize("where", ["per-tensor marker", "header entry"])
+ def test_an_int4_layer_on_a_loader_that_did_not_opt_in_is_named_as_int4(self, where: str) -> None:
+ """Not as an int8 weight with no marker: it has one, the loader just does not decode that format."""
+ sd = {"foo.weight": torch.zeros(4, 4, dtype=torch.int8)}
+ header = {}
+ if where == "per-tensor marker":
+ sd["foo.comfy_quant"] = comfy_quant_marker(convrot_w4a4_marker())
+ else:
+ header = {"foo": convrot_w4a4_marker()}
+
+ with pytest.raises(ValueError, match=r"1 int8 weight\(s\) marked 'convrot_w4a4'.*which Z-Image does not load"):
+ reject_unmarked_int8_weights(sd, extract_int8_convrot_markers(sd), "Z-Image", header_layers=header)
+
def test_a_claimed_weight_is_not_an_orphan(self) -> None:
reject_unmarked_int8_weights({"foo.weight": torch.zeros(4, 4, dtype=torch.int8)}, {"foo": MARKER}, "Krea-2")
@@ -481,6 +500,50 @@ class TestTheSharedInstall:
scale = 4 * 4
assert reserved == [codes + scale + 4096]
+ def test_a_mixed_int8_and_int4_file_installs_each_layer_in_its_own_storage(self) -> None:
+ """The published int4 builds are all mixed: some layers int8, the sensitive ones kept wider. Each layer is
+ installed as its marker declares and charged as stored -- half a byte per weight for the packed one."""
+ model = self._model()
+ int4 = quantize_convrot_int4(torch.randn(4, CONVROT_GROUP_SIZE))
+ sd = {**self._int8_layer("keeps"), "widens.weight": int4.packed, "widens.weight_scale": int4.scale}
+ reserved: list[int] = []
+
+ install_int8_convrot_layers(
+ model,
+ sd,
+ {"keeps": MARKER, "widens": convrot_w4a4_marker()},
+ torch.float32,
+ architecture="Krea-2",
+ reserve=reserved.append,
+ )
+
+ assert type(model.keeps) is Int8ConvrotLinear and type(model.widens) is Int4ConvrotLinear
+ int8_layer = 4 * CONVROT_GROUP_SIZE + 4 * 4
+ int4_layer = 4 * CONVROT_GROUP_SIZE // 2 + 4 * 4
+ assert reserved == [int8_layer + int4_layer]
+
+ def test_an_int4_layer_the_split_widens_is_charged_and_decoded_at_its_unpacked_size(self) -> None:
+ """Its payload holds half the elements it decodes to, so a prediction from the stored element count comes
+ up short by exactly half of what the split allocates."""
+ model = self._model()
+ int4 = quantize_convrot_int4(torch.randn(4, CONVROT_GROUP_SIZE))
+ sd = {"widens.weight": int4.packed, "widens.weight_scale": int4.scale}
+ reserved: list[int] = []
+
+ surviving = install_int8_convrot_layers(
+ model,
+ sd,
+ {"widens": int4_tensorwise_marker()},
+ torch.float32,
+ architecture="Krea-2",
+ reserve=reserved.append,
+ skip_patterns=("widens",),
+ )
+
+ assert surviving == {}
+ assert reserved == [4 * CONVROT_GROUP_SIZE * 4]
+ assert torch.allclose(sd["widens.weight"], int4.dequantized, atol=1e-5)
+
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.
diff --git a/tests/fixtures/device_allocations.py b/tests/fixtures/device_allocations.py
new file mode 100644
index 0000000000..1e02d5d918
--- /dev/null
+++ b/tests/fixtures/device_allocations.py
@@ -0,0 +1,53 @@
+"""Peak live bytes on one device, counted from the tensors aten ops allocate there.
+
+A working-memory estimate states what a call holds at its peak. ``torch.cuda`` can measure that only on a GPU;
+this counts the same allocations on any device, the meta device included, so the meta device can stand in for the
+accelerator and the comparison runs in CI. It sees every tensor an op returns, not the scratch inside a kernel
+(cuBLAS workspaces), and counts requested bytes, without the caching allocator's rounding.
+"""
+
+import weakref
+from typing import Any
+
+import torch
+from torch.utils._python_dispatch import TorchDispatchMode
+from torch.utils._pytree import tree_flatten
+
+
+class PeakDeviceBytes(TorchDispatchMode):
+ """Tracks the bytes of storages ops allocate on ``device`` while the mode is active, and their peak.
+
+ A storage counts from the op that returned it until it is freed. Outputs that alias an input (views, in-place
+ ops) allocate nothing and are skipped, and so is anything that existed before the mode was entered.
+ """
+
+ def __init__(self, device: torch.device) -> None:
+ super().__init__()
+ self.device = device
+ self.live = 0
+ self.peak = 0
+ self._tracked: set[int] = set()
+
+ def __torch_dispatch__(self, func: Any, types: Any, args: Any = (), kwargs: Any = None) -> Any:
+ out = func(*args, **(kwargs or {}))
+ if any(ret.alias_info is not None for ret in func._schema.returns):
+ return out
+ outputs, _ = tree_flatten(out)
+ for tensor in outputs:
+ if isinstance(tensor, torch.Tensor) and tensor.device.type == self.device.type:
+ self._track(tensor.untyped_storage())
+ return out
+
+ def _track(self, storage: torch.UntypedStorage) -> None:
+ key = id(storage)
+ if key in self._tracked:
+ return
+ self._tracked.add(key)
+ nbytes = storage.nbytes()
+ self.live += nbytes
+ self.peak = max(self.peak, self.live)
+ weakref.finalize(storage, self._release, key, nbytes)
+
+ def _release(self, key: int, nbytes: int) -> None:
+ self._tracked.discard(key)
+ self.live -= nbytes
diff --git a/tests/fixtures/quantized_payloads.py b/tests/fixtures/quantized_payloads.py
index 99f20190e0..ff266d8218 100644
--- a/tests/fixtures/quantized_payloads.py
+++ b/tests/fixtures/quantized_payloads.py
@@ -29,6 +29,9 @@ FP8_E4M3_MAX = 448.0
# unused, so a scale derived from 128 is off by one level on every weight.
INT8_LEVELS = 127.0
+# int4 likewise: symmetric against 7, leaving -8 unused.
+INT4_LEVELS = 7
+
# The two nvfp4 codes worth +1.0 and -1.0 in E2M1. Paired with a block scale and a global scale they
# give a weight whose exact value is known without depending on the rest of the E2M1 table.
NVFP4_CODE_PLUS_ONE = 2
@@ -81,6 +84,61 @@ def quantize_convrot(weight: torch.Tensor, *, group_size: int = CONVROT_GROUP_SI
return Int8ConvrotPayload(codes, scale.to(torch.float32), restored.view(out_features, in_features))
+class Int4ConvrotPayload(NamedTuple):
+ """What a packed int4 + convrot layer stores -- ``convrot_w4a4``, ``int4_tensorwise`` and ComfyUI-GGUF's
+ ``Q4_CR`` all store the same bytes -- and the round trip it must come back as."""
+
+ packed: torch.Tensor
+ scale: torch.Tensor
+ dequantized: torch.Tensor
+
+
+def quantize_convrot_int4(weight: torch.Tensor, *, group_size: int = CONVROT_GROUP_SIZE) -> Int4ConvrotPayload:
+ """Mirror of comfy-kitchen's eager ``quantize_convrot_w4a4_weight``: the int8 recipe's rotation, then per-row
+ symmetric int4 against 7 levels, two codes per byte with element ``2j`` in the LOW nibble.
+
+ The packing is written out in unsigned arithmetic rather than shared with any decoder, so a decoder that reads
+ the nibbles in nvfp4's order -- high first -- disagrees with it instead of agreeing by construction.
+ """
+ out_features, in_features = weight.shape
+ hadamard = build_regular_hadamard(group_size, dtype=torch.float32)
+ grouped = weight.float().view(out_features, in_features // group_size, group_size)
+ rotated = (grouped @ hadamard.T).view(out_features, in_features)
+
+ scale = rotated.abs().amax(dim=1, keepdim=True).clamp(min=1e-10) / INT4_LEVELS
+ codes = torch.clamp(torch.round(rotated / scale), -INT4_LEVELS, INT4_LEVELS).to(torch.int8)
+ nibbles = codes.view(torch.uint8) & 0x0F
+ packed = (nibbles[:, 0::2] | (nibbles[:, 1::2] << 4)).view(torch.int8)
+
+ restored = (codes.float() * scale).view(out_features, in_features // group_size, group_size) @ hadamard
+ return Int4ConvrotPayload(packed, scale, restored.view(out_features, in_features))
+
+
+def convrot_w4a4_marker(*, group_size: int = CONVROT_GROUP_SIZE) -> dict[str, Any]:
+ """comfy-kitchen's released int4 layout as the Starnodes converter names it: always rotated, so no ``convrot``
+ flag, and the kernel's activation group size beside it."""
+ return {"format": "convrot_w4a4", "convrot_groupsize": group_size, "quant_group_size": 64}
+
+
+def int4_tensorwise_marker(*, group_size: int = CONVROT_GROUP_SIZE, convrot: bool = True) -> dict[str, Any]:
+ """The same bytes under comfy-kitchen's unreleased ``int4_tensorwise`` name (comfy-quants' int4 exporter)."""
+ return {"format": "int4_tensorwise", "convrot": convrot, "convrot_groupsize": group_size}
+
+
+def q4_cr_marker(rows: int, columns: int, *, group_size: int = CONVROT_GROUP_SIZE, **overrides: Any) -> dict[str, Any]:
+ """The JSON ComfyUI-GGUF's converter stores per ``Q4_CR`` weight (``Q4_CR_W4A4`` in its ``tools/convert.py``):
+ the packed codes are written as ``I8`` ``[rows, columns / 2]``, so the unpacked shape travels in the JSON."""
+ return {
+ "format": "int4_cr",
+ "backing": "w4a4",
+ "convrot_groupsize": group_size,
+ "quant_group_size": 64,
+ "sym": True,
+ "orig_shape": [rows, columns],
+ **overrides,
+ }
+
+
class ScaledFp8Payload(NamedTuple):
"""What a per-tensor scaled-fp8 layer stores, and the weight it decodes back to.