AI-ENGINEERING
    advanced

    LLM Inference Optimization

    AI Engineer path · lesson 103 of 124
    The idea
    Serving an LLM without optimization is like a chef who re-reads the entire recipe before each ingredient. KV cache is sticky-notes for steps already read; continuous batching runs multiple orders on the same stove; quantization uses a slightly smaller measuring cup; speculative decoding has a fast sous-chef guess the next steps while the head chef bulk-reviews them.
    How to use
    Move the sequence length slider (KV cache tab) or click a precision button (Quantization tab) to see memory and speed tradeoffs update in real time.
    KV cache mechanics
    For each attention layer at step t:
    K_t = W_K · x_t (new key)
    V_t = W_V · x_t (new value)
    Cache: [K_1...K_t], [V_1...V_t]

    Without cache: O(n²) per step
    With cache: O(n) per step ← just new token
    Memory per token (Llama-2 70B-style GQA, FP16): 2 × 80 layers × (8 KV heads × 128 dim = 1024) ≈ 0.32 MB/token — without GQA (64 KV heads) this would be ~2.6 MB/token, 8× larger
    Adjust sequence length
    2,048 tokens
    Sequence length
    0.67 GB
    KV cache size
    119 concurrent
    KV-cache slots (80 GB budget)
    PagedAttention (vLLM)
    Standard KV cache pre-allocates contiguous memory for the full max sequence length — wasting GPU memory for short sequences. PagedAttention stores K/V in non-contiguous "pages" (like OS virtual memory), allocated on demand. Result: 20–24× more throughput than HuggingFace Transformers.

    Key insight

    The KV cache is the biggest memory consumer in LLM serving. A single 100K-token context on a 70B model using GQA needs ~32 GB of KV cache — without GQA it would be ~256 GB, more than most GPU servers have. Managing this memory is the primary engineering challenge in long-context serving.

    Prefill or decode?

    Sort

    Sort each property by the inference phase it describes.

    Tap a piece, then tap where it goes — or drag it. Tap the tray to take one back.

    Prefill

    Drop items here

    Decode

    Drop items here
    6 pieces left to place

    Test your knowledge

    20 questions
    Question 1 of 20
    Score: 0

    What does the KV cache store during autoregressive LLM generation?

    The short version

    Serving an LLM without optimization is like a chef who re-reads the entire recipe from scratch before adding each ingredient. The KV cache is sticky-notes for each step already read; continuous batching is running multiple orders in parallel on the same stove; quantization is using a smaller measuring cup that's accurate enough for most dishes; speculative decoding is having a fast sous-chef who guesses the next few steps while the head chef reviews them in bulk.

    In more depth

    LLM Inference Optimization

    LLM generation is autoregressive: each token is conditioned on all previous tokens. Naive inference is extremely slow — optimization is engineering the gap between "correct" and "fast."

    KV Cache

    Self-attention computes K = W_K · x and V = W_V · x for each position. In autoregressive generation, previous positions never change — their K/V can be cached.

    Memory per request: 2 × L × H_kv × D × dtype per token (H_kv = number of KV heads, not query heads — with GQA these differ)

    L=80 layers, H_kv × D = 8 KV heads × 128 dim = 1024 (Llama-2-70B-style GQA), FP16: ~0.32 MB/token
    A 4096-token context: ~1.3 GB for the KV cache alone
    Without GQA (full MHA, 64 KV heads instead of 8): the same math gives ~2.6 MB/token — an 8× larger cache, which is exactly why GQA is standard in modern serving-oriented architectures

    PagedAttention (vLLM) manages KV cache like virtual memory, eliminating fragmentation.

    Continuous Batching

    Static batching waits for a whole batch to finish before accepting new requests — long sequences block short ones. Continuous batching (iteration-level scheduling) inserts new requests at each token step, keeping GPU utilization near 100%.

    Quantization

    PrecisionSizeSpeedQuality loss
    FP324×1×none
    FP16/BF162×1.5–2×minimal
    INT8 (W8A8)1×2–3×<1% on most benchmarks
    INT4 (GPTQ/AWQ)0.5×3–4×~2–5% on hard tasks

    Speculative Decoding

    A small "draft" model generates k tokens cheaply. The large "target" model verifies all k in a single forward pass (parallel). Accepted tokens keep all; rejected tokens are resampled. Net effect: target-model quality at draft-model speed (when acceptance rate is high).

    Interview Questions

    Google
    Meta
    Anthropic
    OpenAI
    Google DeepMind
    Meta
    DeepSeek
    NVIDIA
    Hugging Face
    Together AI
    NVIDIA
    Google
    Anthropic
    NVIDIA
    Hugging Face
    Modal

    Love this visualization?

    Sign up to track your progress, earn achievements, use the AI assistant, and access your personal learning dashboard.

    100% free • No credit card required