Introduction
We study post-training quantization when the format, group size, scale type, activation representation, and serving kernel are fixed. The editable object is the conversion procedure: what data it calibrates on, which function-preserving transformations it applies, how it chooses scales and integer codes, and whether it tunes the exported representation against the original model. The starter procedure uses no calibration and rounds each weight with an absmax group scale. That baseline can match local weights while accumulating a damaging bias over a long chain of generated tokens.
Reasoning models make this accumulation especially visible. A calibration set that contains only short prompts can miss the transitions inside a complete thought and the final answer. A weight error that looks small in a layerwise norm can change a later token distribution, which then changes every subsequent hidden state. The procedure therefore needs a sequence-aware objective while still respecting the exact low-precision arithmetic of both supported formats.
The field offers complementary tools for these problems. GPTQ provides accurate post-training quantization [1]; AWQ is activation-aware weight quantization [2]; QuaRot addresses outliers with rotations [3], while SpinQuant uses learned rotations [4]; AutoRound optimizes weight rounding with signed gradients [5]; and GSQ uses Gumbel-Softmax sampling for low-precision scalar quantization [6]. An empirical study of quantized reasoning models reports that quantization can hurt reasoning [7], motivating calibration that contains reasoning traces rather than treating all tokens alike. PrismPTQ combines these themes, then adds checks that keep every transform and later refinement tied to the fixed serving grid.
Method
Calibration and function-preserving preparation
We build a BOS-aligned tensor of 256 sequences of length 2048. The source classifier separates reasoning, chat, and prose corpora. When time permits, native model generations supply some windows; the remainder mixes offline reasoning traces, instruction or multi-turn chat, and general or STEM prose. Packing keeps both complete shorter traces and prefixes of longer traces, preserving the reasoning delimiters, final answer, and end token whenever they fit.
def build_calib_tokens(
ctx, tok, n_samples: int, seq_len: int, seed: int = 0, cfg: dict | None = None
) -> torch.Tensor:
"""Build BOS-aligned multi-domain sequences [n_samples, seq_len] blending:
- Up to 50% on-policy native BF16 thinking trajectories (Math + STEM + IF) when budget permits
- Curated offline reasoning (<think>...</think> + answer), multi-turn IF/chat, and STEM prose.
"""
rng = random.Random(seed)
reas_corpora, chat_corpora, prose_corpora = _classify_calib_corpora(ctx, seed)
seqs: list[list[int]] = []
sg_mode = cfg.get("use_selfgen_calib", False) if cfg is not None else False
do_selfgen = (sg_mode is True) or (sg_mode == "auto" and len(reas_corpora) == 0)
if cfg is not None and do_selfgen and ctx.time_left() > 1800.0:
try:
seqs.extend(_collect_selfgen_sequences(ctx, tok, reas_corpora, chat_corpora, seq_len, cfg, seed))
except Exception as exc:
ctx.log(f"self-gen calib skipped ({type(exc).__name__}: {exc}); falling back to offline corpora")
n_off = n_samples - len(seqs)
n_reas = int(round(n_off * 0.45))
n_chat = int(round(n_off * 0.35))
def collect_chat_corpus(corpus: str, target_count: int, sample_seed: int):
if target_count <= 0:
return []
recs = ctx.calib_records(corpus, n=min(max(target_count * 8, 400), 3000), seed=sample_seed)
rng.shuffle(recs)
id_lists: list[list[int]] = []
for r in recs:
txt, has_chat = _format_reasoning_record(tok, r)
ids = tok.encode(txt, add_special_tokens=False)
if not has_chat and tok.bos_token_id is not None and (not ids or ids[0] != tok.bos_token_id):
ids = [tok.bos_token_id] + ids
id_lists.append(ids)
return _pack_token_lists(tok, id_lists, seq_len, target_count)Before quantization, we fuse RMSNorm factors into their adjacent linear maps and apply an orthogonal transform when the architecture permits it. The global transform is built from a Hadamard matrix and the eigenspace of observed activations; a per-head Hadamard transform is applied to value and output paths. Data-driven channel equalization then transfers a diagonal scale between paired maps, such as an MLP reader and writer or a value and output projection. For the FP8-activation format, the scale objective includes both weight-grid error and dynamic per-token activation error. The continuous scale search is centered at the identity and constrained to keep the function unchanged.
Every candidate transform is checked by comparing logits from a short probe of the original and transformed BF16 model. We keep it only when the mean KL is at most ; otherwise the source reloads clean weights and tries a less aggressive fallback. This turns rotations and equalization into reversible preprocessing rather than an unverified source of drift.
use_cont = bool(allow_continuous and cfg.get("use_cont_equalize", True))
signed_sc = bool(cfg.get("use_signed_scales", True))
for idx, layer in enumerate(layers):
kind, m_readers, q_readers, m_writer, mlp_readers, mlp_writer = _classify_layer(layer)
# 3A. SwiGLU up_proj / gate_up_proj <-> down_proj channel equalization
if cfg["use_smooth_mlp"] and idx in down_sq:
mlp = layer.mlp
dn = mlp_writer
inter_dim = dn.weight.shape[1]
has_split_up = hasattr(mlp, "up_proj") and mlp.up_proj.weight.shape[0] == inter_dim
has_fused_gu = (
not has_split_up
and hasattr(mlp, "gate_up_proj")
and mlp.gate_up_proj.weight.shape[0] == 2 * inter_dim
)
if has_split_up or has_fused_gu:
w_dn = _read_master_f64(dn, fp32_master, dev)
h_dn = (down_sq[idx].to(dev, torch.float64) / max(1, stat_tokens)).to(torch.float32)
if use_cont:
xs_dn = down_sub[idx].to(dev, torch.float32) if (is_fp8 and idx in down_sub) else None
s = _solve_optimal_col_scale(
[w_dn.float()], h_dn, xs_dn, ctx.fmt, signed_sc, w_dn.shape[1], s_bounds=(0.4, 2.5)
)
else:
if is_fp8:
act_s = down_amax[idx].to(dev, torch.float64).clamp(min=1e-5)
wt_s = w_dn.abs().amax(dim=0).clamp(min=1e-5)
s = (act_s.pow(0.5) / wt_s.pow(0.5)).clamp(min=0.25, max=16.0)
else:
act_rms = h_dn.to(torch.float64).sqrt().clamp(min=1e-6)
s = (act_rms / act_rms.median().clamp(min=1e-6)).pow(0.30).clamp(min=0.5, max=8.0)
s = s / s.log().mean().exp()
s = torch.pow(2.0, torch.round(torch.log2(s.clamp(min=0.25, max=16.0))))Saliency-weighted statistics and group quantization
When the saliency pass runs, we estimate a token weight for each layer from end-loss sensitivity. Let be the top- teacher logits. The source draws a Gaussian cotangent and forms the exact multinomial Fisher vector
It mixes with , backpropagates the resulting scalar through the model, and records the squared hidden-state gradient. A three-token smoothing step reduces single-draw noise. For layer , sequence , and token , the final weight is
renormalized to mean one. These weights multiply both sides of the activation Gram matrices, so tokens that matter more to the end distribution influence the quantizer more strongly. If the saliency pass fails, the code falls back to uniform weights.
For one linear map, let be the activation after the exact format's activation quantizer and its BF16 counterpart. We accumulate
After symmetrization and damping, the cross-activation target is
with and . Each row's correction is clipped to at most one quarter of its original norm, with a small floor for near-zero rows. We sort groups by the trace of their diagonal curvature and sort columns inside each group, while restoring the original order before export. Thus every contiguous group of 128 remains a legal serving group.
def quantize_linear_prism(
W_orig: torch.Tensor, # [out, in] bfloat16/float32 on GPU
H_raw: torch.Tensor, # [in, in] float64 on GPU: (1/M) X_tilde^T X_tilde
G_raw: torch.Tensor, # [in, in] float64 on GPU: (1/M) X_tilde^T X_fp
fmt: formats.FormatSpec,
cfg: dict,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor | tuple[torch.Tensor, torch.Tensor]]:
"""Quantize one Linear layer using:
1. Exact Cross-Activation Drift Target W* = W + gamma * W (G - H)^T H_damped^-1
2. Group-Sorted + Intra-Group-Sorted Hessian Permutation (preserves contiguous g=128 hardware groups!)
3. Interleaved Signed PiSO Scale Optimization + Exact-Hardware-Grid Cholesky OBS Diffusion
4. Monotonic Block Coordinate Descent (CD) Polish on Exact Hardware Codebook.The scale search is signed and format-specific. For w3a16, each code is with a BF16 group scale. For w4a8, the source evaluates the exact FP8 E4M3 dynamic activation path and the signed INT4 codebook, retaining a row anchor so each row's groups share a representable activation scale. Within each group, Cholesky OBS error diffusion rounds a column, updates the remaining columns, and carries the residual into later groups. Two strict coordinate-descent sweeps accept only code or scale changes that lower the local quadratic objective; a closed-form BF16 scale update is used when codes are fixed.
if use_obs_sc:
sc_b = _search_group_scales_obs_w3a16(
W_blk, H_inv_blk, fmt.qmin, fmt.qmax, cfg["use_signed_scales"]
)
else:
sc_b, _, _ = _search_group_scales_w3a16(
W_blk, H_blk, fmt.qmin, fmt.qmax, cfg["use_signed_scales"]
)
scales_p[:, b] = sc_b
sc_b_f = sc_b.float()
else:
is_anc = (anchor_grp_perm == b)
if use_obs_sc:
sc_b, q2_b = _search_group_scales_obs_w4a8(
W_blk, H_inv_blk, row_r, is_anc, int4_grid, cfg["use_signed_scales"]
)
else:
sc_b, q2_b, _ = _search_group_scales_w4a8(
W_blk, H_blk, row_r, is_anc, int4_grid, cfg["use_signed_scales"]
)
scales_p[:, b] = sc_b
q2_p[:, b] = q2_b
chan_s_col = row_r * 8.0
Err_blk = torch.empty_like(W_blk)
for j in range(gs):
w_col = W_blk[:, j]
d_jj = H_inv_blk[j, j].clamp(min=1e-12)
if not is_w4a8:
q_code = torch.clamp(torch.round(w_col / sc_b_f), fmt.qmin, fmt.qmax).to(torch.int8)
w_q = (q_code.float() * sc_b_f).to(torch.bfloat16).float()
else:
q_code, w_q = _round_to_w4a8_codebook(w_col, q2_b, chan_s_col, int4_grid)
codes_p[:, c0 + j] = q_code
W_hat_p[:, c0 + j] = w_q
err_col = (w_col - w_q) / d_jj
Err_blk[:, j] = err_col
if j + 1 < gs:
W_blk[:, j + 1 :] -= err_col[:, None] * H_inv_blk[j, j + 1 :][None, :]Causal refinement and sequence-level tuning
We propagate a BF16 hidden-state stream and a quantized hidden-state stream through the network in causal passes. A runtime equality check enables a fast attention/MLP decomposition only when it is exactly equivalent; otherwise a generic wave-by-wave path handles post-normalization, parallel branches, and other layer layouts. With the default setting, at each block we reset the quantized input to the BF16 block input, which prevents nonlinear drift from earlier approximate blocks from corrupting the current calibration statistics.
After the layerwise solve, when a block has targets and sufficient time, a differentiable hardware simulator temporarily replaces each target linear. It optimizes group scales against the current block output and, when available, a frozen next-block output with a SmoothL1 loss. A held-out portion of the block windows is evaluated at two checkpoints, and only the best hard codes and scales are retained. This is a local lookahead that can repair nonlinear interactions without relaxing the serving representation.
When enabled and the time guard allows it, we cache top-512 logits from the untouched BF16 teacher on a trailing slice of calibration windows. For logits and student logits , the sequence loss is
The scale pass updates only logarithmic scales with AdamW and a cosine schedule, retaining the best held-out value and backing off the learning rate if the initial pass fails to improve it. The discrete pass collects gradients and diagonal K-FAC-like curvature for each target linear, scores one-step integer-code flips by
uses a base relative trust radius of for each target linear, with validation line search scaling it, and accepts a round only after validation. A lower-rate scale polish follows this discrete pass.
def _kl_top_mix(z_s: torch.Tensor, z_t: torch.Tensor) -> torch.Tensor:
lp_t1 = F.log_softmax(z_t, dim=-1)
lp_s1 = F.log_softmax(z_s, dim=-1)
kl1 = (lp_t1.exp() * (lp_t1 - lp_s1)).sum(dim=-1)
lp_t2 = F.log_softmax(z_t * 0.5, dim=-1)
lp_s2 = F.log_softmax(z_s * 0.5, dim=-1)
kl2 = 4.0 * (lp_t2.exp() * (lp_t2 - lp_s2)).sum(dim=-1)
return 0.5 * kl1 + 0.5 * kl2
def _batch_loss(b0: int, b_len: int) -> torch.Tensor:
mb = e2e_ids[b0 : b0 + b_len].to(dev)
ti = t_idx_cpu[b0 : b0 + b_len].to(dev).long()
tv = t_val_cpu[b0 : b0 + b_len].to(dev).float()
Tm1 = ti.shape[1]
if chunked_head_ok:
hs = backbone(input_ids=mb, use_cache=False).last_hidden_state[:, :-1, :]
losses = []
for t0 in range(0, Tm1, 256):
t1 = min(Tm1, t0 + 256)
lg = model.lm_head(hs[:, t0:t1]).float()
zs = lg.gather(-1, ti[:, t0:t1])
losses.append(_kl_top_mix(zs, tv[:, t0:t1]).sum())
return torch.stack(losses).sum() / float(b_len * Tm1)
lg_all = model(input_ids=mb, use_cache=False).logits[:, :-1, :].float()
zs_all = lg_all.gather(-1, ti)
return _kl_top_mix(zs_all, tv).mean()Results
| Method | ① | ② | ③ | ④ | ||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Instruction following ↑ | Math accuracy ↑ | Science accuracy ↑ | Instruction following ↑ | Math accuracy ↑ | Science accuracy ↑ | Instruction following ↑ | Math accuracy ↑ | Science accuracy ↑ | Instruction following ↑ | Math accuracy ↑ | Science accuracy ↑ | |
| Gemini 4 Carbon | 0.607 | 0.667 | 0.720 | 0.610 | 0.754 | 0.780 | 0.577 | 0.246 | 0.343 | 0.617 | 0.270 | 0.389 |
| GPTQ | 0.430 | 0.218 | 0.417 | 0.633 | 0.524 | 0.689 | 0.512 | 0.188 | 0.308 | 0.617 | 0.240 | 0.356 |
| GPTQ + Liu et al. | 0.530 | 0.556 | 0.604 | 0.597 | 0.726 | 0.740 | 0.447 | 0.238 | 0.260 | 0.612 | 0.266 | 0.369 |
| AWQ | 0.203 | 0.020 | 0.215 | 0.577 | 0.544 | 0.616 | 0.344 | 0.077 | 0.199 | 0.604 | 0.260 | 0.369 |
| QuaRot + GPTQ | 0.540 | 0.516 | 0.586 | 0.593 | 0.702 | 0.740 | 0.451 | 0.194 | 0.290 | 0.597 | 0.260 | 0.389 |
| SpinQuant | 0.467 | 0.405 | 0.581 | 0.560 | 0.663 | 0.707 | 0.447 | 0.200 | 0.237 | 0.604 | 0.254 | 0.366 |
| AutoRound | 0.477 | 0.262 | 0.551 | 0.590 | 0.532 | 0.715 | 0.530 | 0.196 | 0.275 | 0.590 | 0.252 | 0.381 |
| GSQ | 0.530 | 0.345 | 0.518 | 0.607 | 0.667 | 0.740 | 0.035 | 0.119 | 0.182 | 0.625 | 0.278 | 0.386 |
- ① 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
The fixed table reports the per-setting means. On Model A W3A16, our instruction-following, math, and science values are respectively 0.607, 0.667, and 0.720; the corresponding best published values are 0.540, 0.556, and 0.604. Our values are higher on every metric. On Model A W4A8, our values are 0.610, 0.754, and 0.780, versus best published values 0.633, 0.726, and 0.740. The math and science means are higher, while instruction following trails the strongest baseline.
On Model B W3A16, PrismPTQ reaches 0.577, 0.246, and 0.343, compared with best published values 0.530, 0.238, and 0.308. Each of our means is higher than the corresponding best baseline. On Model B W4A8, our values are 0.617, 0.270, and 0.389; the best published values are 0.625, 0.278, and 0.389. We trail on instruction following and math and tie the best published science value.
How we got here
The trace records a sequence of fixes and tests. We first corrected per-layer keyword capture for hybrid attention, advanced the BF16 state after the last causal wave, and preserved transformed remainder tensors. A faster implementation then replaced double-precision Gram accumulation with single-precision matrix multiplication; a high-dynamic-range output projection triggered a Cholesky LinAlgError. The submitted implementation uses double-precision accumulation and progressive damping. We next verified the runtime decomposition before using it, fixed activation of gradient checkpointing for top-level decoder layers, and calibrated the refinement rates to the representable grids.
Later iterations added continuous channel equalization, Fisher token saliency, native generation, and multi-round K-FAC discrete steps. The trace records each as a tested addition before the submitted source was finalized. The submitted code retains these pieces and the validation gates; the trace's development measurements are not part of the published per-setting means.
Limitations
The method is computationally heavy. It may generate native calibration traces, run a Fisher backward pass, store CPU hidden states, form double-precision Gram matrices, and perform validation passes for every block before the final teacher-logit tuning. Time-left guards can skip saliency, lookahead, or end-to-end refinements, so the exported procedure can differ across hardware budgets even with the same source.
The transform check is a probe-level KL test, not a proof of equivalence for every prompt. The saliency estimate uses randomized cotangent constructions and a bounded token weight, and the Hessian approximation is damped, block-structured, and processed in a fixed group order. Cholesky OBS and coordinate descent therefore provide a carefully scored local solution rather than a global optimum over all integer codes and scales.
The lookahead and teacher-logit objectives reuse calibration material, so they can overfit the chosen trace mixture. The generic path handles broader layouts, while the non-decoder fallback uses identity statistics and is therefore less tailored. The source also leaves code learning disabled during block lookahead, which limits how much that refinement can repair an imperfect integer assignment.
The results show where the remaining gap is. On Model A W4A8, instruction following is below the best published value; on Model B W4A8, instruction following and math are below their best published values even though science ties it. The method therefore does not dominate every metric on every setting.
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.