Stanford CS336: Language Modeling from Scratch Lecture 10: Inference

Arithmetic Intensity, Model Compression, Speculative Decoding & Serving Systems
Reference GPU: NVIDIA Blackwell B300 · Late 2026

Why Inference Dominates LLM Compute

We use SGLang as our running serving-systems example later in this lecture.

Inference Metrics & the Sequential Bottleneck

Training (parallel across all tokens) t₁ t₂ t₃ t₄ Single large matmul Compute-bound Inference decode (strictly sequential) prompt step 1 step 2 step 3 Reloads weights + KV every token ↑ TTFT (prefill) ← TPOT (latency/tok) →

Autoregressive dependency prevents parallelizing across generated tokens, making GPU utilization hard.

Transformer Shapes & Dimension Notation

Input X [B, T, D] Attention (L layers) Q [B,T,N,H] KV cache [B,S,K,H] A = QKᵀ → softmax(A)V → W_O Gated MLP / MoE Experts U = X W_up, G = X W_gate [B,T,F] Y = (act(G) ⊙ U) W_down [B,T,D] Output Y [B, T, D]
  • Einops-style contraction:
    • $B T \color{#c00000}{D} \times \color{#c00000}{D} H \to B T H$ (red dim contracts)
    • $\color{#1438c8}{B}\color{#c00000}{D} \times \color{#1438c8}{B}\color{#c00000}{D} \to B$ (blue dim batches)
  • Core dimensions:
    • $B$: batch size, $L$: layers, $V$: vocab size
    • $S$: cached context length, $T$: active tokens
    • $D$: model dim, $F$: MLP intermediate dim
    • $N$: query heads, $K$: KV heads, $H$: head dim
  • Standard conventions: $D = N H$, $N = K G$, $F \approx 4D$ (dense), $T = S$ in prefill, $T = 1$ in decode

Arithmetic Intensity & the Hardware Roofline

Arithmetic Intensity (FLOP / byte, log) Achieved FLOP/s (log) Memory-bound Decode (small B) Compute-bound Prefill / large B Ridge point I* = peak FLOP/s ÷ BW
  • Multiply $X\,[B\times D]$ by $W\,[D\times F]$ in BF16 (2 B):
    • $\text{FLOPs} = 2BDF$
    • $\text{Bytes} = 2BD + 2DF + 2BF$
    • For $B \ll D, F$: $\; I = \dfrac{2BDF}{2DF} = \mathbf{B}\text{ FLOP/byte}$
  • Historical baseline (H100 BF16): $989\text{ TFLOP/s} \div 3.35\text{ TB/s} \approx 295\text{ FLOP/B}$ (compute-bound iff $B > 295$)
  • Reference GPU (Blackwell B300): 288 GB HBM (287 GB usable) with native MXFP8 & NVFP4 tensor cores — decode stays memory-bound unless batch $B$ is large

At $B = 1$ (matrix-vector product), $I = 1$: we stream the entire $D\times F$ weight matrix from HBM for just $2DF$ FLOPs.

From $O(T^3)$ Naive Inference to the KV Cache

Naive: Recompute Full History [p₁ p₂] → t₁ [p₁ p₂ t₁] → t₂ [p₁ p₂ t₁ t₂] → t₃ Each step O(T²) → total O(T³) FLOPs KV Cache: Reuse Past Keys & Values 1. Prefill (T = S) HBM KV Cache [B, S, L, K, H] × 2 2. Decode (T = 1) read past K,V append 1 token Trades HBM capacity & BW for O(T²) compute

Arithmetic Intensity of MLP Layers

Gated MLP (BF16, 2 B/param): $U = X W_{\text{up}}$, $G = X W_{\text{gate}}$, $Y = (\text{act}(G)\odot U) W_{\text{down}}$.

OperationFLOPsHBM Bytes (BF16)
Read $X\,[B,T,D]$ & weights $W_{\text{up}}, W_{\text{gate}}, W_{\text{down}}$$0$$2BTD + 6DF$
$U = X W_{\text{up}}$, $G = X W_{\text{gate}}$; write $U, G$$4BTDF$$4BTF$
$Y = (\text{act}(G)\odot U) W_{\text{down}}$; write $Y$$2BTDF$$2BTD$
Total$6BTDF$$4BTD + 4BTF + 6DF$

$$I_{\text{MLP}} = \frac{6BTDF}{4BTD + 4BTF + 6DF} \;\xrightarrow{\;BT \ll D,F\;}\; \mathbf{B \cdot T}$$

Arithmetic Intensity of Attention (and a Classic Pitfall)

FlashAttention with $N$ query heads, $K$ KV heads (group size $G = N/K$), context $S$, active tokens $T$, BF16:

$$I_{\text{attn}} = \frac{4BSTNH}{4BTNH + 4BSKH} = \frac{S\,T\,(N/K)}{T\,(N/K) + S}$$

Raising decode attention intensity (alongside shrinking KV capacity) is the primary reason modern models adopt GQA and MLA.

Memory-Bound Latency & Throughput Model

In memory-bound decode (assuming perfect compute/IO overlap), each step streams all active parameters plus the batch's KV cache from HBM:

$$\text{Memory} = B \cdot \text{KV}_{\text{seq}} + \text{Params}_{\text{bytes}}, \qquad \text{Latency} = \frac{\text{Memory}}{\text{BW}}, \qquad \text{Throughput} = \frac{B}{\text{Latency}}$$

Historical Baseline: Llama 2 13B on H100

Historical 2023 dense model ($L=40, D=5120, F=13824, N=40, H=128, S=1024$, BF16) on Hopper H100 (80 GB, 3.35 TB/s).

ConfigKV / seqBatch $B$Total MemoryLatencyThroughputFits 80 GB?
MHA ($K=40$)839 MB126.9 GB8.0 ms/tok125 tok/sYes
MHA ($K=40$)839 MB6479.7 GB23.8 ms/tok2,689 tok/sBarely
MHA ($K=40$)839 MB256240.8 GB71.9 ms/tok3,562 tok/sOOM
GQA ($K=8$, 1:5)168 MB6433.4 GB10.0 ms/tok6,417 tok/sYes
GQA ($K=8$, 1:5)168 MB25665.6 GB19.6 ms/tok13,068 tok/sYes

2026 Worked Example: GLM-5.3 on Blackwell B300

Specs from GLM-5.3 config: 78 layers, $D=6144$, $N=64$ heads, MLA ($512+64=576$), DSA top-2048, 256 MoE experts (8 active + 1 shared, $F_{\text{moe}}=2048$), 1 MTP layer.

KV Cache Design (78 layers)Formula (bytes / token)Size / tokenvs. MHA BF16
Full MHA ($N H = D = 6144$, BF16)$2 \times 6144 \times 78 \times 2$1,917 KB (~1.87 MB)1.0×
GLM-5.3 MLA (BF16)$576 \times 78 \times 2$89.9 KB (~88 KiB)21.3× smaller
GLM-5.3 MLA (FP8)$576 \times 78 \times 1$44.9 KB (~44 KiB)42.7× smaller

MoE Decode Intensity: Why Batches Collapse

Decode Batch B = 256 tokens Top-8 Router E = 256 experts 256 × 8 = 2,048 assignments Expert 0: ~8 tok Expert 1: ~8 tok Expert 2: ~8 tok ⋮ Expert 255: ~8 tok 8 tok / expert Expert GEMMs deeply memory- bound!

Three Levers to Accelerate Inference

1. Lossy Shortcuts
Shrink bytes & FLOPs per token without hurting quality
  • KV-cache architectures: GQA, MLA, CLA, sparse & hybrid recurrent layers
  • Quantization: NVFP4 weights, FP8/FP4 KV cache
  • Pruning & distillation: remove components and repair

Two recipes: train a faster architecture from scratch, or initialize from a larger model and repair via distillation.

2. Lossless Shortcuts
Exact target distribution, fewer memory-bound steps
  • Speculative decoding: draft $k$ tokens cheaply, verify in one parallel pass
  • MTP heads, draft trees, block-parallel drafters
3. Dynamic Serving Systems
Saturate Blackwell clusters under live traffic
  • Continuous batching, chunked prefill, Paged/Radix/Hybrid KV, P/D disaggregation, wide EP

Grouped-Query Attention (GQA) & Decode Intensity

MHA (K = N) Q₁Q₂Q₃Q₄ KV₁KV₂KV₃KV₄ Decode intensity < 1 1× KV size GQA (1 < K < N) Q₁Q₂Q₃Q₄ KV₁KV₂ Decode intensity ≈ N/K K/N KV size MQA (K = 1) Q₁Q₂Q₃Q₄ KV₁ Decode intensity ≈ N 1/N KV size

Multi-Head Latent Attention (MLA)

h [D] Cached Latent c = W_c h kv_lora_rank = 512 Cached RoPE Key k_R qk_rope_head_dim = 64 K_C = W_UK c V = W_UV c RoPE(k_R) Absorbed Decode Fold W_UK into Q, fold W_UV into W_O 1 latent (576 vals) serves all N heads Total KV cached = 512 + 64 = 576 values / token / layer

Cross-Layer Attention (CLA) & Local Attention

CLA (across layers) Layer ℓ+1 (Q only) Layer ℓ (Q, K, V) Share KV across layers Local Window Fixed window W Three orthogonal KV axes Across heads (GQA / MLA) · Across layers (CLA) Across sequence positions (local & sparse)
  • Cross-Layer Attention (CLA): share $K,V$ across adjacent layers just as GQA shares across heads
    • Pushes out the accuracy vs. KV-size Pareto frontier
    • Used in 2026 frontier designs (e.g., DeepSeek-V4.1-Flash cross-layer KV reuse)
  • Local (sliding-window) attention (Longformer, Mistral 7B): attend only to the last $W$ tokens
    • KV cache becomes independent of sequence length $S$; effective receptive field grows linearly with $L$
    • Pure local hurts long-range recall $\implies$ interleave local with global layers

2026 Sparse Attention at 1M Context

Full Context up to 1M tokens Cheap Indexer / Selection Scores all S tokens → top-k Compressed Blocks m tokens → 1 summary (CSA/HCA) Bounded Attention Core Full attention runs only on selected top-k Core decode cost stops growing past top-k

2026 Hybrid Recurrent–Attention Architectures

Linear attention and state-space layers (Mamba 2, Gated DeltaNet) keep a fixed-size recurrent state independent of sequence length $S$, interleaved with sparse/compressed attention for exact recall.

2026 Frontier ModelLayer Ratio & MechanismMoE & Serving Notes
Kimi K3 / K3.1
July 2026
3 Kimi Delta Attention : 1 gated MLA (1M context)2.8T total / 104B active; 896 experts (16 active + 2 shared); MXFP4 QAT on experts
Qwen3.8-Flash-Next
Aug 2026
3 Gated DeltaNet : 1 QSA sparse attention125B total / 6B active; 512 experts (10+1); 51B n-gram embedding table in host RAM
Nemotron 3.5
Oct 2026
Hybrid Mamba–Transformer MoEFixed-size Mamba state slashes KV footprint alongside sparse Transformer layers

Quantization Mechanics & Blackwell Number Formats

x = 5.2342
scale = 0.1
zero_point = 4
# Quantize
x_q = round(x / scale) + zero_point
# Dequantize
x_hat = (x_q - zero_point) * scale

Lower precision cuts memory bytes proportionally — directly speeding up memory-bound decode.

FormatBytesRange / Role
FP324Training master weights & optimizer states
BF162Historical inference default
FP8 E4M31NVIDIA OCP e4m3fn: [−448, 448] (not ±240, which is e4m3fnuz)
INT8 / INT41 / 0.5[−128, 127] / [−8, 7]; inference-only
MXFP8 / NVFP41 / 0.5Blackwell native block-scaled tensor cores (NVFP4: E4M3 scale per 16 values)
On Blackwell B300, native block-scaled paths make NVFP4 weights + FP8 KV cache the normal serving configuration, not an exotic optimization.

Quantization Methods: QAT, PTQ, GPTQ & AWQ

AWQ: Activation-Aware Protection Activation channels |X|: outlier outlier Corresponding weight columns W: Protect 0.1–1% salient weights via scaling
  • Quantization-Aware Training (QAT)
    • Simulate quantize/dequantize in the forward pass so weights adapt (e.g., Kimi K3 trains MoE experts with MXFP4 QAT)
    • Higher accuracy, but requires large-scale training
  • Post-Training Quantization (PTQ): cheap calibration after training
    • GPTQ: uses Hessian info to update remaining weights to compensate quantization error
    • AWQ: identifies the 0.1–1% salient weights hitting large activation channels (FP16 → INT3: 4× less memory, 3.2× speedup)

FP4 KV Cache: Memory Win vs. Long-Context Risk

Engineering rule: never validate KV quantization on short-context benchmarks alone — always test needle-in-a-haystack and long-context retrieval (e.g., RULER/MRCR).

Model Pruning & Knowledge Distillation

Original Model (teacher) 1. Score Importance layers, heads, hidden dims 1,024 calibration samples 2. Prune drop weak units 3. Distill (Repair) match teacher logits Teacher supervision for recovery

All methods so far are lossy — next, how do we speed up decode with zero change to the output distribution?

Speculative Sampling: Checking Beats Generating

Standard decode: 4 full target-model weight reads Target q → x₁ Target q → x₂ Target q → x₃ Target q → x₄ Speculative decode: cheap draft p (4 steps) + 1 parallel target pass p→x̃₁ p→x̃₂ p→x̃₃ p→x̃₄ Target q verifies [x̃₁..x̃₄] ≈ 1 decode step of wall time! Parallel verification turns T = 1 into T = k + 1, using idle tensor-core FLOPs.

Modified Rejection Sampling: Exactness Proof

  1. Draft model $p$ proposes $k$ tokens $\tilde{x}_1,\dots,\tilde{x}_k$; target $q$ scores all $k+1$ positions in parallel
  2. For each position $i$: accept $\tilde{x}_i$ with probability $\min\!\bigl(1,\; q(\tilde{x}_i)/p(\tilde{x}_i)\bigr)$
  3. On the first rejection, resample from the residual distribution $\text{norm}\!\bigl(\max(q - p,\, 0)\bigr)$ and stop; if all $k$ accept, sample a bonus token from $q_{k+1}$
Proof on vocabulary $\{A, B\}$ — suppose draft oversamples $A$: $p(A) > q(A)$, so $p(B) < q(B)$.
Residual $\max(q - p, 0)$ places probability $0$ on $A$ and $1$ on $B$: $$P(\text{sample } A) = p(A)\cdot\frac{q(A)}{p(A)} + p(B)\cdot 1 \cdot 0 = \mathbf{q(A)}$$ $$P(\text{sample } B) = p(B)\cdot 1 + p(A)\cdot\!\left(1 - \frac{q(A)}{p(A)}\right)\cdot 1 = p(B) + p(A) - q(A) = \mathbf{q(B)}$$

Unlike standard rejection sampling (which loops), the residual step guarantees at least 1 exact target token per verification pass.

Speculative Decoding as Deployed: EAGLE, MTP & Trees

Reuse Target Hidden States (EAGLE / MTP) Target Model hidden state h_t Lightweight Head EAGLE or built-in MTP GLM-5.3: 1 MTP layer · DeepSeek-V4.1-Flash: 3 MTP layers No separate KV-heavy draft model to manage Draft-Tree Verification (1 Target Pass) t a₁ b₁ a₂ a₂' b₂ tree mask verifies all branches Longest accepted path is committed to KV cache

Late-2026 Drafters & Speculative Scheduling

Benchmark hygiene: compare speculative speedups at matched temperature, dataset, and concurrency — gains shrink as batch size grows and decode approaches the compute roof.

Serving Live Traffic: Why Dynamic Workloads Are Hard

Training feeds clean rectangular tensors [B, S, D]. Live inference traffic is asynchronous, ragged, and full of repeated prefixes.
  1. Asynchronous arrivals & finishes: requests arrive unpredictably and stop at different lengths — waiting to form a static batch stalls early requests
  2. Variable sequence lengths: padding short sequences to match the longest sequence wastes both FLOPs and HBM bandwidth
  3. Shared prefixes: system prompts, multi-turn chat histories, agent trajectories, and parallel sampling share long common prefixes

Next: how 2026 serving systems (using SGLang as our running example) solve each of these bottlenecks.

Continuous Batching & Selective Batching (Orca)

Static Batching (wait for longest request) Req 1 (done early) idle padding Req 2 (long generation) Req 3 idle padding Iteration-Level Scheduling (Continuous) Req 1 Req 4 (joins immediately) Req 2 Req 3 Req 5 (joins) Selective Batching for Ragged Lengths [3, H], [9, H], [5, H] Linear / MLP ops: concatenate without padding → [3 + 9 + 5, H] | Attention: run per sequence against each KV cache

Chunked Prefill & Mixed Batching

Without chunking: one long prefill freezes every active decode D Long Prefill (stalls all decode TPOT!) D D Mixed chunked prefill: pack prefill chunks + decode tokens in the same batch Prefill chunk 1 Decode batch Prefill chunk 2 Decode batch Prefill chunk 3 Decode batch Prefill chunk 4 Decode batch 1 weight read serves both phases together!

Standard in SGLang and vLLM; builds directly on continuous and selective batching.

PagedAttention: Virtual Memory for the KV Cache

Request A (logical) Block 0 (shared sys) Block 1 (A unique) Request B (logical) Block 0 (shared sys) Block 1 (B unique) Block Table A 0 → Phys #2 (rc=2) 1 → Phys #5 (rc=1) Block Table B 0 → Phys #2 (rc=2) 1 → Phys #0 (rc=1) Physical HBM KV Pool (non-contiguous) Phys #0 (B1) Phys #1 (free) Phys #2 (Shared) Phys #3 (free) Phys #4 (free) Phys #5 (A1) Copy-on-write on block modification

Prefix Caching: RadixAttention & Hierarchical Cache

System Prompt KV blocks [0..63] Agent Session 1 (Turn 1–4) HBM hot KV Chat User B (Turn 1) HBM hot KV Tool Call A Tool Call B Host DRAM (Hierarchical) Spill cold KV instead of evicting LRU eviction on leaves; zero recompute on prefix hit
  • RadixAttention (SGLang): retains finished requests' KV blocks in a radix tree indexed by token sequences
  • Any new request sharing a prefix (system prompt, multi-turn history, agent loop) hits the tree and skips prefill for those tokens
  • Hierarchical caching spills cold KV blocks from GPU HBM to host memory rather than discarding them, extending effective cache capacity for long-running agents

Hybrid KV Cache Managers for 2026 Models

Unified HBM Memory Pool Grouped by Layer Type Full-Attention Layers Full KV per token Standard radix/block Prefix hit: any block boundary Compressed Layers 4:1 and 128:1 compressed KV (e.g., CSA / HCA layers) Prefix hit: compressed stride Recurrent-State Layers Fixed state (Mamba / DeltaNet) Cannot slice mid-sequence Prefix hit: saved checkpoints only

Prefill / Decode Disaggregation

Prefill Pool Compute-bound (T = S) Small batch → low TTFT Scaled for prompt load No decode interference KV Transfer RDMA (Mooncake / NIXL transports) Decode Pool Memory-bound (T = 1) Large batch + wide EP → high throughput & steady TPOT Scaled independently for active decode concurrency Never stalled by incoming long prompts

Wide Expert Parallelism for MoE Decode

Data-Parallel Attention GPU 0: Batch B₀ (MLA) GPU 1: Batch B₁ (MLA) GPU M−1: Batch Bₘ All-to-All Dispatch (DeepEP) Wide Expert Ranks GPU 0: Experts 0..k (+hot dup) GPU 1: Experts k+1..2k GPU M−1: Experts … All-to-All Combine Higher per-expert batch = compute-bound

Attention–FFN Disaggregation (AFD)

Attention Ranks Hold KV cache only Run microbatch A while microbatch B is in FFN Microbatch A hidden states → ← Microbatch B FFN outputs Ping-pong hides per-layer transfer FFN / MoE Ranks Hold MoE experts only Large pooled expert batches Zero KV cache footprint

Hiding CPU Overhead: Overlap Scheduling & CUDA Graphs

Naive: GPU sits idle waiting for CPU scheduler & kernel launches CPU sched t GPU batch t CPU sched t+1 GPU batch t+1 Overlapped scheduler + CUDA graphs: zero bubbles between GPU steps CPU: Prep batch t+1 Prep batch t+2 Prep batch t+3 GPU: CUDA Graph (t) CUDA Graph (t+1) CUDA Graph (t+2) CUDA Graph (t+3) 1 launch / step

Sync-Free Model Runners & Persistent Megakernels

As Blackwell GPUs execute small decode steps in microseconds, host-side Python/CUDA overhead becomes a first-order bottleneck.

Constrained Decoding & Batch-Invariant Serving

Cache-Aware Routing & Agentic Workloads

Agent Turn k 88k–675k prefix KV-Aware Router score(replica) = prefix hit + queue load Replica 1 (prefix cached!) Skip 99% prefill → sub-second TTFT Replica 2 (cold cache) Would re-prefill entire context

Recap: Anatomy of Fast LLM Inference

LayerCore Bottleneck2026 Solution
Roofline PhysicsDecode is memory-bound; MoE dilutes per-expert batch by $k/E$Batching, KV sharing, Blackwell NVFP4/MXFP8, wide EP
ArchitectureKV capacity & $O(S)$ attention blow up at 1M contextGQA, MLA ($N$ heads/latent), CLA, DSA/CSA/HCA, recurrent hybrids
CompressionModel & KV bytes limit batch size and latencyNVFP4 weights, FP8 KV (test FP4 KV on long context), pruning + KD
Lossless SpeedupSequential 1-token steps waste GPU FLOPsSpeculative decoding: MTP layers, draft trees, DFlash/DSpark, Spec V2
Serving SystemsRagged traffic, prefix recompute, host overheadContinuous/chunked batching, Paged/Radix/Hybrid KV, P/D disagg, overlap + CUDA graphs, KV-aware routing

Fast inference is co-designed across math, model architecture, quantization, and cluster-scale serving systems.