Part 09›
✎

08. Efficient LLM Inference and Deployment#

Level: Practitioner · Reading time: 24 min · Exercise: 60 min Prerequisites: Neural Network Basics for Efficiency (latency versus throughput), Quantization

In one sentence: After this chapter you can estimate a language model's memory and speed on paper, and choose among quantization, attention, KV cache, batching and decoding optimizations for your serving situation.

Why this matters#

You deploy a chat model on one GPU. The first user gets answers at a good pace. Thirty users join and memory runs out. The weights did not change. What grew was a cache that nobody had sized, and each new token now waits behind the others.

LLM inference has two phases with opposite bottlenecks and a memory footprint that keeps growing. Most deployment mistakes come from optimizing one phase and not noticing the other.

The core idea#

A modern language model generates text one token (a chunk of text, roughly a short word) at a time. Each pass through the model has two phases:

The KV cache is what makes decode affordable. In attention, each token looks at every earlier token. Instead of recomputing the key and value vectors of all earlier tokens at every step, the engine stores them. The cost: the cache grows with every token of every request.

The analogy is an incremental build cache. Recompute nothing, look up what you already have. The analogy breaks on size: a build cache is bounded by your source tree, and the KV cache grows with context length times users, and the model has to read it at every step.

How it works: count first#

KV cache bytes = 2 × layers × KV heads × head dimension × tokens × batch × bytes per value

The leading 2 is for keys and values, two of the vectors that attention computes for each token. Each layer computes attention in several heads, parallel sub-calculations, each with its own head dimension; KV heads counts those that produce keys and values. Han's slide from Lecture 15 works the example for Llama-2-70B as if it had no head sharing: 2 × 80 layers × 64 heads × 128 = 2.5 MB per token. Then 4,096 tokens take 10 GB, and a batch of 16 such requests takes 160 GB (22:00). The cache can outgrow the weights.

Decode speed follows from Chapter 02: time per token is about the bytes moved divided by memory bandwidth. Bytes moved per token = weights + KV cache read.

Each technique below attacks one of these three quantities: weight bytes, cache bytes, or arithmetic.

1. Quantization: weight-only or weights and activations#

2. Attention without the N × N matrix#

Plain attention writes an N × N table of attention weights to memory. FlashAttention splits the computation into tiles that fit in fast on-chip memory and never writes that table. The result is mathematically the same. Han describes it as fusing the separate kernels for the query-key product, softmax and the multiply by values (Lecture 13, 70:00). Accuracy cost: none. It mainly helps prefill and long contexts, where the table would be large.

3. Shrink the KV cache#

Technique What it does Cost
Grouped-query attention many query heads share a few key-value heads a little accuracy; needs training or conversion
PagedAttention (vLLM) stores the cache in fixed-size pages allocated as needed none in accuracy; engineering
KV cache quantization stores keys and values in 8 or 4 bits small; keys after rotation are harder
Attention sinks and windows keeps the first few tokens plus a sliding window loses the middle of very long contexts
DuoAttention classifies heads into retrieval heads (full cache) and streaming heads (window) training a small set of gates
Quest loads only the cache pages that matter for the current token approximate

4. Speculative decoding: several tokens per step#

At batch 1, the large model spends its time reading weights. Verifying a wrong token costs as little as verifying a right one, so extra candidates are nearly free.

  1. A small draft model proposes the next few tokens.
  2. The large model checks all of them in one pass.
  3. The longest prefix it agrees with is accepted. At the first disagreement it resamples.
  4. Repeat.

Figure 1. Speculative decoding: a cheap draft, one verification pass, and a loop back for whatever was rejected.

flowchart LR
    D["Draft model proposes a few tokens"] --> V["Large model checks them in one pass"]
    V -->|"agrees"| A["Accept the agreed prefix"]
    V -->|"disagrees"| R["Resample at the first wrong token"]
    A --> N["More tokens needed"]
    R --> N
    N --> D
    N -->|"answer complete"| E["Output identical to the large model alone"]

Each turn costs one pass of the large model for several tokens, which is why the gain is largest when one user has the GPU to itself.

The output distribution matches the large model's. Han reports about 2 to 3 times faster generation with identical outputs (Lecture 13, 72:00). It helps most for a single user and least for a full batch, where arithmetic is already the limit.

5. Batch the requests#

Batching Rule Good for Problem
None run each request as it arrives nothing much GPU sits idle between steps
Static wait for a full batch offline jobs waiting time for real-time use
Dynamic run when the batch is full or a timer fires workloads of equal length short requests wait for long ones
Continuous (in-flight) re-form the batch after every token chat most complex to build

Han's picture for dynamic batching is a bus that leaves "when it's full or when the timer expires" (74:00). For continuous batching, passengers get off at different stops and new ones board at once. The picture breaks in one way: the bus never empties. The engine rebuilds its batch at every single token.

6. Long context: extend, then verify#

7. Metrics and serving choices#

Metric Meaning Set by
Time to first token (TTFT) delay before the answer starts prompt length, prefill speed
Time per output token (TPOT) delay between tokens weight and cache traffic, batch size
Throughput tokens per second across all requests batch size, arithmetic

Total latency = TTFT + TPOT × output tokens (Han, Lecture 13, 64:00). Throughput and TPOT pull in opposite directions.

Situation Choices
One user on a laptop or phone small model, 4-bit weights, 16-bit activations, head sharing
A server with many users continuous batching, paged cache, 8-bit weights and activations if arithmetic-bound
Very long documents head sharing, cache quantization, retrieval, then a needle test
Several GPUs parallelism; see parallelism

How this fits into a production system is covered in deploying a model; the architecture itself in transformer architectures.

Worked example#

A capacity and speed calculator for a 7-billion-parameter model with 32 layers and 32 heads of dimension 128.

def kv_cache_bytes(tokens, batch, layers, kv_heads, head_dim, bytes_per_value=2):
    return 2 * layers * kv_heads * head_dim * tokens * batch * bytes_per_value

def decode_ms(weights_gb, kv_gb, bandwidth_gbps=50.0):      # laptop-class bandwidth
    return (weights_gb + kv_gb) / bandwidth_gbps * 1e3

W16, W4 = 14.0, 3.5                                          # weight memory in GB

for tokens in (1_000, 8_000, 32_000):
    kv = kv_cache_bytes(tokens, 1, 32, 32, 128) / 1e9        # no head sharing
    kv_gqa = kv_cache_bytes(tokens, 1, 32, 8, 128) / 1e9     # 8 shared KV heads
    print(f"{tokens:>6} tokens: KV {kv:5.2f} GB (shared {kv_gqa:4.2f}) | "
          f"16-bit {decode_ms(W16, kv):5.1f} ms/token | "
          f"4-bit {decode_ms(W4, kv):5.1f} | 4-bit+shared {decode_ms(W4, kv_gqa):5.1f}")

What to observe:

The estimates ignore compute time, so they are floors for latency.

What the practitioners say#

Pitfalls#

  1. Quantizing weights to 4 bits on a busy server. Fix: at large batch the job is arithmetic-bound; use 8-bit weights and activations instead.
  2. Sizing memory from the weights alone. Fix: add the KV cache at your longest context and largest batch.
  3. Reporting throughput when users feel TPOT. Fix: record TTFT, TPOT and throughput together.
  4. Static batching for chat traffic. Fix: continuous batching.
  5. Trusting a long-context claim. Fix: run a needle test at your real lengths.
  6. Mixed-precision tensors without a kernel for them. Fix: use a format your engine implements.
  7. Expecting speculative decoding to help a full batch. Fix: measure at your real batch size.

Try it#

Build a capacity sheet for one open model and one machine.

  1. From the model card, collect layers, heads, head dimension, KV heads and parameter count.
  2. Compute weight memory at 16-bit and 4-bit, and cache size per 1,000 tokens.
  3. Compute how many concurrent users fit at 8,000 tokens each, in both precisions.
  4. Run the model locally at two precisions. Measure TTFT and TPOT for a 500-token prompt and 200 output tokens.

You are done when the sheet shows a formula next to every number, and one sentence explains any gap larger than 2 times between estimate and measurement.

Stretch: repeat the measurement with 1, 4 and 16 concurrent requests and plot TPOT against batch size.

Key takeaways#

Self-check#

  1. A model has 40 layers, 8 KV heads, head dimension 128, 16-bit cache. How much cache does one 2,000-token request use?
  2. Why does 4-bit weight quantization help a single user far more than a full batch?
  3. What does FlashAttention change about the mathematics of attention?
  4. A sliding-window cache makes the model produce garbage after a few thousand tokens. What is missing?
  5. In speculative decoding, why is checking four draft tokens almost as cheap as checking one at batch 1?
  6. Your p90 time per output token doubles when traffic triples, while throughput rises. Which two techniques do you apply first?
Show answers 1. 2 × 40 × 8 × 128 × 2,000 × 2 bytes = 327,680,000 bytes, about 0.33 GB. 2. At batch 1 the step is limited by reading the weights, and 4-bit weights are a quarter of the bytes. At large batch arithmetic dominates, and 4-bit weights do not reduce the arithmetic. 3. Nothing. It computes the same attention exactly and avoids writing the N × N table to memory. 4. The attention sinks: the first tokens must stay in the cache. 5. Because the large model still reads its weights only once per pass; verifying more candidates adds arithmetic, which is cheap when memory is the limit. 6. Continuous batching and a paged KV cache, then quantization of weights and activations if arithmetic-bound.

Sources#

Next#

→ LLM Post-Training and On-Device Training, for when the model on the device also has to learn from the device's data.