Introduction
Post-training quantization must choose integer codes and group scales while preserving the behavior of a full-precision model. Sequential quantization makes this harder because later layers receive activations produced by an already quantized prefix. Activation quantization adds another source of mismatch, and long reasoning chains amplify small distribution errors. We therefore make the calibration objective reflect the deployed computation: the quantized stream is propagated through the prefix, while a full-precision stream supplies the target.
The method combines layerwise reconstruction with function-preserving transformations and output-distribution calibration. The available references include GPTQ [1], activation-aware quantization [2], rotated inference [3], learned rotations [4], learned rounding [5], quantized reasoning models [6], and Gumbel-softmax code learning [7].
Method
Prefix-aware calibration and grid-aware scales
For each target linear layer, the procedure collects inputs from a quantized prefix and a full-precision prefix. In the activation-quantized path, inputs are passed through the actual FP8 quantizer before moments are accumulated. The code forms a Hessian-like matrix from the quantized inputs and a cross-moment matrix between full-precision and quantized inputs. When a cross-state mode is enabled, it solves a damped Cholesky system and uses the resulting target; otherwise the target is the original weight.
Group scales are initialized from absolute maxima or, in the submitted W3 path, through a Hessian-weighted Lloyd loop. Each iteration rounds codes on the deployed effective scale, computes a closed-form scale candidate, and accepts it only when the exact quadratic reconstruction loss decreases. The source also provides residual Newton refinement and optional code or sign refinement.
def group_blocks(h, g):
ng = h.shape[0] // g
return h.view(ng, g, ng, g).permute(0, 2, 1, 3).diagonal(dim1=0, dim2=1).permute(2, 0, 1).contiguous()
def initial_scales(target, h, fmt):
stored = formats.absmax_scales(target, fmt)
if os.environ.get("DEV_SCALE", "absmax") == "absmax":
return stored
rows, cols = target.shape
g = fmt.group_size
ng = cols // g
tg = target.view(rows, ng, g)
hb = group_blocks(h, g)
th = torch.einsum("ogi,gij->ogj", tg, hb)
for _ in range(int(os.environ.get("DEV_LLOYD", "4"))):
effective = formats.kernel_effective_scales(stored, fmt)
codes = torch.clamp(torch.round(tg / effective[..., None]), fmt.qmin, fmt.qmax)
ch = torch.einsum("ogi,gij->ogj", codes, hb)
num = (codes * th).sum(-1)
den = (codes * ch).sum(-1).clamp(min=1e-20)
ideal = num / den
valid = torch.isfinite(ideal) & (ideal > 0)
ratio = torch.where(valid, ideal / effective, torch.ones_like(ideal))
candidate = (stored.float() * ratio).to(fmt.scale_dtype).clamp(min=2.0 ** -100)
ce = formats.kernel_effective_scales(candidate, fmt)
c2 = torch.clamp(torch.round(tg / ce[..., None]), fmt.qmin, fmt.qmax)
ch2 = torch.einsum("ogi,gij->ogj", c2, hb)
num2 = (c2 * th).sum(-1)
den2 = (c2 * ch2).sum(-1).clamp(min=1e-20)
old_loss = effective.square() * den - 2 * effective * num
new_loss = ce.square() * den2 - 2 * ce * num2
accept = torch.isfinite(new_loss) & (new_loss < old_loss)
stored = torch.where(accept, candidate, stored)
if not accept.any():
break
return storeddef refine_scales(target, h, codes, stored, fmt):
rows, cols = target.shape
g = fmt.group_size
ng = cols // g
tg = target.view(rows, ng, g)
cg = codes.float().view(rows, ng, g)
hb = group_blocks(h, g)
ch = torch.einsum("ogi,gij->ogj", cg, hb)
den = (cg * ch).sum(-1).clamp(min=1e-20)
for _ in range(int(os.environ.get("DEV_REFINE_SWEEPS", "2"))):
effective = formats.kernel_effective_scales(stored, fmt)
residual = (tg - cg * effective[..., None]).reshape(rows, cols)
hr = (residual @ h).view(rows, ng, g)
num = (cg * hr).sum(-1)
direction = num / den
d = (cg * direction[..., None]).reshape(rows, cols)
a = (d * hr.reshape(rows, cols)).sum(-1)
dh = d @ h
b = (d * dh).sum(-1).clamp(min=1e-20)
alpha = (a / b).clamp(0, 1)
old_loss = (residual * hr.reshape(rows, cols)).sum(-1)
best_loss = old_loss
best = stored
for _ in range(3):
desired = (effective + alpha[:, None] * direction).clamp(min=2.0 ** -100)
candidate = (stored.float() * (desired / effective)).to(fmt.scale_dtype).clamp(min=2.0 ** -100)
ce = formats.kernel_effective_scales(candidate, fmt)
r2 = (tg - cg * ce[..., None]).reshape(rows, cols)
loss2 = (r2 * (r2 @ h)).sum(-1)
accept = torch.isfinite(loss2) & (loss2 < best_loss)
best = torch.where(accept[:, None], candidate, best)
best_loss = torch.where(accept, loss2, best_loss)
alpha *= 0.5
stored = best
if not (best_loss < old_loss).any():
break
effective = formats.kernel_effective_scales(stored, fmt)
q = (cg * effective[..., None]).reshape(rows, cols)
return q, storedFunction-preserving W4A8 rotation
The W4A8 branch applies a common orthogonal transformation across embedding, attention, and MLP projections, with matching left and right multiplications so the represented function is preserved before quantization. For the dense attention path it also applies a head-local transform to value and output projections. The default branch uses a fixed signed Hadamard matrix; a learned rotation can instead be supplied by the calibration procedure.
def right(lin, q):
w = lin.weight.data
lin.weight.data = (w.to(dev, torch.float64) @ q).to(w.dtype).cpu()
def left(lin, q):
w = lin.weight.data
lin.weight.data = (q.T @ w.to(dev, torch.float64)).to(w.dtype).cpu()
for layer in layers:
if is_gdn(layer):
la = layer.linear_attn
readers = [la.in_proj_qkv, la.in_proj_z, la.in_proj_a, la.in_proj_b]
else:
at = layer.self_attn
readers = [at.q_proj, at.k_proj, at.v_proj]
fuse(layer.input_layernorm, readers)
fuse(layer.post_attention_layernorm, [layer.mlp.gate_proj, layer.mlp.up_proj])
fuse(m.norm, [model.lm_head])
q = random_hadamard(d, dev) if learned_q is None else learned_q.to(dev, torch.float64)
e = m.embed_tokens.weight.data
m.embed_tokens.weight.data = (e.to(dev, torch.float64) @ q).to(e.dtype).cpu()
right(model.lm_head, q)
for li, layer in enumerate(layers):
if is_gdn(layer):
la = layer.linear_attn
for lin in (la.in_proj_qkv, la.in_proj_z, la.in_proj_a, la.in_proj_b):
right(lin, q)
left(la.out_proj, q)
else:
at = layer.self_attn
for lin in (at.q_proj, at.k_proj, at.v_proj):
right(lin, q)
left(at.o_proj, q)During layer calibration, the activation hook applies FP8 quantization before statistics and uses the quantized prefix to propagate states. This aligns the collected moments with the fixed serving kernel.
def fp8(x):
xf = x.float()
sa = (xf.abs().amax(-1, keepdim=True) / torch.finfo(torch.float8_e4m3fn).max).clamp(min=1e-12)
return ((xf / sa).to(torch.float8_e4m3fn).float() * sa).to(x.dtype)
def qhook(name):
def hook(_module, args):
x = fp8(args[0]) if ctx.fmt.act_fp8 else args[0]
xf = x.reshape(-1, x.shape[-1]).float()
xq[name] = xf
if MODE in ("local", "local_trust") and (not validate or i < ntrain):
raw = args[0].reshape(-1, args[0].shape[-1]).float()
cs[name].add_(raw.T @ xf, alpha=1.0 / (ntrain * seqlen))
if validate and i >= ntrain:
vhs[name].add_(xf.T @ xf, alpha=1.0 / ((n - ntrain) * seqlen))
else:
hs[name].add_(xf.T @ xf, alpha=1.0 / (ntrain * seqlen))
return (x,) + args[1:]
return hook
def fhook(name):
def hook(_module, args):
if MODE not in ("local", "local_trust"):
xf = args[0].reshape(-1, args[0].shape[-1]).float()
cs[name].add_(xf.T @ xq[name], alpha=1.0 / (n * seqlen))
return hook
def acthook(_module, args):
return (fp8(args[0]),) + args[1:]
for i in range(n):
handles = [lin.register_forward_pre_hook(qhook(name)) for name, lin in linears.items()]
kwargs = dict(attention_mask=None, position_ids=posids, position_embeddings=pos,
past_key_values=None)
layer(qstates[i:i + 1].to(dev), **kwargs)
for h in handles:
h.remove()Output-scale distillation and safeguards
For eligible formats, the procedure wraps quantized linear layers in an output-grid module whose trainable parameters are the logarithms of the group scales. The objective is the full vocabulary forward KL from a BF16 teacher distribution to the current quantized model:
When a candidate checkpoint is selected by the worst relative validation-domain loss, the code tests it on disjoint confirmation data. In the final source, a per-layer acceptance path can retain a candidate only when it improves the validation objective; a later artifact audit rejected one trajectory-dependent W3 output-distillation branch and retained the stable fallback. The core output objective and selection logic are:
def distill_output_scales(ctx, model, ids, codes, scales):
dev = ctx.device
if not ctx.fmt.act_fp8:
torch.manual_seed(0)
teacher = ctx.load_model().eval()
teacher.config.use_cache = False
teacher.requires_grad_(False)
if not ctx.fmt.act_fp8:
model = ctx.load_model().eval()
model.config.use_cache = False
model.requires_grad_(False)
for name in ctx.targets:
hf = ctx.to_hf(name)
parent_name, _, child = hf.rpartition(".")
parent = model.get_submodule(parent_name)
old = getattr(parent, child)
new = OutputGrid(codes[name], scales[name], ctx.fmt)
new.in_features = old.in_features
new.out_features = old.out_features
setattr(parent, child, new)
teacher.to(dev)
model.to(dev)
model.gradient_checkpointing_enable(gradient_checkpointing_kwargs={"use_reentrant": False})
params = [m.log_scale for m in model.modules() if isinstance(m, OutputGrid)]
default_lr = "0.00015" if ctx.fmt.act_fp8 else "0.0015"
lr = float(os.environ.get("DEV_DISTILL_LR", default_lr))
optimizer = torch.optim.Adam(params, lr=lr, betas=(0.9, 0.95), eps=1e-8)
ntrain = 3 * len(ids) // 4
train = ids[:ntrain] def objective(batch):
with torch.no_grad():
target = distributions(teacher, batch)
pred = distributions(model, batch)
return (target.exp() * (target - pred)).sum(-1).mean()
@torch.no_grad()
def validate(batches):
return sum(float(objective(batch)) for batch in batches) / len(batches)
initial_parts = [validate(batches) for batches in groups]
initial = sum(initial_parts) / 2
best = initial
best_score = 1.0
best_step = 0
initial_params = [p.detach().cpu().clone() for p in params]
best_params = [p.detach().cpu().clone() for p in params]
rng = random.Random(123)
steps = int(os.environ.get("DEV_DISTILL_STEPS", "400"))
for step in range(steps):
if ctx.time_left() < 180:
breakResults
| 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 ↑ | |
| Kimi K3.1 Pro | 0.552 | 0.644 | 0.560 | 0.738 | 0.798 | 0.640 | 0.210 | 0.212 | 0.564 | 0.258 | 0.381 | 0.591 |
| 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
Each reported metric is an accuracy, so higher is better. The strongest baseline depends on the setting and metric. On Model A W3A16, our math accuracy is 0.552 versus 0.556 for GPTQ + reasoning [6], while our science and instruction-following accuracies are 0.644 and 0.560. On Model A W4A8, our three values are 0.738, 0.798, and 0.640; on Model B W3A16 they are 0.210, 0.212, and 0.564; on Model B W4A8 they are 0.258, 0.381, and 0.591.
The procedure is above every listed baseline on science and instruction-following for Model A W3A16. It is also above every listed baseline on all three metrics for Model A W4A8. On Model B W3A16, it trails several baselines on science and math, although its instruction-following value is above every listed baseline. On Model B W4A8, it trails several baselines on math, science, and instruction following. These mixed comparisons motivate the per-format safeguards rather than a claim of universal dominance.
How we got here
The trace begins with prefix-aware calibration, because later layers see quantized activations. It then records several measured failures and simplifications. Unguarded cross-state least-squares compensation increased an independent KL diagnostic, and same-data trust selection overfit the calibration prefix. Local FP8 compensation also worsened the corresponding diagnostic. Mirrored scale signs were rejected, while a fixed rotated W4A8 path improved the local distribution diagnostic. A direct learned rotation improved that diagnostic at an intermediate checkpoint but worsened it when extended, so the shorter validated candidate was retained.
For W3, the trace reports that the Hessian-Lloyd scale procedure improved development accuracy and that larger calibration helped both architectures. An output-scale distillation variant later regressed on the exact final artifact; the source was reverted to a stable fallback for that branch. The trace also records a final per-layer branch for one of the two architectures and the retention of the stable W3 fallback. These are development-process facts from the trace, not additional test results.
The trace discusses ZeroQuant (arXiv:2206.01861), UPQ (arXiv:2506.09104), and Cross-Layer Error Compensation (arXiv:2607.14630) as related ideas, but none is cited here because none is among this task's verified references.
Limitations
- Performance varies by setting and metric; several references remain ahead on Model B W3A16 and Model B W4A8.
- The cross-state target is available in the implementation but the trace records that unguarded compensation and local FP8 compensation were rejected. The final behavior therefore relies on format-specific branches and safeguards.
- Output-scale distillation optimizes next-token distributions on calibration and confirmation text. That proxy need not predict long-chain accuracy, as shown by the rejected final W3 artifact.
- The procedure uses fixed calibration counts, sequence construction, rotation steps, and optimizer settings. These constants are source-level choices rather than a learned universal rule.
- The W4A8 rotation is function-preserving before quantization, but quantization and activation rounding still introduce approximation error.
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.
- Ruikang Liu, Yuxuan Sun, Manyi Zhang et al. (2025). Quantization Hurts Reasoning? An Empirical Study on Quantized Reasoning Models. COLM.
- Alireza Dadgarnia, Soroush Tabesh, Mahdi Nikdan et al. (2026). GSQ: Highly-Accurate Low-Precision Scalar Quantization for LLMs via Gumbel-Softmax Sampling. NeurIPS.