bitsim
Model, simulate, estimate and control robots in C++
Loading...
Searching...
No Matches
Evolution strategies over several ranks

Swinging a pole up with evolution strategies learns to swing a pole up with an evolution strategy, on the threads of one process. Here the episodes of every generation are shared out among several ranks: threads, processes or machines. The ranks exchange only the returns of their episodes, not the weights of the network or its gradients, and every rank ends with exactly the parameters of a run on one rank.

What you need

Nothing beyond bitrl. The ranks meet through c10d::TCPStore, the key-value store that comes with libtorch, as in PPO over several ranks. Ranks on other machines need to reach rank 0's port.

Only the returns travel

A generation of EvolutionStrategy is \(n\) pairs of episodes, one at \(\theta + \sigma\epsilon_k\) and one at \(\theta - \sigma\epsilon_k\). With ranks, rank \(r\) plays the pairs \(k\) with \(k \bmod W = r\):

TCPStoreCommunicator communicator(host, port, rank, n_ranks); // rank 0 runs the store
EvolutionStrategy es(config, initial_parameters); // alike on every rank
for (uint_t g = 0; g < generations; ++g)
es.step(fitness, communicator); // this rank's pairs, then the others' returns

The noise \(\epsilon_k\) of pair \(k\) in generation \(g\) is drawn from the seed task_seed(task_seed(seed, g), k), so every rank can draw every direction itself. Once it has the returns of all the pairs, every rank computes the same gradient, adding the pairs in the same order, and takes the same Adam step. That keeps the ranks alike without ever sending a parameter, and the run is the run on one rank, to the last bit.

The noise is drawn with PortableNormal, the Box-Muller transform of std::mt19937_64, rather than std::normal_distribution: the C++ standard fixes the numbers of std::mt19937_64 but leaves the normal distribution to the library, and ranks on machines with different libraries would otherwise draw different noise.

A rank sends the returns of its own pairs, 16 numbers here, 128 bytes, whatever the size of the network. PPO over several ranks sends every rank's gradients instead, 4 bytes per weight: a network of a million weights would send 4 MB per rank and update, and ES would still send 128 bytes. That is why evolution strategies scale to thousands of cores.

Running the example

./es_distributed # one rank, then 4 ranks as threads
for r in 0 1 2 3; do ./es_distributed --rank $r --ranks 4 & done; wait # 4 processes

With --rank, each process is one rank. Rank 0 runs the store at --host and --port (127.0.0.1 and 29541 by default), and the others connect to it, from this machine or another. Every rank plays its episodes on one thread, so that the times compare ranks, not threads.

Output

Swinging the pole up: 300 generations of 64 episodes
1. One rank, on one thread
8.67 s; the return of the mean policy 288.9
2. 4 ranks, each on one thread, every rank 8 of the 32 pairs
2.99 s, a speed-up of 2.90; the return of the mean policy 288.9
every rank ended with the parameters of the one rank, to the last bit: true (checksum 91f1b53333f47f40)
every generation each rank sends the returns of its own pairs, at most 16 numbers, 128 bytes,
and receives the others': 64 returns in all
a gradient of this network would be 452 bytes; of a network of a million weights, 4 MB:
the returns stay 128 bytes, however large the network

Run as four processes, every rank printed checksum 91f1b53333f47f40 too, in 2.8 to 3.1 s.

Four ranks train about 3 times faster than one, not 4 times: every generation waits for the slowest rank, and the ranks share the cores of this laptop with each other. The speed-up varies from run to run, between about 2.5 and 3.4. On separate machines, each rank has its cores to itself.

Things to try

  1. Run 3 ranks. The 32 pairs no longer share out evenly: does the checksum still match?
  2. Run two ranks on two machines: --host is rank 0's address on both.
  3. Give the network 64 hidden units instead of 16. How much more does a generation cost, and how much more does a rank send?

The code

// Evolution strategies over several ranks: every rank plays some of the episodes of a
// generation, and the ranks exchange only the returns, since every rank can draw every
// perturbation from the shared seed.
//
// Usage: es_distributed [--generations N] [--ranks N]
// es_distributed --rank R --ranks N [--generations N] [--host H] [--port P]
//
// Without --rank, the example trains on one rank, and then on N ranks as threads of this
// process, each on one thread. With --rank, it is one rank of N processes; rank 0 runs the
// store at --host:--port.
#include <chrono>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <thread>
#include <vector>
namespace
{
using namespace bitrl::rl::algos::es;
const uint_t MAX_STEPS = 500;
const MLPPolicy NET({5, 16, 1});
// the task of es_cart_pole_swing_up
real_t fitness(const std::vector<real_t> &p, uint_t g, uint_t k)
{
CartPoleSwingUp env;
env.make("v1", {{"max_steps", MAX_STEPS}}, {});
auto act = [&p](const std::vector<real_t> &o)
{ return NET.act_continuous(p, {o[0] / 2.4, o[1] / 3.0, o[2], o[3], o[4] / 10.0}, 10.0); };
return episode_return(env, act, task_seed(g, k), MAX_STEPS);
}
std::vector<real_t> initial_parameters()
{
auto p = NET.initial_parameters(1);
for (std::size_t j = p.size() - 17; j < p.size(); ++j)
{
p[j] *= 0.1;
}
return p;
}
ESConfig config()
{
c.n_pairs = 32;
c.sigma = 0.1;
c.learning_rate = 0.03;
return c;
}
double seconds_since(std::chrono::steady_clock::time_point start)
{
return std::chrono::duration<double>(std::chrono::steady_clock::now() - start).count();
}
// run f on a thread of a pool of one, where parallel_for runs every episode on that thread
template <typename F> void on_one_thread(F &&f)
{
ThreadPool one(1);
one.submit([&] { f(one); }).get();
}
struct Run
{
std::uint64_t checksum{0};
real_t return_of_mean{0.0};
double seconds{0.0};
};
// train on this rank; communicator is null for a run without ranks
Run train(Communicator *communicator, uint_t generations)
{
Run run;
on_one_thread(
[&](ThreadPool &pool)
{
EvolutionStrategy es(config(), initial_parameters());
const auto start = std::chrono::steady_clock::now();
for (uint_t g = 0; g < generations; ++g)
{
if (communicator)
{
es.step(fitness, *communicator, pool);
}
else
{
es.step(fitness, pool);
}
}
run.seconds = seconds_since(start);
run.checksum = es.checksum();
run.return_of_mean = fitness(es.parameters(), 1000000, 0);
});
return run;
}
void report_traffic(uint_t ranks)
{
const uint_t pairs = config().n_pairs;
const uint_t most = 2 * ((pairs + ranks - 1) / ranks);
std::printf(" every generation each rank sends the returns of its own pairs, at most %lu "
"numbers, %lu bytes,\n and receives the others': %lu returns in all\n",
most, most * sizeof(real_t), 2 * pairs);
std::printf(" a gradient of this network would be %lu bytes; of a network of a million "
"weights, 4 MB:\n the returns stay %lu bytes, however large the network\n",
NET.n_parameters() * sizeof(float), most * sizeof(real_t));
}
} // namespace
int main(int argc, char **argv)
{
uint_t generations = 300, ranks = 4;
long rank = -1;
std::string host = "127.0.0.1";
uint_t port = 29541;
for (int i = 1; i + 1 < argc; i += 2)
{
const std::string a = argv[i];
const char *v = argv[i + 1];
if (a == "--generations")
generations = std::strtoul(v, nullptr, 10);
else if (a == "--ranks")
ranks = std::strtoul(v, nullptr, 10);
else if (a == "--rank")
rank = std::strtol(v, nullptr, 10);
else if (a == "--host")
host = v;
else if (a == "--port")
port = std::strtoul(v, nullptr, 10);
}
if (ranks == 0 || generations == 0)
{
std::fprintf(stderr, "need --ranks and --generations of at least 1\n");
return 1;
}
if (rank >= 0)
{
TCPStoreCommunicator communicator(host, port, static_cast<uint_t>(rank), ranks);
const auto run = train(&communicator, generations);
std::printf("rank %ld of %lu: %lu generations in %.2f s, return of the mean %.1f, "
"checksum %lx\n",
rank, ranks, generations, run.seconds, run.return_of_mean, run.checksum);
return 0;
}
std::printf("Swinging the pole up: %lu generations of %lu episodes\n\n", generations,
2 * config().n_pairs);
std::printf("1. One rank, on one thread\n");
const auto alone = train(nullptr, generations);
std::printf(" %.2f s; the return of the mean policy %.1f\n\n", alone.seconds,
alone.return_of_mean);
std::printf("2. %lu ranks, each on one thread, every rank %lu of the %lu pairs\n", ranks,
(config().n_pairs + ranks - 1) / ranks, config().n_pairs);
std::vector<Run> runs(ranks);
std::vector<std::thread> threads;
for (uint_t r = 0; r < ranks; ++r)
{
threads.emplace_back(
[&, r]
{
TCPStoreCommunicator communicator(host, port, r, ranks);
runs[r] = train(&communicator, generations);
});
}
for (auto &t : threads)
{
t.join();
}
bool same = true;
for (const auto &run : runs)
{
same = same && run.checksum == alone.checksum;
}
std::printf(" %.2f s, a speed-up of %.2f; the return of the mean policy %.1f\n",
runs[0].seconds, alone.seconds / runs[0].seconds, runs[0].return_of_mean);
std::printf(" every rank ended with the parameters of the one rank, to the last bit: %s "
"(checksum %lx)\n",
same ? "true" : "false", alone.checksum);
report_traffic(ranks);
return same ? 0 : 1;
}
Swing the pole of a cart-pole up from hanging down, and keep it up, with a force that can take any va...
Definition cart_pole_swing_up.h:44
The evolution strategy of Salimans et al. (2017): a search for the parameters that maximise a fitness...
Definition evolution_strategy.h:100
A small neural network whose weights are a flat vector of parameters, for EvolutionStrategy.
Definition mlp_policy.h:30
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
A fixed number of threads that run the tasks given to them, in the order given.
Definition thread_pool.h:33
int main()
Definition discounted_returns.cpp:19
Definition es_config.h:9
real_t episode_return(EnvType &env, Act &&act, uint_t seed, uint_t max_steps)
The undiscounted return of one episode of env, reset with seed, acting with act, at most max_steps st...
Definition mlp_policy.h:153
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
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
json run(const Config &c, real_t learning_rate, const fs::path &dir, bitrl::network::TensorboardServer *tensorboard)
Definition log_experiment.cpp:106
Run train(GridObservation observation, uint_t seed, uint_t n_episodes)
Definition multi_agent_grid_world.cpp:57
std::vector< T > get(const std::vector< experience_tuple_type > &experience)
Definition dqn_experience_replay.cpp:132
The settings of EvolutionStrategy.
Definition es_config.h:15
real_t sigma
the standard deviation of the perturbations
Definition es_config.h:17
uint_t n_pairs
antithetic pairs per generation: 2 * n_pairs evaluations
Definition es_config.h:16
real_t learning_rate
Adam's step size.
Definition es_config.h:18