Please enable JavaScript to use CodeHS

AI Engineer

Aligning models with humans

RLHF is one of several alignment techniques. This deep dive compares PPO, GRPO, DPO, and the safety tradeoffs.

AI ~15 min Programmer
Vocabulary

Key terms for this tutorial

Here are the words that matter most in this tutorial. Come back here if a term feels fuzzy.

gradient
A vector of partial derivatives showing how much each parameter affects the loss.
loss
A number that measures how wrong the model is. Training tries to minimize loss.
model
A function with learnable parameters that maps inputs to outputs.
policy
In reinforcement learning, the rule (or model) that decides which action to take.
reward
In reinforcement learning, a number that tells the agent how good its action was.
tensor
A multi-dimensional array of numbers, the basic data type in deep learning.
KL divergence
A measure of how much one probability distribution differs from another. In RLHF it keeps the new model close to the original.
reinforcement learning
Training by trying actions and learning from rewards instead of correct answers.

PPO

Proximal policy optimisation

PPO updates a policy without changing it too much in one step. It clips the probability ratio between new and old policies so updates stay in a trust region, keeping training stable.

ppo_clip.py
import torch
# Simplified PPO clipped surrogate objective
ratio = torch.tensor(1.2)
advantage = torch.tensor(0.5)
epsilon = 0.2
surrogate1 = ratio * advantage
surrogate2 = torch.clamp(ratio, 1 - epsilon, 1 + epsilon) * advantage
loss = -torch.min(surrogate1, surrogate2)
print('clipped surrogate loss:', loss.item())
Output
clipped surrogate loss: -0.4000000059604645

Line-by-line: ppo_clip.py

Read this slowly. Each line does one small, concrete thing.

  1. import torch — Import the torch library so we can use its built-in tools.
  2. ratio = torch.tensor(1.2) — Create a PyTorch tensor from raw Python numbers.
  3. advantage = torch.tensor(0.5) — Create a PyTorch tensor from raw Python numbers.
  4. loss = -torch.min(surrogate1, surrogate2) — Compute the loss, which measures how far the prediction is from the target.
  5. print('clipped surrogate loss:', loss.item()) — Print a result so we can see what the model learned.

Pop-in: Read the code one block at a time

Industry code imports many libraries. Focus on the sequence: prepare data, define the model, run the training loop, and evaluate. The rest is setup.

Stuck or curious? Explain this to me on ChatGPT

Prompt: I am a beginner AI engineer working through the CodeHS tutorial 'AI Engineer: Reinforcement Learning — Deep Dive'. Explain the section 'Proximal policy optimisation' in plain English. Include simple analogies, vocabulary definitions, and a short example. Also walk through the code example in this section step by step.


DPO

Direct preference optimisation

DPO skips the reward model. It derives an implicit reward from the log probability ratio between the policy and the reference model, then optimises directly on human preference pairs. This is simpler and often more stable than PPO.

dpo.py
import torch
import torch.nn.functional as F

pi_w = torch.tensor([0.8, 0.2])  # policy probabilities for (win, lose)
pi_l = torch.tensor([0.3, 0.7])
ref_w = torch.tensor([0.6, 0.4])
ref_l = torch.tensor([0.4, 0.6])
beta = 0.1
r_w = beta * (torch.log(pi_w) - torch.log(ref_w))
r_l = beta * (torch.log(pi_l) - torch.log(ref_l))
loss = -F.logsigmoid(r_w - r_l).mean()
print('DPO loss:', loss.item():.4f)
Output
DPO loss: 0.5981

Line-by-line: dpo.py

Read this slowly. Each line does one small, concrete thing.

  1. import torch — Import the torch library so we can use its built-in tools.
  2. import torch.nn.functional as F — Import the torch library so we can use its built-in tools.
  3. pi_w = torch.tensor([0.8, 0.2]) # policy probabilities for (win, lose) — Create a PyTorch tensor from raw Python numbers.
  4. pi_l = torch.tensor([0.3, 0.7]) — Create a PyTorch tensor from raw Python numbers.
  5. ref_w = torch.tensor([0.6, 0.4]) — Create a PyTorch tensor from raw Python numbers.
  6. ref_l = torch.tensor([0.4, 0.6]) — Create a PyTorch tensor from raw Python numbers.
  7. loss = -F.logsigmoid(r_w - r_l).mean() — Compute the loss, which measures how far the prediction is from the target.
  8. print('DPO loss:', loss.item():.4f) — Print a result so we can see what the model learned.

Pop-in: Read the code one block at a time

Industry code imports many libraries. Focus on the sequence: prepare data, define the model, run the training loop, and evaluate. The rest is setup.

Stuck or curious? Explain this to me on ChatGPT

Prompt: I am a beginner AI engineer working through the CodeHS tutorial 'AI Engineer: Reinforcement Learning — Deep Dive'. Explain the section 'Direct preference optimisation' in plain English. Include simple analogies, vocabulary definitions, and a short example. Also walk through the code example in this section step by step.


Safety

Reward hacking and KL penalties

A reward model is a proxy for human judgement. Optimise it too hard and the model finds loopholes: overly long answers, keyword stuffing, or sycophancy. A KL penalty keeps the new policy close to the base model, preserving fluency while improving reward.

GRPO removes the critic by comparing a group of samples, simplifying training at the cost of more rollouts per update. It is popular for reasoning models because it only needs a reward per completion.

?

What is reward hacking?

Why can maximising a reward model go wrong?

The reward model is an imperfect proxy. The policy can exploit its flaws to get high scores without actually satisfying human preferences.

Stuck or curious? Explain this to me on ChatGPT

Prompt: I am a beginner AI engineer studying 'AI Engineer: Reinforcement Learning — Deep Dive'. The practice question 'What is reward hacking?' asks: Why can maximising a reward model go wrong? The answer is: The reward model is an imperfect proxy. The policy can exploit its flaws to get high scores without actually satisfying human preferences.. Explain the concept behind this in simple terms.

Stuck or curious? Explain this to me on ChatGPT

Prompt: I am a beginner AI engineer working through the CodeHS tutorial 'AI Engineer: Reinforcement Learning — Deep Dive'. Explain the section 'Reward hacking and KL penalties' in plain English. Include simple analogies, vocabulary definitions, and a short example.


Check yourself

Check yourself

?

PPO vs DPO

What is the main difference between PPO and DPO?

PPO uses a separate reward model and a policy-gradient update. DPO uses preference pairs and an implicit reward derived from the policy and reference model, no reward model needed.

Stuck or curious? Explain this to me on ChatGPT

Prompt: I am a beginner AI engineer studying 'AI Engineer: Reinforcement Learning — Deep Dive'. The practice question 'PPO vs DPO' asks: What is the main difference between PPO and DPO? The answer is: PPO uses a separate reward model and a policy-gradient update. DPO uses preference pairs and an implicit reward derived from the policy and reference model, no reward model needed.. Explain the concept behind this in simple terms.

Stuck or curious? Explain this to me on ChatGPT

Prompt: I am a beginner AI engineer working through the CodeHS tutorial 'AI Engineer: Reinforcement Learning — Deep Dive'. Explain the section 'Check yourself' in plain English. Include simple analogies, vocabulary definitions, and a short example.


Quick quiz

Three questions

1. What is the purpose of the PPO clip objective?

Stuck or curious? Explain this question to me on ChatGPT

Prompt: I am a beginner AI engineer studying 'AI Engineer: Reinforcement Learning — Deep Dive'. The quiz asks: What is the purpose of the PPO clip objective? The correct answer is: To limit how far the policy can change in one update. Explain why that answer is right and why the other choices are wrong, using a simple example.

2. What does DPO optimise directly?

Stuck or curious? Explain this question to me on ChatGPT

Prompt: I am a beginner AI engineer studying 'AI Engineer: Reinforcement Learning — Deep Dive'. The quiz asks: What does DPO optimise directly? The correct answer is: Preference pairs without a separate reward model. Explain why that answer is right and why the other choices are wrong, using a simple example.

3. Why is a KL penalty used in RL fine-tuning?

Stuck or curious? Explain this question to me on ChatGPT

Prompt: I am a beginner AI engineer studying 'AI Engineer: Reinforcement Learning — Deep Dive'. The quiz asks: Why is a KL penalty used in RL fine-tuning? The correct answer is: To keep the policy close to the base model and preserve fluency. Explain why that answer is right and why the other choices are wrong, using a simple example.

Keep learning

You now have a deep understanding of building and aligning models. Go build something.

Part of the CodeHS tutorial library.