Skip to content
TheQuantaSpace
← Blogs
AI & LLMs6 min read20 min listen

The Architecture of Modern LLM Serving

Pre-training is a one-time cost; serving compounds every day. A first-principles walk through why decoding is memory-bound, where the 128 KB-per-token KV cache comes from, and how PagedAttention, continuous batching and RadixAttention cut GPU bills by 6–7x.

In the lifecycle of deploying large language models, the spotlight often falls on pre-training. We hear about multi-million-dollar training clusters, weeks of compute runs, and astronomical frontier bills. But when transitioning from research to production, an economic reality emerges: pre-training is a one-time capital expenditure (CapEx), whereas model serving is a compounding operational expenditure (OpEx).

If an enterprise deploys an 8B parameter model to serve 1 million active users making 20 queries a day at 500 tokens each, that single system processes 10 billion tokens every single day. Handled naively, that deployment demands around 90 NVIDIA H100 GPUs, translating to an infrastructure bill topping $2,000,000 per year ($0.54 per million tokens).

By redesigning how GPUs handle memory and token generation, modern inference engines like vLLM and SGLang slash those requirements down to ~15 GPUs and roughly $330,000 per year ($0.09 per million tokens), a 6x to 7x reduction.

To understand how this optimization is possible, we need to examine the mechanics of LLM inference: the memory-bound nature of autoregression, the mathematics of the Key-Value (KV) cache, and the architectural innovations behind PagedAttention and RadixAttention.


1. The Core Bottleneck: Compute vs. Memory Bandwidth

To see why simple inference servers collapse under load, consider what happens when a model generates a token. We will use LLaMA 3.1 8B running on an NVIDIA H100 GPU as our baseline.

Model Weight Storage

In half-precision (FP16 or BF16), each parameter occupies 16 bits (2 bytes).

Weight Footprint=8×109 parameters×2 bytes=16 GB\text{Weight Footprint} = 8 \times 10^9 \text{ parameters} \times 2 \text{ bytes} = 16\text{ GB}

The Next-Token Generation Dilemma

Generating a token requires a forward pass across all 32 transformer layers. In basic transformer math, a forward pass requires approximately 2 floating-point operations (FLOPs) per parameter (one multiply, one accumulate):

Workload=8×109 parameters×2 FLOPs=16 GFLOPs\text{Workload} = 8 \times 10^9 \text{ parameters} \times 2\text{ FLOPs} = 16\text{ GFLOPs}

Now, compare the GPU compute capability against its high-bandwidth memory (HBM) transfer speed:

  • H100 Tensor Core Compute: ≈1,000 TFLOPS (1015 operations/second)\approx 1{,}000\text{ TFLOPS}\ (10^{15}\text{ operations/second})
  • H100 Memory Bandwidth (VRAM to SRAM): 3.35 TB/s3.35\text{ TB/s}
  • On-Chip SRAM Capacity: ≈30 MB\approx 30\text{ MB}

Calculating the respective time components reveals a massive imbalance:

  1. Pure Computation Time:

    Compute Latency=16×109 operations1015 operations/sec=16 μs (0.016 ms)\text{Compute Latency} = \frac{16 \times 10^9\text{ operations}}{10^{15}\text{ operations/sec}} = 16\ \mu\text{s}\ (0.016\text{ ms})
  2. Memory Transfer Time: Because the 16 GB of weights cannot fit into the 30 MB on-chip SRAM, weights must be streamed slice-by-slice from VRAM across the memory bus:

    Memory Transfer Latency=16 GB3.35 TB/s≈4.8 ms\text{Memory Transfer Latency} = \frac{16\text{ GB}}{3.35\text{ TB/s}} \approx 4.8\text{ ms}

The data movement takes 300 times longer than the mathematical calculations. When serving a single user, the GPU spends 99.7% of its time idling, waiting for weights to travel across the memory bus. Next-token generation is strictly memory-bandwidth bound.

GPU HBM (VRAM) 80 GB Model weights 16 GB · read in full every step KV cache · grows per token overhead / free Memory bus · 3.35 TB/s the bottleneck Streaming multiprocessors On-chip SRAM ≈ 30 MB · holds a sliver of weights Tensor cores ≈ 1,000 TFLOPS mostly idle at batch size 1 One decode step, batch = 1 Stream weights ≈ 4.8 ms Compute ≈ 16 µs (1/300th)
The memory wall. Every decode step must move all 16 GB of weights from HBM through ~30 MB of on-chip SRAM. At batch size 1 the bus is saturated while the tensor cores wait, so time per token is set by bandwidth, not FLOPs.

2. Prefill vs. Decoding: A Tale of Two Phases

Every LLM generation request consists of two distinct stages:

Prompt tokens Prefill one parallel forward pass matrix × matrix · compute-bound TTFT Output tokens, one per pass step 1 step 2 step 3 step 4 step 5 step 6 Decode matrix × vector · memory-bound every step re-reads all weights + the whole KV cache ITL time
Two phases, two bottlenecks. Prefill processes the whole prompt in one compute-bound pass and sets time to first token (TTFT). Decode then runs one memory-bound pass per output token; the gap between steps is inter-token latency (ITL).

The Prefill Phase (Prompt Processing)

  • Execution: All prompt tokens are known in advance. The engine performs matrix-matrix multiplications (GEMMGEMM) across the entire input sequence simultaneously in parallel.
  • Hardware Profile: Compute-bound. The GPU cores are fully saturated, executing operations rapidly.
  • Impact: Dictates the Time to First Token (TTFT).

The Decoding Phase (Autoregressive Generation)

  • Execution: Generates text sequentially, one token at a time. Token NN cannot be computed until token N−1N-1 is sampled, appended to the context, and passed through the model.
  • Hardware Profile: Memory-bound. Each individual token step requires sweeping all 16 GB of weights through SRAM.
  • Impact: Dictates Inter-Token Latency (ITL) and perceived output streaming speed.

3. Demystifying the KV Cache: The 128 KB/Token Equation

In the attention mechanism:

Attention(Q,K,V)=softmax(QKTdk)V\text{Attention}(Q, K, V) = \text{softmax}\left(\frac{Q K^T}{\sqrt{d_k}}\right) V

During decoding, queries (QQ) are only needed for the single active token being predicted. However, the attention context vector requires computing dot products against the Keys (KK) and taking a weighted sum across the Values (VV) of all past tokens. To avoid recalculating past keys and values at every single step, they are stored in GPU VRAM as the KV Cache.

How 128 KB per Token is Calculated

For LLaMA 3.1 8B, the architecture parameters are:

  • Number of Layers (LL): 3232
  • KV Heads per Layer (HKVH_{KV}): 88 (utilizing Grouped Query Attention / GQA, where multiple query heads share a KV head)
  • Head Dimension (dheadd_{head}): 128128 dimensions per vector
  • Precision (BB): 22 bytes (FP16/BF16)

The formula per token across all layers is:

Memorytoken=2 (for K and V)×L×HKV×dhead×B\text{Memory}_{\text{token}} = 2\ (\text{for } K \text{ and } V) \times L \times H_{KV} \times d_{head} \times B

Plugging in the parameters:

2×32 layers×8 heads×128 dimensions=65,536 floating-point numbers2 \times 32\text{ layers} \times 8\text{ heads} \times 128\text{ dimensions} = 65{,}536\text{ floating-point numbers} 65,536×2 bytes=131,072 bytes=128 KB per token65{,}536 \times 2\text{ bytes} = 131{,}072\text{ bytes} = \mathbf{128\text{ KB per token}}

Concurrency Implications

  • For a typical conversation context of 2,500 tokens, one user’s KV cache requires:

    2,500×128 KB≈327 MB2{,}500 \times 128\text{ KB} \approx \mathbf{327\text{ MB}}
  • On an 80 GB H100 GPU:

    • 16 GB is reserved for model weights.
    • ~10 GB is set aside for runtime overhead and buffers.
    • ~54 GB remains for KV cache storage.
  • Under naive serving, 54 GB of VRAM caps physical concurrency at roughly 160 active streams before running out of memory.

H100 · 80 GB HBM Weights 16 GB Runtime 10 GB KV cache 54 GB one 2,500-token conversation ≈ 327 MB 54 GB ÷ 327 MB ≈ 160 concurrent streams (each tick ≈ 10)
Where the VRAM goes. After weights and runtime buffers, ~54 GB is left for KV cache. At 128 KB per token, that caps a naive server at roughly 160 concurrent 2,500-token conversations, before fragmentation takes its cut.

4. Serving Optimization Frameworks: vLLM and SGLang

Modern serving optimization frameworks sit between raw hardware CUDA kernels and client-facing APIs. They solve the memory and scheduling limitations through three key innovations:

Chat UI Agents Batch jobs API server OpenAI-compatible /v1/chat/completions · tokenizer · streaming (SSE) INFERENCE ENGINE · vLLM / SGLang Scheduler continuous batching waiting running re-forms the batch every iteration KV cache manager Block table · logical → physical Free block pool · ref counts Prefix cache · radix tree (SGLang) alloc free Model runner CUDA graphs · PagedAttention / FlashInfer kernels · sampling tokens GPU HBM Weights paged KV blocks
Inside a modern inference engine. The scheduler picks which requests run each iteration; the KV cache manager hands out fixed-size blocks and tracks shared prefixes; the model runner executes one fused forward pass for the whole batch and streams sampled tokens back through the API server.

Pillar 1: PagedAttention (Solving Memory Fragmentation)

In naive setups, servers must allocate contiguous blocks of VRAM based on a model’s maximum possible sequence length. Because response lengths are inherently unpredictable, 40% to 50%+ of GPU VRAM is wasted on unused allocations and memory fragmentation.

PagedAttention applies the principles of OS virtual memory to the KV cache:

  • It breaks each sequence’s KV cache into non-contiguous physical memory blocks called pages (e.g., 16 tokens per block, occupying ≈2 MB\approx 2\text{ MB}).
  • Physical pages are allocated dynamically as tokens are generated.
  • Only the active 16-token page can be partially empty at any given time.
  • Result: GPU memory utilization surges to 96%, allowing concurrent user batch sizes to scale from 16 up to 128–256 on a single card.
Naive: reserve max_len contiguously per request reserved, never used Paged: logical blocks (16 tokens each) Req A L0 L1 L2 Req B L0 L1 Block table A L0→7 A L1→2 A L2→10 B L0→4 B L1→9 Physical KV blocks in HBM 0 1 2 3 4 5 6 7 8 9 10 11 shaded = in use · dashed = free
PagedAttention is virtual memory for the KV cache. Requests see contiguous logical blocks; a block table maps them onto whatever physical blocks are free. Waste is limited to the unfilled tail of each request’s last block, instead of everything up to max_len.

Pillar 2: Continuous Batching (Iteration-Level Scheduling)

Traditional static batching waits for the slowest request in a batch to complete before accepting new prompts.

  • Continuous batching operates at the token iteration level.
  • As soon as a request emits an end-of-sequence token (<EOS>), its memory pages are instantly reclaimed, and a new request’s prefill or decode iteration is injected into the next forward pass.
  • This keeps GPU compute cores consistently saturated.
Static batching: the batch waits for its longest request slot 1 R1 R5 slot 2 R2 R6 slot 3 R3 R7 slot 4 R4 R8 Continuous batching: a freed slot is refilled on the next iteration slot 1 R1 R5 slot 2 R2 R9 slot 3 R3 R6 R10 slot 4 R4 R7 iterations (forward passes) idle slot <EOS>: request finishes, memory reclaimed
Static vs. continuous batching. With static batching, slots that finish early sit idle until R2 completes at iteration 9. Continuous batching admits a new request into a slot the iteration after <EOS>, so the same 12 passes complete 10 requests instead of 8, with no idle slots.

Pillar 3: RadixAttention & Prefix Caching (SGLang)

In agentic workflows, multi-turn chats, or coding evaluations, requests frequently share identical prompt structures: long system instructions, few-shot examples, or prior conversational context.

  • Rather than discarding prompt states and recalculating identical Key-Value vectors in the prefill phase, SGLang retains KV cache segments in a Radix tree.
  • New requests match incoming token prefixes against the tree and reuse pre-computed KV tensors directly from VRAM, bypassing redundant prefill compute entirely.
root System prompt 1,200 tokens · cached Few-shot examples 800 tokens · cached Chat turn 1 300 tokens · cached Request A new question · ~50 tokens Request B new question · ~50 tokens Request C chat turn 2 · ~80 tokens KV already in VRAM: reused, no prefill new suffix: only these tokens are prefilled
RadixAttention keeps prompt prefixes as a tree. Request B matches 2,000 cached tokens (system prompt + few-shot examples) and prefills only its ~50-token question. When memory runs short, least-recently-used leaves are evicted first, so hot shared prefixes stay resident.

5. Summary: Naive Serving vs. Optimized Engine Economics

Dimension Naive Deployment vLLM / SGLang Optimized
KV Cache Allocation Contiguous (40%–50% fragmentation waste) Paged non-contiguous blocks (96% utilization)
Batching Mechanism Static request-level batching Dynamic continuous (iteration-level) batching
System Prompt Handling Recomputed on every prompt Retained via Prefix Caching / RadixAttention
Concurrent Batch Size 16 users 128 to 256 users
Single H100 Throughput ~1,300 tokens/sec ~8,000 tokens/sec
H100s Needed for 10B Tokens/Day ~90 GPUs ~15 GPUs
Cost per Million Tokens $0.54 $0.09
Annual GPU Cloud Bill ~$2,000,000 / year ~$330,000 / year

Conclusion

Understanding LLM serving requires recognizing that the primary challenge shifts once training concludes. In production, serving is fundamentally constrained by memory bandwidth during decoding and memory capacity within the KV cache.

By restructuring how memory is indexed (PagedAttention), how iterations are scheduled (Continuous Batching), and how shared state is preserved (RadixAttention), engines like vLLM and SGLang convert idle memory transfer cycles into high-density throughput, making enterprise-scale LLM deployment economically sustainable.

  • #llm
  • #inference
  • #vllm
  • #sglang
  • #gpu
  • #kv-cache

Written by