Knowledge Base · Learning paths
The World of LLM Model Quantization (Part 2): Weight-Only Ultra-Low Bit Techniques
This article dives deep into weight-only ultra-low-bit quantization for LLMs. It explores SpQR’s divide-and-conquer approach that isolates sensitive weights and compresses them to 3-bit, SqueezeLLM’s weighted K-means non-uniform quantization with outlier protection, and AQLM’s additive quantization with codebooks that achieves state-of-the-art accuracy at 2-bit.
Translated from Chinese by AI. Spotted an issue? Use the feedback button.
🔗 Original link: https://zhuanlan.zhihu.com/p/691415...
⏰ Published: 2024-06-06 12:51:29 (UTC+8)
Due to formatting difficulties with equations, it is recommended to visit the Zhihu link above for reference.
Update History
| Update Date | Update Content |
|---|---|
| 2024.04.09 | First version of the official edition completed |
Introduction
Hello everyone, I’m Xiao A. In the previous article LLM Model Quantization Worldview (Part 1), we covered the first three of the seven key questions surrounding LLM quantization. In this article, we will discuss the remaining four questions:
-
Question 1: What is the fundamental difference between floating-point and fixed-point numbers?
-
Question 2: How does QAT learn the scale?
-
Question 3: What are the common methods for weight-only conventional bit quantization, and how is the second-order derivative method derived?
-
Question 4: What are some mind-blowing approaches for weight-only ultra-low-bit quantization?
-
Question 5: What are the different techniques for cross-dimension equalization in Activation+Weight quantization?
-
Question 6: How effective is FP8 quantization in practice?
-
Question 7: What methods exist for KV Cache quantization?
Weight-Only Extreme Low-Bit Quantization
Common methods such as OBS, OBQ, GPTQ, OWQ, and AWQ are typically used for quantization at 4 bits or higher. When the bit width drops further below 4 bits, the quantization problem must be re-examined, returning to the original goal of compression for storage. This section introduces three methods:
- SpQR uses a divide-and-conquer approach to isolate sensitive weights, then applies a two-level compression scheme to the non-sensitive weights, converting them into 3-bit storage.
- SqueezeLLM first separates extreme outlier values, then applies a weighted k-means clustering method for non-uniform quantization on the remaining weights.
- AQLM draws inspiration from approximate nearest neighbor search, reformulating the quantization process using codebooks and codewords.
SpQR
SpQR primarily adopts a divide-and-conquer strategy, divided into two steps:
- Step 1: Identify sensitive weights and store them in high-precision FP16.
- Step 2: Apply two-level compression to the remaining weights, converting them into 3-bit storage.
Identifying Sensitive Weights
The selection of sensitive weights is based on the conclusion from OBS:
$$ \Delta_E=\frac{(\text{quant}(w_k)-w_k)^2}{2(H^{-1})_{kk}} $$
Since layer-wise reconstruction error is used, the Hessian matrix $H$ is relatively easy to obtain. Weights are sorted by error from largest to smallest, and the top 1% are considered sensitive and stored in FP16.
Two-Level Compression
For the remaining non-sensitive weights, SpQR applies group-wise quantization to the input activations, where $\beta_1 \in [8,16]$, which is much smaller than the commonly used 128. This makes the storage overhead of scales and zeros non-negligible. Therefore, the authors further quantize the scales and zeros themselves, forming a two-level compression scheme. Specifically, every $\beta_2=16$ consecutive first-level scales and zeros are represented with 3 bits; they share second-level scales and zeros stored in half-precision (FP16).
Results on Llama are shown below:
SqueezeLLM
SqueezeLLM aims to solve the memory-wall access problem. It considers weight loading as the performance bottleneck, making it critical to compress weights to extremely low bit widths. The specific strategies are:
- Use weighted k-means clustering for non-uniform quantization.
- Apply a divide-and-conquer method to identify outliers and store them in high precision.
The authors first tested the end-to-end performance of different bit-width weights, with the computation kept in FP16. As shown below, execution speed improves approximately linearly as bit width decreases.
When the bit width drops below 4 bits, two important insights emerge:
- Quantization slots are extremely valuable; uniform quantization is not the optimal choice.
- Outliers are inevitable and must be separated and stored in high precision.
Non-Uniform Quantization
At 3 bits, there are only 8 quantization slots, so the quantization values must be chosen very carefully. A common approach is to use k-means clustering. The key lies in the definition of the loss function. The authors use the actual task loss instead of a simplified per-layer reconstruction error. From the earlier OBS discussion, we know that the task loss after quantization can be approximated via second-order Taylor expansion as:
$$ \Delta_E = E(\mathbf{w}_q) - E(\mathbf{w}_0) = \frac{1}{2} \Delta_w^T H \Delta_w $$
Solving for the Hessian $H$ is too expensive. The authors instead use the Fisher Information Matrix (FIM) as a replacement. Specifically, they compute the covariance of first-order gradients. The related mathematical proof can be found here.
$$ H \approx F = \frac{1}{|D|} \sum_{d \in D} g_d g_d^T $$
where $g_d$ is the first-order gradient, and the mean is assumed to be zero.
The authors then make a further assumption by setting all off-diagonal elements of $F$ to zero, resulting in $\text{diag}(F)$. The final expression can then be simplified to:
$$ \begin{aligned} L(W_Q) &\approx (W - W_Q)^T \text{diag}(F)(W - W_Q) \ &= \sum_{i=1}^N F_{ii} (w_i - Q(w_i)) \end{aligned} $$
Therefore, for each $Q(w_i)$, the k-means algorithm can be used to minimize the above $L(W_Q)$ loss, ultimately yielding $k$ discrete one-dimensional floating-point values. For 3-bit quantization, $k=8$.
A visualization of the k-means results is shown below:
- Green represents the distribution of the original weights.
- Red represents the top 20 sensitive weights identified using the FIM matrix.
- Purple shows the cluster centers after k-means convergence. Compared to uniform quantization points (green), these centers are positioned much closer to the sensitive weights.
Extreme Value Detection
The author analyzed the weight distributions of the MHA output projection matrix and the FFN contraction matrix, as shown below. They found that:
- 99.9% of the weights are squeezed into the bottom 10% of the maximum range.
- The remaining 0.1% of the weights lie in the 10%–90% range of the maximum interval and are considered outliers.
The author adopted a straightforward divide-and-conquer approach by defining two thresholds, ( T_{\text{min}} ) and ( T_{\text{max}} ), and splitting the weights into two groups:
$$ \left{\begin{aligned} W &= D + S \ WX &= WD + WS \ D &= W[T_{\text{min}} \leq w \leq T_{\text{max}}] \ S &= W[w < T_{\text{min}} \text{ or } w > T_{\text{max}}] \end{aligned}\right. $$
After decomposition, the sparse matrix ( S ) is stored in CSR (Compressed Sparse Row) format. During dequantization, the CUDA kernel must be specially customized—for example, using a 3/4-bit CUDA LUT-based kernel.
AQLM
AQLM is primarily based on a codebook-driven vector compression strategy. It can push the bit-width down to 2 bits while achieving state-of-the-art (SOTA) accuracy.
Core Modeling
The overall idea is straightforward and partially draws inspiration from approximate nearest neighbor search. It attempts to decompose a feature using Additive Quantization. Specifically, for the following GEMM operation:
$$ Y = WX, \quad W \in \mathbb{R}^{d_{\text{out}} \times d_{\text{in}}}, \quad X \in \mathbb{R}^{d_{\text{in}} \times n} $$
-
The weight matrix is quantized in a group-wise manner, processed in row-major order. Every ( g ) elements form a group, treated as a ( g )-dimensional feature vector. Thus, the original weight can be decomposed into ( d_{\text{out}} \times (d_{\text{in}}/g) ) vectors ( \mathbf{w}_i ) of length ( g ).
-
Each vector ( \mathbf{w}_i ) is modeled as a sum of ( M ) codebook entries, each of size ( 2^B ):
$$ \mathbf{w}i = \sum{m=1}^M C_m \mathbf{b}_m $$
where
- ( C_m \in \mathbb{R}^{g \times 2^B} ) is the ( m )-th codebook; each column is a codebook vector.
- ( \mathbf{b}_m ) is a one-hot column vector of length ( 2^B ), indicating which vector from codebook ( C_m ) is selected.
- The summation ( \sum_{m=1}^M ) adds up the ( M ) selected codebook vectors.
The process is illustrated as follows:
- The green blocks on the left represent the weight matrix ( W ) after group partitioning; the blue box highlights one vector ( \mathbf{w}_i ).
- The middle section shows the multiple ( \sum_{m=1}^M ) summation steps.
- The green boxes inside the dashed frame represent the ( M ) codebooks.
- The blue boxes on the far right are the binary one-hot vectors (converted to decimal indices for illustration).
From this, we can calculate the memory footprint (assuming all floating-point values are stored in half precision):
- Codebook storage: Independent of input size, ( g \cdot 2^B \cdot M \cdot 16 ) bits.
- Codeword storage: Dependent on input size, ( d_{\text{out}} \cdot (d_{\text{in}} / g) \cdot B \cdot M ) bits.
- Scale factors: Per-channel scaling coefficients for the weights, ( d_{\text{out}} \cdot 16 ) bits.
Therefore, we can compute the average number of bits occupied per weight.
\begin{aligned}\bar{b}=\frac{\text{size in bits}}{\text{number of parameters}}&=\frac{g \cdot 2^B \cdot M \cdot 16+d_\text{out} \cdot (d_\text{in} / g) \cdot B \cdot M+d_\text{out} \cdot 16}{d_\text{out} \cdot d_\text{in}} \&=\frac{g \cdot 2^B \cdot M \cdot 16}{d_\text{out} \cdot d_\text{in}} + \frac{B\cdot M}{g} + \frac{16}{d_\text{in}}\end{aligned}
When the weights of an LLM are extremely large, the first and third terms can be largely ignored, leaving the second term as the primary focus. The authors also use different hyperparameters for different bit-width settings:
- 2-bit: B=16, M=1, g=8 → $\bar{b} \approx 2$
- 3-bit: B=12, M=2, g=8 → $\bar{b} \approx 3$
- 4-bit: B=16, M=2, g=8 → $\bar{b} \approx 4$
Optimization Objective
Concatenating all $\mathbf{w}_i$ yields the final quantized weight $\hat{W}$:
$$ \left{\begin{aligned} \hat{W}&=\mathbf{w}i \oplus \cdots \oplus \mathbf{w}{d_\text{out}\cdot d_\text{in}/g}\ \mathbf{w}i&=\sum{m=1}^M C_m \mathbf{b}_m \end{aligned}\right. $$
The loss remains the layer-wise reconstruction error:
$$ \arg\min_{\hat{W}} |WX-\hat{W}X|_2^2 $$
Since the Frobenius norm is used, without loss of generality we can set $d_\text{out}=1$ and $g=d_\text{in}$. The loss then simplifies to:
$$ \begin{aligned} &|WX-\sum_{m=1}^M C_m b_m X|2^2\ =\quad& |WX|2^2-2\sum{m=1}^M \langle W,C_m b_m \rangle{XX^T}+\sum_{i=1}^M\sum_{j=1}^M \langle C_i b_i, C_j b_j \rangle_{XX^T} \end{aligned} $$
where the inner product is defined as $\langle A, B \rangle_{XX^T} \overset{\text{def}}{=} \langle AXX^T, B \rangle$.
Because both the codebooks $C_m$ and the codewords $\mathbf{b}_m$ need to be solved for, the entire training process is divided into three stages:
-
Stage 1: Learning the codewords $\mathbf{b}_m$. This is essentially an integer programming problem. The authors adopt a beam search strategy: at each step, they try all possible combinations of $k$ codebooks ($2^B \cdot k$ candidates in total) and keep the top $k$ combinations with the smallest loss.
-
Stage 2: Learning the codebooks $C_m$. Once the $\mathbf{b}_m$ are fixed, $C_m$ has a closed-form solution. However, matrix inversion is computationally expensive, so the authors use full-batch gradient descent instead.
-
Stage 3: Block-wise fine-tuning. Several consecutive layers within a block are jointly updated using the reconstruction error as the objective.
Under 2-bit quantization, AQLM significantly outperforms GPTQ.
Summary
For weight-only quantization below 4 bits:
- Both SpQR and SqueezeLLM first isolate outliers and store them in higher precision, then quantize the remaining weights.
- SpQR’s two-level quantization scheme is essentially designed to mitigate the excessive storage overhead of scales and zeros when the group size in group-wise quantization is too small.
- SqueezeLLM observes that directly applying k-means for non-uniform quantization performs poorly. It therefore uses a weighted k-means approach that biases cluster centers toward more sensitive weights.
- AQLM takes a completely different route: it treats quantization as a generic compression problem and reformulates it using the Additive Quantization technique from approximate nearest neighbor search.
Activation + Weight Quantization
The previous conventional-bit (≥4-bit) and ultra-low-bit (<4-bit) weight-only quantization methods essentially solve the problem of fitting the model into GPU memory. During GEMM computation, they still rely on high-precision FP16.
This section introduces methods that also quantize activations, enabling the use of INT8 GEMM Tensor Cores while keeping accuracy loss under control. The main techniques include the ZeroQuant/LLM.int8()/SmoothQuant/Outlier Suppression family and the RPTQ method.
- ZeroQuant applies online per-token quantization to activations (the origin of “Zero” in ZeroQuant). Weights remain group-wise quantized.
- LLM.int8() isolates sensitive channels in the activations and computes them in FP16, while using INT8 for the remaining channels.
- SmoothQuant focuses on cross-dimension balancing, migrating part of the activation quantization difficulty onto the weights.
- The Outlier Suppression series addresses the distribution differences across activation channels:
- v1 attributes the differences to the γ coefficients of the preceding LayerNorm. These coefficients are first migrated to the activations and then balanced into the weights.
- v2 additionally accounts for mean differences across channels, introducing a shift operation to align them.
- RPTQ also starts from activation channels. It uses clustering to reorder channel sequences and makes corresponding adjustments to the cross-dimension of the weights.
ZeroQuant
The term “Zero” here refers to zero-shot quantization of activations — that is, dynamically computing the scale factor at runtime. This requires rewriting the quantize and dequantize operators.
The authors first evaluated the accuracy of activations and weights under different bit widths, revealing that activations are significantly more sensitive than weights.
They then presented two analysis figures:
- Analysis of the activation range of
in_proj, collected per-token (left figure below). The value ranges vary dramatically, and the authors noted that traditional static per-token quantization cannot adequately handle the large per-sample variance in the inputs. - Analysis of the weight range of
out_proj, collected per-row (in the form of Y = WX, right figure below). The value ranges also differ significantly.
Based on these observations, the authors proposed two improvements:
- For activations, they introduced dynamic per-token quantization, i.e., computing quantization parameters on-the-fly for each sample. This requires modifying the kernel and performing non-trivial kernel fusion.
- For weights, they adopted per-group quantization and, at low bit widths, applied a lightweight form of QAT using floating-point distillation based on Kullback-Leibler divergence (KLD).
The KLD distillation is performed layer-by-layer from front to back. Only one layer is distilled at a time, and the reconstruction error is measured with MSE loss. As shown below, when distilling layer L, the preceding L−1 layers have already been quantized.
$$ \mathcal{L}{\text{LKD},k}=\text{MSE}(L_k \cdot L{k-1} \cdot L_{k-2} \cdot \ldots \cdot L_1(X) - \hat{L}k \cdot L{k-1} \cdot L_{k-2} \cdot \ldots \cdot L_1(X)) $$
Finally, the authors conducted several ablation studies:
- First row: per-tensor quantization on both weights and activations — the model fails completely.
- Second row: group-wise quantization on weights — non-trivial results are obtained.
- Third row: adding per-token quantization on activations improves performance by 14 points.
- Fourth row: applying LKD distillation on weights further improves results by 0.56 points.
LLM.int8()
The authors first tried per-token quantization on X and per-channel quantization on W (in the form Y = XW). They observed that as model size increases, an explosion of outliers occurs between 6B and 6.7B parameters, causing the quantization scheme to break down (see figure below).
The authors defined an outlier as any element whose absolute value exceeds a hyperparameter α = 6.0. Surprisingly, they found that:
-
Outliers only appear in the input activations of the MHA
in_projandout_projprojection matrices, as well as in the input to the first expansion matrix of the FFN. -
Although the 6.7B model has 150k such outlier values, their distribution is extremely regular and exists only within 6 specific cross-dimensional features ( h_i ).
-
When the proportion of layers or tokens affected by outlier values is plotted against network size (model scale), an emergence phenomenon appears, as shown in the left figure (a) below.
-
When network size is replaced with C4 Perplexity on the x-axis, the trend becomes monotonically increasing. This indicates that Perplexity better reveals the underlying cause of outlier emergence, as shown in the right figure (b).
The authors further analyzed the magnitude of outlier values and the number of outlier channels, and found that:
-
As Perplexity decreases, the magnitude of the extreme values exhibits an emergence phenomenon, as shown in the left figure (a).
-
As Perplexity decreases, the number of outlier channels increases only slowly, as shown in the right figure (b).
This naturally leads to the idea of computing these outlier channels in FP16 — that is, performing cross-dimensional channel separation, as illustrated below.
The approach is quite intuitive: extract the columns corresponding to outlier channels, continue to quantize the remaining parts using per-token quantization on ( X ) and per-channel quantization on ( W ), and finally add the two parts together. The mathematical expression is as follows:
[ C_{f16} \approx \sum_{h \in O} X_{f16}^h W_{f16}^h + S_{f16} \cdot \sum_{h \not\in O} X_{i8}^h W_{i8}^h ]
SmoothQuant
SmoothQuant first seeks to understand which dimension activation quantization in LLMs is more sensitive to. As shown in the figure below, experiments revealed that applying per-channel quantization to activations yields results very close to FP16 (in the form ( Y = XW )). This also validates the findings of LLM.int8(). However, applying per-channel quantization directly to ( X ) would prevent the use of INT8 GEMM kernels.
A natural idea is therefore to perform balancing (smoothing) along the cross-dimensional axis. Specifically, multiply each column of the activation by a different scale factor to flatten the activation distribution, and then apply per-tensor quantization, as shown below.
The key lies in how to determine the scale for each column. There are multiple ways to compute this. For example:
-
One can make the maximum value of every column in the activation the same, thereby transferring the quantization difficulty from activations to weights. That is, divide by
[ \mathbf{s}_j = \max(|\mathbf{X}_j|) ] -
Or make the maximum value of every column in the weight the same, transferring the quantization difficulty from weights to activations. That is, divide by
[ \mathbf{s}_j = \frac{1}{\max(|\mathbf{W}_j|)} ]
After experimentation, the authors settled on a balanced formulation:
[ \mathbf{s}_j = \frac{\max(|\mathbf{X}_j|)^\alpha}{\max(|\mathbf{W}_j|)^{1-\alpha}} ]
This effectively balances the corresponding channels of activations and weights using their respective maximum values. After scaling, the maximum value of activation channel ( j ) becomes:
[ \max(|\mathbf{X}_j|)^{1-\alpha} \cdot \max(|\mathbf{W}_j|)^\alpha ]
while the maximum value of weight channel ( j ) becomes:
[ \max(|\mathbf{X}_j|)^\alpha \cdot \max(|\mathbf{W}_j|)^{1-\alpha} ]
As ( \alpha ) varies, the authors observed the following accuracy trends:
-
When ( \alpha > 0.5 ) and continues to increase, the quantization difficulty of activations is transferred to the weights. In this case, if the weight uses more bits (e.g., W16A8), the accuracy curve remains stable.
-
When ( \alpha < 0.5 ) and continues to decrease, the quantization difficulty of weights is transferred to the activations. In this case, if the activation uses more bits (e.g., W8A16), the accuracy curve also remains stable.
For networks that have already undergone equalization, applying per-tensor quantization directly to weights and per-token (or per-tensor) quantization to activations yields the following results. The performance improves significantly, indirectly demonstrating the effectiveness of equalization.
Outlier Suppression
- The paper performs W8A8 quantization using an approach similar to SmoothQuant, both relying on equalization.
- The authors observe that the γ parameter in LayerNorm amplifies outliers across channels and propose absorbing it into the subsequent weight matrix.
- For searching the quantization scale of X itself, they sort the per-token maximum values and test them sequentially. In the final stage, they switch back to grid search.
Gamma Migration
The authors perform a detailed analysis of the feature dimensions in each column of X in the XW computation. They find that positions where X exhibits outliers often correspond to large γ values, leading to the hypothesis that γ exacerbates the magnitude differences within X.
A natural idea is to postpone γ. The original γ in LayerNorm is removed, and the LayerNorm expression becomes:
X'{t,j} = \frac{X{t,j}-\mu_t}{\sqrt{\sigma_t^2+\epsilon}}+\frac{\beta_j}{\gamma_j}
By moving γ downstream, it can be absorbed into the weight of the following Linear layer. Note that the shortcut branch requires special handling: when DeQuant is applied to convert back to FP32/FP16, the scaling coefficient must be restored.
The paper includes a comprehensive diagram that is particularly clear.
Token-Wise Clipping
After migrating γ, X itself still contains outliers. The Suppression paper collects the maximum value of each token, sorts them in descending order, and performs a sequential search over possible clipping thresholds. The search objective is a heuristic L2 error on the final layer’s output activations.
It is observed that the top few outliers are spaced very far apart, and removing them often has minimal impact on the final loss. Once the search approaches convergence, the method switches to a finer-grained grid search to obtain the final optimal scale s_best.
The experiments are primarily conducted on the encoder-only RoBERTa architecture and are extended to 6-bit quantization.
Limitations
- Asymmetric quantization is not considered; future work will incorporate shift operations.
- Equalization is applied indiscriminately to weights without considering the weight matrix’s capacity to absorb the transformation.
Outlier Suppression+
- The method aligns the distributions of different channels as much as possible by applying both shift and scale operations.
- The shift is computed as the per-channel median, while the scale is transformed into solving for a global clipping value t, which greatly reduces search complexity.
Expression Rewriting
This paper attempts to address the problem of excessively large distribution differences across channels during activation quantization, as illustrated below:
- Channel 8725 has a range of [-97, -58]
- In contrast, channel 6354 has a range of [5.7, 43]
A straightforward approach is to perform per-channel zero-point alignment followed by scaling—i.e., applying both shift and scale. Starting from the classic Linear layer, the expression is:
\begin{align*} Y=\text{Linear}(X)=XW+\mathbf{b} \tag{1} \end{align*}
where
- Y∈ℝ^{m×d}, X∈ℝ^{m×d}, W∈ℝ^{d×n}
- b∈ℝ^{1×d}
If we apply shift and scale to X, we obtain:
\begin{align*}X'=(X-\mathbf{z})\oslash\mathbf{s} \tag{2}\end{align*}
-
( X'\in\mathbb{R}^{m \times n} ), ( \mathbf{z}\in\mathbb{R}^{1\times n} ), ( \mathbf{s}\in\mathbb{R}^{1\times n} )
-
( \oslash ) denotes element-wise division (with automatic broadcasting)
Substituting ( X' ) for ( X ) into the Linear expression yields
\begin{align*} Y=(X'\odot s+z)W+b=X'(s^T\odot W)+(zW+b) \tag{3} \end{align*}
where ( \odot ) denotes element-wise multiplication (with automatic broadcasting).
On the other hand, ( X ) is typically the output of LayerNorm, as shown below:
\begin{align*} X=\text{LN}(X'')=\text{Norm}(X'')\odot \mathbf{\gamma} +\mathbf{\beta} \tag{4} \end{align*}
where
- ( X''\in\mathbb{R}^{m \times d} )
- ( \mathbf{\gamma}\in\mathbb{R}^{1\times d} ), ( \mathbf{\beta}\in\mathbb{R}^{1\times d} )
Substituting (4) into (2) gives
\begin{aligned} X'&=(\text{LN}(X'')-z)\oslash s \ &=(\text{Norm}(X'')\odot \gamma+\beta-z) \oslash s \ &=\text{Norm}(X'') \odot (\gamma\oslash s) + (\beta-z)\oslash s \end{aligned}
Therefore, we finally obtain
\begin{aligned} \left{\begin{aligned} X'&=\text{Norm}(X'') \odot (\gamma\oslash s) + (\beta-z)\oslash s \ Y&=X'(s^T\odot W)+(zW+b) \end{aligned}\right. \end{aligned}
The diagram is as follows:
Determining ( z ) and ( s )
We want the zero points of all channels to be as aligned as possible. A heuristic approach is to directly use the midpoint as ( z ), i.e.,
[ z_j = \frac{\max({X_{:, j}})+\min({X_{:, j}})}{2} ]
Determining ( s ) is generally more complex. Instead of searching for each component of ( s ) individually, the paper converts the problem into finding a unified clipping value ( t ), which only needs to be searched once.
Here, ( t ) starts from the maximum activation value after all zero-point alignments and performs ( K )-grid search as follows:
[ t = \max(X-z) \cdot \frac{k}{K},\quad k=1,\cdots,K ]
Once the global clipping value ( t ) is obtained, the scale value for each component can be calculated as:
[ s_j=\max(1.0, \frac{X_{:,j}-z_j}{t}) ]
The complete algorithm flow is shown below:
Eq. (6) and Eq. (7) in the pseudocode refer to the reconstruction error and the softmax output error, which are omitted here for now.
RPTQ
A paper from Houmo AI that achieves channel reordering by clustering channels across the cross-dimension, then applies GPTQ quantization to the weights and per-cluster quantization to the activations.
Reordering Method
Compute the min and max values of each channel along the cross-dimension, treat them as 2D sample points, and perform k-means clustering, as shown in subfigure (d) below:
The method is relatively straightforward, but there are several details worth noting:
-
When a reorder operation follows LayerNorm, kernel fusion can be applied to complete it in one pass (the repo also includes a dedicated CUDA kernel).
-
Since Q and K need to perform bmm (batch matrix multiplication), the R2 order must remain consistent.
-
Shortcut connections usually do not perform channel reordering because they need to fuse the outputs from previous layers.
After reordering, GPTQ quantization is applied to the weights, and linear quantization with zero points is performed on the activations in groups. Note that:
-
Because GPTQ uses group-wise quantization, reordering affects the neighbors within each group, which may actually improve quantization quality.
-
Perform grouped quantization on activations. The cross-dimension is split into many groups, each with its own distinct quantization scale and zero-point. To fully utilize INT8_GEMM kernels in actual acceleration, complex coefficient remapping is required. For example, in the BMM(Q, K) operation, the grouped scales of the cross-dimension in Q and K must be transferred to the weights of their respective projection layers.
Summary
Activations contain far more outliers than weights, making their quantization significantly more difficult.
-
Early methods like ZeroQuant adopted a per-token approach. Since input lengths are variable, they used online statistics to handle sequences of different lengths.
-
Later, the community gradually realized that the key challenge in activation quantization lies in the distributional differences across channels. The solution is therefore either to push the quantization scales forward onto the LayerNorm’s γ parameter, or to absorb them into the adjacent weights.
-
Outlier Suppression further considers a shift operation, which aligns better with intuitive understanding.
-
RPTQ takes a rather bold approach by directly reordering channels through clustering.
FP8 Quantization
FP8 is a new format that NVIDIA heavily promoted in recent years and has gradually been adopted by the industry. This section reviews several classic papers on FP8, covering the following main topics:
- FP8 Fundamentals. This introduces the concepts of normal numbers, subnormal numbers, and special values.
- FP8 Nvidia. Based on a modified version of IEEE-754 E4M3, it compresses the space allocated to special values to achieve a larger dynamic range.
- FP8 Qualcomm. Provides a detailed explanation of the fake-quantization process for FP8.
- FP8 AMD. Explores the strengths and weaknesses of different FP8 formats in PTQ scenarios across various CV and NLP tasks.
- FP8 Microsoft. Extends the FP8 functionality of NVIDIA’s TE library by adding support for distributed communication, optimizers, and distributed strategies.
FP8 Fundamentals
Floating-point numbers consist of three categories:
- Normal numbers. The exponent bits are neither all zeros nor all ones.
- Subnormal numbers. The exponent bits are all zeros.
- Special values (NaN). The exponent bits are all ones.
Normal Numbers
- The exponent field of a normal number is neither all zeros nor all ones, so its possible values range from [1, 254]. With a bias of 127, the actual exponent range is [-126, 127].
- The leading bit of the mantissa is implicitly 1, so the mantissa ranges from
1.00xx000to1.11xx111, which in decimal corresponds to [1, 2). - Therefore, the range of normal numbers is (\pm [1,2)\cdot 2^{[-126,127]}). Expanding this gives:
(-2·2¹²⁷, -1·2⁻¹²⁶] ∪ [1·2⁻¹²⁶, 2·2¹²⁷)
Subnormal Numbers
- Normal numbers cannot represent zero or values very close to zero, so subnormal numbers serve to fill this gap.
- When the exponent bits are all zeros, subtracting the bias of 127 would normally yield -127. However, to preserve the gradual underflow property, it is adjusted to -126 (this will be explained further later).
- The implicit leading bit for subnormals is 0 rather than 1, so the mantissa ranges from
0.00xx000to0.11xx111, which corresponds to [0, 1) in decimal. - Thus, the range of subnormal numbers is (\pm [0,1)\cdot 2^{-126}). When the exponent is set to -126, these values exactly fill the gap between normal numbers. The full range is:
(-1·2⁻¹²⁶, 0] ∪ [0, 1·2⁻¹²⁶) = (-1·2⁻¹²⁶, 1·2⁻¹²⁶)
Special Values
- The exponent bits are all ones. This includes infinity (e.g., positive infinity) and NaN (e.g., the result of division by zero).
- Note that NaN is generally not distinguished between +NaN and -NaN.
FP8 Nvidia
NVIDIA’s main contribution to FP8 is a small but important modification to the E4M3 format that significantly expands its representable range. The original paper is FP8 Formats for Deep Learning.
Compared with the IEEE-754 standard, E5M2 is almost unchanged, while E4M3 receives several adjustments, as shown below:
- In the original IEEE-754, the value
2^e-1for the exponent is reserved for special values. NVIDIA reduces the space allocated to special values to enlarge the dynamic range of E4M3. - The representation of Inf is removed, and only one representation of NaN is kept.
- The maximum exponent for normal numbers increases by 1, from
2^4-2-7=7to2^4-1-7=8. - The mantissa of the maximum normal number loses one slot, changing from
(1.111)_2 = 1.875to(1.110)_2 = 1.75. - As a result, the largest normal number increases from IEEE-754’s
1.875·2^7 = 240to1.75·2^8 = 448.
The paper also presents common FP8 workflows for training and inference.
Training
- All GEMM inputs are converted to FP8 format, ensuring the GEMM computation itself is performed in FP8, while the output is kept in higher precision.
- Weights and forward activations use E4M3; backward gradients use E5M2.
- Note that there is still noticeable accuracy degradation on MobileNet-v2.
Inference
- Uses the E4M3 FP8 format.
- Activations use per-tensor scaling factors; weights use per-channel scaling factors. The scaling method is abs_max.
- Regular GEMM operations can achieve good accuracy even without scaling factors, but operations such as residual connections require scaling factors.
FP8 Qualcomm
High-Quality English Translation:
Qualcomm’s FP8 work is among the earliest efforts to apply FP8 to both CV backbone networks and NLP’s BERT models. It provides fundamental schemes for both PTQ and QAT scenarios. The original paper is titled FP8 Quantization: The Power of the Exponent.
The most valuable contribution of this paper is that it clearly explains how to perform FP8 simulated quantization.
As shown above, floating-point numbers essentially divide the number line into intervals whose lengths grow exponentially. Therefore, for a given positive real number ( x_i ), we can first determine which interval it belongs to using the following expression:
$$ x_i \in [2^{\lfloor \log_2 x_i \rfloor}, 2^{\lfloor \log_2 x_i \rfloor+1}) $$
Within the above interval, we further perform uniform quantization. If the mantissa has ( m ) bits, the interval is evenly divided into ( 2^m ) segments. The step size of each segment can be calculated as:
$$ s_i=\frac{2^{\lfloor \log_2 x_i \rfloor+1}-2^{\lfloor \log_2 x_i \rfloor}}{2^m}=2^{\lfloor \log_2 x_i \rfloor-m} $$
Once we have the quantization step size, we can convert ( x_i ) into its corresponding floating-point quantized value ( x_i^{(q)} ), as follows:
$$ \begin{aligned} x_i^{(q)}&=\left\lfloor \frac{x_i-2^{\lfloor \log_2 x_i \rfloor}}{s_i} \right\rceil \cdot s_i + 2^{\lfloor \log_2 x_i \rfloor} \ &=\left\lfloor \frac{x_i}{s_i}-\frac{2^{\lfloor \log_2 x_i \rfloor}}{s_i} \right\rceil \cdot s_i + 2^{\lfloor \log_2 x_i \rfloor} \ &=\left\lfloor \frac{x_i}{s_i}\right\rceil \cdot s_i -\frac{2^{\lfloor \log_2 x_i \rfloor}}{s_i} \cdot s_i + 2^{\lfloor \log_2 x_i \rfloor} \ &=\left\lfloor \frac{x_i}{s_i}\right\rceil \cdot s_i \end{aligned} $$
Note that ( 2^{\lfloor \log_2 x_i \rfloor} / s_i ) is an integer, so it can be directly factored out of the round-to-nearest operation.
Similar to fixed-point quantization, we must also consider boundary conditions. Assume the floating-point format has ( e ) exponent bits and ( m ) mantissa bits. In the general case:
-
The largest representable normal positive number is ( c_1=(2-2^{-m}) \cdot 2^{2^e-1-b} ), where the exponent field is ( 2^e-1 ) and the exponent bias is ( b ).
-
The smallest representable normal positive number is ( c_2=1 \cdot 2^{1-b}=2^{1-b} ), where the exponent field is 1 and the bias is ( b ).
-
The smallest representable subnormal positive number is ( c_3=2^{-m} \cdot 2^{0-(b-1)}=2^{1-b-m} ), where the exponent field takes its minimum value of 0. Due to the gradual nature of subnormals, the bias becomes ( b-1 ).
In practical FP8 usage, a per-tensor scaling factor ( \gamma ) is often introduced:
$$ x_i = \gamma \cdot x_i' $$
This means we first divide the original input ( x_i ) by ( \gamma ) to obtain ( x_i' ), and then represent ( x_i' ) using the FP8 format.
At this point, the quantization step size for ( x_i' ) becomes:
$$ s_i'=2^{\lfloor \log_2 x_i' \rfloor-m} $$
Consequently, the quantization step size for the original ( x_i ) is:
$$ \begin{align*} s_i&=\gamma s_i'=\gamma \cdot 2^{\lfloor \log_2 (x_i/\gamma) \rfloor-m} \ &= 2^{\lfloor \log_2 x_i - \log_2 \gamma \rfloor+ \log_2 \gamma -m} \ &= 2^{\lfloor \log_2 x_i +(b- \log_2 \gamma) \rfloor- (b-\log_2 \gamma) -m} \tag{5} \end{align*} $$
On the other hand, it is easy to see that when ( x_i' ) enters the subnormal range, its quantization step size ( s_i' ) is forced to the smallest subnormal value ( c_3=2^{1-b-m} ). Converting back to the scale of ( x_i ), we get:
$$ c_3'=\gamma \cdot 2^{1-b-m} = 2^{1-(b-\log_2 \gamma)-m} \tag{6} $$
Further analysis of the conditions for entering the subnormal range is as follows:
FP8 Quantization (Part 2)
[ 2^{\lfloor \log_2 x_i' \rfloor} < c_2 = 2^{1-b} ]
That is,
[ \begin{align*} \lfloor \log_2 x_i - \log_2 \gamma \rfloor + b < 1 \ \Rightarrow \lfloor \log_2 x_i + (b - \log_2 \gamma) \rfloor < 1 \tag{7} \end{align*} ]
By combining equations (5), (6), and (7), and performing variable substitution with ( \hat{b} = b - \log_2 \gamma ) and ( p_i = \log_2 s_i ), we obtain:
[ p_i = \log_2 s_i = \begin{cases} \lfloor \log_2 x_i + \hat{b} \rfloor - \hat{b} - m, & \text{if } \lfloor \log_2 x_i + \hat{b} \rfloor \ge 1 \ 1 - \hat{b} - m, & \text{otherwise} \end{cases} ]
This completes the full mathematical expression for FP8 simulated quantization. Here, ( \gamma ) can be viewed as a learnable exponent bias ( \hat{b} ).
The authors found that during QAT, learning ( c_1 ) directly is numerically more stable than learning ( \gamma ). As shown above, the two are directly interconvertible.
PTQ Results on CV and NLP Tasks
FP8 AMD
AMD’s FP8 work primarily explores the strengths and weaknesses of different FP8 formats under PTQ settings across a variety of CV and NLP tasks. The original paper is Efficient Post-training Quantization with FP8 Formats.
First, the paper intuitively shows the slot distribution of different FP8 formats compared with INT8. From the MSE perspective, E3M4 offers a well-balanced trade-off.
The overall workflow of the paper is shown below, with two key components highlighted:
-
Standard Quantization Scheme
- Similar to INT8: per-channel scaling is used for weights, and per-tensor scaling for activations.
- Scaling factors are chosen using the conventional abs_max method.
- For CV models, quantization of the first and last layers is skipped.
-
Extended Quantization Scheme
- For LayerNorm, BatchNorm, and element-wise operations, FP8 data types are used directly for computation.
- Mixed precision: Different FP8 formats are chosen according to the distinct distribution characteristics of activations and weights. Specifically, NLP activations have a very wide range (range-bound), so E5M2 is used; CV activations as well as both CV and NLP weights follow near-Gaussian distributions (precision-bound), so E3M4 is used.
- Direct / static / dynamic quantization: E5M2 has a wide numerical range and does not require scaling (direct quantization). For E3M4, either static quantization (scaling parameters calibrated in advance) or dynamic quantization (scaling parameters determined on-the-fly) can be selected.
The authors also compare the advantages of mixed-precision FP8 over fixed-format FP8:
FP8 MS
NVIDIA’s Transformer Engine (TE) library only provides FP8 support for GEMM, lacking support for distributed communication, optimizers, and end-to-end distributed training. Microsoft’s FP8 implementation completes these missing FP8 components, enabling true FP8 training. The original paper is FP8-LM: Training FP8 Large Language Models.
FP8 Distributed Communication
Recall that in BF16 mixed-precision training, gradients are computed in BF16 but are typically cast to FP32 during all-reduce. If FP8 is used and we do not want to increase precision during all-reduce, both pre-scaling and post-scaling encounter problems.
For pre-scaling, as shown below, the gradient on each card is prone to underflow when divided by ( N ):
[ g = g_1/N + g_2/N + \cdots + g_N/N ]
For post-scaling, as shown below, the gradient on each card is prone to overflow when accumulated.
g = (g_1 + g_2 + ⋯ + g_N) / N
To address this, the authors introduced auto-scaling. Each GPU’s gradient is multiplied by a scaling factor s_i:
g_i' = s_i · g_i
Here, g_i' is represented in FP8 format, and s_i is dynamically updated according to the following rules:
- If the proportion of values in g_i' that reach the maximum representable value in FP8 exceeds a certain threshold (e.g., 0.001%), s_i is halved: s_i ← s_i / 2.
- If the proportion of values reaching the FP8 maximum remains below that threshold for a fixed number of steps (e.g., 1000 steps), s_i is doubled: s_i ← s_i · 2.
Before performing all-reduce, each GPU therefore holds its scaled gradient and corresponding scaling factor, i.e., a set of (g_i', s_i) pairs. The system then selects the smallest scaling factor among them:
s_g = min(s_1, s_2, ⋯, s_N)
Each gradient is then renormalized accordingly:
g_i'' = FP8(s_g · (g_i' / s_i))
Finally, an FP8 all-reduce is performed:
g = g_1'' + g_2'' + ⋯ + g_N''
The final scaling factor for the aggregated gradient is s = N · s_g.
FP8 Optimizer
In BF16 mixed-precision training, the optimizer is typically Adam, which maintains:
- Master weights, first-order (momentum), and second-order (variance) statistics, all stored in FP32.
- Gradients in BF16, which are converted to FP32 before communication; the grad_buffer is also kept in FP32.
As a result, each weight consumes 16 bytes of optimizer memory.
In the FP8 training regime:
- Master weights still require high precision, because gradient updates can sometimes be extremely small; high-precision master weights are needed to capture these tiny changes.
- Gradients are stored in FP8 using the distributed communication scheme described above.
- The first-order moment in Adam is stored in FP8, while the second-order moment is stored in FP16.
Consequently, the per-weight memory footprint in the optimizer becomes:
FP8 Distributed Strategy
The distributed training strategy includes the common 4D parallelism: Data Parallel (DP), Tensor Parallel (TP), Pipeline Parallel (PP), and Sequence Parallel (SP). DP and PP behave the same under FP8 as in conventional mixed-precision training. TP and SP, however, require modifications, as shown below:
Summary
FP8 comes in multiple formats such as E5M2 and E4M3, each suited to different scenarios:
- E5M2 follows the standard IEEE-754 design, while E4M3 reduces the space allocated to special values (NaN, Inf), thereby expanding the representable value range.
- Quantization simulation for FP8 is significantly more complex than for fixed-point formats, requiring careful handling of the boundary conditions between normal and subnormal numbers.
- In extreme training scenarios, the complexity of FP8 training approaches that of Quantization-Aware Training (QAT). Each tensor must be bound to a learnable scale (i.e., an exponent bias), which can make model convergence more difficult.
- In inference scenarios, FP8 preserves accuracy quite well. Standard PTQ strategies can generally achieve near-lossless performance.
KV Cache Quantization
In ultra-long sequence scenarios, the KV Cache often consumes a significantly larger amount of GPU memory. Typically, FP8 is used to quantize the KV Cache. However, if further bit reduction is desired, special techniques are required. This section introduces a relatively recent paper, WKVQuant, which achieves 4-bit quantization of the KV Cache.
WKVQuant
This paper performs INT4 quantization on all weights and the KV Cache. It introduces three main innovations:
- POQ (Past Only Quantization): Keep the activation of the current token in FP16 while quantizing all past KV Cache entries to INT4.
- Two-dimensional Quantization: Apply both per-token and per-channel quantization to the KV Cache simultaneously.
- CRC (Cross-block Reconstruction Regularization): Use the reconstruction error across multiple blocks as the loss function to fine-tune the hyperparameters.
The authors’ goal is to retain FP16 precision for all computations (including GEMM and BatchMatMul), while applying INT4 quantization to all weights and the KV Cache — hence the title WKVQuant. The overall framework is shown below:
Past Only Quantization
This idea is straightforward. During the decode phase, the activation of the current token is kept in FP16. Only after the computation is completed is it quantized to INT4 and stored. The schematic is shown below. Since it is quite intuitive, we will not elaborate further.
Two-dimensional Quantization
For the input projection of QKV, assume ( X \in \mathbb{R}^{T \times C_{\text{in}}} ), ( W \in \mathbb{R}^{C_{\text{in}} \times C_{\text{out}}} ), and ( B \in \mathbb{R}^{1 \times C_{\text{out}}} ). The output KV Cache is ( Y \in \mathbb{R}^{T \times C_{\text{out}}} ), given by:
[ Y = XW + B ]
We can apply per-channel shift and scale to ( Y ), with parameters ( \delta \in \mathbb{R}^{1 \times C_{\text{out}}} ) and ( s \in \mathbb{R}^{1 \times C_{\text{out}}} ), yielding:
$$ \left{\begin{align*} Y &= XW + B \tag{8} \ Y' &= (Y - \delta) \oslash s \tag{9} \ Y'' &= Q(Y') \odot s + \delta \quad \tag{10} \ Z &= f(Y'') \tag{11} \end{align*}\right. $$
Combining equations (8) and (9) gives:
$$ \begin{aligned} Y' &= (XW + B - \delta) \oslash s \ &= X(W \oslash s) + (B - \delta) \oslash s \ &= XW' + B' \end{aligned} $$
From this we can observe:
- The shift and scale operations on ( Y' ) in (9) can be absorbed into the preceding input projection, meaning the per-channel quantization of ( Y ) is folded into the per-channel quantization of ( W ).
- ( Q(Y') ) in (10) represents per-token quantization of ( Y' ).
- ( f(Y'') ) in (11) denotes the subsequent operations in the network.
The quantization of ( W ) follows the Omniquant method, which is a quantization scheme with a zero point, defined as:
$$ \left{\begin{aligned} W_q &= \text{clamp}\left(\left\lfloor\frac{W}{h}\right\rceil + z, 0, 2^{N-1}\right) \ h &= (\gamma \text{max}(W) - \beta \text{min}(W)) / 2^{N-1} \ z &= -\left\lfloor \beta \text{min}(W) / h \right\rceil \end{aligned}\right. $$
Cross-block Reconstruction Regularization
As shown above, four parameters need to be determined: ( \delta ), ( s ), ( \gamma ), and ( \beta ). The paper uses the reconstruction error across multiple layers as the loss function to optimize these four parameters:
The mathematical formulation is:
$$ \arg\min_{\delta,s,\gamma,\beta} \text{MAE}(\hat{y}{i+k-1}, y{i+k-1}) $$
Final Thoughts
At this point, we can provide a concise summary for the 7 questions about LLM quantization mentioned at the beginning:
-
Floating-point vs. fixed-point numbers. In essence, fixed-point representation means a group of elements shares the same quantization parameters. The way the group is divided determines whether it is per-tensor, per-token, per-channel, or per-group quantization. In the extreme case where the group contains only a single element, its representational power becomes identical to that of floating-point numbers.
-
Scale learning in QAT. By simply applying the chain rule for direct derivation, we can obtain the gradient form that is clipped on both sides of the intermediate “sawtooth.”
-
Conventional bit-width quantization for weight-only. Second-order methods start from the mathematically rigorous OBS (Optimal Brain Surgeon), then continuously relax constraints and apply mathematical approximations, eventually evolving into GPTQ and OWQ, whose solving speed is practically acceptable. Meanwhile, AWQ draws inspiration from SmoothQuant, bringing the idea of equalization into weight-only quantization.
-
Ultra-low-bit weight-only quantization. Once the bit width drops below 4 bits, quantization outliers are typically handled separately—for example, in SpQR and SqueezeLLM. AQLM goes even further by treating the quantization problem as a standard compression task, reformulating it using Additive Quantization techniques from approximate nearest neighbor search.
-
Activation + Weight quantization. From the early focus on per-token quantization in ZeroQuant, later works gradually realized that differences in channel distributions are the real key to activation quantization. Subsequent work such as Outlier Suppression v2 further considers both shift offsets and scale scaling at the same time.
-
FP8 quantization. FP8 still has a relatively high barrier to adoption in training scenarios, but in inference scenarios it can generally be applied quite easily with almost no loss in accuracy.
-
KV Cache quantization. Conventional 8-bit quantization (such as FP8 KV Cache) is basically plug-and-play. However, for even lower bit widths (e.g., 4-bit), techniques from both weight quantization and activation quantization need to be combined (for example, using per-token and per-channel approaches together).
PS: Since the author, Xiao A, has not personally implemented every detail mentioned above, most of the content was summarized in a bottom-up manner through studying code and carefully reading excellent papers. At its core, this is just knowledge aggregation and rephrasing—ultimately, 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; knowledge of LLM distributed training; as well as LLM quantization, inference acceleration, and deployment/servitization, feel free to follow me — aaronxic~
References
Quantization Insights: FP8 and LLM-FP4
FP8 Quantization — Principles, Implementation, and Error Analysis