5"""Discover diverse behaviors with discounted occupancy embeddings and CMA-MAE."""
8from dataclasses
import dataclass
9from math
import isfinite
10from numbers
import Real
16from qdpy.phenotype import Features, Fitness, Individual, ScoresDict
17from .modern
import CMAMAE, _positive_int
18from .task_search
import _validate_grid
20__all__ = [
"OccupancyDescriptor",
"AutoQDResult",
"autoqd_search"]
27 """A seeded random-feature map and its current linear descriptor projection.
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.
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.
41 def __init__(self, trajectory_width, descriptor_dim, *, embedding_dim=128, bandwidth=1., gamma=0.99, seed=0):
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.")
49 rng = np.random.default_rng(seed)
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)
55 raise ValueError(
"The bandwidth produced nonfinite frequencies.")
57 def _embed(self, trajectories):
60 scale = (1 - self.
gamma) * np.sqrt(2. / len(self.
_phase))
61 for trajectory
in trajectories:
62 values = np.asarray(trajectory, dtype=float)
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"):
68 discounts = self.
gamma ** np.arange(len(values))
69 sums.append(scale * (discounts @ np.cos(phases)))
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
80 """Return the random Fourier feature vector before dimensionality reduction."""
81 return self.
_embed(trajectories)[0]
85 """Return calibrated descriptors clipped to the grid limits."""
89 def _project(self, embedding):
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))
96 """Return a calibrated weighted PCA copy if the data can span the requested coordinates."""
97 count = len(embeddings)
99 if count <= dimension:
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:
112 basis = vectors[:dimension]
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)
119 fitted._projection = scale[:,
None] * basis
120 fitted._offset = -1 - scale * low - fitted._projection @ mean
125@dataclass(frozen=True)
127 """Rollout and boundary counts describe valid recorded evaluations.
129 Attempts include callbacks that failed or returned invalid values.
130 Rebuilds and skipped rebuilds count scheduled descriptor updates.
134 projector: OccupancyDescriptor
138 trajectory_steps: int
139 boundary_evaluations: int
141 skipped_rebuilds: int
144def _feedback(archive, fitness, descriptor):
145 descriptor = tuple(map(float, descriptor))
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
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))
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.
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.
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")
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)
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")
221 search = emitter(archive, x0, budget)
222 attempts = failures = rollouts = steps = boundary = rebuilds = skipped = full_batches = 0
224 while attempts < budget:
225 candidates = search.ask_batch(min(batch_size, budget - attempts))
227 for candidate
in candidates:
229 candidate.name = str(attempts)
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)
243 feedback.append(result)
244 embeddings[candidate.name] = embedding
247 boundary += hit_boundary
249 search.tell_batch(feedback)
250 embeddings = {elite.name: embeddings[elite.name]
for elite
in archive}
251 if len(candidates) < batch_size:
254 if update_interval
is None or full_batches % update_interval:
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)
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)
270 projector, archive = fitted, fresh
271 embeddings = {elite.name: embeddings[elite.name]
for elite
in archive}
274 return AutoQDResult(archive, projector, attempts, failures, rollouts, steps, boundary, rebuilds, skipped)
AutoQD's final native grid, fitted descriptor, and evaluation accounting.
Embed discounted state-action occupancy and project it into grid coordinates.
embed(self, trajectories)
Compute a policy's embedding using the complete weighted trajectories.
_project(self, embedding)
_fitted(self, embeddings, fitness)
_embed(self, trajectories)
transform(self, trajectories)
Project trajectories to the same bounded coordinates as the archive.
Adapt a covariance matrix using annealed cell-level improvement.
:param obj: Slice indicating on which objectives the domination is tested.