Systems & Infrastructure · Architecture Teardown

The Latency and Memory Architecture of Modern LLM Inference

Decoding the performance bottleneck of transformer inference reveals a battle between KV cache memory pressure and compute utilization.

Key Thesis

Transformer inference latency is dominated by memory bandwidth, not compute, due to the massive, read-only Key-Value (KV) cache. Continuous batching and optimized attention kernels like FlashAttention improve hardware utilization by managing this cache. The key engineering rule is to size GPU VRAM for your batch size and context length first, as running out of cache memory forces costly recomputation.

The Memory Wall of Transformer Inference

When a large language model generates text, its latency is not primarily constrained by FLOPs. The bottleneck is the movement of model parameters and, critically, a rapidly growing intermediate state called the Key-Value (KV) cache. For a model with N layers, H attention heads, and a hidden dimension d, the KV cache for a single token consumes 2 * N * H * d * bytes_per_param bytes. For a 70B parameter model (Llama 3 70B, N=80, H=64, d=128), this is approximately 2.5 MB per token. A 4096-token context requires over 10 GB of VRAM just for the cache before any model weights are loaded. This read-heavy, sequentially growing memory footprint defines modern inference architecture.

The consequence is that high-throughput serving systems spend more cycles on memory I/O than matrix multiplication. Under load, the failure mode is not a compute queue but an out-of-memory (OOM) error or catastrophic latency spike when the KV cache exhausts VRAM and the system must fall back to recomputing keys and values on-the-fly. This trade-off between memory and recomputation is the central optimization problem.

Continuous Batching and the KV Cache Economy

Naive static batching is disastrous for LLM serving because requests finish at different times, stranding allocated cache memory. Continuous batching, or iteration-level scheduling, addresses this by allowing new requests to fill the "bubbles" left by completed generations within a single batch iteration. This dramatically improves GPU utilization but requires extremely dynamic memory management for the KV cache of each distinct request.

The system must handle a heterogeneous mix of context lengths (prompt cache) and generation lengths (ongoing cache). A simple monolithic memory allocator leads to severe fragmentation, wasting up to 40-50% of reserved VRAM. This fragmentation directly limits the effective batch size and increases latency variance. The solution, exemplified by the vLLM engine's PagedAttention, is to borrow from virtual memory: the KV cache is partitioned into fixed-size blocks (e.g., 16 tokens worth of cache). Blocks are allocated non-contiguously per request, and a logical "block table" maps request tokens to physical blocks.

Logical Request View (Req A, context len=5)
Token Indices: [0][1][2][3][4]
Block Map:     [B1][B2][B3]   # Blocks hold fixed # of tokens

Physical GPU Memory (KV Cache Pool)
[ Block 1 ] [ Block 7 ] [ Block 2 ] [ Free ] [ Block 3 ] [ Free ]
   Req A        Req B       Req A                Req A

This paging eliminates external fragmentation, allowing near-100% memory utilization. However, it introduces overhead: the attention kernel must now gather the keys and values for a sequence from scattered physical blocks, a more complex operation than contiguous memory access. This is a classic trade-off: superior memory efficiency for increased kernel complexity and slight latency overhead.

Quantitative Trade-offs: Latency vs. Throughput

The choice of optimization strategy, maximizing memory efficiency versus minimizing kernel latency, creates a clear Pareto frontier. The following table compares three architectural approaches for serving a 70B parameter model on an 80GB A100 GPU, under a mixed workload of 512- and 2048-token prompts.

Metric / ApproachStatic BatchingContinuous Batching (Contig)PagedAttention (vLLM)
Max Effective Batch Size82440
Tokens/sec1,2003,4004,800
P99 Latency (ms)350180220
Memory Utilization~60%~75%>95%
Tail Latency CauseQueue WaitOOM on Long ContextKernel Gather Overhead

Static batching has predictable but poor throughput. Basic continuous batching improves throughput but hits OOM errors on long-context requests, causing high tail latency as those requests are deferred or fail. The paged approach maximizes throughput and handles variable contexts robustly, but its P99 latency is slightly higher due to the indirect memory access in attention computation. The engineering decision hinges on the service-level objective: choose paged memory for high-throughput, variable-length serving, and optimized contiguous kernels for latency-critical, predictable-length applications.

Attention Kernels and the Hardware Interface

Managing the cache in memory is only half the battle. The attention operation must read from it efficiently. The standard attention calculation is memory-bandwidth bound, as it loads the entire KV cache for each layer to compute softmax scores. FlashAttention and its successors (FlashAttention-2, FlashDecoding) reformulate the algorithm to perform the computation in chunks, keeping intermediate results in fast SRAM (GPU shared memory). This reduces the number of expensive reads/writes to high-bandwidth memory (HBM).

The performance gain is not just theoretical. For a 16k context length, FlashAttention-2 can achieve a 4-5x speedup over a standard implementation. However, these kernels have specific requirements. They expect contiguous memory.

When paired with a paged cache system, an extra "gather" step must first assemble contiguous blocks for a request, adding overhead. This creates a layered optimization stack: the serving runtime (vLLM) manages virtualized, fragmented cache memory, while the kernel (FlashAttention) optimizes I/O for the contiguous views it is given. The failure mode here is kernel divergence. If requests within a batch have wildly different context lengths, the assembled blocks for each request differ, potentially reducing the kernel's parallel efficiency.

The Engineering Verdict: Cache First

The architectural teardown leads to a concrete decision framework. When designing an LLM inference endpoint, start with the KV cache memory budget. Calculate the worst-case cache size: (2 * batch_size * num_layers * num_kv_heads * head_dim * context_length * dtype_size). For the 70B model with a target batch size of 40 and a 8192 context, this exceeds 400 GB. This immediately dictates multi-GGPU partitioning (tensor parallelism) not for compute, but for memory.

Next, select a serving runtime that implements continuous batching with efficient cache memory management, such as vLLM or TGI. Finally, profile to identify your bottleneck. Use a tool like NSight Systems to trace timelines. If memory copies and kernel launch overhead dominate, your batch size or context length may be too small to saturate the compute. If you are compute-bound, you can increase batch size until you hit the memory wall. The system is a balanced equation: Throughput = min(Compute_Capacity, Memory_Bandwidth / Cache_Footprint). Ignoring the memory term is the most common cause of production inference underperformance.

References

Discussion (3)

Ben Callahan OSS Maintainer & Compiler Engineer · Portland, OR

In our vLLM deployment, we observed that PagedAttention reduced VRAM waste from 40% to under 10%, but only when block size was tuned to the typical request profile. At 16-token blocks, we hit a sweet spot for 4K contexts. However, short prompts (<256 tokens) underperformed due to metadata overhead from block mapping, creating latent latency spikes. The memory savings were real, but the trade-off between block granularity and per-request management cost is more nuanced than the model suggests.

Samir Al-Mansoor LLVM & Runtime Engineer · Raleigh, NC

The metadata overhead for short prompts is a real hardware-level tradeoff. You're effectively measuring the TLB miss penalty of this virtual memory scheme. Smaller blocks reduce fragmentation but increase mapping table pressure. Larger blocks waste memory on short contexts. A hybrid allocator that switches block sizes based on predicted context length could mitigate that.

Darius Washington Engineering Manager, Platform · Minneapolis, MN

We've seen KV cache fragmentation become the dominant scaling limiter past 4 A100 80GB nodes. The article's memory wall thesis is correct, but the practical bottleneck shifts: our fragmentation overhead is closer to 20%, not 40-50%, because we aggressively cap max context. The real complexity is the interplay between this paged cache and our custom CUDA kernels for sparse attention. Managing block pointers across kernels adds nontrivial latency.