The Complete Guide to Post-Training of Large Language Models
From Pretraining to Alignment: Everything You Need to Know
Who is this for? You've learned how pretraining works — you understand GPT-2, transformer architectures, next-token prediction, and the cross-entropy loss. Now you want to understand what happens after pretraining: how raw language models become helpful assistants like ChatGPT, Claude, and Gemini. This guide takes you from zero knowledge of post-training to a deep understanding of every major method, with pointers to the key papers, tools, and code.
Chapter 1: The Big Picture — Why Post-Training Exists
1.1 The Gap Between Pretraining and Usefulness
You've pretrained a language model. It can predict the next token with impressive accuracy. It has absorbed vast knowledge from the internet. But try asking it a question:
User: What is the capital of France?
Model: What is the capital of Germany? What is the capital of Italy? What is the...
The model doesn't answer — it continues. That's because the pretraining objective (P(next_token | context)) optimizes for predicting what comes next in web text, not for being helpful. Web documents contain questions followed by more questions, not questions followed by helpful answers.
This is the alignment problem in its simplest form. As the InstructGPT paper (Ouyang et al., 2022) put it:
"Large language models can generate outputs that are untruthful, toxic, or simply not helpful to the user. In other words, these models are not aligned with their users."
1.2 The Three Stages of Post-Training
Post-training is everything that happens after pretraining to make a model useful, safe, and aligned with human intent. The modern post-training pipeline, established by OpenAI's InstructGPT (2022), has three stages:
┌─────────────┐ ┌──────────────────┐ ┌─────────────────────────┐
│ STAGE 1: SFT │ ──> │ STAGE 2: Reward │ ──> │ STAGE 3: RL │
│ │ │ Model Training │ │ (PPO / DPO / GRPO) │
│ Teach format │ │ Learn preferences│ │ Optimize for preferences│
│ & behavior │ │ from comparisons │ │ while staying close to │
│ │ │ │ │ the SFT model │
└─────────────┘ └──────────────────┘ └─────────────────────────┘
Input: Pretrained LM Output: Aligned Assistant
Stage 1 — Supervised Fine-Tuning (SFT): Teach the model the format of helpful responses using human-written demonstrations. Input: instructions. Output: high-quality responses.
Stage 2 — Reward Modeling: Train a separate model to predict which of two responses a human would prefer. This "reward model" captures human preferences as a scalar score.
Stage 3 — Reinforcement Learning: Use the reward model to further improve the SFT model. The model generates responses, gets scored by the reward model, and updates its parameters to produce higher-scoring responses.
Key insight from LIMA (Zhou et al., 2023):"A model's knowledge and capabilities are learnt almost entirely during pretraining, while alignment teaches it which subdistribution of formats should be used when interacting with users." This is called the Superficial Alignment Hypothesis — post-training doesn't teach new knowledge, it teaches the model to surface existing knowledge in the right way.
1.3 The Evolution: From RLHF to Modern Methods
The field has evolved rapidly:
Year
Method
Key Idea
Paper
2017
RLHF (original)
Use human preferences to train reward model, optimize with RL
Christiano et al.
2020
RLHF for LLMs
Apply RLHF to text summarization
Stiennon et al.
2022
InstructGPT
Full SFT → RM → PPO pipeline for general LLMs
Ouyang et al.
2022
Constitutional AI
Use AI feedback instead of human feedback (RLAIF)
Bai et al. (Anthropic)
2023
DPO
Eliminate reward model entirely — train directly on preferences
Rafailov et al.
2024
KTO
Train on binary feedback (good/bad) instead of pairwise
Ethayarajh et al.
2024
ORPO
Combine SFT and preference optimization in one step
Hong et al.
2024
GRPO
Group-based RL for mathematical reasoning (DeepSeek)
Shao et al.
2025
DeepSeek-R1
GRPO to teach models to "think" (chain-of-thought via RL)
SFT is the bridge between a pretrained language model and a useful assistant. It takes a model that predicts web text and teaches it to respond helpfully to instructions.
Before SFT:
Input: "Explain quantum computing in simple terms."
Output: "Explain quantum computing to a 5-year-old. Explain quantum computing..."
After SFT:
Input: "Explain quantum computing in simple terms."
Output: "Quantum computing uses the principles of quantum mechanics to process
information. Unlike classical computers that use bits (0 or 1),
quantum computers use qubits that can be both 0 and 1 simultaneously..."
2.2 The SFT Loss Function
If you understand the pretraining loss, you already understand SFT — with one crucial difference.
Pretraining loss (next-token prediction on everything):
L_pretrain = -Σ log P(token_i | token_1, ..., token_{i-1})
for ALL tokens in the sequence
SFT loss (next-token prediction on the response only):
L_SFT = -Σ log P(c_i | prompt_tokens, c_1, ..., c_{i-1})
for ONLY the completion/response tokens
The prompt tokens are fed into the model but masked from the loss computation. This is important: we don't want the model to learn to generate instructions — we want it to learn to respond to them.
Sequence: [User: What is 2+2?] [Assistant: 4]
Loss mask: [ ----IGNORED---- ] [COMPUTED HERE ]
2.3 Data Formats for SFT
Modern SFT uses chat-formatted data — structured conversations with roles:
python
1# The standard format: a list of messages with roles2{3"messages":[4{"role":"system","content":"You are a helpful assistant."},5{"role":"user","content":"What is the capital of France?"},6{"role":"assistant","content":"The capital of France is Paris."}7]8}
This gets converted to a chat template — a specific text format that the model learns to recognize:
# ChatML format (used by many models):
<|im_start|>system
You are a helpful assistant.<|im_end|>
<|im_start|>user
What is the capital of France?<|im_end|>
<|im_start|>assistant
The capital of France is Paris.<|im_end|>
# Llama-3 format:
<|begin_of_text|><|start_header_id|>system<|end_header_id|>
You are a helpful assistant.<|eot_id|>
<|start_header_id|>user<|end_header_id|>
What is the capital of France?<|eot_id|>
<|start_header_id|>assistant<|end_header_id|>
The capital of France is Paris.<|eot_id|>
Each model family has its own template. The transformers library handles this automatically:
python
1from transformers import AutoTokenizer
23tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-3.1-8B-Instruct")45messages =[6{"role":"user","content":"What is 2+2?"},7{"role":"assistant","content":"4"}8]910# For training (complete conversation):11text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=False)1213# For inference (prompt the model to start generating):14text = tokenizer.apply_chat_template(messages[:1], tokenize=False, add_generation_prompt=True)
2.4 The Key SFT Papers
FLAN (2021) — Instruction Tuning at Scale
Paper:"Finetuned Language Models Are Zero-Shot Learners" (Wei et al., 2021) — arXiv:2109.01652
FLAN proved that fine-tuning on instructions dramatically improves zero-shot performance. They took 62 NLP datasets, formatted them as instructions, and fine-tuned LaMDA-PT 137B.
Key result: FLAN surpassed zero-shot GPT-3 175B on 20 out of 25 tasks.
Key insight: The instruction format itself is critical — fine-tuning on the same tasks without instructions gave much weaker results.
Self-Instruct (2022) — Bootstrapping Training Data
Paper:"Self-Instruct: Aligning Language Models with Self-Generated Instructions" (Wang et al., 2022) — arXiv:2212.10560
A breakthrough idea: use the language model itself to generate training data. Starting from 175 seed tasks, GPT-3 generated 52,445 instructions with responses.
Key result: +33% improvement over vanilla GPT-3 on SuperNaturalInstructions.
Key insight: The era of synthetic data for SFT began here. This directly led to Stanford Alpaca (fine-tuning LLaMA on 52K GPT-generated instructions for <$600).
InstructGPT (2022) — SFT as Stage 1
Paper:"Training Language Models to Follow Instructions with Human Feedback" (Ouyang et al., 2022) — arXiv:2203.02155
InstructGPT established SFT as the foundation of the alignment pipeline. Their SFT model was trained on ~13K human-written demonstrations.
Key details: 16 epochs, cosine LR decay, residual dropout 0.2. They found that SFT models overfit on validation loss after 1 epoch, but training more epochs improved the reward model score — so they selected checkpoints using the RM, not validation loss.
Key result: Even 1.3B InstructGPT was preferred over 175B GPT-3 by human evaluators.
LIMA (2023) — Less Is More
Paper:"LIMA: Less Is More for Alignment" (Zhou et al., 2023) — arXiv:2305.11206
The most provocative SFT paper: fine-tuning LLaMA-65B on just 1,000 carefully curated examples produced a model competitive with GPT-3.5 (DaVinci003) in human evaluations.
Recipe: AdamW, lr 1e-5 → 1e-6 linear decay, 15 epochs, batch size 32, max length 2048. Residual dropout linearly scaled from 0.0 (bottom layer) to 0.3 (top layer).
The takeaway: For SFT, data quality >> data quantity. A small number of consistently styled, high-quality demonstrations is better than a large, noisy dataset.
2.5 SFT in Practice with TRL
python
1from trl import SFTTrainer, SFTConfig
2from datasets import load_dataset
34# Load a chat dataset (must have "messages" column)5dataset = load_dataset("trl-lib/Capybara", split="train")67config = SFTConfig(8 output_dir="./sft-output",9 num_train_epochs=3,10 per_device_train_batch_size=4,11 learning_rate=2e-5,12 max_seq_length=2048,13 gradient_checkpointing=True,# Save memory14 bf16=True,# Use bfloat16 precision15 logging_steps=10,16 push_to_hub=True,17 hub_model_id="your-username/your-sft-model",18)1920trainer = SFTTrainer(21 model="Qwen/Qwen3-0.6B",# Base model22 args=config,23 train_dataset=dataset,24)25trainer.train()
The SFTTrainer automatically:
Detects the messages column and applies the model's chat template
Masks prompt tokens from the loss (trains only on assistant responses)
Handles tokenization and padding
Chapter 3: Reinforcement Learning from Human Feedback (RLHF) — The Breakthrough
3.1 Why SFT Isn't Enough
SFT teaches format and basic behavior, but it has limitations:
It only learns from demonstrations — it can only be as good as the training examples
It can't express preferences — it treats all tokens in a response equally
It can learn bad habits — if training data contains subtle errors, the model learns those too
RLHF addresses this by training the model based on which outputs are better, not on what specific tokens to generate.
3.2 The RLHF Pipeline (Step by Step)
Step 1: Train a Reward Model
A reward model (RM) takes a prompt and a response, and outputs a scalar score indicating how good the response is.
How it's trained:
Generate multiple responses to the same prompt using the SFT model
Have humans rank these responses (e.g., Response A > Response B)
Train the RM to predict these rankings
The RM uses the Bradley-Terry model of preferences:
P(response_A is preferred over response_B) = σ(r(A) - r(B))
where σ is the sigmoid function and r(·) is the reward model's score. The loss function is:
Architecture: The reward model is typically the same architecture as the language model, but with the output head replaced by a linear layer that projects to a single scalar value.
InstructGPT details: They trained a 6B reward model (not 175B — larger RMs had unstable training). The RM dataset contained 33K prompts with human rankings.
Step 2: Optimize the Policy with PPO
Now we use the reward model to improve our language model (the "policy" in RL terminology).
In plain English: generate responses that score high on the reward model, but don't deviate too far from the original SFT model.
The KL divergence penalty (β · KL(π_θ || π_ref)) is crucial — without it, the model quickly learns to exploit the reward model (generating gibberish that tricks the RM into giving high scores, a phenomenon called reward hacking).
PPO (Proximal Policy Optimization) is the RL algorithm used to optimize this objective. Here's the intuition:
Generate: The current model generates responses to a batch of prompts
Score: The reward model scores each response
Compute advantage: Calculate how much better each response is compared to the expected value
Update: Adjust model weights to make high-advantage responses more likely
Clip: Prevent too-large updates (the "proximal" part) for stability
where r_t(θ) = π_θ(a_t|s_t) / π_old(a_t|s_t) is the probability ratio and A_t is the advantage.
InstructGPT training details:
PPO with β = 0.02 for KL penalty
Mixed in 10% pretraining data during PPO to prevent regression on general capabilities
Learning rates scanned from 2.55e-6 to 2.55e-5 (rates > 8.05e-6 diverged)
256K PPO episodes total
3.3 The Alignment Tax
RLHF improves alignment but can hurt performance on standard NLP benchmarks — this is the "alignment tax." InstructGPT mitigated this by mixing pretraining data into PPO training (the PPO-ptx variant).
3.4 Why RLHF is Hard
RLHF works, but it has significant practical challenges:
Complexity: Three separate models needed (policy, reference policy, reward model, value model) — 4 models in memory simultaneously
Instability: PPO training is notoriously sensitive to hyperparameters
Reward hacking: The model can learn to exploit the RM rather than genuinely improve
Cost: Human preference data is expensive to collect
Reproducibility: Small changes in setup can lead to very different outcomes
These challenges directly motivated the development of DPO.
3.5 Constitutional AI (RLAIF)
Paper:"Constitutional AI: Harmlessness from AI Feedback" (Bai et al., 2022) — arXiv:2212.08073
Anthropic's key insight: you can replace human feedback with AI feedback (RLAIF — RL from AI Feedback). Instead of humans ranking responses, an AI system evaluates responses against a set of principles (the "constitution").
This dramatically reduces the cost and enables scaling the feedback process.
Chapter 4: Direct Preference Optimization (DPO) — RLHF Without RL
4.1 The Key Insight
Paper:"Direct Preference Optimization: Your Language Model is Secretly a Reward Model" (Rafailov et al., 2023) — arXiv:2305.18290
DPO's central insight is beautiful in its simplicity: you don't need a separate reward model or RL training loop. The language model itself implicitly represents a reward model.
The authors showed that the optimal solution to the RLHF objective (maximize reward while staying close to the reference model) can be expressed in closed form:
Since the Bradley-Terry preference model only depends on the difference in rewards between two responses, the partition function Z(x) cancels out! This gives us the DPO loss:
Increase the likelihood of the preferred response y_w
Decrease the likelihood of the rejected response y_l
Weight these updates by how "wrong" the model currently is (if the model already prefers y_w, the gradient is small)
The weighting term σ(r̂(x,y_l) - r̂(x,y_w)) is crucial — without it, the model degenerates. This was verified experimentally: a naive "increase chosen, decrease rejected" approach without the weighting fails.
4.4 DPO in Practice
Data format: DPO needs preference pairs — for each prompt, a "chosen" (preferred) and "rejected" response:
python
1{2"prompt":[{"role":"user","content":"Explain gravity"}],3"chosen":[{"role":"assistant","content":"Gravity is a fundamental force..."}],4"rejected":[{"role":"assistant","content":"Gravity is when things fall down."}]5}
When to use: When you suspect your preference data is noisy or when DPO is overfitting.
5.2 KTO — Kahneman-Tversky Optimization
Paper:"KTO: Model Alignment as Prospect Theoretic Optimization" (Ethayarajh et al., 2024) — arXiv:2402.01306
Problem with DPO: DPO requires paired preferences (chosen AND rejected for the same prompt). This is expensive to collect. In reality, it's much easier to get binary feedback: "this response is good" or "this response is bad."
Solution: KTO works with unpaired preferences — you only need individual responses labeled as good or bad, not pairs. It's based on Kahneman and Tversky's prospect theory from behavioral economics: humans feel losses more strongly than equivalent gains.
Data format:
python
1{"prompt":"...","completion":"...","label":True}# Good response2{"prompt":"...","completion":"...","label":False}# Bad response
When to use: When you have thumbs-up/thumbs-down feedback but not pairwise comparisons.
5.3 ORPO — Odds Ratio Preference Optimization
Paper:"ORPO: Monolithic Preference Optimization without Reference Model" (Hong et al., 2024)
Problem with DPO: DPO still requires a separate SFT stage and a reference model.
Solution: ORPO combines SFT and preference optimization into a single training step. It adds a preference signal directly to the SFT loss using the odds ratio:
L_ORPO = L_SFT + λ · L_OR
where L_OR penalizes the model when the odds of generating the rejected response exceed those of the chosen response.
When to use: When you want a simpler pipeline without separate SFT and preference stages.
5.4 SimPO — Simple Preference Optimization
Paper:"SimPO: Simple Preference Optimization with a Reference-Free Reward" (Meng et al., 2024)
Problem with DPO: DPO needs a reference model in memory, doubling GPU requirements.
Solution: SimPO eliminates the reference model entirely by using the average log probability of a sequence as the implicit reward (instead of the total log probability). This length-normalized reward naturally prevents the model from favoring longer responses.
When to use: When GPU memory is a constraint and you want to skip the reference model.
5.5 CPO — Contrastive Preference Optimization
Simplifies DPO by removing the reference model and using a contrastive loss. Similar motivation to SimPO but with a different formulation.
5.6 Online DPO
Problem with standard DPO: DPO trains on a fixed, static preference dataset (offline). But the model changes during training, so the preferences collected from the old model become stale.
Solution: Online DPO generates new completions from the current model during training and gets them scored by a reward model. This keeps the training data fresh and on-policy.
5.7 Summary Table
Method
Needs Reference Model?
Needs Paired Data?
Needs RM?
Separate SFT?
Key Advantage
PPO (RLHF)
Yes
No (uses RM)
Yes
Yes
Gold standard, online
DPO
Yes
Yes
No
Yes
Simple, stable
IPO
Yes
Yes
No
Yes
Robust to noise
KTO
Yes
No (binary)
No
Yes
Works with unpaired data
ORPO
No
Yes
No
No (combined)
Simplest pipeline
SimPO
No
Yes
No
Yes
Memory efficient
CPO
No
Yes
No
Yes
Memory efficient
Online DPO
Yes
Generated online
Yes
Yes
On-policy, fresh data
GRPO
Yes (soft)
No (uses rewards)
Yes (or functions)
Yes
Best for reasoning
Chapter 6: GRPO and the Reasoning Revolution
6.1 What is GRPO?
Paper:"DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language Models" (Shao et al., 2024) — arXiv:2402.03300
Group Relative Policy Optimization (GRPO) is a variant of PPO designed to be more memory-efficient and particularly effective for reasoning tasks (math, code, logic).
The key idea: Instead of training a separate value model (critic) as in PPO, GRPO estimates the "baseline" by generating multiple completions per prompt and using the group average reward as the baseline.
6.2 How GRPO Works
For each prompt:
1. Generate G completions (e.g., G=16)
2. Score each completion with a reward function
3. Compute the advantage for each completion:
Â_i = (r_i - mean(r)) / std(r)
4. Update the model to increase probability of high-advantage completions
and decrease probability of low-advantage completions
where ratio = π_θ(o_{i,t}) / π_old(o_{i,t}) is the importance sampling ratio.
Why "Group Relative"? The advantage is computed relative to the group of completions for the same prompt. A completion is "good" if it scores above the group average, and "bad" if below. This is why the method has that name.
6.3 Why GRPO Matters: The DeepSeek-R1 Story
GRPO became famous when DeepSeek used it to train DeepSeek-R1 — a model that learned to "think" through chain-of-thought reasoning purely through RL, without being taught specific reasoning patterns.
Paper:"DeepSeek-R1: Incentivizing Reasoning Capability in LLMs via Reinforcement Learning" (DeepSeek-AI, 2025) — arXiv:2501.12948
The key discovery: with the right reward function (accuracy on math/coding problems) and GRPO training, the model spontaneously develops chain-of-thought reasoning, self-verification, and error correction — without being explicitly trained to do so.
This opened the "reasoning era" of LLM training, where RL-based methods are used to incentivize complex reasoning behaviors.
6.4 GRPO in Practice
GRPO requires:
A prompt dataset (just prompts, no responses needed)
A reward function (can be a model or a simple Python function)
python
1from trl import GRPOTrainer, GRPOConfig
2from datasets import load_dataset
3import re
45dataset = load_dataset("trl-lib/DeepMath-103K", split="train")67# Custom reward function: checks if the answer is correct8defaccuracy_reward(completions, ground_truth,**kwargs):9 matches =[re.search(r"\\boxed\{(.*?)\}", c)for c in completions]10 contents =[m.group(1)if m else""for m in matches]11return[1.0if c == gt else0.0for c, gt inzip(contents, ground_truth)]1213config = GRPOConfig(14 output_dir="./grpo-output",15 learning_rate=1e-6,16 per_device_train_batch_size=4,17 num_generations=16,# G: number of completions per prompt18 max_completion_length=512,19 logging_steps=10,20 bf16=True,21 gradient_checkpointing=True,22)2324trainer = GRPOTrainer(25 model="Qwen/Qwen2.5-0.5B-Instruct",26 reward_funcs=accuracy_reward,27 args=config,28 train_dataset=dataset,29)30trainer.train()
6.5 Reward Functions vs Reward Models
GRPO is flexible — the reward can come from:
A Python function (rule-based): Check if math answer is correct, if code passes tests, if format is right
A reward model (learned): A separate neural network that scores responses
For math/coding, rule-based rewards are often better because they provide an exact signal — the answer is either right or wrong. For open-ended tasks (chat, creative writing), a learned reward model is needed.
Chapter 7: Parameter-Efficient Fine-Tuning (PEFT) — LoRA, QLoRA, and Adapters
7.1 The Memory Problem
Fine-tuning a 7B parameter model requires:
Model weights: 7B × 2 bytes (bf16) = 14 GB
Gradients: 14 GB
Optimizer states (AdamW): 28 GB (2 states × 14 GB)
Activations: Variable, often 10-30 GB
Total: ~60-80 GB for a single 7B model. That's one A100 GPU just for SFT. For RLHF with PPO (4 models), you'd need 4× this.
7.2 LoRA: Low-Rank Adaptation
Paper:"LoRA: Low-Rank Adaptation of Large Language Models" (Hu et al., 2021) — arXiv:2106.09685
The insight: When fine-tuning, the weight updates have low rank — they can be approximated by small matrices without much loss.
Instead of updating the full weight matrix W (d × d), LoRA adds two small matrices:
W' = W + α · B × A
where:
W is the original frozen weight (d × d)
A is a small matrix (d × r) — "down projection"
B is a small matrix (r × d) — "up projection"
r << d (typically r = 8, 16, 32) — the "rank"
α is a scaling factor
Only A and B are trained — the original weights are frozen. This reduces trainable parameters by 100-1000×.
Key trade-off: LoRA is ~95-99% as good as full fine-tuning for most tasks, at a fraction of the compute. For maximum quality (e.g., training a production model), full fine-tuning is still king.
Chapter 8: The Toolbox — Libraries, Frameworks, and Infrastructure
Handles distributed training across multiple GPUs/nodes. You rarely interact with it directly — it works behind the scenes when you use accelerate launch:
bash
1# Single GPU2python train.py
34# Multi-GPU5accelerate launch --num_processes 4 train.py
67# Multi-GPU with DeepSpeed8accelerate launch --config_file deepspeed_zero3.yaml train.py
For your first experiment: Use trl-lib/Capybara (SFT) or trl-lib/ultrafeedback_binarized (DPO). They're well-formatted and TRL-compatible out of the box.
Quality over quantity: LIMA showed that 1K great examples beats 52K mediocre ones. Invest in data curation.
Match your use case: If training a math model, use math-specific data. If training a general assistant, use diverse conversational data.
Always inspect before training:
python
1from datasets import load_dataset
2ds = load_dataset("trl-lib/Capybara", split="train")3print(ds[0])# Look at the data!
Chapter 10: Evaluation — How to Know If It Worked
10.1 The Evaluation Problem
Evaluating LLMs is fundamentally hard because:
Open-ended outputs can be correct in many different ways
Perplexity doesn't correlate well with usefulness (LIMA found this explicitly)
Side-by-side comparison: Show humans two responses, ask which is better
Likert scale: Rate each response on helpfulness, accuracy, harmlessness (1-7)
Chatbot Arena: Users chat with two anonymous models and vote for the better one
The LMSYS Chatbot Arena provides the most widely-cited human evaluation through crowdsourced blind comparisons.
10.5 The Open LLM Leaderboard
Hugging Face hosts the Open LLM Leaderboard which evaluates open-source models across standardized benchmarks. It's the primary way the community tracks progress.
Chapter 11: Putting It All Together — A Complete Post-Training Recipe
11.1 The Standard Recipe (2024-2025)
Here's a typical post-training pipeline for building a chat model:
Step 1: Choose Base Model
├── Qwen3 (0.6B to 235B) — Currently top-performing family
├── Llama 3.1/3.2 (1B to 405B) — Meta's open models
├── Gemma 3/4 (1B to 27B) — Google's open models
└── Mistral/Mixtral — Strong efficiency
Step 2: SFT
├── Dataset: trl-lib/Capybara or HuggingFaceH4/ultrachat_200k
├── Method: SFTTrainer with LoRA (for efficiency) or full fine-tuning
├── Epochs: 2-3
├── LR: 2e-5 (full) or 2e-4 (LoRA)
└── Output: SFT model (becomes reference model for Stage 3)
Step 3: Preference Optimization (choose one)
├── Option A: DPO (simplest, most popular)
│ ├── Dataset: trl-lib/ultrafeedback_binarized
│ ├── β: 0.1
│ ├── LR: 5e-7
│ └── Epochs: 1-2
├── Option B: GRPO (best for reasoning tasks)
│ ├── Dataset: trl-lib/DeepMath-103K (math)
│ ├── Reward: accuracy_reward + format_reward
│ ├── num_generations: 16
│ └── LR: 1e-6
└── Option C: KTO (if you only have binary feedback)
├── Dataset: unpaired preference data
└── Similar to DPO hyperparameters
Step 4: Evaluation
├── Automated: lm-eval-harness (MMLU, GSM8K, etc.)
├── LLM-Judge: MT-Bench, AlpacaEval
└── Manual: Test with real prompts
Papers: Start with InstructGPT and DPO from the reading list, then follow your interests
Experiment: Fine-tune a small model (Qwen3-0.6B) on your own data — the best way to learn is by doing
This guide was compiled from primary research papers, official Hugging Face documentation, and the TRL library source code. All paper citations link to their arXiv pages. All code examples use current API patterns from TRL v1.2+.