Skip to content

Weight quantization: RTN, GPTQ, AWQ, HQQ and SmoothQuant

At a glance

Weight-only RTN / GPTQ / AWQ quantization to int2-8 or fp8 (see QuantConfig).

Registered name Family Saves Lossless Trainable Configuration
quant weight-compression weight memory or latency no no QuantConfig

Backends (default configuration): transformers: no · gguf: real · mlx: untested · onnx: real · sglang: real · trtllm: no · vllm: real

quant stores the weights of the linear maps in the decoder layers in a low-bit format: int2, int3, int4 or int8 with one scale (and, unless symmetric=True, one zero point) per group of group_size input columns, fp8 (e4m3), or the 4-bit floating-point formats nvfp4 and mxfp4. The embeddings, the norms and the LM head stay in full precision. The method decides how weights are rounded to the grid. rtn rounds to the nearest grid point and hqq refines the zero points by half-quadratic optimization, both without data. GPTQ (Frantar et al., 2023) quantizes one column at a time and spreads the rounding error over the remaining columns through the inverse Hessian of the calibration inputs. AWQ (Lin et al., 2024) searches per-input-channel scales from the activation magnitudes, folds them into the preceding norm or linear map, and then searches clipping thresholds. SmoothQuant (Xiao et al., 2023) moves activation outliers into the weights for W8A8, where the inputs are quantized as well. Nothing is trained, and the result is lossy.

The backend decides how the codes are stored and multiplied. The default auto takes the fastest installed kernel that stores the format and group size and runs on the model's device and dtype: vLLM's Machete (int4 and int8 on Hopper), Marlin (int4, int8 and fp8 weight-only GEMMs on sm80+), CUTLASS (int8 by int8 with activations="int8") or torchao (tinygemm int4, int8, fp8). When none of them fits, it raises a ConfigError with each kernel's reason and the package to install (economize[vllm] or economize[quant]). A format that no kernel stores, such as int3, is refused when the configuration is built. Each kernel can also be named directly. compressed-tensors is export-only: it records the codes for a checkpoint that vLLM and SGLang serve with their own kernels, and the quantized model refuses a forward pass in PyTorch, since its dense weights would spend the unquantized model's memory and time. Quantization rewrites the base weights in place, so the technique cannot be detached.

Setup

import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

import economize

device = "cuda" if torch.cuda.is_available() else "cpu"
base = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B", dtype=torch.bfloat16, device_map=device)
tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-0.5B")
ids = tokenizer("Natalia sold clips to 48 of her friends in April, and then she sold half as many clips in May. "
                "How many clips did Natalia sell altogether?", return_tensors="pt").input_ids.to(device)

Training data is a flat file of uint32 token ids, the format of nanoGPT-style pretraining shards, and calibration data is a [N, S] tensor of token ids. Both are made here from GSM8K:

import numpy as np
from datasets import load_dataset

texts = [f"{row['question']}\n{row['answer']}" for row in load_dataset("openai/gsm8k", "main", split="train")]
tokens = np.concatenate([tokenizer(t + tokenizer.eos_token).input_ids for t in texts]).astype(np.uint32)
tokens[: len(tokens) * 9 // 10].tofile("train.bin")
tokens[len(tokens) * 9 // 10 :].tofile("val.bin")

calibration = torch.from_numpy(tokens[: 128 * 2048].astype(np.int64)).view(128, 2048)

Quantization changes the base model, so measure the full-precision perplexity first:

from economize.train import fixed_windows

windows = fixed_windows("val.bin", 64, 1024).cuda()


@torch.no_grad()
def perplexity(model, windows):
    return torch.stack([model(w[None], labels=w[None]).loss for w in windows]).float().mean().exp().item()


dense_ppl = perplexity(base, windows)

Quick start

Round-to-nearest int4 with groups of 128 columns needs no calibration data:

from economize.techniques.quant import QuantConfig

model = economize.apply(base, QuantConfig(format="int4", method="rtn", group_size=128))

summary = model.techniques["quant"].summary
print(summary["modules"], summary["bits_per_weight"])   # quantized maps, storage bits including scales and zeros
print(summary["kernel"])                                 # the kernel that backend="auto" chose
print(dense_ppl, perplexity(model, windows))

bits_per_weight counts the codes, the scales and the zero points, so int4 with groups of 128 stores a little more than 4 bits per weight. For a bf16 model with vLLM installed, auto chooses Marlin on an A100 and Machete on an H100, and without vLLM torchao's tinygemm kernel. (The page's tests run on a CPU, where no int4 kernel exists, with the dequantized reference of the test suite, which computes the same numbers.)

Methods

GPTQ and AWQ read the calibration tensor, one decoder layer at a time. Every new run needs an unmodified base model:

base = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B", dtype=torch.bfloat16, device_map="cuda")
model = economize.apply(base, QuantConfig(format="int4", method="gptq", group_size=128, act_order=True),
                        calibration=calibration)
print(perplexity(model, windows))

base = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B", dtype=torch.bfloat16, device_map="cuda")
model = economize.apply(base, QuantConfig(format="int4", method="awq", group_size=128), calibration=calibration)
print(perplexity(model, windows))

act_order=True quantizes the columns of GPTQ by decreasing Hessian diagonal, and percdamp sets its damping. awq_grid and awq_clip control AWQ's scale and clipping search, hqq_iters and hqq_lp_norm HQQ's refinement. group_size=None uses one scale per output channel. Options that the chosen method or backend does not read raise a ConfigError when they differ from their defaults.

Kernels and the saving

Every backend that runs in PyTorch realizes the saving. torchao's int8 W8A8 path (per-channel symmetric weights, inputs quantized per token, int8 by int8 matrix products) runs on the CPU as well as on CUDA GPUs:

base = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B", dtype=torch.bfloat16, device_map="cuda")
model = economize.apply(base, QuantConfig(format="int8", group_size=None, symmetric=True, activations="int8",
                                          backend="torchao"))
print(perplexity(model, windows), model.simulations())

The low-bit GPU kernels need CUDA: torchao int4 (tinygemm, sm80+, bf16), Marlin (int4, int8 and fp8 weight-only GEMMs, sm80+), Machete (int4 and int8 on sm90) and CUTLASS (int8 by int8, with activations="int8"):

base = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B", dtype=torch.bfloat16, device_map="cuda")
model = economize.apply(base, QuantConfig(format="int4", method="gptq", group_size=128, backend="marlin"),
                        calibration=calibration)

Saving and loading

A checkpoint stores the configuration. Loading quantizes an unmodified base model again with the same calibration data:

model.save_pretrained("qwen-int8")

base = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B", dtype=torch.bfloat16, device_map="cuda")
model = economize.load(base, "qwen-int8")

Serving

The compressed-tensors backend records the codes, and export_compressed_tensors writes a quantized checkpoint whose size on disk shows the memory saving:

from pathlib import Path

import economize.integrations.compressed_tensors as ct

base = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B", dtype=torch.bfloat16, device_map="cuda")
quantized = economize.apply(base, QuantConfig(format="int4", method="gptq", group_size=128,
                                              backend="compressed-tensors"), calibration=calibration)
ct.export_compressed_tensors(quantized, "qwen-int4-ct")
print(sum(f.stat().st_size for f in Path("qwen-int4-ct").glob("*.safetensors")) / 2**20, "MiB")

vllm serve qwen-int4-ct serves it with vLLM's Marlin or Machete kernels. economize.backends.vllm.serving.to_vllm writes the same export for a model that combines quant with other techniques, together with the engine arguments:

from economize.backends.vllm import serving

plan = serving.to_vllm(quantized, "out/qwen-int4")
print(plan.serve_args())
llm = plan.llm()

Combining with other techniques

quant runs last among the weight transforms, so it quantizes the weights that pruning, low rank or a Hadamard rotation produced. A rotation before GPTQ removes outlier channels from the inputs it quantizes (Hadamard rotations). The sparse kernels of TEAL, CATS and Deja Vu read dense floating-point weights, so they are refused next to packed quantized weights. Removing whole layers first leaves fewer maps to quantize:

from economize.techniques.prune import DepthPruneConfig

print(economize.compatible("quant", "depth_prune"), economize.compatible("quant", "teal"))
base = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B", dtype=torch.bfloat16, device_map="cuda")
model = economize.apply(base, DepthPruneConfig(method="shortgpt", num_blocks=4),
                        QuantConfig(format="int4", method="gptq", group_size=128), calibration=calibration)

Configuration

QuantConfig dataclass

QuantConfig(format: str = 'int4', method: str = 'rtn', group_size: int | None = 128, symmetric: bool = False, backend: str = 'auto', targets: tuple[str, ...] = ('*',), exclude: tuple[str, ...] = (), layers: tuple[int, ...] = (), act_order: bool = False, static_groups: bool = True, true_sequential: bool = True, blocksize: int = 128, percdamp: float = 0.01, keep_zeros: bool | None = None, awq_grid: int = 20, awq_clip: bool = True, hqq_iters: int = 20, hqq_lp_norm: float = 0.7, hqq_beta: float = 10.0, hqq_round_zero: bool = False, hqq_integer_zero: bool = False, smooth_alpha: float = 0.5, fp8_activations: bool = False, activations: str | None = None, offload: bool = False)

Weight-only quantization of the linear maps of the decoder layers (the LM head stays in full precision).

Parameters:

Name Type Description Default
format str

Registered number format: "int4" (default), "int8", "int3", "int2", "fp8" (e4m3, absmax scale), or the FP4 microscaling formats "nvfp4" and "mxfp4" (:mod:.fp4).

'int4'
method str

"rtn" (round to nearest, no data), "hqq" (half-quadratic zero points, no data), "gptq", "awq" or "smoothquant" (these need calibration data); see :mod:.methods.

'rtn'
group_size int | None

Input columns per scale (None: one scale per output channel).

128
symmetric bool

Integer grids without a zero point.

False
backend str

"auto" (default: the fastest installed real kernel for the format, group size, device and dtype, among Machete, Marlin, CUTLASS and torchao; an error names the packages to install when none fits, :mod:.auto), "torchao" (torchao kernels), "marlin" (vLLM's Marlin weight-only GEMM, the fast int8 / fp8 path on A100), "machete" (vLLM's Machete int4 / int8 GEMM on H100), "cutlass" (vLLM's CUTLASS int8 x int8 GEMM, W8A8 with activations="int8") or "compressed-tensors" (export-only: the codes for a compressed-tensors checkpoint served by vLLM or SGLang; the model does not run in PyTorch, :mod:economize.integrations.compressed_tensors); see :mod:.backends.

'auto'
targets tuple[str, ...]

Globs over linear-module names inside a layer.

('*',)
exclude tuple[str, ...]

Globs removed from targets.

()
layers tuple[int, ...]

1-indexed layers to quantize; empty means all.

()
act_order bool

GPTQ: quantize columns by decreasing Hessian diagonal.

False
static_groups bool

GPTQ with act_order and groups: fit the groups on contiguous columns first, so they stay contiguous (default, runs on every backend); False is the reference's plain act_order, whose permuted groups no registered kernel stores (refused).

True
true_sequential bool

GPTQ: quantize the maps that share an input together, in call order.

True
blocksize int

GPTQ lazy-update block.

128
percdamp float

GPTQ relative Hessian damping.

0.01
keep_zeros bool | None

GPTQ and HQQ: keep exactly-zero (pruned) weights at zero (None: when at least 5% of a weight is exactly zero; see :mod:.gptq and :mod:.hqq).

None
awq_grid int

AWQ: number of scale exponents and clipping ratios searched (20 in the paper).

20
awq_clip bool

AWQ: search per-group clipping thresholds.

True
hqq_iters int

HQQ: maximal number of proximal steps (20 in the reference).

20
hqq_lp_norm float

HQQ: exponent p of the error norm (0.7).

0.7
hqq_beta float

HQQ: half-quadratic penalty weight (10).

10.0
hqq_round_zero bool

HQQ: round the initial zero points (the reference's round_zero).

False
hqq_integer_zero bool

HQQ: round the final zero points, for backends without float zero points (Marlin, Machete, compressed-tensors); the reference keeps them real.

False
smooth_alpha float

SmoothQuant: migration strength alpha of the scales max|x|^alpha / max|w|^(1-alpha) (0.5 in the paper, 0.8-0.9 for models with strong outliers).

0.5
fp8_activations bool

torchao fp8: also quantize activations per row and run _scaled_mm (W8A8, sm89+).

False
activations str | None

Also quantize the inputs of the quantized linear maps with this registered scheme (:mod:.activations): "int8" (dynamic per token; with int8 per-channel symmetric weights this is W8A8, which the torchao backend runs on torch._int_mm and vLLM on its CUTLASS int8 GEMM) or "int4" (W4A4, simulated only). None (default): weight-only.

None
offload bool

Keep calibration activations on the CPU between layers.

False

The fields in :attr:method_options are read by some methods only (each method lists its own in :attr:~.methods.QuantMethod.options), and those in :attr:backend_options by some backends only (:attr:~.backends.QuantBackend.options). Setting one that the chosen method or backend ignores is an error.

References

  • Frantar, E., Ashkboos, S., Hoefler, T., & Alistarh, D. (2023). GPTQ: Accurate post-training quantization for generative pre-trained transformers. In International Conference on Learning Representations. https://doi.org/10.48550/arXiv.2210.17323
  • Lin, J., Tang, J., Tang, H., Yang, S., Chen, W.-M., Wang, W.-C., Xiao, G., Dang, X., Gan, C., & Han, S. (2024). AWQ: Activation-aware weight quantization for on-device LLM compression and acceleration. In Conference on Machine Learning and Systems. https://doi.org/10.48550/arXiv.2306.00978
  • Xiao, G., Lin, J., Seznec, M., Wu, H., Demouth, J., & Han, S. (2023). SmoothQuant: Accurate and efficient post-training quantization for large language models. In International Conference on Machine Learning. https://doi.org/10.48550/arXiv.2211.10438