Source code for qdpy.algorithms.me_gide

# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Gradient-informed MAP-Elites on categorical genomes.

"""Guide categorical proposals with derivatives of a one-hot relaxation."""

import numpy as np
from scipy.special import entr, softmax

from qdpy.base import registry
from qdpy.containers import CVTGrid, Grid
from .differentiable import GradientEvaluation, _gradient_basis
from .modern import _FixedGeneration, _positive_int

__all__ = ["MEGIDE"]


def _flip_probabilities(deltas, entropy_fraction):
    deltas = np.asarray(deltas, dtype=float)
    uniform = np.full(len(deltas), 1. / len(deltas))
    if entropy_fraction == 1:
        return uniform
    maxima = deltas == deltas.max()
    target = entropy_fraction * np.log(len(deltas))
    if target <= np.log(maxima.sum()):
        return maxima / maxima.sum()

    # Centre at the maximum and search log inverse temperature for stability.
    costs = deltas.max() - deltas
    positive = costs[costs > 0]
    low = -np.log(positive.max()) - 40
    high = -np.log(positive.min()) + 40
    log_cost = np.log(positive)
    logits = np.zeros_like(costs)
    for _ in range(48):
        middle = (low + high) / 2
        logits[~maxima] = -np.exp(np.clip(log_cost + middle, -745, 700))
        probabilities = softmax(logits)
        if entr(probabilities).sum() > target:
            low = middle
        else:
            high = middle
    return probabilities


## @brief Search a categorical genome with entropy-controlled, gradient-informed edits.
[docs] @registry.register class MEGIDE(_FixedGeneration): """MAP-Elites with the Gradient-Informed Discrete Emitter. Return a :class:`GradientEvaluation` for each integer candidate. Its Jacobian has rows for the objective followed by the descriptors, and columns for adjacent one-hot blocks of the configured category counts. Each call supplies the exact discrete measurements and derivatives of a caller-provided smooth relaxation at that one-hot point. Derivatives are cached for retained elites, so use a fixed evaluator throughout a run. The entropy is controlled separately for each proposal. Like the paper's softmax, each current category is included in its block and may yield an unchanged proposal. :param container: Best-only single-objective Grid or CVTGrid. :param budget: Number of candidate calls, including the initialization. :param nvec: Sequence of positive category counts, with at least two alternatives in one coordinate. Categories are zero-indexed. :param batch_size: Number of candidates selected from a frozen repertoire. :param entropy_fraction: Desired entropy as a fraction of uniform entropy. :param seed: Optional seed for initialization, parent sampling and edits. """ _requires_proposed_genome = True def __init__(self, container, budget, nvec, batch_size=32, *, entropy_fraction=.5, seed=None, **kwargs): if type(container) not in (Grid, CVTGrid) or container.max_items_per_bin != 1 or len(container.fitness_domain) != 1: raise ValueError("MEGIDE requires a best-only single-objective Grid or CVTGrid.") self.nvec = tuple(_positive_int(n, "category count") for n in nvec) if not self.nvec or max(self.nvec) < 2 or not 0 <= entropy_fraction <= 1: raise ValueError("Use a mutable categorical genome and entropy_fraction in [0, 1].") self.entropy_fraction, self.seed = entropy_fraction, seed self._offsets = np.cumsum((0, *self.nvec)) self._blocks = np.repeat(np.arange(len(self.nvec)), self.nvec) self._bases = {} kwargs.setdefault("optimisation_task", container.fitness_weights) super().__init__(container, _positive_int(budget, "budget"), batch_size=_positive_int(batch_size, "batch_size"), dimension=len(self.nvec), **kwargs) def reinit(self): """Reset accounting and proposals while preserving live elite gradients.""" super().reinit() self._rng = np.random.default_rng(self.seed) self._new_bases = {} self._parents = () def _start_fixed_batch(self, size): super()._start_fixed_batch(size) self._bases = {id(ind): self._bases[id(ind)] for ind in self.container if id(ind) in self._bases} self._parents = tuple(self._bases.values()) def _clear_generation(self): super()._clear_generation() self._new_bases.clear() self._parents = () def _internal_ask(self, base_ind): if not self._parents: base_ind[:] = self._rng.integers(self.nvec).tolist() return base_ind entry, basis = self._parents[self._rng.integers(len(self._parents))] parent = tuple(entry) weights = self._rng.normal(size=basis.shape[0]) weights[0] = abs(weights[0]) gradient = weights @ basis deltas = gradient - gradient[self._offsets[:-1] + parent][self._blocks] edit = self._rng.choice(len(deltas), p=_flip_probabilities(deltas, self.entropy_fraction)) block = self._blocks[edit] base_ind[:] = parent base_ind[block] = int(edit - self._offsets[block]) return base_ind def _tell_evaluation_result(self, individual, result, elapsed, verbose): if not isinstance(result, GradientEvaluation): raise TypeError("The MEGIDE evaluator must return a GradientEvaluation.") descriptors = np.asarray(result.descriptors, dtype=float) count = len(self.container.features_domain) jacobian = np.asarray(result.jacobian, dtype=float) if (descriptors.shape != (count,) or not np.isfinite(descriptors).all() or jacobian.shape != (count + 1, self._offsets[-1]) or not np.isfinite(jacobian).all()): raise ValueError("MEGIDE requires finite descriptors and one Jacobian column per category.") self.tell(individual, fitness=(float(result.fitness),), features=tuple(descriptors), elapsed=elapsed, verbose=verbose) self._new_bases[id(individual)] = _gradient_basis(jacobian, self._fitness_weights[0]) return True def _commit_generation(self, evaluated): offered = {} for slot, individual in enumerate(evaluated): if individual is None: continue cell = self.container.index_grid(individual) if self._offer_to_grid(individual, cell): offered[id(individual)] = slot admitted = set() for individual in self.container: identifier = id(individual) if identifier in offered: self._bases[identifier] = (individual, self._new_bases[identifier]) admitted.add(offered[identifier]) self._bases = {id(ind): self._bases[id(ind)] for ind in self.container if id(ind) in self._bases} return admitted