Welcome. Today we isolate the decoding loop: the inference control path that maps hidden states to logits, samples the next token, appends it to the residual stream context, and repeats under causal masking.
Inference splits into prefill and decode. Prefill ingests the prompt in parallel, builds keys and values, and produces the first distribution. Decode then runs one step per token: a forward pass, softmax over vocabulary logits, sampling, and feedback. This division dominates latency, throughput, memory, and serving cost.
The bottleneck is autoregression: the probability of token t is conditioned on every earlier token, so the model cannot emit position t plus one before position t. Parallelism collapses across time; arithmetic intensity low and latency sequential.
We will attack it with four mechanisms: KV caches that reuse keys and values instead of recomputing attention, continuous batching to raise accelerator occupancy, speculative decoding with a small draft model verified by the target, and paged attention for fragmented memory.
Mastering this loop is the prerequisite for credible optimization: accuracy is fixed by the model and sampler, while cost is set by cache traffic, kernel efficiency, batch shape, and memory layout. Keep that separation explicit throughout.
Equations, code and original cards
The Decoding Loop: Prefill, Decode, Repeat
• Phases: prefill parallel, decode sequential
• Latency, throughput, memory, and serving cost
• Autoregressive bottleneck: token t depends on all prior tokens
We now make the KV cache exact: the decoding-time optimization that turns causal self-attention from quadratic recomputation into incremental state updates.
At each layer and head, the residual stream is projected by the learned key and value matrices into keys and values; per head they have shape sequence length by head dimension.
During generation, the cache appends only the new key and value rows to the stored prefix, so attention reads the full causal history without rebuilding it.
The current query is the residual state times the query projection; its logits are the query dot every cached key, divided by the square root of the head dimension, then masked causally.
This removes the old all-prefix recompute: work per generated token becomes linear in context length for attention, while memory grows linearly with tokens times layers times heads.
The output is softmax over those scaled logits times the cached values, exactly equivalent to full attention under teacher forcing, but computed incrementally at decode time.
Latency drops because each step avoids recomputing all previous projections; the bottleneck shifts from arithmetic toward memory bandwidth as the cached context lengthens.
In short: cache the key-value state, extend it by one row per token, form scaled dot-product logits against that prefix, and decode with identical outputs at far lower redundant cost.
Equations, code and original cards
KV Cache: Exact Decode-Time State
1. Projections from the Residual Stream
• K = XW_K, V = XW_V per layer/head
• Per head: K,V ∈ ℝ^{T×d_h}; d_h = d_model/h
• Queries compare to keys; values are mixed
2. Append-Only Prefix State
• Cache stores K_{1:t−1}, V_{1:t−1}
• Extend: K_{1:t}=[K_{1:t−1}; k_t], V likewise
• Causal mask permits positions ≤ t only
\begin{aligned} Q_t &= \text{Query at step } t \\ \text{Attention}_t &= \text{softmax} \left( \frac{Q_t K_{1:t}^\top}{\sqrt{d}} \right) V_{1:t} \end{aligned}
3. Incremental Attention at Step t
• logits: q_t K_{1:t}^T / √d_h, then softmax
• output: softmax(·) V_{1:t}; exact vs full attention
• Per-token attention: O(T d_h), not O(T^2 d_h) recompute
• Cache memory: O(L h T d_h); bandwidth-bound as T grows
Moment 03 / 12
KV Cache Visualization and Manipulation
At the start of decoding, the key and value caches are empty tensors of shape layers by heads by sequence by head dimension. The prefill pass populates them in one shot, computing keys and values for every prompt token in parallel.
Each subsequent decode step appends exactly one new key vector and one new value vector per layer. The cache grows incrementally, so we never recompute representations for tokens we have already processed.
The model then runs cached attention: the current query attends against all accumulated keys via Q K transpose over the square root of d-k, with causal masking already implicit in the cache layout. No redundant computation occurs.
Cache validity depends on prefix stability. If the input prefix is unchanged, we get a cache hit and near-constant per-step latency. Modify any earlier token, however, and every downstream key and value is invalidated, forcing a full recompute.
The payoff is substantial. Naive decoding recomputes attention over the whole prefix each step, costing quadratic work in sequence length overall. Caching reduces each step to one query against n keys, so per-token cost is linear in context length and decoding becomes memory-bandwidth bound rather than compute bound.
Equations, code and original cards
Moment 04 / 12
Batching and Continuous Batching
Batching is the primary lever for inference throughput: without it, the accelerator sits idle between kernel launches. We contrast static batching with continuous, iteration-level scheduling.
Static batching pads a fixed set of requests to the longest sequence and runs them to completion together. Continuous batching, as in Orca, admits and evicts requests every decoding step, so short prompts stop blocking long ones.
Throughput is batch size divided by end-to-end latency. Decoding is memory-bandwidth bound on the key value cache, so larger batches amortize weight reads until compute saturates.
The speedup is latency for a single request divided by latency for the full batch. It is sublinear: prefill is compute bound and parallelizes, while autoregressive decoding serializes across steps.
The cost is scheduling: variable lengths fragment the key value cache, and queuing couples latency to throughput. Paged attention pages that cache into fixed blocks.
The sketch keeps a pending queue and a running batch; each step it admits waiting requests while capacity remains, runs one forward pass, and evicts finished sequences.
In short: static batching is simple but wastes capacity on padding and stragglers; continuous, iteration-level scheduling keeps the device saturated. Throughput scales sublinearly, latency and fragmentation are the price, and systems such as Orca and vLLM operationalize the trade-off.
Equations, code and original cards
Batching and Continuous Batching
Keeping the Accelerator Saturated During Serving
Static vs Continuous Batching
• Static: pad to max length, lock-step until the slowest request finishes • Continuous: iteration-level scheduling; admit and evict requests each decode step
Throughput Improvement Formulas
• Throughput = batch size / end-to-end latency • Speedup = latency(1) / latency(B); sublinear in B • Decode is KV-cache bandwidth bound; batching amortizes weight reads
• Variable lengths fragment the KV cache; head-of-line blocking couples latency to throughput • PagedAttention (vLLM) pages KV into fixed blocks; tune max batch against the latency SLO
Moment 05 / 12
Speculative Decoding Techniques
Today we examine speculative decoding, an inference-time method that accelerates autoregressive language model generation without changing the output distribution.
The core idea is not truly parallel generation: a small draft model proposes several tokens cheaply, then the large target model scores them in one parallel forward pass.
The draft model is a small, fast network that proposes tokens autoregressively; its cost per step is a fraction of the target model's.
The target model then verifies all proposed positions in a single parallel pass, using causal masking exactly as in teacher forcing.
Each drafted token is accepted with probability equal to the minimum of one and the ratio of target to draft probability; on rejection we resample from the positive part of their difference.
The expected tokens per target pass equal one minus acceptance raised to the draft length plus one, over one minus acceptance, all divided by one plus the draft length times the relative draft cost.
The gain therefore hinges on the acceptance rate and the cost ratio: longer drafts help only when the draft model closely tracks the target distribution.
For the rigorous treatment, see Leviathan, Kalman, and Matias, twenty twenty-three, Fast Inference from Transformers via Speculative Decoding, and Chen and colleagues' speculative sampling paper, which prove distributional exactness.
In short, speculative decoding trades a cheap sequential draft for one parallel target verification, preserving the target distribution exactly while cutting memory-bandwidth-bound latency; it is now standard in high-throughput transformer serving.
Clarification: Exact speculative sampling compares target and draft probabilities. Speedup depends on actual costs and accepted length, not a universal fixed formula.
Equations, code and original cards
Speculative Decoding: Lossless Acceleration
• Draft–verify paradigm: a small model proposes, the target model scores all positions in one parallel pass
• Speculative sampling: accept by the min-one target-over-draft ratio; on rejection resample from the positive difference
• Speedup and trade-offs: acceptance rate and draft-to-target cost ratio set the realized gain
P(\text{accept }x)=\min(1,p(x)/q(x))
\text{speedup}=\frac{\text{baseline wall time}}{\text{draft time + verification time}}
Draft Model (proposer)
Target Model (verifier)
• Proposes tokens autoregressively, cheap per step • Small width or depth; a fraction of target cost
• Scores all positions in one parallel pass • Speculative sampling keeps the target distribution exact
• Expected tokens per pass rise with acceptance, fall with draft cost • Longer drafts pay off only when draft tracks target
References: Leviathan et al. 2023, Fast Inference via Speculative Decoding; Chen et al. 2023, Speculative Sampling
Moment 06 / 12
Speculative Decoding Simulation
Use the simulation to probe speculative decoding: a small draft model proposes tokens, the target verifies them in parallel, and rejection sampling keeps the output distribution exact.
Watch latency and throughput as you vary draft speed and acceptance rate; the win appears when verification cost stays below the serial decoding work it removes.
Compare naive decoding with speculative presets, and explain changes through arithmetic intensity, memory bandwidth, acceptance probability, and the expected number of accepted draft tokens.
Equations, code and original cards
Moment 07 / 12
Paged Attention and Efficient Memory Management
Paged attention is the memory-management breakthrough that made long-context transformer serving practical rather than merely possible.
The motivation is fragmentation: conventional key-value caches reserve contiguous buffers for worst-case sequences, so most allocated capacity sits idle during decoding.
Recall attention as the softmax of query-key dot products scaled by the square root of the head dimension, then multiplied by the values; paging changes where keys and values reside, not that equation.
Kwon and colleagues introduced PagedAttention in vLLM: partition each sequence's key-value cache into fixed-size blocks, analogous to virtual-memory pages, and touch only resident blocks while decoding.
The sketch is deliberately simplified: real systems use block tables, copy-on-write for shared prefixes, and kernels that gather noncontiguous pages without materializing a full cache.
The payoff is higher batch occupancy and near-zero fragmentation: serving throughput rises because the bottleneck shifts from hoarded memory back to compute and bandwidth.
Equations, code and original cards
Paged Attention and Efficient Memory Management
vLLM-style block tables for KV-cache serving at scale
• Implementation: gather kernels plus online softmax
A = \text{softmax}\left(\frac{QK^{\top}}{\sqrt{d_k}}\right)V
# PagedAttention sketch: gather KV pages, online softmaxdef paged_attention(Q, K_pages, V_pages, block_table): m, l, out = -inf, 0, 0 # running max, normalizer, accumulator for blk in block_table: Kb, Vb = K_pages[blk], V_pages[blk] # noncontiguous gather s = (Q @ Kb.transpose(-2, -1)) / sqrt(d_k) m_new = maximum(m, s.max(-1)); p = exp(s - m_new) out = out * exp(m - m_new) + p @ Vb; l = l * exp(m - m_new) + p.sum(-1); m = m_new
Moment 08 / 12
Advanced Quantization Methods
Advanced quantization compresses weights and activations from sixteen bit floating point to eight or four bit integers, cutting memory traffic while using calibration, grouping, and Hessian aware rounding to protect logits.
Eight bit quantization is often near lossless with per channel scales; four bit needs groupwise scales and error compensation, as in GPTQ and activation aware weight quantization.
The payoff is bandwidth: weights dominate decode time, so halving bytes roughly doubles effective throughput, while lower precision also raises quantization noise in the residual stream.
The affine map is w-hat approximately equals scale times integer code minus zero point; with uniform rounding, mean squared error is bounded by scale squared over twelve.
The trade off is not accuracy alone: outlier channels, attention softmax, and layer normalization amplify error, so evaluate perplexity, gradient norm proxies, and task accuracy before deployment.
In practice, load a calibrated checkpoint, fuse dequantization into matrix multiply kernels, cache key value tensors at eight bit, and measure tokens per second against quality.
The principle is simple: spend bits where sensitivity is high, save them where it is flat; next we connect that principle to kernels, calibration data, and serving limits.
Clarification: Specify a symmetric signed quantizer with a consistent scale.
Equations, code and original cards
Advanced Quantization: INT8, INT4, GPTQ, AWQ
• Quantization trades numeric precision for bandwidth, memory footprint, and decode throughput
• Error is controlled by calibration, grouping, clipping, and sensitivity-aware rounding
• INT8: per-tensor or per-channel affine scales; often near-lossless
State-of-the-Art and Research Directions (2024-2026)
Today's slide frames the state of the art and the research agenda for 2024 through 2026: where large language model inference stands after the scaling era, and which open problems now define the frontier.
First, scaling laws: Kaplan and Chinchilla tell us loss falls as a power law in parameters, data, and compute, so inference cost becomes a budgeted design variable, not an afterthought.
Second, alignment and fairness: post-training methods such as RLHF and direct preference optimization shape the policy toward helpful, harmless behavior, while raising hard questions about whose preferences the reward model encodes.
Third, decoding: autoregressive generation is memory-bandwidth bound, so speculative decoding, quantization, and key-value cache compression attack latency without retraining the underlying model.
Finally, we survey the papers that moved the field and the directions most likely to matter next, from efficient attention to inference-time scaling of reasoning.
Taken together, these themes map the inference landscape: scale, align, and serve cheaply. Hold onto them as we examine each mechanism in turn.
Equations, code and original cards
State-of-the-Art and Research Directions (2024-2026)
Frontier research in LLM inference:
Compute-optimal scaling, preference alignment, and serving efficiency
• Landmark papers and directions: efficient attention, inference-time reasoning
Moment 10 / 12
Cutting-Edge Variations and Open Research Questions
Let's examine the frontier of inference research: the open problems currently shaping how large language models are served at scale.
First, dynamic key-value cache management and continuous batching: systems like vLLM evict, share, and reschedule cache blocks mid-decode, trading memory footprint against throughput.
Next, hybrid speculative decoding with multi-model ensembles: a small draft model proposes tokens, a larger verifier accepts or rejects them in parallel, pruning compute while preserving the output distribution exactly.
Notice how these methods move beyond single-pass attention. PagedAttention and its successors manage the cache in fixed-size blocks, like virtual memory, enabling efficient serving of long contexts.
These techniques expose real open questions: how to jointly optimize compute, memory bandwidth, and tail latency when the hardware bottleneck shifts with batch size and sequence length.
Mastering these trade-offs is what separates a working demo from a production system serving millions of queries per day.
Equations, code and original cards
Cutting-Edge Variations and Open Research Questions
Experimental methods and unresolved problems in LLM inference systems.
• Dynamic KV cache management and continuous batching
• Hybrid speculative decoding with draft-verifier ensembles
• PagedAttention extensions for long-context serving
• Open questions: joint compute, memory, and latency optimization
Moment 11 / 12
Summary and Key Takeaways
Let's begin our summary by revisiting the autoregressive decoding loop. This core cycle generates tokens sequentially, but its memory-bound nature and quadratic attention cost create bottlenecks that limit inference throughput and scalability.
Next, recall the mathematical foundations of the KV cache and continuous batching. These formulations enable reuse of key and value tensors across decoding steps, trading memory for compute by eliminating redundant attention over the prefix.
Building on this, acceleration techniques such as tensor parallelism, kernel fusion as in FlashAttention, and paged memory management push hardware utilization toward its limits.
Finally, current research targets adaptive batching, speculative decoding, and memory optimizations such as grouped query attention. These directions will define the next generation of scalable, resource-efficient serving systems.
In summary, understanding these components and their interplay is essential for designing scalable inference architectures. Remember how each mechanism, from the KV cache to kernel fusion, serves the overarching goal of accelerating model inference.
Equations, code and original cards
Summary and Key Takeaways
• Decoding Loop:
Memory-bound autoregressive generation and output scheduling
Time to test how well you have internalized the inference-time tradeoffs we just covered: KV-cache memory, quantization error, and speculative decoding. Work through each question independently.
Once you have submitted, we will walk through the solutions together and pin down exactly where any reasoning went wrong.
Equations, code and original cards
MAKE IT YOURS
Explain the change.
References, scope & corrections
Research snapshots in the source material are not a claim of current state of the art. The reference review corrects identified errors; it is not exhaustive certification of every historical statement. Source code snippets are examples, not a tested production training system.