QDpy
Loading...
Searching...
No Matches
serene.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""SERENE with bounded novelty memory and a separate reward repertoire."""
7
8from collections import deque
9from dataclasses import dataclass
10
11import numpy as np
12from scipy.spatial.distance import cdist
13
14from qdpy.containers import CVTGrid, Grid
15from qdpy.phenotype import Features, Fitness, _CellIndividual
16from .modern import _bounds, _positive_int
17
18__all__ = ["SERENE", "SereneElite", "SereneStats"]
19
20
21
22@dataclass(frozen=True)
24 """Record the bounded genome, scalar reward, and measured descriptor."""
25
26 genome: tuple[float, ...]
27 reward: float
28 descriptor: tuple[float, ...]
29
30
31
32@dataclass(frozen=True)
34 """Count failed evaluations in their original phase and in the failure total."""
35
36 exploration_evaluations: int
37 bootstrap_evaluations: int
38 emitter_evaluations: int
39 failed_evaluations: int
40 first_reward_evaluation: int | None
41 reward_updates: int
42 emitters_started: int
43
44 @property
45 def evaluations(self):
46 """Return the number of attempted evaluations across all phases."""
47 return self.exploration_evaluations + self.bootstrap_evaluations + self.emitter_evaluations
48
49
50@dataclass
52 population: list
53 novelty: float
54 improvement: float = 0.
55 stalls: int = 0
56 probes: int = 0
57
58
59
60class SERENE:
61 """Run novelty search with a queue of distinct rewarding discoveries.
62
63 Exploratory offspring compete with the existing population on Euclidean
64 k-nearest-neighbour novelty. A discovery above reward_threshold seeds
65 a Gaussian emitter in its first rewarding cell. During exploitation,
66 bootstrap the most novel queued discovery, then select qualified
67 emitters on the novelty and improvement Pareto front. Only positive
68 bootstrap improvement qualifies an emitter. Novel emitter offspring
69 also enter the exploration memory. The reward grid stores measured
70 rewards independently of novelty selection.
71
72 :param archive: Empty, parentless, best-only Grid or CVTGrid with one maximized reward.
73 :param dimension: Genome length.
74 :param ind_domain: Shared inclusive bounds on genome coordinates.
75 :param reward_threshold: Reward must exceed this value to be stored or seed an emitter.
76 :param population_size: Maximum exploration population.
77 :param novelty_capacity: Maximum retained novelty records.
78 :param novelty_neighbors: Neighbours used for descriptor novelty.
79 :param chunk_size: Calls allotted to each consecutive phase when both can run.
80 :param exploration_sigma: Exploration mutation scale as a fraction of the genome interval.
81 :param emitter_sigma: Local mutation scale as a fraction of the genome interval.
82 :param emitter_size: Maximum reward-selected parents per emitter.
83 :param bootstrap_calls: Calls during a local probe, before testing for improvement.
84 :param stagnation_calls: Consecutive calls without a new best reward before retiring an emitter.
85 :param seed: Private seed for proposals, phase choices, and evaluations.
86 """
87
88 def __init__(self, archive, dimension, *, ind_domain=(0., 1.), reward_threshold=0.,
89 population_size=24, novelty_capacity=256, novelty_neighbors=10, chunk_size=32,
90 exploration_sigma=.15, emitter_sigma=.03, emitter_size=4, bootstrap_calls=8,
91 stagnation_calls=30, seed=0):
92 if (type(archive) not in (Grid, CVTGrid) or len(archive) or archive.parents
93 or archive.max_items_per_bin != 1 or archive.discard_random_on_bin_overload
94 or archive.features_score_names or archive.fitness_score_names
95 or len(archive.fitness_domain or ()) != 1 or len(archive.fitness_weights or ()) != 1
96 or not 0 < archive.fitness_weights[0] < np.inf):
97 raise ValueError("Use an empty, parentless best-only grid with one maximized reward.")
98 if not (np.isfinite(reward_threshold) and 0 < emitter_sigma < np.inf
99 and 0 < exploration_sigma < np.inf):
100 raise ValueError("Use a finite reward threshold and positive finite mutation scales.")
101 self.archive = archive
102 self.dimension = _positive_int(dimension, "dimension")
103 self._bounds = _bounds(ind_domain)
104 width = self._bounds[1] - self._bounds[0]
105 self._exploration_sigma, self._emitter_sigma = exploration_sigma * width, emitter_sigma * width
106 if not all(0 < scale < np.inf for scale in (self._exploration_sigma, self._emitter_sigma)):
107 raise ValueError("The scaled mutation standard deviations must be positive and finite.")
108 self._population_size = _positive_int(population_size, "population_size")
109 self._neighbors = _positive_int(novelty_neighbors, "novelty_neighbors")
110 self._chunk = _positive_int(chunk_size, "chunk_size")
111 self._emitter_size = _positive_int(emitter_size, "emitter_size")
112 self._bootstrap_calls = _positive_int(bootstrap_calls, "bootstrap_calls")
113 self._stagnation = _positive_int(stagnation_calls, "stagnation_calls")
114 self._threshold = float(reward_threshold)
115 self._rng = np.random.default_rng(seed)
116 self._rollouts = np.random.default_rng(np.random.SeedSequence(seed).spawn(1)[0])
117 self._memory = deque(maxlen=_positive_int(novelty_capacity, "novelty_capacity"))
118 self._population, self._active = [], []
119 self._queued, self._discovered = {}, set()
120 self._probe = None
121 self._exploiting, self._remaining = False, self._chunk
122 self._calls, self._first_reward = 0, None
123 self._counts = dict(exploration_evaluations=0, bootstrap_evaluations=0, emitter_evaluations=0,
124 failed_evaluations=0, reward_updates=0, emitters_started=0)
125
126 @property
128 """Return the bounded memory of measured novelty discoveries."""
129 return tuple(self._memory)
130
131 @property
133 """Return the current novelty-selected breeding population."""
134 return tuple(self._population)
135
136 @property
137 def stats(self):
138 """Return cumulative search costs since construction."""
139 return SereneStats(first_reward_evaluation=self._first_reward, **self._counts)
140
141 def _novelty(self, rows, reference):
142 if not reference:
143 return np.zeros(len(rows))
144 distances = cdist([row.descriptor for row in rows], [row.descriptor for row in reference])
145 by_id = {id(row): i for i, row in enumerate(reference)}
146 for i, row in enumerate(rows):
147 if id(row) in by_id:
148 distances[i, by_id[id(row)]] = np.inf
149 count = min(self._neighbors, len(reference))
150 nearest = np.partition(distances, count - 1, axis=1)[:, :count]
151 finite = np.isfinite(nearest)
152 return np.where(finite, nearest, 0.).sum(axis=1) / np.maximum(1, finite.sum(axis=1))
153
154 def _reference(self):
155 return tuple({id(row): row for row in (*self._population, *self._memory)}.values())
156
157 def _measure(self, evaluate, parent, scale, phase):
158 point = (self._rng.uniform(*self._bounds, size=self.dimension) if parent is None else
159 np.clip(np.asarray(parent.genome) + self._rng.normal(0., scale, self.dimension), *self._bounds))
160 genome = tuple(map(float, point))
161 self._calls += 1
162 self._counts[phase] += 1
163 measurement = evaluate(genome, int(self._rollouts.integers(2**32)))
164 if measurement is None:
165 self._counts["failed_evaluations"] += 1
166 return None, None
167 reward, descriptor = measurement
168 reward, descriptor = float(reward), np.asarray(descriptor, dtype=float)
169 if (not np.isfinite(reward) or descriptor.shape != (len(self.archive.features_domain),)
170 or not np.isfinite(descriptor).all()):
171 raise ValueError("Return a finite scalar reward and a descriptor matching the grid, or None.")
172 elite = SereneElite(genome, reward, tuple(map(float, descriptor)))
173 if reward <= self._threshold:
174 return elite, None
175 if self._first_reward is None:
176 self._first_reward = self._calls
177 if (not self.archive.in_bounds(elite.descriptor, self.archive.features_domain)
178 or not self.archive.in_bounds((reward,), self.archive.fitness_domain)):
179 return elite, None
180 cell = self.archive.index_grid(elite.descriptor)
181 if self.archive.free > 0 or self.archive.solutions[cell]:
182 previous = self.archive.nb_added
183 self.archive.add(_CellIndividual(genome, cell, fitness=Fitness((reward,), weights=self.archive.fitness_weights),
184 features=Features(elite.descriptor)))
185 self._counts["reward_updates"] += self.archive.nb_added - previous
186 return elite, cell
187
188 def _explore(self, evaluate):
189 parent = (self._population[self._rng.integers(len(self._population))]
190 if len(self._population) == self._population_size else None)
191 row, cell = self._measure(evaluate, parent, self._exploration_sigma, "exploration_evaluations")
192 if row is None:
193 return
194 if cell is not None and cell not in self._discovered:
195 if cell not in self._queued or row.reward > self._queued[cell].reward:
196 self._queued[cell] = row
197 pool = self._population + [row]
198 reference = tuple({id(item): item for item in (*pool, *self._memory)}.values())
199 scores = self._novelty(pool, reference)
200 keep = np.argsort(-scores, kind="stable")[:self._population_size]
201 self._population = [pool[i] for i in keep]
202 if len(pool) <= self._population_size or len(pool) - 1 in keep:
203 self._memory.append(row)
204
205 def _select_emitter(self):
206 if self._probe is None and self._queued:
207 cells, rows = zip(*self._queued.items())
208 reward_reference = [SereneElite((), 0., tuple(self.archive.get_ind_features(ind)))
209 for ind in self.archive]
210 i = int(np.argmax(self._novelty(rows, reward_reference)))
211 self._discovered.add(cells[i])
212 row = self._queued.pop(cells[i])
213 self._probe = _Emitter([row], self._novelty([row], self._reference())[0])
214 self._counts["emitters_started"] += 1
215 if self._probe is not None:
216 return self._probe
217 scores = np.asarray([(emitter.novelty, emitter.improvement) for emitter in self._active])
218 dominates = (scores[:, None] >= scores).all(axis=2) & (scores[:, None] > scores).any(axis=2)
219 front = np.flatnonzero(~dominates.any(axis=0))
220 return self._active[self._rng.choice(front)]
221
222 def _exploit(self, evaluate):
223 emitter = self._select_emitter()
224 probing = emitter is self._probe
225 parent = emitter.population[self._rng.integers(len(emitter.population))]
226 best = emitter.population[0].reward
227 row, _ = self._measure(evaluate, parent, self._emitter_sigma,
228 "bootstrap_evaluations" if probing else "emitter_evaluations")
229 if row is not None:
230 emitter.population.append(row)
231 emitter.population.sort(key=lambda item: item.reward, reverse=True)
232 del emitter.population[self._emitter_size:]
233 if self._novelty([row], self._reference())[0] > emitter.novelty:
234 self._memory.append(row)
235 gain = emitter.population[0].reward - best
236 if probing:
237 emitter.improvement += gain
238 emitter.probes += 1
239 if emitter.probes == self._bootstrap_calls:
240 if emitter.improvement > 0.:
241 self._active.append(emitter)
242 self._probe = None
243 else:
244 emitter.improvement = .9 * emitter.improvement + .1 * gain
245 emitter.stalls = 0 if gain > 0. else emitter.stalls + 1
246 if emitter.stalls == self._stagnation:
247 self._active.remove(emitter)
248
249
253 def run(self, evaluate, budget):
254 """Continue from the current population and phase, including partial chunks."""
255 for _ in range(_positive_int(budget, "budget")):
256 if self._exploiting and (self._probe is not None or self._queued or self._active):
257 self._exploit(evaluate)
258 else:
259 if self._exploiting:
260 self._exploiting, self._remaining = False, self._chunk
261 self._explore(evaluate)
262 self._remaining -= 1
263 if self._remaining == 0:
264 self._exploiting, self._remaining = not self._exploiting, self._chunk
265 return self.stats
Explore by novelty and exploit rewarding discoveries on alternating budgets.
Definition serene.py:60
_novelty(self, rows, reference)
Definition serene.py:141
_measure(self, evaluate, parent, scale, phase)
Definition serene.py:157
_exploit(self, evaluate)
Definition serene.py:222
run(self, evaluate, budget)
Spend an additional budget of attempted evaluations.
Definition serene.py:253
_explore(self, evaluate)
Definition serene.py:188
An actual evaluator observation retained by the novelty search.
Definition serene.py:23
Cumulative search costs and sparse-reward discovery.
Definition serene.py:33
:param obj: Slice indicating on which objectives the domination is tested.
Definition phenotype.py:405