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.
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.
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:
#include <torch/torch.h>
#include <any>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <map>
#include <string>
#include <tuple>
#include <unordered_map>
#include <vector>
{
const std::string
SERVER_URL =
"http://0.0.0.0:8001/api";
{
return torch::tensor(state, torch::dtype(torch::kFloat32));
}
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)))));
}
std::tuple<uint_t, torch_tensor_t>
act(
const std::vector<real_t> &state)
{
const auto action = distribution.sample();
distribution.log_prob(action).detach()};
}
{
TorchCategorical distribution(out, true);
return {distribution.log_prob(actions.view({-1})), distribution.entropy().mean(), out};
}
{
torch::NoGradGuard no_grad;
}
};
{
:
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::NoGradGuard no_grad;
}
};
typedef bitrl::rl::algos::pg::PPOSolver<env_type, Actor, Critic>
solver_type;
}
{
try
{
torch::manual_seed(
SEED);
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);
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);
trainer.train(env);
const auto &rewards = solver.get_monitor().rewards;
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();
std::ofstream episode("episode.csv");
auto time_step =
env.reset();
episode <<
"# seed " <<
env.last_reset_seed() <<
"\n";
{
const auto action = actor->greedy(time_step.observation());
time_step =
env.step(action);
total += time_step.reward();
}
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
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
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