By Flatkey Editorial. Experiment run and documentation checked November 20, 2026.
Post-training quantization changes the numerical representation of a trained model. Before deploying it, separate three decisions: which tensors to quantize, how to choose their scales, and how to verify the resulting model. “INT8” alone does not answer any of them.
Start with a frozen floating-point checkpoint and an untouched evaluation set. Compare a weight-only variant with a calibrated weight-and-activation variant, keeping preprocessing and evaluation identical. Then test the exported model in the intended runtime and hardware. Numerical agreement and deployment performance need separate measurements.
This guide includes a small CPU experiment where two INT8 calibration sets produced exactly the same top-1 accuracy, yet very different output errors. It demonstrates a calibration failure signal without claiming GPU acceleration or LLM benchmark results.
What changes in post-training quantization?
Quantization maps a tensor onto a smaller set of representable values. In a simple symmetric weight scheme, each output channel has a scale s, an integer value is obtained by rounding weight / s, and the reconstructed value is integer × s. Values outside the selected range are clipped. Smaller steps reduce rounding error, while a range that is too narrow increases clipping.
The deployment choices differ:
| Approach | What is quantized? | Where do activation ranges come from? | What to verify |
|---|---|---|---|
| Weight-only | Selected weights; activations can remain floating point | Depends on the algorithm; activation data may still guide weight scales | Supported weight format, excluded layers and quality |
| Static weight-and-activation | Selected weights and activations | A separate calibration pass determines fixed ranges | Representative inputs, clipping and export coverage |
| Dynamic activation quantization | Weights and selected activations | Activation ranges are determined during inference | Runtime implementation and overhead |
| Quantization-aware training | Quantization effects are included during training or fine-tuning | Depends on the training recipe | Training data, optimization cost and final deployment path |
Weight-only does not mean calibration-free. Our simple weight-only example below derives scales directly from weights, but activation-aware methods can use calibration data while still exporting low-bit weights with floating-point activations. NVIDIA’s PTQ guide describes AWQ weight-only configurations alongside static and dynamic activation approaches. Choose the actual recipe, rather than inferring it from a bit-width label.
Input/output precision is another separate choice. Quantized weights and internal activations do not automatically mean that a model exposes integer inputs and outputs. Inspect the exported graph and runtime bindings.
Choose calibration data before looking at evaluation results
Calibration estimates the ranges or other statistics needed by a particular quantization recipe. It should reflect the inputs the deployed model will encounter: preprocessing, shapes, relevant classes or languages, and the distribution of typical and difficult requests.
Keep a manifest of sample identities and preprocessing. Use a separate evaluation set to judge the completed variant. If you repeatedly tune calibration, clipping thresholds or layer exclusions against the same evaluation results, that set becomes part of your development loop; retain a final untouched test set for the deployment decision.
A useful first comparison changes one factor at a time: the same checkpoint and bit widths, with a representative calibration set versus a deliberately mismatched set. Equal sample counts help isolate the distribution difference. They do not prove that the chosen count is sufficient.
For an LLM, extend the manifest to tokenizer revision, prompt format, sequence lengths and target languages. Do not assume a short English calibration corpus represents a long-context multilingual workload. Our experiment below uses image classification, so it does not establish suitable LLM calibration sizes or distributions.
A fixed-model CPU calibration experiment
We trained one small classifier, froze its weights, and applied the same quantization rules to that checkpoint. All variants used the same held-out images. No variant was retrained.
The environment was macOS 26.7.2 on arm64, Python 3.12.13, NumPy 2.5.5 and PyTorch 2.7.1, using one Torch CPU thread and deterministic algorithms. The model was a 64 → 32 → 10 multilayer perceptron with ReLU and 2,410 parameters. Training used Adam, learning rate 0.01, 120 full-batch epochs and seed 20261120.
The data came from the 1,797 images bundled with scikit-learn’s digits dataset: 8×8 grayscale inputs with pixel values divided by 16. We created a local, per-class split of 1,074 training examples, a 355-example calibration pool and 368 evaluation examples. These three sets have disjoint indices. This is a new split within scikit-learn’s bundled UCI test subset, not the original UCI training/test benchmark, and writer-level separation is not established.
We selected two 32-image calibration sets from the calibration pool:
- Representative: round-robin selection across all ten labels; labels 0 and 1 contribute four examples each, and the others three each.
- Deliberately biased: only digit 1, selecting its 32 lowest-total-intensity images. This changes both class and brightness distributions on purpose.
The two calibration sets overlap in 3 images; neither overlaps training or evaluation. We did not select the architecture, seed or training hyperparameters using evaluation accuracy.
The frozen checkpoint’s SHA-256 was:
a13142583821bc01828a876730c49c997e097fcc12584a5d58a2c312cfdc2195
Quantization rules and boundaries
Weights used symmetric, per-output-channel min-max quantization: [-127, 127] for INT8 and [-7, 7] for the optional INT4 comparison. Biases stayed FP32. Static activation quantization covered the nonnegative input and hidden ReLU output, using an unsigned range and a maximum measured during the FP32 calibration pass. Logits were not quantized. Rounding used NumPy’s nearest-even rint.
These were quantize/dequantize (QDQ) numerical simulations. We reconstructed floating-point tensors and ran FP32 matrix multiplications. This was not an INT8/INT4 inference kernel, packed-model export, GPU test or LLM evaluation. It measured no latency, throughput, resident memory or cost. The INT4 integers also occupied int8 containers in the script, so its arrays do not demonstrate packed 4-bit storage savings.
Actual results on the same 368 examples
Logit MSE is the mean squared difference from the FP32 output across all evaluation logits. “Changed predictions” counts disagreements with FP32, which differs from counting errors against labels.
| Variant | Correct | Top-1 accuracy | Changed predictions | Logit MSE vs FP32 |
|---|---|---|---|---|
| FP32 | 360/368 | 97.8261% | 0 | 0 |
| INT8 weight-only QDQ | 359/368 | 97.5543% | 1 | 0.00149148 |
| INT8 weights + static activations, representative | 358/368 | 97.2826% | 2 | 0.00239786 |
| INT8 weights + static activations, biased | 358/368 | 97.2826% | 2 | 0.04487497 |
| INT4 weight-only QDQ | 359/368 | 97.5543% | 3 | 0.25274768 |
| INT4 weights + static activations, representative | 359/368 | 97.5543% | 5 | 0.36190331 |
| INT4 weights + static activations, biased | 357/368 | 97.0109% | 5 | 0.37917545 |
The two INT8 static variants tied at 358 correct predictions. Their hidden calibration maxima differed: 6.30259228 for the representative set and 5.00206757 for the biased set. Dividing by 255 produced hidden scales of 0.02471604815 and 0.01961595124 respectively.
On evaluation, the representative variant clipped 11 of 11,776 hidden activation elements (0.0934%); the biased variant clipped 121 (1.0275%). Its smaller calibrated range left less room for unseen activations. The larger logit MSE exposes distortion that top-1 accuracy alone missed in this run.
This is an observation about one checkpoint and these samples. It does not prove that biased calibration always lowers top-1 accuracy, or that a lower MSE guarantees better application behavior. Some INT4 variants also tied or exceeded an INT8 variant’s accuracy here; 368 examples do not justify concluding that fewer bits improve a production model.
Reproduce the comparison
Save the complete script at the end of this article as experiment-ptq.py in a new working directory. It requires NumPy and PyTorch. A scikit-learn installation supplies the bundled dataset; the script itself reads its CSV without importing scikit-learn. Our run used the versions listed above, with scikit-learn 1.9.1 supplying the data file.
Copy the bundled data next to the script using an environment where scikit-learn is installed:
from pathlib import Path
import hashlib
import shutil
import sklearn
source = Path(sklearn.__file__).parent / "datasets" / "data" / "digits.csv.gz"
destination = Path("experiment-digits.csv.gz")
expected = "09f66e6debdee2cd2b5ae59e0d6abbb73fc2b0e0185d2e1957e9ebb51e23aa22"
def sha256(path):
return hashlib.sha256(path.read_bytes()).hexdigest()
if sha256(source) != expected:
raise ValueError("Dataset differs from this experiment; verify its source/version.")
if destination.exists():
if sha256(destination) != expected:
raise ValueError("Existing dataset differs; use a separate working directory.")
else:
shutil.copyfile(source, destination)
Run from that directory:
OPENBLAS_NUM_THREADS=1 OMP_NUM_THREADS=1 python experiment-ptq.py
The first run trains and writes experiment-checkpoint.json. Subsequent runs load that file, verify the dataset and split hashes, and evaluate the same weights. Keep the checkpoint when comparing variants. Outputs include the split indices, calibration ranges, quantization scales and per-variant metrics.
The compressed dataset SHA-256 used here was:
09f66e6debdee2cd2b5ae59e0d6abbb73fc2b0e0185d2e1957e9ebb51e23aa22
The split-file SHA-256 was:
43a8d284b2b44b96fb50fcae833e6f349debb20c5420361051d88f839ba7ada0
Replaying our frozen checkpoint reproduced the metrics and scales without changing its hash. Retraining on another CPU or library build may not produce bit-identical weights, even with the same seed. Record your checkpoint hash and compare variants within that run.
Turn the numerical check into a deployment decision
The next step is an actual export and runtime comparison. Use a record like this for each candidate:
| Record | Keep fixed or document explicitly |
|---|---|
| Model | Checkpoint revision/hash, architecture and baseline dtype |
| Inputs | Preprocessing or tokenizer revision, shapes and calibration manifest |
| Quantization | Weight/activation precision, granularity, ranges, exclusions and calibration method |
| Quality | Untouched evaluation identities, task metrics, changed outputs and relevant failure slices |
| Runtime | Export format, engine/version, hardware, actual selected kernels and floating-point fallbacks |
| Performance | Warm-up, batch/concurrency, input/output lengths, latency percentiles, throughput and memory measurement method |
Test the floating-point export first so conversion errors are distinguishable from quantization errors. Inspect layer coverage and fallbacks rather than accepting a filename that says “INT8.” If quality deteriorates, locate the first significant divergence, check preprocessing and calibration coverage, and consider different ranges or retaining sensitive operations at higher precision. Re-evaluate the resulting model; a configuration change is not proof of recovery.
For TensorFlow/LiteRT, check the current migration path before copying an older tutorial. As checked on November 20, 2026, Google’s post-training quantization guide warns that quantization during conversion is deprecated and directs users to export a float32 LiteRT model before using LiteRT Quantizer. The linked migration guidance should determine the supported implementation for your version.
For cloud LLM serving, weight precision, activation precision and KV-cache precision are separate settings. Quantizing weights alone does not establish total-memory savings or a latency improvement at your context length and concurrency. Use our vLLM quantization guide for runtime-format and deployment validation, and FP16 versus BF16 when choosing the floating-point baseline.
Post-training quantization becomes useful when the exact exported model meets your task’s quality and operating requirements. Choose the recipe with evidence from the target workload, and preserve the checkpoint, calibration manifest and evaluation conditions so the decision can be repeated.
If you need GPU capacity for a deployment comparison, contact Flatkey with your model revision, runtime, context length and concurrency requirements. Flatkey publishes this guide and sells GPU services; the CPU experiment above is an educational numerical study, not a service-performance promise. More related material is available in the Flatkey blog.
Complete reproduction script
The code below performs the local experiment described above. It retains floating-point arithmetic after QDQ and deliberately does not time its execution as a deployment benchmark.
#!/usr/bin/env python3
"""CPU-only PTQ numerical simulation; never an integer-kernel benchmark.
Run with existing numpy/torch or install those exact packages independently.
First run trains once; later runs load the frozen JSON checkpoint.
The experiment reads a local dataset and makes no network requests.
"""
from __future__ import annotations
import argparse
import gzip
import hashlib
import io
import json
import os
import platform
import shutil
import sys
from datetime import datetime, timezone
from pathlib import Path
import numpy as np
import torch
ROOT = Path(__file__).resolve().parent
SEED = 20261120
def sha(path):
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
def save(name, value):
path = ROOT / name
path.write_text(json.dumps(value, ensure_ascii=False, indent=2, sort_keys=True) + "\n")
return path
def qdq_weight(w, bits):
# A separate symmetric scale for each output channel. No bias quantization.
qmax = 2 ** (bits - 1) - 1
scale = np.maximum(np.abs(w).max(axis=0), np.finfo(np.float32).tiny) / qmax
q = np.clip(np.rint(w / scale), -qmax, qmax).astype(np.int8)
dq = q.astype(np.float32) * scale
return (
dq,
{
"bits": bits,
"range": [-qmax, qmax],
"axis": "output channel",
"scales": scale.tolist(),
"weight_mse": float(np.mean((w - dq) ** 2)),
},
)
def qdq_activation(a, maximum, bits):
# Input pixels and ReLU outputs are nonnegative, so zero point is exactly 0.
qmax = 2 ** bits - 1
scale = np.float32(max(maximum, float(np.finfo(np.float32).tiny)) / qmax)
clipped = np.count_nonzero((a < 0) | (a > maximum))
dq = np.clip(np.rint(a / scale), 0, qmax).astype(np.float32) * scale
return (
dq,
{
"clip_count": int(clipped),
"element_count": int(a.size),
"clip_rate": float(clipped / a.size),
"qdq_mse": float(np.mean((a - dq) ** 2)),
},
)
def forward(x, arrays):
w1, b1, w2, b2 = arrays
hidden = np.maximum(x @ w1 + b1, 0)
return hidden @ w2 + b2, hidden
def main():
p = argparse.ArgumentParser()
p.add_argument("--data", type=Path, help="Path to scikit-learn bundled digits.csv.gz; cached local file only")
a = p.parse_args()
local_data = ROOT / "experiment-digits.csv.gz"
if not local_data.exists():
if a.data is None or not a.data.is_file():
p.error("first run requires --data pointing to an existing local digits.csv.gz")
shutil.copyfile(a.data, local_data)
raw = gzip.decompress(local_data.read_bytes())
matrix = np.loadtxt(io.BytesIO(raw), delimiter=",", dtype=np.float32)
assert matrix.shape == (1797, 65)
x = matrix[:, :64] / np.float32(16)
y = matrix[:, 64].astype(np.int64)
assert np.all((x >= 0) & (x <= 1))
rng = np.random.default_rng(SEED)
train, pool, test = [], [], []
for label in range(10):
indexes = np.flatnonzero(y == label)
indexes = rng.permutation(indexes)
n1, n2 = int(len(indexes) * .60), int(len(indexes) * .20)
train.extend(indexes[:n1].tolist())
pool.extend(indexes[n1:n1+n2].tolist())
test.extend(indexes[n1+n2:].tolist())
assert not (set(train) & set(pool) or set(train) & set(test) or set(pool) & set(test))
assert len(train) + len(pool) + len(test) == len(y)
# Equal-size 32-example calibration sets, chosen without inspecting test data.
# Representative: label-balanced round-robin through the held-out cal pool.
by_label = {label: [i for i in pool if y[i] == label] for label in range(10)}
representative = [by_label[j % 10][j // 10] for j in range(32)]
# Deliberate bad calibration: only the 32 dimmest images of digit 1.
biased = sorted(by_label[1], key=lambda i: (float(x[i].sum()), i))[:32]
assert len(biased) == len(representative) == 32
assert set(representative) <= set(pool) and set(biased) <= set(pool)
split = {
"seed": SEED,
"algorithm": (
"numpy default_rng; per-label permutation; floor(60%) training, floor(20%) calibration "
"pool, remainder held-out evaluation"
),
"train": train,
"calibration_pool": pool,
"evaluation": test,
"representative_calibration": representative,
"biased_calibration": biased,
"calibration_set_overlap_count": len(set(representative) & set(biased)),
"bias_rule": (
"32 lowest total pixel-intensity examples with label=1 from calibration pool; no test-data "
"selection"
),
}
split_path = save("experiment-splits.json", split)
torch.set_num_threads(1)
torch.manual_seed(SEED)
torch.use_deterministic_algorithms(True)
checkpoint = ROOT / "experiment-checkpoint.json"
if not checkpoint.exists():
model = torch.nn.Sequential(torch.nn.Linear(64, 32), torch.nn.ReLU(), torch.nn.Linear(32, 10))
optimizer = torch.optim.Adam(model.parameters(), lr=.01)
xx, yy = torch.from_numpy(x[train]), torch.from_numpy(y[train])
losses = []
model.train()
for epoch in range(120):
optimizer.zero_grad()
loss = torch.nn.functional.cross_entropy(model(xx), yy)
loss.backward()
optimizer.step()
if epoch in (0, 29, 59, 89, 119):
losses.append({"epoch": epoch + 1, "train_cross_entropy": float(loss.detach())})
trained = {
"seed": SEED,
"architecture": "64->32 ReLU->10 logits",
"dtype": "float32",
"epochs": 120,
"optimizer": "Adam",
"learning_rate": .01,
"batch": "entire training split per update",
"loss_log": losses,
"data_sha256": sha(local_data),
"splits_sha256": sha(split_path),
"w1": model[0].weight.detach().numpy().T.tolist(),
"b1": model[0].bias.detach().numpy().tolist(),
"w2": model[2].weight.detach().numpy().T.tolist(),
"b2": model[2].bias.detach().numpy().tolist(),
}
save(checkpoint.name, trained)
frozen = json.loads(checkpoint.read_text())
assert frozen["data_sha256"] == sha(local_data)
assert frozen["splits_sha256"] == sha(split_path)
arrays = [np.asarray(frozen[k], dtype=np.float32) for k in ("w1", "b1", "w2", "b2")]
w1, b1, w2, b2 = arrays
evaluation = x[test]
fp_logits, _ = forward(evaluation, arrays)
fp_prediction = np.argmax(fp_logits, axis=1)
def metrics(logits):
pred = np.argmax(logits, axis=1)
changed = np.flatnonzero(pred != fp_prediction)
return {
"correct": int(np.count_nonzero(pred == y[test])),
"evaluation_examples": len(test),
"top1_accuracy": float(np.mean(pred == y[test])),
"changed_predictions_vs_fp32": int(len(changed)),
"changed_dataset_indices": [test[j] for j in changed],
"logit_mse_vs_fp32": float(np.mean((logits - fp_logits) ** 2)),
}
variants = [{"name": "FP32 baseline", **metrics(fp_logits)}]
calibration = {}
for name, selected in (("representative", representative), ("biased_digit1_low_intensity", biased)):
_, hidden = forward(x[selected], arrays)
calibration[name] = {
"indices": selected,
"examples": len(selected),
"class_counts": {str(label): int(np.count_nonzero(y[selected] == label)) for label in range(10)},
"input_max": float(x[selected].max()),
"hidden_relu_max": float(hidden.max()),
"source": (
"FP32 checkpoint forward pass over calibration examples only; evaluation data excluded"
),
}
weight_parameters = {}
for bits in (8, 4):
qw1, meta1 = qdq_weight(w1, bits)
qw2, meta2 = qdq_weight(w2, bits)
weight_parameters[str(bits)] = {"layer1": meta1, "layer2": meta2}
quantized_arrays = [qw1, b1, qw2, b2]
logits, _ = forward(evaluation, quantized_arrays)
variants.append({"name": f"INT{bits} weight-only QDQ", "activation_dtype": "float32", **metrics(logits)})
for cal_name, c in calibration.items():
xq, input_metrics = qdq_activation(evaluation, c["input_max"], bits)
h = np.maximum(xq @ qw1 + b1, 0)
hq, hidden_metrics = qdq_activation(h, c["hidden_relu_max"], bits)
logits = hq @ qw2 + b2
variants.append({
"name": f"INT{bits} weights + static activations QDQ / {cal_name}",
"input_scale": c["input_max"] / (2 ** bits - 1),
"hidden_scale": c["hidden_relu_max"] / (2 ** bits - 1),
"input_qdq": input_metrics,
"hidden_qdq": hidden_metrics,
**metrics(logits),
})
output = {
"ranAt": datetime.now(timezone.utc).isoformat(),
"experiment": (
"One frozen CPU-trained small digits MLP; symmetric per-output-channel weight QDQ and "
"unsigned per-tensor static activation QDQ"
),
"environment": {
"python": sys.version,
"numpy": np.__version__,
"torch": torch.__version__,
"platform": platform.platform(),
"machine": platform.machine(),
"processor": platform.processor(),
"torch_cpu_threads": torch.get_num_threads(),
"device": "CPU",
"deterministic_algorithms": True,
},
"dataset": {
"name": (
"scikit-learn bundled optical recognition digits, 1797 samples, 8x8 grayscale, 10 "
"classes"
),
"local_file": local_data.name,
"gzip_sha256": sha(local_data),
"decompressed_csv_sha256": hashlib.sha256(raw).hexdigest(),
"original_source": (
"UCI Optical Recognition of Handwritten Digits dataset: scikit-learn bundles the "
"original UCI test subset; this experiment creates its own three-way split within that "
"bundled subset"
),
"reference": (
"https://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_digits.html"
),
"preprocessing": "pixels/16 -> float32 [0,1]; no train/test-derived normalization statistics",
},
"split_counts": {
"train": len(train),
"calibration_pool": len(pool),
"evaluation": len(test),
"representative_calibration": len(representative),
"biased_calibration": len(biased),
},
"checkpoint": {
"file": checkpoint.name,
"sha256": sha(checkpoint),
"parameters": sum(v.size for v in arrays),
"training": {
k: frozen[k]
for k in (
"seed",
"architecture",
"dtype",
"epochs",
"optimizer",
"learning_rate",
"batch",
"loss_log",
)
},
},
"split_file": {"file": split_path.name, "sha256": sha(split_path)},
"calibration": calibration,
"weight_quantization": weight_parameters,
"variants": variants,
"limits": [
(
"Handwritten QDQ numerical simulation, not an actual INT8 or INT4 inference "
"kernel/export/runtime."
),
(
"All matrix multiplies and dequantized activations remain FP32; no latency, throughput,"
" memory-residency, GPU, LLM or production deployment claims."
),
(
"This is a local stratified split of the bundled 1797-example UCI test subset, not the "
"canonical original UCI train/test benchmark. Writer-level train/test separation is not"
" established."
),
(
"Biases remain FP32; symmetric weights use [-127,127] or [-7,7], unsigned activations "
"use [0,255] or [0,15]. Rounding uses numpy.rint nearest-even."
),
(
"Min-max calibration uses a single tensor maximum per input/ReLU tensor. Does not test "
"histogram/percentile calibration, per-token/channel activations, QAT, GPTQ/AWQ, "
"quantized bias/accumulation, or kernel layout effects."
),
(
"Both calibration sets have 32 examples and are disjoint from training and evaluation; "
"they may overlap each other. Biased set differs in label and intensity distribution on"
" purpose; it is an illustrative distribution-mismatch case, not a universal expected "
"PTQ penalty."
),
(
"No architecture, seed, threshold, or training hyperparameter selected using held-out "
"evaluation results. INT4 included as a predeclared lower-precision contrast, not a "
"deployment recommendation."
),
(
"An accuracy tie does not mean identical logits; clipping and logit MSE describe this "
"checkpoint only."
),
(
"Train once and reload exact checkpoint for all variants; dataset/split/checkpoint "
"hashes identify the run. Training reproducibility across CPU/library versions is not "
"guaranteed bit-for-bit."
),
],
}
result = save("experiment-results.json", output)
print(json.dumps({
"result_file": str(result),
"checkpoint_sha256": sha(checkpoint),
"split_counts": output["split_counts"],
"calibration_maxima": {
k: {
"input_max": v["input_max"],
"hidden_relu_max": v["hidden_relu_max"],
}
for k, v in calibration.items()
},
"variants": variants,
}, indent=2))
if __name__ == "__main__":
main()



