# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Neuro-MAP-Elites with error-mask descriptors and validation-set voting.
# @see https://doi.org/10.1145/3449726.3459549
"""Evolve classifiers across a learned space of per-example errors."""
from dataclasses import dataclass
import numpy as np
from scipy.special import ndtr
from qdpy.containers import Grid
from ._population import _attempt_budget
from .modern import _positive_int
from .task_search import _measurement, _offer, _validate_grid
__all__ = ["NMEEnsemble", "NMEResult", "neuro_map_elites", "nme_ensemble"]
def _labels(values, size=None):
labels = np.asarray(values)
if (labels.ndim != 1 or not len(labels) or (size is not None and len(labels) != size)
or labels.dtype.kind not in "biufUS"
or (labels.dtype.kind == "f" and not np.isfinite(labels).all())):
raise ValueError("Provide a fixed nonempty vector of finite numeric or string labels.")
return labels
def _balanced(correct, groups, counts):
correct_by_class = np.bincount(groups, weights=correct, minlength=len(counts))
return float(np.mean(correct_by_class / counts))
def _vote(votes, classes, predictions):
indices = np.searchsorted(classes, predictions)
if np.any(indices >= len(classes)) or not np.array_equal(classes[indices], predictions):
raise ValueError("A classifier predicted a class outside the training labels.")
votes[np.arange(len(indices)), indices] += 1
## @brief Classifiers selected by validation accuracy and combined with majority voting.
[docs]
@dataclass(frozen=True)
class NMEEnsemble:
"""Preserve vote order and break vote ties by the order of classes."""
genomes: tuple[tuple, ...]
classes: tuple
validation_accuracy: float
validation_evaluations: int
## @brief Predict labels on a shared panel using the selected genomes.
[docs]
def predict(self, predict):
"""Call predict(genome) once per member and return the majority labels."""
classes = np.asarray(self.classes)
votes = None
for genome in self.genomes:
row = _labels(predict(genome), None if votes is None else len(votes))
if votes is None:
votes = np.zeros((len(row), len(classes)), dtype=int)
_vote(votes, classes, row)
return classes[votes.argmax(axis=1)]
## @brief Report the final learned repertoire, initial mining archive, and model-call counts.
[docs]
@dataclass(frozen=True)
class NMEResult:
"""The encoder maps binary error masks to descriptors in the unit cube."""
archive: Grid
mining_archive: Grid
encoder: object
evaluations: int
mining_evaluations: int
encoder_updates: int
training_masks: int
class _MaskEncoder:
def __init__(self, torch, masks, width, hidden, beta, steps, batch, rng):
nn = torch.nn
layout = dict(device="cpu", dtype=torch.float32)
with torch.random.fork_rng(devices=[]):
torch.random.default_generator.manual_seed(int(rng.integers(2**32)))
self._encoder = nn.Sequential(nn.Linear(masks.shape[1], hidden, **layout), nn.ReLU(),
nn.Linear(hidden, 2 * width, **layout))
decoder = nn.Sequential(nn.Linear(width, hidden, **layout), nn.ReLU(),
nn.Linear(hidden, masks.shape[1], **layout))
self._torch, self._size, self._width = torch, masks.shape[1], width
noise = torch.Generator(device="cpu").manual_seed(int(rng.integers(2**32)))
optimizer = torch.optim.Adam((*self._encoder.parameters(), *decoder.parameters()), lr=.003)
data = torch.as_tensor(masks, device="cpu", dtype=torch.float32)
for _ in range(steps):
rows = rng.choice(len(data), min(batch, len(data)), replace=False)
target = data[rows]
mean, log_variance = self._encoder(target).chunk(2, dim=1)
log_variance = log_variance.clamp(-10., 6.)
jitter = torch.randn(mean.shape, device="cpu", dtype=mean.dtype, generator=noise)
sampled = mean + (.5 * log_variance).exp() * jitter
penalty = .5 * (mean.square() + log_variance.exp() - log_variance - 1.).sum(dim=1).mean()
loss = nn.functional.binary_cross_entropy_with_logits(decoder(sampled), target, reduction="sum")
loss = loss / len(rows) + beta * penalty
if not torch.isfinite(loss):
raise FloatingPointError("The error-mask encoder produced a nonfinite loss.")
optimizer.zero_grad(set_to_none=True)
loss.backward()
optimizer.step()
self._encoder.requires_grad_(False)
def transform(self, masks):
"""Return normal quantiles of the latent means for binary error masks."""
masks = np.asarray(masks, dtype=np.float32)
if masks.ndim not in (1, 2) or masks.shape[-1] != self._size or not np.isin(masks, (0, 1)).all():
raise ValueError("Supply binary masks in the original training example order.")
with self._torch.no_grad():
means = self._encoder(self._torch.from_numpy(masks.copy()))[..., :self._width].numpy()
if not np.isfinite(means).all():
raise FloatingPointError("The error-mask encoder produced nonfinite descriptors.")
return ndtr(means.astype(float))
## @brief Mine models, fit a beta-VAE on their errors, and illuminate the latent space.
# @param targets Training labels in prediction order.
# @param predict Callable (genome) returning predicted training labels.
# @param sample Callable (rng) returning a genome iterable.
# @param mutate Callable (genome, rng) returning an offspring genome.
# @param structural Callable (genome) returning the mining descriptors.
# @param mining_archive Empty rectangular mining archive with maximizing fitness.
# @param budget Total prediction calls, including mining.
# @param mining_budget Evaluations spent on structural MAP-Elites.
# @param initial_samples Number of unconditional samples during mining.
# @param shape Shape of the final latent grid.
# @param min_mining_accuracy Minimum balanced accuracy for masks used in training.
# @param fit_steps Number of VAE optimizer updates.
# @param hidden Hidden width of the encoder and decoder.
# @param fit_batch Maximum masks in each optimizer step.
# @param beta Weight of the latent KL term.
# @param seed Seed for variation and training.
# @return NMEResult with archives, encoder and work counters.
[docs]
def neuro_map_elites(targets, predict, *, sample, mutate, structural, mining_archive,
budget, mining_budget, initial_samples=16, shape=(8, 8), min_mining_accuracy=.5,
fit_steps=128, hidden=32, fit_batch=32, beta=.3, seed=0):
"""Run structural and learned-descriptor searches over the same training panel.
Use balanced accuracy in both phases. Retain the error masks of qualifying
mining elites and fit a beta-VAE to the binary masks. Seed the learned
archive from cached mining measurements. Normal quantiles partition each
learned axis into bins of equal mass under the latent prior.
"""
if not all(map(callable, (predict, sample, mutate, structural))):
raise TypeError("Supply callable prediction, variation and mining descriptors.")
_validate_grid(mining_archive)
if type(mining_archive) is not Grid or (mining_archive.fitness_weights or (1.,))[0] <= 0:
raise ValueError("Use a rectangular mining archive which maximizes quality.")
target = _labels(targets)
classes, groups, counts = np.unique(target, return_inverse=True, return_counts=True)
groups = groups.reshape(-1)
budget, first = _attempt_budget(budget), _positive_int(mining_budget, "mining_budget")
initial_samples = _attempt_budget(initial_samples)
shape = tuple(_positive_int(n, "shape") for n in shape)
if (len(classes) < 2 or not shape or budget <= first or not 0 <= min_mining_accuracy <= 1
or not 0 < beta < np.inf):
raise ValueError("Use two or more classes, a mining budget below budget, and valid encoder settings.")
steps = _positive_int(fit_steps, "fit_steps")
hidden = _positive_int(hidden, "hidden")
batch = _positive_int(fit_batch, "fit_batch")
try:
import torch
except ImportError as error:
raise ImportError("Neuro-MAP-Elites requires PyTorch. Install qdpy[rl] or torch.") from error
if mining_archive.fitness_weights is None:
mining_archive._set_fitness_weights((1.,))
rng, fit_rng = map(np.random.default_rng, np.random.SeedSequence(seed).spawn(2))
def propose(grid):
return tuple(mutate(tuple(grid[int(rng.integers(len(grid)))]), rng) if grid else sample(rng))
def score(genome):
predictions = _labels(predict(genome), len(target))
if not np.isin(predictions, classes).all():
raise ValueError("Predicted labels must belong to the training classes.")
mask = predictions != target
return _balanced(~mask, groups, counts), tuple(map(bool, mask))
def admit(grid, genome, quality, mask, descriptor):
candidate = _measurement(grid, ((quality,), descriptor), genome)
candidate[0].scores["nme_error_mask"] = mask
_offer(grid, candidate)
for step in range(first):
genome = tuple(sample(rng)) if step < initial_samples else propose(mining_archive)
quality, mask = score(genome)
admit(mining_archive, genome, quality, mask, structural(genome))
masks = [row.scores["nme_error_mask"] for row in mining_archive
if row.fitness.values[0] >= min_mining_accuracy]
if not masks:
raise ValueError("The mining archive has no qualifying classifiers for the VAE.")
encoder = _MaskEncoder(torch, np.array(masks), len(shape), hidden, beta, steps, batch, fit_rng)
archive = Grid(shape=shape, features_domain=((0., 1.),) * len(shape),
fitness_domain=((0., 1.),), fitness_weights=(1.,))
for row in mining_archive:
mask = row.scores["nme_error_mask"]
admit(archive, tuple(row), row.fitness.values[0], mask, encoder.transform(mask))
for _ in range(budget - first):
genome = propose(archive)
quality, mask = score(genome)
admit(archive, genome, quality, mask, encoder.transform(mask))
return NMEResult(archive, mining_archive, encoder, budget, first, steps, len(masks))
## @brief Select a majority-vote prefix on an independent validation panel.
# @param archive Iterable of measured classifiers with a scalar fitness.
# @param predict Callable (genome) returning labels on the validation panel.
# @param targets Validation labels in callback order.
# @param classes Optional full class list, including classes absent in validation.
# @param max_members Optional cap on ranked archive members tested.
# @param size Optional exact ensemble size for matched-size comparisons.
# @return NMEEnsemble and validation measurement count.
[docs]
def nme_ensemble(archive, predict, targets, *, classes=None, max_members=None, size=None):
"""Try quality-ranked vote prefixes and keep the smallest best-scoring one."""
target = _labels(targets)
observed, groups, counts = np.unique(target, return_inverse=True, return_counts=True)
groups = groups.reshape(-1)
classes = observed if classes is None else np.unique(_labels(classes))
if not np.isin(observed, classes).all():
raise ValueError("The validation targets include an unknown class.")
ranked = sorted(archive, key=lambda row: row.fitness.values[0] * row.fitness.weights[0], reverse=True)
if max_members is not None:
ranked = ranked[:_positive_int(max_members, "max_members")]
if size is not None:
size = _positive_int(size, "size")
if size > len(ranked):
raise ValueError("The archive cannot fill the requested ensemble size.")
ranked = ranked[:size]
if not ranked or not callable(predict):
raise ValueError("Supply a nonempty archive and callable validation prediction.")
genomes = tuple(tuple(row) for row in ranked)
votes = np.zeros((len(target), len(classes)), dtype=int)
best, best_size = -1., 0
for length, genome in enumerate(genomes, 1):
_vote(votes, classes, _labels(predict(genome), len(target)))
value = _balanced(classes[votes.argmax(axis=1)] == target, groups, counts)
if length == size or (size is None and value > best):
best, best_size = value, length
return NMEEnsemble(genomes[:best_size], tuple(classes.tolist()), best, len(genomes))