# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Analytic Diffusion Evolution and its archive-guided emitter.
# @see https://doi.org/10.48550/arXiv.2410.02543
"""Generate offspring with fitness-weighted Gaussian denoising."""
import numpy as np
from scipy.spatial.distance import cdist
from scipy.special import softmax
from qdpy.base import registry
from .modern import _FixedGeneration, _positive_int
from .task_search import _search_bounds, _validate_grid
__all__ = ["DiffusionEvolution", "DiffusionMAPElites"]
def _denoise(particles, references, log_density, alpha, next_alpha, noise_scale, rng):
"""Apply one reverse diffusion step in normalized genome coordinates."""
signal = np.sqrt(alpha)
variance = 1. - alpha
logits = cdist(particles, signal * references, "sqeuclidean")
logits *= -.5 / variance
logits += log_density
estimate = softmax(logits, axis=1) @ references
residual = (particles - signal * estimate) / np.sqrt(variance)
next_variance = 1. - next_alpha
sigma = noise_scale * np.sqrt(next_variance / variance * (1. - alpha / next_alpha))
residual_scale = np.sqrt(max(0., next_variance - sigma**2))
return np.sqrt(next_alpha) * estimate + residual_scale * residual + sigma * rng.normal(size=particles.shape)
def _log_density(quality, temperature):
"""Map signed fitness monotonically to positive relative sampling weights."""
scaled = quality / (np.max(np.abs(quality)) or 1.)
span = np.ptp(scaled)
if span == 0.:
return np.zeros_like(quality)
with np.errstate(over="ignore"):
return np.maximum(((scaled - np.max(scaled)) / span) / temperature, -700.)
## @brief Optimize a measured population with the reverse diffusion update.
[docs]
@registry.register
class DiffusionEvolution(_FixedGeneration):
"""Run bounded, population-only Diffusion Evolution with a reporting grid.
Shape Gaussian denoising estimates using the previous generation's
signed objective. The reporting archive fills from measured candidates
and stays outside the proposal loop. Progress through a cosine
schedule, then start another Gaussian population if more budget
remains. Bounds and fitness scaling adapt the paper to the native
fixed-generation evaluator API.
:param container: Parentless best-only scalar Grid or CVTGrid.
:param budget: Number of attempted candidate evaluations.
:param dimension: Number of real genome coordinates.
:param batch_size: Maximum population size.
:param ind_domain: Shared finite lower and upper bounds.
:param diffusion_steps: Generations per cosine schedule, at least two.
:param temperature: Positive fitness temperature for denoising weights.
:param noise_scale: DDIM noise multiplier between zero and one.
:param seed: Private seed for Gaussian proposals and restart populations.
:param kwargs: Native optimizer options, such as optimisation_task.
"""
_requires_proposed_genome = True
def __init__(self, container, budget, dimension, batch_size, *, ind_domain=(-1., 1.),
diffusion_steps=20, temperature=.25, noise_scale=1., seed=0, **kwargs):
_validate_grid(container, empty=False)
self.ind_domain = _search_bounds(ind_domain)
steps = _positive_int(diffusion_steps, "diffusion_steps")
if (steps < 2 or not np.isfinite(temperature) or temperature <= 0.
or not 0. <= noise_scale <= 1.):
raise ValueError("Use at least two steps, positive finite temperature, and noise_scale in [0, 1].")
self._schedule = 1e-4 + (1. - 2e-4) * np.square(np.sin(np.linspace(0., np.pi / 2, steps)))
self._temperature, self._noise, self._seed = temperature, noise_scale, seed
kwargs.setdefault("optimisation_task", container.fitness_weights or "maximisation")
super().__init__(container, _positive_int(budget, "budget"),
dimension=_positive_int(dimension, "dimension"),
batch_size=_positive_int(batch_size, "batch_size"), **kwargs)
if not np.isfinite(self._fitness_weights[0]) or self._fitness_weights[0] == 0.:
raise ValueError("Use a finite nonzero objective weight.")
def reinit(self):
"""Reset the diffusion schedule and its previous measured population."""
super().reinit()
self._rng = np.random.default_rng(self._seed)
self._population = ()
self._proposals = ()
self._diffusion_proposals = 0
@property
def diffusion_proposals(self):
"""Return the number of candidates produced by completed denoising steps."""
return self._diffusion_proposals
def _normalize(self, entries):
lower, upper = self.ind_domain
return 2. * ((np.asarray(entries, dtype=float) - lower) / (upper - lower)) - 1.
def _sources(self, size, alpha):
if not self._population:
return None
vectors, quality = self._population
parent_ids = np.arange(size) if len(vectors) == size else self._rng.integers(len(vectors), size=size)
return vectors[parent_ids], vectors, quality
def _start_fixed_batch(self, size):
super()._start_fixed_batch(size)
stage = self.current_iter % len(self._schedule)
sources = self._sources(size, self._schedule[stage - 1]) if stage else None
if sources is None:
latent = self._rng.normal(size=(size, self.dimension))
else:
particles, vectors, quality = sources
latent = _denoise(particles, vectors, _log_density(quality, self._temperature),
self._schedule[stage - 1], self._schedule[stage], self._noise, self._rng)
self._diffusion_proposals += size
lower, upper = self.ind_domain
proportion = (.5 + .5 * np.clip(latent, -1., 1.))
self._proposals = np.clip(lower + (upper - lower) * proportion, lower, upper)
def _internal_ask(self, base_ind):
base_ind[:] = self._proposals[len(self._issued)].tolist()
return base_ind
def _clear_generation(self):
super()._clear_generation()
self._proposals = ()
def _check_candidate(self, individual):
self._check_measurements(individual)
fitness = self.container.get_ind_fitness(individual)
features = self.container.get_ind_features(individual)
if len(fitness.values) != 1 or len(features) != len(self.container.features_domain):
raise ValueError("Return one fitness value and the reporting grid's descriptor vector.")
def _fitness(self, individual):
return self.container.get_ind_fitness(individual).values[0]
def _reference_data(self, entries):
genomes = self._normalize(entries)
direction = 1. if self._fitness_weights[0] > 0. else -1.
fitness = direction * np.array([self._fitness(item) for item in entries], dtype=float)
return genomes, fitness
def _commit_generation(self, evaluated):
valid = [item for item in evaluated if item is not None]
self._population = self._reference_data(valid) if valid else ()
admitted = set()
archive = self.container
for slot, item in enumerate(evaluated):
if item is None:
continue
features = archive.get_ind_features(item)
if (archive.in_bounds(features, archive.features_domain)
and archive.in_bounds((self._fitness(item),), archive.fitness_domain)
and self._offer_to_grid(item, archive.index_grid(item))):
admitted.add(slot)
return admitted
## @brief Denoise Gaussian particles around uniformly sampled archive cells.
[docs]
@registry.register
class DiffusionMAPElites(DiffusionEvolution):
"""Use archive elites as references and seed particles across occupied niches.
Each reference is a genuinely measured elite. Draw an occupied cell
for each particle and add forward noise at the current schedule stage.
The same reverse update as DiffusionEvolution proposes offspring.
Select a bounded uniform subset if the archive grows too large.
:param max_elites: Maximum number of occupied cells in the denoising reference pool.
"""
def __init__(self, container, budget, dimension, batch_size, *, max_elites=256, **kwargs):
self.max_elites = _positive_int(max_elites, "max_elites")
super().__init__(container, budget, dimension, batch_size, **kwargs)
def _sources(self, size, alpha):
if not self.container:
return super()._sources(size, alpha)
indices = np.arange(len(self.container))
if len(indices) > self.max_elites:
indices = self._rng.choice(indices, size=self.max_elites, replace=False)
vectors, fitness = self._reference_data([self.container[int(i)] for i in indices])
if (vectors.shape != (len(indices), self.dimension) or not np.isfinite(vectors).all()
or (np.abs(vectors) > 1. + 1e-12).any() or not np.isfinite(fitness).all()):
raise ValueError("Seeded elites must have finite in-domain genomes with the configured dimension.")
parents = vectors[self._rng.integers(len(vectors), size=size)]
particles = np.sqrt(alpha) * parents + np.sqrt(1. - alpha) * self._rng.normal(size=parents.shape)
return particles, vectors, fitness