AI Logic

Model Compression

GPTQ

Updated๏ผš

How GPTQ works. The left side shows the flow for quantizing one layer: collect the layer input X from calibration data, compute H = 2XXแต€ + ฮปI and the Cholesky decomposition of its inverse, then quantize column by column and distribute the error. The right side shows the columns of the weight W being quantized from left to right, with the error of the just-quantized column distributed immediately to the remaining columns inside the block and, at the end of the block, all at once to the columns outside it

Background and Overview

GPTQ is a method that quantizes the weights of a trained GPT-style language model to 3โ€“4 bits without retraining. It was proposed in 2022 by Frantar, Ashkboos, Hoefler, and Alistarh and presented at ICLR 2023.

The simplest form of quantization rounds each weight to the nearest grid value (the paper calls this RTN). At 8 bits this works well enough, but at 4 or 3 bits the grid becomes coarse and the accuracy of large language models drops sharply. On the other hand, accurate post-training quantization methods that carefully adjust the rounding error were computationally heavy and could not be applied to models with billions of parameters.

GPTQ preserves accuracy by quantizing the weights one column at a time and, after each step, cancelling the resulting error by adjusting the weights that are not yet quantized. How to adjust them is determined by a Hessian matrix (second-order information) built from the layer inputs. The method builds on OBQ (Optimal Brain Quantization), which quantizes weights one by one; GPTQ drastically reduces its cost so that it scales to huge models.

In the paper, OPT-175B and BLOOM-176B are quantized on a single GPU in about 4 hours, and at 4 bits they keep nearly the same perplexity as 16 bits. OPT-175B quantized to 3 bits fits on a single 80GB GPU.

Theory (Compensating the Error with the Remaining Weights)

GPTQ quantizes the model one layer at a time. Let WW be the weight of a linear layer (rows are outputs, columns are input dimensions) and XX the layer input obtained by passing a small amount of data. The quantized weight W^\hat{W} is chosen to minimize the change in the layer output (Eq. (1) in the paper).

W^=argminโกW^โˆฅWXโˆ’W^Xโˆฅ22\hat{W} = \operatorname*{argmin}_{\hat{W}} \left\| W X - \hat{W} X \right\|_2^2

This error is quadratic in the weights, and its Hessian is H=2XXโŠคH = 2XX^\top. HH depends only on the input XX and is shared by every row of WW.

When a weight wqw_q is quantized to quant(wq)\mathrm{quant}(w_q), the optimal update of the remaining unquantized weights FF that minimizes the error is given by the following formula (the OBQ update, Eq. (2) in the paper).

ฮดF=โˆ’wqโˆ’quant(wq)[HFโˆ’1]qqโ‹…(HFโˆ’1):,q\delta_F = -\frac{w_q - \mathrm{quant}(w_q)}{[H_F^{-1}]_{qq}} \cdot (H_F^{-1})_{:,q}

In other words, the quantization error is redistributed to the remaining weights, weighted by the inverse Hessian. GPTQ applies this formula in the following steps (Algorithm 1 in the paper).

  1. Pass calibration data to collect the layer input XX and compute H=2XXโŠคH = 2XX^\top. For numerical stability, add ฮป\lambda, equal to 1% of the mean of the diagonal, to the diagonal.
  2. Compute the Cholesky decomposition of Hโˆ’1H^{-1}, precomputing all the information needed later just once.
  3. Split the weight columns, from left to right, into blocks of B=128B = 128 columns.
  4. Within a block, quantize column jj and compute the error E:,j=(W:,jโˆ’Q:,j)/[Hโˆ’1]jjE_{:,j} = (W_{:,j} - Q_{:,j}) / [H^{-1}]_{jj}.
  5. Multiply that error by row jj of Hโˆ’1H^{-1} and subtract it from the not-yet-quantized columns in the block.
  6. Once all columns in the block are quantized, apply the accumulated block error to all columns to the right of the block in one step.
  7. After all columns are quantized, use this layer's output as the next layer's input and move on to the next layer.

The main changes from OBQ are the following three.

TechniqueWhat it doesEffect
Fixed orderEvery row quantizes the columns in the same left-to-right order (OBQ picks the weight with the smallest error first)Hโˆ’1H^{-1} needs to be updated only once per column, reducing the cost from O(drowโ‹…dcol3)O(d_{\mathrm{row}} \cdot d_{\mathrm{col}}^3) to O(maxโก{drowโ‹…dcol2,ย dcol3})O(\max\{d_{\mathrm{row}} \cdot d_{\mathrm{col}}^2,\ d_{\mathrm{col}}^3\})
Lazy batch updatesUpdate only the columns inside a 128-column block first, and update the columns outside the block at once at the end of the blockFewer memory reads and writes, making efficient use of the GPU
Cholesky decompositionCompute the required parts of Hโˆ’1H^{-1} up front with a numerically stable methodPrevents the numerical breakdowns that occurred in large models

Fixing the quantization order is acceptable because, in the paper's experiments, the difference between OBQ's greedy smallest-error-first order and a fixed order was negligible for large layers. With the same order, the set of unquantized columns is the same for every row, so Hโˆ’1H^{-1} can be shared across all rows.

Why Accuracy Is Preserved

With simple rounding (RTN), each weight is rounded independently, and the errors accumulate directly in the layer output. GPTQ cancels the error from rounding one weight by slightly adjusting the weights not yet rounded before moving to the next one. As a result, even though each individual weight lies on the grid, the layer output WXWX stays close to the original.

As an everyday analogy, it is like carrying the rounding difference over to the next line item when rounding amounts in accounting, so that the total does not drift. The Hessian H=2XXโŠคH = 2XX^\top captures which input dimensions move together, so it determines "how much to carry over to which weight so that the output changes the least."

In addition, during quantization the paper uses inputs that have passed through the already-quantized layers rather than the inputs of the original 16-bit model. Because the deviation introduced by earlier layers is also compensated, errors are less likely to accumulate as layers stack up.

Experimental Results

The paper quantizes OPT and BLOOM models using only 128 C4 text segments (2048 tokens each) and compares WikiText2 perplexity (lower is better) (Tables 3 and 4). The quantization grid uses per-row asymmetric min-max.

Model16-bitRTN 4-bitGPTQ 4-bitRTN 3-bitGPTQ 3-bit
OPT-1.3B14.6348.1715.471.3e420.97
OPT-13B10.1311.3210.313.4e311.61
OPT-175B8.3410.548.377.3e38.68
BLOOM-176B8.118.378.215718.64
  • At 4 bits, the perplexity of OPT-175B degraded by only 0.03. RTN degraded it by 2.2, making it worse than the 16-bit 13B model, which is one-tenth the size.
  • At 3 bits, RTN collapses, while GPTQ keeps usable accuracy. Larger models tended to be easier to quantize.
  • Adding per-group scales improves the results further. With groups of 128, 3-bit OPT-175B reached 8.45 (an overhead of about 0.15 bits per weight).

Quantization took 20.9 minutes for OPT-13B and 4.2 hours for OPT-175B on a single A100 (Table 2).

Inference speed is also measured (Table 6: time per token when generating 128 tokens with batch size 1). 3-bit OPT-175B on a single A100 80GB took 71 ms, about 3.2 times faster than the 230 ms of 16 bits (on five of the same GPU). In generation, the speed of matrix-vector products is bound by how fast the weights can be read from memory, so smaller weights mean faster generation.

Practical Considerations

  • Only the weights are quantized. Activations stay at 16 bits, so the amount of computation itself does not decrease. The paper also states that the speedup comes from reduced memory traffic, not from less computation.
  • Speedups require dedicated kernels. Without kernels that read low-bit weights and dequantize them to 16 bits on the fly, memory usage goes down but speed does not improve.
  • Calibration data can be small but should not be biased. The paper uses 128 generic web texts (C4) and does not use data from the evaluation tasks.
  • The embedding and output layers stay at 16 bits. The paper's 3-bit OPT-175B (about 63GB) also keeps these two in FP16.

At 3 bits or below, how much accuracy drops varies greatly between models. In the paper, OPT-66B reached 14.16 at 3 bits, degrading much more than the neighboring model sizes. The paper suggests this may be related to the many nearly inactive units in the early layers of this model. After quantizing, always evaluate on data from the intended use case.

Comparison with Other Methods

The following table compares methods that reduce weights to low bit widths from the same perspectives.

MethodWhat it doesData requiredQuantization effort
RTN (simple rounding)Rounds each weight to the nearest valueNoneAlmost none
GPTQCancels the rounding error by adjusting the remaining weightsSmall (128 texts in the paper)Hessian-based computation (a few hours for 175B)
AWQScales up the weights of channels with large activations before roundingSmallSearch for scales (no backpropagation)
LLM.int8()Rounds to 8 bits and computes only the outlier dimensions in 16 bitsNoneAlmost none
QLoRARounds to 4 bits (NF4), freezes the weights, and trains with LoRATraining dataRequires fine-tuning
  • To greatly reduce memory for inference, 4-bit GPTQ or AWQ are good candidates. Neither requires training.
  • To keep the quantization procedure as simple as possible, 8-bit LLM.int8() is the easiest option.
  • To further tune the quantized model on your own data, use QLoRA.

PyTorch example

Show code
python
import torch

# Algorithm 1 of GPTQ written for a single linear layer (a small implementation for illustration)
# W: (out, in) weights. Columns = input dimensions, quantized from left to right
# X: (in, num_samples) layer inputs (collected by passing calibration data)


def make_quantizer(W, bits=4):
    """Per-row asymmetric min-max grid (same form as in the paper's experiments)"""
    qmax = 2 ** bits - 1
    lo = W.min(dim=1, keepdim=True).values.clamp(max=0)
    hi = W.max(dim=1, keepdim=True).values.clamp(min=0)
    scale = (hi - lo).clamp(min=1e-8) / qmax
    zero = torch.round(-lo / scale)

    def quant(w):  # w: one column of shape (out,)
        q = torch.clamp(torch.round(w / scale[:, 0]) + zero[:, 0], 0, qmax)
        return scale[:, 0] * (q - zero[:, 0])  # value on the grid (dequantized value)
    return quant


@torch.no_grad()
def gptq_quantize(W, X, bits=4, block_size=128, percdamp=0.01):
    W = W.clone().float()
    n_in = W.shape[1]
    quant = make_quantizer(W, bits)

    # 1. Hessian H = 2 X X^T plus a small lambda on the diagonal (1% of the diagonal mean)
    H = 2 * X @ X.T
    H += percdamp * torch.mean(torch.diag(H)) * torch.eye(n_in)

    # 2. Compute the upper-triangular Cholesky factor of H^{-1} once, up front
    Hinv = torch.linalg.cholesky(torch.cholesky_inverse(torch.linalg.cholesky(H)), upper=True)

    Q = torch.zeros_like(W)
    for i1 in range(0, n_in, block_size):            # 3. blocks of B columns
        i2 = min(i1 + block_size, n_in)
        W1 = W[:, i1:i2].clone()
        Q1 = torch.zeros_like(W1)
        Err1 = torch.zeros_like(W1)
        Hinv1 = Hinv[i1:i2, i1:i2]

        for j in range(i2 - i1):                     # 4. quantize column by column
            w = W1[:, j]
            q = quant(w)
            Q1[:, j] = q
            err = (w - q) / Hinv1[j, j]              # error E
            # 5. immediately distribute the error to the remaining columns in the block
            W1[:, j:] -= err.unsqueeze(1) @ Hinv1[j, j:].unsqueeze(0)
            Err1[:, j] = err

        Q[:, i1:i2] = Q1
        # 6. distribute the error to the columns right of the block all at once
        W[:, i2:] -= Err1 @ Hinv[i1:i2, i2:]
    return Q


torch.manual_seed(0)
n_out, n_in, n_samples = 64, 256, 2048
W = torch.randn(n_out, n_in) * 0.02
X = torch.randn(n_in, n_samples)

Q_gptq = gptq_quantize(W, X, bits=3)
quant = make_quantizer(W, bits=3)
Q_rtn = torch.stack([quant(W[:, j]) for j in range(n_in)], dim=1)  # simple rounding (RTN)

err = lambda Q: ((W @ X - Q @ X).norm() / (W @ X).norm()).item()
print("RTN  relative output error:", err(Q_rtn))
print("GPTQ relative output error:", err(Q_gptq))  # smaller than RTN

FAQ

Q. What is the difference between GPTQ and simple rounding (RTN)?
A.

RTN rounds each weight independently to the nearest grid value. GPTQ, each time it rounds a column, cancels the resulting error by adjusting the columns not yet rounded. As a result, each individual weight stays on the grid while the deviation of the layer output WXWX remains small. In the paper, the perplexity degradation of 4-bit OPT-175B was 0.03 with GPTQ versus 2.2 with RTN.

Q. How much data is needed for quantization?
A.

No labels are needed, and a small amount of text is enough. The paper uses only 128 randomly selected text segments of 2048 tokens from C4. These are used to collect the layer inputs XX and build the Hessian H=2XXโŠคH = 2XX^\top; the model is not retrained.

Q. Does quantizing with GPTQ make inference faster?
A.

It tends to be faster in settings such as text generation, where tokens are processed one at a time. There, computation is bound by how fast the weights are read from memory, so smaller weights make it faster. In the paper, 3-bit OPT-175B on a single A100 generated about 3.2 times faster than 16 bits (on five GPUs). However, dedicated kernels for low-bit weights are required, and since activations stay at 16 bits, the amount of computation does not decrease.

References

  1. E. Frantar, S. Ashkboos, T. Hoefler, and D. Alistarh, "GPTQ: Accurate Post-Training Quantization for Generative Pre-trained Transformers," ICLR, 2023. arXiv:2210.17323.
  2. E. Frantar, S. P. Singh, and D. Alistarh, "Optimal Brain Compression: A Framework for Accurate Post-Training Quantization and Pruning," arXiv:2208.11580, 2022.
  3. IST-DASLab, "gptq" (GitHub).