QuantizationNote Part2 Algorithm
QuantizationNote Part2 Algorithm
Part 2: Algorithms
From Distribution Mismatch to Production-Ready Quantization
AnhND + Claude
Prerequisite: Part 1 — Hardware Constraints
Part 1 answered: given a target device and deployment scenario, what kind of quantiza-
tion does the hardware require?
Part 2 answers: given that requirement, how do we minimise the accuracy loss?
Lecture Roadmap
1. Uniform Quantization — the scalar view; XW when weights and activations are
quantized; INT matmul pipeline; granularity
2. Non-Uniform Quantization — codebooks, LUT dequantization, lattice methods,
NVFP4
3. Clip Range & Calibration — rounding vs. clipping error; how the calibration set is
built; Min-Max, Percentile, MSE, KL
4. QAT vs. PTQ — two paradigms; STE; BitNet; who can run what
5. The Outlier Problem — why outliers break quantization; activation vs. weight outliers
6. Weight-Only PTQ — GPTQ (Hessian correction); AWQ (activation-guided scaling)
7. Weight-Activation PTQ — SmoothQuant; rotation-based methods (QuaRot, FlatQuant)
8. KV Cache Quantization — why KV is different; PolarQuant; QJL; TurboQuant
9. Post-Quantization Correction — residual bias; AdaRound; EGBC
10. Synthesis — Algorithm × Hardware matrix; decision flowchart
1
The Narrative Thread
Every section answers the question raised by the previous one:
Connection to Part 1
Part 1 derived which type of quantization the hardware requires (W4A16 vs W8A8,
per-group vs per-channel). Part 2 derives which algorithm minimises accuracy loss within
that type. The two parts are orthogonal axes — hardware and algorithm — and both
must be right for a deployment to succeed.
2
Notation Used in This Lecture
Symbol Meaning
W ∈ Rd×C Full-precision weight matrix (d: input dim, C: output chan-
nels)
X ∈ Rd×m Input activations from m calibration samples
Wq , X q Quantized weight / activation (integer values)
Ŵ , X̂ Dequantized weight / activation (float approximation)
s Scale factor (step size)
z Zero-point (offset for asymmetric quantization)
b Bit-width (e.g. b = 4 for INT4)
µ = E[X] Mean activation vector
Q(·) Quantization operator
WxAy Shorthand: weights at x bits, activations at y bits (e.g.
W4A16, W8A8)
⌊·⌉ Round to nearest integer
⌊·⌋, ⌈·⌉ Floor / ceiling (the two rounding candidates)
H Hessian of the layer reconstruction loss
R Orthogonal rotation matrix
1. Uniform Quantization
x̂ = s · (xq − z)
3
The fundamental tension
Increasing s widens the representable range but coarsens the grid (larger rounding error
per value). Decreasing s gives finer resolution but clips more values to the boundary.
You cannot improve both simultaneously at fixed b. This tension is the root
cause of every difficulty in Sections 5–9.
• Rounding error — every value that falls inside the clip range is rounded to the nearest
grid point. Error bounded by s/2 per value. Decreasing s reduces this.
• Clipping error — values outside the clip range are saturated to the boundary. Error
can be arbitrarily large. Increasing s (widening the range) reduces this.
Key insight. The optimal clip range is not [min(x), max(x)]. Deliberately clipping a
few outliers — accepting some clipping error — often dramatically reduces the rounding
error for the bulk of the distribution. This is the entire motivation for Section 3 (clip
range calibration).
Asymmetric (z ̸= 0)
max(X) − min(X) min(X)
s= , z=−
2b − 1 s
4
Hardware note
The zero-point subtraction (wq − z) must be evaluated at dequantization. For W4A16 this
is absorbed into the register-level unpack — negligible cost. For W8A8 INT matmul the
zero-point induces correction terms in the INT32 accumulator output, requiring extra
additions per output element. ← Part 1, S6 — Kernels & Fusion
Why this works. The activation X stays in FP16 throughout — no quantization error
is introduced into the activations. The only error source is the weight approximation
Ŵ ≈ W . At 4-bit per-group, this error is small enough that model quality is largely
preserved. This is the dominant production scheme for LLMs.
Bandwidth connection
Storing W in INT4 instead of FP16 reduces weight bytes by 4×. Every weight byte
saved is a direct reduction in HBM transfer time. This — not arithmetic speedup — is
why W4A16 works. ← Part 1, S3 — The Memory Bottleneck
Xq = Q(X), Wq = Q(W )
X̂ Ŵ = (sX (Xq − zX )) (sW (Wq − zW )) = sX sW · (Xq − zX )(Wq − zW )
5
Where the arithmetic speedup comes from: INT8 Tensor Cores deliver 2× the through-
put of FP16 Tensor Cores on A100 (624 TOPS vs. 312 TFLOPS). ← Part 1, S6 — Compute
Architecture
Critical condition
This arithmetic speedup only materialises when the workload is compute-bound —
i.e. batch size B ≳ B ∗ ≈ 156 on A100. At small batch sizes (online serving), the chip is
memory-bound and W8A8 is strictly worse than W4A16 in tokens/second while introducing
more accuracy risk. ← Part 1, S5 — Roofline Model
• Softmax requires high dynamic range in its logit inputs: attention scores span a wide
range; coarse quantization shifts the softmax distribution and destroys ranking.
• LayerNorm is sensitive to the mean and variance of its inputs; quantization bias shifts
these statistics across layers.
• Activation outliers (Section 5): a small number of input dimensions carry extremely
large magnitudes — up to 100× the typical value. These blow up the quantization range
for the entire activation tensor.
• Residual connections accumulate quantization error across all layers; the error com-
pounds in a way that CNN skip connections do not exhibit at the same severity.
This is why W4A16 dominates production LLM deployment, not W8A8. Keeping
activations in FP16 sidesteps all four problems above. The price: no arithmetic speedup
from INT8 Tensor Cores. The benefit: orders-of-magnitude simpler quantization with
substantially better accuracy at 4-bit.
6
rounding error. Group size g = 128 is the standard: AWQ and GPTQ both use it.
d 4096
Scale count = C × = 4096 × = 4096 × 32 = 131 072
g 128
Scale storage = 131 072 × 2 bytes (FP16) = 256 KB per layer
Effective bit-width with scales. Adding FP16 scales to INT4 weights increases the
average bit-width slightly:
16 16
Effective bits = 4 + =4+ = 4.125 bits per weight
g 128
At g = 128, the overhead is only 3% above pure INT4. At g = 32, it rises to 4.5 bits — still
acceptable. At g = 8, it reaches 6 bits, largely defeating the purpose of INT4.
unpack cast +
INT4 weightscooperative INT4 tile FP16 × FP16 FP32 acc
tile load + dequant FP16 weights MMA epilogue
+ FP16 scales + scales Tensor Core → FP16
in registers
in HBM in shared mem MMA output
• HBM → shared memory: the only expensive step — this is where the 4× bandwidth
saving of INT4 is realised.
• Unpack in registers: ∼3 instructions per 8 weights; negligible vs. HBM latency.
7
• Tensor Core MMA: runs in FP16 — identical to the FP16 baseline kernel. INT4
storage provides no arithmetic speedup here; the benefit is purely bandwidth.
• FP16 output: activations were never quantized; downstream layers see unmodified FP16
values.
Section 1 in one sentence. Uniform quantization maps floats to integers via a scale
and zero-point; at W4A16, the only change relative to FP16 inference is that weights
travel through HBM in a 4× smaller format and are unpacked to FP16 in registers —
everything else is identical.
2. Non-Uniform Quantization
Codebooks, lookup tables, and floating-point formats — when equal-width bins are not the right answer
This is optimal only if the data is uniformly distributed. LLM weight distributions
are not uniform — they are typically bell-shaped (Gaussian or Laplacian), with the vast
majority of values concentrated near zero and a long, thin tail.
density
bins wasted[-2pt]on sparse tail
w
coarse where[-2pt]data is dense
The mismatch. With b = 4 (16 levels) and a Gaussian weight distribution, roughly
half the levels land in the sparse tails where almost no weights live. Only ∼8 levels
cover the dense central region. A non-uniform grid that concentrates levels near zero
can achieve lower expected quantization error with the same number of bits.
8
2.2 What Is Non-Uniform Quantization?
General definition. Replace the uniform grid {0, s, 2s, . . . , (2b −1)s} with an arbitrary set
of 2b centroids:
C = {c1 , c2 , . . . , c2b }, ck ∈ R
Quantize: wq = arg mink |w − ck | (assign to nearest centroid)
Dequantize: ŵ = cwq (lookup by index)
The quantized representation stores only the index wq ∈ {1, . . . , 2b } — b bits per weight,
same as uniform. The centroids C are stored once per layer (or per group) as a small lookup
table (LUT).
w
c1 c2 c3 c4 c5 c6 c7 c8 c9 c10
Convention reminder
From here on: uniform quantization is the default. Any method using a codebook
will say so explicitly.
The cost of the LUT read depends critically on where C lives in the memory hierarchy
← Part 1, S4 — Memory Hierarchy :
For INT4 (24 = 16 centroids × 2 bytes = 32 bytes), the entire LUT fits in registers —
fast. For INT8 (28 = 256 centroids × 2 bytes = 512 bytes), it must live in shared memory,
requiring careful bank-conflict-free layout. The standard fused dequant-GEMM pattern
from Part 1 cannot be reused without modification; a new kernel must be written. This
is the main reason uniform quantization dominates production: the fused
kernel ecosystem already exists.
9
2.4 Codebook Type I — k-Means Clustering
The simplest non-uniform codebook: run k-means on the weight distribution with k = 2b
clusters.
Procedure:
2. Store the cluster indices wq (b bits per weight) and the centroid table C (FP16, 2b entries).
3. At inference: dequantize via ŵ = C[wq ].
Strengths
• Centroids adapt to the actual weight distribution
• Significant accuracy improvement vs. uniform at the same bit-width
• Simple to implement and understand
Weaknesses
• k-means is sensitive to initialisation
• Codebook is layer-specific: different LUT per layer, complicates batched kernel
launches
• Dequantization is a LUT op, not multiply-add — non-trivial kernel change
Historical note
k-means codebook quantization has a long history in signal processing (vector quantiza-
tion, JPEG, MP3). Its application to neural network weights dates to Han et al. (2016)
— “Deep Compression” — which combined weight pruning, k-means quantization, and
Huffman coding.
10
Vector quantization view. Instead of scalar quantization wi → ck ∈ R, use vector
quantization:
(w1 , . . . , w8 ) → ck ∈ E8 ⊂ R8
Store one 8-bit index per 8 weights: effectively 1 bit per weight in terms of index
overhead, with the E8 lattice providing much better coverage than any scalar 1-bit
scheme.
Why lattice beats k-means. k-means centroids are data-dependent and must be
stored per layer. Lattice centroids are fixed by the mathematical definition of E8 —
they are the same for every layer, eliminating the per-layer LUT storage and allowing
the decode logic to be hardcoded in the kernel.
11
sparsely. This is exactly the non-uniform coverage that matches a Gaussian/Laplacian weight
distribution.
FP8 vs INT8. E4M3 has more representable values near zero (where weights cluster)
and fewer at large magnitudes. This means FP8 often requires no explicit clip range
calibration for weights — the floating-point format naturally matches the distribution.
For activations with outliers, FP8 E5M2’s wider dynamic range (5 exponent bits) is
preferred over E4M3.
• On current GPUs (A100, H100), INT4 is software-emulated : weights are stored in INT4
and unpacked to FP16 in registers. The matmul still runs on FP16 Tensor Cores. The
bandwidth saving is real; the arithmetic speedup is not. ← Part 1, S6 — Compute Architecture
• Blackwell’s Tensor Cores natively support FP4 multiply-accumulate. FP4 storage therefore
provides both bandwidth savings (4× vs FP16) and arithmetic speedup vs FP8/INT8, in
any regime — not just compute-bound.
• The floating-point non-uniformity means FP4 can represent a wider range of weight
magnitudes than INT4 at the same 4 bits, with natural concentration of levels near zero.
Design implication
The roofline framework from Part 1 still applies to FP4 on Blackwell — but the ridge
point analysis changes because FP4 Tensor Core throughput is higher than FP16. The
hardware co-design argument from Part 1 Section 1 holds: the algorithm (choose FP4
vs INT4 vs FP8) must match what the specific chip can execute natively. ← Part 1, S1
— Why Hardware First?
12
2.9 Accuracy vs. Hardware Cost — Where Each Method Sits
Quantization accuracy
Lattice E8
k-means(QuIP#)
Pareto frontier
codebook
FP8
(H100 native)
Uniform INT4
per-group
(AWQ/GPTQ)
Uniform
INT4
per-tensor production
sweet spot
Why the sweet spot is per-group uniform. The Pareto frontier shows that moving
from per-tensor to per-group INT4 yields a large accuracy gain at very low hardware
cost. Moving further to codebook methods yields incremental accuracy improvement at
substantially higher kernel complexity. For most deployments, per-group uniform INT4
(AWQ/GPTQ style) sits at the right trade-off point.
13
Hook into Section 3
The question Section 2 leaves open
Both uniform and non-uniform quantization share the same prerequisite: before any grid
can be placed, someone must decide what range to cover.
The clip range [α, β] determines the step size s = (β − α)/(2b − 1), which sets both the
resolution and the saturation point. A poorly chosen clip range makes every algorithm
in Sections 6–9 irrelevant, because the rounding grid is already badly positioned.
Section 3 answers: how is the clip range chosen, how is the calibration set that informs
this choice constructed, and what estimation methods exist — from the naive (min-max)
to the principled (MSE minimisation, KL divergence)?
The decision every algorithm silently depends on — and how to make it well
β−α jαm
s= , z = − , ŵ = s (wq − z)
2b − 1 s
Every downstream quantity — step size s, rounding decisions, Hessian-based corrections,
bias estimates — is a function of the chosen [α, β].
14
E[(w − ŵ)2 ] = E[(w − ŵ)2 1w∈[α,β] ] + E[(w − ŵ)2 1w∈[α,β]
/ ]
| {z } | {z }
rounding error clipping error
error
α∗
optimal clip
α∗ < max |w|
min-max
(too wide)
Key insight. The optimal clip range α∗ is strictly smaller than max |w|. Deliberately
clipping the most extreme values — accepting a small clipping error — allows a finer
grid that reduces rounding error for the bulk of the distribution. Min-max is almost
never optimal.
What is collected
For each linear layer, collect the input activation matrix X ∈ Rd×m (where m aggregates
all token positions across all calibration sequences). From X: compute per-channel
min, max, percentiles, mean µ, and variance σ 2 — stored once, used by all clip range
estimators below.
15
3.4 Clip Range Estimators — Overview
Given the collected statistics, five standard estimators:
All five estimators require the same calibration data — they differ only in the objective
used to score candidate clip ranges. In practice, MSE minimisation is the most widely
used in PTQ pipelines (GPTQ, AWQ, AutoGPTQ default settings) because it directly
minimises the quantity that matters: the expected squared deviation between w and ŵ.
α = min(W ), β = max(W )
max(W ) − min(W )
s=
2b − 1
Strengths
• Zero clipping error by construction
• No calibration data needed for weights
• O(1) computation (one pass over weights)
• Deterministic: no hyperparameter
Weaknesses
• Dominated by outliers: one value at 50× the typical magnitude forces s to be 50×
too large
• Rounding error becomes catastrophic for the bulk of the distribution
• Almost never the right choice for LLMs where activation outliers are structural
Worked example. Channel with values mostly in [−1, 1] but one outlier at 50. With b = 4
(16 levels):
50 − (−50)
s= ≈ 6.67
15
Every value in [−1, 1] maps to the same quantization level — essentially 1-bit resolution in
the region that contains 99%+ of the data.
16
3.6 Estimator II — Percentile Clipping
Intuition. The extreme outliers that dominate min-max are rare by definition. Clipping the
bottom and top p-fraction removes them, dramatically tightening the clip range and reducing
s, at the cost of a small clipping error for the clipped fraction.
outlier outlier
w
min-max range (dominated by outliers)
Sensitivity warning
where Qα,β is the quantization operator with clip range [α, β].
1. Generate G candidate clip ranges (e.g. β ∈ {0.5, 0.55, . . . , 1.0} × max |w|, symmetric or
asymmetric).
2. For each candidate, quantize all calibration values and compute the average squared error.
3. Select the candidate with the lowest error.
Cost: O(m × G) — fast in practice with G ≈ 100 candidates and m = 128 samples.
Why MSE is the standard choice. It balances rounding error and clipping error
optimally under a squared-loss criterion — the same criterion used by GPTQ’s recon-
struction objective and EGBC’s bias correction. The estimate is also less sensitive to
the calibration set size than percentile-based methods, because the MSE averages over
all values rather than relying on tail statistics.
17
3.8 Estimator IV — KL Divergence
Preserve the shape of the distribution, not just the magnitude of error.
Intuition. MSE penalises large pointwise errors. KL divergence penalises changes to the
probability distribution of values — it cares that the quantized distribution has the same
shape as the original, not just the same average squared deviation.
• The quantized values feed into a softmax (attention scores, output logits): softmax is
sensitive to the relative magnitudes of its inputs, so preserving the distribution shape
matters more than minimising individual errors.
• The deployment metric is perplexity or calibration rather than a regression loss: these
metrics depend on the probability model, which is determined by the distribution of logits.
TensorRT default
NVIDIA’s TensorRT uses KL-divergence calibration as its default for INT8 activation
quantization. The implementation discretises both distributions into 2048-bin histograms
and minimises KL over a set of candidate saturation thresholds.
E[w2 ]
SQNR(α, β) = α∗ , β ∗ = arg max SQNR
E[(w − Qα,β (w))2 ] α,β
Connection to MSE. Maximising SQNR is equivalent to minimising MSE when the signal
power E[w2 ] is constant (i.e. not a function of [α, β]). In practice, the two criteria give nearly
identical clip ranges.
• Gaussian N (0, σ 2 ): optimal clip at α∗ ≈ 2.83 σ for 8-bit quantization (decreases with b).
• Laplacian Lap(0, b): optimal clip at α∗ ≈ 5.0 b for 8-bit quantization.
These analytical solutions are useful for rapid initialisation of the grid search in MSE or KL
optimisation — start near the analytical optimum and search a narrow range.
SQNR comes from the signal processing tradition (audio coding, image compression) and is
less commonly seen in recent PTQ papers, which tend to use MSE or KL directly. It is worth
knowing because some hardware vendor documentation (particularly for DSP-based edge chips)
still expresses quantization specifications in terms of SQNR targets.
18
3.10 Per-Channel and Per-Group Clip Ranges
The clip range estimators above apply to a single tensor. In practice, clip ranges are computed
independently per channel or per group, matching the granularity of the quantization scheme.
• Each output channel has its own weight distribution; a shared clip range would be
dominated by the widest channel.
• Computing per-channel min/max (or percentile, or MSE optimum) adds negligible cost —
it is a single pass over each column of W .
• Per-channel is strictly better than per-tensor for LLMs and should be considered
the minimum granularity.
Per-group clip range (one [αj,g , βj,g ] per group of 128 weights):
Too few samples Tail percentile estimates are Use ≥ 128 samples; prefer
noisy; outlier-sensitive layers MSE over percentile
get wrong clip range
Single-domain bias Clip range tuned for one task Mix data from multiple
fails on another sources (C4, WikiText, task-
specific)
19
Connection to EGBC (Section 9)
We now know what to quantize (uniform integer grid, per-group clip range, MSE-
calibrated) and how to choose the range.
The remaining question is when to quantize — and this is not just a scheduling decision.
It fundamentally changes what information is available, what the model can adapt to,
and what computational resources are required.
Quantization-Aware Training (QAT) simulates the quantization during training,
allowing the model to adapt its weights to minimise quantization error end-to-end.
Post-Training Quantization (PTQ) applies quantization after training is complete,
using only a small calibration set and no gradient computation.
Section 4 maps both paradigms in detail: their inputs, outputs, costs, and the regimes
where each is the right choice.
20
QAT
PTQ
The key asymmetry. QAT has access to gradients and the full training signal — the
model actively adapts its weights to minimise task loss under quantization. PTQ has no
gradients — it can only rearrange the discrete levels of an already-trained model. This
asymmetry explains almost every difference in cost, accuracy, and applicability between
the two.
QAT PTQ
Ŵ = s Q(W/s) − z (fake-quantize)
backprop ∂L update
Ltask (Ŵ ) −−−−−→ −−−−→ W ← W − η ∇W L
∂W
The weights W remain in full precision throughout training. Only the forward pass uses the
21
fake-quantized version Ŵ . The backward pass updates W (full precision) using the gradient
of the task loss computed through Ŵ .
Why this works. With access to the full training objective, the model can learn weight
configurations that are both task-effective and robust to quantization error. Weights
gradually migrate away from rounding boundaries; the distribution adapts to be more
quantization-friendly. This adaptation is impossible in PTQ, which has no gradient
signal.
Three solutions:
Forward pass:
ŵ = s · w/s (actual rounding)
Backward pass (STE):
∂ ŵ STE
= 1|ŵ|≤β (pass gradient through if not clipped)
∂w
What STE does. In the backward pass, treat the rounding function as if it were the identity
(gradient = 1) for values inside the clip range, and as zero for clipped values. The gradient of
the task loss flows through the fake-quantize node as if quantization did not happen.
22
Known limitations
• Gradient is biased — can cause oscillation near rounding boundaries
• Does not work well at very low bit-widths (b = 1) without additional tricks
• Scale s is treated as a fixed hyperparameter (not learned) in basic STE
∂ ŵ ∂
= s · ⌊w/s⌉ ≈ ⌊w/s⌉ − (w/s) · 1|w/s|≤2b−1
∂s ∂s
The gradient w.r.t. s tells the network how to adjust the step size to minimise the task
loss — the scale is no longer a fixed calibration choice but part of the learned model. LSQ
achieves state-of-the-art QAT accuracy at 4-bit and above, particularly for CNNs and small
transformer models.
Soft / Relaxed Quantization. Replace the hard rounding function with a smooth
approximation:
1
⌊x⌉soft = x − sin(2πx) (periodic approximation)
2π
or a sigmoid-based relaxation that interpolates between floor and ceiling. Provides true
gradients everywhere. Used in research settings; less common in production QAT pipelines.
• Weights constrained to {−1, 0, +1} — “1.58 bits” per weight (log2 3 ≈ 1.58).
• Trained from scratch on very large token budgets (same order as full-precision pretraining).
• Key result: with enough data, ternary models approach the performance of full-precision
models at the same parameter count. The model learns to compensate for the extreme
quantization through weight magnitude and structure.
23
Hardware implication. A ternary matmul requires only additions and subtractions —
no multiply instructions at all. This motivates custom silicon (or very efficient FPGA
designs) where multiply units are replaced with adder trees, dramatically reducing power
and area. On current GPUs, ternary weights must still be unpacked to FP16 for the
Tensor Core MMA, so the arithmetic benefit is not yet realised without specialised
hardware.
A compromise used in practice for medium-sized models (1–7B): start from a pretrained
checkpoint, then run a short QAT fine-tuning pass on a domain-specific dataset (rather
than full pretraining from scratch). This requires far less compute than full QAT while
recovering some of the accuracy gap left by PTQ.
Output:
24
The core PTQ insight
Flatten the weight distribution as much as possible before applying the
uniform grid.
All PTQ algorithms in Sections 6–9 are specific instantiations of this single idea:
• AWQ: scale channels to equalise magnitudes
• GPTQ: redistribute error to already-quantized weights
• SmoothQuant: migrate difficulty from activations to weights
• EGBC: correct the first-moment shift after rounding
• Step size s ≈ σ/2 for a typical weight channel (where σ is the channel standard deviation).
• Rounding error per weight ≲ s/2 ≈ σ/4.
• Output error per channel: ∥∆W x∥ is small relative to ∥W x∥ — residual connections
absorb the perturbation.
• PTQ correction methods (Section 9) can recover the small residual bias. ✓
• Step size s ≈ σ — each level covers one standard deviation of weight variation.
• Rounding error per weight ≲ s/2 ≈ σ/2.
• Output error per channel grows proportionally; residual connections no longer absorb the
perturbation.
• The calibration set (128 samples) provides insufficient signal to correct errors of this
magnitude — there are more degrees of freedom in the error than in the calibration data.
25
Notation Meaning Typical regime
26
4.12 Section Summary
Section 4 in five points
1. QAT simulates quantization during training, allowing the model to adapt end-to-end.
Produces the best accuracy at any bit-width, but requires full training compute.
2. PTQ applies quantization after training using only a small calibration set and no
gradients. Practical for any model size; the standard approach for large LLMs.
3. STE is the canonical gradient estimator for QAT — a biased but effective approxi-
mation that treats rounding as identity in the backward pass.
4. BitNet / ternary QAT shows that training-from-scratch at extreme bit-widths
(≤2-bit) can match full-precision quality, at the cost of full pretraining compute and
specialised hardware.
5. PTQ works at 4-bit, struggles below 3-bit. The crossover is determined by
whether the rounding step size is small relative to the weight distribution’s standard
deviation.
The single biggest obstacle to LLM quantization — and why it gets worse with scale
Why this section is here. Every algorithm in Sections 6–9 exists primarily to deal with
outliers. Understanding them precisely — what they are, where they live, and exactly how
27
they break quantization — is the prerequisite for understanding why any of those algorithms
make the design choices they do.
The narrative so far. Sections 1–3 established the quantization grid and clip range.
Section 4 established when to apply quantization. Section 5 establishes what goes wrong
— the enemy that all subsequent algorithms are designed to fight.
• Arise from the interaction of Adam optimiser, weight decay, and layer normalisation
during training.
• Some output channels learn much larger weights than others because they encode more
“salient” features.
• Magnitude: typically 3×–10× the median channel norm.
• Per-channel scaling (Section 3) largely handles this — each channel gets its own clip
range.
• First documented at scale by Dettmers et al. (2022) in LLM.int8() — the paper that
made the problem famous.
• Appear in models with ≥ 6.7B parameters trained on large corpora.
• A small number of fixed input feature dimensions (typically 1–5 out of 4096+) develop
persistent large magnitudes.
• Magnitude: up to 100× the typical activation value.
• Structural: the same dimensions are large across all tokens, all layers, all forward passes.
They are a property of the trained model, not the input.
28
Key structural property. The outlier dimensions (red columns) are identical across
all tokens. Every row of the activation matrix has a large value in dimension 5 and
dimension 12, regardless of the input text. This means the outlier pattern is a property
of the model weights, not the input — and it cannot be addressed by per-token scaling
alone.
β−α
s=
2b − 1
One large outlier forces β (or |α|) to be large, which forces s to be large, which coarsens the
grid for all other values.
Worked example. INT8 quantization (b = 8, 256 levels). A hidden dimension with values
in [−1, 1] but one outlier at 100:
100 − (−100)
smin-max = ≈ 0.784
255
Every value in [−1, 1] is assigned one of only
2
+ 1 = 3 distinct levels
0.784
29
5.5 Weight Outliers vs. Activation Outliers
Per-channel quantization:
max |w:,j | wij
sj = , wq,ij = clip , −(2b−1 ), 2b−1 − 1
2b−1 − 1 sj
ŵij = sj · wq,ij
Achieves
• Isolates each channel’s clip range — one large channel cannot contaminate others
• Dramatically reduces per-channel quantization error vs. per-tensor
• Necessary minimum for LLMs — per-tensor is almost never acceptable
30
Does not achieve
• Does not fix outliers within a channel — the outlier still dominates that channel’s
step size
• Does not address activation outliers (fixed in X, not in W )
• Does not correct the residual bias E[(Wq − W )X] ̸= 0
Per-group scaling (group size 128) goes further: within a channel, each group of 128 weights gets
its own scale, so even intra-channel outliers are isolated. This is the default for AWQ and GPTQ.
|wmost
ij | values use only lowest 1–2 levels
outlier
step size s ∝ max |wij |
outlier
This is exactly the problem AWQ addresses. AWQ identifies that the input
dimensions with large |µi | (large mean activation magnitude) correspond to the weight
dimensions that carry the most output influence. By rescaling those weight dimensions
before quantization, AWQ effectively reduces the intra-group outlier without changing
the mathematical output. We examine the mechanism in Section 6.
1. Dynamic values. Unlike weights, activation values change with each input. The
outlier dimension is fixed, but its magnitude varies per token and per input sequence. A
per-channel scale calibrated on 128 samples may be wrong for a specific inference input.
2. No offline fix. Weight outliers can be handled offline (before deployment) by analysing
the weight matrix. Activation outlier scales must either be calibrated offline (and may
generalise poorly) or computed online (dynamic quantization — expensive per token).
3. Propagation through softmax. A large quantization error in an attention Key shifts
the softmax distribution catastrophically — wrong attention weights corrupt the entire
layer output, not just one dimension.
31
The SmoothQuant insight (preview)
The key observation: if the outlier is in the activation dimension i, we can divide Xi by a
constant si (making it smaller, easier to quantize) and multiply the corresponding weight
row Wi,: by si (absorbing the scale). The product XW is unchanged. This “migrates”
the quantization difficulty from activations to weights. Details in Section 7.
W = Wsparse + Wdense
| {z } | {z }
outlier weights in FP16 remaining weights in INT4
Procedure:
Strengths
• Outlier weights are exact — zero quantization error for the most influential weights
• Principled: protects weights by their actual impact on output
Weaknesses
• Two matmuls per layer — kernel complexity increases
• Sparse FP16 storage overhead reduces effective compression ratio
• Less hardware-friendly than pure INT4 weight storage
32
5.10 The Outlier Landscape — How Each Algorithm Responds
Per-channel scaling Weight channel out- Independent clip range per chan-
liers nel
Per-group scaling Intra-channel weight Independent clip range per 128
outliers weights
AWQ Intra-channel weight Scale salient dims before quan-
outliers tization
GPTQ Intra-channel weight Redistribute error via inverse
outliers Hessian
SmoothQuant Activation outliers Migrate magnitude to weights
(W8A8)
QuaRot/FlatQuant Mixed-dim activation Rotation spreads energy uni-
outliers formly
SpQR Most influential Store outliers in FP16, rest in
weight outliers INT4
EGBC Residual bias from all Correct first-moment shift after
sources rounding
33
Hook into Section 6
The question Section 5 leaves open
We have named the enemy and established the three levels of response.
The first battle is weight-only quantization: target W4A16, GPU deployment, online
serving (the memory-bound regime from Part 1). Activation outliers are sidestepped by
keeping X in FP16. The remaining challenge is weight outliers — intra-channel values
that dominate the per-group step size and cause excessive rounding error.
Section 6 covers the two dominant weight-only PTQ algorithms:
• GPTQ — correct the error after rounding by redistributing it to unquantized weights
via the inverse Hessian.
• AWQ — flatten the distribution before rounding by scaling salient weight dimensions
guided by activation magnitudes.
These are not competing methods — they address the same problem from opposite
directions, and they are composable: AWQ can be applied first, then GPTQ, then
EGBC.
Correcting after rounding vs. flattening before rounding — two complementary answers to the same
problem
34
6.2 GPTQ — Motivation
The NTR blind spot. Nearest-to-Round minimises each weight’s individual rounding
error, but ignores correlations: rounding wij introduces an error that propagates through the
output X ⊤ W , affecting the error contribution of all remaining unquantized weights.
OBQ per-channel problem. For column j, quantize weights wj,1 , wj,2 , . . . , wj,d one at a
time. After quantizing wj,i , update remaining weights via:
(wj,i − ŵj,i )
δwj,i′ = − · [Hj−1 ]ii′ ∀ i′ > i
[Hj−1 ]ii
Observation 1: All columns share the same Hessian. H = 2XX ⊤ ∈ Rd×d does not
depend on j. Compute and invert H once; reuse for all C output channels.
35
6.4 GPTQ — Intuition and Error Flow
quantized
current
unquantized (updated)
Key intuition. When weight i is rounded, the introduced error is “pushed forward” onto
weights i + 1, . . . , d in proportion to their Hessian coupling. Weights that are highly correlated
with i (large [H −1 ]ii′ ) receive a larger compensating update. The result: the overall layer
output error is minimised even though individual rounding errors are non-zero.
Strengths
• Captures weight correlations — the only weight-only method that explicitly models
how quantizing one weight affects others
• Strong accuracy at 4-bit, competitive at 3-bit
• Hardware-friendly output: standard per-group INT4, compatible with all fused
dequant-GEMM kernels
• Composable: can be applied after AWQ or other preprocessing
Weaknesses
• Calibration overfitting: the Hessian correction is fitted to the calibration set.
With only 128 samples, the correction can overfit to calibration distribution and
degrade on out-of-distribution inputs
• Heavier compute than AWQ: O(d2 ) per layer for the Hessian inversion (hours for
70B models)
• Does not address the first-moment bias E[(Wq − W )X] — EGBC can fix this residual
Practical note. GPTQ is implemented in the AutoGPTQ and ExLlamaV2 libraries. For a 70B
model, GPTQ quantization takes 4–8 hours on 4×A100. The resulting model is indistinguishable
from the FP16 baseline on most benchmarks at 4-bit per-group-128.
36
Saliency of weight wij :
Weights at input dimensions with large mean activation magnitude |µi | are salient —
their quantization error has a disproportionate effect on the output.
AWQ’s insight. Rather than protecting salient weights by storing them in higher
precision (as SpQR does), AWQ makes them easier to quantize accurately by rescaling the
corresponding input dimension before the quantization grid is applied. No architecture
change, no extra parameters, no sparse storage.
X ⊤ W = (X · diag(s)−1 ) · (diag(s) · W )
| {z } | {z }
X̃ W̃
How AWQ uses this. Choose si > 1 for salient dimensions (those with large |µi |):
• W̃i,: = si · Wi,: — the salient weight row is scaled up, compressing its dynamic range
relative to the (now larger) per-group maximum. Equivalently: the salient row occupies
more of the quantization grid — finer effective resolution.
• X̃:,i = X:,i /si — the activation dimension is scaled down, absorbed into the modified
weights. At inference, X̃ is the actual input to the quantized layer; the scale si is absorbed
offline into a preceding LayerNorm or stored as a per-channel correction.
2
s∗ = arg min X ⊤ W − X̃ ⊤ Q(W̃ ) F
s
37
In practice: grid search over a simple parameterisation. AWQ parameterises si = |µi |α
for α ∈ [0, 1]:
Why this is fast. No Hessian inversion. No gradient computation. The search over α
requires only ∼20 forward passes through the quantization operator — a few minutes
per layer even for the largest models. AWQ is typically 10×–20× faster than GPTQ.
scale
What the scaling achieves. By scaling the salient weight dimension up (and the
corresponding activation down by the inverse), the effective per-group step size for that
dimension becomes finer — more quantization levels cover the region where the salient
weights actually live. The output product XW = X̃ W̃ is unchanged.
GPTQ AWQ
38
They are composable, not competing
AWQ scales the weight matrix first (flattening outliers), then GPTQ applies error
redistribution on the scaled matrix, then EGBC corrects the residual first-moment bias.
Each method addresses a different layer of the problem. In practice, AWQ + GPTQ
together outperform either alone at 3-bit.
This format is directly consumed by the standard W4A16 fused dequant-GEMM kernel
described in Part 1, Section 7:
INT4 Wq
tile in unpack FP16 Ŵ FP16 MMA FP16
+ FP16 scales
shared mem registers Tensor Core output
HBM
Even after GPTQ or AWQ, the expected output of the quantized layer differs from the
expected output of the full-precision layer by this systematic bias.
• Softmax inputs are shifted — attention calibration is distorted.
• LayerNorm statistics change — normalisation is off.
• The bias compounds across layers.
This is the gap that Section 9 (EGBC) fills. EGBC treats bias correction as a
discrete selection problem: selectively flip quantized weights from ⌊·⌋ to ⌈·⌉ to drive
µ⊤ (Wq − W ) toward zero, per output channel, with negligible computational overhead.
EGBC is designed to be applied after GPTQ or AWQ as a lightweight post-processing
step.
39
6.13 Section Summary
Section 6 in five points
1. GPTQ quantizes weights column-by-column, redistributing each rounding error to
unquantized weights via the inverse Hessian. Strong accuracy, especially at 3-bit;
heavier compute; prone to calibration overfitting.
2. AWQ scales salient weight dimensions (those corresponding to large-magnitude acti-
vation inputs) before quantization, compressing their dynamic range and improving
per-group resolution. Fast, robust, and composable.
3. Both target the same format: per-group INT4 (W4A16), fully compatible with
the fused dequant-GEMM kernel ecosystem.
4. They are composable: AWQ scales first, GPTQ corrects second, EGBC removes
the residual bias third.
5. Neither addresses the first-moment bias µ⊤ (Wq − W ), which is the residual
left for Section 9 (EGBC) to correct.
7. Weight-Activation PTQ
When activations must also be quantized — migration, rotation, and the cost of going beyond W4A16
• Weights are loaded once but reused B times — bandwidth cost per token shrinks with B
• The compute units (Tensor Cores) become the bottleneck
40
• INT8 Tensor Cores deliver 2× the throughput of FP16
• To use INT8 Tensor Cores, both weights and activations must be in INT8
W8A8 pipeline:
INT8 TC MMA ×s s
acc −−−X−−
Xq × Wq −−−−−−−−−−→ |{z} W
→ |{z}
Y
|{z} |{z}
INT8 INT8 INT32 FP16
Weights Activations
The core insight shared by all W8A8 methods: rather than trying to quantize
the outlier activation dimensions accurately (which requires a very large clip range and
coarse grid), reduce their magnitude before quantization. The two approaches
differ in how they reduce it: migration (SmoothQuant) or rotation (QuaRot, FlatQuant).
41
X (activations) W (weights)
×
difficulty in X,normal weights
outlier dim not in W
The SmoothQuant idea. If the difficulty is in the activations but not the weights,
move it from activations to weights via a mathematically equivalent per-channel scaling.
The resulting activations are smooth (easy to quantize); the resulting weights are slightly
harder but still quantizable.
Y = XW = (X diag(s)−1 ) · (diag(s)W )
| {z } | {z }
X̃, smooth W̃ , absorbs outlier
Choose si > 1 for outlier dimension i: divides X:,i by si (reduces outlier magnitude)
and multiplies Wi,: by si (weight row absorbs the scale).
max |X:,i |α
si = , α ∈ [0, 1]
max |Wi,: |1−α
• α = 0: no migration — s = 1, original problem
• α = 0.5: split difficulty equally between X and W
• α = 1: full migration — all difficulty moves to weights
Optimal α is found by grid search over the calibration set, minimising the combined
quantization error of X̃ and W̃ . In practice α = 0.5 works well across most layers.
42
Inference graph is unchanged. The LayerNorm weight γ is modified offline (γ̃i =
γi /si ). The linear layer weight is modified offline (W̃i,: = si Wi,: , then quantized). At
inference: standard LayerNorm + standard INT8 linear — no extra ops, no per-token
scaling, no new parameters.
Limitation 2: The weight side gets harder. Migration moves difficulty from X to W .
If α is too large, the weight rows absorb too much outlier magnitude and become harder to
quantize than the original weights. The optimal α trades off these two difficulties — it never
eliminates both simultaneously.
Since the clip range is determined by ∥ · ∥∞ , rotation directly tightens the quantization
clip range.
43
7.8 Hadamard Rotation — Fast and Parameter-Free
The specific rotation used in QuaRot and FlatQuant.
The normalised Hadamard matrix Hd = √1 Hd where Hd is the d × d Walsh-Hadamard
d
matrix (entries ±1, orthogonal rows).
Why Hadamard?
Advantages
• Fast: O(d log d) via Fast Walsh-Hadamard Transform (vs O(d2 ) for general rotation)
• Fixed: no learned parameters, no calibration needed for R itself
• Uniform spreading: each output dimension receives equal contribution from all
inputs — theoretically optimal flattening
• Fused: can be computed as a single kernel fused with preceding LayerNorm
Limitations
• Requires d to be a power of 2 (padding needed otherwise)
• Fixed structure may leave some residual outlier patterns in pathological weight
matrices
• The inverse rotation R−1 = R⊤ must be applied to activations online — adds
O(d log d) per layer at inference
Random rotation is an alternative: draw R uniformly from the orthogonal group O(d). In
expectation this achieves the same flattening as Hadamard, and avoids pathological cases where
Hadamard leaves structure intact. Used in some ablation studies; Hadamard is preferred in
practice for its speed and reproducibility.
44
Why full d × d rotation is acceptable here
For weight-activation quantization of linear layers, the online cost is O(d log d) per token.
At d = 4096 and Hadamard, this is ∼ 49 000 operations vs ∼ 33 000 000 for the linear
layer itself — about 0.15% overhead. Fusing with LayerNorm eliminates even this.
Compare with KV cache rotation in Section 8, where the situation is different.
• Offline: rotate weights, apply SmoothQuant scaling, quantize to INT8 — all before
deployment, zero inference cost.
• Online: LayerNorm (with absorbed scale), Hadamard rotation (fused with LN), quantize
activations to INT8, INT8 Tensor Core MMA, rescale INT32 accumulator to FP16.
45
• Net effect: activations arrive at the quantization step with no dominant outlier dimensions
— INT8 uses its full 256 levels productively.
46
Hook into Section 8
The question Section 7 leaves open
Sections 6 and 7 have covered the quantization of model weights and layer activations —
the two components of every linear layer.
But at long context lengths (S ≳ 8192 tokens), a third memory bottleneck emerges that
neither section addresses: the KV cache.
Recall from Part 1, Section 3: at S = 100 000 tokens, the KV cache requires ∼210 GB —
six times the 35 GB of INT4 model weights. Quantizing only the model weights is no
longer sufficient; the KV cache has become the dominant bandwidth sink.
Section 8 treats KV cache quantization as a distinct sub-problem: why it is harder than
weight quantization, how rotation applies differently here, and the specific algorithms —
PolarQuant, QJL, TurboQuant — designed for this setting.
8. KV Cache Quantization
At long context, the cache overtakes the weights — a distinct sub-problem with its own algorithms
KV cache size = 2 · L · H · dh · S · B · w
L = layers, H = heads, dh = head dim, S = sequence length, B = batch, w = bytes per
value.
2 048 4 GB 35 GB Weights
8 192 17 GB 35 GB Weights
32 768 67 GB 35 GB KV cache
100 000 210 GB 35 GB KV cache (6× weights)
47
8.2 Why KV Cache Quantization Is Harder
When known Static – offline before de- Dynamic – new K/V com-
ployment puted every decode step
Clip range Calibrate once, stable Must generalise to all se-
quence lengths and all in-
put domains
Outlier pattern Per-channel, fixed Per-head, varies across
layers and positions
Sensitivity Rounding error in W af- Rounding error in K en-
fects output linearly ters softmax – exponen-
tial sensitivity
Scale storage Stored alongside weights Must be stored alongside
(offline) each KV entry (per-token
overhead)
FlashAttention Unaffected FlashAttention removed
attention-score HBM
cost; KV cache is remain-
ing bottleneck
√
The softmax sensitivity issue. Attention scores softmax(QK ⊤ / dh ) are exponen-
tially sensitive to Key values: a small shift in K can dramatically alter which tokens are
attended to. Key quantization is therefore harder than Value quantization – the two
often need different bit-widths or methods.
After FlashAttention. FlashAttention tiles the attention computation to keep the score
matrix in SRAM – it is never written to HBM. ← Part 1, S7 – Kernels & Fusion
KV cache quantization became an active research area after FlashAttention was widely adopted:
once the score-matrix bottleneck was eliminated, the cache itself became the next target.
48
8.4 Granularity – Per-Head and Per-Token Scales
Why per-tensor is insufficient for KV. Key and Value distributions vary significantly
across heads, layers, and sequence positions. A single global scale gives too coarse a grid.
Advantages in KV setting
• Full dh × dh rotation – more flexible than Hadamard
• Learned per-head R adapts to each head’s specific K/V distribution
• K and V can use independent rotations
• Storage overhead: negligible vs. cache at long context
49
Challenges
• Online cost: O(d2h ) per token per head when computing new K/V entries
• Query Q must also be rotated to preserve QK ⊤ : (QR)(RK)⊤ = QK ⊤
• Learned R requires calibration optimisation
• Rotation before quantization adds a kernel step to the attention prefill path
QJL procedure:
50
Procedure. Learn codebook C = {c1 , . . . , c2b } per head from calibration data. At each step:
Accuracy benefit. The codebook concentrates quantization levels where the K/V
distribution is dense (near zero), reducing expected quantization error vs. uniform INT4
at the same 4 bits. Same benefit as Section 2, now applied where the LUT overhead is
tolerable.
• Keys and Values have different outlier structures: Key outliers are primarily along the
channel dimension; Value outliers are primarily along the token dimension.
• Applies per-channel INT2 to Keys, per-token INT2 to Values.
• A small sliding-window “residual cache” keeps recent tokens in full precision; older tokens
are quantized.
• Achieves 2× memory reduction at INT2 with less than 1% degradation on most bench-
marks.
Key vs. Value asymmetry
Keys enter softmax (exponential sensitivity to channel-wise errors); Values are multiplied
by attention weights (linear sensitivity, tolerates per-token quantization). KIVI exploits
this asymmetry explicitly.
51
8.10 The KV Quantization Landscape
52
Hook into Section 9
The question Section 8 leaves open
Sections 6, 7, and 8 cover the three quantization targets: model weights (W4A16), layer
activations (W8A8), and the KV cache.
Each method minimises reconstruction error ∥X ⊤ (W − Ŵ )∥2F or distribution mismatch.
But none explicitly controls the first-order moment:
E (Wq − W )X = µ⊤ (Wq − W ) ̸= 0
This residual systematic bias shifts the expected output of every quantized layer –
distorting softmax calibration, LayerNorm statistics, and compounding across layers.
Section 9 introduces post-quantization correction: methods that treat the residual bias
as a discrete selection problem and fix it with minimal overhead. The centrepiece is
EGBC – positioned alongside AdaRound and BRECQ in the correction landscape.
9. Post-Quantization Correction
Fixing what rounding leaves behind — from bias absorption to discrete smart flipping
Key insight. GPTQ controls the variance of the output error (second-order moment).
Correction methods control the mean of the output error (first-order moment). Both
are needed for a well-calibrated quantized model.
53
Sources of non-zero activation mean:
• LayerNorm with learned bias: γ x̂ + β — the additive offset β shifts the distribution
away from zero.
• Residual stream accumulation: the residual connection adds each layer’s output to a
running sum; the sum develops a non-zero mean over depth.
• Activation functions: SiLU and GeLU are not zero-centred — their outputs have a
positive mean for typical inputs.
• Outlier dimensions: the structural outlier dimensions identified in Section 5 have
persistently large |µi |, contributing the most to µ⊤ ∆W .
bcorrected
j = bj + µ⊤ (wj − ŵj ) = bj − µ⊤ ∆wj
where bj is the bias for output channel j and ∆wj = ŵj − wj is the quantization error
in column j. After correction: E[yq,j ] = E[yj ] for each channel.
Strengths
• Closed-form — no optimisation
• Negligible compute cost
• Exact first-moment alignment per output channel
• Works for any quantization scheme as a post-step
Critical limitation
• Requires an explicit bias parameter bj in the layer
• Modern LLMs (LLaMA, Mistral, Phi, Falcon) are bias-less by design — no bias in
MLP or attention projections
• Adding a new bias parameter breaks optimised kernels and architectural symmetry
• “Hides” the error rather than correcting the weights
54
Optimisation objective (per layer):
2
X
min X ⊤ (W − Ŵδ ) F
+λ h(δi )
δ∈[0,1]n
i
where Ŵδ = s (⌊W/s⌋ + δ), δi ∈ [0, 1] is a continuous relaxation of the binary rounding
decision (δi = 0: floor, δi = 1: ceil), and h(δi ) is a regulariser that drives δi toward 0 or
1 (binary).
Training procedure. Initialise δi = ⌈wi /s⌉ − wi /s (distance to ceiling). Minimise via SGD
with STE through the binary projection. Anneal λ to force binary decisions at convergence.
What AdaRound achieves. By optimising the rounding decisions jointly over the
calibration set, AdaRound can choose a pattern of floors and ceilings that minimises the
layer output error rather than the individual weight errors. This is a stronger objective
than NTR and produces significantly better accuracy at 4-bit and 3-bit.
Strengths
• Directly optimises layer output error — the right objective
• Works for bias-less architectures: no new parameters, just different rounding decisions
• Strong accuracy at 4-bit and especially 3-bit
• Generalises beyond NTR: any rounding pattern is reachable
Weaknesses
• SGD per layer: thousands of gradient steps for each linear layer
• For a 70B model with ∼800 linear layers: days of compute on 8×A100
• Impractical for rapid deployment cycles
• Optimises reconstruction error (second moment) — does not explicitly target the
bias (first moment)
Practical note. AdaRound is widely used for small models (CNNs, 1–7B transformers) where
per-layer SGD takes minutes not days. For large LLMs (≥13B), it is typically replaced by GPTQ
(which achieves similar quality via the Hessian approach without SGD) or EGBC (which corrects
the bias at negligible cost).
55
Block reconstruction objective. Instead of minimising per-layer output error:
2
min fblock (X; W ) − fblock (X; Ŵδ ) F
δℓ
where fblock is the output of a contiguous block of k layers (e.g. one transformer block:
attention + FFN).
Why block-wise matters. Per-layer correction (AdaRound) ignores how quantization error
in layer ℓ propagates to layer ℓ + 1. Block-wise correction allows rounding decisions in earlier
layers to partially compensate for errors they introduce in later layers.
Disadvantage
• Even heavier compute than AdaRound: larger optimisation problem per block
• Completely impractical for 70B+ models without massive compute
Can we correct the systematic bias µ⊤ (Wq − W ) in bias-less LLM architectures without
gradient computation, without new parameters, and with negligible computational cost?
The EGBC insight. For any quantized weight ŵij , there are exactly two candidate discrete
levels: ⌊wij /s⌋ (floor) and ⌈wij /s⌉ (ceiling). NTR always picks the closer one. But a strategic
flip to the adjacent level — guided by the activation mean µ — can reduce the per-channel
bias µ⊤ (Wq − W ) without solving any continuous optimisation problem.
56
C
2 2
X
⊤
Lbias (Wq ) = µ (Wq − W ) 2
= µ⊤ (wq,j − wj )
j=1
| {z }
b2j
Each channel is independent — the loss decomposes into C independent per-channel scalar
problems.
Effect of a single flip. Flipping weight wq,ij from its current level to the adjacent level
changes wq,ij by ±sj (the per-channel step size). This changes bj by:
bj −→ bj ± µi sj
∆Lbias,j = (bj ± µi sj )2 − b2j = ±2bj µi sj + µ2i s2j
Choosing the sign that reduces |bj | gives ∆Lbias,j = −2|bj ||µi |sj + µ2i s2j , which is negative
(beneficial) precisely when 2|bj | > |µi |sj .
1. Knee-point masking: sort dimensions by |µi | descending; detect the “elbow” in the
magnitude profile via a maximum-distance-to-chord criterion. Dimensions above the knee
(outliers) are excluded from flipping.
2. Budget constraint: at most p% of eligible weights per output channel are flipped
(default p = 1%), limiting local quantization distortion.
An outlier dimension |µi | ≫ 2|bj |/sj produces a flip step that overshoots the target,
worsening the bias. The knee-point detects where “high magnitude” ends and “moderate
magnitude” begins — the effective flipping regime.
57
X
min bj − vj,i s.t. |S| ≤ Bj
S⊆Ij
i∈S
EGBC’s greedy solution. Rather than searching all subsets (exponential), restrict to prefix
subsets ordered by distance to the rounding boundary (weights closer to the midpoint
between floor and ceiling are cheaper to flip — smaller local distortion):
Cost: O(|Ij | log |Ij |) sort + O(|Ij |) scan per channel. Total: negligible relative to the
preceding quantization step.
Why the sample mean is problematic. When d is large (4096, 8192) and m is small
(128), x̄ is noisy:
• Noisy extreme values incorrectly label many dimensions as “outliers” in the knee-point
detection, causing the masking to exclude good flipping candidates.
• Noisy µi values give wrong flip signs, worsening rather than improving bj .
For d ≥ 3, James-Stein shrinkage is known to reduce mean-squared estimation error vs. the
sample mean — shrinking noisy extreme coordinates toward a common centre, giving more
reliable flip decisions under limited calibration data.
58
9.12 EGBC — Position in the Correction Landscape
EGBC post-processing
Greedy flip
Deploy
per channel
INT4 model
update Wq
Composability. EGBC is a drop-in post-step. The same INT4 quantized weights, same
per-group scales — only selected integer values are changed by ±1. All existing fused
dequant-GEMM kernels work unchanged.
59
9.14 Section Summary
Section 9 in five points
The practical challenge: given a specific hardware target and deployment scenario, which
combination of these methods should be used? The answer requires mapping hardware
constraints (from Part 1) to algorithm choices (from Part 2).
Section 10 closes the loop: an Algorithm × Hardware matrix, a decision flowchart
companion to Part 1’s synthesis, and the three algorithm-design principles that mirror
Part 1’s three hardware constraints.
60
10.1 What Part 2 Has Built
The journey so far
The unifying question of Section 10: given a target device, deployment scenario,
and context length – which combination of algorithms should you use? The answer
comes directly from the hardware constraints established in Part 1.
Most production pipelines combine all three: flatten first (AWQ or SmoothQuant), correct second
(GPTQ or EGBC), and match granularity to the target device throughout.
61
10.3 Algorithm × Hardware Matrix
Read each column top-to-bottom as the recommended pipeline for that regime. Rows are not
mutually exclusive – flatten + correct is the standard combination. Colour coding: blue =
GPTQ family, green = AWQ family, purple = rotation/migration, orange = KV methods,
red = correction.
Yes
B < B∗?
Yes (mem-bound) No (comp-bound)
GPU or NPU?
GPU NPU
S > 32K?
No Yes
62
10.5 Reading the Flowchart
Gate 1 – Does the model fit? If not, quantization is mandatory and the minimum
bit-width that achieves the required footprint must be chosen first. No accuracy argument
overrides a hard memory constraint.
Gate 3 – GPU or NPU? GPU: per-group INT4 (scales applied in registers, free). NPU:
per-channel INT8 or INT4 if natively supported; per-group scales disrupt the systolic array
pipeline. ← Part 1, S6 – Compute Architecture
Gate 4 – Is context length > 32K? Yes: add a KV cache quantization method from
Section 8. No: per-head INT8 for KV is sufficient at short context.
After the flowchart. The flowchart identifies the type of quantization required. Within
that type, the algorithm choice (GPTQ vs. AWQ vs. SmoothQuant) is determined by
accuracy requirements, calibration budget, and composability preferences – all covered
in Sections 6–9.
scales Wq Wq
AWQ s GPTQ corrected EGBC debiased Deploy
flatten saliency Hessian correction bias correction INT4 kernel
128 calibration
samples
63
Why EGBC is less critical in W8A8
EGBC corrects the first-moment bias µ⊤ (Wq − W ). In W8A8 at INT8 (256 levels), the
step size s is much finer than at INT4 (16 levels), so the absolute magnitude of the
residual bias is smaller. EGBC still helps but the benefit is smaller than at INT4.
SmoothQuant + rotation already do most of the work.
The two parts are orthogonal axes. Part 1 identifies the type of quantization the
hardware requires. Part 2 identifies the algorithms that minimise accuracy loss within
that type. Both must be right for a deployment to succeed. Getting the hardware axis
wrong (wrong bit-width, wrong granularity) wastes all the accuracy work done by the
algorithm axis.
64
10.9 Common Mistakes — and How to Avoid Them
Per-tensor clip range for One outlier destroys Always use per-
LLMs resolution for 99% channel minimum;
of weights per-group pre-
ferred
Min-max clip range Coarse step size; ex- Use MSE minimi-
cessive rounding er- sation; allow delib-
ror for bulk values erate clipping
These topics build directly on the hardware model (Part 1) and algorithm landscape (Part 2)
established here. The mental model you have built – roofline, three levers, flatten/correct/match
– transfers directly.
65
10.11 Part 2 in Ten Sentences
The complete picture
1. Uniform quantization maps floats to integers via a scale and zero-point; per-group granularity
gives the best accuracy-efficiency trade-off on GPU.
2. Non-uniform (codebook) quantization concentrates bins where data is dense; better accuracy
per bit but requires LUT dequantization.
3. The clip range must be calibrated before any algorithm runs; MSE minimisation on 128
calibration samples is the standard.
4. QAT (with STE) trains through quantization for best accuracy; PTQ applies quantization
post-hoc with no gradients.
5. Outliers – structural, persistent, up to 100× typical in activations – are the central obstacle
to accurate quantization.
6. W4A16: AWQ flattens weight saliency; GPTQ corrects reconstruction error; EGBC removes
residual bias.
7. W8A8: SmoothQuant migrates activation outliers to weights; QuaRot/FlatQuant spreads
them via Hadamard rotation.
8. At long context (S > 32K), the KV cache dominates; KIVI, KVQuant, PolarQuant, and
QJL address this distinct sub-problem.
9. Post-quantization correction (AdaRound, EGBC) fixes the first-moment bias µ⊤ (Wq − W )
left by all rounding methods.
10. Hardware determines the design space; algorithms populate it. Both axes must be right.
Thank You
The three levers.[0.5em] Flatten the distribution before rounding. Correct the error
after rounding. Match granularity to the hardware datapath.
66