AKP Anthropic Kernel Path

0/21 read · no cycles yet

Everything About LLMs, Highest → Lowest

A no-shortcut curriculum for AGI research + Anthropic research-engineer / kernel-adjacent interviews As of 2026-08-18. All citations below are real papers/pages with URLs. Do not skip the derivations.

Who this is for. Someone who wants to (1) contribute to frontier AGI work in the Anthropic style — capabilities and alignment as one engineering problem — and (2) pass a research-engineer interview that will put you on a whiteboard deriving softmax(QKᵀ/√d)V, then ask why your FlashAttention kernel NaNs at 100B, then ask how Constitutional AI’s RLAIF loop differs from InstructGPT’s PPO loop.

How to use it. Each section is a gate. You are not done when you have “read” the papers. You are done when you can do the learning outcomes cold, on a whiteboard, and have shipped the labs. Estimated deep hours are after you already have undergrad linear algebra, probability, and C++/Python fluency. Total: ~900–1,200 deep hours (6–12 months at 20–25 h/week, or a brutal 4 months full-time).

Prerequisites (do these first if shaky, ~80–120 h):

  • Linear algebra: SVD, eigenvalues, inner products, Kronecker, broadcasting as tensor diagrams.
  • Probability: entropy, KL, Jensen, concentration; Cover & Thomas Ch. 2–5.
  • Calculus / autodiff: chain rule on tensors; implement backprop for a 2-layer MLP from scratch.
  • Systems: caches, SIMD, occupancy, bandwidth vs compute; know what a GEMM is.

A. Intelligence / AGI framing (Anthropic-flavored)

~80–100 deep hours

Thesis

Intelligence, on this bet, is mostly what you get when you scale general methods that turn compute into prediction, plus the engineering that keeps the resulting systems pointed at human-chosen goals. Alignment is not a separate moral philosophy class. It is the same stack as capabilities: data, loss, optimizer, evals, and the kernels that make the next 10× of compute usable. Kernel work is AGI work because efficiency unlocks scale, and scale is the only reliably observed path to new capabilities.

Learning outcomes

You can:

  1. State Sutton’s bitter lesson in one paragraph, then steelman the opposite (human-knowledge priors, architecture search, interpretability as “knowledge”).
  2. Write Kaplan’s three power laws and Chinchilla’s compute-optimal allocation from memory, including what each assumes and where it broke.
  3. Explain Anthropic’s public bet: scaling is real; safety must be empirical, multi-method, and differentially accelerated; HHH (helpful, honest, harmless) is the near-term target; interpretability + scalable oversight + process supervision are the current research bets.
  4. Argue, with FLOPs, why a 2× kernel speedup on attention is an alignment intervention (it buys another generation of evals, more RL, more SAE training, more red-teaming).
  5. Distinguish capabilities vs alignment as joint engineering from “first make it smart, then bolt on safety.”

Must-read (in this order)

Framing

Scaling as the empirical law of the field

Anthropic’s early alignment lab

Textbooks / courses

Derivation exercises

  1. Kaplan vs Chinchilla (pen + paper). Write \(L(N,D)=E+\frac{A}{N^\alpha}+\frac{B}{D^\beta}\). Under \(C\approx 6ND\), minimize \(L\) at fixed \(C\). Show Chinchilla’s equal scaling of \(N\) and \(D\). Then explain, in writing, why frontier labs in 2024–2026 overtrain relative to Chinchilla (inference cost, data quality, repeated epochs).
  2. Bitter-lesson audit. Pick three “smart” architectural ideas from 2017–2023 that died (relative PE variants, recurrence hybrids, retrieval-as-architecture). Write one page: what compute did they lose to?
  3. Efficiency → scale. A 70B dense model, 8k context, MFU 40% on a given cluster. Attention is 35% of step time. You write a kernel that is 1.8× faster on attention. Compute the new tokens/day and the equivalent “free” model-size increase under Kaplan \(L\sim N^{-0.076}\).

Coding labs

  • Lab A1. Reproduce Kaplan Fig. 1 qualitatively on a toy decoder (nanoGPT-scale): 4 widths × 4 token budgets. Fit a power law. Write down where the fit lies.
  • Lab A2. Read Anthropic’s constitution and the CAI paper’s appendix principles. Implement a tiny “critique → revise” loop with a small open model. The point is the procedure, not the product.

Whiteboard questions Anthropic would ask

  • “Kaplan said big models, little data. Chinchilla said 20 tokens/param. Llama-3 trained way past that. Who was wrong, and what objective were they optimizing?”
  • “Why is a kernel engineer on the critical path for alignment?”
  • “Name a capability that appeared only after a scale jump, and an alleged emergence that was a metric artifact.”
  • “HHH: give a prompt where helpfulness and harmlessness conflict. How should a constitution resolve it? How would you measure that you did?”

B. Language modeling from first principles

~90–110 deep hours

Thesis

A language model is a conditional distribution \(p(x_t\mid x_{<t})\) over tokens. Everything else — transformers, RLHF, kernels — is machinery for representing, training, and sampling that distribution. If you cannot talk about cross-entropy, perplexity, entropy, KL, and bits-per-byte without waving your hands, you do not understand the loss you will spend a career minimizing.

Learning outcomes

You can:

  1. Derive the MLE ≡ cross-entropy ≡ KL-to-data-distribution identity.
  2. Convert freely among nats, bits, perplexity, BPB; explain why BPB is tokenizer-invariant and perplexity is not.
  3. Implement BPE and Unigram LM from scratch; explain SentencePiece’s “raw text, no pretokenizer” bet and byte-level BPE’s unk-free bet.
  4. Narrate the line n-grams → Bengio neural LM → RNN/LSTM → Transformer, with the inductive bias each discarded.
  5. Explain smoothing, backoff, and why n-grams hit a wall that was statistical, not just computational.

Must-read

Textbooks / courses

Derivation exercises

  1. CE = H + KL. Show \(\mathbb{E}_{x\sim p^\star}[-\log q(x)] = H(p^\star)+D_{\mathrm{KL}}(p^\star\|q)\). Interpret training as “matching the data’s next-token distribution.”
  2. Perplexity. \(\mathrm{PPL}=\exp(\overline{\mathrm{CE}}_{\text{nats}})=2^{\overline{\mathrm{CE}}_{\text{bits}}}\). Why comparing PPL across GPT-2 BPE vs Llama SentencePiece is meaningless; how to compute BPB.
  3. BPE by hand. Corpus {low, low, lowest, newer, wider}. Run 6 merges. Then encode lowest. Then implement it.
  4. Unigram LM. Write the EM objective. How do you sample a segmentation (subword regularization)? Why is this closer to a proper LM than BPE?
  5. LSTM gates. Derive the gradient of the cell state through time. Show why the forget-gate identity path beats vanilla RNN vanishing.

Coding labs

  • Lab B1. Shannon game: compress 100k chars of English with (a) char 5-gram Kneser–Ney, (b) a 2-layer LSTM, (c) a 4-layer transformer. Report BPB. You must beat the n-gram.
  • Lab B2. Train BPE (10k merges) and Unigram (10k vocab) on the same corpus. Measure fertility, unk rate, and downstream tiny-LM CE. Write a one-page “what tokenization actually buys.”
  • Lab B3. Byte-level BPE from scratch (GPT-2 style). Verify invertibility on random UTF-8 including emoji.

Whiteboard

  • “Perplexity of 12 on WikiText-103 — is that good? Compared to what? In bits per byte?”
  • “Why did RNNs lose? Give the parallelization argument and the path-length argument.”
  • “BPE is a compression algorithm. Why do we use it as a front end to a neural LM that is itself a compressor?”
  • “Show me that maximizing likelihood minimizes KL to the data. Where does this fail as a human objective?” (bridge to §E)

C. Transformer internals (whiteboard-derivable)

~140–170 deep hours

Thesis

A decoder-only transformer is a residual stream that attention and MLPs read from and write to. Attention is a soft, content-addressable lookup whose scores are scaled dot products. Almost every modern variant (GQA, MQA, MLA, SwiGLU, RoPE, RMSNorm, Pre-LN, MoE) is a systems or stability patch on that picture, not a new theory of intelligence.

Learning outcomes

You can, on a whiteboard with no notes:

  1. Derive \(\mathrm{Attention}(Q,K,V)=\mathrm{softmax}(QK^\top/\sqrt{d})V\), including why \(\sqrt{d}\), complexity \(O(n^2 d + nd^2)\), and the three numerical failure modes (overflow, underflow to one-hot, row-sum cancellation).
  2. Draw multi-head; then GQA; then MQA; then MLA. Compute KV-cache bytes/token for each.
  3. Write SwiGLU and the \(2/3\) width rule that keeps param count matched.
  4. Contrast Post-LN vs Pre-LN gradient scales at init (Xiong et al.).
  5. Derive RoPE: rotation in 2-D planes, \(\langle R_{\theta i}q, R_{\theta j}k\rangle=\langle q,R_{\theta(j-i)}k\rangle\). Compare ALiBi’s linear bias, sinusoid add, and NoPE.
  6. Write LayerNorm and RMSNorm; say what invariance you lose.
  7. Explain why decoder-only won for pretrained general assistants (parallel training, unified interface, zero-shot after LM pretraining).

Must-read

Textbooks / courses

Derivation exercises (non-negotiable)

  1. Scaled dot-product. Let \(q,k\in\mathbb{R}^d\) have i.i.d. entries \(\mathcal{N}(0,1)\). Show \(\mathrm{Var}(q\cdot k)=d\). Conclude the \(\sqrt{d}\) scale. What happens to softmax entropy if you omit it?
  2. Online softmax / numerically stable softmax. Derive \(m=\max_i z_i\), \(p_i=e^{z_i-m}/\sum e^{z_j-m}\). Then the two-pass / running-max form used by FlashAttention (Milakov & Gimelshein 2018 is the ancestor: Online normalizer calculation for softmax, arXiv:1805.02867, https://arxiv.org/abs/1805.02867).
  3. Backprop through attention (preview of §D). Given \(S=QK^\top/\sqrt{d}\), \(P=\mathrm{softmax}(S)\), \(O=PV\), write \(\partial L/\partial Q,\partial L/\partial K,\partial L/\partial V\) in matrix form. You will be asked this.
  4. RoPE. For a 2-D pair, write \(R_\theta=\begin{pmatrix}\cos\theta&-\sin\theta\\ \sin\theta&\cos\theta\end{pmatrix}\). Prove the relative-position identity. Extend to \(d/2\) frequencies \(\theta_i=10000^{-2i/d}\).
  5. GQA math. \(n_q\) query heads, \(n_{kv}\) KV heads. Cache size vs MHA: factor \(n_q/n_{kv}\). Quality story from Ainslie.
  6. MLA. From DeepSeek-V2 §2.1: compressed latent \(c_{KV}\), decoupled RoPE. Bytes/token vs GQA-8 for a 128-head, \(d_h=128\) model.
  7. Param count. For a decoder block: embeddings (tied or not), \(n_{\text{layers}}\times(4d^2\) for MHA \(W_Q,W_K,W_V,W_O\) + \(3d\cdot d_{ff}\) SwiGLU, or \(2d\cdot d_{ff}\) vanilla FFN) + norms. Reproduce Llama-7B ≈ 6.7B.
  8. MoE. Top-1 vs top-2 routing. Auxiliary load-balancing loss (Switch). Expert-parallel all-to-all volume: \(2\times\text{tokens}\times d\times \text{bytes}\) per MoE layer (send activations, receive outputs).

Coding labs

  • Lab C1. Implement a GPT-2-small from scratch (no nn.MultiheadAttention): attention, GQA, RMSNorm, SwiGLU, RoPE. Match HuggingFace logits to 1e-4 on a fixed prompt.
  • Lab C2. Implement FlashAttention forward in PyTorch (blockwise online softmax) and check equality with naive attention. Then read the CUDA of Dao-AILab/flash-attention until you can explain the SRAM tiling.
  • Lab C3. Train a 2-layer attention-only transformer on tiny Shakespeare. Find an induction head (see §G).
  • Lab C4. Ablate Post-LN vs Pre-LN at 6 layers / no warmup. Plot gradient norms by depth.

Whiteboard

  • “Derive attention. Now give me FLOPs for training a token. Now give me bytes moved if K,V are in HBM. When are you compute-bound vs memory-bound?”
  • “Why Pre-LN? What did Xiong actually prove?”
  • “RoPE vs ALiBi vs NoPE for a 1M-context bet. Pick one and defend the kernel implications.”
  • “Decoder-only won. Wang et al. 2022 said encoder-decoder wins after multitask FT. Reconcile this with GPT-4/Claude being decoder-only.”
  • “Draw MLA. Why can’t you just fold RoPE into the latent?”

D. Training

~180–220 deep hours

Thesis

Training is backprop + an adaptive optimizer + a data pipeline + a parallelism plan + a numerical contract. At 100B+ the contract breaks in characteristic ways (attention entropy collapse, logit drift, loss spikes). A research engineer who cannot compute communication volume for DP/TP/PP/SP/CP/EP will ship a cluster that idles.

Learning outcomes

You can:

  1. Derive backprop through attention (full matrix calculus) and through RMSNorm, SwiGLU, RoPE.
  2. Write AdamW; explain why L2 ≠ weight decay under Adam; write \(\mu\)P scaling rules for LR / init / output.
  3. Explain fp16 loss scaling, bf16’s exponent gift, and why NaNs appear (overflow, 0·Inf in softmax, Adam v-hat underflow).
  4. Design a pretraining mixture; explain packing, document attention masking, and why naive concat leaks.
  5. For each parallelism: when, what is sharded, collective, bytes on the wire per step.
  6. Recite Kaplan and Chinchilla; discuss downstream scaling and overtraining.
  7. Name 100B+ instabilities and the standard mitigations (QK-LayerNorm, σReparam, z-loss, warmup, μP).

Must-read

Optimizers & parametrization

Numerics in training

Parallelism

Instabilities

Data

Parallelism cheat sheet (memorize)

SchemeWhat is splitTypical collectiveComm volume (order)Use when
DPbatchAllReduce grads\(2\times\#params\times bytes\) per step (ring)model fits on one GPU
ZeRO-1/2/3opt / +grads / +paramsAllGather + ReduceScattersimilar volume to DP, different peak memmodel + Adam states don’t fit
TP (Megatron)hidden (columns/rows of GEMMs)AllReduce in fwd+bwd (2 per block)\(O(b\cdot s\cdot d)\) per AllReduceintra-node NVLink; model too wide
SPsequence in LayerNorm/dropoutAllGather / ReduceScatter instead of TP AllReducesame volume as TP AllReducealways-on with TP to cut activation mem
PPlayersP2P activation/grad sends\(O(b\cdot s\cdot d)\) per boundary, plus bubble \((p-1)/m\)inter-node; depth-bound
CP / Ring Attnsequence in attentionring P2P of KV blocksoverlapped with compute if block time > transferlong context, \(n\) too big for one GPU
EPMoE expertsAll-to-all tokens\(2\times tokens\times d\times bytes\) per MoE layersparse models

Rules of thumb used in production (2024–2026): TP ≤ GPUs/node (NVLink). PP to hide inter-node latency; microbatches \(m\gtrsim 4p\) to kill bubble. DP/ZeRO for remaining replicas. CP when \(s\) is 32k–1M. EP degree ≈ #experts, with capacity factor ~1–2.

Derivation exercises

  1. Attention backward (full). From \(S=QK^\top/\sqrt{d}\), \(P=\mathrm{softmax}(S)\), \(O=PV\):
  • \(\nabla_V=P^\top\nabla_O\)
  • \(\nabla_P=\nabla_O V^\top\)
  • \(\nabla_S = (P\odot(\nabla_P - \mathbf{1}(P\odot\nabla_P)\mathbf{1}^\top))\) (or the equivalent \(P\odot(\nabla_P - \mathrm{rowsums})\))
  • \(\nabla_Q=\nabla_S K/\sqrt{d}\), \(\nabla_K=\nabla_S^\top Q/\sqrt{d}\) Derive every line. Then write the FlashAttention backward sketch (recompute \(P\) tiles from stored max+rowsum).
  1. AdamW vs Adam+L2. Write both updates. Show L2 is rescaled by \(\sqrt{\hat v}\).
  2. μP. For a linear layer width \(n\), state init std, LR, and activation multiplier so that feature updates stay \(O(1)\) as \(n\to\infty\). Why the output layer LR shrinks.
  3. Loss scaling. fp16 max ≈ 65504. Grad of 1e-8 underflows. Show a scale of \(2^{10}\)–\(2^{16}\) and the unscale-before-Adam step. Why bf16 usually needs no loss scale.
  4. PP bubble. 1F1B schedule: bubble fraction \((p-1)/(m+p-1)\). Interleaved schedule (Narayanan): why it cuts bubble ~2×.
  5. Entropy collapse. Softmax entropy \(H(p)\ge \log n - \|z\|_\infty + \log(\cdots)\). Relate growing \(\|W_Q W_K^\top\|_2\) to one-hot attention (Zhai).
  6. Z-loss (PaLM). \(L_z=\lambda\,\mathrm{mean}(\log^2 Z)\). Why this stops logit drift from making softmax unstable.

Coding labs

  • Lab D1. Autodiff by hand for one attention head (numpy). Check vs torch.autograd to 1e-5.
  • Lab D2. Implement AdamW. Train the same tiny GPT with Adam+L2 vs AdamW; plot weight norms.
  • Lab D3. Implement μP on a width-mutable GPT. Tune LR at width 256; transfer to 1024. Compare to standard parametrization (it should fail).
  • Lab D4. Mixed precision: force fp16 without loss scaling until it NaNs. Then add dynamic loss scaling. Then switch to bf16 and remove scaling.
  • Lab D5. Packing: write a document-aware packer + intra-doc causal mask. Show the CE leak if you omit the mask (next-doc tokens attend to previous doc).
  • Lab D6 (systems). With 2–8 GPUs: implement naive DDP AllReduce; then a Megatron-style column/row TP pair on one linear+GELU+linear; measure busbw. Optional: one PP stage boundary.

Whiteboard

  • “Backprop through softmax-attention. Now. I will interrupt.”
  • “You have 256 H100s, 70B dense, seq 8k, global batch 4M tokens. Pick TP/PP/DP/SP. Estimate MFU.”
  • “Loss spiked at 80B. Attention entropy on 3 heads is 0.01. What do you do this afternoon?”
  • “Why is ZeRO-3 not a substitute for TP?”
  • “μP says you can transfer LR. Name two HPs that don’t transfer and why.”

E. Post-training (Anthropic-critical)

~130–160 deep hours

Thesis

Pretraining grows a prior over text. Post-training selects a policy. Anthropic’s public stack is: SFT on demonstrations → preference model → RL (PPO-like) and/or RLAIF under a constitution, with HHH as the operationalization of “aligned.” The failure modes — over-optimization, sycophancy, jailbreaks — are Goodhart problems in a sociotechnical loop, not “the model is evil.” Kernel people should care because RL sampling, RM forward passes, and long-context many-shot attacks are inference-and-training systems problems.

Learning outcomes

You can:

  1. Write the RLHF objective \(\max_\pi \mathbb{E}[r(x,y)]-\beta D_{\mathrm{KL}}(\pi\|\pi_{\mathrm{SFT}})\).
  2. Derive DPO from that objective + Bradley–Terry: the closed-form reward \(r(x,y)=\beta\log\frac{\pi(y|x)}{\pi_{\mathrm{ref}}(y|x)}\) and the logistic loss.
  3. Describe Constitutional AI as a procedure (supervised critique-revise, then RLAIF preference labels, then RL), not a slogan.
  4. Explain reward-model overoptimization (Gao): gold reward vs \(\sqrt{\mathrm{KL}}\).
  5. Distinguish outcome vs process rewards; say why process supervision is an Anthropic-shaped bet (scalable oversight / “let’s verify”).
  6. Treat sycophancy and jailbreaks as incentive + context + eval failures.

Must-read (read these, not blog summaries)

The RLHF spine

CAI / RLAIF

DPO and cousins

Rewards, process, Goodhart

Systems failure modes

Constitutional AI — the actual procedure (you must be able to recite this)

From Bai et al. 2022, two stages:

Stage 1 — Supervised CAI

  1. Sample responses from a helpful-but-not-yet-harmless model, including on adversarial / harmful prompts.
  2. Ask the same model to critique the response against a randomly chosen constitutional principle.
  3. Ask it to revise the response in light of the critique.
  4. Fine-tune the original model on the revised responses (SL). Multiple rounds of critique-revise are used. Chain-of-thought critiques help.

Stage 2 — RLAIF

  1. Sample two responses from the SL-CAI model.
  2. Ask a model to prefer one, given a constitutional principle (and often CoT).
  3. Fit a preference model on these AI-labeled pairs (harmlessness). Mix with human helpfulness labels as needed.
  4. RL (PPO-style) against that PM + KL to the SL-CAI policy.

Human labels for harmlessness can be near-zero. The constitution is the human bottleneck. Read the paper’s appendix principles; read Claude’s published constitution.

Derivation exercises

  1. Bradley–Terry → DPO. Start from \(p(y_w\succ y_l\mid x)=\sigma(r_w-r_l)\). Impose \(r=\beta\log\pi/\pi_{\mathrm{ref}}+Z(x)\). Cancel \(Z\). Arrive at \(\mathcal{L}_{\mathrm{DPO}}=-\log\sigma(\beta\log\frac{\pi_w}{\pi_{\mathrm{ref},w}}-\beta\log\frac{\pi_l}{\pi_{\mathrm{ref},l}})\).
  2. PPO-clip for a causal LM. Write the token-level advantage (GAE), the clipped ratio, the value loss, the KL/reward-model shaping \(r_t = r_{\mathrm{RM}}\cdot\mathbb{1}[t=T]-\beta\log\frac{\pi}{\pi_{\mathrm{ref}}}\).
  3. Gao overopt. Define \(d=\sqrt{D_{\mathrm{KL}}(\pi\|\pi_0)}\). Sketch \(R_{\mathrm{gold}}(d)\) for BoN vs RL. Why bigger RMs delay the peak.
  4. CAI label generation. Write the exact prompt pattern: principle + two responses + CoT + preference token. Where does position bias enter, and how does the paper swap order?

Coding labs

  • Lab E1. SFT a small model on a tiny instruction set. Measure win-rate vs base with a held-out RM or human-ish heuristic.
  • Lab E2. Implement DPO (the loss is ~30 lines). Train on Anthropic HH (Anthropic/hh-rlhf). Plot implicit reward margin vs KL-to-SFT.
  • Lab E3. Implement Best-of-N with a small RM. Reproduce a toy Gao curve: proxy reward up, gold (a bigger RM or held-out human labels) down.
  • Lab E4. Reproduce CAI Stage 1 on a harmless toy domain (e.g. “don’t give medical dosage advice”): critique → revise → SFT. No need for a frontier model.
  • Lab E5 (evals, not attacks). Read Perez / Sharma. Build a 50-item sycophancy eval (user states a false preference; model should not flip facts). This is measurement, not jailbreak how-to.

Whiteboard

  • “Derive DPO in 10 minutes. When does it underperform PPO?”
  • “Walk me through Constitutional AI as if I have to implement it next quarter. Where do the GPUs go?”
  • “Reward goes up, users say the model got worse. Diagnose.”
  • “Sycophancy: is it pretraining, RLHF, or the preference data? Cite Sharma and Perez.”
  • “Many-shot jailbreaking is ICL. What does that imply for long-context product decisions and for eval design?”
  • “Process vs outcome rewards. Give a math problem where outcome RM is fooled and a PRM is not.”

F. Inference

~110–130 deep hours

Thesis

Autoregressive inference is an HBM-bandwidth problem disguised as a math problem. Prefill is compute-bound; decode is memory-bound on the KV cache. Every major serving trick — GQA/MLA, PagedAttention, continuous batching, speculative decoding, quantization — attacks bytes moved per generated token or reduces serial steps.

Learning outcomes

You can:

  1. Write KV-cache size: \(2\cdot n_{\text{layers}}\cdot n_{kv}\cdot d_h\cdot s\cdot b\cdot \mathrm{sizeof}\). Convert to GB. Predict when you OOM.
  2. Explain prefill vs decode roofline; why batching decode is mandatory.
  3. Explain continuous / iteration-level batching (Orca) vs static batching.
  4. Derive speculative decoding’s exact acceptance rule (Leviathan); expected speedup \(1+\sum p(\text{accept first }k)\).
  5. State what quantization can drop: weights (GPTQ/AWQ) vs KV (fp8/int8) vs activations; when it becomes a quality cliff.
  6. Explain RoPE interpolation, NTK-aware, YaRN (NTK-by-parts + attention temperature), and recency biases (ALiBi).

Must-read

Derivation exercises

  1. Cache math. 70B, 80 layers, 64 q-heads, 8 kv-heads, \(d_h=128\), bf16, batch 32, 8k context. GB of KV. Now 128k context. Now MLA with \(d_c=512\).
  2. Roofline. Decode: bytes = read all weights + read KV. FLOPs ≈ \(2N\) per token (N = params) plus attention. On H100 (3 TB/s, 990 TFLOP/s bf16), show decode of a 70B is memory-bound at batch 1 and becomes compute-bound at large batch.
  3. Speculative sampling. Draft \(q\), target \(p\). Accept token \(x\sim q\) with \(\min(1,p(x)/q(x))\); on reject, sample from \(\mathrm{norm}(\max(0,p-q))\). Prove the output distribution is exactly \(p\).
  4. YaRN. Write the wavelength-partitioned scale \(s\), the ramp on mid-frequencies, and \(\sqrt{1/t}=0.1\ln s+1\). Why low-frequency dims must be interpolated, not extrapolated.
  5. PagedAttention. Internal fragmentation ≤ one block; external = 0. Why this raises max batch (and thus decode utilization).

Coding labs

  • Lab F1. Implement KV-cached decode for your C1 model. Time prefill vs decode. Plot tokens/s vs batch.
  • Lab F2. Tiny speculative decoder: a 4-layer draft + 12-layer target. Measure acceptance rate and wall-clock. Verify token distribution ≈ target by χ² on a toy vocab.
  • Lab F3. Int8-quantize Linear weights (per-channel). Measure CE degradation. Then implement a smooth migration of activation outliers (SmoothQuant idea) on one layer.
  • Lab F4. Read vLLM’s block manager well enough to draw the logical→physical block table and copy-on-write for a beam of 2.

Whiteboard

  • “How big is the KV cache? Don’t look it up.”
  • “Why doesn’t tensor-parallel help decode latency at batch 1 as much as you hoped?”
  • “Speculative decoding changes nothing about the distribution. Prove it.”
  • “What do you refuse to quantize to 4-bit, and why?” (attention KV? layernorm scales? embeddings? first/last layers?)
  • “User wants 1M context. Do you buy more HBM, switch to MLA, use CP, or change the product?”

G. Interpretability (enough to collaborate)

~80–100 deep hours

Thesis

Models implement algorithms in superposition on the residual stream. Neurons are the wrong basis. Features (directions) and circuits (sparse computational graphs) are the current best ontology. SAEs are a dictionary-learning attack on superposition. Kernel / systems people should care because interp at scale is a data-plane problem: hooks, activation dumps, sparse matmuls, and training SAEs on trillions of activation tokens.

Learning outcomes

You can:

  1. Explain linear representation + superposition; draw Elhage’s phase diagram (importance × sparsity).
  2. Write an SAE: \(z=\mathrm{ReLU}(W_e(x-b)+b')\), \(\hat x=W_d z+b\), loss \(\|x-\hat x\|_2^2+\lambda\|z\|_1\), unit-norm decoder columns.
  3. Walk through the induction-head circuit (previous-token head + induction head via K-composition).
  4. Explain QK / OV circuits from Mathematical Framework.
  5. Say what you would instrument in a training stack to make interp possible (residual hooks, activation sharding, replay buffers).

Must-read

Courses / tooling

Derivation / pen-paper

  1. Superposition toy. \(n\) features, \(m<n\) dimensions, sparsity \(s\). Write the interference term. When is a feature allocated its own dimension?
  2. Induction. On the sequence [A][B] … [A], write what the layer-1 previous-token head writes and what the layer-2 head’s keys match. This is K-composition.
  3. SAE scaling. From Scaling Monosemanticity: why residual-stream (not MLP) mid-layer; why L1 on activations + unit-norm decoder; dead-feature problem.

Coding labs

  • Lab G1. Reproduce a superposition toy (5–20 lines of torch + a phase diagram).
  • Lab G2. TransformerLens on GPT-2-small: find an induction head with the prefix-matching score. Ablate it; show ICL loss rises.
  • Lab G3. Train a small SAE on a 1-layer transformer's MLP activations (follow Towards Monosemanticity appendix). Browse features. Expect mostly garbage plus a few real ones — that’s the lesson.
  • Lab G4 (kernel-adjacent). Write a hook that dumps residual stream tiles to disk without stalling training (async copy, downcast to bf16, sequence-parallel aware). Estimate TB/day at 70B, 1M tokens/batch, every 100 steps, 1 layer.

Whiteboard

  • “What is superposition? Why does it make interp hard? Why might it be computationally necessary?”
  • “Explain induction heads to a kernel engineer who has never heard of them. Then tell them what activation they should dump.”
  • “You have 10k H100-hours. SAE on a mid-size model or another pretrain? Anthropic chose both. How do you staff the systems side?”

H. Numerics & “the metal”

~100–130 deep hours

Thesis

The model is a IEEE-754 program. Formats are contracts on range vs precision. Accumulators are where correctness lives. Softmax is a numerically hostile reduction. Determinism is a lie unless you pay for it. This section is what separates “I implemented attention” from “I can ship a 100B train that does not NaN on Friday night.”

Learning outcomes

You can:

  1. Draw the bit layouts of fp32, tf32, bf16, fp16, fp8 E4M3, fp8 E5M2. Give max finite, ULP at 1.0, and typical use.
  2. Explain why GEMM accumulates in fp32 even when inputs are bf16/fp8; what TF32 tensor cores actually do (10-bit mantissa).
  3. Implement stable softmax and online softmax; know FlashAttention’s stored statistics \((m, \ell)\).
  4. List sources of nondeterminism: atomic adds, cuDNN heuristics, dropout, DP reduction order, TF32, async collectives. Know how to force determinism and the speed cost.
  5. Debug a NaN: inf in exp, 0·inf, Adam \(\sqrt{v+\epsilon}\) of a leftover Inf, bf16 overflow of logits, fp16 grad underflow.

Must-read

Format table (memorize)

FormatExpMantissa (stored)Max finite (approx)ε at 1.0Typical role
fp328233e382⁻²³master weights, accumulators, Adam states (or fp32 moments)
tf328103e382⁻¹⁰Ampere+ tensor-core math on fp32 inputs
bf16873e382⁻⁷activations/weights in LLM training
fp16510655042⁻¹⁰inference; training only with loss scale
fp8 E4M343448coarseweights/acts (fwd)
fp8 E5M25257344coarsergrads (bwd)

Accumulator rule: MMA of low-precision inputs → fp32 accumulator → downcast to store. Softmax: accumulate exp-sum in at least fp32. Residual adds: prefer fp32 residual or careful bf16 (Pre-LN helps). Adam: keep moments in fp32.

Derivation exercises

  1. ULP. Compute ULP(1.0) for each format. How many distinct bf16 numbers in \([1,2)\)? Implication for weight updates of size \(10^{-4}\).
  2. Softmax overflow. \(z_i=100\) in fp16. \(e^{100}\) overflows. Show the max-subtraction fix. Show a case where all \(z_i\) are −80 and naive exp underflows to a 0/0 NaN.
  3. Online softmax associativity. Prove you can merge two blocks \((m_1,\ell_1,O_1)\), \((m_2,\ell_2,O_2)\) into a correct \((m,\ell,O)\). This is FlashAttention.
  4. TF32. A matmul in tf32 vs fp32: estimate a relative error. When does a long reduction (e.g. attention over 128k) accumulate enough error to change argmax?
  5. Determinism. AllReduce in tree vs ring: write two summation orders of 8 terms. Bound the fp32 difference.

Coding labs

  • Lab H1. Print bit patterns: take 1.0, 1+ulp, Inf, NaN for fp16/bf16. Write a decoder.
  • Lab H2. Implement GEMM three ways: fp32, bf16-in-fp32-acc, fp16-in-fp16-acc. Compare residual of \(AA^\top\). The last one should scare you.
  • Lab H3. Break softmax on purpose (large logits, all-very-negative, causal mask filled with 0 instead of -inf). Fix each.
  • Lab H4. CUDA (or Triton): write a fused RMSNorm+Linear or online-softmax kernel. Profile with Nsight: achieved bandwidth, occupancy, bank conflicts.
  • Lab H5. Turn on torch.use_deterministic_algorithms(True) for a 2-GPU train. Measure slowdown. Find the op that broke.

Whiteboard

  • “bf16 vs fp16. Don’t say ‘more range.’ Draw the bits. Now tell me why Adam moments stay fp32.”
  • “Your loss is NaN at step 12k, only on TP=8, not TP=1. Walk the debug.”
  • “FlashAttention claims exact attention. Exact in which algebra?”
  • “Can we train in fp8 end-to-end? What tensors stay in higher precision?”
  • “Reproducibility: the paper reviewer wants bitwise-identical runs. What do you tell them?”

Cross-cutting: “what kernel work has to do with AGI”

Keep this paragraph in your head; it is the interview’s connective tissue.

Scaling laws say loss (and, more noisily, capability) is a smooth function of compute, data, and parameters. Every 10–20% you save on step time, activation memory, or decode bandwidth is a larger N, larger D, or more RL/SAE/eval tokens at fixed dollar/carbon budget. Constitutional AI, process rewards, and monosemantic SAEs are hungry for that surplus. A kernel that makes attention 1.5× at 128k context is not a compiler curiosity; it is what makes “many-shot evals,” long-horizon agents, and activation logging at scale affordable. Conversely, an unstable softmax at 100B wastes a cluster-week and produces no science. Anthropic-shaped research engineers are people who can move fluently from “what is the HHH tradeoff on this prompt” to “the accumulator is tf32 and the reduction order changed.”


Suggested 9-month path (20–25 h/week)

MonthsGateYou should be able to
0–1B + H warmupCE/KL/BPB, BPE from scratch, fp16/bf16 bits, stable softmax
1–3C + D mathFull GPT from scratch, attention backward, AdamW, RoPE, Pre-LN
3–5D systems + FParallelism comm math, KV cache, FlashAttention forward, packing
5–7EDPO derived + implemented, CAI procedure recited, Gao curve, sycophancy eval
7–8GInduction head found, SAE trained, superposition toy
8–9A + interview repsScaling-law arguments, 20 whiteboard hours, one Triton/CUDA kernel you can defend

Do not consume all papers linearly. For each section: skim the must-reads → do the derivations → do the labs → re-read the papers. The second reading is where you actually learn.


Interview-day checklist (Anthropic RE / kernel-adjacent)

You should be able to do all of these on a whiteboard in one day:

  1. \(\mathrm{softmax}(QK^\top/\sqrt{d})V\) + complexity + \(\sqrt{d}\) variance argument.
  2. Backprop through attention, matrix form.
  3. KV-cache bytes; GQA vs MQA vs MLA.
  4. AdamW update; why not L2.
  5. DP AllReduce volume; TP AllReduce volume; PP bubble.
  6. FlashAttention: tiling, online softmax merge, what’s stored for backward.
  7. bf16 vs fp16 vs fp8 E4M3/E5M2; where you accumulate.
  8. DPO loss from RLHF+BT in ~10 lines.
  9. Constitutional AI’s two stages, concretely.
  10. One instability: entropy collapse or logit drift, plus the fix.
  11. One bitter-lesson / scaling-law question without becoming a TED talk.
  12. One interp object (induction head or SAE loss) well enough to collaborate.

If you miss more than two of these cold, you are not ready.


Resources index (courses & books, not already listed)


What this curriculum deliberately does not do

  • It does not pretend a blog post replaces Vaswani, Kaplan, Bai, Rafailov, Dao, or Elhage.
  • It does not treat “I fine-tuned Llama with QLoRA” as training knowledge.
  • It does not give jailbreak recipes; it treats jailbreaks as eval and systems problems (Anil et al., product context limits, ICL).
  • It does not pick a winner between DPO and PPO; it makes you derive both.
  • It does not claim kernel work is sufficient for AGI. It claims it is on the critical path of the only research program that has empirically compounded.

If you actually do the labs and the derivations, you will be in the small set of people who can walk into an Anthropic research-engineer interview and treat “intelligence,” “RLAIF,” and “accumulator width” as one subject. That is the point.