QDpy
Loading...
Searching...
No Matches
aurora_xcon.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Single-repertoire AURORA and AURORA-XCon with optional PyTorch."""
7
8from copy import deepcopy
9from dataclasses import dataclass
10
11import numpy as np
12from scipy.spatial.distance import pdist
13
14from qdpy.containers import Container
15from qdpy.containers import mc_aurora
16from qdpy.phenotype import Features, Fitness, Individual
17from qdpy.tools import iso_line_dd
18from .modern import _positive_int, _variation_settings
19
20__all__ = ["AuroraXCon", "AuroraXConStats"]
21
22_OBSERVATION = "aurora_trajectory"
23
24
26 """Apply nearest-neighbour competition at the current novelty radius."""
27
28 def __init__(self, dimensions, radius, capacity):
29 self.radius = radius
30 super().__init__(capacity=capacity, features_domain=((-np.inf, np.inf),) * dimensions,
31 fitness_domain=((-np.inf, np.inf),), fitness_weights=(1.,))
32
33
38 def _add_internal(self, individual, raise_if_not_added_to_parents, only_to_parents):
39 if not self or only_to_parents:
40 return super()._add_internal(individual, raise_if_not_added_to_parents, only_to_parents)
41 victim = self._index_of(individual)
42 if victim is None:
43 distances = np.linalg.norm(np.asarray([row.features.values for row in self]) -
44 individual.features.values, axis=1)
45 nearest = int(np.argmin(distances))
46 if distances[nearest] < self.radius:
47 victim = nearest
48 elif self.free < 1:
49 victim = min(range(len(self)), key=lambda i: self[i].fitness.values[0])
50 if victim is not None and individual.fitness.values[0] <= self[victim].fitness.values[0]:
51 self._nb_rejected += 1
52 return None
53 return super()._add_internal(individual, raise_if_not_added_to_parents, False, victim)
54
55
56
57@dataclass(frozen=True)
59 """Archive updates count normal search admissions, excluding remaps."""
60
61 evaluations: int
62 failed_evaluations: int
63 archive_updates: int
64 refits: int
65 optimizer_steps: int
66 extinctions: int
67 pruned: int
68 novelty_radius: float
69
70
71
73 """Train a latent encoder on live elites, with separate ablation settings.
74
75 Use loss="triplet" for contrastive training or "reconstruction" for plain
76 autoencoding. A positive extinction_period retains the best member and a
77 seeded random subset of others. The active archive is rebuilt after each
78 refit. Keep any external reporting archives in the evaluator so they do
79 not feed discarded records back into search or training.
80
81 :param dimension: Length of the bounded real genome.
82 :param latent_size: Width of the learned descriptor.
83 :param ind_domain: Shared bounds on real parameters.
84 :param capacity: Maximum active repertoire size.
85 :param radius: Initial nearest-neighbour replacement radius in latent coordinates.
86 :param target_size: Desired live repertoire size. Defaults to half capacity, capped at 32.
87 :param size_gain: Relative proportional gain for radius adjustment. Zero fixes the radius.
88 :param loss: "triplet" or "reconstruction".
89 :param initial_samples: Uniform attempts used for the first encoder fit.
90 :param training_period: Attempted evaluations between later refits.
91 :param extinction_period: Attempts after warmup between prunings. Zero disables pruning.
92 :param survival_fraction: Fraction to retain randomly, in addition to the best.
93 :param epochs: Training passes per refit.
94 :param batch_size: Maximum observations or triplets per training update.
95 :param learning_rate: Adam step size, with fresh moments at each refit.
96 :param iso_sigma: Iso+LineDD independent noise scale.
97 :param line_sigma: Iso+LineDD direction scale.
98 :param seed: Seed for proposals, evaluator calls, and training.
99 :param device: PyTorch device, CPU by default.
100 """
101
102 def __init__(self, dimension, *, latent_size=2, ind_domain=(0., 1.), capacity=256, radius=.1, loss="triplet",
103 target_size=None, size_gain=.05,
104 initial_samples=24, training_period=32, extinction_period=128, survival_fraction=.05,
105 epochs=4, batch_size=16, learning_rate=1e-3, iso_sigma=.05, line_sigma=.2, seed=0, device="cpu"):
106 if mc_aurora.torch is None:
107 raise ImportError("AuroraXCon requires PyTorch. Install qdpy[rl] or torch.")
108 if loss not in ("triplet", "reconstruction"):
109 raise ValueError("Choose triplet or reconstruction loss.")
110 if not (0. < radius < np.inf and 0. < learning_rate < np.inf
111 and 0. <= survival_fraction <= 1. and 0. <= size_gain <= 1.):
112 raise ValueError("Use finite positive radius and learning_rate and fractions and gains in [0, 1].")
113 self._dimension = _positive_int(dimension, "dimension")
114 self._latent_size = _positive_int(latent_size, "latent_size")
115 self._bounds = _variation_settings(ind_domain, iso_sigma, line_sigma)
116 if not np.isfinite(self._bounds[1] - self._bounds[0]):
117 raise ValueError("Use a finite decision interval width.")
118 self._capacity = _positive_int(capacity, "capacity")
119 self._target = (max(1, min(32, self._capacity // 2)) if target_size is None
120 else _positive_int(target_size, "target_size"))
121 if self._target > self._capacity:
122 raise ValueError("target_size must fit within capacity.")
123 self._size_gain = size_gain
124 self._warmup = _positive_int(initial_samples, "initial_samples")
125 self._train_period = _positive_int(training_period, "training_period")
126 self._extinction_period = (0 if extinction_period == 0 else _positive_int(extinction_period,
127 "extinction_period"))
128 self._epochs = _positive_int(epochs, "epochs")
129 self._batch_size = _positive_int(batch_size, "batch_size")
130 self._rate, self._radius, self._loss = learning_rate, radius, loss
131 self._survival = survival_fraction
132 self._iso_sigma, self._line_sigma = iso_sigma, line_sigma
133 self._rng = np.random.default_rng(seed)
134 self._training, self._rollouts, self._pruning = (
135 np.random.default_rng(s) for s in np.random.SeedSequence(seed).spawn(3))
136 self._device = mc_aurora.torch.device(device)
137 self.archive = self._new_archive()
138 self._warmup_rows = []
139 self._shape = self._model = None
140 self._counts = dict(evaluations=0, failed_evaluations=0, archive_updates=0, refits=0, optimizer_steps=0,
141 extinctions=0, pruned=0)
142
143 @property
144 def stats(self):
145 """Return cumulative costs and changes since construction."""
146 return AuroraXConStats(**self._counts, novelty_radius=self._radius)
147
148 def _new_archive(self):
149 return _AuroraRepertoire(self._latent_size, self._radius, self._capacity)
150
151 def _tensor(self, points):
152 return mc_aurora.torch.as_tensor(points, dtype=mc_aurora.torch.float32, device=self._device)
153
154 def _rows(self, records):
155 return self._tensor(np.stack([record.scores[_OBSERVATION] for record in records]))
156
157 def _embeddings(self, model, points):
158 with mc_aurora.torch.no_grad():
159 values = model.encoder(points).cpu().numpy()
160 if not np.isfinite(values).all():
161 raise ValueError("The encoder produced nonfinite descriptors.")
162 return values
163
164 def _new_model(self):
165 torch = mc_aurora.torch
166 with torch.random.fork_rng(devices=[]):
167 torch.random.default_generator.manual_seed(int(self._training.integers(2**32)))
169 device=self._device, dtype=torch.float32)
170
171 def _triplets(self, qualities):
172 # Exclude the anchor and sample two distinct challengers.
173 ids = np.arange(len(qualities))
174 first = self._training.integers(len(ids) - 1, size=len(ids))
175 first += first >= ids
176 second = self._training.integers(len(ids) - 2, size=len(ids))
177 second += second >= np.minimum(first, ids)
178 second += second >= np.maximum(first, ids)
179 distances = np.abs(qualities[:, None] * .5 - qualities[np.column_stack((first, second))] * .5)
180 distinct = distances[:, 0] != distances[:, 1]
181 swap = distances[:, 0] > distances[:, 1]
182 return np.column_stack((ids, np.where(swap, second, first), np.where(swap, first, second)))[distinct]
183
184 def _train_encoder(self, model, points, qualities):
185 torch = mc_aurora.torch
186 optimizer = torch.optim.Adam(model.parameters(), lr=self._rate)
187 if self._loss == "triplet" and len(points) < 3:
188 return
189 for _ in range(self._epochs):
190 if self._loss == "triplet":
191 pairs = pdist(self._embeddings(model, points))
192 margin = float(max(np.min(pairs), np.finfo(np.float32).eps))
193 rows = self._triplets(qualities)
194 else:
195 rows = np.arange(len(points))
196 rows = rows[self._training.permutation(len(rows))]
197 for start in range(0, len(rows), self._batch_size):
198 indices = rows[start:start + self._batch_size]
199 if self._loss == "triplet":
200 values = model.encoder(points[indices.reshape(-1)]).reshape(-1, 3, self._latent_size)
201 anchor, near, far = values.unbind(1)
202 loss = (torch.linalg.vector_norm(anchor - near, dim=1) -
203 torch.linalg.vector_norm(anchor - far, dim=1) + margin).clamp_min(0).mean()
204 else:
205 batch = points[indices]
206 loss = (model(batch) - batch).square().mean()
207 if not torch.isfinite(loss):
208 raise ValueError("The encoder loss is nonfinite.")
209 optimizer.zero_grad()
210 loss.backward()
211 optimizer.step()
212 self._counts["optimizer_steps"] += 1
213
214 def _refit(self, records):
215 model = self._new_model() if self._model is None else deepcopy(self._model)
216 points = self._rows(records)
217 qualities = np.asarray([row.fitness.values[0] for row in records])
218 with mc_aurora.torch.enable_grad():
219 self._train_encoder(model, points, qualities)
220 descriptors = self._embeddings(model, points)
221 # Start with the fittest measured solution, then replay in archive order.
222 # Cloning avoids leaving readers of the old archive with stale features.
223 rebuilt = self._new_archive()
224 first = int(np.argmax(qualities))
225 for i in (first, *(j for j in range(len(records)) if j != first)):
226 row = records[i]
227 rebuilt.add(Individual(row, fitness=row.fitness, features=Features(tuple(descriptors[i])),
228 scores={_OBSERVATION: row.scores[_OBSERVATION]}))
229 self.archive, self._model = rebuilt, model
230 self._counts["refits"] += 1
231
232 def _prune(self):
233 before = len(self.archive)
234 others = [row for row in self.archive if row is not self.archive.best]
235 size = int(len(others) * self._survival)
236 keep = set(map(int, self._pruning.choice(len(others), size=size, replace=False)))
237 for i, row in enumerate(others):
238 if i not in keep:
239 self.archive.discard(row)
240 self._counts["extinctions"] += 1
241 self._counts["pruned"] += before - len(self.archive)
242
243 def _adapt_radius(self):
244 error = (len(self.archive) - self._target) / self._target
245 self._radius = max(np.finfo(np.float32).eps, self._radius * (1. + self._size_gain * error))
246 self.archive.radius = self._radius
247
248 def _record(self, genome, reward, trajectory):
249 quality = np.asarray(reward, dtype=float)
250 points = np.array(trajectory, dtype=np.float32, copy=True)
251 if (quality.shape not in ((), (1,)) or not np.isfinite(quality).all() or points.ndim != 2
252 or not points.size or not np.isfinite(points).all() or (np.abs(points) > 1).any()
253 or (self._shape is not None and self._shape != points.shape)):
254 raise ValueError("Return finite scalar fitness and a fixed-shape trajectory scaled to [-1, 1].")
255 self._shape = points.shape
256 points.setflags(write=False)
257 record = Individual(genome, fitness=Fitness((float(quality.item()),), weights=(1.,)),
258 scores={_OBSERVATION: points})
259 if self._model is None:
260 self._warmup_rows.append(record)
261 else:
262 record.features = Features(tuple(self._embeddings(self._model, self._tensor(points[None, ...].copy()))[0]))
263 previous = self.archive.nb_added
264 self.archive.add(record)
265 self._counts["archive_updates"] += self.archive.nb_added - previous
266
267 def _refresh_representation(self):
268 age = self._counts["evaluations"] - self._warmup
269 if self._model is None and age >= 0 and self._warmup_rows:
270 self._refit(self._warmup_rows)
271 self._warmup_rows.clear()
272 elif self.archive and age > 0:
273 if age % self._train_period == 0:
274 self._refit(tuple(self.archive))
275 if self._extinction_period and age % self._extinction_period == 0:
276 self._prune()
277 if self._size_gain:
278 self._adapt_radius()
279
280
284 def run(self, evaluate, budget):
285 """Measure one trajectory per proposal and charge failed attempts."""
286 for _ in range(_positive_int(budget, "budget")):
287 calls = self._counts["evaluations"]
288 if calls < self._warmup or not self.archive:
289 genome = self._rng.uniform(*self._bounds, self._dimension)
290 else:
291 first, second = self._rng.integers(len(self.archive), size=2)
292 genome = iso_line_dd(self.archive[first], self.archive[second], bounds=self._bounds,
293 iso_sigma=self._iso_sigma, line_sigma=self._line_sigma, rng=self._rng)
294 genome = tuple(map(float, genome))
295 self._counts["evaluations"] += 1
296 measurement = evaluate(genome, int(self._rollouts.integers(2**32)))
297 if measurement is None:
298 self._counts["failed_evaluations"] += 1
299 else:
300 self._record(genome, *measurement)
302 return self.stats
Count objective calls, encoder training, remaps, and pruning events.
Search with learned trajectory coordinates and a periodically pruned repertoire.
_record(self, genome, reward, trajectory)
run(self, evaluate, budget)
Continue search, preserving phase timing across additional budgets.
_train_encoder(self, model, points, qualities)
_add_internal(self, individual, raise_if_not_added_to_parents, only_to_parents)
Select a latent neighbour before updating native storage.
Optional[int] _index_of(self, IndividualLike individual)
Definition base.py:769
Dense MC-AURORA default with a smooth activation in the hidden layers.
Definition mc_aurora.py:32
:param obj: Slice indicating on which objectives the domination is tested.
Definition phenotype.py:405