Source code for qdpy.algorithms.discount

# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Native Discount Model Search for vector descriptor spaces.

"""Learn a smooth discount field over a fixed reporting archive."""

from math import sqrt

import numpy as np

from qdpy.base import registry
from qdpy.containers import CVTGrid, Grid
from .modern import CMAMAE, _positive_int

__all__ = ["DiscountModelSearch"]

# Leave headroom for squared losses and Adam's second moments in float32.
_MAX_DISCOUNT_TARGET = sqrt(np.finfo(np.float32).max) / 128


def _check_discount_targets(values):
    if not np.all(np.abs(np.asarray(values, dtype=float)) <= _MAX_DISCOUNT_TARGET):
        raise ValueError(f"DMS signed quality must be within ±{_MAX_DISCOUNT_TARGET:.2g}. "
                         "Rescale the objective or its weight.")


def _discount_targets(previous, qualities, learning_rate):
    return previous + learning_rate * np.maximum(qualities - previous, 0)


class _TorchDiscount:
    """Fit the vector-descriptor MLP and preserve Adam and sampler state."""

    def __init__(self, dimension, seed):
        import torch

        with torch.random.fork_rng(devices=[]):
            torch.random.default_generator.manual_seed(seed)
            cpu = dict(device="cpu", dtype=torch.float32)
            self.network = torch.nn.Sequential(
                torch.nn.Linear(dimension, 128, **cpu),
                torch.nn.ReLU(),
                torch.nn.Linear(128, 128, **cpu),
                torch.nn.ReLU(),
                torch.nn.Linear(128, 1, **cpu),
            )
        self.optimizer = torch.optim.Adam(self.network.parameters(), lr=0.001)
        self.generator = torch.Generator(device="cpu").manual_seed(seed)

    def predict(self, descriptors):
        import torch

        points = torch.as_tensor(descriptors, dtype=torch.float32, device="cpu")
        if not torch.isfinite(points).all():
            raise ValueError("Normalised descriptors are outside the DMS model's finite range.")
        with torch.no_grad():
            return self.network(points).squeeze(-1).numpy()

    def fit(self, descriptors, targets):
        import torch

        _check_discount_targets(targets)
        points = torch.as_tensor(descriptors, dtype=torch.float32, device="cpu")
        targets = torch.as_tensor(targets, dtype=torch.float32, device="cpu")
        for _ in range(5):
            for indices in torch.randperm(len(points), generator=self.generator, device="cpu").split(32):
                self.optimizer.zero_grad()
                loss = torch.nn.functional.mse_loss(self.network(points[indices]).squeeze(-1), targets[indices])
                if not torch.isfinite(loss):
                    raise ValueError("DMS training loss is nonfinite. Rescale the objective or its weight.")
                loss.backward()
                self.optimizer.step()
            with torch.no_grad():
                mse = torch.nn.functional.mse_loss(self.network(points).squeeze(-1), targets)
            if mse <= 0.05:
                break


## @brief Rank a CMA generation against a learned continuous discount.
[docs] @registry.register class DiscountModelSearch(CMAMAE): """Native DMS with one CMA emitter and a CPU vector-descriptor model. Install the optional ``dms`` extra. The fixed Grid or CVTGrid retains each cell's best genuine evaluation. The MLP predicts a separate discount in signed quality units and trains once per committed generation. :param container: One-elite reporting grid. :param budget: Attempted evaluations per run. :param x0: Initial decision point. :param sigma0: Initial CMA search scale. :param batch_size: Full CMA population size. :param threshold_min: Initial discount in signed quality units within the model's numeric range. :param learning_rate: Archive target learning rate. :param initial_anchors: Maximum sampled centres for model initialisation. :param empty_anchors: Maximum sampled empty centres per generation. """ def __init__(self, container, budget, x0, sigma0, batch_size, threshold_min, *, learning_rate=0.1, initial_anchors=256, empty_anchors=256, **kwargs): try: import torch except ImportError as error: raise ImportError("DiscountModelSearch requires the QDpy 'dms' extra.") from error if type(container) not in (Grid, CVTGrid): raise ValueError("DMS requires a fixed Grid or CVTGrid.") _check_discount_targets(threshold_min) lower, upper = np.asarray(container.features_domain, dtype=float).T widths = [float(high) - float(low) for low, high in zip(lower, upper)] if not np.all(np.isfinite(widths)) or np.any(lower >= upper): raise ValueError("DMS needs finite increasing descriptor bounds.") self._descriptor_lower = lower self._descriptor_width = np.asarray(widths) self._cells = tuple(container.solutions) if isinstance(container, CVTGrid): self._centres = np.array(container.cluster_centers, copy=True) else: offsets = (np.asarray(self._cells) + 0.5) / np.asarray(container.shape) self._centres = lower + offsets * self._descriptor_width self._cell_rows = {cell: row for row, cell in enumerate(self._cells)} self.initial_anchors = _positive_int(initial_anchors, "initial_anchors") self.empty_anchors = _positive_int(empty_anchors, "empty_anchors") super().__init__(container, budget, x0, sigma0, batch_size, threshold_min, learning_rate=learning_rate, **kwargs) def reinit(self): """Reset the discount model and emitter while retaining the result archive.""" super().reinit() self._discount_model = None @property def search_elites(self): """Return the result-grid elites that can seed a restart.""" return {cell: entries[0] for cell, entries in self.container.solutions.items() if entries} def _restart_center(self): return self._search_rng().choice(self.container) if len(self.container) else self.x0 def _normalise(self, points): return 2 * ((points - self._descriptor_lower) / self._descriptor_width) - 1 def _anchor_points(self, rows, count): selected = self._search_rng().sample(rows, min(len(rows), count)) return self._centres[selected] def _start_fixed_batch(self, size): if self._discount_model is None: seed = self._search_rng().randint(1, 2**32 - 1) self._discount_model = _TorchDiscount(len(self._descriptor_lower), seed) anchors = self._anchor_points(range(len(self._cells)), self.initial_anchors) self._discount_model.fit(self._normalise(anchors), np.full(len(anchors), self.threshold_min)) super()._start_fixed_batch(size) ## @brief Predict signed discount values at evaluated descriptor vectors.
[docs] def predict_discount(self, descriptors): """Return one signed discount per row after the model has been initialised.""" if self._discount_model is None: raise RuntimeError("Start DMS before querying its discount model.") points = np.atleast_2d(np.asarray(descriptors, dtype=float)) if points.ndim != 2 or points.shape[1] != len(self._descriptor_lower) or not np.all(np.isfinite(points)): raise ValueError("Provide a finite matrix with one column per descriptor.") return self._discount_model.predict(self._normalise(points))
def threshold(self, cell): """Return the discount at a cell centre, or the initial floor before training.""" row = self._cell_rows[cell] if self._discount_model is None: return self.threshold_min return float(self.predict_discount(self._centres[row])[0]) def _check_candidate(self, individual): super()._check_candidate(individual) fitness = self.container.get_ind_fitness(individual) _check_discount_targets(float(fitness.values[0]) * float(fitness.weights[0])) def _commit_generation(self, evaluated): self._gains = np.full(len(evaluated), -np.inf) indices = [slot for slot, ind in enumerate(evaluated) if ind is not None] if not indices: return set() candidates = [evaluated[slot] for slot in indices] points = np.asarray([tuple(self.container.get_ind_features(ind)) for ind in candidates]) qualities = np.array([ fitness.values[0] * fitness.weights[0] for fitness in map(self.container.get_ind_fitness, candidates) ]) predictions = self.predict_discount(points) self._gains[indices] = qualities - predictions targets = _discount_targets(predictions, qualities, self.learning_rate) admitted = set() for slot, individual in zip(indices, candidates): if self._offer_to_grid(individual, self.container.index_grid(individual)): admitted.add(slot) if len(evaluated) == self.batch_size: self._adapt_strategy(self._vectors) empty = [row for row, cell in enumerate(self._cells) if not self.container.solutions[cell]] anchors = self._anchor_points(empty, self.empty_anchors) training_input = self._normalise(np.concatenate((points, anchors), axis=0)) training_target = np.concatenate((targets, np.full(len(anchors), self.threshold_min))) self._discount_model.fit(training_input, training_target) return admitted