https://github.com/mattlack15/PPOExperiments
Purpose
This is a Java implementation of Proximal Policy Optimization (PPO), the reinforcement learning algorithm from OpenAI, which I used to train agents to play a small two-player game. There are no machine learning libraries involved. The neural networks are built with my own NeuralNetLib (https://mattlack.com/project/1748550728354), so I had to write the PPO update, including its gradient, by hand.
The Game
Two players spawn on a 128x128 map, each on top of their own flag at a random position. A flag is just a block, and the first player to break the other player's flag wins. Each episode lasts up to 250 steps.
Every step, each player sees:
- The 7x7 area of blocks around them (49 inputs)
- Their own position and their opponent's position
- The position of their own flag and their opponent's flag
That's 57 inputs, with positions normalized between -1 and 1. The player then outputs 58 numbers that are turned into probability distributions and sampled from:
- Whether to break a block this step
- Which of the 49 blocks around them to break
- One of 4 speeds to move along x, and one of 4 speeds to move along y
The reward is how much closer the player got to the enemy flag that step, plus 1 for breaking it.
Both players use the same actor and critic networks, and both of their experiences are used for training, so the agent is effectively learning by playing against itself.
The Networks
PPO uses two networks. The actor decides what to do, and the critic estimates how good a state is:
actor.addLayer(new DenseLayer(57, 32));
actor.addLayer(new DenseLayer(32, 32));
actor.addLayer(new DenseLayer(32, 58).setActivationFunctionSigmoid());
critic.addLayer(new DenseLayer(57, 32));
critic.addLayer(new DenseLayer(32, 32));
critic.addLayer(new DenseLayer(32, 1).setActivationFunctionLinear());
How PPO works here
After each episode:
- Advantages. For every step, the advantage is the discounted reward from that point on, minus the critic's estimate of the state. A positive advantage means the action turned out better than expected. The discount factor is currently set to 0 for training, so in practice it's just the reward for that step. (I started on generalized advantage estimation, but for now it's commented out in favour of plain discounted rewards.)
- Ratios. The actor is run again on the saved states, and for each action that was taken, I compute the ratio between the new probability and the probability when it was taken.
- Clipping. This is the core idea of PPO. If the ratio has already moved outside of [1 - ε, 1 + ε] in the direction the advantage is pushing it, that action gets no gradient. The policy can only change a little bit per update, which keeps training from falling apart after one bad batch. I use ε = 0.12.
- Back propagation. Since NeuralNetLib has no automatic differentiation, I compute the gradient for each output directly and back propagate it through the actor:
if (batchActions[i1][i2] == 0) {
actorGradient[i1][i2] = 0;
} else {
actorGradient[i1][i2] = batchAdvantages[i1] / (oldProbs[i1][i2] + 1E-10);
if (clippedRatios[i1][i2] < weightedRatios[i1][i2]) { // If the clipped value was used.
double ratio = ratios[i1][i2];
if (ratio > 1.0 + clipParam || ratio < 1.0 - clipParam) { // And it was clipped
actorGradient[i1][i2] = 0; // Don't update any further, gradient is zero.
}
}
}
- The critic is trained towards the actual return (advantage + its old estimate), so its estimates get better over time.
Running it
Training runs for up to 20,000 episodes, with a small window containing a Stop button. When you stop it, the actor and critic are saved to actor.model and critic.model, and the game opens in a window where you can watch the two agents play, with the block each one is targeting highlighted.
Demo
Here are the agents from my saved models playing four games. Both players are blue, the red flag belongs to player 1 and the pink flag to player 2, and a green square is the block a player is trying to break that step. The first game is a typical one where nobody reaches a flag in time, and the other three end with a flag being broken.
Over 1,000 games, the trained agents broke a flag in about 10% of games, compared to about 2% for untrained networks of the same size. The bigger difference is in how they move: the trained agents end a game about half as far from the enemy flag as they started (68 squares on average down to 37), while untrained ones don't get any closer.
Better inputs and outputs
Looking back, the inputs and outputs made the problem harder than it needed to be. The reward only depends on getting closer to the enemy flag, but the network had to work that out from absolute positions, and most of its inputs (the blocks around it, its own flag and the opponent) had nothing to do with the reward. Breaking was also a separate yes/no decision on top of choosing a block, and almost every block it could choose was empty space.
So I changed the inputs and outputs and left the PPO code alone:
- 54 inputs, all relative to the enemy flag from the player's point of view: the direction to it, the offset to it (precise up close), the distance, and which of the 49 squares around the player it's in once it's close enough. The player's own flag and the opponent are gone, since the reward doesn't depend on them.
- 59 outputs. The player only picks one of the 49 blocks once the enemy flag is within reach, so there's no separate break decision. Movement has 5 speeds per axis instead of 4, including 0, so a player can move in a straight line or stop.
Then I trained 3 networks with the old inputs and outputs and 3 with the new ones, 20,000 episodes each, and played 1,000 games with each network:
| Flag broken | Steps per game | Distance from the flag at the end | |
|---|---|---|---|
| My original saved models | 11% | 233 | 37 |
| Old inputs and outputs, retrained | 26–94% | 108–212 | 3–15 |
| New inputs and outputs | 99.6–99.9% | 83–89 | 2 |
The new version breaks the flag in almost every game, and all three runs ended up in the same place, while the old version depends heavily on its random starting weights. These are the first four games one of the new networks played, with nothing picked out: