LLMLLM trainingpretrainingRLHF

Training LLMs: Pre-Training, SFT, RLHF & DPO Explained (2026 Guide)

Full LLM training pipeline revealed: data curation at trillion-token scale, tokenization, pre-training next-token loss, supervised fine-tuning (SFT), RLHF with reward models and PPO/DPO.

ToolsLead TeamSeptember 8, 202616 min read
Share:
Updated Sep 8, 2026

Training a frontier LLM is the most expensive self-supervised task in history: 15 trillion tokens, 1026 FLOPs, 16,000 H100 GPUs running for weeks, and 100,000 human preference judgments — all to make next-token prediction helpful and safe.

⚡ TL;DR Pipeline

  1. Data: Crawl → filter → deduplicate → mix 15T tokens.
  2. Pre-train: Next-token cross-entropy, 80–90% of compute, base model that completes text.
  3. SFT: 100K instruction → response pairs teach “follow instructions”.
  4. RLHF/DPO: Ranked preferences → reward model → PPO/DPO steers tone, safety, helpfulness.

The 4-Stage Training Pipeline

StageObjectiveDataComputeOutput
0. DataCurate high-quality mixtureCommon Crawl + Code + Books + SyntheticCPU + filters15T clean tokens
1. Pre-trainMinimize -log P(next token)Unlabeled text (self-supervised)~90%Base model (e.g., Llama-3-Base)
2. SFTMinimize loss on human-written ideal responses50K–500K instructions~5%Instruction model (chatty but not robust)
3. RLHF/DPOMaximize learned human preference reward50K–200K preference pairs~5%Aligned chat model (GPT-4o, Claude 3.5)

Stage 0: Data — The Real Moat

“Data is the model.” In 2026, teams spend as much engineering on data as on architecture.

Sources & mixture (Llama 3–ish)

  • 50% Common Crawl: Raw web filtered by language ID (fastText), toxicity classifier, heuristic filters (remove boilerplate, too-short docs, lorem ipsum, excessive repetition).
  • 15% Code: GitHub, StackExchange — teaches logic, structure, tool use. Dedup by repository, filter by permissive licenses.
  • 10% Books & Papers: High-quality long-form, narrative coherence.
  • 5% Wikipedia & curated: Factual recall.
  • 10% Math & STEM: arXiv, synthetic proofs.
  • 10% Multilingual: Hindi, Spanish, Chinese etc. — but token fertility high, so sampling carefully balanced.
  • Synthetic (2025+): Model-generated reasoning traces (“Let’s think step by step…”) filtered by reward model and verified by Python execution. Adds 5–15% of tokens, boosts GSM8K/MATH by 5–10 points.

Quality filters

  • Deduplication: MinHash (document-level) + exact substring match (paragraph). Prevents copying Wikipedia verbatim and stops test-set leakage.
  • PII scrubbing: Regex + classifier removes SSNs, API keys, emails (reduces regurgitation risk).
  • Toxicity: Perspective-style classifier downweights hate, but not too aggressively — otherwise model becomes prudish. Balance via mixing.
  • Decontamination: Remove any paragraph that appears in MMLU/GSM8K/benchmarks to avoid cheating.

Final corpus: 15T tokens after filtering. Original raw crawl was ~100T tokens — 85% discarded. Quality beats quantity.

Tokenization & Batching

After data, train tokenizer (BPE) on sample of corpus → 128K vocab (GPT-4o), 32K (Llama 2), 256K (Gemma). Then:

  1. Pack sequences: Concatenate documents with EOS token, cut into fixed 4K/8K blocks for training (no padding waste).
  2. Shuffle globally: Pseudo-random but reproducible seed.
  3. Batch: 4M tokens per step (e.g., 512 seq × 8192 length) — large batch stabilizes Adam.

Stage 1: Pre-Training (Next-Token Loss)

This consumes 90% of budget.

Objective formalized

Given tokens x1…xT, model outputs P(x_{t+1} | x1…xt; θ).

Loss L(θ) = -1/T Σ log P(x_{t+1} | context).

Optimizer: AdamW (β1=0.9, β2=0.95, weight decay 0.1), cosine LR schedule (warmup 2K steps → peak 3e-4 → decay to 10% over 1T tokens).

Precision: BF16 mixed + FP8 matmul (H100), gradient clipping 1.0.

Perplexity = exp(loss). Lower = better. During run, 3.5 → 2.0. But practitioners eval weekly on MMLU, GSM8K, HumanEval, not just perplexity.

Infrastructure

  • Hardware: 16K H100s (each 989 TFLOPs) on InfiniBand. MFU (Model FLOPs Utilization) 40–55% after optimizing kernels (FlashAttention, comm overlap).
  • Parallelism: Data Parallel + Tensor Parallel (split attention heads) + Pipeline Parallel (split layers across nodes) + Sequence Parallel for 128K context.
  • Checkpointing: Save every 1K steps → 30TB of weights/history.
  • Failure handling: With 16K GPUs, mean time between failures is hours — jobs restart from last checkpoint automatically. Lost compute is budgeted.

When to stop

Chinchilla-optimal says stop at ~20 tokens/param. But teams now overtrain: Llama 3 70B saw 15T tokens (214 tokens/param!) because inference cost dominates — a better 70B saves billions in serving vs training a bit longer.

Stage 2: Supervised Fine-Tuning (SFT) — Instruction Tuning

Base model can complete “User: Explain photosynthesis” with “User: Explain …” repeated — it’s a text completer, not an assistant.

SFT fixes it:

  • Dataset: 50K–500K human-written (or high-quality synthetic) pairs: {instruction: “Summarize this PDF in 3 bullets”, response: “- …”}. Often curated from StackExchange, Alpaca, ShareGPT, plus internal annotation teams ($2–5 per example).
  • Training: Fine-tune full model (or LoRA for smaller runs) with cross-entropy only on response tokens (mask prompt). LR 1e-5, 1–3 epochs. Early stopping to avoid overfitting SFT style.
  • Effect: Model learns format, tone, to follow instruction rather than continue. SFT alone makes it chatty but still brittle — easy to jailbreak, verbose, not well-calibrated.

2026 recipe: SFT on high-quality, diverse, maximal-detail examples beats 1M mediocre examples. LIMA (NeurIPS 2023) showed 1,000 excellent examples can align well.

Stage 3: RLHF — Reward Model + PPO

RLHF aligns nuance: helpfulness, harmlessness, honesty, style consistency.

  1. Collect preferences: For each prompt (e.g., “Write a Python quicksort”), sample 2–4 SFT outputs, have human label ranking (1st best, 2nd, …) — with criteria and handling ties. Need 50K–200K pairs. Costly: trained annotators, not crowdworkers, for safety tasks.
  2. Train Reward Model (RM): Take SFT model, replace final head with scalar reward. Train with loss = -log σ(r_winner - r_loser). RM learns to predict human preference. Need help from 6B–13B RM for efficiency; freeze most of LLM, train head.
  3. PPO (Proximal Policy Optimization):
    • Sample prompt → generate response with current policy.
    • Score with RM → reward.
    • Compute KL penalty: reward_final = r_RM - β·KL(policy || SFT) — prevents drift into reward hacking gibberish.
    • Update policy with clipped objective.

Also add rule-based rewards: Python unit tests for code, regex for format (“output must be JSON”), safety classifier score — reduces reliance on pure RM.

Instability is notorious: KL tuning, value network initialization, reward hacking (model learns to repeat flattery to get high reward). Teams log reward, KL, entropy, win-rate daily.

⚠️ Reward Hacking Example

If preference data favors long answers, RM rewards verbosity. PPO then learns to output 500-word answers for “2+2?” — high reward, useless. Fix: include length penalty, or balance preference pairs by length, or use DPO which is less prone.

DPO & Modern Alternatives

DPO (Rafailov 2023) recasts RLHF as classification: directly optimize log σ( β log π_winner/π_ref - β log π_loser/π_ref). No RM, no PPO loop, stable offline training. Result similar to RLHF for most tasks.

MethodNeeds RM?Online?StabilityWhen used 2026
PPO-RLHFYesYes (sample during train)Low — needs tuningFinal frontier polish (OpenAI, Anthropic)
DPONo (implicit)No (static pairs)HighMost open-source (Llama, Mistral) — default
KTO / IPO / RLOONoVariesMediumAlternatives handling noisy prefs
Constitutional AI (RLAIF)AI feedbackBothMediumSafety: AI critiques AI outputs

2026 SOTA stacks often: SFT → DPO → iterative DPO (generate new pairs from DPO model, re-rank with RM) → tiny PPO final.

Compute, Hardware & Cost

ModelParamsTokensGPUs & TimeEst. Cost
Llama 3 8B8B15T1K H100 × 30 days$5M
Llama 3 70B70B15T16K H100 × 39 days$35M
DeepSeek-V3 671B MoE671B (37B active)14.8T2K H800 × 60 days$6M (MoE efficiency)
GPT-4 class~1.8T MoE13T25K H100 × months$100M+

Inference cost reminder: Serving 1B queries at 500 tokens each = 0.5T tokens. At $5/1M tokens, that’s $2.5M revenue but ~$1M GPU cost. Training cost is one-time; serving cost compounds, which is why quantization, MoE and speculative decoding (Part 4) matter.

Alignment Challenges & Evals

  • Helpful vs Harmless: “How to make a bomb?” → must refuse harmfully but allow “How does chemistry of explosives work for my novel?” — fine line, many false refusals if over-tuned.
  • Sycophancy: RM trained on humans who prefer agreeable answers → model flatters. Fix: disagreement-aware labeling.
  • Evaluation: Benchmarks (MMLU, GSM8K, HumanEval, MATH, IFEval) + red-teaming + human win-rate vs previous version. Before any RLHF release, 1K+ adversarial prompts probe jailbreaks.
  • Continual alignment: User feedback (thumbs up/down in Chat with PDF) creates fresh preference pairs for iterative DPO.

Build on aligned LLMs — not raw base models

ToolsLead wraps aligned chat models (GPT-4o-mini, Claude) with retrieval and safety filters — you get helpfulness without training from scratch.

FAQs

Try these free tools mentioned in this article:

Frequently Asked Questions

What data are LLMs trained on?

Pre-training mixes Common Crawl (filtered 50-60%), code (GitHub, Stack), books, arXiv, Wikipedia, plus licensed data. Teams deduplicate globally, filter toxicity/PII with classifiers, and upsample high-quality sources (books, code) 2-3x. Llama 3 used 15T tokens; 2026 frontier uses 20T+ with synthetic reasoning traces filtered by reward models.

Open AI PDF Summarizer

What is RLHF and why is it needed?

Pre-trained base models just continue text. RLHF (Reinforcement Learning from Human Feedback) teaches them to follow instructions, be helpful, harmless and honest. Humans rank outputs, a reward model learns those preferences, then PPO reinforcement learning optimizes the LLM to maximize reward while staying close to the SFT model via KL penalty.

Open AI PDF Summarizer

PPO vs DPO — difference?

PPO (Proximal Policy Optimization) is online RL: sample from current model, score with reward model, update with clipped gradients — powerful but unstable, needs reward model, value network, careful tuning. DPO (Direct Preference Optimization) rewrites the RL objective to a simple classification loss directly on preference pairs — stable, offline, no reward model at train time. Most 2026 labs use DPO/KTO/IPO variants for simplicity, PPO for final polish.

Open AI PDF Summarizer

How much does training an LLM cost?

Llama 3 70B: estimated $30-50M compute on 16K H100s for ~39 days. GPT-4 class: $100M+. Frontier MoE 400B+ with 15T tokens: $80-200M. Cost is GPU rental + data pipeline + eval + human labeling for RLHF (100K preference pairs at $2-5 each = $200-500K). Inference cost dominates lifetime — serving 10M users costs more than training after months.

Open AI PDF Summarizer

Why do models need alignment?

Raw next-token models are helpful but also generate harmful, biased or power-seeking continuations if prompted. Alignment (SFT + RLHF + Constitutional AI) steers them to refuse harm, cite uncertainty, and follow user intent within safety bounds. Without it, models jailbreak trivially.

Open AI PDF Summarizer

Was this article helpful?

T

About ToolsLead Team

ToolsLead is a privacy-first PDF platform. Most tools run in your browser — your files never leave your device. For heavy tasks we use encrypted, auto-deleted server processing. No signup required for basic tools.

Browse all PDF tools