Source code for qdpy.algorithms.edo_cs

# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Evolutionary diversity optimization with clustering-based selection.
# @see https://openreview.net/pdf?id=74x5BXs4bWD

"""Black-box EDO-CS with a bounded behavior archive and UCB-controlled ES."""

from dataclasses import dataclass
from math import dist, fsum, isfinite

import numpy as np
from sklearn.cluster import KMeans

from ._population import _attempt_budget, _finite_vector
from .modern import _bounds, _positive_int

__all__ = ["EDOCS", "EDOCSPolicy", "EDOCSStats"]


## @brief The measured parameters, return, and descriptor of an archived policy.
[docs] @dataclass(frozen=True) class EDOCSPolicy: """Archive only measurements from initialization and evaluated ES centers.""" genome: tuple[float, ...] reward: float descriptor: tuple[float, ...]
## @brief Track policy and perturbation evaluation costs separately.
[docs] @dataclass(frozen=True) class EDOCSStats: """Report attempts, failed slots, completed outer rounds, and UCB feedback counts.""" policy_evaluations: int perturbation_evaluations: int failures: int rounds: int arm_counts: tuple[int, ...] @property def evaluations(self): """Return total evaluator calls.""" return self.policy_evaluations + self.perturbation_evaluations
## @brief Cluster live descriptors and independently update each representative with ES.
[docs] class EDOCS: """Implement EDO-CS over numeric policy vectors and a seeded evaluator. Cluster the current archive with k-means at each round. Always breed the best archived policy, then sample uniformly among the top policies of each other cluster. Estimate raw ES gradients from Gaussian probes against a frozen archive. Use UCB1 on each diversity weight's measured improvement in return. Each accepted offspring is the newest archive entry for FIFO capacity enforcement. :param dimension: Number of parameters in each policy vector. :param archive_size: Number of random initialization attempts and maximum live policies. :param clusters: Maximum number of behavioral clusters. :param top_per_cluster: Number of high-reward policies eligible in each other cluster. :param sample: Optional callable (rng) returning initial parameters. The default is uniform within ind_domain or [-1, 1] if unbounded. :param ind_domain: Optional shared finite bounds for clipped ES. :param novelty_neighbors: Number of nearest archived policies in the ES novelty term. :param novelty_threshold: Descriptor radius within which reward decides replacement. :param probes: Independent Gaussian probes per ES update. :param es_steps: ES updates per selected policy before evaluating its final center. :param sigma: Standard deviation of Gaussian perturbations. :param learning_rate: Step size of the raw ES gradient estimator. :param weights: Diversity weights made available as UCB arms. Pass a single value for a fixed-weight ablation. :param ucb_scale: Nonnegative scale of the confidence bonus. :param seed: Seed for initialization, selection, perturbations, and rollouts. """ def __init__(self, dimension, *, archive_size=32, clusters=5, top_per_cluster=2, sample=None, ind_domain=None, novelty_neighbors=10, novelty_threshold=.05, probes=16, es_steps=5, sigma=.05, learning_rate=.02, weights=(0., .5), ucb_scale=1., seed=0): self._dimension = _positive_int(dimension, "dimension") self._capacity = _positive_int(archive_size, "archive_size") self._clusters = _positive_int(clusters, "clusters") self._top = _positive_int(top_per_cluster, "top_per_cluster") self._neighbors = _positive_int(novelty_neighbors, "novelty_neighbors") self._probes = _positive_int(probes, "probes") self._steps = _positive_int(es_steps, "es_steps") self._weights = _finite_vector(weights, "Diversity weights") if (len(set(self._weights)) != len(self._weights) or any(not 0 <= w <= 1 for w in self._weights) or self._clusters > self._capacity or not 0 <= novelty_threshold < np.inf or not 0 < sigma < np.inf or not 0 < learning_rate < np.inf or not 0 <= ucb_scale < np.inf): raise ValueError("Use valid archive settings, distinct weights in [0, 1], and finite ES scales.") if sample is not None and not callable(sample): raise TypeError("sample must be callable.") self._sample = sample self._bounds = None if ind_domain is None else _bounds(ind_domain) self._threshold, self._sigma, self._rate, self._ucb = novelty_threshold, sigma, learning_rate, ucb_scale self._initial, self._selection, self._variation, self._evaluation = map( np.random.default_rng, np.random.SeedSequence(seed).spawn(4)) self._archive = [] self._arm_counts = np.zeros(len(self._weights), dtype=int) self._arm_means = np.zeros(len(self._weights)) self._initialized = self._policy_calls = self._probe_calls = self._failures = self._rounds = 0 self._descriptor_size = None @property def archive(self): """Return measured policies from oldest to newest.""" return tuple(self._archive) @property def stats(self): """Return cumulative attempts and counts of observed arm rewards.""" return EDOCSStats(self._policy_calls, self._probe_calls, self._failures, self._rounds, tuple(map(int, self._arm_counts))) @property def next_round_cost(self): """Return evaluator calls required by the next round, or zero if empty.""" distinct = len({row.descriptor for row in self._archive}) representatives = min(self._clusters, distinct) or min(1, len(self._archive)) return representatives * (self._steps * self._probes + 1) def _initial_genome(self): genome = (self._initial.uniform(*(self._bounds or (-1., 1.)), size=self._dimension) if self._sample is None else self._sample(self._initial)) vector = _finite_vector(genome, "Policy parameters", self._dimension) if self._bounds is not None and any(not self._bounds[0] <= value <= self._bounds[1] for value in vector): raise ValueError("Initial policy parameters lie outside ind_domain.") return vector def _measure(self, evaluate, genome, *, probe=False): self._probe_calls += int(probe) self._policy_calls += int(not probe) result = evaluate(tuple(map(float, genome)), int(self._evaluation.integers(2**32))) if result is None: self._failures += 1 return None reward, descriptor = result descriptor = _finite_vector(descriptor, "Behavior descriptor", self._descriptor_size) if not isfinite(reward): raise ValueError("Policy reward must be finite.") self._descriptor_size = len(descriptor) return EDOCSPolicy(tuple(map(float, genome)), float(reward), descriptor) def _representatives(self): rows = self._archive positions = np.asarray([row.descriptor for row in rows]) groups = min(self._clusters, len({row.descriptor for row in rows})) best = max(range(len(rows)), key=lambda i: rows[i].reward) if groups == 1: return (rows[best],) positions /= np.max(np.abs(positions)) or 1. labels = KMeans(n_clusters=groups, n_init=1, random_state=int(self._selection.integers(2**32))).fit_predict(positions) choices = [rows[best]] for label in np.unique(labels): if label != labels[best]: eligible = sorted(np.flatnonzero(labels == label), key=lambda i: -rows[i].reward)[:self._top] choices.append(rows[int(self._selection.choice(eligible))]) return tuple(choices) def _arm(self, scheduled): unmeasured = np.flatnonzero(scheduled == 0) if len(unmeasured): return int(unmeasured[0]) bonus = self._ucb * np.sqrt(np.log(max(1, scheduled.sum())) / scheduled) return int(np.argmax(self._arm_means + bonus)) def _novelty(self, row, reference): distances = sorted(dist(row.descriptor, old.descriptor) for old in reference)[:self._neighbors] novelty = fsum(value / len(distances) for value in distances) if not isfinite(novelty): raise ValueError("Novelty is outside the representable range. Rescale descriptors.") return novelty def _offspring(self, evaluate, parent, weight, reference): center = np.asarray(parent.genome) for _ in range(self._steps): noise = self._variation.standard_normal((self._probes, self._dimension)) candidates = center + self._sigma * noise if self._bounds is not None: candidates = np.clip(candidates, *self._bounds) if not np.isfinite(candidates).all(): raise ValueError("An ES probe overflowed. Rescale policy parameters or sigma.") rows = [self._measure(evaluate, candidate, probe=True) for candidate in candidates] if any(row is None for row in rows): continue utilities = np.array([row.reward for row in rows]) if weight: utilities = (1. - weight) * utilities + weight * np.array([ self._novelty(row, reference) for row in rows]) with np.errstate(over="ignore", invalid="ignore"): update = self._rate / self._sigma * ((utilities / self._probes) @ noise) improved = center + update if not np.isfinite(improved).all(): raise ValueError("The ES update overflowed. Rescale reward, descriptors, or ES settings.") center = improved if self._bounds is None else np.clip(improved, *self._bounds) return self._measure(evaluate, center) def _offer(self, row): if self._archive: distances = [dist(row.descriptor, old.descriptor) for old in self._archive] nearest = int(np.argmin(distances)) if distances[nearest] <= self._threshold: if row.reward > self._archive[nearest].reward: del self._archive[nearest] else: return self._archive.append(row) if len(self._archive) > self._capacity: del self._archive[0] ## @brief Measure initialization and as many complete outer rounds as the budget permits. # @param evaluate Callable (parameters, seed) returning (reward, descriptor) or None. # @param budget Maximum additional rollout attempts, including probes. # @return Cumulative EDOCSStats.
[docs] def run(self, evaluate, budget): """Reserve each whole round before updating archive or bandit state.""" remaining = _attempt_budget(budget) while remaining and (self._initialized < self._capacity or not self._archive): row = self._measure(evaluate, self._initial_genome()) if row is not None: self._archive.append(row) self._initialized += 1 remaining -= 1 while (cost := self.next_round_cost) and remaining >= cost: before = self._policy_calls + self._probe_calls reference = self.archive scheduled = self._arm_counts.copy() evaluated = [] for parent in self._representatives(): arm = self._arm(scheduled) scheduled[arm] += 1 child = self._offspring(evaluate, parent, self._weights[arm], reference) if child is not None: gain = child.reward - parent.reward if not isfinite(gain): raise ValueError("Policy reward improvement is outside the representable range.") evaluated.append((arm, child, gain)) for arm, child, gain in evaluated: self._offer(child) self._arm_counts[arm] += 1 count = self._arm_counts[arm] self._arm_means[arm] = self._arm_means[arm] * ((count - 1) / count) + gain / count remaining -= self._policy_calls + self._probe_calls - before self._rounds += 1 return self.stats