Skip to content

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

feat(quantization): run int8 convrot layers on the int8 tensor cores (#9994)

Alexander Eichhornacba5624e2ac
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 97bc1dc0be..36990056d1 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
@@ -43,7 +43,8 @@ Ministral 3B encoder. Others are recognized by their layer names and fail, or mi
| [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 | ✗ | ✗ | ✗ | ✗ |
-- **int8** means ComfyUI's `int8_convrot` (`int8_tensorwise`) builds. **nvfp4** and **fp8 scaled** mean ComfyUI's
+- **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.
- **GGUF** covers the llama.cpp types (Q4_0 through Q8_0, the K-quants, BF16). ComfyUI-GGUF's `Q8_CR` files load
diff --git a/docs/src/content/docs/Users Guide/03.Models/Local Models/anima.mdx b/docs/src/content/docs/Users Guide/03.Models/Local Models/anima.mdx
index dee187c3de..437005a075 100644
--- a/docs/src/content/docs/Users Guide/03.Models/Local Models/anima.mdx
+++ b/docs/src/content/docs/Users Guide/03.Models/Local Models/anima.mdx
@@ -60,7 +60,7 @@ Both finetunes keep Anima's VAE, schedulers and Canvas support, and install from
| Model | What changes | Components |
| ----- | ------------ | ---------- |
-| **Anima-2.9B** (Preview v1) | 40 transformer blocks instead of 28, trained on 1.7M more images (cutoff July 2026). An int8 build (~3.1 GB) halves the memory of the bf16 one (~5.8 GB); it is not faster. | Same as Anima |
+| **Anima-2.9B** (Preview v1) | 40 transformer blocks instead of 28, trained on 1.7M more images (cutoff July 2026). An int8 build (~3.1 GB) halves the memory of the bf16 one (~5.8 GB); by default it is not faster ([int8 Compute](/configuration/optimization/int8-compute/) can run its convrot layers on the int8 tensor cores; not measured on Anima). | Same as Anima |
| **Anima-3.8B** (v1.1) | 52 blocks, plus a **semantic connector** bundled in the checkpoint that adds a second text encoder, **Qwen3.5 4B**, for better prompt adherence, multi-character binding and mixed natural-language/tag prompts. | Qwen3 0.6B **and** Qwen3.5 4B encoder, VAE |
With an Anima-3.8B model selected, the **Components** section shows a third picker, **Qwen3.5 Encoder**,
diff --git a/docs/src/content/docs/Users Guide/03.Models/Local Models/ideogram4.mdx b/docs/src/content/docs/Users Guide/03.Models/Local Models/ideogram4.mdx
index 788326294e..cc983c80a3 100644
--- a/docs/src/content/docs/Users Guide/03.Models/Local Models/ideogram4.mdx
+++ b/docs/src/content/docs/Users Guide/03.Models/Local Models/ideogram4.mdx
@@ -51,7 +51,7 @@ Both branches are resident at once, so double those figures for the pair.
**Without the fp8 matmul, the fp8 build still works — through FP8 Storage.** That setting keeps the file's own fp8 weights and per-tensor scales instead of expanding them, and installation switches it on for these files by itself. Measured on a 4090 with `fp8_compute` off, 1024px: **40.6 s**, 22.9 GB peak, 8.7 GB resident per branch — against **45.7 s** for the int8 pair. With *neither* the matmul nor Storage the weights are expanded to bf16 on load, 17.3 GB per branch, and a 24 GB card runs out of memory during the first step.
-**Use int8 where FP8 Storage is not available.** It requires a CUDA or Intel XPU device; on anything else the fp8 build falls back to the expanded path, while int8 keeps its stored codes and dequantizes them per forward on any device with no setting to turn on.
+**Use int8 where FP8 Storage is not available.** It requires a CUDA or Intel XPU device; on anything else the fp8 build falls back to the expanded path, while int8 keeps its stored codes and dequantizes them per forward on any device with no setting to turn on. The int8 timings above are that dequantizing path; [int8 Compute](/configuration/optimization/int8-compute/) runs the int8 build's convrot layers on the int8 tensor cores of an NVIDIA GPU instead (not measured on Ideogram 4).
On a 24 GB NVIDIA card without the fp8 matmul (RTX 30-series), the int8 pair plus the 8B encoder still adds up to more than the card holds, so the bundled [nf4 build](#installing-ideogram-4) or a [GGUF](#gguf) pair is the smaller option there.
:::
diff --git a/docs/src/content/docs/configuration/Optimization/fp8-storage.mdx b/docs/src/content/docs/configuration/Optimization/fp8-storage.mdx
index f24b6f55b1..6d1d5af95e 100644
--- a/docs/src/content/docs/configuration/Optimization/fp8-storage.mdx
+++ b/docs/src/content/docs/configuration/Optimization/fp8-storage.mdx
@@ -136,7 +136,7 @@ If you see unexpected quality regressions, disable FP8 Storage on the affected m
Everything above describes FP8 *Storage*, which changes how weights are **stored** while the math still runs in BF16. `fp8_compute` is a separate, global setting in `invokeai.yaml` that also does the **math** in FP8, on GPUs that have hardware for it. That makes generation faster, not just smaller.
-It is for models that were **already saved in FP8** by whoever published them — you'll often see these labelled "fp8" or "fp8_scaled" in the filename. Without either setting InvokeAI unpacks them back to BF16 while loading, which is why such a checkpoint has FP8 Storage switched on for it when it is installed. With `fp8_compute` on they stay as they are and run directly on the GPU's FP8 hardware; with FP8 Storage on they also stay as they are, but are unpacked layer by layer during the forward pass instead.
+It is for models that were **already saved in FP8** by whoever published them — you'll often see these labelled "fp8" or "fp8_scaled" in the filename. Without either setting InvokeAI unpacks them back to BF16 while loading, which is why such a checkpoint has FP8 Storage switched on for it when it is installed. With `fp8_compute` on they stay as they are and run directly on the GPU's FP8 hardware; with FP8 Storage on they also stay as they are, but are unpacked layer by layer during the forward pass instead. ComfyUI's int8 builds have a counterpart of their own, [int8 Compute](/configuration/optimization/int8-compute/).
### Checkpoints that are already FP8
diff --git a/docs/src/content/docs/configuration/Optimization/int8-compute.mdx b/docs/src/content/docs/configuration/Optimization/int8-compute.mdx
new file mode 100644
index 0000000000..2d9d215d2f
--- /dev/null
+++ b/docs/src/content/docs/configuration/Optimization/int8-compute.mdx
@@ -0,0 +1,101 @@
+---
+title: int8 Compute
+sidebar:
+ order: 6
+---
+
+ComfyUI's **int8** builds (`int8_tensorwise`, see [Model Format Support](/users-guide/models/model-format-support/))
+store every large layer as 8-bit integers. By default InvokeAI keeps those weights in int8 and unpacks each layer to
+BF16 or FP16 just before it runs, which gives the memory saving but no speedup: each layer runs at 0.75–0.97× the speed
+of a full-precision one.
+
+`int8_compute` is a global setting that does the **math** in int8 as well, on the GPU's int8 tensor cores, for int8
+builds **quantized with convrot** — the `comfy_quant` marker of each layer says `"convrot": true`, which is what the
+published builds use. Each layer then rotates and quantizes its input to int8 per token and multiplies int8 by int8.
+Measured on an RTX 4090 (BF16, model fully in VRAM), the denoising step takes:
+
+| Model (int8 convrot build) | Steps | 1024² | 1536² | 2048² |
+| --- | --- | --- | --- | --- |
+| Z-Image Turbo | 8 | 5.04 s → 2.93 s (1.72×) | 12.78 s → 8.95 s (1.43×) | 26.62 s → 20.71 s (1.29×) |
+| FLUX.1 dev | 20 | 15.25 s → 7.85 s (1.94×) | 36.20 s → 23.88 s (1.52×) | |
+| Krea-2 Turbo | 8 | 9.22 s → 4.51 s (2.04×) | 21.64 s → 12.32 s (1.76×) | |
+
+The gain shrinks at higher resolutions because attention, which `int8_compute` does not touch, takes a larger share of
+each step. Other int8 families use the same layers but have not been measured. A convrot int8 text encoder
+(`qwen_3_8b_int8_convrot` with FLUX.2 Klein 9B) works with it as well; its speed has not been measured.
+
+**Partially loaded models gain the most.** A layer still in system RAM is copied to the GPU as int8 for each step, half
+the bytes of the unpacked weight, and computed exactly like a resident one. With the Z-Image Turbo transformer fully
+streamed (`max_cache_vram_gb: 3`, 0 % in VRAM), 8 steps at 1024² took 34.43 s by default and 9.04 s with
+`int8_compute` (3.81×), and the image was bit-identical to the fully resident one.
+
+It is **opt-in**, because quantizing the inputs changes the numbers: images made with `int8_compute` are not
+pixel-identical to the default path at the same seed. In the measurements above they were visually equivalent (PSNR
+30–46 dB against the default path). Each path is bit-identical from run to run, and how much of the model is in VRAM
+does not change the image.
+
+## Requirements
+
+- **An NVIDIA GPU with compute capability 8.0 or newer** — RTX 30-series, RTX 40-series, RTX 50-series, A100, H100.
+ Measured on an RTX 4090.
+- **Triton**, which InvokeAI's NVIDIA install on Windows x64 and Linux includes (on Windows the `triton-windows`
+ package). A [manual install](/start-here/manual/) on Windows without the `cuda` extra has none; install the
+ `triton-windows` version matching InvokeAI's PyTorch as described under
+ [SageAttention](/configuration/optimization/sage-attention/#windows).
+- Everything else falls back to the default path automatically: AMD (ROCm), Apple Silicon (MPS), Intel (XPU), the CPU,
+ and older NVIDIA GPUs.
+
+## Enabling
+
+Set it in your [`invokeai.yaml`](/configuration/invokeai-yaml/) and restart InvokeAI:
+
+```yaml
+int8_compute: true
+```
+
+The first generation that uses it logs, once per GPU:
+
+```
+int8 compute: rotated int8_tensorwise layers on cuda:0 run on the int8 tensor cores.
+```
+
+If it cannot be used on a device, the log says why once — for example that Triton is missing — and that device keeps
+the default path. When a model loads with layers it does not cover, the log counts them, for example
+`int8_compute: 2 of 264 int8 layer(s) keep dequantizing per forward (2 marked full_precision_matrix_mult, ...)`.
+
+### The first generation pauses
+
+The kernels are tuned once per layer shape and token-count bucket. The first image after enabling it takes about
+**35 seconds** longer; a later size that falls into a new token-count bucket adds about 1–5 seconds. The results are
+cached on disk in Triton's cache directory (`~/.triton/cache`, or `TRITON_CACHE_DIR`), so after a restart the tuning
+comes from that cache, and other sizes in the same bucket do not pay it again.
+
+## What stays on the default path
+
+`int8_compute` only changes how rotated int8 layers multiply. These keep unpacking the weights:
+
+- **Layers quantized without convrot.** Without the rotation, a single outlier channel sets the scale for a whole
+ token, which is where per-token quantization loses the most; no such build has been measured.
+- **Layers the checkpoint marks as full precision** (`full_precision_matrix_mult`).
+- **Layers rotated in groups other than 256.** Every published build uses 256.
+- **FP32 compute.** The kernels run in BF16 and FP16 only.
+
+LoRAs work as usual: they are applied beside the int8 layer in the compute precision, never quantized, and do not
+change which path the layer takes.
+
+## Memory
+
+Once tuned, the kernels never need more working memory than the default path already reserves for unpacking a layer:
+they quantize the input in slices of at most twice the layer's output width, and copy a layer that is still in system
+RAM to the GPU as int8, at half the size of the unpacked weight. The first call for each layer shape and token-count
+bucket may briefly need a little more: tuning uses a buffer the size of the GPU's L2 cache (72 MB on an RTX 4090), and
+the check against the default path afterwards keeps 256 rows of the layer's output from each path.
+
+## When something goes wrong
+
+InvokeAI checks the first result for each layer shape and token-count bucket against the default path. If it does not
+match, or a kernel fails, the log shows one warning and that GPU uses the default path until restart. Usually the
+generation continues; a fault that leaves the GPU unusable (such as an illegal memory access) fails it, and the default
+path cannot recover from that either. Running out of memory is not caught: once the kernels are tuned, the default path
+would not fit either. If an out-of-memory error appears only on the first image at a new size, set `int8_compute: false`
+to rule the tuning out.
diff --git a/docs/src/generated/settings.json b/docs/src/generated/settings.json
index 97c353c671..667bed0525 100644
--- a/docs/src/generated/settings.json
+++ b/docs/src/generated/settings.json
@@ -603,6 +603,17 @@
"type": "<class 'bool'>",
"validation": {}
},
+ {
+ "category": "CACHE",
+ "default": false,
+ "description": "Run the matmuls of ComfyUI int8 builds quantized with convrot ('int8_tensorwise' with 'convrot') on the int8 tensor cores instead of dequantizing their weights on every forward (requires an NVIDIA GPU with compute capability 8.0 or newer and Triton; falls back automatically otherwise, including on AMD, Apple and Intel GPUs and the CPU). Speeds up denoising with these builds, but quantizes activations per token as well, so images will differ from the dequantized path at the same seed. The kernels are tuned once per layer shape and token-count bucket: about 35 seconds for the first image after enabling it, about 1-5 seconds for a later size in a new token-count bucket, cached on disk across restarts.",
+ "env_var": "INVOKEAI_INT8_COMPUTE",
+ "literal_values": [],
+ "name": "int8_compute",
+ "required": false,
+ "type": "<class 'bool'>",
+ "validation": {}
+ },
{
"category": "CACHE",
"default": null,
diff --git a/invokeai/app/services/config/config_default.py b/invokeai/app/services/config/config_default.py
index f0f68078a7..84a6eeb64f 100644
--- a/invokeai/app/services/config/config_default.py
+++ b/invokeai/app/services/config/config_default.py
@@ -123,6 +123,7 @@ class InvokeAIAppConfig(BaseSettings):
clear_vram_after_session: After every queue item (each image of a batch), move the models held in VRAM to RAM and return the freed memory to the GPU driver. The models stay cached in RAM; the next item reloads them from there, which costs a few seconds (more with keep_ram_copy_of_weights off). Changes nothing where VRAM is system memory (CPU, MPS, integrated GPUs). Turn this on if a generation that runs fine the first time runs out of memory, or slows down sharply because the GPU spills into shared memory, when it is repeated.
fp8_compute: Keep ComfyUI 'scaled fp8' checkpoints quantized instead of dequantizing them at load, and run their matmuls on the fp8 tensor cores (requires an Ada/SM 8.9 or newer NVIDIA GPU, or a ROCm GPU that passes an fp8 matmul probe; falls back automatically otherwise). Speeds up denoising and keeps the transformer at fp8 size - FP8 Storage alone also keeps it at that size, without the speedup - but quantizes activations as well, so images will differ from previous versions at the same seed. Reproducibility also requires the model to be FULLY resident in VRAM: a layer whose weights are still in RAM falls back to the dequantized path, and since which layers are resident shifts from run to run, the same seed then yields visibly different images. For repeatable output, ensure the model loads at 100% (e.g. enable_partial_loading=false with enough free VRAM).
fp8_compute_full_precision_hints: Honor the per-layer 'full_precision_matrix_mult' flags that some scaled-fp8 checkpoints ship. Those layers then dequantize on every forward instead of using the fp8 tensor cores, which can cost a large part of the fp8_compute speedup - on checkpoints that mark many layers, most of it. Set to false to run every quantized layer on the fp8 tensor cores, ignoring the producer's instruction; faster, but the marked layers were flagged as numerically sensitive, so quality may suffer. Only has an effect when fp8_compute is enabled.
+ int8_compute: Run the matmuls of ComfyUI int8 builds quantized with convrot ('int8_tensorwise' with 'convrot') on the int8 tensor cores instead of dequantizing their weights on every forward (requires an NVIDIA GPU with compute capability 8.0 or newer and Triton; falls back automatically otherwise, including on AMD, Apple and Intel GPUs and the CPU). Speeds up denoising with these builds, but quantizes activations per token as well, so images will differ from the dequantized path at the same seed. The kernels are tuned once per layer shape and token-count bucket: about 35 seconds for the first image after enabling it, about 1-5 seconds for a later size in a new token-count bucket, cached on disk across restarts.
ram: DEPRECATED: This setting is no longer used. It has been replaced by `max_cache_ram_gb`, but most users will not need to use this config since automatic cache size limits should work well in most cases. This config setting will be removed once the new model cache behavior is stable.
vram: DEPRECATED: This setting is no longer used. It has been replaced by `max_cache_vram_gb`, but most users will not need to use this config since automatic cache size limits should work well in most cases. This config setting will be removed once the new model cache behavior is stable.
lazy_offload: DEPRECATED: This setting is no longer used. Lazy-offloading is enabled by default. This config setting will be removed once the new model cache behavior is stable.
@@ -249,6 +250,7 @@ class InvokeAIAppConfig(BaseSettings):
clear_vram_after_session: bool = Field(default=False, description="After every queue item (each image of a batch), move the models held in VRAM to RAM and return the freed memory to the GPU driver. The models stay cached in RAM; the next item reloads them from there, which costs a few seconds (more with keep_ram_copy_of_weights off). Changes nothing where VRAM is system memory (CPU, MPS, integrated GPUs). Turn this on if a generation that runs fine the first time runs out of memory, or slows down sharply because the GPU spills into shared memory, when it is repeated.")
fp8_compute: bool = Field(default=False, description="Keep ComfyUI 'scaled fp8' checkpoints quantized instead of dequantizing them at load, and run their matmuls on the fp8 tensor cores (requires an Ada/SM 8.9 or newer NVIDIA GPU, or a ROCm GPU that passes an fp8 matmul probe; falls back automatically otherwise). Speeds up denoising and keeps the transformer at fp8 size - FP8 Storage alone also keeps it at that size, without the speedup - but quantizes activations as well, so images will differ from previous versions at the same seed. Reproducibility also requires the model to be FULLY resident in VRAM: a layer whose weights are still in RAM falls back to the dequantized path, and since which layers are resident shifts from run to run, the same seed then yields visibly different images. For repeatable output, ensure the model loads at 100% (e.g. enable_partial_loading=false with enough free VRAM).")
fp8_compute_full_precision_hints: bool = Field(default=True, description="Honor the per-layer 'full_precision_matrix_mult' flags that some scaled-fp8 checkpoints ship. Those layers then dequantize on every forward instead of using the fp8 tensor cores, which can cost a large part of the fp8_compute speedup - on checkpoints that mark many layers, most of it. Set to false to run every quantized layer on the fp8 tensor cores, ignoring the producer's instruction; faster, but the marked layers were flagged as numerically sensitive, so quality may suffer. Only has an effect when fp8_compute is enabled.")
+ int8_compute: bool = Field(default=False, description="Run the matmuls of ComfyUI int8 builds quantized with convrot ('int8_tensorwise' with 'convrot') on the int8 tensor cores instead of dequantizing their weights on every forward (requires an NVIDIA GPU with compute capability 8.0 or newer and Triton; falls back automatically otherwise, including on AMD, Apple and Intel GPUs and the CPU). Speeds up denoising with these builds, but quantizes activations per token as well, so images will differ from the dequantized path at the same seed. The kernels are tuned once per layer shape and token-count bucket: about 35 seconds for the first image after enabling it, about 1-5 seconds for a later size in a new token-count bucket, cached on disk across restarts.")
# Deprecated CACHE configs
ram: Optional[float] = Field(default=None, gt=0, description="DEPRECATED: This setting is no longer used. It has been replaced by `max_cache_ram_gb`, but most users will not need to use this config since automatic cache size limits should work well in most cases. This config setting will be removed once the new model cache behavior is stable.")
vram: Optional[float] = Field(default=None, ge=0, description="DEPRECATED: This setting is no longer used. It has been replaced by `max_cache_vram_gb`, but most users will not need to use this config since automatic cache size limits should work well in most cases. This config setting will be removed once the new model cache behavior is stable.")
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 eeab7e927f..8c5f15fd76 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
@@ -49,7 +49,10 @@ class CustomDequantizingLinear(DequantizingLinear, CustomModuleMixin):
return autocast_linear_forward_sidecar_patches(self, input, self._patches_and_weights)
def _autocast_forward(self, input: torch.Tensor) -> torch.Tensor:
- return DequantizingLinear.forward(self, input)
+ # The scheme's own forward: the next one after this class in the subclass's MRO, e.g.
+ # `Int8ConvrotLinear.forward`, which is where int8 compute decides between its kernels and the dequantized
+ # path. Naming `DequantizingLinear.forward` here would skip that decision for every wrapped layer.
+ return super().forward(input)
def forward(self, input: torch.Tensor) -> torch.Tensor:
if len(self._patches_and_weights) > 0:
diff --git a/invokeai/backend/quantization/int8_convrot.py b/invokeai/backend/quantization/int8_convrot.py
index f6d986a131..fa2f7266cb 100644
--- a/invokeai/backend/quantization/int8_convrot.py
+++ b/invokeai/backend/quantization/int8_convrot.py
@@ -23,10 +23,11 @@ by ``1/sqrt(size)``. This ``H`` is symmetric and orthonormal (``H == H.T``,
Comfy-Org/comfy-quants and comfy-kitchen ``tensor/int8_utils.py`` — reimplemented
here, not copied.)
-Comfy's W8A8 kernels instead rotate activations at runtime and run int8 GEMMs.
-We target bf16 compute with int8 *storage*: ``Int8ConvrotLinear`` keeps the int8
-weight and scale resident (4.6x smaller than bf16) and materializes the
-dequantized, derotated bf16 weight per forward call. The derotation is a
+By default we target bf16 compute with int8 *storage*: ``Int8ConvrotLinear`` keeps
+the int8 weight and scale resident (4.6x smaller than bf16) and materializes the
+dequantized, derotated bf16 weight per forward call. With ``int8_compute`` on, a
+rotated layer instead rotates and quantizes the activation and runs an int8 GEMM, as
+Comfy's W8A8 kernels do (see ``int8_matmul``). The derotation is a
``[out, in/256, 256] @ [256, 256]`` matmul — a rounding error next to the
transformer forward itself — and the transient bf16 weight (<= ~310 MB for H3's
largest layer) has to fit inside the calling node's working-memory reservation:
@@ -34,6 +35,7 @@ largest layer) has to fit inside the calling node's working-memory reservation:
its estimate for that, since the model's resident size does not account for it.
"""
+import functools
import json
import struct
from collections.abc import Callable, Iterable, Mapping
@@ -51,6 +53,15 @@ from invokeai.backend.quantization.fp8_scaled import (
is_castable_float,
iter_weight_scale_pairs,
)
+from invokeai.backend.quantization.int8_matmul import (
+ KERNEL_ROTATION_GROUP_SIZE,
+ can_use_int8_matmul,
+ int8_linear,
+ is_int8_compute_enabled,
+)
+from invokeai.backend.util.logging import InvokeAILogger
+
+logger = InvokeAILogger.get_logger(__name__)
CONVROT_GROUP_SIZE = 256
@@ -236,6 +247,12 @@ class Int8ConvrotLinear(DequantizingLinear):
(at half the bf16 byte count) 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.
+
+ With ``int8_compute`` on, :meth:`forward` runs the int8 kernels instead wherever
+ :meth:`_can_use_int8_matmul` allows -- rotated layers only -- and the dequantized path
+ otherwise. ``full_precision_matmul`` is the producer's ``full_precision_matrix_mult``
+ marker, which Comfy's quantized-layer config carries for every format: such a layer always
+ dequantizes.
"""
def __init__(
@@ -245,6 +262,7 @@ class Int8ConvrotLinear(DequantizingLinear):
convrot: bool,
bias: torch.Tensor | None = None,
group_size: int = CONVROT_GROUP_SIZE,
+ full_precision_matmul: bool = False,
) -> None:
super().__init__()
if weight.dtype != torch.int8:
@@ -252,6 +270,7 @@ class Int8ConvrotLinear(DequantizingLinear):
self.out_features, self.in_features = weight.shape
self.convrot = convrot
self.group_size = group_size
+ self.full_precision_matmul = full_precision_matmul
self.register_buffer("weight", weight)
self.register_buffer("weight_scale", weight_scale.to(torch.float32))
if convrot:
@@ -283,6 +302,27 @@ class Int8ConvrotLinear(DequantizingLinear):
).view(self.out_features, self.in_features)
return w
+ @property
+ def int8_matmul_eligible(self) -> bool:
+ """Whether the int8 kernels cover this layer at all: rotated in the group size they implement, and not
+ marked full precision by the producer."""
+ return self.convrot and self.group_size == KERNEL_ROTATION_GROUP_SIZE and not self.full_precision_matmul
+
+ def _can_use_int8_matmul(self, x: torch.Tensor) -> bool:
+ """Whether this forward may run on the int8 kernels; see :func:`can_use_int8_matmul` for the rest."""
+ return self.int8_matmul_eligible and can_use_int8_matmul(x, self.in_features)
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ if not self._can_use_int8_matmul(x):
+ return super().forward(x)
+ return int8_linear(
+ x,
+ self.weight,
+ self.weight_scale,
+ self.bias,
+ fallback=functools.partial(DequantizingLinear.forward, self),
+ )
+
def dequant_transient_bytes(self, compute_dtype: torch.dtype) -> int:
"""Two weight-sized tensors in the compute dtype.
@@ -295,6 +335,10 @@ class Int8ConvrotLinear(DequantizingLinear):
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``).
"""
return 2 * self.out_features * self.in_features * compute_dtype.itemsize
@@ -669,7 +713,11 @@ def swap_in_int8_linears(model: torch.nn.Module, sd: dict[str, Any], quantized:
Pass only what :func:`split_int8_convrot_layers` returned: every layer refused below is one that
split would have dequantized instead.
+
+ With ``int8_compute`` on, logs how many of the layers its kernels do not cover, so a model that
+ gains little from the setting says why.
"""
+ installed: list[Int8ConvrotLinear] = []
for path, marker in quantized.items():
weight, scale = sd.get(f"{path}.weight"), sd.get(f"{path}.weight_scale")
if weight is None or scale is None:
@@ -696,16 +744,23 @@ def swap_in_int8_linears(model: torch.nn.Module, sd: dict[str, Any], quantized:
f"'{path}' is marked int8_tensorwise and the {extra}'s Linear has a bias, but the "
f"{missing} has none. The checkpoint does not match this architecture."
)
- setattr(
- parent,
- attribute,
- Int8ConvrotLinear(
- weight=weight,
- weight_scale=scale,
- convrot=bool(marker.get("convrot", False)),
- bias=bias,
- group_size=int(marker.get("convrot_groupsize", CONVROT_GROUP_SIZE)),
- ),
+ 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)),
+ )
+ 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)
+ logger.info(
+ f"int8_compute: {len(uncovered)} of {len(installed)} int8 layer(s) keep dequantizing per forward "
+ f"({marked} marked full_precision_matrix_mult, {len(uncovered) - marked} not rotated in groups of "
+ f"{KERNEL_ROTATION_GROUP_SIZE})."
)
diff --git a/invokeai/backend/quantization/int8_matmul.py b/invokeai/backend/quantization/int8_matmul.py
new file mode 100644
index 0000000000..99308fa703
--- /dev/null
+++ b/invokeai/backend/quantization/int8_matmul.py
@@ -0,0 +1,370 @@
+"""int8 compute: W8A8 matmuls for convrot ``int8_tensorwise`` linears on NVIDIA GPUs, opt-in via ``int8_compute``.
+
+By default an :class:`~invokeai.backend.quantization.int8_convrot.Int8ConvrotLinear` dequantizes its int8 weight to
+the compute dtype on every forward and multiplies in bf16/fp16 -- on an RTX 4090 that is 0.75-0.97x the speed of a
+dense bf16 layer. With ``int8_compute`` on, a layer quantized with convrot instead rotates and quantizes its
+*activation* per token to int8 as well and multiplies on the int8 tensor cores (``int8_matmul_kernels``): 2.8-3.2x a
+dense bf16 layer at 4608 tokens, 1.9x at 128.
+
+That changes numerics, which is why it is opt-in: against the dense weight, W8A8 measures ~0.8-0.9 % relative output
+error where the dequantized path measures ~0.3-0.4 %, so images differ from that path at the same seed. Only rotated
+layers take it: the rotation spreads outlier channels across the group before the per-token scale is taken, and
+unrotated layers, where one outlier channel sets the scale for the whole token, were not measured. A layer whose int8
+weight partial loading left in RAM streams it to the GPU per call, as the dequantized path does, and gets the same
+result as when resident.
+
+Memory: a call whose kernels are tuned and validated never needs more than the dequantized path's per-forward transient,
+``Int8ConvrotLinear.dequant_transient_bytes`` (two weight-sized tensors in the compute dtype, 4·N·K bytes). It allocates
+the int8 activation copy for at most ``2·N`` rows at a time (``_chunk_rows``), 2·N·K bytes, plus the int8 weight (N·K)
+when it is streamed; the output is the one ``F.linear`` would allocate too. The first call per tuning key may briefly
+need a little more: tuning allocates an L2-sized flush buffer (see ``int8_matmul_kernels``), and the validation
+afterwards runs ``_FIRST_CALL_ROWS`` rows through the dequantized path -- its own transient, after the kernels' streamed
+weight is released -- and holds that slice of the reference output.
+
+This module owns the policy: which calls may take the kernels, where the kernels exist, and what happens when they
+fail. The kernels live in ``int8_matmul_kernels``, which imports Triton and is therefore imported here lazily, on the
+first call that could use it -- InvokeAI imports and runs without Triton.
+
+Failures never fail a generation the dequantized path could finish (see ``triton_kernels``):
+
+* An out-of-memory error propagates like any other: outside a key's first call, the fallback would not fit either.
+* A Triton cache ``OSError`` falls back for that call; ``MAX_CACHE_FAILURES`` in a row retire the device.
+* Any other kernel error retires the device for int8 compute until restart, with one warning.
+* The first call per autotune key compares a slice of its rows with the dequantized path and retires the device if
+ they disagree by more than ``_FIRST_CALL_MAX_ERROR``: the kernels are JIT-compiled per GPU architecture and tile, so
+ a miscompile would otherwise reach images silently.
+"""
+
+import functools
+import importlib
+import logging
+import math
+import threading
+from collections.abc import Callable
+from types import ModuleType
+
+import torch
+
+from invokeai.backend.util.logging import InvokeAILogger
+from invokeai.backend.util.oom import is_oom_error
+from invokeai.backend.util.triton_kernels import (
+ TRITON_REQUIREMENT,
+ FailureOutcome,
+ TritonKernelHealth,
+ is_missing_triton,
+ relative_error,
+)
+
+logger = InvokeAILogger.get_logger(__name__)
+
+_KERNELS_MODULE = "invokeai.backend.quantization.int8_matmul_kernels"
+# The rotation the activation kernel implements in registers. Weights rotated in other group sizes fall back.
+KERNEL_ROTATION_GROUP_SIZE = 256
+_HALF_PRECISION = (torch.float16, torch.bfloat16)
+# int8 tensor-core GEMMs through Triton: Ampere and newer. Measured on sm_89 only; older GPUs fall back.
+_MIN_CAPABILITY = (8, 0)
+# Largest relative L2 difference between the first kernel result of an autotune key and the dequantized path. W8A8
+# measures ~0.8-0.9 % against the dense weight. A broken kernel lands near 1 or above: an all-zero output scores
+# exactly 1, an unrelated one of the same magnitude ~1.4, a missing scale far more. 0.3 sits well clear of both.
+_FIRST_CALL_MAX_ERROR = 0.3
+# Rows of a key's first call that are recomputed on the dequantized path for that comparison, from the end so the
+# last, partial tile is among them. A kernel that miscompiled garbles every tile, so a slice catches what the whole
+# output would, without holding a second output-sized tensor.
+_FIRST_CALL_ROWS = 256
+# Autotune results are keyed by the next power of two of the row count, capped, rather than by the row count: every
+# resolution inside one bucket reuses the result instead of tuning again.
+_MAX_M_BUCKET = 16384
+
+# Opt-in for the same reason as fp8 compute: an existing install would start producing different images at the same
+# seed. Tests override it process-wide without a configured app.
+_int8_compute_override: bool | None = None
+
+
+def set_int8_compute_enabled(enabled: bool | None) -> None:
+ """Override the configured setting process-wide. Pass ``None`` to revert to the config value."""
+ global _int8_compute_override
+ _int8_compute_override = enabled
+
+
+def is_int8_compute_enabled() -> bool:
+ if _int8_compute_override is not None:
+ return _int8_compute_override
+ try:
+ from invokeai.app.services.config.config_default import get_config
+
+ return bool(get_config().int8_compute)
+ except Exception:
+ # Backend code may run outside a configured app (scripts, tests). Default to the dequantized path.
+ return False
+
+
+_health = TritonKernelHealth()
+_lock = threading.Lock()
+# Held around the kernels of every tuning key not yet validated, i.e. while it may still be tuning. Two GPUs tuning the
+# same key at once compile the same twelve tiles into the same Triton cache files; on Windows that collides with an
+# OSError, each collision falls back and tunes again on the next layer, and three in a row retire the device.
+# Serialized, the second GPU finds the first one's results and compiled kernels on disk. Once a key is validated it
+# is never taken again.
+_tuning_lock = threading.Lock()
+# Per device: whether the kernels can run there at all, decided once (and explained once in the log).
+_available: dict[torch.device, bool] = {}
+
+
+def _load_kernels() -> ModuleType | str:
+ """The kernels module, or why it cannot be imported. Cached: an install does not gain Triton while running."""
+ try:
+ return importlib.import_module(_KERNELS_MODULE)
+ except ModuleNotFoundError as e:
+ if is_missing_triton(e):
+ return f"it needs {TRITON_REQUIREMENT}"
+ return f"loading its kernels failed ({e!r})"
+ except Exception as e:
+ return f"loading Triton failed ({e!r})"
+
+
+def _unavailable_reason(device: torch.device) -> tuple[str, int] | None:
+ """Why the kernels cannot run on ``device``, and how loudly to say so; None where they can."""
+ if device.type != "cuda" or torch.version.hip is not None:
+ return "it runs on NVIDIA GPUs only", logging.INFO
+ major, minor = torch.cuda.get_device_capability(device)
+ if (major, minor) < _MIN_CAPABILITY:
+ required = ".".join(map(str, _MIN_CAPABILITY))
+ return f"it needs compute capability {required} or newer, this GPU has {major}.{minor}", logging.INFO
+ kernels = _load_kernels()
+ # Missing or broken Triton on a GPU that could run the kernels is the one case the user can fix.
+ return (kernels, logging.WARNING) if isinstance(kernels, str) else None
+
+
+def _kernels_available(device: torch.device) -> bool:
+ available = _available.get(device)
+ if available is None:
+ with _lock:
+ available = _available.get(device)
+ if available is None:
+ unavailable = _unavailable_reason(device)
+ available = unavailable is None
+ _available[device] = available
+ if unavailable is not None:
+ reason, level = unavailable
+ logger.log(
+ level,
+ f"int8_compute is enabled, but not used on {device}: {reason}. int8 layers there dequantize.",
+ )
+ return available and not _health.is_retired(device)
+
+
+def can_use_int8_matmul(x: torch.Tensor, in_features: int) -> bool:
+ """Whether a forward of ``x`` through a rotated int8 layer of this width may run on the int8 kernels.
+
+ Every condition falls back to the dequantized path rather than raising: a mid-generation failure is far worse
+ than losing the speedup. Checked per forward, so the cheap ones go first. Where the weight lives does not matter:
+ a streamed one is copied to ``x``'s device.
+ """
+ if not is_int8_compute_enabled():
+ return False
+ if x.dtype not in _HALF_PRECISION or x.numel() == 0:
+ return False
+ # A width mismatch is F.linear's to report; the kernels would read past the weight.
+ if x.shape[-1] != in_features or x.stride(-1) != 1:
+ return False
+ # No backward, and autocast would have changed the dtype F.linear computes in.
+ if torch.is_grad_enabled() and x.requires_grad:
+ return False
+ if torch.is_autocast_enabled(x.device.type):
+ return False
+ return _kernels_available(x.device)
+
+
+def _m_bucket(rows: int) -> int:
+ return min(1 << max(rows - 1, 0).bit_length(), _MAX_M_BUCKET)
+
+
+def _chunk_rows(out_features: int) -> int:
+ """Rows quantized and multiplied at once: their int8 copy (2·N·K bytes) plus a streamed int8 weight (N·K) stays
+ below the dequantized path's 4·N·K, leaving a weight's worth of headroom for the scales and allocator rounding."""
+ return 2 * out_features
+
+
+def int8_linear(
+ x: torch.Tensor,
+ weight: torch.Tensor,
+ weight_scale: torch.Tensor,
+ bias: torch.Tensor | None,
+ *,
+ fallback: Callable[[torch.Tensor], torch.Tensor],
+) -> torch.Tensor:
+ """``F.linear`` of ``x`` with a convrot int8 weight on the int8 kernels, or ``fallback(x)`` where they failed.
+
+ Call only where :func:`can_use_int8_matmul` agreed. ``fallback`` computes the same layer on the dequantized path
+ for any rows of ``x``.
+ """
+ kernels = _load_kernels()
+ assert not isinstance(kernels, str), "can_use_int8_matmul() was not consulted"
+ in_features = x.shape[-1]
+ try:
+ rows = x.view(-1, in_features)
+ except RuntimeError:
+ # Leading dimensions that cannot be merged without a copy; that copy is not in the memory bound.
+ return fallback(x)
+ device = x.device
+ out_features = weight.shape[0]
+ out = torch.empty((rows.shape[0], out_features), dtype=x.dtype, device=device)
+ # The kernels' streamed weight copy is released when this returns: the comparison below runs the dequantized
+ # path, which streams the weight itself.
+ failure, unvalidated = _run_kernels(kernels, rows, weight.to(device), weight_scale.to(device), bias, out)
+ if failure is None and unvalidated:
+ failure = _synchronize_kernels(device)
+ if failure is None:
+ failure = _validate_all(unvalidated, fallback)
+ # The kept rows are views of `out`: every reference to the buffer goes before a fallback allocates its own.
+ del unvalidated
+ if failure is None:
+ _health.record_success(device)
+ if _health.first_use(device):
+ logger.info(f"int8 compute: rotated int8_tensorwise layers on {device} run on the int8 tensor cores.")
+ return out.view(*x.shape[:-1], out_features)
+
+ # Out of the `except` that caught the failure, and with the partial output released, before the fallback runs.
+ del out
+ outcome, error = failure
+ if outcome is FailureOutcome.RETIRED:
+ logger.warning(
+ f"int8 compute failed on {device} for a {out_features}x{in_features} layer, input {tuple(x.shape)} "
+ f"{x.dtype} ({error}). int8 layers on this device dequantize until restart; set `int8_compute: false` "
+ "to stop using int8 compute."
+ )
+ return fallback(x)
+
+
+def _run_kernels(
+ kernels: ModuleType,
+ rows: torch.Tensor,
+ weight: torch.Tensor,
+ weight_scale: torch.Tensor,
+ bias: torch.Tensor | None,
+ out: torch.Tensor,
+) -> tuple[tuple[FailureOutcome, str] | None, dict[tuple, tuple[torch.Tensor, torch.Tensor]]]:
+ """Launch the kernels chunk by chunk into ``out``: the first failure, and the last rows of every chunk whose
+ tuning key is not validated yet, as views of ``rows`` and ``out``."""
+ bias = bias.to(rows.device) if bias is not None else None
+ chunk = _chunk_rows(weight.shape[0])
+ unvalidated: dict[tuple, tuple[torch.Tensor, torch.Tensor]] = {}
+ for start in range(0, rows.shape[0], chunk):
+ chunk_rows, chunk_out = rows[start : start + chunk], out[start : start + chunk]
+ key = _tuning_key(chunk_rows, chunk_out, weight, weight_scale, bias)
+ if _health.is_validated(key):
+ failure = _launch(kernels, chunk_rows, weight, weight_scale, bias, chunk_out)
+ else:
+ with _tuning_lock:
+ failure = _launch(kernels, chunk_rows, weight, weight_scale, bias, chunk_out)
+ tail = slice(-_FIRST_CALL_ROWS, None)
+ unvalidated.setdefault(key, (chunk_rows[tail], chunk_out[tail]))
+ if failure is not None:
+ return failure, unvalidated
+ return None, unvalidated
+
+
+def _synchronize(device: torch.device) -> None:
+ if device.type == "cuda":
+ torch.cuda.synchronize(device)
+
+
+def _synchronize_kernels(device: torch.device) -> tuple[FailureOutcome, str] | None:
+ """Wait for this call's kernels, so a fault they raise asynchronously counts as theirs; None if there was none.
+
+ Triton launches return before the kernel runs, and a fault it hits surfaces at the next synchronization. Without
+ this, that is the dequantized reference of the first-call check, which then raises out of the generation instead
+ of being recorded as int8 compute's failure. Recorded here, the device is retired either way, but only an error
+ that leaves the CUDA context usable falls back cleanly: a sticky one, such as an illegal memory access, makes the
+ fallback fail too, and the generation with it. Only calls with a key still to validate wait here, because that is
+ where a broken compile shows up; steady-state calls stay asynchronous.
+ """
+ try:
+ _synchronize(device)
+ except Exception as e:
+ return _kernel_failure(device, e)
+ return None
+
+
+def _kernel_failure(device: torch.device, error: Exception) -> tuple[FailureOutcome, str]:
+ """Account for a kernel exception and describe it. Out-of-memory errors propagate (see the module docstring).
+
+ Only the description leaves the caller's ``except``: the exception's traceback would keep the failed kernel's
+ tensors alive through the fallback.
+ """
+ if isinstance(error, RuntimeError) and is_oom_error(error):
+ raise error
+ return _health.record_failure(device, error), repr(error)
+
+
+def _tuning_key(
+ rows: torch.Tensor, out: torch.Tensor, weight: torch.Tensor, weight_scale: torch.Tensor, bias: torch.Tensor | None
+) -> tuple:
+ """What selects a different tuned and compiled kernel for this chunk, so each one is validated on its own.
+
+ The autotune key (device, row bucket, N, K, dtypes), plus what Triton specializes a compiled kernel on: whether
+ pointers start 16-byte aligned and integers are multiples of 16. A chunk that starts mid-output for an odd N, or a
+ row count off the 16 grid, runs a different binary than the first chunk did.
+ """
+ return (
+ rows.device,
+ rows.dtype,
+ None if bias is None else bias.dtype,
+ weight_scale.numel() == 1,
+ weight.shape[0],
+ weight.shape[1],
+ _m_bucket(rows.shape[0]),
+ rows.data_ptr() % 16 == 0,
+ out.data_ptr() % 16 == 0,
+ rows.shape[0] % 16 == 0,
+ rows.stride(0) % 16 == 0,
+ )
+
+
+def _validate_all(
+ unvalidated: dict[tuple, tuple[torch.Tensor, torch.Tensor]], fallback: Callable[[torch.Tensor], torch.Tensor]
+) -> tuple[FailureOutcome, str] | None:
+ for key, (rows, out) in unvalidated.items():
+ failure = _validate(key, rows, out, fallback)
+ if failure is not None:
+ return failure
+ return None
+
+
+def _validate(
+ key: tuple, rows: torch.Tensor, out: torch.Tensor, fallback: Callable[[torch.Tensor], torch.Tensor]
+) -> tuple[FailureOutcome, str] | None:
+ """Compare a key's first kernel rows with the dequantized path; the failure to act on, or None.
+
+ Not inside the kernel's ``try``: a dequantized path that fails is not int8 compute's failure. A reference that is
+ not finite (an fp16 overflow, a NaN input) or all zero (zero rows without a bias) says nothing about the kernel:
+ the key is left unvalidated for a later call to check, and the kernel's output stands -- it ran without error,
+ and recomputing the whole layer on the dequantized path would cost the memory the chunking saves.
+ """
+ expected = fallback(rows)
+ reference = torch.linalg.vector_norm(expected, dtype=torch.float32).item()
+ if not math.isfinite(reference) or reference == 0.0:
+ return None
+ error = relative_error(out, expected)
+ if not math.isfinite(error) or error > _FIRST_CALL_MAX_ERROR:
+ mismatch = RuntimeError(f"its first result differs from the dequantized path by {error:.2f} (relative L2)")
+ return _health.record_failure(rows.device, mismatch), repr(mismatch)
+ _health.mark_validated(key)
+ return None
+
+
+def _launch(
+ kernels: ModuleType,
+ rows: torch.Tensor,
+ weight: torch.Tensor,
+ weight_scale: torch.Tensor,
+ bias: torch.Tensor | None,
+ out: torch.Tensor,
+) -> tuple[FailureOutcome, str] | None:
+ """The failure and its description, or None."""
+ try:
+ kernels.w8a8_rows(rows, weight, weight_scale, bias, out, _m_bucket(rows.shape[0]))
+ except Exception as e:
+ return _kernel_failure(rows.device, e)
+ return None
diff --git a/invokeai/backend/quantization/int8_matmul_kernels.py b/invokeai/backend/quantization/int8_matmul_kernels.py
new file mode 100644
index 0000000000..26e9ed7f53
--- /dev/null
+++ b/invokeai/backend/quantization/int8_matmul_kernels.py
@@ -0,0 +1,269 @@
+"""Triton kernels for W8A8 int8 linears: activation rotation + per-token quantization, and the int8 GEMM.
+
+Imported only by ``int8_matmul`` on first use, never at InvokeAI import time: this module imports Triton at the top,
+because ``@triton.jit`` needs it at definition time, and InvokeAI has to import on machines without Triton. Policy --
+which calls run here, how rows are chunked, what happens when a kernel fails -- lives in ``int8_matmul``; this module
+only computes.
+
+For a convrot ``int8_tensorwise`` weight, stored rotated as ``W_rot = grouped_256(W) @ H`` and quantized to ``W_q``
+with per-output-channel scale ``s_w``, ``y = x @ W^T`` is computed as
+
+1. ``x' = grouped_256(x) @ H`` -- ``H`` is symmetric and orthonormal, so ``x @ W^T = x' @ W_rot^T``;
+2. ``q = clamp(floor(x' / s_x + 0.5), -127, 127)`` with ``s_x = amax(|x'|) / 127`` per token (row);
+3. ``y = (q @ W_q^T) * s_x[m] * s_w[n] + bias``, the GEMM in int8 with int32 accumulation, the rest in float32
+ before rounding to the compute dtype once.
+
+Every K handled here is a multiple of 256 (the rotation group), so neither kernel masks along K. Row offsets are
+computed in int64: a row index times a row stride passes 2^31 for large token counts (a video transformer's batch
+of ~100k tokens times a 16k-wide layer), and an int32 wrap there is an illegal memory access the fallback cannot
+recover from.
+"""
+
+import threading
+
+import torch
+import triton
+import triton.language as tl
+
+ROTATION_GROUP_SIZE = 256
+# Rows one program of the activation kernel quantizes. Each program reads its rows twice (amax, then quantize), so
+# small blocks keep the second read in L2; 4 rows measured 0.9-1.5 TB/s on an RTX 4090.
+_QUANT_ROWS = 4
+# Flush buffer for autotune timing when the device does not report its L2 size.
+_DEFAULT_L2_BYTES = 64 * 1024 * 1024
+# Autotune time budget per config, as Triton's own `do_bench` uses (milliseconds).
+_BENCH_WARMUP_MS = 25
+_BENCH_REPEAT_MS = 100
+
+
+def _hadamard_256(x, ROWS: tl.constexpr):
+ """``x @ H`` for each row of a ``[ROWS, 256]`` block, ``H`` the normalized regular Hadamard of size 256.
+
+ ``H = H4 (x) H4 (x) H4 (x) H4 / 16`` with the regular seed ``H4 = J - 2 * antidiag``, so ``H4 @ v`` is
+ ``sum(v) - 2 * flip(v)``: viewed as ``[ROWS, 4, 4, 4, 4]``, the rotation is that step along each of the four
+ axes, in registers, without a matmul or a loaded matrix.
+ """
+ x = tl.reshape(x, (ROWS, 4, 4, 4, 4))
+ x = tl.sum(x, axis=1, keep_dims=True) - 2.0 * tl.flip(x, 1)
+ x = tl.sum(x, axis=2, keep_dims=True) - 2.0 * tl.flip(x, 2)
+ x = tl.sum(x, axis=3, keep_dims=True) - 2.0 * tl.flip(x, 3)
+ x = tl.sum(x, axis=4, keep_dims=True) - 2.0 * tl.flip(x, 4)
+ return tl.reshape(x, (ROWS, 256)) * 0.0625
+
+
+def _nan_max(a, b):
+ # A NaN anywhere in a row makes its scale NaN, so the row's output is NaN as on the dequantized path, instead of
+ # the NaN being dropped by the reduction and the row coming out finite.
+ return tl.maximum(a, b, propagate_nan=tl.PropagateNan.ALL)
+
+
+def _rotated_block(X, row_offsets, row_mask, k, ROWS: tl.constexpr):
+ cols = k + tl.arange(0, 256)
+ x = tl.load(X + row_offsets[:, None] + cols[None, :], mask=row_mask[:, None], other=0.0).to(tl.float32)
+ return _hadamard_256(x, ROWS)
+
+
+def _quantize_activations_kernel(X, Q, S, M, K, stride_xm, stride_qm, ROWS: tl.constexpr):
+ rows = tl.program_id(0) * ROWS + tl.arange(0, ROWS)
+ row_mask = rows < M
+ x_rows = rows.to(tl.int64) * stride_xm
+ q_rows = rows.to(tl.int64) * stride_qm
+ amax = tl.zeros([ROWS], dtype=tl.float32)
+ for k in range(0, K, 256):
+ x = _rotated_block(X, x_rows, row_mask, k, ROWS)
+ amax = _nan_max(amax, tl.reduce(tl.abs(x), 1, _nan_max))
+ amax = _nan_max(amax, 1e-12)
+ inverse = 127.0 / amax
+ tl.store(S + rows, amax / 127.0, mask=row_mask)
+ # Second pass recomputes the rotation rather than keeping K floats per row resident.
+ for k in range(0, K, 256):
+ x = _rotated_block(X, x_rows, row_mask, k, ROWS)
+ q = tl.minimum(tl.maximum(tl.floor(x * inverse[:, None] + 0.5), -127.0), 127.0)
+ tl.store(Q + q_rows[:, None] + (k + tl.arange(0, 256))[None, :], q.to(tl.int8), mask=row_mask[:, None])
+
+
+def gemm_configs() -> list[triton.Config]:
+ """Tiles the autotuner picks from. A tile a GPU lacks the shared memory for fails to compile with
+ ``OutOfResources``, which the autotuner scores as never fastest; the largest ones sit close to the ~99 KB of
+ sm_86 and sm_89."""
+ return [
+ triton.Config({"BM": bm, "BN": bn, "BK": bk, "GROUP_M": 8}, num_stages=stages, num_warps=warps)
+ for bm, bn, bk, stages, warps in (
+ (128, 256, 64, 3, 8),
+ (256, 128, 64, 3, 8),
+ (128, 128, 128, 3, 8),
+ (128, 128, 64, 4, 4),
+ (128, 128, 64, 4, 8),
+ (64, 256, 64, 4, 4),
+ (128, 64, 128, 4, 4),
+ (64, 128, 128, 4, 4),
+ (64, 64, 128, 4, 4),
+ (32, 64, 128, 4, 4),
+ (128, 256, 128, 2, 8),
+ (256, 128, 128, 2, 8),
+ )
+ ]
+
+
+def _int8_gemm_kernel(
+ A, W, A_SCALE, W_SCALE, BIAS, C, M, N, K, M_BUCKET, stride_am, stride_wn, stride_wk, stride_cm, stride_ws,
+ HAS_BIAS: tl.constexpr, BM: tl.constexpr, BN: tl.constexpr, BK: tl.constexpr, GROUP_M: tl.constexpr,
+): # fmt: skip
+ # M_BUCKET is only an autotune key. Grouped launch order: GROUP_M row blocks share each weight column block while
+ # it is in L2.
+ pid = tl.program_id(0)
+ num_pid_m = tl.cdiv(M, BM)
+ num_pid_n = tl.cdiv(N, BN)
+ num_pid_in_group = GROUP_M * num_pid_n
+ first_pid_m = (pid // num_pid_in_group) * GROUP_M
+ group_size_m = min(num_pid_m - first_pid_m, GROUP_M)
+ pid_m = first_pid_m + ((pid % num_pid_in_group) % group_size_m)
+ pid_n = (pid % num_pid_in_group) // group_size_m
+ rm = pid_m * BM + tl.arange(0, BM)
+ rn = pid_n * BN + tl.arange(0, BN)
+ rk = tl.arange(0, BK)
+ # Out-of-range rows and columns read row/column 0 instead of masking every load of the hot loop; the store
+ # discards them. K is a multiple of 256 and therefore of BK.
+ a_ptrs = A + tl.where(rm < M, rm, 0).to(tl.int64)[:, None] * stride_am + rk[None, :]
+ w_ptrs = W + tl.where(rn < N, rn, 0).to(tl.int64)[None, :] * stride_wn + rk[:, None] * stride_wk
+ acc = tl.zeros([BM, BN], dtype=tl.int32)
+ for _ in range(0, tl.cdiv(K, BK)):
+ acc = tl.dot(tl.load(a_ptrs), tl.load(w_ptrs), acc, out_dtype=tl.int32)
+ a_ptrs += BK
+ w_ptrs += BK * stride_wk
+ a_scale = tl.load(A_SCALE + rm, mask=rm < M, other=0.0)
+ w_scale = tl.load(W_SCALE + rn * stride_ws, mask=rn < N, other=0.0).to(tl.float32)
+ out = acc.to(tl.float32) * a_scale[:, None] * w_scale[None, :]
+ if HAS_BIAS:
+ out += tl.load(BIAS + rn, mask=rn < N, other=0.0).to(tl.float32)[None, :]
+ c_mask = (rm < M)[:, None] & (rn < N)[None, :]
+ tl.store(C + rm.to(tl.int64)[:, None] * stride_cm + rn[None, :], out.to(C.dtype.element_ty), mask=c_mask)
+
+
+def _benchmark_with_l2_flush(device: torch.device):
+ """Triton's ``do_bench`` timing loop, with an L2 flush buffer the size of this GPU's L2.
+
+ Triton's own flushes with a fixed 256 MB buffer, allocated per config while a layer is being tuned -- several
+ times what the working-memory estimate of a small model's largest layer leaves room for. A buffer the size of the
+ L2 (72 MB on an RTX 4090) evicts it just the same.
+ """
+ flush_bytes = getattr(torch.cuda.get_device_properties(device), "L2_cache_size", 0) or _DEFAULT_L2_BYTES
+
+ def bench(kernel_call, quantiles):
+ flush = torch.empty(flush_bytes // 4, dtype=torch.int32, device=device)
+ kernel_call()
+ torch.cuda.synchronize(device)
+ start, end = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
+ start.record()
+ for _ in range(5):
+ flush.zero_()
+ kernel_call()
+ end.record()
+ torch.cuda.synchronize(device)
+ estimate_ms = max(start.elapsed_time(end) / 5, 1e-3)
+ for _ in range(max(1, int(_BENCH_WARMUP_MS / estimate_ms))):
+ kernel_call()
+ repeats = max(1, int(_BENCH_REPEAT_MS / estimate_ms))
+ starts = [torch.cuda.Event(enable_timing=True) for _ in range(repeats)]
+ ends = [torch.cuda.Event(enable_timing=True) for _ in range(repeats)]
+ for begin, finish in zip(starts, ends, strict=True):
+ flush.zero_()
+ begin.record()
+ kernel_call()
+ finish.record()
+ torch.cuda.synchronize(device)
+ times = torch.tensor([begin.elapsed_time(finish) for begin, finish in zip(starts, ends, strict=True)])
+ return torch.quantile(times, torch.tensor(quantiles, dtype=times.dtype)).tolist()
+
+ return bench
+
+
+# One autotuner per device. Its in-memory result cache is keyed by shape only, so a machine with two different GPUs
+# would otherwise run the second on the first one's tiles; and its ``run`` keeps per-call state on the instance, which
+# two sessions tuning at once on different GPUs would trample. On disk, results are keyed by GPU architecture too, so
+# identical GPUs share them across restarts.
+_gemm_by_device: dict[torch.device, triton.runtime.Autotuner] = {}
+_gemm_lock = threading.Lock()
+
+
+def _gemm_for(device: torch.device) -> triton.runtime.Autotuner:
+ gemm = _gemm_by_device.get(device)
+ if gemm is None:
+ with _gemm_lock:
+ gemm = _gemm_by_device.get(device)
+ if gemm is None:
+ gemm = triton.autotune(
+ configs=gemm_configs(),
+ key=["M_BUCKET", "N", "K"],
+ cache_results=True,
+ do_bench=_benchmark_with_l2_flush(device),
+ )(_int8_gemm_kernel)
+ _gemm_by_device[device] = gemm
+ return gemm
+
+
+def quantize_activations(x2d: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
+ """Rotate and quantize ``[M, K]`` rows to int8, one float32 scale per row. Rows may be strided along M."""
+ m, k = x2d.shape
+ q = torch.empty((m, k), dtype=torch.int8, device=x2d.device)
+ scale = torch.empty((m,), dtype=torch.float32, device=x2d.device)
+ _quantize_activations_kernel[(triton.cdiv(m, _QUANT_ROWS),)](
+ x2d, q, scale, m, k, x2d.stride(0), q.stride(0), ROWS=_QUANT_ROWS
+ )
+ return q, scale
+
+
+def launch_gemm(
+ kernel,
+ q: torch.Tensor,
+ q_scale: torch.Tensor,
+ weight: torch.Tensor,
+ weight_scale: torch.Tensor,
+ bias: torch.Tensor | None,
+ out: torch.Tensor,
+ m_bucket: int,
+ **meta,
+) -> None:
+ """Write ``(q @ weight^T) * q_scale[:, None] * weight_scale[None, :] + bias`` into ``out``.
+
+ ``kernel`` is the per-device autotuner, or the bare kernel with a tile in ``meta``. ``weight_scale`` holds ``N``
+ per-channel values or one per-tensor value; ``out`` may be a row slice of a larger output.
+ """
+ m, k = q.shape
+ n = weight.shape[0]
+ weight_scale = weight_scale.reshape(-1)
+
+ def grid(launch: dict) -> tuple[int]:
+ return (triton.cdiv(m, launch["BM"]) * triton.cdiv(n, launch["BN"]),)
+
+ kernel[grid](
+ q, weight, q_scale, weight_scale, bias if bias is not None else weight_scale, out, m, n, k, m_bucket,
+ q.stride(0), weight.stride(0), weight.stride(1), out.stride(0), 1 if weight_scale.numel() > 1 else 0,
+ HAS_BIAS=bias is not None, **meta,
+ ) # fmt: skip
+
+
+def w8a8_rows(
+ x2d: torch.Tensor,
+ weight: torch.Tensor,
+ weight_scale: torch.Tensor,
+ bias: torch.Tensor | None,
+ out: torch.Tensor,
+ m_bucket: int,
+) -> None:
+ """``F.linear`` of half-precision rows ``x2d`` with a convrot int8 weight, as W8A8, written into ``out``.
+
+ Every tensor must be on ``x2d``'s CUDA device, and ``x2d`` must have unit stride along K. ``m_bucket`` is the
+ autotune key for the row count. The kernels launch on that device whichever device is current: a session worker
+ pins its thread to its GPU, a single-device install with ``device: cuda:1`` does not.
+ """
+ if x2d.shape[-1] % ROTATION_GROUP_SIZE != 0:
+ raise ValueError(f"in_features {x2d.shape[-1]} is not a multiple of {ROTATION_GROUP_SIZE}")
+ with torch.cuda.device(x2d.device):
+ q, q_scale = quantize_activations(x2d)
+ launch_gemm(_gemm_for(x2d.device), q, q_scale, weight, weight_scale, bias, out, m_bucket)
diff --git a/invokeai/backend/util/sage_attention.py b/invokeai/backend/util/sage_attention.py
index 7510e5a278..1d77825338 100644
--- a/invokeai/backend/util/sage_attention.py
+++ b/invokeai/backend/util/sage_attention.py
@@ -25,7 +25,6 @@ import functools
import inspect
import math
import re
-import threading
from collections import Counter
from collections.abc import Callable, Iterator
from contextlib import contextmanager
@@ -37,6 +36,13 @@ import torch
from invokeai.backend.util.logging import InvokeAILogger
from invokeai.backend.util.oom import is_oom_error
+from invokeai.backend.util.triton_kernels import (
+ TRITON_REQUIREMENT,
+ FailureOutcome,
+ TritonKernelHealth,
+ is_missing_triton,
+ relative_error,
+)
logger = InvokeAILogger.get_logger(__name__)
@@ -61,10 +67,6 @@ _FIRST_CALL_MAX_ERROR = 0.5
# tile is among them. A kernel that never ran garbles every row, so a slice catches what the whole output would; the
# whole output costs ~14 bytes per element to compare -- about 5 GB for one call of Wan 2.2 14B at 720p.
_FIRST_CALL_ROWS = 1024
-# Triton failing to write a compiled kernel to its cache (on Windows, when two GPUs compile the same kernel at once)
-# says nothing about the kernel: that call falls back and the next tries again. A device that fails this way this many
-# times in a row is retired like any other, so a cache that can never be written does not recompile on every call.
-_MAX_CACHE_FAILURES = 3
DOCS_URL = "https://invoke-ai.github.io/InvokeAI-7/configuration/optimization/sage-attention/"
@@ -80,12 +82,8 @@ class _Usage:
_scope: ContextVar[_Usage | None] = ContextVar("invokeai_sage_attention_scope", default=None)
-_lock = threading.Lock()
-_disabled_devices: set[int] = set()
-# (device, dtype, head size): the kernel variants whose first result was compared with SDPA.
-_validated: set[tuple[int, torch.dtype, int]] = set()
-_cache_failures: Counter[int] = Counter()
-_announced_devices: set[int] = set()
+# Keyed by CUDA index; validated variants by (index, dtype, head size), the inputs that pick a different kernel.
+_health = TritonKernelHealth()
@contextmanager
@@ -250,41 +248,23 @@ def _check_first_result(
group = query.shape[1] // key.shape[1]
rows = slice(-_FIRST_CALL_ROWS, None)
expected = original(query[:1, :group, rows], key[:1, :1], value[:1, :1], scale=scale, enable_gqa=group > 1)
- difference = torch.linalg.vector_norm(out[:1, :group, rows] - expected, dtype=torch.float32)
- reference = torch.linalg.vector_norm(expected, dtype=torch.float32).clamp_min(1e-6)
- error = (difference / reference).item()
+ error = relative_error(out[:1, :group, rows], expected)
if not math.isfinite(error) or error > _FIRST_CALL_MAX_ERROR:
raise RuntimeError(f"its first result differs from PyTorch SDPA by {error:.2f} (relative L2)")
- with _lock:
- _validated.add((index, query.dtype, query.shape[-1]))
+ _health.mark_validated((index, query.dtype, query.shape[-1]))
-def _cache_failure(index: int) -> bool:
- """Count a Triton cache failure on this device; True once it failed too often in a row to keep retrying."""
- with _lock:
- _cache_failures[index] += 1
- return _cache_failures[index] >= _MAX_CACHE_FAILURES
-
-
-def _disable(index: int, error: Exception, query: torch.Tensor, key: torch.Tensor) -> None:
- with _lock:
- first = index not in _disabled_devices
- _disabled_devices.add(index)
- if first:
- logger.warning(
- f"SageAttention failed on cuda:{index} for query {tuple(query.shape)}, key {tuple(key.shape)}, "
- f"{query.dtype} ({error!r}). Attention on this device uses PyTorch SDPA until restart; set "
- "`attention_backend: auto` to stop using SageAttention."
- )
+def _warn_retired(index: int, error: Exception, query: torch.Tensor, key: torch.Tensor) -> None:
+ logger.warning(
+ f"SageAttention failed on cuda:{index} for query {tuple(query.shape)}, key {tuple(key.shape)}, "
+ f"{query.dtype} ({error!r}). Attention on this device uses PyTorch SDPA until restart; set "
+ "`attention_backend: auto` to stop using SageAttention."
+ )
def _announce(index: int, version: str, kernel: Callable[..., torch.Tensor]) -> None:
- if index in _announced_devices:
+ if not _health.first_use(index):
return
- with _lock:
- if index in _announced_devices:
- return
- _announced_devices.add(index)
major, minor = torch.cuda.get_device_capability(index)
name = getattr(kernel, "func", kernel).__name__
logger.info(
@@ -342,8 +322,8 @@ def install_sage_attention() -> None:
)
return
except ModuleNotFoundError as e:
- if (e.name or "").split(".")[0] == "triton":
- hint = "it needs Triton, which on Windows is the `triton-windows` package"
+ if is_missing_triton(e):
+ hint = f"it needs {TRITON_REQUIREMENT}"
else:
hint = "the `sageattention` package is not installed"
logger.warning(unavailable + f"{hint}. {see_docs}")
@@ -374,7 +354,7 @@ def install_sage_attention() -> None:
reason = "memory"
if reason is None:
index = _cuda_index(query, key, value)
- kernel = kernels.get(index) if index is not None and index not in _disabled_devices else None
+ kernel = kernels.get(index) if index is not None and not _health.is_retired(index) else None
if index is None or kernel is None:
reason = "device"
else:
@@ -388,7 +368,7 @@ def install_sage_attention() -> None:
is_causal=False,
sm_scale=scale if scale is not None else query.shape[-1] ** -0.5,
)
- if (index, query.dtype, query.shape[-1]) not in _validated:
+ if not _health.is_validated((index, query.dtype, query.shape[-1])):
_check_first_result(index, original, query, key, value, scale, out)
except Exception as e:
if isinstance(e, RuntimeError) and is_oom_error(e):
@@ -402,15 +382,13 @@ def install_sage_attention() -> None:
f"SageAttention ran out of memory on cuda:{index} for query {tuple(query.shape)}; "
"the rest of this generation uses PyTorch SDPA."
)
- elif isinstance(e, OSError) and not _cache_failure(index):
- reason = "cache"
else:
- _disable(index, e, query, key)
- reason = "error"
+ outcome = _health.record_failure(index, e)
+ if outcome is FailureOutcome.RETIRED:
+ _warn_retired(index, e, query, key)
+ reason = "cache" if outcome is FailureOutcome.TRANSIENT else "error"
else:
- if _cache_failures[index]:
- with _lock:
- _cache_failures.pop(index, None)
+ _health.record_success(index)
usage.served += 1
_announce(index, version, kernel)
return out
diff --git a/invokeai/backend/util/triton_kernels.py b/invokeai/backend/util/triton_kernels.py
new file mode 100644
index 0000000000..84a6af8139
--- /dev/null
+++ b/invokeai/backend/util/triton_kernels.py
@@ -0,0 +1,115 @@
+"""Failure policy shared by InvokeAI's optional Triton-backed kernels (SageAttention, int8 compute).
+
+Both run a third-party or JIT-compiled kernel inside a forward pass that must not fail because of it, so both answer
+the same questions the same way:
+
+* A kernel that raised, or whose first result was wrong, is retired for its device until restart, with one warning.
+ A second warning per call would flood the log for every layer of every step.
+* Triton failing to write a compiled kernel to its on-disk cache says nothing about the kernel: that call falls back
+ and the next tries again, unless it keeps failing (see ``MAX_CACHE_FAILURES``).
+* Each kernel variant's first result is compared with the exact path it replaces (see ``relative_error``).
+
+Out-of-memory errors are deliberately not classified here: SageAttention moves the rest of a generation to SDPA,
+which needs less, while int8 compute lets them propagate because its fallback needs more. Each caller decides.
+"""
+
+import threading
+from collections import Counter
+from collections.abc import Hashable
+from enum import Enum
+
+import torch
+
+# Triton failing to write a compiled kernel to its cache (on Windows, when two GPUs compile the same kernel at once)
+# says nothing about the kernel. A device that fails this way this many times in a row is retired like any other, so
+# a cache that can never be written does not recompile on every call.
+MAX_CACHE_FAILURES = 3
+
+# What a log line tells the user to install when Triton is missing.
+TRITON_REQUIREMENT = "Triton, which on Windows is the `triton-windows` package"
+
+
+def is_missing_triton(error: ModuleNotFoundError) -> bool:
+ """Whether an import failed because Triton itself is not installed, rather than the package that needs it."""
+ return (error.name or "").split(".")[0] == "triton"
+
+
+def relative_error(actual: torch.Tensor, expected: torch.Tensor) -> float:
+ """Relative L2 distance of ``actual`` from ``expected``, computed in float32 and read back to the host.
+
+ Reading it back synchronizes the device, which is the point for a first-call check: a kernel launch error that
+ would otherwise surface in some later, unrelated operation is raised here, inside the caller's ``try``. A result
+ that is not finite (uninitialized memory, an overflowed epilogue) comes back as NaN or inf.
+ """
+ difference = torch.linalg.vector_norm(actual - expected, dtype=torch.float32)
+ reference = torch.linalg.vector_norm(expected, dtype=torch.float32).clamp_min(1e-6)
+ return (difference / reference).item()
+
+
+class FailureOutcome(Enum):
+ """What :meth:`TritonKernelHealth.record_failure` decided about a failed kernel call."""
+
+ # A Triton cache failure: fall back for this call, try the kernel again on the next.
+ TRANSIENT = "transient"
+ # The device was retired by this call; the caller warns once.
+ RETIRED = "retired"
+ # Another call retired the device first (concurrent sessions); nothing more to say.
+ ALREADY_RETIRED = "already_retired"
+
+
+class TritonKernelHealth:
+ """Per-device state of one optional kernel: retired devices, cache-failure streaks, validated variants, first use.
+
+ Keys are whatever identifies a device to the caller (a CUDA index, a ``torch.device``); validation keys add what
+ selects a different compiled kernel (dtype, head size). One instance per kernel, for the life of the process.
+ Thread-safe: InvokeAI runs one generation session per GPU concurrently, and those threads share it.
+
+ The read paths (``is_retired``, ``is_validated``, ``record_success``'s common case) take no lock: they run on every
+ kernel call, and reading a set or dict another thread may be adding to is safe under the GIL.
+ """
+
+ def __init__(self, max_cache_failures: int = MAX_CACHE_FAILURES) -> None:
+ self._max_cache_failures = max_cache_failures
+ self._lock = threading.Lock()
+ self._retired: set[Hashable] = set()
+ self._cache_failures: Counter[Hashable] = Counter()
+ self._validated: set[Hashable] = set()
+ self._announced: set[Hashable] = set()
+
+ def is_retired(self, device: Hashable) -> bool:
+ return device in self._retired
+
+ def record_failure(self, device: Hashable, error: Exception) -> FailureOutcome:
+ """Account for a kernel call that raised. Callers handle out-of-memory errors before calling this."""
+ with self._lock:
+ if isinstance(error, OSError) and device not in self._retired:
+ self._cache_failures[device] += 1
+ if self._cache_failures[device] < self._max_cache_failures:
+ return FailureOutcome.TRANSIENT
+ if device in self._retired:
+ return FailureOutcome.ALREADY_RETIRED
+ self._retired.add(device)
+ return FailureOutcome.RETIRED
+
+ def record_success(self, device: Hashable) -> None:
+ """End a device's cache-failure streak: only failures in a row retire it."""
+ if self._cache_failures.get(device):
+ with self._lock:
+ self._cache_failures.pop(device, None)
+
+ def is_validated(self, variant: Hashable) -> bool:
+ return variant in self._validated
+
+ def mark_validated(self, variant: Hashable) -> None:
+ with self._lock:
+ self._validated.add(variant)
+
+ def first_use(self, device: Hashable) -> bool:
+ """True exactly once per device: the call that should announce the kernel is in use there."""
+ if device in self._announced:
+ return False
+ with self._lock:
+ if device in self._announced:
+ return False
+ self._announced.add(device)
+ return True
diff --git a/invokeai/frontend/api/openapi.json b/invokeai/frontend/api/openapi.json
index 952a0e6ec9..1bd67f3212 100644
--- a/invokeai/frontend/api/openapi.json
+++ b/invokeai/frontend/api/openapi.json
@@ -61559,6 +61559,12 @@
"description": "Honor the per-layer 'full_precision_matrix_mult' flags that some scaled-fp8 checkpoints ship. Those layers then dequantize on every forward instead of using the fp8 tensor cores, which can cost a large part of the fp8_compute speedup - on checkpoints that mark many layers, most of it. Set to false to run every quantized layer on the fp8 tensor cores, ignoring the producer's instruction; faster, but the marked layers were flagged as numerically sensitive, so quality may suffer. Only has an effect when fp8_compute is enabled.",
"default": true
},
+ "int8_compute": {
+ "type": "boolean",
+ "title": "Int8 Compute",
+ "description": "Run the matmuls of ComfyUI int8 builds quantized with convrot ('int8_tensorwise' with 'convrot') on the int8 tensor cores instead of dequantizing their weights on every forward (requires an NVIDIA GPU with compute capability 8.0 or newer and Triton; falls back automatically otherwise, including on AMD, Apple and Intel GPUs and the CPU). Speeds up denoising with these builds, but quantizes activations per token as well, so images will differ from the dequantized path at the same seed. The kernels are tuned once per layer shape and token-count bucket: about 35 seconds for the first image after enabling it, about 1-5 seconds for a later size in a new token-count bucket, cached on disk across restarts.",
+ "default": false
+ },
"ram": {
"anyOf": [
{
@@ -62022,7 +62028,7 @@
"additionalProperties": false,
"type": "object",
"title": "InvokeAIAppConfig",
- "description": "Invoke's global app configuration.\n\nTypically, you won't need to interact with this class directly. Instead, use the `get_config` function from `invokeai.app.services.config` to get a singleton config object.\n\nAttributes:\n host: IP address to bind to. Use `0.0.0.0` to serve to your local network.\n port: Port to bind to.\n allow_origins: Allowed CORS origins.\n allow_credentials: Allow CORS credentials.\n allow_methods: Methods allowed for CORS.\n allow_headers: Headers allowed for CORS.\n ssl_certfile: SSL certificate file for HTTPS. See https://www.uvicorn.dev/settings/#https.\n ssl_keyfile: SSL key file for HTTPS. See https://www.uvicorn.dev/settings/#https.\n show_donation_link: Show the Donate to InvokeAI link in the frontend menus.\n log_tokenization: Enable logging of parsed prompt tokens.\n patchmatch: Enable patchmatch inpaint code.\n models_dir: Path to the models directory.\n convert_cache_dir: Path to the converted models cache directory (DEPRECATED, but do not delete because it is needed for migration from previous versions).\n download_cache_dir: Path to the directory that contains dynamically downloaded models.\n legacy_conf_dir: Path to directory of legacy checkpoint config files.\n db_dir: Path to InvokeAI databases directory.\n db_url: URL of a MySQL 8.4+ or MariaDB 10.11+ database to use instead of the SQLite database in `db_dir`, e.g. `mariadb+pymysql://invokeai:[email protected]/invokeai`. Needs the `mysql` extra. One InvokeAI process uses a database at a time. Read at startup only.\n db_synchronous: SQLite durability setting. `full`, the default and what InvokeAI has always used, flushes every commit to disk. `normal` acknowledges commits without waiting for that flush - measured at roughly 12x shorter commits on an SSD - and cannot corrupt the database under WAL, which is why it is refused, with a warning, when WAL is unavailable for the database file. What `normal` gives up is the most recent transactions on a power loss or OS crash: a just-written image record or queue status, not the image file itself.<br>Valid values: `full`, `normal`\n outputs_dir: Path to directory for outputs.\n image_subfolder_strategy: Strategy for organizing images into subfolders. 'flat' stores all images in a single folder. 'date' organizes by YYYY/MM/DD. 'type' organizes by image category. 'hash' uses first 2 characters of UUID for filesystem performance.<br>Valid values: `flat`, `date`, `type`, `hash`\n custom_nodes_dir: Path to directory for custom nodes.\n style_presets_dir: Path to directory for style presets.\n workflow_thumbnails_dir: Path to directory for workflow thumbnails.\n log_handlers: Log handler. Valid options are \"console\", \"file=<path>\", \"syslog=path|address:host:port\", \"http=<url>\".\n log_format: Log format. Use \"plain\" for text-only, \"color\" for colorized output, \"legacy\" for 2.3-style logging and \"syslog\" for syslog-style.<br>Valid values: `plain`, `color`, `syslog`, `legacy`\n log_level: Emit logging messages at this level or higher.<br>Valid values: `debug`, `info`, `warning`, `error`, `critical`\n log_sql: Log SQL queries. `log_level` must be `debug` for this to do anything. Extremely verbose.\n log_level_network: Log level for network-related messages. 'info' and 'debug' are very verbose.<br>Valid values: `debug`, `info`, `warning`, `error`, `critical`\n use_memory_db: Use in-memory database. Useful for development.\n dev_reload: Automatically reload when Python sources are changed. Does not reload node definitions.\n profile_graphs: Enable graph profiling using `cProfile`.\n profile_prefix: An optional prefix for profile output files.\n profiles_dir: Path to profiles output directory.\n max_cache_ram_gb: The maximum amount of CPU RAM to use for model caching in GB. If unset, the limit will be configured based on the available RAM. In most cases, it is recommended to leave this unset.\n max_cache_vram_gb: The amount of VRAM to use for model caching in GB. If unset, the limit will be configured based on the available VRAM and the device_working_mem_gb. In most cases, it is recommended to leave this unset.\n reserve_vram_gb: The amount of VRAM (in GB) to subtract from the model cache's available memory budget. Defaults to 0.\n log_memory_usage: If True, a memory snapshot will be captured before and after every model cache operation, and the result will be logged (at debug level). There is a time cost to capturing the memory snapshots, so it is recommended to only enable this feature if you are actively inspecting the model cache's behaviour.\n model_cache_keep_alive_min: How long to keep models in cache after last use, in minutes. A value of 0 (the default) means models are kept in cache indefinitely. If no model generations occur within the timeout period, the model cache is cleared using the same logic as the 'Clear Model Cache' button.\n device_working_mem_gb: The amount of working memory to keep available on the compute device (in GB). Has no effect if running on CPU. If you are experiencing OOM errors, try increasing this value.\n enable_partial_loading: Enable partial loading of models. This enables models to run with reduced VRAM requirements (at the cost of slower speed) by streaming the model from RAM to VRAM as its used. In some edge cases, partial loading can cause models to run more slowly if they were previously being fully loaded into VRAM.\n keep_ram_copy_of_weights: Whether to keep a full RAM copy of a model's weights when the model is loaded in VRAM. Keeping a RAM copy increases average RAM usage, but speeds up model switching and LoRA patching (assuming there is sufficient RAM). Set this to False if RAM pressure is consistently high.\n offload_on_architecture_switch: When a session uses main models of another architecture than the previous one on the same GPU, move every model it does not use from VRAM to RAM before it runs. Models both sessions use stay. Switching back reloads the moved models from RAM, which costs a few seconds per switch when both architectures would have fit in VRAM together; turn this off if you alternate between such models.\n clear_vram_after_session: After every queue item (each image of a batch), move the models held in VRAM to RAM and return the freed memory to the GPU driver. The models stay cached in RAM; the next item reloads them from there, which costs a few seconds (more with keep_ram_copy_of_weights off). Changes nothing where VRAM is system memory (CPU, MPS, integrated GPUs). Turn this on if a generation that runs fine the first time runs out of memory, or slows down sharply because the GPU spills into shared memory, when it is repeated.\n fp8_compute: Keep ComfyUI 'scaled fp8' checkpoints quantized instead of dequantizing them at load, and run their matmuls on the fp8 tensor cores (requires an Ada/SM 8.9 or newer NVIDIA GPU, or a ROCm GPU that passes an fp8 matmul probe; falls back automatically otherwise). Speeds up denoising and keeps the transformer at fp8 size - FP8 Storage alone also keeps it at that size, without the speedup - but quantizes activations as well, so images will differ from previous versions at the same seed. Reproducibility also requires the model to be FULLY resident in VRAM: a layer whose weights are still in RAM falls back to the dequantized path, and since which layers are resident shifts from run to run, the same seed then yields visibly different images. For repeatable output, ensure the model loads at 100% (e.g. enable_partial_loading=false with enough free VRAM).\n fp8_compute_full_precision_hints: Honor the per-layer 'full_precision_matrix_mult' flags that some scaled-fp8 checkpoints ship. Those layers then dequantize on every forward instead of using the fp8 tensor cores, which can cost a large part of the fp8_compute speedup - on checkpoints that mark many layers, most of it. Set to false to run every quantized layer on the fp8 tensor cores, ignoring the producer's instruction; faster, but the marked layers were flagged as numerically sensitive, so quality may suffer. Only has an effect when fp8_compute is enabled.\n ram: DEPRECATED: This setting is no longer used. It has been replaced by `max_cache_ram_gb`, but most users will not need to use this config since automatic cache size limits should work well in most cases. This config setting will be removed once the new model cache behavior is stable.\n vram: DEPRECATED: This setting is no longer used. It has been replaced by `max_cache_vram_gb`, but most users will not need to use this config since automatic cache size limits should work well in most cases. This config setting will be removed once the new model cache behavior is stable.\n lazy_offload: DEPRECATED: This setting is no longer used. Lazy-offloading is enabled by default. This config setting will be removed once the new model cache behavior is stable.\n pytorch_cuda_alloc_conf: Configure the Torch CUDA memory allocator. This will impact peak reserved VRAM usage and performance. Setting to \"backend:cudaMallocAsync\" works well on many systems. The optimal configuration is highly dependent on the system configuration (device type, VRAM, CUDA driver version, etc.), so must be tuned experimentally. Unset on a ROCm build of PyTorch on Windows, \"expandable_segments:True\" is used.\n device: Preferred execution device. `auto` will choose the device depending on the hardware platform and the installed torch capabilities.<br>Valid values: `auto`, `cpu`, `cuda`, `mps`, `xpu`, `cuda:N`, `xpu:N` (where N is a device number)\n precision: Floating point precision. `float16` will consume half the memory of `float32` but produce slightly lower-quality images. The `auto` setting will guess the proper precision based on your video card and operating system.<br>Valid values: `auto`, `float16`, `bfloat16`, `float32`\n rocm_aotriton_experimental: Use AOTriton's fused (flash and memory-efficient) attention kernels on AMD GPUs that PyTorch marks experimental for them, such as the RX 7600/7700/7800 series, Ryzen AI 300/Max and the RX 9060 series, by setting TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL. Without them, attention on those GPUs runs on the slower math kernel, which also needs far more memory. `auto` turns them on only with a ROCm 10 build of PyTorch, and only when every GPU used for generation is one they were measured correct on (so far gfx1200, the RX 9060 series); `on` and `off` decide for any build and GPU. A TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL value already set in the environment takes precedence. Has no effect on other GPUs.<br>Valid values: `auto`, `on`, `off`\n sequential_guidance: Whether to calculate guidance in serial instead of in parallel, lowering memory requirements.\n noise_dtype: The dtype seeded noise is drawn in for SD1.5/SDXL, SD3, FLUX.1, FLUX.2, CogView4 and the Z-Image seed variance enhancer. `float32` draws the same noise on every platform. `float16` is the half-precision draw of earlier versions: on macOS it keeps the images your seeds gave before this update; on Windows and Linux both values give (nearly) the same images, and images made before the update cannot be reproduced there.<br>Valid values: `float32`, `float16`\n wan_memory_optimization: Enable experimental Wan memory optimizations at the cost of slower generation.\n pid_memory_optimization: Enable experimental PiD decode memory optimizations. Roughly halves the peak activation memory of a PiD decode; in exchange the decoded image changes slightly, because neither the chunked pixel pathway nor the float32 sampler intermediates are bit-exact with the default path.\n attention_type: Attention type.<br>Valid values: `auto`, `normal`, `xformers`, `sliced`, `torch-sdp`\n attention_slice_size: Slice size, valid when attention_type==\"sliced\".<br>Valid values: `auto`, `balanced`, `max`, `1`, `2`, `3`, `4`, `5`, `6`, `7`, `8`\n attention_backend: Attention kernel for the attention inside diffusion models. `auto` lets PyTorch choose among its exact SDPA kernels and never selects a quantized one. `sage` uses SageAttention 2 for the models listed in the SageAttention docs: faster, most at high resolutions and for video, but quantized, so images differ slightly from `auto` at the same seed. SageAttention is installed separately and needs an NVIDIA GPU with compute capability 8.0 or newer; masked attention, text encoders and VAEs keep PyTorch SDPA.<br>Valid values: `auto`, `sage`\n force_tiled_decode: Whether to enable tiled VAE decode (reduces memory consumption with some performance penalty). A tiled decode is not pixel-identical to a single-pass one: a VAE decoder normalises and attends over the whole image, so the difference is spread across it rather than confined to the tile seams. Also tiles the encode. Read by the SD1.5/SDXL, FLUX.1, FLUX.2, Z-Image, Qwen-Image and Qwen-Image-2.1 VAE nodes, the Anima encode, the Z-Image control encode and the Krea-2 style reference; other model families ignore it.\n auto_tiled_decode: Decode large images in tiles when an untiled decode's estimated working memory would take most of the GPU's memory (FLUX.1, FLUX.2, Z-Image, Qwen-Image, Qwen-Image-2.1, Krea-2 and Wan decodes, and Qwen-Image-2.1 encodes). Turn off to decode untiled unless tiling is requested; the FLUX.1, FLUX.2 and Z-Image decodes then still retry tiled after running out of memory. Anima keeps tiling a decode too large for its GPU either way, because tiling is what makes that case fast there.\n pil_compress_level: The compress_level setting of PIL.Image.save(), used for PNG encoding. All settings are lossless. 0 = no compression, 1 = fastest with slightly larger filesize, 9 = slowest with smallest filesize. 1 is typically the best setting.\n max_queue_size: Maximum number of items in the session queue.\n session_queue_mode: Session queue mode. Use 'FIFO' for traditional first-in-first-out, or 'round_robin' to serve each user's jobs in turn. In single-user mode, FIFO is always used regardless of this setting.<br>Valid values: `FIFO`, `round_robin`\n clear_queue_on_startup: Empties session queue on startup. If true, disables `max_queue_history`.\n max_queue_history: Keep the last N completed, failed, and canceled queue items. Older items are deleted on startup. Set to 0 to prune all terminal items. Ignored if `clear_queue_on_startup` is true.\n allow_nodes: List of nodes to allow. Omit to allow all.\n deny_nodes: List of nodes to deny. Omit to deny none.\n node_cache_size: How many cached nodes to keep in memory.\n hashing_algorithm: Model hashing algorthim for model installs. 'blake3_multi' is best for SSDs. 'blake3_single' is best for spinning disk HDDs. 'random' disables hashing, instead assigning a UUID to models. Useful when using a memory db to reduce model installation time, or if you don't care about storing stable hashes for models. Alternatively, any other hashlib algorithm is accepted, though these are not nearly as performant as blake3.<br>Valid values: `blake3_multi`, `blake3_single`, `random`, `md5`, `sha1`, `sha224`, `sha256`, `sha384`, `sha512`, `blake2b`, `blake2s`, `sha3_224`, `sha3_256`, `sha3_384`, `sha3_512`, `shake_128`, `shake_256`\n remote_api_tokens: List of regular expression and token pairs used when downloading models from URLs. The download URL is tested against the regex, and if it matches, the token is provided in as a Bearer token.\n scan_models_on_startup: Scan the models directory on startup, registering orphaned models. This is typically only used in conjunction with `use_memory_db` for testing purposes.\n allow_private_download_urls: Allow the download queue to fetch from loopback, link-local and private-network addresses. Disabled by default so that a download URL cannot be used to reach services that are only reachable from the server. Enable this only if you install models from a mirror on your own network.\n download_proxy: Optional HTTP proxy for model downloads. The proxy must enforce the public-address policy because proxy-side DNS cannot be checked by InvokeAI.\n unsafe_disable_picklescan: UNSAFE. Disable the picklescan security check during model installation. Recommended only for development and testing purposes. This will allow arbitrary code execution during model installation, so should never be used in production.\n allow_unknown_models: Allow installation of models that we are unable to identify. If enabled, models will be marked as `unknown` in the database, and will not have any metadata associated with them. If disabled, unknown models will be rejected during installation.\n multiuser: Enable multiuser support. When disabled, the application runs in single-user mode using a default system account with administrator privileges. When enabled, requires user authentication and authorization.\n strict_password_checking: Enforce strict password requirements. When True, passwords must contain uppercase, lowercase, and numbers. When False (default), any password is accepted but its strength (weak/moderate/strong) is reported to the user.\n image_index_enabled: Maintain a semantic embedding index of gallery images and videos, used by the image map and semantic search features.\n image_index_model: Name of the installed CLIP Vision or SigLIP model used to embed gallery images and video thumbnails. Changing the model discards embeddings computed by the previous model.\n image_index_device: Set to `cpu` to compute image embeddings on the CPU with a service-local copy of the model - avoids VRAM use and lets indexing run during generations. Any other value is ignored: embeddings otherwise run on the model cache's device, pausing while generations are in progress.\n image_index_batch_size: Number of gallery items embedded per batch by the image index worker.\n external_alibabacloud_api_key: API key for Alibaba Cloud DashScope image generation.\n external_alibabacloud_base_url: Base URL override for Alibaba Cloud DashScope image generation.\n external_atlascloud_api_key: API key for Atlas Cloud image generation.\n external_atlascloud_base_url: Base URL override for Atlas Cloud image generation.\n external_gemini_api_key: API key for Gemini image generation.\n external_openai_api_key: API key for OpenAI image generation.\n external_gemini_base_url: Base URL override for Gemini image generation.\n external_openai_base_url: Base URL override for OpenAI image generation.\n external_seedream_api_key: API key for Seedream image generation.\n external_seedream_base_url: Base URL override for Seedream image generation.\n base_url: Public base path when running behind a reverse proxy under a sub-path, e.g. `/invoke`. Set only when the proxy PRESERVES the sub-path (the backend receives `/invoke/api/...`). Leave unset when the proxy strips the sub-path or when serving at the domain root.\n forwarded_allow_ips: Comma-separated list of IPs (or `*`) allowed to set X-Forwarded-* headers. Set to the reverse proxy's IP. Only used when `base_url` is set.\n http_compression_level: Compression level for gzipped HTTP API responses. 0 disables response compression entirely, 1 is fastest, 9 (the default) is smallest. Compression runs on the event loop and blocks the whole server while it works, and level 9 costs about 5.5x the time of level 1 for 0.4 percentage points of extra compression, so lowering this makes the app noticeably more responsive on large libraries. Set to 0 when a reverse proxy already compresses responses."
+ "description": "Invoke's global app configuration.\n\nTypically, you won't need to interact with this class directly. Instead, use the `get_config` function from `invokeai.app.services.config` to get a singleton config object.\n\nAttributes:\n host: IP address to bind to. Use `0.0.0.0` to serve to your local network.\n port: Port to bind to.\n allow_origins: Allowed CORS origins.\n allow_credentials: Allow CORS credentials.\n allow_methods: Methods allowed for CORS.\n allow_headers: Headers allowed for CORS.\n ssl_certfile: SSL certificate file for HTTPS. See https://www.uvicorn.dev/settings/#https.\n ssl_keyfile: SSL key file for HTTPS. See https://www.uvicorn.dev/settings/#https.\n show_donation_link: Show the Donate to InvokeAI link in the frontend menus.\n log_tokenization: Enable logging of parsed prompt tokens.\n patchmatch: Enable patchmatch inpaint code.\n models_dir: Path to the models directory.\n convert_cache_dir: Path to the converted models cache directory (DEPRECATED, but do not delete because it is needed for migration from previous versions).\n download_cache_dir: Path to the directory that contains dynamically downloaded models.\n legacy_conf_dir: Path to directory of legacy checkpoint config files.\n db_dir: Path to InvokeAI databases directory.\n db_url: URL of a MySQL 8.4+ or MariaDB 10.11+ database to use instead of the SQLite database in `db_dir`, e.g. `mariadb+pymysql://invokeai:[email protected]/invokeai`. Needs the `mysql` extra. One InvokeAI process uses a database at a time. Read at startup only.\n db_synchronous: SQLite durability setting. `full`, the default and what InvokeAI has always used, flushes every commit to disk. `normal` acknowledges commits without waiting for that flush - measured at roughly 12x shorter commits on an SSD - and cannot corrupt the database under WAL, which is why it is refused, with a warning, when WAL is unavailable for the database file. What `normal` gives up is the most recent transactions on a power loss or OS crash: a just-written image record or queue status, not the image file itself.<br>Valid values: `full`, `normal`\n outputs_dir: Path to directory for outputs.\n image_subfolder_strategy: Strategy for organizing images into subfolders. 'flat' stores all images in a single folder. 'date' organizes by YYYY/MM/DD. 'type' organizes by image category. 'hash' uses first 2 characters of UUID for filesystem performance.<br>Valid values: `flat`, `date`, `type`, `hash`\n custom_nodes_dir: Path to directory for custom nodes.\n style_presets_dir: Path to directory for style presets.\n workflow_thumbnails_dir: Path to directory for workflow thumbnails.\n log_handlers: Log handler. Valid options are \"console\", \"file=<path>\", \"syslog=path|address:host:port\", \"http=<url>\".\n log_format: Log format. Use \"plain\" for text-only, \"color\" for colorized output, \"legacy\" for 2.3-style logging and \"syslog\" for syslog-style.<br>Valid values: `plain`, `color`, `syslog`, `legacy`\n log_level: Emit logging messages at this level or higher.<br>Valid values: `debug`, `info`, `warning`, `error`, `critical`\n log_sql: Log SQL queries. `log_level` must be `debug` for this to do anything. Extremely verbose.\n log_level_network: Log level for network-related messages. 'info' and 'debug' are very verbose.<br>Valid values: `debug`, `info`, `warning`, `error`, `critical`\n use_memory_db: Use in-memory database. Useful for development.\n dev_reload: Automatically reload when Python sources are changed. Does not reload node definitions.\n profile_graphs: Enable graph profiling using `cProfile`.\n profile_prefix: An optional prefix for profile output files.\n profiles_dir: Path to profiles output directory.\n max_cache_ram_gb: The maximum amount of CPU RAM to use for model caching in GB. If unset, the limit will be configured based on the available RAM. In most cases, it is recommended to leave this unset.\n max_cache_vram_gb: The amount of VRAM to use for model caching in GB. If unset, the limit will be configured based on the available VRAM and the device_working_mem_gb. In most cases, it is recommended to leave this unset.\n reserve_vram_gb: The amount of VRAM (in GB) to subtract from the model cache's available memory budget. Defaults to 0.\n log_memory_usage: If True, a memory snapshot will be captured before and after every model cache operation, and the result will be logged (at debug level). There is a time cost to capturing the memory snapshots, so it is recommended to only enable this feature if you are actively inspecting the model cache's behaviour.\n model_cache_keep_alive_min: How long to keep models in cache after last use, in minutes. A value of 0 (the default) means models are kept in cache indefinitely. If no model generations occur within the timeout period, the model cache is cleared using the same logic as the 'Clear Model Cache' button.\n device_working_mem_gb: The amount of working memory to keep available on the compute device (in GB). Has no effect if running on CPU. If you are experiencing OOM errors, try increasing this value.\n enable_partial_loading: Enable partial loading of models. This enables models to run with reduced VRAM requirements (at the cost of slower speed) by streaming the model from RAM to VRAM as its used. In some edge cases, partial loading can cause models to run more slowly if they were previously being fully loaded into VRAM.\n keep_ram_copy_of_weights: Whether to keep a full RAM copy of a model's weights when the model is loaded in VRAM. Keeping a RAM copy increases average RAM usage, but speeds up model switching and LoRA patching (assuming there is sufficient RAM). Set this to False if RAM pressure is consistently high.\n offload_on_architecture_switch: When a session uses main models of another architecture than the previous one on the same GPU, move every model it does not use from VRAM to RAM before it runs. Models both sessions use stay. Switching back reloads the moved models from RAM, which costs a few seconds per switch when both architectures would have fit in VRAM together; turn this off if you alternate between such models.\n clear_vram_after_session: After every queue item (each image of a batch), move the models held in VRAM to RAM and return the freed memory to the GPU driver. The models stay cached in RAM; the next item reloads them from there, which costs a few seconds (more with keep_ram_copy_of_weights off). Changes nothing where VRAM is system memory (CPU, MPS, integrated GPUs). Turn this on if a generation that runs fine the first time runs out of memory, or slows down sharply because the GPU spills into shared memory, when it is repeated.\n fp8_compute: Keep ComfyUI 'scaled fp8' checkpoints quantized instead of dequantizing them at load, and run their matmuls on the fp8 tensor cores (requires an Ada/SM 8.9 or newer NVIDIA GPU, or a ROCm GPU that passes an fp8 matmul probe; falls back automatically otherwise). Speeds up denoising and keeps the transformer at fp8 size - FP8 Storage alone also keeps it at that size, without the speedup - but quantizes activations as well, so images will differ from previous versions at the same seed. Reproducibility also requires the model to be FULLY resident in VRAM: a layer whose weights are still in RAM falls back to the dequantized path, and since which layers are resident shifts from run to run, the same seed then yields visibly different images. For repeatable output, ensure the model loads at 100% (e.g. enable_partial_loading=false with enough free VRAM).\n fp8_compute_full_precision_hints: Honor the per-layer 'full_precision_matrix_mult' flags that some scaled-fp8 checkpoints ship. Those layers then dequantize on every forward instead of using the fp8 tensor cores, which can cost a large part of the fp8_compute speedup - on checkpoints that mark many layers, most of it. Set to false to run every quantized layer on the fp8 tensor cores, ignoring the producer's instruction; faster, but the marked layers were flagged as numerically sensitive, so quality may suffer. Only has an effect when fp8_compute is enabled.\n int8_compute: Run the matmuls of ComfyUI int8 builds quantized with convrot ('int8_tensorwise' with 'convrot') on the int8 tensor cores instead of dequantizing their weights on every forward (requires an NVIDIA GPU with compute capability 8.0 or newer and Triton; falls back automatically otherwise, including on AMD, Apple and Intel GPUs and the CPU). Speeds up denoising with these builds, but quantizes activations per token as well, so images will differ from the dequantized path at the same seed. The kernels are tuned once per layer shape and token-count bucket: about 35 seconds for the first image after enabling it, about 1-5 seconds for a later size in a new token-count bucket, cached on disk across restarts.\n ram: DEPRECATED: This setting is no longer used. It has been replaced by `max_cache_ram_gb`, but most users will not need to use this config since automatic cache size limits should work well in most cases. This config setting will be removed once the new model cache behavior is stable.\n vram: DEPRECATED: This setting is no longer used. It has been replaced by `max_cache_vram_gb`, but most users will not need to use this config since automatic cache size limits should work well in most cases. This config setting will be removed once the new model cache behavior is stable.\n lazy_offload: DEPRECATED: This setting is no longer used. Lazy-offloading is enabled by default. This config setting will be removed once the new model cache behavior is stable.\n pytorch_cuda_alloc_conf: Configure the Torch CUDA memory allocator. This will impact peak reserved VRAM usage and performance. Setting to \"backend:cudaMallocAsync\" works well on many systems. The optimal configuration is highly dependent on the system configuration (device type, VRAM, CUDA driver version, etc.), so must be tuned experimentally. Unset on a ROCm build of PyTorch on Windows, \"expandable_segments:True\" is used.\n device: Preferred execution device. `auto` will choose the device depending on the hardware platform and the installed torch capabilities.<br>Valid values: `auto`, `cpu`, `cuda`, `mps`, `xpu`, `cuda:N`, `xpu:N` (where N is a device number)\n precision: Floating point precision. `float16` will consume half the memory of `float32` but produce slightly lower-quality images. The `auto` setting will guess the proper precision based on your video card and operating system.<br>Valid values: `auto`, `float16`, `bfloat16`, `float32`\n rocm_aotriton_experimental: Use AOTriton's fused (flash and memory-efficient) attention kernels on AMD GPUs that PyTorch marks experimental for them, such as the RX 7600/7700/7800 series, Ryzen AI 300/Max and the RX 9060 series, by setting TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL. Without them, attention on those GPUs runs on the slower math kernel, which also needs far more memory. `auto` turns them on only with a ROCm 10 build of PyTorch, and only when every GPU used for generation is one they were measured correct on (so far gfx1200, the RX 9060 series); `on` and `off` decide for any build and GPU. A TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL value already set in the environment takes precedence. Has no effect on other GPUs.<br>Valid values: `auto`, `on`, `off`\n sequential_guidance: Whether to calculate guidance in serial instead of in parallel, lowering memory requirements.\n noise_dtype: The dtype seeded noise is drawn in for SD1.5/SDXL, SD3, FLUX.1, FLUX.2, CogView4 and the Z-Image seed variance enhancer. `float32` draws the same noise on every platform. `float16` is the half-precision draw of earlier versions: on macOS it keeps the images your seeds gave before this update; on Windows and Linux both values give (nearly) the same images, and images made before the update cannot be reproduced there.<br>Valid values: `float32`, `float16`\n wan_memory_optimization: Enable experimental Wan memory optimizations at the cost of slower generation.\n pid_memory_optimization: Enable experimental PiD decode memory optimizations. Roughly halves the peak activation memory of a PiD decode; in exchange the decoded image changes slightly, because neither the chunked pixel pathway nor the float32 sampler intermediates are bit-exact with the default path.\n attention_type: Attention type.<br>Valid values: `auto`, `normal`, `xformers`, `sliced`, `torch-sdp`\n attention_slice_size: Slice size, valid when attention_type==\"sliced\".<br>Valid values: `auto`, `balanced`, `max`, `1`, `2`, `3`, `4`, `5`, `6`, `7`, `8`\n attention_backend: Attention kernel for the attention inside diffusion models. `auto` lets PyTorch choose among its exact SDPA kernels and never selects a quantized one. `sage` uses SageAttention 2 for the models listed in the SageAttention docs: faster, most at high resolutions and for video, but quantized, so images differ slightly from `auto` at the same seed. SageAttention is installed separately and needs an NVIDIA GPU with compute capability 8.0 or newer; masked attention, text encoders and VAEs keep PyTorch SDPA.<br>Valid values: `auto`, `sage`\n force_tiled_decode: Whether to enable tiled VAE decode (reduces memory consumption with some performance penalty). A tiled decode is not pixel-identical to a single-pass one: a VAE decoder normalises and attends over the whole image, so the difference is spread across it rather than confined to the tile seams. Also tiles the encode. Read by the SD1.5/SDXL, FLUX.1, FLUX.2, Z-Image, Qwen-Image and Qwen-Image-2.1 VAE nodes, the Anima encode, the Z-Image control encode and the Krea-2 style reference; other model families ignore it.\n auto_tiled_decode: Decode large images in tiles when an untiled decode's estimated working memory would take most of the GPU's memory (FLUX.1, FLUX.2, Z-Image, Qwen-Image, Qwen-Image-2.1, Krea-2 and Wan decodes, and Qwen-Image-2.1 encodes). Turn off to decode untiled unless tiling is requested; the FLUX.1, FLUX.2 and Z-Image decodes then still retry tiled after running out of memory. Anima keeps tiling a decode too large for its GPU either way, because tiling is what makes that case fast there.\n pil_compress_level: The compress_level setting of PIL.Image.save(), used for PNG encoding. All settings are lossless. 0 = no compression, 1 = fastest with slightly larger filesize, 9 = slowest with smallest filesize. 1 is typically the best setting.\n max_queue_size: Maximum number of items in the session queue.\n session_queue_mode: Session queue mode. Use 'FIFO' for traditional first-in-first-out, or 'round_robin' to serve each user's jobs in turn. In single-user mode, FIFO is always used regardless of this setting.<br>Valid values: `FIFO`, `round_robin`\n clear_queue_on_startup: Empties session queue on startup. If true, disables `max_queue_history`.\n max_queue_history: Keep the last N completed, failed, and canceled queue items. Older items are deleted on startup. Set to 0 to prune all terminal items. Ignored if `clear_queue_on_startup` is true.\n allow_nodes: List of nodes to allow. Omit to allow all.\n deny_nodes: List of nodes to deny. Omit to deny none.\n node_cache_size: How many cached nodes to keep in memory.\n hashing_algorithm: Model hashing algorthim for model installs. 'blake3_multi' is best for SSDs. 'blake3_single' is best for spinning disk HDDs. 'random' disables hashing, instead assigning a UUID to models. Useful when using a memory db to reduce model installation time, or if you don't care about storing stable hashes for models. Alternatively, any other hashlib algorithm is accepted, though these are not nearly as performant as blake3.<br>Valid values: `blake3_multi`, `blake3_single`, `random`, `md5`, `sha1`, `sha224`, `sha256`, `sha384`, `sha512`, `blake2b`, `blake2s`, `sha3_224`, `sha3_256`, `sha3_384`, `sha3_512`, `shake_128`, `shake_256`\n remote_api_tokens: List of regular expression and token pairs used when downloading models from URLs. The download URL is tested against the regex, and if it matches, the token is provided in as a Bearer token.\n scan_models_on_startup: Scan the models directory on startup, registering orphaned models. This is typically only used in conjunction with `use_memory_db` for testing purposes.\n allow_private_download_urls: Allow the download queue to fetch from loopback, link-local and private-network addresses. Disabled by default so that a download URL cannot be used to reach services that are only reachable from the server. Enable this only if you install models from a mirror on your own network.\n download_proxy: Optional HTTP proxy for model downloads. The proxy must enforce the public-address policy because proxy-side DNS cannot be checked by InvokeAI.\n unsafe_disable_picklescan: UNSAFE. Disable the picklescan security check during model installation. Recommended only for development and testing purposes. This will allow arbitrary code execution during model installation, so should never be used in production.\n allow_unknown_models: Allow installation of models that we are unable to identify. If enabled, models will be marked as `unknown` in the database, and will not have any metadata associated with them. If disabled, unknown models will be rejected during installation.\n multiuser: Enable multiuser support. When disabled, the application runs in single-user mode using a default system account with administrator privileges. When enabled, requires user authentication and authorization.\n strict_password_checking: Enforce strict password requirements. When True, passwords must contain uppercase, lowercase, and numbers. When False (default), any password is accepted but its strength (weak/moderate/strong) is reported to the user.\n image_index_enabled: Maintain a semantic embedding index of gallery images and videos, used by the image map and semantic search features.\n image_index_model: Name of the installed CLIP Vision or SigLIP model used to embed gallery images and video thumbnails. Changing the model discards embeddings computed by the previous model.\n image_index_device: Set to `cpu` to compute image embeddings on the CPU with a service-local copy of the model - avoids VRAM use and lets indexing run during generations. Any other value is ignored: embeddings otherwise run on the model cache's device, pausing while generations are in progress.\n image_index_batch_size: Number of gallery items embedded per batch by the image index worker.\n external_alibabacloud_api_key: API key for Alibaba Cloud DashScope image generation.\n external_alibabacloud_base_url: Base URL override for Alibaba Cloud DashScope image generation.\n external_atlascloud_api_key: API key for Atlas Cloud image generation.\n external_atlascloud_base_url: Base URL override for Atlas Cloud image generation.\n external_gemini_api_key: API key for Gemini image generation.\n external_openai_api_key: API key for OpenAI image generation.\n external_gemini_base_url: Base URL override for Gemini image generation.\n external_openai_base_url: Base URL override for OpenAI image generation.\n external_seedream_api_key: API key for Seedream image generation.\n external_seedream_base_url: Base URL override for Seedream image generation.\n base_url: Public base path when running behind a reverse proxy under a sub-path, e.g. `/invoke`. Set only when the proxy PRESERVES the sub-path (the backend receives `/invoke/api/...`). Leave unset when the proxy strips the sub-path or when serving at the domain root.\n forwarded_allow_ips: Comma-separated list of IPs (or `*`) allowed to set X-Forwarded-* headers. Set to the reverse proxy's IP. Only used when `base_url` is set.\n http_compression_level: Compression level for gzipped HTTP API responses. 0 disables response compression entirely, 1 is fastest, 9 (the default) is smallest. Compression runs on the event loop and blocks the whole server while it works, and level 9 costs about 5.5x the time of level 1 for 0.4 percentage points of extra compression, so lowering this makes the app noticeably more responsive on large libraries. Set to 0 when a reverse proxy already compresses responses."
},
"InvokeAIAppConfigWithSetFields": {
"properties": {
diff --git a/invokeai/frontend/api/schema.ts b/invokeai/frontend/api/schema.ts
index 7602a13c23..a0898bc64c 100644
--- a/invokeai/frontend/api/schema.ts
+++ b/invokeai/frontend/api/schema.ts
@@ -23433,6 +23433,7 @@ export type components = {
* clear_vram_after_session: After every queue item (each image of a batch), move the models held in VRAM to RAM and return the freed memory to the GPU driver. The models stay cached in RAM; the next item reloads them from there, which costs a few seconds (more with keep_ram_copy_of_weights off). Changes nothing where VRAM is system memory (CPU, MPS, integrated GPUs). Turn this on if a generation that runs fine the first time runs out of memory, or slows down sharply because the GPU spills into shared memory, when it is repeated.
* fp8_compute: Keep ComfyUI 'scaled fp8' checkpoints quantized instead of dequantizing them at load, and run their matmuls on the fp8 tensor cores (requires an Ada/SM 8.9 or newer NVIDIA GPU, or a ROCm GPU that passes an fp8 matmul probe; falls back automatically otherwise). Speeds up denoising and keeps the transformer at fp8 size - FP8 Storage alone also keeps it at that size, without the speedup - but quantizes activations as well, so images will differ from previous versions at the same seed. Reproducibility also requires the model to be FULLY resident in VRAM: a layer whose weights are still in RAM falls back to the dequantized path, and since which layers are resident shifts from run to run, the same seed then yields visibly different images. For repeatable output, ensure the model loads at 100% (e.g. enable_partial_loading=false with enough free VRAM).
* fp8_compute_full_precision_hints: Honor the per-layer 'full_precision_matrix_mult' flags that some scaled-fp8 checkpoints ship. Those layers then dequantize on every forward instead of using the fp8 tensor cores, which can cost a large part of the fp8_compute speedup - on checkpoints that mark many layers, most of it. Set to false to run every quantized layer on the fp8 tensor cores, ignoring the producer's instruction; faster, but the marked layers were flagged as numerically sensitive, so quality may suffer. Only has an effect when fp8_compute is enabled.
+ * int8_compute: Run the matmuls of ComfyUI int8 builds quantized with convrot ('int8_tensorwise' with 'convrot') on the int8 tensor cores instead of dequantizing their weights on every forward (requires an NVIDIA GPU with compute capability 8.0 or newer and Triton; falls back automatically otherwise, including on AMD, Apple and Intel GPUs and the CPU). Speeds up denoising with these builds, but quantizes activations per token as well, so images will differ from the dequantized path at the same seed. The kernels are tuned once per layer shape and token-count bucket: about 35 seconds for the first image after enabling it, about 1-5 seconds for a later size in a new token-count bucket, cached on disk across restarts.
* ram: DEPRECATED: This setting is no longer used. It has been replaced by `max_cache_ram_gb`, but most users will not need to use this config since automatic cache size limits should work well in most cases. This config setting will be removed once the new model cache behavior is stable.
* vram: DEPRECATED: This setting is no longer used. It has been replaced by `max_cache_vram_gb`, but most users will not need to use this config since automatic cache size limits should work well in most cases. This config setting will be removed once the new model cache behavior is stable.
* lazy_offload: DEPRECATED: This setting is no longer used. Lazy-offloading is enabled by default. This config setting will be removed once the new model cache behavior is stable.
@@ -23824,6 +23825,12 @@ export type components = {
* @default true
*/
fp8_compute_full_precision_hints?: boolean;
+ /**
+ * Int8 Compute
+ * @description Run the matmuls of ComfyUI int8 builds quantized with convrot ('int8_tensorwise' with 'convrot') on the int8 tensor cores instead of dequantizing their weights on every forward (requires an NVIDIA GPU with compute capability 8.0 or newer and Triton; falls back automatically otherwise, including on AMD, Apple and Intel GPUs and the CPU). Speeds up denoising with these builds, but quantizes activations per token as well, so images will differ from the dequantized path at the same seed. The kernels are tuned once per layer shape and token-count bucket: about 35 seconds for the first image after enabling it, about 1-5 seconds for a later size in a new token-count bucket, cached on disk across restarts.
+ * @default false
+ */
+ int8_compute?: boolean;
/**
* Ram
* @description DEPRECATED: This setting is no longer used. It has been replaced by `max_cache_ram_gb`, but most users will not need to use this config since automatic cache size limits should work well in most cases. This config setting will be removed once the new model cache behavior is stable.
diff --git a/tests/backend/quantization/test_int8_matmul.py b/tests/backend/quantization/test_int8_matmul.py
new file mode 100644
index 0000000000..d6a0e30536
--- /dev/null
+++ b/tests/backend/quantization/test_int8_matmul.py
@@ -0,0 +1,684 @@
+"""int8 compute: W8A8 kernels behind `Int8ConvrotLinear` (`backend.quantization.int8_matmul`).
+
+With `int8_compute` off, on a device without the kernels, or for a layer they do not cover, `Int8ConvrotLinear` must
+produce exactly what the dequantized path produces. Where the kernels run, they must match an independent W8A8
+reference, stay close to the dense weight and within the dequantized path's memory, serve the model cache's wrapper
+and LoRA sidecars, and fall back -- never fail -- when they break.
+
+The CPU tests run everywhere: a fake kernels module computing in float32 stands in for the Triton kernels, so they
+establish the policy and the routing, not how the kernels compute. `TestOnNvidiaGpu` does, on an NVIDIA GPU (compute
+capability 8.0+) with Triton, which CI does not have. It is marked `slow`, so run it with `-m slow`: its first run
+JIT-compiles and autotunes the kernels for each test shape (about a minute); later runs hit Triton's on-disk cache.
+"""
+
+import logging
+import sys
+import weakref
+from types import SimpleNamespace
+
+import pytest
+import torch
+import torch.nn.functional as F
+
+import invokeai.backend.quantization.int8_matmul as int8_matmul
+from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.torch_module_autocast import (
+ apply_custom_layers_to_model,
+)
+from invokeai.backend.patches.layer_patcher import LayerPatcher
+from invokeai.backend.patches.layers.lora_layer import LoRALayer
+from invokeai.backend.patches.model_patch_raw import ModelPatchRaw
+from invokeai.backend.quantization.dequantizing_linear import DequantizingLinear
+from invokeai.backend.quantization.int8_convrot import (
+ Int8ConvrotLinear,
+ build_regular_hadamard,
+ dequantize_convrot_weight,
+ swap_in_int8_linears,
+)
+from invokeai.backend.util.triton_kernels import MAX_CACHE_FAILURES, TritonKernelHealth
+
+GROUP = 256
+CPU = torch.device("cpu")
+
+
+def _quantize(weight: torch.Tensor, convrot: bool, group: int = GROUP) -> tuple[torch.Tensor, torch.Tensor]:
+ """Per-output-channel int8 the way Comfy's convrot builds store it: rotate, then quantize."""
+ if convrot:
+ out_features, in_features = weight.shape
+ rotation = build_regular_hadamard(group)
+ weight = (weight.view(out_features, in_features // group, group) @ rotation).view(out_features, in_features)
+ scale = weight.abs().amax(dim=1, keepdim=True).clamp_min(1e-8) / 127.0
+ return (weight / scale).round().clamp(-127, 127).to(torch.int8), scale
+
+
+def _layer(
+ out_features: int = 384, in_features: int = 512, convrot: bool = True, bias: bool = True, group: int = GROUP
+) -> Int8ConvrotLinear:
+ weight = torch.randn(out_features, in_features) * 0.05
+ q, scale = _quantize(weight, convrot, group)
+ return Int8ConvrotLinear(
+ q, scale, convrot=convrot, bias=torch.randn(out_features) if bias else None, group_size=group
+ )
+
+
+def _dequantized(layer: Int8ConvrotLinear, x: torch.Tensor) -> torch.Tensor:
+ """The dequantized path's output."""
+ return DequantizingLinear.forward(layer, x)
+
+
+def int8_compute(monkeypatch):
+ """int8 compute switched on, with fresh per-device state."""
+ monkeypatch.setattr(int8_matmul, "_health", TritonKernelHealth())
+ monkeypatch.setattr(int8_matmul, "_available", {})
+ int8_matmul.set_int8_compute_enabled(True)
+ yield
+ int8_matmul.set_int8_compute_enabled(None)
+
+
+# Added to every output the fake kernels write: small enough to pass the first-call comparison, and a result the
+# dequantized fallback cannot produce, so a test can tell which path an output came from.
+MARK = 0.01
+
+
+class FakeKernels:
+ """Stands in for `int8_matmul_kernels` on the CPU: records each call and writes the dequantized result plus `MARK`
+ into the output it is handed -- or raises `error`, or writes `result(rows)` when a test sets one."""
+
+ def __init__(self) -> None:
+ self.calls: list[int] = []
+ self.error: Exception | None = None
+ self.result = None
+
+ def w8a8_rows(self, rows, weight, weight_scale, bias, out, m_bucket) -> None:
+ self.calls.append(rows.shape[0])
+ if self.error is not None:
+ raise self.error
+ if self.result is not None:
+ out.copy_(self.result(rows))
+ return
+ dense = dequantize_convrot_weight(weight, weight_scale, True, rows.dtype)
+ out.copy_(F.linear(rows, dense, bias.to(rows.dtype) if bias is not None else None) + MARK)
+
+
+def fake_kernels(monkeypatch, int8_compute, caplog) -> FakeKernels:
+ """The CPU, in float32 (no CPU bf16 GEMM), treated as a device with the kernels."""
+ kernels = FakeKernels()
+ monkeypatch.setattr(int8_matmul, "_load_kernels", lambda: kernels)
+ monkeypatch.setattr(int8_matmul, "_HALF_PRECISION", (torch.float32,))
+ monkeypatch.setattr(int8_matmul, "_available", {CPU: True})
+ caplog.set_level(logging.WARNING, logger=int8_matmul.__name__)
+ return kernels
+
+
+def _served_by_the_kernels(caplog) -> bool:
+ """The kernel path completed: nothing was retired and nothing warned."""
+ warnings = [r for r in caplog.records if r.name == int8_matmul.__name__ and r.levelno >= logging.WARNING]
+ return not int8_matmul._health.is_retired(CPU) and not warnings
+
+
+class CountingFallback:
+ def __init__(self, layer: Int8ConvrotLinear) -> None:
+ self.layer = layer
+ self.rows: list[torch.Tensor] = []
+ self.error: Exception | None = None
+
+ def __call__(self, x: torch.Tensor) -> torch.Tensor:
+ self.rows.append(x)
+ if self.error is not None:
+ raise self.error
+ return _dequantized(self.layer, x)
+
+
+def _int8_linear(layer: Int8ConvrotLinear, x: torch.Tensor, fallback) -> torch.Tensor:
+ return int8_matmul.int8_linear(x, layer.weight, layer.weight_scale, layer.bias, fallback=fallback)
+
+
[email protected]("enabled", [False, True], ids=["setting-off", "setting-on"])
+def test_the_setting_decides_on_a_device_with_the_kernels(fake_kernels, enabled):
+ torch.manual_seed(0)
+ int8_matmul.set_int8_compute_enabled(enabled)
+ layer = _layer()
+ x = torch.randn(2, 5, 512)
+
+ out = layer(x)
+
+ assert int8_matmul.can_use_int8_matmul(x, 512) is enabled
+ assert fake_kernels.calls == ([10] if enabled else [])
+ if enabled:
+ torch.testing.assert_close(out, _dequantized(layer, x) + MARK)
+ else:
+ assert torch.equal(out, _dequantized(layer, x))
+
+
+class TestWhereTheKernelsExist:
+ @pytest.mark.parametrize(
+ "hip, capability, kernels, available, level",
+ [
+ (None, (8, 9), SimpleNamespace(), True, None),
+ ("6.4", (9, 4), SimpleNamespace(), False, logging.INFO),
+ (None, (7, 5), SimpleNamespace(), False, logging.INFO),
+ (None, (8, 9), "it needs Triton, which on Windows is the `triton-windows` package", False, logging.WARNING),
+ ],
+ ids=["nvidia", "rocm", "turing", "no-triton"],
+ )
+ def test_each_device_is_decided_and_explained_once(
+ self, monkeypatch, int8_compute, caplog, hip, capability, kernels, available, level
+ ):
+ monkeypatch.setattr(torch.version, "hip", hip)
+ monkeypatch.setattr(torch.cuda, "get_device_capability", lambda device=None: capability)
+ monkeypatch.setattr(int8_matmul, "_load_kernels", lambda: kernels)
+ caplog.set_level(logging.INFO, logger=int8_matmul.__name__)
+ device = torch.device("cuda", 0)
+
+ assert [int8_matmul._kernels_available(device) for _ in range(2)] == [available, available]
+ assert [r.levelno for r in caplog.records] == ([] if level is None else [level])
+ if level == logging.WARNING:
+ assert "triton-windows" in caplog.records[0].message
+
+ def test_other_device_types_fall_back(self, int8_compute):
+ assert not int8_matmul._kernels_available(CPU)
+
+
+class TestTheGate:
+ """Branches of `can_use_int8_matmul` and the layer's own conditions, on CPU tensor metadata (no matmul runs)."""
+
+ @pytest.fixture
+ def cpu_with_kernels(self, monkeypatch, int8_compute):
+ monkeypatch.setattr(int8_matmul, "_available", {CPU: True})
+
+ def test_a_half_precision_input_of_the_right_width_qualifies(self, cpu_with_kernels):
+ assert int8_matmul.can_use_int8_matmul(torch.randn(3, 512, dtype=torch.bfloat16), 512)
+
+ @pytest.mark.parametrize("case", ["autocast", "requires-grad", "wrong-width", "strided-columns", "empty"])
+ def test_inputs_the_kernels_cannot_take_fall_back(self, cpu_with_kernels, case):
+ x = torch.randn(3, 512, dtype=torch.bfloat16)
+ if case == "requires-grad":
+ x.requires_grad_(True)
+ elif case == "wrong-width":
+ x = torch.randn(3, 640, dtype=torch.bfloat16)
+ elif case == "strided-columns":
+ x = torch.randn(512, 3, dtype=torch.bfloat16).t()
+ elif case == "empty":
+ x = x[:0]
+
+ if case == "autocast":
+ with torch.autocast("cpu", dtype=torch.bfloat16):
+ assert not int8_matmul.can_use_int8_matmul(x, 512)
+ else:
+ assert not int8_matmul.can_use_int8_matmul(x, 512)
+
+ @pytest.mark.parametrize(
+ "case, eligible",
+ [("rotated", True), ("unrotated", False), ("group-64", False), ("full-precision", False)],
+ )
+ def test_only_rotated_layers_in_groups_of_256_take_the_kernels(self, cpu_with_kernels, case, eligible):
+ layer = _layer(convrot=case != "unrotated", group=64 if case == "group-64" else GROUP)
+ layer.full_precision_matmul = case == "full-precision"
+
+ assert layer._can_use_int8_matmul(torch.randn(3, 512, dtype=torch.bfloat16)) is eligible
+
+
+class TestTheFailurePolicy:
+ def test_the_kernels_result_is_returned_in_the_inputs_shape(self, fake_kernels, caplog):
+ torch.manual_seed(1)
+ layer = _layer()
+ x = torch.randn(2, 7, 512)
+
+ out = layer(x)
+
+ assert fake_kernels.calls == [14] and _served_by_the_kernels(caplog)
+ torch.testing.assert_close(out, _dequantized(layer, x) + MARK)
+
+ def test_rows_are_processed_in_chunks_of_twice_the_output_width(self, fake_kernels, caplog):
+ """Bounds the int8 activation copy by the dequantized path's weight-sized transient."""
+ torch.manual_seed(2)
+ layer = _layer(out_features=16)
+ x = torch.randn(77, 512)
+
+ out = layer(x)
+
+ assert fake_kernels.calls == [32, 32, 13] and _served_by_the_kernels(caplog)
+ torch.testing.assert_close(out, _dequantized(layer, x) + MARK)
+
+ @pytest.mark.parametrize("reference", ["nan", "zero"])
+ def test_a_reference_that_says_nothing_leaves_the_key_for_a_later_call(self, fake_kernels, caplog, reference):
+ """A non-finite reference (NaN input, fp16 overflow) or an all-zero one cannot tell a broken kernel from a
+ working one: neither retire the device nor trust the key yet."""
+ torch.manual_seed(5)
+ layer = _layer(bias=reference == "nan")
+ fallback = CountingFallback(layer)
+ unclear = torch.randn(3, 512) if reference == "nan" else torch.zeros(3, 512)
+ if reference == "nan":
+ unclear[1, 7] = float("nan")
+ clear = torch.randn(3, 512)
+
+ validations, outputs = [], []
+ for x in (unclear, clear, clear):
+ before = len(fallback.rows)
+ outputs.append(_int8_linear(layer, x, fallback))
+ validations.append(len(fallback.rows) - before)
+
+ assert validations == [1, 1, 0], "the clear call validated the key"
+ assert _served_by_the_kernels(caplog)
+ if reference == "nan":
+ assert outputs[0][1].isnan().all()
+ else:
+ assert torch.equal(outputs[0], torch.full_like(outputs[0], MARK)), "the kernels' output stands"
+
+ def test_each_autotune_key_is_validated_once_on_its_last_rows(self, fake_kernels):
+ torch.manual_seed(3)
+ with_bias, without_bias = _layer(), _layer(bias=False)
+ fallbacks = {layer: CountingFallback(layer) for layer in (with_bias, without_bias)}
+ x = torch.randn(300, 512)
+
+ validations = []
+ for layer, rows in [(with_bias, x)] * 3 + [(with_bias, x[:3]), (without_bias, x), (without_bias, x)]:
+ before = len(fallbacks[layer].rows)
+ _int8_linear(layer, rows, fallbacks[layer])
+ validations.append(len(fallbacks[layer].rows) - before)
+
+ assert validations == [1, 0, 0, 1, 1, 0], "once per row bucket and bias"
+ assert torch.equal(fallbacks[with_bias].rows[0], x[-int8_matmul._FIRST_CALL_ROWS :])
+
+ def test_running_out_of_memory_propagates_without_retiring(self, fake_kernels):
+ """By the memory bound, the dequantized fallback would not fit either."""
+ fake_kernels.error = torch.OutOfMemoryError("CUDA out of memory. Tried to allocate 1.50 GiB")
+ layer = _layer()
+
+ with pytest.raises(torch.OutOfMemoryError):
+ layer(torch.randn(3, 512))
+ assert not int8_matmul._health.is_retired(CPU)
+
+ def test_triton_cache_failures_fall_back_and_only_a_streak_retires(self, fake_kernels, caplog):
+ caplog.set_level(logging.WARNING, logger=int8_matmul.__name__)
+ layer = _layer()
+ x = torch.randn(3, 512)
+ fake_kernels.error = PermissionError("[WinError 5] Access is denied")
+
+ outputs = [layer(x) for _ in range(MAX_CACHE_FAILURES - 1)]
+ assert not caplog.records and not int8_matmul._health.is_retired(CPU)
+
+ outputs.append(layer(x))
+ layer(x)
+
+ assert all(torch.equal(out, _dequantized(layer, x)) for out in outputs)
+ assert len(fake_kernels.calls) == MAX_CACHE_FAILURES, "the retired device was not tried again"
+ assert len(caplog.records) == 1
+
+ @pytest.mark.parametrize("broken", ["raises", "wrong-first-result", "nan-first-result", "inf-first-result"])
+ def test_a_broken_kernel_retires_the_device_with_one_warning(self, fake_kernels, caplog, broken):
+ """The reference is finite in every case; a non-finite kernel output is a broken kernel, not an unclear one."""
+ caplog.set_level(logging.WARNING, logger=int8_matmul.__name__)
+ fill = {"wrong-first-result": 0.0, "nan-first-result": float("nan"), "inf-first-result": float("inf")}
+ if broken == "raises":
+ fake_kernels.error = RuntimeError("Triton Error [CUDA]: invalid argument")
+ else:
+ fake_kernels.result = lambda rows: torch.full((rows.shape[0], 384), fill[broken])
+ layer = _layer()
+ x = torch.randn(3, 512)
+
+ outputs = [layer(x), layer(x)]
+
+ assert all(torch.equal(out, _dequantized(layer, x)) for out in outputs)
+ assert len(fake_kernels.calls) == 1
+ assert len(caplog.records) == 1 and "384x512" in caplog.records[0].message
+
+ def test_a_failing_dequantized_path_is_not_blamed_on_int8_compute(self, fake_kernels, monkeypatch):
+ events = []
+ monkeypatch.setattr(int8_matmul, "_synchronize", lambda device: events.append("synchronize"))
+ layer = _layer()
+ fallback = CountingFallback(layer)
+ fallback.error = ValueError("the dequantized path failed")
+
+ with pytest.raises(ValueError, match="dequantized path failed"):
+ _int8_linear(layer, torch.randn(3, 512), fallback)
+ assert events == ["synchronize"], "the kernels were waited for before the reference ran"
+ assert not int8_matmul._health.is_retired(CPU)
+
+ def test_a_kernel_fault_surfacing_asynchronously_retires_the_device_and_falls_back(
+ self, fake_kernels, monkeypatch, caplog
+ ):
+ """Triton launches return before the kernel runs; a fault shows up at the next synchronization, which on a key's
+ first call is the one before the reference -- it must count as the kernel's, not escape the generation."""
+
+ def faulted(device):
+ raise RuntimeError("CUDA error: an illegal memory access was encountered")
+
+ monkeypatch.setattr(int8_matmul, "_synchronize", faulted)
+ layer = _layer()
+ x = torch.randn(3, 512)
+
+ outputs = [layer(x), layer(x)]
+
+ assert all(torch.equal(out, _dequantized(layer, x)) for out in outputs)
+ assert len(fake_kernels.calls) == 1 and int8_matmul._health.is_retired(CPU)
+ assert len(caplog.records) == 1 and "illegal memory access" in caplog.records[0].message
+
+ def test_only_calls_with_a_key_to_validate_wait_for_the_kernels(self, fake_kernels, monkeypatch):
+ synchronized = []
+ monkeypatch.setattr(int8_matmul, "_synchronize", synchronized.append)
+ layer = _layer()
+ x = torch.randn(3, 512)
+
+ layer(x)
+ layer(x)
+
+ assert synchronized == [CPU], "validated calls stay asynchronous"
+
+ def test_the_failed_output_is_released_before_the_fallback_allocates(self, fake_kernels):
+ """Kept validation rows and chunk views must not hold the kernels' output buffer through the fallback."""
+ torch.manual_seed(6)
+ layer = _layer(out_features=16)
+ buffers = []
+
+ def second_chunk_fails(rows, weight, weight_scale, bias, out, m_bucket):
+ buffers.append(weakref.ref(out._base))
+ if len(buffers) == 2:
+ raise RuntimeError("Triton Error [CUDA]: invalid argument")
+
+ fake_kernels.w8a8_rows = second_chunk_fails
+ released = []
+
+ def fallback(x):
+ released.append(all(buffer() is None for buffer in buffers))
+ return _dequantized(layer, x)
+
+ _int8_linear(layer, torch.randn(77, 512), fallback)
+
+ assert released == [True]
+
+
+class TestTheModelCacheWrapper:
+ def test_it_reaches_the_kernels_with_and_without_a_lora_sidecar(self, fake_kernels, caplog):
+ torch.manual_seed(4)
+ model = torch.nn.Module()
+ model.add_module("proj", _layer())
+ apply_custom_layers_to_model(model)
+ down, up = torch.randn(4, 512) * 0.1, torch.randn(384, 4) * 0.1
+ patch = ModelPatchRaw(
+ layers={"lora_transformer-proj": LoRALayer(up=up, mid=None, down=down, alpha=None, bias=None)}
+ )
+ x = torch.randn(5, 512)
+
+ plain = model.proj(x)
+ with LayerPatcher.apply_smart_model_patches(
+ model=model, patches=[(patch, 0.5)], prefix="lora_transformer-", dtype=torch.float32,
+ force_sidecar_patching=True,
+ ): # fmt: skip
+ patched = model.proj(x)
+
+ assert fake_kernels.calls == [5, 5] and _served_by_the_kernels(caplog)
+ torch.testing.assert_close(plain, _dequantized(model.proj, x) + MARK)
+ torch.testing.assert_close(patched, plain + 0.5 * F.linear(F.linear(x, down), up))
+
+
+def test_layers_the_kernels_do_not_cover_are_counted_at_load(caplog, int8_compute):
+ """Comfy's quantized-layer config carries `full_precision_matrix_mult` for every format: a marked int8 layer keeps
+ dequantizing, and so does an unrotated one; a model that gains little from the setting says why."""
+ torch.manual_seed(0)
+ model = torch.nn.Sequential(*(torch.nn.Linear(512, 64) for _ in range(3)))
+ sd = {}
+ for index in ("0", "1", "2"):
+ sd[f"{index}.weight"], sd[f"{index}.weight_scale"] = _quantize(torch.randn(64, 512), convrot=index != "2")
+ sd[f"{index}.bias"] = torch.zeros(64)
+ markers = {
+ "0": {"format": "int8_tensorwise", "convrot": True, "convrot_groupsize": GROUP},
+ "1": {"format": "int8_tensorwise", "convrot": True, "full_precision_matrix_mult": True},
+ "2": {"format": "int8_tensorwise", "convrot": False},
+ }
+ caplog.set_level(logging.INFO, logger="invokeai.backend.quantization.int8_convrot")
+
+ swap_in_int8_linears(model, sd, markers)
+
+ assert [layer.int8_matmul_eligible for layer in model] == [True, False, False]
+ messages = [r.message for r in caplog.records if "int8_compute" in r.message]
+ assert len(messages) == 1 and "2 of 3" in messages[0] and "1 marked full_precision_matrix_mult" in messages[0]
+
+
+def _cuda_unavailable_reason() -> str | None:
+ if not torch.cuda.is_available() or torch.version.hip is not None:
+ return "needs an NVIDIA GPU"
+ if torch.cuda.get_device_capability(0) < (8, 0):
+ return "needs compute capability 8.0 or newer"
+ try:
+ import triton # noqa: F401
+ except ImportError:
+ return "needs Triton"
+ return None
+
+
+def _gemm_configs() -> list:
+ """The autotuner's tiles, where the kernels module can be imported at all."""
+ if _cuda_unavailable_reason() is not None:
+ return []
+ from invokeai.backend.quantization.int8_matmul_kernels import gemm_configs
+
+ return gemm_configs()
+
+
+def _tile_id(tile) -> str:
+ meta = tile.kwargs
+ return f"{meta['BM']}x{meta['BN']}x{meta['BK']}-s{tile.num_stages}-w{tile.num_warps}"
+
+
+def _w8a8_reference(x: torch.Tensor, layer: Int8ConvrotLinear) -> torch.Tensor:
+ """W8A8 in plain torch and float64: rotation, round half up per token, an exact integer GEMM (float64 holds every
+ int8 dot product of these widths exactly), then the scales and bias."""
+ k = x.shape[-1]
+ rows = x.reshape(-1, k).double()
+ rotation = build_regular_hadamard(GROUP, torch.float64).to(x.device)
+ rows = (rows.view(-1, k // GROUP, GROUP) @ rotation).view(-1, k)
+ amax = rows.abs().amax(dim=1).clamp_min(1e-12)
+ q = torch.floor(rows * (127.0 / amax)[:, None] + 0.5).clamp(-127, 127)
+ out = (q @ layer.weight.to(x.device).double().t()) * (amax / 127.0)[:, None]
+ out = out * layer.weight_scale.to(x.device).double().reshape(1, -1)
+ if layer.bias is not None:
+ out = out + layer.bias.to(x.device).double()
+ return out.reshape(*x.shape[:-1], -1)
+
+
+def _relative(actual: torch.Tensor, expected: torch.Tensor) -> float:
+ return ((actual.double() - expected.double()).norm() / expected.double().norm()).item()
+
+
[email protected](_cuda_unavailable_reason() is not None, reason=str(_cuda_unavailable_reason()))
+class TestOnNvidiaGpu:
+ DEVICE = torch.device("cuda:0")
+
+ @pytest.fixture
+ def kernel_calls(self, monkeypatch, int8_compute):
+ """Counts the calls that reached the real kernels."""
+ import invokeai.backend.quantization.int8_matmul_kernels as kernels
+
+ calls = []
+ real = kernels.w8a8_rows
+
+ def counting(rows, *args, **kwargs):
+ calls.append(rows.shape)
+ return real(rows, *args, **kwargs)
+
+ monkeypatch.setattr(kernels, "w8a8_rows", counting)
+ return calls
+
+ def _on_gpu(self, layer: Int8ConvrotLinear) -> Int8ConvrotLinear:
+ return layer.to(self.DEVICE)
+
+ def _x(self, *shape: int, dtype: torch.dtype = torch.bfloat16) -> torch.Tensor:
+ return torch.randn(*shape, device=self.DEVICE, dtype=dtype)
+
+ @pytest.mark.parametrize("dtype", [torch.bfloat16, torch.float16], ids=["bf16", "fp16"])
+ @pytest.mark.parametrize("tokens", [1, 3, 77, 4097])
+ def test_rotated_layers_match_the_w8a8_reference(self, kernel_calls, tokens, dtype):
+ torch.manual_seed(tokens)
+ layer = self._on_gpu(_layer())
+ x = self._x(tokens, 512, dtype=dtype)
+
+ out = layer(x)
+
+ assert kernel_calls and out.dtype == dtype and out.shape == (tokens, 384)
+ # Only the final rounding to the compute dtype (and a rare activation code one step off, where the rotation
+ # sums in another order) separates the kernels from the reference.
+ assert _relative(out, _w8a8_reference(x, layer)) < 2e-3
+
+ @pytest.mark.parametrize("tile", _gemm_configs(), ids=_tile_id)
+ def test_every_tile_the_autotuner_can_pick_computes_the_same_product(self, int8_compute, tile):
+ """The autotuner only ever runs its winner; any of these can win on another GPU or shape. M, N and K are all
+ partial tiles of every config."""
+ import invokeai.backend.quantization.int8_matmul_kernels as kernels
+
+ torch.manual_seed(5)
+ layer = self._on_gpu(_layer(out_features=300, in_features=1024))
+ x = self._x(77, 1024)
+ q, q_scale = kernels.quantize_activations(x)
+ out = torch.empty(77, 300, device=self.DEVICE, dtype=torch.bfloat16)
+
+ kernels.launch_gemm(
+ kernels._int8_gemm_kernel, q, q_scale, layer.weight, layer.weight_scale, layer.bias, out, 128,
+ **tile.all_kwargs(),
+ ) # fmt: skip
+
+ assert _relative(out, _w8a8_reference(x, layer)) < 2e-3
+
+ @pytest.mark.parametrize("layout", ["column", "vector", "scalar"])
+ def test_every_accepted_scale_layout_scales_the_output_channels(self, kernel_calls, layout):
+ torch.manual_seed(1)
+ layer = _layer()
+ scale = {"column": layer.weight_scale, "vector": layer.weight_scale[:, 0], "scalar": layer.weight_scale.max()}
+ layer.weight_scale = scale[layout].clone()
+ layer = self._on_gpu(layer)
+ x = self._x(77, 512)
+
+ out = layer(x)
+
+ assert kernel_calls
+ assert _relative(out, _w8a8_reference(x, layer)) < 2e-3
+
+ def test_the_result_stays_close_to_the_dense_weight(self, kernel_calls):
+ """W8A8 measures ~0.8 % here, the dequantized path ~0.3 %. A bound well above both still catches a lost
+ scale, rotation or bias."""
+ torch.manual_seed(2)
+ dense = torch.randn(384, 512) * 0.05
+ q, scale = _quantize(dense, convrot=True)
+ layer = self._on_gpu(Int8ConvrotLinear(q, scale, convrot=True))
+ x = self._x(4097, 512)
+
+ error = _relative(layer(x), F.linear(x.double(), dense.to(self.DEVICE).double()))
+
+ assert kernel_calls and error < 0.03
+
+ def test_rows_strided_in_memory_quantize_like_contiguous_ones(self, kernel_calls):
+ """The FluxControl sidecar path slices `x[..., :in_features]` out of a wider input."""
+ torch.manual_seed(6)
+ layer = self._on_gpu(_layer())
+ wide = self._x(2, 77, 640)
+
+ assert torch.equal(layer(wide[..., :512]), layer(wide[..., :512].contiguous()))
+ assert len(kernel_calls) == 2
+
+ def test_a_layer_streamed_from_ram_gets_the_resident_result(self, kernel_calls):
+ """Partial loading changes where the int8 weight lives, not what the layer computes."""
+ torch.manual_seed(7)
+ layer = self._on_gpu(_layer())
+ x = self._x(77, 512)
+ resident = layer(x)
+ layer.weight, layer.weight_scale = layer.weight.cpu(), layer.weight_scale.cpu()
+
+ streamed = layer(x)
+
+ assert len(kernel_calls) == 2 and torch.equal(streamed, resident)
+
+ def test_a_nan_input_row_comes_out_nan_as_on_the_dequantized_path(self, kernel_calls):
+ torch.manual_seed(8)
+ layer = self._on_gpu(_layer())
+ x = self._x(9, 512)
+ clean = layer(x)
+ x[4, 100] = float("nan")
+
+ out = layer(x)
+
+ assert out[4].isnan().all() and _dequantized(layer, x)[4].isnan().all()
+ assert torch.equal(out[torch.arange(9) != 4], clean[torch.arange(9) != 4])
+
+ @pytest.mark.parametrize("streamed", [False, True], ids=["resident", "streamed"])
+ def test_the_kernels_stay_within_the_dequantized_paths_memory(self, kernel_calls, streamed):
+ """M far above 2·N, so the output's rows are produced in several chunks."""
+ torch.manual_seed(9)
+ layer = self._on_gpu(_layer(out_features=256))
+ x = self._x(4097, 512)
+ layer(x) # tunes and validates every key first
+ if streamed:
+ layer.weight, layer.weight_scale = layer.weight.cpu(), layer.weight_scale.cpu()
+ output_bytes = 4097 * 256 * x.element_size()
+ torch.cuda.synchronize()
+ torch.cuda.reset_peak_memory_stats(self.DEVICE)
+ baseline = torch.cuda.memory_allocated(self.DEVICE)
+
+ out = layer(x)
+
+ transient = torch.cuda.max_memory_allocated(self.DEVICE) - baseline - output_bytes
+ assert out.shape == (4097, 256) and len(kernel_calls) > 2
+ assert transient <= layer.dequant_transient_bytes(x.dtype)
+
+ def test_the_cache_wrapper_with_a_lora_sidecar_runs_the_kernels_and_adds_the_residual(self, kernel_calls):
+ torch.manual_seed(3)
+ model = torch.nn.Module()
+ model.add_module("proj", self._on_gpu(_layer()))
+ apply_custom_layers_to_model(model)
+ down, up = torch.randn(4, 512) * 0.1, torch.randn(384, 4) * 0.1
+ patch = ModelPatchRaw(
+ layers={"lora_transformer-proj": LoRALayer(up=up, mid=None, down=down, alpha=None, bias=None)}
+ )
+ x = self._x(77, 512)
+
+ with LayerPatcher.apply_smart_model_patches(
+ model=model, patches=[(patch, 0.75)], prefix="lora_transformer-", dtype=torch.bfloat16,
+ force_sidecar_patching=True,
+ ): # fmt: skip
+ out = model.proj(x)
+
+ residual = 0.75 * F.linear(F.linear(x.double(), down.to(self.DEVICE).double()), up.to(self.DEVICE).double())
+ assert len(kernel_calls) == 1
+ assert _relative(out, _w8a8_reference(x, model.proj) + residual) < 3e-3
+
+ @pytest.mark.parametrize("case", ["unrotated", "group-64", "full-precision", "fp32-input"])
+ def test_layers_the_kernels_do_not_cover_compute_exactly_what_they_did(self, kernel_calls, case):
+ torch.manual_seed(4)
+ layer = self._on_gpu(_layer(convrot=case != "unrotated", group=64 if case == "group-64" else GROUP))
+ layer.full_precision_matmul = case == "full-precision"
+ x = self._x(77, 512, dtype=torch.float32 if case == "fp32-input" else torch.bfloat16)
+
+ assert torch.equal(layer(x), _dequantized(layer, x))
+ assert not kernel_calls
+
+ def test_without_triton_the_layer_falls_back_and_says_why_once(self, monkeypatch, int8_compute, caplog):
+ monkeypatch.setitem(sys.modules, "triton", None)
+ monkeypatch.delitem(sys.modules, int8_matmul._KERNELS_MODULE, raising=False)
+ int8_matmul._load_kernels.cache_clear()
+ caplog.set_level(logging.INFO, logger=int8_matmul.__name__)
+ layer = self._on_gpu(_layer())
+ x = self._x(77, 512)
+ try:
+ outputs = [layer(x), layer(x)]
+ finally:
+ int8_matmul._load_kernels.cache_clear()
+
+ assert all(torch.equal(out, _dequantized(layer, x)) for out in outputs)
+ warnings = [r.message for r in caplog.records if r.levelno == logging.WARNING]
+ assert len(warnings) == 1 and "triton-windows" in warnings[0]
+
+ def test_a_kernel_error_on_the_gpu_retires_it_and_falls_back(self, monkeypatch, int8_compute, caplog):
+ import invokeai.backend.quantization.int8_matmul_kernels as kernels
+
+ def broken_gemm(*args, **kwargs):
+ raise RuntimeError("Triton Error [CUDA]: invalid argument")
+
+ monkeypatch.setattr(kernels, "launch_gemm", broken_gemm)
+ caplog.set_level(logging.WARNING, logger=int8_matmul.__name__)
+ layer = self._on_gpu(_layer())
+ x = self._x(77, 512)
+
+ assert torch.equal(layer(x), _dequantized(layer, x))
+ assert int8_matmul._health.is_retired(self.DEVICE)
+ assert len([r for r in caplog.records if "cuda:0" in r.message]) == 1
diff --git a/tests/backend/util/test_sage_attention.py b/tests/backend/util/test_sage_attention.py
index ca1ae56a50..3aef9f35c2 100644
--- a/tests/backend/util/test_sage_attention.py
+++ b/tests/backend/util/test_sage_attention.py
@@ -14,7 +14,6 @@ import functools
import importlib.util
import logging
import threading
-from collections import Counter
from importlib.metadata import PackageNotFoundError
from pathlib import Path
from types import SimpleNamespace
@@ -25,6 +24,7 @@ import torch.nn.functional as F
import invokeai.backend.util.sage_attention as sage
from invokeai.backend.util.sage_attention import install_sage_attention, sage_attention_scope
+from invokeai.backend.util.triton_kernels import MAX_CACHE_FAILURES, TritonKernelHealth
# torch's own function, captured before any test installs the wrapper.
TORCH_SDPA = F.scaled_dot_product_attention
@@ -118,14 +118,18 @@ def _cuda_build(
monkeypatch.setattr(torch.cuda, "get_device_name", lambda index=None: "Fake GPU")
monkeypatch.setattr(sage, "_import_sageattention", lambda: (VERSION, module))
monkeypatch.setattr(sage, "_cuda_index", lambda q, k, v: 0)
- monkeypatch.setattr(sage, "_disabled_devices", set())
- monkeypatch.setattr(sage, "_validated", _all_variants(capabilities))
- monkeypatch.setattr(sage, "_cache_failures", Counter())
- monkeypatch.setattr(sage, "_announced_devices", set())
+ monkeypatch.setattr(sage, "_health", _health_with_validated(_all_variants(capabilities)))
monkeypatch.setattr(torch.cuda, "device", lambda index: contextlib.nullcontext())
return module, torch_calls
+def _health_with_validated(variants) -> TritonKernelHealth:
+ health = TritonKernelHealth()
+ for variant in variants:
+ health.mark_validated(variant)
+ return health
+
+
def _all_variants(devices) -> set:
"""Every kernel variant of these devices, as if each had passed its first-call check."""
return {
@@ -312,7 +316,7 @@ class TestRouting:
class TestFirstCallCheck:
def test_a_devices_first_result_is_compared_with_torch_once(self, monkeypatch):
module, torch_calls = _cuda_build(monkeypatch, {0: (8, 9)})
- monkeypatch.setattr(sage, "_validated", set())
+ monkeypatch.setattr(sage, "_health", TritonKernelHealth())
install_sage_attention()
q, k = _q(1, 2, QUERY_LEN, 64), _q(1, 2, KEY_LEN, 64)
@@ -326,7 +330,7 @@ class TestFirstCallCheck:
def test_the_check_pairs_a_gqa_query_group_with_its_own_kv_head(self, monkeypatch):
"""Query heads 0-3 attend to K/V head 0; comparing them with head 1 instead would retire a correct kernel."""
module, torch_calls = _cuda_build(monkeypatch, {0: (8, 9)})
- monkeypatch.setattr(sage, "_validated", set())
+ monkeypatch.setattr(sage, "_health", TritonKernelHealth())
install_sage_attention()
q, k, v = _q(1, 8, QUERY_LEN, 64), _q(1, 2, KEY_LEN, 64), _q(1, 2, KEY_LEN, 64)
v[:, 1] += 3.0 # a K/V head unlike head 0, so a wrong pairing cannot pass
@@ -341,7 +345,7 @@ class TestFirstCallCheck:
def test_each_precision_and_head_size_is_checked_on_its_first_call(self, monkeypatch):
"""They select different compiled kernels; one passing says nothing about the others."""
module, torch_calls = _cuda_build(monkeypatch, {0: (8, 9)})
- monkeypatch.setattr(sage, "_validated", set())
+ monkeypatch.setattr(sage, "_health", TritonKernelHealth())
install_sage_attention()
hd64, hd128 = _q(1, 2, QUERY_LEN, 64), _q(1, 2, QUERY_LEN, 128)
bf16 = _q(1, 2, QUERY_LEN, 64, dtype=torch.bfloat16)
@@ -357,7 +361,7 @@ class TestFirstCallCheck:
def test_a_wrong_first_result_retires_the_device_and_returns_torchs(self, monkeypatch, caplog, garbage):
"""A kernel the build lacks for this GPU returns uninitialized memory instead of raising."""
module, torch_calls = _cuda_build(monkeypatch, {0: (8, 9)})
- monkeypatch.setattr(sage, "_validated", set())
+ monkeypatch.setattr(sage, "_health", TritonKernelHealth())
install_sage_attention()
q, k = _q(1, 2, QUERY_LEN, 64), _q(1, 2, KEY_LEN, 64)
module.result = torch.full((1, 2, QUERY_LEN, 64), garbage, dtype=torch.float16)
@@ -453,16 +457,16 @@ class TestFailures:
with sage_attention_scope():
F.scaled_dot_product_attention(q, k, k)
- for error in [PermissionError("denied")] * (sage._MAX_CACHE_FAILURES - 1) + [None]:
+ for error in [PermissionError("denied")] * (MAX_CACHE_FAILURES - 1) + [None]:
call(error)
- for _ in range(sage._MAX_CACHE_FAILURES - 1):
+ for _ in range(MAX_CACHE_FAILURES - 1):
call(PermissionError("denied"))
- assert not caplog.records and 0 not in sage._disabled_devices, "the success in between reset the count"
+ assert not caplog.records and not sage._health.is_retired(0), "the success in between reset the count"
call(PermissionError("denied"))
call(None)
- assert 0 in sage._disabled_devices
- assert len(module.calls) == 2 * sage._MAX_CACHE_FAILURES, "the last call no longer reached the kernel"
+ assert sage._health.is_retired(0)
+ assert len(module.calls) == 2 * MAX_CACHE_FAILURES, "the last call no longer reached the kernel"
assert any("cuda:0" in r.message for r in caplog.records if r.levelno == logging.WARNING)
def test_the_scope_closes_when_its_block_raises(self, installed):
@@ -697,10 +701,7 @@ class TestOnNvidiaHardware:
pick = sage._kernel
monkeypatch.setattr(sage, "_kernel", lambda module, _capability, cuda: pick(module, (8, 6), cuda))
monkeypatch.setattr(F, "scaled_dot_product_attention", TORCH_SDPA)
- monkeypatch.setattr(sage, "_disabled_devices", set())
- monkeypatch.setattr(sage, "_validated", set())
- monkeypatch.setattr(sage, "_cache_failures", Counter())
- monkeypatch.setattr(sage, "_announced_devices", set())
+ monkeypatch.setattr(sage, "_health", TritonKernelHealth())
install_sage_attention()
if not getattr(F.scaled_dot_product_attention, sage._SENTINEL, False):
pytest.skip("the installed sageattention is not one InvokeAI uses (see the startup warning)")
diff --git a/tests/backend/util/test_triton_kernels.py b/tests/backend/util/test_triton_kernels.py
new file mode 100644
index 0000000000..490a6b4853
--- /dev/null
+++ b/tests/backend/util/test_triton_kernels.py
@@ -0,0 +1,59 @@
+"""Failure policy shared by the optional Triton-backed kernels (`backend.util.triton_kernels`).
+
+SageAttention's and int8 compute's own tests cover how each caller reacts; these pin the bookkeeping both rely on.
+"""
+
+import math
+
+import pytest
+import torch
+
+from invokeai.backend.util.triton_kernels import (
+ MAX_CACHE_FAILURES,
+ FailureOutcome,
+ TritonKernelHealth,
+ relative_error,
+)
+
+CACHE_ERROR = PermissionError("[WinError 5] Access is denied: 'triton\\cache\\tmp.pid_123'")
+
+
+class TestCacheFailures:
+ def test_only_failures_in_a_row_retire_the_device(self):
+ health = TritonKernelHealth()
+ for _ in range(MAX_CACHE_FAILURES - 1):
+ assert health.record_failure(0, CACHE_ERROR) is FailureOutcome.TRANSIENT
+ health.record_success(0)
+ for _ in range(MAX_CACHE_FAILURES - 1):
+ assert health.record_failure(0, CACHE_ERROR) is FailureOutcome.TRANSIENT
+ assert not health.is_retired(0), "the success in between ended the streak"
+
+ assert health.record_failure(0, CACHE_ERROR) is FailureOutcome.RETIRED
+ assert health.is_retired(0)
+
+ def test_streaks_are_counted_per_device(self):
+ health = TritonKernelHealth()
+ for device in [0, 1] * (MAX_CACHE_FAILURES - 1):
+ health.record_failure(device, CACHE_ERROR)
+ assert not health.is_retired(0) and not health.is_retired(1)
+
+
+class TestKernelErrors:
+ def test_any_other_error_retires_the_device_at_once_and_is_reported_once(self):
+ health = TritonKernelHealth()
+ assert health.record_failure(0, RuntimeError("no kernel image")) is FailureOutcome.RETIRED
+ assert health.record_failure(0, RuntimeError("no kernel image")) is FailureOutcome.ALREADY_RETIRED
+ assert health.record_failure(0, CACHE_ERROR) is FailureOutcome.ALREADY_RETIRED
+ assert health.is_retired(0) and not health.is_retired(1)
+
+
+def test_first_use_is_reported_once_per_device():
+ health = TritonKernelHealth()
+ assert [health.first_use(device) for device in (0, 0, 1, 0)] == [True, False, True, False]
+
+
+def test_relative_error_separates_a_close_result_from_a_broken_one():
+ expected = torch.randn(64, 32)
+ assert relative_error(expected * 1.01, expected) == pytest.approx(0.01, rel=1e-4)
+ assert relative_error(torch.zeros_like(expected), expected) == pytest.approx(1.0, rel=1e-4)
+ assert math.isnan(relative_error(torch.full_like(expected, math.nan), expected))
diff --git a/tests/test_imports.py b/tests/test_imports.py
index 91288d8824..442cfe6d61 100644
--- a/tests/test_imports.py
+++ b/tests/test_imports.py
@@ -1,4 +1,5 @@
import importlib
+import importlib.util
import pkgutil
import subprocess
import sys
@@ -29,6 +30,10 @@ if is_windows_arm64():
# mediapipe has no Windows ARM64 build; this module is imported lazily by the face nodes. Everywhere
# else mediapipe is installed, so this module failing to import is a real regression.
KNOWN_IMPORT_ERRORS.add("invokeai.backend.image_util.mediapipe_face.mediapipe_face_common")
+if importlib.util.find_spec("triton") is None:
+ # The int8 compute kernels import Triton at the top and are loaded lazily, only where Triton is installed (not on
+ # macOS). Where it is installed, this module failing to import is a real regression.
+ KNOWN_IMPORT_ERRORS.add("invokeai.backend.quantization.int8_matmul_kernels")
def test_invokeai_imports():