Source code for qdpy.algorithms.autoqd

# 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.
[docs] def transform(self, trajectories): """Return calibrated descriptors clipped to the grid limits.""" values, _ = self._project(self.embed(trajectories)) return values
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.