Introduction
We start with a BF16 reasoning model and must produce weights for a fixed serving format. The kernel, group size, scale representation, and quantized modules are already chosen, so the open question is the procedure: what calibration traces to use, how to choose integer codes and group scales, whether to transform the weights, and how to tune the result. This is difficult because a small next-token perturbation can be revisited throughout a long chain of thought. A procedure that looks good on short reconstruction batches can still change the model's distribution, induce a repetition loop, or lose instruction-following behaviour.
The usual toolbox attacks different pieces of this problem. GPTQ is a post-training quantization method for generative transformers [1]. AWQ is activation-aware weight quantization [2], while QuaRot and SpinQuant study rotated models and learned rotations [3, 4]. AutoRound optimizes rounding decisions rather than accepting round-to-nearest [5], and GSQ studies low-precision scalar quantization by sampling [6]. The reasoning setting also motivates calibration that reflects the model's own long-form behaviour; the verified literature includes a study of the damage quantization can cause to reasoning models [7].
We propose TFQ around a simple target: preserve the BF16 model's next-token distributions on realistic, long traces, including the distribution's sharpness. We use the BF16 model as the teacher throughout, let the quantized model supply the inputs seen by later layers, and expose the serving kernel's effective grid during both reconstruction and scale tuning. The result is a single procedure for both fixed formats, with no task-specific weight transform.
Method
Calibration follows the deployed trajectory
We draw prompts from several offline source families and ask the BF16 model to produce its own
reasoning traces. Each trace retains its source label. The code's default source mixture uses
weights 0.3, 0.2, 0.35, and 0.15. We shuffle within each source, keep the chat template and
prompt boundary, trim a
verbatim repetition loop at the end when one is detected, and add an end token when generation
ended naturally. When enough self-generated traces are available, we reserve a source-balanced
held-out split for choosing scales.
For reconstruction, traces are truncated to whole 1024-token buckets, at most 8192 tokens in
the driver, and selected so the source with the smallest accumulated token count is used next. End-
to-end refinement samples a source uniformly before selecting a trace. When multiple source groups
are available, this limits any one source's share, and the teacher-forced targets include the
contexts that a deployed model is likely to revisit.
def prompt_pool(ctx, n, seed=0, mix=GEN_MIX, skip=0):
"""n (user prompt, corpus name) drawn from the offline corpora (mixture), deterministic; `skip`
skips the first prompts of each corpus' shuffled order (held-out sets)."""
have = ctx.calib_sources()
mix = [(c, w) for c, w in mix if not have or c in have]
tot = sum(w for _, w in mix)
out = []
for i, (c, w) in enumerate(mix):
k = int(round(n * w / tot)) if i < len(mix) - 1 else n - len(out)
recs = ctx.calib_records(c)
order = list(range(len(recs)))
random.Random(seed + 17 * i).shuffle(order)
got = 0
for j in order[skip:]:
p = _first_user(recs[j]).strip()
if 16 <= len(p) <= 6000:
out.append((p, c))
got += 1
if got >= k:
break
random.Random(seed).shuffle(out)
return outdef calib_batches(seqs, n_tokens, bucket=1024, max_len=16384, seed=0):
"""Whole traces (each starting at its own BOS, as every prompt does at inference), truncated
to a multiple of `bucket` tokens (at most max_len), drawn over the prompt sources with an equal
token budget per source (long math traces would dominate otherwise), until n_tokens."""
rng = random.Random(seed)
groups = []
for g in by_source(seqs):
g = [t for t in g if min(len(t[0]), max_len) >= bucket]
rng.shuffle(g)
if g:
groups.append(g)
out, tot = [], 0
used = [0] * len(groups)
toks = [0] * len(groups)
while tot < n_tokens:
live = [i for i in range(len(groups)) if used[i] < len(groups[i])]
if not live:
break
i = min(live, key=lambda k: toks[k]) # the source with the fewest tokens so far
ids = groups[i][used[i]][0]
used[i] += 1
L = min(len(ids), max_len) // bucket * bucket
out.append(torch.tensor(ids[:L], dtype=torch.long))
toks[i] += L
tot += L
return outIf self-generation fails, we first use offline reasoning traces, then generic corpus text. If no usable data remains or too little time is left, the driver exports a searched-scale round-to-nearest result from the checkpoint alone. These fallbacks preserve the export contract while keeping the calibrated path data-rich.
Format-exact signed scales and codes
For a weight group and effective signed scale , we use the fixed integer grid directly:
The asymmetric signed grid has one extra level on one side. We therefore search both signs of a
group scale and choose the sign with the lower weighted error, allowing a group extreme to align
with the more useful side of the grid. The search evaluates 48 magnitudes from 0.5 to 1.1
times the absmax-derived magnitude. Its error can be weighted by the diagonal of the input second
moment, plus the same damping used by reconstruction. This makes the rounding decision sensitive
to the directions that the trace actually excites.
The w3a16 path stores the selected BF16 scales directly. In w4a8, the serving kernel first re-encodes each row of group scales as FP8 E4M3 relative to the row maximum. We enumerate the positive finite E4M3 values, test the two neighbours around each desired group magnitude, restore the row maximum that defines the kernel's row factor, and fit integer codes to the resulting effective scales. Calibration statistics pass the layer inputs through the same dynamic per-token FP8 quantizer, so the activation rounding participates in the reconstruction target.
@torch.no_grad()
def search_scales(W, fmt, wdiag=None, grid=48, lo=0.5, hi=1.1, rows=2048):
"""Per-group signed scale minimising sum_i d_i (w_i - q_i s)^2 over a magnitude grid and both
signs: the asymmetric INT grid [qmin, qmax] has one more level on the negative side, and a
negative scale moves it to the positive side, so the sign is a free per-group choice.
W [R, C] float32 -> desired effective scales [R, G] float32 (BF16-representable)."""
R, C = W.shape
g = fmt.group_size
G = C // g
wd = None if wdiag is None else wdiag.reshape(1, G, g).float()
out = torch.empty(R, G, device=W.device)
nq = -fmt.qmin
for r0 in range(0, R, rows):
Wg = W[r0:r0 + rows].reshape(-1, G, g)
amax = Wg.abs().amax(-1).clamp(min=1e-12)
imax = Wg.abs().argmax(-1, keepdim=True)
smax = torch.gather(Wg, -1, imax).squeeze(-1).sign()
smax[smax == 0] = 1.0
best = torch.full(amax.shape, float("inf"), device=W.device)
best_s = (amax / nq).to(torch.bfloat16).float()
for sg in (1.0, -1.0):
sign = -smax * sg # sg = 1: the extreme weight maps to code qmin
for k in range(grid):
f = lo + (hi - lo) * k / (grid - 1)
s = ((amax * f / nq) * sign).to(torch.bfloat16).float()
s = torch.where(s == 0, torch.full_like(s, 1e-8), s)
e = group_err(Wg, s, fmt, wd)
upd = e < best
best = torch.where(upd, e, best)
best_s = torch.where(upd, s, best_s)
out[r0:r0 + rows] = best_s
return outSequential BF16-anchored reconstruction
We quantize decoder layers one at a time and process their projection stages in the order encoded
by STAGES: query/key/value and in_proj_qkv/in_proj_z projections, output projection,
gated-up projections, and the down projection. At each stage, the quantized prefix supplies and the untouched BF16 copy supplies
. We accumulate
and fit a target weight by
The ridge is anchored at the original BF16 weight . Directions that the calibration inputs do not excite therefore retain the teacher's weight instead of being pulled toward zero. For w4a8, is FP8-quantized before the moments are accumulated. We then quantize with the searched effective scales, solve a least-squares refit for the scales with codes fixed, and run a second GPTQ pass when it lowers the activation-weighted output error. The model remains the BF16 teacher between layers; only the exported code and scale pairs are retained.
def sequential_quantize(ctx, model, windows, asym=True, rounds=2, damp=0.01, log_every=1):
"""Layer-by-layer, stage-by-stage GPTQ on the self-generated calibration windows.
Returns {ckpt name: (codes int8 cpu, stored scales bf16 cpu)}."""
dev = ctx.device
fmt = ctx.fmt
g = fmt.group_size
lengths = [int(w.numel()) for w in windows]
calls = capture_layer_calls(model, lengths, dev)
emb = model.model.embed_tokens
X_fp = [emb(w.to(dev)[None]) for w in windows]
X_q = [x.clone() for x in X_fp]
per_layer = layer_targets(ctx, model)
result = {}
qs = QState(fmt)
t0 = time.monotonic()
for li, layer in enumerate(model.model.layers):
tg = per_layer[li]
layer_fp = copy.deepcopy(layer)
stats = []
for stage in STAGES:
mods = [(leaf, tg[leaf]) for leaf in stage if leaf in tg]
if not mods:
continue
first = mods[0][1][1]
first_fp = dict(layer_fp.named_modules())[
[n for n, m in layer.named_modules() if m is first][0]]
H, Cm = stage_stats(layer, layer_fp, first, first_fp, X_q, X_fp, calls, li, fmt, asym)
lam = damp * torch.mean(torch.diag(H))
Hd = H.clone()
Hd.diagonal().add_(lam)
if asym:
Cm.diagonal().add_(lam)
for leaf, (name, mod) in mods:
W = mod.weight.data.float()
if asym:
# argmin ||W X_bf16 - V X_q||^2 + lam ||V - W||^2 = W (C + lam I)(H + lam I)^-1:
# ridge toward the BF16 weight, so directions the calibration data does not
# excite keep the original weights (ridge toward 0 would erase them)
Wt = torch.linalg.solve(Hd, (W @ Cm).T).TEnd-to-end scale refinement
After sequential reconstruction, integer codes stay fixed and each stored scale is parameterized as . The student forward pass reconstructs the fixed-format weight, and w4a8 also applies the kernel's FP8 scale and activation roundings with a straight-through gradient. For a teacher distribution and student distribution at each generated position, we minimize the Jeffreys divergence
The forward pass is chunked, and gradients are backpropagated through the student's hidden states
into the group scales. The optimizer is Adam with learning rate 1e-3; its learning rate follows a
time-based cosine schedule, and each is clamped to [-0.5, 1.0], keeping a scale between
0.5 and 2 times its starting value. Only next-token predictions for generated tokens, including
the prediction at the prompt boundary, contribute. A
When a held-out split exists, it is source-balanced and evaluated during refinement, and the best
scale state is restored before export.
class QLinear(torch.nn.Module):
"""A quantized Linear for end-to-end refinement: teacher mode = the original BF16 weight;
student mode = codes * group scales on the fixed grid (scales trainable as s0 * (1 + theta)),
inputs FP8-quantized per token for W4A8 (straight-through)."""
def __init__(self, lin, codes, stored, fmt):
super().__init__()
self.weight = lin.weight
self.weight.requires_grad_(False)
self.fmt = fmt
self.register_buffer("codes", codes.to(lin.weight.device, torch.int8), persistent=False)
self.register_buffer("s0", stored.to(lin.weight.device, torch.float32), persistent=False)
self.theta = torch.nn.Parameter(torch.zeros_like(self.s0))
def scales(self):
s = self.s0 * (1.0 + self.theta)
if self.fmt.act_fp8:
s = _ste_fp8_rows(s, self.fmt)
return s
def stored(self):
with torch.no_grad():
s = (self.s0 * (1.0 + self.theta)).to(torch.bfloat16)
return torch.where(s == 0, self.s0.to(torch.bfloat16), s)
def forward(self, x):
if not Mode.student:
return F.linear(x, self.weight)
g = self.fmt.group_size
W = self.codes.to(x.dtype) * self.scales().to(x.dtype).repeat_interleave(g, dim=1)
if self.fmt.act_fp8:
x = x + (fp8_tokens(x) - x).detach()
return F.linear(x, W)def kl_chunked(lm_head, h_t, h_s, start=0, chunk=2048, div="jeff"):
"""Mean over positions >= start of the divergence between the teacher's and the student's
next-token distributions, from final hidden states, backpropagated into h_s chunk by chunk
(h_s must be a leaf requiring grad). div: "fkl" = KL(teacher || student); "jeff" = Jeffreys
KL(t || s) + KL(s || t), which has no first-order bias toward a flatter or sharper student.
Returns the mean forward KL (for logging)."""
tot = 0.0
T = h_s.shape[0]
n = max(1, T - start)
for c0 in range(start, T, chunk):
with torch.no_grad():
tl = F.log_softmax(lm_head(h_t[c0:c0 + chunk]).float(), -1)
sl = F.log_softmax(lm_head(h_s[c0:c0 + chunk]).float(), -1)
fkl = (tl.exp() * (tl - sl)).sum()
loss = fkl
if div == "jeff":
loss = loss + (sl.exp() * (sl - tl)).sum()
(loss / n).backward()
tot += float(fkl)
return tot / nThe procedure restores the BF16 weights between layers and exports only code and scale pairs; the same overall pipeline applies to both formats. It uses the available time for trace generation, sequential reconstruction, and scale refinement; if the remaining budget is too short for refinement, it exports the sequential result.
Results
| Method | ① | ② | ③ | ④ | ||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Math accuracy ↑ | Science accuracy ↑ | Instruction following ↑ | Math accuracy ↑ | Science accuracy ↑ | Instruction following ↑ | Math accuracy ↑ | Science accuracy ↑ | Instruction following ↑ | Math accuracy ↑ | Science accuracy ↑ | Instruction following ↑ | |
| Claude Opus 5.5 | 0.667 | 0.664 | 0.547 | 0.762 | 0.783 | 0.600 | 0.244 | 0.313 | 0.521 | 0.266 | 0.402 | 0.577 |
| GPTQ | 0.218 | 0.417 | 0.430 | 0.524 | 0.689 | 0.633 | 0.188 | 0.308 | 0.512 | 0.240 | 0.356 | 0.617 |
| GPTQ + Liu et al. | 0.556 | 0.604 | 0.530 | 0.726 | 0.740 | 0.597 | 0.238 | 0.260 | 0.447 | 0.266 | 0.369 | 0.612 |
| AWQ | 0.020 | 0.215 | 0.203 | 0.544 | 0.616 | 0.577 | 0.077 | 0.199 | 0.344 | 0.260 | 0.369 | 0.604 |
| QuaRot + GPTQ | 0.516 | 0.586 | 0.540 | 0.702 | 0.740 | 0.593 | 0.194 | 0.290 | 0.451 | 0.260 | 0.389 | 0.597 |
| SpinQuant | 0.405 | 0.581 | 0.467 | 0.663 | 0.707 | 0.560 | 0.200 | 0.237 | 0.447 | 0.254 | 0.366 | 0.604 |
| AutoRound | 0.262 | 0.551 | 0.477 | 0.532 | 0.715 | 0.590 | 0.196 | 0.275 | 0.530 | 0.252 | 0.381 | 0.590 |
| GSQ | 0.345 | 0.518 | 0.530 | 0.667 | 0.740 | 0.607 | 0.119 | 0.182 | 0.035 | 0.278 | 0.386 | 0.625 |
- ① Qwen3.5-9B · W3A16 (INT3 g128 weights, BF16 activations, Humming kernel)
- ② Qwen3.5-9B · W4A8 (INT4 g128 weights, FP8 per-token activations, CUTLASS W4A8 kernel)
- ③ DeepSeek-R1-Distill-Llama-8B · W3A16
- ④ DeepSeek-R1-Distill-Llama-8B · W4A8
On Model A W3A16, TFQ leads every metric for that setting. Its math accuracy is 0.667 versus 0.556 for GPTQ + reasoning [7], its science accuracy is 0.664 versus 0.604 for GPTQ + reasoning [7], and its instruction-following accuracy is 0.547 versus 0.540 for QuaRot + GPTQ [3].
Model A W4A8 shows the same advantage on math and science: TFQ reaches 0.762 against 0.726 for GPTQ + reasoning [7], and 0.783 against 0.740 for GPTQ + reasoning [7]. Instruction following is the exception, with 0.600 versus 0.633 for GPTQ [1].
Model B W3A16 is more mixed. TFQ reaches 0.244 on math against 0.238 for GPTQ + reasoning [7], and 0.313 on science against 0.308 for GPTQ [1]. On instruction following, it reaches 0.521 against 0.530 for AutoRound [5].
On Model B W4A8, the procedure's science result is 0.402 against 0.389 for QuaRot + GPTQ [3]. Its math result is 0.266 against 0.278 for GSQ [6], and its instruction-following result is 0.577 against 0.625 for GSQ [6]. The table therefore supports a clear gain on several metrics while also exposing a real architecture-and-format sensitivity in the remaining ones.
How we got here
The starter procedure was round-to-nearest with absmax group scales and no calibration data. We replaced it after the development account reported uneven per-token divergence across text domains and no benefit from training on the quantized model's own sampled traces; this led us to use BF16-generated traces and teacher-forced targets, with source balancing so that long traces do not dominate.
The trace records a first attempt at forward-KL refinement that made the student more over-dispersed. We therefore changed the objective to the symmetric Jeffreys divergence, which penalizes both a student that is too flat and one that is too sharp. The code comments also identify an earlier ridge-to-zero target as destructive in weakly excited input directions. We instead solve the BF16-anchored target in the final procedure, preserving the teacher where calibration evidence is thin.
The cited literature covers activation-aware quantization [2], rotations [3, 4], optimized rounding [5], and sampled scalar quantization [6]. The submitted code does not add a BF16-side rotation or learn integer codes end to end. It instead puts the fixed kernel's real grid, upstream quantization error, and teacher trajectory into the reconstruction objective, then spends the remaining budget on scale-only refinement.
Finally, the trace records practical dead ends in the build: a layer-call plumbing bug, missing output directories, and a failed intermediate rewrite. Those were repaired before the final file; the surviving method includes the tested data fallbacks, non-finite-step guard, held-out best-state restore, and data-free export path.
Limitations
- The gains are not uniform. The table shows a strong result on Model A W3A16, clear gains on math and science in Model A W4A8, mixed outcomes in Model B W3A16, and a weaker instruction-following result in Model B W4A8. The method should therefore be viewed as a procedure for targeting teacher trajectories, not a guarantee of improvement on every metric.
- The calibration target is still a proxy. Teacher-forced BF16 traces expose realistic contexts, but they do not make the student generate the same continuation. The procedure matches the teacher's distributions and uses source balance; it does not directly optimize task answers.
- Scale-only refinement leaves code error fixed. After GPTQ, the end-to-end phase can move group scales but cannot change integer codes, group size, or the serving kernel. A poor code choice that survives the sequential pass cannot be repaired by the final optimizer.
- The format-aware search is approximate. The signed scale search uses a finite magnitude grid, and w4a8 chooses neighbouring FP8 values before restoring the row maximum. These choices make the search tractable but do not guarantee the globally best kernel-effective scales.
- The method depends on calibration availability and time. Generation, sequential reconstruction, and refinement consume the build budget. When traces are unavailable or little time remains, the driver falls back to corpus text or searched-scale round-to-nearest, which can omit the self-generated-trajectory matching stages.
- Development evidence is incomplete. Those claims motivate the design and are explicitly kept separate from the per-setting means reported in the results table.
References
- Elias Frantar, Saleh Ashkboos, Torsten Hoefler et al. (2023). GPTQ: Accurate Post-Training Quantization for Generative Pre-trained Transformers. ICLR.
- Ji Lin, Jiaming Tang, Haotian Tang et al. (2023). AWQ: Activation-aware Weight Quantization for LLM Compression and Acceleration.
- Saleh Ashkboos, Amirkeivan Mohtashami, Maximilian L. Croci et al. (2024). QuaRot: Outlier-Free 4-Bit Inference in Rotated LLMs. NeurIPS.
- Zechun Liu, Changsheng Zhao, Igor Fedorov et al. (2025). SpinQuant: LLM quantization with learned rotations. ICLR.
- Wenhua Cheng, Weiwei Zhang, Haihao Shen et al. (2023). Optimize Weight Rounding via Signed Gradient Descent for the Quantization of LLMs.
- Alireza Dadgarnia, Soroush Tabesh, Mahdi Nikdan et al. (2026). GSQ: Highly-Accurate Low-Precision Scalar Quantization for LLMs via Gumbel-Softmax Sampling. NeurIPS.
- Ruikang Liu, Yuxuan Sun, Manyi Zhang et al. (2025). Quantization Hurts Reasoning? An Empirical Study on Quantized Reasoning Models. COLM.