Careers Post-AI
AI infrastructure and systems: all chapters

AI infrastructure and systemsPart 2: Inference serving

Chapter 7Model optimization

30 min read, 1 lab, Intermediate

Converting an 8B model from 16-bit to 4-bit weights shrinks it from about 15 GiB to under 5 GiB and can nearly triple single-stream decode speed on memory-bound hardware. It also changes the model's answers, by an amount most teams never measure. This chapter covers the main ways to make inference cheaper (smaller models, quantization, distillation, pruning, compilation, speculative decoding and caching) and how to put a number on what each one costs in quality.

After this chapter you can

  • Rank optimization levers by effort, speed-up and quality risk, starting with model choice.
  • Explain weight-only and weight-plus-activation quantization and when each helps.
  • Compare GPTQ, AWQ and GGUF k-quants, and read a quantization level name.
  • Measure quality loss with perplexity, KL divergence and task evaluations.
  • Explain why speculative decoding and prefix caching speed up generation without changing outputs.

Start with a smaller model

The biggest optimization is usually not a technique at all. A model with half the parameters needs half the memory and roughly half the bandwidth per decode step, and recent small models often match older large ones on narrow tasks. Before quantizing a 70B model, check whether an 8B model, perhaps fine-tuned (see the chapter on fine-tuning systems), clears your quality bar.

LeverTypical gainEffortChanges outputs?
Smaller model2 to 10 times cheaperLow, needs an evalYes, often a lot
Prefix cachingLarge TTFT cut on repeated prefixesVery lowNo
8-bit quantizationAbout 2 times less weight memoryLowSlightly
4-bit quantizationAbout 3 to 4 times less weight memoryLow to mediumMeasurably
Speculative decoding1.5 to 3 times faster decode at low loadMediumNo, in exact mode
DistillationA small model with some of a big model's skillHigh, needs trainingYes
PruningFewer parameters or sparse matricesHigh, usually needs retrainingYes

Gains in this table are typical ranges from published results and vary widely with hardware and workload. The rule they imply holds anyway: do the cheap, output-preserving changes first, then the ones that need an evaluation.

How quantization works

Quantization stores numbers with fewer bits. A 16-bit weight becomes an 8-bit or 4-bit integer plus a shared scale factor for a small group of weights, typically 32 to 128 values.

scale     = max(|w| in group) / (2^(bits-1) - 1)      # symmetric, per group
q         = round(w / scale)                          # stored integer
w_approx  = q * scale                                 # what the kernel uses
error     = w - w_approx                              # what you pay in quality

Smaller groups mean more scales to store but less error, because one outlier weight only distorts its own group. This is why a "4-bit" format often costs closer to 4.5 to 5 bits per weight once scales are included.

There are two families, and they speed up different phases:

Weight-only (for example W4A16)

  • Weights stored in 4 or 8 bits, unpacked to 16-bit inside the kernel.
  • Activations stay 16-bit.
  • Cuts memory and bandwidth, so it speeds up decode.
  • Little help for compute-bound prefill.
  • GPTQ, AWQ and GGUF are mostly here.

Weights and activations (W8A8, FP8)

  • Both operands in 8 bits, multiplied on 8-bit tensor cores.
  • Roughly doubles arithmetic throughput on supporting GPUs.
  • Speeds up prefill and large batches as well as decode.
  • Needs hardware support (FP8 on NVIDIA Hopper and newer, for example).
  • Activations have outliers, so calibration matters more.

The KV cache can be quantized too, usually to 8 bits. That does not speed up the weights, but it doubles how many tokens fit in cache, which raises concurrency (see the memory budget in the chapter on inference fundamentals).

Methods: round-to-nearest, GPTQ, AWQ and GGUF

All of these are post-training quantization (PTQ): you start from a finished model and convert it, optionally using a few hundred calibration samples. The alternative, quantization-aware training, simulates low precision during training and costs a training run.

MethodIdeaCalibration dataWhere you meet it
Round-to-nearestQuantize each group independentlyNoneBaseline, FP8 dynamic, GGUF Q8_0
GPTQQuantize columns one at a time and adjust the rest to compensate, using second-order informationYesvLLM, Transformers; GPTQModel and llm-compressor create it
AWQFind the small fraction of weight channels that matter most (by activation size) and scale them to protect themYesvLLM, Transformers; llm-compressor creates it
GGUF k-quantsBlock-wise mixed-precision formats; more bits for sensitive tensorsOptional importance matrixllama.cpp, Ollama, LM Studio

GGUF level names encode the format. Q4_K_M means 4-bit, k-quant family, medium mix (some tensors kept at higher precision). Q8_0 is plain 8-bit with one scale per block. IQ types are newer formats designed for very low bit widths, and they benefit most from an importance matrix (--imatrix), which records which weights matter on sample text.

Measuring the quality cost

Never ship a quantized model on vibes. Use three measurements, cheapest first.

  1. Perplexity

    Run the model over a fixed text (WikiText-2 is the convention) and compute how surprised it is by each next token. Lower is better. Compare quantized against the 16-bit original on the same text and settings; the absolute value means little.

  2. KL divergence against the original

    Record the original model's full next-token distribution, then measure how far the quantized model's distribution drifts (Kullback-Leibler divergence). It catches changes that perplexity averages away, and llama.cpp also reports how often the top token stays the same.

  3. Task evaluation

    Run benchmarks close to your use (EleutherAI's lm-evaluation-harness has hundreds) and, more importantly, your own eval set of real prompts with graded answers. This is the only number your users feel.

The llama.cpp perplexity documentation publishes these numbers for Llama 3 8B on WikiText-2, which give you a sense of scale:

LevelSizePerplexityMean KL divergence
Q8_07.96 GiB6.2340.0014
Q6_K6.14 GiB6.2530.0055
Q5_K_M5.33 GiB6.2890.0108
Q4_K_M4.58 GiB6.4070.0313
Q4_04.34 GiB6.7000.0719

The pattern is the lesson: 8-bit is nearly free, 5 and 6-bit are close, and the drop accelerates below 4 bits. Small models degrade faster than large ones at the same bit width, which you will see in the lab.

Distillation and pruning

Distillation trains a small student model to imitate a large teacher, usually by matching the teacher's output probabilities rather than just the correct token. Those soft targets carry more information per example, so the student learns more from less data. Many popular small open models are distilled from larger siblings; for you it is mostly a reason to look for official small variants before building your own.

Pruning removes parameters. Unstructured pruning zeroes individual weights, which saves little unless hardware can skip zeros; NVIDIA GPUs accelerate one specific pattern, 2:4 sparsity, where two of every four weights are zero. Structured pruning removes whole attention heads, channels or layers, giving a genuinely smaller dense model. Both normally need retraining or distillation afterwards to recover quality, so they are platform-team projects, not a flag you flip.

Compilation and optimized runtimes

A model written in PyTorch launches many small GPU kernels, each reading and writing memory. Compilers and runtimes cut that overhead. The main techniques, at a conceptual level:

  • Kernel fusion: combine several operations (for example a matrix multiply, bias and activation) into one kernel so intermediate results never leave on-chip memory.
  • Fused attention kernels: FlashAttention and its successors compute attention in tiles without writing the full attention matrix to memory.
  • CUDA graphs: record a sequence of kernel launches once and replay it, removing CPU launch overhead that dominates at small batch sizes.
  • Ahead-of-time engines: torch.compile, TensorRT and TensorRT-LLM trace the model and generate kernels tuned for one GPU type and shape range.

You rarely do this by hand for LLMs, because serving engines already use fused attention and CUDA graphs. Treat "compile it" as an engine and version choice, verify claims against the engine's own documentation, and measure, since gains depend heavily on batch size and hardware.

Speculative decoding

Decode is memory-bound, so the GPU has spare compute while it streams weights. Speculative decoding spends that spare compute. A cheap drafter guesses the next k tokens, and the big target model checks all k in one forward pass, which costs about the same as generating one token.

With the standard acceptance rule (a form of rejection sampling), the output distribution is exactly the target's; speculation changes speed, not answers. The speed-up depends on how often the drafter is right:

alpha = probability each draft token is accepted, k = draft length
expected tokens per target pass = (1 - alpha^(k+1)) / (1 - alpha)
alpha = 0.8, k = 4  ->  about 3.4 tokens per pass
alpha = 0.5, k = 4  ->  about 1.9 tokens per pass

Drafters come in several kinds: a small model from the same family, n-gram lookup that copies spans from the prompt (great for code editing and summarisation), and trained draft heads such as EAGLE that sit on the target model's hidden states. In vLLM you pass a JSON speculative config; in llama.cpp you add a draft model with -md.

vllm serve meta-llama/Llama-3.1-8B-Instruct \
  --speculative-config '{"method": "ngram", "num_speculative_tokens": 4, "prompt_lookup_max": 4}'

At high batch sizes the GPU no longer has spare compute, and verification work can slow things down. Benchmark at your real concurrency before enabling it.

Prompt and prefix caching

If many requests start with the same tokens (a long system prompt, a tool list, a shared document), the engine can keep their KV cache and skip that prefill. vLLM's automatic prefix caching and SGLang's RadixAttention do this inside one replica; hosted APIs sell the same idea as discounted cached input tokens.

Caching works only on an exact token prefix, so prompt layout matters. Put stable content first (instructions, tools, documents) and variable content last (user message, timestamps). A timestamp at the top of a system prompt silently disables caching for every request. Routing requests with the same prefix to the same replica, covered in the chapter on scaling and routing inference, extends the benefit across a fleet.

Key terms

Quantization
Storing weights or activations in fewer bits, with scale factors to map them back to real values.
Post-training quantization
Quantizing a finished model without retraining, optionally using calibration samples.
Weight-only quantization
Low-bit weights with 16-bit activations; cuts memory and speeds memory-bound decode.
GPTQ
A post-training method that quantizes weights column by column while compensating the error in remaining weights.
AWQ
Activation-aware weight quantization, which protects the most important weight channels by rescaling them.
Perplexity
A measure of how well a model predicts a reference text; lower means less surprised.
KL divergence
A measure of how far one probability distribution drifts from another, used to compare a quantized model with its original.
Distillation
Training a smaller student model to imitate a larger teacher model's outputs.
Speculative decoding
Drafting several tokens cheaply and verifying them in one target-model pass, without changing the output distribution.
Lab

Quantize a model two ways and measure the trade-off

Intermediate, 60 min

Goal: start from a 16-bit model, produce 8-bit and 4-bit versions, and measure speed, memory, perplexity and KL divergence for all three.

You need: macOS or Linux (WSL2 on Windows), about 6 GB free disk, Python 3.10+, llama.cpp (brew install llama.cpp, or build from source per the repository README) and the Hugging Face CLI (pip install -U huggingface_hub, which provides the hf command). Everything runs on CPU or Apple silicon in minutes.

  1. Download the official 16-bit GGUF of Qwen2.5 0.5B Instruct and fetch the WikiText-2 test set with the script in the llama.cpp repository.
mkdir -p quant-lab && cd quant-lab
hf download Qwen/Qwen2.5-0.5B-Instruct-GGUF qwen2.5-0.5b-instruct-fp16.gguf --local-dir .
git clone --depth 1 https://github.com/ggml-org/llama.cpp
bash llama.cpp/scripts/get-wikitext-2.sh
ls wikitext-2-raw/wiki.test.raw
  1. Quantize to two levels. llama-quantize takes input file, output file and type.
llama-quantize qwen2.5-0.5b-instruct-fp16.gguf q8_0.gguf Q8_0
llama-quantize qwen2.5-0.5b-instruct-fp16.gguf q4_k_m.gguf Q4_K_M
ls -lh *.gguf

Expect roughly 1.3 GB for FP16, about half that for Q8_0 and somewhat less again for Q4_K_M. The 4-bit file is not a quarter of the original because embeddings and some sensitive tensors stay at higher precision, and a 0.5B model's large vocabulary embedding is a big share of its size.

  1. Measure speed. llama-bench reports prompt processing (pp512) and token generation (tg128) in tokens per second, averaged over five repetitions.
llama-bench -m qwen2.5-0.5b-instruct-fp16.gguf -m q8_0.gguf -m q4_k_m.gguf -p 512 -n 128 -o md

You should see a Markdown table with one pp512 and one tg128 row per model. Generation speed should rise as bits fall, because decode is memory-bound; prompt processing may change much less, or even favour Q8_0, since prefill is compute-bound.

  1. Record the FP16 model's logits as the reference, then measure perplexity, KL divergence and peak memory for each quantized model. Twenty chunks keeps the logits file to a few GB and the run to a few minutes. Use /usr/bin/time -l on macOS and /usr/bin/time -v on Linux.
/usr/bin/time -l llama-perplexity -m qwen2.5-0.5b-instruct-fp16.gguf \
  -f wikitext-2-raw/wiki.test.raw --chunks 20 --kl-divergence-base fp16.kld
 
for m in q8_0 q4_k_m; do
  /usr/bin/time -l llama-perplexity -m $m.gguf --chunks 20 \
    --kl-divergence-base fp16.kld --kl-divergence 2>&1 | tee $m.log
done

The first run prints a final perplexity estimate and the peak resident memory. The other two print perplexity, mean KL divergence and a "same top" percentage. Expect Q8_0 to be almost indistinguishable from FP16 and Q4_K_M to show a clearly larger KL divergence; on a model this small the 4-bit penalty is larger than the Llama 3 8B table in this chapter.

  1. Write TRADEOFF.md with one table: level, file size, peak memory, pp512, tg128, perplexity, KL divergence and same-top percentage. End with a two-sentence recommendation for a specific use, for example a laptop autocomplete feature versus a customer-facing support bot. Delete fp16.kld afterwards to reclaim disk.

Check your work: your table has three rows; file size and memory fall from FP16 to Q4_K_M, tg128 rises, and KL divergence for Q4_K_M is several times that of Q8_0. If KL divergence is zero for every model, you passed the quantized model as the base by mistake; rerun the reference step with the FP16 file.

Stretch: generate an importance matrix with llama-imatrix on some calibration text, quantize again to IQ4_XS or Q3_K_M with and without --imatrix, and add both rows to your table. Then send ten of your own prompts to each model through llama-server and grade the answers by hand.

Check yourself

A service runs an 8B model at batch size 1 and is limited by decode speed. Which change most directly helps?

Two 4-bit versions of a model have nearly the same WikiText-2 perplexity, but one has three times the KL divergence from the original. What should you conclude?

Speculative decoding with exact verification is enabled, and a user claims the answers got worse. What is true?

Prefix caching is enabled but the cache hit rate is near zero, although every request uses the same 3,000-token system prompt. What is the most likely cause?

Your team wants to cut serving cost for a 70B model by half. Which step should come first?

Recap

  • Try a smaller model and prefix caching before anything that changes outputs.
  • Weight-only quantization speeds memory-bound decode; weight-plus-activation quantization also speeds compute-bound prefill.
  • 8-bit is nearly free, 4-bit costs measurable quality, and small models suffer more.
  • Measure with perplexity, KL divergence against the original, and your own task evaluation.
  • Speculative decoding and prefix caching make generation faster without changing the output distribution.
  • Distillation, pruning and compilation are real but costly; prefer what your engine already provides.

Go deeper