AI Logic

Model Compression

SmoothQuant

Updated:

How SmoothQuant works. The left side shows the outlier channel of the activation X being divided by s and the row of the weight W with the same index being multiplied by s, after which both are computed in INT8. The right side is an example with α = 0.5 showing the per-channel maximum values before and after smoothing, and the change in the number of levels available to the non-outlier channels.

Background and Overview

SmoothQuant is a method that flattens activation outliers by migrating them to the weights, so that both weights and activations can be computed as 8-bit integers. It was proposed by Xiao et al. in 2022 and presented at ICML 2023. It is a post-training quantization (PTQ) method that requires no retraining.

When both weights and activations are 8-bit (W8A8), matrix multiplications can run on 8-bit integer arithmetic units, which not only reduces memory but also speeds up computation. In large language models (LLMs), however, very large values (outliers) appear in some channels of the activations, and plain W8A8 breaks accuracy. LLM.int8() kept accuracy by computing only the outlier dimensions in 16 bits, but this made computation slower.

SmoothQuant starts from two observations.

  • Weights are easy to quantize; activations are hard. Weight distributions are known to be flat, and accuracy rarely drops even at 8 or 4 bits. Activation outliers, on the other hand, are about 100 times larger than the other values.
  • Outliers keep appearing in fixed channels. If a channel has outliers, the same channel is large for almost every token.

So by dividing each activation channel to make its values smaller and multiplying the weights by the same amount, the quantization difficulty can be shifted from the activations to the weights without changing the result of the computation. The paper showed that OPT-175B, BLOOM-176B, GLM-130B, and others can be converted to W8A8 with almost no loss of accuracy.

Theory (Migrating Difficulty from Activations to Weights)

Let the computation of a linear layer be Y=XWY = XW (XX is the activation of shape tokens × input channels, and WW is the weight of shape input channels × outputs). Using a per-input-channel factor s\mathbf{s}, this can be rewritten as follows (Eq. (3) in the paper).

Y=(X diag(s)−1)⋅(diag(s) W)=X^W^Y = \left(X\, \mathrm{diag}(\mathbf{s})^{-1}\right) \cdot \left(\mathrm{diag}(\mathbf{s})\, W\right) = \hat{X} \hat{W}

Since this only divides the jj-th activation channel by sjs_j and multiplies the jj-th row of the weights by sjs_j, the result is the same as before. The factor sjs_j is determined using the migration strength α\alpha as follows (Eq. (4) in the paper).

sj=max⁡(∣Xj∣)αmax⁡(∣Wj∣)1−αs_j = \frac{\max(|X_j|)^{\alpha}}{\max(|W_j|)^{1 - \alpha}}

With α=1\alpha = 1, the activations become completely flat, but all the difficulty moves to the weights. With α=0\alpha = 0, conversely, all the difficulty stays in the activations. With α=0.5\alpha = 0.5, the maximum values of the transformed activations and weights match in each channel, so the difficulty is split evenly.

The procedure is as follows.

  1. Feed a small amount of general text of the kind used in pretraining (512 sentences from the Pile in the paper) through the model, and collect the per-channel maximum absolute value max⁡(∣Xj∣)\max(|X_j|) of the input activations of each linear layer.
  2. Compute the per-channel factor sjs_j with Eq. (4).
  3. Multiply the jj-th row of the weights by sjs_j.
  4. Fold 1/sj1/s_j into the parameters of the layer just before that produces the linear layer's input (such as LayerNorm). All of this transformation is done in advance, so it adds no computation at inference time.
  5. Quantize the transformed weights and activations to 8-bit integers.

In kernels that compute 8-bit matrix multiplication quickly, scales can be applied only along the outer dimensions of the matrix multiplication (the token dimension of the activations and the output dimension of the weights). Quantizing activations with a separate scale per input channel would preserve accuracy, but the kernels do not allow it. SmoothQuant sidesteps this constraint by migrating the per-input-channel differences to the weights in advance.

Why Flattening Makes Quantization Easier

When quantizing with one scale per tensor, the scale is determined by the maximum value mm of the whole matrix. According to Section 3 of the paper, the number of levels that channel ii with maximum value mim_i can actually use is roughly the following.

28⋅mim2^8 \cdot \frac{m_i}{m}

If the outliers are 100 times larger, the other channels can use only 2 to 3 of the 256 levels, and most values are rounded to the same integer. Dividing by sjs_j to equalize the per-channel maxima makes mm smaller, so channels that are not outliers can use many more levels.

The right of the top figure computes this relationship for an example where the outlier channel is 70 and the others are around 1. Smoothing with α=0.5\alpha = 0.5 increases the levels available to the other activation channels from about 4 to about 36. In exchange, the weights get fewer levels, and the role of α\alpha is to balance the two.

Table 1 of the paper compares the granularity at which scales are kept when quantizing OPT's activations to 8 bits (mean accuracy over four tasks).

Model16-bitPer tensorPer tokenPer input channel
OPT-6.7B64.9%39.9%42.5%64.8%
OPT-175B71.6%32.3%31.7%71.4%

Keeping a scale per input channel preserves accuracy. This supports the observation that outliers line up along channels.

Experimental Results

Table 3 of the paper compares accuracy when OPT-175B is converted to 8 bits (mean accuracy over seven zero-shot tasks, and WikiText perplexity).

MethodMean accuracy (higher is better)WikiText (lower is better)
16-bit66.9%10.99
Naive W8A835.5%93080
LLM.int8()66.7%11.10
SmoothQuant-O366.8%11.17

SmoothQuant has three settings, O1 to O3, that differ in quantization granularity. O3 is the fastest: one scale per tensor for both weights and activations, with activation scales fixed in advance (static quantization). Even so, it kept almost the same accuracy as 16 bits.

Speed and memory are as follows.

  • In the PyTorch implementation, OPT-30B (sequence length 256) ran 1.51× faster than 16 bits. LLM.int8() was slower than 16 bits in most cases.
  • In the generation stage (Table 8), running OPT-30B on a single GPU made each step 1.27 to 1.42× faster and reduced memory by 1.59 to 1.91×.
  • The 530B-parameter MT-NLG could also be converted to W8A8 with almost no loss of accuracy (the mean over four tasks was 73.1% for both 16-bit and 8-bit), and a model that had required 16 GPUs ran at about the same speed on a single 8-GPU node.

Practical Considerations

  • Re-tune the migration strength α\alpha for each model. In the paper, α=0.5\alpha = 0.5 worked well for OPT and BLOOM, and α=0.75\alpha = 0.75 for GLM-130B, which has more activation outliers; the value was chosen with a simple search on a subset of the data.
  • There must be somewhere to fold 1/s1/s into. When a linear layer's input comes from LayerNorm or similar, it can be folded into its parameters. When it comes directly from a residual addition, the paper adds a separate factor on the residual branch.
  • An 8-bit matrix multiplication kernel is required. The speedup comes when running in an environment that can compute 8-bit integer matrix multiplications quickly (CUTLASS INT8 kernels in the paper).

If α\alpha is too small, the activations become hard to quantize; if it is too large, the weights do, and either way accuracy drops sharply. In the paper's OPT-175B experiments, accuracy was preserved only for α\alpha in the range 0.4 to 0.6, and it degraded below 0.4 or above 0.6.

Comparison with Other Methods

The following table compares methods by how they handle activation outliers in LLMs.

MethodBit widthHandling of outliersFaster on 8-bit arithmetic units?
Naive W8A8Weights 8, activations 8NoneYes (but accuracy breaks on large models)
LLM.int8()Weights 8, activations 8 (16 for outlier dimensions)Computes only the outlier dimensions in 16 bitsHardly (decomposition overhead tends to slow it down)
SmoothQuantWeights 8, activations 8Flattens outliers by migrating them to the weightsYes
AWQWeights 4 (activations 16)Protects weights of channels with large activations by scaling them upFaster because less weight data is read

SmoothQuant and AWQ both use an equivalent transformation that scales up the weights per input channel and scales down the inputs. SmoothQuant aims to make activations easier to quantize to 8 bits, while AWQ aims to reduce the error when quantizing weights to 4 bits.

  • To speed up the computation itself on servers that process many inputs in batches, SmoothQuant's W8A8 is well suited.
  • To greatly reduce memory when generating one token at a time, AWQ and GPTQ, which make weights 4-bit, are well suited.
  • To first fit a model on fewer GPUs without much implementation effort, LLM.int8() is the easy option.

PyTorch example

Show code
python
import torch
import torch.nn as nn

# SmoothQuant's smoothing transformation applied to a LayerNorm -> Linear pair (a small illustrative implementation)


@torch.no_grad()
def smooth_ln_linear(ln: nn.LayerNorm, fc: nn.Linear, act_max: torch.Tensor, alpha=0.5):
    """act_max: per-input-channel max|X_j| collected on calibration data (shape (in_features,))"""
    w_max = fc.weight.abs().amax(dim=0).clamp(min=1e-5)          # per-input-channel max|W_j|
    s = act_max.clamp(min=1e-5).pow(alpha) / w_max.pow(1 - alpha)  # Eq. (4)
    # Divide activations by s -> fold into the preceding LayerNorm's weight and bias
    ln.weight.div_(s)
    ln.bias.div_(s)
    # Multiply row j of the weights (column j in PyTorch's Linear) by s
    fc.weight.mul_(s.view(1, -1))
    return s


def quantize_per_tensor_int8(x):
    """Per-tensor symmetric quantization (absmax). Returns dequantized values (for checking accuracy)"""
    scale = x.abs().max().clamp(min=1e-8) / 127
    return torch.clamp(torch.round(x / scale), -127, 127) * scale


def w8a8_linear(fc, x):
    return quantize_per_tensor_int8(x) @ quantize_per_tensor_int8(fc.weight).T + fc.bias


torch.manual_seed(0)
d, out = 64, 32
ln, fc = nn.LayerNorm(d), nn.Linear(d, out)
with torch.no_grad():
    ln.weight[:2] = 40.0            # make large values (outliers) appear in only a few channels
x = torch.randn(256, d)

with torch.no_grad():
    h = ln(x)
    ref = fc(h)
    err_before = (w8a8_linear(fc, h) - ref).pow(2).mean()

    act_max = h.abs().amax(dim=0)   # calibration: per-channel maxima
    smooth_ln_linear(ln, fc, act_max, alpha=0.5)
    h2 = ln(x)                      # activations after smoothing
    print("Same result after transformation:", torch.allclose(fc(h2), ref, atol=1e-4))
    err_after = (w8a8_linear(fc, h2) - ref).pow(2).mean()

print("W8A8 error (before smoothing):", err_before.item())
print("W8A8 error (after smoothing):", err_after.item())

FAQ

Q. What is the difference between SmoothQuant and LLM.int8()?
A.

Both handle LLM activation outliers to reach 8 bits, but in different ways. LLM.int8() extracts the outlier dimensions and computes them in 16 bits, which preserves accuracy but tends to be slow due to the decomposition overhead. SmoothQuant migrates the magnitude of the outliers to the weights in advance and computes everything as 8-bit integers, so it can be faster than 16 bits. On OPT-175B in the paper, both had accuracy nearly identical to 16 bits.

Q. How should the migration strength α be chosen?
A.

Start with 0.5 and adjust while checking accuracy on a subset of the data. In the paper, OPT and BLOOM used α=0.5\alpha = 0.5, and GLM-130B, which has many activation outliers, used α=0.75\alpha = 0.75. For OPT-175B, accuracy was preserved only in the range 0.4 to 0.6; outside it, either the activations or the weights became hard to quantize and accuracy degraded.

Q. Does the smoothing transformation add computation at inference?
A.

No. The ss multiplied into the weights is folded into the weights, and the 1/s1/s that divides the activations is folded into the parameters of the preceding LayerNorm or similar layer, so both are done in advance. At inference, the transformed model simply runs as is in 8 bits.

References

  1. G. Xiao, J. Lin, M. Seznec, H. Wu, J. Demouth, and S. Han, "SmoothQuant: Accurate and Efficient Post-Training Quantization for Large Language Models," ICML, 2023. arXiv:2211.10438.
  2. mit-han-lab, "smoothquant" (GitHub).