Source code for qdpy.containers.mc_aurora

# SPDX-License-Identifier: LGPL-3.0-or-later

## @file
# @brief Joint autoencoder training and grid rebuilds for MC-AURORA.

"""Optional CPU PyTorch training for multi-container learned descriptors."""

from copy import deepcopy
from dataclasses import dataclass
from itertools import combinations
import math
from operator import index

import numpy as np

from .feature_extraction import TorchFeatureExtractionContainerDecorator
from .grids import Grid
from qdpy.phenotype import Features

try:
    import torch
except ImportError:
    torch = None

__all__ = ["MCAurora", "MCAuroraTraining"]

_DIVERSITY_TERMS = ("none", "outputs", "covariance", "correlation")


if torch is not None:
    ## @brief Dense MC-AURORA default with a smooth activation in the hidden layers.
    class _EnsembleAutoencoder(torch.nn.Module):
        """Flatten observations for encoding and restore their shape on decoding."""

        def __init__(self, shape, latent_size):
            super().__init__()
            nn = torch.nn
            size = math.prod(shape)
            width = max(latent_size, min(128, max(size, 32)))
            self.encoder = nn.Sequential(nn.Flatten(), nn.Linear(size, width), nn.SiLU(),
                                         nn.Linear(width, latent_size))
            self.decoder = nn.Sequential(nn.Linear(latent_size, width), nn.SiLU(),
                                         nn.Linear(width, size), nn.Tanh(), nn.Unflatten(1, shape))

        ## @brief Reconstruct a batch in its original observation shape.
        def forward(self, batch):
            return self.decoder(self.encoder(batch))


## @brief Use the same descriptor cache as single-archive AURORA.
class _EnsembleDescriptors(TorchFeatureExtractionContainerDecorator):
    ## @brief Create the independently initialised default model for this grid.
    def _make_default_model(self, example_ind):
        return _EnsembleAutoencoder(self._input_shape(example_ind), len(self.features_domain))


## @brief Record the data size and mean losses from the final training epoch.
[docs] @dataclass(frozen=True) class MCAuroraTraining: """One completed refit, with separate reconstruction and diversity terms. ``depot_size`` counts available records. ``sample_size`` counts records actually used for training and quantile fitting. ``diversity`` is the reward before applying the configured weight. ``loss`` is the resulting mean training objective. """ depot_size: int sample_size: int reconstruction: float diversity: float loss: float
## @brief Measure off-diagonal latent covariance or correlation matrix distance. # @details Degenerate coordinates contribute zero correlation. A fully # degenerate representation earns no correlation distance reward. def _latent_diversity(latents, term): if term == "covariance": values = torch.cat(latents, dim=1) centered = values - values.mean(dim=0) covariance = centered.T @ centered / max(1, len(centered) - 1) off_diagonal = ~torch.eye(len(covariance), dtype=torch.bool, device=covariance.device) return -covariance[off_diagonal].abs().mean() matrices = [] for latent in latents: centered = latent - latent.mean(dim=0) epsilon = torch.finfo(centered.dtype).eps scaled = centered / torch.linalg.vector_norm(centered, dim=0).clamp_min(epsilon) matrices.append(scaled.T @ scaled) distances = [] for first, second in combinations(matrices, 2): norm = torch.linalg.matrix_norm(first) * torch.linalg.matrix_norm(second) similarity = (first * second).sum() / norm.clamp_min(epsilon) distances.append(torch.where(norm > epsilon, (1 - similarity).clamp(0, 1), 0.)) return torch.stack(distances).mean() ## @brief Evaluate reconstruction loss and the diversity reward for one batch. # @param models Autoencoders exposing an encoder and a decoder. # @param batch Input observations with a leading batch dimension. # @param term Name of the diversity reward. # @return Reconstruction error and diversity reward as differentiable scalars. def _ensemble_losses(models, batch, term): latents, outputs = [], [] for model in models: dtype = next(model.parameters()).dtype latent = model.encoder(batch.to(dtype=dtype)) if latent.ndim != 2 or len(latent) != len(batch) or latent.shape[1] == 0: raise ValueError("Each encoder must return one latent vector per observation.") decoded = model.decoder(latent) if decoded.shape != batch.shape: raise ValueError("Each decoder must reconstruct the input batch shape.") latents.append(latent) outputs.append(decoded) outputs = torch.stack(outputs) reconstruction = (outputs - batch).square().mean() if term == "outputs": diversity = (outputs - outputs.mean(dim=0)).square().mean() elif term == "none": diversity = reconstruction.new_zeros(()) else: diversity = _latent_diversity(latents, term) return reconstruction, diversity ## @brief Train one encoder per grid and rebuild all learned archives together. # @see https://arxiv.org/abs/2105.00682
[docs] class MCAurora: """Coordinate a multi-container AURORA search on a shared observation depot. Pass distinct, initially empty fixed grids and a separate training container. Each wrapped grid forwards evaluated candidates to the depot, including local rejects. Use ``archives`` as the containers of ordinary ask/tell optimisers, for example with an alternating wrapper. The coordinator keeps training and archive updates on the calling thread. Evaluation workers only need to return fitness and observations. :param grids: Fixed :class:`~qdpy.containers.Grid` instances to wrap. :param training_container: Shared archive of evaluated observations. :param base_scores: Ordered scalar score names to encode. :param observation_score: Name of one fixed-shape numeric observation. :param models: Optional autoencoder per grid, with encoder and decoder. The default is a dense autoencoder with a tanh output. :param training_period: Depot growth between scheduled refits. A value of zero enables manual training only. :param epochs: Training epochs per refit. :param batch_size: Target training batch size. :param learning_rate: Adam learning rate. :param quantile_transform: Map latent coordinates into the unit interval. :param diversity: One of ``none``, ``outputs``, ``covariance``, or ``correlation``. :param diversity_weight: Weight subtracted times the diversity reward. A positive weight penalises off-diagonal covariance. :param rebuild_from: Reinsert the full ``depot`` into all grids or rebuild from each grid's own ``elites``. An empty grid starts from the depot on the first refit in either mode. :param max_training_samples: Optional cap on records used per refit. All rebuild records are encoded even when training uses a sample. :param seed: Seed for model creation, training and depot sampling. Seed the search RNG and any stochastic evaluator separately. """ def __init__(self, grids, training_container, *, base_scores=None, observation_score=None, models=None, training_period: int = 512, epochs: int = 5, batch_size: int = 128, learning_rate: float = 1e-3, quantile_transform: bool = True, diversity: str = "none", diversity_weight: float = 0., rebuild_from: str = "elites", max_training_samples: int | None = None, seed: int = 0): if torch is None: raise ImportError("MC-AURORA requires PyTorch. Install torch in this environment.") grids = tuple(grids) if (len(grids) < 2 or len({id(grid) for grid in grids}) != len(grids) or any(type(grid) is not Grid or len(grid) for grid in grids)): raise ValueError("Pass at least two distinct, empty, fixed Grid instances.") if (any(grid is training_container or grid.only_add_accepted_inds_to_parents for grid in grids) or any(grid.parents and (len(grid.parents) != 1 or grid.parents[0] is not training_container) for grid in grids) or getattr(training_container, "parents", ())): raise ValueError("The grids must forward all evaluations to one separate depot without parents.") if (base_scores is None) == (observation_score is None): raise ValueError("Specify either nonempty base_scores or an observation_score.") if base_scores is not None: base_scores = tuple(base_scores) if not base_scores: raise ValueError("base_scores cannot be empty.") if (not isinstance(training_period, int) or training_period < 0 or not isinstance(epochs, int) or epochs < 1 or not isinstance(batch_size, int) or batch_size < 1 or not math.isfinite(learning_rate) or learning_rate <= 0): raise ValueError("Use a nonnegative period and a positive epoch count, batch size and learning rate.") if diversity not in _DIVERSITY_TERMS or not math.isfinite(diversity_weight): raise ValueError(f"Use a finite diversity weight and one of {_DIVERSITY_TERMS}.") if diversity == "correlation" and len({len(grid.features_domain) for grid in grids}) != 1: raise ValueError("Correlation diversity requires equal latent widths.") if rebuild_from not in ("elites", "depot"): raise ValueError("Choose elites or depot as the rebuild source.") if max_training_samples is not None and ( not isinstance(max_training_samples, int) or max_training_samples < 2): raise ValueError("max_training_samples must be at least two.") models = (None,) * len(grids) if models is None else tuple(models) if len(models) != len(grids): raise ValueError("Supply one model per grid.") for model in models: if model is not None and (not isinstance(model, torch.nn.Module) or not callable(getattr(model, "encoder", None)) or not callable(getattr(model, "decoder", None)) or not any(p.requires_grad for p in model.parameters())): raise ValueError("Each model needs an encoder, decoder and trainable parameters.") if quantile_transform and any(any(lo > 0 or hi < 1 for lo, hi in grid.features_domain) for grid in grids): raise ValueError("Quantile descriptors require grid domains containing [0, 1].") seed = index(seed) if seed < 0: raise ValueError("seed must be nonnegative.") self.training_container = training_container self.training_period = training_period self.epochs = epochs self.batch_size = batch_size self.learning_rate = learning_rate self.diversity = diversity self.diversity_weight = diversity_weight self.rebuild_from = rebuild_from self.max_training_samples = max_training_samples self.seed = seed self.training_history: list[MCAuroraTraining] = [] self.archives = tuple( _EnsembleDescriptors( grid, model=deepcopy(model), base_scores=base_scores, observation_score=observation_score, training_period=0, quantile_transform=quantile_transform) for grid, model in zip(grids, models) ) for grid in grids: grid.parents = [training_container] # Lazy provisional models may be needed before the first refit. # They are seeded per archive without advancing the caller's RNG. for i, archive in enumerate(self.archives): archive._initial_model_seed = (self.seed + i) % (2**64) ## @brief Register scheduled retraining at iteration and final evaluation boundaries. # @param algorithm Optimiser driving search, typically an AlternatingAlgWrapper.
[docs] def attach(self, algorithm): """Register joint retraining after iterations and the final partial batch.""" algorithm.add_callback("iteration", self._on_iteration) algorithm.add_callback("finished_optimisation", self._on_iteration)
## @brief Restore the depot link when loading a saved coordinator. # @details Individual grid snapshots can omit parent references. The # coordinator has its own reference to the training data. def __setstate__(self, state): self.__dict__.update(state) for archive in self.archives: archive.container.parents = [self.training_container] ## @brief Check depot growth at an optimiser event. def _on_iteration(self, _algorithm, _elapsed): self.retrain_if_needed() ## @brief Fit once if the depot has crossed the next training threshold. # @return The completed refit record, or None when training is not due.
[docs] def retrain_if_needed(self) -> MCAuroraTraining | None: """Train when the depot crosses a new multiple of the training period.""" period = self.training_period previous = self.training_history[-1].depot_size if self.training_history else 0 count = len(self.training_container) if period and count >= 2 and count // period > previous // period: return self.fit() return None
## @brief Encode with a candidate model and prepare a replacement grid. # @details Stage readmission without forwarding to parents and retain # references to the original candidates. The live grid is untouched. def _stage_grid(self, archive, model, sample_tensor, records): latent = archive._encode(model, sample_tensor) if latent.shape[1] != len(archive.features_domain): raise ValueError("The encoder width must match the grid descriptor domain.") transformer = archive._fit_quantile_transform(latent) if archive.quantile_transform else None rows = [] for start in range(0, len(records), self.batch_size): batch = archive._score_tensor(records[start:start + self.batch_size]) rows.extend(archive._transform_latent(archive._encode(model, batch), transformer).tolist()) descriptors = {id(ind): Features(row) for ind, row in zip(records, rows)} grid = archive.container memo = {id(entry): entry for entry in grid} memo.update({id(archive): archive, id(grid.parents): grid.parents}) staged = deepcopy(grid, memo) staged.parents = [] staged.clear() staged.get_ind_features = lambda ind: descriptors[id(ind)] staged.update(records, ignore_exceptions=False) staged.parents = grid.parents staged.get_ind_features = grid.get_ind_features return staged, transformer, rows ## @brief Fit model copies and stage every grid before installing the new descriptors. # @return Training diagnostics for the completed refit. # @throws ValueError If fewer than two records are available. # @throws FloatingPointError If the training objective is nonfinite.
[docs] def fit(self) -> MCAuroraTraining: """Train the full ensemble from the current depot and rebuild its grids. The live models, grids and training history are installed only after training, encoding and staged readmission succeed for every grid. Train and call ask/tell serially on the coordinator. """ depot = list(self.training_container) if len(depot) < 2: raise ValueError("MC-AURORA needs at least two depot records.") rng = np.random.default_rng([self.seed, len(self.training_history)]) sample = depot if self.max_training_samples is not None and len(depot) > self.max_training_samples: sampled = np.sort(rng.choice(len(depot), self.max_training_samples, replace=False)) sample = [depot[i] for i in sampled] data = self.archives[0]._score_tensor(sample).detach() if not torch.isfinite(data).all(): raise ValueError("Training observations must be finite.") with torch.random.fork_rng(devices=[]): torch.random.default_generator.manual_seed((self.seed + len(self.training_history)) % (2**64)) models = [deepcopy(archive.model if archive.model is not None else archive._make_default_model(sample[0])).cpu() for archive in self.archives] reconstruction, diversity, loss = self._train(models, data) staged_grids = [] for archive, model in zip(self.archives, models): use_depot = self.rebuild_from == "depot" or (not self.training_history and not len(archive)) records = depot if use_depot else list(archive) staged, transform, rows = self._stage_grid(archive, model, data, records) staged_grids.append((staged, transform, records, rows)) for archive, model, (staged, transform, records, rows) in zip(self.archives, models, staged_grids): archive.model = model archive._quantile_transformer = transform archive._descriptor_version += 1 archive._store_descriptors(records, rows) archive.container.__dict__.update(staged.__dict__) archive.container.features_score_names = archive._extracted_score_names() result = MCAuroraTraining(len(depot), len(sample), reconstruction, diversity, loss) self.training_history.append(result) return result
## @brief Optimise the joint objective and average last-epoch batch losses. def _train(self, models, data): optimizer = torch.optim.Adam((p for model in models for p in model.parameters()), lr=self.learning_rate) for model in models: model.train() for _ in range(self.epochs): totals = np.zeros(3) batches = list(torch.randperm(len(data)).split(self.batch_size)) if self.batch_size > 1 and len(batches) > 1 and len(batches[-1]) == 1: last = batches.pop() batches[-1] = torch.cat((batches[-1], last)) for indices in batches: reconstruction, diversity = _ensemble_losses(models, data[indices], self.diversity) loss = reconstruction - self.diversity_weight * diversity if not torch.isfinite(loss): raise FloatingPointError("MC-AURORA produced a nonfinite loss.") optimizer.zero_grad() loss.backward() optimizer.step() totals += np.asarray([reconstruction.item(), diversity.item(), loss.item()]) * len(indices) return tuple(map(float, totals / len(data)))