Skip to content

Low-bits Quantization

Overview

Quantization is a powerful technique to reduce the memory footprint and computational cost of deep learning models by representing weights and activations with lower precision data types. Cache-DiT supports various quantization methods, including FP8, INT8, INT4, NVFP4 and MXFP4 quantization, to help users achieve faster inference and lower memory usage while maintaining acceptable model performance.

Quantization Types Description Devices
float8_per_row quantize weights and activations to float8 (dynamic quantization) with rowwise method. (recommended) TorchAO: >=sm89; cache-dit: >=sm100
float8_per_tensor quantize weights and activations to float8 (dynamic quantization) with tensorwise method. TorchAO: >=sm89; cache-dit: >=sm100
float8_per_block block-wise quantization weights and activations (dynamic quantization) to float8, which can provide better precision, activations's blocksize: (1, 128), weight's blocksize: (128, 128) TorchAO: >=sm89; cache-dit: >=sm100
float8_weight_only quantize only weights to float8, keep activations in full precision >=sm89, Ada, Hopper or newer
int8_per_row quantize weights and activations to int8 (dynamic quantization) with rowwise method. >=sm80, Ampere or newer
int8_per_tensor quantize weights and activations to int8 (dynamic quantization) with tensorwise method. >=sm80, Ampere or newer
int8_weight_only quantize only weights to int8, keep activations in full precision >=sm80, Ampere or newer
int4_weight_only quantize only weights to int4, keep activations in full precision >=sm90, Hopper or newer, TMA required
nvfp4 Dynamic activation and NVFP4 weight quantization. Available through TorchAO or cache-dit's native backend. TorchAO: >=sm100; cache-dit: >=sm120
nvfp4_weight_only TorchAO NVFP4 weight-only quantization with dynamic per-tensor weight scaling; activations remain in their original precision. >=sm100, Blackwell or newer
mxfp4_weight_only cache-dit native MXFP4 (E2M1 payload + one E8M0 scale per group of 32 along K) weight-only quantization; activations stay in the model dtype. Pure PyTorch packing, no _C_ops extension needed. Any CUDA-like backend without NVFP4 tensor cores; also runs on CPU (slow reference path)
svdq_int4_r{32...} post-training SVDQuant (W4A4) with calibration and checkpoint serialization for users who want the higher-accuracy PTQ workflow. >=sm89, Ada or newer, excluded Hopper (NO INT4 MMA; the unified _C_ops floor)
svdq_nvfp4_r{32...} post-training SVDQuant (W4A4) with NVFP4 packed weights/activations, calibration, and checkpoint serialization. Defaults to runtime_kernel="native"; cute is an explicit opt-in validation path. >=sm120, Blackwell or newer
svdq_int4_r{32...}_dq quantize weights and activations to int4 with SVDQuant dynamic quantization (W4A4) without any calibration. Defaults to the native W4A4 GEMM. >=sm89, Ada or newer, excluded Hopper (NO INT4 MMA; the unified _C_ops floor)
svdq_nvfp4_r{32...}_dq quantize weights and activations to NVFP4 with SVDQuant dynamic quantization (W4A4) without any calibration. Defaults to runtime_kernel="native"; cute is an explicit opt-in validation path. >=sm120, Blackwell or newer
svdq_fp8_r{32|64|128}[_dq] SVDQuant-FP8 (W8A8): an E4M3 residual with a fused BF16 low-rank branch for layers that need better accuracy than plain FP8 per-row. Supports DQ/PTQ and checkpoint save/load through serialize_to and cache_dit.load. >=sm120, Blackwell or newer
svdq_w4a8_r{32|64|128}[_dq] SVDQuant W4A8: E4M3 activations plus packed E2M1 residual weights, with the BF16 low-rank branch fused into the same kernel. Halves residual-weight storage versus W8A8 and supports DQ/PTQ/checkpoint; evaluate accuracy on the target model. >=sm120, Blackwell or newer
svdq_fp6_r{32|64|128}[_dq] (alias svdq_w6a6_*) SVDQuant W6A6: packed E2M3 activations and residual weights with one UE8M0 micro-scale per 32 K elements on both sides, consumed by the MX block-scaled mxf8f6f4 MMA. Three mantissa bits keep E4M3-level resolution while weights shrink 25% versus W8A8; FLUX.1-dev at 1024x1024 measures 26.58 dB / 0.950 against bf16 versus 21.54 dB / 0.913 for W8A8 (28 steps, RTX PRO 5000). Supports DQ/PTQ/checkpoint and torch.compile. >=sm120, Blackwell or newer
svdq_w{1|2|3}a4_r{rank}[_dq] SVDQuant packed W1A4/W2A4/W3A4: E2M1 activations with 1/2/3-bit residual-weight storage and W4A4 compute. W1/W2 accept ranks 0/32/64/128/256/512 and default to the three-stage per-4 codec because their two-stage codebooks are not accurate enough; W3's 3-bit codebook is inherently more accurate, so W3 keeps ranks 0/32/64/128 and defaults to the standard two-stage NVFP4 codec, with an optional per-8 one-bit table selector. W2 targets minimum persistent weight memory, W3 trades memory for accuracy, and W1 is an experimental sign-only tier. Supports DQ/PTQ/checkpoint and compile. >=sm120, Blackwell or newer

Command Line

The cache_dit.generate CLI uses --quantize-config; the first bare entry selects the transformer type and a text: component prefix selects the primary text encoder. A vae: component is rejected because VAE quantization is not available:

Option Meaning
--quantize-config "float8_per_row,text:float8_wo" Generic options: a bare or quant_type= transformer type (without it the type is float8_per_row), backend (torchao|cache_dit, omitted = AUTO), regional_quantize, per_tensor_fallback, exclude_layers (+-separated), text:/text_encoder: (a text encoder type, or true to reuse the transformer type), verbose, fp8_fused_mlp, fp4_fused_mlp, mxfp4_quantize_device.
--svdq-config "k=v,k=v" SVDQuant options for an svdq_* type; the keys are the svdq_kwargs fields (smooth_strategy, calibrate_precision, runtime_kernel, lora_layout, few_shot_*, packed_a4_*, ...). Layerwise enable, placement and transfer options belong to --offload-config 'svdq,...'.

Convenience aliases: float8 / fp8 expand to float8_per_row; append torchao or cache_dit to pick the backend (float8,cache_dit, nvfp4,cache_dit); SVDQ,rank=32 expands to svdq_nvfp4_r32_dq on sm120 and svdq_int4_r32_dq otherwise; text:float8_wo is float8_weight_only.

python3 -m cache_dit.generate flux --quantize-config 'float8_per_row' --compile-config 'transformer'
python3 -m cache_dit.generate flux --quantize-config 'svdq_nvfp4_r64_dq' \
  --svdq-config 'smooth_strategy=few_shot' --compile-config 'transformer'
python3 -m cache_dit.generate flux \
  --quantize-config 'float8_per_row,backend=cache_dit,exclude_layers=adaln_proj+norm_out'

Quantization Backends

The three online FP8 types can run on two independent backends:

  • torchao: the historical path, using TorchAO's Float8Tensor. per_row and per_tensor use torch._scaled_mm; per_block uses TorchAO's Triton blockwise GEMM. Requires torchao and works on >=sm89.
  • cache_dit: Cache-DiT's own E4M3 quantize plus a GEMM selected by use_native. It has no torchao runtime dependency, supports the same three granularities, and currently requires sm100 or newer. CUDA Graph-safe; pre-quantized native checkpoints can be tensor-parallelized by densifying and re-quantizing local shards, while online native quantization still does not accept DTensor weights. cache-dit-convert can serialize all three native FP8 granularities into a complete pipeline checkpoint. per_tensor_fallback is a TorchAO/TP compatibility switch and has no effect on this backend. Under torch.compile, activation quantization switches to an equivalent pure-Torch implementation so Inductor can fuse it; eager keeps the custom quantize kernel.

For the cache-dit FP8 backend, fp8_gemm uses the native CUTLASS collective by default for all three modes. use_native=False selects the torch._scaled_mm reference path for per-row and per-tensor; per-block always uses the native blockwise path. Unsupported Linear shapes are handled through automatic padding and output slicing, so users do not need to align layer dimensions manually.

QuantizeConfig(backend=...) defaults to AUTO. AUTO keeps the existing routing: svdq* uses the cache-dit SVDQuant path and every other type uses TorchAO. Passing backend="cache_dit" with float8_per_row, float8_per_tensor, or float8_per_block selects the native FP8 path; unsupported combinations raise instead of silently falling back. The CLI equivalent is --quantize-config backend=torchao|cache_dit.

import cache_dit
from cache_dit import QuantizeConfig

cache_dit.quantize(
  pipe.transformer,
  QuantizeConfig(quant_type="float8_per_row", backend="cache_dit"),
)
python3 -m cache_dit.generate flux --model-path /PATH/TO/FLUX.1-dev \
  --quantize-config quant_type=float8_per_row,backend=cache_dit --compile-config 'transformer'

The native backend keeps the exact TorchAO granularity semantics: float8_per_row means per-token activations and per-output-channel weights (per-col of the mathematical B), float8_per_tensor uses one scale for the whole tensor, and float8_per_block uses activation blocks of (1, 128) and weight blocks of (128, 128) with a rescale after every 128 K elements. The low-level fp8_gemm accepts use_native; leave it enabled for the default CUTLASS path, or disable it to compare per-row/per-tensor against torch._scaled_mm.

Native FP8 Fused MLP

The cache-dit FP8 backend can fuse supported FeedForward structures after online module replacement. Set QuantizeConfig(fp8_fused_mlp=True) or pass --quantize-config fp8_fused_mlp=true together with backend=cache_dit. The option is disabled by default and is rejected for TorchAO, SVDQ, and native NVFP4 configurations.

config = QuantizeConfig(
  quant_type="float8_per_row",
  backend="cache_dit",
  fp8_fused_mlp=True,
)
cache_dit.quantize(pipe.transformer, config)
python3 -m cache_dit.generate flux --model-path /PATH/TO/FLUX.1-dev \
  --quantize-config backend=cache_dit,fp8_fused_mlp=true

Three structural passes are supported: standard diffusers FeedForward blocks with exact or tanh GELU, single-stream proj_mlp -> GELU -> concat blocks such as FLUX, and SwiGLU blocks with either separate value/gate projections or one half-split projection. The logs report the number of targets for each pass; enabling the option on a module with no supported target raises an error.

For GELU, the first FP8 GEMM applies bias and activation in its CUTLASS EVT. The second layer still performs the original dynamic activation quantization: per-row scales require a full-row amax and per-tensor scales require a global amax, so this path deliberately does not claim SVDQ-style local qout or dense-store elimination. For SwiGLU, the next layer's CUDA producer computes value * silu(gate), amax, and E4M3 quantization without materializing a separate gated BF16 tensor. SiLU and multiplication retain their BF16 rounding order under both eager execution and torch.compile.

The fused path supports all three native FP8 granularities, fake tensors, full-graph compile, and CUDA Graph capture. torch._scaled_mm and _scaled_mm_v2 do not expose an activation epilogue; requesting activation with use_native=False therefore raises instead of silently applying a separate kernel. A native FP8 checkpoint can also be served with TP: the weights are dequantized, sharded along the TP axis, re-quantized per rank, and executed with explicit column/row collectives. Pipeline conversion preserves the fused-MLP setting and reapplies its structural passes when the checkpoint is loaded.

FP8 Quantization

Cache-DiT supports online quantization with different quantization types. The default TorchAO backend requires torchao>=0.17.0; the optional cache-dit backend uses the bundled cache_dit._C_ops extension. Users can implement model quantization by calling quantize or pass a QuantizeConfig to enable_cache API. Install torchao before using the default backend.

# stable: torchao (change cu130 to cu129 if using CUDA 12.9)
pip install torchao --index-url https://download.pytorch.org/whl/cu130 --upgrade
# nightly: torchao (change cu130 to cu129 if using CUDA 12.9)
pip install --pre torchao --index-url https://download.pytorch.org/whl/nightly/cu130 --upgrade

For GPUs with low memory capacity, we recommend using float8_per_row or float8_per_block, as these methods cause almost no loss in precision. We also recommend enabling torch.compile for better performance with quantization. Supported quantization types including:

  • float8_per_row: quantize both weights and activations to float8 (dynamic quantization) with rowwise method.
  • float8_per_tensor: quantize both weights and activations to float8 (dynamic quantization) with tensorwise method.
  • float8_per_block: block-wise quantization weights and activations (dynamic quantization) to float8, which can provide better precision, activations's blocksize: (1, 128), weight's blocksize: (128, 128). NOT supported for distributed inference for now.
  • float8_weight_only: quantize only weights to float8, keep activations in full precision.

Here are some examples of how to use quantization with cache-dit. You can directly specify the quantization config in the enable_cache API.

import cache_dit
from cache_dit import DBCacheConfig, ParallelismConfig, QuantizeConfig

# quant_type: float8_per_row, float8_per_tensor, float8_per_block, float8_weight_only, 
# int8_per_row, int8_per_tensor, int8_weight_only, int4_weight_only, etc.
# Pass a QuantizeConfig to the `enable_cache` API.
cache_dit.enable_cache( 
  pipe, cache_config=DBCacheConfig(), # w/ default
  parallelism_config=ParallelismConfig(ulysses_size=2),
  quantize_config=QuantizeConfig(quant_type="float8_per_row"),
)

Users can also specify different quantization configs for different components. For example, quantize the transformer to float8_per_row and the text encoder to float8_weight_only.

import cache_dit
from cache_dit import DBCacheConfig, ParallelismConfig, QuantizeConfig

cache_dit.enable_cache( 
  pipe, cache_config=DBCacheConfig(), # w/ default
  parallelism_config=ParallelismConfig(ulysses_size=2),
  quantize_config=QuantizeConfig(
    components_to_quantize={
      "transformer": {
        "quant_type": "float8_per_row",
        "exclude_layers": ["embedder", "embed"],
      },
      "text_encoder": {
        "quant_type": "float8_weight_only",
        "exclude_layers": ["lm_head"],
      }
    }
  ),
)

Or, directly call the quantize API for more fine-grained control.

import cache_dit
from cache_dit import QuantizeConfig

cache_dit.quantize(
  pipe.transformer, 
  quantize_config=QuantizeConfig(quant_type="float8_per_row"),
)
cache_dit.quantize(
  pipe.text_encoder, 
  quantize_config=QuantizeConfig(quant_type="float8_weight_only"),
)

Please also enable torch.compile for better performance with quantization.

import cache_dit

cache_dit.set_compile_configs()
pipe.transformer = torch.compile(pipe.transformer)
pipe.text_encoder = torch.compile(pipe.text_encoder)

Users can set exclude_layers in QuantizeConfig to exclude some sensitive layers that are not robust to quantization, e.g., embedding layers. Layers that contain any of the keywords in theexclude_layers list will be excluded from quantization. For example:

import cache_dit
from cache_dit import DBCacheConfig, ParallelismConfig, QuantizeConfig

cache_dit.enable_cache( 
  pipe, cache_config=DBCacheConfig(), # w/ default
  parallelism_config=ParallelismConfig(ulysses_size=2),
  quantize_config=QuantizeConfig(
    quant_type="float8_per_row",
    exclude_layers=["embedder", "embed"],
  ),
)
By default, quant_type="float8_per_row" for better precision. Users can set it to "float8_per_tensor" to use per-tensor quantization for better performance on some hardware.

NVFP4 Quantization

Cache-DiT provides an online NVFP4 W4A4 path on SM120 through QuantizeConfig(quant_type="nvfp4", backend="cache_dit"):

import cache_dit
from cache_dit import QuantizeConfig

cache_dit.quantize(
  pipe.transformer,
  QuantizeConfig(quant_type="nvfp4", backend="cache_dit"),
)
python3 -m cache_dit.generate flux --model-path /PATH/TO/FLUX.1-dev \
  --quantize-config quant_type=nvfp4,backend=cache_dit --compile-config 'transformer'

The cache-dit path provides online NVFP4 W4A4 inference: each weight is quantized once, while activations are quantized at runtime. It is intended for SM120 GPUs and supports the FLUX production shapes.

The two implementations do not use the same quantization recipe. Cache-DiT uses a per-row activation and per-output-channel weight FP32 global scale on top of the per-16 UE4M3 block scale. TorchAO uses a dynamic per-tensor global scale and MSLK Triton quantization. Do not use cross-backend output differences as a kernel correctness gate; compare each backend against its own dequantized reference.

Requirements and limits:

  • Both weight and activation must be BF16. Non-aligned Linear shapes are supported through automatic padding and output slicing. For best performance, prefer in_features % 256 == 0 and out_features % 128 == 0, which avoids padding copies.
  • calibrate_fn is not supported. A serialized checkpoint can still be served with TP: the packed weights are dequantized, sharded, and re-quantized per rank. python3 -m cache_dit.convert --quantize-config 'nvfp4,backend=cache_dit' serializes the packed native weights into a complete pipeline checkpoint. The lower-level QuantizeConfig(serialize_to=...) spelling remains SVDQ-only.
  • nvfp4_weight_only continues to use TorchAO, and AUTO still routes plain nvfp4 to TorchAO. Only an explicit backend="cache_dit" selects this path.

Native NVFP4 Fused MLP

Set QuantizeConfig(fp4_fused_mlp=True) or pass --quantize-config fp4_fused_mlp=true with backend=cache_dit to enable structural GELU and SwiGLU fusion after online NVFP4 module replacement. The option is disabled by default and is rejected for TorchAO, SVDQ, and native FP8 configurations.

config = QuantizeConfig(
  quant_type="nvfp4",
  backend="cache_dit",
  fp4_fused_mlp=True,
)
cache_dit.quantize(pipe.transformer, config)
python3 -m cache_dit.generate flux --model-path /PATH/TO/FLUX.1-dev \
  --quantize-config quant_type=nvfp4,backend=cache_dit,fp4_fused_mlp=true --compile-config 'transformer'

The supported structures match native FP8: standard diffusers FeedForward with exact or tanh GELU, single-stream proj_mlp -> GELU -> concat blocks such as FLUX, and SwiGLU with either separate value/gate projections or one half-split projection. Logs report each pass's target count; enabling the option with no supported target raises an error.

For GELU, the first GEMM applies its level-1 scales, bias, and activation in the CUTLASS EVT. The second layer still computes its original row global scale and per-16 block scales, so this path does not claim dense-store elimination. For SwiGLU, the next layer's producer computes value * silu(gate), both scale levels, and E2M1 packing without materializing a separate gated BF16 tensor. The producer retains BF16 SiLU/multiplication rounding under eager execution, full-graph compile, and CUDA Graph capture. torch._scaled_mm has no public activation epilogue, so activation with use_native=False raises explicitly.

MXFP4 Weight-only Quantization

Cache-DiT ships a native MXFP4 (OCP Microscaling: E2M1 payload with one E8M0 biased-exponent scale per group of 32 elements along K) weight-only path. It targets accelerators where torchao's BlockWise-1x32 torch._scaled_mm MX path is unavailable or broken, and where NVFP4's Blackwell-class tensor cores do not exist. Weights are packed once at load time; activations stay in the model dtype and every layer dequantizes its 4-bit payload and calls F.linear, so the runtime cost is one bandwidth-bound dequant pass over the (4x smaller) packed weights. --compile-config 'transformer' fuses that pass into the GEMM and keeps the memory footprint at the packed size.

import cache_dit
from cache_dit import QuantizeConfig

cache_dit.quantize(
  pipe.transformer,
  QuantizeConfig(quant_type="mxfp4_weight_only"),
)
python3 -m cache_dit.generate flux --model-path /PATH/TO/FLUX.1-dev \
  --quantize-config quant_type=mxfp4_weight_only --compile-config 'transformer'

Requirements and limits:

  • Only the MX dtypes shipped by PyTorch >= 2.6 (torch.float4_e2m1fn_x2, torch.float8_e8m0fnu) are required. The _C_ops CUDA extension is not involved, so this path also runs on CPU (slow reference path) and on backends without NVFP4 tensor cores.
  • in_features must be a multiple of mxfp4_block_size (32, the only spec-compliant value). Layers that do not qualify are skipped; a run that packs no layer raises instead of returning an unquantized module.
  • Weight-only: activations are not quantized, so mxfp4_weight_only is the only public MXFP4 type (there is no W4A4 mxfp4 entry, unlike nvfp4); select it with --quantize-config quant_type=mxfp4_weight_only.
  • Online-only: calibrate_fn, serialize_to, precision_plan, TP/DTensor weights and MXFP4 checkpoint loading/serialization are not supported.
  • mxfp4_quantize_device (auto/cpu/cuda, or --quantize-config mxfp4_quantize_device=...) selects where the one-time packing math runs. auto packs on the current accelerator when one is available and falls back to the weight's device; the packed buffers always return to the weight's own device, so quantization never moves a module.
  • MXFP4Linear supports device moves but not dtype casting of the packed payload: .to(dtype)/.half() keep the fp4 payload verbatim and only recast the bias, which drives the dequant output dtype.

Measured cost and quality (FLUX.1-dev, 1024x1024, 28 steps, seed 0, single RTX PRO 5000 72GB, identical initial noise for every run):

Configuration Latency Peak memory PSNR vs bf16 SSIM vs bf16
bf16 eager 16.99 s 33.82 GiB - -
bf16 + --compile-config 'transformer' 14.88 s 33.82 GiB 27.11 (compile floor) 0.9620
mxfp4_weight_only eager 36.39 s 17.75 GiB 16.25 0.7710
mxfp4_weight_only + --compile-config 'transformer' 15.38 s 17.75 GiB 16.01 0.7610

Read the two floors together with the numbers: repeating one configuration is bit-identical (PSNR = inf), while torch.compile alone already moves the bf16 output by 27.11 dB / 0.9620. The 16 dB / 0.77 MXFP4 gap is therefore the 4-bit weight cost, not measurement drift. Weight-only at 4 bits buys a 47% peak-memory cut for a detail-level quality loss (thin high-frequency structures smooth out); it is not a lossless drop-in.

Packing, not inference, is where the device matters: the same 494 FLUX layers take ~7 s from a CPU-resident transformer with mxfp4_quantize_device="auto" versus ~11 min when packing on CPU. Reproduce the operator numbers with python3 -m bench.kernels.bench_mxfp4.

Regional Quantization

Cache-DiT also supports regional quantization, which allows users to quantize only the repeated blocks in a transformer. This can be useful for better balancing the precision and efficiency. Users can specify the blocks to be quantized via the regional_quantize and repeated_blocks arguments in QuantizeConfig. For example, to quantize repeated blocks of the Flux2's transformer:

import cache_dit
from cache_dit import DBCacheConfig, ParallelismConfig, QuantizeConfig

cache_dit.enable_cache( 
  pipe, cache_config=DBCacheConfig(), # w/ default
  parallelism_config=ParallelismConfig(ulysses_size=2),
  quantize_config=QuantizeConfig(
    quant_type="float8_per_row",
    # Default (True), only quantize the repeated blocks in transformer if the repeated_blocks is 
    # specified. If set to False, the whole transformer will be quantized.
    regional_quantize=True, 
    # Specify the block names for the transformer, cache-dit will automatically find the repeated 
    # blocks and quantize it inplace. The block names can be found in the model architecture, e.g., 
    # for FLUX.2, the block name is "Flux2TransformerBlock" and "Flux2SingleTransformerBlock".
    repeated_blocks=['Flux2TransformerBlock', 'Flux2SingleTransformerBlock'],
    # repeated_blocks will be detected automatically from diffusers' transformer class, namely:
    # default repeated_blocks = transformer._repeated_blocks if exists, else None (quantize 
    # the whole transformer.
  ),
)

FP8 Per-Tensor Fallback

The per_tensor_fallback option in Cache-DiT's quantization configuration allows users to enable a fallback mechanism for layers that do not support float8 per-row or per-block quantization. This is particularly useful in scenarios where tensor parallelism is applied, and certain layers (e.g., those applied with RowwiseParallel) may encounter memory layout mismatch errors when quantized to float8 per-row.

When per_tensor_fallback is set to True, if a layer cannot be quantized to float8 per-row or per-block, it will automatically fall back to float8 per-tensor quantization instead of raising an error. This ensures that the quantization process can continue smoothly without interruption, while still providing the benefits of reduced precision for supported layers.

To enable this feature, simply set the per_tensor_fallback flag to True (default) in the QuantizeConfig when calling the enable_cache API. Only support for float8 quantization for now. For example:

import cache_dit
from cache_dit import DBCacheConfig, ParallelismConfig, QuantizeConfig

cache_dit.enable_cache( 
  pipe, cache_config=DBCacheConfig(), # w/ default
  parallelism_config=ParallelismConfig(tp_size=2),
  quantize_config=QuantizeConfig(
    quant_type="float8_per_row",
    # Must be True to enable fp8 per-tensor fallback.
    regional_quantize=True, # default, True.
    repeated_blocks=['Flux2TransformerBlock', 'Flux2SingleTransformerBlock'],
    # Enable fallback to float8 per-tensor quantization, default to True
    # for better compatibility for layers that do not support float8 per-row 
    # quantization, e.g., layers with RowwiseParallel applied in tensor parallelism.
    per_tensor_fallback=True, 
  ),
)

For examples, without fp8 per-tensor fallback, the cache-dit will auto skip the layers that do not support float8 per-row quantization, and raise warning for those layers. The performance will be worse due to less layers being quantized. (quantize 88 layers, skip 56 layers)

# w/o fp8 per-tensor fallback, quantize 88 layers, skip 56 layers, performance downgrade.
CUDA_VISIBLE_DEVICES=0,1 python3 -m cache_dit.generate flux2_klein_9b_kv_edit \
 --parallel-config 'tp=2' --compile-config 'transformer' --quantize-config \
 quant_type=float8_per_row,verbose=true,per_tensor_fallback=false
-----------------------------------------------------------------------------------
Quantized        Region: ['Flux2TransformerBlock', 'Flux2SingleTransformerBlock']  |
Quantized Linear Layers: 88    float8_per_row     56 (skipped)                     |
Quantized Linear Layers: 88    (total)                                             |
Skipped   Linear Layers: 56    (total)                                             |
Linear           Layers: 144   (total)                                             |
-----------------------------------------------------------------------------------
------------------------------------------------------------------------------------
float8_per_row, skip: attn.to_out.0        : pattern<RowwiseParallel>: 8    layers  |
float8_per_row, skip: attn.to_add_out      : pattern<RowwiseParallel>: 8    layers  |
float8_per_row, skip: ff.linear_out        : pattern<RowwiseParallel>: 8    layers  |
float8_per_row, skip: ff_context.linear_out: pattern<RowwiseParallel>: 8    layers  |
float8_per_row, skip: attn.to_out          : pattern<RowwiseParallel>: 24   layers  |
------------------------------------------------------------------------------------

With fp8 per-tensor fallback enabled, those layers that do not support float8 per-row quantization will be quantized to float8 per-tensor instead, and the performance will be better due to more layers being quantized. (quantize 144 layers, skip 0 layer)

# w/ fp8 per-tensor fallback enabled, quantize 144 layers, skip 0 layer, better performance.
CUDA_VISIBLE_DEVICES=0,1 python3 -m cache_dit.generate flux2_klein_9b_kv_edit \
 --parallel-config 'tp=2' --compile-config 'transformer' --quantize-config quant_type=float8_per_row,verbose=true
# Default, enabled fp8 per-tensor fallback
-----------------------------------------------------------------------------------
Quantized        Region: ['Flux2TransformerBlock', 'Flux2SingleTransformerBlock']  |
Quantized Linear Layers: 88    float8_per_row     0 (skipped)                      |
Quantized Linear Layers: 56    float8_per_tensor  0 (skipped)                      |
Quantized Linear Layers: 144   (total)                                             |
Skipped   Linear Layers: 0     (total)                                             |
Linear           Layers: 144   (total)                                             |
-----------------------------------------------------------------------------------

(Hybrid) Precision Plan

The precision_plan option in QuantizeConfig allows users to specify different quantization types for matched layer-name patterns. It is useful when you want better control of the accuracy and performance trade-off for attention sub-layers (for example, keep to_k/to_v in float8_per_row while using float8_per_tensor for to_q/to_out). Please note:

  • Layers not matched by precision_plan continue to use the base quant_type.
  • precision_plan is only valid when regional_quantize=True. If regional quantization is disabled, precision plan will be ignored.
  • precision_plan is compatible with per_tensor_fallback. If a selected plan type is not supported by a specific layer/hardware path (case: rowwise tensor parallel is used and the basic quantize type is float8_per_row), fallback logic still works automatically when enabled.

For example: (FLUX.2-Klein-9b-kv)

import cache_dit
from cache_dit import DBCacheConfig, ParallelismConfig, QuantizeConfig

cache_dit.enable_cache(
  pipe,
  cache_config=DBCacheConfig(),
  quantize_config=QuantizeConfig(
     # Default type for unmatched layers in transformer.
    quant_type="float8_per_row",
    regional_quantize=True,
    repeated_blocks=['Flux2TransformerBlock', 'Flux2SingleTransformerBlock'],
    per_tensor_fallback=True,
    precision_plan={
      "attn.to_q": "float8_per_tensor",  # match: **attn.to_q**, best performance. 
      "attn.to_k": "float8_weight_only", # match: **attn.to_k**, best precision.
      "attn.to_v": "float8_per_block",   # match: **attn.to_v**, better precision.
      "attn.to_out": "float8_per_row",   # match: **attn.to_out**, better precision.
    },
  ),
)
# For the CLI, express the same plan as a launch `quantize` section or use the Python API above.
Then, the output summary will show the quantization type for each layer, and users can verify the quantization plan is applied correctly.

-----------------------------------------------------------------------------------
Quantized        Region: ['Flux2TransformerBlock', 'Flux2SingleTransformerBlock']  |
Quantized Linear Layers: 96    float8_per_row     0 (skipped)                      |
Quantized Linear Layers: 32    float8_per_tensor  0 (skipped)                      |
Quantized Linear Layers: 8     float8_per_block   0 (skipped)                      |
Quantized Linear Layers: 8     float8_weight_only 0 (skipped)                      |
Quantized Linear Layers: 144   (total)                                             |
Skipped   Linear Layers: 0     (total)                                             |
Linear           Layers: 144   (total)                                             |
-----------------------------------------------------------------------------------

Per-Layer Accuracy Observers (diagnostics, OFF by default)

When a quantized model loses precision and you need to know which layers are responsible, QuantizeConfig.observer attaches a per-layer observer that recomputes every quantized linear in bf16 and reports the fp8 error. The switch is QuantizeConfig(observer=...), default None = disabled:

from cache_dit import QuantizeConfig, QuantizationObserverConfig

quantize_config = QuantizeConfig(
  quant_type="float8_per_row",
  observer=QuantizationObserverConfig(
    enabled=True,                 # the only switch; default False
    json_path="./fp8_observers.json",
    max_steps=1,                  # dump after N transformer forwards
    keep_refs_on_gpu=False,       # True keeps the bf16 refs on device
    # Only observe the layers you care about; Python regex, `re.search`
    # semantics on the fully qualified name, so a fragment is enough.
    # None (default) = every quantized linear.
    layer_name_patterns=[r"feed_forward\.linear_[23]$", r"norm1\.linear$"],
  ),
)

layer_name_patterns is applied before the bf16 snapshot, so unselected layers cost no memory and add no GEMM: matching feed_forward on a double/single-stream DiT observes 144 of 336 linears and roughly halves the observer overhead. Invalid regexes raise ValueError at config construction time.

With observer=None (the default) the quantization path skips the feature completely — no module walk, no bf16 weight snapshot, no forward hooks — so quantize() and inference behave exactly as before, with zero overhead.

Each observed layer reports rel_err (||y_fp8 - y_bf16|| / ||y_bf16||), cos similarity, out_amax, in_outlier (amax/mean(|x|) per token, which predicts how badly a per-token fp8 scale rounds the bulk of a row) and w_rel_err (weight-only quantization error). Group the results by layer name substring to see, for example, that FFN layers are more sensitive than the adaLN modulation projections.

Both quantization backends are covered: TorchAO float8 (the weight becomes a Float8Tensor) and cache-dit's SVDQuant W4A4 runtime layer (the module becomes SVDQW4A4Linear with packed 4-bit weights). For SVDQuant the weight is kept packed, so w_rel_err is null while rel_err and cos are still reported. The lifecycle is owned by one class, QuantizeObserver:

from cache_dit.quantization.observers import QuantizeObserver

observer = QuantizeObserver(config.observer)
refs = observer.capture_references(model)   # before quantization
observer.attach(model, refs)                 # after quantization
observer.dump("./fp8_observers.json")        # write the statistics

Cost: the observers keep one bf16 copy of every observed linear weight (host RAM by default) and add one bf16 GEMM per observed layer per forward, i.e. roughly 1.5-2x transformer forward time, plus a one-off snapshot of the weights during quantize(). Use it for accuracy analysis only — never when measuring latency, throughput or memory.

INT8/INT4 Quantization

In addition to FP8 quantization, Cache-DiT also supports INT8 and INT4 quantization for weights, which can further reduce the memory footprint of the model. Users can specify int8_per_row, int8_per_tensor, int8_weight_only, or int4_weight_only as the quantization type in the QuantizeConfig when calling the enable_cache API. For example:

import cache_dit
from cache_dit import DBCacheConfig, ParallelismConfig, QuantizeConfig  

cache_dit.enable_cache( 
  # Or "int8_per_tensor", "int8_weight_only", "int4_weight_only", etc.
  pipe, quantize_config=QuantizeConfig(quant_type="int8_per_row"), 
)
INT4 quantization can provide even better memory reduction compared to FP8 or INT8, but it may cause more precision loss. We recommend users to try different quantization types and choose the one that best fits their needs in terms of the trade-off between performance and precision. In most cases, float8 per-row can be a good choice for better memory reduction while maintaining acceptable precision.

Please note that users should also install mslk kernel library to enable INT8/INT4 quantization features. The int4_weight_only w4a16 compute kennel requires architectures >= sm90 (Hopper or newer, TMA required). For older architectures, users can use int8_weight_only quantization for better compatibility.

# stable: mslk (change cu13x to cu129 if using CUDA 12.9), torch>=2.11.0
# mslk version matching: torch==2.11.x mslk==1.1.0; torch==2.12.x mslk==1.2.0
pip install torch==2.11.0 mslk==1.1.0 --index-url https://download.pytorch.org/whl/cu130
pip install torch==2.12.0 mslk==1.2.0 --index-url https://download.pytorch.org/whl/cu132
# nightly: mslk (change cu13x to cu129 if using CUDA 12.9), required torch>=2.11.0
pip install --pre torch mslk --index-url https://download.pytorch.org/whl/nightly/cu132

In the case of distributed inference (context parallelism or tensor parallelism), we recommend users to use float8 quantization to avoid potential compatibility issues.

TorchAO NVFP4 Quantization

nvfp4 uses NVFP4DynamicActivationNVFP4WeightConfig from TorchAO's MX formats prototype. Cache-DiT currently fixes both use_triton_kernel=True and use_dynamic_per_tensor_scale=True. It is an online dynamic quantization path and is separate from the svdq_nvfp4_* SVDQuant path. (Required mslk kernels library)

For example:

import cache_dit
from cache_dit import QuantizeConfig  

cache_dit.enable_cache( 
  pipe, cache_config=..., quantize_config=QuantizeConfig(quant_type="nvfp4"), 
)

The current implementation requires Blackwell or newer GPUs (SM100+) and skips Linear layers whose two weight dimensions are not divisible by 16 or whose output dimensions are too small for the NVFP4 kernel. The supported CLI options are:

python3 -m cache_dit.generate flux --quantize-config quant_type=nvfp4
python3 -m cache_dit.generate flux --quantize-config quant_type=nvfp4 --compile-config 'transformer'
python3 -m cache_dit.generate flux --quantize-config quant_type=nvfp4_weight_only

The model must use bfloat16 Linear weights. The Triton activation kernel can fall back internally when a runtime shape does not satisfy its kernel constraints.

SVDQuant (W4A4) PTQ

Cache-DiT provides a native SVDQuant PTQ workflow for W4A4 quantization (with high performance W4A4 GEMM kernels and an easy-to-use PTQ interface). The public API is intentionally small: build a QuantizeConfig, quantize with cache_dit.quantize(...), then reload with cache_dit.load(...). Cache-DiT now supports both INT4 and NVFP4 SVDQuant PTQ flows. We highly recommend using native SVDQuant support in Cache-DiT for W4A4 quantization, as it can provide high performance and better usability compared to other third-party low-bit quantization libraries.

svdq

With Cache-DiT's SVDQuant support, users can easily apply W4A4 quantization to their models with just a few lines of code, without worrying about the underlying implementation details or compatibility issues. Before using SVDQuant, install the pre-built CUDA package (see Installation) or build Cache-DiT from source with the CUDA extensions.

For PTQ, the available quant types are svdq_int4_r{rank} and svdq_nvfp4_r{rank}. The INT4 path remains the general cross-architecture option for supported non-Hopper GPUs and defaults to the native W4A4 GEMM. NVFP4 is currently validated on Blackwell (sm120) and defaults to the same native GEMM. The public runtime_kernel choices are native, cute, flashinfer, flashinfer+cute-dsl, and flashinfer+cutlass-sm120; None selects the defaults above, while the rest are NVFP4-only opt-in paths (see SVDQ Runtime Kernel for the runtime × lora_layout semantics and the native/cute/FlashInfer comparison tables). One native kernel family serves both precisions, so INT4 and NVFP4 differ only in the packed weight format.

# Required: CUDA 13.0+, PyTorch 2.11+ (a CUDA 13 build), and the GLIBC floor of the
# release (2.38; see the platform tags on the index page).
pip install -U cache-dit --extra-index-url https://vipshop.github.io/cache-dit/whl/cu13/ # SVDQuant build, local version +cu13.
# Optional: build Cache-DiT from source with the CUDA extensions.
git clone https://github.com/vipshop/cache-dit.git && cd cache-dit
git submodule update --init --recursive --force # SVDQuant needs spdlog; SM120 CuTe needs CUTLASS 4.8.1
CACHE_DIT_BUILD_CUDA=1 MAX_JOBS=32 pip install -e ".[quantization]"

The only thing users need to do is to prepare the calibration function (calibrate_fn) for collecting quantization statistics, and Cache-DiT will take care of the rest, including computing the quantization parameters, applying quantization, and loading the quantized weights for inference or further fine-tuning. For example:

Step 1: Load the pre-trained model in full precision and DON'T forget to move the model to "CUDA" for better calibration performance.

import torch
import cache_dit
from diffusers import Flux2KleinPipeline
from cache_dit import QuantizeConfig

# 1. Load the pre-trained model in "cuda"
pipe = Flux2KleinPipeline.from_pretrained(
  "black-forest-labs/FLUX.2-klein-4B",
  torch_dtype=torch.bfloat16,
).to("cuda")

Step 2: Prepare the calibration data and calibration function (calibrate_fn) for SVDQuant QuantizeConfig. Cache-DiT will automatically collect the quantization statistics during the calibration process, and use those statistics to compute the quantization parameters for each linear layer.

# 2.1 Prepare the calibration dataset for collecting quantization statistics.
calibration_prompts = ["A cute cat sitting on the beach.", ...]

# 2.2 Define the calibration function for SVDQuant PTQ.
def calibrate_fn(**_: object) -> None:
  with torch.inference_mode():
    for prompt in calibration_prompts:
      _ = pipe(
        prompt=prompt,
        height=1024,
        width=1024,
        num_inference_steps=4,
        generator=torch.Generator(device="cpu").manual_seed(0),
      )

Step 3: Build the QuantizeConfig for SVDQuant, and call cache_dit.quantize(...) to apply SVDQuant W4A4 quantization to the model. We have to wait some time for the quantization process to finish, as SVDQuant will perform SVD decomposition for each linear layer and compute the quantization parameters based on the collected quantization statistics. The quantized model will be saved to disk in the specified directory.

# 3. Build the QuantizeConfig for SVDQuant, and call `cache_dit.quantize(...)`.
quant_config = QuantizeConfig(
  quant_type="svdq_int4_r32", # _r{rank}, e.g., r16, r32, r64, r128, etc.
  calibrate_fn=calibrate_fn,
  serialize_to="./FLUX.2-klein-4B-svdq/",
  svdq_kwargs={"calibrate_precision": "low"},  # default, optional: low | medium | high
)
pipe.transformer = cache_dit.quantize(pipe.transformer, quant_config)

The NVFP4 PTQ flow uses the same public API and selects the native GEMM when runtime_kernel is omitted. Set runtime_kernel="cute" only to opt in to the CuTe validation path:

quant_config = QuantizeConfig(
  quant_type="svdq_nvfp4_r32",  # _r{rank}, e.g., r16, r32, r64, r128, etc.
  calibrate_fn=calibrate_fn,
  serialize_to="./FLUX.2-klein-4B-svdq-nvfp4/",
  svdq_kwargs={
    "calibrate_precision": "low",
  },
)
pipe.transformer = cache_dit.quantize(pipe.transformer, quant_config)

calibrate_precision now defaults to low, which uses randomized torch.svd_lowrank and keeps the calibration math in float32. medium and high remain available as opt-in debugging or accuracy-investigation modes. On a real FLUX.2-klein-4B PTQ run (rank=32, 8 calibration prompts, 1024x1024), the quantized-model behavior was almost the same across all three modes; the practical difference was mostly PTQ cost. The speedup column below refers to quantization-time speedup relative to high.

calibrate_precision low-rank route quantization_s speedup PSNR
low torch.svd_lowrank w/ float32 20.2258 18.02x 29.2528
medium full torch.linalg.svd w/ float32 111.8944 3.26x 29.2454
high float64 full SVD, CUDA gesvd 364.4877 1.00x 29.1880

In practice the PSNR values are almost the same, so low is the recommended production default. It keeps the best PTQ throughput while preserving the same loaded-model behavior seen from medium and high.

svd_refine_iters (default 0) enables alternating SVD refinement of the low-rank/residual split. The one-shot split picks the low-rank branch from the smoothed weight's singular directions alone, so it cannot know what the residual quantizer will get wrong. Each refinement round simulates quantizing the current residual, re-decomposes weight - dequant(quantize(residual)), and re-anchors the residual on weight, letting the low-rank branch absorb the residual quantizer's error pattern. 0 keeps the original one-shot behavior.

Each round adds one SVD per layer, so svd_refine_iters=N costs roughly N+1 times the low-rank portion of PTQ time (the quantization_s column above). The table below is the relative L2 error of the reconstruction the runtime actually evaluates, up @ down + dequant(quantize(residual)), on a single 256x128 spectral-decay weight at rank=32 (make_spectral_decay_weight from the test helpers, calibrate_precision="low", bfloat16):

svd_refine_iters NVFP4 rel L2 INT4 rel L2
0 0.024128 0.026423
1 0.019196 0.021266
2 0.017313 0.019715
5 0.015490 0.018608
10 0.014506 0.018134

The returns flatten quickly, and they survive on real weights: averaged over 14 PixArt-Sigma attention and feed-forward layers with real calibration activations, 5 rounds cut weight error by 7.8-8.9% and layer output error by 17.4-18.2% relative to the one-shot split, for both formats.

These are still single-layer reconstruction numbers, not end-to-end image metrics. Treat them as a guide to where the returns flatten rather than as an expected PSNR gain, and measure PSNR on your own model before committing to a round count.

quant_config = QuantizeConfig(
  quant_type="svdq_nvfp4_r32",
  calibrate_fn=calibrate_fn,
  serialize_to="./FLUX.2-klein-4B-svdq-nvfp4/",
  svdq_kwargs={
    "svd_refine_iters": 5,
  },
)
pipe.transformer = cache_dit.quantize(pipe.transformer, quant_config)

Step 4: The FLUX.2-klein-4B-svdq directory now contains: {quant_type}.safetensors (for example, svdq_int4_r32.safetensors or svdq_nvfp4_r32.safetensors) and quant_config.json. The quantized model can be loaded with cache_dit.load(...) for inference or further fine-tuning. For example:

# 4.1 First, keep in CPU for now.
pipe = Flux2KleinPipeline.from_pretrained(...) 
# 4.2 Load the quantized model for inference.
pipe.transformer = cache_dit.load(pipe.transformer, "./FLUX.2-klein-4B-svdq/")
pipe.to("cuda") # Transfer the model to GPU for inference.

For SVDQuant, serialize_to should point to a directory. Cache-DiT normalizes the checkpoint name to {quant_type}.safetensors, writes a sibling quant_config.json, and lets cache_dit.load(...) recover the real checkpoint path directly from that directory. Performance comparison between SVDQuant W4A4 and full precision BF16 for FLUX.2-klein-4B is listed below:

flux2_klein_4b_svdq

The full benchmark report for FLUX.2-klein-4B SVDQuant (W4A4) is listed below. The SVDQuant W4A4 quantized model can achieve around 2.5x memory reduction for transformer weights, around 1.7x speedup in latency, while maintaining good output quality (the output images are almost the same as the full precision model).

stage resolution avg_latency_s peak_memory_gb transformer_gb
float_reference 1024x1024 2.1302 17.3245 7.2188
memory_quantized 1024x1024 1.2520 12.3916 2.2761
loaded_quantized 1024x1024 1.2410 12.3883 2.2761

Notes: full_blocks means all transformer blocks are quantized; memory_quantized means the quantized model is in memory; loaded_quantized means the quantized model is reloaded from disk with cache_dit.load(...).

SVDQuant in Cache-DiT is compatible with torch.compile, and users can further speed up the quantized model with compilation. The performance comparison between eager and compiled mode for SVDQuant W4A4 is listed below:

stage resolution avg_latency_s latency_delta speedup_vs_eager
quantized + eager 1024x1024 1.2689 0.0000 1.0000x
quantized + compile 1024x1024 1.0161 -0.2528 1.2488x

Cache-DiT also has an NVFP4 PTQ path for Blackwell. On a RTX 5090 (sm120) validation run with FLUX.2-klein-4B, svdq_nvfp4_r32, runtime_kernel="native", 512x512, 4 denoising steps, benchmark_runs=3, and warmup_runs=1, the full e2e example completed end-to-end for in-memory inference, checkpoint reload, and compiled quantized execution:

stage resolution latency_s speedup peak_memory_gb psnr
baseline 512x512 0.3043 1.0000x 15.5402 -
memory_quantized 512x512 0.1725 1.7641x 10.7098 17.0449
loaded_quantized 512x512 0.1764 1.7251x 10.7127 15.5375
compiled_quantized 512x512 0.1430 2.1280x 10.7127 16.1652

In that validation, the loaded transformer reported precision == "nvfp4", confirming that the serialized PTQ checkpoint preserved the NVFP4 precision metadata rather than silently falling back to INT4.

flux2_klein_4b_svdq_nvfp4_512

Under the same svdq_nvfp4_r32 + runtime_kernel="native" setup, rerunning the full e2e example at 1024x1024 on the same RTX 5090 (sm120) kept the same stage ordering while shifting the absolute runtime and memory envelope upward:

stage resolution latency_s speedup peak_memory_gb psnr
baseline 1024x1024 0.9703 1.0000x 17.3245 -
memory_quantized 1024x1024 0.5754 1.6862x 12.4963 20.1529
loaded_quantized 1024x1024 0.5851 1.6584x 12.4969 19.9014
compiled_quantized 1024x1024 0.4742 2.0458x 12.4969 21.2930

For this 1024x1024 run, the transformer CUDA footprint again dropped from 7.2188 GiB in the baseline to 2.3850 GiB in all three quantized stages, while the compiled stage remained the fastest steady-state path.

flux2_klein_4b_svdq_nvfp4_1024

How to use SVDQ in Nunchaku with Cache-DiT?

FAQ: Can I use Cache-DiT's SVDQuant support for Nunchaku int4 models?

Yes, Cache-DiT also supports the caching and context parallelism scheme for int4 models from official Nunchaku library. Users can leverage Cache-DiT to speed up Nunchaku 4-bits W4A4 models. But we recommend users to use Cache-DiT's native SVDQuant support for better compatibility and usability.

import cache_dit
from diffusers import QwenImagePipeline
from nunchaku import NunchakuQwenImageTransformer2DModel

transformer = NunchakuQwenImageTransformer2DModel.from_pretrained(
  f"path-to/svdq-int4_r32-qwen-image.safetensors"
)
pipe = QwenImagePipeline.from_pretrained(
  "Qwen/Qwen-Image", transformer=transformer, torch_dtype=torch.bfloat16,
).to("cuda")

cache_dit.enable_cache(pipe, cache_config=..., parallelism_config=...)

SVDQuant-FP8 (W8A8)

svdq_fp8_r32_dq, svdq_fp8_r64_dq, and svdq_fp8_r128_dq keep the SVDQuant low-rank correction but quantize the residual weight and activation to E4M3 instead of 4-bit formats. This provides rank-dependent accuracy choices for compute-bound, precision-sensitive layers. Larger ranks generally reduce weight error at a small additional kernel and memory cost; rank 128 is the safest default when accuracy matters more than the extra overhead.

The producer fuses per-token activation quantization with the BF16 low-rank down projection. The GEMM accumulates the E4M3 residual product and BF16 low-rank up projection into the same FP32 accumulator; there is no standalone BF16 GEMM or second pass over the dense output. Only sm120 or newer is supported, and ranks 32, 64, and 128 are available.

SVDQ-FP8 DQ

The default DQ smooth strategy is identity, matching SVDQ W4A4 DQ. It needs no calibration data and no extra svdq_kwargs:

pipe.transformer = cache_dit.quantize(
  pipe.transformer,
  QuantizeConfig(quant_type="svdq_fp8_r32_dq"),
)

The generate CLI accepts --quantize-config quant_type=svdq_fp8_r{32|64|128}_dq.

The DQ-only weight and weight_inv strategies are optional zero-calibration heuristics, not defaults. They derive a per-input-channel scale from weight spans and can change which directions the low-rank SVD retains, but they do not use real activation outliers and are not a substitute for PTQ calibration. Measure the target model before opting in; weight is not accepted by the PTQ workflow.

SVDQ-FP8 PTQ

Use svdq_fp8_r{32|64|128} without the _dq suffix and provide calibrate_fn. PTQ always uses smooth_strategy="activation": each calibration forward updates a per-input-channel activation span, and the smooth scale is computed from those spans and the weight spans. Layers not observed during calibration are skipped rather than partially quantized with an invented scale.

def calibrate_fn(module):
  for batch in calibration_batches:
    module(batch)

quant_config = QuantizeConfig(
  quant_type="svdq_fp8_r128",
  calibrate_fn=calibrate_fn,
  serialize_to="./FLUX.1-dev-svdq-fp8-r128-ptq/",
)
pipe.transformer = cache_dit.quantize(pipe.transformer, quant_config)

For SVDQ-FP8 PTQ, serialize_to is optional: omit it for an in-memory quantized model, or set it to produce a reusable checkpoint. Unlike SVDQ-FP8, W4A4 PTQ requires a serialization destination.

SVDQ-FP8 checkpoint save/load

Both DQ and PTQ support checkpoint serialization. Cache-DiT writes {quant_type}.safetensors and a sibling quant_config.json. Load the checkpoint into a fresh float transformer with cache_dit.load(transformer, path), where path can be the checkpoint file, its directory, or a matching QuantizeConfig. The manifest records precision="fp8", so FP8 checkpoints never enter the W4A4 unpacking path.

quant_config = QuantizeConfig(
  quant_type="svdq_fp8_r128_dq",
  serialize_to="./FLUX.1-dev-svdq-fp8-r128/",
  svdq_kwargs={"quantize_device": "cuda"},
)
pipe.transformer = cache_dit.quantize(pipe.transformer, quant_config)

# Later, construct the same float transformer and restore the packed weights:
pipe.transformer = cache_dit.load(pipe.transformer, "./FLUX.1-dev-svdq-fp8-r128/")

The converter CLI also accepts FP8 DQ types, for example python3 -m cache_dit.convert --quantize-config svdq_fp8_r128_dq .... Checkpoint loading currently supports ordinary single-GPU modules; DTensor/TP and layerwise-offload checkpoint paths are rejected. The W4A4 fused-MLP epilogue is not yet implemented for SVDQ-FP8, so fused_mlp=True is explicitly rejected.

SVDQuant-W4A8

SVDQ-W4A8 uses the same per-token E4M3 activation and fused BF16 low-rank branch as SVDQ-FP8, but stores the residual weight as packed E2M1 codes. Its qweight buffer is uint8 [N,K/2] with even-k in the low nibble and odd-k in the high nibble, so residual-weight storage is half of W8A8. This is a memory-oriented format, not a claim of better accuracy than W8A8; measure the target model before selecting a rank.

DQ uses svdq_w4a8_r{32|64|128}_dq and defaults to identity smoothing:

pipe.transformer = cache_dit.quantize(
  pipe.transformer,
  QuantizeConfig(quant_type="svdq_w4a8_r64_dq"),
)

The generate CLI accepts the corresponding --quantize-config quant_type=svdq_w4a8_r{32|64|128}_dq types, and the converter accepts python3 -m cache_dit.convert --quantize-config svdq_w4a8_r64_dq with BF16 source weights.

PTQ uses the type without _dq, for example svdq_w4a8_r64, plus the same calibrate_fn and activation-derived smoothing described in the SVDQ-FP8 PTQ section. Unobserved layers are skipped.

Both DQ and PTQ support serialize_to and cache_dit.load with checkpoint files, directories, or a matching QuantizeConfig. The manifest precision is w4a8, which keeps this packed format out of both the W4A4 and W8A8 loaders. W4A8 currently requires sm120+ and BF16 source weights; fused MLP, DTensor/TP, layerwise offload, and alternate runtime selectors are explicitly rejected.

SVDQuant W6A6 (MXFP6)

svdq_fp6_r{32|64|128}dq (alias svdq_w6a6*) quantizes both operands to packed E2M3 and lets the tensor core apply one UE8M0 micro-scale per 32 K elements. Nothing is promoted blockwise in the mainloop: the scale rows go straight into mma.sync.aligned.kind::mxf8f6f4.block_scale.scale_vec::1X, and the fused BF16 low-rank branch still shares the FP32 accumulator.

import cache_dit

cache_dit.enable_cache(
  pipe,
  quantize_config=cache_dit.QuantizeConfig(quant_type="svdq_fp6_r32_dq"),
)

The generate CLI accepts --quantize-config quant_type=svdq_fp6_r{32|64|128}_dq; the manifest precision is fp6, so the packed layout stays separate from the W4A4/W8A8/W4A8 loaders. Requirements and limits are the same as W4A8: sm120+, BF16 source weights, and no DTensor/TP, fused MLP, or layerwise offload.

Packing is the OCP MXFP6 layout: four codes per three bytes, little-endian within each 24-bit group, so K must be a multiple of 128 (96 bytes per 128 elements). The activation producer derives each block exponent from the group amax of the smoothed activation, which means the quantized activation carries its own [M, K/32] scale row instead of a per-token vector.

SVDQuant (W4A4) DQ

Cache-DiT also supports SVDQ dynamic quantization through quant types ending with _dq, such as svdq_int4_r32_dq, svdq_int4_r128_dq, svdq_nvfp4_r32_dq, and svdq_nvfp4_r128_dq. By default, this workflow keeps the low-rank SVD branch and, by default, fixes the smooth factor to 1, so users do not need to provide a calibration callback or a serialization directory.

The DQ runtime routing is identical to PTQ: INT4 and NVFP4 both default to the native W4A4 GEMM. Explicit runtime_kernel="native" selects that same native kernel; cute and the three flashinfer spellings are NVFP4-only opt-in paths (see SVDQ Runtime Kernel for the runtime × lora_layout semantics and the native/cute/FlashInfer comparison tables). Only None, native, cute, flashinfer, flashinfer+cute-dsl, and flashinfer+cutlass-sm120 are accepted.

Under the hood, cache-dit now treats this as an explicit backend-local smooth-strategy choice: DQ uses the identity smooth vector by default, while PTQ continues to use activation-derived smoothing. The public DQ behavior does not change, but this separation makes it easier to add future opt-in smooth strategies without redefining the meaning of existing _dq quant types.

The default DQ usage keeps the identity smooth vector and does not require any extra svdq_kwargs:

import cache_dit
from cache_dit import QuantizeConfig

# 0. use 'enable_cache' API with the default identity-smooth DQ.
cache_dit.enable_cache(
  pipe,
  quantize_config=QuantizeConfig(
    quant_type="svdq_int4_r32_dq",
  ),
)

# 1. or directly call the `quantize` API for more fine-grained control.
pipe.transformer = cache_dit.quantize(
  pipe.transformer,
  QuantizeConfig(
    quant_type="svdq_int4_r32_dq",
  ),
)

The NVFP4 DQ path uses the same flow and selects the native GEMM by default. Set runtime_kernel="cute" only to opt in to the CuTe validation path:

pipe.transformer = cache_dit.quantize(
  pipe.transformer,
  QuantizeConfig(
    quant_type="svdq_nvfp4_r32_dq",
  ),
)

The avaliable DQ smooth strategies are not limited to the identity smooth vector. We have also implemented some experimental heuristics that derive non-trivial smooth factors from weight statistics alone, without any activation calibration. These heuristics are inspired by the mathematical form of the PTQ smooth factor, but they intentionally ignore the activation term and only use weight statistics to compute the smooth factors. For example, users can set the smooth_strategy in svdq_kwargs to weight, weight_inv, or few_shot to enable these non-default DQ modes:

import cache_dit
from cache_dit import QuantizeConfig

cache_dit.enable_cache(
  pipe,
  quantize_config=QuantizeConfig(
    quant_type="svdq_int4_r32_dq",
    svdq_kwargs={"smooth_strategy": "weight"},
  ),
)

These experimental modes still avoid activation calibration, but derive non-trivial per-channel smooth factors from weight statistics alone. They are currently available as opt-in Python API settings rather than dedicated CLI shortcuts. For the shared generate helpers, Cache-DiT also exposes --svdq-{int4|nvfp4|fp8}-r{32|64|128}-dq as quick DQ entry points (INT4 and NVFP4 additionally accept rank 256). The mathematical difference between the DQ smooth strategies is listed below.

identity: use the unit smooth vector directly.

\[ s_i = 1 \]

This keeps the current zero-calibration DQ behavior unchanged. The low-rank decomposition is applied directly to the original weight matrix, so the entire DQ approximation is driven only by the weight tensor and the target rank.

weight: replace the activation term with a constant proxy and build a purely weight-derived smooth factor. In the current implementation, PTQ uses the following smooth scale:

\[ s_i = \frac{a_i^\alpha}{w_i^{1-\alpha}} \]

The weight-only DQ heuristic starts from:

\[ \hat{s}_i = w_i^{-(1-\alpha)} \]

Here w_i denotes the per-input-channel weight span. Cache-DiT then stabilizes this raw heuristic by geometric-mean normalization and explicit clipping:

\[ s_i = \operatorname{clip}\!\left(\frac{\hat{s}_i}{\exp\left(\frac{1}{n}\sum_j \log \hat{s}_j\right)},\ 0.25,\ 4.0\right) \]

Intuitively, identity does not redistribute any quantization difficulty across channels, while weight tries to equalize channels using weight statistics alone. Because it has no access to real activation outliers, it should be treated as an experimental heuristic rather than a replacement for PTQ smoothing.

weight_inv: use the same weight-only proxy, but flip the exponent direction so that channels with larger weight span receive larger smooth factors.

\[ \hat{s}_i^{\mathrm{inv}} = w_i^{1-\alpha} \]

Cache-DiT then applies the same geometric-mean normalization and clipping.

Intuitively, weight_inv does the opposite trade-off of weight: it intentionally makes the weight tensor harder to quantize on large-span channels, but it may reduce activation quantization difficulty because those activation channels are divided by a larger smooth factor at runtime. For examples:

# default: identity smooth strategy
python -m cache_dit.generate flux2_klein_4b --quantize-config quant_type=svdq_int4_r128_dq \
  --svdq-config smooth_strategy=identity,calibrate_precision=low

# experimental: weight-only heuristic
python -m cache_dit.generate flux2_klein_4b --quantize-config quant_type=svdq_int4_r128_dq \
  --svdq-config smooth_strategy=weight,calibrate_precision=low

# experimental: bias the trade-off toward easier activation quantization
python -m cache_dit.generate flux2_klein_4b --quantize-config quant_type=svdq_int4_r128_dq \
  --svdq-config smooth_strategy=weight_inv,calibrate_precision=low

# high-rank are recommended for better precision while using SVDQ DQ, e.g, 256.
python -m cache_dit.generate flux2_klein_4b --quantize-config quant_type=svdq_int4_r256_dq \
  --svdq-config smooth_strategy=identity,calibrate_precision=low

# higher SVD decomposition precision may be helpful for better DQ accuracy.
python -m cache_dit.generate flux2_klein_4b --quantize-config quant_type=svdq_int4_r256_dq \
  --svdq-config smooth_strategy=identity,calibrate_precision=medium

Here are some preliminary results on the impact of identity, weight-only, and weight_inv heuristics DQ smooth strategies for a SVDQ DQ sweep on FLUX.2-klein-4B.

baseline (bf16) identity (default) weight-only heuristic weight_inv heuristic
2.13s 1.28s 1.28s 1.28s
- PSNR: 28.71 PSNR: 29.62 PSNR: 29.35

few_shot: delay SVDQ DQ materialization until the runtime has observed a small number of real inference forwards. Cache-DiT will keep the transformer in float mode during the first few_shot_steps root-module forwards, stream per-layer activation spans by layer name, and after the last observed forward finishes it will relax those activation spans according to a configurable few-shot policy, recompute activation-derived smooth scales, quantize the eligible linear layers in place, and use the quantized transformer from the next forward onward.

This mode exposes four backend-local knobs:

  • few_shot_steps: number of root-module forwards to observe before quantization. This means transformer/module forward passes, not top-level pipeline invocations, and the count is cumulative on the same armed module. Default: 1. That cumulative behavior matters in diffusion pipelines because one pipeline run usually executes the transformer many times. For example, if the same pipe instance runs a 50-step sample once and then runs another 50-step sample again, the few-shot controller sees roughly 100 root-module forwards in total rather than resetting back to 50 for the second run.
  • few_shot_relax_factor: maximum multiplicative factor applied to activation spans during few-shot relaxation. It must satisfy few_shot_relax_factor >= 1.0, so the observed activation span is preserved or amplified, never reduced. Default: 1.5. In practice, values around 1.5-2.5 are usually the safer starting range; larger values such as 4.0 can still oversmooth or blur image outputs when the outlier prior becomes too strong.
  • few_shot_relax_top_ratio: fraction of the largest activation spans used to define the few-shot threshold. Default: 0.25.
  • few_shot_relax_strategy: how the relax factor is assigned across channels before smooth-scale recomputation. Default: auto. Available values: fixed, top, auto, stable_auto, power, log, and rank.

If the observed activation-span vector is denoted as a and the weight-span vector is denoted as w, Cache-DiT first computes the threshold corresponding to 1 - few_shot_relax_top_ratio on a, relaxes the activation span, and then recomputes the smooth scale:

\[ s_i^{\mathrm{relaxed}} = \frac{\left(a_i^{\mathrm{relaxed}}\right)^\alpha}{w_i^{1-\alpha}} \]

It then applies one of the following relax strategies:

For auto, Cache-DiT also relaxes the channels below the threshold, but uses a smaller multiplier for smaller activation spans and caps the largest channels at few_shot_relax_factor.

\[ m_i = 1 + \left(\text{relax} - 1\right) \cdot \operatorname{clip}\left(\frac{a_i - a_{\min}}{\tau - a_{\min}}, 0, 1\right) \]
\[ a_i^{\mathrm{relaxed}} = a_i \cdot m_i \]

For stable_auto, Cache-DiT keeps the same magnitude-aware linear ramp as auto, but snaps that normalized response to a small number of evenly spaced buckets before applying the final relax multiplier. In the current implementation, the bucketized response is:

\[ r_i^{\mathrm{stable}} = \operatorname{round}(8 \cdot r_i^{\mathrm{auto}}) / 8 \]

This does not make the entire runtime path fully deterministic, but it does make the relax policy less sensitive to small first-forward activation-stat fluctuations.

For top:

\[ a_i^{\mathrm{relaxed}} = \begin{cases} a_i \cdot \text{relax}, & a_i \geq \tau \\ a_i, & a_i < \tau \end{cases} \]

Channels outside the selected top-ratio are kept unchanged.

For fixed:

\[ a_i^{\mathrm{relaxed}} = a_i \]

This disables the relax step entirely and uses the original activation-derived few-shot smooth scale after recomputation from the unchanged activation span. It is useful as a control/baseline when you want few-shot activation collection without any extra channel-wise amplification. At runtime, this strategy ignores few_shot_relax_factor and few_shot_relax_top_ratio.

Here tau is the quantile threshold and a_min is the minimum activation span in the layer. This makes the relax factor increase monotonically with the observed few-shot activation span while keeping it bounded by the configured maximum.

Internally, Cache-DiT first constructs a strategy-specific normalized response in the unit interval [0, 1], then maps it to the activation-span multiplier:

\[ m_i = 1 + r_i \cdot \left(\text{relax} - 1\right) \]

We intentionally clamp the intermediate response to [0, 1] before this affine map so the final activation-span multiplier is always bounded inside [1, relax]. Because relax is constrained to be at least 1, every channel is either unchanged or amplified; no channel can be shrunk by the few-shot relax step. Since smooth scale is recomputed from the activation span raised to alpha, the induced smooth-scale multiplier is bounded more conservatively inside [1, relax^alpha].

That does not mean arbitrarily large factors are safe. A larger factor tells the quantizer to treat the already-large activation-span channels as if they were even more likely to encounter future activation outliers. When that prior becomes too strong, the recomputed smoothing step over-allocates protection to those channels, which often shows up as visibly softer or blurrier image details. If you need a stronger head-channel bias, it is usually better to keep few_shot_relax_factor moderate and change few_shot_relax_strategy to power or reduce few_shot_relax_top_ratio, rather than pushing the factor directly to 4.0.

baseline (bf16) DQ only few-shot 1 steps + auto few-shot 4 steps + auto

The remaining non-trivial strategies reuse the same bounded activation-span multiplier range [1, few_shot_relax_factor], but change how the normalized response is built before that final affine map:

  • stable_auto: uses the same linear response as auto, but bucketizes it into a small number of levels so repeated few-shot runs are less sensitive to tiny activation-stat changes.
  • power: uses a convex squared response.
\[ r_i^2 \]

This makes the largest activation spans receive much stronger amplification while smaller channels stay closer to 1. - log: uses a concave log response, so mid/high activation-span channels get lifted earlier than in the linear auto strategy. - rank: ignores the absolute activation-span gaps and constructs the response from channel rank percentiles, which can be more robust when a layer has a few extreme outliers.

import cache_dit
from cache_dit import QuantizeConfig

cache_dit.enable_cache(
  pipe,
  quantize_config=QuantizeConfig(
    quant_type="svdq_int4_r32_dq",
    svdq_kwargs={
      "smooth_strategy": "few_shot",
      "few_shot_steps": 1,
      "few_shot_relax_factor": 1.5,
      "few_shot_relax_top_ratio": 0.25,
      "few_shot_relax_strategy": "auto",
      # Optional: request compile after runtime quantization finishes.
      "few_shot_auto_compile": True,
    },
  ),
)

When few_shot_auto_compile is enabled, helper flows may defer transformer compilation until the runtime quantization step finishes. This means the warmup forwards stay in float mode, while the next forward after quantization runs on the quantized + compiled transformer.

If no owner-level deferred compile callback is registered, Cache-DiT falls back to compiling the quantized root module in-place with nn.Module.compile(). When the root module is a diffusers transformer that exposes compile_repeated_blocks(), that regional compile path is still preferred.

The same workflow is available from the generate CLI through --quantize-config quant_type=... and --svdq-config:

# few-shot activation-derived DQ: sample one runtime forward, then quantize.
python -m cache_dit.generate flux2_klein_4b --quantize-config quant_type=svdq_int4_r128_dq \
  --svdq-config few_shot_steps=1,few_shot_relax_factor=1.5,few_shot_relax_top_ratio=0.25,smooth_strategy=few_shot

# few-shot fixed: keep the observed activation span unchanged, then recompute smooth scale.
python -m cache_dit.generate flux2_klein_4b --quantize-config quant_type=svdq_int4_r128_dq \
  --svdq-config few_shot_steps=1,few_shot_relax_strategy=fixed,smooth_strategy=few_shot

# few-shot auto relax: larger activation spans receive larger relax factors, capped at 1.5.
python -m cache_dit.generate flux2_klein_4b --quantize-config quant_type=svdq_int4_r128_dq \
  --svdq-config few_shot_steps=1,few_shot_relax_factor=1.5,few_shot_relax_top_ratio=0.25,few_shot_relax_strategy=auto,smooth_strategy=few_shot

# few-shot stable_auto relax: keep the same auto trend, but bucketize it for better stability.
python -m cache_dit.generate flux2_klein_4b --quantize-config quant_type=svdq_int4_r128_dq \
  --svdq-config few_shot_steps=1,few_shot_relax_factor=1.5,few_shot_relax_top_ratio=0.25,few_shot_relax_strategy=stable_auto,smooth_strategy=few_shot

# few-shot power relax: focus the extra amplification on the largest channels.
python -m cache_dit.generate flux2_klein_4b --quantize-config quant_type=svdq_int4_r128_dq \
  --svdq-config few_shot_steps=1,few_shot_relax_factor=1.5,few_shot_relax_top_ratio=0.25,few_shot_relax_strategy=power,smooth_strategy=few_shot

# few-shot rank relax: assign relax factors from channel rank percentiles.
python -m cache_dit.generate flux2_klein_4b --quantize-config quant_type=svdq_int4_r128_dq \
  --svdq-config few_shot_steps=1,few_shot_relax_factor=1.5,few_shot_relax_top_ratio=0.25,few_shot_relax_strategy=rank,smooth_strategy=few_shot

# few-shot + deferred compile after runtime quantization completes.
python -m cache_dit.generate flux2_klein_4b --quantize-config quant_type=svdq_int4_r128_dq \
  --svdq-config few_shot_steps=1,few_shot_auto_compile=true,smooth_strategy=few_shot

# Tip: increase `few_shot_steps` from 1 to a larger number if you want to collect more
# transformer/module forwards before few-shot materialization. The counter is cumulative on the
# same armed module, so two runs of the same 50-step pipeline already contribute about 100
# forwards in total. Larger values can improve few-shot DQ accuracy, but they also increase the
# runtime quantization latency because more warmup forwards are needed before quantization happens.

Unlike the PTQ workflow, SVDQ dynamic quantization does not require calibrate_fn. The default identity mode runs directly in memory; identity, weight, and weight-inv modes may also set serialize_to and reload with load(). The few-shot mode remains in-memory only: it delays materialization to runtime and cannot be emitted as an offline checkpoint.

At the backend-config level, this means DQ currently supports identity by default, experimental weight / weight_inv heuristics, and the runtime-activated few_shot mode as explicit opt-ins. In the CLI, this is controlled by --svdq-config smooth_strategy=..., whose default value is identity. PTQ keeps the activation-derived strategy and serialized checkpoint workflow. We will support more smooth strategies in the future, and this separation makes it easier to add those as opt-in extensions without redefining the meaning of existing _dq quant types.

The CLI also exposes --svdq-config calibrate_precision=... for the SVDQ decomposition math. For DQ, the default remains low to preserve the shipped fast path, but users can now explicitly select medium or high when they want a different accuracy / quantization-time trade-off. The few-shot CLI also exposes the few_shot_steps, few_shot_relax_factor, few_shot_relax_top_ratio, few_shot_relax_strategy, and few_shot_auto_compile keys of --svdq-config. In the shared helper flow, top-level --compile-config 'transformer' is treated as a compatibility alias for few-shot runs, while few_shot_auto_compile=true is the precise switch that means "compile only after runtime quantization completes". The parser also accepts top_q4 as an alias of top, but fixed, top, auto, stable_auto, power, log, and rank are the canonical strategy names.

SVDQuant packed W1A4 / W2A4 / W3A4

These formats keep E2M1 activations and W4A4 Tensor Core compute, but store the residual weight in a smaller codebook before expanding it for the W4A4 kernel:

Type Ranks Stored residual codebook Weight payload excluding LoRA/smooth/padding
svdq_w1a4_r{rank}[_dq] 0, 32, 64, 128, 256, 512 Sign-only {-1.5,+1.5} 0.189 B/weight (0.252 with three stages)
svdq_w2a4_r{rank}[_dq] 0, 32, 64, 128, 256, 512 {-1.5,-0.5,+0.5,+1.5} 0.314 B/weight (0.377 with three stages)
svdq_w3a4_r{rank}[_dq] 0, 32, 64, 128 {-6,-3,-1.5,-0.5,+0.5,+1.5,+3,+6} 0.439 B/weight

Two-stage math (standard NVFP4 compatibility)

For a residual matrix R[N,K], every 16 consecutive K elements form a scale group g. The standard NVFP4 two-stage encoder writes one coarse scale per output channel and one FP8_E4M3 micro-scale per group:

\[ \begin{aligned} A_{n,g} &= \max_{k \in g} \left| R_{n,k} \right|, \\ s^{(c)}_{n} &= \operatorname{BF16}\!\left( \frac{\max_{g} A_{n,g}}{448\,C_b} \right), \\ s^{(g)}_{n,g} &= \operatorname{FP8}_{E4M3}\!\left( \frac{A_{n,g}}{s^{(c)}_{n} C_b} \right), \\ q_{n,k} &= \operatorname*{arg\,min}_{c \in Q_b} \left| \frac{R_{n,k}}{s^{(c)}_{n} s^{(g)}_{n,g}} - c \right|, \\ \hat{R}_{n,k} &= s^{(c)}_{n} s^{(g)}_{n,g} Q_b\!\left[ q_{n,k} \right]. \end{aligned} \]

C_b is the largest codebook magnitude: 6 for W3 and 1.5 for W1/W2. The factor 448 is the largest finite E4M3 value. s_c is rounded to BF16 before s_g and the codes are derived, because that is the exact factor the W4A4 epilogue applies. W3 stores a two-bit magnitude plane plus a separate sign plane; W1 stores only a sign bit; W2 stores sign plus one magnitude bit. W1 cannot represent zero inside a nonzero group and is therefore the experimental maximum-compression tier.

Three-stage math (default for W1/W2)

Default policy: two-stage W1/W2 have too few levels inside a 16-element group to produce meaningful images. For this reason packed_a4_stages=3 is the default for W1A4/W2A4; it is a precision requirement, not an optional tuning knob. W3 stores a 3-bit codebook with eight signed levels and is accurate enough on its own, so packed_a4_stages=2 remains its default to save memory; W3 stage 3 is only an optional accuracy experiment.

The three-stage codec keeps the two NVFP4 scales and adds 2-bit exponents, one per subgroup. The subgroup size defaults to 4 and can be set to 2 with svdq_kwargs={"packed_a4_inner_group": 2} for finer local refinement. A 4-element subgroup uses four exponents per 16 elements; a 2-element subgroup uses eight:

\[ \begin{aligned} s_b(q) &= \begin{cases} q, & b=1, \\ \left\lfloor q/2 \right\rfloor, & b=2, \end{cases} & a_b(q) &= \begin{cases} 0, & b=1, \\ q \bmod 2, & b=2, \end{cases} \\[4pt] m_1(a) &= 1.5, & m_2(a) &= \begin{cases} 0.5, & a=0, \\ 1.5, & a=1, \end{cases} \\[4pt] f_1(e) &= \begin{cases} 1/3, & e=0, \\ 1, & e=1, \\ 2, & e=2, \\ 4, & e=3, \end{cases} & f_2(e) &= \begin{cases} 1, & e=0, \\ 2, & e=1, \\ 4, & e=2,3, \end{cases} \\[4pt] T_b(e,q) &= (-1)^{s_b(q)}\, m_b(a_b(q))\, f_b(e), \\[4pt] \hat{R}_{n,k} &= s^{(c)}_{n} s^{(g)}_{n,g}\, T_b\!\left(e_{n,\lfloor k/G \rfloor}, q_{n,k}\right), \quad G \in \{2,4\}. \end{aligned} \]

The encoder tests all exponent tables for each subgroup, picks the table and code with the smallest squared error, and packs four 2-bit exponents into one uint8. The default 4-element subgroup covers 16 K elements per byte (wmicroscales, uint8 [N,ceil(K/16)]) and costs 0.5 bit/weight. The optional 2-element subgroup covers 8 K elements per byte (uint8 [N,ceil(K/8)]) and costs 1 bit/weight; W1 then totals 2.5 bit/weight and W2 3.5 bit/weight before the coarse scale. Every table value is already a legal E2M1 magnitude, so the exponent is folded into the B nibble during expansion; the MMA still sees exactly one scale per 16 K elements and there is no fourth runtime multiply. Explicit svdq_kwargs={"packed_a4_stages": 2} restores the standard two-stage format for compatibility or controlled comparisons.

# W1/W2 default to three stages.
pipe.transformer = cache_dit.quantize(
  pipe.transformer,
  QuantizeConfig(quant_type="svdq_w2a4_r512_dq"),
)

# Optional finer per-2 exponent grouping (W1/W2, three stages only).
pipe.transformer = cache_dit.quantize(
  pipe.transformer,
  QuantizeConfig(
    quant_type="svdq_w2a4_r32_dq",
    svdq_kwargs={"packed_a4_inner_group": 2},
  ),
)

# Explicit two-stage NVFP4-compatible storage.
pipe.transformer = cache_dit.quantize(
  pipe.transformer,
  QuantizeConfig(
    quant_type="svdq_w2a4_r512_dq",
    svdq_kwargs={"packed_a4_stages": 2},
  ),
)

The generate CLI accepts --quantize-config quant_type=svdq_w1a4_r{32|64|128|256|512}_dq, quant_type=svdq_w2a4_r{32|64|128|256|512}_dq, and quant_type=svdq_w3a4_r{32|64|128}_dq. --svdq-config packed_a4_stages=2 explicitly selects the legacy two-stage codec; packed_a4_stages=3 enables W3's optional per-8 selector (W1/W2 already default to 3); packed_a4_inner_group=2 selects the W1/W2 per-2 exponent layout while the default stays per-4. The converter accepts the same hyphenated quant types with BF16 source weights. PTQ omits _dq and uses the same calibrate_fn and activation-derived smoothing as SVDQ-FP8/W4A8. DQ and PTQ support serialize_to and cache_dit.load; the manifest precision is w1a4, w2a4, or w3a4.

Rank 512 is a quality-rescue option for W1/W2, not a free memory win. On FLUX.1-dev, the 494 quantized block linears contain 11.83B weights; rank 512 costs 2.75B LoRA parameters (23.2% of the block weights), rank 128 costs 5.8%, rank 64 costs 2.9%, and rank 32 costs 1.45%. With three stages enabled, the tested W2 ranks 32/64 already produce complete structure and readable text while retaining only about 4.46/4.78 GiB of persistent weights; W2 r512 reaches about 9.27 GiB on the same padded geometry. Rank 512 is therefore not the first choice for W2 unless additional prompts show a specific need for it. W3A4 r32 is 5.15 GiB and W4A4 r32 is 6.53 GiB.

W1A4 is currently retained only as an experimental sign-only tier: meaningful generation currently requires rank >= 256; lower ranks are not expected to produce a semantically useful image. Even at rank >= 256 quality is not guaranteed: in the sampled FLUX compile check, r256 with the default per-4 codec still showed severe artifacts, while r512 was the first verified meaningful result. Prefer W2A4 unless the goal is specifically to study the sign-only storage limit.

A sampled few-shot check (smooth_strategy="few_shot", few_shot_steps=2, stages 3, inner_group 2, compile) changes the boundary slightly but not the recommendation: W1 r32 still produced only color/structure noise (7.21s, 3.77 GiB), while W1 r64 produced a recognizable cat holding a sign (7.49s, 4.09 GiB) with imperfect text. Without few-shot, the same W1 r64 configuration collapsed into a blur. The few-shot path is experimental for packed A4; it defers quantization for two root forwards, resolves activation-derived smooth scales, then materializes the packed layers and compiles the quantized transformer.

The per-2 option doubles the exponent bytes. W2A4 r32 per-2 uses about 5.15 GiB and produced a valid image in the same FLUX compile check; W1A4 r32/r64 per-2 still did not produce a semantically valid image, so per-2 is not a substitute for switching W1 to W2. The per-4 layout remains the default and the recommended format for W2.

Optional W3 stage 3

W3A4 defaults to the two-stage 3.5-bit codec because its 3-bit codebook already has eight signed levels and is accurate enough. Passing svdq_kwargs={"packed_a4_stages": 3} or --svdq-config packed_a4_stages=3 opts into a lighter selector: one bit per eight K elements selects one of two legal-E2M1 magnitude tables, while the 3-bit W3 code still carries sign plus a two-bit magnitude index. The two tables are {0.5,2,4,6} and {0.5,1.5,3,6}.

  • Extra storage: +0.125 bit/weight; FLUX W3 r32/r64 go from 5.15/5.47 GiB to about 5.32/5.64 GiB.
  • Runtime: the selector adds one byte load and one table lookup per 32 weights; the E2M1 workspace and GEMM are unchanged.
  • Measured FLUX e2e: W3 r32 stage 3 is 6.34s versus 6.36s for stage 2. PSNR/SSIM against BF16 are 17.073/0.79439 versus 17.054/0.79424, while W4A4 r32 is 19.301/0.82608. The offline residual NMSE drops by about 34%, but the end-to-end gain is small because the residual codebook is not the only error source.

W3A4 stage 2 versus stage 3

Top-left is the BF16 reference, top-right is W3 r32 stage 2, bottom-left is W3 r32 stage 3 with the per-8 table selector, and bottom-right is W4A4 r32. The stage-3 result is structurally valid but visually close to stage 2; the small metric gain does not close the gap to W4A4.

W3 stage 3 is therefore an experimental accuracy option, not the default and not a replacement for W4A4.

Memory accounting: what is and is not moved to activations

W1A4/W2A4 do not move the codebook to the activation side. Activations always use the existing A4 path: packed E2M1 values, FP8 per-16 activation scales, and the BF16 LoRA-down activation. There is no per-token codebook index, exponent plane, or lookup buffer on activations. The 8/10-entry decode tables are compile-time constants and consume no model-sized HBM.

The codebook metadata is entirely weight-side: packed code, the per-16 FP8 group scale, the optional per-4 (or per-2) exponent, and the per-channel coarse scale. Relative to W4A4's 4 code bits + 0.5 scale bits, W2 three-stage uses 2 + 0.5 + 0.5 = 3 bits/weight, saving 1.5 bits per residual weight. On the 11.83B residual weights of FLUX.1-dev that is about 2.07 GiB less persistent weight than W4A4 at the same rank.

The only new runtime buffer is the expansion of the current layer's weight into standard E2M1 bytes. For a projection [N,K] that workspace is N*K/2 bytes; the largest FLUX projection is about 18 MiB. Peak memory is therefore approximately:

peak = persistent_weights + runtime_activations + one_layer_expansion_workspace

At the same rank, runtime_activations is identical between W4A4 and W1/W2/W3, so it cancels in the comparison. W2A4 r32 retains about 2.07 GiB less than W4A4 r32 and adds only the ~18 MiB transient buffer. If activations dominate total memory at very large batch or resolution, the absolute weight saving is unchanged; only its percentage of the total becomes smaller. LoRA rank is a separate variable: rank 512 adds about 5.1 GiB of BF16 LoRA and can outweigh the codec saving, so memory-friendly configurations should stay at rank 32/64.

Compile performance

Same-seed FLUX.1-dev, 1024², 28 steps, --compile-config 'transformer'; the table reports steady-state inference time (warmup excluded), speedup over BF16 compile, and persistent transformer-weight memory on one RTX PRO 5000 72GB. W2 uses three stages; W3/W4 use the standard two-stage codec. Memory covers the 494 quantized block linears: packed code, FP8/BF16 scales, three-stage exponents, BF16 LoRA and smooth factors with the runtime's padded geometry; it excludes activations, the transient expansion workspace, and biases.

Configuration Persistent weight memory Inference Speedup vs BF16 compile
BF16 22.04 GiB 14.83s 1.00x
W2A4 r32, three stages 4.46 GiB 6.33s 2.34x
W2A4 r64, three stages 4.78 GiB 6.60s 2.25x
W3A4 r32 5.15 GiB 6.36s 2.33x
W3A4 r64 5.47 GiB 6.66s 2.23x
W4A4 (NVFP4) r32 6.53 GiB 6.01s 2.47x
W4A4 (NVFP4) r64 6.85 GiB 6.19s 2.40x

The gallery below contains the six packed configurations for the same prompt and seed. The extra W4A4 r64 row is the same-rank reference for W2/W3 r64 and is not shown in the gallery. W2 uses ranks 32/64 with three stages, W3 uses ranks 32/64 with the standard two-stage codec, and W4 uses rank 32 in the image. Labels repeat the steady-state compile latency and persistent weight memory from the table. W1A4 is not included because none of the tested W1 configurations produced a semantically valid image.

Packed A4 compile comparison

W2A4 with three stages removes the low-bit blur at ranks 32/64 and reaches W3A4-level perceptual quality while using less persistent weight memory. W1A4 remains an experimental tier and is not a recommended deployment option.

Qwen-Image-2.1-Turbo at 2048²

The same six configurations on Qwen-Image-2.1-Turbo, 2048², fixed 8 steps, seed 0, --compile-config 'transformer', and --extra-config vae_tiling=true (required at this resolution to keep VAE decode within 72 GB):

Configuration Persistent weight memory Inference Speedup vs BF16
BF16 13.00 GiB 18.24s 1.00x
W2A4 r32, three stages 2.60 GiB 11.75s 1.55x
W2A4 r64, three stages 2.75 GiB 11.84s 1.54x
W3A4 r32 3.00 GiB 11.76s 1.55x
W3A4 r64 3.16 GiB 11.88s 1.54x
W4A4 (NVFP4) r32 3.82 GiB 11.21s 1.63x

Memory covers the 224 quantized block linears with the same padded geometry, 128x4 SF swizzle, BF16 LoRA/smooth factors and three-stage exponents as the runtime; it excludes non-quantized modules, activations, the transient expansion workspace and biases. W2/W3 remain 4.8–6.0% behind W4A4 at 2048², consistent with the 1024² FLUX result. W2/W3 are within about 1% of each other; rank 64 adds roughly 0.1s.

Qwen-Image-2.1-Turbo 2048 compile comparison

The expand kernel is vectorized: 32 K elements per thread, 32/64-bit packed loads, one aligned uint4 store, and a four-weight shared decode table instead of per-weight exponent branches. On the largest FLUX projection this reduced the NCU expand duration from about 73 us to 13 us and instructions from 64.3M to 6.2M. The per-call expand is still about 19 us under nsys; side-stream overlap hides part of it, but the residual e2e gap tracks the total expand work. W2/W3 remain about 5-8% behind the same-rank W4A4 compile baseline on FLUX and 4.8-6.0% behind on Qwen 2048². Closing that residual requires cross-layer prefetch, or a producer-warp TMA/cp.async packed decode inside the GEMM; consumer-side on-chip decode was measured at 4.7-4.9ms and is not viable. Both are intentionally deferred here to preserve the single-projection (~18 MiB) workspace contract.

The packed persistent tensors are never replaced by a full-model W4A4 copy. Forward expands only the current projection into a transient E2M1 workspace and overlaps that expansion with activation production on a side CUDA stream. This preserves the W4A4 GEMM path and fullgraph compile, at the cost of one projection-sized workspace. Fused MLP, DTensor/TP, layerwise offload, and alternate runtime selectors are rejected.

Quantized Pipeline Converter CLI

cache-dit-convert loads a floating-point diffusion pipeline, quantizes its transformer partition(s) and optionally its primary text encoder, and writes a complete deployable pipeline directory. cache_dit.generate and cache_dit.serve detect the manifest and restore the quantized components directly; no online re-quantization is needed.

Supported conversion paths:

  • TorchAO: float8_per_row, float8_per_tensor, float8_per_block, float8_weight_only, nvfp4, and nvfp4_weight_only.
  • Cache-DiT native: the three float8_* types with backend=cache_dit, and native nvfp4 with backend=cache_dit.
  • SVDQ: dynamic quantization types ending in _dq, without calibration data. PTQ still uses the Python calibration workflow because the converter has no calibration callback.

TorchAO INT8/INT4, MXFP4, and SVDQ smooth_strategy=few_shot are rejected by this checkpoint workflow. TorchAO and native FP8/NVFP4 checkpoints support TP and CP+TP: loading densifies the quantized linears, the regular TP plan shards the bf16 weights, and each rank then re-quantizes its local shard, so the shard-level scales can differ slightly from a single-GPU conversion.

Passing --parallel-config 'tp=N' to the converter bakes that layout in instead: the transformer is sharded first, each rank quantizes its own local shard, and the checkpoint stores per-rank slices under cache_dit_quant/transformer/tp{N}/rank{R}/ plus the layer plan in the component manifest. Loading such a checkpoint skips densification, re-quantization and planner replay, and only restores the slices, so startup no longer pays the per-layer quantization cost. Workers start automatically, so no manual torchrun is required. This baked path currently supports TorchAO NVFP4 checkpoints; other types keep the runtime TP path below. The checkpoint is bound to its TP degree: serving with another tp fails with an explicit error, while context parallelism stays a runtime choice (--parallel-config 'ulysses=2,tp=2').

CLI reference

python3 -m cache_dit.convert /path/to/FLUX.1-dev \
  --save-dir ./FLUX.1-dev-fp8 \
  --quantize-config 'float8_per_row,text:float8_weight_only'
Argument Required Default Description
MODEL_DIR yes — Source diffusers pipeline directory or Hub repository id, passed positionally.
--save-dir yes — Empty output directory for a complete copy, or MODEL_DIR itself for in-place quantization. The two directories must not contain one another.
--quantize-config yes — Transformer and optional text-encoder configuration, using the same grammar as generate, for example float8_per_row,text:float8_weight_only or nvfp4,backend=cache_dit.
--workflow modular only — Workflow used to load a ModularPipeline, for example t2va. It is rejected for an ordinary DiffusionPipeline.
--torch-dtype no bfloat16 Floating-point pipeline load dtype: float16, bfloat16, or float32. SVDQ FP8/W4A8/W1A4/W2A4/W3A4 require BF16 source weights.
--device no cuda Device used for quantization.
--parallel-config no — Bake a tensor-parallel layout into the checkpoint, for example tp=2. Only tp is accepted here; ulysses/ring and the VAE/text-encoder degrees are runtime-only. Turned into a per-rank checkpoint that must be served with the same tp.
--launcher no auto How TP conversion workers start when the command is not already under torchrun: auto and local both spawn one process per rank.
--svdq-config no — SVDQ options as k=v,k=v. Offline conversion accepts DQ only; few_shot cannot be serialized.
--verbose no false Print detailed per-layer quantization information.

--model-path and --quant-type remain as deprecated aliases for the positional model directory and --quantize-config. Do not combine the old and new spellings.

Usage examples

# TorchAO FP8 transformer and weight-only FP8 primary text encoder
python3 -m cache_dit.convert /path/to/FLUX.1-dev \
  --save-dir ./FLUX.1-dev-torchao-fp8 \
  --quantize-config 'float8_per_row,text:float8_weight_only'

# Cache-DiT native NVFP4 transformer
python3 -m cache_dit.convert /path/to/FLUX.1-dev \
  --save-dir ./FLUX.1-dev-native-nvfp4 \
  --quantize-config 'nvfp4,backend=cache_dit'

# SVDQ NVFP4 DQ with weight-derived smoothing
python3 -m cache_dit.convert /path/to/FLUX.1-dev \
  --save-dir ./FLUX.1-dev-svdq-nvfp4 \
  --quantize-config 'svdq_nvfp4_r32_dq' \
  --svdq-config 'smooth_strategy=weight,calibrate_precision=medium'

# Modular T2VA pipeline
python3 -m cache_dit.convert MiniMaxAI/MiniMax-H3 --workflow t2va \
  --save-dir ./MiniMax-H3-torchao-nvfp4 \
  --quantize-config 'nvfp4,text:float8_weight_only'

# In-place quantization when the source checkpoint is too large to copy
python3 -m cache_dit.convert /path/to/MiniMax-H3 --workflow t2va \
  --save-dir /path/to/MiniMax-H3 \
  --quantize-config 'nvfp4,text:float8_weight_only'

# Bake TP=2 into the checkpoint (workers start automatically)
python3 -m cache_dit.convert /path/to/FLUX.1-dev \
  --save-dir ./FLUX.1-dev-nvfp4-tp2 \
  --quantize-config 'nvfp4' \
  --parallel-config 'tp=2'

Copy and in-place conversion

With different MODEL_DIR and --save-dir paths, the converter copies the complete source directory before loading and quantizing the copied pipeline. The copy includes unquantized weights, pipeline configs, tokenizers, schedulers, custom Python code, assets, and other workflow partitions. Hub inputs are first resolved to a complete local snapshot; the converter checks the Hub cache space before downloading it.

Before copying, the converter checks available space for the complete source copy plus a conservative reserve derived from the components being quantized. If space is insufficient, it exits before copying and suggests using the source directory as --save-dir.

With --save-dir MODEL_DIR, the converter quantizes in place:

  • No source file is copied, deleted, or rewritten.
  • Existing float weights remain on disk.
  • Only cache_dit_quant/ and the root quant_manifest.json are added.
  • Source file size and modification-time signatures are checked before the manifest is written.

In-place mode avoids the extra full copy, but it increases total disk usage because both float and quantized weights remain. At runtime, the quantized components are restored from cache_dit_quant/; their original float weights are not loaded into memory.

A failed conversion can leave a partial output directory or cache_dit_quant/ without a manifest. Inspect and remove that partial output before retrying; the converter does not delete it automatically.

Checkpoint layout and loading

Both modes use cache_dit_quant/ for quantized component configs, manifests, and weights. In independent mode, the copied float weights of quantized components are removed only after every source file has been verified byte-for-byte. In-place mode keeps those float weights.

SAVE_DIR/
├── model_index.json                 # copied unchanged; or modular_model_index.json
├── quant_manifest.json              # written last; source model and component entries
├── transformer/
│   └── config.json                  # copied unchanged in both modes
├── vae/
│   └── ...                          # unquantized weights copied unchanged
├── assets/
│   └── ...                          # assets and custom code copied unchanged
└── cache_dit_quant/
    └── transformer/
        ├── config.json              # config used to rebuild the quantized component
        ├── component_manifest.json
        ├── weights.safetensors      # TorchAO and native FP8/NVFP4
        ├── buffers.safetensors      # optional non-persistent buffers
        └── attributes.safetensors   # optional direct tensor attributes, including RoPE state

Independent mode removes only files recognized as model weights by diffusers, plus their shard index files. Other files in a quantized component directory, including custom code and non-weight tensor assets, are preserved. The full byte comparison is intentionally strict and reads the copied model files once before deletion.

An SVDQ component instead stores {quant_type}.safetensors plus quant_config.json, and may include base.safetensors for unquantized weights. Tensor attributes and non-persistent buffers are restored alongside every format; loading fails if any parameter, buffer, or saved tensor attribute remains on the meta device.

Pass the pipeline directory directly to either CLI and add acceleration flags normally:

python3 -m cache_dit.generate ./FLUX.1-dev-torchao-fp8 \
  --cache-config 'DBCache,rdt=0.12' --compile-config 'transformer' \
  --sampling-config 'height=1024,width=1024,steps=28,seed=0' \
  --save-path ./flux-reloaded.png

python3 -m cache_dit.serve ./FLUX.1-dev-torchao-fp8 \
  --cache-config 'DBCache,rdt=0.12' --compile-config 'transformer' --port 8000

The manifest's source_model is model-selection and provenance metadata only. It is never used to load runtime weights or components. Quantized components and copied non-quantized components load from the current checkpoint directory, including after the directory is moved and the original source is removed. Ordinary pipelines use local-only loading; Modular pipelines bind locally present components to the current directory and leave external component specs unchanged. A Modular source that requires additional external repositories must have those components included in MODEL_DIR for a self-contained result.

Do not pass --quantize-config again: quantized checkpoints reject a second quantization pass. For SVDQ checkpoints, only the runtime-only runtime_kernel and lora_layout overrides are accepted through --svdq-config; quantization algorithms, devices, smoothing, and fused-MLP settings are fixed by the checkpoint.

cache_dit.load also accepts an individual cache_dit_quant/<component>/ directory containing component_manifest.json. The legacy SVDQ checkpoint file/directory forms remain supported. LoRA must be fused before conversion, and device_map=balanced is not supported for pre-quantized pipeline components.

SVDQ Runtime Kernel

The SVDQ W4A4 entry points are organized around two orthogonal selectors: runtime (which backend family runs) and lora_layout (which layout the LoRA-down activation D is stored in).

  • runtime: native | cute | flashinfer | flashinfer+cute-dsl | flashinfer+cutlass-sm120. None/native selects the single native W4A4 GEMM for both INT4 and NVFP4; the rest are NVFP4-only. Bare flashinfer maps to flashinfer+cutlass-sm120.
  • lora_layout: native | row_major. native consumes the producer's packed FP32 MMA-fragment D, while row_major consumes row-major BF16 D with the per-rank scales already folded in. For runtime="cute", the default (None) is row_major; other runtimes default to native. fused_mlp does not change that default: the fused epilogue writes either layout.

Only four combinations are legal: native+native, cute+native, cute+row_major, and flashinfer*+native. runtime="native" accepts nothing but lora_layout="native", enforced in both the public wrapper and the op implementation. lora_layout="row_major" is accepted with fused_mlp as well: the CuTe fused epilogue stages the next layer's down-projection slice in shared memory, accumulates the LoRA-down term in an FP32 scratch, and rounds it into the row-major BF16 D, so a fused GELU MLP chain can stay entirely on the CuTe runtime. Both fused passes work on either layout: the gate of a SwiGLU block is applied by whichever producer the layout selects (native or CuTe row-major). Because the row-major finalize folds one scale per 16-rank group into the next layer's D and the ABI has no channel for that layer's scales, a fused row-major chain requires identity per-rank scales, which is what the operator synthesizes when lora_scales is omitted. Every flashinfer runtime (flashinfer, flashinfer+cute-dsl, flashinfer+cutlass-sm120) runs FlashInfer's own chain, so lora_layout is unused and stays native.

Both selectors are configurable through svdq_kwargs and are carried into every quantized SVDQW4A4Linear layer at runtime (the per-rank lora_scales contract is a kernel-internal detail; checkpoints do not store it). Explicit lora_layout="native" preserves the fragment-D behavior with either runtime. Older cute checkpoints whose metadata omits the layout now resolve to row_major; producer and consumer switch together, but D changes from packed FP32 to BF16 and is not expected to remain bitwise identical to the old execution path.

# Default: runtime and layout are resolved automatically (native runtime + native D).
quant_config = QuantizeConfig(
  quant_type="svdq_int4_r128_dq", # _r{rank}, e.g., r16, r32, r64, r128, etc.
  svdq_kwargs={"runtime_kernel": "native"},  # optional: native is already the default.
)

# CuTe NVFP4 with the row-major BF16 D contract (SM120): the fastest path on
# rank <= 64 in the tables below. Requires NVFP4 + runtime_kernel="cute".
quant_config = QuantizeConfig(
  quant_type="svdq_nvfp4_r64_dq",
  svdq_kwargs={"runtime_kernel": "cute", "lora_layout": "row_major"},
)

The generate CLI exposes both selectors through --svdq-config: runtime_kernel=... for the backend family and lora_layout=... for the D contract (omitting runtime_kernel keeps the same native default):

python3 -m cache_dit.generate flux --quantize-config quant_type=svdq_int4_r64_dq \
  --svdq-config runtime_kernel=native --compile-config 'transformer'
python3 -m cache_dit.generate flux --quantize-config quant_type=svdq_nvfp4_r32_dq \
  --svdq-config runtime_kernel=cute,lora_layout=row_major --compile-config 'transformer'
# FlashInfer comparison runtimes (optional dependency, never the default).
# Bare `flashinfer` == `flashinfer+cutlass-sm120` (ranks 32/64, SM120 only).
python3 -m cache_dit.generate flux --quantize-config quant_type=svdq_nvfp4_r32_dq \
  --svdq-config runtime_kernel=flashinfer
python3 -m cache_dit.generate flux --quantize-config quant_type=svdq_nvfp4_r32_dq \
  --svdq-config runtime_kernel=flashinfer+cute-dsl
python3 -m cache_dit.generate flux --quantize-config quant_type=svdq_nvfp4_r128_dq \
  --svdq-config runtime_kernel=flashinfer+cute-dsl
# Fused MLP: works on both runtimes and both D layouts.
python3 -m cache_dit.generate flux --quantize-config quant_type=svdq_nvfp4_r32_dq \
  --svdq-config fused_mlp=true
python3 -m cache_dit.generate flux --quantize-config quant_type=svdq_nvfp4_r32_dq \
  --svdq-config runtime_kernel=cute,fused_mlp=true

When loading a serialized checkpoint with a QuantizeConfig, an explicitly requested runtime_kernel / lora_layout overrides the value recorded in the checkpoint, since both are pure runtime dispatch choices that do not change the serialized tensors.

Historical INT4 measurements may still label earlier implementation variants. Those labels describe kernel implementations used for comparison, not accepted runtime_kernel configuration values; the native runtime now has exactly one W4A4 GEMM implementation.

The NVFP4 CuTe runtime is an independent workflow. Its activation/LoRA-down producer writes a 256-row interleaved E2M1 activation pack that matches the native packed layout, including activation scales and row-major BF16 LoRA activations. The GEMM loads activation A/SFA gmem-to-register (G2R), while weight B/SFB and BF16 D/L1 use TMA over shared memory, and fuses the BF16 LoRA-up correction into the same FP32 accumulator. It does not call the native activation quantizer or consume the native packed FP32 D. The current producer dispatch uses a fused in-CTA reduction for rank32 above M=8192 and for rank64 with padded M<=512 and K<=3072. Rank128 with padded M<=256 and K<=3072 uses a K128 async split-K schedule; other split-K shapes retain their existing K256/K128 dispatch. Split-K maintains its own FP32 scratch and runs a separate BF16 finalize kernel. The padded batch must be a multiple of 256. Legacy checkpoints are converted to the CuTe weight-side pack once at load time; the serialized native state dict remains unchanged.

FlashInfer comparison runtime

The flashinfer runtimes run FlashInfer's own NVFP4 SVDQuant chain (nvfp4_quantize_smooth → BF16 LoRA-down GEMM → fused W4A4 residual + LoRA-up GEMM) instead of a cache-dit kernel. They exist so the same checkpoint can be timed against FlashInfer end to end; they are never selected automatically. The chain is part of the runtime name:

runtime FlashInfer chain coverage
flashinfer, flashinfer+cutlass-sm120 fused quantize + LoRA-down prefix, then the CUTLASS K3 GEMM ranks 32/64, SM120 (12.0) only; JIT-builds a CUTLASS module on first use
flashinfer+cute-dsl one CuTe implementation per shape (quantize → torch.mm → fused GEMM) every rank the SVDQ runtime accepts
  • The checkpoint is unchanged: FlashInfer's pack is derived once at load time from the native pack (qweight nibbles are unpacked to row-major E2M1, and the per-output-channel wcscales is folded into the per-block FP8 scale). Nothing extra is serialized.
  • That fold re-encodes one FP8 block scale, so the layer output differs from native/cute by a small but measurable amount (about rel_l2 = 1e-1 at rank 32 with random weights); the LoRA branch stays exact. Treat these runtimes as timing baselines, not as evidence about FlashInfer's numerical behavior on its own pack. A block whose folded scale falls below the E4M3 subnormal range rounds to zero and is dropped; the load path logs how many blocks that affects.
  • The per-forward activation global scale is a safe upper bound, 448 * 6 / (max|x| * max|smooth|), instead of an exact amax(x * smooth): it costs one fused reduction instead of a full smoothing pass (~61% cheaper) and can only shrink the FP8 block scales, never overflow them. It moves the layer rel_l2 against native by about +1%.
  • They require NVFP4 + BF16, rank > 0 and rank % 32 == 0, and they are rejected in combination with fused_mlp, layerwise_offload, and tensor parallelism. The call is excluded from torch.compile graphs, so --compile-config 'transformer' does not capture it.
  • Asking for a rank the CUTLASS chain does not cover is an error, not a fallback: use flashinfer+cute-dsl for ranks 96/128 or on SM121.

Performance comparison (native vs cute vs FlashInfer)

The following benchmarks come from PR #1259, measured on an RTX PRO 6000 Blackwell (SM120) with CUDA 13.0.88, torch 2.10.0+cu130, bench_svdquant.py, warmup 10 / iters 50, median of CUDA events (µs). flashinfer cute-dsl is FlashInfer 0.7.3.dev20261106 running on its own 128x4 pack; the cache-dit rows share the native-producer pack unless marked row-major. These rows therefore measure FlashInfer's kernel on FlashInfer's own pack — not the runtime_kernel="flashinfer" path, which runs the whole chain on a pack derived from the cache-dit checkpoint.

Kernel-only GEMM

M,N,K rank native cute (native D) cute (row-major D) flashinfer cute-dsl
4096,3072,3072 32 117.81 115.10 112.19 148.78
4096,3072,3072 64 121.50 118.19 114.00 149.58
4096,3072,3072 128 128.40 127.90 119.12 157.49
8192,3072,3072 32 183.38 176.11 174.62 205.39
8192,3072,3072 64 188.64 183.38 178.10 207.14
8192,3072,3072 128 200.03 198.72 185.57 215.65
4096,6144,3072 32 182.75 175.98 173.49 201.49
4096,6144,3072 64 189.30 184.26 177.23 207.90
4096,6144,3072 128 200.50 197.26 185.62 218.14
8192,6144,3072 32 343.41 326.91 310.40 361.18
8192,6144,3072 64 337.57 321.63 305.90 327.41
8192,6144,3072 128 364.38 346.16 328.29 345.47
16384,8192,8192 32 1590.74 1634.34 1600.50 1571.23
16384,8192,8192 64 1621.04 1654.27 1620.72 1658.22
16384,8192,8192 128 1682.77 1715.42 1660.46 1690.32

CuTe with row-major D is the fastest kernel in 14 of 15 cells (−0.02% to −9.9% vs native); FlashInfer's cute-dsl kernel is the slowest in 11 of 15 cells (+2.3% to +26.3%) and only wins 16384x8192x8192 rank 32 by 1.2%.

Producer and end-to-end

M,N,K rank quantize (native D) quantize-row-major e2e native e2e cute e2e cute+row-major
4096,3072,3072 32 41.79 36.96 143.46 140.37 129.17
4096,3072,3072 128 56.51 68.80 167.25 167.54 168.62
8192,6144,3072 32 58.06 54.11 400.64 367.82 350.27
8192,6144,3072 128 82.83 119.82 459.30 437.76 450.94
16384,8192,8192 32 297.09 269.12 1895.12 1906.40 1849.30
16384,8192,8192 64 374.62 295.87 1991.04 1993.25 1917.74
  • The CuTe producer wins at rank 32 (−7% to −12%) but loses at rank 128 (+22% to +45%), so e2e prefers row-major up to rank 64 and the native-fragment path at rank 128.
  • Quantize is 14–31% of e2e, so kernel-only numbers overstate the win.
  • Measured e2e is slightly below quantize + gemm because the packs stay alive during the GEMM and the allocator reuses the same blocks.

All three cache-dit paths agree numerically: rel_l2 against native is 3.1–3.3e-3 at every shape and rank, kernel-only and e2e. FlashInfer uses its own 128x4 pack, so it is reported as finite only. The flashinfer runtimes derive their pack from the checkpoint instead, so their per-layer rel_l2 against native is about 1e-1 — expected, and the reason they are documented as comparison runtimes.

SVDQ with Fused MLP

When SVDQ quantizes a diffusers transformer whose FeedForward blocks use plain GELU activation, the default execution path runs three GPU kernels per MLP block: the first quantized GEMM, a separate GELU activation kernel, and the second quantized GEMM. Enabling fused MLP combines the first GEMM and GELU into a single kernel (gemm_w4a4): the activated tile is quantized in-register into the 4-bit activation pack that the second GEMM consumes, and the next layer's LoRA-down term is reduced in the same kernel, eliminating one kernel launch and one full-size HBM write per block. Both runtimes implement it, so the whole chain can stay on runtime_kernel="cute" with either lora_layout.

The feature is controlled by svdq_kwargs["fused_mlp"] and works automatically with most diffusers transformer families — no per-model configuration is needed.

Quick start (CLI)

# Add --svdq-config fused_mlp=true to any SVDQ generate command:
python -m cache_dit.generate longcat_image_edit \
  --quantize-config quant_type=svdq_int4_r128_dq --svdq-config fused_mlp=true

[06-09 02:56:25] [Cache-DiT] No caching or parallelism is applied.
[06-09 02:56:25] [Cache-DiT] Quantizing transformer module: LongCatImageTransformer2DModel to svdq_int4_r128_dq ...
[06-09 02:57:24] [Cache-DiT] ✅ Applying pass fused_gelu_mlp to 20 target(s).
[06-09 02:57:24] [Cache-DiT] ✅ Applying pass fused_gelu_proj to 20 target(s).
[06-09 02:57:24] [Cache-DiT] --------------------------------------------------------------------------------------------
[06-09 02:57:24] [Cache-DiT] SVDQuant    Region: ['LongCatImageTransformerBlock', 'LongCatImageSingleTransformerBlock']  |
[06-09 02:57:24] [Cache-DiT] SVDQuant      Type: svdq_int4_r128_dq                                                       |
[06-09 02:57:24] [Cache-DiT] SVDQuant      Rank: 128                                                                     |
[06-09 02:57:24] [Cache-DiT] Quantized   Layers: 260 / 260                                                               |
[06-09 02:57:24] [Cache-DiT] Skipped     Layers: 0                                                                       |
[06-09 02:57:24] [Cache-DiT] Linear      Layers: 260                                                                     |
[06-09 02:57:24] [Cache-DiT] --------------------------------------------------------------------------------------------
Baseline SVDQ QD Rank=128 + Few-Shot SVDQ QD Rank=128 + Few-Shot + Fused MLP
89s 58s 56s

Quick start (Python API — dynamic quantization)

import torch
import cache_dit
from diffusers import FluxPipeline
from cache_dit.quantization import QuantizeConfig

pipe = FluxPipeline.from_pretrained(
    "black-forest-labs/FLUX.1-dev",
    torch_dtype=torch.bfloat16,
).to("cuda")

quant_config = QuantizeConfig(
    quant_type="svdq_int4_r32_dq",
    svdq_kwargs={"fused_mlp": True},
)
pipe.transformer = cache_dit.load(pipe.transformer, quant_config)

image = pipe("A cat holding a sign that says hello world").images[0]
image.save("flux_fused_mlp.png")

Quick start (Python API — PTQ with serialized checkpoint)

quant_config = QuantizeConfig(
    quant_type="svdq_int4_r32",
    serialize_to="./flux-svdq/",
    svdq_kwargs={"fused_mlp": True},
    calibrate_fn=my_calibrate_fn,
)
cache_dit.quantize(pipe.transformer, quant_config)

# Later, at inference time:
pipe.transformer = cache_dit.load(
    pipe.transformer,
    "./flux-svdq/svdq_int4_r32.safetensors",
)

When fused_mlp is enabled, cache-dit applies four complementary passes:

Pass Targets Fusion
fused_gelu_mlp Standard non-gated FeedForward and nested GELU chains fc1 + tanh-GELU + fc2 (qout path, no fp16 HBM write)
fused_gelu_proj Single-stream blocks with concat MLP fc1 + tanh-GELU only (fp16 output, concat unchanged)
fused_swiglu_mlp SiLU-gated MLPs, including FLUX.2/3 standalone gate-first FFNs gate applied inside the activation producer
fused_geglu_mlp Value-first packed GEGLU FeedForward blocks exact/tanh GELU gate inside the activation producer

All passes use structural detection with standalone/geometry guards. Unsupported blocks remain on the original forward path and are reported through the pass skip statistics.

Gated MLPs (SwiGLU and GEGLU)

The gate is fused into the activation producer of down instead of the GEMM epilogue, because its second operand comes from a different projection. This replaces the standalone activation/multiply kernel and its [tokens, hidden] HBM round trip. Both native and CuTe producers support silu, gelu_tanh, and exact gelu. SiLU remains the default; GEGLU uses the producer's value-first packed layout. FLUX.2/3 standalone FFNs explicitly select gate-first order for their [gate | value] projection, while packed QKV+MLP blocks remain outside this pass.

# Qwen-Image-2.1 style gated MLP on the CuTe GEMM with its default row-major D contract.
python3 -m cache_dit.generate qwen_image_21_turbo --quantize-config quant_type=svdq_nvfp4_r32_dq \
  --svdq-config runtime_kernel=cute,fused_mlp=true