AI from scratch · Elective · Reinforcement learning
Reinforcement learning
Every model on this path learned from examples with answers. Some problems have no answers to copy, only consequences: a game won or lost many moves later, a robot that stays upright or falls, a chatbot reply that people rate up or down. Reinforcement learning (RL) learns from consequences: an agent acts, the world responds with a reward, and over many tries the agent learns which actions lead to more reward in the long run. It's how AlphaGo learned Go and part of how chat models learned to be helpful (RLHF). This lesson builds the core ideas on a small city grid you can watch learn.
1. Agent, state, action, reward
At each step the agent sees a state \(s\), picks an action \(a\), receives a reward \(r\) and lands in a new state. Its goal is the return: the sum of future rewards, each step further away worth a factor \(\gamma\) (gamma, the discount, a little under 1) less:
\[ G_t = r_{t+1} + \gamma\, r_{t+2} + \gamma^2 r_{t+3} + \dots \]
The grid below: a rider starts top-left and must reach the station (green, +10). Every step costs −1 (time), the red cells are construction (−5), and the street is slippery: 10% of the time the rider moves in a random direction instead. Nothing tells the agent where the station is; it has to find out.
An agent learns from rewards that may arrive many steps after the action that earned them, aiming for the most discounted reward in the long run.
2. Values, and the Bellman equation
The value of a state is the return you can expect from it if you act well from then on. The key fact: a state's value is the best action's immediate reward plus the discounted value of where it leads. That's the Bellman equation, written with \(Q(s, a)\), the value of taking action \(a\) in state \(s\):
\[ Q(s, a) = \mathbb{E}\left[ r + \gamma \max_{a'} Q(s', a') \right] \]
The colors in the grid are \(\max_a Q(s, a)\) as the agent has learned them, and the arrows the best action from each cell. Watch the values spread outward from the station like a rumor: first its neighbors learn they're close, then their neighbors.
With \(\gamma = 0.9\), a step costs −1 and from the next cell the best you can do is worth 0. What is this step's \(Q\)?
A state's value is its best action's reward plus the discounted value of where that action leads: a recursion that lets value flow backward from rewards.
Why the Bellman equation holds
- The return from now is the next reward plus the discounted return from the next step on: \(G_t = r_{t+1} + \gamma G_{t+1}\) (factor \(\gamma\) out of every later term).
- Take expectations: \(Q(s, a) = \mathbb{E}[G_t \mid s, a] = \mathbb{E}[r_{t+1} + \gamma G_{t+1} \mid s, a]\). The expectation covers the slip: where you land is random.
- If from the next state you act as well as possible, the expected \(G_{t+1}\) is the best \(Q\) there: \(\max_{a'} Q(s', a')\).
- So \(Q(s, a) = \mathbb{E}[r + \gamma \max_{a'} Q(s', a')]\). The values must agree with themselves one step later; that self-consistency is what Q-learning drives toward.
- With \(\gamma < 1\) a reward \(k\) steps away counts \(\gamma^k\): at 0.95, a reward 50 steps away counts 0.077 as much. Lower \(\gamma\) makes the agent short-sighted; try 0.5 in the grid.
3. Q-learning: learn values from your own steps
The agent doesn't know the rules of the world (the slip, where the station is), so it can't solve the equation directly. Q-learning nudges its estimate after every single step toward what that step suggests:
\[ Q(s, a) \leftarrow Q(s, a) + \alpha \left[ r + \gamma \max_{a'} Q(s', a') - Q(s, a) \right] \]
The bracket is the surprise (a "temporal difference" error): what happened plus what's expected next, minus what was expected now. Chapter 2's gradient step, toward a target the agent keeps improving. And it must explore: with probability \(\varepsilon\) take a random action, otherwise the best known one, or it never discovers a better route than the first one it found. In the practice notebook a coffee cart worth +3 sits two steps from the start and the far corner is worth +20: with ε = 0.1 the agent settles for the coffee in all six runs; with ε = 0.5 it finds the corner in all six, after 2,000 episodes. Exploration is necessary, and expensive.
Q-learning moves each estimate toward the reward it just got plus the best estimate of the next state, and explores a little so it can find better paths.
4. Policy gradients, deep RL, and RLHF
A table of \(Q\) works for 48 cells, not for a robot's joint angles or a game screen. Two ways to scale:
- Deep Q-networks replace the table with a network that maps a state to the \(Q\) of each action (DeepMind's Atari player, 2015).
- Policy gradients skip values: a network outputs action probabilities directly, and after each episode, actions that came before a high return are made more likely: the gradient of \(\sum \log \pi(a_t \mid s_t)\) weighted by the return. In the practice notebook this method (REINFORCE) teaches a network to balance a pole on a cart, from falling after a few dozen steps to the 500-step maximum within about 150 tries. PPO, a steadier version, trains most robots and the RL step of chat models.
RLHF (reinforcement learning from human feedback) is the last one at scale: people compare pairs of model answers, a reward model learns to predict their preferences (the evaluating-LLMs lesson's pairwise judging), and the language model is tuned with PPO to produce answers the reward model scores highly.
Why does a pure policy-gradient agent need many episodes even on a simple task?
- Its network is too large
- It learns only from whole-episode returns, which are noisy: a good action in an unlucky episode gets blamed with the rest
- It never explores
To scale, networks replace the table: deep Q-networks predict values, policy gradients make rewarded actions more likely, and RLHF tunes chat models toward human preferences.
Where it breaks: RL gets exactly what you reward
- Reward hacking. In a well-known OpenAI experiment, a boat-racing agent rewarded for hitting targets learned to circle a lagoon forever, catching fire and crashing, scoring more than any finisher and never finishing the race. Agents optimize the reward as written, not as meant. RLHF has the same risk: a chat model can learn to please the reward model (long, confident, flattering) rather than to be right.
- Sparse rewards. If the only reward is at a distant goal, random exploration may never reach it, and nothing is learned. Make the grid's station farther and walled off, and watch learning stall; shaping (small rewards for progress) helps but can itself be hacked.
- Instability. The targets move as the agent learns, and its own actions decide what data it sees. Deep RL runs are notoriously sensitive to seeds and settings (the experiments lesson's seed lottery, much worse).
- The real world is slow and costly. The notebook's pole needs 150 tries; a real robot can't fall 150 times an hour. Most robotics trains in simulation and then fights the gap to reality.
5. Direct Preference Optimization: alignment without a reward model
RLHF with PPO works, but running it is famously complicated: you must train a separate reward model network, freeze it, and then run an actor-critic reinforcement learning loop that samples tokens from the model in an inner loop. If the policy drifts too far from the base model, it can produce gibberish or game the reward model.
In 2023, Rafailov et al. noticed an exact mathematical shortcut. When an agent optimizes a reward function with a penalty for drifting (in KL divergence) from a frozen reference model \(\pi_{\text{ref}}\), the optimal reward can be written directly in terms of the model's own probabilities:
\[ r(x, y) = \beta \log \frac{\pi_\theta(y \mid x)}{\pi_{\text{ref}}(y \mid x)} + \beta \log Z(x) \]
where \(\beta\) is a temperature parameter and \(Z(x)\) is a normalizing factor. When people compare two completions \(y_w\) (winner) and \(y_l\) (loser) for a prompt \(x\), the Bradley-Terry preference probability is the sigmoid of their reward difference. Substituting the formula above makes \(Z(x)\) cancel out completely!
This gives Direct Preference Optimization (DPO). Instead of training a reward model and running PPO, DPO trains the model directly on preference pairs \((x, y_w, y_l)\) using binary cross-entropy:
\[ \mathcal{L}_{\text{DPO}}(\pi_\theta; \pi_{\text{ref}}) = -\mathbb{E}_{(x, y_w, y_l)} \left[ \log \sigma \left( \beta \log \frac{\pi_\theta(y_w \mid x)}{\pi_{\text{ref}}(y_w \mid x)} - \beta \log \frac{\pi_\theta(y_l \mid x)}{\pi_{\text{ref}}(y_l \mid x)} \right) \right] \]
The term inside the sigmoid is simply how much the policy has boosted the winning answer's likelihood relative to the reference, minus how much it boosted the losing answer's likelihood. If the model already prefers \(y_w\) over \(y_l\) more than the reference model did, the loss is small; if it prefers the loser, gradients push the policy to increase \(\pi_\theta(y_w)\) and decrease \(\pi_\theta(y_l)\).
One number decides how far the model may move: \(\beta\). The loss only sees the product of \(\beta\) and the policy's shift \(m\): how much more it now favors the winner over the loser than the reference did (the difference of the two log-ratios above). Predict first: if you double \(\beta\), does the model need to move more or less to reach the same loss?
In Direct Preference Optimization, what happens if \(\beta\) is set to a very large value?
- The policy changes rapidly and ignores the reference model
- The policy is anchored tightly to the reference model \(\pi_{\text{ref}}\), making updates very conservative
- It reverts to standard PPO
The same shift of 2 leaves the loss at 0.598 with \(\beta = 0.1\) but 0.127 with \(\beta = 1\): with a large \(\beta\), small moves already satisfy the loss, so training stops pushing early and the model stays close to the reference.
Direct Preference Optimization mathematically bypasses the reward model and PPO loop, optimizing preference pairs directly with cross-entropy against a frozen reference.
Why the reward model can be bypassed
- Standard RLHF solves:
\[ \max_\pi \mathbb{E}[r(x, y)] - \beta\, \mathbb{D}_{\text{KL}}(\pi \parallel \pi_{\text{ref}}) \]
- Calculus shows the optimal policy is an exponential tilt:
\[ \pi^*(y \mid x) = \frac{1}{Z(x)} \pi_{\text{ref}}(y \mid x) \exp\left(\frac{1}{\beta} r(x, y)\right) \]
- Taking logs and rearranging for \(r\):
\[ r(x, y) = \beta \log \frac{\pi^*(y \mid x)}{\pi_{\text{ref}}(y \mid x)} + \beta \log Z(x) \]
- The Bradley-Terry preference model depends only on the reward difference \(r(x, y_w) - r(x, y_l)\), so the unknown \(Z(x)\) cancels out!
- Therefore, we can fit \(\pi_\theta\) directly by maximizing the likelihood of human preference judgments, without ever explicitly training \(r\).
6. What to carry forward
- Agent, state, action, reward; the goal is the discounted return.
- Bellman: \(Q(s, a) = r + \gamma \max_{a'} Q(s', a')\); values flow backward from rewards.
- Q-learning: a step toward the temporal-difference target; explore with ε.
- Policy gradients raise the probability of actions before high returns; PPO builds on them.
- DPO directly tunes language models on preference pairs against a reference model, cutting out the separate reward model.
- The agent optimizes the reward you wrote: design it, and watch for hacking.
All lessons: AI from scratch. Sutton and Barto, "Reinforcement Learning: An Introduction" (free online), and OpenAI's "Spinning Up in Deep RL" are the standard next steps.
Last updated