# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Learned survival scores for bounded quality-diversity populations.
"""Learned QD inference and native ordered search."""
import numpy as np
from scipy.special import softmax
from qdpy.base import registry
from qdpy.containers import Container
from qdpy.tools import iso_line_dd
from .modern import _FixedGeneration, _positive_int, _variation_settings
__all__ = ["LQDSelector", "LearnedQD"]
def _standardize(values):
"""Scale before computing moments to accommodate large finite coordinates."""
scale = np.max(np.abs(values), axis=0)
scaled = values / np.where(scale > 0, scale, 1.)
centered = scaled - scaled.mean(axis=0)
deviation = np.sqrt(np.mean(centered ** 2, axis=0))
return centered / np.where(deviation > 0, deviation, 1.)
## @brief Permutation-equivariant attention over measured quality and descriptors.
[docs]
class LQDSelector:
"""Produce one learned survival score per population member.
The model standardizes each input column across the population. Its
attention blocks have a residual feed-forward layer and no positional
encodings. The weights can be optimized by an external optimizer.
:param descriptor_size: Number of measured descriptor coordinates.
:param width: Embedding width, divisible by the number of heads.
:param heads: Number of attention heads.
:param layers: Number of attention blocks.
:param parameters: Optional one-dimensional vector of model weights.
:param seed: Local initialization seed when weights are unspecified.
"""
def __init__(self, descriptor_size, *, width=16, heads=4, layers=4, parameters=None, seed=0):
self.descriptor_size = _positive_int(descriptor_size, "descriptor_size")
self.width = _positive_int(width, "width")
self.heads = _positive_int(heads, "heads")
self.layers = _positive_int(layers, "layers")
if self.width % self.heads:
raise ValueError("The embedding width must be divisible by the number of heads.")
width = self.width
count = (self.descriptor_size + 2) * width + self.layers * 8 * width ** 2
if parameters is None:
parameters = np.random.default_rng(seed).normal(scale=0.5 / np.sqrt(width), size=count)
self._parameters = np.array(parameters, dtype=float, copy=True)
if self._parameters.shape != (count,) or not np.isfinite(self._parameters).all():
raise ValueError(f"Provide {count} finite selector weights.")
end = (self.descriptor_size + 1) * width
self._project = self._parameters[:end].reshape(-1, width)
blocks = self._parameters[end:-width].reshape(self.layers, 8, width, width)
self._blocks = tuple((*block[:4], block[4:6].reshape(width, 2 * width),
block[6:].reshape(2 * width, width)) for block in blocks)
self._readout = self._parameters[-width:]
@property
def parameters(self):
"""Return a copy of the flat model weights."""
return self._parameters.copy()
## @brief Score a population using signed quality and measured descriptors.
[docs]
def score(self, quality, descriptors):
"""Return finite scores in the input order. Larger scores survive."""
quality = np.asarray(quality, dtype=float)
descriptors = np.asarray(descriptors, dtype=float)
if (quality.ndim != 1 or not len(quality) or descriptors.shape != (len(quality), self.descriptor_size)
or not np.isfinite(quality).all() or not np.isfinite(descriptors).all()):
raise ValueError("Provide finite quality and descriptors for a nonempty population.")
hidden = _standardize(np.column_stack((quality, descriptors))) @ self._project
head_width = self.width // self.heads
for query, key, value, output, expand, reduce in self._blocks:
q, k, v = ((hidden @ weights).reshape(len(hidden), self.heads, head_width).transpose(1, 0, 2)
for weights in (query, key, value))
attention = softmax((q @ k.transpose(0, 2, 1)) / np.sqrt(head_width), axis=-1)
hidden = hidden + (attention @ v).transpose(1, 0, 2).reshape(len(hidden), self.width) @ output
hidden = hidden + np.maximum(hidden @ expand, 0.) @ reduce
scores = hidden @ self._readout
if not np.isfinite(scores).all():
raise FloatingPointError("The learned selector produced nonfinite scores.")
return scores
## @brief Write versioned numeric weights to a local NPZ file.
[docs]
def save(self, path):
"""Save the model geometry and weights."""
settings = np.array((1, self.descriptor_size, self.width, self.heads, self.layers), dtype=np.int64)
with open(path, "wb") as destination:
np.savez_compressed(destination, settings=settings, parameters=self._parameters)
## @brief Read an LQD selector from a local numeric NPZ file.
[docs]
@classmethod
def load(cls, path):
"""Validate the format version and model geometry before constructing the selector."""
with np.load(path, allow_pickle=False) as data:
settings = data["settings"]
if settings.shape != (5,) or settings.dtype.kind not in "iu" or settings[0] != 1:
raise ValueError("Unsupported LQD selector format.")
_, size, width, heads, layers = settings
return cls(size, width=width, heads=heads, layers=layers, parameters=data["parameters"])
## @brief Use a learned competition rule in an ordered, bounded evolutionary search.
[docs]
@registry.register
class LearnedQD(_FixedGeneration):
"""Evolve a population using Iso+LineDD and learned local competition.
The selector scores the concatenated parent and offspring population.
Keep the highest-scoring distinct genomes with stable ties. Raw fitness
and descriptors remain available for reporting and serialization.
:param selector: LQDSelector for the evaluator's descriptor width.
:param budget: Number of attempted evaluations.
:param dimension: Bounded real genome length.
:param population_size: Maximum retained population size.
:param batch_size: Number of offspring before survival selection.
:param ind_domain: Common clipping interval.
:param fitness_domain: Optional interval in raw objective units.
:param iso_sigma: Isotropic noise scale.
:param line_sigma: Directional noise scale.
:param seed: Local seed for parent draws and variation.
"""
_requires_proposed_genome = True
def __init__(self, selector, budget, dimension, population_size, batch_size, *,
ind_domain=(0., 1.), fitness_domain=None, iso_sigma=.01, line_sigma=.2, seed=0, **kwargs):
if not isinstance(selector, LQDSelector):
raise TypeError("Supply an LQDSelector.")
self.selector, self.seed = selector, seed
self.ind_domain = _variation_settings(ind_domain, iso_sigma, line_sigma)
self.iso_sigma, self.line_sigma = iso_sigma, line_sigma
if fitness_domain is None:
fitness_domain = (-np.inf, np.inf)
if len(fitness_domain) != 2:
raise ValueError("Supply one fitness interval.")
archive = Container(fitness_domain=(fitness_domain,), capacity=_positive_int(population_size, "population_size"))
super().__init__(archive, _positive_int(budget, "budget"),
batch_size=_positive_int(batch_size, "batch_size"),
dimension=_positive_int(dimension, "dimension"), **kwargs)
def reinit(self):
"""Reset the proposal stream and native counters."""
super().reinit()
self._rng = np.random.default_rng(self.seed)
def _internal_ask(self, base_ind):
archive = self.container
if len(archive) < archive.capacity:
base_ind[:] = self._rng.uniform(*self.ind_domain, size=self.dimension)
else:
first, second = self._rng.integers(len(archive), size=2)
base_ind[:] = iso_line_dd(archive[first], archive[second], bounds=self.ind_domain,
iso_sigma=self.iso_sigma, line_sigma=self.line_sigma, rng=self._rng)
return base_ind
def _check_candidate(self, individual):
super()._check_candidate(individual)
if len(individual.features) != self.selector.descriptor_size:
raise ValueError("The descriptor size must match the learned selector.")
def _commit_generation(self, evaluated):
archive = self.container
parents = list(archive)
combined = parents.copy()
slots = {}
seen = {tuple(parent) for parent in parents}
for slot, individual in enumerate(evaluated):
if individual is not None and tuple(individual) not in seen:
seen.add(tuple(individual))
slots[id(individual)] = slot
combined.append(individual)
if len(combined) > archive.capacity:
weight, = archive.fitness_weights
scores = self.selector.score([weight * individual.fitness.values[0] for individual in combined],
[tuple(individual.features) for individual in combined])
indices = np.argsort(-scores, kind="stable")[:archive.capacity]
combined = [combined[i] for i in indices]
selected = {id(individual) for individual in combined}
for parent in parents:
if id(parent) not in selected:
archive.discard(parent)
admitted = set()
for individual in combined:
if id(individual) in slots:
archive.add(individual)
admitted.add(slots[id(individual)])
return admitted