The pole of a cart-pole hangs down, and the cart has to swing it up and then balance it on top. No push of 10 N lifts the pole at once: the cart has to rock back and forth to pump energy into the swing, catch the pole as it goes over the top, and hold it there, all within 2.4 m of the centre. The force can take any value in [-10, 10] N.
Here an evolution strategy learns to do that. It never computes a gradient of the policy: it tries small random changes of the policy's weights, plays an episode with each, and moves the weights towards the changes that did better. The episodes of a generation do not depend on each other, so they all run at the same time, on all the threads.
The learned policy swings the pole up in 1.5 s, and balances it near the centre
What you need
Nothing beyond bitrl. The task is CartPoleSwingUp, simulated in the example's own process with bitsim's cart-pole dynamics, and the policy is an MLPPolicy, a small network that needs no libtorch.
The task
CartPoleSwingUp is the cart and the pole of CartPole, with the pole hanging down at the start. The observation is \([x, \dot x, \sin\theta, \cos\theta, \dot\theta]\), with \(\theta\) from upright, and the action is the force on the cart. Every step of 0.02 s is worth \((1 + \cos\theta)/2 - 0.02 x^2\): 0 for a pole hanging down, 1 for a pole up with the cart at the centre. Leaving the track costs 100 and ends the episode, so the best return over the 500 steps of an episode, 10 s, is a little over 450: the swing up takes time.
The evolution strategy
EvolutionStrategy is the method of Salimans et al. (2017). Its state is one set of parameters \(\theta\), here the 113 weights of a network with 16 tanh units. Every generation it draws 32 directions \(\epsilon_k\) of standard normal noise, and plays one episode at \(\theta + \sigma\epsilon_k\) and one at \(\theta - \sigma\epsilon_k\), with \(\sigma = 0.1\): 64 episodes. Their returns are replaced by their ranks, from -0.5 for the worst to 0.5 for the best, and
\[g = \frac{1}{2 n \sigma} \sum_{k=1}^{n} \left(F(\theta + \sigma\epsilon_k) - F(\theta - \sigma\epsilon_k)\right) \epsilon_k
\]
estimates the direction in which the return grows. Adam takes a step along it. The fitness is any function of the parameters:
const MLPPolicy net({5, 16, 1});
auto fitness = [&](const std::vector<real_t> &p, uint_t generation, uint_t pair) {
CartPoleSwingUp env;
env.make("v1", {{"max_steps", uint_t(500)}}, {});
auto act = [&](const std::vector<real_t> &obs) { return net.act_continuous(p, scaled(obs), 10.0); };
};
EvolutionStrategy es(config, initial_parameters);
for (uint_t g = 0; g < 1500; ++g)
es.step(fitness);
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
Both episodes of a pair start from the same state, seeded with the generation and the pair, so the difference of their returns comes from the change of the weights, not from the luck of the start. The ranks make the method blind to how far apart the returns are, so a few episodes that end off the track, at -100, do not swamp the others. Equal returns share their rank and so point nowhere.
Many threads, the same result
step() plays the 64 episodes on the threads of bitsim's pool. The noise of pair \(k\) in generation \(g\) is drawn from its own seed, task_seed(task_seed(seed, g), k), and the gradient adds the pairs in their order, so the result does not depend on the number of threads, nor on which thread plays which episode. The example checks that by training again on one thread.
Running the example
./es_cart_pole_swing_up [--generations 1500] [--csv swing_up.csv]
python examples/tools/cart_pole_gif.py swing_up.csv --out es_cart_pole_swing_up.gif
Output
1. Learning to swing up, 1500 generations of 64 episodes, on 9 threads
the policy has 113 parameters
generation mean return best return return of the mean
0 -84.4 16.9 -104.4
250 261.5 309.7 288.7
500 326.1 356.5 351.5
750 297.5 448.7 448.5
1000 392.2 451.7 449.9
1250 413.9 452.0 452.1
1499 409.2 452.1 451.8
in 13.1 s
2. The first 50 generations again, on one thread
1.35 s against 0.42 s on 9 threads, a speed-up of 3.22
the same parameters, to the last bit: true
3. The learned policy, from 20 starts it never trained on
start return up after [s] up in the last 5 s furthest from the centre [m]
0 451.7 1.46 100 % 0.68
1 452.3 1.46 100 % 0.64
2 452.4 1.46 100 % 0.63
3 452.4 1.46 100 % 0.62
4 451.1 1.46 100 % 0.70
...
up for the whole of the last 5 s from 20 of 20 starts; up 100 % of that time on average
At first most episodes run off the track, at -100. The return of the mean policy passes 440 after about 750 generations, when it learns to catch the pole at the top. In the end it swings the pole up in under 1.5 s and holds it up for the whole of the last 5 s from all 20 starts; the five shown never take the cart further than 0.7 m from the centre. The mean return of a generation stays below the return of the mean policy, \(\theta\) itself: the perturbed policies are noisier than the policy they perturb.
The episodes are short, a few hundred microseconds, so handing them to the threads costs a good part of what the threads save: 9 threads play them only 3.2 times faster. Episodes that take longer, a physics engine or a policy with more weights, gain more.
Things to try
- Set rank_shaping to false, so that the returns are used as they are. Does it still learn?
- Halve sigma, and double it. What happens to the generations it takes?
- Use 8 pairs per generation instead of 32, and 4 times as many generations. Which learns in less time?
The code
#include <algorithm>
#include <chrono>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <fstream>
#include <string>
#include <vector>
namespace
{
std::vector<real_t> scaled(const std::vector<real_t> &obs)
{
return {obs[0] / 2.4, obs[1] / 3.0, obs[2], obs[3], obs[4] / 10.0};
}
{
}
auto actor(const std::vector<real_t> &p)
{
return [&p](const std::vector<real_t> &obs)
{ return NET.act_continuous(p, scaled(obs), 10.0); };
}
{
}
std::vector<real_t> initial_parameters()
{
auto p = NET.initial_parameters(1);
for (std::size_t j = p.size() - (16 + 1); j < p.size(); ++j)
{
p[j] *= 0.1;
}
return p;
}
{
return c;
}
double seconds_since(std::chrono::steady_clock::time_point start)
{
return std::chrono::duration<double>(std::chrono::steady_clock::now() - start).count();
}
struct Test
{
bool off_track{false};
};
Test test(
const std::vector<real_t> &p,
uint_t seed, std::ofstream *csv =
nullptr)
{
auto act = actor(p);
Test t;
if (csv)
{
*csv << "t,x,theta,force\n";
}
{
const auto force = act(
step.observation());
const bool up =
step.get_extra<
bool>(
"upright");
if (up && t.swing_up_time < 0.0)
{
t.swing_up_time = time;
}
if (up &&
env.n_steps() > MAX_STEPS / 2)
{
++up_late;
}
t.max_x = std::max(t.max_x, std::abs(
env.dynamics().state()[0]));
if (csv)
{
*csv << time <<
"," <<
env.dynamics().state()[0] <<
"," <<
env.angle() <<
","
<<
env.dynamics().limit(force[0]) <<
"\n";
}
}
t.off_track = !
step.get_extra<
bool>(
"truncated");
t.up_last_5s =
static_cast<real_t>(up_late) / (MAX_STEPS / 2);
return t;
}
}
int main(
int argc,
char **argv)
{
std::string csv_path = "swing_up.csv";
for (int i = 1; i + 1 < argc; i += 2)
{
const std::string a = argv[i];
if (a == "--generations")
{
generations = std::strtoul(argv[i + 1], nullptr, 10);
}
else if (a == "--csv")
{
csv_path = argv[i + 1];
}
}
std::printf("1. Learning to swing up, %lu generations of %lu episodes, on %lu threads\n",
generations, 2 * config().n_pairs, pool.size() + 1);
std::printf(" the policy has %lu parameters\n\n", NET.n_parameters());
std::printf(" generation mean return best return return of the mean\n");
std::uint64_t checksum_at_check = 0;
double time_at_check = 0.0;
const auto start = std::chrono::steady_clock::now();
for (
uint_t g = 0; g < generations; ++g)
{
const auto r =
es.step(fitness, pool);
if (
es.generation() == CHECK_AT)
{
checksum_at_check =
es.checksum();
time_at_check = seconds_since(start);
}
if (g % 250 == 0 || g + 1 == generations)
{
std::printf(" %10lu %11.1f %11.1f %18.1f\n", g, r.mean_fitness, r.max_fitness,
fitness(
es.parameters(), 1000000, g));
}
}
std::printf(" in %.1f s\n\n", seconds_since(start));
if (generations >= CHECK_AT)
{
std::printf("2. The first %lu generations again, on one thread\n", CHECK_AT);
ThreadPool one(1);
const auto start1 = std::chrono::steady_clock::now();
one.submit(
[&]
{
for (
uint_t g = 0; g < CHECK_AT; ++g)
{
again.step(fitness, one);
}
})
const double t1 = seconds_since(start1);
std::printf(" %.2f s against %.2f s on %lu threads, a speed-up of %.2f\n", t1,
time_at_check, pool.size() + 1, t1 / time_at_check);
std::printf(" the same parameters, to the last bit: %s\n\n",
again.checksum() == checksum_at_check ? "true" : "false");
}
std::printf("3. The learned policy, from 20 starts it never trained on\n");
std::printf(" start return up after [s] up in the last 5 s furthest from the "
"centre [m]\n");
for (
uint_t i = 0; i < 20; ++i)
{
std::ofstream csv;
if (i == 0)
{
csv.open(csv_path);
}
const auto t = test(
es.parameters(),
task_seed(2000000, i), i == 0 ? &csv :
nullptr);
mean_up += t.up_last_5s / 20.0;
n_up += t.up_last_5s > 0.99 ? 1 : 0;
if (i < 5)
{
char up_after[16];
if (t.swing_up_time < 0.0)
{
std::snprintf(up_after, sizeof(up_after), "never");
}
else
{
std::snprintf(up_after, sizeof(up_after), "%.2f", t.swing_up_time);
}
std::printf(" %5lu %6.1f %12s %16.0f %% %27.2f%s\n", i, t.ret, up_after,
100.0 * t.up_last_5s, t.max_x, t.off_track ? " off the track" : "");
}
}
std::printf(" ...\n up for the whole of the last 5 s from %lu of 20 starts; up %.0f %% of "
"that time on average\n",
n_up, 100.0 * mean_up);
std::printf(" the first start is in %s\n", csv_path.c_str());
return 0;
}
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
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
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
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
MultiAgentGridWorld make_env(GridObservation observation)
Definition multi_agent_grid_world.cpp:48
const uint_t MAX_STEPS
Definition ppo_cartpole.cpp:51
Vector step(const QuadrotorDynamicsConfig &config, const Vector &x, const Vector &u, real_t max_rotor_speed)
Definition quadrotor_lqr.cpp:114
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