Nothing beyond bitrl. The ranks meet through c10d::TCPStore, the key-value store that comes with libtorch. Ranks on other machines need to reach rank 0's port.
Every rank gets exactly the same mean, to the last bit, because the ranks add their gradients in the same order, the order of the ranks. So every rank's Adam takes the same step, and the ranks stay alike: they are one network, trained on the episodes of all of them. The example checks that with a checksum of every rank's networks.
Every gradient goes through the store, so each rank receives the gradients of every rank. For the networks of RL, a few thousand weights, that takes a fraction of a millisecond. Networks of millions of weights want a ring all-reduce, such as Gloo's or MPI's, behind the same Communicator. libtorch has Gloo compiled in, but does not ship its headers.
Each rank normalises the advantages of its own episodes. The actor samples with a generator of its own, so ranks that are threads of one process do not share libtorch's generator.
Sharing out the episodes saves little with 8 episodes per update. Most of a round is spent playing the episodes, a step at a time, and a call of the policy costs about the same for the 2 states of a rank as for the 8 states of one thread. What the ranks share is the update. With 32 episodes per update the update takes longer, and 4 ranks train in less time. On one machine, ParallelPPOSolver with its copies on threads does much the same. Ranks pay off when the episodes outgrow one machine, or when every rank has an expensive simulation of its own.
The two solvers don't learn the same thing: the ranks normalise their advantages apart, and play other episodes. Both learn to keep the pole up.
#include <ATen/CPUGeneratorImpl.h>
#include <torch/torch.h>
#include <algorithm>
#include <any>
#include <chrono>
#include <cstdint>
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <map>
#include <memory>
#include <string>
#include <thread>
#include <tuple>
#include <vector>
{
using steady = std::chrono::steady_clock;
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))),
generator(at::make_generator<at::CPUGeneratorImpl>(seed))
{
}
{
return logits->forward(torch::tanh(
fc2->forward(torch::tanh(
fc1->forward(states)))));
}
{
const auto log_p = torch::log_softmax(
forward(states), -1);
const auto actions = torch::multinomial(log_p.exp(), 1,
true,
generator);
return {actions.view({-1}), log_p.gather(1, actions).view({-1}).detach()};
}
{
TorchCategorical distribution(out, true);
return {distribution.log_prob(actions.view({-1})), distribution.entropy().mean(), out};
}
{
torch::NoGradGuard no_grad;
forward(torch::tensor(state, torch::dtype(torch::kFloat32))).argmax().item<int64_t>());
}
};
{
:
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)))));
}
};
{
config.gamma = 0.99;
config.clip_epsilon = 0.2;
config.max_passes_over_batch = 4;
config.normalize_advantages = true;
return config;
}
{
{
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)
{
}
}
{
};
{
const uint_t rank = communicator.rank();
envs.use_threads(false);
nets.critic, nets.actor_optimizer,
nets.critic_optimizer, communicator);
const auto start = steady::now();
solver.actions_before_training_begins(envs);
for (
uint_t round = 0; round < n_rounds; ++round)
{
solver.on_training_episode(envs, round);
}
r.time =
seconds(steady::now() - start);
r.returns = solver.global_returns();
r.checksum = solver.checksum();
return r;
}
{
envs.use_threads(false);
ppo_config(n_rounds), 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)
{
solver.on_training_episode(envs, round);
}
r.time =
seconds(steady::now() - start);
r.returns = solver.get_monitor().rewards;
return r;
}
void report(
const std::string &name,
const Rank &r)
{
std::cout << " " << std::left << std::setw(34) << name << std::right << std::fixed
<< std::setprecision(1) << std::setw(7) << r.time << " s" << std::setw(12)
<<
tail_mean(r.returns) << std::setw(15) << r.greedy <<
"\n";
}
{
const uint_t n_rounds = n_episodes / (n_ranks * n_copies);
std::to_string(n_ranks * n_copies) + " per update");
std::cout << " " << std::left << std::setw(34) << "" << std::right << std::setw(9) << "time"
<< std::setw(12) << "last 10 %" << std::setw(15) << "greedy return"
<< "\n";
const auto single =
one_thread(n_rounds, n_ranks * n_copies);
report(
"ParallelPPOSolver, 1 thread", single);
std::vector<std::unique_ptr<Networks>> nets;
for (
uint_t r = 0; r < n_ranks; ++r)
{
nets.push_back(std::make_unique<Networks>(r));
}
std::vector<Rank> ranks(n_ranks);
std::vector<std::thread> threads;
const auto start = steady::now();
for (
uint_t r = 0; r < n_ranks; ++r)
{
threads.emplace_back(
[&, r]
{
ranks[r] =
train_rank(communicator, *nets[r], n_rounds, n_copies);
});
}
for (auto &t : threads)
{
t.join();
}
Rank all = ranks.front();
all.time =
seconds(steady::now() - start);
report(
"DistributedPPOSolver, " + std::to_string(n_ranks) +
" ranks of " +
std::to_string(n_copies),
all);
bool same = true;
for (const auto &r : ranks)
{
same = same && r.checksum == ranks.front().checksum;
}
std::cout << "\n every rank ended with the same networks: " << std::boolalpha << same
<< " (checksum " << std::hex << ranks.front().checksum << std::dec << ")\n\n";
return same;
}
{
const bool a =
compare(
"1. ", n_episodes, n_ranks, n_copies, port);
const bool b =
compare(
"2. ", 2 * n_episodes, n_ranks, 4 * n_copies, port + 1);
return a && b ? 0 : 1;
}
const std::string &host,
uint_t port)
{
const uint_t n_rounds = n_episodes / (n_ranks * n_copies);
std::cout << " rank " << rank << " of " << n_ranks << ": waiting for the others at " << host
<< ":" << port << std::endl;
const auto r =
train_rank(communicator, nets, n_rounds, n_copies);
std::cout << " rank " << rank << ": " << n_rounds << " rounds in " << std::fixed
<< std::setprecision(1) << r.time << " s; mean return of the last 10 % "
<<
tail_mean(r.returns) <<
"; greedy return " << r.greedy <<
"; checksum " << std::hex
<< r.checksum << std::dec << std::endl;
return 0;
}
}
int main(
int argc,
char **argv)
{
bitrl::uint_t n_episodes = 800, n_ranks = 4, n_copies = 2, port = 29531;
bool is_rank = false;
std::string host = "127.0.0.1";
for (int i = 1; i + 1 < argc; i += 2)
{
const std::string flag = argv[i], value = argv[i + 1];
if (flag == "--episodes")
n_episodes = std::strtoul(value.c_str(), nullptr, 10);
else if (flag == "--ranks")
n_ranks = std::strtoul(value.c_str(), nullptr, 10);
else if (flag == "--copies")
n_copies = std::strtoul(value.c_str(), nullptr, 10);
else if (flag == "--rank")
{
rank = std::strtoul(value.c_str(), nullptr, 10);
is_rank = true;
}
else if (flag == "--host")
host = value;
else if (flag == "--port")
port = std::strtoul(value.c_str(), nullptr, 10);
else
{
std::cerr << "unknown option " << flag << "\n";
return 1;
}
}
if (n_ranks == 0 || n_copies == 0 || n_episodes < n_ranks * n_copies)
{
std::cerr << "need --episodes of at least --ranks times --copies\n";
return 1;
}
torch::set_num_threads(1);
try
{
if (is_rank)
{
}
}
catch (const std::exception &e)
{
std::cerr << "Error: " << e.what() << "\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 over several ranks, threads, processes or machines, that average their g...
Definition distributed_ppo.h:52
Proximal policy optimisation that learns from several episodes at once, played by the copies of a bit...
Definition parallel_ppo.h:59
How the ranks of a distributed training exchange numbers.
Definition communicator.h:32
A Communicator through c10d::TCPStore, the key-value store that comes with libtorch.
Definition communicator.h:79
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
void print_title(const std::string &title, std::ostream &out)
An empty line and then the title.
Definition print_utils.cpp:17
std::size_t uint_t
uint_t
Definition bitsim_types.h:40
double real_t
real_t
Definition bitsim_types.h:20
CartPoleState start()
Definition cart_pole_lqr_mpc.cpp:73
Definition ppo_distributed.cpp:48
const uint_t SEED
Definition ppo_distributed.cpp:63
uint_t task_seed(uint_t base_seed, uint_t task) noexcept
A seed for task task, made from base_seed.
Definition parallel.h:148
real_t tail_mean(const std::vector< real_t > &v)
Definition ppo_distributed.cpp:190
int run_threads(uint_t n_episodes, uint_t n_ranks, uint_t n_copies, uint_t port)
Definition ppo_distributed.cpp:316
real_t seconds(steady::duration d)
Definition ppo_distributed.cpp:188
pg::PPOConfig ppo_config(uint_t n_rounds)
Definition ppo_distributed.cpp:134
int run_rank(uint_t rank, uint_t n_episodes, uint_t n_ranks, uint_t n_copies, const std::string &host, uint_t port)
Definition ppo_distributed.cpp:325
Rank train_rank(Communicator &communicator, Networks &nets, uint_t n_rounds, uint_t n_copies)
Definition ppo_distributed.cpp:211
std::chrono::steady_clock steady
Definition ppo_distributed.cpp:61
bool compare(const std::string &title, uint_t n_episodes, uint_t n_ranks, uint_t n_copies, uint_t port)
Definition ppo_distributed.cpp:264
const uint_t MAX_STEPS
Definition ppo_distributed.cpp:64
Rank one_thread(uint_t n_rounds, uint_t n_copies)
Definition ppo_distributed.cpp:236
void report(const std::string &name, const Rank &r)
Definition ppo_distributed.cpp:257
const real_t LEARNING_RATE
Definition ppo_distributed.cpp:65
real_t greedy_return(Actor &actor)
Definition ppo_distributed.cpp:171
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 n_episodes
Number of training episodes.
Definition ppo_config.h:61
at::Generator generator
Definition ppo_distributed.cpp:110
torch::nn::Linear fc2
Definition ppo_distributed.cpp:108
uint_t greedy(const std::vector< real_t > &state)
Definition ppo_distributed.cpp:100
torch::nn::Linear logits
Definition ppo_distributed.cpp:109
std::tuple< torch_tensor_t, torch_tensor_t, torch_tensor_t > evaluate(torch_tensor_t states, torch_tensor_t actions)
Definition ppo_distributed.cpp:92
std::tuple< torch_tensor_t, torch_tensor_t > act_batch(torch_tensor_t states)
Definition ppo_distributed.cpp:85
torch::nn::Linear fc1
Definition ppo_distributed.cpp:107
torch_tensor_t forward(torch_tensor_t states)
Definition ppo_distributed.cpp:79
ActorImpl(uint_t seed=SEED)
Definition ppo_distributed.cpp:71
Definition ppo_distributed.cpp:115
torch::nn::Linear value
Definition ppo_distributed.cpp:130
torch::nn::Linear fc2
Definition ppo_distributed.cpp:129
torch_tensor_t forward(torch_tensor_t states)
Definition ppo_distributed.cpp:123
CriticImpl()
Definition ppo_distributed.cpp:116
torch::nn::Linear fc1
Definition ppo_distributed.cpp:128
Definition ppo_distributed.cpp:149
std::unique_ptr< torch::optim::Optimizer > critic_optimizer
Definition ppo_distributed.cpp:153
Critic critic
Definition ppo_distributed.cpp:151
Networks(uint_t rank)
Definition ppo_distributed.cpp:155
std::unique_ptr< torch::optim::Optimizer > actor_optimizer
Definition ppo_distributed.cpp:152
Actor actor
Definition ppo_distributed.cpp:150
Definition ppo_distributed.cpp:203
real_t time
Definition ppo_distributed.cpp:207
std::vector< real_t > returns
Definition ppo_distributed.cpp:204
std::uint64_t checksum
Definition ppo_distributed.cpp:205
real_t greedy
Definition ppo_distributed.cpp:206