Source code for qdpy.algorithms.differentiable

# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Gradient arborescence with annealed archive improvement.

"""CMA-MAEGA with separate centre and offspring evaluation phases."""

from dataclasses import dataclass
from math import isfinite
from typing import Sequence
import warnings

import numpy as np

from qdpy.base import registry
from .constrained import _validate_grid
from .modern import CMAMAE

__all__ = ["GradientEvaluation", "CMAMAEGA", "CMAMEGA"]


## @brief Raw objective, descriptors, and their derivatives at a search point.
[docs] @dataclass(frozen=True) class GradientEvaluation: """Measurements from a single gradient evaluation. The Jacobian has one row for the objective followed by a row for each descriptor. Columns follow the order of the genome coordinates. """ fitness: float descriptors: Sequence[float] jacobian: np.ndarray
def _gradient_basis(jacobian, objective_weight): # Scale rows before taking norms so very large or small derivatives # retain their direction without overflow or underflow. scale = np.max(np.abs(jacobian), axis=1, keepdims=True) rows = np.divide(jacobian, scale, out=np.zeros_like(jacobian), where=scale != 0) rows[0] *= np.sign(objective_weight) norms = np.linalg.norm(rows, axis=1, keepdims=True) return np.divide(rows, norms, out=rows, where=norms != 0) ## @brief Adapt coefficients on a basis of objective and descriptor gradients.
[docs] @registry.register class CMAMAEGA(CMAMAE): """CMA-MAE with a gradient arborescence over the current centre. Install the optional ``cma`` extra. Each centre evaluation consumes one candidate slot. Subsequent offspring use the ordinary QDpy evaluator. The centre and offspring batches each emit an iteration callback. :param gradient_evaluate: Callable returning a GradientEvaluation. :param step_size: Multiplier for the rank-weighted centre displacement. :param sigma0: Initial step size in gradient coefficient coordinates. :param kwargs: CMA-MAE options, including the reporting grid, bounds, budget, initial point, batch size, threshold and archive learning rate. """ def __init__(self, container, budget, x0, sigma0, batch_size, threshold_min, *, gradient_evaluate, step_size=1.0, **kwargs): if not callable(gradient_evaluate): raise TypeError("gradient_evaluate must be callable.") if not 0 < step_size < np.inf: raise ValueError("step_size must be finite and positive.") self.gradient_evaluate = gradient_evaluate self.step_size = step_size super().__init__(container, budget, x0, sigma0, batch_size, threshold_min, **kwargs) def reinit(self): """Reset the centre, coefficient strategy, and gradient evaluation count.""" super().reinit() self._centre = self.x0.copy() self._gradient_evaluations = 0 self._basis = None self._centre_phase = False @property def centre(self): """Return a copy of the current gradient search point.""" return self._centre.copy() @property def gradient_evaluations(self): """Number of attempted centre evaluations, including failed calls.""" return self._gradient_evaluations def _fixed_batch_plan(self, size, evaluate, packed): if self._basis is None: return 1, self.gradient_evaluate, False return size, evaluate, packed ## @brief Issue the current centre for a gradient evaluation.
[docs] def ask_dqd(self): """Return the centre, ready for a report through ``tell_dqd()``.""" if self._basis is not None: raise RuntimeError("Complete an offspring batch before requesting another gradient.") return super().ask_batch(1)[0]
## @brief Report the gradient evaluation for the pending centre.
[docs] def tell_dqd(self, result): """Report a GradientEvaluation or ``None`` for a failed centre call.""" if not self._pending_size or not self._centre_phase: raise RuntimeError("Use ask_dqd() before tell_dqd().") super().tell_batch([result])
[docs] def ask_batch(self, size=None): """Issue offspring after a successful centre evaluation.""" if self._basis is None: raise RuntimeError("Use ask_dqd() and tell_dqd() before asking for offspring.") return super().ask_batch(size)
[docs] def tell_batch(self, results): """Commit the pending offspring in proposal order.""" if self._pending_size and self._centre_phase: raise RuntimeError("Use tell_dqd() to report a centre evaluation.") super().tell_batch(results)
def _sample_vectors(self, size): self._centre_phase = self._basis is None if self._centre_phase: return [self._centre.copy()] if self._strategy is None: self._strategy = self._new_strategy(np.zeros(len(self._basis)), bounded=False) self._coefficients = self._strategy.ask(number=size) vectors = self._centre + np.asarray(self._coefficients) @ self._basis return self._bounded(vectors) def _bounded(self, vectors): return vectors if self.ind_domain is None else np.clip(vectors, *self.ind_domain) def _centre_payload(self, result): if not isinstance(result, GradientEvaluation): raise TypeError("The centre evaluator must return a GradientEvaluation.") count = len(self.container.features_domain) jacobian = np.asarray(result.jacobian, dtype=float) descriptors = np.asarray(result.descriptors, dtype=float) if jacobian.shape != (count + 1, self.dimension) or not np.all(np.isfinite(jacobian)): raise ValueError("The centre Jacobian must be finite and match the objective and descriptors.") if descriptors.shape != (count,) or not np.all(np.isfinite(descriptors)) or not isfinite(result.fitness): raise ValueError("The centre fitness and descriptor vector must be finite and match the grid.") self._basis = _gradient_basis(jacobian, self._fitness_weights[0]) return (result.fitness,), descriptors def _receive_fixed_batch(self, records, verbose, batch_start_time): if self._centre_phase: candidate, result, elapsed = records[0] self._gradient_evaluations += 1 if result is not None: try: result = self._centre_payload(result) except (TypeError, ValueError, OverflowError) as error: warnings.warn(f"Invalid gradient evaluation: {error}", stacklevel=2) result = None records = [(candidate, result, elapsed)] super()._receive_fixed_batch(records, verbose, batch_start_time) def _restart_arborescence(self): self._strategy = None self._centre = np.asarray(self._restart_center(), dtype=float).copy() def _clear_generation(self): super()._clear_generation() self._coefficients = () def _commit_generation(self, evaluated): admitted = self._update_annealed_archive(evaluated) if self._centre_phase: if evaluated[0] is None: self._basis = None self._restart_arborescence() return admitted if len(evaluated) == self.batch_size and any(ind is not None for ind in evaluated): order = self._adapt_strategy(self._coefficients) selected = order[:self._strategy.sp.mu] selected = selected[np.isfinite(self._gains[selected])] if len(selected): weights = np.asarray(self._strategy.sp.weights[:len(selected)]) moves = self._vectors[selected] - self._centre self._centre = self._bounded(self._centre + self.step_size * np.average(moves, axis=0, weights=weights)) if self._strategy.stop() or not np.any(self._gains > 0): self._restart_arborescence() self._basis = None return admitted
## @brief Adapt gradient coefficient samples by best-only archive improvement. # @see https://arxiv.org/abs/2106.03894
[docs] @registry.register class CMAMEGA(CMAMAEGA): """Analytic CMA-MEGA, with Adam for the centre update by default. Each branch generation uses one measured Jacobian at the centre. New cells rank above same-cell improvements. Rejected offspring rank below both. Offspring use the ordinary QDpy evaluator. :param container: Empty best-only scalar Grid or CVTGrid without parents. :param budget: Total candidate calls, including centre Jacobians. :param x0: Starting point in genome coordinates. :param sigma0: Initial standard deviation in coefficient space. :param batch_size: Number of candidate branches per Jacobian. :param gradient_evaluate: Callable returning a GradientEvaluation. :param step_size: Learning rate for the centre update. :param centre_optimizer: "adam" or the paper's plain "gradient" update. :param kwargs: Native algorithm settings, including ind_domain and seed. """ def __init__(self, container, budget, x0, sigma0, batch_size, *, gradient_evaluate, step_size=.05, centre_optimizer="adam", **kwargs): _validate_grid(container) if container.parents: raise ValueError("Use an empty parentless best-only archive for CMA-MEGA.") if centre_optimizer not in ("adam", "gradient"): raise ValueError("centre_optimizer must be 'adam' or 'gradient'.") self.centre_optimizer = centre_optimizer if container.fitness_weights is not None: kwargs.setdefault("optimisation_task", tuple(container.fitness_weights)) super().__init__(container, budget, x0, sigma0, batch_size, 0., gradient_evaluate=gradient_evaluate, step_size=step_size, **kwargs) def _reset_moments(self): self._first = np.zeros_like(self.x0) self._second = np.zeros_like(self.x0) self._adam_steps = 0 def reinit(self): """Reset the coefficient distribution, centre, and Adam state.""" super().reinit() self._reset_moments() def _restart_arborescence(self): self._strategy = None self._centre = self._bounded(np.asarray(self._search_rng().choice(list(self.container)) if self.container else self.x0, dtype=float)).copy() self._reset_moments() def _move_centre(self, direction): if self.centre_optimizer == "adam": self._adam_steps += 1 self._first = .9 * self._first + .1 * direction self._second = .999 * self._second + .001 * direction ** 2 first = self._first / (1. - .9 ** self._adam_steps) second = self._second / (1. - .999 ** self._adam_steps) direction = first / (np.sqrt(second) + 1e-8) self._centre = self._bounded(self._centre + self.step_size * direction) @property def search_elites(self): """Return the best measured candidate in each occupied cell.""" return {cell: front[0] for cell, front in self.container.solutions.items() if front} def threshold(self, cell): """Return signed incumbent fitness, or negative infinity for an empty cell.""" front = self.container.solutions[cell] return np.sign(self._fitness_weights[0]) * self.container.get_ind_fitness(front[0]).values[0] if front else -np.inf def _commit_generation(self, evaluated): self._gains = np.full(len(evaluated), -np.inf) statuses = np.zeros(len(evaluated), dtype=int) admitted = set() direction = np.sign(self._fitness_weights[0]) for index, candidate in enumerate(evaluated): if candidate is None: continue cell = self.container.index_grid(candidate) front = self.container.solutions[cell] value = direction * self.container.get_ind_fitness(candidate).values[0] new_cell = not front self._gains[index] = value if new_cell else value - self.threshold(cell) if self._offer_to_grid(candidate, cell): statuses[index] = 2 if new_cell else 1 admitted.add(index) if self._centre_phase: if evaluated[0] is None: self._basis = None self._restart_arborescence() return admitted if len(evaluated) == self.batch_size: if admitted: order = np.lexsort((-self._gains, -statuses)) losses = np.empty(len(order), dtype=int) losses[order] = np.arange(len(order)) selected = order[:self._strategy.sp.mu] selected = selected[np.isfinite(self._gains[selected])] if len(selected): weights = np.asarray(self._strategy.sp.weights[:len(selected)]) moves = self._vectors[selected] - self._centre self._move_centre(np.average(moves, axis=0, weights=weights)) self._strategy.tell(self._coefficients, losses) if not admitted or self._strategy.stop(): self._restart_arborescence() self._basis = None return admitted