chapter 09 / llm-inference · estimated study time 120-150 min

LLM Inference & Deployment
Every token is money

AUDIO // Chapter audio guide
Chapter contents
  1. Two radically different phases: Prefill and Decode
  2. KV Cache: buying time with VRAM
  3. Interactive Lab ①: KV Cache VRAM calculator
  4. Three generations of KV savings: MQA → GQA → MLA
  5. vLLM: bringing the wisdom of operating systems into VRAM
  6. Quantization: the spectrum of trading precision for throughput
  7. Speculative decoding: free acceleration
  8. The sampling toolkit: temperature's fourth appearance
  9. Cost engineering: putting the inference bill into the product
  10. Interactive Lab ②: product inference cost estimator
  11. Chapter quiz

Two radically different phases: Prefill and Decode

The mine planted in Chapter 6 now officially explodes: training can run in parallel over an entire sentence, but generation must proceed token by token, serially. A single inference actually contains two phases with completely opposite personalities:

Prefill (reading the prompt)Decode (generating token by token)
Compute patternThe entire prompt processed in parallel in one matrix multiplyEach step computes only 1 token
BottleneckCompute-bound (saturates GPU compute)Memory-bandwidth-bound: every token generated requires hauling all the weights from VRAM into the compute units once
User perceptionTime to first token (TTFT)Generation speed (tokens/s)

Decode's bandwidth ceiling can be computed in your head directly: tokens/s ≈ VRAM bandwidth ÷ model bytes. An H100 (3.35TB/s) running a bf16 70B (140GB): single-stream ceiling ≈ 24 tokens/s—no card, however expensive, can break physics. This roofline intuition explains half the techniques in this chapter: quantization (making the model bytes smaller), batching (hauling the weights once to serve multiple requests), speculative decoding (hauling the weights once to verify multiple tokens)—all of them wrestle with the single act of "hauling the weights."

KV Cache: buying time with VRAM

Naive generation recomputes attention over the entire history for every new token—turning $O(n^2)$ complexity into $O(n^3)$ over the whole generation, which is unacceptable. Observation: under a causal mask, the K and V of historical tokens never change (they depend only on the content before themselves). So store them: each time a token is generated, compute only its own q/k/v, append the new k/v to the cache, and have attention query the cache directly. The KV footprint per token has a must-memorize formula:

$$\text{KV bytes/token} = \underbrace{2}_{K\text{ and }V} \times L \times n_{kv} \times d_{head} \times \underbrace{2}_{bf16}$$

LLaMA-3 8B ($L{=}32, n_{kv}{=}8, d_{head}{=}128$): 128KB/token—a single sequence at 8K context is 1GB, and at 128K context it is 16GB (larger than the model weights). The real cost of long context lies not in compute but in VRAM, and it grows linearly with batch size—this is why "concurrency" became a core parameter of inference serving.

Interactive Lab ①: KV Cache VRAM calculator

Must-do experiments: ① 8B + 128K context—the KV is larger than the weights; ② switch to GPT-3-style MHA—the horrifying bill of 96 unshared KV heads makes it instantly obvious why GQA became standard; ③ switch to DeepSeek MLA—at the same context the KV shrinks by an order of magnitude, which is the hardware reason it can serve long context cheaply.

kv-cache.calculator

Formula: 2 × L × n_kv × d_head × 2 bytes × context × concurrency · verdict includes a rough estimate with weights

Three generations of KV savings: MQA → GQA → MLA

VIDEO 01
How DeepSeek Rewrote the Transformer [MLA]
Welch Labs 18:09
Viewing guide · the best video version of this chapter's §1-§4
  • 02:30 Why the KV cache exists and how large it is—an animated derivation of the §2 formula.
  • 07:00 The trade-offs of MQA/GQA.
  • 10:30 The geometric intuition of MLA's low-rank compression + the engineering details of RoPE compatibility—the source of generation speed 6× that of a naive Transformer.

vLLM: bringing the wisdom of operating systems into VRAM

Inference serving before 2023 had a hidden waste: the KV cache was pre-allocated as contiguous VRAM at the "maximum possible length," while only a small portion was actually used—VRAM utilization was often below 40%. vLLM's PagedAttention brought over the whole approach of OS virtual memory: the KV is split into fixed-size blocks (e.g., 16 tokens/block), logically contiguous but physically scattered, allocated on demand. Combined with continuous batching (instead of waiting for an entire batch to finish, whenever a sequence ends a new request is swapped in immediately, so the GPU never sits idle), throughput improves 2-4×. Today vLLM/SGLang are the de facto standard for open-source inference serving—between "running a model" and "efficiently serving a model" lies an entire discipline of systems engineering.

Quantization: the spectrum of trading precision for throughput

The roofline already said it: decode speed ≈ bandwidth ÷ model bytes. Halve the bytes and speed roughly doubles while VRAM halves—quantization is inference's most cost-effective lever:

SchemeBit widthKey points
bf1616Baseline
FP88Natively supported on H100, works for both training and inference, nearly lossless—the new default at frontier labs
INT8 (LLM.int8)8Per-channel scaling + outlier separation (LLM activations have a few enormous outlier dimensions; those whole columns are kept in fp16)
GPTQ / AWQ4Post-training weight quantization: GPTQ minimizes second-order error layer by layer; AWQ protects important weights according to activation magnitude. ~1% loss for 4× compression
KV cache quantization8/4The second battlefield beyond weights—huge gains in long-context scenarios (directly cuts the bill from §2)

Rule of thumb: 4-bit weights are the last stop before the quality cliff (below 3 bits the quality drops noticeably); more parameters + aggressive quantization usually beats fewer parameters + full precision (70B-int4 ≳ 13B-bf16).

Speculative decoding: free acceleration

Decode is bandwidth-bound → the GPU compute units sit largely idle → could we "haul the weights once and verify multiple tokens"? Speculative decoding: a small draft model quickly guesses k tokens, and the large model verifies them in parallel in one forward pass. The key is that it is mathematically lossless: each guessed token is accepted with probability $\min(1, p_{target}/p_{draft})$, and at a rejection point it resamples from the corrected distribution—it can be proven that the final output distribution is exactly identical to that of the large model sampling on its own. If the draft is right you gain k× speed; if it is wrong you only waste a little idle compute. Typical speedup is 2-3×, especially in domains like code where "the next token is often quite certain." Variants: self-drafting (Medusa/EAGLE add lightweight prediction heads to the large model), n-gram matching (copying the answer from the prompt).

The sampling toolkit: temperature's fourth appearance

Once the model gives the next-token distribution, how do you choose? Greedy (always take the maximum) gets trapped in repetition loops ("I think I think I think"—high-probability phrases reinforcing each other). The practical combo:

Cost engineering: putting the inference bill into the product

In a scaled product, model selection is essentially unit economics. Three levers, in order of priority:

  1. Prompt caching (the most easily underestimated): APIs charge 10-25% of the price for cache-hit input tokens. The mechanism: the KV cache of the prefix shared across requests (system prompt, template, few-shot examples) is reused directly (the §2 KV does not need recomputing = does not need to be re-charged). The key engineering insight: real applications have a hit rate far higher than benchmark estimates—especially in remix/template-type scenarios, where huge volumes of requests have nearly identical inputs (same template + same asset library), and an 80-90% hit rate is not rare. When designing prompts, putting the fixed part first and the variable part last is the structural discipline of getting a free discount.
  2. Usage funnel design: the generation cost of a content product is determined by the funnel—when consumption : remix : PGC ≈ 1 : 1/100 : 1/1000 in magnitude, the vast majority of DAUs only read ready-made content (zero generation cost), and only creative actions burn tokens. A product structure of "consume first, create later" is itself cost control. Drag the remix rate around in the estimator below to feel the impact on the bill of tightening the funnel by one notch each time.
  3. Model tiering: high-frequency, narrow-domain, formatted functions (your pixel-art JSON!) get pushed down to flash-tier APIs or self-trained small models (the Chapter 8 SFT loop); low-frequency, open-domain, high-value ones are left to the flagship model. "Hitting the flagship model on every request" is the most common money-burning posture of startups.

Interactive Lab ②: product inference cost estimator

Must-do experiments: ① default parameters (100,000 DAU, remix 1/100, PGC 1/1000, cache hit 70%) and compare the monthly bills of the three model tiers; ② pull the cache hit to 0 and then to 95%—understand why "input structure design" is valuable; ③ pull the remix rate from 1/100 to 1/10 (the product blows up and everyone is creating)—watch the flagship model's bill spiral out of control, and why self-hosted small models are an order-of-magnitude difference in high-frequency scenarios.

inference-cost.estimator

Monthly cost = 30 × daily generations × (missed input × base price + hit input × cache price + output × output price) · all sliders draggable

Why is the output token in API pricing usually 4-5× the input? Explain using this chapter's prefill/decode framework.
Input is processed in the prefill phase: all tokens in one parallel matrix multiply, compute-intensive, with high GPU utilization and a low amortized per-token cost. Output is produced in the decode phase: every token requires hauling the entire set of weights once (bandwidth-bound, low utilization), plus maintaining the KV cache and batch scheduling for it. This cost-structure difference is written directly into the price tag. The same logic explains: why prompt caching discounts can reach 75-90% (a cache hit saves even the prefill, leaving only storage cost); and why "long input, short output" tasks (such as classification and extraction) have a far lower unit cost than "short input, long output" (such as writing).

Chapter quiz