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.
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.
#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>
{
using steady = std::chrono::steady_clock;
{
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(
forward(states),
true);
const auto actions = distribution.sample();
return {actions, distribution.log_prob(actions).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;
}
};
{
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);
}
{
const auto until = steady::now() + std::chrono::duration_cast<steady::duration>(
while (steady::now() < until)
{
}
}
};
{
config.gamma = 0.99;
config.clip_epsilon = 0.2;
config.max_passes_over_batch = 4;
config.normalize_advantages = true;
return config;
}
{
{
torch::manual_seed(
SEED);
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);
}
};
{
for (
uint_t k = 0; k < 20; ++k)
{
{
}
}
return total / 20.0;
}
real_t seconds(steady::duration d) {
return std::chrono::duration<real_t>(d).count(); }
{
const auto n = std::max<std::size_t>(1, v.size() / 10);
for (auto i = v.size() - n; i < v.size(); ++i)
{
}
}
{
};
{
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(
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);
}
return t;
}
template <typename Env>
{
envs.use_threads(threads);
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();
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);
return 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";
}
{
torch::set_num_threads(1);
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";
report(
"ParallelPPOSolver", many);
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";
}
" microseconds");
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;
}
}
int main(
int argc,
char **argv)
{
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;
}
}
}
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
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
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