AI State of the Art
SOTA/Inference & Optimization/38 min
Section 117

Quantization: Concepts (INT8, INT4, FP4, NF4)

Listen as a podcast →

The Size Problem

A 70 billion parameter model in FP16 format (2 bytes per number) weighs 140 GB: 70 × 10⁹ × 2 bytes = 140 × 10⁹ bytes. To give you an idea, that's more than the total memory of an A100 GPU (80 GB). Impossible to load in one piece. And even if you have multiple GPUs, the bill adds up fast.

Quantization is the solution: you replace very precise numbers with coarser, lighter ones. The model loses a bit of finesse, but it fits in memory and runs faster.

Bits and bytes, settled once

This lesson juggles two units, and mixing them up costs you a factor of 8. A bit is a binary digit, 0 or 1. A byte is a bundle of 8 bits. So a "16-bit" format costs 2 bytes per parameter, an "8-bit" format costs 1 byte, a "4-bit" format costs half a byte. Gigabytes (GB) are always bytes; a precision is always bits.

The tradeoff

Quantization is a bargain: you use less memory and run faster, but you lose some precision. Like a JPEG photo: smaller than a PNG, and a bit grainy. The eye barely notices the difference, and the file is 10 times lighter.

Why Shrinking the Weights Makes the Model Faster

This is the point that makes the rest of this module obvious, and it is counter-intuitive: quantization does not reduce the number of operations to perform. The multiplications are the same, and there are just as many of them. Yet the model runs markedly faster. Why?

Because to generate one token, the chip must first fetch every weight in the model out of its memory and feed them into its arithmetic units. And the arithmetic units of a modern GPU are far faster than the pipe that supplies them. The result: they spend most of their time waiting for data. This is what it means to say that language model inference is limited by memory bandwidth (the throughput of that pipe) and not by compute.

A concrete picture: a brilliant cook with a conveyor belt that is too slow. Handing him a second knife changes nothing; shrinking the ingredients he has to move does. That is exactly what quantization does: cutting by four the volume of weights that has to travel down the pipe cuts the waiting by almost four.

Not a hunch, a measurement

The SqueezeLLM authors state it as the premise of their whole paper: the main bottleneck for generative inference with a large language model is memory bandwidth rather than compute, specifically when serving one request at a time. See SqueezeLLM: Dense-and-Sparse Quantization (Kim et al., 2023) and the SqueezeLLM lesson.

One useful corollary: the argument holds when you serve one request at a time. Group dozens of requests and process them together (see batching) and the same weights now serve several requests at once, compute regains weight in the balance, and quantization's payoff is less dramatic.

Number Formats

To understand quantization, you need to understand how computers store numbers. Each format represents a tradeoff between range (what values you can represent) and precision (how many decimal places).

FP32 (32 bits - luxury)

  • Very precise but takes 4 bytes per parameter (32 bits ÷ 8)
  • Used for training (gradients need precision)
  • Range: up to 3.4 x 10^38
  • It's the camera negative, you keep everything, but it's heavy

FP16 / BF16 (16 bits - modern standard)

  • FP16: good tradeoff, but limited range (some values that are too large cause "overflow")
  • BF16: same range as FP32, but with fewer decimal places
  • Standard for modern LLMs: 2 bytes per parameter
  • Most models on Hugging Face are distributed in BF16
BF16 > FP16 for LLMs

BF16 (Brain Float, invented by Google Brain) is like FP32 but cut in half. It keeps the same value range, so no risk of overflow, running past the largest representable number, explained in numerical stability. All modern GPUs (A100, H100, RTX 4090) support it natively. It's the default choice today for both training and inference.

Bit layout comparison of three formats. bfloat16: 1 sign bit, 8 exponent bits, 7 mantissa bits, range about 1e-38 to 3e38. fp32: 1 sign bit, 8 exponent bits, 23 mantissa bits, same range. fp16: 1 sign bit, 5 exponent bits, 10 mantissa bits, range about 6e-8 to 65504.
The whole BF16 versus FP16 story is right here. The grey cells (the exponent) set the range of values, the yellow cells (the mantissa) set the number of decimal places. BF16 keeps FP32's 8 exponent bits and gives up decimals, FP16 does the opposite: more decimals, but a far narrower range: values that are too large overflow, and above all very small ones (a gradient, typically) round to zero and vanish.Source : SX-Aurora (NEC) blog, Llama2 with bfloat16

INT8 (8 bits - integers)

  • Only 256 possible values (-128 to 127)
  • 2x reduction compared to FP16
  • 1 byte per parameter
  • Think of it as a palette of 256 colors instead of millions: for many images, that's enough

INT4 (4 bits - highly compressed)

  • Only 16 possible values (-8 to 7)
  • 4x reduction compared to FP16
  • Half a byte per parameter
  • This is the current sweet spot: compressed enough to be useful, not too degraded to be useless

NF4 (4 bits - smart)

  • Same cost as INT4: half a byte per parameter
  • The 16 levels are placed at the quantiles of the normal distribution: where the weights are most concentrated (around zero), you get more precision levels, and where they're rare (the extremes), you get fewer. This works because LLM weights approximately follow a normal distribution.
  • Imagine you need to summarize a class's grades with 16 values. Instead of spacing them evenly (0, 6, 12, 18...), you put more values around the mean where most students are
  • Used by QLoRA for memory-efficient fine-tuning

How an integer can represent a weight

Floating-point formats and integer formats do not work the same way at all, and this is the point most explanations of quantisation leave out.

A floating-point format like FP16 encodes a decimal number directly, with its sign, its order of magnitude and its significant digits, the mechanics are set out in Mixed precision. An 8-bit integer, by contrast, can only write the whole numbers from −128 to 127. So it cannot hold 0.0374.

The trick is to store not the value, but its position on a graduated ruler. You take a group of weights, note the largest absolute value it contains, and cut that interval into 255 steps. The number stored is no longer the weight: it is the index of the nearest step. And alongside it, once for the whole group, you keep the width of one step, what is called the scale factor.

A worked example

Take a group of weights whose largest absolute value is 0.5.

One step is worth 0.5÷127≈0.003940.5 \div 127 \approx 0.00394.

To store the weight 0.0374, you work out how many steps that is: 0.0374÷0.00394≈9.50.0374 \div 0.00394 \approx 9.5, rounded to 9. That 9 is what goes to disk, in one byte.

To use it again, you reverse the operation: 9×0.00394≈0.03549 \times 0.00394 \approx 0.0354. You do not get 0.0374 back but 0.0354. The gap, about 0.002, is the quantisation error, and that is all you lost.

What this one example explains at once

Why the advertised saving is never quite reached. The scale factor is a full-precision number that has to be stored somewhere. With groups of 128 weights it adds roughly 0.16 bit per weight, hence the 4.16 real bits of a "4-bit" format mentioned below.

Why group size matters. A single extreme weight in a group forces a coarser ruler on all the others. Had our group contained a value of 5 instead of 0.5, one step would become 0.0394: the weight 0.015 would then be 0.38 of a step, rounded to zero. It would simply be erased. That is exactly the problem methods like AWQ and GPTQ work around, each in its own way, see AWQ and GPTQ.

Why NF4 is finer than INT4 at identical cost. Our steps here are evenly spaced, which is a choice. NF4 packs them where weights are dense and spreads them where weights are rare.

One last piece of vocabulary. If the ruler is centred on zero, as in our example, the quantisation is called symmetric: a single number, the scale, describes it fully. If the values to represent are all positive (as activations after a ReLU are), it pays to shift the ruler, and you then need a second number saying where zero sits. That is asymmetric quantisation, and the second number is called the zero point.

What That Comes To in Gigabytes

Let's run the arithmetic end to end on a 7 billion parameter model, the most common size in open weights. The weight on disk is simply the parameter count times the cost of one parameter:

FormatBits / parameterBytes / parameterRaw weight for 7 billion
FP323247 × 4 = 28 GB
FP16 / BF161627 × 2 = 14 GB
INT8817 × 1 = 7 GB
INT4 / NF440.57 × 0.5 = 3.5 GB

That is the entire payoff of quantization, in one multiplication. Going from BF16 to 4 bits means going from 14 GB to 3.5 GB, a factor of 4, because 16 bits ÷ 4 bits = 4.

The advertised factor is never quite reached

The right-hand column is a theoretical floor, and a genuinely quantized model always weighs a little more. Two reasons, both of them systematic:

1. Not everything gets quantized. In practice you leave in high precision the parts of the model that tolerate rounding badly: the embedding table (the map from tokens to vectors), the output layer that produces the probabilities, and the normalization layers. On a 7 billion parameter model that routinely amounts to several hundred million parameters still sitting in 16 bits.

2. The scales have to be stored. A quantized weight is meaningless without its scale factor and zero point (see below). With groups of 128 weights, one group costs 128 × 4 = 512 bits of weights, plus a 16-bit scale and a 4-bit zero point, so 532 bits for 128 weights, that is 4.16 bits per weight, not 4. With groups of 32 the overhead is four times heavier: 32 × 4 + 20 = 148 bits for 32 weights, so 4.63 bits per weight.

Typical outcome for a 7 billion parameter model at 4 bits with groups of 128: a file around 4 GB rather than 3.5. Still nearly 3.5 times smaller than the original 14 GB, but not 4 times. Be wary of any page that announces "four times smaller" without showing this arithmetic.

How Quantization Works

The idea is simple: you take very precise numbers (floats) and "round" them to a limited number of levels. Then you store a formula to (approximately) recover the original values.

  1. Original weight (FP16): 0.123456789
  2. Quantized weight (INT4): 5 (on a 0-15 scale)
  3. During use: 5 x (scale_factor) + zero_point ≈ 0.123456789

You map the real weights to integers, then rescale during use. The approximation error is the price you pay.

Diagram with two axes. On top, a continuous axis r represents floating-point numbers, with a blue band running from r-min to r-max that contains zero. Below, an axis q represents integers, with eight evenly spaced dots between q-min and q-max. Dotted lines connect r-min to q-min and r-max to q-max, a scale factor S links the two axes, and an arrow shows that integer Z (the zero point) maps exactly onto floating-point zero. A table gives q-min and q-max per bit width: 2 bits from -2 to 1, 3 bits from -4 to 3, 4 bits from -8 to 7.
This is what the scale factor and the zero point actually look like. You take the real range of the weights (the blue band) and project it onto a grid of evenly spaced integers. The scale factor S is the real-world distance between two tick marks, and the zero point Z is the integer that lands exactly on floating-point zero. The table on the right shows why INT4 is so tight: only 16 tick marks, from -8 to 7.Source : TinyML KOR lecture notes (lecture 5-6, MIT 6.5940 course)

Per-Channel Quantization

Each column of the weight matrix has its own scaling parameters (scale factor and zero point). It's as if each column of pixels in a photo had its own brightness setting. Finer, so less error, but more metadata to store.

Group Quantization

Weights are divided into groups of 32 or 128. Each group has its own mapping constants. This is the most commonly used practical tradeoff: you don't go down to the individual channel level (too much metadata), but you don't do a global mapping either (too much error).

The Dividing Line: After Training, or During?

Every method in this module falls on one side or the other of a single boundary. This is the distinction to hold on to before anything else.

After. You take an already trained, frozen model and compress it. This is post-training quantization, almost always abbreviated PTQ. Cost: minutes to hours on a single GPU, plus a handful of text samples to calibrate on. That is what GPTQ, AWQ, GGUF and SqueezeLLM do. It is also the only option available to anyone who downloads a model without the means to retrain it.

During. You train the model with the low-precision constraint imposed from the start, so it learns to live with it. This is quantization-aware training, abbreviated QAT, the QAT lesson walks through the mechanism. Cost: a training run, so GPU-days and a real dataset. In exchange, quality holds at precisions where PTQ collapses, notably 2 bits and below (see extreme quantization).

The rest of this page describes PTQ, because it is by far the more common case.

Round-to-Nearest (RTN)

The simplest PTQ: round each weight to the nearest quantization level, independently of the others. Abbreviated RTN. Like rounding all prices in a supermarket to the nearest cent.

  • Decent in INT8
  • Degraded results in INT4 (too few levels, errors accumulate)

Data-Guided Methods (GPTQ, AWQ)

You use a small set of examples (128 to 256 text excerpts) to measure the real impact of each quantization choice on the model's outputs. You protect the important weights and compensate for the errors.

  • Measures importance via the Hessian matrix (the second derivatives of the loss, i.e. of the error measure training tries to reduce) or via activation magnitudes
  • Slower to produce, but significantly better results
The outlier problem

LLMs have outliers: some activation channels are a hundred times larger than the average. Since the quantization scale has to span the largest value present, those few channels stretch the grid over their full height and every other weight ends up squashed onto a handful of levels. Good methods (AWQ, SmoothQuant) handle outliers separately.

Three-dimensional plot of LLM activations. The horizontal axis is the channel index (0 to about 5000), the depth axis is the token index (0 to 300), and the vertical axis is the absolute activation value. Almost the entire surface is a flat blue sheet below 2, but a few channels form red walls rising above 70. The caption states these activations are hard to quantize.
The outlier problem, seen head on. The blue sheet is the thousands of normal channels, all below 2. The red walls are a handful of rare channels reaching 70. Since the scale factor has to cover the maximum, those walls alone stretch the grid over the full height and squash the blue sheet onto a couple of levels.Source : SmoothQuant paper (Xiao et al., 2022), via the Monsoon blog

How Much You Lose, and How to Read It

First, the metric

You will meet the word perplexity everywhere in this module. Let's pin it down once. Perplexity measures how surprised a model is by a text you hand it to read: it is the effective number of options it is torn between when predicting the next word. A perplexity of 5 means "it hesitated as if picking at random among 5 words". Lower is better, and there is no good absolute value: a perplexity is only meaningful as a comparison, between two models reading the same text. The Entropy lesson gives the formal definition.

Perplexity has one big advantage for judging a quantization: it is measured on raw text, with no answers to grade. It has one big drawback: it is highly sensitive to protocol details (which text, cut into windows of what length), so much so that two perplexities from two different papers are not comparable. The field's standard text sets are WikiText-2 (Wikipedia articles) and C4 (a cleaned web crawl).

A loss percentage with no protocol says nothing

"Under 1% degradation" is an empty sentence until you say on which metric, on which model and on which task. The same 4-bit model can lose 1% of perplexity on WikiText-2 and 15 points on a set of math problems. When a page (this one included) hands you a loss figure, demand all three.

Then, the numbers

Here are two published measurements, protocol included, to give the real order of magnitude of a 4-bit quantization.

LLaMA-7B, perplexity on WikiText-2, weights in 4 bits with groups of 128 (table 4 of the AWQ paper):

MethodPerplexityGap to the reference
FP16 (reference)5.68–
RTN (plain rounding)5.96+4.9%
GPTQ6.22+9.5%
GPTQ with reordering5.83+2.6%
AWQ5.78+1.8%

OPT-66B, perplexity on WikiText-2, weights in 4 bits with no groups (table 3 of the GPTQ paper):

MethodPerplexity
FP16 (reference)9.34
RTN (plain rounding)110
GPTQ9.55

This second table is the most instructive in the module: on that particular model, naive rounding does not degrade the result, it destroys the model, a perplexity of 110 is the behaviour of a gibberish generator. That is the entire reason GPTQ and AWQ exist.

Finally, the task

The loss depends on the kind of work you ask for:

  • Math, code, multi-step reasoning: sensitive. An intermediate slip propagates all the way to the end, and an almost-right answer is wrong.
  • Chat, open-ended writing: robust. The loss is often imperceptible, because a thousand phrasings of the same answer are acceptable.
Test on YOUR use case

The figures above are perplexities on Wikipedia articles. A model quantized to INT4 can be excellent for translation and catastrophic for math. Always measure on your actual use case before deploying.

Hardware Acceleration

Shrinking the volume of data to move is already enough to speed things up, as explained above. But the chip still has to handle the compressed format without giving back on the way what it gained:

  • INT8: handled directly by the Tensor Cores, the specialized matrix-arithmetic units on NVIDIA GPUs (A100, H100)
  • INT4: no dedicated unit on mainstream GPUs. You need kernels (small programs written for the GPU, here in CUDA, NVIDIA's GPU programming language) that expand the weights back to 16 bits just before the arithmetic. ExLlama and Marlin are the best known.
  • FP8: an 8-bit floating-point format, handled directly by the hardware from the H100 and RTX 4090 onward
Without the right kernel, no gain

This is the classic 4-bit trap: the weights genuinely take four times less space, but if the program reading them has to expand them one by one in a naive way, the time saved on transport is lost again on decoding, and the quantized model can end up slower than the original. A format and the program that runs it always come as a pair.

Check your understanding0 / 5

1. Quantizing a model to 4 bits divides its size by four, yet it changes nothing about the number of multiplications to perform. Why does generation get so much faster anyway?

2. In a group of 128 weights almost all between −0.5 and 0.5, a single weight equals 5. What does this do to the quantization of that group?

3. A 7-billion-parameter model quantized to 4 bits with groups of 128 weighs about 4 GB, not the theoretical 3.5 GB. Where does the gap come from?

4. A vendor announces: our quantized version loses less than 1 percent of quality. What is missing for that number to mean anything?

5. What is the dividing line between post-training quantization (PTQ) and quantization-aware training (QAT)?