PJ's Guide to Large Language Models

Chapter 5: Inference Roofline Physics, Sparse MoE & Quantization

5.1 Prefill vs. Decode: Roofline & Arithmetic Intensity

LLM inference divides into two physically distinct regimes governed by the hardware ridge point Iridge = Peak FLOP/s ÷ HBM Bandwidth (~295 FLOPs/byte on an H100 SXM in BF16):

  • Prefill (Prompt Processing): Processes all S input tokens in parallel as large matrix-matrix multiplications (GEMMs). High arithmetic intensity ⇒ compute-bound; governs Time-to-First-Token (TTFT).
  • Autoregressive Decode: Generates one token per forward pass as matrix-vector products (GEMVs) for batch size B, loading all model weights + KV cache from HBM for just B tokens (intensity ≈ B FLOPs/byte in BF16). For B < 295, decode is strictly memory-bandwidth-bound; governs Inter-Token Latency (ITL).
PJ demonstrating sparse top-k expert routing at the dog park
Fig 5.1 — Sparse Top-k Routing
y = ∑i∈TopK gi(x) Ei(x)

Prof. PJ routing attention selectively to the tennis-ball expert while keeping 90% of park parameters inactive.

5.2 PagedAttention, Continuous Batching & Speculative Decoding

Because output sequence lengths are unknown a priori, naive contiguous KV-cache pre-allocation wastes 60–80% of GPU VRAM to internal fragmentation. PagedAttention (vLLM; Kwon et al., 2023) borrows virtual memory paging from operating systems: KV states are stored in non-contiguous fixed-size physical blocks mapped via a logical block table, enabling near-zero fragmentation, prefix caching (copy-on-write shared system prompts), and continuous (iteration-level) batching.

Because decode is HBM-bandwidth-bound, verifying K candidate tokens in parallel costs nearly the same latency as generating 1 token! Speculative Decoding (Leviathan et al., 2023; Chen et al., 2023) uses a tiny fast draft model q(x) to propose K tokens, scores all K+1 positions in one target forward pass p(x), and accepts each token xi via rejection sampling with probability:

Paccept(xi) = min(1, p(xi | x<i)q(xi | x<i)),    on rejection resample from   pres(x) = norm(max(0, p(x) − q(x)))
(5.1)

Lossless Exactness Proof: Summing the probability of directly accepting x plus rejecting some earlier draft token and sampling x from the residual distribution yields q(x) min(1, p(x)/q(x)) + [1 − ∑y min(p(y), q(y))] · max(0, p(x) − q(x)) / ∑y max(0, p(y) − q(y)) = min(p(x), q(x)) + max(0, p(x) − q(x)) = p(x) identically! Speculative decoding achieves 2×–3.5× decode speedup with mathematically zero quality degradation.

5.3 Sparse Mixture of Experts (MoE)

Dense Transformers couple parameter capacity linearly to FLOPs per token. Sparse MoE replaces each dense FFN with E parallel expert FFNs (e.g., 64–256 fine-grained experts plus 1–2 always-active shared experts) and a learned linear router Wg that activates only the top-k experts per token (e.g., 671B total parameters, only 37B active per token!). To prevent routing collapse (all tokens saturating a single expert), training adds a differentiable auxiliary load-balancing loss (or auxiliary-loss-free dynamic bias routing as in DeepSeek-V3):

ℒaux = α · E ∑i=1E fi · Pi,     fi = fraction of tokens routed to expert i,   Pi = mean router prob for expert i
(5.2)

5.4 Post-Training Quantization: FP8, GPTQ & AWQ

Reducing weight precision from 16-bit BF16 to 8-bit FP8 or 4-bit INT4 cuts HBM traffic by 2×–4×, directly multiplying decode tokens/second. Because LLM activations exhibit massive channel-wise outlier features (100× larger than median activations), naive round-to-nearest (RTN) INT4 collapses perplexity. Two surgical remedies dominate:

Prof. PJ's Bench Note: Post-set sleep is essentially aggressive 1-bit quantization of dachshund consciousness. My body drops to 0.02 FLOPs/sec on the couch, while a single dedicated FP32 outlier channel remains 100% awake for the acoustic signature of a refrigerator door opening.
« Previous: Ch. 4 — RLHF, DPO & GRPO [ Table of Contents ] Next: Snout-Glossary of AI Terms »