Deep Reinforcement Learning
Deep Reinforcement Learning
Introduction to Deep Reinforcement Learning
Deep reinforcement learning (DRL) represents the marriage between deep learning and reinforcement learning. It enables a single algorithm to train AI agents capable of mastering many Atari games at superhuman levels—one algorithm across 40-50 games exceeding human capability. This was demonstrated in the seminal paper Human-level control through deep reinforcement learning by DeepMind.
Notable milestones in DRL include:
AlphaGo (2017): Defeated the world champion in Go, a game far more complex than chess due to its vast branching factor
AlphaStar and OpenAI Five: Tackled multiplayer strategy games like StarCraft and Dota, requiring long-term planning and multi-agent collaboration
ChatGPT-era models (2022): Applied reinforcement learning from human feedback (RLHF) to align language models with human preferences
Why Reinforcement Learning Instead of Supervised Learning?
In classic supervised learning, you teach by example. To solve the game of Go using supervised learning, one would collect historical game data: input = current board state, label = next move. However, this approach has several critical flaws:
Incomplete state coverage: The number of possible board states on a 13×13 Go board is astronomically large; historical games cannot cover them all.
No guarantee of optimal moves: Even professional players make suboptimal moves. The "ground truth" label may be a poor decision.
No concept of strategy: The model learns one-off mappings without understanding long-term strategy. When facing an unseen state, it cannot generalize.
Ill-defined ground truth: Even the best humans are not perfect, so the target is inherently flawed. The model can never surpass the best human.
Reinforcement learning addresses these issues: RL is about making good sequences of decisions through experience rather than examples. The agent explores the environment, discovers which sequences yield high cumulative reward, and learns strategies that can generalize beyond seen states.
Applications of RL extend beyond games:
Autonomous driving: Dynamic planning—slowing down for a red light that might turn green, etc.
Robotics: Controlling joints to move from point A to point B requires countless good sequential decisions.
Advertising and marketing: Planning a sequence of ads over time to lead a buyer to purchase—requires long-term thinking.
Core Vocabulary of Reinforcement Learning
Agent: The learner and decision-maker.
Environment: Everything the agent interacts with.
State (st): The current situation at time t.
Action (at): A decision made by the agent at time t.
Reward (rt): A scalar signal received after taking an action, indicating immediate goodness.
Observation (ot): What the agent perceives; may be less than the full state (e.g., fog of war in StarCraft).
Transition: The process from state st, taking action at, receiving ot and rt, and arriving at st+1.
Policy (π): A function that maps states to actions; the strategy the agent follows.
Return (R): The cumulative discounted reward: R=∑t=0∞γtrt, where γ∈[0,1] is the discount factor. Discounting reflects the time value of rewards—a dollar now is worth more than a dollar later.
Illustrative Example: The Recycling Game
A simple environment with 5 states:
State 2 (brown): Starting state.
State 1 (left): Garbage can, reward +2.
State 3 (center): Empty, reward 0.
State 4 (right of center): Chocolate packaging, reward +1.
State 5 (far right): Recycle bin, reward +10.
Actions: Left or Right. Terminal states: States 1 and 5 (episode ends). A rule: the garbage collector arrives in 3 minutes; each step takes 1 minute, so the agent cannot bounce back and forth indefinitely.
Goal: Maximize the return (sum of discounted rewards). With γ=1 (no discount), the best strategy is to go right all the way to the recycle bin for a total reward of 0+1+10=11. With γ=0.9, the optimal path is the same, but the discounted return is 0+1+0.9×10=10, then from state 2: 0+0.9×10=9.
Q-Learning and the Q-Table
Q-function Q(s,a) represents the expected return of taking action a in state s and then following the optimal policy thereafter. The Q-table is a matrix of size (number of states) × (number of actions) storing these values. If we have the optimal Q-table (Q∗), the agent can simply look up the best action: pick a with highest Q(s,a).
Backtracking to Fill the Q-Table
Using the recycling game, we build the tree of immediate rewards:
From state 2, left: immediate reward +2, terminal state 1.
Right from 2: reward 0, go to state 3.
From state 3, left: reward 0, back to state 2; right: reward +1, go to state 4.
From state 4, left: reward 0, back to state 3; right: reward +10, terminal state 5.
Now discount with γ=0.9 and backtrack:
From state 4, best future return from right is 10 (terminal). So Q(4,right)=10 (immediate +10, no future). Q(4,left)=0+0.9×Q(3,best).
From state 3, going right gives 1+0.9×10=10; going left gives 0+0.9×Q(2,best).
This can be solved iteratively. The final Q-table is:
State | Action Left | Action Right |
|---|---|---|
1 (terminal) | - | - |
2 | 2 (terminal) | 9 (from 0 + 0.9×10) |
3 | 8.1 (0 + 0.9×9) | 10 (1 + 0.9×10) |
4 | 9 (0 + 0.9×10) | 10 (terminal) |
5 (terminal) | - | - |
The Bellman Optimality Equation
The key equation that the optimal Q-function satisfies:
where:
r(s,a) is the immediate reward received after taking action a in state s
s′ is the next state after the action
γ is the discount factor
maxa′Q∗(s′,a′) is the maximum Q-value over all actions in the next state
This equation captures the idea of backtracking: the optimal Q-value equals the immediate reward plus the discounted best future return. The optimal policy is then:
Deep Q-Learning: Replacing the Q-Table with a Neural Network
In large state-action spaces (e.g., Go, Atari games), the Q-table becomes infeasible due to memory and computation. Instead, we use a deep neural network as a function approximator: Q(s,a;θ) where θ are the network parameters.
Architecture for Atari Breakout:
Input: Preprocessed screen frames (grayscale, cropped, downsampled, 4-frame history to capture motion)
Output: Q-values for each action (e.g., left, right, idle)
Network: Convolutional layers followed by fully connected layers
Training Without Labels
We lack supervised labels (x, y pairs). Instead, we use the Bellman equation to generate target values:
Forward pass: For current state s, compute Q(s,a;θ) for all actions.
Choose action: a=argmaxaQ(s,a;θ) (or use epsilon-greedy).
Execute action: Receive reward r and next state s′.
Compute target y:
If s′ is terminal: y=r
Otherwise: y=r+γmaxa′Q(s′,a′;θ)
Loss function: L=(y−Q(s,a;θ))2
Backpropagate: Update θ to minimize this loss.
The target y is fixed (not differentiated) — it uses the current network to estimate future returns, which improves as the network improves. This is a form of bootstrapping.
Key Training Techniques for Deep Q-Learning
1. Preprocessing
Convert to grayscale
Crop irrelevant areas (e.g., score, background)
Downsample to reduce dimensions
Stack multiple frames (e.g., 4) to provide velocity/motion information
2. Terminal State Handling
When the next state is terminal, the target is simply the immediate reward — no Bellman future term.
3. Experience Replay
Store transitions (s,a,r,s′,done) in a replay memory D. During training, sample a random minibatch from D instead of using consecutive transitions. This:
Breaks correlation between successive experiences (like training on all cats then all dogs)
Increases data efficiency by reusing experiences multiple times
Reduces variance in updates
4. Epsilon-Greedy Exploration (ϵ-greedy)
To avoid getting stuck in local optima (e.g., never discovering the high-reward recycle bin), with probability ϵ, take a random action. This encourages exploration of new states. Over time, ϵ is typically annealed (e.g., from 1.0 down to 0.1), shifting from exploration to exploitation of learned knowledge.
Complete Deep Q-Learning Algorithm (Pseudocode)
Initialize Q-network with random weights θ, replay memory D
For each episode:
Start from initial state s
Until terminal:
Preprocess state: s→ϕ(s)
With probability ϵ: choose random action a; else a=argmaxaQ(ϕ(s),a;θ)
Execute a, observe reward r and next state s′
Preprocess s′: ϕ(s′)
Store transition (ϕ(s),a,r,ϕ(s′),done) in D
Sample random minibatch from D
For each transition in minibatch:
If done: y=r
Else: y=r+γmaxa′Q(ϕ(s′),a′;θ)
Compute loss: L=N1∑(y−Q(ϕ(s),a;θ))2
Update θ via gradient descent
Set s=s′
Advanced Topics in RL
Montezuma's Revenge — The Challenge of Sparse Rewards
This Atari game has a very delayed reward (e.g., reaching a key after many steps). With random initialization, the agent is extremely unlikely to ever stumble upon the key. Humans use prior knowledge (ladders, ropes, enemies) to guide exploration. Solutions include imitation learning (starting from human demonstrations) or using curiosity-driven exploration.
Beyond Q-Learning: Proximal Policy Optimization (PPO)
Q-learning is a value-based method: it learns Q-values, then derives the policy. PPO is a policy-based method that directly optimizes the policy (a probability distribution over actions). Advantages:
Works well with continuous action spaces (e.g., steering angle in autonomous driving)
Often more stable and sample-efficient
Uses an advantage function that measures how much better an action is than the average
Key papers: TRPO and PPO by Schulman et al. (2015, 2017). Another recent algorithm is DPO (Direct Preference Optimization) from Stanford (2023).
Competitive Self-Play
Agents can learn by playing against copies of themselves. In sumo wrestling, emergent behaviors arise (e.g., lowering center of gravity, attacking feet). Multiple copies of the same model are initialized differently, trained, and the best models are periodically copied to others.
Multi-Agent and Partial Observability
Games like StarCraft and Dota involve:
Partial observability: fog of war (observation ≠ state)
Multi-agent coordination: 5v5 team play
Long time horizons
Reinforcement Learning from Human Feedback (RLHF)
RLHF was the key technique that enabled the leap from GPT-2 to ChatGPT, aligning language models with human preferences for helpfulness, safety, and politeness.
Limitations of Standard Pretrained Language Models
Next-token prediction on internet text does not optimize for helpfulness. A model might complete "My laptop won't turn on. What should I do?" with factual but unhelpful text (e.g., "Laptops sometimes don't turn on due to power issues") instead of giving actionable advice.
The model has no concept of being polite, concise, or aligned with human values.
Step 1: Supervised Fine-Tuning (SFT)
Collect a dataset of human-written prompt-response pairs (e.g., 13,000 examples for InstructGPT).
Fine-tune the pretrained language model on this dataset using standard next-token prediction loss.
Limitation: This teaches imitation, not preference optimization. The model learns to mimic human-written responses, but cannot go beyond them, and the dataset is costly to produce.
Step 2: Training a Reward Model (RM)
Goal: Learn a proxy for human preferences that can be applied at scale.
Data collection: Show human labelers multiple responses (sampled from the SFT model) to the same prompt. Labelers rank or compare them (e.g., "Response A is better than B").
Architecture: Initialize from the SFT model, but replace the softmax output layer with a scalar reward head (a linear layer outputting a single number).
Training loss: Use pairwise comparisons to encourage the model to assign higher rewards to preferred responses. The loss function (often Bradley-Terry) maximizes the log probability that the preferred response gets a higher reward.
After training, the reward model can evaluate any prompt-response pair and output a score approximating human preference.
Step 3: Reinforcement Learning (RLHF)
The RL setup is analogous to the games we saw, with:
Agent: The language model being fine-tuned
Environment: Space of possible prompts and continuations
State: Current prompt + generated tokens so far
Action: Next token chosen by the model (policy)
Reward: Score from the trained reward model (only at the end of the full response; intermediate rewards are typically 0)
Episode: One full prompt-response generation
The agent (language model) interacts with the environment (prompts) and receives a reward only at the end of the sequence. It uses a policy gradient method (e.g., PPO) to maximize expected reward.
Why RLHF instead of just SFT? RLHF allows the model to explore different responses and be rewarded for those that humans prefer, even if those responses were not explicitly in the SFT dataset. It scales preference learning beyond human-written examples.
Key Points
The reward model acts as a scalable proxy for human evaluation.
This method is more efficient than SFT because asking humans to compare two responses is faster than asking them to write responses from scratch.
RLHF produces models that are aligned with human preferences, leading to significant improvements in helpfulness and safety (as seen in ChatGPT, Claude, etc.).

Ask anything
We've read this whole study set, so questions about it get the best answers.