AI Logic

Model Compression

LLM.int8()

Updated:

How LLM.int8() works. The left side shows the flow of one matrix multiplication: the outlier dimensions are separated and computed in 16 bits, while the rest are quantized vector-wise, computed in 8 bits, dequantized, and then added together. The right side shows that only the outlier columns of the input X and the rows of the weight W with the same indices are kept in 16 bits

Background and Overview

LLM.int8() is a method that computes the matrix multiplications of the linear layers in a Transformer with 8-bit integers without losing accuracy. It was proposed in 2022 by Dettmers et al. and presented at NeurIPS 2022. A 175B-parameter model stored in 16 bits can be loaded, converted directly to 8 bits, and used for inference.

Large language models (LLMs) need a large amount of GPU memory even just for inference. According to the paper, in models with 6.7B parameters or more, about 95% of the parameters are the weights of the attention projections and the feed-forward layers. Converting these weights to 8 bits therefore cuts memory roughly in half.

However, earlier 8-bit quantization methods lost a lot of accuracy on models beyond a few billion parameters. The paper traced the cause to extremely large values (outliers) that appear in a very small number of hidden dimensions. LLM.int8() avoids this problem by combining the following two techniques.

  • Vector-wise quantization: treats a matrix multiplication as a collection of inner products and uses a separate scale for each row of the input and each column of the weights.
  • Mixed-precision decomposition: computes only the few dimensions containing outliers in 16 bits and the remaining 99.9%+ of the values in 8 bits.

The method is built into the bitsandbytes library and Hugging Face Transformers, and can be enabled with a single setting when loading a model.

Theory (Vector-wise Quantization and Mixed-Precision Decomposition)

Let the input hidden states be X∈Rs×hX \in \mathbb{R}^{s \times h} (ss is the number of tokens and hh the hidden dimension) and the weights W∈Rh×oW \in \mathbb{R}^{h \times o} (oo is the output dimension). LLM.int8() computes XWXW in the following steps.

  1. Inspect each column (hidden dimension) of XX and collect the dimensions containing at least one value whose magnitude is at or above a threshold α\alpha into the set of outlier dimensions OO. In the paper, α=6.0\alpha = 6.0 was sufficient.
  2. Extract the OO columns of XX and the OO rows of WW and compute their matrix product in 16-bit floating point.
  3. For the remaining part, compute a constant cxc_x from the maximum absolute value of each row of XX and a constant cwc_w for each column of WW, and quantize each to 8-bit integers in [−127,127][-127, 127].
  4. Compute the matrix product of the 8-bit integers, accumulating in 32-bit integers.
  5. Divide each element of the result by its row constant and column constant (dequantize) to return to 16 bits.
  6. Add the results of steps 2 and 5 to obtain the output.

The quantization in step 3 is absmax quantization, which divides by the maximum absolute value and multiplies by 127 (Section 2.1 of the paper). When the whole of XX is quantized with a single constant, the formula is as follows.

Xi8=⌊127max⁡ij∣Xij∣ X⌉X_{i8} = \left\lfloor \frac{127}{\max_{ij} |X_{ij}|}\, X \right\rceil

Vector-wise quantization keeps this constant for each row or column. Since element (i,j)(i, j) of the output is the inner product of row ii of XX and column jj of WW, dividing by the product of the row constant cx,ic_{x,i} and the column constant cw,jc_{w,j} restores the original scale. For the whole matrix, this means dividing by the outer product of the constants cx⊗cwc_x \otimes c_w (Eq. (7) in the paper).

XW≈1cx⊗cw∘(Xi8Wi8)XW \approx \frac{1}{c_x \otimes c_w} \circ \left(X_{i8} W_{i8}\right)

Here ∘\circ denotes element-wise multiplication, and the division is also element-wise. cxc_x is a vector of length ss and cwc_w a vector of length oo.

The mixed-precision decomposition that separates the outlier dimensions can be written as follows (Eq. (8) in the paper).

XW≈∑h∈OXf16hWf16h+S⋅∑h∉OXi8hWi8hXW \approx \sum_{h \in O} X^{h}_{f16} W^{h}_{f16} + S \cdot \sum_{h \notin O} X^{h}_{i8} W^{h}_{i8}

The first term is the 16-bit matrix product over the outlier dimensions only, the second term is the 8-bit matrix product over the rest, and SS is the dequantization factor. According to the paper, models up to 13B parameters have at most 7 outlier dimensions, so the extra memory for keeping them in 16 bits is only about 0.1%.

A matrix product is a sum over the hidden dimension hh. Therefore, splitting the hidden dimensions into "dimensions with outliers" and "dimensions without," computing them separately, and adding them at the end gives the same result as computing without splitting. This is why the decomposition does not change the meaning of the computation.

Why Outliers Are a Problem

The paper examines the hidden states of language models with 125M to 13B parameters and reports the following.

  • Outliers concentrate in a fixed, small set of dimensions. In the 6.7B model, a single sequence of 2048 tokens contained about 150,000 outliers, but they were concentrated in just 6 hidden dimensions.
  • Around 6.7B, they suddenly spread to all layers. In terms of parameter count, between 6B and 6.7B the fraction of layers with outliers rose from 65% to 100%, and the fraction of affected tokens from 35% to 75%. On the other hand, when ordered by perplexity, outliers grow smoothly and exponentially as perplexity decreases, and the paper notes that model size alone does not determine them.
  • Outliers are essential to model performance. Zeroing out the outlier dimensions reduced the mean of the largest attention softmax probability from about 40% to about 20% and worsened perplexity by 600–1000%. Zeroing out 7 random dimensions worsened perplexity by only about 0.1%.

The reason 8-bit quantization breaks down lies in the trade-off between clipping and rounding explained in the quantization article. If the scale is set to fit outliers with magnitudes as large as 60, most other values are squeezed into a handful of grid points, and small values are rounded to 0, losing their information. Since outlier dimensions make up only about 0.1% of the total, computing just those in 16 bits lets the rest keep sufficient accuracy in 8 bits.

Experimental Results

Table 1 of the paper compares perplexity (lower is better) on the C4 validation data.

Method125M1.3B2.7B6.7B13B
32-bit floating point25.6515.9114.4313.3012.45
8-bit absmax (tensor-wise)87.7616.5515.1114.5919.08
8-bit absmax (vector-wise)35.8416.8214.9814.1316.48
8-bit zeropoint (vector-wise)25.7215.9414.3613.3813.47
LLM.int8() (absmax, vector-wise + decomposition)25.8315.9314.4413.2412.45

The other 8-bit methods break down as models grow; for example, 13B becomes worse than 6.7B. Only LLM.int8() kept nearly the same values as 32 bits at every size.

The paper also reports the following results.

  • For OPT models from 125M to 175B, zero-shot accuracy (the average of WinoGrande, HellaSwag, PIQA, and LAMBADA) stayed at the same level as 16 bits. With vector-wise absmax quantization alone, accuracy dropped to random-chance level beyond 6.7B.
  • The memory of BLOOM-176B was reduced by a factor of 1.96.
  • The generation speed of BLOOM-176B at batch size 1 was 239 ms per token in 16 bits (eight A100 80GB GPUs) and 247 ms with LLM.int8() (three A100 80GB GPUs). It runs at nearly the same speed on fewer GPUs.

Practical Considerations

  • The goal is to reduce memory, not necessarily to speed things up. According to Appendix D of the paper, because of the overhead of quantization and decomposition, it was faster than 16 bits only for large matrices corresponding to the 13B and 175B GPT-3 sizes. At sizes of 2.7B or below, it is slower.
  • The threshold α\alpha can be tuned. In Hugging Face Transformers, llm_int8_threshold is this threshold, and the documentation describes 6 as a good default. For small models or unstable fine-tuning, a smaller value may be needed.
  • Only the linear-layer weights and their inputs are converted to 8 bits. Computations inside attention (such as the product of queries and keys), as well as embedding and normalization layers, stay in 16 bits.

LLM.int8() is a method for inference; the 8-bit weights themselves cannot be updated by training. The Hugging Face documentation also states that with 8-bit or 4-bit models, only added parameters can be trained. To fine-tune a quantized model, add an adapter such as LoRA and train it (see QLoRA).

Comparison with Other Methods

The following table compares quantization methods for LLMs in terms of how they handle outliers.

MethodBit widthHow outliers are handledInference speed
LLM.int8()Weights 8, activations 8 (outlier dimensions 16)Separates the outlier dimensions and computes them in 16 bitsTends to be slower than 16 bits except for large models
SmoothQuantWeights 8, activations 8Flattens activation outliers by moving their magnitude into the weightsEverything runs in 8 bits, making it easier to speed up
GPTQWeights 3–4 (activations 16)Compensates the weight quantization error with the remaining weightsFewer weight reads, so generation tends to be faster
AWQWeights 4 (activations 16)Protects the weights of channels with large activationsFewer weight reads, so generation tends to be faster
  • When the model does not fit on your GPU and you cannot afford any loss in accuracy, LLM.int8() is the easiest option. It only takes changing one loading setting.
  • To speed up inference with 8 bits, SmoothQuant, which can compute everything with 8-bit integers, is a better fit.
  • To reduce memory even further, choose GPTQ or AWQ, which quantize weights to 4 bits.

PyTorch example

Show code
python
import torch

# The LLM.int8() computation written exactly as Eqs. (7) and (8) of the paper (for illustration; the fast implementation is in bitsandbytes)
# X: (s, h) 16-bit input, W: (h, o) 16-bit weights


def absmax_quantize(x, dim):
    """Quantize to [-127, 127] using the max absolute value along dim. c is 127 / max"""
    c = 127.0 / x.abs().amax(dim=dim, keepdim=True).clamp(min=1e-8)
    return torch.round(x * c).to(torch.int8), c


def llm_int8_matmul(X, W, threshold=6.0):
    # 1. Outlier dimensions: hidden dimensions (columns of X) containing any |value| >= threshold
    outlier = (X.abs() >= threshold).any(dim=0)          # (h,)

    # 2. Matrix product of the outlier dimensions stays in 16 bits
    out_fp16 = X[:, outlier] @ W[outlier, :]

    # 3. Quantize the rest to 8 bits: X per row, W per column (vector-wise quantization)
    Xr, Wr = X[:, ~outlier], W[~outlier, :]
    X_i8, c_x = absmax_quantize(Xr.float(), dim=1)       # c_x: (s, 1)
    W_i8, c_w = absmax_quantize(Wr.float(), dim=0)       # c_w: (1, o)

    # 4. Integer matrix product (accumulated in 32 bits). Computed in int32 here for illustration
    acc_i32 = X_i8.to(torch.int32) @ W_i8.to(torch.int32)

    # 5. Divide by the outer product of row and column constants (dequantization)
    out_int8 = acc_i32.float() / (c_x * c_w)

    # 6. Add the two results
    return out_fp16.float() + out_int8


torch.manual_seed(0)
X = torch.randn(16, 64)
X[:, 5] *= 20                     # put large values (outliers) in a fixed dimension
W = torch.randn(64, 32) * 0.05

ref = X @ W
approx = llm_int8_matmul(X, W)
print("Relative error:", ((approx - ref).norm() / ref.norm()).item())


# Real-world usage (requires a GPU and bitsandbytes)
# from transformers import AutoModelForCausalLM, BitsAndBytesConfig
# config = BitsAndBytesConfig(
#     load_in_8bit=True,          # replace linear layers with LLM.int8()
#     llm_int8_threshold=6.0,     # threshold for treating values as outliers (alpha in the paper)
# )
# model = AutoModelForCausalLM.from_pretrained("facebook/opt-350m", device_map="auto", quantization_config=config)

FAQ

Q. Why does ordinary 8-bit quantization start failing at around 6.7B parameters?
A.

Because beyond that size, extremely large values (outliers) start appearing in a fixed, small set of hidden dimensions across all layers. If the scale is set to fit the outliers, the other values are squeezed into a coarse grid and small values are rounded to 0. The paper reports that although it looks like an abrupt change in terms of parameter count, outliers grow smoothly when viewed against perplexity.

Q. Should the threshold of 6.0 be changed?
A.

In most cases, 6.0 is good enough. In the paper, treating values with magnitude 6 or more as outliers almost completely stopped the degradation in perplexity. The Hugging Face documentation suggests trying a smaller threshold for small models or when fine-tuning is unstable. Setting the threshold to 0 makes it faster but can reduce accuracy.

Q. Does LLM.int8() make inference faster?
A.

The main benefit is memory reduction; speed depends on model size. In the paper's measurements, because of the overhead of quantization and decomposition, it was faster than 16 bits only for large matrices equivalent to 13B and 175B. For BLOOM-176B generation, it ran at nearly the same speed as 16 bits on fewer GPUs.

References

  1. T. Dettmers, M. Lewis, Y. Belkada, and L. Zettlemoyer, "LLM.int8(): 8-bit Matrix Multiplication for Transformers at Scale," NeurIPS, 2022. arXiv:2208.07339.
  2. Hugging Face Transformers Documentation, "Bitsandbytes."
  3. bitsandbytes (GitHub).