← AI Engineering Latent Shelf · Ch.9

Book Study Guide · Chip Huyen · Chapter 9

Inference Optimization

New models come and go, but one thing stays relevant: making them better, cheaper, and faster. Earlier chapters made models better — this one makes them faster and cheaper.

— the optimization mandate

No matter how good a model is, if it's too slow or too costly it's useless. This chapter explains the computational bottlenecks of inference, the metrics that matter (latency, throughput, goodput), and the two families of fixes: model-level optimization and inference-service-level optimization.

compute vs memory-boundlatency & throughputquantizationbatching15 quiz questions
01The landscape

Where inference time actually goes

Inference is the phase where a trained model computes outputs for requests (as opposed to training, which builds the model). It's run by an inference server (hosting models on hardware) inside a broader inference service (routing and preprocessing). Optimization can happen at three levels: the model (make it smaller or more efficient), the hardware (faster chips), and the service (schedule and batch work well). If you use a model API you skip most of this; if you self-host, it's your job.

Key concept · Compute-bound vs. memory-bandwidth-bound

Every workload has one of two bottlenecks. Compute-bound: time is set by the sheer number of calculations (e.g. image generation with Stable Diffusion). Memory-bandwidth-bound (often just "memory-bound"): time is set by how fast data moves between memory and processors. Which one you hit is captured by arithmetic intensity (operations per byte of memory access) and visualized on a roofline chart. The fix differs: compute-bound work wants more/faster compute (higher FLOP/s); memory-bound work wants higher bandwidth. Today, many transformer workloads are memory-bandwidth-bound.

Key concept · Prefill and decode — two different profiles

Autoregressive LLM inference has two steps with opposite characteristics. Prefill processes all input tokens in parallel — it's compute-bound, and its duration sets the time to the first token. Decode generates output tokens one at a time, each step loading the large weight matrices, so it's memory-bandwidth-bound. Because their profiles differ, production servers often decouple prefill and decode onto separate machines. The factors that drive an LLM server's bottlenecks are context length, output length, and batching strategy.

02Metrics & APIs

What to measure before you optimize

From the user's side the central axis is latency; developers must also track throughput and utilization because they set cost. (Response quality is a property of the model, not the inference service.)

Key concept · Latency — TTFT, TPOT, and percentiles

For streaming generation, break latency into time to first token (TTFT) — how fast the first token appears, tied to the prefill step and input length — and time per output token (TPOT) (a.k.a. time between tokens / inter-token latency) — how fast each subsequent token comes. A useful identity: total latency ≈ TTFT + TPOT × (number of output tokens). Two apps with the same total can feel different — instant first token with slow generation, or a slower start with fast generation — and you can trade TTFT for TPOT by shifting compute between prefill and decode. Because latency is a distribution, don't report the average (outliers skew it): use percentiles — p50 (median), p90, p95, p99. A TPOT of ~120 ms (6–8 tokens/sec) beats human reading speed and is enough for most apps.

Key concept · Throughput, goodput, and the trade-off

Throughput is output tokens per second across all requests (tokens/s, or tokens/s/user; also requests/min). It's tied directly to cost — higher throughput means lower cost per token — so compare servers by cost per request rather than raw tokens/s (tokenizers differ). But maximizing throughput can wreck latency (batching more requests raises throughput while slowing each one). So teams track goodput: the requests per second that meet your latency SLO — if a server does 100 req/min but only 30 satisfy the "TTFT ≤ 200 ms, TPOT ≤ 100 ms" target, its goodput is 30. Online APIs optimize for latency (process on arrival, often with a streaming mode); batch APIs optimize for cost (relaxed latency allows heavy batching and cheaper hardware — often ~50% cheaper, in hours not seconds).

03Model-level optimization

Making the model itself cheaper to run

These techniques change the model. Some are lossy (they can cost a little quality), so measure against your evaluation pipeline after applying them.

Key concept · Quantization, distillation, pruning

Three classic ways to shrink a model. Quantization — represent weights/activations in fewer bits (16 → 8 → 4) — is the most popular because it's simple, general, and needs no retraining; it makes the model smaller and faster and is the easiest big win. Distillation — train a small "student" to mimic a large "teacher," getting most of the quality at a fraction of the size. Pruning — remove parts of the network that contribute little (drop connections, or set weights to zero for sparsity). Quantization is usually the first lever to reach for.

Key concept · Attention and the KV cache

Much of an LLM's inference cost lives in attention. During decoding, the model would recompute the keys and values for every prior token at each step, so servers keep a KV cache — storing past keys/values to avoid recomputation. The catch: the KV cache grows with sequence length and batch size and often dominates memory. Optimizations target exactly this: FlashAttention restructures the attention computation to cut slow memory reads/writes (a big speedup), and PagedAttention manages the KV cache in fixed-size "pages" like an operating system's virtual memory (from vLLM), reducing waste and letting you batch more. Some models also cut cost with attention variants (e.g. multi-query / grouped-query attention) that share keys/values across heads.

04Service-level optimization

Scheduling the work well — without touching the model

Service-level techniques leave the model unchanged and optimize how requests are run. They're often the highest-leverage fixes because they don't cost quality.

Key concept · Batching

Running requests together amortizes the cost of loading weights, so batching is the single biggest throughput lever. Static batching waits to fill a fixed-size batch (simple, but early-finishing requests wait for the slowest). Dynamic batching forms a batch within a time window. Continuous batching (a.k.a. in-flight batching) is the LLM-specific winner: because generation is token-by-token, the server can add and evict requests every step as some finish, keeping the hardware busy without making short requests wait for long ones — a large throughput gain at little latency cost.

Key concept · Parallelism, prompt caching, speculative decoding

When a model or workload is too big for one device, split it: replica/data parallelism (copies handle different requests), tensor parallelism (split one layer's math across devices — lowers latency), and pipeline parallelism (put different layers on different devices). Two more high-value tricks: prompt caching reuses the computation for repeated prompt prefixes — long system prompts, a shared document, conversation history — so you don't re-prefill them every call (big savings for chat and RAG); and speculative decoding runs a small, fast "draft" model to propose several tokens that the large model then verifies in parallel, accelerating the memory-bound decode step with no loss in output quality. Underneath it all sit AI accelerators (GPUs/TPUs) chosen for their compute, memory, and bandwidth.

★Test yourself

Chapter 9 quiz

Fifteen questions on bottlenecks, metrics, and optimization. Answer first, then expand Show answer.

Part A · Multiple choice

Q1

Inference optimization can happen at which three levels?

  • A Model, hardware, and (inference) service
  • B Prompt, RAG, finetuning
  • C Data, model, infra
  • D CPU, GPU, TPU
Show answer

A.

Q2

A memory-bandwidth-bound task is limited by:

  • A How fast data moves between memory and processors
  • B The number of calculations
  • C The prompt's wording
  • D The tokenizer
Show answer

A. Compute-bound is instead limited by the amount of computation.

Q3

In LLM inference, the decode step is typically:

  • A Memory-bandwidth-bound (loads large weight matrices per token)
  • B Compute-bound
  • C Free
  • D Done in parallel over all tokens
Show answer

A. Prefill (parallel over input tokens) is compute-bound.

Q4

TTFT measures:

  • A How quickly the first token is generated (tied to prefill)
  • B Tokens per second
  • C Cost per request
  • D Time between later tokens
Show answer

A. TPOT measures the time per subsequent output token.

Q5

Total latency is approximately:

  • A TTFT + TPOT × (number of output tokens)
  • B TTFT × TPOT
  • C TPOT − TTFT
  • D Just the average
Show answer

A.

Q6

Why report latency in percentiles (p50, p90, p99) instead of the average?

  • A Outliers skew the average and hide the real distribution
  • B Averages are illegal
  • C Percentiles are cheaper to compute
  • D There's no difference
Show answer

A. Percentiles also help spot outliers.

Q7

Goodput measures:

  • A Requests per second that satisfy the latency SLO
  • B All requests regardless of latency
  • C Total tokens ever generated
  • D Model accuracy
Show answer

A. It guards against maximizing throughput at the expense of user experience.

Q8

The most popular, retraining-free way to make a model smaller and faster is:

  • A Quantization
  • B Adding parameters
  • C Raising temperature
  • D Prompt caching
Show answer

A. Distillation and pruning are the other model-level techniques.

Q9

The KV cache exists to:

  • A Avoid recomputing keys/values for previous tokens during decoding
  • B Store the prompt text
  • C Compress the model
  • D Cache API responses
Show answer

A. It grows with sequence length and often dominates memory (PagedAttention manages it).

Part B · True or false

Q10

Higher throughput generally lowers cost per token.

Show answer

True. Throughput is tied directly to compute cost.

Q11

Continuous (in-flight) batching lets the server add and evict requests each decoding step.

Show answer

True. Short requests don't have to wait for long ones — a big throughput win.

Q12

Speculative decoding reduces output quality to gain speed.

Show answer

False. A draft model proposes tokens the large model verifies in parallel — same output, faster decode.

Q13

Batch APIs optimize for cost, accepting higher turnaround time.

Show answer

True. Online APIs instead optimize for latency.

Part C · Short answer

Q14

Why are prefill and decode often run on separate machines?

Show answer

They have opposite computational profiles — prefill is compute-bound (parallel over input tokens), decode is memory-bandwidth-bound (one token at a time) — so decoupling lets each be optimized and scaled independently.

Q15

What does prompt caching save, and when does it help most?

Show answer

It reuses the computation for repeated prompt prefixes (long system prompts, a shared document, conversation history) so they aren't re-prefilled each call — biggest wins for chat and RAG.