Cheat sheet · Module 14
Cheat sheet: Inference engineering
Generative AI · Cheat sheet · Inference engineering
Definition: Inference engineering is making a trained model fast, cheap and reliable to run. Predict with FLOPs, bytes and the roofline first; then measure on your own traffic; then change one lever and state its price.
Arithmetic (assumptions in brackets): decode step ≥ weight bytes ÷ (bandwidth × GPUs) [weights only]; 8B in BF16 on an H100 (3.35 TB/s) is 16 GB ÷ 3.35 TB/s = 4.8 ms, at most about 209 tokens per second. Ridge = dense peak FLOP/s ÷ bandwidth (H100 about 295, A100 80 GB about 153, using the dense figure, half the “with sparsity” listing). KV bytes per token = 2 × layers × KV heads × head dim × bytes. KV budget = memory × utilization − weights − overhead. Speculative speedup = (1 − α^(γ+1)) ÷ ((1 − α)(γc + 1)). Cost per million tokens = price per hour ÷ (tokens per second × 3,600) × 10⁶, divided again by utilization. Replicas = peak ÷ per-replica goodput ÷ 0.6 to 0.7, plus a spare. Little’s law: in flight = rate × time.
Request path and metrics
- Tokenize, queue, prefill (all prompt tokens in parallel), decode (one token per step), stream.
- TTFT = queue + prefill (+ network). ITL = (end-to-end − TTFT) ÷ (output tokens − 1). Goodput = requests per second that meet the targets.
- Quote throughput with the token type, the load and the latency. Tools define metrics differently.
Roofline
| Phase | Intensity | Usually |
|---|---|---|
| Decode, batch B, b bytes per weight | about 2B ÷ b (B for BF16) | memory-bound |
| Prefill, n tokens | about n for BF16 | compute-bound only if n is above the ridge |
- Decode reaches the ridge at B* = ridge × b ÷ 2. With 8-bit math (W8A8 or FP8) the crossing stays near 295 on an H100; weight-only 8-bit with BF16 math halves it to about 148.
- Weights-only ceilings ignore the KV read, communication and overhead.
Memory and the KV-cache
- Use KV heads, not attention heads. Llama 3 8B in 16-bit is 128 KiB per token; 70B is 320 KiB.
- Fits is not serves: weights can fit and leave no cache.
- Each step also reads every sequence’s cache, so at large batch the caches can outweigh the weights.
- PagedAttention: blocks and block tables, waste at most part of one block; larger batches; not a smaller cache or faster attention.
- Prefix caching: identical prefix at the start, same model and adapter, same engine. Not a response cache. Saves prefill and memory, not decode.
- GQA and MLA shrink the cache by design; KV quantization doubles capacity at 8 bits and needs validation on your own long inputs.
- Full pool: queue, preempt (recompute or swap) or shed. Watch the preemption count.
Kernels and numerics
- FlashAttention is exact and tiled; it helps prefill most, not single-query decode.
- Quantization stores scale × integer. Outliers break per-tensor 8-bit. Memory-bound: weight-only. Compute-bound: W8A8 or FP8. Check hardware support (FP8 W8A8 is listed for Ada and Hopper, not Ampere, in vLLM’s table).
- LLM.int8 keeps outliers in 16-bit; GPTQ compensates rounding with second-order information; AWQ protects salient channels; SmoothQuant moves difficulty into the weights.
- Validate on task evaluations and slices against the baseline; perplexity alone is not enough.
- CUDA graphs remove launch overhead (padded to captured sizes); fusion removes memory round trips.
- Temperature 0 is greedy, not bit-reproducible: batch-dependent reduction order. Batch-invariant kernels cost speed.
Scheduling and decoding
- Continuous batching re-forms the batch every step. A large prefill stalls decode: 16,000 tokens on an 8B model is at least about 259 ms at peak.
- Chunked prefill: a token budget per step. Smaller budget, smoother ITL; larger budget, faster TTFT for long prompts.
- Little’s law: sustainable rate = concurrency limit ÷ time per request. Beyond it, queues grow. Admission control, priorities, cancellation on disconnect.
- Speculative decoding keeps the target distribution; gains fall at high batch (verifying about (γ + 1) × B tokens) and low acceptance.
- Disaggregation: separate prefill and decode pools plus a KV transfer; chunked prefill first for small deployments.
- Constrained decoding masks tokens; valid is not correct.
Parallelism, engines and hardware
- Smallest degree that fits; then replicas. TP in a fast-link node (all-reduces inside layers); PP across nodes; EP for experts (all-to-all, imbalance); DP for volume.
- Mixture of experts: compute by active parameters, memory and bandwidth by total as the batch grows.
- Multi-LoRA: one base plus small adapters; per-adapter prefix caches.
- Choose engines by criteria and your own traffic; check status (TGI was archived 2026-03-21). Hardware: capacity, bandwidth, compute, interconnect.
Operations
- Scale on queue depth, KV utilization or TTFT, not CPU or GPU utilization. Cold start = image, weights, graph capture, warm-up. Scale up fast, down slowly, with a drain.
- Route to least loaded or to the prefix; retry only safe pre-first-token failures; hedging doubles load.
- Benchmark open loop on realistic lengths, report percentiles and goodput at the target, control the cache and warm-up.
- Page on symptoms, dashboard causes. A health check must generate a token. Degrade on purpose with 429 or 503.
A design answer in seven parts
Clarify · estimate · stack · architecture · evaluation and rollout · failure modes · cost and trade-offs. When a constraint changes, re-cost aloud and say what you give up.
Traps
Decode “compute-bound” · KV-cache as a response cache · attention heads instead of KV heads · “4-bit is 4 times faster” · quantization “free” because perplexity held · FlashAttention approximate · bigger batch lowers latency · scaling on GPU utilization · closed-loop fixed-length benchmarks · cost at 100 percent utilization · “with sparsity” peaks used as dense.