Quantization · LLMs

GPTQ: Accurate Post-Training Quantization for Generative Pre-trained Transformers

Round a large language model's weights to 3 or 4 bits one column at a time, adjusting the weights not yet rounded to cancel each rounding error.

GPTQ compresses a trained model one linear layer at a time, with no retraining. It picks rounding decisions that keep each layer's outputs on a few hundred thousand sample tokens close to the original, and it does this for a 175-billion-parameter model in about four hours on a single GPU.

Explaining the paperGPTQ: Accurate Post-Training Quantization for Generative Pre-trained TransformersFrantar, Ashkboos, Hoefler, Alistarh · ICLR 2023 · arXiv:2210.17323 ↗

Before this paper, only 8-bit rounding had been applied to models of this size. GPTQ put the 3-bit OPT-175B on one 80 GB A100 and generated text with it 3.24 times faster than the FP16 model running on five.

OPT-175B and BLOOM-176B store each weight as a 16-bit float, two bytes. OPT-175B's weights take 326 GiB, so inference needs five 80 GB A100 GPUs before it generates a single token. Quantization stores each weight in fewer bits. At 3 bits per weight OPT-175B takes about 63 GB, which fits on one A100 with room for the attention cache.

The simplest way to get there is round-to-nearest (RTN): move every weight to the closest value on a coarse grid, independently of all the others. At 8 bits this works, and it was the only kind of weight quantization applied at this scale before GPTQ, in ZeroQuant and in LLM.int8(). At 4 bits it raises OPT-175B's WikiText2 perplexity (a measure of how well the model predicts held-out text, lower is better) from 8.34 to 10.54. At 3 bits it gives about 7,300, which means the model's output is noise. GPTQ, by Elias Frantar, Saleh Ashkboos, Torsten Hoefler and Dan Alistarh (IST Austria and ETH Zurich), uses the same grid and gets 8.37 at 4 bits and 8.68 at 3 bits. The name merges OPT with PTQ, for post-training quantization: compressing a finished model using a small amount of sample data and no retraining, which at 175 billion parameters would cost far more than the quantization itself.

The method is built from five pieces, in the order this page covers them:

  1. a per-row grid of 8 or 16 levels, the same one RTN uses;
  2. a per-layer objective: keep the layer's outputs on sample inputs unchanged, not its weights;
  3. error compensation, from the Optimal Brain Surgeon pruning method of 1993: after rounding one weight, shift the not-yet-rounded weights of the same row to cancel the change in the outputs;
  4. one shared column order for all rows, which makes the bookkeeping for that compensation 12,288 times cheaper on OPT-175B's layers;
  5. two implementation changes, batched updates and a Cholesky factorization, that make it fast and numerically stable on a GPU.

What 3-bit and 4-bit weights mean

A bb-bit weight is stored as an integer code kk between 0 and 2b−12^b - 1. The value it stands for is reconstructed from two numbers shared by the whole row of the weight matrix, a scale ss and a zero point zz:

k=clamp(round(w/s)+z, 0, 2b−1),w^=s (k−z)k = \mathrm{clamp}\big(\mathrm{round}(w/s) + z,\ 0,\ 2^b - 1\big), \qquad \hat w = s\,(k - z)k=clamp(round(w/s)+z, 0, 2b−1),w^=s (k−z)\begin{gathered} k = \mathrm{clamp}\big(\mathrm{round}(w/s) + z,\ 0,\ 2^b - 1\big), \\ \hat w = s\,(k - z) \end{gathered}

GPTQ uses the grid from the official quant.py: asymmetric, min-max, one per row. Take the smallest and largest weight in the row, widen the range to include 0 if it does not already, and spread the 2b2^b levels evenly across it, so s=(max⁡−min⁡)/(2b−1)s = (\max - \min)/(2^b - 1) and z=round(−min⁡/s)z = \mathrm{round}(-\min / s). Asymmetric means the range need not be centered on zero; the zero point is the code that represents 0.

Figure 1 shows 16 weights from one row. At 3 bits the smallest weight is −0.033 and the largest 0.094, so s=0.127/7=0.0181s = 0.127/7 = 0.0181 and z=round(1.82)=2z = \mathrm{round}(1.82) = 2. The eight levels are −0.0363, −0.0181, 0, 0.0181, 0.0363, 0.0544, 0.0726 and 0.0907. The weight 0.094 is stored as code 7 and comes back as 0.0907; the weight 0.012 is code 3 and comes back as 0.0181. The root-mean-square rounding error over the row is 0.0056.

Figure 1 · the quantization grid
levels 8step 0.0181RMS error 0.0056max error 0.0090
Each teal dot is a weight; the amber ring is the grid level it rounds to, and the amber lines are the levels. Switch between 2, 3, 4 and 8 bits, and between one grid for the row and one grid per group of 4 weights.

At 2 bits only four levels remain (−0.042, 0, 0.042 and 0.085), 9 of the 16 weights round to 0, and the RMS error rises to 0.0142. The one large weight at index 5 sets the top of the range, so the levels are spaced for it rather than for the 15 small weights. With groups of 4 that weight only widens its own group's grid and the 2-bit RMS error drops to 0.0085. Grouping costs a scale and a zero point per group; it comes back in the section on 2-bit results. Without groups, the scale and zero point are shared by 12,288 or 49,152 weights in OPT-175B, so their storage is negligible.

RTN applies this rounding to every weight on its own. GPTQ keeps the same grid, fixed from the original weights before it starts, and changes which level each weight lands on by modifying weights before they are rounded.

The layer-wise objective

Measuring the effect of a rounding choice on the full model's loss would need a forward pass of the whole model per choice. GPTQ, like the earlier post-training methods it builds on, works one linear layer at a time. Let W\mathbf{W} be a layer's weights, drow×dcold_\text{row} \times d_\text{col} (one row per output, one column per input), and let X\mathbf{X} be dcol×md_\text{col} \times m: the inputs this layer receives for mm sample tokens, one per column. The goal is the grid-valued W^\widehat{\mathbf{W}} whose outputs on those inputs are closest to the original outputs:

argmin⁡W^ ∥WX−W^X∥22\operatorname{argmin}_{\widehat{\mathbf{W}}}\ \big\| \mathbf{W}\mathbf{X} - \widehat{\mathbf{W}}\mathbf{X} \big\|_2^2
(1)

For the first feed-forward layer (fc1) of OPT-175B, W\mathbf{W} is 49,152 × 12,288. The sample inputs are 128 sequences of 2,048 tokens, so X\mathbf{X} is 12,288 × 262,144.

The objective is about outputs because weights with correlated inputs can trade errors. If two inputs always carry the same value, rounding one weight up by 0.01 and the other down by 0.01 leaves every output unchanged, while RTN would count two errors of 0.01. RTN minimizes ∣w−w^∣|w - \hat w| weight by weight and never looks at X\mathbf{X}.

The squared error in (1) is a sum over rows, since each output depends only on its own row of weights. For one row w\mathbf{w} (a row vector) with error e=w−w^\mathbf{e} = \mathbf{w} - \hat{\mathbf{w}}:

∥eX∥2=e XX⊤e⊤=12 e H e⊤,H=2XX⊤\|\mathbf{e}\mathbf{X}\|^2 = \mathbf{e}\,\mathbf{X}\mathbf{X}^\top\mathbf{e}^\top = \tfrac{1}{2}\,\mathbf{e}\,\mathbf{H}\,\mathbf{e}^\top, \qquad \mathbf{H} = 2\mathbf{X}\mathbf{X}^\top∥eX∥2=e XX⊤e⊤=12 e H e⊤,H=2XX⊤\begin{gathered} \|\mathbf{e}\mathbf{X}\|^2 = \mathbf{e}\,\mathbf{X}\mathbf{X}^\top\mathbf{e}^\top = \tfrac{1}{2}\,\mathbf{e}\,\mathbf{H}\,\mathbf{e}^\top, \\ \mathbf{H} = 2\mathbf{X}\mathbf{X}^\top \end{gathered}

H\mathbf{H} is the Hessian, the matrix of second derivatives of the squared error with respect to the row's weights. The error is a quadratic in the weights, so H\mathbf{H} is constant and describes it exactly. It is dcol×dcold_\text{col} \times d_\text{col}, and entry (i,j)(i, j) is twice the summed product of inputs ii and jj over the sample tokens, so it records which inputs move together. It depends only on the inputs, which means every row of the layer has the same H\mathbf{H}. For OPT-175B's second feed-forward layer (fc2) it is 49,152 × 49,152, 9.7 GB in fp32. The code builds it by streaming the sample tokens through the layer and adding 2xx⊤2\mathbf{x}\mathbf{x}^\top for each one (scaled by the number of sequences, which changes nothing below because every formula divides one entry of H−1\mathbf{H}^{-1} by another).

Solving (1) exactly means searching the grid: at 3 bits a row of 12,288 weights has 8122888^{12288} possible roundings. RTN is one cheap point in that space. GPTQ is a greedy method that picks the rounding of one column at a time and corrects for it.

How error compensation works

Floyd–Steinberg dithering, from image processing, works the same way. It converts a grayscale image to black and white one pixel at a time, and each pixel's rounding error is added to the neighbouring pixels that have not been converted yet, so the average brightness of a region survives. GPTQ does the same along a row of weights. Where the analogy breaks: dithering spreads a fixed fraction to four neighbours, while GPTQ computes from H\mathbf{H} how much of the error every remaining weight should absorb, and those amounts can be negative and reach every weight not yet rounded.

The amounts come from the Optimal Brain Surgeon (OBS) of Hassibi and Stork (1993), a pruning method. For a quadratic error with Hessian H\mathbf{H}, OBS gives the best way to remove weight qq (set it to 0) while moving all other weights to compensate. Optimal Brain Quantization (OBQ), from Frantar, Singh and Alistarh earlier in 2022, replaces "set to 0" with "set to its grid value". Let FF be the set of weights in the row not yet quantized and HF\mathbf{H}_F the Hessian restricted to them. OBQ picks the next weight and the update δF\boldsymbol{\delta}_F to all of FF by

wq=argmin⁡wq(quant(wq)−wq)2[HF−1]qq,δF=−wq−quant(wq)[HF−1]qq⋅(HF−1):,qw_q = \operatorname{argmin}_{w_q} \frac{(\mathrm{quant}(w_q) - w_q)^2}{[\mathbf{H}_F^{-1}]_{qq}}, \qquad \boldsymbol{\delta}_F = -\frac{w_q - \mathrm{quant}(w_q)}{[\mathbf{H}_F^{-1}]_{qq}} \cdot (\mathbf{H}_F^{-1})_{:,q}wq=argmin⁡wq(quant(wq)−wq)2[HF−1]qq,δF=−wq−quant(wq)[HF−1]qq⋅(HF−1):,q\begin{gathered} w_q = \operatorname{argmin}_{w_q} \frac{(\mathrm{quant}(w_q) - w_q)^2}{[\mathbf{H}_F^{-1}]_{qq}}, \\ \boldsymbol{\delta}_F = -\frac{w_q - \mathrm{quant}(w_q)}{[\mathbf{H}_F^{-1}]_{qq}} \cdot (\mathbf{H}_F^{-1})_{:,q} \end{gathered}
(2)

The update is a multiple of column qq of the inverse Hessian. Its own entry qq equals −(wq−quant(wq))-(w_q - \mathrm{quant}(w_q)), which moves wqw_q exactly onto the grid, and the other entries shift the remaining weights. The update raises the row's output error by (wq−quant(wq))2/(2[HF−1]qq)(w_q - \mathrm{quant}(w_q))^2 / (2[\mathbf{H}_F^{-1}]_{qq}), the quantity the first formula minimizes; greedy OBQ quantizes whichever weight is cheapest at that moment. Both formulas come from minimizing the error increase 12δHδ⊤\tfrac{1}{2}\boldsymbol{\delta}\mathbf{H}\boldsymbol{\delta}^\top under the single constraint that entry qq of δ\boldsymbol{\delta} puts wqw_q on the grid; with a Lagrange multiplier the solution is proportional to H−1\mathbf{H}^{-1} times the unit vector for qq, which is column qq of the inverse.

Take a row with two weights whose inputs have unit variance and correlation ρ\rho, so XX⊤/m\mathbf{X}\mathbf{X}^\top/m is (1ρρ1)\begin{pmatrix}1 & \rho\\ \rho & 1\end{pmatrix} and the output error per sample is e12+2ρ e1e2+e22e_1^2 + 2\rho\, e_1 e_2 + e_2^2. Quantize w1w_1 first. Plugging this H\mathbf{H} into (2) gives

w1→quant(w1),w2→w2+ρ (w1−quant(w1))w_1 \to \mathrm{quant}(w_1), \qquad w_2 \to w_2 + \rho\,\big(w_1 - \mathrm{quant}(w_1)\big)w1→quant(w1),w2→w2+ρ (w1−quant(w1))\begin{gathered} w_1 \to \mathrm{quant}(w_1), \\ w_2 \to w_2 + \rho\,\big(w_1 - \mathrm{quant}(w_1)\big) \end{gathered}

Rounding w1w_1 down by dd removes d x1d\,x_1 from the output. Input x2x_2 follows x1x_1 with correlation ρ\rho, so raising w2w_2 by ρd\rho d restores the part of that loss that x2x_2 can predict. The error left over is (1−ρ2) d2(1 - \rho^2)\,d^2, against d2d^2 with no compensation; at ρ=0.8\rho = 0.8 compensation removes 64% of it.

Take w=(1.42,1.45)\mathbf{w} = (1.42, 1.45), ρ=0.8\rho = 0.8 and a 2-bit grid with levels 0, 1, 2, 3. RTN rounds both down to (1, 1), with output error 0.681. GPTQ rounds w1w_1 to 1 (error 0.42), moves w2w_2 to 1.45+0.8×0.42=1.7861.45 + 0.8 \times 0.42 = 1.786, and rounds that to 2. The result (1, 2) has output error 0.109, about a sixth of RTN's, and is the best of all 16 grid points.

Figure 2 · compensation with two weights
0.80
1.42
1.45
nearest (1, 1) err 0.681GPTQ (1, 2) err 0.109best (1, 2) err 0.109GPTQ / nearest 0.16
The white dot is the true pair of weights (drag it, or use the w1 and w2 sliders); grey dots are the 2-bit grid. Each ellipse is a set of points with equal output error: dashed amber through the round-to-nearest choice, solid teal through GPTQ's. The teal path rounds the first weight while shifting the second, then rounds the second. The violet ring marks the best grid point.

In Figure 2 the nearest grid point in straight-line distance can sit on a larger ellipse than a farther one, because output error is measured along the ellipses, not in circles. Drag ρ\rho to 0 and the ellipses become circles, the shift ρ (w1−quant(w1))\rho\,(w_1 - \mathrm{quant}(w_1)) vanishes, and GPTQ and RTN agree. Near ρ=±0.99\rho = \pm 0.99 the ellipses are long and thin and the shift is nearly the full rounding error. Switching to "w2 first" at the default weights gives (2, 1) with error 0.121: the order changes the answer, here by a little.

After quantizing wqw_q, OBQ needs HF−1\mathbf{H}_F^{-1} for the smaller set FF without qq. Removing a weight deletes its row and column from H\mathbf{H}, but the inverse of the smaller matrix is not the old inverse with a row and column deleted. One step of Gaussian elimination on the old inverse gives it in O(dcol2)O(d_\text{col}^2) operations instead of the O(dcol3)O(d_\text{col}^3) of a fresh inversion:

H−q−1=(H−1−1[H−1]qq H:,q−1 Hq,:−1)−q\mathbf{H}_{-q}^{-1} = \Big(\mathbf{H}^{-1} - \frac{1}{[\mathbf{H}^{-1}]_{qq}}\, \mathbf{H}^{-1}_{:,q}\,\mathbf{H}^{-1}_{q,:}\Big)_{-q}
(3)

Here (⋅)−q(\cdot)_{-q} means "with row and column qq deleted". The subtraction zeroes row and column qq; what remains is the inverse of H\mathbf{H} with qq removed (the Schur-complement identity for block matrices).

OBQ runs (2) and (3) weight by weight, each row in its own greedy order. Each row has dcold_\text{col} steps that each touch a dcol×dcold_\text{col} \times d_\text{col} inverse, so a layer costs O(drow⋅dcol3)O(d_\text{row} \cdot d_\text{col}^3). It quantizes ResNet-50, 25 million parameters, in about an hour on one GPU. For OPT-175B's fc1 layer alone, drow⋅dcol3d_\text{row} \cdot d_\text{col}^3 is about 9×10169 \times 10^{16}.

How GPTQ works: one column order for every row

Step 1 of the paper rests on an empirical finding: greedy order, always quantizing the currently cheapest weight, does only slightly better than quantizing the weights in an arbitrary fixed order, and the gap shrinks on large layers. The authors' explanation, which they present as likely rather than proven: the few weights with large rounding errors that greedy order postpones get quantized near the end, when few unquantized weights are left to absorb their error.

If order barely matters, GPTQ can choose the same order for every row: column 0 first, then column 1, and so on. Then the set FF of unquantized positions is the same in every row at every step. HF−1\mathbf{H}_F^{-1} depends only on the inputs, so it is also the same for every row. One application of (3) per column now serves all drowd_\text{row} rows, so (3) runs dcold_\text{col} times instead of drow⋅dcold_\text{row} \cdot d_\text{col}. The cost falls to O(max⁡{drowdcol2, dcol3})O(\max\{d_\text{row} d_\text{col}^2,\ d_\text{col}^3\}), smaller by a factor of min⁡{drow,dcol}\min\{d_\text{row}, d_\text{col}\}, which is 12,288 for every linear layer of OPT-175B.

Each step now quantizes a whole column. For column qq, compute the rounding error of every row at once (a vector of length drowd_\text{row}), divide by [HF−1]qq[\mathbf{H}_F^{-1}]_{qq}, and subtract its outer product with row qq of HF−1\mathbf{H}_F^{-1} from the columns still to come. That is (2) for all rows in one rank-1 matrix update.

Figure 3 runs this on a toy layer of 12 outputs and 24 inputs, with 192 sample inputs whose neighbouring features are correlated (about 0.73 for adjacent columns) and share a common component. In the "change from original" view, quantized columns show their rounding errors and the columns to the right show the compensation building up. The bars under the matrix show how far each later column moved when the latest column was rounded: most for its neighbours, but every later column moves.

Figure 3 · GPTQ column by column
9/24
GPTQ error 0.13%nearest error 0.87%final ratio 0.11
Top: the 12 × 24 weight matrix (teal positive, amber negative), with the column just quantized outlined. Middle: how much each later column moved at that step. Bottom: output error as a percentage of the layer's output energy, for GPTQ and for round-to-nearest, as columns are quantized. Press play or scrub; switch bits and views.

At 3 bits the toy layer ends with 0.49% output error under GPTQ and 4.35% under RTN; at 2 bits, 2.94% against 15.81%; at 4 bits, 0.11% against 0.49%. The toy's inputs are more correlated than a typical layer's, so the size of the gap here is illustrative. The real comparison is the perplexity of whole models, later on this page.

Lazy batch updates

The column loop is sequential, and each step rewrites every remaining column: a drowd_\text{row} × (remaining columns) region of W\mathbf{W}, read and written once, with two floating-point operations (a multiply and a subtract) per entry. In fp32 that is 8 bytes of memory traffic for 2 FLOPs, 0.25 FLOP per byte. An A100 does 19.5 trillion fp32 operations per second and moves about 2 TB per second, so it needs roughly 10 FLOPs per byte to keep its arithmetic units busy. At 0.25 the loop waits on memory.

Step 2 of the paper uses one observation: the rounding of column ii depends only on updates already applied to column ii. Updates to columns further right can wait. GPTQ therefore processes B=128B = 128 columns at a time. Inside the block, each step updates only the block's own columns. When the block is done, the 128 pending updates are applied to all later columns in one matrix multiplication, with the multi-weight versions of (2) and (3) for the set QQ of the block's indices:

δF=−(wQ−quant(wQ)) ([HF−1]QQ)−1 (HF−1)Q,:\boldsymbol{\delta}_F = -\big(\mathbf{w}_Q - \mathrm{quant}(\mathbf{w}_Q)\big)\,\big([\mathbf{H}_F^{-1}]_{QQ}\big)^{-1}\,(\mathbf{H}_F^{-1})_{Q,:}δF=−(wQ−quant(wQ))([HF−1]QQ)−1 (HF−1)Q,:\begin{aligned} \boldsymbol{\delta}_F = &-\big(\mathbf{w}_Q - \mathrm{quant}(\mathbf{w}_Q)\big) \\ &\big([\mathbf{H}_F^{-1}]_{QQ}\big)^{-1}\,(\mathbf{H}_F^{-1})_{Q,:} \end{aligned}
(4)
H−Q−1=(H−1−H:,Q−1([H−1]QQ)−1HQ,:−1)−Q\mathbf{H}_{-Q}^{-1} = \Big(\mathbf{H}^{-1} - \mathbf{H}^{-1}_{:,Q}\big([\mathbf{H}^{-1}]_{QQ}\big)^{-1}\mathbf{H}^{-1}_{Q,:}\Big)_{-Q}H−Q−1=(H−1−H:,Q−1([H−1]QQ)−1HQ,:−1)−Q\begin{aligned} \mathbf{H}_{-Q}^{-1} = \Big(&\mathbf{H}^{-1} \\ &- \mathbf{H}^{-1}_{:,Q}\big([\mathbf{H}^{-1}]_{QQ}\big)^{-1}\mathbf{H}^{-1}_{Q,:}\Big)_{-Q} \end{aligned}
(5)

Summing 128 rank-1 updates gives the same matrix as one rank-128 product, so the quantized weights are identical for every block size; only the order of memory accesses changes. The block-end product reads and writes the trailing columns once per 128 columns, so its traffic falls by a factor of 128 while its FLOPs stay the same.

Figure 4 counts the traffic for the three layer shapes of OPT-175B. For fc1 (49,152 × 12,288) at B=1B = 1, the weight updates move about 30 TB, which takes 14.8 s at 2 TB/s against 0.38 s of arithmetic. At B=128B = 128 the traffic drops to 541 GB and the step is limited by arithmetic. Very large blocks bring the problem back from the other side: inside a block every step still rewrites the block's remaining columns, and that traffic grows with BB. At B=dcolB = d_\text{col} the whole layer is one block and the traffic matches B=1B = 1.

Figure 4 · block size and memory traffic
128
traffic 541 GBFLOPs 7.4 Testimate 381 ms, compute-boundcompute-bound for B 64–256
A traffic model of Algorithm 1's weight updates on one OPT-175B layer in fp32, at A100 peak rates. Memory time = bytes moved / 2.0 TB/s; compute time = FLOPs / 19.5 TFLOP/s. Every block size gives the same quantized weights. Estimates from the model, not measurements.

In this model all three layer shapes are compute-bound from B=64B = 64 to at least 256, so the paper's fixed 128 sits in the flat part. The model covers only the weight updates; the measured runtime also includes forward passes and building H\mathbf{H}. The paper reports that lazy batching gives an order-of-magnitude speedup in practice for very large models.

The Cholesky reformulation

At large scale the repeated updates (5) accumulate floating-point error, and HF−1\mathbf{H}_F^{-1} can become indefinite: it acquires a negative eigenvalue, which the inverse of 2XX⊤2\mathbf{X}\mathbf{X}^\top can never have, and the updates computed from it no longer reduce the error. The compensation then pushes weights the wrong way and the layer's quantization is ruined. The paper reports this almost always happens in at least a few layers of models larger than a few billion parameters.

Dampening is the first defence: add λ\lambda, 1% of the mean diagonal entry of H\mathbf{H}, to every diagonal entry. This acts as if each input carried a little extra independent noise, which keeps H\mathbf{H} well conditioned and makes the compensation slightly more cautious. It is enough for small models; on larger ones the paper still saw failures.

Step 3 uses the fact that when column qq is quantized, the algorithm reads only row qq of HFq−1\mathbf{H}_{F_q}^{-1} (where FqF_q is the set of columns from qq onward), from the diagonal to the right. Those rows can all be computed in advance. Factor H−1=U⊤U\mathbf{H}^{-1} = \mathbf{U}^\top\mathbf{U} with U\mathbf{U} upper-triangular (the Cholesky decomposition). Cholesky factorization eliminates one row and column at a time, by the same Gaussian elimination as (3), and stores each eliminated row divided by the square root of its pivot. So row qq of U\mathbf{U} is the row GPTQ needs, rescaled:

Uq, q:=[HFq−1]q, q:[HFq−1]qq,H−1=U⊤U\mathbf{U}_{q,\,q:} = \frac{[\mathbf{H}_{F_q}^{-1}]_{q,\,q:}}{\sqrt{[\mathbf{H}_{F_q}^{-1}]_{qq}}}, \qquad \mathbf{H}^{-1} = \mathbf{U}^\top\mathbf{U}Uq, q:=[HFq−1]q, q:[HFq−1]qq,H−1=U⊤U\begin{gathered} \mathbf{U}_{q,\,q:} = \frac{[\mathbf{H}_{F_q}^{-1}]_{q,\,q:}}{\sqrt{[\mathbf{H}_{F_q}^{-1}]_{qq}}}, \\ \mathbf{H}^{-1} = \mathbf{U}^\top\mathbf{U} \end{gathered}

A 3 × 3 example. Take

H=(421231112),H−1=113(5−3−1−37−2−1−28)\mathbf{H} = \begin{pmatrix}4&2&1\\2&3&1\\1&1&2\end{pmatrix}, \quad \mathbf{H}^{-1} = \tfrac{1}{13}\begin{pmatrix}5&-3&-1\\-3&7&-2\\-1&-2&8\end{pmatrix}H=(421231112),H−1=113(5−3−1−37−2−1−28)\begin{gathered} \mathbf{H} = \begin{pmatrix}4&2&1\\2&3&1\\1&1&2\end{pmatrix}, \\ \mathbf{H}^{-1} = \tfrac{1}{13}\begin{pmatrix}5&-3&-1\\-3&7&-2\\-1&-2&8\end{pmatrix} \end{gathered}
U=(0.6202−0.3721−0.124000.6325−0.3162000.7071)\mathbf{U} = \begin{pmatrix}0.6202&-0.3721&-0.1240\\0&0.6325&-0.3162\\0&0&0.7071\end{pmatrix}

Row 0 of U\mathbf{U} is row 0 of H−1\mathbf{H}^{-1} divided by 5/13\sqrt{5/13}. Remove weight 0 with (3) and the remaining inverse is (0.4−0.2−0.20.6)\begin{pmatrix}0.4&-0.2\\-0.2&0.6\end{pmatrix}, which is also the inverse of the lower-right 2 × 2 block of H\mathbf{H}. Its first row divided by 0.4\sqrt{0.4} is (0.6325, −0.3162), row 1 of U\mathbf{U}. Now quantize a row w=(0.70,0.40,−0.20)\mathbf{w} = (0.70, 0.40, -0.20) on a grid of step 0.5. The first weight rounds to 0.5, an error of 0.20. GPTQ divides by the diagonal entry, 0.20 / 0.6202 = 0.3225, and subtracts 0.3225 × (−0.3721, −0.1240) from the other two weights, raising them by 0.120 and 0.040. Equation (2) gives the same numbers directly: −0.20×(−3/13)/(5/13)=0.12-0.20 \times (-3/13)/(5/13) = 0.12 and −0.20×(−1/13)/(5/13)=0.04-0.20 \times (-1/13)/(5/13) = 0.04.

The implementation inverts the dampened H\mathbf{H} once (through its own Cholesky factor), takes the upper Cholesky factor of the inverse, and never applies (5) at all. Cholesky factorization is numerically stable and has optimized GPU kernels, which the paper notes also add a further speedup; with mild dampening it reports no numerical problems on the largest models. Algorithm 1 in the paper overwrites H−1\mathbf{H}^{-1} with this factor, so its [H−1]jj[\mathbf{H}^{-1}]_{jj} is the factor's diagonal, [HF−1]jj\sqrt{[\mathbf{H}_{F}^{-1}]_{jj}}, not the denominator of (2).

The full algorithm

Put together, one layer is quantized by the loop below, a lightly annotated transcription of fasterquant in the official gptq.py. Inside the inner loop every operation is on a whole column (all drowd_\text{row} rows at once); the last line of the outer loop is the only large matrix multiplication.

# GPTQ on one linear layer, after fasterquant() in gptq.py.
# W: d_row x d_col weights (fp32). H = 2 X X^T: d_col x d_col.
# quant(): round to each row's grid (scale and zero fixed beforehand).
H += 0.01 * mean(diag(H)) * I            # dampening: 1% of the mean diagonal
U = cholesky(inverse(H), upper=True)     # inverse(H) = U^T U, U upper-triangular
Q = zeros_like(W)
for i1 in range(0, d_col, B):            # B = 128 columns per block
    i2 = min(i1 + B, d_col)
    W1 = W[:, i1:i2].clone()             # the block, d_row x B
    Err = zeros_like(W1)
    for i in range(i2 - i1):
        j = i1 + i                       # global column index
        q = quant(W1[:, i])              # round a whole column (all rows)
        Q[:, j] = q
        err = (W1[:, i] - q) / U[j, j]   # vector of length d_row
        W1[:, i:] -= outer(err, U[j, j:i2])   # compensate inside the block
        Err[:, i] = err
    W[:, i2:] -= Err @ U[i1:i2, i2:]     # one matmul for every later column
return Q

For OPT-175B's fc1 layer this is 96 blocks of 128 columns. In each column step err is a vector of 49,152 values and the in-block update touches at most 49,152 × 128 entries. At the end of a block the update multiplies a 49,152 × 128 error matrix by a 128 × (remaining) slice of U\mathbf{U}. Nothing in the loop receives a gradient. The only inputs are the weights, the Hessian built from sample activations, and the grid.

Quantizing a whole model

The sample data is 128 random segments of 2,048 tokens from C4, the web-crawl corpus built for T5: generic text with nothing from the evaluation tasks, which is why the paper can still call its task results zero-shot.

The model is processed one Transformer block at a time, so the GPU never holds more than one block's weights. An OPT block has six linear layers: the query, key, value and output projections of attention (each 12,288 × 12,288) and the two feed-forward layers fc1 and fc2. The procedure, transcribed from opt.py:

# Whole model, after opt.py. Calibration: 128 C4 segments x 2048 tokens.
x = embed(calibration_tokens)            # 128 x 2048 x 12288 for OPT-175B
for block in model.blocks:               # 96 blocks; only this one on the GPU
    H = {lin: zeros(d_in, d_in) for lin in block.linears}   # 6 linears
    block(x)                             # hooks add 2 x x^T into each H[lin]
    for lin in block.linears:
        lin.weight = gptq(lin.weight, H[lin])
    x = block(x)                         # rerun through the QUANTIZED block

Because the inputs to each block come from blocks already quantized, later layers are fitted to the inputs they will actually receive, errors of earlier layers included. The paper reports noticeable improvements from this at negligible cost. In the released code, the six layers inside one block all take their Hessians from a single pass of that block before any of them is quantized, so fc2's Hessian reflects full-precision fc1 outputs; a later --true-sequential option quantizes the layers of a block one after another.

Runtimes on one 80 GB A100 (Table 2): OPT-13B in 20.9 minutes, OPT-30B in 44.9 minutes, OPT-66B in 1.6 hours, OPT-175B in 4.2 hours; BLOOM-176B in 3.8 hours. For comparison the paper cites ZeroQuant-LKD, a method that distils each layer with gradient steps: 3 hours for a 1.3B model on the same hardware, which extrapolates to several hundred hours at 175B.

How accurate is GPTQ at 3 and 4 bits

The main metric is perplexity on WikiText2, a set of Wikipedia articles: ee raised to the average negative log-probability the model assigns to each actual next token, computed over the test set in 2,048-token segments. A perplexity of 8.34 means the model is, on average, as uncertain as a uniform choice among 8.34 tokens. The paper chose perplexity because it is known to be more sensitive to quantization than most task accuracies.

Figure 5 · WikiText2 perplexity by model size
175B
FP16 8.344-bit RTN 10.54 GPTQ 8.373-bit RTN 7.3e3 GPTQ 8.68
Tables 3 and 4 of the paper. Lower is better; log scale. Triangles at the top edge are values off the chart (the readout row gives them). Click a model size or use the slider; switch between OPT and BLOOM.

On OPT-175B, 4-bit GPTQ scores 8.37 against 8.34 for FP16, an increase of 0.03. 4-bit RTN scores 10.54, worse than the full-precision OPT-13B (10.13), a model about one thirteenth the size. At 3 bits RTN gives about 7,300 and GPTQ 8.68, an increase of 0.34. BLOOM-176B behaves the same way with smaller gaps: 8.11 in FP16, 8.21 with 4-bit GPTQ, 8.64 with 3-bit GPTQ and 571 with 3-bit RTN.

Small models lose more. At 3 bits, OPT-125M goes from 27.65 to 53.85 under GPTQ. Moving the slider from left to right in Figure 5 shows the 3-bit GPTQ curve approaching the FP16 curve as models grow, with one exception: OPT-66B (14.16 against 9.34), which the paper links to a large fraction of dead units in that model's early layers.

Table 5 extends this to two more perplexity sets and one accuracy task for the two largest models. For OPT-175B at 4 bits: WikiText2 8.37, Penn Treebank 12.26, C4 10.28, against 8.34, 12.01 and 10.13 in FP16; LAMBADA accuracy (predict the last word of a passage) is 76.80% against 75.59%. At 3 bits: 8.68, 12.68 and 10.67, and 76.19% on LAMBADA. On the zero-shot tasks (LAMBADA, ARC, PIQA), even RTN is usable at 4 bits, and at 3 bits RTN fails while GPTQ holds up.

The paper also checks GPTQ against slower methods where those can run. On ResNet-18 and ResNet-50 for ImageNet (Table 1) it matches AdaRound, BRECQ and OBQ at 4 bits (ResNet-18: 69.37% against OBQ's 69.56%) and trails them slightly at 3 bits (67.88% against 68.69%), while beating AdaQuant, the fastest of them. Against full greedy OBQ on BERT-base and OPT-125M (Table 8) the two are close at 4 bits and GPTQ is better at 3 bits: 86.02 against 85.29 F1 on SQuAD, and 53.85 against 69.32 perplexity on OPT-125M. GPTQ takes under a minute on these models where OBQ takes about an hour.

Grouping, 2-bit and ternary weights

Grouping gives every gg consecutive weights of a row their own scale and zero point, as in the "groups of 4" mode of Figure 1. The paper charges each group an FP16 scale and a bb-bit zero point, so the overhead is (16+b)/g(16 + b)/g bits per weight: 0.02 bits at 3 bits with g=1024g = 1024, and 0.15 bits with g=128g = 128. GPTQ computes each group's grid when the sweep reaches the group's first column, from the weights as they are at that moment, compensation included (gptq.py lines 120-123).

On OPT-175B at 3 bits, WikiText2 perplexity goes from 8.68 (one grid per row) to 8.45 with g=1024g = 1024 and stays at 8.45 with g=128g = 128; BLOOM-176B goes from 8.64 to 8.35 to 8.26. Grouping also makes 2 bits usable (Table 7). On OPT-175B, 2-bit GPTQ scores 9.58 with g=128g = 128 (about 2.2 bits per weight once the group data is counted), 9.18 with g=64g = 64, and 8.94 with g=32g = 32 (about 2.6 bits), against 8.34 in FP16. With groups of 8 the paper goes to ternary weights, three levels per group, and reports 9.20 on OPT-175B. In the code those three levels are the group's minimum, 0 and the group's maximum.

Figure 6 · fitting OPT-175B on A100s
bits/weight 3.00weights 61.9 GiB+ cache 9.0 GiBGPUs 1Wiki2 ppl 8.68
Memory for generation with OPT-175B: weights (linear layers at the chosen bit width plus group data, embeddings in FP16) and the key/value cache for 2,048 tokens, packed onto 80 GiB GPUs. The readout gives the paper's WikiText2 perplexity where it reports that setting.

The linear layers of OPT-175B hold 96 × 12 × 12,288² ≈ 174 billion weights. At 3 bits they take 61 GiB, the FP16 embeddings 1.2 GiB, and the cache of keys and values for 2,048 tokens another 9.0 GiB: 71 GiB, under 80. At 4 bits the weights alone take 82 GiB and the model needs two GPUs. The paper's own figures are about 63 GB and 9 GB, a single A100 at 3 bits, three for 8-bit LLM.int8() and five for FP16; Figure 6 reproduces those GPU counts.

Where the speedup comes from

Generating text at batch size 1 produces one token per forward pass, and each linear layer then multiplies its weight matrix by a single vector. Every weight is read from memory once and used for two floating-point operations, so the time per token is set by how fast the GPU can read the weights. For OPT-175B in FP16 that is 350 GB; at about 2 TB/s the reading alone takes at least 175 ms per token, and the paper measures 230 ms. At 3 bits the weights are about 65 GB, a lower bound near 33 ms.

The paper's CUDA kernel computes the product of a 3-bit matrix and an FP16 vector. It reads the packed 3-bit codes, converts each back to FP16 on the fly with the row's scale and zero point, and multiplies. The arithmetic is still FP16 and the activations are never quantized; the gain is entirely in bytes read. Table 6 reports average per-token latency for 128-token generations:

The A6000 gains more because its memory bandwidth, 768 GB/s, is lower, so FP16 generation on it is more bandwidth-limited. The model's layers are split across GPUs in sequence, and the paper measures communication at under 5% of runtime even with 8 GPUs, so nearly all of the speedup comes from the kernel. The 3.24× figure comes from an optimized kernel added for the camera-ready version; the README records that the earlier kernel gave 1.9×.

At large batch sizes the same weights are reused across many tokens and the work becomes limited by arithmetic, where reading fewer bytes does not help. For that case the paper proposes dequantizing a whole layer before an ordinary FP16 matrix multiplication, which keeps the memory saving: under 1.5 ms on an A100 for OPT-175B's fc2, against 76 ms for the multiplication itself at a batch of 16 × 1,024 tokens.

Limitations and later changes

The authors list the main limits themselves. The speedup comes only from moving less data: mainstream GPUs of the time had no instruction for multiplying FP16 by 4-bit operands, so the multiplications still run in FP16. Only weights are quantized. Activations stay in FP16, which the paper argues is not the bottleneck for generation; methods such as SmoothQuant address 8-bit activations separately. The evaluation is perplexity and a few zero-shot tasks, and the ethics statement notes that effects of compression on secondary measures such as bias were not studied.

The claim that order barely matters held for the OPT and BLOOM models tested, but not universally. The authors later added two options to their repository. --act-order quantizes columns in decreasing order of the diagonal of H\mathbf{H}, so inputs with the largest activations go first and the many columns after them absorb their error. --true-sequential quantizes the layers within a block one after another. Together they took LLaMA-7B at 4 bits from 7.15 to 6.09 WikiText2 perplexity (6.29 with RTN, 5.68 in FP16), and act-order alone took 3-bit OPT-66B from 14.16 to 9.95.

Provenance Verified against primary literatureHow we verify
Frantar et al. (ICLR 2023)arXiv 2210.17323. Source of Equations (1)-(5), Algorithm 1, Tables 1-8. Equations are reproduced with the paper's numbering; (3) carries the index fix in the flag below, and (4) is written with (H_F^-1)_{Q,:} where the paper prints (H_F^-1)_{:,Q}, which is the same matrix transposed (H is symmetric) and is the orientation that multiplies a row vector w_Q.
OBS (1993), OBQ (2022)Hassibi & Stork (1993) and Frantar, Singh & Alistarh (NeurIPS 2022, arXiv 2208.11580). Optimal Brain Surgeon: prune weight p with update -w_p / [H^-1]_pp times column p of H^-1. OBC/OBQ (their Eq. 7) replaces the target 0 by quant(w_p), giving the paper's Eq. (2), and introduces the Gaussian-elimination update of Eq. (3).
gptq.py, lines 53-143IST-DASLab/gptq, lines 53-58, 98-104 and 116-143. Hessian accumulated as (2/n) sum x x^T over calibration sequences; 1% dampening of the mean diagonal; torch.linalg.cholesky, cholesky_inverse, then cholesky(upper=True); per column err = (w - q) / d with d the diagonal of the upper factor, update W1[:, i:] -= err * Hinv1[i, i:]; block-end update W[:, i2:] -= Err1 @ Hinv[i1:i2, i2:]. Columns whose inputs are always zero get H_ii = 1 and weight 0 (lines 77-79).
quant.py, lines 6-76Lines 6-10 and 36-76. Asymmetric min-max grid per row with 0 forced inside the range: scale = (max - min)/(2^b - 1), zero = round(-min/scale), codes clamped to [0, 2^b - 1]. The ternary mode (line 8) outputs one of {group min, 0, group max}, so "(-1, 0, +1)" in the paper means three levels with two per-group scales.
opt.py, lines 77-115Block-sequential quantization: inputs to block i come from the already quantized blocks 0..i-1. Within a block, the six linear layers' Hessians are collected in one forward pass of the not-yet-quantized block, so the paper's "actual layer inputs in the already partially quantized" model holds at block granularity. The README's later --true-sequential flag makes it hold per layer.
IST-DASLab/gptq READMECamera-ready changes: optimized 3-bit kernel ("1.9x -> 3.25x generation speedup for OPT-175B"). Later: --act-order (columns in decreasing activation size) and --true-sequential, which move LLaMA-7B 4-bit from 7.15 to 6.09 WikiText2 perplexity and OPT-66B 3-bit from 14.16 to 9.95.
Numerical checkRun for this page. Equation (3), the Cholesky-row identity of Step 3, block-size invariance of Algorithm 1 (B = 1, 2, 8 give identical Q) and GPTQ = OBQ in a fixed column order were verified in float64 on a random 8-input layer. The figures run the same algorithm in the browser.
NVIDIA datasheetsA100 80GB and RTX A6000. Peak numbers used only for this page's estimates: A100 19.5 TFLOP/s fp32 and about 2.0 TB/s memory bandwidth; A6000 768 GB/s. Figure 4 and the per-token lower bounds are models, not measurements.
correctionEquation (3) in the paper ends with the subscript −p, an index that appears nowhere else in it; the weight being removed is q, so the reduced inverse is (…)_{−q}, matching the −Q of Equation (5). This page prints (3) with −q. Two smaller slips in Section 5: the text says 4-bit GPTQ reaches "≤ 0.25 lower perplexity than the full-precision versions", but Table 5 shows perplexity higher by at most 0.25 (lower perplexity would mean the quantized model is better); and the vision comparison is cited as "Table 2" but printed as Table 1. The 3-bit summary "losing only 0.3−0.6 points" covers 4 of the 6 Table 5 perplexities; OPT-175B on PTB (+0.67) and BLOOM-176B on PTB (+0.98) fall outside it, which the paper hedges with "on most tasks".

Questions you might still have

?

Does GPTQ quantize activations too?
No. Only weights are stored in 3 or 4 bits. Activations stay in FP16, and the paper's kernel turns each weight back into FP16 just before multiplying. Quantizing activations as well is a separate problem, which SmoothQuant (explained in its own article) handles for 8-bit weights and activations.

?

Is the Hessian here the Hessian of the language-model loss?
No. It is the Hessian of one layer's output reconstruction error, which is exactly 2XX^T for that layer's inputs X. Computing it needs only forward passes over calibration text: no labels, no gradients, no backward pass. The "approximate second-order" wording in the abstract refers to using this layer-wise proxy instead of the true loss.

?

If any column order works, why did act-order help later?
The paper's claim is that greedy order beats a fixed order only slightly on large layers, measured on OPT and BLOOM. Some models have a few input dimensions with much larger activations than the rest. Quantizing those columns first (descending diagonal of H) lets the many later columns absorb their error. The authors' README reports this fixed GPTQ's outliers: LLaMA-7B at 4 bits went from 7.15 to 6.09 WikiText2 perplexity, and OPT-66B at 3 bits from 14.16 to 9.95.

?

Can 128 sequences of web text calibrate a 175-billion-parameter model without overfitting?
They supply 262,144 token vectors per layer, and each layer's Hessian is at most 49,152 x 49,152, so the statistics are well determined. The weights stay on a fixed grid and only the rounding choices change, which limits how far the model can drift toward the calibration text. The evaluation sets (WikiText2, PTB, C4 validation, LAMBADA, ARC, PIQA) are never seen during quantization.

?

Why is GPTQ faster at generation when LLM.int8() is not?
Generating one token at batch size 1 reads every weight once and does two floating-point operations with it, so the time is set by memory bandwidth. GPTQ's 3-bit kernel reads about 5.3 times fewer bytes than FP16. LLM.int8() also reads fewer bytes, but splits each multiplication into an int8 part and an FP16 outlier part, and the paper reports it runs at the FP16 baseline's speed. At large batch sizes the work becomes compute-bound and GPTQ's kernel no longer helps; the paper then dequantizes the matrix first, which costs under 1.5 ms per layer on an A100.

?

What does a perplexity change from 8.34 to 8.37 mean?
Perplexity is e raised to the average negative log-probability the model assigns to each next token, so 8.34 means the model is, on average, as uncertain as a uniform choice among 8.34 tokens. A change of 0.03 is a 0.4% change. For scale, the gap between the full-precision OPT-66B (9.34) and OPT-175B (8.34) is 1.0.

Footnotes & further reading

  1. The paper: Frantar, Ashkboos, Hoefler & Alistarh, GPTQ: Accurate Post-Training Quantization for Generative Pre-trained Transformers (ICLR 2023). Official code: IST-DASLab/gptq, whose README also points to the community GPTQ-for-LLaMa repository.
  2. Optimal Brain Quantization: Frantar, Singh & Alistarh, Optimal Brain Compression: A Framework for Accurate Post-Training Quantization and Pruning (NeurIPS 2022). The pruning formulas it extends are Hassibi & Stork, Optimal Brain Surgeon and general network pruning (IEEE ICNN 1993).
  3. The models: Zhang et al., OPT: Open Pre-trained Transformer Language Models (2022), and the BigScience BLOOM model. The 8-bit baseline whose grid GPTQ shares is covered in the LLM.int8() explainer; the Transformer block being quantized is the one from Attention Is All You Need.
  4. The comparison methods: Nagel et al., Up or Down? Adaptive Rounding for Post-Training Quantization (AdaRound, ICML 2020); Li et al., BRECQ (ICLR 2021); Yao et al., ZeroQuant (2022).
  5. Error diffusion: Floyd & Steinberg, "An adaptive algorithm for spatial greyscale", Proceedings of the Society for Information Display 17(2), 1976. The memory-bound argument for generation is the same one behind FlashAttention, which the GPTQ paper cites as compatible with its kernels.