Code Architecture — Continuous Control with Deep RL (DDPG) Notebook
Overview
The notebook implements DDPG from scratch in PyTorch: a replay buffer, a deterministic actor, a Q-critic, target networks with soft updates and Ornstein-Uhlenbeck exploration noise. It trains on Gymnasium’s Pendulum-v1 for 120 episodes, evaluates the noise-free policy against a random policy, and plots rewards and losses. It runs on the CPU.
Notebook Structure
1. Setup & Imports
- PyTorch, Gymnasium, NumPy, matplotlib; nothing is installed
CUBLAS_WORKSPACE_CONFIGset before importing torch; seeds 42 (random, NumPy, torch); cuDNN deterministic,torch.use_deterministic_algorithms(True, warn_only=True)- Figures as JPEG at 80 dpi; on Kaggle an
atexithook and a small background process copy the executed notebook toexecuted_solution.ipynb
2. Environment: Pendulum-v1
- Observation (cos θ, sin θ, angular velocity), 3-dimensional; one torque action in [−2, 2]
- Episodes are cut off (
truncated) after 200 steps; they never end on their own
3. Replay Buffer (ReplayBuffer(capacity=100_000))
- Circular list of (state, action, reward, next_state, done);
sample(batch_size)draws a uniform minibatch and returns tensors
4. Actor (Actor(obs_dim, act_dim, max_action, hidden=256))
- Linear(3, 256) → ReLU → Linear(256, 256) → ReLU → Linear(256, 1) → Tanh, scaled by
max_action = 2.0
5. Critic (Critic(obs_dim, act_dim, hidden=256))
- Concatenates state and action: Linear(4, 256) → ReLU → Linear(256, 256) → ReLU → Linear(256, 1)
6. Ornstein-Uhlenbeck Noise (OUNoise(action_dim, mu=0.0, theta=0.15, sigma=0.2))
- x ← x + θ(μ − x) + σ · N(0, 1) each step;
reset()sets x back to μ
7. DDPG Agent (DDPGAgent)
- Actor, critic and their target copies (initialised with the same weights); Adam with learning rates 1e-4 (actor) and 1e-3 (critic); γ = 0.99, τ = 0.005, batch 64
select_action(state, noise_scale): actor output plusnoise_scale× OU noise, clipped to [−2, 2]train(): waits until the buffer has 64 transitions; critic target y = r + γ(1 − done) Q′(s′, μ′(s′)); MSE critic loss; actor loss −mean Q(s, μ(s)); soft updates θ′ ← τθ + (1 − τ)θ′
8. Training Loop
NUM_EPISODES = 120, 200 steps each, one training step per environment step- Noise scale falls linearly from 0.3 to 0.05 over the episodes
- Stores
float(terminated)as the done flag, so a time-limit cut is not treated as terminal - Prints the 10-episode average reward every 10 episodes
9. Evaluation
- 10 noise-free episodes from start seeds 1000 to 1009; prints mean, std, min and max reward
- A uniform random policy on the same 10 starts as a baseline (
env.action_space.seed(SEED))
10. Reward & Noise Plots
- Episode reward with a 10-episode rolling average, and the noise scale per episode
- Prints the best 10-episode average and its episodes
11. Critic & Actor Loss Curves
- Critic MSE and actor loss (−Q) per training step
- Prints the mean of each over the first and last 1,000 steps
12. Summary
### What the run above showswith the saved run’s numbers
Key Shapes (batch of 64)
| Tensor | Shape |
|---|---|
| States, next states | (64, 3) |
| Actions | (64, 1) |
| Rewards, done flags | (64, 1) |
| Critic input (state ‖ action) | (64, 4) |
| Q values and targets y | (64, 1) |
Deliberate Simplifications vs Full Paper
- Task: one Gymnasium task and one seed instead of more than 20 MuJoCo tasks and Torcs, averaged over 5 runs (Section 4).
- Networks: 256-256 hidden units, action at the critic’s input, no batch normalization, default initialization; the paper uses 400-300 units, the action at the critic’s second hidden layer, batch normalization and ±3 × 10⁻³ final-layer initialization (Section 3, Supplementary Section 7).
- Settings: τ = 0.005 instead of 0.001, buffer 10⁵ instead of 10⁶, no L2 weight decay on the critic (Supplementary Section 7).
- Noise: the OU noise is multiplied by a scale that falls from 0.3 to 0.05; the paper adds the OU noise directly.
- Length: 120 episodes (24,000 steps) instead of up to 2.5 million steps (Table 1).