SDE & MLE Prep

Inference: KV Cache, Batching, Quantization

Q: Why is LLM inference expensive and how is it optimized?

  • Generation is autoregressive: one forward pass per output token. The prefill phase (processing the prompt) is compute-bound; decode (one token at a time) is memory-bandwidth-bound.
  • KV cache: store past keys/values so each new token only computes its own; memory ≈ 2 · layers · heads · d_head · seq_len · batch · bytes. Reduced by MQA/GQA (share K/V across heads) and paged memory (PagedAttention/vLLM).
  • Continuous batching: add/remove requests from the running batch each step → high GPU utilization.
  • Quantization: int8/int4/fp8 weights (GPTQ, AWQ) → less memory and bandwidth.
  • Speculative decoding: a small draft model proposes several tokens; the large model verifies them in one pass (same output distribution).
  • Others: FlashAttention, tensor parallelism, distillation into smaller models, prompt caching.