1. Home
  2. Explore
  3. Computer Science
  4. Deep Reinforcement Learning

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

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:

  1. Incomplete state coverage: The number of possible board states on a 13×13 Go board is astronomically large; historical games cannot cover them all.

  2. No guarantee of optimal moves: Even professional players make suboptimal moves. The "ground truth" label may be a poor decision.

  3. No concept of strategy: The model learns one-off mappings without understanding long-term strategy. When facing an unseen state, it cannot generalize.

  4. 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 (sts_tst​): The current situation at time ttt.

  • Action (ata_tat​): A decision made by the agent at time ttt.

  • Reward (rtr_trt​): A scalar signal received after taking an action, indicating immediate goodness.

  • Observation (oto_tot​): What the agent perceives; may be less than the full state (e.g., fog of war in StarCraft).

  • Transition: The process from state sts_tst​, taking action ata_tat​, receiving oto_tot​ and rtr_trt​, and arriving at st+1s_{t+1}st+1​.

  • Policy (π\piπ): A function that maps states to actions; the strategy the agent follows.

  • Return (RRR): The cumulative discounted reward: R=∑t=0∞γtrtR = \sum_{t=0}^{\infty} \gamma^t r_tR=∑t=0∞​γtrt​, where γ∈[0,1]\gamma \in [0,1]γ∈[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\gamma = 1γ=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=110 + 1 + 10 = 110+1+10=11. With γ=0.9\gamma = 0.9γ=0.9, the optimal path is the same, but the discounted return is 0+1+0.9×10=100 + 1 + 0.9 \times 10 = 100+1+0.9×10=10, then from state 2: 0+0.9×10=90 + 0.9 \times 10 = 90+0.9×10=9.


Q-Learning and the Q-Table

Q-function Q(s,a)Q(s, a)Q(s,a) represents the expected return of taking action aaa in state sss 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∗Q^*Q∗), the agent can simply look up the best action: pick aaa with highest Q(s,a)Q(s, a)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\gamma = 0.9γ=0.9 and backtrack:

  • From state 4, best future return from right is 10 (terminal). So Q(4,right)=10Q(4, \text{right}) = 10Q(4,right)=10 (immediate +10, no future). Q(4,left)=0+0.9×Q(3,best)Q(4, \text{left}) = 0 + 0.9 \times Q(3, \text{best})Q(4,left)=0+0.9×Q(3,best).

  • From state 3, going right gives 1+0.9×10=101 + 0.9 \times 10 = 101+0.9×10=10; going left gives 0+0.9×Q(2,best)0 + 0.9 \times Q(2, \text{best})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:

Q∗(s,a)=r(s,a)+γmax⁡a′Q∗(s′,a′)Q^*(s, a) = r(s, a) + \gamma \max_{a'} Q^*(s', a')Q∗(s,a)=r(s,a)+γmaxa′​Q∗(s′,a′)

where:

  • r(s,a)r(s, a)r(s,a) is the immediate reward received after taking action aaa in state sss

  • s′s's′ is the next state after the action

  • γ\gammaγ is the discount factor

  • max⁡a′Q∗(s′,a′)\max_{a'} Q^*(s', a')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:

π∗(s)=arg⁡max⁡aQ∗(s,a)\pi^*(s) = \arg\max_a Q^*(s, a)π∗(s)=argmaxa​Q∗(s,a)

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;θ)Q(s, a; \theta)Q(s,a;θ) where θ\thetaθ 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:

  1. Forward pass: For current state sss, compute Q(s,a;θ)Q(s, a; \theta)Q(s,a;θ) for all actions.

  2. Choose action: a=arg⁡max⁡aQ(s,a;θ)a = \arg\max_a Q(s, a; \theta)a=argmaxa​Q(s,a;θ) (or use epsilon-greedy).

  3. Execute action: Receive reward rrr and next state s′s's′.

  4. Compute target yyy:

    • If s′s's′ is terminal: y=ry = ry=r

    • Otherwise: y=r+γmax⁡a′Q(s′,a′;θ)y = r + \gamma \max_{a'} Q(s', a'; \theta)y=r+γmaxa′​Q(s′,a′;θ)

  5. Loss function: L=(y−Q(s,a;θ))2L = (y - Q(s, a; \theta))^2L=(y−Q(s,a;θ))2

  6. Backpropagate: Update θ\thetaθ to minimize this loss.

The target yyy 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)(s, a, r, s', \text{done})(s,a,r,s′,done) in a replay memory DDD. During training, sample a random minibatch from DDD 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 (ϵ\epsilonϵ-greedy)

To avoid getting stuck in local optima (e.g., never discovering the high-reward recycle bin), with probability ϵ\epsilonϵ, take a random action. This encourages exploration of new states. Over time, ϵ\epsilonϵ 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)

  1. Initialize Q-network with random weights θ\thetaθ, replay memory DDD

  2. For each episode:

    • Start from initial state sss

    • Until terminal:

      • Preprocess state: s→ϕ(s)s \rightarrow \phi(s)s→ϕ(s)

      • With probability ϵ\epsilonϵ: choose random action aaa; else a=arg⁡max⁡aQ(ϕ(s),a;θ)a = \arg\max_a Q(\phi(s), a; \theta)a=argmaxa​Q(ϕ(s),a;θ)

      • Execute aaa, observe reward rrr and next state s′s's′

      • Preprocess s′s's′: ϕ(s′)\phi(s')ϕ(s′)

      • Store transition (ϕ(s),a,r,ϕ(s′),done)(\phi(s), a, r, \phi(s'), \text{done})(ϕ(s),a,r,ϕ(s′),done) in DDD

      • Sample random minibatch from DDD

      • For each transition in minibatch:

        • If done: y=ry = ry=r

        • Else: y=r+γmax⁡a′Q(ϕ(s′),a′;θ)y = r + \gamma \max_{a'} Q(\phi(s'), a'; \theta)y=r+γmaxa′​Q(ϕ(s′),a′;θ)

      • Compute loss: L=1N∑(y−Q(ϕ(s),a;θ))2L = \frac{1}{N} \sum (y - Q(\phi(s), a; \theta))^2L=N1​∑(y−Q(ϕ(s),a;θ))2

      • Update θ\thetaθ via gradient descent

      • Set s=s′s = s'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.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent