Level 3 In-Depth AI · ML Engineering and Production
Quantization
Store a model's numbers with fewer bits — 8, 4, sometimes fewer, instead of 32 or 16 — so it takes a fraction of the memory and runs faster, usually with little loss in quality. Number formats, the scale-and-round recipe, per-channel and group quantization, and the methods (GPTQ, AWQ, GGUF, NF4) used to shrink large language models.
- Level
- ●●●●● Intermediate
- Reading
- 15 min
- To learn it well
- 1 hour to read, an afternoon to practise
- Builds on
- 15 concepts →
- Quiz
- 5 questions ↓
This leads to
Running Models LocallyThe full path from zero — 15 concepts before this one
- What Is AI?
- Vectors
- Derivatives and Slopes
- Probability Basics
- How Machines Learn
- Matrices and Matrix Multiplication
- Partial Derivatives and Gradients
- Supervised, Unsupervised and Reinforcement Learning
- Tensors and Shapes
- Gradient Descent
- Supervised Learning
- Linear Regression
- The Perceptron
- Logistic Regression
- Neural Networks
- Quantization
Read them roughly in this order. See it on the concept map →
Why it matters
A neural network is mostly a huge collection of numbers, its weights. Each one is traditionally stored as a 32-bit floating-point number, which takes 4 bytes. A model with 70 billion parameters therefore needs 280 GB just to hold its weights. That is more than three of the largest data-centre GPUs, and far more than any laptop.
Quantization stores each number with fewer bits. In 16 bits the same model needs 140 GB, in 8 bits 70 GB, and in 4 bits about 35 GB, which fits on a single 48 GB GPU or a high-end laptop. The model loses a little precision, much as a photo saved at a lower JPEG quality loses some detail. For most models the loss at 8 bits is barely measurable, and at 4 bits it is usually small.
Smaller numbers are also faster. Generating text with a language model is limited mainly by how fast the weights can be read from memory, not by arithmetic (GPUs and Why AI Needs Them). Halve the bytes and you roughly halve the time per token. That is why almost every model you run on your own machine (Running Models Locally) is quantized, why phones can run models at all, and why serving companies quantize to cut costs (Serving LLMs at Scale). Quantization also made fine-tuning big models on a single GPU possible (QLoRA).
The intuition
Imagine recording everyone's height to the nearest micrometre. That precision is pointless: nobody's height is meaningful to a millionth of a metre. Rounding to the nearest centimetre loses nothing that matters, and each number needs far fewer digits.
Neural network weights are similar. Training needs fine precision, because millions of tiny updates must add up. But the finished model is surprisingly tolerant of rounding. Each weight's small error is one of thousands of errors that get added together in every neuron, and these errors tend to cancel rather than accumulate.
Quantization is rounding onto a coarse grid. With 8 bits you have grid points (levels), with 4 bits just 16. The art is placing those few levels where the weights actually are.
Key idea Quantization maps each weight to the nearest of a small number of evenly spaced levels, using a scale factor stored alongside. Fewer bits means less memory and faster inference. The main enemy is outliers: one extreme value stretches the grid and wastes most of the levels.
How it works
Number formats
Computers store real numbers as floating point: a sign, an exponent and a mantissa, like scientific notation (). The exponent bits decide the range (how large and how small a number can be). The mantissa bits decide the precision (how many significant digits).
| Format | Bits (sign / exponent / mantissa) | Bytes per number | Largest value | Rough precision |
|---|---|---|---|---|
| FP32 (single precision) | 1 / 8 / 23 | 4 | about | about 7 decimal digits |
| FP16 (half precision) | 1 / 5 / 10 | 2 | 65,504 | about 3 digits |
| BF16 (bfloat16) | 1 / 8 / 7 | 2 | about | about 2 digits |
| FP8 (E4M3 variant) | 1 / 4 / 3 | 1 | 448 | about 1 digit |
| INT8 | 8-bit integer | 1 | 127 (levels −128 to 127) | 256 even levels |
| INT4 | 4-bit integer | 0.5 | 7 (levels −8 to 7) | 16 even levels |
BF16 was designed by Google for deep learning: same range as FP32, so values almost never overflow, at the cost of precision. It is now the default format for training and storing large models (Mixed Precision Training). FP8 is supported by NVIDIA's H100 and later GPUs. Chips from NVIDIA's Blackwell generation (2025) onward also support 4-bit floating-point formats such as MXFP4 and NVFP4.
"Quantization" usually means going from 16 or 32 bits down to 8 bits or fewer, most often integers.
The recipe: scale, round, clip
To quantize a tensor of weights to signed integers with bits, symmetric quantization uses one scale factor chosen so that the largest weight lands on the largest level (127 for INT8, 7 for INT4):
In words: divide every weight by the scale, round to the nearest whole number, and store those small integers plus the one scale . To use the weights, multiply back: (read "w-hat") is the dequantized approximation of . The error for each weight is at most half a step, .
Worked example. Four weights: . The largest magnitude is 0.61, so . Dividing gives , which rounds to . Multiplying back: . The errors are at most 0.0022, less than half of . Each weight now takes 1 byte instead of 4.
Asymmetric quantization adds a zero point , an integer offset, so the grid can cover a range that isn't centred on zero: . That suits activations after a ReLU, which are never negative, so no levels are wasted on negative values. Weights are roughly symmetric around zero, so symmetric quantization is common for them.
Outliers and granularity
Because the scale comes from the largest value, a single outlier ruins the grid for everyone else. If one weight is 0.5 while the rest are around ±0.02, the step size becomes , and the typical weight uses only a handful of the 256 levels:
The fix is to use more scales, each covering fewer weights:
- Per-tensor: one scale for the whole matrix. Cheapest, most fragile.
- Per-channel quantization: one scale per row (output channel). An outlier only hurts its own row.
- Group-wise quantization (block-wise): one scale per small block, typically 32 to 128 consecutive weights. Standard for 4-bit LLM weights. With a 16-bit scale per 32 weights, the scales add bits per weight, so "4-bit" really costs about 4.5 bits.
In the code below, on a 256 × 256 matrix with one outlier, per-tensor INT8 has 5.7% relative error, per-row INT8 has 0.8%, and grouping INT4 into blocks of 32 cuts its error from 13.6% to 9.9%.
Large language models have a nastier version of the problem in their activations. Dettmers and colleagues (LLM.int8(), 2022) found that in transformers beyond about 6.7 billion parameters, a few hidden dimensions carry outlier features: values far larger than everything else, appearing in the same dimensions across most layers. Naive INT8 quantization of activations then breaks the model. Their fix kept those few dimensions in 16-bit and the rest in 8-bit.
When and how to quantize
- Post-training quantization (PTQ) quantizes a finished model without retraining. Often a small calibration set of a few hundred examples is run through the model to measure the ranges of activations. It is fast and is how nearly all LLMs are quantized.
- Quantization-aware training (QAT) simulates rounding during training (or a short fine-tune), so the model learns weights that survive it. It gives better quality at very low bit widths, at the cost of a training run.
- Weight-only quantization stores weights in 4 or 8 bits but dequantizes them to 16-bit on the fly for the arithmetic. It saves memory and bandwidth, which is what matters for LLM text generation.
- Weight-and-activation quantization does the matrix multiplication itself in INT8 or FP8, which also speeds up compute-heavy work such as processing long prompts, but is harder to get right.
- Dynamic quantization stores weights in INT8 and computes each activation's scale on the fly at run time. It is easy to apply to linear layers on CPUs.
Methods for large language models
Rounding each weight to its nearest level (round-to-nearest) works well at 8 bits. At 4 bits and below, smarter methods help:
- GPTQ (Frantar et al., 2022) quantizes weights one column at a time and adjusts the not-yet-quantized weights to compensate for the error just introduced, using second-order information from calibration data. The authors quantized 175-billion-parameter models to 3–4 bits in about four GPU hours with little loss in accuracy.
- AWQ (activation-aware weight quantization, Lin et al., 2023) observes that about 1% of weights matter far more than the rest: those that multiply large activations. It scales those channels up before quantizing, so they get finer effective precision, without any mixed formats.
- NF4 (4-bit NormalFloat, from QLoRA, 2023) places its 16 levels where normally distributed weights are densest, instead of evenly. It is used by the bitsandbytes library and QLoRA fine-tuning (LoRA and Parameter-Efficient Fine-Tuning).
- GGUF is the file format of llama.cpp, with its own family of block-wise schemes ("k-quants") named like Q8_0, Q5_K_M and Q4_K_M. Running Models Locally explains how to read those names.
Memory arithmetic
Weights only, in gigabytes ( bytes), ignoring the small overhead of scales:
| Model | FP32 (4 B) | BF16 (2 B) | INT8 / FP8 (1 B) | INT4 (0.5 B) |
|---|---|---|---|---|
| 1B parameters | 4 | 2 | 1 | 0.5 |
| 7B | 28 | 14 | 7 | 3.5 |
| 70B | 280 | 140 | 70 | 35 |
| 405B | 1,620 | 810 | 405 | 203 |
Running a model needs this plus the The KV Cache and Fast Inference and some working memory. So a 7B model in BF16 fits a 24 GB GPU with room for context, and in INT4 fits an 8 GB one. A 70B model needs two 80 GB GPUs in BF16, one in INT8 (tightly), and fits a 48 GB card in INT4.
As a rough guide (it varies by model and method), 8-bit weight quantization is usually close to lossless, 4-bit with a good method loses a little on benchmarks, and below about 3 bits quality drops quickly. Larger models tolerate quantization better than small ones. A common finding is that a bigger model quantized to 4 bits beats a smaller model in 16 bits that takes the same memory.
In code
Quantization by hand in NumPy: symmetric INT8 and INT4, per-tensor, per-row and in groups, on a weight matrix with one planted outlier.
import numpy as np
rng = np.random.default_rng(0)
W = rng.normal(0, 0.02, size=(256, 256)).astype(np.float32) # a weight matrix
W[3, 7] = 0.5 # one outlier weight
def quantize(x, bits=8, axis=None):
"""Symmetric quantization: one scale per tensor (axis=None) or per row (axis=1)."""
qmax = 2 ** (bits - 1) - 1 # 127 for int8, 7 for int4
scale = np.abs(x).max(axis=axis, keepdims=axis is not None) / qmax
q = np.clip(np.round(x / scale), -qmax, qmax).astype(np.int8)
return q, scale
def dequantize(q, scale):
return q.astype(np.float32) * scale
def report(name, W_hat):
err = np.abs(W - W_hat)
rel = np.linalg.norm(W - W_hat) / np.linalg.norm(W)
print(f"{name:<26} mean |err| {err.mean():.2e} relative error {rel:.2%}")
q, s = quantize(W)
print("int8 codes:", q[0, :5], " scale:", float(s))
report("int8 per-tensor", dequantize(q, s))
report("int8 per-row", dequantize(*quantize(W, axis=1)))
report("int4 per-row", dequantize(*quantize(W, bits=4, axis=1)))
G = W.reshape(256, -1, 32) # groups of 32 weights
report("int4 groups of 32", dequantize(*quantize(G, bits=4, axis=2)).reshape(W.shape))
print(f"memory: fp32 {W.nbytes} bytes, int8 {q.nbytes} bytes")
# int8 codes: [ 1 -1 3 1 -3] scale: 0.003937007859349251
# int8 per-tensor mean |err| 9.88e-04 relative error 5.68%
# int8 per-row mean |err| 1.23e-04 relative error 0.78%
# int4 per-row mean |err| 2.23e-03 relative error 13.59%
# int4 groups of 32 mean |err| 1.65e-03 relative error 9.92%
# memory: fp32 262144 bytes, int8 65536 bytes
Without the outlier, per-tensor INT8 error falls from 5.68% to about 1.1%. Note that the int4 codes are stored in int8 here for simplicity. Real kernels pack two 4-bit values into each byte.
PyTorch can apply dynamic INT8 quantization to every linear layer in one call. This older torch.ao.quantization API still works but is deprecated in favour of the separate torchao library:
import io, time
import torch
torch.manual_seed(0)
if "qnnpack" in torch.backends.quantized.supported_engines and torch.backends.quantized.engine == "none":
torch.backends.quantized.engine = "qnnpack" # needed on ARM (e.g. Apple silicon)
model = torch.nn.Sequential(torch.nn.Linear(1024, 4096), torch.nn.ReLU(),
torch.nn.Linear(4096, 1024)).eval()
qmodel = torch.ao.quantization.quantize_dynamic(model, {torch.nn.Linear}, dtype=torch.qint8)
def size_mb(m):
buf = io.BytesIO(); torch.save(m.state_dict(), buf); return buf.tell() / 1e6
x = torch.randn(64, 1024)
with torch.no_grad():
y, yq = model(x), qmodel(x)
for m, name in [(model, "fp32"), (qmodel, "int8")]:
t = time.perf_counter()
for _ in range(50): m(x)
print(f"{name}: {size_mb(m):5.1f} MB {(time.perf_counter() - t) / 50 * 1000:.2f} ms per batch")
print(f"relative output error {((y - yq).norm() / y.norm()).item():.2%}")
# fp32: 33.6 MB 2.82 ms per batch
# int8: 8.4 MB 5.09 ms per batch
# relative output error 1.22%
The model is four times smaller and its outputs change by about 1%. But on this ARM laptop the INT8 version was slower: the float32 path uses a highly optimised matrix library, while the INT8 kernels for this backend are not as fast. On x86 servers (the fbgemm backend) dynamic quantization usually speeds up large linear layers. Always measure on your target hardware.
For LLMs you would use a ready-made method instead. With Hugging Face Transformers and bitsandbytes on a CUDA GPU, loading a model in 4-bit NF4 looks like this (it needs a GPU and downloads the model):
import torch
from transformers import AutoModelForCausalLM, BitsAndBytesConfig
config = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type="nf4",
bnb_4bit_compute_dtype=torch.bfloat16)
model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-7B-Instruct",
quantization_config=config, device_map="auto")
print(model.get_memory_footprint() / 1e9, "GB") # roughly 5-6 GB instead of about 15 GB
Common pitfalls
- Judging by perplexity alone. A quantized model can keep nearly the same perplexity yet get worse at long reasoning, coding or less common languages. Evaluate on the tasks you care about (Evaluating LLMs and Benchmarks).
- Expecting speed for free. Smaller weights save memory everywhere, but speed only improves if fast kernels exist for that format on your hardware. Dequantizing on the fly can even slow down compute-bound work such as long prompts.
- Quantizing the sensitive parts. Embedding layers, the final output layer and normalisation layers are often more sensitive. Most toolkits leave them in higher precision by default. Keep it that way unless you've measured.
- Calibration data that doesn't match use. A model calibrated on English Wikipedia may degrade more on code or another language. Calibrate on text like your real inputs.
- Forgetting the KV cache. For long contexts the The KV Cache and Fast Inference can outweigh the weights. Quantizing it (to 8-bit, for example) is a separate setting.
Watch out Very low bit widths (2–3 bits) can look fine on a few test prompts and fail badly on harder tasks. Before deploying an aggressively quantized model, compare it with the 16-bit original on a proper evaluation set, not on a quick chat.
Where it leads
- Mixed Precision Training: using 16-bit and 8-bit formats during training, not just inference.
- Running Models Locally: GGUF files and choosing a quantization level for your laptop.
- LoRA and Parameter-Efficient Fine-Tuning: QLoRA fine-tunes adapters on top of a frozen 4-bit model.
- Serving LLMs at Scale: FP8 and INT4 weights and quantized KV caches in production servers.
- Knowledge Distillation and Small Models and pruning: other ways to make models smaller, often combined with quantization.
- AI Hardware: GPUs, TPUs and Accelerators: low-precision tensor cores are a big part of why each GPU generation is faster.
A bit of history
Low-precision arithmetic for neural networks is old: researchers in the 1990s built networks with a few bits per weight for special-purpose chips. The modern wave began with mobile deployment. In 2017 Jacob and colleagues at Google described integer-only INT8 inference with quantization-aware training, which became the basis of TensorFlow Lite. Krishnamoorthi's 2018 whitepaper became the practical reference for quantizing CNNs. NVIDIA added INT8 support to its inference tools around the same time.
Large language models reopened the problem. In 2022, LLM.int8() showed how activation outliers break naive INT8 in big transformers, and GPTQ showed that 175-billion-parameter models could go down to 3–4 bits. In 2023 came AWQ, QLoRA's NF4, and the GGUF format (replacing the older GGML format in llama.cpp), which together made running capable models on consumer hardware routine. Hardware followed: FP8 arrived with NVIDIA's Hopper GPUs (2022), and 4-bit floating-point formats with Blackwell (2024). Today open models are often released with official quantized versions alongside the 16-bit weights.
Try it
- In the NumPy code, remove the outlier line and rerun. How much does per-tensor INT8 error improve? Does per-row still help?
- Try 3-bit and 2-bit per-row quantization (
bits=3,bits=2). Plot relative error against bits. Where does it rise steeply?- Harder: implement asymmetric quantization with a zero point and apply it to
np.maximum(W, 0)(ReLU outputs). Compare its error with symmetric quantization on the same data.Hint for 3: for non-negative data, symmetric quantization wastes all the negative levels. Use and .
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
A Visual Guide to Quantization
Over fifty illustrations explaining number formats, symmetric and asymmetric quantization, GPTQ, GGUF and BitNet.
LLM.int8(): 8-bit Matrix Multiplication for Transformers at Scale
Discovers emergent outlier features in large transformers and keeps them in 16-bit, making 8-bit inference of 175B-parameter models work without quality loss.
GPTQ: Accurate Post-Training Quantization for Generative Pre-trained Transformers
Quantizes LLM weights to 3–4 bits one column at a time, correcting the remaining weights for each rounding error using second-order information.
AWQ: Activation-aware Weight Quantization for LLM Compression and Acceleration
Protects the small share of weights that multiply large activations by rescaling channels before 4-bit quantization.
Transformers: Quantization
How to load and run quantized models with bitsandbytes, GPTQ, AWQ and other back ends, with a comparison of the methods.
Quantizing deep convolutional networks for efficient inference: A whitepaper
A clear practical overview of symmetric and asymmetric quantization, per-channel scales, post-training quantization and quantization-aware training.
GGUF on the Hugging Face Hub
What the GGUF format contains, the quantization types and their bits per weight, and how to find and inspect GGUF files on the Hub.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/mlops/quantization.md