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 W be the weight of a linear layer (rows are outputs, columns are input dimensions) and X the layer input obtained by passing a small amount of data. The quantized weight W^ is chosen to minimize the change in the layer output (Eq. (1) in the paper).
W^=W^argminโโWXโW^Xโ22โ
This error is quadratic in the weights, and its Hessian is H=2XXโค. H depends only on the input X and is shared by every row of W.
When a weight wqโ is quantized to quant(wqโ), the optimal update of the remaining unquantized weights F that minimizes the error is given by the following formula (the OBQ update, Eq. (2) in the paper).
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).
Pass calibration data to collect the layer input X and compute H=2XXโค. For numerical stability, add ฮป, equal to 1% of the mean of the diagonal, to the diagonal.
Compute the Cholesky decomposition of Hโ1, precomputing all the information needed later just once.
Split the weight columns, from left to right, into blocks of B=128 columns.
Within a block, quantize column j and compute the error E:,jโ=(W:,jโโQ:,jโ)/[Hโ1]jjโ.
Multiply that error by row j of Hโ1 and subtract it from the not-yet-quantized columns in the block.
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.
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.
Technique
What it does
Effect
Fixed order
Every row quantizes the columns in the same left-to-right order (OBQ picks the weight with the smallest error first)
Hโ1 needs to be updated only once per column, reducing the cost from O(drowโโ dcol3โ) to O(max{drowโโ dcol2โ,ย dcol3โ})
Lazy batch updates
Update only the columns inside a 128-column block first, and update the columns outside the block at once at the end of the block
Fewer memory reads and writes, making efficient use of the GPU
Cholesky decomposition
Compute the required parts of Hโ1 up front with a numerically stable method
Prevents 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โ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 WX 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โค 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.
Model
16-bit
RTN 4-bit
GPTQ 4-bit
RTN 3-bit
GPTQ 3-bit
OPT-1.3B
14.63
48.17
15.47
1.3e4
20.97
OPT-13B
10.13
11.32
10.31
3.4e3
11.61
OPT-175B
8.34
10.54
8.37
7.3e3
8.68
BLOOM-176B
8.11
8.37
8.21
571
8.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.
Method
What it does
Data required
Quantization effort
RTN (simple rounding)
Rounds each weight to the nearest value
None
Almost none
GPTQ
Cancels the rounding error by adjusting the remaining weights
Rounds to 4 bits (NF4), freezes the weights, and trains with LoRA
Training data
Requires 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 WX 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 X and build the Hessian H=2XXโค; 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.