Source code for qdpy.algorithms.descriptor_cma

# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Density descent, dynamic archive refresh, and ES gradient arborescences.

"""Continuous black-box QD search with optional pycma strategies."""

from collections import deque
from dataclasses import dataclass
from functools import partial
import numpy as np
from scipy.spatial.distance import cdist
from scipy.special import logsumexp
from scipy.stats import rankdata

from qdpy.containers import Grid
from .differentiable import _gradient_basis
from .modern import _cma_strategy, _positive_int
from .task_search import _measure, _offer, _offer_with_age, _search_bounds, _validate_grid

__all__ = ["DDSResult", "DynamicCMAResult", "CMAMEGAESResult", "dds_kde",
           "dynamic_cma_me", "cma_mega_es"]


## @brief Live passive archive and density search accounting.
@dataclass(frozen=True)
class DDSResult:
    """Evaluator attempts, failed calls, and final descriptor reservoir size."""

    archive: Grid
    attempts: int
    failures: int
    reservoir_size: int


## @brief Dynamic archive and separately accounted evaluation phases.
@dataclass(frozen=True)
class DynamicCMAResult:
    """Search, change detection and refresh counts, including failed attempts."""

    archive: Grid
    offspring_attempts: int
    detection_attempts: int
    refresh_attempts: int
    failures: int
    detected_change_ticks: tuple[int, ...]
    incomplete_updates: int

    @property
    def attempts(self):
        """Return the complete evaluation cost of this run."""
        return self.offspring_attempts + self.detection_attempts + self.refresh_attempts


## @brief Live archive and counts for each arborescence evaluation phase.
@dataclass(frozen=True)
class CMAMEGAESResult:
    """Centre, perturbation, and offspring attempts, including failed calls."""

    archive: Grid
    centre_attempts: int
    perturbation_attempts: int
    offspring_attempts: int
    failures: int

    @property
    def attempts(self):
        """Return the complete evaluation cost of this run."""
        return self.centre_attempts + self.perturbation_attempts + self.offspring_attempts


def _settings(archive, evaluate, x0, sigma0, batch_size, budget, ind_domain, on_step):
    """Validate the shared archive, budget and CMA search domain."""
    try:
        import cma  # noqa: F401
    except ImportError as error:
        raise ImportError("This method needs the QDpy 'cma' extra.") from error
    _validate_grid(archive)
    if not callable(evaluate) or (on_step is not None and not callable(on_step)):
        raise TypeError("Supply a callable evaluator and, optionally, a callable step hook.")
    bounds = None if ind_domain is None else _search_bounds(ind_domain)
    center = np.array(x0, dtype=float, copy=True)
    if center.ndim != 1 or center.size < 2 or not np.isfinite(center).all():
        raise ValueError("x0 must be a finite vector with at least two coordinates.")
    if bounds is not None and not np.array_equal(center, np.clip(center, *bounds)):
        raise ValueError("x0 lies outside the genome bounds.")
    batch_size = _positive_int(batch_size, "batch_size")
    if batch_size < 2 or not 0 < sigma0 < np.inf:
        raise ValueError("Use a CMA batch of at least two and positive finite sigma0.")
    return center, bounds, batch_size, _positive_int(budget, "budget")


def _strategy(center, sigma, population, rng, bounds=None):
    return _cma_strategy(center, sigma, population, int(rng.integers(1, 2**32)), bounds)


def _worker(evaluate, genome):
    try:
        return evaluate(genome), None
    except Exception as error:
        return None, f"{type(error).__name__}: {error}"


def _unwrap(result, error):
    if error is not None:
        raise ValueError(error)
    return result


def _measure_group(archive, evaluate, vectors, executor):
    genomes = [tuple(map(float, vector)) for vector in vectors]
    if executor is None:
        return [_measure(archive, evaluate, (genome,), genome) for genome in genomes]
    responses = executor.map(partial(_worker, evaluate), genomes)
    return [_measure(archive, _unwrap, response, genome)
            for genome, response in zip(genomes, responses, strict=True)]


def _losses(order):
    losses = np.empty(len(order), dtype=int)
    losses[order] = np.arange(len(order))
    return losses


def _improvements(archive, measurements, *, ages=None, tick=None):
    """Rank new cells first, then improvements, then rejected candidates."""
    scores = []
    accepted = 0
    offer = _offer if ages is None else partial(_offer_with_age, last_touched=ages, step=tick)
    for measurement in measurements:
        if measurement is None or measurement[1] is None:
            scores.append((-1, 0.0))
            continue
        candidate, cell = measurement
        front = archive.solutions[cell]
        quality = archive.get_ind_fitness(candidate)
        direction = 1 if quality.weights[0] > 0 else -1
        value = quality.values[0]
        prior = archive.get_ind_fitness(front[0]).values[0] if front else 0.0
        improvement = direction * (value - prior)
        status = 1 if front else 2
        before = archive.nb_added
        offer(archive, measurement)
        if archive.nb_added == before:
            status = 0
        else:
            accepted += 1
        scores.append((status, improvement))
    return sorted(range(len(scores)), key=scores.__getitem__, reverse=True), accepted


def _restart_center(archive, fallback, rng):
    return np.asarray(archive[rng.integers(len(archive))]) if archive else fallback


def _negative_log_density(points, previous, bandwidth):
    """Rank Gaussian KDEs in log space so remote points retain separation."""
    if not len(previous):
        return np.zeros(len(points))
    result = np.empty(len(points))
    for start in range(0, len(points), 64):
        stop = start + 64
        squared = cdist(points[start:stop], previous, metric="sqeuclidean")
        with np.errstate(over="ignore"):
            scaled = (squared / bandwidth) / bandwidth
        result[start:stop] = -logsumexp(-0.5 * scaled, axis=1)
    return result


## @brief Guide CMA by a Gaussian KDE on a bounded reservoir of descriptors.
[docs] def dds_kde(archive, evaluate, *, x0, budget, bandwidth, reservoir_size=1024, sigma0=0.15, batch_size=16, ind_domain=(0, 1), seed=0, executor=None, on_step=None): """Run Density Descent Search with kernel density estimation. Each generation is ranked against the descriptor reservoir from earlier generations. Reuse the previous order to break equal densities. Offer measured solutions to a passive archive. Fitness and archive admission never enter CMA feedback. Valid measurements outside the archive's bounds still inform the density model. :param archive: Empty, parentless, best-only Grid or CVTGrid. :param evaluate: Callable taking an immutable genome and returning a singleton fitness vector and its descriptors. Use constant fitness for a pure diversity task. :param x0: Initial genome for CMA and its restarts. :param budget: Total attempted evaluations. :param bandwidth: Positive Gaussian bandwidth in descriptor units. :param reservoir_size: Maximum number of past descriptors to retain. :param sigma0: Initial CMA sampling scale in genome coordinates. :param batch_size: CMA population size. Commit a final partial batch to the passive archive and reservoir. :param ind_domain: Shared bounds, or None for unbounded search. :param seed: Private seed for CMA and uniform reservoir sampling. :param executor: Optional caller-owned executor with ordered map. :param on_step: Optional callback receiving the archive, iteration and evaluations. :returns: Passive archive and run accounting. """ if not 0 < bandwidth < np.inf: raise ValueError("KDE bandwidth must be finite and positive.") return _density_descent(archive, evaluate, x0, budget, reservoir_size, sigma0, batch_size, ind_domain, seed, executor, on_step, lambda points, previous, _: _negative_log_density(points, previous, bandwidth))
def _density_descent(archive, evaluate, x0, budget, reservoir_size, sigma0, batch_size, ind_domain, seed, executor, on_step, negative_log_density): """Rank valid candidates against an estimator using the previous descriptor reservoir.""" center, bounds, batch_size, budget = _settings( archive, evaluate, x0, sigma0, batch_size, budget, ind_domain, on_step) reservoir_size = _positive_int(reservoir_size, "reservoir_size") cma_seed, buffer_seed = np.random.SeedSequence(seed).spawn(2) rng, buffer_rng = np.random.default_rng(cma_seed), np.random.default_rng(buffer_seed) buffer = np.empty((min(reservoir_size, budget), len(archive.features_domain))) seen = failures = 0 strategy = None for iteration, start in enumerate(range(0, budget, batch_size), 1): size = min(batch_size, budget - start) if strategy is None or strategy.stop(): strategy = _strategy(center, sigma0, batch_size, rng, bounds) vectors = strategy.ask(number=size) measurements = _measure_group(archive, evaluate, vectors, executor) valid = [slot for slot, measure in enumerate(measurements) if measure is not None] failures += size - len(valid) if valid: descriptors = np.asarray([tuple(measurements[slot][0].features) for slot in valid]) density_ranks = np.argsort( -negative_log_density(descriptors, buffer[:min(seen, reservoir_size)], iteration), kind="stable") if size == batch_size: # Failures follow even a valid candidate with negligible density. order = [valid[item] for item in density_ranks] order.extend(slot for slot, measure in enumerate(measurements) if measure is None) strategy.tell(vectors, _losses(order)) for slot, descriptor in zip(valid, descriptors): _offer(archive, measurements[slot]) seen += 1 target = seen - 1 if seen <= reservoir_size else buffer_rng.integers(seen) if target < reservoir_size: buffer[target] = descriptor elif size == batch_size: strategy = None if on_step is not None: on_step(archive, iteration=iteration, evaluations=start + size) return DDSResult(archive, budget, failures, min(seen, reservoir_size)) def _refresh_replacees(archive, offspring, probe, probe_measurement, remeasure): """Stage one probe and all incumbent moves against the unchanged archive.""" pending = deque([probe]) for measurement in offspring: if measurement is not None and measurement[1] is not None: pending.extend(archive.solutions[measurement[1]]) refreshed = {} while pending: incumbent = pending.popleft() key = id(incumbent) if key in refreshed: continue fresh = probe_measurement if incumbent is probe else remeasure(incumbent) if fresh is None: return None refreshed[key] = fresh if fresh[1] is not None: pending.extend(archive.solutions[fresh[1]]) return refreshed ## @brief Revalidate stale incumbents before CMA-ME ranks a generation.
[docs] def dynamic_cma_me(archive, evaluate, *, x0, budget, sigma0=0.15, batch_size=16, ind_domain=(0, 1), seed=0, refresh=True, on_step=None): """Run Dynamic CMA-ME with oldest-elite detection and replacee refresh. A generation shares one tick, the number of attempts already spent when it starts. Probe the least recently checked elite, including with the final available call. If the probe changed, refresh occupied destinations and follow incumbent moves. Commit the updates together before ranking offspring by cell improvement. Failed or unfinished refreshes leave the archive untouched and restart the strategy. Only offspring from a full generation enter CMA feedback. :param archive: Empty, parentless, best-only Grid or CVTGrid. :param evaluate: Callable taking an immutable genome and a tick. Return a singleton fitness vector and its descriptors. :param x0: Initial genome used before the first archive admission. :param budget: All attempted evaluations, including probes and refreshes. :param sigma0: Initial CMA sampling scale. :param batch_size: CMA population size. :param ind_domain: Common bounds, or None for unbounded search. :param seed: Private CMA and restart seed. :param refresh: Enable detection and refresh. False runs static CMA-ME with the same improvement emitter and tick convention. :param on_step: Optional callback receiving the archive, iteration and evaluations. :returns: The live archive and counts per evaluation phase. """ center, bounds, batch_size, budget = _settings( archive, evaluate, x0, sigma0, batch_size, budget, ind_domain, on_step) if type(refresh) is not bool: raise ValueError("refresh must be a bool.") rng = np.random.default_rng(seed) strategy = None last_checked = {} offspring_count = probes = refresh_count = failures = incomplete = iteration = 0 detected = [] def used(): return offspring_count + probes + refresh_count while used() < budget: iteration += 1 tick = used() probe = fresh_probe = None changed = False if refresh and archive: probe = min(archive, key=lambda elite: last_checked[id(elite)]) genome = tuple(probe) probes += 1 fresh_probe = _measure(archive, evaluate, (genome, tick), genome) failures += fresh_probe is None if fresh_probe is not None: candidate = fresh_probe[0] changed = (candidate.fitness.values != probe.fitness.values or tuple(candidate.features) != tuple(probe.features)) if changed: detected.append(tick) size = min(batch_size, budget - used()) vectors = [] if size: if strategy is None or strategy.stop(): strategy = _strategy(_restart_center(archive, center, rng), sigma0, batch_size, rng, bounds) vectors = strategy.ask(number=size) offspring = [] for vector in vectors: genome = tuple(map(float, vector)) offspring_count += 1 measurement = _measure(archive, evaluate, (genome, tick), genome) offspring.append(measurement) failures += measurement is None def new_measurement(elite): nonlocal refresh_count, failures if used() >= budget: return None genome = tuple(elite) refresh_count += 1 result = _measure(archive, evaluate, (genome, tick), genome) failures += result is None return result staged = _refresh_replacees(archive, offspring, probe, fresh_probe, new_measurement) if changed else {} if staged is None or (probe is not None and fresh_probe is None): incomplete += 1 strategy = None else: old = [elite for elite in archive if id(elite) in staged] if probe is not None and not changed: last_checked[id(probe)] = tick for elite in old: archive.discard(elite) del last_checked[id(elite)] for elite in old: _offer_with_age(archive, staged[id(elite)], last_checked, tick) order, admitted = _improvements(archive, offspring, ages=last_checked, tick=tick) if size == batch_size: if admitted: strategy.tell(vectors, _losses(order)) else: strategy = None if on_step is not None: on_step(archive, iteration=iteration, evaluations=used()) last_checked = {id(elite): last_checked.get(id(elite), tick) for elite in archive} return DynamicCMAResult(archive, offspring_count, probes, refresh_count, failures, tuple(detected), incomplete)
def _rank_gradients(noise, positive, negative): """Form mirrored ES gradients using combined per-output ranks.""" ranks = rankdata(np.concatenate((positive, negative)), method="average", axis=0) first, second = np.split(ranks, 2, axis=0) # The positive common ES scale cancels when each gradient is normalised. return (first - second).T @ noise def _es_basis(noise, measurements, objective_weight): """Estimate rank gradients from complete mirrored pairs and normalise each row.""" pairs = len(noise) complete = [slot for slot in range(pairs) if measurements[slot] is not None and measurements[slot + pairs] is not None] if not complete: return None values = [] for slot in [*complete, *(slot + pairs for slot in complete)]: candidate = measurements[slot][0] values.append((*candidate.fitness.values, *candidate.features)) split = len(complete) return _gradient_basis(_rank_gradients(noise[complete], values[:split], values[split:]), objective_weight) ## @brief Build and branch a gradient basis using a single batch of ES perturbations.
[docs] def cma_mega_es(archive, evaluate, *, x0, budget, es_samples=32, es_sigma=0.02, sigma0=0.2, step_size=1.0, batch_size=16, ind_domain=(0, 1), seed=0, executor=None, on_step=None): """Run CMA-MEGA (ES) with measured fitness and black-box descriptors. Evaluate the centre and mirrored perturbations first. Use one rank gradient per output, estimated from the same perturbations. Offer all valid measurements to the archive. Branch along combinations of the normalised gradients and adapt CMA in coefficient space using archive improvement. Advance the centre by rank-weighted gradient ascent. If the budget ends, archive measured partial phases without adapting CMA from a short batch. Discard incomplete mirrored pairs when estimating gradients. :param archive: Empty, parentless, best-only Grid or CVTGrid. :param evaluate: Callable taking an immutable real-valued genome and returning a singleton fitness vector and its descriptors. :param x0: Initial centre in genome coordinates. :param budget: Total attempted centre, perturbation and offspring evaluations. :param es_samples: Even number of perturbations including both signs. :param es_sigma: Perturbation standard deviation in genome coordinates. :param sigma0: Initial CMA step size in gradient coefficient coordinates. :param step_size: Multiplier for the rank-weighted centre displacement. :param batch_size: CMA offspring population size. :param ind_domain: Inclusive bounds, or None for unbounded search. :param seed: Private seed for perturbations, CMA and restart centres. :param executor: Optional caller-owned executor with ordered map. :param on_step: Optional callback receiving the archive, iteration and evaluations. :returns: The live archive and counts for each phase. """ initial, bounds, batch_size, budget = _settings( archive, evaluate, x0, sigma0, batch_size, budget, ind_domain, on_step) es_samples = _positive_int(es_samples, "es_samples") if es_samples % 2 or es_samples < 2: raise ValueError("es_samples must be even and at least two.") if not 0 < es_sigma < np.inf or not 0 < step_size < np.inf: raise ValueError("ES noise and centre step must be finite and positive.") rng = np.random.default_rng(seed) dimension = len(initial) basis_size = len(archive.features_domain) + 1 weight = -1.0 if archive.fitness_weights is None else archive.fitness_weights[0] center = initial strategy = None centre_count = perturbations = offspring_count = failures = iteration = 0 def used(): return centre_count + perturbations + offspring_count def bounded(vectors): return vectors if bounds is None else np.clip(vectors, *bounds) while used() < budget: iteration += 1 count = min(es_samples, budget - used() - 1) noise = rng.standard_normal((min(count, es_samples // 2), dimension)) shifts = np.concatenate((noise, -noise[:count - len(noise)])) points = bounded(np.vstack((center, center + es_sigma * shifts))) measurements = _measure_group(archive, evaluate, points, executor) centre_count += 1 perturbations += count failures += sum(result is None for result in measurements) for result in measurements: if result is not None: _offer(archive, result) basis = _es_basis(noise, measurements[1:], weight) if count == es_samples else None if used() < budget: if basis is None or not np.any(basis): center = _restart_center(archive, initial, rng) strategy = None else: if strategy is None: strategy = _strategy(np.zeros(basis_size), sigma0, batch_size, rng) size = min(batch_size, budget - used()) coefficients = strategy.ask(number=size) vectors = bounded(center + np.asarray(coefficients) @ basis) offspring = _measure_group(archive, evaluate, vectors, executor) offspring_count += size failures += sum(result is None for result in offspring) order, admitted = _improvements(archive, offspring) if size == batch_size: if admitted: strategy.tell(coefficients, _losses(order)) ranked = [slot for slot in order if offspring[slot] is not None and offspring[slot][1] is not None] selected = ranked[:strategy.sp.mu] weights = np.asarray(strategy.sp.weights[:len(selected)]) center = bounded(center + step_size * np.average( vectors[selected] - center, axis=0, weights=weights)) if not admitted or strategy.stop(): center = _restart_center(archive, initial, rng) strategy = None if on_step is not None: on_step(archive, iteration=iteration, evaluations=used()) return CMAMEGAESResult(archive, centre_count, perturbations, offspring_count, failures)