PILLAR · LLM SYSTEMS

LLM training & RLHF

Pretraining, mid-training, SFT, preference optimization, RLVR, reasoning models, interaction models. The May 2026 frontier-lab interview probes the DeepSeek V4 recipe, NVFP4 pretraining, Thinking Machines' Interaction Models, on-policy distillation, and Decoupled DiLoCo. You should be able to design a Llama-scale (or V4-scale) run end-to-end and justify every numerical choice.

Read ~55 min Asked at Anthropic · OpenAI · DeepMind · DeepSeek · Thinking Machines · xAI · Together · NVIDIA Difficulty Sr Staff / Principal Updated May 11, 2026
01
FOUNDATIONS · PRETRAINING

The pretraining recipe — data is the moat, scaling laws are the budget

TL;DR

Frontier 2026 pretraining = 20–40T tokens across web + code + books + math + multilingual + heavy synthetic. Quality classifier and MinHash dedup do most of the heavy lifting. Mixing weights up-sample high-quality sources; phased curricula anneal toward reasoning data near the end. Chinchilla's $D \approx 20N$ is now a lower bound — inference economics push Llama 3 8B to $\sim 1875$ tokens/parameter and DeepSeek V4-Pro to $\sim 32\,\mathrm{T}/49\mathrm{B}_{\text{active}} \approx 650$ tokens/active-param.

Chinchilla in one equation, and why nobody obeys it

Hoffmann et al. (2022) fit pretraining loss as a function of parameters $N$ and tokens $D$ given a compute budget $C \approx 6ND$ FLOPs:

$$L(N, D) = E + \frac{A}{N^{\alpha}} + \frac{B}{D^{\beta}}, \quad \alpha \approx 0.34, \; \beta \approx 0.28$$

Setting $\partial L/\partial N = \partial L/\partial D$ under the budget constraint $C = 6ND$ gives the Chinchilla-optimal allocation $D^* \approx 20 N$. The 2024–2026 frontier deliberately violates this on the data side because training compute is a one-time cost, inference compute is forever. Sardana & Frankle (arXiv 2401.00448) made this rigorous as the "Beyond Chinchilla-Optimal" rule: minimize total cost over expected inference volume, not training loss.

EXAMPLE — tokens/parameter in 2026

Llama 3 8B: $\approx 1875$ tok/param. Llama 3 70B: $\approx 215$. DeepSeek V3: $14.8\mathrm{T}/37\mathrm{B}_{\text{active}} \approx 400$. DeepSeek V4-Pro: $32\mathrm{T}/49\mathrm{B}_{\text{active}} \approx 650$. Kimi K2 1T-A32B: $\approx 470$. The compute-optimal frontier is $\approx 20$ — everyone overtrains by an order of magnitude.

Data sources — what goes in

Frontier mixtures pull from six buckets, in roughly decreasing volume:

Quality filtering — six-stage pipeline

  1. URL/domain filtering — block adult content, low-quality TLDs, known content farms.
  2. Language ID via fastText or CLD3 — keep target languages only.
  3. Heuristic (Gopher) rules — avg word length 3–10, % lines ending in punctuation, % stop words, % alphabetic chars.
  4. Repetition removal — drop docs with excessive line/paragraph repetition.
  5. Toxicity / PII filters.
  6. Quality classifier — small classifier (typically ~1B params) trained on labels distilled from a teacher LLM scoring "educational value"; score every doc and threshold.
EXAMPLE — FineWeb-Edu's classifier filter

HF used Llama-3-70B to label educational value 0–5, trained a small classifier on those labels, then filtered 15T → 1.3T high-quality tokens. Models trained on the 1.3T-token subset beat models trained on the full 15T at the same compute — quality dominates quantity once you cross a threshold. Nemotron-CC v2 (NVIDIA, arXiv 2412.02595) extended this with paraphrase rewriting of low-quality but high-signal pages.

Deduplication — three layers stacked

Mixing weights & curricula

Up-sample high-quality (Wikipedia, books, code), down-sample bulk web. DoReMi (Xie 2023, arXiv 2305.10429) trains a small reference + proxy and uses Group DRO to find weights $\boldsymbol{\alpha}$ minimizing worst-case excess loss:

$$\boldsymbol{\alpha}^* = \arg\min_{\boldsymbol{\alpha}} \max_{i \in \mathcal{D}} \left[ L_i(\theta_{\boldsymbol{\alpha}}) - L_i(\theta_{\text{ref}}) \right]$$

The reference is your best small model; proxy weights chase the worst-performing domain. DataComp-LM (Li 2024, arXiv 2406.11794) sweeps mixtures empirically. Most labs combine: DoReMi for initial weights, then late-stage anneal with a hand-tuned mid-training mix.

EXAMPLE — Llama 3, DeepSeek V3/V4, and the anneal

Llama 3 pretrained on 15T tokens total and annealed on a curated mixture in the last 40B tokens with linear LR decay to ~10% of peak. DeepSeek V3 used a separate mid-training phase emphasizing math and code before SFT. DeepSeek V4 formalizes this as two phases: bulk pretrain (24T tokens, broad mix) → cultivation (8T tokens, reasoning/code/multilingual heavy, WSD decay). The anneal alone moves MMLU-Pro by 4–6 points.

PITFALL — eval contamination
Common dedup pipelines miss test-set leakage from web. MMLU questions appear verbatim on tutoring sites; GSM8K problems get reposted on Reddit; SWE-Bench issues are literally on GitHub. Always run an explicit 13-gram contamination check against your eval suites and remove matches. A few percentage points of "improvement" on MMLU often turns out to be leak — and the 2024–25 LMSYS/Hugging Face contamination audits caught multiple frontier labs.
REMEMBER
  • Chinchilla's $D \approx 20N$ is a lower bound; inference economics push $D/N$ to 200–2000.
  • Quality classifier + MinHash dedup do 90% of the work — get them right.
  • Phased curricula (anneal toward reasoning data) are nearly free wins.
  • Run explicit eval-contamination checks; trust no dedup pipeline by default.
02
PRETRAINING · LIFECYCLE

Mid-training as a canonical stage — IBM's 500-experiment study

TL;DR

Mid-training sits between pretraining and SFT — same causal LM loss, but on clean reasoning-heavy data with WSD decay. IBM Research's 500-experiment study (arXiv 2512.07783, Dec 2025) shows mid-training boosts downstream reasoning $3\text{–}4\times$ at fixed compute vs RL-only. The 2026 canonical post-training pipeline is: pretrain → mid-train → SFT → on-policy distillation → GRPO with verifiable rewards. Continual pretraining (CPT) for domain adaptation uses the same machinery with replay + low LR.

Mid-training — the new norm

Mid-training continues causal LM training but with a different mixture — heavy up-weight on reasoning, math, code, possibly synthetic chain-of-thought. Typically combined with a WSD (warmup-stable-decay) schedule where the decay phase coincides with the mixture shift. The model becomes "reasoning-ready" without yet being instruction-tuned. Token budgets: $5\text{–}25\%$ of total pretraining tokens.

THE INSIGHT — IBM's mid-training study

Why mid-training beats more-RL at fixed compute

Akash et al. (IBM Research, arXiv 2512.07783) ran 500 controlled experiments varying the SFT/mid-train/RL FLOP split for a fixed total budget. Key findings:

  • Pure-RL pipelines plateau early; the reasoning gains come from compressing known traces into the base, not from RL search.
  • Adding a mid-training stage with 200–500B clean reasoning tokens lifts AIME, GPQA, and LiveCodeBench by $3\text{–}4\times$ vs spending the same FLOPs on more GRPO steps.
  • The optimal pipeline they identify is SFT $\to$ mid-train $\to$ on-policy distillation $\to$ GRPO. Skip any of the first three and RL doesn't recover the gap.
  • Reverse-KL on-policy distillation in stage 3 is what eliminates the costly "search phase" of RL (see Ch. 9).

Continual pretraining (CPT) — adapting a frozen base

Take a pretrained model and continue on new data — new language, new domain, new time period. The risk is catastrophic forgetting; the standard mitigations are:

PITFALL — over-aggressive CPT learning rate
Restarting training at the original peak LR is the #1 cause of collapse during CPT. The model's optimizer state is gone but the weights remember nothing about why they're where they are. Use $1/10$ to $1/100$ of pretraining peak and rewarmup over the first 1–2% of tokens.
REMEMBER
  • Mid-training = reasoning-focused causal LM phase; cheap, high-leverage.
  • IBM's 500-experiment study: SFT $\to$ mid-train $\to$ on-policy distill $\to$ GRPO is the 2026 canon.
  • CPT requires replay + low LR or you'll forget everything.
  • WSD decay pairs naturally with mid-training annealing.
03
POST-TRAINING · SFT

SFT — instruction tuning that doesn't blunt capability

TL;DR

SFT trains on (instruction, response) pairs with cross-entropy on response tokens only (prompt is masked). It teaches format, not capability — capability comes from pretraining. LIMA showed diversity beats scale beyond ~10k–100k examples; Tülu 3 and Tülu 4 showed 1M+ helps when domains are diverse. Get the chat template right or everything breaks silently.

The mechanics

Single- or multi-turn instruction-response pairs. Loss is cross-entropy on response tokens; the prompt mask zeroes out prompt positions. Formally, for a sequence $y = (y_1, \dots, y_T)$ partitioned into prompt $\mathcal{P}$ and response $\mathcal{R}$:

$$\mathcal{L}_{\text{SFT}} = -\frac{1}{|\mathcal{R}|} \sum_{t \in \mathcal{R}} \log \pi_\theta(y_t \mid y_{

Modern SFT datasets fall into three buckets:

LIMA hypothesis vs Tülu 3/4

LIMA (arXiv 2305.11206) — "less is more for alignment" — diversity $>$ scale beyond ~10k–100k examples. Capabilities live in the base model; SFT only teaches format/instruction-following.

Tülu 3 (arXiv 2411.15124) and Tülu 4 (arXiv 2511.18402) updated this: up to 1M+ examples helps when domains are diverse (math, code, IF, safety, multilingual, tool-use). The 2026 statement is "diversity matters more than count, but more diversity is more count."

Few-shot vs zero-shot tradeoff

Pretraining gives ICL (in-context learning) ability for free. SFT collapses the model toward instruction-following at zero-shot, which can sometimes hurt few-shot performance. The fix is a small fraction of "raw completion" examples in the SFT mix.

PITFALL — chat template drift
Formatting consistency is critical: system/user/assistant tokens, ChatML, Llama 3 special tokens, DeepSeek V4's new |DSML| tool-call delimiter. A model trained with one template and inferenced with another silently degrades by 5–20 points on benchmarks. Always pin the template; never rely on a tokenizer's default during eval.
REMEMBER
  • SFT teaches format, not capability — keep examples diverse.
  • Mask the prompt; loss on response tokens only.
  • Pin the chat template across train + eval + serve.
04
POST-TRAINING · PREFERENCE OPT

The preference-optimization zoo — DPO derived, GRPO, IPO, KTO, ORPO

TL;DR

RLHF (PPO + reward model + KL penalty) was the original — Christiano 2017, then InstructGPT 2022. DPO (2023) eliminated the RM and the RL loop via a closed-form identity. GRPO (DeepSeek 2024) dropped the value model — group statistics replace the baseline. IPO/KTO/ORPO are variants. Know the DPO derivation cold; it's the most-asked whiteboard problem at Anthropic/OpenAI/DeepSeek.

Original deep RLHF — Christiano 2017

"Deep RL from Human Preferences" (Christiano et al. 2017, arXiv 1706.03741) — predates InstructGPT by 5 years. Demonstrated RLHF on Atari and MuJoCo with a Bradley-Terry preference model and PPO. If an interviewer asks "who invented this?" — name Christiano.

RLHF / PPO — the LLM-era recipe

(Ouyang 2022, arXiv 2203.02155 — InstructGPT.) Three stages:

  1. Reward model on $(x, y_w, y_l)$ pairs with Bradley-Terry: $$P(y_w \succ y_l \mid x) = \sigma\big( r_\phi(x, y_w) - r_\phi(x, y_l) \big), \quad \mathcal{L}_{\text{RM}} = -\mathbb{E}\big[\log \sigma(r_\phi(x, y_w) - r_\phi(x, y_l))\big].$$
  2. RL fine-tune policy $\pi_\theta$ with PPO against $r_\phi$ plus a per-token KL penalty to the SFT reference: $$r_{\text{total}}(x, y) = r_\phi(x, y) - \beta \cdot \mathrm{KL}\big(\pi_\theta(\cdot \mid x) \,\|\, \pi_{\text{ref}}(\cdot \mid x)\big).$$
  3. PPO clipped objective with importance ratio $\rho_t(\theta) = \pi_\theta(a_t \mid s_t) / \pi_{\theta_{\text{old}}}(a_t \mid s_t)$ and advantage $\hat A_t$ (GAE): $$\mathcal{L}^{\text{CLIP}}(\theta) = \mathbb{E}_t \Big[ \min\big( \rho_t \hat A_t,\; \mathrm{clip}(\rho_t, 1 - \epsilon, 1 + \epsilon)\, \hat A_t \big) \Big].$$
PITFALL — reward hacking & RM overoptimization
RM correlates with true preference up to a point, then diverges (Goodhart's law; Gao et al. 2022 quantify the scaling laws). PPO will happily exploit that gap — outputs "look great" to the RM but humans rate them worse. Mitigations: stronger $\beta$, RM ensembles, PPO early stopping by held-out human eval, or move to RLVR (Ch. 6).

DPO — closed-form preference optimization (most popular 2023–24)

Rafailov 2023, arXiv 2305.18290. Reformulates RLHF as classification on the reference policy. Final loss:

$$\mathcal{L}_{\text{DPO}}(\pi_\theta; \pi_{\text{ref}}) = -\mathbb{E}_{(x, y_w, y_l)} \left[ \log \sigma\!\left( \beta \log \frac{\pi_\theta(y_w \mid x)}{\pi_{\text{ref}}(y_w \mid x)} - \beta \log \frac{\pi_\theta(y_l \mid x)}{\pi_{\text{ref}}(y_l \mid x)} \right) \right]$$

THE INSIGHT — DPO derivation, end-to-end

From KL-constrained RL to a classification loss

Step 1. Start with the KL-constrained RL objective:

$$\max_{\pi} \; \mathbb{E}_{x \sim \mathcal{D},\, y \sim \pi(\cdot \mid x)}\big[ r(x, y) \big] \; - \; \beta \cdot \mathrm{KL}\big(\pi(\cdot \mid x) \,\|\, \pi_{\text{ref}}(\cdot \mid x)\big).$$

Step 2. Pointwise in $x$, the solution is the Gibbs distribution:

$$\pi^*(y \mid x) = \frac{1}{Z(x)} \pi_{\text{ref}}(y \mid x) \exp\!\left( \frac{1}{\beta} r(x, y) \right), \quad Z(x) = \sum_{y'} \pi_{\text{ref}}(y' \mid x) \exp\!\left( \frac{r(x, y')}{\beta} \right).$$

(Derive by Lagrangian or by observing $\mathrm{KL}(\pi \| \pi^*) \geq 0$ achieves equality at $\pi = \pi^*$.)

Step 3. Invert to write the implicit reward in terms of policy and reference:

$$r(x, y) = \beta \log \frac{\pi^*(y \mid x)}{\pi_{\text{ref}}(y \mid x)} + \beta \log Z(x).$$

Step 4. Plug into Bradley-Terry. Since both responses share the prompt $x$, $\beta \log Z(x)$ cancels:

$$P(y_w \succ y_l \mid x) = \sigma\!\left( \beta \log \frac{\pi^*(y_w \mid x)}{\pi_{\text{ref}}(y_w \mid x)} - \beta \log \frac{\pi^*(y_l \mid x)}{\pi_{\text{ref}}(y_l \mid x)} \right).$$

Step 5. Treat $\pi^*$ as parameters $\pi_\theta$ and minimize negative-log-likelihood over preference pairs — that's the DPO loss. One step. No RM. No PPO loop.

PITFALL — mode collapse / likelihood displacement in DPO
DPO can simultaneously decrease the likelihood of both chosen and rejected responses — only the gap between log-probs matters in the loss. The policy may drift far from $\pi_{\text{ref}}$ and outputs degrade. Razin et al. (arXiv 2410.08847) named this "likelihood displacement" and showed it correlates with reference-policy KL drift. Mitigations: stronger $\beta$, IPO (squared loss), mix in SFT loss as regularizer ($\mathcal{L}_{\text{DPO}} + \lambda \mathcal{L}_{\text{SFT}}$), conservative sampling temperature, anchor with a small SFT replay set, or use SimPO/CPO variants.

IPO, KTO, ORPO — the variants

GRPO — the 2024 winner (DeepSeek)

DeepSeekMath, arXiv 2402.03300 — central role in R1 and V4. For each prompt $x$, sample a group of $G$ outputs $\{y_i\}_{i=1}^G$ from the current policy. Compute rewards $\{r_i\}$. The sequence-level advantage for output $i$ is the group $z$-score:

$$A_i = \frac{r_i - \mathrm{mean}(r_1, \dots, r_G)}{\mathrm{std}(r_1, \dots, r_G) + \varepsilon}$$

This scalar advantage is broadcast to every token in trajectory $i$. The objective adds a per-token KL penalty against $\pi_{\text{ref}}$ (estimated via $\mathrm{KL}[\pi_\theta \| \pi_{\text{ref}}] \approx \tfrac{\pi_{\text{ref}}}{\pi_\theta} - \log\tfrac{\pi_{\text{ref}}}{\pi_\theta} - 1$, the unbiased k3 estimator):

$$\mathcal{J}_{\text{GRPO}}(\theta) = \mathbb{E}\!\left[ \frac{1}{G}\sum_{i=1}^G \frac{1}{|y_i|} \sum_{t=1}^{|y_i|} \Big( \min(\rho_{i,t} A_i,\, \mathrm{clip}(\rho_{i,t}, 1{-}\epsilon, 1{+}\epsilon) A_i) - \beta\, \mathrm{KL}_t \Big) \right]$$

No critic / value model needed — group statistics replace the value baseline. Removes the critic, saving ~30–50% of total training memory vs PPO (depending on whether the value head shares the policy backbone).

EXAMPLE — per-token credit assignment in GRPO (or lack thereof)

Common follow-up: "What about per-token credit assignment in GRPO?" Answer: there isn't any — every token in output $i$ gets the same scalar $A_i$. This is GRPO's strength on verifiable-reward tasks (the reward is sequence-level — pass/fail unit tests, math correctness) and its weakness on dense-reward problems.

RLOO (Ahmadian 2024, arXiv 2402.14740) and REINFORCE++ are competing approaches that also drop the critic but use different baselines — leave-one-out: $b_i = \tfrac{1}{G-1}\sum_{j \neq i} r_j$. DAPO (Yu 2025, arXiv 2503.14476) replaces the standard-deviation normalizer with a clip-higher / clip-lower scheme to prevent collapse on saturated rewards. GSPO uses sequence-level importance ratios.

PPO (RLHF)

  • Needs RM + value model
  • ~4× base model in memory
  • Per-token credit via GAE
  • Reward hacking risk on learned RM

GRPO

  • No critic; group baseline (mean/std)
  • ~2× base model
  • Sequence-level advantage
  • Pairs naturally with verifiable rewards
REMEMBER
  • Christiano 2017 = origin of deep RLHF; InstructGPT 2022 = LLM application.
  • DPO derivation: KL-constrained RL $\to$ closed-form Gibbs policy $\to$ solve for reward $\to$ Bradley-Terry $\to$ $Z(x)$ cancels.
  • GRPO drops the critic; advantage is sequence-level $z$-score over a group of $G$ rollouts.
  • Mode collapse / likelihood displacement in DPO is real; $\beta$ + SFT mix mitigates.
05
POST-TRAINING · ANTHROPIC STACK

Constitutional AI & RLAIF — preferences from a model, not a crowd

TL;DR

RLAIF replaces human preference labels with AI-judge labels — cheaper, scales further, often comparable quality. Constitutional AI (Anthropic) makes the AI judge follow explicit principles: SL phase trains the model to self-critique and revise; RL phase trains an RM on AI-generated preference pairs. Subjectivity moves from crowd to constitution.

RLAIF — the cheap version

Like RLHF but preference labels come from an AI judge (often a stronger model) instead of humans. Bai et al. (2022) and Lee et al. (2023, arXiv 2309.00267) showed RLAIF matches or beats RLHF on helpfulness, harmlessness, and summarization. The labeling distribution is more consistent than humans (less noise) but inherits the judge's biases.

Constitutional AI (Anthropic)

Bai 2022, arXiv 2212.08073. Two phases:

  1. SL phase (self-revision) — model produces a response; same model critiques it against a sampled constitutional principle; same model revises. SFT the final model on (prompt $\to$ revised response) pairs.
  2. RL phase (RLAIF) — model generates response pairs; another model picks the better one given the constitution; train RM on these AI-generated preferences; PPO as usual.

The constitution itself is a small set of natural-language principles (be helpful, avoid harm, refuse illegal requests, etc.). Subjectivity shifts from crowd workers to the principles you write. Claude 3 / 3.5 / 4 ship updated constitutions; the "Sparrow rules" (DeepMind) and OpenAI's "Model Spec" are analogous artifacts.

REMEMBER
  • RLAIF = labels from an AI judge instead of humans.
  • Constitutional AI = RLAIF where the judge applies explicit written principles.
  • Cheaper than RLHF; subjectivity moves from crowd to constitution.
06
POST-TRAINING · REASONING

RLVR & reasoning models — the verifiable-reward era

TL;DR

RLVR (RL with Verifiable Rewards) replaces a learned RM with a programmatic verifier — unit tests, exact-match math, formal proof checker. No reward hacking on the verifier signal (within limits). This is what made o-series, R1, V4, and Tülu 3/4's reasoning capability possible. Test-time compute (length of reasoning) becomes a knob with a power-law payoff.

RLVR — the idea

Instead of a learned RM, use a programmatic verifier:

The verifier is the ground truth on verifiable tasks. The "RL revolution of 2024–26" is largely RLVR-driven. Used by Tülu 3/4, DeepSeek R1/V4, OpenAI o1/o3, Anthropic's reasoning-mode Claudes, Google's Gemini Reasoner.

PITFALL — reward hacking on the verifier
Even verifiable rewards can be gamed: tampered CoT (correct final answer with non-causal reasoning that the verifier never reads), verifier exploitation (output matches the regex but reasoning is wrong), length hacking (rambling that pads partial-credit graders), Python escape attempts on sandboxed graders. Mitigations: process rewards (PRM), multiple independent verifiers (majority vote), behavioral evals catching CoT-answer mismatch, randomized verifier prompts, and CoT consistency checks.

OpenAI o-series, Claude reasoning mode, Gemini Reasoner

All trained with large-scale RLVR on reasoning traces. The model learns to produce long chains of thought featuring backtracking, self-verification, plan-then-execute, and alternative approaches. Test-time compute (reasoning length) becomes a real monotone knob — Snell et al. (arXiv 2408.03314) and the o1 system card both report power-law scaling of accuracy in $\log(\text{thinking tokens})$.

REMEMBER
  • RLVR = programmatic verifier replaces RM. No (RM-style) reward hacking.
  • Reasoning emerges from RL on verifiable tasks; the base must be strong.
  • Test-time compute is a real, monotone knob — power law in $\log(\text{tokens})$.
07
CASE STUDY · OPEN CANON

DeepSeek V4 — the 2026 open canon

TL;DR

DeepSeek V4 (April 24, 2026) is the most thoroughly documented frontier-scale recipe in the open literature. V4-Pro: 1.6T total / 49B active MoE, 61 layers, 1M context. V4-Flash: 284B/13B active. Trained on 32T+ tokens. Architecture: alternating Compressed Sparse Attention (CSA) and Heavily Compressed Attention (HCA) with sliding-window heads, Manifold-Constrained Hyper-Connections, auxiliary-loss-free expert routing, Muon optimizer in production, MXFP4 MoE weights. Post-training: cultivation $\to$ consolidation via on-policy distillation $\to$ GRPO. Memorize the numbers.

THE INSIGHT — V4 architecture in one screen

What changed from V3 to V4

  • Attention: V3 used MLA (Multi-head Latent Attention). V4 replaces it with an alternating stack of CSA (Compressed Sparse Attention) and HCA (Heavily Compressed Attention), interleaved with sliding-window local heads. KV-cache footprint drops $\sim 8\times$ vs MLA at 1M context.
  • Residual stream: mHC (Manifold-Constrained Hyper-Connections). Four parallel residual streams instead of one; mixing matrices are doubly stochastic.
  • MoE balancing: auxiliary-loss-free per-expert bias (no interference gradient).
  • Optimizer: Muon (Newton-Schulz orthogonalized momentum) — first frontier-scale production use.
  • Precision: MoE weights in MXFP4 (QAT, FP32 master); rest of model in FP8; KV cache FP8 with RoPE in BF16; Lightning Indexer QK in FP4.
  • Tool-use: new |DSML| special token and XML schema; reasoning preserved across tool boundaries, discarded across non-tool turns.
  • Post-training: independent cultivation of capability-specific experts $\to$ consolidation via on-policy distillation $\to$ GRPO with verifiable rewards.

Compressed Sparse Attention (CSA)

Two-stage approximation of full attention designed for long context. Let $L$ be sequence length and $m = 4$ the stage-A compression factor.

Stage A — softmax-gated pooling. Group tokens into blocks of $m$. For each block $b$ produce a compressed key/value $\tilde k_b, \tilde v_b$ via a gated pool:

$$g_{b,j} = \frac{\exp(w^\top k_{b,j})}{\sum_{j'=1}^{m} \exp(w^\top k_{b,j'})}, \quad \tilde k_b = \sum_{j=1}^m g_{b,j} k_{b,j}, \quad \tilde v_b = \sum_{j=1}^m g_{b,j} v_{b,j}.$$

This reduces the KV sequence from $L$ to $L/m$ entries.

Stage B — Lightning Indexer top-$k$. A separate small attention head (64 heads $\times$ $d_h = 128$, FP32 scores) computes block-level scores $s_b = \mathrm{softmax}(q^\top \tilde k_b)$ and picks the top-1024 blocks for each query. Final attention is computed only against the selected blocks. Total compute is $O(L \cdot k)$ with $k$ fixed at 1024 regardless of $L$.

Heavily Compressed Attention (HCA)

Same idea but $m' = 128$ — aggressive compression — followed by dense attention over the resulting short sequence ($L/128$). Used in every other layer so the model retains a global-mixing pathway at near-zero cost.

Manifold-Constrained Hyper-Connections (mHC)

Generalizes residual connections to multiple parallel streams. Let $X_l \in \mathbb{R}^{n \times d \times s}$ stack $s = 4$ residual streams at layer $l$. The update rule is:

$$X_{l+1} = B_l\, X_l \; + \; C_l\, F_l(A_l\, X_l)$$

where $A_l, B_l, C_l \in \mathbb{R}^{s \times s}$ are mixing matrices and $F_l$ is the block (attention or FFN). The key constraint: $B_l$ is projected onto the Birkhoff polytope of doubly stochastic matrices via 20 iterations of Sinkhorn-Knopp normalization after each step. This keeps the residual streams on a stable manifold, preventing the rank-collapse pathology seen in earlier multi-stream residual variants (e.g., NeuTRENO).

Muon optimizer in production

Muon (Jordan et al. 2024, blog; Liu et al. arXiv 2502.16982) replaces SGD-momentum updates $M_t$ with their orthogonalized versions $\mathrm{Orth}(M_t)$, computed as the polar factor $U V^\top$ of the SVD $M_t = U \Sigma V^\top$. Computed via Newton-Schulz iteration on $X \leftarrow X(3I - X^\top X X^\top)/2$-style polynomials applied to a normalized $M_t$.

V4 uses a hybrid 8+2 Newton-Schulz recipe: 8 iterations with the aggressive coefficient set $(3.4445, -4.7750, 2.0315)$ for rapid convergence, followed by 2 iterations of $(2, -1.5, 0.5)$ for numerical polish near the orthogonal manifold. Applied to all 2D weight matrices (attention projections, FFN, expert weights); embeddings and norms use AdamW. Wall-clock overhead $\sim 5\%$, sample efficiency gain $\sim 1.4\times$ vs AdamW at matched compute.

Mixed-precision recipe

ComponentFormatNotes
MoE expert weights (storage + compute)MXFP4QAT during pretraining; FP32 master kept for optimizer
Dense Linear (attention proj, shared FFN)FP8 E4M3 fwd, E5M2 bwdPer-tile 1×128 act / 128×128 weight scaling
KV cacheFP8RoPE positions kept in BF16 — phase precision matters
Lightning Indexer Q/KFP4Scores still accumulated in FP32 for numerical stability
Embeddings, output head, LayerNormBF16Quality-critical small fraction of FLOPs
Optimizer state (master)FP32Standard

Post-training — cultivation then consolidation

  1. Cultivation. Independently fine-tune capability-specific experts from the same base: math expert, code expert, reasoning expert, multilingual expert, safety expert. Each uses domain-specific SFT + RLVR.
  2. Consolidation. Use on-policy distillation (Ch. 9) to fold all cultivated experts into a single student — student samples trajectories, the relevant expert provides per-token reverse-KL targets. The student inherits each expert's strengths without their idiosyncrasies.
  3. Final GRPO with verifiable rewards on a mixed math/code/IF prompt distribution. Mixed preference rewards for safety and helpfulness.
  4. Tool-call token: |DSML| wraps an XML schema. Reasoning traces are preserved across tool boundaries (the model sees its prior CoT after a tool call) but discarded across non-tool conversational turns — prevents context bloat.

V4-Pro benchmark line

BenchmarkV4-Pro
MMLU-Pro87.5
GPQA Diamond90.1
LiveCodeBench93.5
Codeforces (Elo)3206
SWE-Bench Verified80.6

R1-Zero / R1 — the predecessor (for context)

DeepSeek R1 (Jan 2025, arXiv 2501.12948) showed that pure RL with verifiable rewards on a strong base elicits reasoning — no SFT required (R1-Zero). The full R1 wrapped that with cold-start SFT, rejection-sampled SFT, and a final mixed-reward RL. Distilled smaller models (Qwen-7B/14B/32B, Llama-8B/70B) inherited reasoning cheaply. V4 supersedes R1 but the R1 4-stage pipeline is still the right "first pass" mental model.

REMEMBER
  • V4-Pro: 1.6T total / 49B active MoE, 32T+ tokens, 1M context.
  • CSA = stage-A softmax-gated pool ($m=4$) + stage-B Lightning Indexer top-1024 blocks.
  • HCA = aggressive pool ($m'=128$) then dense over the short sequence.
  • mHC = 4 parallel streams, $B_l$ on Birkhoff polytope via Sinkhorn-Knopp.
  • Muon: hybrid 8+2 Newton-Schulz, coefficients (3.4445, -4.7750, 2.0315) then (2, -1.5, 0.5).
  • Post-training: cultivation $\to$ on-policy distill consolidation $\to$ GRPO.
08
CASE STUDY · INTERACTION MODELS

Thinking Machines Interaction Models — encoder-free real-time multimodal

TL;DR

Released today (May 11, 2026). TML-Interaction-Small: 276B-A12B MoE (12B active). End-to-end audio+video+text in $\leq 200\,\mathrm{ms}$ time-aligned micro-turns. Encoder-free early fusion — all modalities co-trained from scratch through the same transformer trunk. Audio embedded via dMel; video as 40×40 patches through an hMLP (Touvron 2022) stem; audio decoded via a flow head (Lipman 2022). Paired with a separate Background Model for async deliberation and tool-use that shares the conversational context. FD-bench turn-taking $\leq 0.4\,\mathrm{s}$ — beats Gemini-3.1-flash-live (0.57 s) and GPT-realtime-2.0 (1.18 s). [blog]

What "interaction model" means

A traditional chatbot is a sequence model over discrete turns. An interaction model is a sequence model over continuous time-aligned micro-turns: the model emits and consumes audio/video/text in lockstep at $\sim 5\,\mathrm{Hz}$ frame rate, so latency is a property of tokens-per-second rather than of full responses. The interlocutor and the model share a single rolling timeline.

Encoder-free early fusion

Older multimodal models bolt on per-modality encoders (Whisper-style for audio, ViT for vision) and pretrained adapters. Interaction Models skip this: every modality is converted to a sequence of embeddings in the same vocabulary space and co-trained from scratch:

Co-training from scratch is the central bet: late fusion preserves modality boundaries; early fusion lets the trunk learn cross-modal correspondences directly. The cost is data-mix careful — the team reports needing $\sim 8\%$ pure-text "anchor" data to avoid text-quality regression.

The Background Model

The interaction trunk has to emit at frame-rate, so it can't think for 30 seconds about a tool call. Instead, a separate Background Model shares the same context window and runs async — when the interaction trunk emits a "delegation" token, the background model is woken with the live context, deliberates (potentially with tools), and returns a summary that the interaction trunk consumes when ready. This decouples real-time turn-taking from arbitrary deliberation depth.

FD-bench latency

FD-bench (Full-Duplex bench) measures the time from end-of-user-speech to start-of-model-speech under realistic acoustic conditions. TML-Interaction-Small: $\leq 0.4\,\mathrm{s}$. Gemini-3.1-flash-live: $0.57\,\mathrm{s}$. GPT-realtime-2.0: $1.18\,\mathrm{s}$. The win comes from (1) encoder-free token stream (no Whisper encode latency), (2) MoE-A12B small active footprint, (3) speculative streaming of mel frames into the flow head.

REMEMBER
  • Interaction = continuous time-aligned micro-turns; latency is a per-token property.
  • Encoder-free early fusion, co-trained from scratch.
  • dMel in, hMLP patches in, flow head out.
  • Background Model for async deliberation / tools, sharing the live context.
09
POST-TRAINING · DISTILLATION

On-policy distillation — replacing the search phase of RL

TL;DR

Thinking Machines (Oct 27, 2025) showed that on-policy distillation — student samples trajectories, teacher provides per-token reverse-KL signal — matches RL accuracy on AIME'24 at $9\text{–}30\times$ less compute. Reverse KL is mode-seeking, so the student can't "hack" it the way it hacks a learned RM. This now replaces the costly search phase of RL in the 2026 canonical pipeline. [blog]

The four flavors of distillation

MethodLossTrajectory source
Hinton soft-label$\mathrm{KL}(p_T \| p_S)$ at temperature $T$Teacher rollouts
Hard-label (SFT-on-teacher)NLL on teacher's argmaxTeacher rollouts
Off-policy KDForward KL, teacher trajectoriesTeacher
On-policy distillation$\mathrm{KL}(\pi_\theta \| \pi_{\text{teacher}})$ (reverse KL)Student

Why reverse KL is "unhackable"

The student loss is:

$$\mathcal{L}_{\text{OPD}}(\theta) = \mathbb{E}_{x \sim \mathcal{D},\, y \sim \pi_\theta(\cdot \mid x)} \big[ \mathrm{KL}\big( \pi_\theta(\cdot \mid x, y_{

Reverse KL $\mathrm{KL}(\pi_\theta \| \pi_{\text{teacher}}) = \sum_y \pi_\theta(y) \log \tfrac{\pi_\theta(y)}{\pi_{\text{teacher}}(y)}$ is mode-seeking: it strongly penalizes any $y$ where $\pi_\theta(y) > 0$ but $\pi_{\text{teacher}}(y) \approx 0$. The student cannot create probability mass on "off-distribution" outputs without being immediately punished — there's no Goodhart gap to exploit, unlike a learned RM where mass on a never-seen response is unconstrained.

Forward KL $\mathrm{KL}(\pi_{\text{teacher}} \| \pi_\theta)$ is mean-seeking — the student spreads mass to cover all teacher modes. Mean-seeking is what classical soft-label distillation does, and it tolerates the student putting mass anywhere as long as it also covers the teacher's modes. Reverse KL forbids this.

Compute numbers

Where it sits in the pipeline

The IBM mid-training study (Ch. 2) places on-policy distillation between SFT and final GRPO. The DeepSeek V4 consolidation step (Ch. 7) is on-policy distillation from multiple capability-specific teachers into one student. Anthropic's "guided RL" methodology in recent Claudes is reported to use a related technique.

REMEMBER
  • Loss: reverse KL $\mathrm{KL}(\pi_\theta \| \pi_{\text{teacher}})$, evaluated on student rollouts.
  • Mode-seeking $\Rightarrow$ unhackable. No Goodhart gap.
  • 9–30× compute reduction vs GRPO to match AIME accuracy.
  • Replaces the costly search phase of RL in the 2026 canonical pipeline.
10
POST-TRAINING · PEFT

LoRA without regret — when adapters match FullFT

TL;DR

Thinking Machines (Sep 29, 2025) gave the cleanest answer yet to "when can LoRA replace full fine-tuning?". Two conditions: (a) apply LoRA to all linear layers including MLP/MoE, and (b) trainable parameters must exceed task information content (~1 bit/token for SFT; $\leq \log B$ bits/episode for RL with group size $B$). Optimal LoRA LR $\approx 10\times$ FullFT LR, approximately rank-independent. LoRA FLOPs $\approx \tfrac{2}{3}$ FullFT. For policy gradients, LoRA matches FullFT even at rank 1. [blog]

The update rule

For a weight $W \in \mathbb{R}^{d \times k}$, LoRA (Hu 2021, arXiv 2106.09685) factorizes the update as a rank-$r$ product:

$$W' = W + \frac{\alpha}{r} B A, \quad A \in \mathbb{R}^{r \times k},\; B \in \mathbb{R}^{d \times r},\; r \ll \min(d, k).$$

Only $A, B$ are trained. The $\alpha/r$ scaling decouples learning rate from rank — increasing $r$ doesn't require re-tuning the LR (this is the "LoRA+" / scaling-stable parameterization).

The two preconditions

  1. All layers. Apply LoRA to every linear: attention $W_Q, W_K, W_V, W_O$, FFN gate/up/down, MoE expert weights, embeddings if you can afford it. Attention-only LoRA leaves $\sim 70\%$ of parameters frozen and silently underfits.
  2. Capacity floor. Trainable parameters must exceed task information content:
    • SFT: $\sim 1$ bit per response token. A 10M-token SFT set needs $\sim 10\,\mathrm{Mbits}$ of trainable params $\to$ $\sim 1.25\,\mathrm{M}$ params $\to$ $r \approx 4\text{–}8$ for a 7B model on all layers.
    • RL: $\leq \log B$ bits per episode with group size $B$. Far less. Rank 1 often suffices for policy gradients.

The optimal LR rule

Empirically across model sizes 1B–70B, tasks, and ranks $r \in \{1, \dots, 256\}$, the optimal LoRA LR sits at $\approx 10\times$ the optimal FullFT LR and is nearly rank-independent when the $\alpha/r$ scaling is used. This contradicts the early-2024 folklore that low-rank LoRA needs higher LR than high-rank LoRA.

Compute and quality

REMEMBER
  • All linears, including MLP/MoE. Attention-only LoRA underfits.
  • Trainable params $\geq$ task information content ($\sim 1$ bit/token SFT; $\leq \log B$ bits/episode RL).
  • Optimal LoRA LR $\approx 10\times$ FullFT LR, rank-independent.
  • Rank 1 suffices for policy gradients.
11
SYSTEMS · SUB-FP8 PRECISION

Sub-FP8 pretraining — NVFP4, Quartet, Four-Over-Six, MXFP4

TL;DR

FP8 (E4M3 / E5M2) was 2024. FP4 pretraining is now production-real. Quartet (arXiv 2505.14669) showed BF16-parity FP4 forward on Blackwell. NVFP4 pretraining (arXiv 2509.25149) scaled a 12B hybrid Mamba-Transformer to 10T tokens in NVFP4. Quartet II (arXiv 2601.22813) introduces MS-EDEN, an unbiased quantization scheme with $>2\times$ lower error than stochastic rounding. Four-Over-Six (arXiv 2512.02010) adaptively uses higher precision on high-dynamic-range blocks. The five required techniques: random Hadamard transforms, 2D block scaling, stochastic rounding (or MS-EDEN), BF16 switch during LR decay, higher precision on numerically sensitive layers.

QAT — train through the quantizer

Insert fake quantization (round-to-low-precision then back) in the forward pass; use the straight-through estimator on the backward — gradient passes through rounding as identity. Train so the model is robust to quantization errors at inference. Used to ship INT4 / NVFP4 inference checkpoints. The forward quantizer at element $x$ with scale $s$:

$$\tilde x = s \cdot Q\!\left(\frac{x}{s}\right), \quad \frac{\partial \tilde x}{\partial x} \approx 1 \;\;(\text{STE}).$$

FP8 training recap (still the workhorse for most labs)

DeepSeek V3's reference recipe (arXiv 2412.19437): per-tile scaling (1×128 activations / 128×128 weights), online scale computation, FP32 accumulation promotion every 128 elements, BF16 fallback for embeddings/output/norms.

MXFP4 / NVFP4 — the FP4 era

OCP Microscaling 2024 standard: block of 32 elements share a single 8-bit (E8M0) power-of-2 scale. MXFP8, MXFP6, MXFP4 are the formats. NVIDIA's NVFP4 variant uses an FP8 (E4M3) per-block scale plus an FP32 per-tensor scale — strictly higher accuracy than MXFP4 for similar memory.

THE INSIGHT — what makes FP4 pretraining work

Five techniques you must combine

  1. Random Hadamard transforms. Multiply activations and weights by a random Hadamard matrix $H$ before quantization; multiply back afterwards. $H$ has $\pm 1$ entries and is its own inverse (up to scale). It rotates outliers into the bulk, dramatically reducing per-block dynamic range. (Tseng 2024, QuaRot.)
  2. 2D block scaling. Apply consistent block geometry in forward and backward — backward computes $\partial L / \partial W$ which has different block alignment than $W$ itself. Inconsistent geometry breaks the chain rule numerics.
  3. Stochastic rounding for unbiased gradients: $Q(x) = \lfloor x \rfloor + \mathrm{Bernoulli}(x - \lfloor x \rfloor)$. Deterministic round-to-nearest biases gradients toward zero in expectation; stochastic rounding has $\mathbb{E}[Q(x)] = x$. Quartet II's MS-EDEN scheme reduces variance $>2\times$ further.
  4. BF16 switch during LR decay. The residual loss gap between FP4 and BF16 pretraining is consistently $\sim 0.5\%$ on validation. Switching to BF16 for the final 10–15% of tokens (the LR decay phase) closes it. NVIDIA's arXiv 2509.25149 first reported this; now standard.
  5. Higher precision on sensitive layers. Embeddings, output head, all LayerNorm/RMSNorm stay BF16. Lightning-Indexer-style scoring heads can use FP4 for $QK$ but FP32 for the score accumulation. RoPE phases must stay BF16.

Quartet, Quartet II, Four-Over-Six

REMEMBER
  • FP8: E4M3 fwd/weights, E5M2 grads, FP32 master, per-tile scaling.
  • FP4 pretraining requires Hadamard rotations + 2D block scaling + stochastic rounding + BF16 switch in decay + sensitive-layer escalation.
  • NVFP4 = FP8 per-block scale + FP32 per-tensor scale (more accurate than MXFP4).
  • MS-EDEN (Quartet II) beats stochastic rounding $>2\times$ on variance.
12
SYSTEMS · DISTRIBUTED

Decoupled DiLoCo — frontier-scale training across the WAN

TL;DR

Google DeepMind's Decoupled DiLoCo (arXiv 2604.21428, April 23, 2026) ran a 12B model across 4 US regions on 2–5 Gbps WAN links — 20× faster than synchronous baselines with 88% goodput under realistic failure rates. The CPU-side parameter-fragment synchronizer with minimum-quorum + adaptive grace window kills the assumption that SPMD over fast NVLink/IB is the only viable paradigm for frontier-scale runs.

DiLoCo recap

DiLoCo (Douillard 2023, arXiv 2311.08105) is "local SGD" for LLMs. Each worker (a full datacenter) runs $H$ inner steps with AdamW on local data, then performs an outer step where the workers' parameter deltas are averaged. The outer step uses an outer optimizer (typically Nesterov momentum). Communication frequency drops from once-per-step to once-per-$H$-steps — orders of magnitude less bandwidth.

$$\theta^{(t+1)} = \theta^{(t)} - \eta_{\text{outer}} \cdot \mathrm{Outer}\!\left( \frac{1}{K} \sum_{k=1}^K \big( \theta_k^{(t,H)} - \theta^{(t)} \big) \right)$$

What "decoupled" adds

Headline numbers

12B model, 4 US regions (us-east-1, us-east-4, us-west-1, us-central-1), 2–5 Gbps inter-region links, $H = 500$, $K = 4$ workers each $\sim$2048 H200 GPUs. Result: $20\times$ wall-clock speedup vs synchronous baseline at the same total compute, and 88% goodput with simulated link failures injected at typical cloud-provider rates.

The strategic implication: training a frontier-scale model no longer requires a single $100\,\mathrm{k}$-GPU datacenter with InfiniBand. You can stitch four 25k-GPU regions together over the public internet — a fundamentally different supply-chain story.

REMEMBER
  • DiLoCo = local SGD with $H$ inner steps + outer Nesterov.
  • Decoupled DiLoCo = async workers + CPU-side fragment synchronizer + minimum-quorum + adaptive grace.
  • 20× wall-clock speedup vs sync; 88% goodput across 4 US regions on 2–5 Gbps WAN.
  • SPMD-on-IB is no longer the only frontier-scale paradigm.
13
SYSTEMS · HP TUNING

µ-transfer at frontier scale — u-µP and GQA-µP

TL;DR

µP (Yang 2022, arXiv 2203.03466) made the LR transfer across width: tune HPs on a small proxy, scale to frontier. u-µP (ICLR 2026) combines µP with unit-scaling so HPs also transfer across precision — BF16 / FP8 / NVFP4. GQA-µP (ICLR 2026) extends µP to Grouped Query Attention and FSDP sharding so the rules survive the actual frontier-training stack. Anthropic and DeepSeek now use this in production; Llama 3 was the last frontier release without it.

µP in one sentence

Under the maximal-update parameterization, the optimal learning rate for each layer scales as $\eta_l \propto 1/\mathrm{fan\_in}_l$, and the same nominal $\eta$ produces feature updates of $\Theta(1)$ at every width. Tune $\eta$ at width $d = 256$, deploy at $d = 16384$, no re-tune. Without µP, optimal LR depends nontrivially on width and you re-tune at every scale (Llama 3's HP sweep cost ~5% of total training FLOPs).

u-µP — across precision

µP transfers across width but not across precision. u-µP composes µP with unit-scaling (Blake 2023, arXiv 2303.11257), which constrains every tensor's pre-quantization variance to $1$. Result: HPs tuned in BF16 on a proxy transfer to FP8 / NVFP4 at frontier scale. Critical when you can't afford an FP8 HP sweep.

GQA-µP — surviving the stack

The original µP derivation assumes vanilla multi-head attention and no parameter sharding. GQA breaks the fan-in counting (KV heads are shared); FSDP shards the parameters and changes the effective initialization geometry. GQA-µP rederives the scaling rules for the actual layer stack used at the frontier and validates HP transfer across $d_{\text{model}} \in [256, 16384]$ and across 1- to 64-way FSDP.

REMEMBER
  • µP: tune at small width, deploy at large width, no re-tune.
  • u-µP: also transfers across BF16 / FP8 / NVFP4.
  • GQA-µP: rederives the scaling rules for GQA + FSDP — the actual frontier stack.
  • Production use at Anthropic, DeepSeek; ICLR 2026 venue.
14
SYSTEMS · MoE

MoE balancing & the auxiliary-loss-free trick

TL;DR

The default MoE load-balance auxiliary loss (Shazeer 2017) competes with the language-modeling loss and degrades quality. Auxiliary-loss-free balancing (DeepSeek, arXiv 2408.15664; theory in arXiv 2512.03915) maintains a per-expert bias added to routing logits before top-$K$, updated step-wise based on recent expert load. The bias is not in the loss $\to$ no interference gradient. Used in V3, V4, Kimi, GLM-5, Qwen 3.5 — effectively the new default.

MoE routing in one line

For input $x$, router logits $g(x) = W_g x \in \mathbb{R}^E$, top-$K$ selection produces a sparse gate $G(x) \in \mathbb{R}^E$ with $K$ nonzero entries. Output is $\sum_e G(x)_e \cdot \text{Expert}_e(x)$. Top-$K$ over a uniform initial $W_g$ collapses to a few experts within hundreds of steps without a balancing mechanism.

The old way — auxiliary loss

Shazeer's original load-balance loss (and the importance-loss variant) adds:

$$\mathcal{L}_{\text{aux}} = E \cdot \sum_{e=1}^E f_e \cdot p_e, \quad f_e = \frac{1}{B}\sum_{i} \mathbb{1}[e \in \text{top-}K(x_i)], \quad p_e = \frac{1}{B}\sum_{i} \mathrm{softmax}(g(x_i))_e.$$

This pushes load toward uniform but its gradient flows through $g$ and therefore through $W_g$, in opposition to the LM-loss gradient. Quality degrades as $\beta_{\text{aux}}$ grows; underdamping leaves load imbalanced.

Auxiliary-loss-free — the new way

Maintain a per-expert bias $b_e$ added to logits only at routing decision time:

$$\hat g(x)_e = g(x)_e + b_e, \quad \text{top-}K(\hat g(x)).$$

After each batch, update:

$$b_e \leftarrow b_e + \gamma \cdot \mathrm{sign}\big( \bar f - f_e \big)$$

where $\bar f$ is the target average load (typically $K/E$) and $\gamma$ is a small step size (e.g., $10^{-3}$). The bias is not a parameter that receives backprop gradient — it's updated like an EMA of utilization. Result: no interference with the LM loss, well-balanced load, no quality regression.

Theory: Wang & Sun (arXiv 2512.03915) show this is a stochastic-approximation algorithm targeting balanced utilization, and prove convergence under mild conditions on the routing-logit distribution.

REMEMBER
  • Aux-loss balancing interferes with the LM gradient.
  • Aux-loss-free: maintain $b_e$, add to logits before top-$K$, update by sign of load error. Not in the loss.
  • Used in V3, V4, Kimi, GLM-5, Qwen 3.5.
15
SYSTEMS · LONG CONTEXT

Long-context extension — YaRN, ring attention, CSA

TL;DR

You don't pretrain on 1M context. You pretrain on 4–32k, then extend with NTK-aware / YaRN, with a continued-training pass. Ring/Striped attention shards sequence across GPUs for the actual long-context training. At 2026 frontier scale, native long-context architectures (V4's CSA/HCA, Gemini's Titan-style memory) increasingly replace post-hoc extension. Then evaluate carefully — RULER and BABILong, not needle-in-haystack.

Position interpolation family

RoPE rotates query/key by angle $\theta_d \cdot m$ at position $m$, dimension $d$, base $\theta_d = b^{-2d/D}$ with $b = 10000$ (typical). To extend from $L_{\text{train}}$ to $L_{\text{target}}$:

Ring & striped attention — sequence-parallel for the actual training

Native long-context architectures

V4's CSA + HCA (Ch. 7), Gemini's Titans/Mneme-style memory layers, and Mamba/SSM hybrids all attack the same problem from the architecture side: keep effective attention cost sub-quadratic so 1M+ is a first-class regime, not a stretch goal. The trade-off is exact-retrieval fidelity (full attention) vs scaling (compressed/sparse). 2026 frontier models accept the trade-off; the loss on needle-style retrieval is tolerable given the latency win.

Long-context evaluation

Standard suite: needle-in-haystack (planted fact — necessary but not sufficient), RULER (Hsieh 2024, multi-needle + multi-hop), LongBench v2, BABILong, multi-doc QA, InfiniteBench.

PITFALL — needle-passing ≠ long-context reasoning
A model that gets needle-in-haystack 100% can still fail at multi-hop reasoning over long context. Single-needle retrieval is the easiest possible long-context task. Always evaluate with RULER or BABILong as well, and probe with multi-doc reasoning. 2026 reality check: most 1M-context advertised numbers are NIAH-tuned; RULER scores drop 30–50 points.

Curriculum / rejection sampling / best-of-N (bonus toolkit)

REMEMBER
  • Pretrain short, extend with YaRN (or NTK-aware), continue-train briefly.
  • Ring + Striped attention + FlashAttention enables 1M+ token training.
  • 2026 frontier: native long-context (CSA/HCA, Titans) replacing post-hoc extension.
  • Needle-in-haystack is necessary but not sufficient — evaluate RULER / BABILong.

0 → hero reading path for LLM training + RLHF

  1. foundation OpenAI Spinning Up — RL primer; the Vanilla PG and PPO chapters are crucial
  2. foundation Chip Huyen — RLHF: Reinforcement Learning from Human Feedback
  3. foundation Hugging Face — Illustrating RLHF
  4. build TRL library — try DPO / PPO on a small model
  5. build GPT-NeoX or Megatron-LM — read pretraining infra code
  6. depth InstructGPT (Ouyang 2022)
  7. depth Christiano 2017 — Deep RLHF (the original)
  8. depth DPO (Rafailov 2023)
  9. depth DeepSeek Math / GRPO
  10. depth DeepSeek R1 paper — read end-to-end
  11. depth Constitutional AI (Bai 2022)
  12. depth Llama 3 paper
  13. depth DeepSeek V3 technical report
  14. depth Tülu 3 — open SFT/DPO recipe
  15. depth Nathan Lambert's Interconnects blog — RLHF / post-training news

LLM training quiz — readiness check

  1. Walk through Llama 3's training pipeline.
    Show answer

    15T pretraining tokens with quality classifier on web; MinHash dedup; phased annealing in last 40B tokens. Then SFT + rejection sampling + DPO. Architecture: GQA + RoPE + RMSNorm + SwiGLU. Scaling: 8B, 70B, 405B variants. Multimodal added in 3.2.

  2. Why GRPO over PPO?
    Show answer

    No critic/value model → saves ~30–50% of total training memory (depends on value-head sharing); group-relative advantage is well-conditioned for verifiable rewards; simpler to scale. Tradeoff: only sequence-level credit assignment.

  3. How would you train a reasoning model from scratch?
    Show answer

    Strong base → RLVR with GRPO + verifiable rewards (math, code) → SFT on rejection-sampled good traces → final RL with mixed verifiable + preference rewards. Distill into smaller dense models.

  4. How does Constitutional AI differ from RLHF?
    Show answer

    Preferences come from an AI judge applying explicit principles, not humans. SL phase: model self-critiques + revises per principles. RL phase: AI-generated preference pairs train RM, then PPO. Reduces human labeling cost; shifts subjectivity to constitution.

  5. What is mode collapse in DPO?
    Show answer

    DPO can decrease likelihood of both chosen and rejected (only the gap matters); policy may drift far from reference. Mitigations: stronger β, IPO (squared loss), mix in SFT loss, conservative sampling.

  6. Walk through DeepSeek V3's FP8 recipe.
    Show answer

    E4M3 forward + weights, E5M2 backward. Per-tile (1×128 activations / 128×128 weights) scaling. FP32 master weights. FP32 partial-sum promotion every 128 elements. BF16 fallback for embeddings, output head, normalization. ~2× speedup vs BF16 with no quality loss.

  7. Explain Chinchilla and why models today violate it.
    Show answer

    Chinchilla: D ≈ 20·N is compute-optimal during training. But inference cost dominates total cost when serving for years → over-train smaller models past Chinchilla optimum (Llama 3 8B on 15T tokens = 1875 tokens/param) for cheaper per-query inference.

  8. What's the closed-form derivation of DPO?
    Show answer

    Start from KL-constrained RL: max E[r] − β KL(π||π_ref). Closed-form optimum: π* = (1/Z) π_ref · exp(r/β). Solve for r: r = β log(π*/π_ref) + β log Z. Plug into Bradley-Terry preference; Z(x) cancels. Result: DPO loss equals NLL of preferences under the implicit reward model induced by the policy.

  9. What's RFT (rejection sampling fine-tuning)?
    Show answer

    Sample many completions per prompt; keep only correct (verified or RM-scored); SFT on those. Llama 3 RLHF used this. Cheaper than RL; often nearly as good. Used as a stage in DeepSeek R1's pipeline.

  10. What is RLVR and what's its main advantage over RLHF?
    Show answer

    RL with verifiable rewards: programmatic verifier (unit tests, math grader, formal proof checker) instead of learned RM. No reward hacking on the verifier signal. Drives reasoning-model training (o-series, R1, Tülu 3).

  11. Walk through DeepSeek R1's pipeline (4 stages).
    Show answer

    (1) Cold-start SFT: small set of curated reasoning traces with desired format. (2) RL with GRPO + verifiable rewards. (3) Rejection-sampling SFT: 600k math/code from stage-2 + 200k general. (4) Final RL: mixed verifiable + preference rewards. Distill into dense models.

  12. What is MinHash LSH for dedup?
    Show answer

    Compute MinHash signatures over n-gram shingles (5-grams typical). Bucket into LSH bands; candidate pairs share at least one band. Verify with Jaccard. For 5T docs, typically 10 bands × 9 hashes (controls precision/recall). Used by DeepSeek, Llama, FineWeb.

  13. What is SemDeDup?
    Show answer

    Cluster embeddings with k-means; dedup within clusters by cosine similarity. Catches near-duplicates that MinHash misses (paraphrases, translations, reformatting). Used as a complement to MinHash.

  14. Why mid-training before SFT?
    Show answer

    A phase between pretraining and SFT: continue causal LM but heavy upweight on reasoning, math, code, possibly synthetic CoT. Combined with WSD decay phase. Model becomes "reasoning-ready" without yet being instruction-tuned. DeepSeek V3 used this.

  15. What's the LIMA hypothesis?
    Show answer

    (arxiv 2305.11206) "Less is more for alignment" — diversity > scale beyond ~10k–100k SFT examples. The model's capabilities come from pretraining; SFT only teaches format/instruction-following. Recent work (Tülu 3) shows up to 1M+ helps when domains are diverse.

  16. What is REINFORCE and why mention it now?
    Show answer

    Original policy gradient: ∇L = −E[log π(a|s) · A]. PPO adds clipping + value baseline. RLOO / REINFORCE++ (Ahmadian 2024) skip the critic (like GRPO) but use leave-one-out or EMA baselines. Coming back into fashion for LLM RL.

  17. What is KTO?
    Show answer

    Kahneman-Tversky Optimization (Ethayarajh 2024). Doesn't require pairwise data — only binary "good"/"bad" labels per response. Models prospect-theoretic utility. Easier data collection.

  18. What's catastrophic forgetting and how do you mitigate?
    Show answer

    Continued training on new data degrades performance on old data. Mitigations: (1) replay (mix old data, 5-30%); (2) much lower LR; (3) PEFT (LoRA — train only adapters); (4) elastic weight consolidation; (5) regularize toward original weights.

  19. What's the difference between in-context learning and fine-tuning?
    Show answer

    ICL: no weight updates; few-shot examples in prompt steer behavior. Fast, no infra, but limited context, no persistence. Fine-tuning: weight updates persist; better quality on narrow domain; risks catastrophic forgetting; needs infra. 2026 guidance: try prompt → RAG → SFT/LoRA → full FT → RL in order.

  20. What's reward hacking in reasoning models?
    Show answer

    Model gaming the reward signal: tampered CoT (correct answer with non-causal reasoning); verifier exploitation (matches the regex but reasoning is wrong); length hacking. Mitigations: process rewards (PRM), multiple verifiers, behavioral evals catching CoT-answer mismatch.