Code Architecture — PPO Implementation
This document describes the notebook structure, key functions and classes, data flow, and the simplifications compared with the paper.
Notebook Structure
1. Setup & Imports
Imports gymnasium, PyTorch and matplotlib. Sets the seed (42) for Python, NumPy and PyTorch, turns on deterministic algorithms, sets JPEG figure output at dpi 80, and registers the atexit hook that saves the executed notebook on Kaggle.
2. Hyperparameters
| Name | Value | Source | |——|——-|——–| | GAMMA | 0.99 | Table 3 | | GAE_LAMBDA | 0.95 | Table 3 | | EPS_CLIP | 0.2 | Section 3, Table 1 | | EPOCHS (K) | 10 | Table 3 | | STEPS_PER_EPOCH (T) | 2048 | Table 3 | | MINIBATCH_SIZE (M) | 64 | Table 3 | | LR | 3e-4 | Table 3 | | HIDDEN_DIM | 64 | Section 6.1 | | C1, C2 | 1.0, 0.01 | Table 5 (Atari) | | TOTAL_TIMESTEPS | 50,000 | our choice |
3. Actor-Critic Networks (ActorCritic)
Two separate MLPs, as in Section 6.1 (no parameter sharing):
policy_net: 4 → 64 → 64 → 2 with tanh, giving action logits for aCategoricaldistribution.value_net: 4 → 64 → 64 → 1 with tanh, giving V(s).get_action(obs)samples an action and returns (action, log π(a|s), V(s));evaluate(obs, actions)returns log-probabilities, values and entropy for a batch.
4. Rollout Buffer (RolloutBuffer)
Stores T = 2048 steps of (observation, action, old log-probability, reward, value, done).
compute_gae(last_value)runs backwards over the buffer: δ_t = r_t + γ V(s_{t+1})(1 − done_t) − V(s_t) and Â_t = δ_t + γλ(1 − done_t)Â_{t+1} (Eqs. 11 and 12).done_tmeans the episode ended after step t, so no value is bootstrapped across an episode end. Returns are Â_t + V(s_t).get_batches()yields shuffled minibatches of 64.
5. PPO Update (ppo_update)
Algorithm 1. Advantages are normalized per batch (not in the paper). For K = 10 epochs over all minibatches:
- ratio r = exp(log π_θ − log π_θold)
- policy loss = −mean(min(r·Â, clip(r, 1 − ε, 1 + ε)·Â)) (Eq. 7)
- value loss = MSE(V(s), return)
- total loss = policy loss + C1 · value loss − C2 · entropy (Eq. 9, written as a loss to minimize)
- Adam step after gradient-norm clipping at 0.5 (not in the paper).
It also records, per update, the mean unclipped objective, mean clipped objective, clip fraction (share of samples with |r − 1| > ε), value loss and entropy.
6. Training Loop (train_ppo)
Collects 2048 steps with the current policy, bootstraps the last value, calls compute_gae and ppo_update, and repeats until 50,000 steps (25 updates). Prints the average of the last 10 episodes every 50 episodes.
7. Results: Episode Rewards
Plots episode rewards with a moving average. Prints the final 20-episode average, the number of episodes, the first episode to reach 500, the number of 500-step episodes among the last 50, and a greedy evaluation over 10 episodes (seeds 1000 to 1009).
8. Results: Clipped vs Unclipped Surrogate Objective
Plots the two objectives, the clip fraction, value loss and entropy per update, and prints their means.
9. Analysis: the Clipping Effect
Prints clip-fraction statistics, the gap between the two objectives, a check that L^CLIP ≤ L^CPI for every update, and the clip fraction in the first and last quarter of training.
10. Summary
States what the saved run shows: first 500 at episode 361, 42 of the last 50 episodes at 500, greedy evaluation 500 in all 10 episodes, mean clip fraction 6.19%, 0 bound violations in 25 updates, the two bugs fixed, and that one seed on CartPole does not reproduce the paper’s benchmarks.
Deliberate Simplifications vs Full Paper
| Aspect | Paper | This Notebook |
|---|---|---|
| Environment | 7 MuJoCo tasks, 49 Atari games | CartPole-v1 |
| Actors | N parallel actors (8 for Atari) | one actor |
| Policy distribution | Gaussian (continuous actions) | Categorical (discrete actions) |
| Parameter sharing | none for MuJoCo (Section 6.1) | none (same) |
| Network | 2 × 64 MLP with tanh | 2 × 64 MLP with tanh (same) |
| KL penalty variant | tested (Section 4) | not implemented (clip only) |
| Timesteps and seeds | 1M steps, 3 seeds per MuJoCo task | 50,000 steps, one seed |
| Entropy coefficient | 0.01 (Atari), none for MuJoCo | 0.01 |
| Advantage normalization | not described | yes |
| Gradient-norm clipping | not described | 0.5 |