QDpy
Loading...
Searching...
No Matches
autoqd.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Discover diverse behaviors with discounted occupancy embeddings and CMA-MAE."""
6
7from copy import copy
8from dataclasses import dataclass
9from math import isfinite
10from numbers import Real
11import warnings
12
13import numpy as np
14
15from qdpy.containers import Grid
16from qdpy.phenotype import Features, Fitness, Individual, ScoresDict
17from .modern import CMAMAE, _positive_int
18from .task_search import _validate_grid
19
20__all__ = ["OccupancyDescriptor", "AutoQDResult", "autoqd_search"]
21
22_MEASURE_LIMIT = 1.2
23
24
25
27 """A seeded random-feature map and its current linear descriptor projection.
28
29 Each trajectory is a finite matrix with one state-action row per
30 transition. Input coordinates stay fixed across fits. The embedding
31 averages discounted Fourier features across complete trajectories.
32
33 :param trajectory_width: Number of numeric coordinates in each row.
34 :param descriptor_dim: Number of dimensions returned by transform().
35 :param embedding_dim: Number of random Fourier features.
36 :param bandwidth: Width of the Gaussian kernel in input units.
37 :param gamma: Discount in [0, 1).
38 :param seed: Seed for the random features and initial orthogonal projection.
39 """
40
41 def __init__(self, trajectory_width, descriptor_dim, *, embedding_dim=128, bandwidth=1., gamma=0.99, seed=0):
42 self.trajectory_width = _positive_int(trajectory_width, "trajectory_width")
43 descriptor_dim = _positive_int(descriptor_dim, "descriptor_dim")
44 embedding_dim = _positive_int(embedding_dim, "embedding_dim")
45 if (not 0 < bandwidth < float("inf") or not isfinite(1. / bandwidth)
46 or not 0 <= gamma < 1 or descriptor_dim > embedding_dim):
47 raise ValueError("Use a finite reciprocal bandwidth, 0 <= gamma < 1, and enough embedding dimensions.")
48 self.gamma = gamma
49 rng = np.random.default_rng(seed)
50 self._frequencies = rng.normal(size=(self.trajectory_width, embedding_dim)) / bandwidth
51 self._phase = rng.uniform(0, 2 * np.pi, size=embedding_dim)
52 self._projection = np.linalg.qr(rng.normal(size=(embedding_dim, descriptor_dim)))[0].T
53 self._offset = np.zeros(descriptor_dim)
54 if not np.isfinite(self._frequencies).all():
55 raise ValueError("The bandwidth produced nonfinite frequencies.")
56
57 def _embed(self, trajectories):
58 sums = []
59 steps = 0
60 scale = (1 - self.gamma) * np.sqrt(2. / len(self._phase))
61 for trajectory in trajectories:
62 values = np.asarray(trajectory, dtype=float)
63 if (values.ndim != 2 or values.shape[1] != self.trajectory_width
64 or not len(values) or not np.isfinite(values).all()):
65 raise ValueError("Each trajectory must be a nonempty finite matrix of the declared width.")
66 with np.errstate(over="ignore", invalid="ignore"):
67 phases = values @ self._frequencies + self._phase
68 discounts = self.gamma ** np.arange(len(values))
69 sums.append(scale * (discounts @ np.cos(phases)))
70 steps += len(values)
71 if not sums:
72 raise ValueError("Supply at least one trajectory per evaluation.")
73 embedding = np.mean(sums, axis=0)
74 if not np.isfinite(embedding).all():
75 raise ValueError("Trajectory coordinates overflowed the Fourier embedding.")
76 return embedding, len(sums), steps
77
78
79 def embed(self, trajectories):
80 """Return the random Fourier feature vector before dimensionality reduction."""
81 return self._embed(trajectories)[0]
82
83
84 def transform(self, trajectories):
85 """Return calibrated descriptors clipped to the grid limits."""
86 values, _ = self._project(self.embed(trajectories))
87 return values
88
89 def _project(self, embedding):
90 raw = self._projection @ embedding + self._offset
91 if not np.isfinite(raw).all():
92 raise ValueError("The occupancy projection returned nonfinite descriptors.")
93 return np.clip(raw, -_MEASURE_LIMIT, _MEASURE_LIMIT), bool(np.any(np.abs(raw) >= _MEASURE_LIMIT))
94
95 def _fitted(self, embeddings, fitness):
96 """Return a calibrated weighted PCA copy if the data can span the requested coordinates."""
97 count = len(embeddings)
98 dimension = len(self._offset)
99 if count <= dimension:
100 return None
101 largest = np.max(np.abs(fitness))
102 quality = fitness / largest if largest else fitness
103 spread = np.ptp(quality)
104 weights = np.maximum((quality - quality.min()) / spread, 1. / count) if spread else np.ones(count)
105 weights /= weights.sum()
106 mean = weights @ embeddings
107 centered = embeddings - mean
108 _, singular, vectors = np.linalg.svd(centered * np.sqrt(weights)[:, None], full_matrices=False)
109 tolerance = np.finfo(float).eps * max(centered.shape) * singular[0]
110 if singular[dimension - 1] <= tolerance:
111 return None
112 basis = vectors[:dimension]
113 # Fix the sign of each axis for consistent interpretation and replay.
114 pivots = np.argmax(np.abs(basis), axis=1)
115 basis *= np.sign(basis[np.arange(dimension), pivots])[:, None]
116 low, high = np.quantile(centered @ basis.T, [0.05, 0.95], axis=0)
117 scale = 2. / np.maximum(high - low, 1e-6)
118 fitted = copy(self)
119 fitted._projection = scale[:, None] * basis
120 fitted._offset = -1 - scale * low - fitted._projection @ mean
121 return fitted
122
123
124
125@dataclass(frozen=True)
127 """Rollout and boundary counts describe valid recorded evaluations.
128
129 Attempts include callbacks that failed or returned invalid values.
130 Rebuilds and skipped rebuilds count scheduled descriptor updates.
131 """
132
133 archive: Grid
134 projector: OccupancyDescriptor
135 attempts: int
136 failures: int
137 rollouts: int
138 trajectory_steps: int
139 boundary_evaluations: int
140 rebuilds: int
141 skipped_rebuilds: int
142
143
144def _feedback(archive, fitness, descriptor):
145 descriptor = tuple(map(float, descriptor))
146 scores = ScoresDict()
147 for labels, values in ((archive.fitness_score_names, (fitness,)),
148 (archive.features_score_names, descriptor)):
149 for name, value in zip(labels, values):
150 if scores.setdefault(name, value) != value:
151 raise ValueError(f"Conflicting measurements for score {name!r}.")
152 return (fitness,), descriptor, scores
153
154
155def _rebuild(archive, projector, embeddings):
156 """Prepare a replacement grid without mutating the previous archive or its candidates."""
157 fresh = Grid(shape=archive.shape, features_domain=archive.features_domain,
158 fitness_domain=archive.fitness_domain, fitness_weights=archive.fitness_weights,
159 fitness_score_names=archive.fitness_score_names, features_score_names=archive.features_score_names,
160 capacity=archive.capacity, storage_type=type(archive.items), name=archive.name)
161 for elite in archive:
162 measured = archive.get_ind_fitness(elite).values[0]
163 features, _ = projector._project(embeddings[elite.name])
164 fitness, descriptors, scores = _feedback(fresh, measured, features)
165 fresh.add(Individual(elite, name=elite.name, fitness=Fitness(fitness, weights=(1.,)),
166 features=Features(descriptors), scores=scores))
167 return fresh
168
169
170
171def autoqd_search(evaluate, archive, *, budget, x0, sigma0, threshold_min, trajectory_width,
172 batch_size=16, ind_domain=None, learning_rate=0.01, embedding_dim=128, bandwidth=1.,
173 gamma=0.99, update_interval=10, seed=0):
174 """Search for high-performing policies with trajectory-derived descriptors.
175
176 :param evaluate: Callable taking a numeric genome tuple and a per-attempt
177 seed. Return (fitness, trajectories), with one or more arrays of
178 state-action rows. Fitness is maximized.
179 :param archive: Empty parentless one-elite Grid with feature bounds
180 [-1.2, 1.2] on every axis and a domain for one maximizing objective.
181 :param budget: Hard budget in attempted candidate calls.
182 :param x0: Initial CMA center with at least two real coordinates.
183 :param sigma0: Initial step size for CMA-MAE and its restarts.
184 :param threshold_min: Initial CMA-MAE threshold in raw quality units.
185 :param trajectory_width: Number of state-action coordinates per step.
186 :param batch_size: CMA population size. The last batch may be partial.
187 :param ind_domain: Optional common lower and upper genome bounds.
188 :param learning_rate: CMA-MAE threshold update rate.
189 :param embedding_dim: Number of random Fourier features.
190 :param bandwidth: Gaussian kernel width in the caller's fixed input units.
191 :param gamma: Discount applied within trajectories.
192 :param update_interval: Full generations between descriptor updates. None
193 keeps the initial projection for a comparison at fixed coordinates.
194 :param seed: Root seed for independent descriptor, evaluator, and emitter streams.
195 :returns: AutoQDResult with the last grid, usable projector, and counts.
196 """
197 if not callable(evaluate):
198 raise TypeError("evaluate must be callable.")
199 _validate_grid(archive)
200 limits = ((-_MEASURE_LIMIT, _MEASURE_LIMIT),) * len(archive.shape)
201 if type(archive) is not Grid or tuple(map(tuple, archive.features_domain)) != limits:
202 raise ValueError("Use a rectangular Grid with descriptor bounds [-1.2, 1.2] on every axis.")
203 if archive.fitness_weights is not None and tuple(archive.fitness_weights) != (1.,):
204 raise ValueError("Use an unweighted maximizing objective (fitness_weights=(1.,)).")
205 budget = _positive_int(budget, "budget")
206 batch_size = _positive_int(batch_size, "batch_size")
207 if update_interval is not None:
208 update_interval = _positive_int(update_interval, "update_interval")
209
210 features_seed, evaluation_seed, emitters_seed = np.random.SeedSequence(seed).spawn(3)
211 rng = np.random.default_rng(evaluation_seed)
212 emitters = np.random.default_rng(emitters_seed)
213 projector = OccupancyDescriptor(trajectory_width, len(archive.shape), embedding_dim=embedding_dim,
214 bandwidth=bandwidth, gamma=gamma, seed=features_seed)
215
216 def emitter(grid, center, remaining):
217 return CMAMAE(grid, remaining, center, sigma0, batch_size, threshold_min, ind_domain=ind_domain,
218 learning_rate=learning_rate, seed=int(emitters.integers(2**32)),
219 optimisation_task="maximisation")
220
221 search = emitter(archive, x0, budget)
222 attempts = failures = rollouts = steps = boundary = rebuilds = skipped = full_batches = 0
223 embeddings = {}
224 while attempts < budget:
225 candidates = search.ask_batch(min(batch_size, budget - attempts))
226 feedback = []
227 for candidate in candidates:
228 attempts += 1
229 candidate.name = str(attempts)
230 try:
231 fitness, trajectories = evaluate(tuple(candidate), int(rng.integers(2**32)))
232 if (not isinstance(fitness, Real) or not isfinite(fitness)
233 or not archive.in_bounds((fitness,), archive.fitness_domain)):
234 raise ValueError("Fitness must be finite and within the archive's fitness domain.")
235 embedding, episodes, length = projector._embed(trajectories)
236 descriptor, hit_boundary = projector._project(embedding)
237 result = _feedback(archive, float(fitness), descriptor)
238 except Exception as error:
239 warnings.warn(f"AutoQD evaluation failed: {error}", stacklevel=2)
240 feedback.append(None)
241 failures += 1
242 continue
243 feedback.append(result)
244 embeddings[candidate.name] = embedding
245 rollouts += episodes
246 steps += length
247 boundary += hit_boundary
248
249 search.tell_batch(feedback)
250 embeddings = {elite.name: embeddings[elite.name] for elite in archive}
251 if len(candidates) < batch_size:
252 continue
253 full_batches += 1
254 if update_interval is None or full_batches % update_interval:
255 continue
256 try:
257 values = np.asarray([embeddings[elite.name] for elite in archive])
258 scores = np.asarray([archive.get_ind_fitness(elite).values[0] for elite in archive])
259 fitted = projector._fitted(values, scores)
260 if fitted is None:
261 skipped += 1
262 continue
263 fresh = _rebuild(archive, fitted, embeddings)
264 if attempts < budget:
265 search = emitter(fresh, list(fresh.best), budget - attempts)
266 except (ValueError, IndexError, KeyError, TypeError, RuntimeError, np.linalg.LinAlgError) as error:
267 warnings.warn(f"AutoQD descriptor update failed: {error}", stacklevel=2)
268 skipped += 1
269 continue
270 projector, archive = fitted, fresh
271 embeddings = {elite.name: embeddings[elite.name] for elite in archive}
272 rebuilds += 1
273
274 return AutoQDResult(archive, projector, attempts, failures, rollouts, steps, boundary, rebuilds, skipped)
AutoQD's final native grid, fitted descriptor, and evaluation accounting.
Definition autoqd.py:126
Embed discounted state-action occupancy and project it into grid coordinates.
Definition autoqd.py:26
embed(self, trajectories)
Compute a policy's embedding using the complete weighted trajectories.
Definition autoqd.py:79
_fitted(self, embeddings, fitness)
Definition autoqd.py:95
transform(self, trajectories)
Project trajectories to the same bounded coordinates as the archive.
Definition autoqd.py:84
Adapt a covariance matrix using annealed cell-level improvement.
Definition modern.py:343
:param obj: Slice indicating on which objectives the domination is tested.
Definition phenotype.py:405