bitsim
Model, simulate, estimate and control robots in C++
Loading...
Searching...
No Matches
PPO on CartPole

This example trains an agent to balance the pole of CartPole with proximal policy optimization (PPO). CartPole has two actions, push the cart left and push it right, and an episode ends when the pole falls over or the cart leaves the track, or after 500 steps. The environment runs on the bitrl-rest-api server, which the example talks to at http://0.0.0.0:8001/api, so start the server first.

The policy PPO learned, playing greedily: it keeps the pole up for 339 of the 500 steps.

PPO

PPO is an actor-critic method. The actor is the policy, \(\pi_\theta(\alpha | s)\), and the critic estimates the value of a state, \(V(s)\). After an episode, the advantage of every step is how much better its discounted return \(G_t\) was than the critic expected, \(A_t = G_t - V(s_t)\). A policy gradient step raises the probability of the actions with a positive advantage; PPO limits how far one step can go. With the ratio \(\rho_t = \pi_\theta(\alpha_t | s_t) / \pi_{\theta_{old}}(\alpha_t | s_t)\) of the new and the old probability of an action, it maximises

\[\min\left( \rho_t A_t, \; \mathrm{clip}(\rho_t, 1 - \epsilon, 1 + \epsilon) A_t \right) , \]

so moving \(\rho_t\) further than \(\epsilon\) from 1 gains nothing. Because of that, it can make several passes over the same episode without the policy running away from the one that collected it.

PPOSolver collects an episode of at most 500 steps, normalises the advantages, and makes 4 passes over it, each minimising the clipped actor loss plus half the squared error of the critic minus 0.01 times the entropy of the policy. The example uses \(\gamma = 0.99\), \(\epsilon = 0.2\), and Adam with a learning rate of 0.001 for both networks, built with bitrl's optimizer factory, for 500 episodes.

The networks

PPOSolver takes the actor and the critic as types, and calls

  • actor->act(state), which samples an action and returns it with its log probability;
  • actor->evaluate(states, actions), which returns the log probabilities of a batch of actions, the entropy of the policy and the network's output;
  • critic->evaluate(state) and critic->forward(states), the value of a state and of a batch.

Here the actor has two hidden layers of 64 units and gives the logits of the two actions, and TorchCategorical is the distribution over them, as in A policy network. The critic has the same hidden layers and one output.

The results

The mean return of the training episodes, a hundred at a time:

Episodes Mean return
1-100 273
101-200 283
201-300 357
301-400 434
401-500 450

Every episode starts from the next seed, so from a different state. The training took 119 s, most of it in the HTTP requests to the server, one per step. After training the example plays an episode with the greedy policy, the action with the larger logit, from the next seed, and writes the seed and its actions to episode.csv; the policy kept the pole up for 339 of the 500 steps. The returns were still rising when training stopped: more episodes would help. examples/tools/episode_gif.py replays them in Gymnasium to make the GIF above:

python examples/tools/episode_gif.py --env CartPole-v1 --actions episode.csv --fps 50 --out ppo_cartpole.gif

The driver code

// Proximal policy optimization on CartPole
//
// PPO is an actor-critic method. The actor, the policy, is a network whose
// outputs are the logits of a categorical distribution over CartPole's two
// actions, push left and push right; the critic is a network that estimates
// the value of a state. PPOSolver plays an episode, works out how much better
// every action did than the critic expected, and changes the policy towards
// the better actions, but no more than its clipped objective allows.
//
// After training the example plays one episode with the greedy policy and
// writes its actions to episode.csv, which examples/tools/episode_gif.py turns
// into a GIF.
//
// Needs the bitrl-rest-api server at SERVER_URL.
#include <torch/torch.h>
#include <any>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <map>
#include <string>
#include <tuple>
#include <unordered_map>
#include <vector>
namespace ppo_cartpole
{
const std::string SERVER_URL = "http://0.0.0.0:8001/api";
const uint_t SEED = 42;
const uint_t N_EPISODES = 500;
const uint_t MAX_STEPS = 500;
const real_t LEARNING_RATE = 0.001;
torch_tensor_t to_tensor(const std::vector<real_t> &state)
{
return torch::tensor(state, torch::dtype(torch::kFloat32));
}
// The actor: the 4 numbers of the state in, the logits of the 2 actions out
struct ActorImpl : torch::nn::Module
{
: fc1(register_module("fc1", torch::nn::Linear(4, 64))),
fc2(register_module("fc2", torch::nn::Linear(64, 64))),
logits(register_module("logits", torch::nn::Linear(64, 2)))
{
}
{
return logits->forward(torch::tanh(fc2->forward(torch::tanh(fc1->forward(states)))));
}
// a sampled action and its log probability, for PPOSolver
std::tuple<uint_t, torch_tensor_t> act(const std::vector<real_t> &state)
{
TorchCategorical distribution(forward(to_tensor(state)), /*from logits*/ true);
const auto action = distribution.sample();
return {static_cast<uint_t>(action.item<int64_t>()),
distribution.log_prob(action).detach()};
}
// the log probabilities of the actions taken in the states, the entropy
// of the policy, and the logits, for PPOSolver's update
std::tuple<torch_tensor_t, torch_tensor_t, torch_tensor_t> evaluate(torch_tensor_t states,
torch_tensor_t actions)
{
const auto out = forward(states);
TorchCategorical distribution(out, /*from logits*/ true);
return {distribution.log_prob(actions.view({-1})), distribution.entropy().mean(), out};
}
// the action the policy rates best, to play after training
uint_t greedy(const std::vector<real_t> &state)
{
torch::NoGradGuard no_grad;
return static_cast<uint_t>(forward(to_tensor(state)).argmax().item<int64_t>());
}
torch::nn::Linear fc1;
torch::nn::Linear fc2;
torch::nn::Linear logits;
};
TORCH_MODULE(Actor);
// The critic: the state in, its value out
struct CriticImpl : torch::nn::Module
{
: fc1(register_module("fc1", torch::nn::Linear(4, 64))),
fc2(register_module("fc2", torch::nn::Linear(64, 64))),
value(register_module("value", torch::nn::Linear(64, 1)))
{
}
{
return value->forward(torch::tanh(fc2->forward(torch::tanh(fc1->forward(states)))));
}
torch_tensor_t evaluate(const std::vector<real_t> &state)
{
torch::NoGradGuard no_grad;
return forward(to_tensor(state));
}
torch::nn::Linear fc1;
torch::nn::Linear fc2;
torch::nn::Linear value;
};
TORCH_MODULE(Critic);
typedef bitrl::rl::algos::pg::PPOSolver<env_type, Actor, Critic> solver_type;
} // namespace ppo_cartpole
int main()
{
using namespace ppo_cartpole;
namespace optim = bitrl::maths::optim;
try
{
torch::manual_seed(SEED);
env_type env(server);
std::unordered_map<std::string, std::any> options;
std::unordered_map<std::string, std::any> reset_options{{"seed", std::any(SEED)}};
env.make("v1", options, reset_options);
config.gamma = 0.99;
config.clip_epsilon = 0.2;
config.normalize_advantages = true;
Actor actor;
Critic critic;
std::map<std::string, std::any> opt_options{{"lr", std::any(LEARNING_RATE)}};
const auto options_adam = optim::pytorch::build_pytorch_optimizer_options(
optim::OptimizerType::ADAM, opt_options);
auto actor_optimizer = optim::pytorch::build_pytorch_optimizer(optim::OptimizerType::ADAM,
*actor, *options_adam);
auto critic_optimizer = optim::pytorch::build_pytorch_optimizer(optim::OptimizerType::ADAM,
*critic, *options_adam);
solver_type solver(config, actor, critic, actor_optimizer, critic_optimizer);
bitrl::rl::RLSerialTrainerConfig trainer_config{50, N_EPISODES, 1.0e-8};
trainer.train(env);
// the return of every training episode
const auto &rewards = solver.get_monitor().rewards;
bitsim::utils::io::CSVWriter rewards_file("rewards.csv", ',');
rewards_file.open();
rewards_file.write_column_names({"episode", "return"});
for (uint_t e = 0; e < rewards.size(); ++e)
{
rewards_file.write_row(std::make_tuple(e, rewards[e]));
}
rewards_file.close();
// one episode with the greedy policy, its actions for the GIF
std::ofstream episode("episode.csv");
auto time_step = env.reset();
// the seed the episode started from, for the GIF to start from it too
episode << "# seed " << env.last_reset_seed() << "\n";
real_t total = 0.0;
for (uint_t step = 0; step < MAX_STEPS && !time_step.done(); ++step)
{
const auto action = actor->greedy(time_step.observation());
episode << action << "\n";
time_step = env.step(action);
total += time_step.reward();
}
env.close();
real_t last_50 = 0.0;
for (auto i = rewards.size() - 50; i < rewards.size(); ++i)
{
last_50 += rewards[i] / 50.0;
}
std::cout << "Mean return of the last 50 training episodes: " << last_50 << "\n"
<< "The greedy policy kept the pole up for " << total << " steps of " << MAX_STEPS
<< std::endl;
}
catch (const std::exception &e)
{
std::cerr << "Error: " << e.what() << std::endl;
return 1;
}
return 0;
}
The CartPole class Interface for CartPole environment.
Definition cart_pole_env.h:70
Definition torch_categorical.h:23
Utility class to facilitate HTTP requests between the environments REST API and C++ drivers.
Definition rest_rl_env_client.h:28
Definition rl_serial_agent_trainer.h:41
The CSVWriter class. Handles writing into CSV file format.
Definition csv_file_writer.h:22
int main()
Definition discounted_returns.cpp:19
Definition optimizer_type.h:12
torch::Tensor torch_tensor_t
torch_tensor_t
Definition bitrl_types.h:95
std::size_t uint_t
uint_t
Definition bitsim_types.h:40
double real_t
real_t
Definition bitsim_types.h:20
dict action
Definition play.py:46
env
Definition play.py:33
Definition ppo_cartpole.cpp:40
bitrl::envs::gymnasium::CartPole env_type
Definition ppo_cartpole.cpp:46
const real_t LEARNING_RATE
Definition ppo_cartpole.cpp:52
torch_tensor_t to_tensor(const std::vector< real_t > &state)
Definition ppo_cartpole.cpp:54
const uint_t SEED
Definition ppo_cartpole.cpp:49
TORCH_MODULE(Actor)
const uint_t N_EPISODES
Definition ppo_cartpole.cpp:50
bitrl::rl::algos::pg::PPOSolver< env_type, Actor, Critic > solver_type
Definition ppo_cartpole.cpp:133
const uint_t MAX_STEPS
Definition ppo_cartpole.cpp:51
const std::string SERVER_URL
Definition ppo_cartpole.cpp:48
Vector step(const QuadrotorDynamicsConfig &config, const Vector &x, const Vector &u, real_t max_rotor_speed)
Definition quadrotor_lqr.cpp:114
The RLSerialTrainerConfig struct. Configuration struct for the serial RL agent trainer.
Definition rl_serial_agent_trainer.h:29
The PPOConfig struct. Configuration for PPOSolver class.
Definition ppo_config.h:26
real_t clip_epsilon
Definition ppo_config.h:75
uint_t n_episodes
Number of training episodes.
Definition ppo_config.h:61
uint_t max_itrs_per_episode
Number of iterations per episode.
Definition ppo_config.h:66
bool normalize_advantages
Definition ppo_config.h:80
uint_t max_passes_over_batch
Definition ppo_config.h:73
real_t gamma
Discount factor.
Definition ppo_config.h:31
std::tuple< torch_tensor_t, torch_tensor_t, torch_tensor_t > evaluate(torch_tensor_t states, torch_tensor_t actions)
Definition ppo_cartpole.cpp:85
torch_tensor_t forward(torch_tensor_t states)
Definition ppo_cartpole.cpp:69
torch::nn::Linear fc2
Definition ppo_cartpole.cpp:101
torch::nn::Linear fc1
Definition ppo_cartpole.cpp:100
std::tuple< uint_t, torch_tensor_t > act(const std::vector< real_t > &state)
Definition ppo_cartpole.cpp:75
uint_t greedy(const std::vector< real_t > &state)
Definition ppo_cartpole.cpp:94
ActorImpl()
Definition ppo_cartpole.cpp:62
torch::nn::Linear logits
Definition ppo_cartpole.cpp:102
Definition ppo_cartpole.cpp:108
torch::nn::Linear value
Definition ppo_cartpole.cpp:129
CriticImpl()
Definition ppo_cartpole.cpp:109
torch_tensor_t evaluate(const std::vector< real_t > &state)
Definition ppo_cartpole.cpp:121
torch::nn::Linear fc2
Definition ppo_cartpole.cpp:128
torch::nn::Linear fc1
Definition ppo_cartpole.cpp:127
torch_tensor_t forward(torch_tensor_t states)
Definition ppo_cartpole.cpp:116