QDpy
Loading...
Searching...
No Matches
novelty_es.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Run NS-ES, NSR-ES, or NSRA-ES with a shared descriptor history."""
7
8from collections import deque
9from dataclasses import dataclass
10from math import dist, fsum, isfinite
11
12import numpy as np
13
14from qdpy.containers import Grid
15from qdpy.phenotype import Features, Fitness, Individual
16from ._population import _attempt_budget, _finite_vector
17from .me_es import _rank_gradient
18from .modern import _bounds, _positive_int
19
20__all__ = ["NoveltyES", "NoveltyESPolicy", "NoveltyESStats"]
21
22
23
24@dataclass(frozen=True)
26 """Keep a parameter vector, its return, and its observed descriptor."""
27
28 genome: tuple[float, ...]
29 reward: float
30 descriptor: tuple[float, ...]
31
32
33
34@dataclass(frozen=True)
36 """Count attempted rollouts and committed center updates."""
37
38 center_evaluations: int
39 perturbation_evaluations: int
40 failures: int
41 updates: int
42 reward_weight: float
43 selection_counts: tuple[int, ...]
44
45 @property
46 def evaluations(self):
47 """Return total evaluator calls."""
48 return self.center_evaluations + self.perturbation_evaluations
49
50
51
53 """Use Conti et al.'s shared novelty memory and three search objectives.
54
55 Each step selects one member with probability proportional to its
56 novelty. Separately rank the probe rewards and novelty scores, then
57 combine their gradient estimates. NS-ES uses only novelty. NSR-ES
58 averages both signals. NSRA-ES starts with reward and lowers its
59 weight as best measured center reward stagnates.
60
61 :param initial_population: Nonempty matrix of finite parameter vectors.
62 :param mode: ``ns-es``, ``nsr-es``, or ``nsra-es``.
63 :param archive: Optional parentless best-only reporting Grid or CVTGrid.
64 It uses reward maximization and does not affect selection.
65 :param pairs: Number of antithetic Gaussian perturbation pairs per step.
66 :param sigma: Gaussian standard deviation.
67 :param learning_rate: Step size of the per-member Adam update.
68 :param l2: Nonnegative weight decay in the parameter gradient.
69 :param neighbors: Number of nearest measured center descriptors.
70 :param distance: Symmetric nonnegative descriptor distance, default Euclidean.
71 :param history_capacity: Optional maximum number of recent center descriptors.
72 :param patience: Stagnant steps before reducing NSRA-ES reward weight.
73 :param weight_step: Amount to change that weight on a plateau or new best.
74 :param ind_domain: Optional common parameter interval for clipped ES.
75 :param seed: Private seed for selection, perturbations, and evaluations.
76 """
77
78 def __init__(self, initial_population, *, mode="nsra-es", archive=None, pairs=16, sigma=.05,
79 learning_rate=.02, l2=.005, neighbors=10, distance=dist, history_capacity=None,
80 patience=10, weight_step=.05, ind_domain=None, seed=0):
81 points = np.asarray(initial_population, dtype=float)
82 if points.ndim != 2 or not all(points.shape) or not np.isfinite(points).all():
83 raise ValueError("Supply a nonempty matrix of finite parameter vectors.")
84 weights = {"ns-es": 0., "nsr-es": .5, "nsra-es": 1.}
85 if mode not in weights:
86 raise ValueError("Choose ns-es, nsr-es, or nsra-es.")
87 if not callable(distance) or not (0 < sigma < np.inf and 0 < learning_rate < np.inf
88 and 0 <= l2 < np.inf and 0 < weight_step <= 1):
89 raise ValueError("Use a distance callable and finite scales.")
90 if archive is not None and (
91 not isinstance(archive, Grid) or archive.parents or archive.max_items_per_bin != 1
92 or archive.discard_random_on_bin_overload or len(archive.fitness_domain or ()) != 1
93 or len(archive.fitness_weights or ()) != 1 or not 0 < archive.fitness_weights[0] < np.inf
94 or archive.features_score_names or archive.fitness_score_names):
95 raise ValueError("Use a parentless best-only grid with a positive scalar fitness weight and native scores.")
96 self.archive, self.mode = archive, mode
97 self._bounds = None if ind_domain is None else _bounds(ind_domain)
98 if not np.array_equal(self._bounded(points), points):
99 raise ValueError("Initial genomes lie outside ind_domain.")
100 self._initial = tuple(map(tuple, points))
101 self._pairs = _positive_int(pairs, "pairs")
102 self._neighbors, self._patience = _positive_int(neighbors, "neighbors"), _positive_int(patience, "patience")
103 self._sigma, self._rate, self._l2, self._distance = sigma, learning_rate, l2, distance
104 self._weight, self._weight_step = weights[mode], weight_step
105 capacity = None if history_capacity is None else _positive_int(history_capacity, "history_capacity")
106 self._history = deque(maxlen=capacity)
107 self._population = [None] * len(points)
108 self._means, self._variances = np.zeros_like(points), np.zeros_like(points)
109 self._steps = np.zeros(len(points), dtype=int)
110 self._selections = self._steps.copy()
111 self._selection, self._variation, self._evaluation = map(
112 np.random.default_rng, np.random.SeedSequence(seed).spawn(3))
113 self._cursor = self._centers = self._probes = self._failures = self._stale = 0
114 self._best = None
115 self._descriptor_size = len(archive.features_domain) if archive is not None else None
116
117 @property
118 def population(self):
119 """Return measured centers in population order."""
120 return tuple(row for row in self._population if row is not None)
121
122 @property
123 def best(self):
124 """Return the historically best measured center, or None before a successful call."""
125 return self._best
126
127 @property
128 def history(self):
129 """Return shared descriptors from committed center measurements."""
130 return tuple(self._history)
131
132 @property
133 def stats(self):
134 """Return a snapshot of cumulative costs and current reward weight."""
135 return NoveltyESStats(self._centers, self._probes, self._failures, int(self._steps.sum()),
136 self._weight, tuple(map(int, self._selections)))
137
138 @property
139 def step_cost(self):
140 """Return evaluator calls reserved for a probe batch and its center."""
141 return 2 * self._pairs + 1
142
143 def _bounded(self, points):
144 return points if self._bounds is None else np.clip(points, *self._bounds)
145
146 def _observe(self, result, genome):
147 if result is None:
148 self._failures += 1
149 return None
150 reward, descriptor = result
151 if not isfinite(reward):
152 raise ValueError("A policy must return a finite reward.")
153 values = _finite_vector(descriptor, "Behavior descriptor", self._descriptor_size)
154 self._descriptor_size = len(values)
155 return NoveltyESPolicy(genome, float(reward), values)
156
157 def _measure(self, evaluate, points, executor, *, center=False):
158 results = []
159 for point in points:
160 genome = _finite_vector(point, "Policy parameters")
161 seed = int(self._evaluation.integers(2**32))
162 if center:
163 self._centers += 1
164 else:
165 self._probes += 1
166 result = evaluate(genome, seed) if executor is None else executor.submit(evaluate, genome, seed)
167 results.append((genome, result))
168 return [self._observe(result if executor is None else result.result(), genome) for genome, result in results]
169
170 def _record(self, slot, row, *, adapt):
171 if row is not None:
172 self._population[slot] = row
173 self._history.append(row.descriptor)
174 if self.archive is not None:
175 archive = self.archive
176 if archive.in_bounds((row.reward,), archive.fitness_domain) and archive.in_bounds(
177 row.descriptor, archive.features_domain):
178 archive.add(Individual(row.genome, fitness=Fitness((row.reward,), weights=archive.fitness_weights),
179 features=Features(row.descriptor)))
180 improved = row is not None and (self._best is None or row.reward > self._best.reward)
181 if improved:
182 self._best = row
183 if adapt and self.mode == "nsra-es":
184 self._stale = 0 if improved else self._stale + 1
185 if improved:
186 self._weight = min(1., self._weight + self._weight_step)
187 elif self._stale >= self._patience:
188 self._weight = max(0., self._weight - self._weight_step)
189 self._stale = 0
190
191 def _novelty(self, descriptor):
192 gaps = [self._distance(descriptor, old) for old in self._history]
193 if any(not isfinite(value) or value < 0. for value in gaps):
194 raise ValueError("Descriptor distances must be finite and nonnegative.")
195 nearest = sorted(gaps)[:self._neighbors]
196 return fsum(value / len(nearest) for value in nearest)
197
198 def _step(self, evaluate, executor):
199 available = [i for i, row in enumerate(self._population) if row is not None]
200 novelty = np.asarray([self._novelty(self._population[i].descriptor) for i in available])
201 scaled = novelty / (novelty.max() or 1.)
202 probability = scaled / scaled.sum() if scaled.any() else None
203 slot = int(self._selection.choice(available, p=probability))
204 self._selections[slot] += 1
205 center = np.asarray(self._population[slot].genome)
206 noise = self._variation.standard_normal((self._pairs, len(center)))
207 probes = self._bounded(center + self._sigma * np.concatenate((noise, -noise)))
208 rows = self._measure(evaluate, probes, executor)
209 if any(row is None for row in rows):
210 self._record(slot, None, adapt=True)
211 return
212 gradient = -self._l2 * center
213 if self._weight:
214 gradient += self._weight * _rank_gradient(noise, [row.reward for row in rows], self._sigma)
215 if self._weight < 1.:
216 values = [self._novelty(row.descriptor) for row in rows]
217 gradient += (1. - self._weight) * _rank_gradient(noise, values, self._sigma)
218 mean = .9 * self._means[slot] + .1 * gradient
219 variance = .999 * self._variances[slot] + .001 * np.square(gradient)
220 step = int(self._steps[slot]) + 1
221 proposal = center + self._rate * (mean / (1. - .9 ** step)) / (np.sqrt(variance / (1. - .999 ** step)) + 1e-8)
222 if not np.isfinite(proposal).all() or not np.isfinite(variance).all():
223 raise ValueError("The ES step overflowed. Rescale parameters or ES settings.")
224 row, = self._measure(evaluate, (self._bounded(proposal),), executor, center=True)
225 if row is not None:
226 self._means[slot], self._variances[slot], self._steps[slot] = mean, variance, step
227 self._record(slot, row, adapt=True)
228
229
234 def run(self, evaluate, budget, *, executor=None):
235 """Retry initialization if all centers fail and reserve full ES steps."""
236 remaining = _attempt_budget(budget)
237 while remaining and self._cursor < len(self._initial):
238 row, = self._measure(evaluate, (self._initial[self._cursor],), executor, center=True)
239 self._record(self._cursor, row, adapt=False)
240 self._cursor += 1
241 remaining -= 1
242 if self._cursor == len(self._initial) and self._best is None:
243 self._cursor = 0
244 while remaining >= self.step_cost and self._best is not None:
245 before = self._centers + self._probes
246 self._step(evaluate, executor)
247 remaining -= self._centers + self._probes - before
248 return self.stats
A policy center measured independently of its perturbations.
Definition novelty_es.py:25
Track search costs and the adaptive reward weight.
Definition novelty_es.py:35
Select one policy by novelty and update it using ranked Gaussian perturbations.
Definition novelty_es.py:52
_record(self, slot, row, *, adapt)
_measure(self, evaluate, points, executor, *, center=False)
run(self, evaluate, budget, *, executor=None)
Run the shared initialization and subsequent rank-based ES steps.
_step(self, evaluate, executor)
:param obj: Slice indicating on which objectives the domination is tested.
Definition phenotype.py:405