RL lecture notes (archive)5 / 7

Lesson 5

Deep RL

These are my original lecture notes, kept as they were. They're being rebuilt into the Reinforcement learning course.

Part 1: Foundational Concepts

1.1 The Two Approaches to RL

There are fundamentally two ways to solve an RL problem:

  1. Value-Based Methods: Learn how "good" states or state-action pairs are, then act greedily with respect to those values
  2. Policy-Based Methods: Directly learn a mapping from states to actions (a policy)

Analogy: Imagine learning to play chess.

  • Value-based: You learn to evaluate board positions ("this position is worth +3 pawns") and pick moves that lead to the best positions
  • Policy-based: You directly learn rules like "in this type of position, move the knight here"

Both approaches have trade-offs, and modern algorithms often combine them.


Part 2: Q-Learning Foundation

2.1 What is a Q-Function?

The Q-function (or action-value function) answers: "If I'm in state ss, take action aa, and then act optimally forever after, what's my expected total discounted reward?"

Qπ(s,a)=Eπ[∑t=0∞γtrt∣s0=s,a0=a]Q^\pi(s, a) = \mathbb{E}_\pi\left[\sum_{t=0}^{\infty} \gamma^t r_t \mid s_0 = s, a_0 = a\right]

The optimal Q-function Q∗(s,a)Q^*(s,a) is the Q-function when following the optimal policy.

Intuition: Think of Q(s,a)Q(s,a) as a "cheat sheet" that tells you the long-term value of each action in each situation. If you had a perfect cheat sheet, you'd just look up your current state and pick the action with the highest value.

2.2 The Bellman Equation

The key insight is that Q-values have a recursive structure. The value of taking action aa in state ss equals:

  • The immediate reward you get, plus
  • The discounted value of the best action in the next state

Q∗(s,a)=Es′[r+γmax⁡a′Q∗(s′,a′)∣s,a]Q^*(s, a) = \mathbb{E}_{s'}\left[r + \gamma \max_{a'} Q^*(s', a') \mid s, a\right]

Intuition: "How good is this move?" = "What do I get now?" + "How good is my best option afterward?"

2.3 Tabular Q-Learning Algorithm

Q-learning learns Q∗Q^* through trial and error without knowing the environment dynamics.

The Update Rule: Q(s,a)←Q(s,a)+α[r+γmax⁡a′Q(s′,a′)−Q(s,a)]Q(s, a) \leftarrow Q(s, a) + \alpha \left[ r + \gamma \max_{a'} Q(s', a') - Q(s, a) \right]

Where:

  • α\alpha is the learning rate
  • r+γmax⁡a′Q(s′,a′)r + \gamma \max_{a'} Q(s', a') is the TD target (our new estimate)
  • Q(s,a)Q(s, a) is our current estimate
  • The bracketed term is the TD error δ\delta

Plain English:

  1. Try an action, see what happens
  2. Compute what you thought would happen vs. what actually happened (plus your best guess for the future)
  3. Nudge your estimate toward reality

Why "max"?: Q-learning is off-policy—it learns about the optimal policy while potentially following a different (exploratory) policy. The max assumes you'll act optimally in the future, regardless of what you actually do during learning.

2.4 Exploration vs. Exploitation

To learn good Q-values, you need to try different actions. Common strategy:

ϵ\epsilon-greedy: With probability ϵ\epsilon, take a random action; otherwise, take arg⁡max⁡aQ(s,a)\arg\max_a Q(s,a)

Typically ϵ\epsilon starts high (explore) and decays over time (exploit).


Part 3: Policy Gradient Foundation

3.1 Why Policy Gradients?

Q-learning struggles with:

  1. Continuous action spaces: Can't compute max⁡aQ(s,a)\max_a Q(s,a) when a∈Rna \in \mathbb{R}^n
  2. Stochastic optimal policies: Sometimes randomness is optimal (e.g., rock-paper-scissors)

Policy gradients directly optimize a parameterized policy πθ(a∣s)\pi_\theta(a|s).

3.2 The Objective

We want to maximize expected return:

J(θ)=Eτ∼πθ[∑t=0Tγtrt]=Eτ∼πθ[R(τ)]J(\theta) = \mathbb{E}_{\tau \sim \pi_\theta}\left[\sum_{t=0}^{T} \gamma^t r_t\right] = \mathbb{E}_{\tau \sim \pi_\theta}[R(\tau)]

Where τ=(s0,a0,r0,s1,a1,r1,…)\tau = (s_0, a_0, r_0, s_1, a_1, r_1, \ldots) is a trajectory.

3.3 The Policy Gradient Theorem

The Problem: How do we take gradients through an expectation over trajectories that depend on θ\theta?

The Solution (the "log-derivative trick"):

∇θJ(θ)=Eτ∼πθ[R(τ)∇θlog⁡P(τ∣θ)]\nabla_\theta J(\theta) = \mathbb{E}_{\tau \sim \pi_\theta}\left[R(\tau) \nabla_\theta \log P(\tau | \theta)\right]

Since the transition dynamics don't depend on θ\theta, this simplifies to:

∇θJ(θ)=Eτ∼πθ[∑t=0T∇θlog⁡πθ(at∣st)⋅Gt]\nabla_\theta J(\theta) = \mathbb{E}_{\tau \sim \pi_\theta}\left[\sum_{t=0}^{T} \nabla_\theta \log \pi_\theta(a_t|s_t) \cdot G_t\right]

Where Gt=∑k=tTγk−trkG_t = \sum_{k=t}^{T} \gamma^{k-t} r_k is the return from time tt.

Derivation Sketch:

  1. ∇θE[f(x)]=∇θ∫pθ(x)f(x)dx\nabla_\theta \mathbb{E}[f(x)] = \nabla_\theta \int p_\theta(x) f(x) dx
  2. =∫∇θpθ(x)f(x)dx= \int \nabla_\theta p_\theta(x) f(x) dx
  3. =∫pθ(x)∇θpθ(x)pθ(x)f(x)dx= \int p_\theta(x) \frac{\nabla_\theta p_\theta(x)}{p_\theta(x)} f(x) dx (multiply by pθpθ\frac{p_\theta}{p_\theta})
  4. =∫pθ(x)∇θlog⁡pθ(x)f(x)dx= \int p_\theta(x) \nabla_\theta \log p_\theta(x) f(x) dx (using ∇log⁡f=∇ff\nabla \log f = \frac{\nabla f}{f})
  5. =Ex∼pθ[f(x)∇θlog⁡pθ(x)]= \mathbb{E}_{x \sim p_\theta}[f(x) \nabla_\theta \log p_\theta(x)]

3.4 REINFORCE Algorithm

The simplest policy gradient algorithm:

  1. Collect a trajectory τ\tau using πθ\pi_\theta
  2. Compute returns GtG_t for each timestep
  3. Update: θ←θ+α∑t∇θlog⁡πθ(at∣st)⋅Gt\theta \leftarrow \theta + \alpha \sum_t \nabla_\theta \log \pi_\theta(a_t|s_t) \cdot G_t

Intuition:

  • If an action led to high return, increase its probability (Gt>0G_t > 0 pushes probability up)
  • If an action led to low return, decrease its probability
  • The gradient ∇θlog⁡πθ(at∣st)\nabla_\theta \log \pi_\theta(a_t|s_t) points in the direction that increases the probability of action ata_t

Analogy: Imagine learning to throw darts. You try different throws, and for throws that land close to the bullseye, you think "do more like that." For throws that miss badly, you think "do less like that." Policy gradients formalize this intuition.

3.5 The Variance Problem and Baselines

Raw REINFORCE has high variance—returns vary wildly between episodes, making learning unstable.

Solution: Subtract a baseline b(s)b(s) from the return:

∇θJ(θ)=E[∑t∇θlog⁡πθ(at∣st)⋅(Gt−b(st))]\nabla_\theta J(\theta) = \mathbb{E}\left[\sum_t \nabla_\theta \log \pi_\theta(a_t|s_t) \cdot (G_t - b(s_t))\right]

Key insight: Subtracting any baseline that doesn't depend on the action preserves the expected gradient (it's unbiased) but can dramatically reduce variance.

Why does this work mathematically? Ea∼π[∇θlog⁡πθ(a∣s)⋅b(s)]=b(s)⋅Ea∼π[∇θlog⁡πθ(a∣s)]=b(s)⋅∇θ∑aπθ(a∣s)=b(s)⋅∇θ1=0\mathbb{E}_{a \sim \pi}[\nabla_\theta \log \pi_\theta(a|s) \cdot b(s)] = b(s) \cdot \mathbb{E}_{a \sim \pi}[\nabla_\theta \log \pi_\theta(a|s)] = b(s) \cdot \nabla_\theta \sum_a \pi_\theta(a|s) = b(s) \cdot \nabla_\theta 1 = 0

Best baseline: The value function V(s)V(s) is provably close to optimal. This gives us the advantage:

A(s,a)=Q(s,a)−V(s)=Gt−V(st)A(s,a) = Q(s,a) - V(s) = G_t - V(s_t)

Intuition: Instead of asking "was this return good?", we ask "was this return better than average for this state?" This centers our updates and reduces variance.


Part 4: Deep Q-Networks (DQN)

4.1 The Challenge of Scale

Tabular Q-learning stores a value for every (s,a)(s, a) pair. This is impossible for:

  • Atari games (state space ≈ 25684×84×4256^{84 \times 84 \times 4})
  • Continuous states

Solution: Approximate Q(s,a)Q(s, a) with a neural network Q(s,a;θ)Q(s, a; \theta).

4.2 Naive Approach and Its Problems

Naively applying Q-learning with neural networks: θ←θ−α∇θ(r+γmax⁡a′Q(s′,a′;θ)−Q(s,a;θ))2\theta \leftarrow \theta - \alpha \nabla_\theta \left(r + \gamma \max_{a'} Q(s', a'; \theta) - Q(s, a; \theta)\right)^2

This fails catastrophically. Why?

  1. Correlated samples: Sequential experiences (st,at,rt,st+1)(s_t, a_t, r_t, s_{t+1}) are highly correlated. Neural networks trained on correlated data overfit to recent experience and forget past learning.

  2. Non-stationary targets: The target r+γmax⁡a′Q(s′,a′;θ)r + \gamma \max_{a'} Q(s', a'; \theta) changes every time we update θ\theta. It's like trying to catch a moving target—the network chases its own tail.

4.3 DQN's Innovations

Innovation 1: Experience Replay

Store transitions (s,a,r,s′)(s, a, r, s') in a replay buffer D\mathcal{D}. Sample random mini-batches for training.

Benefits:

  • Breaks correlation between consecutive samples
  • Each experience can be used multiple times
  • Smooths out the learning distribution

Innovation 2: Target Network

Maintain a separate target network Q(s,a;θ−)Q(s, a; \theta^-) that's updated slowly.

  • The main network θ\theta is updated every step
  • The target network θ−\theta^- is copied from θ\theta every CC steps (or soft-updated)

This stabilizes the target: The thing we're trying to predict doesn't change every update.

4.4 DQN Algorithm

Loss function: L(θ)=E(s,a,r,s′)∼D[(r+γmax⁡a′Q(s′,a′;θ−)−Q(s,a;θ))2]L(\theta) = \mathbb{E}_{(s,a,r,s') \sim \mathcal{D}}\left[\left(r + \gamma \max_{a'} Q(s', a'; \theta^-) - Q(s, a; \theta)\right)^2\right]

Algorithm:

Initialize replay buffer D, Q-network θ, target network θ⁻ = θ
For each episode:
    For each step:
        1. Select action: a = ε-greedy(Q(s, ·; θ))
        2. Execute a, observe r, s'
        3. Store (s, a, r, s') in D
        4. Sample mini-batch from D
        5. Compute targets: y = r + γ max_a' Q(s', a'; θ⁻)
        6. Update θ by gradient descent on (y - Q(s,a;θ))²
        7. Every C steps: θ⁻ ← θ

Intuition: DQN is like studying from flashcards (replay buffer) with an answer key that's updated periodically (target network), rather than constantly rewriting the answer key while studying.

4.5 Implementation Notes

Replay Buffer: Use a circular buffer (collections.deque or numpy array with index wrapping). Typical size: 1M transitions. Don't start training until buffer has ~50k samples for diversity.

# Simple replay buffer sampling
indices = np.random.randint(0, len(buffer), size=batch_size)
batch = [buffer[i] for i in indices]

Target Network Update: Two options:

  • Hard update: Copy weights every C steps (e.g., C=10,000)
  • Soft update: Every step do θ⁻ ← τθ + (1-τ)θ⁻ with τ ≈ 0.005

Soft updates are smoother and often work better.

Frame Stacking (Atari): Stack last 4 frames as state input — gives velocity information from static images. Also skip frames (act every 4th frame, repeat action) to speed up training.

Network Architecture: For images, use CNN → dense. For vector states, 2-3 dense layers with ReLU, typically 256-512 units. Final layer outputs Q-value for each action (no activation).

Numerical Stability:

  • Clip rewards to [-1, 1] (helps with varying reward scales)
  • Clip gradients (max norm ~10)
  • Use Huber loss instead of MSE (less sensitive to outliers): Lδ(y,Q)={12(y−Q)2if ∣y−Q∣≤δδ∣y−Q∣−12δ2otherwiseL_\delta(y, Q) = \begin{cases} \frac{1}{2}(y-Q)^2 & \text{if } |y-Q| \leq \delta \\ \delta|y-Q| - \frac{1}{2}\delta^2 & \text{otherwise} \end{cases}

Epsilon Schedule: Linear decay from 1.0 → 0.1 over first 1M steps, then hold at 0.1.


Part 5: Double DQN

5.1 The Maximization Bias Problem

Standard Q-learning uses max⁡a′Q(s′,a′)\max_{a'} Q(s', a') for the target. This causes overestimation.

Why? The max operator is positively biased when there's noise. If you have noisy estimates and take the max, you're likely to pick an overestimated value.

Example: Suppose in state s′s' all actions have true value 0, but your estimates are [−0.2,+0.3,−0.1,+0.2][-0.2, +0.3, -0.1, +0.2] due to noise. The max is +0.3+0.3, which overestimates the true max of 0.

This bias propagates and compounds through the Bellman updates, leading to overly optimistic Q-values.

5.2 The Double Q-Learning Solution

Key insight: Separate action selection from action evaluation.

In DQN, the target is: yDQN=r+γQ(s′,arg⁡max⁡a′Q(s′,a′;θ−);θ−)y_{DQN} = r + \gamma Q(s', \arg\max_{a'} Q(s', a'; \theta^-); \theta^-)

The same network picks the action AND evaluates it.

Double DQN: Use the online network to select the best action, but the target network to evaluate it:

yDDQN=r+γQ(s′,arg⁡max⁡a′Q(s′,a′;θ);θ−)y_{DDQN} = r + \gamma Q\left(s', \arg\max_{a'} Q(s', a'; \theta); \theta^-\right)

Intuition: It's like getting a second opinion. You might think action A is best, but let's check its value with a different (more stable) estimate before committing.

5.3 Why This Helps

If the online network overestimates action aa's value, it might select aa. But the target network, with different noise, is unlikely to also overestimate aa. The evaluation provides a more grounded estimate.

The improvement is simple to implement (one line change) but often yields significant gains.

5.4 Implementation Notes

The Change is Trivial: In your DQN code, change:

# DQN target
next_q_values = target_net(next_states)
max_next_q = next_q_values.max(dim=1)[0]
 
# Double DQN target (two lines change)
next_actions = online_net(next_states).argmax(dim=1)  # Selection with online
max_next_q = target_net(next_states).gather(1, next_actions.unsqueeze(1))  # Evaluation with target

When to Use: Always use Double DQN over vanilla DQN — there's no downside and it's trivial to implement. The only reason to use vanilla DQN is for educational purposes.


Part 6: Actor-Critic Methods and A2C

6.1 The Actor-Critic Idea

Problem with REINFORCE: We wait until episode end to get returns, leading to high variance and slow learning.

Idea: Combine policy gradients (the "actor") with value function estimation (the "critic"):

  • Actor: Policy πθ(a∣s)\pi_\theta(a|s) that selects actions
  • Critic: Value function Vϕ(s)V_\phi(s) that evaluates states

Analogy: The actor is a student taking actions; the critic is a teacher providing feedback. The teacher doesn't tell the student what to do, just whether their choices were good or bad.

6.2 Advantage Actor-Critic

The policy gradient with baseline: ∇θJ(θ)=E[∑t∇θlog⁡πθ(at∣st)⋅A(st,at)]\nabla_\theta J(\theta) = \mathbb{E}\left[\sum_t \nabla_\theta \log \pi_\theta(a_t|s_t) \cdot A(s_t, a_t)\right]

We estimate advantage as: A^(st,at)=rt+γVϕ(st+1)−Vϕ(st)\hat{A}(s_t, a_t) = r_t + \gamma V_\phi(s_{t+1}) - V_\phi(s_t)

This is called the TD error estimate of advantage. It's biased (since VϕV_\phi is approximate) but low variance.

6.3 A2C: Advantage Actor-Critic

A2C is the synchronous version of A3C (Asynchronous Advantage Actor-Critic).

Architecture: Typically a shared network with two heads:

  • Policy head: outputs πθ(a∣s)\pi_\theta(a|s)
  • Value head: outputs Vϕ(s)V_\phi(s)

Losses:

Policy loss (actor): Lπ=−E[log⁡πθ(at∣st)⋅A^t]L_\pi = -\mathbb{E}\left[\log \pi_\theta(a_t|s_t) \cdot \hat{A}_t\right]

Value loss (critic): LV=E[(Vϕ(st)−Gt)2]L_V = \mathbb{E}\left[(V_\phi(s_t) - G_t)^2\right]

Where GtG_t is the actual return (or a bootstrapped estimate).

Entropy bonus (encourages exploration): LH=−E[∑aπθ(a∣s)log⁡πθ(a∣s)]L_H = -\mathbb{E}\left[\sum_a \pi_\theta(a|s) \log \pi_\theta(a|s)\right]

Total loss: L=Lπ+c1LV−c2LHL = L_\pi + c_1 L_V - c_2 L_H

6.4 A2C Algorithm

Initialize policy π_θ, value function V_φ
For each iteration:
    1. Collect n steps of experience using π_θ (across parallel envs)
    2. Compute advantages: Â_t = r_t + γV(s_{t+1}) - V(s_t)
       (or use GAE - see below)
    3. Compute policy gradient: g = Σ_t ∇_θ log π_θ(a_t|s_t) · Â_t
    4. Update θ using g
    5. Update φ to minimize value prediction error

6.5 Generalized Advantage Estimation (GAE)

There's a bias-variance tradeoff in advantage estimation:

  • 1-step TD: A^t(1)=rt+γV(st+1)−V(st)\hat{A}^{(1)}_t = r_t + \gamma V(s_{t+1}) - V(s_t) — low variance, high bias
  • Monte Carlo: A^t(∞)=Gt−V(st)\hat{A}^{(\infty)}_t = G_t - V(s_t) — high variance, low bias

GAE interpolates using parameter λ∈[0,1]\lambda \in [0,1]:

A^tGAE=∑l=0∞(γλ)lδt+l\hat{A}^{GAE}_t = \sum_{l=0}^{\infty} (\gamma \lambda)^l \delta_{t+l}

Where δt=rt+γV(st+1)−V(st)\delta_t = r_t + \gamma V(s_{t+1}) - V(s_t) is the TD error.

  • λ=0\lambda = 0: Pure TD (low variance, high bias)
  • λ=1\lambda = 1: Pure MC (high variance, low bias)
  • λ≈0.95\lambda \approx 0.95: Common sweet spot

6.6 Implementation Notes

Computing GAE in Practice: Work backwards from the end of the trajectory:

advantages = []
gae = 0
for t in reversed(range(T)):
    delta = rewards[t] + gamma * values[t+1] * (1 - dones[t]) - values[t]
    gae = delta + gamma * lam * (1 - dones[t]) * gae
    advantages.insert(0, gae)

Parallel Environments: A2C typically runs N parallel environments (e.g., N=16) to collect diverse samples. Use vectorized environments (e.g., gym.vector.SyncVectorEnv). This is critical for sample diversity since we're on-policy.

Shared vs Separate Networks:

  • Shared (common): One network, two heads. Faster, acts as regularization.
  • Separate: Independent actor and critic networks. More capacity, sometimes more stable.

For most tasks, shared works fine. Use separate if you see the value head dominating gradients.

Entropy Coefficient: Start with c2≈0.01c_2 \approx 0.01. If policy collapses to deterministic too fast, increase it. If policy stays too random, decrease it. Some implementations decay it over training.

The Expectation is a Sample Average: The theoretical gradient is: ∇θJ=E[∇θlog⁡πθ(a∣s)⋅A^]\nabla_\theta J = \mathbb{E}[\nabla_\theta \log \pi_\theta(a|s) \cdot \hat{A}]

In code, this is just the mean over your batch:

log_probs = dist.log_prob(actions)  # Shape: (batch_size,)
policy_loss = -(log_probs * advantages).mean()  # Sample average ≈ expectation

Gradient Clipping: Clip gradient norm to ~0.5 for stability:

torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=0.5)

Part 7: Continuous Control - DDPG

7.1 The Continuous Action Challenge

DQN can't handle continuous actions because:

  1. We can't enumerate all actions to compute max⁡aQ(s,a)\max_a Q(s,a)
  2. We can't do ϵ\epsilon-greedy over infinite action spaces

DDPG (Deep Deterministic Policy Gradient) solves this.

7.2 Key Idea: Deterministic Policy Gradient

Instead of stochastic πθ(a∣s)\pi_\theta(a|s), learn a deterministic policy μθ(s)\mu_\theta(s) that directly outputs an action.

The deterministic policy gradient theorem: ∇θJ(θ)=Es∼ρμ[∇θμθ(s)⋅∇aQ(s,a)∣a=μθ(s)]\nabla_\theta J(\theta) = \mathbb{E}_{s \sim \rho^\mu}\left[\nabla_\theta \mu_\theta(s) \cdot \nabla_a Q(s, a)|_{a=\mu_\theta(s)}\right]

Intuition:

  1. The critic tells us how QQ changes with respect to action aa
  2. The actor tells us how aa changes with respect to parameters θ\theta
  3. Chain them together to get how to adjust θ\theta to increase QQ

Analogy: The critic is like a GPS telling you "going north increases your value." The actor learns to adjust itself to go more north.

7.3 DDPG Architecture

Four networks:

  1. Actor μθ(s)\mu_\theta(s): Maps states to actions
  2. Critic Qϕ(s,a)Q_\phi(s, a): Evaluates state-action pairs
  3. Target actor μθ′(s)\mu_{\theta'}(s): Slowly-updated copy
  4. Target critic Qϕ′(s,a)Q_{\phi'}(s, a): Slowly-updated copy

7.4 DDPG Algorithm

Critic update (like DQN): y=r+γQϕ′(s′,μθ′(s′))y = r + \gamma Q_{\phi'}(s', \mu_{\theta'}(s')) L(ϕ)=E[(y−Qϕ(s,a))2]L(\phi) = \mathbb{E}\left[(y - Q_\phi(s, a))^2\right]

Actor update (policy gradient): ∇θJ≈E[∇θμθ(s)⋅∇aQϕ(s,a)∣a=μθ(s)]\nabla_\theta J \approx \mathbb{E}\left[\nabla_\theta \mu_\theta(s) \cdot \nabla_a Q_\phi(s, a)|_{a=\mu_\theta(s)}\right]

Soft target updates (instead of hard copy every CC steps): θ′←τθ+(1−τ)θ′\theta' \leftarrow \tau \theta + (1-\tau)\theta' ϕ′←τϕ+(1−τ)ϕ′\phi' \leftarrow \tau \phi + (1-\tau)\phi'

Where τ≪1\tau \ll 1 (e.g., 0.005). This smooths target network changes.

Exploration: Add noise to actions during training: a=μθ(s)+N(0,σ)a = \mu_\theta(s) + \mathcal{N}(0, \sigma)

Commonly Ornstein-Uhlenbeck noise (temporally correlated) or simple Gaussian.

7.5 DDPG Summary

Initialize: Actor μ_θ, Critic Q_φ, target networks θ' = θ, φ' = φ, replay buffer D
 
For each step:
    1. a = μ_θ(s) + noise
    2. Execute a, observe r, s'
    3. Store (s, a, r, s') in D
    4. Sample mini-batch from D
    5. y = r + γ Q_φ'(s', μ_θ'(s'))
    6. Update critic: minimize (y - Q_φ(s,a))²
    7. Update actor: maximize Q_φ(s, μ_θ(s))
    8. Soft update: θ' ← τθ + (1-τ)θ', φ' ← τφ + (1-τ)φ'

7.6 Implementation Notes

Action Scaling: Environments often have action bounds (e.g., [-1, 1]). Use tanh output and scale:

# Actor outputs raw value, then:
action = torch.tanh(raw_action)  # Squash to [-1, 1]
action = low + (action + 1.0) * 0.5 * (high - low)  # Scale to [low, high]

Network Initialization: Critical for DDPG stability!

  • Hidden layers: Default PyTorch init is usually fine
  • Final actor layer: Small weights (e.g., uniform(-3e-3, 3e-3))
  • Final critic layer: Small weights (e.g., uniform(-3e-3, 3e-3))
# Final layer init
nn.init.uniform_(actor.final_layer.weight, -3e-3, 3e-3)
nn.init.uniform_(actor.final_layer.bias, -3e-3, 3e-3)

Critic Architecture: Concatenate action with state after first layer (not at input):

def forward(self, state, action):
    x = F.relu(self.fc1(state))
    x = torch.cat([x, action], dim=1)  # Concat after first layer
    x = F.relu(self.fc2(x))
    return self.fc3(x)

This gives the state a chance to be processed before mixing with action.

Exploration Noise: Two common choices:

  1. Gaussian: Simple, works well. action + N(0, 0.1)
  2. Ornstein-Uhlenbeck: Temporally correlated noise, sometimes better for physical control

In practice, Gaussian is simpler and often just as good. Decay noise over training.

Batch Normalization: Can help but adds complexity. If using it, apply to state inputs only (not actions or after action concatenation). Many successful implementations skip it entirely.

Learning Rates: Critic often uses higher LR than actor (e.g., critic: 1e-3, actor: 1e-4). Intuition: we want an accurate critic before we trust its gradients for the actor.


Part 8: TD3 (Twin Delayed DDPG)

8.1 DDPG's Problems

DDPG is brittle and suffers from:

  1. Overestimation bias: Like DQN, the critic overestimates Q-values
  2. Accumulation of errors: Errors in the critic propagate to the actor
  3. Sensitive to hyperparameters: Requires careful tuning

8.2 TD3's Three Innovations

Innovation 1: Clipped Double Q-Learning

Use two critics Qϕ1,Qϕ2Q_{\phi_1}, Q_{\phi_2} and take the minimum:

y=r+γmin⁡i=1,2Qϕi′(s′,a~′)y = r + \gamma \min_{i=1,2} Q_{\phi'_i}(s', \tilde{a}')

Why minimum? Underestimation is safer than overestimation. Overestimation causes the policy to exploit errors; underestimation leads to conservative but stable behavior.

Innovation 2: Target Policy Smoothing

Add noise to target actions: a~′=μθ′(s′)+clip(ϵ,−c,c),ϵ∼N(0,σ)\tilde{a}' = \mu_{\theta'}(s') + \text{clip}(\epsilon, -c, c), \quad \epsilon \sim \mathcal{N}(0, \sigma)

Why? This regularizes the critic. It's harder for the policy to exploit peaks in the Q-function if nearby actions also need high Q-values. It's like smoothing the value landscape.

Innovation 3: Delayed Policy Updates

Update the actor (and target networks) less frequently than the critic—typically every 2 critic updates.

Why? The actor's gradient depends on the critic. A bad critic gives bad gradients. By updating the critic more often, it's more accurate when we update the actor.

8.3 TD3 Algorithm

Initialize: Actor μ_θ, Critics Q_φ1, Q_φ2, targets θ', φ1', φ2', buffer D
 
For each step:
    1. a = μ_θ(s) + noise, execute, store (s,a,r,s') in D
    2. Sample mini-batch from D
    3. Compute target action: ã' = μ_θ'(s') + clip(N(0,σ), -c, c)
    4. Compute target: y = r + γ min(Q_φ1'(s',ã'), Q_φ2'(s',ã'))
    5. Update both critics: minimize (y - Q_φi(s,a))²
    
    6. If step % policy_delay == 0:
        - Update actor: maximize Q_φ1(s, μ_θ(s))
        - Soft update all target networks

8.4 TD3 vs DDPG Summary

AspectDDPGTD3
Critics12 (take min)
Target actionCleanNoisy (smoothed)
Policy update freqEvery stepEvery 2 steps
StabilityBrittleMuch more stable

8.5 Implementation Notes

Typical Hyperparameters (from the TD3 paper — good starting point):

  • Target policy noise σ\sigma: 0.2
  • Noise clip cc: 0.5
  • Policy delay: 2 (update actor every 2 critic updates)
  • Soft update τ\tau: 0.005
  • Discount γ\gamma: 0.99
  • Batch size: 256 (larger helps with twin critics)

Twin Critics Share No Weights: Implement as two completely separate networks:

self.critic1 = Critic(state_dim, action_dim)
self.critic2 = Critic(state_dim, action_dim)
# NOT: self.critic = Critic(...) with two heads

Target Smoothing in Code:

# Add clipped noise to target action
noise = torch.randn_like(action) * policy_noise
noise = noise.clamp(-noise_clip, noise_clip)
next_action = (target_actor(next_state) + noise).clamp(-max_action, max_action)

Delayed Update Pattern:

for step in range(total_steps):
    # Always update critics
    critic_loss = compute_critic_loss(batch)
    critic_optimizer.step()
    
    # Only update actor every d steps
    if step % policy_delay == 0:
        actor_loss = -critic1(state, actor(state)).mean()
        actor_optimizer.step()
        soft_update(target_networks)

Why TD3 Over DDPG: There's almost no reason to use DDPG in practice. TD3 is strictly better with minimal extra complexity — just two critics and a counter for delayed updates.


Part 9: PPO (Proximal Policy Optimization)

9.1 Motivation: Trust Regions

Policy gradient updates can be unstable—a large update might jump to a much worse policy, from which recovery is difficult.

Trust Region Policy Optimization (TRPO) constrains updates to stay close to the old policy (in KL-divergence). It works but is complex and computationally expensive.

PPO achieves similar stability with a simpler, first-order method.

9.2 The Importance Sampling Objective

To reuse old data, we use importance sampling:

J(θ)=Es,a∼πθold[πθ(a∣s)πθold(a∣s)A^(s,a)]J(\theta) = \mathbb{E}_{s,a \sim \pi_{\theta_{old}}}\left[\frac{\pi_\theta(a|s)}{\pi_{\theta_{old}}(a|s)} \hat{A}(s,a)\right]

Let rt(θ)=πθ(at∣st)πθold(at∣st)r_t(\theta) = \frac{\pi_\theta(a_t|s_t)}{\pi_{\theta_{old}}(a_t|s_t)} be the probability ratio.

Problem: If rt(θ)r_t(\theta) gets too large, the update is too aggressive and destabilizes training.

9.3 PPO-Clip Objective

PPO clips the ratio to prevent large updates:

LCLIP(θ)=E[min⁡(rt(θ)A^t,clip(rt(θ),1−ϵ,1+ϵ)A^t)]L^{CLIP}(\theta) = \mathbb{E}\left[\min\left(r_t(\theta) \hat{A}_t, \text{clip}(r_t(\theta), 1-\epsilon, 1+\epsilon) \hat{A}_t\right)\right]

Where ϵ≈0.2\epsilon \approx 0.2 is a hyperparameter.

How it works:

  • If A^t>0\hat{A}_t > 0 (action was good): We want to increase πθ(a∣s)\pi_\theta(a|s), so rtr_t increases. But clipping at 1+ϵ1+\epsilon stops us from increasing too much.
  • If A^t<0\hat{A}_t < 0 (action was bad): We want to decrease πθ(a∣s)\pi_\theta(a|s), so rtr_t decreases. But clipping at 1−ϵ1-\epsilon stops us from decreasing too much.

The min ensures we take the more conservative (pessimistic) objective.

Intuition: PPO is like a careful driver. Even if GPS says "turn hard right for a shortcut," PPO limits how sharp a turn it takes to avoid crashing. It makes steady progress rather than risky leaps.

9.4 PPO Algorithm

For each iteration:
    1. Collect T timesteps using current policy π_θ
    2. Compute advantages Â_t (using GAE)
    3. Store (s_t, a_t, π_θ(a_t|s_t), Â_t, return_t)
    
    For K epochs:
        For each mini-batch:
            4. Compute r_t(θ) = π_θ(a_t|s_t) / π_θ_old(a_t|s_t)
            5. L_clip = min(r_t · Â_t, clip(r_t, 1-ε, 1+ε) · Â_t)
            6. L_value = (V_φ(s_t) - return_t)²
            7. L_entropy = -Σ π_θ(a|s) log π_θ(a|s)
            8. L = -L_clip + c1·L_value - c2·L_entropy
            9. Update θ and φ using gradient descent on L
    
    10. θ_old ← θ

9.5 Key PPO Details

Multiple epochs: Unlike vanilla policy gradients (one update per batch), PPO reuses data for K epochs (typically 3-10). The clipping keeps updates safe even with reuse.

Value function clipping (optional): Some implementations also clip value updates: LVF=max⁡[(Vθ−Vtarget)2,(clip(Vθ,Vold−ϵ,Vold+ϵ)−Vtarget)2]L^{VF} = \max\left[(V_\theta - V_{target})^2, (\text{clip}(V_\theta, V_{old} - \epsilon, V_{old} + \epsilon) - V_{target})^2\right]

Advantage normalization: Often normalize advantages within each batch: A^t←A^t−mean(A^)std(A^)\hat{A}_t \leftarrow \frac{\hat{A}_t - \text{mean}(\hat{A})}{\text{std}(\hat{A})}

9.6 Implementation Notes

Computing the Ratio with Log-Probs: The ratio rt(θ)=πθ(a∣s)πθold(a∣s)r_t(\theta) = \frac{\pi_\theta(a|s)}{\pi_{\theta_{old}}(a|s)} is computed using log-probs for numerical stability:

# During rollout, store log_prob of action under OLD policy
old_log_prob = old_dist.log_prob(action).detach()
 
# During update, compute log_prob under CURRENT policy  
new_log_prob = new_dist.log_prob(action)
 
# Ratio via exp(log(a/b)) = exp(log(a) - log(b))
ratio = torch.exp(new_log_prob - old_log_prob)

Never compute new_prob / old_prob directly — probabilities can be tiny and cause numerical issues.

The Expectation Is a Sample Mean: The theoretical objective is: LCLIP=E[min⁡(rtA^t,clip(rt,1−ϵ,1+ϵ)A^t)]L^{CLIP} = \mathbb{E}\left[\min(r_t \hat{A}_t, \text{clip}(r_t, 1-\epsilon, 1+\epsilon) \hat{A}_t)\right]

In code, this expectation is just the mean over your mini-batch:

surr1 = ratio * advantages
surr2 = torch.clamp(ratio, 1 - eps, 1 + eps) * advantages
policy_loss = -torch.min(surr1, surr2).mean()  # Mean over batch ≈ expectation

Over enough mini-batches and iterations, this sample mean converges to the true expectation. This is why we can do multiple epochs — we're just getting more samples of the same expectation.

The Full PPO Loss:

# Policy loss (clipped surrogate)
surr1 = ratio * advantages
surr2 = torch.clamp(ratio, 1 - clip_eps, 1 + clip_eps) * advantages
policy_loss = -torch.min(surr1, surr2).mean()
 
# Value loss (MSE or clipped)
value_loss = F.mse_loss(values, returns)
 
# Entropy bonus (encourages exploration)
entropy = dist.entropy().mean()
 
# Total loss
loss = policy_loss + value_coef * value_loss - entropy_coef * entropy

Typical Hyperparameters:

  • Clip ϵ\epsilon: 0.2 (the PPO paper value, rarely needs changing)
  • GAE λ\lambda: 0.95
  • Discount γ\gamma: 0.99
  • Epochs per rollout: 3-10 (more epochs = more sample efficiency, but risk overfitting)
  • Mini-batch size: 64-256
  • Value coefficient: 0.5
  • Entropy coefficient: 0.01 (decay if policy becomes too stochastic)

Rollout Buffer Structure: Store everything needed for updates:

buffer = {
    'states': [],      # For computing new log_probs
    'actions': [],     # For computing new log_probs
    'old_log_probs': [],  # For ratio computation
    'advantages': [],  # Pre-computed GAE
    'returns': [],     # For value loss (advantages + values)
}

Advantage Normalization Is Important:

advantages = (advantages - advantages.mean()) / (advantages.std() + 1e-8)

This centers advantages around 0, so about half of actions get reinforced and half get discouraged. Without this, if all advantages are positive (or all negative), every action gets pushed in the same direction.

Learning Rate Schedule: Linear decay to 0 over training often helps:

lr = initial_lr * (1 - current_step / total_steps)

Multiple Epochs Explained: Unlike A2C (one gradient step per rollout), PPO reuses data:

  1. Collect rollout with πθold\pi_{\theta_{old}}
  2. Compute advantages
  3. For KK epochs, shuffle data into mini-batches and update θ\theta
  4. The clipping ensures θ\theta doesn't drift too far from θold\theta_{old}

This improves sample efficiency significantly.

When Clipping Activates:

  • If A^>0\hat{A} > 0 and r>1+ϵr > 1 + \epsilon: Clip activates (prevents too much increase)
  • If A^<0\hat{A} < 0 and r<1−ϵr < 1 - \epsilon: Clip activates (prevents too much decrease)
  • Otherwise: Unclipped gradient

Part 10: Algorithm Comparison Summary

When to Use What

AlgorithmAction SpaceSample EfficiencyStabilityBest For
DQNDiscreteMediumGoodAtari, discrete control
Double DQNDiscreteMediumBetterWhen DQN overestimates
DDPGContinuousHighPoorContinuous control (with tuning)
TD3ContinuousHighGoodContinuous control
A2CBothLowMediumFast iteration, simple baseline
PPOBothLowExcellentGeneral purpose, robustness

Key Equations Cheat Sheet

Q-Learning Target: y=r+γmax⁡a′Q(s′,a′)y = r + \gamma \max_{a'} Q(s', a')

Double DQN Target: y=r+γQ(s′,arg⁡max⁡a′Q(s′,a′;θ);θ−)y = r + \gamma Q(s', \arg\max_{a'} Q(s', a'; \theta); \theta^-)

Policy Gradient: ∇θJ=E[∑t∇θlog⁡πθ(at∣st)⋅A^t]\nabla_\theta J = \mathbb{E}\left[\sum_t \nabla_\theta \log \pi_\theta(a_t|s_t) \cdot \hat{A}_t\right]

Deterministic Policy Gradient (DDPG/TD3): ∇θJ=E[∇θμθ(s)⋅∇aQ(s,a)∣a=μθ(s)]\nabla_\theta J = \mathbb{E}\left[\nabla_\theta \mu_\theta(s) \cdot \nabla_a Q(s,a)|_{a=\mu_\theta(s)}\right]

PPO Objective: LCLIP=E[min⁡(rtA^t,clip(rt,1−ϵ,1+ϵ)A^t)]L^{CLIP} = \mathbb{E}\left[\min\left(r_t \hat{A}_t, \text{clip}(r_t, 1-\epsilon, 1+\epsilon) \hat{A}_t\right)\right]

TD3 Target (with twin critics and smoothing): y=r+γmin⁡i=1,2Qϕi′(s′,μθ′(s′)+clip(ϵ,−c,c))y = r + \gamma \min_{i=1,2} Q_{\phi'_i}(s', \mu_{\theta'}(s') + \text{clip}(\epsilon, -c, c))

Conceptual Relationships

                    Q-Learning
                         │
                         ▼
             ┌───── Function Approx ─────┐
             │                           │
             ▼                           ▼
           DQN                    Policy Gradients
             │                           │
             ▼                           ▼
        Double DQN                  REINFORCE
             │                           │
             │                           ▼
             │                    Actor-Critic (A2C)
             │                           │
             └──────────┬────────────────┘
                        │
                        ▼
                 ┌──── DDPG ────┐
                 │              │
                 ▼              │
               TD3              │
                                │
                        ┌───────┴───────┐
                        ▼               ▼
                      TRPO            PPO

Part 11: Key Intuitions Summary

  1. DQN: "Learn a cheat sheet of action values, but use flashcards and a stable answer key to avoid forgetting"

  2. Double DQN: "Get a second opinion on action values to avoid wishful thinking"

  3. Actor-Critic: "Have a student (actor) learn from a teacher's (critic) feedback rather than waiting until the end of the semester for grades"

  4. DDPG: "DQN for continuous actions—the critic guides the actor toward better actions"

  5. TD3: "DDPG but more careful—use two critics, add noise for robustness, and don't rush the actor updates"

  6. PPO: "Make steady, conservative policy updates—even if you see a shortcut, don't take a turn so sharp you crash"


Part 12: General Implementation Notes

12.1 Common Pitfalls

Forgetting to Detach: When computing targets, always detach from the computation graph:

# WRONG - gradients flow through target
target = reward + gamma * target_net(next_state).max()
 
# RIGHT - no gradient through target
target = reward + gamma * target_net(next_state).max().detach()
# or equivalently:
with torch.no_grad():
    target = reward + gamma * target_net(next_state).max()

Not Handling Episode Termination: When an episode ends, there's no future value:

# WRONG
target = reward + gamma * V(next_state)
 
# RIGHT  
target = reward + gamma * V(next_state) * (1 - done)

Action Space Mismatch: Always check if your environment has discrete or continuous actions, and that your network output matches (softmax for discrete, tanh for bounded continuous).

12.2 Debugging Tips

Monitor These Metrics:

  • Episode return (should trend up)
  • Policy entropy (shouldn't collapse to 0 too fast)
  • Value loss (should decrease, then plateau)
  • Policy loss (noisy, but shouldn't explode)
  • Q-value estimates (watch for runaway growth — sign of overestimation)

Sanity Checks:

  1. Can your agent solve a trivial version? (CartPole should solve in <100 episodes)
  2. With zero noise, does the policy output deterministic actions?
  3. Is the replay buffer actually being sampled randomly?
  4. Are your advantages centered around 0 after normalization?

12.3 Reproducibility

import torch
import numpy as np
import random
 
def set_seed(seed):
    torch.manual_seed(seed)
    np.random.seed(seed)
    random.seed(seed)
    if torch.cuda.is_available():
        torch.cuda.manual_seed_all(seed)
    # For full determinism (slower):
    torch.backends.cudnn.deterministic = True

12.4 Common Hyperparameter Defaults

ParameterDQN/DDQNDDPGTD3A2CPPO
Learning Rate1e-41e-3 (C), 1e-4 (A)3e-47e-43e-4
Batch Size32256256n_envs × n_steps64
γ\gamma0.990.990.990.990.99
τ\tau (soft update)0.0050.0050.005——
Buffer Size1M1M1M——
Target Update10k stepsevery stepevery step——