bitsim
Model, simulate, estimate and control robots in C++
Loading...
Searching...
No Matches
PPO from several episodes at once

PPO on CartPole learns to balance the pole of CartPole with PPOSolver, which plays an episode, learns from it, and plays the next. This example learns from several episodes at once: ParallelPPOSolver plays an episode in each of 8 copies of the environment at the same time, and learns from the 8 together.

The mean return per episode, learned from one episode or from 8 at a time

What you need

Nothing beyond bitrl: the example uses bitrl::envs::classic_control::CartPole, the cart-pole of Gymnasium simulated in the example's own process with bitsim's cart-pole dynamics, so it needs no server. Its dynamics integrate with Runge-Kutta rather than Gymnasium's Euler step, so the numbers are close to Gymnasium's, not the same.

Several copies of an environment

ParallelEnvs holds copies of an environment, each made with the same options and its own seed. step() takes an action per copy and steps every copy whose episode is not over, on the threads of bitsim's thread pool:

ParallelEnvs<CartPole> envs(8);
envs.make("v1", {{"max_steps", uint_t(500)}}, {{"seed", uint_t(42)}}); // copy i: task_seed(42, i)
const auto &first = envs.reset();
const auto &next = envs.step(actions); // an action per copy
std::size_t uint_t
uint_t
Definition bitsim_types.h:40

Learning from all of them

Every training round of ParallelPPOSolver resets the copies and plays an episode in each. At every step it puts the states of the copies still playing into one batch, and the policy acts for all of them with one call, act_batch(states). Then the networks learn from all the episodes of the round with PPO's clipped objective, as PPOSolver does from one: the advantage of a step is its discounted return, within its own episode, minus the critic's value of the state.

The actions are sampled on the trainer's thread, so a training is the same whatever the number of threads that step the copies. The example checks that.

Running the example

./ppo_parallel_rollouts # 800 episodes, 8 copies
./ppo_parallel_rollouts --episodes 1600 --copies 16

Output

1. The same number of episodes, learned from one or 8 at a time
800 episodes of CartPole, at most 500 steps each
time steps last 10 % greedy return
PPOSolver 38.8 s 329703 493.9 500.0
ParallelPPOSolver 6.7 s 308851 487.3 500.0
and copies on threads 7.7 s 308851 487.3 500.0
the copies on threads learned the same: true
2. An environment whose step takes 1000 microseconds
3 rounds of 8 episodes, 614 steps
the copies one after the other: 0.65 s; on 9 threads: 0.20 s, a speed-up of 3.15
the same episodes: true

Both learn to keep the pole up for all 500 steps; the greedy return is the mean of 20 episodes from starts neither trained on. Episode for episode, PPOSolver climbs faster at first: it updates the networks after every episode, 8 times as often. ParallelPPOSolver's curve is smoother, since every update averages over 8 episodes, and the training takes a sixth of the time: one call of the policy on a batch of 8 states costs little more than a call on one, and it makes an eighth of the updates.

Stepping the copies of CartPole on threads gains nothing: a step of CartPole takes well under a microsecond, less than handing it to a thread. It pays off when a step takes time, as it does for a physics engine such as Chrono, or an environment on a server. The second part gives every step 1 ms of computing, and there the 8 copies on 4 cores run 3 times as fast. Use envs.use_threads(false) for cheap environments.

The example sets torch::set_num_threads(1): on networks this small libtorch's own threads cost more than they gain, and they compete with the thread pool.

Things to try

  1. Train with 4 and with 16 copies on the same number of episodes. Which reaches a return of 400 in the fewest seconds?
  2. Make max_passes_over_batch 8 for ParallelPPOSolver. Does it catch up with PPOSolver episode for episode?
  3. Leave libtorch its threads (remove torch::set_num_threads(1)). How long do the trainings take?

The code

// Proximal policy optimisation on CartPole, learning from several episodes at once.
//
// PPOSolver learns from one episode at a time. ParallelPPOSolver plays an episode in each of the
// copies of a ParallelEnvs at the same time, with one call of the policy for all of them at every
// step, and learns from all the episodes together. The example trains both on the same number of
// episodes of bitrl's own CartPole, which needs no server, and then shows what stepping the copies
// on threads gains when an environment step takes time, as a physics engine's does.
//
// Usage: ppo_parallel_rollouts [--episodes N] [--copies N]
//
// Writes returns.csv, the mean return per episode of both trainings, to the working directory.
#include <torch/torch.h>
#include <algorithm>
#include <any>
#include <chrono>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <map>
#include <string>
#include <tuple>
#include <unordered_map>
#include <vector>
{
namespace pg = bitrl::rl::algos::pg;
namespace optim = bitrl::maths::optim;
using steady = std::chrono::steady_clock;
const uint_t SEED = 42;
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)))));
}
// one state, 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()};
}
// a batch of states, a row each, for ParallelPPOSolver
std::tuple<torch_tensor_t, torch_tensor_t> act_batch(torch_tensor_t states)
{
TorchCategorical distribution(forward(states), /*from logits*/ true);
const auto actions = distribution.sample();
return {actions, distribution.log_prob(actions).detach()};
}
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};
}
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);
// CartPole whose every step also takes STEP_COST of computing, as a physics engine's step would
{
static constexpr real_t STEP_COST = 1.0e-3; // [s]
void make(const std::string &version,
const std::unordered_map<std::string, std::any> &make_options,
const std::unordered_map<std::string, std::any> &reset_options)
{
env.make(version, make_options, reset_options);
}
time_step_type reset() { return env.reset(); }
{
const auto until = steady::now() + std::chrono::duration_cast<steady::duration>(
std::chrono::duration<real_t>(STEP_COST));
while (steady::now() < until)
{
}
return env.step(action);
}
void close() { env.close(); }
CartPole env;
};
{
pg::PPOConfig config;
config.gamma = 0.99;
config.clip_epsilon = 0.2;
config.max_passes_over_batch = 4;
config.normalize_advantages = true;
return config;
}
// An actor, a critic and their optimisers, from the same seed every time
struct Networks
{
Actor actor;
Critic critic;
std::unique_ptr<torch::optim::Optimizer> actor_optimizer;
std::unique_ptr<torch::optim::Optimizer> critic_optimizer;
{
torch::manual_seed(SEED);
actor = Actor();
critic = Critic();
std::map<std::string, std::any> options{{"lr", std::any(LEARNING_RATE)}};
const auto adam =
optim::pytorch::build_pytorch_optimizer_options(optim::OptimizerType::ADAM, options);
optim::pytorch::build_pytorch_optimizer(optim::OptimizerType::ADAM, *actor, *adam);
optim::pytorch::build_pytorch_optimizer(optim::OptimizerType::ADAM, *critic, *adam);
}
};
// The mean return of the greedy policy over 20 episodes it has not trained on
real_t greedy_return(Actor &actor)
{
env.make("v1", {{"max_steps", MAX_STEPS}}, {});
real_t total = 0.0;
for (uint_t k = 0; k < 20; ++k)
{
auto step = env.reset(1000 + k);
while (!step.last())
{
step = env.step(actor->greedy(step.observation()));
total += step.reward();
}
}
return total / 20.0;
}
real_t seconds(steady::duration d) { return std::chrono::duration<real_t>(d).count(); }
real_t tail_mean(const std::vector<real_t> &v)
{
const auto n = std::max<std::size_t>(1, v.size() / 10);
real_t sum = 0.0;
for (auto i = v.size() - n; i < v.size(); ++i)
{
sum += v[i];
}
return sum / n;
}
struct Training
{
std::vector<real_t> returns; // per episode
real_t time{0.0};
real_t greedy{0.0};
};
// PPOSolver: an update after every episode
{
env.make("v1", {{"max_steps", MAX_STEPS}}, {{"seed", SEED}});
Networks nets;
auto config = ppo_config();
config.n_episodes = n_episodes;
solver_type solver(config, nets.actor, nets.critic, nets.actor_optimizer,
nets.critic_optimizer);
bitrl::rl::RLSerialAgentTrainer<CartPole, solver_type> trainer(
{bitsim::consts::INVALID_ID, n_episodes, 1.0e-8}, solver);
const auto start = steady::now();
trainer.train(env);
t.time = seconds(steady::now() - start);
t.returns = solver.get_monitor().rewards;
for (const auto r : t.returns)
{
t.n_steps += static_cast<uint_t>(r);
}
t.greedy = greedy_return(nets.actor);
return t;
}
// ParallelPPOSolver: an update after every round of n_copies episodes
template <typename Env>
Training in_rounds(uint_t n_episodes, uint_t n_copies, bool threads, uint_t max_rounds = 0)
{
ParallelEnvs<Env> envs(n_copies);
envs.make("v1", {{"max_steps", MAX_STEPS}}, {{"seed", SEED}});
envs.use_threads(threads);
Networks nets;
auto config = ppo_config();
uint_t n_rounds = n_episodes / n_copies;
if (max_rounds)
{
n_rounds = std::min(n_rounds, max_rounds);
}
config.n_episodes = n_rounds;
solver_type solver(config, nets.actor, nets.critic, nets.actor_optimizer,
nets.critic_optimizer);
const auto start = steady::now();
// the trainer's loop, by hand, to keep the return of every episode of every round
solver.actions_before_training_begins(envs);
for (uint_t round = 0; round < n_rounds; ++round)
{
const auto info = solver.on_training_episode(envs, round);
t.returns.insert(t.returns.end(), solver.last_returns().begin(),
solver.last_returns().end());
t.n_steps += info.episode_iterations;
}
t.time = seconds(steady::now() - start);
t.greedy = greedy_return(nets.actor);
return t;
}
void report(const std::string &name, const Training &t)
{
std::cout << " " << std::left << std::setw(26) << name << std::right << std::fixed
<< std::setprecision(1) << std::setw(8) << t.time << " s" << std::setw(10)
<< t.n_steps << std::setw(12) << tail_mean(t.returns) << std::setw(14) << t.greedy
<< "\n";
}
int run(uint_t n_episodes, uint_t n_copies)
{
// the networks are small: libtorch's own threads cost more than they gain
torch::set_num_threads(1);
bitsim::utils::io::print_title("1. The same number of episodes, learned from one or " +
std::to_string(n_copies) + " at a time");
std::cout << " " << n_episodes << " episodes of CartPole, at most " << MAX_STEPS
<< " steps each\n\n"
<< " " << std::left << std::setw(26) << "" << std::right << std::setw(10) << "time"
<< std::setw(10) << "steps" << std::setw(12) << "last 10 %" << std::setw(14)
<< "greedy return"
<< "\n";
const auto one = one_at_a_time(n_episodes);
report("PPOSolver", one);
const auto many = in_rounds<CartPole>(n_episodes, n_copies, false);
report("ParallelPPOSolver", many);
const auto threaded = in_rounds<CartPole>(n_episodes, n_copies, true);
report(" and copies on threads", threaded);
std::cout << " the copies on threads learned the same: " << std::boolalpha
<< (threaded.returns == many.returns) << "\n\n";
std::ofstream out("returns.csv");
out << "episode,one_at_a_time,in_rounds\n";
for (std::size_t e = 0; e < std::min(one.returns.size(), many.returns.size()); ++e)
{
out << e << "," << one.returns[e] << "," << many.returns[e] << "\n";
}
bitsim::utils::io::print_title("2. An environment whose step takes " +
std::to_string(static_cast<int>(SlowCartPole::STEP_COST * 1e6)) +
" microseconds");
const uint_t ROUNDS = 3;
const auto serial = in_rounds<SlowCartPole>(n_episodes, n_copies, false, ROUNDS);
const auto parallel = in_rounds<SlowCartPole>(n_episodes, n_copies, true, ROUNDS);
std::cout << " " << ROUNDS << " rounds of " << n_copies << " episodes, " << serial.n_steps
<< " steps\n"
<< " the copies one after the other: " << std::setprecision(2) << serial.time
<< " s; on " << threads << " threads: " << parallel.time << " s, a speed-up of "
<< serial.time / parallel.time << "\n"
<< " the same episodes: " << std::boolalpha << (serial.returns == parallel.returns)
<< "\n";
return 0;
}
} // namespace ppo_parallel_rollouts
int main(int argc, char **argv)
{
bitrl::uint_t n_episodes = 800;
bitrl::uint_t n_copies = 8;
for (int i = 1; i + 1 < argc; i += 2)
{
const std::string flag = argv[i];
if (flag == "--episodes")
n_episodes = std::strtoul(argv[i + 1], nullptr, 10);
else if (flag == "--copies")
n_copies = std::strtoul(argv[i + 1], nullptr, 10);
else
{
std::cerr << "unknown option " << flag << "\n";
return 1;
}
}
return ppo_parallel_rollouts::run(n_episodes, n_copies);
}
Several copies of an environment, stepped at the same time on the threads of a bitsim::utils::concurr...
Definition parallel_envs.h:36
The cart-pole of Barto, Sutton and Anderson, simulated in this process with bitsim::dynamics::CartPol...
Definition cart_pole.h:41
Definition torch_categorical.h:23
Proximal policy optimisation that learns from several episodes at once, played by the copies of a bit...
Definition parallel_ppo.h:59
uint_t size() const noexcept
The number of threads.
Definition thread_pool.h:54
base_type::time_step_type time_step_type
Definition cart_pole.h:46
base_type::state_type state_type
Definition cart_pole.h:47
base_type::action_type action_type
Definition cart_pole.h:48
int main()
Definition discounted_returns.cpp:19
Definition optimizer_type.h:12
std::iterator_traits< IteratorType >::value_type sum(IteratorType begin, IteratorType end, bool parallel=true)
Definition vector_math.h:89
Definition a2c.h:37
torch::Tensor torch_tensor_t
torch_tensor_t
Definition bitrl_types.h:95
const uint_t INVALID_ID
Invalid id.
Definition bitsim_consts.h:16
ThreadPool & default_thread_pool()
The pool that parallel_for() and parallel_map() use when given none. It starts ThreadPool::default_n_...
Definition thread_pool.cpp:77
void print_title(const std::string &title, std::ostream &out)
An empty line and then the title.
Definition print_utils.cpp:17
double real_t
real_t
Definition bitsim_types.h:20
CartPoleState start()
Definition cart_pole_lqr_mpc.cpp:73
ValueIteration< env_type > solver_type
Definition value_iteration.cpp:36
dict action
Definition play.py:46
info
Definition play.py:49
env
Definition play.py:33
Definition ppo_parallel_rollouts.cpp:42
const uint_t SEED
Definition ppo_parallel_rollouts.cpp:54
real_t greedy_return(Actor &actor)
Definition ppo_parallel_rollouts.cpp:206
void report(const std::string &name, const Training &t)
Definition ppo_parallel_rollouts.cpp:304
torch_tensor_t to_tensor(const std::vector< real_t > &state)
Definition ppo_parallel_rollouts.cpp:58
std::chrono::steady_clock steady
Definition ppo_parallel_rollouts.cpp:52
const uint_t MAX_STEPS
Definition ppo_parallel_rollouts.cpp:55
int run(uint_t n_episodes, uint_t n_copies)
Definition ppo_parallel_rollouts.cpp:312
const real_t LEARNING_RATE
Definition ppo_parallel_rollouts.cpp:56
Training in_rounds(uint_t n_episodes, uint_t n_copies, bool threads, uint_t max_rounds=0)
Definition ppo_parallel_rollouts.cpp:272
Training one_at_a_time(uint_t n_episodes)
Definition ppo_parallel_rollouts.cpp:245
pg::PPOConfig ppo_config()
Definition ppo_parallel_rollouts.cpp:171
real_t tail_mean(const std::vector< real_t > &v)
Definition ppo_parallel_rollouts.cpp:225
real_t seconds(steady::duration d)
Definition ppo_parallel_rollouts.cpp:223
Vector step(const QuadrotorDynamicsConfig &config, const Vector &x, const Vector &u, real_t max_rotor_speed)
Definition quadrotor_lqr.cpp:114
Print labelled values, one per line, as the examples do: two spaces, the label padded to a width,...
The PPOConfig struct. Configuration for PPOSolver class.
Definition ppo_config.h:26
uint_t max_itrs_per_episode
Number of iterations per episode.
Definition ppo_config.h:66
torch::nn::Linear fc2
Definition ppo_parallel_rollouts.cpp:110
std::tuple< uint_t, torch_tensor_t > act(const std::vector< real_t > &state)
Definition ppo_parallel_rollouts.cpp:79
torch::nn::Linear fc1
Definition ppo_parallel_rollouts.cpp:109
torch::nn::Linear logits
Definition ppo_parallel_rollouts.cpp:111
ActorImpl()
Definition ppo_parallel_rollouts.cpp:66
uint_t greedy(const std::vector< real_t > &state)
Definition ppo_parallel_rollouts.cpp:103
std::tuple< torch_tensor_t, torch_tensor_t, torch_tensor_t > evaluate(torch_tensor_t states, torch_tensor_t actions)
Definition ppo_parallel_rollouts.cpp:95
std::tuple< torch_tensor_t, torch_tensor_t > act_batch(torch_tensor_t states)
Definition ppo_parallel_rollouts.cpp:88
torch_tensor_t forward(torch_tensor_t states)
Definition ppo_parallel_rollouts.cpp:73
Definition ppo_parallel_rollouts.cpp:117
CriticImpl()
Definition ppo_parallel_rollouts.cpp:118
torch::nn::Linear fc1
Definition ppo_parallel_rollouts.cpp:136
torch::nn::Linear value
Definition ppo_parallel_rollouts.cpp:138
torch_tensor_t evaluate(const std::vector< real_t > &state)
Definition ppo_parallel_rollouts.cpp:130
torch::nn::Linear fc2
Definition ppo_parallel_rollouts.cpp:137
torch_tensor_t forward(torch_tensor_t states)
Definition ppo_parallel_rollouts.cpp:125
Definition ppo_parallel_rollouts.cpp:184
std::unique_ptr< torch::optim::Optimizer > critic_optimizer
Definition ppo_parallel_rollouts.cpp:188
Networks()
Definition ppo_parallel_rollouts.cpp:190
Critic critic
Definition ppo_parallel_rollouts.cpp:186
std::unique_ptr< torch::optim::Optimizer > actor_optimizer
Definition ppo_parallel_rollouts.cpp:187
Actor actor
Definition ppo_parallel_rollouts.cpp:185
Definition ppo_parallel_rollouts.cpp:144
CartPole env
Definition ppo_parallel_rollouts.cpp:168
CartPole::state_type state_type
Definition ppo_parallel_rollouts.cpp:146
static constexpr real_t STEP_COST
Definition ppo_parallel_rollouts.cpp:148
CartPole::time_step_type time_step_type
Definition ppo_parallel_rollouts.cpp:145
time_step_type reset()
Definition ppo_parallel_rollouts.cpp:156
CartPole::action_type action_type
Definition ppo_parallel_rollouts.cpp:147
void make(const std::string &version, const std::unordered_map< std::string, std::any > &make_options, const std::unordered_map< std::string, std::any > &reset_options)
Definition ppo_parallel_rollouts.cpp:150
void close()
Definition ppo_parallel_rollouts.cpp:166
time_step_type step(const action_type &action)
Definition ppo_parallel_rollouts.cpp:157
Definition ppo_parallel_rollouts.cpp:237
real_t time
Definition ppo_parallel_rollouts.cpp:239
uint_t n_steps
Definition ppo_parallel_rollouts.cpp:241
std::vector< real_t > returns
Definition ppo_parallel_rollouts.cpp:238
real_t greedy
Definition ppo_parallel_rollouts.cpp:240