Knowledge Base · Learning paths
LLM Model Quantization Worldview (Part 1): From Fundamentals to Advanced Techniques
This article explores the fundamental differences between floating-point and fixed-point numbers, then systematically breaks down the core concepts of LLM quantization. Using GEMM as a unified mathematical framework, it provides an in-depth analysis of per-token, per-channel, and per-group quantization methods, while also explaining scale learning mechanisms in QAT and common weight-only low-bit quantization approaches.
Translated from Chinese by AI. Spotted an issue? Use the feedback button.
🔗 Original link: https://zhuanlan.zhihu.com/p/686232...
Author: Little A
Update Log
| Update Date | Update Content |
|---|---|
| 2024.03.10 | First edition completed |
Introduction
Hello everyone, I’m Little A. Long time no see. I’ve been really busy lately and ended up delaying updates for an entire quarter. This series will continue to be updated regularly — I promise I won’t abandon it. Flag set! 🚩
Enough with the chit-chat. Buckle up, here we go~
The previous article covered the foundational knowledge of distributed systems. Starting from this one, we’ll dive deep into deployment-related topics. This issue will explore all aspects of the LLM quantization process, focusing on the following seven key questions:
-
What is the fundamental difference between floating-point and fixed-point numbers?
-
How does QAT learn the scale factors?
-
What are the common methods for weight-only regular-bit quantization, and how is the second-order derivative method derived?
-
What are some unconventional, mind-blowing approaches for weight-only extremely low-bit quantization?
-
What are the different techniques for cross-dimension equalization in Activation + Weight quantization?
-
How effective is FP8 quantization in practice?
-
What methods exist for KV Cache quantization?
There’s quite a lot of content, so I’ve decided to split it into two parts. This upper part will cover the first three questions, and the lower part will address the remaining four.
Quantization: A Unified Perspective
Quantization generally refers to fixed-point quantization, where the position of the decimal point is fixed. This is in contrast to the more common floating-point representation.
To better understand the process of fixed-point quantization in LLMs, this section is divided into three parts:
- The first part introduces the basics of floating-point numbers.
- The second part explains the process of fixed-point quantization.
- The third part uses GEMM as the entry point to detail how per-token, per-channel, and per-group quantization work. It also attempts to build a unified mathematical model for them, helping readers better grasp the essence of fixed-point quantization.
Starting with Floating-Point Numbers
Floating-point numbers are the dominant force in modern computing. They were designed to solve the problem that computers cannot represent arbitrary real numbers. Their standard comes from IEEE 754. The diagram below shows FP32 as an example:
In a floating-point number, bits are arranged from high to low on the left to right. It generally consists of three parts: the sign bit (Sign), the exponent (Exponent), and the mantissa/fraction (Mantissa/Fraction).
Mathematically, it is expressed as:
f = (-1)^s · 2^(p-b) · (1 + d₁/2 + d₂/2² + ⋯ + dₘ/2ᵐ)
Where:
- s is the sign bit, e is the number of exponent bits
- 0 ≤ p < 2^e is the exponent value
- b is the exponent bias, typically b = 2^(e-1) - 1 (for example, 127 for FP32)
- d_i ∈ {0, 1} represents the i-th mantissa bit
There are a few additional rules when converting the original binary fraction into the mantissa:
- The leading 1 is hidden. Binary scientific notation defaults to the form
1.xxx, so the1.is fixed and usually omitted. - Lower bits are padded with zeros. The lower bits of the mantissa are filled with 0s.
Therefore, to convert 0100 1000 0000 0000 000 back to a binary fraction, we remove the padded trailing zeros and restore the hidden leading 1, resulting in 1.01001.
Introduction to INTx Quantization
From the format definition of floating-point numbers, it is clear that the decimal point in floating-point representation truly “floats.” If we look at the real number line, floating-point numbers divide the axis into segments of [2^x, 2^{x+1}]. The length of adjacent segments grows exponentially, but within each segment the values are uniformly spaced. The number of divisions within each segment is determined by the mantissa bits. As a result, floating-point numbers are very dense near zero and become increasingly sparse as they move away from zero.
In contrast, fixed-point quantization (INTx quantization) performs uniform sampling across the real number line, with values outside the representable range simply clipped, as shown below.
There are already many articles online explaining fixed-point quantization. Here we will express the process in a slightly more mathematical way.
For a scalar x, we define a scaling factor s and a zero-point z ∈ ℤ that satisfy:
\begin{aligned} x_q&=\text{quant}(x)=\text{clamp}(\text{round}(\frac{x}{s}), \text{min_value}, \text{max_value})-z \ x'&=\text{dequant}(x_q)=(x_q+z)\cdot s \end{aligned}
Here, min_value and max_value are determined by the number of bits and whether the representation is signed. For an 8-bit signed integer (b=8):
\begin{align*} \left{ \begin{aligned} \text{min_value}&=-2^{b-1}=-128 \ \text{max_value}&=2^{b-1}-1=127 \end{aligned} \right.\tag{1} \end{align*}
Commonly:
- When the zero-point z = 0, it becomes linear symmetric quantization.
- The scalar x is typically extended to a multi-dimensional tensor X, where all elements share the same scaling factor s.
A Unified Perspective on GEMM Quantization
From the earlier introduction to floating-point and fixed-point numbers, we can see that:
- In floating-point, each number has its own independent decimal point (exponent bits e).
- In fixed-point, a group of numbers shares a single decimal point (scaling factor s).
A natural idea follows: if we want to improve the precision of fixed-point quantization, can we use more scaling factors? The answer is yes. This is the core idea behind the many quantization methods emerging today, as illustrated below:
For the input matrix X of shape (BL, Ad):
- Per-token: Each row (token) has its own independent quantization scale.
- Per-channel: Each column (channel) has its own independent quantization scale.
For the weight matrix W of shape (Ad, Ad):
- Per-channel: Each output channel (column) has its own independent quantization scale.
- Per-group: Every g consecutive elements in a column form a group and share an independent quantization scale.
Below we provide a unified mathematical formulation, considering a relatively complex case:
- Matrix X ∈ ℝ^{M×K} is quantized with per-token and per-channel schemes.
- Matrix W ∈ ℝ^{K×N} is quantized with a per-channel scheme.
For the GEMM operation, we have:
Where:
From this unified mathematical expression, we can see that:
In summary, besides determining the scaling factor s, fixed-point quantization also requires deciding how many scaling factors are used to represent the tensor. The degree of freedom is therefore an important factor that must be carefully considered in the quantization process.
QAT Basic Introduction
QAT (Quantization Aware Training) refers to the process of fine-tuning the quantization scale factor ( s ) during training. This involves backpropagating gradients with respect to ( s ). Below, we derive it mathematically, reviewing the previous quantization and dequantization process (zero-point ignored):
\begin{aligned} x_q&=\text{quant}(x)=\text{clip}(\lfloor\frac{x}{s}\rceil, -2^{b-1}, 2^{b-1}-1) \ x'&=\text{dequant}(x_q)=x_q\cdot s \end{aligned}
Then we have:
\begin{aligned} \frac{\partial x'}{\partial s}=x_q+\frac{\partial x_q}{\partial s} \cdot s=\left{ \begin{aligned} x_q+\frac{\lfloor x/s \rceil}{\partial s}\cdot s, \quad -2^{b-1}\leq \lfloor x/s \rceil \leq 2^{b-1}-1 \ x_q, \quad \lfloor x/s \rceil < -2^{b-1} \text{or} \lfloor x/s \rceil > 2^{b-1}-1 \end{aligned} \right. \end{aligned}
After further expansion and simplification, it becomes:
\begin{aligned} \frac{\partial x'}{\partial s}=\left{ \begin{aligned} &\lfloor\frac{x}{s}\rceil-\frac{x}{s}, \quad -2^{b-1}\leq \lfloor x/s \rceil \leq 2^{b-1}-1 \ &-2^{b-1}, \quad \lfloor x/s \rceil < -2^{b-1} \ &2^{b-1}-1, \quad \lfloor x/s \rceil > 2^{b-1}-1 \end{aligned} \right. \end{aligned}
The visualization is shown in the left figure below, where ( L=2^{b-1} ). It can be seen that the gradient has a sawtooth shape.
The method above was first proposed in the LSQ (Learned Step Size Quantization) paper. To address the potential instability in learning ( s ), the paper introduced a separate learning rate scale: all activations share one scale, and all weights share another.
With the gradient formula in place, QAT training can proceed following the standard training pipeline.
Weight-Only Conventional Bit Quantization
The most prominent characteristic of LLM models is their enormous number of parameters. The prerequisite for serving them in production is the ability to load them into GPU memory. Therefore, model size compression becomes the top priority issue to solve. A series of methods have been developed to study how to compress the storage space of weight parameters, so that after loading into VRAM, they can be restored on-the-fly back to high-precision FP16 for computation.
Below we introduce the current mainstream second-order derivative approaches in weight-only quantization. These primarily include the classic OBS/OBQ/GPTQ family, the equalization-enhanced AWQ method, and the OWQ method.
OBS
Optimal Brain Surgeon (OBS) is a classic paper from 1992 that mathematically derives how to perform model pruning. In this section, we revisit the derivation of OBS with the goal of model quantization.
It is easy to see that the loss function (E) of a neural network is a function of the network weights (\mathbf{w}) (where (\mathbf{w}) is the column vector obtained by flattening all network parameters). When the network converges to (\mathbf{w}_0), (E) reaches a local minimum. The quantization process can be viewed as introducing a perturbation (\Delta_w) around (\mathbf{w}_0), i.e., the quantized value is (\mathbf{w}_q = \mathbf{w}_0 + \Delta_w).
Consider performing a second-order Taylor expansion around (\mathbf{w}_0):
$$ E(\mathbf{w}_q)=E(\mathbf{w}0)+\frac{\partial E}{\partial \mathbf{w}}\bigg|{\mathbf{w}=\mathbf{w}_0}(\mathbf{w}_q-\mathbf{w}_0)+\frac{1}{2}(\mathbf{w}_q-\mathbf{w}_0)^TH(\mathbf{w}_q-\mathbf{w}_0)+o(|\mathbf{w}_q-\mathbf{w}_0|^2) $$
It is straightforward to see that (\frac{\partial E}{\partial \mathbf{w}}\big|_{\mathbf{w}=\mathbf{w}_0}=0). Ignoring higher-order infinitesimal terms, the expression simplifies to:
$$ E(\mathbf{w}_q)=E(\mathbf{w}_0)+\frac{1}{2}(\mathbf{w}_q-\mathbf{w}_0)^TH(\mathbf{w}_q-\mathbf{w}_0)=E(\mathbf{w}_0)+\frac{1}{2}\Delta_w^TH\Delta_w $$
Therefore,
$$ \Delta_E = E(\mathbf{w}_q)-E(\mathbf{w}_0)=\frac{1}{2}\Delta_w^TH\Delta_w $$
Here, (\Delta_E) represents the quantization error of the loss function, and (\Delta_w) is the change in (\mathbf{w}) after quantization, i.e., (\Delta_w = \mathbf{w}_q - \mathbf{w}_0).
Conventional quantization methods convert the entire (\mathbf{w}_0) to (\mathbf{w}_q) in one go. However, if we consider transforming elements one by one, we can assume that the (k)-th element is currently selected for quantization. The problem then becomes: after quantizing the (k)-th element, how should the remaining elements be adjusted to minimize the quantization error (\Delta_E) of the loss function?
Mathematically, quantizing the (k)-th element can be described as:
$$ \mathbf{e}_k^T\Delta_w=\text{quant}(w_k)-w_k $$
Using the method of Lagrange multipliers, we can formulate the following unconstrained optimization problem:
$$ \min_{\Delta_w,\lambda} \quad \frac{1}{2}\Delta_w^TH\Delta_w + \lambda \cdot[\mathbf{e}_k^T\Delta_w-(\text{quant}(w_k)-w_k)] $$
Taking the derivatives with respect to (\Delta_w) and (\lambda) respectively, we obtain the following system of equations:
$$ \begin{aligned} \left{ \begin{align*} \frac{1}{2}(H+H^T)\Delta_w + \lambda \mathbf{e}_k &= 0 \tag{2} \ \mathbf{e}_k^T\Delta_w-(\text{quant}(w_k)-w_k) &= 0 \tag{3} \end{align*} \right. \end{aligned} $$
Since (H) is a symmetric matrix, (H = H^T), therefore
\begin{aligned} \left{ \begin{align*} H\Delta_w + \lambda \mathbf{e}_k=0 \tag{4}\quad\ \mathbf{e}_k^T\Delta_w-(\text{quant}(w_k)-w_k)=0\tag{5}\quad \end{align*} \right. \end{aligned}
After observation, we can first obtain from equation (4):
\begin{align*} \Delta_w=-\lambda H^{-1}\mathbf{e}_k \tag{6} \end{align*}
Substitute (6) into (5) and solve for $\lambda$:
\begin{align*} \lambda=-\frac{\text{quant}(w_k)-w_k}{\mathbf{e}_k^TH^{-1}\mathbf{e}k}=-\frac{\text{quant}(w_k)-w_k}{(H^{-1}){kk}}\tag{7} \end{align*}
Then substitute (7) back into (6) to solve for $\Delta_w$:
\begin{aligned} \Delta_w&=\frac{\text{quant}(w_k)-w_k}{(H^{-1}){kk}} H^{-1}\mathbf{e}k\ &=\frac{\text{quant}(w_k)-w_k}{(H^{-1}){kk}} (H^{-1}){:,k} \end{aligned} \tag{8}
The quantization error of the loss function at this point is
\begin{aligned} \Delta_E&=\frac{1}{2}[\frac{\text{quant}(w_k)-w_k}{(H^{-1}){kk}} (H^{-1}){k,:}]H[\frac{\text{quant}(w_k)-w_k}{(H^{-1}){kk}} (H^{-1}){:,k}] \ &=\frac{1}{2}[\frac{\text{quant}(w_k)-w_k}{(H^{-1}){kk}}]^2(H^{-1}){k,:}H(H^{-1}){:,k} \ &=\frac{(\text{quant}(w_k)-w_k)^2}{2(H^{-1}){kk}} \end{aligned} \tag{9}
If the dimension of $\mathbf{w}_0$ is $d$, we first need to compute $H^{-1}$ with $O(d^3)$ complexity, then spend $O(d)$ time traversing all elements to find the $w_k$ that minimizes $\Delta_E$. This process is repeated until all $d$ elements are quantized. The overall complexity is
O((d^3+d)\cdot d)=O(d^4)
This is clearly impractical for LLMs, which can easily have billions of parameters. Therefore, accelerated approximation algorithms are urgently needed.
OBQ
OBQ (Optimal Brain Quantization) addresses the slow computation problem of the original OBS through algorithmic approximation and acceleration:
- It replaces the task loss with layer-wise reconstruction L2 error, which significantly reduces the scale of the Hessian matrix $H$.
- It provides a recursive method for computing $H^{-1}$, reducing the complexity to $O(d^2)$, where $d=d_\text{row}\cdot d_\text{col}$.
- When searching for which $w_k$ to select, it uses parallel computation followed by a reduce operation on the loss to select the result.
Optimization 1: Reconstruction L2 Error
The loss function of the original OBS is $E(\mathbf{w}_0)$, also known as task loss. Its specific form varies greatly depending on the task, making the computation of $H$ extremely difficult or even impossible. A common solution is to switch to per-layer reconstruction error quantization: quantize one layer at a time. The reconstruction error for each layer is as follows:
$$ E(W)=||WX-\hat{W}X||_2^2 $$
Here:
- $W$ has dimensions $d_\text{row} \times d_\text{col}$ and is in two-dimensional matrix form (unlike the vector form $\mathbf{w}_0$ used in the earlier OBS derivation), but the underlying principle is the same.
- To stay consistent with the original paper and code, the notation $Y=WX$ is used, so the cross-dimension becomes the columns of $W$ and the rows of $X$.
Note that because the loss function is now in the form of the Frobenius norm of the reconstruction error, the summation over all elements can be decomposed into a sum over all rows:
$$ E(W)=\sum_{i=1}^{d_\text{row}}||W_{i,:}X-\hat{W}_{i,:}X||_2^2 $$
It is therefore easy to see that:
-
The Hessian matrix $H$ becomes block-diagonal, with non-zero elements concentrated near the diagonal blocks and all other elements being zero.
-
Each non-zero block has a size of ( d_\text{col} \times d_\text{col} ), and there are ( d_\text{row} ) such blocks in total.
- The ( i )-th non-zero block can be obtained by solving ( H_i = 2XX^T ), and its size is ( d_\text{col} \times d_\text{col} ).
Reviewing the update formula for ( \Delta_w ) in OBS, we find that:
- Selecting the ( k )-th weight ( w_k ) only affects other elements in the same row of ( W ); elements across different rows remain unchanged after the ( \Delta_w ) update.
- Each non-zero block can perform weight selection independently, meaning the OBS algorithm can run independently on each row.
- The number of elements processed by the OBS algorithm per row is ( d_\text{col} ), so the complexity per row is ( O(d_\text{col}^4) ).
- The total complexity across all rows is ( O(d_\text{row} \cdot d_\text{col}^4) ).
- If the original task loss is used, the complexity becomes ( O(d_\text{row}^4 \cdot d_\text{col}^4) ).
Optimization 2: Recursive Computation of ( H^{-1} )
Although modifying the loss function reduces the overall complexity, the complexity of the OBS process within each row remains unchanged because ( H^{-1} ) still needs to be solved directly at each step. To further reduce complexity, a recursive approach can be used. The mathematical proof is omitted here; the formula is as follows:
[ (H_{-k})^{-1} = \left( H^{-1} - \frac{1}{[H^{-1}]{kk}} H{:,k}^{-1} H_{k,:}^{-1} \right)_{-k} ]
Here:
- The subscript ( H_{-k} ) means the matrix with the ( k )-th row and ( k )-th column removed, because the already quantized weights should no longer be updated.
- The input is the inverse of the Hessian matrix ( H^{-1} ), and the output is the inverse of the Hessian matrix with the ( k )-th row and column removed, ( H_{-k}^{-1} ).
- The computational complexity of inverting the Hessian matrix is reduced from ( O(d_\text{col}^3) ) to ( O(d_\text{col}^2) ), and the overall complexity is reduced from ( O(d_\text{row} \cdot d_\text{col}^4) ) to ( O(d_\text{row} \cdot d_\text{col}^3) ).
Let’s walk through the OBS procedure for each non-zero block again. Suppose pruning is performed for ( k ) steps (quantization is performed for ( d_\text{col} ) steps):
- Step 1: According to Equation (9), select the element index ( p ) from the candidate indices that minimizes the error function.
- Step 2: According to Equation (8), compute the new weight ( \mathbf{w} ).
- Step 3: Compute the inverse of the new Hessian matrix ( H^{-1} ) after removing index ( p ).
- Step 4: Remove ( p ) from the candidate indices.
Optimization 3: Inter-Row Parallelization
As previously analyzed, each row is actually independent, so the computations can be fully parallelized. Note that:
- Although the initial ( H_i = 2XX^T ) is the same for every non-zero block, as each block selects different weight indices, the ( H_i ) matrices gradually become different.
- Finally, the quantization results from all ( d_\text{row} ) rows are concatenated to obtain the final quantized result.
Although the OBQ method applies the above three optimizations based on OBS, it still quantizes each weight sequentially within every row following the OBS approach. This results in long processing times, making the PTQ process excessively slow for networks with more than 100 billion parameters.
GPTQ
GPTQ builds upon the OBQ method with further approximations and accelerations. Its main contributions are:
- Extremely fast computation: quantizing an OPT-175B model requires only 4 GPU hours.
- Can be extended to extremely low bit-widths, such as 2-bit or 3-value quantization.
The speedup is achieved through three approximation optimizations based on OBC:
- Arbitrary Order Insight: The order of index selection is no longer chosen to minimize the quantization error at each step, but is instead manually and arbitrarily specified. This allows all rows to use the exact same index selection order.
- Lazy Batch-Updates: To create more GPU-friendly workloads, updates can be accumulated in batches and applied lazily. The total amount of computation remains the same, but execution is significantly faster.
- Cholesky Reformulation: Performing a Cholesky decomposition on ( H^{-1} ) greatly simplifies many calculations (see the derivation in the following sections).
Optimization 1: Completely Consistent Index Selection Across All Rows
Recalling the earlier discussion on OBC, we know that while all non-zero blocks start with identical ( H_i ), subsequent differences in per-row index selection cause the ( H_i ) matrices to diverge. To reduce the number of ( H^{-1} ) computations, one straightforward approach is to fix the index selection order to be identical across all rows. This way:
-
Each recursive update of ( H^{-1} ) only needs to be computed once and can then be shared across all rows.
-
The algorithmic complexity per step drops from O(d_\text{row} \cdot d_\text{col}^2) to O(d_\text{col}^2).
-
The overall algorithmic complexity is reduced from O(d_\text{row}\cdot d_\text{col}^3) to O(d_\text{col}^3).
Optimization 2: Block-wise Updates
Since the OBS algorithm iterates for a total of d_\text{col} steps and the computation per step is very small, this is not GPU-friendly. A common acceleration technique is to accumulate updates into batches. Specifically:
- Use the natural index order from 0 to d_\text{col}-1.
- Set the batch size to B=128.
In the OBC algorithm, Step 2 and Step 3 theoretically require an update at every step. However, because we follow the natural ordering, the current step k will never affect results before k; it only affects results after k. Therefore, a lazy update strategy can be used:
- The algorithm has reached the k-th step (corresponding to the current white column).
- All related weights W before k can be ignored, as they have already been quantized and are now fixed.
- For subsequent weights W within the current batch B, they must be updated at every step (the part after the white column inside the black box below).
- For subsequent weights W beyond the current batch B, they can be updated together only when the batch reaches its final step; there is no need to update them in the current step.
This approach does not change the asymptotic computational complexity, but it is much more GPU-kernel friendly and therefore runs significantly faster.
Optimization 3: Cholesky Decomposition of H^{-1}
When the parameter scale becomes large, H is often not positive definite, making the numerical inversion process unstable. A common workaround is to add a small noise term \lambda to the diagonal, where \lambda is typically set to 1% of the mean of the eigenvalues. The final algorithm presented in the paper is as follows:
It is easy to see that the biggest change is the complete disappearance of the H^{-1} update, and H^{-1} has been replaced by the upper triangular matrix L^T from the Cholesky decomposition. The original paper explains this step only briefly, and most Zhihu articles also fail to clarify the reasoning. So author A tried to start from the two most important formulas in Step 2 and Step 3, replacing H^{-1} with L L^T, and finally figured out what was going on.
First, recall that Cholesky decomposition states that any positive definite matrix A can be expressed as A = L L^T, where L is a lower triangular matrix.
The above derivation yields a compact expression that depends only on the 0-th column of L.
We then apply a similar approach to rewrite the recursive formula for H^{-1}:
OWQ
OWQ draws heavily on LLM.int8() (which will be introduced later in the Activation + Weight Quantization section). It observes that certain channels across the weight dimensions are particularly sensitive and are best stored in fp16. However, unlike LLM.int8() which uses outlier feature statistics, OWQ selects these sensitive channels using the Hessian matrix.
Similar to the GPTQ method, for the process Y = WX, if we use a per-layer reconstruction loss, we can see that each row of W is completely independent. The Hessian between different rows is zero, and the Hessian for each row is identical:
H^{(i)}=2XX^T
where H^{(i)} \in \mathbb{R}^{C_\text{in} \times C_\text{in}}, X \in \mathbb{R}^{C_\text{in} \times N_\text{Samples}}, and C_\text{in} is the feature length of W in the cross-dimension.
The error function before and after quantization can then be written as
\begin{aligned} \Delta_E&=\sum_{i=1}^{\text{C}\text{out}} \Delta W{i,:} H^{(i)} \Delta (W_{i:,})^T \end{aligned}
We can further expand the quadratic term in the middle and ignore the off-diagonal elements of H^{(i)}, i.e., when j \neq k, H^{(i)}_{j,k}=0, as shown below.
\begin{aligned} \Delta_E&=\sum_{i=1}^{\text{C}\text{out}} \Delta W{i,:} H^{(i)} \Delta (W_{i:,})^T \ &=\sum_{i=1}^{\text{C}\text{out}}[\sum{k=1}^{\text{C}\text{in}}(\sum{j=1}^{\text{C}{\text{in}}}\Delta W{i,j} H^{(i)}{j,k}) \Delta W{i,k}] \ &=\sum_{i=1}^{\text{C}\text{out}}(\sum{j=1}^{\text{C}{\text{in}}}\Delta W{i,j} H^{(i)}{j,j} \Delta W{i,j}) \ &=\sum_{j=1}^{\text{C}\text{in}}(\sum{i=1}^{\text{C}{\text{out}}}\Delta W{i,j}^2 \lambda_j) \ &=\sum_{j=1}^{\text{C}\text{in}}\lambda_j||\Delta W{:,j}||^2_2 \end{aligned}
where (\Delta W \in \mathbb{R}^{C_\text{out} \times C_\text{in}}) and (\Delta W_{i,:} \in \mathbb{R}^{1 \times C_\text{in}}).
It can be seen that the quantization error is equivalent to weighting the per-column quantization error of (W) by the diagonal elements of the Hessian matrix. Therefore, OWQ computes a sensitivity metric for each channel along the cross dimension:
$$ \text{sensitivity}j=\lambda_j||\Delta W{:,j}||^2_2 $$
The top-(k) columns with the highest sensitivity are regarded as weak columns and stored in FP16, while the remaining parts are stored in low-bit precision (e.g., 3-bit). Concretely:
- Convert the original (W) into a full low-bit matrix, with weak columns filled with zeros.
- Separately store the FP16 weak columns and append the column indices after the last element.
The overall workflow of OWQ is shown in the figure below.
Note that (\Delta W) can be obtained using linear quantization with zero-point. The weight can be quantized using either per-channel or per-group scaling.
OWQ is consistently positioned as a counterpart to the GPTQ method.
AWQ
AWQ draws heavily on SmoothQuant (which will be introduced later in the Activation+Weight quantization section). It first performs cross-dimension equalization, followed by weight-only quantization.
- The equalization strategy uses the reconstruction error of a single layer as the objective and performs a heuristic search over the scaling vector (s).
- The vector (s) is derived from the statistics of (X) and (W), and is ultimately reduced to a search over a single parameter (\alpha).
AWQ first explores mixed-precision along the cross dimension (in the form (Y = XW)), as shown below:
- The first column (FP16) represents the baseline where both activations and weights are in FP16, which can be considered essentially equivalent to FP32.
- The second column (RTN — Round to Nearest) is the common group-wise quantization: every 128 elements in column-major order share one quantization scale, with 3-bit integer quantization.
- The third column selects several columns of (X) with large norms and stores them in FP16, while the rest remain INT3 (the corresponding rows of (W) are also stored in FP16, and the rest in INT3).
- The fourth column selects several rows of (W) with large norms and stores them in FP16, while the rest remain INT3 (the corresponding columns of (X) are also stored in FP16, and the rest in INT3).
- The fifth column selects channels randomly along the cross dimension.
It can be seen that starting from columns of (X) with larger norms yields better PPL results (the smaller the better).
Although the third-column scheme achieves high accuracy, it is not friendly to low-level kernel implementations because it requires mixed-precision GEMM. The key insight that can be distilled here is that handling outliers in (X) is more effective than handling outliers in (W).
An equivalent idea is therefore to divide the columns of (X) with large norms by a scaling factor (s) to suppress the outlier values, while multiplying the corresponding rows of (W) by the same factor (s) according to the matrix multiplication rule, so that the final GEMM result remains unchanged. This is illustrated in Figure (c) below.
It is easy to see that the scaling factor (s) here should be greater than 1. The authors first set (s) heuristically and found that it indeed improves performance, as shown in the third column (Heuristic scaling).
It is not difficult to see that this is essentially the same idea as SmoothQuant, with the main differences being:
- SmoothQuant directly uses a manually tuned scaling coefficient s.
- AWQ uses reconstruction error as the loss function and performs a heuristic search over the coefficient s.
Below we rewrite the reconstruction error formula using mathematical notation:
$$ S^*=\arg\min_{S}\mathcal{L}(S),\quad\mathcal{L}(S)=||(XS^{-1})Q(SW)-XW|| $$
Here S is a $K \times K$ square matrix, which is the diagonalized expansion of the vector $\mathbf{s}$, i.e., $\mathbf{S}=\text{diag}(\mathbf{s})$.
Regarding the selection of the vector $\mathbf{s}$, AWQ computes it from both the perspectives of X and W. The formula is as follows:
$$ \mathbf{s}=f(\mathbf{s}_X,\mathbf{s}_W)=\frac{{\mathbf{s}_X}^\alpha}{{\mathbf{s}_W}^\beta} $$
where
From the source code, there are some implementation details that are not mentioned in the paper:
Note that the scaling coefficients after equalizing X can be absorbed into the preceding LayerNorm. This way, X can still use per-tensor quantization during inference.
Summary
In this section, we introduced several common methods used by Weight-only quantization when dealing with bit widths greater than 4-bit. Although some of these methods can also quantize down to 2-bit, the accuracy loss becomes very large, so they are generally considered suitable for quantizing above 4-bit.
The following table summarizes and compares the methods introduced in this section:
| Method | Processing of X | Quantization of W | Uses Hessian Matrix? | Main Contribution |
|---|---|---|---|---|
| OBS | None | per-tensor | Yes | Mathematically derives the process of minimizing quantization error using second-order derivatives |
| OBQ | None | per-channel | Yes | Replaces task loss with layer-wise reconstruction error |
| GPTQ | None | per-group | Yes | Fixes the search order |
| OWQ | None | per-group | Yes | Uses H to identify weak columns across dimensions |
| AWQ | Equalization transferred to LayerNorm | per-group | No | Cross-dimension equalization + minimization of layer-wise reconstruction error |
Final Remarks
Fixed-point quantization methods come in all shapes and forms, but they can ultimately be described by the following formula and diagram.
Weight-only fixed-point quantization mainly focuses on per-channel/per-group quantization of W, while its handling of X is limited to cross-dimension equalization. In the next article, we will introduce Activation+Weight quantization, at which point per-token quantization of X will also be taken into consideration.
PS: Since the author (Aaron) has not personally implemented all the details mentioned above, most of the content was summarized in a bottom-up manner by studying code and carefully reading excellent papers. Essentially, this is just knowledge aggregation and rephrasing. It remains “talking on paper.” Therefore, I sincerely welcome experts with real hands-on experience to critique and correct it. Only through the collision of ideas can sparks fly, and truth becomes clearer through debate.
If you want to learn about Transformer algorithms in NLP, multimodal, and AIGC applications, knowledge of LLM distributed training, as well as LLM quantization, inference acceleration, and deployment/servitization, feel free to follow me — aaronxic~
References
Quantization Deep Dive: FP8 and LLM-FP4
FP8 Quantization – Principles, Implementation, and Error Analysis
IEEE 754 Specification: Part 4 – Subnormal Numbers, ±Infinity, and NaN