Key terms for this tutorial
Here are the words that matter most in this tutorial. Come back here if a term feels fuzzy.
- 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.
- reward model
- A model trained to score how good a completion is, used in RLHF.
- RLHF
- Reinforcement Learning from Human Feedback. Fine-tuning a model with human preference signals.
Train a reward model
A reward model is trained on pairs of completions labelled win/lose. It outputs a scalar score, but the score is only meaningful relative to other completions; it is not an absolute measure of quality.
import torch
import torch.nn as nn
class RewardModel(nn.Module):
def __init__(self, base, hidden):
super().__init__()
self.base = base
self.score = nn.Linear(hidden, 1)
def forward(self, ids):
h = self.base(ids, return_hidden=True) # (b, t, h)
return self.score(h[:, -1, :]).squeeze(-1)
print('RewardModel expects last hidden state of shape (b, hidden)')
RewardModel expects last hidden state of shape (b, hidden)
Line-by-line: reward.py
Read this slowly. Each line does one small, concrete thing.
import torch— Import thetorchlibrary so we can use its built-in tools.import torch.nn as nn— Import thetorchlibrary so we can use its built-in tools.class RewardModel(nn.Module):— Define a customRewardModelclass that tells PyTorch how to fetch one example.def __init__(self, base, hidden):— Define the__init__function, which describes a step in the data or model pipeline.self.score = nn.Linear(hidden, 1)— Add a linear layer that multiplies inputs by a weight matrix and adds a bias.def forward(self, ids):— Define theforwardfunction, which describes a step in the data or model pipeline.print('RewardModel expects last hidden state of shape (b, hidden)')— Print a result so we can see what the model learned.
Pop-in: Reward is just a score, not the truth
A reward model tries to predict human preferences. If the reward is poorly designed, the model can game it, just like students optimizing for test scores instead of learning.
Stuck or curious? Explain this to me on ChatGPT
Prompt: I am a beginner AI engineer working through the CodeHS tutorial 'AI Engineer: RLHF, DPO, and GRPO'. Explain the section 'Train a reward model' in plain English. Include simple analogies, vocabulary definitions, and a short example. Also walk through the code example in this section step by step.
Direct preference optimisation
DPO removes the reward model. It optimises the policy directly on preference pairs by comparing log-probabilities of the policy and a frozen reference model. The implicit reward is the log-ratio multiplied by a temperature coefficient.
import torch
import torch.nn.functional as F
beta = 0.1
pi_w = torch.tensor(0.6) # policy prob for preferred completion
pi_l = torch.tensor(0.3)
ref_w = torch.tensor(0.5)
ref_l = torch.tensor(0.4)
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)
print('DPO loss:', loss.item():.4f)
DPO loss: 0.3799
Line-by-line: dpo_loss.py
Read this slowly. Each line does one small, concrete thing.
import torch— Import thetorchlibrary so we can use its built-in tools.import torch.nn.functional as F— Import thetorchlibrary so we can use its built-in tools.pi_w = torch.tensor(0.6) # policy prob for preferred completion— Create a PyTorch tensor from raw Python numbers.pi_l = torch.tensor(0.3)— Create a PyTorch tensor from raw Python numbers.ref_w = torch.tensor(0.5)— Create a PyTorch tensor from raw Python numbers.ref_l = torch.tensor(0.4)— Create a PyTorch tensor from raw Python numbers.loss = -F.logsigmoid(r_w - r_l)— Compute the loss, which measures how far the prediction is from the target.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: RLHF, DPO, and GRPO'. 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.
Group relative policy optimisation
GRPO removes the critic network. It samples a group of completions for each prompt, normalises their rewards relative to the group mean, and updates the policy. This is popular for reasoning models because it only needs a reward per completion.
import torch
rewards = torch.tensor([0.2, 0.8, 0.5, 0.9, 0.3])
advantages = (rewards - rewards.mean()) / (rewards.std() + 1e-8)
print('advantages:', advantages.round(decimals=2).tolist())
advantages: [-1.11, 0.7, -0.08, 1.15, -0.66]
Line-by-line: grpo.py
Read this slowly. Each line does one small, concrete thing.
import torch— Import thetorchlibrary so we can use its built-in tools.rewards = torch.tensor([0.2, 0.8, 0.5, 0.9, 0.3])— Create a PyTorch tensor from raw Python numbers.print('advantages:', advantages.round(decimals=2).tolist())— Print a result so we can see what the model learned.
Pop-in: Reward is just a score, not the truth
A reward model tries to predict human preferences. If the reward is poorly designed, the model can game it, just like students optimizing for test scores instead of learning.
Stuck or curious? Explain this to me on ChatGPT
Prompt: I am a beginner AI engineer working through the CodeHS tutorial 'AI Engineer: RLHF, DPO, and GRPO'. Explain the section 'Group relative 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.
Check yourself
PPO vs DPO vs GRPO
Which method does not need a separate reward model?
DPO uses an implicit reward from policy/reference log-probabilities; GRPO can use a task reward directly and normalises advantages within a group. PPO typically uses a learned reward model plus a critic.
Stuck or curious? Explain this to me on ChatGPT
Prompt: I am a beginner AI engineer studying 'AI Engineer: RLHF, DPO, and GRPO'. The practice question 'PPO vs DPO vs GRPO' asks: Which method does not need a separate reward model? The answer is: DPO uses an implicit reward from policy/reference log-probabilities; GRPO can use a task reward directly and normalises advantages within a group. PPO typically uses a learned reward model plus a critic.. 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: RLHF, DPO, and GRPO'. Explain the section 'Check yourself' in plain English. Include simple analogies, vocabulary definitions, and a short example.
Three questions
1. What does a reward model output?
Stuck or curious? Explain this question to me on ChatGPT
Prompt: I am a beginner AI engineer studying 'AI Engineer: RLHF, DPO, and GRPO'. The quiz asks: What does a reward model output? The correct answer is: A scalar score for a completion. Explain why that answer is right and why the other choices are wrong, using a simple example.
2. What is the main advantage of DPO over PPO?
Stuck or curious? Explain this question to me on ChatGPT
Prompt: I am a beginner AI engineer studying 'AI Engineer: RLHF, DPO, and GRPO'. The quiz asks: What is the main advantage of DPO over PPO? The correct answer is: It does not need a separate reward model. Explain why that answer is right and why the other choices are wrong, using a simple example.
3. What does GRPO remove?
Stuck or curious? Explain this question to me on ChatGPT
Prompt: I am a beginner AI engineer studying 'AI Engineer: RLHF, DPO, and GRPO'. The quiz asks: What does GRPO remove? The correct answer is: The critic/value network by using group-normalised rewards. Explain why that answer is right and why the other choices are wrong, using a simple example.
Keep learning
Next: evaluate models with industry-standard benchmarks.
Part of the CodeHS tutorial library.