Courses / GenAI & LLM / Module 10
Module 10: Serving and inference optimization: vLLM, quantization, batching, caching
12 h · theory 4 · hands-on 5 · project 2 · revision 1
You will be able to
- Serve an open model with vLLM or llama.cpp
- Choose quantization levels and measure quality loss
- Explain continuous batching and the KV cache, and size GPU memory
- Cut cost and latency with caching and routing between models
Capstone increment: Self-hosted model endpoint with a router (cheap model first, escalate on low confidence) and a response cache; measured before and after.
Job-description skills: Inference optimization, Model serving · Lab tools: vllm, llama.cpp, redis
1. Where the time and money go
Inference has two phases. Prefill processes the whole prompt in parallel and decides time to first token. Decode generates one token at a time, each needing a pass through the model and a read of all its weights, and decides total time. Decode is limited by memory bandwidth more than raw compute, which is why batching many requests together is so effective.
The KV cache stores attention keys and values for every token in flight so they aren't recomputed. Its size grows with context length times the number of concurrent requests, and on a busy server it, not the weights, decides how many users one GPU can serve.
Deep dive
Deep dive: prefill, decode and the KV cache
Generating text has two phases. Prefill runs the whole prompt through the model at once; it is one big matrix multiplication, limited by GPU compute, and it sets the time to first token. Decode then produces one token per forward pass. Each pass does little maths but must read every weight and the whole KV cache from GPU memory, so it is limited by memory bandwidth.
The KV cache stores the key and value vectors of every earlier token in every layer, so a new token computes only its own q, k and v and attends to the cache. Its size grows with tokens and with concurrent requests, which is why the cache, not the weights, usually decides how many users one GPU can serve.
vLLM’s PagedAttention stores the cache in fixed-size blocks, like virtual-memory pages, so memory isn’t reserved for the longest possible answer. Continuous batching adds new requests to the running batch at every decode step. Together they explain most of the throughput gap between vLLM and a naive server.
Worked example: the KV cache of Llama 3 8B in 16-bit
bytes per token = 2 (K and V) × layers × KV heads × head size × bytes
= 2 × 32 × 8 × 128 × 2 = 131,072 bytes = 128 KiB
one 8,192-token request = 8,192 × 128 KiB = 1 GiB
32 such requests = 32 GiB, on top of 16 GB of weights
one decode step at batch 1 reads ~16 GB of weights; at ~2 TB/s that is ~8 ms
→ at most ~125 tokens/s for one user; batching shares that read across users2. Serving engines: vLLM and llama.cpp
vLLM is the common choice for GPU serving: PagedAttention stores the KV cache in small pages (like virtual memory) so little is wasted, continuous batching adds new requests the moment a slot frees up, and it serves an OpenAI-compatible API. SGLang is a strong alternative with similar features.
llama.cpp (and Ollama, built on it) runs quantized GGUF models on CPUs, Apple silicon and modest GPUs. It is ideal for development, edge devices and low-traffic internal tools, not for high-concurrency serving.
3. Size the GPU before you buy it
Weights cost parameters × bytes per parameter: an 8B model is about 16 GB in bf16, 8 GB in 8-bit and roughly 4-5 GB in 4-bit. Whatever memory remains holds the KV cache, and that sets your concurrency. Use the sizer to see why quantization often increases capacity far more than the weight saving suggests.
Weights 16.1 GB · KV cache per full-length request 1074 MB (128 KB per token) · needed for 16 requests 34.2 GB of 22 GB usable
At most 4 full-length requests fit at once. The rest wait in the queue, so latency climbs.
vLLM’s paged KV cache only allocates for tokens actually used, so short requests fit many more than this worst case.
Guided experiments
- 8B model, bf16, 24 GB GPU, 8,192 context. How many requests fit? Switch the weights to 4-bit. Why does capacity jump so much more than the weight saving alone suggests?
- Raise context to 131,072 tokens. How many requests fit now? What does that tell you about offering “128k context” to every user?
- Try the 70B model on 80 GB, then on 160 GB. What is the smallest setup that serves 16 users at 8k context?
- Turn on the 8-bit KV cache. When would you accept the small quality risk for this gain?
4. Quantization without surprises
Quantization stores weights in fewer bits. Common formats: AWQ and GPTQ (4-bit, for GPU serving with vLLM), FP8 on recent NVIDIA GPUs, and GGUF variants such as Q4_K_M for llama.cpp. 8-bit is nearly lossless for most models; 4-bit usually costs a little quality, more on small models and on tasks like maths, code and non-English text.
Never assume: run your golden set on the quantized model and compare. A 1% drop in field accuracy can be a fine trade for a 3x capacity gain, or unacceptable, depending on the product.
Deep dive
Deep dive: quantization, one weight at a time
Quantization stores each weight as a small integer plus a shared scale. Symmetric absmax quantization to b bits sets scale = max|w| ÷ (2^(b−1) − 1), stores q = round(w ÷ scale) and uses w ≈ q × scale at run time. Every weight in the group snaps to one of a few evenly spaced values; the error is the rounding.
The catch is outliers. LLMs have a few weights and activations far larger than the rest. One of them sets the scale for its whole group, the spacing becomes huge and the ordinary weights round to zero. The quantization formats are mostly different fixes for this: small groups (every 32–128 weights get their own scale), keeping outliers in 16-bit (LLM.int8()), or rescaling channels by how much they matter before rounding (AWQ, GPTQ).
Worked example: 4-bit absmax on a group of four weights
weights = [0.021, −0.013, 0.004, 0.035] levels = 2^(4−1) − 1 = 7, so integers −7 … 7 scale = 0.035 / 7 = 0.005 q = round(w / s) = [4, −3, 1, 7] (4.2 → 4, −2.6 → −3, 0.8 → 1) dequantized = [0.020, −0.015, 0.005, 0.035] small errors now add an outlier 0.4 to the group: scale = 0.4 / 7 = 0.057 q = [0, 0, 0, 1, 7] dequantized = [0, 0, 0, 0.057, 0.4] three weights are gone
Representable values in the first group’s range: 15 ticks, spacing 0.0108 · error 15.3% of the typical weight size · small weights rounded to zero 22%
Storage: 4.02 bits per weight including the 16-bit scales, so a 7B model needs about 3.5 GB (16-bit: 14 GB).
Guided experiments
- 8-bit, per-tensor, no outliers. How big is the error? Drop to 4, 3 and 2 bits. Where does the error stop being small?
- 4-bit, per-tensor, then add the outliers. What happens to the tick spacing, and why does most of the tensor round to zero? This is what broke naive 8-bit quantization of large models.
- Keep the outliers and switch to groups of 64, then 32. Why does a smaller group help, and what does each group cost in extra storage?
- Tick “Keep outliers in 16-bit”. The error drops back. GPTQ and AWQ take other routes to the same goal: protect the weights that matter most. Which would you test first for a 4-bit deployment?
5. The cheapest call is the one you don’t make
Caching: an exact-match cache keyed on the normalised prompt, prompt version and model catches repeated requests. Semantic caches (match similar prompts) save more but can return a wrong answer for a subtly different question; use them only where that is acceptable.
Routing: send easy requests to a small, fast model and escalate only when a check fails (validation error, low confidence, specific document types). In many workloads most traffic is easy, so routing cuts cost several-fold. Measure before and after on cost, latency and accuracy.
Hands-on: coding window
The coding window and the full VS Code lab are available after you sign in.
Sign in to codeLabs
Lab 10.1: Serve with vLLM
On a rented or free GPU, serve a 3B-8B instruct model with vLLM in bf16 and in AWQ 4-bit. Load-test each with 1, 8 and 32 concurrent users and record time to first token, tokens per second and p95 latency.
Expected: A results table for both precisions and three concurrency levels, plus golden-set accuracy for each precision.
Lab 10.2: Router and cache (capstone increment)
Put a response cache and a router in front of the capstone’s model calls: small model first, escalate on validation failure or low confidence. Log which tier answered each request.
Expected: Before and after numbers for cost per document, p95 latency and field accuracy on the golden set; the share of traffic per tier.
Lab 10.3: Local CPU serving
Run the same model as Q4_K_M and Q8_0 GGUF with llama.cpp or Ollama on your laptop. Compare tokens per second and accuracy on 30 golden-set cases.
Expected: A short note on when local CPU serving is good enough for this capstone.
Go deeper
Videos
- Fast LLM Serving with vLLM and PagedAttention · Anyscale · ~32 min. The vLLM authors explain PagedAttention and why it raises throughput.
- Which Quantization Method is Right for You? (GPTQ vs. GGUF vs. AWQ) · Maarten Grootendorst · ~15 min. A clear comparison of the main quantization formats and when to use each.
- The KV Cache: Memory Usage in Transformers · Efficient NLP · ~9 min. Exactly how big the KV cache is and why it limits serving, with the formula worked through.
- What Is Quantization? How AI Models Get Smaller & Faster · IBM Technology · ~8 min. A short, accurate overview of what quantization does to weights and why it saves memory.
- How FlashAttention Accelerates Generative AI Revolution · Jia-Bin Huang · ~12 min. Why FlashAttention is faster without changing the result: it’s about memory reads, not maths.
- Speculative Decoding: When Two LLMs are Faster than One · Efficient NLP · ~13 min. Speculative decoding: how a small draft model speeds up a big one with identical outputs.
Further reading
- Paper Efficient Memory Management for Large Language Model Serving with PagedAttention · Kwon et al., SOSP 2023. The vLLM paper: why KV-cache fragmentation wastes memory and how paging fixes it.
- Article A Visual Guide to Quantization · Maarten Grootendorst. Dozens of diagrams from absmax to GPTQ, AWQ and GGUF; the best single explainer of LLM quantization.
- Paper LLM.int8(): 8-bit Matrix Multiplication for Transformers at Scale · Dettmers et al., 2022. Where the outlier problem was first measured, and the mixed-precision fix.
- Paper AWQ: Activation-aware Weight Quantization · Lin et al., 2023. Protect the 1% of weights that matter by scaling channels before rounding.
- Paper FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness · Dao et al., 2022. Exact attention that is faster because it reads and writes GPU memory less.
- Paper Fast Inference from Transformers via Speculative Decoding · Leviathan et al., 2022. A small draft model proposes tokens and the big model checks them in one pass, with identical outputs.
- Docs LLM inference optimization · Hugging Face Transformers docs. KV-cache types, static caches, compilation and attention kernels in one page.
GitHub repositories
- vllm-project/vllm: The OpenAI-compatible server docs, quantization options and the benchmarks folder for load testing.
- ggml-org/llama.cpp: tools/server for the HTTP server, and the quantization README for GGUF types.
- sgl-project/sglang: RadixAttention prefix caching: a different approach to sharing prompt prefixes across requests.
Checkpoint quiz
Interview questions
- Explain prefill and decode. Which one does batching help most, and why?
- How many concurrent users can one 24 GB GPU serve with an 8B model at 8k context? Walk through the estimate.
- How would you decide between 8-bit and 4-bit quantization for a product?
- Design a router that cuts LLM cost without hurting quality. How do you prove it works?
- When would you self-host a model instead of using an API?
Ask the professor
Sign in to ask questions about this module.
Discussion
Community discussion appears here once giscus is configured (see README).