Phase 04/Numbers and precision/INT8 and INT4 quantization
PHASE 04 · Numbers and precision

INT8 and INT4 quantization

0%
10 h6 subtopics3 lessons · 1 required
In plain English

Quantization stores the model's numbers as small whole numbers instead of decimals. Imagine compressing a photo by allowing each pixel only 256 shades instead of millions: the file shrinks a lot and, if you pick the 256 shades wisely for each region, the picture still looks right. INT8 gives each weight 256 possible values and INT4 only 16, so the model takes a quarter or an eighth of the memory and loads much faster. The art is in choosing the scale for each group of numbers so that the rare very large values do not force everything else to be rounded away. Weights are easy to quantize because they never change; activations are harder because they are different for every input.

Why it matters

Quantization is the single biggest lever for fitting a model on fewer GPUs and for speeding up memory-bound decode. Every serving engine ships INT8/INT4 paths (AWQ, GPTQ, FP8, SmoothQuant), and knowing how error is introduced lets you choose a method and verify it did not break the model.

Hiring signal

Skills this topic builds, with the number of the 46 analysed job postings that ask for each. Companies asking: Anthropic, Anyscale, Baseten, Cerebras, CoreWeave, Crusoe, Databricks, ElevenLabs, Fireworks, Hugging Face, Liquid AI, Modal, nvidia, OpenAI, Perplexity, Thinking Machines, Together AI, xAI.See all skills →

Learning objectives

  • Implement symmetric and asymmetric per-tensor, per-channel and per-group quantization from scratch.
  • Measure quantization error on real GPT-2 weights and relate it to perplexity change.
  • Explain why activation outliers make activation quantization harder than weight quantization.
  • Compare weight-only (GPTQ, AWQ) and weight-and-activation (SmoothQuant, FP8) methods and when each wins.
  • Run a quantized model in a serving engine and measure memory and tokens/s versus FP16.

Key concepts

Scale and zero point
q = round(x / scale) + zero_point; scale maps the integer grid to the real range.
Symmetric versus asymmetric
Symmetric centers the grid on zero (no zero point); asymmetric shifts it to fit a skewed range.
Granularity
Per-tensor, per-channel or per-group (e.g. 128 weights) scales; finer groups reduce error at a small storage cost.
Weight-only quantization
Weights stored in INT4/INT8 and dequantized to 16-bit before the matmul; speeds up memory-bound decode.
Activation outliers
A few channels with values 100x larger than the rest, which wreck per-tensor activation scales in large models.
GPTQ
Post-training method that quantizes weights column by column while correcting remaining columns using second-order information.
AWQ
Activation-aware weight quantization that protects the one percent of salient weights by scaling channels before rounding.
SmoothQuant
Migrates activation outlier magnitude into the weights so both can be quantized to INT8.
FP8 (E4M3 / E5M2)
8-bit floating formats on Hopper and later that quantize weights and activations with hardware support.

Subtopics

  1. 1. Uniform integer quantization math

    Derive scale and zero point from min/max or from a clipping threshold; round, clamp, dequantize; compute error.

  2. 2. Granularity and group size

    Per-tensor versus per-channel versus per-group; storage overhead of scales; why 128 is the common group size.

  3. 3. Weight quantization methods

    Round-to-nearest, GPTQ and AWQ; what calibration data is for; the 4-bit kernels that dequantize on the fly.

  4. 4. Activation quantization and outliers

    Dynamic versus static activation scales, the outlier channel problem, SmoothQuant and FP8 as answers.

  5. 5. Evaluating a quantized model

    Perplexity deltas, task accuracy, and spot-checking generations; when a 0.1 perplexity change is fine and when it is not.

  6. 6. Quantization in serving engines

    Loading AWQ/GPTQ/FP8 checkpoints in vLLM and TensorRT-LLM; which kernels run and what speedup to expect per batch size.

Resources

Hands-on lessons

L1

Quantize GPT-2 weights by hand and measure the damage

CPU · your Macnotebook120 minrequired

Goal · Implement INT8 and INT4 quantization at three granularities, apply it to every GPT-2 linear layer, and plot perplexity versus bits.

  1. 1Load gpt2 and a 200-sample slice of wikitext-2; compute baseline perplexity in FP32.
  2. 2Write quantize(w, bits, granularity) returning int tensor, scales and zero points for per-tensor, per-channel and per-group(128).
  3. 3Write dequantize and report mean squared error and max error for the first MLP weight at each setting.
  4. 4Replace every nn.Linear weight with its dequantized version and recompute perplexity for INT8 and INT4 at each granularity.
  5. 5Plot perplexity versus (bits, granularity) and mark the FP32 baseline.
  6. 6Try a simple clipping threshold (e.g. 99.99th percentile) instead of min/max for INT4 and record the change.
Deliverable
A notebook with the quantizer, the error table and the perplexity plot.
Check
INT8 per-channel perplexity is within 1 percent of FP32; INT4 per-tensor is visibly worse than INT4 per-group(128).
L2

Show the activation outlier problem

CPU · your Macexperiment60 minoptional

Goal · Visualize per-channel activation magnitudes in GPT-2 and measure how per-tensor INT8 activation quantization hurts more than weight quantization.

  1. 1Hook the input of each attention and MLP linear layer in gpt2 and record max(abs) per hidden channel across a batch of prompts.
  2. 2Plot the sorted channel maxima for a middle layer; note how many channels exceed 10x the median.
  3. 3Quantize the activations to INT8 per-tensor and per-token and compute the relative error of the following matmul output.
  4. 4Apply a SmoothQuant-style scaling (divide activations and multiply weights by sqrt of channel max) and re-measure.
  5. 5Write a short note comparing the three errors.
Deliverable
The channel magnitude plot and a table of relative errors for the three schemes.
Check
Per-token or smoothed quantization has lower relative error than per-tensor; you can name the outlier channels by index.
L3

Serve an AWQ model and benchmark it against FP16

Colab T4 · freecli90 minoptional

Goal · Measure memory footprint and decode tokens/s of an FP16 model versus its AWQ INT4 version in vLLM on a T4.

  1. 1pip install vllm in Colab; pick a small model with an AWQ checkpoint on the Hub (for example a 1B to 3B instruct model).
  2. 2Start vllm serve for the FP16 checkpoint with a small max-model-len; record GPU memory from nvidia-smi.
  3. 3Run a 32-request batch with the vllm bench or a short asyncio client and record output tokens per second.
  4. 4Repeat with the AWQ checkpoint and --quantization awq.
  5. 5Compare three sample generations side by side for obvious quality regressions.
Deliverable
A table with memory, tokens/s and a qualitative note for both checkpoints.
Check
AWQ weight memory is below 45 percent of the FP16 figure; you can explain the tokens/s result in terms of memory-bound decode and dequantization overhead.
Fallback
Run the FP16 and AWQ checkpoints with transformers and autoawq on CPU for 20 tokens each and compare only memory and output quality.

Build your own

Build your own quantizer

PythonCPU · your Mac~10 h

A post-training weight quantizer for GPT-2 (absmax int8, group-wise int4, GPTQ-lite and AWQ-lite) that reports packed bytes and the perplexity it costs.

The real thing: github.com/IST-DASLab/gptq ↗

How you know a stage passes

Write tests/test_quant.py first. Every stage adds a test over real GPT-2-small weights that asserts a reconstruction-error bound, an exact packed-byte count from a formula, and a perplexity delta on a fixed 2,048-token WikiText-2 slice against the fp32 model (perplexity computed by your own code and cross-checked once against transformers). A CLI `python quant.py --method <m> --bits <b> --group <g>` prints bytes, compression ratio and perplexity delta; `quant.py report` writes results.csv. Run `pytest -q`; a stage is done when its test passes and all earlier tests still pass.

Stages, in order. Each one leaves you with something that runs.0/7
  1. 01symmetric absmax int8 for one matrix
    `quantize_absmax(W)` returns int8 codes and one fp32 scale; `dequantize` reverses it.
    test · For gpt2 h.0.mlp.c_fc.weight every code lies in [-127, 127] with dtype int8, max abs reconstruction error is at most scale / 2, and relative Frobenius error is below 2 percent.
  2. 02per-channel and group-wise asymmetric int4 with nibble packing
    Int4 codes with a zero point, per output channel or per group of 128 along the input dimension, packed two per byte with scales stored in fp16.
    test · unpack(pack(q)) equals q for 100 random matrices; the packed size of a 768 x 3072 matrix with group 128 is 768 * 3072 / 2 bytes plus 768 * 24 * (2 + 1) bytes for scales and zeros, asserted exactly; group-wise int4 Frobenius error is at least 3x lower than per-tensor int4 on the same matrix.
  3. 03swap quantized weights into the model and pay for it in perplexity
    A loader fake-quantizes every Linear and Conv1D weight in GPT-2 at load time and a `perplexity()` function evaluates the fixed slice.
    test · Your fp32 perplexity matches transformers' loss-based figure within 0.01; int8 per-channel raises perplexity by less than 0.1; per-tensor round-to-nearest int4 raises it by more than 1.0, and the CLI prints all three.
  4. 04GPTQ-lite
    Collect a Hessian H = 2 X^T X per layer from 128 calibration sequences, then quantize columns one at a time with the OBQ error-feedback update and 1 percent diagonal damping.
    test · H is symmetric and its smallest eigenvalue after damping is at least -1e-6 for every layer; int4 group-128 GPTQ perplexity delta is at least 20 percent smaller than round-to-nearest int4 group-128 on the same slice.
  5. 05AWQ-lite activation-aware scaling
    Per input channel compute s = mean|X|^alpha, search alpha over 20 points in [0, 1] to minimise output MSE after quantization, and fold the scale into the preceding layer so the model's math is unchanged.
    test · The fp32 model with scales folded in produces logits within 1e-4 of the unscaled model; the chosen alpha reduces post-quantization output MSE versus alpha 0 in at least 80 percent of layers; the resulting int4 perplexity delta is printed alongside GPTQ's.
  6. 06W8A8 with outlier decomposition
    Per-token dynamic int8 activation quantization plus the LLM.int8 trick of keeping channels whose magnitude exceeds 6.0 in fp16.
    test · Naive W8A8 perplexity delta is larger than the decomposed version's; the decomposed delta is below 0.5; fewer than 2 percent of hidden channels are flagged as outliers and the test prints which ones.
  7. 07the report
    `quant.py report` runs every method and writes results.csv plus a bar chart of perplexity delta against compression ratio.
    test · results.csv has one row per configuration with columns method, bits, group, bytes, ratio, ppl_delta, seconds; the README table is generated from it and int8 shows at least 3.8x compression over fp32 weights.

Knowledge check

QWhy is weight-only INT4 quantization fast for small batch decode but not for large batch prefill?

Decode is memory-bound, so reading 4x fewer weight bytes helps; prefill is compute-bound and the dequantize step adds work without removing any FLOPs.

QWhat problem does per-group quantization solve compared to per-channel?

A single outlier in a channel forces a large scale for the whole channel; grouping 128 weights limits the damage to one group.

QWhy are activations harder to quantize than weights?

Activations change per input and in large models a few channels have values 100x larger than the rest, so a single scale wastes most of the integer grid.

QWhat does GPTQ use calibration data for?

To estimate the Hessian of the layer output so that the rounding error of each weight column can be compensated in the remaining columns.

Completion

  • All 6 subtopics marked done
  • All 1 required lessons done
  • All subtopics marked completed.
  • Lesson l1 perplexity plot saved and the check passes.
  • Can explain, in one paragraph, the difference between GPTQ, AWQ and SmoothQuant.
Topic progress is derived; it reaches 100% when both checks above pass.Next recommended topic →