Please enable JavaScript to use CodeHS

AI Engineer

Steer a model with rewards

A pre-trained language model predicts the next token, but it does not know what you value. Reinforcement learning turns human preferences into a reward signal and teaches the model to produce outputs that people prefer.

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.
language model
A model that predicts the next token (or fills in missing tokens) in a sequence of text.
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.
optimizer
An algorithm, like SGD or Adam, that updates model weights using gradients.
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.
softmax
A function that turns logits into probabilities that add up to 1.

Problem

Pre-training is not enough

After pre-training, a model is good at grammar and facts but may be verbose, biased, or unhelpful. The last step in building products like ChatGPT is alignment: teaching the model to be helpful, harmless, and honest.

Alignment uses reinforcement learning. The model is the policy: it chooses actions (tokens). A reward model scores the resulting text. The policy is updated to maximize expected reward.

Core idea: pre-training creates a simulator of language. Reinforcement learning turns that simulator into a useful assistant.

Stuck or curious? Explain this to me on ChatGPT

Prompt: I am a beginner AI engineer working through the CodeHS tutorial 'AI Engineer: Fine-Tune with Reinforcement Learning'. Explain the section 'Pre-training is not enough' in plain English. Include simple analogies, vocabulary definitions, and a short example.


Reward model

Learning a reward model from human preferences

Humans compare two model outputs and say which one is better. The reward model is trained to predict that judgment: it takes a prompt and a completion and outputs a scalar score.

Because humans are slow and expensive, we train a small classifier to mimic their preferences, then use it as an automatic judge for millions of reinforcement-learning steps.

reward_model.py
import torch
import torch.nn as nn

class RewardModel(nn.Module):
    def __init__(self, base_gpt, hidden_dim):
        super().__init__()
        self.base = base_gpt
        self.score_head = nn.Linear(hidden_dim, 1)

    def forward(self, input_ids):
        hidden = self.base(input_ids, return_hidden=True)  # (b, t, hidden)
        # Score the last hidden state
        last_hidden = hidden[:, -1, :]
        return self.score_head(last_hidden).squeeze(-1)

# Example: score a completion
rm = RewardModel(model, hidden_dim=32)
score = rm(torch.tensor([[5, 12, 7]]))
print("reward:", score.item())
Output
reward: 0.1342

Line-by-line: reward_model.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 as nn — Import the torch library so we can use its built-in tools.
  3. class RewardModel(nn.Module): — Define a custom RewardModel class that tells PyTorch how to fetch one example.
  4. def __init__(self, base_gpt, hidden_dim): — Define the __init__ function, which describes a step in the data or model pipeline.
  5. self.score_head = nn.Linear(hidden_dim, 1) — Add a linear layer that multiplies inputs by a weight matrix and adds a bias.
  6. def forward(self, input_ids): — Define the forward function, which describes a step in the data or model pipeline.
  7. score = rm(torch.tensor([[5, 12, 7]])) — Create a PyTorch tensor from raw Python numbers.
  8. print("reward:", score.item()) — 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: Fine-Tune with Reinforcement Learning'. Explain the section 'Learning a reward model from human preferences' in plain English. Include simple analogies, vocabulary definitions, and a short example. Also walk through the code example in this section step by step.


Policy gradient

Policy gradient in one dimension

The policy generates text. The reward model scores it. If the score is high, we increase the probability of the tokens that produced it; if low, we decrease it. This is the REINFORCE idea.

In practice, modern RL uses PPO or GRPO. They add a baseline to reduce variance and a KL penalty to keep the policy close to the pre-trained model so it does not forget language.

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

# Simple bandit-style policy gradient: choose one of four actions,
# receive a reward, and nudge logits toward the good ones.

logits = torch.zeros(4, requires_grad=True)
optimizer = torch.optim.SGD([logits], lr=0.1)
rewards = torch.tensor([10.0, 1.0, 3.0, 5.0])  # we know the true reward

for _ in range(100):
    probs = F.softmax(logits, dim=-1)
    # Expected reward under the current policy
    expected = (probs * rewards).sum()
    loss = -expected

    optimizer.zero_grad()
    loss.backward()
    optimizer.step()

print("final probabilities:", F.softmax(logits, dim=-1).detach().round(3).tolist())
Output
final probabilities: [0.981, 0.0, 0.003, 0.016]

Line-by-line: policy_gradient.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. optimizer = torch.optim.SGD([logits], lr=0.1) — Create an SGD optimizer that will update the model's weights using gradients.
  4. rewards = torch.tensor([10.0, 1.0, 3.0, 5.0]) # we know the true reward — Create a PyTorch tensor from raw Python numbers.
  5. for _ in range(100): — Loop over the data one batch at a time.
  6. probs = F.softmax(logits, dim=-1) — Convert logits into probabilities that add up to 1.
  7. loss = -expected — Compute the loss, which measures how far the prediction is from the target.
  8. optimizer.zero_grad() — Clear out old gradients so they do not accumulate across steps.
  9. loss.backward() — Compute gradients: how much each weight contributed to the loss.
  10. optimizer.step() — Update the model weights using the gradients the optimizer just computed.
  11. print("final probabilities:", F.softmax(logits, dim=-1).detach().round(3).tolist()) — Convert logits into probabilities that add up to 1.

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.

The policy quickly learns to favor the action with reward 10. In a language model, actions are tokens and rewards come from the reward model, but the idea is identical.

Stuck or curious? Explain this to me on ChatGPT

Prompt: I am a beginner AI engineer working through the CodeHS tutorial 'AI Engineer: Fine-Tune with Reinforcement Learning'. Explain the section 'Policy gradient in one dimension' in plain English. Include simple analogies, vocabulary definitions, and a short example. Also walk through the code example in this section step by step.


RLHF

The RLHF pipeline

  • 1. Pre-train a base language model on general text.
  • 2. Collect comparisons of model outputs from humans.
  • 3. Train a reward model to predict those preferences.
  • 4. Fine-tune the policy with PPO/GRPO to maximize reward while staying close to the base model.

The result is a model that is not just fluent but aligned with human intent. That is the final step in turning a pile of tensors into a product.

Stuck or curious? Explain this to me on ChatGPT

Prompt: I am a beginner AI engineer working through the CodeHS tutorial 'AI Engineer: Fine-Tune with Reinforcement Learning'. Explain the section 'The RLHF pipeline' in plain English. Include simple analogies, vocabulary definitions, and a short example.


Check yourself

Check yourself

?

Why use a reward model instead of directly training on human ratings?

Human feedback is expensive. How does a reward model help?

A reward model is trained once on human comparisons and then acts as an automatic, cheap critic. RL can query it millions of times during fine-tuning, which would be impossible with real human judges.

Stuck or curious? Explain this to me on ChatGPT

Prompt: I am a beginner AI engineer studying 'AI Engineer: Fine-Tune with Reinforcement Learning'. The practice question 'Why use a reward model instead of directly training on human ratings?' asks: Human feedback is expensive. How does a reward model help? The answer is: A reward model is trained once on human comparisons and then acts as an automatic, cheap critic. RL can query it millions of times during fine-tuning, which would be impossible with real human judges.. 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: Fine-Tune with Reinforcement Learning'. 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 'policy' in RLHF for language models?

Stuck or curious? Explain this question to me on ChatGPT

Prompt: I am a beginner AI engineer studying 'AI Engineer: Fine-Tune with Reinforcement Learning'. The quiz asks: What is the 'policy' in RLHF for language models? The correct answer is: The language model that chooses tokens. Explain why that answer is right and why the other choices are wrong, using a simple example.

2. 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: Fine-Tune with Reinforcement Learning'. 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.

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

Stuck or curious? Explain this question to me on ChatGPT

Prompt: I am a beginner AI engineer studying 'AI Engineer: Fine-Tune with Reinforcement Learning'. The quiz asks: Why is a KL penalty used during RL fine-tuning? The correct answer is: To keep the new policy close to the pre-trained model so it does not collapse into gibberish. Explain why that answer is right and why the other choices are wrong, using a simple example.

Keep learning

Deep dive into PPO, DPO, GRPO, reward hacking, and alignment safety.

Part of the CodeHS tutorial library.