LLM Foundations
This section explains how a trained LLM works and how it is used: the Transformer, reasoning at inference time, long context, fast inference and cheap adaptation. It is for researchers who use LLMs (as rerankers, readers or agent policies) and want the mechanisms behind them. How a model is built lives in Pretraining; how it is post-trained with RL lives in Reinforcement Learning.
There are two stages:
- Stage 1 is the main track: the Transformer and its tokenizer and position encoding, what scale and prompting give you, the three inference bottlenecks, and LoRA plus model soups.
- Stage 2 is for following current models: long context and how it fails, compressed KV caches, faster decoding, modern serving engines, test-time compute, distillation, pruning, inference-aware scaling and how frontier recipes merge models.
Both stages are reading. Karpathy’s video builds the model in code; watch it for the mechanics, and type along only if you want to. The rest of the sidebar is optional depth.
Stage 1 · Main track · 11 numbered items · about 10.5 h of reading. Optional reading is under Optional deep dives below.
- Attention Is All You NeedThe paper that replaced recurrence with scaled dot-product attention, multi-head attention and positional encodings, and introduced the Transformer.
- BPE (subword units)Sennrich, Haddow and Birch adapt byte-pair encoding to learn a subword vocabulary by repeatedly merging the most frequent adjacent symbol pair, giving open-vocabulary neural translation and the basis of most LLM tokenizers.
- Karpathy: Let's build GPTA two-hour coding lecture that builds a character-level GPT on Tiny Shakespeare, from a bigram baseline to masked multi-head self-attention, residual blocks and layer norm.
- RoPE (RoFormer)RoPE encodes position by rotating each 2-D slice of the query and key, so that attention scores depend only on the relative offset between tokens.
- GPT-3 (few-shot learners)GPT-3, a 175B-parameter autoregressive Transformer, performs many tasks from a task description and a few examples in its context window, with no gradient updates, and the benefit of examples grows with model size.
- Chain-of-Thought promptingAdding worked reasoning steps to few-shot exemplars makes large language models write their own intermediate steps, which sharply improves multi-step arithmetic, commonsense and symbolic reasoning, but only at around 100B parameters.
- FlashAttentionDao et al. compute exact attention tile by tile in on-chip SRAM with an online softmax, so the N×N score matrix never touches HBM; fewer memory transfers make attention several times faster and linear in memory.
- GQA (and MQA)Ainslie et al. let groups of query heads share one key-value head, interpolating between multi-head and multi-query attention, and show that an existing multi-head checkpoint can be converted with about 5% extra pre-training.
- vLLM / PagedAttentionKwon et al. store each sequence's KV cache in fixed-size blocks mapped through a block table, as an operating system pages virtual memory, which nearly removes fragmentation, enables copy-on-write sharing, and raises serving throughput 2–4×.
- LoRAHu et al. freeze the pretrained weights and learn each weight update as a product of two thin matrices, cutting trainable parameters by up to 10,000× on GPT-3 175B while matching full fine-tuning and adding no inference latency.
- Model soups & weight averagingWortsman et al. average the weights of many models fine-tuned from one pretrained checkpoint, beating the best single model at no extra inference cost. This page covers why that works: linear mode connectivity, shared initialisation, uniform and greedy soups, WiSE-FT, the soup-vs-ensemble analysis, SWA/EMA/LAWA checkpoint averaging, and why different random inits need permutation alignment.
Why this order
Section titled “Why this order”- The model (1–4). Attention Is All You Need gives the architecture from the primary source. BPE (a Pretraining page) explains the tokens the model actually sees. Let’s build GPT shows a decoder-only model end to end. RoPE is how current decoders encode position, and MLA, YaRN and every long-context page assume it. If the paper’s notation is a hurdle, read The Illustrated Transformer first.
- What scale and prompting give you (5–6). GPT-3 shows in-context learning; chain-of-thought shows that asking for intermediate steps elicits reasoning. This is the bridge into Reasoning RL.
- The cost of inference (7–9). FlashAttention, GQA and vLLM/PagedAttention address three different bottlenecks: attention’s memory traffic inside one forward pass, the size of the KV cache that decoding re-reads for every token, and KV-cache memory across many requests. Together they explain the cost of every agent rollout.
- Adaptation and averaging (10–11). LoRA is the default way to adapt a model on an academic budget. Model soups explain why averaging the weights of runs fine-tuned from one checkpoint often works; Gemini Embedding, Qwen3 Embedding and most post-training reports do it, so you need it to read any recent embedder paper.
Stage 2 · Frontier
Section titled “Stage 2 · Frontier”Start Stage 2 after Stage 1. Five items are Pretraining pages; where an item is marked section, read only that part.
Ready for Stage 2? Check that you can do these without looking anything up. If not, reread the Stage 1 page in brackets.
- Explain how RoPE turns a position into a rotation and why relative offsets fall out (RoPE).
- Compute KV-cache bytes per token for a model with and without GQA (GQA).
- Say why decoding is memory-bound and prefill is compute-bound (FlashAttention, vLLM).
- Explain what the low-rank update in LoRA restricts (LoRA).
- Say when averaging two fine-tuned checkpoints should work and how you would check it (Model soups).
Stage 2 · Frontier · 15 numbered items · about 10.5 h of reading. Optional reading is under Optional deep dives below.
- Lost in the middleLiu et al. move the answer-bearing passage through a list of retrieved passages and find a U-shaped curve, where models use evidence at the start or end of the prompt far better than evidence in the middle, sometimes doing worse than with no passages at all.
- YaRNPeng, Quesnelle, Fan and Shippole extend RoPE models to 64K–128K tokens by interpolating only the low-frequency rotary dimensions, leaving high-frequency ones alone and adding an attention temperature, with about 10× fewer tokens and 2.5× fewer steps than earlier methods.
- RULERHsieh et al. build 13 synthetic tasks across retrieval, multi-hop tracing, aggregation and QA with configurable length and difficulty, and show that most models claiming 32K–1M tokens stay above a simple quality bar for only a fraction of that.
- Context RotChroma's technical report holds task difficulty fixed while input length grows, and finds that all 18 tested LLMs degrade non-uniformly, faster when the needle matches the question less closely, when distractors are present, and, surprisingly, when the haystack is coherent rather than shuffled.
- MLA (DeepSeek-V2 latent attention)DeepSeek-V2 introduces Multi-head Latent Attention (MLA), which caches one low-rank latent vector plus a small shared RoPE key per token instead of per-head keys and values, cutting the KV cache to a few percent of multi-head attention without losing quality.
- DeepSeek-V4Key idea only: compressed/sparse attention (CSA/HCA) and low-precision KV cache for 1M-token context.DeepSeek's 1M-context MoE pair, which compresses the KV cache with hybrid CSA/HCA attention, widens the residual with mHC and trains with Muon.
- Speculative decodingLeviathan et al. let a small draft model propose several tokens and have the large model verify them in one parallel pass, with a rejection rule that keeps the output distribution exactly the large model's; Chen et al. at DeepMind derived the same scheme independently as speculative sampling.
- Multi-token prediction (MTP)Gloeckle et al. train a shared transformer trunk with n independent output heads that each predict a different future token, which improves code models at scale and lets the extra heads act as a built-in draft model for up to 3× faster self-speculative decoding.
- Modern serving: prefix cache, PD, KVThe 2023–24 systems ideas behind modern LLM serving, with DeepSeek-V3 as a deployment case study. SGLang's RadixAttention keeps finished requests' KV cache in a radix tree so shared prefixes are never recomputed; Sarathi-Serve chunks prefills so decodes never stall; DistServe and DeepSeek-V3 put prefill and decode on different GPUs; KIVI quantises the cache to 2 bits.
- Compute-optimal test-time scalingSnell et al. show that the best way to spend inference compute depends on question difficulty, and that difficulty-aware allocation beats best-of-N with up to 4× less compute and can beat a 14× larger model on easier questions.
- s1 (budget forcing)s1 fine-tunes Qwen2.5-32B-Instruct on 1,000 curated reasoning traces and controls thinking length with budget forcing, showing that a minimal recipe gives a reasoning model whose accuracy rises with test-time compute.
- Knowledge distillationHinton, Vinyals and Dean train a small model to match a large model's temperature-softened output distribution, transferring most of an ensemble's gain into a single deployable network.
- Pruning LLMs (SparseGPT, Wanda, Minitron)A mini-survey of LLM weight pruning anchored on Wanda. Magnitude pruning collapses on LLMs because of outlier activations; SparseGPT fixes it with an OBS-style weight update, Wanda with a one-line score |W|·‖X‖ and no update. Structured and depth pruning (LLM-Pruner, Sheared LLaMA, Minitron, ShortGPT, Gromov et al.) give real speedups but usually need retraining or distillation.
- Over-training scaling lawsGadre et al. train 104 models and show that scaling laws stay predictable when models are trained far past the Chinchilla point; the token-to-parameter ratio shifts the loss curve without changing its slope, and loss in turn predicts average downstream error.
- Merging in practice: LLMs & retrieversYadav et al. merge 2–8 fully fine-tuned PaLM-2 experts at 1B–64B and find that instruction-tuned bases, larger models and held-out evaluation all favour merging, and that merging methods behave alike at scale. Around that anchor, this page covers how Llama 3, Command A, OLMo, WARM/WARP, Tongyi DeepResearch, Perplexity and the Gemini, Qwen3 and Nemotron embedders use souping in 2024–2026, and how to evaluate a merge.
Why this order
Section titled “Why this order”- Long context (1–4). Lost in the Middle is the first result that long windows do not replace retrieval. YaRN shows how windows are extended. RULER and Context Rot measure effective context and how it decays with distractors.
- Smaller KV caches (5–6). MLA compresses K and V into a latent; DeepSeek-V4’s key idea combines compressed and sparse attention for 1M-token context.
- Faster decoding and serving (7–9). Speculative decoding drafts and verifies tokens without changing the output distribution; multi-token prediction trains the draft heads into the model. Modern serving covers prefix caching, prefill/decode disaggregation and KV-cache compression, i.e. how SGLang- and vLLM-style engines serve agents and RL rollouts.
- Spending compute at inference (10–11). Compute-optimal test-time scaling compares parallel sampling and sequential revision; s1 shows the simplest budget-forcing recipe.
- Smaller models (12–14). Knowledge distillation is the base for on-policy distillation in RL. LLM pruning is its partner: Minitron-style prune-then-distill is how several small open models are made, and the page separates real speedups from paper sparsity. Overtraining laws explain why deployed models are trained far past Chinchilla-optimal.
- Merging at scale (15). Merging in practice is the capstone: what merging-at-scale experiments show, and how Llama 3, OLMo, WARM, Perplexity and the Gemini, Qwen3 and Nemotron embedders use souping, plus how to evaluate a merge.
- Optional companions. NoLiMa, You Don’t Need Long Context, Recursive Language Models, QLoRA, FlashAttention-2 and DeepSeek-R1.
Optional deep dives
Section titled “Optional deep dives”- Read 1 · Transformer basics further if you want visual intuition or the encoder families behind retrievers: start with The Illustrated Transformer, then BERT and T5.
- Read Courses & videos (hands-on) if you want a full lifecycle overview or a semester-long build: start with Karpathy: Deep Dive into LLMs; Stanford CS336 is the from-scratch course.
- Read 2 · Prompting, reasoning & test-time compute further if you need the simplest working test-time-scaling recipe: start with Self-consistency, then Weng’s survey Why We Think.
- Read 3 · Long context further if you need to evaluate effective context length or argue “retrieve vs. put everything in the prompt”: start with NoLiMa. For the opposite argument, read You Don’t Need Long Context: in the tested tasks, frequent compaction and selective reading often preserve accuracy. Its cost reductions are estimates, and the largest come from selective reading of long inputs.
- Read 4 · Efficient attention & inference further if you size KV caches or need faster decoding: start with FlashAttention-2; Making DL go brrrr teaches how to find the bottleneck.
- Read 5 · Adaptation & distillation further if you fine-tune large models on one GPU or compress a model: start with QLoRA.
- Read 6 · Model merging & pruning if you average checkpoints, combine fine-tunes without retraining, or shrink a model: Model soups (Stage 1), LLM pruning and Merging in practice (Stage 2) are on the tracks; the optional pages are Task arithmetic, TIES & DARE, for merging models fine-tuned on different tasks, and MergeKit, which shows what the toolkit does to each tensor.
All pages by group
Full reading path (includes optional pages)
- Optional orientation: Karpathy’s Deep Dive into LLMs walks through the whole lifecycle (data, pretraining, post-training, use) before any details.
- Build intuition: The Illustrated Transformer, then 3Blue1Brown, then Attention Is All You Need. The Illustrated Transformer and 3Blue1Brown are companions that teach the same forward pass as the paper; read whichever explanation works for you, then the paper. Code it with Karpathy’s Let’s build GPT.
- From encoders to in-context learning: BERT and T5 (the models behind dense retrievers and monoT5), then GPT-3. RoPE explains how many current decoder-only LLMs encode position.
- Reasoning at inference time: chain-of-thought → self-consistency → compute-optimal test-time scaling → s1. This is the bridge into Reasoning RL.
- Long context vs. retrieval: Lost in the Middle, RULER, NoLiMa and Context Rot show why long windows do not replace retrieval. YaRN shows how windows get extended.
- Making it fast: FlashAttention → GQA → PagedAttention → speculative decoding. These are the costs behind every agent rollout.
- Adapting on an academic budget: LoRA, QLoRA and distillation.
- Combining and shrinking models: model soups → task arithmetic, TIES and DARE → merging in practice (LLM post-training and embedding models) → MergeKit; then LLM pruning.
For an IR researcher: BERT/T5 → long context → efficient inference is the shortest path from your own work to the systems your RL-trained search agents run on.
Questions to think through
These questions have no single right answer. Write or say your answer before you open the hints. Mark a question once you could defend your answer in a reading group.
- Mechanism
BERT, T5 and GPT-3 share the Transformer block but differ in attention mask and training objective. For each, give the mask, the objective and the IR role it most naturally fills, and explain why the mask decides whether a model can generate text and reuse a KV cache.
What a strong answer covers
- BERT: encoder-only with a bidirectional mask and masked-language-model pretraining; every token sees the whole input, which suits bi-encoders (embed query and passage separately) and cross-encoders (score a query-passage pair).
- T5: encoder-decoder; a bidirectional encoder reads the input and a causal decoder writes the output; span-corruption pretraining and a text-to-text format, so a reranker such as monoT5 scores relevance through the probability of generating "true".
- GPT-3: decoder-only with a causal mask and next-token prediction; prompting and few-shot in-context learning make it a generative reader or LLM reranker without task-specific heads.
- Only a causal mask lets earlier tokens' keys and values stay fixed as new tokens arrive, so generation can cache them; a bidirectional encoder must recompute every position when the input changes.
- Design
A colleague proposes dropping retrieval and placing a whole 500-document collection (about 400k tokens) in a 1M-token window. Use Lost in the Middle, RULER, NoLiMa and Context Rot to say what the evidence predicts, then design the comparison that would settle it for your reader model.
What a strong answer covers
- Lost in the Middle: accuracy depends on where the evidence sits, typically best at the start or end, so a 400k-token prompt places most evidence in the weak middle.
- RULER: claimed window is not effective length; near-perfect needle tests coexist with large drops on harder tasks at long lengths.
- NoLiMa and Context Rot: when the question shares few words with the evidence, or when similar-looking distractors are present, accuracy falls faster with length, which is the realistic search case.
- Context Rot's focused prompts are oracle evidence, so they bound what retrieval could gain rather than proving a real pipeline wins.
- Comparison: same reader and questions; full-collection prompt versus retrieve-and-rerank at several k; report accuracy, abstention, evidence recall, latency and token cost per query.
- Derive / compute
For a hypothetical decoder with 32 layers, 32 query heads, head dimension 128 and a 16-bit KV cache, compute the KV cache per token and for one 32,768-token sequence with full multi-head attention and with GQA using 8 KV heads. Then say which of FlashAttention, GQA, PagedAttention and speculative decoding shrink memory and which mainly cut latency.
What a strong answer covers
- MHA: 2 (K and V) × 32 layers × 32 heads × 128 × 2 bytes = 524,288 bytes = 512 KiB per token, so 32,768 tokens need 16 GiB.
- GQA with 8 KV heads: 128 KiB per token and 4 GiB per sequence, a 4× saving in memory and in bytes read per decoding step.
- FlashAttention computes exact attention in tiles without writing the full score matrix to HBM; it cuts memory traffic and activation memory but not the KV cache.
- PagedAttention allocates the KV cache in fixed-size blocks, reducing fragmentation so more sequences fit in a batch; per-token cache size is unchanged.
- Speculative decoding lets a small draft propose tokens that the target verifies in one pass; it reduces latency while preserving the target's output distribution, at the cost of extra compute.