Code Architecture — Trust Region Policy Optimization Notebook

Overview

The notebook implements TRPO from scratch in PyTorch: the surrogate objective, the mean KL divergence, Fisher-vector products, conjugate gradient and a backtracking line search. It trains a small policy on CartPole-v1 for 100 iterations of 2,000 timesteps and plots reward, KL, surrogate and step acceptance. It runs on the CPU.

Notebook Structure

1. Setup & Imports

  • PyTorch, Gymnasium, NumPy, matplotlib; nothing is installed
  • CUBLAS_WORKSPACE_CONFIG set before importing torch; seeds 42; cuDNN deterministic, torch.use_deterministic_algorithms(True, warn_only=True)
  • Figures as JPEG at 80 dpi; on Kaggle an atexit hook and a small background process copy the executed notebook to executed_solution.ipynb

2. Environment: CartPole-v1

  • 4-dimensional observation, 2 actions; episodes end at 500 steps

3. Policy Network (PolicyNetwork)

  • Linear(4, 64) → Tanh → Linear(64, 64) → Tanh → Linear(64, 2) logits; 4,610 parameters
  • get_action(obs) samples from a categorical distribution
  • get_log_probs_and_entropy(obs, actions) returns log π(a | s), the entropy and the action probabilities

4. Value Network (ValueNetwork)

  • Linear(4, 64) → Tanh → Linear(64, 64) → Tanh → Linear(64, 1); 4,545 parameters; Adam with learning rate 1e-3

5. Trajectory Collection & GAE (collect_trajectories)

  • Runs the policy until 2,000 timesteps are collected; records states, actions, rewards, log-probabilities, values and finished-episode rewards
  • GAE advantages with γ = 0.99 and λ = 0.95, normalised to mean 0 and standard deviation 1; returns = advantages + values (before normalisation)

6. TRPO Core

  • surrogate_loss: mean of exp(log π_new − log π_old) · A
  • kl_divergence: mean over states of Σ_a π_old(a | s) · (log π_old(a | s) − log π_new(a | s))
  • get_flat_params, set_flat_params, get_flat_grad: move between parameter lists and one flat vector
  • fisher_vector_product(policy, states, old_probs, v, damping=1e-2): gradient of (∇KL · v), computed with create_graph=True, plus 0.01 · v

7. Conjugate Gradient (conjugate_gradient(fvp_func, b, n_steps=10, residual_tol=1e-10))

  • Solves F x = g using only Fisher-vector products

8. Line Search (trpo_step)

  • Direction s from conjugate gradient; largest step β = √(2δ / sᵀFs)
  • Tries β, β/2, β/4, … (up to 10 tries) and accepts the first step with KL ≤ δ and surrogate > 0; otherwise restores the old parameters
  • Returns KL and surrogate before and after, and whether a step was accepted

9. Value Function Update (update_value)

  • 10 epochs of mini-batch (64) MSE regression of the value network on the returns

10. Training Loop

  • MAX_ITERATIONS = 100, BATCH_SIZE = 2000, GAMMA = 0.99, LAM = 0.95, MAX_KL = 0.01, CG_STEPS = 10, VALUE_EPOCHS = 10, LS_BACKTRACK = 10
  • Each iteration: collect a batch, compute old probabilities, one TRPO step, then the value update
  • Logs average episode reward, its 10-iteration moving average, KL, surrogate, value loss and step acceptance; prints every 10 iterations

11. Visualization

  • 2×2 plot: reward with moving average, KL per update against δ, surrogate per update, cumulative acceptance rate
  • Prints how many iterations averaged 500, the first such iteration, the lowest average after it, the highest KL and the number of accepted steps

12. Summary

  • ### What the run above shows with the saved run’s numbers

Key Shapes

Tensor Shape
States (2000, 4)
Actions, advantages, returns, old log-probs (2000,)
Logits / old probabilities (2000, 2)
Flat policy parameters, gradient, step direction (4610,)

Deliberate Simplifications vs Full Paper

  1. Task: CartPole-v1 instead of MuJoCo locomotion and Atari (Section 8).
  2. Advantages: GAE with a learned value network instead of Monte Carlo estimates; no vine sampling (Section 5).
  3. Damping: 0.01 · v added to Fisher-vector products; the paper does not mention damping.
  4. Line search: halves the step up to 10 times and requires the surrogate to be positive; the paper shrinks the step exponentially until the objective improves (Appendix C).
  5. Scale: 100 iterations and one seed.