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\)?

\(-1 + 0.9 \times 0 = -1\). If the next cell were worth 10: \(-1 + 0.9 \times 10 = 8\). Values are built from the rewards ahead, discounted.

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
  1. 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).
  2. 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.
  3. 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')\).
  4. 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.
  5. 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:

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?

Credit assignment with noisy returns needs many samples to average out (C4's 1/√N). Baselines (subtracting the average return) and learned value estimates (actor-critic, PPO) reduce the noise.

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

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?

\(\beta\) controls the strength of the KL divergence penalty against drifting from the frozen reference model. Higher \(\beta\) keeps \(\pi_\theta\) closer to \(\pi_{\text{ref}}\).

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
  1. Standard RLHF solves:
    \[ \max_\pi \mathbb{E}[r(x, y)] - \beta\, \mathbb{D}_{\text{KL}}(\pi \parallel \pi_{\text{ref}}) \]
  2. 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) \]
  3. 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) \]
  4. 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!
  5. 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

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