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:
- Value-Based Methods: Learn how "good" states or state-action pairs are, then act greedily with respect to those values
- 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 , take action , and then act optimally forever after, what's my expected total discounted reward?"
The optimal Q-function is the Q-function when following the optimal policy.
Intuition: Think of 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 in state equals:
- The immediate reward you get, plus
- The discounted value of the best action in the next state
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 through trial and error without knowing the environment dynamics.
The Update Rule:
Where:
- is the learning rate
- is the TD target (our new estimate)
- is our current estimate
- The bracketed term is the TD error
Plain English:
- Try an action, see what happens
- Compute what you thought would happen vs. what actually happened (plus your best guess for the future)
- 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:
-greedy: With probability , take a random action; otherwise, take
Typically starts high (explore) and decays over time (exploit).
Part 3: Policy Gradient Foundation
3.1 Why Policy Gradients?
Q-learning struggles with:
- Continuous action spaces: Can't compute when
- Stochastic optimal policies: Sometimes randomness is optimal (e.g., rock-paper-scissors)
Policy gradients directly optimize a parameterized policy .
3.2 The Objective
We want to maximize expected return:
Where is a trajectory.
3.3 The Policy Gradient Theorem
The Problem: How do we take gradients through an expectation over trajectories that depend on ?
The Solution (the "log-derivative trick"):
Since the transition dynamics don't depend on , this simplifies to:
Where is the return from time .
Derivation Sketch:
- (multiply by )
- (using )
3.4 REINFORCE Algorithm
The simplest policy gradient algorithm:
- Collect a trajectory using
- Compute returns for each timestep
- Update:
Intuition:
- If an action led to high return, increase its probability ( pushes probability up)
- If an action led to low return, decrease its probability
- The gradient points in the direction that increases the probability of action
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 from the return:
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?
Best baseline: The value function is provably close to optimal. This gives us the advantage:
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 pair. This is impossible for:
- Atari games (state space ≈ )
- Continuous states
Solution: Approximate with a neural network .
4.2 Naive Approach and Its Problems
Naively applying Q-learning with neural networks:
This fails catastrophically. Why?
-
Correlated samples: Sequential experiences are highly correlated. Neural networks trained on correlated data overfit to recent experience and forget past learning.
-
Non-stationary targets: The target changes every time we update . 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 in a replay buffer . 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 that's updated slowly.
- The main network is updated every step
- The target network is copied from every 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:
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):
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 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 all actions have true value 0, but your estimates are due to noise. The max is , 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:
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:
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 's value, it might select . But the target network, with different noise, is unlikely to also overestimate . 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 targetWhen 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 that selects actions
- Critic: Value function 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:
We estimate advantage as:
This is called the TD error estimate of advantage. It's biased (since 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
- Value head: outputs
Losses:
Policy loss (actor):
Value loss (critic):
Where is the actual return (or a bootstrapped estimate).
Entropy bonus (encourages exploration):
Total loss:
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 error6.5 Generalized Advantage Estimation (GAE)
There's a bias-variance tradeoff in advantage estimation:
- 1-step TD: — low variance, high bias
- Monte Carlo: — high variance, low bias
GAE interpolates using parameter :
Where is the TD error.
- : Pure TD (low variance, high bias)
- : Pure MC (high variance, low bias)
- : 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 . 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:
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 ≈ expectationGradient 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:
- We can't enumerate all actions to compute
- We can't do -greedy over infinite action spaces
DDPG (Deep Deterministic Policy Gradient) solves this.
7.2 Key Idea: Deterministic Policy Gradient
Instead of stochastic , learn a deterministic policy that directly outputs an action.
The deterministic policy gradient theorem:
Intuition:
- The critic tells us how changes with respect to action
- The actor tells us how changes with respect to parameters
- Chain them together to get how to adjust to increase
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:
- Actor : Maps states to actions
- Critic : Evaluates state-action pairs
- Target actor : Slowly-updated copy
- Target critic : Slowly-updated copy
7.4 DDPG Algorithm
Critic update (like DQN):
Actor update (policy gradient):
Soft target updates (instead of hard copy every steps):
Where (e.g., 0.005). This smooths target network changes.
Exploration: Add noise to actions during training:
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:
- Gaussian: Simple, works well.
action + N(0, 0.1) - 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:
- Overestimation bias: Like DQN, the critic overestimates Q-values
- Accumulation of errors: Errors in the critic propagate to the actor
- Sensitive to hyperparameters: Requires careful tuning
8.2 TD3's Three Innovations
Innovation 1: Clipped Double Q-Learning
Use two critics and take the minimum:
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:
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 networks8.4 TD3 vs DDPG Summary
| Aspect | DDPG | TD3 |
|---|---|---|
| Critics | 1 | 2 (take min) |
| Target action | Clean | Noisy (smoothed) |
| Policy update freq | Every step | Every 2 steps |
| Stability | Brittle | Much more stable |
8.5 Implementation Notes
Typical Hyperparameters (from the TD3 paper — good starting point):
- Target policy noise : 0.2
- Noise clip : 0.5
- Policy delay: 2 (update actor every 2 critic updates)
- Soft update : 0.005
- Discount : 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 headsTarget 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:
Let be the probability ratio.
Problem: If gets too large, the update is too aggressive and destabilizes training.
9.3 PPO-Clip Objective
PPO clips the ratio to prevent large updates:
Where is a hyperparameter.
How it works:
- If (action was good): We want to increase , so increases. But clipping at stops us from increasing too much.
- If (action was bad): We want to decrease , so decreases. But clipping at 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:
Advantage normalization: Often normalize advantages within each batch:
9.6 Implementation Notes
Computing the Ratio with Log-Probs: The ratio 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:
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 ≈ expectationOver 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 * entropyTypical Hyperparameters:
- Clip : 0.2 (the PPO paper value, rarely needs changing)
- GAE : 0.95
- Discount : 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:
- Collect rollout with
- Compute advantages
- For epochs, shuffle data into mini-batches and update
- The clipping ensures doesn't drift too far from
This improves sample efficiency significantly.
When Clipping Activates:
- If and : Clip activates (prevents too much increase)
- If and : Clip activates (prevents too much decrease)
- Otherwise: Unclipped gradient
Part 10: Algorithm Comparison Summary
When to Use What
| Algorithm | Action Space | Sample Efficiency | Stability | Best For |
|---|---|---|---|---|
| DQN | Discrete | Medium | Good | Atari, discrete control |
| Double DQN | Discrete | Medium | Better | When DQN overestimates |
| DDPG | Continuous | High | Poor | Continuous control (with tuning) |
| TD3 | Continuous | High | Good | Continuous control |
| A2C | Both | Low | Medium | Fast iteration, simple baseline |
| PPO | Both | Low | Excellent | General purpose, robustness |
Key Equations Cheat Sheet
Q-Learning Target:
Double DQN Target:
Policy Gradient:
Deterministic Policy Gradient (DDPG/TD3):
PPO Objective:
TD3 Target (with twin critics and smoothing):
Conceptual Relationships
Q-Learning
│
▼
┌───── Function Approx ─────┐
│ │
▼ ▼
DQN Policy Gradients
│ │
▼ ▼
Double DQN REINFORCE
│ │
│ ▼
│ Actor-Critic (A2C)
│ │
└──────────┬────────────────┘
│
▼
┌──── DDPG ────┐
│ │
▼ │
TD3 │
│
┌───────┴───────┐
▼ ▼
TRPO PPOPart 11: Key Intuitions Summary
-
DQN: "Learn a cheat sheet of action values, but use flashcards and a stable answer key to avoid forgetting"
-
Double DQN: "Get a second opinion on action values to avoid wishful thinking"
-
Actor-Critic: "Have a student (actor) learn from a teacher's (critic) feedback rather than waiting until the end of the semester for grades"
-
DDPG: "DQN for continuous actions—the critic guides the actor toward better actions"
-
TD3: "DDPG but more careful—use two critics, add noise for robustness, and don't rush the actor updates"
-
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:
- Can your agent solve a trivial version? (CartPole should solve in <100 episodes)
- With zero noise, does the policy output deterministic actions?
- Is the replay buffer actually being sampled randomly?
- 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 = True12.4 Common Hyperparameter Defaults
| Parameter | DQN/DDQN | DDPG | TD3 | A2C | PPO |
|---|---|---|---|---|---|
| Learning Rate | 1e-4 | 1e-3 (C), 1e-4 (A) | 3e-4 | 7e-4 | 3e-4 |
| Batch Size | 32 | 256 | 256 | n_envs × n_steps | 64 |
| 0.99 | 0.99 | 0.99 | 0.99 | 0.99 | |
| (soft update) | 0.005 | 0.005 | 0.005 | — | — |
| Buffer Size | 1M | 1M | 1M | — | — |
| Target Update | 10k steps | every step | every step | — | — |