LLM Inference, KV Cache & Continuous Batching

Prefill vs. autoregressive decode, Key-Value (KV) caching with PagedAttention, and continuous batching for high GPU throughput

Difficulty: Intermediate · Read time: 10 min · Access: Free Interactive Lesson

How It Works

Serving a Large Language Model (LLM) happens in two distinct phases. First, the Prefill phase reads the entire input prompt in parallel (bound by GPU compute math speed, measured in FLOPs — Floating-Point Operations) and computes Key and Value (K/V) attention tensors for every prompt token. Second, the Decode phase generates one new word/token at a time in a sequential loop (bound by GPU memory bandwidth—how fast the chip can read data out of VRAM, or Video RAM). Storing those Key/Value matrices in a Key-Value Cache (KV Cache) prevents re-computing the entire prompt on every single output token. Modern engines like vLLM (Virtual LLM) pair PagedAttention (virtual-memory-style KV paging) with Continuous Batching to maximize concurrent users on each GPU.

Why It Matters

Naive LLM serving pre-allocates huge contiguous memory buffers inside expensive GPU VRAM for every request’s maximum context window—wasting 60%–75% of GPU memory—and forces fast short replies to wait idle behind long essays in static batches, multiplying hardware bills 4x–8x.

Interactive Architecture Scenarios

  • Prefill -> KV Cache -> Continuous Decode Stream
  • Failure Mode: Static Batching & VRAM OOM

Key Terms & Short Forms

  • LLM (Large Language Model): Neural network trained on massive text corpora to predict and generate tokens (e.g., Llama-3, GPT, Claude).
  • KV Cache (Key-Value Cache): GPU memory store holding intermediate Key & Value attention tensors of prior tokens so future steps reuse them instead of recomputing from scratch.
  • VRAM (Video Random-Access Memory): Ultra-fast high-bandwidth memory on a GPU (e.g., 80 GB HBM3 on an NVIDIA H100) where model weights and KV Cache live.
  • FLOPs (Floating-Point Operations): Measure of raw matrix-multiplication math capacity; the main bottleneck during the parallel Prefill phase.
  • TTFT (Time to First Token): Delay from sending a prompt until the very first answer token appears on screen, dominated by Prefill computation.
  • ITL / TPOT (Inter-Token Latency / Time Per Output Token): Average milliseconds between streaming consecutive output tokens (determines reading speed in tokens/sec).
  • EOS (End-of-Sequence Token): Special stop token generated by the model signaling that the response is complete.
  • SSE (Server-Sent Events): Lightweight HTTP streaming protocol (`text/event-stream`) used to push tokens word-by-word to the browser.
  • PagedAttention (Paged Attention Memory Manager): vLLM technique splitting KV Cache tensors into small fixed-size memory blocks (like OS RAM pages) allocated only as tokens grow.

Related Lessons in GenAI, RAG & AI Agents (Priority)