Skip to content

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.

Requestprompt + paramsCacheexact / semanticRouterrules or classifierSmall modelquantized, fastCheckconfidence / schemaLarge modelescalation pathvLLMcontinuous batchingKV cachepaged GPU memoryGPUweights + KVCheapest correct answer firstInside the inference serverlow confidence: escalatehit: skip the model
Most cost and latency wins come from not calling the big model: caching, routing, and right-sized quantized models.

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 users
Prompte.g. 2,000 tokensForward passall in parallelKV cacheK, V per tokenFirst tokentime to 1st tokenNew tokenjust 1 vectorAttendto all cached K, VAppendits K, V to cacheSampleuntil stop tokenPrefill: the whole prompt in one pass (compute-bound)Decode: one token per step (memory-bound)read every stepnext step
Without the cache, every step would recompute keys and values for the whole sequence. With it, each step reads the whole cache from GPU memory, which is why decode speed is set by memory bandwidth.
Common misconception: “The model is slow” usually means one of two different problems. A slow first token is prefill (long prompts, no prompt caching); slow streaming is decode (memory bandwidth, batch size). Measure time to first token and tokens per second separately.

2. 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.

In production: Turn on prefix caching in vLLM when many requests share a long system prompt. Shared prefixes are computed once and reused.

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.

GPU memory for servingWeights are a fixed cost. The KV cache grows with context length × requests in flight, and that decides how many users one GPU can serve.

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
  1. 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?
  2. Raise context to 131,072 tokens. How many requests fit now? What does that tell you about offering “128k context” to every user?
  3. Try the 70B model on 80 GB, then on 160 GB. What is the smallest setup that serves 16 users at 8k context?
  4. 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.

Common misconception: “4-bit is always fine.” It is often fine for large models in English. Small models and Indian-language text can degrade noticeably. Measure on your own task.

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
Quantization, one weight at a timeEach weight becomes round(w / scale), an integer between −7 and 7; scale = the largest |w| in its group ÷ 7. The bars are the weights; the ticks are the only values left after quantizing.
−0.080.08

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
  1. 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?
  2. 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.
  3. 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?
  4. 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?
In production: Always re-run your eval set after quantizing. 8-bit is usually indistinguishable; 4-bit with a good method (AWQ, GPTQ, GGUF Q4_K_M) usually costs a little; 3-bit and below often breaks reasoning and long-context tasks first.

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 code

Labs

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

Further reading

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

1. On a busy GPU server, what usually limits how many requests run at once?
2. What does continuous batching do?
3. Moving an 8B model from bf16 to 4-bit on a 24 GB GPU mainly…
4. Which statement about quantization is safest?
5. Why include the prompt version and model in a cache key?
6. Llama 3 8B has 32 layers, 8 KV heads and head size 128. In 16-bit, how much KV cache does one token need?
7. Why does one outlier weight hurt per-tensor 4-bit quantization so much?

Interview questions

  1. Explain prefill and decode. Which one does batching help most, and why?
  2. How many concurrent users can one 24 GB GPU serve with an 8B model at 8k context? Walk through the estimate.
  3. How would you decide between 8-bit and 4-bit quantization for a product?
  4. Design a router that cuts LLM cost without hurting quality. How do you prove it works?
  5. 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).