Source code for qdpy.algorithms.bayesian_batch

# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Select a generation by joint posterior improvement of its archive.
# @see https://arxiv.org/abs/2005.04320
# @see https://proceedings.neurips.cc/paper/2020/hash/6fec24eac8f18ed793f5eaad3dd7977c-Abstract.html

"""Greedy batch expected archive improvement on a shared posterior sample."""

from collections.abc import Sequence

import numpy as np

from qdpy.base import registry
from .bayesian import BOPElites
from .modern import _positive_int

__all__ = ["BatchBOPElites"]


def _sample_posterior(model, points, samples, rng):
    mean, cov = model.predict(points, return_cov=True)
    eig, directions = np.linalg.eigh((cov + cov.T) * .5)
    tolerance = max(np.max(abs(eig)), np.finfo(float).tiny) * 1e-7
    if eig.min() < -tolerance:
        raise ValueError("A Gaussian-process posterior covariance is not positive semidefinite.")
    noise = rng.normal(size=(samples, len(points)))
    return mean + (noise * np.sqrt(eig.clip(min=0.))) @ directions.T


def _draw_cells(descriptors, shape, domain):
    """Use native rectangular grid geometry and reserve an invalid-cell sentinel."""
    lo, hi = np.asarray(domain, dtype=float).T
    span = (hi - lo) / shape
    finite = np.isfinite(descriptors).all(axis=-1)
    valid = finite & ((descriptors >= lo) & (descriptors <= hi)).all(axis=-1)
    clipped = np.where(valid[..., None], descriptors, lo)
    bins = np.minimum(((clipped - lo) / span).astype(int), np.asarray(shape) - 1)
    indices = np.ravel_multi_index(tuple(np.moveaxis(bins, -1, 0)), shape)
    return np.where(valid, indices, np.prod(shape))


def _select_batch(cells, gains, size, joint):
    """Select unique proposals by stable greedy marginal improvement."""
    if not joint:
        return np.argsort(-gains.mean(axis=0), kind="stable")[:size]
    selected = []
    current = np.zeros_like(gains)
    for _ in range(size):
        marginal = np.maximum(gains - current, 0.).mean(axis=0)
        marginal[selected] = -np.inf
        index = int(marginal.argmax())
        selected.append(index)
        # Keep the best selected gain for each proposal's sampled cell.
        same_cell = cells == cells[:, index:index + 1]
        np.maximum(current, gains[:, index:index + 1], out=current, where=same_cell)
    return selected


## @brief Optimize expected per-cell improvement of a whole batch.
[docs] @registry.register class BatchBOPElites(BOPElites): """Fit objective and descriptor models once per generation. Draw correlated samples across the Sobol candidate pool for each independent output GP. Greedily select a batch that maximizes the expected sum of the largest improvement in each cell. Outside-grid samples have zero gain. Only measured candidates can update the archive. This variant works with native scalar fitness and one or two direct descriptors. :param container: Parentless best-only rectangular Grid. :param budget: Maximum true-evaluation attempts. :param dimension: Number of bounded decision variables. :param ind_domain: Common finite decision interval. :param quality_floor: Empty-cell threshold in signed weighted quality units. :param batch_size: Maximum number of candidates in a generation. :param candidates: Number of Sobol proposals scored jointly. :param samples: Number of joint normal posterior draws per generation. :param selection: Joint marginal improvement or independent top-k. :param initial_samples: Minimum number of initial Sobol proposals. :param seed: Seed for Sobol proposals and posterior draws. :param kwargs: Native optimiser options. """ def __init__(self, container, budget, dimension, ind_domain, quality_floor, *, batch_size=4, candidates=96, samples=128, selection="joint", initial_samples=None, seed=None, **kwargs): self._bop_batch_size = _positive_int(batch_size, "batch_size") candidates = _positive_int(candidates, "candidates") self.samples = _positive_int(samples, "samples") if (selection not in ("joint", "independent") or candidates < self._bop_batch_size or container.parents or container.discard_random_on_bin_overload or container.fitness_score_names or container.features_score_names or kwargs.keys() & {"model_feasibility", "descriptor_transform", "latent_size", "restarts", "candidate_pool", "posterior_samples"}): raise ValueError("Use direct measurements, candidates >= batch_size, and joint or independent selection.") task = kwargs.get("optimisation_task") if isinstance(task, Sequence) and not isinstance(task, str) and tuple(task) == (0.,): raise ValueError("Batch expected improvement needs a nonzero objective weight.") self.selection = selection lower, upper = map(float, ind_domain) if not np.isfinite(upper - lower): raise ValueError("The decision interval must have a finite width.") spans = np.ptp(np.asarray(container.features_domain, dtype=float), axis=1) if not (np.isfinite(spans).all() and (spans / container.shape > 0.).all()): raise ValueError("The descriptor grid must have finite positive cell widths.") super().__init__(container, budget, dimension, (lower, upper), quality_floor, initial_samples=initial_samples, candidate_pool=candidates, seed=seed, **kwargs)
[docs] def reinit(self): """Reset posterior draws and generation-local proposals.""" super().reinit() self._draw_rng = np.random.default_rng(self.seed) self._points = []
def _pool(self, size): pool = {} for _ in range(32 * size): point = self._sobol_point() key = tuple(self._raw_point(point)) pool.setdefault(key, point) if len(pool) == size: return np.asarray(tuple(pool.values())) raise RuntimeError("Could not draw enough distinct Sobol candidates in the chosen decision interval.") def _start_fixed_batch(self, size): super()._start_fixed_batch(size) if self.nb_suggestions < self.initial_samples or self.n_observations < 2: self._points = self._pool(size) return points = self._pool(self.candidate_pool) draws = np.stack([_sample_posterior(model, points, self.samples, self._draw_rng) for model in self._fit_models()], axis=-1) grid = self.container cells = _draw_cells(draws[..., 1:], grid.shape, grid.features_domain) thresholds = self._thresholds() cell_count = len(thresholds) signed = draws[..., 0] low, high = sorted(bound * grid.fitness_weights[0] for bound in grid.fitness_domain[0]) valid = (cells < cell_count) & (signed >= low) & (signed <= high) gains = np.maximum(signed - np.r_[thresholds, 0.][cells], 0.) gains = np.where(valid, gains, 0.) indices = _select_batch(cells, gains, size, self.selection == "joint") self._points = points[indices] def _internal_ask(self, base_ind): base_ind[:] = self._raw_point(self._points[len(self._issued)]) self._seen.add(tuple(base_ind)) return base_ind def _commit_generation(self, evaluated): admitted = set() for slot, individual in enumerate(evaluated): self._unit_candidate = self._points[slot] # Report no single-cell prediction for a joint acquisition. if super()._commit_generation((individual,)): admitted.add(slot) return admitted