AI Logic

Model Compression

Quantization

Updated:

How quantization works. The left side shows a 3-bit example in which real values are rounded to the integer grid 0 to 7 using a scale s and zero point z, with out-of-range values clamped to the ends. The right side shows the different units that share a scale (per tensor, per channel, per group).

Background and Overview

Quantization makes a model smaller and faster by representing weights and activations (layer outputs) as integers with fewer bits. Neural networks are usually trained in 32-bit or 16-bit floating point, but 8-bit or 4-bit integers are often sufficient for inference.

It has two main benefits.

  • Memory decreases. Going from 32 bits to 8 bits cuts both the memory that holds the weights and the amount of data moved from memory to the compute units to 1/4.
  • Computation gets lighter. Integer multiplication and addition need smaller circuits than floating point and consume less power. Nagel et al. (2021) explain that the cost of arithmetic grows linearly to quadratically with the number of bits.

An everyday analogy is "making the marks on a ruler coarser". Switching a ruler from 1 mm marks to 1 cm marks makes reading faster and easier, but values between the marks are rounded to the nearest mark. The craft of quantization methods lies in keeping the error from this rounding from hurting accuracy.

Quantization is one of the main ways to shrink a model, alongside pruning and knowledge distillation, and it can be combined with them. For large language models (LLMs), many quantization-based methods have been proposed, including LLM.int8(), GPTQ, AWQ, SmoothQuant, and QLoRA.

Theory (Quantization and Dequantization)

The most widely used approach is uniform quantization, which maps values onto an evenly spaced grid. A tensor (such as a weight matrix) is converted to integers by the following steps.

  1. Choose the range of values [α,β][\alpha, \beta] to represent with integers (the clipping range). This step is called calibration. The simplest approach uses the minimum and maximum of the values as they are.
  2. From the bit width bb, determine the scale ss, which is the spacing of the grid.
  3. Determine the zero point zz (an integer), which says which integer the real number 0 maps to.
  4. Divide each value by ss, round, add zz, and clip at the ends so it fits in the integer range (quantization).
  5. For computation, subtract zz from the integer and multiply by ss to get a real number close to the original (dequantization).

The scale is the size obtained by dividing the range into 2b−12^b - 1 intervals (Eq. (4) in the survey by Gholami et al.).

s=β−α2b−1s = \frac{\beta - \alpha}{2^b - 1}

Quantization and dequantization can be written as follows (Eqs. (4) and (6) in the white paper by Nagel et al.).

xint=clamp ⁣(⌊xs⌉+z; 0, 2b−1),x^=s (xint−z)x_{\mathrm{int}} = \mathrm{clamp}\!\left(\left\lfloor \frac{x}{s} \right\rceil + z;\ 0,\ 2^b - 1\right), \qquad \hat{x} = s\,(x_{\mathrm{int}} - z)

Here ⌊⋅⌉\lfloor \cdot \rceil is rounding to the nearest integer, and clamp(⋅;a,c)\mathrm{clamp}(\cdot; a, c) sets values smaller than aa to aa and values larger than cc to cc. This form is called asymmetric quantization (affine quantization). Thanks to the zero point, the real 0 maps exactly to an integer, so zero padding and the zeros output by ReLU incur no error.

Fixing the zero point at 0 gives symmetric quantization. With signed integers, it becomes the following (Eqs. (8a) and (8c) in the white paper).

xint=clamp ⁣(⌊xs⌉; −2b−1, 2b−1−1),x^=s xintx_{\mathrm{int}} = \mathrm{clamp}\!\left(\left\lfloor \frac{x}{s} \right\rceil;\ -2^{b-1},\ 2^{b-1} - 1\right), \qquad \hat{x} = s\, x_{\mathrm{int}}

A common choice is to set s=max⁡∣x∣/(2b−1−1)s = \max|x| / (2^{b-1} - 1) from the maximum absolute value, which maps to [−127,127][-127, 127] at 8 bits. This is also called absmax quantization.

When both the weights WW and the activations xx are quantized, a matrix-vector product can be computed as a sum of integer products multiplied by the scales just once (Eq. (3) in the white paper, for symmetric quantization).

y^n=swsx∑mWn,mint xmint\hat{y}_n = s_w s_x \sum_m W^{\mathrm{int}}_{n,m}\, x^{\mathrm{int}}_m

Since the sum contains only integers, it can be computed by integer multiply-accumulate units. However, adding many products quickly exceeds 8 bits, so the accumulator is 32 bits. The result is requantized to 8 bits before being passed to the next layer.

"W8A8" means 8-bit weights and 8-bit activations, and "W4A16" means 4-bit weights and 16-bit activations. Weight-only quantization is suited to reducing memory, while quantizing both weights and activations is suited to speeding up computation with integer arithmetic units.

Where the Error Comes From (Rounding and Clipping)

Quantization error comes in two kinds (Section 2.2 of the white paper).

ErrorAffected valuesMagnitudeHow to reduce it
Rounding errorValues inside the rangeAt most s/2s/2Make the scale ss smaller (narrow the range)
Clipping errorValues outside the rangeDistance from the edge of the rangeWiden the range (ss becomes larger)

With a fixed bit width, the number of grid points is fixed at 2b2^b. Widening the range makes the grid coarser, and narrowing it lets more values fall outside. Choosing the range means balancing these two. Besides using the minimum and maximum, other approaches use an upper percentile or search for the range that minimizes the mean squared error (MSE) before and after quantization.

Especially troublesome are a few very large values (outliers). Widening the range to fit outliers squeezes most values into a handful of grid points, erasing fine differences. For this reason, there are techniques that make the unit sharing a scale finer (right of the top figure).

  • Per tensor: One scale for the whole matrix. This is the simplest method and the easiest for hardware to handle.
  • Per channel: A scale for each output channel (row) of the weights. This is the standard method for convolution weights.
  • Per group: Each row is further split into chunks of tens to a hundred or so values, each with its own scale. Accuracy improves, but the amount of stored scales and the computational overhead increase.

Because activations change with each input, you can also choose when to determine the range. Static quantization, which fixes the range in advance using a small number of inputs (calibration data), gives faster inference; dynamic quantization, which computes the range at every inference, tends to give better accuracy at the cost of extra work.

How to Quantize (PTQ and QAT)

Methods for quantizing a trained model fall into two broad groups.

MethodProcedureRequirementsSuitable when
Post-training quantization (PTQ)Quantize the trained weights and set the ranges with a small amount of dataA small amount of unlabeled data (the white paper notes that 500 to 1000 images are often enough)8 bits, no time to retrain, very large models
Quantization-aware training (QAT)Fine-tune while simulating quantizationTraining data and training computeKeeping accuracy at 4 bits or below

In QAT, values are quantized and dequantized only in the forward pass so the model experiences the error, while the weights are updated in floating point. However, the rounding function has a slope of 0 almost everywhere, so gradients cannot flow through it in backpropagation as is. The straight-through estimator (STE), which treats the slope of rounding as 1, is therefore used (Eqs. (36) and (37) in the white paper).

∂⌊y⌉∂y≈1⟹∂x^∂x={1qmin⁡≤x≤qmax⁡0otherwise\frac{\partial \lfloor y \rceil}{\partial y} \approx 1 \quad\Longrightarrow\quad \frac{\partial \hat{x}}{\partial x} = \begin{cases} 1 & q_{\min} \le x \le q_{\max} \\ 0 & \text{otherwise} \end{cases}

In other words, gradients pass through unchanged for values inside the range, and no gradient flows for values clipped outside it.

Quantized weights and activations deviate slightly from their original values. These deviations accumulate layer after layer, so always check a quantized model's accuracy on validation data before using it.

Experimental Results

The white paper by Nagel et al. (2021) reports results of quantizing image recognition and language understanding models with PTQ and QAT (Tables 6 and 10; all metrics, such as ImageNet accuracy, are higher-is-better).

Model (evaluation)Floating pointPTQ W8A8PTQ W4A8QAT W4A8QAT W4A4
ResNet-50 (ImageNet)76.0775.8775.1575.8975.10
MobileNetV2 (ImageNet)71.7270.9969.2170.1766.43
EfficientNet lite (ImageNet)75.4275.2571.2471.5570.22
BERT-base (GLUE)83.0682.4381.7682.6478.83

The values in the table are for one scale per tensor. In PTQ of BERT-base, some activations with extremely wide value ranges are kept at 16 bits.

These results show the following.

  • At 8 bits (W8A8), PTQ alone nearly preserves accuracy. For the four models in the table, the drop from floating point was under 0.8 points in every case.
  • Making weights 4-bit produces differences between models. ResNet-50 stayed within 1 point, but MobileNetV2 and EfficientNet lite, which use depthwise separable convolutions, dropped substantially. For EfficientNet lite, PTQ W4A8 rose from 71.24 to 74.01 with per-channel scales.
  • QAT narrows the gap even at 4 bits. For ResNet-50, the drop stayed within 1 point even at W4A4.

Practical Considerations

  • Start with 8-bit PTQ. It takes little effort and gives sufficient accuracy for many models. If you want to go to 4 bits or below, consider per-channel scales, QAT, and LLM-specific methods.
  • Check that the hardware and libraries support it. In environments without integer arithmetic units, quantization may only reduce memory without making things faster. Fine-grained schemes such as per-group scales are slow without dedicated compute routines (kernels).
  • Find layers that are hard to quantize. Keeping the first and last layers, and activations with extremely wide value ranges, at higher precision can recover accuracy.
  • PyTorch's quantization API is in transition. The official PyTorch documentation states that quantization development is being consolidated into torchao and that torch.ao.quantization is planned for removal. When adopting it, check the documentation for the version you use.

In large language models, very large values (outliers) are known to appear in some dimensions of the activations, and ordinary 8-bit quantization can degrade accuracy substantially. When quantizing an LLM, use methods that handle outliers, such as LLM.int8() or SmoothQuant.

Comparison with Other Methods

The following table compares representative ways to shrink a model from the same viewpoints.

MethodWhat it reducesRetraining?Conditions for a speedup
QuantizationBits per valueNot for PTQ, required for QATLow-bit arithmetic, or kernels that read low-bit weights
PruningNumber of weights or channelsUsually requiredRemoving whole structures, or hardware that supports sparse computation
Knowledge distillationSize of the model itself (builds a small student)RequiredIf the student is small, it is fast as is
Low-rank factorizationMatrix size (product of two thin matrices)Usually requiredThe factorized matrices are thin enough

Quantization methods for LLMs differ in what they quantize and to how many bits.

MethodWhat is quantizedKey idea
LLM.int8()Weights and activations to 8 bitsComputes only the outlier dimensions in 16 bits
SmoothQuantWeights and activations to 8 bitsMoves the magnitude of activation outliers to the weights
GPTQWeights to 3 to 4 bitsQuantizes one column at a time and compensates for the error in the remaining columns
AWQWeights to 4 bitsScales up the weights of channels with large activations before quantizing
QLoRAWeights to 4 bits (NF4)Freezes the quantized model and fine-tunes it with LoRA
  • For an easy way to lighten a model without losing accuracy, 8-bit PTQ is the first choice.
  • To greatly speed up inference or run on small devices, combine quantization with knowledge distillation and pruning.
  • To run an LLM with as little GPU memory as possible, GPTQ and AWQ, which make weights 4-bit, are well suited.

PyTorch example

Show code
python
import torch
import torch.nn as nn

# 1. PyTorch built-in: represent a tensor with 8-bit integers
#    torch.quantize_per_tensor(input, scale, zero_point, dtype)
#    dtype is one of torch.quint8 (0-255), torch.qint8 (-128-127), or torch.qint32
x = torch.tensor([-1.15, -0.5, 0.13, 0.55, 1.07, 1.52, 2.55])
q = torch.quantize_per_tensor(x, scale=0.02, zero_point=128, dtype=torch.quint8)
print(q.int_repr())    # integer values
print(q.dequantize())  # dequantized values (close to the originals)


# 2. Quantization following the formula (asymmetric, b bits); the range comes from the min and max
def quantize_asym(x, b=8):
    qmax = 2 ** b - 1
    lo, hi = x.min().clamp(max=0), x.max().clamp(min=0)  # make sure 0 is in the range
    s = (hi - lo).clamp(min=1e-8) / qmax                 # scale
    z = torch.round(-lo / s)                             # zero point
    x_int = torch.clamp(torch.round(x / s) + z, 0, qmax)
    return x_int, s, z

def dequantize(x_int, s, z):
    return s * (x_int - z)


# 3. Symmetric quantization of weights per output channel (row) (absmax)
def quantize_weight_per_channel(w, b=8):
    qmax = 2 ** (b - 1) - 1                                     # 127 for 8 bits
    s = w.abs().amax(dim=1, keepdim=True).clamp(min=1e-8) / qmax  # per-row scale
    w_int = torch.clamp(torch.round(w / s), -qmax, qmax)
    return w_int, s


# 4. Fake quantization and the straight-through estimator (STE) for quantization-aware training (QAT)
class FakeQuantSTE(torch.autograd.Function):
    @staticmethod
    def forward(ctx, x, s, qmin, qmax):
        ctx.save_for_backward(x)
        ctx.lo, ctx.hi = qmin * s, qmax * s
        return torch.clamp(torch.round(x / s), qmin, qmax) * s  # quantize and immediately dequantize

    @staticmethod
    def backward(ctx, grad_out):
        (x,) = ctx.saved_tensors
        inside = (x >= ctx.lo) & (x <= ctx.hi)                  # pass gradients only inside the range
        return grad_out * inside, None, None, None


class QATLinear(nn.Linear):
    """Linear layer that fake-quantizes weights to b bits before computing (the weights themselves are updated in floating point)"""
    def __init__(self, in_features, out_features, b=4):
        super().__init__(in_features, out_features)
        self.qmax = 2 ** (b - 1) - 1

    def forward(self, x):
        s = self.weight.detach().abs().max().clamp(min=1e-8) / self.qmax  # per-tensor scale
        w_q = FakeQuantSTE.apply(self.weight, s, -self.qmax, self.qmax)
        return nn.functional.linear(x, w_q, self.bias)


x_int, s, z = quantize_asym(x, b=3)
print(x_int, dequantize(x_int, s, z))

layer = QATLinear(16, 8, b=4)
layer.train()
out = layer(torch.randn(2, 16))
out.sum().backward()  # thanks to STE, gradients reach the weights
print(layer.weight.grad.shape)

FAQ

Q. How much does accuracy drop at 8 bits?
A.

It depends on the model, but for image recognition, BERT, and similar models, post-training quantization (PTQ) alone often keeps the drop under 1 point. In the experiments of Nagel et al. (2021), W8A8 PTQ dropped accuracy by less than 0.8 points for ResNet-50, MobileNetV2, BERT-base, and others. On the other hand, LLMs with more than a few billion parameters develop outliers in their activations, and ordinary 8-bit quantization can degrade them substantially, so dedicated methods such as LLM.int8() are used.

Q. When should symmetric versus asymmetric quantization be used?
A.

For weights, which are distributed nearly symmetrically around 0, symmetric quantization (zero point z=0z = 0) is often used because the computation is simple. For activations skewed to one side, such as ReLU outputs, asymmetric quantization, which uses the range without waste, is a better fit. Asymmetric quantization adds computation for the zero point, but most of it can be precomputed and folded into the bias.

Q. Does a quantized model run faster in every environment?
A.

Not necessarily. Memory always decreases, but computation becomes faster only when there are low-bit integer arithmetic units or dedicated kernels that compute while reading low-bit weights. In unsupported environments, converting back to floating point before computing adds overhead, and things can even become slower.

References

  1. M. Nagel, M. Fournarakis, R. A. Amjad, Y. Bondarenko, M. van Baalen, and T. Blankevoort, "A White Paper on Neural Network Quantization," arXiv:2106.08295, 2021.
  2. A. Gholami, S. Kim, Z. Dong, Z. Yao, M. W. Mahoney, and K. Keutzer, "A Survey of Quantization Methods for Efficient Neural Network Inference," arXiv:2103.13630, 2021.
  3. B. Jacob, S. Kligys, B. Chen, M. Zhu, M. Tang, A. Howard, H. Adam, and D. Kalenichenko, "Quantization and Training of Neural Networks for Efficient Integer-Arithmetic-Only Inference," arXiv:1712.05877, 2017.
  4. PyTorch Documentation, "torch.quantize_per_tensor."
  5. PyTorch Documentation, "Quantization."