Source code for qdpy.algorithms.cosine_elites

# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Cosine-kernel MAP-Elites for evolving complementary predictive models.
# @see https://doi.org/10.1007/978-3-031-29573-7_6

"""Rebuild an elite map in a prediction space fitted to symmetric reference points."""

from dataclasses import dataclass
from math import isfinite

import numpy as np

from qdpy.containers import Grid
from qdpy.phenotype import Features, Fitness, Individual
from ._population import _attempt_budget, _finite_vector
from .modern import _positive_int

__all__ = ["CosineMAPElites", "CosineElitesStats"]


def _unit_rows(points):
    scale = np.max(np.abs(points), axis=1, keepdims=True)
    scaled = np.divide(points, scale, out=np.zeros_like(points), where=scale > 0.)
    norms = np.linalg.norm(scaled, axis=1, keepdims=True)
    return np.divide(scaled, norms, out=np.zeros_like(scaled), where=norms > 0.)


def _cosine_projection(predictions, targets, alpha, dimensions):
    with np.errstate(over="ignore", invalid="ignore"):
        toward = (1. - alpha) * targets + alpha * predictions
        reflected = (1. + alpha) * targets - alpha * predictions
    references = np.vstack((toward, reflected))
    if not np.isfinite(references).all():
        raise ValueError("Reference predictions overflowed. Rescale the training targets.")
    references = _unit_rows(references)
    center = references.mean(axis=0)
    # The cosine kernel is the linear kernel on unit rows. Thin SVD
    # avoids the centered reference-by-reference Gram matrix.
    _, singular, directions = np.linalg.svd(references - center, full_matrices=False)
    tolerance = np.finfo(float).eps * max(references.shape) * max(1., singular[0])
    selected = directions[:min(dimensions, np.count_nonzero(singular > tolerance))]
    projected = (_unit_rows(predictions) - center) @ selected.T
    return np.pad(projected, ((0, 0), (0, dimensions - projected.shape[1])))


## @brief Count model measurements and archive rebuilds.
[docs] @dataclass(frozen=True) class CosineElitesStats: """Count attempted fits, failed evaluations, and completed archive projections.""" evaluations: int failures: int rebuilds: int
## @brief Fit cosine-kernel PCA over symmetric prediction references and retain one elite per cell.
[docs] class CosineMAPElites: """Implement the semantic search of Zhang et al. with caller-defined model encodings. Fit a cosine-kernel projection using symmetric reference predictions around the target vector. Preserve the best fraction of offspring and incumbents before rebuilding the archive in the new coordinates. Evaluators should provide out-of-fold or other training-only predictions. Use held-out observations only for final comparison. :param targets: Supervised target vector in evaluator prediction order. :param sample: Callable (rng) returning a model genome iterable. :param mutate: Callable (genome, rng) returning an offspring genome. :param crossover: Optional callable (genome, donor, rng) returning a recombinant genome. :param crossover_probability: Probability of crossing before mutation when supplied. :param shape: Number of cells along each projected axis. :param population_size: Initial sample and offspring batch size. :param alpha: Reference displacement along the target-to-prediction vector. :param retain_fraction: Fraction of the merged pool considered for the new archive. :param maximize: Compare larger fitness when True and smaller fitness otherwise. :param seed: Seed for parent selection, variation, and model evaluation. """ def __init__(self, targets, *, sample, mutate, crossover=None, crossover_probability=.5, shape=(8, 8), population_size=32, alpha=.1, retain_fraction=.5, maximize=False, seed=0): self._targets = np.asarray(_finite_vector(targets, "Training targets")) self._shape = tuple(_positive_int(size, "shape") for size in shape) if not self._shape or not 0 < alpha <= 1 or not 0 < retain_fraction <= 1 or not 0 <= crossover_probability <= 1: raise ValueError("Use a nonempty shape, valid probabilities, and positive alpha and retain_fraction.") if not callable(sample) or not callable(mutate) or (crossover is not None and not callable(crossover)): raise TypeError("Provide callable variation functions.") self._size = _positive_int(population_size, "population_size") self._sample, self._mutate, self._crossover = sample, mutate, crossover self._probability = crossover_probability self._alpha, self._fraction, self._direction = alpha, retain_fraction, 1. if maximize else -1. self._variation, self._evaluation = map(np.random.default_rng, np.random.SeedSequence(seed).spawn(2)) self._archive = self._grid(((-1., 1.),) * len(self._shape)) self._children = [] self._pending = self._evaluations = self._failures = self._rebuilds = 0 def _grid(self, bounds): return Grid(shape=self._shape, features_domain=bounds, fitness_domain=((-np.inf, np.inf),), fitness_weights=(self._direction,)) @property def archive(self): """Return the native Grid from the most recent fit. Its geometry can change at a rebuild.""" return self._archive @property def stats(self): """Return model evaluation and archive rebuild counts.""" return CosineElitesStats(self._evaluations, self._failures, self._rebuilds) def _genome(self): if not self._archive: return tuple(self._sample(self._variation)) parent = tuple(self._archive[int(self._variation.integers(len(self._archive)))]) if self._crossover is not None and self._variation.random() < self._probability: donor = tuple(self._archive[int(self._variation.integers(len(self._archive)))]) parent = tuple(self._crossover(parent, donor, self._variation)) return tuple(self._mutate(parent, self._variation)) def _rebuild(self): if self._children: previous = [(tuple(row), row.fitness.values[0], row.scores["predictions"]) for row in self._archive] pool = previous + self._children if previous: pool.sort(key=lambda row: -self._direction * row[1]) pool = pool[:max(1, int(len(pool) * self._fraction))] predictions = np.asarray([row[2] for row in pool]) points = _cosine_projection(predictions, self._targets, self._alpha, len(self._shape)) bounds = [(float(lo), float(hi)) if hi - lo > np.finfo(float).eps else (-2., 2.) for lo, hi in zip(points.min(axis=0), points.max(axis=0))] archive = self._grid(bounds) for (genome, fitness, semantic), point in zip(pool, points): row = Individual(genome, fitness=Fitness((fitness,), weights=(self._direction,)), features=Features(tuple(point))) row.scores["predictions"] = semantic archive.add(row) self._archive = archive self._rebuilds += 1 self._children.clear() self._pending = 0 ## @brief Evaluate and project model batches on the fixed training panel. # @param evaluate Callable (genome, seed) returning (fitness, predictions) or None. # @param budget Additional attempted model evaluations. # @return Cumulative CosineElitesStats.
[docs] def run(self, evaluate, budget): """Retain any incomplete batch so a later call continues the same trajectory.""" budget = _attempt_budget(budget) if self._pending == self._size: self._rebuild() for _ in range(budget): genome = self._genome() self._evaluations += 1 result = evaluate(genome, int(self._evaluation.integers(2**32))) if result is None: self._failures += 1 else: fitness, predictions = result if not isfinite(fitness): raise ValueError("Model fitness must be finite.") semantic = _finite_vector(predictions, "Predictions", len(self._targets)) self._children.append((genome, float(fitness), semantic)) self._pending += 1 if self._pending == self._size: self._rebuild() return self.stats
## @brief Average final elite predictions on a new dataset. # @param predict Callable taking a genome and returning predictions on held-out data. # @param size Optional maximum number of members, selected by training fitness. # @return One ensemble prediction per held-out observation.
[docs] def predict(self, predict, *, size=None): """Keep held-out predictions outside the evolution loop.""" if not self._archive: raise RuntimeError("Fit at least one nonempty model batch before predicting.") members = tuple(self._archive) if size is not None: members = sorted(members, key=lambda row: -self._direction * row.fitness.values[0]) members = members[:_positive_int(size, "size")] predictions = [_finite_vector(predict(tuple(row)), "Held-out predictions") for row in members] if len({len(row) for row in predictions}) != 1: raise ValueError("Every ensemble member must predict the same held-out observations.") return np.sum(np.asarray(predictions) / len(members), axis=0)