bitsim
Model, simulate, estimate and control robots in C++
Loading...
Searching...
No Matches
evolution_strategy.h
Go to the documentation of this file.
1#ifndef BITRL_RL_ALGORITHMS_ES_EVOLUTION_STRATEGY_H
2#define BITRL_RL_ALGORITHMS_ES_EVOLUTION_STRATEGY_H
3
8
9#include <algorithm>
10#include <cmath>
11#include <cstdint>
12#include <cstring>
13#include <functional>
14#include <numeric>
15#include <random>
16#include <stdexcept>
17#include <string>
18#include <vector>
19
20namespace bitrl
21{
22namespace rl::algos::es
23{
24
33{
34 public:
35 explicit PortableNormal(std::uint64_t seed) : rng_(seed) {}
36
38 {
39 if (has_spare_)
40 {
41 has_spare_ = false;
42 return spare_;
43 }
44 // u1 in (0, 1], u2 in [0, 1), from the top 53 bits
45 const real_t u1 = (static_cast<real_t>(rng_() >> 11) + 1.0) * 0x1.0p-53;
46 const real_t u2 = static_cast<real_t>(rng_() >> 11) * 0x1.0p-53;
47 const real_t r = std::sqrt(-2.0 * std::log(u1));
48 const real_t a = 2.0 * M_PI * u2;
49 spare_ = r * std::sin(a);
50 has_spare_ = true;
51 return r * std::cos(a);
52 }
53
54 private:
55 std::mt19937_64 rng_;
56 real_t spare_{0.0};
57 bool has_spare_{false};
58};
59
71
100{
101 public:
102 typedef std::function<real_t(const std::vector<real_t> &, uint_t, uint_t)> fitness_type;
103
104 EvolutionStrategy(const ESConfig &config, std::vector<real_t> initial_parameters);
105
109 GenerationResult step(const fitness_type &fitness,
112
122
126 const std::vector<real_t> &parameters() const noexcept { return theta_; }
127
131 std::vector<real_t> noise(uint_t generation, uint_t pair) const;
132
136 uint_t generation() const noexcept { return generation_; }
137
141 const std::vector<real_t> &last_fitnesses() const noexcept { return fitnesses_; }
142
143 const ESConfig &config() const noexcept { return config_; }
144
148 static std::vector<real_t> centred_ranks(const std::vector<real_t> &values);
149
153 std::uint64_t checksum() const noexcept;
154
155 private:
156 // evaluate the pairs for which mine(k) is true; the others stay 0
157 template <typename Mine>
158 void evaluate_(const fitness_type &fitness, Mine mine,
159 bitsim::utils::concurrency::ThreadPool &pool);
160 GenerationResult update_();
161
162 ESConfig config_;
163 std::vector<real_t> theta_;
164 std::vector<real_t> m_;
165 std::vector<real_t> v_;
166 std::vector<real_t> fitnesses_;
167 uint_t generation_{0};
168};
169
171 std::vector<real_t> initial_parameters)
172 : config_(config), theta_(std::move(initial_parameters)), m_(theta_.size(), 0.0),
173 v_(theta_.size(), 0.0)
174{
175 if (theta_.empty())
176 {
177 throw std::invalid_argument("EvolutionStrategy: no parameters");
178 }
179 if (config_.n_pairs == 0 || !(config_.sigma > 0.0))
180 {
181 throw std::invalid_argument("EvolutionStrategy: needs n_pairs > 0 and sigma > 0");
182 }
183}
184
185inline std::vector<real_t> EvolutionStrategy::noise(uint_t generation, uint_t pair) const
186{
188 PortableNormal normal(task_seed(task_seed(config_.seed, generation), pair));
189 std::vector<real_t> eps(theta_.size());
190 for (auto &e : eps)
191 {
192 e = normal();
193 }
194 return eps;
195}
196
197template <typename Mine>
198void EvolutionStrategy::evaluate_(const fitness_type &fitness, Mine mine,
200{
201 const uint_t n = config_.n_pairs;
202 fitnesses_.assign(2 * n, 0.0);
203 // one task per evaluation, so that the two of a pair can run at the same time
205 0, 2 * n,
206 [&](uint_t i)
207 {
208 const uint_t k = i / 2;
209 if (!mine(k))
210 {
211 return;
212 }
213 const real_t sign = (i % 2 == 0) ? 1.0 : -1.0;
214 auto candidate = noise(generation_, k);
215 for (std::size_t j = 0; j < candidate.size(); ++j)
216 {
217 candidate[j] = theta_[j] + sign * config_.sigma * candidate[j];
218 }
219 fitnesses_[i] = fitness(candidate, generation_, k);
220 },
221 pool);
222}
223
226{
227 evaluate_(fitness, [](uint_t) { return true; }, pool);
228 return update_();
229}
230
232 rl::distributed::Communicator &communicator,
234{
235 const uint_t rank = communicator.rank();
236 const uint_t world = communicator.world_size();
237 auto mine = [world](uint_t k, uint_t r) { return k % world == r; };
238 evaluate_(fitness, [&](uint_t k) { return mine(k, rank); }, pool);
239
240 // send only this rank's fitnesses, in the order of the pairs, and put every rank's back
241 std::vector<real_t> own;
242 for (uint_t k = rank; k < config_.n_pairs; k += world)
243 {
244 own.push_back(fitnesses_[2 * k]);
245 own.push_back(fitnesses_[2 * k + 1]);
246 }
247 const auto all = communicator.all_gather(
248 std::string(reinterpret_cast<const char *>(own.data()), own.size() * sizeof(real_t)));
249 for (uint_t r = 0; r < world; ++r)
250 {
251 std::vector<real_t> theirs(all[r].size() / sizeof(real_t));
252 std::memcpy(theirs.data(), all[r].data(), theirs.size() * sizeof(real_t));
253 std::size_t i = 0;
254 for (uint_t k = r; k < config_.n_pairs; k += world)
255 {
256 if (i + 2 > theirs.size())
257 {
258 throw std::runtime_error("EvolutionStrategy: a rank sent too few fitnesses");
259 }
260 fitnesses_[2 * k] = theirs[i++];
261 fitnesses_[2 * k + 1] = theirs[i++];
262 }
263 }
264 return update_();
265}
266
267inline std::vector<real_t> EvolutionStrategy::centred_ranks(const std::vector<real_t> &values)
268{
269 const std::size_t n = values.size();
270 std::vector<std::size_t> order(n);
271 std::iota(order.begin(), order.end(), std::size_t(0));
272 std::stable_sort(order.begin(), order.end(),
273 [&values](std::size_t a, std::size_t b) { return values[a] < values[b]; });
274 std::vector<real_t> ranks(n, 0.0);
275 if (n < 2)
276 {
277 return ranks;
278 }
279 // equal values share the mean of their ranks, so that ties make no gradient
280 for (std::size_t first = 0; first < n;)
281 {
282 std::size_t last = first + 1;
283 while (last < n && values[order[last]] == values[order[first]])
284 {
285 ++last;
286 }
287 const real_t mean_rank = 0.5 * static_cast<real_t>(first + last - 1);
288 for (std::size_t r = first; r < last; ++r)
289 {
290 ranks[order[r]] = mean_rank / static_cast<real_t>(n - 1) - 0.5;
291 }
292 first = last;
293 }
294 return ranks;
295}
296
297inline GenerationResult EvolutionStrategy::update_()
298{
299 const uint_t n = config_.n_pairs;
300 const std::size_t d = theta_.size();
301
302 GenerationResult result;
303 result.generation = generation_;
304 result.max_fitness = *std::max_element(fitnesses_.begin(), fitnesses_.end());
305 result.min_fitness = *std::min_element(fitnesses_.begin(), fitnesses_.end());
306 result.mean_fitness =
307 std::accumulate(fitnesses_.begin(), fitnesses_.end(), 0.0) / static_cast<real_t>(2 * n);
308
309 const auto shaped = config_.rank_shaping ? centred_ranks(fitnesses_) : fitnesses_;
310
311 // the gradient, the pairs added in the order of k
312 std::vector<real_t> g(d, 0.0);
313 for (uint_t k = 0; k < n; ++k)
314 {
315 const real_t w = shaped[2 * k] - shaped[2 * k + 1];
316 const auto eps = noise(generation_, k);
317 for (std::size_t j = 0; j < d; ++j)
318 {
319 g[j] += w * eps[j];
320 }
321 }
322 real_t norm2 = 0.0;
323 for (std::size_t j = 0; j < d; ++j)
324 {
325 g[j] /= 2.0 * static_cast<real_t>(n) * config_.sigma;
326 norm2 += g[j] * g[j];
327 g[j] -= config_.weight_decay * theta_[j];
328 }
329 result.gradient_norm = std::sqrt(norm2);
330
331 // Adam, up the gradient
332 const real_t t = static_cast<real_t>(generation_ + 1);
333 const real_t c1 = 1.0 - std::pow(config_.beta1, t);
334 const real_t c2 = 1.0 - std::pow(config_.beta2, t);
335 for (std::size_t j = 0; j < d; ++j)
336 {
337 m_[j] = config_.beta1 * m_[j] + (1.0 - config_.beta1) * g[j];
338 v_[j] = config_.beta2 * v_[j] + (1.0 - config_.beta2) * g[j] * g[j];
339 theta_[j] += config_.learning_rate * (m_[j] / c1) /
340 (std::sqrt(v_[j] / c2) + config_.adam_epsilon);
341 }
342 ++generation_;
343 return result;
344}
345
346inline std::uint64_t EvolutionStrategy::checksum() const noexcept
347{
348 std::uint64_t h = 1469598103934665603ULL; // FNV-1a
349 for (const real_t x : theta_)
350 {
351 unsigned char bytes[sizeof(real_t)];
352 std::memcpy(bytes, &x, sizeof(real_t));
353 for (const unsigned char b : bytes)
354 {
355 h ^= b;
356 h *= 1099511628211ULL;
357 }
358 }
359 return h;
360}
361
362} // namespace rl::algos::es
363} // namespace bitrl
364
365#endif // BITRL_RL_ALGORITHMS_ES_EVOLUTION_STRATEGY_H
const std::vector< real_t > & parameters() const noexcept
The parameters: the mean of the search distribution.
Definition evolution_strategy.h:126
std::function< real_t(const std::vector< real_t > &, uint_t, uint_t)> fitness_type
Definition evolution_strategy.h:102
static std::vector< real_t > centred_ranks(const std::vector< real_t > &values)
The centred ranks of values, in [-0.5, 0.5]; equal values share their mean rank.
Definition evolution_strategy.h:267
std::vector< real_t > noise(uint_t generation, uint_t pair) const
The noise of pair k in generation generation.
Definition evolution_strategy.h:185
EvolutionStrategy(const ESConfig &config, std::vector< real_t > initial_parameters)
Definition evolution_strategy.h:170
const ESConfig & config() const noexcept
Definition evolution_strategy.h:143
const std::vector< real_t > & last_fitnesses() const noexcept
The fitnesses of the last generation: entry 2k is pair k plus, 2k + 1 pair k minus.
Definition evolution_strategy.h:141
std::uint64_t checksum() const noexcept
A checksum of the parameters, to tell that two runs, or two ranks, agree.
Definition evolution_strategy.h:346
uint_t generation() const noexcept
The generations taken so far.
Definition evolution_strategy.h:136
GenerationResult step(const fitness_type &fitness, bitsim::utils::concurrency::ThreadPool &pool=bitsim::utils::concurrency::default_thread_pool())
One generation, evaluated on the threads of pool.
Definition evolution_strategy.h:224
Normal random numbers that are the same on every machine.
Definition evolution_strategy.h:33
PortableNormal(std::uint64_t seed)
Definition evolution_strategy.h:35
real_t operator()()
Definition evolution_strategy.h:37
How the ranks of a distributed training exchange numbers.
Definition communicator.h:32
virtual uint_t rank() const noexcept=0
virtual uint_t world_size() const noexcept=0
virtual std::vector< std::string > all_gather(const std::string &mine)=0
What every rank gave, in the order of the ranks.
A fixed number of threads that run the tasks given to them, in the order given.
Definition thread_pool.h:33
Definition es_config.h:9
Definition bitrl_concepts.h:22
Various utilities used when working with RL problems.
Definition bitrl_log.h:25
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
void parallel_for(Index begin, Index end, F &&f, ThreadPool &pool=default_thread_pool(), Index grain=1)
Call f(i) for every i in [begin, end), spread over the threads of pool.
Definition parallel.h:38
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
Definition dc_motor_backend_base.h:9
std::size_t uint_t
uint_t
Definition bitsim_types.h:40
double real_t
real_t
Definition bitsim_types.h:20
The settings of EvolutionStrategy.
Definition es_config.h:15
real_t sigma
the standard deviation of the perturbations
Definition es_config.h:17
real_t weight_decay
pulls the parameters towards 0, as an L2 penalty
Definition es_config.h:19
uint_t n_pairs
antithetic pairs per generation: 2 * n_pairs evaluations
Definition es_config.h:16
real_t beta2
Adam.
Definition es_config.h:21
real_t beta1
Adam.
Definition es_config.h:20
real_t learning_rate
Adam's step size.
Definition es_config.h:18
bool rank_shaping
use centred ranks of the fitnesses, not the fitnesses
Definition es_config.h:23
real_t adam_epsilon
Adam.
Definition es_config.h:22
What one generation of EvolutionStrategy gave.
Definition evolution_strategy.h:64
real_t min_fitness
Definition evolution_strategy.h:68
real_t mean_fitness
over the 2 * n_pairs perturbed parameters
Definition evolution_strategy.h:66
real_t gradient_norm
of the estimated gradient, before Adam
Definition evolution_strategy.h:69
real_t max_fitness
Definition evolution_strategy.h:67
uint_t generation
Definition evolution_strategy.h:65