Welcome to our advanced course on the AI inference pipeline. We treat the full pipeline as one integrated highway, where each stage, from tokenization through the forward pass to decoding, flows directly into the next, and end-to-end latency is the quantity we actually optimize.
Define the inference pipeline as a single unified system, not isolated steps. That framing lets us optimize holistically: computation, memory bandwidth, and hardware acceleration interact, so a kernel-level gain means nothing if it starves the KV cache or stalls data movement.
Notice how the key points stress connectivity between components, building on earlier modules where we covered modular network design and deployment. Here we push further: the residual stream, layer normalization, and attention blocks are no longer abstractions but stages with measurable cost.
Expect serious mathematics: optimization for inference, statistical guarantees on model behavior, and complexity analysis such as the quadratic attention cost in sequence length. You will implement efficient pipelines in Python and PyTorch, not just read about them.
Throughout, we reference current research from 2024 onward: quantization, speculative decoding, and serving systems, so your skills stay both cutting edge and academically grounded.
With scope and objectives set, we move to the detailed components of the inference pipeline and, more importantly, their interactions, where the real performance gains and bottlenecks live.
Equations, code and original cards
Course Introduction and Overview
• Inference Pipeline as One Integrated Highway
• Builds on Prior Modules: Modular Design and Deployment
• Expect Rigorous Math and Python/PyTorch Implementation
Moment 02 / 09
Mathematical Foundations of Transformer Inference
Today we examine the mathematical machinery of transformer inference: the projections, attention kernels, and objectives that make autoregressive decoding tractable and effective.
Begin with multi-head attention: the residual stream is projected by learned weight matrices into queries, keys, and values, one triple per head.
The query projection is Q equals X times W-Q; the input activations meet a head-specific weight matrix, producing the vectors whose inner products become attention logits.
Attention scores are softmax of Q K transpose over the square root of d-k, then multiplied by V; the scaling keeps pre-softmax logits variance-stable as head dimension grows.
For training, gradients must flow through softmax and the projections; the chain rule across attention is what backpropagation actually computes.
The Jacobian of softmax couples every logit to every output, so the gradient of the loss with respect to the scores mixes all positions in the row.
At inference the objective becomes the cross-entropy over next-token predictions; we do not backpropagate, we only evaluate likelihoods and decode.
Concretely, the loss is the negative log likelihood of x-t given all previous tokens, summed over the sequence under teacher forcing.
So: projections build queries, keys, values; scaled dot-product attention mixes them; gradients descend through a softmax Jacobian; and cross-entropy ties decoding to likelihood. That is the inference core.
Equations, code and original cards
Mathematical Foundations of Transformer Inference
• Q, K, V Projections and the Residual Stream
• Softmax Jacobian and Backpropagation Through Attention
• Cross-Entropy and Teacher Forcing at Decode Time
Caching keys and values avoids projecting the entire prefix again for every generated token. It does not make dense attention constant-time per token. Each new query still compares against a growing set of cached keys.
For fixed width and layers, cache storage grows linearly with context length. Total dense attention work over N generated positions remains quadratic in N. Prefill, projection work and decode attention are different costs.
Equations, code and original cards
KV Cache and Redundant Computation Optimization
Naïve Autoregressive Decoding
KV Cache Optimization
• Each step recomputes K, V projections for the full prefix • Total cost: O(N²d) FLOPs over N generated tokens • Causal masking makes this recomputation provably redundant
• Cache past Key and Value tensors; they never change • Compute Q, K, V only for the new token; attend over cache • Per-step cost drops to O(Nd); total attention reads O(N²) → O(N)
Complexity: Quadratic to Linear per Token
\text{Naïve: }\quad T(N) = \sum_{n=1}^N n = \frac{N(N+1)}{2} = O(N^2)
\text{With KV Cache: }\quad T(N) = N \times c = O(N) \quad \text{(constant c per token)}
Derivation of the Compute Savings
• Naïve: step t re-projects t tokens → sum is O(N²d) • Cached: one projection plus t cached reads per step • Tradeoff: cache memory grows as O(N · d · layers); see MQA/GQA
Moment 04 / 09
Visualizing KV Cache Performance Gains
Start with decoding as a Markov chain over the residual stream: each step reads the prefix, applies causal masking, and turns the final hidden state into logits for the next token.
Without caching, every step rebuilds keys and values for the whole prefix, so attention work grows quadratically in context length and quickly dominates the forward pass.
The key value cache stores per layer key and value tensors for prior positions; a new step appends one entry and attends against memory, giving linear marginal cost.
Watch the reuse pattern: only the current query, plus one fresh key value pair, is new; cached projections carry the history, cutting latency, bandwidth pressure, and redundant arithmetic.
The curves should separate as context grows: cached decoding stays near linear in generated tokens, while recomputation bends upward, exposing throughput and memory bandwidth limits.
Equations, code and original cards
Moment 05 / 09
Speculative Decoding: Draft & Validate Process
Speculative decoding attacks the core bottleneck of autoregressive inference: every token demands a full forward pass through the target model. The draft and validate paradigm, introduced independently by Leviathan and colleagues and by Chen and colleagues in 2023, restores parallelism without altering the output distribution.
A small draft model, often a distilled or shallower variant, proposes a block of candidate tokens cheaply. The large target model then scores the entire block in one parallel forward pass, accepting the longest prefix consistent with its own distribution. Cost per token falls while output quality is provably unchanged.
Mechanically, the draft model generates k candidates autoregressively; the target model evaluates all k plus one positions in a single pass, since causal masking makes these evaluations independent. Accepted tokens are committed, and a correction token is sampled from the residual distribution at the first rejection point.
Formally, the draft proposal at position i is written x-hat sub i, sampled from the draft distribution q sub phi conditioned on the accepted prefix. The target model's distribution is p sub theta. Keeping this notation straight separates the cheap proposer from the expensive verifier in what follows.
We model the target as p sub theta, the conditional distribution over the vocabulary at each position, and the draft as q sub phi. Verification compares these two distributions token by token, guaranteeing that accepted samples are drawn exactly from p sub theta rather than from the cheaper approximation.
The acceptance rule comes from speculative sampling: accept a draft token with probability equal to the minimum of one and the ratio of p sub theta to q sub phi. This is precisely the rejection-sampling argument that relates the two distributions, and it preserves the target distribution exactly, not approximately.
The loop is simple: draft a block of tokens, verify them in one target forward pass, commit the accepted prefix plus a correction token, and repeat until the end-of-sequence token appears. In practice this yields roughly two to three times wall-clock speedup on large models at batch size one.
In summary, speculative decoding combines a cheap autoregressive drafter, exact rejection-based verification, and batched target evaluation to cut inference latency with zero distributional shift. It is now standard in production serving stacks and remains an active research direction, including self-drafting and tree-based variants.
Equations, code and original cards
Speculative Decoding: Draft & Validate Process
Exact inference acceleration via draft-then-verify (Leviathan et al. 2023; Chen et al. 2023)
1. Draft & Verify Pipeline
• Draft model proposes k tokens autoregressively, cheaply
• Target model scores all k+1 positions in one forward pass
• Accept longest prefix consistent with p_theta; sample correction at first rejection
We turn now to research trends from 2024 through 2026: the scaling, efficiency, and alignment results currently reshaping large language model inference.
Let us isolate the four research threads driving that progress.
Scaling laws govern inference cost and utilization. Kaplan, then Hoffmann's Chinchilla result, optimal parameters near twenty times tokens, lets us predict loss and plan compute-efficient deployment.
Efficiency has become architectural. FlashAttention cuts attention memory traffic, grouped-query attention shrinks the key-value cache, and structured pruning removes FLOPs, lowering latency and energy without materially degrading accuracy.
Alignment keeps outputs reliable and value-consistent. InstructGPT established reinforcement learning from human feedback; direct preference optimization removes the reward model, while constitutional and red-teaming constraints bound failure modes.
Finally, recent benchmark papers define the frontier and the open problems we will track, rather than any single canonical result.
The throughline is balance: scaling sets the capability ceiling, efficiency determines serving cost and latency, and alignment decides whether deployment is responsible. Carry those three coupled constraints forward.
Equations, code and original cards
State-of-the-Art Research Trends (2024-2026)
Scaling laws, efficiency, and alignment results that govern modern LLM inference.
Key Research Threads
• Scaling laws predict loss and inference cost (Kaplan 2020; Chinchilla 2022)
Let's move from theory to implementation: how the key inference optimizations from this module actually look in Python and PyTorch. Seeing these mechanisms as executable code is what turns an architectural diagram into a working system.
We will cover four things: a key-value cache implemented in PyTorch, a speculative decoding loop, efficient batched matrix operations, and disciplined code annotation. Each targets a different bottleneck in autoregressive inference, from memory bandwidth to redundant compute.
Here is the constructor of a key-value cache. We preallocate key and value tensors at the maximum sequence length, so decoding never reallocates memory. Caching previously computed projections is what drops per-token attention cost from quadratic in context length to linear.
Next, speculative decoding: a small draft model proposes several tokens, and the large target model verifies them in a single parallel forward pass. Accepted tokens cost one pass instead of many, which matters enormously for latency-sensitive serving.
The matrix operations underneath deserve equal care. Batched matrix multiplication, in-place updates, and preallocated buffers keep the GPU saturated and avoid host-device synchronization, which is typically the real bottleneck rather than raw floating point throughput.
The takeaway: these are not exotic techniques but composable building blocks. A cache, a draft model, and careful tensor management together yield order-of-magnitude inference speedups, and you now have the vocabulary to implement them yourself.
Today's frontier is efficient inference: architectural variants that cut latency and memory, and the open problems that still resist current methods.
The slide summarizes architectures built for decoding speed: sparsely gated mixture of experts, where each token routes to a small subset of feed-forward blocks, and linear or kernelized attention that avoids the quadratic cost.
These go well past K V cache reuse and speculative decoding: the target is the autoregressive bottleneck itself, not just cheaper attention or better batching.
Throughput work now centers on adaptive computation: early exit and layer skipping spend fewer FLOPs on easy tokens, while dynamic pruning drops low-salience keys from the cache under a fixed memory budget.
The open problem is the speed-accuracy frontier: sparsity, pruning, and quantization all shift the loss, and at Chinchilla scale even a small degradation compounds across trillions of tokens.
That trade-off is where student projects bite: measure quality per joule or per millisecond, not accuracy alone, and ablate each efficiency trick against a dense baseline.
In short: sparse and expert models, optimizations past the K V cache, and the unresolved coupling between efficiency and alignment. The methods that hold quality fixed while cutting cost by an order of magnitude will set the agenda for the next decade of inference research.
Equations, code and original cards
Advanced Inference Variations and Open Research Questions
• Sparse and expert architectures: mixture-of-experts, sub-quadratic attention
• Beyond KV cache and speculative decoding: early exit, layer skip, cache pruning
• Open problems: the speed–accuracy frontier and alignment drift at scale
• Research directions: quality per joule, ablations against dense baselines
Let's put the inference machinery to work. This quiz probes both the concepts and the arithmetic behind large language model serving: autoregressive decoding, KV caching, attention complexity, and the compute-versus-bandwidth tradeoffs that govern latency.
Work each question independently before submitting. We will then walk through the solutions together, isolating exactly where the reasoning breaks down and correcting any faulty intuition.
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.