Quantize a matrix and measure what the rounding costs
Round a 256 by 256 matrix to symmetric int8, dequantize it, and separate the fourfold size saving from the error it introduces.
Quantization replaces a wide number format with a narrower one. The saving is easy to state: a float32 matrix of 65,536 values occupies 262,144 bytes; the same matrix in int8 occupies 65,536 bytes. The cost is also easy to state but harder to accept: every value is rounded, and the error depends on the scale.
This example uses symmetric per-tensor int8 quantization. One scale is chosen
from the largest absolute value, every element is divided by that scale, rounded,
clamped to [-127, 127], and later multiplied back. The page reports the maximum
and mean absolute reconstruction error. It does not claim that the quantized
model is faster or that its text is equivalent; those are separate experiments.
Run it
From the canonical repository at commit
f958967d70992d7b09d9c75000bd8c543f1644d4:
python examples/ch12/quantization.py --dtype int8 --size 256 --jsonPython 3.11 or later with PyTorch. CPU-only, seeded, no model download, network,
GPU or credentials. It finishes in well under a second. The --dtype option also
accepts fp16 and bf16 for comparison.
Implementation
The scale is max(abs(x)) / 127. Zero maps to zero, and the largest magnitude
maps to ±127. Dequantization is one multiply. This is the simplest scheme, not
a calibrated or per-channel one.
def quantize_symmetric_int8(tensor: torch.Tensor) -> Tuple[torch.Tensor, float]:
if tensor.numel() == 0:
raise ValueError("tensor must not be empty")
max_abs = float(tensor.abs().max().item())
if max_abs == 0:
scale = 1.0
else:
scale = max_abs / 127.0
q = torch.round(tensor / scale).clamp(-127, 127).to(torch.int8)
return q, scale
def dequantize_symmetric_int8(q: torch.Tensor, scale: float) -> torch.Tensor:
return q.to(torch.float32) * scale
def run(dtype: str, size: int = 256, seed: int = 0) -> QuantResult:
torch.manual_seed(seed)
x = torch.randn(size, size)
start = time.perf_counter()
if dtype == "int8":
q, scale = quantize_symmetric_int8(x)
y = dequantize_symmetric_int8(q, scale)
quantized_bytes = q.numel() * 1
elif dtype == "fp16":
y = x.to(torch.float16).to(torch.float32)
quantized_bytes = x.numel() * 2
elif dtype == "bf16":
y = x.to(torch.bfloat16).to(torch.float32)
quantized_bytes = x.numel() * 2
else:
raise ValueError(f"unsupported dtype: {dtype}")
seconds = time.perf_counter() - start
error = (x - y).abs()
return QuantResult(
dtype=dtype,
max_abs_error=float(error.max().item()),
mean_abs_error=float(error.mean().item()),
original_bytes=x.numel() * 4,
quantized_bytes=quantized_bytes,
seconds=seconds,
metadata={"size": size, "seed": seed},
)Expected outcome
Observed with the command above (exit 0). Selected stable fields:
"dtype": "int8",
"max_abs_error": 0.017963290214538574,
"mean_abs_error": 0.009005710482597351,
"original_bytes": 262144,
"quantized_bytes": 65536,The matrix shrank by exactly four times. The largest reconstruction error was
about 0.018, the mean about 0.009, on values drawn from a standard normal
distribution. The seconds field is omitted because it measures the conversion
loop in this process, not inference speed.
Mechanism and limitations
Documented: the quantizer rejects an empty tensor, chooses scale from the
maximum absolute value, rounds and clamps to the int8 range, and dequantizes with
one multiply. run supports int8, fp16 and bf16 and rejects anything else. The
tests check round-trip shape, finite int8 error, fp16 error below 1e-2, bf16
error below 0.1, invalid dtype, empty input and JSON serialisation.
Observed: the command exited 0 with the fourfold byte reduction and the errors
above. The targeted tests.test_ch12_quantization is part of the canonical suite;
no independent test count is claimed here.
Not shown: model-level quality, perplexity, task accuracy, throughput, memory bandwidth or kernel support. A random normal matrix is not a weight matrix with outliers, and per-tensor scaling is the weakest granularity. The conversion time is not an inference benchmark. A fourfold size reduction does not imply a fourfold speedup; the arithmetic may still run in a wider format.
Challenge this result
Make the matrix mostly small values with one large outlier, for example by
setting x[0, 0] = 100. Predict what happens to the scale, the large value’s
error and the small values’ errors. Then run --dtype fp16 and --dtype bf16
and compare both error and bytes. Explain why bf16 keeps a wide exponent but
loses mantissa bits, and why that trade-off can matter more for activations than
for weights.
Source and verification
Canonical source:
examples/ch12/quantization.py
at commit f958967d70992d7b09d9c75000bd8c543f1644d4. Tests:
tests/test_ch12_quantization.py
.
Chapter: Quantization and Numerical Precision
.
The run above is a fresh local execution on Windows 11 with Python 3.13.15 and
PyTorch 2.6.0+cu124; it quantizes random tensors, not a model.
Understand this example
Copy this prompt into your AI tool. No code runs here.
Apply this example
Copy this prompt into your AI tool. No code runs here.