# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Novelty-seeking and novelty-reward evolution strategies.
# @see https://proceedings.neurips.cc/paper/2018/hash/b1301141feffabac455e1f90a7de2054-Abstract.html
"""Run NS-ES, NSR-ES, or NSRA-ES with a shared descriptor history."""
from collections import deque
from dataclasses import dataclass
from math import dist, fsum, isfinite
import numpy as np
from qdpy.containers import Grid
from qdpy.phenotype import Features, Fitness, Individual
from ._population import _attempt_budget, _finite_vector
from .me_es import _rank_gradient
from .modern import _bounds, _positive_int
__all__ = ["NoveltyES", "NoveltyESPolicy", "NoveltyESStats"]
## @brief A policy center measured independently of its perturbations.
[docs]
@dataclass(frozen=True)
class NoveltyESPolicy:
"""Keep a parameter vector, its return, and its observed descriptor."""
genome: tuple[float, ...]
reward: float
descriptor: tuple[float, ...]
## @brief Track search costs and the adaptive reward weight.
[docs]
@dataclass(frozen=True)
class NoveltyESStats:
"""Count attempted rollouts and committed center updates."""
center_evaluations: int
perturbation_evaluations: int
failures: int
updates: int
reward_weight: float
selection_counts: tuple[int, ...]
@property
def evaluations(self):
"""Return total evaluator calls."""
return self.center_evaluations + self.perturbation_evaluations
## @brief Select one policy by novelty and update it using ranked Gaussian perturbations.
[docs]
class NoveltyES:
"""Use Conti et al.'s shared novelty memory and three search objectives.
Each step selects one member with probability proportional to its
novelty. Separately rank the probe rewards and novelty scores, then
combine their gradient estimates. NS-ES uses only novelty. NSR-ES
averages both signals. NSRA-ES starts with reward and lowers its
weight as best measured center reward stagnates.
:param initial_population: Nonempty matrix of finite parameter vectors.
:param mode: ``ns-es``, ``nsr-es``, or ``nsra-es``.
:param archive: Optional parentless best-only reporting Grid or CVTGrid.
It uses reward maximization and does not affect selection.
:param pairs: Number of antithetic Gaussian perturbation pairs per step.
:param sigma: Gaussian standard deviation.
:param learning_rate: Step size of the per-member Adam update.
:param l2: Nonnegative weight decay in the parameter gradient.
:param neighbors: Number of nearest measured center descriptors.
:param distance: Symmetric nonnegative descriptor distance, default Euclidean.
:param history_capacity: Optional maximum number of recent center descriptors.
:param patience: Stagnant steps before reducing NSRA-ES reward weight.
:param weight_step: Amount to change that weight on a plateau or new best.
:param ind_domain: Optional common parameter interval for clipped ES.
:param seed: Private seed for selection, perturbations, and evaluations.
"""
def __init__(self, initial_population, *, mode="nsra-es", archive=None, pairs=16, sigma=.05,
learning_rate=.02, l2=.005, neighbors=10, distance=dist, history_capacity=None,
patience=10, weight_step=.05, ind_domain=None, seed=0):
points = np.asarray(initial_population, dtype=float)
if points.ndim != 2 or not all(points.shape) or not np.isfinite(points).all():
raise ValueError("Supply a nonempty matrix of finite parameter vectors.")
weights = {"ns-es": 0., "nsr-es": .5, "nsra-es": 1.}
if mode not in weights:
raise ValueError("Choose ns-es, nsr-es, or nsra-es.")
if not callable(distance) or not (0 < sigma < np.inf and 0 < learning_rate < np.inf
and 0 <= l2 < np.inf and 0 < weight_step <= 1):
raise ValueError("Use a distance callable and finite scales.")
if archive is not None and (
not isinstance(archive, Grid) or archive.parents or archive.max_items_per_bin != 1
or archive.discard_random_on_bin_overload or len(archive.fitness_domain or ()) != 1
or len(archive.fitness_weights or ()) != 1 or not 0 < archive.fitness_weights[0] < np.inf
or archive.features_score_names or archive.fitness_score_names):
raise ValueError("Use a parentless best-only grid with a positive scalar fitness weight and native scores.")
self.archive, self.mode = archive, mode
self._bounds = None if ind_domain is None else _bounds(ind_domain)
if not np.array_equal(self._bounded(points), points):
raise ValueError("Initial genomes lie outside ind_domain.")
self._initial = tuple(map(tuple, points))
self._pairs = _positive_int(pairs, "pairs")
self._neighbors, self._patience = _positive_int(neighbors, "neighbors"), _positive_int(patience, "patience")
self._sigma, self._rate, self._l2, self._distance = sigma, learning_rate, l2, distance
self._weight, self._weight_step = weights[mode], weight_step
capacity = None if history_capacity is None else _positive_int(history_capacity, "history_capacity")
self._history = deque(maxlen=capacity)
self._population = [None] * len(points)
self._means, self._variances = np.zeros_like(points), np.zeros_like(points)
self._steps = np.zeros(len(points), dtype=int)
self._selections = self._steps.copy()
self._selection, self._variation, self._evaluation = map(
np.random.default_rng, np.random.SeedSequence(seed).spawn(3))
self._cursor = self._centers = self._probes = self._failures = self._stale = 0
self._best = None
self._descriptor_size = len(archive.features_domain) if archive is not None else None
@property
def population(self):
"""Return measured centers in population order."""
return tuple(row for row in self._population if row is not None)
@property
def best(self):
"""Return the historically best measured center, or None before a successful call."""
return self._best
@property
def history(self):
"""Return shared descriptors from committed center measurements."""
return tuple(self._history)
@property
def stats(self):
"""Return a snapshot of cumulative costs and current reward weight."""
return NoveltyESStats(self._centers, self._probes, self._failures, int(self._steps.sum()),
self._weight, tuple(map(int, self._selections)))
@property
def step_cost(self):
"""Return evaluator calls reserved for a probe batch and its center."""
return 2 * self._pairs + 1
def _bounded(self, points):
return points if self._bounds is None else np.clip(points, *self._bounds)
def _observe(self, result, genome):
if result is None:
self._failures += 1
return None
reward, descriptor = result
if not isfinite(reward):
raise ValueError("A policy must return a finite reward.")
values = _finite_vector(descriptor, "Behavior descriptor", self._descriptor_size)
self._descriptor_size = len(values)
return NoveltyESPolicy(genome, float(reward), values)
def _measure(self, evaluate, points, executor, *, center=False):
results = []
for point in points:
genome = _finite_vector(point, "Policy parameters")
seed = int(self._evaluation.integers(2**32))
if center:
self._centers += 1
else:
self._probes += 1
result = evaluate(genome, seed) if executor is None else executor.submit(evaluate, genome, seed)
results.append((genome, result))
return [self._observe(result if executor is None else result.result(), genome) for genome, result in results]
def _record(self, slot, row, *, adapt):
if row is not None:
self._population[slot] = row
self._history.append(row.descriptor)
if self.archive is not None:
archive = self.archive
if archive.in_bounds((row.reward,), archive.fitness_domain) and archive.in_bounds(
row.descriptor, archive.features_domain):
archive.add(Individual(row.genome, fitness=Fitness((row.reward,), weights=archive.fitness_weights),
features=Features(row.descriptor)))
improved = row is not None and (self._best is None or row.reward > self._best.reward)
if improved:
self._best = row
if adapt and self.mode == "nsra-es":
self._stale = 0 if improved else self._stale + 1
if improved:
self._weight = min(1., self._weight + self._weight_step)
elif self._stale >= self._patience:
self._weight = max(0., self._weight - self._weight_step)
self._stale = 0
def _novelty(self, descriptor):
gaps = [self._distance(descriptor, old) for old in self._history]
if any(not isfinite(value) or value < 0. for value in gaps):
raise ValueError("Descriptor distances must be finite and nonnegative.")
nearest = sorted(gaps)[:self._neighbors]
return fsum(value / len(nearest) for value in nearest)
def _step(self, evaluate, executor):
available = [i for i, row in enumerate(self._population) if row is not None]
novelty = np.asarray([self._novelty(self._population[i].descriptor) for i in available])
scaled = novelty / (novelty.max() or 1.)
probability = scaled / scaled.sum() if scaled.any() else None
slot = int(self._selection.choice(available, p=probability))
self._selections[slot] += 1
center = np.asarray(self._population[slot].genome)
noise = self._variation.standard_normal((self._pairs, len(center)))
probes = self._bounded(center + self._sigma * np.concatenate((noise, -noise)))
rows = self._measure(evaluate, probes, executor)
if any(row is None for row in rows):
self._record(slot, None, adapt=True)
return
gradient = -self._l2 * center
if self._weight:
gradient += self._weight * _rank_gradient(noise, [row.reward for row in rows], self._sigma)
if self._weight < 1.:
values = [self._novelty(row.descriptor) for row in rows]
gradient += (1. - self._weight) * _rank_gradient(noise, values, self._sigma)
mean = .9 * self._means[slot] + .1 * gradient
variance = .999 * self._variances[slot] + .001 * np.square(gradient)
step = int(self._steps[slot]) + 1
proposal = center + self._rate * (mean / (1. - .9 ** step)) / (np.sqrt(variance / (1. - .999 ** step)) + 1e-8)
if not np.isfinite(proposal).all() or not np.isfinite(variance).all():
raise ValueError("The ES step overflowed. Rescale parameters or ES settings.")
row, = self._measure(evaluate, (self._bounded(proposal),), executor, center=True)
if row is not None:
self._means[slot], self._variances[slot], self._steps[slot] = mean, variance, step
self._record(slot, row, adapt=True)
## @brief Run the shared initialization and subsequent rank-based ES steps.
# @param evaluate Callable (genome, seed) returning (reward, descriptor), or None on failure.
# @param budget Maximum number of additional evaluator calls.
# @param executor Optional executor with submit(); feedback is consumed in proposal order.
# @return Cumulative NoveltyESStats.
[docs]
def run(self, evaluate, budget, *, executor=None):
"""Retry initialization if all centers fail and reserve full ES steps."""
remaining = _attempt_budget(budget)
while remaining and self._cursor < len(self._initial):
row, = self._measure(evaluate, (self._initial[self._cursor],), executor, center=True)
self._record(self._cursor, row, adapt=False)
self._cursor += 1
remaining -= 1
if self._cursor == len(self._initial) and self._best is None:
self._cursor = 0
while remaining >= self.step_cost and self._best is not None:
before = self._centers + self._probes
self._step(evaluate, executor)
remaining -= self._centers + self._probes - before
return self.stats