# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Deep surrogate-assisted illumination with measured archive admission.
"""DSAGE with batched prediction, ancillary observations, and stratified promotion."""
from dataclasses import dataclass
from math import ceil, isfinite, sqrt
from operator import index
import numpy as np
from qdpy.containers import Grid
from qdpy.phenotype import Features, Fitness, Individual
from .modern import IsoLineMAPElites, _bounds, _positive_int
__all__ = ["DSAGE", "DSAGEMeasurement", "DSAGESurrogate", "DSAGEStats"]
## @brief One true measurement with optional simulator observations.
[docs]
@dataclass(frozen=True)
class DSAGEMeasurement:
"""Supply scalar fitness, descriptor coordinates, and optional ancillary targets."""
fitness: float
features: tuple[float, ...]
auxiliary: object = None
## @brief Separate ground-truth attempts, surrogate predictions, and model training calls.
[docs]
@dataclass(frozen=True)
class DSAGEStats:
"""Cumulative search costs."""
evaluations: int
surrogate_evaluations: int
model_fits: int
## @brief CPU neural surrogate with an optional first stage for ancillary observations.
[docs]
class DSAGESurrogate:
"""Train a PyTorch MLP on encoded genome rows.
With ancillary targets, a first network predicts them. A second
network consumes the encoded genome and those predictions to
predict fitness and descriptors. Both losses train the first network.
When auxiliary targets are absent, train only the second network.
"""
def __init__(self, *, width=64, epochs=30, learning_rate=.003, auxiliary_weight=1., seed=0):
self.width = _positive_int(width, "width")
self.epochs = _positive_int(epochs, "epochs")
if not (0 < learning_rate < np.inf and 0 <= auxiliary_weight < np.inf):
raise ValueError("Use a finite positive learning rate and nonnegative auxiliary weight.")
self.learning_rate, self.auxiliary_weight = learning_rate, auxiliary_weight
self._seed = int(np.random.default_rng(seed).integers(2**32))
self._model = None
## @brief Fit fresh networks on measured targets and ancillary labels.
[docs]
def fit(self, x, targets, auxiliary=None):
"""Fit using input rows and targets ordered as fitness then descriptors."""
try:
import torch
from torch import nn
except ImportError as error:
raise ImportError("The built-in DSAGE surrogate requires PyTorch.") from error
def normalized(values):
array = np.asarray(values, dtype=np.float32)
if array.ndim != 2 or not array.size or not np.isfinite(array).all():
raise ValueError("Surrogate training arrays must be finite two-dimensional matrices.")
tensor = torch.from_numpy(array)
mean, scale = tensor.mean(dim=0), tensor.std(dim=0, unbiased=False).clamp(min=1e-6)
if not torch.isfinite(mean).all() or not torch.isfinite(scale).all():
raise ValueError("Surrogate training normalisation overflowed.")
return (tensor - mean) / scale, mean, scale
x, xm, xs = normalized(x)
y, ym, ys = normalized(targets)
aux = normalized(auxiliary)[0] if auxiliary is not None else None
if len(x) != len(y) or (aux is not None and len(x) != len(aux)):
raise ValueError("Measurements and ancillary targets must match the input rows.")
n_aux = 0 if aux is None else aux.shape[1]
def network(inputs, outputs):
return nn.Sequential(nn.Linear(inputs, self.width, device="cpu"), nn.SiLU(),
nn.Linear(self.width, outputs, device="cpu"))
with torch.random.fork_rng(devices=[]):
torch.random.default_generator.manual_seed(self._seed)
ancillary = network(x.shape[1], n_aux) if n_aux else None
model = network(x.shape[1] + n_aux, y.shape[1])
parameters = list(model.parameters())
if ancillary is not None:
parameters.extend(ancillary.parameters())
optimizer = torch.optim.Adam(parameters, lr=self.learning_rate)
for _ in range(self.epochs):
if ancillary is None:
prediction = model(x)
loss = (prediction - y).square().mean()
else:
predicted_aux = ancillary(x)
prediction = model(torch.cat((x, predicted_aux), dim=1))
loss = (prediction - y).square().mean()
loss = loss + self.auxiliary_weight * (predicted_aux - aux).square().mean()
if not torch.isfinite(loss):
raise ValueError("Training the DSAGE surrogate produced a nonfinite loss.")
optimizer.zero_grad(set_to_none=True)
loss.backward()
optimizer.step()
self._model = model, ancillary, xm, xs, ym, ys
## @brief Predict fitness and descriptors for a batch of encoded genomes.
[docs]
def predict(self, x):
"""Return a matrix in the original target units."""
if self._model is None:
raise RuntimeError("Fit the surrogate before predicting.")
import torch
model, ancillary, xm, xs, ym, ys = self._model
x = torch.as_tensor(np.asarray(x, dtype=np.float32), device="cpu")
if x.ndim != 2 or x.shape[1] != len(xm) or not torch.isfinite(x).all():
raise ValueError("Prediction rows must match the fitted input width and be finite.")
with torch.no_grad():
inputs = (x - xm) / xs
if ancillary is not None:
inputs = torch.cat((inputs, ancillary(inputs)), dim=1)
return (model(inputs) * ys + ym).numpy()
## @brief Alternate measured simulations with illumination in a surrogate grid.
[docs]
class DSAGE:
"""Deep Surrogate Assisted Generation of Environments on fixed grids.
A bounded real genome can parameterize any caller-provided simulator.
The optional encoder builds a fixed-width vector for the surrogate.
For custom models, supply fit(X, targets, auxiliary) and predict(X),
with target columns ordered as fitness followed by descriptors.
Admit measured results to archive. The inner search illuminates a
separate predicted grid. Before simulation, uniformly pick an elite
from each selected occupied region of a coarser descriptor grid.
"""
def __init__(self, archive, dimension, *, ind_domain=(0., 1.), initial_samples=24,
surrogate_evaluations=256, simulation_batch_size=8, prediction_batch_size=32,
downsample_shape=None, encoder=None, surrogate=None, seed=0, maximise=True):
if (type(archive) is not Grid or archive.max_items_per_bin != 1
or len(archive.fitness_domain) != 1 or archive.parents or len(archive)):
raise ValueError("DSAGE needs an empty parentless scalar Grid with one elite per cell.")
self.archive = archive
self.dimension = _positive_int(dimension, "dimension")
self.bounds = _bounds(ind_domain)
self.initial_samples = _positive_int(initial_samples, "initial_samples")
self.surrogate_budget = _positive_int(surrogate_evaluations, "surrogate_evaluations")
self.simulation_batch_size = _positive_int(simulation_batch_size, "simulation_batch_size")
self.prediction_batch_size = _positive_int(prediction_batch_size, "prediction_batch_size")
if downsample_shape is None:
downsample_shape = tuple(ceil(sqrt(n)) for n in archive.shape)
self._strata = tuple(_positive_int(n, "strata extent") for n in downsample_shape)
if len(self._strata) != len(archive.shape) or any(a > b for a, b in zip(self._strata, archive.shape)):
raise ValueError("Downsample strata must fit inside the archive shape.")
if encoder is not None and not callable(encoder):
raise TypeError("encoder must be callable.")
self._encoder = encoder
self.surrogate = DSAGESurrogate(seed=seed) if surrogate is None else surrogate
if not all(callable(getattr(self.surrogate, name, None)) for name in ("fit", "predict")):
raise TypeError("surrogate needs fit and predict methods.")
self._weights = (1.,) if maximise else (-1.,)
archive._set_fitness_weights(self._weights)
self._rng = np.random.default_rng(seed)
self._inputs, self._targets, self._auxiliary = [], [], []
self._trials = self._predictions = self._model_fits = 0
self.last_surrogate_archive = None
@property
def stats(self):
"""Return the actual cumulative search costs."""
return DSAGEStats(self._trials, self._predictions, self._model_fits)
def _random(self):
return tuple(map(float, self._rng.uniform(*self.bounds, size=self.dimension)))
def _encode(self, genome):
features = np.asarray(genome if self._encoder is None else self._encoder(genome), dtype=float).ravel()
if not features.size or not np.isfinite(features).all():
raise ValueError("The encoded genome must be nonempty and finite.")
if self._inputs and len(features) != len(self._inputs[0]):
raise ValueError("The encoder must return a fixed number of values.")
return features.copy()
def _measure(self, genome, evaluate):
inputs = self._encode(genome)
self._trials += 1
result = evaluate(genome)
if not isinstance(result, DSAGEMeasurement):
raise TypeError("evaluate must return DSAGEMeasurement.")
value, features = float(result.fitness), tuple(map(float, result.features))
if not isfinite(value) or len(features) != len(self.archive.shape) or not all(map(isfinite, features)):
raise ValueError("Measured fitness and descriptors must be finite and match the grid.")
aux = None if result.auxiliary is None else np.asarray(result.auxiliary, dtype=float).ravel().copy()
if aux is not None and (not aux.size or not np.isfinite(aux).all()):
raise ValueError("Auxiliary observations must be nonempty and finite.")
if self._auxiliary and ((aux is None) != (self._auxiliary[0] is None)
or (aux is not None and aux.shape != self._auxiliary[0].shape)):
raise ValueError("All measurements must use the same auxiliary schema.")
individual = Individual(genome, fitness=Fitness((value,), weights=self._weights), features=Features(features))
if (self.archive.in_bounds((value,), self.archive.fitness_domain)
and self.archive.in_bounds(features, self.archive.features_domain)):
cell = self.archive.index_grid(features)
if self.archive.free or self.archive.solutions[cell]:
self.archive.add(individual)
self._inputs.append(inputs)
self._targets.append((value, *features))
self._auxiliary.append(aux)
def _promote(self, predicted, limit):
strata = {}
for item in predicted:
cell = predicted.index_grid(item)
region = tuple(i * k // n for i, k, n in zip(cell, self._strata, predicted.shape))
strata.setdefault(region, []).append(item)
groups = tuple(strata.values())
return [tuple(groups[i][int(self._rng.integers(len(groups[i])))])
for i in self._rng.permutation(len(groups))[:limit]]
def _illuminate(self):
from qdpy.simple import _coordinator_seed
archive = self.archive
imagined = Grid(shape=archive.shape, features_domain=archive.features_domain,
fitness_domain=archive.fitness_domain)
search = IsoLineMAPElites(imagined, budget=self.surrogate_budget, dimension=self.dimension,
ind_domain=self.bounds, optimisation_task=self._weights)
low, high = np.asarray((*archive.fitness_domain, *archive.features_domain)).T
with _coordinator_seed(int(self._rng.integers(2**32))):
for start in range(0, self.surrogate_budget, self.prediction_batch_size):
size = min(self.prediction_batch_size, self.surrogate_budget - start)
candidates = [search.ask() for _ in range(size)]
inputs = np.stack([self._encode(tuple(ind)) for ind in candidates])
self._predictions += size
y = np.asarray(self.surrogate.predict(inputs), dtype=float)
if y.shape != (size, len(low)) or not np.isfinite(y).all():
raise ValueError("Surrogate prediction needs one finite fitness/descriptor row per genome.")
for candidate, row in zip(candidates, np.clip(y, low, high)):
search.tell(candidate, fitness=(float(row[0]),), features=tuple(row[1:]))
self.last_surrogate_archive = imagined
return imagined
## @brief Spend a hard budget of additional true simulator calls.
[docs]
def run(self, evaluate, *, budget):
"""Run initial and promoted measurements and return cumulative counters."""
budget = index(budget)
if budget < 0 or not callable(evaluate):
raise ValueError("Use a nonnegative budget and callable evaluate.")
stop = self._trials + budget
while len(self._inputs) < self.initial_samples and self._trials < stop:
self._measure(self._random(), evaluate)
while self._trials < stop:
auxiliary = None if self._auxiliary[0] is None else np.stack(self._auxiliary)
self._model_fits += 1
self.surrogate.fit(np.stack(self._inputs), np.asarray(self._targets), auxiliary)
imagined = self._illuminate()
selected = self._promote(imagined, min(self.simulation_batch_size, stop - self._trials))
for genome in selected or [self._random()]:
self._measure(genome, evaluate)
return self.stats