13.1 PTQ vs QAT
Seventy billion BF16 weights occupy 140 GB before serving a single token. At four bits per weight the raw payload would be 35 GB. Scales, unquantized layers, the KV cache and runtime buffers all add to that number. The first question for an engineer is whether the rounded weights still make the decisions that matter.
Post-training quantization (PTQ) converts an existing checkpoint. Quantization-aware training (QAT) lets an optimizer update weights while the forward pass simulates the target representation. Try the eight-weight example to see exactly where their forward and backward computations differ.
1. The Mathematics of Linear Quantization
Affine quantization uses a positive scale , an integer zero-point , and an integer interval from to . For a real scalar , compute the integer code and clamp it to that interval [2].
An integer kernel can accumulate quantized products before rescaling; other weight-only kernels dequantize before multiplication. The scalar reconstruction is:
The examples use a signed symmetric grid with . For bits set , choose codes through , and leave the most negative storage code unused. A positive bound sets the spacing . Zero is represented exactly. Halfway values round to the nearest even code, the convention used by PyTorch [3].
2. Post-Training Quantization (PTQ)
PTQ converts a pretrained checkpoint to a lower-precision representation. Methods range from rounding to data-driven error compensation and reconstruction; not all freeze every weight or require activation calibration. Weight-only and data-free methods also exist.
Scope of calibration
Static activation quantization estimates ranges from representative inputs. Record sample count, domain/length/language distribution and clipping objective. Distribution shifts can increase saturation and error, but do not inevitably cause catastrophic collapse. Inspect activation distributions, saturation, held-out evaluations and outputs from the actual kernel together.
Engineering the Calibration Loop
For a static per-tensor INT8 scale, the largest magnitude from all calibration batches matters. Suppose the first batch reaches 2.0 and the last reaches only 0.25. Replacing the scale at each batch would make even an ordinary 1.0 input saturate at 0.25. Running min/max observers retain extrema across batches [4].
CPU FP32 example. This simulates quantized inputs and weights in one frozen linear layer. The scale buffers travel with the checkpoint. Packing, integer kernels, per-channel scales, and a model-level evaluation are outside the example.
import torch
from torch import nn
class PTQLinear(nn.Module):
def __init__(self, in_features, out_features):
super().__init__()
self.weight = nn.Parameter(torch.randn(out_features, in_features))
self.bias = nn.Parameter(torch.zeros(out_features))
self.register_buffer("act_scale", torch.tensor(0.0))
self.register_buffer("weight_scale", torch.tensor(0.0))
@torch.no_grad()
def calibrate(self, x):
# Keep extrema across batches of the same frozen checkpoint.
if x.ndim < 1 or x.shape[-1] != self.weight.shape[1] or x.numel() == 0:
raise ValueError("expected a nonempty batch with the layer's input width")
peaks = torch.stack((x.abs().amax(), self.weight.abs().amax()))
if not torch.isfinite(peaks).all():
raise ValueError("nonfinite calibration data or weights")
scales = (peaks / 127).clamp_min(torch.finfo(self.weight.dtype).tiny)
self.act_scale.copy_(torch.maximum(self.act_scale, scales[0]))
self.weight_scale.copy_(scales[1])
def forward(self, x):
if self.act_scale.item() == 0:
raise RuntimeError("calibrate the layer or load its calibrated state")
weight_codes = (self.weight / self.weight_scale).round().clamp(-127, 127)
input_codes = (x / self.act_scale).round().clamp(-127, 127)
accumulated = nn.functional.linear(input_codes, weight_codes)
return accumulated * self.act_scale * self.weight_scale + self.bias
layer = PTQLinear(1, 1).eval()
with torch.no_grad():
layer.weight.fill_(1)
layer.calibrate(torch.tensor([[2.0]]))
layer.calibrate(torch.tensor([[0.25]]))
probes = torch.tensor([[1.0], [3.0]])
restored = PTQLinear(1, 1).eval()
restored.load_state_dict(layer.state_dict())
torch.testing.assert_close(restored(probes), torch.tensor([[128 / 127], [2.0]]))
The retained activation scale is . The restored layer maps 1.0 to and 3.0 to 2.0. A checkpoint containing only the weights and bias cannot reproduce this behavior. Use separate held-out inputs to measure saturation and task quality.
3. Quantization-Aware Training (QAT): The Active Approach
QAT keeps trainable weights in floating point and computes the training loss with simulated quantized values in the forward pass. An optimizer can change a weight enough to cross a rounding boundary. This costs training compute and data. Test whether the exported model recovers the failing capability under the same evaluation and deployment kernel.
The Straight-Through Estimator (STE)
Within each rounding interval a small change in the input leaves the reconstructed value unchanged. Its true derivative is zero there and undefined where the output jumps. A straight-through estimator (STE) supplies a surrogate gradient for training [1]. Here we choose a specific backward rule for a fixed scale. Write . Multiply the upstream gradient by 1 if and by 0 otherwise. This tests the rounded code, so an input slightly above the largest reconstructed value can still pass a gradient.
Engineering Fake Quantization with STE
CPU FP32 example. The forward and backward passes below exercise one weight quantizer. The layer estimates its scale from its detached weights. The eight-value test fixes the scale to expose the boundary. It omits a training loop, packed weights, learned scales, and deployment kernels.
import torch
from torch import nn
class RoundClampSTE(torch.autograd.Function):
@staticmethod
def forward(ctx, x, limit):
rounded = torch.round(x)
ctx.save_for_backward(rounded.abs() <= limit)
return rounded.clamp(-limit, limit)
@staticmethod
def backward(ctx, grad_output):
(in_range,) = ctx.saved_tensors
return grad_output * in_range, None
def fake_quantize(tensor, scale, bits=4):
limit = 2 ** (bits - 1) - 1
return RoundClampSTE.apply(tensor / scale, limit) * scale
class QATLinear(nn.Module):
def __init__(self, in_features, out_features, bits=4):
super().__init__()
if not 2 <= bits <= 8:
raise ValueError("this example supports 2 to 8 bits")
self.weight = nn.Parameter(torch.randn(out_features, in_features) * 0.02)
self.bias = nn.Parameter(torch.zeros(out_features))
self.bits = bits
def forward(self, x):
limit = 2 ** (self.bits - 1) - 1
scale = (self.weight.detach().abs().amax() / limit).clamp_min(torch.finfo(self.weight.dtype).tiny)
return nn.functional.linear(x, fake_quantize(self.weight, scale, self.bits), self.bias)
# A fixed calibration scale makes rounding and clamping visible separately.
w = torch.tensor([-2, -1.25, -0.75, 0, 0.25, 1.25, 1.6, 2.0], requires_grad=True)
reconstructed = fake_quantize(w, scale=0.5, bits=3)
reconstructed.sum().backward()
torch.testing.assert_close(reconstructed, torch.tensor([-1.5, -1, -1, 0, 0, 1, 1.5, 1.5]))
torch.testing.assert_close(w.grad, torch.tensor([0., 1., 1., 1., 1., 1., 1., 0.]))
Summing the reconstructions sends an upstream gradient of 1 to every row. Equal reconstructed values can then expose different gradient masks. The same fixture runs in the interactive table below.
4. Memory and Mixed-Precision Design
QAT’s memory cost depends on what is trainable, master-weight precision, optimizer state, activations, and whether fake-quantization intermediates are materialized or fused. It is not universally twice ordinary training or identical to LoRA. Account for parameters, gradients, optimizer states, activations, temporary buffers, collectives, checkpoints and evaluation separately; state precision, sharding, recomputation and sequence lengths.
Mixed precision allocates formats to tensors or layers based on measured sensitivity and kernel support. A learned quantization scale adjusts a grid; it does not by itself choose the bit-width. Early/final layers are useful candidates for sensitivity sweeps, not guaranteed exceptions. Compare model quality and realized runtime under the exact packed format and hardware, including cache precision separately from weight precision.
Pin base/tokenizer/template, calibration or tuning data manifests, objective, quantization granularity, optimizer/learning rate, trainable modules, response caps, reference identity or explicit absence, and the export kernel. Native-template SFT needs assistant masks, BOS/EOS and truncation/padding checks, variable-length reductions, and packed-sample isolation. Quarantine evaluations and retain provenance, licenses, filter versions, sample IDs and shard hashes.
Monitor token-normalized loss and domain/retention slices, nonfinite/overflow, gradient/activation norms, saturation and quantization error, throughput, MFU, data wait and collectives/stragglers with batch IDs. Stop on predeclared numerical or quality failures. Save full sharded training state, scheduler/scaler, RNG, sampler/data cursor and artifact hashes; export weights, scales, packing metadata and kernel requirements atomically with checksums. Rehearse restore and rollback, and gate the exported artifact on paired quality, safety, format/tools, latency, cost and errors. Fake-quantized training quality alone does not validate the deployed packed kernel.
Why does an FP4 expert have an I8 tensor?
As of 2026-11-25, Baidu publishes three open-weight editions of ERNIE 5.5 Flash Preview under Apache 2.0. The default pairs blockwise FP8 with MXFP4 routed experts. Follow the same expert weight, model.layers.1.block_sparse_moe.experts.0.w1.weight, through each edition’s safetensors index to its shard header. [5]
| Preview checkpoint | Storage dtype in header | Stored shape | Weight payload alone |
|---|---|---|---|
| Default [6] | I8 | 2048 × 1024 | 2 MiB |
| FP8 [7] | F8_E4M3 | 2048 × 2048 | 4 MiB |
| BF16 [8] | BF16 | 2048 × 2048 | 8 MiB |
The default packs two four-bit weights per byte, which explains the halved row width. Its companion w1.weight_scale_inv has shape 2048 × 64 and dtype F8_E8M0, adding 128 KiB of scales. You can inspect the default shard by requesting its first 256 KiB with Python’s standard library. [5] [6]
import json
from urllib.request import Request, urlopen
url = ("https://huggingface.co/baidu/ERNIE-5.5-Flash-Preview/resolve/"
"ace1100dcde7bf4eb06add6ae11ce4f43a11ddfe/model-00002-of-00128.safetensors")
with urlopen(Request(url, headers={"Range": "bytes=0-262143"}), timeout=30) as response:
header_bytes = int.from_bytes(response.read(8), "little")
header = json.loads(response.read(header_bytes))
key = "model.layers.1.block_sparse_moe.experts.0.w1.weight"
print(header[key]["dtype"], header[key]["shape"]) # I8 [2048, 1024]
This establishes how the weights were stored. For the training history, Baidu’s card reports W4A8 QAT for the routed experts during post-training, with fake quantization matched to the serving format. The card directs users without FP4 kernels to the FP8 or BF16 edition. To compare serving speed, run the same prompts and batch sizes on the target hardware. [5]
5. Interactive Component: Quantization Error Visualizer
At 3 bits and a reconstruction bound of 1.5, the seven codes run from −3 to 3 and the spacing is 0.5. Start with 1.25. Its scaled value is 2.5, so the even code 2 reconstructs as 1.0. Now compare 1.6 with 2.0. Both reconstruct as 1.5. Which one can pass a gradient in QAT?
Switch to QAT. The input 1.6 rounds to code 3 and passes a gradient of 1. The input 2.0 rounds to code 4, which clamps to 3 and blocks the gradient. The eight reconstructions stay the same in both modes. Two rounded codes are clamped and the weight mean squared error is 0.095. Changing the bit width or range recomputes every row. The table treats the displayed decimals as exact. A kernel using binary floating-point arithmetic may land just to one side of a nominal tie.
Same quantized value, different gradient
The 7 codes run from −3 through 3 at a grid spacing of 0.5000. Zero maps to zero. Halfway values round to the even code.
PTQ shows the actual derivative of the forward map. It is zero on a plateau and undefined at a jump. PTQ does not use it to train the weights.
| Input | Round | Clamp | Output | Derivative |
|---|---|---|---|---|
| -2 | -4 | -3 | -1.500 | 0 |
| -1.25 | -2 | -2 | -1.000 | undefined |
| -0.75 | -2 | -2 | -1.000 | undefined |
| 0 | 0 | 0 | 0.000 | 0 |
| 0.25 | 0 | 0 | 0.000 | undefined |
| 1.25 | 2 | 2 | 1.000 | undefined |
| 1.6 | 3 | 3 | 1.500 | 0 |
| 2 | 4 | 3 | 1.500 | 0 |
Codes changed by clamping 2 / 8 · Weight MSE 0.0950
6. Summary Comparison
| Feature | Post-Training Quantization (PTQ) | Quantization-Aware Training (QAT) |
|---|---|---|
| Complexity | Calibration and conversion; workload-dependent | Additional training or adaptation |
| Data Required | Representative calibration or data-free method, depending on algorithm | Representative adaptation data for the objective |
| Accuracy | Depends on format, calibration, model and task | Can recover some low-bit degradation; not guaranteed |
| Memory Overhead | Depends on calibration statistics, temporary tensors and method | Depends on trainable state and kernel implementation |
| Best Use Case | Compression with limited adaptation budget | Adaptation when PTQ misses the quality gate |
Section 13.2 examines where GPTQ and AWQ place rounding error, then shows how a container such as GGUF describes the stored tensors.
Quizzes
Quiz 1: Why does good performance on calibration data not establish deployment quality?
Static activation ranges may saturate or lose precision on unseen distributions. Check independent domain/length slices and the exported kernel. Not every PTQ method uses static activation calibration.
Quiz 2: What would ordinary backpropagation through the rounding operation do to a weight update?
On a plateau the exact derivative is zero. An STE supplies a different local derivative so optimization can move a weight across a grid boundary. Other gradient estimators are possible.
Quiz 3: What must be verified before selecting mixed precision?
Measure layer sensitivity, format metadata, kernel support, quality and latency. First and last layers are not universally the most sensitive, and uniform precision can simplify implementation and improve execution efficiency.
Quiz 4: How does QAT differ from PTQ, and why is it not always better?
QAT simulates quantization error during training so weights can adapt, while PTQ transforms already-trained weights. Benefits depend on data, budget, precision and kernels; evaluate quality and cost of the exported artifact.
Quiz 5: Why can 1.6 and 2.0 reconstruct identically and receive different gradients?
At scale 0.5 the rounded codes are 3 and 4. Only the latter exceeds the maximum code 3, so only its gradient is blocked by the chosen surrogate. The scale stays fixed during the backward pass.
References
- Bengio, Y., Léonard, N., & Courville, A. (2013). Estimating or Propagating Gradients Through Stochastic Neurons for Conditional Computation. arXiv:1308.3432.
- Jacob, B., et al. (2017). Quantization and Training of Neural Networks for Efficient Integer-Arithmetic-Only Inference. Paper.
- PyTorch. torch.round. Rounding convention.
- PyTorch. MinMaxObserver. Running calibration statistics.
- Baidu. ERNIE 5.5 Flash Preview. Model card · Quantization config · Preview weights license.
- Baidu. ERNIE-5.5-Flash-Preview. Tensor index · Weight shard.
- Baidu. ERNIE-5.5-Flash-Preview-FP8. Tensor index · Weight shard.
- Baidu. ERNIE-5.5-Flash-Preview-BF16. Tensor index · Weight shard.