1#ifndef BITRL_RL_ALGORITHMS_ES_EVOLUTION_STRATEGY_H
2#define BITRL_RL_ALGORITHMS_ES_EVOLUTION_STRATEGY_H
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);
51 return r * std::cos(a);
57 bool has_spare_{
false};
126 const std::vector<real_t> &
parameters() const noexcept {
return theta_; }
141 const std::vector<real_t> &
last_fitnesses() const noexcept {
return fitnesses_; }
148 static std::vector<real_t>
centred_ranks(
const std::vector<real_t> &values);
153 std::uint64_t
checksum() const noexcept;
157 template <typename Mine>
163 std::vector<
real_t> theta_;
166 std::vector<
real_t> fitnesses_;
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)
177 throw std::invalid_argument(
"EvolutionStrategy: no parameters");
179 if (config_.n_pairs == 0 || !(config_.sigma > 0.0))
181 throw std::invalid_argument(
"EvolutionStrategy: needs n_pairs > 0 and sigma > 0");
189 std::vector<real_t> eps(theta_.size());
197template <
typename Mine>
198void EvolutionStrategy::evaluate_(
const fitness_type &fitness, Mine mine,
202 fitnesses_.assign(2 * n, 0.0);
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)
217 candidate[j] = theta_[j] + sign * config_.
sigma * candidate[j];
219 fitnesses_[i] = fitness(candidate, generation_, k);
227 evaluate_(fitness, [](
uint_t) {
return true; }, pool);
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);
241 std::vector<real_t> own;
242 for (
uint_t k = rank; k < config_.n_pairs; k += world)
244 own.push_back(fitnesses_[2 * k]);
245 own.push_back(fitnesses_[2 * k + 1]);
248 std::string(
reinterpret_cast<const char *
>(own.data()), own.size() *
sizeof(
real_t)));
249 for (
uint_t r = 0; r < world; ++r)
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));
254 for (
uint_t k = r; k < config_.n_pairs; k += world)
256 if (i + 2 > theirs.size())
258 throw std::runtime_error(
"EvolutionStrategy: a rank sent too few fitnesses");
260 fitnesses_[2 * k] = theirs[i++];
261 fitnesses_[2 * k + 1] = theirs[i++];
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);
280 for (std::size_t first = 0; first < n;)
282 std::size_t last = first + 1;
283 while (last < n && values[order[last]] == values[order[first]])
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)
290 ranks[order[r]] = mean_rank /
static_cast<real_t>(n - 1) - 0.5;
300 const std::size_t d = theta_.size();
304 result.
max_fitness = *std::max_element(fitnesses_.begin(), fitnesses_.end());
305 result.
min_fitness = *std::min_element(fitnesses_.begin(), fitnesses_.end());
307 std::accumulate(fitnesses_.begin(), fitnesses_.end(), 0.0) /
static_cast<real_t>(2 * n);
312 std::vector<real_t> g(d, 0.0);
313 for (
uint_t k = 0; k < n; ++k)
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)
323 for (std::size_t j = 0; j < d; ++j)
325 g[j] /= 2.0 *
static_cast<real_t>(n) * config_.
sigma;
326 norm2 += g[j] * g[j];
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)
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];
348 std::uint64_t h = 1469598103934665603ULL;
349 for (
const real_t x : theta_)
351 unsigned char bytes[
sizeof(
real_t)];
352 std::memcpy(bytes, &x,
sizeof(
real_t));
353 for (
const unsigned char b : bytes)
356 h *= 1099511628211ULL;
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 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