AI Infrastructure

From Prompt to Token: The Complete LLM Inference Pipeline Explained

How modern LLM systems turn a user prompt into a streamed response, and why it is one of the hardest distributed systems problems in production today.

TL;DR
Contents
  1. The LLM Inference Stack at a Glance
  2. Why Inference Is Harder Than It Looks
  3. Prompt Arrival: Load Balancing and Continuous Batching
  4. Tokenization: From Text to Integer IDs
  5. Prefill vs Decode: The Two Phases of Generation
  6. Transformer Attention Deep Dive: Q, K, V
  7. The KV Cache: Why It Exists and What It Costs
  8. Grouped Query Attention: MHA to GQA
  9. PagedAttention and Prefix Caching
  10. The GPU Memory Stack
  11. HBM: The Real Bottleneck
  12. Triton and FlashAttention
  13. TensorRT and Quantization
  14. Speculative Decoding
  15. Where Inference Time Actually Goes
  16. The Four Bottlenecks Framework
  17. Conclusion
  18. Frequently Asked Questions

1. The LLM Inference Stack at a Glance

When you send a prompt to an AI model, what actually happens before that first word appears on your screen? To the user, it feels like magic. To a systems engineer, it is a highly orchestrated distributed systems problem constrained by memory bandwidth, interconnect latency, and hardware utilization.

The modern inference stack is not merely about running a neural network forward. It is a pipeline of distinct operational phases, each with its own hardware profile, failure mode, and optimization surface.

The Lifecycle of a Request

1
Prompt Arrival
The request hits the API. A load balancer routes it to the inference server with the most available capacity.
2
Tokenization
Text is converted into a sequence of integer IDs the model can process.
3
Scheduler
The sequence is queued and batched dynamically using continuous batching.
4
Prefill
The model processes the entire prompt in parallel, building the initial attention state.
5
KV Cache
The attention state is stored in GPU memory so it does not have to be recomputed on every token.
6
Decode Loop
The model generates the response sequentially, one token at a time, reading the KV cache on every step.
7
Sampling
The raw model output (logits) is filtered and sampled to select the next token.
8
Streaming
The token is returned to the user via Server-Sent Events, and the loop repeats from step 6.

The Infrastructure Layers

Each step in the lifecycle executes inside one of six distinct infrastructure layers:

Application Layer
Load balancers, API gateways, and user routing. Handles authentication, rate limiting, and request admission.
Serving Layer
Engines like vLLM or TensorRT-LLM manage scheduling, continuous batching, and memory allocation.
Runtime Layer
Framework execution graphs (PyTorch, TensorRT, ONNX) that translate model operations into GPU instructions.
Kernel Layer
Highly optimized hardware routines written in CUDA or Triton that execute matrix math directly on GPU cores.
Communication Layer
Network protocols like NCCL and MPI that coordinate data movement across multiple GPUs and nodes.
Hardware Layer
The physical GPUs, HBM, NVLink interconnects, and PCIe buses that everything ultimately executes on.
The complete LLM inference architecture: request lifecycle mapped to infrastructure layers from API gateway through serving engine, runtime, GPU kernels, and hardware

2. Why Inference Is Harder Than It Looks

A common misconception is that serving an AI model is simply running the training loop forward. In reality, the two workloads stress the hardware in completely opposite ways.

Training
  • Compute-bound: data flows in massive, predictable, static batches
  • GPUs spend almost all time performing matrix math
  • Tensor Cores stay saturated
  • Batch sizes are large and fixed
  • Context lengths are known upfront
Inference
  • Memory-bound: requests arrive randomly with unpredictable lengths
  • GPUs spend most time waiting for data from memory
  • Tensor Cores sit idle between memory fetches
  • Batch sizes are small and variable
  • Generation length is unknown until the model finishes

Because of these realities, companies increasingly invest more engineering effort in serving infrastructure than in model training infrastructure. The physics of serving dictate the economics of the entire product, and a model that generates at 5 tokens per second is unusable in a chat product regardless of its quality.

3. Prompt Arrival: Load Balancing and Continuous Batching

The lifecycle of an LLM response begins long before the GPU spins up. When you hit Enter, your text is encapsulated in an API request routed to an inference cluster.

Network and Routing

In a production environment, your request first hits a load balancer. LLMs are largely stateless across requests, so the load balancer routes your prompt to the inference server with the most available capacity. For latency-sensitive applications, this routing also considers geographic proximity: a request from Tokyo should not traverse to a US datacenter when a regional node is available.

The Scheduler and Continuous Batching

Once the inference server receives the request, it enters a queue. In traditional deep learning, batching is static: you wait for 8 requests to arrive, pad them to the same length, and run them together. For LLMs, this is highly inefficient because sequences have unpredictable generation lengths. One request might generate "Yes," while another generates a 500-word essay.

To maximize throughput, modern inference servers use continuous batching (also called iteration-level scheduling). Instead of waiting for an entire batch to finish, the scheduler operates at the token level. The moment a sequence emits an end-of-sequence token, it is immediately evicted from the batch and a new request is slotted in its place. This drastically improves GPU utilization and handles concurrent users efficiently.

Key insight
Continuous batching is the single most impactful scheduling optimization in modern LLM serving. By evicting completed sequences token-by-token rather than waiting for the whole batch, it dramatically improves GPU utilization and directly reduces the per-token cost of inference, which is why every major serving engine (vLLM, TensorRT-LLM, SGLang) implements it by default.

4. Tokenization: From Text to Integer IDs

GPUs do not understand text: they understand numbers. Before your prompt can touch the model, it must be converted into a sequence of integers through tokenization.

Text to Tokens

Modern LLMs use subword tokenization algorithms like Byte Pair Encoding (BPE) or SentencePiece. These algorithms learn statistical representations of text, compressing common words into single tokens while breaking rare words into subword pieces.

Consider the word "unbelievable". A tokenizer might split it into three tokens: un, believ, able. Each is mapped to a specific integer ID in the model's vocabulary, for example [345, 8712, 1102]. The full vocabulary of modern models typically contains 32,000 to 128,000 unique tokens.

Why Token Count Drives Cost, Latency, and Limits

In LLM systems, token count is the fundamental unit of everything:

5. Prefill vs Decode: The Two Phases of Generation

Once tokenized, the sequence enters the neural network. LLM inference is split into two fundamentally different execution phases with opposing hardware profiles.

The Prefill Phase

Prefill is the ingestion of your entire prompt. Because all input tokens are known upfront, the GPU processes them in parallel. During this forward pass, the model does two things simultaneously: calculates the probability distribution for the very first token to generate, and builds the attention state (the KV cache) for every input token. The prefill phase is compute-bound and dictates your Time To First Token (TTFT).

The Decode Phase

Decode is fundamentally different. The model can only generate one token at a time: it cannot predict token 3 without first knowing token 2. For every single generated token, the GPU must load the entire model weight set and the entire KV cache from memory, perform a relatively small matrix-vector multiplication, and write back one new token. The decode phase is memory-bound and dictates your tokens-per-second output rate (TPOT).

Prefill vs Decode execution comparison: prefill as dense parallel compute block, decode as sequential narrow steps limited by HBM bandwidth
Characteristic Prefill (Processing the Prompt) Decode (Generating the Response)
ParallelismHigh: all prompt tokens simultaneouslyLow: one token at a time, sequentially
Compute PatternMatrix-Matrix Multiplication (GEMM)Matrix-Vector Multiplication (GEMV)
BottleneckCompute-bound (GPU FLOPS)Memory-bound (HBM bandwidth)
GPU UtilizationHigh: Tensor Cores saturatedLow: Tensor Cores wait for memory
Latency MetricTime To First Token (TTFT)Time Per Output Token (TPOT)
KV Cache UsageWrites heavily to cacheReads heavily; writes 1 new entry per token
Scaling BehaviorCost grows quadratically with prompt lengthCost grows linearly with generation length

Understanding this split is arguably the most important concept in AI infrastructure. The same GPU must excel at two completely different workloads within a single request, and optimizing one often comes at the cost of the other.

6. Transformer Attention Deep Dive: Q, K, V

To understand why the KV Cache exists, you must first understand the math of transformer attention during inference.

Query, Key, and Value

In a transformer, attention allows every token to gather context from all other tokens in the sequence. Every token produces three vectors:

Attention scores are computed as:

During generation, when predicting token N+1, the model generates a single Query for the current token. To understand context, this Query must attend to the Keys and Values of all preceding tokens (0 through N).

Why This Forces Caching

If Keys and Values were not saved, the model would have to rerun the entire sequence through the neural network for every new word, resulting in O(N²) computational complexity for generation. By caching K and V tensors, generating the next token becomes O(N). This is the KV cache. Without it, even a 100-token response would require running 5,050 forward passes instead of 100.

7. The KV Cache: Why It Exists and What It Costs

The KV cache prevents exponential compute costs, but it introduces massive GPU memory requirements. Understanding this trade-off is central to every inference infrastructure decision.

What Determines KV Cache Size

Cache size is determined entirely by architecture parameters; it is independent of model weight size:

The Math: Why GPT-3 Scale Was Unsustainable

For a traditional Multi-Head Attention model like GPT-3 (96 layers, 96 heads, 128 head-dim, FP16):

For a single user with an 8,000-token context:

An NVIDIA A100 has 80 GB of total VRAM. Without architectural optimization, a single GPU could barely serve two concurrent users. This made large-context serving economically impossible.

The Modern Reality: Llama 3 with GQA

Modern models solve this by drastically reducing KV heads. Llama 3 70B uses 80 layers, head-dim 128, FP16, but only 8 KV heads instead of 64:

By changing the attention architecture, the per-user memory footprint dropped from 37.7 GB to 2.6 GB, a 14× reduction that makes dozens of concurrent users viable on the same hardware.

KV cache memory lifecycle: allocation during prefill, growth during decode, and eviction after sequence completion

8. Grouped Query Attention: MHA to GQA

The dramatic memory reduction shown above comes from Grouped Query Attention (GQA), the architectural change that made large-context inference financially viable.

MHA vs MQA vs GQA: Attention Head Architectures
graph TD subgraph MHA["Multi-Head Attention (MHA)"] Q1[Q1] --> K1[K1/V1] Q2[Q2] --> K2[K2/V2] Q3[Q3] --> K3[K3/V3] Q4[Q4] --> K4[K4/V4] end subgraph MQA["Multi-Query Attention (MQA)"] Q5[Q1] --> KV1[K/V] Q6[Q2] --> KV1 Q7[Q3] --> KV1 Q8[Q4] --> KV1 end subgraph GQA["Grouped Query Attention (GQA)"] Q9[Q1] --> KVA[K/V Group A] Q10[Q2] --> KVA Q11[Q3] --> KVB[K/V Group B] Q12[Q4] --> KVB end
Multi-Head Attention
Maximum Quality
Every Query head has its own dedicated K and V head. Provides maximum reasoning quality but consumes maximum memory, the GPT-3 era standard.
Multi-Query Attention
Maximum Savings
All Query heads share a single K and V head. Massive memory savings, but causes notable degradation in model reasoning quality.
Grouped Query Attention
The Industry Compromise
Query heads are divided into groups, each group sharing one K and V head. Used by Llama 3, Mistral, Gemma, the dominant pattern today.

During decode, the GPU must stream the entire KV cache from HBM to compute cores for every token generated. A smaller cache means less data to move, directly translating to faster generation speeds. GQA is why modern frontier models can run long-context inference at commercially viable speeds.

9. PagedAttention and Prefix Caching

PagedAttention: Eliminating Memory Waste

Even with GQA, dynamically allocating KV cache memory is complex. Early inference systems allocated memory for the maximum possible sequence length contiguously upfront. If a slot was reserved for 2,048 tokens but the model generated only 10, the remaining 2,038 slots were wasted, causing internal fragmentation that was destroying GPU utilization.

PagedAttention borrows the concept of virtual memory from operating systems. The cache is divided into small, fixed-size blocks (typically 16 tokens per block). The GPU allocates these blocks non-contiguously on demand, linking them via a block table. This practically eliminates memory waste and allows vLLM to serve far more concurrent requests on the same hardware.

Prefix Caching: Reusing Work Across Requests

Many production workloads send requests that share identical starting tokens. A customer service bot with a large system prompt, or a RAG pipeline inserting the same document into multiple concurrent queries, will rebuild identical KV cache states for those shared tokens on every single request, wasting compute and memory bandwidth.

Prefix caching allows the serving engine to recognize identical token sequences and reuse previously computed KV states. By storing shared prefixes in HBM, engines like vLLM and SGLang skip the most expensive part of the prefill phase entirely.

Prefix Caching: Shared System Prompt Computed Once
flowchart TD SP["System Prompt Tokens\n(computed once, cached)"] SP --> U1["User Query 1\n(unique: compute only this)"] SP --> U2["User Query 2\n(unique: compute only this)"] SP --> U3["User Query 3\n(unique: compute only this)"] U1 --> R1["Response 1"] U2 --> R2["Response 2"] U3 --> R3["Response 3"]

The practical results are significant: reduced TTFT, lower compute costs per request, and massively improved multi-user throughput, especially for RAG and agent pipelines that reuse the same context repeatedly.

10. The GPU Memory Stack

Before isolating the ultimate hardware bottleneck, you need a clear picture of where data actually lives inside a GPU. The GPU memory hierarchy dictates almost all modern inference optimizations.

Moving data is significantly slower and more power-hungry than performing math on it. As data moves further from the compute cores, latency skyrockets and bandwidth plummets:

1
Registers
Physically wired to the arithmetic logic units (ALUs). Near-zero latency, extremely scarce (kilobytes). The fastest memory that exists.
2
Shared Memory (SRAM)
Ultra-fast programmable cache inside each Streaming Multiprocessor (SM). ~20 MB total per GPU. This is where FlashAttention tiles live.
3
L1 / L2 Cache
Hardware-managed caches. L2 (~50 MB) is shared across all SMs and acts as the gatekeeper between compute and main memory.
4
HBM (High Bandwidth Memory)
The main VRAM (80 to 192 GB), dramatically slower than SRAM. This is where model weights and the KV cache live. The real bottleneck.
GPU memory hierarchy pyramid: Registers at the top (fastest, smallest), SRAM, L1/L2 cache, then HBM at the base (largest, slowest)

Optimizing inference is fundamentally a battle to keep model weights and KV cache data in Registers and SRAM for as long as possible, avoiding the latency penalty of constantly reading from and writing to HBM. Every major inference kernel optimization is a variation on this theme.

11. HBM: The Real Bottleneck of LLM Inference

When discussing GPU performance, mainstream coverage focuses on FLOPS. In LLM generation, FLOPS hardly matter. The actual bottleneck is High Bandwidth Memory (HBM).

The Core Reality of AI Infrastructure
The common assumption is that AI systems are limited by computation. Modern LLM inference is usually limited by moving data. Generating a token involves reading far more bytes from memory than performing mathematical operations. This is why memory bandwidth, caching, and communication dominate modern AI infrastructure design.
Why modern LLM inference is memory-bound: decode phase reads entire model weights from HBM for every single token generated

GPU Bandwidth Comparison

GPUHBM CapacityMemory BandwidthRelative Throughput
NVIDIA A10080 GB2.0 TB/s1.0×
NVIDIA H10080 GB3.35 TB/s~1.7×
NVIDIA H200141 GB4.8 TB/s~2.4×
NVIDIA B200192 GB8.0 TB/s~4×

Relative throughput normalized to A100 baseline. Real throughput depends on batch size, quantization, and KV cache size.

For large language models, inference is often memory-bandwidth bound rather than compute-bound. During token generation, the GPU must repeatedly stream model weights from HBM into compute units. If the active model weights and KV cache together occupy roughly 100 GB, an H100 with 3.35 TB/s of memory bandwidth can move that data in about 30 ms, implying an upper bound of roughly 33 tokens per second for a single sequential request. In practice, optimizations, batching, quantization, and cache reuse can improve throughput, but memory bandwidth remains a primary bottleneck for large models. This is why GPUs such as the H200, which significantly increase memory capacity and bandwidth while offering only modest compute improvements, can deliver substantial real-world inference speedups for large-scale LLM workloads.

GPU Occupancy and Warp Scheduling

A GPU is divided into Streaming Multiprocessors (SMs). Each SM manages execution in groups of 32 threads called warps. To hide memory latency, an SM needs multiple warps loaded simultaneously: while one warp waits for data to arrive from HBM, the SM swaps to another warp. If there are not enough active warps, the SM stalls and compute throughput collapses.

Inference workloads frequently suffer from low occupancy when serving a single user. By grouping 64 or 128 requests into a batch via continuous batching, the matrix sizes grow large enough to fill all SMs, amortizing the cost of reading model weights across many users simultaneously.

12. Triton and FlashAttention: Kernel-Level Optimization

The Triton Language

Standard framework code runs inefficiently on GPUs. To extract maximum performance, engineers write specialized software routines called kernels. Historically this meant writing CUDA, notoriously complex and error-prone. The Triton language, developed by OpenAI, allows engineers to write fast GPU kernels in Python while retaining direct control over SRAM and HBM access patterns.

Kernel Fusion

In standard PyTorch, operations execute sequentially. An addition followed by layer normalization writes the addition result back to HBM, then reads it back into SRAM for normalization, a round trip that destroys latency. Kernel fusion eliminates this: a fused Triton kernel loads data into SRAM once, performs the addition, runs the normalization, applies the activation, and only then writes the final result back to HBM. One trip instead of four.

FlashAttention: Tiling the Attention Matrix

Standard attention computes an N×N matrix where N is sequence length. For a 10,000-token context, that is a 100-million element matrix written to HBM and read back, catastrophically slow. FlashAttention solves this using tiling.

Instead of computing the whole matrix at once, the FlashAttention kernel breaks Queries, Keys, and Values into small tiles that fit entirely inside the GPU's SRAM. It computes attention for each tile, updates a running sum, and moves to the next, without ever materializing the full N×N matrix in HBM. Memory reads and writes drop from O(N²) to O(N), dramatically accelerating the prefill phase and enabling practical long-context inference.

Why FlashAttention matters
FlashAttention is not just an optimization: it is an enabler. Without it, 128k-token context windows would be practically unusable due to HBM I/O overhead. It is the reason long-context models like Gemini and Claude can run at commercially viable speeds.

13. TensorRT and Quantization

TensorRT: Compiling for the Hardware

Before a model is deployed to production, it undergoes a compilation phase. TensorRT takes the model's neural network graph and acts as an optimizing compiler. It analyzes the specific GPU it will run on, tests hundreds of different low-level kernel algorithms, and selects the fastest implementation for each layer of the specific model architecture. The result is a compiled engine that runs significantly faster than the original framework code.

Quantization: Halving the Memory Problem

Since generation is memory-bound, reducing the size of what gets moved from HBM is a direct performance multiplier. Quantization converts model weights from 16-bit floats (FP16) to 8-bit integers (INT8) or 8-bit floats (FP8).

The arithmetic is straightforward: FP16 to FP8 halves the bytes per parameter. A 70B model in FP16 consumes ~140 GB. Quantized to FP8, it consumes ~70 GB, fitting on a single H100 that previously required two GPUs. Every token now requires moving half as many bytes from HBM, theoretically doubling generation speed while fitting twice as many concurrent users on the same cluster.

FP16 / BF16
2 bytes per parameter
Standard training and inference precision. Full quality, maximum memory footprint. 70B model = ~140 GB.
FP8 / INT8
1 byte per parameter
50% memory reduction with minimal quality loss on most tasks. The standard for production serving of large models today.
INT4 / NF4
0.5 bytes per parameter
75% memory reduction. Measurable quality degradation on complex reasoning. Used for consumer hardware deployment (GGUF, llama.cpp).

14. Speculative Decoding: Generating Multiple Tokens per Step

The fundamental bottleneck of autoregressive generation (where each token is predicted from all previous tokens, one at a time) is sequentiality: one token at a time. The entire memory-bound decode cycle must run end-to-end for every single word. Speculative decoding breaks this constraint by generating multiple tokens per step without degrading output quality.

How It Works

Speculative decoding pairs a small, fast "draft" model with the large "target" model:

  1. The draft model rapidly predicts a sequence of future tokens (e.g., 4 tokens ahead). Because it is small, this is cheap and fast.
  2. The target model takes this proposed sequence and runs a single parallel forward pass to verify all tokens at once.
  3. Accepted tokens are immediately emitted. If the draft guessed incorrectly at token 3, the target rejects from that point forward and inserts the correct token.
Speculative Decoding: Draft, Verify, Emit
flowchart LR DM["Draft Model\n(small, fast)"] DM --> T1["Token 1\n✓ Accepted"] DM --> T2["Token 2\n✓ Accepted"] DM --> T3["Token 3\n✓ Accepted"] DM --> T4["Token 4\n✗ Rejected"] TM["Target Model\n(one parallel verification pass)"] T1 --> TM T2 --> TM T3 --> TM T4 --> TM TM --> OUT["Emit tokens 1–3\n+ corrected token 4"]

Because validating a batch of tokens in parallel is far cheaper than generating them one-by-one, speculative decoding can double or triple tokens-per-second throughput. It is now a standard technique in frontier production systems, used by Google, Anthropic, and Meta for their inference pipelines.

15. Where Inference Time Actually Goes: TTFT vs TPOT

When a user complains about slow generation, where is the time actually being spent? System architects break inference latency into two distinct metrics that must be optimized entirely differently.

TTFT: Time To First Token
  • How long until the first word appears
  • Dominated by prefill compute and queueing delay
  • Critical for interactive chat applications
  • Optimized via FlashAttention, chunked prefill, prefix caching
TPOT: Time Per Output Token
  • Interval between each subsequent token
  • Dominated by HBM bandwidth during decode
  • Critical for bulk / throughput workloads
  • Optimized via quantization, GQA, speculative decoding
StageMetricPrimary BottleneckKey Optimizations
NetworkTTFTPhysical distance / ISPEdge routing, regional datacenters
TokenizationTTFTCPU parsing speedFast tokenizers written in Rust or C++
QueueingTTFTConcurrent loadContinuous batching, admission control
PrefillTTFTGPU FLOPS (compute-bound)FlashAttention, chunked prefill
KV Cache ReadsTPOTHBM capacity and bandwidthPagedAttention, GQA, KV quantization
DecodeTPOTHBM bandwidth (memory-bound)Weight quantization (FP8/INT8)
SamplingTPOTCPU/GPU sync overheadFused logits kernels
Multi-GPU SyncTPOTInterconnect latencyNVLink, NCCL AllReduce tuning
StreamingTPOTNetwork connectionServer-Sent Events (SSE) optimization

Interactive applications (chatbots, copilots) prioritize low TTFT: users are sensitive to initial delays and will abandon sessions that feel unresponsive. Enterprise workloads (batch summarization, document processing) care about overall throughput: low TPOT means higher requests per second, lower GPU cost per output token.

16. The Four Bottlenecks Framework

Almost every inference performance problem reduces to one of four fundamental system bottlenecks. Having a clear mental framework for these is essential for diagnosing production issues and knowing which optimization to reach for first.

The four bottlenecks of LLM inference: compute, memory, communication, and scheduling bottlenecks with symptoms and remedies for each
1
Compute Bottleneck
Symptoms: High GPU utilization (near 100%) but low throughput. The SMs are doing math as fast as they can, but there is too much of it. When: Large batch prefill, very large batch decode. Fix: Better kernels (Triton), faster hardware (more FLOPS), precision reduction (quantization).
2
Memory Bottleneck
Symptoms: Low tokens/sec despite surprisingly low GPU utilization: the compute cores are starving, waiting for bytes from HBM. When: Decode phase, large KV caches, long contexts. Fix: GQA, FlashAttention, quantization, upgrading to faster HBM hardware.
3
Communication Bottleneck
Symptoms: Poor multi-GPU scaling: adding more GPUs does not yield proportional speedups. When: Tensor parallelism synchronization, MoE expert routing, AllReduce operations. Fix: Utilizing NVLink and NCCL, tuning topology, minimizing synchronization boundaries.
4
Scheduling Bottleneck
Symptoms: Long user queues and poor cluster utilization despite individual nodes running fine. When: Variable request lengths, routing mismatches, repeated prefill of shared context. Fix: Continuous batching, prefix caching, better serving engines.
How bottlenecks shift as you scale
Optimization is never finished: fixing one bottleneck exposes the next. Small models are compute-bottlenecked. Long contexts become memory-bottlenecked. Large deployments hit HBM bandwidth. Multi-GPU systems hit communication limits. Massive clusters hit scheduling. Each layer of scale reveals the next constraint.

Conclusion: Engineering the Response

Every word an LLM streams to you is the result of a precisely coordinated systems pipeline fighting against the fundamental physics of data movement. The model is not the hard part: the infrastructure around it is.

The engineers shipping the fastest AI products are not the ones with the largest models: they are the ones who most deeply understand the memory hierarchy, the batching scheduler, and the kernel optimizations that determine how many tokens per second their hardware can produce. That understanding is what this article builds toward.

Disclaimer
Hardware specifications, throughput figures, and software capabilities described in this article reflect the state of LLM inference infrastructure as of mid-2026. This field evolves rapidly. Token rates and memory capacities cited are illustrative; actual production performance depends on model architecture, batch configuration, and hardware topology. Verify vendor specifications before capacity planning.

Frequently Asked Questions

What is the difference between prefill and decode?

Prefill processes your entire input prompt in parallel and is compute-bound: it determines Time To First Token (TTFT). Decode generates one token at a time by reading model weights and the KV cache from memory on every step, and is memory-bound: it determines how fast tokens stream back to you (TPOT). The same GPU executes both phases within a single request.

Why is LLM inference memory-bound rather than compute-bound?

During decode, generating each token requires loading the model's full weight set and KV cache from HBM to compute cores. The math itself is a single matrix-vector multiply. The bottleneck is how fast the GPU can shuttle bytes, not how fast it can do arithmetic. An H100 can theoretically perform 1,979 TFLOPS of BF16 compute but can only move 3.35 TB/s of data. For large models, the data movement is the ceiling.

What happens when the KV cache fills up?

When the KV cache exhausts GPU VRAM, the serving engine must evict sequences. Less sophisticated systems will reject new requests or return out-of-memory errors. More advanced systems (like vLLM with PagedAttention) can swap low-priority blocks to CPU RAM, though this comes with significant latency penalties. This is why KV cache memory management (through GQA, quantization, and PagedAttention) is central to production LLM infrastructure.

Does speculative decoding change the model output?

Speculative decoding is provably mathematically equivalent to standard autoregressive sampling. The target model verifies every draft token, and rejected tokens are replaced with the target model's correct prediction. The output distribution is identical to running the large model alone. The only change is speed: fewer sequential decode steps for the same number of generated tokens.

What is vLLM and why does it matter?

vLLM is an open-source LLM serving engine developed at UC Berkeley that popularized PagedAttention and continuous batching. It is the most widely deployed open-source inference server, running models from Llama to Mistral to Qwen in production across thousands of organizations. Understanding vLLM's architecture gives you a concrete implementation of almost every concept covered in this article: continuous batching, PagedAttention, prefix caching, and speculative decoding.