The roofline lesson told us what quantisation buys: weight-only INT4 cuts bytes 4× and helps decode below its (now 4× smaller) critical batch; W8A8 FP8 doubles both the memory-bound and the compute-bound rate; KV quantisation attacks long-context decode. This lesson is about what it costs — where the error comes from, and the methods and formats that keep it small. It ends with the case that matters most for post-training: running RL rollouts in low precision while the trainer stays in BF16.
Uniform quantisation and why outliers hurt
Symmetric -bit quantisation of a group of values with scale :
The rounding error is roughly uniform on , variance . For values with standard deviation , the signal-to-quantisation-noise ratio is
Each extra bit buys 6 dB; each doubling of the crest factor costs 6 dB — one bit. A single outlier 30σ out in a group costs about 3 bits for everybody else in that group. Every method in this lesson is a way of keeping small where it matters: smaller groups (more scales, or extra bits per value), floating-point elements (relative rather than absolute error), or transforms that move or spread the outliers.
Formats: FP8, MX and NVFP4
FP8. E4M3 (bias 7, max 448, no infinities, one NaN pattern) and E5M2 (bias 15, max 57,344, IEEE-like). A float’s error is relative, about of the value, so a large crest factor matters much less than for integers; E4M3 has more precision, E5M2 more range (it is usually reserved for gradients). FP8 still needs a scale to map the tensor’s range onto the format’s.
Microscaling (MX). The OCP MX formats share one scale per block of 32 elements, and the scale is a power of two (E8M0). MXFP4 elements are E2M1: the magnitudes . Small blocks localise outliers; a power-of-two scale is cheap but can waste up to almost one binade of the element range.
NVFP4. Blocks of 16 E2M1 values, each with an E4M3 scale, plus one FP32 scale per tensor so the block scales fit E4M3’s range — 4.5 bits per value. Half the block size and a finer scale than MXFP4. NVIDIA reports about 1% or less accuracy loss from FP8 for DeepSeek-R1-0528 in NVFP4.
roofline 레슨은 양자화가 무엇을 사 주는지 말했다. weight-only INT4는 바이트를 4배 줄여 (이제 4배 작아진) critical batch 아래의 decode를 돕고, W8A8 FP8은 memory-bound와 compute-bound 속도를 모두 두 배로 하며, KV 양자화는 긴 문맥 decode를 공략한다. 이 레슨은 그 비용에 대한 것이다. 오차가 어디서 오는지, 그것을 작게 유지하는 방법과 형식은 무엇인지. 마지막은 사후학습에 가장 중요한 경우, 즉 trainer는 BF16으로 두고 RL rollout을 저정밀로 돌리는 경우다.
균일 양자화와 outlier가 아픈 이유
scale 로 값 묶음을 대칭 비트 양자화하면
반올림 오차는 대략 위의 균등분포, 분산 다. 표준편차 인 값들의 신호 대 양자화 잡음비는
이다. 비트 하나가 6 dB를 사고, crest factor 가 두 배가 될 때마다 6 dB, 즉 비트 하나를 잃는다. 묶음 안에 30σ짜리 outlier 하나가 있으면 나머지 모두가 약 3비트를 잃는다. 이 레슨의 모든 방법은 중요한 곳에서 를 작게 유지하는 방법이다. 더 작은 그룹(scale이 늘어 값당 나 비트 추가), 부동소수점 원소(절대 오차가 아니라 상대 오차), outlier를 옮기거나 퍼뜨리는 변환.
형식: FP8, MX, NVFP4
FP8. E4M3(bias 7, 최댓값 448, 무한대 없음, NaN 패턴 하나)과 E5M2(bias 15, 최댓값 57,344, IEEE식). float의 오차는 상대적이어서 값의 약 이므로, 정수보다 crest factor의 영향이 훨씬 작다. E4M3는 정밀도가, E5M2는 범위가 더 크다(E5M2는 보통 gradient용). FP8도 tensor의 범위를 형식의 범위에 맞추는 scale이 필요하다.
Microscaling(MX). OCP MX 형식은 원소 32개 블록마다 scale 하나를 공유하고, scale은 2의 거듭제곱(E8M0)이다. MXFP4 원소는 E2M1, 크기 이다. 작은 블록은 outlier를 국소화한다. 2의 거듭제곱 scale은 싸지만 원소 범위를 거의 한 binade까지 낭비할 수 있다.
NVFP4. E2M1 값 16개 블록마다 E4M3 scale 하나, 그리고 블록 scale이 E4M3 범위에 들어가도록 tensor당 FP32 scale 하나. 값당 4.5비트다. MXFP4보다 블록이 절반이고 scale이 더 촘촘하다. NVIDIA는 DeepSeek-R1-0528을 NVFP4로 했을 때 FP8 대비 정확도 손실이 약 1% 이하라고 보고한다.
Things to try: set outliers to 0. The formats do not line up on one “bits × 6 dB” line. INT8 per-tensor reads 40.2 dB, which is the formula above with this tensor’s crest factor of 4.3: . A floating format’s error is relative, so its SQNR is set by the mantissa bits — about 6 dB per mantissa bit plus a constant (roughly 13–14 dB here) — not by the total bit count: E4M3 (3 mantissa bits) reads 31.9 dB and E5M2 (2 mantissa bits) 25.5 dB although both are 8 bits, and the E2M1 formats (1 mantissa bit) land at 18.5 dB (MXFP4) and 20.5 dB (NVFP4). So on well-behaved weights FP8 E4M3 is worse than INT8 per-tensor: it spends bits on exponent range the tensor does not need. Now, with the default 8 outliers, raise the multiplier to ×50. The slider multiplies each chosen weight by that factor, so an outlier ends at 50 times its own value, not at a fixed 50σ (the one in block 0 lands at −24.7σ). INT8 per-tensor drops by ~20 dB (to 20.1 dB) while E4M3 loses nothing (34.9 dB — the outliers add signal power); among the 4-bit formats INT4 group-128 loses the most (18.4 → 15.1 dB), the 32-blocks lose 1–2 dB, and NVFP4’s 16-blocks lose nothing. Pick MXFP4 and look at the top panel: the block’s scale was rounded up to a power of two, so the largest grid point overshoots the largest weight and part of the 8-value grid is unused.
Weight-only post-training quantisation
The layer-wise objective: find quantised minimising the output error on calibration inputs ,
Each output row is an independent quadratic problem with the same Hessian (input dimension × input dimension).
GPTQ: quantise one weight, compensate with the rest. From Optimal Brain Surgeon: if we fix weight of a row to its quantised value, the best adjustment of the remaining weights solves subject to . The Lagrangian gives
The error of one weight is pushed onto the not-yet-quantised weights along the directions the inputs are correlated. GPTQ’s engineering makes this feasible at scale: quantise columns in a fixed order for all rows at once (greedy ordering gains little), so all rows share one sequence of updates; read those updates off a Cholesky factor of instead of re-inverting; update in lazy blocks of 128 columns to stay compute-bound; and add a damping of 1% of the mean diagonal to . The paper quantises 175B-parameter models to 3–4 bits in about four GPU hours.
AWQ: protect the weights that see large activations. Only 0.1–1% of weight channels are salient, and they are found by activation magnitude, not weight magnitude. Instead of keeping them in FP16 (mixed precision is hardware-unfriendly), scale input channel of up by and the corresponding activation down by — the product is unchanged. The quantisation step of a group barely changes when one channel grows, so that channel’s relative error drops by about . AWQ uses with the per-channel mean activation magnitude and grid-searches on the calibration set. In the paper’s OPT-6.7B ablation, scaling salient channels by 2 cut perplexity from 23.54 to 11.92. AWQ received the MLSys 2024 best paper award.
Activations: outliers and SmoothQuant
Weights are well-behaved; activations are not. LLM.int8() found that from about 6.7B parameters, a few hidden dimensions carry systematic outliers (magnitude ≥ 6, recurring across layers); it routed those ~0.1% of dimensions through a 16-bit matmul. SmoothQuant observed outliers ~100× larger than typical values, concentrated in a few channels — which per-tensor or per-token activation scales cannot isolate, but per-channel weight scales can. So migrate the range: with ,
splits the difficulty between activations and weights; was a well-balanced point for OPT and BLOOM, for GLM-130B. The scales fold into the previous LayerNorm/linear offline, so W8A8 runs at full INT8 speed: up to 1.56× speedup and 2× memory reduction. Rotations go further: multiplying by an orthogonal (e.g. Hadamard) matrix leaves the product unchanged but spreads an outlier channel across all channels. QuaRot uses this for 4-bit weights, activations and KV; SpinQuant learns the rotations; FlashAttention-3’s incoherent processing and NVIDIA’s NVFP4 pretraining recipe use random Hadamard transforms for the same reason.
해 볼 것: outlier를 0으로 두라. 형식들은 “비트 × 6 dB” 한 선 위에 늘어서지 않는다. per-tensor INT8은 40.2 dB인데, 위 식에 이 텐서의 crest factor 4.3을 넣은 값 이다. 부동소수점 형식은 오차가 상대적이라 SQNR을 정하는 것이 전체 비트 수가 아니라 가수 비트다. 가수 비트 하나에 약 6 dB, 여기에 상수(여기서는 약 13–14 dB)가 더해진다. 둘 다 8비트인데 E4M3(가수 3비트)는 31.9 dB, E5M2(가수 2비트)는 25.5 dB이고, E2M1 형식(가수 1비트)은 18.5 dB(MXFP4)와 20.5 dB(NVFP4)다. 그래서 얌전한 가중치에서는 FP8 E4M3가 per-tensor INT8보다 나쁘다. 텐서에 필요 없는 지수 범위에 비트를 쓰기 때문이다. 이제 기본값 outlier 8개에서 배율을 ×50으로 올려 보라. 슬라이더는 고른 가중치 각각에 그 배율을 곱하므로, outlier는 고정된 50σ가 아니라 자기 값의 50배에 놓인다(블록 0의 것은 −24.7σ). per-tensor INT8은 ~20 dB 떨어지는데(20.1 dB) E4M3는 잃는 것이 없다(34.9 dB. outlier가 신호 전력을 보탠다). 4비트 형식 중에서는 INT4 group-128이 가장 많이 잃고(18.4 → 15.1 dB), 32 블록은 1–2 dB를 잃으며, NVFP4의 16 블록은 잃지 않는다. MXFP4를 골라 위 패널을 보라. 블록 scale이 2의 거듭제곱으로 올림되어 격자의 가장 큰 점이 가장 큰 가중치를 넘어서고, 8값 격자의 일부가 쓰이지 않는다.
Weight-only 사후 양자화
층 단위 목적함수: calibration 입력 에서 출력 오차를 최소화하는 양자화된 를 찾는다.
출력 행 하나하나가 같은 Hessian (입력 차원 × 입력 차원)를 가진 독립적인 이차 문제다.
GPTQ: 가중치 하나를 양자화하고 나머지로 보정한다. Optimal Brain Surgeon에서: 행의 가중치 를 양자화된 값으로 고정하면, 나머지 가중치의 최적 조정 는 제약 아래 를 푼다. 라그랑지안에서
가 나온다. 가중치 하나의 오차가 입력들이 상관된 방향을 따라 아직 양자화하지 않은 가중치로 밀려난다. GPTQ의 공학이 이것을 큰 규모에서 가능하게 한다. 모든 행에 대해 고정된 순서로 열을 한꺼번에 양자화하고(greedy 순서의 이득은 작다), 그래서 모든 행이 갱신 순서 하나를 공유한다. 그 갱신은 매번 역행렬을 다시 구하는 대신 의 Cholesky 인수에서 읽는다. compute-bound를 유지하려고 128열 lazy block으로 갱신하고, 에 대각 평균의 1%를 damping으로 더한다. 논문은 175B 모델을 GPU 약 4시간에 3–4비트로 양자화한다.
AWQ: 큰 활성값을 보는 가중치를 보호한다. 중요한 가중치 channel은 0.1–1%뿐이고, 가중치 크기가 아니라 활성값 크기로 찾는다. 그것들을 FP16으로 남기는 대신(혼합 정밀도는 하드웨어에 불리하다) 의 입력 channel 를 배로 키우고 해당 활성값을 로 줄인다. 곱은 그대로다. channel 하나가 커져도 그룹의 양자화 간격은 거의 변하지 않으므로, 그 channel의 상대 오차는 약 로 준다. AWQ는 를 channel별 평균 활성값 크기로 두고 를 쓰며, calibration 집합에서 를 격자 탐색한다. 논문의 OPT-6.7B ablation에서 중요한 channel을 2배로 scaling하자 perplexity가 23.54에서 11.92로 떨어졌다. AWQ는 MLSys 2024 best paper를 받았다.
활성값: outlier와 SmoothQuant
가중치는 얌전하고 활성값은 그렇지 않다. LLM.int8()은 약 6.7B 매개변수부터 몇몇 hidden 차원이 체계적인 outlier(크기 ≥ 6, 층을 가로질러 반복)를 가진다는 것을 발견하고, 그 ~0.1% 차원을 16비트 행렬곱으로 보냈다. SmoothQuant는 outlier가 보통 값보다 ~100배 크고 소수의 channel에 몰려 있음을 관찰했다. per-tensor나 per-token 활성값 scale로는 격리할 수 없지만 channel별 가중치 scale로는 할 수 있다. 그러니 범위를 옮긴다. 로 두고
가 어려움을 활성값과 가중치에 나눈다. OPT와 BLOOM에서는 가, GLM-130B에서는 가 균형점이었다. scale은 오프라인으로 앞의 LayerNorm/선형층에 접혀 들어가므로 W8A8이 온전한 INT8 속도로 돈다. 최대 1.56배 속도, 2배 메모리 절감. 회전은 한 걸음 더 간다. 직교행렬(예: Hadamard)을 곱하면 곱은 그대로이고 outlier channel 하나가 모든 channel로 퍼진다. QuaRot은 이것으로 가중치·활성값·KV를 4비트로 하고, SpinQuant는 회전을 학습한다. FlashAttention-3의 incoherent processing과 NVIDIA의 NVFP4 사전학습 레시피도 같은 이유로 무작위 Hadamard 변환을 쓴다.
Things to try: at 3 bits with 20× outliers AWQ cuts RTN’s error by about 40%, because the error is dominated by the four outlier channels it protects; GPTQ helps less in this tiny layer (only 64 input columns to spread each error over — in the larger NumPy layer below it gains more). At 8 bits all three coincide (nothing to fix). Set the outlier scale to 1: AWQ’s best α drops to ~0 (no salient channels to protect) and SmoothQuant gains nothing. Raise it to 60: naive W8A8 grows with the outliers while SmoothQuant near α ≈ 0.5–0.75 stays flat. GPTQ is evaluated on its own calibration data here; with held-out inputs its advantage shrinks somewhat.
Low-precision rollouts in RL
Rollout generation dominates RL step time, so running the sampler in FP8 or 4 bits is attractive — but the sampler then follows a slightly different policy , and the weights change every step.
FP8 rollout. FP8-RL (implemented in verl) runs the rollout’s linear layers in blockwise FP8 W8A8 — following DeepSeek-V3, 128×128 blocks for weights and 1×128 tiles for activations — and keeps the router, embeddings and LM head in BF16. Because the policy changes every step, the trainer re-quantises its BF16 weights to the inference checkpoint’s FP8 block format at every weight sync (the PyTorch block below is exactly that conversion). The KV cache can also be FP8, with the Q/K/V scales recalibrated every step. The extra mismatch is absorbed by token-level importance-sampling correction (TIS/MIS, see off-policy mismatch); verl’s documentation reports an obvious accuracy drop without it. Reported gains: up to 44% rollout throughput in the paper; in verl’s docs ~12–18% for Qwen3-8B and over 35% for Qwen3-30B-A3B.
4-bit rollout with QAT. At 4 bits post-training quantisation drifts too far, so the trainer is made to see the quantisation: its forward pass uses fake-quantised weights (quantise–dequantise), the backward uses the straight-through estimator on BF16 master weights, and the rollout engine runs the real low-bit kernels on the same grid. Kimi K2 Thinking is the public precedent: INT4 weight-only quantisation of the MoE components with QAT in post-training, for a roughly 2× generation speed-up in low-latency mode; the reason given is that long thinking traces make post-training quantisation degrade. An LMSYS reproduction (Megatron fake quantisation, SGLang INT4 W4A16 kernels, 1×32 groups) found the train–rollout log-prob gap almost identical to BF16 and clearly below FP8 rollout, with the main win being memory: the rollout fits on one node. NeMo RL’s quantisation-aware RL does the same for NVFP4: W4A16 converges under GRPO, while W4A4 still has known convergence issues.
The code below measures the mismatch on a toy LM head: KL between the BF16 policy and its quantised copy, and the range of the per-token ratio on tokens sampled by the quantised policy — the quantity an IS correction has to clip.
Implementing it
import numpy as np
rng = np.random.default_rng(0)
# --- number formats -------------------------------------------------------------------------
def fp_round(x, m_bits, emin, maxval):
"""Round to a minifloat with m_bits mantissa bits, min normal exponent emin, saturating at maxval."""
a = np.minimum(np.abs(x), maxval)
e = np.floor(np.log2(np.maximum(a, 1e-30)))
step = 2.0 ** (np.maximum(e, emin) - m_bits) # subnormals share the emin step
return np.sign(x) * np.minimum(np.round(a / step) * step, maxval)
e4m3 = lambda x: fp_round(x, 3, -6, 448.0) # FP8 E4M3 (bias 7, max 448)
e5m2 = lambda x: fp_round(x, 2, -14, 57344.0) # FP8 E5M2 (bias 15, max 57344)
e2m1 = lambda x: fp_round(x, 1, 0, 6.0) # FP4 E2M1: 0, .5, 1, 1.5, 2, 3, 4, 6
print("E2M1 grid:", np.unique(np.abs(e2m1(np.linspace(-7, 7, 2001)))))
# np.round is round-half-to-even (IEEE default); the figure uses the same rule. Midpoints go to the even neighbour:
print("ties to even: e4m3(1.0625) =", e4m3(1.0625), "(not 1.125); e2m1(0.25) =", e2m1(0.25), "(not 0.5)")
def int_sym(x, bits, axis=None):
s = np.abs(x).max(axis=axis, keepdims=True) / (2 ** (bits - 1) - 1)
return np.round(x / s) * s
def grouped(x, g, f): # f sees rows of g consecutive values
return f(x.reshape(-1, g)).reshape(x.shape)
amax = lambda c: np.maximum(np.abs(c).max(axis=1, keepdims=True), 1e-12) # all-zero block -> no 0/0
def mxfp4(x): # 32-value blocks, power-of-two (E8M0) scale
return grouped(x, 32, lambda c: e2m1(c / (s := 2.0 ** np.ceil(np.log2(amax(c) / 6)))) * s)
def nvfp4(x): # 16-value blocks, E4M3 scale, FP32 tensor scale
g = np.abs(x).max() / (6 * 448)
# clamp the block scale to the smallest positive E4M3 (2^-9): a tiny block would round it to 0 -> NaN
return grouped(x, 16, lambda c: e2m1(c / (s := np.maximum(e4m3(amax(c) / 6 / g), 2.0 ** -9) * g)) * s)
def sqnr(x, q): return 10 * np.log10((x ** 2).sum() / ((x - q) ** 2).sum())
w = rng.normal(size=4096) * 0.02
w[rng.choice(4096, 8, replace=False)] *= 30 # a few outlier weights
fmts = {"INT8 per-tensor (8)": int_sym(w, 8), "FP8 E4M3 per-tensor (8)": e4m3(w / (np.abs(w).max() / 448)) * (np.abs(w).max() / 448),
"FP8 E5M2 per-tensor (8)": e5m2(w / (np.abs(w).max() / 57344)) * (np.abs(w).max() / 57344),
"INT4 group-128 (4.125)": grouped(w, 128, lambda c: int_sym(c, 4, axis=1)), "INT4 group-32 (4.5)": grouped(w, 32, lambda c: int_sym(c, 4, axis=1)),
"MXFP4 (4.25)": mxfp4(w), "NVFP4 (4.5)": nvfp4(w)}
print("\nSQNR on weights with outliers (format, bits/value):")
for k, q in fmts.items(): print(f" {k:<26} {sqnr(w, q):5.1f} dB")
# --- weight-only methods on one linear layer ------------------------------------------------------
d_in, d_out, n = 256, 128, 512
X = rng.normal(size=(n, d_in)); X[:, :4] *= 20 # 4 outlier activation channels
W = rng.normal(size=(d_out, d_in)) / np.sqrt(d_in)
Y = X @ W.T
err = lambda Wq: np.linalg.norm(X @ Wq.T - Y) / np.linalg.norm(Y)
rtn = lambda W, b: int_sym(W, b, axis=1) # per-output-channel symmetric
def gptq(W, X, bits, damp=0.01):
H = 2 * X.T @ X
H += damp * np.mean(np.diag(H)) * np.eye(len(H)) # 1% of the mean diagonal
U = np.linalg.cholesky(np.linalg.inv(H)).T # upper Cholesky factor of H^-1
Wc, Q = W.copy(), np.zeros_like(W)
scale = np.abs(W).max(axis=1) / (2 ** (bits - 1) - 1) # grid fixed from the original weights
for i in range(W.shape[1]): # quantise input column i ...
Q[:, i] = np.clip(np.round(Wc[:, i] / scale), -(2 ** (bits - 1) - 1), 2 ** (bits - 1) - 1) * scale
e = (Wc[:, i] - Q[:, i]) / U[i, i]
Wc[:, i + 1:] -= np.outer(e, U[i, i + 1:]) # ... and push its error onto the later columns
return Q
def awq(W, X, bits):
sx = np.abs(X).mean(axis=0)
best = None
for a in np.linspace(0, 1, 11): # grid search alpha in [0, 1]
s = sx ** a; s /= np.sqrt(s.max() * s.min())
e = np.linalg.norm((X / s) @ rtn(W * s, bits).T - Y) / np.linalg.norm(Y)
if best is None or e < best[0]: best = (e, a)
return best
print("\nweight-only, relative output error ||XW^T - XQ^T|| / ||XW^T||:")
for bits in [4, 3]:
e_awq, a = awq(W, X, bits)
print(f" W{bits}: RTN {err(rtn(W, bits)):.4f} AWQ {e_awq:.4f} (alpha={a:.2f}) GPTQ {err(gptq(W, X, bits)):.4f}")
# --- W8A8: activation outliers and SmoothQuant -------------------------------------------------
def w8a8(X, W, alpha=None):
if alpha is not None:
s = np.abs(X).max(0) ** alpha / np.abs(W).max(0) ** (1 - alpha)
X, W = X / s, W * s # X diag(s)^-1 . diag(s) W^T: same product
return np.linalg.norm(int_sym(X, 8) @ int_sym(W, 8, axis=1).T - Y) / np.linalg.norm(Y)
print(f"\nW8A8 per-tensor activations: naive {w8a8(X, W):.4f} " + " ".join(f"SmoothQuant a={a} {w8a8(X, W, a):.4f}" for a in [0.25, 0.5, 0.75]))
# --- low-precision rollout: how far does the quantised policy drift? -----------------------------
V, Hd = 2048, 128
Wlm = rng.normal(size=(V, Hd)) / np.sqrt(Hd) * 3
h = rng.normal(size=(64, Hd))
def logp(Wm):
z = h @ Wm.T; z -= z.max(1, keepdims=True); return z - np.log(np.exp(z).sum(1, keepdims=True))
def fp8_block(Wm, b=128): # 128x128 blocks, E4M3 values + one scale per block
Q = np.empty_like(Wm)
for i in range(0, Wm.shape[0], b):
for j in range(0, Wm.shape[1], b):
blk = Wm[i:i + b, j:j + b]; s = np.abs(blk).max() / 448
Q[i:i + b, j:j + b] = e4m3(blk / s) * s
return Q
lp = logp(Wlm)
for name, Wq in [("FP8 128x128 blocks", fp8_block(Wlm)), ("NVFP4", nvfp4(Wlm.ravel()).reshape(Wlm.shape)),
("INT4 group-32", grouped(Wlm.ravel(), 32, lambda c: int_sym(c, 4, axis=1)).reshape(Wlm.shape))]:
lq = logp(Wq); p = np.exp(lp)
kl = (p * (lp - lq)).sum(1).mean()
y = np.array([rng.choice(V, p=np.exp(r)) for r in lq]) # tokens sampled by the quantised rollout policy
ratio = np.exp(lp[np.arange(64), y] - lq[np.arange(64), y])
print(f"{name:<20} KL(train||rollout) {kl:.2e} pi_train/pi_rollout on sampled tokens: [{ratio.min():.3f}, {ratio.max():.3f}]")import torch
FMAX = torch.finfo(torch.float8_e4m3fn).max # 448.0
def quant_fp8_block(W: torch.Tensor, b: int = 128):
"""BF16 [R, C] -> FP8 E4M3 values + one FP32 scale per b x b block (DeepSeek-V3-style weight format)."""
Wb = W.float().unflatten(0, (-1, b)).unflatten(2, (-1, b)) # [R/b, b, C/b, b]
scale = Wb.abs().amax(dim=(1, 3), keepdim=True).clamp(min=1e-12) / FMAX
return (Wb / scale).to(torch.float8_e4m3fn), scale
def dequant_fp8_block(q: torch.Tensor, scale: torch.Tensor) -> torch.Tensor:
return (q.float() * scale).flatten(2).flatten(0, 1)
@torch.no_grad()
def sync_weights_fp8(trainer_model, send):
"""At every weight sync: re-quantise the trainer's BF16 weights to the rollout engine's FP8 format."""
for name, p in trainer_model.named_parameters():
if p.ndim == 2 and p.shape[0] % 128 == 0 and p.shape[1] % 128 == 0 and "lm_head" not in name and "embed" not in name:
q, s = quant_fp8_block(p.detach())
send(name, q, s.squeeze(1).squeeze(-1)) # FP8 tensor + [R/128, C/128] scales
else:
send(name, p.detach().to(torch.bfloat16), None) # router, embeddings, LM head stay BF16
W = torch.randn(4096, 4096, device="cuda", dtype=torch.bfloat16) * 0.02
q, s = quant_fp8_block(W)
rel = (dequant_fp8_block(q, s) - W.float()).norm() / W.float().norm()
print(f"FP8 128x128 block relative error {rel.item():.2e}; bytes {q.numel() + 4 * s.numel():,} vs {2 * W.numel():,}")A model's activations have a few channels that are ~100x larger than the rest. You want W8A8 with per-tensor activation scales. What does SmoothQuant do?
exactly. Dividing the outlier channels shrinks the activation crest factor that a per-tensor scale must cover; the weights absorb the range, which their per-output-channel scales tolerate. The scales are folded into the preceding layer offline, so there is no runtime cost. Keeping channels in FP16 is LLM.int8()‘s approach.
Why do 4-bit RL rollouts use quantisation-aware training rather than quantising the policy after each update?
The importance ratio is what off-policy corrections have to manage. QAT makes the trainer compute log-probabilities under the same quantisation grid the sampler uses, so the mismatch shrinks to kernel-level differences (LMSYS measured a gap close to BF16 and below FP8). FP8 is close enough for PTQ plus TIS; 4-bit generally is not.
Summary
- Uniform quantisation loses one bit per doubling of the crest factor: outliers are the whole problem.
- Floats (FP8) make error relative; block scaling (MXFP4: 32 + E8M0; NVFP4: 16 + E4M3 + FP32, 4.5 bits) localises outliers.
- GPTQ compensates each weight’s rounding error with the inverse Hessian of the calibration inputs; AWQ scales up activation-salient channels; both beat RTN most at 3–4 bits.
- SmoothQuant migrates activation outliers into the weights for W8A8; rotations (QuaRot, SpinQuant, Hadamard transforms) spread them out for 4-bit.
- FP8 rollouts: blockwise W8A8, re-quantise at every sync, recalibrate KV scales, correct with TIS/MIS. 4-bit rollouts: QAT so the trainer sees the rollout’s grid.
해 볼 것: 3비트, outlier 20배에서 AWQ는 RTN의 오차를 40% 정도 줄인다. 오차를 지배하는 것이 AWQ가 보호하는 outlier channel 4개이기 때문이다. GPTQ는 이 작은 층에서는 덜 돕는다(오차를 퍼뜨릴 입력 열이 64개뿐이다. 아래 NumPy의 더 큰 층에서는 이득이 더 크다). 8비트에서는 셋이 같아진다(고칠 것이 없다). outlier 배율을 1로 두면 AWQ의 최적 α가 ~0으로 떨어지고(보호할 중요 channel이 없다) SmoothQuant도 얻는 것이 없다. 60으로 올리면 naive W8A8은 outlier와 함께 나빠지고, α ≈ 0.5–0.75 근처의 SmoothQuant는 평평하다. 여기서 GPTQ는 자기 calibration 데이터로 평가했다. held-out 입력에서는 이점이 다소 줄어든다.
RL의 저정밀 rollout
rollout 생성이 RL step 시간을 지배하므로 sampler를 FP8이나 4비트로 돌리는 것은 매력적이다. 그런데 그러면 sampler는 조금 다른 정책 를 따르고, 가중치는 step마다 바뀐다.
FP8 rollout. FP8-RL(verl에 구현됨)은 rollout의 선형층을 blockwise FP8 W8A8로 돌린다. DeepSeek-V3를 따라 가중치는 128×128 블록, 활성값은 1×128 tile이고, router·embedding·LM head는 BF16으로 남긴다. 정책이 step마다 바뀌므로 trainer는 weight sync 때마다 BF16 가중치를 inference checkpoint의 FP8 블록 형식으로 다시 양자화한다(아래 PyTorch 블록이 정확히 그 변환이다). KV cache도 FP8로 할 수 있고, Q/K/V scale은 step마다 다시 보정한다. 추가된 불일치는 토큰 단위 importance-sampling 보정(TIS/MIS, off-policy 불일치 참고)이 흡수한다. verl 문서는 보정 없이는 정확도가 눈에 띄게 떨어진다고 보고한다. 보고된 이득: 논문은 rollout 처리량 최대 44%, verl 문서는 Qwen3-8B에서 ~12–18%, Qwen3-30B-A3B에서 35% 이상.
QAT로 하는 4비트 rollout. 4비트에서는 사후 양자화가 너무 멀리 벗어나므로, trainer가 양자화를 보게 만든다. forward는 가짜 양자화된(양자화–역양자화) 가중치를 쓰고, backward는 BF16 master 가중치에 straight-through estimator를 쓰며, rollout 엔진은 같은 격자의 실제 저비트 kernel을 돌린다. Kimi K2 Thinking이 공개된 선례다. MoE 부분에 INT4 weight-only 양자화를 하고 사후학습에서 QAT를 써서, low-latency 모드에서 생성 속도를 약 2배로 했다. 이유로 든 것은 긴 thinking trace 때문에 사후 양자화가 성능을 떨어뜨린다는 점이다. LMSYS의 재현(Megatron 가짜 양자화, SGLang INT4 W4A16 kernel, 1×32 그룹)은 학습–rollout log-prob 차이가 BF16과 거의 같고 FP8 rollout보다 확실히 작으며, 주된 이득은 메모리, 즉 rollout이 노드 하나에 들어간다는 것을 확인했다. NeMo RL의 quantization-aware RL은 같은 일을 NVFP4로 한다. W4A16은 GRPO에서 수렴하고, W4A4는 아직 알려진 수렴 문제가 있다.
아래 코드는 장난감 LM head에서 불일치를 잰다. BF16 정책과 양자화된 사본 사이의 KL, 그리고 양자화 정책이 샘플한 토큰에서의 토큰별 비 의 범위다. IS 보정이 잘라 내야 하는 바로 그 양이다.
구현하기
import numpy as np
rng = np.random.default_rng(0)
# --- number formats -------------------------------------------------------------------------
def fp_round(x, m_bits, emin, maxval):
"""Round to a minifloat with m_bits mantissa bits, min normal exponent emin, saturating at maxval."""
a = np.minimum(np.abs(x), maxval)
e = np.floor(np.log2(np.maximum(a, 1e-30)))
step = 2.0 ** (np.maximum(e, emin) - m_bits) # subnormals share the emin step
return np.sign(x) * np.minimum(np.round(a / step) * step, maxval)
e4m3 = lambda x: fp_round(x, 3, -6, 448.0) # FP8 E4M3 (bias 7, max 448)
e5m2 = lambda x: fp_round(x, 2, -14, 57344.0) # FP8 E5M2 (bias 15, max 57344)
e2m1 = lambda x: fp_round(x, 1, 0, 6.0) # FP4 E2M1: 0, .5, 1, 1.5, 2, 3, 4, 6
print("E2M1 grid:", np.unique(np.abs(e2m1(np.linspace(-7, 7, 2001)))))
# np.round는 짝수 쪽 반올림(IEEE 기본). 그림도 같은 규칙을 쓴다. 정확히 중간인 값은 짝수 이웃으로 간다:
print("짝수 쪽 반올림: e4m3(1.0625) =", e4m3(1.0625), "(1.125 아님); e2m1(0.25) =", e2m1(0.25), "(0.5 아님)")
def int_sym(x, bits, axis=None):
s = np.abs(x).max(axis=axis, keepdims=True) / (2 ** (bits - 1) - 1)
return np.round(x / s) * s
def grouped(x, g, f): # f sees rows of g consecutive values
return f(x.reshape(-1, g)).reshape(x.shape)
amax = lambda c: np.maximum(np.abs(c).max(axis=1, keepdims=True), 1e-12) # all-zero block -> no 0/0
def mxfp4(x): # 32-value blocks, power-of-two (E8M0) scale
return grouped(x, 32, lambda c: e2m1(c / (s := 2.0 ** np.ceil(np.log2(amax(c) / 6)))) * s)
def nvfp4(x): # 16-value blocks, E4M3 scale, FP32 tensor scale
g = np.abs(x).max() / (6 * 448)
# clamp the block scale to the smallest positive E4M3 (2^-9): a tiny block would round it to 0 -> NaN
return grouped(x, 16, lambda c: e2m1(c / (s := np.maximum(e4m3(amax(c) / 6 / g), 2.0 ** -9) * g)) * s)
def sqnr(x, q): return 10 * np.log10((x ** 2).sum() / ((x - q) ** 2).sum())
w = rng.normal(size=4096) * 0.02
w[rng.choice(4096, 8, replace=False)] *= 30 # a few outlier weights
fmts = {"INT8 per-tensor (8)": int_sym(w, 8), "FP8 E4M3 per-tensor (8)": e4m3(w / (np.abs(w).max() / 448)) * (np.abs(w).max() / 448),
"FP8 E5M2 per-tensor (8)": e5m2(w / (np.abs(w).max() / 57344)) * (np.abs(w).max() / 57344),
"INT4 group-128 (4.125)": grouped(w, 128, lambda c: int_sym(c, 4, axis=1)), "INT4 group-32 (4.5)": grouped(w, 32, lambda c: int_sym(c, 4, axis=1)),
"MXFP4 (4.25)": mxfp4(w), "NVFP4 (4.5)": nvfp4(w)}
print("\nSQNR on weights with outliers (format, bits/value):")
for k, q in fmts.items(): print(f" {k:<26} {sqnr(w, q):5.1f} dB")
# --- weight-only methods on one linear layer ------------------------------------------------------
d_in, d_out, n = 256, 128, 512
X = rng.normal(size=(n, d_in)); X[:, :4] *= 20 # 4 outlier activation channels
W = rng.normal(size=(d_out, d_in)) / np.sqrt(d_in)
Y = X @ W.T
err = lambda Wq: np.linalg.norm(X @ Wq.T - Y) / np.linalg.norm(Y)
rtn = lambda W, b: int_sym(W, b, axis=1) # per-output-channel symmetric
def gptq(W, X, bits, damp=0.01):
H = 2 * X.T @ X
H += damp * np.mean(np.diag(H)) * np.eye(len(H)) # 1% of the mean diagonal
U = np.linalg.cholesky(np.linalg.inv(H)).T # upper Cholesky factor of H^-1
Wc, Q = W.copy(), np.zeros_like(W)
scale = np.abs(W).max(axis=1) / (2 ** (bits - 1) - 1) # grid fixed from the original weights
for i in range(W.shape[1]): # quantise input column i ...
Q[:, i] = np.clip(np.round(Wc[:, i] / scale), -(2 ** (bits - 1) - 1), 2 ** (bits - 1) - 1) * scale
e = (Wc[:, i] - Q[:, i]) / U[i, i]
Wc[:, i + 1:] -= np.outer(e, U[i, i + 1:]) # ... and push its error onto the later columns
return Q
def awq(W, X, bits):
sx = np.abs(X).mean(axis=0)
best = None
for a in np.linspace(0, 1, 11): # grid search alpha in [0, 1]
s = sx ** a; s /= np.sqrt(s.max() * s.min())
e = np.linalg.norm((X / s) @ rtn(W * s, bits).T - Y) / np.linalg.norm(Y)
if best is None or e < best[0]: best = (e, a)
return best
print("\nweight-only, relative output error ||XW^T - XQ^T|| / ||XW^T||:")
for bits in [4, 3]:
e_awq, a = awq(W, X, bits)
print(f" W{bits}: RTN {err(rtn(W, bits)):.4f} AWQ {e_awq:.4f} (alpha={a:.2f}) GPTQ {err(gptq(W, X, bits)):.4f}")
# --- W8A8: activation outliers and SmoothQuant -------------------------------------------------
def w8a8(X, W, alpha=None):
if alpha is not None:
s = np.abs(X).max(0) ** alpha / np.abs(W).max(0) ** (1 - alpha)
X, W = X / s, W * s # X diag(s)^-1 . diag(s) W^T: same product
return np.linalg.norm(int_sym(X, 8) @ int_sym(W, 8, axis=1).T - Y) / np.linalg.norm(Y)
print(f"\nW8A8 per-tensor activations: naive {w8a8(X, W):.4f} " + " ".join(f"SmoothQuant a={a} {w8a8(X, W, a):.4f}" for a in [0.25, 0.5, 0.75]))
# --- low-precision rollout: how far does the quantised policy drift? -----------------------------
V, Hd = 2048, 128
Wlm = rng.normal(size=(V, Hd)) / np.sqrt(Hd) * 3
h = rng.normal(size=(64, Hd))
def logp(Wm):
z = h @ Wm.T; z -= z.max(1, keepdims=True); return z - np.log(np.exp(z).sum(1, keepdims=True))
def fp8_block(Wm, b=128): # 128x128 blocks, E4M3 values + one scale per block
Q = np.empty_like(Wm)
for i in range(0, Wm.shape[0], b):
for j in range(0, Wm.shape[1], b):
blk = Wm[i:i + b, j:j + b]; s = np.abs(blk).max() / 448
Q[i:i + b, j:j + b] = e4m3(blk / s) * s
return Q
lp = logp(Wlm)
for name, Wq in [("FP8 128x128 blocks", fp8_block(Wlm)), ("NVFP4", nvfp4(Wlm.ravel()).reshape(Wlm.shape)),
("INT4 group-32", grouped(Wlm.ravel(), 32, lambda c: int_sym(c, 4, axis=1)).reshape(Wlm.shape))]:
lq = logp(Wq); p = np.exp(lp)
kl = (p * (lp - lq)).sum(1).mean()
y = np.array([rng.choice(V, p=np.exp(r)) for r in lq]) # tokens sampled by the quantised rollout policy
ratio = np.exp(lp[np.arange(64), y] - lq[np.arange(64), y])
print(f"{name:<20} KL(train||rollout) {kl:.2e} pi_train/pi_rollout on sampled tokens: [{ratio.min():.3f}, {ratio.max():.3f}]")import torch
FMAX = torch.finfo(torch.float8_e4m3fn).max # 448.0
def quant_fp8_block(W: torch.Tensor, b: int = 128):
"""BF16 [R, C] -> FP8 E4M3 values + one FP32 scale per b x b block (DeepSeek-V3-style weight format)."""
Wb = W.float().unflatten(0, (-1, b)).unflatten(2, (-1, b)) # [R/b, b, C/b, b]
scale = Wb.abs().amax(dim=(1, 3), keepdim=True).clamp(min=1e-12) / FMAX
return (Wb / scale).to(torch.float8_e4m3fn), scale
def dequant_fp8_block(q: torch.Tensor, scale: torch.Tensor) -> torch.Tensor:
return (q.float() * scale).flatten(2).flatten(0, 1)
@torch.no_grad()
def sync_weights_fp8(trainer_model, send):
"""At every weight sync: re-quantise the trainer's BF16 weights to the rollout engine's FP8 format."""
for name, p in trainer_model.named_parameters():
if p.ndim == 2 and p.shape[0] % 128 == 0 and p.shape[1] % 128 == 0 and "lm_head" not in name and "embed" not in name:
q, s = quant_fp8_block(p.detach())
send(name, q, s.squeeze(1).squeeze(-1)) # FP8 tensor + [R/128, C/128] scales
else:
send(name, p.detach().to(torch.bfloat16), None) # router, embeddings, LM head stay BF16
W = torch.randn(4096, 4096, device="cuda", dtype=torch.bfloat16) * 0.02
q, s = quant_fp8_block(W)
rel = (dequant_fp8_block(q, s) - W.float()).norm() / W.float().norm()
print(f"FP8 128x128 block relative error {rel.item():.2e}; bytes {q.numel() + 4 * s.numel():,} vs {2 * W.numel():,}")어떤 모델의 활성값에 나머지보다 ~100배 큰 channel이 몇 개 있다. per-tensor 활성값 scale로 W8A8을 하고 싶다. SmoothQuant는 무엇을 하나?
는 정확히 성립한다. outlier channel을 나누면 per-tensor scale이 덮어야 하는 활성값 crest factor가 줄고, 범위는 가중치가 흡수하는데 가중치의 출력 channel별 scale은 그것을 견딘다. scale은 오프라인으로 앞 층에 접혀 들어가므로 실행 시간 비용이 없다. channel을 FP16으로 남기는 것은 LLM.int8()의 방식이다.
4비트 RL rollout은 왜 매 갱신 뒤 정책을 사후 양자화하지 않고 quantization-aware training을 쓰나?
off-policy 보정이 관리해야 하는 것은 importance 비 이다. QAT는 trainer가 sampler와 같은 양자화 격자에서 log-probability를 계산하게 하므로 불일치가 kernel 수준 차이로 줄어든다(LMSYS는 BF16에 가깝고 FP8보다 작은 차이를 측정했다). FP8은 PTQ + TIS로 충분히 가깝고, 4비트는 대개 그렇지 않다.
정리
- 균일 양자화는 crest factor가 두 배가 될 때마다 비트 하나를 잃는다. 문제는 전부 outlier다.
- float(FP8)는 오차를 상대적으로 만들고, block scaling(MXFP4: 32 + E8M0, NVFP4: 16 + E4M3 + FP32, 4.5비트)은 outlier를 국소화한다.
- GPTQ는 각 가중치의 반올림 오차를 calibration 입력의 역 Hessian으로 보정하고, AWQ는 활성값 기준으로 중요한 channel을 키운다. 둘 다 3–4비트에서 RTN을 가장 크게 이긴다.
- SmoothQuant는 W8A8을 위해 활성값 outlier를 가중치로 옮기고, 회전(QuaRot, SpinQuant, Hadamard 변환)은 4비트를 위해 그것을 퍼뜨린다.
- FP8 rollout: blockwise W8A8, sync마다 재양자화, KV scale 재보정, TIS/MIS 보정. 4비트 rollout: trainer가 rollout의 격자를 보도록 QAT.
더 읽을거리Further reading
- Frantar et al., GPTQ: Accurate Post-Training Quantization for Generative Pre-trained Transformers (ICLR 2023) — OBS식 오차 보정을 열 순서·lazy batch·Cholesky로 거대 모델에 적용.OBS-style error compensation made practical for huge models with a fixed column order, lazy batches and Cholesky.
- Lin et al., AWQ: Activation-aware Weight Quantization for LLM Compression and Acceleration (MLSys 2024) — 활성값이 큰 channel의 가중치를 scaling으로 보호한다.Protects the weights of high-activation channels by scaling.
- Xiao et al., SmoothQuant: Accurate and Efficient Post-Training Quantization for Large Language Models (ICML 2023) — 활성값 outlier의 크기를 수학적으로 동치인 변환으로 가중치에 옮긴다.Moves the magnitude of activation outliers into the weights with a mathematically equivalent transform.
- Micikevicius et al., FP8 Formats for Deep Learning (2022) — E4M3과 E5M2의 정의.The definitions of E4M3 and E5M2.
- NVIDIA, Introducing NVFP4 for Efficient and Accurate Low-Precision Inference (2025) — 16값 블록, E4M3 scale, tensor별 FP32 scale. MXFP4와의 비교.16-value blocks, an E4M3 scale and a per-tensor FP32 scale; comparison with MXFP4.
- Qiu et al., FP8-RL: A Practical and Stable Low-Precision Stack for LLM Reinforcement Learning (2026) — blockwise FP8 W8A8 rollout, 매 sync 재양자화, FP8 KV의 step별 scale 재보정, TIS/MIS 보정. verl 문서(low_precision/fp8)도 함께.Blockwise FP8 W8A8 rollout, re-quantisation at every sync, per-step FP8 KV scale recalibration, TIS/MIS correction. Read with the verl docs (low_precision/fp8).
- NVIDIA NeMo RL, Quantization-Aware RL guide; LMSYS, INT4 QAT for RL (2026) — 학습 forward를 가짜 양자화로 돌려 rollout의 실제 NVFP4/INT4와 맞춘다. LMSYS 글(lmsys.org/blog/2026-01-26-int4-qat)은 Kimi K2 Thinking식 INT4 W4A16 QAT를 재현한다.Fake-quantise the training forward to match the rollout's real NVFP4/INT4. The LMSYS post (lmsys.org/blog/2026-01-26-int4-qat) reproduces Kimi K2 Thinking-style INT4 W4A16 QAT.
- Ashkboos et al., QuaRot: Outlier-Free 4-Bit Inference in Rotated LLMs (2024) — Hadamard 회전으로 outlier를 없애 가중치·활성값·KV를 모두 4비트로.Hadamard rotations remove outliers so weights, activations and KV all go to 4 bits.