Paul's Python CoursePPC

Project 11 of 12, for Aaesha

Actor-Critic and PPO

One part acts and one part judges, as one theory of the brain has it: one-step actor-critic on the racing grid, with the critic's TD error as each move's verdict, and PPO's clipped objective read and worked by hand.

About 2 hours, in 8 steps.

Sign up free to open itLog in

Act 8 needs a free account, so your work is saved as you go. Act 1 is open to everyone.

The brief

  • AaeshaREINFORCE waits until the race is over before it learns anything, and brains definitely don't wait that long.
  • YahyaI comment on every move you make at the cabinet.
  • CaitlinYou do, and it's really annoying, but it also works.
  • AaeshaThere's a theory that the brain has one part picking the move and another judging it, with dopamine carrying the verdict.
  • PaulThen let's give the crab a critic, with one part acting and one judging, and both learning as they go.

Write actor_critic.py, one-step actor-critic on the racing grid in track.py. The actor is theta, a (3, 4, 4) array of preferences, with chances and grad_log_chance from Policy Gradients. The critic is values, a (3, 4) array.

  1. td_error(values, tile, reward, after, over, gamma=0.9): the critic's verdict on a move: the reward, plus gamma times the value of where it landed unless the race is over, minus the value of where it was.
  2. update(theta, values, tile, action, reward, after, over, gamma=0.9, actor_rate=0.2, critic_rate=0.2): one step of actor-critic, in place. Work out the TD error and the gradient first; then values[tile] moves critic_rate times the error, and theta moves actor_rate times the error times the gradient. Returns the TD error.
  3. train(episodes, rng, gamma=0.9, actor_rate=0.2, critic_rate=0.2): races from the start of at most 50 moves, each drawn by chance, with an update after every move. Returns (theta, values).
  4. clipped_objective(ratio, advantage, epsilon=0.2): PPO's objective, the smaller of ratio * advantage and the ratio clipped to between 1 - epsilon and 1 + epsilon, times the advantage. Numbers or NumPy arrays.

Run as a program, it trains for 200 races and shows its most likely moves, the critic's values and its average return over 1000 races, then PPO's clip for four moves.

The stretches go on from there: a small PPO of your own on the grid, then a real PPO implementation, read and changed at home.

What it prints
After 200 races, its most likely moves
> > > F
^ # ^ P
^ > ^ <
The critic's values
   4.2   7.1   9.9   0.0
   2.9     #   6.3   0.0
   0.2  -2.3   0.8  -4.8
Average return over 1000 races: 1.05

PPO's clip, with epsilon 0.2
ratio 1.5, advantage 2.0: 2.4
ratio 0.5, advantage 2.0: 1.0
ratio 1.5, advantage -2.0: -3.0
ratio 0.5, advantage -2.0: -1.6

What you learn

What's in it

  1. One acts, one judges
  2. A move that cost a point
  3. Change, but not too much
  4. The clip
  5. How Paul would do it
  6. Make the actor and the critic
  7. Ship it