# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Trajectory-based descriptors and scheduled CMA-MAE rebuilds for AutoQD.
"""Discover diverse behaviors with discounted occupancy embeddings and CMA-MAE."""
from copy import copy
from dataclasses import dataclass
from math import isfinite
from numbers import Real
import warnings
import numpy as np
from qdpy.containers import Grid
from qdpy.phenotype import Features, Fitness, Individual, ScoresDict
from .modern import CMAMAE, _positive_int
from .task_search import _validate_grid
__all__ = ["OccupancyDescriptor", "AutoQDResult", "autoqd_search"]
_MEASURE_LIMIT = 1.2
## @brief Embed discounted state-action occupancy and project it into grid coordinates.
[docs]
class OccupancyDescriptor:
"""A seeded random-feature map and its current linear descriptor projection.
Each trajectory is a finite matrix with one state-action row per
transition. Input coordinates stay fixed across fits. The embedding
averages discounted Fourier features across complete trajectories.
:param trajectory_width: Number of numeric coordinates in each row.
:param descriptor_dim: Number of dimensions returned by transform().
:param embedding_dim: Number of random Fourier features.
:param bandwidth: Width of the Gaussian kernel in input units.
:param gamma: Discount in [0, 1).
:param seed: Seed for the random features and initial orthogonal projection.
"""
def __init__(self, trajectory_width, descriptor_dim, *, embedding_dim=128, bandwidth=1., gamma=0.99, seed=0):
self.trajectory_width = _positive_int(trajectory_width, "trajectory_width")
descriptor_dim = _positive_int(descriptor_dim, "descriptor_dim")
embedding_dim = _positive_int(embedding_dim, "embedding_dim")
if (not 0 < bandwidth < float("inf") or not isfinite(1. / bandwidth)
or not 0 <= gamma < 1 or descriptor_dim > embedding_dim):
raise ValueError("Use a finite reciprocal bandwidth, 0 <= gamma < 1, and enough embedding dimensions.")
self.gamma = gamma
rng = np.random.default_rng(seed)
self._frequencies = rng.normal(size=(self.trajectory_width, embedding_dim)) / bandwidth
self._phase = rng.uniform(0, 2 * np.pi, size=embedding_dim)
self._projection = np.linalg.qr(rng.normal(size=(embedding_dim, descriptor_dim)))[0].T
self._offset = np.zeros(descriptor_dim)
if not np.isfinite(self._frequencies).all():
raise ValueError("The bandwidth produced nonfinite frequencies.")
def _embed(self, trajectories):
sums = []
steps = 0
scale = (1 - self.gamma) * np.sqrt(2. / len(self._phase))
for trajectory in trajectories:
values = np.asarray(trajectory, dtype=float)
if (values.ndim != 2 or values.shape[1] != self.trajectory_width
or not len(values) or not np.isfinite(values).all()):
raise ValueError("Each trajectory must be a nonempty finite matrix of the declared width.")
with np.errstate(over="ignore", invalid="ignore"):
phases = values @ self._frequencies + self._phase
discounts = self.gamma ** np.arange(len(values))
sums.append(scale * (discounts @ np.cos(phases)))
steps += len(values)
if not sums:
raise ValueError("Supply at least one trajectory per evaluation.")
embedding = np.mean(sums, axis=0)
if not np.isfinite(embedding).all():
raise ValueError("Trajectory coordinates overflowed the Fourier embedding.")
return embedding, len(sums), steps
## @brief Compute a policy's embedding using the complete weighted trajectories.
[docs]
def embed(self, trajectories):
"""Return the random Fourier feature vector before dimensionality reduction."""
return self._embed(trajectories)[0]
## @brief Project trajectories to the same bounded coordinates as the archive.
def _project(self, embedding):
raw = self._projection @ embedding + self._offset
if not np.isfinite(raw).all():
raise ValueError("The occupancy projection returned nonfinite descriptors.")
return np.clip(raw, -_MEASURE_LIMIT, _MEASURE_LIMIT), bool(np.any(np.abs(raw) >= _MEASURE_LIMIT))
def _fitted(self, embeddings, fitness):
"""Return a calibrated weighted PCA copy if the data can span the requested coordinates."""
count = len(embeddings)
dimension = len(self._offset)
if count <= dimension:
return None
largest = np.max(np.abs(fitness))
quality = fitness / largest if largest else fitness
spread = np.ptp(quality)
weights = np.maximum((quality - quality.min()) / spread, 1. / count) if spread else np.ones(count)
weights /= weights.sum()
mean = weights @ embeddings
centered = embeddings - mean
_, singular, vectors = np.linalg.svd(centered * np.sqrt(weights)[:, None], full_matrices=False)
tolerance = np.finfo(float).eps * max(centered.shape) * singular[0]
if singular[dimension - 1] <= tolerance:
return None
basis = vectors[:dimension]
# Fix the sign of each axis for consistent interpretation and replay.
pivots = np.argmax(np.abs(basis), axis=1)
basis *= np.sign(basis[np.arange(dimension), pivots])[:, None]
low, high = np.quantile(centered @ basis.T, [0.05, 0.95], axis=0)
scale = 2. / np.maximum(high - low, 1e-6)
fitted = copy(self)
fitted._projection = scale[:, None] * basis
fitted._offset = -1 - scale * low - fitted._projection @ mean
return fitted
## @brief AutoQD's final native grid, fitted descriptor, and evaluation accounting.
[docs]
@dataclass(frozen=True)
class AutoQDResult:
"""Rollout and boundary counts describe valid recorded evaluations.
Attempts include callbacks that failed or returned invalid values.
Rebuilds and skipped rebuilds count scheduled descriptor updates.
"""
archive: Grid
projector: OccupancyDescriptor
attempts: int
failures: int
rollouts: int
trajectory_steps: int
boundary_evaluations: int
rebuilds: int
skipped_rebuilds: int
def _feedback(archive, fitness, descriptor):
descriptor = tuple(map(float, descriptor))
scores = ScoresDict()
for labels, values in ((archive.fitness_score_names, (fitness,)),
(archive.features_score_names, descriptor)):
for name, value in zip(labels, values):
if scores.setdefault(name, value) != value:
raise ValueError(f"Conflicting measurements for score {name!r}.")
return (fitness,), descriptor, scores
def _rebuild(archive, projector, embeddings):
"""Prepare a replacement grid without mutating the previous archive or its candidates."""
fresh = Grid(shape=archive.shape, features_domain=archive.features_domain,
fitness_domain=archive.fitness_domain, fitness_weights=archive.fitness_weights,
fitness_score_names=archive.fitness_score_names, features_score_names=archive.features_score_names,
capacity=archive.capacity, storage_type=type(archive.items), name=archive.name)
for elite in archive:
measured = archive.get_ind_fitness(elite).values[0]
features, _ = projector._project(embeddings[elite.name])
fitness, descriptors, scores = _feedback(fresh, measured, features)
fresh.add(Individual(elite, name=elite.name, fitness=Fitness(fitness, weights=(1.,)),
features=Features(descriptors), scores=scores))
return fresh
## @brief Run AutoQD with numeric trajectories and the optional CMA-MAE backend.
[docs]
def autoqd_search(evaluate, archive, *, budget, x0, sigma0, threshold_min, trajectory_width,
batch_size=16, ind_domain=None, learning_rate=0.01, embedding_dim=128, bandwidth=1.,
gamma=0.99, update_interval=10, seed=0):
"""Search for high-performing policies with trajectory-derived descriptors.
:param evaluate: Callable taking a numeric genome tuple and a per-attempt
seed. Return (fitness, trajectories), with one or more arrays of
state-action rows. Fitness is maximized.
:param archive: Empty parentless one-elite Grid with feature bounds
[-1.2, 1.2] on every axis and a domain for one maximizing objective.
:param budget: Hard budget in attempted candidate calls.
:param x0: Initial CMA center with at least two real coordinates.
:param sigma0: Initial step size for CMA-MAE and its restarts.
:param threshold_min: Initial CMA-MAE threshold in raw quality units.
:param trajectory_width: Number of state-action coordinates per step.
:param batch_size: CMA population size. The last batch may be partial.
:param ind_domain: Optional common lower and upper genome bounds.
:param learning_rate: CMA-MAE threshold update rate.
:param embedding_dim: Number of random Fourier features.
:param bandwidth: Gaussian kernel width in the caller's fixed input units.
:param gamma: Discount applied within trajectories.
:param update_interval: Full generations between descriptor updates. None
keeps the initial projection for a comparison at fixed coordinates.
:param seed: Root seed for independent descriptor, evaluator, and emitter streams.
:returns: AutoQDResult with the last grid, usable projector, and counts.
"""
if not callable(evaluate):
raise TypeError("evaluate must be callable.")
_validate_grid(archive)
limits = ((-_MEASURE_LIMIT, _MEASURE_LIMIT),) * len(archive.shape)
if type(archive) is not Grid or tuple(map(tuple, archive.features_domain)) != limits:
raise ValueError("Use a rectangular Grid with descriptor bounds [-1.2, 1.2] on every axis.")
if archive.fitness_weights is not None and tuple(archive.fitness_weights) != (1.,):
raise ValueError("Use an unweighted maximizing objective (fitness_weights=(1.,)).")
budget = _positive_int(budget, "budget")
batch_size = _positive_int(batch_size, "batch_size")
if update_interval is not None:
update_interval = _positive_int(update_interval, "update_interval")
features_seed, evaluation_seed, emitters_seed = np.random.SeedSequence(seed).spawn(3)
rng = np.random.default_rng(evaluation_seed)
emitters = np.random.default_rng(emitters_seed)
projector = OccupancyDescriptor(trajectory_width, len(archive.shape), embedding_dim=embedding_dim,
bandwidth=bandwidth, gamma=gamma, seed=features_seed)
def emitter(grid, center, remaining):
return CMAMAE(grid, remaining, center, sigma0, batch_size, threshold_min, ind_domain=ind_domain,
learning_rate=learning_rate, seed=int(emitters.integers(2**32)),
optimisation_task="maximisation")
search = emitter(archive, x0, budget)
attempts = failures = rollouts = steps = boundary = rebuilds = skipped = full_batches = 0
embeddings = {}
while attempts < budget:
candidates = search.ask_batch(min(batch_size, budget - attempts))
feedback = []
for candidate in candidates:
attempts += 1
candidate.name = str(attempts)
try:
fitness, trajectories = evaluate(tuple(candidate), int(rng.integers(2**32)))
if (not isinstance(fitness, Real) or not isfinite(fitness)
or not archive.in_bounds((fitness,), archive.fitness_domain)):
raise ValueError("Fitness must be finite and within the archive's fitness domain.")
embedding, episodes, length = projector._embed(trajectories)
descriptor, hit_boundary = projector._project(embedding)
result = _feedback(archive, float(fitness), descriptor)
except Exception as error:
warnings.warn(f"AutoQD evaluation failed: {error}", stacklevel=2)
feedback.append(None)
failures += 1
continue
feedback.append(result)
embeddings[candidate.name] = embedding
rollouts += episodes
steps += length
boundary += hit_boundary
search.tell_batch(feedback)
embeddings = {elite.name: embeddings[elite.name] for elite in archive}
if len(candidates) < batch_size:
continue
full_batches += 1
if update_interval is None or full_batches % update_interval:
continue
try:
values = np.asarray([embeddings[elite.name] for elite in archive])
scores = np.asarray([archive.get_ind_fitness(elite).values[0] for elite in archive])
fitted = projector._fitted(values, scores)
if fitted is None:
skipped += 1
continue
fresh = _rebuild(archive, fitted, embeddings)
if attempts < budget:
search = emitter(fresh, list(fresh.best), budget - attempts)
except (ValueError, IndexError, KeyError, TypeError, RuntimeError, np.linalg.LinAlgError) as error:
warnings.warn(f"AutoQD descriptor update failed: {error}", stacklevel=2)
skipped += 1
continue
projector, archive = fitted, fresh
embeddings = {elite.name: embeddings[elite.name] for elite in archive}
rebuilds += 1
return AutoQDResult(archive, projector, attempts, failures, rollouts, steps, boundary, rebuilds, skipped)